diff --git a/crates/ec-h264/examples/bench_decode.rs b/crates/ec-h264/examples/bench_decode.rs new file mode 100644 index 00000000..6311b3b0 --- /dev/null +++ b/crates/ec-h264/examples/bench_decode.rs @@ -0,0 +1,158 @@ +//! Throwaway decode-throughput probe for lane-h264perf: raw demux+decode +//! Mpx/s, no render. One untimed warm pass, then best-of-N timed passes over a +//! decoder built fresh per pass. `--hash` FNV-1a-hashes every released frame +//! (display order, visible rows only) so a byte-exact A/B is a file diff. +//! +//! `.mp4` drives the registry surface (ec-mp4 demux, avcC extradata, +//! send_packet/receive_frame); `.264` drives the NAL surface (push_nal + +//! end_picture + flush), both the way the crate's own conformance suite does. +//! +//! usage: bench_decode [reps] [--hash] +use std::time::Instant; + +use ec_core::frame::{Frame, Plane}; +use ec_core::packet::Packet; +use ec_core::registry::{CodecId, Decoder as _, Demuxer as _}; +use ec_h264::{Decoder as H264NalDecoder, H264Decoder, NalOutcome}; + +/// FNV-1a 64 over the visible bytes of every plane (I420 geometry — the same +/// bytes conformance.rs's frame_bytes packs), plus the geometry. +fn hash_frame(h: &mut u64, w: u32, height: u32, planes: &[Plane]) { + let mut fold = |bytes: &[u8]| { + for &b in bytes { + *h ^= u64::from(b); + *h = h.wrapping_mul(0x100000001b3); + } + }; + fold(&w.to_le_bytes()); + fold(&height.to_le_bytes()); + let (w2, h2) = (w.div_ceil(2) as usize, height.div_ceil(2) as usize); + let dims = [(w as usize, height as usize), (w2, h2), (w2, h2)]; + for (plane, (pw, ph)) in planes.iter().zip(dims) { + for y in 0..ph { + let row = plane.row(y, pw).expect("plane row"); + fold(row); + } + } +} + +fn decode_mp4( + packets: &[Packet], + params: &ec_core::registry::CodecParameters, + hash: bool, +) -> (usize, u64, u32, u32) { + let mut dec = H264Decoder::new(params.clone()).expect("h264 decoder"); + let mut frames = 0usize; + let mut h: u64 = 0xcbf29ce484222325; + let mut dims = (0u32, 0u32); + for p in packets { + dec.send_packet(p).expect("send_packet"); + while let Ok(Frame::Video(f)) = dec.receive_frame() { + if hash { + hash_frame(&mut h, f.width, f.height, &f.planes); + } + dims = (f.width, f.height); + frames += 1; + } + } + dec.flush().expect("flush"); + while let Ok(Frame::Video(f)) = dec.receive_frame() { + if hash { + hash_frame(&mut h, f.width, f.height, &f.planes); + } + dims = (f.width, f.height); + frames += 1; + } + (frames, h, dims.0, dims.1) +} + +fn decode_annexb(bytes: &[u8], hash: bool) -> (usize, u64, u32, u32) { + let mut dec = H264NalDecoder::new(); + let mut frames = 0usize; + let mut h: u64 = 0xcbf29ce484222325; + let mut dims = (0u32, 0u32); + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { + if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary { + dec.end_picture().expect("end_picture"); + dec.push_nal(nal).expect("re-push"); + } + while let Some(f) = dec.next_frame() { + if hash { + hash_frame(&mut h, f.width, f.height, &f.planes); + } + dims = (f.width, f.height); + frames += 1; + } + } + dec.flush().expect("flush"); + while let Some(f) = dec.next_frame() { + if hash { + hash_frame(&mut h, f.width, f.height, &f.planes); + } + dims = (f.width, f.height); + frames += 1; + } + (frames, h, dims.0, dims.1) +} + +enum Source { + Mp4(Vec, ec_core::registry::CodecParameters), + AnnexB(Vec), +} + +fn decode(src: &Source, hash: bool) -> (usize, u64, u32, u32) { + match src { + Source::Mp4(p, par) => decode_mp4(p, par, hash), + Source::AnnexB(b) => decode_annexb(b, hash), + } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let path = args.first().expect("usage: bench_decode [reps] [--hash]"); + let reps: u32 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(3); + let hash = args.iter().any(|a| a == "--hash"); + + let src = if path.ends_with(".mp4") { + let file = std::fs::File::open(path).expect("open mp4"); + let mut demux = + ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 open"); + let (idx, params) = demux + .streams() + .iter() + .find(|s| s.params.codec == CodecId::H264) + .map(|s| (s.index, s.params.clone())) + .expect("no H.264 track"); + let mut packets = Vec::new(); + while let Ok(p) = demux.next_packet() { + if p.stream == idx { + packets.push(p); + } + } + Source::Mp4(packets, params) + } else { + Source::AnnexB(std::fs::read(path).expect("read annexb")) + }; + + // Warm pass (untimed): page in, branch predictors, allocator pools. + let (frames, h, w, height) = decode(&src, hash); + assert!(frames > 0, "no frames decoded"); + if hash { + println!("hash={h:016x} frames={frames} {w}x{height}"); + } + + let px = u64::from(w) * u64::from(height) * frames as u64; + let mut best = f64::MAX; + for _ in 0..reps { + let t = Instant::now(); + let r = decode(&src, false); + let e = t.elapsed().as_secs_f64(); + assert_eq!(r.0, frames, "frame count diverged between passes"); + best = best.min(e); + } + println!( + "{path}: frames={frames} px={px} best={:.1}ms over {reps} -> {:.1} Mpx/s", + best * 1e3, + px as f64 / best / 1e6 + ); +} diff --git a/crates/ec-h264/src/bits.rs b/crates/ec-h264/src/bits.rs index fec78f52..24ad5865 100644 --- a/crates/ec-h264/src/bits.rs +++ b/crates/ec-h264/src/bits.rs @@ -132,6 +132,43 @@ impl<'a> BitCursor<'a> { Ok(v) } + /// Read `n` bits (`n <= 32`) MSB-first, zero-filled past the end of the + /// stream — the CABAC engine's supply contract (see the module note in + /// `cabac.rs`): a conformant stream never depends on those bits, and the + /// phantom reads do not advance `bit_position` beyond the real ones. + #[inline] + pub fn bits_zero_fill(&mut self, n: u32) -> u32 { + debug_assert!(n <= 32); + if n == 0 { + return 0; + } + if self.cached < n { + self.refill(); + } + if self.cached >= n { + let v = (self.cache >> (64 - n)) as u32; + self.cache <<= n; + self.cached -= n; + return v; + } + // Genuinely past the end: consume what is cached, zero-fill the rest. + let have = self.cached; + let v = if have == 0 { + 0 + } else { + ((self.cache >> (64 - have)) as u32) << (n - have) + }; + self.cache <<= have; + self.cached = 0; + v + } + + /// One bit, zero-filled past the end (see [`bits_zero_fill`]). + #[inline] + pub fn bit_zero_fill(&mut self) -> u32 { + self.bits_zero_fill(1) + } + /// Count leading zero bits up to and including the terminating one bit /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros. #[inline] diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index 0e642dec..9f9bf1d0 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -188,16 +188,20 @@ impl<'a> Cabac<'a> { /// One bit of slice data; zero past the end (see the module note). #[inline] fn bit(&mut self) -> u32 { - u32::from(self.r.read_bit().unwrap_or(false)) + self.r.bit_zero_fill() } /// 9.3.3.2.2 RenormD. + /// + /// codIRange is at most 510, so the number of doublings the loop form + /// would take is `leading_zeros - 23` — zero when no renorm is due. One + /// bulk read replaces the per-bit supply, and the position accounting of + /// the zero-filled read matches the loop's bit-by-bit one exactly. #[inline] fn renorm(&mut self) { - while self.range < 256 { - self.range <<= 1; - self.offset = (self.offset << 1) | self.bit(); - } + let shifts = self.range.leading_zeros() - 23; + self.range <<= shifts; + self.offset = (self.offset << shifts) | self.r.bits_zero_fill(shifts); } /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1. @@ -787,14 +791,15 @@ impl<'a> Cabac<'a> { 4.min(1 + num_eq1) as usize }; let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize; - // Prefix: TU with cMax = uCoff = 14. + // Prefix: TU with cMax = uCoff = 14. The first bin reads the + // inc0 context, every later one the inc1 context, so the two + // spellings are hoisted out of the loop. let mut prefix = 0u32; - while prefix < 14 { - let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 }; - if !self.decision(ctx_idx) { - break; + if self.decision(abs_base + inc0) { + prefix = 1; + while prefix < 14 && self.decision(abs_base + inc1) { + prefix += 1; } - prefix += 1; } let abs_minus1 = if prefix < 14 { prefix diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index c57e2531..a8e32461 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -901,6 +901,14 @@ impl SliceCtx { refs.get(self.lists[list].get(idx as usize)?) } + /// True when no slice-level weighting can apply at all, so every + /// component of every partition resolves to [`Weights::DEFAULT`] without + /// the per-component lookup: neither weighted prediction (P) nor + /// weighted/bi-prediction (B) is signalled. + fn no_weights(&self) -> bool { + self.weighted_bipred_idc == 0 && !self.weighted_pred + } + /// Prediction weights of one component (clause 8.4.3). fn weights_for( &self, @@ -2226,13 +2234,21 @@ fn compensate( let x0 = (mb_x * 16 + px * 4) as i32; let y0 = (mb_y * 16 + py * 4) as i32; let (w, h) = (pw * 4, ph * 4); - - let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); - // 8.4.2.3.1 over one list is the identity, so the interpolation of that one - // list IS the prediction: it is written straight into the picture at the - // picture's own pitch, rather than into a temporary that is combined into a - // second temporary and copied a third time. - let direct = wt.is_default() && (use0 != use1); + // A stream carrying no weighted prediction at all resolves every + // component to the identity weighting without the per-component lookup. + let plain = ctx.no_weights(); + let wt = if plain { + Weights::DEFAULT + } else { + ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1) + }; + // 8.4.2.3.1 over one list is the identity, so the interpolation of that + // one list IS the prediction: it is written straight into the picture at + // the picture's own pitch. Over both lists the combined prediction is the + // rounded byte average of the two clipped ones, so list 0 interpolates + // into the picture and list 1 averages on top of it (Put::Avg) — no + // temporaries, no combining pass, no copy back. + let direct = wt.is_default(); let luma_ref = |list: usize| -> Result> { let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { Error::corrupt("reference index names a picture the buffer does not hold") @@ -2248,7 +2264,46 @@ fn compensate( }; let stride = pic.y.stride; let origin = pic.y.at(x0 as usize, y0 as usize); - if direct { + // Weighted bi-prediction fuses the same way: the combining formula is + // per-sample, so list 0 lands in the picture and list 1 combines on top + // of it (Put::AvgW) with 8.4.2.3.2's exact integers. + let weighted_put = if !direct && use0 && use1 { + Some(crate::inter::Put::AvgW { + w0: wt.w[0], + w1: wt.w[1], + shift: (wt.log_wd + 1) as u32, + round: 1 << wt.log_wd, + off: (wt.o[0] + wt.o[1] + 1) >> 1, + }) + } else { + None + }; + if direct && use0 && use1 { + let plane = luma_ref(0)?; + mc_luma( + &plane, + x0, + y0, + mv[0], + w, + h, + stride, + &mut pic.y.data[origin..], + crate::inter::Put::Set, + ); + let plane = luma_ref(1)?; + mc_luma( + &plane, + x0, + y0, + mv[1], + w, + h, + stride, + &mut pic.y.data[origin..], + crate::inter::Put::Avg, + ); + } else if direct { // No scratch buffer is declared on this path at all: the scratch is // zeroed on entry, and most partitions of a P slice come through here. let list = usize::from(!use0); @@ -2262,6 +2317,32 @@ fn compensate( h, stride, &mut pic.y.data[origin..], + crate::inter::Put::Set, + ); + } else if let Some(put) = weighted_put { + let plane = luma_ref(0)?; + mc_luma( + &plane, + x0, + y0, + mv[0], + w, + h, + stride, + &mut pic.y.data[origin..], + crate::inter::Put::Set, + ); + let plane = luma_ref(1)?; + mc_luma( + &plane, + x0, + y0, + mv[1], + w, + h, + stride, + &mut pic.y.data[origin..], + put, ); } else { let mut part = [[0u8; 256]; 2]; @@ -2270,7 +2351,7 @@ fn compensate( continue; } let plane = luma_ref(list)?; - mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list]); + mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list], crate::inter::Put::Set); } let mut out = [0u8; 256]; let (p0, p1) = part.split_at(1); @@ -2286,8 +2367,26 @@ fn compensate( let (cw, ch) = (w / 2, h / 2); let (cx0, cy0) = (x0 / 2, y0 / 2); for comp in 0..2 { - let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); - let direct = wt.is_default() && (use0 != use1); + let wt = if plain { + Weights::DEFAULT + } else { + ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1) + }; + let direct = wt.is_default(); + // The combining weights are per-component syntax (luma and chroma + // carry their own denoms, weights and offsets), so this component's + // fused mode is built from ITS OWN lookup — never the luma one. + let weighted_put = if !direct && use0 && use1 { + Some(crate::inter::Put::AvgW { + w0: wt.w[0], + w1: wt.w[1], + shift: (wt.log_wd + 1) as u32, + round: 1 << wt.log_wd, + off: (wt.o[0] + wt.o[1] + 1) >> 1, + }) + } else { + None + }; let chroma_ref = |list: usize| -> RefPlane<'_> { let rp = ctx .reference(refs, list, ref_idx[list]) @@ -2305,7 +2404,57 @@ fn compensate( let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; let stride = plane_out.stride; let origin = plane_out.at(cx0 as usize, cy0 as usize); - if direct { + if direct && use0 && use1 { + let plane = chroma_ref(0); + mc_chroma( + &plane, + cx0, + cy0, + mv[0], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Set, + ); + let plane = chroma_ref(1); + mc_chroma( + &plane, + cx0, + cy0, + mv[1], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Avg, + ); + } else if let Some(put) = weighted_put { + let plane = chroma_ref(0); + mc_chroma( + &plane, + cx0, + cy0, + mv[0], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Set, + ); + let plane = chroma_ref(1); + mc_chroma( + &plane, + cx0, + cy0, + mv[1], + cw, + ch, + stride, + &mut plane_out.data[origin..], + put, + ); + } else if direct { let list = usize::from(!use0); let plane = chroma_ref(list); mc_chroma( @@ -2317,6 +2466,7 @@ fn compensate( ch, stride, &mut plane_out.data[origin..], + crate::inter::Put::Set, ); } else { let mut cpart = [[0u8; 64]; 2]; @@ -2325,7 +2475,17 @@ fn compensate( continue; } let plane = chroma_ref(list); - mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, cw, &mut cpart[list]); + mc_chroma( + &plane, + cx0, + cy0, + mv[list], + cw, + ch, + cw, + &mut cpart[list], + crate::inter::Put::Set, + ); } let mut cout = [0u8; 64]; let (c0, c1) = cpart.split_at(1); @@ -2817,3 +2977,142 @@ fn boundary_strength( }; bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::dpb::RefList; + use ec_h264_syntax::{PredWeightTable, WeightEntry}; + + /// A picture whose visible samples are a fixed ramp, borders replicated. + fn ramp_picture(value: impl Fn(usize, usize) -> u8) -> Picture { + let mut pic = Picture::default(); + pic.mb_w = 1; + pic.mb_h = 1; + for (plane, size) in [(0usize, 16usize), (1, 8), (2, 8)] { + let p = match plane { + 0 => &mut pic.y, + 1 => &mut pic.cb, + _ => &mut pic.cr, + }; + let pad = 8; + let stride = size + 2 * pad; + let mut data = vec![0u8; stride * (size + 2 * pad)]; + for y in 0..size { + for x in 0..size { + data[(pad + y) * stride + pad + x] = value(x, y); + } + } + *p = Plane8 { + data, + stride, + origin: pad * stride + pad, + width: size, + height: size, + pad, + }; + p.extend_borders(); + } + pic + } + + fn plane_byte(p: &Plane8, x: usize, y: usize) -> u8 { + p.data[p.origin + y * p.stride + x] + } + + /// Explicit-weight bipred combines each component with ITS OWN weights: + /// luma and chroma signal independent denoms/weights/offsets, so chroma + /// must never ride the luma lookup (regression guard for the fused + /// weighted path in [`compensate`]). + #[test] + fn weighted_bipred_combines_per_component() { + let refs = vec![ + ramp_picture(|x, y| (40 + x * 3 + y) as u8), + ramp_picture(|x, y| (220 - x - y * 2) as u8), + ]; + let mut l0 = RefList::default(); + l0.push(0); + let mut l1 = RefList::default(); + l1.push(1); + let ctx = SliceCtx { + slice_id: 0, + slice_type: SliceType::B, + qp: 30, + cb_qp_offset: 0, + cr_qp_offset: 0, + transform_8x8_mode: false, + constrained_intra_pred: false, + qp_delta_inc: 0, + lists: [l0, l1], + num_ref_idx: [1, 1], + direct_spatial: true, + direct_8x8_inference: true, + weighted_pred: false, + weighted_bipred_idc: 1, + weights: Some(PredWeightTable { + luma_log2_weight_denom: 1, + chroma_log2_weight_denom: 2, + l0: vec![WeightEntry { + luma: Some((2, 1)), + chroma: Some([(5, 2), (7, 3)]), + }], + l1: vec![WeightEntry { + luma: Some((2, 1)), + chroma: Some([(5, 2), (7, 3)]), + }], + }), + poc: 4, + shapes: MbShapes::default(), + }; + let mut pic = ramp_picture(|_, _| 0); + + compensate(&mut pic, &refs, &ctx, 0, 0, 0, 0, 4, 4, [[0, 0]; 2], [0, 0]) + .expect("compensate"); + + let expected = |p0: u8, p1: u8, w: i32, log_wd: u32, o: i32| -> u8 { + let v = (((i32::from(p0) * w + i32::from(p1) * w + (1 << log_wd)) + >> (log_wd + 1)) + + o) + .clamp(0, 255); + v as u8 + }; + // Luma: weights (2, 1) — whatever luma does is the luma reference + // behaviour; the point is chroma below. + for y in 0..16 { + for x in 0..16 { + let (p0, p1) = ( + plane_byte(&refs[0].y, x, y), + plane_byte(&refs[1].y, x, y), + ); + assert_eq!( + plane_byte(&pic.y, x, y), + expected(p0, p1, 2, 1, 1), + "luma ({x},{y})" + ); + } + } + // Chroma Cb: weights (5, 2) with denom 2 — NOT the luma weights. + for y in 0..8 { + for x in 0..8 { + let (p0, p1) = ( + plane_byte(&refs[0].cb, x, y), + plane_byte(&refs[1].cb, x, y), + ); + assert_eq!( + plane_byte(&pic.cb, x, y), + expected(p0, p1, 5, 2, 2), + "cb ({x},{y})" + ); + let (p0, p1) = ( + plane_byte(&refs[0].cr, x, y), + plane_byte(&refs[1].cr, x, y), + ); + assert_eq!( + plane_byte(&pic.cr, x, y), + expected(p0, p1, 7, 2, 3), + "cr ({x},{y})" + ); + } + } + } +} diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs index a784910c..904b2874 100644 --- a/crates/ec-h264/src/dpb.rs +++ b/crates/ec-h264/src/dpb.rs @@ -83,7 +83,9 @@ impl Plane8 { /// Replicate the edge samples into the padding, which turns the per-sample /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see /// [`crate::inter`]). - fn extend_borders(&mut self) { + /// Replicate edge samples into the border; also the setup decoder tests + /// need for planes that inter::RefPlane reads. + pub(crate) fn extend_borders(&mut self) { let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride); for y in 0..h { let row = self.origin + y * stride; @@ -307,7 +309,9 @@ impl RefList { (idx < self.len).then(|| usize::from(self.entries[idx])) } - fn push(&mut self, idx: usize) { + /// Append one DPB index; also the constructor decoder tests need to name + /// a non-empty reference list. + pub(crate) fn push(&mut self, idx: usize) { if self.len < self.entries.len() { self.entries[self.len] = idx as u8; self.len += 1; diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index ba45b0c1..6425470f 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -24,7 +24,7 @@ use crate::entropy::{ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, }; -use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; +use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma}; use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; use crate::pred::{ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, @@ -863,6 +863,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec, mb_x: usize, mb_y: usize) -> Vec, mb_x: usize, mb_y: usize) -> Vec i16x16 { /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes. #[inline] -fn store_half8(dst: &mut [u8], v: i16x8) { +fn store_half8(dst: &mut [u8], v: i16x8, put: Put) { let c = ((v + i16x8::splat(16)) >> 5u32) .max(i16x8::ZERO) .min(i16x8::splat(255)); - for (o, &s) in dst.iter_mut().zip(c.as_array()) { - *o = s as u8; + match put { + Put::Set => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = s as u8; + } + } + Put::Avg => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = avg(*o, s as u8); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + store_weighted(o, s as u8, w0, w1, shift, round, off); + } + } } } /// The same over sixteen lanes. #[inline] -fn store_half16(dst: &mut [u8], v: i16x16) { +fn store_half16(dst: &mut [u8], v: i16x16, put: Put) { let c = ((v + i16x16::splat(16)) >> 5u32) .max(i16x16::ZERO) .min(i16x16::splat(255)); - for (o, &s) in dst.iter_mut().zip(c.as_array()) { - *o = s as u8; + match put { + Put::Set => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = s as u8; + } + } + Put::Avg => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = avg(*o, s as u8); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + store_weighted(o, s as u8, w0, w1, shift, round, off); + } + } } } - /// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is /// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the /// horizontal filter, the plane stride for the vertical one. @@ -166,6 +205,7 @@ fn half_block( store_half16( &mut dst[row * 16..row * 16 + 16], tap6_16(data, base + row * stride, step), + Put::Set, ); } } else { @@ -173,6 +213,7 @@ fn half_block( store_half8( &mut dst[row * w..row * w + w], tap6_8(data, base + row * stride, step), + Put::Set, ); } } @@ -201,12 +242,32 @@ fn tap6_inter8(v: &[i16], at: usize, step: usize) -> i32x8 { /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes. #[inline] -fn store_centre(dst: &mut [u8], v: i32x8) { +fn store_centre(dst: &mut [u8], v: i32x8, put: Put) { let c = ((v + i32x8::splat(512)) >> 10u32) .max(i32x8::ZERO) .min(i32x8::splat(255)); - for (o, &s) in dst.iter_mut().zip(c.as_array()) { - *o = s as u8; + match put { + Put::Set => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = s as u8; + } + } + Put::Avg => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = avg(*o, s as u8); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => { + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + store_weighted(o, s as u8, w0, w1, shift, round, off); + } + } } } @@ -225,27 +286,65 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) { /// The same average, written into a destination of pitch `os` from two /// `w`-pitch sources. #[inline] -fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize) { +fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize, put: Put) { if os == w { - avg_rows(out, a, b, w * h); + avg_rows_to_contig(out, a, b, w * h, put); return; } for row in 0..h { - avg_rows( + avg_rows_to_contig( &mut out[row * os..row * os + w], &a[row * w..], &b[row * w..], w, + put, ); } } +/// The average over contiguous equal-length slices, honouring `put`. +#[inline] +fn avg_rows_to_contig(out: &mut [u8], a: &[u8], b: &[u8], n: usize, put: Put) { + match put { + Put::Set => avg_rows(out, a, b, n), + Put::Avg => { + let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]); + for i in 0..n { + out[i] = avg(avg(a[i], b[i]), out[i]); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => avg_rows_weighted(out, a, b, n, w0, w1, shift, round, off), + } +} + /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch -/// destination. +/// destination, honouring `put`. #[inline] -fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize) { +fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize, put: Put) { for row in 0..h { - out[row * os..row * os + w].copy_from_slice(&src[row * w..row * w + w]); + let dst = &mut out[row * os..row * os + w]; + let src = &src[row * w..row * w + w]; + match put { + Put::Set => dst.copy_from_slice(src), + Put::Avg => { + for (d, &s) in dst.iter_mut().zip(src) { + *d = avg(*d, s); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => copy_rows_weighted(dst, src, w0, w1, shift, round, off), + } } } @@ -275,10 +374,10 @@ pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usiz let yi = clamp_origin(y, h, r.height, r.pad, 2, 3); r.at(xi, yi) } - -/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose -/// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter -/// samples. Writes `w` x `h` prediction samples into `out` at pitch `os`. +/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition +/// whose full-sample origin is `(x, y)` and whose motion vector is `mv` in +/// quarter samples. Writes `w` x `h` prediction samples into `out` at pitch +/// `os`, honouring `put` (see [`Put`]). /// /// The pitch is a parameter so that the single-list, default-weight case — /// which is most of a P slice — interpolates straight into the picture instead @@ -293,6 +392,7 @@ pub(crate) fn mc_luma( h: usize, os: usize, out: &mut [u8], + put: Put, ) { let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); @@ -302,9 +402,41 @@ pub(crate) fn mc_luma( // Full sample: a straight copy. if fx == 0 && fy == 0 { - for row in 0..h { - let src = base + row * stride; - out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); + match put { + Put::Set => { + for row in 0..h { + let src = base + row * stride; + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); + } + } + Put::Avg => { + for row in 0..h { + let src = base + row * stride; + let dst = &mut out[row * os..row * os + w]; + for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) { + *d = avg(*d, v); + } + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => copy_weighted( + out, + os, + &r.data[base..], + stride, + w, + h, + w0, + w1, + shift, + round, + off, + ), } return; } @@ -350,7 +482,7 @@ pub(crate) fn mc_luma( for col in (0..w).step_by(8) { let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W); let n = (w - col).min(8); - store_centre(&mut jj[row * w + col..row * w + col + n], v); + store_centre(&mut jj[row * w + col..row * w + col + n], v, Put::Set); } } } @@ -359,11 +491,11 @@ pub(crate) fn mc_luma( // the average of two of them. Resolving it once per partition rather than // once per sample is what keeps the copy loops straight. match (fx, fy) { - (2, 0) => copy_rows(out, os, &bb, w, h), - (0, 2) => copy_rows(out, os, &hh, w, h), - (2, 2) => copy_rows(out, os, &jj, w, h), - (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h), - (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h), + (2, 0) => copy_rows(out, os, &bb, w, h, put), + (0, 2) => copy_rows(out, os, &hh, w, h, put), + (2, 2) => copy_rows(out, os, &jj, w, h, put), + (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h, put), + (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h, put), (1, 0) | (3, 0) | (0, 1) | (0, 3) => { // Averaged with an integer sample one row or column over. let (dx, dy) = match (fx, fy) { @@ -377,13 +509,41 @@ pub(crate) fn mc_luma( let s = &r.data[src..src + w]; let hl = &half[row * w..row * w + w]; let dst = &mut out[row * os..row * os + w]; - for col in 0..w { - dst[col] = avg(s[col], hl[col]); + match put { + Put::Set => { + for col in 0..w { + dst[col] = avg(s[col], hl[col]); + } + } + Put::Avg => { + for col in 0..w { + dst[col] = avg(dst[col], avg(s[col], hl[col])); + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => { + for col in 0..w { + store_weighted( + &mut dst[col], + avg(s[col], hl[col]), + w0, + w1, + shift, + round, + off, + ); + } + } } } } // Diagonal quarter positions: the two nearest half samples. - _ => avg_rows_to(out, os, &bb, &hh, w, h), + _ => avg_rows_to(out, os, &bb, &hh, w, h, put), } } @@ -403,6 +563,7 @@ fn chroma_rows( wt: [u16; 4], os: usize, out: &mut [u8], + put: Put, ) { for row in 0..h { let src = base + row * stride; @@ -415,7 +576,17 @@ fn chroma_rows( + u16::from(q[c]) * wt[2] + u16::from(q[c + 1]) * wt[3] + 32; - dst[c] = (v >> 6) as u8; + match put { + Put::Set => dst[c] = (v >> 6) as u8, + Put::Avg => dst[c] = avg(dst[c], (v >> 6) as u8), + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => store_weighted(&mut dst[c], (v >> 6) as u8, w0, w1, shift, round, off), + } } } } @@ -431,6 +602,7 @@ pub(crate) fn mc_chroma( h: usize, os: usize, out: &mut [u8], + put: Put, ) { let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16); let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1); @@ -441,20 +613,51 @@ pub(crate) fn mc_chroma( // Full sample: a straight copy. A zero motion vector is the most common // vector in real content, and it lands here. if fx == 0 && fy == 0 { - for row in 0..h { - let src = base + row * stride; - out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); + match put { + Put::Set => { + for row in 0..h { + let src = base + row * stride; + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); + } + } + Put::Avg => { + for row in 0..h { + let src = base + row * stride; + let dst = &mut out[row * os..row * os + w]; + for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) { + *d = avg(*d, v); + } + } + } + Put::AvgW { + w0, + w1, + shift, + round, + off, + } => copy_weighted( + out, + os, + &r.data[base..], + stride, + w, + h, + w0, + w1, + shift, + round, + off, + ), } return; } - // The four weights sum to 64, so the weighted sum of Equation 8-270 never // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes. let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy]; match w { - 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out), - 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out), - _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out), + 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out, put), + 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out, put), + _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out, put), } } @@ -485,6 +688,101 @@ impl Weights { } } +/// How an interpolation result lands in `out`: written outright, or rounded +/// into what is already there. +/// +/// The weighted second pass of 8.4.2.3.2 is a fusion mode as well: the first +/// prediction sits in `out`, and the second list's sample `v` combines with +/// it as `clip((out*w0 + v*w1 + round) >> shift) + off` — the same integer +/// formula, on the same bytes, as running the combining pass over the two +/// clipped predictions. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Put { + /// Write the prediction. + Set, + /// Average the prediction into the bytes already in `out`. + Avg, + /// Weighted-average the prediction into the bytes already in `out`. + AvgW { + w0: i32, + w1: i32, + shift: u32, + round: i32, + off: i32, + }, +} + +/// The 8.4.2.3.2 combining step for one sample: list 0's prediction is the +/// byte already in `dst`, list 1's is `v`. +#[inline] +fn store_weighted(dst: &mut u8, v: u8, w0: i32, w1: i32, shift: u32, round: i32, off: i32) { + let p0 = i32::from(*dst); + *dst = clip8((((p0 * w0 + i32::from(v) * w1 + round) >> shift) + off) as i32); +} +/// The weighted combining pass over a whole block: `h` rows of `w` samples +/// from a `stride`-pitch source into an `os`-pitch destination. +#[inline(never)] +#[allow(clippy::too_many_arguments)] +fn copy_weighted( + out: &mut [u8], + os: usize, + src: &[u8], + stride: usize, + w: usize, + h: usize, + w0: i32, + w1: i32, + shift: u32, + round: i32, + off: i32, +) { + for row in 0..h { + let dst = &mut out[row * os..row * os + w]; + let s = &src[row * stride..row * stride + w]; + for (d, &v) in dst.iter_mut().zip(s) { + store_weighted(d, v, w0, w1, shift, round, off); + } + } +} + +/// The weighted combining pass over contiguous equal-length slices, where +/// list 1's sample is the rounded average of `a` and `b`. +#[inline(never)] +#[allow(clippy::too_many_arguments)] +fn avg_rows_weighted( + out: &mut [u8], + a: &[u8], + b: &[u8], + n: usize, + w0: i32, + w1: i32, + shift: u32, + round: i32, + off: i32, +) { + let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]); + for i in 0..n { + store_weighted(&mut out[i], avg(a[i], b[i]), w0, w1, shift, round, off); + } +} + +/// The weighted combining pass over a whole block from a `w`-pitch source. +#[inline(never)] +#[allow(clippy::too_many_arguments)] +fn copy_rows_weighted( + out: &mut [u8], + src: &[u8], + w0: i32, + w1: i32, + shift: u32, + round: i32, + off: i32, +) { + for (d, &s) in out.iter_mut().zip(src) { + store_weighted(d, s, w0, w1, shift, round, off); + } +} + /// Combine the list predictions of one partition into the final prediction /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that /// is not used is ignored. @@ -674,7 +972,7 @@ mod tests { for fx in 0..4i16 { for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { let mv = [fx - 20 * 4, fy + 12]; - mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours); + mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours, Put::Set); spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs); assert_eq!( ours[..pw * ph], @@ -687,6 +985,38 @@ mod tests { } } + /// `Put::Avg` turns `mc_luma` into the second half of a default-weighted + /// bi-prediction: averaging into the first list's bytes is bit-exact with + /// running the combining pass over the two clipped predictions (8.4.2.3.1). + #[test] + fn avg_mode_matches_the_combining_pass() { + let (w, h, pad) = (48usize, 32usize, 32usize); + let (data, stride, origin) = ramp_plane(w, h, pad); + let r = plane(&data, stride, origin, w, h, pad); + let mut fused = [0u8; 256]; + let mut p0 = [0u8; 256]; + let mut p1 = [0u8; 256]; + let mut out = [0u8; 256]; + for mv0 in [[0i16; 2], [7, -3], [-41, 22]] { + for mv1 in [[2i16; 2], [5, 1], [-13, 9]] { + for &(pw, ph) in &[(16usize, 16usize), (8, 8), (4, 4)] { + mc_luma(&r, 4, 4, mv0, pw, ph, pw, &mut p0, Put::Set); + mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut p1, Put::Set); + combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, pw * ph); + // The fused shape: first list into the picture, second + // averaged on top of it. + fused[..pw * ph].copy_from_slice(&p0[..pw * ph]); + mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut fused, Put::Avg); + assert_eq!( + fused[..pw * ph], + out[..pw * ph], + "mv {mv0:?} + {mv1:?} {pw}x{ph}" + ); + } + } + } + } + #[test] fn chroma_interpolation_matches_equation_8_270() { let (w, h, pad) = (24usize, 16usize, 16usize); @@ -697,7 +1027,7 @@ mod tests { for fy in 0..8i16 { for fx in 0..8i16 { let mv = [fx, fy]; - mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours); + mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours, Put::Set); for row in 0..8i32 { for col in 0..8i32 { let s = |dx: i32, dy: i32| -> i32 {