forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

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