forge
Explore
Log in

Don't you dare go Hollow

Fuse the bi-predicted combining pass into motion compensation

Browse files at this commit

57ad7ebb5f36c93e2353fe4b33aadfb66b5f88a4Ahmet Kaan GümüşParent: 781bd7a
  • perf
    • fuse the bi-predicted combining pass into motion compensation
Show full message
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.rsadded+158 -0
@@ -0,0 +1,158 @@
1+//! Throwaway decode-throughput probe for lane-h264perf: raw demux+decode
2+//! Mpx/s, no render. One untimed warm pass, then best-of-N timed passes over a
3+//! decoder built fresh per pass. `--hash` FNV-1a-hashes every released frame
4+//! (display order, visible rows only) so a byte-exact A/B is a file diff.
5+//!
6+//! `.mp4` drives the registry surface (ec-mp4 demux, avcC extradata,
7+//! send_packet/receive_frame); `.264` drives the NAL surface (push_nal +
8+//! end_picture + flush), both the way the crate's own conformance suite does.
9+//!
10+//! usage: bench_decode <file.mp4|file.264> [reps] [--hash]
11+use std::time::Instant;
12+
13+use ec_core::frame::{Frame, Plane};
14+use ec_core::packet::Packet;
15+use ec_core::registry::{CodecId, Decoder as _, Demuxer as _};
16+use ec_h264::{Decoder as H264NalDecoder, H264Decoder, NalOutcome};
17+
18+/// FNV-1a 64 over the visible bytes of every plane (I420 geometry — the same
19+/// bytes conformance.rs's frame_bytes packs), plus the geometry.
20+fn hash_frame(h: &mut u64, w: u32, height: u32, planes: &[Plane]) {
21+ let mut fold = |bytes: &[u8]| {
22+ for &b in bytes {
23+ *h ^= u64::from(b);
24+ *h = h.wrapping_mul(0x100000001b3);
25+ }
26+ };
27+ fold(&w.to_le_bytes());
28+ fold(&height.to_le_bytes());
29+ let (w2, h2) = (w.div_ceil(2) as usize, height.div_ceil(2) as usize);
30+ let dims = [(w as usize, height as usize), (w2, h2), (w2, h2)];
31+ for (plane, (pw, ph)) in planes.iter().zip(dims) {
32+ for y in 0..ph {
33+ let row = plane.row(y, pw).expect("plane row");
34+ fold(row);
35+ }
36+ }
37+}
38+
39+fn decode_mp4(
40+ packets: &[Packet],
41+ params: &ec_core::registry::CodecParameters,
42+ hash: bool,
43+) -> (usize, u64, u32, u32) {
44+ let mut dec = H264Decoder::new(params.clone()).expect("h264 decoder");
45+ let mut frames = 0usize;
46+ let mut h: u64 = 0xcbf29ce484222325;
47+ let mut dims = (0u32, 0u32);
48+ for p in packets {
49+ dec.send_packet(p).expect("send_packet");
50+ while let Ok(Frame::Video(f)) = dec.receive_frame() {
51+ if hash {
52+ hash_frame(&mut h, f.width, f.height, &f.planes);
53+ }
54+ dims = (f.width, f.height);
55+ frames += 1;
56+ }
57+ }
58+ dec.flush().expect("flush");
59+ while let Ok(Frame::Video(f)) = dec.receive_frame() {
60+ if hash {
61+ hash_frame(&mut h, f.width, f.height, &f.planes);
62+ }
63+ dims = (f.width, f.height);
64+ frames += 1;
65+ }
66+ (frames, h, dims.0, dims.1)
67+}
68+
69+fn decode_annexb(bytes: &[u8], hash: bool) -> (usize, u64, u32, u32) {
70+ let mut dec = H264NalDecoder::new();
71+ let mut frames = 0usize;
72+ let mut h: u64 = 0xcbf29ce484222325;
73+ let mut dims = (0u32, 0u32);
74+ for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
75+ if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary {
76+ dec.end_picture().expect("end_picture");
77+ dec.push_nal(nal).expect("re-push");
78+ }
79+ while let Some(f) = dec.next_frame() {
80+ if hash {
81+ hash_frame(&mut h, f.width, f.height, &f.planes);
82+ }
83+ dims = (f.width, f.height);
84+ frames += 1;
85+ }
86+ }
87+ dec.flush().expect("flush");
88+ while let Some(f) = dec.next_frame() {
89+ if hash {
90+ hash_frame(&mut h, f.width, f.height, &f.planes);
91+ }
92+ dims = (f.width, f.height);
93+ frames += 1;
94+ }
95+ (frames, h, dims.0, dims.1)
96+}
97+
98+enum Source {
99+ Mp4(Vec<Packet>, ec_core::registry::CodecParameters),
100+ AnnexB(Vec<u8>),
101+}
102+
103+fn decode(src: &Source, hash: bool) -> (usize, u64, u32, u32) {
104+ match src {
105+ Source::Mp4(p, par) => decode_mp4(p, par, hash),
106+ Source::AnnexB(b) => decode_annexb(b, hash),
107+ }
108+}
109+
110+fn main() {
111+ let args: Vec<String> = std::env::args().skip(1).collect();
112+ let path = args.first().expect("usage: bench_decode <file.mp4|.264> [reps] [--hash]");
113+ let reps: u32 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(3);
114+ let hash = args.iter().any(|a| a == "--hash");
115+
116+ let src = if path.ends_with(".mp4") {
117+ let file = std::fs::File::open(path).expect("open mp4");
118+ let mut demux =
119+ ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 open");
120+ let (idx, params) = demux
121+ .streams()
122+ .iter()
123+ .find(|s| s.params.codec == CodecId::H264)
124+ .map(|s| (s.index, s.params.clone()))
125+ .expect("no H.264 track");
126+ let mut packets = Vec::new();
127+ while let Ok(p) = demux.next_packet() {
128+ if p.stream == idx {
129+ packets.push(p);
130+ }
131+ }
132+ Source::Mp4(packets, params)
133+ } else {
134+ Source::AnnexB(std::fs::read(path).expect("read annexb"))
135+ };
136+
137+ // Warm pass (untimed): page in, branch predictors, allocator pools.
138+ let (frames, h, w, height) = decode(&src, hash);
139+ assert!(frames > 0, "no frames decoded");
140+ if hash {
141+ println!("hash={h:016x} frames={frames} {w}x{height}");
142+ }
143+
144+ let px = u64::from(w) * u64::from(height) * frames as u64;
145+ let mut best = f64::MAX;
146+ for _ in 0..reps {
147+ let t = Instant::now();
148+ let r = decode(&src, false);
149+ let e = t.elapsed().as_secs_f64();
150+ assert_eq!(r.0, frames, "frame count diverged between passes");
151+ best = best.min(e);
152+ }
153+ println!(
154+ "{path}: frames={frames} px={px} best={:.1}ms over {reps} -> {:.1} Mpx/s",
155+ best * 1e3,
156+ px as f64 / best / 1e6
157+ );
158+}
crates/ec-h264/src/decoder.rsmodified+95 -13
@@ -901,6 +901,14 @@ impl SliceCtx {
901901 refs.get(self.lists[list].get(idx as usize)?)
902902 }
903903
904+ /// True when no slice-level weighting can apply at all, so every
905+ /// component of every partition resolves to [`Weights::DEFAULT`] without
906+ /// the per-component lookup: neither weighted prediction (P) nor
907+ /// weighted/bi-prediction (B) is signalled.
908+ fn no_weights(&self) -> bool {
909+ self.weighted_bipred_idc == 0 && !self.weighted_pred
910+ }
911+
904912 /// Prediction weights of one component (clause 8.4.3).
905913 fn weights_for(
906914 &self,
@@ -2226,13 +2234,21 @@ fn compensate(
22262234 let x0 = (mb_x * 16 + px * 4) as i32;
22272235 let y0 = (mb_y * 16 + py * 4) as i32;
22282236 let (w, h) = (pw * 4, ph * 4);
2229-
2230- let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1);
2231- // 8.4.2.3.1 over one list is the identity, so the interpolation of that one
2232- // list IS the prediction: it is written straight into the picture at the
2233- // picture's own pitch, rather than into a temporary that is combined into a
2234- // second temporary and copied a third time.
2235- let direct = wt.is_default() && (use0 != use1);
2237+ // A stream carrying no weighted prediction at all resolves every
2238+ // component to the identity weighting without the per-component lookup.
2239+ let plain = ctx.no_weights();
2240+ let wt = if plain {
2241+ Weights::DEFAULT
2242+ } else {
2243+ ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1)
2244+ };
2245+ // 8.4.2.3.1 over one list is the identity, so the interpolation of that
2246+ // one list IS the prediction: it is written straight into the picture at
2247+ // the picture's own pitch. Over both lists the combined prediction is the
2248+ // rounded byte average of the two clipped ones, so list 0 interpolates
2249+ // into the picture and list 1 averages on top of it (Put::Avg) — no
2250+ // temporaries, no combining pass, no copy back.
2251+ let direct = wt.is_default();
22362252 let luma_ref = |list: usize| -> Result<RefPlane<'_>> {
22372253 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
22382254 Error::corrupt("reference index names a picture the buffer does not hold")
@@ -2248,7 +2264,32 @@ fn compensate(
22482264 };
22492265 let stride = pic.y.stride;
22502266 let origin = pic.y.at(x0 as usize, y0 as usize);
2251- if direct {
2267+ if direct && use0 && use1 {
2268+ let plane = luma_ref(0)?;
2269+ mc_luma(
2270+ &plane,
2271+ x0,
2272+ y0,
2273+ mv[0],
2274+ w,
2275+ h,
2276+ stride,
2277+ &mut pic.y.data[origin..],
2278+ crate::inter::Put::Set,
2279+ );
2280+ let plane = luma_ref(1)?;
2281+ mc_luma(
2282+ &plane,
2283+ x0,
2284+ y0,
2285+ mv[1],
2286+ w,
2287+ h,
2288+ stride,
2289+ &mut pic.y.data[origin..],
2290+ crate::inter::Put::Avg,
2291+ );
2292+ } else if direct {
22522293 // No scratch buffer is declared on this path at all: the scratch is
22532294 // zeroed on entry, and most partitions of a P slice come through here.
22542295 let list = usize::from(!use0);
@@ -2262,6 +2303,7 @@ fn compensate(
22622303 h,
22632304 stride,
22642305 &mut pic.y.data[origin..],
2306+ crate::inter::Put::Set,
22652307 );
22662308 } else {
22672309 let mut part = [[0u8; 256]; 2];
@@ -2270,7 +2312,7 @@ fn compensate(
22702312 continue;
22712313 }
22722314 let plane = luma_ref(list)?;
2273- mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list]);
2315+ mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list], crate::inter::Put::Set);
22742316 }
22752317 let mut out = [0u8; 256];
22762318 let (p0, p1) = part.split_at(1);
@@ -2286,8 +2328,12 @@ fn compensate(
22862328 let (cw, ch) = (w / 2, h / 2);
22872329 let (cx0, cy0) = (x0 / 2, y0 / 2);
22882330 for comp in 0..2 {
2289- let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1);
2290- let direct = wt.is_default() && (use0 != use1);
2331+ let wt = if plain {
2332+ Weights::DEFAULT
2333+ } else {
2334+ ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1)
2335+ };
2336+ let direct = wt.is_default();
22912337 let chroma_ref = |list: usize| -> RefPlane<'_> {
22922338 let rp = ctx
22932339 .reference(refs, list, ref_idx[list])
@@ -2305,7 +2351,32 @@ fn compensate(
23052351 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
23062352 let stride = plane_out.stride;
23072353 let origin = plane_out.at(cx0 as usize, cy0 as usize);
2308- if direct {
2354+ if direct && use0 && use1 {
2355+ let plane = chroma_ref(0);
2356+ mc_chroma(
2357+ &plane,
2358+ cx0,
2359+ cy0,
2360+ mv[0],
2361+ cw,
2362+ ch,
2363+ stride,
2364+ &mut plane_out.data[origin..],
2365+ crate::inter::Put::Set,
2366+ );
2367+ let plane = chroma_ref(1);
2368+ mc_chroma(
2369+ &plane,
2370+ cx0,
2371+ cy0,
2372+ mv[1],
2373+ cw,
2374+ ch,
2375+ stride,
2376+ &mut plane_out.data[origin..],
2377+ crate::inter::Put::Avg,
2378+ );
2379+ } else if direct {
23092380 let list = usize::from(!use0);
23102381 let plane = chroma_ref(list);
23112382 mc_chroma(
@@ -2317,6 +2388,7 @@ fn compensate(
23172388 ch,
23182389 stride,
23192390 &mut plane_out.data[origin..],
2391+ crate::inter::Put::Set,
23202392 );
23212393 } else {
23222394 let mut cpart = [[0u8; 64]; 2];
@@ -2325,7 +2397,17 @@ fn compensate(
23252397 continue;
23262398 }
23272399 let plane = chroma_ref(list);
2328- mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, cw, &mut cpart[list]);
2400+ mc_chroma(
2401+ &plane,
2402+ cx0,
2403+ cy0,
2404+ mv[list],
2405+ cw,
2406+ ch,
2407+ cw,
2408+ &mut cpart[list],
2409+ crate::inter::Put::Set,
2410+ );
23292411 }
23302412 let mut cout = [0u8; 64];
23312413 let (c0, c1) = cpart.split_at(1);
crates/ec-h264/src/enc/mb.rsmodified+6 -4
@@ -24,7 +24,7 @@ use crate::entropy::{
2424 BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
2525 MbCtx, MbInfo,
2626 };
27-use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};
27+use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};
2828 use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
2929 use crate::pred::{
3030 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<I
863863 ch,
864864 cw,
865865 &mut buf,
866+ crate::inter::Put::Set,
866867 );
867868 let plane = if comp == 0 { &e.src.u } else { &e.src.v };
868869 sum += satd_block(
@@ -910,7 +911,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I
910911 );
911912 return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
912913 }
913- mc_luma(&plane, x0 as i32, y0 as i32, mv, w, h, w, &mut buf);
914+ mc_luma(&plane, x0 as i32, y0 as i32, mv, w, h, w, &mut buf, crate::inter::Put::Set);
914915 let d = if satd {
915916 satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
916917 } else {
@@ -1001,7 +1002,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I
10011002 let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
10021003 let skip_cost = {
10031004 let mut buf = [0u8; 256];
1004- mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf);
1005+ mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf, Put::Set);
10051006 // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
10061007 // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
10071008 // and -0.741/-0.696 on the screen capture -- the two contents disagree
@@ -2962,7 +2963,7 @@ fn compensate_part(
29622963 };
29632964 let stride = pic.y.stride;
29642965 let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4);
2965- mc_luma(&plane, x0, y0, mv, w, h, stride, &mut pic.y.data[origin..]);
2966+ mc_luma(&plane, x0, y0, mv, w, h, stride, &mut pic.y.data[origin..], Put::Set);
29662967 for comp in 0..2 {
29672968 let src = if comp == 0 {
29682969 &reference.cb
@@ -2989,6 +2990,7 @@ fn compensate_part(
29892990 h / 2,
29902991 stride,
29912992 &mut dst.data[origin..],
2993+ Put::Set,
29922994 );
29932995 }
29942996 }
crates/ec-h264/src/inter.rsmodified+137 -34
@@ -124,26 +124,25 @@ fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 {
124124
125125 /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes.
126126 #[inline]
127-fn store_half8(dst: &mut [u8], v: i16x8) {
127+fn store_half8(dst: &mut [u8], v: i16x8, put: Put) {
128128 let c = ((v + i16x8::splat(16)) >> 5u32)
129129 .max(i16x8::ZERO)
130130 .min(i16x8::splat(255));
131131 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
132- *o = s as u8;
132+ store_u8(o, s as u8, put);
133133 }
134134 }
135135
136136 /// The same over sixteen lanes.
137137 #[inline]
138-fn store_half16(dst: &mut [u8], v: i16x16) {
138+fn store_half16(dst: &mut [u8], v: i16x16, put: Put) {
139139 let c = ((v + i16x16::splat(16)) >> 5u32)
140140 .max(i16x16::ZERO)
141141 .min(i16x16::splat(255));
142142 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
143- *o = s as u8;
143+ store_u8(o, s as u8, put);
144144 }
145145 }
146-
147146 /// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is
148147 /// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the
149148 /// horizontal filter, the plane stride for the vertical one.
@@ -166,6 +165,7 @@ fn half_block(
166165 store_half16(
167166 &mut dst[row * 16..row * 16 + 16],
168167 tap6_16(data, base + row * stride, step),
168+ Put::Set,
169169 );
170170 }
171171 } else {
@@ -173,6 +173,7 @@ fn half_block(
173173 store_half8(
174174 &mut dst[row * w..row * w + w],
175175 tap6_8(data, base + row * stride, step),
176+ Put::Set,
176177 );
177178 }
178179 }
@@ -201,12 +202,12 @@ fn tap6_inter8(v: &[i16], at: usize, step: usize) -> i32x8 {
201202
202203 /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.
203204 #[inline]
204-fn store_centre(dst: &mut [u8], v: i32x8) {
205+fn store_centre(dst: &mut [u8], v: i32x8, put: Put) {
205206 let c = ((v + i32x8::splat(512)) >> 10u32)
206207 .max(i32x8::ZERO)
207208 .min(i32x8::splat(255));
208209 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
209- *o = s as u8;
210+ store_u8(o, s as u8, put);
210211 }
211212 }
212213
@@ -225,27 +226,51 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) {
225226 /// The same average, written into a destination of pitch `os` from two
226227 /// `w`-pitch sources.
227228 #[inline]
228-fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize) {
229+fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize, put: Put) {
229230 if os == w {
230- avg_rows(out, a, b, w * h);
231+ avg_rows_to_contig(out, a, b, w * h, put);
231232 return;
232233 }
233234 for row in 0..h {
234- avg_rows(
235+ avg_rows_to_contig(
235236 &mut out[row * os..row * os + w],
236237 &a[row * w..],
237238 &b[row * w..],
238239 w,
240+ put,
239241 );
240242 }
241243 }
242244
245+/// The average over contiguous equal-length slices, honouring `put`.
246+#[inline]
247+fn avg_rows_to_contig(out: &mut [u8], a: &[u8], b: &[u8], n: usize, put: Put) {
248+ match put {
249+ Put::Set => avg_rows(out, a, b, n),
250+ Put::Avg => {
251+ let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
252+ for i in 0..n {
253+ out[i] = avg(avg(a[i], b[i]), out[i]);
254+ }
255+ }
256+ }
257+}
258+
243259 /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch
244-/// destination.
260+/// destination, honouring `put`.
245261 #[inline]
246-fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize) {
262+fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize, put: Put) {
247263 for row in 0..h {
248- out[row * os..row * os + w].copy_from_slice(&src[row * w..row * w + w]);
264+ let dst = &mut out[row * os..row * os + w];
265+ let src = &src[row * w..row * w + w];
266+ match put {
267+ Put::Set => dst.copy_from_slice(src),
268+ Put::Avg => {
269+ for (d, &s) in dst.iter_mut().zip(src) {
270+ *d = avg(*d, s);
271+ }
272+ }
273+ }
249274 }
250275 }
251276
@@ -275,10 +300,10 @@ pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usiz
275300 let yi = clamp_origin(y, h, r.height, r.pad, 2, 3);
276301 r.at(xi, yi)
277302 }
278-
279-/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose
280-/// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter
281-/// samples. Writes `w` x `h` prediction samples into `out` at pitch `os`.
303+/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition
304+/// whose full-sample origin is `(x, y)` and whose motion vector is `mv` in
305+/// quarter samples. Writes `w` x `h` prediction samples into `out` at pitch
306+/// `os`, honouring `put` (see [`Put`]).
282307 ///
283308 /// The pitch is a parameter so that the single-list, default-weight case —
284309 /// which is most of a P slice — interpolates straight into the picture instead
@@ -293,6 +318,7 @@ pub(crate) fn mc_luma(
293318 h: usize,
294319 os: usize,
295320 out: &mut [u8],
321+ put: Put,
296322 ) {
297323 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
298324 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(
304330 if fx == 0 && fy == 0 {
305331 for row in 0..h {
306332 let src = base + row * stride;
307- out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
333+ let dst = &mut out[row * os..row * os + w];
334+ let s = &r.data[src..src + w];
335+ match put {
336+ Put::Set => dst.copy_from_slice(s),
337+ Put::Avg => {
338+ for (d, &v) in dst.iter_mut().zip(s) {
339+ *d = avg(*d, v);
340+ }
341+ }
342+ }
308343 }
309344 return;
310345 }
@@ -350,7 +385,7 @@ pub(crate) fn mc_luma(
350385 for col in (0..w).step_by(8) {
351386 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);
352387 let n = (w - col).min(8);
353- store_centre(&mut jj[row * w + col..row * w + col + n], v);
388+ store_centre(&mut jj[row * w + col..row * w + col + n], v, Put::Set);
354389 }
355390 }
356391 }
@@ -359,11 +394,11 @@ pub(crate) fn mc_luma(
359394 // the average of two of them. Resolving it once per partition rather than
360395 // once per sample is what keeps the copy loops straight.
361396 match (fx, fy) {
362- (2, 0) => copy_rows(out, os, &bb, w, h),
363- (0, 2) => copy_rows(out, os, &hh, w, h),
364- (2, 2) => copy_rows(out, os, &jj, w, h),
365- (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h),
366- (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h),
397+ (2, 0) => copy_rows(out, os, &bb, w, h, put),
398+ (0, 2) => copy_rows(out, os, &hh, w, h, put),
399+ (2, 2) => copy_rows(out, os, &jj, w, h, put),
400+ (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h, put),
401+ (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h, put),
367402 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {
368403 // Averaged with an integer sample one row or column over.
369404 let (dx, dy) = match (fx, fy) {
@@ -378,12 +413,12 @@ pub(crate) fn mc_luma(
378413 let hl = &half[row * w..row * w + w];
379414 let dst = &mut out[row * os..row * os + w];
380415 for col in 0..w {
381- dst[col] = avg(s[col], hl[col]);
416+ store_u8(&mut dst[col], avg(s[col], hl[col]), put);
382417 }
383418 }
384419 }
385420 // Diagonal quarter positions: the two nearest half samples.
386- _ => avg_rows_to(out, os, &bb, &hh, w, h),
421+ _ => avg_rows_to(out, os, &bb, &hh, w, h, put),
387422 }
388423 }
389424
@@ -403,6 +438,7 @@ fn chroma_rows<const W: usize>(
403438 wt: [u16; 4],
404439 os: usize,
405440 out: &mut [u8],
441+ put: Put,
406442 ) {
407443 for row in 0..h {
408444 let src = base + row * stride;
@@ -415,7 +451,7 @@ fn chroma_rows<const W: usize>(
415451 + u16::from(q[c]) * wt[2]
416452 + u16::from(q[c + 1]) * wt[3]
417453 + 32;
418- dst[c] = (v >> 6) as u8;
454+ store_u8(&mut dst[c], (v >> 6) as u8, put);
419455 }
420456 }
421457 }
@@ -431,6 +467,7 @@ pub(crate) fn mc_chroma(
431467 h: usize,
432468 os: usize,
433469 out: &mut [u8],
470+ put: Put,
434471 ) {
435472 let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16);
436473 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(
443480 if fx == 0 && fy == 0 {
444481 for row in 0..h {
445482 let src = base + row * stride;
446- out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
483+ let dst = &mut out[row * os..row * os + w];
484+ let s = &r.data[src..src + w];
485+ match put {
486+ Put::Set => dst.copy_from_slice(s),
487+ Put::Avg => {
488+ for (d, &v) in dst.iter_mut().zip(s) {
489+ *d = avg(*d, v);
490+ }
491+ }
492+ }
447493 }
448494 return;
449495 }
450-
451496 // The four weights sum to 64, so the weighted sum of Equation 8-270 never
452497 // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes.
453498 let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy];
454499 match w {
455- 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out),
456- 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out),
457- _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out),
500+ 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out, put),
501+ 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out, put),
502+ _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out, put),
458503 }
459504 }
460505
@@ -485,6 +530,32 @@ impl Weights {
485530 }
486531 }
487532
533+/// How an interpolation result lands in `out`: written outright, or rounded
534+/// into what is already there.
535+///
536+/// `Avg` is the second list of a default-weighted bi-prediction (8.4.2.3.1):
537+/// the combined prediction is the rounded average of the two lists' *clipped
538+/// byte* predictions, so the first list interpolates straight into the
539+/// picture and the second averages on top of it. The average reads the same
540+/// bytes whether the first one arrived through a temporary or not — no
541+/// temporary, no combining pass, no copy back.
542+#[derive(Clone, Copy, PartialEq, Eq)]
543+pub(crate) enum Put {
544+ /// Write the prediction.
545+ Set,
546+ /// Average the prediction into the bytes already in `out`.
547+ Avg,
548+}
549+
550+#[inline]
551+fn store_u8(dst: &mut u8, v: u8, put: Put) {
552+ if put == Put::Avg {
553+ *dst = avg(*dst, v);
554+ } else {
555+ *dst = v;
556+ }
557+}
558+
488559 /// Combine the list predictions of one partition into the final prediction
489560 /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that
490561 /// is not used is ignored.
@@ -674,7 +745,7 @@ mod tests {
674745 for fx in 0..4i16 {
675746 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {
676747 let mv = [fx - 20 * 4, fy + 12];
677- mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours);
748+ mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours, Put::Set);
678749 spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);
679750 assert_eq!(
680751 ours[..pw * ph],
@@ -687,6 +758,38 @@ mod tests {
687758 }
688759 }
689760
761+ /// `Put::Avg` turns `mc_luma` into the second half of a default-weighted
762+ /// bi-prediction: averaging into the first list's bytes is bit-exact with
763+ /// running the combining pass over the two clipped predictions (8.4.2.3.1).
764+ #[test]
765+ fn avg_mode_matches_the_combining_pass() {
766+ let (w, h, pad) = (48usize, 32usize, 32usize);
767+ let (data, stride, origin) = ramp_plane(w, h, pad);
768+ let r = plane(&data, stride, origin, w, h, pad);
769+ let mut fused = [0u8; 256];
770+ let mut p0 = [0u8; 256];
771+ let mut p1 = [0u8; 256];
772+ let mut out = [0u8; 256];
773+ for mv0 in [[0i16; 2], [7, -3], [-41, 22]] {
774+ for mv1 in [[2i16; 2], [5, 1], [-13, 9]] {
775+ for &(pw, ph) in &[(16usize, 16usize), (8, 8), (4, 4)] {
776+ mc_luma(&r, 4, 4, mv0, pw, ph, pw, &mut p0, Put::Set);
777+ mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut p1, Put::Set);
778+ combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, pw * ph);
779+ // The fused shape: first list into the picture, second
780+ // averaged on top of it.
781+ fused[..pw * ph].copy_from_slice(&p0[..pw * ph]);
782+ mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut fused, Put::Avg);
783+ assert_eq!(
784+ fused[..pw * ph],
785+ out[..pw * ph],
786+ "mv {mv0:?} + {mv1:?} {pw}x{ph}"
787+ );
788+ }
789+ }
790+ }
791+ }
792+
690793 #[test]
691794 fn chroma_interpolation_matches_equation_8_270() {
692795 let (w, h, pad) = (24usize, 16usize, 16usize);
@@ -697,7 +800,7 @@ mod tests {
697800 for fy in 0..8i16 {
698801 for fx in 0..8i16 {
699802 let mv = [fx, fy];
700- mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours);
803+ mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours, Put::Set);
701804 for row in 0..8i32 {
702805 for col in 0..8i32 {
703806 let s = |dx: i32, dy: i32| -> i32 {