forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

syntax.rs2521 lines, 112.2 KiBHistoryRawDownload
1use super::*;
2
3/// One quantised coefficient of a transform block.
4///
5/// `row` and `col` are its position in the transform it belongs to — 32x32 for
6/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
7/// row 0 varies along the picture's width and one at column 0 along its
8/// height, and the coefficient at the origin is the DC the block's average
9/// sample value rides on.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct Coeff {
12 /// The coefficient's row in the transform.
13 pub row: u8,
14 /// The coefficient's column in the transform.
15 pub col: u8,
16 /// Its quantised level, which the base and base-range syntax carry for
17 /// magnitudes up to [`MAX_LEVEL`].
18 pub level: i32,
19}
20
21/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
22/// the 16x16 transform each chroma plane covers the same area with.
23#[derive(Clone, Debug, Default, PartialEq, Eq)]
24pub struct BlockCoeffs {
25 /// The luma transform's coefficients.
26 pub luma: Vec<Coeff>,
27 /// One transform type per luma transform unit, raster order (lane-txset).
28 /// Empty is `DCT_DCT` throughout -- what every block coded before the
29 /// search offered a type, and what an inter block still carries.
30 pub luma_tx_types: Vec<TxType>,
31 /// The U plane's.
32 pub u: Vec<Coeff>,
33 /// The V plane's.
34 pub v: Vec<Coeff>,
35 /// The luma intra mode the block is predicted with, one of the thirteen
36 /// modes a key frame codes (`DC_PRED` is zero, which is what
37 /// [`Default`] and a plain coefficient list give).
38 pub mode: u8,
39 /// The chroma intra mode both chroma planes are predicted with (spec
40 /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
41 /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
42 /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
43 /// 9.3), which is never coded as a symbol.
44 pub uv_mode: u8,
45 /// Whether the block carries no residual at all (spec `skip`). An intra
46 /// block may still be skipped; `false` (the [`Default`]) codes whatever
47 /// `luma`/`u`/`v` carry.
48 pub skip: bool,
49 /// The block's inter mode and motion vector, or `None` for an intra
50 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
51 /// frame writers never read this field.
52 pub inter: Option<InterInfo>,
53 /// This (single-reference inter) block's spec `motion_mode`, written by
54 /// [`write_motion_mode`]: 0 `SIMPLE_TRANSLATION` (the [`Default`], and
55 /// the only mode this writer coded before lane-av1obmc), 1 `OBMC_CAUSAL`,
56 /// 2 `WARPED_CAUSAL` (lane-av1obmc2).
57 pub motion_mode: u8,
58 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
59 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
60 /// raster order among the leaves that are inside the true frame. `Some`
61 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
62 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
63 /// per-quadrant fields are unused.
64 pub eight: Option<Vec<BlockCoeffs>>,
65 /// The luma palette this block is predicted with (spec 5.11.46
66 /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
67 /// `DC_PRED` block on a frame whose header set
68 /// `allow_screen_content_tools` may carry one, and it forces
69 /// `tx_depth` to zero (the whole block is one transform over the
70 /// palette's own prediction).
71 pub palette: Option<PaletteY>,
72 /// The chroma palette this block's two chroma planes are predicted with
73 /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
74 /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
75 /// one; it is independent of [`Self::palette`] (either, both or neither).
76 pub palette_uv: Option<PaletteUv>,
77 /// How many times this block's luma transform is halved under
78 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
79 /// block). Read only by the writers a `tx_select` frame calls; a
80 /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
81 /// `luma` then carries the whole block's levels in BLOCK coordinates,
82 /// which the writer slices per transform unit.
83 pub tx_depth: u8,
84 /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec
85 /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for
86 /// any other chroma mode. `Some` iff [`Self::uv_mode`] is
87 /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint
88 /// sign symbol has no (ZERO, ZERO) value.
89 pub cfl_alphas: Option<(i32, i32)>,
90 /// This block's `filter_intra_mode` (spec 5.11.14, 0..=4) when it is
91 /// coded with recursive filter intra, or `None`. `Some` only on a DC_PRED
92 /// luma block of at most 32x32 with no luma palette, on a sequence whose
93 /// header set `enable_filter_intra` ([`arm_filter_intra`]); the block's
94 /// luma transform types are then coded from
95 /// `fimode_to_intradir[filter_intra_mode]`'s row ([`tx_row`]) while its
96 /// neighbour mode stays `DC_PRED`.
97 pub filter_intra: Option<u8>,
98 /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3),
99 /// zero for every non-directional luma mode -- which is what
100 /// [`Default`] gives, and what every writer coded before lane-av1cfl.
101 pub angle_delta_y: i8,
102 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
103 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
104 /// an ordinary intra block. Only a key frame whose header set
105 /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
106 /// coded `skip` with no residual, no mode, no palette -- exactly what
107 /// decode.rs `read_intra_mode` reads back and returns early on.
108 ///
109 /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
110 /// block needs the INTER coefficient tables plus the var-tx tree
111 /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
112 /// is to route the block through [`write_tx_syntax_inter`] instead of
113 /// returning early here.
114 pub dv: Option<(i32, i32)>,
115}
116
117/// A block's luma palette: its base colours (ascending, only the first
118/// `size` entries are real) and the per-pixel colour-index map, `side*side`
119/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
120/// out of the stream.
121#[derive(Clone, Debug, Default, PartialEq, Eq)]
122pub struct PaletteY {
123 /// How many base colours, 2..=8 (spec `PaletteSizeY`).
124 pub size: u8,
125 /// The base colours, ascending.
126 pub colors: [u16; 8],
127 /// Which colour each pixel takes, row-major over the block's own side.
128 pub map: Vec<u8>,
129}
130
131/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
132/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
133/// are co-located after 4:2:0 subsampling) plus each plane's own base
134/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
135/// the stream.
136#[derive(Clone, Debug, Default, PartialEq, Eq)]
137pub struct PaletteUv {
138 /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
139 pub size: u8,
140 /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
141 /// merges the cached and transmitted lists as two ascending runs, and its
142 /// delta form only ever steps upwards.
143 pub u_colors: [u16; 8],
144 /// V's base colours, in the same cluster order as [`Self::u_colors`] --
145 /// the shared map indexes both, and V's own coding needs no ordering.
146 pub v_colors: [u16; 8],
147 /// Which colour each chroma pixel takes, row-major over the subsampled
148 /// block's own `(side / 2).max(4)` side.
149 pub map: Vec<u8>,
150}
151
152/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
153/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
154/// [`write_inter_mode`] with the decoder's own contexts.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum InterMode {
157 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
158 NearestMv,
159 /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
160 /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
161 NearMv,
162 /// `GLOBALMV`: the identity global model's zero vector, two symbols and
163 /// no MV at all.
164 GlobalMv,
165 /// `NEWMV`: codes `mv` as a residual against the stack entry
166 /// [`InterInfo::ref_mv_idx`] names.
167 NewMv,
168 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
169 /// pair, no residual, no DRL.
170 NearestNearestMv,
171 /// `NEAR_NEARMV`: both sides take compound stack entry
172 /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
173 /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
174 NearNearMv,
175 /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
176 /// second codes a residual against stack entry 0.
177 NearestNewMv,
178 /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
179 /// the second takes the stack's nearest vector.
180 NewNearestMv,
181 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
182 /// vector.
183 GlobalGlobalMv,
184 /// `NEW_NEWMV`: both sides code a residual against the compound stack
185 /// entry [`InterInfo::ref_mv_idx`] names.
186 NewNewMv,
187}
188
189impl InterMode {
190 /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
191 /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
192 /// for a single-reference one.
193 pub(super) fn compound_index(self) -> Option<usize> {
194 match self {
195 InterMode::NearestNearestMv => Some(0),
196 InterMode::NearNearMv => Some(1),
197 InterMode::NearestNewMv => Some(2),
198 InterMode::NewNearestMv => Some(3),
199 InterMode::GlobalGlobalMv => Some(6),
200 InterMode::NewNewMv => Some(7),
201 _ => None,
202 }
203 }
204}
205
206/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
207/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
208/// and codes the stack's own candidate instead — the decoder derives it, so
209/// nothing here can disagree with it.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub struct InterInfo {
212 /// The mode this block is coded with.
213 pub mode: InterMode,
214 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
215 pub mv: (i32, i32),
216 /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
217 /// spec 6.10.24's alphabet), written by [`write_single_ref`].
218 pub ref_frame: i8,
219 /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
220 /// `MvStack::entries` slot `NEWMV` codes its residual against, or
221 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
222 /// index (`NEARESTMV`, `GLOBALMV`).
223 pub ref_mv_idx: u8,
224 /// The block's second reference (spec `RefFrames[1]`), `None` for a
225 /// single-reference block. `Some` only on a `reference_select` frame, and
226 /// only beside one of [`InterMode`]'s compound modes.
227 pub ref1: Option<i8>,
228 /// The motion vector into `ref1`, for the compound modes that code one
229 /// (`NEW_NEWMV`); the other two derive both sides.
230 pub mv1: (i32, i32),
231}
232
233impl From<Vec<Coeff>> for BlockCoeffs {
234 /// A block that codes luma only.
235 fn from(luma: Vec<Coeff>) -> Self {
236 Self {
237 luma,
238 ..Self::default()
239 }
240 }
241}
242
243/// Side of the luma transform the coefficient writer codes.
244pub(super) const TX32: usize = 32;
245/// Side of the larger of the two blocks a superblock splits into, in samples.
246pub(super) const BLOCK: usize = 32;
247/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
248/// of a 16x16 block.
249pub(super) const TX16: usize = 16;
250/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
251/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
252pub(super) const TX8: usize = 8;
253/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
254pub(super) const TX4: usize = 4;
255/// Side of a superblock, in samples, which is the size a block outside the
256/// tile reads as.
257pub(super) const SB: usize = 64;
258
259/// The `above_side`/`left_side` value a cell with no coded neighbour holds
260/// (tile start, superblock-row start) -- the writer's copy of
261/// `crate::decode::NO_NEIGHBOUR_SIDE`, and 128 for the same reason: at 64 it
262/// reads identically at every level up to 64x64 but sets the bit at the
263/// `BLOCK_128X128` root (64 * 2 <= 128), putting that root's partition symbol
264/// on CDF row 3 where libaom uses row 0.
265pub(super) const NO_NEIGHBOUR_SIDE: usize = 128;
266/// Side of the smallest block the writer codes, in samples, which is the grid
267/// the neighbour bookkeeping is kept on.
268pub(super) const SUB: usize = 16;
269/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
270/// and left entropy-context arrays are actually kept on (spec
271/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
272pub(super) const MI: usize = 4;
273
274/// What one coded block leaves behind for the blocks that read it as a
275/// neighbour: whether it coded anything at all, and the sign of its DC.
276#[derive(Clone, Copy, Default)]
277pub(super) struct Neighbour {
278 /// Whether the plane's transform block carried a coefficient.
279 pub(super) coded: bool,
280 /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
281 /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
282 /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
283 /// where "coded or not" is not enough.
284 pub(super) level: u8,
285 /// The sign of its DC, absent when the DC itself is zero.
286 pub(super) dc: Option<bool>,
287}
288
289/// Rejects a frame with no mode-info grid at all.
290///
291/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
292/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
293/// grid: a block whose origin sits at or past this bound is not coded (spec's
294/// `decode_partition` never visits it), and one that straddles the bound is
295/// coded whole, its samples coming from the padded planes.
296pub(super) fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
297 if mi_cols == 0 || mi_rows == 0 {
298 return Err(Error::unsupported(
299 "AV1 tile",
300 "a coefficient key frame needs a nonzero mode-info grid",
301 ));
302 }
303 Ok(())
304}
305
306/// The coefficients of one superblock: either one 64x64 block covering it, or
307/// the four 32x32 blocks it is split into.
308///
309/// A superblock at the right-hand or bottom edge of the frame may be half
310/// outside it, and such a superblock cannot be left whole — the spec has no
311/// partition that keeps a block outside the frame — so it must be
312/// [`Split`](Superblock::Split), and carries only the quadrants that are
313/// inside, in raster order among themselves.
314// Whole is the common case; boxing it would add an allocation per superblock on the decode path.
315#[allow(clippy::large_enum_variant)]
316#[derive(Clone, Debug, PartialEq, Eq)]
317pub enum Superblock {
318 /// One 64x64 block, whose luma transform is 64x64 — of which only the
319 /// top-left 32x32 carries coefficients — and whose chroma transforms are
320 /// 32x32 each at 4:2:0.
321 Whole(BlockCoeffs),
322 /// The 32x32 quadrants the superblock is split into, each either one
323 /// block or four 16x16 blocks of its own.
324 Split(Vec<Quadrant>),
325}
326
327/// One 32x32 quadrant of a split superblock.
328#[derive(Clone, Debug, PartialEq, Eq)]
329pub enum Quadrant {
330 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
331 /// chroma plane.
332 Whole(BlockCoeffs),
333 /// The four 16x16 blocks it is split into, in raster order, each with a
334 /// 16x16 luma transform and an 8x8 transform per chroma plane.
335 Split(Vec<BlockCoeffs>),
336 /// lane-b64: not a quadrant at all -- the whole 64x64 superblock this
337 /// quadrant is the TOP-LEFT of, coded as one block (`PARTITION_NONE` at
338 /// `BLOCK_64X64`). Only the top-left quadrant of a superblock carries it
339 /// and the other three carry [`Covered`](Quadrant::Covered), so the
340 /// per-32x32-entry shape the inter writer takes is unchanged.
341 ///
342 /// The block is single-reference; the writer refuses a compound one. It
343 /// may be skipped or carry a real residual -- one TX_64X64 luma transform
344 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
345 /// plane (lane-tx64, `crate::encode::b64_residual`).
346 Whole64(BlockCoeffs),
347 /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
348 /// top-left of, coded as one block (`PARTITION_NONE` at the root's
349 /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
350 /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
351 ///
352 /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
353 /// interleaved with its chroma per 64x64 mu chunk, which this writer has
354 /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
355 Whole128(BlockCoeffs),
356 /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a
357 /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the
358 /// order the decoder reads them (top then bottom, left then right).
359 /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
360 /// [`Whole128`](Quadrant::Whole128) is.
361 ///
362 /// Skip-only by default; a piece carries a real residual under
363 /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
364 /// compound either way.
365 Rect128(bool, Vec<BlockCoeffs>),
366 /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
367 /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
368 /// the order the decoder reads them
369 /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol
370 /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the
371 /// top-left 32x32 entry of the root's sixteen, exactly as
372 /// [`Rect128`](Quadrant::Rect128) is.
373 ///
374 /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
375 /// three pieces may carry a real residual.
376 Ab128(u8, Vec<BlockCoeffs>),
377 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
378 /// top-left already coded; it carries no block of its own.
379 Covered,
380}
381
382impl Quadrant {
383 /// The blocks it carries, in the order they are coded.
384 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
385 match self {
386 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
387 std::slice::from_ref(block)
388 }
389 Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) | Quadrant::Ab128(_, blocks) => {
390 blocks.as_slice()
391 }
392 Quadrant::Covered => &[],
393 }
394 }
395}
396
397/// What the blocks above and to the left of the one being coded left behind,
398/// kept on the 16x16 grid the smallest block sits on.
399pub(super) struct Neighbours {
400 /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
401 /// `MiColStart`): every "is there a neighbour above/left of me" answer is
402 /// TILE-relative, not frame-relative -- the decoder's own
403 /// `Neighbours::start_tile` sets the same pair, and a writer that asked
404 /// `mi_row > 0` instead coded a tile's own first row against a neighbour
405 /// the decoder does not have (class: new map ignores tile edge).
406 pub(super) tile_row0_mi: usize,
407 pub(super) tile_col0_mi: usize,
408 /// Per plane, whether the neighbour coded anything and the sign of its DC.
409 pub(super) above: Vec<[Neighbour; 3]>,
410 /// The same, down the left edge.
411 pub(super) left: Vec<[Neighbour; 3]>,
412 /// The neighbour's luma intra mode, which picks the CDF the next block's
413 /// mode is coded with.
414 pub(super) above_mode: Vec<usize>,
415 /// The same, down the left edge.
416 pub(super) left_mode: Vec<usize>,
417 /// The side of the neighbour block, in samples, which is what the
418 /// partition symbol's context reads.
419 pub(super) above_side: Vec<usize>,
420 /// The same, down the left edge.
421 pub(super) left_side: Vec<usize>,
422 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
423 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
424 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
425 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
426 /// leaf's partition symbol that the first one was coded at 8x8 (finer
427 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
428 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
429 /// which libaom keeps per mi unit for this reason).
430 pub(super) above_side_mi: Vec<usize>,
431 /// The same, down the left edge.
432 pub(super) left_side_mi: Vec<usize>,
433 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
434 /// skip context. Unused (and left at its default) by the key frame writers.
435 /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the
436 /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a
437 /// 16x16 read (and leave) different contexts inside one [`SUB`] slot.
438 pub(super) above_skip: Vec<bool>,
439 /// The same, down the left edge.
440 pub(super) left_skip: Vec<bool>,
441 /// The side, in pixels, of the transform last written in this 4x4
442 /// mode-info column -- the deblock `tx_grid` a key frame's
443 /// `get_tx_size_context` reads (decode.rs `tx_size_context_txfm`/`tx_px_at`),
444 /// which is what picks the CDF row of a `TxMode::Select` block's
445 /// `tx_depth` symbol.
446 pub(super) above_tx: Vec<u8>,
447 /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
448 /// every transform this writer codes is square, so one value serves).
449 pub(super) left_tx: Vec<u8>,
450 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
451 /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
452 /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
453 /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
454 /// zero (decode.rs `TXFM_CTX_INIT`).
455 pub(super) above_txfm: Vec<u8>,
456 /// The same, down the left edge (transform HEIGHT).
457 pub(super) left_txfm: Vec<u8>,
458 /// The palette size each 4x4 mode-info column last left behind, and its
459 /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
460 /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
461 /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
462 /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
463 /// frame writes them, `0` when it took no palette, so a stale size never
464 /// survives into the next block's context.
465 pub(super) above_palette_size: Vec<u8>,
466 /// The same, down the left edge.
467 pub(super) left_palette_size: Vec<u8>,
468 /// What the block being written right now will leave in the two palette
469 /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
470 /// block of either frame type passes through, so an inter block (or an
471 /// intra block that took no palette) clears the bands rather than letting
472 /// an earlier palette block's size stand (the neighbour-band hazard
473 /// lane-t900 r23 hit on the decoder side).
474 pub(super) pending_palette: Option<(u8, [u16; 8])>,
475 /// The colours beside [`Self::above_palette_size`].
476 pub(super) above_palette_colors: Vec<[u16; 8]>,
477 /// The chroma (U-channel) halves of the three bands above --
478 /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
479 /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
480 pub(super) above_palette_uv_size: Vec<u8>,
481 pub(super) left_palette_uv_size: Vec<u8>,
482 pub(super) above_palette_uv_colors: Vec<[u16; 8]>,
483 pub(super) left_palette_uv_colors: Vec<[u16; 8]>,
484 /// [`Self::pending_palette`] for the chroma palette.
485 pub(super) pending_palette_uv: Option<(u8, [u16; 8])>,
486 /// The same, down the left edge.
487 pub(super) left_palette_colors: Vec<[u16; 8]>,
488 /// Whether the neighbour was coded inter, for the `is_inter` context.
489 /// Unused by the key frame writers.
490 pub(super) above_inter: Vec<bool>,
491 /// The same, down the left edge.
492 pub(super) left_inter: Vec<bool>,
493 /// The reference each neighbour named, `-1` for an intra or unavailable
494 /// one -- what the decoder keeps in its own `Neighbours::above_ref`
495 /// (decode.rs) and feeds `read_single_ref`'s context functions.
496 pub(super) above_ref: Vec<i8>,
497 /// The same, down the left edge.
498 pub(super) left_ref: Vec<i8>,
499 /// Each neighbour's SECOND reference, `None` for a single-reference or
500 /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
501 /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
502 /// `comp_ref`/`comp_bwdref` votes).
503 pub(super) above_ref1: Vec<Option<i8>>,
504 /// The same, down the left edge.
505 pub(super) left_ref1: Vec<Option<i8>>,
506 /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
507 /// neighbour's own `comp_group_idx`, or libaom's single-reference special
508 /// case (`3` for an ALTREF block, `0` otherwise).
509 pub(super) above_comp_group_idx: Vec<u8>,
510 /// The same, down the left edge.
511 pub(super) left_comp_group_idx: Vec<u8>,
512 /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
513 pub(super) above_compound_idx: Vec<u8>,
514 /// The same, down the left edge.
515 pub(super) left_compound_idx: Vec<u8>,
516 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
517 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
518 /// `av1_set_entropy_contexts`): a block whose row or column run spills
519 /// past this bound leaves its trailing 4x4 units at their default,
520 /// mid-cell if need be.
521 pub(super) mi_cols: usize,
522 pub(super) mi_rows: usize,
523}
524
525/// What one plane's neighbours leave for a block, gathered across every cell
526/// the block spans -- which is what the decoder's own derivation reads
527/// (spec 5.11.39), and what a single cell only stands in for while every block
528/// is the same size.
529#[derive(Clone, Copy, Default)]
530pub(super) struct Around {
531 /// Whether any transform block above this one carried a coefficient.
532 pub(super) above_coded: bool,
533 /// The same, to the left.
534 pub(super) left_coded: bool,
535 /// The running vote of the neighbours' DC signs: negative DCs count down,
536 /// positive ones up, and a neighbour with no DC does not count.
537 pub(super) dc_vote: i32,
538}
539
540impl Neighbours {
541 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
542 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
543 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
544 /// mode-info units.
545 pub(super) fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
546 Self {
547 tile_row0_mi: 0,
548 tile_col0_mi: 0,
549 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
550 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
551 above_mode: vec![DC_PRED; cols],
552 left_mode: vec![DC_PRED; rows],
553 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
554 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
555 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
556 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
557 above_skip: vec![false; cols * (SUB / MI)],
558 left_skip: vec![false; rows * (SUB / MI)],
559 above_inter: vec![false; cols * (SUB / MI)],
560 left_inter: vec![false; rows * (SUB / MI)],
561 above_ref: vec![-1; cols * (SUB / MI)],
562 left_ref: vec![-1; rows * (SUB / MI)],
563 above_ref1: vec![None; cols * (SUB / MI)],
564 left_ref1: vec![None; rows * (SUB / MI)],
565 above_comp_group_idx: vec![0; cols * (SUB / MI)],
566 left_comp_group_idx: vec![0; rows * (SUB / MI)],
567 above_compound_idx: vec![0; cols * (SUB / MI)],
568 left_compound_idx: vec![0; rows * (SUB / MI)],
569 above_tx: vec![0; cols * (SUB / MI)],
570 left_tx: vec![0; rows * (SUB / MI)],
571 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
572 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
573 above_palette_size: vec![0; cols * (SUB / MI)],
574 left_palette_size: vec![0; rows * (SUB / MI)],
575 pending_palette: None,
576 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
577 above_palette_uv_size: vec![0; cols * (SUB / MI)],
578 left_palette_uv_size: vec![0; rows * (SUB / MI)],
579 above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
580 left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
581 pending_palette_uv: None,
582 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
583 mi_cols,
584 mi_rows,
585 }
586 }
587
588 /// Clears the left edge, which a tile starts every superblock row with.
589 /// Points this writer's availability answers at one tile
590 /// ([`Self::tile_row0_mi`]).
591 pub(super) fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
592 self.tile_row0_mi = row0_mi;
593 self.tile_col0_mi = col0_mi;
594 }
595
596 /// Whether the block at mode-info row `mi_r` has a neighbour above it
597 /// INSIDE its own tile, and the same to the left.
598 pub(super) fn has_above(&self, mi_r: usize) -> bool {
599 mi_r > self.tile_row0_mi
600 }
601
602 pub(super) fn has_left(&self, mi_c: usize) -> bool {
603 mi_c > self.tile_col0_mi
604 }
605
606 pub(super) fn start_row(&mut self) {
607 self.left.iter_mut().for_each(|l| *l = Default::default());
608 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
609 self.left_side
610 .iter_mut()
611 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
612 self.left_side_mi
613 .iter_mut()
614 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
615 self.left_skip.iter_mut().for_each(|s| *s = false);
616 self.left_inter.iter_mut().for_each(|i| *i = false);
617 self.left_ref.iter_mut().for_each(|r| *r = -1);
618 self.left_ref1.iter_mut().for_each(|r| *r = None);
619 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
620 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
621 self.left_tx.iter_mut().for_each(|t| *t = 0);
622 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
623 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
624 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
625 self.left_palette_uv_colors
626 .iter_mut()
627 .for_each(|c| *c = [0u16; 8]);
628 }
629
630 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
631 /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
632 /// `palette_y_mode` context (how many of the two neighbours took a
633 /// palette) and the ascending, deduplicated colour cache the neighbours
634 /// offer. `mi` is the block's own position in 4x4 units; this writer
635 /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
636 /// availability terms read against.
637 pub(super) fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
638 // `av1_get_palette_cache` drops the above neighbour on a 64-px
639 // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
640 // not, which is why the two terms below are asked separately.
641 let above_ok = r % 16 != 0;
642 let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
643 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
644 (
645 usize::from(self.above_palette_size[c]),
646 self.above_palette_colors[c],
647 )
648 } else {
649 (0, [0u16; 8])
650 };
651 let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
652 (
653 usize::from(self.left_palette_size[r]),
654 self.left_palette_colors[r],
655 )
656 } else {
657 (0, [0u16; 8])
658 };
659 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
660 let mut cache = Vec::with_capacity(16);
661 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
662 if cache.last() != Some(&v) {
663 cache.push(v);
664 }
665 };
666 let (mut ai, mut li) = (0usize, 0usize);
667 while ai < above_n && li < left_n {
668 let (va, vl) = (above_colors[ai], left_colors[li]);
669 if vl < va {
670 push_dedup(&mut cache, vl);
671 li += 1;
672 } else {
673 push_dedup(&mut cache, va);
674 ai += 1;
675 if vl == va {
676 li += 1;
677 }
678 }
679 }
680 while ai < above_n {
681 push_dedup(&mut cache, above_colors[ai]);
682 ai += 1;
683 }
684 while li < left_n {
685 push_dedup(&mut cache, left_colors[li]);
686 li += 1;
687 }
688 (ctx, cache)
689 }
690
691 /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
692 /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
693 /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
694 /// neighbour lookup at all (it is this block's own just-decided Y palette
695 /// use), so only the cache is wanted here.
696 pub(super) fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
697 let above_ok = r % 16 != 0;
698 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
699 (
700 usize::from(self.above_palette_uv_size[c]),
701 self.above_palette_uv_colors[c],
702 )
703 } else {
704 (0, [0u16; 8])
705 };
706 let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
707 (
708 usize::from(self.left_palette_uv_size[r]),
709 self.left_palette_uv_colors[r],
710 )
711 } else {
712 (0, [0u16; 8])
713 };
714 let mut cache = Vec::with_capacity(16);
715 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
716 if cache.last() != Some(&v) {
717 cache.push(v);
718 }
719 };
720 let (mut ai, mut li) = (0usize, 0usize);
721 while ai < above_n && li < left_n {
722 let (va, vl) = (above_colors[ai], left_colors[li]);
723 if vl < va {
724 push_dedup(&mut cache, vl);
725 li += 1;
726 } else {
727 push_dedup(&mut cache, va);
728 ai += 1;
729 if vl == va {
730 li += 1;
731 }
732 }
733 }
734 while ai < above_n {
735 push_dedup(&mut cache, above_colors[ai]);
736 ai += 1;
737 }
738 while li < left_n {
739 push_dedup(&mut cache, left_colors[li]);
740 li += 1;
741 }
742 cache
743 }
744
745 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
746 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
747 /// way, and the span is in LUMA pixels for both planes' bands alike.
748 pub(super) fn record_palette_uv(
749 &mut self,
750 (r, c): (usize, usize),
751 (w, h): (usize, usize),
752 size: u8,
753 colors: [u16; 8],
754 ) {
755 // lane-b128hv: the above band spans the block's WIDTH and the left
756 // band its HEIGHT; identical to the one loop this replaces at w == h.
757 for cell in 0..(w / MI).max(1) {
758 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
759 *e = size;
760 if size > 0 {
761 self.above_palette_uv_colors[c + cell] = colors;
762 }
763 }
764 }
765 for cell in 0..(h / MI).max(1) {
766 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
767 *e = size;
768 if size > 0 {
769 self.left_palette_uv_colors[r + cell] = colors;
770 }
771 }
772 }
773 }
774
775 /// What a just-written block leaves in the palette bands (decode.rs
776 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
777 /// spans, `0` for a block that took no palette.
778 pub(super) fn record_palette_y(
779 &mut self,
780 (r, c): (usize, usize),
781 (w, h): (usize, usize),
782 size: u8,
783 colors: [u16; 8],
784 ) {
785 // lane-b128hv: the above band spans the block's WIDTH and the left
786 // band its HEIGHT; identical to the one loop this replaces at w == h.
787 for cell in 0..(w / MI).max(1) {
788 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
789 *e = size;
790 if size > 0 {
791 self.above_palette_colors[c + cell] = colors;
792 }
793 }
794 }
795 for cell in 0..(h / MI).max(1) {
796 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
797 *e = size;
798 if size > 0 {
799 self.left_palette_colors[r + cell] = colors;
800 }
801 }
802 }
803 }
804
805 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
806 /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
807 /// resolved transform size over the span `(w_px, h_px)`, which for a
808 /// SKIPPED inter block is its own block size instead.
809 pub(super) fn record_txfm(
810 &mut self,
811 (mi_r, mi_c): (usize, usize),
812 tx_px: usize,
813 w_px: usize,
814 h_px: usize,
815 ) {
816 for i in 0..h_px / MI {
817 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
818 *cell = tx_px as u8;
819 }
820 }
821 for i in 0..w_px / MI {
822 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
823 *cell = tx_px as u8;
824 }
825 }
826 }
827
828 /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands
829 /// take the transform's own HEIGHT (left) and WIDTH (above), over the
830 /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`.
831 pub(super) fn record_txfm_rect(
832 &mut self,
833 (mi_r, mi_c): (usize, usize),
834 (tx_w, tx_h): (usize, usize),
835 (txb_w, txb_h): (usize, usize),
836 ) {
837 for i in 0..txb_h / MI {
838 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
839 *cell = tx_h as u8;
840 }
841 }
842 for i in 0..txb_w / MI {
843 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
844 *cell = tx_w as u8;
845 }
846 }
847 }
848
849 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
850 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
851 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
852 ///
853 /// lane-av1tx2 r1: a neighbour OUTSIDE the tile contributes nothing at all
854 /// -- the decoder's `tx_size_context_txfm` drops the whole term when
855 /// `has_above`/`has_left` is false, where this counted the band's
856 /// [`TXFM_CTX_INIT`] (64, the widest transform) as a real neighbour. Every
857 /// intra block on a tile's top row or left column then took its `tx_depth`
858 /// off a CDF row one higher than the decoder's, which is the first
859 /// divergence of the inter `TxMode::Select` stream.
860 pub(super) fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
861 let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
862 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
863 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
864 if has_above && self.above_inter[mi_c] {
865 above = self.above_side_mi[mi_c] >= own_side;
866 }
867 if has_left && self.left_inter[mi_r] {
868 left = self.left_side_mi[mi_r] >= own_side;
869 }
870 usize::from(has_above && above) + usize::from(has_left && left)
871 }
872
873 /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context_txfm`]):
874 /// whether the transform above is at least as wide as this block's own
875 /// largest transform, plus whether the one to the left is at least as
876 /// tall. A neighbour outside the tile contributes nothing.
877 pub(super) fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
878 usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
879 + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
880 }
881
882 /// Publishes one block's resolved transform side over every 4x4 unit it
883 /// covers, the way the decoder's `fill_lf_grid` does at the end of every
884 /// block.
885 pub(super) fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
886 for cell in 0..side / MI {
887 if mi_r + cell < self.left_tx.len() {
888 self.left_tx[mi_r + cell] = tx_px as u8;
889 }
890 if mi_c + cell < self.above_tx.len() {
891 self.above_tx[mi_c + cell] = tx_px as u8;
892 }
893 }
894 }
895
896 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
897 /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
898 /// tiers, each ORed over the unit's own span and clamped to 4.
899 pub(super) fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
900 let mut top = 0u8;
901 let mut left = 0u8;
902 for cell in 0..side_mi {
903 top |= self.above[mi_c + cell][0].level;
904 left |= self.left[mi_r + cell][0].level;
905 }
906 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
907 }
908
909 /// Publishes ONE luma transform unit's coefficient context, the way the
910 /// decoder's `record_mi_luma` does between the units of a split block.
911 pub(super) fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
912 let state = neighbour_state(grid);
913 for cell in 0..tx_px / MI {
914 if mi_r + cell < self.mi_rows {
915 self.left[mi_r + cell][0] = state;
916 }
917 if mi_c + cell < self.mi_cols {
918 self.above[mi_c + cell][0] = state;
919 }
920 }
921 }
922
923 /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
924 /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
925 /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
926 /// the previous one's state (its `txb_skip_ctx` base 1 from the left
927 /// neighbour). `span_px` is the unit's LUMA span, which is what the
928 /// luma-mi-indexed bands are addressed in.
929 pub(super) fn record_mi_chroma(
930 &mut self,
931 (mi_r, mi_c): (usize, usize),
932 span_px: usize,
933 plane: usize,
934 grid: &[i32],
935 ) {
936 let round_up_even = |n: usize| n.div_ceil(2) * 2;
937 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
938 let state = neighbour_state(grid);
939 for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
940 self.left[mi_r + cell][plane] = state;
941 }
942 for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
943 self.above[mi_c + cell][plane] = state;
944 }
945 }
946
947 /// Writes one coded block into every 16x16 column and row it covers, and,
948 /// on the finer 4x4 grid libaom's entropy context arrays are actually
949 /// kept on, into every unit up to the true frame edge -- the units past
950 /// it are left at their default (uncoded), even mid-16x16-cell (spec
951 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
952 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
953 /// side).
954 pub(super) fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
955 self.record_planes(at, side, mode, grids, true);
956 }
957
958 /// [`Self::record`] with a switch for plane 0: a block whose luma was
959 /// written as several transform units published each unit's own context
960 /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
961 /// would clobber what the next block reads (decode.rs
962 /// `record_split_luma`).
963 pub(super) fn record_planes(
964 &mut self,
965 at: (usize, usize),
966 side: usize,
967 mode: usize,
968 grids: &[Vec<i32>; 3],
969 luma: bool,
970 ) {
971 self.record_planes_rect(at, (side, side), mode, grids, luma);
972 }
973
974 /// lane-b128hv: [`Self::record_planes`] with independent above (width) /
975 /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the
976 /// 128 root's HORZ/VERT halves are the writer's first rect blocks.
977 pub(super) fn record_planes_rect(
978 &mut self,
979 at: (usize, usize),
980 (w, h): (usize, usize),
981 mode: usize,
982 grids: &[Vec<i32>; 3],
983 luma: bool,
984 ) {
985 let (r, c) = at;
986 for cell in 0..w / SUB {
987 self.above_mode[c + cell] = mode;
988 self.above_side[c + cell] = w;
989 }
990 for cell in 0..h / SUB {
991 self.left_mode[r + cell] = mode;
992 self.left_side[r + cell] = h;
993 }
994 self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma);
995 }
996
997 /// The coefficient-context half of [`Self::record`], taking the block's
998 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
999 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
1000 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
1001 /// `above`/`left` arrays it writes into are already sized to the full mi
1002 /// grid, so no resizing is needed to write into them at this
1003 /// finer-than-SUB granularity.
1004 pub(super) fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
1005 self.record_mi_planes(at_mi, side, grids, true);
1006 }
1007
1008 /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
1009 pub(super) fn record_mi_planes(
1010 &mut self,
1011 at_mi: (usize, usize),
1012 side: usize,
1013 grids: &[Vec<i32>; 3],
1014 luma: bool,
1015 ) {
1016 self.record_mi_planes_rect(at_mi, (side, side), grids, luma);
1017 }
1018
1019 /// [`Self::record_mi_planes`] with independent above (width) / left
1020 /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`).
1021 pub(super) fn record_mi_planes_rect(
1022 &mut self,
1023 at_mi: (usize, usize),
1024 (w, h): (usize, usize),
1025 grids: &[Vec<i32>; 3],
1026 luma: bool,
1027 ) {
1028 let (mi_r, mi_c) = at_mi;
1029 if screen_armed() {
1030 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
1031 self.record_palette_y(at_mi, (w, h), size, colors);
1032 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
1033 self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors);
1034 }
1035 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1036 let (w_mi, h_mi) = (w / MI, h / MI);
1037 for cell in 0..h_mi {
1038 self.left_side_mi[mi_r + cell] = h;
1039 }
1040 for cell in 0..w_mi {
1041 self.above_side_mi[mi_c + cell] = w;
1042 }
1043 // libaom rounds the luma edge up to the plane's own 4x4 unit before
1044 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
1045 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
1046 // a chroma 4x4 unit straddling the true luma edge is still whole in
1047 // chroma's own halved grid, so it stays valid one luma-mi row/col
1048 // past where luma's own edge falls when that edge is odd.
1049 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1050 let bound_h = [
1051 self.mi_rows,
1052 round_up_even(self.mi_rows),
1053 round_up_even(self.mi_rows),
1054 ];
1055 let bound_w = [
1056 self.mi_cols,
1057 round_up_even(self.mi_cols),
1058 round_up_even(self.mi_cols),
1059 ];
1060 for cell in 0..h_mi {
1061 let keep_left = self.left[mi_r + cell][0];
1062 self.left[mi_r + cell] = std::array::from_fn(|plane| {
1063 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
1064 states[plane]
1065 } else {
1066 Default::default()
1067 }
1068 });
1069 if !luma {
1070 self.left[mi_r + cell][0] = keep_left;
1071 }
1072 }
1073 for cell in 0..w_mi {
1074 let keep_above = self.above[mi_c + cell][0];
1075 self.above[mi_c + cell] = std::array::from_fn(|plane| {
1076 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
1077 states[plane]
1078 } else {
1079 Default::default()
1080 }
1081 });
1082 if !luma {
1083 self.above[mi_c + cell][0] = keep_above;
1084 }
1085 }
1086 }
1087
1088 /// Writes one inter-frame block's skip flag and inter/intra state into
1089 /// every 16x16 column and row it covers, the same span [`Self::record`]
1090 /// fills for the coefficient and mode state.
1091 pub(super) fn record_inter(
1092 &mut self,
1093 at: (usize, usize),
1094 side: usize,
1095 skip: bool,
1096 is_inter: bool,
1097 ref_frame: i8,
1098 ) {
1099 let (r, c) = at;
1100 self.record_inter_mi(
1101 (r * (SUB / MI), c * (SUB / MI)),
1102 side,
1103 skip,
1104 is_inter,
1105 ref_frame,
1106 );
1107 }
1108
1109 /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width)
1110 /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split.
1111 pub(super) fn record_inter_rect_mi(
1112 &mut self,
1113 (mi_r, mi_c): (usize, usize),
1114 (w, h): (usize, usize),
1115 skip: bool,
1116 is_inter: bool,
1117 ref_frame: i8,
1118 ) {
1119 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1120 for cell in 0..h / MI {
1121 self.left_skip[mi_r + cell] = skip;
1122 self.left_inter[mi_r + cell] = is_inter;
1123 self.left_ref[mi_r + cell] = ref_frame;
1124 self.left_ref1[mi_r + cell] = None;
1125 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
1126 self.left_compound_idx[mi_r + cell] = u8::from(altref);
1127 }
1128 for cell in 0..w / MI {
1129 self.above_skip[mi_c + cell] = skip;
1130 self.above_inter[mi_c + cell] = is_inter;
1131 self.above_ref[mi_c + cell] = ref_frame;
1132 self.above_ref1[mi_c + cell] = None;
1133 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
1134 self.above_compound_idx[mi_c + cell] = u8::from(altref);
1135 }
1136 }
1137
1138 /// [`Self::record_compound_mi`] over a rect block's own two spans.
1139 pub(super) fn record_compound_rect_mi(
1140 &mut self,
1141 (mi_r, mi_c): (usize, usize),
1142 (w, h): (usize, usize),
1143 ref1: i8,
1144 comp_group_idx: u8,
1145 compound_idx: u8,
1146 ) {
1147 for cell in 0..h / MI {
1148 self.left_ref1[mi_r + cell] = Some(ref1);
1149 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
1150 self.left_compound_idx[mi_r + cell] = compound_idx;
1151 }
1152 for cell in 0..w / MI {
1153 self.above_ref1[mi_c + cell] = Some(ref1);
1154 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
1155 self.above_compound_idx[mi_c + cell] = compound_idx;
1156 }
1157 }
1158
1159 /// [`Self::record_inter_mi`]'s compound half (decode.rs
1160 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
1161 /// single-reference default with a real compound block's own second
1162 /// reference and `comp_group_idx`/`compound_idx` bits, called right after
1163 /// it for every compound-coded block.
1164 pub(super) fn record_compound_mi(
1165 &mut self,
1166 (mi_r, mi_c): (usize, usize),
1167 side: usize,
1168 ref1: i8,
1169 comp_group_idx: u8,
1170 compound_idx: u8,
1171 ) {
1172 for cell in 0..side / MI {
1173 self.above_ref1[mi_c + cell] = Some(ref1);
1174 self.left_ref1[mi_r + cell] = Some(ref1);
1175 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
1176 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
1177 self.above_compound_idx[mi_c + cell] = compound_idx;
1178 self.left_compound_idx[mi_r + cell] = compound_idx;
1179 }
1180 }
1181
1182 /// [`Self::record_inter`] taking the block's position directly in 4x4
1183 /// mode-info units, for a block finer than one [`SUB`] slot.
1184 pub(super) fn record_inter_mi(
1185 &mut self,
1186 (mi_r, mi_c): (usize, usize),
1187 side: usize,
1188 skip: bool,
1189 is_inter: bool,
1190 ref_frame: i8,
1191 ) {
1192 for cell in 0..side / MI {
1193 self.above_skip[mi_c + cell] = skip;
1194 self.left_skip[mi_r + cell] = skip;
1195 self.above_inter[mi_c + cell] = is_inter;
1196 self.left_inter[mi_r + cell] = is_inter;
1197 self.above_ref[mi_c + cell] = ref_frame;
1198 self.left_ref[mi_r + cell] = ref_frame;
1199 // decode.rs `record_inter`'s single-reference default: no second
1200 // reference, and libaom's ALTREF special case in the two compound
1201 // context bands. `record_compound_mi` overwrites both for a real
1202 // compound block.
1203 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1204 self.above_ref1[mi_c + cell] = None;
1205 self.left_ref1[mi_r + cell] = None;
1206 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
1207 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
1208 self.above_compound_idx[mi_c + cell] = u8::from(altref);
1209 self.left_compound_idx[mi_r + cell] = u8::from(altref);
1210 }
1211 }
1212
1213 /// The above neighbour as decode.rs' own `NeighbourRef`, for every
1214 /// compound context function (`reference_mode_ctx`,
1215 /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
1216 pub(super) fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
1217 let is_inter = self.above_inter[mi_c];
1218 let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
1219 let ref1 = self.above_ref1[mi_c];
1220 crate::mvstack::NeighbourRef {
1221 is_inter,
1222 ref0,
1223 ref1,
1224 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
1225 }
1226 }
1227
1228 /// [`Self::above_nbr`], down the left edge.
1229 pub(super) fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
1230 let is_inter = self.left_inter[mi_r];
1231 let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
1232 let ref1 = self.left_ref1[mi_r];
1233 crate::mvstack::NeighbourRef {
1234 is_inter,
1235 ref0,
1236 ref1,
1237 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
1238 }
1239 }
1240
1241 /// The context of a block's partition symbol (spec 9.3): whether the
1242 /// blocks above it and to its left were split finer than it is.
1243 /// The gathered state of the blocks above and to the left of one block,
1244 /// per plane.
1245 pub(super) fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
1246 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
1247 }
1248
1249 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
1250 /// units, for the same reason [`Self::record_mi`] does.
1251 pub(super) fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
1252 let side_mi = side / MI;
1253 std::array::from_fn(|plane| {
1254 let mut around = Around::default();
1255 for cell in 0..side_mi {
1256 let (above, left) = (
1257 &self.above[mi_c + cell][plane],
1258 &self.left[mi_r + cell][plane],
1259 );
1260 around.above_coded |= above.coded;
1261 around.left_coded |= left.coded;
1262 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
1263 }
1264 around
1265 })
1266 }
1267
1268 pub(super) fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
1269 // Delegates to the mi-precise reader (same pattern as `around` /
1270 // `around_mi`): `above_side`/`left_side` are only ever advanced in
1271 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
1272 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
1273 // them stale for the *next* sibling's own partition symbol, reading a
1274 // 16x16-slot side that already split into 8x8s underneath it.
1275 let (r, c) = at;
1276 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
1277 }
1278
1279 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
1280 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
1281 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
1282 /// than the enclosing 16x16 slot's stale, shared state.
1283 pub(super) fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
1284 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
1285 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
1286 }
1287}
1288
1289/// Writes the payload of a one-tile key frame built from `superblocks`, each
1290/// either one 64x64 block or the 32x32 blocks it splits into.
1291///
1292/// `superblocks` gives one entry per superblock in raster order across the
1293/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
1294/// otherwise, and carries the coefficients its lists give; the coefficients
1295/// may sit anywhere in their transform, so a block is a picture rather than a
1296/// flat grey.
1297///
1298/// # Errors
1299/// Returns an error when the frame is not a whole number of 32x32 blocks, when
1300/// `superblocks` does not carry exactly one entry per superblock or an entry
1301/// does not carry one block per quadrant inside the frame, when a superblock
1302/// that is half outside the frame is left whole, when a block names an intra
1303/// mode a key frame does not code, when a coefficient sits outside its
1304/// transform, repeats a position, carries a zero level or one wider than the
1305/// Golomb tail reaches.
1306pub fn sb_coeff_key_frame_tile(
1307 mi_cols: u32,
1308 mi_rows: u32,
1309 base_q_idx: u8,
1310 superblocks: &[Superblock],
1311) -> Result<Vec<u8>> {
1312 sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
1313}
1314
1315/// [`sb_coeff_key_frame_tile`] for a frame header carrying
1316/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
1317/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
1318/// several transform units ([`write_luma_select`]). With `tx_select` false
1319/// this writes exactly the stream it always did.
1320///
1321/// # Errors
1322/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
1323/// nonzero (not written yet).
1324pub fn sb_coeff_key_frame_tile_tx(
1325 mi_cols: u32,
1326 mi_rows: u32,
1327 base_q_idx: u8,
1328 superblocks: &[Superblock],
1329 tx_select: bool,
1330) -> Result<Vec<u8>> {
1331 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1332 sb_coeff_key_frame_tile_cdfs(
1333 mi_cols,
1334 mi_rows,
1335 base_q_idx,
1336 superblocks,
1337 tx_select,
1338 &mut cdfs,
1339 TileRect::whole(mi_cols, mi_rows),
1340 )
1341}
1342
1343/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
1344/// caller's own CDF state, which is what a frame whose
1345/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
1346/// start where this tile ended (spec 7.20, mirrored by
1347/// `crate::stream::stored_cdfs_for`).
1348///
1349/// # Errors
1350/// As [`sb_coeff_key_frame_tile_tx`].
1351pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1352 mi_cols: u32,
1353 mi_rows: u32,
1354 _base_q_idx: u8,
1355 superblocks: &[Superblock],
1356 tx_select: bool,
1357 cdfs: &mut Cdfs,
1358 // This tile's own span (spec 5.11.1): the writer walks only these
1359 // superblocks, and its neighbour bands start blank, so everything
1360 // outside reads as unavailable exactly as the decoder's own per-tile
1361 // reset makes it.
1362 tile: TileRect,
1363) -> Result<Vec<u8>> {
1364 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1365 let _cdef_idx = CdefIdxGuard;
1366 check_blocks(mi_cols, mi_rows)?;
1367 // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
1368 // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
1369 // allows no intrabc arms none and every `record_intrabc_mi` below is a
1370 // no-op.
1371 if intrabc_armed() {
1372 // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
1373 // frame with the default (whole-grid) bounds, so the writer must
1374 // too. `encode_key_frame_inner` only allows intrabc on a
1375 // single-tile frame, where the two grids are the same grid.
1376 let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
1377 INTRABC_GRID.with(|g| {
1378 *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
1379 });
1380 }
1381 let (cols, rows) = block_grid(mi_cols, mi_rows);
1382 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
1383 if superblocks.len() != (sb_cols * sb_rows) as usize {
1384 return Err(Error::unsupported(
1385 "AV1 tile",
1386 "a coefficient key frame needs one entry per superblock",
1387 ));
1388 }
1389 let mut coded: Vec<&BlockCoeffs> = Vec::new();
1390 for superblock in superblocks {
1391 match superblock {
1392 Superblock::Whole(block) => coded.push(block),
1393 Superblock::Split(quadrants) => {
1394 for block in quadrants.iter().flat_map(Quadrant::blocks) {
1395 match &block.eight {
1396 Some(leaves) => coded.extend(leaves.iter()),
1397 None => coded.push(block),
1398 }
1399 }
1400 }
1401 }
1402 }
1403 if let Some(bad) = coded
1404 .into_iter()
1405 .find(|b| usize::from(b.mode) >= INTRA_MODES)
1406 {
1407 return Err(Error::unsupported(
1408 "AV1 tile",
1409 format!(
1410 "intra mode {} is not one of the thirteen a key frame codes",
1411 bad.mode
1412 ),
1413 ));
1414 }
1415
1416 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
1417 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
1418 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
1419 let scans = [
1420 default_scan(TX32),
1421 default_scan(TX16),
1422 default_scan(TX8),
1423 default_scan(TX4),
1424 ];
1425 // The blocks above and to the left, on the 16x16 grid. The left edge is
1426 // reset at every superblock row because a tile starts each row with no
1427 // left neighbour.
1428 let mut neighbours = Neighbours::new(
1429 cols as usize * 2,
1430 rows as usize * 2,
1431 mi_cols as usize,
1432 mi_rows as usize,
1433 );
1434 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
1435
1436 // The tile adapts every non-literal CDF it writes, exactly as the decoder
1437 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
1438 // off.
1439 let mut enc = SymbolEncoder::new();
1440 let sb128 = sb128_armed();
1441 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
1442 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
1443 // and partition symbol first; at a 64 one this is plain raster and every
1444 // cell is its own superblock, i.e. byte-identical to the loop before.
1445 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
1446 tile.sb_row0,
1447 tile.sb_row1.min(sb_rows),
1448 tile.sb_col0,
1449 tile.sb_col1.min(sb_cols),
1450 sb128,
1451 ) {
1452 if row_start {
1453 neighbours.start_row();
1454 }
1455 if sb128 && sb_start {
1456 write_sb128_root(
1457 &mut enc,
1458 cdfs,
1459 &neighbours,
1460 sb_r,
1461 sb_c,
1462 mi_cols,
1463 mi_rows,
1464 PARTITION_SPLIT,
1465 );
1466 }
1467 {
1468 if !sb128 {
1469 write_lr(&mut enc, cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
1470 }
1471 let at = (sb_r as usize * 4, sb_c as usize * 4);
1472 let ctx = neighbours.partition_ctx(at, SB);
1473 ec_rng_trace(|| {
1474 format!(
1475 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
1476 at.0 * 4,
1477 at.1 * 4,
1478 ctx,
1479 enc.tell()
1480 )
1481 });
1482 // A superblock whose bottom or right half is outside the frame
1483 // cannot be left unsplit, so the decoder reads a flag instead of
1484 // the partition symbol — and reads nothing at all when both halves
1485 // are outside, where the split is the only partition left.
1486 let (has_cols, has_rows) = (
1487 sb_c * SB_MI + SB_MI / 2 < mi_cols,
1488 sb_r * SB_MI + SB_MI / 2 < mi_rows,
1489 );
1490 // The quadrants of this superblock that are inside the frame, as
1491 // positions in the 32x32 block grid.
1492 let quadrant_positions: Vec<(usize, usize)> = (0..4)
1493 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
1494 .filter(|&(r, c)| r < rows && c < cols)
1495 .map(|(r, c)| (r as usize, c as usize))
1496 .collect();
1497
1498 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
1499 Superblock::Whole(block) => {
1500 if !has_cols || !has_rows {
1501 return Err(Error::unsupported(
1502 "AV1 tile",
1503 "a superblock that is half outside the frame cannot be left whole",
1504 ));
1505 }
1506 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
1507 let grids = [
1508 level_grid(&block.luma, TX32)?,
1509 level_grid(&block.u, TX32)?,
1510 level_grid(&block.v, TX32)?,
1511 ];
1512 write_block(
1513 &mut enc,
1514 cdfs,
1515 &mut neighbours,
1516 block,
1517 at,
1518 SB,
1519 &whole_planes,
1520 &grids,
1521 [&scans[0], &scans[0], &scans[0]],
1522 // A 64x64 block is too big to be offered chroma from
1523 // luma, so its chroma mode reads the table without it.
1524 false,
1525 tx_select,
1526 &scans,
1527 )?;
1528 ec_rng_trace(|| {
1529 format!(
1530 "EC_TOK mi_row={} mi_col={} tell={}",
1531 at.0 * 4,
1532 at.1 * 4,
1533 enc.tell()
1534 )
1535 });
1536 }
1537 Superblock::Split(quadrants) => {
1538 match (has_cols, has_rows) {
1539 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
1540 // The gathered CDF an edge superblock reads is built
1541 // for the read and thrown away: the decoder never
1542 // stores it back, so nothing adapts here.
1543 (true, false) => {
1544 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
1545 }
1546 (false, true) => {
1547 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
1548 }
1549 (false, false) => {}
1550 }
1551 if quadrants.len() != quadrant_positions.len() {
1552 return Err(Error::unsupported(
1553 "AV1 tile",
1554 "a split superblock needs one block per quadrant inside the frame",
1555 ));
1556 }
1557 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
1558 let at = (r * 2, c * 2);
1559 let ctx = neighbours.partition_ctx(at, BLOCK);
1560 // Recomputed at this 32x32 block's own half (spec
1561 // `decode_partition`, called again at every size, not
1562 // just once for the superblock): the true frame edge
1563 // can fall inside this quadrant even when the
1564 // superblock it sits in was itself whole or safely
1565 // split above.
1566 let (has_cols32, has_rows32) = (
1567 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
1568 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
1569 );
1570 ec_rng_trace(|| {
1571 format!(
1572 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
1573 at.0 * 4,
1574 at.1 * 4,
1575 ctx,
1576 enc.tell()
1577 )
1578 });
1579 match quadrant {
1580 // A 64x64 root is an INTER-frame partition; a
1581 // key frame codes one as `Superblock::Whole`.
1582 Quadrant::Whole64(_)
1583 | Quadrant::Whole128(_)
1584 | Quadrant::Rect128(..)
1585 | Quadrant::Ab128(..)
1586 | Quadrant::Covered => {
1587 return Err(Error::unsupported(
1588 "AV1 tile",
1589 "a key frame codes a 64x64 block as `Superblock::Whole`",
1590 ));
1591 }
1592 Quadrant::Whole(block) => {
1593 if !has_cols32 || !has_rows32 {
1594 return Err(Error::unsupported(
1595 "AV1 tile",
1596 "a 32x32 block that is half outside the true frame \
1597 cannot be left whole",
1598 ));
1599 }
1600 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
1601 let grids = [
1602 level_grid(&block.luma, TX32)?,
1603 level_grid(&block.u, TX16)?,
1604 level_grid(&block.v, TX16)?,
1605 ];
1606 write_block(
1607 &mut enc,
1608 cdfs,
1609 &mut neighbours,
1610 block,
1611 at,
1612 BLOCK,
1613 &split_planes,
1614 &grids,
1615 [&scans[0], &scans[1], &scans[1]],
1616 true,
1617 tx_select,
1618 &scans,
1619 )?;
1620 ec_rng_trace(|| {
1621 format!(
1622 "EC_TOK mi_row={} mi_col={} tell={}",
1623 at.0 * 4,
1624 at.1 * 4,
1625 enc.tell()
1626 )
1627 });
1628 }
1629 Quadrant::Split(blocks) => {
1630 // The 16x16 sub-blocks this quadrant's split
1631 // carries: only those whose own mi origin is
1632 // inside the true frame (spec `decode_partition`'s
1633 // `r >= MiRows || c >= MiCols` early return),
1634 // which need not be all four when the true
1635 // edge falls inside this quadrant.
1636 let sub_positions: Vec<(usize, usize)> = (0..4)
1637 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
1638 .filter(|&(sr, sc)| {
1639 (sr as u32) * SUB_MI < mi_rows
1640 && (sc as u32) * SUB_MI < mi_cols
1641 })
1642 .collect();
1643 if blocks.len() != sub_positions.len() {
1644 return Err(Error::unsupported(
1645 "AV1 tile",
1646 "a split 32x32 block needs one 16x16 entry per \
1647 sub-block inside the true frame",
1648 ));
1649 }
1650 // Same three-way spec signaling as the
1651 // superblock level above, recomputed at this
1652 // block's own half: a full alphabet symbol
1653 // only when both halves are inside, a single
1654 // gathered bit when just one is, and nothing
1655 // at all (SPLIT is inferred) when neither is.
1656 match (has_cols32, has_rows32) {
1657 (true, true) => {
1658 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
1659 }
1660 (true, false) => {
1661 enc.symbol_fixed(
1662 1,
1663 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
1664 );
1665 }
1666 (false, true) => {
1667 enc.symbol_fixed(
1668 1,
1669 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
1670 );
1671 }
1672 (false, false) => {}
1673 }
1674 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
1675 // A 16x16 leaf's own hasRows/hasCols,
1676 // recomputed at this leaf's own half
1677 // (same three-way signaling as the 32x32
1678 // and 64x64 levels above).
1679 let (has_cols16, has_rows16) = (
1680 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
1681 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
1682 );
1683 let at = (sr, sc);
1684 let ctx = neighbours.partition_ctx(at, SUB);
1685 ec_rng_trace(|| {
1686 format!(
1687 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
1688 at.0 * 4,
1689 at.1 * 4,
1690 ctx,
1691 enc.tell()
1692 )
1693 });
1694 if has_cols16 && has_rows16 {
1695 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
1696 let grids = [
1697 level_grid(&block.luma, TX16)?,
1698 level_grid(&block.u, TX8)?,
1699 level_grid(&block.v, TX8)?,
1700 ];
1701 write_block(
1702 &mut enc,
1703 cdfs,
1704 &mut neighbours,
1705 block,
1706 at,
1707 SUB,
1708 &sub_planes,
1709 &grids,
1710 [&scans[1], &scans[2], &scans[2]],
1711 true,
1712 tx_select,
1713 &scans,
1714 )?;
1715 ec_rng_trace(|| {
1716 format!(
1717 "EC_TOK mi_row={} mi_col={} tell={}",
1718 at.0 * 4,
1719 at.1 * 4,
1720 enc.tell()
1721 )
1722 });
1723 continue;
1724 }
1725 // The true edge falls inside this 16x16
1726 // leaf itself: the block splits into the
1727 // 8x8s that are inside, each its own
1728 // leaf. Same three-way spec signaling as
1729 // every level above -- a single gathered
1730 // bit when one half is outside, and
1731 // nothing at all when BOTH are, where
1732 // `decode_partition` infers the split
1733 // (lane-av1rect: no rectangular
1734 // transform is needed for this, the
1735 // earlier refusal here misread 5.11.4).
1736 match (has_cols16, has_rows16) {
1737 (true, false) => enc.symbol_fixed(
1738 1,
1739 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
1740 ),
1741 (false, true) => enc.symbol_fixed(
1742 1,
1743 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
1744 ),
1745 _ => {}
1746 }
1747 let leaves = block.eight.as_ref().ok_or_else(|| {
1748 Error::unsupported(
1749 "AV1 tile",
1750 "a 16x16 block the true frame edge cuts through \
1751 needs its `eight` leaves populated",
1752 )
1753 })?;
1754 let (mi_row0, mi_col0) =
1755 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
1756 let leaf_positions: Vec<(u32, u32)> = (0..4)
1757 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
1758 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
1759 .collect();
1760 if leaves.len() != leaf_positions.len() {
1761 return Err(Error::unsupported(
1762 "AV1 tile",
1763 "a straddling 16x16 block needs one `eight` entry \
1764 per 8x8 leaf inside the true frame",
1765 ));
1766 }
1767 // r11: the enclosing 16x16 slot's
1768 // above_mode/left_mode arrays are too
1769 // coarse for a second leaf whose true
1770 // above (or left) neighbour is the FIRST
1771 // leaf -- track it here and hand it to
1772 // write_leaf8 as a context override.
1773 let mut prev_leaf: Option<((usize, usize), usize)> = None;
1774 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
1775 let leaf_mi = (mr as usize, mc as usize);
1776 // r8: read at mi granularity, not the
1777 // enclosing 16x16 slot -- the first
1778 // leaf's `record_mi` call below
1779 // updates `above_side_mi`/
1780 // `left_side_mi` at this leaf's own
1781 // mi position, which the second
1782 // leaf's ctx lookup then sees.
1783 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1784 ec_rng_trace(|| {
1785 format!(
1786 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
1787 leaf_mi.0,
1788 leaf_mi.1,
1789 leaf_ctx,
1790 enc.tell()
1791 )
1792 });
1793 enc.symbol(
1794 PARTITION_NONE,
1795 &mut cdfs.partition_w8[leaf_ctx],
1796 );
1797 let grids = [
1798 level_grid(&leaf.luma, TX8)?,
1799 level_grid(&leaf.u, TX4)?,
1800 level_grid(&leaf.v, TX4)?,
1801 ];
1802 let leaf_mode = write_leaf8(
1803 &mut enc,
1804 cdfs,
1805 &mut neighbours,
1806 leaf,
1807 at,
1808 leaf_mi,
1809 &grids,
1810 [&scans[2], &scans[3], &scans[3]],
1811 prev_leaf,
1812 tx_select,
1813 &scans,
1814 )?;
1815 prev_leaf = Some((leaf_mi, leaf_mode));
1816 ec_rng_trace(|| {
1817 format!(
1818 "EC_TOK mi_row={} mi_col={} tell={}",
1819 leaf_mi.0,
1820 leaf_mi.1,
1821 enc.tell()
1822 )
1823 });
1824 }
1825 // `record()`'s `above_mode`/`left_mode`
1826 // write is a no-op at an 8x8 leaf's own
1827 // side (`side / SUB == 0`), so the next
1828 // 16x16 quadrant beyond this straddling
1829 // one would otherwise see whatever stale
1830 // mode sat here before it: force the
1831 // write once the whole quadrant's leaves
1832 // are done, from the last (bottom/right-
1833 // most) leaf -- lane-av1-rect r15: doing
1834 // this *inside* `write_leaf8`, once per
1835 // leaf, let the first leaf's write
1836 // clobber the true external neighbour a
1837 // second leaf of the *same* quadrant
1838 // still needed to read on its
1839 // non-adjacency axis.
1840 if let Some((_, mode)) = prev_leaf {
1841 neighbours.above_mode[at.1] = mode;
1842 neighbours.left_mode[at.0] = mode;
1843 }
1844 }
1845 }
1846 }
1847 }
1848 }
1849 }
1850 }
1851 }
1852 Ok(enc.finish())
1853}
1854
1855/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
1856/// which the palette colour-index map's first (context-free) symbol is coded
1857/// with.
1858pub(super) fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
1859 let l = crate::decode::ceil_log2(n as u32);
1860 let m = (1usize << l) - n;
1861 if value < m {
1862 enc.literal(value as u32, l - 1);
1863 } else {
1864 enc.literal(((value + m) >> 1) as u32, l - 1);
1865 enc.literal(((value + m) & 1) as u32, 1);
1866 }
1867}
1868
1869/// `write_palette_colors_y` (bitstream.c:1178), the write side of
1870/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
1871/// entry (taken when this palette holds that colour, in cache order, stopping
1872/// once `n` are cached), then the colours the cache did not supply -- the
1873/// first raw, the rest as deltas off a bit width that shrinks with the range
1874/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
1875/// of the two ascending lists puts it back exactly.
1876pub(super) fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
1877 let n = colors.len();
1878 let mut cached: Vec<u16> = Vec::with_capacity(n);
1879 for &c in cache {
1880 if cached.len() >= n {
1881 break;
1882 }
1883 let take = colors.contains(&c);
1884 enc.literal(u32::from(take), 1);
1885 if take {
1886 cached.push(c);
1887 }
1888 }
1889 let transmitted: Vec<u16> = colors
1890 .iter()
1891 .copied()
1892 .filter(|c| !cached.contains(c))
1893 .collect();
1894 if transmitted.is_empty() {
1895 return;
1896 }
1897 enc.literal(u32::from(transmitted[0]), 8);
1898 if transmitted.len() == 1 {
1899 return;
1900 }
1901 // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
1902 // under which every delta still fits its (shrinking) width. `extra == 3`
1903 // always works -- a delta can never exceed the range left -- so the
1904 // search below always finds one.
1905 let fits = |extra: u32| -> bool {
1906 let mut bits = 5 + extra;
1907 let mut range = 255i32 - i32::from(transmitted[0]);
1908 for w in transmitted.windows(2) {
1909 let delta = i32::from(w[1]) - i32::from(w[0]);
1910 if delta > (1i32 << bits) {
1911 return false;
1912 }
1913 range -= delta;
1914 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1915 }
1916 true
1917 };
1918 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
1919 enc.literal(extra, 2);
1920 let mut bits = 5 + extra;
1921 let mut range = 255i32 - i32::from(transmitted[0]);
1922 for w in transmitted.windows(2) {
1923 let delta = i32::from(w[1]) - i32::from(w[0]);
1924 enc.literal((delta - 1) as u32, bits);
1925 range -= delta;
1926 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1927 }
1928}
1929
1930/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
1931/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
1932/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
1933/// documented differences -- the shrinking range starts at `256 - first`
1934/// (not `255 - first`) and each delta is written unbiased (no `-1`).
1935///
1936/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
1937/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
1938/// Ceiling: about `n` bits per chroma-palette block more than the delta form
1939/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
1940/// below sees, so it only ever makes the encoder take FEWER chroma palettes
1941/// than it should -- never a wrong stream. Upgrade path: price both forms
1942/// here and write the cheaper one under its own leading bit.
1943pub(super) fn write_palette_colors_uv(
1944 enc: &mut SymbolEncoder,
1945 u_colors: &[u16],
1946 v_colors: &[u16],
1947 cache: &[u16],
1948) {
1949 let n = u_colors.len();
1950 let mut cached: Vec<u16> = Vec::with_capacity(n);
1951 for &c in cache {
1952 if cached.len() >= n {
1953 break;
1954 }
1955 let take = u_colors.contains(&c);
1956 enc.literal(u32::from(take), 1);
1957 if take {
1958 PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1959 cached.push(c);
1960 }
1961 }
1962 let transmitted: Vec<u16> = u_colors
1963 .iter()
1964 .copied()
1965 .filter(|c| !cached.contains(c))
1966 .collect();
1967 if !transmitted.is_empty() {
1968 enc.literal(u32::from(transmitted[0]), 8);
1969 if transmitted.len() > 1 {
1970 let fits = |extra: u32| -> bool {
1971 let mut bits = 5 + extra;
1972 let mut range = 256i32 - i32::from(transmitted[0]);
1973 for w in transmitted.windows(2) {
1974 let delta = i32::from(w[1]) - i32::from(w[0]);
1975 if delta >= (1i32 << bits) {
1976 return false;
1977 }
1978 range -= delta;
1979 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1980 }
1981 true
1982 };
1983 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
1984 enc.literal(extra, 2);
1985 let mut bits = 5 + extra;
1986 let mut range = 256i32 - i32::from(transmitted[0]);
1987 for w in transmitted.windows(2) {
1988 let delta = i32::from(w[1]) - i32::from(w[0]);
1989 enc.literal(delta as u32, bits);
1990 range -= delta;
1991 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1992 }
1993 }
1994 }
1995 enc.literal(0, 1);
1996 for &v in v_colors {
1997 enc.literal(u32::from(v), 8);
1998 }
1999}
2000
2001/// `write_palette_color_map` (bitstream.c), the write side of
2002/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
2003/// each symbol written as the position its colour takes in the neighbour
2004/// ordering `av1_get_palette_color_index_context` hands back.
2005pub(super) fn write_color_index_map(
2006 enc: &mut SymbolEncoder,
2007 idx_cdfs: &mut [[u16; 9]; 5],
2008 map: &[u8],
2009 side: usize,
2010 n: usize,
2011 // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units:
2012 // a block cut by the frame's right/bottom mi edge codes ONLY this corner
2013 // and the decoder replicates it outward (`decode::palette_replicate`).
2014 // Writing the full grid spent symbols a conformant decoder never reads,
2015 // desyncing the rest of the tile (lane-palw, class
2016 // writer-phantom-units-past-edge).
2017 on: (usize, usize),
2018) {
2019 let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
2020 write_uniform(enc, usize::from(map[0]), n);
2021 for i in 1..(on_w + on_h - 1) {
2022 for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
2023 let (row, col) = (i - j, j);
2024 let (ctx, color_order) =
2025 crate::decode::palette_color_index_context(map, side, row, col, n);
2026 let want = map[row * side + col];
2027 let symbol = color_order[..n]
2028 .iter()
2029 .position(|&c| c == want)
2030 .expect("every colour index is in the block\'s own palette");
2031 enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
2032 }
2033 }
2034}
2035
2036/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
2037/// the size symbol, the colours and the whole colour-index map, priced
2038/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
2039/// search reads the rate the tile will really spend, not an estimate of it.
2040/// The neighbour cache is taken as empty (the search runs before the tile
2041/// knows what its neighbours will be), which only ever over-prices.
2042pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 {
2043 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2044 return f64::INFINITY;
2045 };
2046 let n = usize::from(pal.size);
2047 let mut enc = SymbolEncoder::pricer();
2048 let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
2049 enc.symbol(1, &mut mode_cdf);
2050 let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
2051 enc.symbol(n - 2, &mut size_cdf);
2052 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
2053 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
2054 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on);
2055 enc.bits()
2056}
2057
2058/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
2059/// size symbol, both colour lists and the shared colour-index map, priced
2060/// through the very writers above (empty cache, which only over-prices).
2061pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 {
2062 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2063 return f64::INFINITY;
2064 };
2065 let n = usize::from(pal.size);
2066 let mut enc = SymbolEncoder::pricer();
2067 let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
2068 enc.symbol(1, &mut mode_cdf);
2069 let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
2070 enc.symbol(n - 2, &mut size_cdf);
2071 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
2072 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
2073 write_color_index_map(
2074 &mut enc,
2075 &mut idx_cdfs,
2076 &pal.map,
2077 palette_uv_side(side),
2078 n,
2079 on,
2080 );
2081 enc.bits()
2082}
2083
2084/// Writes everything a key frame's block carries before its coefficients: the
2085/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2086/// the angle a directional mode is steered by, and its chroma mode. Hands back
2087/// the luma mode, which is what the blocks beside it read.
2088/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
2089/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
2090/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
2091/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
2092/// superblock to the left on the tile's first superblock row, then floored to
2093/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
2094/// tile ever reaches.
2095pub(super) fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
2096 const INTRABC_DELAY_PIXELS: i32 = 256;
2097 let n4 = side / MI;
2098 let stack_pred = INTRABC_GRID.with(|g| {
2099 let g = g.borrow();
2100 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
2101 let stack = crate::mvstack::find_mv_stack(
2102 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
2103 *mi_cols, *mi_rows,
2104 );
2105 if stack.nearest_mv == (0, 0) {
2106 stack.near_mv
2107 } else {
2108 stack.nearest_mv
2109 }
2110 })
2111 });
2112 let mut pred = stack_pred.unwrap_or((0, 0));
2113 if pred == (0, 0) {
2114 // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size
2115 // in mi units (lane-b128m: hardcoding 16 here made the writer's DV
2116 // predictor one 64 superblock up while decode.rs `read_intrabc_dv`
2117 // took 128 -- identical symbols, different reconstructed DV). The
2118 // tile row start is 0, exactly as the reader takes it -- both are
2119 // written for the single-tile-row streams this encoder produces.
2120 let sb_mi = if sb128_armed() { 32i32 } else { 16i32 };
2121 let sb_px = sb_mi * MI as i32;
2122 pred = if (mi_r as i32) < sb_mi {
2123 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
2124 } else {
2125 (-sb_px * 8, 0)
2126 };
2127 }
2128 ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
2129}
2130
2131/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
2132/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
2133/// its DV as an `INTRA_FRAME` candidate.
2134pub(super) fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
2135 INTRABC_GRID.with(|g| {
2136 let mut g = g.borrow_mut();
2137 let Some((grid, _, _)) = g.as_mut() else {
2138 return;
2139 };
2140 let info = crate::mvstack::MiInfo {
2141 is_inter: dv.is_some(),
2142 ref_frame: 0,
2143 ref_frame1: crate::mvstack::NO_REF1,
2144 mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
2145 mv1: (0, 0),
2146 is_new_mv: dv.is_some(),
2147 is_global_mv0: false,
2148 is_global_mv1: false,
2149 size: n4 as u8,
2150 size_h: n4 as u8,
2151 };
2152 for r in mi_r..mi_r + n4 {
2153 for c in mi_c..mi_c + n4 {
2154 grid.set(r, c, info);
2155 }
2156 }
2157 });
2158}
2159
2160/// One full-pel block-vector component, [`write_mv_component`]'s
2161/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
2162/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
2163/// `force_integer_mv`, so neither symbol is written here -- writing them
2164/// would leave the decoder two symbols behind from this block on.
2165pub(super) fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
2166 let mag = diff.unsigned_abs() as i32;
2167 if mag % 8 != 0 {
2168 return Err(Error::unsupported(
2169 "AV1 tile",
2170 "a block vector is coded at full-pel precision only",
2171 ));
2172 }
2173 enc.symbol(usize::from(diff < 0), &mut c.sign);
2174 let z = mag - 1;
2175 let class = mv_class_of(z);
2176 enc.symbol(class, &mut c.class);
2177 let local = z - mv_class_base(class);
2178 if class == 0 {
2179 enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
2180 } else {
2181 let d = local >> 3;
2182 for i in 0..class {
2183 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
2184 }
2185 }
2186 Ok(())
2187}
2188
2189/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
2190/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
2191pub(super) fn write_dv(
2192 enc: &mut SymbolEncoder,
2193 cdfs: &mut Cdfs,
2194 dv: (i32, i32),
2195 pred: (i32, i32),
2196) -> Result<()> {
2197 let diff = (dv.0 - pred.0, dv.1 - pred.1);
2198 let joint = match (diff.0 != 0, diff.1 != 0) {
2199 (false, false) => 0,
2200 (false, true) => 1,
2201 (true, false) => 2,
2202 (true, true) => 3,
2203 };
2204 enc.symbol(joint, &mut cdfs.dv_joint);
2205 if diff.0 != 0 {
2206 write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
2207 }
2208 if diff.1 != 0 {
2209 write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
2210 }
2211 Ok(())
2212}
2213
2214/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
2215/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
2216/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
2217/// no transform size and no residual. Publishes the block into every
2218/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
2219/// skipped state a decoder reads back for it.
2220pub(super) fn write_intrabc_block(
2221 enc: &mut SymbolEncoder,
2222 cdfs: &mut Cdfs,
2223 neighbours: &mut Neighbours,
2224 dv: (i32, i32),
2225 mi: (usize, usize),
2226 side: usize,
2227) -> Result<()> {
2228 let skip_ctx =
2229 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
2230 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
2231 write_cdef_idx(enc, mi, true);
2232 enc.symbol(1, &mut cdfs.intrabc);
2233 write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
2234 note_intrabc(dv);
2235 // The bands: DC_PRED mode (what the decoder forces), no coefficients
2236 // anywhere (skip), the block's own side for the partition context, the
2237 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
2238 // for the deblock grid, and `skip` itself for the next block's skip
2239 // context.
2240 // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
2241 // sign vote, and a skipped block leaves every context cleared.
2242 let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
2243 for cell in 0..(side / SUB).max(1) {
2244 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
2245 neighbours.above_mode[c + cell] = DC_PRED;
2246 neighbours.left_mode[r + cell] = DC_PRED;
2247 neighbours.above_side[c + cell] = side;
2248 neighbours.left_side[r + cell] = side;
2249 }
2250 neighbours.record_mi_planes(mi, side, &empty, true);
2251 neighbours.record_tx(mi, side, side.min(64));
2252 for cell in 0..side / MI {
2253 neighbours.above_skip[mi.1 + cell] = true;
2254 neighbours.left_skip[mi.0 + cell] = true;
2255 }
2256 Ok(())
2257}
2258
2259/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
2260/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
2261/// constant.
2262pub(crate) const UV_CFL_PRED: usize = 13;
2263
2264/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
2265/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
2266/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
2267/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
2268/// CfL block is nonzero by construction.
2269pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
2270 let sign = |a: i32| match a.signum() {
2271 0 => 0,
2272 -1 => 1,
2273 _ => 2,
2274 };
2275 let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
2276 (0..8)
2277 .find(|&j| {
2278 let su = ((j + 1) * 11) >> 5;
2279 (su, (j + 1) - 3 * su) == (want_u, want_v)
2280 })
2281 .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
2282}
2283
2284/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
2285/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
2286/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
2287pub(super) fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
2288 let joint = joint as i32;
2289 let su = ((joint + 1) * 11) >> 5;
2290 let sv = (joint + 1) - 3 * su;
2291 if plane == 0 {
2292 (joint + 1 - 3) as usize
2293 } else {
2294 (sv * 3 + su - 3) as usize
2295 }
2296}
2297
2298/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
2299/// tables -- the encoder's RD price for the CfL arm.
2300pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
2301 use crate::encode::symbol_bits;
2302 let joint = cfl_joint_sign(alpha_u, alpha_v);
2303 let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
2304 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
2305 if alpha != 0 {
2306 bits += symbol_bits(
2307 &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
2308 (alpha.unsigned_abs() - 1) as usize,
2309 );
2310 }
2311 }
2312 bits
2313}
2314
2315/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
2316/// plane's magnitude where its sign is nonzero.
2317pub(super) fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
2318 let joint = cfl_joint_sign(alpha_u, alpha_v);
2319 enc.symbol(joint, &mut cdfs.cfl_sign);
2320 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
2321 if alpha != 0 {
2322 enc.symbol(
2323 (alpha.unsigned_abs() - 1) as usize,
2324 &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
2325 );
2326 }
2327 }
2328}
2329
2330// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
2331#[allow(clippy::too_many_arguments)]
2332pub(super) fn write_intra_mode(
2333 enc: &mut SymbolEncoder,
2334 cdfs: &mut Cdfs,
2335 neighbours: &mut Neighbours,
2336 block: &BlockCoeffs,
2337 above_mode: usize,
2338 left_mode: usize,
2339 cfl: bool,
2340 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
2341 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
2342 mi: (usize, usize),
2343 // The block's side in samples, which gates the palette syntax below
2344 // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
2345 side: usize,
2346) -> usize {
2347 let mode = usize::from(block.mode);
2348 // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
2349 // above + left. Every block this writer codes outside an `allow_intrabc`
2350 // frame is unskipped, so both bands stay false and this stays 0 -- the
2351 // literal every stream before this lane was written with.
2352 let skip_ctx =
2353 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
2354 enc.symbol(0, &mut cdfs.skip[skip_ctx]);
2355 write_cdef_idx(enc, mi, false);
2356 // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
2357 // block of an `allow_intrabc` frame, not only the ones that use it.
2358 if intrabc_armed() {
2359 enc.symbol(0, &mut cdfs.intrabc);
2360 }
2361 enc.symbol(
2362 mode,
2363 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
2364 );
2365 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
2366 if (V_PRED..=D67_PRED).contains(&mode) {
2367 enc.symbol(
2368 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
2369 &mut cdfs.angle_delta[mode - V_PRED],
2370 );
2371 }
2372 // A block small enough to be offered chroma from luma reads the wider
2373 // table even when it does not take the mode.
2374 let uv_mode = usize::from(block.uv_mode);
2375 if cfl {
2376 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
2377 } else {
2378 debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
2379 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
2380 }
2381 if uv_mode == UV_CFL_PRED {
2382 write_cfl_alphas(
2383 enc,
2384 cdfs,
2385 block
2386 .cfl_alphas
2387 .expect("a UV_CFL_PRED block carries its alphas"),
2388 );
2389 }
2390 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
2391 // the luma delta reads, indexed by the chroma mode.
2392 if (V_PRED..=D67_PRED).contains(&uv_mode) {
2393 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
2394 }
2395 // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
2396 // the decoder's own read in `read_intra_mode`: on a frame whose header set
2397 // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
2398 // chroma pair each carry a use-palette flag. Both contexts are 0 here --
2399 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
2400 // codes none -- exactly the ctx-0 read the decoder does under the same
2401 // condition.
2402 write_palette_syntax(
2403 enc,
2404 cdfs,
2405 neighbours,
2406 block.palette.as_ref(),
2407 block.palette_uv.as_ref(),
2408 block.filter_intra,
2409 mode,
2410 uv_mode,
2411 mi,
2412 side,
2413 );
2414 mode
2415}
2416
2417/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
2418/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
2419/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
2420/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
2421/// then codes its size, its colours (against the neighbour colour cache) and
2422/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
2423/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
2424/// by the three intra arms of the inter-frame writers, which read the same
2425/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
2426///
2427/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
2428/// one point every block passes through), so a block that takes no palette
2429/// still clears what the column held.
2430#[allow(clippy::too_many_arguments)]
2431pub(super) fn write_palette_syntax(
2432 enc: &mut SymbolEncoder,
2433 cdfs: &mut Cdfs,
2434 neighbours: &mut Neighbours,
2435 palette: Option<&PaletteY>,
2436 palette_uv: Option<&PaletteUv>,
2437 // lane-fintra: this block's chosen `filter_intra_mode`, or `None`. Written
2438 // here rather than by the caller because its symbol sits BETWEEN the
2439 // palette colour lists and the colour-index maps (decode.rs
2440 // `read_intra_mode`), which is inside this function.
2441 filter_intra: Option<u8>,
2442 mode: usize,
2443 uv_mode: usize,
2444 mi: (usize, usize),
2445 side: usize,
2446) {
2447 if !screen_armed() {
2448 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
2449 return;
2450 }
2451 let palette = palette.filter(|_| mode == DC_PRED);
2452 let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
2453 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2454 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2455 let uv_cache = neighbours.palette_uv_cache(mi);
2456 if mode == DC_PRED {
2457 enc.symbol(
2458 usize::from(palette.is_some()),
2459 &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
2460 );
2461 }
2462 if let Some(pal) = palette {
2463 let n = usize::from(pal.size);
2464 enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
2465 write_palette_colors_y(enc, &pal.colors[..n], &cache);
2466 }
2467 if uv_mode == DC_PRED {
2468 enc.symbol(
2469 usize::from(palette_uv.is_some()),
2470 &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
2471 );
2472 }
2473 if let Some(pal) = palette_uv {
2474 let n = usize::from(pal.size);
2475 enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
2476 write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
2477 }
2478 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
2479 // Both colour-index maps come after BOTH colour lists, in plane order
2480 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
2481 // The on-screen extent of THIS block, from the frame mi dims armed
2482 // for this tile write -- the decoder's `palette_onscreen` half.
2483 let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims());
2484 if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) {
2485 PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2486 }
2487 if let Some(pal) = palette {
2488 let n = usize::from(pal.size);
2489 write_color_index_map(
2490 enc,
2491 &mut cdfs.palette_y_color_index[n - 2],
2492 &pal.map,
2493 side,
2494 n,
2495 on,
2496 );
2497 note_palette(n);
2498 }
2499 if let Some(pal) = palette_uv {
2500 let n = usize::from(pal.size);
2501 let uv_side = palette_uv_side(side);
2502 write_color_index_map(
2503 enc,
2504 &mut cdfs.palette_uv_color_index[n - 2],
2505 &pal.map,
2506 uv_side,
2507 n,
2508 // The encoder writes 4:2:0 only (`palette_uv_side` above).
2509 crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side), (1, 1)),
2510 );
2511 note_palette_uv(n);
2512 }
2513 } else {
2514 // Below `av1_allow_palette`'s size bound there is no palette syntax at
2515 // all, but `av1_filter_intra_allowed_bsize` still admits the block.
2516 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
2517 }
2518 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
2519 neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
2520}
2521