Run PNS noise substitution before M/S and intensity stereo
Browse files at this commit7efd1d72c1123563a8886f2a809d486d605d9d65Parent: ca94f24- fix
- run PNS noise substitution before M/S and intensity stereo
6 changed files +497 -2
- crates/ec-aac/src/decode.rs +93 -1
- crates/ec-aac/src/lib.rs +1 -1
- crates/ec-aac/tests/obs_real_content.rs +202 -0
- crates/ec-aac/tests/oracle.rs +43 -0
- crates/ec-aac/tests/reelh_per_frame.rs +140 -0
- scripts/gen-fixtures.sh +18 -0
crates/ec-aac/src/decode.rsmodified+93 -1
| @@ -59,6 +59,52 @@ impl WindowSequence { | |||
| 59 | } | 59 | } |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 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 | + std::env::var("EC_AAC_TOOL_SIDEINFO_DEBUG").is_ok() | ||
| 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 | + | ||
| 62 | /// `ics_info` (§4.4.2.1) plus the grouping it implies. | 108 | /// `ics_info` (§4.4.2.1) plus the grouping it implies. |
| 63 | #[derive(Clone, Debug)] | 109 | #[derive(Clone, Debug)] |
| 64 | pub struct IcsInfo { | 110 | pub struct IcsInfo { |
| @@ -657,6 +703,14 @@ impl BlockDecoder { | |||
| 657 | /// Runs the stereo tools, TNS and the filterbank over one element's | 703 | /// Runs the stereo tools, TNS and the filterbank over one element's |
| 658 | /// channels, appending each channel's PCM to `out`. | 704 | /// channels, appending each channel's PCM to `out`. |
| 659 | fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec<Vec<f32>>) { | 705 | fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec<Vec<f32>>) { |
| 706 | + // Noise substitution (§4.6.13) must fill its bands before M/S and | ||
| 707 | + // intensity stereo run, so those tools combine the noise-filled | ||
| 708 | + // coefficients like any other spectral data rather than the zeroes | ||
| 709 | + // `dequantize` left behind for NOISE_HCB bands -- matching the | ||
| 710 | + // decode order every reference decoder uses. | ||
| 711 | + for ch in chans.iter_mut() { | ||
| 712 | + fill_noise(ch, &mut self.noise); | ||
| 713 | + } | ||
| 660 | if let ([left, right], Some(mask)) = (&mut *chans, ms) { | 714 | if let ([left, right], Some(mask)) = (&mut *chans, ms) { |
| 661 | apply_ms(left, right, mask); | 715 | apply_ms(left, right, mask); |
| 662 | } | 716 | } |
| @@ -664,7 +718,6 @@ impl BlockDecoder { | |||
| 664 | apply_intensity(left, right, ms); | 718 | apply_intensity(left, right, ms); |
| 665 | } | 719 | } |
| 666 | for ch in chans.iter_mut() { | 720 | for ch in chans.iter_mut() { |
| 667 | - fill_noise(ch, &mut self.noise); | ||
| 668 | let windows = if ch.ics.window_sequence.is_short() { | 721 | let windows = if ch.ics.window_sequence.is_short() { |
| 669 | 8 | 722 | 8 |
| 670 | } else { | 723 | } else { |
| @@ -693,6 +746,8 @@ impl BlockDecoder { | |||
| 693 | // FIL's SBR payload would apply to, per §4.5.1: a fill_element | 746 | // FIL's SBR payload would apply to, per §4.5.1: a fill_element |
| 694 | // directly follows the element it decorates. | 747 | // directly follows the element it decorates. |
| 695 | let mut pending: Option<(u8, usize, usize, bool)> = None; | 748 | let mut pending: Option<(u8, usize, usize, bool)> = None; |
| 749 | + let dump_tools = tool_sideinfo_enabled(); | ||
| 750 | + let au = if dump_tools { next_tool_sideinfo_au() } else { 0 }; | ||
| 696 | loop { | 751 | loop { |
| 697 | if r.bits_remaining() < 3 { | 752 | if r.bits_remaining() < 3 { |
| 698 | break; | 753 | break; |
| @@ -706,6 +761,9 @@ impl BlockDecoder { | |||
| 706 | let tag = r.read_bits(4)? as u8; | 761 | let tag = r.read_bits(4)? as u8; |
| 707 | let start = out.len(); | 762 | let start = out.len(); |
| 708 | let mut ch = [self.channel_stream(r, None)?]; | 763 | let mut ch = [self.channel_stream(r, None)?]; |
| 764 | + if dump_tools { | ||
| 765 | + log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None)); | ||
| 766 | + } | ||
| 709 | self.finish(&mut ch, None, &mut out); | 767 | self.finish(&mut ch, None, &mut out); |
| 710 | pending = Some((tag, start, 1, false)); | 768 | pending = Some((tag, start, 1, false)); |
| 711 | } | 769 | } |
| @@ -738,6 +796,9 @@ impl BlockDecoder { | |||
| 738 | self.channel_stream(r, shared.as_ref())?, | 796 | self.channel_stream(r, shared.as_ref())?, |
| 739 | self.channel_stream(r, shared.as_ref())?, | 797 | self.channel_stream(r, shared.as_ref())?, |
| 740 | ]; | 798 | ]; |
| 799 | + if dump_tools { | ||
| 800 | + log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask))); | ||
| 801 | + } | ||
| 741 | self.finish(&mut pair, Some(&mask), &mut out); | 802 | self.finish(&mut pair, Some(&mask), &mut out); |
| 742 | pending = Some((tag, start, 2, true)); | 803 | pending = Some((tag, start, 2, true)); |
| 743 | } | 804 | } |
| @@ -949,6 +1010,37 @@ fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) { | |||
| 949 | } | 1010 | } |
| 950 | } | 1011 | } |
| 951 | 1012 | ||
| 1013 | +/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics` | ||
| 1014 | +/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the | ||
| 1015 | +/// dump only needs whether the element used the tool at all). | ||
| 1016 | +fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow { | ||
| 1017 | + let mut ms_bands = 0; | ||
| 1018 | + let mut pns_bands = 0; | ||
| 1019 | + let mut is_bands = 0; | ||
| 1020 | + for g in 0..ch.ics.num_groups { | ||
| 1021 | + for sfb in 0..ch.ics.max_sfb { | ||
| 1022 | + if mask.is_some_and(|m| m.used(g, sfb)) { | ||
| 1023 | + ms_bands += 1; | ||
| 1024 | + } | ||
| 1025 | + match ch.cb[g][sfb] { | ||
| 1026 | + NOISE_HCB => pns_bands += 1, | ||
| 1027 | + INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1, | ||
| 1028 | + _ => {} | ||
| 1029 | + } | ||
| 1030 | + } | ||
| 1031 | + } | ||
| 1032 | + ToolSideInfoRow { | ||
| 1033 | + au, | ||
| 1034 | + tag, | ||
| 1035 | + is_cpe, | ||
| 1036 | + window_sequence: ch.ics.window_sequence, | ||
| 1037 | + ms_bands, | ||
| 1038 | + pns_bands, | ||
| 1039 | + is_bands, | ||
| 1040 | + tns_present: !ch.tns.filters.is_empty(), | ||
| 1041 | + } | ||
| 1042 | +} | ||
| 1043 | + | ||
| 952 | fn is_intensity(cb: u8) -> bool { | 1044 | fn is_intensity(cb: u8) -> bool { |
| 953 | cb == INTENSITY_HCB || cb == INTENSITY_HCB2 | 1045 | cb == INTENSITY_HCB || cb == INTENSITY_HCB2 |
| 954 | } | 1046 | } |
crates/ec-aac/src/lib.rsmodified+1 -1
| @@ -46,7 +46,7 @@ pub use config::{ | |||
| 46 | parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate, | 46 | parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate, |
| 47 | write_adts_header, write_audio_specific_config, | 47 | write_adts_header, write_audio_specific_config, |
| 48 | }; | 48 | }; |
| 49 | -pub use decode::{FRAME_LEN, WindowSequence}; | 49 | +pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log}; |
| 50 | pub use ec_core::{Error, Result}; | 50 | pub use ec_core::{Error, Result}; |
| 51 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; | 51 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; |
| 52 | /// Diagnostic only (round-20): per-(access-unit, channel) side-info rows | 52 | /// Diagnostic only (round-20): per-(access-unit, channel) side-info rows |
crates/ec-aac/tests/obs_real_content.rsadded+202 -0
| @@ -0,0 +1,202 @@ | |||
| 1 | +//! Table over every screen recording under `~/Videos/OBS`, diagnosing the | ||
| 2 | +//! PNS/M/S decorrelation the consumer sweep found in that encoder's output | ||
| 3 | +//! (see repo ledger). Real files, read-only, absent directory skips loudly. | ||
| 4 | + | ||
| 5 | +use std::path::{Path, PathBuf}; | ||
| 6 | +use std::process::Command; | ||
| 7 | + | ||
| 8 | +use ec_aac::AacDecoder; | ||
| 9 | +use ec_core::{CodecId, Demuxer, Packet}; | ||
| 10 | +use ec_mp4::Mp4Demuxer; | ||
| 11 | +use std::fs::File; | ||
| 12 | +use std::io::BufReader; | ||
| 13 | + | ||
| 14 | +const MAX_SAMPLES: usize = 480_000; // 10s @ 48kHz | ||
| 15 | +const LAG_MAX: usize = 4_000; | ||
| 16 | +const WINDOW: usize = 200_000; | ||
| 17 | + | ||
| 18 | +fn have_ffmpeg() -> bool { | ||
| 19 | + Command::new("ffmpeg") | ||
| 20 | + .arg("-version") | ||
| 21 | + .output() | ||
| 22 | + .map(|o| o.status.success()) | ||
| 23 | + .unwrap_or(false) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> { | ||
| 27 | + let out = Command::new("ffmpeg") | ||
| 28 | + .args(["-v", "error", "-i"]) | ||
| 29 | + .arg(path) | ||
| 30 | + .args([ | ||
| 31 | + "-map", "0:a:0", "-t", "10", "-f", "f32le", "-acodec", "pcm_f32le", "-", | ||
| 32 | + ]) | ||
| 33 | + .output() | ||
| 34 | + .expect("ffmpeg runs"); | ||
| 35 | + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); | ||
| 36 | + let samples: Vec<f32> = out | ||
| 37 | + .stdout | ||
| 38 | + .chunks_exact(4) | ||
| 39 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 40 | + .collect(); | ||
| 41 | + let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; | ||
| 42 | + for (i, &v) in samples.iter().enumerate() { | ||
| 43 | + planes[i % channels].push(v); | ||
| 44 | + } | ||
| 45 | + planes | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +fn extract_aac_track(path: &Path) -> Option<(Vec<u8>, Vec<Vec<u8>>)> { | ||
| 49 | + let f = File::open(path).ok()?; | ||
| 50 | + let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?; | ||
| 51 | + let aac = d.streams().iter().find(|s| s.params.codec == CodecId::Aac)?; | ||
| 52 | + let idx = aac.index; | ||
| 53 | + let asc = aac.params.extradata.as_ref()?.to_vec(); | ||
| 54 | + let mut aus = Vec::new(); | ||
| 55 | + while aus.len() < 1_500 { | ||
| 56 | + match d.next_packet() { | ||
| 57 | + Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()), | ||
| 58 | + Ok(_) => continue, | ||
| 59 | + Err(_) => break, | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + Some((asc, aus)) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +fn our_decode(path: &Path) -> Option<Vec<Vec<f32>>> { | ||
| 66 | + let (asc, aus) = extract_aac_track(path)?; | ||
| 67 | + let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?; | ||
| 68 | + let mut planes: Vec<Vec<f32>> = Vec::new(); | ||
| 69 | + let mut failed = 0usize; | ||
| 70 | + for au in &aus { | ||
| 71 | + let frame = match decoder.decode(au, None) { | ||
| 72 | + Ok(f) => f, | ||
| 73 | + Err(_) => { | ||
| 74 | + failed += 1; | ||
| 75 | + continue; | ||
| 76 | + } | ||
| 77 | + }; | ||
| 78 | + let ch = usize::from(frame.channels); | ||
| 79 | + if ch == 0 { | ||
| 80 | + continue; | ||
| 81 | + } | ||
| 82 | + if planes.is_empty() { | ||
| 83 | + planes = vec![Vec::new(); ch]; | ||
| 84 | + } | ||
| 85 | + for (i, v) in frame.samples.iter().enumerate() { | ||
| 86 | + planes[i % ch].push(*v); | ||
| 87 | + } | ||
| 88 | + if planes[0].len() >= MAX_SAMPLES { | ||
| 89 | + break; | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + eprintln!(" {failed}/{} AUs failed", aus.len()); | ||
| 93 | + if planes.is_empty() { None } else { Some(planes) } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +fn dot(a: &[f32], b: &[f32]) -> f64 { | ||
| 97 | + a.iter().zip(b).map(|(x, y)| f64::from(*x) * f64::from(*y)).sum() | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +fn correlation(a: &[f32], b: &[f32]) -> f64 { | ||
| 101 | + let n = a.len().min(b.len()); | ||
| 102 | + if n < 1024 { | ||
| 103 | + return 0.0; | ||
| 104 | + } | ||
| 105 | + let (a, b) = (&a[..n], &b[..n]); | ||
| 106 | + let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 107 | + let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; | ||
| 108 | + let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect(); | ||
| 109 | + let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect(); | ||
| 110 | + let num = dot(&ac, &bc); | ||
| 111 | + let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt(); | ||
| 112 | + if den == 0.0 { 0.0 } else { num / den } | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { | ||
| 116 | + const COARSE: usize = 4_096; | ||
| 117 | + let start = ours.len().min(theirs.len()).saturating_sub(WINDOW).min(ours.len() / 4); | ||
| 118 | + let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | ||
| 119 | + let (oa, ob) = if lag >= 0 { (start, start + lag as usize) } else { (start + (-lag) as usize, start) }; | ||
| 120 | + if oa + len > ours.len() || ob + len > theirs.len() { None } else { Some((oa, ob)) } | ||
| 121 | + }; | ||
| 122 | + let mut coarse_best = (0i64, -1.0f64, 0.0f64); | ||
| 123 | + for lag in -(LAG_MAX as i64)..=(LAG_MAX as i64) { | ||
| 124 | + let Some((oa, ob)) = slice_at(lag, COARSE) else { continue }; | ||
| 125 | + let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]); | ||
| 126 | + if c.abs() > coarse_best.1 { | ||
| 127 | + coarse_best = (lag, c.abs(), c); | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + let mut best = (coarse_best.0, -1.0f64, 0.0f64); | ||
| 131 | + for lag in (coarse_best.0 - 8)..=(coarse_best.0 + 8) { | ||
| 132 | + let Some((oa, ob)) = slice_at(lag, WINDOW) else { continue }; | ||
| 133 | + let c = correlation(&ours[oa..oa + WINDOW], &theirs[ob..ob + WINDOW]); | ||
| 134 | + if c.abs() > best.1 { | ||
| 135 | + best = (lag, c.abs(), c); | ||
| 136 | + } | ||
| 137 | + } | ||
| 138 | + (best.0, best.2) | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +fn rms(a: &[f32]) -> f64 { | ||
| 142 | + (a.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / a.len().max(1) as f64).sqrt() | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +#[test] | ||
| 146 | +fn obs_content_table() { | ||
| 147 | + if !have_ffmpeg() { | ||
| 148 | + eprintln!("skip: no ffmpeg"); | ||
| 149 | + return; | ||
| 150 | + } | ||
| 151 | + let dir = PathBuf::from(std::env::var("HOME").unwrap()).join("Videos/OBS"); | ||
| 152 | + let Ok(rd) = std::fs::read_dir(&dir) else { | ||
| 153 | + eprintln!("skip: no {}", dir.display()); | ||
| 154 | + return; | ||
| 155 | + }; | ||
| 156 | + let mut files: Vec<PathBuf> = rd | ||
| 157 | + .filter_map(|e| e.ok()) | ||
| 158 | + .map(|e| e.path()) | ||
| 159 | + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4")) | ||
| 160 | + .collect(); | ||
| 161 | + files.sort(); | ||
| 162 | + unsafe { | ||
| 163 | + std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1"); | ||
| 164 | + } | ||
| 165 | + for path in files { | ||
| 166 | + eprintln!("== {}", path.display()); | ||
| 167 | + let before = ec_aac::tool_sideinfo_log().len(); | ||
| 168 | + let Some(ours) = our_decode(&path) else { | ||
| 169 | + eprintln!(" our_decode: None"); | ||
| 170 | + continue; | ||
| 171 | + }; | ||
| 172 | + let theirs = ffmpeg_decode(&path, ours.len()); | ||
| 173 | + for (ch, (o, t)) in ours.iter().zip(theirs.iter()).enumerate() { | ||
| 174 | + let (lag, corr) = best_lag_correlation(o, t); | ||
| 175 | + // Also the direct, un-windowed corr from t=0 (no lag search) -- | ||
| 176 | + // this is what the consumer sweep that found this regression | ||
| 177 | + // measured, and can disagree with the windowed/lag-searched | ||
| 178 | + // number above if only part of the file is corrupted. | ||
| 179 | + let corr0 = correlation(o, t); | ||
| 180 | + let non_finite = o.iter().filter(|v| !v.is_finite()).count(); | ||
| 181 | + eprintln!( | ||
| 182 | + " ch{ch}: corr={corr:.4} corr@lag0={corr0:.4} lag={lag} rms_ours={:.5} rms_ffmpeg={:.5} non_finite={non_finite}", | ||
| 183 | + rms(o), | ||
| 184 | + rms(t) | ||
| 185 | + ); | ||
| 186 | + } | ||
| 187 | + let all_rows = ec_aac::tool_sideinfo_log(); | ||
| 188 | + let rows = &all_rows[before..]; | ||
| 189 | + let (mut pns, mut is_, mut ms, mut tns, mut cpe) = (0usize, 0usize, 0usize, 0usize, 0usize); | ||
| 190 | + for r in rows { | ||
| 191 | + if r.pns_bands > 0 { pns += 1; } | ||
| 192 | + if r.is_bands > 0 { is_ += 1; } | ||
| 193 | + if r.ms_bands > 0 { ms += 1; } | ||
| 194 | + if r.tns_present { tns += 1; } | ||
| 195 | + if r.is_cpe { cpe += 1; } | ||
| 196 | + } | ||
| 197 | + eprintln!( | ||
| 198 | + " tools over {} AUs: cpe={cpe} pns_aus={pns} is_aus={is_} ms_aus={ms} tns_aus={tns}", | ||
| 199 | + rows.len() | ||
| 200 | + ); | ||
| 201 | + } | ||
| 202 | +} | ||
crates/ec-aac/tests/oracle.rsmodified+43 -0
| @@ -187,6 +187,49 @@ fn mp4_fixtures_match_ffmpeg_per_channel() { | |||
| 187 | assert!(checked > 0, "no AAC-in-mp4 fixtures found"); | 187 | assert!(checked > 0, "no AAC-in-mp4 fixtures found"); |
| 188 | } | 188 | } |
| 189 | 189 | ||
| 190 | +/// One fixture per §4.6 coding tool ffmpeg's native encoder can force in | ||
| 191 | +/// isolation (plus one with all four together), pinning the PNS/M-S ordering | ||
| 192 | +/// bug found against real OBS screen recordings (repo ledger): PNS must fill | ||
| 193 | +/// its bands before M/S and intensity stereo combine them. | ||
| 194 | +#[test] | ||
| 195 | +fn aac_coding_tools_match_ffmpeg_in_isolation() { | ||
| 196 | + if !have_ffmpeg() { | ||
| 197 | + eprintln!("SKIP: ffmpeg not on PATH"); | ||
| 198 | + return; | ||
| 199 | + } | ||
| 200 | + let dir = fixtures().join("audio"); | ||
| 201 | + let tmp = std::env::temp_dir().join("ec-aac-tools-oracle"); | ||
| 202 | + std::fs::create_dir_all(&tmp).expect("temp dir"); | ||
| 203 | + let mut checked = 0; | ||
| 204 | + for tool in ["pns", "is", "ms", "tns", "all"] { | ||
| 205 | + let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a"); | ||
| 206 | + let path = dir.join(&name); | ||
| 207 | + if !path.exists() { | ||
| 208 | + eprintln!("SKIP {name}: fixture missing"); | ||
| 209 | + continue; | ||
| 210 | + } | ||
| 211 | + let adts = tmp.join(format!("{name}.aac")); | ||
| 212 | + let out = Command::new("ffmpeg") | ||
| 213 | + .args(["-v", "error", "-y", "-i"]) | ||
| 214 | + .arg(&path) | ||
| 215 | + .args(["-c:a", "copy", "-f", "adts"]) | ||
| 216 | + .arg(&adts) | ||
| 217 | + .output() | ||
| 218 | + .expect("ffmpeg runs"); | ||
| 219 | + assert!(out.status.success(), "remux failed for {name}"); | ||
| 220 | + let corr = compare(&adts); | ||
| 221 | + println!("{name}: {corr:?}"); | ||
| 222 | + for (ch, c) in corr.iter().enumerate() { | ||
| 223 | + assert!( | ||
| 224 | + *c >= 0.999, | ||
| 225 | + "{name} channel {ch} correlation {c:.6} < 0.999" | ||
| 226 | + ); | ||
| 227 | + } | ||
| 228 | + checked += 1; | ||
| 229 | + } | ||
| 230 | + assert!(checked > 0, "no AAC tool-isolation fixtures found"); | ||
| 231 | +} | ||
| 232 | + | ||
| 190 | /// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR. | 233 | /// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR. |
| 191 | /// Each channel carries its own tone, mapped explicitly onto the layout, so a | 234 | /// Each channel carries its own tone, mapped explicitly onto the layout, so a |
| 192 | /// wrong element order shows up as the wrong tone on the wrong channel. | 235 | /// wrong element order shows up as the wrong tone on the wrong channel. |
crates/ec-aac/tests/reelh_per_frame.rsadded+140 -0
| @@ -0,0 +1,140 @@ | |||
| 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 | +use std::path::Path; | ||
| 9 | +use std::process::Command; | ||
| 10 | + | ||
| 11 | +use ec_aac::AacDecoder; | ||
| 12 | +use ec_core::{CodecId, Demuxer, Packet}; | ||
| 13 | +use ec_mp4::Mp4Demuxer; | ||
| 14 | + | ||
| 15 | +fn have_ffmpeg() -> bool { | ||
| 16 | + Command::new("ffmpeg") | ||
| 17 | + .arg("-version") | ||
| 18 | + .output() | ||
| 19 | + .map(|o| o.status.success()) | ||
| 20 | + .unwrap_or(false) | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +#[test] | ||
| 24 | +fn reelh_per_frame_scan() { | ||
| 25 | + if !have_ffmpeg() { | ||
| 26 | + eprintln!("skip: no ffmpeg"); | ||
| 27 | + return; | ||
| 28 | + } | ||
| 29 | + let path = Path::new("/home/user/Downloads/reelh.mp4"); | ||
| 30 | + if !path.exists() { | ||
| 31 | + eprintln!("skip: file not present"); | ||
| 32 | + return; | ||
| 33 | + } | ||
| 34 | + unsafe { | ||
| 35 | + std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1"); | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + // ffmpeg's channel-0-only decode (pan, not -ac, per the repro). | ||
| 39 | + let out = Command::new("ffmpeg") | ||
| 40 | + .args(["-v", "error", "-i"]) | ||
| 41 | + .arg(path) | ||
| 42 | + .args([ | ||
| 43 | + "-map", "0:a:0", "-af", "pan=1c|c0=c0", "-f", "f32le", "-acodec", "pcm_f32le", "-", | ||
| 44 | + ]) | ||
| 45 | + .output() | ||
| 46 | + .expect("ffmpeg runs"); | ||
| 47 | + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); | ||
| 48 | + let theirs: Vec<f32> = out | ||
| 49 | + .stdout | ||
| 50 | + .chunks_exact(4) | ||
| 51 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 52 | + .collect(); | ||
| 53 | + | ||
| 54 | + // Our sequential decode: one decoder, no reset, packet 0 onward. | ||
| 55 | + let f = File::open(path).unwrap(); | ||
| 56 | + let mut d = Mp4Demuxer::new(BufReader::new(f)).unwrap(); | ||
| 57 | + let aac = d | ||
| 58 | + .streams() | ||
| 59 | + .iter() | ||
| 60 | + .find(|s| s.params.codec == CodecId::Aac) | ||
| 61 | + .unwrap(); | ||
| 62 | + let idx = aac.index; | ||
| 63 | + let asc = aac.params.extradata.as_ref().unwrap().to_vec(); | ||
| 64 | + let mut decoder = AacDecoder::with_config_bytes(&asc).unwrap(); | ||
| 65 | + | ||
| 66 | + let mut ours: Vec<f32> = Vec::new(); | ||
| 67 | + let mut frame_starts: Vec<usize> = Vec::new(); // sample offset each AU's ch0 output starts at | ||
| 68 | + let mut au_idx = 0usize; | ||
| 69 | + loop { | ||
| 70 | + let pkt = match d.next_packet() { | ||
| 71 | + Ok(Packet { stream, data, .. }) if stream == idx => data.to_vec(), | ||
| 72 | + Ok(_) => continue, | ||
| 73 | + Err(_) => break, | ||
| 74 | + }; | ||
| 75 | + frame_starts.push(ours.len()); | ||
| 76 | + match decoder.decode(&pkt, None) { | ||
| 77 | + Ok(frame) => { | ||
| 78 | + let ch = usize::from(frame.channels); | ||
| 79 | + if ch > 0 { | ||
| 80 | + for chunk in frame.samples.chunks_exact(ch) { | ||
| 81 | + ours.push(chunk[0]); | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + Err(e) => eprintln!("AU {au_idx} decode error: {e:?}"), | ||
| 86 | + } | ||
| 87 | + au_idx += 1; | ||
| 88 | + } | ||
| 89 | + eprintln!("decoded {au_idx} AUs, {} ch0 samples ours, {} ffmpeg", ours.len(), theirs.len()); | ||
| 90 | + | ||
| 91 | + let rows = ec_aac::tool_sideinfo_log(); | ||
| 92 | + | ||
| 93 | + // Per-AU corr at zero lag (both start from packet 0 in decode order -- | ||
| 94 | + // no lag search needed unless the two genuinely desync). | ||
| 95 | + let win = 1024usize; | ||
| 96 | + let mut first_bad: Option<usize> = None; | ||
| 97 | + for (i, &start) in frame_starts.iter().enumerate() { | ||
| 98 | + if start + win > ours.len() || start + win > theirs.len() { | ||
| 99 | + break; | ||
| 100 | + } | ||
| 101 | + let a = &ours[start..start + win]; | ||
| 102 | + let b = &theirs[start..start + win]; | ||
| 103 | + let ma = a.iter().sum::<f32>() / win as f32; | ||
| 104 | + let mb = b.iter().sum::<f32>() / win as f32; | ||
| 105 | + let num: f64 = a.iter().zip(b).map(|(x, y)| f64::from(*x - ma) * f64::from(*y - mb)).sum(); | ||
| 106 | + let da: f64 = a.iter().map(|x| f64::from(*x - ma).powi(2)).sum(); | ||
| 107 | + let db: f64 = b.iter().map(|y| f64::from(*y - mb).powi(2)).sum(); | ||
| 108 | + let corr = if da * db == 0.0 { 1.0 } else { num / (da * db).sqrt() }; | ||
| 109 | + if corr.abs() < 0.9 { | ||
| 110 | + if first_bad.is_none() { | ||
| 111 | + first_bad = Some(i); | ||
| 112 | + } | ||
| 113 | + eprintln!("AU {i}: sample_start={start} corr={corr:.4} BAD"); | ||
| 114 | + } else if i % 50 == 0 { | ||
| 115 | + eprintln!("AU {i}: sample_start={start} corr={corr:.4}"); | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + // Dump raw samples around the bad AU for inspection. | ||
| 120 | + if let Some(&start) = frame_starts.get(4) { | ||
| 121 | + eprintln!("--- AU4 samples (start={start}) ---"); | ||
| 122 | + for k in 0..16 { | ||
| 123 | + eprintln!(" k={k} ours={:.6} ffmpeg={:.6}", ours[start + k], theirs[start + k]); | ||
| 124 | + } | ||
| 125 | + let rms_o: f64 = (ours[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 126 | + let rms_t: f64 = (theirs[start..start + win].iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / win as f64).sqrt(); | ||
| 127 | + eprintln!(" rms ours={rms_o:.6} ffmpeg={rms_t:.6}"); | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + if let Some(bad) = first_bad { | ||
| 131 | + eprintln!("=== first bad AU: {bad} ==="); | ||
| 132 | + for i in bad.saturating_sub(2)..=bad + 2 { | ||
| 133 | + if let Some(row) = rows.get(i) { | ||
| 134 | + eprintln!(" AU {i}: {row:?}"); | ||
| 135 | + } | ||
| 136 | + } | ||
| 137 | + } else { | ||
| 138 | + eprintln!("no AU dropped below 0.9 corr"); | ||
| 139 | + } | ||
| 140 | +} | ||
scripts/gen-fixtures.shmodified+18 -0
| @@ -120,6 +120,24 @@ for lspec in "stereo|2" "5.1|6"; do | |||
| 120 | "${AIN[@]}" "${AMAP[@]}" -c:a alac -sample_fmt s32p -ar 48000 | 120 | "${AIN[@]}" "${AMAP[@]}" -c:a alac -sample_fmt s32p -ar 48000 |
| 121 | done | 121 | done |
| 122 | 122 | ||
| 123 | +# AAC coding-tool isolation: one fixture per §4.6 tool ffmpeg's native aac | ||
| 124 | +# encoder can force on its own (plus one with all four), so a decode | ||
| 125 | +# regression in any single tool pins to its own fixture rather than a mix. | ||
| 126 | +AAC_TOOL_VARIANTS=( | ||
| 127 | + "pns|-aac_pns 1 -aac_is 0 -aac_ms 0 -aac_tns 0" | ||
| 128 | + "is|-aac_pns 0 -aac_is 1 -aac_ms 0 -aac_tns 0" | ||
| 129 | + "ms|-aac_pns 0 -aac_is 0 -aac_ms 1 -aac_tns 0" | ||
| 130 | + "tns|-aac_pns 0 -aac_is 0 -aac_ms 0 -aac_tns 1" | ||
| 131 | + "all|-aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1" | ||
| 132 | +) | ||
| 133 | +for spec in "${AAC_TOOL_VARIANTS[@]}"; do | ||
| 134 | + IFS='|' read -r vname vargs <<<"$spec" | ||
| 135 | + read -r -a VARGS <<<"$vargs" | ||
| 136 | + build_audio_in 2 48000 | ||
| 137 | + gen "$FIXTURES/audio/aac-tool-${vname}-mp4-stereo-48000.m4a" \ | ||
| 138 | + "${AIN[@]}" "${AMAP[@]}" -c:a aac -b:a 160k "${VARGS[@]}" -ar 48000 | ||
| 139 | +done | ||
| 140 | + | ||
| 123 | # Matroska-carried audio: what the probe hands to the Matroska reader rather | 141 | # Matroska-carried audio: what the probe hands to the Matroska reader rather |
| 124 | # than parsing itself. One per codec family that has a Matroska mapping. | 142 | # than parsing itself. One per codec family that has a Matroska mapping. |
| 125 | for spec in "aac|-c:a aac -b:a 160k" "flac|-c:a flac" "opus|-c:a libopus -b:a 160k"; do | 143 | for spec in "aac|-c:a aac -b:a 160k" "flac|-c:a flac" "opus|-c:a libopus -b:a 160k"; do |