diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 7079dac6..b9f93f6d 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -59,6 +59,52 @@ 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 { + std::env::var("EC_AAC_TOOL_SIDEINFO_DEBUG").is_ok() +} + +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 { @@ -657,6 +703,14 @@ impl BlockDecoder { /// Runs the stereo tools, TNS and the filterbank over one element's /// channels, appending each channel's PCM to `out`. fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec>) { + // Noise substitution (§4.6.13) must fill its bands before M/S and + // intensity stereo run, so those tools combine the noise-filled + // coefficients like any other spectral data rather than the zeroes + // `dequantize` left behind for NOISE_HCB bands -- matching the + // decode order every reference decoder uses. + for ch in chans.iter_mut() { + fill_noise(ch, &mut self.noise); + } if let ([left, right], Some(mask)) = (&mut *chans, ms) { apply_ms(left, right, mask); } @@ -664,7 +718,6 @@ impl BlockDecoder { apply_intensity(left, right, ms); } for ch in chans.iter_mut() { - fill_noise(ch, &mut self.noise); let windows = if ch.ics.window_sequence.is_short() { 8 } else { @@ -693,6 +746,8 @@ 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 }; loop { if r.bits_remaining() < 3 { break; @@ -706,6 +761,9 @@ impl BlockDecoder { let tag = r.read_bits(4)? as u8; let start = out.len(); let mut ch = [self.channel_stream(r, None)?]; + if dump_tools { + log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None)); + } self.finish(&mut ch, None, &mut out); pending = Some((tag, start, 1, false)); } @@ -738,6 +796,9 @@ impl BlockDecoder { self.channel_stream(r, shared.as_ref())?, self.channel_stream(r, shared.as_ref())?, ]; + if dump_tools { + log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask))); + } self.finish(&mut pair, Some(&mask), &mut out); pending = Some((tag, start, 2, true)); } @@ -949,6 +1010,37 @@ 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 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/lib.rs b/crates/ec-aac/src/lib.rs index 75c5aab7..e909edfd 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -46,7 +46,7 @@ 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, WindowSequence}; +pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log}; pub use ec_core::{Error, Result}; pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; /// Diagnostic only (round-20): per-(access-unit, channel) side-info rows diff --git a/crates/ec-aac/tests/obs_real_content.rs b/crates/ec-aac/tests/obs_real_content.rs new file mode 100644 index 00000000..40c23550 --- /dev/null +++ b/crates/ec-aac/tests/obs_real_content.rs @@ -0,0 +1,202 @@ +//! Table over every screen recording under `~/Videos/OBS`, diagnosing the +//! PNS/M/S decorrelation the consumer sweep found in that encoder's output +//! (see repo ledger). Real files, read-only, absent directory skips loudly. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_aac::AacDecoder; +use ec_core::{CodecId, Demuxer, Packet}; +use ec_mp4::Mp4Demuxer; +use std::fs::File; +use std::io::BufReader; + +const MAX_SAMPLES: usize = 480_000; // 10s @ 48kHz +const LAG_MAX: usize = 4_000; +const WINDOW: usize = 200_000; + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +fn ffmpeg_decode(path: &Path, channels: usize) -> Vec> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-map", "0:a:0", "-t", "10", "-f", "f32le", "-acodec", "pcm_f32le", "-", + ]) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let samples: Vec = out + .stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; + for (i, &v) in samples.iter().enumerate() { + planes[i % channels].push(v); + } + planes +} + +fn extract_aac_track(path: &Path) -> Option<(Vec, Vec>)> { + let f = File::open(path).ok()?; + let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?; + let aac = d.streams().iter().find(|s| s.params.codec == CodecId::Aac)?; + let idx = aac.index; + let asc = aac.params.extradata.as_ref()?.to_vec(); + let mut aus = Vec::new(); + while aus.len() < 1_500 { + match d.next_packet() { + Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()), + Ok(_) => continue, + Err(_) => break, + } + } + Some((asc, aus)) +} + +fn our_decode(path: &Path) -> Option>> { + let (asc, aus) = extract_aac_track(path)?; + let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?; + let mut planes: Vec> = Vec::new(); + let mut failed = 0usize; + for au in &aus { + let frame = match decoder.decode(au, None) { + Ok(f) => f, + Err(_) => { + failed += 1; + continue; + } + }; + let ch = usize::from(frame.channels); + if ch == 0 { + continue; + } + if planes.is_empty() { + planes = vec![Vec::new(); ch]; + } + for (i, v) in frame.samples.iter().enumerate() { + planes[i % ch].push(*v); + } + if planes[0].len() >= MAX_SAMPLES { + break; + } + } + eprintln!(" {failed}/{} AUs failed", aus.len()); + if planes.is_empty() { None } else { Some(planes) } +} + +fn dot(a: &[f32], b: &[f32]) -> f64 { + a.iter().zip(b).map(|(x, y)| f64::from(*x) * f64::from(*y)).sum() +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let n = a.len().min(b.len()); + if n < 1024 { + return 0.0; + } + let (a, b) = (&a[..n], &b[..n]); + let ma = a.iter().map(|v| f64::from(*v)).sum::() / n as f64; + let mb = b.iter().map(|v| f64::from(*v)).sum::() / n as f64; + let ac: Vec = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect(); + let bc: Vec = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect(); + let num = dot(&ac, &bc); + let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt(); + if den == 0.0 { 0.0 } else { num / den } +} + +fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { + const COARSE: usize = 4_096; + let start = ours.len().min(theirs.len()).saturating_sub(WINDOW).min(ours.len() / 4); + let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { + let (oa, ob) = if lag >= 0 { (start, start + lag as usize) } else { (start + (-lag) as usize, start) }; + if oa + len > ours.len() || ob + len > theirs.len() { None } else { Some((oa, ob)) } + }; + let mut coarse_best = (0i64, -1.0f64, 0.0f64); + for lag in -(LAG_MAX as i64)..=(LAG_MAX as i64) { + let Some((oa, ob)) = slice_at(lag, COARSE) else { continue }; + let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]); + if c.abs() > coarse_best.1 { + coarse_best = (lag, c.abs(), c); + } + } + let mut best = (coarse_best.0, -1.0f64, 0.0f64); + for lag in (coarse_best.0 - 8)..=(coarse_best.0 + 8) { + let Some((oa, ob)) = slice_at(lag, WINDOW) else { continue }; + let c = correlation(&ours[oa..oa + WINDOW], &theirs[ob..ob + WINDOW]); + if c.abs() > best.1 { + best = (lag, c.abs(), c); + } + } + (best.0, best.2) +} + +fn rms(a: &[f32]) -> f64 { + (a.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() / a.len().max(1) as f64).sqrt() +} + +#[test] +fn obs_content_table() { + if !have_ffmpeg() { + eprintln!("skip: no ffmpeg"); + return; + } + let dir = PathBuf::from(std::env::var("HOME").unwrap()).join("Videos/OBS"); + let Ok(rd) = std::fs::read_dir(&dir) else { + eprintln!("skip: no {}", dir.display()); + return; + }; + let mut files: Vec = rd + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4")) + .collect(); + files.sort(); + unsafe { + std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1"); + } + for path in files { + eprintln!("== {}", path.display()); + let before = ec_aac::tool_sideinfo_log().len(); + let Some(ours) = our_decode(&path) else { + eprintln!(" our_decode: None"); + continue; + }; + let theirs = ffmpeg_decode(&path, ours.len()); + for (ch, (o, t)) in ours.iter().zip(theirs.iter()).enumerate() { + let (lag, corr) = best_lag_correlation(o, t); + // Also the direct, un-windowed corr from t=0 (no lag search) -- + // this is what the consumer sweep that found this regression + // measured, and can disagree with the windowed/lag-searched + // number above if only part of the file is corrupted. + let corr0 = correlation(o, t); + let non_finite = o.iter().filter(|v| !v.is_finite()).count(); + eprintln!( + " ch{ch}: corr={corr:.4} corr@lag0={corr0:.4} lag={lag} rms_ours={:.5} rms_ffmpeg={:.5} non_finite={non_finite}", + rms(o), + rms(t) + ); + } + let all_rows = ec_aac::tool_sideinfo_log(); + let rows = &all_rows[before..]; + let (mut pns, mut is_, mut ms, mut tns, mut cpe) = (0usize, 0usize, 0usize, 0usize, 0usize); + for r in rows { + if r.pns_bands > 0 { pns += 1; } + if r.is_bands > 0 { is_ += 1; } + if r.ms_bands > 0 { ms += 1; } + if r.tns_present { tns += 1; } + if r.is_cpe { cpe += 1; } + } + eprintln!( + " tools over {} AUs: cpe={cpe} pns_aus={pns} is_aus={is_} ms_aus={ms} tns_aus={tns}", + rows.len() + ); + } +} diff --git a/crates/ec-aac/tests/oracle.rs b/crates/ec-aac/tests/oracle.rs index 77b01c51..30f5f335 100644 --- a/crates/ec-aac/tests/oracle.rs +++ b/crates/ec-aac/tests/oracle.rs @@ -187,6 +187,49 @@ fn mp4_fixtures_match_ffmpeg_per_channel() { assert!(checked > 0, "no AAC-in-mp4 fixtures found"); } +/// One fixture per §4.6 coding tool ffmpeg's native encoder can force in +/// isolation (plus one with all four together), pinning the PNS/M-S ordering +/// bug found against real OBS screen recordings (repo ledger): PNS must fill +/// its bands before M/S and intensity stereo combine them. +#[test] +fn aac_coding_tools_match_ffmpeg_in_isolation() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = fixtures().join("audio"); + let tmp = std::env::temp_dir().join("ec-aac-tools-oracle"); + std::fs::create_dir_all(&tmp).expect("temp dir"); + let mut checked = 0; + for tool in ["pns", "is", "ms", "tns", "all"] { + let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a"); + let path = dir.join(&name); + if !path.exists() { + eprintln!("SKIP {name}: fixture missing"); + continue; + } + let adts = tmp.join(format!("{name}.aac")); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-i"]) + .arg(&path) + .args(["-c:a", "copy", "-f", "adts"]) + .arg(&adts) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "remux failed for {name}"); + let corr = compare(&adts); + println!("{name}: {corr:?}"); + for (ch, c) in corr.iter().enumerate() { + assert!( + *c >= 0.999, + "{name} channel {ch} correlation {c:.6} < 0.999" + ); + } + checked += 1; + } + assert!(checked > 0, "no AAC tool-isolation fixtures found"); +} + /// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR. /// Each channel carries its own tone, mapped explicitly onto the layout, so a /// wrong element order shows up as the wrong tone on the wrong channel. diff --git a/crates/ec-aac/tests/reelh_per_frame.rs b/crates/ec-aac/tests/reelh_per_frame.rs new file mode 100644 index 00000000..5be7925e --- /dev/null +++ b/crates/ec-aac/tests/reelh_per_frame.rs @@ -0,0 +1,140 @@ +//! Per-frame corr scan for the coordinator's second repro: a real download +//! whose AAC-LC decode reads clean for the first several seconds then +//! collapses mid-stream, sequentially, with no seek/reset. Finds the first +//! bad frame and its side info, to compare with the frame before. + +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::process::Command; + +use ec_aac::AacDecoder; +use ec_core::{CodecId, Demuxer, Packet}; +use ec_mp4::Mp4Demuxer; + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +#[test] +fn reelh_per_frame_scan() { + if !have_ffmpeg() { + eprintln!("skip: no ffmpeg"); + return; + } + let path = Path::new("/home/user/Downloads/reelh.mp4"); + if !path.exists() { + eprintln!("skip: file not present"); + return; + } + unsafe { + std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1"); + } + + // ffmpeg's channel-0-only decode (pan, not -ac, per the repro). + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-map", "0:a:0", "-af", "pan=1c|c0=c0", "-f", "f32le", "-acodec", "pcm_f32le", "-", + ]) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let theirs: Vec = out + .stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + + // Our sequential decode: one decoder, no reset, packet 0 onward. + let f = File::open(path).unwrap(); + let mut d = Mp4Demuxer::new(BufReader::new(f)).unwrap(); + let aac = d + .streams() + .iter() + .find(|s| s.params.codec == CodecId::Aac) + .unwrap(); + let idx = aac.index; + let asc = aac.params.extradata.as_ref().unwrap().to_vec(); + let mut decoder = AacDecoder::with_config_bytes(&asc).unwrap(); + + let mut ours: Vec = Vec::new(); + let mut frame_starts: Vec = Vec::new(); // sample offset each AU's ch0 output starts at + let mut au_idx = 0usize; + loop { + let pkt = match d.next_packet() { + Ok(Packet { stream, data, .. }) if stream == idx => data.to_vec(), + Ok(_) => continue, + Err(_) => break, + }; + frame_starts.push(ours.len()); + match decoder.decode(&pkt, None) { + Ok(frame) => { + let ch = usize::from(frame.channels); + if ch > 0 { + for chunk in frame.samples.chunks_exact(ch) { + ours.push(chunk[0]); + } + } + } + Err(e) => eprintln!("AU {au_idx} decode error: {e:?}"), + } + au_idx += 1; + } + eprintln!("decoded {au_idx} AUs, {} ch0 samples ours, {} ffmpeg", ours.len(), theirs.len()); + + let rows = ec_aac::tool_sideinfo_log(); + + // Per-AU corr at zero lag (both start from packet 0 in decode order -- + // no lag search needed unless the two genuinely desync). + let win = 1024usize; + let mut first_bad: Option = None; + for (i, &start) in frame_starts.iter().enumerate() { + if start + win > ours.len() || start + win > theirs.len() { + break; + } + let a = &ours[start..start + win]; + let b = &theirs[start..start + win]; + let ma = a.iter().sum::() / win as f32; + let mb = b.iter().sum::() / win as f32; + let num: f64 = a.iter().zip(b).map(|(x, y)| f64::from(*x - ma) * f64::from(*y - mb)).sum(); + let da: f64 = a.iter().map(|x| f64::from(*x - ma).powi(2)).sum(); + let db: f64 = b.iter().map(|y| f64::from(*y - mb).powi(2)).sum(); + let corr = if da * db == 0.0 { 1.0 } else { num / (da * db).sqrt() }; + if corr.abs() < 0.9 { + if first_bad.is_none() { + first_bad = Some(i); + } + eprintln!("AU {i}: sample_start={start} corr={corr:.4} BAD"); + } else if i % 50 == 0 { + eprintln!("AU {i}: sample_start={start} corr={corr:.4}"); + } + } + + // Dump raw samples around the bad AU for inspection. + if let Some(&start) = frame_starts.get(4) { + eprintln!("--- AU4 samples (start={start}) ---"); + for k in 0..16 { + eprintln!(" k={k} ours={:.6} ffmpeg={:.6}", ours[start + k], theirs[start + k]); + } + let rms_o: f64 = (ours[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::() / win as f64).sqrt(); + let rms_t: f64 = (theirs[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::() / win as f64).sqrt(); + eprintln!(" rms ours={rms_o:.6} ffmpeg={rms_t:.6}"); + } + + if let Some(bad) = first_bad { + eprintln!("=== first bad AU: {bad} ==="); + for i in bad.saturating_sub(2)..=bad + 2 { + if let Some(row) = rows.get(i) { + eprintln!(" AU {i}: {row:?}"); + } + } + } else { + eprintln!("no AU dropped below 0.9 corr"); + } +} diff --git a/scripts/gen-fixtures.sh b/scripts/gen-fixtures.sh index cbcb5f8d..88eafed8 100755 --- a/scripts/gen-fixtures.sh +++ b/scripts/gen-fixtures.sh @@ -120,6 +120,24 @@ for lspec in "stereo|2" "5.1|6"; do "${AIN[@]}" "${AMAP[@]}" -c:a alac -sample_fmt s32p -ar 48000 done +# AAC coding-tool isolation: one fixture per §4.6 tool ffmpeg's native aac +# encoder can force on its own (plus one with all four), so a decode +# regression in any single tool pins to its own fixture rather than a mix. +AAC_TOOL_VARIANTS=( + "pns|-aac_pns 1 -aac_is 0 -aac_ms 0 -aac_tns 0" + "is|-aac_pns 0 -aac_is 1 -aac_ms 0 -aac_tns 0" + "ms|-aac_pns 0 -aac_is 0 -aac_ms 1 -aac_tns 0" + "tns|-aac_pns 0 -aac_is 0 -aac_ms 0 -aac_tns 1" + "all|-aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1" +) +for spec in "${AAC_TOOL_VARIANTS[@]}"; do + IFS='|' read -r vname vargs <<<"$spec" + read -r -a VARGS <<<"$vargs" + build_audio_in 2 48000 + gen "$FIXTURES/audio/aac-tool-${vname}-mp4-stereo-48000.m4a" \ + "${AIN[@]}" "${AMAP[@]}" -c:a aac -b:a 160k "${VARGS[@]}" -ar 48000 +done + # Matroska-carried audio: what the probe hands to the Matroska reader rather # than parsing itself. One per codec family that has a Matroska mapping. for spec in "aac|-c:a aac -b:a 160k" "flac|-c:a flac" "opus|-c:a libopus -b:a 160k"; do