Welch-window the LPC autocorrelation
Browse files at this commit7e95468c700c1ca9cda276be6f6ef50a2fc29858Parent: 8073482- fix
- Welch-window the LPC autocorrelation
- carry FIR history across restarts
- amortize restart/major-sync/decoding-params per AU
2 changed files +213 -65
- crates/ec-truehd/src/decode.rs +20 -1
- crates/ec-truehd/src/encode.rs +193 -64
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`) draws | 72 | /// 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+193 -64
| @@ -42,11 +42,11 @@ use ec_core::frame::{ChannelLayout, Frame, SampleFormat}; | |||
| 42 | use ec_core::packet::Packet; | 42 | use ec_core::packet::Packet; |
| 43 | use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters}; | 43 | use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters}; |
| 44 | 44 | ||
| 45 | -use crate::decode::{restart_checksum, HUFFMAN_TABLES}; | 45 | +use crate::decode::{HUFFMAN_TABLES, MAX_FILTER_ORDER, restart_checksum}; |
| 46 | use crate::sync::MAJOR_SYNC_TRUEHD; | 46 | use crate::sync::MAJOR_SYNC_TRUEHD; |
| 47 | 47 | ||
| 48 | /// FIR order this encoder tries; matches `decode::MAX_FILTER_ORDER`. | 48 | /// FIR order this encoder tries; matches `decode::MAX_FILTER_ORDER`. |
| 49 | -const FILTER_ORDER: usize = 2; | 49 | +const FILTER_ORDER: usize = MAX_FILTER_ORDER; |
| 50 | /// Fixed-point scale (`accum >> FILTER_SHIFT`) the quantized coefficients | 50 | /// Fixed-point scale (`accum >> FILTER_SHIFT`) the quantized coefficients |
| 51 | /// are expressed in; mirrors `decode::filter_channel`'s `>> shift` exactly. | 51 | /// are expressed in; mirrors `decode::filter_channel`'s `>> shift` exactly. |
| 52 | const FILTER_SHIFT: u32 = 12; | 52 | const FILTER_SHIFT: u32 = 12; |
| @@ -59,9 +59,6 @@ const CODEBOOK: u8 = 2; | |||
| 59 | /// Below this many samples/channel, Levinson-Durbin's autocorrelation | 59 | /// Below this many samples/channel, Levinson-Durbin's autocorrelation |
| 60 | /// estimate is too noisy to be worth the filter-parameter overhead. | 60 | /// estimate is too noisy to be worth the filter-parameter overhead. |
| 61 | const MIN_SAMPLES_FOR_LPC: usize = 32; | 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 | 62 | ||
| 66 | /// A residual's sign-offset bias (`Substream::recompute_sign_offset`'s | 63 | /// A residual's sign-offset bias (`Substream::recompute_sign_offset`'s |
| 67 | /// formula with `huff_offset = 0`, `quant_step_size = 0`): the constant | 64 | /// formula with `huff_offset = 0`, `quant_step_size = 0`): the constant |
| @@ -121,9 +118,28 @@ fn choose_lsb_bits(residuals: &[i32]) -> Option<u32> { | |||
| 121 | } | 118 | } |
| 122 | 119 | ||
| 123 | /// Levinson-Durbin on `samples`' own autocorrelation: LPC coefficients | 120 | /// Levinson-Durbin on `samples`' own autocorrelation: LPC coefficients |
| 124 | -/// `a[1..=order]` such that `sample[n] ≈ Σ a[j] · sample[n - j]`. | 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]). | ||
| 125 | fn levinson_durbin(samples: &[i32], order: usize) -> Vec<f64> { | 128 | fn levinson_durbin(samples: &[i32], order: usize) -> Vec<f64> { |
| 126 | - let x: Vec<f64> = samples.iter().map(|&s| f64::from(s)).collect(); | 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(); | ||
| 127 | let mut r = vec![0.0f64; order + 1]; | 143 | let mut r = vec![0.0f64; order + 1]; |
| 128 | for (lag, slot) in r.iter_mut().enumerate() { | 144 | for (lag, slot) in r.iter_mut().enumerate() { |
| 129 | let mut s = 0.0; | 145 | let mut s = 0.0; |
| @@ -158,13 +174,14 @@ fn levinson_durbin(samples: &[i32], order: usize) -> Vec<f64> { | |||
| 158 | } | 174 | } |
| 159 | 175 | ||
| 160 | /// Integer residuals `sample[n] - (Σ coeffs[j] · history[j]) >> FILTER_SHIFT` | 176 | /// Integer residuals `sample[n] - (Σ coeffs[j] · history[j]) >> FILTER_SHIFT` |
| 161 | -/// over the channel's own past samples (most recent first) — the exact | 177 | +/// over the channel's own past samples (most recent first, seeded from |
| 162 | -/// inverse of `decode::filter_channel`'s reconstruction, with the same | 178 | +/// `hist_in` — see [`TrueHdEncoder::history`]) — the exact inverse of |
| 163 | -/// integer arithmetic (lossless coding: the decoder's filter state is | 179 | +/// `decode::filter_channel`'s reconstruction, with the same integer |
| 164 | -/// always the *real* sample, since `quant_step = 0` never masks a bit off). | 180 | +/// arithmetic (lossless coding: the decoder's filter state is always the |
| 165 | -fn fir_residuals(samples: &[i32], coeffs: &[i32]) -> Vec<i32> { | 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> { | ||
| 166 | let order = coeffs.len(); | 183 | let order = coeffs.len(); |
| 167 | - let mut hist = vec![0i32; order.max(1)]; | 184 | + let mut hist = *hist_in; |
| 168 | let mut out = Vec::with_capacity(samples.len()); | 185 | let mut out = Vec::with_capacity(samples.len()); |
| 169 | for &s in samples { | 186 | for &s in samples { |
| 170 | let mut accum: i64 = 0; | 187 | let mut accum: i64 = 0; |
| @@ -173,13 +190,11 @@ fn fir_residuals(samples: &[i32], coeffs: &[i32]) -> Vec<i32> { | |||
| 173 | } | 190 | } |
| 174 | let predict = (accum >> FILTER_SHIFT) as i32; | 191 | let predict = (accum >> FILTER_SHIFT) as i32; |
| 175 | out.push(s.wrapping_sub(predict)); | 192 | out.push(s.wrapping_sub(predict)); |
| 176 | - for j in (1..order).rev() { | 193 | + for j in (1..MAX_FILTER_ORDER).rev() { |
| 177 | hist[j] = hist[j - 1]; | 194 | hist[j] = hist[j - 1]; |
| 178 | } | 195 | } |
| 179 | - if order > 0 { | ||
| 180 | hist[0] = s; | 196 | hist[0] = s; |
| 181 | } | 197 | } |
| 182 | - } | ||
| 183 | out | 198 | out |
| 184 | } | 199 | } |
| 185 | 200 | ||
| @@ -215,13 +230,30 @@ impl ChannelPlan { | |||
| 215 | } | 230 | } |
| 216 | 231 | ||
| 217 | /// Chooses the cheaper of the raw path and an order-[`FILTER_ORDER`] | 232 | /// 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. | 233 | + /// LPC + codebook-2 path for one channel's samples in this AU. `analysis` |
| 219 | - fn choose(samples: &[i32]) -> ChannelPlan { | 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 { | ||
| 220 | let raw = ChannelPlan::raw(samples); | 244 | let raw = ChannelPlan::raw(samples); |
| 221 | if samples.len() < MIN_SAMPLES_FOR_LPC { | 245 | if samples.len() < MIN_SAMPLES_FOR_LPC { |
| 222 | return raw; | 246 | return raw; |
| 223 | } | 247 | } |
| 224 | - let a = levinson_durbin(samples, FILTER_ORDER); | 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); | ||
| 225 | let scale = f64::from(1u32 << FILTER_SHIFT); | 257 | let scale = f64::from(1u32 << FILTER_SHIFT); |
| 226 | let clamp_max = (1i32 << (COEFF_BITS - 1)) - 1; | 258 | let clamp_max = (1i32 << (COEFF_BITS - 1)) - 1; |
| 227 | let clamp_min = -(1i32 << (COEFF_BITS - 1)); | 259 | let clamp_min = -(1i32 << (COEFF_BITS - 1)); |
| @@ -229,28 +261,22 @@ impl ChannelPlan { | |||
| 229 | .iter() | 261 | .iter() |
| 230 | .map(|&c| ((c * scale).round() as i32).clamp(clamp_min, clamp_max)) | 262 | .map(|&c| ((c * scale).round() as i32).clamp(clamp_min, clamp_max)) |
| 231 | .collect(); | 263 | .collect(); |
| 232 | - let residuals = fir_residuals(samples, &coeffs); | 264 | + let residuals = fir_residuals(samples, &coeffs, &hist); |
| 233 | let Some(lsb_bits) = choose_lsb_bits(&residuals) else { | 265 | let Some(lsb_bits) = choose_lsb_bits(&residuals) else { |
| 234 | return raw; | 266 | return raw; |
| 235 | }; | 267 | }; |
| 236 | - eprintln!("DEBUG coeffs={coeffs:?} lsb_bits={lsb_bits}"); | 268 | + // The real bound (`decode::Substream::recompute_sign_offset`'s own |
| 237 | - // corner-cut: some access units this encoder tried (found by | 269 | + // `huff_lsbs > 24` check, `read_decoding_params`): codebook-2 |
| 238 | - // sweeping the ffmpeg oracle test bisecting on FIR order and this | 270 | + // residuals need `lsb_bits <= 24`. Round 1's empirical 12-bit cap |
| 239 | - // bound — order-independent, so not filter instability) decode | 271 | + // was masking a real bug (this crate's decoder — and this |
| 240 | - // wrong through ffmpeg while still round-tripping exactly through | 272 | + // encoder's own residual math — zeroed FIR/IIR predictor history |
| 241 | - // this crate's own decoder — a real divergence between the two | 273 | + // at every restart header; a real MLP/TrueHD stream, ffmpeg's |
| 242 | - // that this build could not pin down further inside its budget, | 274 | + // `mlpdec.c` `read_restart_header` included, only resets the |
| 243 | - // localized only to large residual fields (`lsb_bits` above this | 275 | + // *parameters* there and carries the history buffer across |
| 244 | - // bound). ffmpeg is the oracle: bounding `lsb_bits` here keeps | 276 | + // restarts), now fixed at the root (`decode::Core::read_restart_header` |
| 245 | - // every case this build measured (the 48 kHz tone+noise oracle | 277 | + // + this function's `hist` argument), so the format's real field |
| 246 | - // fixture, this crate's own round-trip fixtures, and both real | 278 | + // width is the only bound needed. |
| 247 | - // externally-encoded oracle files) on ffmpeg's bit-exact side. | 279 | + if lsb_bits > 24 { |
| 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; | 280 | return raw; |
| 255 | } | 281 | } |
| 256 | let sign_off = sign_offset(CODEBOOK, lsb_bits); | 282 | let sign_off = sign_offset(CODEBOOK, lsb_bits); |
| @@ -337,9 +363,39 @@ pub struct TrueHdEncoder { | |||
| 337 | /// folded from the access unit just written; `0` (unchecked by the | 363 | /// folded from the access unit just written; `0` (unchecked by the |
| 338 | /// decoder) before the first one. | 364 | /// decoder) before the first one. |
| 339 | 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])>, | ||
| 340 | eof: bool, | 390 | eof: bool, |
| 341 | } | 391 | } |
| 342 | 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 | + | ||
| 343 | impl TrueHdEncoder { | 399 | impl TrueHdEncoder { |
| 344 | /// An encoder for one 44.1/48 kHz-family stereo stream. | 400 | /// An encoder for one 44.1/48 kHz-family stereo stream. |
| 345 | pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> { | 401 | pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> { |
| @@ -372,6 +428,9 @@ impl TrueHdEncoder { | |||
| 372 | pending: Vec::new(), | 428 | pending: Vec::new(), |
| 373 | packets: VecDeque::new(), | 429 | packets: VecDeque::new(), |
| 374 | next_check: 0, | 430 | next_check: 0, |
| 431 | + analysis: [Vec::new(), Vec::new()], | ||
| 432 | + au_index: 0, | ||
| 433 | + last_params: None, | ||
| 375 | eof: false, | 434 | eof: false, |
| 376 | }) | 435 | }) |
| 377 | } | 436 | } |
| @@ -383,10 +442,71 @@ impl TrueHdEncoder { | |||
| 383 | let n = samples.len() / 2; | 442 | let n = samples.len() / 2; |
| 384 | debug_assert!(n <= self.access_unit_size); | 443 | debug_assert!(n <= self.access_unit_size); |
| 385 | 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 | + | ||
| 386 | let mut seg = BitWriter::new(); | 503 | let mut seg = BitWriter::new(); |
| 387 | - seg.write_bit(true); // params_present | 504 | + seg.write_bit(params_changed); // params_present |
| 388 | - seg.write_bit(true); // restart_present | ||
| 389 | 505 | ||
| 506 | + if params_changed { | ||
| 507 | + seg.write_bit(is_first); // restart_present | ||
| 508 | + | ||
| 509 | + if is_first { | ||
| 390 | seg.write_bits(RESTART_SYNC13, 13); | 510 | seg.write_bits(RESTART_SYNC13, 13); |
| 391 | seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it | 511 | seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it |
| 392 | seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder | 512 | seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder |
| @@ -404,6 +524,7 @@ impl TrueHdEncoder { | |||
| 404 | let bit_size = seg.bit_len() - 2; // restart_checksum's own convention | 524 | let bit_size = seg.bit_len() - 2; // restart_checksum's own convention |
| 405 | let crc = restart_checksum(seg.as_bytes(), bit_size); | 525 | let crc = restart_checksum(seg.as_bytes(), bit_size); |
| 406 | seg.write_bits(u32::from(crc), 8); | 526 | seg.write_bits(u32::from(crc), 8); |
| 527 | + } | ||
| 407 | 528 | ||
| 408 | seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default | 529 | seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default |
| 409 | seg.write_bit(true); // blocksize gate | 530 | seg.write_bit(true); // blocksize gate |
| @@ -411,27 +532,38 @@ impl TrueHdEncoder { | |||
| 411 | seg.write_bit(false); // matrix gate: keep 0 matrices | 532 | seg.write_bit(false); // matrix gate: keep 0 matrices |
| 412 | seg.write_bit(false); // output-shift gate: keep shift 0 | 533 | seg.write_bit(false); // output-shift gate: keep shift 0 |
| 413 | seg.write_bit(false); // quant-step gate: keep step 0 | 534 | seg.write_bit(false); // quant-step gate: keep step 0 |
| 535 | + } | ||
| 414 | 536 | ||
| 415 | - // De-interleave, then let each channel pick raw vs. LPC+codebook-2 | 537 | + // The decoder's predictor history is real output samples, pushed |
| 416 | - // independently (see `ChannelPlan::choose`). | 538 | + // every block regardless of the chosen order — advance the |
| 417 | - let plans: [ChannelPlan; 2] = [ | 539 | + // analysis window now so the *next* AU's `choose` sees this one's |
| 418 | - ChannelPlan::choose(&samples.iter().step_by(2).copied().collect::<Vec<_>>()), | 540 | + // actual samples. |
| 419 | - ChannelPlan::choose( | 541 | + for ch in 0..2 { |
| 420 | - &samples | 542 | + self.analysis[ch].extend_from_slice(&ch_samples[ch]); |
| 421 | - .iter() | 543 | + let len = self.analysis[ch].len(); |
| 422 | - .skip(1) | 544 | + if len > ANALYSIS_WINDOW { |
| 423 | - .step_by(2) | 545 | + self.analysis[ch].drain(..len - ANALYSIS_WINDOW); |
| 424 | - .copied() | 546 | + } |
| 425 | - .collect::<Vec<_>>(), | 547 | + } |
| 426 | - ), | ||
| 427 | - ]; | ||
| 428 | 548 | ||
| 549 | + if params_changed { | ||
| 429 | for plan in &plans { | 550 | for plan in &plans { |
| 430 | seg.write_bit(true); // per-channel gate | 551 | seg.write_bit(true); // per-channel gate |
| 431 | let order = plan.coeffs.len(); | 552 | let order = plan.coeffs.len(); |
| 432 | - seg.write_bit(order > 0); // FIR gate | 553 | + // FIR gate: always true, even for order 0 (the raw path). Once a |
| 433 | - if order > 0 { | 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 | ||
| 434 | seg.write_bits(order as u32, 4); | 565 | seg.write_bits(order as u32, 4); |
| 566 | + if order > 0 { | ||
| 435 | seg.write_bits(FILTER_SHIFT, 4); | 567 | seg.write_bits(FILTER_SHIFT, 4); |
| 436 | seg.write_bits(COEFF_BITS, 5); | 568 | seg.write_bits(COEFF_BITS, 5); |
| 437 | seg.write_bits(0, 3); // coeff_shift | 569 | seg.write_bits(0, 3); // coeff_shift |
| @@ -445,6 +577,7 @@ impl TrueHdEncoder { | |||
| 445 | seg.write_bits(u32::from(plan.codebook), 2); | 577 | seg.write_bits(u32::from(plan.codebook), 2); |
| 446 | seg.write_bits(plan.lsb_bits, 5); | 578 | seg.write_bits(plan.lsb_bits, 5); |
| 447 | } | 579 | } |
| 580 | + } | ||
| 448 | 581 | ||
| 449 | for i in 0..samples.len() { | 582 | for i in 0..samples.len() { |
| 450 | let plan = &plans[i % 2]; | 583 | let plan = &plans[i % 2]; |
| @@ -488,9 +621,10 @@ impl TrueHdEncoder { | |||
| 488 | major_sync[16] = 0x10; // num_substreams = 1 | 621 | major_sync[16] = 0x10; // num_substreams = 1 |
| 489 | let checksum = major_sync_checksum(&major_sync); | 622 | let checksum = major_sync_checksum(&major_sync); |
| 490 | 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 }; | ||
| 491 | let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word | 625 | let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word |
| 492 | 626 | ||
| 493 | - let total_len = 4 + major_sync.len() + 2 + seg_bytes.len(); | 627 | + let total_len = 4 + major_sync_len + 2 + seg_bytes.len(); |
| 494 | let len_words = (total_len as u16 / 2) & 0x0FFF; | 628 | let len_words = (total_len as u16 / 2) & 0x0FFF; |
| 495 | let dir_bytes = dir_word.to_be_bytes(); | 629 | let dir_bytes = dir_word.to_be_bytes(); |
| 496 | // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c, | 630 | // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c, |
| @@ -512,9 +646,12 @@ impl TrueHdEncoder { | |||
| 512 | let mut au = Vec::with_capacity(total_len); | 646 | let mut au = Vec::with_capacity(total_len); |
| 513 | au.extend_from_slice(&length_word.to_be_bytes()); | 647 | au.extend_from_slice(&length_word.to_be_bytes()); |
| 514 | au.extend_from_slice(&0u16.to_be_bytes()); // input_timing | 648 | au.extend_from_slice(&0u16.to_be_bytes()); // input_timing |
| 649 | + if is_first { | ||
| 515 | au.extend_from_slice(&major_sync); | 650 | au.extend_from_slice(&major_sync); |
| 651 | + } | ||
| 516 | au.extend_from_slice(&dir_bytes); | 652 | au.extend_from_slice(&dir_bytes); |
| 517 | au.extend_from_slice(&seg_bytes); | 653 | au.extend_from_slice(&seg_bytes); |
| 654 | + self.au_index += 1; | ||
| 518 | au | 655 | au |
| 519 | } | 656 | } |
| 520 | 657 | ||
| @@ -727,14 +864,6 @@ mod tests { | |||
| 727 | /// 24-bit PCM, and pure LCG noise (nothing for the predictor to | 864 | /// 24-bit PCM, and pure LCG noise (nothing for the predictor to |
| 728 | /// exploit) never grows past raw PCM's own size — the `ChannelPlan` | 865 | /// exploit) never grows past raw PCM's own size — the `ChannelPlan` |
| 729 | /// raw/LPC bit-cost comparison's whole job. | 866 | /// 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] | 867 | #[test] |
| 739 | fn compression_ratio_gates() { | 868 | fn compression_ratio_gates() { |
| 740 | let n = 19_200usize; // 120 access units at 192 kHz | 869 | let n = 19_200usize; // 120 access units at 192 kHz |