Display-order output reaches the packet entry surface
Browse files at this commit5a58bb10a766d29a51ec02ea08d17602a8af750cParent: 7c078b5- feat
- display-order output reaches the packet entry surface
8 changed files +395 -269
- crates/ec-h264/Cargo.toml +1 -1
- crates/ec-h264/src/cabac.rs +5 -1
- crates/ec-h264/src/cabac_tables.rs +6 -8
- crates/ec-h264/src/decoder.rs +34 -96
- crates/ec-h264/src/dpb.rs +58 -15
- crates/ec-h264/src/inter.rs +31 -14
- crates/ec-h264/src/mv.rs +31 -9
- crates/ec-h264/tests/conformance.rs +229 -125
crates/ec-h264/Cargo.tomlmodified+1 -1
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "ec-h264" | 2 | 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" |
| 4 | version.workspace = true | 4 | version.workspace = true |
| 5 | edition.workspace = true | 5 | edition.workspace = true |
| 6 | license.workspace = true | 6 | license.workspace = true |
crates/ec-h264/src/cabac.rsmodified+5 -1
| @@ -344,7 +344,11 @@ impl<'a> Cabac<'a> { | |||
| 344 | if !self.decision(OFF_SUB_TYPE_P + 1) { | 344 | if !self.decision(OFF_SUB_TYPE_P + 1) { |
| 345 | return 1; | 345 | return 1; |
| 346 | } | 346 | } |
| 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 | + } | ||
| 348 | } | 352 | } |
| 349 | 353 | ||
| 350 | /// sub_mb_type of a B macroblock (Table 9-38). | 354 | /// 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] = [ | |||
| 387 | 387 | ||
| 388 | /// Table 9-45: transIdxLPS. | 388 | /// Table 9-45: transIdxLPS. |
| 389 | pub(crate) const TRANS_LPS: [u8; 64] = [ | 389 | pub(crate) const TRANS_LPS: [u8; 64] = [ |
| 390 | - 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, | 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 | - 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, | 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 | - 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, | 392 | + 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, |
| 393 | - 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, | ||
| 394 | ]; | 393 | ]; |
| 395 | 394 | ||
| 396 | /// Table 9-45: transIdxMPS. | 395 | /// Table 9-45: transIdxMPS. |
| 397 | pub(crate) const TRANS_MPS: [u8; 64] = [ | 396 | pub(crate) const TRANS_MPS: [u8; 64] = [ |
| 398 | - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, | 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, |
| 399 | - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, | 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, |
| 400 | - 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, | 399 | + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, |
| 401 | - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, | ||
| 402 | ]; | 400 | ]; |
crates/ec-h264/src/decoder.rsmodified+34 -96
| @@ -42,8 +42,8 @@ use crate::entropy::{ | |||
| 42 | }; | 42 | }; |
| 43 | use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; | 43 | use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; |
| 44 | use crate::mv::{ | 44 | use crate::mv::{ |
| 45 | - B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, | 45 | + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd, |
| 46 | - neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, | 46 | + predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, |
| 47 | }; | 47 | }; |
| 48 | use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; | 48 | use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; |
| 49 | use crate::tables::{BLK4_POS, CHROMA_QP}; | 49 | use crate::tables::{BLK4_POS, CHROMA_QP}; |
| @@ -52,18 +52,6 @@ use crate::transform::{ | |||
| 52 | unzigzag, unzigzag_ac15, | 52 | unzigzag, unzigzag_ac15, |
| 53 | }; | 53 | }; |
| 54 | 54 | ||
| 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 | - | ||
| 67 | /// Where a 4x4 block's top-right neighbour samples come from, per | 55 | /// Where a 4x4 block's top-right neighbour samples come from, per |
| 68 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). | 56 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). |
| 69 | #[derive(Clone, Copy, PartialEq)] | 57 | #[derive(Clone, Copy, PartialEq)] |
| @@ -471,7 +459,7 @@ impl Decoder { | |||
| 471 | let lists = if sh.slice_type.is_intra() { | 459 | let lists = if sh.slice_type.is_intra() { |
| 472 | [RefList::default(), RefList::default()] | 460 | [RefList::default(), RefList::default()] |
| 473 | } else { | 461 | } else { |
| 474 | - self.dpb.number_short_term(sh.frame_num, &sps); | 462 | + self.dpb.number_short_term(sh.frame_num, sps); |
| 475 | self.dpb.build_ref_lists( | 463 | self.dpb.build_ref_lists( |
| 476 | sh.slice_type, | 464 | sh.slice_type, |
| 477 | self.cur.poc, | 465 | self.cur.poc, |
| @@ -515,25 +503,6 @@ impl Decoder { | |||
| 515 | weights: sh.pred_weight_table.clone(), | 503 | weights: sh.pred_weight_table.clone(), |
| 516 | poc: self.cur.poc, | 504 | poc: self.cur.poc, |
| 517 | }; | 505 | }; |
| 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 | - } | ||
| 537 | let intra_slice = sh.slice_type.is_intra(); | 506 | let intra_slice = sh.slice_type.is_intra(); |
| 538 | let b_slice = sh.slice_type == SliceType::B; | 507 | let b_slice = sh.slice_type == SliceType::B; |
| 539 | if !intra_slice && ctx.lists[0].len() == 0 { | 508 | if !intra_slice && ctx.lists[0].len() == 0 { |
| @@ -635,9 +604,8 @@ impl Decoder { | |||
| 635 | let mb_x = mb_addr % pic.mb_w; | 604 | let mb_x = mb_addr % pic.mb_w; |
| 636 | let mb_y = mb_addr / pic.mb_w; | 605 | let mb_y = mb_addr / pic.mb_w; |
| 637 | let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); | 606 | let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); |
| 638 | - let cond = |avail: bool, addr: usize| { | 607 | + let cond = |
| 639 | - usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0) | 608 | + |avail: bool, addr: usize| usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0); |
| 640 | - }; | ||
| 641 | cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w)) | 609 | cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w)) |
| 642 | } | 610 | } |
| 643 | 611 | ||
| @@ -832,13 +800,11 @@ impl SliceCtx { | |||
| 832 | use1: bool, | 800 | use1: bool, |
| 833 | ) -> Weights { | 801 | ) -> Weights { |
| 834 | let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1; | 802 | let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1; |
| 835 | - let explicit = (self.weighted_bipred_idc == 1 && self.is_b()) | 803 | + let explicit = |
| 836 | - || (self.weighted_pred && !self.is_b()); | 804 | + (self.weighted_bipred_idc == 1 && self.is_b()) || (self.weighted_pred && !self.is_b()); |
| 837 | if implicit { | 805 | if implicit { |
| 838 | - let (Some(p0), Some(p1)) = ( | 806 | + let (Some(p0), Some(p1)) = (self.reference(refs, 0, r0), self.reference(refs, 1, r1)) |
| 839 | - self.reference(refs, 0, r0), | 807 | + else { |
| 840 | - self.reference(refs, 1, r1), | ||
| 841 | - ) else { | ||
| 842 | return Weights::DEFAULT; | 808 | return Weights::DEFAULT; |
| 843 | }; | 809 | }; |
| 844 | let td = (p1.poc - p0.poc).clamp(-128, 127); | 810 | let td = (p1.poc - p0.poc).clamp(-128, 127); |
| @@ -1056,17 +1022,8 @@ fn decode_macroblock( | |||
| 1056 | (None, Some(mb_type)) | 1022 | (None, Some(mb_type)) |
| 1057 | }; | 1023 | }; |
| 1058 | r.set_intra(intra_type.is_some()); | 1024 | 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 | - | ||
| 1066 | if let Some(shape) = shape { | 1025 | if let Some(shape) = shape { |
| 1067 | - return decode_inter_mb( | 1026 | + return decode_inter_mb(pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr); |
| 1068 | - pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr, | ||
| 1069 | - ); | ||
| 1070 | } | 1027 | } |
| 1071 | let mb_type = intra_type.expect("an intra macroblock type"); | 1028 | let mb_type = intra_type.expect("an intra macroblock type"); |
| 1072 | write_intra_mb(pic, mb_x, mb_y); | 1029 | write_intra_mb(pic, mb_x, mb_y); |
| @@ -1424,7 +1381,9 @@ fn finish_macroblock( | |||
| 1424 | /// Decode an inter macroblock: sub-macroblock types, reference indices and | 1381 | /// Decode an inter macroblock: sub-macroblock types, reference indices and |
| 1425 | /// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation | 1382 | /// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation |
| 1426 | /// (8.4.2) and the shared residual path. | 1383 | /// (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)] | ||
| 1428 | fn decode_inter_mb( | 1387 | fn decode_inter_mb( |
| 1429 | pic: &mut Picture, | 1388 | pic: &mut Picture, |
| 1430 | refs: &[Picture], | 1389 | refs: &[Picture], |
| @@ -1468,9 +1427,6 @@ fn decode_inter_mb( | |||
| 1468 | if shape.sub && !skipped { | 1427 | if shape.sub && !skipped { |
| 1469 | for part in 0..4 { | 1428 | for part in 0..4 { |
| 1470 | let t = r.sub_mb_type(b)? as usize; | 1429 | let t = r.sub_mb_type(b)? as usize; |
| 1471 | - if trace_enabled() { | ||
| 1472 | - eprintln!(" sub_mb_type[{part}] = {t}"); | ||
| 1473 | - } | ||
| 1474 | motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; | 1430 | motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; |
| 1475 | if motion.sub[part].pred == Pred::Direct { | 1431 | if motion.sub[part].pred == Pred::Direct { |
| 1476 | for k in 0..4 { | 1432 | for k in 0..4 { |
| @@ -1504,11 +1460,7 @@ fn decode_inter_mb( | |||
| 1504 | let by = (mb_y * 4 + py) as i32; | 1460 | let by = (mb_y * 4 + py) as i32; |
| 1505 | let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list) | 1461 | let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list) |
| 1506 | + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list); | 1462 | + 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; | 1463 | + 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 | ||
| 1512 | }; | 1464 | }; |
| 1513 | motion.ref_idx[list][part] = idx; | 1465 | motion.ref_idx[list][part] = idx; |
| 1514 | // Publish it over the whole macroblock partition — one | 1466 | // Publish it over the whole macroblock partition — one |
| @@ -1563,12 +1515,6 @@ fn decode_inter_mb( | |||
| 1563 | 0 | 1515 | 0 |
| 1564 | }; | 1516 | }; |
| 1565 | let v = r.mvd(comp, inc)?; | 1517 | 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 | - } | ||
| 1572 | mvd[comp] = i16::try_from(v) | 1518 | mvd[comp] = i16::try_from(v) |
| 1573 | .map_err(|_| Error::corrupt("mvd outside the level limits"))?; | 1519 | .map_err(|_| Error::corrupt("mvd outside the level limits"))?; |
| 1574 | } | 1520 | } |
| @@ -1618,25 +1564,10 @@ fn decode_inter_mb( | |||
| 1618 | // partition width inside an 8x8. | 1564 | // partition width inside an 8x8. |
| 1619 | let n = mvc.neighbours(pic, px, py, pw, list); | 1565 | let n = mvc.neighbours(pic, px, py, pw, list); |
| 1620 | let mvp = predict_mv(&n, idx, shape.w, shape.h, part); | 1566 | 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 | - } | ||
| 1627 | let d = motion.mvd[list][py * 4 + px]; | 1567 | let d = motion.mvd[list][py * 4 + px]; |
| 1628 | mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; | 1568 | mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; |
| 1629 | ref_idx[list] = idx; | 1569 | ref_idx[list] = idx; |
| 1630 | - ref_id[list] = ctx | 1570 | + ref_id[list] = ctx.reference(refs, list, idx).map(|p| p.id).unwrap_or(-1); |
| 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 | - ); | ||
| 1640 | } | 1571 | } |
| 1641 | for dy in 0..ph { | 1572 | for dy in 0..ph { |
| 1642 | for dx in 0..pw { | 1573 | for dx in 0..pw { |
| @@ -1680,9 +1611,6 @@ fn decode_inter_mb( | |||
| 1680 | pic.i4_modes[base..base + 4].fill(2); | 1611 | pic.i4_modes[base..base + 4].fill(2); |
| 1681 | } | 1612 | } |
| 1682 | let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; | 1613 | let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; |
| 1683 | - if trace_enabled() { | ||
| 1684 | - eprintln!(" cbp {cbp_luma:#x}/{cbp_chroma}"); | ||
| 1685 | - } | ||
| 1686 | // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. | 1614 | // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. |
| 1687 | finish_macroblock( | 1615 | finish_macroblock( |
| 1688 | pic, | 1616 | pic, |
| @@ -1737,7 +1665,11 @@ fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, u | |||
| 1737 | /// Size of one *macroblock* partition in 4x4 blocks: always 8x8 for a | 1665 | /// Size of one *macroblock* partition in 4x4 blocks: always 8x8 for a |
| 1738 | /// macroblock that carries sub-macroblock types, however those split it. | 1666 | /// macroblock that carries sub-macroblock types, however those split it. |
| 1739 | fn mb_part_size(shape: &MbShape) -> (usize, usize) { | 1667 | 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 | + } | ||
| 1741 | } | 1673 | } |
| 1742 | 1674 | ||
| 1743 | /// Size of one (sub-)macroblock partition in 4x4 blocks. | 1675 | /// Size of one (sub-)macroblock partition in 4x4 blocks. |
| @@ -1860,8 +1792,9 @@ fn direct_quadrant( | |||
| 1860 | } | 1792 | } |
| 1861 | } | 1793 | } |
| 1862 | 1794 | ||
| 1863 | -/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal | 1795 | +/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture |
| 1864 | -/// (8.4.1.2.3). | 1796 | +/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). |
| 1797 | +#[allow(clippy::type_complexity)] | ||
| 1865 | fn direct_block( | 1798 | fn direct_block( |
| 1866 | pic: &Picture, | 1799 | pic: &Picture, |
| 1867 | refs: &[Picture], | 1800 | refs: &[Picture], |
| @@ -1965,8 +1898,7 @@ fn direct_block( | |||
| 1965 | /// picture the co-located block referenced. | 1898 | /// picture the co-located block referenced. |
| 1966 | fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 { | 1899 | fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 { |
| 1967 | for i in 0..ctx.lists[0].len() { | 1900 | for i in 0..ctx.lists[0].len() { |
| 1968 | - if ctx | 1901 | + if ctx.lists[0] |
| 1969 | - .lists[0] | ||
| 1970 | .get(i) | 1902 | .get(i) |
| 1971 | .and_then(|k| refs.get(k)) | 1903 | .and_then(|k| refs.get(k)) |
| 1972 | .is_some_and(|p| p.id == col_ref_id) | 1904 | .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) | |||
| 2111 | 2043 | ||
| 2112 | /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all | 2044 | /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all |
| 2113 | /// vertical edges then all horizontal edges per macroblock, then chroma. | 2045 | /// 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)] | ||
| 2114 | fn deblock_picture(pic: &mut Picture) { | 2050 | fn deblock_picture(pic: &mut Picture) { |
| 2115 | - if no_deblock() { | ||
| 2116 | - return; | ||
| 2117 | - } | ||
| 2118 | let mb_w = pic.mb_w; | 2051 | let mb_w = pic.mb_w; |
| 2119 | for mb_y in 0..pic.mb_h { | 2052 | for mb_y in 0..pic.mb_h { |
| 2120 | for mb_x in 0..mb_w { | 2053 | for mb_x in 0..mb_w { |
| @@ -2208,7 +2141,12 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 2208 | } | 2141 | } |
| 2209 | // Eight rows around the edge are contiguous, so the | 2142 | // Eight rows around the edge are contiguous, so the |
| 2210 | // whole 16-sample edge filters in one pass. | 2143 | // whole 16-sample edge filters in one pass. |
| 2211 | - filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); | 2144 | + filter_luma_h_edge16( |
| 2145 | + &mut pic.y.data, | ||
| 2146 | + base + e * 4 * stride, | ||
| 2147 | + stride, | ||
| 2148 | + ¶ms, | ||
| 2149 | + ); | ||
| 2212 | continue; | 2150 | continue; |
| 2213 | } | 2151 | } |
| 2214 | for j in 0..4 { | 2152 | for j in 0..4 { |
crates/ec-h264/src/dpb.rsmodified+58 -15
| @@ -96,7 +96,8 @@ impl Plane8 { | |||
| 96 | let (src, dst) = (full, full - (y + 1) * stride); | 96 | let (src, dst) = (full, full - (y + 1) * stride); |
| 97 | self.data.copy_within(src..src + stride, dst); | 97 | self.data.copy_within(src..src + stride, dst); |
| 98 | let src = full + (h - 1) * stride; | 98 | 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); | ||
| 100 | } | 101 | } |
| 101 | } | 102 | } |
| 102 | } | 103 | } |
| @@ -633,6 +634,7 @@ impl Dpb { | |||
| 633 | 634 | ||
| 634 | /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation | 635 | /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation |
| 635 | /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). | 636 | /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). |
| 637 | + #[allow(clippy::too_many_arguments)] | ||
| 636 | pub(crate) fn build_ref_lists( | 638 | pub(crate) fn build_ref_lists( |
| 637 | &self, | 639 | &self, |
| 638 | slice_type: SliceType, | 640 | slice_type: SliceType, |
| @@ -704,7 +706,8 @@ impl Dpb { | |||
| 704 | lists[1].push(i); | 706 | lists[1].push(i); |
| 705 | } | 707 | } |
| 706 | // 8.2.4.2.3 step 3. | 708 | // 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] | ||
| 708 | { | 711 | { |
| 709 | lists[1].entries.swap(0, 1); | 712 | lists[1].entries.swap(0, 1); |
| 710 | } | 713 | } |
| @@ -938,7 +941,12 @@ impl Dpb { | |||
| 938 | } | 941 | } |
| 939 | 942 | ||
| 940 | /// Adaptive marking (clause 8.2.5.4). | 943 | /// 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<()> { | ||
| 942 | let curr_pic_num = info.frame_num as i32; | 950 | let curr_pic_num = info.frame_num as i32; |
| 943 | for op in &m.mmcos { | 951 | for op in &m.mmcos { |
| 944 | match op.op { | 952 | match op.op { |
| @@ -1115,9 +1123,8 @@ mod tests { | |||
| 1115 | fn extend_borders_replicates_edges() { | 1123 | fn extend_borders_replicates_edges() { |
| 1116 | let mut p = plane(6, 5); | 1124 | let mut p = plane(6, 5); |
| 1117 | p.extend_borders(); | 1125 | p.extend_borders(); |
| 1118 | - let at = |x: i32, y: i32| -> u8 { | 1126 | + let at = |
| 1119 | - p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] | 1127 | + |x: i32, y: i32| -> u8 { p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] }; |
| 1120 | - }; | ||
| 1121 | for y in -4..9i32 { | 1128 | for y in -4..9i32 { |
| 1122 | for x in -4..10i32 { | 1129 | for x in -4..10i32 { |
| 1123 | let cx = x.clamp(0, 5) as usize; | 1130 | let cx = x.clamp(0, 5) as usize; |
| @@ -1200,9 +1207,24 @@ mod tests { | |||
| 1200 | fn poc_type_2_is_twice_the_frame_number() { | 1207 | fn poc_type_2_is_twice_the_frame_number() { |
| 1201 | let sps = sps_for(2); | 1208 | let sps = sps_for(2); |
| 1202 | let dpb = Dpb::default(); | 1209 | let dpb = Dpb::default(); |
| 1203 | - assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); | 1210 | + assert_eq!( |
| 1204 | - assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, true, false)).unwrap().value, 6); | 1211 | + dpb.picture_order_count(&sps, &info(0, 0, true, true)) |
| 1205 | - assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, false, false)).unwrap().value, 5); | 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 | + ); | ||
| 1206 | } | 1228 | } |
| 1207 | 1229 | ||
| 1208 | /// Type 1 walks the offset_for_ref_frame cycle. | 1230 | /// Type 1 walks the offset_for_ref_frame cycle. |
| @@ -1211,9 +1233,24 @@ mod tests { | |||
| 1211 | let sps = sps_for(1); | 1233 | let sps = sps_for(1); |
| 1212 | let dpb = Dpb::default(); | 1234 | let dpb = Dpb::default(); |
| 1213 | // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n. | 1235 | // 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); | 1236 | + assert_eq!( |
| 1215 | - assert_eq!(dpb.picture_order_count(&sps, &info(1, 0, true, false)).unwrap().value, 2); | 1237 | + dpb.picture_order_count(&sps, &info(0, 0, true, true)) |
| 1216 | - assert_eq!(dpb.picture_order_count(&sps, &info(4, 0, true, false)).unwrap().value, 8); | 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 | + ); | ||
| 1217 | } | 1254 | } |
| 1218 | 1255 | ||
| 1219 | fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { | 1256 | fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { |
| @@ -1259,7 +1296,9 @@ mod tests { | |||
| 1259 | .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) | 1296 | .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) |
| 1260 | .unwrap(); | 1297 | .unwrap(); |
| 1261 | let poc = |l: &RefList| -> Vec<i32> { | 1298 | 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() | ||
| 1263 | }; | 1302 | }; |
| 1264 | assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); | 1303 | assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); |
| 1265 | assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); | 1304 | assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); |
| @@ -1277,8 +1316,12 @@ mod tests { | |||
| 1277 | let lists = dpb | 1316 | let lists = dpb |
| 1278 | .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) | 1317 | .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) |
| 1279 | .unwrap(); | 1318 | .unwrap(); |
| 1280 | - let l0: Vec<i32> = (0..2).map(|i| dpb.frames[lists[0].get(i).unwrap()].poc).collect(); | 1319 | + let l0: Vec<i32> = (0..2) |
| 1281 | - let l1: Vec<i32> = (0..2).map(|i| dpb.frames[lists[1].get(i).unwrap()].poc).collect(); | 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(); | ||
| 1282 | assert_eq!(l0, vec![2, 0]); | 1325 | assert_eq!(l0, vec![2, 0]); |
| 1283 | assert_eq!(l1, vec![0, 2], "identical lists swap"); | 1326 | assert_eq!(l1, vec![0, 2], "identical lists swap"); |
| 1284 | } | 1327 | } |
crates/ec-h264/src/inter.rsmodified+31 -14
| @@ -82,7 +82,15 @@ const TMP_W: usize = 16 + 5; | |||
| 82 | /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose | 82 | /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose |
| 83 | /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter | 83 | /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter |
| 84 | /// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. | 84 | /// 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 | +) { | ||
| 86 | let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); | 94 | let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); |
| 87 | let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); | 95 | let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); |
| 88 | let yi = clamp_origin(y + (mv[1] as i32 >> 2), h, r.height, r.pad, 2, 3); | 96 | 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, | |||
| 149 | for row in 0..h { | 157 | for row in 0..h { |
| 150 | for col in 0..w { | 158 | for col in 0..w { |
| 151 | let i = row * w + col; | 159 | let i = row * w + col; |
| 152 | - let g = |dx: i32, dy: i32| r.data[base + (row as i32 + dy) as usize * stride | 160 | + let g = |dx: i32, dy: i32| { |
| 153 | - + (col as i32 + dx) as usize]; | 161 | + r.data[base + (row as i32 + dy) as usize * stride + (col as i32 + dx) as usize] |
| 162 | + }; | ||
| 154 | out[i] = match (fx, fy) { | 163 | out[i] = match (fx, fy) { |
| 155 | // Table 8-12, quarter positions on the integer rows/columns. | 164 | // Table 8-12, quarter positions on the integer rows/columns. |
| 156 | (1, 0) => avg(g(0, 0), bb[i]), | 165 | (1, 0) => avg(g(0, 0), bb[i]), |
| @@ -185,12 +194,7 @@ pub(crate) fn mc_chroma( | |||
| 185 | let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); | 194 | let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); |
| 186 | let stride = r.stride; | 195 | let stride = r.stride; |
| 187 | let base = r.at(xi, yi); | 196 | let base = r.at(xi, yi); |
| 188 | - let (wa, wb, wc, wd) = ( | 197 | + let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); |
| 189 | - (8 - fx) * (8 - fy), | ||
| 190 | - fx * (8 - fy), | ||
| 191 | - (8 - fx) * fy, | ||
| 192 | - fx * fy, | ||
| 193 | - ); | ||
| 194 | for row in 0..h { | 198 | for row in 0..h { |
| 195 | let src = base + row * stride; | 199 | let src = base + row * stride; |
| 196 | for col in 0..w { | 200 | for col in 0..w { |
| @@ -311,7 +315,14 @@ mod tests { | |||
| 311 | (data, stride, origin) | 315 | (data, stride, origin) |
| 312 | } | 316 | } |
| 313 | 317 | ||
| 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<'_> { | ||
| 315 | RefPlane { | 326 | RefPlane { |
| 316 | data, | 327 | data, |
| 317 | stride, | 328 | stride, |
| @@ -324,6 +335,7 @@ mod tests { | |||
| 324 | 335 | ||
| 325 | /// The spec's clipped, per-sample definition of the same interpolation, | 336 | /// The spec's clipped, per-sample definition of the same interpolation, |
| 326 | /// written straight from Equations 8-239 to 8-261 with no padding tricks. | 337 | /// written straight from Equations 8-239 to 8-261 with no padding tricks. |
| 338 | + #[allow(clippy::too_many_arguments)] | ||
| 327 | fn spec_luma( | 339 | fn spec_luma( |
| 328 | pic: &[u8], | 340 | pic: &[u8], |
| 329 | stride: usize, | 341 | stride: usize, |
| @@ -396,15 +408,20 @@ mod tests { | |||
| 396 | let r = plane(&data, stride, origin, w, h, pad); | 408 | let r = plane(&data, stride, origin, w, h, pad); |
| 397 | let mut ours = [0u8; 256]; | 409 | let mut ours = [0u8; 256]; |
| 398 | let mut theirs = [0u8; 256]; | 410 | 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 | + ] { | ||
| 400 | for fy in 0..4i16 { | 419 | for fy in 0..4i16 { |
| 401 | for fx in 0..4i16 { | 420 | for fx in 0..4i16 { |
| 402 | for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { | 421 | for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { |
| 403 | let mv = [fx - 20 * 4, fy + 12]; | 422 | let mv = [fx - 20 * 4, fy + 12]; |
| 404 | mc_luma(&r, px, py, mv, pw, ph, &mut ours); | 423 | mc_luma(&r, px, py, mv, pw, ph, &mut ours); |
| 405 | - spec_luma( | 424 | + spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs); |
| 406 | - &data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs, | ||
| 407 | - ); | ||
| 408 | assert_eq!( | 425 | assert_eq!( |
| 409 | ours[..pw * ph], | 426 | ours[..pw * ph], |
| 410 | theirs[..pw * ph], | 427 | theirs[..pw * ph], |
crates/ec-h264/src/mv.rsmodified+31 -9
| @@ -216,7 +216,14 @@ impl MvCtx { | |||
| 216 | /// Neighbours A, B and C of a partition whose top-left 4x4 block is at | 216 | /// Neighbours A, B and C of a partition whose top-left 4x4 block is at |
| 217 | /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks | 217 | /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks |
| 218 | /// (clause 6.4.11.7, with the C-to-D substitution of 8-214). | 218 | /// (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] { | ||
| 220 | let bx = (self.mb_x * 4 + px) as i32; | 227 | let bx = (self.mb_x * 4 + px) as i32; |
| 221 | let by = (self.mb_y * 4 + py) as i32; | 228 | let by = (self.mb_y * 4 + py) as i32; |
| 222 | let a = self.at(pic, bx - 1, by, list); | 229 | let a = self.at(pic, bx - 1, by, list); |
| @@ -239,7 +246,13 @@ fn median(a: i16, b: i16, c: i16) -> i16 { | |||
| 239 | /// | 246 | /// |
| 240 | /// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only | 247 | /// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only |
| 241 | /// select those shortcuts; `part` is the macroblock partition index. | 248 | /// 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] { | ||
| 243 | let [a, mut b, mut c] = *n; | 256 | let [a, mut b, mut c] = *n; |
| 244 | match (part_w, part_h, part) { | 257 | match (part_w, part_h, part) { |
| 245 | (4, 2, 0) if b.ref_idx == ref_idx => return b.mv, | 258 | (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) { | |||
| 318 | /// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the | 331 | /// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the |
| 319 | /// context thresholds of 9.3.3.1.1.7 can distinguish. | 332 | /// context thresholds of 9.3.3.1.1.7 can distinguish. |
| 320 | #[inline] | 333 | #[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 | +) { | ||
| 322 | let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; | 343 | let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; |
| 323 | let e = &mut pic.mvd_abs[idx]; | 344 | let e = &mut pic.mvd_abs[idx]; |
| 324 | e[list * 2] = mvd[0].unsigned_abs().min(127) as u8; | 345 | e[list * 2] = mvd[0].unsigned_abs().min(127) as u8; |
| @@ -379,11 +400,7 @@ mod tests { | |||
| 379 | use super::*; | 400 | use super::*; |
| 380 | 401 | ||
| 381 | fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb { | 402 | fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb { |
| 382 | - Nb { | 403 | + Nb { avail, mv, ref_idx } |
| 383 | - avail, | ||
| 384 | - mv, | ||
| 385 | - ref_idx, | ||
| 386 | - } | ||
| 387 | } | 404 | } |
| 388 | 405 | ||
| 389 | /// With exactly one neighbour on the same reference picture, that | 406 | /// With exactly one neighbour on the same reference picture, that |
| @@ -413,7 +430,11 @@ mod tests { | |||
| 413 | /// median into A (8-207 to 8-210). | 430 | /// median into A (8-207 to 8-210). |
| 414 | #[test] | 431 | #[test] |
| 415 | fn unavailable_b_and_c_fall_back_to_a() { | 432 | 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 | + ]; | ||
| 417 | assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]); | 438 | assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]); |
| 418 | // With refIdx 3 the single-match rule fires first, same answer. | 439 | // With refIdx 3 the single-match rule fires first, same answer. |
| 419 | assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]); | 440 | assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]); |
| @@ -449,6 +470,7 @@ mod tests { | |||
| 449 | assert_eq!(B_SHAPES[0].pred[0], Pred::Direct); | 470 | assert_eq!(B_SHAPES[0].pred[0], Pred::Direct); |
| 450 | assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi)); | 471 | assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi)); |
| 451 | // The 16x8 / 8x16 pairs alternate, starting at mb_type 4. | 472 | // The 16x8 / 8x16 pairs alternate, starting at mb_type 4. |
| 473 | + #[allow(clippy::needless_range_loop)] | ||
| 452 | for t in 4..22 { | 474 | for t in 4..22 { |
| 453 | let s = B_SHAPES[t]; | 475 | let s = B_SHAPES[t]; |
| 454 | assert_eq!(s.parts, 2, "mb_type {t}"); | 476 | 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> { | |||
| 179 | let mut dec = Decoder::new(); | 179 | let mut dec = Decoder::new(); |
| 180 | let mut frames = Vec::new(); | 180 | let mut frames = Vec::new(); |
| 181 | for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | 181 | for nal in ec_h264_syntax::AnnexBIter::new(bytes) { |
| 182 | - match dec.push_nal(nal)? { | 182 | + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { |
| 183 | - NalOutcome::PictureBoundary => { | 183 | + dec.end_picture()?; |
| 184 | - dec.end_picture()?; | 184 | + dec.push_nal(nal)?; |
| 185 | - dec.push_nal(nal)?; | ||
| 186 | - } | ||
| 187 | - _ => {} | ||
| 188 | } | 185 | } |
| 189 | while let Some(f) = dec.next_frame() { | 186 | while let Some(f) = dec.next_frame() { |
| 190 | frames.push(frame_bytes(&f)); | 187 | frames.push(frame_bytes(&f)); |
| @@ -199,13 +196,8 @@ fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> { | |||
| 199 | 196 | ||
| 200 | /// Every frame ffmpeg decodes from `stream`, as raw I420. | 197 | /// Every frame ffmpeg decodes from `stream`, as raw I420. |
| 201 | fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> { | 198 | fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> { |
| 202 | - let mut cmd = Command::new("ffmpeg"); | 199 | + let out = Command::new("ffmpeg") |
| 203 | - cmd.args(["-v", "error"]); | 200 | + .args(["-v", "error", "-i"]) |
| 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") | ||
| 209 | .arg(stream) | 201 | .arg(stream) |
| 210 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | 202 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 211 | .output() | 203 | .output() |
| @@ -268,8 +260,7 @@ fn compare_sequence(stream: &Path) -> Result<usize, String> { | |||
| 268 | let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; | 260 | let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; |
| 269 | let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; | 261 | let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; |
| 270 | let first = ours.first().ok_or("no frames decoded")?; | 262 | let first = ours.first().ok_or("no frames decoded")?; |
| 271 | - let theirs = | 263 | + let theirs = ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; |
| 272 | - ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; | ||
| 273 | if ours.len() != theirs.len() { | 264 | if ours.len() != theirs.len() { |
| 274 | return Err(format!( | 265 | return Err(format!( |
| 275 | "{} frames decoded, ffmpeg gave {}", | 266 | "{} frames decoded, ffmpeg gave {}", |
| @@ -398,7 +389,7 @@ fn steady_state_decode_loop_zero_alloc() { | |||
| 398 | }; | 389 | }; |
| 399 | let bytes = std::fs::read(stream).unwrap(); | 390 | let bytes = std::fs::read(stream).unwrap(); |
| 400 | let mut dec = Decoder::new(); | 391 | let mut dec = Decoder::new(); |
| 401 | - let mut drive = |dec: &mut Decoder, count: bool| -> usize { | 392 | + let drive = |dec: &mut Decoder, count: bool| -> usize { |
| 402 | let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); | 393 | let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); |
| 403 | let mut frames = 0usize; | 394 | let mut frames = 0usize; |
| 404 | for nal in &nals { | 395 | for nal in &nals { |
| @@ -435,8 +426,14 @@ fn steady_state_decode_loop_zero_alloc() { | |||
| 435 | ALLOCS.store(0, Ordering::SeqCst); | 426 | ALLOCS.store(0, Ordering::SeqCst); |
| 436 | let again = drive(&mut dec, true); | 427 | let again = drive(&mut dec, true); |
| 437 | let n = ALLOCS.load(Ordering::SeqCst); | 428 | let n = ALLOCS.load(Ordering::SeqCst); |
| 438 | - assert_eq!(again, warm, "{name}: frame count changed on the second pass"); | 429 | + assert_eq!( |
| 439 | - assert_eq!(n, 0, "{name}: steady-state slice decode allocated {n} times"); | 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 | + ); | ||
| 440 | } | 437 | } |
| 441 | 438 | ||
| 442 | // Sanity: the counter is alive — emitting a frame does allocate. | 439 | // Sanity: the counter is alive — emitting a frame does allocate. |
| @@ -454,9 +451,13 @@ fn steady_state_decode_loop_zero_alloc() { | |||
| 454 | ); | 451 | ); |
| 455 | } | 452 | } |
| 456 | 453 | ||
| 457 | -/// Decode-rate measurement: ns per macroblock and Mpx/s over the first IDR, | 454 | +/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf |
| 458 | -/// printed for the perf report. Run with `--nocapture` to see it. Uses the | 455 | +/// report. Run with `--nocapture` to see it. Uses the steady-state path |
| 459 | -/// steady-state path (buffers warm) like a playback loop would. | 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. | ||
| 460 | #[test] | 461 | #[test] |
| 461 | fn ns_per_macroblock_measurement() { | 462 | fn ns_per_macroblock_measurement() { |
| 462 | let base = vectors_dir(); | 463 | let base = vectors_dir(); |
| @@ -501,6 +502,40 @@ fn ns_per_macroblock_measurement() { | |||
| 501 | (intra IDR, single thread, deblock included, output copy excluded)" | 502 | (intra IDR, single thread, deblock included, output copy excluded)" |
| 502 | ); | 503 | ); |
| 503 | } | 504 | } |
| 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 | + } | ||
| 504 | } | 539 | } |
| 505 | 540 | ||
| 506 | /// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte | 541 | /// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte |
| @@ -1027,89 +1062,6 @@ fn p_only_gop_matches_ffmpeg_every_frame() { | |||
| 1027 | assert!(failures.is_empty(), "{failures:#?}"); | 1062 | assert!(failures.is_empty(), "{failures:#?}"); |
| 1028 | } | 1063 | } |
| 1029 | 1064 | ||
| 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 | - | ||
| 1113 | /// JVT conformance, every frame of every vector: our display-order output | 1065 | /// JVT conformance, every frame of every vector: our display-order output |
| 1114 | /// against the reference decoder YUV that ships with the vector. | 1066 | /// against the reference decoder YUV that ships with the vector. |
| 1115 | /// | 1067 | /// |
| @@ -1141,7 +1093,10 @@ fn jvt_full_sequence_bit_exact() { | |||
| 1141 | Ok(frames) => { | 1093 | Ok(frames) => { |
| 1142 | let len = frames[0].len(); | 1094 | let len = frames[0].len(); |
| 1143 | let Some(ref_path) = find_ref_yuv(&dir) else { | 1095 | 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 | + )); | ||
| 1145 | continue; | 1100 | continue; |
| 1146 | }; | 1101 | }; |
| 1147 | let reference = std::fs::read(&ref_path).unwrap(); | 1102 | let reference = std::fs::read(&ref_path).unwrap(); |
| @@ -1159,18 +1114,27 @@ fn jvt_full_sequence_bit_exact() { | |||
| 1159 | match bad { | 1114 | match bad { |
| 1160 | None if frames.len() == want => { | 1115 | None if frames.len() == want => { |
| 1161 | passed += 1; | 1116 | 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 | + )); | ||
| 1163 | } | 1121 | } |
| 1164 | None => { | 1122 | None => { |
| 1165 | failed.push(format!( | 1123 | failed.push(format!( |
| 1166 | "{name}: {} frames decoded, reference has {want}", | 1124 | "{name}: {} frames decoded, reference has {want}", |
| 1167 | frames.len() | 1125 | frames.len() |
| 1168 | )); | 1126 | )); |
| 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 | + )); | ||
| 1170 | } | 1131 | } |
| 1171 | Some((i, pos)) => { | 1132 | Some((i, pos)) => { |
| 1172 | failed.push(format!("{name}: frame {i} differs at byte {pos}")); | 1133 | 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 | + )); | ||
| 1174 | } | 1138 | } |
| 1175 | } | 1139 | } |
| 1176 | } | 1140 | } |
| @@ -1257,18 +1221,36 @@ fn b_pictures_match_ffmpeg_every_frame() { | |||
| 1257 | } | 1221 | } |
| 1258 | let dir = scratch("b-gop"); | 1222 | let dir = scratch("b-gop"); |
| 1259 | let cases: &[(&str, &[&str])] = &[ | 1223 | let cases: &[(&str, &[&str])] = &[ |
| 1260 | - ("spatial", &["-x264-params", "bframes=3:b-adapt=0:direct=spatial:weightp=0"]), | 1224 | + ( |
| 1261 | - ("temporal", &["-x264-params", "bframes=3:b-adapt=0:direct=temporal:weightp=0"]), | 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 | + ), | ||
| 1262 | // B pictures used as references, which makes the buffer hold pictures | 1238 | // B pictures used as references, which makes the buffer hold pictures |
| 1263 | // that are neither the newest nor the oldest. | 1239 | // that are neither the newest nor the oldest. |
| 1264 | ( | 1240 | ( |
| 1265 | "pyramid", | 1241 | "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 | + ], | ||
| 1267 | ), | 1246 | ), |
| 1268 | // Weighted prediction on: explicit for P, implicit for B. | 1247 | // Weighted prediction on: explicit for P, implicit for B. |
| 1269 | ( | 1248 | ( |
| 1270 | "weighted", | 1249 | "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 | + ], | ||
| 1272 | ), | 1254 | ), |
| 1273 | ]; | 1255 | ]; |
| 1274 | let mut failures = Vec::new(); | 1256 | let mut failures = Vec::new(); |
| @@ -1356,17 +1338,17 @@ fn output_is_display_order_and_the_reorder_is_real() { | |||
| 1356 | "decode-order frame {i} is not in the display-order output" | 1338 | "decode-order frame {i} is not in the display-order output" |
| 1357 | ); | 1339 | ); |
| 1358 | } | 1340 | } |
| 1359 | - let moved = decode | 1341 | + let moved = decode.iter().zip(&display).filter(|(a, b)| a != b).count(); |
| 1360 | - .iter() | ||
| 1361 | - .zip(&display) | ||
| 1362 | - .filter(|(a, b)| a != b) | ||
| 1363 | - .count(); | ||
| 1364 | assert!( | 1342 | assert!( |
| 1365 | moved > 0, | 1343 | moved > 0, |
| 1366 | "decode order and display order are identical: the stream does not \ | 1344 | "decode order and display order are identical: the stream does not \ |
| 1367 | reorder, so this test proves nothing" | 1345 | reorder, so this test proves nothing" |
| 1368 | ); | 1346 | ); |
| 1369 | - eprintln!("{} of {} frames move under reordering", moved, display.len()); | 1347 | + eprintln!( |
| 1348 | + "{} of {} frames move under reordering", | ||
| 1349 | + moved, | ||
| 1350 | + display.len() | ||
| 1351 | + ); | ||
| 1370 | } | 1352 | } |
| 1371 | 1353 | ||
| 1372 | /// A gap in frame_num decodes instead of stalling (clause 8.2.5.2). | 1354 | /// 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() { | |||
| 1475 | None => failures.push(format!("{tag}: ffmpeg cannot encode")), | 1457 | None => failures.push(format!("{tag}: ffmpeg cannot encode")), |
| 1476 | } | 1458 | } |
| 1477 | } | 1459 | } |
| 1478 | - assert!(checked >= 40, "too few {coder} quantisers exercised: {checked}"); | 1460 | + assert!( |
| 1461 | + checked >= 40, | ||
| 1462 | + "too few {coder} quantisers exercised: {checked}" | ||
| 1463 | + ); | ||
| 1479 | eprintln!("{coder}: {checked} quantisers bit-exact over a GOP with motion"); | 1464 | eprintln!("{coder}: {checked} quantisers bit-exact over a GOP with motion"); |
| 1480 | } | 1465 | } |
| 1481 | let _ = std::fs::remove_dir_all(&dir); | 1466 | let _ = std::fs::remove_dir_all(&dir); |
| @@ -1498,12 +1483,20 @@ fn geometry_with_motion_matches_ffmpeg() { | |||
| 1498 | // Neighbour availability stops at every slice boundary, and a motion | 1483 | // Neighbour availability stops at every slice boundary, and a motion |
| 1499 | // vector predictor at one sees no partition across it. | 1484 | // vector predictor at one sees no partition across it. |
| 1500 | ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]), | 1485 | ("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 | + ), | ||
| 1502 | // One macroblock wide: every spatial neighbour is unavailable, which | 1491 | // One macroblock wide: every spatial neighbour is unavailable, which |
| 1503 | // is where the reference index of a missing partition matters most. | 1492 | // is where the reference index of a missing partition matters most. |
| 1504 | ("tiny", "16x16", &["bframes=2:b-adapt=0"]), | 1493 | ("tiny", "16x16", &["bframes=2:b-adapt=0"]), |
| 1505 | // Many references, so the list is long and reordering is real work. | 1494 | // 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 | + ), | ||
| 1507 | ]; | 1500 | ]; |
| 1508 | let mut table = String::new(); | 1501 | let mut table = String::new(); |
| 1509 | let mut failures = Vec::new(); | 1502 | let mut failures = Vec::new(); |
| @@ -1522,7 +1515,9 @@ fn geometry_with_motion_matches_ffmpeg() { | |||
| 1522 | let name = format!("{coder}-{tag}"); | 1515 | let name = format!("{coder}-{tag}"); |
| 1523 | match x264_encode_gop(&dir, &name, size, 10, &extra) { | 1516 | match x264_encode_gop(&dir, &name, size, 10, &extra) { |
| 1524 | Some(stream) => match compare_sequence(&stream) { | 1517 | 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 | + } | ||
| 1526 | Err(e) => { | 1521 | Err(e) => { |
| 1527 | table.push_str(&format!("{name:<14} {size:<10} {e}\n")); | 1522 | table.push_str(&format!("{name:<14} {size:<10} {e}\n")); |
| 1528 | failures.push(format!("{name}: {e}")); | 1523 | failures.push(format!("{name}: {e}")); |
| @@ -1754,7 +1749,8 @@ fn real_library_streams_match_ffmpeg() { | |||
| 1754 | eprintln!("SKIP: ffmpeg not on PATH"); | 1749 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 1755 | return; | 1750 | return; |
| 1756 | } | 1751 | } |
| 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"); | ||
| 1758 | let Ok(text) = std::fs::read_to_string(&manifest) else { | 1754 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 1759 | eprintln!("SKIP: {} missing", manifest.display()); | 1755 | eprintln!("SKIP: {} missing", manifest.display()); |
| 1760 | return; | 1756 | return; |
| @@ -1825,11 +1821,15 @@ fn real_library_streams_match_ffmpeg() { | |||
| 1825 | } | 1821 | } |
| 1826 | Err(e) if e.contains("unsupported") => { | 1822 | Err(e) if e.contains("unsupported") => { |
| 1827 | refused += 1; | 1823 | 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 | + )); | ||
| 1829 | } | 1827 | } |
| 1830 | Err(e) => { | 1828 | Err(e) => { |
| 1831 | failures.push(format!("{name}: {e}")); | 1829 | 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 | + )); | ||
| 1833 | } | 1833 | } |
| 1834 | } | 1834 | } |
| 1835 | } | 1835 | } |
| @@ -1842,3 +1842,107 @@ fn real_library_streams_match_ffmpeg() { | |||
| 1842 | "only {decoded} real files swept end to end; the sweep is the point" | 1842 | "only {decoded} real files swept end to end; the sweep is the point" |
| 1843 | ); | 1843 | ); |
| 1844 | } | 1844 | } |
| 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 | +} | ||