From 57ad7ebb5f36c93e2353fe4b33aadfb66b5f88a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 23:28:37 +0300 Subject: [PATCH] perf(h264): fuse the bi-predicted combining pass into motion compensation Default-weighted bi-prediction (8.4.2.3.1) is the rounded average of the two lists' clipped byte predictions, so list 0 now interpolates straight into the picture and list 1 averages on top of it (Put::Avg) instead of both landing in 256/64-byte temporaries, going through combine(), and being copied back per row. Weighted slices keep the temporary path. SliceCtx::no_weights() hoists the per-component weights_for lookup for streams that signal no weighted prediction at all. Byte-exact A/B vs d27a904d on five fixture classes (720p High CABAC+B, 720p CAVLC baseline, 1440p High no-B, 1080p Main, 4K Main): all display- order frame hashes identical. ec-h264 suite green (79 lib + 23 conformance + 12 encode + 1 decode-first). --- crates/ec-h264/examples/bench_decode.rs | 158 ++++++++++++++++++++++ crates/ec-h264/src/decoder.rs | 108 +++++++++++++-- crates/ec-h264/src/enc/mb.rs | 10 +- crates/ec-h264/src/inter.rs | 171 +++++++++++++++++++----- 4 files changed, 396 insertions(+), 51 deletions(-) create mode 100644 crates/ec-h264/examples/bench_decode.rs 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/decoder.rs b/crates/ec-h264/src/decoder.rs index c57e2531..ed30aab2 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,32 @@ fn compensate( }; let stride = pic.y.stride; let origin = pic.y.at(x0 as usize, y0 as usize); - if direct { + 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 +2303,7 @@ fn compensate( h, stride, &mut pic.y.data[origin..], + crate::inter::Put::Set, ); } else { let mut part = [[0u8; 256]; 2]; @@ -2270,7 +2312,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 +2328,12 @@ 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(); let chroma_ref = |list: usize| -> RefPlane<'_> { let rp = ctx .reference(refs, list, ref_idx[list]) @@ -2305,7 +2351,32 @@ 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 direct { let list = usize::from(!use0); let plane = chroma_ref(list); mc_chroma( @@ -2317,6 +2388,7 @@ fn compensate( ch, stride, &mut plane_out.data[origin..], + crate::inter::Put::Set, ); } else { let mut cpart = [[0u8; 64]; 2]; @@ -2325,7 +2397,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); 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; + store_u8(o, s as u8, put); } } /// 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; + store_u8(o, s as u8, put); } } - /// 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 +165,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 +173,7 @@ fn half_block( store_half8( &mut dst[row * w..row * w + w], tap6_8(data, base + row * stride, step), + Put::Set, ); } } @@ -201,12 +202,12 @@ 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; + store_u8(o, s as u8, put); } } @@ -225,27 +226,51 @@ 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]); + } + } + } +} + /// 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); + } + } + } } } @@ -275,10 +300,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 +318,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); @@ -304,7 +330,16 @@ pub(crate) fn mc_luma( 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]); + let dst = &mut out[row * os..row * os + w]; + let s = &r.data[src..src + w]; + match put { + Put::Set => dst.copy_from_slice(s), + Put::Avg => { + for (d, &v) in dst.iter_mut().zip(s) { + *d = avg(*d, v); + } + } + } } return; } @@ -350,7 +385,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 +394,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) { @@ -378,12 +413,12 @@ pub(crate) fn mc_luma( 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]); + store_u8(&mut dst[col], avg(s[col], hl[col]), put); } } } // 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 +438,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 +451,7 @@ fn chroma_rows( + u16::from(q[c]) * wt[2] + u16::from(q[c + 1]) * wt[3] + 32; - dst[c] = (v >> 6) as u8; + store_u8(&mut dst[c], (v >> 6) as u8, put); } } } @@ -431,6 +467,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); @@ -443,18 +480,26 @@ pub(crate) fn mc_chroma( 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]); + let dst = &mut out[row * os..row * os + w]; + let s = &r.data[src..src + w]; + match put { + Put::Set => dst.copy_from_slice(s), + Put::Avg => { + for (d, &v) in dst.iter_mut().zip(s) { + *d = avg(*d, v); + } + } + } } 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 +530,32 @@ impl Weights { } } +/// How an interpolation result lands in `out`: written outright, or rounded +/// into what is already there. +/// +/// `Avg` is the second list of a default-weighted bi-prediction (8.4.2.3.1): +/// the combined prediction is the rounded average of the two lists' *clipped +/// byte* predictions, so the first list interpolates straight into the +/// picture and the second averages on top of it. The average reads the same +/// bytes whether the first one arrived through a temporary or not — no +/// temporary, no combining pass, no copy back. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Put { + /// Write the prediction. + Set, + /// Average the prediction into the bytes already in `out`. + Avg, +} + +#[inline] +fn store_u8(dst: &mut u8, v: u8, put: Put) { + if put == Put::Avg { + *dst = avg(*dst, v); + } else { + *dst = v; + } +} + /// 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 +745,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 +758,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 +800,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 {