forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h264perf' (f24daaff): ec-h264 decode closes the B-frame CABAC gap 0.78 -> 0.930 vs rusty (4K +17.2%, 1080p Main +18.8%, 1440p +5.7%) -- bipred combining fused into MC (default + weighted paths per 8.4.2.3.1/8.4.2.3.2), CABAC renorm bulk-read, zero-fill bit supply; reviewer-caught defect fixed before merge: explicit-weight bipred chroma combines with CHROMA weights (per-component, witness fails pre-fix); golden FNV-1a hashes identical on all five fixture classes on both machines

Browse files at this commit

d5d7c0a0b70bedc1d66acb0447c8eb19e6ce4b89Ahmet Kaan GümüşParent: 2ef29da1b55d6c
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/bits.rsmodified+37 -0
@@ -132,6 +132,43 @@ impl<'a> BitCursor<'a> {
132 Ok(v)132 Ok(v)
133 }133 }
134 134
135+ /// Read `n` bits (`n <= 32`) MSB-first, zero-filled past the end of the
136+ /// stream — the CABAC engine's supply contract (see the module note in
137+ /// `cabac.rs`): a conformant stream never depends on those bits, and the
138+ /// phantom reads do not advance `bit_position` beyond the real ones.
139+ #[inline]
140+ pub fn bits_zero_fill(&mut self, n: u32) -> u32 {
141+ debug_assert!(n <= 32);
142+ if n == 0 {
143+ return 0;
144+ }
145+ if self.cached < n {
146+ self.refill();
147+ }
148+ if self.cached >= n {
149+ let v = (self.cache >> (64 - n)) as u32;
150+ self.cache <<= n;
151+ self.cached -= n;
152+ return v;
153+ }
154+ // Genuinely past the end: consume what is cached, zero-fill the rest.
155+ let have = self.cached;
156+ let v = if have == 0 {
157+ 0
158+ } else {
159+ ((self.cache >> (64 - have)) as u32) << (n - have)
160+ };
161+ self.cache <<= have;
162+ self.cached = 0;
163+ v
164+ }
165+
166+ /// One bit, zero-filled past the end (see [`bits_zero_fill`]).
167+ #[inline]
168+ pub fn bit_zero_fill(&mut self) -> u32 {
169+ self.bits_zero_fill(1)
170+ }
171+
135 /// Count leading zero bits up to and including the terminating one bit172 /// Count leading zero bits up to and including the terminating one bit
136 /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros.173 /// (level_prefix / exp-Golomb prefix). Capped at `cap` zeros.
137 #[inline]174 #[inline]
crates/ec-h264/src/cabac.rsmodified+16 -11
@@ -188,16 +188,20 @@ impl<'a> Cabac<'a> {
188 /// One bit of slice data; zero past the end (see the module note).188 /// One bit of slice data; zero past the end (see the module note).
189 #[inline]189 #[inline]
190 fn bit(&mut self) -> u32 {190 fn bit(&mut self) -> u32 {
191- u32::from(self.r.read_bit().unwrap_or(false))191+ self.r.bit_zero_fill()
192 }192 }
193 193
194 /// 9.3.3.2.2 RenormD.194 /// 9.3.3.2.2 RenormD.
195+ ///
196+ /// codIRange is at most 510, so the number of doublings the loop form
197+ /// would take is `leading_zeros - 23` — zero when no renorm is due. One
198+ /// bulk read replaces the per-bit supply, and the position accounting of
199+ /// the zero-filled read matches the loop's bit-by-bit one exactly.
195 #[inline]200 #[inline]
196 fn renorm(&mut self) {201 fn renorm(&mut self) {
197- while self.range < 256 {202+ let shifts = self.range.leading_zeros() - 23;
198- self.range <<= 1;203+ self.range <<= shifts;
199- self.offset = (self.offset << 1) | self.bit();204+ self.offset = (self.offset << shifts) | self.r.bits_zero_fill(shifts);
200- }
201 }205 }
202 206
203 /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1.207 /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1.
@@ -787,15 +791,16 @@ impl<'a> Cabac<'a> {
787 4.min(1 + num_eq1) as usize791 4.min(1 + num_eq1) as usize
788 };792 };
789 let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;793 let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;
790- // Prefix: TU with cMax = uCoff = 14.794+ // Prefix: TU with cMax = uCoff = 14. The first bin reads the
795+ // inc0 context, every later one the inc1 context, so the two
796+ // spellings are hoisted out of the loop.
791 let mut prefix = 0u32;797 let mut prefix = 0u32;
792- while prefix < 14 {798+ if self.decision(abs_base + inc0) {
793- let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };799+ prefix = 1;
794- if !self.decision(ctx_idx) {800+ while prefix < 14 && self.decision(abs_base + inc1) {
795- break;
796- }
797 prefix += 1;801 prefix += 1;
798 }802 }
803+ }
799 let abs_minus1 = if prefix < 14 {804 let abs_minus1 = if prefix < 14 {
800 prefix805 prefix
801 } else {806 } else {
crates/ec-h264/src/decoder.rsmodified+312 -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,46 @@ 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+ // Weighted bi-prediction fuses the same way: the combining formula is
2268+ // per-sample, so list 0 lands in the picture and list 1 combines on top
2269+ // of it (Put::AvgW) with 8.4.2.3.2's exact integers.
2270+ let weighted_put = if !direct && use0 && use1 {
2271+ Some(crate::inter::Put::AvgW {
2272+ w0: wt.w[0],
2273+ w1: wt.w[1],
2274+ shift: (wt.log_wd + 1) as u32,
2275+ round: 1 << wt.log_wd,
2276+ off: (wt.o[0] + wt.o[1] + 1) >> 1,
2277+ })
2278+ } else {
2279+ None
2280+ };
2281+ if direct && use0 && use1 {
2282+ let plane = luma_ref(0)?;
2283+ mc_luma(
2284+ &plane,
2285+ x0,
2286+ y0,
2287+ mv[0],
2288+ w,
2289+ h,
2290+ stride,
2291+ &mut pic.y.data[origin..],
2292+ crate::inter::Put::Set,
2293+ );
2294+ let plane = luma_ref(1)?;
2295+ mc_luma(
2296+ &plane,
2297+ x0,
2298+ y0,
2299+ mv[1],
2300+ w,
2301+ h,
2302+ stride,
2303+ &mut pic.y.data[origin..],
2304+ crate::inter::Put::Avg,
2305+ );
2306+ } else if direct {
2252 // No scratch buffer is declared on this path at all: the scratch is2307 // 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.2308 // zeroed on entry, and most partitions of a P slice come through here.
2254 let list = usize::from(!use0);2309 let list = usize::from(!use0);
@@ -2262,6 +2317,32 @@ fn compensate(
2262 h,2317 h,
2263 stride,2318 stride,
2264 &mut pic.y.data[origin..],2319 &mut pic.y.data[origin..],
2320+ crate::inter::Put::Set,
2321+ );
2322+ } else if let Some(put) = weighted_put {
2323+ let plane = luma_ref(0)?;
2324+ mc_luma(
2325+ &plane,
2326+ x0,
2327+ y0,
2328+ mv[0],
2329+ w,
2330+ h,
2331+ stride,
2332+ &mut pic.y.data[origin..],
2333+ crate::inter::Put::Set,
2334+ );
2335+ let plane = luma_ref(1)?;
2336+ mc_luma(
2337+ &plane,
2338+ x0,
2339+ y0,
2340+ mv[1],
2341+ w,
2342+ h,
2343+ stride,
2344+ &mut pic.y.data[origin..],
2345+ put,
2265 );2346 );
2266 } else {2347 } else {
2267 let mut part = [[0u8; 256]; 2];2348 let mut part = [[0u8; 256]; 2];
@@ -2270,7 +2351,7 @@ fn compensate(
2270 continue;2351 continue;
2271 }2352 }
2272 let plane = luma_ref(list)?;2353 let plane = luma_ref(list)?;
2273- mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list]);2354+ mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list], crate::inter::Put::Set);
2274 }2355 }
2275 let mut out = [0u8; 256];2356 let mut out = [0u8; 256];
2276 let (p0, p1) = part.split_at(1);2357 let (p0, p1) = part.split_at(1);
@@ -2286,8 +2367,26 @@ fn compensate(
2286 let (cw, ch) = (w / 2, h / 2);2367 let (cw, ch) = (w / 2, h / 2);
2287 let (cx0, cy0) = (x0 / 2, y0 / 2);2368 let (cx0, cy0) = (x0 / 2, y0 / 2);
2288 for comp in 0..2 {2369 for comp in 0..2 {
2289- let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1);2370+ let wt = if plain {
2290- let direct = wt.is_default() && (use0 != use1);2371+ Weights::DEFAULT
2372+ } else {
2373+ ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1)
2374+ };
2375+ let direct = wt.is_default();
2376+ // The combining weights are per-component syntax (luma and chroma
2377+ // carry their own denoms, weights and offsets), so this component's
2378+ // fused mode is built from ITS OWN lookup — never the luma one.
2379+ let weighted_put = if !direct && use0 && use1 {
2380+ Some(crate::inter::Put::AvgW {
2381+ w0: wt.w[0],
2382+ w1: wt.w[1],
2383+ shift: (wt.log_wd + 1) as u32,
2384+ round: 1 << wt.log_wd,
2385+ off: (wt.o[0] + wt.o[1] + 1) >> 1,
2386+ })
2387+ } else {
2388+ None
2389+ };
2291 let chroma_ref = |list: usize| -> RefPlane<'_> {2390 let chroma_ref = |list: usize| -> RefPlane<'_> {
2292 let rp = ctx2391 let rp = ctx
2293 .reference(refs, list, ref_idx[list])2392 .reference(refs, list, ref_idx[list])
@@ -2305,7 +2404,57 @@ fn compensate(
2305 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };2404 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2306 let stride = plane_out.stride;2405 let stride = plane_out.stride;
2307 let origin = plane_out.at(cx0 as usize, cy0 as usize);2406 let origin = plane_out.at(cx0 as usize, cy0 as usize);
2308- if direct {2407+ if direct && use0 && use1 {
2408+ let plane = chroma_ref(0);
2409+ mc_chroma(
2410+ &plane,
2411+ cx0,
2412+ cy0,
2413+ mv[0],
2414+ cw,
2415+ ch,
2416+ stride,
2417+ &mut plane_out.data[origin..],
2418+ crate::inter::Put::Set,
2419+ );
2420+ let plane = chroma_ref(1);
2421+ mc_chroma(
2422+ &plane,
2423+ cx0,
2424+ cy0,
2425+ mv[1],
2426+ cw,
2427+ ch,
2428+ stride,
2429+ &mut plane_out.data[origin..],
2430+ crate::inter::Put::Avg,
2431+ );
2432+ } else if let Some(put) = weighted_put {
2433+ let plane = chroma_ref(0);
2434+ mc_chroma(
2435+ &plane,
2436+ cx0,
2437+ cy0,
2438+ mv[0],
2439+ cw,
2440+ ch,
2441+ stride,
2442+ &mut plane_out.data[origin..],
2443+ crate::inter::Put::Set,
2444+ );
2445+ let plane = chroma_ref(1);
2446+ mc_chroma(
2447+ &plane,
2448+ cx0,
2449+ cy0,
2450+ mv[1],
2451+ cw,
2452+ ch,
2453+ stride,
2454+ &mut plane_out.data[origin..],
2455+ put,
2456+ );
2457+ } else if direct {
2309 let list = usize::from(!use0);2458 let list = usize::from(!use0);
2310 let plane = chroma_ref(list);2459 let plane = chroma_ref(list);
2311 mc_chroma(2460 mc_chroma(
@@ -2317,6 +2466,7 @@ fn compensate(
2317 ch,2466 ch,
2318 stride,2467 stride,
2319 &mut plane_out.data[origin..],2468 &mut plane_out.data[origin..],
2469+ crate::inter::Put::Set,
2320 );2470 );
2321 } else {2471 } else {
2322 let mut cpart = [[0u8; 64]; 2];2472 let mut cpart = [[0u8; 64]; 2];
@@ -2325,7 +2475,17 @@ fn compensate(
2325 continue;2475 continue;
2326 }2476 }
2327 let plane = chroma_ref(list);2477 let plane = chroma_ref(list);
2328- mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, cw, &mut cpart[list]);2478+ mc_chroma(
2479+ &plane,
2480+ cx0,
2481+ cy0,
2482+ mv[list],
2483+ cw,
2484+ ch,
2485+ cw,
2486+ &mut cpart[list],
2487+ crate::inter::Put::Set,
2488+ );
2329 }2489 }
2330 let mut cout = [0u8; 64];2490 let mut cout = [0u8; 64];
2331 let (c0, c1) = cpart.split_at(1);2491 let (c0, c1) = cpart.split_at(1);
@@ -2817,3 +2977,142 @@ fn boundary_strength(
2817 };2977 };
2818 bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0)2978 bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0)
2819 }2979 }
2980+
2981+#[cfg(test)]
2982+mod tests {
2983+ use super::*;
2984+ use crate::dpb::RefList;
2985+ use ec_h264_syntax::{PredWeightTable, WeightEntry};
2986+
2987+ /// A picture whose visible samples are a fixed ramp, borders replicated.
2988+ fn ramp_picture(value: impl Fn(usize, usize) -> u8) -> Picture {
2989+ let mut pic = Picture::default();
2990+ pic.mb_w = 1;
2991+ pic.mb_h = 1;
2992+ for (plane, size) in [(0usize, 16usize), (1, 8), (2, 8)] {
2993+ let p = match plane {
2994+ 0 => &mut pic.y,
2995+ 1 => &mut pic.cb,
2996+ _ => &mut pic.cr,
2997+ };
2998+ let pad = 8;
2999+ let stride = size + 2 * pad;
3000+ let mut data = vec![0u8; stride * (size + 2 * pad)];
3001+ for y in 0..size {
3002+ for x in 0..size {
3003+ data[(pad + y) * stride + pad + x] = value(x, y);
3004+ }
3005+ }
3006+ *p = Plane8 {
3007+ data,
3008+ stride,
3009+ origin: pad * stride + pad,
3010+ width: size,
3011+ height: size,
3012+ pad,
3013+ };
3014+ p.extend_borders();
3015+ }
3016+ pic
3017+ }
3018+
3019+ fn plane_byte(p: &Plane8, x: usize, y: usize) -> u8 {
3020+ p.data[p.origin + y * p.stride + x]
3021+ }
3022+
3023+ /// Explicit-weight bipred combines each component with ITS OWN weights:
3024+ /// luma and chroma signal independent denoms/weights/offsets, so chroma
3025+ /// must never ride the luma lookup (regression guard for the fused
3026+ /// weighted path in [`compensate`]).
3027+ #[test]
3028+ fn weighted_bipred_combines_per_component() {
3029+ let refs = vec![
3030+ ramp_picture(|x, y| (40 + x * 3 + y) as u8),
3031+ ramp_picture(|x, y| (220 - x - y * 2) as u8),
3032+ ];
3033+ let mut l0 = RefList::default();
3034+ l0.push(0);
3035+ let mut l1 = RefList::default();
3036+ l1.push(1);
3037+ let ctx = SliceCtx {
3038+ slice_id: 0,
3039+ slice_type: SliceType::B,
3040+ qp: 30,
3041+ cb_qp_offset: 0,
3042+ cr_qp_offset: 0,
3043+ transform_8x8_mode: false,
3044+ constrained_intra_pred: false,
3045+ qp_delta_inc: 0,
3046+ lists: [l0, l1],
3047+ num_ref_idx: [1, 1],
3048+ direct_spatial: true,
3049+ direct_8x8_inference: true,
3050+ weighted_pred: false,
3051+ weighted_bipred_idc: 1,
3052+ weights: Some(PredWeightTable {
3053+ luma_log2_weight_denom: 1,
3054+ chroma_log2_weight_denom: 2,
3055+ l0: vec![WeightEntry {
3056+ luma: Some((2, 1)),
3057+ chroma: Some([(5, 2), (7, 3)]),
3058+ }],
3059+ l1: vec![WeightEntry {
3060+ luma: Some((2, 1)),
3061+ chroma: Some([(5, 2), (7, 3)]),
3062+ }],
3063+ }),
3064+ poc: 4,
3065+ shapes: MbShapes::default(),
3066+ };
3067+ let mut pic = ramp_picture(|_, _| 0);
3068+
3069+ compensate(&mut pic, &refs, &ctx, 0, 0, 0, 0, 4, 4, [[0, 0]; 2], [0, 0])
3070+ .expect("compensate");
3071+
3072+ let expected = |p0: u8, p1: u8, w: i32, log_wd: u32, o: i32| -> u8 {
3073+ let v = (((i32::from(p0) * w + i32::from(p1) * w + (1 << log_wd))
3074+ >> (log_wd + 1))
3075+ + o)
3076+ .clamp(0, 255);
3077+ v as u8
3078+ };
3079+ // Luma: weights (2, 1) — whatever luma does is the luma reference
3080+ // behaviour; the point is chroma below.
3081+ for y in 0..16 {
3082+ for x in 0..16 {
3083+ let (p0, p1) = (
3084+ plane_byte(&refs[0].y, x, y),
3085+ plane_byte(&refs[1].y, x, y),
3086+ );
3087+ assert_eq!(
3088+ plane_byte(&pic.y, x, y),
3089+ expected(p0, p1, 2, 1, 1),
3090+ "luma ({x},{y})"
3091+ );
3092+ }
3093+ }
3094+ // Chroma Cb: weights (5, 2) with denom 2 — NOT the luma weights.
3095+ for y in 0..8 {
3096+ for x in 0..8 {
3097+ let (p0, p1) = (
3098+ plane_byte(&refs[0].cb, x, y),
3099+ plane_byte(&refs[1].cb, x, y),
3100+ );
3101+ assert_eq!(
3102+ plane_byte(&pic.cb, x, y),
3103+ expected(p0, p1, 5, 2, 2),
3104+ "cb ({x},{y})"
3105+ );
3106+ let (p0, p1) = (
3107+ plane_byte(&refs[0].cr, x, y),
3108+ plane_byte(&refs[1].cr, x, y),
3109+ );
3110+ assert_eq!(
3111+ plane_byte(&pic.cr, x, y),
3112+ expected(p0, p1, 7, 2, 3),
3113+ "cr ({x},{y})"
3114+ );
3115+ }
3116+ }
3117+ }
3118+}
crates/ec-h264/src/dpb.rsmodified+6 -2
@@ -83,7 +83,9 @@ impl Plane8 {
83 /// Replicate the edge samples into the padding, which turns the per-sample83 /// Replicate the edge samples into the padding, which turns the per-sample
84 /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see84 /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see
85 /// [`crate::inter`]).85 /// [`crate::inter`]).
86- fn extend_borders(&mut self) {86+ /// Replicate edge samples into the border; also the setup decoder tests
87+ /// need for planes that inter::RefPlane reads.
88+ pub(crate) fn extend_borders(&mut self) {
87 let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride);89 let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride);
88 for y in 0..h {90 for y in 0..h {
89 let row = self.origin + y * stride;91 let row = self.origin + y * stride;
@@ -307,7 +309,9 @@ impl RefList {
307 (idx < self.len).then(|| usize::from(self.entries[idx]))309 (idx < self.len).then(|| usize::from(self.entries[idx]))
308 }310 }
309 311
310- fn push(&mut self, idx: usize) {312+ /// Append one DPB index; also the constructor decoder tests need to name
313+ /// a non-empty reference list.
314+ pub(crate) fn push(&mut self, idx: usize) {
311 if self.len < self.entries.len() {315 if self.len < self.entries.len() {
312 self.entries[self.len] = idx as u8;316 self.entries[self.len] = idx as u8;
313 self.len += 1;317 self.len += 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+358 -28
@@ -124,26 +124,65 @@ 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+ match put {
132+ Put::Set => {
131 for (o, &s) in dst.iter_mut().zip(c.as_array()) {133 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
132 *o = s as u8;134 *o = s as u8;
133 }135 }
134 }136 }
137+ Put::Avg => {
138+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
139+ *o = avg(*o, s as u8);
140+ }
141+ }
142+ Put::AvgW {
143+ w0,
144+ w1,
145+ shift,
146+ round,
147+ off,
148+ } => {
149+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
150+ store_weighted(o, s as u8, w0, w1, shift, round, off);
151+ }
152+ }
153+ }
154+}
135 155
136 /// The same over sixteen lanes.156 /// The same over sixteen lanes.
137 #[inline]157 #[inline]
138-fn store_half16(dst: &mut [u8], v: i16x16) {158+fn store_half16(dst: &mut [u8], v: i16x16, put: Put) {
139 let c = ((v + i16x16::splat(16)) >> 5u32)159 let c = ((v + i16x16::splat(16)) >> 5u32)
140 .max(i16x16::ZERO)160 .max(i16x16::ZERO)
141 .min(i16x16::splat(255));161 .min(i16x16::splat(255));
162+ match put {
163+ Put::Set => {
142 for (o, &s) in dst.iter_mut().zip(c.as_array()) {164 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
143 *o = s as u8;165 *o = s as u8;
144 }166 }
145 }167 }
146-168+ Put::Avg => {
169+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
170+ *o = avg(*o, s as u8);
171+ }
172+ }
173+ Put::AvgW {
174+ w0,
175+ w1,
176+ shift,
177+ round,
178+ off,
179+ } => {
180+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
181+ store_weighted(o, s as u8, w0, w1, shift, round, off);
182+ }
183+ }
184+ }
185+}
147 /// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is186 /// 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 the187 /// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the
149 /// horizontal filter, the plane stride for the vertical one.188 /// horizontal filter, the plane stride for the vertical one.
@@ -166,6 +205,7 @@ fn half_block(
166 store_half16(205 store_half16(
167 &mut dst[row * 16..row * 16 + 16],206 &mut dst[row * 16..row * 16 + 16],
168 tap6_16(data, base + row * stride, step),207 tap6_16(data, base + row * stride, step),
208+ Put::Set,
169 );209 );
170 }210 }
171 } else {211 } else {
@@ -173,6 +213,7 @@ fn half_block(
173 store_half8(213 store_half8(
174 &mut dst[row * w..row * w + w],214 &mut dst[row * w..row * w + w],
175 tap6_8(data, base + row * stride, step),215 tap6_8(data, base + row * stride, step),
216+ Put::Set,
176 );217 );
177 }218 }
178 }219 }
@@ -201,14 +242,34 @@ fn tap6_inter8(v: &[i16], at: usize, step: usize) -> i32x8 {
201 242
202 /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.243 /// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.
203 #[inline]244 #[inline]
204-fn store_centre(dst: &mut [u8], v: i32x8) {245+fn store_centre(dst: &mut [u8], v: i32x8, put: Put) {
205 let c = ((v + i32x8::splat(512)) >> 10u32)246 let c = ((v + i32x8::splat(512)) >> 10u32)
206 .max(i32x8::ZERO)247 .max(i32x8::ZERO)
207 .min(i32x8::splat(255));248 .min(i32x8::splat(255));
249+ match put {
250+ Put::Set => {
208 for (o, &s) in dst.iter_mut().zip(c.as_array()) {251 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
209 *o = s as u8;252 *o = s as u8;
210 }253 }
211 }254 }
255+ Put::Avg => {
256+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
257+ *o = avg(*o, s as u8);
258+ }
259+ }
260+ Put::AvgW {
261+ w0,
262+ w1,
263+ shift,
264+ round,
265+ off,
266+ } => {
267+ for (o, &s) in dst.iter_mut().zip(c.as_array()) {
268+ store_weighted(o, s as u8, w0, w1, shift, round, off);
269+ }
270+ }
271+ }
272+}
212 273
213 /// The rounded average of Equation 8-247 over `n` samples, sixteen at a time.274 /// The rounded average of Equation 8-247 over `n` samples, sixteen at a time.
214 #[inline]275 #[inline]
@@ -225,27 +286,65 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) {
225 /// The same average, written into a destination of pitch `os` from two286 /// The same average, written into a destination of pitch `os` from two
226 /// `w`-pitch sources.287 /// `w`-pitch sources.
227 #[inline]288 #[inline]
228-fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize) {289+fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize, put: Put) {
229 if os == w {290 if os == w {
230- avg_rows(out, a, b, w * h);291+ avg_rows_to_contig(out, a, b, w * h, put);
231 return;292 return;
232 }293 }
233 for row in 0..h {294 for row in 0..h {
234- avg_rows(295+ avg_rows_to_contig(
235 &mut out[row * os..row * os + w],296 &mut out[row * os..row * os + w],
236 &a[row * w..],297 &a[row * w..],
237 &b[row * w..],298 &b[row * w..],
238 w,299 w,
300+ put,
239 );301 );
240 }302 }
241 }303 }
242 304
305+/// The average over contiguous equal-length slices, honouring `put`.
306+#[inline]
307+fn avg_rows_to_contig(out: &mut [u8], a: &[u8], b: &[u8], n: usize, put: Put) {
308+ match put {
309+ Put::Set => avg_rows(out, a, b, n),
310+ Put::Avg => {
311+ let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
312+ for i in 0..n {
313+ out[i] = avg(avg(a[i], b[i]), out[i]);
314+ }
315+ }
316+ Put::AvgW {
317+ w0,
318+ w1,
319+ shift,
320+ round,
321+ off,
322+ } => avg_rows_weighted(out, a, b, n, w0, w1, shift, round, off),
323+ }
324+}
325+
243 /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch326 /// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch
244-/// destination.327+/// destination, honouring `put`.
245 #[inline]328 #[inline]
246-fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize) {329+fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize, put: Put) {
247 for row in 0..h {330 for row in 0..h {
248- out[row * os..row * os + w].copy_from_slice(&src[row * w..row * w + w]);331+ let dst = &mut out[row * os..row * os + w];
332+ let src = &src[row * w..row * w + w];
333+ match put {
334+ Put::Set => dst.copy_from_slice(src),
335+ Put::Avg => {
336+ for (d, &s) in dst.iter_mut().zip(src) {
337+ *d = avg(*d, s);
338+ }
339+ }
340+ Put::AvgW {
341+ w0,
342+ w1,
343+ shift,
344+ round,
345+ off,
346+ } => copy_rows_weighted(dst, src, w0, w1, shift, round, off),
347+ }
249 }348 }
250 }349 }
251 350
@@ -275,10 +374,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);374 let yi = clamp_origin(y, h, r.height, r.pad, 2, 3);
276 r.at(xi, yi)375 r.at(xi, yi)
277 }376 }
278-377+/// 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 whose378+/// 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 quarter379+/// 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`.380+/// `os`, honouring `put` (see [`Put`]).
282 ///381 ///
283 /// The pitch is a parameter so that the single-list, default-weight case —382 /// 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 instead383 /// which is most of a P slice — interpolates straight into the picture instead
@@ -293,6 +392,7 @@ pub(crate) fn mc_luma(
293 h: usize,392 h: usize,
294 os: usize,393 os: usize,
295 out: &mut [u8],394 out: &mut [u8],
395+ put: Put,
296 ) {396 ) {
297 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);397 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);398 let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3);
@@ -302,10 +402,42 @@ pub(crate) fn mc_luma(
302 402
303 // Full sample: a straight copy.403 // Full sample: a straight copy.
304 if fx == 0 && fy == 0 {404 if fx == 0 && fy == 0 {
405+ match put {
406+ Put::Set => {
305 for row in 0..h {407 for row in 0..h {
306 let src = base + row * stride;408 let src = base + row * stride;
307 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);409 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
308 }410 }
411+ }
412+ Put::Avg => {
413+ for row in 0..h {
414+ let src = base + row * stride;
415+ let dst = &mut out[row * os..row * os + w];
416+ for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) {
417+ *d = avg(*d, v);
418+ }
419+ }
420+ }
421+ Put::AvgW {
422+ w0,
423+ w1,
424+ shift,
425+ round,
426+ off,
427+ } => copy_weighted(
428+ out,
429+ os,
430+ &r.data[base..],
431+ stride,
432+ w,
433+ h,
434+ w0,
435+ w1,
436+ shift,
437+ round,
438+ off,
439+ ),
440+ }
309 return;441 return;
310 }442 }
311 443
@@ -350,7 +482,7 @@ pub(crate) fn mc_luma(
350 for col in (0..w).step_by(8) {482 for col in (0..w).step_by(8) {
351 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);483 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);
352 let n = (w - col).min(8);484 let n = (w - col).min(8);
353- store_centre(&mut jj[row * w + col..row * w + col + n], v);485+ store_centre(&mut jj[row * w + col..row * w + col + n], v, Put::Set);
354 }486 }
355 }487 }
356 }488 }
@@ -359,11 +491,11 @@ pub(crate) fn mc_luma(
359 // the average of two of them. Resolving it once per partition rather than491 // the average of two of them. Resolving it once per partition rather than
360 // once per sample is what keeps the copy loops straight.492 // once per sample is what keeps the copy loops straight.
361 match (fx, fy) {493 match (fx, fy) {
362- (2, 0) => copy_rows(out, os, &bb, w, h),494+ (2, 0) => copy_rows(out, os, &bb, w, h, put),
363- (0, 2) => copy_rows(out, os, &hh, w, h),495+ (0, 2) => copy_rows(out, os, &hh, w, h, put),
364- (2, 2) => copy_rows(out, os, &jj, w, h),496+ (2, 2) => copy_rows(out, os, &jj, w, h, put),
365- (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h),497+ (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),498+ (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h, put),
367 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {499 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {
368 // Averaged with an integer sample one row or column over.500 // Averaged with an integer sample one row or column over.
369 let (dx, dy) = match (fx, fy) {501 let (dx, dy) = match (fx, fy) {
@@ -377,13 +509,41 @@ pub(crate) fn mc_luma(
377 let s = &r.data[src..src + w];509 let s = &r.data[src..src + w];
378 let hl = &half[row * w..row * w + w];510 let hl = &half[row * w..row * w + w];
379 let dst = &mut out[row * os..row * os + w];511 let dst = &mut out[row * os..row * os + w];
512+ match put {
513+ Put::Set => {
380 for col in 0..w {514 for col in 0..w {
381 dst[col] = avg(s[col], hl[col]);515 dst[col] = avg(s[col], hl[col]);
382 }516 }
383 }517 }
518+ Put::Avg => {
519+ for col in 0..w {
520+ dst[col] = avg(dst[col], avg(s[col], hl[col]));
521+ }
522+ }
523+ Put::AvgW {
524+ w0,
525+ w1,
526+ shift,
527+ round,
528+ off,
529+ } => {
530+ for col in 0..w {
531+ store_weighted(
532+ &mut dst[col],
533+ avg(s[col], hl[col]),
534+ w0,
535+ w1,
536+ shift,
537+ round,
538+ off,
539+ );
540+ }
541+ }
542+ }
543+ }
384 }544 }
385 // Diagonal quarter positions: the two nearest half samples.545 // Diagonal quarter positions: the two nearest half samples.
386- _ => avg_rows_to(out, os, &bb, &hh, w, h),546+ _ => avg_rows_to(out, os, &bb, &hh, w, h, put),
387 }547 }
388 }548 }
389 549
@@ -403,6 +563,7 @@ fn chroma_rows<const W: usize>(
403 wt: [u16; 4],563 wt: [u16; 4],
404 os: usize,564 os: usize,
405 out: &mut [u8],565 out: &mut [u8],
566+ put: Put,
406 ) {567 ) {
407 for row in 0..h {568 for row in 0..h {
408 let src = base + row * stride;569 let src = base + row * stride;
@@ -415,7 +576,17 @@ fn chroma_rows<const W: usize>(
415 + u16::from(q[c]) * wt[2]576 + u16::from(q[c]) * wt[2]
416 + u16::from(q[c + 1]) * wt[3]577 + u16::from(q[c + 1]) * wt[3]
417 + 32;578 + 32;
418- dst[c] = (v >> 6) as u8;579+ match put {
580+ Put::Set => dst[c] = (v >> 6) as u8,
581+ Put::Avg => dst[c] = avg(dst[c], (v >> 6) as u8),
582+ Put::AvgW {
583+ w0,
584+ w1,
585+ shift,
586+ round,
587+ off,
588+ } => store_weighted(&mut dst[c], (v >> 6) as u8, w0, w1, shift, round, off),
589+ }
419 }590 }
420 }591 }
421 }592 }
@@ -431,6 +602,7 @@ pub(crate) fn mc_chroma(
431 h: usize,602 h: usize,
432 os: usize,603 os: usize,
433 out: &mut [u8],604 out: &mut [u8],
605+ put: Put,
434 ) {606 ) {
435 let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16);607 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);608 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(
441 // Full sample: a straight copy. A zero motion vector is the most common613 // Full sample: a straight copy. A zero motion vector is the most common
442 // vector in real content, and it lands here.614 // vector in real content, and it lands here.
443 if fx == 0 && fy == 0 {615 if fx == 0 && fy == 0 {
616+ match put {
617+ Put::Set => {
444 for row in 0..h {618 for row in 0..h {
445 let src = base + row * stride;619 let src = base + row * stride;
446 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);620 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
447 }621 }
622+ }
623+ Put::Avg => {
624+ for row in 0..h {
625+ let src = base + row * stride;
626+ let dst = &mut out[row * os..row * os + w];
627+ for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) {
628+ *d = avg(*d, v);
629+ }
630+ }
631+ }
632+ Put::AvgW {
633+ w0,
634+ w1,
635+ shift,
636+ round,
637+ off,
638+ } => copy_weighted(
639+ out,
640+ os,
641+ &r.data[base..],
642+ stride,
643+ w,
644+ h,
645+ w0,
646+ w1,
647+ shift,
648+ round,
649+ off,
650+ ),
651+ }
448 return;652 return;
449 }653 }
450-
451 // The four weights sum to 64, so the weighted sum of Equation 8-270 never654 // 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.655 // 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];656 let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy];
454 match w {657 match w {
455- 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out),658+ 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),659+ 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),660+ _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out, put),
458 }661 }
459 }662 }
460 663
@@ -485,6 +688,101 @@ impl Weights {
485 }688 }
486 }689 }
487 690
691+/// How an interpolation result lands in `out`: written outright, or rounded
692+/// into what is already there.
693+///
694+/// The weighted second pass of 8.4.2.3.2 is a fusion mode as well: the first
695+/// prediction sits in `out`, and the second list's sample `v` combines with
696+/// it as `clip((out*w0 + v*w1 + round) >> shift) + off` — the same integer
697+/// formula, on the same bytes, as running the combining pass over the two
698+/// clipped predictions.
699+#[derive(Clone, Copy, PartialEq, Eq)]
700+pub(crate) enum Put {
701+ /// Write the prediction.
702+ Set,
703+ /// Average the prediction into the bytes already in `out`.
704+ Avg,
705+ /// Weighted-average the prediction into the bytes already in `out`.
706+ AvgW {
707+ w0: i32,
708+ w1: i32,
709+ shift: u32,
710+ round: i32,
711+ off: i32,
712+ },
713+}
714+
715+/// The 8.4.2.3.2 combining step for one sample: list 0's prediction is the
716+/// byte already in `dst`, list 1's is `v`.
717+#[inline]
718+fn store_weighted(dst: &mut u8, v: u8, w0: i32, w1: i32, shift: u32, round: i32, off: i32) {
719+ let p0 = i32::from(*dst);
720+ *dst = clip8((((p0 * w0 + i32::from(v) * w1 + round) >> shift) + off) as i32);
721+}
722+/// The weighted combining pass over a whole block: `h` rows of `w` samples
723+/// from a `stride`-pitch source into an `os`-pitch destination.
724+#[inline(never)]
725+#[allow(clippy::too_many_arguments)]
726+fn copy_weighted(
727+ out: &mut [u8],
728+ os: usize,
729+ src: &[u8],
730+ stride: usize,
731+ w: usize,
732+ h: usize,
733+ w0: i32,
734+ w1: i32,
735+ shift: u32,
736+ round: i32,
737+ off: i32,
738+) {
739+ for row in 0..h {
740+ let dst = &mut out[row * os..row * os + w];
741+ let s = &src[row * stride..row * stride + w];
742+ for (d, &v) in dst.iter_mut().zip(s) {
743+ store_weighted(d, v, w0, w1, shift, round, off);
744+ }
745+ }
746+}
747+
748+/// The weighted combining pass over contiguous equal-length slices, where
749+/// list 1's sample is the rounded average of `a` and `b`.
750+#[inline(never)]
751+#[allow(clippy::too_many_arguments)]
752+fn avg_rows_weighted(
753+ out: &mut [u8],
754+ a: &[u8],
755+ b: &[u8],
756+ n: usize,
757+ w0: i32,
758+ w1: i32,
759+ shift: u32,
760+ round: i32,
761+ off: i32,
762+) {
763+ let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
764+ for i in 0..n {
765+ store_weighted(&mut out[i], avg(a[i], b[i]), w0, w1, shift, round, off);
766+ }
767+}
768+
769+/// The weighted combining pass over a whole block from a `w`-pitch source.
770+#[inline(never)]
771+#[allow(clippy::too_many_arguments)]
772+fn copy_rows_weighted(
773+ out: &mut [u8],
774+ src: &[u8],
775+ w0: i32,
776+ w1: i32,
777+ shift: u32,
778+ round: i32,
779+ off: i32,
780+) {
781+ for (d, &s) in out.iter_mut().zip(src) {
782+ store_weighted(d, s, w0, w1, shift, round, off);
783+ }
784+}
785+
488 /// Combine the list predictions of one partition into the final prediction786 /// 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 that787 /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that
490 /// is not used is ignored.788 /// is not used is ignored.
@@ -674,7 +972,7 @@ mod tests {
674 for fx in 0..4i16 {972 for fx in 0..4i16 {
675 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {973 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {
676 let mv = [fx - 20 * 4, fy + 12];974 let mv = [fx - 20 * 4, fy + 12];
677- mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours);975+ 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);976 spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);
679 assert_eq!(977 assert_eq!(
680 ours[..pw * ph],978 ours[..pw * ph],
@@ -687,6 +985,38 @@ mod tests {
687 }985 }
688 }986 }
689 987
988+ /// `Put::Avg` turns `mc_luma` into the second half of a default-weighted
989+ /// bi-prediction: averaging into the first list's bytes is bit-exact with
990+ /// running the combining pass over the two clipped predictions (8.4.2.3.1).
991+ #[test]
992+ fn avg_mode_matches_the_combining_pass() {
993+ let (w, h, pad) = (48usize, 32usize, 32usize);
994+ let (data, stride, origin) = ramp_plane(w, h, pad);
995+ let r = plane(&data, stride, origin, w, h, pad);
996+ let mut fused = [0u8; 256];
997+ let mut p0 = [0u8; 256];
998+ let mut p1 = [0u8; 256];
999+ let mut out = [0u8; 256];
1000+ for mv0 in [[0i16; 2], [7, -3], [-41, 22]] {
1001+ for mv1 in [[2i16; 2], [5, 1], [-13, 9]] {
1002+ for &(pw, ph) in &[(16usize, 16usize), (8, 8), (4, 4)] {
1003+ mc_luma(&r, 4, 4, mv0, pw, ph, pw, &mut p0, Put::Set);
1004+ mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut p1, Put::Set);
1005+ combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, pw * ph);
1006+ // The fused shape: first list into the picture, second
1007+ // averaged on top of it.
1008+ fused[..pw * ph].copy_from_slice(&p0[..pw * ph]);
1009+ mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut fused, Put::Avg);
1010+ assert_eq!(
1011+ fused[..pw * ph],
1012+ out[..pw * ph],
1013+ "mv {mv0:?} + {mv1:?} {pw}x{ph}"
1014+ );
1015+ }
1016+ }
1017+ }
1018+ }
1019+
690 #[test]1020 #[test]
691 fn chroma_interpolation_matches_equation_8_270() {1021 fn chroma_interpolation_matches_equation_8_270() {
692 let (w, h, pad) = (24usize, 16usize, 16usize);1022 let (w, h, pad) = (24usize, 16usize, 16usize);
@@ -697,7 +1027,7 @@ mod tests {
697 for fy in 0..8i16 {1027 for fy in 0..8i16 {
698 for fx in 0..8i16 {1028 for fx in 0..8i16 {
699 let mv = [fx, fy];1029 let mv = [fx, fy];
700- mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours);1030+ mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours, Put::Set);
701 for row in 0..8i32 {1031 for row in 0..8i32 {
702 for col in 0..8i32 {1032 for col in 0..8i32 {
703 let s = |dx: i32, dy: i32| -> i32 {1033 let s = |dx: i32, dy: i32| -> i32 {