diff --git a/crates/ec-h265/src/dec/cu_syntax.rs b/crates/ec-h265/src/dec/cu_syntax.rs index b30fda7b..c5783aa4 100644 --- a/crates/ec-h265/src/dec/cu_syntax.rs +++ b/crates/ec-h265/src/dec/cu_syntax.rs @@ -1,14 +1,11 @@ -//! CABAC syntax of slice data for P and B slices (and for I slices when the -//! syntax check runs): coding quadtree, coding units, prediction units, the +//! CABAC syntax of slice data for I, P and B slices: coding quadtree, coding units, prediction units, the //! transform tree, SAO parameters and the slice-segment loop (H.265 7.3.8.1 to //! 7.3.8.12, bin binarisations of 9.3.3 and context selection of 9.3.4.2). //! //! The parser reads every bin, keeps the syntax of each coding unit, and turns //! each transform block's coefficients into residual samples through the same //! dequantisation and inverse transform the intra path uses. It does not -//! predict. Motion for each prediction unit comes from a [`MotionSource`]; the -//! merge and AMVP lane implements that trait, and [`ZeroMotion`] stands in until -//! then. +//! predict. Motion for each prediction unit comes from a [`SliceMotion`]. //! //! Slices, slice segments, tiles and wavefront substreams are followed: CTBs //! are visited in tile scan order, contexts are initialised, synced or restored @@ -17,7 +14,7 @@ use super::inter::{self, InterRefs}; use super::mc::{Block, McScratch}; -use super::motion_field::MotionField; +use super::motion_field::SliceMotion; use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter}; use super::rext; use super::tiles::TileScan; @@ -93,7 +90,7 @@ pub struct PredictionUnit { pub mvd: [[i32; 2]; 2], } -/// Motion of one prediction unit, as a [`MotionSource`] returns it. +/// Motion of one prediction unit, as [`SliceMotion::derive_motion`] returns it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Motion { /// `predFlagLX` for list 0 and list 1. @@ -104,75 +101,6 @@ pub struct Motion { pub mv: [[i32; 2]; 2], } -/// The geometry of a coding unit, as a [`MotionSource`] needs it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct CuGeometry { - /// Luma position of the coding unit. - pub x: usize, - /// Luma position of the coding unit. - pub y: usize, - /// Luma size of the coding unit. - pub size: usize, - /// The partitioning. - pub part_mode: PartMode, - /// Whether the coding unit is skipped. - pub skip: bool, -} - -/// Derives the motion of each prediction unit. Called once per unit, in decoding -/// order, after the unit's syntax has been parsed (so merge candidates from -/// earlier units are available to the implementation). Merge and AMVP derivation -/// (8.5.3) is the job of the implementation; the parser does not look inside. -pub trait MotionSource { - /// The motion of unit `pu_index` of the coding unit `cu`. - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion; - - /// Called once the CTB row that ends at luma row `row_end` is fully parsed. Only - /// pictures with one tile get the call (their CTBs come in raster order). - fn row_done(&mut self, _pic: &mut PicState, _row_end: usize) {} - - /// The motion field this source writes, when it is a wavefront band (see [`wpp`]). - fn band_cells(&mut self) -> Option<&mut MotionField> { - None - } -} - -/// The placeholder [`MotionSource`]: zero motion vectors and reference index 0 for -/// every list the unit uses. Replace it with the merge/AMVP derivation. -#[derive(Clone, Copy, Debug, Default)] -pub struct ZeroMotion; - -impl MotionSource for ZeroMotion { - fn derive_motion(&mut self, _cu: &CuGeometry, _pu_index: usize, pu: &PredictionUnit) -> Motion { - let pred_flags = if pu.merge_flag { - [true, false] - } else { - match pu.inter_pred_idc { - InterPredIdc::PredL0 => [true, false], - InterPredIdc::PredL1 => [false, true], - InterPredIdc::PredBi => [true, true], - } - }; - let ref_idx = [ - if pred_flags[0] { - i8::try_from(pu.ref_idx[0]).unwrap_or(0) - } else { - -1 - }, - if pred_flags[1] { - i8::try_from(pu.ref_idx[1]).unwrap_or(0) - } else { - -1 - }, - ]; - Motion { - pred_flags, - ref_idx, - mv: [[0, 0], [0, 0]], - } - } -} - /// The residual samples of one transform block, after dequantisation and the /// inverse transform. Samples are row-major, `size * size`. #[derive(Clone, Debug, PartialEq, Eq)] @@ -212,7 +140,7 @@ pub struct CodingUnit { pub chroma_mode: u8, /// The prediction units, in order. pub pus: Vec, - /// The motion of each prediction unit, from the [`MotionSource`]. + /// The motion of each prediction unit, from [`SliceMotion`]. pub motion: Vec, /// `rqt_root_cbf` (inferred 1 for intra). pub rqt_root_cbf: bool, @@ -245,8 +173,7 @@ pub struct SliceStats { } /// Parse one slice segment's data into `pic`. The block maps are always -/// filled. When `pic` has sample planes (pixel decode), intra coding units are -/// reconstructed in decoding order, and inter coding units are predicted from +/// filled. Intra coding units are reconstructed in decoding order, and inter coding units are predicted from /// `refs` (8.5.3.3) per prediction unit, then get their residual added. #[allow(clippy::too_many_arguments)] // the slice, the picture it decodes into, and its references pub fn parse_slice_into( @@ -254,7 +181,7 @@ pub fn parse_slice_into( pps: &Pps, header: &SliceHeader, data: &[u8], - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, pic: &mut PicState, refs: Option<&InterRefs>, sink: &mut dyn FnMut(&CodingUnit), @@ -456,15 +383,15 @@ pub(super) fn trailing_bits_ok(data: &[u8], read: usize) -> bool { } /// The coding-tree walk of one slice segment, starting with `last_qp` as qPY_PREV. -fn new_parser<'a>( +fn new_parser<'a, 'm>( sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, pic: &'a mut PicState, refs: Option<&'a InterRefs>, - motion: &'a mut dyn MotionSource, + motion: &'a mut SliceMotion<'m>, last_qp: i32, -) -> Parser<'a> { +) -> Parser<'a, 'm> { let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; @@ -555,7 +482,7 @@ struct Cbf { } /// The coding-tree walk state for one slice segment. -struct Parser<'a> { +struct Parser<'a, 'm> { sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, @@ -599,11 +526,11 @@ struct Parser<'a> { cu_bypass: bool, /// The chroma modes of the intra coding unit being parsed, with their DM flags. chroma_modes: ([u8; 4], [bool; 4]), - motion: &'a mut dyn MotionSource, + motion: &'a mut SliceMotion<'m>, stats: SliceStats, } -impl Parser<'_> { +impl Parser<'_, '_> { fn info_at(&self, x: usize, y: usize) -> BlockInfo { self.pic.info[self.pic.unit(x, y)] } @@ -765,15 +692,10 @@ impl Parser<'_> { if skip { self.stats.skip_cus += 1; - let geom = CuGeometry { - x: x0, - y: y0, - size: n, - part_mode: PartMode::Part2Nx2N, - skip: true, - }; let pu = self.prediction_unit(dec, x0, y0, n, n, depth, true)?; - let m = self.motion.derive_motion(&geom, 0, &pu); + let m = self + .motion + .derive_motion(x0, y0, n, PartMode::Part2Nx2N, 0, &pu); self.predict_pu(x0, y0, n, n, &m)?; cu.motion.push(m); cu.pus.push(pu); @@ -823,16 +745,9 @@ impl Parser<'_> { } else { PartMode::Part2Nx2N }; - let geom = CuGeometry { - x: x0, - y: y0, - size: n, - part_mode: cu.part_mode, - skip: false, - }; for (i, (px, py, pw, ph)) in pu_rects(cu.part_mode, x0, y0, n).into_iter().enumerate() { let pu = self.prediction_unit(dec, px, py, pw, ph, depth, false)?; - let m = self.motion.derive_motion(&geom, i, &pu); + let m = self.motion.derive_motion(x0, y0, n, cu.part_mode, i, &pu); self.predict_pu(px, py, pw, ph, &m)?; self.pic.mark_edges(px, py, pw, ph, EDGE_PU); cu.motion.push(m); @@ -861,7 +776,7 @@ impl Parser<'_> { } /// Motion-compensated prediction of one prediction unit (8.5.3.3) into the - /// picture's samples. Nothing happens without pixel decode. + /// picture's samples. fn predict_pu(&mut self, x: usize, y: usize, w: usize, h: usize, m: &Motion) -> Result<()> { let Some(refs) = self.refs else { return Err(Error::corrupt( @@ -1217,7 +1132,7 @@ impl Parser<'_> { } /// The transform unit (7.3.8.10): the QP delta, then each coded block's - /// residual. With pixel decode on, an intra block is predicted and + /// residual. An intra block is predicted and /// reconstructed here, in the order luma, Cb, Cr that its neighbours need. fn transform_unit( &mut self, diff --git a/crates/ec-h265/src/dec/cu_syntax/wpp.rs b/crates/ec-h265/src/dec/cu_syntax/wpp.rs index 1fa27ada..79617bae 100644 --- a/crates/ec-h265/src/dec/cu_syntax/wpp.rs +++ b/crates/ec-h265/src/dec/cu_syntax/wpp.rs @@ -18,7 +18,7 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex, MutexGuard}; -use super::{MotionSource, SliceStats, new_parser, trailing_bits_ok}; +use super::{SliceStats, new_parser, trailing_bits_ok}; use crate::cabac::{CabacDecoder, Contexts}; use crate::dec::inter::InterRefs; use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion}; @@ -127,7 +127,7 @@ impl Board { ry: usize, x: usize, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, ) -> Result> { if ry == 0 { return Ok(None); @@ -163,9 +163,7 @@ impl Board { pic.ctb[(ry - 1) * cols + k] = slot.ctb[k]; } let unit_row = (ry << self.ctb_log2) / 4 - 1; - let field = motion - .band_cells() - .ok_or_else(|| Error::corrupt("HEVC slice (wavefront): a row without a motion band"))?; + let field = &mut *motion.field; for k in k0..=k1 { let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); field.cell_row_mut(unit_row)[ua..ub].copy_from_slice(&slot.cells[ua..ub]); @@ -180,7 +178,7 @@ impl Board { ry: usize, x: usize, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, wpp: Option<&Contexts>, ) -> Result<()> { let ctb = 1usize << self.ctb_log2; @@ -193,13 +191,7 @@ impl Board { (((x + 1) * ctb) >> self.sub_x).min(cw), ); let (ua, ub) = (x * ctb / 4, ((x + 1) * ctb / 4).min(self.w4)); - let field = if full { - Some(motion.band_cells().ok_or_else(|| { - Error::corrupt("HEVC slice (wavefront): a row without a motion band") - })?) - } else { - None - }; + let field = if full { Some(&mut *motion.field) } else { None }; let mut st = lock(&self.state); let slot = &mut st.slots[ry]; if slot.ctb.is_empty() { @@ -254,13 +246,13 @@ trait RowSync { fn enter( &mut self, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, ) -> Result>; fn leave( &mut self, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, wpp: Option<&Contexts>, ) -> Result<()>; @@ -270,7 +262,7 @@ impl RowSync for Link<'_> { fn enter( &mut self, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, ) -> Result> { self.board.enter(self.ry, x, pic, motion) @@ -279,7 +271,7 @@ impl RowSync for Link<'_> { fn leave( &mut self, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, wpp: Option<&Contexts>, ) -> Result<()> { @@ -319,7 +311,7 @@ fn parse_row( pps: &Pps, header: &SliceHeader, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, refs: Option<&InterRefs>, seg: &SegConsts, data: &[u8], @@ -576,9 +568,7 @@ pub(in crate::dec) fn parse_segment( }; let results: Vec>> = std::thread::scope(|s| { let helpers: Vec<_> = (1..workers.clamp(1, nrows)) - .map(|_| { - s.spawn(|| run()) - }) + .map(|_| s.spawn(|| run())) .collect(); let mut all = vec![run()]; for h in helpers { diff --git a/crates/ec-h265/src/dec/dpb.rs b/crates/ec-h265/src/dec/dpb.rs index 7d05a503..3c1013cb 100644 --- a/crates/ec-h265/src/dec/dpb.rs +++ b/crates/ec-h265/src/dec/dpb.rs @@ -40,8 +40,7 @@ pub struct DpbPicture { pub au_index: u32, /// Cropping of the SPS the picture was decoded under. pub window: ConformanceWindow, - /// The samples and the collocated motion (8.5.3.2.8). Empty samples when the decoder - /// runs without pixel decode. The samples may still be being decoded. + /// The samples and the collocated motion (8.5.3.2.8). The samples may still be being decoded. pub picture: Arc, /// HDR, colour and hash metadata of the picture. pub meta: Arc, @@ -97,7 +96,10 @@ impl Frame { pub fn cropped(&self) -> DecodedPicture { let p = &self.picture; let (sx, sy) = crate::decode::chroma_shifts(p.chroma_format_idc); - let (left, top) = ((self.window.left << sx) as usize, (self.window.top << sy) as usize); + let (left, top) = ( + (self.window.left << sx) as usize, + (self.window.top << sy) as usize, + ); let width = p.width - left - ((self.window.right << sx) as usize); let height = p.height - top - ((self.window.bottom << sy) as usize); let crop = |plane: &[u16], stride: usize, x: usize, y: usize, w: usize, h: usize| { diff --git a/crates/ec-h265/src/dec/merge.rs b/crates/ec-h265/src/dec/merge.rs index 658b68d0..eb113e84 100644 --- a/crates/ec-h265/src/dec/merge.rs +++ b/crates/ec-h265/src/dec/merge.rs @@ -3,7 +3,7 @@ //! temporal candidate, combined bi-predictive candidates for B slices, zero //! candidates, and the 8x4 / 4x8 restriction on bi-prediction. -use super::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; +use super::cu_syntax::{PartMode, PredictionUnit}; use super::motion_field::{PbMotion, SliceMotion, to16}; /// Table 8-7: `l0CandIdx` for `combIdx` 0 to 11. @@ -15,21 +15,24 @@ const COMB_L1: [usize; 12] = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]; /// the merge candidate list (8.5.3.2.2). pub fn derive_merge( src: &SliceMotion<'_>, - cu: &CuGeometry, + cu_x: usize, + cu_y: usize, + cu_size: usize, + part_mode: PartMode, pu_index: usize, pu: &PredictionUnit, ) -> PbMotion { let params = src.params; // 8.5.3.2.2: with a parallel merge level above 4x4, every 8x8 coding unit shares // one merge list, derived as if it were a single prediction unit. - let single_list = params.log2_par_mrg_level > 2 && cu.size == 8; + let single_list = params.log2_par_mrg_level > 2 && cu_size == 8; let (x, y, w, h, part_idx) = if single_list { - (cu.x, cu.y, cu.size, cu.size, 0) + (cu_x, cu_y, cu_size, cu_size, 0) } else { (pu.x, pu.y, pu.width, pu.height, pu_index) }; - let mut cands = spatial_candidates(src, cu.part_mode, x, y, w, h, part_idx); + let mut cands = spatial_candidates(src, part_mode, x, y, w, h, part_idx); if let Some(col) = temporal_candidate(src, x, y, w, h) { cands.push(col); } diff --git a/crates/ec-h265/src/dec/motion_field.rs b/crates/ec-h265/src/dec/motion_field.rs index 43133330..00811d0c 100644 --- a/crates/ec-h265/src/dec/motion_field.rs +++ b/crates/ec-h265/src/dec/motion_field.rs @@ -15,7 +15,7 @@ use std::sync::Arc; -use super::cu_syntax::{CuGeometry, Motion, MotionSource, PredictionUnit}; +use super::cu_syntax::{Motion, PartMode, PredictionUnit}; use super::dpb::Dpb; use super::pic::{PicState, PuMotion}; use super::rps::{RefEntry, RefPicLists}; @@ -55,7 +55,7 @@ impl PbMotion { PbMotion::new(m.pred_flags, m.ref_idx, [to16(m.mv[0]), to16(m.mv[1])]) } - /// The [`Motion`] a [`MotionSource`] returns for this block. + /// The [`Motion`] [`SliceMotion::derive_motion`] returns for this block. pub fn to_motion(self) -> Motion { Motion { pred_flags: self.pred, @@ -427,7 +427,7 @@ pub struct MotionParams { pub no_backward_pred: bool, } -/// The [`MotionSource`] of the decoder: derives each prediction unit's motion with +/// The motion source of the decoder: derives each prediction unit's motion with /// the merge or AMVP process and stores it in the picture's motion field. pub struct SliceMotion<'a> { /// Slice parameters. @@ -441,7 +441,7 @@ pub struct SliceMotion<'a> { /// The collocated picture, if temporal prediction applies. pub col: Option>, /// The picture this slice belongs to, when its rows are published as they are - /// decoded (see [`MotionSource::row_done`]). + /// decoded (see [`SliceMotion::row_done`]). pub publish: Option>, /// Index of this slice in the picture's slice list. pub slice: u16, @@ -589,8 +589,9 @@ impl<'a> SliceMotion<'a> { } } -impl MotionSource for SliceMotion<'_> { - fn row_done(&mut self, pic: &mut PicState, row_end: usize) { +impl SliceMotion<'_> { + /// Called once the CTB row that ends at luma row `row_end` is fully parsed. + pub fn row_done(&mut self, pic: &mut PicState, row_end: usize) { // The CTB row that ended is `row_end - ctb`; its motion is final. let ctb = 1usize << self.params.ctb_log2; let y0 = row_end.saturating_sub(ctb); @@ -601,14 +602,20 @@ impl MotionSource for SliceMotion<'_> { } } - fn band_cells(&mut self) -> Option<&mut MotionField> { - Some(&mut *self.field) - } - - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion { - self.field.cur_tile = self.field.tile_at(cu.x, cu.y); + /// The motion of unit `pu_index` of the coding unit at `(x, y)`, `size` luma samples + /// square, derived and stored. + pub fn derive_motion( + &mut self, + x: usize, + y: usize, + size: usize, + part_mode: PartMode, + pu_index: usize, + pu: &PredictionUnit, + ) -> Motion { + self.field.cur_tile = self.field.tile_at(x, y); let derived = if pu.merge_flag { - merge::derive_merge(self, cu, pu_index, pu) + merge::derive_merge(self, x, y, size, part_mode, pu_index, pu) } else { amvp::derive_amvp(self, pu) }; @@ -636,7 +643,6 @@ pub fn scale_mv(mv: [i32; 2], td: i32, tb: i32) -> [i32; 2] { }) } - /// A vector widened to `i32`. pub fn to32(mv: [i16; 2]) -> [i32; 2] { [i32::from(mv[0]), i32::from(mv[1])] diff --git a/crates/ec-h265/src/enc_p.rs b/crates/ec-h265/src/enc_p.rs index 1ea32d4d..fac5106d 100644 --- a/crates/ec-h265/src/enc_p.rs +++ b/crates/ec-h265/src/enc_p.rs @@ -22,7 +22,7 @@ use crate::cabac::{CabacEncoder, Contexts, ctx}; use crate::ctu::{Pel, lambda_for}; use crate::dec::amvp::derive_amvp; -use crate::dec::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; +use crate::dec::cu_syntax::{PartMode, PredictionUnit}; use crate::dec::deblock::{deblock_picture, deblock_rows}; use crate::dec::mc::{Block, McScratch, PlaneMut, PlaneRef, RefPicture, predict_pu}; use crate::dec::merge::derive_merge; @@ -905,13 +905,6 @@ impl<'a> PCoder<'a> { ) -> Result<()> { let n = 1usize << log2; let analysis_mv = analysis.mv; - let geom = CuGeometry { - x, - y, - size: n, - part_mode: PartMode::Part2Nx2N, - skip: false, - }; // Candidate motions: each distinct merge candidate, then AMVP with the // analysed vector under either predictor. let mut merge_motions: Vec<(u8, PbMotion)> = Vec::new(); @@ -927,7 +920,7 @@ impl<'a> PCoder<'a> { }; let m = { let sm = self.sm(); - derive_merge(&sm, &geom, 0, &pu) + derive_merge(&sm, x, y, n, PartMode::Part2Nx2N, 0, &pu) }; if merge_motions.iter().all(|(_, prev)| *prev != m) { merge_motions.push((idx, m));