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 {
901 refs.get(self.lists[list].get(idx as usize)?)901 refs.get(self.lists[list].get(idx as usize)?)
902 }902 }
903 903
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+
904 /// Prediction weights of one component (clause 8.4.3).912 /// Prediction weights of one component (clause 8.4.3).
905 fn weights_for(913 fn weights_for(
906 &self,914 &self,
@@ -2226,13 +2234,21 @@ fn compensate(
2226 let x0 = (mb_x * 16 + px * 4) as i32;2234 let x0 = (mb_x * 16 + px * 4) as i32;
2227 let y0 = (mb_y * 16 + py * 4) as i32;2235 let y0 = (mb_y * 16 + py * 4) as i32;
2228 let (w, h) = (pw * 4, ph * 4);2236 let (w, h) = (pw * 4, ph * 4);
2229-2237+ // A stream carrying no weighted prediction at all resolves every
2230- let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1);2238+ // component to the identity weighting without the per-component lookup.
2231- // 8.4.2.3.1 over one list is the identity, so the interpolation of that one2239+ let plain = ctx.no_weights();
2232- // list IS the prediction: it is written straight into the picture at the2240+ let wt = if plain {
2233- // picture's own pitch, rather than into a temporary that is combined into a2241+ Weights::DEFAULT
2234- // second temporary and copied a third time.2242+ } else {
2235- let direct = wt.is_default() && (use0 != use1);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();
2236 let luma_ref = |list: usize| -> Result<RefPlane<'_>> {2252 let luma_ref = |list: usize| -> Result<RefPlane<'_>> {
2237 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {2253 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
2238 Error::corrupt("reference index names a picture the buffer does not hold")2254 Error::corrupt("reference index names a picture the buffer does not hold")
@@ -2248,7 +2264,32 @@ fn compensate(
2248 };2264 };
2249 let stride = pic.y.stride;2265 let stride = pic.y.stride;
2250 let origin = pic.y.at(x0 as usize, y0 as usize);2266 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 {
2252 // No scratch buffer is declared on this path at all: the scratch is2293 // No scratch buffer is declared on this path at all: the scratch is
2253 // zeroed on entry, and most partitions of a P slice come through here.2294 // zeroed on entry, and most partitions of a P slice come through here.
2254 let list = usize::from(!use0);2295 let list = usize::from(!use0);
@@ -2262,6 +2303,7 @@ fn compensate(
2262 h,2303 h,
2263 stride,2304 stride,
2264 &mut pic.y.data[origin..],2305 &mut pic.y.data[origin..],
2306+ crate::inter::Put::Set,
2265 );2307 );
2266 } else {2308 } else {
2267 let mut part = [[0u8; 256]; 2];2309 let mut part = [[0u8; 256]; 2];
@@ -2270,7 +2312,7 @@ fn compensate(
2270 continue;2312 continue;
2271 }2313 }
2272 let plane = luma_ref(list)?;2314 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);
2274 }2316 }
2275 let mut out = [0u8; 256];2317 let mut out = [0u8; 256];
2276 let (p0, p1) = part.split_at(1);2318 let (p0, p1) = part.split_at(1);
@@ -2286,8 +2328,12 @@ fn compensate(
2286 let (cw, ch) = (w / 2, h / 2);2328 let (cw, ch) = (w / 2, h / 2);
2287 let (cx0, cy0) = (x0 / 2, y0 / 2);2329 let (cx0, cy0) = (x0 / 2, y0 / 2);
2288 for comp in 0..2 {2330 for comp in 0..2 {
2289- let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1);2331+ let wt = if plain {
2290- let direct = wt.is_default() && (use0 != use1);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();
2291 let chroma_ref = |list: usize| -> RefPlane<'_> {2337 let chroma_ref = |list: usize| -> RefPlane<'_> {
2292 let rp = ctx2338 let rp = ctx
2293 .reference(refs, list, ref_idx[list])2339 .reference(refs, list, ref_idx[list])
@@ -2305,7 +2351,32 @@ fn compensate(
2305 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };2351 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2306 let stride = plane_out.stride;2352 let stride = plane_out.stride;
2307 let origin = plane_out.at(cx0 as usize, cy0 as usize);2353 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 {
2309 let list = usize::from(!use0);2380 let list = usize::from(!use0);
2310 let plane = chroma_ref(list);2381 let plane = chroma_ref(list);
2311 mc_chroma(2382 mc_chroma(
@@ -2317,6 +2388,7 @@ fn compensate(
2317 ch,2388 ch,
2318 stride,2389 stride,
2319 &mut plane_out.data[origin..],2390 &mut plane_out.data[origin..],
2391+ crate::inter::Put::Set,
2320 );2392 );
2321 } else {2393 } else {
2322 let mut cpart = [[0u8; 64]; 2];2394 let mut cpart = [[0u8; 64]; 2];
@@ -2325,7 +2397,17 @@ fn compensate(
2325 continue;2397 continue;
2326 }2398 }
2327 let plane = chroma_ref(list);2399 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+ );
2329 }2411 }
2330 let mut cout = [0u8; 64];2412 let mut cout = [0u8; 64];
2331 let (c0, c1) = cpart.split_at(1);2413 let (c0, c1) = cpart.split_at(1);
crates/ec-h264/src/enc/mb.rsmodified+6 -4
@@ -24,7 +24,7 @@ use crate::entropy::{
24 BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,24 BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
25 MbCtx, MbInfo,25 MbCtx, MbInfo,
26 };26 };
27-use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};27+use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};
28 use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};28 use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
29 use crate::pred::{29 use crate::pred::{
30 PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,30 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
863 ch,863 ch,
864 cw,864 cw,
865 &mut buf,865 &mut buf,
866+ crate::inter::Put::Set,
866 );867 );
867 let plane = if comp == 0 { &e.src.u } else { &e.src.v };868 let plane = if comp == 0 { &e.src.u } else { &e.src.v };
868 sum += satd_block(869 sum += satd_block(
@@ -910,7 +911,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I
910 );911 );
911 return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;912 return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
912 }913 }
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);
914 let d = if satd {915 let d = if satd {
915 satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)916 satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
916 } else {917 } else {
@@ -1001,7 +1002,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I
1001 let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);1002 let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
1002 let skip_cost = {1003 let skip_cost = {
1003 let mut buf = [0u8; 256];1004 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);
1005 // P_Skip's rebate is the signalling it genuinely saves. Re-measured on1006 // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
1006 // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip1007 // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
1007 // and -0.741/-0.696 on the screen capture -- the two contents disagree1008 // and -0.741/-0.696 on the screen capture -- the two contents disagree
@@ -2962,7 +2963,7 @@ fn compensate_part(
2962 };2963 };
2963 let stride = pic.y.stride;2964 let stride = pic.y.stride;
2964 let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4);2965 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);
2966 for comp in 0..2 {2967 for comp in 0..2 {
2967 let src = if comp == 0 {2968 let src = if comp == 0 {
2968 &reference.cb2969 &reference.cb
@@ -2989,6 +2990,7 @@ fn compensate_part(
2989 h / 2,2990 h / 2,
2990 stride,2991 stride,
2991 &mut dst.data[origin..],2992 &mut dst.data[origin..],
2993+ Put::Set,
2992 );2994 );
2993 }2995 }
2994 }2996 }
crates/ec-h264/src/inter.rsmodified+137 -34
@@ -124,26 +124,25 @@ fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 {
124 124
125 /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes.125 /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes.
126 #[inline]126 #[inline]
127-fn store_half8(dst: &mut [u8], v: i16x8) {127+fn store_half8(dst: &mut [u8], v: i16x8, put: Put) {
128 let c = ((v + i16x8::splat(16)) >> 5u32)128 let c = ((v + i16x8::splat(16)) >> 5u32)
129 .max(i16x8::ZERO)129 .max(i16x8::ZERO)
130 .min(i16x8::splat(255));130 .min(i16x8::splat(255));
131 for (o, &s) in dst.iter_mut().zip(c.as_array()) {131 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
132- *o = s as u8;132+ store_u8(o, s as u8, put);
133 }133 }
134 }134 }
135 135
136 /// The same over sixteen lanes.136 /// The same over sixteen lanes.
137 #[inline]137 #[inline]
138-fn store_half16(dst: &mut [u8], v: i16x16) {138+fn store_half16(dst: &mut [u8], v: i16x16, put: Put) {
139 let c = ((v + i16x16::splat(16)) >> 5u32)139 let c = ((v + i16x16::splat(16)) >> 5u32)
140 .max(i16x16::ZERO)140 .max(i16x16::ZERO)
141 .min(i16x16::splat(255));141 .min(i16x16::splat(255));
142 for (o, &s) in dst.iter_mut().zip(c.as_array()) {142 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
143- *o = s as u8;143+ store_u8(o, s as u8, put);
144 }144 }
145 }145 }
146-
147 /// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is146 /// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is
148 /// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the147 /// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the
149 /// horizontal filter, the plane stride for the vertical one.148 /// horizontal filter, the plane stride for the vertical one.
@@ -166,6 +165,7 @@ fn half_block(
166 store_half16(165 store_half16(
167 &mut dst[row * 16..row * 16 + 16],166 &mut dst[row * 16..row * 16 + 16],
168 tap6_16(data, base + row * stride, step),167 tap6_16(data, base + row * stride, step),
168+ Put::Set,
169 );169 );
170 }170 }
171 } else {171 } else {
@@ -173,6 +173,7 @@ fn half_block(
173 store_half8(173 store_half8(
174 &mut dst[row * w..row * w + w],174 &mut dst[row * w..row * w + w],
175 tap6_8(data, base + row * stride, step),175 tap6_8(data, base + row * stride, step),
176+ Put::Set,
176 );177 );
177 }178 }
178 }179 }
@@ -201,12 +202,12 @@ fn tap6_inter8(v: &[i16], at: usize, step: usize) -> i32x8 {
201 202
202 /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.203 /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.
203 #[inline]204 #[inline]
204-fn store_centre(dst: &mut [u8], v: i32x8) {205+fn store_centre(dst: &mut [u8], v: i32x8, put: Put) {
205 let c = ((v + i32x8::splat(512)) >> 10u32)206 let c = ((v + i32x8::splat(512)) >> 10u32)
206 .max(i32x8::ZERO)207 .max(i32x8::ZERO)
207 .min(i32x8::splat(255));208 .min(i32x8::splat(255));
208 for (o, &s) in dst.iter_mut().zip(c.as_array()) {209 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
209- *o = s as u8;210+ store_u8(o, s as u8, put);
210 }211 }
211 }212 }
212 213
@@ -225,27 +226,51 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) {
225 /// The same average, written into a destination of pitch `os` from two226 /// The same average, written into a destination of pitch `os` from two
226 /// `w`-pitch sources.227 /// `w`-pitch sources.
227 #[inline]228 #[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) {
229 if os == w {230 if os == w {
230- avg_rows(out, a, b, w * h);231+ avg_rows_to_contig(out, a, b, w * h, put);
231 return;232 return;
232 }233 }
233 for row in 0..h {234 for row in 0..h {
234- avg_rows(235+ avg_rows_to_contig(
235 &mut out[row * os..row * os + w],236 &mut out[row * os..row * os + w],
236 &a[row * w..],237 &a[row * w..],
237 &b[row * w..],238 &b[row * w..],
238 w,239 w,
240+ put,
239 );241 );
240 }242 }
241 }243 }
242 244
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+
243 /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch259 /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch
244-/// destination.260+/// destination, honouring `put`.
245 #[inline]261 #[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) {
247 for row in 0..h {263 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+ }
249 }274 }
250 }275 }
251 276
@@ -275,10 +300,10 @@ pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usiz
275 let yi = clamp_origin(y, h, r.height, r.pad, 2, 3);300 let yi = clamp_origin(y, h, r.height, r.pad, 2, 3);
276 r.at(xi, yi)301 r.at(xi, yi)
277 }302 }
278-303+/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition
279-/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose304+/// whose full-sample origin is `(x, y)` and whose motion vector is `mv` in
280-/// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter305+/// quarter samples. Writes `w` x `h` prediction samples into `out` at pitch
281-/// samples. Writes `w` x `h` prediction samples into `out` at pitch `os`.306+/// `os`, honouring `put` (see [`Put`]).
282 ///307 ///
283 /// The pitch is a parameter so that the single-list, default-weight case —308 /// The pitch is a parameter so that the single-list, default-weight case —
284 /// which is most of a P slice — interpolates straight into the picture instead309 /// which is most of a P slice — interpolates straight into the picture instead
@@ -293,6 +318,7 @@ pub(crate) fn mc_luma(
293 h: usize,318 h: usize,
294 os: usize,319 os: usize,
295 out: &mut [u8],320 out: &mut [u8],
321+ put: Put,
296 ) {322 ) {
297 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);323 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
298 let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3);324 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(
304 if fx == 0 && fy == 0 {330 if fx == 0 && fy == 0 {
305 for row in 0..h {331 for row in 0..h {
306 let src = base + row * stride;332 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+ }
308 }343 }
309 return;344 return;
310 }345 }
@@ -350,7 +385,7 @@ pub(crate) fn mc_luma(
350 for col in (0..w).step_by(8) {385 for col in (0..w).step_by(8) {
351 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);386 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);
352 let n = (w - col).min(8);387 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);
354 }389 }
355 }390 }
356 }391 }
@@ -359,11 +394,11 @@ pub(crate) fn mc_luma(
359 // the average of two of them. Resolving it once per partition rather than394 // the average of two of them. Resolving it once per partition rather than
360 // once per sample is what keeps the copy loops straight.395 // once per sample is what keeps the copy loops straight.
361 match (fx, fy) {396 match (fx, fy) {
362- (2, 0) => copy_rows(out, os, &bb, w, h),397+ (2, 0) => copy_rows(out, os, &bb, w, h, put),
363- (0, 2) => copy_rows(out, os, &hh, w, h),398+ (0, 2) => copy_rows(out, os, &hh, w, h, put),
364- (2, 2) => copy_rows(out, os, &jj, w, h),399+ (2, 2) => copy_rows(out, os, &jj, w, h, put),
365- (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h),400+ (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h, put),
366- (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h),401+ (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h, put),
367 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {402 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {
368 // Averaged with an integer sample one row or column over.403 // Averaged with an integer sample one row or column over.
369 let (dx, dy) = match (fx, fy) {404 let (dx, dy) = match (fx, fy) {
@@ -378,12 +413,12 @@ pub(crate) fn mc_luma(
378 let hl = &half[row * w..row * w + w];413 let hl = &half[row * w..row * w + w];
379 let dst = &mut out[row * os..row * os + w];414 let dst = &mut out[row * os..row * os + w];
380 for col in 0..w {415 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);
382 }417 }
383 }418 }
384 }419 }
385 // Diagonal quarter positions: the two nearest half samples.420 // 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),
387 }422 }
388 }423 }
389 424
@@ -403,6 +438,7 @@ fn chroma_rows<const W: usize>(
403 wt: [u16; 4],438 wt: [u16; 4],
404 os: usize,439 os: usize,
405 out: &mut [u8],440 out: &mut [u8],
441+ put: Put,
406 ) {442 ) {
407 for row in 0..h {443 for row in 0..h {
408 let src = base + row * stride;444 let src = base + row * stride;
@@ -415,7 +451,7 @@ fn chroma_rows<const W: usize>(
415 + u16::from(q[c]) * wt[2]451 + u16::from(q[c]) * wt[2]
416 + u16::from(q[c + 1]) * wt[3]452 + u16::from(q[c + 1]) * wt[3]
417 + 32;453 + 32;
418- dst[c] = (v >> 6) as u8;454+ store_u8(&mut dst[c], (v >> 6) as u8, put);
419 }455 }
420 }456 }
421 }457 }
@@ -431,6 +467,7 @@ pub(crate) fn mc_chroma(
431 h: usize,467 h: usize,
432 os: usize,468 os: usize,
433 out: &mut [u8],469 out: &mut [u8],
470+ put: Put,
434 ) {471 ) {
435 let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16);472 let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16);
436 let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1);473 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(
443 if fx == 0 && fy == 0 {480 if fx == 0 && fy == 0 {
444 for row in 0..h {481 for row in 0..h {
445 let src = base + row * stride;482 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+ }
447 }493 }
448 return;494 return;
449 }495 }
450-
451 // The four weights sum to 64, so the weighted sum of Equation 8-270 never496 // The four weights sum to 64, so the weighted sum of Equation 8-270 never
452 // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes.497 // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes.
453 let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy];498 let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy];
454 match w {499 match w {
455- 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out),500+ 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out, put),
456- 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out),501+ 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out, put),
457- _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out),502+ _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out, put),
458 }503 }
459 }504 }
460 505
@@ -485,6 +530,32 @@ impl Weights {
485 }530 }
486 }531 }
487 532
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+
488 /// Combine the list predictions of one partition into the final prediction559 /// Combine the list predictions of one partition into the final prediction
489 /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that560 /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that
490 /// is not used is ignored.561 /// is not used is ignored.
@@ -674,7 +745,7 @@ mod tests {
674 for fx in 0..4i16 {745 for fx in 0..4i16 {
675 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {746 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {
676 let mv = [fx - 20 * 4, fy + 12];747 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);
678 spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);749 spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);
679 assert_eq!(750 assert_eq!(
680 ours[..pw * ph],751 ours[..pw * ph],
@@ -687,6 +758,38 @@ mod tests {
687 }758 }
688 }759 }
689 760
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+
690 #[test]793 #[test]
691 fn chroma_interpolation_matches_equation_8_270() {794 fn chroma_interpolation_matches_equation_8_270() {
692 let (w, h, pad) = (24usize, 16usize, 16usize);795 let (w, h, pad) = (24usize, 16usize, 16usize);
@@ -697,7 +800,7 @@ mod tests {
697 for fy in 0..8i16 {800 for fy in 0..8i16 {
698 for fx in 0..8i16 {801 for fx in 0..8i16 {
699 let mv = [fx, fy];802 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);
701 for row in 0..8i32 {804 for row in 0..8i32 {
702 for col in 0..8i32 {805 for col in 0..8i32 {
703 let s = |dx: i32, dy: i32| -> i32 {806 let s = |dx: i32, dy: i32| -> i32 {