diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 621264b6..ae083e85 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -31,17 +31,18 @@ use ec_h264_syntax::{ use crate::deblock::{chroma_qp, deblock_picture}; use crate::dpb::{ - BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE, + BLK_DIRECT, BLK_SKIP, BOTTOM, CODED_AFRM, Dpb, FRAME, Mark, NO_SLICE, PicInfo, PicPlane, Picture, RefList, SliceParams, TOP, }; use crate::entropy::{ BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, MbaffA, }; +use crate::direct::{predict_direct, predict_direct_8x8}; use crate::inter::Weights; use crate::mbaff::{self, MbPos}; use crate::mv::{ - B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd, + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, }; use crate::pred::{ @@ -1582,48 +1583,48 @@ impl Geo { /// Mutable per-slice decode state. pub(crate) struct SliceCtx { - slice_id: u16, - slice_type: SliceType, - qp: i32, - cb_qp_offset: i32, - cr_qp_offset: i32, + pub(crate) slice_id: u16, + pub(crate) slice_type: SliceType, + pub(crate) qp: i32, + pub(crate) cb_qp_offset: i32, + pub(crate) cr_qp_offset: i32, /// Chroma rows per macroblock: 8 (4:2:0) or 16 (4:2:2). - cmb_h: usize, + pub(crate) cmb_h: usize, /// ChromaArrayType of the picture being decoded. pub(crate) cat: u8, - transform_8x8_mode: bool, - constrained_intra_pred: bool, + pub(crate) transform_8x8_mode: bool, + pub(crate) constrained_intra_pred: bool, /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5). - qp_delta_inc: u8, + pub(crate) qp_delta_inc: u8, /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices. - lists: [RefList; 2], - num_ref_idx: [usize; 2], - direct_spatial: bool, - direct_8x8_inference: bool, - weighted_pred: bool, - weighted_bipred_idc: u8, - weights: Option, + pub(crate) lists: [RefList; 2], + pub(crate) num_ref_idx: [usize; 2], + pub(crate) direct_spatial: bool, + pub(crate) direct_8x8_inference: bool, + pub(crate) weighted_pred: bool, + pub(crate) weighted_bipred_idc: u8, + pub(crate) weights: Option, /// `PicOrderCnt( CurrPic )`. - poc: i32, + pub(crate) poc: i32, /// `TopFieldOrderCnt` and `BottomFieldOrderCnt` of the current picture. - fpoc: [i32; 2], + pub(crate) fpoc: [i32; 2], /// Structure of the picture being decoded: [`FRAME`], [`TOP`] or [`BOTTOM`]. - structure: u8, + pub(crate) structure: u8, /// Parity of the macroblock being decoded when it is a field macroblock /// ([`TOP`] or [`BOTTOM`]), [`FRAME`] for a frame macroblock. In a field /// picture this is the picture's own parity. - mb_parity: u8, + pub(crate) mb_parity: u8, /// Where the macroblock being decoded sits when the picture is an MBAFF /// frame (`pos.active`); inert otherwise. - pos: MbPos, + pub(crate) pos: MbPos, } impl SliceCtx { /// `PicOrderCnt` of the current picture, or of the field of the current /// macroblock's parity for a field macroblock of an MBAFF frame (8.4.1.2.3, 8.4.2.3.1). #[inline] - fn cur_poc(&self) -> i32 { + pub(crate) fn cur_poc(&self) -> i32 { if self.pos.active && self.pos.field { self.fpoc[usize::from(self.mb_parity == BOTTOM)] } else { @@ -1631,7 +1632,7 @@ impl SliceCtx { } } - fn is_b(&self) -> bool { + pub(crate) fn is_b(&self) -> bool { self.slice_type == SliceType::B } @@ -1663,7 +1664,7 @@ impl SliceCtx { /// [`SliceCtx::reference`] for a field macroblock of an MBAFF frame. #[inline(never)] - fn field_mb_reference<'a, S: Sample>( + pub(crate) fn field_mb_reference<'a, S: Sample>( &self, refs: &'a [Picture], list: usize, @@ -2094,13 +2095,13 @@ fn build_mb_ctx( /// Motion data parsed for one macroblock, before prediction derivation. #[derive(Clone, Copy)] -struct MbMotion { +pub(crate) struct MbMotion { /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock. - sub: [SubShape; 4], + pub(crate) sub: [SubShape; 4], /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list. - ref_idx: [[i8; 4]; 2], + pub(crate) ref_idx: [[i8; 4]; 2], /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position. - mvd: [[[i16; 2]; 16]; 2], + pub(crate) mvd: [[[i16; 2]; 16]; 2], } /// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp` @@ -3047,384 +3048,6 @@ fn predict_p_skip( ) } -/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. -fn predict_direct( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - skip: bool, -) -> Result<()> { - for quad in 0..4 { - direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; - } - Ok(()) -} - -/// B_Direct_8x8 for one 8x8 sub-macroblock. -fn predict_direct_8x8( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - part: usize, -) -> Result<()> { - direct_quadrant(pic, refs, ctx, mvc, part, false) -} - -/// One 8x8 quadrant of a direct-mode macroblock. With -/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its -/// outer corner 4x4 block; without it each 4x4 block is derived on its own. -fn direct_quadrant( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - quad: usize, - skip: bool, -) -> Result<()> { - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); - let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; - if ctx.direct_8x8_inference { - // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own - // outer corner of the macroblock. - let corner = (quad % 2 * 3, quad / 2 * 3); - let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; - for dy in 0..2 { - for dx in 0..2 { - write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); - } - } - S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) - } else { - // Each 4x4 block derives its own motion, but they usually come out - // equal: interpolation is position-invariant, so one 8x8 compensation - // of the shared vector produces the same samples as four 4x4 ones and - // pays the per-partition setup once instead of four times. - let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4]; - for dy in 0..2 { - for dx in 0..2 { - let (px, py) = (qx + dx, qy + dy); - let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; - write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); - motion[dy * 2 + dx] = (mv, ref_idx); - } - } - if motion.iter().all(|m| *m == motion[0]) { - let (mv, ref_idx) = motion[0]; - return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx); - } - for dy in 0..2 { - for dx in 0..2 { - let (mv, ref_idx) = motion[dy * 2 + dx]; - S::compensate( - pic, - refs, - ctx, - mb_x, - mb_y, - qx + dx, - qy + dy, - 1, - 1, - mv, - ref_idx, - )?; - } - } - Ok(()) - } -} - -/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture -/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). -#[allow(clippy::type_complexity)] -fn direct_block( - pic: &Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &MvCtx, - at: (usize, usize), -) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { - // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or - // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol — - // an index into the co-located picture's own reference list, not ours. - let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at); - let col = ctx.reference(refs, 1, 0); - - if ctx.direct_spatial { - // Reference indices from the macroblock's own neighbours, once. - let mut ref_idx = [-1i8; 2]; - let mut mvp = [[0i16; 2]; 2]; - for list in 0..2 { - let n = mvc.neighbours(pic, 0, 0, 4, list); - ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); - mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); - } - let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; - if zero_prediction { - ref_idx = [0, 0]; - } - // colZeroFlag (8.4.1.2.2): the co-located block sits still on a - // short-term picture, referencing that picture's own list entry 0. The - // index is the one belonging to the list 8.4.1.2.1 picked — reading - // "either list is 0" instead lets a bi-predicted co-located block whose - // list 1 index happens to be 0 zero a motion vector it must not, which - // only shows on a B picture used as the co-located one. - let col_short = col.is_some_and(|c| c.mark == Mark::Short); - let col_zero = col_short - && col_ref_id >= 0 - && col_ref_idx == 0 - && (-1..=1).contains(&col_mv[0]) - && (-1..=1).contains(&col_mv[1]); - let mut mv = [[0i16; 2]; 2]; - let mut ref_id = [-1i32; 2]; - for list in 0..2 { - if ref_idx[list] < 0 { - continue; - } - ref_id[list] = ctx - .reference(refs, list, ref_idx[list]) - .map(|p| p.id) - .unwrap_or(-1); - if zero_prediction || (ref_idx[list] == 0 && col_zero) { - mv[list] = [0; 2]; - } else { - mv[list] = mvp[list]; - } - } - return Ok((mv, ref_idx, ref_id)); - } - - // Temporal direct (8.4.1.2.3). - let ref_idx0 = if col_ref_id < 0 { - 0 - } else { - map_col_to_list0(ctx, refs, col_ref_id, vscale) - }; - let col_mv = match vscale { - // 8-195 and 8-196: "/" truncates toward zero. - COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2], - COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)], - _ => col_mv, - }; - let pic0 = ctx.reference(refs, 0, ref_idx0); - let pic1 = ctx.reference(refs, 1, 0); - let ref_id = [ - pic0.map(|p| p.id).unwrap_or(-1), - pic1.map(|p| p.id).unwrap_or(-1), - ]; - let (Some(p0), Some(p1)) = (pic0, pic1) else { - return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); - }; - let td = (p1.poc - p0.poc).clamp(-128, 127); - if p0.mark == Mark::Long || td == 0 { - return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); - } - let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127); - let tx = (16384 + (td / 2).abs()) / td; - let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); - let mv0 = [ - ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, - ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, - ]; - let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; - Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) -} - -/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the -/// picture the co-located block referenced. -fn map_col_to_list0( - ctx: &SliceCtx, - refs: &[Picture], - col_ref_id: i32, - vscale: u8, -) -> i8 { - // Picture ids step by 4: a field id is its frame's id + 1 + parity. - let field_mb = ctx.pos.active && ctx.pos.field; - let want = match vscale { - // The field of the referenced frame with the current picture's (or - // macroblock's) parity. - COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity), - // A field macroblock of an MBAFF frame names the field of the frame - // the co-located field macroblock referenced that has its own parity. - _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => { - (col_ref_id & !3) + i32::from(ctx.mb_parity) - } - _ => col_ref_id, - }; - let n = if field_mb { - 2 * ctx.lists[0].len() - } else { - ctx.lists[0].len() - }; - for i in 0..n { - let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| { - if vscale == COL_FLD_TO_FRM { - p.id == col_ref_id & !3 - } else { - p.id == want - } - }); - if hit { - return i as i8; - } - } - 0 -} - -/// Whether a field macroblock of an MBAFF frame whose co-located block is a -/// field macroblock maps the referenced field to the field of the same parity -/// as itself (true) or to that very field (false). -const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false; - -/// `vertMvScale` of 8.4.1.2.1. -const COL_ONE_TO_ONE: u8 = 0; -const COL_FRM_TO_FLD: u8 = 1; -const COL_FLD_TO_FRM: u8 = 2; - -/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame. -#[inline(never)] -fn colocated_mbaff( - ctx: &SliceCtx, - refs: &[Picture], - mvc: &MvCtx, - at: (usize, usize), -) -> (i32, [i16; 2], i8, u8) { - const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); - let Some((k, _)) = ctx.lists[1].get_ref(0) else { - return NONE; - }; - let Some(store) = refs.get(k) else { - return NONE; - }; - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let w = store.mb_w.max(1); - let (c, bx, by, vs) = { - let field_mb = ctx.pos.field; - let bot = mb_y & 1; - let top = mb_y & !1; - // The field of a complementary pair, or of an MBAFF frame's field - // macroblock pair, a frame macroblock takes its co-located block from. - let by_poc = - usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs()); - if store.coding == CODED_FLD { - let p = if field_mb { bot } else { by_poc }; - let Some(f) = store.fields.get(p) else { - return NONE; - }; - if field_mb { - (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE) - } else { - // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8). - let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2; - (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } - } else { - let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0; - match (field_mb, col_field) { - (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), - (false, true) => { - let slot = top + by_poc; - let by = slot * 4 + 2 * bot + at.1 / 2; - (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } - (true, false) => { - let slot = top + at.1 / 2; - let by = slot * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } - (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), - } - } - }; - let idx = by * c.mb_w.max(1) * 4 + bx; - if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { - let list = usize::from(c.ref_id[idx][0] < 0); - ( - c.ref_id[idx][list], - c.mv[idx][list], - c.ref_idx[idx][list], - vs, - ) - } else { - (-1, [0; 2], -1, vs) - } -} - -/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current -/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the -/// identity is -1 for an intra block. -fn colocated( - ctx: &SliceCtx, - refs: &[Picture], - mvc: &MvCtx, - at: (usize, usize), -) -> (i32, [i16; 2], i8, u8) { - const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); - let Some((k, _)) = ctx.lists[1].get_ref(0) else { - return NONE; - }; - let Some(store) = refs.get(k) else { - return NONE; - }; - if ctx.pos.active { - return colocated_mbaff(ctx, refs, mvc, at); - } - let Some(cur) = ctx.reference(refs, 1, 0) else { - return NONE; - }; - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let w = store.mb_w.max(1); - // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the - // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`). - let (c, bx, by, vs) = if ctx.structure != FRAME { - if store.coding == CODED_FLD { - (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) - } else if store.coding == CODED_AFRM { - let top = 2 * mb_y; - if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 { - // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16. - let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } else { - // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag. - let slot = top + usize::from(ctx.structure == BOTTOM); - (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE) - } - } else { - // mbAddrCol1 and yM = (2 * yCol) % 16. - let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } - } else if store.coding == CODED_FLD { - let top = (store.fpoc[0] - ctx.poc).abs(); - let bottom = (store.fpoc[1] - ctx.poc).abs(); - let p = usize::from(top >= bottom); - let Some(f) = store.fields.get(p) else { - return NONE; - }; - // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8). - let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2; - (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } else { - (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) - }; - let idx = by * c.mb_w.max(1) * 4 + bx; - if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { - let list = usize::from(c.ref_id[idx][0] < 0); - ( - c.ref_id[idx][list], - c.mv[idx][list], - c.ref_idx[idx][list], - vs, - ) - } else { - (-1, [0; 2], -1, vs) - } -} - /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), /// including the top-right substitution rule. diff --git a/crates/ec-h264/src/direct.rs b/crates/ec-h264/src/direct.rs new file mode 100644 index 00000000..f9219543 --- /dev/null +++ b/crates/ec-h264/src/direct.rs @@ -0,0 +1,385 @@ +use ec_core::error::Result; + +use crate::decoder::SliceCtx; +use crate::dpb::{BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, FRAME, Mark, Picture}; +use crate::mv::{MvCtx, min_positive, predict_mv, write_block}; +use crate::sample::Sample; + +/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. +pub(crate) fn predict_direct( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + skip: bool, +) -> Result<()> { + for quad in 0..4 { + direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; + } + Ok(()) +} + +/// B_Direct_8x8 for one 8x8 sub-macroblock. +pub(crate) fn predict_direct_8x8( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + part: usize, +) -> Result<()> { + direct_quadrant(pic, refs, ctx, mvc, part, false) +} + +/// One 8x8 quadrant of a direct-mode macroblock. With +/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its +/// outer corner 4x4 block; without it each 4x4 block is derived on its own. +fn direct_quadrant( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + quad: usize, + skip: bool, +) -> Result<()> { + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); + let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; + if ctx.direct_8x8_inference { + // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own + // outer corner of the macroblock. + let corner = (quad % 2 * 3, quad / 2 * 3); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; + for dy in 0..2 { + for dx in 0..2 { + write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); + } + } + S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) + } else { + // Each 4x4 block derives its own motion, but they usually come out + // equal: interpolation is position-invariant, so one 8x8 compensation + // of the shared vector produces the same samples as four 4x4 ones and + // pays the per-partition setup once instead of four times. + let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4]; + for dy in 0..2 { + for dx in 0..2 { + let (px, py) = (qx + dx, qy + dy); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; + write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); + motion[dy * 2 + dx] = (mv, ref_idx); + } + } + if motion.iter().all(|m| *m == motion[0]) { + let (mv, ref_idx) = motion[0]; + return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx); + } + for dy in 0..2 { + for dx in 0..2 { + let (mv, ref_idx) = motion[dy * 2 + dx]; + S::compensate( + pic, + refs, + ctx, + mb_x, + mb_y, + qx + dx, + qy + dy, + 1, + 1, + mv, + ref_idx, + )?; + } + } + Ok(()) + } +} + +/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture +/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). +#[allow(clippy::type_complexity)] +fn direct_block( + pic: &Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &MvCtx, + at: (usize, usize), +) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { + // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or + // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol — + // an index into the co-located picture's own reference list, not ours. + let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at); + let col = ctx.reference(refs, 1, 0); + + if ctx.direct_spatial { + // Reference indices from the macroblock's own neighbours, once. + let mut ref_idx = [-1i8; 2]; + let mut mvp = [[0i16; 2]; 2]; + for list in 0..2 { + let n = mvc.neighbours(pic, 0, 0, 4, list); + ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); + mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); + } + let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; + if zero_prediction { + ref_idx = [0, 0]; + } + // colZeroFlag (8.4.1.2.2): the co-located block sits still on a + // short-term picture, referencing that picture's own list entry 0. The + // index is the one belonging to the list 8.4.1.2.1 picked — reading + // "either list is 0" instead lets a bi-predicted co-located block whose + // list 1 index happens to be 0 zero a motion vector it must not, which + // only shows on a B picture used as the co-located one. + let col_short = col.is_some_and(|c| c.mark == Mark::Short); + let col_zero = col_short + && col_ref_id >= 0 + && col_ref_idx == 0 + && (-1..=1).contains(&col_mv[0]) + && (-1..=1).contains(&col_mv[1]); + let mut mv = [[0i16; 2]; 2]; + let mut ref_id = [-1i32; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + ref_id[list] = ctx + .reference(refs, list, ref_idx[list]) + .map(|p| p.id) + .unwrap_or(-1); + if zero_prediction || (ref_idx[list] == 0 && col_zero) { + mv[list] = [0; 2]; + } else { + mv[list] = mvp[list]; + } + } + return Ok((mv, ref_idx, ref_id)); + } + + // Temporal direct (8.4.1.2.3). + let ref_idx0 = if col_ref_id < 0 { + 0 + } else { + map_col_to_list0(ctx, refs, col_ref_id, vscale) + }; + let col_mv = match vscale { + // 8-195 and 8-196: "/" truncates toward zero. + COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2], + COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)], + _ => col_mv, + }; + let pic0 = ctx.reference(refs, 0, ref_idx0); + let pic1 = ctx.reference(refs, 1, 0); + let ref_id = [ + pic0.map(|p| p.id).unwrap_or(-1), + pic1.map(|p| p.id).unwrap_or(-1), + ]; + let (Some(p0), Some(p1)) = (pic0, pic1) else { + return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); + }; + let td = (p1.poc - p0.poc).clamp(-128, 127); + if p0.mark == Mark::Long || td == 0 { + return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); + } + let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127); + let tx = (16384 + (td / 2).abs()) / td; + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); + let mv0 = [ + ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, + ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, + ]; + let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; + Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) +} + +/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the +/// picture the co-located block referenced. +fn map_col_to_list0( + ctx: &SliceCtx, + refs: &[Picture], + col_ref_id: i32, + vscale: u8, +) -> i8 { + // Picture ids step by 4: a field id is its frame's id + 1 + parity. + let field_mb = ctx.pos.active && ctx.pos.field; + let want = match vscale { + // The field of the referenced frame with the current picture's (or + // macroblock's) parity. + COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity), + // A field macroblock of an MBAFF frame names the field of the frame + // the co-located field macroblock referenced that has its own parity. + _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => { + (col_ref_id & !3) + i32::from(ctx.mb_parity) + } + _ => col_ref_id, + }; + let n = if field_mb { + 2 * ctx.lists[0].len() + } else { + ctx.lists[0].len() + }; + for i in 0..n { + let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| { + if vscale == COL_FLD_TO_FRM { + p.id == col_ref_id & !3 + } else { + p.id == want + } + }); + if hit { + return i as i8; + } + } + 0 +} + +/// Whether a field macroblock of an MBAFF frame whose co-located block is a +/// field macroblock maps the referenced field to the field of the same parity +/// as itself (true) or to that very field (false). +const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false; + +/// `vertMvScale` of 8.4.1.2.1. +const COL_ONE_TO_ONE: u8 = 0; +const COL_FRM_TO_FLD: u8 = 1; +const COL_FLD_TO_FRM: u8 = 2; + +/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame. +#[inline(never)] +fn colocated_mbaff( + ctx: &SliceCtx, + refs: &[Picture], + mvc: &MvCtx, + at: (usize, usize), +) -> (i32, [i16; 2], i8, u8) { + const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); + let Some((k, _)) = ctx.lists[1].get_ref(0) else { + return NONE; + }; + let Some(store) = refs.get(k) else { + return NONE; + }; + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let w = store.mb_w.max(1); + let (c, bx, by, vs) = { + let field_mb = ctx.pos.field; + let bot = mb_y & 1; + let top = mb_y & !1; + // The field of a complementary pair, or of an MBAFF frame's field + // macroblock pair, a frame macroblock takes its co-located block from. + let by_poc = + usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs()); + if store.coding == CODED_FLD { + let p = if field_mb { bot } else { by_poc }; + let Some(f) = store.fields.get(p) else { + return NONE; + }; + if field_mb { + (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE) + } else { + // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8). + let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2; + (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } + } else { + let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0; + match (field_mb, col_field) { + (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), + (false, true) => { + let slot = top + by_poc; + let by = slot * 4 + 2 * bot + at.1 / 2; + (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } + (true, false) => { + let slot = top + at.1 / 2; + let by = slot * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } + (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), + } + } + }; + let idx = by * c.mb_w.max(1) * 4 + bx; + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { + let list = usize::from(c.ref_id[idx][0] < 0); + ( + c.ref_id[idx][list], + c.mv[idx][list], + c.ref_idx[idx][list], + vs, + ) + } else { + (-1, [0; 2], -1, vs) + } +} + +/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current +/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the +/// identity is -1 for an intra block. +fn colocated( + ctx: &SliceCtx, + refs: &[Picture], + mvc: &MvCtx, + at: (usize, usize), +) -> (i32, [i16; 2], i8, u8) { + const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); + let Some((k, _)) = ctx.lists[1].get_ref(0) else { + return NONE; + }; + let Some(store) = refs.get(k) else { + return NONE; + }; + if ctx.pos.active { + return colocated_mbaff(ctx, refs, mvc, at); + } + let Some(cur) = ctx.reference(refs, 1, 0) else { + return NONE; + }; + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let w = store.mb_w.max(1); + // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the + // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`). + let (c, bx, by, vs) = if ctx.structure != FRAME { + if store.coding == CODED_FLD { + (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) + } else if store.coding == CODED_AFRM { + let top = 2 * mb_y; + if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 { + // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16. + let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } else { + // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag. + let slot = top + usize::from(ctx.structure == BOTTOM); + (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE) + } + } else { + // mbAddrCol1 and yM = (2 * yCol) % 16. + let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } + } else if store.coding == CODED_FLD { + let top = (store.fpoc[0] - ctx.poc).abs(); + let bottom = (store.fpoc[1] - ctx.poc).abs(); + let p = usize::from(top >= bottom); + let Some(f) = store.fields.get(p) else { + return NONE; + }; + // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8). + let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2; + (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } else { + (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) + }; + let idx = by * c.mb_w.max(1) * 4 + bx; + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { + let list = usize::from(c.ref_id[idx][0] < 0); + ( + c.ref_id[idx][list], + c.mv[idx][list], + c.ref_idx[idx][list], + vs, + ) + } else { + (-1, [0; 2], -1, vs) + } +} + diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index a8617d59..dc363d8e 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -43,6 +43,7 @@ mod cavlc; mod codec; mod deblock; mod deblock_mbaff; +mod direct; mod decoder; mod dpb; mod enc;