forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb7434a2Tahinli1 month ago3896 commits

split.rs3334 lines, 132.1 KiBHistoryRawDownload
1use super::*;
2
3/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
5/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
6/// trials offered, trials the split won, then the (rate, distortion) of the
7/// split and flat arms summed apart for the split-won and flat-won trials --
8/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
9pub(super) static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
10 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
11
12/// Whether [`SPLIT_CENSUS`] is armed, read once.
13pub(crate) fn split_census_on() -> bool {
14 static ON: std::sync::LazyLock<bool> =
15 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
16 *ON
17}
18
19/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
20/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
21pub(super) fn split_census_base(site: usize, key: bool, side: usize) -> usize {
22 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
23 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
24}
25
26/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
27/// `(rate in bits, distortion as squared error)`.
28pub(super) fn split_census(
29 site: usize,
30 key: bool,
31 side: usize,
32 split_won: bool,
33 split: (f64, f64),
34 flat: (f64, f64),
35) {
36 use std::sync::atomic::Ordering::Relaxed;
37 let base = split_census_base(site, key, side);
38 let add = |i: usize, v: u64| {
39 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
40 };
41 add(0, 1);
42 let off = if split_won {
43 add(1, 1);
44 2
45 } else {
46 6
47 };
48 let (win, lose) = if split_won {
49 (split, flat)
50 } else {
51 (flat, split)
52 };
53 add(off, (win.0 * 64.0).max(0.0) as u64);
54 add(off + 1, win.1.max(0.0) as u64);
55 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
56 add(off + 3, lose.1.max(0.0) as u64);
57}
58
59/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
60/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
61/// last table a run prints is the whole encode's total (there is no flush
62/// hook the encoder API guarantees to reach).
63pub(crate) fn dump_split_census() {
64 use std::sync::atomic::Ordering::Relaxed;
65 eprintln!(
66 "SPLITCENSUS site frame side offered split share% \
67 win_rate win_dist lose_rate lose_dist"
68 );
69 for site in 0..2 {
70 for key in [true, false] {
71 for side_idx in 0..4 {
72 let base = split_census_base(site, key, 8 << side_idx);
73 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
74 if v[0] == 0 {
75 continue;
76 }
77 let (n, s) = (v[0] as f64, v[1] as f64);
78 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
79 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
80 // all `n` trials, not a mean of two means.
81 eprintln!(
82 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
83 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
84 if site == 0 { "intra" } else { "inter" },
85 if key { "key " } else { "inter" },
86 8 << side_idx,
87 v[0],
88 v[1],
89 100.0 * s / n,
90 (v[2] + v[6]) as f64 / n / 64.0,
91 (v[3] + v[7]) as f64 / n,
92 (v[4] + v[8]) as f64 / n / 64.0,
93 (v[5] + v[9]) as f64 / n,
94 );
95 }
96 }
97 }
98}
99
100/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
101/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
102/// its mode/reference syntax and not the search's own cost function
103/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
104/// control; below 1 a coded vector is charged less and `NEWMV` wins more
105/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
106pub(crate) fn mv_lambda_mult() -> f64 {
107 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
108 crate::envflags::var("EC_AV1_MV_LAMBDA")
109 .ok()
110 .and_then(|v| v.parse().ok())
111 .unwrap_or(MV_LAMBDA)
112 });
113 *M
114}
115
116/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
117pub(super) const MV_LAMBDA: f64 = 1.0;
118
119/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
120/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
121/// which the RD cost multiplies by lambda). Zero at the default weight.
122pub(super) fn mv_rate_surcharge(mv_bits: f64) -> f64 {
123 (mv_lambda_mult() - 1.0) * mv_bits
124}
125
126/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
127/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
128/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
129/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
130/// cost it won by, 4 the summed cost it lost by, 5 the summed
131/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
132/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
133/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
134/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
135/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
136pub(super) static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
137 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
138
139/// Whether [`NEWMV_CENSUS`] is armed, read once.
140pub(crate) fn newmv_census_on() -> bool {
141 static ON: std::sync::LazyLock<bool> =
142 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
143 *ON
144}
145
146/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
147pub(super) fn newmv_census_global(i: usize) {
148 if newmv_census_on() {
149 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
150 }
151}
152
153/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
154/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
155/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
156/// candidate's own; both `f64::INFINITY` is a block that offered neither.
157pub(super) fn newmv_census_block(
158 side: usize,
159 offered: bool,
160 new_cost: f64,
161 other_cost: f64,
162 mv: (i32, i32),
163 nearest: (i32, i32),
164 mv_bits: f64,
165) {
166 if !newmv_census_on() {
167 return;
168 }
169 use std::sync::atomic::Ordering::Relaxed;
170 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
171 let add = |i: usize, v: u64| {
172 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
173 };
174 add(0, 1);
175 if !offered {
176 return;
177 }
178 add(1, 1);
179 if new_cost < other_cost {
180 add(2, 1);
181 add(3, (other_cost - new_cost).max(0.0) as u64);
182 } else {
183 add(4, (new_cost - other_cost).max(0.0) as u64);
184 }
185 add(
186 5,
187 ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64,
188 );
189 if mv == nearest {
190 add(6, 1);
191 }
192 add(7, (mv_bits * 64.0).max(0.0) as u64);
193}
194
195/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
196/// same guard [`dump_split_census`] rides (cumulative, so the last table a
197/// run prints is the whole encode's).
198pub(crate) fn dump_newmv_census() {
199 use std::sync::atomic::Ordering::Relaxed;
200 eprintln!(
201 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
202 mv_dist_q3 mv==nearest% mv_bits"
203 );
204 for side_idx in 0..4 {
205 let base = side_idx * 8;
206 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
207 if v[0] == 0 {
208 continue;
209 }
210 let off = v[1].max(1) as f64;
211 eprintln!(
212 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
213 8 << side_idx,
214 v[0],
215 v[1],
216 v[2],
217 100.0 * v[2] as f64 / off,
218 v[3] as f64 / v[2].max(1) as f64,
219 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
220 v[5] as f64 / off,
221 100.0 * v[6] as f64 / off,
222 v[7] as f64 / off / 64.0,
223 );
224 }
225 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
226 // for, and how many of those named a vector no non-hp frame can code.
227 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
228 eprintln!(
229 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
230 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
231 );
232 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
233 eprintln!(
234 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
235 leaf second reference {}/{} ({:.1}%)",
236 g[1],
237 g[0],
238 100.0 * g[1] as f64 / g[0].max(1) as f64,
239 g[3],
240 g[2],
241 100.0 * g[3] as f64 / g[2].max(1) as f64,
242 );
243 let [
244 calls,
245 evals,
246 _subpel,
247 rounds,
248 near_pred,
249 unmoved,
250 widest,
251 widest_moves,
252 ] = crate::motion::take_census();
253 let per = |n: u64| n as f64 / calls.max(1) as f64;
254 eprintln!(
255 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
256 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
257 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
258 per(evals),
259 per(rounds),
260 100.0 * near_pred as f64 / calls.max(1) as f64,
261 100.0 * unmoved as f64 / calls.max(1) as f64,
262 100.0 * widest as f64 / calls.max(1) as f64,
263 per(widest_moves),
264 );
265}
266
267/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
268/// the intra witness's fire count stays its own.
269pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
270 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
271
272/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
273/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
274/// `0` compares types on reconstruction error alone, which is what separates
275/// a rate-term calibration (class `rd-rate-term-calibration`) from a
276/// distortion the trial mis-measures.
277pub(crate) fn tx_type_lambda_mult() -> f64 {
278 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
279 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
280 .ok()
281 .and_then(|v| v.parse().ok())
282 .unwrap_or(1.0)
283 });
284 *M
285}
286
287/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
288/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
289/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
290/// question needs: at weight 1 the five-type intra search spends 1.2% more
291/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
292/// of the type it picks.
293pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
294 if tx_type == TxType::DctDct {
295 0.0
296 } else {
297 lambda * (tx_type_lambda_mult() - 1.0) * bits
298 }
299}
300
301/// lane-txrd instrument: over the FLAT inter luma decision, the summed
302/// reconstruction error and priced bits of the type the search chose against
303/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
304/// integer counter. `EC_AV1_TXRD_CENSUS`.
305pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
306 std::sync::atomic::AtomicU64::new(0),
307 std::sync::atomic::AtomicU64::new(0),
308 std::sync::atomic::AtomicU64::new(0),
309 std::sync::atomic::AtomicU64::new(0),
310 std::sync::atomic::AtomicU64::new(0),
311 std::sync::atomic::AtomicU64::new(0),
312 std::sync::atomic::AtomicU64::new(0),
313];
314
315/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
316/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
317#[cfg(test)]
318pub(crate) fn take_txrd_stats() -> [u64; 7] {
319 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
320}
321
322/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
323#[cfg(test)]
324pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
325 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
326}
327
328/// How many luma transform units resolved to each [`TxType`], indexed by the
329/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
330/// and the instrument that says which types the search actually reaches.
331pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
332 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
333
334/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
335/// counts to its own encode.
336#[cfg(test)]
337pub(crate) fn take_tx_type_hits() -> [usize; 16] {
338 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
339}
340
341/// How many blocks resolved to each `tx_depth`, the fire count that says
342/// whether the depth search below reaches its candidates at all.
343pub(super) static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
344 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
345
346/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
347/// to its own encode.
348#[cfg(test)]
349pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
350 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
351}
352
353/// How many inter blocks resolved to each var-tx depth (0 = one transform
354/// over the whole block, 1 = its four halves), the fire count a gate prints
355/// to see the split search reach its candidates at all. Indexed
356/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
357/// says which of the four block classes the split reaches -- the 32x32 root
358/// and the compound blocks are this lane's two new ones.
359pub(super) static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
360 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
361
362/// Whether a 32x32 inter winner searches its own var-tx depth (the four
363/// 16x16 units against the flat transform) instead of coding depth 0 blind.
364/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
365///
366/// Rejected three times on the bars rows of the native gate (flat to +0.3).
367/// lane-av1resweep re-judged it on the two REAL film crops at
368/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
369/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
370///
371/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
372/// |---|---|---|---|
373/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
374/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
375/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
376/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
377/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
378///
379/// The bars rows are ~90% zero-intra-cost cells, so the split never had
380/// residual to reach there -- the tool was being judged on content that
381/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
382pub(super) fn tx32_depth_search() -> bool {
383 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
384 crate::envflags::var("EC_AV1_TX32_DEPTH")
385 .ok()
386 .map(|v| !matches!(v.as_str(), "0" | "off"))
387 });
388 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
389}
390
391/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
392/// trial units have to be predicted from BOTH references
393/// ([`mc_trial_compound`]) or the split would re-predict them by single-
394/// reference translation, which is not what the decoder reconstructs.
395/// ON by default (the table on [`tx32_depth_search`]: on real film it is
396/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
397/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
398/// `EC_AV1_COMP_VARTX`.
399pub(super) fn compound_var_tx() -> bool {
400 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
401 crate::envflags::var("EC_AV1_COMP_VARTX")
402 .ok()
403 .map(|v| !matches!(v.as_str(), "0" | "off"))
404 });
405 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
406}
407
408/// How many 32x32-and-below inter blocks each reference frame won, indexed by
409/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
410/// fire count a gate prints to see an extra reference reach a block at all
411/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
412/// chosen is a pyramid that costs bytes and buys nothing).
413pub(super) static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
414 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
415
416/// Reads [`REF_FRAME_HITS`] and zeroes it.
417#[cfg(test)]
418pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
419 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
420}
421
422/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
423#[cfg(test)]
424pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
425 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
426}
427
428/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
429/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
430/// is one flag, depth 1 is a split root plus one unsplit flag per child
431/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
432/// or a 4x4 sub-size).
433pub(super) fn txfm_split_bits(side: usize, depth: usize) -> f64 {
434 let max_tx = side.min(64);
435 let ctx = |tx: usize| {
436 crate::decode::txfm_partition_ctx_rect(
437 crate::decode::TXFM_CTX_INIT,
438 crate::decode::TXFM_CTX_INIT,
439 side,
440 tx,
441 tx,
442 )
443 };
444 if depth == 0 {
445 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
446 }
447 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
448 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
449}
450
451/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
452/// type is never coded -- the decoder takes the LUMA type of the block's
453/// chroma-reference position and reduces it to the set the chroma size allows
454/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
455/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
456/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
457/// basis they were never produced for: on the bars gate row the luma of the
458/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
459/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
460/// collapse two lanes attributed to the type PRICE (class
461/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
462/// field the encoder never mirrored).
463///
464/// Re-codes the two chroma planes of a committed inter block at the type the
465/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
466/// the trials the caller already holds are right.
467#[allow(clippy::too_many_arguments)]
468pub(super) fn recode_inter_chroma(
469 chroma: &[Plane; 2],
470 (x, y): (usize, usize),
471 side: usize,
472 mv: (i32, i32),
473 refs: [(&[u16], usize, usize, usize); 2],
474 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
475 search: &Search,
476 set: TxbSet,
477 luma_tx_type: TxType,
478 fctx: &crate::decode::FrameCtx,
479) -> Option<[Trial; 2]> {
480 let c = side / 2;
481 let tx =
482 crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
483 if tx == TxType::DctDct {
484 return None;
485 }
486 Some([0usize, 1].map(|p| match second {
487 Some((mv1, r1)) => mc_trial_compound_typed(
488 &chroma[p],
489 x / 2,
490 y / 2,
491 c,
492 (mv, mv1),
493 false,
494 refs[p],
495 r1[p],
496 search.base_q_idx,
497 search.deadzone,
498 set,
499 tx,
500 fctx,
501 ),
502 None => mc_trial_typed(
503 &chroma[p],
504 x / 2,
505 y / 2,
506 c,
507 mv,
508 false,
509 refs[p].0,
510 refs[p].1,
511 refs[p].2,
512 refs[p].3,
513 false,
514 search.base_q_idx,
515 search.deadzone,
516 set,
517 tx,
518 fctx,
519 ),
520 }))
521}
522
523/// The inter block's own var-tx decision, once its motion vector is settled:
524/// its residual as ONE transform over the whole block, or as the four
525/// transforms of half the side the tree's first halving names. The prediction
526/// is the same motion compensation either way, so the split trial
527/// re-transforms the identical residual in four pieces -- it wins where four
528/// small transforms carry a locally varying residual cheaper than one big
529/// one. Commits the winner into `luma` and hands back its block-coordinate
530/// levels, the depth the writer codes and the cost the winner adds to (or
531/// takes off) the caller's already-computed flat cost.
532///
533/// Only for a block wholly inside the frame: past the true edge the reader's
534/// var-tx recursion skips the units that fall outside
535/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
536/// leave the residual units this writes unpaired.
537#[allow(clippy::too_many_arguments)]
538pub(super) fn commit_inter_luma(
539 luma: &mut Plane,
540 (x, y): (usize, usize),
541 side: usize,
542 mv: (i32, i32),
543 reference: (&[u16], usize, usize, usize),
544 search: &Search,
545 flat: &Trial,
546 skip: bool,
547 // A COMPOUND winner's second half: the vector and reference planes the
548 // trial units are blended from ([`mc_trial_compound`], the decoder's own
549 // `comp_group_idx == 0` average). `None` is the single-reference block.
550 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
551 fctx: &crate::decode::FrameCtx,
552) -> (Vec<i32>, u8, f64, Vec<TxType>) {
553 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
554 // type out of the two-type inter set the writer already codes a symbol
555 // for, priced the same way the intra search is (sse + lambda * bits, the
556 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
557 // block codes no residual and the 64-point transform names no type.
558 let mut flat_typed: Option<Trial> = None;
559 let mut flat_type = TxType::DctDct;
560 if !skip {
561 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
562 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
563 // the intra search already takes), which is what makes the wider
564 // seven-type candidate list below reachable -- and prices every
565 // candidate, `IDTX` included, in the alphabet its symbol is really
566 // coded into.
567 if let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) {
568 let lambda = search.lambda * tx_type_lambda_mult();
569 let cost = |t: &Trial| t.sse + lambda * t.bits;
570 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
571 if tx_type == TxType::DctDct {
572 continue;
573 }
574 let candidate = match second {
575 Some((mv1, ref1)) => mc_trial_compound_typed(
576 luma,
577 x,
578 y,
579 side,
580 (mv, mv1),
581 true,
582 reference,
583 ref1,
584 search.base_q_idx,
585 search.deadzone,
586 fset,
587 tx_type,
588 fctx,
589 ),
590 None => mc_trial_typed(
591 luma,
592 x,
593 y,
594 side,
595 mv,
596 true,
597 reference.0,
598 reference.1,
599 reference.2,
600 reference.3,
601 false,
602 search.base_q_idx,
603 search.deadzone,
604 fset,
605 tx_type,
606 fctx,
607 ),
608 };
609 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
610 flat_type = tx_type;
611 flat_typed = Some(candidate);
612 }
613 }
614 }
615 }
616 // Counted at the return points, so the census names the types the block
617 // really CODES -- a split unit's winner that the flat cost then beats was
618 // never written (class `counter from refused stream`).
619 let count = |types: &[TxType]| {
620 for &t in types {
621 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
622 }
623 };
624 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
625 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
626 use std::sync::atomic::Ordering::Relaxed;
627 TXRD_STATS[0].fetch_add(1, Relaxed);
628 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
629 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
630 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
631 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
632 // Is the `DCT_DCT` baseline the search compares against the trial
633 // THIS function would build for the same block? A stale or
634 // differently-predicted baseline is what would let a candidate win on
635 // both terms at once (class `local-rd-on-references` vs a real
636 // pricing defect); re-predicting it here is the only way to tell.
637 if let Some(fset) = inter_luma_set(side) {
638 let here = match second {
639 Some((mv1, ref1)) => mc_trial_compound_typed(
640 luma,
641 x,
642 y,
643 side,
644 (mv, mv1),
645 true,
646 reference,
647 ref1,
648 search.base_q_idx,
649 search.deadzone,
650 fset,
651 TxType::DctDct,
652 fctx,
653 ),
654 None => mc_trial_typed(
655 luma,
656 x,
657 y,
658 side,
659 mv,
660 true,
661 reference.0,
662 reference.1,
663 reference.2,
664 reference.3,
665 false,
666 search.base_q_idx,
667 search.deadzone,
668 fset,
669 TxType::DctDct,
670 fctx,
671 ),
672 };
673 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
674 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
675 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
676 let n = TXRD_STATS[0].load(Relaxed);
677 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
678 eprintln!(
679 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
680 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
681 sse={:.0} bits={:.1}",
682 second.is_some(),
683 flat.sse,
684 flat.bits,
685 here.sse,
686 here.bits,
687 flat_ref.sse,
688 flat_ref.bits,
689 );
690 }
691 }
692 }
693 // What the caller's already-counted `flat` cost has to be corrected by
694 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
695 let flat_gain =
696 (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits);
697 let eligible = tx_select()
698 && tx_select_inter()
699 && !skip
700 && side >= 16
701 && (second.is_none() || compound_var_tx())
702 && (side != BLOCK || tx32_depth_search())
703 && x + side <= luma.true_width
704 && y + side <= luma.true_height;
705 if !eligible {
706 luma.commit(x, y, side, flat_ref);
707 count(&[flat_type]);
708 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
709 }
710 let tx = side / 2;
711 let set = luma_set_for(
712 if tx >= 32 {
713 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
714 TxbSet::Luma32Inter
715 } else if tx >= 16 {
716 TxbSet::Luma16Inter
717 } else {
718 TxbSet::Luma8Inter
719 },
720 search.screen,
721 );
722 let mut levels = vec![0i32; side * side];
723 let (mut sse, mut bits) = (0.0, 0.0);
724 let mut units = Vec::with_capacity(4);
725 // The split units are smaller than their block, so their `txb_skip`
726 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
727 // each unit's own commit publishes what the next one reads, coding order.
728 luma.ctx.tu_split = true;
729 // One type per unit in the writer's own raster order (tile.rs
730 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
731 let mut split_types = vec![TxType::DctDct; 4];
732 for tu_row in 0..2 {
733 for tu_col in 0..2 {
734 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
735 let unit = |tx_type: TxType| match second {
736 Some((mv1, ref1)) => mc_trial_compound_typed(
737 luma,
738 tu_x,
739 tu_y,
740 tx,
741 (mv, mv1),
742 true,
743 reference,
744 ref1,
745 search.base_q_idx,
746 search.deadzone,
747 set,
748 tx_type,
749 fctx,
750 ),
751 None => mc_trial_typed(
752 luma,
753 tu_x,
754 tu_y,
755 tx,
756 mv,
757 true,
758 reference.0,
759 reference.1,
760 reference.2,
761 reference.3,
762 false,
763 search.base_q_idx,
764 search.deadzone,
765 set,
766 tx_type,
767 fctx,
768 ),
769 };
770 let mut best: Option<(f64, TxType, Trial)> = None;
771 for &tx_type in inter_tx_type_candidates(set, search.screen) {
772 let candidate = unit(tx_type);
773 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
774 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
775 best = Some((cost, tx_type, candidate));
776 }
777 }
778 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
779 split_types[tu_row * 2 + tu_col] = tx_type;
780 sse += trial.sse;
781 bits += trial.bits;
782 for row in 0..tx {
783 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
784 .copy_from_slice(&trial.levels[row * tx..][..tx]);
785 }
786 units.push((tu_x, tu_y, trial));
787 }
788 }
789 luma.ctx.tu_split = false;
790 let split_rate = bits + txfm_split_bits(side, 1);
791 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
792 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
793 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
794 if split_census_on() {
795 split_census(
796 1,
797 false,
798 side,
799 split_cost < flat_cost,
800 (split_rate, sse),
801 (flat_rate, flat_ref.sse),
802 );
803 }
804 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
805 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
806 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
807 // in the leaf row (class `gate-blind-to-feature`).
808 let counted = side <= BLOCK;
809 if split_cost < flat_cost {
810 for (tu_x, tu_y, trial) in &units {
811 luma.commit(*tu_x, *tu_y, tx, trial);
812 }
813 if counted {
814 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
815 }
816 count(&split_types);
817 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
818 }
819 if counted {
820 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
821 }
822 luma.commit(x, y, side, flat_ref);
823 count(&[flat_type]);
824 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
825}
826
827/// The largest distinct-colour count a block may hold and still be offered a
828/// palette candidate at all: past it the k-means quantisation costs more
829/// error than the map saves rate, and every trial is wasted wall.
830///
831/// Swept on the gate's own screen capture (lane-av1pal2, the
832/// `unswept-decision-constants` class): 32 (the value this lane inherited)
833/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
834/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
835/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
836/// binds on nothing this content holds. 128 ships: best BD against both
837/// references and no wall cost at all (6.1s, the same as at 32, because the
838/// blocks it newly admits are ones the RD then keeps).
839/// `EC_AV1_PAL_MAXCOLORS`.
840pub(super) fn palette_max_colors() -> usize {
841 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
842 *N.get_or_init(|| {
843 std::env::var("EC_AV1_PAL_MAXCOLORS")
844 .ok()
845 .and_then(|v| v.parse().ok())
846 .unwrap_or(128)
847 })
848}
849
850/// The palettes worth trying for one block's luma, in the shape libaom's
851/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
852/// distinct colours takes them ALL (the prediction is then exact and the
853/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
854/// one-dimensional Lloyd iteration seeded evenly across its range -- both
855/// offered, because which wins is an RD question the caller answers.
856/// `block` is `side*side` source samples, row-major.
857pub(super) fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
858 let mut histogram = [0u32; 256];
859 for &v in block {
860 histogram[usize::from(v)] += 1;
861 }
862 let present: Vec<u16> = (0..256u16)
863 .filter(|&v| histogram[usize::from(v)] > 0)
864 .collect();
865 if present.len() < 2 {
866 return Vec::new();
867 }
868 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
869 let mut base = [0u16; 8];
870 base[..colors.len()].copy_from_slice(colors);
871 let map = block
872 .iter()
873 .map(|&v| {
874 colors
875 .iter()
876 .enumerate()
877 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
878 .map(|(i, _)| i as u8)
879 .expect("a palette holds at least two colours")
880 })
881 .collect();
882 crate::tile::PaletteY {
883 size: colors.len() as u8,
884 colors: base,
885 map,
886 }
887 };
888 if present.len() <= 8 {
889 return vec![exact(&present)];
890 }
891 if present.len() > palette_max_colors() {
892 return Vec::new();
893 }
894 let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1]));
895 let mut out = Vec::with_capacity(2);
896 for n in [8usize, 4] {
897 // Even seeding across the block's own range, then four Lloyd passes
898 // over the histogram (256 bins, not `side*side` pixels).
899 let mut centres: Vec<f64> = (0..n)
900 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
901 .collect();
902 for _ in 0..4 {
903 let mut sums = vec![0f64; n];
904 let mut counts = vec![0u32; n];
905 for (v, &count) in histogram.iter().enumerate() {
906 if count == 0 {
907 continue;
908 }
909 let k = (0..n)
910 .min_by(|&a, &b| {
911 (centres[a] - v as f64)
912 .abs()
913 .total_cmp(&(centres[b] - v as f64).abs())
914 })
915 .expect("n >= 2");
916 sums[k] += (v as u32 * count) as f64;
917 counts[k] += count;
918 }
919 for k in 0..n {
920 if counts[k] > 0 {
921 centres[k] = sums[k] / f64::from(counts[k]);
922 }
923 }
924 }
925 let mut colors: Vec<u16> = centres
926 .iter()
927 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
928 .collect();
929 colors.sort_unstable();
930 colors.dedup();
931 if colors.len() >= 2 {
932 out.push(exact(&colors));
933 }
934 }
935 out
936}
937
938// ---------------------------------------------------------------------------
939// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
940// validity). A key frame that detected screen content and finds enough exact
941// repeats in its own source sets `allow_intrabc`, which the spec forces every
942// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
943// its place when the copied blocks pay back the deblock/CDEF/LR the frame
944// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
945// ---------------------------------------------------------------------------
946
947/// Whether intra block copy is offered at all. **Off by default** --
948/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
949/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
950/// but on the gate's real screen capture it MEASURED WORSE: setting
951/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
952/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
953/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
954/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
955/// that detected no screen content.
956pub(super) fn intrabc_enabled() -> bool {
957 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
958 return forced;
959 }
960 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
961 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
962}
963
964thread_local! {
965 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
966 /// probe runs both arms in one process, and the suite is one process, so
967 /// an environment variable cannot separate them (same reason
968 /// [`SCREEN_FORCE`] exists).
969 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
970}
971
972#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
973pub(crate) fn force_intrabc(value: Option<bool>) {
974 INTRABC_FORCE.with(|c| c.set(value));
975}
976
977/// How many of a screen frame's 16x16 blocks must have an exact repeat
978/// somewhere else in the source before `allow_intrabc` is worth the in-loop
979/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
980/// constant class: `probe_intrabc_threshold` measures the arm at several
981/// values.
982pub(super) fn intrabc_pct() -> usize {
983 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
984 *N.get_or_init(|| {
985 std::env::var("EC_AV1_INTRABC_PCT")
986 .ok()
987 .and_then(|v| v.parse().ok())
988 .unwrap_or(10)
989 })
990}
991
992/// The pixel grid intrabc source positions are hashed on
993/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
994/// which keeps the block-hash table (and so the search) linear in the frame
995/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
996/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
997/// bilinear interpolation decode.rs applies but this encoder does not.
998pub(super) fn intrabc_step() -> usize {
999 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1000 *N.get_or_init(|| {
1001 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
1002 .ok()
1003 .and_then(|v| v.parse().ok())
1004 .unwrap_or(4);
1005 if n.is_multiple_of(2) { n.max(2) } else { 4 }
1006 })
1007}
1008
1009/// The side of the luma square the block-hash table is keyed on.
1010pub(super) const IBC_HASH: usize = 16;
1011
1012/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
1013/// the current one the source's bottom-right corner must already be. Under
1014/// 128 superblocks the same 256 pixels are two superblocks, which
1015/// [`Ibc::dv_valid`] derives from the size itself.
1016pub(super) const INTRABC_DELAY_SB64: i32 = 4;
1017
1018/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
1019pub(super) fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
1020 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1021 for row in 0..IBC_HASH {
1022 let base = (y + row) * width + x;
1023 for &v in &plane[base..base + IBC_HASH] {
1024 h ^= u64::from(v);
1025 h = h.wrapping_mul(0x100_0000_01b3);
1026 }
1027 }
1028 h
1029}
1030
1031/// Every `intrabc_step()`-aligned position of `plane` inside
1032/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
1033pub(super) fn ibc_index(
1034 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
1035 plane: &[u8],
1036 width: usize,
1037 (x0, y0): (usize, usize),
1038 (x1, y1): (usize, usize),
1039) {
1040 let step = intrabc_step();
1041 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
1042 return;
1043 }
1044 let mut y = y0.next_multiple_of(step);
1045 while y + IBC_HASH <= y1 {
1046 let mut x = x0.next_multiple_of(step);
1047 while x + IBC_HASH <= x1 {
1048 table
1049 .entry(ibc_hash(plane, width, x, y))
1050 .or_default()
1051 .push((x as u32, y as u32));
1052 x += step;
1053 }
1054 y += step;
1055 }
1056}
1057
1058/// Whether `screen`-detected source `y` repeats itself enough to be worth
1059/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
1060/// content appears at some other position, against [`intrabc_pct`]. Returns
1061/// the share as well, for the gate's own print.
1062pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
1063 if true_width < 4 * 64 || true_height < 2 * 64 {
1064 return (false, 0.0);
1065 }
1066 let mut table = std::collections::HashMap::new();
1067 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
1068 let (mut total, mut matched) = (0usize, 0usize);
1069 let mut by = 0;
1070 while by + IBC_HASH <= true_height {
1071 let mut bx = 0;
1072 while bx + IBC_HASH <= true_width {
1073 total += 1;
1074 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by))
1075 && hits
1076 .iter()
1077 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
1078 {
1079 matched += 1;
1080 }
1081 bx += IBC_HASH;
1082 }
1083 by += IBC_HASH;
1084 }
1085 let share = if total == 0 {
1086 0.0
1087 } else {
1088 matched as f64 / total as f64
1089 };
1090 (share * 100.0 >= intrabc_pct() as f64, share)
1091}
1092
1093/// One tile's intrabc search state: a block-hash table over the part of the
1094/// tile's own reconstruction that is already final (whole superblock rows --
1095/// the in-loop filters are off on this frame, so a coded superblock row never
1096/// changes again), plus the last DV chosen, which the RD price uses as its
1097/// predictor estimate.
1098pub(super) struct Ibc {
1099 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
1100 /// source repeats exactly where a lossily coded reconstruction only
1101 /// nearly does, so an exact-match table over the reconstruction finds
1102 /// almost nothing. The candidate is then SCORED against the
1103 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
1104 pub(super) table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
1105 /// The tile's own luma rect, in samples.
1106 pub(super) tile: (usize, usize, usize, usize),
1107 /// The DV the previous intrabc block of this tile took -- the *estimate*
1108 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
1109 /// against. The writer computes the true predictor off its own mi grid
1110 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
1111 /// a slightly mispriced candidate, never a wrong bitstream.
1112 pub(super) last_dv: Option<(i32, i32)>,
1113 /// How many blocks took intrabc, and how many hash lookups found at least
1114 /// one valid candidate -- the gate's own fire counts.
1115 pub(super) hits: usize,
1116 pub(super) lookups: usize,
1117 pub(super) found: usize,
1118}
1119
1120impl Ibc {
1121 pub(super) fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
1122 let mut table = std::collections::HashMap::new();
1123 ibc_index(
1124 &mut table,
1125 source,
1126 width,
1127 (tile.0, tile.1),
1128 (tile.2, tile.3),
1129 );
1130 Self {
1131 table,
1132 tile,
1133 last_dv: None,
1134 hits: 0,
1135 lookups: 0,
1136 found: 0,
1137 }
1138 }
1139
1140 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
1141 /// (1/8 pel), with this lane's own extra restriction on top: the source
1142 /// must lie entirely in a COMPLETED superblock row, which is exactly the
1143 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
1144 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
1145 /// wavefront's own diagonal) are legal and not searched; the upgrade path
1146 /// is to index the current row's finished superblocks too.
1147 pub(super) fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
1148 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
1149 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
1150 return false;
1151 }
1152 let (tx0, ty0, tx1, ty1) = (
1153 self.tile.0 as i32,
1154 self.tile.1 as i32,
1155 self.tile.2 as i32,
1156 self.tile.3 as i32,
1157 );
1158 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
1159 let (w, h) = (w as i32, h as i32);
1160 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
1161 return false;
1162 }
1163 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
1164 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
1165 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
1166 // Counting 64s under a 128 superblock let the search take a source
1167 // from a 64 row the 128 visit order had not reconstructed yet.
1168 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
1169 let delay: i32 = if sb_log2 == 7 {
1170 INTRABC_DELAY_SB64 / 2
1171 } else {
1172 INTRABC_DELAY_SB64
1173 };
1174 let active_sb_row = (y as i32 - ty0) >> sb_log2;
1175 let active_sb_col = (x as i32 - tx0) >> sb_log2;
1176 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
1177 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
1178 // This lane's own restriction (see the doc comment).
1179 if src_sb_row >= active_sb_row {
1180 return false;
1181 }
1182 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
1183 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
1184 return false;
1185 }
1186 // libaom's wavefront: only the top-left cone of the frame is legal.
1187 let wf = (1 + delay) * (active_sb_row - src_sb_row);
1188 src_sb_col < active_sb_col - delay + wf
1189 }
1190}
1191
1192/// How many block searches ran, how many found at least one VALID candidate,
1193/// and how many won on rate-distortion -- the hash hit rate a gate prints
1194/// (class `gate-blind-to-feature`: "the search ran" and "the search found
1195/// something" and "the block took it" are three different claims).
1196pub(super) static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
1197 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1198
1199impl Drop for Ibc {
1200 fn drop(&mut self) {
1201 for (slot, n) in [self.lookups, self.found, self.hits]
1202 .into_iter()
1203 .enumerate()
1204 {
1205 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1206 }
1207 }
1208}
1209
1210/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
1211/// its own encode.
1212#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1213pub(crate) fn take_intrabc_search() -> [usize; 3] {
1214 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1215}
1216
1217/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
1218/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
1219/// infers rather than codes.
1220pub(super) fn dv_component_bits(diff: i32) -> f64 {
1221 let z = diff.unsigned_abs() as i32 - 1;
1222 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
1223 let class = mv_class_of(z);
1224 bits += symbol_bits(&cdf::MV_CLASS, class);
1225 let local = z - mv_class_base(class);
1226 if class == 0 {
1227 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
1228 } else {
1229 let d = local >> 3;
1230 for i in 0..class {
1231 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
1232 }
1233 }
1234 bits
1235}
1236
1237/// What one block vector costs against `pred`, plus the `skip` and
1238/// `use_intrabc` flags the block carries and the ordinary intra block does
1239/// not pay in this currency.
1240pub(super) fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
1241 let diff = (dv.0 - pred.0, dv.1 - pred.1);
1242 let joint = match (diff.0 != 0, diff.1 != 0) {
1243 (false, false) => 0,
1244 (false, true) => 1,
1245 (true, false) => 2,
1246 (true, true) => 3,
1247 };
1248 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
1249 if diff.0 != 0 {
1250 bits += dv_component_bits(diff.0);
1251 }
1252 if diff.1 != 0 {
1253 bits += dv_component_bits(diff.1);
1254 }
1255 bits
1256}
1257
1258/// The squared error of copying the `side`-square block at `(sx, sy)` of each
1259/// plane's reconstruction onto the source block at `(x, y)`, luma and both
1260/// chroma planes together -- what an intrabc block's whole (residual-free)
1261/// distortion is.
1262pub(super) fn ibc_sse(
1263 luma: &Plane,
1264 chroma: &[Plane; 2],
1265 (x, y): (usize, usize),
1266 (sx, sy): (usize, usize),
1267 side: usize,
1268) -> f64 {
1269 // Inside the true frame only, for the reason [`Plane::block_sse`] is
1270 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
1271 // how well it copies the padding.
1272 let mut sse = 0.0f64;
1273 let clip = |whole: usize, inside: usize| match edge_sse() {
1274 true => whole.min(inside),
1275 false => whole,
1276 };
1277 let rows = clip(side, luma.true_height.saturating_sub(y));
1278 let cols = clip(side, luma.true_width.saturating_sub(x));
1279 for row in 0..rows {
1280 let src = &luma.source[(y + row) * luma.width + x..][..cols];
1281 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
1282 for (&s, &r) in src.iter().zip(rec) {
1283 let d = f64::from(i32::from(s) - i32::from(r));
1284 sse += d * d;
1285 }
1286 }
1287 let half = side / 2;
1288 for plane in chroma {
1289 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
1290 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
1291 for row in 0..rows {
1292 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
1293 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
1294 for (&s, &r) in src.iter().zip(rec) {
1295 let d = f64::from(i32::from(s) - i32::from(r));
1296 sse += d * d;
1297 }
1298 }
1299 }
1300 sse
1301}
1302
1303/// Copies the `side`-square block at `(sx, sy)` of each plane's
1304/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
1305/// since it carries no residual (`skip`). Full-pel in both planes by
1306/// construction ([`intrabc_step`] keeps every DV even), which is what makes
1307/// this a plain copy where decode.rs runs the bilinear kernel over the same
1308/// samples.
1309pub(super) fn ibc_commit(
1310 luma: &mut Plane,
1311 chroma: &mut [Plane; 2],
1312 (x, y): (usize, usize),
1313 (sx, sy): (usize, usize),
1314 side: usize,
1315) {
1316 for row in 0..side {
1317 let from = (sy + row) * luma.width + sx;
1318 let to = (y + row) * luma.width + x;
1319 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
1320 luma.reconstruction[to..to + side].copy_from_slice(&copied);
1321 }
1322 let half = side / 2;
1323 for plane in chroma {
1324 for row in 0..half {
1325 let from = (sy / 2 + row) * plane.width + sx / 2;
1326 let to = (y / 2 + row) * plane.width + x / 2;
1327 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
1328 plane.reconstruction[to..to + half].copy_from_slice(&copied);
1329 }
1330 plane.commit_ctx_zero(x / 2, y / 2, half);
1331 }
1332 luma.commit_ctx_zero(x, y, side);
1333}
1334
1335/// Searches this block's own DV: every hash-table position whose 16x16 luma
1336/// square equals the block's source square, plus the previous block's DV as a
1337/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
1338/// the winning `(dv, cost)`, or `None` when nothing valid was found.
1339pub(super) fn ibc_search(
1340 ibc: &mut Ibc,
1341 luma: &Plane,
1342 chroma: &[Plane; 2],
1343 (x, y): (usize, usize),
1344 side: usize,
1345 lambda: f64,
1346) -> Option<((i32, i32), f64, (usize, usize))> {
1347 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
1348 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
1349 let consider =
1350 |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
1351 let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8);
1352 if !ibc.dv_valid(x, y, side, side, dv) {
1353 return;
1354 }
1355 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
1356 if best.as_ref().is_none_or(|b| cost < b.1) {
1357 *best = Some((dv, cost, (sx, sy)));
1358 }
1359 };
1360 ibc.lookups += 1;
1361 let key = ibc_hash(luma.source, luma.width, x, y);
1362 // The table is filled in raster order, so the entries BEFORE this block's
1363 // own position are exactly the already-coded ones -- and the nearest of
1364 // them costs the fewest DV bits. Walking backwards from the block's own
1365 // slot is what makes the search look up-and-left; taking the newest
1366 // entries outright only ever finds candidates below and to the right,
1367 // every one of which `dv_valid` rejects.
1368 let hits: Vec<(u32, u32)> = ibc
1369 .table
1370 .get(&key)
1371 .map(|h| {
1372 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
1373 h[..end].iter().rev().take(32).copied().collect()
1374 })
1375 .unwrap_or_default();
1376 for (hx, hy) in hits {
1377 consider(&*ibc, hx as usize, hy as usize, &mut best);
1378 }
1379 if let Some(dv) = ibc.last_dv {
1380 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
1381 if sx >= 0 && sy >= 0 {
1382 consider(&*ibc, sx as usize, sy as usize, &mut best);
1383 }
1384 }
1385 if best.is_some() {
1386 ibc.found += 1;
1387 }
1388 best
1389}
1390
1391// Spec-shaped signature; bundling the operands would obscure the spec mapping.
1392#[allow(clippy::too_many_arguments)]
1393pub(super) fn code_square(
1394 luma: &mut Plane,
1395 chroma: &mut [Plane; 2],
1396 (x, y): (usize, usize),
1397 side: usize,
1398 search: &Search,
1399 mode_bits: &[f64; 13],
1400 // The frame header's `tx_mode == TxMode::Select`: the block then searches
1401 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
1402 // transform over its whole side.
1403 tx_select: bool,
1404 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
1405 // header did not set `allow_intrabc`.
1406 ibc: Option<&mut Ibc>,
1407 // Whether this is a KEY frame's block, read only by the split census
1408 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
1409 // which is this lane's whole finding.
1410 census_key: bool,
1411 fctx: &crate::decode::FrameCtx,
1412) -> (BlockCoeffs, f64) {
1413 let (luma_set, chroma_set) = if side == SUPERBLOCK {
1414 // A whole superblock coded as ONE intra block (lane-i64): one
1415 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
1416 // `code_from_prediction` hands back, and one TX_32X32 per chroma
1417 // plane -- the same three sets the key frame writer's
1418 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
1419 // uses (`search_skip_64`).
1420 (TxbSet::Luma64, TxbSet::Chroma32)
1421 } else if side == BLOCK {
1422 (TxbSet::Luma32, TxbSet::Chroma16)
1423 } else if side == 8 {
1424 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
1425 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
1426 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
1427 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
1428 // (this branch is still unreached), so leaving `Chroma8` here would
1429 // silently wire the wrong table the moment one does; `Chroma4` is
1430 // what a real caller needs.
1431 (TxbSet::Luma8, TxbSet::Chroma4)
1432 } else {
1433 (TxbSet::Luma16, TxbSet::Chroma8)
1434 };
1435 let at = At {
1436 x,
1437 y,
1438 side,
1439 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
1440 set: luma_set_for(luma_set, search.screen),
1441 };
1442 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
1443 luma.search_block(at, search, mode_bits, fctx);
1444 let mut luma_tx_types = vec![tx_type];
1445 // The depth search runs on the mode the whole-block transform picked --
1446 // libaom's own ordering, and the reason it costs one extra pass per depth
1447 // rather than one per (mode, depth) pair.
1448 let mut tx_depth = 0u8;
1449 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
1450 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
1451 // pays that zero exactly as a 32x32's depth search makes it pay
1452 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
1453 // below hands the root a symbol for free.
1454 if tx_select && side == SUPERBLOCK {
1455 cost += search.lambda * tx_depth_bits(side, 0);
1456 }
1457 if tx_select && max_tx_depth(side) > 0 {
1458 let mut best = (
1459 cost + search.lambda * tx_depth_bits(side, 0),
1460 0usize,
1461 luma.snapshot(x, y, side),
1462 luma_coeffs,
1463 );
1464 let mut best_types = std::mem::take(&mut luma_tx_types);
1465 // The census wants the flat arm's own (rate, distortion), which
1466 // `search_block` only hands back folded into one cost -- so under the
1467 // env flag alone it is re-coded at depth 0 and the plane restored.
1468 let census_flat = split_census_on().then(|| {
1469 let kept = luma.snapshot(x, y, side);
1470 let (_, sse, bits, _) =
1471 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
1472 luma.restore(x, y, side, &kept);
1473 (bits + tx_depth_bits(side, 0), sse)
1474 });
1475 let mut census_split: Option<(f64, f64)> = None;
1476 for depth in 1..=max_tx_depth(side) {
1477 let (levels, sse, bits, types) =
1478 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
1479 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
1480 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
1481 if census_flat.is_some() {
1482 let c = (bits + tx_depth_bits(side, depth), sse);
1483 if census_split
1484 .is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
1485 {
1486 census_split = Some(c);
1487 }
1488 }
1489 if cost_d < best.0 {
1490 best = (
1491 cost_d,
1492 depth,
1493 luma.snapshot(x, y, side),
1494 coeffs(&levels, side),
1495 );
1496 best_types = types;
1497 }
1498 }
1499 if let (Some(flat), Some(split)) = (census_flat, census_split) {
1500 split_census(0, census_key, side, best.1 > 0, split, flat);
1501 }
1502 luma_tx_types = best_types;
1503 luma.restore(x, y, side, &best.2);
1504 cost = best.0;
1505 tx_depth = best.1 as u8;
1506 luma_coeffs = best.3;
1507 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1508 }
1509 // The palette candidate is priced against the mode the luma search (and
1510 // its transform-depth search) already settled on, so a block only takes
1511 // one when it beats the best ordinary intra coding of the same pixels.
1512 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
1513 // prediction is the colour map, not the DC of its neighbours.
1514 let mut mode = mode;
1515 let mut angle_delta = angle_delta;
1516 let mut palette = None;
1517 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
1518 let source: Vec<u8> = (y..y + side)
1519 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
1520 .collect();
1521 let kept = luma.snapshot(x, y, side);
1522 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
1523 // its map over the ON-SCREEN corner only and the decoder replicates
1524 // that outward, so the searched map is folded the same way here --
1525 // the prediction priced, the reconstruction committed and the symbols
1526 // `write_color_index_map` writes are then one and the same map
1527 // (lane-palw).
1528 let on = (
1529 side.min(luma.true_width.saturating_sub(x)),
1530 side.min(luma.true_height.saturating_sub(y)),
1531 );
1532 for mut pal in palette_candidates(&source) {
1533 let n = usize::from(pal.size);
1534 crate::decode::palette_replicate(&mut pal.map, side, side, on);
1535 let prediction: Vec<u8> = pal
1536 .map
1537 .iter()
1538 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
1539 .collect();
1540 let trial = luma.code_from_prediction(
1541 x,
1542 y,
1543 side,
1544 &prediction,
1545 false,
1546 search.base_q_idx,
1547 search.deadzone,
1548 luma_set,
1549 );
1550 let cost_p = trial.sse
1551 + search.lambda
1552 * (trial.bits
1553 + mode_bits[DC_PRED as usize]
1554 + crate::tile::palette_bits(&pal, side, on)
1555 + if tx_select {
1556 tx_depth_bits(side, 0)
1557 } else {
1558 0.0
1559 });
1560 if cost_p < cost {
1561 cost = cost_p;
1562 mode = DC_PRED;
1563 angle_delta = 0;
1564 tx_depth = 0;
1565 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
1566 luma.commit(x, y, side, &trial);
1567 palette = Some(pal);
1568 }
1569 }
1570 if palette.is_none() {
1571 luma.restore(x, y, side, &kept);
1572 }
1573 }
1574
1575 // The five recursive filter-intra modes (spec 5.11.14), priced against
1576 // whatever the mode, transform-depth and palette searches settled on --
1577 // the same "one candidate loop after the incumbent is known" shape the
1578 // palette above uses. A block that takes one is `DC_PRED` with no palette
1579 // by construction (`av1_filter_intra_allowed`), and its luma transform
1580 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
1581 //
1582 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
1583 // depth the ordinary intra search runs, each unit predicting recursively
1584 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
1585 // arm), so a block whose ordinary winner wanted a split transform is
1586 // compared against a filter arm that may split too.
1587 //
1588 // Measured (native BD table, lane-fitu): searching the depths on EVERY
1589 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
1590 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
1591 // locally cheaper reconstruction that the film rows go on to predict from
1592 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
1593 // content is where it pays, and a non-screen frame keeps the depth-0-only
1594 // arm, byte for byte.
1595 let mut filter_intra: Option<u8> = None;
1596 if filter_intra_on()
1597 && palette.is_none()
1598 && let Some(class) = crate::decode::filter_intra_size_class(side)
1599 {
1600 let row = &cdf::FILTER_INTRA[class];
1601 // With the sequence bit on, EVERY `DC_PRED` block without a luma
1602 // palette carries the flag, so the incumbent pays its zero before the
1603 // comparison -- otherwise the candidate is charged a bit the block
1604 // spends either way (class `price-the-narrowing-not-the-table`).
1605 if mode == DC_PRED {
1606 cost += search.lambda * symbol_bits(row, 0);
1607 }
1608 let one_bits = symbol_bits(row, 1);
1609 let kept = luma.snapshot(x, y, side);
1610 let max_depth = if tx_select && search.screen {
1611 max_tx_depth(side)
1612 } else {
1613 0
1614 };
1615 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
1616 for fi in 0..5u8 {
1617 for depth in 0..=max_depth {
1618 // A filter-intra block's units are coded through
1619 // `code_from_prediction`, which is `DCT_DCT` throughout, so
1620 // this arm keeps the empty (all-`DCT_DCT`) type list.
1621 let (levels, sse, bits, _) =
1622 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
1623 let cost_f = sse
1624 + search.lambda
1625 * (bits
1626 + mode_bits[DC_PRED as usize]
1627 + one_bits
1628 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
1629 + if tx_select {
1630 tx_depth_bits(side, depth)
1631 } else {
1632 0.0
1633 });
1634 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
1635 best = Some((
1636 cost_f,
1637 fi,
1638 depth,
1639 luma.snapshot(x, y, side),
1640 coeffs(&levels, side),
1641 ));
1642 }
1643 }
1644 }
1645 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
1646 cost = cost_f;
1647 mode = DC_PRED;
1648 angle_delta = 0;
1649 tx_depth = depth as u8;
1650 luma_coeffs = levels;
1651 luma.restore(x, y, side, &snapshot);
1652 filter_intra = Some(fi);
1653 } else {
1654 luma.restore(x, y, side, &kept);
1655 }
1656 }
1657
1658 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
1659 // planes; what it costs still counts towards the partition decision.
1660 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
1661 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
1662 cost += chroma_cost;
1663
1664 // The intrabc arm is priced against the WHOLE block -- luma and both
1665 // chroma planes, residual-free -- so it is compared after the chroma
1666 // search has added its own cost, not against the luma decision alone.
1667 if let Some(ibc) = ibc
1668 && let Some((dv, cost_ibc, src)) =
1669 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
1670 && cost_ibc < cost {
1671 ibc_commit(luma, chroma, (x, y), src, side);
1672 ibc.last_dv = Some(dv);
1673 ibc.hits += 1;
1674 return (
1675 BlockCoeffs {
1676 skip: true,
1677 dv: Some(dv),
1678 ..BlockCoeffs::default()
1679 },
1680 cost_ibc,
1681 );
1682 }
1683 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
1684 // (its levels came from `code_from_prediction`), so the searched types
1685 // belong to a block this one no longer is.
1686 if palette.is_some() || filter_intra.is_some() {
1687 luma_tx_types = Vec::new();
1688 }
1689 (
1690 BlockCoeffs {
1691 u,
1692 v,
1693 luma: luma_coeffs,
1694 mode,
1695 uv_mode,
1696 tx_depth,
1697 palette,
1698 palette_uv,
1699 filter_intra,
1700 cfl_alphas,
1701 angle_delta_y: angle_delta as i8,
1702 luma_tx_types,
1703 ..BlockCoeffs::default()
1704 },
1705 cost,
1706 )
1707}
1708
1709/// The chroma modes the search offers, and the only ones it may offer: each
1710/// predicts from the row directly above and the column directly to the left
1711/// and nothing further, so none of them needs the above-right/below-left
1712/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
1713/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
1714/// reconstruction and its own alpha syntax; both are left out here.
1715pub(super) const CHROMA_MODES: [u8; 7] = [
1716 DC_PRED,
1717 V_PRED,
1718 H_PRED,
1719 SMOOTH_PRED,
1720 SMOOTH_V_PRED,
1721 SMOOTH_H_PRED,
1722 PAETH_PRED,
1723];
1724
1725/// The thirteen intra mode names, for the chroma fire count's print.
1726#[cfg(test)]
1727pub(super) const UV_MODE_NAMES: [&str; 14] = [
1728 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
1729 "PAETH", "CFL",
1730];
1731
1732/// How many blocks each chroma mode has won, indexed by the mode itself --
1733/// the fire count that says whether the search below reaches its candidates
1734/// at all (the `gate-blind-to-feature` class), printed once per gate run.
1735pub(super) static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
1736 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
1737
1738/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
1739/// won, summed over both chroma planes -- the alpha histogram the gate prints
1740/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
1741/// magnitude only is a search that never left its first candidate).
1742pub(super) static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
1743 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
1744
1745/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
1746/// zero on a CfL block", `1..=16` the magnitudes.
1747#[cfg(test)]
1748pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
1749 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
1750}
1751
1752/// How many directional luma blocks won at each `angle_delta_y`, indexed
1753/// `delta + 3` -- the histogram that says whether the refinement below ever
1754/// leaves zero (`gate-blind-to-feature`).
1755pub(super) static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
1756 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1757
1758/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
1759#[cfg(test)]
1760pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
1761 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
1762}
1763
1764/// Whether the luma search refines a directional winner's `angle_delta_y`
1765/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
1766pub(super) fn angle_delta_on() -> bool {
1767 static ENV: std::sync::LazyLock<Option<bool>> =
1768 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
1769 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
1770}
1771
1772/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
1773/// switches it off, which is how the lane measured its own on/off pair).
1774pub(super) fn cfl_on() -> bool {
1775 static ENV: std::sync::LazyLock<Option<bool>> =
1776 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0"));
1777 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
1778}
1779
1780// Whether the intra search offers the five recursive filter-intra modes at
1781// all, and with them whether the sequence header sets `enable_filter_intra`
1782// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
1783// its own on/off pair -- and how every byte pin written before it still
1784// reproduces). It is also a speed lever: on at preset 0, off above it.
1785// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
1786// it off for the whole process (a sequence-header field, so it cannot change
1787// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
1788// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
1789// this workspace.
1790
1791/// Whether a sequence codes 128x128 superblocks when the environment says
1792/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
1793/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
1794/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
1795/// 128x128 block in it every row of the native BD gate is down or flat on
1796/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
1797///
1798/// | row | 64 superblocks | 128 + the 128 root |
1799/// |---|---|---|
1800/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
1801/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
1802/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
1803/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
1804/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
1805///
1806/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
1807/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
1808///
1809/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
1810/// off (the delta_q unit at the 128 superblock, the superblock size travelling
1811/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
1812/// predictor and wavefront, and seven test harnesses that handed the encoder a
1813/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
1814pub(crate) const SB128_DEFAULT: bool = true;
1815
1816/// Whether this process's sequences code 128x128 superblocks. An ENCODER
1817/// knob (like `speed::SPEED`), never read by a decode: read through a
1818/// process-global (not a thread-local) because the tile writers run on
1819/// worker threads; `2` is "the environment has not been read yet".
1820pub(super) static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
1821
1822/// Whether this process's sequences code 128x128 superblocks.
1823pub(crate) fn sb128_on() -> bool {
1824 use std::sync::atomic::Ordering::Relaxed;
1825 match ENC_SB128.load(Relaxed) {
1826 2 => {
1827 let on = crate::envflags::var("EC_AV1_SB128")
1828 .ok()
1829 .map_or(SB128_DEFAULT, |v| v != "0");
1830 ENC_SB128.store(u8::from(on), Relaxed);
1831 on
1832 }
1833 v => v == 1,
1834 }
1835}
1836
1837/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
1838/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
1839/// exactly like the speed-preset gates.
1840#[cfg(test)]
1841pub(crate) fn force_sb128(on: bool) {
1842 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
1843}
1844
1845/// The luma loop-restoration unit size this sequence codes: a 128 superblock
1846/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
1847/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
1848/// 128), which is the one filter parameter the superblock size moves.
1849pub(crate) fn lr_unit() -> u32 {
1850 if sb128_on() { 128 } else { 64 }
1851}
1852
1853pub(crate) fn filter_intra_on() -> bool {
1854 #[cfg(test)]
1855 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
1856 return forced;
1857 }
1858 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1859 crate::envflags::var("EC_AV1_FILTER_INTRA")
1860 .ok()
1861 .map(|v| v != "0")
1862 });
1863 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
1864}
1865
1866/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
1867/// to its own encode.
1868#[cfg(test)]
1869pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
1870 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
1871}
1872
1873/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
1874/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
1875/// Returns each plane's levels, the mode, and what the pair cost (squared
1876/// error plus lambda times bits, the same currency the luma search speaks).
1877///
1878/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
1879/// which is what the luma mode decision was taken against, so what a
1880/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
1881/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
1882/// writer then has to code.
1883#[allow(clippy::too_many_arguments)]
1884/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
1885/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
1886/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
1887/// trials all seven, as before this lever.
1888///
1889/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
1890/// the search's largest trial population by far -- seven modes times two
1891/// planes for every intra block, against 3.7 luma trials -- and the RD
1892/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
1893/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
1894pub(super) fn chroma_top_k() -> Option<usize> {
1895 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
1896 crate::envflags::var("EC_AV1_CHROMA_K")
1897 .ok()
1898 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
1899 });
1900 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
1901}
1902
1903/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
1904/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
1905/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
1906/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
1907/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
1908/// BD swings by about a point in either direction as near-tie chroma modes
1909/// flip, which is the measurement's own sensitivity, not a trend: nothing
1910/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
1911/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
1912/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
1913/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
1914pub(crate) const CHROMA_TOP_K: Option<usize> = None;
1915
1916// Spec-shaped signature; bundling the operands would obscure the spec mapping.
1917#[allow(clippy::too_many_arguments)]
1918pub(super) fn search_chroma(
1919 chroma: &mut [Plane; 2],
1920 // The luma plane's RECONSTRUCTION under this block, already committed by
1921 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
1922 luma: &Plane,
1923 (x, y): (usize, usize),
1924 side: usize,
1925 set: TxbSet,
1926 search: &Search,
1927 luma_mode: u8,
1928 fctx: &crate::decode::FrameCtx,
1929) -> (
1930 [Vec<Coeff>; 2],
1931 u8,
1932 f64,
1933 Option<crate::tile::PaletteUv>,
1934 Option<(i32, i32)>,
1935) {
1936 let at = At {
1937 x: x / 2,
1938 y: y / 2,
1939 side: side / 2,
1940 reach: Reach::none(),
1941 set,
1942 };
1943 // The census's cheap proxy for a chroma mode: the SAD of its prediction
1944 // summed over both planes, ranked by the same rule the luma histogram
1945 // uses. Only built under `EC_AV1_CENSUS`.
1946 // The SAD of each mode's prediction, summed over both planes -- the
1947 // census's ranking rule, and what [`chroma_top_k`] prunes by.
1948 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
1949 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
1950 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
1951 u.iter()
1952 .zip(v.iter())
1953 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
1954 .collect()
1955 };
1956 let modes: Vec<u8> = match chroma_top_k() {
1957 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
1958 _ => CHROMA_MODES.to_vec(),
1959 };
1960 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
1961 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
1962 let ranking: Vec<(f64, u8)> = if census_on() {
1963 sad_scores(chroma)
1964 } else {
1965 Vec::new()
1966 };
1967 census_add(2, 1);
1968 census_add(3, modes.len());
1969 let mut best: Option<(f64, u8, Trial, Trial)> = None;
1970 for mode in modes {
1971 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
1972 if (V_PRED..=D67_PRED).contains(&mode) {
1973 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
1974 }
1975 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
1976 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
1977 // chroma of a 64x64 block is `DCT_DCT` whatever
1978 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
1979 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
1980 // points.
1981 let tx_type = if at.side >= 32 {
1982 TxType::DctDct
1983 } else {
1984 crate::decode::default_intra_tx_type(mode)
1985 };
1986 let u = chroma[0].trial_typed(
1987 at,
1988 mode,
1989 0,
1990 search.base_q_idx,
1991 search.deadzone,
1992 tx_type,
1993 fctx,
1994 );
1995 let v = chroma[1].trial_typed(
1996 at,
1997 mode,
1998 0,
1999 search.base_q_idx,
2000 search.deadzone,
2001 tx_type,
2002 fctx,
2003 );
2004 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
2005 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
2006 best = Some((cost, mode, u, v));
2007 }
2008 }
2009 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
2010 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
2011 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
2012 // what keeps `u_colors` ascending and distinct the way
2013 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
2014 // each cluster's own mean, since the colour-index map is SHARED by the
2015 // two planes. Priced against the best ordinary chroma mode above, so a
2016 // block only takes one when it beats it; a palette block's chroma mode is
2017 // `UV_DC_PRED` by construction.
2018 let mut palette_uv = None;
2019 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2020 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
2021 let plane_source = |p: &Plane| -> Vec<u8> {
2022 (at.y..at.y + at.side)
2023 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
2024 .collect()
2025 };
2026 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
2027 // The luma on-screen extent carried into this plane exactly as the
2028 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
2029 let on_uv = crate::decode::palette_onscreen_uv(
2030 (side, side),
2031 (
2032 side.min(luma.true_width.saturating_sub(x)),
2033 side.min(luma.true_height.saturating_sub(y)),
2034 ),
2035 (at.side, at.side),
2036 // The encoder writes 4:2:0 only (`palette_uv_side` above).
2037 (1, 1),
2038 );
2039 for mut pal in palette_candidates(&u_source) {
2040 let n = usize::from(pal.size);
2041 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
2042 // V's base colour per cluster: the mean of the samples the shared
2043 // map assigns to it (an empty cluster cannot happen -- every
2044 // colour `palette_candidates` returns is some pixel's nearest).
2045 let mut sums = [0u32; 8];
2046 let mut counts = [0u32; 8];
2047 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
2048 let k = usize::from(i).min(n - 1);
2049 sums[k] += u32::from(sample);
2050 counts[k] += 1;
2051 }
2052 let mut v_colors = [0u16; 8];
2053 for k in 0..n {
2054 v_colors[k] = (sums[k] + counts[k] / 2).checked_div(counts[k]).unwrap_or(0) as u16;
2055 }
2056 let candidate = crate::tile::PaletteUv {
2057 size: pal.size,
2058 u_colors: pal.colors,
2059 v_colors,
2060 map: pal.map,
2061 };
2062 let predict = |colors: &[u16; 8]| -> Vec<u8> {
2063 candidate
2064 .map
2065 .iter()
2066 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
2067 .collect()
2068 };
2069 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
2070 let u_trial = chroma[0].code_from_prediction(
2071 at.x,
2072 at.y,
2073 at.side,
2074 &pu,
2075 false,
2076 search.base_q_idx,
2077 search.deadzone,
2078 set,
2079 );
2080 let v_trial = chroma[1].code_from_prediction(
2081 at.x,
2082 at.y,
2083 at.side,
2084 &pv,
2085 false,
2086 search.base_q_idx,
2087 search.deadzone,
2088 set,
2089 );
2090 let cost_p = u_trial.sse
2091 + v_trial.sse
2092 + search.lambda
2093 * (u_trial.bits
2094 + v_trial.bits
2095 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
2096 if cost_p < cost {
2097 cost = cost_p;
2098 mode = DC_PRED;
2099 u = u_trial;
2100 v = v_trial;
2101 palette_uv = Some(candidate);
2102 }
2103 }
2104 }
2105 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
2106 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
2107 // nudges every sample by `alpha_q3` times the block's subsampled,
2108 // average-subtracted luma reconstruction. Offered only where
2109 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
2110 // and priced against the best ordinary chroma mode above, palette
2111 // included, so a block only takes it when it beats both.
2112 let mut cfl_alphas = None;
2113 if side <= 32 && cfl_on() {
2114 // The AC signal, through the decoder's own
2115 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
2116 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
2117 i32::from(luma.reconstruction[ly * luma.width + lx])
2118 });
2119 let dc_prediction = |plane: &Plane| -> Vec<u8> {
2120 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2121 let (above, left, corner) =
2122 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
2123 let mut prediction = vec![0u8; at.side * at.side];
2124 intra_predict_u8(
2125 DC_PRED,
2126 0,
2127 above,
2128 left,
2129 corner,
2130 at.side,
2131 at.side,
2132 false,
2133 false,
2134 &mut prediction,
2135 fctx,
2136 );
2137 prediction
2138 };
2139 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
2140 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
2141 // add the residual -- which is what [`Plane::code_from_prediction`]
2142 // does with what this returns.
2143 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
2144 base.iter()
2145 .zip(ac.iter())
2146 .map(|(&b, &a)| {
2147 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
2148 })
2149 .collect()
2150 };
2151 // The least-squares alpha, then its two neighbours: minimising
2152 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
2153 // dot-product ratio, and the quantised optimum is one of the two
2154 // integers around it (the clamp and the Q6 rounding are what the SSE
2155 // check below re-decides). libaom sweeps all sixteen magnitudes under
2156 // full RD; three predictions per plane buy nearly the same alpha for a
2157 // thirtieth of the search.
2158 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
2159 let (mut num, mut den) = (0.0f64, 0.0f64);
2160 for row in 0..at.side {
2161 for col in 0..at.side {
2162 let i = row * at.side + col;
2163 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
2164 - f64::from(base[i]);
2165 num += d * f64::from(ac[i]);
2166 den += f64::from(ac[i]) * f64::from(ac[i]);
2167 }
2168 }
2169 if den == 0.0 {
2170 return 0;
2171 }
2172 let ideal = 64.0 * num / den;
2173 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
2174 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
2175 let alpha = alpha.clamp(-16, 16) as i32;
2176 if alpha == 0 {
2177 continue;
2178 }
2179 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
2180 if sse < best.0 {
2181 best = (sse, alpha);
2182 }
2183 }
2184 best.1
2185 };
2186 let picked = [
2187 pick_alpha(&chroma[0], &bases[0]),
2188 pick_alpha(&chroma[1], &bases[1]),
2189 ];
2190 if picked != [0, 0] {
2191 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
2192 let trial = |plane_idx: usize, alpha: i32| -> Trial {
2193 let prediction = if alpha == 0 {
2194 bases[plane_idx].clone()
2195 } else {
2196 apply(&bases[plane_idx], alpha)
2197 };
2198 chroma[plane_idx].code_from_prediction(
2199 at.x,
2200 at.y,
2201 at.side,
2202 &prediction,
2203 false,
2204 search.base_q_idx,
2205 search.deadzone,
2206 set,
2207 )
2208 };
2209 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
2210 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
2211 let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])];
2212 for &(alpha_u, alpha_v) in &combos {
2213 if (alpha_u, alpha_v) == (0, 0) {
2214 continue;
2215 }
2216 let cu = trial(0, alpha_u);
2217 let cv = trial(1, alpha_v);
2218 let bits =
2219 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
2220 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
2221 if cost_cfl < cost {
2222 cost = cost_cfl;
2223 mode = crate::tile::UV_CFL_PRED as u8;
2224 u = cu;
2225 v = cv;
2226 palette_uv = None;
2227 cfl_alphas = Some((alpha_u, alpha_v));
2228 }
2229 }
2230 }
2231 }
2232 if let Some((alpha_u, alpha_v)) = cfl_alphas {
2233 for alpha in [alpha_u, alpha_v] {
2234 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
2235 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2236 }
2237 }
2238 if census_on() {
2239 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2240 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2241 }
2242 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2243 chroma[0].commit(at.x, at.y, at.side, &u);
2244 chroma[1].commit(at.x, at.y, at.side, &v);
2245 (
2246 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
2247 mode,
2248 cost,
2249 palette_uv,
2250 cfl_alphas,
2251 )
2252}
2253
2254/// Codes one leaf of a straddling quadrant as whichever costs least of intra
2255/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
2256/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
2257/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
2258/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
2259/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
2260/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
2261/// attempted here: these leaves only ever fill the sliver of real content a
2262/// true edge lands in the middle of a larger block, not a leaf worth a full
2263/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
2264/// (see `write_inter_frame_leaf`'s doc comment).
2265#[allow(clippy::too_many_arguments)]
2266/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
2267/// as [`code_square_inter`] wants them: empty on a frame that codes no
2268/// `reference_select`, or when the leaf compound candidates are switched off.
2269/// One helper because THREE leaf call sites need it -- the split quadrants
2270/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
2271/// `&[]` and so coded no compound block anywhere along the frame's true edge.
2272pub(super) fn leaf_compound_stacks<'a>(
2273 grid: &MiGrid,
2274 mi_row: usize,
2275 mi_col: usize,
2276 bw4: usize,
2277 bh4: usize,
2278 mi_cols: usize,
2279 mi_rows: usize,
2280 reference_select: bool,
2281 golden: Option<&'a Picture>,
2282 altref: Option<&'a Picture>,
2283) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
2284 if !(reference_select && leaf_compound()) {
2285 return Vec::new();
2286 }
2287 [
2288 (crate::mvstack::GOLDEN_FRAME, golden),
2289 (crate::mvstack::ALTREF_FRAME, altref),
2290 ]
2291 .into_iter()
2292 .filter_map(|(r, pic)| {
2293 pic.map(|p| {
2294 (
2295 r,
2296 p,
2297 crate::mvstack::find_mv_stack_compound(
2298 grid,
2299 mi_row,
2300 mi_col,
2301 bw4,
2302 bh4,
2303 (crate::mvstack::LAST_FRAME, r),
2304 mi_cols,
2305 mi_rows,
2306 grid.sign_bias_table(),
2307 &[(0, 0); 7],
2308 None,
2309 ),
2310 )
2311 })
2312 })
2313 .collect()
2314}
2315
2316/// The OBMC prediction of one square single-reference block: this block's own
2317/// translation prediction (`mc::predict`) with every bordering above/left
2318/// neighbour blended into the overlap strips by the DECODER's own plan and
2319/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
2320/// the search prices is what a decoder reconstructs -- never a second
2321/// implementation of the blend. `None` when the block has no overlappable
2322/// neighbour at all (the writer would then code no `motion_mode` symbol) or
2323/// when the plan cannot be built (a neighbour naming a reference this encode
2324/// does not hold).
2325#[allow(clippy::too_many_arguments)]
2326pub(super) fn obmc_prediction(
2327 grid: &MiGrid,
2328 (mi_row, mi_col): (usize, usize),
2329 (mi_rows, mi_cols): (usize, usize),
2330 (x, y): (usize, usize),
2331 side: usize,
2332 mv: (i32, i32),
2333 refs: &[Option<&Picture>; 8],
2334 // This block's OWN reference planes, luma then both chroma, each as
2335 // (samples, stride, true width, true height).
2336 ref_planes: [(&[u16], usize, usize, usize); 3],
2337 frame_size: (usize, usize),
2338 fctx: &crate::decode::FrameCtx,
2339) -> Option<[Vec<u8>; 3]> {
2340 let n4 = side / 4;
2341 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
2342 return None;
2343 }
2344 let refpix = crate::decode::RefPix::ready(*refs);
2345 let plan = crate::decode::obmc_plan(
2346 grid,
2347 &[],
2348 &[],
2349 mi_row,
2350 mi_col,
2351 n4,
2352 n4,
2353 mi_rows,
2354 mi_cols,
2355 side,
2356 side,
2357 side,
2358 crate::decode::ss_x(fctx),
2359 crate::decode::ss_y(fctx),
2360 side / 2,
2361 x,
2362 y,
2363 x / 2,
2364 y / 2,
2365 &refpix,
2366 Some(fctx.interp_filter.get()),
2367 frame_size,
2368 )
2369 .ok()?;
2370 let mut pred = [
2371 vec![0u16; side * side],
2372 vec![0u16; side * side / 4],
2373 vec![0u16; side * side / 4],
2374 ];
2375 for (i, r) in ref_planes.into_iter().enumerate() {
2376 let luma_plane = i == 0;
2377 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
2378 let s = if luma_plane { side } else { side / 2 };
2379 mc::predict(
2380 r.0,
2381 r.1,
2382 r.2,
2383 r.3,
2384 mv_to_q4(px, mv.1, luma_plane),
2385 mv_to_q4(py, mv.0, luma_plane),
2386 s,
2387 s,
2388 &mut pred[i],
2389 fctx,
2390 );
2391 }
2392 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
2393 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
2394 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
2395 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
2396}
2397
2398// Spec-shaped signature; bundling the operands would obscure the spec mapping.
2399#[allow(clippy::too_many_arguments)]
2400pub(super) fn code_square_inter(
2401 luma: &mut Plane,
2402 chroma: &mut [Plane; 2],
2403 (x, y): (usize, usize),
2404 side: usize,
2405 search: &Search,
2406 mode_bits: &[f64; 13],
2407 reference: &Picture,
2408 stack: &MvStack,
2409 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
2410 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
2411 // `reference_select`, and at the straddling call sites).
2412 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
2413 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
2414 // (`record_mi`, in the writer's own coding order) and this leaf's place in
2415 // it -- what the OBMC candidate's eligibility walk and neighbour plan
2416 // read, the same state the tile writer reads when it codes the leaf's
2417 // `motion_mode` symbol.
2418 grid: &MiGrid,
2419 (mi_row, mi_col): (usize, usize),
2420 (mi_rows, mi_cols): (usize, usize),
2421 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
2422 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
2423 refs: &[Option<&Picture>; 8],
2424 fctx: &crate::decode::FrameCtx,
2425) -> (BlockCoeffs, f64) {
2426 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
2427 // candidate at all -- `intra_cost` stays at infinity, so every
2428 // comparison below takes an inter candidate and the fallback arm at the
2429 // tail is unreachable. The planes hold what the caller snapshotted until
2430 // the winner commits: the intra trial used to commit here and be
2431 // overwritten by the inter commit, so skipping it changes no committed
2432 // sample, only work.
2433 let (intra_block, intra_cost) = if search.arf_leaf_intra {
2434 code_square(
2435 luma,
2436 chroma,
2437 (x, y),
2438 side,
2439 search,
2440 mode_bits,
2441 tx_select() && tx_select_inter(),
2442 None,
2443 false,
2444 fctx,
2445 )
2446 } else {
2447 arfmode_hit(0);
2448 (BlockCoeffs::default(), f64::INFINITY)
2449 };
2450 let luma_set = if side == 8 {
2451 TxbSet::Luma8Inter
2452 } else {
2453 TxbSet::Luma16Inter
2454 };
2455 let chroma_set = if side == 8 {
2456 TxbSet::Chroma4
2457 } else {
2458 TxbSet::Chroma8
2459 };
2460
2461 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
2462 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
2463 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
2464 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
2465 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
2466 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
2467
2468 let mv = stack.nearest_mv;
2469 let ref_luma = (
2470 &reference.y,
2471 reference.width,
2472 luma.true_width,
2473 luma.true_height,
2474 );
2475 let ref_u = (
2476 &reference.u,
2477 reference.width / 2,
2478 chroma[0].true_width,
2479 chroma[0].true_height,
2480 );
2481 let ref_v = (
2482 &reference.v,
2483 reference.width / 2,
2484 chroma[1].true_width,
2485 chroma[1].true_height,
2486 );
2487 let luma_trial = mc_trial(
2488 luma,
2489 x,
2490 y,
2491 side,
2492 mv,
2493 true,
2494 ref_luma.0,
2495 ref_luma.1,
2496 ref_luma.2,
2497 ref_luma.3,
2498 false,
2499 search.base_q_idx,
2500 search.deadzone,
2501 luma_set,
2502 fctx,
2503 );
2504 let u = mc_trial(
2505 &chroma[0],
2506 x / 2,
2507 y / 2,
2508 side / 2,
2509 mv,
2510 false,
2511 ref_u.0,
2512 ref_u.1,
2513 ref_u.2,
2514 ref_u.3,
2515 false,
2516 search.base_q_idx,
2517 search.deadzone,
2518 chroma_set,
2519 fctx,
2520 );
2521 let v = mc_trial(
2522 &chroma[1],
2523 x / 2,
2524 y / 2,
2525 side / 2,
2526 mv,
2527 false,
2528 ref_v.0,
2529 ref_v.1,
2530 ref_v.2,
2531 ref_v.3,
2532 false,
2533 search.base_q_idx,
2534 search.deadzone,
2535 chroma_set,
2536 fctx,
2537 );
2538 let skip = luma_trial.levels.iter().all(|&l| l == 0)
2539 && u.levels.iter().all(|&l| l == 0)
2540 && v.levels.iter().all(|&l| l == 0);
2541 let inter_cost = luma_trial.sse
2542 + u.sse
2543 + v.sse
2544 + search.lambda
2545 * (skip_bits(skip)
2546 + intra_inter_bits(true)
2547 + single_ref_bits
2548 + mode_bits_inter
2549 + if skip {
2550 0.0
2551 } else {
2552 luma_trial.bits + u.bits + v.bits
2553 });
2554
2555 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
2556 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
2557 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
2558 // scan's own coverage already reached as far) but a real gap at 4-mi
2559 // leaf geometry. r3 ported the extended scan and, while proving it a
2560 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
2561 // `mvstack.rs`), found and fixed a second bug the extended scan's
2562 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
2563 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
2564 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
2565 // regardless of whether it also casts a ref-frame-matching vote) --
2566 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
2567 // branches), which is what made 8-mi geometry a true no-op instead of
2568 // one that only held when every neighbour happened to be inter.
2569 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
2570 // only ever took the stack's NEARESTMV candidate or went intra, so a
2571 // 32x32 block splitting because its four quarters MOVE differently could
2572 // not code the movement it split for. Same candidate `search_inter_block`
2573 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
2574 // a vector the residual syntax can name -- at this leaf's own side.
2575 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
2576 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
2577 // re-price below can hand it back as the winner's own mode info.
2578 let nearest_info = InterInfo {
2579 ref1: None,
2580 mv1: (0, 0),
2581 ref_frame: crate::mvstack::LAST_FRAME,
2582 mode: InterMode::NearestMv,
2583 mv,
2584 ref_mv_idx: 0,
2585 };
2586 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
2587 // syntax, apart from its residual: the OBMC candidate re-prices the same
2588 // syntax against a different prediction, so both sides of that comparison
2589 // carry it.
2590 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
2591 // This leaf's own `NEWMV` vector, kept whether or not it won the
2592 // single-reference comparison: it seeds the compound half-new candidate
2593 // below, exactly as `search_inter_block` seeds its own from the searches
2594 // it already ran.
2595 let mut searched_new: Option<(i32, i32)> = None;
2596 // What that search cost, kept for the second reference's own early-out
2597 // below (`None` when this leaf ran no search at all).
2598 let mut searched_new_cost: Option<f64> = None;
2599 let source_block = luma.source_block(x, y, side);
2600 if leaf_new_mv() {
2601 let (seeds, seed_n) = mv_seeds(stack);
2602 let found = motion::search(
2603 ref_luma.0,
2604 ref_luma.1,
2605 ref_luma.2,
2606 ref_luma.3,
2607 &source_block,
2608 x,
2609 y,
2610 side,
2611 side,
2612 stack.pred_mv,
2613 &seeds[..seed_n],
2614 search.lambda,
2615 fctx,
2616 1,
2617 );
2618 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
2619 searched_new_cost = Some(found.cost);
2620 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
2621 if mv_residual.is_none() {
2622 // lane-newmv: a vector the writer cannot name never reaches RD.
2623 newmv_census_block(
2624 side,
2625 false,
2626 f64::INFINITY,
2627 best.0,
2628 new_mv,
2629 stack.nearest_mv,
2630 0.0,
2631 );
2632 }
2633 if let Some(mv_bits) = mv_residual {
2634 searched_new = Some(new_mv);
2635 // Same reuse as `search_inter_block`: a NEWMV equal to the
2636 // stack's NEARESTMV is the same three trials, already run above.
2637 let (luma_new, u_new, v_new) = if new_mv == mv {
2638 (luma_trial.clone(), u.clone(), v.clone())
2639 } else {
2640 (
2641 mc_trial(
2642 luma,
2643 x,
2644 y,
2645 side,
2646 new_mv,
2647 true,
2648 ref_luma.0,
2649 ref_luma.1,
2650 ref_luma.2,
2651 ref_luma.3,
2652 false,
2653 search.base_q_idx,
2654 search.deadzone,
2655 luma_set,
2656 fctx,
2657 ),
2658 mc_trial(
2659 &chroma[0],
2660 x / 2,
2661 y / 2,
2662 side / 2,
2663 new_mv,
2664 false,
2665 ref_u.0,
2666 ref_u.1,
2667 ref_u.2,
2668 ref_u.3,
2669 false,
2670 search.base_q_idx,
2671 search.deadzone,
2672 chroma_set,
2673 fctx,
2674 ),
2675 mc_trial(
2676 &chroma[1],
2677 x / 2,
2678 y / 2,
2679 side / 2,
2680 new_mv,
2681 false,
2682 ref_v.0,
2683 ref_v.1,
2684 ref_v.2,
2685 ref_v.3,
2686 false,
2687 search.base_q_idx,
2688 search.deadzone,
2689 chroma_set,
2690 fctx,
2691 ),
2692 )
2693 };
2694 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
2695 && u_new.levels.iter().all(|&l| l == 0)
2696 && v_new.levels.iter().all(|&l| l == 0);
2697 let drl_bits = if stack.entries.len() > 1 {
2698 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
2699 } else {
2700 0.0
2701 };
2702 let cost_new = luma_new.sse
2703 + u_new.sse
2704 + v_new.sse
2705 + search.lambda
2706 * (skip_bits(skip_new)
2707 + intra_inter_bits(true)
2708 + single_ref_bits
2709 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
2710 + drl_bits
2711 + mv_bits
2712 + mv_rate_surcharge(mv_bits)
2713 + if skip_new {
2714 0.0
2715 } else {
2716 luma_new.bits + u_new.bits + v_new.bits
2717 });
2718 newmv_census_block(
2719 side,
2720 true,
2721 cost_new,
2722 best.0,
2723 new_mv,
2724 stack.nearest_mv,
2725 mv_bits,
2726 );
2727 if cost_new < best.0 {
2728 single_syntax = intra_inter_bits(true)
2729 + single_ref_bits
2730 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
2731 + drl_bits
2732 + mv_bits;
2733 best = (
2734 cost_new,
2735 Some((
2736 luma_new,
2737 u_new,
2738 v_new,
2739 skip_new,
2740 InterInfo {
2741 ref1: None,
2742 mv1: (0, 0),
2743 ref_frame: crate::mvstack::LAST_FRAME,
2744 mode: InterMode::NewMv,
2745 mv: new_mv,
2746 ref_mv_idx: 0,
2747 },
2748 )),
2749 );
2750 }
2751 }
2752 }
2753
2754 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
2755 // `search_inter_block` prices for a whole 32x32 block:
2756 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
2757 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
2758 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
2759 // too. Priced with the same static-CDF approximation, plus the
2760 // compound-only syntax the writer emits.
2761 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
2762 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
2763 // per leaf, not once per pair); the single-reference candidates
2764 // above stay.
2765 arfmode_hit(2);
2766 }
2767 for (ref1, g, cstack) in compound
2768 .iter()
2769 .filter(|_| leaf_compound() && search.arf_leaf_compound)
2770 {
2771 let (ref1, g) = (*ref1, *g);
2772 // The whole `comp_mode` + reference-pair tree at the writer's own
2773 // contexts, for THIS pair (lane-ctx).
2774 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
2775 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
2776 let mode_bits_of =
2777 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
2778 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
2779 (
2780 cstack.nearest_mv,
2781 mode_bits_of(0),
2782 InterInfo {
2783 ref_frame: crate::mvstack::LAST_FRAME,
2784 mode: InterMode::NearestNearestMv,
2785 mv: cstack.nearest_mv.0,
2786 mv1: cstack.nearest_mv.1,
2787 ref1: Some(ref1),
2788 ref_mv_idx: 0,
2789 },
2790 ),
2791 (
2792 ((0, 0), (0, 0)),
2793 mode_bits_of(6),
2794 InterInfo {
2795 ref_frame: crate::mvstack::LAST_FRAME,
2796 mode: InterMode::GlobalGlobalMv,
2797 mv: (0, 0),
2798 mv1: (0, 0),
2799 ref1: Some(ref1),
2800 ref_mv_idx: 0,
2801 },
2802 ),
2803 ];
2804 // Every compound MV residual here is priced against compound stack
2805 // entry 0, which is what `assign_compound_mv` predicts from at
2806 // `ref_mv_idx = 0` -- so it is also what the second-reference search
2807 // below seeds from and rounds to, and no candidate it finds can then
2808 // fail `mv_residual_bits`.
2809 let cbase = cstack
2810 .entries
2811 .first()
2812 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
2813 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
2814 // it a leaf could only name a stack vector for the second half, and
2815 // screen capture showed the consequence: every leaf compound block
2816 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
2817 // extra-reference `NEWMV`, when this reference's own
2818 // `NEAREST_NEARESTMV` vector already prices `margin` times better
2819 // than the `LAST` search of this same leaf did -- one candidate
2820 // evaluation standing in for a whole search.
2821 let margin = leaf_second_new_margin();
2822 let mut second_new: Option<(i32, i32)> = None;
2823 if leaf_second_new_mv() {
2824 newmv_census_global(2);
2825 let skip = margin > 0.0
2826 && searched_new_cost.is_some_and(|last| {
2827 motion::cost_at(
2828 &g.y,
2829 g.width,
2830 luma.true_width,
2831 luma.true_height,
2832 &source_block,
2833 x,
2834 y,
2835 side,
2836 side,
2837 cstack.nearest_mv.1,
2838 cbase.1,
2839 search.lambda,
2840 fctx,
2841 ) * margin
2842 <= last
2843 });
2844 if skip {
2845 newmv_census_global(3);
2846 }
2847 if !skip {
2848 let mut seeds = [(0, 0); 4];
2849 let mut seed_n = 1;
2850 for e in cstack.entries.iter().take(3) {
2851 seeds[seed_n] = e.mv1;
2852 seed_n += 1;
2853 }
2854 let found = motion::search(
2855 &g.y,
2856 g.width,
2857 luma.true_width,
2858 luma.true_height,
2859 &source_block,
2860 x,
2861 y,
2862 side,
2863 side,
2864 cbase.1,
2865 &seeds[..seed_n],
2866 search.lambda,
2867 fctx,
2868 ref_distance(ref1),
2869 );
2870 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
2871 }
2872 }
2873 if let Some(new_mv) = searched_new
2874 && let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
2875 ccands.push((
2876 (new_mv, cstack.nearest_mv.1),
2877 mode_bits_of(3) + b0,
2878 InterInfo {
2879 ref_frame: crate::mvstack::LAST_FRAME,
2880 mode: InterMode::NewNearestMv,
2881 mv: new_mv,
2882 mv1: cstack.nearest_mv.1,
2883 ref1: Some(ref1),
2884 ref_mv_idx: 0,
2885 },
2886 ));
2887 }
2888 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
2889 // searches this leaf ran, each residual priced against `cbase`.
2890 if let Some(mv1) = second_new
2891 && let Some(b1) = mv_residual_bits(mv1, cbase.1) {
2892 ccands.push((
2893 (cstack.nearest_mv.0, mv1),
2894 mode_bits_of(2) + b1,
2895 InterInfo {
2896 ref_frame: crate::mvstack::LAST_FRAME,
2897 mode: InterMode::NearestNewMv,
2898 mv: cstack.nearest_mv.0,
2899 mv1,
2900 ref1: Some(ref1),
2901 ref_mv_idx: 0,
2902 },
2903 ));
2904 if let Some((new_mv, b0)) =
2905 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
2906 {
2907 ccands.push((
2908 (new_mv, mv1),
2909 mode_bits_of(7) + b0 + b1,
2910 InterInfo {
2911 ref_frame: crate::mvstack::LAST_FRAME,
2912 mode: InterMode::NewNewMv,
2913 mv: new_mv,
2914 mv1,
2915 ref1: Some(ref1),
2916 ref_mv_idx: 0,
2917 },
2918 ));
2919 }
2920 }
2921 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
2922 ccands.dedup_by_key(|c| c.0);
2923 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
2924 let g_u = (
2925 g.u.as_slice(),
2926 g.width / 2,
2927 chroma[0].true_width,
2928 chroma[0].true_height,
2929 );
2930 let g_v = (
2931 g.v.as_slice(),
2932 g.width / 2,
2933 chroma[1].true_width,
2934 chroma[1].true_height,
2935 );
2936 for (mvs, bits, info) in ccands {
2937 let luma_c = mc_trial_compound(
2938 luma,
2939 x,
2940 y,
2941 side,
2942 mvs,
2943 true,
2944 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
2945 g_luma,
2946 search.base_q_idx,
2947 search.deadzone,
2948 luma_set,
2949 fctx,
2950 );
2951 let u_c = mc_trial_compound(
2952 &chroma[0],
2953 x / 2,
2954 y / 2,
2955 side / 2,
2956 mvs,
2957 false,
2958 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
2959 g_u,
2960 search.base_q_idx,
2961 search.deadzone,
2962 chroma_set,
2963 fctx,
2964 );
2965 let v_c = mc_trial_compound(
2966 &chroma[1],
2967 x / 2,
2968 y / 2,
2969 side / 2,
2970 mvs,
2971 false,
2972 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
2973 g_v,
2974 search.base_q_idx,
2975 search.deadzone,
2976 chroma_set,
2977 fctx,
2978 );
2979 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
2980 && u_c.levels.iter().all(|&l| l == 0)
2981 && v_c.levels.iter().all(|&l| l == 0);
2982 let cost_c = luma_c.sse
2983 + u_c.sse
2984 + v_c.sse
2985 + search.lambda
2986 * (skip_bits(skip_c)
2987 + intra_inter_bits(true)
2988 + bits
2989 + if skip_c {
2990 0.0
2991 } else {
2992 luma_c.bits + u_c.bits + v_c.bits
2993 });
2994 if cost_c < best.0 {
2995 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
2996 }
2997 }
2998 }
2999
3000 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
3001 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
3002 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
3003 // the writer codes no symbol for one. The prediction is the decoder's own
3004 // plan and blend over the neighbours this leaf's `grid` already carries
3005 // (published by `record_mi` in the writer's coding order), so the
3006 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
3007 // offered this only at 32x32, which is not where libaom cashes its OBMC
3008 // gain.
3009 let mut motion_won = 0u8;
3010 let single = match &best.1 {
3011 None => Some(nearest_info),
3012 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
3013 Some(_) => None,
3014 };
3015 if let Some(info) = single.filter(|i| {
3016 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
3017 && i.ref_frame == crate::mvstack::LAST_FRAME
3018 }) {
3019 let planes = [
3020 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3021 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3022 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3023 ];
3024 // Which alphabet this block's writer will code the symbol against
3025 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
3026 // 3-symbol one only under `allow_warped_motion` and at least one warp
3027 // sample. Mirrored here so the candidates are priced against the
3028 // table the tile really narrows.
3029 let warp_alphabet = warp_on()
3030 && crate::decode::num_proj_ref(
3031 grid,
3032 mi_row,
3033 mi_col,
3034 side / 4,
3035 side / 4,
3036 mi_cols,
3037 mi_rows,
3038 info.ref_frame,
3039 fctx,
3040 ) >= 1;
3041 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
3042 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
3043 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side()
3044 && let Some(pred) = obmc_prediction(
3045 grid,
3046 (mi_row, mi_col),
3047 (mi_rows, mi_cols),
3048 (x, y),
3049 side,
3050 info.mv,
3051 refs,
3052 planes,
3053 (reference.width, reference.height),
3054 fctx,
3055 ) {
3056 candidates.push((1, pred));
3057 }
3058 if warp_alphabet
3059 && let Some(pred) = warp_prediction(
3060 grid,
3061 (mi_row, mi_col),
3062 (mi_rows, mi_cols),
3063 (x, y),
3064 side,
3065 info.mv,
3066 info.ref_frame,
3067 planes,
3068 fctx,
3069 ) {
3070 candidates.push((2, pred));
3071 }
3072 for (motion, pred) in candidates {
3073 let luma_o = luma.code_from_prediction(
3074 x,
3075 y,
3076 side,
3077 &pred[0],
3078 false,
3079 search.base_q_idx,
3080 search.deadzone,
3081 luma_set,
3082 );
3083 let u_o = chroma[0].code_from_prediction(
3084 x / 2,
3085 y / 2,
3086 side / 2,
3087 &pred[1],
3088 false,
3089 search.base_q_idx,
3090 search.deadzone,
3091 chroma_set,
3092 );
3093 let v_o = chroma[1].code_from_prediction(
3094 x / 2,
3095 y / 2,
3096 side / 2,
3097 &pred[2],
3098 false,
3099 search.base_q_idx,
3100 search.deadzone,
3101 chroma_set,
3102 );
3103 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
3104 && u_o.levels.iter().all(|&l| l == 0)
3105 && v_o.levels.iter().all(|&l| l == 0);
3106 let cost_o = luma_o.sse
3107 + u_o.sse
3108 + v_o.sse
3109 + search.lambda
3110 * (skip_bits(skip_o)
3111 + single_syntax
3112 + mm(motion)
3113 + if skip_o {
3114 0.0
3115 } else {
3116 luma_o.bits + u_o.bits + v_o.bits
3117 });
3118 // The incumbent pays the motion_mode symbol IT would code, so
3119 // both sides of the comparison carry that syntax.
3120 if cost_o < best.0 + search.lambda * mm(motion_won) {
3121 motion_won = motion;
3122 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
3123 }
3124 }
3125 }
3126
3127 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best
3128 && cost < intra_cost {
3129 // A compound winner commits the flat trial it was priced from:
3130 // `commit_inter_luma`'s var-tx trial set is single-reference
3131 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3132 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
3133 // predicting each half-side trial from BOTH references, verified
3134 // byte-identical to this when its split is disabled) and MEASURED
3135 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
3136 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
3137 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
3138 // compound block's residual is small enough that the four extra
3139 // per-unit txb_skip/eob symbols cost more ladder bytes than this
3140 // encoder's static-CDF estimate prices them at, so the local RD
3141 // win does not convert. lane-av1txbits REBUILT it on top of a
3142 // search that prices against the tables the frame is really
3143 // written with (`tile::arm_pricing_cdfs`, the estimate error on
3144 // these very blocks measured down from +31% to +3%) and measured
3145 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
3146 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
3147 // same build without it. The static-CDF estimate was NOT what
3148 // held the compound var-tx trial back. The flat trial stays.
3149 // An OBMC winner commits the flat trial too: `commit_inter_luma`
3150 // re-predicts each var-tx unit by plain translation, which is not
3151 // the prediction this candidate was priced from.
3152 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
3153 // 0.05 (both rejections above were measured at 0.1, the weight
3154 // the lambda lane showed was 2x too heavy): a compound winner is
3155 // offered the same var-tx split, its units predicted from BOTH
3156 // references (`mc_trial_compound`). RE-MEASURED native: film
3157 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
3158 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
3159 // one row 0.2 down, two flat, short of the two-down-one-flat keep
3160 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
3161 // rather than change the default on a single 0.2 row. It fires:
3162 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
3163 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
3164 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
3165 // 1.3/1.2 down there, which is where the upgrade path is if this
3166 // is picked up again.
3167 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3168 refs[r as usize].map(|g| {
3169 (
3170 info.mv1,
3171 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3172 )
3173 })
3174 });
3175 let (levels, tx_depth, dcost, luma_tx_types) =
3176 if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
3177 luma.commit(x, y, side, &luma_new);
3178 (luma_new.levels.clone(), 0, 0.0, Vec::new())
3179 } else {
3180 commit_inter_luma(
3181 luma,
3182 (x, y),
3183 side,
3184 info.mv,
3185 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3186 search,
3187 &luma_new,
3188 skip_new,
3189 second,
3190 fctx,
3191 )
3192 };
3193 // lane-txrd: chroma follows the luma type the search just chose.
3194 let [u_new, v_new] = match luma_tx_types.first().copied() {
3195 Some(t) => recode_inter_chroma(
3196 chroma,
3197 (x, y),
3198 side,
3199 info.mv,
3200 [
3201 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3202 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3203 ],
3204 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3205 refs[r as usize].map(|g| {
3206 (
3207 info.mv1,
3208 [
3209 (
3210 g.u.as_slice(),
3211 g.width / 2,
3212 chroma[0].true_width,
3213 chroma[0].true_height,
3214 ),
3215 (
3216 g.v.as_slice(),
3217 g.width / 2,
3218 chroma[1].true_width,
3219 chroma[1].true_height,
3220 ),
3221 ],
3222 )
3223 })
3224 }),
3225 search,
3226 chroma_set,
3227 t,
3228 fctx,
3229 )
3230 .unwrap_or([u_new, v_new]),
3231 None => [u_new, v_new],
3232 };
3233 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3234 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3235 return (
3236 BlockCoeffs {
3237 angle_delta_y: 0,
3238 cfl_alphas: None,
3239 filter_intra: None,
3240 luma: coeffs(&levels, side),
3241 u: coeffs(&u_new.levels, side / 2),
3242 v: coeffs(&v_new.levels, side / 2),
3243 mode: DC_PRED,
3244 uv_mode: DC_PRED,
3245 skip: skip_new,
3246 eight: None,
3247 dv: None,
3248 palette: None,
3249 palette_uv: None,
3250 tx_depth,
3251 luma_tx_types,
3252 inter: Some(info),
3253 motion_mode: motion_won,
3254 },
3255 cost + dcost,
3256 );
3257 }
3258
3259 census_add(8, 1);
3260 if skip {
3261 census_add(10, 1);
3262 }
3263 if inter_cost >= intra_cost {
3264 census_add(9, 1);
3265 }
3266 if inter_cost < intra_cost {
3267 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
3268 luma,
3269 (x, y),
3270 side,
3271 mv,
3272 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3273 search,
3274 &luma_trial,
3275 skip,
3276 None,
3277 fctx,
3278 );
3279 // lane-txrd: chroma follows the luma type (this tail's block is
3280 // single-reference `NEARESTMV`, so no compound second half).
3281 let [u, v] = match luma_tx_types.first().copied() {
3282 Some(t) => recode_inter_chroma(
3283 chroma,
3284 (x, y),
3285 side,
3286 mv,
3287 [
3288 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3289 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3290 ],
3291 None,
3292 search,
3293 chroma_set,
3294 t,
3295 fctx,
3296 )
3297 .unwrap_or([u, v]),
3298 None => [u, v],
3299 };
3300 chroma[0].commit(x / 2, y / 2, side / 2, &u);
3301 chroma[1].commit(x / 2, y / 2, side / 2, &v);
3302 (
3303 BlockCoeffs {
3304 luma_tx_types,
3305 angle_delta_y: 0,
3306 cfl_alphas: None,
3307 filter_intra: None,
3308 luma: coeffs(&levels, side),
3309 u: coeffs(&u.levels, side / 2),
3310 v: coeffs(&v.levels, side / 2),
3311 mode: DC_PRED,
3312 uv_mode: DC_PRED,
3313 skip,
3314 eight: None,
3315 dv: None,
3316 palette: None,
3317 palette_uv: None,
3318 tx_depth,
3319 motion_mode: 0,
3320 inter: Some(InterInfo {
3321 ref1: None,
3322 mv1: (0, 0),
3323 ref_frame: crate::mvstack::LAST_FRAME,
3324 mode: InterMode::NearestMv,
3325 mv,
3326 ref_mv_idx: 0,
3327 }),
3328 },
3329 inter_cost + dcost,
3330 )
3331 } else {
3332 (intra_block, intra_cost)
3333 }
3334}