forge
Explore
Log in

Don't you dare go Hollow

wip(truehd): FIR LPC + codebook-2 residuals, debug artifacts still in — not a done state

Browse files at this commit

8073482ec2a611d2a038de7b133764fc8684a01fAhmet Kaan GümüşParent: d86dccb
crates/ec-truehd/src/encode.rsmodified+356 -14
@@ -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,246 @@ 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::{restart_checksum, HUFFMAN_TABLES};
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 = 2;
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+/// The largest `lsb_bits` (see [`choose_lsb_bits`]) an LPC plan is allowed
63+/// to need; see `ChannelPlan::choose`'s corner-cut comment.
64+const MAX_LPC_LSB_BITS: u32 = 12;
65+
66+/// A residual's sign-offset bias (`Substream::recompute_sign_offset`'s
67+/// formula with `huff_offset = 0`, `quant_step_size = 0`): the constant
68+/// subtracted from a raw sample/residual before it is split into a
69+/// codebook index (`codebook > 0`) or written bare (`codebook == 0`).
70+fn sign_offset(codebook: u8, lsb_bits: u32) -> i32 {
71+ let lsb_bits = lsb_bits as i32;
72+ let sign_shift = lsb_bits
73+ + if codebook > 0 {
74+ 2 - i32::from(codebook)
75+ } else {
76+ -1
77+ };
78+ let mut off = if codebook > 0 { -(7 << lsb_bits) } else { 0 };
79+ if sign_shift >= 0 {
80+ off -= 1 << sign_shift;
81+ }
82+ off
83+}
84+
85+/// Writes one residual through `codebook`/`lsb_bits`/`sign_off` (from
86+/// [`sign_offset`]) — the exact inverse of
87+/// `decode::Core::read_block`'s per-sample reconstruction.
88+fn write_residual(bw: &mut BitWriter, codebook: u8, lsb_bits: u32, sign_off: i32, r: i32) {
89+ let raw = (r.wrapping_sub(sign_off)) as u32;
90+ if codebook == 0 {
91+ bw.write_bits(raw, lsb_bits);
92+ return;
93+ }
94+ let idx = (raw >> lsb_bits) as usize;
95+ let (code, len) = HUFFMAN_TABLES[usize::from(codebook) - 1][idx];
96+ debug_assert!(len > 0, "residual quotient {idx} outside codebook range");
97+ bw.write_bits(u32::from(code), u32::from(len));
98+ if lsb_bits > 0 {
99+ bw.write_bits(raw & ((1u32 << lsb_bits) - 1), lsb_bits);
100+ }
101+}
102+
103+/// The smallest `lsb_bits` (format field `huff_lsbs`, `quant_step = 0`) for
104+/// which every residual's codebook-2 quotient (`(r - sign_offset(2,
105+/// lsb_bits)) >> lsb_bits`) lands inside `0..16` (codebook 2's 16 valid
106+/// entries) — or `None` if no field width up to the format's 24-bit cap
107+/// does (residuals too wild for this codebook; caller falls back to raw).
108+fn choose_lsb_bits(residuals: &[i32]) -> Option<u32> {
109+ let (mut max_r, mut min_r) = (i32::MIN, i32::MAX);
110+ for &r in residuals {
111+ max_r = max_r.max(r);
112+ min_r = min_r.min(r);
113+ }
114+ let threshold = i64::from(max_r).max(-1 - i64::from(min_r)).max(0);
115+ for lsb_bits in 0..=24u32 {
116+ if (8i64 << lsb_bits) > threshold {
117+ return Some(lsb_bits);
118+ }
119+ }
120+ None
121+}
122+
123+/// Levinson-Durbin on `samples`' own autocorrelation: LPC coefficients
124+/// `a[1..=order]` such that `sample[n] ≈ Σ a[j] · sample[n - j]`.
125+fn levinson_durbin(samples: &[i32], order: usize) -> Vec<f64> {
126+ let x: Vec<f64> = samples.iter().map(|&s| f64::from(s)).collect();
127+ let mut r = vec![0.0f64; order + 1];
128+ for (lag, slot) in r.iter_mut().enumerate() {
129+ let mut s = 0.0;
130+ for i in 0..x.len() - lag {
131+ s += x[i] * x[i + lag];
132+ }
133+ *slot = s;
134+ }
135+ let mut err = r[0];
136+ let mut a = vec![0.0f64; order + 1];
137+ if err <= 0.0 {
138+ return vec![0.0; order];
139+ }
140+ for i in 1..=order {
141+ let mut acc = r[i];
142+ for j in 1..i {
143+ acc -= a[j] * r[i - j];
144+ }
145+ let k = acc / err;
146+ let mut new_a = a.clone();
147+ new_a[i] = k;
148+ for j in 1..i {
149+ new_a[j] = a[j] - k * a[i - j];
150+ }
151+ a = new_a;
152+ err *= 1.0 - k * k;
153+ if err <= 1e-9 {
154+ break;
155+ }
156+ }
157+ a[1..=order].to_vec()
158+}
159+
160+/// Integer residuals `sample[n] - (Σ coeffs[j] · history[j]) >> FILTER_SHIFT`
161+/// over the channel's own past samples (most recent first) — the exact
162+/// inverse of `decode::filter_channel`'s reconstruction, with the same
163+/// integer arithmetic (lossless coding: the decoder's filter state is
164+/// always the *real* sample, since `quant_step = 0` never masks a bit off).
165+fn fir_residuals(samples: &[i32], coeffs: &[i32]) -> Vec<i32> {
166+ let order = coeffs.len();
167+ let mut hist = vec![0i32; order.max(1)];
168+ let mut out = Vec::with_capacity(samples.len());
169+ for &s in samples {
170+ let mut accum: i64 = 0;
171+ for j in 0..order {
172+ accum += i64::from(hist[j]) * i64::from(coeffs[j]);
173+ }
174+ let predict = (accum >> FILTER_SHIFT) as i32;
175+ out.push(s.wrapping_sub(predict));
176+ for j in (1..order).rev() {
177+ hist[j] = hist[j - 1];
178+ }
179+ if order > 0 {
180+ hist[0] = s;
181+ }
182+ }
183+ out
184+}
185+
186+/// One channel's chosen encoding for an access unit: either a quantized
187+/// order-`coeffs.len()` FIR predictor with codebook-2 residual coding, or
188+/// the raw 24-bit path (`coeffs` empty, `codebook = 0`, `lsb_bits = 24`) —
189+/// whichever this AU's own samples cost fewer bits under.
190+struct ChannelPlan {
191+ coeffs: Vec<i32>,
192+ codebook: u8,
193+ lsb_bits: u32,
194+ sign_off: i32,
195+ residuals: Vec<i32>,
196+}
197+
198+impl ChannelPlan {
199+ /// `filter_overhead_bits` for a chosen `order`: the decoding-params
200+ /// fields a non-zero FIR order adds (`shift(4) + coeff_bits(5) +
201+ /// coeff_shift(3) + coeffs(order * COEFF_BITS)`).
202+ fn fir_overhead_bits(order: usize) -> u64 {
203+ 4 + 5 + 3 + (order as u64) * u64::from(COEFF_BITS)
204+ }
205+
206+ fn raw(samples: &[i32]) -> ChannelPlan {
207+ let lsb_bits = 24;
208+ ChannelPlan {
209+ coeffs: Vec::new(),
210+ codebook: 0,
211+ lsb_bits,
212+ sign_off: sign_offset(0, lsb_bits),
213+ residuals: samples.to_vec(),
214+ }
215+ }
216+
217+ /// Chooses the cheaper of the raw path and an order-[`FILTER_ORDER`]
218+ /// LPC + codebook-2 path for one channel's samples in this AU.
219+ fn choose(samples: &[i32]) -> ChannelPlan {
220+ let raw = ChannelPlan::raw(samples);
221+ if samples.len() < MIN_SAMPLES_FOR_LPC {
222+ return raw;
223+ }
224+ let a = levinson_durbin(samples, FILTER_ORDER);
225+ let scale = f64::from(1u32 << FILTER_SHIFT);
226+ let clamp_max = (1i32 << (COEFF_BITS - 1)) - 1;
227+ let clamp_min = -(1i32 << (COEFF_BITS - 1));
228+ let coeffs: Vec<i32> = a
229+ .iter()
230+ .map(|&c| ((c * scale).round() as i32).clamp(clamp_min, clamp_max))
231+ .collect();
232+ let residuals = fir_residuals(samples, &coeffs);
233+ let Some(lsb_bits) = choose_lsb_bits(&residuals) else {
234+ return raw;
235+ };
236+ eprintln!("DEBUG coeffs={coeffs:?} lsb_bits={lsb_bits}");
237+ // corner-cut: some access units this encoder tried (found by
238+ // sweeping the ffmpeg oracle test bisecting on FIR order and this
239+ // bound — order-independent, so not filter instability) decode
240+ // wrong through ffmpeg while still round-tripping exactly through
241+ // this crate's own decoder — a real divergence between the two
242+ // that this build could not pin down further inside its budget,
243+ // localized only to large residual fields (`lsb_bits` above this
244+ // bound). ffmpeg is the oracle: bounding `lsb_bits` here keeps
245+ // every case this build measured (the 48 kHz tone+noise oracle
246+ // fixture, this crate's own round-trip fixtures, and both real
247+ // externally-encoded oracle files) on ffmpeg's bit-exact side.
248+ // Ceiling: the divergence's actual cause (likely in
249+ // `decode::filter_channel` or the codebook-2 sign-offset math,
250+ // unexercised by real FIR streams this narrow before) is still
251+ // open — see the ledger — and would let this bound widen back
252+ // toward the format's real 24-bit `lsb_bits` range.
253+ if lsb_bits > MAX_LPC_LSB_BITS {
254+ return raw;
255+ }
256+ let sign_off = sign_offset(CODEBOOK, lsb_bits);
257+ let mut lpc_bits = Self::fir_overhead_bits(FILTER_ORDER);
258+ let book = &HUFFMAN_TABLES[usize::from(CODEBOOK) - 1];
259+ for &r in &residuals {
260+ let raw_val = (r.wrapping_sub(sign_off)) as u32;
261+ let idx = (raw_val >> lsb_bits) as usize;
262+ let Some(&(_, len)) = book.get(idx).filter(|&&(_, len)| len > 0) else {
263+ return raw;
264+ };
265+ lpc_bits += u64::from(len) + u64::from(lsb_bits);
266+ }
267+ let raw_bits = (samples.len() as u64) * 24;
268+ if lpc_bits < raw_bits {
269+ ChannelPlan {
270+ coeffs,
271+ codebook: CODEBOOK,
272+ lsb_bits,
273+ sign_off,
274+ residuals,
275+ }
276+ } else {
277+ raw
278+ }
279+ }
280+}
281+
35 /// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both282 /// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both
36 /// noise types (the 14th bit picks the type).283 /// noise types (the 14th bit picks the type).
37 const RESTART_SYNC13: u32 = 0x31EA >> 1;284 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`]285 /// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]
45 /// uses for the lossless-check byte).286 /// uses for the lossless-check byte).
46 fn xor_32_to_8(v: u32) -> u8 {287 fn xor_32_to_8(v: u32) -> u8 {
@@ -170,18 +411,50 @@ impl TrueHdEncoder {
170 seg.write_bit(false); // matrix gate: keep 0 matrices411 seg.write_bit(false); // matrix gate: keep 0 matrices
171 seg.write_bit(false); // output-shift gate: keep shift 0412 seg.write_bit(false); // output-shift gate: keep shift 0
172 seg.write_bit(false); // quant-step gate: keep step 0413 seg.write_bit(false); // quant-step gate: keep step 0
173- for _ch in 0..2 {414+
415+ // De-interleave, then let each channel pick raw vs. LPC+codebook-2
416+ // independently (see `ChannelPlan::choose`).
417+ let plans: [ChannelPlan; 2] = [
418+ ChannelPlan::choose(&samples.iter().step_by(2).copied().collect::<Vec<_>>()),
419+ ChannelPlan::choose(
420+ &samples
421+ .iter()
422+ .skip(1)
423+ .step_by(2)
424+ .copied()
425+ .collect::<Vec<_>>(),
426+ ),
427+ ];
428+
429+ for plan in &plans {
174 seg.write_bit(true); // per-channel gate430 seg.write_bit(true); // per-channel gate
175- seg.write_bit(false); // FIR gate: keep order 0431+ let order = plan.coeffs.len();
432+ seg.write_bit(order > 0); // FIR gate
433+ if order > 0 {
434+ seg.write_bits(order as u32, 4);
435+ seg.write_bits(FILTER_SHIFT, 4);
436+ seg.write_bits(COEFF_BITS, 5);
437+ seg.write_bits(0, 3); // coeff_shift
438+ for &c in &plan.coeffs {
439+ seg.write_signed(c, COEFF_BITS);
440+ }
441+ seg.write_bit(false); // explicit-state gate: read_filter always reads this (FIR too)
442+ }
176 seg.write_bit(false); // IIR gate: keep order 0443 seg.write_bit(false); // IIR gate: keep order 0
177 seg.write_bit(false); // huff_offset gate: keep 0444 seg.write_bit(false); // huff_offset gate: keep 0
178- seg.write_bits(0, 2); // codebook 0: raw, no Huffman code445+ seg.write_bits(u32::from(plan.codebook), 2);
179- seg.write_bits(24, 5); // huff_lsbs: full 24-bit raw residual446+ seg.write_bits(plan.lsb_bits, 5);
180 }447 }
181 448
182- for &sample in samples {449+ for i in 0..samples.len() {
183- let raw = ((i64::from(sample) + SAMPLE_BIAS_24) as u32) & 0x00FF_FFFF;450+ let plan = &plans[i % 2];
184- seg.write_bits(raw, 24);451+ write_residual(
452+ &mut seg,
453+ plan.codebook,
454+ plan.lsb_bits,
455+ plan.sign_off,
456+ plan.residuals[i / 2],
457+ );
185 }458 }
186 459
187 seg.write_bit(true); // end_of_segment460 seg.write_bit(true); // end_of_segment
@@ -416,4 +689,73 @@ mod tests {
416 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");689 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");
417 }690 }
418 }691 }
692+
693+ /// A pure LCG noise fixture (no tonal structure for LPC to exploit),
694+ /// same shape as [`tone_fixture`].
695+ fn noise_fixture(n: usize) -> Vec<i32> {
696+ let mut v = Vec::with_capacity(n * 2);
697+ let mut lcg: u32 = 0xACE1_5AFE;
698+ for _ in 0..n {
699+ for _ in 0..2 {
700+ lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
701+ let s = ((lcg >> 8) as i32 % 16_777_216) - 8_388_608;
702+ v.push(s.clamp(-8_388_608, 8_388_607));
703+ }
704+ }
705+ v
706+ }
707+
708+ fn encoded_bytes(samples: &[i32], sample_rate: u32) -> usize {
709+ let mut enc = TrueHdEncoder::new(sample_rate).unwrap();
710+ enc.send_frame(&EcFrame::Audio(s32_frame(samples, sample_rate)))
711+ .unwrap();
712+ enc.flush().unwrap();
713+ let mut total = 0;
714+ loop {
715+ match enc.receive_packet() {
716+ Ok(pkt) => total += pkt.data.len(),
717+ Err(Error::Eof) => break,
718+ Err(e) => panic!("{e:?}"),
719+ }
720+ }
721+ total
722+ }
723+
724+ /// Compression gate: at 192 kHz (160 samples/AU, so the fixed per-AU
725+ /// header cost amortizes to a few percent) tonal content — where the
726+ /// FIR predictor should do real work — encodes to at most 65% of raw
727+ /// 24-bit PCM, and pure LCG noise (nothing for the predictor to
728+ /// exploit) never grows past raw PCM's own size — the `ChannelPlan`
729+ /// raw/LPC bit-cost comparison's whole job.
730+ #[test]
731+ fn dbg_plan() {
732+ let samples = tone_fixture(160);
733+ let ch0: Vec<i32> = samples.iter().step_by(2).copied().collect();
734+ let plan = ChannelPlan::choose(&ch0);
735+ println!("order={} codebook={} lsb_bits={}", plan.coeffs.len(), plan.codebook, plan.lsb_bits);
736+ }
737+
738+ #[test]
739+ fn compression_ratio_gates() {
740+ let n = 19_200usize; // 120 access units at 192 kHz
741+ let raw_bytes = n * 2 * 3; // 2 channels, 24-bit/3-byte samples
742+
743+ let tonal = tone_fixture(n);
744+ let tonal_bytes = encoded_bytes(&tonal, 192_000);
745+ let tonal_ratio = tonal_bytes as f64 / raw_bytes as f64;
746+ assert!(
747+ tonal_ratio <= 0.65,
748+ "tonal: {tonal_bytes} bytes vs {raw_bytes} raw ({:.1}%), want <=65%",
749+ tonal_ratio * 100.0
750+ );
751+
752+ let noise = noise_fixture(n);
753+ let noise_bytes = encoded_bytes(&noise, 192_000);
754+ let noise_ratio = noise_bytes as f64 / raw_bytes as f64;
755+ assert!(
756+ noise_ratio <= 1.0,
757+ "noise: {noise_bytes} bytes vs {raw_bytes} raw ({:.1}%), want <=100%",
758+ noise_ratio * 100.0
759+ );
760+ }
419 }761 }