forge
Explore
Log in

Don't you dare go Hollow

Display-order output reaches the packet entry surface

Browse files at this commit

5a58bb10a766d29a51ec02ea08d17602a8af750cAhmet Kaan GümüşParent: 7c078b5
  • feat
    • display-order output reaches the packet entry surface
Show full message
feat(h264): display-order output reaches the packet entry surface

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.tomlmodified+1 -1
@@ -1,6 +1,6 @@
11 [package]
22 name = "ec-h264"
3-description = "H.264 software decoder (CAVLC intra loop, growing toward full)"
3+description = "H.264 software decoder: I, P and B slices, CAVLC and CABAC, 8-bit 4:2:0 progressive, display-order output"
44 version.workspace = true
55 edition.workspace = true
66 license.workspace = true
crates/ec-h264/src/cabac.rsmodified+5 -1
@@ -344,7 +344,11 @@ impl<'a> Cabac<'a> {
344344 if !self.decision(OFF_SUB_TYPE_P + 1) {
345345 return 1;
346346 }
347- if self.decision(OFF_SUB_TYPE_P + 2) { 2 } else { 3 }
347+ if self.decision(OFF_SUB_TYPE_P + 2) {
348+ 2
349+ } else {
350+ 3
351+ }
348352 }
349353
350354 /// sub_mb_type of a B macroblock (Table 9-38).
crates/ec-h264/src/cabac_tables.rsmodified+6 -8
@@ -387,16 +387,14 @@ pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [
387387
388388 /// Table 9-45: transIdxLPS.
389389 pub(crate) const TRANS_LPS: [u8; 64] = [
390- 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
391- 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
392- 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
393- 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
390+ 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,
391+ 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34,
392+ 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
394393 ];
395394
396395 /// Table 9-45: transIdxMPS.
397396 pub(crate) const TRANS_MPS: [u8; 64] = [
398- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
399- 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
400- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
401- 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
397+ 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,
398+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
399+ 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
402400 ];
crates/ec-h264/src/decoder.rsmodified+34 -96
@@ -42,8 +42,8 @@ use crate::entropy::{
4242 };
4343 use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};
4444 use crate::mv::{
45- B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive,
46- neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
45+ B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd,
46+ predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
4747 };
4848 use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
4949 use crate::tables::{BLK4_POS, CHROMA_QP};
@@ -52,18 +52,6 @@ use crate::transform::{
5252 unzigzag, unzigzag_ac15,
5353 };
5454
55-/// Debug tracing gates, resolved once: reading the environment per macroblock
56-/// would allocate, which the zero-allocation test would (rightly) catch.
57-fn trace_enabled() -> bool {
58- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
59- *ON.get_or_init(|| std::env::var_os("EC_H264_TRACE").is_some())
60-}
61-
62-fn no_deblock() -> bool {
63- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
64- *ON.get_or_init(|| std::env::var_os("EC_H264_NO_DEBLOCK").is_some())
65-}
66-
6755 /// Where a 4x4 block's top-right neighbour samples come from, per
6856 /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule).
6957 #[derive(Clone, Copy, PartialEq)]
@@ -471,7 +459,7 @@ impl Decoder {
471459 let lists = if sh.slice_type.is_intra() {
472460 [RefList::default(), RefList::default()]
473461 } else {
474- self.dpb.number_short_term(sh.frame_num, &sps);
462+ self.dpb.number_short_term(sh.frame_num, sps);
475463 self.dpb.build_ref_lists(
476464 sh.slice_type,
477465 self.cur.poc,
@@ -515,25 +503,6 @@ impl Decoder {
515503 weights: sh.pred_weight_table.clone(),
516504 poc: self.cur.poc,
517505 };
518- if trace_enabled() {
519- eprintln!(
520- "SLICE type {:?} qp {} cabac_init_idc {} l0 {} l1 {} first_mb {first_mb} \
521- header_bits {} bytes {:02x?}",
522- sh.slice_type, sh.slice_qp, sh.cabac_init_idc, sh.num_ref_idx_l0_active,
523- sh.num_ref_idx_l1_active, sh.header_bits, &rbsp[..rbsp.len().min(6)]
524- );
525- }
526- if trace_enabled() && !sh.slice_type.is_intra() {
527- for x in 0..2 {
528- let l: Vec<(u32, i32)> = (0..lists[x].len())
529- .filter_map(|i| lists[x].get(i))
530- .map(|k| (self.dpb.frames[k].frame_num, self.dpb.frames[k].poc))
531- .collect();
532- if !l.is_empty() {
533- eprintln!(" RefPicList{x} (frame_num, poc): {l:?}");
534- }
535- }
536- }
537506 let intra_slice = sh.slice_type.is_intra();
538507 let b_slice = sh.slice_type == SliceType::B;
539508 if !intra_slice && ctx.lists[0].len() == 0 {
@@ -635,9 +604,8 @@ impl Decoder {
635604 let mb_x = mb_addr % pic.mb_w;
636605 let mb_y = mb_addr / pic.mb_w;
637606 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
638- let cond = |avail: bool, addr: usize| {
639- usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0)
640- };
607+ let cond =
608+ |avail: bool, addr: usize| usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0);
641609 cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w))
642610 }
643611
@@ -832,13 +800,11 @@ impl SliceCtx {
832800 use1: bool,
833801 ) -> Weights {
834802 let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1;
835- let explicit = (self.weighted_bipred_idc == 1 && self.is_b())
836- || (self.weighted_pred && !self.is_b());
803+ let explicit =
804+ (self.weighted_bipred_idc == 1 && self.is_b()) || (self.weighted_pred && !self.is_b());
837805 if implicit {
838- let (Some(p0), Some(p1)) = (
839- self.reference(refs, 0, r0),
840- self.reference(refs, 1, r1),
841- ) else {
806+ let (Some(p0), Some(p1)) = (self.reference(refs, 0, r0), self.reference(refs, 1, r1))
807+ else {
842808 return Weights::DEFAULT;
843809 };
844810 let td = (p1.poc - p0.poc).clamp(-128, 127);
@@ -1056,17 +1022,8 @@ fn decode_macroblock(
10561022 (None, Some(mb_type))
10571023 };
10581024 r.set_intra(intra_type.is_some());
1059- if trace_enabled() {
1060- eprintln!(
1061- "MB {mb_addr} ({mb_x},{mb_y}) type {} skipped {skipped} qp {}",
1062- mb_type as i64, ctx.qp
1063- );
1064- }
1065-
10661025 if let Some(shape) = shape {
1067- return decode_inter_mb(
1068- pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr,
1069- );
1026+ return decode_inter_mb(pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr);
10701027 }
10711028 let mb_type = intra_type.expect("an intra macroblock type");
10721029 write_intra_mb(pic, mb_x, mb_y);
@@ -1424,7 +1381,9 @@ fn finish_macroblock(
14241381 /// Decode an inter macroblock: sub-macroblock types, reference indices and
14251382 /// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation
14261383 /// (8.4.2) and the shared residual path.
1427-#[allow(clippy::too_many_arguments)]
1384+// `comp` indexes a motion vector component and selects its context offset at
1385+// the same time, which an iterator would obscure.
1386+#[allow(clippy::too_many_arguments, clippy::needless_range_loop)]
14281387 fn decode_inter_mb(
14291388 pic: &mut Picture,
14301389 refs: &[Picture],
@@ -1468,9 +1427,6 @@ fn decode_inter_mb(
14681427 if shape.sub && !skipped {
14691428 for part in 0..4 {
14701429 let t = r.sub_mb_type(b)? as usize;
1471- if trace_enabled() {
1472- eprintln!(" sub_mb_type[{part}] = {t}");
1473- }
14741430 motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] };
14751431 if motion.sub[part].pred == Pred::Direct {
14761432 for k in 0..4 {
@@ -1504,11 +1460,7 @@ fn decode_inter_mb(
15041460 let by = (mb_y * 4 + py) as i32;
15051461 let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list)
15061462 + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list);
1507- let v = r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8;
1508- if trace_enabled() {
1509- eprintln!(" ref_idx part {part} list {list} inc {inc} = {v}");
1510- }
1511- v
1463+ r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8
15121464 };
15131465 motion.ref_idx[list][part] = idx;
15141466 // Publish it over the whole macroblock partition — one
@@ -1563,12 +1515,6 @@ fn decode_inter_mb(
15631515 0
15641516 };
15651517 let v = r.mvd(comp, inc)?;
1566- if trace_enabled() {
1567- eprintln!(
1568- " mvd part {part} sp {sp} at ({px},{py}) list {list} comp {comp} \
1569- absA {a} absB {bb} inc {inc} = {v}"
1570- );
1571- }
15721518 mvd[comp] = i16::try_from(v)
15731519 .map_err(|_| Error::corrupt("mvd outside the level limits"))?;
15741520 }
@@ -1618,25 +1564,10 @@ fn decode_inter_mb(
16181564 // partition width inside an 8x8.
16191565 let n = mvc.neighbours(pic, px, py, pw, list);
16201566 let mvp = predict_mv(&n, idx, shape.w, shape.h, part);
1621- if trace_enabled() {
1622- eprintln!(
1623- " nb A {:?} B {:?} C {:?} shape {}x{} part {part} mvp {mvp:?} written {:#06x}",
1624- n[0], n[1], n[2], shape.w, shape.h, mvc.written
1625- );
1626- }
16271567 let d = motion.mvd[list][py * 4 + px];
16281568 mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])];
16291569 ref_idx[list] = idx;
1630- ref_id[list] = ctx
1631- .reference(refs, list, idx)
1632- .map(|p| p.id)
1633- .unwrap_or(-1);
1634- }
1635- if trace_enabled() {
1636- eprintln!(
1637- " MV part {part} sp {sp} at ({px},{py}) {pw}x{ph} mv {:?} ref {:?}",
1638- mv[0], ref_idx
1639- );
1570+ ref_id[list] = ctx.reference(refs, list, idx).map(|p| p.id).unwrap_or(-1);
16401571 }
16411572 for dy in 0..ph {
16421573 for dx in 0..pw {
@@ -1680,9 +1611,6 @@ fn decode_inter_mb(
16801611 pic.i4_modes[base..base + 4].fill(2);
16811612 }
16821613 let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?;
1683- if trace_enabled() {
1684- eprintln!(" cbp {cbp_luma:#x}/{cbp_chroma}");
1685- }
16861614 // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual.
16871615 finish_macroblock(
16881616 pic,
@@ -1737,7 +1665,11 @@ fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, u
17371665 /// Size of one *macroblock* partition in 4x4 blocks: always 8x8 for a
17381666 /// macroblock that carries sub-macroblock types, however those split it.
17391667 fn mb_part_size(shape: &MbShape) -> (usize, usize) {
1740- if shape.sub { (2, 2) } else { (shape.w, shape.h) }
1668+ if shape.sub {
1669+ (2, 2)
1670+ } else {
1671+ (shape.w, shape.h)
1672+ }
17411673 }
17421674
17431675 /// Size of one (sub-)macroblock partition in 4x4 blocks.
@@ -1860,8 +1792,9 @@ fn direct_quadrant(
18601792 }
18611793 }
18621794
1863-/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal
1864-/// (8.4.1.2.3).
1795+/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture
1796+/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3).
1797+#[allow(clippy::type_complexity)]
18651798 fn direct_block(
18661799 pic: &Picture,
18671800 refs: &[Picture],
@@ -1965,8 +1898,7 @@ fn direct_block(
19651898 /// picture the co-located block referenced.
19661899 fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 {
19671900 for i in 0..ctx.lists[0].len() {
1968- if ctx
1969- .lists[0]
1901+ if ctx.lists[0]
19701902 .get(i)
19711903 .and_then(|k| refs.get(k))
19721904 .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)
21112043
21122044 /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
21132045 /// vertical edges then all horizontal edges per macroblock, then chroma.
2046+// `e` and `j` are edge and segment positions inside the macroblock, used to
2047+// index the plane as well as the strength arrays; iterating the arrays would
2048+// hide which geometry each one names.
2049+#[allow(clippy::needless_range_loop)]
21142050 fn deblock_picture(pic: &mut Picture) {
2115- if no_deblock() {
2116- return;
2117- }
21182051 let mb_w = pic.mb_w;
21192052 for mb_y in 0..pic.mb_h {
21202053 for mb_x in 0..mb_w {
@@ -2208,7 +2141,12 @@ fn deblock_picture(pic: &mut Picture) {
22082141 }
22092142 // Eight rows around the edge are contiguous, so the
22102143 // whole 16-sample edge filters in one pass.
2211- filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, &params);
2144+ filter_luma_h_edge16(
2145+ &mut pic.y.data,
2146+ base + e * 4 * stride,
2147+ stride,
2148+ &params,
2149+ );
22122150 continue;
22132151 }
22142152 for j in 0..4 {
crates/ec-h264/src/dpb.rsmodified+58 -15
@@ -96,7 +96,8 @@ impl Plane8 {
9696 let (src, dst) = (full, full - (y + 1) * stride);
9797 self.data.copy_within(src..src + stride, dst);
9898 let src = full + (h - 1) * stride;
99- self.data.copy_within(src..src + stride, src + (y + 1) * stride);
99+ self.data
100+ .copy_within(src..src + stride, src + (y + 1) * stride);
100101 }
101102 }
102103 }
@@ -633,6 +634,7 @@ impl Dpb {
633634
634635 /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation
635636 /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3).
637+ #[allow(clippy::too_many_arguments)]
636638 pub(crate) fn build_ref_lists(
637639 &self,
638640 slice_type: SliceType,
@@ -704,7 +706,8 @@ impl Dpb {
704706 lists[1].push(i);
705707 }
706708 // 8.2.4.2.3 step 3.
707- if lists[1].len > 1 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len]
709+ if lists[1].len > 1
710+ && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len]
708711 {
709712 lists[1].entries.swap(0, 1);
710713 }
@@ -938,7 +941,12 @@ impl Dpb {
938941 }
939942
940943 /// Adaptive marking (clause 8.2.5.4).
941- fn apply_mmco(&mut self, pic: &mut Picture, m: &DecRefPicMarking, info: &PicInfo) -> Result<()> {
944+ fn apply_mmco(
945+ &mut self,
946+ pic: &mut Picture,
947+ m: &DecRefPicMarking,
948+ info: &PicInfo,
949+ ) -> Result<()> {
942950 let curr_pic_num = info.frame_num as i32;
943951 for op in &m.mmcos {
944952 match op.op {
@@ -1115,9 +1123,8 @@ mod tests {
11151123 fn extend_borders_replicates_edges() {
11161124 let mut p = plane(6, 5);
11171125 p.extend_borders();
1118- let at = |x: i32, y: i32| -> u8 {
1119- p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize]
1120- };
1126+ let at =
1127+ |x: i32, y: i32| -> u8 { p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] };
11211128 for y in -4..9i32 {
11221129 for x in -4..10i32 {
11231130 let cx = x.clamp(0, 5) as usize;
@@ -1200,9 +1207,24 @@ mod tests {
12001207 fn poc_type_2_is_twice_the_frame_number() {
12011208 let sps = sps_for(2);
12021209 let dpb = Dpb::default();
1203- assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0);
1204- assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, true, false)).unwrap().value, 6);
1205- assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, false, false)).unwrap().value, 5);
1210+ assert_eq!(
1211+ dpb.picture_order_count(&sps, &info(0, 0, true, true))
1212+ .unwrap()
1213+ .value,
1214+ 0
1215+ );
1216+ assert_eq!(
1217+ dpb.picture_order_count(&sps, &info(3, 0, true, false))
1218+ .unwrap()
1219+ .value,
1220+ 6
1221+ );
1222+ assert_eq!(
1223+ dpb.picture_order_count(&sps, &info(3, 0, false, false))
1224+ .unwrap()
1225+ .value,
1226+ 5
1227+ );
12061228 }
12071229
12081230 /// Type 1 walks the offset_for_ref_frame cycle.
@@ -1211,9 +1233,24 @@ mod tests {
12111233 let sps = sps_for(1);
12121234 let dpb = Dpb::default();
12131235 // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n.
1214- assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0);
1215- assert_eq!(dpb.picture_order_count(&sps, &info(1, 0, true, false)).unwrap().value, 2);
1216- assert_eq!(dpb.picture_order_count(&sps, &info(4, 0, true, false)).unwrap().value, 8);
1236+ assert_eq!(
1237+ dpb.picture_order_count(&sps, &info(0, 0, true, true))
1238+ .unwrap()
1239+ .value,
1240+ 0
1241+ );
1242+ assert_eq!(
1243+ dpb.picture_order_count(&sps, &info(1, 0, true, false))
1244+ .unwrap()
1245+ .value,
1246+ 2
1247+ );
1248+ assert_eq!(
1249+ dpb.picture_order_count(&sps, &info(4, 0, true, false))
1250+ .unwrap()
1251+ .value,
1252+ 8
1253+ );
12171254 }
12181255
12191256 fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) {
@@ -1259,7 +1296,9 @@ mod tests {
12591296 .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[]))
12601297 .unwrap();
12611298 let poc = |l: &RefList| -> Vec<i32> {
1262- (0..l.len()).map(|i| dpb.frames[l.get(i).unwrap()].poc).collect()
1299+ (0..l.len())
1300+ .map(|i| dpb.frames[l.get(i).unwrap()].poc)
1301+ .collect()
12631302 };
12641303 assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]);
12651304 assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]);
@@ -1277,8 +1316,12 @@ mod tests {
12771316 let lists = dpb
12781317 .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[]))
12791318 .unwrap();
1280- let l0: Vec<i32> = (0..2).map(|i| dpb.frames[lists[0].get(i).unwrap()].poc).collect();
1281- let l1: Vec<i32> = (0..2).map(|i| dpb.frames[lists[1].get(i).unwrap()].poc).collect();
1319+ let l0: Vec<i32> = (0..2)
1320+ .map(|i| dpb.frames[lists[0].get(i).unwrap()].poc)
1321+ .collect();
1322+ let l1: Vec<i32> = (0..2)
1323+ .map(|i| dpb.frames[lists[1].get(i).unwrap()].poc)
1324+ .collect();
12821325 assert_eq!(l0, vec![2, 0]);
12831326 assert_eq!(l1, vec![0, 2], "identical lists swap");
12841327 }
crates/ec-h264/src/inter.rsmodified+31 -14
@@ -82,7 +82,15 @@ const TMP_W: usize = 16 + 5;
8282 /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose
8383 /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter
8484 /// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`.
85-pub(crate) fn mc_luma(r: &RefPlane<'_>, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [u8]) {
85+pub(crate) fn mc_luma(
86+ r: &RefPlane<'_>,
87+ x: i32,
88+ y: i32,
89+ mv: [i16; 2],
90+ w: usize,
91+ h: usize,
92+ out: &mut [u8],
93+) {
8694 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
8795 let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3);
8896 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,
149157 for row in 0..h {
150158 for col in 0..w {
151159 let i = row * w + col;
152- let g = |dx: i32, dy: i32| r.data[base + (row as i32 + dy) as usize * stride
153- + (col as i32 + dx) as usize];
160+ let g = |dx: i32, dy: i32| {
161+ r.data[base + (row as i32 + dy) as usize * stride + (col as i32 + dx) as usize]
162+ };
154163 out[i] = match (fx, fy) {
155164 // Table 8-12, quarter positions on the integer rows/columns.
156165 (1, 0) => avg(g(0, 0), bb[i]),
@@ -185,12 +194,7 @@ pub(crate) fn mc_chroma(
185194 let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1);
186195 let stride = r.stride;
187196 let base = r.at(xi, yi);
188- let (wa, wb, wc, wd) = (
189- (8 - fx) * (8 - fy),
190- fx * (8 - fy),
191- (8 - fx) * fy,
192- fx * fy,
193- );
197+ let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy);
194198 for row in 0..h {
195199 let src = base + row * stride;
196200 for col in 0..w {
@@ -311,7 +315,14 @@ mod tests {
311315 (data, stride, origin)
312316 }
313317
314- fn plane(data: &[u8], stride: usize, origin: usize, w: usize, h: usize, pad: usize) -> RefPlane<'_> {
318+ fn plane(
319+ data: &[u8],
320+ stride: usize,
321+ origin: usize,
322+ w: usize,
323+ h: usize,
324+ pad: usize,
325+ ) -> RefPlane<'_> {
315326 RefPlane {
316327 data,
317328 stride,
@@ -324,6 +335,7 @@ mod tests {
324335
325336 /// The spec's clipped, per-sample definition of the same interpolation,
326337 /// written straight from Equations 8-239 to 8-261 with no padding tricks.
338+ #[allow(clippy::too_many_arguments)]
327339 fn spec_luma(
328340 pic: &[u8],
329341 stride: usize,
@@ -396,15 +408,20 @@ mod tests {
396408 let r = plane(&data, stride, origin, w, h, pad);
397409 let mut ours = [0u8; 256];
398410 let mut theirs = [0u8; 256];
399- for &(px, py) in &[(8i32, 8i32), (0, 0), (32, 16), (-40, -40), (60, 44), (44, 4)] {
411+ for &(px, py) in &[
412+ (8i32, 8i32),
413+ (0, 0),
414+ (32, 16),
415+ (-40, -40),
416+ (60, 44),
417+ (44, 4),
418+ ] {
400419 for fy in 0..4i16 {
401420 for fx in 0..4i16 {
402421 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {
403422 let mv = [fx - 20 * 4, fy + 12];
404423 mc_luma(&r, px, py, mv, pw, ph, &mut ours);
405- spec_luma(
406- &data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs,
407- );
424+ spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);
408425 assert_eq!(
409426 ours[..pw * ph],
410427 theirs[..pw * ph],
crates/ec-h264/src/mv.rsmodified+31 -9
@@ -216,7 +216,14 @@ impl MvCtx {
216216 /// Neighbours A, B and C of a partition whose top-left 4x4 block is at
217217 /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks
218218 /// (clause 6.4.11.7, with the C-to-D substitution of 8-214).
219- pub(crate) fn neighbours(&self, pic: &Picture, px: usize, py: usize, pw: usize, list: usize) -> [Nb; 3] {
219+ pub(crate) fn neighbours(
220+ &self,
221+ pic: &Picture,
222+ px: usize,
223+ py: usize,
224+ pw: usize,
225+ list: usize,
226+ ) -> [Nb; 3] {
220227 let bx = (self.mb_x * 4 + px) as i32;
221228 let by = (self.mb_y * 4 + py) as i32;
222229 let a = self.at(pic, bx - 1, by, list);
@@ -239,7 +246,13 @@ fn median(a: i16, b: i16, c: i16) -> i16 {
239246 ///
240247 /// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only
241248 /// select those shortcuts; `part` is the macroblock partition index.
242-pub(crate) fn predict_mv(n: &[Nb; 3], ref_idx: i8, part_w: usize, part_h: usize, part: usize) -> [i16; 2] {
249+pub(crate) fn predict_mv(
250+ n: &[Nb; 3],
251+ ref_idx: i8,
252+ part_w: usize,
253+ part_h: usize,
254+ part: usize,
255+) -> [i16; 2] {
243256 let [a, mut b, mut c] = *n;
244257 match (part_w, part_h, part) {
245258 (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) {
318331 /// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the
319332 /// context thresholds of 9.3.3.1.1.7 can distinguish.
320333 #[inline]
321-pub(crate) fn write_mvd(pic: &mut Picture, mb_x: usize, mb_y: usize, px: usize, py: usize, list: usize, mvd: [i16; 2]) {
334+pub(crate) fn write_mvd(
335+ pic: &mut Picture,
336+ mb_x: usize,
337+ mb_y: usize,
338+ px: usize,
339+ py: usize,
340+ list: usize,
341+ mvd: [i16; 2],
342+) {
322343 let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px;
323344 let e = &mut pic.mvd_abs[idx];
324345 e[list * 2] = mvd[0].unsigned_abs().min(127) as u8;
@@ -379,11 +400,7 @@ mod tests {
379400 use super::*;
380401
381402 fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb {
382- Nb {
383- avail,
384- mv,
385- ref_idx,
386- }
403+ Nb { avail, mv, ref_idx }
387404 }
388405
389406 /// With exactly one neighbour on the same reference picture, that
@@ -413,7 +430,11 @@ mod tests {
413430 /// median into A (8-207 to 8-210).
414431 #[test]
415432 fn unavailable_b_and_c_fall_back_to_a() {
416- let n = [nb(true, [6, -6], 3), nb(false, [0, 0], -1), nb(false, [0, 0], -1)];
433+ let n = [
434+ nb(true, [6, -6], 3),
435+ nb(false, [0, 0], -1),
436+ nb(false, [0, 0], -1),
437+ ];
417438 assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]);
418439 // With refIdx 3 the single-match rule fires first, same answer.
419440 assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]);
@@ -449,6 +470,7 @@ mod tests {
449470 assert_eq!(B_SHAPES[0].pred[0], Pred::Direct);
450471 assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi));
451472 // The 16x8 / 8x16 pairs alternate, starting at mb_type 4.
473+ #[allow(clippy::needless_range_loop)]
452474 for t in 4..22 {
453475 let s = B_SHAPES[t];
454476 assert_eq!(s.parts, 2, "mb_type {t}");
crates/ec-h264/tests/conformance.rsmodified+229 -125
@@ -179,12 +179,9 @@ fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> {
179179 let mut dec = Decoder::new();
180180 let mut frames = Vec::new();
181181 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
182- match dec.push_nal(nal)? {
183- NalOutcome::PictureBoundary => {
184- dec.end_picture()?;
185- dec.push_nal(nal)?;
186- }
187- _ => {}
182+ if dec.push_nal(nal)? == NalOutcome::PictureBoundary {
183+ dec.end_picture()?;
184+ dec.push_nal(nal)?;
188185 }
189186 while let Some(f) = dec.next_frame() {
190187 frames.push(frame_bytes(&f));
@@ -199,13 +196,8 @@ fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> {
199196
200197 /// Every frame ffmpeg decodes from `stream`, as raw I420.
201198 fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> {
202- let mut cmd = Command::new("ffmpeg");
203- cmd.args(["-v", "error"]);
204- if std::env::var_os("EC_H264_NO_DEBLOCK").is_some() {
205- cmd.args(["-skip_loop_filter", "all"]);
206- }
207- let out = cmd
208- .arg("-i")
199+ let out = Command::new("ffmpeg")
200+ .args(["-v", "error", "-i"])
209201 .arg(stream)
210202 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
211203 .output()
@@ -268,8 +260,7 @@ fn compare_sequence(stream: &Path) -> Result<usize, String> {
268260 let bytes = std::fs::read(stream).map_err(|e| e.to_string())?;
269261 let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?;
270262 let first = ours.first().ok_or("no frames decoded")?;
271- let theirs =
272- ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?;
263+ let theirs = ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?;
273264 if ours.len() != theirs.len() {
274265 return Err(format!(
275266 "{} frames decoded, ffmpeg gave {}",
@@ -398,7 +389,7 @@ fn steady_state_decode_loop_zero_alloc() {
398389 };
399390 let bytes = std::fs::read(stream).unwrap();
400391 let mut dec = Decoder::new();
401- let mut drive = |dec: &mut Decoder, count: bool| -> usize {
392+ let drive = |dec: &mut Decoder, count: bool| -> usize {
402393 let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
403394 let mut frames = 0usize;
404395 for nal in &nals {
@@ -435,8 +426,14 @@ fn steady_state_decode_loop_zero_alloc() {
435426 ALLOCS.store(0, Ordering::SeqCst);
436427 let again = drive(&mut dec, true);
437428 let n = ALLOCS.load(Ordering::SeqCst);
438- assert_eq!(again, warm, "{name}: frame count changed on the second pass");
439- assert_eq!(n, 0, "{name}: steady-state slice decode allocated {n} times");
429+ assert_eq!(
430+ again, warm,
431+ "{name}: frame count changed on the second pass"
432+ );
433+ assert_eq!(
434+ n, 0,
435+ "{name}: steady-state slice decode allocated {n} times"
436+ );
440437 }
441438
442439 // Sanity: the counter is alive — emitting a frame does allocate.
@@ -454,9 +451,13 @@ fn steady_state_decode_loop_zero_alloc() {
454451 );
455452 }
456453
457-/// Decode-rate measurement: ns per macroblock and Mpx/s over the first IDR,
458-/// printed for the perf report. Run with `--nocapture` to see it. Uses the
459-/// steady-state path (buffers warm) like a playback loop would.
454+/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf
455+/// report. Run with `--nocapture` to see it. Uses the steady-state path
456+/// (buffers warm) like a playback loop would.
457+///
458+/// Both halves matter: the intra measurement is what the previous release
459+/// reported, and the whole-sequence one is what playback actually costs, since
460+/// a real stream is almost all inter pictures.
460461 #[test]
461462 fn ns_per_macroblock_measurement() {
462463 let base = vectors_dir();
@@ -501,6 +502,40 @@ fn ns_per_macroblock_measurement() {
501502 (intra IDR, single thread, deblock included, output copy excluded)"
502503 );
503504 }
505+ perf_whole_sequence();
506+}
507+
508+/// The same measurement over whole sequences, where inter prediction, the
509+/// decoded picture buffer and output all count.
510+fn perf_whole_sequence() {
511+ let base = vectors_dir();
512+ for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] {
513+ let Some(stream) = find_stream(&base.join(name)) else {
514+ continue;
515+ };
516+ let bytes = std::fs::read(stream).unwrap();
517+ let Ok(warm) = decode_all(&bytes) else {
518+ continue;
519+ };
520+ if warm.is_empty() {
521+ continue;
522+ }
523+ let frames = warm.len() as f64;
524+ let start = std::time::Instant::now();
525+ let iters = 5u32;
526+ for _ in 0..iters {
527+ let _ = decode_all(&bytes).expect("decode");
528+ }
529+ let elapsed = start.elapsed().as_secs_f64() / f64::from(iters);
530+ // Every vector here is QCIF: 11 x 9 macroblocks.
531+ let mbs = 99.0 * frames;
532+ eprintln!(
533+ "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \
534+ (full sequence, single thread, deblock and output copy included)",
535+ elapsed * 1e9 / mbs,
536+ 176.0 * 144.0 * frames / elapsed / 1e6
537+ );
538+ }
504539 }
505540
506541 /// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte
@@ -1027,89 +1062,6 @@ fn p_only_gop_matches_ffmpeg_every_frame() {
10271062 assert!(failures.is_empty(), "{failures:#?}");
10281063 }
10291064
1030-/// Scratch driver kept out of the default run: decode a stream named by
1031-/// `EC_H264_DEBUG_STREAM` frame by frame and report the first mismatch.
1032-#[test]
1033-#[ignore]
1034-fn debug_named_stream() {
1035- let Ok(path) = std::env::var("EC_H264_DEBUG_STREAM") else {
1036- return;
1037- };
1038- let stream = PathBuf::from(path);
1039- let bytes = std::fs::read(&stream).unwrap();
1040- let mut dec = Decoder::new();
1041- let mut pictures = 0usize;
1042- for (i, nal) in ec_h264_syntax::AnnexBIter::new(&bytes).enumerate() {
1043- let kind = nal[0] & 0x1F;
1044- match dec.push_nal(nal) {
1045- Ok(NalOutcome::PictureBoundary) => {
1046- dec.end_picture().unwrap();
1047- pictures += 1;
1048- if let Err(e) = dec.push_nal(nal) {
1049- panic!("nal {i} (type {kind}) after {pictures} pictures: {e}");
1050- }
1051- }
1052- Ok(_) => {}
1053- Err(e) => panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"),
1054- }
1055- while dec.next_frame().is_some() {}
1056- }
1057- dec.flush().unwrap();
1058- eprintln!("decoded {pictures} pictures");
1059- let ours = decode_all(&bytes).unwrap();
1060- let theirs = match std::env::var("EC_H264_DEBUG_REF") {
1061- Ok(p) => {
1062- let raw = std::fs::read(p).unwrap();
1063- raw.chunks_exact(ours[0].len()).map(<[u8]>::to_vec).collect()
1064- }
1065- Err(_) => ffmpeg_all_frames(&stream, ours[0].len()).unwrap(),
1066- };
1067- if std::env::var_os("EC_H264_DUMP").is_some() {
1068- let w = 176usize;
1069- for (label, f) in [("ref0", &ours[0]), ("ours1", &ours[1]), ("ff1", &theirs[1])] {
1070- eprintln!("--- {label} MB(0,0) rows 0..4 ---");
1071- for y in 0..4 {
1072- let row: Vec<u8> = (0..16).map(|x| f[y * w + x]).collect();
1073- eprintln!("{row:?}");
1074- }
1075- }
1076- }
1077- for (i, a) in ours.iter().enumerate().take(4) {
1078- let best = theirs
1079- .iter()
1080- .enumerate()
1081- .map(|(j, b)| (a.iter().zip(b).filter(|(x, y)| x != y).count(), j))
1082- .min();
1083- eprintln!("our frame {i} best matches reference {best:?}");
1084- }
1085- let w = 176usize;
1086- let h = 144usize;
1087- for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1088- let diff = a.iter().zip(b).filter(|(x, y)| x != y).count();
1089- if diff == 0 {
1090- eprintln!("frame {i}: exact");
1091- continue;
1092- }
1093- let mut mbs = std::collections::BTreeSet::new();
1094- for (k, (x, y)) in a.iter().zip(b).enumerate().take(w * h) {
1095- if x != y {
1096- mbs.insert(((k / w) / 16 * (w / 16) + (k % w) / 16, ((k % w) / 16, (k / w) / 16)));
1097- }
1098- }
1099- eprintln!(" first differing MBs: {:?}", mbs.iter().take(6).map(|m| m.1).collect::<Vec<_>>());
1100- let max = a
1101- .iter()
1102- .zip(b)
1103- .map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs())
1104- .max()
1105- .unwrap_or(0);
1106- eprintln!(
1107- "frame {i}: {diff} bytes differ, max delta {max}, {} luma MBs",
1108- mbs.len()
1109- );
1110- }
1111-}
1112-
11131065 /// JVT conformance, every frame of every vector: our display-order output
11141066 /// against the reference decoder YUV that ships with the vector.
11151067 ///
@@ -1141,7 +1093,10 @@ fn jvt_full_sequence_bit_exact() {
11411093 Ok(frames) => {
11421094 let len = frames[0].len();
11431095 let Some(ref_path) = find_ref_yuv(&dir) else {
1144- table.push_str(&format!("{name:<16} {:>3} frames, no reference YUV\n", frames.len()));
1096+ table.push_str(&format!(
1097+ "{name:<16} {:>3} frames, no reference YUV\n",
1098+ frames.len()
1099+ ));
11451100 continue;
11461101 };
11471102 let reference = std::fs::read(&ref_path).unwrap();
@@ -1159,18 +1114,27 @@ fn jvt_full_sequence_bit_exact() {
11591114 match bad {
11601115 None if frames.len() == want => {
11611116 passed += 1;
1162- table.push_str(&format!("{name:<16} {:>3}/{want:<3} frames bit-exact\n", frames.len()));
1117+ table.push_str(&format!(
1118+ "{name:<16} {:>3}/{want:<3} frames bit-exact\n",
1119+ frames.len()
1120+ ));
11631121 }
11641122 None => {
11651123 failed.push(format!(
11661124 "{name}: {} frames decoded, reference has {want}",
11671125 frames.len()
11681126 ));
1169- table.push_str(&format!("{name:<16} {:>3}/{want:<3} FRAME COUNT\n", frames.len()));
1127+ table.push_str(&format!(
1128+ "{name:<16} {:>3}/{want:<3} FRAME COUNT\n",
1129+ frames.len()
1130+ ));
11701131 }
11711132 Some((i, pos)) => {
11721133 failed.push(format!("{name}: frame {i} differs at byte {pos}"));
1173- table.push_str(&format!("{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", frames.len()));
1134+ table.push_str(&format!(
1135+ "{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n",
1136+ frames.len()
1137+ ));
11741138 }
11751139 }
11761140 }
@@ -1257,18 +1221,36 @@ fn b_pictures_match_ffmpeg_every_frame() {
12571221 }
12581222 let dir = scratch("b-gop");
12591223 let cases: &[(&str, &[&str])] = &[
1260- ("spatial", &["-x264-params", "bframes=3:b-adapt=0:direct=spatial:weightp=0"]),
1261- ("temporal", &["-x264-params", "bframes=3:b-adapt=0:direct=temporal:weightp=0"]),
1224+ (
1225+ "spatial",
1226+ &[
1227+ "-x264-params",
1228+ "bframes=3:b-adapt=0:direct=spatial:weightp=0",
1229+ ],
1230+ ),
1231+ (
1232+ "temporal",
1233+ &[
1234+ "-x264-params",
1235+ "bframes=3:b-adapt=0:direct=temporal:weightp=0",
1236+ ],
1237+ ),
12621238 // B pictures used as references, which makes the buffer hold pictures
12631239 // that are neither the newest nor the oldest.
12641240 (
12651241 "pyramid",
1266- &["-x264-params", "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial"],
1242+ &[
1243+ "-x264-params",
1244+ "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial",
1245+ ],
12671246 ),
12681247 // Weighted prediction on: explicit for P, implicit for B.
12691248 (
12701249 "weighted",
1271- &["-x264-params", "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial"],
1250+ &[
1251+ "-x264-params",
1252+ "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial",
1253+ ],
12721254 ),
12731255 ];
12741256 let mut failures = Vec::new();
@@ -1356,17 +1338,17 @@ fn output_is_display_order_and_the_reorder_is_real() {
13561338 "decode-order frame {i} is not in the display-order output"
13571339 );
13581340 }
1359- let moved = decode
1360- .iter()
1361- .zip(&display)
1362- .filter(|(a, b)| a != b)
1363- .count();
1341+ let moved = decode.iter().zip(&display).filter(|(a, b)| a != b).count();
13641342 assert!(
13651343 moved > 0,
13661344 "decode order and display order are identical: the stream does not \
13671345 reorder, so this test proves nothing"
13681346 );
1369- eprintln!("{} of {} frames move under reordering", moved, display.len());
1347+ eprintln!(
1348+ "{} of {} frames move under reordering",
1349+ moved,
1350+ display.len()
1351+ );
13701352 }
13711353
13721354 /// 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() {
14751457 None => failures.push(format!("{tag}: ffmpeg cannot encode")),
14761458 }
14771459 }
1478- assert!(checked >= 40, "too few {coder} quantisers exercised: {checked}");
1460+ assert!(
1461+ checked >= 40,
1462+ "too few {coder} quantisers exercised: {checked}"
1463+ );
14791464 eprintln!("{coder}: {checked} quantisers bit-exact over a GOP with motion");
14801465 }
14811466 let _ = std::fs::remove_dir_all(&dir);
@@ -1498,12 +1483,20 @@ fn geometry_with_motion_matches_ffmpeg() {
14981483 // Neighbour availability stops at every slice boundary, and a motion
14991484 // vector predictor at one sees no partition across it.
15001485 ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]),
1501- ("nodeblock", "352x288", &["bframes=2:b-adapt=0:no-deblock=1"]),
1486+ (
1487+ "nodeblock",
1488+ "352x288",
1489+ &["bframes=2:b-adapt=0:no-deblock=1"],
1490+ ),
15021491 // One macroblock wide: every spatial neighbour is unavailable, which
15031492 // is where the reference index of a missing partition matters most.
15041493 ("tiny", "16x16", &["bframes=2:b-adapt=0"]),
15051494 // Many references, so the list is long and reordering is real work.
1506- ("manyref", "352x288", &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"]),
1495+ (
1496+ "manyref",
1497+ "352x288",
1498+ &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"],
1499+ ),
15071500 ];
15081501 let mut table = String::new();
15091502 let mut failures = Vec::new();
@@ -1522,7 +1515,9 @@ fn geometry_with_motion_matches_ffmpeg() {
15221515 let name = format!("{coder}-{tag}");
15231516 match x264_encode_gop(&dir, &name, size, 10, &extra) {
15241517 Some(stream) => match compare_sequence(&stream) {
1525- Ok(n) => table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n")),
1518+ Ok(n) => {
1519+ table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n"))
1520+ }
15261521 Err(e) => {
15271522 table.push_str(&format!("{name:<14} {size:<10} {e}\n"));
15281523 failures.push(format!("{name}: {e}"));
@@ -1754,7 +1749,8 @@ fn real_library_streams_match_ffmpeg() {
17541749 eprintln!("SKIP: ffmpeg not on PATH");
17551750 return;
17561751 }
1757- let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
1752+ let manifest =
1753+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
17581754 let Ok(text) = std::fs::read_to_string(&manifest) else {
17591755 eprintln!("SKIP: {} missing", manifest.display());
17601756 return;
@@ -1825,11 +1821,15 @@ fn real_library_streams_match_ffmpeg() {
18251821 }
18261822 Err(e) if e.contains("unsupported") => {
18271823 refused += 1;
1828- table.push_str(&format!("{name:<40} {container:<12} {width:>5}px refused: {e}\n"));
1824+ table.push_str(&format!(
1825+ "{name:<40} {container:<12} {width:>5}px refused: {e}\n"
1826+ ));
18291827 }
18301828 Err(e) => {
18311829 failures.push(format!("{name}: {e}"));
1832- table.push_str(&format!("{name:<40} {container:<12} {width:>5}px ERROR {e}\n"));
1830+ table.push_str(&format!(
1831+ "{name:<40} {container:<12} {width:>5}px ERROR {e}\n"
1832+ ));
18331833 }
18341834 }
18351835 }
@@ -1842,3 +1842,107 @@ fn real_library_streams_match_ffmpeg() {
18421842 "only {decoded} real files swept end to end; the sweep is the point"
18431843 );
18441844 }
1845+
1846+/// The registry entry surface, driven the way a demuxer drives it: one access
1847+/// unit per packet, frames pulled with `receive_frame`.
1848+///
1849+/// This is where display order has to actually arrive. Everything above tests
1850+/// the NAL-level API; a player never touches that one, so a reordering decoder
1851+/// whose packet API still hands back decode order would look correct in every
1852+/// other test here and wrong on screen.
1853+#[test]
1854+fn packet_entry_surface_reorders_and_carries_timestamps() {
1855+ if !have_ffmpeg() {
1856+ eprintln!("SKIP: ffmpeg not on PATH");
1857+ return;
1858+ }
1859+ let dir = scratch("entry");
1860+ let extra = [
1861+ "-profile:v",
1862+ "main",
1863+ "-coder",
1864+ "ac",
1865+ "-qp",
1866+ "26",
1867+ "-x264-params",
1868+ "bframes=3:b-adapt=0:b-pyramid=normal",
1869+ ];
1870+ let stream = x264_encode_gop(&dir, "entry", "176x144", 16, &extra).expect("encode");
1871+ let data = std::fs::read(&stream).unwrap();
1872+ assert!(
1873+ slice_type_counts(&data)[2] > 0,
1874+ "the encoder produced no B slices"
1875+ );
1876+
1877+ // Split the stream into access units the way a demuxer would: a new one
1878+ // starts at each parameter set or first slice of a picture.
1879+ let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
1880+ .map(<[u8]>::to_vec)
1881+ .collect();
1882+ let mut access_units: Vec<Vec<u8>> = Vec::new();
1883+ let mut current: Vec<u8> = Vec::new();
1884+ let mut current_has_slice = false;
1885+ for unit in &units {
1886+ let is_slice = matches!(unit[0] & 0x1F, 1 | 5);
1887+ if is_slice && current_has_slice {
1888+ access_units.push(std::mem::take(&mut current));
1889+ current_has_slice = false;
1890+ }
1891+ current_has_slice |= is_slice;
1892+ current.extend_from_slice(&[0, 0, 0, 1]);
1893+ current.extend_from_slice(unit);
1894+ }
1895+ if current_has_slice {
1896+ access_units.push(current);
1897+ }
1898+
1899+ let time_base = TimeBase::new(1, 25);
1900+ let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder");
1901+ let mut out: Vec<(i64, Vec<u8>)> = Vec::new();
1902+ for (i, au) in access_units.iter().enumerate() {
1903+ let packet = Packet::new(0, time_base, au.clone()).with_pts(i as i64);
1904+ decoder.send_packet(&packet).expect("send_packet");
1905+ while let Ok(Frame::Video(f)) = decoder.receive_frame() {
1906+ out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f)));
1907+ }
1908+ }
1909+ decoder.flush().expect("flush");
1910+ while let Ok(Frame::Video(f)) = decoder.receive_frame() {
1911+ out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f)));
1912+ }
1913+
1914+ let expected = ffmpeg_all_frames(&stream, out[0].1.len()).expect("ffmpeg");
1915+ let _ = std::fs::remove_dir_all(&dir);
1916+ assert_eq!(out.len(), expected.len(), "frame count");
1917+ for (i, ((_, ours), theirs)) in out.iter().zip(&expected).enumerate() {
1918+ assert!(
1919+ first_diff(ours, theirs).is_none(),
1920+ "packet-path frame {i} differs from ffmpeg"
1921+ );
1922+ }
1923+ // Each packet was tagged with its own index in *decode* order, so the tag
1924+ // that comes back on a picture says which packet produced it. Decoding the
1925+ // same stream in decode order gives the pixels for each of those indices,
1926+ // and the two have to line up: that is the timestamp staying with its
1927+ // picture across the reordering, not merely arriving in some order.
1928+ let by_decode_order = decode_all_in_decode_order(&data).expect("decode order");
1929+ assert_eq!(by_decode_order.len(), out.len());
1930+ for (position, (tag, pixels)) in out.iter().enumerate() {
1931+ let tag = usize::try_from(*tag).expect("a tag was lost");
1932+ assert!(
1933+ first_diff(pixels, &by_decode_order[tag]).is_none(),
1934+ "output position {position} carries the timestamp of packet {tag}, \
1935+ but its pixels are a different picture"
1936+ );
1937+ }
1938+ let order: Vec<i64> = out.iter().map(|(pts, _)| *pts).collect();
1939+ assert_ne!(
1940+ order,
1941+ (0..order.len() as i64).collect::<Vec<_>>(),
1942+ "output order equals packet order, so no reordering happened"
1943+ );
1944+ eprintln!(
1945+ "packet entry surface: {} frames, packets emitted in order {order:?}",
1946+ out.len()
1947+ );
1948+}