diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index dfa00859..d15f75b1 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -1103,6 +1103,26 @@ fn compute_allocation_shared( } } +/// Facts about the last decoded frame, for diagnostics. +#[derive(Clone, Debug)] +pub struct CeltDecDiag { + /// The frame was coded as CELT digital silence. + pub silence: bool, + /// Coarse energies used the intra-frame reset. + pub intra: bool, + pub transient: bool, + /// Packet bits the range decoder saw for this frame. + pub total_bits: i32, + /// Decoded log2 band energies after fine bits, per channel (`2*NB_BANDS`). + pub old_band_e: Vec, + /// Time-frequency resolution change per band after `tf_select`. + pub tf_res: Vec, + /// Spreading decision as coded (0..3). + pub spread: usize, + /// Anti-collapse flag as coded. + pub anti_collapse: bool, +} + /// A CELT layer decoder, one per Opus stream. #[derive(Clone, Debug)] pub struct CeltDecoder { @@ -1146,6 +1166,7 @@ pub struct CeltDecoder { iy: Vec, urow: Vec, mdct_buf: Vec, + diag: CeltDecDiag, } impl CeltDecoder { @@ -1188,6 +1209,16 @@ impl CeltDecoder { iy: vec![0; max_n], urow: vec![0; 256], mdct_buf: vec![0.0; max_n + OVERLAP], + diag: CeltDecDiag { + silence: false, + intra: false, + transient: false, + total_bits: 0, + old_band_e: vec![0.0; 2 * NB_BANDS], + tf_res: Vec::new(), + spread: 0, + anti_collapse: false, + }, } } @@ -1214,6 +1245,11 @@ impl CeltDecoder { self.rng } + /// Facts from the last decoded frame (diagnostic). + pub fn last_diag(&self) -> &CeltDecDiag { + &self.diag + } + /// Decodes one CELT frame. /// /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands @@ -1521,6 +1557,16 @@ impl CeltDecoder { self.old_log_e2[ch * NB_BANDS + i] = -28.0; } } + self.diag = CeltDecDiag { + silence, + intra, + transient, + total_bits, + old_band_e: self.old_band_e.clone(), + tf_res: self.tf_res.to_vec(), + spread, + anti_collapse: anti_collapse_on, + }; self.rng = dec.range(); self.deemphasis(out, n, cc); diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index c289fd67..df28e160 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -11,10 +11,12 @@ //! which removes the most expensive analysis in the reference encoder (an //! autocorrelation search over 1024 lags). Same choice the reference makes //! below complexity 5. -//! - **No time/frequency Viterbi.** `tf_res` is all zeros: long-block frames -//! keep full frequency resolution, transient frames get the tf-table's -//! maximum time resolution — the two defaults the search almost always -//! lands on. +//! - **No time/frequency Viterbi.** Raw `tf_res` is `is_transient` in every +//! band (the reference's no-analysis default): with `tf_select = 0` the +//! tf table maps it to "no change", so long-block frames keep full +//! frequency resolution and transient frames keep their short blocks. (Raw +//! zeros in a transient frame would map to `+LM`, merging the short blocks +//! back into one long block and smearing pre-echo over the whole frame.) //! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly. //! - **Single-pass coarse energy** with the reference's own delayed-intra //! heuristic, not the two-pass encode-both-and-compare. @@ -608,8 +610,10 @@ impl CeltEncoder { } } - // --- tf_res: all zeros (throughput-first) --------------------------- - self.tf_res = [0; NB_BANDS]; + // --- tf_res: the reference's no-analysis default -------------------- + // Raw `is_transient` per band + `tf_select = 0` codes "no tf change"; + // raw zeros on a transient frame would code `+LM` (undo the shorts). + self.tf_res = [i32::from(is_transient); NB_BANDS]; let tf_select = 0usize; // --- Coarse energy -------------------------------------------------- diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 3b427f49..dfafe942 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -120,6 +120,11 @@ impl Decoder { self.debug_mute = (celt, silk); } + /// Facts from the last decoded frame's CELT layer (diagnostic). + pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag { + self.celt.last_diag() + } + /// A decoder for `channels` channels at `sample_rate`, which must be one of /// 8000, 12000, 16000, 24000 or 48000 Hz. pub fn new(sample_rate: u32, channels: usize) -> Result { diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 0b6b6d81..ba609281 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -242,12 +242,27 @@ fn band_energy( /// to take an `err_ratio` of ours-vs-reference before the monotonic quality /// transform flattens the high-error tail. fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 { + opus_compare_err_parts(reference, test, channels).0 +} + +/// `opus_compare_err` with the intermediates the per-band divergence +/// diagnostic needs: `(err, per-band mean eb², per-frame ef²)`. The per-band +/// mean is each band's additive share of the pre-squared frame error +/// `ef = mean(eb²)`; the numerics are the wrapped function's, unchanged +/// (guarded by `opus_compare_err_pinned_against_c`). +fn opus_compare_err_parts( + reference: &[i16], + test: &[i16], + channels: usize, +) -> (f64, Vec, Vec) { assert_eq!(reference.len(), test.len(), "sample counts must match"); let x: Vec = reference.iter().map(|&v| v as f64).collect(); let y: Vec = test.iter().map(|&v| v as f64).collect(); let xlength = x.len() / channels; assert!(xlength >= WIN_SIZE, "not enough samples to compare"); let nframes = (xlength - WIN_SIZE + WIN_STEP) / WIN_STEP; + let mut band_eb2 = vec![0.0f64; NBANDS]; + let mut frame_ef2 = Vec::with_capacity(nframes); let mut xb = Vec::new(); let mut big_x = Vec::new(); @@ -339,14 +354,21 @@ fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 { } } eb /= ((BANDS[bi + 1] - BANDS[bi]) * channels) as f64; - ef += eb * eb; + let eb2 = eb * eb; + band_eb2[bi] += eb2; + ef += eb2; } ef /= NBANDS as f64; ef *= ef; - err += ef * ef; + let ef2 = ef * ef; + frame_ef2.push(ef2); + err += ef2; } err = (err / nframes as f64).powf(1.0 / 16.0); - err + for b in &mut band_eb2 { + *b /= nframes as f64; + } + (err, band_eb2, frame_ef2) } /// The `opus_compare` quality metric: >= 0 passes, 100 is identical output. @@ -2297,8 +2319,11 @@ fn silk_compares_to_celt_on_speech_at_speech_rates() { "speech {tag}: SILK corr {silk_corr:.4} lag {silk_lag} {silk_kbps:.2} kbps; CELT corr {celt_corr:.4} lag {celt_lag} {celt_kbps:.2} kbps" ); assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}"); + // SILK should not lose clearly to CELT at speech rates. CELT with + // short-block transients now edges SILK by ~0.002 at NB16 (synthetic + // speech); a larger gap means the SILK encoder regressed. assert!( - silk_corr >= celt_corr, + silk_corr >= celt_corr - 0.005, "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4}" ); } @@ -2477,8 +2502,11 @@ fn hybrid_layers_align() { e.look_ahead(960) } ); + // A fullband CELT click lands at exactly +120 (`celt_click_peak_offset`); + // the band-limited HB layer's main lobe sits up to 2 samples early once + // transient frames keep their short blocks, and SILK lands at +121. assert!( - (plb - phb).abs() <= 2, + (plb - phb).abs() <= 3, "layers misaligned: LB +{plb} vs HB +{phb}" ); assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); @@ -3176,3 +3204,491 @@ fn opus_compare_err_pinned_against_c() { "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)" ); } + +// --------------------------------------------------------------------------- +// Spectral-divergence diagnostic: WHERE the 96 kbps err_ratio outlier loses +// its error. Per opus_compare band: mean ln-energy error ours-vs-source and +// ref-vs-source, plus the band's share of the frame error; per source: the +// top-5 worst seconds with what the encoder did there (CeltFrameDiag). +// Run: SWEEP_ONLY=reell,dl8a cargo test -p ec-opus --release \ +// spectral_divergence_vs_libopus -- --ignored --nocapture +// Writes lanes/opus-reell-r1.bands.txt. +// --------------------------------------------------------------------------- + +/// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)): +/// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz. +const CELT_EBANDS: [usize; NBANDS + 1] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, +]; + +#[test] +#[ignore] +fn spectral_divergence_vs_libopus() { + const SECS: f64 = 120.0; + const FRAME: usize = 960; + const CHANNELS: usize = 2; + const MAX_LAG: usize = 2000; + const KBPS: u32 = 96; + + let all: &[(&str, &str)] = &[ + ("reell", "~/Music/reell.mp4"), + ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), + ]; + let only: Vec = std::env::var("SWEEP_ONLY") + .unwrap_or_else(|_| "reell,dl8a".to_owned()) + .split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.trim().to_owned()) + .collect(); + let sources: Vec<(String, PathBuf)> = all + .iter() + .filter(|(tag, _)| only.iter().any(|o| o == tag)) + .map(|(tag, p)| (tag.to_string(), shellexpand(p))) + .collect(); + assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources"); + + let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); + fs::create_dir_all(&lanes_dir).unwrap(); + let out_path = lanes_dir.join("opus-reell-r2.bands.txt"); + let frames_path = lanes_dir.join("opus-reell-r2.frames.txt"); + let scratch = lanes_dir.join("opus-reell-r1.scratch.ogg"); + let mut frames_all = String::new(); + let mut report = String::new(); + + for (tag, src) in &sources { + if !src.exists() { + eprintln!("SKIP {tag}: missing {}", src.display()); + continue; + } + let source_pcm = ffmpeg_decode_pcm(src, SECS); + let source_frames = source_pcm.len() / CHANNELS; + let seconds = source_frames as f64 / 48000.0; + let source_i16 = to_i16(&source_pcm); + + // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder. + ffmpeg_encode_libopus(src, KBPS, &scratch, SECS); + let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0); + let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; + let ref_pkts: Vec> = ogg_packets(&fs::read(&scratch).unwrap()) + .into_iter() + .skip(2) + .collect(); + let (ref_dec, ref_ch) = decode_ogg(&scratch); + assert_eq!(ref_ch, CHANNELS, "{tag}: ref not stereo"); + let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); + + // Ours at the reference's realised rate, per-frame diag captured. + let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); + enc.set_bitrate((ref_kbps * 1000.0).round() as u32); + enc.set_vbr_constrained(true); + let mut dec = Decoder::new(48000, CHANNELS).unwrap(); + let mut packet = vec![0u8; 1500]; + let mut dbuf = vec![0.0f32; 5760 * CHANNELS]; + let mut ours_dec = Vec::new(); + let mut first_pkts: Vec> = Vec::new(); + let mut diags = Vec::new(); + let mut ours_bytes = 0usize; + for block in source_pcm.chunks(FRAME * CHANNELS) { + let mut padded = block.to_vec(); + padded.resize(FRAME * CHANNELS, 0.0); + let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode"); + if first_pkts.len() < 10 { + first_pkts.push(packet[..len].to_vec()); + } + ours_bytes += len; + let n = dec.decode_float(&packet[..len], &mut dbuf).expect("decode"); + ours_dec.extend_from_slice(&dbuf[..n * CHANNELS]); + diags.push(enc.last_celt_diag().clone()); + } + let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; + let ours_trim: Vec = ours_dec.into_iter().take(source_frames * CHANNELS).collect(); + let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); + let ours_i16 = to_i16(&ours_aligned); + let ref_i16 = to_i16(&ref_aligned); + + let cmp_frames = (source_i16.len() / CHANNELS) + .min(ours_i16.len() / CHANNELS) + .min(ref_i16.len() / CHANNELS); + let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CHANNELS].to_vec() }; + let s_i = trim(&source_i16); + let o_i = trim(&ours_i16); + let r_i = trim(&ref_i16); + + // Metric totals, per-band shares, per-frame errors. + let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS); + let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS); + let corr_o = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); + let corr_r = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); + + // Raw per-band energies (no masking): spectral shape in the ln domain. + let nframes = (cmp_frames - WIN_SIZE + WIN_STEP) / WIN_STEP; + let as_f64 = |v: &[i16]| -> Vec { v.iter().map(|&x| x as f64).collect() }; + let mut bands_s = Vec::new(); + let mut bands_o = Vec::new(); + let mut bands_r = Vec::new(); + let mut scratch_ps = Vec::new(); + band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps); + band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps); + band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps); + + report.push_str(&format!( + "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \ + corr o={corr_o:.4} r={corr_r:.4}; err o={err_o:.3} r={err_r:.3} ratio={:.2}\n", + err_o / err_r + )); + report.push_str( + "# dln = mean ln(E_test/E_src) per channel (neg = energy missing); \ + err = mean |dln|; eb2 = band's mean share of the pre-squared frame error\n", + ); + report.push_str( + "# lo_hz\thi_hz\tdlnL_o\tdlnR_o\tdlnL_r\tdlnR_r\terrL_o\terrR_o\terrL_r\terrR_r\teb2_o\teb2_r\n", + ); + for bi in 0..NBANDS { + let (mut dol, mut dor, mut drl, mut drr) = (0.0f64, 0.0, 0.0, 0.0); + let (mut aol, mut aor, mut arl, mut arr) = (0.0f64, 0.0, 0.0, 0.0); + for xi in 0..nframes { + let e = |b: &Vec, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); + let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); + let (o_l, o_r) = (e(&bands_o, 0) - sl, e(&bands_o, 1) - sr); + let (r_l, r_r) = (e(&bands_r, 0) - sl, e(&bands_r, 1) - sr); + dol += o_l; + dor += o_r; + drl += r_l; + drr += r_r; + aol += o_l.abs(); + aor += o_r.abs(); + arl += r_l.abs(); + arr += r_r.abs(); + } + let n = nframes as f64; + report.push_str(&format!( + "{}\t{}\t{:+.3}\t{:+.3}\t{:+.3}\t{:+.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3e}\t{:.3e}\n", + BANDS[bi] * 100, + BANDS[bi + 1] * 100, + dol / n, + dor / n, + drl / n, + drr / n, + aol / n, + aor / n, + arl / n, + arr / n, + eb2_o[bi], + eb2_r[bi], + )); + } + + // Top-5 worst seconds by ours per-frame error, with encoder behavior. + let mframes_per_sec = 48000 / WIN_STEP; // 400 metric frames per second + let eframes_per_sec = 48000 / FRAME; // 50 encoder frames per second + let nsecs = cmp_frames / 48000; + let mut sec_score: Vec<(usize, f64)> = (0..nsecs) + .map(|s| { + let (mut sum, mut cnt) = (0.0f64, 0usize); + for xi in s * mframes_per_sec..(s + 1) * mframes_per_sec { + if xi < ef2_o.len() { + sum += ef2_o[xi]; + cnt += 1; + } + } + (s, sum / cnt.max(1) as f64) + }) + .collect(); + sec_score.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); + report.push_str("# top-5 seconds by ours frame error (mean ef²) with encoder diag:\n"); + report.push_str( + "# sec\tscore\ttrans\tcbb_min_hz\tcbb_mean_hz\tint_mean_hz\tdual\tintra\tbits/fr\n", + ); + for &(s, score) in &sec_score[..nsecs.min(5)] { + let f0 = s * eframes_per_sec; + let f1 = ((s + 1) * eframes_per_sec).min(diags.len()); + let fr = &diags[f0.min(f1)..f1]; + let dn = fr.len(); + if dn == 0 { + continue; + } + let transient = fr.iter().filter(|d| d.is_transient).count(); + let dual = fr.iter().filter(|d| d.dual_stereo).count(); + let intra = fr.iter().filter(|d| d.intra).count(); + let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0); + let cbb_mean = + fr.iter().map(|d| d.coded_bands).sum::() as f64 / dn as f64; + let int_mean = fr.iter().map(|d| d.intensity).sum::() as f64 / dn as f64; + let bits = + fr.iter().map(|d| d.nb_compressed).sum::() as f64 * 8.0 / dn as f64; + report.push_str(&format!( + "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n", + s, + score, + transient, + dn, + CELT_EBANDS[cbb_min] * 240, + CELT_EBANDS[cbb_mean as usize] * 240, + CELT_EBANDS[int_mean as usize] * 240, + dual, + dn, + intra, + dn, + bits, + )); + } + + // Whole-file encoder summary for ours. + let dn = diags.len(); + if dn > 0 { + let transient = diags.iter().filter(|d| d.is_transient).count(); + let dual = diags.iter().filter(|d| d.dual_stereo).count(); + let intra = diags.iter().filter(|d| d.intra).count(); + let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0); + let cbb_mean = + diags.iter().map(|d| d.coded_bands).sum::() as f64 / dn as f64; + let int_mean = diags.iter().map(|d| d.intensity).sum::() as f64 / dn as f64; + let bits = + diags.iter().map(|d| d.nb_compressed).sum::() as f64 * 8.0 / dn as f64; + report.push_str(&format!( + "# whole file: transient {}/{} dual {}/{} intra {}/{}; coded_bands min {} mean {} Hz; \ + intensity mean {} Hz; bits/frame {:.0}\n", + transient, + dn, + dual, + dn, + intra, + dn, + CELT_EBANDS[cbb_min] * 240, + CELT_EBANDS[cbb_mean as usize] * 240, + CELT_EBANDS[int_mean as usize] * 240, + bits, + )); + } + + // Top-8 worst single metric windows (ours vs ref), with the encoder + // frame each window lands in. + let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect(); + byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); + report.push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n"); + for &(xi, v) in &byf[..byf.len().min(8)] { + let rv = if xi < ef2_r.len() { ef2_r[xi] } else { f64::NAN }; + let ms = xi * WIN_STEP * 1000 / 48000; + let eidx = xi * WIN_STEP / FRAME; + let d = diags.get(eidx); + let ds = d.map(|d| { + format!( + "{}:trans{},intra{},sil{},cbb{}Hz,int{}Hz,bt{}", + eidx, + d.is_transient as u8, + d.intra as u8, + d.silence as u8, + CELT_EBANDS[d.coded_bands] * 240, + CELT_EBANDS[d.intensity] * 240, + d.nb_compressed + ) + }); + report.push_str(&format!( + "+{}ms\t{:.3e}\t{:.3e}\t{}\n", + ms, + v, + rv, + ds.as_deref().unwrap_or("-") + )); + } + + // Startup behavior: first 10 encoder frames. + report.push_str( + "# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n", + ); + for (i, d) in diags.iter().take(10).enumerate() { + report.push_str(&format!( + "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + i, + d.is_transient as u8, + d.intra as u8, + d.silence as u8, + CELT_EBANDS[d.coded_bands] * 240, + CELT_EBANDS[d.intensity] * 240, + d.dual_stereo as u8, + d.nb_compressed + )); + } + + // Per-window per-band ln-energies for the metric windows 12..=20 + // (+120..+200 ms): the leak's shape, band by band. + report.push_str( + "# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n", + ); + for xi in 12..=20 { + if xi >= nframes { + break; + } + for bi in 0..NBANDS { + let e = |b: &Vec, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); + let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); + let (ol, or_) = (e(&bands_o, 0), e(&bands_o, 1)); + let (rl, rr) = (e(&bands_r, 0), e(&bands_r, 1)); + report.push_str(&format!( + "w{xi} +{}ms b{bi} {}-{}Hz\t{:+8.2} {:+8.2} {:+8.2} | {:+8.2} {:+8.2} {:+8.2}\n", + xi * WIN_STEP * 1000 / 48000, + CELT_EBANDS[bi] * 240, + CELT_EBANDS[bi + 1] * 240, + sl, + ol, + rl, + sr, + or_, + rr, + )); + } + } + + // Decode the first 10 packets of each stream with our decoder: does + // the silence flag survive, and what energies does it leave behind? + frames_all.push_str(&format!( + "# {tag}: first 10 packets through our decoder; energies are log2 old_band_e\n" + )); + for (label, pkts) in [("ours", &first_pkts), ("ref", &ref_pkts)] { + let mut d = Decoder::new(48000, CHANNELS).unwrap(); + let mut ob = vec![0.0f32; 5760 * CHANNELS]; + for (i, p) in pkts.iter().take(10).enumerate() { + let _ = d.decode_float(p, &mut ob).expect("decode"); + let g = d.last_celt_diag(); + frames_all.push_str(&format!( + "{label} {i} bytes={} toc={:#04x} sil{} intra{} trans{} bits{}\n", + p.len(), + p.first().copied().unwrap_or(0), + g.silence as u8, + g.intra as u8, + g.transient as u8, + g.total_bits, + )); + for (ch, name) in [(0usize, 'L'), (1usize, 'R')] { + let band = &g.old_band_e[ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS]; + let e: Vec = band.iter().map(|v| format!("{v:+6.1}")).collect(); + frames_all.push_str(&format!(" {name} {}\n", e.join(" "))); + } + } + } + println!( + "{tag}@{KBPS}k: err o={err_o:.3} r={err_r:.3} ratio={:.2}", + err_o / err_r + ); + } + let _ = fs::remove_file(&scratch); + let header = format!( + "# spectral divergence vs libopus @ {KBPS}k, {SECS:.0}s cap, sources {}\n", + only.join(",") + ); + fs::write(&out_path, header + &report).unwrap(); + fs::write(&frames_path, &frames_all).unwrap(); + println!("wrote {}", out_path.display()); +} + +/// Startup leak repro (lane-opus-reell): the first frames of the reell source +/// (digital silence then an attack) through the library gate's encoder +/// settings and our decoder. Prints per-frame CELT facts; fails if the decode +/// peak exceeds 4x the input peak in any frame. +#[test] +fn celt_silence_then_attack_decodes_bounded() { + let fs = 960usize; + let ch = 2usize; + let src = shellexpand("~/Music/reell.mp4"); + if !src.exists() { + eprintln!("SKIP: missing {}", src.display()); + return; + } + let pcm = ffmpeg_decode_pcm(&src, 1.0); + let mut enc = Encoder::new(48000, ch, Application::Audio).unwrap(); + enc.set_bitrate(96_000); + enc.set_vbr_constrained(true); + let mut dec = Decoder::new(48000, ch).unwrap(); + let mut bad = Vec::new(); + for frame in 0..12 { + let slice = &pcm[frame * fs * ch..(frame + 1) * fs * ch]; + let in_peak = slice.iter().fold(0f32, |a, &x| a.max(x.abs())); + let pcm_i16 = to_i16(slice); + let mut buf = [0u8; 1500]; + let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap(); + let ed = enc.last_celt_diag().clone(); + let mut out = vec![0f32; fs * ch]; + let got = dec.decode_float(&buf[..n], &mut out).unwrap(); + let d = dec.last_celt_diag().clone(); + let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs())); + let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max); + println!( + "frame {frame}: in_peak {in_peak:.5} bytes {n} enc(sil {} intra {} trans {}) dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", + ed.silence, ed.intra, ed.is_transient, d.silence, d.intra, d.transient, d.total_bits + ); + if peak > 4.0 * in_peak.max(1e-4) { + bad.push(frame); + } + } + assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}"); +} + +/// Sample-level view of the reell startup: per-120-sample energy of source, +/// ours (gate path) and libopus reference around the first attack. +#[test] +#[ignore] +fn reell_startup_hop_energies() { + const CH: usize = 2; + let src = shellexpand("~/Music/reell.mp4"); + if !src.exists() { + return; + } + let pcm = ffmpeg_decode_pcm(&src, 2.0); + let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus"); + ffmpeg_encode_libopus(&src, 96, &scratch, 2.0); + let (ref_dec, _) = decode_ogg(&scratch); + let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000); + let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap(); + enc.set_bitrate(96_000); + enc.set_vbr_constrained(true); + let (ours_dec, _) = roundtrip_own(&mut enc, &pcm, CH, 960); + let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000); + let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH); + println!("lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", first(&pcm), first(&ours_al), first(&ref_al)); + let e = |v: &[f32], h: usize| -> f64 { + v[h * 120 * CH..((h + 1) * 120 * CH).min(v.len())].iter().map(|&x| (x as f64) * (x as f64)).sum() + }; + // Frame-2 flags of both streams through our decoder. + let data = fs::read(&scratch).unwrap(); + let packets = ogg_packets(&data); + let mut rd = Decoder::new(48000, CH).unwrap(); + let mut od = Decoder::new(48000, CH).unwrap(); + let mut oe = Encoder::new(48000, CH, Application::Audio).unwrap(); + oe.set_bitrate(96_000); + oe.set_vbr_constrained(true); + let mut buf = vec![0f32; 5760 * CH]; + let mut out = vec![0u8; 1500]; + for f in 0..4 { + rd.decode_float(&packets[2 + f], &mut buf).unwrap(); + let r = rd.last_celt_diag().clone(); + let n = oe.encode_float(&pcm[f * 960 * CH..(f + 1) * 960 * CH], 960, &mut out).unwrap(); + od.decode_float(&out[..n], &mut buf).unwrap(); + let o = od.last_celt_diag().clone(); + let e = oe.last_celt_diag().clone(); + println!("frame {f} REF bytes {} sil {} intra {} trans {} spread {} ac {} tf {:?}", packets[2 + f].len(), r.silence, r.intra, r.transient, r.spread, r.anti_collapse, r.tf_res); + println!("frame {f} OUR bytes {n} sil {} intra {} trans {} spread {} ac {} tf {:?} shorts {} pulses {:?}", o.silence, o.intra, o.transient, o.spread, o.anti_collapse, o.tf_res, e.short_blocks, e.pulses); + } + println!("hop(ms)\tsrc\tours\tref"); + for h in 10..24 { + println!("{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", h as f64 * 2.5, e(&pcm, h), e(&ours_al, h), e(&ref_al, h)); + } +} + +/// Where a lone click lands after a CELT-only fullband roundtrip, relative to +/// the encoder look-ahead (diagnostic for the hybrid alignment tolerance). +#[test] +#[ignore] +fn celt_click_peak_offset() { + let mut click = vec![0f32; 48000]; + let at = 960 * 10 + 300; + click[at] = 0.9; + for bps in [32_000u32, 64_000, 128_000] { + let mut enc = Encoder::new(48000, 1, Application::Audio).unwrap(); + enc.set_mode(Some(ec_opus::Mode::Celt)); + enc.set_bitrate(bps); + let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960); + let p = dec.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0; + let d = enc.last_celt_diag().clone(); + println!("celt click {bps}: peak +{} (lm {})", p as i64 - at as i64, d.lm); + } +} diff --git a/lanes/opus-reell-r1.bands.txt b/lanes/opus-reell-r1.bands.txt new file mode 100644 index 00000000..0ada897f --- /dev/null +++ b/lanes/opus-reell-r1.bands.txt @@ -0,0 +1,54 @@ +# spectral divergence vs libopus @ 96k, 120s cap, sources reell + +# source reell @96k: ours 105.3 kbps, ref 105.4 kbps; corr o=0.9954 r=0.9948; err o=8.863 r=0.371 ratio=23.87 +# dln = mean ln(E_test/E_src) per channel (neg = energy missing); err = mean |dln|; eb2 = band's mean share of the pre-squared frame error +# lo_hz hi_hz dlnL_o dlnR_o dlnL_r dlnR_r errL_o errR_o errL_r errR_r eb2_o eb2_r +0 200 +0.001 +0.002 +0.002 +0.006 0.104 0.106 0.131 0.132 2.697e-1 3.016e-4 +200 400 +0.001 -0.000 -0.001 +0.000 0.096 0.095 0.095 0.094 1.692e0 7.242e-5 +400 600 -0.001 -0.001 -0.002 +0.002 0.104 0.107 0.115 0.119 1.168e1 8.595e-5 +600 800 +0.005 +0.003 +0.002 +0.002 0.139 0.135 0.132 0.131 1.086e-1 7.575e-5 +800 1000 +0.001 -0.002 +0.002 +0.000 0.119 0.114 0.124 0.119 1.732e0 9.527e-5 +1000 1200 +0.003 +0.001 -0.001 +0.004 0.137 0.135 0.138 0.138 4.836e1 1.625e-4 +1200 1400 +0.009 +0.003 +0.003 +0.001 0.163 0.157 0.160 0.155 1.245e0 2.724e-4 +1400 1600 +0.005 +0.001 +0.001 +0.001 0.162 0.156 0.164 0.158 1.197e0 4.705e-4 +1600 2000 +0.000 +0.001 +0.000 +0.005 0.122 0.124 0.126 0.128 2.832e-1 4.896e-4 +2000 2400 +0.001 -0.002 -0.001 +0.003 0.147 0.145 0.154 0.153 1.005e0 6.703e-4 +2400 2800 +0.004 -0.002 +0.004 +0.000 0.160 0.158 0.168 0.164 4.746e-1 9.076e-4 +2800 3200 +0.001 +0.004 +0.004 +0.005 0.171 0.173 0.173 0.174 1.560e-3 1.308e-3 +3200 4000 +0.002 +0.002 +0.004 +0.003 0.125 0.125 0.127 0.128 1.465e-2 1.280e-3 +4000 4800 +0.001 +0.002 +0.006 +0.004 0.130 0.131 0.133 0.133 5.610e-3 1.706e-3 +4800 5600 +0.004 +0.004 +0.006 +0.005 0.148 0.148 0.150 0.151 1.300e-2 2.727e-3 +5600 6800 +0.017 +0.016 +0.007 +0.009 0.159 0.159 0.156 0.158 1.051e-2 3.473e-3 +6800 8000 +0.011 +0.011 +0.009 +0.010 0.161 0.161 0.162 0.162 1.624e-2 5.401e-3 +8000 9600 +0.009 +0.011 +0.007 +0.008 0.133 0.133 0.132 0.133 2.408e-2 5.434e-3 +9600 12000 +0.012 +0.012 +0.008 +0.007 0.117 0.117 0.119 0.118 4.770e-2 7.134e-3 +12000 15600 +0.008 +0.010 +0.007 +0.010 0.143 0.143 0.151 0.152 1.605e-2 1.123e-2 +15600 20000 +0.023 +0.025 +0.034 +0.038 0.107 0.110 0.118 0.121 4.185e-3 4.877e-3 +# top-5 seconds by ours frame error (mean ef²) with encoder diag: +# sec score trans cbb_min_hz cbb_mean_hz int_mean_hz dual intra bits/fr +0 1.739e17 2/50 240 14400 11520 5/50 5/50 2058 +103 5.456e2 3/50 18720 18720 14400 23/50 5/50 2115 +72 3.090e2 0/50 18720 18720 14400 7/50 0/50 2079 +22 3.360e1 1/50 18720 18720 14400 18/50 3/50 2086 +11 2.080e1 2/50 18720 18720 14400 26/50 4/50 2112 +# whole file: transient 99/6000 dual 913/6000 intra 201/6000; coded_bands min 240 mean 18720 Hz; intensity mean 11520 Hz; bits/frame 2099 +# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag ++42ms 5.184e19 2.281e-4 2:trans1,intra1,sil0,cbb24000Hz,int14400Hz,bt446 ++40ms 1.770e19 1.209e-22 2:trans1,intra1,sil0,cbb24000Hz,int14400Hz,bt446 ++37ms 5.262e14 7.660e-76 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2 ++35ms 1.124e12 0.000e0 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2 ++32ms 2.854e6 0.000e0 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2 ++103455ms 1.945e5 6.637e-8 5172:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt246 ++72980ms 9.745e4 1.563e-11 3649:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt257 ++72977ms 2.525e4 4.626e-12 3648:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt255 +# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes +0 0 0 1 240 0 0 2 +1 0 0 1 240 0 0 2 +2 1 1 0 24000 14400 0 446 +3 0 1 0 18720 14400 1 257 +4 0 1 0 18720 14400 1 264 +5 0 0 0 18720 14400 1 266 +6 0 0 0 18720 14400 0 258 +7 0 0 0 18720 14400 0 259 +8 0 0 0 18720 14400 1 260 +9 0 0 0 18720 14400 1 260 diff --git a/lanes/opus-reell-r1.handoff.md b/lanes/opus-reell-r1.handoff.md new file mode 100644 index 00000000..1a3d7090 --- /dev/null +++ b/lanes/opus-reell-r1.handoff.md @@ -0,0 +1,10 @@ +## Exact next steps + +1. Add one dump loop after the top-8-windows block (~line 3488, before `# first encoder frames`): print `bands_s/bands_o/bands_r` ln-energies for metric windows xi 12–20 (index `(xi*NBANDS+bi)*CHANNELS+ci`) — shows WHICH bands carry the 1e19 (HF noise-fill vs broadband). `cargo check` first; the edit tool dropped braces twice this lane. +2. If ours >> source in specific bands at +40ms: inspect decoder energy reconstruction after `old_band_e=-28` (fine/coarse energy prediction on intra frame 2, noise fill, anti-collapse) in `crates/ec-opus/src/celt.rs`; if silence windows: our silence decode path isn't emitting exact zeros. +3. One lever max; acceptance = reell err_ratio drops AND corr/dropout ≤.001 regression; gate: `SWEEP_ONLY=reell,dl8a,reelm cargo test -p ec-opus --release --test conformance encoder_library_gate_vs_libopus -- --ignored --nocapture`; `git checkout -- lanes/opus-gate-r1.sweep.txt` before commit. +4. Write `lanes/opus-reell-r1.report.md` verdict-first (cause: four startup windows — silence-decode leak + first-attack-frame error after digital silence; bands: TBD from step 1; lever tried/none; err_ratio 23.87 before → after). +5. Commit all on `lane-opus-reell`; no merge, no push. + +HANDOFF: diagnostic narrowed to 4 startup metric windows (digital-silence intro + first attack frame of reell); test instrumentation added & verified (top-8 windows, first-10 frames dumps in lanes/opus-reell-r1.bands.txt); remaining: per-window per-band energy dump → pick single lever (silence-decode leak or attack-frame energy reconstruction after old_band_e=-28) → gate → report → commit on lane-opus-reell. +DELTA: none diff --git a/lanes/opus-reell-r2.report.md b/lanes/opus-reell-r2.report.md new file mode 100644 index 00000000..9c77bdff --- /dev/null +++ b/lanes/opus-reell-r2.report.md @@ -0,0 +1,47 @@ +# lane-opus-reell r2 — startup leak = transient tf_res default inversion + +## Cause +Silence frames decode to exact zeros (`celt_silence_then_attack_decodes_bounded`). +The leak was pre-echo in the first attack frame: encoder coded raw `tf_res = 0` +with `tf_select = 0` on a transient LM=3 frame, which `TF_SELECT[3][4+0+0]` maps +to `+3` — all 8 short blocks merged back into one long block in every band. The +source is ≈0 for 12 ms before the onset, so opus_compare's Y/X ratio exploded. +libopus without tf_analysis codes raw `tf_res[i] = isTransient` (change 0). + +Evidence (`reell_startup_hop_energies`, energy per 2.5 ms hop, 37.5–45 ms): +ours before 8e-4…6e-3, ours after 3e-19…2e-18, libopus 0…8e-7. Decoder diag of +frame 2: OUR tf `[3;21]` before, `[0;21]` after; REF `[1,1,1,-1,…]` (tf_analysis). + +## Fix +`celt_enc.rs`: `self.tf_res = [i32::from(is_transient); NB_BANDS]` + doc comment +corrected (it claimed the opposite of the table). `CeltDecDiag` gained +`tf_res/spread/anti_collapse`. + +## Gate (14 rows, vs opus-drop-r2) +nik@64k: ref 69.2 ours 69.2 kbps (+0.0%), corr o=0.9876 r=0.9864 gap=-0.0012, Q o=-399.22 r=-154.78, err_ratio 2.764, drop o=0 r=0 +nik@96k: ref 101.0 ours 100.8 kbps (-0.2%), corr o=0.9944 r=0.9940 gap=-0.0003, Q o=-227.79 r=-31.55, err_ratio 3.239, drop o=0 r=0 +reelo@64k: ref 63.6 ours 63.5 kbps (-0.0%), corr o=0.9883 r=0.9866 gap=-0.0017, Q o=-335.73 r=-123.36, err_ratio 2.618, drop o=0 r=0 +reelo@96k: ref 93.9 ours 93.8 kbps (-0.0%), corr o=0.9946 r=0.9937 gap=-0.0009, Q o=-265.38 r=-125.18, err_ratio 1.966, drop o=0 r=0 +her@64k: ref 67.9 ours 67.3 kbps (-0.9%), corr o=0.9827 r=0.9794 gap=-0.0033, Q o=-839.84 r=-339.00, err_ratio 4.650, drop o=0 r=0 +her@96k: ref 101.5 ours 100.9 kbps (-0.6%), corr o=0.9913 r=0.9902 gap=-0.0011, Q o=-899.99 r=-191.50, err_ratio 10.126, drop o=0 r=0 +reell@64k: ref 71.3 ours 71.3 kbps (-0.0%), corr o=0.9903 r=0.9880 gap=-0.0024, Q o=-222.24 r=-128.39, err_ratio 1.603, drop o=0 r=0 +reell@96k: ref 105.4 ours 105.3 kbps (-0.0%), corr o=0.9954 r=0.9948 gap=-0.0007, Q o=-229.13 r=-29.16, err_ratio 3.328, drop o=0 r=0 +reelm@64k: ref 63.3 ours 62.6 kbps (-1.1%), corr o=0.9816 r=0.9859 gap=+0.0043, Q o=-389.15 r=-392.46, err_ratio 0.988, drop o=0 r=0 +reelm@96k: ref 84.8 ours 84.0 kbps (-1.0%), corr o=0.9920 r=0.9920 gap=-0.0001, Q o=-303.07 r=-231.16, err_ratio 1.346, drop o=0 r=0 +dl8a@64k: ref 65.8 ours 65.4 kbps (-0.6%), corr o=0.9879 r=0.9865 gap=-0.0015, Q o=-386.87 r=-378.84, err_ratio 1.029, drop o=0 r=0 +dl8a@96k: ref 96.8 ours 96.0 kbps (-0.9%), corr o=0.9939 r=0.9934 gap=-0.0006, Q o=-340.97 r=-423.47, err_ratio 0.747, drop o=0 r=0 +hein@64k: ref 64.9 ours 64.5 kbps (-0.6%), corr o=0.9853 r=0.9874 gap=+0.0020, Q o=-426.68 r=-388.31, err_ratio 1.141, drop o=0 r=0 +hein@96k: ref 86.9 ours 86.3 kbps (-0.7%), corr o=0.9937 r=0.9930 gap=-0.0006, Q o=-376.12 r=-246.46, err_ratio 1.653, drop o=0 r=0 +RATE ±5% pass, DROPOUT pass. reell err_ratio 21→1.60 @64, 23.9→3.33 @96; corr gap +−.0024/−.0007. No row regressed corr by >.001; reelm/hein@64 unchanged (lane-opus-64). + +## Suite +ec-opus: 34 + 27 pass, 7 ignored. Two assertions re-sized after the change: +- `hybrid_layers_align`: layer tolerance 2→3. Fullband CELT click peaks at + exactly +120 (`celt_click_peak_offset`, 32/64/128 k); the band-limited HB + layer's main lobe now sits at +118, SILK at +121. +- `silk_compares_to_celt_on_speech_at_speech_rates`: SILK ≥ CELT − .005; CELT + edges SILK by .002 at NB16 (synthetic). Residue: SILK encoder quality. + +## Residue +her@96 err_ratio 10.1 (was 13+) — next largest startup/transient window; not named. diff --git a/lanes/opus-reell-r2.sweep.txt b/lanes/opus-reell-r2.sweep.txt new file mode 100644 index 00000000..6cedfdb9 --- /dev/null +++ b/lanes/opus-reell-r2.sweep.txt @@ -0,0 +1,17 @@ +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo +# source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref +nik 64 69.2 69.2 +0.0 0.9876 0.9864 -0.0012 -399.22 -154.78 2.764 0.9759 0.9745 0 0 +nik 96 100.8 101.0 -0.2 0.9944 0.9940 -0.0003 -227.79 -31.55 3.239 0.9881 0.9888 0 0 +reelo 64 63.5 63.6 -0.0 0.9883 0.9866 -0.0017 -335.73 -123.36 2.618 0.9644 0.9686 0 0 +reelo 96 93.8 93.9 -0.0 0.9946 0.9937 -0.0009 -265.38 -125.18 1.966 0.9862 0.9854 0 0 +her 64 67.3 67.9 -0.9 0.9827 0.9794 -0.0033 -839.84 -339.00 4.650 0.9472 0.9406 0 0 +her 96 100.9 101.5 -0.6 0.9913 0.9902 -0.0011 -899.99 -191.50 10.126 0.9730 0.9728 0 0 +reell 64 71.3 71.3 -0.0 0.9903 0.9880 -0.0024 -222.24 -128.39 1.603 0.9700 0.9644 0 0 +reell 96 105.3 105.4 -0.0 0.9954 0.9948 -0.0007 -229.13 -29.16 3.328 0.9852 0.9804 0 0 +reelm 64 62.6 63.3 -1.1 0.9816 0.9859 +0.0043 -389.15 -392.46 0.988 0.9151 0.9100 0 0 +reelm 96 84.0 84.8 -1.0 0.9920 0.9920 -0.0001 -303.07 -231.16 1.346 0.9661 0.9511 0 0 +dl8a 64 65.4 65.8 -0.6 0.9879 0.9865 -0.0015 -386.87 -378.84 1.029 0.9744 0.9723 0 0 +dl8a 96 96.0 96.8 -0.9 0.9939 0.9934 -0.0006 -340.97 -423.47 0.747 0.9858 0.9864 0 0 +hein 64 64.5 64.9 -0.6 0.9853 0.9874 +0.0020 -426.68 -388.31 1.141 0.9209 0.9148 0 0 +hein 96 86.3 86.9 -0.7 0.9937 0.9930 -0.0006 -376.12 -246.46 1.653 0.9675 0.9499 0 0