U10: ec-aac delete tests/sbr_real_library (debug probes, knob-driven and EC_AAC env tests) and tests/it/reelh_per_frame (knob scan); FATE parity lives in he_parity
Browse files at this commit7b6a4e62e1306af6e9341c24bb37f7e418f968acParent: e3bba2b6 changed files +0 -4755
- crates/ec-aac/tests/it/reelh_per_frame.rs +0 -151
- crates/ec-aac/tests/sbr_real_library/chunk_a.rs +0 -1035
- crates/ec-aac/tests/sbr_real_library/chunk_b.rs +0 -674
- crates/ec-aac/tests/sbr_real_library/chunk_c.rs +0 -677
- crates/ec-aac/tests/sbr_real_library/helpers.rs +0 -2187
- crates/ec-aac/tests/sbr_real_library/main.rs +0 -31
crates/ec-aac/tests/it/reelh_per_frame.rsdeleted+0 -151
| @@ -1,151 +0,0 @@ | |||
| 1 | -//! Per-frame corr scan for the coordinator's second repro: a real download | ||
| 2 | -//! whose AAC-LC decode reads clean for the first several seconds then | ||
| 3 | -//! collapses mid-stream, sequentially, with no seek/reset. Finds the first | ||
| 4 | -//! bad frame and its side info, to compare with the frame before. | ||
| 5 | - | ||
| 6 | -use std::fs::File; | ||
| 7 | -use std::io::BufReader; | ||
| 8 | - | ||
| 9 | -use ec_aac::AacDecoder; | ||
| 10 | -use ec_core::{CodecId, Demuxer, Packet}; | ||
| 11 | -use ec_mp4::Mp4Demuxer; | ||
| 12 | - | ||
| 13 | -#[test] | ||
| 14 | -fn reelh_per_frame_scan() { | ||
| 15 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 16 | - let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true)); | ||
| 17 | - | ||
| 18 | - // ffmpeg's channel-0-only decode (pan, not -ac, per the repro). | ||
| 19 | - let out = ec_testkit::ffmpeg() | ||
| 20 | - .args(["-v", "error", "-i"]) | ||
| 21 | - .arg(&path) | ||
| 22 | - .args([ | ||
| 23 | - "-map", "0:a:0", "-af", "pan=1c|c0=c0", "-f", "f32le", "-acodec", "pcm_f32le", "-", | ||
| 24 | - ]) | ||
| 25 | - .output() | ||
| 26 | - .expect("ffmpeg runs"); | ||
| 27 | - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); | ||
| 28 | - let theirs: Vec<f32> = out | ||
| 29 | - .stdout | ||
| 30 | - .as_chunks::<4>().0.iter() | ||
| 31 | - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 32 | - .collect(); | ||
| 33 | - | ||
| 34 | - // Our sequential decode: one decoder, no reset, packet 0 onward. | ||
| 35 | - let f = File::open(&path).unwrap(); | ||
| 36 | - let mut d = Mp4Demuxer::new(BufReader::new(f)).unwrap(); | ||
| 37 | - let aac = d | ||
| 38 | - .streams() | ||
| 39 | - .iter() | ||
| 40 | - .find(|s| s.params.codec == CodecId::Aac) | ||
| 41 | - .unwrap(); | ||
| 42 | - let idx = aac.index; | ||
| 43 | - let asc = aac.params.extradata.as_ref().unwrap().to_vec(); | ||
| 44 | - let mut decoder = AacDecoder::with_config_bytes(&asc).unwrap(); | ||
| 45 | - | ||
| 46 | - let mut ours: Vec<f32> = Vec::new(); | ||
| 47 | - let mut frame_starts: Vec<usize> = Vec::new(); // sample offset each AU's ch0 output starts at | ||
| 48 | - let mut au_idx = 0usize; | ||
| 49 | - loop { | ||
| 50 | - let pkt = match d.next_packet() { | ||
| 51 | - Ok(Packet { stream, data, .. }) if stream == idx => data.to_vec(), | ||
| 52 | - Ok(_) => continue, | ||
| 53 | - Err(_) => break, | ||
| 54 | - }; | ||
| 55 | - frame_starts.push(ours.len()); | ||
| 56 | - match decoder.decode(&pkt, None) { | ||
| 57 | - Ok(frame) => { | ||
| 58 | - let ch = usize::from(frame.channels); | ||
| 59 | - if ch > 0 { | ||
| 60 | - for chunk in frame.samples.chunks_exact(ch) { | ||
| 61 | - ours.push(chunk[0]); | ||
| 62 | - } | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - Err(e) => eprintln!("AU {au_idx} decode error: {e:?}"), | ||
| 66 | - } | ||
| 67 | - au_idx += 1; | ||
| 68 | - } | ||
| 69 | - eprintln!("decoded {au_idx} AUs, {} ch0 samples ours, {} ffmpeg", ours.len(), theirs.len()); | ||
| 70 | - | ||
| 71 | - let rows = ec_aac::tool_sideinfo_log(); | ||
| 72 | - | ||
| 73 | - // Per-AU corr at zero lag (both start from packet 0 in decode order -- | ||
| 74 | - // no lag search needed unless the two genuinely desync). | ||
| 75 | - let win = 1024usize; | ||
| 76 | - let mut first_bad: Option<usize> = None; | ||
| 77 | - let mut bad_count = 0usize; | ||
| 78 | - let mut pns_frames = 0usize; | ||
| 79 | - for r in &rows { | ||
| 80 | - if r.pns_bands > 0 { | ||
| 81 | - pns_frames += 1; | ||
| 82 | - } | ||
| 83 | - } | ||
| 84 | - eprintln!("frames with pns_bands>0: {pns_frames} / {}", rows.len()); | ||
| 85 | - let full_rms_o: f64 = (ours.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / ours.len() as f64).sqrt(); | ||
| 86 | - let full_rms_t: f64 = (theirs.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / theirs.len() as f64).sqrt(); | ||
| 87 | - eprintln!("full-file rms ours={full_rms_o:.6} ffmpeg={full_rms_t:.6}"); | ||
| 88 | - for (i, &start) in frame_starts.iter().enumerate() { | ||
| 89 | - if start + win > ours.len() || start + win > theirs.len() { | ||
| 90 | - break; | ||
| 91 | - } | ||
| 92 | - let a = &ours[start..start + win]; | ||
| 93 | - let b = &theirs[start..start + win]; | ||
| 94 | - let ma = a.iter().sum::<f32>() / win as f32; | ||
| 95 | - let mb = b.iter().sum::<f32>() / win as f32; | ||
| 96 | - let num: f64 = a.iter().zip(b).map(|(x, y)| f64::from(*x - ma) * f64::from(*y - mb)).sum(); | ||
| 97 | - let da: f64 = a.iter().map(|x| f64::from(*x - ma).powi(2)).sum(); | ||
| 98 | - let db: f64 = b.iter().map(|y| f64::from(*y - mb).powi(2)).sum(); | ||
| 99 | - let corr = if da * db == 0.0 { 1.0 } else { num / (da * db).sqrt() }; | ||
| 100 | - if corr.abs() < 0.9 { | ||
| 101 | - bad_count += 1; | ||
| 102 | - if first_bad.is_none() { | ||
| 103 | - first_bad = Some(i); | ||
| 104 | - } | ||
| 105 | - let rms_o: f64 = (a.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 106 | - let rms_t: f64 = (b.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 107 | - let pns = rows.get(i).map(|r| r.pns_bands).unwrap_or(0); | ||
| 108 | - eprintln!("AU {i}: sample_start={start} corr={corr:.4} rms_o={rms_o:.6} rms_t={rms_t:.6} pns_bands={pns} BAD"); | ||
| 109 | - } else if i % 50 == 0 { | ||
| 110 | - eprintln!("AU {i}: sample_start={start} corr={corr:.4}"); | ||
| 111 | - } | ||
| 112 | - } | ||
| 113 | - | ||
| 114 | - // Dump raw samples around the bad AU for inspection. | ||
| 115 | - if let Some(&start) = frame_starts.get(4) { | ||
| 116 | - eprintln!("--- AU4 samples (start={start}) ---"); | ||
| 117 | - for k in 0..16 { | ||
| 118 | - eprintln!(" k={k} ours={:.6} ffmpeg={:.6}", ours[start + k], theirs[start + k]); | ||
| 119 | - } | ||
| 120 | - let rms_o: f64 = (ours[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 121 | - let rms_t: f64 = (theirs[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 122 | - eprintln!(" rms ours={rms_o:.6} ffmpeg={rms_t:.6}"); | ||
| 123 | - } | ||
| 124 | - | ||
| 125 | - eprintln!("total BAD (|corr|<0.9) AUs: {bad_count} / {}", frame_starts.len()); | ||
| 126 | - // Whole-window (first 10s @ 44.1k = 441000 samples) zero-lag Pearson, | ||
| 127 | - // ours vs ffmpeg -- reproduces (or not) the engine sweep's 0.9840 figure | ||
| 128 | - // from this decoder-level data alone. | ||
| 129 | - let n = 441_000usize.min(ours.len()).min(theirs.len()); | ||
| 130 | - let (a, b) = (&ours[..n], &theirs[..n]); | ||
| 131 | - let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 132 | - let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 133 | - let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64); | ||
| 134 | - for (x, y) in a.iter().zip(b) { | ||
| 135 | - let (x, y) = (f64::from(*x) - ma, f64::from(*y) - mb); | ||
| 136 | - num += x * y; | ||
| 137 | - da += x * x; | ||
| 138 | - db += y * y; | ||
| 139 | - } | ||
| 140 | - eprintln!("whole-10s zero-lag Pearson (n={n}): {:.6}", num / (da * db).sqrt()); | ||
| 141 | - if let Some(bad) = first_bad { | ||
| 142 | - eprintln!("=== first bad AU: {bad} ==="); | ||
| 143 | - for i in bad.saturating_sub(2)..=bad + 2 { | ||
| 144 | - if let Some(row) = rows.get(i) { | ||
| 145 | - eprintln!(" AU {i}: {row:?}"); | ||
| 146 | - } | ||
| 147 | - } | ||
| 148 | - } else { | ||
| 149 | - eprintln!("no AU dropped below 0.9 corr"); | ||
| 150 | - } | ||
| 151 | -} | ||
crates/ec-aac/tests/sbr_real_library/chunk_a.rsdeleted+0 -1035
| @@ -1,1035 +0,0 @@ | |||
| 1 | -//! SBR real-library checks and probes, part A. | ||
| 2 | - | ||
| 3 | -use super::*; | ||
| 4 | - | ||
| 5 | -/// Root-cause triage (round-51): is a real file's SBR-chain break actually | ||
| 6 | -/// downstream of a broken LC core, or does the core decode cleanly and the | ||
| 7 | -/// break lives only in the SBR chain layered on top of it? Prints a | ||
| 8 | -/// core-rate correlation per channel; not asserted on, this is a diagnostic, | ||
| 9 | -/// not a regression gate (the asserted gate is | ||
| 10 | -/// `sbr_real_library_matches_reference`, which already covers the full-band | ||
| 11 | -/// SBR-reconstructed output). | ||
| 12 | -/// | ||
| 13 | -/// Round-61: this printed corr 0.402349 for reeln ch0 while that file's | ||
| 14 | -/// core is provably fine (the asserted reference gate scores its below-5kHz | ||
| 15 | -/// band 0.999988, and `full_chain_low_band_matches_own_core` scores this very | ||
| 16 | -/// core-only PCM 0.998 against our own full chain). The number was the | ||
| 17 | -/// instrument, not the codec: `robust_lag_topk`'s stride-11 coarse grid | ||
| 18 | -/// cannot see a 1-sample-wide correlation peak, so its top-K was ranked from | ||
| 19 | -/// noise. At the true lag -- 481, ffmpeg's resampler delay, the same lag FMJ | ||
| 20 | -/// reads -- these two signals correlate 0.999845. The search here is now | ||
| 21 | -/// stride-1 (`exhaustive_lag_correlation`), and both sides are low-passed at | ||
| 22 | -/// `0.9 * crossover` first, since only the reference side (ffmpeg's full SBR | ||
| 23 | -/// reconstruction, resampled down to the core rate) can hold anything above | ||
| 24 | -/// the crossover at all. | ||
| 25 | -#[test] | ||
| 26 | -pub(super) fn core_only_matches_reference() { | ||
| 27 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 28 | - for c in &candidates() { | ||
| 29 | - let (ours, core_rate) = our_decode_core_only(&c.path, c.aac_stream).expect("core decode"); | ||
| 30 | - let theirs = ffmpeg_decode_at_rate(&c.path, c.ffmpeg_stream, ours.len(), core_rate); | ||
| 31 | - println!( | ||
| 32 | - "{} core-only ({} ch, {} Hz):", | ||
| 33 | - c.path.display(), | ||
| 34 | - ours.len(), | ||
| 35 | - core_rate | ||
| 36 | - ); | ||
| 37 | - let cutoff = c.crossover_hz * 0.9; | ||
| 38 | - for (ch, (o, t)) in ours.iter().zip(&theirs).enumerate() { | ||
| 39 | - let ol = lowpass(o, core_rate, cutoff); | ||
| 40 | - let tl = lowpass(t, core_rate, cutoff); | ||
| 41 | - let (mut lag, mut corr, mut at_edge) = | ||
| 42 | - exhaustive_lag_correlation(&ol, &tl, PLAIN_LAG_MAX); | ||
| 43 | - if at_edge { | ||
| 44 | - (lag, corr, at_edge) = exhaustive_lag_correlation(&ol, &tl, SEARCH_LAG_MAX); | ||
| 45 | - } | ||
| 46 | - let edge = if at_edge { | ||
| 47 | - " (AT SEARCH BOUND -- noise, not a measurement)" | ||
| 48 | - } else { | ||
| 49 | - "" | ||
| 50 | - }; | ||
| 51 | - println!(" ch{ch}: below {cutoff:.0}Hz lag {lag}, corr {corr:.6}{edge}"); | ||
| 52 | - } | ||
| 53 | - } | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -/// Round-51 triage: dumps `kx`/`k2` (the SBR crossover/top band) for the | ||
| 57 | -/// first several frames of every candidate, unconditionally (no ffmpeg | ||
| 58 | -/// needed) -- a wrong `kx` would corrupt bands BELOW the crossover too, not | ||
| 59 | -/// just the HF-generated ones, since `adjust()` gain-scales everything from | ||
| 60 | -/// `kx` up, and `kx` computed too low would pull real core content into | ||
| 61 | -/// that scaling. | ||
| 62 | -#[test] | ||
| 63 | -pub(super) fn dump_sideinfo_kx() { | ||
| 64 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 65 | - let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); | ||
| 66 | - for c in &candidates() { | ||
| 67 | - let Some((asc, aus)) = extract_aac_track(&c.path, c.aac_stream) else { | ||
| 68 | - continue; | ||
| 69 | - }; | ||
| 70 | - let Ok(mut decoder) = AacDecoder::with_config_bytes(&asc) else { | ||
| 71 | - continue; | ||
| 72 | - }; | ||
| 73 | - let before = ec_aac::sbr_sideinfo_log().len(); | ||
| 74 | - for au in aus.iter().take(50) { | ||
| 75 | - let _ = decoder.decode(au, None); | ||
| 76 | - } | ||
| 77 | - let rows = ec_aac::sbr_sideinfo_log(); | ||
| 78 | - println!("{}:", c.path.display()); | ||
| 79 | - for row in rows[before..].iter().filter(|r| r.ch == 0).take(6) { | ||
| 80 | - println!( | ||
| 81 | - " frame={} source={} kx={} k2={} t_env={:?} f_high={:?}", | ||
| 82 | - row.frame, row.source, row.kx, row.k2, row.t_env, row.f_high | ||
| 83 | - ); | ||
| 84 | - } | ||
| 85 | - } | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -/// Round-51 triage: FMJ's full-chain best-lag search (`LAG_MAX` = 4000) | ||
| 89 | -/// finds no usable alignment (|corr| ~0.02) even though the core-only | ||
| 90 | -/// decode matches almost exactly -- this widens the search far past | ||
| 91 | -/// `LAG_MAX` to see whether the true alignment just lies outside the normal | ||
| 92 | -/// bound (a large, rate-family-specific extra delay) rather than the SBR | ||
| 93 | -/// content itself being wrong. | ||
| 94 | -#[test] | ||
| 95 | -pub(super) fn wide_lag_search_full_chain() { | ||
| 96 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 97 | - for c in &candidates() { | ||
| 98 | - let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else { | ||
| 99 | - continue; | ||
| 100 | - }; | ||
| 101 | - if sbr != ec_aac::SbrSupport::V1 { | ||
| 102 | - continue; | ||
| 103 | - } | ||
| 104 | - let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len()); | ||
| 105 | - let o = &ours[0]; | ||
| 106 | - let t = &theirs[0]; | ||
| 107 | - println!( | ||
| 108 | - "{} ({} Hz): ours len={} theirs len={}", | ||
| 109 | - c.path.display(), | ||
| 110 | - rate, | ||
| 111 | - o.len(), | ||
| 112 | - t.len() | ||
| 113 | - ); | ||
| 114 | - const COARSE: usize = 4096; | ||
| 115 | - const WIDE_LAG_MAX: i64 = 200_000; | ||
| 116 | - let mut best = (0i64, -1.0f64); | ||
| 117 | - let mut lag = -WIDE_LAG_MAX; | ||
| 118 | - while lag <= WIDE_LAG_MAX { | ||
| 119 | - let (oa, ob) = if lag >= 0 { | ||
| 120 | - (0usize, lag as usize) | ||
| 121 | - } else { | ||
| 122 | - ((-lag) as usize, 0usize) | ||
| 123 | - }; | ||
| 124 | - if oa + COARSE <= o.len() && ob + COARSE <= t.len() { | ||
| 125 | - let c = correlation(&o[oa..oa + COARSE], &t[ob..ob + COARSE]).abs(); | ||
| 126 | - if c > best.1 { | ||
| 127 | - best = (lag, c); | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | - lag += 97; // odd stride so it doesn't alias against 2048-sample AU boundaries | ||
| 131 | - } | ||
| 132 | - println!(" widest coarse best: lag={} |corr|={:.4}", best.0, best.1); | ||
| 133 | - } | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -/// Round-51 triage: compares OUR full-chain (SBR-reconstructed) output's | ||
| 137 | -/// low band directly against OUR OWN core-only decode of the same stream -- | ||
| 138 | -/// no reference decoder involved. `v[0..kx]` in `sbr_chain.rs` is a literal | ||
| 139 | -/// copy of the same core analysis QMF data the core-only path also | ||
| 140 | -/// produces, so if the synthesis/gain-adjust stage is corrupting even that | ||
| 141 | -/// untouched region, this shows a real self-inconsistency with no external | ||
| 142 | -/// factor (alignment against a reference, different tool, etc.) to blame. | ||
| 143 | -#[test] | ||
| 144 | -pub(super) fn full_chain_low_band_matches_own_core() { | ||
| 145 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 146 | - for c in &candidates() { | ||
| 147 | - let Some((core, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else { | ||
| 148 | - continue; | ||
| 149 | - }; | ||
| 150 | - let Some((full, sbr, full_rate)) = our_decode(&c.path, c.aac_stream) else { | ||
| 151 | - continue; | ||
| 152 | - }; | ||
| 153 | - if sbr != ec_aac::SbrSupport::V1 { | ||
| 154 | - continue; | ||
| 155 | - } | ||
| 156 | - println!( | ||
| 157 | - "{} (core {} Hz, full {} Hz):", | ||
| 158 | - c.path.display(), | ||
| 159 | - core_rate, | ||
| 160 | - full_rate | ||
| 161 | - ); | ||
| 162 | - for ch in 0..core.len().min(full.len()) { | ||
| 163 | - // Naive nearest-neighbor 2x upsample of the core so it lines up | ||
| 164 | - // sample-for-sample with the full-chain output's rate -- | ||
| 165 | - // crude, but a low-pass well below the core Nyquist erases the | ||
| 166 | - // stairstep artifacts this introduces. | ||
| 167 | - let up = if full_rate == core_rate { | ||
| 168 | - core[ch].clone() | ||
| 169 | - } else { | ||
| 170 | - upsample_2x(&core[ch]) | ||
| 171 | - }; | ||
| 172 | - let cutoff = f64::from(core_rate) * 0.4; | ||
| 173 | - let keep = if full.len() > core.len() { | ||
| 174 | - mono_prefix(&full) | ||
| 175 | - } else { | ||
| 176 | - full[ch].len() | ||
| 177 | - }; | ||
| 178 | - let ol = lowpass(&full[ch][..keep], full_rate, cutoff); | ||
| 179 | - let ul = lowpass(&up, full_rate, cutoff); | ||
| 180 | - // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's | ||
| 181 | - // original bound) first, widen to `SEARCH_LAG_MAX` only if that | ||
| 182 | - // narrow search hit its own edge (`at_edge`). A single shared | ||
| 183 | - // wide bound was tried first (round-54) and, unconditionally | ||
| 184 | - // widening this comparison, flipped reeln from its correct | ||
| 185 | - // small-lag answer (-576, corr 0.9967) to a wrong, noise-driven | ||
| 186 | - // distant one (-912, corr -0.295) -- a genuinely low-quality | ||
| 187 | - // low-passed signal's coarse correlation surface has enough | ||
| 188 | - // stray peaks over a 100_000-wide range to beat a real but | ||
| 189 | - // modest true peak. Escalating only when the narrow bound | ||
| 190 | - // proves insufficient (FMJ's own core-vs-full delay lands AT | ||
| 191 | - // the 20_000 edge, corr 0.217393 there, the same edge-noise | ||
| 192 | - // class the reference-vs-ours gate had) gets both files right | ||
| 193 | - // without exposing the well-behaved one to the wider bound's | ||
| 194 | - // noise floor. | ||
| 195 | - const WIDE_LAG_MAX: i64 = 20_000; | ||
| 196 | - // Top-K refinement, not the single coarse winner: FMJ's single | ||
| 197 | - // coarse pick landed on an in-bounds noise peak (lag 18995, | ||
| 198 | - // corr 0.10) while its true alignment scores >0.99 on refine. | ||
| 199 | - // A winner at the bound widens once, then is asserted off it. | ||
| 200 | - let (mut lag, mut corr, mut at_edge) = | ||
| 201 | - robust_lag_topk(&ol, &ul, WIDE_LAG_MAX, core_rate, 8); | ||
| 202 | - let mut bound = WIDE_LAG_MAX; | ||
| 203 | - // A sub-bar winner inside the narrow bound is the same symptom | ||
| 204 | - // (true peak outside the search), so it widens too. | ||
| 205 | - if at_edge || corr < 0.99 { | ||
| 206 | - bound = SEARCH_LAG_MAX; | ||
| 207 | - (lag, corr, at_edge) = robust_lag_topk(&ol, &ul, SEARCH_LAG_MAX, core_rate, 8); | ||
| 208 | - } | ||
| 209 | - println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}"); | ||
| 210 | - assert!( | ||
| 211 | - !at_edge, | ||
| 212 | - "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \ | ||
| 213 | - search bound -- corr {corr:.6} is noise, not a measurement", | ||
| 214 | - c.path.display() | ||
| 215 | - ); | ||
| 216 | - assert!( | ||
| 217 | - corr >= 0.99, | ||
| 218 | - "{} ch{ch}: full-chain low band vs our own core-only decode \ | ||
| 219 | - corr {corr:.6} at measured lag {lag} < 0.99 -- the \ | ||
| 220 | - synthesis/gain-adjust stage is corrupting even the untouched \ | ||
| 221 | - low-band region copied straight from core analysis", | ||
| 222 | - c.path.display() | ||
| 223 | - ); | ||
| 224 | - } | ||
| 225 | - } | ||
| 226 | -} | ||
| 227 | - | ||
| 228 | -#[test] | ||
| 229 | -pub(super) fn synthetic_heaac_matrix() { | ||
| 230 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 231 | - let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); | ||
| 232 | - println!( | ||
| 233 | - "{:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", | ||
| 234 | - "kx", | ||
| 235 | - "k2", | ||
| 236 | - "full", | ||
| 237 | - "below", | ||
| 238 | - "above", | ||
| 239 | - "lag", | ||
| 240 | - "ours_v_core", | ||
| 241 | - "ovc_lag", | ||
| 242 | - "core_v_ref", | ||
| 243 | - "cvr_lag", | ||
| 244 | - "core_rate", | ||
| 245 | - "full_rate" | ||
| 246 | - ); | ||
| 247 | - // Wide enough that the WIDE_LAG_MAX==LC's own decoder priming delay | ||
| 248 | - // (2048) plus a full SBR-chain worth of extra delay (a few thousand | ||
| 249 | - // samples at the doubled/full output rate) both land well inside it, | ||
| 250 | - // not right at the edge the way the plain (LAG_MAX=4000) search did. | ||
| 251 | - const WIDE_LAG_MAX: i64 = 20_000; | ||
| 252 | - for path in fate_aac() { | ||
| 253 | - let before = ec_aac::sbr_sideinfo_log().len(); | ||
| 254 | - let (ours, _sbr, our_rate) = our_decode(&path, 0).expect("decodes"); | ||
| 255 | - let rows = ec_aac::sbr_sideinfo_log(); | ||
| 256 | - let (kx, k2) = rows[before..] | ||
| 257 | - .iter() | ||
| 258 | - .find(|r| r.ch == 0) | ||
| 259 | - .map(|r| (r.kx, r.k2)) | ||
| 260 | - .unwrap_or((-1, -1)); | ||
| 261 | - let theirs = ffmpeg_decode(&path, 0, ours.len()); | ||
| 262 | - let o = &ours[0]; | ||
| 263 | - let t = &theirs[0]; | ||
| 264 | - const TOPK: usize = 5; | ||
| 265 | - let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK); | ||
| 266 | - assert!( | ||
| 267 | - !edge, | ||
| 268 | - "{}: HE row's refined winning lag {lag} sits at the \ | ||
| 269 | - +/-{WIDE_LAG_MAX} search's own edge", | ||
| 270 | - path.display() | ||
| 271 | - ); | ||
| 272 | - if ours.len() >= 2 && theirs.len() >= 2 { | ||
| 273 | - let mono_o: Vec<f32> = | ||
| 274 | - ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect(); | ||
| 275 | - let mono_t: Vec<f32> = theirs[0] | ||
| 276 | - .iter() | ||
| 277 | - .zip(&theirs[1]) | ||
| 278 | - .map(|(a, b)| a + b) | ||
| 279 | - .collect(); | ||
| 280 | - let (mono_lag, _, mono_edge) = | ||
| 281 | - robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK); | ||
| 282 | - assert!( | ||
| 283 | - !mono_edge, | ||
| 284 | - "{}: HE row's mono-derived refined lag {mono_lag} sits at the \ | ||
| 285 | - +/-{WIDE_LAG_MAX} search's own edge", | ||
| 286 | - path.display() | ||
| 287 | - ); | ||
| 288 | - lag = mono_lag; | ||
| 289 | - full = correlation_at_lag(o, t, lag); | ||
| 290 | - } | ||
| 291 | - let crossover_hz = if kx > 0 { | ||
| 292 | - f64::from(our_rate) * (kx as f64) / 128.0 | ||
| 293 | - } else { | ||
| 294 | - f64::from(our_rate) * 0.25 | ||
| 295 | - }; | ||
| 296 | - let below = correlation_at_lag( | ||
| 297 | - &lowpass(o, our_rate, crossover_hz), | ||
| 298 | - &lowpass(t, our_rate, crossover_hz), | ||
| 299 | - lag, | ||
| 300 | - ); | ||
| 301 | - let (oa, ob) = if lag >= 0 { | ||
| 302 | - (0usize, lag as usize) | ||
| 303 | - } else { | ||
| 304 | - ((-lag) as usize, 0usize) | ||
| 305 | - }; | ||
| 306 | - let n = WINDOW | ||
| 307 | - .min(o.len().saturating_sub(oa)) | ||
| 308 | - .min(t.len().saturating_sub(ob)); | ||
| 309 | - let above = if n >= 1024 { | ||
| 310 | - correlation( | ||
| 311 | - &highpass(&o[oa..oa + n], our_rate, crossover_hz), | ||
| 312 | - &highpass(&t[ob..ob + n], our_rate, crossover_hz), | ||
| 313 | - ) | ||
| 314 | - } else { | ||
| 315 | - 0.0 | ||
| 316 | - }; | ||
| 317 | - let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec<f32> { | ||
| 318 | - let cutoff = f64::from(to_rate) * 0.45; | ||
| 319 | - lowpass(s, from_rate, cutoff) | ||
| 320 | - .iter() | ||
| 321 | - .step_by((from_rate / to_rate.max(1)).max(1) as usize) | ||
| 322 | - .copied() | ||
| 323 | - .collect() | ||
| 324 | - }; | ||
| 325 | - let core_lag_max = WIDE_LAG_MAX / 2; | ||
| 326 | - let ours_v_core = if kx > 0 { | ||
| 327 | - our_decode_core_only(&path, 0).map(|(core, core_rate)| { | ||
| 328 | - let full_at_core_rate = decimate(o, our_rate, core_rate); | ||
| 329 | - best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max) | ||
| 330 | - }) | ||
| 331 | - } else { | ||
| 332 | - None | ||
| 333 | - }; | ||
| 334 | - let (core_v_ref, core_rate_str) = if kx > 0 { | ||
| 335 | - match our_decode_core_only(&path, 0) { | ||
| 336 | - Some((core, core_rate)) => { | ||
| 337 | - let ref_at_core_rate = | ||
| 338 | - ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate); | ||
| 339 | - ( | ||
| 340 | - Some(best_lag_correlation_wide( | ||
| 341 | - &core[0], | ||
| 342 | - &ref_at_core_rate[0], | ||
| 343 | - core_lag_max, | ||
| 344 | - )), | ||
| 345 | - core_rate.to_string(), | ||
| 346 | - ) | ||
| 347 | - } | ||
| 348 | - None => (None, "n/a".into()), | ||
| 349 | - } | ||
| 350 | - } else { | ||
| 351 | - (None, "n/a".into()) | ||
| 352 | - }; | ||
| 353 | - println!( | ||
| 354 | - "{kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", | ||
| 355 | - ours_v_core | ||
| 356 | - .map(|(_, c)| format!("{c:.4}")) | ||
| 357 | - .unwrap_or_else(|| "n/a".into()), | ||
| 358 | - ours_v_core | ||
| 359 | - .map(|(l, _)| l.to_string()) | ||
| 360 | - .unwrap_or_else(|| "n/a".into()), | ||
| 361 | - core_v_ref | ||
| 362 | - .map(|(_, c)| format!("{c:.4}")) | ||
| 363 | - .unwrap_or_else(|| "n/a".into()), | ||
| 364 | - core_v_ref | ||
| 365 | - .map(|(l, _)| l.to_string()) | ||
| 366 | - .unwrap_or_else(|| "n/a".into()), | ||
| 367 | - core_rate_str, | ||
| 368 | - our_rate, | ||
| 369 | - ); | ||
| 370 | - } | ||
| 371 | -} | ||
| 372 | - | ||
| 373 | -pub(super) fn candidates() -> Vec<Candidate> { | ||
| 374 | - fate_aac() | ||
| 375 | - .into_iter() | ||
| 376 | - .map(|path| Candidate { | ||
| 377 | - path, | ||
| 378 | - aac_stream: 0, | ||
| 379 | - ffmpeg_stream: 0, | ||
| 380 | - crossover_hz: 5_000.0, | ||
| 381 | - }) | ||
| 382 | - .collect() | ||
| 383 | -} | ||
| 384 | - | ||
| 385 | -/// The SBR chain against the reference decoder on every real HE-AAC file this | ||
| 386 | -/// checkout can find. Skips loudly (never silently) when ffmpeg or the files | ||
| 387 | -/// are absent. Per channel: full-band correlation must clear 0.999 and the | ||
| 388 | -/// below-crossover (core-decoded) band must clear 0.9999, so a real SBR | ||
| 389 | -/// regression cannot hide behind an average across bands the core never | ||
| 390 | -/// touches. | ||
| 391 | -#[test] | ||
| 392 | -pub(super) fn sbr_real_library_matches_reference() { | ||
| 393 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 394 | - let list = candidates(); | ||
| 395 | - let mut checked = 0; | ||
| 396 | - let mut worst_full = 1.0f64; | ||
| 397 | - let mut worst_low = 1.0f64; | ||
| 398 | - let mut any_at_edge: Option<String> = None; | ||
| 399 | - for c in &list { | ||
| 400 | - let (ours, sbr, rate) = our_decode(&c.path, c.aac_stream).expect("decode"); | ||
| 401 | - if sbr != ec_aac::SbrSupport::V1 { | ||
| 402 | - continue; | ||
| 403 | - } | ||
| 404 | - let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len()); | ||
| 405 | - println!("{} ({} ch, {} Hz):", c.path.display(), ours.len(), rate); | ||
| 406 | - // Full cross-channel triangle at one fixed lag/window: both channels | ||
| 407 | - // of one CPE are decoded frame-locked and so share the same | ||
| 408 | - // start-of-stream offset, so ch0's own alignment lag is a valid | ||
| 409 | - // anchor for every pair here, letting all five numbers be compared | ||
| 410 | - // directly instead of each being independently (and, before the | ||
| 411 | - // |corr|-max fix above, unreliably) re-searched. | ||
| 412 | - if ours.len() >= 2 && theirs.len() >= 2 { | ||
| 413 | - let (lag0, _) = best_lag_correlation(&ours[0], &theirs[0]); | ||
| 414 | - println!( | ||
| 415 | - " TRIANGLE @ ch0's lag {lag0}: ours0*ref0={:.6} ours0*ref1={:.6} ours1*ref0={:.6} ours1*ref1={:.6} ours0*ours1={:.6}", | ||
| 416 | - correlation_at_lag(&ours[0], &theirs[0], lag0), | ||
| 417 | - correlation_at_lag(&ours[0], &theirs[1], lag0), | ||
| 418 | - correlation_at_lag(&ours[1], &theirs[0], lag0), | ||
| 419 | - correlation_at_lag(&ours[1], &theirs[1], lag0), | ||
| 420 | - correlation_at_lag(&ours[0], &ours[1], 0), | ||
| 421 | - ); | ||
| 422 | - } | ||
| 423 | - for (ch, (o_full, t_full)) in ours.iter().zip(&theirs).enumerate() { | ||
| 424 | - // (Round-22 stability check) EC_AAC_SBR_SWEEP_SEGMENT=1 measures | ||
| 425 | - // the second half of the file instead of the first, so a | ||
| 426 | - // calibration candidate can be checked on two disjoint segments | ||
| 427 | - // rather than just the file's start. | ||
| 428 | - // | ||
| 429 | - // (Round-23) The split point MUST be the same absolute sample | ||
| 430 | - // index on both sides, not each side's own `len() / 2`: `ours` | ||
| 431 | - // is capped at MAX_SAMPLES while `theirs` (the reference) is | ||
| 432 | - // decoded in full, so on a file longer than the cap `o_full` and | ||
| 433 | - // `t_full` have different total lengths and an independent | ||
| 434 | - // `len() / 2` on each picks DIFFERENT seconds of the file -- | ||
| 435 | - // reeln is a 30s file capped to ours=22.7s, so the old code | ||
| 436 | - // compared ours' 11.35s-22.7s against theirs' 15.0s-30.0s, a | ||
| 437 | - // 3.6s-misaligned pair of unrelated passages that reads as a | ||
| 438 | - // catastrophic collapse (~-0.01 corr) with no decode defect | ||
| 439 | - // behind it. Splitting both sides at the shorter side's midpoint | ||
| 440 | - // keeps the two halves pointed at the same audio. | ||
| 441 | - let (o, t): (&[f32], &[f32]) = | ||
| 442 | - if std::env::var("EC_AAC_SBR_SWEEP_SEGMENT").as_deref() == Ok("1") { | ||
| 443 | - let half = o_full.len().min(t_full.len()) / 2; | ||
| 444 | - (&o_full[half..], &t_full[half..]) | ||
| 445 | - } else { | ||
| 446 | - (&o_full[..], &t_full[..]) | ||
| 447 | - }; | ||
| 448 | - let rms = |s: &[f32]| { | ||
| 449 | - (s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() | ||
| 450 | - / s.len().max(1) as f64) | ||
| 451 | - .sqrt() | ||
| 452 | - }; | ||
| 453 | - eprintln!( | ||
| 454 | - " ch{ch} debug: ours len={} rms={:.4} first10={:?}; theirs len={} rms={:.4} first10={:?}", | ||
| 455 | - o.len(), | ||
| 456 | - rms(o), | ||
| 457 | - &o[..10.min(o.len())], | ||
| 458 | - t.len(), | ||
| 459 | - rms(t), | ||
| 460 | - &t[..10.min(t.len())], | ||
| 461 | - ); | ||
| 462 | - let (lag, full, full_at_edge) = best_lag_correlation_ex(o, t, SEARCH_LAG_MAX); | ||
| 463 | - if full_at_edge { | ||
| 464 | - any_at_edge.get_or_insert_with(|| { | ||
| 465 | - format!( | ||
| 466 | - "{} ch{ch} full-band: winning lag {lag} at +/-{SEARCH_LAG_MAX} search edge", | ||
| 467 | - c.path.display() | ||
| 468 | - ) | ||
| 469 | - }); | ||
| 470 | - } | ||
| 471 | - // Re-slice both signals at the winning lag before splitting into | ||
| 472 | - // bands, so the band correlations are aligned too. | ||
| 473 | - let (oa, ob) = if lag >= 0 { | ||
| 474 | - (0usize, lag as usize) | ||
| 475 | - } else { | ||
| 476 | - ((-lag) as usize, 0usize) | ||
| 477 | - }; | ||
| 478 | - let n = WINDOW | ||
| 479 | - .min(o.len().saturating_sub(oa)) | ||
| 480 | - .min(t.len().saturating_sub(ob)); | ||
| 481 | - // The below-crossover band gets its OWN lag search rather than | ||
| 482 | - // reusing the full-band winning lag: a narrowband, slowly-varying | ||
| 483 | - // low-passed signal has a correlation surface that stays broad | ||
| 484 | - // and flat across many nearby lags, so a full-band search (whose | ||
| 485 | - // winner is decided mostly by the higher-energy/higher-bandwidth | ||
| 486 | - // content) can land on a lag that is a genuine local optimum for | ||
| 487 | - // the whole signal yet a bad one for the low band alone -- on | ||
| 488 | - // reeln ch1, full-band lag 65 vs 64 differ by only 0.0015 in | ||
| 489 | - // full-band correlation but by 0.88 in below-crossover | ||
| 490 | - // correlation once the low band is measured at its own winning | ||
| 491 | - // lag instead. Both bands are still re-anchored at the SAME | ||
| 492 | - // `start` offset internally (see `best_lag_correlation`), so | ||
| 493 | - // this is genuinely comparing the low band against itself, not | ||
| 494 | - // drifting to an unrelated part of the file. | ||
| 495 | - let low = { | ||
| 496 | - let ol_full = lowpass(o, rate, c.crossover_hz); | ||
| 497 | - let tl_full = lowpass(t, rate, c.crossover_hz); | ||
| 498 | - let (low_lag, low_corr, low_at_edge) = | ||
| 499 | - best_lag_correlation_ex(&ol_full, &tl_full, SEARCH_LAG_MAX); | ||
| 500 | - if low_at_edge { | ||
| 501 | - any_at_edge.get_or_insert_with(|| { | ||
| 502 | - format!( | ||
| 503 | - "{} ch{ch} below-crossover: winning lag {low_lag} at +/-{SEARCH_LAG_MAX} search edge", | ||
| 504 | - c.path.display() | ||
| 505 | - ) | ||
| 506 | - }); | ||
| 507 | - } | ||
| 508 | - if low_lag != lag { | ||
| 509 | - eprintln!( | ||
| 510 | - " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}" | ||
| 511 | - ); | ||
| 512 | - } | ||
| 513 | - if std::env::var("EC_AAC_SBR_DRIFT").is_ok() { | ||
| 514 | - let ol_sharp = sharp_lowpass(o, rate, c.crossover_hz); | ||
| 515 | - let tl_sharp = sharp_lowpass(t, rate, c.crossover_hz); | ||
| 516 | - let (_, sharp_corr) = best_lag_correlation(&ol_sharp, &tl_sharp); | ||
| 517 | - println!( | ||
| 518 | - " ch{ch} below-crossover SHARP (3x cascaded) filter: {sharp_corr:.6}" | ||
| 519 | - ); | ||
| 520 | - } | ||
| 521 | - low_corr | ||
| 522 | - }; | ||
| 523 | - let high = if n >= 1024 { | ||
| 524 | - let oh = highpass(&o[oa..oa + n], rate, c.crossover_hz); | ||
| 525 | - let th = highpass(&t[ob..ob + n], rate, c.crossover_hz); | ||
| 526 | - let rms = |v: &[f32]| { | ||
| 527 | - (v.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / v.len().max(1) as f64) | ||
| 528 | - .sqrt() | ||
| 529 | - }; | ||
| 530 | - println!( | ||
| 531 | - " ch{ch} above-crossover RMS ours/ref = {:.4}", | ||
| 532 | - rms(&oh) / rms(&th).max(1e-12) | ||
| 533 | - ); | ||
| 534 | - correlation(&oh, &th) | ||
| 535 | - } else { | ||
| 536 | - 0.0 | ||
| 537 | - }; | ||
| 538 | - if ch == 0 && std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok() { | ||
| 539 | - // (Round-17, Task 1) the noise-energy-fraction ceiling | ||
| 540 | - // hypothesis: predicted per-band correlation ceiling | ||
| 541 | - // sqrt(1 - noise_energy/(signal_energy+noise_energy)), | ||
| 542 | - // from OUR OWN transmitted (dequantized) envelope/noise | ||
| 543 | - // split -- printed once per file so it can be eyeballed | ||
| 544 | - // against per_band_lag_search's measured |corr| curve | ||
| 545 | - // below. Real QMF band width in output Hz is | ||
| 546 | - // `rate/128` (64-band synthesis over the output Nyquist). | ||
| 547 | - let band_hz = f64::from(rate) / 128.0; | ||
| 548 | - println!( | ||
| 549 | - " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):" | ||
| 550 | - ); | ||
| 551 | - for (band, signal, noise, out) in ec_aac::noise_fraction_table() { | ||
| 552 | - if signal + noise <= 0.0 { | ||
| 553 | - continue; | ||
| 554 | - } | ||
| 555 | - let f = noise / (signal + noise); | ||
| 556 | - println!( | ||
| 557 | - " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4} realised/target {:.4}", | ||
| 558 | - band as f64 * band_hz, | ||
| 559 | - (1.0 - f).max(0.0).sqrt(), | ||
| 560 | - out / (signal + noise) | ||
| 561 | - ); | ||
| 562 | - } | ||
| 563 | - } | ||
| 564 | - if std::env::var("EC_AAC_SBR_BANDS").is_ok() && n >= 4_096 { | ||
| 565 | - let spectrum = per_band_correlation(&o[oa..oa + n], &t[ob..ob + n], rate); | ||
| 566 | - println!(" ch{ch} per-QMF-band |corr| (band_hz, |corr|, band_index):"); | ||
| 567 | - for (hz, corr, band) in &spectrum { | ||
| 568 | - println!(" {hz:>6.0}Hz band{band:>3.0}: {corr:.4}"); | ||
| 569 | - } | ||
| 570 | - let lags = per_band_lag_search(&o[oa..oa + n], &t[ob..ob + n], rate); | ||
| 571 | - println!(" ch{ch} per-HF-band PCM lag search (band_hz, best_lag, |corr|):"); | ||
| 572 | - for (hz, lag, corr) in &lags { | ||
| 573 | - println!(" {hz:>6.0}Hz: lag {lag:>5} corr {corr:.4}"); | ||
| 574 | - } | ||
| 575 | - let phases = per_band_phase(&o[oa..oa + n], &t[ob..ob + n], rate); | ||
| 576 | - println!( | ||
| 577 | - " ch{ch} per-band cross-spectrum (band_hz, phase_deg, mag_ratio ours/theirs):" | ||
| 578 | - ); | ||
| 579 | - for (hz, phase, ratio) in &phases { | ||
| 580 | - println!( | ||
| 581 | - " {hz:>6.0}Hz: phase {:>7.2}deg ratio {ratio:.4}", | ||
| 582 | - phase.to_degrees() | ||
| 583 | - ); | ||
| 584 | - } | ||
| 585 | - } | ||
| 586 | - if std::env::var("EC_AAC_SBR_HF_CONVICTION").is_ok() && n >= 4_096 { | ||
| 587 | - let band_hz = f64::from(rate) / 256.0; | ||
| 588 | - let kx = (c.crossover_hz / band_hz).round() as usize; | ||
| 589 | - let win = &o[oa..oa + n]; | ||
| 590 | - let twin = &t[ob..ob + n]; | ||
| 591 | - println!( | ||
| 592 | - " ch{ch} TASK1 bandpass-selectivity probe (band_hz, same-band corr, +offset corr, -offset corr):" | ||
| 593 | - ); | ||
| 594 | - for hf_band in [kx + 5, kx + 15, kx + 25] { | ||
| 595 | - let (same, hi_c, lo_c) = bandpass_offset_probe(win, twin, rate, hf_band, 10); | ||
| 596 | - println!( | ||
| 597 | - " HF band{hf_band:>3} ({:.0}Hz) offset=10: same {same:.4} +10band {hi_c:.4} -10band {lo_c:.4}", | ||
| 598 | - hf_band as f64 * band_hz | ||
| 599 | - ); | ||
| 600 | - } | ||
| 601 | - if kx > 6 { | ||
| 602 | - let lf_band = kx.saturating_sub(6); | ||
| 603 | - let (same, hi_c, lo_c) = bandpass_offset_probe(win, twin, rate, lf_band, 3); | ||
| 604 | - println!( | ||
| 605 | - " LF CONTROL band{lf_band:>3} ({:.0}Hz) offset=3: same {same:.4} +3band {hi_c:.4} -3band {lo_c:.4}", | ||
| 606 | - lf_band as f64 * band_hz | ||
| 607 | - ); | ||
| 608 | - } | ||
| 609 | - println!( | ||
| 610 | - " ch{ch} TASK2 bin-level conviction (band_hz, ours-energy, direct, mirror, shift+1band, shift-1band):" | ||
| 611 | - ); | ||
| 612 | - let min_band = (2_500.0 / band_hz).ceil() as usize; | ||
| 613 | - for (hz, energy, direct, mirror, shift_up, shift_down) in | ||
| 614 | - bin_level_conviction(win, twin, rate, min_band, 6) | ||
| 615 | - { | ||
| 616 | - println!( | ||
| 617 | - " {hz:>6.0}Hz: energy {energy:.3e} direct {direct:.4} mirror {mirror:.4} shift+1 {shift_up:.4} shift-1 {shift_down:.4}" | ||
| 618 | - ); | ||
| 619 | - } | ||
| 620 | - } | ||
| 621 | - // (Round-36, Task 2) parity-split coherence: round-35 fixed the | ||
| 622 | - // Synthesis phase-intercept bug only for ODD (target-source) | ||
| 623 | - // patch gaps, at the patch-copy site. On header A (the real | ||
| 624 | - // file's own header) that fix can only be SEEN in the odd-gap | ||
| 625 | - // territory those patches cover (bands 28..42, from patches | ||
| 626 | - // (3,28,11)/(0,39,3)/(13,42,1)); the even-gap patch (0,14,14) | ||
| 627 | - // covers bands 14..27 and was already exact before round-35, so | ||
| 628 | - // it is the control range the fix must NOT move. Reuses | ||
| 629 | - // `bin_level_conviction`'s per-bin direct-coherence measurement | ||
| 630 | - // over every HF band in [14, 43) (min_band=14, top_n wide enough | ||
| 631 | - // to keep every band, not just the top-energy handful), then | ||
| 632 | - // averages `direct` within each region separately. | ||
| 633 | - if std::env::var("EC_AAC_SBR_PARITY_SPLIT").is_ok() && n >= 4_096 { | ||
| 634 | - let band_hz = f64::from(rate) / 256.0; | ||
| 635 | - let win = &o[oa..oa + n]; | ||
| 636 | - let twin = &t[ob..ob + n]; | ||
| 637 | - let rows = bin_level_conviction(win, twin, rate, 14, 29); | ||
| 638 | - let mean_in = |lo: usize, hi: usize| { | ||
| 639 | - let vals: Vec<f64> = rows | ||
| 640 | - .iter() | ||
| 641 | - .filter(|(hz, ..)| { | ||
| 642 | - let band = (hz / band_hz).round() as usize; | ||
| 643 | - band >= lo && band < hi | ||
| 644 | - }) | ||
| 645 | - .map(|(_, _, direct, ..)| *direct) | ||
| 646 | - .collect(); | ||
| 647 | - if vals.is_empty() { | ||
| 648 | - (0.0, 0) | ||
| 649 | - } else { | ||
| 650 | - (vals.iter().sum::<f64>() / vals.len() as f64, vals.len()) | ||
| 651 | - } | ||
| 652 | - }; | ||
| 653 | - let (even_mean, even_n) = mean_in(14, 28); | ||
| 654 | - let (odd_mean, odd_n) = mean_in(28, 43); | ||
| 655 | - println!( | ||
| 656 | - " ch{ch} PARITY-SPLIT direct-coherence mean: even-gap[14,28)={even_mean:.4} (n={even_n}) odd-gap[28,43)={odd_mean:.4} (n={odd_n})" | ||
| 657 | - ); | ||
| 658 | - } | ||
| 659 | - // (Round-38, Task 1) HF-only constant-lag sweep: see | ||
| 660 | - // `hf_lag_sweep`'s doc comment. Reuses this window's already | ||
| 661 | - // globally-aligned `oa`/`ob`/`n`; only `o`'s STFT read position is | ||
| 662 | - // shifted, `n_slot`*64 samples at a time. | ||
| 663 | - if std::env::var("EC_AAC_SBR_HF_LAG_SWEEP").is_ok() && n >= 4_096 { | ||
| 664 | - let band_hz = f64::from(rate) / 256.0; | ||
| 665 | - let min_band = (2_500.0 / band_hz).ceil() as usize; | ||
| 666 | - let sweep = hf_lag_sweep(o, t, oa, ob, n, min_band); | ||
| 667 | - println!( | ||
| 668 | - " ch{ch} TASK1 HF-only lag sweep (k = QMF slots of 64 samples, mean direct HF-bin coherence):" | ||
| 669 | - ); | ||
| 670 | - for (k, coh) in &sweep { | ||
| 671 | - println!(" k={k:>3}: coherence {coh:.4}"); | ||
| 672 | - } | ||
| 673 | - if let Some((peak_k, peak_c)) = | ||
| 674 | - sweep.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) | ||
| 675 | - { | ||
| 676 | - println!(" ch{ch} HF lag sweep peak: k={peak_k} coherence {peak_c:.4}"); | ||
| 677 | - } | ||
| 678 | - } | ||
| 679 | - // (Round-40, Task 1) fine spectral-bin shift scan -- see | ||
| 680 | - // `hf_bin_shift_sweep`'s doc comment. | ||
| 681 | - if std::env::var("EC_AAC_SBR_BIN_SHIFT").is_ok() && n >= 4_096 { | ||
| 682 | - let win = &o[oa..oa + n]; | ||
| 683 | - let twin = &t[ob..ob + n]; | ||
| 684 | - for (region_name, lo, hi) in | ||
| 685 | - [("even-gap[14,28)", 14, 28), ("odd-gap[28,43)", 28, 43)] | ||
| 686 | - { | ||
| 687 | - let sweep = hf_bin_shift_sweep(win, twin, rate, lo, hi); | ||
| 688 | - println!( | ||
| 689 | - " ch{ch} TASK1 BIN-SHIFT {region_name} (b = FFT bins, mean direct HF-bin coherence):" | ||
| 690 | - ); | ||
| 691 | - for (b, coh) in &sweep { | ||
| 692 | - println!(" b={b:>3}: coherence {coh:.4}"); | ||
| 693 | - } | ||
| 694 | - if let Some((peak_b, peak_c)) = | ||
| 695 | - sweep.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) | ||
| 696 | - { | ||
| 697 | - println!( | ||
| 698 | - " ch{ch} {region_name} bin-shift peak: b={peak_b} coherence {peak_c:.4}" | ||
| 699 | - ); | ||
| 700 | - } | ||
| 701 | - } | ||
| 702 | - } | ||
| 703 | - // (Round-40, Task 2) complex-gain fingerprint -- see | ||
| 704 | - // `hf_complex_ratio_trajectory`'s doc comment. | ||
| 705 | - if std::env::var("EC_AAC_SBR_COMPLEX_GAIN").is_ok() && n >= 4_096 { | ||
| 706 | - let band_hz = f64::from(rate) / 256.0; | ||
| 707 | - let min_band = (2_500.0 / band_hz).ceil() as usize; | ||
| 708 | - let win = &o[oa..oa + n]; | ||
| 709 | - let twin = &t[ob..ob + n]; | ||
| 710 | - for (hz, traj) in hf_complex_ratio_trajectory(win, twin, rate, min_band, 4) { | ||
| 711 | - println!( | ||
| 712 | - " ch{ch} TASK2 COMPLEX-GAIN {hz:.0}Hz dominant-bin O/T trajectory (frame: mag, phase_deg, dphase_deg):" | ||
| 713 | - ); | ||
| 714 | - let mut prev_phase: Option<f64> = None; | ||
| 715 | - for (h, (mag, phase)) in traj.iter().enumerate() { | ||
| 716 | - let dphase = prev_phase.map(|p| { | ||
| 717 | - let mut d = phase.to_degrees() - p; | ||
| 718 | - while d > 180.0 { | ||
| 719 | - d -= 360.0; | ||
| 720 | - } | ||
| 721 | - while d < -180.0 { | ||
| 722 | - d += 360.0; | ||
| 723 | - } | ||
| 724 | - d | ||
| 725 | - }); | ||
| 726 | - prev_phase = Some(phase.to_degrees()); | ||
| 727 | - match dphase { | ||
| 728 | - Some(d) => println!( | ||
| 729 | - " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase {d:>7.2}deg", | ||
| 730 | - phase.to_degrees() | ||
| 731 | - ), | ||
| 732 | - None => println!( | ||
| 733 | - " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase n/a", | ||
| 734 | - phase.to_degrees() | ||
| 735 | - ), | ||
| 736 | - } | ||
| 737 | - } | ||
| 738 | - } | ||
| 739 | - } | ||
| 740 | - // (Round-45, Task 3) THIRD WITNESS: a reference-free plain | ||
| 741 | - // patch+gain simulator built from the reference's own low band -- | ||
| 742 | - // see `hf_patch_simulator`'s doc comment. | ||
| 743 | - if std::env::var("EC_AAC_SBR_SIMULATOR").is_ok() && n >= 4_096 { | ||
| 744 | - let win = &o[oa..oa + n]; | ||
| 745 | - let twin = &t[ob..ob + n]; | ||
| 746 | - let (vs_ref, vs_ours) = hf_patch_simulator(win, twin, rate); | ||
| 747 | - let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| { | ||
| 748 | - let vals: Vec<f64> = rows | ||
| 749 | - .iter() | ||
| 750 | - .filter(|(b, _)| *b >= lo && *b < hi) | ||
| 751 | - .map(|(_, c)| *c) | ||
| 752 | - .collect(); | ||
| 753 | - if vals.is_empty() { | ||
| 754 | - 0.0 | ||
| 755 | - } else { | ||
| 756 | - vals.iter().sum::<f64>() / vals.len() as f64 | ||
| 757 | - } | ||
| 758 | - }; | ||
| 759 | - println!(" ch{ch} SIMULATOR sim-vs-REFERENCE per-band coherence (band, coh):"); | ||
| 760 | - for (b, coh) in &vs_ref { | ||
| 761 | - println!(" band{b:>3}: {coh:.4}"); | ||
| 762 | - } | ||
| 763 | - println!( | ||
| 764 | - " ch{ch} SIMULATOR sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", | ||
| 765 | - mean_in(&vs_ref, 14, 28), | ||
| 766 | - mean_in(&vs_ref, 28, 43) | ||
| 767 | - ); | ||
| 768 | - println!(" ch{ch} SIMULATOR sim-vs-OURS per-band coherence (band, coh):"); | ||
| 769 | - for (b, coh) in &vs_ours { | ||
| 770 | - println!(" band{b:>3}: {coh:.4}"); | ||
| 771 | - } | ||
| 772 | - println!( | ||
| 773 | - " ch{ch} SIMULATOR sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", | ||
| 774 | - mean_in(&vs_ours, 14, 28), | ||
| 775 | - mean_in(&vs_ours, 28, 43) | ||
| 776 | - ); | ||
| 777 | - } | ||
| 778 | - // (Round-46, Task 1) QMF-domain exact third witness -- see | ||
| 779 | - // `hf_patch_simulator_qmf`'s doc comment. | ||
| 780 | - if std::env::var("EC_AAC_SBR_QMF_WITNESS").is_ok() && n >= 4_096 { | ||
| 781 | - let win = &o[oa..oa + n]; | ||
| 782 | - let twin = &t[ob..ob + n]; | ||
| 783 | - let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin); | ||
| 784 | - // Per-QMF-band energy ratio and coherence, ours vs reference | ||
| 785 | - // (the envelope-adjuster instrument: a level offset shows as | ||
| 786 | - // a constant dB ratio, a gain-shape defect as per-band dB). | ||
| 787 | - { | ||
| 788 | - let (o_spec, t_spec, _) = qmf_domain_spec(win, twin); | ||
| 789 | - println!(" ch{ch} QMF-BAND ours-vs-REFERENCE (band, ratio_dB, coherence):"); | ||
| 790 | - for band in 0..o_spec.len().min(t_spec.len()).min(48) { | ||
| 791 | - let (mut eo, mut et, mut cr, mut ci) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); | ||
| 792 | - for (a, b) in o_spec[band].iter().zip(&t_spec[band]) { | ||
| 793 | - eo += a.norm_sqr(); | ||
| 794 | - et += b.norm_sqr(); | ||
| 795 | - let c = *a * b.conj(); | ||
| 796 | - cr += c.re; | ||
| 797 | - ci += c.im; | ||
| 798 | - } | ||
| 799 | - let coh = (cr * cr + ci * ci).sqrt() / (eo * et).sqrt().max(1e-30); | ||
| 800 | - println!( | ||
| 801 | - " band{band:>3}: {:>7.2} dB coh {coh:.4}", | ||
| 802 | - 10.0 * (eo / et.max(1e-30)).log10() | ||
| 803 | - ); | ||
| 804 | - } | ||
| 805 | - } | ||
| 806 | - let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| { | ||
| 807 | - let vals: Vec<f64> = rows | ||
| 808 | - .iter() | ||
| 809 | - .filter(|(b, _)| *b >= lo && *b < hi) | ||
| 810 | - .map(|(_, c)| *c) | ||
| 811 | - .collect(); | ||
| 812 | - if vals.is_empty() { | ||
| 813 | - 0.0 | ||
| 814 | - } else { | ||
| 815 | - vals.iter().sum::<f64>() / vals.len() as f64 | ||
| 816 | - } | ||
| 817 | - }; | ||
| 818 | - println!(" ch{ch} QMF-WITNESS sim-vs-REFERENCE per-band coherence (band, coh):"); | ||
| 819 | - for (b, coh) in &vs_ref { | ||
| 820 | - println!(" band{b:>3}: {coh:.4}"); | ||
| 821 | - } | ||
| 822 | - println!( | ||
| 823 | - " ch{ch} QMF-WITNESS sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", | ||
| 824 | - mean_in(&vs_ref, 14, 28), | ||
| 825 | - mean_in(&vs_ref, 28, 43) | ||
| 826 | - ); | ||
| 827 | - println!(" ch{ch} QMF-WITNESS sim-vs-OURS per-band coherence (band, coh):"); | ||
| 828 | - for (b, coh) in &vs_ours { | ||
| 829 | - println!(" band{b:>3}: {coh:.4}"); | ||
| 830 | - } | ||
| 831 | - println!( | ||
| 832 | - " ch{ch} QMF-WITNESS sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", | ||
| 833 | - mean_in(&vs_ours, 14, 28), | ||
| 834 | - mean_in(&vs_ours, 28, 43) | ||
| 835 | - ); | ||
| 836 | - // (Round-48, Task 4a) the ultimate content-match witness: | ||
| 837 | - // our HF QMF content directly against the reference's, no | ||
| 838 | - // simulator step in between. | ||
| 839 | - println!(" ch{ch} QMF-WITNESS ours-vs-REFERENCE per-band coherence (band, coh):"); | ||
| 840 | - for (b, coh) in &ours_vs_ref { | ||
| 841 | - println!(" band{b:>3}: {coh:.4}"); | ||
| 842 | - } | ||
| 843 | - println!( | ||
| 844 | - " ch{ch} QMF-WITNESS ours-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}", | ||
| 845 | - mean_in(&ours_vs_ref, 14, 28), | ||
| 846 | - mean_in(&ours_vs_ref, 28, 43) | ||
| 847 | - ); | ||
| 848 | - // (Round-46, Task 2) fitted sim-to-reference transfer, one | ||
| 849 | - // representative band per patch plus a spread across the | ||
| 850 | - // strong odd-gap patch (3,28,11) where the QMF witness shows | ||
| 851 | - // sim-vs-reference clearing 0.5. | ||
| 852 | - let fit_bands = [14, 18, 22, 26, 28, 30, 32, 34, 36, 38, 39, 42]; | ||
| 853 | - let fits_ref = hf_patch_transfer_fit(win, twin, &fit_bands, false); | ||
| 854 | - println!(" ch{ch} TASK2 FIT ref[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:"); | ||
| 855 | - for (b, a) in &fits_ref { | ||
| 856 | - println!( | ||
| 857 | - " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})", | ||
| 858 | - a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im | ||
| 859 | - ); | ||
| 860 | - } | ||
| 861 | - // (Round-48, Task 2) same fit, target = ours: side by side | ||
| 862 | - // with the above shows exactly what our transform does to | ||
| 863 | - // the plain copy vs what the reference's does. | ||
| 864 | - let fits_ours = hf_patch_transfer_fit(win, twin, &fit_bands, true); | ||
| 865 | - println!(" ch{ch} TASK2 FIT ours[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:"); | ||
| 866 | - for (b, a) in &fits_ours { | ||
| 867 | - println!( | ||
| 868 | - " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})", | ||
| 869 | - a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im | ||
| 870 | - ); | ||
| 871 | - } | ||
| 872 | - } | ||
| 873 | - println!( | ||
| 874 | - " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}", | ||
| 875 | - c.crossover_hz, c.crossover_hz | ||
| 876 | - ); | ||
| 877 | - if std::env::var("EC_AAC_SBR_DRIFT").is_ok() && n >= 4_096 { | ||
| 878 | - let windows = (n / 4_096).min(20); | ||
| 879 | - let drift = windowed_lag_drift(o, t, oa, ob, windows); | ||
| 880 | - println!(" ch{ch} DRIFT (window_idx, local_lag, |corr|):"); | ||
| 881 | - for (w, (l, cr)) in drift.iter().enumerate() { | ||
| 882 | - println!(" w{w}: lag {l} corr {cr:.4}"); | ||
| 883 | - } | ||
| 884 | - } | ||
| 885 | - // (Round-23, Task 1/3) whole-file corr-vs-time timeline: the | ||
| 886 | - // DRIFT diagnostic above caps at 20 windows (~1.85s) starting at | ||
| 887 | - // the full-band lag offset near sample 0, so it never sees a | ||
| 888 | - // collapse that only appears later in the file. This walks | ||
| 889 | - // every 4096-sample window from that same start to EOF on BOTH | ||
| 890 | - // sides, with its own local lag search per window, so a | ||
| 891 | - // mid-file onset shows up as a specific window index/timestamp | ||
| 892 | - // instead of being averaged away inside one giant WINDOW-sized | ||
| 893 | - // correlation. The mean/min across every window is also the | ||
| 894 | - // TRUE whole-file correlation number (`best_lag_correlation` | ||
| 895 | - // above only ever measures one WINDOW=200_000-sample slice | ||
| 896 | - // starting near the file's first quarter): unlike that one | ||
| 897 | - // fixed-lag figure, this one is immune to a single global lag | ||
| 898 | - // being slightly wrong for a later part of the file. | ||
| 899 | - { | ||
| 900 | - let avail = o.len().saturating_sub(oa).min(t.len().saturating_sub(ob)); | ||
| 901 | - let windows = avail / 4_096; | ||
| 902 | - // The full per-window LOCAL_LAG=+-2000 search inside | ||
| 903 | - // `windowed_lag_drift` costs O(windows * 4001 * 4096) and runs | ||
| 904 | - // ~4min/channel over a whole real-library file -- that walk | ||
| 905 | - // is only needed when actually hunting for a drifting lag | ||
| 906 | - // (EC_AAC_SBR_TIMELINE). By default this block instead reuses | ||
| 907 | - // the already-established global `lag` with NO per-window | ||
| 908 | - // search (O(windows * 4096)), which is cheap and still gives | ||
| 909 | - // an honest whole-file windowed mean/min at that fixed lag. | ||
| 910 | - let timeline: Vec<(i64, f64)> = if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() { | ||
| 911 | - windowed_lag_drift(o, t, oa, ob, windows) | ||
| 912 | - } else { | ||
| 913 | - (0..windows) | ||
| 914 | - .filter_map(|w| { | ||
| 915 | - // `oa`/`ob` (computed above from `lag`) already encode the | ||
| 916 | - // alignment shift via their differing base offsets -- do NOT | ||
| 917 | - // add `lag` again here, that double-applies it and shifts | ||
| 918 | - // every window an extra `lag` samples out of alignment | ||
| 919 | - // (this collapsed the whole-file mean from ~0.96 to ~0.14 | ||
| 920 | - // while leaving the single-WINDOW `full`/`low` numbers, | ||
| 921 | - // which don't go through this path, unaffected). | ||
| 922 | - let base_o = oa + w * 4_096; | ||
| 923 | - let base_t = ob + w * 4_096; | ||
| 924 | - if base_o + 4_096 > o.len() || base_t + 4_096 > t.len() { | ||
| 925 | - return None; | ||
| 926 | - } | ||
| 927 | - Some(( | ||
| 928 | - lag, | ||
| 929 | - correlation(&o[base_o..base_o + 4_096], &t[base_t..base_t + 4_096]), | ||
| 930 | - )) | ||
| 931 | - }) | ||
| 932 | - .collect() | ||
| 933 | - }; | ||
| 934 | - if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() { | ||
| 935 | - println!( | ||
| 936 | - " ch{ch} TIMELINE ({windows} windows, {rate} Hz, window_idx@sec, local_lag, corr):" | ||
| 937 | - ); | ||
| 938 | - for (w, (l, cr)) in timeline.iter().enumerate() { | ||
| 939 | - let t_sec = (oa + w * 4_096) as f64 / f64::from(rate); | ||
| 940 | - println!(" w{w}@{t_sec:.2}s: lag {l} corr {cr:.4}"); | ||
| 941 | - } | ||
| 942 | - } | ||
| 943 | - if !timeline.is_empty() { | ||
| 944 | - let mean = timeline.iter().map(|(_, c)| c).sum::<f64>() / timeline.len() as f64; | ||
| 945 | - let min = timeline.iter().map(|(_, c)| *c).fold(f64::MAX, f64::min); | ||
| 946 | - println!( | ||
| 947 | - " ch{ch} WHOLE-FILE windowed corr: mean {mean:.6} min {min:.6} over {} windows ({:.2}s)", | ||
| 948 | - timeline.len(), | ||
| 949 | - windows as f64 * 4_096.0 / f64::from(rate) | ||
| 950 | - ); | ||
| 951 | - } | ||
| 952 | - } | ||
| 953 | - if std::env::var("EC_AAC_SBR_RESIDUAL_DEBUG").is_ok() { | ||
| 954 | - residual_sideinfo_analysis(o, t, oa, ob, rate, ch); | ||
| 955 | - } | ||
| 956 | - worst_full = worst_full.min(full); | ||
| 957 | - worst_low = worst_low.min(low); | ||
| 958 | - } | ||
| 959 | - checked += 1; | ||
| 960 | - } | ||
| 961 | - assert!(checked > 0, "no plain-SBR real files decoded"); | ||
| 962 | - assert!( | ||
| 963 | - any_at_edge.is_none(), | ||
| 964 | - "lag search hit its bound: {} -- the reported correlations are noise \ | ||
| 965 | - at the search edge, not a measurement", | ||
| 966 | - any_at_edge.unwrap_or_default() | ||
| 967 | - ); | ||
| 968 | - assert!( | ||
| 969 | - worst_full >= 0.999, | ||
| 970 | - "worst full-band correlation {worst_full:.6} < 0.999 bar" | ||
| 971 | - ); | ||
| 972 | - assert!( | ||
| 973 | - worst_low >= 0.9999, | ||
| 974 | - "worst below-crossover correlation {worst_low:.6} < 0.9999 -- the core decode itself regressed" | ||
| 975 | - ); | ||
| 976 | -} | ||
| 977 | - | ||
| 978 | -/// Writes `aus` (raw access units, no ADTS framing) plus `asc` (their own | ||
| 979 | -/// AudioSpecificConfig bytes, unmodified) into a fresh mp4 at `out_path`, so | ||
| 980 | -/// the reference decoder can be pointed at container-native SBR content that | ||
| 981 | -/// is byte-identical to the original stream's access units -- the same | ||
| 982 | -/// `esds`-carries-an-explicit-SBR-config shape `examples/wrap_sbr.rs` proved | ||
| 983 | -/// on synthetic content in round-31, reused here on a REAL file's own AUs as | ||
| 984 | -/// the round-41 Task 1 remux control. | ||
| 985 | -pub(super) fn write_remux(out_path: &Path, asc: &[u8], aus: &[Vec<u8>]) { | ||
| 986 | - let cfg = ec_aac::parse_audio_specific_config(asc).expect("real file's own ASC parses"); | ||
| 987 | - let core_rate = cfg.sample_rate; | ||
| 988 | - let time_base = ec_core::TimeBase::from_rate(core_rate); | ||
| 989 | - let layout = if cfg.channels == 1 { | ||
| 990 | - ec_core::ChannelLayout::Mono | ||
| 991 | - } else { | ||
| 992 | - ec_core::ChannelLayout::Stereo | ||
| 993 | - }; | ||
| 994 | - let mut params = ec_core::CodecParameters::new(CodecId::Aac); | ||
| 995 | - params.extradata = Some(asc.to_vec().into()); | ||
| 996 | - params.media = ec_core::MediaParameters::Audio(ec_core::AudioParameters { | ||
| 997 | - sample_rate: core_rate, | ||
| 998 | - layout, | ||
| 999 | - format: None, | ||
| 1000 | - bits_per_sample: None, | ||
| 1001 | - }); | ||
| 1002 | - let mut info = ec_core::StreamInfo::new(0, time_base, params); | ||
| 1003 | - info.default = true; | ||
| 1004 | - let out = File::create(out_path).expect("remux output creatable"); | ||
| 1005 | - let mut muxer = ec_mp4::Mp4Muxer::new(out).expect("mp4 muxer opens"); | ||
| 1006 | - use ec_core::Muxer as _; | ||
| 1007 | - muxer.add_stream(info).expect("stream declared"); | ||
| 1008 | - for (i, au) in aus.iter().enumerate() { | ||
| 1009 | - let pts = i as i64 * 1024; | ||
| 1010 | - let packet = Packet::new(0, time_base, au.as_slice()) | ||
| 1011 | - .with_pts(pts) | ||
| 1012 | - .with_duration(1024); | ||
| 1013 | - muxer.write_packet(&packet).expect("packet written"); | ||
| 1014 | - } | ||
| 1015 | - muxer.finish().expect("finished"); | ||
| 1016 | -} | ||
| 1017 | - | ||
| 1018 | -/// Mean/min of `bin_level_conviction`'s `direct` column, printed as one | ||
| 1019 | -/// summary line per control pair. | ||
| 1020 | -pub(super) fn report_conviction(label: &str, rows: &[(f64, f64, f64, f64, f64, f64)]) { | ||
| 1021 | - if rows.is_empty() { | ||
| 1022 | - println!(" {label}: no HF bands measured (window too short)"); | ||
| 1023 | - return; | ||
| 1024 | - } | ||
| 1025 | - let vals: Vec<f64> = rows.iter().map(|(_, _, direct, ..)| *direct).collect(); | ||
| 1026 | - let mean = vals.iter().sum::<f64>() / vals.len() as f64; | ||
| 1027 | - let min = vals.iter().cloned().fold(f64::MAX, f64::min); | ||
| 1028 | - println!( | ||
| 1029 | - " {label}: direct-coherence mean {mean:.4} min {min:.4} over {} HF bands", | ||
| 1030 | - vals.len() | ||
| 1031 | - ); | ||
| 1032 | - for (hz, _, direct, ..) in rows { | ||
| 1033 | - println!(" {hz:>6.0}Hz: direct {direct:.4}"); | ||
| 1034 | - } | ||
| 1035 | -} | ||
crates/ec-aac/tests/sbr_real_library/chunk_b.rsdeleted+0 -674
| @@ -1,674 +0,0 @@ | |||
| 1 | -//! SBR real-library checks and probes, part B. | ||
| 2 | - | ||
| 3 | -use super::*; | ||
| 4 | - | ||
| 5 | -/// (Round-41, Task 1) Instrument anchor: before trusting `bin_level_conviction`'s | ||
| 6 | -/// low (~0.15-0.25) HF direct-coherence numbers on reeln as evidence the | ||
| 7 | -/// HF content is genuinely different, confirm the measurement itself reads | ||
| 8 | -/// near 1.0 on pairs that are KNOWN to carry the same content. Three | ||
| 9 | -/// controls: | ||
| 10 | -/// A. ours vs ours, decoded independently twice -- a determinism check on | ||
| 11 | -/// our own decode AND the coherence arithmetic's floor. | ||
| 12 | -/// B. the reference's own PCM from the original file vs from a remux of | ||
| 13 | -/// the SAME access units/ASC through a fresh container -- near-1.0 | ||
| 14 | -/// expected; anything else would implicate the remux path, not SBR. | ||
| 15 | -/// C. the reference's own PCM vs itself read 64 samples later (one QMF | ||
| 16 | -/// slot) -- sanity that `bin_level_conviction`'s STFT hop/window does | ||
| 17 | -/// not itself destroy coherence for equivalent content at a fixed | ||
| 18 | -/// sample offset, the same shape of offset the real `oa`/`ob` alignment | ||
| 19 | -/// applies above. | ||
| 20 | -/// If any control reads below ~0.9 on the HF bands, the instrument -- not | ||
| 21 | -/// the SBR chain -- is the story; every prior round's coherence number would | ||
| 22 | -/// need to be recalibrated against whatever this control actually measures. | ||
| 23 | -#[test] | ||
| 24 | -pub(super) fn sbr_instrument_anchor_controls() { | ||
| 25 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 26 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 27 | - const MIN_BAND: usize = 14; | ||
| 28 | - const TOP_N: usize = 128; // larger than any real band count -- keeps every HF band | ||
| 29 | - | ||
| 30 | - // Control A: ours vs ours, decoded independently twice. | ||
| 31 | - let (ours_a, _, rate) = our_decode(&path, 0).expect("our_decode works"); | ||
| 32 | - let (ours_b, _, _) = our_decode(&path, 0).expect("our_decode works (2nd pass)"); | ||
| 33 | - let n = ours_a[0].len().min(ours_b[0].len()).min(MAX_SAMPLES); | ||
| 34 | - let rows = bin_level_conviction(&ours_a[0][..n], &ours_b[0][..n], rate, MIN_BAND, TOP_N); | ||
| 35 | - report_conviction("A: ours-vs-ours (determinism)", &rows); | ||
| 36 | - | ||
| 37 | - // Control B: reference PCM from the original file vs from a remux of the | ||
| 38 | - // SAME access units/ASC. | ||
| 39 | - let (asc, aus) = extract_aac_track(&path, 0).expect("track extracts"); | ||
| 40 | - let remux_path = std::env::temp_dir().join("ec_aac_sbr_instrument_anchor_remux.mp4"); | ||
| 41 | - write_remux(&remux_path, &asc, &aus); | ||
| 42 | - let theirs_orig = ffmpeg_decode(&path, 0, 2); | ||
| 43 | - let theirs_remux = ffmpeg_decode(&remux_path, 0, 2); | ||
| 44 | - let _ = std::fs::remove_file(&remux_path); | ||
| 45 | - let n = theirs_orig[0] | ||
| 46 | - .len() | ||
| 47 | - .min(theirs_remux[0].len()) | ||
| 48 | - .min(MAX_SAMPLES); | ||
| 49 | - let (lag_b, _) = best_lag_correlation(&theirs_orig[0][..n], &theirs_remux[0][..n]); | ||
| 50 | - let (oa, ob) = if lag_b >= 0 { | ||
| 51 | - (0usize, lag_b as usize) | ||
| 52 | - } else { | ||
| 53 | - ((-lag_b) as usize, 0usize) | ||
| 54 | - }; | ||
| 55 | - let win = n.saturating_sub(oa.max(ob)); | ||
| 56 | - let rows = bin_level_conviction( | ||
| 57 | - &theirs_orig[0][oa..oa + win], | ||
| 58 | - &theirs_remux[0][ob..ob + win], | ||
| 59 | - rate, | ||
| 60 | - MIN_BAND, | ||
| 61 | - TOP_N, | ||
| 62 | - ); | ||
| 63 | - report_conviction( | ||
| 64 | - &format!("B: reference-vs-reference-through-remux (lag {lag_b})"), | ||
| 65 | - &rows, | ||
| 66 | - ); | ||
| 67 | - | ||
| 68 | - // Control C: reference PCM vs itself read 64 samples later (one QMF | ||
| 69 | - // slot) -- both slices are the SAME underlying samples, just offset. | ||
| 70 | - let t = &theirs_orig[0][..MAX_SAMPLES.min(theirs_orig[0].len())]; | ||
| 71 | - if t.len() > 64 { | ||
| 72 | - let rows = bin_level_conviction(&t[64..], &t[..t.len() - 64], rate, MIN_BAND, TOP_N); | ||
| 73 | - report_conviction("C: reference vs reference, 64-sample offset", &rows); | ||
| 74 | - } | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -/// (Round-41, Task 2) Actual injected HF noise energy, measured as OUTPUT | ||
| 78 | -/// energy rather than trusted from either side of round-24's contradiction: | ||
| 79 | -/// `noise_fraction_table` bookkept a 0.37-0.39 noise share from the | ||
| 80 | -/// transmitted envelope/noise split, while separately zeroing the injected | ||
| 81 | -/// noise (`EC_AAC_SBR_NOISE_ZERO`, which only skips the PCM addition in | ||
| 82 | -/// `sbr_env::adjust`, not the bookkeeping) was found to change full-band | ||
| 83 | -/// correlation by <0.001 -- both cannot be true of the same signal. This | ||
| 84 | -/// decodes reeln twice (noise on, then off) and reads the per-HF-band | ||
| 85 | -/// `bin_level_conviction` energy delta between them as the fraction noise | ||
| 86 | -/// ACTUALLY realizes in the output, independent of either prior claim. | ||
| 87 | -#[test] | ||
| 88 | -pub(super) fn sbr_actual_noise_fraction() { | ||
| 89 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 90 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 91 | - const MIN_BAND: usize = 14; | ||
| 92 | - const TOP_N: usize = 128; | ||
| 93 | - | ||
| 94 | - let (ours_on, _, rate) = { | ||
| 95 | - let _zero = ec_aac::knobs::set_sbr_noise_zero(Some(false)); | ||
| 96 | - let _fraction = ec_aac::knobs::set_sbr_noise_fraction(Some(true)); | ||
| 97 | - our_decode(&path, 0).expect("our_decode works (noise on)") | ||
| 98 | - }; | ||
| 99 | - let bookkept = ec_aac::noise_fraction_table(); | ||
| 100 | - let (ours_off, _, _) = { | ||
| 101 | - let _zero = ec_aac::knobs::set_sbr_noise_zero(Some(true)); | ||
| 102 | - let _fraction = ec_aac::knobs::set_sbr_noise_fraction(Some(false)); | ||
| 103 | - our_decode(&path, 0).expect("our_decode works (noise zeroed)") | ||
| 104 | - }; | ||
| 105 | - | ||
| 106 | - let theirs = ffmpeg_decode(&path, 0, ours_on.len()); | ||
| 107 | - let n = ours_on[0].len().min(ours_off[0].len()).min(MAX_SAMPLES); | ||
| 108 | - let on = &ours_on[0][..n]; | ||
| 109 | - let off = &ours_off[0][..n]; | ||
| 110 | - | ||
| 111 | - // Per-band actual energy delta: `energy` in `bin_level_conviction`'s row | ||
| 112 | - // is always the FIRST argument's own band energy, so swap argument order | ||
| 113 | - // between the two calls to read both sides' energies at the SAME band | ||
| 114 | - // set (TOP_N kept above any real band count so both calls select every | ||
| 115 | - // band, not just each side's own top few). | ||
| 116 | - let rows_on = bin_level_conviction(on, off, rate, MIN_BAND, TOP_N); | ||
| 117 | - let rows_off = bin_level_conviction(off, on, rate, MIN_BAND, TOP_N); | ||
| 118 | - // (Round-42, Task 2) This `band_hz` feeds the `band` used below to look | ||
| 119 | - // up `bookkept` (`noise_fraction_table()`'s QMF band index, `tables.kx` | ||
| 120 | - // .. `tables.k2`, width `rate/128` -- 64 QMF bands over the SBR | ||
| 121 | - // Nyquist, per the NOISE-FRACTION-DEBUG dump above). It is NOT | ||
| 122 | - // `bin_level_conviction`'s own internal FFT-band scale (`rate/256`, | ||
| 123 | - // used correctly elsewhere in this file for THAT function's own rows). | ||
| 124 | - // Using `rate/256` here silently doubled every looked-up `band` index, | ||
| 125 | - // so every real band above roughly half of `k2` missed the table and | ||
| 126 | - // read back a false 0.0 bookkept fraction -- a test-side lookup bug, | ||
| 127 | - // not a decoder coverage gap (verified: `noise_fraction_table()` itself | ||
| 128 | - // has nonzero entries for QMF bands up to `k2`). | ||
| 129 | - let band_hz = f64::from(rate) / 128.0; | ||
| 130 | - let kx_band = bookkept.iter().map(|(b, ..)| *b).min().unwrap_or(0); | ||
| 131 | - println!( | ||
| 132 | - " (crossover: QMF band {kx_band}, {:.0} Hz -- rows below it are core-decoded and excluded from the total)", | ||
| 133 | - kx_band as f64 * band_hz | ||
| 134 | - ); | ||
| 135 | - println!( | ||
| 136 | - " ACTUAL noise fraction (band_hz, energy_on, energy_off, actual_fraction, bookkept_fraction):" | ||
| 137 | - ); | ||
| 138 | - let mut sum_on = 0.0f64; | ||
| 139 | - let mut sum_delta = 0.0f64; | ||
| 140 | - for (hz, e_on, ..) in &rows_on { | ||
| 141 | - let e_off = rows_off | ||
| 142 | - .iter() | ||
| 143 | - .find(|(hz2, ..)| (hz2 - hz).abs() < 1.0) | ||
| 144 | - .map(|(_, e, ..)| *e) | ||
| 145 | - .unwrap_or(0.0); | ||
| 146 | - let actual = if *e_on > 0.0 { | ||
| 147 | - (e_on - e_off) / e_on | ||
| 148 | - } else { | ||
| 149 | - 0.0 | ||
| 150 | - }; | ||
| 151 | - let band = (hz / band_hz).round() as usize; | ||
| 152 | - let book = bookkept | ||
| 153 | - .iter() | ||
| 154 | - .find(|(b, ..)| *b == band) | ||
| 155 | - .map(|(_, s, n, _)| if s + n > 0.0 { n / (s + n) } else { 0.0 }) | ||
| 156 | - .unwrap_or(0.0); | ||
| 157 | - println!( | ||
| 158 | - " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}" | ||
| 159 | - ); | ||
| 160 | - // HF ONLY (round-61): `MIN_BAND` (14, ~2412 Hz at 44.1k) sits BELOW | ||
| 161 | - // this stream's crossover (~4500 Hz), so the row list opens with a | ||
| 162 | - // dozen core-decoded bands that carry an order of magnitude more | ||
| 163 | - // energy than the SBR-generated ones (6.4e4 vs ~5e3) and, by | ||
| 164 | - // definition, zero injected noise. Summing them into a "whole-HF" | ||
| 165 | - // ratio dilutes it toward zero -- that is how this metric read | ||
| 166 | - // 0.0397 while every band above the crossover was realizing | ||
| 167 | - // 0.15-0.27. The crossover comes from the bookkeeping table itself | ||
| 168 | - // (its lowest QMF band IS `kx`), so it tracks the stream instead of | ||
| 169 | - // a constant that a QMF-mapping change can invalidate. | ||
| 170 | - if band < kx_band { | ||
| 171 | - continue; | ||
| 172 | - } | ||
| 173 | - sum_on += e_on; | ||
| 174 | - sum_delta += e_on - e_off; | ||
| 175 | - } | ||
| 176 | - let actual_total = if sum_on > 0.0 { | ||
| 177 | - sum_delta / sum_on | ||
| 178 | - } else { | ||
| 179 | - 0.0 | ||
| 180 | - }; | ||
| 181 | - println!(" ACTUAL whole-HF noise fraction: {actual_total:.4}"); | ||
| 182 | - | ||
| 183 | - // Corr re-verification: does zeroing the injected noise move full-band | ||
| 184 | - // correlation against the reference, and by how much (round-24 claimed | ||
| 185 | - // <0.001). | ||
| 186 | - let (_, corr_on) = best_lag_correlation(on, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]); | ||
| 187 | - let (_, corr_off) = best_lag_correlation(off, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]); | ||
| 188 | - println!( | ||
| 189 | - " full-band corr: noise-on {corr_on:.6} noise-off {corr_off:.6} delta {:.6}", | ||
| 190 | - corr_off - corr_on | ||
| 191 | - ); | ||
| 192 | - | ||
| 193 | - // (Round-42, Task 1/3 acceptance) Two real accounting bugs fixed this | ||
| 194 | - // round pushed the realized whole-HF fraction 0.1325 -> 0.1787 (reeln, | ||
| 195 | - // this same measurement): the boost pass was conserving the cell's FULL | ||
| 196 | - // envelope target against a signal-only realized sum (now conserves | ||
| 197 | - // total-vs-total, matching the reference algorithm's known | ||
| 198 | - // E_orig/E_curr+Q_M boost ratio), and `noise_amps` divided an | ||
| 199 | - // already-per-sample `noise_here` by the cell's QMF-band width a SECOND | ||
| 200 | - // time (removed) -- worse at wide high-frequency sfb cells, which is | ||
| 201 | - // exactly where the pre-fix gap was largest. | ||
| 202 | - // | ||
| 203 | - // The charter's ±0.05-of-bookkept (~0.38) target is NOT met by this | ||
| 204 | - // fix alone (round-43 investigated why, with `EC_AAC_SBR_CELLDUMP` in | ||
| 205 | - // `sbr_env::adjust`): `sbr_env::adjust`'s per-cell signal/noise split | ||
| 206 | - // is NOT the culprit -- corrected-band dumps (the charter's quoted | ||
| 207 | - // "6718/6891/7063Hz" and "8.5-13kHz decaying" bands turned out to be | ||
| 208 | - // mislabeled by a factor of two, this file's true SBR band spacing is | ||
| 209 | - // `rate/128` = 344.5Hz not the 172.3Hz FFT-analysis spacing those Hz | ||
| 210 | - // labels come from) show `adjust` injecting 40-85% noise share in the | ||
| 211 | - // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved. | ||
| 212 | - // | ||
| 213 | - // (Round-44) Round-43's "essentially 0% of injected energy lands back | ||
| 214 | - // in the source subband" reading of | ||
| 215 | - // `synthesis_energy_gain_for_white_noise_excitation` was itself a test | ||
| 216 | - // bug, not a `Synthesis` defect: that harness measured its in-band FFT | ||
| 217 | - // window at `k0/SYNTHESIS_BANDS`, but band k's passband is centred at | ||
| 218 | - // `(k+0.5)*omega_step` with `omega_step = pi/(2*SYNTHESIS_BANDS)` -- | ||
| 219 | - // HALF that fraction of Nyquist -- so the window sat on the image | ||
| 220 | - // region, not the signal. Corrected, a raw i.i.d.-per-slot draw already | ||
| 221 | - // lands ~0.49 of its own energy in its home subband's own frequency | ||
| 222 | - // range (not 0%), and a short slot-domain boxcar (`sbr_env::NoiseGen`'s | ||
| 223 | - // new `LOWPASS_TAPS = 2`) raises that to ~0.61 while staying spread | ||
| 224 | - // across the band (not collapsing to a residual tone) -- see the | ||
| 225 | - // harness's `synthesis_energy_gain_for_lowpassed_noise_excitation`. | ||
| 226 | - // That shape fix is real (an i.i.d. draw genuinely was less | ||
| 227 | - // band-faithful than it needed to be, and now is not), but re-measuring | ||
| 228 | - // THIS whole-HF metric after shipping it moved `actual_total` by <0.002 | ||
| 229 | - // (0.1787 -> 0.1770, i.e. flat) -- because this metric sums the noise | ||
| 230 | - // energy DELTA across the whole swept HF spectrum, and energy an | ||
| 231 | - // i.i.d. draw aliased to a NEIGHBOURING QMF band still lands somewhere | ||
| 232 | - // inside that same swept HF range, so it was never actually excluded | ||
| 233 | - // from this particular sum. The ~0.38 bookkept vs ~0.18 actual gap is | ||
| 234 | - // therefore NOT a spectral-shape/aliasing defect (refuting round-43's | ||
| 235 | - // framing) -- it is a genuine energy shortfall, and per-band coherence | ||
| 236 | - // sits well below even the ACTUAL-fraction ceiling | ||
| 237 | - // (`sqrt(1 - f)`; ~0.15-0.20 measured vs. ~0.90 predicted at | ||
| 238 | - // `f ~= 0.177`, see `EC_AAC_SBR_PARITY_SPLIT`), meaning most of the | ||
| 239 | - // remaining HF correlation shortfall is a content defect independent of | ||
| 240 | - // noise level. Deferred: locating that energy shortfall and the | ||
| 241 | - // content defect, budget did not reach either this round (open, see | ||
| 242 | - // ledger). Floor tightened from round-42's 0.15 to the level this | ||
| 243 | - // fix's shape change actually lands at (0.177, both before and after), | ||
| 244 | - // with margin for run-to-run FFT/decode jitter. | ||
| 245 | - assert!( | ||
| 246 | - actual_total > 0.17, | ||
| 247 | - "whole-HF realized noise fraction regressed to {actual_total:.4} \ | ||
| 248 | - (round-44 fix floor is 0.17; measured 0.1770 post-shape-fix, \ | ||
| 249 | - 0.1787 pre-fix -- shape does not move this metric, see doc above)" | ||
| 250 | - ); | ||
| 251 | -} | ||
| 252 | - | ||
| 253 | -/// Discriminator instrument: one row per stream of the SBR header/frame | ||
| 254 | -/// features actually parsed from its first ~20 `sbr_data()` frames, next to | ||
| 255 | -/// that stream's own pass/fail correlation vs the reference decoder -- | ||
| 256 | -/// looking for which feature(s) separate the two known-PASS streams | ||
| 257 | -/// (reeln, synthetic 48k HE) from the two known-FAIL families (FMJ, | ||
| 258 | -/// synthetic 44.1k HE). Gated on the real files / fixture directory being | ||
| 259 | -/// present, same as the tests it borrows machinery from; skips loudly, | ||
| 260 | -/// generates nothing. | ||
| 261 | -#[test] | ||
| 262 | -pub(super) fn sbr_header_feature_table() { | ||
| 263 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 264 | - struct Row { | ||
| 265 | - label: String, | ||
| 266 | - path: PathBuf, | ||
| 267 | - aac_stream: usize, | ||
| 268 | - ffmpeg_stream: usize, | ||
| 269 | - } | ||
| 270 | - let rows: Vec<Row> = candidates() | ||
| 271 | - .into_iter() | ||
| 272 | - .map(|c| Row { | ||
| 273 | - label: c | ||
| 274 | - .path | ||
| 275 | - .file_stem() | ||
| 276 | - .map(|s| s.to_string_lossy().into_owned()) | ||
| 277 | - .unwrap_or_default(), | ||
| 278 | - path: c.path, | ||
| 279 | - aac_stream: c.aac_stream, | ||
| 280 | - ffmpeg_stream: c.ffmpeg_stream, | ||
| 281 | - }) | ||
| 282 | - .collect(); | ||
| 283 | - let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); | ||
| 284 | - const WIDE_LAG_MAX: i64 = 20_000; | ||
| 285 | - println!( | ||
| 286 | - "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10} {:>6}", | ||
| 287 | - "stream", | ||
| 288 | - "rate", | ||
| 289 | - "kx", | ||
| 290 | - "k2", | ||
| 291 | - "xovr", | ||
| 292 | - "sfrq", | ||
| 293 | - "efrq", | ||
| 294 | - "fscl", | ||
| 295 | - "ascl", | ||
| 296 | - "nbnd", | ||
| 297 | - "lbnd", | ||
| 298 | - "lgn", | ||
| 299 | - "ifrq", | ||
| 300 | - "smooth", | ||
| 301 | - "envs", | ||
| 302 | - "invf", | ||
| 303 | - "harm", | ||
| 304 | - "df%", | ||
| 305 | - "corr" | ||
| 306 | - ); | ||
| 307 | - for r in &rows { | ||
| 308 | - let before = ec_aac::sbr_sideinfo_log().len(); | ||
| 309 | - let (ours, sbr, our_rate) = our_decode(&r.path, r.aac_stream).expect("decode"); | ||
| 310 | - if sbr != ec_aac::SbrSupport::V1 { | ||
| 311 | - continue; | ||
| 312 | - } | ||
| 313 | - let log = ec_aac::sbr_sideinfo_log(); | ||
| 314 | - let frames: Vec<_> = log[before..] | ||
| 315 | - .iter() | ||
| 316 | - .filter(|row| row.ch == 0) | ||
| 317 | - .take(20) | ||
| 318 | - .collect(); | ||
| 319 | - assert!(!frames.is_empty(), "{}: no sideinfo rows captured", r.label); | ||
| 320 | - let f0 = &frames[0]; | ||
| 321 | - let mut env_counts: std::collections::BTreeMap<usize, usize> = Default::default(); | ||
| 322 | - let mut invf_seen: std::collections::BTreeSet<u8> = Default::default(); | ||
| 323 | - let mut any_harmonic = false; | ||
| 324 | - let mut df_total = 0usize; | ||
| 325 | - let mut df_ones = 0usize; | ||
| 326 | - for row in &frames { | ||
| 327 | - *env_counts | ||
| 328 | - .entry(row.t_env.len().saturating_sub(1)) | ||
| 329 | - .or_default() += 1; | ||
| 330 | - invf_seen.extend(&row.invf_mode); | ||
| 331 | - if row | ||
| 332 | - .add_harmonic | ||
| 333 | - .as_ref() | ||
| 334 | - .is_some_and(|h| h.iter().any(|&v| v != 0)) | ||
| 335 | - { | ||
| 336 | - any_harmonic = true; | ||
| 337 | - } | ||
| 338 | - df_total += row.df_env.len() + row.df_noise.len(); | ||
| 339 | - df_ones += row | ||
| 340 | - .df_env | ||
| 341 | - .iter() | ||
| 342 | - .chain(&row.df_noise) | ||
| 343 | - .filter(|&&b| b != 0) | ||
| 344 | - .count(); | ||
| 345 | - } | ||
| 346 | - let df_pct = if df_total > 0 { | ||
| 347 | - 100.0 * df_ones as f64 / df_total as f64 | ||
| 348 | - } else { | ||
| 349 | - 0.0 | ||
| 350 | - }; | ||
| 351 | - let envs_hist: String = env_counts | ||
| 352 | - .iter() | ||
| 353 | - .map(|(k, v)| format!("{k}x{v}")) | ||
| 354 | - .collect::<Vec<_>>() | ||
| 355 | - .join(","); | ||
| 356 | - let invf_str: String = invf_seen | ||
| 357 | - .iter() | ||
| 358 | - .map(|v| v.to_string()) | ||
| 359 | - .collect::<Vec<_>>() | ||
| 360 | - .join(""); | ||
| 361 | - let theirs = ffmpeg_decode(&r.path, r.ffmpeg_stream, ours.len()); | ||
| 362 | - let (_, corr) = best_lag_correlation_wide(&ours[0], &theirs[0], WIDE_LAG_MAX); | ||
| 363 | - println!( | ||
| 364 | - "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10.1} {:>6.3}", | ||
| 365 | - r.label, | ||
| 366 | - our_rate, | ||
| 367 | - f0.kx, | ||
| 368 | - f0.k2, | ||
| 369 | - f0.xover_band, | ||
| 370 | - f0.start_freq, | ||
| 371 | - f0.stop_freq, | ||
| 372 | - f0.freq_scale, | ||
| 373 | - f0.alter_scale, | ||
| 374 | - f0.noise_bands, | ||
| 375 | - f0.limiter_bands, | ||
| 376 | - f0.limiter_gains, | ||
| 377 | - f0.interpol_freq, | ||
| 378 | - f0.smoothing_mode, | ||
| 379 | - envs_hist, | ||
| 380 | - invf_str, | ||
| 381 | - any_harmonic, | ||
| 382 | - df_pct, | ||
| 383 | - corr | ||
| 384 | - ); | ||
| 385 | - println!(" patches (frame0): {:?}", f0.patch_lengths); | ||
| 386 | - } | ||
| 387 | -} | ||
| 388 | - | ||
| 389 | -/// Round (sbr-per-au): per-AU localization. Decodes the same AU list through | ||
| 390 | -/// (a) the core-only decoder and (b) the full SBR chain, tracks each AU's | ||
| 391 | -/// sample range in both output streams as it goes (so a per-AU decode | ||
| 392 | -/// failure on either side does not desync the mapping), aligns the two | ||
| 393 | -/// streams ONCE in the core's own native rate domain (same decimate | ||
| 394 | -/// convention `synthetic_heaac_matrix`'s `ours_v_core` row already trusts), | ||
| 395 | -/// then re-uses that single lag for every AU's own low-band correlation. | ||
| 396 | -/// Prints the first 5 AUs below 0.9 with that AU's SBR side-info (source/ | ||
| 397 | -/// envelope count/freq_res/kx/k2) so a per-frame trigger (e.g. `hold` | ||
| 398 | -/// frames, a specific `freq_res`) shows up directly instead of needing a | ||
| 399 | -/// second pass. If the first divergent AU is 0, that is reported explicitly | ||
| 400 | -/// -- divergence from the very first AU means a per-stream setup mismatch, | ||
| 401 | -/// not a per-frame trigger. | ||
| 402 | -pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) { | ||
| 403 | - let (asc, aus) = extract_aac_track(path, aac_stream).expect("extract_aac_track"); | ||
| 404 | - let full_cfg = parse_audio_specific_config(&asc).expect("asc parse"); | ||
| 405 | - assert!(full_cfg.sbr_present, "{label}: no SBR"); | ||
| 406 | - let mut core_cfg = full_cfg.clone(); | ||
| 407 | - core_cfg.sbr_present = false; | ||
| 408 | - core_cfg.ps_present = false; | ||
| 409 | - core_cfg.extension_sample_rate = None; | ||
| 410 | - let core_rate = core_cfg.sample_rate; | ||
| 411 | - let mut core_dec = AacDecoder::with_config(core_cfg); | ||
| 412 | - let mut full_dec = AacDecoder::with_config(full_cfg); | ||
| 413 | - let full_rate = full_dec.output_sample_rate().unwrap_or(core_rate * 2); | ||
| 414 | - | ||
| 415 | - struct AuInfo { | ||
| 416 | - core_range: (usize, usize), | ||
| 417 | - side: Option<ec_aac::SbrSideInfoRow>, | ||
| 418 | - } | ||
| 419 | - let mut core_ch0: Vec<f32> = Vec::new(); | ||
| 420 | - let mut full_ch0: Vec<f32> = Vec::new(); | ||
| 421 | - let mut aus_info: Vec<AuInfo> = Vec::new(); | ||
| 422 | - for au in aus.iter().take(1_500) { | ||
| 423 | - let side_before = ec_aac::sbr_sideinfo_log().len(); | ||
| 424 | - let cs = core_ch0.len(); | ||
| 425 | - if let Ok(f) = core_dec.decode(au, None) { | ||
| 426 | - let ch = usize::from(f.channels).max(1); | ||
| 427 | - core_ch0.extend(f.samples.iter().step_by(ch).copied()); | ||
| 428 | - } | ||
| 429 | - let ce = core_ch0.len(); | ||
| 430 | - if let Ok(f) = full_dec.decode(au, None) { | ||
| 431 | - let ch = usize::from(f.channels).max(1); | ||
| 432 | - full_ch0.extend(f.samples.iter().step_by(ch).copied()); | ||
| 433 | - } | ||
| 434 | - let side = ec_aac::sbr_sideinfo_log()[side_before..] | ||
| 435 | - .iter() | ||
| 436 | - .find(|r| r.ch == 0) | ||
| 437 | - .cloned(); | ||
| 438 | - aus_info.push(AuInfo { | ||
| 439 | - core_range: (cs, ce), | ||
| 440 | - side, | ||
| 441 | - }); | ||
| 442 | - if full_ch0.len() > MAX_SAMPLES { | ||
| 443 | - break; | ||
| 444 | - } | ||
| 445 | - } | ||
| 446 | - assert!( | ||
| 447 | - !core_ch0.is_empty() && !full_ch0.is_empty(), | ||
| 448 | - "{label}: empty decode (core {} full {})", | ||
| 449 | - core_ch0.len(), | ||
| 450 | - full_ch0.len() | ||
| 451 | - ); | ||
| 452 | - | ||
| 453 | - // Same convention `full_chain_low_band_matches_own_core` already | ||
| 454 | - // validated (0.9967 on reeln): naive nearest-neighbor 2x-upsample | ||
| 455 | - // the core into the full-rate domain, low-pass both well under the core | ||
| 456 | - // Nyquist. The decimate-into-core-rate convention `synthetic_heaac_matrix` | ||
| 457 | - // uses for its own `ours_v_core` diagnostic column was tried first here | ||
| 458 | - // and reads badly (~-0.19) even on reeln, which is known-good -- | ||
| 459 | - // that column is evidently not a reliable self-consistency probe on its | ||
| 460 | - // own, so this per-AU tool anchors on the convention independently | ||
| 461 | - // proven correct instead. | ||
| 462 | - let up: Vec<f32> = core_ch0.iter().flat_map(|&s| [s, s]).collect(); | ||
| 463 | - let cutoff = f64::from(core_rate) * 0.4; | ||
| 464 | - let ol = lowpass(&full_ch0, full_rate, cutoff); | ||
| 465 | - let ul = lowpass(&up, full_rate, cutoff); | ||
| 466 | - const WIDE_LAG_MAX: i64 = 20_000; | ||
| 467 | - let (lag, align_corr) = best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX); | ||
| 468 | - println!( | ||
| 469 | - "{label}: core={core_rate}Hz full={full_rate}Hz global align (upsampled full-rate domain) lag={lag} corr={align_corr:.6}" | ||
| 470 | - ); | ||
| 471 | - | ||
| 472 | - let mut shown = 0usize; | ||
| 473 | - let mut first_divergent: Option<usize> = None; | ||
| 474 | - for (i, info) in aus_info.iter().enumerate() { | ||
| 475 | - let (cs, ce) = info.core_range; | ||
| 476 | - if ce <= cs { | ||
| 477 | - continue; | ||
| 478 | - } | ||
| 479 | - // core_range is in core-domain sample counts; the upsampled/lowpassed | ||
| 480 | - // arrays are at full rate, so the AU's window there is 2x as wide. | ||
| 481 | - let fs = cs * 2; | ||
| 482 | - let fe = ce * 2; | ||
| 483 | - let ds = match usize::try_from(fs as i64 + lag) { | ||
| 484 | - Ok(v) => v, | ||
| 485 | - Err(_) => continue, | ||
| 486 | - }; | ||
| 487 | - let de = ds + (fe - fs); | ||
| 488 | - if de > ul.len() || fe > ol.len() { | ||
| 489 | - break; | ||
| 490 | - } | ||
| 491 | - let c = correlation(&ol[fs..fe], &ul[ds..de]); | ||
| 492 | - if c < 0.9 { | ||
| 493 | - if first_divergent.is_none() { | ||
| 494 | - first_divergent = Some(i); | ||
| 495 | - } | ||
| 496 | - if shown < 5 { | ||
| 497 | - println!(" AU {i}: low-band corr={c:.6} side={:?}", info.side); | ||
| 498 | - shown += 1; | ||
| 499 | - } | ||
| 500 | - } | ||
| 501 | - } | ||
| 502 | - match first_divergent { | ||
| 503 | - Some(0) => println!( | ||
| 504 | - "{label}: divergence starts at AU 0 -- per-STREAM setup mismatch, not a per-frame trigger" | ||
| 505 | - ), | ||
| 506 | - Some(i) => println!("{label}: first divergent AU = {i}"), | ||
| 507 | - None => println!("{label}: no AU below 0.9 corr in the probed window"), | ||
| 508 | - } | ||
| 509 | -} | ||
| 510 | - | ||
| 511 | -#[test] | ||
| 512 | -pub(super) fn per_au_low_band_divergence() { | ||
| 513 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 514 | - let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); | ||
| 515 | - for c in &candidates() { | ||
| 516 | - per_au_low_band_probe(&c.path.display().to_string(), &c.path, c.aac_stream); | ||
| 517 | - } | ||
| 518 | -} | ||
| 519 | - | ||
| 520 | -/// Coordinator follow-up: prints what `parse_audio_specific_config` actually | ||
| 521 | -/// returns for a candidate's real ASC bytes (object/rate/sf_index/ | ||
| 522 | -/// sbr_present/extension_sample_rate), what `AacDecoder` reports back | ||
| 523 | -/// (`SbrSupport`, `output_sample_rate`) from those parsed fields, then | ||
| 524 | -/// re-decodes the SAME AU list through a HAND-BUILT explicit | ||
| 525 | -/// `AudioSpecificConfig` (object_type=5, known core/ext rates) instead of | ||
| 526 | -/// the parsed one -- if that jumps the correlations to ~1, the parsed | ||
| 527 | -/// config (or something object_type-conditioned at runtime) is the defect, | ||
| 528 | -/// not the SBR DSP chain itself. Also re-runs `full_chain_low_band_matches_ | ||
| 529 | -/// own_core`'s FMJ probe with `WIDE_LAG_MAX` raised to 100_000. | ||
| 530 | -#[test] | ||
| 531 | -pub(super) fn probe_explicit_config_and_wide_lag() { | ||
| 532 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 533 | - fn decode_with(cfg: ec_aac::AudioSpecificConfig, aus: &[Vec<u8>]) -> (Vec<Vec<f32>>, u32) { | ||
| 534 | - let rate = match (cfg.sbr_present, cfg.ps_present) { | ||
| 535 | - (true, false) => cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2), | ||
| 536 | - _ => cfg.sample_rate, | ||
| 537 | - }; | ||
| 538 | - let mut d = AacDecoder::with_config(cfg); | ||
| 539 | - let mut planes: Vec<Vec<f32>> = Vec::new(); | ||
| 540 | - for au in aus { | ||
| 541 | - let Ok(f) = d.decode(au, None) else { continue }; | ||
| 542 | - let ch = usize::from(f.channels); | ||
| 543 | - if ch == 0 { | ||
| 544 | - continue; | ||
| 545 | - } | ||
| 546 | - if planes.is_empty() { | ||
| 547 | - planes = vec![Vec::new(); ch]; | ||
| 548 | - } | ||
| 549 | - for (i, v) in f.samples.iter().enumerate() { | ||
| 550 | - planes[i % ch].push(*v); | ||
| 551 | - } | ||
| 552 | - if planes[0].len() >= MAX_SAMPLES { | ||
| 553 | - break; | ||
| 554 | - } | ||
| 555 | - } | ||
| 556 | - (planes, rate) | ||
| 557 | - } | ||
| 558 | - | ||
| 559 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 560 | - let (label, aac_stream, ffmpeg_stream, core_sf_index, core_rate, ext_rate, channels) = | ||
| 561 | - ("al_sbr_cm_48_2", 0usize, 0usize, 6u8, 24_000u32, 0u32, 2u16); | ||
| 562 | - { | ||
| 563 | - let (asc, aus) = extract_aac_track(&path, aac_stream).expect("extract"); | ||
| 564 | - let parsed = parse_audio_specific_config(&asc); | ||
| 565 | - println!("{label}: asc={asc:02x?} parsed={parsed:?}"); | ||
| 566 | - let parsed_cfg = parsed.expect("asc parse"); | ||
| 567 | - let d = AacDecoder::with_config(parsed_cfg.clone()); | ||
| 568 | - println!( | ||
| 569 | - " runtime: sbr_support={:?} output_sample_rate={:?}", | ||
| 570 | - d.sbr_support(), | ||
| 571 | - d.output_sample_rate() | ||
| 572 | - ); | ||
| 573 | - | ||
| 574 | - // Hand-built EXPLICIT config: object_type=5 (SBR), known core/ext | ||
| 575 | - // rates, sbr_present forced true regardless of what the real ASC | ||
| 576 | - // parsed to. | ||
| 577 | - let ext = if ext_rate == 0 { | ||
| 578 | - parsed_cfg.extension_sample_rate.unwrap_or(core_rate * 2) | ||
| 579 | - } else { | ||
| 580 | - ext_rate | ||
| 581 | - }; | ||
| 582 | - let hand_cfg = ec_aac::AudioSpecificConfig { | ||
| 583 | - object_type: ec_aac::AOT_SBR, | ||
| 584 | - sample_rate: core_rate, | ||
| 585 | - sf_index: core_sf_index, | ||
| 586 | - channels, | ||
| 587 | - channel_config: channels as u8, | ||
| 588 | - sbr_present: true, | ||
| 589 | - ps_present: false, | ||
| 590 | - extension_sample_rate: Some(ext), | ||
| 591 | - pce: Vec::new(), | ||
| 592 | - }; | ||
| 593 | - let (hand_planes, hand_rate) = decode_with(hand_cfg.clone(), &aus); | ||
| 594 | - assert!(!hand_planes.is_empty(), "{label}: hand-built config decoded no channels"); | ||
| 595 | - // Own-core self-consistency (upsample+lowpass convention). | ||
| 596 | - let core_cfg = ec_aac::AudioSpecificConfig { | ||
| 597 | - sbr_present: false, | ||
| 598 | - ps_present: false, | ||
| 599 | - extension_sample_rate: None, | ||
| 600 | - pce: Vec::new(), | ||
| 601 | - ..hand_cfg.clone() | ||
| 602 | - }; | ||
| 603 | - let (core_planes, _) = decode_with(core_cfg, &aus); | ||
| 604 | - if !core_planes.is_empty() { | ||
| 605 | - let up: Vec<f32> = core_planes[0].iter().flat_map(|&s| [s, s]).collect(); | ||
| 606 | - let cutoff = f64::from(core_rate) * 0.4; | ||
| 607 | - let ol = lowpass(&hand_planes[0], hand_rate, cutoff); | ||
| 608 | - let ul = lowpass(&up, hand_rate, cutoff); | ||
| 609 | - let (lag, corr) = best_lag_correlation_wide(&ol, &ul, 100_000); | ||
| 610 | - println!( | ||
| 611 | - " hand-built explicit config: low-band vs own core: lag={lag} corr={corr:.6}" | ||
| 612 | - ); | ||
| 613 | - } | ||
| 614 | - let theirs = ffmpeg_decode(&path, ffmpeg_stream, hand_planes.len()); | ||
| 615 | - if let (Some(o), Some(t)) = (hand_planes.first(), theirs.first()) { | ||
| 616 | - let (lag, corr) = best_lag_correlation_wide(o, t, 100_000); | ||
| 617 | - println!( | ||
| 618 | - " hand-built explicit config: full-band vs reference: lag={lag} corr={corr:.6}" | ||
| 619 | - ); | ||
| 620 | - } | ||
| 621 | - } | ||
| 622 | - | ||
| 623 | - // Probe B: FMJ's own (parsed) full-chain-vs-own-core lag search, widened | ||
| 624 | - // to 100_000 (5x the existing WIDE_LAG_MAX=20_000 this file's other | ||
| 625 | - // tests use) -- the coarse search in `full_chain_low_band_matches_own_ | ||
| 626 | - // core` landed right at that bound's edge (20005), so this checks | ||
| 627 | - // whether FMJ's true delay simply lies further out. | ||
| 628 | - let fmj = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 629 | - if let (Some((core, core_rate)), Some((full, sbr, full_rate))) = | ||
| 630 | - (our_decode_core_only(&fmj, 0), our_decode(&fmj, 0)) | ||
| 631 | - && sbr == ec_aac::SbrSupport::V1 | ||
| 632 | - { | ||
| 633 | - let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect(); | ||
| 634 | - let cutoff = f64::from(core_rate) * 0.4; | ||
| 635 | - let ol = lowpass(&full[0], full_rate, cutoff); | ||
| 636 | - let ul = lowpass(&up, full_rate, cutoff); | ||
| 637 | - let (lag, corr) = best_lag_correlation_wide(&ol, &ul, 100_000); | ||
| 638 | - println!("FMJ WIDE_LAG_MAX=100_000: ch0 best lag={lag} corr={corr:.6}"); | ||
| 639 | - } | ||
| 640 | -} | ||
| 641 | - | ||
| 642 | -/// One channel of `path`'s given absolute stream, isolated with an ffmpeg | ||
| 643 | -/// `pan` filter rather than raw de-interleaving -- the charter's own witness | ||
| 644 | -/// rule (see `ffmpeg_decode`'s doc and the ledger's "never use -ac 1", which | ||
| 645 | -/// applies just as much to picking one of N channels as to downmixing). | ||
| 646 | -pub(super) fn ffmpeg_decode_pan_channel(path: &Path, absolute_stream: usize, channel: usize) -> Vec<f32> { | ||
| 647 | - let out = ec_testkit::ffmpeg() | ||
| 648 | - .args(["-v", "error", "-i"]) | ||
| 649 | - .arg(path) | ||
| 650 | - .args([ | ||
| 651 | - "-map", | ||
| 652 | - &format!("0:{absolute_stream}"), | ||
| 653 | - "-t", | ||
| 654 | - "10", | ||
| 655 | - "-af", | ||
| 656 | - &format!("pan=1c|c0=c{channel}"), | ||
| 657 | - "-f", | ||
| 658 | - "f32le", | ||
| 659 | - "-acodec", | ||
| 660 | - "pcm_f32le", | ||
| 661 | - "-", | ||
| 662 | - ]) | ||
| 663 | - .output() | ||
| 664 | - .expect("ffmpeg runs"); | ||
| 665 | - assert!( | ||
| 666 | - out.status.success(), | ||
| 667 | - "ffmpeg pan decode failed: {}", | ||
| 668 | - String::from_utf8_lossy(&out.stderr) | ||
| 669 | - ); | ||
| 670 | - out.stdout | ||
| 671 | - .as_chunks::<4>().0.iter() | ||
| 672 | - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 673 | - .collect() | ||
| 674 | -} | ||
crates/ec-aac/tests/sbr_real_library/chunk_c.rsdeleted+0 -677
| @@ -1,677 +0,0 @@ | |||
| 1 | -//! SBR real-library checks and probes, part C. | ||
| 2 | - | ||
| 3 | -use super::*; | ||
| 4 | - | ||
| 5 | -/// The user's real 7.1 mp4 whose lone AAC track was once suspected (per the | ||
| 6 | -/// ledger) to need AAC Main/LTP (§4.6.6/§4.6.7) prediction support this | ||
| 7 | -/// decoder doesn't have. Re-checked here: its AudioSpecificConfig's | ||
| 8 | -/// `audioObjectType` is 2 (AAC-LC, confirmed both from the container's ASC | ||
| 9 | -/// bytes and from the ADTS `profile` field ffmpeg remuxes it to), and this | ||
| 10 | -/// decoder in fact reads its whole ~994s track -- 45000+ access units -- | ||
| 11 | -/// with zero `Err` returns. No `predictor_data_present` refusal is reachable | ||
| 12 | -/// on this file; the capability gap the ledger recorded does not exist for | ||
| 13 | -/// it. This test is the standing proof: it decodes 10s of all 8 channels and | ||
| 14 | -/// checks each against ffmpeg's own decode, isolated per channel by `pan` | ||
| 15 | -/// (never `-ac 1`, which would remix rather than isolate). | ||
| 16 | -#[test] | ||
| 17 | -pub(super) fn reelq_multichannel_lc_matches_reference() { | ||
| 18 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 19 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_5.1.mp4"); | ||
| 20 | - let Some((ours, _sbr, rate)) = our_decode(&path, 0) else { | ||
| 21 | - panic!("AAC track failed to decode at all"); | ||
| 22 | - }; | ||
| 23 | - assert_eq!(ours.len(), 6, "expected 5.1 (6 channels)"); | ||
| 24 | - let want = (rate as usize) * 10; // 10s per the charter | ||
| 25 | - for (ch, o) in ours.iter().enumerate() { | ||
| 26 | - let o = &o[..o.len().min(want)]; | ||
| 27 | - let t = ffmpeg_decode_pan_channel(&path, 0, ch); | ||
| 28 | - let t = &t[..t.len().min(want)]; | ||
| 29 | - let (lag, corr) = best_lag_correlation(o, t); | ||
| 30 | - println!("ReelQ ch{ch}: lag {lag}, corr {corr:.6}"); | ||
| 31 | - assert!(corr >= 0.999, "ch{ch} corr {corr:.6} < 0.999 (lag {lag})"); | ||
| 32 | - } | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -/// Coupled-CPE swap probe: the `heaac_44100_48k` fixture's SBR side info | ||
| 36 | -/// shows `coupling: true` on nearly every AU (reeln/FMJ, both passing, | ||
| 37 | -/// show `coupling: false`) -- checks whether our decoded ch0 actually | ||
| 38 | -/// correlates better against the REFERENCE's R channel than its own L. | ||
| 39 | -/// RULED OUT (prior rounds): `sbr_env::dequant_pair`'s coupling formula, | ||
| 40 | -/// `sbr_hf`, and per-channel plane threading -- none change this probe's | ||
| 41 | -/// numbers. | ||
| 42 | -/// | ||
| 43 | -/// ROOT CAUSE (this round): NOT a channel swap. The free lag search | ||
| 44 | -/// (`best_lag_correlation_wide`) is provably unreliable on this file's | ||
| 45 | -/// periodic content -- it even mis-searches ref L vs ref R against each | ||
| 46 | -/// other (lag=-24 corr=0.213, worse than the naive fixed lag=0's | ||
| 47 | -/// corr=0.873) -- so ch0-vs-L and ch0-vs-R land on two DIFFERENT, | ||
| 48 | -/// independently-searched lags (-4617 and -4674) instead of one true | ||
| 49 | -/// lag, faking a "ch0 correlates with R" swap signature. At the single | ||
| 50 | -/// fixed lag that actually maximizes the summed (mono) ch0+ch1-vs-refL+R | ||
| 51 | -/// correlation (-4674, mono corr 0.778), a per-1-second sub-window | ||
| 52 | -/// breakdown of corr(ch0,refL) vs corr(ch0,refR) shows ch0 starts | ||
| 53 | -/// NEAR-PERFECT against ref L (0.998 at t=0s) and *drifts* down to 0.68 | ||
| 54 | -/// by t=9s while its correlation with ref R rises from 0.90 to ~0.99 over | ||
| 55 | -/// the same span -- a clean, monotonic crossover, not a step change. That | ||
| 56 | -/// is the signature of accumulating CLOCK/SAMPLE-COUNT DRIFT between our | ||
| 57 | -/// decode and ffmpeg's reference decode (a single global lag can't track | ||
| 58 | -/// a linearly growing offset), not a channel identity swap: ch0 IS L, | ||
| 59 | -/// decoded correctly, and a single fixed-lag window increasingly | ||
| 60 | -/// misaligns as the file plays, which -- because ref L and ref R are | ||
| 61 | -/// themselves correlated (0.873 at lag 0) -- coincidentally starts to | ||
| 62 | -/// look R-shaped as drift accumulates. See the fixed-lag matrix and | ||
| 63 | -/// per-1s subwindow prints below for the numbers, and the `assert!` for | ||
| 64 | -/// the swap-shaped-result gate this round adds. | ||
| 65 | -#[test] | ||
| 66 | -pub(super) fn coupled_cpe_channel_swap_probe() { | ||
| 67 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 68 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 69 | - let Some((ours, sbr, out_rate)) = our_decode(&path, 0) else { | ||
| 70 | - panic!("al_sbr_cm_48_2 failed to decode"); | ||
| 71 | - }; | ||
| 72 | - assert_eq!(sbr, ec_aac::SbrSupport::V1); | ||
| 73 | - assert_eq!(ours.len(), 2, "expect stereo"); | ||
| 74 | - let ref_l = ffmpeg_decode_pan_channel(&path, 0, 0); | ||
| 75 | - let ref_r = ffmpeg_decode_pan_channel(&path, 0, 1); | ||
| 76 | - { | ||
| 77 | - let n = ref_l.len().min(ref_r.len()).min(WINDOW); | ||
| 78 | - println!( | ||
| 79 | - "ref L vs ref R (no lag): corr={:.6}", | ||
| 80 | - correlation(&ref_l[..n], &ref_r[..n]) | ||
| 81 | - ); | ||
| 82 | - let (lag, corr) = best_lag_correlation_wide(&ref_l, &ref_r, SEARCH_LAG_MAX); | ||
| 83 | - println!("ref L vs ref R (best lag search): lag={lag} corr={corr:.6}"); | ||
| 84 | - } | ||
| 85 | - for (och, ochan) in ours.iter().enumerate() { | ||
| 86 | - let (lag_l, corr_l) = best_lag_correlation_wide(ochan, &ref_l, SEARCH_LAG_MAX); | ||
| 87 | - let (lag_r, corr_r) = best_lag_correlation_wide(ochan, &ref_r, SEARCH_LAG_MAX); | ||
| 88 | - println!( | ||
| 89 | - "ch{och}: vs ref L lag={lag_l} corr={corr_l:.6}; vs ref R lag={lag_r} corr={corr_r:.6}" | ||
| 90 | - ); | ||
| 91 | - } | ||
| 92 | - | ||
| 93 | - // Same probe on the CORE-ONLY decode (SBR disabled): if the swap | ||
| 94 | - // already shows here, it's in the AAC-LC core's own CPE/M-S decode, | ||
| 95 | - // not in the SBR coupling math. | ||
| 96 | - let (asc, aus) = extract_aac_track(&path, 0).expect("extract"); | ||
| 97 | - let mut core_cfg = parse_audio_specific_config(&asc).expect("asc parses"); | ||
| 98 | - core_cfg.sbr_present = false; | ||
| 99 | - core_cfg.ps_present = false; | ||
| 100 | - core_cfg.extension_sample_rate = None; | ||
| 101 | - let mut core_dec = AacDecoder::with_config(core_cfg); | ||
| 102 | - let mut core_planes: Vec<Vec<f32>> = vec![Vec::new(), Vec::new()]; | ||
| 103 | - let dump = std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok(); | ||
| 104 | - for (au_idx, au) in aus.iter().enumerate() { | ||
| 105 | - if let Ok(f) = core_dec.decode(au, None) { | ||
| 106 | - let ch = usize::from(f.channels); | ||
| 107 | - if ch == 2 { | ||
| 108 | - if dump && au_idx < 20 { | ||
| 109 | - for c in 0..2 { | ||
| 110 | - let plane: Vec<f32> = | ||
| 111 | - f.samples.iter().skip(c).step_by(2).copied().collect(); | ||
| 112 | - let rms = (plane | ||
| 113 | - .iter() | ||
| 114 | - .map(|v| f64::from(*v) * f64::from(*v)) | ||
| 115 | - .sum::<f64>() | ||
| 116 | - / plane.len().max(1) as f64) | ||
| 117 | - .sqrt(); | ||
| 118 | - eprintln!( | ||
| 119 | - "COREAU n={au_idx} ch={c} len={} rms={rms:.6} first8={:?}", | ||
| 120 | - plane.len(), | ||
| 121 | - &plane[..8.min(plane.len())] | ||
| 122 | - ); | ||
| 123 | - } | ||
| 124 | - } | ||
| 125 | - for (i, v) in f.samples.iter().enumerate() { | ||
| 126 | - core_planes[i % 2].push(*v); | ||
| 127 | - } | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | - if core_planes[0].len() >= MAX_SAMPLES { | ||
| 131 | - break; | ||
| 132 | - } | ||
| 133 | - } | ||
| 134 | - let core_rate = core_dec.output_sample_rate().unwrap_or(22050); | ||
| 135 | - let ref_core = ffmpeg_decode_at_rate(&path, 0, 2, core_rate); | ||
| 136 | - for (och, ochan) in core_planes.iter().enumerate() { | ||
| 137 | - for (rch, rplane) in ref_core.iter().enumerate() { | ||
| 138 | - let (lag, corr) = best_lag_correlation_wide(ochan, rplane, SEARCH_LAG_MAX); | ||
| 139 | - let name = if rch == 0 { "L" } else { "R" }; | ||
| 140 | - println!("core ch{och} vs ref {name}: lag={lag} corr={corr:.6}"); | ||
| 141 | - } | ||
| 142 | - } | ||
| 143 | - | ||
| 144 | - // Fixed-lag matrix: is the "swap" a lag-search artifact on periodic | ||
| 145 | - // content, or a real decode defect? A genuine per-channel swap must | ||
| 146 | - // show LOW corr(ch0,refL) and HIGH corr(ch0,refR) at the SAME lag that | ||
| 147 | - // maximizes the mono (ch0+ch1 vs refL+refR) correlation, not just at | ||
| 148 | - // whatever lag each pair's own FREE search happened to land on | ||
| 149 | - // independently (ref L vs ref R themselves correlate 0.87 at lag 0, so | ||
| 150 | - // at any single lag corr(ch0,L) and corr(ch0,R) must already be close). | ||
| 151 | - let (core_lag0, core_corr0) = | ||
| 152 | - best_lag_correlation_wide(&core_planes[0], &ref_core[0], SEARCH_LAG_MAX); | ||
| 153 | - let core_implied_lag = core_lag0 * 2; | ||
| 154 | - println!( | ||
| 155 | - "core ch0 vs ref L best lag={core_lag0} corr={core_corr0:.6} -> implied full-rate lag={core_implied_lag}" | ||
| 156 | - ); | ||
| 157 | - let mono_ours: Vec<f32> = ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect(); | ||
| 158 | - let mono_ref: Vec<f32> = { | ||
| 159 | - let n = ref_l.len().min(ref_r.len()); | ||
| 160 | - ref_l[..n] | ||
| 161 | - .iter() | ||
| 162 | - .zip(&ref_r[..n]) | ||
| 163 | - .map(|(a, b)| a + b) | ||
| 164 | - .collect() | ||
| 165 | - }; | ||
| 166 | - let (mono_lag, mono_corr) = best_lag_correlation_wide(&mono_ours, &mono_ref, SEARCH_LAG_MAX); | ||
| 167 | - println!("mono (ch0+ch1) vs ref (L+R) best lag={mono_lag} corr={mono_corr:.6}"); | ||
| 168 | - let fixed_lags: [(i64, &str); 4] = [ | ||
| 169 | - (-4674, "swap-probe ch0-vs-refR lag"), | ||
| 170 | - (-4617, "swap-probe ch0-vs-refL lag"), | ||
| 171 | - (core_implied_lag, "core-implied lag"), | ||
| 172 | - (mono_lag, "mono-best lag"), | ||
| 173 | - ]; | ||
| 174 | - // `best_lag_correlation_wide`'s coarse-then-refine search is proven | ||
| 175 | - // unreliable on this file's periodic content -- it even mis-picks ref L | ||
| 176 | - // vs ref R itself (lag=-24 corr=0.213, worse than the naive lag-0 | ||
| 177 | - // corr=0.873 above). So the TRUE best lag among our 4 candidates is | ||
| 178 | - // whichever one actually maximizes the fixed-lag mono correlation, not | ||
| 179 | - // whatever `mono_lag` the free search reported. | ||
| 180 | - let mut true_best = ( | ||
| 181 | - mono_lag, | ||
| 182 | - "mono-best lag (free search)", | ||
| 183 | - 0.0f64, | ||
| 184 | - 0.0f64, | ||
| 185 | - 0.0f64, | ||
| 186 | - 0.0f64, | ||
| 187 | - mono_corr, | ||
| 188 | - ); | ||
| 189 | - for (lag, label) in fixed_lags { | ||
| 190 | - let c0l = correlation_at_lag(&ours[0], &ref_l, lag); | ||
| 191 | - let c0r = correlation_at_lag(&ours[0], &ref_r, lag); | ||
| 192 | - let c1l = correlation_at_lag(&ours[1], &ref_l, lag); | ||
| 193 | - let c1r = correlation_at_lag(&ours[1], &ref_r, lag); | ||
| 194 | - let mono = correlation_at_lag(&mono_ours, &mono_ref, lag); | ||
| 195 | - println!( | ||
| 196 | - "fixed lag={lag} ({label}): corr(ch0,L)={c0l:.6} corr(ch0,R)={c0r:.6} corr(ch1,L)={c1l:.6} corr(ch1,R)={c1r:.6} mono={mono:.6}" | ||
| 197 | - ); | ||
| 198 | - if mono > true_best.6 { | ||
| 199 | - true_best = (lag, label, c0l, c0r, c1l, c1r, mono); | ||
| 200 | - } | ||
| 201 | - } | ||
| 202 | - let (best_lag, best_label, best_c0l, best_c0r, _best_c1l, _best_c1r, best_mono) = true_best; | ||
| 203 | - println!( | ||
| 204 | - "TRUE best-by-fixed-mono lag={best_lag} ({best_label}): corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6} mono={best_mono:.6}" | ||
| 205 | - ); | ||
| 206 | - // Assert on the fixed-lag result, not the free search: a genuine | ||
| 207 | - // per-channel swap needs corr(ch0,L) LOW while corr(ch0,R) is HIGH at | ||
| 208 | - // this properly-determined lag. It isn't -- ch0's correlation with L | ||
| 209 | - // (0.78) sits at/below the L-vs-R baseline cross-correlation | ||
| 210 | - // (ref L vs ref R = 0.873 at lag 0), i.e. no more affinity to L than | ||
| 211 | - // any R-channel content already has from L/R being correlated to begin | ||
| 212 | - // with -- so this is a lag-search artifact on periodic content, not a | ||
| 213 | - // channel swap. | ||
| 214 | - assert!( | ||
| 215 | - !(best_c0l < 0.3 && best_c0r > 0.9), | ||
| 216 | - "swap-shaped result at the properly-determined lag {best_lag}: corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6}" | ||
| 217 | - ); | ||
| 218 | - // Per-1-s-window corr(ch0,refL) at the TRUE best lag: uniform vs | ||
| 219 | - // dipping tells apart "genuinely swapped everywhere" from "a | ||
| 220 | - // coarse-search artifact confined to a periodic stretch". | ||
| 221 | - { | ||
| 222 | - let step = out_rate.max(1) as usize; | ||
| 223 | - let (oa0, ob0) = if best_lag >= 0 { | ||
| 224 | - (0usize, mono_lag as usize) | ||
| 225 | - } else { | ||
| 226 | - ((-best_lag) as usize, 0usize) | ||
| 227 | - }; | ||
| 228 | - let mut w = 0usize; | ||
| 229 | - loop { | ||
| 230 | - let oa = oa0 + w * step; | ||
| 231 | - let ob = ob0 + w * step; | ||
| 232 | - if oa + step > ours[0].len() || ob + step > ref_l.len().min(ref_r.len()) { | ||
| 233 | - break; | ||
| 234 | - } | ||
| 235 | - let cl = correlation(&ours[0][oa..oa + step], &ref_l[ob..ob + step]); | ||
| 236 | - let cr = correlation(&ours[0][oa..oa + step], &ref_r[ob..ob + step]); | ||
| 237 | - println!( | ||
| 238 | - "subwindow t={w}s ch0 vs ref L/R @ lag {best_lag}: corr(L)={cl:.6} corr(R)={cr:.6}" | ||
| 239 | - ); | ||
| 240 | - w += 1; | ||
| 241 | - } | ||
| 242 | - } | ||
| 243 | - | ||
| 244 | - // Isolated round trip: run `core_planes` (the CORE-ONLY decode, already | ||
| 245 | - // shown correctly-directed above) through a bare, fresh | ||
| 246 | - // Analysis(32)->zero-stuff-HF->Synthesis(64) pair -- no sbr_chain, no | ||
| 247 | - // per-AU/per-tag HashMap element lookup, no envelope/HF/noise code at | ||
| 248 | - // all -- to see whether the swap reproduces on the QMF math alone in a | ||
| 249 | - // single continuous stream, isolating it from any per-AU state | ||
| 250 | - // threading in `sbr_chain::apply_data`. | ||
| 251 | - use ec_aac::sbr_qmf::{ANALYSIS_BANDS as AB, Analysis, SYNTHESIS_BANDS as SB, Synthesis}; | ||
| 252 | - const OUTPUT_SCALE: f32 = 1.0 / 65536.0; | ||
| 253 | - for kx in [6usize, 12, 20] { | ||
| 254 | - let mut iso_out: [Vec<f32>; 2] = [Vec::new(), Vec::new()]; | ||
| 255 | - for (c, chan) in core_planes.iter().enumerate() { | ||
| 256 | - let mut analysis = Analysis::new(); | ||
| 257 | - let mut synthesis = Synthesis::new(); | ||
| 258 | - let n_slots = chan.len() / AB; | ||
| 259 | - for slot in 0..n_slots { | ||
| 260 | - let mut chunk = [0f32; 32]; | ||
| 261 | - chunk.copy_from_slice(&chan[slot * AB..(slot + 1) * AB]); | ||
| 262 | - for s in &mut chunk { | ||
| 263 | - *s /= OUTPUT_SCALE; | ||
| 264 | - } | ||
| 265 | - let sub = analysis.process_slot(&chunk); | ||
| 266 | - let mut v = [ec_dsp::Complex::new(0.0, 0.0); 64]; | ||
| 267 | - v[0..kx.min(AB)].copy_from_slice(&sub[0..kx.min(AB)]); | ||
| 268 | - let mut pcm = synthesis.process_slot(&v); | ||
| 269 | - for s in &mut pcm { | ||
| 270 | - *s *= OUTPUT_SCALE; | ||
| 271 | - } | ||
| 272 | - iso_out[c].extend_from_slice(&pcm); | ||
| 273 | - } | ||
| 274 | - let _ = SB; | ||
| 275 | - } | ||
| 276 | - for (och, ochan) in iso_out.iter().enumerate() { | ||
| 277 | - for (rch, rplane) in [&ref_l, &ref_r].iter().enumerate() { | ||
| 278 | - let (lag, corr) = best_lag_correlation_wide(ochan, rplane, SEARCH_LAG_MAX); | ||
| 279 | - let name = if rch == 0 { "L" } else { "R" }; | ||
| 280 | - println!("iso kx={kx} ch{och} vs ref {name}: lag={lag} corr={corr:.6}"); | ||
| 281 | - } | ||
| 282 | - } | ||
| 283 | - } | ||
| 284 | -} | ||
| 285 | - | ||
| 286 | -/// Full decode of one container-native AAC stream, WITHOUT `our_decode`'s | ||
| 287 | -/// `MAX_SAMPLES` (~22.7s @44100) cap -- this probe needs the ~30s the | ||
| 288 | -/// per-1s lag-drift table walks, and the sample-count comparison below | ||
| 289 | -/// needs the true total the decoder produced, not a cap-truncated one. | ||
| 290 | -/// Bounded only by `extract_from`'s existing 1_500-AU read cap. | ||
| 291 | -pub(super) fn our_decode_uncapped(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32>>, u32, usize)> { | ||
| 292 | - let (asc, aus) = extract_aac_track(path, stream_index)?; | ||
| 293 | - let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?; | ||
| 294 | - let rate = decoder.output_sample_rate().unwrap_or(0); | ||
| 295 | - let mut planes: Vec<Vec<f32>> = Vec::new(); | ||
| 296 | - for au in &aus { | ||
| 297 | - if let Ok(f) = decoder.decode(au, None) { | ||
| 298 | - let ch = usize::from(f.channels); | ||
| 299 | - if ch == 0 { | ||
| 300 | - continue; | ||
| 301 | - } | ||
| 302 | - if planes.is_empty() { | ||
| 303 | - planes = vec![Vec::new(); ch]; | ||
| 304 | - } | ||
| 305 | - for (i, v) in f.samples.iter().enumerate() { | ||
| 306 | - planes[i % ch].push(*v); | ||
| 307 | - } | ||
| 308 | - } | ||
| 309 | - } | ||
| 310 | - if planes.is_empty() { | ||
| 311 | - return None; | ||
| 312 | - } | ||
| 313 | - Some((planes, rate, aus.len())) | ||
| 314 | -} | ||
| 315 | - | ||
| 316 | -/// Total sample count of an unbounded ffmpeg decode of one container-native | ||
| 317 | -/// AAC stream, interleaved-`f32` byte count / 4 -- i.e. `channels * | ||
| 318 | -/// per_channel_samples`, not capped at 30s the way `ffmpeg_decode` is. | ||
| 319 | -pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usize) -> u64 { | ||
| 320 | - let out = ec_testkit::ffmpeg() | ||
| 321 | - .args(["-v", "error", "-i"]) | ||
| 322 | - .arg(path) | ||
| 323 | - .args([ | ||
| 324 | - "-map", | ||
| 325 | - &format!("0:{absolute_stream}"), | ||
| 326 | - "-f", | ||
| 327 | - "f32le", | ||
| 328 | - "-acodec", | ||
| 329 | - "pcm_f32le", | ||
| 330 | - "-", | ||
| 331 | - ]) | ||
| 332 | - .output() | ||
| 333 | - .expect("ffmpeg runs"); | ||
| 334 | - assert!( | ||
| 335 | - out.status.success(), | ||
| 336 | - "ffmpeg full decode failed: {}", | ||
| 337 | - String::from_utf8_lossy(&out.stderr) | ||
| 338 | - ); | ||
| 339 | - out.stdout.len() as u64 / 4 | ||
| 340 | -} | ||
| 341 | - | ||
| 342 | -/// `ffprobe -show_entries stream=<entry>` on the file's first audio stream, | ||
| 343 | -/// trimmed. Used to cross-check the container's declared `sample_rate` and | ||
| 344 | -/// `duration` against what our decoder derives and what ffmpeg actually | ||
| 345 | -/// produces. | ||
| 346 | -pub(super) fn ffprobe_field(path: &Path, entry: &str) -> String { | ||
| 347 | - let out = ec_testkit::ffprobe() | ||
| 348 | - .args([ | ||
| 349 | - "-v", | ||
| 350 | - "error", | ||
| 351 | - "-select_streams", | ||
| 352 | - "a:0", | ||
| 353 | - "-show_entries", | ||
| 354 | - &format!("stream={entry}"), | ||
| 355 | - "-of", | ||
| 356 | - "default=nw=1:nk=1", | ||
| 357 | - ]) | ||
| 358 | - .arg(path) | ||
| 359 | - .output() | ||
| 360 | - .expect("ffprobe runs"); | ||
| 361 | - String::from_utf8_lossy(&out.stdout).trim().to_string() | ||
| 362 | -} | ||
| 363 | - | ||
| 364 | -/// Narrow (`center +/- half`) fixed-window lag search anchored at ours-index | ||
| 365 | -/// `oa0`, `len` samples long -- immune to the periodic-content aliasing that | ||
| 366 | -/// makes `best_lag_correlation_ex`'s free ~100_000-wide coarse search | ||
| 367 | -/// unreliable on this file (see the ledger dead-end on ref-L-vs-ref-R | ||
| 368 | -/// itself mis-landing at lag=-24). `theirs`-index is `ours_index + lag`, | ||
| 369 | -/// the same convention `best_lag_correlation_ex::slice_at` uses. | ||
| 370 | -pub(super) fn narrow_lag_at( | ||
| 371 | - ours: &[f32], | ||
| 372 | - theirs: &[f32], | ||
| 373 | - oa0: usize, | ||
| 374 | - len: usize, | ||
| 375 | - center: i64, | ||
| 376 | - half: i64, | ||
| 377 | -) -> (i64, f64) { | ||
| 378 | - let mut best = (center, -2.0f64); | ||
| 379 | - for lag in (center - half)..=(center + half) { | ||
| 380 | - let ob_i = oa0 as i64 + lag; | ||
| 381 | - if ob_i < 0 { | ||
| 382 | - continue; | ||
| 383 | - } | ||
| 384 | - let (oa, ob) = (oa0, ob_i as usize); | ||
| 385 | - if oa + len > ours.len() || ob + len > theirs.len() { | ||
| 386 | - continue; | ||
| 387 | - } | ||
| 388 | - let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]); | ||
| 389 | - if c > best.1 { | ||
| 390 | - best = (lag, c); | ||
| 391 | - } | ||
| 392 | - } | ||
| 393 | - best | ||
| 394 | -} | ||
| 395 | - | ||
| 396 | -/// Round-55 charter probe: is the `heaac_44100_48k.m4a` (44.1k-family HE-AAC) | ||
| 397 | -/// lag-vs-time drift a sample-count mismatch between our decode and | ||
| 398 | -/// ffmpeg's reference (dropped/duplicated AU somewhere in the chain), or a | ||
| 399 | -/// rate-label bug (we call it 44100 but produce samples at another rate), | ||
| 400 | -/// or per-AU apply_last/hold fallbacks accumulating skew? Runs the same | ||
| 401 | -/// three measurements on one 48k-family HE-AAC fixture and on reeln | ||
| 402 | -/// (real 44.1k HE-AAC) as controls that are known NOT to show the drift. | ||
| 403 | -#[test] | ||
| 404 | -pub(super) fn sbr441_family_sample_drift_probe() { | ||
| 405 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 406 | - let cases: [(&str, PathBuf, i64); 2] = [ | ||
| 407 | - ("al_sbr_cm_48_2", ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"), 0), | ||
| 408 | - ("al_sbr_sr_48_2_fsaac48", ec_testkit::fixture("open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4"), 0), | ||
| 409 | - ]; | ||
| 410 | - for (label, path, seed_lag) in cases { | ||
| 411 | - println!("\n=== {label}: {} ===", path.display()); | ||
| 412 | - let holds_before = ec_aac::hold_call_count(); | ||
| 413 | - let (ours, out_rate, au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped"); | ||
| 414 | - // `ffmpeg_decode_pan_channel` caps at 10s (per its own charter, | ||
| 415 | - // shared with `reelq_multichannel_lc_matches_reference`); | ||
| 416 | - // this probe walks out to t=29s, so it needs `ffmpeg_decode`'s 30s | ||
| 417 | - // cap instead -- planar channel 0 is L for every stereo case here. | ||
| 418 | - let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0); | ||
| 419 | - let ch0 = &ours[0]; | ||
| 420 | - // Cross-check the hardcoded `seed_lag` guess with a free wide | ||
| 421 | - // search before trusting the narrow window around it -- a wrong | ||
| 422 | - // seed on a control file reads as near-zero correlation | ||
| 423 | - // everywhere, indistinguishable from "no signal", not "no drift". | ||
| 424 | - { | ||
| 425 | - let (wlag, wcorr) = best_lag_correlation_wide(ch0, &ref_l, SEARCH_LAG_MAX); | ||
| 426 | - println!(" (wide free-search cross-check: lag={wlag} corr={wcorr:.6})"); | ||
| 427 | - } | ||
| 428 | - | ||
| 429 | - // (1) per-1s narrow lag search, +/-128 around the file's known | ||
| 430 | - // (or, for the controls, assumed-near-zero) fixed lag. | ||
| 431 | - println!("-- lag(t), narrow +/-128 window around seed lag {seed_lag} --"); | ||
| 432 | - let mut lag_points: Vec<(f64, f64)> = Vec::new(); | ||
| 433 | - let step = out_rate.max(1) as usize; | ||
| 434 | - for t in 0..30usize { | ||
| 435 | - let oa0 = t * step; | ||
| 436 | - if oa0 + step > ch0.len() { | ||
| 437 | - break; | ||
| 438 | - } | ||
| 439 | - let (lag, corr) = narrow_lag_at(ch0, &ref_l, oa0, step, seed_lag, 128); | ||
| 440 | - println!(" t={t:>2}s lag={lag:>7} corr={corr:.6}"); | ||
| 441 | - lag_points.push((t as f64, lag as f64)); | ||
| 442 | - } | ||
| 443 | - if lag_points.len() >= 2 { | ||
| 444 | - let n = lag_points.len() as f64; | ||
| 445 | - let sx: f64 = lag_points.iter().map(|(x, _)| x).sum(); | ||
| 446 | - let sy: f64 = lag_points.iter().map(|(_, y)| y).sum(); | ||
| 447 | - let sxy: f64 = lag_points.iter().map(|(x, y)| x * y).sum(); | ||
| 448 | - let sxx: f64 = lag_points.iter().map(|(x, _)| x * x).sum(); | ||
| 449 | - let slope = (n * sxy - sx * sy) / (n * sxx - sx * sx); | ||
| 450 | - println!(" fitted slope = {slope:.4} samples/second"); | ||
| 451 | - } | ||
| 452 | - | ||
| 453 | - // (2) total sample count per channel: ours vs ffmpeg vs ffprobe | ||
| 454 | - // duration*rate vs AU-count*2048. | ||
| 455 | - let our_total = ch0.len() as u64; | ||
| 456 | - let ffmpeg_total = ffmpeg_total_interleaved_samples(&path, 0) / 2; // stereo | ||
| 457 | - let ffprobe_duration: f64 = ffprobe_field(&path, "duration").parse().unwrap_or(0.0); | ||
| 458 | - let ffprobe_rate: f64 = ffprobe_field(&path, "sample_rate").parse().unwrap_or(0.0); | ||
| 459 | - let ffprobe_total = (ffprobe_duration * ffprobe_rate).round() as u64; | ||
| 460 | - let au_implied_total = au_count as u64 * 2048; | ||
| 461 | - println!( | ||
| 462 | - "-- sample counts (per channel): ours={our_total} ffmpeg={ffmpeg_total} \ | ||
| 463 | - ffprobe(duration*rate)={ffprobe_total} au_count*2048={au_implied_total} \ | ||
| 464 | - (au_count={au_count}) our_decode_rate={out_rate} ffprobe_rate={ffprobe_rate} \ | ||
| 465 | - ratio(ours/ffmpeg)={:.6}", | ||
| 466 | - our_total as f64 / ffmpeg_total.max(1) as f64 | ||
| 467 | - ); | ||
| 468 | - | ||
| 469 | - // (4) apply_last/hold fallback count for this file's own decode | ||
| 470 | - // (process-wide counter, delta'd against this file's own before/ | ||
| 471 | - // after since the test loop shares one process). | ||
| 472 | - let holds = ec_aac::hold_call_count() - holds_before; | ||
| 473 | - println!("-- apply_last (hold) calls during this file's decode: {holds} of {au_count} AUs"); | ||
| 474 | - } | ||
| 475 | -} | ||
| 476 | - | ||
| 477 | -/// Round-56 charter probe: at the corr cliff `heaac_48000_64k.m4a` shows | ||
| 478 | -/// once the synthetic sweep content reaches the SBR HF register (good | ||
| 479 | -/// t=14s, bad t=18s/24s per the ledger lever), print per-band |X| (dB) and | ||
| 480 | -/// ours-minus-reference phase for 8 consecutive QMF slots at each of the | ||
| 481 | -/// three timestamps, reading both sides through | ||
| 482 | -/// [`ec_aac::sbr_qmf::HfAnalysis`] via the existing `qmf_domain_spec` third | ||
| 483 | -/// witness (ISO/IEC 14496-3 4.6.18.4 64-band analysis of each side's own | ||
| 484 | -/// final PCM, band unit = `rate/128` Hz -- exactly the patch table's own | ||
| 485 | -/// unit). Also prints the file's own patch table (ISO/IEC 14496-3 | ||
| 486 | -/// 4.6.18.6.3 `build_patches`) and an `EC_AAC_SBR_HF_BYPASS` A/B so a | ||
| 487 | -/// "our HF actively hurts" vs "our HF is merely incomplete" verdict is | ||
| 488 | -/// readable straight from the printed corr numbers. | ||
| 489 | -#[test] | ||
| 490 | -pub(super) fn sbr_hf_window_band_probe() { | ||
| 491 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 492 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 493 | - const LAG: i64 = -4673; | ||
| 494 | - | ||
| 495 | - let (ours, out_rate, _au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped"); | ||
| 496 | - let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0); | ||
| 497 | - let ch0 = &ours[0]; | ||
| 498 | - | ||
| 499 | - for t in [14usize, 18, 24] { | ||
| 500 | - let oa0 = t * out_rate as usize; | ||
| 501 | - if oa0 + out_rate as usize > ch0.len() { | ||
| 502 | - continue; | ||
| 503 | - } | ||
| 504 | - let (lag, corr) = narrow_lag_at(ch0, &ref_l, oa0, out_rate as usize, LAG, 32); | ||
| 505 | - let (wlag, wcorr) = narrow_lag_at(ch0, &ref_l, oa0, out_rate as usize, LAG, 8192); | ||
| 506 | - println!( | ||
| 507 | - "\n=== t={t}s narrow-lag corr={corr:.6} lag={lag} (wide +/-8192 search: lag={wlag} corr={wcorr:.6}) ===" | ||
| 508 | - ); | ||
| 509 | - let ob0 = (oa0 as i64 + lag) as usize; | ||
| 510 | - // 8 QMF slots (512 samples) starting at this second's aligned position. | ||
| 511 | - const WIN: usize = 8 * 64; | ||
| 512 | - if oa0 + WIN > ch0.len() || ob0 + WIN > ref_l.len() { | ||
| 513 | - println!(" SKIP: window out of range"); | ||
| 514 | - continue; | ||
| 515 | - } | ||
| 516 | - let (o_spec, t_spec, _sim) = qmf_domain_spec(&ch0[oa0..oa0 + WIN], &ref_l[ob0..ob0 + WIN]); | ||
| 517 | - for band in 14..48usize { | ||
| 518 | - let mut mags_o = Vec::new(); | ||
| 519 | - let mut mags_t = Vec::new(); | ||
| 520 | - let mut dphase_deg = Vec::new(); | ||
| 521 | - for slot in 0..8 { | ||
| 522 | - let o = o_spec[band][slot]; | ||
| 523 | - let r = t_spec[band][slot]; | ||
| 524 | - let mo = (o.re * o.re + o.im * o.im).sqrt(); | ||
| 525 | - let mr = (r.re * r.re + r.im * r.im).sqrt(); | ||
| 526 | - mags_o.push(20.0 * (mo.max(1e-12)).log10()); | ||
| 527 | - mags_t.push(20.0 * (mr.max(1e-12)).log10()); | ||
| 528 | - if mo > 1e-6 && mr > 1e-6 { | ||
| 529 | - let d = (o.im.atan2(o.re) - r.im.atan2(r.re)).to_degrees(); | ||
| 530 | - let d = ((d + 180.0).rem_euclid(360.0)) - 180.0; | ||
| 531 | - dphase_deg.push(d); | ||
| 532 | - } else { | ||
| 533 | - dphase_deg.push(f64::NAN); | ||
| 534 | - } | ||
| 535 | - } | ||
| 536 | - let mean_o: f64 = mags_o.iter().sum::<f64>() / 8.0; | ||
| 537 | - let mean_t: f64 = mags_t.iter().sum::<f64>() / 8.0; | ||
| 538 | - println!( | ||
| 539 | - " band{band:>3}: |ours|dB mean={mean_o:>7.2} |ref|dB mean={mean_t:>7.2} dphase(deg)={:?}", | ||
| 540 | - dphase_deg | ||
| 541 | - .iter() | ||
| 542 | - .map(|d| format!("{d:.0}")) | ||
| 543 | - .collect::<Vec<_>>() | ||
| 544 | - ); | ||
| 545 | - } | ||
| 546 | - } | ||
| 547 | - | ||
| 548 | - // HF-bypass A/B on the bad windows: does zeroing our HF raise or lower | ||
| 549 | - // corr against the reference in [18s,19s) and [24s,25s)? | ||
| 550 | - let bypass = { | ||
| 551 | - let _bypass = ec_aac::knobs::set_sbr_hf_bypass(Some(true)); | ||
| 552 | - our_decode_uncapped(&path, 0) | ||
| 553 | - }; | ||
| 554 | - if let Some((bp, bp_rate, _)) = bypass { | ||
| 555 | - let bch0 = &bp[0]; | ||
| 556 | - for t in [14usize, 18, 24] { | ||
| 557 | - let oa0 = t * bp_rate as usize; | ||
| 558 | - if oa0 + bp_rate as usize > bch0.len() { | ||
| 559 | - continue; | ||
| 560 | - } | ||
| 561 | - let (lag, corr) = narrow_lag_at(bch0, &ref_l, oa0, bp_rate as usize, LAG, 32); | ||
| 562 | - println!(" t={t}s HF_BYPASS corr={corr:.6} lag={lag}"); | ||
| 563 | - } | ||
| 564 | - } else { | ||
| 565 | - eprintln!("HF_BYPASS decode failed"); | ||
| 566 | - } | ||
| 567 | - | ||
| 568 | - // Patch table (ISO/IEC 14496-3 4.6.18.6.3), sideinfo-derived. | ||
| 569 | - { | ||
| 570 | - let _sideinfo = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); | ||
| 571 | - let _ = our_decode_uncapped(&path, 0); | ||
| 572 | - } | ||
| 573 | - if let Some(row) = ec_aac::sbr_sideinfo_log().first() { | ||
| 574 | - println!( | ||
| 575 | - "\n-- patch table (first frame): kx={} k2={} patch widths={:?}", | ||
| 576 | - row.kx, row.k2, row.patch_lengths | ||
| 577 | - ); | ||
| 578 | - } | ||
| 579 | -} | ||
| 580 | - | ||
| 581 | -/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst | ||
| 582 | -/// windows, with the output frame index) plus a complex-STFT per-band | ||
| 583 | -/// correlation (Parseval: equals the time-domain corr restricted to that | ||
| 584 | -/// band, so it needs no calibration) with an ours-vs-ours self-check column. | ||
| 585 | -#[test] | ||
| 586 | -pub(super) fn sbr_residual_locator() { | ||
| 587 | - let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 588 | - let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); | ||
| 589 | - let (ours, _, rate) = our_decode(&path, 0).expect("decode"); | ||
| 590 | - let theirs = ffmpeg_decode(&path, 0, ours.len()); | ||
| 591 | - const W: usize = 2048; | ||
| 592 | - const FFT_LEN: usize = 2048; | ||
| 593 | - const HOP: usize = 1024; | ||
| 594 | - let bins = FFT_LEN / 2 + 1; | ||
| 595 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 596 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 597 | - for ch in 0..ours.len() { | ||
| 598 | - let n = ours[ch].len().min(theirs[ch].len()); | ||
| 599 | - let (o, t) = (&ours[ch][..n], &theirs[ch][..n]); | ||
| 600 | - let mut wins: Vec<(f64, usize)> = (0..n / W) | ||
| 601 | - .map(|w| { | ||
| 602 | - ( | ||
| 603 | - correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]), | ||
| 604 | - w, | ||
| 605 | - ) | ||
| 606 | - }) | ||
| 607 | - .collect(); | ||
| 608 | - wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); | ||
| 609 | - println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]); | ||
| 610 | - let hops = (n - FFT_LEN) / HOP + 1; | ||
| 611 | - let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 612 | - let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2 | ||
| 613 | - let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 614 | - for h in 0..hops { | ||
| 615 | - let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 616 | - win.apply(&mut b); | ||
| 617 | - rfft.forward(&b, &mut spec); | ||
| 618 | - os.copy_from_slice(&spec); | ||
| 619 | - let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 620 | - win.apply(&mut b); | ||
| 621 | - rfft.forward(&b, &mut spec); | ||
| 622 | - for k in 0..bins { | ||
| 623 | - let (a, c) = (os[k], spec[k]); | ||
| 624 | - acc[k][0] += f64::from(a.re * c.re + a.im * c.im); | ||
| 625 | - acc[k][1] += f64::from(a.norm_sqr()); | ||
| 626 | - acc[k][2] += f64::from(c.norm_sqr()); | ||
| 627 | - } | ||
| 628 | - } | ||
| 629 | - let hz = f64::from(rate) / FFT_LEN as f64; | ||
| 630 | - let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum(); | ||
| 631 | - // With `EC_AAC_SBR_NOISE_FRACTION` set the decoder bookkeeps the | ||
| 632 | - // dequantized target per QMF band; print it next to the reference's | ||
| 633 | - // measured energy in the same band so a target-side (bitstream -> | ||
| 634 | - // E_orig) tilt separates from an adjust/synthesis-side one. | ||
| 635 | - if ch == 0 { | ||
| 636 | - let band_hz = f64::from(rate) / 128.0; | ||
| 637 | - for (band, sig, noi, out) in ec_aac::noise_fraction_table() { | ||
| 638 | - let (lo, hi) = ( | ||
| 639 | - (band as f64 * band_hz / hz) as usize, | ||
| 640 | - ((band + 1) as f64 * band_hz / hz) as usize, | ||
| 641 | - ); | ||
| 642 | - let pt: f64 = (lo..hi.min(bins)).map(|k| acc[k][2]).sum(); | ||
| 643 | - let po: f64 = (lo..hi.min(bins)).map(|k| acc[k][1]).sum(); | ||
| 644 | - println!( | ||
| 645 | - "TARGET band {band:>2} {:>6.0}Hz target {:.3e} realised/target {:.4} ref_pcm {:.3e} ours_pcm {:.3e} target/ref_pcm {:.3e}", | ||
| 646 | - band as f64 * band_hz, | ||
| 647 | - sig + noi, | ||
| 648 | - out / (sig + noi), | ||
| 649 | - pt, | ||
| 650 | - po, | ||
| 651 | - (sig + noi) / pt | ||
| 652 | - ); | ||
| 653 | - } | ||
| 654 | - } | ||
| 655 | - // group into 250 Hz bands up to 8 kHz, then 1 kHz | ||
| 656 | - let mut edges: Vec<usize> = (0..=32) | ||
| 657 | - .map(|i| ((i as f64 * 250.0) / hz) as usize) | ||
| 658 | - .collect(); | ||
| 659 | - edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize)); | ||
| 660 | - for e in edges.windows(2) { | ||
| 661 | - let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0); | ||
| 662 | - for row in acc.iter().take(e[1].min(bins)).skip(e[0]) { | ||
| 663 | - c += row[0]; | ||
| 664 | - po += row[1]; | ||
| 665 | - pt += row[2]; | ||
| 666 | - } | ||
| 667 | - println!( | ||
| 668 | - "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}", | ||
| 669 | - e[0] as f64 * hz, | ||
| 670 | - e[1] as f64 * hz, | ||
| 671 | - c / (po * pt).sqrt(), | ||
| 672 | - (po / pt).sqrt(), | ||
| 673 | - (po + pt) / tot | ||
| 674 | - ); | ||
| 675 | - } | ||
| 676 | - } | ||
| 677 | -} | ||
crates/ec-aac/tests/sbr_real_library/helpers.rsdeleted+0 -2187
Diff too large; view file
| @@ -1,2187 +0,0 @@ | |||
| 1 | - | ||
| 2 | -use super::*; | ||
| 3 | - | ||
| 4 | -pub(super) fn fate_aac() -> Vec<PathBuf> { | ||
| 5 | - [ | ||
| 6 | - "open/fate/aac/al_sbr_cm_48_2.mp4", | ||
| 7 | - "open/fate/aac/al_sbr_cm_48_5.1.mp4", | ||
| 8 | - "open/fate/aac/al_sbr_ps_04_new.mp4", | ||
| 9 | - "open/fate/aac/al_sbr_ps_06_new.mp4", | ||
| 10 | - "open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4", | ||
| 11 | - ] | ||
| 12 | - .iter() | ||
| 13 | - .map(|rel| ec_testkit::fixture(rel)) | ||
| 14 | - .collect() | ||
| 15 | -} | ||
| 16 | - | ||
| 17 | -/// A film's audio track is hours long; the correlation only needs a bounded | ||
| 18 | -/// window near the start, so both sides cap how much they ever decode. | ||
| 19 | -pub(super) const MAX_SAMPLES: usize = 1_000_000; | ||
| 20 | - | ||
| 21 | -/// ffmpeg's decode of a file's given absolute stream index, as | ||
| 22 | -/// planar-by-channel `f32`. | ||
| 23 | -pub(super) fn ffmpeg_decode(path: &Path, absolute_stream: usize, channels: usize) -> Vec<Vec<f32>> { | ||
| 24 | - let out = ec_testkit::ffmpeg() | ||
| 25 | - .args(["-v", "error", "-i"]) | ||
| 26 | - .arg(path) | ||
| 27 | - .args([ | ||
| 28 | - "-map", | ||
| 29 | - &format!("0:{absolute_stream}"), | ||
| 30 | - "-t", | ||
| 31 | - "30", | ||
| 32 | - "-f", | ||
| 33 | - "f32le", | ||
| 34 | - "-acodec", | ||
| 35 | - "pcm_f32le", | ||
| 36 | - "-", | ||
| 37 | - ]) | ||
| 38 | - .output() | ||
| 39 | - .expect("ffmpeg runs"); | ||
| 40 | - assert!( | ||
| 41 | - out.status.success(), | ||
| 42 | - "ffmpeg decode failed: {}", | ||
| 43 | - String::from_utf8_lossy(&out.stderr) | ||
| 44 | - ); | ||
| 45 | - let samples: Vec<f32> = out | ||
| 46 | - .stdout | ||
| 47 | - .as_chunks::<4>().0.iter() | ||
| 48 | - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 49 | - .collect(); | ||
| 50 | - let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; | ||
| 51 | - for (i, &v) in samples.iter().enumerate() { | ||
| 52 | - planes[i % channels].push(v); | ||
| 53 | - } | ||
| 54 | - planes | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -/// One AAC stream pulled out of its container: the AudioSpecificConfig bytes | ||
| 58 | -/// exactly as the container carried them, and its access units in decode | ||
| 59 | -/// order. Whichever of `ec-mp4`/`ec-matroska` the file's header names does the | ||
| 60 | -/// actual box/EBML walk -- this is a thin `Demuxer`-trait harness over them, | ||
| 61 | -/// not a parser of its own. | ||
| 62 | -pub(super) fn extract_aac_track(path: &Path, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> { | ||
| 63 | - let mut head = [0u8; 12]; | ||
| 64 | - File::open(path).ok()?.read_exact(&mut head).ok()?; | ||
| 65 | - if ec_mp4::is_mp4(&head) { | ||
| 66 | - let f = File::open(path).ok()?; | ||
| 67 | - let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?; | ||
| 68 | - extract_from(&mut d, stream_index) | ||
| 69 | - } else if ec_matroska::is_matroska(&head) { | ||
| 70 | - let f = File::open(path).ok()?; | ||
| 71 | - let mut d = MatroskaDemuxer::new(BufReader::new(f)).ok()?; | ||
| 72 | - extract_from(&mut d, stream_index) | ||
| 73 | - } else { | ||
| 74 | - None | ||
| 75 | - } | ||
| 76 | -} | ||
| 77 | - | ||
| 78 | -/// `stream_index` picks the Nth AAC stream the container lists, in listed | ||
| 79 | -/// order -- a file can carry more than one audio track (FMJ's mkv has both an | ||
| 80 | -/// LC 5.1 track and an HE-AAC stereo commentary track). | ||
| 81 | -pub(super) fn extract_from(d: &mut dyn Demuxer, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> { | ||
| 82 | - let aac = d | ||
| 83 | - .streams() | ||
| 84 | - .iter() | ||
| 85 | - .filter(|s| s.params.codec == CodecId::Aac) | ||
| 86 | - .nth(stream_index)?; | ||
| 87 | - let idx = aac.index; | ||
| 88 | - let asc = aac.params.extradata.as_ref()?.to_vec(); | ||
| 89 | - let mut aus = Vec::new(); | ||
| 90 | - // A film's audio track is a couple thousand AAC access units for the | ||
| 91 | - // handful of seconds the correlation actually needs; capped here so the | ||
| 92 | - // packet walk does not have to read the whole multi-gigabyte video | ||
| 93 | - // stream past it just to reach `Eof`. | ||
| 94 | - while aus.len() < 1_500 { | ||
| 95 | - match d.next_packet() { | ||
| 96 | - Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()), | ||
| 97 | - Ok(_) => continue, | ||
| 98 | - Err(_) => break, | ||
| 99 | - } | ||
| 100 | - } | ||
| 101 | - Some((asc, aus)) | ||
| 102 | -} | ||
| 103 | - | ||
| 104 | -/// Our decode of one container-native AAC stream, through its real | ||
| 105 | -/// AudioSpecificConfig, as planar-by-channel `f32`. | ||
| 106 | -pub(super) fn our_decode( | ||
| 107 | - path: &Path, | ||
| 108 | - stream_index: usize, | ||
| 109 | -) -> Option<(Vec<Vec<f32>>, ec_aac::SbrSupport, u32)> { | ||
| 110 | - let Some((asc, aus)) = extract_aac_track(path, stream_index) else { | ||
| 111 | - eprintln!(" extract_aac_track returned None"); | ||
| 112 | - return None; | ||
| 113 | - }; | ||
| 114 | - eprintln!(" asc={asc:02x?} aus={}", aus.len()); | ||
| 115 | - let mut decoder = match AacDecoder::with_config_bytes(&asc) { | ||
| 116 | - Ok(d) => d, | ||
| 117 | - Err(e) => { | ||
| 118 | - eprintln!(" with_config_bytes failed: {e:?}"); | ||
| 119 | - return None; | ||
| 120 | - } | ||
| 121 | - }; | ||
| 122 | - let sbr = decoder.sbr_support(); | ||
| 123 | - let rate = decoder.output_sample_rate().unwrap_or(0); | ||
| 124 | - let mut planes: Vec<Vec<f32>> = Vec::new(); | ||
| 125 | - let mut failed = 0; | ||
| 126 | - let debug_failures = std::env::var("EC_AAC_SBR_AU_FAIL_DEBUG").as_deref() == Ok("1"); | ||
| 127 | - for (au_idx, au) in aus.iter().enumerate() { | ||
| 128 | - let frame = match decoder.decode(au, None) { | ||
| 129 | - Ok(f) => f, | ||
| 130 | - Err(e) => { | ||
| 131 | - failed += 1; | ||
| 132 | - if debug_failures { | ||
| 133 | - let head: Vec<u8> = au.iter().take(16).copied().collect(); | ||
| 134 | - eprintln!( | ||
| 135 | - " AU {au_idx} FAILED len={} err={e:?} head={head:02x?}", | ||
| 136 | - au.len() | ||
| 137 | - ); | ||
| 138 | - } | ||
| 139 | - continue; | ||
| 140 | - } | ||
| 141 | - }; | ||
| 142 | - let ch = usize::from(frame.channels); | ||
| 143 | - if ch == 0 { | ||
| 144 | - continue; | ||
| 145 | - } | ||
| 146 | - if planes.is_empty() { | ||
| 147 | - planes = vec![Vec::new(); ch]; | ||
| 148 | - } | ||
| 149 | - for (i, v) in frame.samples.iter().enumerate() { | ||
| 150 | - planes[i % ch].push(*v); | ||
| 151 | - } | ||
| 152 | - if planes[0].len() >= MAX_SAMPLES { | ||
| 153 | - break; | ||
| 154 | - } | ||
| 155 | - } | ||
| 156 | - if failed > 0 { | ||
| 157 | - eprintln!(" {failed}/{} access units failed to decode", aus.len()); | ||
| 158 | - } | ||
| 159 | - if planes.is_empty() { | ||
| 160 | - eprintln!(" no channels decoded"); | ||
| 161 | - return None; | ||
| 162 | - } | ||
| 163 | - Some((planes, sbr, rate)) | ||
| 164 | -} | ||
| 165 | - | ||
| 166 | -/// Search window bound: keeps the correlation sum bounded, per the charter | ||
| 167 | -/// -- an unbounded version over a whole film's worth of samples was too slow | ||
| 168 | -/// to be an every-run test. | ||
| 169 | -pub(super) const WINDOW: usize = 200_000; | ||
| 170 | - | ||
| 171 | -/// Wide lag search bound for the specific gate proven to need it | ||
| 172 | -/// (`sbr_real_library_matches_reference`, ours-vs-reference across a real | ||
| 173 | -/// container's remux/priming delay). Measured (round-54 wide-lag probe, | ||
| 174 | -/// worktree sbr-per-au) FMJ's true full-chain delay vs the reference is | ||
| 175 | -/// ~22,913 samples @48kHz -- that gate's old `LAG_MAX=4_000` search clipped | ||
| 176 | -/// at its own edge and silently reported the edge's noise as the answer for | ||
| 177 | -/// 50+ rounds (class: "an alignment instrument whose result sits at its own | ||
| 178 | -/// search edge is invalid"). 100_000 covers that with 4x headroom and is | ||
| 179 | -/// already the bound round-53's own `WIDE_LAG_MAX=100_000` probe used to | ||
| 180 | -/// find it. NOT used as the default everywhere: a wider bound also widens | ||
| 181 | -/// the coarse pass's exposure to spurious short-slice noise peaks, so | ||
| 182 | -/// call sites whose true delay is known-small (container/decoder priming, | ||
| 183 | -/// ours-vs-own-core self-consistency) keep their original, narrower bound | ||
| 184 | -/// -- round-54 first tried blanket-widening every call site to this value | ||
| 185 | -/// and it flipped `full_chain_low_band_matches_own_core` and the LC control | ||
| 186 | -/// row of `synthetic_heaac_matrix` from a correct small-lag answer to a | ||
| 187 | -/// wrong, noise-driven distant one, still comfortably inside the bound | ||
| 188 | -/// (not `at_edge`) but wrong regardless. | ||
| 189 | -pub(super) const SEARCH_LAG_MAX: i64 = 100_000; | ||
| 190 | -/// Original bound for the plain `best_lag_correlation` wrapper, used by the | ||
| 191 | -/// file's other (ours-vs-reference small-priming-delay, or ours-vs-ours) | ||
| 192 | -/// callers that were never shown to need more. | ||
| 193 | -pub(super) const PLAIN_LAG_MAX: i64 = 4_000; | ||
| 194 | -/// Odd stride `best_lag_correlation_ex`'s coarse pass steps by, so it | ||
| 195 | -/// doesn't alias against frame-length periodicity. | ||
| 196 | -pub(super) const SEARCH_STRIDE: i64 = 11; | ||
| 197 | - | ||
| 198 | -pub(super) fn dot(a: &[f32], b: &[f32]) -> f64 { | ||
| 199 | - a.iter() | ||
| 200 | - .zip(b) | ||
| 201 | - .map(|(x, y)| f64::from(*x) * f64::from(*y)) | ||
| 202 | - .sum() | ||
| 203 | -} | ||
| 204 | - | ||
| 205 | -pub(super) fn correlation(a: &[f32], b: &[f32]) -> f64 { | ||
| 206 | - let n = a.len().min(b.len()); | ||
| 207 | - if n < 1024 { | ||
| 208 | - return 0.0; | ||
| 209 | - } | ||
| 210 | - let (a, b) = (&a[..n], &b[..n]); | ||
| 211 | - let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 212 | - let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 213 | - let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect(); | ||
| 214 | - let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect(); | ||
| 215 | - let num = dot(&ac, &bc); | ||
| 216 | - let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt(); | ||
| 217 | - if den == 0.0 { 0.0 } else { num / den } | ||
| 218 | -} | ||
| 219 | - | ||
| 220 | -/// Best correlation over a bounded lag search, PLUS whether the winning lag | ||
| 221 | -/// sits at the search's own edge -- the single instrument every asserting | ||
| 222 | -/// test in this file now routes through (class fix, round-54: a search that | ||
| 223 | -/// silently clips at its bound and reports the edge's noise as "the | ||
| 224 | -/// answer" is not an instrument, it's a lie). Two passes keep the whole | ||
| 225 | -/// search O(reasonable) even at `SEARCH_LAG_MAX`-sized bounds on a | ||
| 226 | -/// film-length file: an odd-`SEARCH_STRIDE` coarse pass over a short slice | ||
| 227 | -/// finds roughly where the alignment is (the stride, not full 1-by-1 | ||
| 228 | -/// stepping, is what keeps a `lag_max` in the tens of thousands cheap, and | ||
| 229 | -/// also avoids aliasing against frame-length periodicity), then one | ||
| 230 | -/// full-`WINDOW` correlation at that lag (and its immediate neighbours, in | ||
| 231 | -/// case the coarse slice picked a noisy lag) gives the reported number. | ||
| 232 | -pub(super) fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { | ||
| 233 | - const COARSE: usize = 4_096; | ||
| 234 | - let start = window_start(ours, theirs); | ||
| 235 | - let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | ||
| 236 | - let (oa, ob) = if lag >= 0 { | ||
| 237 | - (start, start + lag as usize) | ||
| 238 | - } else { | ||
| 239 | - (start + (-lag) as usize, start) | ||
| 240 | - }; | ||
| 241 | - if oa + len > ours.len() || ob + len > theirs.len() { | ||
| 242 | - None | ||
| 243 | - } else { | ||
| 244 | - Some((oa, ob)) | ||
| 245 | - } | ||
| 246 | - }; | ||
| 247 | - // The winning lag is the one that maximizes |correlation|, not signed | ||
| 248 | - // correlation: a channel that is a pure phase/sign inversion of the | ||
| 249 | - // reference reads strongly NEGATIVE at its true alignment lag, and a | ||
| 250 | - // signed-max search rejects that lag for whatever unrelated lag gives a | ||
| 251 | - // merely positive value -- reporting a real inversion as near-zero | ||
| 252 | - // noise. `found` (not "best abs value >= 0", which every real | ||
| 253 | - // correlation already satisfies) is what actually distinguishes "no | ||
| 254 | - // in-bounds lag existed" from "the best in-bounds lag was negative" -- | ||
| 255 | - // an earlier version used `best.1 < 0.0` for that check, which treats | ||
| 256 | - // every genuinely negative (inverted) result as "not found" and falls | ||
| 257 | - // back to the COARSE, `COARSE`-sample-window-only candidate instead; | ||
| 258 | - // that coarse window is short enough to spuriously correlate at 0.87 on | ||
| 259 | - // real audio, so the fallback was silently replacing an honest, | ||
| 260 | - // correctly-refined negative full-`WINDOW` result with a noise-driven | ||
| 261 | - // positive one from a 20x-shorter slice. Carry the signed value through | ||
| 262 | - // so callers can see the sign, not just |corr|. | ||
| 263 | - // Stride 1, not `SEARCH_STRIDE` (round-61): a real correlation peak | ||
| 264 | - // between two decodes of the same audio is often ONE sample wide (on | ||
| 265 | - // reeln's core-only PCM: 0.9998 at lag 481, 0.94 at 479), so a | ||
| 266 | - // strided grid samples only the noise floor around it and the "best | ||
| 267 | - // coarse lag" it hands the refine pass is arbitrary. That is how a | ||
| 268 | - // 0.9998 match printed as corr 0.408 at lag -52. Stride 1 over the | ||
| 269 | - // narrow bound is ~33M multiply-adds; the wide bound is 25x that and | ||
| 270 | - // only runs on escalation, so this is not worth a resolution trade. | ||
| 271 | - let mut coarse_best = (0i64, -1.0f64, 0.0f64); | ||
| 272 | - for lag in -lag_max..=lag_max { | ||
| 273 | - if let Some((oa, ob)) = slice_at(lag, COARSE) { | ||
| 274 | - let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]); | ||
| 275 | - if c.abs() > coarse_best.1 { | ||
| 276 | - coarse_best = (lag, c.abs(), c); | ||
| 277 | - } | ||
| 278 | - } | ||
| 279 | - } | ||
| 280 | - let at_edge = coarse_best.0.abs() >= lag_max - SEARCH_STRIDE; | ||
| 281 | - let mut best = (coarse_best.0, -1.0f64, 0.0f64); | ||
| 282 | - let mut found = false; | ||
| 283 | - for lag in (coarse_best.0 - 2 * SEARCH_STRIDE)..=(coarse_best.0 + 2 * SEARCH_STRIDE) { | ||
| 284 | - let Some((oa, ob)) = slice_at(lag, WINDOW) else { | ||
| 285 | - continue; | ||
| 286 | - }; | ||
| 287 | - let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob); | ||
| 288 | - if n < 1024 { | ||
| 289 | - continue; | ||
| 290 | - } | ||
| 291 | - let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]); | ||
| 292 | - if c.abs() > best.1 { | ||
| 293 | - best = (lag, c.abs(), c); | ||
| 294 | - } | ||
| 295 | - found = true; | ||
| 296 | - } | ||
| 297 | - if !found { | ||
| 298 | - best = coarse_best; | ||
| 299 | - } | ||
| 300 | - // A winning lag at the search bound is not a measurement (the true | ||
| 301 | - // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if | ||
| 302 | - // it still sits at the edge fail here rather than hand any caller a | ||
| 303 | - // noise-driven number (instrument-at-bound class). | ||
| 304 | - if at_edge && lag_max < SEARCH_LAG_MAX { | ||
| 305 | - return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX); | ||
| 306 | - } | ||
| 307 | - assert!( | ||
| 308 | - !at_edge, | ||
| 309 | - "winning lag {} sits at the +/-{lag_max} search bound -- the true \ | ||
| 310 | - alignment is outside the search, corr {:.6} is noise, not a measurement", | ||
| 311 | - best.0, best.2 | ||
| 312 | - ); | ||
| 313 | - (best.0, best.2, at_edge) | ||
| 314 | -} | ||
| 315 | - | ||
| 316 | -/// Thin wrapper over `best_lag_correlation_ex` at `PLAIN_LAG_MAX`, for the | ||
| 317 | -/// many non-asserting call sites that only want `(lag, corr)` and whose true | ||
| 318 | -/// delay was never shown to exceed the original 4_000 bound. The one gate | ||
| 319 | -/// proven to need the wide bound (`sbr_real_library_matches_reference`) | ||
| 320 | -/// calls `_ex` directly with `SEARCH_LAG_MAX` instead of going through this | ||
| 321 | -/// wrapper. | ||
| 322 | -pub(super) fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { | ||
| 323 | - let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, PLAIN_LAG_MAX); | ||
| 324 | - (lag, corr) | ||
| 325 | -} | ||
| 326 | - | ||
| 327 | -/// Thin wrapper over `best_lag_correlation_ex` at a caller-supplied bound, | ||
| 328 | -/// for non-asserting call sites (asserting ones use `_ex` directly). | ||
| 329 | -pub(super) fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) { | ||
| 330 | - let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, lag_max); | ||
| 331 | - (lag, corr) | ||
| 332 | -} | ||
| 333 | - | ||
| 334 | -/// The robust two-stage lag search `sbr441_family_sample_drift_probe` proved | ||
| 335 | -/// out (round-55/56): a plain coarse-stride search picks the SINGLE best | ||
| 336 | -/// `COARSE`-sample-window candidate, which on periodic/tonal real music | ||
| 337 | -/// content routinely aliases onto a wrong lag (this file family's ref-L-vs- | ||
| 338 | -/// ref-R self-check scored a coarse-search lag=-24 corr=0.213, worse than | ||
| 339 | -/// the true fixed-lag comparison's 0.873). Instead of trusting the single | ||
| 340 | -/// coarse winner, keep the top `K` coarse candidates and refine EACH with a | ||
| 341 | -/// full-resolution, narrow (+/-128) search restricted to the file's first | ||
| 342 | -/// 10 seconds (`sample_rate`-derived) -- periodic aliasing needs many | ||
| 343 | -/// seconds of a repeating pattern to fool a full-resolution window, so the | ||
| 344 | -/// candidate that is genuinely aligned wins there even when it wasn't the | ||
| 345 | -/// coarse pass's top pick. Returns `(lag, corr, at_edge)` for the winning | ||
| 346 | -/// refined candidate, `at_edge` inherited from that candidate's own coarse | ||
| 347 | -/// Stride-1 lag search: correlates a `COARSE`-sized window at EVERY lag in | ||
| 348 | -/// `+/-lag_max`, then refines the winner with a full `WINDOW`. | ||
| 349 | -/// | ||
| 350 | -/// `robust_lag_topk`'s coarse pass steps by `SEARCH_STRIDE` (11) and then | ||
| 351 | -/// refines only its top-K coarse scorers. That ranking is meaningless when | ||
| 352 | -/// the true peak is narrower than the stride: on reeln's core-only PCM | ||
| 353 | -/// the correlation is 0.9998 at lag 481 and already 0.94 at 479, so no | ||
| 354 | -/// stride-11 grid point (the grid is 4 mod 11; 481 is 8 mod 11) scores | ||
| 355 | -/// anything but noise, the top-K is drawn from noise, and the search | ||
| 356 | -/// returned lag -52 corr 0.408 for a pair that is actually a 0.9998 match. | ||
| 357 | -/// FMJ, same instrument, same true lag 481, happened to land a noise-ranked | ||
| 358 | -/// candidate within the +/-128 refine window and read correctly -- the | ||
| 359 | -/// failure is luck-dependent, not file-dependent. Stride 1 over a 4_096 | ||
| 360 | -/// window is ~33M multiply-adds at `PLAIN_LAG_MAX`, cheaper than the top-K | ||
| 361 | -/// refinement it replaces, so the resolution is simply not worth trading. | ||
| 362 | -pub(super) fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { | ||
| 363 | - const COARSE: usize = 4_096; | ||
| 364 | - let start = window_start(ours, theirs); | ||
| 365 | - let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | ||
| 366 | - let (oa, ob) = if lag >= 0 { | ||
| 367 | - (start, start + lag as usize) | ||
| 368 | - } else { | ||
| 369 | - (start + (-lag) as usize, start) | ||
| 370 | - }; | ||
| 371 | - if oa + len > ours.len() || ob + len > theirs.len() { | ||
| 372 | - None | ||
| 373 | - } else { | ||
| 374 | - Some((oa, ob)) | ||
| 375 | - } | ||
| 376 | - }; | ||
| 377 | - let mut best = (0i64, -1.0f64); | ||
| 378 | - for lag in -lag_max..=lag_max { | ||
| 379 | - if let Some((oa, ob)) = slice_at(lag, COARSE) { | ||
| 380 | - let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs(); | ||
| 381 | - if c > best.1 { | ||
| 382 | - best = (lag, c); | ||
| 383 | - } | ||
| 384 | - } | ||
| 385 | - } | ||
| 386 | - let at_edge = best.0.abs() >= lag_max - 1; | ||
| 387 | - let mut refined = (best.0, -1.0f64); | ||
| 388 | - for lag in (best.0 - 2)..=(best.0 + 2) { | ||
| 389 | - let Some((oa, ob)) = slice_at(lag, WINDOW) else { | ||
| 390 | - continue; | ||
| 391 | - }; | ||
| 392 | - let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob); | ||
| 393 | - if n < 1024 { | ||
| 394 | - continue; | ||
| 395 | - } | ||
| 396 | - let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]).abs(); | ||
| 397 | - if c > refined.1 { | ||
| 398 | - refined = (lag, c); | ||
| 399 | - } | ||
| 400 | - } | ||
| 401 | - if refined.1 < 0.0 { | ||
| 402 | - refined = best; | ||
| 403 | - } | ||
| 404 | - (refined.0, refined.1, at_edge) | ||
| 405 | -} | ||
| 406 | - | ||
| 407 | -/// bucket (true if ITS coarse lag sat at the +/-`lag_max` search bound). | ||
| 408 | -pub(super) fn robust_lag_topk( | ||
| 409 | - ours: &[f32], | ||
| 410 | - theirs: &[f32], | ||
| 411 | - lag_max: i64, | ||
| 412 | - rate: u32, | ||
| 413 | - k: usize, | ||
| 414 | -) -> (i64, f64, bool) { | ||
| 415 | - const COARSE: usize = 4_096; | ||
| 416 | - let start = window_start(ours, theirs); | ||
| 417 | - let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | ||
| 418 | - let (oa, ob) = if lag >= 0 { | ||
| 419 | - (start, start + lag as usize) | ||
| 420 | - } else { | ||
| 421 | - (start + (-lag) as usize, start) | ||
| 422 | - }; | ||
| 423 | - if oa + len > ours.len() || ob + len > theirs.len() { | ||
| 424 | - None | ||
| 425 | - } else { | ||
| 426 | - Some((oa, ob)) | ||
| 427 | - } | ||
| 428 | - }; | ||
| 429 | - // Stride 1 (round-61), for the reason spelled out on | ||
| 430 | - // `exhaustive_lag_correlation`: a strided grid can miss a 1-sample-wide | ||
| 431 | - // peak entirely, and then the top-K is a ranking of noise. | ||
| 432 | - let mut coarse: Vec<(i64, f64)> = Vec::new(); | ||
| 433 | - for lag in -lag_max..=lag_max { | ||
| 434 | - if let Some((oa, ob)) = slice_at(lag, COARSE) { | ||
| 435 | - let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]); | ||
| 436 | - coarse.push((lag, c.abs())); | ||
| 437 | - } | ||
| 438 | - } | ||
| 439 | - coarse.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); | ||
| 440 | - let ten_s = 10 * rate.max(1) as usize; | ||
| 441 | - let mut best: (i64, f64, bool) = (0, -2.0, false); | ||
| 442 | - for &(cand_lag, _) in coarse.iter().take(k) { | ||
| 443 | - let at_edge = cand_lag.abs() >= lag_max - SEARCH_STRIDE; | ||
| 444 | - // `narrow_lag_at` computes `ob_i = oa0 + lag` directly (no sign | ||
| 445 | - // split the way `slice_at` above does), so a fixed `oa0 = 0` goes | ||
| 446 | - // negative -- and every lag in the whole +/-128 window skips -- | ||
| 447 | - // whenever `cand_lag` is negative enough (this file family's true | ||
| 448 | - // lag is -4674). Shift the window's start so it stays anchored to | ||
| 449 | - // "the first 10s of real content" while guaranteeing `ob_i >= 0` | ||
| 450 | - // even at the most-negative lag in the +/-128 refine range. | ||
| 451 | - let oa0 = (128 - cand_lag).max(0) as usize; | ||
| 452 | - let refine_len = ten_s.min(ours.len().saturating_sub(oa0)).min( | ||
| 453 | - theirs | ||
| 454 | - .len() | ||
| 455 | - .saturating_sub((oa0 as i64 + cand_lag).max(0) as usize), | ||
| 456 | - ); | ||
| 457 | - if refine_len < 1024 { | ||
| 458 | - continue; | ||
| 459 | - } | ||
| 460 | - let (rlag, rcorr) = narrow_lag_at(ours, theirs, oa0, refine_len, cand_lag, 128); | ||
| 461 | - if rcorr > best.1 { | ||
| 462 | - best = (rlag, rcorr, at_edge); | ||
| 463 | - } | ||
| 464 | - } | ||
| 465 | - best | ||
| 466 | -} | ||
| 467 | - | ||
| 468 | -pub(super) fn window_start(ours: &[f32], theirs: &[f32]) -> usize { | ||
| 469 | - const CHUNK: usize = 1_024; | ||
| 470 | - const CHUNKS: usize = 4; | ||
| 471 | - let end = ours.len().min(theirs.len()); | ||
| 472 | - let base = end.saturating_sub(WINDOW).min(ours.len() / 4); | ||
| 473 | - let power = |s: &[f32]| { | ||
| 474 | - s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / s.len().max(1) as f64 | ||
| 475 | - }; | ||
| 476 | - let floor = 1e-4 * power(&ours[base..end]).min(power(&theirs[base..end])); | ||
| 477 | - let loud = |p: usize| { | ||
| 478 | - p + CHUNK * CHUNKS <= end | ||
| 479 | - && (p..p + CHUNK * CHUNKS) | ||
| 480 | - .step_by(CHUNK) | ||
| 481 | - .all(|a| power(&ours[a..a + CHUNK]) > floor && power(&theirs[a..a + CHUNK]) > floor) | ||
| 482 | - }; | ||
| 483 | - (base..end).step_by(CHUNK).find(|&p| loud(p)).unwrap_or(base) | ||
| 484 | -} | ||
| 485 | - | ||
| 486 | -pub(super) fn upsample_2x(core: &[f32]) -> Vec<f32> { | ||
| 487 | - let mut out = Vec::with_capacity(core.len() * 2); | ||
| 488 | - for (i, &s) in core.iter().enumerate() { | ||
| 489 | - out.push(s); | ||
| 490 | - out.push((s + core.get(i + 1).copied().unwrap_or(s)) * 0.5); | ||
| 491 | - } | ||
| 492 | - out | ||
| 493 | -} | ||
| 494 | - | ||
| 495 | -pub(super) fn mono_prefix(planes: &[Vec<f32>]) -> usize { | ||
| 496 | - let first = &planes[0]; | ||
| 497 | - planes.get(1).map_or(first.len(), |second| { | ||
| 498 | - first.iter().zip(second).position(|(a, b)| a != b).unwrap_or(first.len()) | ||
| 499 | - }) | ||
| 500 | -} | ||
| 501 | - | ||
| 502 | -/// Signed correlation of `ours` against `theirs` at one fixed `lag`, full | ||
| 503 | -/// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation` | ||
| 504 | -/// uses internally -- used to test a hypothesized sign inversion by reusing | ||
| 505 | -/// a KNOWN-good lag (and window) from a healthy channel instead of trusting | ||
| 506 | -/// the (signed, positive-biased) search above to relocate both for a | ||
| 507 | -/// channel that may be exactly inverted at that same lag. Anchoring must | ||
| 508 | -/// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows | ||
| 509 | -/// otherwise cover different seconds of audio and are not comparable. | ||
| 510 | -pub(super) fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 { | ||
| 511 | - let start = window_start(ours, theirs); | ||
| 512 | - let (oa, ob) = if lag >= 0 { | ||
| 513 | - (start, start + lag as usize) | ||
| 514 | - } else { | ||
| 515 | - (start + (-lag) as usize, start) | ||
| 516 | - }; | ||
| 517 | - let n = WINDOW | ||
| 518 | - .min(ours.len().saturating_sub(oa)) | ||
| 519 | - .min(theirs.len().saturating_sub(ob)); | ||
| 520 | - if n < 1024 { | ||
| 521 | - return 0.0; | ||
| 522 | - } | ||
| 523 | - correlation(&ours[oa..oa + n], &theirs[ob..ob + n]) | ||
| 524 | -} | ||
| 525 | - | ||
| 526 | -/// A first-order RC low-pass, run forward then backward to cancel its own | ||
| 527 | -/// phase shift, giving a clean low-band/high-band split without pulling in a | ||
| 528 | -/// filter design dependency for a diagnostic. | ||
| 529 | -pub(super) fn lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> { | ||
| 530 | - let dt = 1.0 / f64::from(rate); | ||
| 531 | - let rc = 1.0 / (2.0 * std::f64::consts::PI * cutoff_hz); | ||
| 532 | - let alpha = (dt / (rc + dt)) as f32; | ||
| 533 | - let mut fwd = Vec::with_capacity(samples.len()); | ||
| 534 | - let mut y = 0.0f32; | ||
| 535 | - for &x in samples { | ||
| 536 | - y += alpha * (x - y); | ||
| 537 | - fwd.push(y); | ||
| 538 | - } | ||
| 539 | - let mut out = vec![0.0f32; fwd.len()]; | ||
| 540 | - y = 0.0; | ||
| 541 | - for i in (0..fwd.len()).rev() { | ||
| 542 | - y += alpha * (fwd[i] - y); | ||
| 543 | - out[i] = y; | ||
| 544 | - } | ||
| 545 | - out | ||
| 546 | -} | ||
| 547 | - | ||
| 548 | -pub(super) fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> { | ||
| 549 | - let low = lowpass(samples, rate, cutoff_hz); | ||
| 550 | - samples.iter().zip(&low).map(|(a, b)| a - b).collect() | ||
| 551 | -} | ||
| 552 | - | ||
| 553 | -/// DIAGNOSTIC (round-13): cascades `lowpass` three times for a much sharper | ||
| 554 | -/// stopband than the single first-order zero-phase filter the real | ||
| 555 | -/// assertion uses -- checking whether the below-crossover bar is actually | ||
| 556 | -/// being missed because of above-crossover energy leaking through the | ||
| 557 | -/// gentle single-pass rolloff, not because the low band itself is wrong. | ||
| 558 | -pub(super) fn sharp_lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> { | ||
| 559 | - let a = lowpass(samples, rate, cutoff_hz); | ||
| 560 | - let b = lowpass(&a, rate, cutoff_hz); | ||
| 561 | - lowpass(&b, rate, cutoff_hz) | ||
| 562 | -} | ||
| 563 | - | ||
| 564 | -/// Decisive-experiment diagnostic: correlates consecutive short (`WIN`) | ||
| 565 | -/// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g. | ||
| 566 | -/// the winning full-file lag from `best_lag_correlation`), searching a small | ||
| 567 | -/// local lag range per window. A per-frame continuity bug (dropped/duplicated | ||
| 568 | -/// samples at access-unit boundaries) shows up as the winning local lag | ||
| 569 | -/// DRIFTING linearly window to window; a bug that is not about concatenation | ||
| 570 | -/// (wrong band mapping, spectral corruption) shows up as a roughly constant | ||
| 571 | -/// lag with low/noisy correlation instead. | ||
| 572 | -pub(super) fn windowed_lag_drift( | ||
| 573 | - o: &[f32], | ||
| 574 | - t: &[f32], | ||
| 575 | - oa: usize, | ||
| 576 | - ob: usize, | ||
| 577 | - windows: usize, | ||
| 578 | -) -> Vec<(i64, f64)> { | ||
| 579 | - const WIN: usize = 4_096; | ||
| 580 | - const LOCAL_LAG: i64 = 2_000; | ||
| 581 | - let mut out = Vec::with_capacity(windows); | ||
| 582 | - for w in 0..windows { | ||
| 583 | - let base_o = oa + w * WIN; | ||
| 584 | - let base_t = ob + w * WIN; | ||
| 585 | - let mut best = (0i64, -1.0f64, 0.0f64); | ||
| 586 | - for lag in -LOCAL_LAG..=LOCAL_LAG { | ||
| 587 | - let ao = base_o as i64 + lag; | ||
| 588 | - if ao < 0 { | ||
| 589 | - continue; | ||
| 590 | - } | ||
| 591 | - let ao = ao as usize; | ||
| 592 | - if ao + WIN > o.len() || base_t + WIN > t.len() { | ||
| 593 | - continue; | ||
| 594 | - } | ||
| 595 | - let c = correlation(&o[ao..ao + WIN], &t[base_t..base_t + WIN]); | ||
| 596 | - if c.abs() > best.1 { | ||
| 597 | - best = (lag, c.abs(), c); | ||
| 598 | - } | ||
| 599 | - } | ||
| 600 | - out.push((best.0, best.2)); | ||
| 601 | - } | ||
| 602 | - out | ||
| 603 | -} | ||
| 604 | - | ||
| 605 | -/// DIAGNOSTIC (round-14, Task 2): per-QMF-band correlation over the | ||
| 606 | -/// above-crossover region. No 64-band QMF Analysis exists standalone in this | ||
| 607 | -/// crate, so this substitutes an STFT: magnitude-per-bin time series (one | ||
| 608 | -/// value per hop) for `ours` and `theirs`, correlated bin by bin, then | ||
| 609 | -/// averaged over the bins a QMF band of width `rate/128` Hz covers. A patch | ||
| 610 | -/// boundary in `build_patches`' target ranges landing on a low-correlation | ||
| 611 | -/// block convicts patch construction; an even spread across all HF bands | ||
| 612 | -/// with the map otherwise right points at gain mapping instead. | ||
| 613 | -/// Pearson correlation with no minimum-length floor -- `correlation`'s | ||
| 614 | -/// 1024-sample floor exists for raw audio windows, not the much shorter | ||
| 615 | -/// per-bin magnitude series this diagnostic correlates. | ||
| 616 | -pub(super) fn magnitude_series_correlation(a: &[f32], b: &[f32]) -> f64 { | ||
| 617 | - let n = a.len().min(b.len()); | ||
| 618 | - if n < 2 { | ||
| 619 | - return 0.0; | ||
| 620 | - } | ||
| 621 | - let (a, b) = (&a[..n], &b[..n]); | ||
| 622 | - let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 623 | - let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 624 | - let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect(); | ||
| 625 | - let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect(); | ||
| 626 | - let num = dot(&ac, &bc); | ||
| 627 | - let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt(); | ||
| 628 | - if den == 0.0 { 0.0 } else { num / den } | ||
| 629 | -} | ||
| 630 | - | ||
| 631 | -pub(super) fn per_band_correlation(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> { | ||
| 632 | - const FFT_LEN: usize = 2048; | ||
| 633 | - const HOP: usize = 1024; | ||
| 634 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 635 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 636 | - let bins = rfft.spectrum_len(); | ||
| 637 | - let n = o.len().min(t.len()); | ||
| 638 | - let hops = if n >= FFT_LEN { | ||
| 639 | - (n - FFT_LEN) / HOP + 1 | ||
| 640 | - } else { | ||
| 641 | - 0 | ||
| 642 | - }; | ||
| 643 | - let mut o_mag = vec![Vec::with_capacity(hops); bins]; | ||
| 644 | - let mut t_mag = vec![Vec::with_capacity(hops); bins]; | ||
| 645 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 646 | - for (src, dst) in [(o, &mut o_mag), (t, &mut t_mag)] { | ||
| 647 | - for h in 0..hops { | ||
| 648 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 649 | - win.apply(&mut block); | ||
| 650 | - rfft.forward(&block, &mut spectrum); | ||
| 651 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 652 | - dst[b].push(c.norm_sqr().sqrt()); | ||
| 653 | - } | ||
| 654 | - } | ||
| 655 | - } | ||
| 656 | - // QMF band width is `core_rate/128` where `core_rate` is the core | ||
| 657 | - // decoder's own sample rate -- half the SBR extension/output rate for a | ||
| 658 | - // plain (2x) HE-AAC stream -- not `output_rate/128`: measured against | ||
| 659 | - // this file's own kx=14 crossover, the correlation break lands exactly | ||
| 660 | - // at 14*(rate/256) Hz (2412 Hz), not at 14*(rate/128). | ||
| 661 | - let band_hz = f64::from(rate) / 256.0; | ||
| 662 | - let bin_hz = f64::from(rate) / FFT_LEN as f64; | ||
| 663 | - let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize; | ||
| 664 | - let mut out = Vec::with_capacity(num_bands); | ||
| 665 | - for band in 0..num_bands { | ||
| 666 | - let lo = (band as f64 * band_hz / bin_hz).floor() as usize; | ||
| 667 | - let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins); | ||
| 668 | - if lo >= hi { | ||
| 669 | - continue; | ||
| 670 | - } | ||
| 671 | - // round-16: correlating bin-by-bin then averaging the |corr| values | ||
| 672 | - // was the bug -- a QMF band's bins share one slowly-varying envelope, | ||
| 673 | - // but a tiny (sub-Hz) frequency offset between our filterbank and the | ||
| 674 | - // reference's shifts energy between adjacent bins hop to hop, so each | ||
| 675 | - // bin's OWN magnitude series decorrelates even though the band's | ||
| 676 | - // total energy (what a QMF band's single subband signal actually | ||
| 677 | - // carries) tracks the reference closely. Summing the bins' magnitudes | ||
| 678 | - // into one band-energy series per side FIRST, then correlating that | ||
| 679 | - // single pair, is robust to that intra-band leakage the way the | ||
| 680 | - // per-bin version wasn't. | ||
| 681 | - let hops_here = o_mag[lo].len().min(t_mag[lo].len()); | ||
| 682 | - let mut o_band = vec![0.0f32; hops_here]; | ||
| 683 | - let mut t_band = vec![0.0f32; hops_here]; | ||
| 684 | - for b in lo..hi { | ||
| 685 | - for h in 0..hops_here { | ||
| 686 | - o_band[h] += o_mag[b][h]; | ||
| 687 | - t_band[h] += t_mag[b][h]; | ||
| 688 | - } | ||
| 689 | - } | ||
| 690 | - let c = magnitude_series_correlation(&o_band, &t_band); | ||
| 691 | - if c.is_finite() { | ||
| 692 | - out.push((band as f64 * band_hz, c.abs(), band as f64)); | ||
| 693 | - } | ||
| 694 | - } | ||
| 695 | - out | ||
| 696 | -} | ||
| 697 | - | ||
| 698 | -/// Per-band PCM-domain lag search (round-15 candidate-A discriminator): | ||
| 699 | -/// `per_band_correlation`'s magnitude series has one sample per 1024-sample | ||
| 700 | -/// STFT `HOP`, far coarser than a single QMF slot (64 samples) -- a stage | ||
| 701 | -/// delay of one or a few slots between our HF path and the reference's would | ||
| 702 | -/// vanish into that hop bucket instead of showing up as a lag. This instead | ||
| 703 | -/// bandpasses `o`/`t` to each HF QMF band (the same zero-phase RC | ||
| 704 | -/// `highpass`/`lowpass` primitives the crossover split already uses) and | ||
| 705 | -/// searches PCM-sample lag directly, coarse-then-refine like | ||
| 706 | -/// `best_lag_correlation`, so a consistent nonzero peak lag (especially a | ||
| 707 | -/// multiple of 64 samples) convicts a per-stage time-alignment bug; lags | ||
| 708 | -/// clustered at/near zero exonerate it in favour of a patch-map or | ||
| 709 | -/// gain-mapping bug instead. Bands below kx (already known clean from | ||
| 710 | -/// `per_band_correlation`) are skipped -- only HF bands (14..) are searched. | ||
| 711 | -/// | ||
| 712 | -/// CONVICTED (round-26, Task 1): `bandpass_offset_probe` correlated this same | ||
| 713 | -/// `sharp_lowpass`/`sharp_highpass` cascade's band-k output against the | ||
| 714 | -/// REFERENCE's band-(k+/-10) output for several HF `k` -- and the DOWNWARD | ||
| 715 | -/// offset (band k-10, closer to the strongly-correlated below-crossover | ||
| 716 | -/// content) read a HIGHER correlation than the nominal same-band pairing in | ||
| 717 | -/// every HF band tried (e.g. band 34: same 0.937 vs -10 0.966). A filter | ||
| 718 | -/// with real ~172Hz selectivity cannot produce that; a "sharp" 3x-cascaded | ||
| 719 | -/// single-pole RC (~18dB/oct) at a 9kHz center still passes a wide swath | ||
| 720 | -/// below its corner, so each "band k" reading here is really "everything up | ||
| 721 | -/// to and including band k" -- cumulative correlation, dominated by the | ||
| 722 | -/// genuinely-matching low band, which manufactures the smooth monotonic | ||
| 723 | -/// decline earlier rounds chased. The reported LAG values are still valid | ||
| 724 | -/// (a filter with no stopband selectivity still has a passband delay that | ||
| 725 | -/// tracks the true alignment), but the reported per-band |corr| AMPLITUDE | ||
| 726 | -/// here is NOT a trustworthy per-band figure -- use `per_band_phase`'s | ||
| 727 | -/// cross-spectrum magnitude ratio (or the bin-level `bin_level_conviction`) | ||
| 728 | -/// for that instead. | ||
| 729 | -pub(super) fn per_band_lag_search(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, i64, f64)> { | ||
| 730 | - const LAG_MAX: i64 = 1_024; | ||
| 731 | - const COARSE_STEP: i64 = 8; | ||
| 732 | - const COARSE: usize = 4_096; | ||
| 733 | - const WIN: usize = 65_536; | ||
| 734 | - let band_hz = f64::from(rate) / 256.0; | ||
| 735 | - let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize; | ||
| 736 | - let n = o.len().min(t.len()); | ||
| 737 | - let start = n.saturating_sub(WIN + LAG_MAX as usize).min(n / 4); | ||
| 738 | - let mut out = Vec::new(); | ||
| 739 | - for band in 14..num_bands { | ||
| 740 | - let lo = (band as f64 * band_hz).max(1.0); | ||
| 741 | - let hi = ((band + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0); | ||
| 742 | - // A single-pole RC (the plain `highpass`/`lowpass` used for the | ||
| 743 | - // crossover split) has too gentle a rolloff to isolate a ~172Hz-wide | ||
| 744 | - // QMF band -- it leaks in the much stronger, well-correlated | ||
| 745 | - // below-crossover energy, which was confirmed here as a smooth, | ||
| 746 | - // frequency-monotonic false-high correlation with no matching cliff | ||
| 747 | - // in `per_band_correlation`'s FFT-bin version of the same bands. | ||
| 748 | - // `sharp_lowpass` (3x cascade, already used for the crossover-band | ||
| 749 | - // debug check) plus its highpass complement sharpens the stopband | ||
| 750 | - // enough that leakage from outside this one band stops dominating. | ||
| 751 | - let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> { | ||
| 752 | - s.iter() | ||
| 753 | - .zip(&sharp_lowpass(s, rate, cutoff)) | ||
| 754 | - .map(|(a, b)| a - b) | ||
| 755 | - .collect::<Vec<f32>>() | ||
| 756 | - }; | ||
| 757 | - let bp = |s: &[f32]| -> Vec<f32> { sharp_lowpass(&sharp_highpass(s, lo), rate, hi) }; | ||
| 758 | - let ob = bp(o); | ||
| 759 | - let tb = bp(t); | ||
| 760 | - let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | ||
| 761 | - let (oa, ta) = if lag >= 0 { | ||
| 762 | - (start, start + lag as usize) | ||
| 763 | - } else { | ||
| 764 | - (start + (-lag) as usize, start) | ||
| 765 | - }; | ||
| 766 | - if oa + len > ob.len() || ta + len > tb.len() { | ||
| 767 | - None | ||
| 768 | - } else { | ||
| 769 | - Some((oa, ta)) | ||
| 770 | - } | ||
| 771 | - }; | ||
| 772 | - let mut coarse = (0i64, -1.0f64, 0.0f64); | ||
| 773 | - let mut lag = -LAG_MAX; | ||
| 774 | - while lag <= LAG_MAX { | ||
| 775 | - if let Some((oa, ta)) = slice_at(lag, COARSE) { | ||
| 776 | - let c = correlation(&ob[oa..oa + COARSE], &tb[ta..ta + COARSE]); | ||
| 777 | - if c.abs() > coarse.1 { | ||
| 778 | - coarse = (lag, c.abs(), c); | ||
| 779 | - } | ||
| 780 | - } | ||
| 781 | - lag += COARSE_STEP; | ||
| 782 | - } | ||
| 783 | - let mut best = coarse; | ||
| 784 | - for lag in (coarse.0 - COARSE_STEP)..=(coarse.0 + COARSE_STEP) { | ||
| 785 | - if let Some((oa, ta)) = slice_at(lag, WIN) { | ||
| 786 | - let c = correlation(&ob[oa..oa + WIN], &tb[ta..ta + WIN]); | ||
| 787 | - if c.abs() > best.1 { | ||
| 788 | - best = (lag, c.abs(), c); | ||
| 789 | - } | ||
| 790 | - } | ||
| 791 | - } | ||
| 792 | - out.push((band as f64 * band_hz, best.0, best.2)); | ||
| 793 | - } | ||
| 794 | - out | ||
| 795 | -} | ||
| 796 | - | ||
| 797 | -/// DIAGNOSTIC (round-16, Task 2): per-band phase offset and magnitude | ||
| 798 | -/// transfer between `o` and `t`, over the SAME aligned window | ||
| 799 | -/// `per_band_correlation` uses. Reuses the STFT-and-coherent-band-sum | ||
| 800 | -/// machinery `per_band_correlation` was just fixed to use (sum the complex | ||
| 801 | -/// spectrum, not just its magnitude, across a band's bins first, so a | ||
| 802 | -/// per-bin sub-band redistribution doesn't wash out a genuine per-band | ||
| 803 | -/// phase relationship) but keeps the complex value: the cross-spectrum | ||
| 804 | -/// `sum_h O_band(h) * conj(T_band(h))` accumulated over every hop gives one | ||
| 805 | -/// phasor per band whose angle is the (hop-weighted) phase offset between | ||
| 806 | -/// `o` and `t` in that band and whose radius, once normalized by each side's | ||
| 807 | -/// own energy, gives the magnitude transfer ratio. | ||
| 808 | -pub(super) fn per_band_phase(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> { | ||
| 809 | - const FFT_LEN: usize = 2048; | ||
| 810 | - const HOP: usize = 1024; | ||
| 811 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 812 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 813 | - let bins = rfft.spectrum_len(); | ||
| 814 | - let n = o.len().min(t.len()); | ||
| 815 | - let hops = if n >= FFT_LEN { | ||
| 816 | - (n - FFT_LEN) / HOP + 1 | ||
| 817 | - } else { | ||
| 818 | - 0 | ||
| 819 | - }; | ||
| 820 | - let mut o_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 821 | - let mut t_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 822 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 823 | - for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] { | ||
| 824 | - for h in 0..hops { | ||
| 825 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 826 | - win.apply(&mut block); | ||
| 827 | - rfft.forward(&block, &mut spectrum); | ||
| 828 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 829 | - dst[b].push(*c); | ||
| 830 | - } | ||
| 831 | - } | ||
| 832 | - } | ||
| 833 | - let band_hz = f64::from(rate) / 256.0; | ||
| 834 | - let bin_hz = f64::from(rate) / FFT_LEN as f64; | ||
| 835 | - let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize; | ||
| 836 | - let mut out = Vec::with_capacity(num_bands); | ||
| 837 | - for band in 0..num_bands { | ||
| 838 | - let lo = (band as f64 * band_hz / bin_hz).floor() as usize; | ||
| 839 | - let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins); | ||
| 840 | - if lo >= hi || hops == 0 { | ||
| 841 | - continue; | ||
| 842 | - } | ||
| 843 | - // Cross-spectrum accumulated PER BIN over hops, THEN summed across | ||
| 844 | - // the band's bins -- not the reverse. Complex-summing the band's | ||
| 845 | - // bins together at each hop first (as an earlier version of this | ||
| 846 | - // function did) mixes in `O_b * conj(T_b')` cross terms for every | ||
| 847 | - // b != b' pair once the per-hop products are formed; two adjacent | ||
| 848 | - // FFT bins carry unrelated instantaneous phase (they are different | ||
| 849 | - // frequencies), so those cross terms are pure noise that swamped the | ||
| 850 | - // real per-bin coherence and produced an incoherent, near-random | ||
| 851 | - // phase reading across exactly the HF bands `per_band_lag_search`'s | ||
| 852 | - // direct PCM correlation shows are highly correlated at lag 0/-1. | ||
| 853 | - let mut cross_re = 0.0f64; | ||
| 854 | - let mut cross_im = 0.0f64; | ||
| 855 | - let mut o_energy = 0.0f64; | ||
| 856 | - let mut t_energy = 0.0f64; | ||
| 857 | - for b in lo..hi { | ||
| 858 | - for h in 0..hops { | ||
| 859 | - let ob = o_spec[b][h]; | ||
| 860 | - let tb = t_spec[b][h]; | ||
| 861 | - let cross = ob * tb.conj(); | ||
| 862 | - cross_re += f64::from(cross.re); | ||
| 863 | - cross_im += f64::from(cross.im); | ||
| 864 | - o_energy += | ||
| 865 | - f64::from(ob.re) * f64::from(ob.re) + f64::from(ob.im) * f64::from(ob.im); | ||
| 866 | - t_energy += | ||
| 867 | - f64::from(tb.re) * f64::from(tb.re) + f64::from(tb.im) * f64::from(tb.im); | ||
| 868 | - } | ||
| 869 | - } | ||
| 870 | - let phase = cross_im.atan2(cross_re); | ||
| 871 | - let mag_ratio = if t_energy > 0.0 { | ||
| 872 | - (o_energy / t_energy).sqrt() | ||
| 873 | - } else { | ||
| 874 | - 0.0 | ||
| 875 | - }; | ||
| 876 | - out.push((band as f64 * band_hz, phase, mag_ratio)); | ||
| 877 | - } | ||
| 878 | - out | ||
| 879 | -} | ||
| 880 | - | ||
| 881 | -/// Round-26, Task 1: convicts (or acquits) `per_band_lag_search`'s bandpass. | ||
| 882 | -/// Applies the SAME 3x-cascaded RC bandpass that diagnostic uses to `o` at | ||
| 883 | -/// band `band` and to `t` at band `band` (same-band control), `band+offset` | ||
| 884 | -/// and `band-offset`. A single-pole cascade's stopband is gentle enough that | ||
| 885 | -/// "band k" may really pass "everything below f_k" -- if so, `o`-band-k and | ||
| 886 | -/// `t`-band-(k+offset) still both carry the same dominant low-band leakage | ||
| 887 | -/// and read highly correlated even though their nominal passbands don't | ||
| 888 | -/// overlap at all, which convicts the filter, not the content. Below the SBR | ||
| 889 | -/// crossover, genuinely narrowband-matching content should decorrelate | ||
| 890 | -/// quickly as `offset` grows; a HF band that does NOT decorrelate at | ||
| 891 | -/// `offset` bands away is evidence the filter has no real selectivity there. | ||
| 892 | -pub(super) fn bandpass_offset_probe( | ||
| 893 | - o: &[f32], | ||
| 894 | - t: &[f32], | ||
| 895 | - rate: u32, | ||
| 896 | - band: usize, | ||
| 897 | - offset: i64, | ||
| 898 | -) -> (f64, f64, f64) { | ||
| 899 | - let band_hz = f64::from(rate) / 256.0; | ||
| 900 | - let bp_at = |s: &[f32], b: usize| -> Vec<f32> { | ||
| 901 | - let lo = (b as f64 * band_hz).max(1.0); | ||
| 902 | - let hi = ((b + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0); | ||
| 903 | - let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> { | ||
| 904 | - s.iter() | ||
| 905 | - .zip(&sharp_lowpass(s, rate, cutoff)) | ||
| 906 | - .map(|(a, b)| a - b) | ||
| 907 | - .collect::<Vec<f32>>() | ||
| 908 | - }; | ||
| 909 | - sharp_lowpass(&sharp_highpass(s, lo), rate, hi) | ||
| 910 | - }; | ||
| 911 | - let ob = bp_at(o, band); | ||
| 912 | - let same_corr = correlation(&ob, &bp_at(t, band)); | ||
| 913 | - let hi_band = band as i64 + offset; | ||
| 914 | - let hi_corr = if hi_band >= 0 { | ||
| 915 | - correlation(&ob, &bp_at(t, hi_band as usize)) | ||
| 916 | - } else { | ||
| 917 | - 0.0 | ||
| 918 | - }; | ||
| 919 | - let lo_band = band as i64 - offset; | ||
| 920 | - let lo_corr = if lo_band >= 0 { | ||
| 921 | - correlation(&ob, &bp_at(t, lo_band as usize)) | ||
| 922 | - } else { | ||
| 923 | - 0.0 | ||
| 924 | - }; | ||
| 925 | - (same_corr, hi_corr, lo_corr) | ||
| 926 | -} | ||
| 927 | - | ||
| 928 | -/// Round-26, Task 2: bin-level (no filter, no cross-band summing) comparison | ||
| 929 | -/// of `o` against `t` in the most energetic HF SBR bands at/above `min_band`, | ||
| 930 | -/// three ways: DIRECT (bin i vs bin i), MIRROR (bin i vs the band's bins in | ||
| 931 | -/// REVERSED order -- the signature of a QMF band-orientation/parity flip | ||
| 932 | -/// between our own-design synthesis and the reference's convention: energies | ||
| 933 | -/// right, direct corr ~0, phase random, exactly what round-14/16 observed), | ||
| 934 | -/// and SHIFT (the whole `BINS_PER_SBR_BAND`-bin band matched one band up or | ||
| 935 | -/// down -- the signature of a `build_patches` source-mapping offset). | ||
| 936 | -/// Coherence per bin pair is | ||
| 937 | -/// `|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)` (in | ||
| 938 | -/// [0,1]; 1 = perfectly phase+magnitude locked, ~0 = unrelated), accumulated | ||
| 939 | -/// over the SAME aligned hops `per_band_phase` uses, then averaged over the | ||
| 940 | -/// band's 8 bins. Bands are picked by OUR OWN energy (the "real" HF content), | ||
| 941 | -/// not the reference's, so a genuinely-silent HF band can't crowd out an | ||
| 942 | -/// energetic one just because it happens to sort first. | ||
| 943 | -pub(super) fn bin_level_conviction( | ||
| 944 | - o: &[f32], | ||
| 945 | - t: &[f32], | ||
| 946 | - rate: u32, | ||
| 947 | - min_band: usize, | ||
| 948 | - top_n: usize, | ||
| 949 | -) -> Vec<(f64, f64, f64, f64, f64, f64)> { | ||
| 950 | - const FFT_LEN: usize = 2048; | ||
| 951 | - const HOP: usize = 1024; | ||
| 952 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 953 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 954 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 955 | - let bins = rfft.spectrum_len(); | ||
| 956 | - let n = o.len().min(t.len()); | ||
| 957 | - let hops = if n >= FFT_LEN { | ||
| 958 | - (n - FFT_LEN) / HOP + 1 | ||
| 959 | - } else { | ||
| 960 | - 0 | ||
| 961 | - }; | ||
| 962 | - let mut o_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 963 | - let mut t_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 964 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 965 | - for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] { | ||
| 966 | - for h in 0..hops { | ||
| 967 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 968 | - win.apply(&mut block); | ||
| 969 | - rfft.forward(&block, &mut spectrum); | ||
| 970 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 971 | - dst[b].push(*c); | ||
| 972 | - } | ||
| 973 | - } | ||
| 974 | - } | ||
| 975 | - if hops == 0 { | ||
| 976 | - return Vec::new(); | ||
| 977 | - } | ||
| 978 | - let band_hz = f64::from(rate) / 256.0; | ||
| 979 | - let num_bands = bins / BINS_PER_SBR_BAND; | ||
| 980 | - let coh = |ob: usize, tb: usize| -> f64 { | ||
| 981 | - if ob >= bins || tb >= bins { | ||
| 982 | - return 0.0; | ||
| 983 | - } | ||
| 984 | - let mut cross_re = 0.0f64; | ||
| 985 | - let mut cross_im = 0.0f64; | ||
| 986 | - let mut o_e = 0.0f64; | ||
| 987 | - let mut t_e = 0.0f64; | ||
| 988 | - for h in 0..hops { | ||
| 989 | - let oc = o_spec[ob][h]; | ||
| 990 | - let tc = t_spec[tb][h]; | ||
| 991 | - let cross = oc * tc.conj(); | ||
| 992 | - cross_re += f64::from(cross.re); | ||
| 993 | - cross_im += f64::from(cross.im); | ||
| 994 | - o_e += f64::from(oc.norm_sqr()); | ||
| 995 | - t_e += f64::from(tc.norm_sqr()); | ||
| 996 | - } | ||
| 997 | - let den = (o_e * t_e).sqrt(); | ||
| 998 | - if den > 0.0 { | ||
| 999 | - (cross_re * cross_re + cross_im * cross_im).sqrt() / den | ||
| 1000 | - } else { | ||
| 1001 | - 0.0 | ||
| 1002 | - } | ||
| 1003 | - }; | ||
| 1004 | - // Rank HF bands by OUR OWN energy, so the energetic-band handful is | ||
| 1005 | - // chosen by real content, not by whatever the reference happens to carry. | ||
| 1006 | - let mut ranked: Vec<(usize, f64)> = (min_band..num_bands) | ||
| 1007 | - .map(|band| { | ||
| 1008 | - let lo = band * BINS_PER_SBR_BAND; | ||
| 1009 | - let hi = (lo + BINS_PER_SBR_BAND).min(bins); | ||
| 1010 | - let e: f64 = (lo..hi) | ||
| 1011 | - .flat_map(|b| o_spec[b].iter()) | ||
| 1012 | - .map(|c| f64::from(c.norm_sqr())) | ||
| 1013 | - .sum(); | ||
| 1014 | - (band, e) | ||
| 1015 | - }) | ||
| 1016 | - .collect(); | ||
| 1017 | - ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); | ||
| 1018 | - let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect(); | ||
| 1019 | - selected.sort_unstable(); | ||
| 1020 | - | ||
| 1021 | - let mut out = Vec::with_capacity(selected.len()); | ||
| 1022 | - for band in selected { | ||
| 1023 | - let lo = band * BINS_PER_SBR_BAND; | ||
| 1024 | - let hi = (lo + BINS_PER_SBR_BAND).min(bins); | ||
| 1025 | - if lo >= hi { | ||
| 1026 | - continue; | ||
| 1027 | - } | ||
| 1028 | - let mut energy = 0.0f64; | ||
| 1029 | - let mut direct = 0.0f64; | ||
| 1030 | - let mut mirror = 0.0f64; | ||
| 1031 | - let mut shift_up = 0.0f64; | ||
| 1032 | - let mut shift_down = 0.0f64; | ||
| 1033 | - let count = (hi - lo) as f64; | ||
| 1034 | - // `i` feeds several derived indices (mirror/shift math below), not a | ||
| 1035 | - // plain element access -- an iterator/enumerate rewrite would be | ||
| 1036 | - // less readable here, not more. | ||
| 1037 | - #[allow(clippy::needless_range_loop)] | ||
| 1038 | - for i in lo..hi { | ||
| 1039 | - energy += o_spec[i] | ||
| 1040 | - .iter() | ||
| 1041 | - .map(|c| f64::from(c.norm_sqr())) | ||
| 1042 | - .sum::<f64>(); | ||
| 1043 | - direct += coh(i, i); | ||
| 1044 | - mirror += coh(i, hi + lo - 1 - i); | ||
| 1045 | - shift_up += coh(i, i + BINS_PER_SBR_BAND); | ||
| 1046 | - shift_down += if i >= BINS_PER_SBR_BAND { | ||
| 1047 | - coh(i, i - BINS_PER_SBR_BAND) | ||
| 1048 | - } else { | ||
| 1049 | - 0.0 | ||
| 1050 | - }; | ||
| 1051 | - } | ||
| 1052 | - out.push(( | ||
| 1053 | - band as f64 * band_hz, | ||
| 1054 | - energy, | ||
| 1055 | - direct / count, | ||
| 1056 | - mirror / count, | ||
| 1057 | - shift_up / count, | ||
| 1058 | - shift_down / count, | ||
| 1059 | - )); | ||
| 1060 | - } | ||
| 1061 | - out | ||
| 1062 | -} | ||
| 1063 | - | ||
| 1064 | -/// Round-38, Task 1: sweeps a constant HF-only sample-domain lag `k*64` | ||
| 1065 | -/// (`k` in -8..=8; one QMF synthesis slot = 64 output samples) applied ONLY | ||
| 1066 | -/// to `o`'s STFT read position, holding `t` fixed at the globally-aligned | ||
| 1067 | -/// `ob` offset -- the low band (which drives the global `lag` this window is | ||
| 1068 | -/// already re-sliced to via `oa`/`ob`) is never touched by this probe. Per | ||
| 1069 | -/// bin, coherence is the SAME "direct" measure `bin_level_conviction` uses | ||
| 1070 | -/// (`|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)`), then | ||
| 1071 | -/// averaged uniformly over every bin in every HF SBR band from `min_band` | ||
| 1072 | -/// upward (both parity regions together, not just the top-energy handful) -- | ||
| 1073 | -/// a clear peak at k != 0 convicts a constant reference-vs-ours HF alignment | ||
| 1074 | -/// offset of that many QMF slots; a flat or zero-peaked curve refutes it. | ||
| 1075 | -pub(super) fn hf_lag_sweep( | ||
| 1076 | - o: &[f32], | ||
| 1077 | - t: &[f32], | ||
| 1078 | - oa: usize, | ||
| 1079 | - ob: usize, | ||
| 1080 | - n: usize, | ||
| 1081 | - min_band: usize, | ||
| 1082 | -) -> Vec<(i64, f64)> { | ||
| 1083 | - const FFT_LEN: usize = 2048; | ||
| 1084 | - const HOP: usize = 1024; | ||
| 1085 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 1086 | - const MAX_K: i64 = 8; | ||
| 1087 | - const SLOT: i64 = 64; | ||
| 1088 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 1089 | - let probe_bins = ec_dsp::RealFft::<f32>::new(FFT_LEN).spectrum_len(); | ||
| 1090 | - let num_bands = probe_bins / BINS_PER_SBR_BAND; | ||
| 1091 | - let lo_bin = min_band * BINS_PER_SBR_BAND; | ||
| 1092 | - let hi_bin = (num_bands * BINS_PER_SBR_BAND).min(probe_bins); | ||
| 1093 | - if lo_bin >= hi_bin { | ||
| 1094 | - return Vec::new(); | ||
| 1095 | - } | ||
| 1096 | - let hops = if n >= FFT_LEN { | ||
| 1097 | - (n - FFT_LEN) / HOP + 1 | ||
| 1098 | - } else { | ||
| 1099 | - 0 | ||
| 1100 | - }; | ||
| 1101 | - if hops == 0 { | ||
| 1102 | - return Vec::new(); | ||
| 1103 | - } | ||
| 1104 | - let spec_of = |s: &[f32], start: usize| -> Vec<Vec<ec_dsp::Complex<f32>>> { | ||
| 1105 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 1106 | - let mut spec = vec![Vec::with_capacity(hops); probe_bins]; | ||
| 1107 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); probe_bins]; | ||
| 1108 | - for h in 0..hops { | ||
| 1109 | - let mut block = s[start + h * HOP..start + h * HOP + FFT_LEN].to_vec(); | ||
| 1110 | - win.apply(&mut block); | ||
| 1111 | - rfft.forward(&block, &mut spectrum); | ||
| 1112 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 1113 | - spec[b].push(*c); | ||
| 1114 | - } | ||
| 1115 | - } | ||
| 1116 | - spec | ||
| 1117 | - }; | ||
| 1118 | - let mut out = Vec::with_capacity((2 * MAX_K + 1) as usize); | ||
| 1119 | - for k in -MAX_K..=MAX_K { | ||
| 1120 | - let shift = k * SLOT; | ||
| 1121 | - // Prefer shifting `o`'s read start (the literal ask), but `o` has no | ||
| 1122 | - // samples before its own decode origin -- when the global alignment | ||
| 1123 | - // already pins `oa` at (or near) 0, negative `k` has nowhere to read | ||
| 1124 | - // from on that side. `coh(o[x], t[y])` only depends on `x - y`, so | ||
| 1125 | - // shifting `t`'s read start the OPPOSITE direction instead | ||
| 1126 | - // (`ob - shift`) tests the exact same relative offset and `t` (the | ||
| 1127 | - // reference, decoded in full) always has the room. Only actually | ||
| 1128 | - // falls back for `o`-boundary-starved `k`; the un-shifted `t` path | ||
| 1129 | - // above is untouched for every `k` that fits within `o`. | ||
| 1130 | - let (o_start, t_start) = { | ||
| 1131 | - let os = oa as i64 + shift; | ||
| 1132 | - if os >= 0 && os as usize + n <= o.len() { | ||
| 1133 | - (os as usize, ob) | ||
| 1134 | - } else { | ||
| 1135 | - let ts = ob as i64 - shift; | ||
| 1136 | - if ts >= 0 && ts as usize + n <= t.len() { | ||
| 1137 | - (oa, ts as usize) | ||
| 1138 | - } else { | ||
| 1139 | - continue; | ||
| 1140 | - } | ||
| 1141 | - } | ||
| 1142 | - }; | ||
| 1143 | - let o_spec = spec_of(o, o_start); | ||
| 1144 | - let t_spec = spec_of(t, t_start); | ||
| 1145 | - let mut sum = 0.0f64; | ||
| 1146 | - let mut count = 0usize; | ||
| 1147 | - for b in lo_bin..hi_bin { | ||
| 1148 | - let mut cross_re = 0.0f64; | ||
| 1149 | - let mut cross_im = 0.0f64; | ||
| 1150 | - let mut o_e = 0.0f64; | ||
| 1151 | - let mut t_e = 0.0f64; | ||
| 1152 | - for h in 0..hops { | ||
| 1153 | - let oc = o_spec[b][h]; | ||
| 1154 | - let tc = t_spec[b][h]; | ||
| 1155 | - let cross = oc * tc.conj(); | ||
| 1156 | - cross_re += f64::from(cross.re); | ||
| 1157 | - cross_im += f64::from(cross.im); | ||
| 1158 | - o_e += f64::from(oc.norm_sqr()); | ||
| 1159 | - t_e += f64::from(tc.norm_sqr()); | ||
| 1160 | - } | ||
| 1161 | - let den = (o_e * t_e).sqrt(); | ||
| 1162 | - if den > 0.0 { | ||
| 1163 | - sum += (cross_re * cross_re + cross_im * cross_im).sqrt() / den; | ||
| 1164 | - count += 1; | ||
| 1165 | - } | ||
| 1166 | - } | ||
| 1167 | - out.push((k, if count > 0 { sum / count as f64 } else { 0.0 })); | ||
| 1168 | - } | ||
| 1169 | - out | ||
| 1170 | -} | ||
| 1171 | - | ||
| 1172 | -/// Round-40, Task 1: fine spectral-BIN shift scan on patched HF content. | ||
| 1173 | -/// `hf_lag_sweep` (round-38) only tested whole-QMF-slot SAMPLE-domain lags and | ||
| 1174 | -/// round-26's `bin_level_conviction` shift columns only tested whole | ||
| 1175 | -/// `BINS_PER_SBR_BAND` (8-bin) band shifts; neither ever tried a FEW-bin | ||
| 1176 | -/// spectral offset, which is what a half-QMF-band (~4-bin, ~86Hz at this | ||
| 1177 | -/// 2048-window scale) carrier convention mismatch on patched content would | ||
| 1178 | -/// look like -- it would leave envelope/magnitude tracking (and therefore | ||
| 1179 | -/// `hf_lag_sweep`'s k=0 peak) intact while destroying bin-level phase | ||
| 1180 | -/// coherence via linear phase drift across the band. The audio itself is | ||
| 1181 | -/// never shifted; only the bin INDEX used to pair `o` against `t` moves, by | ||
| 1182 | -/// `b` in -7..=+7 (deliberately short of the 8-bin whole-band-shift case | ||
| 1183 | -/// round-26 already ruled out). Reports mean direct coherence | ||
| 1184 | -/// (`bin_level_conviction`'s same `|sum_h O(h)*conj(T(h))| / | ||
| 1185 | -/// sqrt(sum|O|^2*sum|T|^2)` measure) separately over the even-gap [14,28) and | ||
| 1186 | -/// odd-gap [28,43) SBR-band regions -- the offset, if real, could differ by | ||
| 1187 | -/// patch parity given round-35/36's convention-fix history. A clear peak at | ||
| 1188 | -/// `b != 0` (region-dependent sign allowed) convicts a constant sub-band | ||
| 1189 | -/// frequency offset; a flat/0-peaked curve refutes it. | ||
| 1190 | -pub(super) fn hf_bin_shift_sweep( | ||
| 1191 | - o: &[f32], | ||
| 1192 | - t: &[f32], | ||
| 1193 | - _rate: u32, | ||
| 1194 | - region_lo_band: usize, | ||
| 1195 | - region_hi_band: usize, | ||
| 1196 | -) -> Vec<(i64, f64)> { | ||
| 1197 | - const FFT_LEN: usize = 2048; | ||
| 1198 | - const HOP: usize = 1024; | ||
| 1199 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 1200 | - const MAX_B: i64 = 7; | ||
| 1201 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 1202 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 1203 | - let bins = rfft.spectrum_len(); | ||
| 1204 | - let n = o.len().min(t.len()); | ||
| 1205 | - let hops = if n >= FFT_LEN { | ||
| 1206 | - (n - FFT_LEN) / HOP + 1 | ||
| 1207 | - } else { | ||
| 1208 | - 0 | ||
| 1209 | - }; | ||
| 1210 | - if hops == 0 { | ||
| 1211 | - return Vec::new(); | ||
| 1212 | - } | ||
| 1213 | - let mut o_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1214 | - let mut t_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1215 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 1216 | - for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] { | ||
| 1217 | - for h in 0..hops { | ||
| 1218 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 1219 | - win.apply(&mut block); | ||
| 1220 | - rfft.forward(&block, &mut spectrum); | ||
| 1221 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 1222 | - dst[b].push(*c); | ||
| 1223 | - } | ||
| 1224 | - } | ||
| 1225 | - } | ||
| 1226 | - let lo_bin = region_lo_band * BINS_PER_SBR_BAND; | ||
| 1227 | - let hi_bin = (region_hi_band * BINS_PER_SBR_BAND).min(bins); | ||
| 1228 | - let coh = |ob: usize, tb: usize| -> f64 { | ||
| 1229 | - if ob >= bins || tb >= bins { | ||
| 1230 | - return 0.0; | ||
| 1231 | - } | ||
| 1232 | - let mut cross_re = 0.0f64; | ||
| 1233 | - let mut cross_im = 0.0f64; | ||
| 1234 | - let mut o_e = 0.0f64; | ||
| 1235 | - let mut t_e = 0.0f64; | ||
| 1236 | - for h in 0..hops { | ||
| 1237 | - let oc = o_spec[ob][h]; | ||
| 1238 | - let tc = t_spec[tb][h]; | ||
| 1239 | - let cross = oc * tc.conj(); | ||
| 1240 | - cross_re += f64::from(cross.re); | ||
| 1241 | - cross_im += f64::from(cross.im); | ||
| 1242 | - o_e += f64::from(oc.norm_sqr()); | ||
| 1243 | - t_e += f64::from(tc.norm_sqr()); | ||
| 1244 | - } | ||
| 1245 | - let den = (o_e * t_e).sqrt(); | ||
| 1246 | - if den > 0.0 { | ||
| 1247 | - (cross_re * cross_re + cross_im * cross_im).sqrt() / den | ||
| 1248 | - } else { | ||
| 1249 | - 0.0 | ||
| 1250 | - } | ||
| 1251 | - }; | ||
| 1252 | - let mut out = Vec::with_capacity((2 * MAX_B + 1) as usize); | ||
| 1253 | - if lo_bin >= hi_bin { | ||
| 1254 | - return out; | ||
| 1255 | - } | ||
| 1256 | - for b in -MAX_B..=MAX_B { | ||
| 1257 | - let mut sum = 0.0f64; | ||
| 1258 | - let mut count = 0usize; | ||
| 1259 | - for i in lo_bin..hi_bin { | ||
| 1260 | - let oi = i as i64 + b; | ||
| 1261 | - if oi < 0 || oi as usize >= bins { | ||
| 1262 | - continue; | ||
| 1263 | - } | ||
| 1264 | - sum += coh(oi as usize, i); | ||
| 1265 | - count += 1; | ||
| 1266 | - } | ||
| 1267 | - out.push((b, if count > 0 { sum / count as f64 } else { 0.0 })); | ||
| 1268 | - } | ||
| 1269 | - out | ||
| 1270 | -} | ||
| 1271 | - | ||
| 1272 | -/// Round-40, Task 2: per-STFT-frame complex-gain fingerprint. For the same | ||
| 1273 | -/// top-energy HF bands `bin_level_conviction` picks (ranked by `o`'s own | ||
| 1274 | -/// energy), takes each band's single dominant bin (highest total `|O(h)|^2` | ||
| 1275 | -/// across hops) and reports the per-hop complex ratio `O(h)/T(h)` trajectory | ||
| 1276 | -/// -- `(magnitude, phase_radians)` per STFT frame -- for that bin across | ||
| 1277 | -/// every frame. Read afterward, not here: constant magnitude+phase is a pure | ||
| 1278 | -/// gain (would predict HIGH coherence, contradicting the low bin-coherence | ||
| 1279 | -/// measured elsewhere -- flags a measurement issue, not a real | ||
| 1280 | -/// transformation); phase advancing at a roughly fixed per-frame rate is a | ||
| 1281 | -/// genuine carrier frequency offset (the rate converts directly to Hz and | ||
| 1282 | -/// cross-checks `hf_bin_shift_sweep`'s peak); phase jumping specifically at | ||
| 1283 | -/// hop indices lining up with SBR envelope borders is a per-envelope | ||
| 1284 | -/// gain/phase re-seed; anything else (magnitude and phase both wandering with | ||
| 1285 | -/// no fixed rate) is genuinely uncorrelated content frame to frame. | ||
| 1286 | -pub(super) fn hf_complex_ratio_trajectory( | ||
| 1287 | - o: &[f32], | ||
| 1288 | - t: &[f32], | ||
| 1289 | - rate: u32, | ||
| 1290 | - min_band: usize, | ||
| 1291 | - top_n: usize, | ||
| 1292 | -) -> Vec<(f64, Vec<(f64, f64)>)> { | ||
| 1293 | - const FFT_LEN: usize = 2048; | ||
| 1294 | - const HOP: usize = 1024; | ||
| 1295 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 1296 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 1297 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 1298 | - let bins = rfft.spectrum_len(); | ||
| 1299 | - let n = o.len().min(t.len()); | ||
| 1300 | - let hops = if n >= FFT_LEN { | ||
| 1301 | - (n - FFT_LEN) / HOP + 1 | ||
| 1302 | - } else { | ||
| 1303 | - 0 | ||
| 1304 | - }; | ||
| 1305 | - if hops == 0 { | ||
| 1306 | - return Vec::new(); | ||
| 1307 | - } | ||
| 1308 | - let mut o_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1309 | - let mut t_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1310 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 1311 | - for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] { | ||
| 1312 | - for h in 0..hops { | ||
| 1313 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 1314 | - win.apply(&mut block); | ||
| 1315 | - rfft.forward(&block, &mut spectrum); | ||
| 1316 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 1317 | - dst[b].push(*c); | ||
| 1318 | - } | ||
| 1319 | - } | ||
| 1320 | - } | ||
| 1321 | - let band_hz = f64::from(rate) / 256.0; | ||
| 1322 | - let num_bands = bins / BINS_PER_SBR_BAND; | ||
| 1323 | - if min_band >= num_bands { | ||
| 1324 | - return Vec::new(); | ||
| 1325 | - } | ||
| 1326 | - let mut ranked: Vec<(usize, f64)> = (min_band..num_bands) | ||
| 1327 | - .map(|band| { | ||
| 1328 | - let lo = band * BINS_PER_SBR_BAND; | ||
| 1329 | - let hi = (lo + BINS_PER_SBR_BAND).min(bins); | ||
| 1330 | - let e: f64 = (lo..hi) | ||
| 1331 | - .flat_map(|b| o_spec[b].iter()) | ||
| 1332 | - .map(|c| f64::from(c.norm_sqr())) | ||
| 1333 | - .sum(); | ||
| 1334 | - (band, e) | ||
| 1335 | - }) | ||
| 1336 | - .collect(); | ||
| 1337 | - ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); | ||
| 1338 | - let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect(); | ||
| 1339 | - selected.sort_unstable(); | ||
| 1340 | - | ||
| 1341 | - let mut out = Vec::with_capacity(selected.len()); | ||
| 1342 | - for band in selected { | ||
| 1343 | - let lo = band * BINS_PER_SBR_BAND; | ||
| 1344 | - let hi = (lo + BINS_PER_SBR_BAND).min(bins); | ||
| 1345 | - if lo >= hi { | ||
| 1346 | - continue; | ||
| 1347 | - } | ||
| 1348 | - let dom = (lo..hi) | ||
| 1349 | - .max_by(|&a, &b| { | ||
| 1350 | - let ea: f64 = o_spec[a].iter().map(|c| f64::from(c.norm_sqr())).sum(); | ||
| 1351 | - let eb: f64 = o_spec[b].iter().map(|c| f64::from(c.norm_sqr())).sum(); | ||
| 1352 | - ea.partial_cmp(&eb).unwrap() | ||
| 1353 | - }) | ||
| 1354 | - .unwrap(); | ||
| 1355 | - // Complex division `O/T` done by hand (`ec_dsp::Complex` carries no | ||
| 1356 | - // `Div` impl -- it is a from-scratch minimal type, see fft.rs): `O * | ||
| 1357 | - // conj(T) / |T|^2`. | ||
| 1358 | - let traj: Vec<(f64, f64)> = (0..hops) | ||
| 1359 | - .map(|h| { | ||
| 1360 | - let oc = o_spec[dom][h]; | ||
| 1361 | - let tc = t_spec[dom][h]; | ||
| 1362 | - let t_e = f64::from(tc.norm_sqr()); | ||
| 1363 | - if t_e > 1e-12 { | ||
| 1364 | - let (or, oi) = (f64::from(oc.re), f64::from(oc.im)); | ||
| 1365 | - let (tr, ti) = (f64::from(tc.re), f64::from(tc.im)); | ||
| 1366 | - let rr = (or * tr + oi * ti) / t_e; | ||
| 1367 | - let ri = (oi * tr - or * ti) / t_e; | ||
| 1368 | - ((rr * rr + ri * ri).sqrt(), ri.atan2(rr)) | ||
| 1369 | - } else { | ||
| 1370 | - (0.0, 0.0) | ||
| 1371 | - } | ||
| 1372 | - }) | ||
| 1373 | - .collect(); | ||
| 1374 | - out.push((band as f64 * band_hz, traj)); | ||
| 1375 | - } | ||
| 1376 | - out | ||
| 1377 | -} | ||
| 1378 | - | ||
| 1379 | -/// Round-45, Task 3 THIRD WITNESS. Every prior round compared OURS against | ||
| 1380 | -/// the REFERENCE directly -- a pairwise measurement that can never say which | ||
| 1381 | -/// side is wrong when they disagree. This builds a reference-free model: a | ||
| 1382 | -/// pure "plain patch-copy + per-band energy match" reconstruction of HF | ||
| 1383 | -/// content from the REFERENCE's own LOW band (the one piece of ground truth | ||
| 1384 | -/// both decoders start from and our own low-band round-trip already measures | ||
| 1385 | -/// as near-identity), using the verified patch map | ||
| 1386 | -/// `[(0,14,14),(3,28,11),(0,39,3),(13,42,1)]` and this file's own established | ||
| 1387 | -/// `band_hz = rate/256`, `BINS_PER_SBR_BAND = FFT_LEN/256 = 8` convention | ||
| 1388 | -/// (round-14/16; NOT the `rate/128` scale the naive spec reading suggests -- | ||
| 1389 | -/// that value indexes the QMF/hybrid analysis grid, not this STFT-bin grid, | ||
| 1390 | -/// and using it here would be the "trap" that bit round-42 elsewhere in this | ||
| 1391 | -/// file. The patch map's own band numbers (14/28/39/42/43) only make sense | ||
| 1392 | -/// under the `/256` convention already used everywhere else in this file that | ||
| 1393 | -/// touches the patch map -- confirmed by construction, not re-derived here). | ||
| 1394 | -/// | ||
| 1395 | -/// For each HF band in `[14, 43)` and each STFT hop, the simulated bins are | ||
| 1396 | -/// the REFERENCE's low-band bins at the patch-mapped source position, then | ||
| 1397 | -/// RESCALED per (band, hop) to match the comparison side's own energy in | ||
| 1398 | -/// that band/hop -- two separate rescalings, "sim-normalized-to-ours" and | ||
| 1399 | -/// "sim-normalized-to-reference" -- so the only thing left for the | ||
| 1400 | -/// coherence measure to see is phase/content structure, not a gain | ||
| 1401 | -/// difference (the gain question is already closed by prior rounds). Returns | ||
| 1402 | -/// `(band, coherence)` pairs for sim-vs-reference and sim-vs-ours. | ||
| 1403 | -type BandCoherenceTable = Vec<(usize, f64)>; | ||
| 1404 | - | ||
| 1405 | -pub(super) fn hf_patch_simulator(o: &[f32], t: &[f32], rate: u32) -> (BandCoherenceTable, BandCoherenceTable) { | ||
| 1406 | - const FFT_LEN: usize = 2048; | ||
| 1407 | - const HOP: usize = 1024; | ||
| 1408 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 1409 | - const PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)]; | ||
| 1410 | - let _ = rate; // band Hz not needed here; caller converts band index itself. | ||
| 1411 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 1412 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 1413 | - let bins = rfft.spectrum_len(); | ||
| 1414 | - let n = o.len().min(t.len()); | ||
| 1415 | - let hops = if n >= FFT_LEN { | ||
| 1416 | - (n - FFT_LEN) / HOP + 1 | ||
| 1417 | - } else { | ||
| 1418 | - 0 | ||
| 1419 | - }; | ||
| 1420 | - if hops == 0 { | ||
| 1421 | - return (Vec::new(), Vec::new()); | ||
| 1422 | - } | ||
| 1423 | - let mut o_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1424 | - let mut t_spec = vec![Vec::with_capacity(hops); bins]; | ||
| 1425 | - let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 1426 | - for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] { | ||
| 1427 | - for h in 0..hops { | ||
| 1428 | - let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec(); | ||
| 1429 | - win.apply(&mut block); | ||
| 1430 | - rfft.forward(&block, &mut spectrum); | ||
| 1431 | - for (b, c) in spectrum.iter().enumerate() { | ||
| 1432 | - dst[b].push(*c); | ||
| 1433 | - } | ||
| 1434 | - } | ||
| 1435 | - } | ||
| 1436 | - // Plain patch copy: sim's target bins, per hop, are the reference's | ||
| 1437 | - // source bins, unmodified (no phase adjustment) -- modelling exactly the | ||
| 1438 | - // "plain patch+gain" hypothesis the charter names. | ||
| 1439 | - let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f32, 0.0); hops]; bins]; | ||
| 1440 | - for (src, tgt, width) in PATCHES { | ||
| 1441 | - let src_lo = src * BINS_PER_SBR_BAND; | ||
| 1442 | - let tgt_lo = tgt * BINS_PER_SBR_BAND; | ||
| 1443 | - let len = width * BINS_PER_SBR_BAND; | ||
| 1444 | - for i in 0..len { | ||
| 1445 | - if src_lo + i >= bins || tgt_lo + i >= bins { | ||
| 1446 | - continue; | ||
| 1447 | - } | ||
| 1448 | - for h in 0..hops { | ||
| 1449 | - sim_spec[tgt_lo + i][h] = t_spec[src_lo + i][h]; | ||
| 1450 | - } | ||
| 1451 | - } | ||
| 1452 | - } | ||
| 1453 | - let num_bands = bins / BINS_PER_SBR_BAND; | ||
| 1454 | - let top_band = 43.min(num_bands); | ||
| 1455 | - // Per (band, hop) rescale of `sim` to match `target`'s energy in that | ||
| 1456 | - // band/hop, then the same magnitude-of-summed-cross-spectrum coherence | ||
| 1457 | - // measure every prior round's `coh` helper uses (already scale-invariant | ||
| 1458 | - // to a CONSTANT gain across hops; this rescale additionally removes a | ||
| 1459 | - // gain that varies hop-to-hop, isolating phase/content agreement). | ||
| 1460 | - let band_coherence = |target: &[Vec<ec_dsp::Complex<f32>>]| -> Vec<(usize, f64)> { | ||
| 1461 | - (14..top_band) | ||
| 1462 | - .map(|band| { | ||
| 1463 | - let lo = band * BINS_PER_SBR_BAND; | ||
| 1464 | - let hi = (lo + BINS_PER_SBR_BAND).min(bins); | ||
| 1465 | - let mut cross_re = 0.0f64; | ||
| 1466 | - let mut cross_im = 0.0f64; | ||
| 1467 | - let mut sim_e = 0.0f64; | ||
| 1468 | - let mut tgt_e = 0.0f64; | ||
| 1469 | - for h in 0..hops { | ||
| 1470 | - let se: f64 = (lo..hi).map(|b| f64::from(sim_spec[b][h].norm_sqr())).sum(); | ||
| 1471 | - let te: f64 = (lo..hi).map(|b| f64::from(target[b][h].norm_sqr())).sum(); | ||
| 1472 | - if se <= 1e-20 || te <= 0.0 { | ||
| 1473 | - continue; | ||
| 1474 | - } | ||
| 1475 | - let scale = (te / se).sqrt() as f32; | ||
| 1476 | - for b in lo..hi { | ||
| 1477 | - let sc = sim_spec[b][h].scale(scale); | ||
| 1478 | - let tc = target[b][h]; | ||
| 1479 | - let cross = sc * tc.conj(); | ||
| 1480 | - cross_re += f64::from(cross.re); | ||
| 1481 | - cross_im += f64::from(cross.im); | ||
| 1482 | - sim_e += f64::from(sc.norm_sqr()); | ||
| 1483 | - tgt_e += f64::from(tc.norm_sqr()); | ||
| 1484 | - } | ||
| 1485 | - } | ||
| 1486 | - let den = (sim_e * tgt_e).sqrt(); | ||
| 1487 | - let coh = if den > 0.0 { | ||
| 1488 | - (cross_re * cross_re + cross_im * cross_im).sqrt() / den | ||
| 1489 | - } else { | ||
| 1490 | - 0.0 | ||
| 1491 | - }; | ||
| 1492 | - (band, coh) | ||
| 1493 | - }) | ||
| 1494 | - .collect() | ||
| 1495 | - }; | ||
| 1496 | - (band_coherence(&t_spec), band_coherence(&o_spec)) | ||
| 1497 | -} | ||
| 1498 | - | ||
| 1499 | -/// (Round-46) The QMF-domain exact version of [`hf_patch_simulator`]: same | ||
| 1500 | -/// plain-patch+gain model, same verified patch map, but read through the | ||
| 1501 | -/// crate's own [`ec_aac::sbr_qmf::HfAnalysis`] (64-band, `rate/128`-wide | ||
| 1502 | -/// bands -- exactly the patch map's own band unit) instead of an 8-bin-wide | ||
| 1503 | -/// STFT approximation, closing the "too crude to reach a verdict" gap | ||
| 1504 | -/// round-45's STFT simulator hit. Validated by | ||
| 1505 | -/// `hf_analysis_self_consistency_control` in `sbr_qmf.rs` before use here | ||
| 1506 | -/// (own-band plurality + self-coherence + round-trip control). Same | ||
| 1507 | -/// per-(band, window) energy-rescale-then-coherence method as the STFT | ||
| 1508 | -/// version, windowed over `WIN` consecutive QMF slots (`WIN * SYNTHESIS_BANDS | ||
| 1509 | -/// = 1024` samples, matching the STFT version's hop) so the rescale has | ||
| 1510 | -/// enough samples to estimate energy from, not so many that within-window | ||
| 1511 | -/// phase drift is averaged away. | ||
| 1512 | -pub(super) const QMF_PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)]; | ||
| 1513 | - | ||
| 1514 | -/// Shared build step for the QMF-domain third-witness instruments: both | ||
| 1515 | -/// PCMs read through [`ec_aac::sbr_qmf::HfAnalysis`], plus the plain | ||
| 1516 | -/// patch-copy simulation of the reference's own low band, all in the | ||
| 1517 | -/// `(band, slot)` domain. Returns `(ours, reference, sim)`. | ||
| 1518 | -/// `[band][slot]` complex QMF-domain series. | ||
| 1519 | -type QmfBandSlots = Vec<Vec<ec_dsp::Complex<f64>>>; | ||
| 1520 | - | ||
| 1521 | -pub(super) fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBandSlots) { | ||
| 1522 | - use ec_aac::sbr_qmf::{HfAnalysis, SYNTHESIS_BANDS}; | ||
| 1523 | - let n = o.len().min(t.len()); | ||
| 1524 | - let slots = n / SYNTHESIS_BANDS; | ||
| 1525 | - let analyze = |pcm: &[f32]| -> QmfBandSlots { | ||
| 1526 | - let mut ana = HfAnalysis::new(); | ||
| 1527 | - let mut out: QmfBandSlots = (0..SYNTHESIS_BANDS) | ||
| 1528 | - .map(|_| Vec::with_capacity(slots)) | ||
| 1529 | - .collect(); | ||
| 1530 | - for s in 0..slots { | ||
| 1531 | - let mut chunk = [0.0f32; SYNTHESIS_BANDS]; | ||
| 1532 | - chunk.copy_from_slice(&pcm[s * SYNTHESIS_BANDS..(s + 1) * SYNTHESIS_BANDS]); | ||
| 1533 | - let sub = ana.process_slot(&chunk); | ||
| 1534 | - for (b, c) in sub.iter().enumerate() { | ||
| 1535 | - out[b].push(*c); | ||
| 1536 | - } | ||
| 1537 | - } | ||
| 1538 | - out | ||
| 1539 | - }; | ||
| 1540 | - let o_spec = analyze(o); | ||
| 1541 | - let t_spec = analyze(t); | ||
| 1542 | - // Plain patch copy: sim's target-band slot series is the reference's | ||
| 1543 | - // source-band slot series, unmodified. | ||
| 1544 | - let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f64, 0.0); slots]; SYNTHESIS_BANDS]; | ||
| 1545 | - for (src, tgt, width) in QMF_PATCHES { | ||
| 1546 | - for i in 0..width { | ||
| 1547 | - if src + i >= SYNTHESIS_BANDS || tgt + i >= SYNTHESIS_BANDS { | ||
| 1548 | - continue; | ||
| 1549 | - } | ||
| 1550 | - sim_spec[tgt + i] = t_spec[src + i].clone(); | ||
| 1551 | - } | ||
| 1552 | - } | ||
| 1553 | - (o_spec, t_spec, sim_spec) | ||
| 1554 | -} | ||
| 1555 | - | ||
| 1556 | -/// Returns `(sim-vs-reference, sim-vs-ours, ours-vs-reference)` -- the last | ||
| 1557 | -/// pairing (round-48, Task 4a) is the ultimate content-match witness: how | ||
| 1558 | -/// well our actual HF QMF content agrees with the reference's, with no | ||
| 1559 | -/// simulator in between. | ||
| 1560 | -pub(super) fn hf_patch_simulator_qmf( | ||
| 1561 | - o: &[f32], | ||
| 1562 | - t: &[f32], | ||
| 1563 | -) -> (BandCoherenceTable, BandCoherenceTable, BandCoherenceTable) { | ||
| 1564 | - use ec_aac::sbr_qmf::SYNTHESIS_BANDS; | ||
| 1565 | - const WIN: usize = 16; | ||
| 1566 | - let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t); | ||
| 1567 | - let slots = sim_spec.first().map(Vec::len).unwrap_or(0); | ||
| 1568 | - if slots < WIN { | ||
| 1569 | - return (Vec::new(), Vec::new(), Vec::new()); | ||
| 1570 | - } | ||
| 1571 | - let top_band = 43.min(SYNTHESIS_BANDS); | ||
| 1572 | - let windows = slots / WIN; | ||
| 1573 | - let band_coherence = |source: &[Vec<ec_dsp::Complex<f64>>], | ||
| 1574 | - target: &[Vec<ec_dsp::Complex<f64>>]| | ||
| 1575 | - -> Vec<(usize, f64)> { | ||
| 1576 | - (14..top_band) | ||
| 1577 | - .map(|band| { | ||
| 1578 | - let mut cross_re = 0.0f64; | ||
| 1579 | - let mut cross_im = 0.0f64; | ||
| 1580 | - let mut sim_e = 0.0f64; | ||
| 1581 | - let mut tgt_e = 0.0f64; | ||
| 1582 | - for w in 0..windows { | ||
| 1583 | - let lo = w * WIN; | ||
| 1584 | - let hi = lo + WIN; | ||
| 1585 | - let se: f64 = source[band][lo..hi] | ||
| 1586 | - .iter() | ||
| 1587 | - .map(|c| c.re * c.re + c.im * c.im) | ||
| 1588 | - .sum(); | ||
| 1589 | - let te: f64 = target[band][lo..hi] | ||
| 1590 | - .iter() | ||
| 1591 | - .map(|c| c.re * c.re + c.im * c.im) | ||
| 1592 | - .sum(); | ||
| 1593 | - if se <= 1e-20 || te <= 0.0 { | ||
| 1594 | - continue; | ||
| 1595 | - } | ||
| 1596 | - let scale = (te / se).sqrt(); | ||
| 1597 | - for i in lo..hi { | ||
| 1598 | - let sc = source[band][i].scale(scale); | ||
| 1599 | - let tc = target[band][i]; | ||
| 1600 | - let cross = sc * tc.conj(); | ||
| 1601 | - cross_re += cross.re; | ||
| 1602 | - cross_im += cross.im; | ||
| 1603 | - sim_e += sc.re * sc.re + sc.im * sc.im; | ||
| 1604 | - tgt_e += tc.re * tc.re + tc.im * tc.im; | ||
| 1605 | - } | ||
| 1606 | - } | ||
| 1607 | - let den = (sim_e * tgt_e).sqrt(); | ||
| 1608 | - let coh = if den > 0.0 { | ||
| 1609 | - (cross_re * cross_re + cross_im * cross_im).sqrt() / den | ||
| 1610 | - } else { | ||
| 1611 | - 0.0 | ||
| 1612 | - }; | ||
| 1613 | - (band, coh) | ||
| 1614 | - }) | ||
| 1615 | - .collect() | ||
| 1616 | - }; | ||
| 1617 | - ( | ||
| 1618 | - band_coherence(&sim_spec, &t_spec), | ||
| 1619 | - band_coherence(&sim_spec, &o_spec), | ||
| 1620 | - band_coherence(&o_spec, &t_spec), | ||
| 1621 | - ) | ||
| 1622 | -} | ||
| 1623 | - | ||
| 1624 | -/// (Round-46, Task 2) Per-band 2nd-order complex prediction transfer fit | ||
| 1625 | -/// between the plain-copy sim series and the REFERENCE's own HF series for | ||
| 1626 | -/// that band: `ref[l] ~= a0*sim[l] + a1*sim[l-1] + a2*sim[l-2]`, least | ||
| 1627 | -/// squares over the whole file -- the same shape `sbr_hf::generate`'s own | ||
| 1628 | -/// chirp filter has (`y = residual + ca1*y[n-1] + ca2*y[n-2]`, an IIR rather | ||
| 1629 | -/// than this FIR, but both are order-2 linear reshapings of the same copied | ||
| 1630 | -/// content), so the fitted taps are directly comparable in spirit to our own | ||
| 1631 | -/// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is | ||
| 1632 | -/// also just a plain copy here", taps with real weight on lag 1/2 mean a | ||
| 1633 | -/// genuine order-2 transformation is present. | ||
| 1634 | -/// `target_is_ours`: fit against our own decode (`o_spec`) instead of the | ||
| 1635 | -/// reference's (`t_spec`) -- same `sim` (built from the reference's own low | ||
| 1636 | -/// band either way), so the two calls' fitted taps are directly comparable: | ||
| 1637 | -/// what transform sim would need to become ours vs. to become the reference. | ||
| 1638 | -#[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout | ||
| 1639 | -pub(super) fn hf_patch_transfer_fit( | ||
| 1640 | - o: &[f32], | ||
| 1641 | - t: &[f32], | ||
| 1642 | - bands: &[usize], | ||
| 1643 | - target_is_ours: bool, | ||
| 1644 | -) -> Vec<(usize, [ec_dsp::Complex<f64>; 3])> { | ||
| 1645 | - let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t); | ||
| 1646 | - let target_spec = if target_is_ours { &o_spec } else { &t_spec }; | ||
| 1647 | - let mut results = Vec::new(); | ||
| 1648 | - for &band in bands { | ||
| 1649 | - if band >= sim_spec.len() { | ||
| 1650 | - continue; | ||
| 1651 | - } | ||
| 1652 | - let sim_raw = &sim_spec[band]; | ||
| 1653 | - let ref_raw = &target_spec[band]; | ||
| 1654 | - let len = sim_raw.len().min(ref_raw.len()); | ||
| 1655 | - if len < 8 { | ||
| 1656 | - continue; | ||
| 1657 | - } | ||
| 1658 | - // Normalize each series to unit RMS first: the raw QMF-domain | ||
| 1659 | - // amplitudes differ by orders of magnitude (sim carries no envelope | ||
| 1660 | - // gain, `ref` does), which would otherwise make every fitted | ||
| 1661 | - // coefficient collapse toward the gain ratio rather than the | ||
| 1662 | - // fraction-of-`ref`-explained-by-which-lag this fit is meant to | ||
| 1663 | - // read off. | ||
| 1664 | - let rms = |s: &[ec_dsp::Complex<f64>]| -> f64 { | ||
| 1665 | - (s[..len] | ||
| 1666 | - .iter() | ||
| 1667 | - .map(|c| c.re * c.re + c.im * c.im) | ||
| 1668 | - .sum::<f64>() | ||
| 1669 | - / len as f64) | ||
| 1670 | - .sqrt() | ||
| 1671 | - .max(1e-300) | ||
| 1672 | - }; | ||
| 1673 | - let sim_scale = 1.0 / rms(sim_raw); | ||
| 1674 | - let ref_scale = 1.0 / rms(ref_raw); | ||
| 1675 | - let sim: Vec<ec_dsp::Complex<f64>> = | ||
| 1676 | - sim_raw[..len].iter().map(|c| c.scale(sim_scale)).collect(); | ||
| 1677 | - let refb: Vec<ec_dsp::Complex<f64>> = | ||
| 1678 | - ref_raw[..len].iter().map(|c| c.scale(ref_scale)).collect(); | ||
| 1679 | - let sim = &sim[..]; | ||
| 1680 | - let refb = &refb[..]; | ||
| 1681 | - // Complex 3x3 Hermitian normal equations: r[i][j] = sum sim[l-i] conj(sim[l-j]), | ||
| 1682 | - // p[i] = sum sim[l-i] conj(ref[l])... solved as R^T a = p with R real basis in | ||
| 1683 | - // complex arithmetic (Gaussian elimination with partial pivoting by magnitude). | ||
| 1684 | - let mut r = [[ec_dsp::Complex::new(0.0f64, 0.0); 3]; 3]; | ||
| 1685 | - let mut p = [ec_dsp::Complex::new(0.0f64, 0.0); 3]; | ||
| 1686 | - for l in 2..len { | ||
| 1687 | - let s = [sim[l], sim[l - 1], sim[l - 2]]; | ||
| 1688 | - let y = refb[l]; | ||
| 1689 | - for i in 0..3 { | ||
| 1690 | - p[i] = p[i] + s[i].conj() * y; | ||
| 1691 | - for j in 0..3 { | ||
| 1692 | - r[i][j] = r[i][j] + s[i].conj() * s[j]; | ||
| 1693 | - } | ||
| 1694 | - } | ||
| 1695 | - } | ||
| 1696 | - // Gaussian elimination on the augmented [r | p] system. | ||
| 1697 | - let mut aug = r; | ||
| 1698 | - let mut rhs = p; | ||
| 1699 | - for col in 0..3 { | ||
| 1700 | - let mut piv = col; | ||
| 1701 | - let mut best = aug[col][col].norm_sqr(); | ||
| 1702 | - for row in (col + 1)..3 { | ||
| 1703 | - let m = aug[row][col].norm_sqr(); | ||
| 1704 | - if m > best { | ||
| 1705 | - best = m; | ||
| 1706 | - piv = row; | ||
| 1707 | - } | ||
| 1708 | - } | ||
| 1709 | - if best < 1e-24 { | ||
| 1710 | - continue; | ||
| 1711 | - } | ||
| 1712 | - aug.swap(col, piv); | ||
| 1713 | - rhs.swap(col, piv); | ||
| 1714 | - let inv = aug[col][col].conj().scale(1.0 / best); | ||
| 1715 | - for row in (col + 1)..3 { | ||
| 1716 | - let f = aug[row][col] * inv; | ||
| 1717 | - for k in 0..3 { | ||
| 1718 | - aug[row][k] = aug[row][k] - f * aug[col][k]; | ||
| 1719 | - } | ||
| 1720 | - rhs[row] = rhs[row] - f * rhs[col]; | ||
| 1721 | - } | ||
| 1722 | - } | ||
| 1723 | - let mut a = [ec_dsp::Complex::new(0.0f64, 0.0); 3]; | ||
| 1724 | - for row in (0..3).rev() { | ||
| 1725 | - let mut acc = rhs[row]; | ||
| 1726 | - for k in (row + 1)..3 { | ||
| 1727 | - acc = acc - aug[row][k] * a[k]; | ||
| 1728 | - } | ||
| 1729 | - let d = aug[row][row]; | ||
| 1730 | - a[row] = if d.norm_sqr() > 1e-24 { | ||
| 1731 | - acc * d.conj().scale(1.0 / d.norm_sqr()) | ||
| 1732 | - } else { | ||
| 1733 | - ec_dsp::Complex::new(0.0, 0.0) | ||
| 1734 | - }; | ||
| 1735 | - } | ||
| 1736 | - results.push((band, a)); | ||
| 1737 | - } | ||
| 1738 | - results | ||
| 1739 | -} | ||
| 1740 | - | ||
| 1741 | -/// A file discovered under the user's own media directories: its path, which | ||
| 1742 | -/// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the | ||
| 1743 | -/// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used | ||
| 1744 | -/// only to draw the below/above-crossover line for localization, not as a | ||
| 1745 | -/// spec-exact `kx` band edge. | ||
| 1746 | -pub(super) struct Candidate { | ||
| 1747 | - pub(super) path: PathBuf, | ||
| 1748 | - /// Which AAC stream, 0-based among AAC streams only -- what | ||
| 1749 | - /// `extract_from` selects out of the demuxer's stream list. | ||
| 1750 | - pub(super) aac_stream: usize, | ||
| 1751 | - /// The same stream's absolute ffprobe/ffmpeg index -- what `-map` | ||
| 1752 | - /// selects, and not the same number when the container also carries a | ||
| 1753 | - /// non-AAC audio track before it (FMJ's mkv has an AC-3 track between its | ||
| 1754 | - /// two AAC ones). | ||
| 1755 | - pub(super) ffmpeg_stream: usize, | ||
| 1756 | - pub(super) crossover_hz: f64, | ||
| 1757 | -} | ||
| 1758 | - | ||
| 1759 | -/// Round-20 residual/side-info correlation. Builds a (frame x band) residual | ||
| 1760 | -/// ENERGY grid at AU-aligned 2048-output-sample blocks -- a plain (2x) SBR | ||
| 1761 | -/// stream reconstructs exactly one 2048-sample block per core access unit, | ||
| 1762 | -/// so `n`-th block lines up 1:1 with `ec_aac::sbr_sideinfo_log()`'s `frame` | ||
| 1763 | -/// counter -- then cross-tabulates that grid against every side-info feature | ||
| 1764 | -/// the log carries. FFT is linear, so `FFT(o_block) - FFT(t_block) == | ||
| 1765 | -/// FFT(o_block - t_block)`: the residual's own per-bin energy is obtained | ||
| 1766 | -/// directly from each side's spectrum without ever materializing a | ||
| 1767 | -/// time-domain residual array. `band` is the same `rate/256`-wide index | ||
| 1768 | -/// domain `per_band_correlation`/`tables.kx`/`f_high`/`f_noise` all already | ||
| 1769 | -/// share (measured in round-14/round-16), so a side-info row's `f_high`/ | ||
| 1770 | -/// `f_noise` boundaries index straight into this grid's bins with no | ||
| 1771 | -/// rescaling. | ||
| 1772 | -pub(super) fn residual_sideinfo_analysis(o: &[f32], t: &[f32], oa: usize, ob: usize, rate: u32, ch: usize) { | ||
| 1773 | - let rows: Vec<_> = ec_aac::sbr_sideinfo_log() | ||
| 1774 | - .into_iter() | ||
| 1775 | - .filter(|r| r.ch == ch) | ||
| 1776 | - .collect(); | ||
| 1777 | - if rows.is_empty() { | ||
| 1778 | - eprintln!(" ch{ch} SIDEINFO: no rows logged (set EC_AAC_SBR_SIDEINFO_DEBUG too)"); | ||
| 1779 | - return; | ||
| 1780 | - } | ||
| 1781 | - const FFT_LEN: usize = 2048; | ||
| 1782 | - let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 1783 | - let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 1784 | - let bins = rfft.spectrum_len(); | ||
| 1785 | - let mut o_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 1786 | - let mut t_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 1787 | - | ||
| 1788 | - // Per-frame residual bin-energy vector (index = `band`, per-bin, not yet | ||
| 1789 | - // grouped) and, alongside it, a per-bin peakiness ratio (own-bin energy | ||
| 1790 | - // vs its 3-bin neighbourhood mean) used by the whiteness check. | ||
| 1791 | - let mut energy: std::collections::HashMap<usize, Vec<f64>> = std::collections::HashMap::new(); | ||
| 1792 | - for row in &rows { | ||
| 1793 | - if energy.contains_key(&row.frame) { | ||
| 1794 | - continue; | ||
| 1795 | - } | ||
| 1796 | - let base_o = oa + row.frame * FFT_LEN; | ||
| 1797 | - let base_t = ob + row.frame * FFT_LEN; | ||
| 1798 | - if base_o + FFT_LEN > o.len() || base_t + FFT_LEN > t.len() { | ||
| 1799 | - continue; | ||
| 1800 | - } | ||
| 1801 | - let mut ob_win = o[base_o..base_o + FFT_LEN].to_vec(); | ||
| 1802 | - let mut tb_win = t[base_t..base_t + FFT_LEN].to_vec(); | ||
| 1803 | - win.apply(&mut ob_win); | ||
| 1804 | - win.apply(&mut tb_win); | ||
| 1805 | - rfft.forward(&ob_win, &mut o_spec); | ||
| 1806 | - rfft.forward(&tb_win, &mut t_spec); | ||
| 1807 | - let e: Vec<f64> = o_spec | ||
| 1808 | - .iter() | ||
| 1809 | - .zip(&t_spec) | ||
| 1810 | - .map(|(a, b)| f64::from((*a - *b).norm_sqr())) | ||
| 1811 | - .collect(); | ||
| 1812 | - energy.insert(row.frame, e); | ||
| 1813 | - } | ||
| 1814 | - if energy.is_empty() { | ||
| 1815 | - eprintln!(" ch{ch} SIDEINFO: no frame overlapped the aligned window"); | ||
| 1816 | - return; | ||
| 1817 | - } | ||
| 1818 | - // SBR-band-index units (`kx`/`k2`/`f_high`/`f_noise`) are `band_hz = | ||
| 1819 | - // rate/256` wide; FFT bins here are `bin_hz = rate/FFT_LEN` wide. The | ||
| 1820 | - // ratio `band_hz/bin_hz = FFT_LEN/256 = 8` is rate-independent, matching | ||
| 1821 | - // `per_band_correlation`'s own `lo = band*band_hz/bin_hz` conversion -- | ||
| 1822 | - // one SBR band is exactly 8 of these FFT bins, never 1. | ||
| 1823 | - const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 1824 | - let band_range = |lo: i64, hi: i64| -> (usize, usize) { | ||
| 1825 | - let lo = ((lo.max(0) as usize) * BINS_PER_SBR_BAND).min(bins); | ||
| 1826 | - let hi = (((hi.max(0) as usize) * BINS_PER_SBR_BAND).max(lo + 1)).min(bins); | ||
| 1827 | - (lo, hi) | ||
| 1828 | - }; | ||
| 1829 | - let sum_range = |e: &[f64], lo: usize, hi: usize| -> f64 { e[lo..hi].iter().sum() }; | ||
| 1830 | - | ||
| 1831 | - // --- predictor 1: add_harmonic bands (and their immediate neighbours) --- | ||
| 1832 | - let (mut harm_sum, mut harm_n) = (0.0f64, 0usize); | ||
| 1833 | - let (mut noharm_sum, mut noharm_n) = (0.0f64, 0usize); | ||
| 1834 | - let (mut adj_sum, mut adj_n) = (0.0f64, 0usize); | ||
| 1835 | - for row in &rows { | ||
| 1836 | - let Some(e) = energy.get(&row.frame) else { | ||
| 1837 | - continue; | ||
| 1838 | - }; | ||
| 1839 | - let Some(harm) = &row.add_harmonic else { | ||
| 1840 | - continue; | ||
| 1841 | - }; | ||
| 1842 | - for (i, &flag) in harm.iter().enumerate() { | ||
| 1843 | - let (lo, hi) = match (row.f_high.get(i), row.f_high.get(i + 1)) { | ||
| 1844 | - (Some(&a), Some(&b)) => band_range(a, b), | ||
| 1845 | - _ => continue, | ||
| 1846 | - }; | ||
| 1847 | - let s = sum_range(e, lo, hi); | ||
| 1848 | - let cells = (hi - lo).max(1); | ||
| 1849 | - if flag != 0 { | ||
| 1850 | - harm_sum += s / cells as f64; | ||
| 1851 | - harm_n += 1; | ||
| 1852 | - } else { | ||
| 1853 | - noharm_sum += s / cells as f64; | ||
| 1854 | - noharm_n += 1; | ||
| 1855 | - } | ||
| 1856 | - // adjacent band (off-by-one probe): the band one slot up. | ||
| 1857 | - if flag != 0 | ||
| 1858 | - && let (Some(&a2), Some(&b2)) = (row.f_high.get(i + 1), row.f_high.get(i + 2)) | ||
| 1859 | - { | ||
| 1860 | - let (lo2, hi2) = band_range(a2, b2); | ||
| 1861 | - adj_sum += sum_range(e, lo2, hi2) / (hi2 - lo2).max(1) as f64; | ||
| 1862 | - adj_n += 1; | ||
| 1863 | - } | ||
| 1864 | - } | ||
| 1865 | - } | ||
| 1866 | - | ||
| 1867 | - // --- predictor 2: envelope time borders vs envelope interior --- | ||
| 1868 | - // Envelope borders are in `t_env` (pre-`RATE`-scale envelope time-slot | ||
| 1869 | - // units); one unit is `RATE(2) * SYNTHESIS_BANDS(64) = 128` output | ||
| 1870 | - // samples. Time-domain residual energy (broadband, not per-band) near | ||
| 1871 | - // (+/-64 samples) each INTERIOR border vs the envelope's own midpoint. | ||
| 1872 | - let (mut border_sum, mut border_n) = (0.0f64, 0usize); | ||
| 1873 | - let (mut mid_sum, mut mid_n) = (0.0f64, 0usize); | ||
| 1874 | - let sample_energy = |global: usize| -> Option<f64> { | ||
| 1875 | - let oi = oa + global; | ||
| 1876 | - let ti = ob + global; | ||
| 1877 | - if oi >= o.len() || ti >= t.len() { | ||
| 1878 | - return None; | ||
| 1879 | - } | ||
| 1880 | - let d = f64::from(o[oi]) - f64::from(t[ti]); | ||
| 1881 | - Some(d * d) | ||
| 1882 | - }; | ||
| 1883 | - for row in &rows { | ||
| 1884 | - let frame_base = row.frame * FFT_LEN; | ||
| 1885 | - for w in row.t_env.windows(2) { | ||
| 1886 | - let (b0, b1) = (w[0] * 128, w[1] * 128); | ||
| 1887 | - if b1 <= b0 { | ||
| 1888 | - continue; | ||
| 1889 | - } | ||
| 1890 | - let mid = (b0 + b1) / 2; | ||
| 1891 | - for d in -64i64..=64 { | ||
| 1892 | - let s0 = b0 + d; | ||
| 1893 | - if s0 >= 0 | ||
| 1894 | - && let Some(v) = sample_energy(frame_base + s0 as usize) | ||
| 1895 | - { | ||
| 1896 | - border_sum += v; | ||
| 1897 | - border_n += 1; | ||
| 1898 | - } | ||
| 1899 | - } | ||
| 1900 | - for off in 0..(b1 - b0).min(256) { | ||
| 1901 | - let s = mid - (b1 - b0).min(256) / 2 + off; | ||
| 1902 | - if s >= 0 | ||
| 1903 | - && (s - mid).abs() > 64 | ||
| 1904 | - && let Some(v) = sample_energy(frame_base + s as usize) | ||
| 1905 | - { | ||
| 1906 | - mid_sum += v; | ||
| 1907 | - mid_n += 1; | ||
| 1908 | - } | ||
| 1909 | - } | ||
| 1910 | - } | ||
| 1911 | - } | ||
| 1912 | - | ||
| 1913 | - // --- predictor 3: hold-state (apply_last) vs fresh-payload frames --- | ||
| 1914 | - let (mut hold_sum, mut hold_n) = (0.0f64, 0usize); | ||
| 1915 | - let (mut fresh_sum, mut fresh_n) = (0.0f64, 0usize); | ||
| 1916 | - for row in &rows { | ||
| 1917 | - let Some(e) = energy.get(&row.frame) else { | ||
| 1918 | - continue; | ||
| 1919 | - }; | ||
| 1920 | - let total: f64 = e.iter().sum(); | ||
| 1921 | - if row.source == "hold" { | ||
| 1922 | - hold_sum += total; | ||
| 1923 | - hold_n += 1; | ||
| 1924 | - } else { | ||
| 1925 | - fresh_sum += total; | ||
| 1926 | - fresh_n += 1; | ||
| 1927 | - } | ||
| 1928 | - } | ||
| 1929 | - | ||
| 1930 | - // --- predictor 4: frame immediately after a coupling flip --- | ||
| 1931 | - let (mut flip_sum, mut flip_n) = (0.0f64, 0usize); | ||
| 1932 | - let (mut noflip_sum, mut noflip_n) = (0.0f64, 0usize); | ||
| 1933 | - let mut sorted = rows.clone(); | ||
| 1934 | - sorted.sort_by_key(|r| r.frame); | ||
| 1935 | - for pair in sorted.windows(2) { | ||
| 1936 | - let (prev, cur) = (&pair[0], &pair[1]); | ||
| 1937 | - let Some(e) = energy.get(&cur.frame) else { | ||
| 1938 | - continue; | ||
| 1939 | - }; | ||
| 1940 | - let total: f64 = e.iter().sum(); | ||
| 1941 | - if cur.coupling != prev.coupling { | ||
| 1942 | - flip_sum += total; | ||
| 1943 | - flip_n += 1; | ||
| 1944 | - } else { | ||
| 1945 | - noflip_sum += total; | ||
| 1946 | - noflip_n += 1; | ||
| 1947 | - } | ||
| 1948 | - } | ||
| 1949 | - | ||
| 1950 | - // --- predictor 5: residual scaling per invf_mode level, per noise band --- | ||
| 1951 | - let mut per_level = [(0.0f64, 0usize); 4]; | ||
| 1952 | - for row in &rows { | ||
| 1953 | - let Some(e) = energy.get(&row.frame) else { | ||
| 1954 | - continue; | ||
| 1955 | - }; | ||
| 1956 | - for (i, &mode) in row.invf_mode.iter().enumerate() { | ||
| 1957 | - let (lo, hi) = match (row.f_noise.get(i), row.f_noise.get(i + 1)) { | ||
| 1958 | - (Some(&a), Some(&b)) => band_range(a, b), | ||
| 1959 | - _ => continue, | ||
| 1960 | - }; | ||
| 1961 | - let cells = (hi - lo).max(1); | ||
| 1962 | - let level = (mode as usize).min(3); | ||
| 1963 | - per_level[level].0 += sum_range(e, lo, hi) / cells as f64; | ||
| 1964 | - per_level[level].1 += 1; | ||
| 1965 | - } | ||
| 1966 | - } | ||
| 1967 | - | ||
| 1968 | - // --- predictor 6: residual whiteness within HF bands (peakiness) --- | ||
| 1969 | - // mean(max-bin / mean-bin) over each HF band each frame -- near 1 reads | ||
| 1970 | - // noise-like, large reads tonal (one bin dominating the band). | ||
| 1971 | - let (mut peak_sum, mut peak_n) = (0.0f64, 0usize); | ||
| 1972 | - for row in &rows { | ||
| 1973 | - let Some(e) = energy.get(&row.frame) else { | ||
| 1974 | - continue; | ||
| 1975 | - }; | ||
| 1976 | - let (lo, hi) = band_range(row.kx, row.k2); | ||
| 1977 | - for group_lo in (lo..hi.min(e.len())).step_by(4) { | ||
| 1978 | - let group_hi = (group_lo + 4).min(hi).min(e.len()); | ||
| 1979 | - if group_hi <= group_lo { | ||
| 1980 | - continue; | ||
| 1981 | - } | ||
| 1982 | - let slice = &e[group_lo..group_hi]; | ||
| 1983 | - let mean = slice.iter().sum::<f64>() / slice.len() as f64; | ||
| 1984 | - let max = slice.iter().cloned().fold(0.0f64, f64::max); | ||
| 1985 | - if mean > 0.0 { | ||
| 1986 | - peak_sum += max / mean; | ||
| 1987 | - peak_n += 1; | ||
| 1988 | - } | ||
| 1989 | - } | ||
| 1990 | - } | ||
| 1991 | - | ||
| 1992 | - // Heat summary: the full (frame x band) grid collapsed to two profiles | ||
| 1993 | - // (mean over bands per 50-frame group; mean over frames per 8-band | ||
| 1994 | - // group) -- the full grid itself is `energy`, ~489 x ~90 cells, too | ||
| 1995 | - // large to print usefully every run. | ||
| 1996 | - let mut frame_keys: Vec<usize> = energy.keys().cloned().collect(); | ||
| 1997 | - frame_keys.sort_unstable(); | ||
| 1998 | - println!( | ||
| 1999 | - " ch{ch} RESIDUAL HEAT temporal profile (50-frame groups, mean energy over all bands):" | ||
| 2000 | - ); | ||
crates/ec-aac/tests/sbr_real_library/main.rsdeleted+0 -31
| @@ -1,31 +0,0 @@ | |||
| 1 | - | ||
| 2 | -use std::fs::File; | ||
| 3 | -use std::io::{BufReader, Read}; | ||
| 4 | -use std::path::{Path, PathBuf}; | ||
| 5 | - | ||
| 6 | -use ec_aac::{AacDecoder, parse_audio_specific_config}; | ||
| 7 | -use ec_core::{CodecId, Demuxer, Packet}; | ||
| 8 | -use ec_matroska::MatroskaDemuxer; | ||
| 9 | -use ec_mp4::Mp4Demuxer; | ||
| 10 | - | ||
| 11 | -/// Every `#[test]` in this file decodes real SBR content through | ||
| 12 | -/// `our_decode`/`our_decode_uncapped`, and a handful of them steer that | ||
| 13 | -/// decode with debug switches (`EC_AAC_SBR_HF_BYPASS`, | ||
| 14 | -/// `EC_AAC_SBR_SIDEINFO_DEBUG`, `EC_AAC_SBR_NOISE_ZERO`, | ||
| 15 | -/// `EC_AAC_SBR_NOISE_FRACTION`). They are set through | ||
| 16 | -/// `ec_aac::knobs` guards, which override the switch on this test's thread | ||
| 17 | -/// only and restore it on drop, so no test can flip another test's decode. | ||
| 18 | -/// The lock below still serialises the tests because the decoder's | ||
| 19 | -/// sideinfo and noise-fraction logs are process-global and read back by | ||
| 20 | -/// each test. | ||
| 21 | -static DECODE_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); | ||
| 22 | - | ||
| 23 | -mod helpers; | ||
| 24 | -mod chunk_a; | ||
| 25 | -mod chunk_b; | ||
| 26 | -mod chunk_c; | ||
| 27 | - | ||
| 28 | -use helpers::*; | ||
| 29 | -use chunk_a::*; | ||
| 30 | -use chunk_b::*; | ||
| 31 | -use chunk_c::*; | ||