forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

inter_search.rs4687 lines, 188.3 KiBHistoryRawDownload
1use super::*;
2
3/// Publishes one coded inter-frame block into the `mi` grid the next block's
4/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
5/// block casts no vote but is still a coded cell (see `code_square_inter`'s
6/// note on `processed_rows`/`processed_cols`).
7pub(super) fn record_mi(
8 grid: &mut MiGrid,
9 mi_row: usize,
10 mi_col: usize,
11 size: u8,
12 inter: Option<InterInfo>,
13 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
14 // the RD pricer the two cells the writer's `skip_ctx` sums.
15 skip: bool,
16) {
17 let info = match inter {
18 Some(info) => MiInfo {
19 is_inter: true,
20 ref_frame: info.ref_frame,
21 // A COMPOUND block votes with BOTH of its references and both of
22 // its vectors, exactly as the tile writer publishes it: recording
23 // a compound block as a single-reference one here left the
24 // encoder's own grid disagreeing with the writer's from the first
25 // compound block on, so every later stack it searched against was
26 // not the stack the decoder derives.
27 ref_frame1: info.ref1.unwrap_or(NO_REF1),
28 mv1: mv16(info.mv1),
29 mv: mv16(info.mv),
30 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
31 // side, compound modes 2/3/7 on the other.
32 is_new_mv: matches!(
33 info.mode,
34 InterMode::NewMv
35 | InterMode::NewNewMv
36 | InterMode::NearestNewMv
37 | InterMode::NewNearestMv
38 ),
39 size,
40 size_h: size,
41 is_global_mv0: false,
42 is_global_mv1: false,
43 },
44 None => MiInfo {
45 is_inter: false,
46 ref_frame: -1,
47 ref_frame1: NO_REF1,
48 mv1: (0, 0),
49 mv: (0, 0),
50 is_new_mv: false,
51 size,
52 size_h: size,
53 is_global_mv0: false,
54 is_global_mv1: false,
55 },
56 };
57 for dr in 0..usize::from(size) {
58 for dc in 0..usize::from(size) {
59 grid.set(mi_row + dr, mi_col + dc, info);
60 grid.set_skip(mi_row + dr, mi_col + dc, skip);
61 }
62 }
63}
64
65/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
66/// writer's own `write_inter_block_128_rect` makes, so the second half of a
67/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
68pub(super) fn record_mi_rect(
69 grid: &mut MiGrid,
70 mi_row: usize,
71 mi_col: usize,
72 (w_mi, h_mi): (usize, usize),
73 inter: Option<InterInfo>,
74 skip: bool,
75) {
76 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
77 // `record_mi` stamped the square corner; widen it to the true footprint,
78 // with the block's own (rect) size fields.
79 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
80 info.size = w_mi as u8;
81 info.size_h = h_mi as u8;
82 for dr in 0..h_mi {
83 for dc in 0..w_mi {
84 grid.set(mi_row + dr, mi_col + dc, info);
85 grid.set_skip(mi_row + dr, mi_col + dc, skip);
86 }
87 }
88}
89
90/// The reconstructed samples one 32x32 square covers in all three planes, so
91/// that a partition trial can be undone.
92/// One square of a plane, row-major, the inverse of [`Plane::restore`].
93///
94/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
95/// which allocated and freed a `Vec` per row of every block it copied --
96/// `Plane::snapshot` runs once per partition trial.
97pub(super) fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
98 let mut out = vec![0u8; side * side];
99 for row in 0..side {
100 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
101 }
102 out
103}
104
105pub(super) fn snapshot(
106 luma: &Plane,
107 chroma: &[Plane; 2],
108 (x, y): (usize, usize),
109 side: usize,
110) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
111 [
112 luma.snapshot(x, y, side),
113 chroma[0].snapshot(x / 2, y / 2, side / 2),
114 chroma[1].snapshot(x / 2, y / 2, side / 2),
115 ]
116}
117
118/// Puts such a snapshot back.
119pub(super) fn restore(
120 luma: &mut Plane,
121 chroma: &mut [Plane; 2],
122 (x, y): (usize, usize),
123 side: usize,
124 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
125) {
126 luma.restore(x, y, side, &saved[0]);
127 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
128 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
129}
130
131/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
132/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
133/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
134/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
135/// rule shared with the key-frame path, not a second one that could diverge.
136pub(super) fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
137 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
138 let dc_entry = dc_pos.map(|i| scored.remove(i));
139 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
140 scored.truncate(if dc_entry.is_some() {
141 top_k.saturating_sub(1)
142 } else {
143 top_k
144 });
145 if let Some(dc_entry) = dc_entry {
146 scored.push(dc_entry);
147 }
148 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
149 modes.iter().copied().filter(|m| keep.contains(m)).collect()
150}
151
152pub(super) fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
153 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
154 [INTRA_MODE_CTX[usize::from(left_mode)]];
155 std::array::from_fn(|mode| {
156 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
157 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
158 } else {
159 0.0
160 };
161 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
162 })
163}
164
165/// What the luma mode search picks between, and under what terms.
166#[derive(Clone, Copy)]
167pub(super) struct Search<'a> {
168 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
169 /// luma search then offers a palette candidate beside the intra modes.
170 pub(super) screen: bool,
171 pub(super) base_q_idx: u8,
172 pub(super) deadzone: f64,
173 pub(super) lambda: f64,
174 pub(super) modes: &'a [u8],
175 /// How many of `modes` the full RD trial (forward transform, quantize,
176 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
177 /// pre-pass on the prediction residual alone plus DC (always kept, since
178 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
179 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
180 /// mode through full RD, unchanged from before this lever.
181 pub(super) top_k: Option<usize>,
182 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
183 /// -- `false` cuts the named candidate group from the whole-32 search
184 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
185 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
186 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
187 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
188 /// leaves and the flat path keep intra and compound, and the
189 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
190 /// The probe's correction: with the leaf gate ALONE the film A stream
191 /// was byte-identical to the control -- the ARF's intra area lives at
192 /// the whole-32 level, so the intra arm must cut it there too.
193 pub(super) arf_leaf_intra: bool,
194 pub(super) arf_leaf8: bool,
195 pub(super) arf_leaf_compound: bool,
196}
197
198/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
199/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
200/// shipped table -- 0, bit-exact with the pre-lane encoder).
201pub(super) fn arfmode() -> u8 {
202 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
203 u8::MAX => {}
204 n => return n,
205 }
206 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
207 crate::envflags::var("EC_AV1_ARFMODE")
208 .ok()
209 .and_then(|v| v.parse().ok())
210 });
211 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
212}
213
214/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
215pub(super) static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
216
217/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
218/// process constant ([`crate::envflags`]), so an in-process witness needs
219/// this to arm the lever.
220#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
221pub(crate) fn set_arfmode(n: Option<u8>) {
222 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
223}
224
225/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
226/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
227/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
228/// split the search would have offered and the arm refused, 2 = a top-ARF
229/// leaf whose compound set was dropped. A green gate over counts of zero
230/// proves nothing about the lever.
231pub(super) static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
232 std::sync::atomic::AtomicUsize::new(0),
233 std::sync::atomic::AtomicUsize::new(0),
234 std::sync::atomic::AtomicUsize::new(0),
235];
236
237/// Records one such hit.
238pub(super) fn arfmode_hit(which: usize) {
239 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
240}
241
242/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
243/// condition, so the counter only runs when every other prune let the split
244/// through and the arm alone refuses it.
245pub(super) fn arfmode_hit_and_no() -> bool {
246 arfmode_hit(1);
247 false
248}
249
250/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
251/// probe point can print a non-zero engagement count under the env knob
252/// itself -- the counter the gate BD numbers are read against.
253pub fn take_arfmode_hits() -> [usize; 3] {
254 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
255}
256
257pub(super) fn prune_top_k() -> Option<usize> {
258 #[cfg(test)]
259 {
260 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
261 return k;
262 }
263 }
264 let swept = std::env::var("EC_AV1_PRUNE_K")
265 .ok()
266 .and_then(|v| v.parse::<usize>().ok());
267 match swept {
268 Some(k) if cfg!(test) => Some(k),
269 _ => crate::speed::at(&crate::speed::PRUNE_K),
270 }
271}
272
273// A per-thread override [`prune_top_k`] checks first, so one test can sweep
274// `top_k` in-process without mutating the environment (forbidden here --
275// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
276#[cfg(test)]
277thread_local! {
278 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
279 const { std::cell::Cell::new(None) };
280}
281
282#[cfg(test)]
283pub(super) fn set_test_top_k_override(value: Option<usize>) {
284 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
285}
286
287/// The default: unpruned, thirteen full trials per block, same as before this
288/// lever. Set from the sweep in the lane report if the quality gate clears it.
289pub(crate) const PRUNE_TOP_K: Option<usize> = None;
290
291/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
292/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
293/// quality gates were measured separately and may land on different
294/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
295/// [`EC_AV1_PRUNE_K`] or the key-frame path.
296pub(super) fn prune_top_k_inter() -> Option<usize> {
297 #[cfg(test)]
298 {
299 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
300 return k;
301 }
302 }
303 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
304 .ok()
305 .and_then(|v| v.parse::<usize>().ok());
306 match swept {
307 Some(k) if cfg!(test) => Some(k),
308 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
309 }
310}
311
312// A per-thread override [`prune_top_k_inter`] checks first, same reason as
313// [`TEST_TOP_K_OVERRIDE`].
314#[cfg(test)]
315thread_local! {
316 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
317 const { std::cell::Cell::new(None) };
318}
319
320#[cfg(test)]
321pub(super) fn set_test_top_k_override_inter(value: Option<usize>) {
322 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
323}
324
325/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
326/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
327/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
328/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
329/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
330/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
331/// pruning them costs less quality here.
332pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
333
334// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
335// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
336// inter frame's cost can be attributed to a bucket without changing what
337// the search actually does. Index: 0 = whole-call time inside
338// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
339// [`crate::mc::predict`] (every call, from the motion search's own
340// candidates and from a committed inter block's final prediction alike),
341// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
342#[cfg(test)]
343thread_local! {
344 static STAGE_NS: [std::cell::Cell<u64>; 4] = const {
345 [
346 std::cell::Cell::new(0),
347 std::cell::Cell::new(0),
348 std::cell::Cell::new(0),
349 std::cell::Cell::new(0),
350 ]
351 };
352}
353
354/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
355/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
356/// per transform trial and per `mc::predict` call whether or not anyone was
357/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
358/// The clock is now read only when [`crate::par::stage_times`] is on, which
359/// is what prints the breakdown in the first place.
360#[cfg(test)]
361pub(crate) fn stage_start() -> Option<std::time::Instant> {
362 crate::par::stage_times().then(std::time::Instant::now)
363}
364
365#[cfg(test)]
366pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
367 if let Some(t) = t {
368 stage_add(bucket, t.elapsed());
369 }
370}
371
372#[cfg(test)]
373pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
374 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
375}
376
377#[cfg(test)]
378pub(super) fn stage_reset() {
379 crate::par::set_stage_times(true);
380 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
381}
382
383#[cfg(test)]
384pub(super) fn stage_read() -> [std::time::Duration; 4] {
385 crate::par::set_stage_times(false);
386 STAGE_NS.with(|c| {
387 c.each_ref()
388 .map(|cell| std::time::Duration::from_nanos(cell.get()))
389 })
390}
391
392/// One mode's coding of one block, before it is committed.
393#[derive(Clone)]
394pub(super) struct Trial {
395 pub(super) levels: Vec<i32>,
396 pub(super) reconstruction: Vec<u8>,
397 pub(super) sse: f64,
398 pub(super) bits: f64,
399}
400
401/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
402/// of a 64-point transform that is actually coded (everything outside it is
403/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
404pub(super) fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
405 let mut out = vec![0i32; to * to];
406 for row in 0..to {
407 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
408 }
409 out
410}
411
412/// The non-zero levels of a block, as the tile writer takes them.
413pub(super) fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
414 levels
415 .iter()
416 .enumerate()
417 .filter(|&(_, &level)| level != 0)
418 .map(|(i, &level)| Coeff {
419 row: (i / side) as u8,
420 col: (i % side) as u8,
421 level,
422 })
423 .collect()
424}
425
426thread_local! {
427 /// The tile grid the next frame is coded with, as `(TileColsLog2,
428 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
429 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
430 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
431 /// one tile per frame, what every caller that never arms anything gets
432 /// and what every stream this crate wrote before tiles existed carries.
433 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
434}
435
436/// Arms this thread's next frame encodes with a tile grid (log2 counts).
437pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
438 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
439}
440
441pub(super) fn armed_tiles() -> (u32, u32) {
442 let armed = TILE_LOG2.with(std::cell::Cell::get);
443 if armed != (0, 0) {
444 return armed;
445 }
446 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
447 // (which codes through `encode_sequence`, not the facade) can measure what
448 // a tile grid costs without a knob of its own -- same shape as
449 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
450 match std::env::var("EC_AV1_TILES").ok() {
451 Some(v) if cfg!(test) => {
452 let mut f = v.split(':');
453 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
454 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
455 (cols, rows)
456 }
457 _ => armed,
458 }
459}
460
461/// Codes a frame's `tiles` tiles, each entirely on its own (see
462/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
463/// the crate's own pool, and hands back their payloads in tile order plus
464/// whatever `code` returned for tile `store` -- the CDF state
465/// `context_update_tile_id` names. The result cannot depend on the thread
466/// count: each job writes one tile from the frame's own starting tables into
467/// its own slot.
468pub(super) fn write_tiles<F>(
469 tiles: usize,
470 store: usize,
471 code: F,
472) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
473where
474 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
475{
476 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
477 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
478 let threads = crate::par::tile_threads().min(tiles);
479 let mut slots: Vec<Slot> = Vec::new();
480 if threads <= 1 {
481 for index in 0..tiles {
482 slots.push(Some(code(index)));
483 }
484 } else {
485 let done: std::sync::Mutex<Vec<Slot>> =
486 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
487 {
488 crate::par::scope("ec-av1-tile", |batch| {
489 for (from, to) in crate::par::bands(tiles, threads) {
490 let done = &done;
491 let code = &code;
492 batch.submit(move || {
493 for index in from..to {
494 let coded = code(index);
495 done.lock().expect("tile slots")[index] = Some(coded);
496 }
497 });
498 }
499 });
500 }
501 slots = done.into_inner().expect("tile slots");
502 }
503 let mut out = Vec::with_capacity(tiles);
504 let mut stored = None;
505 for (index, slot) in slots.into_iter().enumerate() {
506 let (bytes, cdfs) = slot.expect("every tile was coded")?;
507 if index == store {
508 stored = cdfs;
509 }
510 out.push(bytes);
511 }
512 Ok((out, stored))
513}
514
515/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
516/// workers, and returns the results in tile order. The counterpart of
517/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
518/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
519/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
520/// availability is already tile-relative (`clip_planes_to_tile`,
521/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
522/// other tiles have run -- gated by
523/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
524/// covers the search as well as the write.
525///
526/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
527/// by design) and moved into the worker, exactly as the decoder's filter bands
528/// do it through [`crate::par::scope`].
529pub(super) fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
530where
531 T: Send,
532 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
533{
534 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
535 let threads = crate::par::tile_threads().min(tiles);
536 if threads <= 1 {
537 return (0..tiles).map(|index| job(index, fctx)).collect();
538 }
539 type Slot<T> = Option<Result<T>>;
540 let done: std::sync::Mutex<Vec<Slot<T>>> =
541 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
542 {
543 crate::par::scope("ec-av1-tile-search", |batch| {
544 for (from, to) in crate::par::bands(tiles, threads) {
545 let done = &done;
546 let job = &job;
547 let ctx = crate::decode::filter_ctx_copy(fctx);
548 batch.submit(move || {
549 for index in from..to {
550 let searched = job(index, &ctx);
551 done.lock().expect("tile slots")[index] = Some(searched);
552 }
553 });
554 }
555 });
556 }
557 done.into_inner()
558 .expect("tile slots")
559 .into_iter()
560 .map(|slot| slot.expect("every tile was searched"))
561 .collect()
562}
563
564/// One tile job's own copy of a plane: the frame's source, a blank
565/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
566/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
567/// of the frame's reconstruction because a tile's prediction never reads a
568/// sample outside its own rectangle, and every sample inside it is written
569/// before it is read.
570pub(super) fn fresh_plane(
571 source: &[u8],
572 width: usize,
573 height: usize,
574 true_width: usize,
575 true_height: usize,
576) -> Plane<'_> {
577 Plane {
578 source,
579 reconstruction: vec![128; source.len()],
580 width,
581 height,
582 true_width,
583 true_height,
584 tile_x0: 0,
585 tile_y0: 0,
586 tile_x1: width,
587 tile_y1: height,
588 ctx: CoefCtxMap::default(),
589 }
590}
591
592/// One tile job's reconstructed rectangles, handed back to the calling thread
593/// (which copies them into the frame planes in tile order).
594pub(super) struct TilePixels {
595 pub(super) luma_rect: (usize, usize, usize, usize),
596 pub(super) chroma_rect: (usize, usize, usize, usize),
597 pub(super) luma: Vec<u8>,
598 pub(super) chroma: [Vec<u8>; 2],
599}
600
601/// The rectangle `[x0, x1) x [y0, y1)` of a plane with `stride`, copied out as
602/// its rows back to back.
603pub(super) fn take_rect(plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize)) -> Vec<u8> {
604 let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0));
605 for y in y0..y1 {
606 out.extend_from_slice(&plane[y * stride + x0..y * stride + x1]);
607 }
608 out
609}
610
611/// The inverse of [`take_rect`]: writes `rows` (as `take_rect` produced them)
612/// back into the rectangle of `plane`.
613pub(super) fn put_rect(plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize), rows: &[u8]) {
614 let w = x1 - x0;
615 for (row, y) in (y0..y1).enumerate() {
616 plane[y * stride + x0..y * stride + x1].copy_from_slice(&rows[row * w..(row + 1) * w]);
617 }
618}
619
620/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
621/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
622/// tables the frame stores (spec 7.20), which is what
623/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
624/// below publish.
625pub(super) fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
626 ec_av1_syntax::TileInfo {
627 uniform_spacing: true,
628 cols: layout.cols(),
629 rows: layout.rows(),
630 cols_log2: layout.cols_log2,
631 rows_log2: layout.rows_log2,
632 mi_col_starts: layout.mi_col_starts(),
633 mi_row_starts: layout.mi_row_starts(),
634 context_update_tile_id: layout.largest_tile() as u32,
635 tile_size_bytes,
636 }
637}
638
639/// Clips the three planes' intra edge reads to `rect`, the tile the
640/// superblock about to be searched belongs to (the encoder side of the
641/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
642/// raster order -- which is a linear extension of every tile's own coding
643/// order, so a block still only ever predicts from samples already
644/// reconstructed -- and only availability is tile-relative.
645pub(super) fn clip_planes_to_tile(
646 luma: &mut Plane<'_>,
647 chroma: &mut [Plane<'_>; 2],
648 rect: crate::tile::TileRect,
649) {
650 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
651 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
652 luma.set_tile(x0, y0, x1, y1);
653 for plane in chroma.iter_mut() {
654 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
655 }
656}
657
658/// Encodes one picture as a key frame.
659///
660/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
661/// picks its coefficient CDFs from one of four q contexts by that index.
662/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
663/// smaller values trade fidelity for rate.
664///
665/// The picture may be any even width and height: the encoder pads it by edge
666/// replication to a whole number of 32x32 blocks internally, and the frame it
667/// writes crops back to the picture's own size (`render_width`/
668/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
669/// own size, never the padded one.
670///
671/// # Errors
672/// Returns an error when the picture's width or height is zero or odd, or
673/// when its planes are not 4:2:0 of that size.
674/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
675/// stream. The per-frame decode state this needs lives for exactly this call.
676///
677/// # Errors
678/// Returns an error under the same conditions
679/// [`encode_key_frame_with_modes`] does.
680pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
681 encode_key_frame_with_ctx(
682 picture,
683 base_q_idx,
684 deadzone,
685 &crate::decode::FrameCtx::for_encoder(),
686 )
687}
688
689/// [`encode_key_frame`] with the per-block intra modes given rather than
690/// searched.
691///
692/// # Errors
693/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
694/// is empty, or when a block's coefficients do not fit the coded frame.
695pub fn encode_key_frame_with_modes(
696 picture: &Picture,
697 base_q_idx: u8,
698 deadzone: f64,
699 modes: &[u8],
700) -> Result<Encoded> {
701 encode_key_frame_with_modes_with_ctx(
702 picture,
703 base_q_idx,
704 deadzone,
705 modes,
706 &crate::decode::FrameCtx::for_encoder(),
707 )
708}
709
710/// Codes `pictures` as one key frame followed by inter frames.
711///
712/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
713/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
714/// `show_existing_frame` header, so `stream` is in CODING order while
715/// `frames` stays in display order (`EncodedSequence::coding_order` is the
716/// map). Screen content codes flat, decided once per sequence by the same
717/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
718/// puts every stream back on the flat path for an A/B.
719///
720/// # Errors
721/// Returns an error under the same conditions [`encode_key_frame`] and the
722/// inter frame path do.
723pub fn encode_sequence(
724 pictures: &[Picture],
725 base_q_idx: u8,
726 deadzone: f64,
727) -> Result<EncodedSequence> {
728 encode_sequence_with_ctx(
729 pictures,
730 base_q_idx,
731 deadzone,
732 &crate::decode::FrameCtx::for_encoder(),
733 )
734}
735
736/// Codes one padded picture as a key frame whose HEADER declares
737/// `frame_width` x `frame_height` -- a frame size the picture's own
738/// `width`/`height` need not be, and in particular need not be even.
739///
740/// [`encode_key_frame`] derives the declared size from the picture and
741/// refuses an odd one, which is a property of a 4:2:0 SOURCE (an odd luma
742/// column has no chroma sample of its own to be fed), not of the format: a
743/// 65-wide 4:2:0 frame is a legal AV1 frame, with
744/// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
745/// `av1_common_plane_width` / `ROUND_POWER_OF_TWO`, `av1/common/
746/// av1_common_int.h`), and aomenc never emits one only because it rounds the
747/// coded size down to even before it looks at the picture
748/// (`av1enc_set_frame_size`). This is the entry that can produce one, and it
749/// is what the odd-luma coverage fixture is built with: the caller hands
750/// over a picture already padded to the block grid and names the size to
751/// declare, so the block walk codes exactly the `mi_cols`/`mi_rows` a
752/// decoder derives from the declared size (spec `compute_image_size`).
753///
754/// # Errors
755/// Returns an error when `picture` is not a whole number of 32x32 blocks
756/// ([`Picture::check`]'s own rule), when either declared size is zero or
757/// larger than the padded picture's, or when the mode search fails -- the
758/// same conditions [`encode_key_frame`] reports for a malformed picture.
759pub fn encode_key_frame_at_size(
760 picture: &Picture,
761 frame_width: usize,
762 frame_height: usize,
763 base_q_idx: u8,
764 deadzone: f64,
765) -> Result<Encoded> {
766 picture.check()?;
767 if frame_width == 0
768 || frame_height == 0
769 || frame_width > picture.width
770 || frame_height > picture.height
771 {
772 return Err(Error::unsupported(
773 "AV1 encode",
774 "the declared frame size must be nonzero and fit inside the padded picture",
775 ));
776 }
777 let encoded = encode_key_frame_inner(
778 picture,
779 base_q_idx,
780 deadzone,
781 &KEY_FRAME_MODES,
782 split_blocks(),
783 (frame_width, frame_height),
784 unspecified_color_config(),
785 &crate::decode::FrameCtx::for_encoder(),
786 )?;
787 Ok(crop_encoded(&encoded, frame_width, frame_height))
788}
789
790pub(crate) fn encode_key_frame_with_ctx(
791 picture: &Picture,
792 base_q_idx: u8,
793 deadzone: f64,
794 fctx: &crate::decode::FrameCtx,
795) -> Result<Encoded> {
796 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
797}
798
799/// Encodes one picture as a key frame, choosing each block's luma mode from
800/// `modes` alone.
801///
802/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
803/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
804/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
805/// uses.
806///
807/// # Errors
808/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
809/// names a mode [`crate::intra::predict`] does not predict.
810pub(crate) fn encode_key_frame_with_modes_with_ctx(
811 picture: &Picture,
812 base_q_idx: u8,
813 deadzone: f64,
814 modes: &[u8],
815 fctx: &crate::decode::FrameCtx,
816) -> Result<Encoded> {
817 picture.check_even()?;
818 let padded = picture.padded_to(BLOCK);
819 let encoded = encode_key_frame_inner(
820 &padded,
821 base_q_idx,
822 deadzone,
823 modes,
824 split_blocks(),
825 (picture.width, picture.height),
826 unspecified_color_config(),
827 fctx,
828 )?;
829 Ok(crop_encoded(&encoded, picture.width, picture.height))
830}
831
832/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
833/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
834/// already padded to a whole number of 32x32 blocks; `render` is the real
835/// (pre-pad) size the frame header tells a decoder to crop back to.
836// Spec-shaped signature; bundling the operands would obscure the spec mapping.
837#[allow(clippy::too_many_arguments)]
838pub(crate) fn encode_key_frame_inner(
839 picture: &Picture,
840 base_q_idx: u8,
841 deadzone: f64,
842 modes: &[u8],
843 split_blocks: bool,
844 render: (usize, usize),
845 color_config: ColorConfig,
846 fctx: &crate::decode::FrameCtx,
847) -> Result<Encoded> {
848 // lane-refs: an intra frame runs no motion compensation, and the
849 // context is shared across the sequence -- put the kernel back to the
850 // default so nothing reads the previous inter frame's.
851 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
852 picture.check()?;
853 if modes.is_empty() {
854 return Err(Error::unsupported(
855 "AV1 encode",
856 "a mode search needs at least one mode to choose from",
857 ));
858 }
859 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
860 return Err(Error::unsupported(
861 "AV1 encode",
862 format!("intra mode {bad} is not one the encoder predicts"),
863 ));
864 }
865 // The header carries the frame's true (unpadded) size as `frame_width`/
866 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
867 // `mi_rows` derived from that same true size (spec `compute_image_size`).
868 // `render_width`/`render_height` come out equal to it too, so
869 // `render_and_frame_size_different` is false and no render_size bits are
870 // written, mirroring libaom/rav1e: the padded `picture` below is only the
871 // internal coding surface, never what the header names.
872 // Screen-content detection runs on the SOURCE luma, before any header is
873 // built: it decides this sequence's `seq_force_screen_content_tools` (and
874 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
875 // this frame's own `allow_screen_content_tools`.
876 let screen = screen_content(
877 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
878 picture.width,
879 (picture.width).min(render.0),
880 (picture.height).min(render.1),
881 );
882 arm_seq_screen(screen);
883 // A key frame's writer really does start from the defaults, and a search
884 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
885 // disarm, or a key frame's bits would depend on which thread searched it.
886 crate::tile::arm_pricing_cdfs(None, false);
887 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
888 // forces deblocking, CDEF and loop restoration OFF for this frame
889 // (frame.rs:194/210/252/272), so it is only set when the source repeats
890 // itself enough for the copied blocks to pay that back
891 // ([`intrabc_worth_it`]).
892 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
893 // grid across every tile while this writer builds one per tile, so a
894 // multi-tile allow_intrabc frame would predict its DVs off a different
895 // grid than the decoder does. corner-cut, ceiling named: the upgrade
896 // path is a frame-scoped grid shared by the tile writers.
897 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
898 intrabc_worth_it(
899 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
900 picture.width,
901 picture.width.min(render.0),
902 picture.height.min(render.1),
903 )
904 } else {
905 (false, 0.0)
906 };
907 IBC_SHARE.with(|c| c.set(ibc_share));
908 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
909 header.allow_screen_content_tools = screen;
910 // lane-txi: the wider `tx_type` alphabets, gated by the same content
911 // rule the type search itself stands behind ([`wide_tx_set`]).
912 header.reduced_tx_set = !wide_tx_set(screen);
913 header.allow_intrabc = allow_intrabc;
914 header.render_width = render.0 as u32;
915 header.render_height = render.1 as u32;
916 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
917 // its luma transform below its own side (`crate::tile::write_luma_select`).
918 // Set here rather than in `key_frame_headers_colour` so the header
919 // builders' other callers -- the hand-built tile writers, which code no
920 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
921 let tx_select = tx_select();
922 if tx_select {
923 header.tx_mode = TxMode::Select;
924 }
925 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
926
927 // Prediction reads no further than this, in each plane's own units --
928 // see `Plane::true_width`/`true_height`.
929 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
930 // lane-palw: the encoder's own in-process reconstruct reads its palette
931 // colour-index maps back through `decode::palette_onscreen`, which takes
932 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
933 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
934 // them here so the reconstruct clamps a block cut by the frame edge
935 // exactly as the writer now does.
936 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
937 fctx.seg_mi_dims.set(frame_mi_dims);
938 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
939 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
940 // design (see `intra_predict_u8`'s doc comment), so narrow the source
941 // once here.
942 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
943 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
944 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
945 let mut luma = Plane {
946 source: &picture_y8,
947 reconstruction: vec![128; picture_y8.len()],
948 width: picture.width,
949 height: picture.height,
950 true_width,
951 true_height,
952 tile_x0: 0,
953 tile_y0: 0,
954 tile_x1: picture.width,
955 tile_y1: picture.height,
956 ctx: CoefCtxMap::default(),
957 };
958 let mut chroma = [
959 Plane {
960 source: &picture_u8,
961 reconstruction: vec![128; picture_u8.len()],
962 width: picture.width / 2,
963 height: picture.height / 2,
964 true_width: true_width / 2,
965 true_height: true_height / 2,
966 tile_x0: 0,
967 tile_y0: 0,
968 tile_x1: picture.width / 2,
969 tile_y1: picture.height / 2,
970 ctx: CoefCtxMap::default(),
971 },
972 Plane {
973 source: &picture_v8,
974 reconstruction: vec![128; picture_v8.len()],
975 width: picture.width / 2,
976 height: picture.height / 2,
977 true_width: true_width / 2,
978 true_height: true_height / 2,
979 tile_x0: 0,
980 tile_y0: 0,
981 tile_x1: picture.width / 2,
982 tile_y1: picture.height / 2,
983 ctx: CoefCtxMap::default(),
984 },
985 ];
986
987 // The search trades a bit for the squared error it saves, in the units the
988 // reconstruction is measured in: one step of the quantizer, squared.
989 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
990 let search = Search {
991 base_q_idx,
992 deadzone,
993 lambda: lambda_scale() * key_lambda_factor() * step * step,
994 modes,
995 top_k: prune_top_k(),
996 screen,
997 arf_leaf_intra: true,
998 arf_leaf8: true,
999 arf_leaf_compound: true,
1000 };
1001
1002 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
1003 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
1004 // which may be fewer columns/rows than the padded picture has room for
1005 // -- a block whose origin sits past the true bound is not coded at all,
1006 // matching what a decoder derives from `frame_width`/`frame_height` and
1007 // so never visits either.
1008 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
1009 let (cols, rows) = (cols as usize, rows as usize);
1010 // The luma mode of the block above and of the block to the left, which is
1011 // what picks the CDF the next block's mode is coded against -- the same
1012 // bookkeeping the tile writer keeps, so that the search is costing the
1013 // symbol the writer will actually write.
1014 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
1015 // because a 32x32 block may be split into four 16x16 ones.
1016 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
1017 // This frame's tile grid (one tile unless the facade armed more).
1018 let layout = crate::tile::TileLayout::new(
1019 header.mi_cols,
1020 header.mi_rows,
1021 tile_cols_log2,
1022 tile_rows_log2,
1023 );
1024 header.tile_info = tile_info_of(&layout, 1);
1025 // The filter search re-decodes this frame's tiles; the decoder derives
1026 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
1027 // `mi_row_starts`), which is what makes the writer's rects and the
1028 // reader's the same rects.
1029 let header_tile_info = header.tile_info.clone();
1030 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
1031 // once over the whole frame. Each tile job builds its own reconstruction
1032 // planes and its own `above_mode`/`left_mode` bands, which is also what
1033 // the tile writer reads -- a tile resets its neighbour contexts (spec
1034 // 5.11.1), so a block at a tile's left edge must cost its mode against
1035 // the default context, not against whatever the tile to its west left in
1036 // that row. At one tile the bands are the frame's, exactly as before.
1037 let (frame_width, frame_height) = (picture.width, picture.height);
1038 let search_tile = |index: usize,
1039 fctx: &crate::decode::FrameCtx|
1040 -> Result<(Vec<(usize, Superblock, Vec<u8>)>, TilePixels)> {
1041 crate::tile::arm_pricing_cdfs(None, false);
1042 let rect = layout.rect(index);
1043 let mut luma = fresh_plane(
1044 &picture_y8,
1045 frame_width,
1046 frame_height,
1047 true_width,
1048 true_height,
1049 );
1050 let mut chroma = [
1051 fresh_plane(
1052 &picture_u8,
1053 frame_width / 2,
1054 frame_height / 2,
1055 true_width / 2,
1056 true_height / 2,
1057 ),
1058 fresh_plane(
1059 &picture_v8,
1060 frame_width / 2,
1061 frame_height / 2,
1062 true_width / 2,
1063 true_height / 2,
1064 ),
1065 ];
1066 clip_planes_to_tile(&mut luma, &mut chroma, rect);
1067 let mut above_mode = vec![DC_PRED; cols * 2];
1068 let mut left_mode = vec![DC_PRED; rows * 2];
1069 let mut ibc = allow_intrabc.then(|| {
1070 Ibc::new(
1071 (
1072 rect.mi_col0 as usize * 4,
1073 rect.mi_row0 as usize * 4,
1074 (rect.mi_col1 as usize * 4).min(true_width),
1075 (rect.mi_row1 as usize * 4).min(true_height),
1076 ),
1077 &picture_y8,
1078 frame_width,
1079 )
1080 });
1081 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
1082 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
1083 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
1084 let mut modes = Vec::with_capacity(4);
1085 // The quadrants of a superblock are coded in the order the decoder
1086 // walks them, which for a 64x64 split into 32x32 blocks is raster
1087 // order among the quadrants that are inside the frame.
1088 let mut blocks = Vec::with_capacity(4);
1089 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
1090 // BEFORE its quadrants (so both start from the same
1091 // reconstruction) and compared against the four of them below --
1092 // the shape the inter frame's own 64 root takes
1093 // (`search_skip_64`). A frame that allows intrabc is refused
1094 // outright ([`I64_ROOT`]) because the quadrant searches below
1095 // carry DV state a discarded trial would desync.
1096 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
1097 // lane-corner LIFTED the two guards this root shipped with: the
1098 // frame no longer has to be a whole number of superblocks, and
1099 // the superblock no longer has to be wholly inside the frame.
1100 // The desync the guards were written for (a 248x152 corner's
1101 // chroma disagreeing three ways) does NOT reproduce at this
1102 // revision -- see
1103 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
1104 // which pins all three planes of the encoder's reconstruction,
1105 // our decoder and ffmpeg on four straddling sizes, three of them
1106 // cut on BOTH axes, with the edge fire count asserted. What the
1107 // guards cost was every key-frame root on an arbitrary export
1108 // size (the `aligned` line switched the whole feature off on, for
1109 // instance, a 1920x792 frame).
1110 let whole_inside =
1111 x64 + SUPERBLOCK <= luma.true_width && y64 + SUPERBLOCK <= luma.true_height;
1112 // lane-corner: and the superblock the true frame edge CUTS
1113 // THROUGH with more than half of each axis still inside, which is
1114 // all AV1 asks of a `PARTITION_NONE` root (spec
1115 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
1116 // key writer's `Superblock::Whole` arm checks) -- the shape the
1117 // inter root already takes ([`b64_edge`]).
1118 let edge_inside = edge_root_enabled()
1119 && crate::tile::has_half(
1120 sb_col as u32 * crate::tile::SB_MI,
1121 crate::tile::SB_MI,
1122 header.mi_cols,
1123 )
1124 && crate::tile::has_half(
1125 sb_row as u32 * crate::tile::SB_MI,
1126 crate::tile::SB_MI,
1127 header.mi_rows,
1128 );
1129 let sb64_legal = i64_root()
1130 && ibc.is_none()
1131 && sb_row * 2 + 1 < rows
1132 && sb_col * 2 + 1 < cols
1133 && (whole_inside || edge_inside);
1134 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
1135 if sb64_legal {
1136 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1137 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
1138 let (c64, r64) = (sb_col * 4, sb_row * 4);
1139 let (block, cost) = code_square(
1140 &mut luma,
1141 &mut chroma,
1142 (x64, y64),
1143 SUPERBLOCK,
1144 &search,
1145 &mode_bits(above_mode[c64], left_mode[r64]),
1146 tx_select,
1147 None,
1148 true,
1149 fctx,
1150 );
1151 let cost =
1152 cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
1153 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
1154 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
1155 sb64 = Some((cost, block, after));
1156 }
1157 // A superblock whose 64x64 trial already codes almost nothing per
1158 // pixel is taken outright and its quadrants are never searched --
1159 // `split_rd_breakout` one size up, at the threshold the inter
1160 // root clamps to ([`b64_breakout_threshold`]), where this lever
1161 // BUYS wall instead of spending it.
1162 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
1163 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
1164 });
1165 // What the four quadrants cost together, including the split
1166 // partition symbol at the superblock level, so the two arms are
1167 // one comparable number.
1168 let mut sb_cost = match sb64 {
1169 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
1170 None => 0.0,
1171 };
1172 for quadrant in 0..if early64 { 0 } else { 4 } {
1173 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
1174 if col >= cols || row >= rows {
1175 continue;
1176 }
1177 let (x, y) = (col * BLOCK, row * BLOCK);
1178 let (c0, r0) = (col * 2, row * 2);
1179 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
1180
1181 // spec `decode_partition`'s hasRows/hasCols recomputed at this
1182 // 32x32 block's own half (see `crate::tile::has_half`): the
1183 // true frame edge can fall inside a quadrant a superblock-level
1184 // check already let through. A quadrant that fails either may
1185 // not be left whole; a 16x16 sub-block that fails either (once
1186 // split) is a leaf this writer has no rectangular transform
1187 // for, so the search must not pick a split that would need one.
1188 let (has_cols32, has_rows32) = (
1189 crate::tile::has_half(
1190 col as u32 * crate::tile::BLOCK_MI,
1191 crate::tile::BLOCK_MI,
1192 header.mi_cols,
1193 ),
1194 crate::tile::has_half(
1195 row as u32 * crate::tile::BLOCK_MI,
1196 crate::tile::BLOCK_MI,
1197 header.mi_rows,
1198 ),
1199 );
1200 let whole_legal = has_cols32 && has_rows32;
1201 // A 16x16 sub-block's own hasCols/hasRows (spec
1202 // `decode_partition`, recomputed at this leaf's own half):
1203 // either axis false is a straddling leaf this writer codes as
1204 // the 8x8 leaves that are inside it
1205 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
1206 // false is the same split with the partition symbol inferred
1207 // rather than coded -- no rectangular transform is needed
1208 // (lane-av1rect).
1209 let sub_half = |sr: usize, sc: usize| {
1210 (
1211 crate::tile::has_half(
1212 sc as u32 * crate::tile::SUB_MI,
1213 crate::tile::SUB_MI,
1214 header.mi_cols,
1215 ),
1216 crate::tile::has_half(
1217 sr as u32 * crate::tile::SUB_MI,
1218 crate::tile::SUB_MI,
1219 header.mi_rows,
1220 ),
1221 )
1222 };
1223 // What the whole 32x32 costs, including the partition symbol
1224 // that says it is not split.
1225 let (whole, mut cost_whole) = code_square(
1226 &mut luma,
1227 &mut chroma,
1228 (x, y),
1229 BLOCK,
1230 &search,
1231 &mode_bits(above_mode[c0], left_mode[r0]),
1232 tx_select,
1233 ibc.as_mut(),
1234 true,
1235 fctx,
1236 );
1237 cost_whole += search.lambda * partition_bits(BLOCK, false);
1238 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
1239
1240 // What four 16x16 blocks cost instead, each searched against
1241 // the reconstruction the ones before it left.
1242 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
1243 let mut split = Vec::with_capacity(4);
1244 let mut cost_split = search.lambda
1245 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
1246 let mut split_modes = Vec::with_capacity(4);
1247 for sub in 0..4 {
1248 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
1249 // Same filter as the writer's `sub_positions` (spec
1250 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
1251 // return): a sub-block whose own origin sits past the
1252 // true frame is never coded, so it must not be searched
1253 // or pushed onto `split` either, or the writer's block
1254 // count will not match what it is prepared to name.
1255 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
1256 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
1257 {
1258 continue;
1259 }
1260 let (has_cols16, has_rows16) = sub_half(sr, sc);
1261 if has_cols16 && has_rows16 {
1262 let (block, cost) = code_square(
1263 &mut luma,
1264 &mut chroma,
1265 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
1266 SUB,
1267 &search,
1268 &mode_bits(above_mode[sc], left_mode[sr]),
1269 tx_select,
1270 ibc.as_mut(),
1271 true,
1272 fctx,
1273 );
1274 cost_split += cost;
1275 split_modes.push(block.mode);
1276 above_mode[sc] = block.mode;
1277 left_mode[sr] = block.mode;
1278 split.push(block);
1279 } else {
1280 // A straddling 16x16: two (or, at a true corner, one)
1281 // 8x8 leaves, in the raster order `write_leaf8`'s
1282 // caller expects. Both leaves cost against the SAME
1283 // enclosing-slot mode context (see
1284 // `crate::tile::write_leaf8`'s doc), and neither
1285 // updates `above_mode`/`left_mode` at this SUB slot --
1286 // the writer never does either, so the search must
1287 // not diverge from what it will actually read next.
1288 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
1289 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
1290 let mut leaves = Vec::with_capacity(2);
1291 for i in 0..4 {
1292 let leaf_x = x_sub + (i % 2) * 8;
1293 let leaf_y = y_sub + (i / 2) * 8;
1294 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
1295 continue;
1296 }
1297 let (leaf, cost) = code_square(
1298 &mut luma,
1299 &mut chroma,
1300 (leaf_x, leaf_y),
1301 8,
1302 &search,
1303 &leaf_mode_bits,
1304 tx_select,
1305 None,
1306 true,
1307 fctx,
1308 );
1309 cost_split += cost;
1310 split_modes.push(leaf.mode);
1311 leaves.push(leaf);
1312 }
1313 split.push(BlockCoeffs {
1314 eight: Some(leaves),
1315 ..BlockCoeffs::default()
1316 });
1317 }
1318 }
1319
1320 // A split whose subs are all whole 16x16 is a real quality
1321 // alternative to `whole`, exactly as before. Through r14, a
1322 // split carrying an 8x8-leaf sub was only ever forced
1323 // (`!whole_legal`), never chosen on cost, because the leaf
1324 // path was not yet proven against a real decoder; r15 proved
1325 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
1326 // the read path (`decode_leaf8`), so leaf8 can now win on
1327 // cost anywhere, same as any other split.
1328 if !whole_legal || (split_blocks && cost_split < cost_whole) {
1329 sb_cost += cost_split;
1330 modes.extend_from_slice(&split_modes);
1331 blocks.push(Quadrant::Split(split));
1332 } else {
1333 sb_cost += cost_whole;
1334 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
1335 for cell in 0..2 {
1336 above_mode[c0 + cell] = whole.mode;
1337 left_mode[r0 + cell] = whole.mode;
1338 }
1339 modes.push(whole.mode);
1340 blocks.push(Quadrant::Whole(whole));
1341 }
1342 }
1343 let index = sb_row * sb_cols + sb_col;
1344 match sb64 {
1345 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
1346 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
1347 for cell in 0..4 {
1348 above_mode[sb_col * 4 + cell] = block.mode;
1349 left_mode[sb_row * 4 + cell] = block.mode;
1350 }
1351 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1352 if !whole_inside {
1353 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1354 }
1355 let mode = block.mode;
1356 coded.push((index, Superblock::Whole(block), vec![mode]));
1357 }
1358 _ => coded.push((index, Superblock::Split(blocks), modes)),
1359 }
1360 }
1361 }
1362 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
1363 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
1364 let luma_rect = (x0, y0, x1, y1);
1365 let chroma_rect = (x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
1366 let pixels = TilePixels {
1367 luma_rect,
1368 chroma_rect,
1369 luma: take_rect(&luma.reconstruction, frame_width, luma_rect),
1370 chroma: [
1371 take_rect(&chroma[0].reconstruction, frame_width / 2, chroma_rect),
1372 take_rect(&chroma[1].reconstruction, frame_width / 2, chroma_rect),
1373 ],
1374 };
1375 Ok((coded, pixels))
1376 };
1377 // Each tile's reconstructed rectangles are copied back here, on this
1378 // thread. The rectangles partition the frame, so the copy order does not
1379 // change the bytes.
1380 let searched = search_tiles(layout.count(), fctx, search_tile)?;
1381 let mut searched_coded = Vec::with_capacity(searched.len());
1382 for (coded, pixels) in searched {
1383 put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma);
1384 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {
1385 put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes);
1386 }
1387 searched_coded.push(coded);
1388 }
1389 let searched = searched_coded;
1390 // Back into frame raster order: the tile writer indexes `superblocks` by
1391 // the frame's own superblock index, and `modes` is the coding order the
1392 // ablation drivers read.
1393 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> =
1394 (0..sb_cols * sb_rows).map(|_| None).collect();
1395 for (at, superblock, block_modes) in searched.into_iter().flatten() {
1396 in_order[at] = Some((superblock, block_modes));
1397 }
1398 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
1399 let mut modes = Vec::with_capacity(cols * rows);
1400 for slot in in_order {
1401 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
1402 superblocks.push(superblock);
1403 modes.extend_from_slice(&block_modes);
1404 }
1405
1406 #[cfg(test)]
1407 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(
1408 &superblocks,
1409 base_q_idx,
1410 ));
1411 // A key frame always starts from the defaults (`primary_ref_frame` is
1412 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
1413 // set, so what it stores into the slots it refreshes is exactly those
1414 // defaults again (spec 7.20's `started_from` arm) -- the first inter
1415 // frame after it therefore starts from the defaults too.
1416 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
1417 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
1418 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
1419 // from -- `Cdfs::txb` widens every luma set under it.
1420 cdfs.reduced_tx_set = header.reduced_tx_set;
1421 let start_cdfs = CdfSnapshot(cdfs);
1422 // The luma restoration-unit grid this frame's `lr_params` implies
1423 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
1424 // swallowed by the one before it), for the tile writer's own per-unit
1425 // walk.
1426 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
1427 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
1428 // Every tile is coded from this frame's OWN starting tables and leaves
1429 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
1430 // loop-restoration reference and its neighbour contexts), so the tiles
1431 // are independent of each other and of the order they are written in.
1432 let code_tiles = |bits: u8,
1433 sb_cols: usize,
1434 grid: &[u8],
1435 units: &[Option<crate::restoration::WienerInfo>]|
1436 -> Result<Vec<Vec<u8>>> {
1437 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
1438 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
1439 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
1440 crate::tile::arm_sb128(sb128_on());
1441 let mut cdfs = start_cdfs.0.clone();
1442 crate::tile::arm_screen(screen);
1443 crate::tile::arm_frame_mi_dims(frame_mi_dims);
1444 crate::tile::arm_filter_intra(filter_intra_on());
1445 crate::tile::arm_intrabc(allow_intrabc);
1446 crate::tile::arm_pricing_cdfs(None, false);
1447 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
1448 mi_cols,
1449 mi_rows,
1450 base_q_idx,
1451 &superblocks,
1452 tx_select,
1453 &mut cdfs,
1454 layout.rect(index),
1455 )?;
1456 Ok((bytes, None))
1457 })?;
1458 Ok(out)
1459 };
1460 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
1461 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
1462 // the tile just coded back to the decoder under each candidate (see
1463 // `crate::filter_search`), and keep the filtered picture that wins as
1464 // the reconstruction -- what a decoder outputs, and what the next
1465 // frame predicts from.
1466 pick_and_apply_filters(
1467 &mut header,
1468 &mut luma,
1469 &mut chroma,
1470 [&picture_y8, &picture_u8, &picture_v8],
1471 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
1472 // and loop restoration off and codes none of their parameters
1473 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
1474 // the encoder's reconstruction is already what a decoder produces.
1475 !allow_intrabc,
1476 &mut tiles,
1477 search.lambda,
1478 fctx,
1479 // A key frame codes no 128x128 root block (the writer has no intra
1480 // path at that size), so every unit carries its own literal.
1481 &[],
1482 // Every re-code starts from this frame's OWN starting tables, never
1483 // from where the first write left them: the second tile is the same
1484 // symbol sequence plus new ones, so it must adapt from the same
1485 // point the decoder will.
1486 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
1487 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
1488 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
1489 crate::decode::decode_key_frame_tiles_lr(
1490 &payloads,
1491 &header_tile_info,
1492 h.mi_cols,
1493 h.mi_rows,
1494 base_q_idx,
1495 h.frame_width,
1496 h.frame_height,
1497 seq.enable_filter_intra,
1498 cdef,
1499 lf,
1500 tx_select,
1501 h.reduced_tx_set,
1502 h.allow_screen_content_tools,
1503 h.allow_intrabc,
1504 lr,
1505 fctx,
1506 )
1507 },
1508 )?;
1509 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
1510 header.tile_info.tile_size_bytes = tile_size_bytes;
1511 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
1512 let mut stream = temporal_delimiter();
1513 stream.extend_from_slice(&sequence_header_obu(&seq)?);
1514 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
1515
1516 let [u, v] = chroma;
1517 Ok(Encoded {
1518 stream,
1519 modes,
1520 inter_block_share: 0.0,
1521 reconstruction: Picture {
1522 width: luma.width,
1523 height: luma.height,
1524 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
1525 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
1526 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
1527 },
1528 tile,
1529 mi_cols: header.mi_cols,
1530 mi_rows: header.mi_rows,
1531 base_q_idx,
1532 tx_select,
1533 // A key frame codes no inter block, so no motion_mode symbol.
1534 switchable_motion_mode: false,
1535 screen,
1536 reduced_tx_set: header.reduced_tx_set,
1537 next_cdfs: Box::new(start_cdfs.clone()),
1538 start_cdfs: Box::new(start_cdfs),
1539 loop_filter: header.loop_filter,
1540 cdef: header.cdef,
1541 loop_restoration: header.loop_restoration,
1542 allow_intrabc,
1543 delta: header.delta,
1544 })
1545}
1546
1547/// Chooses this frame's deblocking levels and CDEF strengths, writes them
1548/// into `header` and
1549/// replaces the frame's own region of the encoder's reconstruction with the
1550/// filtered picture the decoder produced under them
1551/// ([`crate::filter_search::pick_deblock`]).
1552///
1553/// `search == false` leaves the header at level 0 (deblocking off) and the
1554/// reconstruction untouched: the caller's stream is one this crate's own
1555/// decoder cannot read back, so there is nothing to search against.
1556///
1557/// # Errors
1558/// The decoder's own error, when it refuses the tile the encoder just wrote
1559/// -- that is an encoder defect, not a filter one, so it is propagated
1560/// rather than swallowed into "no deblocking".
1561// Spec-shaped signature; bundling the operands would obscure the spec mapping.
1562#[allow(clippy::too_many_arguments)]
1563pub(super) fn pick_and_apply_filters(
1564 header: &mut FrameHeader,
1565 luma: &mut Plane<'_>,
1566 chroma: &mut [Plane<'_>; 2],
1567 source: [&[u8]; 3],
1568 search: bool,
1569 // The coded tiles, one payload per tile of the frame's grid, replaced in
1570 // place when the search chooses a per-64x64 `cdef_idx` list
1571 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
1572 // tile is written a second time under `recode` and the winner
1573 // re-decoded from them.
1574 tiles: &mut Vec<Vec<u8>>,
1575 lambda: f64,
1576 fctx: &crate::decode::FrameCtx,
1577 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
1578 // carry -- empty (the identity map) for a frame whose every block covers
1579 // one 64x64 CDEF unit.
1580 cdef_owner: &[u32],
1581 recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<Vec<u8>>>,
1582 decode: impl Fn(
1583 &LoopFilterParams,
1584 &CdefParams,
1585 &FrameHeader,
1586 &[Vec<u8>],
1587 &LoopRestorationParams,
1588 ) -> Result<Picture>,
1589) -> Result<()> {
1590 if !search {
1591 return Ok(());
1592 }
1593 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
1594 let hdr = header.clone();
1595 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
1596 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
1597 let damping = 3 + (header.quantization.base_q_idx >> 6);
1598 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
1599 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
1600 let none_lr = LoopRestorationParams::default();
1601 // Every candidate scores the same coded tile: decode it once and re-run
1602 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
1603 // the encoder's profile before this). The per-64x64 error the CDEF
1604 // preset search reads comes off the REPLAYED picture, which is the same
1605 // picture a decode produces -- that is what the replay is pinned on.
1606 crate::decode::clear_filter_replay();
1607 // lane-av1fpar: the per-tile search is over, so every core is idle from
1608 // here to the end of the frame -- band each candidate's deblock/CDEF
1609 // replay, the capture decode's own filter chain and the loop-restoration
1610 // passes across the same workers the search used.
1611 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
1612 let ft = crate::par::timer(crate::par::S_FILTER);
1613 let search_result = crate::filter_search::pick_filters(
1614 |lf, cdef| {
1615 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
1616 return Ok(picture);
1617 }
1618 crate::decode::arm_filter_replay();
1619 let _t = crate::par::timer(crate::par::S_FIRST);
1620 decode(lf, cdef, &hdr, tiles, &none_lr)
1621 },
1622 source,
1623 luma.width,
1624 (fw, fh),
1625 damping,
1626 (sb_cols, sb_rows),
1627 lambda,
1628 cdef_owner,
1629 );
1630 drop(ft);
1631 let (lf, cdef, idx_grid, picture) = search_result?;
1632 header.loop_filter = lf;
1633 header.cdef = cdef;
1634 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
1635 // in the frame header, so a re-decode under candidate parameters cannot
1636 // search them the way deblocking and CDEF are searched above. What the
1637 // decoder hands back instead is its own filter chain's intermediates
1638 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
1639 // those, through the decoder's own Wiener kernel.
1640 //
1641 // The capture rides the decode this stage was already going to do: the
1642 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
1643 // decode of the tile as it stands. That decode's header still says
1644 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
1645 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
1646 // an approximation inside the SEARCH only; the reconstruction this
1647 // function ends up splicing is always a real decode of the real tile.
1648 let lr_on = restoration_enabled();
1649 // The `cdef_idx` literals live in the tile payload, so a frame that
1650 // chose a per-64x64 preset list codes its tiles a second time.
1651 if !idx_grid.is_empty() {
1652 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
1653 }
1654 // lane-av1cap: that re-coded tile used to be DECODED here as well --
1655 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
1656 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
1657 // and the picture this function splices. Both come out of ONE more
1658 // replay of the winning parameters on the same captured pre-filter
1659 // planes every candidate was scored on: the same two filter kernels, on
1660 // the same input, in the same order, so the same bytes. Re-coding the
1661 // tile does not move the reconstruction the replay holds -- `cdef_idx`
1662 // is an equiprobable literal, so it adapts no CDF and changes no
1663 // residual.
1664 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
1665 #[cfg(test)]
1666 let replay_was_used = replayed.is_some();
1667 let (mut filtered, mut stages) = match replayed {
1668 Some((picture, stages)) => (picture, stages),
1669 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
1670 // refuses): every candidate was a full decode, so the winner's own
1671 // picture stands, and the stages still need a capturing decode.
1672 None => {
1673 fctx.capture_stages.set(lr_on);
1674 let picture = if idx_grid.is_empty() && !lr_on {
1675 picture
1676 } else {
1677 let _t = crate::par::timer(crate::par::S_CAPTURE);
1678 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
1679 };
1680 fctx.capture_stages.set(false);
1681 (picture, crate::decode::take_filter_stages(fctx))
1682 }
1683 };
1684 #[cfg(test)]
1685 if crate::decode::verify_final_replay() && replay_was_used {
1686 fctx.capture_stages.set(lr_on);
1687 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
1688 fctx.capture_stages.set(false);
1689 let want_stages = crate::decode::take_filter_stages(fctx);
1690 assert!(
1691 (want.width, want.height) == (filtered.width, filtered.height)
1692 && want.y == filtered.y
1693 && want.u == filtered.u
1694 && want.v == filtered.v,
1695 "the final filter replay is not the capture decode it stands in for",
1696 );
1697 // Only the frame's own cropped region: the plane is padded to the
1698 // superblock grid and the columns past the mi extent are written by
1699 // nothing (the decoder's plane pool leaves whatever the last frame
1700 // put there), while the restoration search reads strictly inside
1701 // `fw x fh` -- `restoration::lr_sample` clamps its column to
1702 // `plane_w - 1` and its row to the frame's, and
1703 // `filter_search::pick_restoration`'s own SSE walk never leaves the
1704 // crop either.
1705 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
1706 for row in 0..h {
1707 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
1708 assert!(
1709 x == y,
1710 "{what}: the replayed filter stages are not the ones the capture \
1711 decode returns (row {row} of {h}, width {w}, stride {stride})",
1712 );
1713 }
1714 };
1715 match (&want_stages, &stages) {
1716 (Some(a), Some(b)) => {
1717 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
1718 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
1719 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
1720 region(
1721 &a.deblocked[i],
1722 &b.deblocked[i],
1723 a.stride[i],
1724 w,
1725 h,
1726 "deblocked",
1727 );
1728 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
1729 }
1730 }
1731 (None, None) => {}
1732 _ => panic!("one path captured filter stages and the other did not"),
1733 }
1734 }
1735 // lane-av1cap2: the capture stays live past the restoration search --
1736 // `crate::decode::replay_restoration` filters the same post-CDEF plane
1737 // rather than decoding the re-coded tile. Cleared at the end instead.
1738 let mut lr = LoopRestorationParams::default();
1739 if lr_on {
1740 let unit = lr_unit();
1741 let mut want = LoopRestorationParams {
1742 loop_restoration_size: [unit, unit, unit],
1743 uses_lr: true,
1744 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
1745 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
1746 lr_unit_shift: u8::from(unit == 128),
1747 ..LoopRestorationParams::default()
1748 };
1749 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
1750 let lrt = crate::par::timer(crate::par::S_LR);
1751 let units = match stages.take() {
1752 Some(stages) => crate::filter_search::pick_restoration(
1753 &stages,
1754 source[0],
1755 luma.width,
1756 (fw, fh),
1757 &want,
1758 lambda,
1759 fctx,
1760 ),
1761 None => Vec::new(),
1762 };
1763 // A frame no unit restores keeps `RESTORE_NONE` on every plane
1764 // rather than paying ~1 bit per 64x64 for a tile full of
1765 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
1766 // clip whose units never take a filter).
1767 drop(lrt);
1768 if units.iter().any(Option::is_some) {
1769 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
1770 let _t = crate::par::timer(crate::par::S_CAPTURE);
1771 // lane-av1cap2: that re-coded tile used to be DECODED here to
1772 // reach the restored reference frame -- 5.6% of a 4K frame,
1773 // for a filter that reads nothing of the tile but the per-unit
1774 // Wiener filters this stage just chose. Run the decoder's own
1775 // restoration kernel on the replay's post-CDEF plane instead
1776 // (`crate::decode::replay_restoration`), with the real
1777 // post-deblock stripe borders.
1778 match crate::decode::replay_restoration(&want, &units, fctx) {
1779 Some(y) => {
1780 #[cfg(test)]
1781 let margin = fctx
1782 .last_frame_wide_margin
1783 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
1784 #[cfg(test)]
1785 if crate::decode::verify_final_replay() {
1786 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
1787 assert!(
1788 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
1789 && want_pic.u == filtered.u
1790 && want_pic.v == filtered.v,
1791 "the restoration replay moved a chroma plane or the picture size",
1792 );
1793 assert!(
1794 want_pic.y == y,
1795 "the restoration replay is not the decode of the re-coded tile",
1796 );
1797 assert!(
1798 fctx.last_frame_wide_margin
1799 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
1800 == margin,
1801 "the restoration replay's wide-margin luma is not the decode's",
1802 );
1803 }
1804 filtered.y = y;
1805 }
1806 // Nothing captured: the winner came out of a full decode,
1807 // so this one does too.
1808 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
1809 }
1810 *tiles = coded;
1811 lr = want;
1812 }
1813 }
1814 crate::decode::clear_filter_replay();
1815 header.loop_restoration = lr;
1816 let dec_cw = filtered.width.div_ceil(2);
1817 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
1818 crate::filter_search::splice(
1819 &mut luma.reconstruction,
1820 luma.width,
1821 &filtered.y,
1822 filtered.width,
1823 fw,
1824 fh,
1825 );
1826 crate::filter_search::splice(
1827 &mut chroma[0].reconstruction,
1828 chroma[0].width,
1829 &filtered.u,
1830 dec_cw,
1831 cw,
1832 ch,
1833 );
1834 crate::filter_search::splice(
1835 &mut chroma[1].reconstruction,
1836 chroma[1].width,
1837 &filtered.v,
1838 dec_cw,
1839 cw,
1840 ch,
1841 );
1842 Ok(())
1843}
1844
1845/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
1846/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
1847/// since every block this crate's inter tile writer codes is 32x32.
1848pub(super) const SIZE_GROUP_32: usize = 3;
1849
1850/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
1851/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
1852/// stack this encoder builds is ever asked to predict against.
1853pub(super) const LAST_FRAME: i8 = 1;
1854
1855/// What an inter frame's intra branch spends to name each of the thirteen
1856/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
1857/// context, since an inter frame's intra blocks do not read their
1858/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
1859/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
1860/// state, so it is built once per frame.
1861pub(super) fn inter_mode_bits() -> [f64; 13] {
1862 std::array::from_fn(|mode| {
1863 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
1864 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
1865 } else {
1866 0.0
1867 };
1868 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
1869 + angle
1870 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
1871 })
1872}
1873
1874/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
1875/// [`mc::predict`] takes, in the units of the plane it predicts into.
1876///
1877/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
1878/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
1879/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
1880/// domain. `luma` picks which.
1881pub(super) fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
1882 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
1883}
1884
1885/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
1886/// that module): the magnitude an `MV_CLASS_n` component's own bits start
1887/// counting from.
1888pub(super) fn mv_class_base(class: usize) -> i32 {
1889 if class == 0 { 0 } else { 2i32 << (class + 2) }
1890}
1891
1892/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
1893/// `tile::mv_class_of`.
1894pub(super) fn mv_class_of(z: i32) -> usize {
1895 let mut class = 0;
1896 while class < 10 && mv_class_base(class + 1) <= z {
1897 class += 1;
1898 }
1899 class
1900}
1901
1902/// What [`crate::tile::write_mv_component`] (private to that module) would
1903/// spend coding one non-zero motion vector component, against the same
1904/// static default CDFs the writer starts a frame from — the same
1905/// static-table approximation [`mode_bits`] costs the luma mode symbol
1906/// through, not the tile writer's own adapting state, which this encoder has
1907/// no way to read without duplicating it block for block.
1908///
1909/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
1910/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
1911/// exists to avoid ever happening.
1912pub(super) fn mv_component_bits(diff: i32) -> Option<f64> {
1913 let hp_frame = crate::tile::high_precision_mv();
1914 let mag = diff.unsigned_abs() as i32;
1915 let z = mag - 1;
1916 if !hp_frame && z & 1 == 0 {
1917 return None;
1918 }
1919 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
1920 let class = mv_class_of(z);
1921 bits += symbol_bits(&cdf::MV_CLASS, class);
1922 let local = z - mv_class_base(class);
1923 let hp = (local & 1) as usize;
1924 if class == 0 {
1925 let bit = (local >> 3) & 1;
1926 let fr = (local >> 1) & 3;
1927 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
1928 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
1929 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
1930 // frame, so the pricer charges for it there and only there.
1931 if hp_frame {
1932 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
1933 }
1934 } else {
1935 let d = local >> 3;
1936 let fr = (local >> 1) & 3;
1937 for i in 0..class {
1938 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
1939 }
1940 bits += symbol_bits(&cdf::MV_FR, fr as usize);
1941 if hp_frame {
1942 bits += symbol_bits(&cdf::MV_HP, hp);
1943 }
1944 }
1945 Some(bits)
1946}
1947
1948/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
1949/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
1950/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
1951/// value without the second motion search's wall.
1952pub(super) fn last2_new_mv() -> bool {
1953 match std::env::var("EC_AV1_LAST2_NEW").ok() {
1954 Some(v) => v != "0",
1955 None => true,
1956 }
1957}
1958
1959/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
1960/// own -- a second motion search per block against that reference's picture,
1961/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
1962/// off in a test build (what the lane measured both arms with).
1963pub(super) fn extra_ref_new_mv() -> bool {
1964 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
1965 Some(v) if cfg!(test) => v != "0",
1966 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
1967 }
1968}
1969
1970/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
1971/// flat slot plan (`inter_frame_headers_slots`): every reference but
1972/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
1973/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
1974/// frame two back when there is one (otherwise it, too, names the key frame's
1975/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
1976pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
1977 let last = order_hint.wrapping_sub(1) & 0x7f;
1978 let alt = if has_altref {
1979 order_hint.wrapping_sub(2) & 0x7f
1980 } else {
1981 key_hint
1982 };
1983 [last, last, last, key_hint, last, last, alt]
1984}
1985
1986/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
1987/// header bit that lets each block choose between a single and a compound
1988/// reference. Off by default until compound prediction is measured to pay;
1989/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
1990/// runs as), and every block still codes SINGLE, so the only cost is one
1991/// `comp_mode` symbol per inter block.
1992pub(crate) const REFERENCE_SELECT: bool = true;
1993
1994/// [`REFERENCE_SELECT`], with the test-build environment override.
1995pub(crate) fn reference_select() -> bool {
1996 match std::env::var("EC_AV1_COMPOUND").ok() {
1997 Some(v) if cfg!(test) => v != "0",
1998 _ => crate::speed::at(&crate::speed::COMPOUND),
1999 }
2000}
2001
2002/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
2003/// per entry past `start`, `1` to advance and `0` to stop, at most two.
2004pub(super) fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
2005 let mut bits = 0.0;
2006 let mut idx = start;
2007 while idx < start + 2 && stack.entries.len() > idx + 1 {
2008 let advance = idx < target;
2009 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
2010 if !advance {
2011 break;
2012 }
2013 idx += 1;
2014 }
2015 bits
2016}
2017
2018/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
2019/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
2020/// `assign_mv`), so the same vector costs a different residual from each.
2021pub(super) fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
2022 let mut best: Option<(f64, u8)> = None;
2023 for idx in 0..3usize {
2024 if idx > 0 && stack.entries.len() <= idx {
2025 break;
2026 }
2027 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
2028 if let Some(b) = mv_residual_bits(mv, base) {
2029 let total = b + drl_bits_for(stack, 0, idx);
2030 if best.is_none_or(|(t, _)| total < t) {
2031 best = Some((total, idx as u8));
2032 }
2033 }
2034 }
2035 best
2036}
2037
2038/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
2039/// zero vector and the stack's own candidates. A neighbour block's vector is
2040/// where this block's motion most often already is, which is what pays for
2041/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
2042/// vs libaom for 0.2 s off a 6 s ladder).
2043pub(super) fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
2044 let mut seeds = [(0, 0); 4];
2045 let mut n = 1;
2046 for e in stack.entries.iter().take(3) {
2047 seeds[n] = e.mv;
2048 n += 1;
2049 }
2050 (seeds, n)
2051}
2052
2053/// What [`crate::tile::write_mv`] (private to that module) would spend
2054/// coding `mv` as a residual against `pred`: the joint symbol naming which
2055/// components differ, then each differing component. `None` under the same
2056/// condition [`mv_component_bits`] returns `None`.
2057/// How many frames back `ref_frame` sits from the frame being coded, off the
2058/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
2059/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
2060/// what [`crate::motion::search`] scales its starting step by.
2061pub(super) fn ref_distance(ref_frame: i8) -> u32 {
2062 let (bits, order_hint, hints) = crate::tile::order_hints();
2063 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
2064 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
2065 .unsigned_abs()
2066 .max(1);
2067 if crate::envflags::env_flag!("EC_TRACE_DIST") {
2068 eprintln!(
2069 "EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}",
2070 hints[i]
2071 );
2072 }
2073 d
2074}
2075
2076pub(super) fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
2077 let diff = (mv.0 - pred.0, mv.1 - pred.1);
2078 let joint = match (diff.0 != 0, diff.1 != 0) {
2079 (false, false) => 0,
2080 (false, true) => 1,
2081 (true, false) => 2,
2082 (true, true) => 3,
2083 };
2084 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
2085 for d in [diff.0, diff.1] {
2086 if d != 0 {
2087 bits += mv_component_bits(d)?;
2088 }
2089 }
2090 Some(bits)
2091}
2092
2093/// Rounds `mv` so that its residual against `pred` is one
2094/// [`crate::tile::write_mv_component`] can actually code: each component's
2095/// difference is either zero or has an even magnitude (the eighth-pel bit
2096/// `allow_high_precision_mv` off always infers as one forces the coded
2097/// magnitude odd one step further in, which comes out even here since this
2098/// crate's motion search works in whole units of that same step). Rounding
2099/// down keeps every coded MV — and so every `nearest_mv` a later block's
2100/// stack votes with — built from an even displacement from `(0, 0)`, so the
2101/// invariant holds without this function seeing the whole stack.
2102/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
2103/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
2104/// always), the shape [`set_frame_interp`] has: the witness that has to see
2105/// `mv_hp` symbols coded turns it on through this while holding
2106/// [`crate::speed::knob_write`].
2107pub(super) static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2108
2109/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
2110#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2111pub(crate) fn set_high_precision_mv(on: Option<bool>) {
2112 HP_MV_OVERRIDE.store(
2113 on.map_or(u8::MAX, u8::from),
2114 std::sync::atomic::Ordering::Relaxed,
2115 );
2116}
2117
2118/// The qindex below which an inter frame codes `allow_high_precision_mv`
2119/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
2120/// crate's shipped value, i.e. high-precision motion vectors off in every
2121/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
2122pub(crate) const HP_MV_QTHRESH: u8 = 0;
2123
2124/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
2125/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
2126/// always, any number as the threshold) so the BD gate can sweep the policy
2127/// without a rebuild.
2128pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
2129 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2130 0 => return false,
2131 1 => return true,
2132 _ => {}
2133 }
2134 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
2135 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
2136 Some("all" | "always") => 256,
2137 Some("0" | "off") => 0,
2138 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
2139 None => u16::from(HP_MV_QTHRESH),
2140 });
2141 u16::from(base_q_idx) < threshold
2142}
2143
2144pub(super) fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
2145 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
2146 // residual is codable and there is nothing to round away.
2147 if crate::tile::high_precision_mv() {
2148 return mv;
2149 }
2150 let round = |m: i32, p: i32| {
2151 let diff = m - p;
2152 let mag = diff.unsigned_abs() as i32;
2153 let even = mag - mag % 2;
2154 if even == 0 {
2155 p
2156 } else {
2157 p + even * diff.signum()
2158 }
2159 };
2160 (round(mv.0, pred.0), round(mv.1, pred.1))
2161}
2162
2163/// Predicts one `side`-square block by motion compensation from `reference`
2164/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
2165#[allow(clippy::too_many_arguments)]
2166pub(super) fn mc_trial(
2167 plane: &Plane,
2168 x: usize,
2169 y: usize,
2170 side: usize,
2171 mv: (i32, i32),
2172 luma: bool,
2173 reference: &[u16],
2174 stride: usize,
2175 ref_width: usize,
2176 ref_height: usize,
2177 skip: bool,
2178 base_q_idx: u8,
2179 deadzone: f64,
2180 set: TxbSet,
2181 fctx: &crate::decode::FrameCtx,
2182) -> Trial {
2183 mc_trial_typed(
2184 plane,
2185 x,
2186 y,
2187 side,
2188 mv,
2189 luma,
2190 reference,
2191 stride,
2192 ref_width,
2193 ref_height,
2194 skip,
2195 base_q_idx,
2196 deadzone,
2197 set,
2198 TxType::DctDct,
2199 fctx,
2200 )
2201}
2202
2203/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
2204#[allow(clippy::too_many_arguments)]
2205pub(super) fn mc_trial_typed(
2206 plane: &Plane,
2207 x: usize,
2208 y: usize,
2209 side: usize,
2210 mv: (i32, i32),
2211 luma: bool,
2212 reference: &[u16],
2213 stride: usize,
2214 ref_width: usize,
2215 ref_height: usize,
2216 skip: bool,
2217 base_q_idx: u8,
2218 deadzone: f64,
2219 set: TxbSet,
2220 tx_type: TxType,
2221 fctx: &crate::decode::FrameCtx,
2222) -> Trial {
2223 let x_q4 = mv_to_q4(x, mv.1, luma);
2224 let y_q4 = mv_to_q4(y, mv.0, luma);
2225 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
2226 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
2227 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
2228 // lane-av1speed: both buffers are per-candidate scratch on the hottest
2229 // path in the encoder, so they live on the stack -- `side` is at most
2230 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
2231 // per motion-compensated trial otherwise.
2232 let mut prediction16 = [0u16; BLOCK * BLOCK];
2233 let prediction16 = &mut prediction16[..side * side];
2234 mc::predict(
2235 reference,
2236 stride,
2237 ref_width,
2238 ref_height,
2239 x_q4,
2240 y_q4,
2241 side,
2242 side,
2243 prediction16,
2244 fctx,
2245 );
2246 let mut prediction = [0u8; BLOCK * BLOCK];
2247 let prediction = &mut prediction[..side * side];
2248 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
2249 *dst = src as u8;
2250 }
2251 plane.code_from_prediction_typed(
2252 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
2253 )
2254}
2255
2256/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
2257/// references predict into the `CONV_BUF` intermediate domain
2258/// ([`mc::predict_compound_intermediate`]) and are blended by
2259/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
2260/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
2261/// block, so the encoder's reconstruction is the decoder's.
2262#[allow(clippy::too_many_arguments)]
2263pub(super) fn mc_trial_compound(
2264 plane: &Plane,
2265 x: usize,
2266 y: usize,
2267 side: usize,
2268 mvs: ((i32, i32), (i32, i32)),
2269 luma: bool,
2270 ref0: (&[u16], usize, usize, usize),
2271 ref1: (&[u16], usize, usize, usize),
2272 base_q_idx: u8,
2273 deadzone: f64,
2274 set: TxbSet,
2275 fctx: &crate::decode::FrameCtx,
2276) -> Trial {
2277 mc_trial_compound_typed(
2278 plane,
2279 x,
2280 y,
2281 side,
2282 mvs,
2283 luma,
2284 ref0,
2285 ref1,
2286 base_q_idx,
2287 deadzone,
2288 set,
2289 TxType::DctDct,
2290 fctx,
2291 )
2292}
2293
2294/// [`mc_trial_compound`] coding its residual with a named transform type
2295/// (lane-txset2).
2296#[allow(clippy::too_many_arguments)]
2297pub(super) fn mc_trial_compound_typed(
2298 plane: &Plane,
2299 x: usize,
2300 y: usize,
2301 side: usize,
2302 (mv0, mv1): ((i32, i32), (i32, i32)),
2303 luma: bool,
2304 ref0: (&[u16], usize, usize, usize),
2305 ref1: (&[u16], usize, usize, usize),
2306 base_q_idx: u8,
2307 deadzone: f64,
2308 set: TxbSet,
2309 tx_type: TxType,
2310 fctx: &crate::decode::FrameCtx,
2311) -> Trial {
2312 let mut inter0 = [0i32; BLOCK * BLOCK];
2313 let mut inter1 = [0i32; BLOCK * BLOCK];
2314 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
2315 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
2316 mc::predict_compound_intermediate(
2317 r.0,
2318 r.1,
2319 r.2,
2320 r.3,
2321 mv_to_q4(x, mv.1, luma),
2322 mv_to_q4(y, mv.0, luma),
2323 mc::RefScale::UNSCALED,
2324 side,
2325 side,
2326 fctx.interp_filter.get(),
2327 fctx.interp_filter.get(),
2328 dst,
2329 fctx,
2330 );
2331 }
2332 let mut blended16 = [0u16; BLOCK * BLOCK];
2333 let blended16 = &mut blended16[..side * side];
2334 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
2335 let mut prediction = [0u8; BLOCK * BLOCK];
2336 let prediction = &mut prediction[..side * side];
2337 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
2338 *dst = src as u8;
2339 }
2340 plane.code_from_prediction_typed(
2341 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
2342 )
2343}
2344
2345/// Codes one 32x32 block of an inter frame as whichever costs least of: each
2346/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
2347/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
2348/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
2349/// coding a real residual (`skip: false`) whenever one prices out cheaper
2350/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
2351/// missing inter `tx_type` symbol (the desync this function's candidates
2352/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
2353/// fixed.
2354///
2355/// The symbol costs this ranks candidates by use fixed contexts (0) for
2356/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
2357/// contexts for those come from its own neighbour bookkeeping
2358/// (`tile::Neighbours`), which is private to that module and not worth
2359/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
2360/// `drl_mode` contexts come straight from `stack`, which is exact, because
2361/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
2362/// the tile writer derives from the same grid state.
2363#[allow(clippy::too_many_arguments)]
2364/// One prediction of `side` x `side` samples from `reference`, as `u8` --
2365/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
2366/// four times the stack scratch that function sizes for [`BLOCK`].
2367pub(super) fn predict_u8(
2368 reference: &[u16],
2369 stride: usize,
2370 ref_width: usize,
2371 ref_height: usize,
2372 (x, y): (usize, usize),
2373 side: usize,
2374 mv: (i32, i32),
2375 luma: bool,
2376 fctx: &crate::decode::FrameCtx,
2377) -> Vec<u8> {
2378 let mut prediction = vec![0u16; side * side];
2379 mc::predict(
2380 reference,
2381 stride,
2382 ref_width,
2383 ref_height,
2384 mv_to_q4(x, mv.1, luma),
2385 mv_to_q4(y, mv.0, luma),
2386 side,
2387 side,
2388 &mut prediction,
2389 fctx,
2390 );
2391 prediction.iter().map(|&v| v as u8).collect()
2392}
2393
2394/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
2395/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
2396/// references predict into the `CONV_BUF` intermediate domain and are blended
2397/// at the simple-average split `(8, 8)`, the same path (and so the same
2398/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
2399pub(super) fn predict_compound_u8(
2400 ref0: (&[u16], usize, usize, usize),
2401 ref1: (&[u16], usize, usize, usize),
2402 (x, y): (usize, usize),
2403 side: usize,
2404 (mv0, mv1): ((i32, i32), (i32, i32)),
2405 luma: bool,
2406 fctx: &crate::decode::FrameCtx,
2407) -> Vec<u8> {
2408 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
2409 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
2410 mc::predict_compound_intermediate(
2411 r.0,
2412 r.1,
2413 r.2,
2414 r.3,
2415 mv_to_q4(x, mv.1, luma),
2416 mv_to_q4(y, mv.0, luma),
2417 mc::RefScale::UNSCALED,
2418 side,
2419 side,
2420 fctx.interp_filter.get(),
2421 fctx.interp_filter.get(),
2422 dst,
2423 fctx,
2424 );
2425 }
2426 let mut blended = vec![0u16; side * side];
2427 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
2428 blended.iter().map(|&v| v as u8).collect()
2429}
2430
2431/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
2432/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
2433/// one motion vector where the four 64x64 roots below spend four of each.
2434///
2435/// SKIP only (`residual: false`): a 128x128 block's residual is four
2436/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
2437/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
2438/// path for -- offering one here would price a block
2439/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
2440/// the same reason: the compound arm at this size is untested against the
2441/// writer's own `write_compound_block` window.
2442///
2443/// Only a root whose whole 128x128 lies inside the true frame AND inside
2444/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
2445/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
2446/// block would have to be ranked over its inside part alone.
2447///
2448/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
2449/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
2450/// against the four superblocks plus the SPLIT symbol.
2451#[allow(clippy::too_many_arguments)]
2452pub(super) fn search_root_128(
2453 luma: &mut Plane,
2454 chroma: &mut [Plane; 2],
2455 grid: &crate::mvstack::MiGrid,
2456 (root_r, root_c): (usize, usize),
2457 // The 32x32-block grid this tile's `blocks` vector is indexed on.
2458 (rows, cols): (usize, usize),
2459 // The frame's own mode-info grid, which bounds the root.
2460 (mi_cols, mi_rows): (u32, u32),
2461 search: Search<'_>,
2462 tpl_factors: &Option<Vec<f64>>,
2463 sb_q: Option<&Vec<u8>>,
2464 sb_cols: usize,
2465 tpl_cells_x: usize,
2466 base_q_idx: u8,
2467 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
2468 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
2469 dq_res: i32,
2470 reference: &Picture,
2471 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
2472 // built by the caller off the same grid the tile writer rebuilds its
2473 // stack from (empty unless the frame carries `reference_select` and
2474 // [`b128_compound`] is on).
2475 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
2476 fctx: &crate::decode::FrameCtx,
2477) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
2478 const SIDE: usize = SUPERBLOCK * 2;
2479 const SIDE_MI: usize = SIDE / 4;
2480 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
2481 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
2482 if root_r * 2 + 3 >= rows
2483 || root_c * 2 + 3 >= cols
2484 || (mi_row + SIDE_MI) as u32 > mi_rows
2485 || (mi_col + SIDE_MI) as u32 > mi_cols
2486 || x128 + SIDE > luma.true_width
2487 || y128 + SIDE > luma.true_height
2488 {
2489 return None;
2490 }
2491 // One lambda for the whole root, the mean of what its four superblocks
2492 // would each be searched at -- the 128-vs-four comparison weighs one cost
2493 // against four, so both sides have to be priced at the same lambda (the
2494 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
2495 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
2496 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
2497 (None, Some(f)) => {
2498 let mean = (0..16)
2499 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
2500 .sum::<f64>()
2501 / 16.0;
2502 search.lambda * mean
2503 }
2504 (None, None) => search.lambda,
2505 };
2506 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
2507 .iter()
2508 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
2509 .sum::<f64>()
2510 / 4.0;
2511 // The qindex this root is really quantized at: the delta_q unit is the
2512 // 128 superblock, so the root's own top-left cell is the one coded
2513 // (lane-b128m), and the residual arm below has to quantize at exactly it.
2514 let root_search = Search {
2515 lambda,
2516 ..match sb_q {
2517 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
2518 None => search,
2519 }
2520 };
2521 let stack = find_mv_stack(
2522 grid,
2523 mi_row,
2524 mi_col,
2525 SIDE_MI,
2526 SIDE_MI,
2527 LAST_FRAME,
2528 mi_cols as usize,
2529 mi_rows as usize,
2530 );
2531 let base = snapshot(luma, chroma, (x128, y128), SIDE);
2532 let found = search_skip_64(
2533 luma,
2534 chroma,
2535 (x128, y128),
2536 (SIDE, SIDE),
2537 &root_search,
2538 false,
2539 reference,
2540 &stack,
2541 compound,
2542 fctx,
2543 );
2544 let (mut cost, mut block) = found?;
2545 if block.inter.is_some_and(|i| i.ref1.is_some()) {
2546 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2547 }
2548 // lane-b128r: the same prediction with a REAL residual, priced against
2549 // the skip arm the search just committed to the planes (which IS the
2550 // winner's prediction, sample for sample). The block's residual is four
2551 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
2552 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
2553 // sides the forward network already reaches, never as one 128-point
2554 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
2555 //
2556 // The four `txfm_partition` symbols the writer codes for them are not
2557 // priced, exactly as the 64 root does not price its own (their contexts
2558 // are only known at write time); at four symbols a root this is under a
2559 // bit against residuals of hundreds.
2560 if b128_residual() && block.skip {
2561 // Every unit's coded level grid is 32x32 (a 64-point transform codes
2562 // only its top-left corner), packed per plane into one 64-wide grid
2563 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
2564 // `write_inter_block_128` slices back out in the same chunk order.
2565 let mut packed = [
2566 vec![0i32; 64 * 64],
2567 vec![0i32; 64 * 64],
2568 vec![0i32; 64 * 64],
2569 ];
2570 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
2571 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
2572 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
2573 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
2574 let (cx, cy) = (px / 2, py / 2);
2575 let half = SUPERBLOCK / 2;
2576 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
2577 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
2578 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
2579 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
2580 + chroma[0].block_sse(cx, cy, half, &pred_u)
2581 + chroma[1].block_sse(cx, cy, half, &pred_v);
2582 let trials = [
2583 luma.code_from_prediction(
2584 px,
2585 py,
2586 SUPERBLOCK,
2587 &pred_y,
2588 false,
2589 root_search.base_q_idx,
2590 root_search.deadzone,
2591 TxbSet::Luma64,
2592 ),
2593 chroma[0].code_from_prediction(
2594 cx,
2595 cy,
2596 half,
2597 &pred_u,
2598 false,
2599 root_search.base_q_idx,
2600 root_search.deadzone,
2601 TxbSet::Chroma32,
2602 ),
2603 chroma[1].code_from_prediction(
2604 cx,
2605 cy,
2606 half,
2607 &pred_v,
2608 false,
2609 root_search.base_q_idx,
2610 root_search.deadzone,
2611 TxbSet::Chroma32,
2612 ),
2613 ];
2614 for (plane, trial) in trials.iter().enumerate() {
2615 sse_res += trial.sse;
2616 coeff_bits += trial.bits;
2617 for row in 0..32 {
2618 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
2619 .copy_from_slice(&trial.levels[row * 32..][..32]);
2620 }
2621 }
2622 chunks.push(((cr, cc), trials));
2623 }
2624 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
2625 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
2626 // coefficients.
2627 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
2628 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
2629 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
2630 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2631 for ((cr, cc), trials) in &chunks {
2632 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
2633 let half = SUPERBLOCK / 2;
2634 luma.commit(px, py, SUPERBLOCK, &trials[0]);
2635 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
2636 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
2637 }
2638 cost = res_cost;
2639 block.skip = false;
2640 block.tx_depth = 0;
2641 block.luma_tx_types = Vec::new();
2642 block.luma = coeffs(&packed[0], 64);
2643 block.u = coeffs(&packed[1], 64);
2644 block.v = coeffs(&packed[2], 64);
2645 }
2646 }
2647 let after = snapshot(luma, chroma, (x128, y128), SIDE);
2648 restore(luma, chroma, (x128, y128), SIDE, &base);
2649 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
2650 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
2651 // residual arm above codes it like every other block does.
2652 let dq = if block.skip {
2653 0.0
2654 } else {
2655 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
2656 };
2657 Some((
2658 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
2659 lambda,
2660 block,
2661 after,
2662 ))
2663}
2664
2665/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
2666/// arm the caller's [`search_skip_64`] just committed to the planes (which
2667/// IS the winner's prediction, sample for sample -- the same rule
2668/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
2669/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
2670/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
2671/// each trial at sides the forward network already reaches, never a
2672/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
2673/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
2674///
2675/// The depth-0 `txfm_partition` symbols the writer codes for the units are
2676/// not priced, exactly as [`search_root_128`] does not price its four (their
2677/// contexts are only known at write time); at two symbols a half this is
2678/// under a bit against residuals of hundreds. On a win (or under the witness
2679/// force) the trials are committed to the planes, `block` is flipped to
2680/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
2681/// slices back out, and the new cost is returned; otherwise `cost` passes
2682/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
2683#[allow(clippy::too_many_arguments)]
2684pub(super) fn search_rect_residual(
2685 luma: &mut Plane,
2686 chroma: &mut [Plane; 2],
2687 // The piece's own top-left, in luma samples.
2688 (px, py): (usize, usize),
2689 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
2690 (w, h): (usize, usize),
2691 cost: f64,
2692 lambda: f64,
2693 search: &Search<'_>,
2694 // The piece's own mv stack, for the skip symbol's cost either way.
2695 stack: &crate::mvstack::MvStack,
2696 block: &mut BlockCoeffs,
2697) -> f64 {
2698 /// The 64x64 "mu" chunk side, luma; chroma halves it.
2699 const MU: usize = SUPERBLOCK;
2700 let chunks: [(usize, usize); 2] = match (w, h) {
2701 (128, 64) => [(0, 0), (0, 1)],
2702 (64, 128) => [(0, 0), (1, 0)],
2703 _ => [(0, 0), (0, 0)],
2704 };
2705 let n = if w.max(h) > MU { 2 } else { 1 };
2706 // Every unit's coded level grid is 32x32 (a 64-point transform codes
2707 // only its top-left corner), packed per plane into one 64-wide grid with
2708 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
2709 // back out in the same chunk order.
2710 let mut packed = [
2711 vec![0i32; 64 * 64],
2712 vec![0i32; 64 * 64],
2713 vec![0i32; 64 * 64],
2714 ];
2715 let mut sse_skip = 0.0f64;
2716 let mut sse_res = 0.0f64;
2717 let mut coeff_bits = 0.0f64;
2718 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
2719 for &(cr, cc) in &chunks[..n] {
2720 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
2721 let (cx, cy) = (cxx / 2, cyy / 2);
2722 let half = MU / 2;
2723 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
2724 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
2725 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
2726 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
2727 + chroma[0].block_sse(cx, cy, half, &pred_u)
2728 + chroma[1].block_sse(cx, cy, half, &pred_v);
2729 let trials = [
2730 luma.code_from_prediction(
2731 cxx,
2732 cyy,
2733 MU,
2734 &pred_y,
2735 false,
2736 search.base_q_idx,
2737 search.deadzone,
2738 TxbSet::Luma64,
2739 ),
2740 chroma[0].code_from_prediction(
2741 cx,
2742 cy,
2743 half,
2744 &pred_u,
2745 false,
2746 search.base_q_idx,
2747 search.deadzone,
2748 TxbSet::Chroma32,
2749 ),
2750 chroma[1].code_from_prediction(
2751 cx,
2752 cy,
2753 half,
2754 &pred_v,
2755 false,
2756 search.base_q_idx,
2757 search.deadzone,
2758 TxbSet::Chroma32,
2759 ),
2760 ];
2761 for (plane, trial) in trials.iter().enumerate() {
2762 sse_res += trial.sse;
2763 coeff_bits += trial.bits;
2764 for row in 0..32 {
2765 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
2766 .copy_from_slice(&trial.levels[row * 32..][..32]);
2767 }
2768 }
2769 trials_per_chunk.push(trials);
2770 }
2771 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
2772 // pays the same syntax with `skip` coded 0 instead of 1, plus its
2773 // coefficients.
2774 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
2775 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
2776 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
2777 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
2778 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
2779 let (cx, cy) = (cxx / 2, cyy / 2);
2780 let half = MU / 2;
2781 luma.commit(cxx, cyy, MU, &trials[0]);
2782 chroma[0].commit(cx, cy, half, &trials[1]);
2783 chroma[1].commit(cx, cy, half, &trials[2]);
2784 }
2785 block.skip = false;
2786 block.tx_depth = 0;
2787 block.luma_tx_types = Vec::new();
2788 block.luma = coeffs(&packed[0], 64);
2789 block.u = coeffs(&packed[1], 64);
2790 block.v = coeffs(&packed[2], 64);
2791 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2792 res_cost
2793 } else {
2794 cost
2795 }
2796}
2797
2798/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
2799/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
2800/// shipped NONE machinery halved. Skip-only by default, single reference or
2801/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
2802/// ([`search_rect_residual`]) -- exactly what
2803/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
2804/// reads at `sb128_rect`.
2805///
2806/// The FIRST half is published into `grid` before the second is searched --
2807/// the writer publishes it too, so a second half searched against the stale
2808/// grid would be priced (and its mv predicted) off a stack the decoder never
2809/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
2810/// both planes are put back before returning; the caller re-applies the
2811/// winner.
2812///
2813/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
2814/// carrying the root's own partition symbol so it ranks against
2815/// [`search_root_128`] and against the four superblocks below.
2816#[allow(clippy::too_many_arguments)]
2817pub(super) fn search_root_128_rect(
2818 luma: &mut Plane,
2819 chroma: &mut [Plane; 2],
2820 grid: &mut crate::mvstack::MiGrid,
2821 (root_r, root_c): (usize, usize),
2822 (rows, cols): (usize, usize),
2823 (mi_cols, mi_rows): (u32, u32),
2824 search: Search<'_>,
2825 tpl_factors: &Option<Vec<f64>>,
2826 sb_q: Option<&Vec<u8>>,
2827 sb_cols: usize,
2828 tpl_cells_x: usize,
2829 base_q_idx: u8,
2830 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
2831 dq_res: i32,
2832 reference: &Picture,
2833 // The `LAST` + extra-reference pairs offered at this root; only the
2834 // reference and its picture are read here, since each HALF derives its
2835 // own compound stack at its own rectangular window.
2836 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
2837 horz: bool,
2838 fctx: &crate::decode::FrameCtx,
2839) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
2840 const SIDE: usize = SUPERBLOCK * 2;
2841 const SIDE_MI: usize = SIDE / 4;
2842 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
2843 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
2844 if root_r * 2 + 3 >= rows
2845 || root_c * 2 + 3 >= cols
2846 || (mi_row + SIDE_MI) as u32 > mi_rows
2847 || (mi_col + SIDE_MI) as u32 > mi_cols
2848 || x128 + SIDE > luma.true_width
2849 || y128 + SIDE > luma.true_height
2850 {
2851 return None;
2852 }
2853 // The root's own lambda, the mean of its four superblocks' -- the same
2854 // one [`search_root_128`] prices with, so the three root candidates and
2855 // the four-superblock arm are all comparable.
2856 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
2857 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
2858 (None, Some(f)) => {
2859 let mean = (0..16)
2860 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
2861 .sum::<f64>()
2862 / 16.0;
2863 search.lambda * mean
2864 }
2865 (None, None) => search.lambda,
2866 };
2867 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
2868 .iter()
2869 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
2870 .sum::<f64>()
2871 / 4.0;
2872 let root_search = Search {
2873 lambda,
2874 ..match sb_q {
2875 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
2876 None => search,
2877 }
2878 };
2879 let (w, h) = if horz {
2880 (SIDE, SUPERBLOCK)
2881 } else {
2882 (SUPERBLOCK, SIDE)
2883 };
2884 let (w_mi, h_mi) = (w / 4, h / 4);
2885 let base = snapshot(luma, chroma, (x128, y128), SIDE);
2886 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
2887 let mut cost = 0.0f64;
2888 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
2889 for i in 0..2usize {
2890 let (mr, mc) = if horz {
2891 (mi_row + i * 16, mi_col)
2892 } else {
2893 (mi_row, mi_col + i * 16)
2894 };
2895 let stack = find_mv_stack(
2896 grid,
2897 mr,
2898 mc,
2899 w_mi,
2900 h_mi,
2901 LAST_FRAME,
2902 mi_cols as usize,
2903 mi_rows as usize,
2904 );
2905 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
2906 .iter()
2907 .map(|&(r, pic, _)| {
2908 (
2909 r,
2910 pic,
2911 crate::mvstack::find_mv_stack_compound(
2912 grid,
2913 mr,
2914 mc,
2915 w_mi,
2916 h_mi,
2917 (LAST_FRAME, r),
2918 mi_cols as usize,
2919 mi_rows as usize,
2920 grid.sign_bias_table(),
2921 &[(0, 0); 7],
2922 None,
2923 ),
2924 )
2925 })
2926 .collect();
2927 let found = search_skip_64(
2928 luma,
2929 chroma,
2930 (mc * 4, mr * 4),
2931 (w, h),
2932 &root_search,
2933 false,
2934 reference,
2935 &stack,
2936 &half_compound,
2937 fctx,
2938 );
2939 match found {
2940 Some((mut c, mut block)) => {
2941 // lane-rectres: the same prediction with a REAL residual,
2942 // priced against the skip arm the search just committed to
2943 // the planes -- two 64x64 mu chunks for a half.
2944 if rectres() && block.skip {
2945 c = search_rect_residual(
2946 luma,
2947 chroma,
2948 (mc * 4, mr * 4),
2949 (w, h),
2950 c,
2951 root_search.lambda,
2952 &root_search,
2953 &stack,
2954 &mut block,
2955 );
2956 }
2957 cost += c;
2958 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
2959 halves.push(block);
2960 }
2961 None => {
2962 restore(luma, chroma, (x128, y128), SIDE, &base);
2963 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
2964 return None;
2965 }
2966 }
2967 }
2968 let after = snapshot(luma, chroma, (x128, y128), SIDE);
2969 restore(luma, chroma, (x128, y128), SIDE, &base);
2970 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
2971 let symbol = if horz { 1 } else { 2 };
2972 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
2973 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
2974 // codes the delta_q group whether it is skipped or not
2975 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
2976 // half is at a non-origin mi and codes none.
2977 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
2978 Some((
2979 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
2980 lambda,
2981 [b0, b1],
2982 after,
2983 ))
2984}
2985
2986/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
2987/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
2988/// decoder's own). Each piece is priced through the same `search_skip_64`
2989/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
2990/// into `grid` before the next is searched -- the writer publishes it too, so
2991/// a later piece searched against a stale grid would be priced (and its mv
2992/// predicted) off a stack the decoder never derives (class
2993/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
2994/// are put back before returning; the caller re-applies the winner.
2995///
2996/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
2997/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
2998/// libaom's own AB shapes earn their keep.
2999///
3000/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
3001/// already carrying the root's own partition symbol so it ranks against the
3002/// other root candidates and against the four superblocks below.
3003#[allow(clippy::too_many_arguments)]
3004pub(super) fn search_root_128_ab(
3005 luma: &mut Plane,
3006 chroma: &mut [Plane; 2],
3007 grid: &mut crate::mvstack::MiGrid,
3008 (root_r, root_c): (usize, usize),
3009 (rows, cols): (usize, usize),
3010 (mi_cols, mi_rows): (u32, u32),
3011 search: Search<'_>,
3012 tpl_factors: &Option<Vec<f64>>,
3013 sb_q: Option<&Vec<u8>>,
3014 sb_cols: usize,
3015 tpl_cells_x: usize,
3016 base_q_idx: u8,
3017 reference: &Picture,
3018 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3019 // The partition symbol, 4..=7.
3020 symbol: usize,
3021 fctx: &crate::decode::FrameCtx,
3022) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
3023 const SIDE: usize = SUPERBLOCK * 2;
3024 const SIDE_MI: usize = SIDE / 4;
3025 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
3026 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
3027 if root_r * 2 + 3 >= rows
3028 || root_c * 2 + 3 >= cols
3029 || (mi_row + SIDE_MI) as u32 > mi_rows
3030 || (mi_col + SIDE_MI) as u32 > mi_cols
3031 || x128 + SIDE > luma.true_width
3032 || y128 + SIDE > luma.true_height
3033 {
3034 return None;
3035 }
3036 // The root's own lambda, the mean of its four superblocks' -- the same one
3037 // [`search_root_128`] prices with, so every root candidate and the
3038 // four-superblock arm are comparable.
3039 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
3040 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
3041 (None, Some(f)) => {
3042 let mean = (0..16)
3043 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
3044 .sum::<f64>()
3045 / 16.0;
3046 search.lambda * mean
3047 }
3048 (None, None) => search.lambda,
3049 };
3050 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
3051 .iter()
3052 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
3053 .sum::<f64>()
3054 / 4.0;
3055 let root_search = Search {
3056 lambda,
3057 ..match sb_q {
3058 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
3059 None => search,
3060 }
3061 };
3062 let base = snapshot(luma, chroma, (x128, y128), SIDE);
3063 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
3064 let mut cost = 0.0f64;
3065 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
3066 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
3067 let (w_mi, h_mi) = (w / 4, h / 4);
3068 let stack = find_mv_stack(
3069 grid,
3070 mr,
3071 mc,
3072 w_mi,
3073 h_mi,
3074 LAST_FRAME,
3075 mi_cols as usize,
3076 mi_rows as usize,
3077 );
3078 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
3079 .iter()
3080 .map(|&(r, pic, _)| {
3081 (
3082 r,
3083 pic,
3084 crate::mvstack::find_mv_stack_compound(
3085 grid,
3086 mr,
3087 mc,
3088 w_mi,
3089 h_mi,
3090 (LAST_FRAME, r),
3091 mi_cols as usize,
3092 mi_rows as usize,
3093 grid.sign_bias_table(),
3094 &[(0, 0); 7],
3095 None,
3096 ),
3097 )
3098 })
3099 .collect();
3100 let found = search_skip_64(
3101 luma,
3102 chroma,
3103 (mc * 4, mr * 4),
3104 (w, h),
3105 &root_search,
3106 false,
3107 reference,
3108 &stack,
3109 &piece_compound,
3110 fctx,
3111 );
3112 match found {
3113 Some((mut c, mut block)) => {
3114 // lane-rectres: the same prediction with a REAL residual,
3115 // priced against the skip arm the search just committed to
3116 // the planes -- one mu chunk for a 64x64 square, two for a
3117 // half. The 64x64 squares are where libaom's own AB shapes
3118 // earn their keep.
3119 if rectres() && block.skip {
3120 c = search_rect_residual(
3121 luma,
3122 chroma,
3123 (mc * 4, mr * 4),
3124 (w, h),
3125 c,
3126 root_search.lambda,
3127 &root_search,
3128 &stack,
3129 &mut block,
3130 );
3131 }
3132 cost += c;
3133 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
3134 pieces.push(block);
3135 }
3136 None => {
3137 restore(luma, chroma, (x128, y128), SIDE, &base);
3138 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
3139 return None;
3140 }
3141 }
3142 }
3143 let after = snapshot(luma, chroma, (x128, y128), SIDE);
3144 restore(luma, chroma, (x128, y128), SIDE, &base);
3145 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
3146 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
3147 Some((
3148 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
3149 lambda,
3150 [b0, b1, b2],
3151 after,
3152 ))
3153}
3154
3155/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
3156/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
3157/// SKIP, priced through the same `symbol_bits` path every other candidate
3158/// uses. The winner's prediction is committed to the planes (it IS the
3159/// reconstruction -- a skip block has no residual); the caller restores them
3160/// if the four quadrants come out cheaper.
3161///
3162/// `None` when no candidate could be coded at all (a `NEWMV` residual the
3163/// writer cannot name is simply not offered, and the other modes always are,
3164/// so this only happens if every candidate is refused).
3165// Spec-shaped signature; bundling the operands would obscure the spec mapping.
3166#[allow(clippy::too_many_arguments)]
3167pub(super) fn search_skip_64(
3168 luma: &mut Plane,
3169 chroma: &mut [Plane; 2],
3170 (x, y): (usize, usize),
3171 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
3172 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
3173 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
3174 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
3175 // side (one square when it is square, two otherwise), and the residual
3176 // arm is only ever asked for at 64 -- a 128 block's residual is four
3177 // TX_64X64 units the writer has no path for.
3178 (bw, bh): (usize, usize),
3179 search: &Search,
3180 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
3181 // screen content -- see that function's doc).
3182 residual: bool,
3183 reference: &Picture,
3184 stack: &MvStack,
3185 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
3186 // superblock's 16x16-mi window, built off the same grid the tile writer
3187 // rebuilds it from (empty unless the frame carries `reference_select`).
3188 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3189 fctx: &crate::decode::FrameCtx,
3190) -> Option<(f64, BlockCoeffs)> {
3191 debug_assert!(
3192 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
3193 "only a 64 root has a residual arm"
3194 );
3195 // The square units every trial below is taken on: the block itself when
3196 // it is square, its two halves otherwise. Luma first (in raster order),
3197 // then each chroma plane over the same tiling at half the side -- which is
3198 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
3199 let sq = bw.min(bh);
3200 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
3201 .flat_map(|plane| {
3202 let (ox, oy, s) = if plane == 0 {
3203 (x, y, sq)
3204 } else {
3205 (x / 2, y / 2, sq / 2)
3206 };
3207 (0..bh / sq).flat_map(move |j| {
3208 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
3209 })
3210 })
3211 .collect();
3212 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
3213 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
3214 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
3215 // What every candidate pays whatever its vector: `skip` coded 1, then
3216 // `is_inter` coded 1, then the LAST chain above.
3217 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
3218 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
3219 ref1: None,
3220 mv1: (0, 0),
3221 ref_frame: crate::mvstack::LAST_FRAME,
3222 mode,
3223 mv,
3224 ref_mv_idx,
3225 };
3226 let mut cands: Vec<(f64, InterInfo)> = vec![
3227 (
3228 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
3229 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
3230 ),
3231 (
3232 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
3233 info_of(InterMode::GlobalMv, (0, 0), 0),
3234 ),
3235 ];
3236 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
3237 for idx in 1..=2usize {
3238 if let Some(e) = stack.entries.get(idx) {
3239 cands.push((
3240 near_bits + drl_bits_for(stack, 1, idx),
3241 info_of(InterMode::NearMv, e.mv, idx as u8),
3242 ));
3243 }
3244 }
3245 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
3246 // candidate below to pair with the second reference's NEAREST half.
3247 let mut last_new_mv: Option<(i32, i32)> = None;
3248 if leaf_new_mv() {
3249 let source_block = luma.source_block_rect(x, y, bw, bh);
3250 let (seeds, seed_n) = mv_seeds(stack);
3251 let found = motion::search(
3252 &reference.y,
3253 reference.width,
3254 luma.true_width,
3255 luma.true_height,
3256 &source_block,
3257 x,
3258 y,
3259 bw,
3260 bh,
3261 stack.pred_mv,
3262 &seeds[..seed_n],
3263 search.lambda,
3264 fctx,
3265 1,
3266 );
3267 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
3268 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
3269 last_new_mv = Some(mv);
3270 cands.push((
3271 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
3272 info_of(InterMode::NewMv, mv, ref_mv_idx),
3273 ));
3274 }
3275 }
3276
3277 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
3278 for (bits, info) in cands {
3279 let trials: Vec<Trial> = units
3280 .iter()
3281 .map(|&(plane, px, py, s, is_luma)| {
3282 let (samples, stride, w, h) = match plane {
3283 0 => (
3284 &reference.y,
3285 reference.width,
3286 luma.true_width,
3287 luma.true_height,
3288 ),
3289 1 => (
3290 &reference.u,
3291 reference.width / 2,
3292 chroma[0].true_width,
3293 chroma[0].true_height,
3294 ),
3295 _ => (
3296 &reference.v,
3297 reference.width / 2,
3298 chroma[1].true_width,
3299 chroma[1].true_height,
3300 ),
3301 };
3302 let prediction =
3303 predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
3304 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
3305 // `skip` true: the trial is the prediction itself plus its SSE,
3306 // so no transform of any size is involved (the reason a 64x64
3307 // root can be coded at all before a forward TX_64X64 exists).
3308 target.code_from_prediction(
3309 px,
3310 py,
3311 s,
3312 &prediction,
3313 true,
3314 search.base_q_idx,
3315 search.deadzone,
3316 TxbSet::Luma32Inter,
3317 )
3318 })
3319 .collect();
3320 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
3321 if best.as_ref().is_none_or(|b| cost < b.0) {
3322 best = Some((cost, fixed + bits, info, trials));
3323 }
3324 }
3325
3326 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
3327 // superblock can form without a second motion search ([`b64_compound`]),
3328 // priced through the same `symbol_bits` path -- `fixed` minus the single
3329 // reference's tree, plus the pair tree and the compound mode.
3330 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
3331 let (ref1, g) = (*ref1, *g);
3332 // The whole `comp_mode` + reference-pair tree at the writer's own
3333 // contexts, for THIS pair (lane-ctx).
3334 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
3335 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
3336 let mode_bits_of =
3337 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
3338 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
3339 ref1: Some(ref1),
3340 mv1: mvs.1,
3341 ref_frame: crate::mvstack::LAST_FRAME,
3342 mode,
3343 mv: mvs.0,
3344 ref_mv_idx: 0,
3345 };
3346 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
3347 (
3348 cstack.nearest_mv,
3349 mode_bits_of(0),
3350 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
3351 ),
3352 (
3353 ((0, 0), (0, 0)),
3354 mode_bits_of(6),
3355 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
3356 ),
3357 ];
3358 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
3359 // above, its residual priced against compound stack entry 0 -- what
3360 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
3361 let cbase = cstack
3362 .entries
3363 .first()
3364 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
3365 if let Some(new_mv) = last_new_mv
3366 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
3367 {
3368 let mvs = (new_mv, cstack.nearest_mv.1);
3369 ccands.push((
3370 mvs,
3371 mode_bits_of(3) + b0,
3372 compound_info(InterMode::NewNearestMv, mvs),
3373 ));
3374 }
3375 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3376 ccands.dedup_by_key(|c| c.0);
3377 for (mvs, bits, info) in ccands {
3378 let trials: Vec<Trial> = units
3379 .iter()
3380 .map(|&(plane, px, py, s, is_luma)| {
3381 let (r0, r1) = match plane {
3382 0 => (
3383 (
3384 reference.y.as_slice(),
3385 reference.width,
3386 luma.true_width,
3387 luma.true_height,
3388 ),
3389 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3390 ),
3391 1 => (
3392 (
3393 reference.u.as_slice(),
3394 reference.width / 2,
3395 chroma[0].true_width,
3396 chroma[0].true_height,
3397 ),
3398 (
3399 g.u.as_slice(),
3400 g.width / 2,
3401 chroma[0].true_width,
3402 chroma[0].true_height,
3403 ),
3404 ),
3405 _ => (
3406 (
3407 reference.v.as_slice(),
3408 reference.width / 2,
3409 chroma[1].true_width,
3410 chroma[1].true_height,
3411 ),
3412 (
3413 g.v.as_slice(),
3414 g.width / 2,
3415 chroma[1].true_width,
3416 chroma[1].true_height,
3417 ),
3418 ),
3419 };
3420 let prediction = predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
3421 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
3422 target.code_from_prediction(
3423 px,
3424 py,
3425 s,
3426 &prediction,
3427 true,
3428 search.base_q_idx,
3429 search.deadzone,
3430 TxbSet::Luma32Inter,
3431 )
3432 })
3433 .collect();
3434 let syntax = fixed - ref_bits + bits;
3435 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
3436 if best.as_ref().is_none_or(|b| cost < b.0) {
3437 best = Some((cost, syntax, info, trials));
3438 }
3439 }
3440 }
3441
3442 let (skip_cost, syntax, info, skip_trials) = best?;
3443
3444 // The winner's prediction coded with a REAL residual (lane-tx64): one
3445 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
3446 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
3447 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
3448 // the skip arm already chose is re-coded: the prediction with the lowest
3449 // SSE is also the cheapest residual to code, and a second 64x64 motion
3450 // search per superblock is the wall this root was taken to SAVE.
3451 //
3452 // Priced against the skip arm through the same `symbol_bits` path, so the
3453 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
3454 // arm charges 0 instead and adds its three planes' coefficient bits.
3455 let mut chosen = (skip_cost, true, skip_trials);
3456 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
3457 // into the plane, so the tail below does not commit over its units.
3458 let mut luma_committed = false;
3459 // The residual arm's luma levels and the `txfm_split` depth the writer
3460 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
3461 // four TX_32X32 units in 64x64 ones.
3462 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
3463 if residual {
3464 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
3465 // Square by construction (the `debug_assert` above), so `units` is
3466 // one entry per plane and `chosen.2[plane]` is that plane's trial.
3467 let residual_trials = [0usize, 1, 2].map(|plane| {
3468 let (target, px, py, s) = if plane == 0 {
3469 (&*luma, x, y, bw)
3470 } else {
3471 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
3472 };
3473 target.code_from_prediction(
3474 px,
3475 py,
3476 s,
3477 &chosen.2[plane].reconstruction,
3478 false,
3479 search.base_q_idx,
3480 search.deadzone,
3481 sets[plane],
3482 )
3483 });
3484 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
3485 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
3486 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
3487 // four TX_32X32 units of `txfm_split = 1`, taken by the same
3488 // `commit_inter_luma` every other inter block's is (it commits the
3489 // winner and hands back the cost it took off the flat arm).
3490 let (levels, depth, gain, tx_types) = if b64_var_tx() {
3491 let second = info.ref1.and_then(|r1| {
3492 compound
3493 .iter()
3494 .find(|(r, _, _)| *r == r1)
3495 .map(|&(_, g, _)| {
3496 (
3497 info.mv1,
3498 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3499 )
3500 })
3501 });
3502 luma_committed = true;
3503 commit_inter_luma(
3504 luma,
3505 (x, y),
3506 bw,
3507 info.mv,
3508 (
3509 &reference.y,
3510 reference.width,
3511 luma.true_width,
3512 luma.true_height,
3513 ),
3514 search,
3515 &residual_trials[0],
3516 false,
3517 second,
3518 fctx,
3519 )
3520 } else {
3521 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
3522 };
3523 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
3524 + search.lambda * (syntax + unskip + coeff_bits)
3525 + gain;
3526 if cost < skip_cost {
3527 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3528 if depth == 1 {
3529 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3530 }
3531 luma_levels = Some((levels, depth, tx_types));
3532 chosen = (cost, false, residual_trials.to_vec());
3533 }
3534 }
3535
3536 let (cost, skip, trials) = chosen;
3537 // `commit_inter_luma` already wrote the residual arm's luma (its four
3538 // split units are not one 64-sided trial); a skip winner overwrites it.
3539 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
3540 match plane {
3541 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
3542 0 => {}
3543 _ => chroma[plane - 1].commit(px, py, s, trial),
3544 }
3545 }
3546 Some((
3547 cost,
3548 BlockCoeffs {
3549 skip,
3550 inter: Some(info),
3551 // The chroma grids are whole TX_32X32; the luma one is the
3552 // 64-point transform's coded 32x32 corner at depth 0 and the
3553 // whole 64-sided block at depth 1 (lane-b64b).
3554 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
3555 luma_tx_types: match (skip, &luma_levels) {
3556 (false, Some((_, _, types))) => types.clone(),
3557 _ => Vec::new(),
3558 },
3559 luma: match (skip, &luma_levels) {
3560 (true, _) => Vec::new(),
3561 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
3562 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
3563 (false, None) => coeffs(&trials[0].levels, BLOCK),
3564 },
3565 u: if skip {
3566 Vec::new()
3567 } else {
3568 coeffs(&trials[1].levels, bw / 2)
3569 },
3570 v: if skip {
3571 Vec::new()
3572 } else {
3573 coeffs(&trials[2].levels, bw / 2)
3574 },
3575 ..BlockCoeffs::default()
3576 },
3577 ))
3578}
3579
3580// Spec-shaped signature; bundling the operands would obscure the spec mapping.
3581#[allow(clippy::too_many_arguments)]
3582pub(super) fn search_inter_block(
3583 luma: &mut Plane,
3584 chroma: &mut [Plane; 2],
3585 (x, y): (usize, usize),
3586 search: &Search,
3587 mode_bits: &[f64; 13],
3588 reference: &Picture,
3589 stack: &MvStack,
3590 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
3591 // for the whole GOP, with the stack this block derives against it. Only
3592 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
3593 // second motion search would double the wall of the stage that already
3594 // owns most of it.
3595 extra: &[(i8, &Picture, &MvStack)],
3596 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
3597 // the caller off the same MI grid the tile writer will (empty unless the
3598 // frame carries `reference_select`).
3599 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3600 // lane-av1obmc: the mi grid this search's neighbours were published into
3601 // (`record_mi`) and this block's own place in it -- what the OBMC
3602 // candidate's eligibility walk and neighbour plan read, the same state
3603 // the tile writer will read when it codes the `motion_mode` symbol.
3604 grid: &MiGrid,
3605 (mi_row, mi_col): (usize, usize),
3606 (mi_rows, mi_cols): (usize, usize),
3607 fctx: &crate::decode::FrameCtx,
3608) -> (BlockCoeffs, f64) {
3609 // `luma_set` is the INTRA candidates' table; the two inter candidates
3610 // below price their coefficients through `TxbSet::Luma32Inter`, which is
3611 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
3612 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
3613 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
3614 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
3615
3616 // skip / intra_inter symbol costs at a fixed context -- see this
3617 // function's doc comment.
3618 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
3619 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
3620
3621 struct Candidate {
3622 cost: f64,
3623 luma: Trial,
3624 u: Trial,
3625 v: Trial,
3626 mode: u8,
3627 skip: bool,
3628 inter: Option<InterInfo>,
3629 /// The mode/mv syntax this candidate pays for, apart from its
3630 /// residual -- what the OBMC candidate below has to re-pay when it
3631 /// re-prices the winner's prediction.
3632 mode_bits: f64,
3633 }
3634 let mut best: Option<Candidate> = None;
3635 let mut consider = |candidate: Candidate| {
3636 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
3637 best = Some(candidate);
3638 }
3639 };
3640
3641 // The chroma trial an intra candidate prices does not depend on `mode`
3642 // at all -- both planes always code `DC_PRED` here (a coding choice this
3643 // search inherited, not this loop's to second-guess) at the same `reach:
3644 // Reach::none()` -- so it is the same call with the same inputs on every
3645 // one of the thirteen iterations below; run it once and reuse the result
3646 // rather than repeat an already-priced transform/quantize/entropy call
3647 // twelve times for nothing (bit-identical: the value each iteration
3648 // reads back is exactly what it used to recompute).
3649 let u_trial = chroma[0].trial(
3650 At {
3651 x: x / 2,
3652 y: y / 2,
3653 side: BLOCK / 2,
3654 reach: Reach::none(),
3655 set: chroma_set,
3656 },
3657 DC_PRED,
3658 0,
3659 search.base_q_idx,
3660 search.deadzone,
3661 fctx,
3662 );
3663 let v_trial = chroma[1].trial(
3664 At {
3665 x: x / 2,
3666 y: y / 2,
3667 side: BLOCK / 2,
3668 reach: Reach::none(),
3669 set: chroma_set,
3670 },
3671 DC_PRED,
3672 0,
3673 search.base_q_idx,
3674 search.deadzone,
3675 fctx,
3676 );
3677
3678 let intra_modes: Vec<u8> = match search.top_k {
3679 Some(k) if k < search.modes.len() => {
3680 let scored = luma.intra_scores(
3681 At {
3682 x,
3683 y,
3684 side: BLOCK,
3685 reach,
3686 set: luma_set,
3687 },
3688 search.modes,
3689 mode_bits,
3690 search.lambda,
3691 fctx,
3692 );
3693 prune_by_sad(search.modes, scored, k)
3694 }
3695 _ => search.modes.to_vec(),
3696 };
3697 census_add(5, 1);
3698 census_add(
3699 6,
3700 if search.arf_leaf_intra {
3701 intra_modes.len()
3702 } else {
3703 0
3704 },
3705 );
3706 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
3707 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
3708 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
3709 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
3710 // hatch nothing else was using. Counted once per block.
3711 if search.arf_leaf_intra {
3712 for &mode in &intra_modes {
3713 let luma_trial = luma.trial(
3714 At {
3715 x,
3716 y,
3717 side: BLOCK,
3718 reach,
3719 set: luma_set,
3720 },
3721 mode,
3722 0,
3723 search.base_q_idx,
3724 search.deadzone,
3725 fctx,
3726 );
3727 let u = u_trial.clone();
3728 let v = v_trial.clone();
3729 let cost = luma_trial.sse
3730 + u.sse
3731 + v.sse
3732 + search.lambda
3733 * (luma_trial.bits
3734 + u.bits
3735 + v.bits
3736 + mode_bits[usize::from(mode)]
3737 + skip_bits(false)
3738 + intra_inter_bits(false));
3739 consider(Candidate {
3740 cost,
3741 luma: luma_trial,
3742 u,
3743 v,
3744 mode,
3745 skip: false,
3746 inter: None,
3747 mode_bits: mode_bits[usize::from(mode)],
3748 });
3749 }
3750 } else {
3751 arfmode_hit(0);
3752 }
3753
3754 // The reference frame buffer a spec decoder holds is exactly the true
3755 // (unpadded) coded extent -- a superblock whose partition stops early at
3756 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
3757 // beyond it, so those samples are never part of the decoded picture.
3758 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
3759 // reference sample position clamp), not to this crate's own
3760 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
3761 // here would let a fractional-pel read past the true edge pick up this
3762 // encoder's own uncoded padding instead of the true edge's replicated
3763 // value a decoder computes.
3764 let ref_luma = (
3765 &reference.y,
3766 reference.width,
3767 luma.true_width,
3768 luma.true_height,
3769 );
3770 let ref_u = (
3771 &reference.u,
3772 reference.width / 2,
3773 chroma[0].true_width,
3774 chroma[0].true_height,
3775 );
3776 let ref_v = (
3777 &reference.v,
3778 reference.width / 2,
3779 chroma[1].true_width,
3780 chroma[1].true_height,
3781 );
3782 // Every single-reference mode the writer can code (spec 5.11.24's symbol
3783 // chain, mirrored by `tile::write_inter_mode`), priced with the static
3784 // CDFs at this block's own stack contexts. A candidate is a motion
3785 // vector plus the cheapest syntax that reaches it, so two modes landing
3786 // on the same vector share one set of trials: the added modes cost
3787 // mode-bit arithmetic, not another motion compensation.
3788 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
3789 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
3790 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
3791 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
3792 // the loop cannot reach is never offered below -- every candidate's
3793 // index is one this same loop walks to.
3794 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
3795 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
3796 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
3797 (
3798 stack.nearest_mv,
3799 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
3800 InterInfo {
3801 ref1: None,
3802 mv1: (0, 0),
3803 ref_frame: crate::mvstack::LAST_FRAME,
3804 mode: InterMode::NearestMv,
3805 mv: stack.nearest_mv,
3806 ref_mv_idx: 0,
3807 },
3808 ),
3809 // GLOBALMV is the identity model's zero vector -- this encoder writes
3810 // no `gm_params` -- and the cheapest syntax of the four on the static
3811 // content where that vector is also the right one.
3812 (
3813 (0, 0),
3814 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
3815 InterInfo {
3816 ref1: None,
3817 mv1: (0, 0),
3818 ref_frame: crate::mvstack::LAST_FRAME,
3819 mode: InterMode::GlobalMv,
3820 mv: (0, 0),
3821 ref_mv_idx: 0,
3822 },
3823 ),
3824 ];
3825 let near_bits =
3826 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
3827 for idx in 1..=2usize {
3828 if let Some(e) = stack.entries.get(idx) {
3829 cands.push((
3830 e.mv,
3831 near_bits + drl_bits(1, idx),
3832 InterInfo {
3833 ref1: None,
3834 mv1: (0, 0),
3835 ref_frame: crate::mvstack::LAST_FRAME,
3836 mode: InterMode::NearMv,
3837 mv: e.mv,
3838 ref_mv_idx: idx as u8,
3839 },
3840 ));
3841 }
3842 }
3843
3844 let source_block = luma.source_block(x, y, BLOCK);
3845 let (seeds, seed_n) = mv_seeds(stack);
3846 #[cfg(test)]
3847 let t = stage_start();
3848 let found = motion::search(
3849 ref_luma.0,
3850 ref_luma.1,
3851 ref_luma.2,
3852 ref_luma.3,
3853 &source_block,
3854 x,
3855 y,
3856 BLOCK,
3857 BLOCK,
3858 stack.pred_mv,
3859 &seeds[..seed_n],
3860 search.lambda,
3861 fctx,
3862 1,
3863 );
3864 #[cfg(test)]
3865 stage_since(0, t);
3866 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
3867 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
3868 // costs, for the census below (`None` when the writer cannot name it).
3869 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
3870 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
3871 // the same vector costs a different residual from each: take the index
3872 // whose residual plus DRL bits is cheapest, not entry 0 by default.
3873 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
3874 newmv_syntax = Some((mv, bits));
3875 cands.push((
3876 mv,
3877 last_ref_bits
3878 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
3879 + bits
3880 + mv_rate_surcharge(bits),
3881 InterInfo {
3882 ref1: None,
3883 mv1: (0, 0),
3884 ref_frame: crate::mvstack::LAST_FRAME,
3885 mode: InterMode::NewMv,
3886 mv,
3887 ref_mv_idx,
3888 },
3889 ));
3890 }
3891
3892 // Each extra reference's own `NEWMV` vector, for the compound
3893 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
3894 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
3895 for &(ref_frame, g, gstack) in extra {
3896 let g_ref_bits = single_ref_bits(ref_frame, gstack);
3897 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
3898 cands.push((
3899 gstack.nearest_mv,
3900 g_ref_bits
3901 + g_not_new
3902 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
3903 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
3904 InterInfo {
3905 ref1: None,
3906 mv1: (0, 0),
3907 ref_frame,
3908 mode: InterMode::NearestMv,
3909 mv: gstack.nearest_mv,
3910 ref_mv_idx: 0,
3911 },
3912 ));
3913 cands.push((
3914 (0, 0),
3915 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
3916 InterInfo {
3917 ref1: None,
3918 mv1: (0, 0),
3919 ref_frame,
3920 mode: InterMode::GlobalMv,
3921 mv: (0, 0),
3922 ref_mv_idx: 0,
3923 },
3924 ));
3925 // A motion search of this reference's own: without it, GOLDEN/ALTREF
3926 // can only be coded at a vector some neighbour already found, which
3927 // is why they carried a third of the inter blocks at their two
3928 // search-free modes alone.
3929 // The search is skipped when this reference's own NEARESTMV already
3930 // prices out `margin` times better than LAST's best vector does --
3931 // one candidate evaluation (`motion::cost_at`) standing in for a
3932 // whole search of ~50.
3933 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
3934 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
3935 // neighbour already found, which is how GOLDEN/ALTREF were offered
3936 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
3937 // own value from the second motion search's wall.
3938 let searched =
3939 extra_ref_new_mv() && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
3940 let margin = extra_new_skip_margin();
3941 if searched {
3942 newmv_census_global(0);
3943 }
3944 let skip_search = searched
3945 && margin > 0.0
3946 && motion::cost_at(
3947 &g.y,
3948 g.width,
3949 luma.true_width,
3950 luma.true_height,
3951 &source_block,
3952 x,
3953 y,
3954 BLOCK,
3955 BLOCK,
3956 gstack.nearest_mv,
3957 gstack.pred_mv,
3958 search.lambda,
3959 fctx,
3960 ) * margin
3961 <= found.cost;
3962 if skip_search {
3963 newmv_census_global(1);
3964 }
3965 if searched && !skip_search {
3966 let (gseeds, gn) = mv_seeds(gstack);
3967 #[cfg(test)]
3968 let t = stage_start();
3969 let gfound = motion::search(
3970 &g.y,
3971 g.width,
3972 luma.true_width,
3973 luma.true_height,
3974 &source_block,
3975 x,
3976 y,
3977 BLOCK,
3978 BLOCK,
3979 gstack.pred_mv,
3980 &gseeds[..gn],
3981 search.lambda,
3982 fctx,
3983 ref_distance(ref_frame),
3984 );
3985 #[cfg(test)]
3986 stage_since(0, t);
3987 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
3988 extra_new_mvs.push((ref_frame, gmv));
3989 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
3990 cands.push((
3991 gmv,
3992 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
3993 InterInfo {
3994 ref1: None,
3995 mv1: (0, 0),
3996 ref_frame,
3997 mode: InterMode::NewMv,
3998 mv: gmv,
3999 ref_mv_idx,
4000 },
4001 ));
4002 }
4003 }
4004 }
4005
4006 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
4007 // trial set each: both references predict the block and the two
4008 // predictions are averaged, which is what pays on content where neither
4009 // reference alone is right. Priced with the same static-CDF approximation
4010 // the single-reference candidates use, plus the compound-only symbols
4011 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
4012 // The two compound-mode arms, each measured alone on the BD gate before
4013 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
4014 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
4015 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
4016 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
4017 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
4018 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
4019 // the keep rule. Still behind the knob.
4020 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
4021 let half_new = true;
4022 for (ref1, g, cstack) in compound {
4023 let (ref1, g) = (*ref1, *g);
4024 // The whole `comp_mode` + reference-pair tree at the writer's own
4025 // contexts, for THIS pair (lane-ctx).
4026 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
4027 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
4028 let mode_bits_of =
4029 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
4030 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
4031 (
4032 cstack.nearest_mv,
4033 mode_bits_of(0),
4034 InterInfo {
4035 ref_frame: crate::mvstack::LAST_FRAME,
4036 mode: InterMode::NearestNearestMv,
4037 mv: cstack.nearest_mv.0,
4038 mv1: cstack.nearest_mv.1,
4039 ref1: Some(ref1),
4040 ref_mv_idx: 0,
4041 },
4042 ),
4043 (
4044 ((0, 0), (0, 0)),
4045 mode_bits_of(6),
4046 InterInfo {
4047 ref_frame: crate::mvstack::LAST_FRAME,
4048 mode: InterMode::GlobalGlobalMv,
4049 mv: (0, 0),
4050 mv1: (0, 0),
4051 ref1: Some(ref1),
4052 ref_mv_idx: 0,
4053 },
4054 ),
4055 ];
4056 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
4057 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
4058 // the stack is deep enough for that walk to read one.
4059 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
4060 let drl = if cstack.entries.len() > 2 {
4061 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
4062 } else {
4063 0.0
4064 };
4065 ccands.push((
4066 (e.mv0, e.mv1),
4067 mode_bits_of(1) + drl,
4068 InterInfo {
4069 ref_frame: crate::mvstack::LAST_FRAME,
4070 mode: InterMode::NearNearMv,
4071 mv: e.mv0,
4072 mv1: e.mv1,
4073 ref1: Some(ref1),
4074 ref_mv_idx: 0,
4075 },
4076 ));
4077 }
4078 // The half-new modes and `NEW_NEWMV`, all seeded from the two
4079 // single-reference searches this block already ran -- no joint search
4080 // of its own. Every residual is priced against stack entry 0, which
4081 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
4082 let cbase = cstack
4083 .entries
4084 .first()
4085 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
4086 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
4087 ccands.push((
4088 (mv, cstack.nearest_mv.1),
4089 mode_bits_of(3) + b0,
4090 InterInfo {
4091 ref_frame: crate::mvstack::LAST_FRAME,
4092 mode: InterMode::NewNearestMv,
4093 mv,
4094 mv1: cstack.nearest_mv.1,
4095 ref1: Some(ref1),
4096 ref_mv_idx: 0,
4097 },
4098 ));
4099 }
4100 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
4101 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
4102 ccands.push((
4103 (cstack.nearest_mv.0, mv1),
4104 mode_bits_of(2) + b1,
4105 InterInfo {
4106 ref_frame: crate::mvstack::LAST_FRAME,
4107 mode: InterMode::NearestNewMv,
4108 mv: cstack.nearest_mv.0,
4109 mv1,
4110 ref1: Some(ref1),
4111 ref_mv_idx: 0,
4112 },
4113 ));
4114 }
4115 let base = cbase;
4116 if let (Some(b0), Some(b1)) =
4117 (mv_residual_bits(mv, base.0), mv_residual_bits(mv1, base.1))
4118 {
4119 ccands.push((
4120 (mv, mv1),
4121 mode_bits_of(7) + b0 + b1,
4122 InterInfo {
4123 ref_frame: crate::mvstack::LAST_FRAME,
4124 mode: InterMode::NewNewMv,
4125 mv,
4126 mv1,
4127 ref1: Some(ref1),
4128 ref_mv_idx: 0,
4129 },
4130 ));
4131 }
4132 }
4133 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
4134 ccands.dedup_by_key(|c| c.0);
4135 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
4136 let g_u = (
4137 g.u.as_slice(),
4138 g.width / 2,
4139 chroma[0].true_width,
4140 chroma[0].true_height,
4141 );
4142 let g_v = (
4143 g.v.as_slice(),
4144 g.width / 2,
4145 chroma[1].true_width,
4146 chroma[1].true_height,
4147 );
4148 for (mvs, bits, info) in ccands {
4149 let luma_trial = mc_trial_compound(
4150 luma,
4151 x,
4152 y,
4153 BLOCK,
4154 mvs,
4155 true,
4156 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4157 g_luma,
4158 search.base_q_idx,
4159 search.deadzone,
4160 TxbSet::Luma32Inter,
4161 fctx,
4162 );
4163 let u = mc_trial_compound(
4164 &chroma[0],
4165 x / 2,
4166 y / 2,
4167 BLOCK / 2,
4168 mvs,
4169 false,
4170 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
4171 g_u,
4172 search.base_q_idx,
4173 search.deadzone,
4174 chroma_set,
4175 fctx,
4176 );
4177 let v = mc_trial_compound(
4178 &chroma[1],
4179 x / 2,
4180 y / 2,
4181 BLOCK / 2,
4182 mvs,
4183 false,
4184 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
4185 g_v,
4186 search.base_q_idx,
4187 search.deadzone,
4188 chroma_set,
4189 fctx,
4190 );
4191 let skip = luma_trial.levels.iter().all(|&l| l == 0)
4192 && u.levels.iter().all(|&l| l == 0)
4193 && v.levels.iter().all(|&l| l == 0);
4194 let cost = luma_trial.sse
4195 + u.sse
4196 + v.sse
4197 + search.lambda
4198 * (skip_bits(skip)
4199 + intra_inter_bits(true)
4200 + bits
4201 + if skip {
4202 0.0
4203 } else {
4204 luma_trial.bits + u.bits + v.bits
4205 });
4206 consider(Candidate {
4207 cost,
4208 luma: luma_trial,
4209 u,
4210 v,
4211 mode: DC_PRED,
4212 skip,
4213 mode_bits: bits,
4214 inter: Some(info),
4215 });
4216 }
4217 }
4218
4219 // One trial set per distinct (reference, vector) pair: sort, cheapest
4220 // syntax first, and drop the rest of each pair's run.
4221 cands.sort_by(|a, b| {
4222 (a.2.ref_frame, a.0)
4223 .cmp(&(b.2.ref_frame, b.0))
4224 .then(a.1.total_cmp(&b.1))
4225 });
4226 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
4227 census_add(7, cands.len());
4228 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
4229 // this block reaches WITHOUT it, taken inside the one loop that prices
4230 // them all (a second pricing pass would be a second oracle).
4231 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
4232 {
4233 for (mv, mode_bits_inter, info) in cands {
4234 let (ref_luma, ref_u, ref_v) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame)
4235 {
4236 Some(&(_, g, _)) => (
4237 (&g.y, g.width, luma.true_width, luma.true_height),
4238 (
4239 &g.u,
4240 g.width / 2,
4241 chroma[0].true_width,
4242 chroma[0].true_height,
4243 ),
4244 (
4245 &g.v,
4246 g.width / 2,
4247 chroma[1].true_width,
4248 chroma[1].true_height,
4249 ),
4250 ),
4251 None => (ref_luma, ref_u, ref_v),
4252 };
4253 let luma_trial = mc_trial(
4254 luma,
4255 x,
4256 y,
4257 BLOCK,
4258 mv,
4259 true,
4260 ref_luma.0,
4261 ref_luma.1,
4262 ref_luma.2,
4263 ref_luma.3,
4264 false,
4265 search.base_q_idx,
4266 search.deadzone,
4267 TxbSet::Luma32Inter,
4268 fctx,
4269 );
4270 let u = mc_trial(
4271 &chroma[0],
4272 x / 2,
4273 y / 2,
4274 BLOCK / 2,
4275 mv,
4276 false,
4277 ref_u.0,
4278 ref_u.1,
4279 ref_u.2,
4280 ref_u.3,
4281 false,
4282 search.base_q_idx,
4283 search.deadzone,
4284 chroma_set,
4285 fctx,
4286 );
4287 let v = mc_trial(
4288 &chroma[1],
4289 x / 2,
4290 y / 2,
4291 BLOCK / 2,
4292 mv,
4293 false,
4294 ref_v.0,
4295 ref_v.1,
4296 ref_v.2,
4297 ref_v.3,
4298 false,
4299 search.base_q_idx,
4300 search.deadzone,
4301 chroma_set,
4302 fctx,
4303 );
4304 let skip = luma_trial.levels.iter().all(|&l| l == 0)
4305 && u.levels.iter().all(|&l| l == 0)
4306 && v.levels.iter().all(|&l| l == 0);
4307 let cost = luma_trial.sse
4308 + u.sse
4309 + v.sse
4310 + search.lambda
4311 * (skip_bits(skip)
4312 + intra_inter_bits(true)
4313 + mode_bits_inter
4314 + if skip {
4315 0.0
4316 } else {
4317 luma_trial.bits + u.bits + v.bits
4318 });
4319 consider(Candidate {
4320 cost,
4321 luma: luma_trial,
4322 u,
4323 v,
4324 mode: DC_PRED,
4325 skip,
4326 mode_bits: mode_bits_inter,
4327 inter: Some(info),
4328 });
4329 if newmv_census_on() {
4330 if info.mode == InterMode::NewMv
4331 && info.ref1.is_none()
4332 && info.ref_frame == crate::mvstack::LAST_FRAME
4333 {
4334 new_cost = cost;
4335 } else {
4336 other_cost = other_cost.min(cost);
4337 }
4338 }
4339 }
4340 }
4341 if let Some((new_mv, bits)) = newmv_syntax {
4342 newmv_census_block(
4343 BLOCK,
4344 true,
4345 new_cost,
4346 other_cost,
4347 new_mv,
4348 stack.nearest_mv,
4349 bits,
4350 );
4351 } else {
4352 newmv_census_block(
4353 BLOCK,
4354 false,
4355 f64::INFINITY,
4356 other_cost,
4357 mv,
4358 stack.nearest_mv,
4359 0.0,
4360 );
4361 }
4362
4363 let best = best.expect("the search offers at least the intra modes");
4364 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
4365 // offered to the SINGLE-REFERENCE winner only -- libaom's
4366 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
4367 // compound block, so the writer codes no symbol for one. The prediction
4368 // is built by the DECODER's own plan and blend
4369 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
4370 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
4371 // this search's `grid` already carries, so what is priced here is what a
4372 // decoder reconstructs -- never a second implementation of the blend.
4373 //
4374 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
4375 // on). Native crop BD, the standing recipe, with it on against the same
4376 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
4377 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
4378 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
4379 // one UP -- the keep rule wants two down and one flat, so it stays off.
4380 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
4381 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
4382 // things bound it and are the upgrade path: only the 32x32 winner is
4383 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
4384 // that is where libaom cashes most of its OBMC gain), and the symbol/
4385 // residual price here is the static-CDF estimate.
4386 let mut best = best;
4387 let mut motion_won = 0u8;
4388 if let Some(info) = best
4389 .inter
4390 .filter(|i| i.ref1.is_none() && (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()))
4391 {
4392 let mut refs: [Option<&Picture>; 8] = [None; 8];
4393 refs[LAST_FRAME as usize] = Some(reference);
4394 for &(r, p, _) in extra {
4395 refs[r as usize] = Some(p);
4396 }
4397 // This block's OWN reference planes: the single-reference winner may
4398 // be one of the extra references, not LAST.
4399 let planes: [(&[u16], usize, usize, usize); 3] =
4400 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
4401 Some(&(_, g, _)) => [
4402 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
4403 (
4404 g.u.as_slice(),
4405 g.width / 2,
4406 chroma[0].true_width,
4407 chroma[0].true_height,
4408 ),
4409 (
4410 g.v.as_slice(),
4411 g.width / 2,
4412 chroma[1].true_width,
4413 chroma[1].true_height,
4414 ),
4415 ],
4416 None => [
4417 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4418 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
4419 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
4420 ],
4421 };
4422 // The alphabet `tile::write_motion_mode` will code this block's
4423 // symbol against, mirrored term for term (libaom
4424 // `motion_mode_allowed`).
4425 let warp_alphabet = warp_on()
4426 && crate::decode::num_proj_ref(
4427 grid,
4428 mi_row,
4429 mi_col,
4430 8,
4431 8,
4432 mi_cols,
4433 mi_rows,
4434 info.ref_frame,
4435 fctx,
4436 ) >= 1;
4437 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
4438 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
4439 if crate::envflags::env_flag!("EC_AV1_OBMC")
4440 && let Some(pred) = obmc_prediction(
4441 grid,
4442 (mi_row, mi_col),
4443 (mi_rows, mi_cols),
4444 (x, y),
4445 BLOCK,
4446 info.mv,
4447 &refs,
4448 planes,
4449 (reference.width, reference.height),
4450 fctx,
4451 ) {
4452 candidates.push((1, pred));
4453 }
4454 if warp_alphabet
4455 && let Some(pred) = warp_prediction(
4456 grid,
4457 (mi_row, mi_col),
4458 (mi_rows, mi_cols),
4459 (x, y),
4460 BLOCK,
4461 info.mv,
4462 info.ref_frame,
4463 planes,
4464 fctx,
4465 ) {
4466 candidates.push((2, pred));
4467 }
4468 for (motion, pred) in candidates {
4469 let luma_trial = luma.code_from_prediction(
4470 x,
4471 y,
4472 BLOCK,
4473 &pred[0],
4474 false,
4475 search.base_q_idx,
4476 search.deadzone,
4477 TxbSet::Luma32Inter,
4478 );
4479 let u = chroma[0].code_from_prediction(
4480 x / 2,
4481 y / 2,
4482 BLOCK / 2,
4483 &pred[1],
4484 false,
4485 search.base_q_idx,
4486 search.deadzone,
4487 chroma_set,
4488 );
4489 let v = chroma[1].code_from_prediction(
4490 x / 2,
4491 y / 2,
4492 BLOCK / 2,
4493 &pred[2],
4494 false,
4495 search.base_q_idx,
4496 search.deadzone,
4497 chroma_set,
4498 );
4499 let skip = luma_trial.levels.iter().all(|&l| l == 0)
4500 && u.levels.iter().all(|&l| l == 0)
4501 && v.levels.iter().all(|&l| l == 0);
4502 let cost = luma_trial.sse
4503 + u.sse
4504 + v.sse
4505 + search.lambda
4506 * (skip_bits(skip)
4507 + intra_inter_bits(true)
4508 + best.mode_bits
4509 + mm(motion)
4510 + if skip {
4511 0.0
4512 } else {
4513 luma_trial.bits + u.bits + v.bits
4514 });
4515 if cost < best.cost + search.lambda * mm(motion_won) {
4516 motion_won = motion;
4517 best = Candidate {
4518 cost,
4519 luma: luma_trial,
4520 u,
4521 v,
4522 mode: DC_PRED,
4523 skip,
4524 mode_bits: best.mode_bits,
4525 inter: best.inter,
4526 };
4527 }
4528 }
4529 }
4530 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
4531 // default OFF): the four 16x16 units of `commit_inter_luma` against the
4532 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
4533 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
4534 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
4535 // it, and it is worse again on the deciding native table: film 1080p
4536 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
4537 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
4538 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
4539 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
4540 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
4541 // +28.4/+47.4/-4.0 -- the native table decides.)
4542 //
4543 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
4544 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
4545 // either, and the census names the row: the split units' own set
4546 // `Luma16Inter` is priced within 1.4% of what it is written at in every
4547 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
4548 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
4549 // so a perfect pricer would split even more, and more splitting is what
4550 // measured worse. The four extra txb_skip/eob symbols simply cost more
4551 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
4552 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
4553 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
4554 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
4555 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
4556 // plain translation, which is not the prediction it was priced from.
4557 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
4558 Some(info) => {
4559 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
4560 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
4561 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4562 };
4563 let second = info.ref1.and_then(|r| {
4564 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
4565 (
4566 info.mv1,
4567 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
4568 )
4569 })
4570 });
4571 match info.ref1.is_some() && second.is_none() {
4572 true => {
4573 luma.commit(x, y, BLOCK, &best.luma);
4574 (best.luma.levels.clone(), 0, 0.0, Vec::new())
4575 }
4576 false => commit_inter_luma(
4577 luma,
4578 (x, y),
4579 BLOCK,
4580 info.mv,
4581 own,
4582 search,
4583 &best.luma,
4584 best.skip,
4585 second,
4586 fctx,
4587 ),
4588 }
4589 }
4590 None => {
4591 luma.commit(x, y, BLOCK, &best.luma);
4592 (best.luma.levels.clone(), 0, 0.0, Vec::new())
4593 }
4594 };
4595 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
4596 let [bu, bv] = match (
4597 best.inter.filter(|_| motion_won == 0),
4598 luma_tx_types.first().copied(),
4599 ) {
4600 (Some(info), Some(t)) => {
4601 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
4602 Some(&(_, g, _)) => (
4603 (
4604 g.u.as_slice(),
4605 g.width / 2,
4606 chroma[0].true_width,
4607 chroma[0].true_height,
4608 ),
4609 (
4610 g.v.as_slice(),
4611 g.width / 2,
4612 chroma[1].true_width,
4613 chroma[1].true_height,
4614 ),
4615 ),
4616 None => (
4617 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
4618 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
4619 ),
4620 };
4621 let sec = info.ref1.and_then(|r| {
4622 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
4623 (
4624 info.mv1,
4625 [
4626 (
4627 g.u.as_slice(),
4628 g.width / 2,
4629 chroma[0].true_width,
4630 chroma[0].true_height,
4631 ),
4632 (
4633 g.v.as_slice(),
4634 g.width / 2,
4635 chroma[1].true_width,
4636 chroma[1].true_height,
4637 ),
4638 ],
4639 )
4640 })
4641 });
4642 recode_inter_chroma(
4643 chroma,
4644 (x, y),
4645 BLOCK,
4646 info.mv,
4647 [ou, ov],
4648 sec,
4649 search,
4650 chroma_set,
4651 t,
4652 fctx,
4653 )
4654 .unwrap_or([best.u, best.v])
4655 }
4656 _ => [best.u, best.v],
4657 };
4658 let best = Candidate {
4659 u: bu,
4660 v: bv,
4661 ..best
4662 };
4663 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
4664 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
4665 (
4666 BlockCoeffs {
4667 luma_tx_types,
4668 angle_delta_y: 0,
4669 cfl_alphas: None,
4670 filter_intra: None,
4671 luma: coeffs(&levels, BLOCK),
4672 u: coeffs(&best.u.levels, BLOCK / 2),
4673 v: coeffs(&best.v.levels, BLOCK / 2),
4674 mode: best.mode,
4675 uv_mode: DC_PRED,
4676 skip: best.skip,
4677 inter: best.inter,
4678 motion_mode: motion_won,
4679 eight: None,
4680 dv: None,
4681 palette: None,
4682 palette_uv: None,
4683 tx_depth,
4684 },
4685 best.cost + dcost,
4686 )
4687}