forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-opus-reell': transient frames keep short blocks

Browse files at this commit

63753b87d89b9d8ebfef1732e5fcd442037258e1Ahmet Kaan GümüşParent: 6828b155b61429
crates/ec-opus/src/celt.rsmodified+46 -0
@@ -1103,6 +1103,26 @@ fn compute_allocation_shared(
1103 }1103 }
1104 }1104 }
1105 1105
1106+/// Facts about the last decoded frame, for diagnostics.
1107+#[derive(Clone, Debug)]
1108+pub struct CeltDecDiag {
1109+ /// The frame was coded as CELT digital silence.
1110+ pub silence: bool,
1111+ /// Coarse energies used the intra-frame reset.
1112+ pub intra: bool,
1113+ pub transient: bool,
1114+ /// Packet bits the range decoder saw for this frame.
1115+ pub total_bits: i32,
1116+ /// Decoded log2 band energies after fine bits, per channel (`2*NB_BANDS`).
1117+ pub old_band_e: Vec<f32>,
1118+ /// Time-frequency resolution change per band after `tf_select`.
1119+ pub tf_res: Vec<i32>,
1120+ /// Spreading decision as coded (0..3).
1121+ pub spread: usize,
1122+ /// Anti-collapse flag as coded.
1123+ pub anti_collapse: bool,
1124+}
1125+
1106 /// A CELT layer decoder, one per Opus stream.1126 /// A CELT layer decoder, one per Opus stream.
1107 #[derive(Clone, Debug)]1127 #[derive(Clone, Debug)]
1108 pub struct CeltDecoder {1128 pub struct CeltDecoder {
@@ -1146,6 +1166,7 @@ pub struct CeltDecoder {
1146 iy: Vec<i32>,1166 iy: Vec<i32>,
1147 urow: Vec<u32>,1167 urow: Vec<u32>,
1148 mdct_buf: Vec<f32>,1168 mdct_buf: Vec<f32>,
1169+ diag: CeltDecDiag,
1149 }1170 }
1150 1171
1151 impl CeltDecoder {1172 impl CeltDecoder {
@@ -1188,6 +1209,16 @@ impl CeltDecoder {
1188 iy: vec![0; max_n],1209 iy: vec![0; max_n],
1189 urow: vec![0; 256],1210 urow: vec![0; 256],
1190 mdct_buf: vec![0.0; max_n + OVERLAP],1211 mdct_buf: vec![0.0; max_n + OVERLAP],
1212+ diag: CeltDecDiag {
1213+ silence: false,
1214+ intra: false,
1215+ transient: false,
1216+ total_bits: 0,
1217+ old_band_e: vec![0.0; 2 * NB_BANDS],
1218+ tf_res: Vec::new(),
1219+ spread: 0,
1220+ anti_collapse: false,
1221+ },
1191 }1222 }
1192 }1223 }
1193 1224
@@ -1214,6 +1245,11 @@ impl CeltDecoder {
1214 self.rng1245 self.rng
1215 }1246 }
1216 1247
1248+ /// Facts from the last decoded frame (diagnostic).
1249+ pub fn last_diag(&self) -> &CeltDecDiag {
1250+ &self.diag
1251+ }
1252+
1217 /// Decodes one CELT frame.1253 /// Decodes one CELT frame.
1218 ///1254 ///
1219 /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands1255 /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands
@@ -1521,6 +1557,16 @@ impl CeltDecoder {
1521 self.old_log_e2[ch * NB_BANDS + i] = -28.0;1557 self.old_log_e2[ch * NB_BANDS + i] = -28.0;
1522 }1558 }
1523 }1559 }
1560+ self.diag = CeltDecDiag {
1561+ silence,
1562+ intra,
1563+ transient,
1564+ total_bits,
1565+ old_band_e: self.old_band_e.clone(),
1566+ tf_res: self.tf_res.to_vec(),
1567+ spread,
1568+ anti_collapse: anti_collapse_on,
1569+ };
1524 self.rng = dec.range();1570 self.rng = dec.range();
1525 1571
1526 self.deemphasis(out, n, cc);1572 self.deemphasis(out, n, cc);
crates/ec-opus/src/celt_enc.rsmodified+10 -6
@@ -11,10 +11,12 @@
11 //! which removes the most expensive analysis in the reference encoder (an11 //! which removes the most expensive analysis in the reference encoder (an
12 //! autocorrelation search over 1024 lags). Same choice the reference makes12 //! autocorrelation search over 1024 lags). Same choice the reference makes
13 //! below complexity 5.13 //! below complexity 5.
14-//! - **No time/frequency Viterbi.** `tf_res` is all zeros: long-block frames14+//! - **No time/frequency Viterbi.** Raw `tf_res` is `is_transient` in every
15-//! keep full frequency resolution, transient frames get the tf-table's15+//! band (the reference's no-analysis default): with `tf_select = 0` the
16-//! maximum time resolution — the two defaults the search almost always16+//! tf table maps it to "no change", so long-block frames keep full
17-//! lands on.17+//! frequency resolution and transient frames keep their short blocks. (Raw
18+//! zeros in a transient frame would map to `+LM`, merging the short blocks
19+//! back into one long block and smearing pre-echo over the whole frame.)
18 //! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly.20 //! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly.
19 //! - **Single-pass coarse energy** with the reference's own delayed-intra21 //! - **Single-pass coarse energy** with the reference's own delayed-intra
20 //! heuristic, not the two-pass encode-both-and-compare.22 //! heuristic, not the two-pass encode-both-and-compare.
@@ -608,8 +610,10 @@ impl CeltEncoder {
608 }610 }
609 }611 }
610 612
611- // --- tf_res: all zeros (throughput-first) ---------------------------613+ // --- tf_res: the reference's no-analysis default --------------------
612- self.tf_res = [0; NB_BANDS];614+ // Raw `is_transient` per band + `tf_select = 0` codes "no tf change";
615+ // raw zeros on a transient frame would code `+LM` (undo the shorts).
616+ self.tf_res = [i32::from(is_transient); NB_BANDS];
613 let tf_select = 0usize;617 let tf_select = 0usize;
614 618
615 // --- Coarse energy --------------------------------------------------619 // --- Coarse energy --------------------------------------------------
crates/ec-opus/src/lib.rsmodified+5 -0
@@ -120,6 +120,11 @@ impl Decoder {
120 self.debug_mute = (celt, silk);120 self.debug_mute = (celt, silk);
121 }121 }
122 122
123+ /// Facts from the last decoded frame's CELT layer (diagnostic).
124+ pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag {
125+ self.celt.last_diag()
126+ }
127+
123 /// A decoder for `channels` channels at `sample_rate`, which must be one of128 /// A decoder for `channels` channels at `sample_rate`, which must be one of
124 /// 8000, 12000, 16000, 24000 or 48000 Hz.129 /// 8000, 12000, 16000, 24000 or 48000 Hz.
125 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {130 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
crates/ec-opus/tests/conformance.rsmodified+521 -5
@@ -242,12 +242,27 @@ fn band_energy(
242 /// to take an `err_ratio` of ours-vs-reference before the monotonic quality242 /// to take an `err_ratio` of ours-vs-reference before the monotonic quality
243 /// transform flattens the high-error tail.243 /// transform flattens the high-error tail.
244 fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 {244 fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 {
245+ opus_compare_err_parts(reference, test, channels).0
246+}
247+
248+/// `opus_compare_err` with the intermediates the per-band divergence
249+/// diagnostic needs: `(err, per-band mean eb², per-frame ef²)`. The per-band
250+/// mean is each band's additive share of the pre-squared frame error
251+/// `ef = mean(eb²)`; the numerics are the wrapped function's, unchanged
252+/// (guarded by `opus_compare_err_pinned_against_c`).
253+fn opus_compare_err_parts(
254+ reference: &[i16],
255+ test: &[i16],
256+ channels: usize,
257+) -> (f64, Vec<f64>, Vec<f64>) {
245 assert_eq!(reference.len(), test.len(), "sample counts must match");258 assert_eq!(reference.len(), test.len(), "sample counts must match");
246 let x: Vec<f64> = reference.iter().map(|&v| v as f64).collect();259 let x: Vec<f64> = reference.iter().map(|&v| v as f64).collect();
247 let y: Vec<f64> = test.iter().map(|&v| v as f64).collect();260 let y: Vec<f64> = test.iter().map(|&v| v as f64).collect();
248 let xlength = x.len() / channels;261 let xlength = x.len() / channels;
249 assert!(xlength >= WIN_SIZE, "not enough samples to compare");262 assert!(xlength >= WIN_SIZE, "not enough samples to compare");
250 let nframes = (xlength - WIN_SIZE + WIN_STEP) / WIN_STEP;263 let nframes = (xlength - WIN_SIZE + WIN_STEP) / WIN_STEP;
264+ let mut band_eb2 = vec![0.0f64; NBANDS];
265+ let mut frame_ef2 = Vec::with_capacity(nframes);
251 266
252 let mut xb = Vec::new();267 let mut xb = Vec::new();
253 let mut big_x = Vec::new();268 let mut big_x = Vec::new();
@@ -339,14 +354,21 @@ fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 {
339 }354 }
340 }355 }
341 eb /= ((BANDS[bi + 1] - BANDS[bi]) * channels) as f64;356 eb /= ((BANDS[bi + 1] - BANDS[bi]) * channels) as f64;
342- ef += eb * eb;357+ let eb2 = eb * eb;
358+ band_eb2[bi] += eb2;
359+ ef += eb2;
343 }360 }
344 ef /= NBANDS as f64;361 ef /= NBANDS as f64;
345 ef *= ef;362 ef *= ef;
346- err += ef * ef;363+ let ef2 = ef * ef;
364+ frame_ef2.push(ef2);
365+ err += ef2;
347 }366 }
348 err = (err / nframes as f64).powf(1.0 / 16.0);367 err = (err / nframes as f64).powf(1.0 / 16.0);
349- err368+ for b in &mut band_eb2 {
369+ *b /= nframes as f64;
370+ }
371+ (err, band_eb2, frame_ef2)
350 }372 }
351 373
352 /// The `opus_compare` quality metric: >= 0 passes, 100 is identical output.374 /// 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() {
2297 "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"2319 "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"
2298 );2320 );
2299 assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}");2321 assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}");
2322+ // SILK should not lose clearly to CELT at speech rates. CELT with
2323+ // short-block transients now edges SILK by ~0.002 at NB16 (synthetic
2324+ // speech); a larger gap means the SILK encoder regressed.
2300 assert!(2325 assert!(
2301- silk_corr >= celt_corr,2326+ silk_corr >= celt_corr - 0.005,
2302 "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4}"2327 "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4}"
2303 );2328 );
2304 }2329 }
@@ -2477,8 +2502,11 @@ fn hybrid_layers_align() {
2477 e.look_ahead(960)2502 e.look_ahead(960)
2478 }2503 }
2479 );2504 );
2505+ // A fullband CELT click lands at exactly +120 (`celt_click_peak_offset`);
2506+ // the band-limited HB layer's main lobe sits up to 2 samples early once
2507+ // transient frames keep their short blocks, and SILK lands at +121.
2480 assert!(2508 assert!(
2481- (plb - phb).abs() <= 2,2509+ (plb - phb).abs() <= 3,
2482 "layers misaligned: LB +{plb} vs HB +{phb}"2510 "layers misaligned: LB +{plb} vs HB +{phb}"
2483 );2511 );
2484 assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120");2512 assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120");
@@ -3176,3 +3204,491 @@ fn opus_compare_err_pinned_against_c() {
3176 "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)"3204 "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)"
3177 );3205 );
3178 }3206 }
3207+
3208+// ---------------------------------------------------------------------------
3209+// Spectral-divergence diagnostic: WHERE the 96 kbps err_ratio outlier loses
3210+// its error. Per opus_compare band: mean ln-energy error ours-vs-source and
3211+// ref-vs-source, plus the band's share of the frame error; per source: the
3212+// top-5 worst seconds with what the encoder did there (CeltFrameDiag).
3213+// Run: SWEEP_ONLY=reell,dl8a cargo test -p ec-opus --release \
3214+// spectral_divergence_vs_libopus -- --ignored --nocapture
3215+// Writes lanes/opus-reell-r1.bands.txt.
3216+// ---------------------------------------------------------------------------
3217+
3218+/// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)):
3219+/// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz.
3220+const CELT_EBANDS: [usize; NBANDS + 1] = [
3221+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100,
3222+];
3223+
3224+#[test]
3225+#[ignore]
3226+fn spectral_divergence_vs_libopus() {
3227+ const SECS: f64 = 120.0;
3228+ const FRAME: usize = 960;
3229+ const CHANNELS: usize = 2;
3230+ const MAX_LAG: usize = 2000;
3231+ const KBPS: u32 = 96;
3232+
3233+ let all: &[(&str, &str)] = &[
3234+ ("reell", "~/Music/reell.mp4"),
3235+ ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
3236+ ];
3237+ let only: Vec<String> = std::env::var("SWEEP_ONLY")
3238+ .unwrap_or_else(|_| "reell,dl8a".to_owned())
3239+ .split(',')
3240+ .filter(|s| !s.is_empty())
3241+ .map(|s| s.trim().to_owned())
3242+ .collect();
3243+ let sources: Vec<(String, PathBuf)> = all
3244+ .iter()
3245+ .filter(|(tag, _)| only.iter().any(|o| o == tag))
3246+ .map(|(tag, p)| (tag.to_string(), shellexpand(p)))
3247+ .collect();
3248+ assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources");
3249+
3250+ let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3251+ fs::create_dir_all(&lanes_dir).unwrap();
3252+ let out_path = lanes_dir.join("opus-reell-r2.bands.txt");
3253+ let frames_path = lanes_dir.join("opus-reell-r2.frames.txt");
3254+ let scratch = lanes_dir.join("opus-reell-r1.scratch.ogg");
3255+ let mut frames_all = String::new();
3256+ let mut report = String::new();
3257+
3258+ for (tag, src) in &sources {
3259+ if !src.exists() {
3260+ eprintln!("SKIP {tag}: missing {}", src.display());
3261+ continue;
3262+ }
3263+ let source_pcm = ffmpeg_decode_pcm(src, SECS);
3264+ let source_frames = source_pcm.len() / CHANNELS;
3265+ let seconds = source_frames as f64 / 48000.0;
3266+ let source_i16 = to_i16(&source_pcm);
3267+
3268+ // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder.
3269+ ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
3270+ let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
3271+ let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3272+ let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
3273+ .into_iter()
3274+ .skip(2)
3275+ .collect();
3276+ let (ref_dec, ref_ch) = decode_ogg(&scratch);
3277+ assert_eq!(ref_ch, CHANNELS, "{tag}: ref not stereo");
3278+ let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG);
3279+
3280+ // Ours at the reference's realised rate, per-frame diag captured.
3281+ let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3282+ enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3283+ enc.set_vbr_constrained(true);
3284+ let mut dec = Decoder::new(48000, CHANNELS).unwrap();
3285+ let mut packet = vec![0u8; 1500];
3286+ let mut dbuf = vec![0.0f32; 5760 * CHANNELS];
3287+ let mut ours_dec = Vec::new();
3288+ let mut first_pkts: Vec<Vec<u8>> = Vec::new();
3289+ let mut diags = Vec::new();
3290+ let mut ours_bytes = 0usize;
3291+ for block in source_pcm.chunks(FRAME * CHANNELS) {
3292+ let mut padded = block.to_vec();
3293+ padded.resize(FRAME * CHANNELS, 0.0);
3294+ let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode");
3295+ if first_pkts.len() < 10 {
3296+ first_pkts.push(packet[..len].to_vec());
3297+ }
3298+ ours_bytes += len;
3299+ let n = dec.decode_float(&packet[..len], &mut dbuf).expect("decode");
3300+ ours_dec.extend_from_slice(&dbuf[..n * CHANNELS]);
3301+ diags.push(enc.last_celt_diag().clone());
3302+ }
3303+ let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3304+ let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
3305+ let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3306+ let ours_i16 = to_i16(&ours_aligned);
3307+ let ref_i16 = to_i16(&ref_aligned);
3308+
3309+ let cmp_frames = (source_i16.len() / CHANNELS)
3310+ .min(ours_i16.len() / CHANNELS)
3311+ .min(ref_i16.len() / CHANNELS);
3312+ let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3313+ let s_i = trim(&source_i16);
3314+ let o_i = trim(&ours_i16);
3315+ let r_i = trim(&ref_i16);
3316+
3317+ // Metric totals, per-band shares, per-frame errors.
3318+ let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS);
3319+ let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS);
3320+ let corr_o = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3321+ let corr_r = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3322+
3323+ // Raw per-band energies (no masking): spectral shape in the ln domain.
3324+ let nframes = (cmp_frames - WIN_SIZE + WIN_STEP) / WIN_STEP;
3325+ let as_f64 = |v: &[i16]| -> Vec<f64> { v.iter().map(|&x| x as f64).collect() };
3326+ let mut bands_s = Vec::new();
3327+ let mut bands_o = Vec::new();
3328+ let mut bands_r = Vec::new();
3329+ let mut scratch_ps = Vec::new();
3330+ band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps);
3331+ band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps);
3332+ band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps);
3333+
3334+ report.push_str(&format!(
3335+ "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \
3336+ corr o={corr_o:.4} r={corr_r:.4}; err o={err_o:.3} r={err_r:.3} ratio={:.2}\n",
3337+ err_o / err_r
3338+ ));
3339+ report.push_str(
3340+ "# dln = mean ln(E_test/E_src) per channel (neg = energy missing); \
3341+ err = mean |dln|; eb2 = band's mean share of the pre-squared frame error\n",
3342+ );
3343+ report.push_str(
3344+ "# 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",
3345+ );
3346+ for bi in 0..NBANDS {
3347+ let (mut dol, mut dor, mut drl, mut drr) = (0.0f64, 0.0, 0.0, 0.0);
3348+ let (mut aol, mut aor, mut arl, mut arr) = (0.0f64, 0.0, 0.0, 0.0);
3349+ for xi in 0..nframes {
3350+ let e = |b: &Vec<f64>, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln();
3351+ let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1));
3352+ let (o_l, o_r) = (e(&bands_o, 0) - sl, e(&bands_o, 1) - sr);
3353+ let (r_l, r_r) = (e(&bands_r, 0) - sl, e(&bands_r, 1) - sr);
3354+ dol += o_l;
3355+ dor += o_r;
3356+ drl += r_l;
3357+ drr += r_r;
3358+ aol += o_l.abs();
3359+ aor += o_r.abs();
3360+ arl += r_l.abs();
3361+ arr += r_r.abs();
3362+ }
3363+ let n = nframes as f64;
3364+ report.push_str(&format!(
3365+ "{}\t{}\t{:+.3}\t{:+.3}\t{:+.3}\t{:+.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3e}\t{:.3e}\n",
3366+ BANDS[bi] * 100,
3367+ BANDS[bi + 1] * 100,
3368+ dol / n,
3369+ dor / n,
3370+ drl / n,
3371+ drr / n,
3372+ aol / n,
3373+ aor / n,
3374+ arl / n,
3375+ arr / n,
3376+ eb2_o[bi],
3377+ eb2_r[bi],
3378+ ));
3379+ }
3380+
3381+ // Top-5 worst seconds by ours per-frame error, with encoder behavior.
3382+ let mframes_per_sec = 48000 / WIN_STEP; // 400 metric frames per second
3383+ let eframes_per_sec = 48000 / FRAME; // 50 encoder frames per second
3384+ let nsecs = cmp_frames / 48000;
3385+ let mut sec_score: Vec<(usize, f64)> = (0..nsecs)
3386+ .map(|s| {
3387+ let (mut sum, mut cnt) = (0.0f64, 0usize);
3388+ for xi in s * mframes_per_sec..(s + 1) * mframes_per_sec {
3389+ if xi < ef2_o.len() {
3390+ sum += ef2_o[xi];
3391+ cnt += 1;
3392+ }
3393+ }
3394+ (s, sum / cnt.max(1) as f64)
3395+ })
3396+ .collect();
3397+ sec_score.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
3398+ report.push_str("# top-5 seconds by ours frame error (mean ef²) with encoder diag:\n");
3399+ report.push_str(
3400+ "# sec\tscore\ttrans\tcbb_min_hz\tcbb_mean_hz\tint_mean_hz\tdual\tintra\tbits/fr\n",
3401+ );
3402+ for &(s, score) in &sec_score[..nsecs.min(5)] {
3403+ let f0 = s * eframes_per_sec;
3404+ let f1 = ((s + 1) * eframes_per_sec).min(diags.len());
3405+ let fr = &diags[f0.min(f1)..f1];
3406+ let dn = fr.len();
3407+ if dn == 0 {
3408+ continue;
3409+ }
3410+ let transient = fr.iter().filter(|d| d.is_transient).count();
3411+ let dual = fr.iter().filter(|d| d.dual_stereo).count();
3412+ let intra = fr.iter().filter(|d| d.intra).count();
3413+ let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0);
3414+ let cbb_mean =
3415+ fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
3416+ let int_mean = fr.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
3417+ let bits =
3418+ fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
3419+ report.push_str(&format!(
3420+ "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n",
3421+ s,
3422+ score,
3423+ transient,
3424+ dn,
3425+ CELT_EBANDS[cbb_min] * 240,
3426+ CELT_EBANDS[cbb_mean as usize] * 240,
3427+ CELT_EBANDS[int_mean as usize] * 240,
3428+ dual,
3429+ dn,
3430+ intra,
3431+ dn,
3432+ bits,
3433+ ));
3434+ }
3435+
3436+ // Whole-file encoder summary for ours.
3437+ let dn = diags.len();
3438+ if dn > 0 {
3439+ let transient = diags.iter().filter(|d| d.is_transient).count();
3440+ let dual = diags.iter().filter(|d| d.dual_stereo).count();
3441+ let intra = diags.iter().filter(|d| d.intra).count();
3442+ let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0);
3443+ let cbb_mean =
3444+ diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
3445+ let int_mean = diags.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
3446+ let bits =
3447+ diags.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
3448+ report.push_str(&format!(
3449+ "# whole file: transient {}/{} dual {}/{} intra {}/{}; coded_bands min {} mean {} Hz; \
3450+ intensity mean {} Hz; bits/frame {:.0}\n",
3451+ transient,
3452+ dn,
3453+ dual,
3454+ dn,
3455+ intra,
3456+ dn,
3457+ CELT_EBANDS[cbb_min] * 240,
3458+ CELT_EBANDS[cbb_mean as usize] * 240,
3459+ CELT_EBANDS[int_mean as usize] * 240,
3460+ bits,
3461+ ));
3462+ }
3463+
3464+ // Top-8 worst single metric windows (ours vs ref), with the encoder
3465+ // frame each window lands in.
3466+ let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect();
3467+ byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
3468+ report.push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n");
3469+ for &(xi, v) in &byf[..byf.len().min(8)] {
3470+ let rv = if xi < ef2_r.len() { ef2_r[xi] } else { f64::NAN };
3471+ let ms = xi * WIN_STEP * 1000 / 48000;
3472+ let eidx = xi * WIN_STEP / FRAME;
3473+ let d = diags.get(eidx);
3474+ let ds = d.map(|d| {
3475+ format!(
3476+ "{}:trans{},intra{},sil{},cbb{}Hz,int{}Hz,bt{}",
3477+ eidx,
3478+ d.is_transient as u8,
3479+ d.intra as u8,
3480+ d.silence as u8,
3481+ CELT_EBANDS[d.coded_bands] * 240,
3482+ CELT_EBANDS[d.intensity] * 240,
3483+ d.nb_compressed
3484+ )
3485+ });
3486+ report.push_str(&format!(
3487+ "+{}ms\t{:.3e}\t{:.3e}\t{}\n",
3488+ ms,
3489+ v,
3490+ rv,
3491+ ds.as_deref().unwrap_or("-")
3492+ ));
3493+ }
3494+
3495+ // Startup behavior: first 10 encoder frames.
3496+ report.push_str(
3497+ "# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n",
3498+ );
3499+ for (i, d) in diags.iter().take(10).enumerate() {
3500+ report.push_str(&format!(
3501+ "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
3502+ i,
3503+ d.is_transient as u8,
3504+ d.intra as u8,
3505+ d.silence as u8,
3506+ CELT_EBANDS[d.coded_bands] * 240,
3507+ CELT_EBANDS[d.intensity] * 240,
3508+ d.dual_stereo as u8,
3509+ d.nb_compressed
3510+ ));
3511+ }
3512+
3513+ // Per-window per-band ln-energies for the metric windows 12..=20
3514+ // (+120..+200 ms): the leak's shape, band by band.
3515+ report.push_str(
3516+ "# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n",
3517+ );
3518+ for xi in 12..=20 {
3519+ if xi >= nframes {
3520+ break;
3521+ }
3522+ for bi in 0..NBANDS {
3523+ let e = |b: &Vec<f64>, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln();
3524+ let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1));
3525+ let (ol, or_) = (e(&bands_o, 0), e(&bands_o, 1));
3526+ let (rl, rr) = (e(&bands_r, 0), e(&bands_r, 1));
3527+ report.push_str(&format!(
3528+ "w{xi} +{}ms b{bi} {}-{}Hz\t{:+8.2} {:+8.2} {:+8.2} | {:+8.2} {:+8.2} {:+8.2}\n",
3529+ xi * WIN_STEP * 1000 / 48000,
3530+ CELT_EBANDS[bi] * 240,
3531+ CELT_EBANDS[bi + 1] * 240,
3532+ sl,
3533+ ol,
3534+ rl,
3535+ sr,
3536+ or_,
3537+ rr,
3538+ ));
3539+ }
3540+ }
3541+
3542+ // Decode the first 10 packets of each stream with our decoder: does
3543+ // the silence flag survive, and what energies does it leave behind?
3544+ frames_all.push_str(&format!(
3545+ "# {tag}: first 10 packets through our decoder; energies are log2 old_band_e\n"
3546+ ));
3547+ for (label, pkts) in [("ours", &first_pkts), ("ref", &ref_pkts)] {
3548+ let mut d = Decoder::new(48000, CHANNELS).unwrap();
3549+ let mut ob = vec![0.0f32; 5760 * CHANNELS];
3550+ for (i, p) in pkts.iter().take(10).enumerate() {
3551+ let _ = d.decode_float(p, &mut ob).expect("decode");
3552+ let g = d.last_celt_diag();
3553+ frames_all.push_str(&format!(
3554+ "{label} {i} bytes={} toc={:#04x} sil{} intra{} trans{} bits{}\n",
3555+ p.len(),
3556+ p.first().copied().unwrap_or(0),
3557+ g.silence as u8,
3558+ g.intra as u8,
3559+ g.transient as u8,
3560+ g.total_bits,
3561+ ));
3562+ for (ch, name) in [(0usize, 'L'), (1usize, 'R')] {
3563+ let band = &g.old_band_e[ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS];
3564+ let e: Vec<String> = band.iter().map(|v| format!("{v:+6.1}")).collect();
3565+ frames_all.push_str(&format!(" {name} {}\n", e.join(" ")));
3566+ }
3567+ }
3568+ }
3569+ println!(
3570+ "{tag}@{KBPS}k: err o={err_o:.3} r={err_r:.3} ratio={:.2}",
3571+ err_o / err_r
3572+ );
3573+ }
3574+ let _ = fs::remove_file(&scratch);
3575+ let header = format!(
3576+ "# spectral divergence vs libopus @ {KBPS}k, {SECS:.0}s cap, sources {}\n",
3577+ only.join(",")
3578+ );
3579+ fs::write(&out_path, header + &report).unwrap();
3580+ fs::write(&frames_path, &frames_all).unwrap();
3581+ println!("wrote {}", out_path.display());
3582+}
3583+
3584+/// Startup leak repro (lane-opus-reell): the first frames of the reell source
3585+/// (digital silence then an attack) through the library gate's encoder
3586+/// settings and our decoder. Prints per-frame CELT facts; fails if the decode
3587+/// peak exceeds 4x the input peak in any frame.
3588+#[test]
3589+fn celt_silence_then_attack_decodes_bounded() {
3590+ let fs = 960usize;
3591+ let ch = 2usize;
3592+ let src = shellexpand("~/Music/reell.mp4");
3593+ if !src.exists() {
3594+ eprintln!("SKIP: missing {}", src.display());
3595+ return;
3596+ }
3597+ let pcm = ffmpeg_decode_pcm(&src, 1.0);
3598+ let mut enc = Encoder::new(48000, ch, Application::Audio).unwrap();
3599+ enc.set_bitrate(96_000);
3600+ enc.set_vbr_constrained(true);
3601+ let mut dec = Decoder::new(48000, ch).unwrap();
3602+ let mut bad = Vec::new();
3603+ for frame in 0..12 {
3604+ let slice = &pcm[frame * fs * ch..(frame + 1) * fs * ch];
3605+ let in_peak = slice.iter().fold(0f32, |a, &x| a.max(x.abs()));
3606+ let pcm_i16 = to_i16(slice);
3607+ let mut buf = [0u8; 1500];
3608+ let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap();
3609+ let ed = enc.last_celt_diag().clone();
3610+ let mut out = vec![0f32; fs * ch];
3611+ let got = dec.decode_float(&buf[..n], &mut out).unwrap();
3612+ let d = dec.last_celt_diag().clone();
3613+ let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs()));
3614+ let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max);
3615+ println!(
3616+ "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}",
3617+ ed.silence, ed.intra, ed.is_transient, d.silence, d.intra, d.transient, d.total_bits
3618+ );
3619+ if peak > 4.0 * in_peak.max(1e-4) {
3620+ bad.push(frame);
3621+ }
3622+ }
3623+ assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}");
3624+}
3625+
3626+/// Sample-level view of the reell startup: per-120-sample energy of source,
3627+/// ours (gate path) and libopus reference around the first attack.
3628+#[test]
3629+#[ignore]
3630+fn reell_startup_hop_energies() {
3631+ const CH: usize = 2;
3632+ let src = shellexpand("~/Music/reell.mp4");
3633+ if !src.exists() {
3634+ return;
3635+ }
3636+ let pcm = ffmpeg_decode_pcm(&src, 2.0);
3637+ let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus");
3638+ ffmpeg_encode_libopus(&src, 96, &scratch, 2.0);
3639+ let (ref_dec, _) = decode_ogg(&scratch);
3640+ let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000);
3641+ let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap();
3642+ enc.set_bitrate(96_000);
3643+ enc.set_vbr_constrained(true);
3644+ let (ours_dec, _) = roundtrip_own(&mut enc, &pcm, CH, 960);
3645+ let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000);
3646+ let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH);
3647+ println!("lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", first(&pcm), first(&ours_al), first(&ref_al));
3648+ let e = |v: &[f32], h: usize| -> f64 {
3649+ v[h * 120 * CH..((h + 1) * 120 * CH).min(v.len())].iter().map(|&x| (x as f64) * (x as f64)).sum()
3650+ };
3651+ // Frame-2 flags of both streams through our decoder.
3652+ let data = fs::read(&scratch).unwrap();
3653+ let packets = ogg_packets(&data);
3654+ let mut rd = Decoder::new(48000, CH).unwrap();
3655+ let mut od = Decoder::new(48000, CH).unwrap();
3656+ let mut oe = Encoder::new(48000, CH, Application::Audio).unwrap();
3657+ oe.set_bitrate(96_000);
3658+ oe.set_vbr_constrained(true);
3659+ let mut buf = vec![0f32; 5760 * CH];
3660+ let mut out = vec![0u8; 1500];
3661+ for f in 0..4 {
3662+ rd.decode_float(&packets[2 + f], &mut buf).unwrap();
3663+ let r = rd.last_celt_diag().clone();
3664+ let n = oe.encode_float(&pcm[f * 960 * CH..(f + 1) * 960 * CH], 960, &mut out).unwrap();
3665+ od.decode_float(&out[..n], &mut buf).unwrap();
3666+ let o = od.last_celt_diag().clone();
3667+ let e = oe.last_celt_diag().clone();
3668+ 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);
3669+ 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);
3670+ }
3671+ println!("hop(ms)\tsrc\tours\tref");
3672+ for h in 10..24 {
3673+ println!("{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", h as f64 * 2.5, e(&pcm, h), e(&ours_al, h), e(&ref_al, h));
3674+ }
3675+}
3676+
3677+/// Where a lone click lands after a CELT-only fullband roundtrip, relative to
3678+/// the encoder look-ahead (diagnostic for the hybrid alignment tolerance).
3679+#[test]
3680+#[ignore]
3681+fn celt_click_peak_offset() {
3682+ let mut click = vec![0f32; 48000];
3683+ let at = 960 * 10 + 300;
3684+ click[at] = 0.9;
3685+ for bps in [32_000u32, 64_000, 128_000] {
3686+ let mut enc = Encoder::new(48000, 1, Application::Audio).unwrap();
3687+ enc.set_mode(Some(ec_opus::Mode::Celt));
3688+ enc.set_bitrate(bps);
3689+ let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960);
3690+ let p = dec.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0;
3691+ let d = enc.last_celt_diag().clone();
3692+ println!("celt click {bps}: peak +{} (lm {})", p as i64 - at as i64, d.lm);
3693+ }
3694+}
lanes/opus-reell-r1.bands.txtadded+54 -0
@@ -0,0 +1,54 @@
1+# spectral divergence vs libopus @ 96k, 120s cap, sources reell
2+
3+# 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
4+# 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
5+# lo_hz hi_hz dlnL_o dlnR_o dlnL_r dlnR_r errL_o errR_o errL_r errR_r eb2_o eb2_r
6+0 200 +0.001 +0.002 +0.002 +0.006 0.104 0.106 0.131 0.132 2.697e-1 3.016e-4
7+200 400 +0.001 -0.000 -0.001 +0.000 0.096 0.095 0.095 0.094 1.692e0 7.242e-5
8+400 600 -0.001 -0.001 -0.002 +0.002 0.104 0.107 0.115 0.119 1.168e1 8.595e-5
9+600 800 +0.005 +0.003 +0.002 +0.002 0.139 0.135 0.132 0.131 1.086e-1 7.575e-5
10+800 1000 +0.001 -0.002 +0.002 +0.000 0.119 0.114 0.124 0.119 1.732e0 9.527e-5
11+1000 1200 +0.003 +0.001 -0.001 +0.004 0.137 0.135 0.138 0.138 4.836e1 1.625e-4
12+1200 1400 +0.009 +0.003 +0.003 +0.001 0.163 0.157 0.160 0.155 1.245e0 2.724e-4
13+1400 1600 +0.005 +0.001 +0.001 +0.001 0.162 0.156 0.164 0.158 1.197e0 4.705e-4
14+1600 2000 +0.000 +0.001 +0.000 +0.005 0.122 0.124 0.126 0.128 2.832e-1 4.896e-4
15+2000 2400 +0.001 -0.002 -0.001 +0.003 0.147 0.145 0.154 0.153 1.005e0 6.703e-4
16+2400 2800 +0.004 -0.002 +0.004 +0.000 0.160 0.158 0.168 0.164 4.746e-1 9.076e-4
17+2800 3200 +0.001 +0.004 +0.004 +0.005 0.171 0.173 0.173 0.174 1.560e-3 1.308e-3
18+3200 4000 +0.002 +0.002 +0.004 +0.003 0.125 0.125 0.127 0.128 1.465e-2 1.280e-3
19+4000 4800 +0.001 +0.002 +0.006 +0.004 0.130 0.131 0.133 0.133 5.610e-3 1.706e-3
20+4800 5600 +0.004 +0.004 +0.006 +0.005 0.148 0.148 0.150 0.151 1.300e-2 2.727e-3
21+5600 6800 +0.017 +0.016 +0.007 +0.009 0.159 0.159 0.156 0.158 1.051e-2 3.473e-3
22+6800 8000 +0.011 +0.011 +0.009 +0.010 0.161 0.161 0.162 0.162 1.624e-2 5.401e-3
23+8000 9600 +0.009 +0.011 +0.007 +0.008 0.133 0.133 0.132 0.133 2.408e-2 5.434e-3
24+9600 12000 +0.012 +0.012 +0.008 +0.007 0.117 0.117 0.119 0.118 4.770e-2 7.134e-3
25+12000 15600 +0.008 +0.010 +0.007 +0.010 0.143 0.143 0.151 0.152 1.605e-2 1.123e-2
26+15600 20000 +0.023 +0.025 +0.034 +0.038 0.107 0.110 0.118 0.121 4.185e-3 4.877e-3
27+# top-5 seconds by ours frame error (mean ef²) with encoder diag:
28+# sec score trans cbb_min_hz cbb_mean_hz int_mean_hz dual intra bits/fr
29+0 1.739e17 2/50 240 14400 11520 5/50 5/50 2058
30+103 5.456e2 3/50 18720 18720 14400 23/50 5/50 2115
31+72 3.090e2 0/50 18720 18720 14400 7/50 0/50 2079
32+22 3.360e1 1/50 18720 18720 14400 18/50 3/50 2086
33+11 2.080e1 2/50 18720 18720 14400 26/50 4/50 2112
34+# 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
35+# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag
36++42ms 5.184e19 2.281e-4 2:trans1,intra1,sil0,cbb24000Hz,int14400Hz,bt446
37++40ms 1.770e19 1.209e-22 2:trans1,intra1,sil0,cbb24000Hz,int14400Hz,bt446
38++37ms 5.262e14 7.660e-76 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2
39++35ms 1.124e12 0.000e0 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2
40++32ms 2.854e6 0.000e0 1:trans0,intra0,sil1,cbb240Hz,int0Hz,bt2
41++103455ms 1.945e5 6.637e-8 5172:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt246
42++72980ms 9.745e4 1.563e-11 3649:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt257
43++72977ms 2.525e4 4.626e-12 3648:trans0,intra0,sil0,cbb18720Hz,int14400Hz,bt255
44+# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes
45+0 0 0 1 240 0 0 2
46+1 0 0 1 240 0 0 2
47+2 1 1 0 24000 14400 0 446
48+3 0 1 0 18720 14400 1 257
49+4 0 1 0 18720 14400 1 264
50+5 0 0 0 18720 14400 1 266
51+6 0 0 0 18720 14400 0 258
52+7 0 0 0 18720 14400 0 259
53+8 0 0 0 18720 14400 1 260
54+9 0 0 0 18720 14400 1 260
lanes/opus-reell-r1.handoff.mdadded+10 -0
@@ -0,0 +1,10 @@
1+## Exact next steps
2+
3+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.
4+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.
5+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.
6+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).
7+5. Commit all on `lane-opus-reell`; no merge, no push.
8+
9+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.
10+DELTA: none
lanes/opus-reell-r2.report.mdadded+47 -0
@@ -0,0 +1,47 @@
1+# lane-opus-reell r2 — startup leak = transient tf_res default inversion
2+
3+## Cause
4+Silence frames decode to exact zeros (`celt_silence_then_attack_decodes_bounded`).
5+The leak was pre-echo in the first attack frame: encoder coded raw `tf_res = 0`
6+with `tf_select = 0` on a transient LM=3 frame, which `TF_SELECT[3][4+0+0]` maps
7+to `+3` — all 8 short blocks merged back into one long block in every band. The
8+source is ≈0 for 12 ms before the onset, so opus_compare's Y/X ratio exploded.
9+libopus without tf_analysis codes raw `tf_res[i] = isTransient` (change 0).
10+
11+Evidence (`reell_startup_hop_energies`, energy per 2.5 ms hop, 37.5–45 ms):
12+ours before 8e-4…6e-3, ours after 3e-19…2e-18, libopus 0…8e-7. Decoder diag of
13+frame 2: OUR tf `[3;21]` before, `[0;21]` after; REF `[1,1,1,-1,…]` (tf_analysis).
14+
15+## Fix
16+`celt_enc.rs`: `self.tf_res = [i32::from(is_transient); NB_BANDS]` + doc comment
17+corrected (it claimed the opposite of the table). `CeltDecDiag` gained
18+`tf_res/spread/anti_collapse`.
19+
20+## Gate (14 rows, vs opus-drop-r2)
21+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
22+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
23+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
24+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
25+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
26+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
27+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
28+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
29+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
30+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
31+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
32+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
33+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
34+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
35+RATE ±5% pass, DROPOUT pass. reell err_ratio 21→1.60 @64, 23.9→3.33 @96; corr gap
36+−.0024/−.0007. No row regressed corr by >.001; reelm/hein@64 unchanged (lane-opus-64).
37+
38+## Suite
39+ec-opus: 34 + 27 pass, 7 ignored. Two assertions re-sized after the change:
40+- `hybrid_layers_align`: layer tolerance 2→3. Fullband CELT click peaks at
41+ exactly +120 (`celt_click_peak_offset`, 32/64/128 k); the band-limited HB
42+ layer's main lobe now sits at +118, SILK at +121.
43+- `silk_compares_to_celt_on_speech_at_speech_rates`: SILK ≥ CELT − .005; CELT
44+ edges SILK by .002 at NB16 (synthetic). Residue: SILK encoder quality.
45+
46+## Residue
47+her@96 err_ratio 10.1 (was 13+) — next largest startup/transient window; not named.
lanes/opus-reell-r2.sweep.txtadded+17 -0
@@ -0,0 +1,17 @@
1+# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)
2+# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo
3+# 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
4+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
5+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
6+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
7+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
8+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
9+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
10+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
11+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
12+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
13+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
14+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
15+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
16+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
17+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