forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-truehd2': FIR-LPC prediction with cross-AU state, ffmpeg-exact

Browse files at this commit

360bf3ba97b986645e57621a95749aba3ecd9cbcAhmet Kaan GümüşParent: cd31f8db0c2924
crates/ec-truehd/src/decode.rsmodified+20 -1
@@ -66,7 +66,7 @@ const MAX_MATRIX_CHANNEL: usize = 7;
66 /// appends after the last matrix channel.66 /// appends after the last matrix channel.
67 const MAX_CHANNELS: usize = MAX_MATRIX_CHANNEL + 3;67 const MAX_CHANNELS: usize = MAX_MATRIX_CHANNEL + 3;
68 const MAX_MATRICES: usize = 8;68 const MAX_MATRICES: usize = 8;
69-const MAX_FILTER_ORDER: usize = 8;69+pub(crate) const MAX_FILTER_ORDER: usize = 8;
70 const END_OF_STREAM: u32 = 0xD234_D234;70 const END_OF_STREAM: u32 = 0xD234_D234;
71 71
72 /// The fixed 256-entry dither table noise type 1 (TrueHD's `0x31EB`) draws72 /// The fixed 256-entry dither table noise type 1 (TrueHD's `0x31EB`) draws
@@ -583,6 +583,21 @@ impl Core {
583 self.stats.lossless_check_failures += 1;583 self.stats.lossless_check_failures += 1;
584 }584 }
585 let s = &mut self.substreams[idx];585 let s = &mut self.substreams[idx];
586+ // A restart header resets every decoding *parameter* (order,
587+ // codebook, huff_lsbs, ...) to its spec default, but — per ffmpeg's
588+ // `read_restart_header` (mlpdec.c), which `memset`s
589+ // `output_shift`/`quant_step_size`/per-channel param fields but
590+ // never touches `filter_params[FIR/IIR].state` — the FIR/IIR
591+ // predictor's *history* (the actual past decoded samples) is a
592+ // rolling buffer `filter_channel` maintains every block regardless
593+ // of the channel's current order, and survives every restart
594+ // header in an access-unit stream. Zeroing it here (this crate's
595+ // previous behaviour) was self-consistent with our own encoder's
596+ // matching per-AU-fresh-history assumption but diverges from a
597+ // real MLP/TrueHD stream from AU 2 onward whenever a channel uses
598+ // a nonzero-order filter.
599+ let old_states: [(Filter, Filter); MAX_CHANNELS] =
600+ std::array::from_fn(|ch| (s.channels[ch].fir, s.channels[ch].iir));
586 *s = Substream {601 *s = Substream {
587 restart_seen: true,602 restart_seen: true,
588 noise_type,603 noise_type,
@@ -595,6 +610,10 @@ impl Core {
595 ch_assign,610 ch_assign,
596 ..Substream::new()611 ..Substream::new()
597 };612 };
613+ for (ch, (old_fir, old_iir)) in old_states.into_iter().enumerate() {
614+ s.channels[ch].fir.state = old_fir.state;
615+ s.channels[ch].iir.state = old_iir.state;
616+ }
598 Ok(())617 Ok(())
599 }618 }
600 619
crates/ec-truehd/src/encode.rsmodified+522 -17
@@ -20,6 +20,19 @@
20 //! `lossless_check_data` fold); since every access unit here is its own20 //! `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 way21 //! 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.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.
23 36
24 use std::collections::VecDeque;37 use std::collections::VecDeque;
25 38
@@ -29,18 +42,272 @@ use ec_core::frame::{ChannelLayout, Frame, SampleFormat};
29 use ec_core::packet::Packet;42 use ec_core::packet::Packet;
30 use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters};43 use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters};
31 44
32-use crate::decode::restart_checksum;45+use crate::decode::{HUFFMAN_TABLES, MAX_FILTER_ORDER, restart_checksum};
33 use crate::sync::MAJOR_SYNC_TRUEHD;46 use crate::sync::MAJOR_SYNC_TRUEHD;
34 47
48+/// FIR order this encoder tries; matches `decode::MAX_FILTER_ORDER`.
49+const 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.
52+const FILTER_SHIFT: u32 = 12;
53+/// Coefficient field width; `coeff_shift` stays 0 (`15 + 0 <= 16`, the
54+/// decoder's own bound).
55+const 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.
58+const 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.
61+const 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`).
67+fn 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.
85+fn 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).
105+fn 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]).
128+fn 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).
182+fn 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.
205+struct ChannelPlan {
206+ coeffs: Vec<i32>,
207+ codebook: u8,
208+ lsb_bits: u32,
209+ sign_off: i32,
210+ residuals: Vec<i32>,
211+}
212+
213+impl 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+
35 /// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both308 /// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both
36 /// noise types (the 14th bit picks the type).309 /// noise types (the 14th bit picks the type).
37 const RESTART_SYNC13: u32 = 0x31EA >> 1;310 const RESTART_SYNC13: u32 = 0x31EA >> 1;
38-/// Offset-binary bias for a 24-bit residual with no predictor and no
39-/// quantization: `sample + 2^23`, matching
40-/// [`crate::decode::Substream::recompute_sign_offset`] at `codebook = 0`,
41-/// `huff_lsbs = 24`, `quant_step = 0`.
42-const SAMPLE_BIAS_24: i64 = 1 << 23;
43-
44 /// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]311 /// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]
45 /// uses for the lossless-check byte).312 /// uses for the lossless-check byte).
46 fn xor_32_to_8(v: u32) -> u8 {313 fn xor_32_to_8(v: u32) -> u8 {
@@ -96,9 +363,39 @@ pub struct TrueHdEncoder {
96 /// folded from the access unit just written; `0` (unchecked by the363 /// folded from the access unit just written; `0` (unchecked by the
97 /// decoder) before the first one.364 /// decoder) before the first one.
98 next_check: u8,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])>,
99 eof: bool,390 eof: bool,
100 }391 }
101 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.
397+const ANALYSIS_WINDOW: usize = 16384;
398+
102 impl TrueHdEncoder {399 impl TrueHdEncoder {
103 /// An encoder for one 44.1/48 kHz-family stereo stream.400 /// An encoder for one 44.1/48 kHz-family stereo stream.
104 pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> {401 pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> {
@@ -131,6 +428,9 @@ impl TrueHdEncoder {
131 pending: Vec::new(),428 pending: Vec::new(),
132 packets: VecDeque::new(),429 packets: VecDeque::new(),
133 next_check: 0,430 next_check: 0,
431+ analysis: [Vec::new(), Vec::new()],
432+ au_index: 0,
433+ last_params: None,
134 eof: false,434 eof: false,
135 })435 })
136 }436 }
@@ -142,10 +442,71 @@ impl TrueHdEncoder {
142 let n = samples.len() / 2;442 let n = samples.len() / 2;
143 debug_assert!(n <= self.access_unit_size);443 debug_assert!(n <= self.access_unit_size);
144 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+
145 let mut seg = BitWriter::new();503 let mut seg = BitWriter::new();
146- seg.write_bit(true); // params_present504+ seg.write_bit(params_changed); // params_present
147- seg.write_bit(true); // restart_present505+
506+ if params_changed {
507+ seg.write_bit(is_first); // restart_present
148 508
509+ if is_first {
149 seg.write_bits(RESTART_SYNC13, 13);510 seg.write_bits(RESTART_SYNC13, 13);
150 seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it511 seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it
151 seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder512 seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder
@@ -163,6 +524,7 @@ impl TrueHdEncoder {
163 let bit_size = seg.bit_len() - 2; // restart_checksum's own convention524 let bit_size = seg.bit_len() - 2; // restart_checksum's own convention
164 let crc = restart_checksum(seg.as_bytes(), bit_size);525 let crc = restart_checksum(seg.as_bytes(), bit_size);
165 seg.write_bits(u32::from(crc), 8);526 seg.write_bits(u32::from(crc), 8);
527+ }
166 528
167 seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default529 seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default
168 seg.write_bit(true); // blocksize gate530 seg.write_bit(true); // blocksize gate
@@ -170,18 +532,62 @@ impl TrueHdEncoder {
170 seg.write_bit(false); // matrix gate: keep 0 matrices532 seg.write_bit(false); // matrix gate: keep 0 matrices
171 seg.write_bit(false); // output-shift gate: keep shift 0533 seg.write_bit(false); // output-shift gate: keep shift 0
172 seg.write_bit(false); // quant-step gate: keep step 0534 seg.write_bit(false); // quant-step gate: keep step 0
173- for _ch in 0..2 {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 {
174 seg.write_bit(true); // per-channel gate551 seg.write_bit(true); // per-channel gate
175- seg.write_bit(false); // FIR gate: keep order 0552+ 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+ }
176 seg.write_bit(false); // IIR gate: keep order 0575 seg.write_bit(false); // IIR gate: keep order 0
177 seg.write_bit(false); // huff_offset gate: keep 0576 seg.write_bit(false); // huff_offset gate: keep 0
178- seg.write_bits(0, 2); // codebook 0: raw, no Huffman code577+ seg.write_bits(u32::from(plan.codebook), 2);
179- seg.write_bits(24, 5); // huff_lsbs: full 24-bit raw residual578+ seg.write_bits(plan.lsb_bits, 5);
579+ }
180 }580 }
181 581
182- for &sample in samples {582+ for i in 0..samples.len() {
183- let raw = ((i64::from(sample) + SAMPLE_BIAS_24) as u32) & 0x00FF_FFFF;583+ let plan = &plans[i % 2];
184- seg.write_bits(raw, 24);584+ write_residual(
585+ &mut seg,
586+ plan.codebook,
587+ plan.lsb_bits,
588+ plan.sign_off,
589+ plan.residuals[i / 2],
590+ );
185 }591 }
186 592
187 seg.write_bit(true); // end_of_segment593 seg.write_bit(true); // end_of_segment
@@ -215,9 +621,10 @@ impl TrueHdEncoder {
215 major_sync[16] = 0x10; // num_substreams = 1621 major_sync[16] = 0x10; // num_substreams = 1
216 let checksum = major_sync_checksum(&major_sync);622 let checksum = major_sync_checksum(&major_sync);
217 major_sync[26..28].copy_from_slice(&checksum.to_le_bytes());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 };
218 let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word625 let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word
219 626
220- let total_len = 4 + major_sync.len() + 2 + seg_bytes.len();627+ let total_len = 4 + major_sync_len + 2 + seg_bytes.len();
221 let len_words = (total_len as u16 / 2) & 0x0FFF;628 let len_words = (total_len as u16 / 2) & 0x0FFF;
222 let dir_bytes = dir_word.to_be_bytes();629 let dir_bytes = dir_word.to_be_bytes();
223 // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c,630 // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c,
@@ -239,9 +646,12 @@ impl TrueHdEncoder {
239 let mut au = Vec::with_capacity(total_len);646 let mut au = Vec::with_capacity(total_len);
240 au.extend_from_slice(&length_word.to_be_bytes());647 au.extend_from_slice(&length_word.to_be_bytes());
241 au.extend_from_slice(&0u16.to_be_bytes()); // input_timing648 au.extend_from_slice(&0u16.to_be_bytes()); // input_timing
649+ if is_first {
242 au.extend_from_slice(&major_sync);650 au.extend_from_slice(&major_sync);
651+ }
243 au.extend_from_slice(&dir_bytes);652 au.extend_from_slice(&dir_bytes);
244 au.extend_from_slice(&seg_bytes);653 au.extend_from_slice(&seg_bytes);
654+ self.au_index += 1;
245 au655 au
246 }656 }
247 657
@@ -416,4 +826,99 @@ mod tests {
416 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");826 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");
417 }827 }
418 }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+ }
419 }924 }