From 5a58bb10a766d29a51ec02ea08d17602a8af750c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 13:50:51 +0300 Subject: [PATCH] feat(h264): display-order output reaches the packet entry surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A player never touches the NAL-level API, so the reordering has to arrive at H264Decoder: packets in, frames out, timestamps travelling with their pictures rather than with the packets that carried them. packet_entry_surface_reorders_and_carries_timestamps drives exactly that path — one access unit per packet, frames pulled with receive_frame — and proves three things at once: every frame is bit-exact against ffmpeg, the output order is a real permutation of the packet order, and the tag on each emitted frame identifies the packet whose picture it actually is (checked against the same stream decoded in decode order). Also: the crate description now states the scope it reached, the debug tracing added while chasing the inter defects is gone, and clippy and rustfmt are clean. --- crates/ec-h264/Cargo.toml | 2 +- crates/ec-h264/src/cabac.rs | 6 +- crates/ec-h264/src/cabac_tables.rs | 14 +- crates/ec-h264/src/decoder.rs | 130 +++------- crates/ec-h264/src/dpb.rs | 73 ++++-- crates/ec-h264/src/inter.rs | 45 ++-- crates/ec-h264/src/mv.rs | 40 +++- crates/ec-h264/tests/conformance.rs | 354 ++++++++++++++++++---------- 8 files changed, 395 insertions(+), 269 deletions(-) diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml index 9fa92723..97605f74 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ec-h264" -description = "H.264 software decoder (CAVLC intra loop, growing toward full)" +description = "H.264 software decoder: I, P and B slices, CAVLC and CABAC, 8-bit 4:2:0 progressive, display-order output" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index a954c04e..2378b064 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -344,7 +344,11 @@ impl<'a> Cabac<'a> { if !self.decision(OFF_SUB_TYPE_P + 1) { return 1; } - if self.decision(OFF_SUB_TYPE_P + 2) { 2 } else { 3 } + if self.decision(OFF_SUB_TYPE_P + 2) { + 2 + } else { + 3 + } } /// sub_mb_type of a B macroblock (Table 9-38). diff --git a/crates/ec-h264/src/cabac_tables.rs b/crates/ec-h264/src/cabac_tables.rs index fd061702..794284a4 100644 --- a/crates/ec-h264/src/cabac_tables.rs +++ b/crates/ec-h264/src/cabac_tables.rs @@ -387,16 +387,14 @@ pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ /// Table 9-45: transIdxLPS. pub(crate) const TRANS_LPS: [u8; 64] = [ - 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, - 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, - 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, - 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, + 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, + 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, ]; /// Table 9-45: transIdxMPS. pub(crate) const TRANS_MPS: [u8; 64] = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, ]; diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 21197e87..80e1eb8e 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -42,8 +42,8 @@ use crate::entropy::{ }; use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; use crate::mv::{ - B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, - neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd, + predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, }; use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; use crate::tables::{BLK4_POS, CHROMA_QP}; @@ -52,18 +52,6 @@ use crate::transform::{ unzigzag, unzigzag_ac15, }; -/// Debug tracing gates, resolved once: reading the environment per macroblock -/// would allocate, which the zero-allocation test would (rightly) catch. -fn trace_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("EC_H264_TRACE").is_some()) -} - -fn no_deblock() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("EC_H264_NO_DEBLOCK").is_some()) -} - /// Where a 4x4 block's top-right neighbour samples come from, per /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). #[derive(Clone, Copy, PartialEq)] @@ -471,7 +459,7 @@ impl Decoder { let lists = if sh.slice_type.is_intra() { [RefList::default(), RefList::default()] } else { - self.dpb.number_short_term(sh.frame_num, &sps); + self.dpb.number_short_term(sh.frame_num, sps); self.dpb.build_ref_lists( sh.slice_type, self.cur.poc, @@ -515,25 +503,6 @@ impl Decoder { weights: sh.pred_weight_table.clone(), poc: self.cur.poc, }; - if trace_enabled() { - eprintln!( - "SLICE type {:?} qp {} cabac_init_idc {} l0 {} l1 {} first_mb {first_mb} \ - header_bits {} bytes {:02x?}", - sh.slice_type, sh.slice_qp, sh.cabac_init_idc, sh.num_ref_idx_l0_active, - sh.num_ref_idx_l1_active, sh.header_bits, &rbsp[..rbsp.len().min(6)] - ); - } - if trace_enabled() && !sh.slice_type.is_intra() { - for x in 0..2 { - let l: Vec<(u32, i32)> = (0..lists[x].len()) - .filter_map(|i| lists[x].get(i)) - .map(|k| (self.dpb.frames[k].frame_num, self.dpb.frames[k].poc)) - .collect(); - if !l.is_empty() { - eprintln!(" RefPicList{x} (frame_num, poc): {l:?}"); - } - } - } let intra_slice = sh.slice_type.is_intra(); let b_slice = sh.slice_type == SliceType::B; if !intra_slice && ctx.lists[0].len() == 0 { @@ -635,9 +604,8 @@ impl Decoder { let mb_x = mb_addr % pic.mb_w; let mb_y = mb_addr / pic.mb_w; let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); - let cond = |avail: bool, addr: usize| { - usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0) - }; + let cond = + |avail: bool, addr: usize| usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0); cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w)) } @@ -832,13 +800,11 @@ impl SliceCtx { use1: bool, ) -> Weights { let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1; - let explicit = (self.weighted_bipred_idc == 1 && self.is_b()) - || (self.weighted_pred && !self.is_b()); + let explicit = + (self.weighted_bipred_idc == 1 && self.is_b()) || (self.weighted_pred && !self.is_b()); if implicit { - let (Some(p0), Some(p1)) = ( - self.reference(refs, 0, r0), - self.reference(refs, 1, r1), - ) else { + let (Some(p0), Some(p1)) = (self.reference(refs, 0, r0), self.reference(refs, 1, r1)) + else { return Weights::DEFAULT; }; let td = (p1.poc - p0.poc).clamp(-128, 127); @@ -1056,17 +1022,8 @@ fn decode_macroblock( (None, Some(mb_type)) }; r.set_intra(intra_type.is_some()); - if trace_enabled() { - eprintln!( - "MB {mb_addr} ({mb_x},{mb_y}) type {} skipped {skipped} qp {}", - mb_type as i64, ctx.qp - ); - } - if let Some(shape) = shape { - return decode_inter_mb( - pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr, - ); + return decode_inter_mb(pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr); } let mb_type = intra_type.expect("an intra macroblock type"); write_intra_mb(pic, mb_x, mb_y); @@ -1424,7 +1381,9 @@ fn finish_macroblock( /// Decode an inter macroblock: sub-macroblock types, reference indices and /// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation /// (8.4.2) and the shared residual path. -#[allow(clippy::too_many_arguments)] +// `comp` indexes a motion vector component and selects its context offset at +// the same time, which an iterator would obscure. +#[allow(clippy::too_many_arguments, clippy::needless_range_loop)] fn decode_inter_mb( pic: &mut Picture, refs: &[Picture], @@ -1468,9 +1427,6 @@ fn decode_inter_mb( if shape.sub && !skipped { for part in 0..4 { let t = r.sub_mb_type(b)? as usize; - if trace_enabled() { - eprintln!(" sub_mb_type[{part}] = {t}"); - } motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; if motion.sub[part].pred == Pred::Direct { for k in 0..4 { @@ -1504,11 +1460,7 @@ fn decode_inter_mb( let by = (mb_y * 4 + py) as i32; let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list) + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list); - let v = r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8; - if trace_enabled() { - eprintln!(" ref_idx part {part} list {list} inc {inc} = {v}"); - } - v + r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8 }; motion.ref_idx[list][part] = idx; // Publish it over the whole macroblock partition — one @@ -1563,12 +1515,6 @@ fn decode_inter_mb( 0 }; let v = r.mvd(comp, inc)?; - if trace_enabled() { - eprintln!( - " mvd part {part} sp {sp} at ({px},{py}) list {list} comp {comp} \ - absA {a} absB {bb} inc {inc} = {v}" - ); - } mvd[comp] = i16::try_from(v) .map_err(|_| Error::corrupt("mvd outside the level limits"))?; } @@ -1618,25 +1564,10 @@ fn decode_inter_mb( // partition width inside an 8x8. let n = mvc.neighbours(pic, px, py, pw, list); let mvp = predict_mv(&n, idx, shape.w, shape.h, part); - if trace_enabled() { - eprintln!( - " nb A {:?} B {:?} C {:?} shape {}x{} part {part} mvp {mvp:?} written {:#06x}", - n[0], n[1], n[2], shape.w, shape.h, mvc.written - ); - } let d = motion.mvd[list][py * 4 + px]; mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; ref_idx[list] = idx; - ref_id[list] = ctx - .reference(refs, list, idx) - .map(|p| p.id) - .unwrap_or(-1); - } - if trace_enabled() { - eprintln!( - " MV part {part} sp {sp} at ({px},{py}) {pw}x{ph} mv {:?} ref {:?}", - mv[0], ref_idx - ); + ref_id[list] = ctx.reference(refs, list, idx).map(|p| p.id).unwrap_or(-1); } for dy in 0..ph { for dx in 0..pw { @@ -1680,9 +1611,6 @@ fn decode_inter_mb( pic.i4_modes[base..base + 4].fill(2); } let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; - if trace_enabled() { - eprintln!(" cbp {cbp_luma:#x}/{cbp_chroma}"); - } // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. finish_macroblock( pic, @@ -1737,7 +1665,11 @@ fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, u /// Size of one *macroblock* partition in 4x4 blocks: always 8x8 for a /// macroblock that carries sub-macroblock types, however those split it. fn mb_part_size(shape: &MbShape) -> (usize, usize) { - if shape.sub { (2, 2) } else { (shape.w, shape.h) } + if shape.sub { + (2, 2) + } else { + (shape.w, shape.h) + } } /// Size of one (sub-)macroblock partition in 4x4 blocks. @@ -1860,8 +1792,9 @@ fn direct_quadrant( } } -/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal -/// (8.4.1.2.3). +/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture +/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). +#[allow(clippy::type_complexity)] fn direct_block( pic: &Picture, refs: &[Picture], @@ -1965,8 +1898,7 @@ fn direct_block( /// picture the co-located block referenced. fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 { for i in 0..ctx.lists[0].len() { - if ctx - .lists[0] + if ctx.lists[0] .get(i) .and_then(|k| refs.get(k)) .is_some_and(|p| p.id == col_ref_id) @@ -2111,10 +2043,11 @@ fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all /// vertical edges then all horizontal edges per macroblock, then chroma. +// `e` and `j` are edge and segment positions inside the macroblock, used to +// index the plane as well as the strength arrays; iterating the arrays would +// hide which geometry each one names. +#[allow(clippy::needless_range_loop)] fn deblock_picture(pic: &mut Picture) { - if no_deblock() { - return; - } let mb_w = pic.mb_w; for mb_y in 0..pic.mb_h { for mb_x in 0..mb_w { @@ -2208,7 +2141,12 @@ fn deblock_picture(pic: &mut Picture) { } // Eight rows around the edge are contiguous, so the // whole 16-sample edge filters in one pass. - filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); + filter_luma_h_edge16( + &mut pic.y.data, + base + e * 4 * stride, + stride, + ¶ms, + ); continue; } for j in 0..4 { diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs index 6bf30168..7ca2d3dc 100644 --- a/crates/ec-h264/src/dpb.rs +++ b/crates/ec-h264/src/dpb.rs @@ -96,7 +96,8 @@ impl Plane8 { let (src, dst) = (full, full - (y + 1) * stride); self.data.copy_within(src..src + stride, dst); let src = full + (h - 1) * stride; - self.data.copy_within(src..src + stride, src + (y + 1) * stride); + self.data + .copy_within(src..src + stride, src + (y + 1) * stride); } } } @@ -633,6 +634,7 @@ impl Dpb { /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). + #[allow(clippy::too_many_arguments)] pub(crate) fn build_ref_lists( &self, slice_type: SliceType, @@ -704,7 +706,8 @@ impl Dpb { lists[1].push(i); } // 8.2.4.2.3 step 3. - if lists[1].len > 1 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] + if lists[1].len > 1 + && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] { lists[1].entries.swap(0, 1); } @@ -938,7 +941,12 @@ impl Dpb { } /// Adaptive marking (clause 8.2.5.4). - fn apply_mmco(&mut self, pic: &mut Picture, m: &DecRefPicMarking, info: &PicInfo) -> Result<()> { + fn apply_mmco( + &mut self, + pic: &mut Picture, + m: &DecRefPicMarking, + info: &PicInfo, + ) -> Result<()> { let curr_pic_num = info.frame_num as i32; for op in &m.mmcos { match op.op { @@ -1115,9 +1123,8 @@ mod tests { fn extend_borders_replicates_edges() { let mut p = plane(6, 5); p.extend_borders(); - let at = |x: i32, y: i32| -> u8 { - p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] - }; + let at = + |x: i32, y: i32| -> u8 { p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] }; for y in -4..9i32 { for x in -4..10i32 { let cx = x.clamp(0, 5) as usize; @@ -1200,9 +1207,24 @@ mod tests { fn poc_type_2_is_twice_the_frame_number() { let sps = sps_for(2); let dpb = Dpb::default(); - assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); - assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, true, false)).unwrap().value, 6); - assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, false, false)).unwrap().value, 5); + assert_eq!( + dpb.picture_order_count(&sps, &info(0, 0, true, true)) + .unwrap() + .value, + 0 + ); + assert_eq!( + dpb.picture_order_count(&sps, &info(3, 0, true, false)) + .unwrap() + .value, + 6 + ); + assert_eq!( + dpb.picture_order_count(&sps, &info(3, 0, false, false)) + .unwrap() + .value, + 5 + ); } /// Type 1 walks the offset_for_ref_frame cycle. @@ -1211,9 +1233,24 @@ mod tests { let sps = sps_for(1); let dpb = Dpb::default(); // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n. - assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); - assert_eq!(dpb.picture_order_count(&sps, &info(1, 0, true, false)).unwrap().value, 2); - assert_eq!(dpb.picture_order_count(&sps, &info(4, 0, true, false)).unwrap().value, 8); + assert_eq!( + dpb.picture_order_count(&sps, &info(0, 0, true, true)) + .unwrap() + .value, + 0 + ); + assert_eq!( + dpb.picture_order_count(&sps, &info(1, 0, true, false)) + .unwrap() + .value, + 2 + ); + assert_eq!( + dpb.picture_order_count(&sps, &info(4, 0, true, false)) + .unwrap() + .value, + 8 + ); } fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { @@ -1259,7 +1296,9 @@ mod tests { .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) .unwrap(); let poc = |l: &RefList| -> Vec { - (0..l.len()).map(|i| dpb.frames[l.get(i).unwrap()].poc).collect() + (0..l.len()) + .map(|i| dpb.frames[l.get(i).unwrap()].poc) + .collect() }; assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); @@ -1277,8 +1316,12 @@ mod tests { let lists = dpb .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) .unwrap(); - let l0: Vec = (0..2).map(|i| dpb.frames[lists[0].get(i).unwrap()].poc).collect(); - let l1: Vec = (0..2).map(|i| dpb.frames[lists[1].get(i).unwrap()].poc).collect(); + let l0: Vec = (0..2) + .map(|i| dpb.frames[lists[0].get(i).unwrap()].poc) + .collect(); + let l1: Vec = (0..2) + .map(|i| dpb.frames[lists[1].get(i).unwrap()].poc) + .collect(); assert_eq!(l0, vec![2, 0]); assert_eq!(l1, vec![0, 2], "identical lists swap"); } diff --git a/crates/ec-h264/src/inter.rs b/crates/ec-h264/src/inter.rs index 916eca1c..f7565070 100644 --- a/crates/ec-h264/src/inter.rs +++ b/crates/ec-h264/src/inter.rs @@ -82,7 +82,15 @@ const TMP_W: usize = 16 + 5; /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter /// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. -pub(crate) fn mc_luma(r: &RefPlane<'_>, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [u8]) { +pub(crate) fn mc_luma( + r: &RefPlane<'_>, + x: i32, + y: i32, + mv: [i16; 2], + w: usize, + h: usize, + out: &mut [u8], +) { let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); let yi = clamp_origin(y + (mv[1] as i32 >> 2), h, r.height, r.pad, 2, 3); @@ -149,8 +157,9 @@ pub(crate) fn mc_luma(r: &RefPlane<'_>, x: i32, y: i32, mv: [i16; 2], w: usize, for row in 0..h { for col in 0..w { let i = row * w + col; - let g = |dx: i32, dy: i32| r.data[base + (row as i32 + dy) as usize * stride - + (col as i32 + dx) as usize]; + let g = |dx: i32, dy: i32| { + r.data[base + (row as i32 + dy) as usize * stride + (col as i32 + dx) as usize] + }; out[i] = match (fx, fy) { // Table 8-12, quarter positions on the integer rows/columns. (1, 0) => avg(g(0, 0), bb[i]), @@ -185,12 +194,7 @@ pub(crate) fn mc_chroma( let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); let stride = r.stride; let base = r.at(xi, yi); - let (wa, wb, wc, wd) = ( - (8 - fx) * (8 - fy), - fx * (8 - fy), - (8 - fx) * fy, - fx * fy, - ); + let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); for row in 0..h { let src = base + row * stride; for col in 0..w { @@ -311,7 +315,14 @@ mod tests { (data, stride, origin) } - fn plane(data: &[u8], stride: usize, origin: usize, w: usize, h: usize, pad: usize) -> RefPlane<'_> { + fn plane( + data: &[u8], + stride: usize, + origin: usize, + w: usize, + h: usize, + pad: usize, + ) -> RefPlane<'_> { RefPlane { data, stride, @@ -324,6 +335,7 @@ mod tests { /// The spec's clipped, per-sample definition of the same interpolation, /// written straight from Equations 8-239 to 8-261 with no padding tricks. + #[allow(clippy::too_many_arguments)] fn spec_luma( pic: &[u8], stride: usize, @@ -396,15 +408,20 @@ mod tests { let r = plane(&data, stride, origin, w, h, pad); let mut ours = [0u8; 256]; let mut theirs = [0u8; 256]; - for &(px, py) in &[(8i32, 8i32), (0, 0), (32, 16), (-40, -40), (60, 44), (44, 4)] { + for &(px, py) in &[ + (8i32, 8i32), + (0, 0), + (32, 16), + (-40, -40), + (60, 44), + (44, 4), + ] { for fy in 0..4i16 { for fx in 0..4i16 { for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { let mv = [fx - 20 * 4, fy + 12]; mc_luma(&r, px, py, mv, pw, ph, &mut ours); - spec_luma( - &data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs, - ); + spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs); assert_eq!( ours[..pw * ph], theirs[..pw * ph], diff --git a/crates/ec-h264/src/mv.rs b/crates/ec-h264/src/mv.rs index 51eb202c..68f25943 100644 --- a/crates/ec-h264/src/mv.rs +++ b/crates/ec-h264/src/mv.rs @@ -216,7 +216,14 @@ impl MvCtx { /// Neighbours A, B and C of a partition whose top-left 4x4 block is at /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks /// (clause 6.4.11.7, with the C-to-D substitution of 8-214). - pub(crate) fn neighbours(&self, pic: &Picture, px: usize, py: usize, pw: usize, list: usize) -> [Nb; 3] { + pub(crate) fn neighbours( + &self, + pic: &Picture, + px: usize, + py: usize, + pw: usize, + list: usize, + ) -> [Nb; 3] { let bx = (self.mb_x * 4 + px) as i32; let by = (self.mb_y * 4 + py) as i32; let a = self.at(pic, bx - 1, by, list); @@ -239,7 +246,13 @@ fn median(a: i16, b: i16, c: i16) -> i16 { /// /// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only /// select those shortcuts; `part` is the macroblock partition index. -pub(crate) fn predict_mv(n: &[Nb; 3], ref_idx: i8, part_w: usize, part_h: usize, part: usize) -> [i16; 2] { +pub(crate) fn predict_mv( + n: &[Nb; 3], + ref_idx: i8, + part_w: usize, + part_h: usize, + part: usize, +) -> [i16; 2] { let [a, mut b, mut c] = *n; match (part_w, part_h, part) { (4, 2, 0) if b.ref_idx == ref_idx => return b.mv, @@ -318,7 +331,15 @@ pub(crate) fn write_intra_mb(pic: &mut Picture, mb_x: usize, mb_y: usize) { /// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the /// context thresholds of 9.3.3.1.1.7 can distinguish. #[inline] -pub(crate) fn write_mvd(pic: &mut Picture, mb_x: usize, mb_y: usize, px: usize, py: usize, list: usize, mvd: [i16; 2]) { +pub(crate) fn write_mvd( + pic: &mut Picture, + mb_x: usize, + mb_y: usize, + px: usize, + py: usize, + list: usize, + mvd: [i16; 2], +) { let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; let e = &mut pic.mvd_abs[idx]; e[list * 2] = mvd[0].unsigned_abs().min(127) as u8; @@ -379,11 +400,7 @@ mod tests { use super::*; fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb { - Nb { - avail, - mv, - ref_idx, - } + Nb { avail, mv, ref_idx } } /// With exactly one neighbour on the same reference picture, that @@ -413,7 +430,11 @@ mod tests { /// median into A (8-207 to 8-210). #[test] fn unavailable_b_and_c_fall_back_to_a() { - let n = [nb(true, [6, -6], 3), nb(false, [0, 0], -1), nb(false, [0, 0], -1)]; + let n = [ + nb(true, [6, -6], 3), + nb(false, [0, 0], -1), + nb(false, [0, 0], -1), + ]; assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]); // With refIdx 3 the single-match rule fires first, same answer. assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]); @@ -449,6 +470,7 @@ mod tests { assert_eq!(B_SHAPES[0].pred[0], Pred::Direct); assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi)); // The 16x8 / 8x16 pairs alternate, starting at mb_type 4. + #[allow(clippy::needless_range_loop)] for t in 4..22 { let s = B_SHAPES[t]; assert_eq!(s.parts, 2, "mb_type {t}"); diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 63ef99bf..bc0e12d5 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -179,12 +179,9 @@ fn decode_all(bytes: &[u8]) -> Result>, Error> { let mut dec = Decoder::new(); let mut frames = Vec::new(); for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - match dec.push_nal(nal)? { - NalOutcome::PictureBoundary => { - dec.end_picture()?; - dec.push_nal(nal)?; - } - _ => {} + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { + dec.end_picture()?; + dec.push_nal(nal)?; } while let Some(f) = dec.next_frame() { frames.push(frame_bytes(&f)); @@ -199,13 +196,8 @@ fn decode_all(bytes: &[u8]) -> Result>, Error> { /// Every frame ffmpeg decodes from `stream`, as raw I420. fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option>> { - let mut cmd = Command::new("ffmpeg"); - cmd.args(["-v", "error"]); - if std::env::var_os("EC_H264_NO_DEBLOCK").is_some() { - cmd.args(["-skip_loop_filter", "all"]); - } - let out = cmd - .arg("-i") + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) .arg(stream) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) .output() @@ -268,8 +260,7 @@ fn compare_sequence(stream: &Path) -> Result { let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; let first = ours.first().ok_or("no frames decoded")?; - let theirs = - ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; + let theirs = ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; if ours.len() != theirs.len() { return Err(format!( "{} frames decoded, ffmpeg gave {}", @@ -398,7 +389,7 @@ fn steady_state_decode_loop_zero_alloc() { }; let bytes = std::fs::read(stream).unwrap(); let mut dec = Decoder::new(); - let mut drive = |dec: &mut Decoder, count: bool| -> usize { + let drive = |dec: &mut Decoder, count: bool| -> usize { let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); let mut frames = 0usize; for nal in &nals { @@ -435,8 +426,14 @@ fn steady_state_decode_loop_zero_alloc() { ALLOCS.store(0, Ordering::SeqCst); let again = drive(&mut dec, true); let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(again, warm, "{name}: frame count changed on the second pass"); - assert_eq!(n, 0, "{name}: steady-state slice decode allocated {n} times"); + assert_eq!( + again, warm, + "{name}: frame count changed on the second pass" + ); + assert_eq!( + n, 0, + "{name}: steady-state slice decode allocated {n} times" + ); } // Sanity: the counter is alive — emitting a frame does allocate. @@ -454,9 +451,13 @@ fn steady_state_decode_loop_zero_alloc() { ); } -/// Decode-rate measurement: ns per macroblock and Mpx/s over the first IDR, -/// printed for the perf report. Run with `--nocapture` to see it. Uses the -/// steady-state path (buffers warm) like a playback loop would. +/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf +/// report. Run with `--nocapture` to see it. Uses the steady-state path +/// (buffers warm) like a playback loop would. +/// +/// Both halves matter: the intra measurement is what the previous release +/// reported, and the whole-sequence one is what playback actually costs, since +/// a real stream is almost all inter pictures. #[test] fn ns_per_macroblock_measurement() { let base = vectors_dir(); @@ -501,6 +502,40 @@ fn ns_per_macroblock_measurement() { (intra IDR, single thread, deblock included, output copy excluded)" ); } + perf_whole_sequence(); +} + +/// The same measurement over whole sequences, where inter prediction, the +/// decoded picture buffer and output all count. +fn perf_whole_sequence() { + let base = vectors_dir(); + for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] { + let Some(stream) = find_stream(&base.join(name)) else { + continue; + }; + let bytes = std::fs::read(stream).unwrap(); + let Ok(warm) = decode_all(&bytes) else { + continue; + }; + if warm.is_empty() { + continue; + } + let frames = warm.len() as f64; + let start = std::time::Instant::now(); + let iters = 5u32; + for _ in 0..iters { + let _ = decode_all(&bytes).expect("decode"); + } + let elapsed = start.elapsed().as_secs_f64() / f64::from(iters); + // Every vector here is QCIF: 11 x 9 macroblocks. + let mbs = 99.0 * frames; + eprintln!( + "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \ + (full sequence, single thread, deblock and output copy included)", + elapsed * 1e9 / mbs, + 176.0 * 144.0 * frames / elapsed / 1e6 + ); + } } /// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte @@ -1027,89 +1062,6 @@ fn p_only_gop_matches_ffmpeg_every_frame() { assert!(failures.is_empty(), "{failures:#?}"); } -/// Scratch driver kept out of the default run: decode a stream named by -/// `EC_H264_DEBUG_STREAM` frame by frame and report the first mismatch. -#[test] -#[ignore] -fn debug_named_stream() { - let Ok(path) = std::env::var("EC_H264_DEBUG_STREAM") else { - return; - }; - let stream = PathBuf::from(path); - let bytes = std::fs::read(&stream).unwrap(); - let mut dec = Decoder::new(); - let mut pictures = 0usize; - for (i, nal) in ec_h264_syntax::AnnexBIter::new(&bytes).enumerate() { - let kind = nal[0] & 0x1F; - match dec.push_nal(nal) { - Ok(NalOutcome::PictureBoundary) => { - dec.end_picture().unwrap(); - pictures += 1; - if let Err(e) = dec.push_nal(nal) { - panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"); - } - } - Ok(_) => {} - Err(e) => panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"), - } - while dec.next_frame().is_some() {} - } - dec.flush().unwrap(); - eprintln!("decoded {pictures} pictures"); - let ours = decode_all(&bytes).unwrap(); - let theirs = match std::env::var("EC_H264_DEBUG_REF") { - Ok(p) => { - let raw = std::fs::read(p).unwrap(); - raw.chunks_exact(ours[0].len()).map(<[u8]>::to_vec).collect() - } - Err(_) => ffmpeg_all_frames(&stream, ours[0].len()).unwrap(), - }; - if std::env::var_os("EC_H264_DUMP").is_some() { - let w = 176usize; - for (label, f) in [("ref0", &ours[0]), ("ours1", &ours[1]), ("ff1", &theirs[1])] { - eprintln!("--- {label} MB(0,0) rows 0..4 ---"); - for y in 0..4 { - let row: Vec = (0..16).map(|x| f[y * w + x]).collect(); - eprintln!("{row:?}"); - } - } - } - for (i, a) in ours.iter().enumerate().take(4) { - let best = theirs - .iter() - .enumerate() - .map(|(j, b)| (a.iter().zip(b).filter(|(x, y)| x != y).count(), j)) - .min(); - eprintln!("our frame {i} best matches reference {best:?}"); - } - let w = 176usize; - let h = 144usize; - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let diff = a.iter().zip(b).filter(|(x, y)| x != y).count(); - if diff == 0 { - eprintln!("frame {i}: exact"); - continue; - } - let mut mbs = std::collections::BTreeSet::new(); - for (k, (x, y)) in a.iter().zip(b).enumerate().take(w * h) { - if x != y { - mbs.insert(((k / w) / 16 * (w / 16) + (k % w) / 16, ((k % w) / 16, (k / w) / 16))); - } - } - eprintln!(" first differing MBs: {:?}", mbs.iter().take(6).map(|m| m.1).collect::>()); - let max = a - .iter() - .zip(b) - .map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs()) - .max() - .unwrap_or(0); - eprintln!( - "frame {i}: {diff} bytes differ, max delta {max}, {} luma MBs", - mbs.len() - ); - } -} - /// JVT conformance, every frame of every vector: our display-order output /// against the reference decoder YUV that ships with the vector. /// @@ -1141,7 +1093,10 @@ fn jvt_full_sequence_bit_exact() { Ok(frames) => { let len = frames[0].len(); let Some(ref_path) = find_ref_yuv(&dir) else { - table.push_str(&format!("{name:<16} {:>3} frames, no reference YUV\n", frames.len())); + table.push_str(&format!( + "{name:<16} {:>3} frames, no reference YUV\n", + frames.len() + )); continue; }; let reference = std::fs::read(&ref_path).unwrap(); @@ -1159,18 +1114,27 @@ fn jvt_full_sequence_bit_exact() { match bad { None if frames.len() == want => { passed += 1; - table.push_str(&format!("{name:<16} {:>3}/{want:<3} frames bit-exact\n", frames.len())); + table.push_str(&format!( + "{name:<16} {:>3}/{want:<3} frames bit-exact\n", + frames.len() + )); } None => { failed.push(format!( "{name}: {} frames decoded, reference has {want}", frames.len() )); - table.push_str(&format!("{name:<16} {:>3}/{want:<3} FRAME COUNT\n", frames.len())); + table.push_str(&format!( + "{name:<16} {:>3}/{want:<3} FRAME COUNT\n", + frames.len() + )); } Some((i, pos)) => { failed.push(format!("{name}: frame {i} differs at byte {pos}")); - table.push_str(&format!("{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", frames.len())); + table.push_str(&format!( + "{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", + frames.len() + )); } } } @@ -1257,18 +1221,36 @@ fn b_pictures_match_ffmpeg_every_frame() { } let dir = scratch("b-gop"); let cases: &[(&str, &[&str])] = &[ - ("spatial", &["-x264-params", "bframes=3:b-adapt=0:direct=spatial:weightp=0"]), - ("temporal", &["-x264-params", "bframes=3:b-adapt=0:direct=temporal:weightp=0"]), + ( + "spatial", + &[ + "-x264-params", + "bframes=3:b-adapt=0:direct=spatial:weightp=0", + ], + ), + ( + "temporal", + &[ + "-x264-params", + "bframes=3:b-adapt=0:direct=temporal:weightp=0", + ], + ), // B pictures used as references, which makes the buffer hold pictures // that are neither the newest nor the oldest. ( "pyramid", - &["-x264-params", "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial"], + &[ + "-x264-params", + "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial", + ], ), // Weighted prediction on: explicit for P, implicit for B. ( "weighted", - &["-x264-params", "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial"], + &[ + "-x264-params", + "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial", + ], ), ]; let mut failures = Vec::new(); @@ -1356,17 +1338,17 @@ fn output_is_display_order_and_the_reorder_is_real() { "decode-order frame {i} is not in the display-order output" ); } - let moved = decode - .iter() - .zip(&display) - .filter(|(a, b)| a != b) - .count(); + let moved = decode.iter().zip(&display).filter(|(a, b)| a != b).count(); assert!( moved > 0, "decode order and display order are identical: the stream does not \ reorder, so this test proves nothing" ); - eprintln!("{} of {} frames move under reordering", moved, display.len()); + eprintln!( + "{} of {} frames move under reordering", + moved, + display.len() + ); } /// A gap in frame_num decodes instead of stalling (clause 8.2.5.2). @@ -1475,7 +1457,10 @@ fn every_quantiser_with_motion_matches_ffmpeg() { None => failures.push(format!("{tag}: ffmpeg cannot encode")), } } - assert!(checked >= 40, "too few {coder} quantisers exercised: {checked}"); + assert!( + checked >= 40, + "too few {coder} quantisers exercised: {checked}" + ); eprintln!("{coder}: {checked} quantisers bit-exact over a GOP with motion"); } let _ = std::fs::remove_dir_all(&dir); @@ -1498,12 +1483,20 @@ fn geometry_with_motion_matches_ffmpeg() { // Neighbour availability stops at every slice boundary, and a motion // vector predictor at one sees no partition across it. ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]), - ("nodeblock", "352x288", &["bframes=2:b-adapt=0:no-deblock=1"]), + ( + "nodeblock", + "352x288", + &["bframes=2:b-adapt=0:no-deblock=1"], + ), // One macroblock wide: every spatial neighbour is unavailable, which // is where the reference index of a missing partition matters most. ("tiny", "16x16", &["bframes=2:b-adapt=0"]), // Many references, so the list is long and reordering is real work. - ("manyref", "352x288", &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"]), + ( + "manyref", + "352x288", + &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"], + ), ]; let mut table = String::new(); let mut failures = Vec::new(); @@ -1522,7 +1515,9 @@ fn geometry_with_motion_matches_ffmpeg() { let name = format!("{coder}-{tag}"); match x264_encode_gop(&dir, &name, size, 10, &extra) { Some(stream) => match compare_sequence(&stream) { - Ok(n) => table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n")), + Ok(n) => { + table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n")) + } Err(e) => { table.push_str(&format!("{name:<14} {size:<10} {e}\n")); failures.push(format!("{name}: {e}")); @@ -1754,7 +1749,8 @@ fn real_library_streams_match_ffmpeg() { eprintln!("SKIP: ffmpeg not on PATH"); return; } - let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); + let manifest = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); let Ok(text) = std::fs::read_to_string(&manifest) else { eprintln!("SKIP: {} missing", manifest.display()); return; @@ -1825,11 +1821,15 @@ fn real_library_streams_match_ffmpeg() { } Err(e) if e.contains("unsupported") => { refused += 1; - table.push_str(&format!("{name:<40} {container:<12} {width:>5}px refused: {e}\n")); + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px refused: {e}\n" + )); } Err(e) => { failures.push(format!("{name}: {e}")); - table.push_str(&format!("{name:<40} {container:<12} {width:>5}px ERROR {e}\n")); + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px ERROR {e}\n" + )); } } } @@ -1842,3 +1842,107 @@ fn real_library_streams_match_ffmpeg() { "only {decoded} real files swept end to end; the sweep is the point" ); } + +/// The registry entry surface, driven the way a demuxer drives it: one access +/// unit per packet, frames pulled with `receive_frame`. +/// +/// This is where display order has to actually arrive. Everything above tests +/// the NAL-level API; a player never touches that one, so a reordering decoder +/// whose packet API still hands back decode order would look correct in every +/// other test here and wrong on screen. +#[test] +fn packet_entry_surface_reorders_and_carries_timestamps() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("entry"); + let extra = [ + "-profile:v", + "main", + "-coder", + "ac", + "-qp", + "26", + "-x264-params", + "bframes=3:b-adapt=0:b-pyramid=normal", + ]; + let stream = x264_encode_gop(&dir, "entry", "176x144", 16, &extra).expect("encode"); + let data = std::fs::read(&stream).unwrap(); + assert!( + slice_type_counts(&data)[2] > 0, + "the encoder produced no B slices" + ); + + // Split the stream into access units the way a demuxer would: a new one + // starts at each parameter set or first slice of a picture. + 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); + } + + let time_base = TimeBase::new(1, 25); + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder"); + let mut out: Vec<(i64, Vec)> = Vec::new(); + for (i, au) in access_units.iter().enumerate() { + let packet = Packet::new(0, time_base, au.clone()).with_pts(i as i64); + decoder.send_packet(&packet).expect("send_packet"); + while let Ok(Frame::Video(f)) = decoder.receive_frame() { + out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f))); + } + } + decoder.flush().expect("flush"); + while let Ok(Frame::Video(f)) = decoder.receive_frame() { + out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f))); + } + + let expected = ffmpeg_all_frames(&stream, out[0].1.len()).expect("ffmpeg"); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out.len(), expected.len(), "frame count"); + for (i, ((_, ours), theirs)) in out.iter().zip(&expected).enumerate() { + assert!( + first_diff(ours, theirs).is_none(), + "packet-path frame {i} differs from ffmpeg" + ); + } + // Each packet was tagged with its own index in *decode* order, so the tag + // that comes back on a picture says which packet produced it. Decoding the + // same stream in decode order gives the pixels for each of those indices, + // and the two have to line up: that is the timestamp staying with its + // picture across the reordering, not merely arriving in some order. + let by_decode_order = decode_all_in_decode_order(&data).expect("decode order"); + assert_eq!(by_decode_order.len(), out.len()); + for (position, (tag, pixels)) in out.iter().enumerate() { + let tag = usize::try_from(*tag).expect("a tag was lost"); + assert!( + first_diff(pixels, &by_decode_order[tag]).is_none(), + "output position {position} carries the timestamp of packet {tag}, \ + but its pixels are a different picture" + ); + } + let order: Vec = out.iter().map(|(pts, _)| *pts).collect(); + assert_ne!( + order, + (0..order.len() as i64).collect::>(), + "output order equals packet order, so no reordering happened" + ); + eprintln!( + "packet entry surface: {} frames, packets emitted in order {order:?}", + out.len() + ); +}