diff --git a/Cargo.lock b/Cargo.lock index b11de139..dca8720c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -347,8 +347,11 @@ dependencies = [ name = "ec-matroska" version = "0.1.0" dependencies = [ + "ec-aac", + "ec-ac3", "ec-core", "ec-inflate", + "ec-mp4", ] [[package]] diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 5f4e79fe..2d636189 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); // §4.6.18.1: SBR is never applied to the LFE channel (no // FIL/SBR payload follows it), so it must not become a @@ -748,6 +806,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)); } @@ -961,6 +1022,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/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 317b1b7c..fae8fa61 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -352,9 +352,18 @@ impl Encoder { /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate /// encodes, and no VPP conversion this crate builds, has a destination /// for a 12-bit source. - /// - `frame`'s coded size does not match this encoder's: the surface - /// formats have to agree for the driver to read one as the other, and - /// the VPP conversion pass (when one runs) does not resize. + /// + /// A `frame` whose coded size does not match this encoder's (a common + /// case: HEVC block-rounds to 32, so a 3840x2160 source's 2160 stays + /// unrounded while the encoder's coded height becomes 2176) is not + /// refused — it goes through the same VPP pool a 10-bit source uses, + /// placed by explicit region rather than a whole-surface convert: only + /// `frame.display_size` is read from the source and written into the + /// destination at `(0, 0)`, so the padding rows/columns beyond it are + /// never touched by the copy. Those padding pixels are still fed to the + /// encoder as part of the coded surface, so the pool is painted black + /// once, on creation, rather than left as whatever the driver's fresh + /// allocation happened to contain. pub fn encode_frame( &mut self, frame: &crate::frame::Frame, @@ -373,28 +382,33 @@ impl Encoder { "encode_frame: the frame was decoded on a different Display than this encoder", )); } - if frame.coded_size != self.coded_size { - return Err(Error::config(format!( - "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}", - self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1 - ))); - } - let source = if frame.bit_depth == 10 { - self.nv12_from_p010(frame.surface())? + let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { + self.vpp_into_pool(frame.surface(), frame.display_size)? } else { Arc::clone(frame.surface()) }; self.encode_surface(source, meta) } - /// Convert a P010 surface into this encoder's coded size, in NV12, on the - /// GPU. Builds the VPP pipeline and its two-surface pool on first use. - fn nv12_from_p010(&mut self, source: &Arc) -> Result> { + /// Place a source surface's visible rect into this encoder's coded size, + /// in NV12, on the GPU: a whole-surface convert when the source is + /// already the encoder's coded size (the common 10-bit case), a region + /// copy/convert otherwise. Builds the VPP pipeline and its two-surface + /// pool on first use, painting the pool black so any padding beyond + /// `display_size` a region copy never touches is deterministic. + fn vpp_into_pool( + &mut self, + source: &Arc, + display_size: (u32, u32), + ) -> Result> { if self.vpp.is_none() { let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); let display = self.context.display(); let surfaces = Surface::create_pool(display, &spec, 2)?; + for s in &surfaces { + Self::fill_black(s, self.coded_size)?; + } let vpp = Vpp::new( display, sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10, @@ -405,11 +419,32 @@ impl Encoder { } let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]); self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); - Ok(self - .vpp - .as_ref() - .expect("just built above if it was None") - .convert(source, dest)?) + let vpp = self.vpp.as_ref().expect("just built above if it was None"); + if display_size == self.coded_size { + Ok(vpp.convert(source, dest)?) + } else { + let rect = (0, 0, display_size.0, display_size.1); + Ok(vpp.convert_region(source, rect, dest, rect)?) + } + } + + /// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the + /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a + /// region copy's untouched padding reads the same deterministic value on + /// every driver instead of whatever the fresh allocation contained. + fn fill_black(surface: &Arc, size: (u32, u32)) -> Result<()> { + let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; + { + let mut mapped = image.map()?; + if let Some(y) = mapped.plane_mut(0) { + y.fill(16); + } + if let Some(uv) = mapped.plane_mut(1) { + uv.fill(128); + } + } + surface.write_from(&image, size.0, size.1)?; + Ok(()) } /// Shared submission path for [`Encoder::encode`] and diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 91904af6..da88096c 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -1531,13 +1531,14 @@ fn encode_frame_accepts_p010_via_vpp() { }; // This film's HEVC SPS `pic_height_in_luma_samples` is 2160, which is a - // multiple of the H.264 encode block size (16) but not the HEVC one - // (32, next_multiple_of gives 2176) — `encode_frame` refuses that - // mismatch by documented design ("frame's coded size does not match - // this encoder's ... the VPP conversion pass does not resize") rather - // than silently stretching the picture, so the HEVC target is expected - // to be *refused* here, not to round-trip; only H.264 gets the full - // encode/decode/PSNR comparison. + // multiple of the H.264 encode block size (16) but not the HEVC one (32, + // next_multiple_of gives 2176) — `encode_frame` no longer refuses that + // mismatch: it routes through the VPP pool by explicit region + // (`Encoder::vpp_into_pool`), so both targets get the full + // encode/decode/PSNR comparison, and the HEVC one additionally gets an + // `ffprobe` check that the visible size in the produced stream is still + // 3840x2160 (the encoder's own cropping, not a VPP resize). + let (mut w, mut h) = (0u32, 0u32); for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); let mut zc_stream = Vec::new(); @@ -1545,13 +1546,13 @@ fn encode_frame_accepts_p010_via_vpp() { let mut count = 0i64; let mut zero_copy: Option = None; let mut cpu_path: Option = None; - let mut refused = false; + let refused = false; decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { if refused { return; } - let (w, h) = frame.display_size; + (w, h) = frame.display_size; let zero_copy = zero_copy.get_or_insert_with(|| { let mut cfg = EncoderConfig::new(target, w, h); cfg.gop_size = 30; @@ -1568,22 +1569,10 @@ fn encode_frame_accepts_p010_via_vpp() { timestamp: count, force_keyframe: false, }; - match zero_copy.encode_frame(&frame, meta) { - Ok(zc) => zc_stream.extend_from_slice(&zc.data), - Err(e) if target == EncCodec::H265 => { - println!( - "{target:?}: encode_frame refused as documented (block size vs SPS \ - pic height): {e}" - ); - assert!( - e.to_string().contains("encoder surfaces are"), - "unexpected refusal reason: {e}" - ); - refused = true; - return; - } - Err(e) => panic!("encode_frame (zero copy, P010 via VPP): {e}"), - } + let zc = zero_copy + .encode_frame(&frame, meta) + .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)"); + zc_stream.extend_from_slice(&zc.data); let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); cpu_stream.extend_from_slice(&cpu.data); @@ -1629,6 +1618,35 @@ fn encode_frame_accepts_p010_via_vpp() { println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB"); assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path"); assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path"); + + // The size-mismatch route (HEVC: 2160 visible vs 2176 coded) places + // the picture by VPP region rather than encoder cropping alone, so + // confirm the encoder's own SPS conformance window still reports the + // real 3840x2160 — not the padded 2176 the coded surface carries. + let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}")); + std::fs::create_dir_all(&dir).expect("temp dir"); + let path = dir.join(match target { + EncCodec::H264 => "out.264", + EncCodec::H265 => "out.265", + EncCodec::Av1 => "out.obu", + }); + std::fs::write(&path, &zc_stream).expect("write bitstream"); + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe runs"); + let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); + assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}"); } } @@ -1637,12 +1655,10 @@ fn encode_frame_accepts_p010_via_vpp() { /// says whether the VPP conversion is cheap enough to keep the zero-copy path /// meaningfully faster than reading the frame back to system memory. /// -/// Targets H.264: this film's HEVC SPS `pic_height_in_luma_samples` (2160) -/// is not a multiple of this crate's HEVC encode block size (32), so -/// `encode_frame` refuses the HEVC target on this file by documented design -/// (see `encode_frame_accepts_p010_via_vpp`) — 2160 *is* a multiple of the -/// H.264 block size (16), so H.264 is the target that actually exercises the -/// zero-copy path on this real source. +/// Both H.264 (coded size already matches this film's 2160 visible height, +/// so the P010->NV12 convert is whole-surface) and HEVC (2160 is not a +/// multiple of the 32-block HEVC coded size, so `encode_frame` also takes +/// the VPP region-copy route — `Encoder::vpp_into_pool`) get a bench row. #[test] fn p010_zero_copy_encode_is_realtime() { let Some(display) = display() else { return }; @@ -1659,66 +1675,78 @@ fn p010_zero_copy_encode_is_realtime() { let units = split_access_units(&data, Codec::H265); assert!(units.len() > limit, "film clip too short for {limit} frames"); - println!("{:<24} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); - let mut zc_median = None; - let mut cpu_median = None; - for (name, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut encoder: Option = None; - let mut durations: Vec = Vec::new(); - let mut count = 0i64; - 'outer: for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - let (w, h) = frame.display_size; - let encoder = encoder.get_or_insert_with(|| { - let mut cfg = EncoderConfig::new(EncCodec::H264, w, h); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - Encoder::new(&display, cfg).expect("encoder opens") - }); - let meta = FrameMetadata { - timestamp: count, - force_keyframe: false, - }; - let t0 = Instant::now(); - if zero_copy { - encoder.encode_frame(&frame, meta).expect("encode_frame"); - } else { - let i420 = frame.to_i420().expect("readback"); - encoder.encode(&i420, meta).expect("encode"); - } - durations.push(t0.elapsed()); - count += 1; - if durations.len() >= limit { - break 'outer; + println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); + // (target, zero-copy median ms, CPU-path median ms) rows, filled in order. + let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new(); + for target in [EncCodec::H264, EncCodec::H265] { + let mut zc_median = None; + let mut cpu_median = None; + for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { + let name = format!("{target:?} {label}"); + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut encoder: Option = None; + let mut durations: Vec = Vec::new(); + let mut count = 0i64; + 'outer: for (i, unit) in units.iter().enumerate() { + decoder.decode(unit, i as i64).expect("decode"); + while let Some(frame) = decoder.next_frame() { + let (w, h) = frame.display_size; + let encoder = encoder.get_or_insert_with(|| { + let mut cfg = EncoderConfig::new(target, w, h); + cfg.gop_size = 30; + cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; + Encoder::new(&display, cfg).expect("encoder opens") + }); + let meta = FrameMetadata { + timestamp: count, + force_keyframe: false, + }; + let t0 = Instant::now(); + if zero_copy { + encoder.encode_frame(&frame, meta).expect("encode_frame"); + } else { + let i420 = frame.to_i420().expect("readback"); + encoder.encode(&i420, meta).expect("encode"); + } + durations.push(t0.elapsed()); + count += 1; + if durations.len() >= limit { + break 'outer; + } } } + assert!( + durations.len() >= limit, + "{name}: only {} of {limit} frames encoded", + durations.len() + ); + durations.sort(); + let ms = |d: Duration| d.as_secs_f64() * 1000.0; + let median = ms(durations[durations.len() / 2]); + let min = ms(durations[0]); + let max = ms(durations[durations.len() - 1]); + println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}"); + if zero_copy { + zc_median = Some(median); + } else { + cpu_median = Some(median); + } } + rows.push(( + target, + zc_median.expect("zero-copy phase ran"), + cpu_median.expect("CPU-path phase ran"), + )); + } + for (target, zc, cpu) in rows { + println!( + "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})" + ); assert!( - durations.len() >= limit, - "{name}: only {} of {limit} frames encoded", - durations.len() + zc <= 20.0, + "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" ); - durations.sort(); - let ms = |d: Duration| d.as_secs_f64() * 1000.0; - let median = ms(durations[durations.len() / 2]); - let min = ms(durations[0]); - let max = ms(durations[durations.len() - 1]); - println!("{name:<24} {median:>10.2} {min:>10.2} {max:>10.2}"); - if zero_copy { - zc_median = Some(median); - } else { - cpu_median = Some(median); - } } - let zc = zc_median.expect("zero-copy phase ran"); - let cpu = cpu_median.expect("CPU-path phase ran"); - println!("target: decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})"); - assert!( - zc <= 20.0, - "decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" - ); } /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in diff --git a/crates/ec-matroska/Cargo.toml b/crates/ec-matroska/Cargo.toml index 271df6f1..fe7329f5 100644 --- a/crates/ec-matroska/Cargo.toml +++ b/crates/ec-matroska/Cargo.toml @@ -9,3 +9,8 @@ authors.workspace = true [dependencies] ec-core.workspace = true ec-inflate.workspace = true + +[dev-dependencies] +ec-mp4.workspace = true +ec-aac.workspace = true +ec-ac3.workspace = true diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 106aa6b9..b8ea327c 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -975,3 +975,317 @@ fn real_hdr_film_container_states_no_light_metadata() { } assert!(checked, "no video stream found"); } + +// ===== mkv-vs-mp4 audio A/B (mkv-audio-timing) ===== +// +// The consumer sweep found: same OBS recording's `.mkv` leg scores far below +// its sibling `.mp4` leg on channel-0 correlation from t=0, and 5.1 AC-3/E-AC-3 +// tracks that are only ever carried in Matroska score near zero. These tests +// isolate whether that is packet delivery out of `ec-matroska` (order, +// duplication, pts) or the shared decoder crate, and which physical channel +// our 5.1 decode calls "channel 0". + +use ec_ac3::Ac3Decoder; +use ec_aac::AacDecoder; +use ec_core::CodecId; + +/// Opens whichever container `path` actually is — both crates implement the +/// same `Demuxer` trait, so the rest of the harness never has to know which. +fn open_any(path: &Path) -> Box { + use std::io::Read; + let mut head = [0u8; 12]; + File::open(path) + .expect("open") + .read_exact(&mut head) + .expect("read head"); + if ec_mp4::is_mp4(&head) { + Box::new(ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4 opens")) + } else { + Box::new(MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv opens")) + } +} + +/// The first stream of `codec`'s extradata plus its packets, `(pts, data)`, +/// in the order the container's own demuxer hands them back — capped so a +/// multi-gigabyte recording does not have to be decoded whole. +fn audio_track(path: &Path, codec: CodecId) -> Option<(Option>, u32, Vec<(i64, Vec)>)> { + let mut d = open_any(path); + let s = d.streams().iter().find(|s| s.params.codec == codec)?; + let idx = s.index; + let extradata = s.params.extradata.as_ref().map(|b| b.to_vec()); + let rate = s.params.audio()?.sample_rate; + let mut pkts = Vec::new(); + loop { + match d.next_packet() { + Ok(p) if p.stream == idx => { + pkts.push((p.pts.unwrap_or(0), p.data.to_vec())); + if pkts.len() >= 2_000 { + break; + } + } + Ok(_) => continue, + Err(_) => break, + } + } + Some((extradata, rate, pkts)) +} + +/// Our AAC decode of a container's access units, interleaved-to-planar. +fn decode_aac(extradata: &[u8], pkts: &[(i64, Vec)]) -> Vec> { + let mut decoder = AacDecoder::with_config_bytes(extradata).expect("AudioSpecificConfig parses"); + let mut planes: Vec> = Vec::new(); + for (_, au) in pkts { + let Ok(frame) = decoder.decode(au, None) else { + 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); + } + } + planes +} + +/// Our AC-3/E-AC-3 decode of a container's frames, interleaved-to-planar. +fn decode_ac3(pkts: &[(i64, Vec)]) -> Vec> { + let mut decoder = Ac3Decoder::new(); + let mut planes: Vec> = Vec::new(); + for (_, data) in pkts { + let Ok(frame) = decoder.decode_frame(data) else { + continue; + }; + let ch = frame.channels(); + if ch == 0 { + continue; + } + if planes.is_empty() { + planes = vec![Vec::new(); ch]; + } + let samples: Vec = frame.data[0] + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + for (i, v) in samples.iter().enumerate() { + planes[i % ch].push(*v); + } + } + planes +} + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .is_ok_and(|o| o.status.success()) +} + +/// ffmpeg's decode of a file's first audio stream, planar by channel. +fn ffmpeg_decode_planar(path: &Path, channels: usize) -> Vec> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-map", "0:a:0", "-t", "20", "-f", "f32le", "-acodec", "pcm_f32le", "-", + ]) + .output() + .expect("ffmpeg runs"); + assert!( + out.status.success(), + "ffmpeg decode failed: {}", + 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 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 (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); + num += x * y; + da += x * x; + db += y * y; + } + let den = (da * db).sqrt(); + if den == 0.0 { 0.0 } else { num / den } +} + +/// Best correlation over a bounded lag search from the start of both +/// streams — the whole point here is t=0 alignment, so no whole-file window +/// slide is needed, just enough lag to absorb container/codec delay. +const LAG_MAX: i64 = 4_000; +const WINDOW: usize = 100_000; + +fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { + let mut best_abs = -1.0f64; + let mut best = (0i64, 0.0f64); + for lag in -LAG_MAX..=LAG_MAX { + let (oa, ob) = if lag >= 0 { (0usize, lag as usize) } else { ((-lag) as usize, 0usize) }; + let len = WINDOW.min(ours.len().saturating_sub(oa)).min(theirs.len().saturating_sub(ob)); + if len < 1024 { + continue; + } + let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]); + if c.abs() > best_abs { + best_abs = c.abs(); + best = (lag, c); + } + } + best +} + +/// mkv vs mp4: the same recording's AAC stream, decoded through each +/// container's own demux path, ours-vs-ours and each vs ffmpeg. Isolates the +/// consumer sweep's "same channel 0, same track, `.mkv` corr 0.06-0.34 but +/// sibling `.mp4` 0.76-0.92" finding to this crate's packet delivery or to +/// the shared AAC decoder. +/// +/// Run with `cargo test -p ec-matroska --test matroska mkv_vs_mp4_aac_pipeline -- --ignored --nocapture`. +#[test] +#[ignore = "reads the real library, mkv-audio-timing A/B"] +fn mkv_vs_mp4_aac_pipeline() { + if !have_ffmpeg() { + eprintln!("skipped: no ffmpeg"); + return; + } + let obs = Path::new("/home/user/Videos/OBS"); + let stems = [ + "2026-07-25 02-09-04", + "2026-08-17 01-57-17", + "2026-08-17 11-01-56", + ]; + let mut any = false; + for stem in stems { + let mkv = obs.join(format!("{stem}.mkv")); + let mp4 = obs.join(format!("{stem}.mp4")); + if !mkv.exists() || !mp4.exists() { + continue; + } + any = true; + println!("=== {stem} ==="); + let (mkv_asc, mkv_rate, mkv_pkts) = audio_track(&mkv, CodecId::Aac).expect("mkv aac track"); + let (mp4_asc, mp4_rate, mp4_pkts) = audio_track(&mp4, CodecId::Aac).expect("mp4 aac track"); + println!( + "mkv asc={:02x?} rate={mkv_rate} packets={} bytes={}", + mkv_asc, + mkv_pkts.len(), + mkv_pkts.iter().map(|(_, d)| d.len()).sum::() + ); + println!( + "mp4 asc={:02x?} rate={mp4_rate} packets={} bytes={}", + mp4_asc, + mp4_pkts.len(), + mp4_pkts.iter().map(|(_, d)| d.len()).sum::() + ); + println!( + "mkv first5 pts = {:?}", + mkv_pkts.iter().take(5).map(|(p, _)| *p).collect::>() + ); + println!( + "mp4 first5 pts = {:?}", + mp4_pkts.iter().take(5).map(|(p, _)| *p).collect::>() + ); + let (mut out_of_order, mut dup) = (0, 0); + for w in mkv_pkts.windows(2) { + if w[1].0 < w[0].0 { + out_of_order += 1; + } + if w[1].0 == w[0].0 { + dup += 1; + } + } + println!("mkv out_of_order={out_of_order} dup_pts={dup}"); + + let mkv_planes = decode_aac(mkv_asc.as_deref().unwrap_or(&[]), &mkv_pkts); + let mp4_planes = decode_aac(mp4_asc.as_deref().unwrap_or(&[]), &mp4_pkts); + assert!( + !mkv_planes.is_empty() && !mp4_planes.is_empty(), + "{stem}: decode produced no channels (mkv {} ch, mp4 {} ch)", + mkv_planes.len(), + mp4_planes.len() + ); + + let (lag, c_mm) = best_lag_correlation(&mkv_planes[0], &mp4_planes[0]); + let mkv_ff = ffmpeg_decode_planar(&mkv, mkv_planes.len()); + let mp4_ff = ffmpeg_decode_planar(&mp4, mp4_planes.len()); + let (_, c_mkv_ff) = best_lag_correlation(&mkv_planes[0], &mkv_ff[0]); + let (_, c_mp4_ff) = best_lag_correlation(&mp4_planes[0], &mp4_ff[0]); + println!( + "{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}" + ); + } + assert!(any, "no OBS mkv/mp4 pairs present"); +} + +/// The two mkv-only 5.1 real-library rows the consumer sweep flagged +/// (E-AC-3 and AC-3): our decode of every channel against ffmpeg's channel +/// 0, so a channel-order mismatch (mkv hands a different physical channel +/// first than ffmpeg calls "channel 0") shows up as a non-zero-index best +/// match instead of a flat near-zero across all of them. +/// +/// Run with `cargo test -p ec-matroska --test matroska mkv_51_channel_order -- --ignored --nocapture`. +#[test] +#[ignore = "reads the real library, mkv-audio-timing A/B"] +fn mkv_51_channel_order() { + if !have_ffmpeg() { + eprintln!("skipped: no ffmpeg"); + return; + } + let files: [(&str, CodecId); 2] = [ + ( + "/home/user/Downloads/reelf/reelf.mkv", + CodecId::EAc3, + ), + ( + "/home/user/Downloads/reelg/reelg.mkv", + CodecId::Ac3, + ), + ]; + let mut any = false; + for (path, codec) in files { + let path = Path::new(path); + if !path.exists() { + eprintln!("skipped: {} absent", path.display()); + continue; + } + any = true; + let (_, _rate, pkts) = audio_track(path, codec).expect("audio track"); + println!( + "{}: first5 pts = {:?}", + path.file_name().unwrap().to_string_lossy(), + pkts.iter().take(5).map(|(p, _)| *p).collect::>() + ); + let planes = decode_ac3(&pkts); + assert!(!planes.is_empty(), "{}: no channels decoded", path.display()); + let ffref = ffmpeg_decode_planar(path, planes.len()); + for (i, ch) in planes.iter().enumerate() { + let (lag, c) = best_lag_correlation(ch, &ffref[0]); + println!( + "{}: our ch{i} vs ffmpeg ch0 corr={c:.4} lag={lag}", + path.file_name().unwrap().to_string_lossy() + ); + } + } + assert!(any, "no 5.1 mkv fixtures present"); +} diff --git a/crates/ec-mp3/src/lib.rs b/crates/ec-mp3/src/lib.rs index fd966553..7a32715a 100644 --- a/crates/ec-mp3/src/lib.rs +++ b/crates/ec-mp3/src/lib.rs @@ -74,8 +74,17 @@ impl Mp3Decoder { }) } - fn take(&mut self) { - while let Ok(frame) = self.reader.next_frame() { + // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof` + // just mean "nothing left to take yet" and end the loop quietly; any + // other error (corrupt CRC, unsupported layer) is real and must reach + // the caller rather than vanish here. + fn take(&mut self) -> Result<()> { + loop { + let frame = match self.reader.next_frame() { + Ok(frame) => frame, + Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), + Err(e) => return Err(e), + }; if frame.samples.is_empty() { continue; } @@ -111,8 +120,7 @@ impl Decoder for Mp3Decoder { fn send_packet(&mut self, packet: &Packet) -> Result<()> { self.reader.push(packet.data.as_ref()); - self.take(); - Ok(()) + self.take() } fn receive_frame(&mut self) -> Result { @@ -127,7 +135,7 @@ impl Decoder for Mp3Decoder { } fn flush(&mut self) -> Result<()> { - self.take(); + self.take()?; self.drained = true; Ok(()) } diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index 4337e1d0..b5b5ea12 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -259,3 +259,72 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec { .map(|l| l.trim().to_string()) .collect() } + +/// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole +/// image ahead of the first frame; opening must skip the tag by its own +/// syncsafe size and never confuse the codec/window prefixes it hunts for +/// sync in with that image's bytes. Matched against ffmpeg's own decode of +/// the same first second, not just "it opened". +#[test] +fn a_cover_art_tagged_mp3_opens() { + let path = Path::new("/home/user/Music/reeli.mp3"); + if !path.exists() { + eprintln!("file not present, skipping"); + return; + } + let mut reader = Reader::open(path).expect("open"); + let audio = reader + .default_stream(MediaType::Audio) + .cloned() + .expect("audio stream"); + let mut decoder = reader.make_decoder(audio.index).expect("decoder"); + let rate = decoder.sample_rate(); + let channels = decoder.channels().max(1) as u32; + // The raw decoder hands back every sample the bitstream carries, + // including the LAME/Xing encoder's lead-in; `initial_padding` (parsed + // from that header) is how many of them a player is meant to drop + // (ec-core registry.rs: "audible length is duration - initial_padding"). + // ffmpeg does that trim itself before writing PCM, so match it here. + let lead_in = audio.initial_padding * channels; + let mut ours = Vec::new(); + let mut scratch = Vec::new(); + let mut n = 0; + while (ours.len() as u32) < rate + lead_in { + let packet = match reader.next_packet() { + Ok(p) => p, + Err(e) => panic!("next_packet after {n} packets, {} samples: {e}", ours.len()), + }; + n += 1; + if packet.stream != audio.index { + continue; + } + decoder.decode(&packet, &mut scratch).expect("decode 1s"); + ours.extend_from_slice(&scratch); + } + let ours = &ours[lead_in as usize..]; + assert!(ours.len() as u32 >= rate / 2, "decoded too little audio"); + + let out = Command::new("ffmpeg") + .args(["-v", "error", "-t", "1", "-i"]) + .arg(path) + .args(["-map", "0:a:0", "-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(); + + let n = ours.len().min(theirs.len()); + let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + let (a, b) = (ours[i] as f64, theirs[i] as f64); + num += a * b; + a2 += a * a; + b2 += b * b; + } + let corr = num / (a2.sqrt() * b2.sqrt()).max(1e-12); + assert!(corr >= 0.999, "corr vs ffmpeg = {corr}"); +} diff --git a/crates/ec-va/src/vpp.rs b/crates/ec-va/src/vpp.rs index 505132d5..29d3f876 100644 --- a/crates/ec-va/src/vpp.rs +++ b/crates/ec-va/src/vpp.rs @@ -95,6 +95,55 @@ impl Vpp { Ok(surface) } + /// Convert `source` into `dest` like [`Vpp::convert`], but reading only + /// `source_region` of `source` and writing only `dest_region` of `dest` — + /// no scaling (both regions are the same size in every caller today), + /// just a placement: the pixels outside `dest_region` are left exactly as + /// `dest` already had them. This is how a visible picture smaller than + /// its block-aligned coded surface (e.g. a 2160-tall HEVC source, whose + /// coded height rounds to 2176) lands inside a differently-padded + /// destination without a resize. + pub fn convert_region( + &self, + source: &Arc, + source_region: (u32, u32, u32, u32), + dest: Arc, + dest_region: (u32, u32, u32, u32), + ) -> Result> { + let sr = sys::VARectangle { + x: source_region.0 as i16, + y: source_region.1 as i16, + width: source_region.2 as u16, + height: source_region.3 as u16, + }; + let dr = sys::VARectangle { + x: dest_region.0 as i16, + y: dest_region.1 as i16, + width: dest_region.2 as u16, + height: dest_region.3 as u16, + }; + let param = sys::VAProcPipelineParameterBuffer { + surface: source.id(), + surface_region: &sr, + output_region: &dr, + ..Default::default() + }; + // SAFETY: `surface_region`/`output_region` point at `sr`/`dr`, which + // outlive this call (built here, read only while `Buffer::from_param` + // constructs the driver buffer below); otherwise identical to + // `convert`'s safety argument. + let buffer = unsafe { + Buffer::from_param(&self.context, sys::VAProcPipelineParameterBufferType, ¶m)? + }; + let surface = Picture::new(&self.context, dest) + .begin()? + .render(buffer)? + .end()? + .sync()? + .into_surface(); + Ok(surface) + } + fn context_id(&self) -> sys::VAContextID { // `Context` does not expose its raw id outside the crate; VPP needs // it for `vaQueryVideoProcFilters`, which has no typestate-protected 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 diff --git a/scripts/scan-real-library.sh b/scripts/scan-real-library.sh index 3bf81e8c..0035effc 100755 --- a/scripts/scan-real-library.sh +++ b/scripts/scan-real-library.sh @@ -81,7 +81,7 @@ nerr=0 "${vpix:--}" "${vbits:--}" "${acodecs:--}" "${duration:--}" \ "$(stat -c %s -- "$f")" n=$((n + 1)) - done < <(find "${DIRS[@]}" -type f \( "${find_args[@]}" \) -print0 2>/dev/null) + done < <(find "${DIRS[@]}" -type f \( "${find_args[@]}" \) ! -name "*.export*.mp4" -print0 2>/dev/null) } >"$tmp" mv -- "$tmp" "$OUT" diff --git a/shims/symphonia/tests/edith_surface.rs b/shims/symphonia/tests/edith_surface.rs index 5aadbbef..f1030b9b 100644 --- a/shims/symphonia/tests/edith_surface.rs +++ b/shims/symphonia/tests/edith_surface.rs @@ -280,3 +280,68 @@ fn opus_has_a_decoder_in_the_registry() { "the refusal names the codec: {refusal}" ); } + +/// Regression for `open: NeedMore` on a real mp3 whose ID3v2 header carries a +/// large APIC cover-art picture and whose tail carries an ID3v1 `TAG` block: +/// the probe must skip both rather than reading a bounded head short of the +/// first mp3 frame sync, or getting confused reading a 128-byte tail as audio. +/// Built out of a plain mp3 fixture wrapped in a synthetic 2 MB ID3v2 APIC +/// header and an ID3v1 tail, so this needs no real file on disk. +#[test] +fn cover_art_and_id3v1_tail_do_not_stop_the_probe() { + let raw = std::fs::read(fixtures().join("mp3-stereo-48000.mp3")).expect("fixture mp3"); + // A 2 MB ID3v2.3 tag: one oversized `APIC` frame of filler bytes. The + // probe only needs to skip past the tag's declared size, so the frame + // body's content does not matter. + let apic_body_len = 2_000_000usize; + let mut id3 = Vec::new(); + id3.extend_from_slice(b"ID3"); + id3.extend_from_slice(&[3, 0, 0]); // version 2.3.0, no flags + let frame_len = apic_body_len as u32; + let tag_size = 10 + apic_body_len as u32; // one frame header (10) + body + id3.extend_from_slice(&syncsafe(tag_size)); + id3.extend_from_slice(b"APIC"); + id3.extend_from_slice(&frame_len.to_be_bytes()); + id3.extend_from_slice(&[0, 0]); // frame flags + id3.extend(std::iter::repeat_n(0u8, apic_body_len)); + + let mut id3v1 = vec![0u8; 128]; + id3v1[0..3].copy_from_slice(b"TAG"); + + let mut bytes = id3; + bytes.extend_from_slice(&raw); + bytes.extend_from_slice(&id3v1); + + let path = std::env::temp_dir().join("edith-cover-art-id3v1-tail.mp3"); + std::fs::write(&path, &bytes).expect("write synthetic mp3"); + + let mut track = SymTrack::open(&path).expect("open past the ID3v2 APIC and ID3v1 tail"); + assert_eq!(track.codec, "mp3"); + let mut decoder = track.decoder(); + let mut out = Vec::new(); + let mut decoded_packets = 0; + while let Some(packet) = track.reader.next_packet().expect("demux") { + if packet.track_id != track.track_id { + continue; + } + decoder + .decode(&packet) + .expect("decode") + .copy_to_vec_interleaved::(&mut out); + decoded_packets += 1; + } + assert!(decoded_packets > 0, "no audio packets decoded"); + assert!(!out.is_empty(), "no samples decoded"); + let _ = std::fs::remove_file(&path); +} + +/// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear), +/// big-endian. +fn syncsafe(mut n: u32) -> [u8; 4] { + let mut out = [0u8; 4]; + for b in out.iter_mut().rev() { + *b = (n & 0x7f) as u8; + n >>= 7; + } + out +}