forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into sbr-per-au

Browse files at this commit

55972ba8b66ec4e8d7130a00ff1947fd37d2b464Ahmet Kaan GümüşParent: 7dce885537e531

16 changed files +1183 -112

Cargo.lockmodified+3 -0
@@ -347,8 +347,11 @@ dependencies = [
347347 name = "ec-matroska"
348348 version = "0.1.0"
349349 dependencies = [
350+ "ec-aac",
351+ "ec-ac3",
350352 "ec-core",
351353 "ec-inflate",
354+ "ec-mp4",
352355 ]
353356
354357 [[package]]
crates/ec-aac/src/decode.rsmodified+93 -1
@@ -59,6 +59,52 @@ 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+ 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+
62108 /// `ics_info` (§4.4.2.1) plus the grouping it implies.
63109 #[derive(Clone, Debug)]
64110 pub struct IcsInfo {
@@ -657,6 +703,14 @@ impl BlockDecoder {
657703 /// Runs the stereo tools, TNS and the filterbank over one element's
658704 /// channels, appending each channel's PCM to `out`.
659705 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+ }
660714 if let ([left, right], Some(mask)) = (&mut *chans, ms) {
661715 apply_ms(left, right, mask);
662716 }
@@ -664,7 +718,6 @@ impl BlockDecoder {
664718 apply_intensity(left, right, ms);
665719 }
666720 for ch in chans.iter_mut() {
667- fill_noise(ch, &mut self.noise);
668721 let windows = if ch.ics.window_sequence.is_short() {
669722 8
670723 } else {
@@ -693,6 +746,8 @@ impl BlockDecoder {
693746 // FIL's SBR payload would apply to, per §4.5.1: a fill_element
694747 // directly follows the element it decorates.
695748 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 };
696751 loop {
697752 if r.bits_remaining() < 3 {
698753 break;
@@ -706,6 +761,9 @@ impl BlockDecoder {
706761 let tag = r.read_bits(4)? as u8;
707762 let start = out.len();
708763 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+ }
709767 self.finish(&mut ch, None, &mut out);
710768 // §4.6.18.1: SBR is never applied to the LFE channel (no
711769 // FIL/SBR payload follows it), so it must not become a
@@ -748,6 +806,9 @@ impl BlockDecoder {
748806 self.channel_stream(r, shared.as_ref())?,
749807 self.channel_stream(r, shared.as_ref())?,
750808 ];
809+ if dump_tools {
810+ log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));
811+ }
751812 self.finish(&mut pair, Some(&mask), &mut out);
752813 pending = Some((tag, start, 2, true));
753814 }
@@ -961,6 +1022,37 @@ fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
9611022 }
9621023 }
9631024
1025+/// Builds one `EC_AAC_TOOL_SIDEINFO_DEBUG` row from an already-decoded `Ics`
1026+/// (any channel of a CPE, since PNS/IS/TNS presence is per-channel but the
1027+/// dump only needs whether the element used the tool at all).
1028+fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {
1029+ let mut ms_bands = 0;
1030+ let mut pns_bands = 0;
1031+ let mut is_bands = 0;
1032+ for g in 0..ch.ics.num_groups {
1033+ for sfb in 0..ch.ics.max_sfb {
1034+ if mask.is_some_and(|m| m.used(g, sfb)) {
1035+ ms_bands += 1;
1036+ }
1037+ match ch.cb[g][sfb] {
1038+ NOISE_HCB => pns_bands += 1,
1039+ INTENSITY_HCB | INTENSITY_HCB2 => is_bands += 1,
1040+ _ => {}
1041+ }
1042+ }
1043+ }
1044+ ToolSideInfoRow {
1045+ au,
1046+ tag,
1047+ is_cpe,
1048+ window_sequence: ch.ics.window_sequence,
1049+ ms_bands,
1050+ pns_bands,
1051+ is_bands,
1052+ tns_present: !ch.tns.filters.is_empty(),
1053+ }
1054+}
1055+
9641056 fn is_intensity(cb: u8) -> bool {
9651057 cb == INTENSITY_HCB || cb == INTENSITY_HCB2
9661058 }
crates/ec-aac/src/lib.rsmodified+1 -1
@@ -46,7 +46,7 @@ pub use config::{
4646 parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
4747 write_adts_header, write_audio_specific_config,
4848 };
49-pub use decode::{FRAME_LEN, WindowSequence};
49+pub use decode::{FRAME_LEN, ToolSideInfoRow, WindowSequence, tool_sideinfo_log};
5050 pub use ec_core::{Error, Result};
5151 pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
5252 /// 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() {
187187 assert!(checked > 0, "no AAC-in-mp4 fixtures found");
188188 }
189189
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+
190233 /// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR.
191234 /// Each channel carries its own tone, mapped explicitly onto the layout, so a
192235 /// 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+}
crates/ec-hw/src/enc/mod.rsmodified+54 -19
@@ -352,9 +352,18 @@ impl Encoder {
352352 /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate
353353 /// encodes, and no VPP conversion this crate builds, has a destination
354354 /// for a 12-bit source.
355- /// - `frame`'s coded size does not match this encoder's: the surface
356- /// formats have to agree for the driver to read one as the other, and
357- /// the VPP conversion pass (when one runs) does not resize.
355+ ///
356+ /// A `frame` whose coded size does not match this encoder's (a common
357+ /// case: HEVC block-rounds to 32, so a 3840x2160 source's 2160 stays
358+ /// unrounded while the encoder's coded height becomes 2176) is not
359+ /// refused — it goes through the same VPP pool a 10-bit source uses,
360+ /// placed by explicit region rather than a whole-surface convert: only
361+ /// `frame.display_size` is read from the source and written into the
362+ /// destination at `(0, 0)`, so the padding rows/columns beyond it are
363+ /// never touched by the copy. Those padding pixels are still fed to the
364+ /// encoder as part of the coded surface, so the pool is painted black
365+ /// once, on creation, rather than left as whatever the driver's fresh
366+ /// allocation happened to contain.
358367 pub fn encode_frame(
359368 &mut self,
360369 frame: &crate::frame::Frame,
@@ -373,28 +382,33 @@ impl Encoder {
373382 "encode_frame: the frame was decoded on a different Display than this encoder",
374383 ));
375384 }
376- if frame.coded_size != self.coded_size {
377- return Err(Error::config(format!(
378- "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}",
379- self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
380- )));
381- }
382- let source = if frame.bit_depth == 10 {
383- self.nv12_from_p010(frame.surface())?
385+ let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size {
386+ self.vpp_into_pool(frame.surface(), frame.display_size)?
384387 } else {
385388 Arc::clone(frame.surface())
386389 };
387390 self.encode_surface(source, meta)
388391 }
389392
390- /// Convert a P010 surface into this encoder's coded size, in NV12, on the
391- /// GPU. Builds the VPP pipeline and its two-surface pool on first use.
392- fn nv12_from_p010(&mut self, source: &Arc<Surface>) -> Result<Arc<Surface>> {
393+ /// Place a source surface's visible rect into this encoder's coded size,
394+ /// in NV12, on the GPU: a whole-surface convert when the source is
395+ /// already the encoder's coded size (the common 10-bit case), a region
396+ /// copy/convert otherwise. Builds the VPP pipeline and its two-surface
397+ /// pool on first use, painting the pool black so any padding beyond
398+ /// `display_size` a region copy never touches is deterministic.
399+ fn vpp_into_pool(
400+ &mut self,
401+ source: &Arc<Surface>,
402+ display_size: (u32, u32),
403+ ) -> Result<Arc<Surface>> {
393404 if self.vpp.is_none() {
394405 let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1)
395406 .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER);
396407 let display = self.context.display();
397408 let surfaces = Surface::create_pool(display, &spec, 2)?;
409+ for s in &surfaces {
410+ Self::fill_black(s, self.coded_size)?;
411+ }
398412 let vpp = Vpp::new(
399413 display,
400414 sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10,
@@ -405,11 +419,32 @@ impl Encoder {
405419 }
406420 let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]);
407421 self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len();
408- Ok(self
409- .vpp
410- .as_ref()
411- .expect("just built above if it was None")
412- .convert(source, dest)?)
422+ let vpp = self.vpp.as_ref().expect("just built above if it was None");
423+ if display_size == self.coded_size {
424+ Ok(vpp.convert(source, dest)?)
425+ } else {
426+ let rect = (0, 0, display_size.0, display_size.1);
427+ Ok(vpp.convert_region(source, rect, dest, rect)?)
428+ }
429+ }
430+
431+ /// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the
432+ /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a
433+ /// region copy's untouched padding reads the same deterministic value on
434+ /// every driver instead of whatever the fresh allocation contained.
435+ fn fill_black(surface: &Arc<Surface>, size: (u32, u32)) -> Result<()> {
436+ let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?;
437+ {
438+ let mut mapped = image.map()?;
439+ if let Some(y) = mapped.plane_mut(0) {
440+ y.fill(16);
441+ }
442+ if let Some(uv) = mapped.plane_mut(1) {
443+ uv.fill(128);
444+ }
445+ }
446+ surface.write_from(&image, size.0, size.1)?;
447+ Ok(())
413448 }
414449
415450 /// Shared submission path for [`Encoder::encode`] and
crates/ec-hw/tests/gpu.rsmodified+113 -85
@@ -1531,13 +1531,14 @@ fn encode_frame_accepts_p010_via_vpp() {
15311531 };
15321532
15331533 // This film's HEVC SPS `pic_height_in_luma_samples` is 2160, which is a
1534- // multiple of the H.264 encode block size (16) but not the HEVC one
1535- // (32, next_multiple_of gives 2176) — `encode_frame` refuses that
1536- // mismatch by documented design ("frame's coded size does not match
1537- // this encoder's ... the VPP conversion pass does not resize") rather
1538- // than silently stretching the picture, so the HEVC target is expected
1539- // to be *refused* here, not to round-trip; only H.264 gets the full
1540- // encode/decode/PSNR comparison.
1534+ // multiple of the H.264 encode block size (16) but not the HEVC one (32,
1535+ // next_multiple_of gives 2176) — `encode_frame` no longer refuses that
1536+ // mismatch: it routes through the VPP pool by explicit region
1537+ // (`Encoder::vpp_into_pool`), so both targets get the full
1538+ // encode/decode/PSNR comparison, and the HEVC one additionally gets an
1539+ // `ffprobe` check that the visible size in the produced stream is still
1540+ // 3840x2160 (the encoder's own cropping, not a VPP resize).
1541+ let (mut w, mut h) = (0u32, 0u32);
15411542 for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
15421543 let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
15431544 let mut zc_stream = Vec::new();
@@ -1545,13 +1546,13 @@ fn encode_frame_accepts_p010_via_vpp() {
15451546 let mut count = 0i64;
15461547 let mut zero_copy: Option<Encoder> = None;
15471548 let mut cpu_path: Option<Encoder> = None;
1548- let mut refused = false;
1549+ let refused = false;
15491550
15501551 decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
15511552 if refused {
15521553 return;
15531554 }
1554- let (w, h) = frame.display_size;
1555+ (w, h) = frame.display_size;
15551556 let zero_copy = zero_copy.get_or_insert_with(|| {
15561557 let mut cfg = EncoderConfig::new(target, w, h);
15571558 cfg.gop_size = 30;
@@ -1568,22 +1569,10 @@ fn encode_frame_accepts_p010_via_vpp() {
15681569 timestamp: count,
15691570 force_keyframe: false,
15701571 };
1571- match zero_copy.encode_frame(&frame, meta) {
1572- Ok(zc) => zc_stream.extend_from_slice(&zc.data),
1573- Err(e) if target == EncCodec::H265 => {
1574- println!(
1575- "{target:?}: encode_frame refused as documented (block size vs SPS \
1576- pic height): {e}"
1577- );
1578- assert!(
1579- e.to_string().contains("encoder surfaces are"),
1580- "unexpected refusal reason: {e}"
1581- );
1582- refused = true;
1583- return;
1584- }
1585- Err(e) => panic!("encode_frame (zero copy, P010 via VPP): {e}"),
1586- }
1572+ let zc = zero_copy
1573+ .encode_frame(&frame, meta)
1574+ .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)");
1575+ zc_stream.extend_from_slice(&zc.data);
15871576 let i420 = frame.to_i420().expect("readback for the CPU-path baseline");
15881577 let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)");
15891578 cpu_stream.extend_from_slice(&cpu.data);
@@ -1629,6 +1618,35 @@ fn encode_frame_accepts_p010_via_vpp() {
16291618 println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB");
16301619 assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path");
16311620 assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path");
1621+
1622+ // The size-mismatch route (HEVC: 2160 visible vs 2176 coded) places
1623+ // the picture by VPP region rather than encoder cropping alone, so
1624+ // confirm the encoder's own SPS conformance window still reports the
1625+ // real 3840x2160 — not the padded 2176 the coded surface carries.
1626+ let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}"));
1627+ std::fs::create_dir_all(&dir).expect("temp dir");
1628+ let path = dir.join(match target {
1629+ EncCodec::H264 => "out.264",
1630+ EncCodec::H265 => "out.265",
1631+ EncCodec::Av1 => "out.obu",
1632+ });
1633+ std::fs::write(&path, &zc_stream).expect("write bitstream");
1634+ let probe = Command::new("ffprobe")
1635+ .args([
1636+ "-v",
1637+ "error",
1638+ "-select_streams",
1639+ "v:0",
1640+ "-show_entries",
1641+ "stream=width,height",
1642+ "-of",
1643+ "csv=p=0",
1644+ ])
1645+ .arg(&path)
1646+ .output()
1647+ .expect("ffprobe runs");
1648+ let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string();
1649+ assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}");
16321650 }
16331651 }
16341652
@@ -1637,12 +1655,10 @@ fn encode_frame_accepts_p010_via_vpp() {
16371655 /// says whether the VPP conversion is cheap enough to keep the zero-copy path
16381656 /// meaningfully faster than reading the frame back to system memory.
16391657 ///
1640-/// Targets H.264: this film's HEVC SPS `pic_height_in_luma_samples` (2160)
1641-/// is not a multiple of this crate's HEVC encode block size (32), so
1642-/// `encode_frame` refuses the HEVC target on this file by documented design
1643-/// (see `encode_frame_accepts_p010_via_vpp`) — 2160 *is* a multiple of the
1644-/// H.264 block size (16), so H.264 is the target that actually exercises the
1645-/// zero-copy path on this real source.
1658+/// Both H.264 (coded size already matches this film's 2160 visible height,
1659+/// so the P010->NV12 convert is whole-surface) and HEVC (2160 is not a
1660+/// multiple of the 32-block HEVC coded size, so `encode_frame` also takes
1661+/// the VPP region-copy route — `Encoder::vpp_into_pool`) get a bench row.
16461662 #[test]
16471663 fn p010_zero_copy_encode_is_realtime() {
16481664 let Some(display) = display() else { return };
@@ -1659,66 +1675,78 @@ fn p010_zero_copy_encode_is_realtime() {
16591675 let units = split_access_units(&data, Codec::H265);
16601676 assert!(units.len() > limit, "film clip too short for {limit} frames");
16611677
1662- println!("{:<24} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms");
1663- let mut zc_median = None;
1664- let mut cpu_median = None;
1665- for (name, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] {
1666- let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1667- let mut encoder: Option<Encoder> = None;
1668- let mut durations: Vec<Duration> = Vec::new();
1669- let mut count = 0i64;
1670- 'outer: for (i, unit) in units.iter().enumerate() {
1671- decoder.decode(unit, i as i64).expect("decode");
1672- while let Some(frame) = decoder.next_frame() {
1673- let (w, h) = frame.display_size;
1674- let encoder = encoder.get_or_insert_with(|| {
1675- let mut cfg = EncoderConfig::new(EncCodec::H264, w, h);
1676- cfg.gop_size = 30;
1677- cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1678- Encoder::new(&display, cfg).expect("encoder opens")
1679- });
1680- let meta = FrameMetadata {
1681- timestamp: count,
1682- force_keyframe: false,
1683- };
1684- let t0 = Instant::now();
1685- if zero_copy {
1686- encoder.encode_frame(&frame, meta).expect("encode_frame");
1687- } else {
1688- let i420 = frame.to_i420().expect("readback");
1689- encoder.encode(&i420, meta).expect("encode");
1690- }
1691- durations.push(t0.elapsed());
1692- count += 1;
1693- if durations.len() >= limit {
1694- break 'outer;
1678+ println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms");
1679+ // (target, zero-copy median ms, CPU-path median ms) rows, filled in order.
1680+ let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new();
1681+ for target in [EncCodec::H264, EncCodec::H265] {
1682+ let mut zc_median = None;
1683+ let mut cpu_median = None;
1684+ for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] {
1685+ let name = format!("{target:?} {label}");
1686+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1687+ let mut encoder: Option<Encoder> = None;
1688+ let mut durations: Vec<Duration> = Vec::new();
1689+ let mut count = 0i64;
1690+ 'outer: for (i, unit) in units.iter().enumerate() {
1691+ decoder.decode(unit, i as i64).expect("decode");
1692+ while let Some(frame) = decoder.next_frame() {
1693+ let (w, h) = frame.display_size;
1694+ let encoder = encoder.get_or_insert_with(|| {
1695+ let mut cfg = EncoderConfig::new(target, w, h);
1696+ cfg.gop_size = 30;
1697+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1698+ Encoder::new(&display, cfg).expect("encoder opens")
1699+ });
1700+ let meta = FrameMetadata {
1701+ timestamp: count,
1702+ force_keyframe: false,
1703+ };
1704+ let t0 = Instant::now();
1705+ if zero_copy {
1706+ encoder.encode_frame(&frame, meta).expect("encode_frame");
1707+ } else {
1708+ let i420 = frame.to_i420().expect("readback");
1709+ encoder.encode(&i420, meta).expect("encode");
1710+ }
1711+ durations.push(t0.elapsed());
1712+ count += 1;
1713+ if durations.len() >= limit {
1714+ break 'outer;
1715+ }
16951716 }
16961717 }
1718+ assert!(
1719+ durations.len() >= limit,
1720+ "{name}: only {} of {limit} frames encoded",
1721+ durations.len()
1722+ );
1723+ durations.sort();
1724+ let ms = |d: Duration| d.as_secs_f64() * 1000.0;
1725+ let median = ms(durations[durations.len() / 2]);
1726+ let min = ms(durations[0]);
1727+ let max = ms(durations[durations.len() - 1]);
1728+ println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}");
1729+ if zero_copy {
1730+ zc_median = Some(median);
1731+ } else {
1732+ cpu_median = Some(median);
1733+ }
16971734 }
1735+ rows.push((
1736+ target,
1737+ zc_median.expect("zero-copy phase ran"),
1738+ cpu_median.expect("CPU-path phase ran"),
1739+ ));
1740+ }
1741+ for (target, zc, cpu) in rows {
1742+ println!(
1743+ "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})"
1744+ );
16981745 assert!(
1699- durations.len() >= limit,
1700- "{name}: only {} of {limit} frames encoded",
1701- durations.len()
1746+ zc <= 20.0,
1747+ "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)"
17021748 );
1703- durations.sort();
1704- let ms = |d: Duration| d.as_secs_f64() * 1000.0;
1705- let median = ms(durations[durations.len() / 2]);
1706- let min = ms(durations[0]);
1707- let max = ms(durations[durations.len() - 1]);
1708- println!("{name:<24} {median:>10.2} {min:>10.2} {max:>10.2}");
1709- if zero_copy {
1710- zc_median = Some(median);
1711- } else {
1712- cpu_median = Some(median);
1713- }
17141749 }
1715- let zc = zc_median.expect("zero-copy phase ran");
1716- let cpu = cpu_median.expect("CPU-path phase ran");
1717- println!("target: decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})");
1718- assert!(
1719- zc <= 20.0,
1720- "decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)"
1721- );
17221750 }
17231751
17241752 /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in
crates/ec-matroska/Cargo.tomlmodified+5 -0
@@ -9,3 +9,8 @@ authors.workspace = true
99 [dependencies]
1010 ec-core.workspace = true
1111 ec-inflate.workspace = true
12+
13+[dev-dependencies]
14+ec-mp4.workspace = true
15+ec-aac.workspace = true
16+ec-ac3.workspace = true
crates/ec-matroska/tests/matroska.rsmodified+314 -0
@@ -975,3 +975,317 @@ fn real_hdr_film_container_states_no_light_metadata() {
975975 }
976976 assert!(checked, "no video stream found");
977977 }
978+
979+// ===== mkv-vs-mp4 audio A/B (mkv-audio-timing) =====
980+//
981+// The consumer sweep found: same OBS recording's `.mkv` leg scores far below
982+// its sibling `.mp4` leg on channel-0 correlation from t=0, and 5.1 AC-3/E-AC-3
983+// tracks that are only ever carried in Matroska score near zero. These tests
984+// isolate whether that is packet delivery out of `ec-matroska` (order,
985+// duplication, pts) or the shared decoder crate, and which physical channel
986+// our 5.1 decode calls "channel 0".
987+
988+use ec_ac3::Ac3Decoder;
989+use ec_aac::AacDecoder;
990+use ec_core::CodecId;
991+
992+/// Opens whichever container `path` actually is — both crates implement the
993+/// same `Demuxer` trait, so the rest of the harness never has to know which.
994+fn open_any(path: &Path) -> Box<dyn Demuxer> {
995+ use std::io::Read;
996+ let mut head = [0u8; 12];
997+ File::open(path)
998+ .expect("open")
999+ .read_exact(&mut head)
1000+ .expect("read head");
1001+ if ec_mp4::is_mp4(&head) {
1002+ Box::new(ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4 opens"))
1003+ } else {
1004+ Box::new(MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv opens"))
1005+ }
1006+}
1007+
1008+/// The first stream of `codec`'s extradata plus its packets, `(pts, data)`,
1009+/// in the order the container's own demuxer hands them back — capped so a
1010+/// multi-gigabyte recording does not have to be decoded whole.
1011+fn audio_track(path: &Path, codec: CodecId) -> Option<(Option<Vec<u8>>, u32, Vec<(i64, Vec<u8>)>)> {
1012+ let mut d = open_any(path);
1013+ let s = d.streams().iter().find(|s| s.params.codec == codec)?;
1014+ let idx = s.index;
1015+ let extradata = s.params.extradata.as_ref().map(|b| b.to_vec());
1016+ let rate = s.params.audio()?.sample_rate;
1017+ let mut pkts = Vec::new();
1018+ loop {
1019+ match d.next_packet() {
1020+ Ok(p) if p.stream == idx => {
1021+ pkts.push((p.pts.unwrap_or(0), p.data.to_vec()));
1022+ if pkts.len() >= 2_000 {
1023+ break;
1024+ }
1025+ }
1026+ Ok(_) => continue,
1027+ Err(_) => break,
1028+ }
1029+ }
1030+ Some((extradata, rate, pkts))
1031+}
1032+
1033+/// Our AAC decode of a container's access units, interleaved-to-planar.
1034+fn decode_aac(extradata: &[u8], pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1035+ let mut decoder = AacDecoder::with_config_bytes(extradata).expect("AudioSpecificConfig parses");
1036+ let mut planes: Vec<Vec<f32>> = Vec::new();
1037+ for (_, au) in pkts {
1038+ let Ok(frame) = decoder.decode(au, None) else {
1039+ continue;
1040+ };
1041+ let ch = usize::from(frame.channels);
1042+ if ch == 0 {
1043+ continue;
1044+ }
1045+ if planes.is_empty() {
1046+ planes = vec![Vec::new(); ch];
1047+ }
1048+ for (i, v) in frame.samples.iter().enumerate() {
1049+ planes[i % ch].push(*v);
1050+ }
1051+ }
1052+ planes
1053+}
1054+
1055+/// Our AC-3/E-AC-3 decode of a container's frames, interleaved-to-planar.
1056+fn decode_ac3(pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1057+ let mut decoder = Ac3Decoder::new();
1058+ let mut planes: Vec<Vec<f32>> = Vec::new();
1059+ for (_, data) in pkts {
1060+ let Ok(frame) = decoder.decode_frame(data) else {
1061+ continue;
1062+ };
1063+ let ch = frame.channels();
1064+ if ch == 0 {
1065+ continue;
1066+ }
1067+ if planes.is_empty() {
1068+ planes = vec![Vec::new(); ch];
1069+ }
1070+ let samples: Vec<f32> = frame.data[0]
1071+ .chunks_exact(4)
1072+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1073+ .collect();
1074+ for (i, v) in samples.iter().enumerate() {
1075+ planes[i % ch].push(*v);
1076+ }
1077+ }
1078+ planes
1079+}
1080+
1081+fn have_ffmpeg() -> bool {
1082+ Command::new("ffmpeg")
1083+ .arg("-version")
1084+ .output()
1085+ .is_ok_and(|o| o.status.success())
1086+}
1087+
1088+/// ffmpeg's decode of a file's first audio stream, planar by channel.
1089+fn ffmpeg_decode_planar(path: &Path, channels: usize) -> Vec<Vec<f32>> {
1090+ let out = Command::new("ffmpeg")
1091+ .args(["-v", "error", "-i"])
1092+ .arg(path)
1093+ .args([
1094+ "-map", "0:a:0", "-t", "20", "-f", "f32le", "-acodec", "pcm_f32le", "-",
1095+ ])
1096+ .output()
1097+ .expect("ffmpeg runs");
1098+ assert!(
1099+ out.status.success(),
1100+ "ffmpeg decode failed: {}",
1101+ String::from_utf8_lossy(&out.stderr)
1102+ );
1103+ let samples: Vec<f32> = out
1104+ .stdout
1105+ .chunks_exact(4)
1106+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1107+ .collect();
1108+ let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
1109+ for (i, v) in samples.iter().enumerate() {
1110+ planes[i % channels].push(*v);
1111+ }
1112+ planes
1113+}
1114+
1115+fn correlation(a: &[f32], b: &[f32]) -> f64 {
1116+ let n = a.len().min(b.len());
1117+ if n < 1024 {
1118+ return 0.0;
1119+ }
1120+ let (a, b) = (&a[..n], &b[..n]);
1121+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1122+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1123+ let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64);
1124+ for i in 0..n {
1125+ let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
1126+ num += x * y;
1127+ da += x * x;
1128+ db += y * y;
1129+ }
1130+ let den = (da * db).sqrt();
1131+ if den == 0.0 { 0.0 } else { num / den }
1132+}
1133+
1134+/// Best correlation over a bounded lag search from the start of both
1135+/// streams — the whole point here is t=0 alignment, so no whole-file window
1136+/// slide is needed, just enough lag to absorb container/codec delay.
1137+const LAG_MAX: i64 = 4_000;
1138+const WINDOW: usize = 100_000;
1139+
1140+fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
1141+ let mut best_abs = -1.0f64;
1142+ let mut best = (0i64, 0.0f64);
1143+ for lag in -LAG_MAX..=LAG_MAX {
1144+ let (oa, ob) = if lag >= 0 { (0usize, lag as usize) } else { ((-lag) as usize, 0usize) };
1145+ let len = WINDOW.min(ours.len().saturating_sub(oa)).min(theirs.len().saturating_sub(ob));
1146+ if len < 1024 {
1147+ continue;
1148+ }
1149+ let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]);
1150+ if c.abs() > best_abs {
1151+ best_abs = c.abs();
1152+ best = (lag, c);
1153+ }
1154+ }
1155+ best
1156+}
1157+
1158+/// mkv vs mp4: the same recording's AAC stream, decoded through each
1159+/// container's own demux path, ours-vs-ours and each vs ffmpeg. Isolates the
1160+/// consumer sweep's "same channel 0, same track, `.mkv` corr 0.06-0.34 but
1161+/// sibling `.mp4` 0.76-0.92" finding to this crate's packet delivery or to
1162+/// the shared AAC decoder.
1163+///
1164+/// Run with `cargo test -p ec-matroska --test matroska mkv_vs_mp4_aac_pipeline -- --ignored --nocapture`.
1165+#[test]
1166+#[ignore = "reads the real library, mkv-audio-timing A/B"]
1167+fn mkv_vs_mp4_aac_pipeline() {
1168+ if !have_ffmpeg() {
1169+ eprintln!("skipped: no ffmpeg");
1170+ return;
1171+ }
1172+ let obs = Path::new("/home/user/Videos/OBS");
1173+ let stems = [
1174+ "2026-07-25 02-09-04",
1175+ "2026-08-17 01-57-17",
1176+ "2026-08-17 11-01-56",
1177+ ];
1178+ let mut any = false;
1179+ for stem in stems {
1180+ let mkv = obs.join(format!("{stem}.mkv"));
1181+ let mp4 = obs.join(format!("{stem}.mp4"));
1182+ if !mkv.exists() || !mp4.exists() {
1183+ continue;
1184+ }
1185+ any = true;
1186+ println!("=== {stem} ===");
1187+ let (mkv_asc, mkv_rate, mkv_pkts) = audio_track(&mkv, CodecId::Aac).expect("mkv aac track");
1188+ let (mp4_asc, mp4_rate, mp4_pkts) = audio_track(&mp4, CodecId::Aac).expect("mp4 aac track");
1189+ println!(
1190+ "mkv asc={:02x?} rate={mkv_rate} packets={} bytes={}",
1191+ mkv_asc,
1192+ mkv_pkts.len(),
1193+ mkv_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1194+ );
1195+ println!(
1196+ "mp4 asc={:02x?} rate={mp4_rate} packets={} bytes={}",
1197+ mp4_asc,
1198+ mp4_pkts.len(),
1199+ mp4_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1200+ );
1201+ println!(
1202+ "mkv first5 pts = {:?}",
1203+ mkv_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1204+ );
1205+ println!(
1206+ "mp4 first5 pts = {:?}",
1207+ mp4_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1208+ );
1209+ let (mut out_of_order, mut dup) = (0, 0);
1210+ for w in mkv_pkts.windows(2) {
1211+ if w[1].0 < w[0].0 {
1212+ out_of_order += 1;
1213+ }
1214+ if w[1].0 == w[0].0 {
1215+ dup += 1;
1216+ }
1217+ }
1218+ println!("mkv out_of_order={out_of_order} dup_pts={dup}");
1219+
1220+ let mkv_planes = decode_aac(mkv_asc.as_deref().unwrap_or(&[]), &mkv_pkts);
1221+ let mp4_planes = decode_aac(mp4_asc.as_deref().unwrap_or(&[]), &mp4_pkts);
1222+ assert!(
1223+ !mkv_planes.is_empty() && !mp4_planes.is_empty(),
1224+ "{stem}: decode produced no channels (mkv {} ch, mp4 {} ch)",
1225+ mkv_planes.len(),
1226+ mp4_planes.len()
1227+ );
1228+
1229+ let (lag, c_mm) = best_lag_correlation(&mkv_planes[0], &mp4_planes[0]);
1230+ let mkv_ff = ffmpeg_decode_planar(&mkv, mkv_planes.len());
1231+ let mp4_ff = ffmpeg_decode_planar(&mp4, mp4_planes.len());
1232+ let (_, c_mkv_ff) = best_lag_correlation(&mkv_planes[0], &mkv_ff[0]);
1233+ let (_, c_mp4_ff) = best_lag_correlation(&mp4_planes[0], &mp4_ff[0]);
1234+ println!(
1235+ "{stem}: mkv-vs-mp4(ours) corr={c_mm:.4} lag={lag}; mkv-vs-ffmpeg corr={c_mkv_ff:.4}; mp4-vs-ffmpeg corr={c_mp4_ff:.4}"
1236+ );
1237+ }
1238+ assert!(any, "no OBS mkv/mp4 pairs present");
1239+}
1240+
1241+/// The two mkv-only 5.1 real-library rows the consumer sweep flagged
1242+/// (E-AC-3 and AC-3): our decode of every channel against ffmpeg's channel
1243+/// 0, so a channel-order mismatch (mkv hands a different physical channel
1244+/// first than ffmpeg calls "channel 0") shows up as a non-zero-index best
1245+/// match instead of a flat near-zero across all of them.
1246+///
1247+/// Run with `cargo test -p ec-matroska --test matroska mkv_51_channel_order -- --ignored --nocapture`.
1248+#[test]
1249+#[ignore = "reads the real library, mkv-audio-timing A/B"]
1250+fn mkv_51_channel_order() {
1251+ if !have_ffmpeg() {
1252+ eprintln!("skipped: no ffmpeg");
1253+ return;
1254+ }
1255+ let files: [(&str, CodecId); 2] = [
1256+ (
1257+ "/home/user/Downloads/reelf/reelf.mkv",
1258+ CodecId::EAc3,
1259+ ),
1260+ (
1261+ "/home/user/Downloads/reelg/reelg.mkv",
1262+ CodecId::Ac3,
1263+ ),
1264+ ];
1265+ let mut any = false;
1266+ for (path, codec) in files {
1267+ let path = Path::new(path);
1268+ if !path.exists() {
1269+ eprintln!("skipped: {} absent", path.display());
1270+ continue;
1271+ }
1272+ any = true;
1273+ let (_, _rate, pkts) = audio_track(path, codec).expect("audio track");
1274+ println!(
1275+ "{}: first5 pts = {:?}",
1276+ path.file_name().unwrap().to_string_lossy(),
1277+ pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1278+ );
1279+ let planes = decode_ac3(&pkts);
1280+ assert!(!planes.is_empty(), "{}: no channels decoded", path.display());
1281+ let ffref = ffmpeg_decode_planar(path, planes.len());
1282+ for (i, ch) in planes.iter().enumerate() {
1283+ let (lag, c) = best_lag_correlation(ch, &ffref[0]);
1284+ println!(
1285+ "{}: our ch{i} vs ffmpeg ch0 corr={c:.4} lag={lag}",
1286+ path.file_name().unwrap().to_string_lossy()
1287+ );
1288+ }
1289+ }
1290+ assert!(any, "no 5.1 mkv fixtures present");
1291+}
crates/ec-mp3/src/lib.rsmodified+13 -5
@@ -74,8 +74,17 @@ impl Mp3Decoder {
7474 })
7575 }
7676
77- fn take(&mut self) {
78- while let Ok(frame) = self.reader.next_frame() {
77+ // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof`
78+ // just mean "nothing left to take yet" and end the loop quietly; any
79+ // other error (corrupt CRC, unsupported layer) is real and must reach
80+ // the caller rather than vanish here.
81+ fn take(&mut self) -> Result<()> {
82+ loop {
83+ let frame = match self.reader.next_frame() {
84+ Ok(frame) => frame,
85+ Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
86+ Err(e) => return Err(e),
87+ };
7988 if frame.samples.is_empty() {
8089 continue;
8190 }
@@ -111,8 +120,7 @@ impl Decoder for Mp3Decoder {
111120
112121 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
113122 self.reader.push(packet.data.as_ref());
114- self.take();
115- Ok(())
123+ self.take()
116124 }
117125
118126 fn receive_frame(&mut self) -> Result<Frame> {
@@ -127,7 +135,7 @@ impl Decoder for Mp3Decoder {
127135 }
128136
129137 fn flush(&mut self) -> Result<()> {
130- self.take();
138+ self.take()?;
131139 self.drained = true;
132140 Ok(())
133141 }
crates/ec-probe/tests/library.rsmodified+69 -0
@@ -259,3 +259,72 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
259259 .map(|l| l.trim().to_string())
260260 .collect()
261261 }
262+
263+/// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole
264+/// image ahead of the first frame; opening must skip the tag by its own
265+/// syncsafe size and never confuse the codec/window prefixes it hunts for
266+/// sync in with that image's bytes. Matched against ffmpeg's own decode of
267+/// the same first second, not just "it opened".
268+#[test]
269+fn a_cover_art_tagged_mp3_opens() {
270+ let path = Path::new("/home/user/Music/reeli.mp3");
271+ if !path.exists() {
272+ eprintln!("file not present, skipping");
273+ return;
274+ }
275+ let mut reader = Reader::open(path).expect("open");
276+ let audio = reader
277+ .default_stream(MediaType::Audio)
278+ .cloned()
279+ .expect("audio stream");
280+ let mut decoder = reader.make_decoder(audio.index).expect("decoder");
281+ let rate = decoder.sample_rate();
282+ let channels = decoder.channels().max(1) as u32;
283+ // The raw decoder hands back every sample the bitstream carries,
284+ // including the LAME/Xing encoder's lead-in; `initial_padding` (parsed
285+ // from that header) is how many of them a player is meant to drop
286+ // (ec-core registry.rs: "audible length is duration - initial_padding").
287+ // ffmpeg does that trim itself before writing PCM, so match it here.
288+ let lead_in = audio.initial_padding * channels;
289+ let mut ours = Vec::new();
290+ let mut scratch = Vec::new();
291+ let mut n = 0;
292+ while (ours.len() as u32) < rate + lead_in {
293+ let packet = match reader.next_packet() {
294+ Ok(p) => p,
295+ Err(e) => panic!("next_packet after {n} packets, {} samples: {e}", ours.len()),
296+ };
297+ n += 1;
298+ if packet.stream != audio.index {
299+ continue;
300+ }
301+ decoder.decode(&packet, &mut scratch).expect("decode 1s");
302+ ours.extend_from_slice(&scratch);
303+ }
304+ let ours = &ours[lead_in as usize..];
305+ assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");
306+
307+ let out = Command::new("ffmpeg")
308+ .args(["-v", "error", "-t", "1", "-i"])
309+ .arg(path)
310+ .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
311+ .output()
312+ .expect("ffmpeg runs");
313+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
314+ let theirs: Vec<f32> = out
315+ .stdout
316+ .chunks_exact(4)
317+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
318+ .collect();
319+
320+ let n = ours.len().min(theirs.len());
321+ let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64);
322+ for i in 0..n {
323+ let (a, b) = (ours[i] as f64, theirs[i] as f64);
324+ num += a * b;
325+ a2 += a * a;
326+ b2 += b * b;
327+ }
328+ let corr = num / (a2.sqrt() * b2.sqrt()).max(1e-12);
329+ assert!(corr >= 0.999, "corr vs ffmpeg = {corr}");
330+}
crates/ec-va/src/vpp.rsmodified+49 -0
@@ -95,6 +95,55 @@ impl Vpp {
9595 Ok(surface)
9696 }
9797
98+ /// Convert `source` into `dest` like [`Vpp::convert`], but reading only
99+ /// `source_region` of `source` and writing only `dest_region` of `dest` —
100+ /// no scaling (both regions are the same size in every caller today),
101+ /// just a placement: the pixels outside `dest_region` are left exactly as
102+ /// `dest` already had them. This is how a visible picture smaller than
103+ /// its block-aligned coded surface (e.g. a 2160-tall HEVC source, whose
104+ /// coded height rounds to 2176) lands inside a differently-padded
105+ /// destination without a resize.
106+ pub fn convert_region(
107+ &self,
108+ source: &Arc<Surface>,
109+ source_region: (u32, u32, u32, u32),
110+ dest: Arc<Surface>,
111+ dest_region: (u32, u32, u32, u32),
112+ ) -> Result<Arc<Surface>> {
113+ let sr = sys::VARectangle {
114+ x: source_region.0 as i16,
115+ y: source_region.1 as i16,
116+ width: source_region.2 as u16,
117+ height: source_region.3 as u16,
118+ };
119+ let dr = sys::VARectangle {
120+ x: dest_region.0 as i16,
121+ y: dest_region.1 as i16,
122+ width: dest_region.2 as u16,
123+ height: dest_region.3 as u16,
124+ };
125+ let param = sys::VAProcPipelineParameterBuffer {
126+ surface: source.id(),
127+ surface_region: &sr,
128+ output_region: &dr,
129+ ..Default::default()
130+ };
131+ // SAFETY: `surface_region`/`output_region` point at `sr`/`dr`, which
132+ // outlive this call (built here, read only while `Buffer::from_param`
133+ // constructs the driver buffer below); otherwise identical to
134+ // `convert`'s safety argument.
135+ let buffer = unsafe {
136+ Buffer::from_param(&self.context, sys::VAProcPipelineParameterBufferType, &param)?
137+ };
138+ let surface = Picture::new(&self.context, dest)
139+ .begin()?
140+ .render(buffer)?
141+ .end()?
142+ .sync()?
143+ .into_surface();
144+ Ok(surface)
145+ }
146+
98147 fn context_id(&self) -> sys::VAContextID {
99148 // `Context` does not expose its raw id outside the crate; VPP needs
100149 // it for `vaQueryVideoProcFilters`, which has no typestate-protected
scripts/gen-fixtures.shmodified+18 -0
@@ -120,6 +120,24 @@ for lspec in "stereo|2" "5.1|6"; do
120120 "${AIN[@]}" "${AMAP[@]}" -c:a alac -sample_fmt s32p -ar 48000
121121 done
122122
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+
123141 # Matroska-carried audio: what the probe hands to the Matroska reader rather
124142 # than parsing itself. One per codec family that has a Matroska mapping.
125143 for spec in "aac|-c:a aac -b:a 160k" "flac|-c:a flac" "opus|-c:a libopus -b:a 160k"; do
scripts/scan-real-library.shmodified+1 -1
@@ -81,7 +81,7 @@ nerr=0
8181 "${vpix:--}" "${vbits:--}" "${acodecs:--}" "${duration:--}" \
8282 "$(stat -c %s -- "$f")"
8383 n=$((n + 1))
84- done < <(find "${DIRS[@]}" -type f \( "${find_args[@]}" \) -print0 2>/dev/null)
84+ done < <(find "${DIRS[@]}" -type f \( "${find_args[@]}" \) ! -name "*.export*.mp4" -print0 2>/dev/null)
8585 } >"$tmp"
8686
8787 mv -- "$tmp" "$OUT"
shims/symphonia/tests/edith_surface.rsmodified+65 -0
@@ -280,3 +280,68 @@ fn opus_has_a_decoder_in_the_registry() {
280280 "the refusal names the codec: {refusal}"
281281 );
282282 }
283+
284+/// Regression for `open: NeedMore` on a real mp3 whose ID3v2 header carries a
285+/// large APIC cover-art picture and whose tail carries an ID3v1 `TAG` block:
286+/// the probe must skip both rather than reading a bounded head short of the
287+/// first mp3 frame sync, or getting confused reading a 128-byte tail as audio.
288+/// Built out of a plain mp3 fixture wrapped in a synthetic 2 MB ID3v2 APIC
289+/// header and an ID3v1 tail, so this needs no real file on disk.
290+#[test]
291+fn cover_art_and_id3v1_tail_do_not_stop_the_probe() {
292+ let raw = std::fs::read(fixtures().join("mp3-stereo-48000.mp3")).expect("fixture mp3");
293+ // A 2 MB ID3v2.3 tag: one oversized `APIC` frame of filler bytes. The
294+ // probe only needs to skip past the tag's declared size, so the frame
295+ // body's content does not matter.
296+ let apic_body_len = 2_000_000usize;
297+ let mut id3 = Vec::new();
298+ id3.extend_from_slice(b"ID3");
299+ id3.extend_from_slice(&[3, 0, 0]); // version 2.3.0, no flags
300+ let frame_len = apic_body_len as u32;
301+ let tag_size = 10 + apic_body_len as u32; // one frame header (10) + body
302+ id3.extend_from_slice(&syncsafe(tag_size));
303+ id3.extend_from_slice(b"APIC");
304+ id3.extend_from_slice(&frame_len.to_be_bytes());
305+ id3.extend_from_slice(&[0, 0]); // frame flags
306+ id3.extend(std::iter::repeat_n(0u8, apic_body_len));
307+
308+ let mut id3v1 = vec![0u8; 128];
309+ id3v1[0..3].copy_from_slice(b"TAG");
310+
311+ let mut bytes = id3;
312+ bytes.extend_from_slice(&raw);
313+ bytes.extend_from_slice(&id3v1);
314+
315+ let path = std::env::temp_dir().join("edith-cover-art-id3v1-tail.mp3");
316+ std::fs::write(&path, &bytes).expect("write synthetic mp3");
317+
318+ let mut track = SymTrack::open(&path).expect("open past the ID3v2 APIC and ID3v1 tail");
319+ assert_eq!(track.codec, "mp3");
320+ let mut decoder = track.decoder();
321+ let mut out = Vec::new();
322+ let mut decoded_packets = 0;
323+ while let Some(packet) = track.reader.next_packet().expect("demux") {
324+ if packet.track_id != track.track_id {
325+ continue;
326+ }
327+ decoder
328+ .decode(&packet)
329+ .expect("decode")
330+ .copy_to_vec_interleaved::<f32>(&mut out);
331+ decoded_packets += 1;
332+ }
333+ assert!(decoded_packets > 0, "no audio packets decoded");
334+ assert!(!out.is_empty(), "no samples decoded");
335+ let _ = std::fs::remove_file(&path);
336+}
337+
338+/// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear),
339+/// big-endian.
340+fn syncsafe(mut n: u32) -> [u8; 4] {
341+ let mut out = [0u8; 4];
342+ for b in out.iter_mut().rev() {
343+ *b = (n & 0x7f) as u8;
344+ n >>= 7;
345+ }
346+ out
347+}