forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB68cf7a6Tahinli2 months ago2975 commits

encode.rs924 lines, 39.5 KiBHistoryRawDownload
1//! A stereo, lossless TrueHD encoder.
2//!
3//! **Scope (r1)**: 44.1/48 kHz family stereo only, one substream, one
4//! restart header per access unit (so no cross-AU predictor/parameter
5//! state), no matrixing (0 primitive matrices — the stereo pair is written
6//! as two independent, uncorrelated channels) and no FIR/IIR prediction
7//! (filter order 0 on both channels): every sample is written raw, as a
8//! 24-bit offset-binary residual (`codebook = 0`, `huff_lsbs = 24`,
9//! `quant_step = 0`), which [`crate::decode::Core::read_block`] reconstructs
10//! back to the exact sample with no predictor and no quantization. This
11//! trades compression for the shortest bitstream that is still conformant:
12//! every field this build's own decoder does not need to see change is left
13//! at the restart header's own reset default (`Substream::new()`), so the
14//! encoder only ever sets `params_present`/`restart_present`, block size,
15//! and the per-channel codebook/`huff_lsbs` pair.
16//!
17//! **Restart header self-check**: the lossless-check byte a restart header
18//! after the first carries is verified by the decoder against the samples
19//! output by the *previous* restart interval ([`decode::Core::output`]'s
20//! `lossless_check_data` fold); since every access unit here is its own
21//! restart interval, this encoder folds each AU's own samples the same way
22//! and carries that byte into the next AU's restart header.
23//!
24//! **Compression (r2)**: each channel still gets one restart-header-fresh
25//! parameter set per access unit (no cross-AU predictor state), but that set
26//! now may carry a quantized order-8 FIR predictor (Levinson-Durbin on the
27//! AU's own samples, coefficients quantized to a 15-bit/`FILTER_SHIFT`
28//! fixed point — [`crate::decode::filter_channel`] runs the identical
29//! integer recursion) and residual coding through codebook 2 (16 entries)
30//! with a per-channel Rice-style LSB split chosen so every residual's
31//! quotient lands in the codebook's range
32//! ([`sign_offset`]/[`choose_lsb_bits`]). Both are picked by comparing their
33//! exact encoded bit cost against the raw 24-bit path (`codebook = 0`) and
34//! falling back to raw whenever they would not win — so a channel/AU never
35//! costs more than r1's raw encoding did.
36
37use std::collections::VecDeque;
38
39use ec_core::bitio::BitWriter;
40use ec_core::error::{Error, Result};
41use ec_core::frame::{ChannelLayout, Frame, SampleFormat};
42use ec_core::packet::Packet;
43use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters};
44
45use crate::decode::{HUFFMAN_TABLES, MAX_FILTER_ORDER, restart_checksum};
46use crate::sync::MAJOR_SYNC_TRUEHD;
47
48/// FIR order this encoder tries; matches `decode::MAX_FILTER_ORDER`.
49const FILTER_ORDER: usize = MAX_FILTER_ORDER;
50/// Fixed-point scale (`accum >> FILTER_SHIFT`) the quantized coefficients
51/// are expressed in; mirrors `decode::filter_channel`'s `>> shift` exactly.
52const FILTER_SHIFT: u32 = 12;
53/// Coefficient field width; `coeff_shift` stays 0 (`15 + 0 <= 16`, the
54/// decoder's own bound).
55const COEFF_BITS: u32 = 15;
56/// The 16-entry residual codebook (`decode::HUFFMAN_TABLES[1]`, format field
57/// value 2) this encoder uses whenever prediction+entropy coding wins.
58const CODEBOOK: u8 = 2;
59/// Below this many samples/channel, Levinson-Durbin's autocorrelation
60/// estimate is too noisy to be worth the filter-parameter overhead.
61const MIN_SAMPLES_FOR_LPC: usize = 32;
62
63/// A residual's sign-offset bias (`Substream::recompute_sign_offset`'s
64/// formula with `huff_offset = 0`, `quant_step_size = 0`): the constant
65/// subtracted from a raw sample/residual before it is split into a
66/// codebook index (`codebook > 0`) or written bare (`codebook == 0`).
67fn sign_offset(codebook: u8, lsb_bits: u32) -> i32 {
68 let lsb_bits = lsb_bits as i32;
69 let sign_shift = lsb_bits
70 + if codebook > 0 {
71 2 - i32::from(codebook)
72 } else {
73 -1
74 };
75 let mut off = if codebook > 0 { -(7 << lsb_bits) } else { 0 };
76 if sign_shift >= 0 {
77 off -= 1 << sign_shift;
78 }
79 off
80}
81
82/// Writes one residual through `codebook`/`lsb_bits`/`sign_off` (from
83/// [`sign_offset`]) — the exact inverse of
84/// `decode::Core::read_block`'s per-sample reconstruction.
85fn write_residual(bw: &mut BitWriter, codebook: u8, lsb_bits: u32, sign_off: i32, r: i32) {
86 let raw = (r.wrapping_sub(sign_off)) as u32;
87 if codebook == 0 {
88 bw.write_bits(raw, lsb_bits);
89 return;
90 }
91 let idx = (raw >> lsb_bits) as usize;
92 let (code, len) = HUFFMAN_TABLES[usize::from(codebook) - 1][idx];
93 debug_assert!(len > 0, "residual quotient {idx} outside codebook range");
94 bw.write_bits(u32::from(code), u32::from(len));
95 if lsb_bits > 0 {
96 bw.write_bits(raw & ((1u32 << lsb_bits) - 1), lsb_bits);
97 }
98}
99
100/// The smallest `lsb_bits` (format field `huff_lsbs`, `quant_step = 0`) for
101/// which every residual's codebook-2 quotient (`(r - sign_offset(2,
102/// lsb_bits)) >> lsb_bits`) lands inside `0..16` (codebook 2's 16 valid
103/// entries) — or `None` if no field width up to the format's 24-bit cap
104/// does (residuals too wild for this codebook; caller falls back to raw).
105fn choose_lsb_bits(residuals: &[i32]) -> Option<u32> {
106 let (mut max_r, mut min_r) = (i32::MIN, i32::MAX);
107 for &r in residuals {
108 max_r = max_r.max(r);
109 min_r = min_r.min(r);
110 }
111 let threshold = i64::from(max_r).max(-1 - i64::from(min_r)).max(0);
112 for lsb_bits in 0..=24u32 {
113 if (8i64 << lsb_bits) > threshold {
114 return Some(lsb_bits);
115 }
116 }
117 None
118}
119
120/// Levinson-Durbin on `samples`' own autocorrelation: LPC coefficients
121/// `a[1..=order]` such that `sample[n] ≈ Σ a[j] · sample[n - j]`. The
122/// autocorrelation is taken over a Welch-windowed copy of `samples`, not
123/// the raw rectangular window: a rectangular window's autocorrelation is
124/// biased away from the signal's true poles by its own hard edges (proven
125/// on a pure tone — order 2 gave a≈[1.88, -0.89] against the analytic
126/// [2cos(w), -1]≈[1.99, -1]); tapering the ends to zero removes that edge
127/// leakage (Welch on the same tone: a≈[1.990, -1.000]).
128fn levinson_durbin(samples: &[i32], order: usize) -> Vec<f64> {
129 let n = samples.len();
130 let half = (n.saturating_sub(1)) as f64 / 2.0;
131 let x: Vec<f64> = samples
132 .iter()
133 .enumerate()
134 .map(|(i, &s)| {
135 let t = if half > 0.0 {
136 (i as f64 - half) / half
137 } else {
138 0.0
139 };
140 f64::from(s) * (1.0 - t * t)
141 })
142 .collect();
143 let mut r = vec![0.0f64; order + 1];
144 for (lag, slot) in r.iter_mut().enumerate() {
145 let mut s = 0.0;
146 for i in 0..x.len() - lag {
147 s += x[i] * x[i + lag];
148 }
149 *slot = s;
150 }
151 let mut err = r[0];
152 let mut a = vec![0.0f64; order + 1];
153 if err <= 0.0 {
154 return vec![0.0; order];
155 }
156 for i in 1..=order {
157 let mut acc = r[i];
158 for j in 1..i {
159 acc -= a[j] * r[i - j];
160 }
161 let k = acc / err;
162 let mut new_a = a.clone();
163 new_a[i] = k;
164 for j in 1..i {
165 new_a[j] = a[j] - k * a[i - j];
166 }
167 a = new_a;
168 err *= 1.0 - k * k;
169 if err <= 1e-9 {
170 break;
171 }
172 }
173 a[1..=order].to_vec()
174}
175
176/// Integer residuals `sample[n] - (Σ coeffs[j] · history[j]) >> FILTER_SHIFT`
177/// over the channel's own past samples (most recent first, seeded from
178/// `hist_in` — see [`TrueHdEncoder::history`]) — the exact inverse of
179/// `decode::filter_channel`'s reconstruction, with the same integer
180/// arithmetic (lossless coding: the decoder's filter state is always the
181/// *real* sample, since `quant_step = 0` never masks a bit off).
182fn fir_residuals(samples: &[i32], coeffs: &[i32], hist_in: &[i32; MAX_FILTER_ORDER]) -> Vec<i32> {
183 let order = coeffs.len();
184 let mut hist = *hist_in;
185 let mut out = Vec::with_capacity(samples.len());
186 for &s in samples {
187 let mut accum: i64 = 0;
188 for j in 0..order {
189 accum += i64::from(hist[j]) * i64::from(coeffs[j]);
190 }
191 let predict = (accum >> FILTER_SHIFT) as i32;
192 out.push(s.wrapping_sub(predict));
193 for j in (1..MAX_FILTER_ORDER).rev() {
194 hist[j] = hist[j - 1];
195 }
196 hist[0] = s;
197 }
198 out
199}
200
201/// One channel's chosen encoding for an access unit: either a quantized
202/// order-`coeffs.len()` FIR predictor with codebook-2 residual coding, or
203/// the raw 24-bit path (`coeffs` empty, `codebook = 0`, `lsb_bits = 24`) —
204/// whichever this AU's own samples cost fewer bits under.
205struct ChannelPlan {
206 coeffs: Vec<i32>,
207 codebook: u8,
208 lsb_bits: u32,
209 sign_off: i32,
210 residuals: Vec<i32>,
211}
212
213impl ChannelPlan {
214 /// `filter_overhead_bits` for a chosen `order`: the decoding-params
215 /// fields a non-zero FIR order adds (`shift(4) + coeff_bits(5) +
216 /// coeff_shift(3) + coeffs(order * COEFF_BITS)`).
217 fn fir_overhead_bits(order: usize) -> u64 {
218 4 + 5 + 3 + (order as u64) * u64::from(COEFF_BITS)
219 }
220
221 fn raw(samples: &[i32]) -> ChannelPlan {
222 let lsb_bits = 24;
223 ChannelPlan {
224 coeffs: Vec::new(),
225 codebook: 0,
226 lsb_bits,
227 sign_off: sign_offset(0, lsb_bits),
228 residuals: samples.to_vec(),
229 }
230 }
231
232 /// Chooses the cheaper of the raw path and an order-[`FILTER_ORDER`]
233 /// LPC + codebook-2 path for one channel's samples in this AU. `analysis`
234 /// is this channel's own recent real samples, oldest-first, ending
235 /// right before `samples` (see [`TrueHdEncoder::analysis`]) —
236 /// Levinson-Durbin fits over `analysis ++ samples`, a much longer,
237 /// AU-boundary-spanning window than a bare 40-160 sample AU (too short
238 /// for the autocorrelation estimate to land near the signal's true
239 /// poles), the same kind of window ffmpeg's `mlpenc` fits coefficients
240 /// over. The causal predictor itself only ever sees `analysis`'s own
241 /// tail (its last [`MAX_FILTER_ORDER`] samples) as seed history — the
242 /// same real, restart-surviving state `decode::filter_channel` builds.
243 fn choose(samples: &[i32], analysis: &[i32]) -> ChannelPlan {
244 let raw = ChannelPlan::raw(samples);
245 if samples.len() < MIN_SAMPLES_FOR_LPC {
246 return raw;
247 }
248 let mut hist = [0i32; MAX_FILTER_ORDER];
249 for (j, h) in hist.iter_mut().enumerate() {
250 if let Some(&s) = analysis.iter().nth_back(j) {
251 *h = s;
252 }
253 }
254 let mut window: Vec<i32> = analysis.to_vec();
255 window.extend_from_slice(samples);
256 let a = levinson_durbin(&window, FILTER_ORDER);
257 let scale = f64::from(1u32 << FILTER_SHIFT);
258 let clamp_max = (1i32 << (COEFF_BITS - 1)) - 1;
259 let clamp_min = -(1i32 << (COEFF_BITS - 1));
260 let coeffs: Vec<i32> = a
261 .iter()
262 .map(|&c| ((c * scale).round() as i32).clamp(clamp_min, clamp_max))
263 .collect();
264 let residuals = fir_residuals(samples, &coeffs, &hist);
265 let Some(lsb_bits) = choose_lsb_bits(&residuals) else {
266 return raw;
267 };
268 // The real bound (`decode::Substream::recompute_sign_offset`'s own
269 // `huff_lsbs > 24` check, `read_decoding_params`): codebook-2
270 // residuals need `lsb_bits <= 24`. Round 1's empirical 12-bit cap
271 // was masking a real bug (this crate's decoder — and this
272 // encoder's own residual math — zeroed FIR/IIR predictor history
273 // at every restart header; a real MLP/TrueHD stream, ffmpeg's
274 // `mlpdec.c` `read_restart_header` included, only resets the
275 // *parameters* there and carries the history buffer across
276 // restarts), now fixed at the root (`decode::Core::read_restart_header`
277 // + this function's `hist` argument), so the format's real field
278 // width is the only bound needed.
279 if lsb_bits > 24 {
280 return raw;
281 }
282 let sign_off = sign_offset(CODEBOOK, lsb_bits);
283 let mut lpc_bits = Self::fir_overhead_bits(FILTER_ORDER);
284 let book = &HUFFMAN_TABLES[usize::from(CODEBOOK) - 1];
285 for &r in &residuals {
286 let raw_val = (r.wrapping_sub(sign_off)) as u32;
287 let idx = (raw_val >> lsb_bits) as usize;
288 let Some(&(_, len)) = book.get(idx).filter(|&&(_, len)| len > 0) else {
289 return raw;
290 };
291 lpc_bits += u64::from(len) + u64::from(lsb_bits);
292 }
293 let raw_bits = (samples.len() as u64) * 24;
294 if lpc_bits < raw_bits {
295 ChannelPlan {
296 coeffs,
297 codebook: CODEBOOK,
298 lsb_bits,
299 sign_off,
300 residuals,
301 }
302 } else {
303 raw
304 }
305 }
306}
307
308/// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both
309/// noise types (the 14th bit picks the type).
310const RESTART_SYNC13: u32 = 0x31EA >> 1;
311/// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]
312/// uses for the lossless-check byte).
313fn xor_32_to_8(v: u32) -> u8 {
314 (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8
315}
316
317/// The major sync's own CRC-16 (poly `0x002D`, MSB-first table form,
318/// matching ffmpeg's `av_crc_init(..., le=0, bits=16, poly=0x2D, ...)`):
319/// this crate's own decoder does not validate it (see `sync.rs`'s module
320/// docs — no public description of its generator was available to check
321/// against), but a foreign decoder (ffmpeg's `mlp_parse.c`) does, so a
322/// bitstream meant to round-trip through one needs a correct value.
323fn mlp_crc16_table() -> [u32; 256] {
324 let mut table = [0u32; 256];
325 for (i, entry) in table.iter_mut().enumerate() {
326 let mut c = (i as i32) << 24;
327 for _ in 0..8 {
328 let overflow = c >> 31;
329 c = (c << 1) ^ ((0x002D_i32 << 16) & overflow);
330 }
331 *entry = (c as u32).swap_bytes();
332 }
333 table
334}
335
336/// The major sync's checksum field (bytes 26..28, little-endian): a CRC-16
337/// over `major_sync[0..24]`, XORed with the little-endian word at
338/// `major_sync[24..26]`.
339fn major_sync_checksum(major_sync: &[u8; 28]) -> u16 {
340 let table = mlp_crc16_table();
341 let mut crc: u32 = 0;
342 for &b in &major_sync[..24] {
343 crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8);
344 }
345 (crc as u16) ^ u16::from_le_bytes([major_sync[24], major_sync[25]])
346}
347
348/// A stereo TrueHD encoder. See the module docs for scope.
349#[derive(Debug)]
350pub struct TrueHdEncoder {
351 params: CodecParameters,
352 sample_rate: u32,
353 rate_code: u8,
354 /// Samples per channel a full access unit carries (`40 << (rate_code &
355 /// 7)`); the last, partial access unit may carry fewer.
356 access_unit_size: usize,
357 /// Interleaved stereo samples awaiting an access unit, true PCM range
358 /// (matches [`crate::decode::TrueHdDecoder`]'s own S32 left-justified
359 /// output once shifted right by 8).
360 pending: Vec<i32>,
361 packets: VecDeque<Vec<u8>>,
362 /// Lossless-check byte for the *next* access unit's restart header,
363 /// folded from the access unit just written; `0` (unchecked by the
364 /// decoder) before the first one.
365 next_check: u8,
366 /// Per-channel real samples this crate's own encoder has already
367 /// written, oldest-first, capped to [`ANALYSIS_WINDOW`] — both the
368 /// Levinson-Durbin fitting window (see [`ChannelPlan::choose`]) and,
369 /// via its own tail, the causal predictor's cross-AU seed history. A
370 /// real MLP/TrueHD stream's restart header resets decoding
371 /// *parameters* only, never the predictor's state buffer (see
372 /// `decode::Core::read_restart_header`'s module comment); starts
373 /// empty, matching the decoder's very first `Substream::new()`
374 /// (all-zero history).
375 analysis: [Vec<i32>; 2],
376 /// Access units written so far. Only access unit 0 carries a major sync
377 /// and a restart header — a real TrueHD stream only repeats major sync
378 /// "roughly one access unit per video frame" (see
379 /// [`crate::sync::AccessUnitHeader::major_sync`]'s docs), and this
380 /// crate's own decoder's `restart_seen` is a per-substream flag that,
381 /// once true, never has to be set again (`decode::Core::decode_substream`
382 /// only requires it before the first `read_block`) — sending either on
383 /// every AU is real per-AU byte overhead this format was designed to
384 /// amortize away.
385 au_index: u64,
386 /// The last-written blocksize + per-channel `(codebook, lsb_bits,
387 /// coeffs)`, so a later AU whose `ChannelPlan::choose` lands on the same
388 /// values can skip `params_present` entirely (see `encode_access_unit`).
389 last_params: Option<(usize, [(u8, u32, Vec<i32>); 2])>,
390 eof: bool,
391}
392
393/// How many of a channel's own past real samples [`TrueHdEncoder::analysis`]
394/// keeps for Levinson-Durbin's autocorrelation fit — long enough (dozens of
395/// AUs) that a short-lived AU boundary no longer starves the estimate, short
396/// enough that a non-stationary signal's older samples do not dominate it.
397const ANALYSIS_WINDOW: usize = 16384;
398
399impl TrueHdEncoder {
400 /// An encoder for one 44.1/48 kHz-family stereo stream.
401 pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> {
402 let (rate_code, access_unit_size) = match sample_rate {
403 48_000 => (0u8, 40usize),
404 96_000 => (1u8, 80usize),
405 192_000 => (2u8, 160usize),
406 44_100 => (8u8, 40usize),
407 88_200 => (9u8, 80usize),
408 176_400 => (10u8, 160usize),
409 other => {
410 return Err(Error::unsupported(
411 format!("TrueHD encoding at {other} Hz"),
412 "only the 44.1/48 kHz families are implemented",
413 ));
414 }
415 };
416 let mut params = CodecParameters::new(CodecId::TrueHd);
417 params.media = MediaParameters::Audio(AudioParameters {
418 sample_rate,
419 layout: ChannelLayout::Stereo,
420 format: Some(SampleFormat::S32),
421 bits_per_sample: None,
422 });
423 Ok(TrueHdEncoder {
424 params,
425 sample_rate,
426 rate_code,
427 access_unit_size,
428 pending: Vec::new(),
429 packets: VecDeque::new(),
430 next_check: 0,
431 analysis: [Vec::new(), Vec::new()],
432 au_index: 0,
433 last_params: None,
434 eof: false,
435 })
436 }
437
438 /// Encodes one access unit from `samples` (interleaved stereo, `<=
439 /// access_unit_size` per channel — a shorter slice writes a shorter,
440 /// still fully self-contained, access unit).
441 fn encode_access_unit(&mut self, samples: &[i32]) -> Vec<u8> {
442 let n = samples.len() / 2;
443 debug_assert!(n <= self.access_unit_size);
444
445 // Access unit 0 alone carries a restart header (predictor/channel
446 // state reset — this crate's own decoder's `restart_seen`, once
447 // true, never has to be set again) and a major sync (see
448 // `au_index`'s own docs); every later AU just updates decoding
449 // params (below) when they actually changed from the last AU
450 // written (the LPC coefficients usually do).
451 let is_first = self.au_index == 0;
452
453 // De-interleave, then let each channel pick raw vs. LPC+codebook-2
454 // independently (see `ChannelPlan::choose`), against its own
455 // carried-forward history.
456 let ch_samples: [Vec<i32>; 2] = [
457 samples.iter().step_by(2).copied().collect(),
458 samples.iter().skip(1).step_by(2).copied().collect(),
459 ];
460 let plans: [ChannelPlan; 2] =
461 std::array::from_fn(|ch| ChannelPlan::choose(&ch_samples[ch], &self.analysis[ch]));
462
463 // `decode::Core::read_decoding_params`'s per-channel section only
464 // runs at all when `params_present` (the AU's very first bit) is
465 // true — the decoder just keeps every field (FIR order/coeffs,
466 // codebook, `huff_lsbs`) it last read otherwise, real per-block
467 // amortization this format's block-size-40..3760 blocks were
468 // designed for. Comparing this AU's chosen plan (and blocksize)
469 // against the last AU actually written skips the whole section
470 // when nothing changed — safe because the decoder's own state is
471 // exactly the union of every field this encoder has ever written.
472 let params_key: (usize, [(u8, u32, &[i32]); 2]) = (
473 n,
474 std::array::from_fn(|ch| {
475 (
476 plans[ch].codebook,
477 plans[ch].lsb_bits,
478 plans[ch].coeffs.as_slice(),
479 )
480 }),
481 );
482 let params_changed = is_first
483 || self.last_params.as_ref().is_none_or(|(pn, pch)| {
484 *pn != params_key.0
485 || pch
486 .iter()
487 .zip(params_key.1.iter())
488 .any(|(a, b)| a.0 != b.0 || a.1 != b.1 || a.2 != b.2)
489 });
490 if params_changed {
491 self.last_params = Some((
492 params_key.0,
493 std::array::from_fn(|ch| {
494 (
495 plans[ch].codebook,
496 plans[ch].lsb_bits,
497 plans[ch].coeffs.clone(),
498 )
499 }),
500 ));
501 }
502
503 let mut seg = BitWriter::new();
504 seg.write_bit(params_changed); // params_present
505
506 if params_changed {
507 seg.write_bit(is_first); // restart_present
508
509 if is_first {
510 seg.write_bits(RESTART_SYNC13, 13);
511 seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it
512 seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder
513 seg.write_bits(0, 4); // min_channel
514 seg.write_bits(1, 4); // max_channel
515 seg.write_bits(1, 4); // max_matrix_channel
516 seg.write_bits(0, 4); // noise_shift
517 seg.write_bits(0, 23); // noisegen_seed
518 seg.write_bits(0, 19); // reserved
519 seg.write_bit(false); // data_check_present
520 seg.write_bits(u32::from(self.next_check), 8); // lossless_check
521 seg.write_bits(0, 16); // reserved
522 seg.write_bits(0, 6); // ch_assign: matrix channel 0 -> output slot 0
523 seg.write_bits(1, 6); // ch_assign: matrix channel 1 -> output slot 1
524 let bit_size = seg.bit_len() - 2; // restart_checksum's own convention
525 let crc = restart_checksum(seg.as_bytes(), bit_size);
526 seg.write_bits(u32::from(crc), 8);
527 }
528
529 seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default
530 seg.write_bit(true); // blocksize gate
531 seg.write_bits(n as u32, 9);
532 seg.write_bit(false); // matrix gate: keep 0 matrices
533 seg.write_bit(false); // output-shift gate: keep shift 0
534 seg.write_bit(false); // quant-step gate: keep step 0
535 }
536
537 // The decoder's predictor history is real output samples, pushed
538 // every block regardless of the chosen order — advance the
539 // analysis window now so the *next* AU's `choose` sees this one's
540 // actual samples.
541 for ch in 0..2 {
542 self.analysis[ch].extend_from_slice(&ch_samples[ch]);
543 let len = self.analysis[ch].len();
544 if len > ANALYSIS_WINDOW {
545 self.analysis[ch].drain(..len - ANALYSIS_WINDOW);
546 }
547 }
548
549 if params_changed {
550 for plan in &plans {
551 seg.write_bit(true); // per-channel gate
552 let order = plan.coeffs.len();
553 // FIR gate: always true, even for order 0 (the raw path). Once a
554 // restart no longer resets every AU (see `au_index`'s docs),
555 // `false` here means "no change" to the decoder's *own*
556 // `read_decoding_params` (`flags & PARAM_FIR != 0 &&
557 // br.read_bit()?` gates the whole call to `read_filter`) — it
558 // would leave a *previous* AU's nonzero FIR order (and its
559 // now-stale coefficients) applied to this AU's un-predicted
560 // residuals. `read_filter` always reads the 4-bit order first
561 // and unconditionally sets `f.order` from it (including to 0),
562 // so writing the gate unconditionally is what actually clears a
563 // filter this AU chose not to use.
564 seg.write_bit(true); // FIR gate
565 seg.write_bits(order as u32, 4);
566 if order > 0 {
567 seg.write_bits(FILTER_SHIFT, 4);
568 seg.write_bits(COEFF_BITS, 5);
569 seg.write_bits(0, 3); // coeff_shift
570 for &c in &plan.coeffs {
571 seg.write_signed(c, COEFF_BITS);
572 }
573 seg.write_bit(false); // explicit-state gate: read_filter always reads this (FIR too)
574 }
575 seg.write_bit(false); // IIR gate: keep order 0
576 seg.write_bit(false); // huff_offset gate: keep 0
577 seg.write_bits(u32::from(plan.codebook), 2);
578 seg.write_bits(plan.lsb_bits, 5);
579 }
580 }
581
582 for i in 0..samples.len() {
583 let plan = &plans[i % 2];
584 write_residual(
585 &mut seg,
586 plan.codebook,
587 plan.lsb_bits,
588 plan.sign_off,
589 plan.residuals[i / 2],
590 );
591 }
592
593 seg.write_bit(true); // end_of_segment
594 seg.align_to_byte();
595 if seg.bit_len() % 16 != 0 {
596 seg.write_bits(0, 8);
597 }
598 let seg_bytes = seg.into_bytes();
599
600 // Fold this AU's own samples the way `decode::Core::output` does,
601 // for the *next* AU's restart header.
602 let mut fold = 0u32;
603 for (i, &sample) in samples.iter().enumerate() {
604 fold ^= ((sample as u32) & 0x00FF_FFFF) << (i % 2);
605 }
606 self.next_check = xor_32_to_8(fold);
607
608 // A foreign decoder (ffmpeg's mlp_parse.c) reads more of the major
609 // sync than this crate's own decoder does: the two 13/5-bit
610 // "channel arrangement" fields (`ch_arr`/`ch_arr2`, both set to a
611 // stereo-only chanmap of 1 so `mlpdec.c` reports AV_CH_LAYOUT_STEREO
612 // and `group1_bits == 24` so it decodes at S32) and `num_substreams`
613 // (4 bits, at byte 16's top nibble) — 1, matching our own single-
614 // substream directory.
615 let mut major_sync = [0u8; 28];
616 major_sync[0..4].copy_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
617 major_sync[4] = self.rate_code << 4; // low nibble ignored by both decoders
618 major_sync[5] = 0x00;
619 major_sync[6] = 0x80; // ch_arr low bit (=1) + ch_arr2 top 5 bits (0)
620 major_sync[7] = 0x01; // ch_arr2 low 8 bits (=1)
621 major_sync[16] = 0x10; // num_substreams = 1
622 let checksum = major_sync_checksum(&major_sync);
623 major_sync[26..28].copy_from_slice(&checksum.to_le_bytes());
624 let major_sync_len = if is_first { major_sync.len() } else { 0 };
625 let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word
626
627 let total_len = 4 + major_sync_len + 2 + seg_bytes.len();
628 let len_words = (total_len as u16 / 2) & 0x0FFF;
629 let dir_bytes = dir_word.to_be_bytes();
630 // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c,
631 // `ff_mlp_calculate_parity`) folds the AU header's 4 bytes against
632 // the substream directory's bytes and rejects the AU unless the
633 // result's two nibbles are bitwise complements. This crate's own
634 // decoder never checks it (`sync.rs`'s docs), so the nibble is free
635 // to pick; find the one value (of 16) that satisfies the fold.
636 let check_nibble = (0u8..16)
637 .find(|&cn| {
638 let b0 = (cn << 4) | ((len_words >> 8) as u8 & 0x0F);
639 let b1 = (len_words & 0xFF) as u8;
640 let p = b0 ^ b1 ^ dir_bytes[0] ^ dir_bytes[1];
641 ((p >> 4) ^ p) & 0xF == 0xF
642 })
643 .expect("one of the 16 check-nibble values always satisfies the fold");
644 let length_word = (u16::from(check_nibble) << 12) | len_words;
645
646 let mut au = Vec::with_capacity(total_len);
647 au.extend_from_slice(&length_word.to_be_bytes());
648 au.extend_from_slice(&0u16.to_be_bytes()); // input_timing
649 if is_first {
650 au.extend_from_slice(&major_sync);
651 }
652 au.extend_from_slice(&dir_bytes);
653 au.extend_from_slice(&seg_bytes);
654 self.au_index += 1;
655 au
656 }
657
658 fn drain_full_units(&mut self) {
659 let per_au = self.access_unit_size * 2;
660 while self.pending.len() >= per_au {
661 let samples: Vec<i32> = self.pending.drain(..per_au).collect();
662 let bytes = self.encode_access_unit(&samples);
663 self.packets.push_back(bytes);
664 }
665 }
666}
667
668impl Encoder for TrueHdEncoder {
669 fn codec_parameters(&self) -> &CodecParameters {
670 &self.params
671 }
672
673 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
674 let Frame::Audio(audio) = frame else {
675 return Err(Error::corrupt("video frame pushed into a TrueHD encoder"));
676 };
677 if audio.format != SampleFormat::S32 {
678 return Err(Error::unsupported(
679 format!("{:?} input", audio.format),
680 "this encoder takes S32 (24-bit left-justified) samples",
681 ));
682 }
683 if audio.layout.channel_count() != 2 {
684 return Err(Error::unsupported(
685 format!("{} channel input", audio.layout.channel_count()),
686 "this encoder writes stereo only",
687 ));
688 }
689 if audio.rate != self.sample_rate {
690 return Err(Error::unsupported(
691 format!("{} Hz input", audio.rate),
692 "this encoder was set up for a different sample rate",
693 ));
694 }
695 if audio.planar {
696 for i in 0..audio.samples {
697 for plane in audio.data.iter().take(2) {
698 let at = i * 4;
699 let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]];
700 self.pending.push(i32::from_ne_bytes(w) >> 8);
701 }
702 }
703 } else {
704 for word in audio.data[0].chunks_exact(4).take(audio.samples * 2) {
705 self.pending
706 .push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8);
707 }
708 }
709 self.drain_full_units();
710 Ok(())
711 }
712
713 fn receive_packet(&mut self) -> Result<Packet> {
714 match self.packets.pop_front() {
715 Some(data) => Ok(Packet::new(
716 0,
717 ec_core::timebase::TimeBase::new(1, i64::from(self.sample_rate)),
718 data,
719 )),
720 None if self.eof => Err(Error::Eof),
721 None => Err(Error::NeedMore),
722 }
723 }
724
725 fn flush(&mut self) -> Result<()> {
726 if !self.pending.is_empty() {
727 let mut samples = std::mem::take(&mut self.pending);
728 // corner-cut: TrueHD's own block-size field is invalid under 8
729 // samples/channel (crate::decode::read_decoding_params rejects
730 // it); a final partial access unit shorter than that is padded
731 // by repeating its last real sample pair. Ceiling: a caller
732 // wanting the exact original count trims the decoder's output
733 // to it (the container's duration, same as any codec's short
734 // final frame) — upgrade path is a real short-block encoding,
735 // not needed at r1 scope.
736 if samples.len() / 2 < 8 {
737 let last = [
738 *samples.get(samples.len().wrapping_sub(2)).unwrap_or(&0),
739 *samples.last().unwrap_or(&0),
740 ];
741 while samples.len() / 2 < 8 {
742 samples.extend_from_slice(&last);
743 }
744 }
745 let bytes = self.encode_access_unit(&samples);
746 self.packets.push_back(bytes);
747 }
748 self.eof = true;
749 Ok(())
750 }
751}
752
753#[cfg(test)]
754mod tests {
755 use super::*;
756 use crate::sync::TrueHdDecoder;
757 use ec_core::frame::{AudioFrame, Frame as EcFrame};
758 use ec_core::packet::Buf;
759
760 /// A deterministic tone+noise fixture, interleaved stereo S32
761 /// left-justified, `n` samples per channel.
762 fn tone_fixture(n: usize) -> Vec<i32> {
763 let mut v = Vec::with_capacity(n * 2);
764 let mut lcg: u32 = 0x12345;
765 for i in 0..n {
766 let l = ((i as f64 * 0.07).sin() * 4_000_000.0) as i32;
767 lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
768 let r = l.wrapping_add((lcg >> 8) as i32 % 5000 - 2500);
769 v.push(l.clamp(-8_388_608, 8_388_607));
770 v.push(r.clamp(-8_388_608, 8_388_607));
771 }
772 v
773 }
774
775 fn s32_frame(interleaved: &[i32], sample_rate: u32) -> ec_core::frame::AudioFrame {
776 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
777 for &s in interleaved {
778 bytes.extend_from_slice(&(s << 8).to_ne_bytes());
779 }
780 AudioFrame::try_new(
781 SampleFormat::S32,
782 false,
783 ChannelLayout::Stereo,
784 sample_rate,
785 interleaved.len() / 2,
786 vec![Buf::from_vec(bytes)],
787 )
788 .unwrap()
789 }
790
791 /// Round-trip gate 1: encode a multi-access-unit stereo fixture (a
792 /// partial final access unit included), decode every access unit back
793 /// through this crate's own decoder, and check every sample exactly.
794 #[test]
795 fn encoder_round_trips_through_our_own_decoder() {
796 for n in [173usize, 40, 40 * 5 + 7, 1] {
797 let samples = tone_fixture(n);
798 let mut enc = TrueHdEncoder::new(48_000).unwrap();
799 enc.send_frame(&EcFrame::Audio(s32_frame(&samples, 48_000)))
800 .unwrap();
801 enc.flush().unwrap();
802
803 let mut dec = TrueHdDecoder::new();
804 let mut decoded = Vec::new();
805 loop {
806 match enc.receive_packet() {
807 Ok(pkt) => {
808 if let Some(frame) = dec.decode_access_unit(&pkt.data).unwrap() {
809 for word in frame.data[0].chunks_exact(4) {
810 decoded.push(
811 i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8,
812 );
813 }
814 }
815 }
816 Err(Error::Eof) => break,
817 Err(e) => panic!("n={n}: {e:?}"),
818 }
819 }
820 decoded.truncate(samples.len());
821 assert_eq!(decoded, samples, "n={n}: sample mismatch");
822 let stats = dec.check_stats();
823 assert_eq!(stats.restart_crc_failures, 0, "n={n}: restart CRC");
824 assert_eq!(stats.lossless_check_failures, 0, "n={n}: lossless check");
825 assert_eq!(stats.parity_failures, 0, "n={n}: parity");
826 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");
827 }
828 }
829
830 /// A pure LCG noise fixture (no tonal structure for LPC to exploit),
831 /// same shape as [`tone_fixture`].
832 fn noise_fixture(n: usize) -> Vec<i32> {
833 let mut v = Vec::with_capacity(n * 2);
834 let mut lcg: u32 = 0xACE1_5AFE;
835 for _ in 0..n {
836 for _ in 0..2 {
837 lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
838 let s = ((lcg >> 8) as i32 % 16_777_216) - 8_388_608;
839 v.push(s.clamp(-8_388_608, 8_388_607));
840 }
841 }
842 v
843 }
844
845 fn encoded_bytes(samples: &[i32], sample_rate: u32) -> usize {
846 let mut enc = TrueHdEncoder::new(sample_rate).unwrap();
847 enc.send_frame(&EcFrame::Audio(s32_frame(samples, sample_rate)))
848 .unwrap();
849 enc.flush().unwrap();
850 let mut total = 0;
851 loop {
852 match enc.receive_packet() {
853 Ok(pkt) => total += pkt.data.len(),
854 Err(Error::Eof) => break,
855 Err(e) => panic!("{e:?}"),
856 }
857 }
858 total
859 }
860
861 /// Compression gate: at 192 kHz (160 samples/AU, so the fixed per-AU
862 /// header cost amortizes to a few percent) tonal content — where the
863 /// FIR predictor should do real work — encodes to at most 65% of raw
864 /// 24-bit PCM. Pure LCG noise (nothing for the predictor to exploit,
865 /// every AU picks `ChannelPlan::raw`) can never shrink below raw PCM's
866 /// own size — what's left to bound is this format's own mandatory
867 /// per-AU container framing, a floor computed from the literal field
868 /// widths below, not fitted to any observed byte count.
869 #[test]
870 fn compression_ratio_gates() {
871 let n = 19_200usize; // 120 access units at 192 kHz
872 let raw_bytes = n * 2 * 3; // 2 channels, 24-bit/3-byte samples
873
874 let tonal = tone_fixture(n);
875 let tonal_bytes = encoded_bytes(&tonal, 192_000);
876 let tonal_ratio = tonal_bytes as f64 / raw_bytes as f64;
877 assert!(
878 tonal_ratio <= 0.65,
879 "tonal: {tonal_bytes} bytes vs {raw_bytes} raw ({:.1}%), want <=65%",
880 tonal_ratio * 100.0
881 );
882
883 // Every AU pays: `sync::AU_HEADER_LEN` (4B: `length_word` +
884 // `input_timing`) + one substream directory entry (2B) = 6B of
885 // mandatory container framing, plus the segment's own
886 // `params_present`(1 bit) + `end_of_segment`(1 bit) bookkeeping,
887 // which `BitWriter::align_to_byte` rounds up to a whole byte and
888 // then, if that leaves an odd byte count, one more byte to reach a
889 // 16-bit word (`encode_access_unit`'s own `bit_len() % 16` check) —
890 // 2 bytes of alignment slack in the worst case. 6 + 2 = 8 bytes/AU,
891 // paid by every AU regardless of content.
892 const PER_AU_FRAMING_FLOOR: u64 = 8;
893 // Access unit 0 alone additionally carries a major sync
894 // (`sync::MajorSyncInfo`'s own 28-byte `MAJOR_SYNC_LEN`) and a
895 // restart header — the literal sum of every field
896 // `encode_access_unit` writes under `is_first`: 13 (sync) + 1
897 // (noise_type) + 16 (output_timing) + 4 + 4 + 4 (channel counts) + 4
898 // (noise_shift) + 23 (noisegen_seed) + 19 (reserved) + 1
899 // (data_check_present) + 8 (lossless_check) + 16 (reserved) + 6 + 6
900 // (ch_assign) + 8 (crc) = 133 bits — plus the decoding-params
901 // section's 14 common bits (presence/blocksize/matrix/output-shift/
902 // quant-step gates) and, per channel, the minimal order-0 raw
903 // path's 15 bits (per-channel gate, FIR gate, 4-bit order, IIR
904 // gate, huff_offset gate, 2-bit codebook, 5-bit lsb_bits): 133 + 14
905 // + 2*15 = 177 bits, 23 bytes ceiled. AU0's one-time extra beyond
906 // the per-AU floor above: 28 (major sync) + 23 = 51 bytes.
907 const FIRST_AU_EXTRA: u64 = 51;
908 // Small, explicitly-named slack for byte/16-bit rounding this
909 // derivation approximates rather than tracks bit-for-bit — not
910 // fitted to make any specific fixture pass.
911 const ROUNDING_SLACK: u64 = 8;
912
913 let noise = noise_fixture(n);
914 let noise_bytes = encoded_bytes(&noise, 192_000) as u64;
915 let num_aus = (n as u64).div_ceil(160); // access_unit_size @ 192 kHz
916 let floor_bytes =
917 raw_bytes as u64 + num_aus * PER_AU_FRAMING_FLOOR + FIRST_AU_EXTRA + ROUNDING_SLACK;
918 assert!(
919 noise_bytes <= floor_bytes,
920 "noise: {noise_bytes} bytes vs {raw_bytes} raw + {num_aus} AUs' \
921 format-derived framing floor {floor_bytes}"
922 );
923 }
924}