diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 6160d5c9..61887a8a 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -59,52 +59,6 @@ impl WindowSequence { } } -/// One `raw_data_block` element's coding-tool usage, gated by -/// `EC_AAC_TOOL_SIDEINFO_DEBUG` -- mirrors `sbr_chain::SbrSideInfoRow`'s -/// pattern for the LC core, so a real file's PNS/M-S/IS/TNS mix can be read -/// back per AU without re-parsing debug text. -#[derive(Clone, Debug)] -pub struct ToolSideInfoRow { - pub au: usize, - pub tag: u8, - pub is_cpe: bool, - pub window_sequence: WindowSequence, - pub ms_bands: usize, - pub pns_bands: usize, - pub is_bands: usize, - pub tns_present: bool, -} - -static TOOL_SIDEINFO_LOG: std::sync::OnceLock>> = - std::sync::OnceLock::new(); -static TOOL_SIDEINFO_AU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -fn tool_sideinfo_enabled() -> bool { - crate::knobs::tool_sideinfo_debug() -} - -fn log_tool_sideinfo(row: ToolSideInfoRow) { - let log = TOOL_SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new())); - if let Ok(mut l) = log.lock() { - l.push(row); - } -} - -/// Bumps the shared AU counter once per `raw_data_block`, returning the value -/// that call's rows should carry. -fn next_tool_sideinfo_au() -> usize { - TOOL_SIDEINFO_AU.fetch_add(1, std::sync::atomic::Ordering::Relaxed) -} - -/// Every row logged so far this process, in call order. Empty unless -/// `EC_AAC_TOOL_SIDEINFO_DEBUG` was set before decoding. -pub fn tool_sideinfo_log() -> Vec { - let Some(log) = TOOL_SIDEINFO_LOG.get() else { - return Vec::new(); - }; - log.lock().map(|l| l.clone()).unwrap_or_default() -} - /// `ics_info` (§4.4.2.1) plus the grouping it implies. #[derive(Clone, Debug)] pub struct IcsInfo { @@ -845,12 +799,6 @@ impl BlockDecoder { // FIL's SBR payload would apply to, per §4.5.1: a fill_element // directly follows the element it decorates. let mut pending: Option<(u8, usize, usize, bool)> = None; - let dump_tools = tool_sideinfo_enabled(); - let au = if dump_tools { - next_tool_sideinfo_au() - } else { - 0 - }; let mut pns = false; // Speaker per plane so far; `named` drops to false at the first element a PCE does not name. let mut speakers: Vec = Vec::new(); @@ -869,9 +817,6 @@ impl BlockDecoder { let start = out.len(); let mut ch = [self.channel_stream(r, None)?]; pns |= has_pns(&ch[0]); - if dump_tools { - log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None)); - } self.finish(&mut ch, None, &mut out); if let (3, Some(sbr), Some(plane)) = (id, self.sbr.as_mut(), out.get_mut(start)) { sbr.bypass_plane(tag, plane); @@ -919,9 +864,6 @@ impl BlockDecoder { self.channel_stream(r, shared.as_ref())?, ]; pns |= pair.iter().any(has_pns); - if dump_tools { - log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask))); - } self.finish(&mut pair, Some(&mask), &mut out); named &= self.note_speakers(1, tag, 2, &mut speakers); pending = Some((tag, start, 2, true)); @@ -1193,43 +1135,12 @@ fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) { } } -/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics` -/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the -/// dump only needs whether the element used the tool at all). fn has_pns(ch: &Ics) -> bool { ch.cb .iter() .any(|group| group.contains(&NOISE_HCB)) } -fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow { - let mut ms_bands = 0; - let mut pns_bands = 0; - let mut is_bands = 0; - for g in 0..ch.ics.num_groups { - for sfb in 0..ch.ics.max_sfb { - if mask.is_some_and(|m| m.used(g, sfb)) { - ms_bands += 1; - } - match ch.cb[g][sfb] { - NOISE_HCB => pns_bands += 1, - INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1, - _ => {} - } - } - } - ToolSideInfoRow { - au, - tag, - is_cpe, - window_sequence: ch.ics.window_sequence, - ms_bands, - pns_bands, - is_bands, - tns_present: !ch.tns.filters.is_empty(), - } -} - fn is_intensity(cb: u8) -> bool { cb == INTENSITY_HCB || cb == INTENSITY_HCB2 } diff --git a/crates/ec-aac/src/knobs.rs b/crates/ec-aac/src/knobs.rs deleted file mode 100644 index 6bb16ed7..00000000 --- a/crates/ec-aac/src/knobs.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Debug switches the AAC/SBR decoder reads from the environment, with a -//! per-thread override that tests set instead of editing the process -//! environment (which is `unsafe` in Rust 2024). -//! -//! The decoder reads these on the thread that calls `decode`, so an override -//! set on a test's own thread covers exactly that test's decodes and nothing -//! running in parallel. With no override set, each reader answers from the -//! environment exactly as it always has, so manual runs with `EC_AAC_*` set -//! behave as before. - -use std::cell::Cell; -use std::thread::LocalKey; - -type Slot = Cell>; - -thread_local! { - static TOOL_SIDEINFO_DEBUG: Slot = const { Cell::new(None) }; - static SBR_SIDEINFO_DEBUG: Slot = const { Cell::new(None) }; - static SBR_HF_BYPASS: Slot = const { Cell::new(None) }; - static SBR_NOISE_ZERO: Slot = const { Cell::new(None) }; - static SBR_NOISE_FRACTION: Slot = const { Cell::new(None) }; -} - -/// The override on this thread if one is set, else whether `var` is set. -fn enabled(slot: &'static LocalKey, var: &str) -> bool { - slot.with(Cell::get) - .unwrap_or_else(|| std::env::var(var).is_ok()) -} - -fn force(slot: &'static LocalKey, on: Option) -> Override> { - let prev = slot.with(|c| c.replace(on)); - Override { slot, prev } -} - -/// Restores the value a knob had before [`set_tool_sideinfo_debug`] and its -/// siblings were called, when dropped. -#[doc(hidden)] -#[must_use = "the override ends as soon as this guard is dropped"] -pub struct Override { - slot: &'static LocalKey>, - prev: T, -} - -impl Drop for Override { - fn drop(&mut self) { - self.slot.with(|c| c.set(self.prev)); - } -} - -/// `EC_AAC_TOOL_SIDEINFO_DEBUG`. -pub(crate) fn tool_sideinfo_debug() -> bool { - enabled(&TOOL_SIDEINFO_DEBUG, "EC_AAC_TOOL_SIDEINFO_DEBUG") -} - -/// `EC_AAC_SBR_SIDEINFO_DEBUG`. -pub(crate) fn sbr_sideinfo_debug() -> bool { - enabled(&SBR_SIDEINFO_DEBUG, "EC_AAC_SBR_SIDEINFO_DEBUG") -} - -/// `EC_AAC_SBR_HF_BYPASS`. -pub(crate) fn sbr_hf_bypass() -> bool { - enabled(&SBR_HF_BYPASS, "EC_AAC_SBR_HF_BYPASS") -} - -/// `EC_AAC_SBR_NOISE_ZERO`. -pub(crate) fn sbr_noise_zero() -> bool { - enabled(&SBR_NOISE_ZERO, "EC_AAC_SBR_NOISE_ZERO") -} - -/// `EC_AAC_SBR_NOISE_FRACTION`. -pub(crate) fn sbr_noise_fraction() -> bool { - enabled(&SBR_NOISE_FRACTION, "EC_AAC_SBR_NOISE_FRACTION") -} - -/// Forces `EC_AAC_TOOL_SIDEINFO_DEBUG` on (`Some(true)`), off (`Some(false)`) -/// or back to the environment (`None`) on this thread, until the guard drops. -#[doc(hidden)] -pub fn set_tool_sideinfo_debug(on: Option) -> Override> { - force(&TOOL_SIDEINFO_DEBUG, on) -} - -/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_SIDEINFO_DEBUG`. -#[doc(hidden)] -pub fn set_sbr_sideinfo_debug(on: Option) -> Override> { - force(&SBR_SIDEINFO_DEBUG, on) -} - -/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_HF_BYPASS`. -#[doc(hidden)] -pub fn set_sbr_hf_bypass(on: Option) -> Override> { - force(&SBR_HF_BYPASS, on) -} - -/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_ZERO`. -#[doc(hidden)] -pub fn set_sbr_noise_zero(on: Option) -> Override> { - force(&SBR_NOISE_ZERO, on) -} - -/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_FRACTION`. -#[doc(hidden)] -pub fn set_sbr_noise_fraction(on: Option) -> Override> { - force(&SBR_NOISE_FRACTION, on) -} diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 2a96f88e..78197eea 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -42,8 +42,6 @@ mod ps_dsp; mod ps_huff; mod sbr_tables; pub mod tables; -#[doc(hidden)] -pub mod knobs; pub use config::{ AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig, @@ -51,16 +49,9 @@ pub use config::{ parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate, write_adts_header, write_audio_specific_config, }; -pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log}; +pub use decode::{FRAME_LEN, WindowSequence}; pub use ec_core::{Error, Result}; pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; -/// Diagnostic only (round-20): per-(access-unit, channel) side-info rows -/// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set. -pub use sbr_chain::{SbrSideInfoRow, hold_call_count, sbr_sideinfo_log}; -/// Diagnostic only (round-17 Task 1 conviction check): reads back the -/// per-absolute-QMF-band transmitted signal/noise energy sums -/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. -pub use sbr_env::noise_fraction_table; pub use tables::SAMPLE_RATES; use decode::BlockDecoder; diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index 0ba1c501..4fcf994f 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -13,168 +13,12 @@ use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; use ec_core::BitReader; use ec_dsp::Complex; use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; - -/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames -/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated). -fn debug_dump( - header: &crate::sbr_payload::SbrHeader, - tables: &crate::sbr_bands::BandTables, - ch: &SbrChannel, - ch_idx: usize, -) { - static COUNT: AtomicUsize = AtomicUsize::new(0); - let n = COUNT.fetch_add(1, Ordering::Relaxed); - if n >= 20 { - return; - } - eprintln!( - "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={:?}", - header.amp_res, - tables.kx, - tables.k2, - tables.n_low, - tables.n_high, - tables.n_q, - ch.t_env, - ch.freq_res, - ch.t_noise, - tables.f_high, - crate::sbr_hf::build_patches(tables), - ); - for (i, row) in ch.e_q.iter().enumerate() { - let (mn, mx) = row - .iter() - .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); - eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); - } - for (i, row) in ch.q_q.iter().enumerate() { - let (mn, mx) = row - .iter() - .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); - eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); - } -} /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a /// 1024-sample core frame) are half as fine as the QMF slots SBR actually /// runs at (32 per frame): `RATE = 2` converts one to the other. const RATE: i64 = 2; -/// Round-20 residual/side-info correlation: one row per (access unit, -/// channel) `apply_data` actually ran, giving `sbr_real_library.rs`'s -/// residual-energy grid a side-info table to correlate against without -/// re-parsing debug text. `frame` is a single counter shared by every -/// channel `apply_data` touches in one call, so it lines up 1:1 with the -/// AU-aligned (2048 output samples/AU for a plain 2x stream) blocks the -/// residual grid uses. -#[derive(Clone, Debug)] -pub struct SbrSideInfoRow { - pub frame: usize, - pub tag: u8, - pub ch: usize, - /// `"fresh"` for a frame `apply` reached (a real payload this AU), - /// `"hold"` for one `apply_last` reached (no fresh payload, reusing the - /// last parsed frame's data per §4.6.18). - pub source: &'static str, - pub coupling: bool, - pub amp_res: u8, - /// Band-index domain (same units `f_high`/`f_noise` and the residual - /// grid's FFT-bucket index share, per `per_band_correlation`'s - /// `band_hz = rate/256` measurement) the crossover and high-res/noise - /// band boundaries below live in. - pub kx: i64, - pub k2: i64, - pub f_high: Vec, - pub f_noise: Vec, - pub t_env: Vec, - pub freq_res: Vec, - pub invf_mode: Vec, - pub add_harmonic: Option>, - pub e_q_means: Vec, - pub q_q_means: Vec, - /// Header fields held for the frame's duration (§4.6.18.3.2), added for - /// the FMJ-vs-reeln feature-table hunt: `sbr_header()`'s own coding - /// choices, not per-envelope grid data. - pub freq_scale: u8, - pub alter_scale: u8, - pub noise_bands: u8, - pub limiter_bands: u8, - pub limiter_gains: u8, - pub interpol_freq: u8, - pub smoothing_mode: u8, - pub start_freq: u8, - pub stop_freq: u8, - pub xover_band: u8, - /// `t_noise.len() - 1`, i.e. `numNoiseFloors` this frame. - pub num_noise: usize, - /// One entry per HF patch, each the patch's band count (from - /// `sbr_hf::build_patches`), so patch geometry is visible per frame. - pub patch_lengths: Vec, - pub df_env: Vec, - pub df_noise: Vec, -} - -static SIDEINFO_LOG: std::sync::OnceLock>> = - std::sync::OnceLock::new(); -static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0); - -/// Diagnostic-only counter: how many `apply_data` calls process-wide ran -/// with `source == "hold"` (an AU whose FIL carried no fresh SBR payload, -/// falling back to `apply_last`'s reuse of the last parsed frame). Read via -/// [`hold_call_count`]; not gated by an env var since incrementing an atomic -/// is unconditionally cheap, unlike the `EC_AAC_SBR_*_DEBUG` prints nearby. -static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0); - -/// Total `apply_data` calls process-wide where the SBR payload was reused -/// from a prior frame (`apply_last`) rather than freshly parsed this AU -- -/// diagnostic instrument for `sbr441_family_sample_drift_probe`. -pub fn hold_call_count() -> usize { - HOLD_CALLS.load(Ordering::Relaxed) -} - -fn sideinfo_enabled() -> bool { - crate::knobs::sbr_sideinfo_debug() -} - -/// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named -/// pipeline stage, gated by `EC_AAC_SBR_QMFDUMP`. `start_band` is the -/// absolute QMF band index `rows[0]` represents (`0` for the core analysis -/// matrix, `kx` for the HF matrix), so every printed band index lines up -/// with `build_patches`' target-band units without the reader having to -/// offset anything by hand. -fn qmfdump_enabled() -> bool { - std::env::var("EC_AAC_SBR_QMFDUMP").is_ok() -} - -fn qmfdump_energies(stage: &str, start_band: usize, rows: &[Vec>]) { - let means: Vec = rows - .iter() - .map(|series| { - if series.is_empty() { - 0.0 - } else { - series - .iter() - .map(|c| c.re * c.re + c.im * c.im) - .sum::() - / series.len() as f64 - } - }) - .collect(); - eprintln!("QMFDUMP stage={stage} start_band={start_band} means={means:?}"); -} - -/// Drains nothing -- returns a clone of every row logged so far this -/// process, in call order. Empty unless `EC_AAC_SBR_SIDEINFO_DEBUG` was set -/// before decoding. -pub fn sbr_sideinfo_log() -> Vec { - let Some(log) = SIDEINFO_LOG.get() else { - return Vec::new(); - }; - log.lock().map(|l| l.clone()).unwrap_or_default() -} - /// Per-channel DSP state an SBR element's reconstruction carries across /// frames: the QMF filterbank pair, the HF generator's LPC history and /// chirp factors, and the noise-floor generator. @@ -469,7 +313,7 @@ impl SbrChain { if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) { elem.last_data = Some(data.clone()); } - self.apply_data(tag, is_cpe, data, planes, "fresh") + self.apply_data(tag, is_cpe, data, planes) } /// Re-runs the chain for `tag` using the last successfully parsed @@ -491,7 +335,7 @@ impl SbrChain { self.apply_low_only(tag, is_cpe, planes); return Ok(()); }; - self.apply_data(tag, is_cpe, &data, planes, "hold") + self.apply_data(tag, is_cpe, &data, planes) } fn apply_data( @@ -500,11 +344,7 @@ impl SbrChain { is_cpe: bool, data: &SbrData, planes: &mut [Vec], - source: &'static str, ) -> crate::Result<()> { - if source == "hold" { - HOLD_CALLS.fetch_add(1, Ordering::Relaxed); - } let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS }; let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { return Ok(()); @@ -518,12 +358,6 @@ impl SbrChain { return Ok(()); }; let coupling = data.coupling; - let sideinfo_on = sideinfo_enabled(); - let au_frame = if sideinfo_on { - SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed) - } else { - 0 - }; // PS: the mono channel is synthesized twice, through its own state and // through channel 1's (the right output), so both stay in step. let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some(); @@ -542,20 +376,6 @@ impl SbrChain { if num_slots == 0 { continue; } - if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { - static N: AtomicUsize = AtomicUsize::new(0); - let n = N.fetch_add(1, Ordering::Relaxed); - if n < 40 { - let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() - / plane.len().max(1) as f64) - .sqrt(); - eprintln!( - "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}", - plane.len(), - &plane[..8.min(plane.len())] - ); - } - } let state = &mut elem.channels[ch]; let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; let mut raw = Vec::with_capacity(num_slots); @@ -584,63 +404,6 @@ impl SbrChain { } let sbr_ch = &data.channels[ch]; - if std::env::var("EC_AAC_SBR_DEBUG").is_ok() { - eprintln!("SBRDBG coupling={}", data.coupling); - debug_dump(&header, &tables, sbr_ch, ch); - } - if sideinfo_on { - let mean = |rows: &[Vec]| -> Vec { - rows.iter() - .map(|r| { - if r.is_empty() { - 0.0 - } else { - r.iter().map(|&v| f64::from(v)).sum::() / r.len() as f64 - } - }) - .collect() - }; - let row = SbrSideInfoRow { - frame: au_frame, - tag, - ch, - source, - coupling, - amp_res: header.amp_res, - kx: tables.kx, - k2: tables.k2, - f_high: tables.f_high.clone(), - f_noise: tables.f_noise.clone(), - t_env: sbr_ch.t_env.clone(), - freq_res: sbr_ch.freq_res.clone(), - invf_mode: sbr_ch.invf_mode.clone(), - add_harmonic: sbr_ch.add_harmonic.clone(), - e_q_means: mean(&sbr_ch.e_q), - q_q_means: mean(&sbr_ch.q_q), - freq_scale: header.freq_scale, - alter_scale: header.alter_scale, - noise_bands: header.noise_bands, - limiter_bands: header.limiter_bands, - limiter_gains: header.limiter_gains, - interpol_freq: header.interpol_freq, - smoothing_mode: header.smoothing_mode, - start_freq: header.start_freq, - stop_freq: header.stop_freq, - xover_band: header.xover_band, - num_noise: sbr_ch.t_noise.len().saturating_sub(1), - patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(), - df_env: sbr_ch.df_env.clone(), - df_noise: sbr_ch.df_noise.clone(), - }; - let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new())); - if let Ok(mut l) = log.lock() { - l.push(row); - } - } - let qmfdump_on = qmfdump_enabled(); - if qmfdump_on { - qmfdump_energies("analysis", 0, &low_cur); - } let hf = sbr_hf::generate( &low_cur, &tables, @@ -648,9 +411,6 @@ impl SbrChain { &mut state.chirp, &mut state.hf_hist, ); - if qmfdump_on { - qmfdump_energies("post_patch", tables.kx as usize, &hf); - } let (env_energy, noise_energy) = sbr_env::dequantize_frame(&data.channels, ch, coupling); // sbr_env::adjust works in QMF-slot units; the parsed borders @@ -718,9 +478,6 @@ impl SbrChain { d.truncate(num_slots); d }; - if qmfdump_on { - qmfdump_energies("post_adjust", tables.kx as usize, &hf); - } let kx = (tables.kx as usize).min(ANALYSIS_BANDS); let k2 = (tables.k2 as usize).min(band_limit); @@ -728,11 +485,9 @@ impl SbrChain { for slot in 0..num_slots { let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; v[0..kx].copy_from_slice(&raw[slot][0..kx]); - if !crate::knobs::sbr_hf_bypass() { - for b in kx..k2 { - if b - kx < hf.len() { - v[b] = hf[b - kx][slot]; - } + for b in kx..k2 { + if b - kx < hf.len() { + v[b] = hf[b - kx][slot]; } } vs.push(v); @@ -760,20 +515,6 @@ impl SbrChain { } _ => synth_slots(&mut state.synthesis, &vs), }; - if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { - static N: AtomicUsize = AtomicUsize::new(0); - let n = N.fetch_add(1, Ordering::Relaxed); - if n < 40 { - let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() - / out.len().max(1) as f64) - .sqrt(); - eprintln!( - "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}", - out.len(), - &out[..8.min(out.len())] - ); - } - } if ps_planes.is_none() { *plane = out; } diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 2ede748b..b7e07548 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -168,29 +168,6 @@ impl Default for AdjustState { } } -fn noise_fraction_debug() -> bool { - crate::knobs::sbr_noise_fraction() -} - -type NoiseFractionRows = Vec<(usize, f64, f64, f64)>; - -static NOISE_FRACTION: std::sync::OnceLock> = - std::sync::OnceLock::new(); - -/// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band, -/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots, Σ |Y|² -/// post-adjust)` -- the last column against the first two's sum is the -/// per-subband realised/target energy ratio. -pub fn noise_fraction_table() -> Vec<(usize, f64, f64, f64)> { - let mut out: Vec<(usize, f64, f64, f64)> = NOISE_FRACTION - .get() - .and_then(|m| m.lock().ok()) - .map(|g| g.clone()) - .unwrap_or_default(); - out.sort_by_key(|e| e.0); - out -} - /// Adjusts `hf` (`[m][slot]`, `m = k - kx`) in place: envelope gains, /// noise floor and added sinusoids per §4.6.18.7.3-7.6. `ch.t_env`/`t_noise` /// are in QMF slots (already ×2). `reset` mirrors the spec's header-reset @@ -222,14 +199,7 @@ pub fn adjust( state.g_hist.clear(); state.q_hist.clear(); } - let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() { - LIMITER_FACTOR[3] - } else { - LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)] - }; - let zero_noise = crate::knobs::sbr_noise_zero(); - let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok(); - let track_fraction = noise_fraction_debug(); + let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]; let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 }; let l_a = ch.l_a; let l_a_prev: i64 = if state.la_prev_at_end { 0 } else { -1 }; @@ -340,13 +310,9 @@ pub fn adjust( let sum_orig: f64 = (lo..hi).map(|m| e_orig[m]).sum(); let sum_curr: f64 = (lo..hi).map(|m| e_curr[m]).sum(); let g_max = (limiter_max * ((EPS + sum_orig) / (EPS + sum_curr)).sqrt()).min(GAIN_MAX_CLIP); - let mut capped = 0usize; for m in lo..hi { let q_max = q_m[e][m] * g_max / gain[e][m]; q_m[e][m] = q_m[e][m].min(q_max); - if gain[e][m] > g_max { - capped += 1; - } gain[e][m] = gain[e][m].min(g_max); } let sum_act: f64 = (lo..hi) @@ -362,32 +328,6 @@ pub fn adjust( q_m[e][m] *= boost; s_m[e][m] *= boost; } - if limdump { - eprintln!( - "LIMDUMP ei={e} band=[{},{}) limiter_bands={} j={j}/{n_lim} \ - E_orig_mapped={sum_orig:.6e} E_curr={sum_curr:.6e} G_max={g_max:.6} \ - capped_cells={capped}/{} E_actual={sum_act:.6e} G_boost={boost:.6}", - limiter_table[j], - limiter_table[j + 1], - header.limiter_bands, - hi - lo, - ); - } - } - if track_fraction { - let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new())); - if let Ok(mut t) = tab.lock() { - for m in 0..m_max { - let sig = e_orig[m] / (1.0 + q_mapped[m]) * slots; - let noi = e_orig[m] * q_mapped[m] / (1.0 + q_mapped[m]) * slots; - if let Some(row) = t.iter_mut().find(|r| r.0 == m + kx) { - row.1 += sig; - row.2 += noi; - } else { - t.push((m + kx, sig, noi, 0.0)); - } - } - } } } state.s_index_prev = s_index_prev; @@ -451,25 +391,13 @@ pub fn adjust( noise_idx = (noise_idx + 1) & 0x1ff; if s_m[e][m] != 0.0 { y = y + Complex::new(s_m[e][m] * p_re, s_m[e][m] * p_im); - } else if !transient && !zero_noise { + } else if !transient { let (vr, vi) = SBR_NOISE[noise_idx]; y = y + Complex::new(q_filt[m] * vr, q_filt[m] * vi); } row[i] = y; p_im = -p_im; } - if track_fraction { - let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new())); - if let Ok(mut t) = tab.lock() { - for m in 0..m_max { - if let (Some(row), Some(y)) = - (t.iter_mut().find(|r| r.0 == m + kx), hf[m].get(i)) - { - row.3 += y.norm_sqr(); - } - } - } - } state.index_noise = (state.index_noise + m_max) & 0x1ff; state.index_sine = (state.index_sine + 1) & 3; } diff --git a/crates/ec-aac/tests/it/main.rs b/crates/ec-aac/tests/it/main.rs index a7758904..e31d506e 100644 --- a/crates/ec-aac/tests/it/main.rs +++ b/crates/ec-aac/tests/it/main.rs @@ -6,7 +6,6 @@ mod common; mod he_parity; mod implicit_ps; mod implicit_sbr; -mod reelh_per_frame; mod multichannel_parity; mod no_panic; mod ps_mp4;