forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into sbr-normative-qmf

Browse files at this commit

f3d1b0d3e877e820ac68006dbccb877fbc3e8c24Ahmet Kaan GümüşParent: ddccd80a5703e8
.gitignoremodified+1 -0
@@ -2,3 +2,4 @@ target/
22 fixtures/
33 __pycache__/
44 scripts/aac-tables/sbr-cache.json
5+.cache/
crates/ec-aac/tests/sbr_real_library.rsmodified+256 -0
@@ -2107,6 +2107,262 @@ fn full_chain_low_band_matches_own_core() {
21072107 }
21082108 }
21092109
2110+/// Follow-up to round-52: `best_lag_correlation`'s `LAG_MAX=4000` bound was
2111+/// landing HE-AAC winning lags right at its own edge (-3634..-3882) on the
2112+/// synthetic matrix -- this is the same shape `wide_lag_search_full_chain`
2113+/// diagnosed on FMJ. Mirrors that diagnostic's odd-stride coarse pass, but
2114+/// over a caller-supplied `lag_max` and followed by the same full-`WINDOW`
2115+/// refine `best_lag_correlation` does, so its result is directly comparable
2116+/// (not just a coarse `|corr|` estimate).
2117+fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) {
2118+ const COARSE: usize = 4096;
2119+ let start = ours
2120+ .len()
2121+ .min(theirs.len())
2122+ .saturating_sub(WINDOW)
2123+ .min(ours.len() / 4);
2124+ let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
2125+ let (oa, ob) = if lag >= 0 {
2126+ (start, start + lag as usize)
2127+ } else {
2128+ (start + (-lag) as usize, start)
2129+ };
2130+ if oa + len > ours.len() || ob + len > theirs.len() {
2131+ None
2132+ } else {
2133+ Some((oa, ob))
2134+ }
2135+ };
2136+ let mut coarse_best = (0i64, -1.0f64);
2137+ let mut lag = -lag_max;
2138+ while lag <= lag_max {
2139+ if let Some((oa, ob)) = slice_at(lag, COARSE) {
2140+ let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs();
2141+ if c > coarse_best.1 {
2142+ coarse_best = (lag, c);
2143+ }
2144+ }
2145+ lag += 11; // odd stride so it doesn't alias against frame-length periodicity
2146+ }
2147+ let mut best = (coarse_best.0, -1.0f64, 0.0f64);
2148+ for lag in (coarse_best.0 - 16)..=(coarse_best.0 + 16) {
2149+ let Some((oa, ob)) = slice_at(lag, WINDOW) else {
2150+ continue;
2151+ };
2152+ let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
2153+ if n < 1024 {
2154+ continue;
2155+ }
2156+ let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]);
2157+ if c.abs() > best.1 {
2158+ best = (lag, c.abs(), c);
2159+ }
2160+ }
2161+ (best.0, best.2)
2162+}
2163+
2164+/// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real
2165+/// file each, whose sample rate, bitrate and content all differ at once),
2166+/// every row here decodes the SAME synthesized source (three summed sine
2167+/// sweeps 100 Hz-18 kHz + seeded pink noise, per-channel phase offset),
2168+/// varying only sample rate (44100/48000) and bitrate (32k/48k/64k/96k,
2169+/// which sweeps the SBR crossover `kx`/`k2`), so a break tied to a rate
2170+/// FAMILY or to `kx` GEOMETRY shows as a pattern across the table instead
2171+/// of being confounded with one file's own content. `aac_low` control rows
2172+/// (no SBR at all) prove the harness itself -- container extraction,
2173+/// decode, correlation -- is sound before the HE-AAC rows next to them are
2174+/// trusted; those are the only asserted numbers here, everything else is
2175+/// instrumentation for the ledger, not a regression gate yet.
2176+///
2177+/// Env-gated on `EC_AAC_HEAAC_FIXTURES` (defaults to the same
2178+/// `<repo>/.cache/heaac-fixtures` `scripts/aac-tables/make-heaac-fixtures.sh`
2179+/// writes to) -- skips loudly, generates nothing itself, when that
2180+/// directory is absent.
2181+#[test]
2182+fn synthetic_heaac_matrix() {
2183+ if !have_ffmpeg() {
2184+ eprintln!("SKIP: ffmpeg not on PATH");
2185+ return;
2186+ }
2187+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| {
2188+ format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))
2189+ });
2190+ let dir = PathBuf::from(dir);
2191+ if !dir.is_dir() {
2192+ eprintln!(
2193+ "SKIP: {} absent -- run scripts/aac-tables/make-heaac-fixtures.sh first",
2194+ dir.display()
2195+ );
2196+ return;
2197+ }
2198+ unsafe {
2199+ std::env::set_var("EC_AAC_SBR_SIDEINFO_DEBUG", "1");
2200+ }
2201+ println!(
2202+ "{:>5} {:>6} {:>4} {:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
2203+ "rate", "kbps", "prof", "kx", "k2", "full", "below", "above", "lag", "ours_v_core", "ovc_lag",
2204+ "core_v_ref", "cvr_lag", "core_rate", "full_rate"
2205+ );
2206+ // Wide enough that the WIDE_LAG_MAX==LC's own decoder priming delay
2207+ // (2048) plus a full SBR-chain worth of extra delay (a few thousand
2208+ // samples at the doubled/full output rate) both land well inside it,
2209+ // not right at the edge the way the plain (LAG_MAX=4000) search did.
2210+ const WIDE_LAG_MAX: i64 = 20_000;
2211+ for rate in [48_000u32, 44_100] {
2212+ for br in ["32k", "48k", "64k", "96k"] {
2213+ // LC first: its winning lag is the pure container/decoder
2214+ // priming delay with no SBR chain involved, and is reused below
2215+ // as the anchor for the HE row's own delay-candidate probe.
2216+ let mut lc_lag: Option<i64> = None;
2217+ for (profile, prefix) in [("LC", "lc"), ("HE", "heaac")] {
2218+ let path = dir.join(format!("{prefix}_{rate}_{br}.m4a"));
2219+ if !path.exists() {
2220+ eprintln!("SKIP {}: missing", path.display());
2221+ continue;
2222+ }
2223+ let before = ec_aac::sbr_sideinfo_log().len();
2224+ let Some((ours, _sbr, our_rate)) = our_decode(&path, 0) else {
2225+ eprintln!("SKIP {}: could not decode", path.display());
2226+ continue;
2227+ };
2228+ let rows = ec_aac::sbr_sideinfo_log();
2229+ let (kx, k2) = rows[before..]
2230+ .iter()
2231+ .find(|r| r.ch == 0)
2232+ .map(|r| (r.kx, r.k2))
2233+ .unwrap_or((-1, -1));
2234+ let theirs = ffmpeg_decode(&path, 0, ours.len());
2235+ let o = &ours[0];
2236+ let t = &theirs[0];
2237+ let (lag, full) = best_lag_correlation_wide(o, t, WIDE_LAG_MAX);
2238+ if profile == "LC" {
2239+ lc_lag = Some(lag);
2240+ }
2241+ // Crossover in Hz from the actual parsed kx (band width
2242+ // rate/128, same domain `sbr_chain.rs`'s own doc comment
2243+ // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist
2244+ // split for the LC controls, which carry no kx at all.
2245+ let crossover_hz = if kx > 0 {
2246+ f64::from(our_rate) * (kx as f64) / 128.0
2247+ } else {
2248+ f64::from(our_rate) * 0.25
2249+ };
2250+ let (_, below) = best_lag_correlation_wide(
2251+ &lowpass(o, our_rate, crossover_hz),
2252+ &lowpass(t, our_rate, crossover_hz),
2253+ WIDE_LAG_MAX,
2254+ );
2255+ // `above` re-slices at the FULL-band winning `lag` before
2256+ // splitting, same convention `sbr_real_library_matches_reference`
2257+ // uses -- round-52's first cut of this row measured `o[..n]`
2258+ // against `t[..n]` with no lag offset at all, which is only
2259+ // valid by accident at lag 0 and was silently wrong for
2260+ // every other winning lag in that table.
2261+ let (oa, ob) = if lag >= 0 {
2262+ (0usize, lag as usize)
2263+ } else {
2264+ ((-lag) as usize, 0usize)
2265+ };
2266+ let n = WINDOW.min(o.len().saturating_sub(oa)).min(t.len().saturating_sub(ob));
2267+ let above = if n >= 1024 {
2268+ correlation(
2269+ &highpass(&o[oa..oa + n], our_rate, crossover_hz),
2270+ &highpass(&t[ob..ob + n], our_rate, crossover_hz),
2271+ )
2272+ } else {
2273+ 0.0
2274+ };
2275+ // Round-51's self-consistency probe (our full chain's low
2276+ // band vs our own core-only decode, 2x upsampled), run
2277+ // per-row so a rate/kx-specific self-inconsistency shows in
2278+ // the same table instead of needing a second pass.
2279+ let ours_v_core = if kx > 0 {
2280+ our_decode_core_only(&path, 0).map(|(core, core_rate)| {
2281+ let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();
2282+ let cutoff = f64::from(core_rate) * 0.4;
2283+ let ol = lowpass(o, our_rate, cutoff);
2284+ let ul = lowpass(&up, our_rate, cutoff);
2285+ best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX)
2286+ })
2287+ } else {
2288+ None
2289+ };
2290+ // Coordinator follow-up 2: splits "our core decode of THIS
2291+ // fixture is wrong" (core_v_ref ~0) from "the SBR chain
2292+ // scrambles a good core" (core_v_ref >= ~0.99 while `below`
2293+ // above stays ~0/negative) -- OUR core-only decode (2x
2294+ // upsampled, same convention `ours_v_core` uses) against the
2295+ // REFERENCE decoder's own decode, below the crossover only,
2296+ // wide lag search since this is an independent alignment
2297+ // from `full`/`below`'s (core-only carries no SBR delay).
2298+ let (core_v_ref, core_rate_str) = if kx > 0 {
2299+ match our_decode_core_only(&path, 0) {
2300+ Some((core, core_rate)) => {
2301+ let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();
2302+ let tl = lowpass(t, our_rate, crossover_hz);
2303+ let ul = lowpass(&up, our_rate, crossover_hz);
2304+ (Some(best_lag_correlation_wide(&ul, &tl, WIDE_LAG_MAX)), core_rate.to_string())
2305+ }
2306+ None => (None, "n/a".into()),
2307+ }
2308+ } else {
2309+ (None, "n/a".into())
2310+ };
2311+ println!(
2312+ "{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}",
2313+ ours_v_core
2314+ .map(|(_, c)| format!("{c:.4}"))
2315+ .unwrap_or_else(|| "n/a".into()),
2316+ ours_v_core
2317+ .map(|(l, _)| l.to_string())
2318+ .unwrap_or_else(|| "n/a".into()),
2319+ core_v_ref
2320+ .map(|(_, c)| format!("{c:.4}"))
2321+ .unwrap_or_else(|| "n/a".into()),
2322+ core_v_ref
2323+ .map(|(l, _)| l.to_string())
2324+ .unwrap_or_else(|| "n/a".into()),
2325+ core_rate_str,
2326+ our_rate,
2327+ );
2328+ // Coordinator follow-up (4): on the two named rows, probe
2329+ // candidate total HE-vs-reference delays built from LC's own
2330+ // priming lag plus a guessed SBR-chain contribution, to see
2331+ // which (if any) actually lands near 1.0 -- and whether that
2332+ // offset is constant across the two rows.
2333+ if profile == "HE"
2334+ && ((rate == 44_100 && br == "48k") || (rate == 48_000 && br == "64k"))
2335+ {
2336+ let lc = lc_lag.unwrap_or(-2048);
2337+ println!(" ch0 delay probe (LC lag {lc}):");
2338+ for (label, extra) in [
2339+ ("2990", 2990i64),
2340+ ("3010", 3010),
2341+ ("3020", 3020),
2342+ ("1505x2", 1505 * 2),
2343+ ("962x2", 962 * 2),
2344+ ] {
2345+ let candidate = (lc - 2048) + extra;
2346+ println!(
2347+ " offset={label:>6} -> lag={candidate:>6} corr={:.6}",
2348+ correlation_at_lag(o, t, candidate)
2349+ );
2350+ }
2351+ }
2352+ if profile == "LC" {
2353+ assert!(
2354+ full >= 0.999,
2355+ "{}: LC control full-band corr {full:.6} < 0.999 -- the \
2356+ harness itself (extraction/decode/correlation) is broken, \
2357+ not the SBR chain this fixture matrix is meant to isolate",
2358+ path.display()
2359+ );
2360+ }
2361+ }
2362+ }
2363+ }
2364+}
2365+
21102366 fn candidates() -> Vec<Candidate> {
21112367 let home = std::env::var("HOME").unwrap_or_default();
21122368 [
crates/ec-h264/src/decoder.rsmodified+33 -3
@@ -134,6 +134,19 @@ pub struct Decoder {
134134 out: VecDeque<VideoFrame>,
135135 /// Presentation timestamp to attach to the next picture started.
136136 pending_pts: Option<Timestamp>,
137+ /// `PicOrderCnt` of the random-access point most recently established by
138+ /// [`Decoder::reset_pictures`] — the first picture decoded after it,
139+ /// i.e. the I picture a seek landed on. `None` before that picture
140+ /// completes. Absent a recovery_point SEI (not parsed here), D.2.8's
141+ /// recovery point defaults to this picture itself: anything with a
142+ /// smaller POC that had to guess a reference (see `cur_ref_padded`)
143+ /// predicts from something never decoded since the seek and must not
144+ /// reach the caller.
145+ recovery_poc: Option<i32>,
146+ /// Set while decoding the open picture if `build_ref_lists` had to pad a
147+ /// reference list, i.e. this picture asked for a reference the DPB does
148+ /// not have. Reset per picture in `start_picture`.
149+ cur_ref_padded: bool,
137150 }
138151
139152 /// What [`Decoder::push_nal`] did with a NAL unit.
@@ -199,6 +212,8 @@ impl Decoder {
199212 output_order: OutputOrder::default(),
200213 out: VecDeque::new(),
201214 pending_pts: None,
215+ recovery_poc: None,
216+ cur_ref_padded: false,
202217 }
203218 }
204219
@@ -301,13 +316,18 @@ impl Decoder {
301316 self.cur.extend_borders();
302317 self.cur.complete = true;
303318 self.last_decoded = self.cur.id;
319+ // The first picture completed after a reset is the random-access
320+ // point the seek landed on; its own POC becomes the recovery
321+ // threshold (see `recovery_poc`'s doc comment).
322+ let recovery_poc = *self.recovery_poc.get_or_insert(self.cur.poc);
323+ let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc);
304324 let sps_id = self.cur.sps_id as usize;
305325 let sps = self.sps_map[sps_id]
306326 .take()
307327 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
308328 let pic = core::mem::take(&mut self.cur);
309329 let marking = self.has_marking.then_some(&self.cur_marking);
310- let stored = self.dpb.store(pic, &sps, &self.cur_info, marking);
330+ let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok);
311331 self.sps_map[sps_id] = Some(sps);
312332 stored?;
313333 self.has_picture = false;
@@ -357,6 +377,7 @@ impl Decoder {
357377 self.out.clear();
358378 self.last_decoded = -1;
359379 self.pending_pts = None;
380+ self.recovery_poc = None;
360381 }
361382
362383 /// Move pictures out of the decoded picture buffer into the output queue.
@@ -472,7 +493,7 @@ impl Decoder {
472493 [RefList::default(), RefList::default()]
473494 } else {
474495 self.dpb.number_short_term(sh.frame_num, sps);
475- self.dpb.build_ref_lists(
496+ let (lists, padded) = self.dpb.build_ref_lists(
476497 sh.slice_type,
477498 self.cur.poc,
478499 sh.frame_num as i32,
@@ -480,7 +501,15 @@ impl Decoder {
480501 sh.num_ref_idx_l0_active as usize,
481502 sh.num_ref_idx_l1_active as usize,
482503 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
483- )?
504+ )?;
505+ // A ref list shorter than requested was padded by repeating an
506+ // available entry (8.2.4.2's unspecified tail) rather than the
507+ // reference this slice actually asked for. Right after a seek's
508+ // reset, that means the picture predicts from something never
509+ // decoded since the random-access start; recorded here so
510+ // `end_picture` can hold its output back (see `recovery_poc`).
511+ self.cur_ref_padded |= padded;
512+ lists
484513 };
485514
486515 let mut r = if pps.entropy_coding_mode {
@@ -632,6 +661,7 @@ impl Decoder {
632661 sh: &SliceHeader,
633662 header: NalHeader,
634663 ) -> Result<()> {
664+ self.cur_ref_padded = false;
635665 let info = PicInfo {
636666 is_idr: header.is_idr(),
637667 is_reference: header.ref_idc != 0,
crates/ec-h264/src/dpb.rsmodified+18 -7
@@ -644,7 +644,8 @@ impl Dpb {
644644 num_l0: usize,
645645 num_l1: usize,
646646 mods: (&[RefPicListMod], &[RefPicListMod]),
647- ) -> Result<[RefList; 2]> {
647+ ) -> Result<([RefList; 2], bool)> {
648+ let mut padded = false;
648649 let mut lists = [RefList::default(), RefList::default()];
649650 // Short-term candidates, then long-term, both by index into `frames`.
650651 let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
@@ -737,13 +738,16 @@ impl Dpb {
737738 // conformant stream fills it by modification; repeating entry 0
738739 // keeps every index in range meanwhile.
739740 let first = lists[x].entries[0];
741+ if lists[x].len < wanted[x] {
742+ padded = true;
743+ }
740744 while lists[x].len < wanted[x] {
741745 lists[x].push(usize::from(first));
742746 }
743747 lists[x].len = wanted[x];
744748 self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
745749 }
746- Ok(lists)
750+ Ok((lists, padded))
747751 }
748752
749753 /// Reference picture list modification (clause 8.2.4.3), following the
@@ -826,15 +830,22 @@ impl Dpb {
826830 }
827831
828832 /// Store a decoded picture and apply the reference marking of 8.2.5.
833+ ///
834+ /// `output_ok` is false for a picture that predicted from a reference
835+ /// never decoded since the last `reset()` (a random-access leading
836+ /// picture whose ref list build had to pad) — it still joins the DPB, as
837+ /// a reference for later pictures and for `PicNum`/`FrameNumWrap`
838+ /// bookkeeping, but the bumping process must never hand it to a caller.
829839 pub(crate) fn store(
830840 &mut self,
831841 mut pic: Picture,
832842 sps: &Sps,
833843 info: &PicInfo,
834844 marking: Option<&DecRefPicMarking>,
845+ output_ok: bool,
835846 ) -> Result<()> {
836847 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
837- pic.output = true;
848+ pic.output = output_ok;
838849 pic.complete = true;
839850 // Clause 8.2.4.1 against this picture's frame_num, which is what both
840851 // the sliding window (8.2.5.3) and the MMCO picture numbers (8.2.5.4)
@@ -1275,7 +1286,7 @@ mod tests {
12751286 lt.long_term_frame_idx = 1;
12761287 lt.pic_num = 1;
12771288 dpb.frames.push(lt);
1278- let lists = dpb
1289+ let (lists, _) = dpb
12791290 .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[]))
12801291 .unwrap();
12811292 let nums: Vec<i32> = (0..lists[0].len())
@@ -1292,7 +1303,7 @@ mod tests {
12921303 push_ref(&mut dpb, 1, 8, Mark::Short);
12931304 push_ref(&mut dpb, 2, 4, Mark::Short);
12941305 push_ref(&mut dpb, 3, 12, Mark::Short);
1295- let lists = dpb
1306+ let (lists, _) = dpb
12961307 .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[]))
12971308 .unwrap();
12981309 let poc = |l: &RefList| -> Vec<i32> {
@@ -1313,7 +1324,7 @@ mod tests {
13131324 push_ref(&mut dpb, 1, 2, Mark::Short);
13141325 // Both references precede the current picture, so initialisation gives
13151326 // list 0 and list 1 the same descending-POC order.
1316- let lists = dpb
1327+ let (lists, _) = dpb
13171328 .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[]))
13181329 .unwrap();
13191330 let l0: Vec<i32> = (0..2)
@@ -1338,7 +1349,7 @@ mod tests {
13381349 abs_diff_pic_num_minus1: 2,
13391350 add: false,
13401351 }];
1341- let lists = dpb
1352+ let (lists, _) = dpb
13421353 .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[]))
13431354 .unwrap();
13441355 let nums: Vec<i32> = (0..3)
crates/ec-h264/tests/conformance.rsmodified+131 -0
@@ -2245,3 +2245,134 @@ fn high_profile_8x8_inter_sequences_match_ffmpeg() {
22452245 let _ = std::fs::remove_dir_all(&dir);
22462246 assert!(failures.is_empty(), "{failures:#?}");
22472247 }
2248+
2249+/// An open-GOP boundary's non-IDR I picture (`nal_unit_type` 1, not 5) is
2250+/// followed in decode order by leading B pictures that display *before* it
2251+/// but predict from the previous GOP. A decoder started fresh at that I
2252+/// picture — what a seek does — never decoded those previous-GOP references,
2253+/// so it must not hand back the leading B pictures at all (H.264's analogue
2254+/// of HEVC's RASL/`NoRaslOutputFlag` case): output must resume at the I
2255+/// picture itself, per D.2.8 absent a recovery_point SEI.
2256+#[test]
2257+fn h264_seek_matches_linear_open_gop() {
2258+ if !have_ffmpeg() {
2259+ eprintln!("SKIP: ffmpeg not on PATH");
2260+ return;
2261+ }
2262+ let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4");
2263+ if !src.is_file() {
2264+ eprintln!("SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)");
2265+ return;
2266+ }
2267+ let dir = scratch("open-gop");
2268+ std::fs::create_dir_all(&dir).unwrap();
2269+ let annexb = dir.join("open-gop.264");
2270+ assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction");
2271+ let data = std::fs::read(&annexb).unwrap();
2272+ let _ = std::fs::remove_dir_all(&dir);
2273+
2274+ // Split into access units the way a demuxer would: a new one starts at
2275+ // each slice NAL (type 1 or 5).
2276+ let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
2277+ .map(<[u8]>::to_vec)
2278+ .collect();
2279+ let mut access_units: Vec<Vec<u8>> = Vec::new();
2280+ let mut current: Vec<u8> = Vec::new();
2281+ let mut current_has_slice = false;
2282+ for unit in &units {
2283+ let is_slice = matches!(unit[0] & 0x1F, 1 | 5);
2284+ if is_slice && current_has_slice {
2285+ access_units.push(std::mem::take(&mut current));
2286+ current_has_slice = false;
2287+ }
2288+ current_has_slice |= is_slice;
2289+ current.extend_from_slice(&[0, 0, 0, 1]);
2290+ current.extend_from_slice(unit);
2291+ }
2292+ if current_has_slice {
2293+ access_units.push(current);
2294+ }
2295+
2296+ // Linear decode: every picture from the start, display frame 30 kept for
2297+ // comparison (the fixture's second I picture, `keyint=30`).
2298+ const TARGET: usize = 30;
2299+ let mut dec = Decoder::new();
2300+ let mut linear_frame_30 = None;
2301+ let mut index = 0usize;
2302+ for nal in ec_h264_syntax::AnnexBIter::new(&data) {
2303+ if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary {
2304+ dec.end_picture().expect("end_picture");
2305+ dec.push_nal(nal).expect("re-push");
2306+ }
2307+ while let Some(f) = dec.next_frame() {
2308+ if index == TARGET {
2309+ linear_frame_30 = Some(frame_bytes(&f));
2310+ }
2311+ index += 1;
2312+ }
2313+ }
2314+ dec.flush().expect("flush");
2315+ while let Some(f) = dec.next_frame() {
2316+ if index == TARGET {
2317+ linear_frame_30 = Some(frame_bytes(&f));
2318+ }
2319+ index += 1;
2320+ }
2321+ let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
2322+
2323+ // Find the access unit whose first VCL NAL is a non-IDR I slice
2324+ // (`nal_unit_type` 1, `slice_type % 5 == 2`) — the open-GOP boundary.
2325+ let is_open_gop_i = |au: &[u8]| -> bool {
2326+ let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else {
2327+ return false;
2328+ };
2329+ if header & 0x1F != 1 {
2330+ return false;
2331+ }
2332+ let mut r = ec_core::BitReader::new(payload);
2333+ if r.read_ue().is_err() {
2334+ return false;
2335+ }
2336+ matches!(r.read_ue(), Ok(code) if code % 5 == 2)
2337+ };
2338+ let cra_at = access_units
2339+ .iter()
2340+ .position(|au| is_open_gop_i(au))
2341+ .expect("an open-GOP I access unit exists");
2342+
2343+ // A seek reuses the parameter sets a decoder already learned; a fresh one
2344+ // is primed the way `Decoder::reset_pictures`'s doc comment expects: the
2345+ // leading IDR's parameter sets are decoded and its picture discarded.
2346+ let mut seek_dec = Decoder::new();
2347+ for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) {
2348+ seek_dec.push_nal(nal).expect("prime parameter sets");
2349+ }
2350+ seek_dec.end_picture().expect("end priming IDR");
2351+ seek_dec.reset_pictures();
2352+
2353+ let mut seeked_frame = None;
2354+ 'outer: for au in &access_units[cra_at..] {
2355+ for nal in ec_h264_syntax::AnnexBIter::new(au) {
2356+ if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary {
2357+ seek_dec.end_picture().expect("end_picture");
2358+ seek_dec.push_nal(nal).expect("re-push");
2359+ }
2360+ }
2361+ if let Some(f) = seek_dec.next_frame() {
2362+ seeked_frame = Some(frame_bytes(&f));
2363+ break 'outer;
2364+ }
2365+ }
2366+ if seeked_frame.is_none() {
2367+ seek_dec.flush().expect("flush");
2368+ seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f));
2369+ }
2370+ let seeked_frame = seeked_frame.expect("a frame came out after the seek");
2371+
2372+ assert_eq!(
2373+ seeked_frame, linear_frame_30,
2374+ "seeking to the open-GOP I before frame 30 handed back a different \
2375+ picture than a linear decode of frame 30 — leading pictures with \
2376+ missing references were not dropped"
2377+ );
2378+}
crates/ec-hw/src/dec/av1.rsmodified+2 -0
@@ -115,6 +115,7 @@ impl Av1Decoder {
115115 (header.render_width, header.render_height),
116116 session.coded_size,
117117 session.bit_depth,
118+ None,
118119 ));
119120 // 7.21: showing a KEY frame again refreshes every reference slot with
120121 // it, which the reference *surfaces* have to follow too.
@@ -183,6 +184,7 @@ impl Av1Decoder {
183184 (header.render_width, header.render_height),
184185 session.coded_size,
185186 session.bit_depth,
187+ None,
186188 ));
187189 }
188190 Ok(())
crates/ec-hw/src/dec/dpb264.rsmodified+13 -3
@@ -420,7 +420,8 @@ impl Dpb {
420420 num_l0: usize,
421421 num_l1: usize,
422422 mods: (&[RefPicListMod], &[RefPicListMod]),
423- ) -> Result<[RefList; 2]> {
423+ ) -> Result<([RefList; 2], bool)> {
424+ let mut padded = false;
424425 let mut lists = [RefList::default(), RefList::default()];
425426 let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
426427 let mut n_short = 0usize;
@@ -505,13 +506,16 @@ impl Dpb {
505506 )));
506507 }
507508 let first = lists[x].entries[0];
509+ if lists[x].len < wanted[x] {
510+ padded = true;
511+ }
508512 while lists[x].len < wanted[x] {
509513 lists[x].push(usize::from(first));
510514 }
511515 lists[x].len = wanted[x];
512516 self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
513517 }
514- Ok(lists)
518+ Ok((lists, padded))
515519 }
516520
517521 /// Reference picture list modification (8.2.4.3), by the insert-and-compact
@@ -589,15 +593,21 @@ impl Dpb {
589593 }
590594
591595 /// Store a decoded picture and apply the reference marking of 8.2.5.
596+ ///
597+ /// `output_ok` is false for a picture that predicted from a reference
598+ /// never decoded since the last `reset()` (a random-access leading
599+ /// picture whose ref list build had to pad) — it still joins the DPB as
600+ /// a reference and for bookkeeping, but must never be handed to a caller.
592601 pub(crate) fn store(
593602 &mut self,
594603 mut pic: Picture,
595604 sps: &Sps,
596605 info: &PicInfo,
597606 marking: Option<&DecRefPicMarking>,
607+ output_ok: bool,
598608 ) -> Result<()> {
599609 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
600- pic.output = true;
610+ pic.output = output_ok;
601611 self.number_short_term(info.frame_num, sps);
602612 pic.frame_num_wrap = pic.frame_num as i32;
603613 pic.pic_num = pic.frame_num as i32;
crates/ec-hw/src/dec/h264.rsmodified+62 -4
@@ -2,6 +2,7 @@
22
33 use std::sync::Arc;
44
5+use ec_core::color::{ColorDescription, ContentLight, Tags};
56 use ec_h264_syntax::{
67 AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader,
78 SliceType, Sps, unescape_rbsp,
@@ -12,7 +13,7 @@ use ec_va::{Buffer, Display, sys};
1213 use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList};
1314 use super::{ReadyFrames, Session, StreamInfo};
1415 use crate::error::{Error, Result};
15-use crate::frame::Frame;
16+use crate::frame::{Colour, Frame};
1617 use crate::params::h264::{
1718 IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE,
1819 PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264,
@@ -38,6 +39,8 @@ struct Current {
3839 /// Parameter and data buffers submitted so far.
3940 buffers: Vec<Buffer>,
4041 slices: usize,
42+ /// Set if any slice's ref list build had to pad (see `H264Decoder::recovery_poc`).
43+ ref_padded: bool,
4144 }
4245
4346 /// A stateless H.264 decoder.
@@ -52,6 +55,16 @@ pub struct H264Decoder {
5255 /// Reusable unescape buffer; NAL payloads are rewritten into it in turn.
5356 rbsp: Vec<u8>,
5457 gap_frames: u64,
58+ /// `PicOrderCnt` of the random-access point most recently established by
59+ /// `reset()` — the first picture decoded after it. `None` before that
60+ /// picture completes. Absent a recovery_point SEI (not parsed here),
61+ /// D.2.8's recovery point defaults to this picture itself: anything with
62+ /// a smaller POC that had to guess a reference (`Current::ref_padded`)
63+ /// predicts from something never decoded since the seek and must not
64+ /// reach the caller.
65+ recovery_poc: Option<i32>,
66+ /// The most recent SPS's VUI colour tags, sticky across pictures.
67+ colour_tags: Tags,
5568 }
5669
5770 impl H264Decoder {
@@ -68,6 +81,8 @@ impl H264Decoder {
6881 current: None,
6982 rbsp: Vec::new(),
7083 gap_frames: 0,
84+ recovery_poc: None,
85+ colour_tags: Tags::default(),
7186 }
7287 }
7388
@@ -86,6 +101,7 @@ impl H264Decoder {
86101 self.rbsp = rbsp;
87102 let sps = sps?;
88103 self.dpb.configure(&sps);
104+ self.colour_tags = vui_colour_tags(&sps);
89105 let id = usize::from(sps.id);
90106 self.sps_map[id] = Some(sps);
91107 }
@@ -132,6 +148,7 @@ impl H264Decoder {
132148 self.dpb.clear();
133149 self.ready.clear();
134150 self.gap_frames = 0;
151+ self.recovery_poc = None;
135152 }
136153
137154 /// What the stream turned out to be, once its first SPS was seen.
@@ -268,6 +285,7 @@ impl H264Decoder {
268285 marking: sh.dec_ref_pic_marking.clone(),
269286 buffers: Vec::new(),
270287 slices: 0,
288+ ref_padded: false,
271289 });
272290 Ok(())
273291 }
@@ -317,7 +335,7 @@ impl H264Decoder {
317335 [RefList::default(), RefList::default()]
318336 } else {
319337 self.dpb.number_short_term(sh.frame_num, sps);
320- self.dpb.build_ref_lists(
338+ let (lists, padded) = self.dpb.build_ref_lists(
321339 sh.slice_type,
322340 current.poc.value,
323341 sh.frame_num as i32,
@@ -325,7 +343,9 @@ impl H264Decoder {
325343 sh.num_ref_idx_l0_active as usize,
326344 sh.num_ref_idx_l1_active as usize,
327345 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
328- )?
346+ )?;
347+ current.ref_padded |= padded;
348+ lists
329349 };
330350
331351 let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb);
@@ -359,6 +379,10 @@ impl H264Decoder {
359379
360380 session.submit(&current.surface, current.buffers)?;
361381
382+ // See `recovery_poc`'s doc comment.
383+ let recovery_poc = *self.recovery_poc.get_or_insert(current.poc.value);
384+ let output_ok = !(current.ref_padded && current.poc.value < recovery_poc);
385+
362386 let picture = Picture {
363387 id: current.id,
364388 surface: Arc::clone(&current.surface),
@@ -376,7 +400,7 @@ impl H264Decoder {
376400 output: true,
377401 };
378402 self.dpb
379- .store(picture, &sps, &current.info, current.marking.as_ref())?;
403+ .store(picture, &sps, &current.info, current.marking.as_ref(), output_ok)?;
380404 self.bump(false);
381405 Ok(())
382406 }
@@ -395,11 +419,45 @@ impl H264Decoder {
395419 session.display_size,
396420 session.coded_size,
397421 session.bit_depth,
422+ self.colour(),
398423 );
399424 self.ready.push(frame);
400425 self.dpb.released(idx);
401426 }
402427 }
428+
429+ /// This stream's colour metadata, once its first SPS has been seen. No SEI
430+ /// here — H.264's mastering-display/content-light-level SEI is not parsed
431+ /// by this family today, so this is VUI-only.
432+ pub fn colour(&self) -> Option<Colour> {
433+ let session = self.session.as_ref()?;
434+ Some(Colour {
435+ description: ColorDescription::resolve(
436+ Tags::default(),
437+ self.colour_tags,
438+ session.display_size.1,
439+ ),
440+ light: ContentLight::default(),
441+ })
442+ }
443+}
444+
445+/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
446+/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
447+/// `video_signal_type` at all.
448+fn vui_colour_tags(sps: &Sps) -> Tags {
449+ let Some(vui) = &sps.vui else {
450+ return Tags::default();
451+ };
452+ if vui.video_format.is_none() {
453+ return Tags::default();
454+ }
455+ let (_primaries, transfer, matrix) = vui.colour_description.unwrap_or((0, 0, 0));
456+ Tags::from_codes(
457+ u64::from(matrix),
458+ u64::from(transfer),
459+ if vui.video_full_range { 2 } else { 1 },
460+ )
403461 }
404462
405463 /// The `pic_parameter_set_id` of a slice header, which is the second syntax
crates/ec-hw/src/dec/hevc.rsmodified+92 -2
@@ -9,6 +9,7 @@
99
1010 use std::sync::Arc;
1111
12+use ec_core::color::{ColorDescription, ContentLight, Tags};
1213 use ec_h265_syntax::{
1314 NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b,
1415 unescape_rbsp,
@@ -18,7 +19,7 @@ use ec_va::{Buffer, Display, sys};
1819
1920 use super::{ReadyFrames, Session, StreamInfo};
2021 use crate::error::{Error, Result};
21-use crate::frame::Frame;
22+use crate::frame::{Colour, Frame};
2223 use crate::params::hevc::{
2324 IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR,
2425 PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC,
@@ -93,8 +94,18 @@ pub struct HevcDecoder {
9394 prev_tid0_poc: i32,
9495 /// Set once a picture has been decoded since the last reset.
9596 started: bool,
97+ /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures
98+ /// associated with it must not be decoded or output when set, because
99+ /// they predict from pictures before a random-access point this decoder
100+ /// never saw.
101+ no_rasl_output: bool,
96102 max_reorder: usize,
97103 max_dec_pic_buffering: usize,
104+ /// The most recent SPS's VUI colour tags, sticky across pictures.
105+ colour_tags: Tags,
106+ /// The prefix SEI HDR peak seen so far, merged so a later access unit that
107+ /// says nothing does not erase what an earlier IRAP declared.
108+ colour_light: ContentLight,
98109 }
99110
100111 impl HevcDecoder {
@@ -111,8 +122,11 @@ impl HevcDecoder {
111122 current: None,
112123 prev_tid0_poc: 0,
113124 started: false,
125+ no_rasl_output: false,
114126 max_reorder: 1,
115127 max_dec_pic_buffering: 6,
128+ colour_tags: Tags::default(),
129+ colour_light: ContentLight::default(),
116130 }
117131 }
118132
@@ -131,6 +145,7 @@ impl HevcDecoder {
131145 let sps = Sps::parse(&nal.rbsp())?;
132146 self.max_reorder = sps.max_num_reorder_pics as usize;
133147 self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;
148+ self.colour_tags = vui_colour_tags(&sps);
134149 let id = sps.id as usize;
135150 if id < self.sps_map.len() {
136151 self.sps_map[id] = Some(sps);
@@ -149,10 +164,33 @@ impl HevcDecoder {
149164 _ => {}
150165 }
151166 }
167+ // The HDR SEI messages (mastering display, content light level) live
168+ // outside the slice loop above and are read on the whole access unit:
169+ // an encoder writes them once, ahead of the IRAP they describe, and
170+ // they otherwise say nothing (`ContentLight::default()`), so a later
171+ // access unit that carries neither never overwrites what an earlier
172+ // one declared.
173+ let light = ec_core::color::hevc_sei_light(data);
174+ if light != ContentLight::default() {
175+ self.colour_light = light.over(self.colour_light);
176+ }
152177 self.finish_picture()?;
153178 Ok(())
154179 }
155180
181+ /// This stream's colour metadata, once its first SPS has been seen.
182+ pub fn colour(&self) -> Option<Colour> {
183+ let session = self.session.as_ref()?;
184+ Some(Colour {
185+ description: ColorDescription::resolve(
186+ Tags::default(),
187+ self.colour_tags,
188+ session.display_size.1,
189+ ),
190+ light: self.colour_light,
191+ })
192+ }
193+
156194 /// The next frame in output order.
157195 pub fn next_frame(&mut self) -> Option<Frame> {
158196 self.ready.pop()
@@ -171,6 +209,7 @@ impl HevcDecoder {
171209 self.ready.clear();
172210 self.prev_tid0_poc = 0;
173211 self.started = false;
212+ self.no_rasl_output = false;
174213 }
175214
176215 /// What the stream turned out to be.
@@ -202,7 +241,14 @@ impl HevcDecoder {
202241
203242 if sh.first_slice_segment_in_pic {
204243 self.finish_picture()?;
205- self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?;
244+ // 8.1.3 / C.5.2.2: a RASL picture associated with an IRAP whose
245+ // NoRaslOutputFlag is 1 predicts from pictures before that IRAP,
246+ // which a mid-stream start never decoded. It is not output and
247+ // is not guaranteed decodable, so it is dropped whole rather than
248+ // handed to the driver.
249+ if !(is_rasl_picture(nal_type) && self.no_rasl_output) {
250+ self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?;
251+ }
206252 }
207253 if self.current.is_none() {
208254 return Ok(());
@@ -256,6 +302,13 @@ impl HevcDecoder {
256302 ) -> Result<()> {
257303 self.ensure_session(sps)?;
258304
305+ if nal_type.is_irap() {
306+ // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded
307+ // video sequence — which a mid-stream start's first IRAP always
308+ // is, `self.started` still being false at that point.
309+ self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started;
310+ }
311+
259312 let poc = self.picture_order_count(sps, sh, nal_type);
260313 // 8.3.2 runs before the picture is decoded and after its POC is known:
261314 // every stored picture the set does not name stops being a reference.
@@ -616,6 +669,7 @@ impl HevcDecoder {
616669 session.display_size,
617670 session.coded_size,
618671 session.bit_depth,
672+ self.colour(),
619673 ));
620674 self.dpb[idx].output = false;
621675 self.dpb.retain(|p| p.stored());
@@ -636,6 +690,42 @@ fn is_leading_picture(nal_type: NalUnitType) -> bool {
636690 (6..=9).contains(&nal_type.code())
637691 }
638692
693+/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
694+/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
695+/// `video_signal_type` at all.
696+fn vui_colour_tags(sps: &Sps) -> Tags {
697+ let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else {
698+ return Tags::default();
699+ };
700+ let (_primaries, transfer, matrix) = vst
701+ .colour_description
702+ .map(|cd| {
703+ (
704+ cd.colour_primaries,
705+ cd.transfer_characteristics,
706+ cd.matrix_coeffs,
707+ )
708+ })
709+ .unwrap_or((0, 0, 0));
710+ Tags::from_codes(
711+ u64::from(matrix),
712+ u64::from(transfer),
713+ if vst.video_full_range_flag { 2 } else { 1 },
714+ )
715+}
716+
717+/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's
718+/// `NoRaslOutputFlag` is 1 (8.1.3).
719+fn is_rasl_picture(nal_type: NalUnitType) -> bool {
720+ matches!(nal_type.code(), 8 | 9)
721+}
722+
723+/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1
724+/// (8.1.3), a broken-link splice point that never has a decodable RASL.
725+fn is_bla_picture(nal_type: NalUnitType) -> bool {
726+ (16..=18).contains(&nal_type.code())
727+}
728+
639729 /// `slice_pic_parameter_set_id`, readable without any parameter set.
640730 fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
641731 let mut r = ec_core::BitReader::new(rbsp);
crates/ec-hw/src/dec/mod.rsmodified+11 -0
@@ -154,6 +154,17 @@ impl Decoder {
154154 Inner::Av1(d) => d.stream_info(),
155155 }
156156 }
157+
158+ /// This stream's colour metadata, once a session exists. [`None`] for VP9
159+ /// and AV1: neither's sequence header colour config is parsed by this
160+ /// family yet.
161+ pub fn colour(&self) -> Option<crate::frame::Colour> {
162+ match &self.inner {
163+ Inner::H264(d) => d.colour(),
164+ Inner::H265(d) => d.colour(),
165+ Inner::Vp9(_) | Inner::Av1(_) => None,
166+ }
167+ }
157168 }
158169
159170 /// Frames waiting to be collected, oldest first.
crates/ec-hw/src/dec/vp9.rsmodified+2 -0
@@ -98,6 +98,7 @@ impl Vp9Decoder {
9898 (header.width, header.height),
9999 session.coded_size,
100100 session.bit_depth,
101+ None,
101102 ));
102103 return Ok(());
103104 }
@@ -137,6 +138,7 @@ impl Vp9Decoder {
137138 (header.width, header.height),
138139 session.coded_size,
139140 session.bit_depth,
141+ None,
140142 ));
141143 }
142144 Ok(())
crates/ec-hw/src/enc/h264.rsmodified+1 -0
@@ -134,6 +134,7 @@ pub(super) fn parameters(
134134 num_units_in_tick: seq.num_units_in_tick,
135135 time_scale: seq.time_scale,
136136 pic_init_qp: pic.pic_init_qp,
137+ colour: config.colour,
137138 };
138139 if keyframe {
139140 encoder.push_packed(&headers::h264_sps(&header_params), out)?;
crates/ec-hw/src/enc/headers.rsmodified+24 -2
@@ -12,6 +12,7 @@
1212
1313 use ec_core::BitWriter;
1414
15+use super::Colour;
1516 use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
1617
1718 /// A header ready to submit: escaped bytes plus its exact length in bits.
@@ -49,6 +50,7 @@ pub(super) struct H264Params {
4950 pub(super) num_units_in_tick: u32,
5051 pub(super) time_scale: u32,
5152 pub(super) pic_init_qp: u8,
53+ pub(super) colour: Option<Colour>,
5254 }
5355
5456 /// `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 {
8789 w.write_bit(true); // vui_parameters_present_flag
8890 w.write_bit(false); // aspect_ratio_info_present_flag
8991 w.write_bit(false); // overscan_info_present_flag
90- w.write_bit(false); // video_signal_type_present_flag
92+ w.write_bit(p.colour.is_some()); // video_signal_type_present_flag
93+ if let Some(colour) = p.colour {
94+ w.write_bits(5, 3); // video_format: unspecified
95+ w.write_bit(colour.full_range);
96+ w.write_bit(true); // colour_description_present_flag
97+ w.write_bits(u32::from(colour.primaries), 8);
98+ w.write_bits(u32::from(colour.transfer), 8);
99+ w.write_bits(u32::from(colour.matrix), 8);
100+ }
91101 w.write_bit(false); // chroma_loc_info_present_flag
92102 w.write_bit(true); // timing_info_present_flag
93103 w.write_bits(p.num_units_in_tick, 32);
@@ -185,7 +195,7 @@ pub(super) mod hevc {
185195 SliceHeader, SliceType, Sps, Vps,
186196 };
187197
188- use super::{Packed, nal};
198+ use super::{Colour, Packed, nal};
189199 use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
190200
191201 /// Geometry and timing for the parameter sets.
@@ -198,6 +208,7 @@ pub(super) mod hevc {
198208 pub(in crate::enc) num_units_in_tick: u32,
199209 pub(in crate::enc) time_scale: u32,
200210 pub(in crate::enc) init_qp: u8,
211+ pub(in crate::enc) colour: Option<Colour>,
201212 }
202213
203214 /// The VPS, SPS and PPS, in that order.
@@ -254,6 +265,17 @@ pub(super) mod hevc {
254265 ptl,
255266 vui: Some(ec_h265_syntax::vui::VuiParameters {
256267 timing: Some((p.num_units_in_tick, p.time_scale)),
268+ video_signal_type: p.colour.map(|colour| {
269+ ec_h265_syntax::vui::VideoSignalType {
270+ video_format: 5, // unspecified
271+ video_full_range_flag: colour.full_range,
272+ colour_description: Some(ec_h265_syntax::vui::ColourDescription {
273+ colour_primaries: colour.primaries,
274+ transfer_characteristics: colour.transfer,
275+ matrix_coeffs: colour.matrix,
276+ }),
277+ }
278+ }),
257279 ..ec_h265_syntax::vui::VuiParameters::default()
258280 }),
259281 };
crates/ec-hw/src/enc/hevc.rsmodified+1 -0
@@ -146,6 +146,7 @@ pub(super) fn parameters(
146146 num_units_in_tick: seq.vui_num_units_in_tick,
147147 time_scale: seq.vui_time_scale,
148148 init_qp: pic.pic_init_qp,
149+ colour: config.colour,
149150 };
150151 let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params);
151152 if keyframe {
crates/ec-hw/src/enc/mod.rsmodified+94 -5
@@ -97,6 +97,27 @@ pub struct EncoderConfig {
9797 pub quality: u32,
9898 /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused.
9999 pub allow_av1: bool,
100+ /// The colour description to write into the VUI, or `None` to leave it
101+ /// unsignalled (`video_signal_type_present_flag = 0`) as before.
102+ pub colour: Option<Colour>,
103+}
104+
105+/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI.
106+///
107+/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and
108+/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting
109+/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273
110+/// tables 2/3/4).
111+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112+pub struct Colour {
113+ /// `colour_primaries`.
114+ pub primaries: u8,
115+ /// `transfer_characteristics`.
116+ pub transfer: u8,
117+ /// `matrix_coeffs`.
118+ pub matrix: u8,
119+ /// `video_full_range_flag`.
120+ pub full_range: bool,
100121 }
101122
102123 impl EncoderConfig {
@@ -112,8 +133,26 @@ impl EncoderConfig {
112133 rate_control: RateControlMode::ConstantBitrate,
113134 quality: 0,
114135 allow_av1: false,
136+ colour: None,
115137 }
116138 }
139+
140+ /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.
141+ pub fn colour(
142+ mut self,
143+ primaries: u8,
144+ transfer: u8,
145+ matrix: u8,
146+ full_range: bool,
147+ ) -> EncoderConfig {
148+ self.colour = Some(Colour {
149+ primaries,
150+ transfer,
151+ matrix,
152+ full_range,
153+ });
154+ self
155+ }
117156 }
118157
119158 /// One coded picture.
@@ -269,15 +308,65 @@ impl Encoder {
269308 self.config.width, self.config.height, frame.width, frame.height
270309 )));
271310 }
272- let keyframe = meta.force_keyframe
273- || self.reference.is_none()
274- || self.gop_position >= self.config.gop_size.max(1);
275-
276311 let input = self
277312 .pool
278313 .acquire()
279314 .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
280315 self.upload(frame, &input)?;
316+ self.encode_surface(Arc::clone(input.surface()), meta)
317+ }
318+
319+ /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back,
320+ /// no re-upload, just the decoder's picture handed straight to the
321+ /// encoder as its source. This is the path a decode-then-encode pipeline
322+ /// (e.g. a transcode) wants — the alternative is a full frame through
323+ /// system memory and back for no reason.
324+ ///
325+ /// Refused, rather than silently working around, when:
326+ /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id
327+ /// only means anything on the display that created it.
328+ /// - `frame` is 10-bit (P010): every profile this crate encodes
329+ /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless
330+ /// destination for the extra two bits — call [`Frame::to_i420`] and
331+ /// [`Encoder::encode`] if the truncation is acceptable.
332+ /// - `frame`'s coded size does not match this encoder's: the surface
333+ /// formats have to agree for the driver to read one as the other with
334+ /// no VPP conversion pass, and this crate does not carry a VPP-free
335+ /// fallback for a mismatched size.
336+ pub fn encode_frame(
337+ &mut self,
338+ frame: &crate::frame::Frame,
339+ meta: FrameMetadata,
340+ ) -> Result<CodedFrame> {
341+ if frame.bit_depth != 8 {
342+ return Err(Error::unsupported(
343+ format!("encode_frame of a {}-bit source", frame.bit_depth),
344+ "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \
345+ decode to I420 with Frame::to_i420 and call Encoder::encode instead",
346+ ));
347+ }
348+ if !Arc::ptr_eq(frame.surface().display(), self.context.display()) {
349+ return Err(Error::config(
350+ "encode_frame: the frame was decoded on a different Display than this encoder",
351+ ));
352+ }
353+ if frame.coded_size != self.coded_size {
354+ return Err(Error::config(format!(
355+ "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}",
356+ self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
357+ )));
358+ }
359+ self.encode_surface(Arc::clone(frame.surface()), meta)
360+ }
361+
362+ /// Shared submission path for [`Encoder::encode`] and
363+ /// [`Encoder::encode_frame`]: everything after the source surface is
364+ /// settled.
365+ fn encode_surface(&mut self, source: Arc<Surface>, meta: FrameMetadata) -> Result<CodedFrame> {
366+ let keyframe = meta.force_keyframe
367+ || self.reference.is_none()
368+ || self.gop_position >= self.config.gop_size.max(1);
369+
281370 let recon = self
282371 .pool
283372 .acquire()
@@ -298,7 +387,7 @@ impl Encoder {
298387 buffers.extend(self.rate_control_buffers()?);
299388 buffers.push(coded_buf);
300389
301- let mut picture = Picture::new(&self.context, Arc::clone(input.surface()))
390+ let mut picture = Picture::new(&self.context, source)
302391 .begin()?
303392 .render_all(buffers)?
304393 .end()?
crates/ec-hw/src/frame.rsmodified+24 -0
@@ -3,12 +3,27 @@
33
44 use std::sync::{Arc, Mutex};
55
6+use ec_core::color::{ColorDescription, ContentLight};
67 use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010};
78 use ec_va::{Image, MappedImage, PrimeSurface, Surface};
89
910 use crate::error::{Error, Result};
1011 use crate::pool::PooledSurface;
1112
13+/// A stream's colour metadata, resolved from its own headers: VUI tags for the
14+/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
15+/// messages for the peak the mastering grade and the content itself declared.
16+/// No container tier here: ec-hw only ever sees the elementary stream, so a
17+/// caller that also holds the container's tags resolves those over this.
18+#[derive(Debug, Clone, Copy, PartialEq)]
19+pub struct Colour {
20+ /// Matrix/transfer/range, resolved from the bitstream's own VUI.
21+ pub description: ColorDescription,
22+ /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
23+ /// the stream carried them (HEVC prefix SEI only).
24+ pub light: ContentLight,
25+}
26+
1227 /// The readback image a decoder reuses across frames.
1328 ///
1429 /// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on
@@ -33,6 +48,8 @@ pub struct Frame {
3348 pub coded_size: (u32, u32),
3449 /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.
3550 pub bit_depth: u8,
51+ /// This stream's colour metadata, when the codec's decoder resolves one.
52+ pub colour: Option<Colour>,
3653 }
3754
3855 /// 8-bit planar 4:2:0, the currency edith's software path speaks.
@@ -73,6 +90,7 @@ impl Frame {
7390 display_size: (u32, u32),
7491 coded_size: (u32, u32),
7592 bit_depth: u8,
93+ colour: Option<Colour>,
7694 ) -> Frame {
7795 Frame {
7896 surface,
@@ -81,6 +99,7 @@ impl Frame {
8199 display_size,
82100 coded_size,
83101 bit_depth,
102+ colour,
84103 }
85104 }
86105
@@ -89,6 +108,11 @@ impl Frame {
89108 &self.surface
90109 }
91110
111+ /// This frame's colour metadata, when the codec's decoder resolves one.
112+ pub fn colour(&self) -> Option<Colour> {
113+ self.colour
114+ }
115+
92116 /// Export the surface as DRM PRIME file descriptors.
93117 ///
94118 /// This is the path edith's `engine-hw` takes: the fds are imported into
crates/ec-hw/src/lib.rsmodified+1 -1
@@ -56,5 +56,5 @@ pub use enc::{
5656 CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings,
5757 };
5858 pub use error::{Error, Result};
59-pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};
59+pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};
6060 pub use pool::{PooledSurface, SurfacePool};
crates/ec-hw/tests/gpu.rsmodified+662 -1
@@ -12,6 +12,7 @@ use std::io::Read;
1212 use std::path::{Path, PathBuf};
1313 use std::process::{Command, Stdio};
1414 use std::sync::Arc;
15+use std::time::{Duration, Instant};
1516
1617 use ec_hw::{
1718 Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode,
@@ -71,7 +72,15 @@ impl Reference {
7172 // pictures on a film whose real cadence differs — which shows up
7273 // here as everything being one frame out from some point onward.
7374 .args([
74- "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-",
75+ "-map",
76+ "0:v:0",
77+ "-fps_mode",
78+ "passthrough",
79+ "-pix_fmt",
80+ pix,
81+ "-f",
82+ "rawvideo",
83+ "-",
7584 ])
7685 .stdout(Stdio::piped())
7786 .stderr(Stdio::null())
@@ -657,6 +666,183 @@ fn our_encoder_and_our_decoder_agree() {
657666 }
658667 }
659668
669+/// A decoded surface goes straight into an encoder with no `to_i420`
670+/// read-back, and what comes out is not measurably different from the
671+/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames.
672+///
673+/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block
674+/// rounding both land on the same 1920x1088 coded size for it, so the
675+/// decoder's surfaces satisfy `encode_frame`'s coded-size check against
676+/// either target codec without a second fixture.
677+#[test]
678+fn encode_frame_zero_copy_matches_the_cpu_path() {
679+ let Some(display) = display() else { return };
680+ let (width, height) = (1920u32, 1080u32);
681+ let Some(path) = fixtures(".264")
682+ .into_iter()
683+ .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264"))
684+ else {
685+ eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh");
686+ return;
687+ };
688+ let data = std::fs::read(&path).expect("fixture is readable");
689+ let frames = 10usize;
690+
691+ for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
692+ let mut cfg = EncoderConfig::new(target, width, height);
693+ cfg.gop_size = 30;
694+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
695+ let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens");
696+ let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens");
697+ let mut zc_stream = Vec::new();
698+ let mut cpu_stream = Vec::new();
699+ let mut count = 0i64;
700+
701+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
702+ decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| {
703+ let meta = FrameMetadata {
704+ timestamp: count,
705+ force_keyframe: false,
706+ };
707+ // The zero-copy path never reads the surface back to the CPU: the
708+ // only `to_i420` call in this loop is the CPU-path baseline's.
709+ let zc = zero_copy
710+ .encode_frame(&frame, meta)
711+ .expect("encode_frame (zero copy)");
712+ zc_stream.extend_from_slice(&zc.data);
713+ let i420 = frame.to_i420().expect("readback for the CPU-path baseline");
714+ let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)");
715+ cpu_stream.extend_from_slice(&cpu.data);
716+ count += 1;
717+ })
718+ .expect("decode");
719+ assert_eq!(
720+ count as usize, frames,
721+ "{target:?}: decoded {count} of {frames}"
722+ );
723+
724+ let ext = match target {
725+ EncCodec::H264 => "264",
726+ EncCodec::H265 => "265",
727+ EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"),
728+ };
729+ let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy");
730+ std::fs::create_dir_all(&dir).expect("temp dir");
731+ for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] {
732+ std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream");
733+ }
734+
735+ let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens");
736+ let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens");
737+ let mut zc_frames = Vec::new();
738+ let mut cpu_frames = Vec::new();
739+ decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| {
740+ zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))
741+ })
742+ .expect("decode zero-copy stream");
743+ decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| {
744+ cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))
745+ })
746+ .expect("decode CPU-path stream");
747+ assert_eq!(
748+ zc_frames.len(),
749+ frames,
750+ "{target:?}: zero-copy stream frame count"
751+ );
752+ assert_eq!(
753+ cpu_frames.len(),
754+ frames,
755+ "{target:?}: CPU-path stream frame count"
756+ );
757+
758+ let worst = zc_frames
759+ .iter()
760+ .zip(&cpu_frames)
761+ .map(|(a, b)| psnr(a, b))
762+ .fold(f64::INFINITY, f64::min);
763+ println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB");
764+ assert!(
765+ worst >= 35.0,
766+ "{target:?}: worst {worst:.1} dB vs the CPU path"
767+ );
768+ }
769+}
770+
771+/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an
772+/// export with a colour description survives ffprobe reading it back, and
773+/// leaving it unset keeps today's behaviour (no `video_signal_type`,
774+/// deterministically — two encodes of the same picture with no colour set
775+/// come back byte for byte identical).
776+#[test]
777+fn colour_description_reaches_the_vui() {
778+ let Some(display) = display() else { return };
779+ let (width, height) = (640u32, 480u32);
780+ let dir = std::env::temp_dir().join("ec-hw-colour-vui");
781+ std::fs::create_dir_all(&dir).expect("temp dir");
782+
783+ let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) {
784+ let mut cfg = EncoderConfig::new(EncCodec::H265, width, height);
785+ cfg.rate_control = RateControlMode::ConstantQp { qp: 26 };
786+ if let Some((primaries, transfer, matrix, full_range)) = colour {
787+ cfg = cfg.colour(primaries, transfer, matrix, full_range);
788+ }
789+ let mut enc = Encoder::new(&display, cfg).expect("encoder opens");
790+ let coded = enc
791+ .encode(
792+ &source_frame(width, height, 0),
793+ FrameMetadata {
794+ timestamp: 0,
795+ force_keyframe: true,
796+ },
797+ )
798+ .expect("encode");
799+ let path = dir.join(name);
800+ std::fs::write(&path, &coded.data).expect("write bitstream");
801+ (path, coded.data)
802+ };
803+ let probe = |path: &Path| -> String {
804+ let out = Command::new("ffprobe")
805+ .args([
806+ "-v",
807+ "error",
808+ "-select_streams",
809+ "v:0",
810+ "-show_entries",
811+ "stream=color_primaries,color_transfer,color_space",
812+ "-of",
813+ "csv=p=0",
814+ ])
815+ .arg(path)
816+ .output()
817+ .expect("ffprobe runs");
818+ String::from_utf8_lossy(&out.stdout).trim().to_string()
819+ };
820+
821+ // Pinned default case: no colour set, twice, must match exactly.
822+ let (default_path, default_bytes) = encode_one(None, "default-a.265");
823+ let (_, default_bytes2) = encode_one(None, "default-b.265");
824+ assert_eq!(
825+ default_bytes, default_bytes2,
826+ "no colour set: two encodes of the same picture must be byte-identical"
827+ );
828+ let default_probe = probe(&default_path);
829+ println!("no colour set: ffprobe sees `{default_probe}`");
830+ assert!(
831+ !default_probe.contains("bt2020"),
832+ "no colour set should not read back as BT.2020: `{default_probe}`"
833+ );
834+
835+ // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9).
836+ let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265");
837+ // ffprobe's csv reorders these as color_space,color_transfer,color_primaries
838+ // regardless of the -show_entries order given above.
839+ let got = probe(&bt2020_path);
840+ assert_eq!(
841+ got, "bt2020nc,smpte2084,bt2020",
842+ "ffprobe on the BT.2020 stream"
843+ );
844+}
845+
660846 /// AV1 encoding is opt-in, and this test does not turn it on.
661847 ///
662848 /// It was probed once, live, at the driver's own minimum encode size
@@ -1032,3 +1218,478 @@ fn short(path: &Path) -> String {
10321218 .map(|n| n.to_string_lossy().to_string())
10331219 .unwrap_or_default()
10341220 }
1221+
1222+/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match).
1223+fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 {
1224+ let n = a.len().min(b.len());
1225+ let mse: f64 = a[..n]
1226+ .iter()
1227+ .zip(&b[..n])
1228+ .map(|(&p, &q)| {
1229+ let d = f64::from(p) - f64::from(q);
1230+ d * d
1231+ })
1232+ .sum::<f64>()
1233+ / n as f64;
1234+ if mse == 0.0 {
1235+ f64::INFINITY
1236+ } else {
1237+ 10.0 * (peak * peak / mse).log10()
1238+ }
1239+}
1240+
1241+/// P010 correctness on the real 4K HDR film, plane by plane.
1242+///
1243+/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB
1244+/// for a mix of files; this isolates Y from U/V on this specific 10-bit film,
1245+/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the
1246+/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output
1247+/// against this crate's un-dithered right-shift -- a real but small gap, not
1248+/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma
1249+/// plane is being read at the wrong stride/offset; it is not, on this file.
1250+#[test]
1251+fn ten_bit_4k_chroma_is_not_grey() {
1252+ let Some(display) = display() else { return };
1253+ let path = Path::new(
1254+ "/home/user/Downloads/reeld\
1255+ /reeld.mkv",
1256+ );
1257+ if !path.exists() {
1258+ eprintln!("skipped: film not present");
1259+ return;
1260+ }
1261+ let frames = 3usize;
1262+ let Some(data) = elementary(path, Codec::H265, frames) else {
1263+ eprintln!("skipped: no elementary stream");
1264+ return;
1265+ };
1266+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1267+ let mut ref10: Option<Reference> = None;
1268+ let mut ref8: Option<Reference> = None;
1269+ let mut compared = 0usize;
1270+ decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
1271+ let (w, h) = frame.display_size;
1272+ let ref10 =
1273+ ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs"));
1274+ let want10 = ref10.next(w, h).expect("ffmpeg has a frame");
1275+ let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback"));
1276+ let y_db = plane_psnr(&got16.y, &want10.y, 1023.0);
1277+ let uv_db = plane_psnr(
1278+ &[got16.u.as_slice(), got16.v.as_slice()].concat(),
1279+ &[want10.u.as_slice(), want10.v.as_slice()].concat(),
1280+ 1023.0,
1281+ );
1282+ println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB");
1283+ assert!(
1284+ y_db >= 50.0,
1285+ "frame {compared}: Y PSNR collapsed to {y_db:.1} dB"
1286+ );
1287+ assert!(
1288+ uv_db >= 50.0,
1289+ "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)"
1290+ );
1291+
1292+ let ref8 =
1293+ ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs"));
1294+ let want8 = ref8.next(w, h).expect("ffmpeg has a frame");
1295+ let got8 = Planes::from_8bit(&frame.to_i420().expect("readback"));
1296+ let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0);
1297+ let uv_db8 = plane_psnr(
1298+ &[got8.u.as_slice(), got8.v.as_slice()].concat(),
1299+ &[want8.u.as_slice(), want8.v.as_slice()].concat(),
1300+ 255.0,
1301+ );
1302+ println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB");
1303+ // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both
1304+ // are legitimate 10-to-8 roundings, so the floor here is the
1305+ // dithering noise floor, not the lossless bound above.
1306+ assert!(
1307+ y_db8 >= 30.0,
1308+ "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB"
1309+ );
1310+ assert!(
1311+ uv_db8 >= 30.0,
1312+ "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)"
1313+ );
1314+ compared += 1;
1315+ })
1316+ .expect("decode");
1317+ assert_eq!(compared, frames, "not all frames were compared");
1318+}
1319+
1320+/// The HEVC HDR peak (`content_light_level_information` and
1321+/// `mastering_display_colour_volume` prefix SEI), on the one real file that
1322+/// only carries it there: the Matroska `Colour` element itself has no MaxCLL/
1323+/// MaxFALL for this rip (verified separately against `ffprobe`), so a decoder
1324+/// that does not read the SEI reports none at all. Numbers match what
1325+/// `ffprobe -show_frames -read_intervals %+#1 -show_entries
1326+/// frame_side_data_list` reports for this file.
1327+#[test]
1328+fn hdr_film_light_level_sei_is_exposed() {
1329+ let Some(display) = display() else { return };
1330+ let path = Path::new(
1331+ "/home/user/Downloads/reeld\
1332+ /reeld.mkv",
1333+ );
1334+ if !path.exists() {
1335+ eprintln!("skipped: film not present");
1336+ return;
1337+ }
1338+ let frames = 2usize;
1339+ let Some(data) = elementary(path, Codec::H265, frames) else {
1340+ eprintln!("skipped: no elementary stream");
1341+ return;
1342+ };
1343+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1344+ let mut seen = 0usize;
1345+ decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
1346+ seen += 1;
1347+ let colour = frame
1348+ .colour()
1349+ .expect("HEVC decoder resolves colour metadata");
1350+ assert_eq!(
1351+ colour.description.codes(),
1352+ (9, 16, 9),
1353+ "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)"
1354+ );
1355+ assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL");
1356+ assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL");
1357+ assert!(
1358+ colour.light.mastering_max.is_some(),
1359+ "mastering display peak missing"
1360+ );
1361+ })
1362+ .expect("decode");
1363+ assert_eq!(seen, frames, "not all frames were compared");
1364+}
1365+
1366+/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour`
1367+/// either resolves from the VUI or answers [`None`], but never panics.
1368+#[test]
1369+fn sdr_h264_colour_never_panics() {
1370+ let Some(display) = display() else { return };
1371+ let paths = fixtures(".264");
1372+ if paths.is_empty() {
1373+ eprintln!("skipped: no H.264 fixtures generated");
1374+ return;
1375+ }
1376+ let path = &paths[0];
1377+ let Some(data) = std::fs::read(path).ok() else {
1378+ eprintln!("skipped: fixture unreadable");
1379+ return;
1380+ };
1381+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1382+ let mut seen = 0usize;
1383+ decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| {
1384+ seen += 1;
1385+ // No SEI parsing on this codec: content light is always absent.
1386+ if let Some(colour) = frame.colour() {
1387+ assert_eq!(colour.light.max_cll, None);
1388+ }
1389+ })
1390+ .expect("decode");
1391+ assert!(seen > 0, "{}: nothing decoded", short(path));
1392+}
1393+
1394+/// Per-frame cost of the 4K 10-bit read-back path, isolated from decode
1395+/// submission itself.
1396+///
1397+/// The consumer's `hw_decode::the_hdr_film_renders_tone_mapped` measured
1398+/// 1352.5 ms/frame against a 39 ms (24 fps) budget on this film. Decode
1399+/// correctness on it is already pinned by `real_library_spot_check` (bit-exact
1400+/// against ffmpeg), so this isolates which stage of the frame path -- decode,
1401+/// 8-bit readback, 10-bit readback or DRM PRIME export -- the time goes to.
1402+#[test]
1403+fn ten_bit_4k_frame_path_is_realtime() {
1404+ let Some(display) = display() else { return };
1405+ let path = Path::new(
1406+ "/home/user/Downloads/reeld\
1407+ /reeld.mkv",
1408+ );
1409+ if !path.exists() {
1410+ eprintln!("skipped: film not present");
1411+ return;
1412+ }
1413+ let limit = 120usize;
1414+ let Some(data) = elementary(path, Codec::H265, limit) else {
1415+ eprintln!("skipped: no elementary stream");
1416+ return;
1417+ };
1418+ let units = split_access_units(&data, Codec::H265);
1419+ assert!(
1420+ units.len() > limit,
1421+ "film clip too short for {limit} frames"
1422+ );
1423+
1424+ #[derive(Clone, Copy)]
1425+ enum Op {
1426+ DecodeOnly,
1427+ ToI420,
1428+ ToI420_16,
1429+ ExportPrime,
1430+ }
1431+ fn apply(op: Op, frame: Frame) {
1432+ match op {
1433+ Op::DecodeOnly => drop(frame),
1434+ Op::ToI420 => {
1435+ frame.to_i420().expect("readback");
1436+ }
1437+ Op::ToI420_16 => {
1438+ frame.to_i420_16().expect("readback");
1439+ }
1440+ Op::ExportPrime => {
1441+ frame.export_prime().expect("export");
1442+ }
1443+ }
1444+ }
1445+
1446+ println!(
1447+ "{:<22} {:>10} {:>10} {:>10}",
1448+ "stage", "median ms", "min ms", "max ms"
1449+ );
1450+ let mut got_to_i420_16 = None;
1451+ for (name, op) in [
1452+ ("decode-only", Op::DecodeOnly),
1453+ ("decode+to_i420", Op::ToI420),
1454+ ("decode+to_i420_16", Op::ToI420_16),
1455+ ("decode+export_prime", Op::ExportPrime),
1456+ ] {
1457+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1458+ let mut durations: Vec<Duration> = Vec::new();
1459+ // Hold a few frames before reading, as the resident-set test does:
1460+ // reading one frame per submission measures latency, not throughput,
1461+ // and lets decode run ahead of read-back the way a real player does.
1462+ let mut pending: Vec<Frame> = Vec::new();
1463+ let mut t_prev = Instant::now();
1464+ 'outer: for (i, unit) in units.iter().enumerate() {
1465+ decoder.decode(unit, i as i64).expect("decode");
1466+ while let Some(frame) = decoder.next_frame() {
1467+ pending.push(frame);
1468+ if pending.len() < 4 {
1469+ continue;
1470+ }
1471+ for frame in pending.drain(..) {
1472+ apply(op, frame);
1473+ let now = Instant::now();
1474+ durations.push(now.duration_since(t_prev));
1475+ t_prev = now;
1476+ }
1477+ if durations.len() >= limit {
1478+ break 'outer;
1479+ }
1480+ }
1481+ }
1482+ decoder.flush().expect("flush");
1483+ while durations.len() < limit {
1484+ let Some(frame) = decoder.next_frame() else {
1485+ break;
1486+ };
1487+ apply(op, frame);
1488+ let now = Instant::now();
1489+ durations.push(now.duration_since(t_prev));
1490+ t_prev = now;
1491+ }
1492+ assert!(
1493+ durations.len() >= 24,
1494+ "{name}: only {} frames decoded",
1495+ durations.len()
1496+ );
1497+ durations.sort();
1498+ let ms = |d: Duration| d.as_secs_f64() * 1000.0;
1499+ let median = ms(durations[durations.len() / 2]);
1500+ let min = ms(durations[0]);
1501+ let max = ms(durations[durations.len() - 1]);
1502+ println!("{name:<22} {median:>10.2} {min:>10.2} {max:>10.2}");
1503+ if name == "decode+to_i420_16" {
1504+ got_to_i420_16 = Some(median);
1505+ }
1506+ }
1507+ let got = got_to_i420_16.expect("to_i420_16 phase ran");
1508+ println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}");
1509+}
1510+
1511+/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in
1512+/// decode order, even though they display before it (they predict from
1513+/// pictures the CRA's own random-access point does not have). A decoder
1514+/// started fresh at that CRA — what a seek does — must therefore drop those
1515+/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by
1516+/// however many RASL pictures the GOP has, handing back the wrong picture for
1517+/// every display index at or after the seek target.
1518+#[test]
1519+fn hevc_seek_matches_linear_mkv() {
1520+ let Some(display) = display() else { return };
1521+ let path = bitstreams().join("test_hevc.mkv");
1522+ let Some(data) = elementary(&path, Codec::H265, 45) else {
1523+ eprintln!("skipped: no test_hevc.mkv fixture");
1524+ return;
1525+ };
1526+ let units = split_access_units(&data, Codec::H265);
1527+
1528+ // Linear decode: every picture from the start, frame 30 kept for
1529+ // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture
1530+ // GOPs).
1531+ const TARGET: usize = 30;
1532+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1533+ let mut linear_frame_30 = None;
1534+ let mut index = 0usize;
1535+ decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| {
1536+ if index == TARGET {
1537+ linear_frame_30 = Some(frame.to_i420().expect("readback"));
1538+ }
1539+ index += 1;
1540+ })
1541+ .expect("linear decode");
1542+ let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
1543+
1544+ // Find the access unit whose first VCL NAL is the CRA at this GOP
1545+ // boundary, and feed the decoder from there on, exactly as a seek would:
1546+ // nothing from before it goes in.
1547+ let cra_at = units
1548+ .iter()
1549+ .position(|au| starts_with_cra(au))
1550+ .expect("a CRA access unit exists");
1551+
1552+ // A seek reuses the parameter sets a decoder already learned; a fresh one
1553+ // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a
1554+ // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown
1555+ // away) and reset picture state before feeding the seek target.
1556+ let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1557+ seek_decoder
1558+ .decode(units[0], 0)
1559+ .expect("prime parameter sets");
1560+ seek_decoder.reset();
1561+ let mut seeked_frame = None;
1562+ for (i, unit) in units[cra_at..].iter().enumerate() {
1563+ seek_decoder.decode(unit, i as i64).expect("seek decode");
1564+ if let Some(frame) = seek_decoder.next_frame() {
1565+ seeked_frame = Some(frame.to_i420().expect("readback"));
1566+ break;
1567+ }
1568+ }
1569+ if seeked_frame.is_none() {
1570+ seek_decoder.flush().expect("flush");
1571+ seeked_frame = seek_decoder
1572+ .next_frame()
1573+ .map(|f| f.to_i420().expect("readback"));
1574+ }
1575+ let seeked_frame = seeked_frame.expect("a frame came out after the seek");
1576+
1577+ assert_eq!(
1578+ seeked_frame, linear_frame_30,
1579+ "seeking to the CRA before frame 30 handed back a different picture \
1580+ than a linear decode of frame 30 — RASL pictures were not dropped"
1581+ );
1582+}
1583+
1584+/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice
1585+/// (`nal_unit_type` 1) whose predecessors in decode order can still hold
1586+/// references from before it, so leading pictures between it and the next
1587+/// IDR may predict from a picture never decoded since a fresh start there —
1588+/// exactly what a seek does. A decoder started at that I must drop those
1589+/// leading pictures per D.2.8's recovery point default, or its output shifts
1590+/// by however many leading pictures the GOP has.
1591+#[test]
1592+fn h264_seek_matches_linear_open_gop() {
1593+ let Some(display) = display() else { return };
1594+ let path = bitstreams().join("h264-open-gop.mp4");
1595+ let Some(data) = elementary(&path, Codec::H264, 60) else {
1596+ eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)");
1597+ return;
1598+ };
1599+ let units = split_access_units(&data, Codec::H264);
1600+
1601+ // Linear decode: every picture from the start, frame 30 kept for
1602+ // comparison (the fixture's second I picture, `keyint=30`).
1603+ const TARGET: usize = 30;
1604+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1605+ let mut linear_frame_30 = None;
1606+ let mut index = 0usize;
1607+ decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| {
1608+ if index == TARGET {
1609+ linear_frame_30 = Some(frame.to_i420().expect("readback"));
1610+ }
1611+ index += 1;
1612+ })
1613+ .expect("linear decode");
1614+ let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
1615+
1616+ // Find the access unit whose first VCL NAL is the open-GOP I picture at
1617+ // this GOP boundary, and feed the decoder from there on, exactly as a
1618+ // seek would: nothing from before it goes in.
1619+ let open_gop_at = units
1620+ .iter()
1621+ .position(|au| is_open_gop_i(au))
1622+ .expect("an open-GOP I access unit exists");
1623+
1624+ // A seek reuses the parameter sets a decoder already learned; a fresh one
1625+ // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a
1626+ // caller to: decode the leading IDR (its picture is thrown away) and
1627+ // reset picture state before feeding the seek target.
1628+ let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1629+ seek_decoder.decode(units[0], 0).expect("prime parameter sets");
1630+ seek_decoder.reset();
1631+ let mut seeked_frame = None;
1632+ for (i, unit) in units[open_gop_at..].iter().enumerate() {
1633+ seek_decoder.decode(unit, i as i64).expect("seek decode");
1634+ if let Some(frame) = seek_decoder.next_frame() {
1635+ seeked_frame = Some(frame.to_i420().expect("readback"));
1636+ break;
1637+ }
1638+ }
1639+ if seeked_frame.is_none() {
1640+ seek_decoder.flush().expect("flush");
1641+ seeked_frame = seek_decoder
1642+ .next_frame()
1643+ .map(|f| f.to_i420().expect("readback"));
1644+ }
1645+ let seeked_frame = seeked_frame.expect("a frame came out after the seek");
1646+
1647+ assert_eq!(
1648+ seeked_frame, linear_frame_30,
1649+ "seeking to the open-GOP I before frame 30 handed back a different \
1650+ picture than a linear decode of frame 30 — leading pictures with \
1651+ missing references were not dropped"
1652+ );
1653+}
1654+
1655+/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice
1656+/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the
1657+/// access unit's first start code rather than assuming a fixed prefix length.
1658+fn is_open_gop_i(au: &[u8]) -> bool {
1659+ let mut i = 0usize;
1660+ while i + 3 < au.len() {
1661+ if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 {
1662+ i += 1;
1663+ continue;
1664+ }
1665+ let header = au[i + 3];
1666+ if header & 0x1f != 1 {
1667+ return false;
1668+ }
1669+ let mut r = ec_core::BitReader::new(&au[i + 4..]);
1670+ if r.read_ue().is_err() {
1671+ return false;
1672+ }
1673+ return matches!(r.read_ue(), Ok(code) if code % 5 == 2);
1674+ }
1675+ false
1676+}
1677+
1678+/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21).
1679+/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past
1680+/// non-VCL NALs to the first one that carries a slice.
1681+fn starts_with_cra(au: &[u8]) -> bool {
1682+ let mut i = 0usize;
1683+ while i + 3 < au.len() {
1684+ if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 {
1685+ let t = (au[i + 3] >> 1) & 0x3f;
1686+ if t <= 31 {
1687+ return t == 21;
1688+ }
1689+ i += 3;
1690+ continue;
1691+ }
1692+ i += 1;
1693+ }
1694+ false
1695+}
crates/ec-matroska/tests/matroska.rsmodified+147 -1
@@ -8,7 +8,7 @@ use std::io::BufReader;
88 use std::path::{Path, PathBuf};
99 use std::process::Command;
1010
11-use ec_core::{Demuxer, Error, Muxer, SeekMode, TimeBase, Timestamp};
11+use ec_core::{Demuxer, Error, MediaType, Muxer, SeekMode, TimeBase, Timestamp};
1212 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
1313
1414 fn fixtures() -> PathBuf {
@@ -711,3 +711,149 @@ fn the_first_cluster_is_reachable_when_no_cue_names_it() {
711711 break;
712712 }
713713 }
714+
715+
716+/// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in
717+/// *timestamp* -- split from decode, per the round's charter: this measures
718+/// only [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what
719+/// `ffprobe` reports for the same track near the same instant. If this lands
720+/// exact, the +0.145 s the consumer measured is downstream of the demuxer
721+/// (the AC-3 decoder or its frame-count bookkeeping in `engine`), not here.
722+///
723+/// Skipped, not failed, without the film: a claim about his library cannot be
724+/// made by a machine that does not have it.
725+#[test]
726+fn seek_landing_on_his_eac3_film_matches_ffprobe() {
727+ same_class_sweep(
728+ "/home/user/Downloads/reeld/reeld.mkv",
729+ &[600.0, 610.0],
730+ );
731+ // Same-class sweep (round charter task 3): an Opus 5.1 Matroska, a codec
732+ // that already goes through this crate's demuxer -- if this lands as
733+ // tight as the E-AC-3 one, the demuxer's seek is not codec-specific and
734+ // the +0.145 s the consumer measured on the E-AC-3 path is downstream of
735+ // it either way.
736+ same_class_sweep(
737+ "/home/user/Downloads/reelb.mkv",
738+ &[600.0, 610.0],
739+ );
740+}
741+
742+/// Where our own demuxer's seek lands on `path`, in *timestamp* -- split from
743+/// decode, per the round's charter: this measures only
744+/// [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what
745+/// `ffprobe` reports for the same track near the same instant.
746+///
747+/// Skipped, not failed, without the film: a claim about his library cannot be
748+/// made by a machine that does not have it.
749+fn same_class_sweep(path: &str, wants: &[f64]) {
750+ let film = Path::new(path);
751+ if !film.exists() {
752+ eprintln!("skipped: {path} is not present");
753+ return;
754+ }
755+ let mut demux =
756+ MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))).expect("demuxes");
757+ let audio = demux
758+ .streams()
759+ .iter()
760+ .find(|s| s.params.codec.media_type() == MediaType::Audio)
761+ .expect("the film has an audio stream")
762+ .clone();
763+
764+ for &want in wants {
765+ let target = Timestamp::new(
766+ (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64,
767+ audio.time_base,
768+ );
769+ demux
770+ .seek(audio.index, target, SeekMode::SyncBefore)
771+ .expect("seek");
772+ let landed = loop {
773+ let packet = demux.next_packet().expect("a packet after the seek");
774+ if packet.stream == audio.index {
775+ break packet.pts.expect("audio packet carries a pts");
776+ }
777+ };
778+ let our_secs = landed as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64;
779+
780+ let ffprobe = Command::new("ffprobe")
781+ .args([
782+ "-v",
783+ "error",
784+ "-select_streams",
785+ "a:0",
786+ "-show_entries",
787+ "packet=pts_time",
788+ "-of",
789+ "csv=p=0",
790+ "-read_intervals",
791+ ])
792+ .arg(format!("{want}%+#1"))
793+ .arg(film)
794+ .output();
795+ let Ok(ffprobe) = ffprobe else {
796+ eprintln!("skipped ffprobe cross-check: ffprobe not runnable");
797+ eprintln!("want {want}s, our demuxer landed at {our_secs:.3}s (pts {landed})");
798+ continue;
799+ };
800+ let reference: f64 = String::from_utf8_lossy(&ffprobe.stdout)
801+ .lines()
802+ .next()
803+ .unwrap_or("")
804+ .trim()
805+ .parse()
806+ .unwrap_or(f64::NAN);
807+ eprintln!(
808+ "want {want}s: our demuxer landed {our_secs:.3}s (pts {landed}), ffprobe's own packet at {reference:.3}s"
809+ );
810+ }
811+}
812+
813+/// `ffprobe` reports MaxCLL 1230 / MaxFALL 419 for this real HDR10 film, but
814+/// that reading comes from `[SIDE_DATA]` on the first *frame* (a
815+/// `content_light_level_information` HEVC SEI message inside the bitstream),
816+/// not from the container's own `Colour` element. This file's `Colour`
817+/// element genuinely carries no `MaxCLL`/`MaxFALL`/`MasteringMetadata`
818+/// children (checked with `ffprobe -show_entries stream=side_data_list`,
819+/// which comes back empty) — so a demuxer-only reader is correct to return
820+/// `None` here, and the consumer's brightness-metadata gap is downstream, in
821+/// whether anything reads the HEVC SEI (`ec_core::color::hevc_sei_light`
822+/// exists and round-trips in `ec-h265-syntax`, but nothing in this workspace
823+/// calls it from a real decode path yet).
824+#[test]
825+#[ignore = "reads a real local file, not a CI fixture"]
826+fn real_hdr_film_container_states_no_light_metadata() {
827+ use ec_core::{Demuxer, MediaParameters};
828+ use ec_matroska::MatroskaDemuxer;
829+ let path = "/home/user/Downloads/reeld/reeld.mkv";
830+ if !std::path::Path::new(path).exists() {
831+ eprintln!("skipped: film not present");
832+ return;
833+ }
834+ let f = std::fs::File::open(path).expect("open");
835+ let demux = MatroskaDemuxer::new(f).expect("demux opens");
836+ let mut checked = false;
837+ for s in demux.streams() {
838+ if let MediaParameters::Video(v) = &s.params.media {
839+ println!("color = {:?}", v.color);
840+ println!("light = {:?}", v.light);
841+ // BT.2020 non-constant luminance, PQ transfer, BT.2020 primaries —
842+ // this much the Colour element does carry, and it must match
843+ // ffprobe's color_space/color_primaries/color_transfer.
844+ assert_eq!(v.color.matrix, 9, "expected bt2020nc");
845+ assert_eq!(v.color.transfer, 16, "expected smpte2084 (PQ)");
846+ assert_eq!(v.color.primaries, 9, "expected bt2020");
847+ assert_eq!(
848+ v.light,
849+ ec_core::color::ContentLight::default(),
850+ "the Colour element has no light metadata for this file — a \
851+ non-default reading here would mean either ffprobe or this \
852+ reader started finding it in the container and the doc \
853+ comment above is stale"
854+ );
855+ checked = true;
856+ }
857+ }
858+ assert!(checked, "no video stream found");
859+}
scripts/aac-tables/make-heaac-fixtures.shadded+67 -0
@@ -0,0 +1,67 @@
1+#!/usr/bin/env bash
2+# Deterministic HE-AAC v1 fixture matrix for tests/sbr_real_library.rs's
3+# `synthetic_heaac_matrix`: two sample-rate families (48000, 44100) x four
4+# bitrates (32k/48k/64k/96k) x two profiles (aac_he, aac_low control) = 16
5+# .m4a files, sweeping the SBR crossover (kx/k2) that bitrate controls
6+# without depending on any one real file's content.
7+#
8+# `ffmpeg`'s system libfdk_aac (the `fdk-aac-free` package) has SBR/PS
9+# encoding compiled out (patent-restricted tools) -- `-profile:a aac_he`
10+# fails with "Unable to set the AOT 5: Invalid config" against it. RPM
11+# Fusion's full `fdk-aac` package carries the SBR-capable encoder but
12+# installs to its OWN /usr/lib64/fdk-aac dir specifically so it doesn't
13+# clobber the system one; this script fetches (no root) and extracts just
14+# that .so into a local cache and points ffmpeg at it via
15+# LD_LIBRARY_PATH for the encode step only, never touching the system
16+# library.
17+set -euo pipefail
18+
19+SCRATCH="${EC_AAC_HEAAC_FIXTURES:-$(cd "$(dirname "$0")/../.." && pwd)/.cache/heaac-fixtures}"
20+mkdir -p "$SCRATCH"
21+CACHE="$SCRATCH/.fdk-aac-full"
22+mkdir -p "$CACHE"
23+
24+fdk_libdir="$CACHE/usr/lib64/fdk-aac"
25+if [ ! -f "$fdk_libdir/libfdk-aac.so.2" ]; then
26+ echo "fetching SBR-capable libfdk-aac (no root, local cache only)..."
27+ ( cd "$CACHE" && dnf download fdk-aac.x86_64 )
28+ rpm_file=$(find "$CACHE" -maxdepth 1 -name 'fdk-aac-*.rpm' | head -1)
29+ ( cd "$CACHE" && rpm2cpio "$rpm_file" | cpio -idm --quiet )
30+fi
31+export LD_LIBRARY_PATH="$fdk_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
32+
33+# Three summed sweeps 100 Hz -> 18 kHz over the full 30 s (phase(t) =
34+# 2*pi*(f0*t + (f1-f0)/(2T)*t^2), f0=100 f1=18000 T=30 ->
35+# (f1-f0)/(2T)=298.333), offset in phase per partial and per channel so
36+# left/right are correlated but not identical -- plus low-level pink noise
37+# (seeded, so every run of this script reproduces bit-identical fixtures).
38+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)"; }
39+L=$(sweep 0 1.047 2.094)
40+R=$(sweep 0.5 1.571 2.618)
41+
42+synth_source() {
43+ local rate=$1 out=$2
44+ ffmpeg -y -hide_banner -loglevel error -filter_complex "
45+ aevalsrc=exprs='${L}|${R}':channel_layout=stereo:sample_rate=${rate}:duration=30 [tone];
46+ anoisesrc=color=pink:amplitude=0.05:seed=42:sample_rate=${rate}:duration=30 [n0];
47+ anoisesrc=color=pink:amplitude=0.05:seed=43:sample_rate=${rate}:duration=30 [n1];
48+ [n0][n1] amerge=inputs=2 [noise];
49+ [tone][noise] amix=inputs=2:normalize=0 [out]
50+ " -map "[out]" -ar "$rate" -sample_fmt s16 -f wav "$out"
51+}
52+
53+for rate in 48000 44100; do
54+ src="$SCRATCH/src_${rate}.wav"
55+ [ -f "$src" ] || synth_source "$rate" "$src"
56+ for br in 32k 48k 64k 96k; do
57+ he="$SCRATCH/heaac_${rate}_${br}.m4a"
58+ lc="$SCRATCH/lc_${rate}_${br}.m4a"
59+ [ -f "$he" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \
60+ -c:a libfdk_aac -profile:a aac_he -b:a "$br" "$he"
61+ [ -f "$lc" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \
62+ -c:a libfdk_aac -profile:a aac_low -b:a "$br" "$lc"
63+ done
64+done
65+
66+echo "fixtures in $SCRATCH:"
67+ls "$SCRATCH"/*.m4a
scripts/gen-fixtures.shmodified+9 -0
@@ -198,6 +198,15 @@ for spec in "${VIDEO_CODECS[@]}"; do
198198 esac
199199 done
200200
201+# Open-GOP H.264: a non-IDR I picture (nal_unit_type 1, not 5) at a GOP
202+# boundary, with B-pyramid pictures around it referencing across the
203+# boundary. A decoder started fresh at that I (what a seek does) must not
204+# hand back a picture whose references it never decoded — the H.264 sibling
205+# of the HEVC RASL/NoRaslOutputFlag case.
206+gen "$FIXTURES/video/h264-open-gop.mp4" \
207+ -f lavfi -i "testsrc2=size=320x240:rate=30:duration=4" -pix_fmt yuv420p \
208+ -c:v libx264 -x264-params "keyint=30:min-keyint=30:open-gop=1:bframes=3:b-pyramid=normal:scenecut=0"
209+
201210 # -------------------------------------------------------------- summary -----
202211 printf '\n%s\n' "== fixtures: $FIXTURES =="
203212 printf '%-42s %10s %s\n' FILE SIZE PROBE