probe(sbr-residual): frame x band residual/side-info correlation instrument
Browse files at this commit6fea6db6f77c3ce5e703c85640d7b1d271fef4b1Parent: 9a984c93 changed files +436 -3
- crates/ec-aac/src/lib.rs +3 -0
- crates/ec-aac/src/sbr_chain.rs +102 -3
- crates/ec-aac/tests/sbr_real_library.rs +331 -0
crates/ec-aac/src/lib.rsmodified+3 -0
| @@ -48,6 +48,9 @@ pub use config::{ | |||
| 48 | pub use decode::{FRAME_LEN, WindowSequence}; | 48 | pub use decode::{FRAME_LEN, WindowSequence}; |
| 49 | pub use ec_core::{Error, Result}; | 49 | pub use ec_core::{Error, Result}; |
| 50 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; | 50 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; |
| 51 | +/// Diagnostic only (round-20): per-(access-unit, channel) side-info rows | ||
| 52 | +/// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set. | ||
| 53 | +pub use sbr_chain::{SbrSideInfoRow, sbr_sideinfo_log}; | ||
| 51 | /// Diagnostic only (round-17 Task 1 conviction check): reads back the | 54 | /// Diagnostic only (round-17 Task 1 conviction check): reads back the |
| 52 | /// per-absolute-QMF-band transmitted signal/noise energy sums | 55 | /// per-absolute-QMF-band transmitted signal/noise energy sums |
| 53 | /// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. | 56 | /// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. |
crates/ec-aac/src/sbr_chain.rsmodified+102 -3
| @@ -59,6 +59,58 @@ fn debug_dump( | |||
| 59 | /// runs at (32 per frame): `RATE = 2` converts one to the other. | 59 | /// runs at (32 per frame): `RATE = 2` converts one to the other. |
| 60 | const RATE: i64 = 2; | 60 | const RATE: i64 = 2; |
| 61 | 61 | ||
| 62 | +/// Round-20 residual/side-info correlation: one row per (access unit, | ||
| 63 | +/// channel) `apply_data` actually ran, giving `sbr_real_library.rs`'s | ||
| 64 | +/// residual-energy grid a side-info table to correlate against without | ||
| 65 | +/// re-parsing debug text. `frame` is a single counter shared by every | ||
| 66 | +/// channel `apply_data` touches in one call, so it lines up 1:1 with the | ||
| 67 | +/// AU-aligned (2048 output samples/AU for a plain 2x stream) blocks the | ||
| 68 | +/// residual grid uses. | ||
| 69 | +#[derive(Clone, Debug)] | ||
| 70 | +pub struct SbrSideInfoRow { | ||
| 71 | + pub frame: usize, | ||
| 72 | + pub tag: u8, | ||
| 73 | + pub ch: usize, | ||
| 74 | + /// `"fresh"` for a frame `apply` reached (a real payload this AU), | ||
| 75 | + /// `"hold"` for one `apply_last` reached (no fresh payload, reusing the | ||
| 76 | + /// last parsed frame's data per §4.6.18). | ||
| 77 | + pub source: &'static str, | ||
| 78 | + pub coupling: bool, | ||
| 79 | + pub amp_res: u8, | ||
| 80 | + /// Band-index domain (same units `f_high`/`f_noise` and the residual | ||
| 81 | + /// grid's FFT-bucket index share, per `per_band_correlation`'s | ||
| 82 | + /// `band_hz = rate/256` measurement) the crossover and high-res/noise | ||
| 83 | + /// band boundaries below live in. | ||
| 84 | + pub kx: i64, | ||
| 85 | + pub k2: i64, | ||
| 86 | + pub f_high: Vec<i64>, | ||
| 87 | + pub f_noise: Vec<i64>, | ||
| 88 | + pub t_env: Vec<i64>, | ||
| 89 | + pub freq_res: Vec<u8>, | ||
| 90 | + pub invf_mode: Vec<u8>, | ||
| 91 | + pub add_harmonic: Option<Vec<u8>>, | ||
| 92 | + pub e_q_means: Vec<f64>, | ||
| 93 | + pub q_q_means: Vec<f64>, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> = | ||
| 97 | + std::sync::OnceLock::new(); | ||
| 98 | +static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0); | ||
| 99 | + | ||
| 100 | +fn sideinfo_enabled() -> bool { | ||
| 101 | + std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok() | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Drains nothing -- returns a clone of every row logged so far this | ||
| 105 | +/// process, in call order. Empty unless `EC_AAC_SBR_SIDEINFO_DEBUG` was set | ||
| 106 | +/// before decoding. | ||
| 107 | +pub fn sbr_sideinfo_log() -> Vec<SbrSideInfoRow> { | ||
| 108 | + let Some(log) = SIDEINFO_LOG.get() else { | ||
| 109 | + return Vec::new(); | ||
| 110 | + }; | ||
| 111 | + log.lock().map(|l| l.clone()).unwrap_or_default() | ||
| 112 | +} | ||
| 113 | + | ||
| 62 | /// Per-channel DSP state an SBR element's reconstruction carries across | 114 | /// Per-channel DSP state an SBR element's reconstruction carries across |
| 63 | /// frames: the QMF filterbank pair, the HF generator's LPC history and | 115 | /// frames: the QMF filterbank pair, the HF generator's LPC history and |
| 64 | /// chirp factors, and the noise-floor generator. | 116 | /// chirp factors, and the noise-floor generator. |
| @@ -138,7 +190,7 @@ impl SbrChain { | |||
| 138 | if let Some(elem) = self.elements.get_mut(&tag) { | 190 | if let Some(elem) = self.elements.get_mut(&tag) { |
| 139 | elem.last_data = Some(data.clone()); | 191 | elem.last_data = Some(data.clone()); |
| 140 | } | 192 | } |
| 141 | - self.apply_data(tag, data, planes); | 193 | + self.apply_data(tag, data, planes, "fresh"); |
| 142 | } | 194 | } |
| 143 | 195 | ||
| 144 | /// Re-runs the chain for `tag` using the last successfully parsed | 196 | /// Re-runs the chain for `tag` using the last successfully parsed |
| @@ -150,10 +202,16 @@ impl SbrChain { | |||
| 150 | let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else { | 202 | let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else { |
| 151 | return; | 203 | return; |
| 152 | }; | 204 | }; |
| 153 | - self.apply_data(tag, &data, planes); | 205 | + self.apply_data(tag, &data, planes, "hold"); |
| 154 | } | 206 | } |
| 155 | 207 | ||
| 156 | - fn apply_data(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) { | 208 | + fn apply_data( |
| 209 | + &mut self, | ||
| 210 | + tag: u8, | ||
| 211 | + data: &SbrData, | ||
| 212 | + planes: &mut [Vec<f32>], | ||
| 213 | + source: &'static str, | ||
| 214 | + ) { | ||
| 157 | let Some(elem) = self.elements.get_mut(&tag) else { | 215 | let Some(elem) = self.elements.get_mut(&tag) else { |
| 158 | return; | 216 | return; |
| 159 | }; | 217 | }; |
| @@ -164,6 +222,12 @@ impl SbrChain { | |||
| 164 | return; | 222 | return; |
| 165 | }; | 223 | }; |
| 166 | let coupling = data.coupling; | 224 | let coupling = data.coupling; |
| 225 | + let sideinfo_on = sideinfo_enabled(); | ||
| 226 | + let au_frame = if sideinfo_on { | ||
| 227 | + SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed) | ||
| 228 | + } else { | ||
| 229 | + 0 | ||
| 230 | + }; | ||
| 167 | for (ch, plane) in planes.iter_mut().enumerate() { | 231 | for (ch, plane) in planes.iter_mut().enumerate() { |
| 168 | if ch >= data.channels.len() || ch >= elem.channels.len() { | 232 | if ch >= data.channels.len() || ch >= elem.channels.len() { |
| 169 | continue; | 233 | continue; |
| @@ -204,6 +268,41 @@ impl SbrChain { | |||
| 204 | eprintln!("SBRDBG coupling={}", data.coupling); | 268 | eprintln!("SBRDBG coupling={}", data.coupling); |
| 205 | debug_dump(&header, &tables, sbr_ch, ch); | 269 | debug_dump(&header, &tables, sbr_ch, ch); |
| 206 | } | 270 | } |
| 271 | + if sideinfo_on { | ||
| 272 | + let mean = |rows: &[Vec<i32>]| -> Vec<f64> { | ||
| 273 | + rows.iter() | ||
| 274 | + .map(|r| { | ||
| 275 | + if r.is_empty() { | ||
| 276 | + 0.0 | ||
| 277 | + } else { | ||
| 278 | + r.iter().map(|&v| f64::from(v)).sum::<f64>() / r.len() as f64 | ||
| 279 | + } | ||
| 280 | + }) | ||
| 281 | + .collect() | ||
| 282 | + }; | ||
| 283 | + let row = SbrSideInfoRow { | ||
| 284 | + frame: au_frame, | ||
| 285 | + tag, | ||
| 286 | + ch, | ||
| 287 | + source, | ||
| 288 | + coupling, | ||
| 289 | + amp_res: header.amp_res, | ||
| 290 | + kx: tables.kx, | ||
| 291 | + k2: tables.k2, | ||
| 292 | + f_high: tables.f_high.clone(), | ||
| 293 | + f_noise: tables.f_noise.clone(), | ||
| 294 | + t_env: sbr_ch.t_env.clone(), | ||
| 295 | + freq_res: sbr_ch.freq_res.clone(), | ||
| 296 | + invf_mode: sbr_ch.invf_mode.clone(), | ||
| 297 | + add_harmonic: sbr_ch.add_harmonic.clone(), | ||
| 298 | + e_q_means: mean(&sbr_ch.e_q), | ||
| 299 | + q_q_means: mean(&sbr_ch.q_q), | ||
| 300 | + }; | ||
| 301 | + let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new())); | ||
| 302 | + if let Ok(mut l) = log.lock() { | ||
| 303 | + l.push(row); | ||
| 304 | + } | ||
| 305 | + } | ||
| 207 | let mut hf = sbr_hf::generate( | 306 | let mut hf = sbr_hf::generate( |
| 208 | &low_cur, | 307 | &low_cur, |
| 209 | &tables, | 308 | &tables, |
crates/ec-aac/tests/sbr_real_library.rsmodified+331 -0
| @@ -650,6 +650,334 @@ struct Candidate { | |||
| 650 | crossover_hz: f64, | 650 | crossover_hz: f64, |
| 651 | } | 651 | } |
| 652 | 652 | ||
| 653 | +/// Round-20 residual/side-info correlation. Builds a (frame x band) residual | ||
| 654 | +/// ENERGY grid at AU-aligned 2048-output-sample blocks -- a plain (2x) SBR | ||
| 655 | +/// stream reconstructs exactly one 2048-sample block per core access unit, | ||
| 656 | +/// so `n`-th block lines up 1:1 with `ec_aac::sbr_sideinfo_log()`'s `frame` | ||
| 657 | +/// counter -- then cross-tabulates that grid against every side-info feature | ||
| 658 | +/// the log carries. FFT is linear, so `FFT(o_block) - FFT(t_block) == | ||
| 659 | +/// FFT(o_block - t_block)`: the residual's own per-bin energy is obtained | ||
| 660 | +/// directly from each side's spectrum without ever materializing a | ||
| 661 | +/// time-domain residual array. `band` is the same `rate/256`-wide index | ||
| 662 | +/// domain `per_band_correlation`/`tables.kx`/`f_high`/`f_noise` all already | ||
| 663 | +/// share (measured in round-14/round-16), so a side-info row's `f_high`/ | ||
| 664 | +/// `f_noise` boundaries index straight into this grid's bins with no | ||
| 665 | +/// rescaling. | ||
| 666 | +fn residual_sideinfo_analysis(o: &[f32], t: &[f32], oa: usize, ob: usize, rate: u32, ch: usize) { | ||
| 667 | + let rows: Vec<_> = ec_aac::sbr_sideinfo_log() | ||
| 668 | + .into_iter() | ||
| 669 | + .filter(|r| r.ch == ch) | ||
| 670 | + .collect(); | ||
| 671 | + if rows.is_empty() { | ||
| 672 | + eprintln!(" ch{ch} SIDEINFO: no rows logged (set EC_AAC_SBR_SIDEINFO_DEBUG too)"); | ||
| 673 | + return; | ||
| 674 | + } | ||
| 675 | + const FFT_LEN: usize = 2048; | ||
| 676 | + let win = ec_dsp::Window::<f32>::sine(FFT_LEN); | ||
| 677 | + let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN); | ||
| 678 | + let bins = rfft.spectrum_len(); | ||
| 679 | + let mut o_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 680 | + let mut t_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; | ||
| 681 | + | ||
| 682 | + // Per-frame residual bin-energy vector (index = `band`, per-bin, not yet | ||
| 683 | + // grouped) and, alongside it, a per-bin peakiness ratio (own-bin energy | ||
| 684 | + // vs its 3-bin neighbourhood mean) used by the whiteness check. | ||
| 685 | + let mut energy: std::collections::HashMap<usize, Vec<f64>> = std::collections::HashMap::new(); | ||
| 686 | + for row in &rows { | ||
| 687 | + if energy.contains_key(&row.frame) { | ||
| 688 | + continue; | ||
| 689 | + } | ||
| 690 | + let base_o = oa + row.frame * FFT_LEN; | ||
| 691 | + let base_t = ob + row.frame * FFT_LEN; | ||
| 692 | + if base_o + FFT_LEN > o.len() || base_t + FFT_LEN > t.len() { | ||
| 693 | + continue; | ||
| 694 | + } | ||
| 695 | + let mut ob_win = o[base_o..base_o + FFT_LEN].to_vec(); | ||
| 696 | + let mut tb_win = t[base_t..base_t + FFT_LEN].to_vec(); | ||
| 697 | + win.apply(&mut ob_win); | ||
| 698 | + win.apply(&mut tb_win); | ||
| 699 | + rfft.forward(&ob_win, &mut o_spec); | ||
| 700 | + rfft.forward(&tb_win, &mut t_spec); | ||
| 701 | + let e: Vec<f64> = o_spec | ||
| 702 | + .iter() | ||
| 703 | + .zip(&t_spec) | ||
| 704 | + .map(|(a, b)| f64::from((*a - *b).norm_sqr())) | ||
| 705 | + .collect(); | ||
| 706 | + energy.insert(row.frame, e); | ||
| 707 | + } | ||
| 708 | + if energy.is_empty() { | ||
| 709 | + eprintln!(" ch{ch} SIDEINFO: no frame overlapped the aligned window"); | ||
| 710 | + return; | ||
| 711 | + } | ||
| 712 | + // SBR-band-index units (`kx`/`k2`/`f_high`/`f_noise`) are `band_hz = | ||
| 713 | + // rate/256` wide; FFT bins here are `bin_hz = rate/FFT_LEN` wide. The | ||
| 714 | + // ratio `band_hz/bin_hz = FFT_LEN/256 = 8` is rate-independent, matching | ||
| 715 | + // `per_band_correlation`'s own `lo = band*band_hz/bin_hz` conversion -- | ||
| 716 | + // one SBR band is exactly 8 of these FFT bins, never 1. | ||
| 717 | + const BINS_PER_SBR_BAND: usize = FFT_LEN / 256; | ||
| 718 | + let band_range = |lo: i64, hi: i64| -> (usize, usize) { | ||
| 719 | + let lo = ((lo.max(0) as usize) * BINS_PER_SBR_BAND).min(bins); | ||
| 720 | + let hi = (((hi.max(0) as usize) * BINS_PER_SBR_BAND).max(lo + 1)).min(bins); | ||
| 721 | + (lo, hi) | ||
| 722 | + }; | ||
| 723 | + let sum_range = |e: &[f64], lo: usize, hi: usize| -> f64 { e[lo..hi].iter().sum() }; | ||
| 724 | + | ||
| 725 | + // --- predictor 1: add_harmonic bands (and their immediate neighbours) --- | ||
| 726 | + let (mut harm_sum, mut harm_n) = (0.0f64, 0usize); | ||
| 727 | + let (mut noharm_sum, mut noharm_n) = (0.0f64, 0usize); | ||
| 728 | + let (mut adj_sum, mut adj_n) = (0.0f64, 0usize); | ||
| 729 | + for row in &rows { | ||
| 730 | + let Some(e) = energy.get(&row.frame) else { | ||
| 731 | + continue; | ||
| 732 | + }; | ||
| 733 | + let Some(harm) = &row.add_harmonic else { | ||
| 734 | + continue; | ||
| 735 | + }; | ||
| 736 | + for (i, &flag) in harm.iter().enumerate() { | ||
| 737 | + let (lo, hi) = match (row.f_high.get(i), row.f_high.get(i + 1)) { | ||
| 738 | + (Some(&a), Some(&b)) => band_range(a, b), | ||
| 739 | + _ => continue, | ||
| 740 | + }; | ||
| 741 | + let s = sum_range(e, lo, hi); | ||
| 742 | + let cells = (hi - lo).max(1); | ||
| 743 | + if flag != 0 { | ||
| 744 | + harm_sum += s / cells as f64; | ||
| 745 | + harm_n += 1; | ||
| 746 | + } else { | ||
| 747 | + noharm_sum += s / cells as f64; | ||
| 748 | + noharm_n += 1; | ||
| 749 | + } | ||
| 750 | + // adjacent band (off-by-one probe): the band one slot up. | ||
| 751 | + if flag != 0 | ||
| 752 | + && let (Some(&a2), Some(&b2)) = (row.f_high.get(i + 1), row.f_high.get(i + 2)) | ||
| 753 | + { | ||
| 754 | + let (lo2, hi2) = band_range(a2, b2); | ||
| 755 | + adj_sum += sum_range(e, lo2, hi2) / (hi2 - lo2).max(1) as f64; | ||
| 756 | + adj_n += 1; | ||
| 757 | + } | ||
| 758 | + } | ||
| 759 | + } | ||
| 760 | + | ||
| 761 | + // --- predictor 2: envelope time borders vs envelope interior --- | ||
| 762 | + // Envelope borders are in `t_env` (pre-`RATE`-scale envelope time-slot | ||
| 763 | + // units); one unit is `RATE(2) * SYNTHESIS_BANDS(64) = 128` output | ||
| 764 | + // samples. Time-domain residual energy (broadband, not per-band) near | ||
| 765 | + // (+/-64 samples) each INTERIOR border vs the envelope's own midpoint. | ||
| 766 | + let (mut border_sum, mut border_n) = (0.0f64, 0usize); | ||
| 767 | + let (mut mid_sum, mut mid_n) = (0.0f64, 0usize); | ||
| 768 | + let sample_energy = |global: usize| -> Option<f64> { | ||
| 769 | + let oi = oa + global; | ||
| 770 | + let ti = ob + global; | ||
| 771 | + if oi >= o.len() || ti >= t.len() { | ||
| 772 | + return None; | ||
| 773 | + } | ||
| 774 | + let d = f64::from(o[oi]) - f64::from(t[ti]); | ||
| 775 | + Some(d * d) | ||
| 776 | + }; | ||
| 777 | + for row in &rows { | ||
| 778 | + let frame_base = row.frame * FFT_LEN; | ||
| 779 | + for w in row.t_env.windows(2) { | ||
| 780 | + let (b0, b1) = (w[0] * 128, w[1] * 128); | ||
| 781 | + if b1 <= b0 { | ||
| 782 | + continue; | ||
| 783 | + } | ||
| 784 | + let mid = (b0 + b1) / 2; | ||
| 785 | + for d in -64i64..=64 { | ||
| 786 | + let s0 = b0 + d; | ||
| 787 | + if s0 >= 0 | ||
| 788 | + && let Some(v) = sample_energy(frame_base + s0 as usize) | ||
| 789 | + { | ||
| 790 | + border_sum += v; | ||
| 791 | + border_n += 1; | ||
| 792 | + } | ||
| 793 | + } | ||
| 794 | + for off in 0..(b1 - b0).min(256) { | ||
| 795 | + let s = mid - (b1 - b0).min(256) / 2 + off; | ||
| 796 | + if s >= 0 | ||
| 797 | + && (s - mid).abs() > 64 | ||
| 798 | + && let Some(v) = sample_energy(frame_base + s as usize) | ||
| 799 | + { | ||
| 800 | + mid_sum += v; | ||
| 801 | + mid_n += 1; | ||
| 802 | + } | ||
| 803 | + } | ||
| 804 | + } | ||
| 805 | + } | ||
| 806 | + | ||
| 807 | + // --- predictor 3: hold-state (apply_last) vs fresh-payload frames --- | ||
| 808 | + let (mut hold_sum, mut hold_n) = (0.0f64, 0usize); | ||
| 809 | + let (mut fresh_sum, mut fresh_n) = (0.0f64, 0usize); | ||
| 810 | + for row in &rows { | ||
| 811 | + let Some(e) = energy.get(&row.frame) else { | ||
| 812 | + continue; | ||
| 813 | + }; | ||
| 814 | + let total: f64 = e.iter().sum(); | ||
| 815 | + if row.source == "hold" { | ||
| 816 | + hold_sum += total; | ||
| 817 | + hold_n += 1; | ||
| 818 | + } else { | ||
| 819 | + fresh_sum += total; | ||
| 820 | + fresh_n += 1; | ||
| 821 | + } | ||
| 822 | + } | ||
| 823 | + | ||
| 824 | + // --- predictor 4: frame immediately after a coupling flip --- | ||
| 825 | + let (mut flip_sum, mut flip_n) = (0.0f64, 0usize); | ||
| 826 | + let (mut noflip_sum, mut noflip_n) = (0.0f64, 0usize); | ||
| 827 | + let mut sorted = rows.clone(); | ||
| 828 | + sorted.sort_by_key(|r| r.frame); | ||
| 829 | + for pair in sorted.windows(2) { | ||
| 830 | + let (prev, cur) = (&pair[0], &pair[1]); | ||
| 831 | + let Some(e) = energy.get(&cur.frame) else { | ||
| 832 | + continue; | ||
| 833 | + }; | ||
| 834 | + let total: f64 = e.iter().sum(); | ||
| 835 | + if cur.coupling != prev.coupling { | ||
| 836 | + flip_sum += total; | ||
| 837 | + flip_n += 1; | ||
| 838 | + } else { | ||
| 839 | + noflip_sum += total; | ||
| 840 | + noflip_n += 1; | ||
| 841 | + } | ||
| 842 | + } | ||
| 843 | + | ||
| 844 | + // --- predictor 5: residual scaling per invf_mode level, per noise band --- | ||
| 845 | + let mut per_level = [(0.0f64, 0usize); 4]; | ||
| 846 | + for row in &rows { | ||
| 847 | + let Some(e) = energy.get(&row.frame) else { | ||
| 848 | + continue; | ||
| 849 | + }; | ||
| 850 | + for (i, &mode) in row.invf_mode.iter().enumerate() { | ||
| 851 | + let (lo, hi) = match (row.f_noise.get(i), row.f_noise.get(i + 1)) { | ||
| 852 | + (Some(&a), Some(&b)) => band_range(a, b), | ||
| 853 | + _ => continue, | ||
| 854 | + }; | ||
| 855 | + let cells = (hi - lo).max(1); | ||
| 856 | + let level = (mode as usize).min(3); | ||
| 857 | + per_level[level].0 += sum_range(e, lo, hi) / cells as f64; | ||
| 858 | + per_level[level].1 += 1; | ||
| 859 | + } | ||
| 860 | + } | ||
| 861 | + | ||
| 862 | + // --- predictor 6: residual whiteness within HF bands (peakiness) --- | ||
| 863 | + // mean(max-bin / mean-bin) over each HF band each frame -- near 1 reads | ||
| 864 | + // noise-like, large reads tonal (one bin dominating the band). | ||
| 865 | + let (mut peak_sum, mut peak_n) = (0.0f64, 0usize); | ||
| 866 | + for row in &rows { | ||
| 867 | + let Some(e) = energy.get(&row.frame) else { | ||
| 868 | + continue; | ||
| 869 | + }; | ||
| 870 | + let (lo, hi) = band_range(row.kx, row.k2); | ||
| 871 | + for group_lo in (lo..hi.min(e.len())).step_by(4) { | ||
| 872 | + let group_hi = (group_lo + 4).min(hi).min(e.len()); | ||
| 873 | + if group_hi <= group_lo { | ||
| 874 | + continue; | ||
| 875 | + } | ||
| 876 | + let slice = &e[group_lo..group_hi]; | ||
| 877 | + let mean = slice.iter().sum::<f64>() / slice.len() as f64; | ||
| 878 | + let max = slice.iter().cloned().fold(0.0f64, f64::max); | ||
| 879 | + if mean > 0.0 { | ||
| 880 | + peak_sum += max / mean; | ||
| 881 | + peak_n += 1; | ||
| 882 | + } | ||
| 883 | + } | ||
| 884 | + } | ||
| 885 | + | ||
| 886 | + // Heat summary: the full (frame x band) grid collapsed to two profiles | ||
| 887 | + // (mean over bands per 50-frame group; mean over frames per 8-band | ||
| 888 | + // group) -- the full grid itself is `energy`, ~489 x ~90 cells, too | ||
| 889 | + // large to print usefully every run. | ||
| 890 | + let mut frame_keys: Vec<usize> = energy.keys().cloned().collect(); | ||
| 891 | + frame_keys.sort_unstable(); | ||
| 892 | + println!( | ||
| 893 | + " ch{ch} RESIDUAL HEAT temporal profile (50-frame groups, mean energy over all bands):" | ||
| 894 | + ); | ||
| 895 | + for chunk in frame_keys.chunks(50) { | ||
| 896 | + let (mut s, mut n) = (0.0f64, 0usize); | ||
| 897 | + for &f in chunk { | ||
| 898 | + if let Some(e) = energy.get(&f) { | ||
| 899 | + s += e.iter().sum::<f64>(); | ||
| 900 | + n += e.len(); | ||
| 901 | + } | ||
| 902 | + } | ||
| 903 | + if n > 0 { | ||
| 904 | + println!( | ||
| 905 | + " frames {}..{}: {:.6e}", | ||
| 906 | + chunk[0], | ||
| 907 | + chunk[chunk.len() - 1], | ||
| 908 | + s / n as f64 | ||
| 909 | + ); | ||
| 910 | + } | ||
| 911 | + } | ||
| 912 | + // Nyquist bin: FFT_LEN/2 (the real bin at the Nyquist frequency, always | ||
| 913 | + // present in an RFFT of an even-length transform) -- bins past it are | ||
| 914 | + // this RFFT's own redundant/unused tail, never real spectrum. | ||
| 915 | + let bin_hz = f64::from(rate) / FFT_LEN as f64; | ||
| 916 | + let nyquist_bin = (FFT_LEN / 2 + 1).min(bins); | ||
| 917 | + println!( | ||
| 918 | + " ch{ch} RESIDUAL HEAT spectral profile ({BINS_PER_SBR_BAND}-bin == 1 SBR-band groups, mean energy over all frames):" | ||
| 919 | + ); | ||
| 920 | + for group_lo in (0..nyquist_bin).step_by(BINS_PER_SBR_BAND) { | ||
| 921 | + let group_hi = (group_lo + BINS_PER_SBR_BAND).min(nyquist_bin); | ||
| 922 | + let (mut s, mut n) = (0.0f64, 0usize); | ||
| 923 | + for e in energy.values() { | ||
| 924 | + for &v in &e[group_lo..group_hi] { | ||
| 925 | + s += v; | ||
| 926 | + n += 1; | ||
| 927 | + } | ||
| 928 | + } | ||
| 929 | + if n > 0 { | ||
| 930 | + println!( | ||
| 931 | + " {:>6.0}Hz..{:>6.0}Hz (band {}): {:.6e}", | ||
| 932 | + group_lo as f64 * bin_hz, | ||
| 933 | + group_hi as f64 * bin_hz, | ||
| 934 | + group_lo / BINS_PER_SBR_BAND, | ||
| 935 | + s / n as f64 | ||
| 936 | + ); | ||
| 937 | + } | ||
| 938 | + } | ||
| 939 | + | ||
| 940 | + let avg = |s: f64, n: usize| if n > 0 { s / n as f64 } else { f64::NAN }; | ||
| 941 | + println!( | ||
| 942 | + " ch{ch} RESIDUAL/SIDEINFO ranked predictors ({} frames, {} rows):", | ||
| 943 | + energy.len(), | ||
| 944 | + rows.len() | ||
| 945 | + ); | ||
| 946 | + println!( | ||
| 947 | + " 1. add_harmonic band mean energy: flagged={:.6e} (n={harm_n}) unflagged={:.6e} (n={noharm_n}) ratio={:.3} | adjacent(+1)-band-of-flagged={:.6e} (n={adj_n})", | ||
| 948 | + avg(harm_sum, harm_n), | ||
| 949 | + avg(noharm_sum, noharm_n), | ||
| 950 | + avg(harm_sum, harm_n) / avg(noharm_sum, noharm_n).max(1e-300), | ||
| 951 | + avg(adj_sum, adj_n) | ||
| 952 | + ); | ||
| 953 | + println!( | ||
| 954 | + " 2. envelope time-border (+/-64 smp) mean energy={:.6e} (n={border_n}) vs interior={:.6e} (n={mid_n}) ratio={:.3}", | ||
| 955 | + avg(border_sum, border_n), | ||
| 956 | + avg(mid_sum, mid_n), | ||
| 957 | + avg(border_sum, border_n) / avg(mid_sum, mid_n).max(1e-300) | ||
| 958 | + ); | ||
| 959 | + println!( | ||
| 960 | + " 3. hold-state(apply_last) frame total energy={:.6e} (n={hold_n}) vs fresh-payload={:.6e} (n={fresh_n}) ratio={:.3}", | ||
| 961 | + avg(hold_sum, hold_n), | ||
| 962 | + avg(fresh_sum, fresh_n), | ||
| 963 | + avg(hold_sum, hold_n) / avg(fresh_sum, fresh_n).max(1e-300) | ||
| 964 | + ); | ||
| 965 | + println!( | ||
| 966 | + " 4. frame-after-coupling-flip total energy={:.6e} (n={flip_n}) vs no-flip={:.6e} (n={noflip_n}) ratio={:.3}", | ||
| 967 | + avg(flip_sum, flip_n), | ||
| 968 | + avg(noflip_sum, noflip_n), | ||
| 969 | + avg(flip_sum, flip_n) / avg(noflip_sum, noflip_n).max(1e-300) | ||
| 970 | + ); | ||
| 971 | + println!(" 5. invf_mode level -> mean per-band residual energy:"); | ||
| 972 | + for (level, (s, n)) in per_level.iter().enumerate() { | ||
| 973 | + println!(" level {level}: {:.6e} (n={n})", avg(*s, *n)); | ||
| 974 | + } | ||
| 975 | + println!( | ||
| 976 | + " 6. HF residual peakiness (max/mean over 4-bin groups): {:.3} (n={peak_n}) [near 1 = noise-like, larger = tonal]", | ||
| 977 | + avg(peak_sum, peak_n) | ||
| 978 | + ); | ||
| 979 | +} | ||
| 980 | + | ||
| 653 | fn candidates() -> Vec<Candidate> { | 981 | fn candidates() -> Vec<Candidate> { |
| 654 | let home = std::env::var("HOME").unwrap_or_default(); | 982 | let home = std::env::var("HOME").unwrap_or_default(); |
| 655 | [ | 983 | [ |
| @@ -850,6 +1178,9 @@ fn sbr_real_library_matches_reference() { | |||
| 850 | println!(" w{w}: lag {l} corr {cr:.4}"); | 1178 | println!(" w{w}: lag {l} corr {cr:.4}"); |
| 851 | } | 1179 | } |
| 852 | } | 1180 | } |
| 1181 | + if std::env::var("EC_AAC_SBR_RESIDUAL_DEBUG").is_ok() { | ||
| 1182 | + residual_sideinfo_analysis(o, t, oa, ob, rate, ch); | ||
| 1183 | + } | ||
| 853 | worst_full = worst_full.min(full); | 1184 | worst_full = worst_full.min(full); |
| 854 | worst_low = worst_low.min(low); | 1185 | worst_low = worst_low.min(low); |
| 855 | } | 1186 | } |