forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

frame.rs2871 lines, 136.2 KiBHistoryRawDownload
1use super::*;
2
3/// lane-av1tpl: the strength `k` of the temporal lambda weighting
4/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
5/// is what every measurement before this lane was taken on. Swept by
6/// `EC_AV1_TPL=<k>`.
7///
8/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
9/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
10/// baseline exactly, which is the control the rest of the table is read
11/// against:
12///
13/// | k | film 1080p | film 2160p | screen |
14/// |---|---|---|---|
15/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
16/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
17/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
18/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
19/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
20///
21/// 0.5 is the only arm that is at least flat on every row and down on five of
22/// the six columns, so it ships as the default. The lookahead pass that feeds
23/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
24pub(super) const TPL_STRENGTH: f64 = 0.5;
25
26/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
27/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
28/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
29/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
30///
31/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
32/// nothing to vary the quantizer BY and codes no delta syntax at all.
33pub(super) fn deltaq_res_log2() -> Option<u8> {
34 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
35 u8::MAX => {}
36 4 => return None,
37 r => return Some(r),
38 }
39 match crate::envflags::var("EC_AV1_DELTAQ")
40 .ok()
41 .as_deref()
42 .map(str::trim)
43 {
44 Some("0") => None,
45 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
46 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
47 }
48}
49
50/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
51/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
52/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
53/// speed presets take, because the streams every other test pins move under
54/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
55pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
56
57/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
58#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
59pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
60 DELTAQ_OVERRIDE.store(
61 res_log2.unwrap_or(u8::MAX),
62 std::sync::atomic::Ordering::Relaxed,
63 );
64}
65
66/// How much of the derived qindex step is actually taken
67/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
68pub(super) fn deltaq_k() -> f64 {
69 crate::envflags::var("EC_AV1_DELTAQ_K")
70 .ok()
71 .and_then(|v| v.trim().parse::<f64>().ok())
72 .filter(|k| k.is_finite() && *k >= 0.0)
73 .unwrap_or(1.0)
74}
75
76/// The largest qindex the map may move a superblock by, either way
77/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
78/// deltaq around a quarter of the base qindex).
79pub(super) fn deltaq_clamp() -> i32 {
80 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
81 .ok()
82 .and_then(|v| v.trim().parse::<i32>().ok())
83 .filter(|c| (0..=63).contains(c))
84 .unwrap_or(16)
85}
86
87/// The qindex a lambda factor `f` asks for, derived rather than fitted.
88///
89/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
90/// square of the quantizer step (`encode_inter_frame`'s own
91/// `lambda = .. * step * step`), so the step this superblock wants is
92/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
93/// step ratio is inverted through the table itself -- the index whose `ac_q`
94/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
95/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
96/// bounds it, and the answer is snapped onto the `res` grid so that every
97/// superblock's qindex is congruent to `base` and the coded delta is a whole
98/// number of steps.
99pub(super) fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
100 let base_ac = f64::from(ac_q(8, i32::from(base)));
101 let target = base_ac * f.max(1e-6).sqrt();
102 let exact = (1..=255)
103 .min_by(|&a, &b| {
104 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
105 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
106 })
107 .expect("the qindex range is not empty")
108 - i32::from(base);
109 let want = (exact as f64 * k).round() as i32;
110 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
111 // and need not be a whole number of steps, and clamping afterwards would
112 // hand back a qindex that is not congruent to `base`.
113 let max_steps = clamp / res;
114 let steps = (want as f64 / f64::from(res)).round() as i32;
115 let delta = steps.clamp(-max_steps, max_steps) * res;
116 (i32::from(base) + delta).clamp(1, 255) as u8
117}
118
119/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
120/// objective would, from the SAME tpl dependence ratio our own map already
121/// carries (`EC_AV1_DQ_TPL=1`).
122///
123/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
124/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
125/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
126/// same expression at frame scope) by it, and asks
127/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
128/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
129/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
130/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
131/// libaom reads `r0`. The offset is clamped to libaom's own
132/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
133/// twice the +-16 qindex [`deltaq_for_factor`] allows.
134///
135/// Two things differ from [`deltaq_for_factor`] and both are the point of the
136/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
137/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
138/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
139/// much stronger for the same map. `strength` scales the offset.
140pub(super) fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
141 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
142 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
143 let exact = (1..=255)
144 .min_by(|&a, &b| {
145 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
146 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
147 })
148 .expect("the qindex range is not empty")
149 - i32::from(base);
150 let want = exact as f64 * strength;
151 // Snapped onto the `res` grid first, so the coded delta is a whole number
152 // of steps, then bounded by libaom's own `res * 9 - 1`.
153 let max_steps = (res * 9 - 1) / res;
154 let steps = (want / f64::from(res)).round() as i32;
155 let delta = steps.clamp(-max_steps, max_steps) * res;
156 (i32::from(base) + delta).clamp(1, 255) as u8
157}
158
159/// The frame-level `r0` libaom's objective divides by: the log-mean of
160/// `1 + r` over the frame's cells, minus 1.
161pub(super) fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
162 if ratio.is_empty() {
163 return 0.0;
164 }
165 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
166 m.exp() - 1.0
167}
168
169/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
170/// [`deltaq_for_factor`] derivation.
171///
172/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
173/// the strength (default 1.0 = libaom's own offset when the flag armed it);
174/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
175pub(super) fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
176 let m = dq_level_k()[level as usize];
177 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
178 .ok()
179 .and_then(|v| v.trim().parse::<f64>().ok())
180 .filter(|k| k.is_finite() && *k >= 0.0);
181 let base = match crate::envflags::var("EC_AV1_DQ_TPL")
182 .ok()
183 .as_deref()
184 .map(str::trim)
185 {
186 Some("0") => return None,
187 Some(_) => Some(env_k.unwrap_or(1.0)),
188 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
189 };
190 base.map(|k| k * m).filter(|k| *k > 0.0)
191}
192
193/// lane-arfq: which pyramid level the frame asking for a
194/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
195/// codes no `delta_q` syntax at all (the whole lever lives in
196/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
197/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub(crate) enum DqLevel {
200 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
201 /// group predicts from (directly or through the mid level).
202 TopArf = 0,
203 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
204 MidArf = 1,
205 /// A shown leaf -- and every frame of the flat, non-pyramid path.
206 Leaf = 2,
207}
208
209/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
210/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
211/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
212/// no `delta_q` (see [`DqLevel`]).
213pub(super) fn dq_level_k() -> [f64; 3] {
214 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
215}
216
217/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
218/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
219pub(super) fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
220 let mut k = crate::speed::DQ_LEVEL_K;
221 if let Some(spec) = spec {
222 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
223 if let Some(v) = field
224 .trim()
225 .parse::<f64>()
226 .ok()
227 .filter(|v: &f64| v.is_finite() && *v >= 0.0)
228 {
229 *slot = v;
230 }
231 }
232 }
233 k
234}
235
236/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
237/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
238/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
239/// the same tpl map -- and which of the two the frame actually coded.
240pub(super) fn dq_census() -> bool {
241 crate::envflags::var("EC_AV1_DQ_CENSUS")
242 .ok()
243 .as_deref()
244 .map(str::trim)
245 == Some("1")
246}
247
248/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
249pub(super) fn dq_summary(offsets: &[i32]) -> String {
250 let n = offsets.len().max(1);
251 let (lo, hi) = offsets
252 .iter()
253 .fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
254 let nz = offsets.iter().filter(|&&o| o != 0).count();
255 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
256 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
257 let mut levels: Vec<i32> = offsets.to_vec();
258 levels.sort_unstable();
259 levels.dedup();
260 format!(
261 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
262 offsets.len(),
263 levels.len()
264 )
265}
266
267/// How many DISTINCT per-superblock quantizer levels the last inter frame's
268/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
269/// (class `gate-blind-to-feature`: every exactness assert below passes on a
270/// grid that is one flat value, i.e. on no delta_q at all). Process-global
271/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
272/// keeps the LARGEST count seen since the last read.
273pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
274
275/// [`DELTAQ_LEVELS`], reset to 0.
276#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
277pub(crate) fn take_deltaq_levels() -> usize {
278 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
279}
280
281/// This superblock's search state: the quantizer it is coded at, and the
282/// lambda that quantizer implies. RD lambda goes as the square of the step,
283/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
284/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
285/// before lane-deltaq).
286pub(super) fn sb_q_search<'m>(
287 sb_q: &[u8],
288 sb_cols: usize,
289 base_q_idx: u8,
290 (sb_r, sb_c): (usize, usize),
291 base: Search<'m>,
292) -> Search<'m> {
293 let q = sb_q[sb_r * sb_cols + sb_c];
294 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
295 Search {
296 base_q_idx: q,
297 lambda: base.lambda * ratio * ratio,
298 ..base
299 }
300}
301
302pub(super) fn tpl_strength() -> f64 {
303 std::env::var("EC_AV1_TPL")
304 .ok()
305 .and_then(|v| v.parse::<f64>().ok())
306 .filter(|k| k.is_finite() && *k >= 0.0)
307 .unwrap_or(TPL_STRENGTH)
308}
309
310/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
311/// the frame being coded. 1 turns the weighting off; 2 is the shipped
312/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
313/// [`tpl_propagating`], which is the map that can actually use them and is
314/// the default since lane-av1tpl3, so the default window is 8. Swept by
315/// `EC_AV1_TPL_D=<d>`.
316///
317/// The streaming facade holds `depth - 1` pictures back so it feeds
318/// `encode_inter_frame` the same window `encode_sequence` does; both read
319/// THIS function, so the two paths cannot disagree about the window.
320pub(crate) const TPL_DEPTH: usize = 8;
321
322/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
323/// 0.5 is libaom's own square-root compression of its dependence ratio.
324pub(super) const TPL_POWER: f64 = 0.5;
325
326/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
327/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
328///
329/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
330/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
331/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
332///
333/// | k | D | p | film 1080p | film 2160p | screen |
334/// |---|---|---|---|---|---|
335/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
336/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
337/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
338/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
339/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
340/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
341/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
342/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
343/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
344/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
345/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
346/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
347///
348/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
349/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
350/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
351/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
352/// 0.1..0.4 UP on film 2160p, so it shipped off.
353///
354/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
355/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
356/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
357/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
358/// wherever the window leans on a flat bar, which is exactly where coding is
359/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
360/// (libaom's own granularity) puts a busy cell's denominator next to the flat
361/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
362/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
363/// the same native gate (baseline = the shipped one-frame map):
364///
365/// | arm | film 1080p | film 2160p | screen |
366/// |---|---|---|---|
367/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
368/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
369/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
370/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
371/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
372/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
373/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
374/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
375/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
376/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
377///
378/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
379/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
380/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
381/// floor is a real effect on the ratio and never a win once the aggregation
382/// is in -- the aggregation is the same fix, done where libaom does it.
383pub(super) fn tpl_propagating() -> bool {
384 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
385}
386
387pub(crate) fn tpl_depth() -> usize {
388 std::env::var("EC_AV1_TPL_D")
389 .ok()
390 .and_then(|v| v.parse::<usize>().ok())
391 .filter(|d| *d >= 1)
392 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
393 .max(1)
394}
395
396/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
397/// process, so the gate can price it against the encode it rides on.
398pub(super) static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
399
400/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
401/// the winning displacement and its SAD.
402///
403/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
404/// the left/above winners, first-best tie-break. Built once on the frame's
405/// own thread and read-only afterwards, so it cannot make a tile's bytes
406/// depend on the thread count.
407pub(super) fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> {
408 let (cells_x, cells_y) = (width / 16, height / 16);
409 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
410 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
411 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
412 return u32::MAX;
413 }
414 let (sx, sy) = (sx as usize, sy as usize);
415 let mut sum = 0u32;
416 for r in 0..16 {
417 let a = &next[(by + r) * width + bx..][..16];
418 let b = &cur[(sy + r) * width + sx..][..16];
419 sum += a
420 .iter()
421 .zip(b)
422 .map(|(&p, &q)| u32::from(p.abs_diff(q)))
423 .sum::<u32>();
424 }
425 sum
426 };
427 let mut out = Vec::with_capacity(cells_x * cells_y);
428 let mut above = vec![(0i32, 0i32); cells_x];
429 for cy in 0..cells_y {
430 let mut left = (0i32, 0i32);
431 // Index loop: `above` is read per column beside the block origin; an iterator would obscure it.
432 #[allow(clippy::needless_range_loop)]
433 for cx in 0..cells_x {
434 let (bx, by) = (cx * 16, cy * 16);
435 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
436 for cand in [left, above[cx]] {
437 if cand != (0, 0) {
438 let s = sad(bx, by, cand);
439 if s < best.0 {
440 best = (s, cand);
441 }
442 }
443 }
444 for step in [8i32, 4, 2, 1] {
445 let centre = best.1;
446 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
447 let mv = (centre.0 + dx, centre.1 + dy);
448 if mv.0.abs() > 32 || mv.1.abs() > 32 {
449 continue;
450 }
451 let s = sad(bx, by, mv);
452 if s < best.0 {
453 best = (s, mv);
454 }
455 }
456 }
457 left = best.1;
458 above[cx] = best.1;
459 out.push((best.1, best.0));
460 }
461 }
462 out
463}
464
465/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
466/// transform: here, the mean absolute deviation of the cell from its own DC.
467/// It is the denominator every propagated cost is read against, so only its
468/// SHAPE across the frame matters, not its scale.
469pub(super) fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
470 let (cells_x, cells_y) = (width / 16, height / 16);
471 let mut out = Vec::with_capacity(cells_x * cells_y);
472 for cy in 0..cells_y {
473 for cx in 0..cells_x {
474 let (bx, by) = (cx * 16, cy * 16);
475 let mut sum = 0u32;
476 for r in 0..16 {
477 sum += frame[(by + r) * width + bx..][..16]
478 .iter()
479 .map(|&p| u32::from(p))
480 .sum::<u32>();
481 }
482 let dc = ((sum + 128) / 256) as u8;
483 let mut cost = 0u32;
484 for r in 0..16 {
485 cost += frame[(by + r) * width + bx..][..16]
486 .iter()
487 .map(|&p| u32::from(p.abs_diff(dc)))
488 .sum::<u32>();
489 }
490 out.push(cost);
491 }
492 }
493 out
494}
495
496/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
497/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
498/// splats its own area, at its winning displacement, onto the (at most four)
499/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
500pub(super) fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
501 let start = std::time::Instant::now();
502 let (cells_x, cells_y) = (width / 16, height / 16);
503 let pass = tpl_coarse_pass(cur, next, width, height);
504 let mut area = vec![0.0f64; cells_x * cells_y];
505 for cy in 0..cells_y {
506 for cx in 0..cells_x {
507 let (mv, _) = pass[cy * cells_x + cx];
508 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
509 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
510 for ci in x0 / 16..=x0.div_ceil(16).min(cells_x - 1) {
511 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
512 for ri in y0 / 16..=y0.div_ceil(16).min(cells_y - 1) {
513 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
514 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
515 }
516 }
517 }
518 }
519 TPL_NANOS.fetch_add(
520 start.elapsed().as_nanos() as u64,
521 std::sync::atomic::Ordering::Relaxed,
522 );
523 area
524}
525
526/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
527/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
528/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
529/// Decreasing in referenced-ness (a block the next frame leans on is coded
530/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
531/// total lambda scale is only redistributed, never moved -- a global move is
532/// the thing lane-av1lambda already measured inert.
533pub(super) fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
534 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
535 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
536 let mut out = Vec::with_capacity(sb_cols * sb_rows);
537 for sr in 0..sb_rows {
538 for sc in 0..sb_cols {
539 let mut sum = 0.0;
540 for r in 0..4 {
541 for c in 0..4 {
542 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
543 }
544 }
545 let w_rel = sum / 16.0 / mean;
546 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
547 }
548 }
549 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
550 let mut hist = [0usize; 8];
551 for w in map {
552 hist[((w / mean * 2.0) as usize).min(7)] += 1;
553 }
554 let (lo, hi) = out
555 .iter()
556 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
557 eprintln!(
558 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
559 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
560 map.len(),
561 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
562 );
563 }
564 out
565}
566
567/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
568/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
569/// much of the WHOLE lookahead window leans on that cell.
570///
571/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
572/// coarse pass gives a displacement and an inter cost; a cell's own
573/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
574/// cell well saves the frames that predict from it -- and it is splatted,
575/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
576/// displacement lands on. Walking `f` from the far end of the window back to
577/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
578/// area map could not do at all.
579///
580/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
581/// factor over the frame is exactly 1: a cell the window leans on is coded
582/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
583/// scale only moves around, never up or down -- a global move is what
584/// lane-av1lambda already measured inert.
585/// Returns the per-cell lambda factors AND the per-cell dependence ratio
586/// `mc_dep / intra` they were derived from -- the second half is what
587/// [`deltaq_libaom`] needs, since the factor alone has been through a
588/// mean normalisation the raw ratio cannot be recovered across.
589pub(super) fn tpl_lambda_factors(
590 frames: &[&[u8]],
591 width: usize,
592 height: usize,
593 k: f64,
594) -> (Vec<f64>, Vec<f64>) {
595 let start = std::time::Instant::now();
596 let (cells_x, cells_y) = (width / 16, height / 16);
597 let cells = cells_x * cells_y;
598 let levels = frames.len();
599 let intra: Vec<Vec<u32>> = frames
600 .iter()
601 .map(|f| tpl_intra_costs(f, width, height))
602 .collect();
603 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
604 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
605 .collect();
606 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
607 for f in (1..levels).rev() {
608 for cy in 0..cells_y {
609 for cx in 0..cells_x {
610 let ci = cy * cells_x + cx;
611 let (mv, inter) = passes[f - 1][ci];
612 let saved = f64::from(intra[f][ci].saturating_sub(inter));
613 let propagate = saved + mc_dep[f][ci];
614 if propagate <= 0.0 {
615 continue;
616 }
617 // The 16x16 window of the PREVIOUS frame this cell predicted
618 // from, spread over the cells it overlaps.
619 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
620 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
621 for rc in x0 / 16..=x0.div_ceil(16).min(cells_x - 1) {
622 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
623 for rr in y0 / 16..=y0.div_ceil(16).min(cells_y - 1) {
624 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
625 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
626 }
627 }
628 }
629 }
630 }
631 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
632 // tail (a nearly flat cell the window leans on has a tiny denominator),
633 // and at p = 1 that tail slams into the clamp. libaom reads its own
634 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
635 // sweeps the exponent, 1 being the raw ratio.
636 let power = std::env::var("EC_AV1_TPL_P")
637 .ok()
638 .and_then(|v| v.parse::<f64>().ok())
639 .filter(|p| p.is_finite() && *p > 0.0)
640 .unwrap_or(TPL_POWER);
641 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
642 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
643 // `0` to take either back out); `FLOOR` defaults to off.
644 //
645 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
646 // frame's own mean intra cost. A cell of flat content has a near-zero
647 // MAD, so its ratio explodes exactly where coding is cheap.
648 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
649 // and mc_dep are summed over the 64x64 superblock first -- libaom's
650 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
651 // per-16x16 numbers), which is also what makes the ratio survive one
652 // flat cell next to a busy one.
653 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
654 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
655 // harder than the `p` exponent alone can.
656 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
657 .ok()
658 .and_then(|v| v.parse::<f64>().ok())
659 .filter(|f| f.is_finite() && *f >= 0.0)
660 .unwrap_or(0.0);
661 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
662 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
663 let intra_mean = intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
664 let floor = floor_frac * intra_mean;
665 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
666 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
667 // every cell under it. The edge groups are partial and summed as they are.
668 let ratio: Vec<f64> = if sb_agg {
669 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
670 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
671 for cy in 0..cells_y {
672 for cx in 0..cells_x {
673 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
674 e.0 += mc_dep[0][cy * cells_x + cx];
675 e.1 += denom(cy * cells_x + cx);
676 }
677 }
678 (0..cells)
679 .map(|c| {
680 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
681 dep / den.max(1.0)
682 })
683 .collect()
684 } else {
685 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
686 };
687 let mut out: Vec<f64> = ratio
688 .iter()
689 .map(|&r| {
690 let r = if log_beta { (1.0 + r).log2() } else { r };
691 (1.0 + k * r).powf(-power)
692 })
693 .collect();
694 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
695 for f in &mut out {
696 *f = (*f / mean).clamp(0.25, 4.0);
697 }
698 TPL_NANOS.fetch_add(
699 start.elapsed().as_nanos() as u64,
700 std::sync::atomic::Ordering::Relaxed,
701 );
702 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
703 let mut hist = [0usize; 8];
704 for &f in &out {
705 hist[((f * 4.0) as usize).min(7)] += 1;
706 }
707 let (lo, hi) = out
708 .iter()
709 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
710 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
711 eprintln!(
712 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
713 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
714 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
715 );
716 }
717 (out, ratio)
718}
719
720/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
721/// references name, which slot it refreshes, whether it is shown when it is
722/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
723/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
724/// 0/2 alternation, every frame shown, every reference in the past).
725///
726/// The sign bias is carried rather than derived here because only the caller
727/// knows what order hint each slot holds; it is armed onto the tile writer
728/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
729/// the writer scans the same stacks the decoder will.
730#[derive(Debug, Clone, Copy)]
731pub(crate) struct PyramidFrame {
732 /// The slot `LAST_FRAME` (and every reference this encoder does not name
733 /// apart) reads.
734 pub last_slot: u8,
735 /// The single slot `refresh_frame_flags` sets.
736 pub self_slot: u8,
737 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
738 /// pyramid, which is what makes `sign_bias`'s last entry true.
739 pub altref_slot: u8,
740 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
741 /// picture (the leaf chain alternates its refresh between two slots, so
742 /// the frame before `LAST` is still intact). `None` leaves
743 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
744 /// wrote before, and the caller then passes no `last2` picture either.
745 pub last2_slot: Option<u8>,
746 /// `show_frame`: false for a hidden frame, output later by a
747 /// `show_existing_frame` header.
748 pub show_frame: bool,
749 /// lane-arfq: which level's `delta_q` strength this frame reads
750 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
751 /// one share `Level::Arf` and differ only by their q offset.
752 pub dq_level: DqLevel,
753 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
754 pub sign_bias: crate::mvstack::SignBiasTable,
755}
756
757/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
758/// `temporal_filter` in the small: every 16x16 luma block of `src` is
759/// motion-compensated from each picture of `window` (the group's own display
760/// neighbours, nearest first) and averaged in with weight
761/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
762/// nothing and one that matches well cancels the grain the block's residual
763/// would otherwise have to code.
764///
765/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
766/// rides the luma block's own vector (halved), which is what libaom does at
767/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
768/// grid tiles it exactly.
769///
770/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
771/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
772/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
773/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
774/// quality the ARF is coded at, so the substitution itself costs little.
775// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
776// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
777pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
778 const SIDE: usize = 16;
779 let neighbours: Vec<&Picture> = window
780 .iter()
781 .filter(|p| p.width == src.width && p.height == src.height)
782 .collect();
783 if neighbours.is_empty() || strength <= 0.0 {
784 return src.clone();
785 }
786 let mut out = src.clone();
787 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
788 // `None` when the displaced block leaves the picture.
789 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
790 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
791 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
792 return None;
793 }
794 let (sy, sx) = (sy as usize, sx as usize);
795 let mut acc = 0u64;
796 for row in 0..SIDE {
797 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
798 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
799 acc += c
800 .iter()
801 .zip(p)
802 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
803 .sum::<u64>();
804 }
805 Some((acc, (sy, sx)))
806 };
807 // The log-step diamond `arf_pred_census` priced this with.
808 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
809 let mut best = sad(r, bx, by, (0, 0))?;
810 let mut centre = (0isize, 0isize);
811 let mut step = 16isize;
812 while step >= 1 {
813 let from = centre;
814 for (dy, dx) in [
815 (-1, -1),
816 (-1, 0),
817 (-1, 1),
818 (0, -1),
819 (0, 1),
820 (1, -1),
821 (1, 0),
822 (1, 1),
823 ] {
824 let mv = (from.0 + dy * step, from.1 + dx * step);
825 if let Some(s) = sad(r, bx, by, mv)
826 && s.0 < best.0 {
827 best = s;
828 centre = mv;
829 }
830 }
831 step /= 2;
832 }
833 Some(best.1)
834 };
835 let (cw, ch) = (src.width / 2, src.height / 2);
836 for by in (0..src.height).step_by(SIDE) {
837 for bx in (0..src.width).step_by(SIDE) {
838 if by + SIDE > src.height || bx + SIDE > src.width {
839 continue;
840 }
841 let mut y_acc = vec![0f64; SIDE * SIDE];
842 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
843 let mut wsum = 1.0f64;
844 // Chroma keeps its OWN weight sum: an edge block whose halved
845 // vector leaves the chroma plane contributes to luma only, and
846 // dividing chroma by the luma sum would darken it (class
847 // `metric blind to a plane`, on the encoder side).
848 let mut cwsum = 1.0f64;
849 for row in 0..SIDE {
850 for col in 0..SIDE {
851 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
852 }
853 }
854 for row in 0..SIDE / 2 {
855 for col in 0..SIDE / 2 {
856 let i = (by / 2 + row) * cw + bx / 2 + col;
857 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
858 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
859 }
860 }
861 for r in &neighbours {
862 let Some((sy, sx)) = search(r, bx, by) else {
863 continue;
864 };
865 let mut sse = 0f64;
866 for row in 0..SIDE {
867 for col in 0..SIDE {
868 let d = f64::from(src.y[(by + row) * src.width + bx + col])
869 - f64::from(r.y[(sy + row) * r.width + sx + col]);
870 sse += d * d;
871 }
872 }
873 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
874 for row in 0..SIDE {
875 for col in 0..SIDE {
876 y_acc[row * SIDE + col] +=
877 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
878 }
879 }
880 // Chroma reads the luma vector halved; a block on the picture
881 // edge whose halved vector would leave the chroma plane is
882 // left to luma alone rather than clamped to a different
883 // displacement than the luma it must stay registered with.
884 let (cy, cx) = (sy / 2, sx / 2);
885 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
886 for row in 0..SIDE / 2 {
887 for col in 0..SIDE / 2 {
888 let i = (cy + row) * cw + cx + col;
889 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
890 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
891 }
892 }
893 cwsum += w;
894 }
895 wsum += w;
896 }
897 for row in 0..SIDE {
898 for col in 0..SIDE {
899 out.y[(by + row) * src.width + bx + col] =
900 (y_acc[row * SIDE + col] / wsum).round() as u16;
901 }
902 }
903 for row in 0..SIDE / 2 {
904 for col in 0..SIDE / 2 {
905 let i = (by / 2 + row) * cw + bx / 2 + col;
906 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
907 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
908 }
909 }
910 }
911 }
912 out
913}
914
915/// Encodes one picture as an inter frame predicting from `reference`'s
916/// reconstruction, which the caller decoded (or, for the frame right after
917/// the key frame, is the key frame's own reconstruction).
918// Spec-shaped signature; bundling the operands would obscure the spec mapping.
919#[allow(clippy::too_many_arguments)]
920pub(crate) fn encode_inter_frame(
921 picture: &Picture,
922 reference: &Picture,
923 base_q_idx: u8,
924 deadzone: f64,
925 order_hint: u32,
926 // The order hint each of the seven `ref_frame_idx` entries names, which a
927 // decoder reads out of its own reference state -- only spec 5.9.22's
928 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
929 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
930 // callers that follow this crate's own flat slot plan.
931 order_hints: [u32; 7],
932 render: (usize, usize),
933 // The tables this frame's writer starts from: what the previous frame
934 // stored into the slot this one's `primary_ref_frame` names. `None`
935 // starts from the defaults, which is right only for the frame straight
936 // after a key frame.
937 start_cdfs: Option<&crate::cdf_state::Cdfs>,
938 // The key frame's own (padded) reconstruction, which every frame of the
939 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
940 // with `LAST_FRAME` alone, exactly as before.
941 golden: Option<&Picture>,
942 // The frame two back, held in the slot this frame is about to refresh
943 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
944 // inter frames of a GOP, where the frame two back IS the key frame.
945 altref: Option<&Picture>,
946 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
947 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
948 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
949 // take. `None` (every caller but the pyramid leaves) codes the frame
950 // with the reference set unchanged.
951 last2: Option<&Picture>,
952 fctx: &crate::decode::FrameCtx,
953 // Where this frame sits in the coding-order pyramid; `None` is the flat
954 // one-shown-frame-per-picture stream this encoder wrote before.
955 pyramid: Option<PyramidFrame>,
956 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
957 // them), padded like this one -- the lookahead window the per-block
958 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
959 // EMPTY slice codes the frame at one lambda, as before.
960 lookahead: &[Picture],
961) -> Result<Encoded> {
962 picture.check()?;
963 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
964 return Err(Error::unsupported(
965 "AV1 encode",
966 "an inter frame is coded only for a picture that is a whole number \
967 of 64x64 superblocks -- the inter tile writer never splits a \
968 superblock's partition below that",
969 ));
970 }
971 if reference.width != picture.width || reference.height != picture.height {
972 return Err(Error::unsupported(
973 "AV1 encode",
974 "the reference picture must be the same size as the one being coded",
975 ));
976 }
977
978 // The single slot this crate's inter frames ever predict from or
979 // refresh (`inter_frame_headers`'s contract): every frame both reads and
980 // overwrites slot 0, so the frame just coded is always what the next one
981 // predicts against.
982 const LAST_SLOT: u8 = 0;
983 // Slot 0 and slot 2 alternate so the frame two back survives one more
984 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
985 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
986 // in the very slot it will overwrite.
987 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
988 let last_slot = pyramid.map_or(
989 if order_hint <= 1 {
990 LAST_SLOT
991 } else if (order_hint - 1) % 2 == 1 {
992 0
993 } else {
994 2
995 },
996 |p| p.last_slot,
997 );
998 // `render`, not `picture.width`/`picture.height`: `picture` here is
999 // already padded to a whole number of superblocks (`encode_sequence`'s
1000 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
1001 // every true-edge clamp downstream) must come from the frame's real,
1002 // unpadded size, same as `key_frame_headers_colour` takes `render` and
1003 // not the padded picture in `encode_key_frame_inner`.
1004 let (seq, mut header) = inter_frame_headers_slots(
1005 render.0,
1006 render.1,
1007 base_q_idx,
1008 order_hint,
1009 last_slot,
1010 self_slot,
1011 match pyramid {
1012 Some(p) => p.altref_slot,
1013 None if altref.is_some() => self_slot,
1014 None => GOLDEN_SLOT,
1015 },
1016 )?;
1017 header.render_width = render.0 as u32;
1018 header.render_height = render.1 as u32;
1019 // lane-refs: this frame's motion-compensation kernel, written into the
1020 // header AND armed on the context every prediction reads, in one place so
1021 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
1022 // tile decodes to different pixels than the encoder scored).
1023 header.interpolation_filter = frame_interp_filter();
1024 fctx.interp_filter.set(mc::InterpFilterKind::from_header(
1025 header.interpolation_filter,
1026 ));
1027 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
1028 // The order hint behind each `ref_frame_idx` entry. The flat path's own
1029 // slot plan (`inter_frame_headers_slots`) is: every reference but
1030 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
1031 // `ALTREF_FRAME`, which reads the frame two back when there is one;
1032 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
1033 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
1034 header.order_hints = order_hints;
1035 // lane-last2: `inter_frame_headers_slots` points every un-named
1036 // reference at `last_slot`; the pyramid's leaf chain retains a second,
1037 // older picture and names it here. The caller's `sign_bias` /
1038 // `order_hints` entry 1 is derived from this same slot, so the stack
1039 // scans and `skipModeAllowed` read what the decoder will.
1040 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
1041 header.ref_frame_idx[1] = slot;
1042 }
1043 header.reference_select = reference_select();
1044 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
1045 // per-reference order-hint distance is read by the block SEARCH, which
1046 // runs long before the writer arms these (the distance-scaled search step
1047 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
1048 // never reached the tool).
1049 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
1050 // lane-hpmv: armed here for the same reason the order hints are -- the
1051 // block SEARCH reads it (its eighth-pel stage) long before the writer.
1052 let hp_mv = header.allow_high_precision_mv;
1053 crate::tile::arm_high_precision_mv(hp_mv);
1054 if let Some(p) = pyramid {
1055 header.show_frame = p.show_frame;
1056 header.showable_frame = !p.show_frame;
1057 header.ref_frame_sign_bias = p.sign_bias;
1058 }
1059 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
1060 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
1061 // block inside this frame codes and searches its own `tx_depth`, the same
1062 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
1063 let tx_select = tx_select() && tx_select_inter();
1064 if tx_select {
1065 header.tx_mode = TxMode::Select;
1066 }
1067
1068 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
1069 // lane-palw: the encoder's own in-process reconstruct reads its palette
1070 // colour-index maps back through `decode::palette_onscreen`, which takes
1071 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
1072 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
1073 // them here so the reconstruct clamps a block cut by the frame edge
1074 // exactly as the writer now does.
1075 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
1076 fctx.seg_mi_dims.set(frame_mi_dims);
1077 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
1078 // here (see `encode_key_frame_inner`).
1079 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1080 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
1081 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
1082 // This frame's own `allow_screen_content_tools`. It can only be set when
1083 // the SEQUENCE offers the bit at all, which is the key frame's decision
1084 // ([`SEQ_SCREEN`]): a frame header that contradicts
1085 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
1086 // encode.
1087 let screen =
1088 seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height);
1089 header.allow_screen_content_tools = screen;
1090 // lane-txi, as on the key frame: the header bit the writer's own
1091 // `Cdfs` then reads for every luma `tx_type` symbol.
1092 header.reduced_tx_set = !wide_tx_set(screen);
1093 // lane-intertx, desync (a): the frame context this value is read back
1094 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
1095 // `recode_inter_chroma`, and every inter decode helper the search's own
1096 // trial decode shares) must carry THIS frame's bit, not whatever the
1097 // previous frame's trial decode last left in the shared cell -- a stale
1098 // `true` here narrows the chroma allowance the search reconstructs
1099 // against under the one the header's bit actually allows.
1100 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
1101 // The search prices coefficients against the tables this frame's writer
1102 // starts from, not against the defaults (lane-av1txbits) -- but only on a
1103 // frame the screen detector said no to (lane-av1price2): armed HERE, after
1104 // `screen` exists, and again on every search/tile worker below.
1105 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
1106 let mut luma = Plane {
1107 source: &picture_y8,
1108 reconstruction: vec![128; picture_y8.len()],
1109 width: picture.width,
1110 height: picture.height,
1111 true_width,
1112 true_height,
1113 tile_x0: 0,
1114 tile_y0: 0,
1115 tile_x1: picture.width,
1116 tile_y1: picture.height,
1117 ctx: CoefCtxMap::default(),
1118 };
1119 let mut chroma = [
1120 Plane {
1121 source: &picture_u8,
1122 reconstruction: vec![128; picture_u8.len()],
1123 width: picture.width / 2,
1124 height: picture.height / 2,
1125 true_width: true_width / 2,
1126 true_height: true_height / 2,
1127 tile_x0: 0,
1128 tile_y0: 0,
1129 tile_x1: picture.width / 2,
1130 tile_y1: picture.height / 2,
1131 ctx: CoefCtxMap::default(),
1132 },
1133 Plane {
1134 source: &picture_v8,
1135 reconstruction: vec![128; picture_v8.len()],
1136 width: picture.width / 2,
1137 height: picture.height / 2,
1138 true_width: true_width / 2,
1139 true_height: true_height / 2,
1140 tile_x0: 0,
1141 tile_y0: 0,
1142 tile_x1: picture.width / 2,
1143 tile_y1: picture.height / 2,
1144 ctx: CoefCtxMap::default(),
1145 },
1146 ];
1147
1148 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
1149 let top_arf = matches!(
1150 pyramid,
1151 Some(p) if p.dq_level == DqLevel::TopArf
1152 );
1153 let arfmode_v = arfmode();
1154 let search = Search {
1155 base_q_idx,
1156 deadzone,
1157 lambda: lambda_scale()
1158 * match pyramid {
1159 Some(p) if !p.show_frame => hidden_lambda_factor(),
1160 _ => 1.0,
1161 }
1162 * step
1163 * step,
1164 modes: &KEY_FRAME_MODES,
1165 top_k: prune_top_k_inter(),
1166 screen,
1167 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
1168 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
1169 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
1170 // and quarter hidden frames, the leaves, the flat path -- keeps the
1171 // full set.
1172 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
1173 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
1174 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
1175 };
1176 let mode_bits_table = inter_mode_bits();
1177 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
1178 // this frame the NEXT one predicts from. Off (`None`) without a
1179 // lookahead picture or at strength 0.
1180 let tpl_k = tpl_strength();
1181 let window: Vec<&Picture> = lookahead
1182 .iter()
1183 .take_while(|n| n.width == picture.width && n.height == picture.height)
1184 .collect();
1185 let tpl_sources: Vec<Vec<u8>> = window
1186 .iter()
1187 .map(|n| n.y.iter().map(|&v| v as u8).collect())
1188 .collect();
1189 let tpl_cells_x = picture.width / 16;
1190 // `.1` is the propagating map's raw per-cell dependence ratio, which only
1191 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
1192 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = (tpl_k > 0.0 && !tpl_sources.is_empty())
1193 .then(|| {
1194 if tpl_propagating() {
1195 let mut frames: Vec<&[u8]> = vec![&picture_y8];
1196 frames.extend(tpl_sources.iter().map(Vec::as_slice));
1197 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
1198 (f, Some(r))
1199 } else {
1200 // The shipped map is one factor per 64x64; it is spread over that
1201 // superblock's own 16 cells so the application site below (which
1202 // averages the four cells of a 32x32 block) reads exactly the
1203 // superblock factor, whichever map fed it.
1204 let map = tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
1205 let cells_y = picture.height / 16;
1206 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
1207 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
1208 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
1209 .collect();
1210 (f, None)
1211 }
1212 });
1213 let (tpl_factors, tpl_ratio) = match tpl_both {
1214 Some((f, r)) => (Some(f), r),
1215 None => (None, None),
1216 };
1217
1218 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
1219 // coding surface's: `blocks` carries one entry per 32x32 block the tile
1220 // writer will actually visit, same count it checks `blocks.len()`
1221 // against, which is fewer than the padded surface's own block count
1222 // whenever the true size is not a 64x64 multiple.
1223 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
1224 let (cols, rows) = (cols as usize, rows as usize);
1225 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
1226 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
1227 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
1228 // only when the map is, and `delta_q_res` follows straight into the frame
1229 // header (`write_delta_q_params`) and into the tile writer's own plan.
1230 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
1231 // measured the per-superblock quantizer as a win on both films and a
1232 // 0.5 loss vs libaom on the desktop capture, so a frame that set
1233 // `allow_screen_content_tools` codes no delta syntax at all and stays
1234 // byte-identical to the pre-lane encoder.
1235 // lane-arfq: the level whose `delta_q` strength this frame reads; the
1236 // flat path (no pyramid) is a leaf.
1237 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
1238 let deltaq_res: Option<i32> = tpl_factors
1239 .as_ref()
1240 .filter(|_| !screen)
1241 .and(deltaq_res_log2().map(|r| 1i32 << r));
1242 // The same 16-cell mean the superblock's own lambda takes, clamped to the
1243 // map the frame actually has -- read over the factors or over the raw
1244 // dependence ratios, whichever mapping is asking.
1245 let sb_mean = |m: &[f64], sb: usize| {
1246 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
1247 (0..16)
1248 .map(|i| {
1249 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
1250 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
1251 })
1252 .sum::<f64>()
1253 / 16.0
1254 };
1255 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
1256 // raw dependence ratio; without it (and always without a ratio map, i.e.
1257 // on the one-frame area map) the shipped derivation stands.
1258 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
1259 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
1260 match (libaom, tpl_ratio.as_deref(), r_frame) {
1261 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
1262 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
1263 }
1264 };
1265 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
1266 (Some(f), Some(res)) => {
1267 let libaom = dq_tpl_strength(dq_level);
1268 let mut g: Vec<u8> = (0..sb_cols * _sb_rows)
1269 .map(|sb| sb_qindex(f, res, sb, libaom))
1270 .collect();
1271 // lane-b128m: under 128 superblocks the delta_q syntax is coded
1272 // ONCE per 128 root (the reader's own unit), so all four 64x64
1273 // cells of a root have to be searched -- and quantized -- at the
1274 // one qindex the root's top-left cell codes.
1275 if sb128_on() {
1276 for sb_r in 0.._sb_rows {
1277 for sb_c in 0..sb_cols {
1278 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
1279 g[sb_r * sb_cols + sb_c] = q;
1280 }
1281 }
1282 }
1283 Some(g)
1284 }
1285 _ => None,
1286 };
1287 // lane-dq census: both mappings on the SAME superblocks, whether or not
1288 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
1289 // off, and the census then prices the default `res = 4` grid).
1290 if dq_census()
1291 && let Some(f) = &tpl_factors {
1292 let res = deltaq_res.unwrap_or(4);
1293 let off = |libaom: Option<f64>| -> Vec<i32> {
1294 (0..sb_cols * _sb_rows)
1295 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
1296 .collect()
1297 };
1298 let strength = dq_tpl_strength(dq_level);
1299 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
1300 let coded = match (deltaq_res.is_some(), strength) {
1301 (false, _) => "none".to_string(),
1302 (true, None) => "ours".to_string(),
1303 (true, Some(k)) => format!("libaom k={k}"),
1304 };
1305 eprintln!(
1306 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
1307 sb_cols * _sb_rows,
1308 r_frame.unwrap_or(f64::NAN),
1309 dq_summary(&ours),
1310 dq_summary(&aom),
1311 );
1312 }
1313 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
1314 header.delta.q_present = true;
1315 header.delta.q_res = res.trailing_zeros() as u8;
1316 }
1317 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
1318 // below, so the root search prices the group the writer really codes.
1319 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
1320 if let Some(g) = &sb_q {
1321 let mut levels: Vec<u8> = g.clone();
1322 levels.sort_unstable();
1323 levels.dedup();
1324 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
1325 }
1326 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
1327 // This frame's tile grid, as in `encode_key_frame_inner`.
1328 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
1329 let layout = crate::tile::TileLayout::new(
1330 header.mi_cols,
1331 header.mi_rows,
1332 tile_cols_log2,
1333 tile_rows_log2,
1334 );
1335 header.tile_info = tile_info_of(&layout, 1);
1336 let header_tile_info = header.tile_info.clone();
1337 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
1338 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
1339 // once per frame (lane-av1rd2), not once per block, which is a whole
1340 // plane's map per 32x32 block and now per leaf too.
1341 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
1342 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
1343 // availability -- intra edges and the MV stack's scans alike -- already
1344 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
1345 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
1346 // giving each job its own planes and its own `MiGrid` therefore leaves
1347 // every decision, and so every coded bit, exactly where the whole-frame
1348 // loop left it, at any tile count and any thread count.
1349 let (frame_width, frame_height) = (picture.width, picture.height);
1350 let search_tile = |index: usize,
1351 fctx: &crate::decode::FrameCtx|
1352 -> Result<(Vec<(usize, Quadrant)>, TilePixels)> {
1353 // Thread-local, and this job may be running on a `search_tiles`
1354 // worker: `ref_distance`'s order-hint distance (the scaled motion
1355 // search step) is read by the SEARCH, so every worker arms it or the
1356 // tile's bits depend on the thread count.
1357 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
1358 crate::tile::arm_high_precision_mv(hp_mv);
1359 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
1360 let rect = layout.rect(index);
1361 let mut luma = fresh_plane(
1362 &picture_y8,
1363 frame_width,
1364 frame_height,
1365 true_width,
1366 true_height,
1367 );
1368 let mut chroma = [
1369 fresh_plane(
1370 &picture_u8,
1371 frame_width / 2,
1372 frame_height / 2,
1373 true_width / 2,
1374 true_height / 2,
1375 ),
1376 fresh_plane(
1377 &picture_v8,
1378 frame_width / 2,
1379 frame_height / 2,
1380 true_width / 2,
1381 true_height / 2,
1382 ),
1383 ];
1384 clip_planes_to_tile(&mut luma, &mut chroma, rect);
1385 let mut grid = MiGrid::new(mi_cols, mi_rows);
1386 grid.set_sign_bias(sign_bias);
1387 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
1388 // built once per tile job (`obmc_prediction`).
1389 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
1390 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
1391 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
1392 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
1393 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
1394 grid.set_tile_bounds(
1395 rect.mi_row0 as usize,
1396 rect.mi_col0 as usize,
1397 rect.mi_row1 as usize,
1398 rect.mi_col1 as usize,
1399 );
1400 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
1401 // lane-b128: under a 128x128 superblock the search walks the roots the
1402 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
1403 // not plain raster -- a search that visits BL before TR builds every mv
1404 // stack and neighbour context off blocks the writer has not coded yet,
1405 // which is what made the write-time drl clamp fire at all (lane-sb128b).
1406 // At a 64 superblock the two orders are identical and this is the same
1407 // raster loop as before.
1408 let sb128_search = sb128_on();
1409 let root_step = if sb128_search { 2 } else { 1 };
1410 let mut roots: Vec<(usize, usize)> = Vec::new();
1411 {
1412 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
1413 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
1414 let mut r = r0;
1415 while r < r1 {
1416 let mut c = c0;
1417 while c < c1 {
1418 roots.push((r, c));
1419 c += root_step;
1420 }
1421 r += root_step;
1422 }
1423 }
1424 for (root_r, root_c) in roots {
1425 // The 64x64 cells of this root, in the writer's own order.
1426 let cells: Vec<(usize, usize)> = if sb128_search {
1427 [(0, 0), (0, 1), (1, 0), (1, 1)]
1428 .into_iter()
1429 .map(|(dr, dc)| (root_r + dr, root_c + dc))
1430 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
1431 .collect()
1432 } else {
1433 vec![(root_r, root_c)]
1434 };
1435 // What the four cells below really cost, against which the whole
1436 // 128x128 candidate is weighed.
1437 let mark128 = blocks.len();
1438 let mut root_cost = 0.0f64;
1439 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
1440 // root builds the same list one size down, per superblock).
1441 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
1442 if header.reference_select && b128_compound() && !screen && sb128_search {
1443 [
1444 (crate::mvstack::GOLDEN_FRAME, golden),
1445 (crate::mvstack::ALTREF_FRAME, altref),
1446 ]
1447 .into_iter()
1448 .filter_map(|(r, pic)| {
1449 pic.map(|p| {
1450 (
1451 r,
1452 p,
1453 crate::mvstack::find_mv_stack_compound(
1454 &grid,
1455 root_r * 16,
1456 root_c * 16,
1457 32,
1458 32,
1459 (crate::mvstack::LAST_FRAME, r),
1460 mi_cols,
1461 mi_rows,
1462 grid.sign_bias_table(),
1463 &[(0, 0); 7],
1464 None,
1465 ),
1466 )
1467 })
1468 })
1469 .collect()
1470 } else {
1471 Vec::new()
1472 };
1473 let root128 = (sb128_search && b128_root() && cells.len() == 4)
1474 .then(|| {
1475 search_root_128(
1476 &mut luma,
1477 &mut chroma,
1478 &grid,
1479 (root_r, root_c),
1480 (rows, cols),
1481 (header.mi_cols, header.mi_rows),
1482 search,
1483 &tpl_factors,
1484 sb_q.as_ref(),
1485 sb_cols,
1486 tpl_cells_x,
1487 base_q_idx,
1488 dq_res,
1489 reference,
1490 &root_compound,
1491 fctx,
1492 )
1493 })
1494 .flatten();
1495 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
1496 // are priced; the cheaper one competes with the NONE block and with
1497 // the four superblocks below.
1498 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
1499 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
1500 .then(|| {
1501 let mut best: Option<(bool, _)> = None;
1502 for horz in [true, false] {
1503 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
1504 continue;
1505 }
1506 let Some(found) = search_root_128_rect(
1507 &mut luma,
1508 &mut chroma,
1509 &mut grid,
1510 (root_r, root_c),
1511 (rows, cols),
1512 (header.mi_cols, header.mi_rows),
1513 search,
1514 &tpl_factors,
1515 sb_q.as_ref(),
1516 sb_cols,
1517 tpl_cells_x,
1518 base_q_idx,
1519 dq_res,
1520 reference,
1521 &root_compound,
1522 horz,
1523 fctx,
1524 ) else {
1525 continue;
1526 };
1527 if best
1528 .as_ref()
1529 .is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0)
1530 {
1531 best = Some((horz, found));
1532 }
1533 }
1534 best
1535 })
1536 .flatten();
1537 // lane-ab128: and the same root as one of the four AB shapes -- two
1538 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
1539 // the cheapest joins the candidate list below.
1540 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
1541 let root_ab = (sb128_search
1542 && (b128_ab() || forced_ab != 0)
1543 && cells.len() == 4
1544 && forced_rect == 0)
1545 .then(|| {
1546 let mut best: Option<(usize, _)> = None;
1547 for symbol in 4..=7usize {
1548 if forced_ab != 0 && usize::from(forced_ab) != symbol {
1549 continue;
1550 }
1551 let Some(found) = search_root_128_ab(
1552 &mut luma,
1553 &mut chroma,
1554 &mut grid,
1555 (root_r, root_c),
1556 (rows, cols),
1557 (header.mi_cols, header.mi_rows),
1558 search,
1559 &tpl_factors,
1560 sb_q.as_ref(),
1561 sb_cols,
1562 tpl_cells_x,
1563 base_q_idx,
1564 reference,
1565 &root_compound,
1566 symbol,
1567 fctx,
1568 ) else {
1569 continue;
1570 };
1571 if best
1572 .as_ref()
1573 .is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0)
1574 {
1575 best = Some((symbol, found));
1576 }
1577 }
1578 best
1579 })
1580 .flatten();
1581 for (sb_r, sb_c) in cells {
1582 // lane-b64: the whole superblock as ONE 64x64 block, tried before
1583 // its quadrants are (`search_skip_64`) and compared against the
1584 // four of them below. Only a superblock wholly inside the true
1585 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
1586 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
1587 // only that the block's half is inside, and the trial is ranked
1588 // over the inside part alone ([`Plane::block_sse`]).
1589 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
1590 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
1591 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
1592 && x64 + SUPERBLOCK <= luma.true_width
1593 && y64 + SUPERBLOCK <= luma.true_height;
1594 let edge_inside = b64_edge()
1595 && crate::tile::has_half(
1596 sb_c as u32 * crate::tile::SB_MI,
1597 crate::tile::SB_MI,
1598 header.mi_cols,
1599 )
1600 && crate::tile::has_half(
1601 sb_r as u32 * crate::tile::SB_MI,
1602 crate::tile::SB_MI,
1603 header.mi_rows,
1604 );
1605 let sb64_legal = b64_root()
1606 && sb_r * 2 + 1 < rows
1607 && sb_c * 2 + 1 < cols
1608 && (whole_inside || edge_inside);
1609 // One lambda for the whole superblock, the same mean the 32x32
1610 // level takes over its own four tpl cells: the 64-vs-four-32
1611 // comparison below weighs one cost against four, so both sides
1612 // have to be priced at the same lambda.
1613 let sb_search = match &tpl_factors {
1614 // lane-deltaq: with a per-superblock quantizer the lambda
1615 // comes from that quantizer, not from the raw map factor --
1616 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
1617 Some(_) if sb_q.is_some() => sb_q_search(
1618 sb_q.as_ref().expect("armed"),
1619 sb_cols,
1620 base_q_idx,
1621 (sb_r, sb_c),
1622 search,
1623 ),
1624 Some(f) if sb64_legal => {
1625 let mean = (0..16)
1626 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
1627 .sum::<f64>()
1628 / 16.0;
1629 Search {
1630 lambda: search.lambda * mean,
1631 ..search
1632 }
1633 }
1634 _ => search,
1635 };
1636 let mark = blocks.len();
1637 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
1638 let mut sb_cost = 0.0f64;
1639 if sb64_legal {
1640 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
1641 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
1642 let stack =
1643 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
1644 // lane-b64b: the `LAST` + extra-reference pairs at this
1645 // superblock's own 16x16-mi window, the same stacks the tile
1646 // writer's `Whole64` arm rebuilds. Empty unless the frame
1647 // codes `reference_select`, which is what gates the syntax.
1648 // `!screen` for the same reason the residual arm is gated
1649 // there ([`b64_residual`]): a desktop capture's superblocks
1650 // are flat runs the skip arm already codes for nothing, and
1651 // MEASURED, compound at the root cost it +33.4/-23.8 ->
1652 // +33.7/-23.6 while both film rows gained (step 1's table).
1653 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
1654 if header.reference_select && b64_compound() && !screen {
1655 [
1656 (crate::mvstack::GOLDEN_FRAME, golden),
1657 (crate::mvstack::ALTREF_FRAME, altref),
1658 ]
1659 .into_iter()
1660 .filter_map(|(r, pic)| {
1661 pic.map(|p| {
1662 (
1663 r,
1664 p,
1665 crate::mvstack::find_mv_stack_compound(
1666 &grid,
1667 mi_row,
1668 mi_col,
1669 16,
1670 16,
1671 (crate::mvstack::LAST_FRAME, r),
1672 mi_cols,
1673 mi_rows,
1674 grid.sign_bias_table(),
1675 &[(0, 0); 7],
1676 None,
1677 ),
1678 )
1679 })
1680 })
1681 .collect()
1682 } else {
1683 Vec::new()
1684 };
1685 if let Some((cost, block)) = search_skip_64(
1686 &mut luma,
1687 &mut chroma,
1688 (x64, y64),
1689 (SUPERBLOCK, SUPERBLOCK),
1690 &sb_search,
1691 b64_residual() && !screen,
1692 reference,
1693 &stack,
1694 &sb_compound,
1695 fctx,
1696 ) {
1697 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
1698 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
1699 let cost = cost
1700 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
1701 sb64 = Some((cost, block, after));
1702 }
1703 }
1704 // A superblock whose 64x64 trial already codes almost nothing per
1705 // pixel is taken outright and its quadrants are never searched --
1706 // the same `split_rd_breakout` shape the 32x32 level uses one
1707 // size up, and where this lever BUYS wall instead of spending it.
1708 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
1709 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, sb_search.lambda)
1710 });
1711 for quadrant in 0..if early64 { 0 } else { 4 } {
1712 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
1713 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
1714 // decision under it (partition, mode, tx, motion) reads
1715 // `search.lambda`, so scaling the one field here scales all
1716 // of them. 32x32 and not the 16x16 the map is built at
1717 // because the whole-vs-split comparison right below weighs
1718 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
1719 // would make those two numbers incomparable.
1720 let search = match &tpl_factors {
1721 // lane-deltaq: the quantizer is a SUPERBLOCK-level
1722 // symbol, so all four quadrants take their superblock's
1723 // own qindex and the lambda it implies. No granularity is
1724 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
1725 // factor per superblock, shared by its sixteen cells.
1726 Some(_) if sb_q.is_some() => sb_q_search(
1727 sb_q.as_ref().expect("armed"),
1728 sb_cols,
1729 base_q_idx,
1730 (sb_r, sb_c),
1731 search,
1732 ),
1733 Some(f) => {
1734 let mean = (0..4)
1735 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
1736 .sum::<f64>()
1737 / 4.0;
1738 Search {
1739 lambda: search.lambda * mean,
1740 ..search
1741 }
1742 }
1743 None => search,
1744 };
1745 // Same filter as the tile writer's: a quadrant whose own mi
1746 // origin is not inside the true frame is never coded.
1747 if r32 >= rows || c32 >= cols {
1748 continue;
1749 }
1750 // spec `decode_partition`'s hasRows/hasCols recomputed at this
1751 // 32x32 block's own half (`crate::tile::has_half`), same as
1752 // the key frame search: the true frame edge can fall inside a
1753 // quadrant a superblock-level check already let through, and
1754 // such a quadrant cannot be left whole -- it must split into
1755 // the 16x16 leaves that are actually inside the true frame
1756 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
1757 // arm).
1758 let (has_cols32, has_rows32) = (
1759 crate::tile::has_half(
1760 c32 as u32 * crate::tile::BLOCK_MI,
1761 crate::tile::BLOCK_MI,
1762 header.mi_cols,
1763 ),
1764 crate::tile::has_half(
1765 r32 as u32 * crate::tile::BLOCK_MI,
1766 crate::tile::BLOCK_MI,
1767 header.mi_rows,
1768 ),
1769 );
1770 if has_cols32 && has_rows32 {
1771 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
1772 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
1773 let stack = find_mv_stack(
1774 &grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows,
1775 );
1776 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
1777 (crate::mvstack::LAST2_FRAME, last2),
1778 (crate::mvstack::GOLDEN_FRAME, golden),
1779 (crate::mvstack::ALTREF_FRAME, altref),
1780 ]
1781 .into_iter()
1782 .filter_map(|(r, pic)| {
1783 pic.map(|p| {
1784 (
1785 r,
1786 p,
1787 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
1788 )
1789 })
1790 })
1791 .collect();
1792 let extra: Vec<(i8, &Picture, &MvStack)> =
1793 extra_stacks.iter().map(|(r, p, st)| (*r, *p, st)).collect();
1794 // The COMPOUND stack of each `LAST` + extra pair, off the
1795 // same grid (and the same armed sign bias) the tile writer
1796 // rebuilds it from. Empty unless this frame codes
1797 // `reference_select`, which is what gates the syntax.
1798 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
1799 if header.reference_select {
1800 extra_stacks
1801 .iter()
1802 .map(|&(r, p, _)| {
1803 (
1804 r,
1805 p,
1806 crate::mvstack::find_mv_stack_compound(
1807 &grid,
1808 mi_row,
1809 mi_col,
1810 8,
1811 8,
1812 (crate::mvstack::LAST_FRAME, r),
1813 mi_cols,
1814 mi_rows,
1815 grid.sign_bias_table(),
1816 &[(0, 0); 7],
1817 None,
1818 ),
1819 )
1820 })
1821 .collect()
1822 } else {
1823 Vec::new()
1824 };
1825
1826 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
1827 let (block, mut cost_whole) = search_inter_block(
1828 &mut luma,
1829 &mut chroma,
1830 (x, y),
1831 &search,
1832 &mode_bits_table,
1833 reference,
1834 &stack,
1835 &extra,
1836 &compound,
1837 &grid,
1838 (mi_row, mi_col),
1839 (mi_rows, mi_cols),
1840 fctx,
1841 );
1842 cost_whole += search.lambda * partition_bits(BLOCK, false);
1843 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
1844
1845 // What four 16x16 leaves cost instead (spec
1846 // PARTITION_SPLIT at BLOCK_32X32, which
1847 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
1848 // already writes for a straddling quadrant). Each leaf is
1849 // searched against the reconstruction -- and the `mi`
1850 // grid -- the ones before it left, exactly as the writer
1851 // and the decoder will read them.
1852 //
1853 // A block the whole-32 search left skipped (no residual
1854 // at all) is not offered the split: libaom prunes the
1855 // same way at cpu-used 6, and it is where the wall would
1856 // otherwise go on static content.
1857 let leaf_positions: Vec<(usize, usize)> =
1858 (0..4).map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)).collect();
1859 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
1860 crate::tile::has_half(
1861 sc as u32 * crate::tile::SUB_MI,
1862 crate::tile::SUB_MI,
1863 header.mi_cols,
1864 ) && crate::tile::has_half(
1865 sr as u32 * crate::tile::SUB_MI,
1866 crate::tile::SUB_MI,
1867 header.mi_rows,
1868 )
1869 });
1870 // The breakout above: a 32x32 block that codes almost
1871 // nothing is not offered the split at all.
1872 let breakout = split_breakout_coeffs();
1873 let split = (!block.skip
1874 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
1875 && (breakout == 0 || block.luma.len() > 4 * breakout)
1876 && leaves_legal
1877 && split_inter_blocks())
1878 .then(|| {
1879 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
1880 let mut cost = search.lambda * partition_bits(BLOCK, true);
1881 let mut leaves = Vec::with_capacity(4);
1882 for &(sr, sc) in &leaf_positions {
1883 let (mi_row, mi_col) = (sr * 4, sc * 4);
1884 let (lx, ly) = (sc * SUB, sr * SUB);
1885 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
1886 let stack = find_mv_stack(
1887 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
1888 );
1889 let cstacks = leaf_compound_stacks(
1890 &grid,
1891 mi_row,
1892 mi_col,
1893 4,
1894 4,
1895 mi_cols,
1896 mi_rows,
1897 header.reference_select,
1898 golden,
1899 altref,
1900 );
1901 let (leaf, leaf_cost) = code_square_inter(
1902 &mut luma,
1903 &mut chroma,
1904 (lx, ly),
1905 SUB,
1906 &search,
1907 &mode_bits_table,
1908 reference,
1909 &stack,
1910 &cstacks,
1911 &grid,
1912 (mi_row, mi_col),
1913 (mi_rows, mi_cols),
1914 &obmc_refs,
1915 fctx,
1916 );
1917 let leaf_cost =
1918 leaf_cost + search.lambda * partition_bits(SUB, false);
1919 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
1920
1921 // And what four 8x8 leaves cost instead --
1922 // the same tree one step further down, which
1923 // the writer codes as a real PARTITION_SPLIT
1924 // at BLOCK_16X16 (lane-av1rd2). Same
1925 // skipped-block prune as the level above.
1926 let eight = (!leaf.skip
1927 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
1928 && (breakout == 0 || leaf.luma.len() > breakout)
1929 && split_inter_8()
1930 // lane-arfmode: arm 2 makes 16x16 the top
1931 // ARF's leaf floor -- the RD-optional 8x8
1932 // comparison is not offered. Counted only
1933 // when every other prune let it through,
1934 // so the counter means "refused", not
1935 // "never considered". The spec-forced 8x8s
1936 // at a straddling 16x16 (the
1937 // `sub_positions` path below) are a
1938 // different site and stay.
1939 && (search.arf_leaf8 || arfmode_hit_and_no()))
1940 .then(|| {
1941 restore(&mut luma, &mut chroma, (lx, ly), SUB, &leaf_base);
1942 let mut cost8 = search.lambda
1943 * (partition_bits(SUB, true)
1944 + 4.0 * partition_bits(8, false));
1945 let mut eight = Vec::with_capacity(4);
1946 for i in 0..4 {
1947 let (mr, mc) = (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
1948 let stack8 = find_mv_stack(
1949 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
1950 );
1951 let cstacks8: Vec<(
1952 i8,
1953 &Picture,
1954 crate::mvstack::CompoundMvStack,
1955 )> = if header.reference_select && leaf_compound() {
1956 [
1957 (crate::mvstack::GOLDEN_FRAME, golden),
1958 (crate::mvstack::ALTREF_FRAME, altref),
1959 ]
1960 .into_iter()
1961 .filter_map(|(r, pic)| {
1962 pic.map(|p| {
1963 (
1964 r,
1965 p,
1966 crate::mvstack::find_mv_stack_compound(
1967 &grid,
1968 mr,
1969 mc,
1970 2,
1971 2,
1972 (crate::mvstack::LAST_FRAME, r),
1973 mi_cols,
1974 mi_rows,
1975 grid.sign_bias_table(),
1976 &[(0, 0); 7],
1977 None,
1978 ),
1979 )
1980 })
1981 })
1982 .collect()
1983 } else {
1984 Vec::new()
1985 };
1986 let (leaf8, cost) = code_square_inter(
1987 &mut luma,
1988 &mut chroma,
1989 (lx + (i % 2) * 8, ly + (i / 2) * 8),
1990 8,
1991 &search,
1992 &mode_bits_table,
1993 reference,
1994 &stack8,
1995 &cstacks8,
1996 &grid,
1997 (mr, mc),
1998 (mi_rows, mi_cols),
1999 &obmc_refs,
2000 fctx,
2001 );
2002 cost8 += cost;
2003 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
2004 eight.push(leaf8);
2005 }
2006 (eight, cost8)
2007 });
2008 match eight {
2009 Some((eight, cost8)) if cost8 < leaf_cost => {
2010 partition_hit(3);
2011 cost += cost8;
2012 leaves.push(BlockCoeffs {
2013 eight: Some(eight),
2014 ..BlockCoeffs::default()
2015 });
2016 continue;
2017 }
2018 Some(_) => {
2019 restore(&mut luma, &mut chroma, (lx, ly), SUB, &after_leaf)
2020 }
2021 None => {}
2022 }
2023 partition_hit(2);
2024 cost += leaf_cost;
2025 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
2026 leaves.push(leaf);
2027 }
2028 (leaves, cost)
2029 });
2030 if let Some((leaves, cost)) = split {
2031 if cost < cost_whole {
2032 // The leaves' own `mi` cells are already in the
2033 // grid, and their reconstruction is what the
2034 // planes hold.
2035 partition_hit(1);
2036 sb_cost += cost;
2037 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
2038 continue;
2039 }
2040 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
2041 }
2042 partition_hit(0);
2043 sb_cost += cost_whole;
2044 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
2045 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
2046 } else {
2047 // The sub-positions actually inside the true frame, same
2048 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
2049 let sub_positions: Vec<(usize, usize)> = (0..4)
2050 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
2051 .filter(|&(sr, sc)| {
2052 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
2053 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
2054 })
2055 .collect();
2056 // Each leaf searches intra against its own `NEARESTMV`
2057 // candidate (`code_square_inter`), same real-inter choice
2058 // `search_inter_block` makes for a whole 32x32 block, at
2059 // this leaf's own 4x4-mi mv-stack window -- unless the
2060 // leaf's own half itself straddles the true edge, which
2061 // it codes as two (or one, at a true corner) 8x8 leaves
2062 // (`crate::tile::write_leaf8`'s inter counterpart),
2063 // mirroring the key frame search's straddling-16x16
2064 // handling above (lane-av1inter8).
2065 let mut leaves = Vec::with_capacity(sub_positions.len());
2066 for (sr, sc) in sub_positions {
2067 let (has_cols16, has_rows16) = (
2068 crate::tile::has_half(
2069 sc as u32 * crate::tile::SUB_MI,
2070 crate::tile::SUB_MI,
2071 header.mi_cols,
2072 ),
2073 crate::tile::has_half(
2074 sr as u32 * crate::tile::SUB_MI,
2075 crate::tile::SUB_MI,
2076 header.mi_rows,
2077 ),
2078 );
2079 if has_cols16 && has_rows16 {
2080 let (x, y) = (sc * SUB, sr * SUB);
2081 let (mi_row, mi_col) = (sr * 4, sc * 4);
2082 let stack = find_mv_stack(
2083 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
2084 );
2085 let cstacks = leaf_compound_stacks(
2086 &grid,
2087 mi_row,
2088 mi_col,
2089 4,
2090 4,
2091 mi_cols,
2092 mi_rows,
2093 header.reference_select,
2094 golden,
2095 altref,
2096 );
2097 let (block, _) = code_square_inter(
2098 &mut luma,
2099 &mut chroma,
2100 (x, y),
2101 SUB,
2102 &search,
2103 &mode_bits_table,
2104 reference,
2105 &stack,
2106 &cstacks,
2107 &grid,
2108 (mi_row, mi_col),
2109 (mi_rows, mi_cols),
2110 &obmc_refs,
2111 fctx,
2112 );
2113 // One publication point for every coded leaf
2114 // (`record_mi`): this site used to spell the vote
2115 // out with `ref_frame` pinned to LAST and `mv1`
2116 // to (0,0), which is the encoder-grid-drift class
2117 // -- correct only for as long as a leaf can never
2118 // be compound.
2119 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
2120 leaves.push(block);
2121 } else {
2122 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
2123 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
2124 let mut eight = Vec::with_capacity(2);
2125 for i in 0..4 {
2126 let leaf_x = x_sub + (i % 2) * 8;
2127 let leaf_y = y_sub + (i / 2) * 8;
2128 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
2129 continue;
2130 }
2131 let (mi_row, mi_col) =
2132 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
2133 let stack = find_mv_stack(
2134 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
2135 );
2136 let cstacks = leaf_compound_stacks(
2137 &grid,
2138 mi_row,
2139 mi_col,
2140 2,
2141 2,
2142 mi_cols,
2143 mi_rows,
2144 header.reference_select,
2145 golden,
2146 altref,
2147 );
2148 let (leaf, _) = code_square_inter(
2149 &mut luma,
2150 &mut chroma,
2151 (leaf_x, leaf_y),
2152 8,
2153 &search,
2154 &mode_bits_table,
2155 reference,
2156 &stack,
2157 &cstacks,
2158 &grid,
2159 (mi_row, mi_col),
2160 (mi_rows, mi_cols),
2161 &obmc_refs,
2162 fctx,
2163 );
2164 // Same publication point as the 16x16
2165 // straddling leaf above (`record_mi`).
2166 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
2167 eight.push(leaf);
2168 }
2169 leaves.push(BlockCoeffs {
2170 eight: Some(eight),
2171 ..BlockCoeffs::default()
2172 });
2173 }
2174 }
2175 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
2176 }
2177 }
2178 // The 64x64 root against what its four quadrants really cost.
2179 if let Some((cost64, block, after)) = sb64
2180 && (early64
2181 || cost64
2182 < sb_cost
2183 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
2184 {
2185 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2186 if block.inter.is_some_and(|i| i.ref1.is_some()) {
2187 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2188 }
2189 if !whole_inside {
2190 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2191 }
2192 blocks.truncate(mark);
2193 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
2194 // Overwrites every 16x16 mi cell the quadrant searches
2195 // published under this superblock, so the next block's stack
2196 // is built off the block that was really coded.
2197 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
2198 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
2199 for q in 1..4 {
2200 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
2201 blocks.push((r32 * cols + c32, Quadrant::Covered));
2202 }
2203 root_cost += cost64;
2204 } else {
2205 root_cost += sb_cost;
2206 }
2207 }
2208 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
2209 // `partition_w128` symbol) against what its four superblocks really
2210 // cost, the same weighing the 64 root does one size down. Both sides
2211 // carry their own partition symbol, so the comparison is complete.
2212 // The root candidates, each tagged with the PARTITION symbol its
2213 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
2214 // shapes (lane-ab128).
2215 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
2216 if let Some((c, l, b, a)) = root128 {
2217 cands.push((c, l, 0, vec![b], a));
2218 }
2219 if let Some((horz, (c, l, halves, a))) = root_rect {
2220 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
2221 }
2222 if let Some((symbol, (c, l, pieces, a))) = root_ab {
2223 cands.push((c, l, symbol, pieces.to_vec(), a));
2224 }
2225 // The witness knobs drop every other arm outright: on synthetic
2226 // content the whole block always wins its own comparison.
2227 if forced_rect != 0 {
2228 cands.retain(|c| c.2 == 1 || c.2 == 2);
2229 }
2230 if forced_ab != 0 {
2231 cands.retain(|c| c.2 == usize::from(forced_ab));
2232 }
2233 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
2234 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
2235 // superblock arm codes the delta_q group too -- the Whole64 writer
2236 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
2237 // with `!sb128_armed()`) and every smaller shape below it pass
2238 // `is_whole_sb = false` under a 128 grid, so the arm's first
2239 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
2240 // NONE root escapes it, so the split side is charged here at the same
2241 // root lambda the candidates are priced with.
2242 let split_dq =
2243 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
2244 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
2245 && (cost128
2246 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
2247 // The witness knobs take the root whatever it costs, so the
2248 // forced block really reaches the writer.
2249 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
2250 || forced_rect != 0
2251 || forced_ab != 0)
2252 {
2253 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
2254 blocks.truncate(mark128);
2255 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
2256 let at = (root_r * 2) * cols + root_c * 2;
2257 match shape {
2258 0 => {
2259 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2260 let block = halves.into_iter().next().expect("the NONE arm's block");
2261 record_mi(
2262 &mut grid,
2263 root_r * 16,
2264 root_c * 16,
2265 32,
2266 block.inter,
2267 block.skip,
2268 );
2269 blocks.push((at, Quadrant::Whole128(block)));
2270 }
2271 // lane-ab128: three pieces, published at their own footprints
2272 // in the writer's own order ([`ab128_pieces`]).
2273 symbol @ 4..=7 => {
2274 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2275 for (((mr, mc), (w, h)), piece) in
2276 ab128_pieces(symbol, (root_r * 16, root_c * 16))
2277 .iter()
2278 .zip(&halves)
2279 {
2280 record_mi_rect(
2281 &mut grid,
2282 *mr,
2283 *mc,
2284 (w / 4, h / 4),
2285 piece.inter,
2286 piece.skip,
2287 );
2288 }
2289 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
2290 }
2291 symbol => {
2292 let horz = symbol == 1;
2293 if horz {
2294 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2295 } else {
2296 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2297 }
2298 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
2299 for (i, half) in halves.iter().enumerate() {
2300 let (mr, mc) = if horz {
2301 (root_r * 16 + i * 16, root_c * 16)
2302 } else {
2303 (root_r * 16, root_c * 16 + i * 16)
2304 };
2305 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
2306 }
2307 blocks.push((at, Quadrant::Rect128(horz, halves)));
2308 }
2309 }
2310 for q in 1..16 {
2311 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
2312 blocks.push((r32 * cols + c32, Quadrant::Covered));
2313 }
2314 }
2315 }
2316 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
2317 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
2318 let luma_rect = (x0, y0, x1, y1);
2319 let chroma_rect = (x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
2320 let pixels = TilePixels {
2321 luma_rect,
2322 chroma_rect,
2323 luma: take_rect(&luma.reconstruction, frame_width, luma_rect),
2324 chroma: [
2325 take_rect(&chroma[0].reconstruction, frame_width / 2, chroma_rect),
2326 take_rect(&chroma[1].reconstruction, frame_width / 2, chroma_rect),
2327 ],
2328 };
2329 Ok((blocks, pixels))
2330 };
2331 // Each tile's rectangles are copied back on this thread, in tile order (the
2332 // rectangles partition the frame, so the order does not change the bytes).
2333 let mut searched_blocks = Vec::new();
2334 for (tile_blocks, pixels) in search_tiles(layout.count(), fctx, search_tile)? {
2335 put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma);
2336 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {
2337 put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes);
2338 }
2339 searched_blocks.push(tile_blocks);
2340 }
2341 for (at, quadrant) in searched_blocks.into_iter().flatten() {
2342 blocks[at] = quadrant;
2343 }
2344
2345 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
2346 // superblock roots the search left whole, so a flat BD result is
2347 // attributable (class `gate-blind-to-feature`). A key frame codes none:
2348 // only the inter writer has a 128x128 block.
2349 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
2350 let whole = blocks
2351 .iter()
2352 .filter(|q| matches!(q, Quadrant::Whole128(_)))
2353 .count();
2354 let roots = blocks
2355 .iter()
2356 .filter(|q| !matches!(q, Quadrant::Covered))
2357 .count();
2358 // lane-b128r: of those roots, how many code a REAL residual rather
2359 // than the skip-only block lane-b128 shipped -- the fire count this
2360 // arm's own gate row is read against.
2361 let residual = blocks
2362 .iter()
2363 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
2364 .count();
2365 // lane-b128r: and how many named a second reference (the compound
2366 // arm at the 128 root).
2367 let compound = blocks
2368 .iter()
2369 .filter(
2370 |q| matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())),
2371 )
2372 .count();
2373 // lane-b128hv: and how many roots took a rect cut instead, per shape
2374 // -- the HORZ/VERT fire count the gate rows are read against.
2375 let horz = blocks
2376 .iter()
2377 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
2378 .count();
2379 let vert = blocks
2380 .iter()
2381 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
2382 .count();
2383 let rect_compound = blocks
2384 .iter()
2385 .filter(|q| {
2386 matches!(q, Quadrant::Rect128(_, hs)
2387 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
2388 })
2389 .count();
2390 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
2391 // .. _VERT_B order -- the per-shape fire count its gate rows are read
2392 // against.
2393 let ab: [usize; 4] = std::array::from_fn(|i| {
2394 blocks
2395 .iter()
2396 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
2397 .count()
2398 });
2399 eprintln!(
2400 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
2401 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
2402 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
2403 {roots} coded blocks ({:.1}% of the frame's area at 128)",
2404 ab[0],
2405 ab[1],
2406 ab[2],
2407 ab[3],
2408 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
2409 / blocks.len().max(1) as f64,
2410 );
2411 }
2412 let modes = blocks
2413 .iter()
2414 .flat_map(Quadrant::blocks)
2415 .map(|b| b.mode)
2416 .collect::<Vec<_>>();
2417 let inter_block_share = blocks
2418 .iter()
2419 .flat_map(Quadrant::blocks)
2420 .filter(|b| b.inter.is_some())
2421 .count() as f64
2422 / modes.len() as f64;
2423 for block in blocks.iter().flat_map(Quadrant::blocks) {
2424 if let Some(info) = block.inter {
2425 let r = (info.ref_frame as usize).min(7);
2426 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2427 }
2428 }
2429 #[cfg(test)]
2430 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
2431 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
2432 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
2433 // next frame's writer starts from them -- exactly what
2434 // `crate::stream::stored_cdfs_for` hands the decoder.
2435 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
2436 let mut cdfs = start_cdfs
2437 .cloned()
2438 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
2439 // lane-txi: set per frame, never inherited from the snapshot the
2440 // previous frame stored -- the content gate can flip the bit between
2441 // frames (class `per-tile-state-not-reset`).
2442 cdfs.reduced_tx_set = header.reduced_tx_set;
2443 let start_cdfs = CdfSnapshot(cdfs);
2444 let reference_select_bit = header.reference_select;
2445 let switchable_motion_mode = header.is_motion_mode_switchable;
2446 let warped_motion = header.allow_warped_motion;
2447 let order_hint_bits = seq.order_hint_bits;
2448 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
2449 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
2450 // What this frame stores is the LARGEST tile's end-of-tile tables --
2451 // its own header's `context_update_tile_id` (spec 7.20), which
2452 // `tile_info_of` set to exactly that tile.
2453 let store_tile = layout.largest_tile();
2454 let end_cdfs = std::cell::RefCell::new(None);
2455 // As in `encode_key_frame_inner`: every tile starts from this frame's
2456 // own tables, so no tile depends on any other.
2457 let code_tiles = |bits: u8,
2458 sb_cols: usize,
2459 cdef_grid: &[u8],
2460 units: &[Option<crate::restoration::WienerInfo>]|
2461 -> Result<Vec<Vec<u8>>> {
2462 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
2463 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
2464 crate::tile::arm_delta_q(
2465 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
2466 sb_cols,
2467 sb_q.clone().unwrap_or_default(),
2468 base_q_idx,
2469 );
2470 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
2471 crate::tile::arm_sb128(sb128_on());
2472 crate::tile::arm_sign_bias(sign_bias);
2473 // Thread-locals: every tile job arms its own worker.
2474 crate::tile::arm_reference_select(reference_select_bit);
2475 crate::tile::arm_motion_mode(switchable_motion_mode);
2476 crate::tile::arm_warped_motion(warped_motion);
2477 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
2478 crate::tile::arm_high_precision_mv(hp_mv);
2479 crate::tile::arm_screen(screen);
2480 crate::tile::arm_frame_mi_dims(frame_mi_dims);
2481 crate::tile::arm_filter_intra(filter_intra_on());
2482 let mut cdfs = start_cdfs.0.clone();
2483 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
2484 // Each tile's own MV grid: a candidate scan never reaches past
2485 // the tile's bounds, so a grid holding only this tile's own
2486 // blocks reads exactly as the decoder's frame-wide one does
2487 // under `MiGrid::set_tile_bounds`.
2488 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2489 mv_grid.set_sign_bias(sign_bias);
2490 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
2491 mi_cols,
2492 mi_rows,
2493 base_q_idx,
2494 &blocks,
2495 tx_select,
2496 &mut cdfs,
2497 layout.rect(index),
2498 &mut mv_grid,
2499 )?;
2500 Ok((bytes, Some(cdfs)))
2501 })?;
2502 if let Some(cdfs) = stored {
2503 *end_cdfs.borrow_mut() = Some(cdfs);
2504 }
2505 Ok(out)
2506 };
2507 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
2508 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
2509 // this tile against the same single-slot reference this encoder predicted
2510 // from, under each candidate level.
2511 // The reference a DECODER holds is this frame's cropped size, not the
2512 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
2513 // reference whose height is not the header's own `frame_height` (spec
2514 // 7.9's compatible-size rule), and the chained-decode round trips prove
2515 // the two predict identically.
2516 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
2517 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
2518 reference.clone()
2519 } else {
2520 Picture {
2521 width: fw,
2522 height: fh,
2523 y: crop_plane(&reference.y, reference.width, fw, fh),
2524 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
2525 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
2526 }
2527 };
2528 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
2529 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
2530 // blocks may name GOLDEN needs that plane too, cropped the same way.
2531 let trial_golden = golden.map(|g| {
2532 if (g.width, g.height) == (fw, fh) {
2533 g.clone()
2534 } else {
2535 Picture {
2536 width: fw,
2537 height: fh,
2538 y: crop_plane(&g.y, g.width, fw, fh),
2539 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
2540 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
2541 }
2542 }
2543 });
2544 let trial_altref = altref.map(|a| {
2545 if (a.width, a.height) == (fw, fh) {
2546 a.clone()
2547 } else {
2548 Picture {
2549 width: fw,
2550 height: fh,
2551 y: crop_plane(&a.y, a.width, fw, fh),
2552 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
2553 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
2554 }
2555 }
2556 });
2557 let trial_last2 = last2.map(|l| {
2558 if (l.width, l.height) == (fw, fh) {
2559 l.clone()
2560 } else {
2561 Picture {
2562 width: fw,
2563 height: fh,
2564 y: crop_plane(&l.y, l.width, fw, fh),
2565 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
2566 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
2567 }
2568 }
2569 });
2570 let mut refs: [Option<&Picture>; 8] = [None; 8];
2571 refs[1] = Some(&trial_ref);
2572 refs[2] = trial_last2.as_ref();
2573 refs[4] = trial_golden.as_ref();
2574 refs[7] = trial_altref.as_ref();
2575 let refpix = crate::decode::RefPix::ready(refs);
2576 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
2577 // sum the block search believed it was minimising. Against the
2578 // post-filter per-frame PSNR the gate prints, this separates a trial
2579 // whose reconstruction is a lie from a filter stage that undoes the win.
2580 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
2581 let sse: u64 = luma
2582 .reconstruction
2583 .chunks(luma.width)
2584 .take(luma.true_height)
2585 .zip(picture_y8.chunks(luma.width))
2586 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
2587 .map(|(&r, &s)| {
2588 let d = i64::from(r) - i64::from(s);
2589 (d * d) as u64
2590 })
2591 .sum();
2592 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
2593 }
2594 let post = |luma: &Plane<'_>, tag: &str| {
2595 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
2596 return;
2597 }
2598 let sse: u64 = luma
2599 .reconstruction
2600 .chunks(luma.width)
2601 .take(luma.true_height)
2602 .zip(picture_y8.chunks(luma.width))
2603 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
2604 .map(|(&r, &s)| {
2605 let d = i64::from(r) - i64::from(s);
2606 (d * d) as u64
2607 })
2608 .sum();
2609 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
2610 };
2611 pick_and_apply_filters(
2612 &mut header,
2613 &mut luma,
2614 &mut chroma,
2615 [&picture_y8, &picture_u8, &picture_v8],
2616 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
2617 // this frame's own `tx_select`, so the search runs under inter
2618 // `TxMode::Select` too (it used to skip and leave every inter frame
2619 // unfiltered once Select became the default).
2620 true,
2621 &mut tiles,
2622 search.lambda,
2623 fctx,
2624 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
2625 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
2626 // are what the NEXT frame writes from, so the winning re-code
2627 // publishes its own into `end_cdfs` -- the first write's are stale
2628 // the moment a second tile is coded.
2629 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
2630 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
2631 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
2632 crate::decode::decode_inter_frame_tiles_lr(
2633 &payloads,
2634 &header_tile_info,
2635 h.mi_cols,
2636 h.mi_rows,
2637 base_q_idx,
2638 h.frame_width,
2639 h.frame_height,
2640 &refpix,
2641 cdef,
2642 lf,
2643 h.allow_high_precision_mv,
2644 h.force_integer_mv,
2645 Some(fctx.interp_filter.get()),
2646 seq.enable_dual_filter,
2647 h.reference_select,
2648 // lane-txi: this frame's own bit, not the hardcoded `true`
2649 // the wrapper used to pass.
2650 h.reduced_tx_set,
2651 tx_select,
2652 lr,
2653 // The trial decode re-reads the tile the writer just wrote,
2654 // so it starts from the same tables the writer did (this
2655 // frame's `start_cdfs`), not from the defaults.
2656 Some(start_cdfs.0.clone()),
2657 sign_bias,
2658 h.allow_screen_content_tools,
2659 switchable_motion_mode,
2660 h.allow_warped_motion,
2661 seq.enable_filter_intra,
2662 // lane-deltaq: this frame's own delta_q/delta_lf params, so
2663 // the trial decode reads the per-superblock `delta_qindex`
2664 // syntax the writer just wrote.
2665 h.delta,
2666 fctx,
2667 )
2668 },
2669 )?;
2670 post(&luma, "EC_POSTFILTER");
2671 let mut cdfs = end_cdfs
2672 .into_inner()
2673 .unwrap_or_else(|| start_cdfs.0.clone());
2674 cdfs.reset_counts();
2675 let next_cdfs = CdfSnapshot(cdfs);
2676 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
2677 header.tile_info.tile_size_bytes = tile_size_bytes;
2678 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
2679 let mut stream = temporal_delimiter();
2680 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
2681
2682 let [u, v] = chroma;
2683 Ok(Encoded {
2684 stream,
2685 modes,
2686 inter_block_share,
2687 reconstruction: Picture {
2688 width: luma.width,
2689 height: luma.height,
2690 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
2691 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
2692 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
2693 },
2694 tile,
2695 mi_cols: header.mi_cols,
2696 mi_rows: header.mi_rows,
2697 base_q_idx,
2698 tx_select,
2699 switchable_motion_mode,
2700 screen,
2701 reduced_tx_set: header.reduced_tx_set,
2702 start_cdfs: Box::new(start_cdfs),
2703 next_cdfs: Box::new(next_cdfs),
2704 loop_filter: header.loop_filter,
2705 cdef: header.cdef,
2706 loop_restoration: header.loop_restoration,
2707 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
2708 // intra frames only).
2709 allow_intrabc: false,
2710 delta: header.delta,
2711 })
2712}
2713
2714/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
2715/// frame's temporal unit followed by one inter frame's temporal unit per
2716/// remaining picture, all sharing the key frame's sequence header -- and
2717/// each frame's own [`Encoded`], in coding order.
2718#[derive(Clone, Debug)]
2719pub struct EncodedSequence {
2720 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
2721 /// sequence header and the key frame) followed by each later frame's
2722 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
2723 /// the sequence header the key frame carried).
2724 pub stream: Vec<u8>,
2725 /// One entry per picture, in DISPLAY order — the order a decoder outputs
2726 /// them and the order `pictures` came in. Without a pyramid that is also
2727 /// the coding order; with one the two differ, and `coding_order` is the
2728 /// map between them.
2729 pub frames: Vec<Encoded>,
2730 /// The index into `frames` of each coded frame, in CODING order — what a
2731 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
2732 /// `0..frames.len()` on the flat path.
2733 pub coding_order: Vec<usize>,
2734}
2735
2736/// Encodes a sequence of pictures as a key frame followed by one inter frame
2737/// per remaining picture, each predicting from the previous frame's own
2738/// decoded reconstruction — never from the source, which is what a decoder
2739/// cannot see. Every picture must be the same even size (any even width and
2740/// height — each is padded to a whole number of 64x64 superblocks
2741/// internally, which is what lets an inter frame's reference always match
2742/// the frame being coded against it), and `pictures` must be non-empty.
2743///
2744/// # Errors
2745/// Returns an error when `pictures` is empty, when any picture besides the
2746/// first is not the same size as the first, or under the same conditions
2747/// [`encode_key_frame`] and the inter frame path do.
2748pub(crate) fn encode_sequence_with_ctx(
2749 pictures: &[Picture],
2750 base_q_idx: u8,
2751 deadzone: f64,
2752 fctx: &crate::decode::FrameCtx,
2753) -> Result<EncodedSequence> {
2754 let Some((first, rest)) = pictures.split_first() else {
2755 return Err(Error::unsupported(
2756 "AV1 encode",
2757 "a sequence needs at least one picture",
2758 ));
2759 };
2760 first.check_even()?;
2761 let render = (first.width, first.height);
2762 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
2763 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
2764 // the leaves that predict backward off it, and a `show_existing_frame`
2765 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
2766 // an A/B. Screen content stays flat (the content gate in
2767 // `Av1Encoder::encode_frames`, whose detector this asks first so the
2768 // whole sequence path is decided in one place), and so does a run that
2769 // asks for a quantizer rounding offset the facade does not carry: the
2770 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
2771 // the ablations' -- must keep the flat path rather than be silently
2772 // ignored.
2773 //
2774 // The reordering itself is NOT reimplemented here: it is the facade's
2775 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
2776 // called with this sequence's shape, so the two paths cannot drift.
2777 let pyramid = crate::encoder::Pyramid::from_env()
2778 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
2779 .filter(|_| !picture_is_screen(first));
2780 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
2781 if let Some(pyramid) = pyramid {
2782 for picture in rest {
2783 picture.check_even()?;
2784 if (picture.width, picture.height) != render {
2785 return Err(Error::unsupported(
2786 "AV1 encode",
2787 "every picture in a sequence must be the same size as the first",
2788 ));
2789 }
2790 }
2791 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
2792 pictures,
2793 base_q_idx,
2794 pyramid,
2795 armed_tiles(),
2796 );
2797 }
2798 // The key frame and every inter frame after it are coded at the same
2799 // padded size, so the reference each inter frame predicts from -- the
2800 // previous frame's own uncropped reconstruction, at the size a decoder's
2801 // reference buffer actually holds -- always matches the frame being
2802 // coded against it.
2803 let key = encode_key_frame_inner(
2804 &first.padded_to(SUPERBLOCK),
2805 base_q_idx,
2806 deadzone,
2807 &KEY_FRAME_MODES,
2808 split_blocks(),
2809 render,
2810 unspecified_color_config(),
2811 fctx,
2812 )?;
2813 let mut stream = key.stream.clone();
2814 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
2815 // key frame refreshes every slot, each inter frame only slot 0), which is
2816 // what `GOLDEN_FRAME` names.
2817 let golden = key.reconstruction.clone();
2818 // The frame two back, once there is one that is not the key frame
2819 // itself (which `GOLDEN_FRAME` already names).
2820 let mut prev2: Option<Picture> = None;
2821 let mut carried = key.next_cdfs.clone();
2822 let mut reference = key.reconstruction.clone();
2823 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
2824 for (i, picture) in rest.iter().enumerate() {
2825 picture.check_even()?;
2826 // lane-av1tpl2: the lookahead window the per-block lambda weighting
2827 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
2828 // sources at this frame's coded (padded) size. The tail of the
2829 // sequence gets a shorter window, and the last frame none at all.
2830 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
2831 .iter()
2832 .take(tpl_depth() - 1)
2833 .map(|n| n.padded_to(SUPERBLOCK))
2834 .collect();
2835 if (picture.width, picture.height) != render {
2836 return Err(Error::unsupported(
2837 "AV1 encode",
2838 "every picture in a sequence must be the same size as the first",
2839 ));
2840 }
2841 let order_hint = (i + 1) as u32;
2842 let inter = encode_inter_frame(
2843 &picture.padded_to(SUPERBLOCK),
2844 &reference,
2845 base_q_idx,
2846 deadzone,
2847 order_hint,
2848 flat_order_hints(order_hint, 0, prev2.is_some()),
2849 render,
2850 Some(&carried.0),
2851 Some(&golden),
2852 prev2.as_ref(),
2853 None,
2854 fctx,
2855 None,
2856 &lookahead,
2857 )?;
2858 stream.extend_from_slice(&inter.stream);
2859 carried = inter.next_cdfs.clone();
2860 prev2 = Some(std::mem::replace(
2861 &mut reference,
2862 inter.reconstruction.clone(),
2863 ));
2864 frames.push(crop_encoded(&inter, render.0, render.1));
2865 }
2866 Ok(EncodedSequence {
2867 stream,
2868 coding_order: (0..frames.len()).collect(),
2869 frames,
2870 })
2871}