forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u10' into simplify/w1b

Browse files at this commit

329d10ddbd986c30dfb0d03a6f7321cf0449cff9Ahmet Kaan GümüşParent: eb9d687adeb902

28 changed files +144 -11410

Cargo.lockmodified+0 -1
@@ -361,7 +361,6 @@ version = "0.1.0"
361361 dependencies = [
362362 "ec-core",
363363 "ec-dsp",
364- "ec-matroska",
365364 "ec-mp4",
366365 "ec-testkit",
367366 ]
crates/ec-aac/Cargo.tomlmodified+0 -1
@@ -12,5 +12,4 @@ ec-dsp = { workspace = true }
1212
1313 [dev-dependencies]
1414 ec-mp4 = { workspace = true }
15-ec-matroska = { workspace = true }
1615 ec-testkit.workspace = true
crates/ec-aac/examples/aacenc_rt.rsdeleted+0 -105
@@ -1,105 +0,0 @@
1-//! AAC-LC encode speed relative to realtime, which is how the crate's encode
2-//! perf claim is measured: a deterministic tonal-plus-transient program, ten
3-//! seconds, at the seat's rates (stereo 256 kbit/s, 5.1 512 kbit/s), the
4-//! shortest wall of several alternating repetitions.
5-//!
6-//! ```text
7-//! cargo run --release -p ec-aac --example aacenc_rt
8-//! ```
9-
10-use std::time::Instant;
11-
12-use ec_aac::{AacEncoder, AacEncoderConfig};
13-
14-/// Deterministic tonal stacks with periodic noise bursts: enough tonality for
15-/// the spreading function to bite, enough attacks to exercise the short-block
16-/// path.
17-struct Lcg(u64);
18-impl Lcg {
19- fn next_f32(&mut self) -> f32 {
20- self.0 = self
21- .0
22- .wrapping_mul(6364136223846793005)
23- .wrapping_add(1442695040888963407);
24- ((self.0 >> 40) as f32 / 16777216.0) * 2.0 - 1.0
25- }
26-}
27-
28-fn channel(f0: f64, seed: u64, rate: u32, secs: usize, burst_period: f64) -> Vec<f32> {
29- let mut noise = Lcg(seed);
30- let mut out = Vec::with_capacity(secs * rate as usize);
31- for i in 0..secs * rate as usize {
32- let t = i as f64 / rate as f64;
33- let frac = (t % burst_period) / burst_period;
34- let burst = (-frac * 18.0_f64).exp() as f32;
35- let stack = (f0.sin() * 0.5
36- + (f0 * 3.0).sin() * 0.15
37- + (f0 * 5.0 + 0.31 * (6.0 * std::f64::consts::TAU * t).sin()).sin() * 0.08)
38- as f32
39- * (0.7 + 0.3 * (0.5 * std::f64::consts::TAU * t).sin()) as f32;
40- out.push(stack + burst * noise.next_f32() * 0.3);
41- }
42- out
43-}
44-
45-fn program(channels: usize, rate: u32, secs: usize) -> Vec<f32> {
46- let stereo = [0x5EED_1234u64, 0xC0FF_EE01];
47- let five_one = [0x5EED_1234, 0xC0FF_EE01, 0xABCD_0001, 0xABCD_0002, 0xABCD_0003, 0xABCD_0004];
48- let f0s = [220.0f64, 277.0, 330.0, 55.0, 196.0, 246.9];
49- let periods = [0.9f64, 0.8, 1.1, 1.3, 0.7, 0.85];
50- let seeds: &[u64] = if channels == 2 {
51- &stereo
52- } else {
53- &five_one
54- };
55- let chans: Vec<Vec<f32>> = (0..channels)
56- .map(|c| channel(f0s[c], seeds[c], rate, secs, periods[c]))
57- .collect();
58- let mut pcm = Vec::with_capacity(chans[0].len() * channels);
59- for i in 0..chans[0].len() {
60- for c in &chans {
61- pcm.push(c[i]);
62- }
63- }
64- pcm
65-}
66-
67-fn encode(pcm: &[f32], channels: usize, kbps: u32) -> usize {
68- let mut enc = AacEncoder::new(AacEncoderConfig {
69- bitrate_bps: kbps * 1_000,
70- ..Default::default()
71- });
72- enc.push_pcm(pcm, channels as u16, 48_000).expect("pcm accepted");
73- enc.finish();
74- let mut bytes = 0usize;
75- while let Ok(p) = enc.next_packet() {
76- bytes += p.data.len();
77- }
78- bytes
79-}
80-
81-fn main() {
82- let reps: usize = std::env::var("REPS")
83- .ok()
84- .and_then(|s| s.parse().ok())
85- .unwrap_or(7);
86- for (channels, kbps) in [(2usize, 256u32), (6, 512)] {
87- let pcm = program(channels, 48_000, 10);
88- let secs = pcm.len() as f64 / (48_000.0 * channels as f64);
89- let _ = encode(&pcm, channels, kbps); // warm
90- let mut walls = Vec::with_capacity(reps);
91- for _ in 0..reps {
92- let t0 = Instant::now();
93- let bytes = encode(&pcm, channels, kbps);
94- walls.push((t0.elapsed().as_secs_f64(), bytes));
95- }
96- walls.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
97- let (wall, bytes) = walls[0];
98- println!(
99- "{channels}ch {kbps}k: min {wall:.4}s = {:.1}x realtime ({} B, {} reps)",
100- secs / wall,
101- bytes,
102- reps
103- );
104- }
105-}
crates/ec-aac/examples/adts_to_pcm.rsmodified+1 -33
@@ -9,39 +9,7 @@ fn main() {
99 .nth(1)
1010 .expect("usage: adts_to_pcm <file.aac>");
1111 let data = std::fs::read(&path).expect("file readable");
12- // Plain `AacDecoder::new()` never enables SBR (it only turns on from an
13- // explicit AudioSpecificConfig's `sbr_present`, per `with_config`) --
14- // the probe streams here are raw same-rate-SBR ADTS with no ASC, so
15- // build one directly rather than parsing bytes we don't have.
16- let same_rate_sbr = std::env::var("EC_AAC_SBR_SAME_RATE").is_ok();
17- let channels: u16 = std::env::var("EC_AAC_SBR_CHANNELS")
18- .ok()
19- .and_then(|s| s.parse().ok())
20- .unwrap_or(1);
21- // Round-32: built via the SAME write_audio_specific_config +
22- // with_config_bytes round trip `wrap_sbr` uses (AOT_SBR, core rate
23- // 22050 = ADTS sf_index 7's SAMPLE_RATES entry, extension 44100) so this
24- // path and the reference's wrap_sbr-wrapped mp4 read byte-identical ASC
25- // semantics -- the prior hand-built config (object_type=2/AAC-LC,
26- // sample_rate=44100 for what is actually the 22050 Hz *core*) diverged
27- // from wrap_sbr's ASC, which is why the sanity gate (ours vs
28- // build_patches) was failing independent of any patch-map bug.
29- let mut decoder = if same_rate_sbr {
30- let asc = ec_aac::write_audio_specific_config(&ec_aac::AudioSpecificConfig {
31- object_type: ec_aac::AOT_SBR,
32- sample_rate: 22050,
33- sf_index: 7,
34- channels,
35- channel_config: channels as u8,
36- sbr_present: true,
37- ps_present: false,
38- extension_sample_rate: Some(44100),
39- pce: Vec::new(),
40- });
41- ec_aac::AacDecoder::with_config_bytes(&asc).expect("asc parses")
42- } else {
43- ec_aac::AacDecoder::new()
44- };
12+ let mut decoder = ec_aac::AacDecoder::new();
4513 let mut at = 0usize;
4614 let stdout = std::io::stdout();
4715 let mut out = stdout.lock();
crates/ec-aac/examples/wrap_sbr.rsdeleted+0 -109
@@ -1,109 +0,0 @@
1-//! Wraps a bare ADTS stream (the SBR patch-map probes'
2-//! `scripts/aac-tables/sbrpatchmap.py` output) in an mp4 container carrying
3-//! an EXPLICIT-SBR AudioSpecificConfig as its `esds` -- the instrument
4-//! round-30's blocker needed: a bare `.aac` file carries no out-of-band
5-//! AudioSpecificConfig at all, so a decoder that trusts one (rather than
6-//! only its bare-ADTS implicit per-frame SBR detection) has nothing to arm
7-//! HE-AAC output from and locks to core-rate.
8-//!
9-//! Matroska was tried first (`MatroskaMuxer`, dev-dep already proven to
10-//! round-trip `CodecPrivate` byte-for-byte in
11-//! `crates/ec-aac/tests/sbr_real_library.rs`) but the reference decoder's
12-//! Matroska demuxer reads the *codec ID string* ("A_AAC" vs.
13-//! "A_AAC/MPEG4/SBR") for its reported profile, not just the `CodecPrivate`
14-//! bytes our `MatroskaMuxer` writes generically -- it still upgraded the
15-//! reported sample rate to the extension rate (proving it DOES parse
16-//! `CodecPrivate` for that), but kept reporting profile "LC". mp4's `esds`
17-//! carries the same explicit-SBR AudioSpecificConfig and needs no such
18-//! sibling string, matching the real `~/Music/reeln.mp4` fixture's
19-//! own container exactly.
20-//!
21-//! `stream()`/`stream_one_band()`'s probe frames are full ADTS (7-byte
22-//! header + raw_data_block); this strips the header off each frame and
23-//! remuxes the raw access units into an mp4 track whose `esds` is
24-//! `write_audio_specific_config` with `object_type = AOT_SBR` and an
25-//! explicit `extension_sample_rate`.
26-//!
27-//! usage: wrap_sbr_mkv <in.aac> <core_rate> <ext_rate> <channels> <out.mp4>
28-use std::fs::File;
29-
30-use ec_aac::{AOT_SBR, AudioSpecificConfig, sf_index_for_rate, write_audio_specific_config};
31-use ec_core::{
32- AudioParameters, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, Packet,
33- StreamInfo, TimeBase,
34-};
35-use ec_mp4::Mp4Muxer;
36-
37-fn main() {
38- let args: Vec<String> = std::env::args().collect();
39- assert_eq!(
40- args.len(),
41- 6,
42- "usage: wrap_sbr_mkv <in.aac> <core_rate> <ext_rate> <channels> <out.mkv>"
43- );
44- let data = std::fs::read(&args[1]).expect("input readable");
45- let core_rate: u32 = args[2].parse().expect("core_rate is a number");
46- let ext_rate: u32 = args[3].parse().expect("ext_rate is a number");
47- let channels: u16 = args[4].parse().expect("channels is a number");
48-
49- // Strip each ADTS frame down to its raw access unit (no header, no CRC).
50- let mut aus = Vec::new();
51- let mut at = 0usize;
52- while at + 7 <= data.len() {
53- let Ok(header) = ec_aac::parse_adts(&data[at..]) else {
54- break;
55- };
56- let end = (at + header.frame_length).min(data.len());
57- aus.push(data[at + header.header_len..end].to_vec());
58- at = end;
59- }
60- assert!(!aus.is_empty(), "no ADTS frames found in {}", args[1]);
61-
62- let sf_index = sf_index_for_rate(core_rate).expect("core_rate is a valid AAC rate");
63- let channel_config = channels as u8;
64- let asc = write_audio_specific_config(&AudioSpecificConfig {
65- object_type: AOT_SBR,
66- sample_rate: core_rate,
67- sf_index,
68- channels,
69- channel_config,
70- sbr_present: true,
71- ps_present: false,
72- extension_sample_rate: Some(ext_rate),
73- pce: Vec::new(),
74- });
75-
76- let time_base = TimeBase::from_rate(core_rate);
77- let layout = if channels == 1 {
78- ChannelLayout::Mono
79- } else {
80- ChannelLayout::Stereo
81- };
82- let mut params = CodecParameters::new(CodecId::Aac);
83- params.extradata = Some(asc.into());
84- params.media = MediaParameters::Audio(AudioParameters {
85- sample_rate: core_rate,
86- layout,
87- format: None,
88- bits_per_sample: None,
89- });
90- let mut info = StreamInfo::new(0, time_base, params);
91- info.default = true;
92-
93- let out = File::create(&args[5]).expect("output creatable");
94- let mut muxer = Mp4Muxer::new(out).expect("mp4 muxer opens");
95- muxer.add_stream(info).expect("stream declared");
96- for (i, au) in aus.iter().enumerate() {
97- let pts = i as i64 * 1024;
98- let packet = Packet::new(0, time_base, au.as_slice())
99- .with_pts(pts)
100- .with_duration(1024);
101- muxer.write_packet(&packet).expect("packet written");
102- }
103- muxer.finish().expect("finished");
104- eprintln!(
105- "wrote {} ({} frames, core={core_rate}Hz ext={ext_rate}Hz ch={channels})",
106- args[5],
107- aus.len()
108- );
109-}
crates/ec-aac/src/decode.rsmodified+0 -89
@@ -59,52 +59,6 @@ impl WindowSequence {
5959 }
6060 }
6161
62-/// One `raw_data_block` element's coding-tool usage, gated by
63-/// `EC_AAC_TOOL_SIDEINFO_DEBUG` -- mirrors `sbr_chain::SbrSideInfoRow`'s
64-/// pattern for the LC core, so a real file's PNS/M-S/IS/TNS mix can be read
65-/// back per AU without re-parsing debug text.
66-#[derive(Clone, Debug)]
67-pub struct ToolSideInfoRow {
68- pub au: usize,
69- pub tag: u8,
70- pub is_cpe: bool,
71- pub window_sequence: WindowSequence,
72- pub ms_bands: usize,
73- pub pns_bands: usize,
74- pub is_bands: usize,
75- pub tns_present: bool,
76-}
77-
78-static TOOL_SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<ToolSideInfoRow>>> =
79- std::sync::OnceLock::new();
80-static TOOL_SIDEINFO_AU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
81-
82-fn tool_sideinfo_enabled() -> bool {
83- crate::knobs::tool_sideinfo_debug()
84-}
85-
86-fn log_tool_sideinfo(row: ToolSideInfoRow) {
87- let log = TOOL_SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
88- if let Ok(mut l) = log.lock() {
89- l.push(row);
90- }
91-}
92-
93-/// Bumps the shared AU counter once per `raw_data_block`, returning the value
94-/// that call's rows should carry.
95-fn next_tool_sideinfo_au() -> usize {
96- TOOL_SIDEINFO_AU.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
97-}
98-
99-/// Every row logged so far this process, in call order. Empty unless
100-/// `EC_AAC_TOOL_SIDEINFO_DEBUG` was set before decoding.
101-pub fn tool_sideinfo_log() -> Vec<ToolSideInfoRow> {
102- let Some(log) = TOOL_SIDEINFO_LOG.get() else {
103- return Vec::new();
104- };
105- log.lock().map(|l| l.clone()).unwrap_or_default()
106-}
107-
10862 /// `ics_info` (§4.4.2.1) plus the grouping it implies.
10963 #[derive(Clone, Debug)]
11064 pub struct IcsInfo {
@@ -845,12 +799,6 @@ impl BlockDecoder {
845799 // FIL's SBR payload would apply to, per §4.5.1: a fill_element
846800 // directly follows the element it decorates.
847801 let mut pending: Option<(u8, usize, usize, bool)> = None;
848- let dump_tools = tool_sideinfo_enabled();
849- let au = if dump_tools {
850- next_tool_sideinfo_au()
851- } else {
852- 0
853- };
854802 let mut pns = false;
855803 // Speaker per plane so far; `named` drops to false at the first element a PCE does not name.
856804 let mut speakers: Vec<crate::config::Speaker> = Vec::new();
@@ -869,9 +817,6 @@ impl BlockDecoder {
869817 let start = out.len();
870818 let mut ch = [self.channel_stream(r, None)?];
871819 pns |= has_pns(&ch[0]);
872- if dump_tools {
873- log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None));
874- }
875820 self.finish(&mut ch, None, &mut out);
876821 if let (3, Some(sbr), Some(plane)) = (id, self.sbr.as_mut(), out.get_mut(start)) {
877822 sbr.bypass_plane(tag, plane);
@@ -919,9 +864,6 @@ impl BlockDecoder {
919864 self.channel_stream(r, shared.as_ref())?,
920865 ];
921866 pns |= pair.iter().any(has_pns);
922- if dump_tools {
923- log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));
924- }
925867 self.finish(&mut pair, Some(&mask), &mut out);
926868 named &= self.note_speakers(1, tag, 2, &mut speakers);
927869 pending = Some((tag, start, 2, true));
@@ -1193,43 +1135,12 @@ fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
11931135 }
11941136 }
11951137
1196-/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics`
1197-/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the
1198-/// dump only needs whether the element used the tool at all).
11991138 fn has_pns(ch: &Ics) -> bool {
12001139 ch.cb
12011140 .iter()
12021141 .any(|group| group.contains(&NOISE_HCB))
12031142 }
12041143
1205-fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {
1206- let mut ms_bands = 0;
1207- let mut pns_bands = 0;
1208- let mut is_bands = 0;
1209- for g in 0..ch.ics.num_groups {
1210- for sfb in 0..ch.ics.max_sfb {
1211- if mask.is_some_and(|m| m.used(g, sfb)) {
1212- ms_bands += 1;
1213- }
1214- match ch.cb[g][sfb] {
1215- NOISE_HCB => pns_bands += 1,
1216- INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1,
1217- _ => {}
1218- }
1219- }
1220- }
1221- ToolSideInfoRow {
1222- au,
1223- tag,
1224- is_cpe,
1225- window_sequence: ch.ics.window_sequence,
1226- ms_bands,
1227- pns_bands,
1228- is_bands,
1229- tns_present: !ch.tns.filters.is_empty(),
1230- }
1231-}
1232-
12331144 fn is_intensity(cb: u8) -> bool {
12341145 cb == INTENSITY_HCB || cb == INTENSITY_HCB2
12351146 }
crates/ec-aac/src/knobs.rsdeleted+0 -104
@@ -1,104 +0,0 @@
1-//! Debug switches the AAC/SBR decoder reads from the environment, with a
2-//! per-thread override that tests set instead of editing the process
3-//! environment (which is `unsafe` in Rust 2024).
4-//!
5-//! The decoder reads these on the thread that calls `decode`, so an override
6-//! set on a test's own thread covers exactly that test's decodes and nothing
7-//! running in parallel. With no override set, each reader answers from the
8-//! environment exactly as it always has, so manual runs with `EC_AAC_*` set
9-//! behave as before.
10-
11-use std::cell::Cell;
12-use std::thread::LocalKey;
13-
14-type Slot = Cell<Option<bool>>;
15-
16-thread_local! {
17- static TOOL_SIDEINFO_DEBUG: Slot = const { Cell::new(None) };
18- static SBR_SIDEINFO_DEBUG: Slot = const { Cell::new(None) };
19- static SBR_HF_BYPASS: Slot = const { Cell::new(None) };
20- static SBR_NOISE_ZERO: Slot = const { Cell::new(None) };
21- static SBR_NOISE_FRACTION: Slot = const { Cell::new(None) };
22-}
23-
24-/// The override on this thread if one is set, else whether `var` is set.
25-fn enabled(slot: &'static LocalKey<Slot>, var: &str) -> bool {
26- slot.with(Cell::get)
27- .unwrap_or_else(|| std::env::var(var).is_ok())
28-}
29-
30-fn force(slot: &'static LocalKey<Slot>, on: Option<bool>) -> Override<Option<bool>> {
31- let prev = slot.with(|c| c.replace(on));
32- Override { slot, prev }
33-}
34-
35-/// Restores the value a knob had before [`set_tool_sideinfo_debug`] and its
36-/// siblings were called, when dropped.
37-#[doc(hidden)]
38-#[must_use = "the override ends as soon as this guard is dropped"]
39-pub struct Override<T: Copy + 'static> {
40- slot: &'static LocalKey<Cell<T>>,
41- prev: T,
42-}
43-
44-impl<T: Copy + 'static> Drop for Override<T> {
45- fn drop(&mut self) {
46- self.slot.with(|c| c.set(self.prev));
47- }
48-}
49-
50-/// `EC_AAC_TOOL_SIDEINFO_DEBUG`.
51-pub(crate) fn tool_sideinfo_debug() -> bool {
52- enabled(&TOOL_SIDEINFO_DEBUG, "EC_AAC_TOOL_SIDEINFO_DEBUG")
53-}
54-
55-/// `EC_AAC_SBR_SIDEINFO_DEBUG`.
56-pub(crate) fn sbr_sideinfo_debug() -> bool {
57- enabled(&SBR_SIDEINFO_DEBUG, "EC_AAC_SBR_SIDEINFO_DEBUG")
58-}
59-
60-/// `EC_AAC_SBR_HF_BYPASS`.
61-pub(crate) fn sbr_hf_bypass() -> bool {
62- enabled(&SBR_HF_BYPASS, "EC_AAC_SBR_HF_BYPASS")
63-}
64-
65-/// `EC_AAC_SBR_NOISE_ZERO`.
66-pub(crate) fn sbr_noise_zero() -> bool {
67- enabled(&SBR_NOISE_ZERO, "EC_AAC_SBR_NOISE_ZERO")
68-}
69-
70-/// `EC_AAC_SBR_NOISE_FRACTION`.
71-pub(crate) fn sbr_noise_fraction() -> bool {
72- enabled(&SBR_NOISE_FRACTION, "EC_AAC_SBR_NOISE_FRACTION")
73-}
74-
75-/// Forces `EC_AAC_TOOL_SIDEINFO_DEBUG` on (`Some(true)`), off (`Some(false)`)
76-/// or back to the environment (`None`) on this thread, until the guard drops.
77-#[doc(hidden)]
78-pub fn set_tool_sideinfo_debug(on: Option<bool>) -> Override<Option<bool>> {
79- force(&TOOL_SIDEINFO_DEBUG, on)
80-}
81-
82-/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_SIDEINFO_DEBUG`.
83-#[doc(hidden)]
84-pub fn set_sbr_sideinfo_debug(on: Option<bool>) -> Override<Option<bool>> {
85- force(&SBR_SIDEINFO_DEBUG, on)
86-}
87-
88-/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_HF_BYPASS`.
89-#[doc(hidden)]
90-pub fn set_sbr_hf_bypass(on: Option<bool>) -> Override<Option<bool>> {
91- force(&SBR_HF_BYPASS, on)
92-}
93-
94-/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_ZERO`.
95-#[doc(hidden)]
96-pub fn set_sbr_noise_zero(on: Option<bool>) -> Override<Option<bool>> {
97- force(&SBR_NOISE_ZERO, on)
98-}
99-
100-/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_FRACTION`.
101-#[doc(hidden)]
102-pub fn set_sbr_noise_fraction(on: Option<bool>) -> Override<Option<bool>> {
103- force(&SBR_NOISE_FRACTION, on)
104-}
crates/ec-aac/src/lib.rsmodified+6 -16
@@ -35,15 +35,13 @@ mod sbr_chain;
3535 mod sbr_env;
3636 mod sbr_hf;
3737 mod sbr_payload;
38-pub mod sbr_qmf;
38+mod sbr_qmf;
3939 mod sbr_qmf_window;
4040 mod ps_data;
4141 mod ps_dsp;
4242 mod ps_huff;
4343 mod sbr_tables;
44-pub mod tables;
45-#[doc(hidden)]
46-pub mod knobs;
44+mod tables;
4745
4846 pub use config::{
4947 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
@@ -51,16 +49,9 @@ pub use config::{
5149 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
5250 write_adts_header, write_audio_specific_config,
5351 };
54-pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log};
52+pub use decode::{FRAME_LEN, WindowSequence};
5553 pub use ec_core::{Error, Result};
5654 pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
57-/// Diagnostic only (round-20): per-(access-unit, channel) side-info rows
58-/// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set.
59-pub use sbr_chain::{SbrSideInfoRow, hold_call_count, sbr_sideinfo_log};
60-/// Diagnostic only (round-17 Task 1 conviction check): reads back the
61-/// per-absolute-QMF-band transmitted signal/noise energy sums
62-/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode.
63-pub use sbr_env::noise_fraction_table;
6455 pub use tables::SAMPLE_RATES;
6556
6657 use decode::BlockDecoder;
@@ -74,9 +65,6 @@ pub enum SbrSupport {
7465 /// SBR is signalled and **is** reconstructed: the decoded audio spans
7566 /// the full extension bandwidth at the extension sample rate.
7667 V1,
77- /// SBR is signalled but not reconstructed. Not produced by this decoder
78- /// any more: Parametric Stereo streams report [`SbrSupport::V1`].
79- CoreOnly,
8068 }
8169
8270 /// One decoded frame: interleaved `f32` in film channel order.
@@ -305,7 +293,9 @@ impl AacDecoder {
305293 let frames = planes[0].len();
306294 let mut samples = vec![0.0f32; frames * channels];
307295 for (out_ch, &src) in order.iter().take(channels).enumerate() {
308- let plane = &planes[src.min(channels - 1)];
296+ let plane = planes
297+ .get(src)
298+ .ok_or_else(|| Error::corrupt("aac: channel order names a missing plane"))?;
309299 // Planes can differ in length after `merge`; only the first `frames` samples fit.
310300 for (i, &v) in plane.iter().take(frames).enumerate() {
311301 samples[i * channels + out_ch] = v;
crates/ec-aac/src/sbr_bands/tests.rsmodified+1 -1
@@ -2,7 +2,7 @@ use super::*;
22 use super::vectors::VECTORS;
33
44 #[test]
5-fn matches_reference_derivation_on_500_configurations() {
5+fn matches_reference_derivation() {
66 let mut mismatches = 0;
77 for &(
88 rate,
crates/ec-aac/src/sbr_bands/vectors/mod.rsmodified+1 -2
@@ -4,7 +4,6 @@
44 //! `scripts/aac-tables/sbrtables.py`'s `freq_tables` if that function ever changes.
55
66 mod part0;
7-mod part1;
87
98 /// `(sbr_rate, start_freq, stop_freq, freq_scale, alter_scale, noise_bands,
109 /// xover_band, expected)`, `expected` being `(n_master, n_high, n_low, n_q,
@@ -22,4 +21,4 @@ pub(super) type Vector = (
2221 );
2322
2423 /// All reference vectors, in two parts.
25-pub(super) static VECTORS: &[&[Vector]] = &[part0::PART, part1::PART];
24+pub(super) static VECTORS: &[&[Vector]] = &[part0::PART];
crates/ec-aac/src/sbr_bands/vectors/part0.rsmodified+0 -3821

Diff too large; view file

@@ -481,3825 +481,4 @@ pub(super) static PART: &[Vector] = &[
481481 5,
482482 Some((8, 3, 2, 1, &[36, 38, 40, 42], &[36, 38, 42], &[36, 42])),
483483 ),
484- (
485- 24000,
486- 5,
487- 14,
488- 0,
489- 0,
490- 0,
491- 7,
492- Some((
493- 16,
494- 9,
495- 5,
496- 1,
497- &[24, 25, 26, 27, 28, 29, 30, 31, 32, 34],
498- &[24, 25, 27, 29, 31, 34],
499- &[24, 34],
500- )),
501- ),
502- (22050, 14, 3, 2, 0, 3, 6, None),
503- (
504- 96000,
505- 6,
506- 7,
507- 3,
508- 0,
509- 1,
510- 6,
511- Some((
512- 12,
513- 6,
514- 3,
515- 1,
516- &[18, 20, 22, 24, 26, 28, 31],
517- &[18, 22, 26, 31],
518- &[18, 31],
519- )),
520- ),
521- (
522- 22050,
523- 12,
524- 3,
525- 1,
526- 0,
527- 1,
528- 7,
529- Some((8, 1, 1, 1, &[37, 40], &[37, 40], &[37, 40])),
530- ),
531- (
532- 32000,
533- 2,
534- 7,
535- 0,
536- 0,
537- 0,
538- 5,
539- Some((
540- 32,
541- 27,
542- 14,
543- 1,
544- &[
545- 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
546- 39, 40, 41, 42, 43, 44, 45, 46,
547- ],
548- &[19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
549- &[19, 46],
550- )),
551- ),
552- (96000, 15, 3, 2, 1, 1, 0, None),
553- (
554- 96000,
555- 4,
556- 8,
557- 3,
558- 1,
559- 2,
560- 1,
561- Some((
562- 14,
563- 13,
564- 7,
565- 4,
566- &[10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 25, 28, 31, 35],
567- &[10, 11, 13, 15, 18, 22, 28, 35],
568- &[10, 11, 15, 22, 35],
569- )),
570- ),
571- (
572- 96000,
573- 4,
574- 9,
575- 3,
576- 0,
577- 0,
578- 1,
579- Some((
580- 16,
581- 15,
582- 8,
583- 1,
584- &[
585- 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 29, 32, 35, 39,
586- ],
587- &[10, 11, 13, 15, 18, 22, 26, 32, 39],
588- &[10, 39],
589- )),
590- ),
591- (
592- 22050,
593- 15,
594- 13,
595- 0,
596- 0,
597- 2,
598- 0,
599- Some((
600- 34,
601- 34,
602- 17,
603- 2,
604- &[
605- 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
606- 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
607- ],
608- &[
609- 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
610- ],
611- &[30, 46, 64],
612- )),
613- ),
614- (96000, 13, 0, 0, 0, 0, 1, None),
615- (
616- 64000,
617- 7,
618- 3,
619- 2,
620- 0,
621- 1,
622- 7,
623- Some((8, 1, 1, 1, &[24, 26], &[24, 26], &[24, 26])),
624- ),
625- (
626- 64000,
627- 0,
628- 7,
629- 0,
630- 1,
631- 0,
632- 0,
633- Some((
634- 16,
635- 16,
636- 8,
637- 1,
638- &[
639- 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37,
640- ],
641- &[6, 9, 13, 17, 21, 25, 29, 33, 37],
642- &[6, 37],
643- )),
644- ),
645- (64000, 1, 7, 2, 1, 0, 2, None),
646- (
647- 24000,
648- 6,
649- 8,
650- 1,
651- 1,
652- 1,
653- 5,
654- Some((
655- 16,
656- 11,
657- 6,
658- 1,
659- &[23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 49],
660- &[23, 24, 28, 32, 36, 42, 49],
661- &[23, 49],
662- )),
663- ),
664- (
665- 16000,
666- 15,
667- 1,
668- 2,
669- 0,
670- 2,
671- 2,
672- Some((6, 4, 2, 1, &[36, 39, 42, 45, 49], &[36, 42, 49], &[36, 49])),
673- ),
674- (
675- 22050,
676- 7,
677- 9,
678- 1,
679- 0,
680- 1,
681- 0,
682- Some((
683- 18,
684- 18,
685- 9,
686- 1,
687- &[
688- 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49, 52,
689- ],
690- &[19, 21, 23, 26, 30, 34, 38, 42, 46, 52],
691- &[19, 52],
692- )),
693- ),
694- (
695- 32000,
696- 7,
697- 5,
698- 3,
699- 1,
700- 3,
701- 4,
702- Some((
703- 10,
704- 6,
705- 3,
706- 2,
707- &[26, 28, 30, 33, 36, 39, 42],
708- &[26, 30, 36, 42],
709- &[26, 30, 42],
710- )),
711- ),
712- (96000, 15, 11, 2, 0, 1, 6, None),
713- (48000, 10, 11, 0, 1, 0, 0, None),
714- (
715- 32000,
716- 6,
717- 1,
718- 2,
719- 1,
720- 2,
721- 5,
722- Some((
723- 10,
724- 5,
725- 3,
726- 1,
727- &[24, 26, 28, 30, 32, 34],
728- &[24, 26, 30, 34],
729- &[24, 34],
730- )),
731- ),
732- (88200, 6, 3, 1, 0, 1, 6, None),
733- (
734- 88200,
735- 9,
736- 7,
737- 0,
738- 1,
739- 0,
740- 6,
741- Some((10, 4, 2, 1, &[25, 27, 29, 31, 33], &[25, 29, 33], &[25, 33])),
742- ),
743- (96000, 14, 2, 2, 0, 0, 1, None),
744- (32000, 6, 11, 2, 1, 1, 3, None),
745- (
746- 16000,
747- 2,
748- 0,
749- 2,
750- 1,
751- 3,
752- 3,
753- Some((
754- 14,
755- 11,
756- 6,
757- 4,
758- &[21, 23, 25, 27, 29, 31, 33, 36, 39, 42, 45, 48],
759- &[21, 23, 27, 31, 36, 42, 48],
760- &[21, 23, 27, 36, 48],
761- )),
762- ),
763- (
764- 44100,
765- 10,
766- 5,
767- 0,
768- 1,
769- 0,
770- 2,
771- Some((
772- 8,
773- 6,
774- 3,
775- 1,
776- &[22, 24, 26, 28, 30, 32, 34],
777- &[22, 26, 30, 34],
778- &[22, 34],
779- )),
780- ),
781- (88200, 14, 5, 1, 1, 2, 6, None),
782- (64000, 8, 11, 2, 1, 0, 4, None),
783- (
784- 32000,
785- 15,
786- 8,
787- 2,
788- 0,
789- 0,
790- 3,
791- Some((6, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
792- ),
793- (
794- 32000,
795- 11,
796- 0,
797- 2,
798- 0,
799- 0,
800- 2,
801- Some((4, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
802- ),
803- (88200, 7, 7, 1, 1, 1, 1, None),
804- (
805- 48000,
806- 9,
807- 0,
808- 0,
809- 0,
810- 0,
811- 0,
812- Some((4, 4, 2, 1, &[17, 18, 19, 20, 21], &[17, 19, 21], &[17, 21])),
813- ),
814- (48000, 12, 13, 0, 0, 0, 5, None),
815- (
816- 96000,
817- 15,
818- 12,
819- 1,
820- 0,
821- 0,
822- 7,
823- Some((10, 3, 2, 1, &[47, 50, 53, 57], &[47, 50, 57], &[47, 57])),
824- ),
825- (96000, 14, 0, 3, 1, 2, 0, None),
826- (
827- 64000,
828- 6,
829- 14,
830- 3,
831- 1,
832- 0,
833- 1,
834- Some((
835- 8,
836- 7,
837- 4,
838- 1,
839- &[14, 15, 16, 18, 20, 22, 24, 26],
840- &[14, 15, 18, 22, 26],
841- &[14, 26],
842- )),
843- ),
844- (64000, 1, 2, 3, 0, 3, 7, None),
845- (
846- 48000,
847- 8,
848- 8,
849- 2,
850- 0,
851- 1,
852- 7,
853- Some((
854- 14,
855- 7,
856- 4,
857- 1,
858- &[26, 28, 30, 32, 34, 36, 38, 41],
859- &[26, 28, 32, 36, 41],
860- &[26, 41],
861- )),
862- ),
863- (48000, 7, 1, 3, 0, 1, 6, None),
864- (
865- 32000,
866- 2,
867- 15,
868- 0,
869- 1,
870- 0,
871- 0,
872- Some((
873- 14,
874- 14,
875- 7,
876- 1,
877- &[14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
878- &[14, 18, 22, 26, 30, 34, 38, 42],
879- &[14, 42],
880- )),
881- ),
882- (64000, 4, 5, 1, 0, 1, 0, None),
883- (
884- 32000,
885- 2,
886- 5,
887- 1,
888- 0,
889- 1,
890- 1,
891- Some((
892- 20,
893- 19,
894- 10,
895- 1,
896- &[
897- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 29, 30, 32, 34, 36, 38, 40, 42,
898- ],
899- &[15, 16, 18, 20, 22, 24, 28, 30, 34, 38, 42],
900- &[15, 42],
901- )),
902- ),
903- (64000, 11, 4, 2, 0, 3, 6, None),
904- (
905- 16000,
906- 4,
907- 13,
908- 2,
909- 0,
910- 3,
911- 5,
912- Some((
913- 16,
914- 11,
915- 6,
916- 4,
917- &[28, 30, 32, 34, 37, 40, 43, 47, 51, 55, 59, 64],
918- &[28, 30, 34, 40, 47, 55, 64],
919- &[28, 30, 34, 47, 64],
920- )),
921- ),
922- (
923- 64000,
924- 15,
925- 14,
926- 0,
927- 0,
928- 1,
929- 3,
930- Some((
931- 30,
932- 27,
933- 14,
934- 1,
935- &[
936- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
937- 53, 54, 55, 56, 57, 58, 59, 60,
938- ],
939- &[33, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60],
940- &[33, 60],
941- )),
942- ),
943- (
944- 22050,
945- 8,
946- 15,
947- 0,
948- 0,
949- 0,
950- 3,
951- Some((
952- 40,
953- 37,
954- 19,
955- 1,
956- &[
957- 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
958- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
959- ],
960- &[
961- 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
962- ],
963- &[23, 60],
964- )),
965- ),
966- (44100, 1, 4, 1, 0, 3, 1, None),
967- (
968- 16000,
969- 2,
970- 2,
971- 2,
972- 0,
973- 2,
974- 4,
975- Some((
976- 14,
977- 10,
978- 5,
979- 2,
980- &[23, 25, 27, 29, 31, 33, 36, 39, 42, 46, 50],
981- &[23, 27, 31, 36, 42, 50],
982- &[23, 31, 50],
983- )),
984- ),
985- (
986- 44100,
987- 10,
988- 4,
989- 3,
990- 0,
991- 3,
992- 1,
993- Some((
994- 6,
995- 5,
996- 3,
997- 2,
998- &[20, 22, 24, 26, 28, 31],
999- &[20, 22, 26, 31],
1000- &[20, 22, 31],
1001- )),
1002- ),
1003- (
1004- 22050,
1005- 8,
1006- 12,
1007- 0,
1008- 0,
1009- 3,
1010- 7,
1011- Some((
1012- 40,
1013- 33,
1014- 17,
1015- 4,
1016- &[
1017- 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
1018- 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61,
1019- ],
1020- &[
1021- 27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 61,
1022- ],
1023- &[27, 34, 42, 50, 61],
1024- )),
1025- ),
1026- (
1027- 24000,
1028- 9,
1029- 5,
1030- 1,
1031- 0,
1032- 2,
1033- 2,
1034- Some((
1035- 12,
1036- 10,
1037- 5,
1038- 2,
1039- &[23, 24, 25, 27, 29, 31, 33, 35, 37, 39, 42],
1040- &[23, 25, 29, 33, 37, 42],
1041- &[23, 29, 42],
1042- )),
1043- ),
1044- (
1045- 24000,
1046- 8,
1047- 10,
1048- 3,
1049- 0,
1050- 0,
1051- 1,
1052- Some((
1053- 12,
1054- 11,
1055- 6,
1056- 1,
1057- &[22, 24, 26, 28, 31, 34, 37, 40, 43, 47, 51, 55],
1058- &[22, 24, 28, 34, 40, 47, 55],
1059- &[22, 55],
1060- )),
1061- ),
1062- (
1063- 48000,
1064- 13,
1065- 7,
1066- 0,
1067- 0,
1068- 1,
1069- 5,
1070- Some((
1071- 14,
1072- 9,
1073- 5,
1074- 1,
1075- &[29, 30, 31, 32, 33, 34, 35, 36, 37, 38],
1076- &[29, 30, 32, 34, 36, 38],
1077- &[29, 38],
1078- )),
1079- ),
1080- (64000, 13, 5, 2, 1, 3, 7, None),
1081- (24000, 0, 13, 2, 0, 2, 7, None),
1082- (
1083- 64000,
1084- 2,
1085- 14,
1086- 3,
1087- 0,
1088- 1,
1089- 4,
1090- Some((8, 4, 2, 1, &[13, 14, 15, 16, 18], &[13, 15, 18], &[13, 18])),
1091- ),
1092- (
1093- 88200,
1094- 14,
1095- 10,
1096- 2,
1097- 1,
1098- 0,
1099- 3,
1100- Some((
1101- 8,
1102- 5,
1103- 3,
1104- 1,
1105- &[33, 35, 37, 40, 43, 46],
1106- &[33, 35, 40, 46],
1107- &[33, 46],
1108- )),
1109- ),
1110- (88200, 5, 12, 2, 1, 1, 4, None),
1111- (64000, 3, 13, 0, 0, 0, 2, None),
1112- (
1113- 16000,
1114- 4,
1115- 10,
1116- 2,
1117- 1,
1118- 3,
1119- 7,
1120- Some((
1121- 14,
1122- 7,
1123- 4,
1124- 3,
1125- &[32, 34, 37, 40, 44, 48, 53, 58],
1126- &[32, 34, 40, 48, 58],
1127- &[32, 34, 40, 58],
1128- )),
1129- ),
1130- (
1131- 24000,
1132- 2,
1133- 9,
1134- 1,
1135- 1,
1136- 0,
1137- 5,
1138- Some((
1139- 20,
1140- 15,
1141- 8,
1142- 1,
1143- &[
1144- 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 35, 38, 41, 44, 48, 52,
1145- ],
1146- &[19, 20, 22, 24, 28, 32, 38, 44, 52],
1147- &[19, 52],
1148- )),
1149- ),
1150- (
1151- 24000,
1152- 12,
1153- 8,
1154- 2,
1155- 1,
1156- 2,
1157- 7,
1158- Some((10, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
1159- ),
1160- (
1161- 32000,
1162- 6,
1163- 2,
1164- 0,
1165- 1,
1166- 0,
1167- 4,
1168- Some((
1169- 10,
1170- 6,
1171- 3,
1172- 1,
1173- &[24, 26, 28, 30, 32, 34, 36],
1174- &[24, 28, 32, 36],
1175- &[24, 36],
1176- )),
1177- ),
1178- (96000, 12, 4, 0, 1, 2, 2, None),
1179- (88200, 9, 12, 3, 1, 0, 3, None),
1180- (
1181- 44100,
1182- 2,
1183- 3,
1184- 0,
1185- 1,
1186- 1,
1187- 2,
1188- Some((
1189- 10,
1190- 8,
1191- 4,
1192- 1,
1193- &[13, 15, 17, 19, 21, 23, 25, 27, 29],
1194- &[13, 17, 21, 25, 29],
1195- &[13, 29],
1196- )),
1197- ),
1198- (
1199- 24000,
1200- 4,
1201- 2,
1202- 2,
1203- 0,
1204- 0,
1205- 4,
1206- Some((
1207- 12,
1208- 8,
1209- 4,
1210- 1,
1211- &[20, 22, 24, 26, 28, 30, 32, 34, 36],
1212- &[20, 24, 28, 32, 36],
1213- &[20, 36],
1214- )),
1215- ),
1216- (44100, 14, 1, 2, 1, 3, 7, None),
1217- (
1218- 16000,
1219- 14,
1220- 13,
1221- 0,
1222- 0,
1223- 3,
1224- 5,
1225- Some((
1226- 34,
1227- 29,
1228- 15,
1229- 3,
1230- &[
1231- 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
1232- 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
1233- ],
1234- &[
1235- 35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
1236- ],
1237- &[35, 44, 54, 64],
1238- )),
1239- ),
1240- (
1241- 24000,
1242- 5,
1243- 4,
1244- 1,
1245- 0,
1246- 1,
1247- 4,
1248- Some((
1249- 14,
1250- 10,
1251- 5,
1252- 1,
1253- &[21, 22, 23, 24, 26, 28, 30, 32, 34, 37, 40],
1254- &[21, 23, 26, 30, 34, 40],
1255- &[21, 40],
1256- )),
1257- ),
1258- (
1259- 32000,
1260- 12,
1261- 2,
1262- 1,
1263- 0,
1264- 3,
1265- 2,
1266- Some((6, 4, 2, 1, &[28, 30, 32, 34, 36], &[28, 32, 36], &[28, 36])),
1267- ),
1268- (
1269- 96000,
1270- 4,
1271- 1,
1272- 3,
1273- 1,
1274- 3,
1275- 1,
1276- Some((
1277- 6,
1278- 5,
1279- 3,
1280- 2,
1281- &[10, 11, 12, 13, 14, 15],
1282- &[10, 11, 13, 15],
1283- &[10, 11, 15],
1284- )),
1285- ),
1286- (
1287- 64000,
1288- 5,
1289- 14,
1290- 0,
1291- 0,
1292- 1,
1293- 4,
1294- Some((
1295- 12,
1296- 8,
1297- 4,
1298- 1,
1299- &[16, 17, 18, 19, 20, 21, 22, 23, 24],
1300- &[16, 18, 20, 22, 24],
1301- &[16, 24],
1302- )),
1303- ),
1304- (
1305- 24000,
1306- 13,
1307- 8,
1308- 2,
1309- 0,
1310- 1,
1311- 0,
1312- Some((
1313- 8,
1314- 8,
1315- 4,
1316- 1,
1317- &[27, 29, 31, 33, 36, 39, 42, 45, 49],
1318- &[27, 31, 36, 42, 49],
1319- &[27, 49],
1320- )),
1321- ),
1322- (
1323- 96000,
1324- 6,
1325- 2,
1326- 2,
1327- 1,
1328- 0,
1329- 3,
1330- Some((6, 3, 2, 1, &[14, 15, 16, 17], &[14, 15, 17], &[14, 17])),
1331- ),
1332- (
1333- 88200,
1334- 7,
1335- 6,
1336- 3,
1337- 0,
1338- 3,
1339- 4,
1340- Some((
1341- 10,
1342- 6,
1343- 3,
1344- 3,
1345- &[16, 18, 20, 22, 24, 26, 29],
1346- &[16, 20, 24, 29],
1347- &[16, 20, 24, 29],
1348- )),
1349- ),
1350- (88200, 2, 14, 1, 0, 0, 5, None),
1351- (
1352- 96000,
1353- 6,
1354- 3,
1355- 3,
1356- 0,
1357- 3,
1358- 1,
1359- Some((
1360- 6,
1361- 5,
1362- 3,
1363- 2,
1364- &[12, 13, 14, 15, 17, 19],
1365- &[12, 13, 15, 19],
1366- &[12, 13, 19],
1367- )),
1368- ),
1369- (32000, 0, 3, 1, 1, 2, 6, None),
1370- (
1371- 48000,
1372- 14,
1373- 5,
1374- 1,
1375- 0,
1376- 2,
1377- 0,
1378- Some((2, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
1379- ),
1380- (64000, 3, 8, 1, 1, 3, 5, None),
1381- (
1382- 22050,
1383- 13,
1384- 0,
1385- 3,
1386- 0,
1387- 2,
1388- 0,
1389- Some((4, 4, 2, 1, &[26, 28, 30, 32, 35], &[26, 30, 35], &[26, 35])),
1390- ),
1391- (
1392- 44100,
1393- 0,
1394- 8,
1395- 0,
1396- 1,
1397- 2,
1398- 1,
1399- Some((
1400- 18,
1401- 17,
1402- 9,
1403- 5,
1404- &[
1405- 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43,
1406- ],
1407- &[9, 11, 15, 19, 23, 27, 31, 35, 39, 43],
1408- &[9, 11, 19, 27, 35, 43],
1409- )),
1410- ),
1411- (
1412- 48000,
1413- 9,
1414- 14,
1415- 3,
1416- 1,
1417- 2,
1418- 7,
1419- Some((8, 1, 1, 1, &[31, 34], &[31, 34], &[31, 34])),
1420- ),
1421- (88200, 13, 6, 1, 1, 0, 7, None),
1422- (88200, 2, 3, 3, 1, 3, 6, None),
1423- (
1424- 64000,
1425- 0,
1426- 0,
1427- 0,
1428- 0,
1429- 0,
1430- 1,
1431- Some((
1432- 14,
1433- 13,
1434- 7,
1435- 1,
1436- &[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
1437- &[7, 8, 10, 12, 14, 16, 18, 20],
1438- &[7, 20],
1439- )),
1440- ),
1441- (44100, 0, 5, 1, 0, 1, 4, None),
1442- (48000, 0, 13, 2, 1, 2, 3, None),
1443- (
1444- 44100,
1445- 14,
1446- 6,
1447- 1,
1448- 1,
1449- 3,
1450- 2,
1451- Some((4, 2, 1, 1, &[32, 34, 37], &[32, 37], &[32, 37])),
1452- ),
1453- (96000, 2, 10, 0, 0, 1, 0, None),
1454- (88200, 3, 11, 3, 1, 1, 3, None),
1455- (
1456- 64000,
1457- 13,
1458- 11,
1459- 0,
1460- 1,
1461- 2,
1462- 3,
1463- Some((
1464- 16,
1465- 13,
1466- 7,
1467- 2,
1468- &[28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54],
1469- &[28, 30, 34, 38, 42, 46, 50, 54],
1470- &[28, 38, 54],
1471- )),
1472- ),
1473- (64000, 14, 0, 3, 1, 1, 1, None),
1474- (
1475- 24000,
1476- 11,
1477- 13,
1478- 2,
1479- 0,
1480- 1,
1481- 0,
1482- Some((
1483- 14,
1484- 14,
1485- 7,
1486- 1,
1487- &[23, 24, 26, 28, 30, 32, 34, 37, 40, 43, 46, 50, 54, 59, 64],
1488- &[23, 26, 30, 34, 40, 46, 54, 64],
1489- &[23, 64],
1490- )),
1491- ),
1492- (
1493- 32000,
1494- 11,
1495- 8,
1496- 0,
1497- 1,
1498- 1,
1499- 1,
1500- Some((
1501- 14,
1502- 13,
1503- 7,
1504- 1,
1505- &[24, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49],
1506- &[24, 25, 29, 33, 37, 41, 45, 49],
1507- &[24, 49],
1508- )),
1509- ),
1510- (
1511- 96000,
1512- 11,
1513- 6,
1514- 0,
1515- 0,
1516- 2,
1517- 2,
1518- Some((
1519- 8,
1520- 6,
1521- 3,
1522- 1,
1523- &[20, 21, 22, 23, 24, 25, 27],
1524- &[20, 22, 24, 27],
1525- &[20, 27],
1526- )),
1527- ),
1528- (44100, 0, 14, 2, 1, 1, 5, None),
1529- (
1530- 32000,
1531- 6,
1532- 2,
1533- 3,
1534- 0,
1535- 2,
1536- 2,
1537- Some((
1538- 8,
1539- 6,
1540- 3,
1541- 2,
1542- &[21, 23, 25, 27, 30, 33, 36],
1543- &[21, 25, 30, 36],
1544- &[21, 25, 36],
1545- )),
1546- ),
1547- (
1548- 32000,
1549- 3,
1550- 3,
1551- 3,
1552- 0,
1553- 3,
1554- 1,
1555- Some((
1556- 10,
1557- 9,
1558- 5,
1559- 4,
1560- &[16, 17, 19, 21, 23, 25, 27, 30, 34, 38],
1561- &[16, 17, 21, 25, 30, 38],
1562- &[16, 17, 21, 25, 38],
1563- )),
1564- ),
1565- (
1566- 44100,
1567- 14,
1568- 12,
1569- 0,
1570- 1,
1571- 1,
1572- 6,
1573- Some((
1574- 16,
1575- 10,
1576- 5,
1577- 1,
1578- &[39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59],
1579- &[39, 43, 47, 51, 55, 59],
1580- &[39, 59],
1581- )),
1582- ),
1583- (
1584- 24000,
1585- 11,
1586- 8,
1587- 0,
1588- 1,
1589- 1,
1590- 6,
1591- Some((
1592- 14,
1593- 8,
1594- 4,
1595- 1,
1596- &[33, 35, 37, 39, 41, 43, 45, 47, 49],
1597- &[33, 37, 41, 45, 49],
1598- &[33, 49],
1599- )),
1600- ),
1601- (
1602- 22050,
1603- 1,
1604- 9,
1605- 2,
1606- 0,
1607- 0,
1608- 3,
1609- Some((
1610- 20,
1611- 17,
1612- 9,
1613- 1,
1614- &[
1615- 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 52,
1616- ],
1617- &[16, 17, 19, 22, 26, 30, 34, 39, 45, 52],
1618- &[16, 52],
1619- )),
1620- ),
1621- (
1622- 16000,
1623- 3,
1624- 8,
1625- 0,
1626- 1,
1627- 2,
1628- 2,
1629- Some((
1630- 18,
1631- 16,
1632- 8,
1633- 3,
1634- &[
1635- 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 56,
1636- ],
1637- &[23, 27, 31, 35, 39, 43, 47, 51, 56],
1638- &[23, 31, 43, 56],
1639- )),
1640- ),
1641- (44100, 4, 1, 1, 0, 0, 3, None),
1642- (
1643- 64000,
1644- 10,
1645- 1,
1646- 1,
1647- 0,
1648- 2,
1649- 1,
1650- Some((4, 3, 2, 1, &[18, 19, 20, 22], &[18, 19, 22], &[18, 22])),
1651- ),
1652- (
1653- 24000,
1654- 1,
1655- 3,
1656- 0,
1657- 0,
1658- 0,
1659- 2,
1660- Some((
1661- 24,
1662- 22,
1663- 11,
1664- 1,
1665- &[
1666- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
1667- 35, 36, 38,
1668- ],
1669- &[15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 38],
1670- &[15, 38],
1671- )),
1672- ),
1673- (24000, 11, 1, 3, 1, 2, 5, None),
1674- (
1675- 24000,
1676- 5,
1677- 7,
1678- 1,
1679- 0,
1680- 2,
1681- 7,
1682- Some((
1683- 18,
1684- 11,
1685- 6,
1686- 2,
1687- &[24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
1688- &[24, 26, 30, 34, 38, 42, 46],
1689- &[24, 34, 46],
1690- )),
1691- ),
1692- (
1693- 88200,
1694- 14,
1695- 10,
1696- 0,
1697- 1,
1698- 3,
1699- 4,
1700- Some((
1701- 10,
1702- 6,
1703- 3,
1704- 1,
1705- &[34, 36, 38, 40, 42, 44, 46],
1706- &[34, 38, 42, 46],
1707- &[34, 46],
1708- )),
1709- ),
1710- (64000, 13, 12, 3, 1, 1, 6, None),
1711- (
1712- 96000,
1713- 11,
1714- 10,
1715- 2,
1716- 1,
1717- 0,
1718- 5,
1719- Some((
1720- 12,
1721- 7,
1722- 4,
1723- 1,
1724- &[25, 27, 29, 31, 33, 36, 40, 44],
1725- &[25, 27, 31, 36, 44],
1726- &[25, 44],
1727- )),
1728- ),
1729- (
1730- 44100,
1731- 3,
1732- 6,
1733- 0,
1734- 0,
1735- 3,
1736- 6,
1737- Some((
1738- 24,
1739- 18,
1740- 9,
1741- 3,
1742- &[
1743- 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37,
1744- ],
1745- &[18, 20, 22, 24, 26, 28, 30, 32, 34, 37],
1746- &[18, 24, 30, 37],
1747- )),
1748- ),
1749- (88200, 12, 13, 1, 1, 0, 0, None),
1750- (
1751- 96000,
1752- 12,
1753- 7,
1754- 1,
1755- 0,
1756- 2,
1757- 2,
1758- Some((
1759- 8,
1760- 6,
1761- 3,
1762- 1,
1763- &[22, 23, 24, 25, 27, 29, 31],
1764- &[22, 24, 27, 31],
1765- &[22, 31],
1766- )),
1767- ),
1768- (44100, 3, 4, 1, 1, 2, 5, None),
1769- (
1770- 88200,
1771- 5,
1772- 7,
1773- 0,
1774- 0,
1775- 1,
1776- 4,
1777- Some((
1778- 22,
1779- 18,
1780- 9,
1781- 1,
1782- &[
1783- 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33,
1784- ],
1785- &[14, 16, 18, 20, 22, 24, 26, 28, 30, 33],
1786- &[14, 33],
1787- )),
1788- ),
1789- (32000, 0, 11, 1, 0, 1, 3, None),
1790- (
1791- 48000,
1792- 4,
1793- 8,
1794- 2,
1795- 0,
1796- 0,
1797- 6,
1798- Some((
1799- 18,
1800- 12,
1801- 6,
1802- 1,
1803- &[18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 41],
1804- &[18, 20, 24, 28, 32, 36, 41],
1805- &[18, 41],
1806- )),
1807- ),
1808- (
1809- 88200,
1810- 14,
1811- 10,
1812- 3,
1813- 0,
1814- 3,
1815- 5,
1816- Some((6, 1, 1, 1, &[42, 46], &[42, 46], &[42, 46])),
1817- ),
1818- (
1819- 16000,
1820- 10,
1821- 2,
1822- 1,
1823- 1,
1824- 0,
1825- 1,
1826- Some((
1827- 12,
1828- 11,
1829- 6,
1830- 1,
1831- &[27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 47, 50],
1832- &[27, 28, 32, 36, 40, 44, 50],
1833- &[27, 50],
1834- )),
1835- ),
1836- (
1837- 32000,
1838- 10,
1839- 8,
1840- 0,
1841- 0,
1842- 2,
1843- 0,
1844- Some((
1845- 26,
1846- 26,
1847- 13,
1848- 2,
1849- &[
1850- 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
1851- 42, 43, 44, 45, 46, 47, 49,
1852- ],
1853- &[22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49],
1854- &[22, 34, 49],
1855- )),
1856- ),
1857- (64000, 6, 15, 1, 0, 0, 0, None),
1858- (
1859- 44100,
1860- 1,
1861- 8,
1862- 0,
1863- 1,
1864- 1,
1865- 3,
1866- Some((
1867- 16,
1868- 13,
1869- 7,
1870- 1,
1871- &[16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 43],
1872- &[16, 18, 22, 26, 30, 34, 38, 43],
1873- &[16, 43],
1874- )),
1875- ),
1876- (
1877- 96000,
1878- 12,
1879- 11,
1880- 3,
1881- 1,
1882- 2,
1883- 4,
1884- Some((
1885- 10,
1886- 6,
1887- 3,
1888- 2,
1889- &[28, 31, 34, 37, 40, 45, 50],
1890- &[28, 34, 40, 50],
1891- &[28, 34, 50],
1892- )),
1893- ),
1894- (96000, 3, 0, 3, 0, 2, 0, None),
1895- (
1896- 48000,
1897- 12,
1898- 4,
1899- 3,
1900- 1,
1901- 3,
1902- 0,
1903- Some((4, 4, 2, 1, &[22, 23, 25, 27, 29], &[22, 25, 29], &[22, 29])),
1904- ),
1905- (96000, 3, 11, 2, 1, 2, 2, None),
1906- (
1907- 44100,
1908- 2,
1909- 5,
1910- 0,
1911- 1,
1912- 3,
1913- 3,
1914- Some((
1915- 12,
1916- 9,
1917- 5,
1918- 3,
1919- &[16, 18, 20, 22, 24, 26, 28, 30, 32, 34],
1920- &[16, 18, 22, 26, 30, 34],
1921- &[16, 18, 26, 34],
1922- )),
1923- ),
1924- (44100, 11, 1, 1, 0, 3, 4, None),
1925- (88200, 6, 1, 2, 1, 0, 6, None),
1926- (
1927- 16000,
1928- 2,
1929- 5,
1930- 2,
1931- 1,
1932- 2,
1933- 3,
1934- Some((
1935- 14,
1936- 11,
1937- 6,
1938- 3,
1939- &[21, 23, 25, 27, 29, 31, 33, 36, 40, 44, 48, 53],
1940- &[21, 23, 27, 31, 36, 44, 53],
1941- &[21, 27, 36, 53],
1942- )),
1943- ),
1944- (
1945- 64000,
1946- 5,
1947- 1,
1948- 3,
1949- 1,
1950- 0,
1951- 3,
1952- Some((6, 3, 2, 1, &[16, 18, 20, 22], &[16, 18, 22], &[16, 22])),
1953- ),
1954- (
1955- 24000,
1956- 2,
1957- 0,
1958- 0,
1959- 1,
1960- 3,
1961- 5,
1962- Some((
1963- 10,
1964- 5,
1965- 3,
1966- 2,
1967- &[22, 24, 26, 28, 30, 32],
1968- &[22, 24, 28, 32],
1969- &[22, 24, 32],
1970- )),
1971- ),
1972- (
1973- 64000,
1974- 8,
1975- 8,
1976- 2,
1977- 0,
1978- 2,
1979- 3,
1980- Some((
1981- 14,
1982- 11,
1983- 6,
1984- 2,
1985- &[18, 19, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41],
1986- &[18, 19, 22, 26, 30, 35, 41],
1987- &[18, 26, 41],
1988- )),
1989- ),
1990- (
1991- 16000,
1992- 12,
1993- 12,
1994- 0,
1995- 0,
1996- 2,
1997- 7,
1998- Some((
1999- 34,
2000- 27,
2001- 14,
2002- 2,
2003- &[
2004- 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
2005- 55, 56, 57, 58, 59, 60, 61, 62,
2006- ],
2007- &[35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62],
2008- &[35, 48, 62],
2009- )),
2010- ),
2011- (88200, 14, 13, 2, 1, 1, 2, None),
2012- (
2013- 32000,
2014- 13,
2015- 11,
2016- 1,
2017- 1,
2018- 0,
2019- 7,
2020- Some((
2021- 14,
2022- 7,
2023- 4,
2024- 1,
2025- &[39, 41, 43, 46, 49, 52, 55, 58],
2026- &[39, 41, 46, 52, 58],
2027- &[39, 58],
2028- )),
2029- ),
2030- (44100, 15, 4, 2, 0, 2, 3, None),
2031- (
2032- 22050,
2033- 12,
2034- 6,
2035- 2,
2036- 0,
2037- 1,
2038- 4,
2039- Some((
2040- 10,
2041- 6,
2042- 3,
2043- 1,
2044- &[31, 33, 35, 37, 40, 43, 46],
2045- &[31, 35, 40, 46],
2046- &[31, 46],
2047- )),
2048- ),
2049- (
2050- 48000,
2051- 4,
2052- 6,
2053- 3,
2054- 0,
2055- 3,
2056- 7,
2057- Some((
2058- 12,
2059- 5,
2060- 3,
2061- 2,
2062- &[22, 24, 26, 29, 32, 35],
2063- &[22, 24, 29, 35],
2064- &[22, 24, 35],
2065- )),
2066- ),
2067- (64000, 3, 14, 1, 0, 0, 3, None),
2068- (
2069- 24000,
2070- 6,
2071- 0,
2072- 0,
2073- 0,
2074- 1,
2075- 0,
2076- Some((
2077- 14,
2078- 14,
2079- 7,
2080- 1,
2081- &[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32],
2082- &[18, 20, 22, 24, 26, 28, 30, 32],
2083- &[18, 32],
2084- )),
2085- ),
2086- (64000, 11, 15, 1, 1, 0, 3, None),
2087- (
2088- 32000,
2089- 3,
2090- 4,
2091- 0,
2092- 0,
2093- 2,
2094- 4,
2095- Some((
2096- 24,
2097- 20,
2098- 10,
2099- 2,
2100- &[
2101- 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
2102- 40,
2103- ],
2104- &[19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 40],
2105- &[19, 29, 40],
2106- )),
2107- ),
2108- (48000, 9, 13, 3, 1, 2, 1, None),
2109- (
2110- 24000,
2111- 13,
2112- 5,
2113- 1,
2114- 0,
2115- 3,
2116- 5,
2117- Some((8, 3, 2, 1, &[36, 38, 40, 42], &[36, 38, 42], &[36, 42])),
2118- ),
2119- (
2120- 16000,
2121- 6,
2122- 3,
2123- 3,
2124- 1,
2125- 2,
2126- 6,
2127- Some((10, 4, 2, 1, &[37, 40, 44, 47, 51], &[37, 44, 51], &[37, 51])),
2128- ),
2129- (
2130- 24000,
2131- 3,
2132- 11,
2133- 3,
2134- 0,
2135- 1,
2136- 2,
2137- Some((
2138- 16,
2139- 14,
2140- 7,
2141- 2,
2142- &[17, 19, 21, 23, 25, 27, 30, 33, 36, 39, 42, 46, 50, 54, 58],
2143- &[17, 21, 25, 30, 36, 42, 50, 58],
2144- &[17, 30, 58],
2145- )),
2146- ),
2147- (
2148- 24000,
2149- 14,
2150- 9,
2151- 0,
2152- 1,
2153- 3,
2154- 6,
2155- Some((
2156- 12,
2157- 6,
2158- 3,
2159- 1,
2160- &[40, 42, 44, 46, 48, 50, 52],
2161- &[40, 44, 48, 52],
2162- &[40, 52],
2163- )),
2164- ),
2165- (
2166- 32000,
2167- 3,
2168- 14,
2169- 3,
2170- 0,
2171- 0,
2172- 1,
2173- Some((
2174- 8,
2175- 7,
2176- 4,
2177- 1,
2178- &[16, 17, 19, 21, 23, 25, 27, 30],
2179- &[16, 17, 21, 25, 30],
2180- &[16, 30],
2181- )),
2182- ),
2183- (64000, 13, 1, 1, 1, 1, 6, None),
2184- (64000, 0, 11, 1, 0, 3, 5, None),
2185- (32000, 6, 12, 2, 0, 1, 2, None),
2186- (
2187- 22050,
2188- 4,
2189- 5,
2190- 1,
2191- 0,
2192- 2,
2193- 2,
2194- Some((
2195- 18,
2196- 16,
2197- 8,
2198- 3,
2199- &[
2200- 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44,
2201- ],
2202- &[18, 20, 22, 24, 28, 32, 36, 40, 44],
2203- &[18, 22, 32, 44],
2204- )),
2205- ),
2206- (
2207- 24000,
2208- 8,
2209- 8,
2210- 1,
2211- 1,
2212- 0,
2213- 4,
2214- Some((
2215- 14,
2216- 10,
2217- 5,
2218- 1,
2219- &[24, 26, 28, 30, 32, 34, 36, 38, 40, 44, 49],
2220- &[24, 28, 32, 36, 40, 49],
2221- &[24, 49],
2222- )),
2223- ),
2224- (
2225- 24000,
2226- 9,
2227- 9,
2228- 1,
2229- 0,
2230- 2,
2231- 6,
2232- Some((
2233- 16,
2234- 10,
2235- 5,
2236- 2,
2237- &[29, 31, 33, 35, 37, 39, 42, 44, 46, 49, 52],
2238- &[29, 33, 37, 42, 46, 52],
2239- &[29, 37, 52],
2240- )),
2241- ),
2242- (
2243- 64000,
2244- 9,
2245- 4,
2246- 3,
2247- 1,
2248- 2,
2249- 1,
2250- Some((
2251- 6,
2252- 5,
2253- 3,
2254- 1,
2255- &[17, 19, 21, 23, 25, 28],
2256- &[17, 19, 23, 28],
2257- &[17, 28],
2258- )),
2259- ),
2260- (
2261- 22050,
2262- 9,
2263- 9,
2264- 3,
2265- 1,
2266- 0,
2267- 0,
2268- Some((
2269- 10,
2270- 10,
2271- 5,
2272- 1,
2273- &[21, 23, 25, 27, 29, 32, 35, 38, 42, 47, 52],
2274- &[21, 25, 29, 35, 42, 52],
2275- &[21, 52],
2276- )),
2277- ),
2278- (
2279- 32000,
2280- 9,
2281- 5,
2282- 0,
2283- 0,
2284- 0,
2285- 5,
2286- Some((
2287- 20,
2288- 15,
2289- 8,
2290- 1,
2291- &[
2292- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42,
2293- ],
2294- &[26, 27, 29, 31, 33, 35, 37, 39, 42],
2295- &[26, 42],
2296- )),
2297- ),
2298- (64000, 14, 5, 3, 0, 0, 4, None),
2299- (
2300- 44100,
2301- 11,
2302- 4,
2303- 0,
2304- 0,
2305- 3,
2306- 3,
2307- Some((
2308- 10,
2309- 7,
2310- 4,
2311- 1,
2312- &[24, 25, 26, 27, 28, 29, 30, 31],
2313- &[24, 25, 27, 29, 31],
2314- &[24, 31],
2315- )),
2316- ),
2317- (
2318- 64000,
2319- 8,
2320- 15,
2321- 0,
2322- 1,
2323- 0,
2324- 1,
2325- Some((
2326- 16,
2327- 15,
2328- 8,
2329- 1,
2330- &[
2331- 16, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45,
2332- ],
2333- &[16, 17, 21, 25, 29, 33, 37, 41, 45],
2334- &[16, 45],
2335- )),
2336- ),
2337- (
2338- 64000,
2339- 15,
2340- 12,
2341- 0,
2342- 1,
2343- 2,
2344- 7,
2345- Some((
2346- 14,
2347- 7,
2348- 4,
2349- 1,
2350- &[44, 46, 48, 50, 52, 54, 56, 59],
2351- &[44, 46, 50, 54, 59],
2352- &[44, 59],
2353- )),
2354- ),
2355- (88200, 13, 0, 0, 0, 3, 3, None),
2356- (
2357- 64000,
2358- 3,
2359- 4,
2360- 3,
2361- 0,
2362- 2,
2363- 3,
2364- Some((
2365- 12,
2366- 9,
2367- 5,
2368- 2,
2369- &[13, 14, 15, 16, 18, 20, 22, 24, 26, 28],
2370- &[13, 14, 16, 20, 24, 28],
2371- &[13, 16, 28],
2372- )),
2373- ),
2374- (
2375- 16000,
2376- 3,
2377- 4,
2378- 1,
2379- 1,
2380- 2,
2381- 6,
2382- Some((
2383- 16,
2384- 10,
2385- 5,
2386- 2,
2387- &[26, 28, 30, 32, 34, 36, 38, 41, 44, 48, 52],
2388- &[26, 30, 34, 38, 44, 52],
2389- &[26, 34, 52],
2390- )),
2391- ),
2392- (32000, 0, 8, 2, 1, 1, 6, None),
2393- (96000, 1, 9, 3, 0, 2, 4, None),
2394- (48000, 7, 12, 3, 1, 0, 7, None),
2395- (
2396- 24000,
2397- 9,
2398- 13,
2399- 1,
2400- 1,
2401- 1,
2402- 6,
2403- Some((
2404- 18,
2405- 12,
2406- 6,
2407- 1,
2408- &[29, 31, 33, 35, 37, 39, 42, 45, 48, 52, 56, 60, 64],
2409- &[29, 33, 37, 42, 48, 56, 64],
2410- &[29, 64],
2411- )),
2412- ),
2413- (
2414- 16000,
2415- 10,
2416- 9,
2417- 3,
2418- 1,
2419- 2,
2420- 0,
2421- Some((
2422- 10,
2423- 10,
2424- 5,
2425- 2,
2426- &[26, 28, 30, 32, 35, 38, 41, 45, 49, 53, 57],
2427- &[26, 30, 35, 41, 49, 57],
2428- &[26, 35, 57],
2429- )),
2430- ),
2431- (64000, 14, 12, 3, 1, 0, 7, None),
2432- (32000, 10, 15, 3, 1, 2, 2, None),
2433- (64000, 9, 0, 3, 1, 1, 6, None),
2434- (96000, 4, 9, 2, 1, 1, 3, None),
2435- (
2436- 24000,
2437- 9,
2438- 12,
2439- 3,
2440- 1,
2441- 3,
2442- 0,
2443- Some((
2444- 12,
2445- 12,
2446- 6,
2447- 5,
2448- &[21, 23, 25, 27, 29, 32, 35, 38, 42, 46, 51, 56, 61],
2449- &[21, 25, 29, 35, 42, 51, 61],
2450- &[21, 25, 29, 35, 42, 61],
2451- )),
2452- ),
2453- (
2454- 22050,
2455- 3,
2456- 1,
2457- 1,
2458- 0,
2459- 3,
2460- 0,
2461- Some((
2462- 16,
2463- 16,
2464- 8,
2465- 4,
2466- &[
2467- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 31, 32, 34, 36,
2468- ],
2469- &[15, 17, 19, 21, 23, 26, 30, 32, 36],
2470- &[15, 19, 23, 30, 36],
2471- )),
2472- ),
2473- (32000, 8, 12, 0, 1, 2, 2, None),
2474- (64000, 2, 0, 1, 0, 0, 1, None),
2475- (
2476- 22050,
2477- 4,
2478- 4,
2479- 1,
2480- 0,
crates/ec-aac/src/sbr_bands/vectors/part1.rsdeleted+0 -1695
@@ -1,1695 +0,0 @@
1-//! Reference vectors for the `freq_tables` tests, second half of the 500 (test-only data).
2-
3-use super::Vector;
4-
5-pub(super) static PART: &[Vector] = &[
6- (
7- 16000,
8- 5,
9- 5,
10- 1,
11- 1,
12- 2,
13- 2,
14- Some((
15- 16,
16- 14,
17- 7,
18- 2,
19- &[23, 24, 25, 27, 29, 31, 33, 35, 37, 39, 42, 44, 47, 50, 53],
20- &[23, 25, 29, 33, 37, 42, 47, 53],
21- &[23, 33, 53],
22- )),
23- ),
24- (
25- 16000,
26- 10,
27- 7,
28- 2,
29- 1,
30- 2,
31- 4,
32- Some((
33- 10,
34- 6,
35- 3,
36- 1,
37- &[35, 38, 41, 44, 47, 51, 55],
38- &[35, 41, 47, 55],
39- &[35, 55],
40- )),
41- ),
42- (48000, 2, 12, 2, 1, 0, 4, None),
43- (88200, 0, 6, 1, 0, 1, 0, None),
44- (
45- 22050,
46- 3,
47- 4,
48- 1,
49- 0,
50- 1,
51- 7,
52- Some((
53- 18,
54- 11,
55- 6,
56- 1,
57- &[22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
58- &[22, 23, 26, 30, 34, 38, 42],
59- &[22, 42],
60- )),
61- ),
62- (
63- 64000,
64- 3,
65- 2,
66- 0,
67- 0,
68- 2,
69- 7,
70- Some((
71- 14,
72- 7,
73- 4,
74- 1,
75- &[17, 18, 19, 20, 21, 22, 23, 24],
76- &[17, 18, 20, 22, 24],
77- &[17, 24],
78- )),
79- ),
80- (
81- 16000,
82- 4,
83- 2,
84- 0,
85- 1,
86- 1,
87- 5,
88- Some((
89- 16,
90- 11,
91- 6,
92- 1,
93- &[28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50],
94- &[28, 30, 34, 38, 42, 46, 50],
95- &[28, 50],
96- )),
97- ),
98- (
99- 64000,
100- 6,
101- 2,
102- 3,
103- 0,
104- 2,
105- 2,
106- Some((
107- 8,
108- 6,
109- 3,
110- 1,
111- &[15, 16, 17, 18, 20, 22, 24],
112- &[15, 17, 20, 24],
113- &[15, 24],
114- )),
115- ),
116- (
117- 32000,
118- 11,
119- 4,
120- 1,
121- 1,
122- 2,
123- 6,
124- Some((10, 4, 2, 1, &[32, 34, 36, 38, 40], &[32, 36, 40], &[32, 40])),
125- ),
126- (88200, 2, 5, 2, 0, 2, 3, None),
127- (64000, 1, 7, 2, 1, 1, 2, None),
128- (
129- 24000,
130- 4,
131- 5,
132- 3,
133- 0,
134- 2,
135- 2,
136- Some((
137- 12,
138- 10,
139- 5,
140- 2,
141- &[19, 21, 23, 25, 27, 29, 32, 34, 36, 39, 42],
142- &[19, 23, 27, 32, 36, 42],
143- &[19, 27, 42],
144- )),
145- ),
146- (
147- 24000,
148- 10,
149- 5,
150- 3,
151- 0,
152- 1,
153- 4,
154- Some((8, 4, 2, 1, &[30, 33, 36, 39, 42], &[30, 36, 42], &[30, 42])),
155- ),
156- (
157- 16000,
158- 6,
159- 1,
160- 3,
161- 0,
162- 0,
163- 4,
164- Some((
165- 10,
166- 6,
167- 3,
168- 1,
169- &[30, 33, 36, 39, 42, 45, 49],
170- &[30, 36, 42, 49],
171- &[30, 49],
172- )),
173- ),
174- (88200, 8, 15, 1, 0, 2, 3, None),
175- (
176- 24000,
177- 2,
178- 3,
179- 1,
180- 0,
181- 2,
182- 7,
183- Some((
184- 18,
185- 11,
186- 6,
187- 2,
188- &[21, 22, 23, 24, 26, 28, 29, 30, 32, 34, 36, 38],
189- &[21, 22, 24, 28, 30, 34, 38],
190- &[21, 28, 38],
191- )),
192- ),
193- (48000, 1, 15, 1, 1, 1, 0, None),
194- (48000, 6, 11, 0, 1, 2, 5, None),
195- (
196- 48000,
197- 0,
198- 0,
199- 0,
200- 0,
201- 0,
202- 5,
203- Some((
204- 14,
205- 9,
206- 5,
207- 1,
208- &[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
209- &[12, 13, 15, 17, 19, 21],
210- &[12, 21],
211- )),
212- ),
213- (64000, 12, 0, 3, 0, 1, 5, None),
214- (88200, 4, 12, 0, 0, 0, 5, None),
215- (22050, 8, 0, 3, 0, 3, 6, None),
216- (24000, 0, 12, 0, 1, 2, 4, None),
217- (
218- 16000,
219- 4,
220- 15,
221- 0,
222- 0,
223- 0,
224- 5,
225- Some((
226- 40,
227- 35,
228- 18,
229- 1,
230- &[
231- 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
232- 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
233- ],
234- &[
235- 25, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
236- ],
237- &[25, 60],
238- )),
239- ),
240- (
241- 96000,
242- 14,
243- 10,
244- 2,
245- 1,
246- 2,
247- 1,
248- Some((
249- 8,
250- 7,
251- 4,
252- 1,
253- &[28, 30, 32, 34, 36, 38, 41, 44],
254- &[28, 30, 34, 38, 44],
255- &[28, 44],
256- )),
257- ),
258- (44100, 15, 10, 3, 0, 0, 6, None),
259- (
260- 22050,
261- 4,
262- 15,
263- 0,
264- 0,
265- 0,
266- 3,
267- Some((
268- 32,
269- 29,
270- 15,
271- 1,
272- &[
273- 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
274- 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
275- ],
276- &[
277- 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48,
278- ],
279- &[19, 48],
280- )),
281- ),
282- (
283- 48000,
284- 3,
285- 8,
286- 2,
287- 1,
288- 3,
289- 3,
290- Some((
291- 16,
292- 13,
293- 7,
294- 5,
295- &[14, 15, 16, 17, 18, 19, 20, 22, 24, 27, 30, 33, 37, 41],
296- &[14, 15, 17, 19, 22, 27, 33, 41],
297- &[14, 15, 17, 19, 27, 41],
298- )),
299- ),
300- (48000, 14, 13, 2, 1, 0, 6, None),
301- (
302- 96000,
303- 14,
304- 14,
305- 0,
306- 1,
307- 1,
308- 5,
309- Some((
310- 14,
311- 9,
312- 5,
313- 1,
314- &[36, 38, 40, 42, 44, 46, 48, 50, 52, 54],
315- &[36, 38, 42, 46, 50, 54],
316- &[36, 54],
317- )),
318- ),
319- (
320- 24000,
321- 13,
322- 12,
323- 1,
324- 0,
325- 2,
326- 0,
327- Some((
328- 14,
329- 14,
330- 7,
331- 2,
332- &[27, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48, 51, 54, 57, 61],
333- &[27, 30, 34, 38, 42, 48, 54, 61],
334- &[27, 38, 61],
335- )),
336- ),
337- (
338- 22050,
339- 10,
340- 4,
341- 1,
342- 1,
343- 3,
344- 5,
345- Some((
346- 12,
347- 7,
348- 4,
349- 2,
350- &[28, 30, 32, 34, 36, 38, 40, 42],
351- &[28, 30, 34, 38, 42],
352- &[28, 34, 42],
353- )),
354- ),
355- (
356- 16000,
357- 5,
358- 9,
359- 3,
360- 1,
361- 3,
362- 6,
363- Some((
364- 10,
365- 4,
366- 2,
367- 2,
368- &[35, 38, 42, 49, 57],
369- &[35, 42, 57],
370- &[35, 42, 57],
371- )),
372- ),
373- (
374- 16000,
375- 12,
376- 8,
377- 0,
378- 0,
379- 3,
380- 1,
381- Some((
382- 28,
383- 27,
384- 14,
385- 3,
386- &[
387- 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
388- 49, 50, 51, 52, 53, 54, 55, 56,
389- ],
390- &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56],
391- &[29, 36, 46, 56],
392- )),
393- ),
394- (
395- 88200,
396- 2,
397- 8,
398- 0,
399- 0,
400- 0,
401- 3,
402- Some((
403- 30,
404- 27,
405- 14,
406- 1,
407- &[
408- 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
409- 30, 31, 32, 33, 34, 35, 36, 37,
410- ],
411- &[10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37],
412- &[10, 37],
413- )),
414- ),
415- (
416- 16000,
417- 14,
418- 5,
419- 1,
420- 1,
421- 1,
422- 7,
423- Some((10, 3, 2, 1, &[44, 47, 50, 53], &[44, 47, 53], &[44, 53])),
424- ),
425- (
426- 96000,
427- 11,
428- 6,
429- 0,
430- 0,
431- 1,
432- 0,
433- Some((
434- 8,
435- 8,
436- 4,
437- 1,
438- &[18, 19, 20, 21, 22, 23, 24, 25, 27],
439- &[18, 20, 22, 24, 27],
440- &[18, 27],
441- )),
442- ),
443- (
444- 24000,
445- 15,
446- 12,
447- 3,
448- 1,
449- 3,
450- 5,
451- Some((8, 3, 2, 1, &[48, 52, 56, 61], &[48, 52, 61], &[48, 61])),
452- ),
453- (
454- 44100,
455- 6,
456- 6,
457- 1,
458- 1,
459- 0,
460- 6,
461- Some((
462- 14,
463- 8,
464- 4,
465- 1,
466- &[21, 22, 23, 24, 26, 28, 30, 33, 37],
467- &[21, 23, 26, 30, 37],
468- &[21, 37],
469- )),
470- ),
471- (
472- 64000,
473- 7,
474- 8,
475- 2,
476- 1,
477- 2,
478- 5,
479- Some((
480- 14,
481- 9,
482- 5,
483- 2,
484- &[19, 20, 22, 24, 26, 28, 31, 34, 37, 41],
485- &[19, 20, 24, 28, 34, 41],
486- &[19, 24, 41],
487- )),
488- ),
489- (
490- 48000,
491- 13,
492- 12,
493- 3,
494- 0,
495- 3,
496- 6,
497- Some((
498- 10,
499- 4,
500- 2,
501- 2,
502- &[40, 44, 48, 53, 59],
503- &[40, 48, 59],
504- &[40, 48, 59],
505- )),
506- ),
507- (
508- 64000,
509- 12,
510- 7,
511- 2,
512- 0,
513- 0,
514- 1,
515- Some((
516- 8,
517- 7,
518- 4,
519- 1,
520- &[22, 24, 26, 28, 30, 32, 34, 37],
521- &[22, 24, 28, 32, 37],
522- &[22, 37],
523- )),
524- ),
525- (
526- 16000,
527- 2,
528- 10,
529- 1,
530- 1,
531- 3,
532- 2,
533- Some((
534- 18,
535- 16,
536- 8,
537- 5,
538- &[
539- 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 49, 53, 58,
540- ],
541- &[20, 22, 24, 28, 32, 36, 42, 49, 58],
542- &[20, 22, 24, 32, 42, 58],
543- )),
544- ),
545- (
546- 48000,
547- 6,
548- 14,
549- 1,
550- 1,
551- 1,
552- 6,
553- Some((
554- 12,
555- 6,
556- 3,
557- 1,
558- &[20, 21, 22, 23, 24, 26, 28],
559- &[20, 22, 24, 28],
560- &[20, 28],
561- )),
562- ),
563- (
564- 16000,
565- 7,
566- 3,
567- 2,
568- 0,
569- 3,
570- 0,
571- Some((
572- 12,
573- 12,
574- 6,
575- 3,
576- &[23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 51],
577- &[23, 26, 30, 34, 39, 45, 51],
578- &[23, 30, 39, 51],
579- )),
580- ),
581- (
582- 88200,
583- 11,
584- 14,
585- 2,
586- 1,
587- 0,
588- 0,
589- Some((
590- 10,
591- 10,
592- 5,
593- 1,
594- &[18, 19, 20, 21, 23, 25, 27, 29, 31, 33, 36],
595- &[18, 20, 23, 27, 31, 36],
596- &[18, 36],
597- )),
598- ),
599- (
600- 16000,
601- 13,
602- 6,
603- 3,
604- 0,
605- 1,
606- 2,
607- Some((
608- 8,
609- 6,
610- 3,
611- 1,
612- &[34, 37, 40, 43, 46, 50, 54],
613- &[34, 40, 46, 54],
614- &[34, 54],
615- )),
616- ),
617- (
618- 32000,
619- 5,
620- 2,
621- 0,
622- 1,
623- 3,
624- 2,
625- Some((
626- 10,
627- 8,
628- 4,
629- 3,
630- &[20, 22, 24, 26, 28, 30, 32, 34, 36],
631- &[20, 24, 28, 32, 36],
632- &[20, 24, 28, 36],
633- )),
634- ),
635- (
636- 22050,
637- 8,
638- 6,
639- 2,
640- 0,
641- 2,
642- 7,
643- Some((
644- 12,
645- 5,
646- 3,
647- 1,
648- &[32, 34, 37, 40, 43, 46],
649- &[32, 34, 40, 46],
650- &[32, 46],
651- )),
652- ),
653- (
654- 32000,
655- 8,
656- 5,
657- 0,
658- 1,
659- 0,
660- 7,
661- Some((
662- 12,
663- 5,
664- 3,
665- 1,
666- &[32, 34, 36, 38, 40, 42],
667- &[32, 34, 38, 42],
668- &[32, 42],
669- )),
670- ),
671- (
672- 48000,
673- 3,
674- 1,
675- 0,
676- 0,
677- 3,
678- 7,
679- Some((
680- 12,
681- 5,
682- 3,
683- 1,
684- &[18, 19, 20, 21, 22, 23],
685- &[18, 19, 21, 23],
686- &[18, 23],
687- )),
688- ),
689- (
690- 22050,
691- 0,
692- 7,
693- 3,
694- 0,
695- 2,
696- 1,
697- Some((
698- 16,
699- 15,
700- 8,
701- 4,
702- &[
703- 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 31, 34, 37, 40, 44, 48,
704- ],
705- &[13, 14, 16, 20, 24, 28, 34, 40, 48],
706- &[13, 16, 24, 34, 48],
707- )),
708- ),
709- (
710- 32000,
711- 10,
712- 9,
713- 0,
714- 0,
715- 3,
716- 7,
717- Some((
718- 30,
719- 23,
720- 12,
721- 3,
722- &[
723- 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
724- 49, 50, 51, 52,
725- ],
726- &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52],
727- &[29, 36, 44, 52],
728- )),
729- ),
730- (
731- 32000,
732- 3,
733- 0,
734- 2,
735- 0,
736- 3,
737- 1,
738- Some((
739- 10,
740- 9,
741- 5,
742- 3,
743- &[16, 17, 18, 19, 21, 23, 25, 27, 29, 32],
744- &[16, 17, 19, 23, 27, 32],
745- &[16, 17, 23, 32],
746- )),
747- ),
748- (
749- 48000,
750- 3,
751- 3,
752- 0,
753- 1,
754- 2,
755- 7,
756- Some((8, 1, 1, 1, &[25, 27], &[25, 27], &[25, 27])),
757- ),
758- (
759- 22050,
760- 13,
761- 2,
762- 2,
763- 0,
764- 0,
765- 2,
766- Some((6, 4, 2, 1, &[29, 31, 33, 35, 38], &[29, 33, 38], &[29, 38])),
767- ),
768- (
769- 96000,
770- 2,
771- 6,
772- 0,
773- 0,
774- 0,
775- 3,
776- Some((
777- 20,
778- 17,
779- 9,
780- 1,
781- &[
782- 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
783- ],
784- &[10, 11, 13, 15, 17, 19, 21, 23, 25, 27],
785- &[10, 27],
786- )),
787- ),
788- (
789- 64000,
790- 14,
791- 9,
792- 1,
793- 0,
794- 3,
795- 3,
796- Some((
797- 10,
798- 7,
799- 4,
800- 2,
801- &[30, 32, 34, 36, 38, 40, 42, 45],
802- &[30, 32, 36, 40, 45],
803- &[30, 36, 45],
804- )),
805- ),
806- (
807- 16000,
808- 13,
809- 14,
810- 0,
811- 1,
812- 1,
813- 6,
814- Some((
815- 14,
816- 8,
817- 4,
818- 1,
819- &[41, 43, 45, 47, 49, 51, 53, 55, 58],
820- &[41, 45, 49, 53, 58],
821- &[41, 58],
822- )),
823- ),
824- (
825- 96000,
826- 9,
827- 5,
828- 3,
829- 1,
830- 2,
831- 5,
832- Some((6, 1, 1, 1, &[22, 24], &[22, 24], &[22, 24])),
833- ),
834- (
835- 16000,
836- 5,
837- 15,
838- 1,
839- 0,
840- 2,
841- 7,
842- Some((
843- 20,
844- 13,
845- 7,
846- 2,
847- &[31, 33, 35, 37, 39, 42, 44, 46, 48, 51, 54, 57, 60, 63],
848- &[31, 33, 37, 42, 46, 51, 57, 63],
849- &[31, 42, 63],
850- )),
851- ),
852- (
853- 24000,
854- 12,
855- 4,
856- 2,
857- 0,
858- 1,
859- 3,
860- Some((6, 3, 2, 1, &[31, 34, 37, 40], &[31, 34, 40], &[31, 40])),
861- ),
862- (
863- 32000,
864- 14,
865- 10,
866- 3,
867- 0,
868- 3,
869- 2,
870- Some((
871- 8,
872- 6,
873- 3,
874- 2,
875- &[34, 37, 40, 43, 47, 51, 55],
876- &[34, 40, 47, 55],
877- &[34, 40, 55],
878- )),
879- ),
880- (
881- 32000,
882- 11,
883- 2,
884- 3,
885- 0,
886- 3,
887- 2,
888- Some((6, 4, 2, 1, &[27, 29, 31, 33, 36], &[27, 31, 36], &[27, 36])),
889- ),
890- (
891- 32000,
892- 10,
893- 1,
894- 2,
895- 0,
896- 1,
897- 4,
898- Some((6, 2, 1, 1, &[29, 31, 34], &[29, 34], &[29, 34])),
899- ),
900- (
901- 16000,
902- 5,
903- 15,
904- 1,
905- 1,
906- 1,
907- 3,
908- Some((
909- 18,
910- 15,
911- 8,
912- 1,
913- &[
914- 24, 25, 27, 29, 31, 33, 35, 37, 39, 42, 45, 48, 51, 55, 59, 63,
915- ],
916- &[24, 25, 29, 33, 37, 42, 48, 55, 63],
917- &[24, 63],
918- )),
919- ),
920- (
921- 22050,
922- 10,
923- 3,
924- 1,
925- 0,
926- 1,
927- 7,
928- Some((10, 3, 2, 1, &[33, 35, 37, 40], &[33, 35, 40], &[33, 40])),
929- ),
930- (
931- 22050,
932- 10,
933- 4,
934- 0,
935- 1,
936- 2,
937- 2,
938- Some((
939- 10,
940- 8,
941- 4,
942- 1,
943- &[26, 28, 30, 32, 34, 36, 38, 40, 42],
944- &[26, 30, 34, 38, 42],
945- &[26, 42],
946- )),
947- ),
948- (
949- 24000,
950- 0,
951- 4,
952- 2,
953- 0,
954- 0,
955- 5,
956- Some((
957- 18,
958- 13,
959- 7,
960- 1,
961- &[16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 37, 40],
962- &[16, 17, 19, 22, 26, 30, 34, 40],
963- &[16, 40],
964- )),
965- ),
966- (
967- 24000,
968- 7,
969- 1,
970- 2,
971- 1,
972- 0,
973- 0,
974- Some((
975- 8,
976- 8,
977- 4,
978- 1,
979- &[19, 20, 21, 23, 25, 27, 29, 31, 34],
980- &[19, 21, 25, 29, 34],
981- &[19, 34],
982- )),
983- ),
984- (
985- 16000,
986- 11,
987- 15,
988- 1,
989- 1,
990- 1,
991- 6,
992- Some((
993- 14,
994- 8,
995- 4,
996- 1,
997- &[38, 40, 42, 45, 48, 51, 54, 59, 64],
998- &[38, 42, 48, 54, 64],
999- &[38, 64],
1000- )),
1001- ),
1002- (
1003- 44100,
1004- 1,
1005- 1,
1006- 0,
1007- 1,
1008- 0,
1009- 5,
1010- Some((8, 3, 2, 1, &[19, 21, 23, 25], &[19, 21, 25], &[19, 25])),
1011- ),
1012- (
1013- 64000,
1014- 15,
1015- 10,
1016- 3,
1017- 1,
1018- 2,
1019- 1,
1020- Some((
1021- 6,
1022- 5,
1023- 3,
1024- 1,
1025- &[32, 35, 38, 41, 45, 49],
1026- &[32, 35, 41, 49],
1027- &[32, 49],
1028- )),
1029- ),
1030- (
1031- 88200,
1032- 10,
1033- 14,
1034- 3,
1035- 0,
1036- 0,
1037- 4,
1038- Some((8, 4, 2, 1, &[23, 25, 27, 29, 32], &[23, 27, 32], &[23, 32])),
1039- ),
1040- (
1041- 32000,
1042- 10,
1043- 7,
1044- 3,
1045- 0,
1046- 3,
1047- 6,
1048- Some((8, 2, 1, 1, &[38, 42, 46], &[38, 46], &[38, 46])),
1049- ),
1050- (
1051- 22050,
1052- 12,
1053- 4,
1054- 0,
1055- 1,
1056- 1,
1057- 2,
1058- Some((
1059- 10,
1060- 8,
1061- 4,
1062- 1,
1063- &[26, 28, 30, 32, 34, 36, 38, 40, 42],
1064- &[26, 30, 34, 38, 42],
1065- &[26, 42],
1066- )),
1067- ),
1068- (
1069- 22050,
1070- 4,
1071- 11,
1072- 1,
1073- 0,
1074- 1,
1075- 2,
1076- Some((
1077- 22,
1078- 20,
1079- 10,
1080- 2,
1081- &[
1082- 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48, 51, 54,
1083- 58,
1084- ],
1085- &[18, 20, 22, 24, 28, 32, 36, 40, 45, 51, 58],
1086- &[18, 32, 58],
1087- )),
1088- ),
1089- (
1090- 24000,
1091- 1,
1092- 1,
1093- 2,
1094- 0,
1095- 2,
1096- 6,
1097- Some((
1098- 14,
1099- 8,
1100- 4,
1101- 2,
1102- &[19, 20, 22, 24, 26, 28, 30, 32, 34],
1103- &[19, 22, 26, 30, 34],
1104- &[19, 26, 34],
1105- )),
1106- ),
1107- (
1108- 32000,
1109- 4,
1110- 2,
1111- 1,
1112- 1,
1113- 1,
1114- 7,
1115- Some((
1116- 14,
1117- 7,
1118- 4,
1119- 1,
1120- &[23, 24, 26, 28, 30, 32, 34, 36],
1121- &[23, 24, 28, 32, 36],
1122- &[23, 36],
1123- )),
1124- ),
1125- (
1126- 22050,
1127- 9,
1128- 13,
1129- 2,
1130- 0,
1131- 3,
1132- 2,
1133- Some((
1134- 16,
1135- 14,
1136- 7,
1137- 4,
1138- &[24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 52, 56, 60, 64],
1139- &[24, 28, 32, 36, 42, 48, 56, 64],
1140- &[24, 28, 36, 48, 64],
1141- )),
1142- ),
1143- (
1144- 44100,
1145- 11,
1146- 9,
1147- 2,
1148- 1,
1149- 2,
1150- 1,
1151- Some((
1152- 12,
1153- 11,
1154- 6,
1155- 2,
1156- &[22, 23, 25, 27, 29, 31, 33, 35, 38, 41, 44, 47],
1157- &[22, 23, 27, 31, 35, 41, 47],
1158- &[22, 31, 47],
1159- )),
1160- ),
1161- (
1162- 96000,
1163- 7,
1164- 10,
1165- 2,
1166- 0,
1167- 1,
1168- 7,
1169- Some((
1170- 18,
1171- 11,
1172- 6,
1173- 1,
1174- &[19, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41, 44],
1175- &[19, 20, 24, 28, 32, 38, 44],
1176- &[19, 44],
1177- )),
1178- ),
1179- (
1180- 24000,
1181- 12,
1182- 8,
1183- 0,
1184- 1,
1185- 3,
1186- 4,
1187- Some((
1188- 12,
1189- 8,
1190- 4,
1191- 2,
1192- &[33, 35, 37, 39, 41, 43, 45, 47, 49],
1193- &[33, 37, 41, 45, 49],
1194- &[33, 41, 49],
1195- )),
1196- ),
1197- (
1198- 22050,
1199- 7,
1200- 7,
1201- 1,
1202- 1,
1203- 1,
1204- 6,
1205- Some((
1206- 16,
1207- 10,
1208- 5,
1209- 1,
1210- &[26, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48],
1211- &[26, 30, 34, 38, 42, 48],
1212- &[26, 48],
1213- )),
1214- ),
1215- (
1216- 48000,
1217- 13,
1218- 10,
1219- 0,
1220- 0,
1221- 3,
1222- 5,
1223- Some((
1224- 24,
1225- 19,
1226- 10,
1227- 2,
1228- &[
1229- 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49,
1230- ],
1231- &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49],
1232- &[29, 38, 49],
1233- )),
1234- ),
1235- (
1236- 32000,
1237- 15,
1238- 15,
1239- 0,
1240- 0,
1241- 1,
1242- 5,
1243- Some((
1244- 32,
1245- 27,
1246- 14,
1247- 1,
1248- &[
1249- 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
1250- 57, 58, 59, 60, 61, 62, 63, 64,
1251- ],
1252- &[37, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64],
1253- &[37, 64],
1254- )),
1255- ),
1256- (
1257- 96000,
1258- 11,
1259- 10,
1260- 1,
1261- 0,
1262- 3,
1263- 1,
1264- Some((
1265- 16,
1266- 15,
1267- 8,
1268- 4,
1269- &[
1270- 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44,
1271- ],
1272- &[19, 20, 22, 24, 28, 32, 36, 40, 44],
1273- &[19, 22, 28, 36, 44],
1274- )),
1275- ),
1276- (
1277- 22050,
1278- 12,
1279- 12,
1280- 0,
1281- 0,
1282- 0,
1283- 2,
1284- Some((
1285- 36,
1286- 34,
1287- 17,
1288- 1,
1289- &[
1290- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
1291- 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61,
1292- ],
1293- &[
1294- 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 61,
1295- ],
1296- &[26, 61],
1297- )),
1298- ),
1299- (
1300- 22050,
1301- 9,
1302- 14,
1303- 2,
1304- 1,
1305- 0,
1306- 6,
1307- Some((10, 4, 2, 1, &[32, 34, 36, 39, 42], &[32, 36, 42], &[32, 42])),
1308- ),
1309- (
1310- 96000,
1311- 2,
1312- 4,
1313- 0,
1314- 1,
1315- 0,
1316- 7,
1317- Some((8, 1, 1, 1, &[19, 21], &[19, 21], &[19, 21])),
1318- ),
1319- (
1320- 24000,
1321- 4,
1322- 3,
1323- 0,
1324- 1,
1325- 0,
1326- 4,
1327- Some((
1328- 12,
1329- 8,
1330- 4,
1331- 1,
1332- &[22, 24, 26, 28, 30, 32, 34, 36, 38],
1333- &[22, 26, 30, 34, 38],
1334- &[22, 38],
1335- )),
1336- ),
1337- (
1338- 48000,
1339- 10,
1340- 9,
1341- 3,
1342- 0,
1343- 2,
1344- 0,
1345- Some((
1346- 10,
1347- 10,
1348- 5,
1349- 3,
1350- &[18, 19, 21, 23, 25, 27, 30, 33, 36, 40, 45],
1351- &[18, 21, 25, 30, 36, 45],
1352- &[18, 21, 30, 45],
1353- )),
1354- ),
1355- (
1356- 16000,
1357- 11,
1358- 2,
1359- 2,
1360- 1,
1361- 3,
1362- 7,
1363- Some((8, 1, 1, 1, &[46, 50], &[46, 50], &[46, 50])),
1364- ),
1365- (
1366- 64000,
1367- 11,
1368- 8,
1369- 3,
1370- 1,
1371- 0,
1372- 7,
1373- Some((8, 1, 1, 1, &[37, 41], &[37, 41], &[37, 41])),
1374- ),
1375- (
1376- 22050,
1377- 1,
1378- 12,
1379- 2,
1380- 0,
1381- 1,
1382- 3,
1383- Some((
1384- 22,
1385- 19,
1386- 10,
1387- 2,
1388- &[
1389- 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 37, 40, 43, 46, 49, 53, 57, 61,
1390- ],
1391- &[16, 17, 19, 22, 26, 30, 34, 40, 46, 53, 61],
1392- &[16, 30, 61],
1393- )),
1394- ),
1395- (
1396- 32000,
1397- 5,
1398- 5,
1399- 1,
1400- 0,
1401- 2,
1402- 5,
1403- Some((
1404- 16,
1405- 11,
1406- 6,
1407- 2,
1408- &[22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
1409- &[22, 23, 26, 30, 34, 38, 42],
1410- &[22, 30, 42],
1411- )),
1412- ),
1413- (
1414- 48000,
1415- 9,
1416- 2,
1417- 3,
1418- 1,
1419- 2,
1420- 1,
1421- Some((4, 3, 2, 1, &[19, 21, 23, 25], &[19, 21, 25], &[19, 25])),
1422- ),
1423- (
1424- 16000,
1425- 13,
1426- 5,
1427- 1,
1428- 0,
1429- 0,
1430- 2,
1431- Some((
1432- 10,
1433- 8,
1434- 4,
1435- 1,
1436- &[33, 35, 37, 39, 41, 44, 47, 50, 53],
1437- &[33, 37, 41, 47, 53],
1438- &[33, 53],
1439- )),
1440- ),
1441- (
1442- 88200,
1443- 9,
1444- 14,
1445- 1,
1446- 1,
1447- 2,
1448- 7,
1449- Some((
1450- 12,
1451- 5,
1452- 3,
1453- 1,
1454- &[21, 22, 23, 24, 26, 28],
1455- &[21, 22, 24, 28],
1456- &[21, 28],
1457- )),
1458- ),
1459- (
1460- 88200,
1461- 10,
1462- 2,
1463- 1,
1464- 0,
1465- 3,
1466- 1,
1467- Some((2, 1, 1, 1, &[17, 19], &[17, 19], &[17, 19])),
1468- ),
1469- (
1470- 44100,
1471- 15,
1472- 15,
1473- 3,
1474- 0,
1475- 3,
1476- 1,
1477- Some((
1478- 8,
1479- 7,
1480- 4,
1481- 3,
1482- &[35, 38, 41, 45, 49, 54, 59, 64],
1483- &[35, 38, 45, 54, 64],
1484- &[35, 38, 45, 64],
1485- )),
1486- ),
1487- (
1488- 22050,
1489- 5,
1490- 7,
1491- 2,
1492- 1,
1493- 0,
1494- 6,
1495- Some((
1496- 14,
1497- 8,
1498- 4,
1499- 1,
1500- &[26, 28, 30, 32, 34, 37, 40, 44, 48],
1501- &[26, 30, 34, 40, 48],
1502- &[26, 48],
1503- )),
1504- ),
1505- (
1506- 48000,
1507- 15,
1508- 15,
1509- 1,
1510- 0,
1511- 3,
1512- 7,
1513- Some((
1514- 12,
1515- 5,
1516- 3,
1517- 1,
1518- &[47, 50, 53, 56, 60, 64],
1519- &[47, 50, 56, 64],
1520- &[47, 64],
1521- )),
1522- ),
1523- (
1524- 64000,
1525- 12,
1526- 6,
1527- 2,
1528- 1,
1529- 1,
1530- 0,
1531- Some((
1532- 6,
1533- 6,
1534- 3,
1535- 1,
1536- &[21, 23, 25, 27, 29, 31, 34],
1537- &[21, 25, 29, 34],
1538- &[21, 34],
1539- )),
1540- ),
1541- (
1542- 32000,
1543- 7,
1544- 2,
1545- 2,
1546- 0,
1547- 2,
1548- 4,
1549- Some((
1550- 10,
1551- 6,
1552- 3,
1553- 1,
1554- &[24, 26, 28, 30, 32, 34, 36],
1555- &[24, 28, 32, 36],
1556- &[24, 36],
1557- )),
1558- ),
1559- (
1560- 44100,
1561- 6,
1562- 1,
1563- 2,
1564- 0,
1565- 3,
1566- 1,
1567- Some((
1568- 8,
1569- 7,
1570- 4,
1571- 2,
1572- &[16, 17, 18, 19, 20, 21, 23, 25],
1573- &[16, 17, 19, 21, 25],
1574- &[16, 19, 25],
1575- )),
1576- ),
1577- (
1578- 32000,
1579- 9,
1580- 1,
1581- 2,
1582- 1,
1583- 2,
1584- 0,
1585- Some((
1586- 6,
1587- 6,
1588- 3,
1589- 1,
1590- &[21, 23, 25, 27, 29, 31, 34],
1591- &[21, 25, 29, 34],
1592- &[21, 34],
1593- )),
1594- ),
1595- (
1596- 64000,
1597- 9,
1598- 9,
1599- 2,
1600- 1,
1601- 1,
1602- 7,
1603- Some((
1604- 14,
1605- 7,
1606- 4,
1607- 1,
1608- &[26, 28, 30, 32, 35, 38, 41, 45],
1609- &[26, 28, 32, 38, 45],
1610- &[26, 45],
1611- )),
1612- ),
1613- (
1614- 16000,
1615- 14,
1616- 0,
1617- 1,
1618- 0,
1619- 0,
1620- 1,
1621- Some((
1622- 8,
1623- 7,
1624- 4,
1625- 1,
1626- &[32, 34, 36, 38, 40, 42, 45, 48],
1627- &[32, 34, 38, 42, 48],
1628- &[32, 48],
1629- )),
1630- ),
1631- (
1632- 44100,
1633- 5,
1634- 9,
1635- 3,
1636- 0,
1637- 0,
1638- 1,
1639- Some((
1640- 14,
1641- 13,
1642- 7,
1643- 1,
1644- &[15, 16, 18, 20, 22, 24, 26, 28, 30, 33, 36, 39, 43, 47],
1645- &[15, 16, 20, 24, 28, 33, 39, 47],
1646- &[15, 47],
1647- )),
1648- ),
1649- (
1650- 44100,
1651- 11,
1652- 11,
1653- 2,
1654- 1,
1655- 1,
1656- 2,
1657- Some((
1658- 12,
1659- 10,
1660- 5,
1661- 1,
1662- &[24, 26, 28, 30, 32, 34, 36, 39, 42, 48, 55],
1663- &[24, 28, 32, 36, 42, 55],
1664- &[24, 55],
1665- )),
1666- ),
1667- (
1668- 88200,
1669- 0,
1670- 15,
1671- 0,
1672- 1,
1673- 1,
1674- 2,
1675- Some((6, 4, 2, 1, &[7, 9, 11, 13, 15], &[7, 11, 15], &[7, 15])),
1676- ),
1677- (
1678- 44100,
1679- 5,
1680- 9,
1681- 1,
1682- 0,
1683- 1,
1684- 6,
1685- Some((
1686- 20,
1687- 14,
1688- 7,
1689- 1,
1690- &[20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 41, 44, 47],
1691- &[20, 22, 24, 28, 32, 36, 41, 47],
1692- &[20, 47],
1693- )),
1694- ),
1695-];
crates/ec-aac/src/sbr_chain.rsmodified+5 -264
@@ -13,168 +13,12 @@ use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
1313 use ec_core::BitReader;
1414 use ec_dsp::Complex;
1515 use std::collections::HashMap;
16-use std::sync::atomic::{AtomicUsize, Ordering};
17-
18-/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames
19-/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated).
20-fn debug_dump(
21- header: &crate::sbr_payload::SbrHeader,
22- tables: &crate::sbr_bands::BandTables,
23- ch: &SbrChannel,
24- ch_idx: usize,
25-) {
26- static COUNT: AtomicUsize = AtomicUsize::new(0);
27- let n = COUNT.fetch_add(1, Ordering::Relaxed);
28- if n >= 20 {
29- return;
30- }
31- eprintln!(
32- "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?} f_high={:?} patches={:?}",
33- header.amp_res,
34- tables.kx,
35- tables.k2,
36- tables.n_low,
37- tables.n_high,
38- tables.n_q,
39- ch.t_env,
40- ch.freq_res,
41- ch.t_noise,
42- tables.f_high,
43- crate::sbr_hf::build_patches(tables),
44- );
45- for (i, row) in ch.e_q.iter().enumerate() {
46- let (mn, mx) = row
47- .iter()
48- .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
49- eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
50- }
51- for (i, row) in ch.q_q.iter().enumerate() {
52- let (mn, mx) = row
53- .iter()
54- .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
55- eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
56- }
57-}
5816
5917 /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a
6018 /// 1024-sample core frame) are half as fine as the QMF slots SBR actually
6119 /// runs at (32 per frame): `RATE = 2` converts one to the other.
6220 const RATE: i64 = 2;
6321
64-/// Round-20 residual/side-info correlation: one row per (access unit,
65-/// channel) `apply_data` actually ran, giving `sbr_real_library.rs`'s
66-/// residual-energy grid a side-info table to correlate against without
67-/// re-parsing debug text. `frame` is a single counter shared by every
68-/// channel `apply_data` touches in one call, so it lines up 1:1 with the
69-/// AU-aligned (2048 output samples/AU for a plain 2x stream) blocks the
70-/// residual grid uses.
71-#[derive(Clone, Debug)]
72-pub struct SbrSideInfoRow {
73- pub frame: usize,
74- pub tag: u8,
75- pub ch: usize,
76- /// `"fresh"` for a frame `apply` reached (a real payload this AU),
77- /// `"hold"` for one `apply_last` reached (no fresh payload, reusing the
78- /// last parsed frame's data per §4.6.18).
79- pub source: &'static str,
80- pub coupling: bool,
81- pub amp_res: u8,
82- /// Band-index domain (same units `f_high`/`f_noise` and the residual
83- /// grid's FFT-bucket index share, per `per_band_correlation`'s
84- /// `band_hz = rate/256` measurement) the crossover and high-res/noise
85- /// band boundaries below live in.
86- pub kx: i64,
87- pub k2: i64,
88- pub f_high: Vec<i64>,
89- pub f_noise: Vec<i64>,
90- pub t_env: Vec<i64>,
91- pub freq_res: Vec<u8>,
92- pub invf_mode: Vec<u8>,
93- pub add_harmonic: Option<Vec<u8>>,
94- pub e_q_means: Vec<f64>,
95- pub q_q_means: Vec<f64>,
96- /// Header fields held for the frame's duration (§4.6.18.3.2), added for
97- /// the FMJ-vs-reeln feature-table hunt: `sbr_header()`'s own coding
98- /// choices, not per-envelope grid data.
99- pub freq_scale: u8,
100- pub alter_scale: u8,
101- pub noise_bands: u8,
102- pub limiter_bands: u8,
103- pub limiter_gains: u8,
104- pub interpol_freq: u8,
105- pub smoothing_mode: u8,
106- pub start_freq: u8,
107- pub stop_freq: u8,
108- pub xover_band: u8,
109- /// `t_noise.len() - 1`, i.e. `numNoiseFloors` this frame.
110- pub num_noise: usize,
111- /// One entry per HF patch, each the patch's band count (from
112- /// `sbr_hf::build_patches`), so patch geometry is visible per frame.
113- pub patch_lengths: Vec<usize>,
114- pub df_env: Vec<u8>,
115- pub df_noise: Vec<u8>,
116-}
117-
118-static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> =
119- std::sync::OnceLock::new();
120-static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0);
121-
122-/// Diagnostic-only counter: how many `apply_data` calls process-wide ran
123-/// with `source == "hold"` (an AU whose FIL carried no fresh SBR payload,
124-/// falling back to `apply_last`'s reuse of the last parsed frame). Read via
125-/// [`hold_call_count`]; not gated by an env var since incrementing an atomic
126-/// is unconditionally cheap, unlike the `EC_AAC_SBR_*_DEBUG` prints nearby.
127-static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0);
128-
129-/// Total `apply_data` calls process-wide where the SBR payload was reused
130-/// from a prior frame (`apply_last`) rather than freshly parsed this AU --
131-/// diagnostic instrument for `sbr441_family_sample_drift_probe`.
132-pub fn hold_call_count() -> usize {
133- HOLD_CALLS.load(Ordering::Relaxed)
134-}
135-
136-fn sideinfo_enabled() -> bool {
137- crate::knobs::sbr_sideinfo_debug()
138-}
139-
140-/// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named
141-/// pipeline stage, gated by `EC_AAC_SBR_QMFDUMP`. `start_band` is the
142-/// absolute QMF band index `rows[0]` represents (`0` for the core analysis
143-/// matrix, `kx` for the HF matrix), so every printed band index lines up
144-/// with `build_patches`' target-band units without the reader having to
145-/// offset anything by hand.
146-fn qmfdump_enabled() -> bool {
147- std::env::var("EC_AAC_SBR_QMFDUMP").is_ok()
148-}
149-
150-fn qmfdump_energies(stage: &str, start_band: usize, rows: &[Vec<Complex<f64>>]) {
151- let means: Vec<f64> = rows
152- .iter()
153- .map(|series| {
154- if series.is_empty() {
155- 0.0
156- } else {
157- series
158- .iter()
159- .map(|c| c.re * c.re + c.im * c.im)
160- .sum::<f64>()
161- / series.len() as f64
162- }
163- })
164- .collect();
165- eprintln!("QMFDUMP stage={stage} start_band={start_band} means={means:?}");
166-}
167-
168-/// Drains nothing -- returns a clone of every row logged so far this
169-/// process, in call order. Empty unless `EC_AAC_SBR_SIDEINFO_DEBUG` was set
170-/// before decoding.
171-pub fn sbr_sideinfo_log() -> Vec<SbrSideInfoRow> {
172- let Some(log) = SIDEINFO_LOG.get() else {
173- return Vec::new();
174- };
175- log.lock().map(|l| l.clone()).unwrap_or_default()
176-}
177-
17822 /// Per-channel DSP state an SBR element's reconstruction carries across
17923 /// frames: the QMF filterbank pair, the HF generator's LPC history and
18024 /// chirp factors, and the noise-floor generator.
@@ -469,7 +313,7 @@ impl SbrChain {
469313 if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
470314 elem.last_data = Some(data.clone());
471315 }
472- self.apply_data(tag, is_cpe, data, planes, "fresh")
316+ self.apply_data(tag, is_cpe, data, planes)
473317 }
474318
475319 /// Re-runs the chain for `tag` using the last successfully parsed
@@ -491,7 +335,7 @@ impl SbrChain {
491335 self.apply_low_only(tag, is_cpe, planes);
492336 return Ok(());
493337 };
494- self.apply_data(tag, is_cpe, &data, planes, "hold")
338+ self.apply_data(tag, is_cpe, &data, planes)
495339 }
496340
497341 fn apply_data(
@@ -500,11 +344,7 @@ impl SbrChain {
500344 is_cpe: bool,
501345 data: &SbrData,
502346 planes: &mut [Vec<f32>],
503- source: &'static str,
504347 ) -> crate::Result<()> {
505- if source == "hold" {
506- HOLD_CALLS.fetch_add(1, Ordering::Relaxed);
507- }
508348 let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS };
509349 let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
510350 return Ok(());
@@ -518,12 +358,6 @@ impl SbrChain {
518358 return Ok(());
519359 };
520360 let coupling = data.coupling;
521- let sideinfo_on = sideinfo_enabled();
522- let au_frame = if sideinfo_on {
523- SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed)
524- } else {
525- 0
526- };
527361 // PS: the mono channel is synthesized twice, through its own state and
528362 // through channel 1's (the right output), so both stay in step.
529363 let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some();
@@ -542,20 +376,6 @@ impl SbrChain {
542376 if num_slots == 0 {
543377 continue;
544378 }
545- if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
546- static N: AtomicUsize = AtomicUsize::new(0);
547- let n = N.fetch_add(1, Ordering::Relaxed);
548- if n < 40 {
549- let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
550- / plane.len().max(1) as f64)
551- .sqrt();
552- eprintln!(
553- "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
554- plane.len(),
555- &plane[..8.min(plane.len())]
556- );
557- }
558- }
559379 let state = &mut elem.channels[ch];
560380 let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
561381 let mut raw = Vec::with_capacity(num_slots);
@@ -584,63 +404,6 @@ impl SbrChain {
584404 }
585405
586406 let sbr_ch = &data.channels[ch];
587- if std::env::var("EC_AAC_SBR_DEBUG").is_ok() {
588- eprintln!("SBRDBG coupling={}", data.coupling);
589- debug_dump(&header, &tables, sbr_ch, ch);
590- }
591- if sideinfo_on {
592- let mean = |rows: &[Vec<i32>]| -> Vec<f64> {
593- rows.iter()
594- .map(|r| {
595- if r.is_empty() {
596- 0.0
597- } else {
598- r.iter().map(|&v| f64::from(v)).sum::<f64>() / r.len() as f64
599- }
600- })
601- .collect()
602- };
603- let row = SbrSideInfoRow {
604- frame: au_frame,
605- tag,
606- ch,
607- source,
608- coupling,
609- amp_res: header.amp_res,
610- kx: tables.kx,
611- k2: tables.k2,
612- f_high: tables.f_high.clone(),
613- f_noise: tables.f_noise.clone(),
614- t_env: sbr_ch.t_env.clone(),
615- freq_res: sbr_ch.freq_res.clone(),
616- invf_mode: sbr_ch.invf_mode.clone(),
617- add_harmonic: sbr_ch.add_harmonic.clone(),
618- e_q_means: mean(&sbr_ch.e_q),
619- q_q_means: mean(&sbr_ch.q_q),
620- freq_scale: header.freq_scale,
621- alter_scale: header.alter_scale,
622- noise_bands: header.noise_bands,
623- limiter_bands: header.limiter_bands,
624- limiter_gains: header.limiter_gains,
625- interpol_freq: header.interpol_freq,
626- smoothing_mode: header.smoothing_mode,
627- start_freq: header.start_freq,
628- stop_freq: header.stop_freq,
629- xover_band: header.xover_band,
630- num_noise: sbr_ch.t_noise.len().saturating_sub(1),
631- patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(),
632- df_env: sbr_ch.df_env.clone(),
633- df_noise: sbr_ch.df_noise.clone(),
634- };
635- let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
636- if let Ok(mut l) = log.lock() {
637- l.push(row);
638- }
639- }
640- let qmfdump_on = qmfdump_enabled();
641- if qmfdump_on {
642- qmfdump_energies("analysis", 0, &low_cur);
643- }
644407 let hf = sbr_hf::generate(
645408 &low_cur,
646409 &tables,
@@ -648,9 +411,6 @@ impl SbrChain {
648411 &mut state.chirp,
649412 &mut state.hf_hist,
650413 );
651- if qmfdump_on {
652- qmfdump_energies("post_patch", tables.kx as usize, &hf);
653- }
654414 let (env_energy, noise_energy) =
655415 sbr_env::dequantize_frame(&data.channels, ch, coupling);
656416 // sbr_env::adjust works in QMF-slot units; the parsed borders
@@ -718,9 +478,6 @@ impl SbrChain {
718478 d.truncate(num_slots);
719479 d
720480 };
721- if qmfdump_on {
722- qmfdump_energies("post_adjust", tables.kx as usize, &hf);
723- }
724481
725482 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
726483 let k2 = (tables.k2 as usize).min(band_limit);
@@ -728,11 +485,9 @@ impl SbrChain {
728485 for slot in 0..num_slots {
729486 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
730487 v[0..kx].copy_from_slice(&raw[slot][0..kx]);
731- if !crate::knobs::sbr_hf_bypass() {
732- for b in kx..k2 {
733- if b - kx < hf.len() {
734- v[b] = hf[b - kx][slot];
735- }
488+ for b in kx..k2 {
489+ if b - kx < hf.len() {
490+ v[b] = hf[b - kx][slot];
736491 }
737492 }
738493 vs.push(v);
@@ -760,20 +515,6 @@ impl SbrChain {
760515 }
761516 _ => synth_slots(&mut state.synthesis, &vs),
762517 };
763- if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
764- static N: AtomicUsize = AtomicUsize::new(0);
765- let n = N.fetch_add(1, Ordering::Relaxed);
766- if n < 40 {
767- let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
768- / out.len().max(1) as f64)
769- .sqrt();
770- eprintln!(
771- "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
772- out.len(),
773- &out[..8.min(out.len())]
774- );
775- }
776- }
777518 if ps_planes.is_none() {
778519 *plane = out;
779520 }
crates/ec-aac/src/sbr_env.rsmodified+2 -74
@@ -168,29 +168,6 @@ impl Default for AdjustState {
168168 }
169169 }
170170
171-fn noise_fraction_debug() -> bool {
172- crate::knobs::sbr_noise_fraction()
173-}
174-
175-type NoiseFractionRows = Vec<(usize, f64, f64, f64)>;
176-
177-static NOISE_FRACTION: std::sync::OnceLock<std::sync::Mutex<NoiseFractionRows>> =
178- std::sync::OnceLock::new();
179-
180-/// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band,
181-/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots, Σ |Y|²
182-/// post-adjust)` -- the last column against the first two's sum is the
183-/// per-subband realised/target energy ratio.
184-pub fn noise_fraction_table() -> Vec<(usize, f64, f64, f64)> {
185- let mut out: Vec<(usize, f64, f64, f64)> = NOISE_FRACTION
186- .get()
187- .and_then(|m| m.lock().ok())
188- .map(|g| g.clone())
189- .unwrap_or_default();
190- out.sort_by_key(|e| e.0);
191- out
192-}
193-
194171 /// Adjusts `hf` (`[m][slot]`, `m = k - kx`) in place: envelope gains,
195172 /// noise floor and added sinusoids per §4.6.18.7.3-7.6. `ch.t_env`/`t_noise`
196173 /// are in QMF slots (already ×2). `reset` mirrors the spec's header-reset
@@ -222,14 +199,7 @@ pub fn adjust(
222199 state.g_hist.clear();
223200 state.q_hist.clear();
224201 }
225- let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() {
226- LIMITER_FACTOR[3]
227- } else {
228- LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]
229- };
230- let zero_noise = crate::knobs::sbr_noise_zero();
231- let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok();
232- let track_fraction = noise_fraction_debug();
202+ let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)];
233203 let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 };
234204 let l_a = ch.l_a;
235205 let l_a_prev: i64 = if state.la_prev_at_end { 0 } else { -1 };
@@ -340,13 +310,9 @@ pub fn adjust(
340310 let sum_orig: f64 = (lo..hi).map(|m| e_orig[m]).sum();
341311 let sum_curr: f64 = (lo..hi).map(|m| e_curr[m]).sum();
342312 let g_max = (limiter_max * ((EPS + sum_orig) / (EPS + sum_curr)).sqrt()).min(GAIN_MAX_CLIP);
343- let mut capped = 0usize;
344313 for m in lo..hi {
345314 let q_max = q_m[e][m] * g_max / gain[e][m];
346315 q_m[e][m] = q_m[e][m].min(q_max);
347- if gain[e][m] > g_max {
348- capped += 1;
349- }
350316 gain[e][m] = gain[e][m].min(g_max);
351317 }
352318 let sum_act: f64 = (lo..hi)
@@ -362,32 +328,6 @@ pub fn adjust(
362328 q_m[e][m] *= boost;
363329 s_m[e][m] *= boost;
364330 }
365- if limdump {
366- eprintln!(
367- "LIMDUMP ei={e} band=[{},{}) limiter_bands={} j={j}/{n_lim} \
368- E_orig_mapped={sum_orig:.6e} E_curr={sum_curr:.6e} G_max={g_max:.6} \
369- capped_cells={capped}/{} E_actual={sum_act:.6e} G_boost={boost:.6}",
370- limiter_table[j],
371- limiter_table[j + 1],
372- header.limiter_bands,
373- hi - lo,
374- );
375- }
376- }
377- if track_fraction {
378- let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
379- if let Ok(mut t) = tab.lock() {
380- for m in 0..m_max {
381- let sig = e_orig[m] / (1.0 + q_mapped[m]) * slots;
382- let noi = e_orig[m] * q_mapped[m] / (1.0 + q_mapped[m]) * slots;
383- if let Some(row) = t.iter_mut().find(|r| r.0 == m + kx) {
384- row.1 += sig;
385- row.2 += noi;
386- } else {
387- t.push((m + kx, sig, noi, 0.0));
388- }
389- }
390- }
391331 }
392332 }
393333 state.s_index_prev = s_index_prev;
@@ -451,25 +391,13 @@ pub fn adjust(
451391 noise_idx = (noise_idx + 1) & 0x1ff;
452392 if s_m[e][m] != 0.0 {
453393 y = y + Complex::new(s_m[e][m] * p_re, s_m[e][m] * p_im);
454- } else if !transient && !zero_noise {
394+ } else if !transient {
455395 let (vr, vi) = SBR_NOISE[noise_idx];
456396 y = y + Complex::new(q_filt[m] * vr, q_filt[m] * vi);
457397 }
458398 row[i] = y;
459399 p_im = -p_im;
460400 }
461- if track_fraction {
462- let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
463- if let Ok(mut t) = tab.lock() {
464- for m in 0..m_max {
465- if let (Some(row), Some(y)) =
466- (t.iter_mut().find(|r| r.0 == m + kx), hf[m].get(i))
467- {
468- row.3 += y.norm_sqr();
469- }
470- }
471- }
472- }
473401 state.index_noise = (state.index_noise + m_max) & 0x1ff;
474402 state.index_sine = (state.index_sine + 1) & 3;
475403 }
crates/ec-aac/src/sbr_hf.rsmodified+9 -126
@@ -57,64 +57,6 @@
5757 use crate::sbr_bands::BandTables;
5858 use ec_dsp::Complex;
5959
60-/// Characterizes (but, as of round-37, is deliberately NOT applied to) a QMF
61-/// bank convention gap `sbr_qmf`'s round-trip tuning never exercised:
62-/// replaying a source band's raw complex series into a *different* synthesis
63-/// band (exactly what patch copying does) lands the content at the "wrong"
64-/// absolute frequency by exactly one synthesis-band width whenever
65-/// `target_band - source_band` is odd, with the sign flipping every other
66-/// odd step -- i.e. a period-4 pattern in `target - source` (even
67-/// difference: no error; `+1 mod 4`: content lands one band flat; `+3 mod
68-/// 4`: one band sharp). `sbr_qmf::Synthesis`'s modulation kernel centres
69-/// band `k` at `(k+0.5) * pi/(2*SYNTHESIS_BANDS)` via a phase intercept that
70-/// is itself `(k+0.5) * pi/4` -- exactly the odd-stacked cosine-modulated-
71-/// bank convention the round-trip test tuned for same-band replay, where
72-/// this intercept cancels against the receiving band's own reconstruction.
73-///
74-/// Round-35 had `generate` counter-rotate the patched series by this amount
75-/// before it reaches `Synthesis`, and proved (in isolation, via a
76-/// stationary-tone FFT probe through the actual production call site --
77-/// `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`)
78-/// that doing so restores textbook-coherent absolute-frequency placement.
79-/// Round-36/37's real-file mechanical A/B (`EC_AAC_SBR_PARITY_SPLIT`)
80-/// showed applying that correction REGRESSES odd-gap coherence against the
81-/// reference decoder (ch0 0.1907->0.0714, ch1 0.2461->0.0741; a
82-/// sign-flipped variant and a half-rate variant both regress it too, to
83-/// 0.0757 and 0.1449 respectively on ch0) -- the reference apparently
84-/// reproduces this same "wrong" convention itself, so leaving the raw copy
85-/// unrotated is what actually matches it. This function is kept (and
86-/// pinned by its own unit tests) purely to document that convention as
87-/// intentional, not to be called from `generate`'s patch-copy site.
88-///
89-/// Round-46 raised a re-trial candidate: `EC_AAC_SBR_PARITY_SPLIT` (an 8-bin
90-/// STFT metric) had been suspected untrustworthy at this precision, and a
91-/// QMF-exact fit of the reference decoder's own HF content on patch
92-/// `(3,28,11)` (gap 25, `mod 4 == 1`) found a transfer with this function's
93-/// quarter-turn phase signature. Round-47 re-applied the rotation at
94-/// `generate`'s patch-copy site (env-gated, both signs) and re-judged with
95-/// `EC_AAC_SBR_QMF_WITNESS`'s own QMF-domain coherence table instead of the
96-/// STFT one -- the trustworthy instrument the re-trial was chartered to use.
97-/// Both signs made sim-vs-ours coherence on patch `(3,28,11)` WORSE, not
98-/// better (band28 0.2628 unrotated -> 0.0161 rotated -> 0.0282 flipped;
99-/// band38 0.0669 -> 0.0694 -> 0.1068), moving further from the reference's
100-/// 0.42-0.79 rather than toward it, refuting round-46's fit-based
101-/// prediction under the very instrument that was supposed to vindicate it.
102-/// (One sign did nudge whole-file full-band correlation up rather than
103-/// round-36's dip, but that's moot once the witness itself disagrees.) The
104-/// verdict stands as round-37 left it: `generate`'s patch-copy site keeps
105-/// the plain, unrotated copy.
106-/// Returns the signed number of `pi/2` quarter-turns per QMF slot that
107-/// *would* need to be applied to restore frequency-pure placement.
108-#[allow(dead_code)] // documentation of the characterized convention; tests call it
109-pub(crate) fn band_shift_correction(_target_band: usize, _source_band: usize) -> i64 {
110- // The fitted Kaiser bank's odd-stacked convention needed a per-slot
111- // quarter-turn correction here (see the doc above); the normative
112- // ISO/IEC 14496-3 4.6.18.4/4.6.18.8.2 QMF pair in `sbr_qmf` carries its
113- // own correct phase from the spec equations directly, so patching needs
114- // no extra rotation at this site.
115- 0
116-}
117-
11860 /// One copy-up patch: `width` consecutive QMF bands starting at
11961 /// `source_start` are written to `target_start..target_start+width`.
12062 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -283,40 +225,18 @@ impl ChirpState {
283225
284226 /// Advances the state one frame given this frame's `bs_invf_mode` per
285227 /// noise band, returning the smoothed bw to use for HF generation.
286- ///
287- /// (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_BW_SCALE`
288- /// scales the chirp target globally (clamped below 1.0) before
289- /// smoothing, to probe whether the chirp/inverse-filter strength is
290- /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips
291- /// the attack/release smoothing entirely (target used immediately);
292- /// `=swap` swaps which curve (0.75/0.25 vs 0.90625/0.09375) applies to
293- /// rising vs falling bw, to probe whether the asymmetry is backwards.
294228 pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] {
295- let scale = bw_scale_override();
296- let smooth = chirp_smooth_mode();
297229 for ((slot, prev), &mode) in self.bw.iter_mut().zip(&mut self.prev_mode).zip(invf_mode) {
298- let target = (bw_target(mode, *prev) * scale).min(0.999_999);
230+ let target = bw_target(mode, *prev).min(0.999_999);
299231 *prev = mode;
300- *slot = match smooth {
301- ChirpSmooth::None => target,
302- ChirpSmooth::Current => {
303- // 4.6.18.6.3 bwArray smoothing: both branches weight the
304- // NEW value (0.75 falling, 0.90625 rising). The rising
305- // branch previously had the operands swapped (0.09375
306- // of the new value), making every rise ~10x too slow.
307- if target < *slot {
308- 0.75 * target + 0.25 * *slot
309- } else {
310- 0.90625 * target + 0.09375 * *slot
311- }
312- }
313- ChirpSmooth::Swap => {
314- if target < *slot {
315- 0.90625 * target + 0.09375 * *slot
316- } else {
317- 0.75 * *slot + 0.25 * target
318- }
319- }
232+ // 4.6.18.6.3 bwArray smoothing: both branches weight the
233+ // NEW value (0.75 falling, 0.90625 rising). The rising
234+ // branch previously had the operands swapped (0.09375
235+ // of the new value), making every rise ~10x too slow.
236+ *slot = if target < *slot {
237+ 0.75 * target + 0.25 * *slot
238+ } else {
239+ 0.90625 * target + 0.09375 * *slot
320240 };
321241 // 4.6.18.6.3: a smoothed bw under 0.015 is forced to zero.
322242 if *slot < 0.015 {
@@ -327,32 +247,6 @@ impl ChirpState {
327247 }
328248 }
329249
330-/// `EC_AAC_SBR_BW_SCALE` global multiplier on the chirp target, clamped below 1.0
331-/// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a
332-/// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable.
333-fn bw_scale_override() -> f64 {
334- std::env::var("EC_AAC_SBR_BW_SCALE")
335- .ok()
336- .and_then(|s| s.parse::<f64>().ok())
337- .map(|s| s.max(0.0))
338- .unwrap_or(1.0)
339-}
340-
341-#[derive(Clone, Copy, PartialEq, Eq)]
342-enum ChirpSmooth {
343- None,
344- Current,
345- Swap,
346-}
347-
348-fn chirp_smooth_mode() -> ChirpSmooth {
349- match std::env::var("EC_AAC_SBR_CHIRP_SMOOTH").as_deref() {
350- Ok("none") => ChirpSmooth::None,
351- Ok("swap") => ChirpSmooth::Swap,
352- _ => ChirpSmooth::Current,
353- }
354-}
355-
356250 /// Order-2 linear-prediction coefficients per ISO 14496-3 4.6.18.6.2
357251 /// (covariance method, `phi(i,j) = sum_n x[n-i]*conj(x[n-j])` over
358252 /// `n = 2..x.len()`, index 0 of `x` is the oldest slot). Returns the spec's
@@ -464,13 +358,6 @@ pub fn generate(
464358 lpc2(&ext)
465359 };
466360 let g = bw[noise_band_of(target_band)];
467- // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched
468- // band per frame with the smoothed chirp bw actually applied,
469- // to compare against the QMF-domain fitted reference transfer
470- // (`hf_patch_transfer_fit` in the real-file test).
471- if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
472- eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
473- }
474361 // 4.6.18.6.3 feed-forward: X_high = X_low + bw*alpha0*X_low[l-1]
475362 // + bw^2*alpha1*X_low[l-2]. bw=0 is a plain copy, bw->1 is the
476363 // full inverse (whitening) filter. The all-pole recursion this
@@ -493,10 +380,6 @@ pub fn generate(
493380 };
494381 let dst = &mut out[target_band - kx];
495382 for (n, &x) in series.iter().enumerate() {
496- // Round-37 (Task 2): `band_shift_correction` is proven exact
497- // in isolation but a real-file A/B (`EC_AAC_SBR_PARITY_SPLIT`)
498- // shows applying it REGRESSES odd-gap coherence against the
499- // reference; `dst` stays the uncorrected band placement.
500383 dst[n] = x + c1 * x_prev1 + c2 * x_prev2;
501384 x_prev2 = x_prev1;
502385 x_prev1 = x;
crates/ec-aac/src/sbr_payload.rsmodified+0 -5
@@ -443,11 +443,6 @@ impl SbrParser {
443443 row[b] = (row[b - 1] + delta).clamp(0, cap);
444444 }
445445 }
446- if std::env::var("EC_AAC_SBR_ENV_DEBUG").is_ok() {
447- eprintln!(
448- "ENVDBG dt={dt} balance={balance} amp_res={amp_res} bands={bands} prev={prev:?} row={row:?}"
449- );
450- }
451446 Ok(row)
452447 }
453448
crates/ec-aac/src/sbr_qmf.rsmodified+0 -126
@@ -31,67 +31,6 @@ pub const ANALYSIS_BANDS: usize = 32;
3131 /// Synthesis channel count (twice the core's, spanning the doubled band).
3232 pub const SYNTHESIS_BANDS: usize = 64;
3333
34-/// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN`
35-/// real history samples in (newest inserted last, matching PCM order),
36-/// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new
37-/// samples.
38-struct QmfAnalysis64 {
39- hist: [f64; PROTO_LEN],
40- cos_tab: Vec<f64>,
41- sin_tab: Vec<f64>,
42-}
43-
44-impl QmfAnalysis64 {
45- fn new() -> QmfAnalysis64 {
46- let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
47- let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128];
48- for k in 0..SYNTHESIS_BANDS {
49- for n in 0..128 {
50- // X[k] = sum_n u[n] * exp(j*pi/128*(k+0.5)*(2n-1))
51- let theta = std::f64::consts::PI / 128.0
52- * (k as f64 + 0.5)
53- * (2.0 * n as f64 - 1.0);
54- cos_tab[k * 128 + n] = theta.cos();
55- sin_tab[k * 128 + n] = theta.sin();
56- }
57- }
58- QmfAnalysis64 {
59- hist: [0.0; PROTO_LEN],
60- cos_tab,
61- sin_tab,
62- }
63- }
64-
65- fn process_slot(&mut self, samples64: &[f64; SYNTHESIS_BANDS]) -> [Complex<f64>; SYNTHESIS_BANDS] {
66- for &s in samples64 {
67- self.hist.copy_within(0..PROTO_LEN - 1, 1);
68- self.hist[0] = s;
69- }
70- // Z[n] = x[n]*c[n], n=0..639; u[n] = sum_{j=0}^{4} Z[n+128j], n=0..127
71- let mut u = [0.0f64; 128];
72- for (n, uu) in u.iter_mut().enumerate() {
73- let mut acc = 0.0;
74- for j in 0..5 {
75- let idx = n + 128 * j;
76- acc += self.hist[idx] * QMF_WINDOW[idx];
77- }
78- *uu = acc;
79- }
80- let mut out = [Complex::new(0.0, 0.0); SYNTHESIS_BANDS];
81- for (k, slot) in out.iter_mut().enumerate() {
82- let row = k * 128;
83- let mut re = 0.0f64;
84- let mut im = 0.0f64;
85- for (n, &u_n) in u.iter().enumerate() {
86- re += u_n * self.cos_tab[row + n];
87- im += u_n * self.sin_tab[row + n];
88- }
89- *slot = Complex::new(re, im);
90- }
91- out
92- }
93-}
94-
9534 /// ISO/IEC 14496-3 4.6.18.4.1 32-band analysis: core PCM in (32
9635 /// samples/slot), 32 complex subbands out, the decimated prototype `c[2n]`
9736 /// over a 320-sample history and carrier `exp(j*pi/64*(k+0.5)*(2n-0.5))`
@@ -176,48 +115,6 @@ impl Default for Analysis {
176115 }
177116 }
178117
179-/// The same [`QmfAnalysis64`] core run directly on already-doubled-rate
180-/// samples: doubled-rate PCM in, complex subband slots out, one slot per
181-/// [`SYNTHESIS_BANDS`] input samples. The decoder itself never runs this --
182-/// it only ever synthesizes at this band count, from HF-generated subbands,
183-/// never analyzes a full-rate PCM signal back into them -- so this exists
184-/// for exact QMF-domain measurement only (round-46's third-witness
185-/// instrument): it lets a test read the reference decoder's and our own
186-/// already-decoded 44100Hz output straight into the same 64-band grid the
187-/// patch map's band indices are defined in, with no STFT-bin-width
188-/// approximation.
189-pub struct HfAnalysis {
190- core: QmfAnalysis64,
191-}
192-
193-impl HfAnalysis {
194- pub fn new() -> HfAnalysis {
195- HfAnalysis {
196- core: QmfAnalysis64::new(),
197- }
198- }
199-
200- /// Feeds exactly [`SYNTHESIS_BANDS`] new samples (oldest first, matching
201- /// PCM order) and returns the [`SYNTHESIS_BANDS`] complex subband
202- /// samples for this slot.
203- pub fn process_slot(
204- &mut self,
205- samples: &[f32; SYNTHESIS_BANDS],
206- ) -> [Complex<f64>; SYNTHESIS_BANDS] {
207- let mut x64 = [0.0f64; SYNTHESIS_BANDS];
208- for (d, &s) in x64.iter_mut().zip(samples.iter()) {
209- *d = s as f64;
210- }
211- self.core.process_slot(&x64)
212- }
213-}
214-
215-impl Default for HfAnalysis {
216- fn default() -> HfAnalysis {
217- HfAnalysis::new()
218- }
219-}
220-
221118 pub struct Synthesis {
222119 bands: usize,
223120 v: Vec<f64>,
@@ -474,29 +371,6 @@ mod tests {
474371
475372
476373
477- #[allow(dead_code)]
478- /// Peak-bin frequency (cycles/sample, in `0.0..0.5`) of a real signal's
479- /// dominant spectral line: FFT magnitude over the whole window, biggest
480- /// positive-frequency bin. `signal.len()` must be a power of two.
481- fn dominant_freq(signal: &[f64]) -> f64 {
482- let n = signal.len();
483- let mut fft = Fft::<f64>::new(n);
484- let mut spectrum: Vec<Complex<f64>> =
485- signal.iter().map(|&v| Complex::new(v, 0.0)).collect();
486- fft.forward(&mut spectrum);
487- let mut best_bin = 1usize;
488- let mut best_mag = -1.0f64;
489- for (k, c) in spectrum.iter().enumerate().take(n / 2).skip(1) {
490- let mag = c.norm_sqr();
491- if mag > best_mag {
492- best_mag = mag;
493- best_bin = k;
494- }
495- }
496- best_bin as f64 / n as f64
497- }
498-
499-
500374 /// TASK 1(b) (round-35 SBR-HF-patch conviction): the actual patch
501375 /// operation -- analyze a real tone at a known offset from source band
502376 /// `p`'s own centre via [`Analysis`], copy that complex series straight
crates/ec-aac/src/tables.rsmodified+63 -0
@@ -1607,3 +1607,66 @@ pub static TNS_MAX_BANDS_LONG: [usize; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42
16071607
16081608 /// The same limit for 128-line windows.
16091609 pub static TNS_MAX_BANDS_SHORT: [usize; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14];
1610+
1611+#[cfg(test)]
1612+mod tests {
1613+ use super::*;
1614+
1615+ /// The derived tables have to be complete prefix codes, and that is checkable
1616+ /// without any oracle: a Kraft sum of exactly 1 with the entry count the
1617+ /// standard prescribes leaves no room for a transcription slip.
1618+ #[test]
1619+ fn every_codebook_is_a_complete_prefix_code() {
1620+ let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
1621+ for (i, cb) in CODEBOOKS.iter().enumerate() {
1622+ assert_eq!(
1623+ cb.codes.len(),
1624+ expected[i],
1625+ "codebook {} entry count",
1626+ i + 1
1627+ );
1628+ let kraft: f64 = cb
1629+ .codes
1630+ .iter()
1631+ .map(|(l, _)| 2f64.powi(-i32::from(*l)))
1632+ .sum();
1633+ assert!(
1634+ (kraft - 1.0).abs() < 1e-12,
1635+ "codebook {} Kraft sum {kraft}",
1636+ i + 1
1637+ );
1638+ assert_prefix_free(cb.codes, &format!("codebook {}", i + 1));
1639+ }
1640+ let sf = SCALEFACTOR_CODES;
1641+ assert_eq!(sf.len(), 121, "scalefactor codebook entry count");
1642+ let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum();
1643+ assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}");
1644+ assert_prefix_free(sf, "scalefactor codebook");
1645+ }
1646+
1647+ fn assert_prefix_free(codes: &[(u8, u32)], what: &str) {
1648+ for (i, &(li, ci)) in codes.iter().enumerate() {
1649+ for &(lj, cj) in codes.iter().skip(i + 1) {
1650+ let short = li.min(lj);
1651+ if (ci >> (li - short)) == (cj >> (lj - short)) {
1652+ panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix");
1653+ }
1654+ }
1655+ }
1656+ }
1657+
1658+ /// Band tables must be monotone and land exactly on the window length.
1659+ #[test]
1660+ fn band_tables_span_the_window() {
1661+ for (i, swb) in SWB_LONG.iter().enumerate() {
1662+ assert_eq!(swb[0], 0, "long index {i}");
1663+ assert_eq!(*swb.last().unwrap(), 1024, "long index {i}");
1664+ assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}");
1665+ }
1666+ for (i, swb) in SWB_SHORT.iter().enumerate() {
1667+ assert_eq!(swb[0], 0, "short index {i}");
1668+ assert_eq!(*swb.last().unwrap(), 128, "short index {i}");
1669+ assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}");
1670+ }
1671+ }
1672+}
crates/ec-aac/tests/it/he_parity.rsmodified+55 -13
@@ -3,8 +3,7 @@
33 //! Fixtures live in `tests/data/he/` and are generated by `scripts/aac-tables/make-he-fixtures.sh`.
44 //! Each stream is written as ADTS (`.aac`) and MP4 (`.m4a`). The reference is FFmpeg's own decode
55 //! of the `.aac`, stored next to it as signed 16-bit little-endian PCM (`.s16`), in FFmpeg's channel
6-//! count and order. Nothing here runs FFmpeg, so the test needs neither FFmpeg nor the fdk-aac
7-//! library.
6+//! count and order. The FATE files are decoded by FFmpeg at test time.
87 //!
98 //! Acceptance: every channel of every container must correlate with the matching reference channel
109 //! at least `MIN_CORR` at the best lag in `-LAG_MAX..=LAG_MAX`, and the channel count and sample rate
@@ -126,6 +125,59 @@ fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
126125 (best.0, correlation(a, b))
127126 }
128127
128+const FATE_FILES: &[&str] = &[
129+ "open/fate/aac/al_sbr_cm_48_2.mp4",
130+ "open/fate/aac/al_sbr_cm_48_5.1.mp4",
131+ "open/fate/aac/al_sbr_ps_04_new.mp4",
132+ "open/fate/aac/al_sbr_ps_06_new.mp4",
133+ "open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4",
134+];
135+
136+fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
137+ let out = ec_testkit::ffmpeg()
138+ .args(["-v", "error", "-i"])
139+ .arg(path)
140+ .args(["-map", "0:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
141+ .output()
142+ .expect("ffmpeg runs");
143+ assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr));
144+ let samples: Vec<f32> = out
145+ .stdout
146+ .as_chunks::<4>()
147+ .0
148+ .iter()
149+ .map(|c| f32::from_le_bytes(*c))
150+ .collect();
151+ deinterleave(&samples, channels)
152+}
153+
154+fn check_channels(label: &str, ours: &[Vec<f32>], theirs: &[Vec<f32>], failures: &mut Vec<String>) {
155+ for ch in 0..ours.len() {
156+ let (lag, corr) = best_lag(&ours[ch], &theirs[ch]);
157+ println!(
158+ "he {label} ch{ch}: ours {} frames, ffmpeg {} frames, lag {lag}, corr {corr:.6}",
159+ ours[ch].len(),
160+ theirs[ch].len()
161+ );
162+ if corr < MIN_CORR {
163+ failures.push(format!("{label} ch{ch}: corr {corr:.6} < {MIN_CORR}"));
164+ }
165+ }
166+}
167+
168+#[test]
169+fn fate_sbr_fixtures_match_ffmpeg_per_channel() {
170+ let mut failures = Vec::new();
171+ for rel in FATE_FILES {
172+ let path = ec_testkit::fixture(rel);
173+ let (channels, _, samples) = decode_m4a(&path);
174+ let ours = deinterleave(&samples, usize::from(channels));
175+ let theirs = ffmpeg_decode(&path, usize::from(channels));
176+ check_channels(rel, &ours, &theirs, &mut failures);
177+ }
178+ assert!(failures.is_empty(), "HE-AAC does not match ffmpeg:\n{}", failures.join("\n"));
179+}
180+
129181 #[test]
130182 fn he_fixtures_match_ffmpeg_per_channel() {
131183 let mut failures = Vec::new();
@@ -145,17 +197,7 @@ fn he_fixtures_match_ffmpeg_per_channel() {
145197 continue;
146198 }
147199 let ours = deinterleave(&samples, fixture.channels);
148- for ch in 0..fixture.channels {
149- let (lag, corr) = best_lag(&ours[ch], &theirs[ch]);
150- println!(
151- "he {label} ch{ch}: ours {} frames, ffmpeg {} frames, lag {lag}, corr {corr:.6}",
152- ours[ch].len(),
153- theirs[ch].len()
154- );
155- if corr < MIN_CORR {
156- failures.push(format!("{label} ch{ch}: corr {corr:.6} < {MIN_CORR}"));
157- }
158- }
200+ check_channels(&label, &ours, &theirs, &mut failures);
159201 }
160202 }
161203 assert!(failures.is_empty(), "HE-AAC does not match ffmpeg:\n{}", failures.join("\n"));
crates/ec-aac/tests/it/main.rsmodified+1 -1
@@ -6,8 +6,8 @@ mod common;
66 mod he_parity;
77 mod implicit_ps;
88 mod implicit_sbr;
9-mod reelh_per_frame;
109 mod multichannel_parity;
1110 mod no_panic;
1211 mod ps_mp4;
12+mod oracle;
1313 mod ps_oracle;
crates/ec-aac/tests/it/multichannel_parity.rsmodified+0 -11
@@ -305,17 +305,6 @@ fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &m
305305 .map(|(k, row)| format!("{:.6}", row[k]))
306306 .collect();
307307 println!("{label} lag {lag:>5} corr [{}]", diag.join(", "));
308- if std::env::var_os("EC_AAC_PARITY_DEBUG").is_some() {
309- let rms = |p: &[f32]| (p.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / p.len() as f64).sqrt();
310- let fmt = |planes: &[Vec<f32>]| planes.iter().map(|p| format!("{:.4}", rms(p))).collect::<Vec<_>>().join(" ");
311- println!(" rms ours [{}]", fmt(&ours));
312- println!(" rms ffmpeg [{}]", fmt(&theirs));
313- for (k, row) in grid.iter().enumerate() {
314- let cells: Vec<String> = row.iter().map(|c| format!("{c:+.3}")).collect();
315- println!(" ours {k}: {}", cells.join(" "));
316- }
317- }
318-
319308 for (k, row) in grid.iter().enumerate() {
320309 let own = row[k];
321310 let (best_j, best_c) = row
crates/ec-aac/tests/oracle.rs → crates/ec-aac/tests/it/oracle.rsrenamed+0 -58
@@ -670,64 +670,6 @@ fn encoder_output_decodes_in_ffmpeg_without_warnings() {
670670 }
671671 }
672672
673-/// The derived tables have to be complete prefix codes, and that is checkable
674-/// without any oracle: a Kraft sum of exactly 1 with the entry count the
675-/// standard prescribes leaves no room for a transcription slip.
676-#[test]
677-fn every_codebook_is_a_complete_prefix_code() {
678- let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
679- for (i, cb) in ec_aac::tables::CODEBOOKS.iter().enumerate() {
680- assert_eq!(
681- cb.codes.len(),
682- expected[i],
683- "codebook {} entry count",
684- i + 1
685- );
686- let kraft: f64 = cb
687- .codes
688- .iter()
689- .map(|(l, _)| 2f64.powi(-i32::from(*l)))
690- .sum();
691- assert!(
692- (kraft - 1.0).abs() < 1e-12,
693- "codebook {} Kraft sum {kraft}",
694- i + 1
695- );
696- assert_prefix_free(cb.codes, &format!("codebook {}", i + 1));
697- }
698- let sf = ec_aac::tables::SCALEFACTOR_CODES;
699- assert_eq!(sf.len(), 121, "scalefactor codebook entry count");
700- let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum();
701- assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}");
702- assert_prefix_free(sf, "scalefactor codebook");
703-}
704-
705-fn assert_prefix_free(codes: &[(u8, u32)], what: &str) {
706- for (i, &(li, ci)) in codes.iter().enumerate() {
707- for &(lj, cj) in codes.iter().skip(i + 1) {
708- let short = li.min(lj);
709- if (ci >> (li - short)) == (cj >> (lj - short)) {
710- panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix");
711- }
712- }
713- }
714-}
715-
716-/// Band tables must be monotone and land exactly on the window length.
717-#[test]
718-fn band_tables_span_the_window() {
719- for (i, swb) in ec_aac::tables::SWB_LONG.iter().enumerate() {
720- assert_eq!(swb[0], 0, "long index {i}");
721- assert_eq!(*swb.last().unwrap(), 1024, "long index {i}");
722- assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}");
723- }
724- for (i, swb) in ec_aac::tables::SWB_SHORT.iter().enumerate() {
725- assert_eq!(swb[0], 0, "short index {i}");
726- assert_eq!(*swb.last().unwrap(), 128, "short index {i}");
727- assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}");
728- }
729-}
730-
731673 /// The AudioSpecificConfig this crate writes is byte-identical to the one the
732674 /// reference muxer puts in an `esds`, which is what "ffmpeg accepts our ASC"
733675 /// means in practice.
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::*;