diff --git a/.gitignore b/.gitignore index 9d7816c2..eba9f4b8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ target/ fixtures/ __pycache__/ scripts/aac-tables/sbr-cache.json +.cache/ diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 6dc528fd..e1437444 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -2107,6 +2107,262 @@ fn full_chain_low_band_matches_own_core() { } } +/// Follow-up to round-52: `best_lag_correlation`'s `LAG_MAX=4000` bound was +/// landing HE-AAC winning lags right at its own edge (-3634..-3882) on the +/// synthetic matrix -- this is the same shape `wide_lag_search_full_chain` +/// diagnosed on FMJ. Mirrors that diagnostic's odd-stride coarse pass, but +/// over a caller-supplied `lag_max` and followed by the same full-`WINDOW` +/// refine `best_lag_correlation` does, so its result is directly comparable +/// (not just a coarse `|corr|` estimate). +fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) { + const COARSE: usize = 4096; + 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); + let mut lag = -lag_max; + while lag <= lag_max { + if let Some((oa, ob)) = slice_at(lag, COARSE) { + let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs(); + if c > coarse_best.1 { + coarse_best = (lag, c); + } + } + lag += 11; // odd stride so it doesn't alias against frame-length periodicity + } + let mut best = (coarse_best.0, -1.0f64, 0.0f64); + for lag in (coarse_best.0 - 16)..=(coarse_best.0 + 16) { + let Some((oa, ob)) = slice_at(lag, WINDOW) else { + continue; + }; + let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob); + if n < 1024 { + continue; + } + let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]); + if c.abs() > best.1 { + best = (lag, c.abs(), c); + } + } + (best.0, best.2) +} + +/// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real +/// file each, whose sample rate, bitrate and content all differ at once), +/// every row here decodes the SAME synthesized source (three summed sine +/// sweeps 100 Hz-18 kHz + seeded pink noise, per-channel phase offset), +/// varying only sample rate (44100/48000) and bitrate (32k/48k/64k/96k, +/// which sweeps the SBR crossover `kx`/`k2`), so a break tied to a rate +/// FAMILY or to `kx` GEOMETRY shows as a pattern across the table instead +/// of being confounded with one file's own content. `aac_low` control rows +/// (no SBR at all) prove the harness itself -- container extraction, +/// decode, correlation -- is sound before the HE-AAC rows next to them are +/// trusted; those are the only asserted numbers here, everything else is +/// instrumentation for the ledger, not a regression gate yet. +/// +/// Env-gated on `EC_AAC_HEAAC_FIXTURES` (defaults to the same +/// `/.cache/heaac-fixtures` `scripts/aac-tables/make-heaac-fixtures.sh` +/// writes to) -- skips loudly, generates nothing itself, when that +/// directory is absent. +#[test] +fn synthetic_heaac_matrix() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| { + format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")) + }); + let dir = PathBuf::from(dir); + if !dir.is_dir() { + eprintln!( + "SKIP: {} absent -- run scripts/aac-tables/make-heaac-fixtures.sh first", + dir.display() + ); + return; + } + unsafe { + std::env::set_var("EC_AAC_SBR_SIDEINFO_DEBUG", "1"); + } + println!( + "{:>5} {:>6} {:>4} {:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", + "rate", "kbps", "prof", "kx", "k2", "full", "below", "above", "lag", "ours_v_core", "ovc_lag", + "core_v_ref", "cvr_lag", "core_rate", "full_rate" + ); + // Wide enough that the WIDE_LAG_MAX==LC's own decoder priming delay + // (2048) plus a full SBR-chain worth of extra delay (a few thousand + // samples at the doubled/full output rate) both land well inside it, + // not right at the edge the way the plain (LAG_MAX=4000) search did. + const WIDE_LAG_MAX: i64 = 20_000; + for rate in [48_000u32, 44_100] { + for br in ["32k", "48k", "64k", "96k"] { + // LC first: its winning lag is the pure container/decoder + // priming delay with no SBR chain involved, and is reused below + // as the anchor for the HE row's own delay-candidate probe. + let mut lc_lag: Option = None; + for (profile, prefix) in [("LC", "lc"), ("HE", "heaac")] { + let path = dir.join(format!("{prefix}_{rate}_{br}.m4a")); + if !path.exists() { + eprintln!("SKIP {}: missing", path.display()); + continue; + } + let before = ec_aac::sbr_sideinfo_log().len(); + let Some((ours, _sbr, our_rate)) = our_decode(&path, 0) else { + eprintln!("SKIP {}: could not decode", path.display()); + continue; + }; + let rows = ec_aac::sbr_sideinfo_log(); + let (kx, k2) = rows[before..] + .iter() + .find(|r| r.ch == 0) + .map(|r| (r.kx, r.k2)) + .unwrap_or((-1, -1)); + let theirs = ffmpeg_decode(&path, 0, ours.len()); + let o = &ours[0]; + let t = &theirs[0]; + let (lag, full) = best_lag_correlation_wide(o, t, WIDE_LAG_MAX); + if profile == "LC" { + lc_lag = Some(lag); + } + // Crossover in Hz from the actual parsed kx (band width + // rate/128, same domain `sbr_chain.rs`'s own doc comment + // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist + // split for the LC controls, which carry no kx at all. + let crossover_hz = if kx > 0 { + f64::from(our_rate) * (kx as f64) / 128.0 + } else { + f64::from(our_rate) * 0.25 + }; + let (_, below) = best_lag_correlation_wide( + &lowpass(o, our_rate, crossover_hz), + &lowpass(t, our_rate, crossover_hz), + WIDE_LAG_MAX, + ); + // `above` re-slices at the FULL-band winning `lag` before + // splitting, same convention `sbr_real_library_matches_reference` + // uses -- round-52's first cut of this row measured `o[..n]` + // against `t[..n]` with no lag offset at all, which is only + // valid by accident at lag 0 and was silently wrong for + // every other winning lag in that table. + let (oa, ob) = if lag >= 0 { + (0usize, lag as usize) + } else { + ((-lag) as usize, 0usize) + }; + let n = WINDOW.min(o.len().saturating_sub(oa)).min(t.len().saturating_sub(ob)); + let above = if n >= 1024 { + correlation( + &highpass(&o[oa..oa + n], our_rate, crossover_hz), + &highpass(&t[ob..ob + n], our_rate, crossover_hz), + ) + } else { + 0.0 + }; + // Round-51's self-consistency probe (our full chain's low + // band vs our own core-only decode, 2x upsampled), run + // per-row so a rate/kx-specific self-inconsistency shows in + // the same table instead of needing a second pass. + let ours_v_core = if kx > 0 { + our_decode_core_only(&path, 0).map(|(core, core_rate)| { + let up: Vec = core[0].iter().flat_map(|&s| [s, s]).collect(); + let cutoff = f64::from(core_rate) * 0.4; + let ol = lowpass(o, our_rate, cutoff); + let ul = lowpass(&up, our_rate, cutoff); + best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX) + }) + } else { + None + }; + // Coordinator follow-up 2: splits "our core decode of THIS + // fixture is wrong" (core_v_ref ~0) from "the SBR chain + // scrambles a good core" (core_v_ref >= ~0.99 while `below` + // above stays ~0/negative) -- OUR core-only decode (2x + // upsampled, same convention `ours_v_core` uses) against the + // REFERENCE decoder's own decode, below the crossover only, + // wide lag search since this is an independent alignment + // from `full`/`below`'s (core-only carries no SBR delay). + let (core_v_ref, core_rate_str) = if kx > 0 { + match our_decode_core_only(&path, 0) { + Some((core, core_rate)) => { + let up: Vec = core[0].iter().flat_map(|&s| [s, s]).collect(); + let tl = lowpass(t, our_rate, crossover_hz); + let ul = lowpass(&up, our_rate, crossover_hz); + (Some(best_lag_correlation_wide(&ul, &tl, WIDE_LAG_MAX)), core_rate.to_string()) + } + None => (None, "n/a".into()), + } + } else { + (None, "n/a".into()) + }; + println!( + "{rate:>5} {br:>6} {profile:>4} {kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", + ours_v_core + .map(|(_, c)| format!("{c:.4}")) + .unwrap_or_else(|| "n/a".into()), + ours_v_core + .map(|(l, _)| l.to_string()) + .unwrap_or_else(|| "n/a".into()), + core_v_ref + .map(|(_, c)| format!("{c:.4}")) + .unwrap_or_else(|| "n/a".into()), + core_v_ref + .map(|(l, _)| l.to_string()) + .unwrap_or_else(|| "n/a".into()), + core_rate_str, + our_rate, + ); + // Coordinator follow-up (4): on the two named rows, probe + // candidate total HE-vs-reference delays built from LC's own + // priming lag plus a guessed SBR-chain contribution, to see + // which (if any) actually lands near 1.0 -- and whether that + // offset is constant across the two rows. + if profile == "HE" + && ((rate == 44_100 && br == "48k") || (rate == 48_000 && br == "64k")) + { + let lc = lc_lag.unwrap_or(-2048); + println!(" ch0 delay probe (LC lag {lc}):"); + for (label, extra) in [ + ("2990", 2990i64), + ("3010", 3010), + ("3020", 3020), + ("1505x2", 1505 * 2), + ("962x2", 962 * 2), + ] { + let candidate = (lc - 2048) + extra; + println!( + " offset={label:>6} -> lag={candidate:>6} corr={:.6}", + correlation_at_lag(o, t, candidate) + ); + } + } + if profile == "LC" { + assert!( + full >= 0.999, + "{}: LC control full-band corr {full:.6} < 0.999 -- the \ + harness itself (extraction/decode/correlation) is broken, \ + not the SBR chain this fixture matrix is meant to isolate", + path.display() + ); + } + } + } + } +} + fn candidates() -> Vec { let home = std::env::var("HOME").unwrap_or_default(); [ diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 62f271ea..01f5abb9 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -134,6 +134,19 @@ pub struct Decoder { out: VecDeque, /// Presentation timestamp to attach to the next picture started. pending_pts: Option, + /// `PicOrderCnt` of the random-access point most recently established by + /// [`Decoder::reset_pictures`] — the first picture decoded after it, + /// i.e. the I picture a seek landed on. `None` before that picture + /// completes. Absent a recovery_point SEI (not parsed here), D.2.8's + /// recovery point defaults to this picture itself: anything with a + /// smaller POC that had to guess a reference (see `cur_ref_padded`) + /// predicts from something never decoded since the seek and must not + /// reach the caller. + recovery_poc: Option, + /// Set while decoding the open picture if `build_ref_lists` had to pad a + /// reference list, i.e. this picture asked for a reference the DPB does + /// not have. Reset per picture in `start_picture`. + cur_ref_padded: bool, } /// What [`Decoder::push_nal`] did with a NAL unit. @@ -199,6 +212,8 @@ impl Decoder { output_order: OutputOrder::default(), out: VecDeque::new(), pending_pts: None, + recovery_poc: None, + cur_ref_padded: false, } } @@ -301,13 +316,18 @@ impl Decoder { self.cur.extend_borders(); self.cur.complete = true; self.last_decoded = self.cur.id; + // The first picture completed after a reset is the random-access + // point the seek landed on; its own POC becomes the recovery + // threshold (see `recovery_poc`'s doc comment). + let recovery_poc = *self.recovery_poc.get_or_insert(self.cur.poc); + let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc); let sps_id = self.cur.sps_id as usize; let sps = self.sps_map[sps_id] .take() .ok_or_else(|| Error::corrupt("active SPS vanished"))?; let pic = core::mem::take(&mut self.cur); let marking = self.has_marking.then_some(&self.cur_marking); - let stored = self.dpb.store(pic, &sps, &self.cur_info, marking); + let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok); self.sps_map[sps_id] = Some(sps); stored?; self.has_picture = false; @@ -357,6 +377,7 @@ impl Decoder { self.out.clear(); self.last_decoded = -1; self.pending_pts = None; + self.recovery_poc = None; } /// Move pictures out of the decoded picture buffer into the output queue. @@ -472,7 +493,7 @@ impl Decoder { [RefList::default(), RefList::default()] } else { self.dpb.number_short_term(sh.frame_num, sps); - self.dpb.build_ref_lists( + let (lists, padded) = self.dpb.build_ref_lists( sh.slice_type, self.cur.poc, sh.frame_num as i32, @@ -480,7 +501,15 @@ impl Decoder { sh.num_ref_idx_l0_active as usize, sh.num_ref_idx_l1_active as usize, (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), - )? + )?; + // A ref list shorter than requested was padded by repeating an + // available entry (8.2.4.2's unspecified tail) rather than the + // reference this slice actually asked for. Right after a seek's + // reset, that means the picture predicts from something never + // decoded since the random-access start; recorded here so + // `end_picture` can hold its output back (see `recovery_poc`). + self.cur_ref_padded |= padded; + lists }; let mut r = if pps.entropy_coding_mode { @@ -632,6 +661,7 @@ impl Decoder { sh: &SliceHeader, header: NalHeader, ) -> Result<()> { + self.cur_ref_padded = false; let info = PicInfo { is_idr: header.is_idr(), is_reference: header.ref_idc != 0, diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs index 7ca2d3dc..a784910c 100644 --- a/crates/ec-h264/src/dpb.rs +++ b/crates/ec-h264/src/dpb.rs @@ -644,7 +644,8 @@ impl Dpb { num_l0: usize, num_l1: usize, mods: (&[RefPicListMod], &[RefPicListMod]), - ) -> Result<[RefList; 2]> { + ) -> Result<([RefList; 2], bool)> { + let mut padded = false; let mut lists = [RefList::default(), RefList::default()]; // Short-term candidates, then long-term, both by index into `frames`. let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; @@ -737,13 +738,16 @@ impl Dpb { // conformant stream fills it by modification; repeating entry 0 // keeps every index in range meanwhile. let first = lists[x].entries[0]; + if lists[x].len < wanted[x] { + padded = true; + } while lists[x].len < wanted[x] { lists[x].push(usize::from(first)); } lists[x].len = wanted[x]; self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); } - Ok(lists) + Ok((lists, padded)) } /// Reference picture list modification (clause 8.2.4.3), following the @@ -826,15 +830,22 @@ impl Dpb { } /// Store a decoded picture and apply the reference marking of 8.2.5. + /// + /// `output_ok` is false for a picture that predicted from a reference + /// never decoded since the last `reset()` (a random-access leading + /// picture whose ref list build had to pad) — it still joins the DPB, as + /// a reference for later pictures and for `PicNum`/`FrameNumWrap` + /// bookkeeping, but the bumping process must never hand it to a caller. pub(crate) fn store( &mut self, mut pic: Picture, sps: &Sps, info: &PicInfo, marking: Option<&DecRefPicMarking>, + output_ok: bool, ) -> Result<()> { let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); - pic.output = true; + pic.output = output_ok; pic.complete = true; // Clause 8.2.4.1 against this picture's frame_num, which is what both // the sliding window (8.2.5.3) and the MMCO picture numbers (8.2.5.4) @@ -1275,7 +1286,7 @@ mod tests { lt.long_term_frame_idx = 1; lt.pic_num = 1; dpb.frames.push(lt); - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[])) .unwrap(); let nums: Vec = (0..lists[0].len()) @@ -1292,7 +1303,7 @@ mod tests { push_ref(&mut dpb, 1, 8, Mark::Short); push_ref(&mut dpb, 2, 4, Mark::Short); push_ref(&mut dpb, 3, 12, Mark::Short); - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) .unwrap(); let poc = |l: &RefList| -> Vec { @@ -1313,7 +1324,7 @@ mod tests { push_ref(&mut dpb, 1, 2, Mark::Short); // Both references precede the current picture, so initialisation gives // list 0 and list 1 the same descending-POC order. - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) .unwrap(); let l0: Vec = (0..2) @@ -1338,7 +1349,7 @@ mod tests { abs_diff_pic_num_minus1: 2, add: false, }]; - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[])) .unwrap(); let nums: Vec = (0..3) diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 619ae22d..5d19b39a 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -2245,3 +2245,134 @@ fn high_profile_8x8_inter_sequences_match_ffmpeg() { let _ = std::fs::remove_dir_all(&dir); assert!(failures.is_empty(), "{failures:#?}"); } + +/// An open-GOP boundary's non-IDR I picture (`nal_unit_type` 1, not 5) is +/// followed in decode order by leading B pictures that display *before* it +/// but predict from the previous GOP. A decoder started fresh at that I +/// picture — what a seek does — never decoded those previous-GOP references, +/// so it must not hand back the leading B pictures at all (H.264's analogue +/// of HEVC's RASL/`NoRaslOutputFlag` case): output must resume at the I +/// picture itself, per D.2.8 absent a recovery_point SEI. +#[test] +fn h264_seek_matches_linear_open_gop() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4"); + if !src.is_file() { + eprintln!("SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)"); + return; + } + let dir = scratch("open-gop"); + std::fs::create_dir_all(&dir).unwrap(); + let annexb = dir.join("open-gop.264"); + assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction"); + let data = std::fs::read(&annexb).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + + // Split into access units the way a demuxer would: a new one starts at + // each slice NAL (type 1 or 5). + let units: Vec> = ec_h264_syntax::AnnexBIter::new(&data) + .map(<[u8]>::to_vec) + .collect(); + let mut access_units: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + let mut current_has_slice = false; + for unit in &units { + let is_slice = matches!(unit[0] & 0x1F, 1 | 5); + if is_slice && current_has_slice { + access_units.push(std::mem::take(&mut current)); + current_has_slice = false; + } + current_has_slice |= is_slice; + current.extend_from_slice(&[0, 0, 0, 1]); + current.extend_from_slice(unit); + } + if current_has_slice { + access_units.push(current); + } + + // Linear decode: every picture from the start, display frame 30 kept for + // comparison (the fixture's second I picture, `keyint=30`). + const TARGET: usize = 30; + let mut dec = Decoder::new(); + let mut linear_frame_30 = None; + let mut index = 0usize; + for nal in ec_h264_syntax::AnnexBIter::new(&data) { + if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary { + dec.end_picture().expect("end_picture"); + dec.push_nal(nal).expect("re-push"); + } + while let Some(f) = dec.next_frame() { + if index == TARGET { + linear_frame_30 = Some(frame_bytes(&f)); + } + index += 1; + } + } + dec.flush().expect("flush"); + while let Some(f) = dec.next_frame() { + if index == TARGET { + linear_frame_30 = Some(frame_bytes(&f)); + } + index += 1; + } + let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); + + // Find the access unit whose first VCL NAL is a non-IDR I slice + // (`nal_unit_type` 1, `slice_type % 5 == 2`) — the open-GOP boundary. + let is_open_gop_i = |au: &[u8]| -> bool { + let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else { + return false; + }; + if header & 0x1F != 1 { + return false; + } + let mut r = ec_core::BitReader::new(payload); + if r.read_ue().is_err() { + return false; + } + matches!(r.read_ue(), Ok(code) if code % 5 == 2) + }; + let cra_at = access_units + .iter() + .position(|au| is_open_gop_i(au)) + .expect("an open-GOP I access unit exists"); + + // A seek reuses the parameter sets a decoder already learned; a fresh one + // is primed the way `Decoder::reset_pictures`'s doc comment expects: the + // leading IDR's parameter sets are decoded and its picture discarded. + let mut seek_dec = Decoder::new(); + for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) { + seek_dec.push_nal(nal).expect("prime parameter sets"); + } + seek_dec.end_picture().expect("end priming IDR"); + seek_dec.reset_pictures(); + + let mut seeked_frame = None; + 'outer: for au in &access_units[cra_at..] { + for nal in ec_h264_syntax::AnnexBIter::new(au) { + if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary { + seek_dec.end_picture().expect("end_picture"); + seek_dec.push_nal(nal).expect("re-push"); + } + } + if let Some(f) = seek_dec.next_frame() { + seeked_frame = Some(frame_bytes(&f)); + break 'outer; + } + } + if seeked_frame.is_none() { + seek_dec.flush().expect("flush"); + seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f)); + } + let seeked_frame = seeked_frame.expect("a frame came out after the seek"); + + assert_eq!( + seeked_frame, linear_frame_30, + "seeking to the open-GOP I before frame 30 handed back a different \ + picture than a linear decode of frame 30 — leading pictures with \ + missing references were not dropped" + ); +} diff --git a/crates/ec-hw/src/dec/av1.rs b/crates/ec-hw/src/dec/av1.rs index 2c5ad2d3..961264ee 100644 --- a/crates/ec-hw/src/dec/av1.rs +++ b/crates/ec-hw/src/dec/av1.rs @@ -115,6 +115,7 @@ impl Av1Decoder { (header.render_width, header.render_height), session.coded_size, session.bit_depth, + None, )); // 7.21: showing a KEY frame again refreshes every reference slot with // it, which the reference *surfaces* have to follow too. @@ -183,6 +184,7 @@ impl Av1Decoder { (header.render_width, header.render_height), session.coded_size, session.bit_depth, + None, )); } Ok(()) diff --git a/crates/ec-hw/src/dec/dpb264.rs b/crates/ec-hw/src/dec/dpb264.rs index 50a53308..7fc2f73a 100644 --- a/crates/ec-hw/src/dec/dpb264.rs +++ b/crates/ec-hw/src/dec/dpb264.rs @@ -420,7 +420,8 @@ impl Dpb { num_l0: usize, num_l1: usize, mods: (&[RefPicListMod], &[RefPicListMod]), - ) -> Result<[RefList; 2]> { + ) -> Result<([RefList; 2], bool)> { + let mut padded = false; let mut lists = [RefList::default(), RefList::default()]; let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; let mut n_short = 0usize; @@ -505,13 +506,16 @@ impl Dpb { ))); } let first = lists[x].entries[0]; + if lists[x].len < wanted[x] { + padded = true; + } while lists[x].len < wanted[x] { lists[x].push(usize::from(first)); } lists[x].len = wanted[x]; self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); } - Ok(lists) + Ok((lists, padded)) } /// Reference picture list modification (8.2.4.3), by the insert-and-compact @@ -589,15 +593,21 @@ impl Dpb { } /// Store a decoded picture and apply the reference marking of 8.2.5. + /// + /// `output_ok` is false for a picture that predicted from a reference + /// never decoded since the last `reset()` (a random-access leading + /// picture whose ref list build had to pad) — it still joins the DPB as + /// a reference and for bookkeeping, but must never be handed to a caller. pub(crate) fn store( &mut self, mut pic: Picture, sps: &Sps, info: &PicInfo, marking: Option<&DecRefPicMarking>, + output_ok: bool, ) -> Result<()> { let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); - pic.output = true; + pic.output = output_ok; self.number_short_term(info.frame_num, sps); pic.frame_num_wrap = pic.frame_num as i32; pic.pic_num = pic.frame_num as i32; diff --git a/crates/ec-hw/src/dec/h264.rs b/crates/ec-hw/src/dec/h264.rs index 31843549..740f7fff 100644 --- a/crates/ec-hw/src/dec/h264.rs +++ b/crates/ec-hw/src/dec/h264.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use ec_core::color::{ColorDescription, ContentLight, Tags}; use ec_h264_syntax::{ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, SliceType, Sps, unescape_rbsp, @@ -12,7 +13,7 @@ use ec_va::{Buffer, Display, sys}; use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; -use crate::frame::Frame; +use crate::frame::{Colour, Frame}; use crate::params::h264::{ IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE, PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264, @@ -38,6 +39,8 @@ struct Current { /// Parameter and data buffers submitted so far. buffers: Vec, slices: usize, + /// Set if any slice's ref list build had to pad (see `H264Decoder::recovery_poc`). + ref_padded: bool, } /// A stateless H.264 decoder. @@ -52,6 +55,16 @@ pub struct H264Decoder { /// Reusable unescape buffer; NAL payloads are rewritten into it in turn. rbsp: Vec, gap_frames: u64, + /// `PicOrderCnt` of the random-access point most recently established by + /// `reset()` — the first picture decoded after it. `None` before that + /// picture completes. Absent a recovery_point SEI (not parsed here), + /// D.2.8's recovery point defaults to this picture itself: anything with + /// a smaller POC that had to guess a reference (`Current::ref_padded`) + /// predicts from something never decoded since the seek and must not + /// reach the caller. + recovery_poc: Option, + /// The most recent SPS's VUI colour tags, sticky across pictures. + colour_tags: Tags, } impl H264Decoder { @@ -68,6 +81,8 @@ impl H264Decoder { current: None, rbsp: Vec::new(), gap_frames: 0, + recovery_poc: None, + colour_tags: Tags::default(), } } @@ -86,6 +101,7 @@ impl H264Decoder { self.rbsp = rbsp; let sps = sps?; self.dpb.configure(&sps); + self.colour_tags = vui_colour_tags(&sps); let id = usize::from(sps.id); self.sps_map[id] = Some(sps); } @@ -132,6 +148,7 @@ impl H264Decoder { self.dpb.clear(); self.ready.clear(); self.gap_frames = 0; + self.recovery_poc = None; } /// What the stream turned out to be, once its first SPS was seen. @@ -268,6 +285,7 @@ impl H264Decoder { marking: sh.dec_ref_pic_marking.clone(), buffers: Vec::new(), slices: 0, + ref_padded: false, }); Ok(()) } @@ -317,7 +335,7 @@ impl H264Decoder { [RefList::default(), RefList::default()] } else { self.dpb.number_short_term(sh.frame_num, sps); - self.dpb.build_ref_lists( + let (lists, padded) = self.dpb.build_ref_lists( sh.slice_type, current.poc.value, sh.frame_num as i32, @@ -325,7 +343,9 @@ impl H264Decoder { sh.num_ref_idx_l0_active as usize, sh.num_ref_idx_l1_active as usize, (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), - )? + )?; + current.ref_padded |= padded; + lists }; let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb); @@ -359,6 +379,10 @@ impl H264Decoder { session.submit(¤t.surface, current.buffers)?; + // See `recovery_poc`'s doc comment. + let recovery_poc = *self.recovery_poc.get_or_insert(current.poc.value); + let output_ok = !(current.ref_padded && current.poc.value < recovery_poc); + let picture = Picture { id: current.id, surface: Arc::clone(¤t.surface), @@ -376,7 +400,7 @@ impl H264Decoder { output: true, }; self.dpb - .store(picture, &sps, ¤t.info, current.marking.as_ref())?; + .store(picture, &sps, ¤t.info, current.marking.as_ref(), output_ok)?; self.bump(false); Ok(()) } @@ -395,11 +419,45 @@ impl H264Decoder { session.display_size, session.coded_size, session.bit_depth, + self.colour(), ); self.ready.push(frame); self.dpb.released(idx); } } + + /// This stream's colour metadata, once its first SPS has been seen. No SEI + /// here — H.264's mastering-display/content-light-level SEI is not parsed + /// by this family today, so this is VUI-only. + pub fn colour(&self) -> Option { + let session = self.session.as_ref()?; + Some(Colour { + description: ColorDescription::resolve( + Tags::default(), + self.colour_tags, + session.display_size.1, + ), + light: ContentLight::default(), + }) + } +} + +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no +/// `video_signal_type` at all. +fn vui_colour_tags(sps: &Sps) -> Tags { + let Some(vui) = &sps.vui else { + return Tags::default(); + }; + if vui.video_format.is_none() { + return Tags::default(); + } + let (_primaries, transfer, matrix) = vui.colour_description.unwrap_or((0, 0, 0)); + Tags::from_codes( + u64::from(matrix), + u64::from(transfer), + if vui.video_full_range { 2 } else { 1 }, + ) } /// The `pic_parameter_set_id` of a slice header, which is the second syntax diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs index c23a2183..13646cee 100644 --- a/crates/ec-hw/src/dec/hevc.rs +++ b/crates/ec-hw/src/dec/hevc.rs @@ -9,6 +9,7 @@ use std::sync::Arc; +use ec_core::color::{ColorDescription, ContentLight, Tags}; use ec_h265_syntax::{ NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b, unescape_rbsp, @@ -18,7 +19,7 @@ use ec_va::{Buffer, Display, sys}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; -use crate::frame::Frame; +use crate::frame::{Colour, Frame}; use crate::params::hevc::{ IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC, @@ -93,8 +94,18 @@ pub struct HevcDecoder { prev_tid0_poc: i32, /// Set once a picture has been decoded since the last reset. started: bool, + /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures + /// associated with it must not be decoded or output when set, because + /// they predict from pictures before a random-access point this decoder + /// never saw. + no_rasl_output: bool, max_reorder: usize, max_dec_pic_buffering: usize, + /// The most recent SPS's VUI colour tags, sticky across pictures. + colour_tags: Tags, + /// The prefix SEI HDR peak seen so far, merged so a later access unit that + /// says nothing does not erase what an earlier IRAP declared. + colour_light: ContentLight, } impl HevcDecoder { @@ -111,8 +122,11 @@ impl HevcDecoder { current: None, prev_tid0_poc: 0, started: false, + no_rasl_output: false, max_reorder: 1, max_dec_pic_buffering: 6, + colour_tags: Tags::default(), + colour_light: ContentLight::default(), } } @@ -131,6 +145,7 @@ impl HevcDecoder { let sps = Sps::parse(&nal.rbsp())?; self.max_reorder = sps.max_num_reorder_pics as usize; self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; + self.colour_tags = vui_colour_tags(&sps); let id = sps.id as usize; if id < self.sps_map.len() { self.sps_map[id] = Some(sps); @@ -149,10 +164,33 @@ impl HevcDecoder { _ => {} } } + // The HDR SEI messages (mastering display, content light level) live + // outside the slice loop above and are read on the whole access unit: + // an encoder writes them once, ahead of the IRAP they describe, and + // they otherwise say nothing (`ContentLight::default()`), so a later + // access unit that carries neither never overwrites what an earlier + // one declared. + let light = ec_core::color::hevc_sei_light(data); + if light != ContentLight::default() { + self.colour_light = light.over(self.colour_light); + } self.finish_picture()?; Ok(()) } + /// This stream's colour metadata, once its first SPS has been seen. + pub fn colour(&self) -> Option { + let session = self.session.as_ref()?; + Some(Colour { + description: ColorDescription::resolve( + Tags::default(), + self.colour_tags, + session.display_size.1, + ), + light: self.colour_light, + }) + } + /// The next frame in output order. pub fn next_frame(&mut self) -> Option { self.ready.pop() @@ -171,6 +209,7 @@ impl HevcDecoder { self.ready.clear(); self.prev_tid0_poc = 0; self.started = false; + self.no_rasl_output = false; } /// What the stream turned out to be. @@ -202,7 +241,14 @@ impl HevcDecoder { if sh.first_slice_segment_in_pic { self.finish_picture()?; - self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?; + // 8.1.3 / C.5.2.2: a RASL picture associated with an IRAP whose + // NoRaslOutputFlag is 1 predicts from pictures before that IRAP, + // which a mid-stream start never decoded. It is not output and + // is not guaranteed decodable, so it is dropped whole rather than + // handed to the driver. + if !(is_rasl_picture(nal_type) && self.no_rasl_output) { + self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?; + } } if self.current.is_none() { return Ok(()); @@ -256,6 +302,13 @@ impl HevcDecoder { ) -> Result<()> { self.ensure_session(sps)?; + if nal_type.is_irap() { + // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded + // video sequence — which a mid-stream start's first IRAP always + // is, `self.started` still being false at that point. + self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started; + } + let poc = self.picture_order_count(sps, sh, nal_type); // 8.3.2 runs before the picture is decoded and after its POC is known: // every stored picture the set does not name stops being a reference. @@ -616,6 +669,7 @@ impl HevcDecoder { session.display_size, session.coded_size, session.bit_depth, + self.colour(), )); self.dpb[idx].output = false; self.dpb.retain(|p| p.stored()); @@ -636,6 +690,42 @@ fn is_leading_picture(nal_type: NalUnitType) -> bool { (6..=9).contains(&nal_type.code()) } +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no +/// `video_signal_type` at all. +fn vui_colour_tags(sps: &Sps) -> Tags { + let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { + return Tags::default(); + }; + let (_primaries, transfer, matrix) = vst + .colour_description + .map(|cd| { + ( + cd.colour_primaries, + cd.transfer_characteristics, + cd.matrix_coeffs, + ) + }) + .unwrap_or((0, 0, 0)); + Tags::from_codes( + u64::from(matrix), + u64::from(transfer), + if vst.video_full_range_flag { 2 } else { 1 }, + ) +} + +/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's +/// `NoRaslOutputFlag` is 1 (8.1.3). +fn is_rasl_picture(nal_type: NalUnitType) -> bool { + matches!(nal_type.code(), 8 | 9) +} + +/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 +/// (8.1.3), a broken-link splice point that never has a decodable RASL. +fn is_bla_picture(nal_type: NalUnitType) -> bool { + (16..=18).contains(&nal_type.code()) +} + /// `slice_pic_parameter_set_id`, readable without any parameter set. fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result { let mut r = ec_core::BitReader::new(rbsp); diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs index d152ba73..438a7a7c 100644 --- a/crates/ec-hw/src/dec/mod.rs +++ b/crates/ec-hw/src/dec/mod.rs @@ -154,6 +154,17 @@ impl Decoder { Inner::Av1(d) => d.stream_info(), } } + + /// This stream's colour metadata, once a session exists. [`None`] for VP9 + /// and AV1: neither's sequence header colour config is parsed by this + /// family yet. + pub fn colour(&self) -> Option { + match &self.inner { + Inner::H264(d) => d.colour(), + Inner::H265(d) => d.colour(), + Inner::Vp9(_) | Inner::Av1(_) => None, + } + } } /// Frames waiting to be collected, oldest first. diff --git a/crates/ec-hw/src/dec/vp9.rs b/crates/ec-hw/src/dec/vp9.rs index 15deb4d3..8310f237 100644 --- a/crates/ec-hw/src/dec/vp9.rs +++ b/crates/ec-hw/src/dec/vp9.rs @@ -98,6 +98,7 @@ impl Vp9Decoder { (header.width, header.height), session.coded_size, session.bit_depth, + None, )); return Ok(()); } @@ -137,6 +138,7 @@ impl Vp9Decoder { (header.width, header.height), session.coded_size, session.bit_depth, + None, )); } Ok(()) diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs index 70a7cd5e..5c142b1d 100644 --- a/crates/ec-hw/src/enc/h264.rs +++ b/crates/ec-hw/src/enc/h264.rs @@ -134,6 +134,7 @@ pub(super) fn parameters( num_units_in_tick: seq.num_units_in_tick, time_scale: seq.time_scale, pic_init_qp: pic.pic_init_qp, + colour: config.colour, }; if keyframe { encoder.push_packed(&headers::h264_sps(&header_params), out)?; diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs index 2563ae81..0083a77a 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -12,6 +12,7 @@ use ec_core::BitWriter; +use super::Colour; use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; /// A header ready to submit: escaped bytes plus its exact length in bits. @@ -49,6 +50,7 @@ pub(super) struct H264Params { pub(super) num_units_in_tick: u32, pub(super) time_scale: u32, pub(super) pic_init_qp: u8, + pub(super) colour: Option, } /// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`. @@ -87,7 +89,15 @@ pub(super) fn h264_sps(p: &H264Params) -> Packed { w.write_bit(true); // vui_parameters_present_flag w.write_bit(false); // aspect_ratio_info_present_flag w.write_bit(false); // overscan_info_present_flag - w.write_bit(false); // video_signal_type_present_flag + w.write_bit(p.colour.is_some()); // video_signal_type_present_flag + if let Some(colour) = p.colour { + w.write_bits(5, 3); // video_format: unspecified + w.write_bit(colour.full_range); + w.write_bit(true); // colour_description_present_flag + w.write_bits(u32::from(colour.primaries), 8); + w.write_bits(u32::from(colour.transfer), 8); + w.write_bits(u32::from(colour.matrix), 8); + } w.write_bit(false); // chroma_loc_info_present_flag w.write_bit(true); // timing_info_present_flag w.write_bits(p.num_units_in_tick, 32); @@ -185,7 +195,7 @@ pub(super) mod hevc { SliceHeader, SliceType, Sps, Vps, }; - use super::{Packed, nal}; + use super::{Colour, Packed, nal}; use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; /// Geometry and timing for the parameter sets. @@ -198,6 +208,7 @@ pub(super) mod hevc { pub(in crate::enc) num_units_in_tick: u32, pub(in crate::enc) time_scale: u32, pub(in crate::enc) init_qp: u8, + pub(in crate::enc) colour: Option, } /// The VPS, SPS and PPS, in that order. @@ -254,6 +265,17 @@ pub(super) mod hevc { ptl, vui: Some(ec_h265_syntax::vui::VuiParameters { timing: Some((p.num_units_in_tick, p.time_scale)), + video_signal_type: p.colour.map(|colour| { + ec_h265_syntax::vui::VideoSignalType { + video_format: 5, // unspecified + video_full_range_flag: colour.full_range, + colour_description: Some(ec_h265_syntax::vui::ColourDescription { + colour_primaries: colour.primaries, + transfer_characteristics: colour.transfer, + matrix_coeffs: colour.matrix, + }), + } + }), ..ec_h265_syntax::vui::VuiParameters::default() }), }; diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index a139afd9..bfe5485e 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -146,6 +146,7 @@ pub(super) fn parameters( num_units_in_tick: seq.vui_num_units_in_tick, time_scale: seq.vui_time_scale, init_qp: pic.pic_init_qp, + colour: config.colour, }; let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params); if keyframe { diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 0de67604..c71c6402 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -97,6 +97,27 @@ pub struct EncoderConfig { pub quality: u32, /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused. pub allow_av1: bool, + /// The colour description to write into the VUI, or `None` to leave it + /// unsignalled (`video_signal_type_present_flag = 0`) as before. + pub colour: Option, +} + +/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. +/// +/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and +/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting +/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273 +/// tables 2/3/4). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Colour { + /// `colour_primaries`. + pub primaries: u8, + /// `transfer_characteristics`. + pub transfer: u8, + /// `matrix_coeffs`. + pub matrix: u8, + /// `video_full_range_flag`. + pub full_range: bool, } impl EncoderConfig { @@ -112,8 +133,26 @@ impl EncoderConfig { rate_control: RateControlMode::ConstantBitrate, quality: 0, allow_av1: false, + colour: None, } } + + /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. + pub fn colour( + mut self, + primaries: u8, + transfer: u8, + matrix: u8, + full_range: bool, + ) -> EncoderConfig { + self.colour = Some(Colour { + primaries, + transfer, + matrix, + full_range, + }); + self + } } /// One coded picture. @@ -269,15 +308,65 @@ impl Encoder { self.config.width, self.config.height, frame.width, frame.height ))); } - let keyframe = meta.force_keyframe - || self.reference.is_none() - || self.gop_position >= self.config.gop_size.max(1); - let input = self .pool .acquire() .ok_or_else(|| Error::config("encode: every surface is still in use"))?; self.upload(frame, &input)?; + self.encode_surface(Arc::clone(input.surface()), meta) + } + + /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, + /// no re-upload, just the decoder's picture handed straight to the + /// encoder as its source. This is the path a decode-then-encode pipeline + /// (e.g. a transcode) wants — the alternative is a full frame through + /// system memory and back for no reason. + /// + /// Refused, rather than silently working around, when: + /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id + /// only means anything on the display that created it. + /// - `frame` is 10-bit (P010): every profile this crate encodes + /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless + /// destination for the extra two bits — call [`Frame::to_i420`] and + /// [`Encoder::encode`] if the truncation is acceptable. + /// - `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 with + /// no VPP conversion pass, and this crate does not carry a VPP-free + /// fallback for a mismatched size. + pub fn encode_frame( + &mut self, + frame: &crate::frame::Frame, + meta: FrameMetadata, + ) -> Result { + if frame.bit_depth != 8 { + return Err(Error::unsupported( + format!("encode_frame of a {}-bit source", frame.bit_depth), + "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \ + decode to I420 with Frame::to_i420 and call Encoder::encode instead", + )); + } + if !Arc::ptr_eq(frame.surface().display(), self.context.display()) { + return Err(Error::config( + "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 + ))); + } + self.encode_surface(Arc::clone(frame.surface()), meta) + } + + /// Shared submission path for [`Encoder::encode`] and + /// [`Encoder::encode_frame`]: everything after the source surface is + /// settled. + fn encode_surface(&mut self, source: Arc, meta: FrameMetadata) -> Result { + let keyframe = meta.force_keyframe + || self.reference.is_none() + || self.gop_position >= self.config.gop_size.max(1); + let recon = self .pool .acquire() @@ -298,7 +387,7 @@ impl Encoder { buffers.extend(self.rate_control_buffers()?); buffers.push(coded_buf); - let mut picture = Picture::new(&self.context, Arc::clone(input.surface())) + let mut picture = Picture::new(&self.context, source) .begin()? .render_all(buffers)? .end()? diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 3488e4c1..cc46ef06 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -3,12 +3,27 @@ use std::sync::{Arc, Mutex}; +use ec_core::color::{ColorDescription, ContentLight}; use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010}; use ec_va::{Image, MappedImage, PrimeSurface, Surface}; use crate::error::{Error, Result}; use crate::pool::PooledSurface; +/// A stream's colour metadata, resolved from its own headers: VUI tags for the +/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI +/// messages for the peak the mastering grade and the content itself declared. +/// No container tier here: ec-hw only ever sees the elementary stream, so a +/// caller that also holds the container's tags resolves those over this. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Colour { + /// Matrix/transfer/range, resolved from the bitstream's own VUI. + pub description: ColorDescription, + /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when + /// the stream carried them (HEVC prefix SEI only). + pub light: ContentLight, +} + /// The readback image a decoder reuses across frames. /// /// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on @@ -33,6 +48,8 @@ pub struct Frame { pub coded_size: (u32, u32), /// Luma bit depth: 8 for NV12 surfaces, 10 for P010. pub bit_depth: u8, + /// This stream's colour metadata, when the codec's decoder resolves one. + pub colour: Option, } /// 8-bit planar 4:2:0, the currency edith's software path speaks. @@ -73,6 +90,7 @@ impl Frame { display_size: (u32, u32), coded_size: (u32, u32), bit_depth: u8, + colour: Option, ) -> Frame { Frame { surface, @@ -81,6 +99,7 @@ impl Frame { display_size, coded_size, bit_depth, + colour, } } @@ -89,6 +108,11 @@ impl Frame { &self.surface } + /// This frame's colour metadata, when the codec's decoder resolves one. + pub fn colour(&self) -> Option { + self.colour + } + /// Export the surface as DRM PRIME file descriptors. /// /// This is the path edith's `engine-hw` takes: the fds are imported into diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 8c759e27..24269672 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -56,5 +56,5 @@ pub use enc::{ CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings, }; pub use error::{Error, Result}; -pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; +pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; pub use pool::{PooledSurface, SurfacePool}; diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 0b7c8fd1..a6928ac4 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -12,6 +12,7 @@ use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Arc; +use std::time::{Duration, Instant}; use ec_hw::{ Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode, @@ -71,7 +72,15 @@ impl Reference { // pictures on a film whose real cadence differs — which shows up // here as everything being one frame out from some point onward. .args([ - "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-", + "-map", + "0:v:0", + "-fps_mode", + "passthrough", + "-pix_fmt", + pix, + "-f", + "rawvideo", + "-", ]) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -657,6 +666,183 @@ fn our_encoder_and_our_decoder_agree() { } } +/// A decoded surface goes straight into an encoder with no `to_i420` +/// read-back, and what comes out is not measurably different from the +/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. +/// +/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block +/// rounding both land on the same 1920x1088 coded size for it, so the +/// decoder's surfaces satisfy `encode_frame`'s coded-size check against +/// either target codec without a second fixture. +#[test] +fn encode_frame_zero_copy_matches_the_cpu_path() { + let Some(display) = display() else { return }; + let (width, height) = (1920u32, 1080u32); + let Some(path) = fixtures(".264") + .into_iter() + .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264")) + else { + eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh"); + return; + }; + let data = std::fs::read(&path).expect("fixture is readable"); + let frames = 10usize; + + for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { + let mut cfg = EncoderConfig::new(target, width, height); + cfg.gop_size = 30; + cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; + let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); + let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); + let mut zc_stream = Vec::new(); + let mut cpu_stream = Vec::new(); + let mut count = 0i64; + + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { + let meta = FrameMetadata { + timestamp: count, + force_keyframe: false, + }; + // The zero-copy path never reads the surface back to the CPU: the + // only `to_i420` call in this loop is the CPU-path baseline's. + let zc = zero_copy + .encode_frame(&frame, meta) + .expect("encode_frame (zero copy)"); + 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); + count += 1; + }) + .expect("decode"); + assert_eq!( + count as usize, frames, + "{target:?}: decoded {count} of {frames}" + ); + + let ext = match target { + EncCodec::H264 => "264", + EncCodec::H265 => "265", + EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), + }; + let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); + std::fs::create_dir_all(&dir).expect("temp dir"); + for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { + std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); + } + + let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); + let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); + let mut zc_frames = Vec::new(); + let mut cpu_frames = Vec::new(); + decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { + zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) + }) + .expect("decode zero-copy stream"); + decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { + cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) + }) + .expect("decode CPU-path stream"); + assert_eq!( + zc_frames.len(), + frames, + "{target:?}: zero-copy stream frame count" + ); + assert_eq!( + cpu_frames.len(), + frames, + "{target:?}: CPU-path stream frame count" + ); + + let worst = zc_frames + .iter() + .zip(&cpu_frames) + .map(|(a, b)| psnr(a, b)) + .fold(f64::INFINITY, f64::min); + println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); + assert!( + worst >= 35.0, + "{target:?}: worst {worst:.1} dB vs the CPU path" + ); + } +} + +/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an +/// export with a colour description survives ffprobe reading it back, and +/// leaving it unset keeps today's behaviour (no `video_signal_type`, +/// deterministically — two encodes of the same picture with no colour set +/// come back byte for byte identical). +#[test] +fn colour_description_reaches_the_vui() { + let Some(display) = display() else { return }; + let (width, height) = (640u32, 480u32); + let dir = std::env::temp_dir().join("ec-hw-colour-vui"); + std::fs::create_dir_all(&dir).expect("temp dir"); + + let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec) { + let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); + cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; + if let Some((primaries, transfer, matrix, full_range)) = colour { + cfg = cfg.colour(primaries, transfer, matrix, full_range); + } + let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); + let coded = enc + .encode( + &source_frame(width, height, 0), + FrameMetadata { + timestamp: 0, + force_keyframe: true, + }, + ) + .expect("encode"); + let path = dir.join(name); + std::fs::write(&path, &coded.data).expect("write bitstream"); + (path, coded.data) + }; + let probe = |path: &Path| -> String { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=color_primaries,color_transfer,color_space", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("ffprobe runs"); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + + // Pinned default case: no colour set, twice, must match exactly. + let (default_path, default_bytes) = encode_one(None, "default-a.265"); + let (_, default_bytes2) = encode_one(None, "default-b.265"); + assert_eq!( + default_bytes, default_bytes2, + "no colour set: two encodes of the same picture must be byte-identical" + ); + let default_probe = probe(&default_path); + println!("no colour set: ffprobe sees `{default_probe}`"); + assert!( + !default_probe.contains("bt2020"), + "no colour set should not read back as BT.2020: `{default_probe}`" + ); + + // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). + let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); + // ffprobe's csv reorders these as color_space,color_transfer,color_primaries + // regardless of the -show_entries order given above. + let got = probe(&bt2020_path); + assert_eq!( + got, "bt2020nc,smpte2084,bt2020", + "ffprobe on the BT.2020 stream" + ); +} + /// AV1 encoding is opt-in, and this test does not turn it on. /// /// It was probed once, live, at the driver's own minimum encode size @@ -1032,3 +1218,478 @@ fn short(path: &Path) -> String { .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default() } + +/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match). +fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { + let n = a.len().min(b.len()); + let mse: f64 = a[..n] + .iter() + .zip(&b[..n]) + .map(|(&p, &q)| { + let d = f64::from(p) - f64::from(q); + d * d + }) + .sum::() + / n as f64; + if mse == 0.0 { + f64::INFINITY + } else { + 10.0 * (peak * peak / mse).log10() + } +} + +/// P010 correctness on the real 4K HDR film, plane by plane. +/// +/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB +/// for a mix of files; this isolates Y from U/V on this specific 10-bit film, +/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the +/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output +/// against this crate's un-dithered right-shift -- a real but small gap, not +/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma +/// plane is being read at the wrong stride/offset; it is not, on this file. +#[test] +fn ten_bit_4k_chroma_is_not_grey() { + let Some(display) = display() else { return }; + let path = Path::new( + "/home/user/Downloads/reeld\ + /reeld.mkv", + ); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let frames = 3usize; + let Some(data) = elementary(path, Codec::H265, frames) else { + eprintln!("skipped: no elementary stream"); + return; + }; + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut ref10: Option = None; + let mut ref8: Option = None; + let mut compared = 0usize; + decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { + let (w, h) = frame.display_size; + let ref10 = + ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); + let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); + let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); + let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); + let uv_db = plane_psnr( + &[got16.u.as_slice(), got16.v.as_slice()].concat(), + &[want10.u.as_slice(), want10.v.as_slice()].concat(), + 1023.0, + ); + println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); + assert!( + y_db >= 50.0, + "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" + ); + assert!( + uv_db >= 50.0, + "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" + ); + + let ref8 = + ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); + let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); + let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); + let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); + let uv_db8 = plane_psnr( + &[got8.u.as_slice(), got8.v.as_slice()].concat(), + &[want8.u.as_slice(), want8.v.as_slice()].concat(), + 255.0, + ); + println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); + // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both + // are legitimate 10-to-8 roundings, so the floor here is the + // dithering noise floor, not the lossless bound above. + assert!( + y_db8 >= 30.0, + "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" + ); + assert!( + uv_db8 >= 30.0, + "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" + ); + compared += 1; + }) + .expect("decode"); + assert_eq!(compared, frames, "not all frames were compared"); +} + +/// The HEVC HDR peak (`content_light_level_information` and +/// `mastering_display_colour_volume` prefix SEI), on the one real file that +/// only carries it there: the Matroska `Colour` element itself has no MaxCLL/ +/// MaxFALL for this rip (verified separately against `ffprobe`), so a decoder +/// that does not read the SEI reports none at all. Numbers match what +/// `ffprobe -show_frames -read_intervals %+#1 -show_entries +/// frame_side_data_list` reports for this file. +#[test] +fn hdr_film_light_level_sei_is_exposed() { + let Some(display) = display() else { return }; + let path = Path::new( + "/home/user/Downloads/reeld\ + /reeld.mkv", + ); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let frames = 2usize; + let Some(data) = elementary(path, Codec::H265, frames) else { + eprintln!("skipped: no elementary stream"); + return; + }; + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut seen = 0usize; + decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { + seen += 1; + let colour = frame + .colour() + .expect("HEVC decoder resolves colour metadata"); + assert_eq!( + colour.description.codes(), + (9, 16, 9), + "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)" + ); + assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL"); + assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL"); + assert!( + colour.light.mastering_max.is_some(), + "mastering display peak missing" + ); + }) + .expect("decode"); + assert_eq!(seen, frames, "not all frames were compared"); +} + +/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` +/// either resolves from the VUI or answers [`None`], but never panics. +#[test] +fn sdr_h264_colour_never_panics() { + let Some(display) = display() else { return }; + let paths = fixtures(".264"); + if paths.is_empty() { + eprintln!("skipped: no H.264 fixtures generated"); + return; + } + let path = &paths[0]; + let Some(data) = std::fs::read(path).ok() else { + eprintln!("skipped: fixture unreadable"); + return; + }; + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + let mut seen = 0usize; + decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { + seen += 1; + // No SEI parsing on this codec: content light is always absent. + if let Some(colour) = frame.colour() { + assert_eq!(colour.light.max_cll, None); + } + }) + .expect("decode"); + assert!(seen > 0, "{}: nothing decoded", short(path)); +} + +/// Per-frame cost of the 4K 10-bit read-back path, isolated from decode +/// submission itself. +/// +/// The consumer's `hw_decode::the_hdr_film_renders_tone_mapped` measured +/// 1352.5 ms/frame against a 39 ms (24 fps) budget on this film. Decode +/// correctness on it is already pinned by `real_library_spot_check` (bit-exact +/// against ffmpeg), so this isolates which stage of the frame path -- decode, +/// 8-bit readback, 10-bit readback or DRM PRIME export -- the time goes to. +#[test] +fn ten_bit_4k_frame_path_is_realtime() { + let Some(display) = display() else { return }; + let path = Path::new( + "/home/user/Downloads/reeld\ + /reeld.mkv", + ); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let limit = 120usize; + let Some(data) = elementary(path, Codec::H265, limit) else { + eprintln!("skipped: no elementary stream"); + return; + }; + let units = split_access_units(&data, Codec::H265); + assert!( + units.len() > limit, + "film clip too short for {limit} frames" + ); + + #[derive(Clone, Copy)] + enum Op { + DecodeOnly, + ToI420, + ToI420_16, + ExportPrime, + } + fn apply(op: Op, frame: Frame) { + match op { + Op::DecodeOnly => drop(frame), + Op::ToI420 => { + frame.to_i420().expect("readback"); + } + Op::ToI420_16 => { + frame.to_i420_16().expect("readback"); + } + Op::ExportPrime => { + frame.export_prime().expect("export"); + } + } + } + + println!( + "{:<22} {:>10} {:>10} {:>10}", + "stage", "median ms", "min ms", "max ms" + ); + let mut got_to_i420_16 = None; + for (name, op) in [ + ("decode-only", Op::DecodeOnly), + ("decode+to_i420", Op::ToI420), + ("decode+to_i420_16", Op::ToI420_16), + ("decode+export_prime", Op::ExportPrime), + ] { + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut durations: Vec = Vec::new(); + // Hold a few frames before reading, as the resident-set test does: + // reading one frame per submission measures latency, not throughput, + // and lets decode run ahead of read-back the way a real player does. + let mut pending: Vec = Vec::new(); + let mut t_prev = Instant::now(); + 'outer: for (i, unit) in units.iter().enumerate() { + decoder.decode(unit, i as i64).expect("decode"); + while let Some(frame) = decoder.next_frame() { + pending.push(frame); + if pending.len() < 4 { + continue; + } + for frame in pending.drain(..) { + apply(op, frame); + let now = Instant::now(); + durations.push(now.duration_since(t_prev)); + t_prev = now; + } + if durations.len() >= limit { + break 'outer; + } + } + } + decoder.flush().expect("flush"); + while durations.len() < limit { + let Some(frame) = decoder.next_frame() else { + break; + }; + apply(op, frame); + let now = Instant::now(); + durations.push(now.duration_since(t_prev)); + t_prev = now; + } + assert!( + durations.len() >= 24, + "{name}: only {} frames decoded", + 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:<22} {median:>10.2} {min:>10.2} {max:>10.2}"); + if name == "decode+to_i420_16" { + got_to_i420_16 = Some(median); + } + } + let got = got_to_i420_16.expect("to_i420_16 phase ran"); + println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}"); +} + +/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in +/// decode order, even though they display before it (they predict from +/// pictures the CRA's own random-access point does not have). A decoder +/// started fresh at that CRA — what a seek does — must therefore drop those +/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by +/// however many RASL pictures the GOP has, handing back the wrong picture for +/// every display index at or after the seek target. +#[test] +fn hevc_seek_matches_linear_mkv() { + let Some(display) = display() else { return }; + let path = bitstreams().join("test_hevc.mkv"); + let Some(data) = elementary(&path, Codec::H265, 45) else { + eprintln!("skipped: no test_hevc.mkv fixture"); + return; + }; + let units = split_access_units(&data, Codec::H265); + + // Linear decode: every picture from the start, frame 30 kept for + // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture + // GOPs). + const TARGET: usize = 30; + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut linear_frame_30 = None; + let mut index = 0usize; + decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { + if index == TARGET { + linear_frame_30 = Some(frame.to_i420().expect("readback")); + } + index += 1; + }) + .expect("linear decode"); + let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); + + // Find the access unit whose first VCL NAL is the CRA at this GOP + // boundary, and feed the decoder from there on, exactly as a seek would: + // nothing from before it goes in. + let cra_at = units + .iter() + .position(|au| starts_with_cra(au)) + .expect("a CRA access unit exists"); + + // A seek reuses the parameter sets a decoder already learned; a fresh one + // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a + // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown + // away) and reset picture state before feeding the seek target. + let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + seek_decoder + .decode(units[0], 0) + .expect("prime parameter sets"); + seek_decoder.reset(); + let mut seeked_frame = None; + for (i, unit) in units[cra_at..].iter().enumerate() { + seek_decoder.decode(unit, i as i64).expect("seek decode"); + if let Some(frame) = seek_decoder.next_frame() { + seeked_frame = Some(frame.to_i420().expect("readback")); + break; + } + } + if seeked_frame.is_none() { + seek_decoder.flush().expect("flush"); + seeked_frame = seek_decoder + .next_frame() + .map(|f| f.to_i420().expect("readback")); + } + let seeked_frame = seeked_frame.expect("a frame came out after the seek"); + + assert_eq!( + seeked_frame, linear_frame_30, + "seeking to the CRA before frame 30 handed back a different picture \ + than a linear decode of frame 30 — RASL pictures were not dropped" + ); +} + +/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice +/// (`nal_unit_type` 1) whose predecessors in decode order can still hold +/// references from before it, so leading pictures between it and the next +/// IDR may predict from a picture never decoded since a fresh start there — +/// exactly what a seek does. A decoder started at that I must drop those +/// leading pictures per D.2.8's recovery point default, or its output shifts +/// by however many leading pictures the GOP has. +#[test] +fn h264_seek_matches_linear_open_gop() { + let Some(display) = display() else { return }; + let path = bitstreams().join("h264-open-gop.mp4"); + let Some(data) = elementary(&path, Codec::H264, 60) else { + eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)"); + return; + }; + let units = split_access_units(&data, Codec::H264); + + // Linear decode: every picture from the start, frame 30 kept for + // comparison (the fixture's second I picture, `keyint=30`). + const TARGET: usize = 30; + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + let mut linear_frame_30 = None; + let mut index = 0usize; + decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { + if index == TARGET { + linear_frame_30 = Some(frame.to_i420().expect("readback")); + } + index += 1; + }) + .expect("linear decode"); + let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); + + // Find the access unit whose first VCL NAL is the open-GOP I picture at + // this GOP boundary, and feed the decoder from there on, exactly as a + // seek would: nothing from before it goes in. + let open_gop_at = units + .iter() + .position(|au| is_open_gop_i(au)) + .expect("an open-GOP I access unit exists"); + + // A seek reuses the parameter sets a decoder already learned; a fresh one + // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a + // caller to: decode the leading IDR (its picture is thrown away) and + // reset picture state before feeding the seek target. + let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + seek_decoder.decode(units[0], 0).expect("prime parameter sets"); + seek_decoder.reset(); + let mut seeked_frame = None; + for (i, unit) in units[open_gop_at..].iter().enumerate() { + seek_decoder.decode(unit, i as i64).expect("seek decode"); + if let Some(frame) = seek_decoder.next_frame() { + seeked_frame = Some(frame.to_i420().expect("readback")); + break; + } + } + if seeked_frame.is_none() { + seek_decoder.flush().expect("flush"); + seeked_frame = seek_decoder + .next_frame() + .map(|f| f.to_i420().expect("readback")); + } + let seeked_frame = seeked_frame.expect("a frame came out after the seek"); + + assert_eq!( + seeked_frame, linear_frame_30, + "seeking to the open-GOP I before frame 30 handed back a different \ + picture than a linear decode of frame 30 — leading pictures with \ + missing references were not dropped" + ); +} + +/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice +/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the +/// access unit's first start code rather than assuming a fixed prefix length. +fn is_open_gop_i(au: &[u8]) -> bool { + let mut i = 0usize; + while i + 3 < au.len() { + if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { + i += 1; + continue; + } + let header = au[i + 3]; + if header & 0x1f != 1 { + return false; + } + let mut r = ec_core::BitReader::new(&au[i + 4..]); + if r.read_ue().is_err() { + return false; + } + return matches!(r.read_ue(), Ok(code) if code % 5 == 2); + } + false +} + +/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). +/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past +/// non-VCL NALs to the first one that carries a slice. +fn starts_with_cra(au: &[u8]) -> bool { + let mut i = 0usize; + while i + 3 < au.len() { + if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { + let t = (au[i + 3] >> 1) & 0x3f; + if t <= 31 { + return t == 21; + } + i += 3; + continue; + } + i += 1; + } + false +} diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 930c15c8..c6359040 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -8,7 +8,7 @@ use std::io::BufReader; use std::path::{Path, PathBuf}; use std::process::Command; -use ec_core::{Demuxer, Error, Muxer, SeekMode, TimeBase, Timestamp}; +use ec_core::{Demuxer, Error, MediaType, Muxer, SeekMode, TimeBase, Timestamp}; use ec_matroska::{MatroskaDemuxer, MatroskaMuxer}; fn fixtures() -> PathBuf { @@ -711,3 +711,149 @@ fn the_first_cluster_is_reachable_when_no_cue_names_it() { break; } } + + +/// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in +/// *timestamp* -- split from decode, per the round's charter: this measures +/// only [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what +/// `ffprobe` reports for the same track near the same instant. If this lands +/// exact, the +0.145 s the consumer measured is downstream of the demuxer +/// (the AC-3 decoder or its frame-count bookkeeping in `engine`), not here. +/// +/// Skipped, not failed, without the film: a claim about his library cannot be +/// made by a machine that does not have it. +#[test] +fn seek_landing_on_his_eac3_film_matches_ffprobe() { + same_class_sweep( + "/home/user/Downloads/reeld/reeld.mkv", + &[600.0, 610.0], + ); + // Same-class sweep (round charter task 3): an Opus 5.1 Matroska, a codec + // that already goes through this crate's demuxer -- if this lands as + // tight as the E-AC-3 one, the demuxer's seek is not codec-specific and + // the +0.145 s the consumer measured on the E-AC-3 path is downstream of + // it either way. + same_class_sweep( + "/home/user/Downloads/reelb.mkv", + &[600.0, 610.0], + ); +} + +/// Where our own demuxer's seek lands on `path`, in *timestamp* -- split from +/// decode, per the round's charter: this measures only +/// [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what +/// `ffprobe` reports for the same track near the same instant. +/// +/// Skipped, not failed, without the film: a claim about his library cannot be +/// made by a machine that does not have it. +fn same_class_sweep(path: &str, wants: &[f64]) { + let film = Path::new(path); + if !film.exists() { + eprintln!("skipped: {path} is not present"); + return; + } + let mut demux = + MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))).expect("demuxes"); + let audio = demux + .streams() + .iter() + .find(|s| s.params.codec.media_type() == MediaType::Audio) + .expect("the film has an audio stream") + .clone(); + + for &want in wants { + let target = Timestamp::new( + (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64, + audio.time_base, + ); + demux + .seek(audio.index, target, SeekMode::SyncBefore) + .expect("seek"); + let landed = loop { + let packet = demux.next_packet().expect("a packet after the seek"); + if packet.stream == audio.index { + break packet.pts.expect("audio packet carries a pts"); + } + }; + let our_secs = landed as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64; + + let ffprobe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "packet=pts_time", + "-of", + "csv=p=0", + "-read_intervals", + ]) + .arg(format!("{want}%+#1")) + .arg(film) + .output(); + let Ok(ffprobe) = ffprobe else { + eprintln!("skipped ffprobe cross-check: ffprobe not runnable"); + eprintln!("want {want}s, our demuxer landed at {our_secs:.3}s (pts {landed})"); + continue; + }; + let reference: f64 = String::from_utf8_lossy(&ffprobe.stdout) + .lines() + .next() + .unwrap_or("") + .trim() + .parse() + .unwrap_or(f64::NAN); + eprintln!( + "want {want}s: our demuxer landed {our_secs:.3}s (pts {landed}), ffprobe's own packet at {reference:.3}s" + ); + } +} + +/// `ffprobe` reports MaxCLL 1230 / MaxFALL 419 for this real HDR10 film, but +/// that reading comes from `[SIDE_DATA]` on the first *frame* (a +/// `content_light_level_information` HEVC SEI message inside the bitstream), +/// not from the container's own `Colour` element. This file's `Colour` +/// element genuinely carries no `MaxCLL`/`MaxFALL`/`MasteringMetadata` +/// children (checked with `ffprobe -show_entries stream=side_data_list`, +/// which comes back empty) — so a demuxer-only reader is correct to return +/// `None` here, and the consumer's brightness-metadata gap is downstream, in +/// whether anything reads the HEVC SEI (`ec_core::color::hevc_sei_light` +/// exists and round-trips in `ec-h265-syntax`, but nothing in this workspace +/// calls it from a real decode path yet). +#[test] +#[ignore = "reads a real local file, not a CI fixture"] +fn real_hdr_film_container_states_no_light_metadata() { + use ec_core::{Demuxer, MediaParameters}; + use ec_matroska::MatroskaDemuxer; + let path = "/home/user/Downloads/reeld/reeld.mkv"; + if !std::path::Path::new(path).exists() { + eprintln!("skipped: film not present"); + return; + } + let f = std::fs::File::open(path).expect("open"); + let demux = MatroskaDemuxer::new(f).expect("demux opens"); + let mut checked = false; + for s in demux.streams() { + if let MediaParameters::Video(v) = &s.params.media { + println!("color = {:?}", v.color); + println!("light = {:?}", v.light); + // BT.2020 non-constant luminance, PQ transfer, BT.2020 primaries — + // this much the Colour element does carry, and it must match + // ffprobe's color_space/color_primaries/color_transfer. + assert_eq!(v.color.matrix, 9, "expected bt2020nc"); + assert_eq!(v.color.transfer, 16, "expected smpte2084 (PQ)"); + assert_eq!(v.color.primaries, 9, "expected bt2020"); + assert_eq!( + v.light, + ec_core::color::ContentLight::default(), + "the Colour element has no light metadata for this file — a \ + non-default reading here would mean either ffprobe or this \ + reader started finding it in the container and the doc \ + comment above is stale" + ); + checked = true; + } + } + assert!(checked, "no video stream found"); +} diff --git a/scripts/aac-tables/make-heaac-fixtures.sh b/scripts/aac-tables/make-heaac-fixtures.sh new file mode 100755 index 00000000..279aebee --- /dev/null +++ b/scripts/aac-tables/make-heaac-fixtures.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Deterministic HE-AAC v1 fixture matrix for tests/sbr_real_library.rs's +# `synthetic_heaac_matrix`: two sample-rate families (48000, 44100) x four +# bitrates (32k/48k/64k/96k) x two profiles (aac_he, aac_low control) = 16 +# .m4a files, sweeping the SBR crossover (kx/k2) that bitrate controls +# without depending on any one real file's content. +# +# `ffmpeg`'s system libfdk_aac (the `fdk-aac-free` package) has SBR/PS +# encoding compiled out (patent-restricted tools) -- `-profile:a aac_he` +# fails with "Unable to set the AOT 5: Invalid config" against it. RPM +# Fusion's full `fdk-aac` package carries the SBR-capable encoder but +# installs to its OWN /usr/lib64/fdk-aac dir specifically so it doesn't +# clobber the system one; this script fetches (no root) and extracts just +# that .so into a local cache and points ffmpeg at it via +# LD_LIBRARY_PATH for the encode step only, never touching the system +# library. +set -euo pipefail + +SCRATCH="${EC_AAC_HEAAC_FIXTURES:-$(cd "$(dirname "$0")/../.." && pwd)/.cache/heaac-fixtures}" +mkdir -p "$SCRATCH" +CACHE="$SCRATCH/.fdk-aac-full" +mkdir -p "$CACHE" + +fdk_libdir="$CACHE/usr/lib64/fdk-aac" +if [ ! -f "$fdk_libdir/libfdk-aac.so.2" ]; then + echo "fetching SBR-capable libfdk-aac (no root, local cache only)..." + ( cd "$CACHE" && dnf download fdk-aac.x86_64 ) + rpm_file=$(find "$CACHE" -maxdepth 1 -name 'fdk-aac-*.rpm' | head -1) + ( cd "$CACHE" && rpm2cpio "$rpm_file" | cpio -idm --quiet ) +fi +export LD_LIBRARY_PATH="$fdk_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + +# Three summed sweeps 100 Hz -> 18 kHz over the full 30 s (phase(t) = +# 2*pi*(f0*t + (f1-f0)/(2T)*t^2), f0=100 f1=18000 T=30 -> +# (f1-f0)/(2T)=298.333), offset in phase per partial and per channel so +# left/right are correlated but not identical -- plus low-level pink noise +# (seeded, so every run of this script reproduces bit-identical fixtures). +sweep() { echo "0.15*sin(2*PI*(100*t+298.333*t*t)+$1)+0.15*sin(2*PI*(100*t+298.333*t*t)+$2)+0.15*sin(2*PI*(100*t+298.333*t*t)+$3)"; } +L=$(sweep 0 1.047 2.094) +R=$(sweep 0.5 1.571 2.618) + +synth_source() { + local rate=$1 out=$2 + ffmpeg -y -hide_banner -loglevel error -filter_complex " + aevalsrc=exprs='${L}|${R}':channel_layout=stereo:sample_rate=${rate}:duration=30 [tone]; + anoisesrc=color=pink:amplitude=0.05:seed=42:sample_rate=${rate}:duration=30 [n0]; + anoisesrc=color=pink:amplitude=0.05:seed=43:sample_rate=${rate}:duration=30 [n1]; + [n0][n1] amerge=inputs=2 [noise]; + [tone][noise] amix=inputs=2:normalize=0 [out] + " -map "[out]" -ar "$rate" -sample_fmt s16 -f wav "$out" +} + +for rate in 48000 44100; do + src="$SCRATCH/src_${rate}.wav" + [ -f "$src" ] || synth_source "$rate" "$src" + for br in 32k 48k 64k 96k; do + he="$SCRATCH/heaac_${rate}_${br}.m4a" + lc="$SCRATCH/lc_${rate}_${br}.m4a" + [ -f "$he" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \ + -c:a libfdk_aac -profile:a aac_he -b:a "$br" "$he" + [ -f "$lc" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \ + -c:a libfdk_aac -profile:a aac_low -b:a "$br" "$lc" + done +done + +echo "fixtures in $SCRATCH:" +ls "$SCRATCH"/*.m4a diff --git a/scripts/gen-fixtures.sh b/scripts/gen-fixtures.sh index 64ce90d9..cbcb5f8d 100755 --- a/scripts/gen-fixtures.sh +++ b/scripts/gen-fixtures.sh @@ -198,6 +198,15 @@ for spec in "${VIDEO_CODECS[@]}"; do esac done +# Open-GOP H.264: a non-IDR I picture (nal_unit_type 1, not 5) at a GOP +# boundary, with B-pyramid pictures around it referencing across the +# boundary. A decoder started fresh at that I (what a seek does) must not +# hand back a picture whose references it never decoded — the H.264 sibling +# of the HEVC RASL/NoRaslOutputFlag case. +gen "$FIXTURES/video/h264-open-gop.mp4" \ + -f lavfi -i "testsrc2=size=320x240:rate=30:duration=4" -pix_fmt yuv420p \ + -c:v libx264 -x264-params "keyint=30:min-keyint=30:open-gop=1:bframes=3:b-pyramid=normal:scenecut=0" + # -------------------------------------------------------------- summary ----- printf '\n%s\n' "== fixtures: $FIXTURES ==" printf '%-42s %10s %s\n' FILE SIZE PROBE