forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-thread1' (24d7e690): the 38 per-frame decode-state thread_locals become one crate-private FrameCtx threaded through the decoder; public encoder signatures unchanged; byte-exact on four inputs, 2.6% fewer instructions (merge also makes decode_inter_frame_tile and InterStripChroma crate-private for a clean workspace check)

Browse files at this commit

63370ce41c84f60b9e7def94d4c7eb6c8bd476cdAhmet Kaan GümüşParent: e320ba71c71b70

11 changed files +1700 -1468

crates/ec-av1/src/decode.rsmodified+1197 -1141

Diff too large; view file

@@ -27,6 +27,130 @@ use ec_av1_syntax::{
27 };27 };
28 use ec_core::{Error, Result};28 use ec_core::{Error, Result};
29 29
30+/// Per-frame decode state, one instance per decoded stream (lane-thread1).
31+///
32+/// Every field here used to be a `thread_local!` static, which made a decode a
33+/// function of the calling THREAD's history rather than of the bitstream alone
34+/// -- and made frame-parallel decoding impossible, since a worker thread sees
35+/// empty state. The cells keep exactly the interior mutability the statics
36+/// had, so every read/write site is byte-identical; what changes is WHERE the
37+/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
38+/// the decode call graph.
39+///
40+/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
41+/// exactly one thread's decode, and is never shared between workers.
42+pub(crate) struct FrameCtx {
43+ pub(crate) sb128_flag: std::cell::Cell<bool>,
44+ pub(crate) cdef_bits: std::cell::Cell<u8>,
45+ pub(crate) bit_depth: std::cell::Cell<u8>,
46+ pub(crate) superres: std::cell::Cell<(u32, u32)>,
47+ pub(crate) cdef_transmitted: std::cell::Cell<bool>,
48+ pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
49+ pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
50+ pub(crate) delta_q_present: std::cell::Cell<bool>,
51+ pub(crate) delta_q_res: std::cell::Cell<i32>,
52+ pub(crate) current_q_idx: std::cell::Cell<i32>,
53+ pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
54+ pub(crate) delta_lf_present: std::cell::Cell<bool>,
55+ pub(crate) delta_lf_res: std::cell::Cell<i32>,
56+ pub(crate) delta_lf_multi: std::cell::Cell<bool>,
57+ pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
58+ pub(crate) seg: std::cell::RefCell<SegmentationParams>,
59+ pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
60+ pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
61+ pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
62+ pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
63+ pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
64+ pub(crate) cur_segment_id: std::cell::Cell<u8>,
65+ pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
66+ pub(crate) tx_select_inter: std::cell::Cell<bool>,
67+ pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
68+ pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
69+ pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
70+ pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
71+ pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
72+ pub(crate) luma_tx_type: std::cell::Cell<TxType>,
73+ pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
74+ pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
75+ pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
76+ pub(crate) inter_last_mc:
77+ std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
78+ pub(crate) enable_edge_filter: std::cell::Cell<bool>,
79+ pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
80+ pub(crate) reach_sb_px: std::cell::Cell<usize>,
81+ pub(crate) grain_bit_depth: std::cell::Cell<u32>,
82+}
83+
84+impl std::fmt::Debug for FrameCtx {
85+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86+ f.write_str("FrameCtx")
87+ }
88+}
89+
90+impl FrameCtx {
91+ /// A fresh context, every field at the default its thread-local
92+ /// predecessor was born with.
93+ pub(crate) fn new() -> Self {
94+ Self {
95+ sb128_flag: std::cell::Cell::new(false),
96+ cdef_bits: std::cell::Cell::new(0),
97+ bit_depth: std::cell::Cell::new(8),
98+ superres: std::cell::Cell::new((0, 8)),
99+ cdef_transmitted: std::cell::Cell::new(false),
100+ cdef_sb_cols: std::cell::Cell::new(0),
101+ cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
102+ delta_q_present: std::cell::Cell::new(false),
103+ delta_q_res: std::cell::Cell::new(1),
104+ current_q_idx: std::cell::Cell::new(0),
105+ quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
106+ y_dc: 0,
107+ u_dc: 0,
108+ u_ac: 0,
109+ v_dc: 0,
110+ v_ac: 0,
111+ }),
112+ delta_lf_present: std::cell::Cell::new(false),
113+ delta_lf_res: std::cell::Cell::new(1),
114+ delta_lf_multi: std::cell::Cell::new(false),
115+ current_delta_lf: std::cell::Cell::new([0; 4]),
116+ seg: std::cell::RefCell::new(SegmentationParams::default()),
117+ seg_ids: std::cell::RefCell::new(Vec::new()),
118+ prev_seg_ids: std::cell::RefCell::new(Vec::new()),
119+ seg_mi_dims: std::cell::Cell::new((0, 0)),
120+ above_seg_pred: std::cell::RefCell::new(Vec::new()),
121+ left_seg_pred: std::cell::RefCell::new(Vec::new()),
122+ cur_segment_id: std::cell::Cell::new(0),
123+ seg_tile_origin: std::cell::Cell::new((0, 0)),
124+ tx_select_inter: std::cell::Cell::new(false),
125+ reduced_tx_set_inter: std::cell::Cell::new(true),
126+ enable_filter_intra_inter: std::cell::Cell::new(false),
127+ palette_pred: std::cell::RefCell::new(None),
128+ intrabc_mi_grid: std::cell::RefCell::new(None),
129+ intrabc_dv: std::cell::Cell::new(None),
130+ luma_tx_type: std::cell::Cell::new(TxType::DctDct),
131+ intrabc_chroma_tx: std::cell::Cell::new(None),
132+ intra_in_inter_mode: std::cell::Cell::new(None),
133+ inter_strip_chroma: std::cell::Cell::new(None),
134+ inter_last_mc: std::cell::Cell::new(None),
135+ enable_edge_filter: std::cell::Cell::new(false),
136+ last_frame_wide_margin: std::cell::RefCell::new(None),
137+ reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
138+ grain_bit_depth: std::cell::Cell::new(8),
139+ }
140+ }
141+}
142+
143+/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
144+/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
145+/// `with` still wins for the scratch pools and gate counters that stay
146+/// thread-local.
147+pub(crate) trait WithRef {
148+ fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
149+ f(self)
150+ }
151+}
152+impl<T: ?Sized> WithRef for T {}
153+
30 use crate::cdf;154 use crate::cdf;
31 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};155 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
32 use crate::encode::{Picture, Reach};156 use crate::encode::{Picture, Reach};
@@ -103,23 +227,20 @@ pub(crate) fn coeff_trace_on() -> bool {
103 }227 }
104 }228 }
105 229
106-thread_local! {
107- static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
108-}
109 230
110 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).231 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
111-pub(crate) fn set_sb128(v: bool) {232+pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
112- SB128.with(|c| c.set(v));233+ fctx.sb128_flag.with(|c| c.set(v));
113- crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });234+ crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
114 }235 }
115 236
116-fn sb128() -> bool {237+fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
117- SB128.with(|c| c.get())238+ fctx.sb128_flag.with(|c| c.get())
118 }239 }
119 240
120 /// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).241 /// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
121-pub(crate) fn sb_mi_cur() -> u32 {242+pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
122- if sb128() { SB_MI * 2 } else { SB_MI }243+ if sb128(fctx) { SB_MI * 2 } else { SB_MI }
123 }244 }
124 245
125 /// How many real 128-level partition symbols this decoder has read, and how246 /// How many real 128-level partition symbols this decoder has read, and how
@@ -246,9 +367,6 @@ pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
246 // frame-level flag through the recursive block decode -- `0` (the default)367 // frame-level flag through the recursive block decode -- `0` (the default)
247 // makes every call a true no-op, matching every existing gate stream's368 // makes every call a true no-op, matching every existing gate stream's
248 // `cdef_bits == 0` behaviour exactly.369 // `cdef_bits == 0` behaviour exactly.
249-thread_local! {
250- static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
251-}
252 // lane-realworld r8: the sequence header's `color_config.bit_depth`, set370 // lane-realworld r8: the sequence header's `color_config.bit_depth`, set
253 // once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`371 // once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
254 // call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still372 // call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
@@ -257,26 +375,22 @@ thread_local! {
257 // `8`) is stage 1 of widening past that refusal without re-deriving every375 // `8`) is stage 1 of widening past that refusal without re-deriving every
258 // clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of376 // clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
259 // depth (this decoder's own internal choice, matches dav1d/libaom).377 // depth (this decoder's own internal choice, matches dav1d/libaom).
260-thread_local! {
261- static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
262-}
263 /// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current378 /// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
264 /// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.379 /// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
265-pub(crate) fn sample_max() -> i32 {380+pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
266- (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1381+ (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
267 }382 }
268 /// The current stream's bit depth, for callers (e.g. dequant) that need the383 /// The current stream's bit depth, for callers (e.g. dequant) that need the
269 /// raw value rather than the derived clamp bound.384 /// raw value rather than the derived clamp bound.
270-pub(crate) fn bit_depth() -> u8 {385+pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
271- BIT_DEPTH.with(std::cell::Cell::get)386+ fctx.bit_depth.with(std::cell::Cell::get)
272 }387 }
273 /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from388 /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
274 /// [`crate::stream`]'s decode loop.389 /// [`crate::stream`]'s decode loop.
275-pub(crate) fn set_bit_depth(bit_depth: u8) {390+pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
276- BIT_DEPTH.with(|c| c.set(bit_depth));391+ fctx.bit_depth.with(|c| c.set(bit_depth));
277 }392 }
278 393
279-thread_local! {
280 /// This frame's superres state: `(upscaled_width, superres_denom)`, or394 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
281 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs395 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
282 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,396 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
@@ -287,40 +401,29 @@ thread_local! {
287 /// superres arms). Set once per frame from [`crate::stream`]'s decode401 /// superres arms). Set once per frame from [`crate::stream`]'s decode
288 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame402 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
289 /// so a later frame never inherits it.403 /// so a later frame never inherits it.
290- static SUPERRES: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 8)) };
291-}
292 404
293 /// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and405 /// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
294 /// `denom` 8) for a frame that is not superres-scaled.406 /// `denom` 8) for a frame that is not superres-scaled.
295-pub(crate) fn set_superres(upscaled_width: u32, denom: u32) {407+pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
296- SUPERRES.with(|c| c.set((upscaled_width, denom)));408+ fctx.superres.with(|c| c.set((upscaled_width, denom)));
297 }409 }
298 410
299 /// `(upscaled_width, superres_denom)` when this frame is superres-scaled411 /// `(upscaled_width, superres_denom)` when this frame is superres-scaled
300 /// (libaom `av1_superres_scaled`), else `None`.412 /// (libaom `av1_superres_scaled`), else `None`.
301-pub(crate) fn superres() -> Option<(u32, u32)> {413+pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
302- let (w, d) = SUPERRES.with(std::cell::Cell::get);414+ let (w, d) = fctx.superres.with(std::cell::Cell::get);
303 (w > 0 && d != 8).then_some((w, d))415 (w > 0 && d != 8).then_some((w, d))
304 }416 }
305 // Whether this superblock's single CDEF unit (this decoder has no 128x128417 // Whether this superblock's single CDEF unit (this decoder has no 128x128
306 // SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal418 // SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
307 // read -- reset to `false` at the top of each superblock in the two tile419 // read -- reset to `false` at the top of each superblock in the two tile
308 // loops, spec `read_cdef`'s `cdef_transmitted[index]`.420 // loops, spec `read_cdef`'s `cdef_transmitted[index]`.
309-thread_local! {
310- static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
311-}
312 // Number of superblock columns in the current tile's grid, so421 // Number of superblock columns in the current tile's grid, so
313 // [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into422 // [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
314 // [`CDEF_IDX_GRID`].423 // [`CDEF_IDX_GRID`].
315-thread_local! {
316- static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
317-}
318 // One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select424 // One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
319 // which of the header's `1 << cdef.bits` strength pairs applies to that425 // which of the header's `1 << cdef.bits` strength pairs applies to that
320 // superblock's samples.426 // superblock's samples.
321-thread_local! {
322- static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
323-}
324 // How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]427 // How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
325 // has read, across every call on the current thread -- the gate's proof that a428 // has read, across every call on the current thread -- the gate's proof that a
326 // `cdef_bits > 0` stream actually reached the new reader rather than every429 // `cdef_bits > 0` stream actually reached the new reader rather than every
@@ -392,33 +495,15 @@ pub(crate) fn edge_filter_mi_fix_hits() -> usize {
392 // 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a495 // 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
393 // true no-op, matching every existing gate stream's `delta_q_present == 0`496 // true no-op, matching every existing gate stream's `delta_q_present == 0`
394 // behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.497 // behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
395-thread_local! {
396- static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
397- static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
398-}
399 // The running quantizer index (spec `CurrentQIndex`, libaom498 // The running quantizer index (spec `CurrentQIndex`, libaom
400 // `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the499 // `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
401 // top of every tile (spec `decode_tile`), carried across superblocks within500 // top of every tile (spec `decode_tile`), carried across superblocks within
402 // that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the501 // that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
403 // dequantization call sites instead of the frame-constant `base_q_idx`.502 // dequantization call sites instead of the frame-constant `base_q_idx`.
404-thread_local! {
405- static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
406-}
407 // This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,503 // This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
408 // spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not504 // spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
409 // per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read505 // per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
410 // back at every dequantization call site keyed on which plane it is doing.506 // back at every dequantization call site keyed on which plane it is doing.
411-thread_local! {
412- static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
413- std::cell::Cell::new(crate::quant::QuantDeltas {
414- y_dc: 0,
415- u_dc: 0,
416- u_ac: 0,
417- v_dc: 0,
418- v_ac: 0,
419- })
420- };
421-}
422 // How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has507 // How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
423 // read, across every call on the current thread -- the gate's proof that a508 // read, across every call on the current thread -- the gate's proof that a
424 // `delta_q_present` stream actually reached the new reader.509 // `delta_q_present` stream actually reached the new reader.
@@ -434,8 +519,8 @@ pub(crate) fn delta_q_hits() -> usize {
434 /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =519 /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
435 /// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads520 /// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
436 /// one), so it is always `0` here.521 /// one), so it is always `0` here.
437-fn plane_q_delta(plane_idx: usize) -> (i32, i32) {522+fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
438- let d = QUANT_DELTAS.with(|c| c.get());523+ let d = fctx.quant_deltas.with(|c| c.get());
439 match plane_idx {524 match plane_idx {
440 0 => (d.y_dc, 0),525 0 => (d.y_dc, 0),
441 1 => (d.u_dc, d.u_ac),526 1 => (d.u_dc, d.u_ac),
@@ -452,11 +537,11 @@ fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
452 /// top-left leaf is the only block that can ever land there), or when that537 /// top-left leaf is the only block that can ever land there), or when that
453 /// leaf both *is* the whole superblock and is `skip` (the one case libaom538 /// leaf both *is* the whole superblock and is `skip` (the one case libaom
454 /// itself skips the read, state carrying over unchanged).539 /// itself skips the read, state carrying over unchanged).
455-fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {540+fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
456- if !DELTA_Q_PRESENT.with(|c| c.get()) {541+ if !fctx.delta_q_present.with(|c| c.get()) {
457 return;542 return;
458 }543 }
459- let sb_mi = sb_mi_cur() as usize;544+ let sb_mi = sb_mi_cur(fctx) as usize;
460 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {545 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
461 return;546 return;
462 }547 }
@@ -478,25 +563,17 @@ fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_
478 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };563 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
479 let reduced = if sign_negative { -abs } else { abs };564 let reduced = if sign_negative { -abs } else { abs };
480 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));565 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
481- let res = DELTA_Q_RES.with(|c| c.get());566+ let res = fctx.delta_q_res.with(|c| c.get());
482- CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));567+ fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
483 }568 }
484 569
485 // lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`570 // lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
486 // (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.571 // (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
487-thread_local! {
488- static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
489- static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
490- static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
491-}
492 // The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,572 // The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
493 // `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,573 // `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
494 // mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever574 // mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
495 // updates index 0 and every reader treats that as the value for all 4575 // updates index 0 and every reader treats that as the value for all 4
496 // indices (spec `read_delta_lf_params`'s own single-cdf branch).576 // indices (spec `read_delta_lf_params`'s own single-cdf branch).
497-thread_local! {
498- static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
499-}
500 // How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has577 // How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
501 // read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].578 // read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
502 thread_local! {579 thread_local! {
@@ -513,11 +590,11 @@ pub(crate) fn delta_lf_hits() -> usize {
513 /// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over590 /// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
514 /// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or591 /// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
515 /// read once into index 0 otherwise.592 /// read once into index 0 otherwise.
516-fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {593+fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
517- if !DELTA_LF_PRESENT.with(|c| c.get()) {594+ if !fctx.delta_lf_present.with(|c| c.get()) {
518 return;595 return;
519 }596 }
520- let sb_mi = sb_mi_cur() as usize;597+ let sb_mi = sb_mi_cur(fctx) as usize;
521 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {598 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
522 return;599 return;
523 }600 }
@@ -529,10 +606,10 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
529 if is_whole_sb && skip {606 if is_whole_sb && skip {
530 return;607 return;
531 }608 }
532- let multi = DELTA_LF_MULTI.with(|c| c.get());609+ let multi = fctx.delta_lf_multi.with(|c| c.get());
533- let res = DELTA_LF_RES.with(|c| c.get());610+ let res = fctx.delta_lf_res.with(|c| c.get());
534 let count = if multi { 4 } else { 1 };611 let count = if multi { 4 } else { 1 };
535- let mut cur = CURRENT_DELTA_LF.with(|c| c.get());612+ let mut cur = fctx.current_delta_lf.with(|c| c.get());
536 for i in 0..count {613 for i in 0..count {
537 let mut abs = if multi {614 let mut abs = if multi {
538 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32615 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
@@ -550,7 +627,7 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
550 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);627 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
551 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));628 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
552 }629 }
553- CURRENT_DELTA_LF.with(|c| c.set(cur));630+ fctx.current_delta_lf.with(|c| c.set(cur));
554 }631 }
555 632
556 /// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right633 /// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
@@ -559,18 +636,18 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
559 /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/636 /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
560 /// `allow_intrabc`, so neither needs a separate check here. Reads once per637 /// `allow_intrabc`, so neither needs a separate check here. Reads once per
561 /// superblock, at the first non-skip block.638 /// superblock, at the first non-skip block.
562-fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {639+fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
563- let bits = CDEF_BITS.with(|c| c.get());640+ let bits = fctx.cdef_bits.with(|c| c.get());
564- if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {641+ if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
565 return;642 return;
566 }643 }
567 let idx = dec.literal(u32::from(bits)) as u8;644 let idx = dec.literal(u32::from(bits)) as u8;
568- CDEF_TRANSMITTED.with(|c| c.set(true));645+ fctx.cdef_transmitted.with(|c| c.set(true));
569 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));646 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
570 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);647 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
571- let sb_cols = CDEF_SB_COLS.with(|c| c.get());648+ let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
572 if sb_cols > 0 {649 if sb_cols > 0 {
573- CDEF_IDX_GRID.with(|g| {650+ fctx.cdef_idx_grid.with(|g| {
574 let mut g = g.borrow_mut();651 let mut g = g.borrow_mut();
575 let i = sb_r * sb_cols + sb_c;652 let i = sb_r * sb_cols + sb_c;
576 if i < g.len() {653 if i < g.len() {
@@ -591,25 +668,16 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip:
591 // PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which668 // PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
592 // is what the oracle every gate here compares against actually does.669 // is what the oracle every gate here compares against actually does.
593 thread_local! {670 thread_local! {
594- static SEG: std::cell::RefCell<SegmentationParams> =
595- std::cell::RefCell::new(SegmentationParams::default());
596 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries671 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
597 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).672 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
598- static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
599 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when673 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
600 /// this frame has no primary reference (spec `load_previous_segment_ids`).674 /// this frame has no primary reference (spec `load_previous_segment_ids`).
601- static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
602 /// `(mi_rows, mi_cols)` for both maps above.675 /// `(mi_rows, mi_cols)` for both maps above.
603- static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
604 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi676 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
605 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which677 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
606 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.678 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
607- static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
608- static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
609 /// The block currently being decoded -- read back by [`block_q_idx`].679 /// The block currently being decoded -- read back by [`block_q_idx`].
610- static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
611 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.680 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
612- static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
613 /// How many real `segment_id` symbols were read, and the set of segment681 /// How many real `segment_id` symbols were read, and the set of segment
614 /// ids any block ended up with -- the gate's proof the feature fired.682 /// ids any block ended up with -- the gate's proof the feature fired.
615 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };683 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
@@ -626,12 +694,12 @@ pub(crate) fn set_segmentation(
626 seg: SegmentationParams,694 seg: SegmentationParams,
627 mi_rows: usize,695 mi_rows: usize,
628 mi_cols: usize,696 mi_cols: usize,
629- prev: Option<&[u8]>,697+ prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
630 ) {698 ) {
631- SEG.with(|s| *s.borrow_mut() = seg);699+ fctx.seg.with(|s| *s.borrow_mut() = seg);
632- SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));700+ fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
633- SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);701+ fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
634- PREV_SEG_IDS.with(|m| {702+ fctx.prev_seg_ids.with(|m| {
635 let mut m = m.borrow_mut();703 let mut m = m.borrow_mut();
636 m.clear();704 m.clear();
637 if let Some(p) = prev {705 if let Some(p) = prev {
@@ -640,15 +708,15 @@ pub(crate) fn set_segmentation(
640 }708 }
641 }709 }
642 });710 });
643- ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);711+ fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
644- LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);712+ fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
645- CUR_SEGMENT_ID.with(|c| c.set(0));713+ fctx.cur_segment_id.with(|c| c.set(0));
646 }714 }
647 715
648 /// This frame's decoded segment map, to be stored into whichever reference716 /// This frame's decoded segment map, to be stored into whichever reference
649 /// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).717 /// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
650-pub(crate) fn take_segment_ids() -> Vec<u8> {718+pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
651- SEG_IDS.with(|m| m.borrow().clone())719+ fctx.seg_ids.with(|m| m.borrow().clone())
652 }720 }
653 721
654 /// How many `segment_id` symbols have been read (never reset per frame).722 /// How many `segment_id` symbols have been read (never reset per frame).
@@ -675,8 +743,8 @@ pub(crate) fn reset_segment_hits() {
675 743
676 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently744 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently
677 /// being decoded, with its `FeatureData` value.745 /// being decoded, with its `FeatureData` value.
678-fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {746+fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
679- SEG.with(|s| {747+ fctx.seg.with(|s| {
680 let s = s.borrow();748 let s = s.borrow();
681 s.feature_active(segment_id, feature)749 s.feature_active(segment_id, feature)
682 .then(|| i32::from(s.feature_data[segment_id][feature]))750 .then(|| i32::from(s.feature_data[segment_id][feature]))
@@ -687,29 +755,29 @@ fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
687 /// `av1_get_qindex`) for the block currently being decoded: the running755 /// `av1_get_qindex`) for the block currently being decoded: the running
688 /// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.756 /// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
689 /// Every dequant call site reads the block's quantizer through here.757 /// Every dequant call site reads the block's quantizer through here.
690-fn block_q_idx() -> i32 {758+fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
691- let base = CURRENT_Q_IDX.with(|c| c.get());759+ let base = fctx.current_q_idx.with(|c| c.get());
692- let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;760+ let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
693- match seg_feature(seg_id, SEG_LVL_ALT_Q) {761+ match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
694 Some(data) => (base + data).clamp(0, 255),762 Some(data) => (base + data).clamp(0, 255),
695 None => base,763 None => base,
696 }764 }
697 }765 }
698 766
699 /// The segment id recorded for one mi cell of the current frame's map.767 /// The segment id recorded for one mi cell of the current frame's map.
700-fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {768+fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
701- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());769+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
702 if mi_r >= mi_rows || mi_c >= mi_cols {770 if mi_r >= mi_rows || mi_c >= mi_cols {
703 return 0;771 return 0;
704 }772 }
705- SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])773+ fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
706 }774 }
707 775
708 /// `set_segment_id`: stamps `id` over every mi cell this block covers.776 /// `set_segment_id`: stamps `id` over every mi cell this block covers.
709-fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {777+fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
710- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());778+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
711 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));779 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
712- SEG_IDS.with(|m| {780+ fctx.seg_ids.with(|m| {
713 let mut m = m.borrow_mut();781 let mut m = m.borrow_mut();
714 for y in 0..y_mis {782 for y in 0..y_mis {
715 for x in 0..x_mis {783 for x in 0..x_mis {
@@ -717,16 +785,16 @@ fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8)
717 }785 }
718 }786 }
719 });787 });
720- CUR_SEGMENT_ID.with(|c| c.set(id));788+ fctx.cur_segment_id.with(|c| c.set(id));
721 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));789 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
722 }790 }
723 791
724 /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over792 /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
725 /// `last_frame_seg_map`): the minimum previous-frame segment id over the793 /// `last_frame_seg_map`): the minimum previous-frame segment id over the
726 /// block's own mi footprint. `0` when there is no previous map.794 /// block's own mi footprint. `0` when there is no previous map.
727-fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {795+fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
728- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());796+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
729- PREV_SEG_IDS.with(|m| {797+ fctx.prev_seg_ids.with(|m| {
730 let m = m.borrow();798 let m = m.borrow();
731 if m.is_empty() {799 if m.is_empty() {
732 return 0;800 return 0;
@@ -767,12 +835,12 @@ fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
767 835
768 /// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current836 /// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
769 /// frame's already-decoded above/left/above-left neighbours.837 /// frame's already-decoded above/left/above-left neighbours.
770-fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {838+fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
771- let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());839+ let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
772 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);840 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
773- let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));841+ let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
774- let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));842+ let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
775- let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));843+ let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
776 let ctx = match prev_ul {844 let ctx = match prev_ul {
777 None => 0,845 None => 0,
778 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,846 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
@@ -796,14 +864,14 @@ fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
796 /// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id864 /// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
797 /// when `skip`, otherwise one `segment_id` symbol de-interleaved against865 /// when `skip`, otherwise one `segment_id` symbol de-interleaved against
798 /// that prediction. Does NOT write the map -- callers do.866 /// that prediction. Does NOT write the map -- callers do.
799-fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {867+fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
800- let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);868+ let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
801 if skip {869 if skip {
802 return pred as u8;870 return pred as u8;
803 }871 }
804 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;872 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
805 SEG_ID_HITS.with(|c| c.set(c.get() + 1));873 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
806- let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));874+ let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
807 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8875 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
808 }876 }
809 877
@@ -817,19 +885,19 @@ fn intra_segment_id(
817 mi_c: usize,885 mi_c: usize,
818 w_mi: usize,886 w_mi: usize,
819 h_mi: usize,887 h_mi: usize,
820- skip: bool,888+ skip: bool, fctx: &crate::decode::FrameCtx,
821 ) {889 ) {
822- if !SEG.with(|s| s.borrow().enabled) {890+ if !fctx.seg.with(|s| s.borrow().enabled) {
823 return;891 return;
824 }892 }
825- let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);893+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
826- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);894+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
827 }895 }
828 896
829 /// Whether this frame's intra blocks read their `segment_id` before `skip`897 /// Whether this frame's intra blocks read their `segment_id` before `skip`
830 /// (`SegIdPreSkip`); `false` also when segmentation is off.898 /// (`SegIdPreSkip`); `false` also when segmentation is off.
831-fn seg_id_pre_skip() -> bool {899+fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
832- SEG.with(|s| {900+ fctx.seg.with(|s| {
833 let s = s.borrow();901 let s = s.borrow();
834 s.enabled && s.seg_id_pre_skip902 s.enabled && s.seg_id_pre_skip
835 })903 })
@@ -846,9 +914,9 @@ fn inter_segment_id(
846 w_mi: usize,914 w_mi: usize,
847 h_mi: usize,915 h_mi: usize,
848 skip: bool,916 skip: bool,
849- pre_skip: bool,917+ pre_skip: bool, fctx: &crate::decode::FrameCtx,
850 ) {918 ) {
851- let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {919+ let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
852 let s = s.borrow();920 let s = s.borrow();
853 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)921 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
854 });922 });
@@ -857,8 +925,8 @@ fn inter_segment_id(
857 }925 }
858 if !update_map {926 if !update_map {
859 // The map is inherited wholesale from the previous frame.927 // The map is inherited wholesale from the previous frame.
860- let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);928+ let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
861- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);929+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
862 return;930 return;
863 }931 }
864 if pre_skip && !pre_skip_frame {932 if pre_skip && !pre_skip_frame {
@@ -867,40 +935,40 @@ fn inter_segment_id(
867 if !pre_skip && skip {935 if !pre_skip && skip {
868 // libaom: a skipped block never codes `seg_id_predicted`, and its936 // libaom: a skipped block never codes `seg_id_predicted`, and its
869 // segment id is the spatial prediction.937 // segment id is the spatial prediction.
870- stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);938+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
871- let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);939+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
872- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);940+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
873 return;941 return;
874 }942 }
875 let id = if temporal_update {943 let id = if temporal_update {
876- let ctx = seg_pred_ctx(mi_r, mi_c);944+ let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
877 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;945 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
878 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));946 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
879- stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));947+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
880 if predicted {948 if predicted {
881- predicted_segment_id(mi_r, mi_c, w_mi, h_mi)949+ predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
882 } else {950 } else {
883- read_segment_id(dec, cdfs, mi_r, mi_c, false)951+ read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
884 }952 }
885 } else {953 } else {
886- read_segment_id(dec, cdfs, mi_r, mi_c, false)954+ read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
887 };955 };
888- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);956+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
889 }957 }
890 958
891 /// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.959 /// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
892-fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {960+fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
893 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and961 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
894 // so contribute 0) outside the tile -- the availability check here is962 // so contribute 0) outside the tile -- the availability check here is
895 // what keeps a previous tile's stamps out of this tile's context.963 // what keeps a previous tile's stamps out of this tile's context.
896- let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());964+ let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
897 let above = if mi_r > row0 {965 let above = if mi_r > row0 {
898- ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))966+ fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
899 } else {967 } else {
900 0968 0
901 };969 };
902 let left = if mi_c > col0 {970 let left = if mi_c > col0 {
903- LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))971+ fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
904 } else {972 } else {
905 0973 0
906 };974 };
@@ -908,8 +976,8 @@ fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
908 }976 }
909 977
910 /// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.978 /// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
911-fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {979+fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
912- ABOVE_SEG_PRED.with(|m| {980+ fctx.above_seg_pred.with(|m| {
913 let mut m = m.borrow_mut();981 let mut m = m.borrow_mut();
914 for i in 0..w_mi {982 for i in 0..w_mi {
915 if let Some(cell) = m.get_mut(mi_c + i) {983 if let Some(cell) = m.get_mut(mi_c + i) {
@@ -917,7 +985,7 @@ fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8)
917 }985 }
918 }986 }
919 });987 });
920- LEFT_SEG_PRED.with(|m| {988+ fctx.left_seg_pred.with(|m| {
921 let mut m = m.borrow_mut();989 let mut m = m.borrow_mut();
922 for i in 0..h_mi {990 for i in 0..h_mi {
923 if let Some(cell) = m.get_mut(mi_r + i) {991 if let Some(cell) = m.get_mut(mi_r + i) {
@@ -974,10 +1042,10 @@ fn tu_reach(
974 px: usize,1042 px: usize,
975 py: usize,1043 py: usize,
976 width: usize,1044 width: usize,
977- height: usize,1045+ height: usize, fctx: &crate::decode::FrameCtx,
978 ) -> Reach {1046 ) -> Reach {
979 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);1047 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
980- let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);1048+ let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
981 if fixed != standalone {1049 if fixed != standalone {
982 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));1050 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
983 }1051 }
@@ -1163,13 +1231,9 @@ thread_local! {
1163 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --1231 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1164 // `decode_inter_block` already carries forty parameters and both are1232 // `decode_inter_block` already carries forty parameters and both are
1165 // frame-constant.1233 // frame-constant.
1166- static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1167- static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1168 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,1234 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1169 // frame-constant like the two above and stashed the same way -- an intra1235 // frame-constant like the two above and stashed the same way -- an intra
1170 // block inside an inter frame reads `use_filter_intra` under it.1236 // block inside an inter frame reads `use_filter_intra` under it.
1171- static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
1172- const { std::cell::Cell::new(false) };
1173 }1237 }
1174 1238
1175 /// Current value of [`TXFM_SPLIT_READS`].1239 /// Current value of [`TXFM_SPLIT_READS`].
@@ -1243,11 +1307,11 @@ fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1243 pub(crate) fn set_inter_tx_mode(1307 pub(crate) fn set_inter_tx_mode(
1244 tx_select: bool,1308 tx_select: bool,
1245 reduced_tx_set: bool,1309 reduced_tx_set: bool,
1246- enable_filter_intra: bool,1310+ enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1247 ) {1311 ) {
1248- TX_SELECT_INTER.with(|c| c.set(tx_select));1312+ fctx.tx_select_inter.with(|c| c.set(tx_select));
1249- REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));1313+ fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1250- ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));1314+ fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1251 }1315 }
1252 1316
1253 // How many `partition_w16` reads (a 16x16 block's own partition symbol, key1317 // How many `partition_w16` reads (a 16x16 block's own partition symbol, key
@@ -1817,7 +1881,6 @@ pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1817 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)1881 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1818 }1882 }
1819 1883
1820-thread_local! {
1821 /// A just-decoded palette-Y block's own predicted pixels1884 /// A just-decoded palette-Y block's own predicted pixels
1822 /// (`side*side`, row-major, `colors[map[i]]`), consumed by1885 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1823 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the1886 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
@@ -1826,9 +1889,6 @@ thread_local! {
1826 /// alternative this avoids). Always empty again once that call consumes1889 /// alternative this avoids). Always empty again once that call consumes
1827 /// it (`.take()`), so a non-palette block's own `reconstruct` call never1890 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1828 /// sees stale state.1891 /// sees stale state.
1829- static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1830- const { std::cell::RefCell::new(None) };
1831-}
1832 1892
1833 1893
1834 /// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`1894 /// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
@@ -1837,21 +1897,21 @@ thread_local! {
1837 /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so1897 /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1838 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.1898 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1839 #[track_caller]1899 #[track_caller]
1840-fn set_palette_pred(buf: Vec<u16>) {1900+fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
1841 if crate::envflags::env_flag!("EC_DEBUG_PAL") {1901 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1842- let stale = PALETTE_PRED.with(|c| c.borrow().is_some());1902+ let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
1843 eprintln!(1903 eprintln!(
1844 "PALSET len={} stale={stale} at {}",1904 "PALSET len={} stale={stale} at {}",
1845 buf.len(),1905 buf.len(),
1846 std::panic::Location::caller()1906 std::panic::Location::caller()
1847 );1907 );
1848 }1908 }
1849- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));1909+ fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
1850 }1910 }
1851 1911
1852 #[track_caller]1912 #[track_caller]
1853-fn take_palette_pred() -> Option<Vec<u16>> {1913+fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
1854- let got = PALETTE_PRED.with(|c| c.borrow_mut().take());1914+ let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
1855 if crate::envflags::env_flag!("EC_DEBUG_PAL") {1915 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1856 eprintln!(1916 eprintln!(
1857 "PALTAKE len={:?} at {}",1917 "PALTAKE len={:?} at {}",
@@ -1874,37 +1934,32 @@ thread_local! {
1874 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off1934 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1875 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would1935 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1876 /// be wrong there; upgrade = record from the rect/leaf paths too.1936 /// be wrong there; upgrade = record from the rect/leaf paths too.
1877- static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1878- const { std::cell::RefCell::new(None) };
1879 /// The block vector [`read_intra_mode`] just decoded, handed to1937 /// The block vector [`read_intra_mode`] just decoded, handed to
1880 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],1938 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1881 /// which the alternative -- a tenth tuple member through every caller --1939 /// which the alternative -- a tenth tuple member through every caller --
1882 /// already avoids). Always `.take()`n by the block that reads it.1940 /// already avoids). Always `.take()`n by the block that reads it.
1883- static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1884 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.1941 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1885 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };1942 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1886- /// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1887- /// an intrabc block's chroma reads can inherit it (see
1888- /// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1889- /// through that one arming site.
1890- static LUMA_TX_TYPE: std::cell::Cell<TxType> = const { std::cell::Cell::new(TxType::DctDct) };
1891- /// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1892- /// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1893- /// satisfies (`blockd.h:373`) -- and takes the *colocated luma
1894- /// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1895- /// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1896- /// intrabc block's two chroma [`read_plane`] calls; the type decides the
1897- /// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1898- /// -- getting it wrong desyncs the chroma coefficients, it is not a
1899- /// reconstruction-only detail.
1900- static INTRABC_CHROMA_TX: std::cell::Cell<Option<TxType>> = const { std::cell::Cell::new(None) };
1901 }1943 }
1944+ // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1945+ // an intrabc block's chroma reads can inherit it (see
1946+ // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1947+ // through that one arming site.
1948+ // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1949+ // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1950+ // satisfies (`blockd.h:373`) -- and takes the *colocated luma
1951+ // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1952+ // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1953+ // intrabc block's two chroma [`read_plane`] calls; the type decides the
1954+ // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1955+ // -- getting it wrong desyncs the chroma coefficients, it is not a
1956+ // reconstruction-only detail.
1902 1957
1903 /// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is1958 /// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
1904 /// `Some` exactly then (set once per frame in `decode_frame`), so the flag1959 /// `Some` exactly then (set once per frame in `decode_frame`), so the flag
1905 /// needs no separate plumbing to reach the rect-strip mode reader.1960 /// needs no separate plumbing to reach the rect-strip mode reader.
1906-fn allow_intrabc_frame() -> bool {1961+fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
1907- INTRABC_MI_GRID.with(|g| g.borrow().is_some())1962+ fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
1908 }1963 }
1909 1964
1910 thread_local! {1965 thread_local! {
@@ -1954,8 +2009,8 @@ pub(crate) fn reset_intrabc_hits() {
1954 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any2009 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1955 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an2010 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1956 /// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).2011 /// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1957-fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {2012+fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
1958- INTRABC_MI_GRID.with(|g| {2013+ fctx.intrabc_mi_grid.with(|g| {
1959 let mut g = g.borrow_mut();2014 let mut g = g.borrow_mut();
1960 let Some((grid, _, _)) = g.as_mut() else {2015 let Some((grid, _, _)) = g.as_mut() else {
1961 return;2016 return;
@@ -2680,10 +2735,6 @@ pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
2680 // already read by [`decode_inter_block`] and (b) the luma mode comes off2735 // already read by [`decode_inter_block`] and (b) the luma mode comes off
2681 // `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,2736 // `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2682 // decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.2737 // decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2683-thread_local! {
2684- static INTRA_IN_INTER_MODE: std::cell::Cell<Option<(usize, bool)>> =
2685- const { std::cell::Cell::new(None) };
2686-}
2687 2738
2688 // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader2739 // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
2689 // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an2740 // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
@@ -3065,7 +3116,7 @@ pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
3065 /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites3116 /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
3066 /// that all mean "an ordinary block, chroma of its own".3117 /// that all mean "an ordinary block, chroma of its own".
3067 #[derive(Clone, Copy)]3118 #[derive(Clone, Copy)]
3068-struct InterStripChroma {3119+pub(crate) struct InterStripChroma {
3069 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which3120 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
3070 /// read and reconstruct NO chroma at all.3121 /// read and reconstruct NO chroma at all.
3071 has_chroma: bool,3122 has_chroma: bool,
@@ -3081,15 +3132,8 @@ struct InterStripChroma {
3081 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,3132 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3082 }3133 }
3083 3134
3084-thread_local! {
3085- static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
3086- const { std::cell::Cell::new(None) };
3087 /// The single-reference MC parameters of the inter block that decoded3135 /// The single-reference MC parameters of the inter block that decoded
3088 /// last -- read by the next 1:4 strip to build its pair's chroma.3136 /// last -- read by the next 1:4 strip to build its pair's chroma.
3089- static INTER_LAST_MC: std::cell::Cell<
3090- Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3091- > = const { std::cell::Cell::new(None) };
3092-}
3093 3137
3094 fn bump_ab16_inter(arm: usize) {3138 fn bump_ab16_inter(arm: usize) {
3095 AB16_INTER_HITS.with(|c| {3139 AB16_INTER_HITS.with(|c| {
@@ -3417,14 +3461,11 @@ pub(crate) fn ref_hits(ref_frame: i8) -> usize {
3417 c.with(|v| v.get())3461 c.with(|v| v.get())
3418 }3462 }
3419 3463
3420-thread_local! {
3421 /// The sequence header's `enable_intra_edge_filter`, set once per3464 /// The sequence header's `enable_intra_edge_filter`, set once per
3422 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s3465 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
3423 /// own read of it, kept off the call stack (see that function's own doc3466 /// own read of it, kept off the call stack (see that function's own doc
3424 /// comment for why) rather than threaded through every `read_plane`/3467 /// comment for why) rather than threaded through every `read_plane`/
3425 /// `decode_block`/`decode_leaf8` call between here and there.3468 /// `decode_block`/`decode_leaf8` call between here and there.
3426- static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3427-}
3428 3469
3429 /// Set [`ENABLE_EDGE_FILTER`] for this thread.3470 /// Set [`ENABLE_EDGE_FILTER`] for this thread.
3430 ///3471 ///
@@ -3436,8 +3477,8 @@ thread_local! {
3436 /// thread, inherits a foreign sequence's bit: decode stops being a pure3477 /// thread, inherits a foreign sequence's bit: decode stops being a pure
3437 /// function of the bitstream. `decode_stream` now calls this once per stream3478 /// function of the bitstream. `decode_stream` now calls this once per stream
3438 /// from the sequence header, which covers every frame including inter ones.3479 /// from the sequence header, which covers every frame including inter ones.
3439-pub(crate) fn set_enable_edge_filter(value: bool) {3480+pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
3440- ENABLE_EDGE_FILTER.with(|f| f.set(value));3481+ fctx.enable_edge_filter.with(|f| f.set(value));
3441 }3482 }
3442 3483
3443 /// Current value of [`ANGLE_DELTA_HITS`].3484 /// Current value of [`ANGLE_DELTA_HITS`].
@@ -4959,7 +5000,7 @@ struct Neighbours {
4959 impl Neighbours {5000 impl Neighbours {
4960 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's5001 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
4961 /// true (unpadded) size in 4x4 mode-info units.5002 /// true (unpadded) size in 4x4 mode-info units.
4962- fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {5003+ fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
4963 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its5004 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
4964 // neighbour state over the whole 64-row extent, past the frame's last5005 // neighbour state over the whole 64-row extent, past the frame's last
4965 // mi row (mi_rows 198, block rows 192..208). libaom's own context5006 // mi row (mi_rows 198, block rows 192..208). libaom's own context
@@ -4967,7 +5008,7 @@ impl Neighbours {
4967 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the5008 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
4968 // side arrays to a superblock multiple and leave those cells unread --5009 // side arrays to a superblock multiple and leave those cells unread --
4969 // every availability check uses the true `mi_rows`/`mi_cols` below.5010 // every availability check uses the true `mi_rows`/`mi_cols` below.
4970- let sb_sub = (sb_mi_cur() as usize) / (SUB / MI);5011+ let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
4971 let (cols, rows) = (5012 let (cols, rows) = (
4972 cols.next_multiple_of(sb_sub),5013 cols.next_multiple_of(sb_sub),
4973 rows.next_multiple_of(sb_sub),5014 rows.next_multiple_of(sb_sub),
@@ -5043,10 +5084,10 @@ impl Neighbours {
5043 /// availability check below. Left context resets every superblock row5084 /// availability check below. Left context resets every superblock row
5044 /// regardless of tile ([`Self::start_row`], already called once per SB5085 /// regardless of tile ([`Self::start_row`], already called once per SB
5045 /// row by every caller) so it needs no tile-specific reset here.5086 /// row by every caller) so it needs no tile-specific reset here.
5046- fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {5087+ fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
5047 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction5088 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
5048 // are tile-relative, same as every other neighbour lookup here.5089 // are tile-relative, same as every other neighbour lookup here.
5049- SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));5090+ fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
5050 self.tile_row0_mi = row0_mi;5091 self.tile_row0_mi = row0_mi;
5051 self.tile_col0_mi = col0_mi;5092 self.tile_col0_mi = col0_mi;
5052 let end = col1_mi.min(self.above.len());5093 let end = col1_mi.min(self.above.len());
@@ -5317,8 +5358,8 @@ impl Neighbours {
5317 /// transform width (in pixels) and `is_inter` flag -- the loop filter's5358 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
5318 /// per-edge lookup (`apply_deblock`), filled at the same call sites and5359 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
5319 /// units as [`Self::fill_skip_grid`].5360 /// units as [`Self::fill_skip_grid`].
5320- fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {5361+ fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
5321- self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);5362+ self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
5322 }5363 }
5323 5364
5324 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions5365 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
@@ -5359,7 +5400,7 @@ impl Neighbours {
5359 h_mi: usize,5400 h_mi: usize,
5360 tx_px: u8,5401 tx_px: u8,
5361 tx_h_px: u8,5402 tx_h_px: u8,
5362- ref_frame: i8,5403+ ref_frame: i8, fctx: &crate::decode::FrameCtx,
5363 ) {5404 ) {
5364 let (mi_r, mi_c) = at_mi;5405 let (mi_r, mi_c) = at_mi;
5365 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is5406 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
@@ -5370,8 +5411,8 @@ impl Neighbours {
5370 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {5411 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
5371 eprintln!("EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");5412 eprintln!("EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
5372 }5413 }
5373- let cur = CURRENT_DELTA_LF.with(|c| c.get());5414+ let cur = fctx.current_delta_lf.with(|c| c.get());
5374- let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {5415+ let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
5375 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)5416 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
5376 } else {5417 } else {
5377 [cur[0].clamp(-63, 63) as i8; 4]5418 [cur[0].clamp(-63, 63) as i8; 4]
@@ -6594,7 +6635,7 @@ fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
6594 /// (one flag bit each, in cache order), then delta-codes the remainder6635 /// (one flag bit each, in cache order), then delta-codes the remainder
6595 /// (first value raw, each following delta `>= 1` off a shrinking bit width),6636 /// (first value raw, each following delta `>= 1` off a shrinking bit width),
6596 /// and merges the two ascending lists back together.6637 /// and merges the two ascending lists back together.
6597-fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {6638+fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
6598 let mut cached = Vec::with_capacity(n);6639 let mut cached = Vec::with_capacity(n);
6599 for &c in cache {6640 for &c in cache {
6600 if cached.len() >= n {6641 if cached.len() >= n {
@@ -6604,7 +6645,7 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u
6604 cached.push(c);6645 cached.push(c);
6605 }6646 }
6606 }6647 }
6607- let bd = u32::from(bit_depth());6648+ let bd = u32::from(bit_depth(fctx));
6608 let max_val = (1i32 << bd) - 1;6649 let max_val = (1i32 << bd) - 1;
6609 let mut colors = [0u16; 8];6650 let mut colors = [0u16; 8];
6610 let n_cached = cached.len();6651 let n_cached = cached.len();
@@ -6641,7 +6682,7 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u
6641 /// side by side). V never uses a cache: a leading bit picks either `n` raw6682 /// side by side). V never uses a cache: a leading bit picks either `n` raw
6642 /// literals, or a first raw value plus `n-1` signed deltas that wrap mod 2566683 /// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
6643 /// rather than clamp.6684 /// rather than clamp.
6644-fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {6685+fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
6645 let mut cached = Vec::with_capacity(n);6686 let mut cached = Vec::with_capacity(n);
6646 for &c in cache {6687 for &c in cache {
6647 if cached.len() >= n {6688 if cached.len() >= n {
@@ -6651,7 +6692,7 @@ fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> (
6651 cached.push(c);6692 cached.push(c);
6652 }6693 }
6653 }6694 }
6654- let bd = u32::from(bit_depth());6695+ let bd = u32::from(bit_depth(fctx));
6655 let max_val = 1i32 << bd;6696 let max_val = 1i32 << bd;
6656 let mut u_colors = [0u16; 8];6697 let mut u_colors = [0u16; 8];
6657 let n_cached = cached.len();6698 let n_cached = cached.len();
@@ -6869,7 +6910,7 @@ fn read_intra_mode_rect(
6869 palette: Option<(usize, &[u16])>,6910 palette: Option<(usize, &[u16])>,
6870 palette_uv_cache: &[u16],6911 palette_uv_cache: &[u16],
6871 mi_r: usize,6912 mi_r: usize,
6872- mi_c: usize,6913+ mi_c: usize, fctx: &crate::decode::FrameCtx,
6873 ) -> Result<(6914 ) -> Result<(
6874 bool,6915 bool,
6875 usize,6916 usize,
@@ -6914,27 +6955,27 @@ fn read_intra_mode_rect(
6914 // lane-intra14 r1: on the INTER block path everything up to and including6955 // lane-intra14 r1: on the INTER block path everything up to and including
6915 // `is_inter` was already read by [`decode_inter_block`], so this reader6956 // `is_inter` was already read by [`decode_inter_block`], so this reader
6916 // starts at the mode syntax with the `skip` that caller read.6957 // starts at the mode syntax with the `skip` that caller read.
6917- let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);6958+ let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
6918 let skip = if let Some((_, skip)) = inter {6959 let skip = if let Some((_, skip)) = inter {
6919 skip6960 skip
6920 } else {6961 } else {
6921 // Same `intra_segment_id` placement as the square reader above.6962 // Same `intra_segment_id` placement as the square reader above.
6922 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);6963 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6923- if seg_id_pre_skip() {6964+ if seg_id_pre_skip(fctx) {
6924- intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);6965+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
6925 }6966 }
6926 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;6967 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6927 istep!("skip", skip as i32);6968 istep!("skip", skip as i32);
6928- if !seg_id_pre_skip() {6969+ if !seg_id_pre_skip(fctx) {
6929- intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);6970+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
6930 }6971 }
6931- maybe_read_cdef_idx(dec, mi_r, mi_c, skip);6972+ maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
6932 istep!("cdef", 0);6973 istep!("cdef", 0);
6933 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never6974 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
6934 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always6975 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
6935 // `false`.6976 // `false`.
6936- maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);6977+ maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
6937- maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);6978+ maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
6938 istep!("dq", 0);6979 istep!("dq", 0);
6939 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after6980 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
6940 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the6981 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
@@ -6946,7 +6987,7 @@ fn read_intra_mode_rect(
6946 // `--tune-content=screen` key frame. Reconstruction of a real intrabc6987 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
6947 // block at this shape is out of scope, so the flag is consumed and6988 // block at this shape is out of scope, so the flag is consumed and
6948 // refused by name when it fires.6989 // refused by name when it fires.
6949- if allow_intrabc_frame() {6990+ if allow_intrabc_frame(fctx) {
6950 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;6991 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6951 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));6992 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
6952 istep!("intrabc", use_intrabc as i32);6993 istep!("intrabc", use_intrabc as i32);
@@ -7036,7 +7077,7 @@ fn read_intra_mode_rect(
7036 ));7077 ));
7037 }7078 }
7038 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);7079 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7039- let colors = read_palette_colors_y(dec, n, cache);7080+ let colors = read_palette_colors_y(dec, n, cache, fctx);
7040 palette_y_pending = Some((n, colors));7081 palette_y_pending = Some((n, colors));
7041 }7082 }
7042 let palette_uv_mode_ctx = usize::from(use_palette_y);7083 let palette_uv_mode_ctx = usize::from(use_palette_y);
@@ -7046,7 +7087,7 @@ fn read_intra_mode_rect(
7046 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 07087 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
7047 {7088 {
7048 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);7089 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
7049- let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);7090+ let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
7050 palette_uv_pending = Some((n, u_colors, v_colors));7091 palette_uv_pending = Some((n, u_colors, v_colors));
7051 }7092 }
7052 }7093 }
@@ -7302,7 +7343,7 @@ fn decode_rect_split(
7302 u: &mut PlaneBuf,7343 u: &mut PlaneBuf,
7303 v: &mut PlaneBuf,7344 v: &mut PlaneBuf,
7304 base_q_idx: u8,7345 base_q_idx: u8,
7305- reduced_tx_set: bool,7346+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
7306 ) -> Result<()> {7347 ) -> Result<()> {
7307 let (mi_r, mi_c) = at_mi;7348 let (mi_r, mi_c) = at_mi;
7308 let (px, py) = (mi_c * MI, mi_r * MI);7349 let (px, py) = (mi_c * MI, mi_r * MI);
@@ -7422,7 +7463,7 @@ fn decode_rect_split(
7422 let zero_tu = vec![0i32; tx_w * tx_h];7463 let zero_tu = vec![0i32; tx_w * tx_h];
7423 // The strip's OWN edge availability, the fallback for a transform unit7464 // The strip's OWN edge availability, the fallback for a transform unit
7424 // whose top-right/bottom-left pixels fall outside the strip.7465 // whose top-right/bottom-left pixels fall outside the strip.
7425- let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);7466+ let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
7426 for tu_row in 0..bh / tx_h {7467 for tu_row in 0..bh / tx_h {
7427 for tu_col in 0..bw / tx_w {7468 for tu_col in 0..bw / tx_w {
7428 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));7469 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
@@ -7462,7 +7503,7 @@ fn decode_rect_split(
7462 buf[base..base + tx_w].iter().copied()7503 buf[base..base + tx_w].iter().copied()
7463 })7504 })
7464 .collect();7505 .collect();
7465- set_palette_pred(tu_buf);7506+ set_palette_pred(tu_buf, fctx);
7466 }7507 }
7467 if m.skip {7508 if m.skip {
7468 y.reconstruct_rect(7509 y.reconstruct_rect(
@@ -7476,7 +7517,7 @@ fn decode_rect_split(
7476 &zero_tu,7517 &zero_tu,
7477 None,7518 None,
7478 m.filter_intra,7519 m.filter_intra,
7479- m.smooth_neighbor,7520+ m.smooth_neighbor, fctx,
7480 );7521 );
7481 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);7522 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
7482 } else if luma_64corner && luma_rect.is_none() {7523 } else if luma_64corner && luma_rect.is_none() {
@@ -7517,10 +7558,10 @@ fn decode_rect_split(
7517 &tu_grid,7558 &tu_grid,
7518 tx_w,7559 tx_w,
7519 tx_h,7560 tx_h,
7520- crate::decode::bit_depth(),7561+ crate::decode::bit_depth(fctx),
7521- block_q_idx(),7562+ block_q_idx(fctx),
7522- plane_q_delta(0).0,7563+ plane_q_delta(0, fctx).0,
7523- plane_q_delta(0).1,7564+ plane_q_delta(0, fctx).1,
7524 tu_tx_type,7565 tu_tx_type,
7525 );7566 );
7526 y.reconstruct_rect(7567 y.reconstruct_rect(
@@ -7534,7 +7575,7 @@ fn decode_rect_split(
7534 &residual,7575 &residual,
7535 None,7576 None,
7536 m.filter_intra,7577 m.filter_intra,
7537- m.smooth_neighbor,7578+ m.smooth_neighbor, fctx,
7538 );7579 );
7539 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);7580 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7540 } else if let Some((rect_set, rect_scan)) = luma_rect {7581 } else if let Some((rect_set, rect_scan)) = luma_rect {
@@ -7573,10 +7614,10 @@ fn decode_rect_split(
7573 &tu_grid,7614 &tu_grid,
7574 tx_w,7615 tx_w,
7575 tx_h,7616 tx_h,
7576- crate::decode::bit_depth(),7617+ crate::decode::bit_depth(fctx),
7577- block_q_idx(),7618+ block_q_idx(fctx),
7578- plane_q_delta(0).0,7619+ plane_q_delta(0, fctx).0,
7579- plane_q_delta(0).1,7620+ plane_q_delta(0, fctx).1,
7580 tu_tx_type,7621 tu_tx_type,
7581 );7622 );
7582 y.reconstruct_rect(7623 y.reconstruct_rect(
@@ -7590,7 +7631,7 @@ fn decode_rect_split(
7590 &residual,7631 &residual,
7591 None,7632 None,
7592 m.filter_intra,7633 m.filter_intra,
7593- m.smooth_neighbor,7634+ m.smooth_neighbor, fctx,
7594 );7635 );
7595 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);7636 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7596 } else {7637 } else {
@@ -7619,7 +7660,7 @@ fn decode_rect_split(
7619 None,7660 None,
7620 m.filter_intra,7661 m.filter_intra,
7621 Some(tu_skip_ctx),7662 Some(tu_skip_ctx),
7622- m.smooth_neighbor,7663+ m.smooth_neighbor, fctx,
7623 )?;7664 )?;
7624 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);7665 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
7625 }7666 }
@@ -7631,18 +7672,18 @@ fn decode_rect_split(
7631 let (u_grid, v_grid) = if m.skip {7672 let (u_grid, v_grid) = if m.skip {
7632 let zero = vec![0i32; chroma_w * chroma_h];7673 let zero = vec![0i32; chroma_w * chroma_h];
7633 if let Some((ub, _)) = &m.palette_uv {7674 if let Some((ub, _)) = &m.palette_uv {
7634- set_palette_pred(ub.clone());7675+ set_palette_pred(ub.clone(), fctx);
7635 }7676 }
7636 u.reconstruct_rect(7677 u.reconstruct_rect(
7637 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,7678 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7638- m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,7679+ m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
7639 );7680 );
7640 if let Some((_, vb)) = &m.palette_uv {7681 if let Some((_, vb)) = &m.palette_uv {
7641- set_palette_pred(vb.clone());7682+ set_palette_pred(vb.clone(), fctx);
7642 }7683 }
7643 v.reconstruct_rect(7684 v.reconstruct_rect(
7644 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,7685 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7645- m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,7686+ m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
7646 );7687 );
7647 (zero.clone(), zero)7688 (zero.clone(), zero)
7648 } else {7689 } else {
@@ -7675,17 +7716,17 @@ fn decode_rect_split(
7675 // (lane-rectsplit r4: lifting the split-transform refusal moved7716 // (lane-rectsplit r4: lifting the split-transform refusal moved
7676 // superblock strips onto this path, so only counting there would7717 // superblock strips onto this path, so only counting there would
7677 // leave the delta_q gate's counter silent for them).7718 // leave the delta_q gate's counter silent for them).
7678- if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {7719+ if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
7679 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));7720 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7680 }7721 }
7681 let residual = dequant_and_inverse_typed_wh(7722 let residual = dequant_and_inverse_typed_wh(
7682 &levels,7723 &levels,
7683 chroma_w,7724 chroma_w,
7684 chroma_h,7725 chroma_h,
7685- crate::decode::bit_depth(),7726+ crate::decode::bit_depth(fctx),
7686- CURRENT_Q_IDX.with(|c| c.get()),7727+ fctx.current_q_idx.with(|c| c.get()),
7687- plane_q_delta(plane_idx).0,7728+ plane_q_delta(plane_idx, fctx).0,
7688- plane_q_delta(plane_idx).1,7729+ plane_q_delta(plane_idx, fctx).1,
7689 tx_type,7730 tx_type,
7690 );7731 );
7691 let cfl = m7732 let cfl = m
@@ -7695,7 +7736,7 @@ fn decode_rect_split(
7695 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };7736 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
7696 if let Some((ub, vb)) = &m.palette_uv {7737 if let Some((ub, vb)) = &m.palette_uv {
7697 let buf = if plane_idx == 1 { ub } else { vb };7738 let buf = if plane_idx == 1 { ub } else { vb };
7698- set_palette_pred(buf.clone());7739+ set_palette_pred(buf.clone(), fctx);
7699 }7740 }
7700 plane.reconstruct_rect(7741 plane.reconstruct_rect(
7701 cpx,7742 cpx,
@@ -7708,7 +7749,7 @@ fn decode_rect_split(
7708 &residual,7749 &residual,
7709 cfl,7750 cfl,
7710 None,7751 None,
7711- m.smooth_neighbor_uv,7752+ m.smooth_neighbor_uv, fctx,
7712 );7753 );
7713 grids.push(levels);7754 grids.push(levels);
7714 }7755 }
@@ -7724,7 +7765,7 @@ fn decode_rect_split(
7724 [&u_grid, &v_grid],7765 [&u_grid, &v_grid],
7725 );7766 );
7726 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);7767 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
7727- neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);7768+ neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
7728 if crate::envflags::env_flag!("EC_AV1_TRACE") {7769 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7729 let (rng, _) = dec.debug_state();7770 let (rng, _) = dec.debug_state();
7730 eprintln!(7771 eprintln!(
@@ -7930,7 +7971,7 @@ fn decode_intra_rect_in_inter(
7930 y: &mut PlaneBuf,7971 y: &mut PlaneBuf,
7931 u: &mut PlaneBuf,7972 u: &mut PlaneBuf,
7932 v: &mut PlaneBuf,7973 v: &mut PlaneBuf,
7933- base_q_idx: u8,7974+ base_q_idx: u8, fctx: &crate::decode::FrameCtx,
7934 ) -> Result<()> {7975 ) -> Result<()> {
7935 // `at` is in MI units (the inter path's own unit since lane-inter4);7976 // `at` is in MI units (the inter path's own unit since lane-inter4);
7936 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands7977 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
@@ -7962,7 +8003,7 @@ fn decode_intra_rect_in_inter(
7962 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry8003 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
7963 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.8004 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
7964 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });8005 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
7965- INTRA_IN_INTER_MODE.with(|c| c.set(Some((0, skip))));8006+ fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
7966 let res = decode_rect4_16_strip(8007 let res = decode_rect4_16_strip(
7967 dec,8008 dec,
7968 cdfs,8009 cdfs,
@@ -7977,13 +8018,13 @@ fn decode_intra_rect_in_inter(
7977 y,8018 y,
7978 u,8019 u,
7979 v,8020 v,
7980- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),8021+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
7981 allow_screen_content_tools,8022 allow_screen_content_tools,
7982 base_q_idx,8023 base_q_idx,
7983- TX_SELECT_INTER.with(std::cell::Cell::get),8024+ fctx.tx_select_inter.with(std::cell::Cell::get),
7984- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),8025+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
7985 );8026 );
7986- INTRA_IN_INTER_MODE.with(|c| c.set(None));8027+ fctx.intra_in_inter_mode.with(|c| c.set(None));
7987 let (mode, uv, (tx_w, tx_h)) = res?;8028 let (mode, uv, (tx_w, tx_h)) = res?;
7988 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip8029 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
7989 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs8030 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
@@ -8074,7 +8115,7 @@ fn decode_intra_rect_in_inter(
8074 // (class `counter-from-refused-stream`).8115 // (class `counter-from-refused-stream`).
8075 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");8116 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
8076 }8117 }
8077- INTRA_IN_INTER_MODE.with(|c| c.set(Some((3, skip))));8118+ fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
8078 let res = decode_block_128rect(8119 let res = decode_block_128rect(
8079 dec,8120 dec,
8080 cdfs,8121 cdfs,
@@ -8086,12 +8127,12 @@ fn decode_intra_rect_in_inter(
8086 u,8127 u,
8087 v,8128 v,
8088 base_q_idx,8129 base_q_idx,
8089- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),8130+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
8090 allow_screen_content_tools,8131 allow_screen_content_tools,
8091- TX_SELECT_INTER.with(std::cell::Cell::get),8132+ fctx.tx_select_inter.with(std::cell::Cell::get),
8092- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),8133+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
8093 );8134 );
8094- INTRA_IN_INTER_MODE.with(|c| c.set(None));8135+ fctx.intra_in_inter_mode.with(|c| c.set(None));
8095 return res;8136 return res;
8096 }8137 }
8097 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {8138 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
@@ -8131,7 +8172,7 @@ fn decode_intra_rect_in_inter(
8131 // `decode_block_rect64`), asserted here so a future shape cannot drift.8172 // `decode_block_rect64`), asserted here so a future shape cannot drift.
8132 if bw.max(bh) == 4 * bw.min(bh) {8173 if bw.max(bh) == 4 * bw.min(bh) {
8133 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });8174 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
8134- INTRA_IN_INTER_MODE.with(|c| c.set(Some((size_group, skip))));8175+ fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
8135 let res = if bw.max(bh) == 64 {8176 let res = if bw.max(bh) == 64 {
8136 decode_block_rect64(8177 decode_block_rect64(
8137 dec,8178 dec,
@@ -8143,11 +8184,11 @@ fn decode_intra_rect_in_inter(
8143 y,8184 y,
8144 u,8185 u,
8145 v,8186 v,
8146- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),8187+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
8147 allow_screen_content_tools,8188 allow_screen_content_tools,
8148 base_q_idx,8189 base_q_idx,
8149- TX_SELECT_INTER.with(std::cell::Cell::get),8190+ fctx.tx_select_inter.with(std::cell::Cell::get),
8150- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),8191+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
8151 )8192 )
8152 } else {8193 } else {
8153 decode_block_rect4(8194 decode_block_rect4(
@@ -8161,14 +8202,14 @@ fn decode_intra_rect_in_inter(
8161 y,8202 y,
8162 u,8203 u,
8163 v,8204 v,
8164- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),8205+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
8165 allow_screen_content_tools,8206 allow_screen_content_tools,
8166 base_q_idx,8207 base_q_idx,
8167- TX_SELECT_INTER.with(std::cell::Cell::get),8208+ fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
8168 )8209 )
8169 .map(|_| ())8210 .map(|_| ())
8170 };8211 };
8171- INTRA_IN_INTER_MODE.with(|c| c.set(None));8212+ fctx.intra_in_inter_mode.with(|c| c.set(None));
8172 res?;8213 res?;
8173 let shape = match (bw, bh) {8214 let shape = match (bw, bh) {
8174 (64, 16) => 0,8215 (64, 16) => 0,
@@ -8271,7 +8312,7 @@ fn decode_intra_rect_in_inter(
8271 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;8312 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
8272 if use_palette_y {8313 if use_palette_y {
8273 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);8314 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8274- palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache)));8315+ palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
8275 }8316 }
8276 // A 2:1 strip of at least 8x8 is always a chroma reference, so8317 // A 2:1 strip of at least 8x8 is always a chroma reference, so
8277 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.8318 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
@@ -8282,7 +8323,7 @@ fn decode_intra_rect_in_inter(
8282 }8323 }
8283 if use_palette_uv {8324 if use_palette_uv {
8284 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);8325 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8285- let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache);8326+ let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
8286 palette_uv_pending = Some((n, u_colors, v_colors));8327 palette_uv_pending = Some((n, u_colors, v_colors));
8287 }8328 }
8288 }8329 }
@@ -8294,7 +8335,7 @@ fn decode_intra_rect_in_inter(
8294 // ([`filter_intra_size_class_rect`]).8335 // ([`filter_intra_size_class_rect`]).
8295 let mut filter_intra = None;8336 let mut filter_intra = None;
8296 if mode == DC_PRED8337 if mode == DC_PRED
8297- && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)8338+ && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
8298 // `av1_filter_intra_allowed` excludes a palette-Y block.8339 // `av1_filter_intra_allowed` excludes a palette-Y block.
8299 && palette_y_pending.is_none()8340 && palette_y_pending.is_none()
8300 && let Some(class) = filter_intra_size_class_rect(bw, bh)8341 && let Some(class) = filter_intra_size_class_rect(bw, bh)
@@ -8338,10 +8379,10 @@ fn decode_intra_rect_in_inter(
8338 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));8379 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
8339 }8380 }
8340 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);8381 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
8341- let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) {8382+ let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
8342 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's8383 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
8343 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].8384 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
8344- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));8385+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
8345 let d = match tx_cat {8386 let d = match tx_cat {
8346 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),8387 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
8347 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),8388 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
@@ -8419,7 +8460,7 @@ fn decode_intra_rect_in_inter(
8419 u,8460 u,
8420 v,8461 v,
8421 base_q_idx,8462 base_q_idx,
8422- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),8463+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
8423 )?;8464 )?;
8424 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of8465 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
8425 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in8466 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
@@ -8487,7 +8528,7 @@ fn decode_block_rect(
8487 allow_screen_content_tools: bool,8528 allow_screen_content_tools: bool,
8488 base_q_idx: u8,8529 base_q_idx: u8,
8489 tx_select: bool,8530 tx_select: bool,
8490- reduced_tx_set: bool,8531+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
8491 ) -> Result<()> {8532 ) -> Result<()> {
8492 let (r, c) = at;8533 let (r, c) = at;
8493 let (px, py) = (c * SUB, r * SUB);8534 let (px, py) = (c * SUB, r * SUB);
@@ -8510,7 +8551,7 @@ fn decode_block_rect(
8510 Some((palette_ctx, &palette_cache)),8551 Some((palette_ctx, &palette_cache)),
8511 &palette_uv_cache,8552 &palette_uv_cache,
8512 r * (SUB / MI),8553 r * (SUB / MI),
8513- c * (SUB / MI),8554+ c * (SUB / MI), fctx,
8514 )?;8555 )?;
8515 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);8556 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8516 if smooth_neighbor {8557 if smooth_neighbor {
@@ -8550,8 +8591,8 @@ fn decode_block_rect(
8550 // written. Measured on the 10-bit 1920x792 128-superblock stream,8591 // written. Measured on the 10-bit 1920x792 128-superblock stream,
8551 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read8592 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
8552 // `tx_size_cat2` row 1 where libaom reads row 2.8593 // `tx_size_cat2` row 1 where libaom reads row 2.
8553- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {8594+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
8554- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)8595+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
8555 } else {8596 } else {
8556 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)8597 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
8557 };8598 };
@@ -8617,7 +8658,7 @@ fn decode_block_rect(
8617 u,8658 u,
8618 v,8659 v,
8619 base_q_idx,8660 base_q_idx,
8620- reduced_tx_set,8661+ reduced_tx_set, fctx,
8621 )?;8662 )?;
8622 // This early return skips this fn's own tail, so the palette8663 // This early return skips this fn's own tail, so the palette
8623 // neighbour state has to be stamped HERE too: without it a split-tx8664 // neighbour state has to be stamped HERE too: without it a split-tx
@@ -8637,7 +8678,7 @@ fn decode_block_rect(
8637 let (tx_w, tx_h) = (bw, bh);8678 let (tx_w, tx_h) = (bw, bh);
8638 let (cpx, cpy) = (px / 2, py / 2);8679 let (cpx, cpy) = (px / 2, py / 2);
8639 let (chroma_w, chroma_h) = (bw / 2, bh / 2);8680 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8640- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);8681+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
8641 if crate::envflags::env_flag!("EC_AV1_TRACE") {8682 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8642 let (rng, _) = dec.debug_state();8683 let (rng, _) = dec.debug_state();
8643 eprintln!(8684 eprintln!(
@@ -8651,7 +8692,7 @@ fn decode_block_rect(
8651 // right before each `reconstruct_rect` call below (lane-palette2 r4).8692 // right before each `reconstruct_rect` call below (lane-palette2 r4).
8652 if let Some(ref pyv) = palette_y {8693 if let Some(ref pyv) = palette_y {
8653 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();8694 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
8654- set_palette_pred(buf);8695+ set_palette_pred(buf, fctx);
8655 }8696 }
8656 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {8697 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8657 (8698 (
@@ -8671,11 +8712,11 @@ fn decode_block_rect(
8671 &vec![0i32; bw * bh],8712 &vec![0i32; bw * bh],
8672 None,8713 None,
8673 filter_intra,8714 filter_intra,
8674- smooth_neighbor,8715+ smooth_neighbor, fctx,
8675 );8716 );
8676 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));8717 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8677 if let Some((ub, _)) = &palette_uv_bufs {8718 if let Some((ub, _)) = &palette_uv_bufs {
8678- set_palette_pred(ub.clone());8719+ set_palette_pred(ub.clone(), fctx);
8679 }8720 }
8680 u.reconstruct_rect(8721 u.reconstruct_rect(
8681 cpx,8722 cpx,
@@ -8688,10 +8729,10 @@ fn decode_block_rect(
8688 &vec![0i32; chroma_w * chroma_h],8729 &vec![0i32; chroma_w * chroma_h],
8689 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),8730 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8690 None,8731 None,
8691- smooth_neighbor_uv,8732+ smooth_neighbor_uv, fctx,
8692 );8733 );
8693 if let Some((_, vb)) = &palette_uv_bufs {8734 if let Some((_, vb)) = &palette_uv_bufs {
8694- set_palette_pred(vb.clone());8735+ set_palette_pred(vb.clone(), fctx);
8695 }8736 }
8696 v.reconstruct_rect(8737 v.reconstruct_rect(
8697 cpx,8738 cpx,
@@ -8704,7 +8745,7 @@ fn decode_block_rect(
8704 &vec![0i32; chroma_w * chroma_h],8745 &vec![0i32; chroma_w * chroma_h],
8705 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),8746 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8706 None,8747 None,
8707- smooth_neighbor_uv,8748+ smooth_neighbor_uv, fctx,
8708 );8749 );
8709 neighbours.record_rect(8750 neighbours.record_rect(
8710 at,8751 at,
@@ -8784,10 +8825,10 @@ fn decode_block_rect(
8784 &luma_levels,8825 &luma_levels,
8785 bw,8826 bw,
8786 bh,8827 bh,
8787- crate::decode::bit_depth(),8828+ crate::decode::bit_depth(fctx),
8788- block_q_idx(),8829+ block_q_idx(fctx),
8789- plane_q_delta(0).0,8830+ plane_q_delta(0, fctx).0,
8790- plane_q_delta(0).1,8831+ plane_q_delta(0, fctx).1,
8791 luma_tx_type,8832 luma_tx_type,
8792 );8833 );
8793 y.reconstruct_rect(8834 y.reconstruct_rect(
@@ -8801,11 +8842,11 @@ fn decode_block_rect(
8801 &luma_residual,8842 &luma_residual,
8802 None,8843 None,
8803 filter_intra,8844 filter_intra,
8804- smooth_neighbor,8845+ smooth_neighbor, fctx,
8805 );8846 );
8806 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));8847 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8807 if let Some((ub, _)) = &palette_uv_bufs {8848 if let Some((ub, _)) = &palette_uv_bufs {
8808- set_palette_pred(ub.clone());8849+ set_palette_pred(ub.clone(), fctx);
8809 }8850 }
8810 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);8851 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8811 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);8852 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
@@ -8828,10 +8869,10 @@ fn decode_block_rect(
8828 &u_levels,8869 &u_levels,
8829 chroma_w,8870 chroma_w,
8830 chroma_h,8871 chroma_h,
8831- crate::decode::bit_depth(),8872+ crate::decode::bit_depth(fctx),
8832- block_q_idx(),8873+ block_q_idx(fctx),
8833- plane_q_delta(1).0,8874+ plane_q_delta(1, fctx).0,
8834- plane_q_delta(1).1,8875+ plane_q_delta(1, fctx).1,
8835 u_tx_type,8876 u_tx_type,
8836 );8877 );
8837 u.reconstruct_rect(8878 u.reconstruct_rect(
@@ -8845,10 +8886,10 @@ fn decode_block_rect(
8845 &u_residual,8886 &u_residual,
8846 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),8887 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8847 None,8888 None,
8848- smooth_neighbor_uv,8889+ smooth_neighbor_uv, fctx,
8849 );8890 );
8850 if let Some((_, vb)) = &palette_uv_bufs {8891 if let Some((_, vb)) = &palette_uv_bufs {
8851- set_palette_pred(vb.clone());8892+ set_palette_pred(vb.clone(), fctx);
8852 }8893 }
8853 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);8894 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8854 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);8895 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
@@ -8871,10 +8912,10 @@ fn decode_block_rect(
8871 &v_levels,8912 &v_levels,
8872 chroma_w,8913 chroma_w,
8873 chroma_h,8914 chroma_h,
8874- crate::decode::bit_depth(),8915+ crate::decode::bit_depth(fctx),
8875- block_q_idx(),8916+ block_q_idx(fctx),
8876- plane_q_delta(2).0,8917+ plane_q_delta(2, fctx).0,
8877- plane_q_delta(2).1,8918+ plane_q_delta(2, fctx).1,
8878 v_tx_type,8919 v_tx_type,
8879 );8920 );
8880 v.reconstruct_rect(8921 v.reconstruct_rect(
@@ -8888,7 +8929,7 @@ fn decode_block_rect(
8888 &v_residual,8929 &v_residual,
8889 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),8930 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8890 None,8931 None,
8891- smooth_neighbor_uv,8932+ smooth_neighbor_uv, fctx,
8892 );8933 );
8893 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);8934 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
8894 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));8935 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
@@ -8900,7 +8941,7 @@ fn decode_block_rect(
8900 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));8941 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8901 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);8942 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8902 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);8943 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
8903- neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);8944+ neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
8904 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));8945 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8905 if crate::envflags::env_flag!("EC_AV1_TRACE") {8946 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8906 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");8947 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
@@ -8943,7 +8984,7 @@ fn decode_leaf_rect(
8943 allow_screen_content_tools: bool,8984 allow_screen_content_tools: bool,
8944 base_q_idx: u8,8985 base_q_idx: u8,
8945 tx_select: bool,8986 tx_select: bool,
8946- reduced_tx_set: bool,8987+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
8947 ) -> Result<usize> {8988 ) -> Result<usize> {
8948 let _ = base_q_idx;8989 let _ = base_q_idx;
8949 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {8990 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
@@ -9007,7 +9048,7 @@ fn decode_leaf_rect(
9007 Some((palette_ctx, &palette_cache)),9048 Some((palette_ctx, &palette_cache)),
9008 &palette_uv_cache,9049 &palette_uv_cache,
9009 leaf_mi.0,9050 leaf_mi.0,
9010- leaf_mi.1,9051+ leaf_mi.1, fctx,
9011 )?;9052 )?;
9012 // lane-kf900 r4: palette prediction on this shape, the same colour-index9053 // lane-kf900 r4: palette prediction on this shape, the same colour-index
9013 // map -> base colours buffer [`decode_block_rect`] hands each9054 // map -> base colours buffer [`decode_block_rect`] hands each
@@ -9047,8 +9088,8 @@ fn decode_leaf_rect(
9047 let depth = if tx_select {9088 let depth = if tx_select {
9048 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read9089 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
9049 // every other rect reader now does -- a no-op on a key frame.9090 // every other rect reader now does -- a no-op on a key frame.
9050- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {9091+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9051- tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh)9092+ tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
9052 } else {9093 } else {
9053 tx_size_context_rect(neighbours, leaf_mi, bw, bh)9094 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
9054 };9095 };
@@ -9112,7 +9153,7 @@ fn decode_leaf_rect(
9112 u,9153 u,
9113 v,9154 v,
9114 base_q_idx,9155 base_q_idx,
9115- reduced_tx_set,9156+ reduced_tx_set, fctx,
9116 )?;9157 )?;
9117 record_strip_palette(9158 record_strip_palette(
9118 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,9159 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
@@ -9120,7 +9161,7 @@ fn decode_leaf_rect(
9120 return Ok(mode);9161 return Ok(mode);
9121 }9162 }
9122 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);9163 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9123- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);9164+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9124 let (cpx, cpy) = (px / 2, py / 2);9165 let (cpx, cpy) = (px / 2, py / 2);
9125 let (chroma_w, chroma_h) = (bw / 2, bh / 2);9166 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9126 let (luma_levels, u_levels, v_levels);9167 let (luma_levels, u_levels, v_levels);
@@ -9129,26 +9170,26 @@ fn decode_leaf_rect(
9129 u_levels = vec![0i32; chroma_w * chroma_h];9170 u_levels = vec![0i32; chroma_w * chroma_h];
9130 v_levels = vec![0i32; chroma_w * chroma_h];9171 v_levels = vec![0i32; chroma_w * chroma_h];
9131 if let Some(b) = &palette_y_buf {9172 if let Some(b) = &palette_y_buf {
9132- set_palette_pred(b.clone());9173+ set_palette_pred(b.clone(), fctx);
9133 }9174 }
9134 y.reconstruct_rect(9175 y.reconstruct_rect(
9135 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,9176 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
9136- smooth_neighbor,9177+ smooth_neighbor, fctx,
9137 );9178 );
9138 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));9179 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9139 if let Some((ub, _)) = &palette_uv_bufs {9180 if let Some((ub, _)) = &palette_uv_bufs {
9140- set_palette_pred(ub.clone());9181+ set_palette_pred(ub.clone(), fctx);
9141 }9182 }
9142 u.reconstruct_rect(9183 u.reconstruct_rect(
9143 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,9184 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
9144- alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,9185+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
9145 );9186 );
9146 if let Some((_, vb)) = &palette_uv_bufs {9187 if let Some((_, vb)) = &palette_uv_bufs {
9147- set_palette_pred(vb.clone());9188+ set_palette_pred(vb.clone(), fctx);
9148 }9189 }
9149 v.reconstruct_rect(9190 v.reconstruct_rect(
9150 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,9191 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
9151- alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,9192+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
9152 );9193 );
9153 } else {9194 } else {
9154 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,9195 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
@@ -9178,15 +9219,15 @@ fn decode_leaf_rect(
9178 }9219 }
9179 luma_levels = l_levels;9220 luma_levels = l_levels;
9180 let luma_residual = dequant_and_inverse_typed_wh(9221 let luma_residual = dequant_and_inverse_typed_wh(
9181- &luma_levels, bw, bh, crate::decode::bit_depth(),9222+ &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
9182- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,9223+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
9183 );9224 );
9184 if let Some(b) = &palette_y_buf {9225 if let Some(b) = &palette_y_buf {
9185- set_palette_pred(b.clone());9226+ set_palette_pred(b.clone(), fctx);
9186 }9227 }
9187 y.reconstruct_rect(9228 y.reconstruct_rect(
9188 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,9229 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
9189- smooth_neighbor,9230+ smooth_neighbor, fctx,
9190 );9231 );
9191 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));9232 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9192 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);9233 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
@@ -9198,15 +9239,15 @@ fn decode_leaf_rect(
9198 )?;9239 )?;
9199 u_levels = u_l;9240 u_levels = u_l;
9200 let u_residual = dequant_and_inverse_typed_wh(9241 let u_residual = dequant_and_inverse_typed_wh(
9201- &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),9242+ &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
9202- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,9243+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
9203 );9244 );
9204 if let Some((ub, _)) = &palette_uv_bufs {9245 if let Some((ub, _)) = &palette_uv_bufs {
9205- set_palette_pred(ub.clone());9246+ set_palette_pred(ub.clone(), fctx);
9206 }9247 }
9207 u.reconstruct_rect(9248 u.reconstruct_rect(
9208 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,9249 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
9209- alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,9250+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
9210 );9251 );
9211 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);9252 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
9212 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);9253 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
@@ -9217,21 +9258,21 @@ fn decode_leaf_rect(
9217 )?;9258 )?;
9218 v_levels = v_l;9259 v_levels = v_l;
9219 let v_residual = dequant_and_inverse_typed_wh(9260 let v_residual = dequant_and_inverse_typed_wh(
9220- &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),9261+ &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
9221- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,9262+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
9222 );9263 );
9223 if let Some((_, vb)) = &palette_uv_bufs {9264 if let Some((_, vb)) = &palette_uv_bufs {
9224- set_palette_pred(vb.clone());9265+ set_palette_pred(vb.clone(), fctx);
9225 }9266 }
9226 v.reconstruct_rect(9267 v.reconstruct_rect(
9227 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,9268 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
9228- alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,9269+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
9229 );9270 );
9230 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));9271 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
9231 }9272 }
9232 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);9273 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
9233 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);9274 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
9234- neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);9275+ neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
9235 // The leaf's own palette state (`0` clears, as this site always did9276 // The leaf's own palette state (`0` clears, as this site always did
9236 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT9277 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
9237 // AXIS only until the pair's closing leaf: the coarse cell holds one9278 // AXIS only until the pair's closing leaf: the coarse cell holds one
@@ -9282,7 +9323,7 @@ fn decode_block_rect4(
9282 enable_filter_intra: bool,9323 enable_filter_intra: bool,
9283 allow_screen_content_tools: bool,9324 allow_screen_content_tools: bool,
9284 base_q_idx: u8,9325 base_q_idx: u8,
9285- tx_select: bool,9326+ tx_select: bool, fctx: &crate::decode::FrameCtx,
9286 ) -> Result<(usize, usize)> {9327 ) -> Result<(usize, usize)> {
9287 let _ = base_q_idx;9328 let _ = base_q_idx;
9288 let (mi_r, mi_c) = strip_mi;9329 let (mi_r, mi_c) = strip_mi;
@@ -9336,7 +9377,7 @@ fn decode_block_rect4(
9336 Some((palette_ctx, &palette_cache)),9377 Some((palette_ctx, &palette_cache)),
9337 &palette_uv_cache,9378 &palette_uv_cache,
9338 mi_r,9379 mi_r,
9339- mi_c,9380+ mi_c, fctx,
9340 )?;9381 )?;
9341 // lane-kf900 r4: palette prediction on this shape, exactly as9382 // lane-kf900 r4: palette prediction on this shape, exactly as
9342 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map9383 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
@@ -9390,8 +9431,8 @@ fn decode_block_rect4(
9390 // written. Measured on the 10-bit 1920x792 128-superblock stream,9431 // written. Measured on the 10-bit 1920x792 128-superblock stream,
9391 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read9432 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
9392 // `tx_size_cat2` row 1 where libaom reads row 2.9433 // `tx_size_cat2` row 1 where libaom reads row 2.
9393- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {9434+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9394- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)9435+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
9395 } else {9436 } else {
9396 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)9437 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
9397 };9438 };
@@ -9412,7 +9453,7 @@ fn decode_block_rect4(
9412 neighbours,9453 neighbours,
9413 (mi_r, mi_c),9454 (mi_r, mi_c),
9414 depth_to_tx_wh(bw, bh, depth),9455 depth_to_tx_wh(bw, bh, depth),
9415- (bw, bh),9456+ (bw, bh), fctx,
9416 );9457 );
9417 if depth != 0 {9458 if depth != 0 {
9418 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's9459 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
@@ -9463,7 +9504,7 @@ fn decode_block_rect4(
9463 u,9504 u,
9464 v,9505 v,
9465 base_q_idx,9506 base_q_idx,
9466- false,9507+ false, fctx,
9467 )?;9508 )?;
9468 record_strip_palette(9509 record_strip_palette(
9469 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,9510 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
@@ -9512,7 +9553,7 @@ fn decode_block_rect4(
9512 let (px, py) = (mi_c * MI, mi_r * MI);9553 let (px, py) = (mi_c * MI, mi_r * MI);
9513 let (cpx, cpy) = (px / 2, py / 2);9554 let (cpx, cpy) = (px / 2, py / 2);
9514 let (chroma_w, chroma_h) = (bw / 2, bh / 2);9555 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9515- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);9556+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9516 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {9557 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
9517 (&SCAN_32X8, &SCAN_16X4)9558 (&SCAN_32X8, &SCAN_16X4)
9518 } else {9559 } else {
@@ -9561,14 +9602,14 @@ fn decode_block_rect4(
9561 &luma_levels,9602 &luma_levels,
9562 bw,9603 bw,
9563 bh,9604 bh,
9564- crate::decode::bit_depth(),9605+ crate::decode::bit_depth(fctx),
9565- block_q_idx(),9606+ block_q_idx(fctx),
9566- plane_q_delta(0).0,9607+ plane_q_delta(0, fctx).0,
9567- plane_q_delta(0).1,9608+ plane_q_delta(0, fctx).1,
9568 luma_tx_type,9609 luma_tx_type,
9569 );9610 );
9570 if let Some(b) = &palette_y_buf {9611 if let Some(b) = &palette_y_buf {
9571- set_palette_pred(b.clone());9612+ set_palette_pred(b.clone(), fctx);
9572 }9613 }
9573 y.reconstruct_rect(9614 y.reconstruct_rect(
9574 px,9615 px,
@@ -9581,7 +9622,7 @@ fn decode_block_rect4(
9581 &luma_residual,9622 &luma_residual,
9582 None,9623 None,
9583 filter_intra,9624 filter_intra,
9584- smooth_neighbor,9625+ smooth_neighbor, fctx,
9585 );9626 );
9586 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));9627 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9587 for (plane, buf, levels, tx_type) in [9628 for (plane, buf, levels, tx_type) in [
@@ -9592,14 +9633,14 @@ fn decode_block_rect4(
9592 levels,9633 levels,
9593 chroma_w,9634 chroma_w,
9594 chroma_h,9635 chroma_h,
9595- crate::decode::bit_depth(),9636+ crate::decode::bit_depth(fctx),
9596- block_q_idx(),9637+ block_q_idx(fctx),
9597- plane_q_delta(plane).0,9638+ plane_q_delta(plane, fctx).0,
9598- plane_q_delta(plane).1,9639+ plane_q_delta(plane, fctx).1,
9599 tx_type,9640 tx_type,
9600 );9641 );
9601 if let Some((ub, vb)) = &palette_uv_bufs {9642 if let Some((ub, vb)) = &palette_uv_bufs {
9602- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });9643+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
9603 }9644 }
9604 buf.reconstruct_rect(9645 buf.reconstruct_rect(
9605 cpx,9646 cpx,
@@ -9614,7 +9655,7 @@ fn decode_block_rect4(
9614 .zip(ac.as_deref())9655 .zip(ac.as_deref())
9615 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),9656 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9616 None,9657 None,
9617- smooth_neighbor_uv,9658+ smooth_neighbor_uv, fctx,
9618 );9659 );
9619 }9660 }
9620 neighbours.record_mi_rect(9661 neighbours.record_mi_rect(
@@ -9624,7 +9665,7 @@ fn decode_block_rect4(
9624 &[luma_levels, u_levels, v_levels],9665 &[luma_levels, u_levels, v_levels],
9625 );9666 );
9626 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);9667 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9627- neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);9668+ neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
9628 record_strip_palette(9669 record_strip_palette(
9629 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,9670 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
9630 pal_uv_colors,9671 pal_uv_colors,
@@ -9644,7 +9685,7 @@ fn decode_block_rect4(
9644 return Ok((mode, uv_predict_mode));9685 return Ok((mode, uv_predict_mode));
9645 };9686 };
9646 if let Some(b) = &palette_y_buf {9687 if let Some(b) = &palette_y_buf {
9647- set_palette_pred(b.clone());9688+ set_palette_pred(b.clone(), fctx);
9648 }9689 }
9649 y.reconstruct_rect(9690 y.reconstruct_rect(
9650 px,9691 px,
@@ -9657,11 +9698,11 @@ fn decode_block_rect4(
9657 &luma_levels,9698 &luma_levels,
9658 None,9699 None,
9659 filter_intra,9700 filter_intra,
9660- smooth_neighbor,9701+ smooth_neighbor, fctx,
9661 );9702 );
9662 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));9703 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9663 if let Some((ub, _)) = &palette_uv_bufs {9704 if let Some((ub, _)) = &palette_uv_bufs {
9664- set_palette_pred(ub.clone());9705+ set_palette_pred(ub.clone(), fctx);
9665 }9706 }
9666 u.reconstruct_rect(9707 u.reconstruct_rect(
9667 cpx,9708 cpx,
@@ -9674,10 +9715,10 @@ fn decode_block_rect4(
9674 &u_levels,9715 &u_levels,
9675 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),9716 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9676 None,9717 None,
9677- smooth_neighbor_uv,9718+ smooth_neighbor_uv, fctx,
9678 );9719 );
9679 if let Some((_, vb)) = &palette_uv_bufs {9720 if let Some((_, vb)) = &palette_uv_bufs {
9680- set_palette_pred(vb.clone());9721+ set_palette_pred(vb.clone(), fctx);
9681 }9722 }
9682 v.reconstruct_rect(9723 v.reconstruct_rect(
9683 cpx,9724 cpx,
@@ -9690,11 +9731,11 @@ fn decode_block_rect4(
9690 &v_levels,9731 &v_levels,
9691 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),9732 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9692 None,9733 None,
9693- smooth_neighbor_uv,9734+ smooth_neighbor_uv, fctx,
9694 );9735 );
9695 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);9736 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
9696 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);9737 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9697- neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);9738+ neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
9698 record_strip_palette(9739 record_strip_palette(
9699 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,9740 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9700 );9741 );
@@ -9752,7 +9793,7 @@ fn decode_rect4_16(
9752 allow_screen_content_tools: bool,9793 allow_screen_content_tools: bool,
9753 base_q_idx: u8,9794 base_q_idx: u8,
9754 tx_select: bool,9795 tx_select: bool,
9755- reduced_tx_set: bool,9796+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9756 ) -> Result<()> {9797 ) -> Result<()> {
9757 let (r, c) = at16;9798 let (r, c) = at16;
9758 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));9799 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
@@ -9785,7 +9826,7 @@ fn decode_rect4_16(
9785 allow_screen_content_tools,9826 allow_screen_content_tools,
9786 base_q_idx,9827 base_q_idx,
9787 tx_select,9828 tx_select,
9788- reduced_tx_set,9829+ reduced_tx_set, fctx,
9789 )?;9830 )?;
9790 if let Some(m) = uv {9831 if let Some(m) = uv {
9791 last_uv_mode = m;9832 last_uv_mode = m;
@@ -9828,7 +9869,7 @@ fn decode_rect4_16_strip(
9828 allow_screen_content_tools: bool,9869 allow_screen_content_tools: bool,
9829 base_q_idx: u8,9870 base_q_idx: u8,
9830 tx_select: bool,9871 tx_select: bool,
9831- reduced_tx_set: bool,9872+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9832 ) -> Result<(usize, Option<usize>, (usize, usize))> {9873 ) -> Result<(usize, Option<usize>, (usize, usize))> {
9833 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));9874 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
9834 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };9875 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
@@ -9880,7 +9921,7 @@ fn decode_rect4_16_strip(
9880 Some((palette_ctx, &palette_cache)),9921 Some((palette_ctx, &palette_cache)),
9881 &palette_uv_cache,9922 &palette_uv_cache,
9882 lmi.0,9923 lmi.0,
9883- lmi.1,9924+ lmi.1, fctx,
9884 )?;9925 )?;
9885 if palette_y.is_some() || palette_uv.is_some() {9926 if palette_y.is_some() || palette_uv.is_some() {
9886 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));9927 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
@@ -9914,8 +9955,8 @@ fn decode_rect4_16_strip(
9914 // the 2:1 intra-in-inter strip already does); the key frame's9955 // the 2:1 intra-in-inter strip already does); the key frame's
9915 // deblock-grid approximation is only right where those bands were9956 // deblock-grid approximation is only right where those bands were
9916 // never written.9957 // never written.
9917- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {9958+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9918- tx_size_context_txfm_rect(neighbours, lmi, bw, bh)9959+ tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
9919 } else {9960 } else {
9920 tx_size_context_rect(neighbours, lmi, bw, bh)9961 tx_size_context_rect(neighbours, lmi, bw, bh)
9921 };9962 };
@@ -9938,7 +9979,7 @@ fn decode_rect4_16_strip(
9938 }9979 }
9939 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);9980 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9940 let (px, py) = (lmi.1 * MI, lmi.0 * MI);9981 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9941- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);9982+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9942 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);9983 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
9943 if depth != 0 {9984 if depth != 0 {
9944 // [`decode_rect_split`]'s per-unit walk, inlined because the9985 // [`decode_rect_split`]'s per-unit walk, inlined because the
@@ -9969,12 +10010,12 @@ fn decode_rect4_16_strip(
9969 b[base..base + tx_w].iter().copied()10010 b[base..base + tx_w].iter().copied()
9970 })10011 })
9971 .collect();10012 .collect();
9972- set_palette_pred(tu_buf);10013+ set_palette_pred(tu_buf, fctx);
9973 }10014 }
9974 if skip {10015 if skip {
9975 y.reconstruct_rect(10016 y.reconstruct_rect(
9976 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,10017 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
9977- None, filter_intra, smooth_neighbor,10018+ None, filter_intra, smooth_neighbor, fctx,
9978 );10019 );
9979 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);10020 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9980 } else if rect_unit {10021 } else if rect_unit {
@@ -10005,15 +10046,15 @@ fn decode_rect4_16_strip(
10005 &tu_grid,10046 &tu_grid,
10006 tx_w,10047 tx_w,
10007 tx_h,10048 tx_h,
10008- crate::decode::bit_depth(),10049+ crate::decode::bit_depth(fctx),
10009- block_q_idx(),10050+ block_q_idx(fctx),
10010- plane_q_delta(0).0,10051+ plane_q_delta(0, fctx).0,
10011- plane_q_delta(0).1,10052+ plane_q_delta(0, fctx).1,
10012 tu_tx_type,10053 tu_tx_type,
10013 );10054 );
10014 y.reconstruct_rect(10055 y.reconstruct_rect(
10015 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,10056 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
10016- None, filter_intra, smooth_neighbor,10057+ None, filter_intra, smooth_neighbor, fctx,
10017 );10058 );
10018 if tu_grid.iter().any(|&l| l != 0) {10059 if tu_grid.iter().any(|&l| l != 0) {
10019 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));10060 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
@@ -10042,7 +10083,7 @@ fn decode_rect4_16_strip(
10042 None,10083 None,
10043 filter_intra,10084 filter_intra,
10044 Some(tu_skip_ctx),10085 Some(tu_skip_ctx),
10045- smooth_neighbor,10086+ smooth_neighbor, fctx,
10046 )?;10087 )?;
10047 if tu_grid.iter().any(|&l| l != 0) {10088 if tu_grid.iter().any(|&l| l != 0) {
10048 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));10089 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
@@ -10055,11 +10096,11 @@ fn decode_rect4_16_strip(
10055 let levels = if skip {10096 let levels = if skip {
10056 let zeros = vec![0i32; bw * bh];10097 let zeros = vec![0i32; bw * bh];
10057 if let Some(b) = &palette_y_buf {10098 if let Some(b) = &palette_y_buf {
10058- set_palette_pred(b.clone());10099+ set_palette_pred(b.clone(), fctx);
10059 }10100 }
10060 y.reconstruct_rect(10101 y.reconstruct_rect(
10061 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,10102 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
10062- smooth_neighbor,10103+ smooth_neighbor, fctx,
10063 );10104 );
10064 zeros10105 zeros
10065 } else {10106 } else {
@@ -10087,18 +10128,18 @@ fn decode_rect4_16_strip(
10087 &levels,10128 &levels,
10088 bw,10129 bw,
10089 bh,10130 bh,
10090- crate::decode::bit_depth(),10131+ crate::decode::bit_depth(fctx),
10091- block_q_idx(),10132+ block_q_idx(fctx),
10092- plane_q_delta(0).0,10133+ plane_q_delta(0, fctx).0,
10093- plane_q_delta(0).1,10134+ plane_q_delta(0, fctx).1,
10094 tx_type,10135 tx_type,
10095 );10136 );
10096 if let Some(b) = &palette_y_buf {10137 if let Some(b) = &palette_y_buf {
10097- set_palette_pred(b.clone());10138+ set_palette_pred(b.clone(), fctx);
10098 }10139 }
10099 y.reconstruct_rect(10140 y.reconstruct_rect(
10100 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,10141 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
10101- smooth_neighbor,10142+ smooth_neighbor, fctx,
10102 );10143 );
10103 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));10144 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
10104 levels10145 levels
@@ -10106,7 +10147,7 @@ fn decode_rect4_16_strip(
10106 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);10147 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
10107 }10148 }
10108 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);10149 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
10109- neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0);10150+ neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
10110 // `update_partition_context` writes `partition_context_lookup[10151 // `update_partition_context` writes `partition_context_lookup[
10111 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on10152 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
10112 // the left (mirrored under VERT_4).10153 // the left (mirrored under VERT_4).
@@ -10135,7 +10176,7 @@ fn decode_rect4_16_strip(
10135 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {10176 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
10136 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));10177 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
10137 }10178 }
10138- let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);10179+ let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
10139 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours10180 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
10140 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s10181 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
10141 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/10182 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
@@ -10166,7 +10207,7 @@ fn decode_rect4_16_strip(
10166 }10207 }
10167 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {10208 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
10168 if let Some((ub, vb)) = &palette_uv_bufs {10209 if let Some((ub, vb)) = &palette_uv_bufs {
10169- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });10210+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
10170 }10211 }
10171 buf.reconstruct_rect(10212 buf.reconstruct_rect(
10172 cpx,10213 cpx,
@@ -10181,7 +10222,7 @@ fn decode_rect4_16_strip(
10181 .zip(ac.as_deref())10222 .zip(ac.as_deref())
10182 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),10223 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10183 None,10224 None,
10184- smooth_neighbor_uv,10225+ smooth_neighbor_uv, fctx,
10185 );10226 );
10186 }10227 }
10187 (zeros.clone(), zeros)10228 (zeros.clone(), zeros)
@@ -10217,14 +10258,14 @@ fn decode_rect4_16_strip(
10217 levels,10258 levels,
10218 cw,10259 cw,
10219 ch,10260 ch,
10220- crate::decode::bit_depth(),10261+ crate::decode::bit_depth(fctx),
10221- block_q_idx(),10262+ block_q_idx(fctx),
10222- plane_q_delta(plane).0,10263+ plane_q_delta(plane, fctx).0,
10223- plane_q_delta(plane).1,10264+ plane_q_delta(plane, fctx).1,
10224 tx_type,10265 tx_type,
10225 );10266 );
10226 if let Some((ub, vb)) = &palette_uv_bufs {10267 if let Some((ub, vb)) = &palette_uv_bufs {
10227- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });10268+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
10228 }10269 }
10229 buf.reconstruct_rect(10270 buf.reconstruct_rect(
10230 cpx,10271 cpx,
@@ -10239,7 +10280,7 @@ fn decode_rect4_16_strip(
10239 .zip(ac.as_deref())10280 .zip(ac.as_deref())
10240 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),10281 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10241 None,10282 None,
10242- smooth_neighbor_uv,10283+ smooth_neighbor_uv, fctx,
10243 );10284 );
10244 }10285 }
10245 (u_levels, v_levels)10286 (u_levels, v_levels)
@@ -10330,7 +10371,7 @@ fn decode_block_rect64(
10330 allow_screen_content_tools: bool,10371 allow_screen_content_tools: bool,
10331 base_q_idx: u8,10372 base_q_idx: u8,
10332 tx_select: bool,10373 tx_select: bool,
10333- reduced_tx_set: bool,10374+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10334 ) -> Result<()> {10375 ) -> Result<()> {
10335 let (r, c) = at;10376 let (r, c) = at;
10336 let (px, py) = (c * SUB, r * SUB);10377 let (px, py) = (c * SUB, r * SUB);
@@ -10360,7 +10401,7 @@ fn decode_block_rect64(
10360 Some((palette_ctx, &palette_cache)),10401 Some((palette_ctx, &palette_cache)),
10361 &palette_uv_cache,10402 &palette_uv_cache,
10362 r * (SUB / MI),10403 r * (SUB / MI),
10363- c * (SUB / MI),10404+ c * (SUB / MI), fctx,
10364 )?;10405 )?;
10365 if (palette_y.is_some() || palette_uv.is_some()) && !skip {10406 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
10366 // The luma coefficient path here is the corner-cropped 32x32 real10407 // The luma coefficient path here is the corner-cropped 32x32 real
@@ -10412,8 +10453,8 @@ fn decode_block_rect64(
10412 // written. Measured on the 10-bit 1920x792 128-superblock stream,10453 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10413 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read10454 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10414 // `tx_size_cat2` row 1 where libaom reads row 2.10455 // `tx_size_cat2` row 1 where libaom reads row 2.
10415- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {10456+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10416- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)10457+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10417 } else {10458 } else {
10418 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)10459 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10419 };10460 };
@@ -10441,7 +10482,7 @@ fn decode_block_rect64(
10441 neighbours,10482 neighbours,
10442 (mi_r, mi_c),10483 (mi_r, mi_c),
10443 depth_to_tx_wh(bw, bh, depth),10484 depth_to_tx_wh(bw, bh, depth),
10444- (bw, bh),10485+ (bw, bh), fctx,
10445 );10486 );
crates/ec-av1/src/encode.rsmodified+229 -147
@@ -14,6 +14,7 @@
14 //! as the decoder will. That makes the reconstruction a claim about what a14 //! as the decoder will. That makes the reconstruction a claim about what a
15 //! decoder produces, and it is gated as one — sample for sample against ffmpeg.15 //! decoder produces, and it is gated as one — sample for sample against ffmpeg.
16 16
17+use crate::decode::WithRef;
17 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};18 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
18 use ec_av1_syntax::{19 use ec_av1_syntax::{
19 ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,20 ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
@@ -54,17 +55,14 @@ pub(crate) const SUPERBLOCK: usize = 64;
54 // superblock changes every answer inside it (the tables themselves are55 // superblock changes every answer inside it (the tables themselves are
55 // already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]56 // already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
56 // stays the encoder's own fixed 64.57 // stays the encoder's own fixed 64.
57-thread_local! {
58- static REACH_SB_PX: std::cell::Cell<usize> = const { std::cell::Cell::new(SUPERBLOCK) };
59-}
60 58
61 /// Sets the superblock size [`Reach`] answers against (64 or 128).59 /// Sets the superblock size [`Reach`] answers against (64 or 128).
62-pub(crate) fn set_reach_superblock_px(px: usize) {60+pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
63- REACH_SB_PX.with(|c| c.set(px));61+ fctx.reach_sb_px.with(|c| c.set(px));
64 }62 }
65 63
66-fn reach_sb_px() -> usize {64+fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
67- REACH_SB_PX.with(|c| c.get())65+ fctx.reach_sb_px.with(|c| c.get())
68 }66 }
69 67
70 /// How heavily the mode search weighs rate against squared error, in units of68 /// How heavily the mode search weighs rate against squared error, in units of
@@ -241,7 +239,7 @@ fn intra_predict_u8(
241 bh: usize,239 bh: usize,
242 enable_edge_filter: bool,240 enable_edge_filter: bool,
243 smooth_neighbor: bool,241 smooth_neighbor: bool,
244- dst: &mut [u8],242+ dst: &mut [u8], fctx: &crate::decode::FrameCtx,
245 ) {243 ) {
246 let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());244 let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());
247 let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());245 let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());
@@ -256,7 +254,7 @@ fn intra_predict_u8(
256 bh,254 bh,
257 enable_edge_filter,255 enable_edge_filter,
258 smooth_neighbor,256 smooth_neighbor,
259- &mut dst16,257+ &mut dst16, fctx,
260 );258 );
261 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {259 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
262 *d = s as u8;260 *d = s as u8;
@@ -658,7 +656,7 @@ impl Plane<'_> {
658 /// Codes one block under one mode without committing it: hands back the656 /// Codes one block under one mode without committing it: hands back the
659 /// levels, the block the decoder would reconstruct, the squared error657 /// levels, the block the decoder would reconstruct, the squared error
660 /// against the source and an estimate of what the levels cost in bits.658 /// against the source and an estimate of what the levels cost in bits.
661- fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {659+ fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
662 let At {660 let At {
663 x, y, side, reach, ..661 x, y, side, reach, ..
664 } = at;662 } = at;
@@ -674,7 +672,7 @@ impl Plane<'_> {
674 side,672 side,
675 false,673 false,
676 false,674 false,
677- &mut prediction,675+ &mut prediction, fctx,
678 );676 );
679 677
680 let mut residual = vec![0i32; side * side];678 let mut residual = vec![0i32; side * side];
@@ -832,9 +830,9 @@ impl Plane<'_> {
832 at: At,830 at: At,
833 mode: u8,831 mode: u8,
834 base_q_idx: u8,832 base_q_idx: u8,
835- deadzone: f64,833+ deadzone: f64, fctx: &crate::decode::FrameCtx,
836 ) -> (Vec<Coeff>, f64, f64) {834 ) -> (Vec<Coeff>, f64, f64) {
837- let trial = self.trial(at, mode, base_q_idx, deadzone);835+ let trial = self.trial(at, mode, base_q_idx, deadzone, fctx);
838 self.commit(at.x, at.y, at.side, &trial);836 self.commit(at.x, at.y, at.side, &trial);
839 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)837 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
840 }838 }
@@ -874,7 +872,7 @@ impl Plane<'_> {
874 at: At,872 at: At,
875 modes: &[u8],873 modes: &[u8],
876 mode_bits: &[f64; 13],874 mode_bits: &[f64; 13],
877- lambda: f64,875+ lambda: f64, fctx: &crate::decode::FrameCtx,
878 ) -> Vec<(f64, u8)> {876 ) -> Vec<(f64, u8)> {
879 let At {877 let At {
880 x, y, side, reach, ..878 x, y, side, reach, ..
@@ -894,7 +892,7 @@ impl Plane<'_> {
894 side,892 side,
895 false,893 false,
896 false,894 false,
897- &mut prediction,895+ &mut prediction, fctx,
898 );896 );
899 let sad: f64 = (0..side * side)897 let sad: f64 = (0..side * side)
900 .map(|i| {898 .map(|i| {
@@ -925,7 +923,7 @@ impl Plane<'_> {
925 &mut self,923 &mut self,
926 at: At,924 at: At,
927 search: &Search,925 search: &Search,
928- mode_bits: &[f64; 13],926+ mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
929 ) -> (Vec<Coeff>, u8, f64) {927 ) -> (Vec<Coeff>, u8, f64) {
930 let At {928 let At {
931 x, y, side, reach, ..929 x, y, side, reach, ..
@@ -946,7 +944,7 @@ impl Plane<'_> {
946 side,944 side,
947 false,945 false,
948 false,946 false,
949- &mut prediction,947+ &mut prediction, fctx,
950 );948 );
951 let sad: f64 = (0..side * side)949 let sad: f64 = (0..side * side)
952 .map(|i| {950 .map(|i| {
@@ -1298,10 +1296,10 @@ impl Reach {
1298 1296
1299 /// What a block of `side` samples at `(x, y)` may read past its own edges,1297 /// What a block of `side` samples at `(x, y)` may read past its own edges,
1300 /// in a frame of `width` by `height`.1298 /// in a frame of `width` by `height`.
1301- pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {1299+ pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
1302 Self {1300 Self {
1303- above_right: y > 0 && x + side < width && Self::top_right(side, x, y),1301+ above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
1304- below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),1302+ below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
1305 }1303 }
1306 }1304 }
1307 1305
@@ -1316,11 +1314,11 @@ impl Reach {
1316 x: usize,1314 x: usize,
1317 y: usize,1315 y: usize,
1318 width: usize,1316 width: usize,
1319- height: usize,1317+ height: usize, fctx: &crate::decode::FrameCtx,
1320 ) -> Self {1318 ) -> Self {
1321 Self {1319 Self {
1322- above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y),1320+ above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
1323- below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y),1321+ below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
1324 }1322 }
1325 }1323 }
1326 1324
@@ -1338,8 +1336,8 @@ impl Reach {
1338 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,1336 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
1339 /// the transform covering the whole block, luma): everything before the1337 /// the transform covering the whole block, luma): everything before the
1340 /// table lookup is that function's own early-exit ladder.1338 /// table lookup is that function's own early-exit ladder.
1341- fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {1339+ fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1342- let sb_mi: usize = reach_sb_px() / 4;1340+ let sb_mi: usize = reach_sb_px(fctx) / 4;
1343 let (mi_row, mi_col) = (y / 4, x / 4);1341 let (mi_row, mi_col) = (y / 4, x / 4);
1344 let bw_log2 = (bw / 4).trailing_zeros() as usize;1342 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1345 let bh_log2 = (bh / 4).trailing_zeros() as usize;1343 let bh_log2 = (bh / 4).trailing_zeros() as usize;
@@ -1371,8 +1369,8 @@ impl Reach {
1371 }1369 }
1372 1370
1373 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].1371 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
1374- fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {1372+ fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1375- let sb_mi: usize = reach_sb_px() / 4;1373+ let sb_mi: usize = reach_sb_px(fctx) / 4;
1376 let (mi_row, mi_col) = (y / 4, x / 4);1374 let (mi_row, mi_col) = (y / 4, x / 4);
1377 let bw_log2 = (bw / 4).trailing_zeros() as usize;1375 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1378 let bh_log2 = (bh / 4).trailing_zeros() as usize;1376 let bh_log2 = (bh / 4).trailing_zeros() as usize;
@@ -1421,8 +1419,8 @@ impl Reach {
1421 /// row of a superblock reads into the superblock above, which is decoded;1419 /// row of a superblock reads into the superblock above, which is decoded;
1422 /// the rightmost column would read into the superblock to the right, which1420 /// the rightmost column would read into the superblock to the right, which
1423 /// is not; and everything between is the table's to answer.1421 /// is not; and everything between is the table's to answer.
1424- fn top_right(side: usize, x: usize, y: usize) -> bool {1422+ fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1425- let (row, col, per_side) = Self::position(side, x, y);1423+ let (row, col, per_side) = Self::position(side, x, y, fctx);
1426 if row == 0 {1424 if row == 0 {
1427 return true;1425 return true;
1428 }1426 }
@@ -1456,10 +1454,10 @@ impl Reach {
1456 /// reads into the superblock to its left, which is decoded only as far1454 /// reads into the superblock to its left, which is decoded only as far
1457 /// down as its own bottom; the bottom row would read into the superblock1455 /// down as its own bottom; the bottom row would read into the superblock
1458 /// below, which is not decoded at all; and the table answers the rest.1456 /// below, which is not decoded at all; and the table answers the rest.
1459- fn bottom_left(side: usize, x: usize, y: usize) -> bool {1457+ fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1460- let (row, col, per_side) = Self::position(side, x, y);1458+ let (row, col, per_side) = Self::position(side, x, y, fctx);
1461 if col == 0 {1459 if col == 0 {
1462- return row * side + side < reach_sb_px();1460+ return row * side + side < reach_sb_px(fctx);
1463 }1461 }
1464 if row + 1 == per_side {1462 if row + 1 == per_side {
1465 return false;1463 return false;
@@ -1489,8 +1487,8 @@ impl Reach {
1489 1487
1490 /// Where a block sits inside its superblock, in blocks of its own size,1488 /// Where a block sits inside its superblock, in blocks of its own size,
1491 /// and how many of them a superblock is across.1489 /// and how many of them a superblock is across.
1492- fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {1490+ fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
1493- let sb = reach_sb_px();1491+ let sb = reach_sb_px(fctx);
1494 ((y % sb) / side, (x % sb) / side, sb / side)1492 ((y % sb) / side, (x % sb) / side, sb / side)
1495 }1493 }
1496 1494
@@ -1550,7 +1548,7 @@ fn code_square(
1550 (x, y): (usize, usize),1548 (x, y): (usize, usize),
1551 side: usize,1549 side: usize,
1552 search: &Search,1550 search: &Search,
1553- mode_bits: &[f64; 13],1551+ mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
1554 ) -> (BlockCoeffs, f64) {1552 ) -> (BlockCoeffs, f64) {
1555 let (luma_set, chroma_set) = if side == BLOCK {1553 let (luma_set, chroma_set) = if side == BLOCK {
1556 (TxbSet::Luma32, TxbSet::Chroma16)1554 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -1571,11 +1569,11 @@ fn code_square(
1571 x,1569 x,
1572 y,1570 y,
1573 side,1571 side,
1574- reach: Reach::of(side, x, y, luma.true_width, luma.true_height),1572+ reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
1575 set: luma_set,1573 set: luma_set,
1576 },1574 },
1577 search,1575 search,
1578- mode_bits,1576+ mode_bits, fctx,
1579 );1577 );
1580 // Chroma is predicted DC because that is the mode the tile writer codes1578 // Chroma is predicted DC because that is the mode the tile writer codes
1581 // for it; what it costs still counts towards the partition decision.1579 // for it; what it costs still counts towards the partition decision.
@@ -1591,7 +1589,7 @@ fn code_square(
1591 },1589 },
1592 DC_PRED,1590 DC_PRED,
1593 search.base_q_idx,1591 search.base_q_idx,
1594- search.deadzone,1592+ search.deadzone, fctx,
1595 );1593 );
1596 *coeffs = levels;1594 *coeffs = levels;
1597 cost += sse + search.lambda * bits;1595 cost += sse + search.lambda * bits;
@@ -1629,9 +1627,9 @@ fn code_square_inter(
1629 search: &Search,1627 search: &Search,
1630 mode_bits: &[f64; 13],1628 mode_bits: &[f64; 13],
1631 reference: &Picture,1629 reference: &Picture,
1632- stack: &MvStack,1630+ stack: &MvStack, fctx: &crate::decode::FrameCtx,
1633 ) -> BlockCoeffs {1631 ) -> BlockCoeffs {
1634- let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits);1632+ let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits, fctx);
1635 let luma_set = if side == 8 {1633 let luma_set = if side == 8 {
1636 TxbSet::Luma8Inter1634 TxbSet::Luma8Inter
1637 } else {1635 } else {
@@ -1685,7 +1683,7 @@ fn code_square_inter(
1685 false,1683 false,
1686 search.base_q_idx,1684 search.base_q_idx,
1687 search.deadzone,1685 search.deadzone,
1688- luma_set,1686+ luma_set, fctx,
1689 );1687 );
1690 let u = mc_trial(1688 let u = mc_trial(
1691 &chroma[0],1689 &chroma[0],
@@ -1701,7 +1699,7 @@ fn code_square_inter(
1701 false,1699 false,
1702 search.base_q_idx,1700 search.base_q_idx,
1703 search.deadzone,1701 search.deadzone,
1704- chroma_set,1702+ chroma_set, fctx,
1705 );1703 );
1706 let v = mc_trial(1704 let v = mc_trial(
1707 &chroma[1],1705 &chroma[1],
@@ -1717,7 +1715,7 @@ fn code_square_inter(
1717 false,1715 false,
1718 search.base_q_idx,1716 search.base_q_idx,
1719 search.deadzone,1717 search.deadzone,
1720- chroma_set,1718+ chroma_set, fctx,
1721 );1719 );
1722 let skip = luma_trial.levels.iter().all(|&l| l == 0)1720 let skip = luma_trial.levels.iter().all(|&l| l == 0)
1723 && u.levels.iter().all(|&l| l == 0)1721 && u.levels.iter().all(|&l| l == 0)
@@ -1997,8 +1995,52 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
1997 /// # Errors1995 /// # Errors
1998 /// Returns an error when the picture's width or height is zero or odd, or1996 /// Returns an error when the picture's width or height is zero or odd, or
1999 /// when its planes are not 4:2:0 of that size.1997 /// when its planes are not 4:2:0 of that size.
1998+/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
1999+/// stream. The per-frame decode state this needs lives for exactly this call.
2000+///
2001+/// # Errors
2002+/// Returns an error under the same conditions
2003+/// [`encode_key_frame_with_modes`] does.
2000 pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {2004 pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
2001- encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES)2005+ encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
2006+}
2007+
2008+/// [`encode_key_frame`] with the per-block intra modes given rather than
2009+/// searched.
2010+///
2011+/// # Errors
2012+/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
2013+/// is empty, or when a block's coefficients do not fit the coded frame.
2014+pub fn encode_key_frame_with_modes(
2015+ picture: &Picture,
2016+ base_q_idx: u8,
2017+ deadzone: f64,
2018+ modes: &[u8],
2019+) -> Result<Encoded> {
2020+ encode_key_frame_with_modes_with_ctx(
2021+ picture,
2022+ base_q_idx,
2023+ deadzone,
2024+ modes,
2025+ &crate::decode::FrameCtx::new(),
2026+ )
2027+}
2028+
2029+/// Codes `pictures` as one key frame followed by inter frames.
2030+///
2031+/// # Errors
2032+/// Returns an error under the same conditions [`encode_key_frame`] and the
2033+/// inter frame path do.
2034+pub fn encode_sequence(
2035+ pictures: &[Picture],
2036+ base_q_idx: u8,
2037+ deadzone: f64,
2038+) -> Result<EncodedSequence> {
2039+ encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
2040+}
2041+
2042+pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
2043+ encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
2002 }2044 }
2003 2045
2004 /// Encodes one picture as a key frame, choosing each block's luma mode from2046 /// Encodes one picture as a key frame, choosing each block's luma mode from
@@ -2012,11 +2054,11 @@ pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Res
2012 /// # Errors2054 /// # Errors
2013 /// The same as [`encode_key_frame`], and additionally when `modes` is empty or2055 /// The same as [`encode_key_frame`], and additionally when `modes` is empty or
2014 /// names a mode [`crate::intra::predict`] does not predict.2056 /// names a mode [`crate::intra::predict`] does not predict.
2015-pub fn encode_key_frame_with_modes(2057+pub(crate) fn encode_key_frame_with_modes_with_ctx(
2016 picture: &Picture,2058 picture: &Picture,
2017 base_q_idx: u8,2059 base_q_idx: u8,
2018 deadzone: f64,2060 deadzone: f64,
2019- modes: &[u8],2061+ modes: &[u8], fctx: &crate::decode::FrameCtx,
2020 ) -> Result<Encoded> {2062 ) -> Result<Encoded> {
2021 picture.check_even()?;2063 picture.check_even()?;
2022 let padded = picture.padded_to(BLOCK);2064 let padded = picture.padded_to(BLOCK);
@@ -2027,7 +2069,7 @@ pub fn encode_key_frame_with_modes(
2027 modes,2069 modes,
2028 split_blocks(),2070 split_blocks(),
2029 (picture.width, picture.height),2071 (picture.width, picture.height),
2030- unspecified_color_config(),2072+ unspecified_color_config(), fctx,
2031 )?;2073 )?;
2032 Ok(crop_encoded(&encoded, picture.width, picture.height))2074 Ok(crop_encoded(&encoded, picture.width, picture.height))
2033 }2075 }
@@ -2043,7 +2085,7 @@ pub(crate) fn encode_key_frame_inner(
2043 modes: &[u8],2085 modes: &[u8],
2044 split_blocks: bool,2086 split_blocks: bool,
2045 render: (usize, usize),2087 render: (usize, usize),
2046- color_config: ColorConfig,2088+ color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
2047 ) -> Result<Encoded> {2089 ) -> Result<Encoded> {
2048 picture.check()?;2090 picture.check()?;
2049 if modes.is_empty() {2091 if modes.is_empty() {
@@ -2220,7 +2262,7 @@ pub(crate) fn encode_key_frame_inner(
2220 (x, y),2262 (x, y),
2221 BLOCK,2263 BLOCK,
2222 &search,2264 &search,
2223- &mode_bits(above_mode[c0], left_mode[r0]),2265+ &mode_bits(above_mode[c0], left_mode[r0]), fctx,
2224 );2266 );
2225 cost_whole += search.lambda * partition_bits(BLOCK, false);2267 cost_whole += search.lambda * partition_bits(BLOCK, false);
2226 let after_whole = snapshot(&luma, &chroma, (x, y));2268 let after_whole = snapshot(&luma, &chroma, (x, y));
@@ -2253,7 +2295,7 @@ pub(crate) fn encode_key_frame_inner(
2253 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),2295 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
2254 SUB,2296 SUB,
2255 &search,2297 &search,
2256- &mode_bits(above_mode[sc], left_mode[sr]),2298+ &mode_bits(above_mode[sc], left_mode[sr]), fctx,
2257 );2299 );
2258 cost_split += cost;2300 cost_split += cost;
2259 split_modes.push(block.mode);2301 split_modes.push(block.mode);
@@ -2284,7 +2326,7 @@ pub(crate) fn encode_key_frame_inner(
2284 (leaf_x, leaf_y),2326 (leaf_x, leaf_y),
2285 8,2327 8,
2286 &search,2328 &search,
2287- &leaf_mode_bits,2329+ &leaf_mode_bits, fctx,
2288 );2330 );
2289 cost_split += cost;2331 cost_split += cost;
2290 split_modes.push(leaf.mode);2332 split_modes.push(leaf.mode);
@@ -2500,7 +2542,7 @@ fn mc_trial(
2500 skip: bool,2542 skip: bool,
2501 base_q_idx: u8,2543 base_q_idx: u8,
2502 deadzone: f64,2544 deadzone: f64,
2503- set: TxbSet,2545+ set: TxbSet, fctx: &crate::decode::FrameCtx,
2504 ) -> Trial {2546 ) -> Trial {
2505 let x_q4 = mv_to_q4(x, mv.1, luma);2547 let x_q4 = mv_to_q4(x, mv.1, luma);
2506 let y_q4 = mv_to_q4(y, mv.0, luma);2548 let y_q4 = mv_to_q4(y, mv.0, luma);
@@ -2517,7 +2559,7 @@ fn mc_trial(
2517 y_q4,2559 y_q4,
2518 side,2560 side,
2519 side,2561 side,
2520- &mut prediction16,2562+ &mut prediction16, fctx,
2521 );2563 );
2522 let prediction: Vec<u8> = prediction16.iter().map(|&v| v as u8).collect();2564 let prediction: Vec<u8> = prediction16.iter().map(|&v| v as u8).collect();
2523 plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set)2565 plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set)
@@ -2549,10 +2591,10 @@ fn search_inter_block(
2549 search: &Search,2591 search: &Search,
2550 mode_bits: &[f64; 13],2592 mode_bits: &[f64; 13],
2551 reference: &Picture,2593 reference: &Picture,
2552- stack: &MvStack,2594+ stack: &MvStack, fctx: &crate::decode::FrameCtx,
2553 ) -> BlockCoeffs {2595 ) -> BlockCoeffs {
2554 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);2596 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
2555- let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height);2597+ let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
2556 2598
2557 // skip / intra_inter symbol costs at a fixed context -- see this2599 // skip / intra_inter symbol costs at a fixed context -- see this
2558 // function's doc comment.2600 // function's doc comment.
@@ -2596,7 +2638,7 @@ fn search_inter_block(
2596 },2638 },
2597 DC_PRED,2639 DC_PRED,
2598 search.base_q_idx,2640 search.base_q_idx,
2599- search.deadzone,2641+ search.deadzone, fctx,
2600 );2642 );
2601 let v_trial = chroma[1].trial(2643 let v_trial = chroma[1].trial(
2602 At {2644 At {
@@ -2608,7 +2650,7 @@ fn search_inter_block(
2608 },2650 },
2609 DC_PRED,2651 DC_PRED,
2610 search.base_q_idx,2652 search.base_q_idx,
2611- search.deadzone,2653+ search.deadzone, fctx,
2612 );2654 );
2613 2655
2614 let intra_modes: Vec<u8> = match search.top_k {2656 let intra_modes: Vec<u8> = match search.top_k {
@@ -2623,7 +2665,7 @@ fn search_inter_block(
2623 },2665 },
2624 search.modes,2666 search.modes,
2625 mode_bits,2667 mode_bits,
2626- search.lambda,2668+ search.lambda, fctx,
2627 );2669 );
2628 prune_by_sad(search.modes, scored, k)2670 prune_by_sad(search.modes, scored, k)
2629 }2671 }
@@ -2640,7 +2682,7 @@ fn search_inter_block(
2640 },2682 },
2641 mode,2683 mode,
2642 search.base_q_idx,2684 search.base_q_idx,
2643- search.deadzone,2685+ search.deadzone, fctx,
2644 );2686 );
2645 let u = u_trial.clone();2687 let u = u_trial.clone();
2646 let v = v_trial.clone();2688 let v = v_trial.clone();
@@ -2716,7 +2758,7 @@ fn search_inter_block(
2716 false,2758 false,
2717 search.base_q_idx,2759 search.base_q_idx,
2718 search.deadzone,2760 search.deadzone,
2719- luma_set,2761+ luma_set, fctx,
2720 );2762 );
2721 let u = mc_trial(2763 let u = mc_trial(
2722 &chroma[0],2764 &chroma[0],
@@ -2732,7 +2774,7 @@ fn search_inter_block(
2732 false,2774 false,
2733 search.base_q_idx,2775 search.base_q_idx,
2734 search.deadzone,2776 search.deadzone,
2735- chroma_set,2777+ chroma_set, fctx,
2736 );2778 );
2737 let v = mc_trial(2779 let v = mc_trial(
2738 &chroma[1],2780 &chroma[1],
@@ -2748,7 +2790,7 @@ fn search_inter_block(
2748 false,2790 false,
2749 search.base_q_idx,2791 search.base_q_idx,
2750 search.deadzone,2792 search.deadzone,
2751- chroma_set,2793+ chroma_set, fctx,
2752 );2794 );
2753 let skip = luma_trial.levels.iter().all(|&l| l == 0)2795 let skip = luma_trial.levels.iter().all(|&l| l == 0)
2754 && u.levels.iter().all(|&l| l == 0)2796 && u.levels.iter().all(|&l| l == 0)
@@ -2797,7 +2839,7 @@ fn search_inter_block(
2797 BLOCK,2839 BLOCK,
2798 BLOCK,2840 BLOCK,
2799 stack.pred_mv,2841 stack.pred_mv,
2800- search.lambda,2842+ search.lambda, fctx,
2801 );2843 );
2802 #[cfg(test)]2844 #[cfg(test)]
2803 stage_add(0, t.elapsed());2845 stage_add(0, t.elapsed());
@@ -2817,7 +2859,7 @@ fn search_inter_block(
2817 false,2859 false,
2818 search.base_q_idx,2860 search.base_q_idx,
2819 search.deadzone,2861 search.deadzone,
2820- luma_set,2862+ luma_set, fctx,
2821 );2863 );
2822 let u = mc_trial(2864 let u = mc_trial(
2823 &chroma[0],2865 &chroma[0],
@@ -2833,7 +2875,7 @@ fn search_inter_block(
2833 false,2875 false,
2834 search.base_q_idx,2876 search.base_q_idx,
2835 search.deadzone,2877 search.deadzone,
2836- chroma_set,2878+ chroma_set, fctx,
2837 );2879 );
2838 let v = mc_trial(2880 let v = mc_trial(
2839 &chroma[1],2881 &chroma[1],
@@ -2849,7 +2891,7 @@ fn search_inter_block(
2849 false,2891 false,
2850 search.base_q_idx,2892 search.base_q_idx,
2851 search.deadzone,2893 search.deadzone,
2852- chroma_set,2894+ chroma_set, fctx,
2853 );2895 );
2854 let drl_bits = if stack.entries.len() > 1 {2896 let drl_bits = if stack.entries.len() > 1 {
2855 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)2897 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
@@ -2912,7 +2954,7 @@ pub(crate) fn encode_inter_frame(
2912 base_q_idx: u8,2954 base_q_idx: u8,
2913 deadzone: f64,2955 deadzone: f64,
2914 order_hint: u32,2956 order_hint: u32,
2915- render: (usize, usize),2957+ render: (usize, usize), fctx: &crate::decode::FrameCtx,
2916 ) -> Result<Encoded> {2958 ) -> Result<Encoded> {
2917 picture.check()?;2959 picture.check()?;
2918 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {2960 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -3043,7 +3085,7 @@ pub(crate) fn encode_inter_frame(
3043 &search,3085 &search,
3044 &mode_bits_table,3086 &mode_bits_table,
3045 reference,3087 reference,
3046- &stack,3088+ &stack, fctx,
3047 );3089 );
3048 3090
3049 for dr in 0..8 {3091 for dr in 0..8 {
@@ -3142,7 +3184,7 @@ pub(crate) fn encode_inter_frame(
3142 &search,3184 &search,
3143 &mode_bits_table,3185 &mode_bits_table,
3144 reference,3186 reference,
3145- &stack,3187+ &stack, fctx,
3146 );3188 );
3147 for dr in 0..4 {3189 for dr in 0..4 {
3148 for dc in 0..4 {3190 for dc in 0..4 {
@@ -3202,7 +3244,7 @@ pub(crate) fn encode_inter_frame(
3202 &search,3244 &search,
3203 &mode_bits_table,3245 &mode_bits_table,
3204 reference,3246 reference,
3205- &stack,3247+ &stack, fctx,
3206 );3248 );
3207 for dr in 0..2 {3249 for dr in 0..2 {
3208 for dc in 0..2 {3250 for dc in 0..2 {
@@ -3316,10 +3358,10 @@ pub struct EncodedSequence {
3316 /// Returns an error when `pictures` is empty, when any picture besides the3358 /// Returns an error when `pictures` is empty, when any picture besides the
3317 /// first is not the same size as the first, or under the same conditions3359 /// first is not the same size as the first, or under the same conditions
3318 /// [`encode_key_frame`] and the inter frame path do.3360 /// [`encode_key_frame`] and the inter frame path do.
3319-pub fn encode_sequence(3361+pub(crate) fn encode_sequence_with_ctx(
3320 pictures: &[Picture],3362 pictures: &[Picture],
3321 base_q_idx: u8,3363 base_q_idx: u8,
3322- deadzone: f64,3364+ deadzone: f64, fctx: &crate::decode::FrameCtx,
3323 ) -> Result<EncodedSequence> {3365 ) -> Result<EncodedSequence> {
3324 let Some((first, rest)) = pictures.split_first() else {3366 let Some((first, rest)) = pictures.split_first() else {
3325 return Err(Error::unsupported(3367 return Err(Error::unsupported(
@@ -3341,7 +3383,7 @@ pub fn encode_sequence(
3341 &KEY_FRAME_MODES,3383 &KEY_FRAME_MODES,
3342 split_blocks(),3384 split_blocks(),
3343 render,3385 render,
3344- unspecified_color_config(),3386+ unspecified_color_config(), fctx,
3345 )?;3387 )?;
3346 let mut stream = key.stream.clone();3388 let mut stream = key.stream.clone();
3347 let mut reference = key.reconstruction.clone();3389 let mut reference = key.reconstruction.clone();
@@ -3361,7 +3403,7 @@ pub fn encode_sequence(
3361 base_q_idx,3403 base_q_idx,
3362 deadzone,3404 deadzone,
3363 order_hint,3405 order_hint,
3364- render,3406+ render, fctx,
3365 )?;3407 )?;
3366 stream.extend_from_slice(&inter.stream);3408 stream.extend_from_slice(&inter.stream);
3367 reference = inter.reconstruction.clone();3409 reference = inter.reconstruction.clone();
@@ -3442,6 +3484,7 @@ mod tests {
3442 /// (the horizontal shapes, which those partitions never produce).3484 /// (the horizontal shapes, which those partitions never produce).
3443 #[test]3485 #[test]
3444 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {3486 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
3487+ let fctx = &crate::decode::FrameCtx::new();
3445 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).3488 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
3446 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [3489 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
3447 (4, 8, 64, 9280, 64, 550),3490 (4, 8, 64, 9280, 64, 550),
@@ -3469,7 +3512,7 @@ mod tests {
3469 x: usize,3512 x: usize,
3470 y: usize,3513 y: usize,
3471 width: usize,3514 width: usize,
3472- height: usize,3515+ height: usize, fctx: &crate::decode::FrameCtx,
3473 ) -> (bool, bool) {3516 ) -> (bool, bool) {
3474 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);3517 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
3475 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);3518 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
@@ -3518,8 +3561,8 @@ mod tests {
3518 for sb_x in [0usize, 64] {3561 for sb_x in [0usize, 64] {
3519 for y in (sb_y..sb_y + 64).step_by(bh) {3562 for y in (sb_y..sb_y + 64).step_by(bh) {
3520 for x in (sb_x..sb_x + 64).step_by(bw) {3563 for x in (sb_x..sb_x + 64).step_by(bw) {
3521- let got = Reach::of_rect(bw, bh, x, y, 256, 256);3564+ let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
3522- let want = libaom_reach(bw, bh, x, y, 256, 256);3565+ let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
3523 assert_eq!(3566 assert_eq!(
3524 (got.above_right, got.below_left),3567 (got.above_right, got.below_left),
3525 want,3568 want,
@@ -3653,13 +3696,14 @@ mod tests {
3653 /// which is why this is an equality and not a tolerance.3696 /// which is why this is an equality and not a tolerance.
3654 #[test]3697 #[test]
3655 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {3698 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
3699+ let fctx = &crate::decode::FrameCtx::new();
3656 if !have_ffmpeg() {3700 if !have_ffmpeg() {
3657 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");3701 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
3658 return;3702 return;
3659 }3703 }
3660 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {3704 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
3661 let picture = test_card(width, height);3705 let picture = test_card(width, height);
3662- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();3706+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3663 let decoded = ffmpeg_decode(&encoded.stream, width, height);3707 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3664 assert_eq!(3708 assert_eq!(
3665 decoded.y, encoded.reconstruction.y,3709 decoded.y, encoded.reconstruction.y,
@@ -3673,7 +3717,7 @@ mod tests {
3673 let (width, height) = (64usize, 64usize);3717 let (width, height) = (64usize, 64usize);
3674 let picture = test_card(width, height);3718 let picture = test_card(width, height);
3675 for &q in &[15u8, 45, 100, 200] {3719 for &q in &[15u8, 45, 100, 200] {
3676- let encoded = encode_key_frame(&picture, q, 0.5).unwrap();3720+ let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
3677 let decoded = ffmpeg_decode(&encoded.stream, width, height);3721 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3678 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");3722 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
3679 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");3723 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
@@ -3691,6 +3735,7 @@ mod tests {
3691 /// same coefficient syntax decodes clean on every intra key-frame gate).3735 /// same coefficient syntax decodes clean on every intra key-frame gate).
3692 #[test]3736 #[test]
3693 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {3737 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
3738+ let fctx = &crate::decode::FrameCtx::new();
3694 if !have_ffmpeg() {3739 if !have_ffmpeg() {
3695 eprintln!(3740 eprintln!(
3696 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"3741 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
@@ -3699,7 +3744,7 @@ mod tests {
3699 }3744 }
3700 let (width, height) = (64usize, 64usize);3745 let (width, height) = (64usize, 64usize);
3701 let picture = Picture::grey(width, height);3746 let picture = Picture::grey(width, height);
3702- let key = encode_key_frame(&picture, 100, 0.5).unwrap();3747+ let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3703 3748
3704 let (seq, _) = key_frame_headers(width, height, 100).unwrap();3749 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
3705 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();3750 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
@@ -3810,6 +3855,7 @@ mod tests {
3810 /// `ffprobe` is asserted to report below.3855 /// `ffprobe` is asserted to report below.
3811 #[test]3856 #[test]
3812 fn a_frame_round_trips_at_its_own_size() {3857 fn a_frame_round_trips_at_its_own_size() {
3858+ let fctx = &crate::decode::FrameCtx::new();
3813 if !have_ffmpeg() {3859 if !have_ffmpeg() {
3814 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");3860 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
3815 return;3861 return;
@@ -3827,7 +3873,7 @@ mod tests {
3827 (192, 120),3873 (192, 120),
3828 ] {3874 ] {
3829 let picture = test_card(width, height);3875 let picture = test_card(width, height);
3830- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();3876+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3831 assert_eq!(3877 assert_eq!(
3832 (encoded.reconstruction.width, encoded.reconstruction.height),3878 (encoded.reconstruction.width, encoded.reconstruction.height),
3833 (width, height),3879 (width, height),
@@ -3875,12 +3921,13 @@ mod tests {
3875 /// the header's own size before output).3921 /// the header's own size before output).
3876 #[test]3922 #[test]
3877 fn an_854x480_picture_round_trips_through_its_padding() {3923 fn an_854x480_picture_round_trips_through_its_padding() {
3924+ let fctx = &crate::decode::FrameCtx::new();
3878 if !have_ffmpeg() {3925 if !have_ffmpeg() {
3879 return;3926 return;
3880 }3927 }
3881 let (width, height) = (854usize, 480usize);3928 let (width, height) = (854usize, 480usize);
3882 let picture = test_card(width, height);3929 let picture = test_card(width, height);
3883- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();3930+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3884 let decoded = ffmpeg_decode(&encoded.stream, width, height);3931 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3885 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");3932 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
3886 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");3933 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
@@ -3905,19 +3952,20 @@ mod tests {
3905 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).3952 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
3906 #[test]3953 #[test]
3907 fn of_tu_follows_the_block_row_including_under_vert_ab() {3954 fn of_tu_follows_the_block_row_including_under_vert_ab() {
3955+ let fctx = &crate::decode::FrameCtx::new();
3908 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in3956 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
3909 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's3957 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
3910 // above-right answer is the BLOCK's, which is the whole reason a unit3958 // above-right answer is the BLOCK's, which is the whole reason a unit
3911 // asks the block instead of looking itself up (the3959 // asks the block instead of looking itself up (the
3912 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).3960 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
3913- let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);3961+ let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
3914 assert_eq!(3962 assert_eq!(
3915 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,3963 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
3916 plain.above_right,3964 plain.above_right,
3917 "ordinary table: the top-right TX4 unit takes the block's row"3965 "ordinary table: the top-right TX4 unit takes the block's row"
3918 );3966 );
3919 let guard = Reach::vert_ab_partition();3967 let guard = Reach::vert_ab_partition();
3920- let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);3968+ let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
3921 assert_eq!(3969 assert_eq!(
3922 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,3970 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
3923 vert.above_right,3971 vert.above_right,
@@ -3939,6 +3987,7 @@ mod tests {
3939 /// wrong for one block size while looking plausible for the other.3987 /// wrong for one block size while looking plausible for the other.
3940 #[test]3988 #[test]
3941 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {3989 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
3990+ let fctx = &crate::decode::FrameCtx::new();
3942 // Transcribed from has_top_right/has_bottom_left's row_off==0,3991 // Transcribed from has_top_right/has_bottom_left's row_off==0,
3943 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a3992 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
3944 // 128px reference grid) pinned as libaom pins it, independent of the3993 // 128px reference grid) pinned as libaom pins it, independent of the
@@ -3968,7 +4017,7 @@ mod tests {
3968 (table[index / 8] >> (index % 8)) & 1 != 04017 (table[index / 8] >> (index % 8)) & 1 != 0
3969 }4018 }
3970 4019
3971- fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize) -> bool {4020+ fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, fctx: &crate::decode::FrameCtx) -> bool {
3972 if x == 0 || y + side >= height {4021 if x == 0 || y + side >= height {
3973 return false;4022 return false;
3974 }4023 }
@@ -3997,7 +4046,7 @@ mod tests {
3997 for side in [16usize, BLOCK] {4046 for side in [16usize, BLOCK] {
3998 for y in (0..height).step_by(side) {4047 for y in (0..height).step_by(side) {
3999 for x in (0..width).step_by(side) {4048 for x in (0..width).step_by(side) {
4000- let reach = Reach::of(side, x, y, width, height);4049+ let reach = Reach::of(side, x, y, width, height, fctx);
4001 assert_eq!(4050 assert_eq!(
4002 reach.above_right,4051 reach.above_right,
4003 libaom_top_right(side, x, y, width, height),4052 libaom_top_right(side, x, y, width, height),
@@ -4005,7 +4054,7 @@ mod tests {
4005 );4054 );
4006 assert_eq!(4055 assert_eq!(
4007 reach.below_left,4056 reach.below_left,
4008- libaom_bottom_left(side, x, y, height),4057+ libaom_bottom_left(side, x, y, height, fctx),
4009 "side={side} x={x} y={y}: below_left"4058 "side={side} x={x} y={y}: below_left"
4010 );4059 );
4011 }4060 }
@@ -4083,6 +4132,7 @@ mod tests {
4083 4132
4084 #[test]4133 #[test]
4085 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {4134 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
4135+ let fctx = &crate::decode::FrameCtx::new();
4086 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);4136 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
4087 // Interior superblock, so neither the frame edge nor the col == 0 /4137 // Interior superblock, so neither the frame edge nor the col == 0 /
4088 // last-row early returns answer instead of the table.4138 // last-row early returns answer instead of the table.
@@ -4091,10 +4141,10 @@ mod tests {
4091 for row in 0..8 {4141 for row in 0..8 {
4092 for col in 1..8 {4142 for col in 1..8 {
4093 let (x, y) = (sb_x + col * 8, sb_y + row * 8);4143 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
4094- let raster = Reach::of(8, x, y, width, height).below_left;4144+ let raster = Reach::of(8, x, y, width, height, fctx).below_left;
4095 let vert = {4145 let vert = {
4096 let _guard = Reach::vert_ab_partition();4146 let _guard = Reach::vert_ab_partition();
4097- Reach::of(8, x, y, width, height).below_left4147+ Reach::of(8, x, y, width, height, fctx).below_left
4098 };4148 };
4099 // The TR square of a VERT_A/_B sits at an even row, odd4149 // The TR square of a VERT_A/_B sits at an even row, odd
4100 // column; every other slot must be untouched by the guard.4150 // column; every other slot must be untouched by the guard.
@@ -4109,16 +4159,17 @@ mod tests {
4109 }4159 }
4110 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");4160 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
4111 // The guard is scoped: it must not leak past its own block.4161 // The guard is scoped: it must not leak past its own block.
4112- assert!(!Reach::of(8, sb_x + 8, sb_y, width, height).below_left);4162+ assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
4113 }4163 }
4114 4164
4115 /// An odd width or height is refused by name, not by however the padder4165 /// An odd width or height is refused by name, not by however the padder
4116 /// or the block coder would happen to fail on it.4166 /// or the block coder would happen to fail on it.
4117 #[test]4167 #[test]
4118 fn odd_dimensions_are_refused() {4168 fn odd_dimensions_are_refused() {
4169+ let fctx = &crate::decode::FrameCtx::new();
4119 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {4170 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
4120 let picture = Picture::grey(width, height);4171 let picture = Picture::grey(width, height);
4121- let err = encode_key_frame(&picture, 100, 0.5)4172+ let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
4122 .expect_err(&format!("{width}x{height} is odd and must be refused"));4173 .expect_err(&format!("{width}x{height} is odd and must be refused"));
4123 assert!(4174 assert!(
4124 err.to_string().contains("even"),4175 err.to_string().contains("even"),
@@ -4133,6 +4184,7 @@ mod tests {
4133 /// own (padded) reconstruction.4184 /// own (padded) reconstruction.
4134 #[test]4185 #[test]
4135 fn sequence_round_trips_at_a_non_multiple_size() {4186 fn sequence_round_trips_at_a_non_multiple_size() {
4187+ let fctx = &crate::decode::FrameCtx::new();
4136 if !have_ffmpeg() {4188 if !have_ffmpeg() {
4137 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");4189 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
4138 return;4190 return;
@@ -4141,7 +4193,7 @@ mod tests {
4141 let pictures: Vec<Picture> = (0..3)4193 let pictures: Vec<Picture> = (0..3)
4142 .map(|i| panned_test_card(width, height, i * 3))4194 .map(|i| panned_test_card(width, height, i * 3))
4143 .collect();4195 .collect();
4144- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();4196+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4145 assert_eq!(encoded.frames.len(), 3);4197 assert_eq!(encoded.frames.len(), 3);
4146 for (i, frame) in encoded.frames.iter().enumerate() {4198 for (i, frame) in encoded.frames.iter().enumerate() {
4147 assert_eq!(4199 assert_eq!(
@@ -4175,6 +4227,7 @@ mod tests {
4175 /// inter tile writer's parity with it across a real multi-frame export.4227 /// inter tile writer's parity with it across a real multi-frame export.
4176 #[test]4228 #[test]
4177 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {4229 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
4230+ let fctx = &crate::decode::FrameCtx::new();
4178 if !have_ffmpeg() {4231 if !have_ffmpeg() {
4179 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");4232 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
4180 return;4233 return;
@@ -4183,7 +4236,7 @@ mod tests {
4183 let pictures: Vec<Picture> = (0..3)4236 let pictures: Vec<Picture> = (0..3)
4184 .map(|i| panned_test_card(width, height, i * 3))4237 .map(|i| panned_test_card(width, height, i * 3))
4185 .collect();4238 .collect();
4186- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();4239+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4187 assert_eq!(encoded.frames.len(), 3);4240 assert_eq!(encoded.frames.len(), 3);
4188 for (i, frame) in encoded.frames.iter().enumerate() {4241 for (i, frame) in encoded.frames.iter().enumerate() {
4189 assert_eq!(4242 assert_eq!(
@@ -4219,14 +4272,15 @@ mod tests {
4219 /// actually exercised).4272 /// actually exercised).
4220 #[test]4273 #[test]
4221 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {4274 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
4275+ let fctx = &crate::decode::FrameCtx::new();
4222 let (width, height) = (640usize, 360usize);4276 let (width, height) = (640usize, 360usize);
4223 let picture = Picture::grey(width, height);4277 let picture = Picture::grey(width, height);
4224- encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle");4278+ encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
4225 4279
4226 // `encode_sequence`'s second frame is the inter path: same size, now4280 // `encode_sequence`'s second frame is the inter path: same size, now
4227 // wired the same way.4281 // wired the same way.
4228 let pictures = vec![picture.clone(), picture];4282 let pictures = vec![picture.clone(), picture];
4229- encode_sequence(&pictures, 100, 0.5)4283+ encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
4230 .expect("inter frame now codes the mod-32==8 straddle too");4284 .expect("inter frame now codes the mod-32==8 straddle too");
4231 }4285 }
4232 4286
@@ -4237,6 +4291,7 @@ mod tests {
4237 /// only encoder-clean.4291 /// only encoder-clean.
4238 #[test]4292 #[test]
4239 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {4293 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
4294+ let fctx = &crate::decode::FrameCtx::new();
4240 if !have_ffmpeg() {4295 if !have_ffmpeg() {
4241 eprintln!(4296 eprintln!(
4242 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \4297 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
@@ -4247,7 +4302,7 @@ mod tests {
4247 let (width, height) = (640usize, 360usize);4302 let (width, height) = (640usize, 360usize);
4248 for shift in [0i64, 7, 19] {4303 for shift in [0i64, 7, 19] {
4249 let picture = panned_test_card(width, height, shift);4304 let picture = panned_test_card(width, height, shift);
4250- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();4305+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4251 let decoded = ffmpeg_decode(&encoded.stream, width, height);4306 let decoded = ffmpeg_decode(&encoded.stream, width, height);
4252 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");4307 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
4253 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");4308 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
@@ -4261,6 +4316,7 @@ mod tests {
4261 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.4316 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
4262 #[test]4317 #[test]
4263 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {4318 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
4319+ let fctx = &crate::decode::FrameCtx::new();
4264 if !have_ffmpeg() {4320 if !have_ffmpeg() {
4265 eprintln!(4321 eprintln!(
4266 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"4322 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
@@ -4271,7 +4327,7 @@ mod tests {
4271 let pictures: Vec<Picture> = (0..4)4327 let pictures: Vec<Picture> = (0..4)
4272 .map(|i| panned_test_card(width, height, i * 3))4328 .map(|i| panned_test_card(width, height, i * 3))
4273 .collect();4329 .collect();
4274- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();4330+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4275 assert_eq!(encoded.frames.len(), 4);4331 assert_eq!(encoded.frames.len(), 4);
4276 if let Ok(path) = std::env::var("EC_AV1_DUMP") {4332 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
4277 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");4333 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
@@ -4319,6 +4375,7 @@ mod tests {
4319 #[test]4375 #[test]
4320 #[ignore = "a sweep, not a gate"]4376 #[ignore = "a sweep, not a gate"]
4321 fn probe_lambda() {4377 fn probe_lambda() {
4378+ let fctx = &crate::decode::FrameCtx::new();
4322 let mut pictures = vec![4379 let mut pictures = vec![
4323 ("test card".to_string(), test_card(160, 96)),4380 ("test card".to_string(), test_card(160, 96)),
4324 ("stripes".to_string(), stripes(160, 96, true)),4381 ("stripes".to_string(), stripes(160, 96, true)),
@@ -4331,8 +4388,8 @@ mod tests {
4331 }4388 }
4332 }4389 }
4333 for (name, picture) in pictures {4390 for (name, picture) in pictures {
4334- let dc = ladder(&picture, &[DC_PRED]);4391+ let dc = ladder(&picture, &[DC_PRED], fctx);
4335- let searched = ladder(&picture, &NON_DIRECTIONAL);4392+ let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
4336 println!(4393 println!(
4337 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",4394 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
4338 bd_rate(&dc, &searched) * 100.0,4395 bd_rate(&dc, &searched) * 100.0,
@@ -4349,8 +4406,9 @@ mod tests {
4349 #[test]4406 #[test]
4350 #[ignore = "a sweep, not a gate"]4407 #[ignore = "a sweep, not a gate"]
4351 fn probe_ladder() {4408 fn probe_ladder() {
4409+ let fctx = &crate::decode::FrameCtx::new();
4352 for (name, picture) in sweep_pictures() {4410 for (name, picture) in sweep_pictures() {
4353- let all = ladder(&picture, &KEY_FRAME_MODES);4411+ let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
4354 let points = all4412 let points = all
4355 .iter()4413 .iter()
4356 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))4414 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
@@ -4366,6 +4424,7 @@ mod tests {
4366 #[test]4424 #[test]
4367 #[ignore = "a sweep, not a gate"]4425 #[ignore = "a sweep, not a gate"]
4368 fn probe_split() {4426 fn probe_split() {
4427+ let fctx = &crate::decode::FrameCtx::new();
4369 for (name, picture) in sweep_pictures() {4428 for (name, picture) in sweep_pictures() {
4370 let ladder = |split: bool| {4429 let ladder = |split: bool| {
4371 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]4430 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
@@ -4378,7 +4437,7 @@ mod tests {
4378 &KEY_FRAME_MODES,4437 &KEY_FRAME_MODES,
4379 split,4438 split,
4380 (picture.width, picture.height),4439 (picture.width, picture.height),
4381- unspecified_color_config(),4440+ unspecified_color_config(), fctx,
4382 )4441 )
4383 .unwrap();4442 .unwrap();
4384 (4443 (
@@ -4398,7 +4457,7 @@ mod tests {
4398 &KEY_FRAME_MODES,4457 &KEY_FRAME_MODES,
4399 true,4458 true,
4400 (picture.width, picture.height),4459 (picture.width, picture.height),
4401- unspecified_color_config(),4460+ unspecified_color_config(), fctx,
4402 )4461 )
4403 .unwrap()4462 .unwrap()
4404 .modes4463 .modes
@@ -4446,6 +4505,7 @@ mod tests {
4446 /// over a whole picture and the reconstruction gated against ffmpeg.4505 /// over a whole picture and the reconstruction gated against ffmpeg.
4447 #[test]4506 #[test]
4448 fn every_mode_decodes_to_what_the_encoder_predicted() {4507 fn every_mode_decodes_to_what_the_encoder_predicted() {
4508+ let fctx = &crate::decode::FrameCtx::new();
4449 if !have_ffmpeg() {4509 if !have_ffmpeg() {
4450 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");4510 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
4451 return;4511 return;
@@ -4456,7 +4516,7 @@ mod tests {
4456 for (width, height) in [(128, 96), (160, 96)] {4516 for (width, height) in [(128, 96), (160, 96)] {
4457 let picture = test_card(width, height);4517 let picture = test_card(width, height);
4458 for mode in KEY_FRAME_MODES {4518 for mode in KEY_FRAME_MODES {
4459- let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();4519+ let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
4460 let decoded = ffmpeg_decode(&encoded.stream, width, height);4520 let decoded = ffmpeg_decode(&encoded.stream, width, height);
4461 for (plane, ours, theirs, stride) in [4521 for (plane, ours, theirs, stride) in [
4462 ("luma", &encoded.reconstruction.y, &decoded.y, width),4522 ("luma", &encoded.reconstruction.y, &decoded.y, width),
@@ -4483,6 +4543,7 @@ mod tests {
4483 /// while leaving every fidelity gate intact.4543 /// while leaving every fidelity gate intact.
4484 #[test]4544 #[test]
4485 fn the_search_picks_the_direction_the_picture_runs() {4545 fn the_search_picks_the_direction_the_picture_runs() {
4546+ let fctx = &crate::decode::FrameCtx::new();
4486 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {4547 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
4487 let picture = stripes(128, 96, vertical);4548 let picture = stripes(128, 96, vertical);
4488 // Only the pair, because on stripes a third mode predicts exactly4549 // Only the pair, because on stripes a third mode predicts exactly
@@ -4491,7 +4552,7 @@ mod tests {
4491 // tie then goes to whichever is cheaper to name, which is not what4552 // tie then goes to whichever is cheaper to name, which is not what
4492 // this gate is about.4553 // this gate is about.
4493 let encoded =4554 let encoded =
4494- encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap();4555+ encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
4495 // The first block of the picture has neither neighbour, so it4556 // The first block of the picture has neither neighbour, so it
4496 // cannot tell the modes apart; every other one can.4557 // cannot tell the modes apart; every other one can.
4497 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();4558 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
@@ -4536,11 +4597,11 @@ mod tests {
4536 4597
4537 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by4598 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
4538 /// fidelity.4599 /// fidelity.
4539- fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> {4600+ fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
4540 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]4601 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
4541 .iter()4602 .iter()
4542 .map(|&q| {4603 .map(|&q| {
4543- let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap();4604+ let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
4544 (4605 (
4545 psnr(&encoded.reconstruction.y, picture.y.as_slice()),4606 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
4546 (encoded.stream.len() as f64).log10(),4607 (encoded.stream.len() as f64).log10(),
@@ -4557,13 +4618,14 @@ mod tests {
4557 /// directional pair has.4618 /// directional pair has.
4558 #[test]4619 #[test]
4559 fn the_search_beats_dc_alone() {4620 fn the_search_beats_dc_alone() {
4621+ let fctx = &crate::decode::FrameCtx::new();
4560 for (name, picture, want) in [4622 for (name, picture, want) in [
4561 ("test card", test_card(160, 96), -0.05),4623 ("test card", test_card(160, 96), -0.05),
4562 ("stripes", stripes(160, 96, true), -0.40),4624 ("stripes", stripes(160, 96, true), -0.40),
4563 ] {4625 ] {
4564 let saved = bd_rate(4626 let saved = bd_rate(
4565- &ladder(&picture, &[DC_PRED]),4627+ &ladder(&picture, &[DC_PRED], fctx),
4566- &ladder(&picture, &NON_DIRECTIONAL),4628+ &ladder(&picture, &NON_DIRECTIONAL, fctx),
4567 );4629 );
4568 assert!(4630 assert!(
4569 saved < want,4631 saved < want,
@@ -4598,11 +4660,12 @@ mod tests {
4598 #[test]4660 #[test]
4599 #[ignore = "a sweep, not a gate"]4661 #[ignore = "a sweep, not a gate"]
4600 fn probe_directional() {4662 fn probe_directional() {
4663+ let fctx = &crate::decode::FrameCtx::new();
4601 for (name, picture) in sweep_pictures() {4664 for (name, picture) in sweep_pictures() {
4602- let dc = ladder(&picture, &[DC_PRED]);4665+ let dc = ladder(&picture, &[DC_PRED], fctx);
4603- let flat = ladder(&picture, &NON_DIRECTIONAL);4666+ let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
4604- let all = ladder(&picture, &KEY_FRAME_MODES);4667+ let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
4605- let encoded = encode_key_frame(&picture, 90, 0.5).unwrap();4668+ let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
4606 let directional = encoded4669 let directional = encoded
4607 .modes4670 .modes
4608 .iter()4671 .iter()
@@ -4646,8 +4709,8 @@ mod tests {
4646 4709
4647 /// The mode picked by the most blocks of a picture, ignoring the first4710 /// The mode picked by the most blocks of a picture, ignoring the first
4648 /// block, which has no neighbours to tell the modes apart with.4711 /// block, which has no neighbours to tell the modes apart with.
4649- fn favourite_mode(picture: &Picture) -> (u8, usize, usize) {4712+ fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
4650- let encoded = encode_key_frame(picture, 100, 0.5).unwrap();4713+ let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
4651 let blocks = &encoded.modes[1..];4714 let blocks = &encoded.modes[1..];
4652 let mut counts = [0usize; 13];4715 let mut counts = [0usize; 13];
4653 for &mode in blocks {4716 for &mode in blocks {
@@ -4667,9 +4730,10 @@ mod tests {
4667 /// the above row where it should read the left column, would swap these.4730 /// the above row where it should read the left column, would swap these.
4668 #[test]4731 #[test]
4669 fn the_search_picks_the_diagonal_the_picture_runs() {4732 fn the_search_picks_the_diagonal_the_picture_runs() {
4733+ let fctx = &crate::decode::FrameCtx::new();
4670 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {4734 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
4671 let picture = diagonal(160, 96, down_right);4735 let picture = diagonal(160, 96, down_right);
4672- let (mode, count, blocks) = favourite_mode(&picture);4736+ let (mode, count, blocks) = favourite_mode(&picture, fctx);
4673 assert_eq!(4737 assert_eq!(
4674 mode, want,4738 mode, want,
4675 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"4739 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
@@ -4685,14 +4749,15 @@ mod tests {
4685 /// it, which is what costing the mode symbol is for.4749 /// it, which is what costing the mode symbol is for.
4686 #[test]4750 #[test]
4687 fn the_diagonals_beat_the_modes_that_read_no_further() {4751 fn the_diagonals_beat_the_modes_that_read_no_further() {
4752+ let fctx = &crate::decode::FrameCtx::new();
4688 for (name, picture, want) in [4753 for (name, picture, want) in [
4689 ("down-right", diagonal(160, 96, true), -0.20),4754 ("down-right", diagonal(160, 96, true), -0.20),
4690 ("down-left", diagonal(160, 96, false), -0.20),4755 ("down-left", diagonal(160, 96, false), -0.20),
4691 ("test card", test_card(160, 96), 0.01),4756 ("test card", test_card(160, 96), 0.01),
4692 ] {4757 ] {
4693 let saved = bd_rate(4758 let saved = bd_rate(
4694- &ladder(&picture, &NON_DIRECTIONAL),4759+ &ladder(&picture, &NON_DIRECTIONAL, fctx),
4695- &ladder(&picture, &KEY_FRAME_MODES),4760+ &ladder(&picture, &KEY_FRAME_MODES, fctx),
4696 );4761 );
4697 assert!(4762 assert!(
4698 saved < want,4763 saved < want,
@@ -4707,15 +4772,16 @@ mod tests {
4707 /// something else, and a search with nothing to choose from likewise.4772 /// something else, and a search with nothing to choose from likewise.
4708 #[test]4773 #[test]
4709 fn a_mode_the_encoder_cannot_predict_is_refused() {4774 fn a_mode_the_encoder_cannot_predict_is_refused() {
4775+ let fctx = &crate::decode::FrameCtx::new();
4710 let picture = test_card(64, 64);4776 let picture = test_card(64, 64);
4711- let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13])4777+ let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
4712 .unwrap_err()4778 .unwrap_err()
4713 .to_string();4779 .to_string();
4714 assert!(4780 assert!(
4715 message.contains("intra mode 13"),4781 message.contains("intra mode 13"),
4716 "the refusal must name the mode, got {message}"4782 "the refusal must name the mode, got {message}"
4717 );4783 );
4718- assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());4784+ assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
4719 }4785 }
4720 4786
4721 /// The picture that comes back is the picture that went in, to within the4787 /// The picture that comes back is the picture that went in, to within the
@@ -4725,8 +4791,9 @@ mod tests {
4725 /// right picture.4791 /// right picture.
4726 #[test]4792 #[test]
4727 fn the_encoded_picture_is_the_one_that_went_in() {4793 fn the_encoded_picture_is_the_one_that_went_in() {
4794+ let fctx = &crate::decode::FrameCtx::new();
4728 let picture = test_card(160, 96);4795 let picture = test_card(160, 96);
4729- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();4796+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4730 let luma = psnr(&encoded.reconstruction.y, &picture.y);4797 let luma = psnr(&encoded.reconstruction.y, &picture.y);
4731 assert!(luma > 36.0, "luma PSNR {luma} at q 100");4798 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
4732 for (plane, (got, want)) in [4799 for (plane, (got, want)) in [
@@ -4746,10 +4813,11 @@ mod tests {
4746 /// loop above this will assume.4813 /// loop above this will assume.
4747 #[test]4814 #[test]
4748 fn fidelity_and_rate_move_with_the_quantizer() {4815 fn fidelity_and_rate_move_with_the_quantizer() {
4816+ let fctx = &crate::decode::FrameCtx::new();
4749 let picture = test_card(128, 128);4817 let picture = test_card(128, 128);
4750 let mut previous: Option<(usize, f64)> = None;4818 let mut previous: Option<(usize, f64)> = None;
4751 for &q in &[70u8, 90, 110] {4819 for &q in &[70u8, 90, 110] {
4752- let encoded = encode_key_frame(&picture, q, 0.5).unwrap();4820+ let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
4753 let quality = psnr(&encoded.reconstruction.y, &picture.y);4821 let quality = psnr(&encoded.reconstruction.y, &picture.y);
4754 if let Some((bytes, better)) = previous {4822 if let Some((bytes, better)) = previous {
4755 assert!(4823 assert!(
@@ -4764,7 +4832,7 @@ mod tests {
4764 4832
4765 let mut previous = None;4833 let mut previous = None;
4766 for &deadzone in &[0.5f64, 0.3, 0.15] {4834 for &deadzone in &[0.5f64, 0.3, 0.15] {
4767- let encoded = encode_key_frame(&picture, 100, deadzone).unwrap();4835+ let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap();
4768 let quality = psnr(&encoded.reconstruction.y, &picture.y);4836 let quality = psnr(&encoded.reconstruction.y, &picture.y);
4769 if let Some((bytes, better)) = previous {4837 if let Some((bytes, better)) = previous {
4770 assert!(4838 assert!(
@@ -4782,8 +4850,8 @@ mod tests {
4782 // even though a coarser quantizer always codes no more than a finer4850 // even though a coarser quantizer always codes no more than a finer
4783 // one on the same picture.4851 // one on the same picture.
4784 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {4852 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
4785- let lo_bytes = encode_key_frame(&picture, lo, 0.5).unwrap().stream.len();4853+ let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
4786- let hi_bytes = encode_key_frame(&picture, hi, 0.5).unwrap().stream.len();4854+ let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
4787 assert!(4855 assert!(
4788 hi_bytes <= lo_bytes,4856 hi_bytes <= lo_bytes,
4789 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"4857 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
@@ -4795,9 +4863,10 @@ mod tests {
4795 /// average, which is the picture's own value, and codes nothing.4863 /// average, which is the picture's own value, and codes nothing.
4796 #[test]4864 #[test]
4797 fn a_flat_picture_costs_almost_nothing() {4865 fn a_flat_picture_costs_almost_nothing() {
4866+ let fctx = &crate::decode::FrameCtx::new();
4798 let mut picture = Picture::grey(128, 128);4867 let mut picture = Picture::grey(128, 128);
4799 picture.y.fill(97);4868 picture.y.fill(97);
4800- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();4869+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4801 // The first block has no neighbour and predicts 128, so it carries a4870 // The first block has no neighbour and predicts 128, so it carries a
4802 // DC; every block after it predicts 97 and carries nothing.4871 // DC; every block after it predicts 97 and carries nothing.
4803 assert!(4872 assert!(
@@ -4824,14 +4893,15 @@ mod tests {
4824 /// corrupting the stream.4893 /// corrupting the stream.
4825 #[test]4894 #[test]
4826 fn a_picture_off_the_block_grid_is_refused() {4895 fn a_picture_off_the_block_grid_is_refused() {
4827- let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5)4896+ let fctx = &crate::decode::FrameCtx::new();
4897+ let msg = encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
4828 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")4898 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")
4829 .to_string();4899 .to_string();
4830 assert!(msg.contains("rectangular"), "refusal: {msg}");4900 assert!(msg.contains("rectangular"), "refusal: {msg}");
4831 4901
4832 let mut short = Picture::grey(64, 64);4902 let mut short = Picture::grey(64, 64);
4833 short.u.truncate(10);4903 short.u.truncate(10);
4834- assert!(encode_key_frame(&short, 100, 0.5).is_err());4904+ assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
4835 }4905 }
4836 4906
4837 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own4907 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
@@ -4906,13 +4976,14 @@ mod tests {
4906 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.4976 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
4907 #[test]4977 #[test]
4908 fn a_single_axis_straddle_round_trips_through_ffmpeg() {4978 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
4979+ let fctx = &crate::decode::FrameCtx::new();
4909 if !have_ffmpeg() {4980 if !have_ffmpeg() {
4910 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");4981 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
4911 return;4982 return;
4912 }4983 }
4913 let (width, height) = (40usize, 32usize);4984 let (width, height) = (40usize, 32usize);
4914 let picture = test_card(width, height);4985 let picture = test_card(width, height);
4915- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();4986+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4916 assert_eq!(4987 assert_eq!(
4917 (encoded.reconstruction.width, encoded.reconstruction.height),4988 (encoded.reconstruction.width, encoded.reconstruction.height),
4918 (width, height)4989 (width, height)
@@ -4934,6 +5005,7 @@ mod tests {
4934 /// synthetic pictures — real video reaches contexts a test card does not.5005 /// synthetic pictures — real video reaches contexts a test card does not.
4935 #[test]5006 #[test]
4936 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {5007 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
5008+ let fctx = &crate::decode::FrameCtx::new();
4937 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {5009 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
4938 eprintln!(5010 eprintln!(
4939 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \5011 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
@@ -4953,7 +5025,7 @@ mod tests {
4953 let (width, height) = (640usize, 352usize);5025 let (width, height) = (640usize, 352usize);
4954 let picture = clip_frame(&clip, &skip, width, height);5026 let picture = clip_frame(&clip, &skip, width, height);
4955 5027
4956- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();5028+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4957 let decoded = ffmpeg_decode(&encoded.stream, width, height);5029 let decoded = ffmpeg_decode(&encoded.stream, width, height);
4958 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");5030 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
4959 assert_eq!(decoded.u, encoded.reconstruction.u, "U");5031 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
@@ -5064,6 +5136,7 @@ mod tests {
5064 /// just the last one, and why this is an equality and not a tolerance.5136 /// just the last one, and why this is an equality and not a tolerance.
5065 #[test]5137 #[test]
5066 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {5138 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
5139+ let fctx = &crate::decode::FrameCtx::new();
5067 if !have_ffmpeg() {5140 if !have_ffmpeg() {
5068 eprintln!(5141 eprintln!(
5069 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"5142 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
@@ -5074,7 +5147,7 @@ mod tests {
5074 let pictures: Vec<Picture> = (0..5)5147 let pictures: Vec<Picture> = (0..5)
5075 .map(|i| panned_test_card(width, height, i * 3))5148 .map(|i| panned_test_card(width, height, i * 3))
5076 .collect();5149 .collect();
5077- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();5150+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5078 assert_eq!(encoded.frames.len(), 5);5151 assert_eq!(encoded.frames.len(), 5);
5079 5152
5080 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);5153 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
@@ -5104,11 +5177,12 @@ mod tests {
5104 /// asserted on beyond being reachable at all.5177 /// asserted on beyond being reachable at all.
5105 #[test]5178 #[test]
5106 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {5179 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
5180+ let fctx = &crate::decode::FrameCtx::new();
5107 let (width, height) = (256usize, 128usize);5181 let (width, height) = (256usize, 128usize);
5108 let pictures: Vec<Picture> = (0..5)5182 let pictures: Vec<Picture> = (0..5)
5109 .map(|i| panned_test_card(width, height, i * 2))5183 .map(|i| panned_test_card(width, height, i * 2))
5110 .collect();5184 .collect();
5111- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();5185+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5112 5186
5113 let key_bytes = encoded.frames[0].stream.len();5187 let key_bytes = encoded.frames[0].stream.len();
5114 eprintln!("frame bytes inter share");5188 eprintln!("frame bytes inter share");
@@ -5140,22 +5214,23 @@ mod tests {
5140 #[test]5214 #[test]
5141 #[ignore = "a perf probe, not a gate"]5215 #[ignore = "a perf probe, not a gate"]
5142 fn stage_timing_breakdown() {5216 fn stage_timing_breakdown() {
5217+ let fctx = &crate::decode::FrameCtx::new();
5143 use std::time::Instant;5218 use std::time::Instant;
5144 5219
5145 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {5220 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
5146 let picture = test_card(width, height);5221 let picture = test_card(width, height);
5147 5222
5148 let t = Instant::now();5223 let t = Instant::now();
5149- let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap();5224+ let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
5150 let dc_only_t = t.elapsed();5225 let dc_only_t = t.elapsed();
5151 5226
5152 let t = Instant::now();5227 let t = Instant::now();
5153 let non_directional =5228 let non_directional =
5154- encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap();5229+ encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
5155 let non_directional_t = t.elapsed();5230 let non_directional_t = t.elapsed();
5156 5231
5157 let t = Instant::now();5232 let t = Instant::now();
5158- let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap();5233+ let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
5159 let all_modes_t = t.elapsed();5234 let all_modes_t = t.elapsed();
5160 5235
5161 eprintln!(5236 eprintln!(
@@ -5175,7 +5250,7 @@ mod tests {
5175 let padded_pic = picture.padded_to(SUPERBLOCK);5250 let padded_pic = picture.padded_to(SUPERBLOCK);
5176 let t = Instant::now();5251 let t = Instant::now();
5177 let inter =5252 let inter =
5178- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();5253+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
5179 let inter_t = t.elapsed();5254 let inter_t = t.elapsed();
5180 eprintln!(5255 eprintln!(
5181 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \5256 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -5233,7 +5308,7 @@ mod tests {
5233 side,5308 side,
5234 false,5309 false,
5235 false,5310 false,
5236- &mut prediction,5311+ &mut prediction, fctx,
5237 );5312 );
5238 }5313 }
5239 let predict_t = t.elapsed() / N;5314 let predict_t = t.elapsed() / N;
@@ -5261,18 +5336,19 @@ mod tests {
5261 #[test]5336 #[test]
5262 #[ignore = "a perf probe, not a gate"]5337 #[ignore = "a perf probe, not a gate"]
5263 fn stage_timing_breakdown_inter() {5338 fn stage_timing_breakdown_inter() {
5339+ let fctx = &crate::decode::FrameCtx::new();
5264 use std::time::Instant;5340 use std::time::Instant;
5265 5341
5266 let (width, height) = (1280usize, 720);5342 let (width, height) = (1280usize, 720);
5267 let picture = test_card(width, height);5343 let picture = test_card(width, height);
5268- let key = encode_key_frame(&picture, 100, 0.5).unwrap();5344+ let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
5269 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);5345 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
5270 let padded_pic = picture.padded_to(SUPERBLOCK);5346 let padded_pic = picture.padded_to(SUPERBLOCK);
5271 5347
5272 stage_reset();5348 stage_reset();
5273 let t = Instant::now();5349 let t = Instant::now();
5274 let inter =5350 let inter =
5275- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();5351+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
5276 let total_t = t.elapsed();5352 let total_t = t.elapsed();
5277 let [motion_search, interpolation, transform_quant, entropy] = stage_read();5353 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
5278 let accounted = motion_search + transform_quant + entropy;5354 let accounted = motion_search + transform_quant + entropy;
@@ -5308,6 +5384,7 @@ mod tests {
5308 #[test]5384 #[test]
5309 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]5385 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
5310 fn prune_k_quality_sweep() {5386 fn prune_k_quality_sweep() {
5387+ let fctx = &crate::decode::FrameCtx::new();
5311 if !have_ffmpeg() {5388 if !have_ffmpeg() {
5312 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");5389 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
5313 return;5390 return;
@@ -5343,7 +5420,7 @@ mod tests {
5343 // a single-threaded #[ignore] probe, run by hand, never5420 // a single-threaded #[ignore] probe, run by hand, never
5344 // alongside other tests that read Search::top_k.5421 // alongside other tests that read Search::top_k.
5345 set_test_top_k_override(None);5422 set_test_top_k_override(None);
5346- let baseline = encode_key_frame(&picture, q, 0.5).unwrap();5423+ let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
5347 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);5424 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
5348 eprint!(5425 eprint!(
5349 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",5426 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
@@ -5352,7 +5429,7 @@ mod tests {
5352 );5429 );
5353 for &k in &[3usize, 4, 6] {5430 for &k in &[3usize, 4, 6] {
5354 set_test_top_k_override(Some(k));5431 set_test_top_k_override(Some(k));
5355- let pruned = encode_key_frame(&picture, q, 0.5).unwrap();5432+ let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
5356 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);5433 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
5357 eprint!(5434 eprint!(
5358 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",5435 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
@@ -5407,6 +5484,7 @@ mod tests {
5407 #[test]5484 #[test]
5408 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]5485 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
5409 fn prune_k_quality_sweep_inter() {5486 fn prune_k_quality_sweep_inter() {
5487+ let fctx = &crate::decode::FrameCtx::new();
5410 if !have_ffmpeg() {5488 if !have_ffmpeg() {
5411 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");5489 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
5412 return;5490 return;
@@ -5440,14 +5518,14 @@ mod tests {
5440 // single-threaded #[ignore] probe, run by hand, never5518 // single-threaded #[ignore] probe, run by hand, never
5441 // alongside other tests that read Search::top_k.5519 // alongside other tests that read Search::top_k.
5442 set_test_top_k_override_inter(None);5520 set_test_top_k_override_inter(None);
5443- let key = encode_key_frame(&key_source, q, 0.5).unwrap();5521+ let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
5444 let baseline = encode_inter_frame(5522 let baseline = encode_inter_frame(
5445 &inter_source,5523 &inter_source,
5446 &key.reconstruction,5524 &key.reconstruction,
5447 q,5525 q,
5448 0.5,5526 0.5,
5449 1,5527 1,
5450- (width, height),5528+ (width, height), fctx,
5451 )5529 )
5452 .unwrap();5530 .unwrap();
5453 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);5531 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -5464,7 +5542,7 @@ mod tests {
5464 q,5542 q,
5465 0.5,5543 0.5,
5466 1,5544 1,
5467- (width, height),5545+ (width, height), fctx,
5468 )5546 )
5469 .unwrap();5547 .unwrap();
5470 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);5548 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
@@ -5544,6 +5622,7 @@ mod tests {
5544 /// measured - 0.5 dB; byte ceiling = measured * 1.15).5622 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
5545 #[test]5623 #[test]
5546 fn real_clip_encodes_within_its_quality_and_size_budget() {5624 fn real_clip_encodes_within_its_quality_and_size_budget() {
5625+ let fctx = &crate::decode::FrameCtx::new();
5547 if !have_ffmpeg() {5626 if !have_ffmpeg() {
5548 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");5627 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
5549 return;5628 return;
@@ -5559,7 +5638,7 @@ mod tests {
5559 }5638 }
5560 let (width, height, frame_count) = (640usize, 384usize, 12usize);5639 let (width, height, frame_count) = (640usize, 384usize, 12usize);
5561 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);5640 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
5562- let encoded = encode_sequence(&source, 100, 0.5).unwrap();5641+ let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
5563 assert_eq!(encoded.frames.len(), frame_count);5642 assert_eq!(encoded.frames.len(), frame_count);
5564 5643
5565 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole5644 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
@@ -5604,6 +5683,7 @@ mod tests {
5604 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).5683 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
5605 #[test]5684 #[test]
5606 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {5685 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
5686+ let fctx = &crate::decode::FrameCtx::new();
5607 if !have_ffmpeg() {5687 if !have_ffmpeg() {
5608 eprintln!(5688 eprintln!(
5609 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \5689 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
@@ -5623,7 +5703,7 @@ mod tests {
5623 }5703 }
5624 let (width, height, frame_count) = (704usize, 400usize, 8usize);5704 let (width, height, frame_count) = (704usize, 400usize, 8usize);
5625 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);5705 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
5626- let encoded = encode_sequence(&source, 100, 0.5).unwrap();5706+ let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
5627 assert_eq!(encoded.frames.len(), frame_count);5707 assert_eq!(encoded.frames.len(), frame_count);
5628 5708
5629 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole5709 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
@@ -5660,13 +5740,14 @@ mod tests {
5660 #[test]5740 #[test]
5661 #[ignore = "a perf probe, not a gate"]5741 #[ignore = "a perf probe, not a gate"]
5662 fn sequence_bench_sanity() {5742 fn sequence_bench_sanity() {
5743+ let fctx = &crate::decode::FrameCtx::new();
5663 use std::time::Instant;5744 use std::time::Instant;
5664 let (width, height) = (1280usize, 720usize);5745 let (width, height) = (1280usize, 720usize);
5665 let pictures: Vec<Picture> = (0..24)5746 let pictures: Vec<Picture> = (0..24)
5666 .map(|i| panned_test_card(width, height, i * 3))5747 .map(|i| panned_test_card(width, height, i * 3))
5667 .collect();5748 .collect();
5668 let t = Instant::now();5749 let t = Instant::now();
5669- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();5750+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5670 let elapsed = t.elapsed();5751 let elapsed = t.elapsed();
5671 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();5752 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
5672 eprintln!(5753 eprintln!(
@@ -5682,6 +5763,7 @@ mod tests {
5682 #[test]5763 #[test]
5683 #[ignore = "a calibration probe, not a gate"]5764 #[ignore = "a calibration probe, not a gate"]
5684 fn calibration_sweep_base_q_idx() {5765 fn calibration_sweep_base_q_idx() {
5766+ let fctx = &crate::decode::FrameCtx::new();
5685 if !have_ffmpeg() {5767 if !have_ffmpeg() {
5686 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");5768 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
5687 return;5769 return;
@@ -5701,7 +5783,7 @@ mod tests {
5701 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);5783 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
5702 eprintln!("--- {clip} ---");5784 eprintln!("--- {clip} ---");
5703 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {5785 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
5704- let encoded = encode_sequence(&source, q, 0.5).unwrap();5786+ let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
5705 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);5787 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
5706 let mean_psnr: f64 = decoded5788 let mean_psnr: f64 = decoded
5707 .iter()5789 .iter()
crates/ec-av1/src/encoder.rsmodified+16 -0
@@ -221,8 +221,21 @@ pub struct Av1Encoder {
221 /// otherwise every picture is coded at `config.base_q_idx`, unchanged221 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
222 /// from before this field existed.222 /// from before this field existed.
223 rate_loop: Option<RateLoop>,223 rate_loop: Option<RateLoop>,
224+ /// This stream's decode-side per-frame state, owned here so `encode`
225+ /// keeps the public signature it had before the state stopped being
226+ /// thread-local. One per encoder, never per frame: several of its fields
227+ /// (the inter-frame inheritance guards) carry state ACROSS frames.
228+ fctx: crate::decode::FrameCtx,
224 }229 }
225 230
231+/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
232+/// `Send` but `!Sync`): it can move to another thread, it just cannot be
233+/// shared by reference across threads.
234+const _: fn() = || {
235+ fn assert_send<T: Send>() {}
236+ assert_send::<Av1Encoder>();
237+};
238+
226 impl Av1Encoder {239 impl Av1Encoder {
227 /// # Errors240 /// # Errors
228 /// Returns an error when `config.width`/`config.height` are zero, odd,241 /// Returns an error when `config.width`/`config.height` are zero, odd,
@@ -243,6 +256,7 @@ impl Av1Encoder {
243 reference: None,256 reference: None,
244 next_index: 0,257 next_index: 0,
245 rate_loop: None,258 rate_loop: None,
259+ fctx: crate::decode::FrameCtx::new(),
246 })260 })
247 }261 }
248 262
@@ -325,6 +339,7 @@ impl Av1Encoder {
325 split_blocks(),339 split_blocks(),
326 render,340 render,
327 self.color_config,341 self.color_config,
342+ &self.fctx,
328 )?343 )?
329 } else {344 } else {
330 let reference = self.reference.as_ref().ok_or_else(|| {345 let reference = self.reference.as_ref().ok_or_else(|| {
@@ -340,6 +355,7 @@ impl Av1Encoder {
340 DEADZONE,355 DEADZONE,
341 order as u32,356 order as u32,
342 render,357 render,
358+ &self.fctx,
343 )?359 )?
344 };360 };
345 361
crates/ec-av1/src/film_grain.rsmodified+45 -47
@@ -13,6 +13,7 @@
13 //! the frame it pushes onto its output `Vec<Picture>`, after saving the13 //! the frame it pushes onto its output `Vec<Picture>`, after saving the
14 //! clean decode into the reference slot bank.14 //! clean decode into the reference slot bank.
15 15
16+use crate::decode::WithRef;
16 use crate::encode::Picture;17 use crate::encode::Picture;
17 use ec_av1_syntax::FilmGrainParams;18 use ec_av1_syntax::FilmGrainParams;
18 19
@@ -43,23 +44,20 @@ const LUMA_BLOCK_W: i32 =
43 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;44 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
44 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;45 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
45 46
46-thread_local! {
47 /// `params->bit_depth` of the picture currently being grained. libaom47 /// `params->bit_depth` of the picture currently being grained. libaom
48 /// keeps `grain_min`/`grain_max` as file statics set once per48 /// keeps `grain_min`/`grain_max` as file statics set once per
49 /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors49 /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors
50 /// that rather than threading a parameter through every helper.50 /// that rather than threading a parameter through every helper.
51- static GRAIN_BIT_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(8) };
52-}
53 51
54 /// `params->bit_depth` for the [`apply_grain`] call in progress.52 /// `params->bit_depth` for the [`apply_grain`] call in progress.
55-fn grain_bit_depth() -> u32 {53+fn grain_bit_depth(fctx: &crate::decode::FrameCtx) -> u32 {
56- GRAIN_BIT_DEPTH.with(|c| c.get())54+ fctx.grain_bit_depth.with(|c| c.get())
57 }55 }
58 56
59 /// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`):57 /// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`):
60 /// `grain_center = 128 << (bit_depth - 8)`.58 /// `grain_center = 128 << (bit_depth - 8)`.
61-fn grain_range() -> (i32, i32) {59+fn grain_range(fctx: &crate::decode::FrameCtx) -> (i32, i32) {
62- let center = 128i32 << (grain_bit_depth() - 8);60+ let center = 128i32 << (grain_bit_depth(fctx) - 8);
63 (-center, center - 1)61 (-center, center - 1)
64 }62 }
65 63
@@ -135,14 +133,14 @@ fn build_pred_pos(lag: i32, has_luma_avg: bool) -> Vec<(i32, i32, i32)> {
135 fn generate_luma_grain_block(133 fn generate_luma_grain_block(
136 fg: &FilmGrainParams,134 fg: &FilmGrainParams,
137 pred_pos: &[(i32, i32, i32)],135 pred_pos: &[(i32, i32, i32)],
138- rng: &mut Rng,136+ rng: &mut Rng, fctx: &crate::decode::FrameCtx,
139 ) -> Vec<i32> {137 ) -> Vec<i32> {
140- let (grain_min, grain_max) = grain_range();138+ let (grain_min, grain_max) = grain_range(fctx);
141 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];139 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
142 if fg.num_y_points == 0 {140 if fg.num_y_points == 0 {
143 return block;141 return block;
144 }142 }
145- let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;143+ let gauss_sec_shift = 12 - grain_bit_depth(fctx) as i32 + fg.grain_scale_shift as i32;
146 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;144 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
147 let rounding_offset = 1i32 << (ar_coeff_shift - 1);145 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
148 146
@@ -172,12 +170,12 @@ fn generate_chroma_grain_blocks(
172 fg: &FilmGrainParams,170 fg: &FilmGrainParams,
173 pred_pos: &[(i32, i32, i32)],171 pred_pos: &[(i32, i32, i32)],
174 luma_block: &[i32],172 luma_block: &[i32],
175- seed: u16,173+ seed: u16, fctx: &crate::decode::FrameCtx,
176 ) -> (Vec<i32>, Vec<i32>) {174 ) -> (Vec<i32>, Vec<i32>) {
177- let (grain_min, grain_max) = grain_range();175+ let (grain_min, grain_max) = grain_range(fctx);
178 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];176 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
179 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];177 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
180- let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;178+ let gauss_sec_shift = 12 - grain_bit_depth(fctx) as i32 + fg.grain_scale_shift as i32;
181 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;179 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
182 let rounding_offset = 1i32 << (ar_coeff_shift - 1);180 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
183 181
@@ -336,12 +334,12 @@ fn add_noise_to_block(
336 cg_row0: i32,334 cg_row0: i32,
337 cg_col0: i32,335 cg_col0: i32,
338 half_h: i32,336 half_h: i32,
339- half_w: i32,337+ half_w: i32, fctx: &crate::decode::FrameCtx,
340 ) {338 ) {
341 let y_stride = picture.width as i32;339 let y_stride = picture.width as i32;
342 let c_stride = (picture.width / 2) as i32;340 let c_stride = (picture.width / 2) as i32;
343 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;341 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
344- let bit_depth = grain_bit_depth();342+ let bit_depth = grain_bit_depth(fctx);
345 let bd_shift = bit_depth - 8;343 let bd_shift = bit_depth - 8;
346 // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp.344 // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp.
347 let index_max = (256i32 << bd_shift) - 1;345 let index_max = (256i32 << bd_shift) - 1;
@@ -700,9 +698,9 @@ fn ver_overlap_inplace(
700 right_row0: i32,698 right_row0: i32,
701 right_col0: i32,699 right_col0: i32,
702 width: i32,700 width: i32,
703- height: i32,701+ height: i32, fctx: &crate::decode::FrameCtx,
704 ) {702 ) {
705- let (grain_min, grain_max) = grain_range();703+ let (grain_min, grain_max) = grain_range(fctx);
706 for h in 0..height {704 for h in 0..height {
707 if width == 1 {705 if width == 1 {
708 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);706 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -750,9 +748,9 @@ fn hor_overlap_inplace(
750 bot_row0: i32,748 bot_row0: i32,
751 bot_col0: i32,749 bot_col0: i32,
752 width: i32,750 width: i32,
753- height: i32,751+ height: i32, fctx: &crate::decode::FrameCtx,
754 ) {752 ) {
755- let (grain_min, grain_max) = grain_range();753+ let (grain_min, grain_max) = grain_range(fctx);
756 if height == 1 {754 if height == 1 {
757 for w in 0..width {755 for w in 0..width {
758 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);756 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);
@@ -800,9 +798,9 @@ fn copy_area(
800 src_row0: i32,798 src_row0: i32,
801 src_col0: i32,799 src_col0: i32,
802 width: i32,800 width: i32,
803- height: i32,801+ height: i32, fctx: &crate::decode::FrameCtx,
804 ) {802 ) {
805- let (grain_min, grain_max) = grain_range();803+ let (grain_min, grain_max) = grain_range(fctx);
806 for h in 0..height {804 for h in 0..height {
807 for w in 0..width {805 for w in 0..width {
808 let v = at(src, src_stride, src_row0 + h, src_col0 + w);806 let v = at(src, src_stride, src_row0 + h, src_col0 + w);
@@ -830,13 +828,13 @@ pub(crate) fn apply_grain(
830 picture: &Picture,828 picture: &Picture,
831 fg: &FilmGrainParams,829 fg: &FilmGrainParams,
832 mc_identity: bool,830 mc_identity: bool,
833- bit_depth: u32,831+ bit_depth: u32, fctx: &crate::decode::FrameCtx,
834 ) -> Picture {832 ) -> Picture {
835 let mut out = picture.clone();833 let mut out = picture.clone();
836 if !fg.apply_grain {834 if !fg.apply_grain {
837 return out;835 return out;
838 }836 }
839- GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth));837+ fctx.grain_bit_depth.with(|c| c.set(bit_depth));
840 GRAIN_HITS.with(|c| c.set(c.get() + 1));838 GRAIN_HITS.with(|c| c.set(c.get() + 1));
841 let width = out.width as i32;839 let width = out.width as i32;
842 let height = out.height as i32;840 let height = out.height as i32;
@@ -848,9 +846,9 @@ pub(crate) fn apply_grain(
848 let pred_chroma = build_pred_pos(lag, fg.num_y_points > 0);846 let pred_chroma = build_pred_pos(lag, fg.num_y_points > 0);
849 847
850 let mut rng = Rng::raw(fg.grain_seed);848 let mut rng = Rng::raw(fg.grain_seed);
851- let luma_template = generate_luma_grain_block(fg, &pred_luma, &mut rng);849+ let luma_template = generate_luma_grain_block(fg, &pred_luma, &mut rng, fctx);
852 let (cb_template, cr_template) =850 let (cb_template, cr_template) =
853- generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed);851+ generate_chroma_grain_blocks(fg, &pred_chroma, &luma_template, fg.grain_seed, fctx);
854 852
855 let scaling_y = build_scaling_lut(853 let scaling_y = build_scaling_lut(
856 &fg.point_y_value,854 &fg.point_y_value,
@@ -874,7 +872,7 @@ pub(crate) fn apply_grain(
874 )872 )
875 };873 };
876 874
877- let expand_bd = grain_bit_depth();875+ let expand_bd = grain_bit_depth(fctx);
878 let scaling_y = expand_scaling_lut(&scaling_y, expand_bd);876 let scaling_y = expand_scaling_lut(&scaling_y, expand_bd);
879 let scaling_cb = expand_scaling_lut(&scaling_cb, expand_bd);877 let scaling_cb = expand_scaling_lut(&scaling_cb, expand_bd);
880 let scaling_cr = expand_scaling_lut(&scaling_cr, expand_bd);878 let scaling_cr = expand_scaling_lut(&scaling_cr, expand_bd);
@@ -914,7 +912,7 @@ pub(crate) fn apply_grain(
914 luma_off_y,912 luma_off_y,
915 luma_off_x,913 luma_off_x,
916 2,914 2,
917- h_count,915+ h_count, fctx,
918 );916 );
919 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);917 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
920 ver_overlap_inplace(918 ver_overlap_inplace(
@@ -927,7 +925,7 @@ pub(crate) fn apply_grain(
927 chroma_off_y,925 chroma_off_y,
928 chroma_off_x,926 chroma_off_x,
929 1,927 1,
930- hc_count,928+ hc_count, fctx,
931 );929 );
932 ver_overlap_inplace(930 ver_overlap_inplace(
933 &mut cr_col_buf,931 &mut cr_col_buf,
@@ -939,7 +937,7 @@ pub(crate) fn apply_grain(
939 chroma_off_y,937 chroma_off_y,
940 chroma_off_x,938 chroma_off_x,
941 1,939 1,
942- hc_count,940+ hc_count, fctx,
943 );941 );
944 942
945 let i = if y != 0 { 1 } else { 0 };943 let i = if y != 0 { 1 } else { 0 };
@@ -962,7 +960,7 @@ pub(crate) fn apply_grain(
962 i,960 i,
963 0,961 0,
964 (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i,962 (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i,
965- 1,963+ 1, fctx,
966 );964 );
967 }965 }
968 966
@@ -978,7 +976,7 @@ pub(crate) fn apply_grain(
978 0,976 0,
979 0,977 0,
980 2,978 2,
981- 2,979+ 2, fctx,
982 );980 );
983 hor_overlap_inplace(981 hor_overlap_inplace(
984 &mut cb_line_buf,982 &mut cb_line_buf,
@@ -990,7 +988,7 @@ pub(crate) fn apply_grain(
990 0,988 0,
991 0,989 0,
992 1,990 1,
993- 1,991+ 1, fctx,
994 );992 );
995 hor_overlap_inplace(993 hor_overlap_inplace(
996 &mut cr_line_buf,994 &mut cr_line_buf,
@@ -1002,7 +1000,7 @@ pub(crate) fn apply_grain(
1002 0,1000 0,
1003 0,1001 0,
1004 1,1002 1,
1005- 1,1003+ 1, fctx,
1006 );1004 );
1007 }1005 }
1008 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };1006 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
@@ -1018,7 +1016,7 @@ pub(crate) fn apply_grain(
1018 luma_off_y,1016 luma_off_y,
1019 luma_off_x + if x != 0 { 2 } else { 0 },1017 luma_off_x + if x != 0 { 2 } else { 0 },
1020 lw,1018 lw,
1021- 2,1019+ 2, fctx,
1022 );1020 );
1023 let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1);1021 let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1);
1024 hor_overlap_inplace(1022 hor_overlap_inplace(
@@ -1031,7 +1029,7 @@ pub(crate) fn apply_grain(
1031 chroma_off_y,1029 chroma_off_y,
1032 chroma_off_x + if x != 0 { 1 } else { 0 },1030 chroma_off_x + if x != 0 { 1 } else { 0 },
1033 cw,1031 cw,
1034- 1,1032+ 1, fctx,
1035 );1033 );
1036 hor_overlap_inplace(1034 hor_overlap_inplace(
1037 &mut cr_line_buf,1035 &mut cr_line_buf,
@@ -1043,7 +1041,7 @@ pub(crate) fn apply_grain(
1043 chroma_off_y,1041 chroma_off_y,
1044 chroma_off_x + if x != 0 { 1 } else { 0 },1042 chroma_off_x + if x != 0 { 1 } else { 0 },
1045 cw,1043 cw,
1046- 1,1044+ 1, fctx,
1047 );1045 );
1048 1046
1049 add_noise_to_block(1047 add_noise_to_block(
@@ -1065,7 +1063,7 @@ pub(crate) fn apply_grain(
1065 0,1063 0,
1066 x,1064 x,
1067 1,1065 1,
1068- (LUMA_SUBBLOCK >> 1).min(width / 2 - x),1066+ (LUMA_SUBBLOCK >> 1).min(width / 2 - x), fctx,
1069 );1067 );
1070 }1068 }
1071 1069
@@ -1090,7 +1088,7 @@ pub(crate) fn apply_grain(
1090 chroma_off_y + i,1088 chroma_off_y + i,
1091 chroma_off_x + j,1089 chroma_off_x + j,
1092 (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i,1090 (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i,
1093- (LUMA_SUBBLOCK >> 1).min(width / 2 - x) - j,1091+ (LUMA_SUBBLOCK >> 1).min(width / 2 - x) - j, fctx,
1094 );1092 );
1095 1093
1096 if overlap {1094 if overlap {
@@ -1105,7 +1103,7 @@ pub(crate) fn apply_grain(
1105 LUMA_SUBBLOCK,1103 LUMA_SUBBLOCK,
1106 0,1104 0,
1107 2,1105 2,
1108- 2,1106+ 2, fctx,
1109 );1107 );
1110 copy_area(1108 copy_area(
1111 &mut cb_line_buf,1109 &mut cb_line_buf,
@@ -1117,7 +1115,7 @@ pub(crate) fn apply_grain(
1117 CHROMA_SUBBLOCK,1115 CHROMA_SUBBLOCK,
1118 0,1116 0,
1119 1,1117 1,
1120- 1,1118+ 1, fctx,
1121 );1119 );
1122 copy_area(1120 copy_area(
1123 &mut cr_line_buf,1121 &mut cr_line_buf,
@@ -1129,7 +1127,7 @@ pub(crate) fn apply_grain(
1129 CHROMA_SUBBLOCK,1127 CHROMA_SUBBLOCK,
1130 0,1128 0,
1131 1,1129 1,
1132- 1,1130+ 1, fctx,
1133 );1131 );
1134 }1132 }
1135 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };1133 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
@@ -1146,7 +1144,7 @@ pub(crate) fn apply_grain(
1146 luma_off_y + LUMA_SUBBLOCK,1144 luma_off_y + LUMA_SUBBLOCK,
1147 luma_off_x + lcut,1145 luma_off_x + lcut,
1148 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,1146 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,
1149- 2,1147+ 2, fctx,
1150 );1148 );
1151 copy_area(1149 copy_area(
1152 &mut cb_line_buf,1150 &mut cb_line_buf,
@@ -1158,7 +1156,7 @@ pub(crate) fn apply_grain(
1158 chroma_off_y + CHROMA_SUBBLOCK,1156 chroma_off_y + CHROMA_SUBBLOCK,
1159 chroma_off_x + ccut,1157 chroma_off_x + ccut,
1160 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,1158 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1161- 1,1159+ 1, fctx,
1162 );1160 );
1163 copy_area(1161 copy_area(
1164 &mut cr_line_buf,1162 &mut cr_line_buf,
@@ -1170,7 +1168,7 @@ pub(crate) fn apply_grain(
1170 chroma_off_y + CHROMA_SUBBLOCK,1168 chroma_off_y + CHROMA_SUBBLOCK,
1171 chroma_off_x + ccut,1169 chroma_off_x + ccut,
1172 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,1170 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1173- 1,1171+ 1, fctx,
1174 );1172 );
1175 1173
1176 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));1174 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));
@@ -1184,7 +1182,7 @@ pub(crate) fn apply_grain(
1184 luma_off_y,1182 luma_off_y,
1185 luma_off_x + LUMA_SUBBLOCK,1183 luma_off_x + LUMA_SUBBLOCK,
1186 2,1184 2,
1187- h_count,1185+ h_count, fctx,
1188 );1186 );
1189 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);1187 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
1190 copy_area(1188 copy_area(
@@ -1197,7 +1195,7 @@ pub(crate) fn apply_grain(
1197 chroma_off_y,1195 chroma_off_y,
1198 chroma_off_x + CHROMA_SUBBLOCK,1196 chroma_off_x + CHROMA_SUBBLOCK,
1199 1,1197 1,
1200- hc_count,1198+ hc_count, fctx,
1201 );1199 );
1202 copy_area(1200 copy_area(
1203 &mut cr_col_buf,1201 &mut cr_col_buf,
@@ -1209,7 +1207,7 @@ pub(crate) fn apply_grain(
1209 chroma_off_y,1207 chroma_off_y,
1210 chroma_off_x + CHROMA_SUBBLOCK,1208 chroma_off_x + CHROMA_SUBBLOCK,
1211 1,1209 1,
1212- hc_count,1210+ hc_count, fctx,
1213 );1211 );
1214 }1212 }
1215 1213
crates/ec-av1/src/intra.rsmodified+27 -25
@@ -149,7 +149,7 @@ impl Edges {
149 left: Option<&[u16]>,149 left: Option<&[u16]>,
150 corner: Option<u16>,150 corner: Option<u16>,
151 bw: usize,151 bw: usize,
152- bh: usize,152+ bh: usize, fctx: &crate::decode::FrameCtx,
153 ) -> Self {153 ) -> Self {
154 let want = bw + bh;154 let want = bw + bh;
155 let extend = |samples: &[u16]| {155 let extend = |samples: &[u16]| {
@@ -166,7 +166,7 @@ impl Edges {
166 // comment block, lane-tiny r1; an earlier attempt at this fix used166 // comment block, lane-tiny r1; an earlier attempt at this fix used
167 // 127/129 for the corner instead and made a passing 16x16 fixture167 // 127/129 for the corner instead and made a passing 16x16 fixture
168 // regress, which is what caught the misreading).168 // regress, which is what caught the misreading).
169- let base = 1i32 << (crate::decode::bit_depth() - 1);169+ let base = 1i32 << (crate::decode::bit_depth(fctx) - 1);
170 let above_row = match (above, left) {170 let above_row = match (above, left) {
171 (Some(a), _) => extend(a),171 (Some(a), _) => extend(a),
172 (None, Some(l)) => vec![i32::from(l[0]); want],172 (None, Some(l)) => vec![i32::from(l[0]); want],
@@ -262,7 +262,7 @@ pub(crate) fn intra_edge_filter_hits() -> usize {
262 }262 }
263 263
264 #[allow(clippy::too_many_arguments)]264 #[allow(clippy::too_many_arguments)]
265-pub fn predict(265+pub(crate) fn predict(
266 mode: u8,266 mode: u8,
267 angle_delta: i32,267 angle_delta: i32,
268 above: Option<&[u16]>,268 above: Option<&[u16]>,
@@ -272,7 +272,7 @@ pub fn predict(
272 bh: usize,272 bh: usize,
273 enable_edge_filter: bool,273 enable_edge_filter: bool,
274 smooth_neighbor: bool,274 smooth_neighbor: bool,
275- dst: &mut [u16],275+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
276 ) {276 ) {
277 assert_eq!(dst.len(), bw * bh, "the destination is the block");277 assert_eq!(dst.len(), bw * bh, "the destination is the block");
278 match mode {278 match mode {
@@ -282,7 +282,7 @@ pub fn predict(
282 PAETH_PRED => PAETH_PRED_HITS.with(|c| c.set(c.get() + 1)),282 PAETH_PRED => PAETH_PRED_HITS.with(|c| c.set(c.get() + 1)),
283 _ => {}283 _ => {}
284 }284 }
285- let edges = Edges::build(above, left, corner, bw, bh);285+ let edges = Edges::build(above, left, corner, bw, bh, fctx);
286 let is_directional = matches!(286 let is_directional = matches!(
287 mode,287 mode,
288 V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED288 V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
@@ -306,7 +306,7 @@ pub fn predict(
306 smooth_neighbor,306 smooth_neighbor,
307 n_top,307 n_top,
308 n_left,308 n_left,
309- dst,309+ dst, fctx,
310 );310 );
311 return;311 return;
312 }312 }
@@ -323,7 +323,7 @@ pub fn predict(
323 let last_w = bw as i32 - 1;323 let last_w = bw as i32 - 1;
324 let last_h = bh as i32 - 1;324 let last_h = bh as i32 - 1;
325 let value = match mode {325 let value = match mode {
326- DC_PRED => dc(above, left, bw, bh),326+ DC_PRED => dc(above, left, bw, bh, fctx),
327 V_PRED => edges.above(c),327 V_PRED => edges.above(c),
328 H_PRED => edges.left(r),328 H_PRED => edges.left(r),
329 SMOOTH_PRED => round2(329 SMOOTH_PRED => round2(
@@ -346,7 +346,7 @@ pub fn predict(
346 PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),346 PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),
347 other => panic!("intra mode {other} is not one this module predicts"),347 other => panic!("intra mode {other} is not one this module predicts"),
348 };348 };
349- dst[row * bw + col] = value.clamp(0, crate::decode::sample_max()) as u16;349+ dst[row * bw + col] = value.clamp(0, crate::decode::sample_max(fctx)) as u16;
350 }350 }
351 }351 }
352 }352 }
@@ -463,7 +463,7 @@ fn filter_intra_edge(buf: &mut [i32], strength: i32) {
463 /// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between463 /// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between
464 /// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled464 /// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled
465 /// slot.465 /// slot.
466-fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {466+fn upsample_intra_edge(buf: &[i32], fctx: &crate::decode::FrameCtx) -> Vec<i32> {
467 let sz = buf.len() - 1;467 let sz = buf.len() - 1;
468 let mut inp = vec![0i32; sz + 3];468 let mut inp = vec![0i32; sz + 3];
469 inp[0] = buf[0];469 inp[0] = buf[0];
@@ -474,7 +474,7 @@ fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {
474 out[0] = inp[0];474 out[0] = inp[0];
475 for i in 0..sz {475 for i in 0..sz {
476 let s = -inp[i] + 9 * inp[i + 1] + 9 * inp[i + 2] - inp[i + 3];476 let s = -inp[i] + 9 * inp[i + 1] + 9 * inp[i + 2] - inp[i + 3];
477- out[2 * i + 1] = ((s + 8) >> 4).clamp(0, crate::decode::sample_max());477+ out[2 * i + 1] = ((s + 8) >> 4).clamp(0, crate::decode::sample_max(fctx));
478 out[2 * i + 2] = inp[i + 2];478 out[2 * i + 2] = inp[i + 2];
479 }479 }
480 out480 out
@@ -495,7 +495,7 @@ fn directional(
495 smooth_neighbor: bool,495 smooth_neighbor: bool,
496 n_top: usize,496 n_top: usize,
497 n_left: usize,497 n_left: usize,
498- dst: &mut [u16],498+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
499 ) {499 ) {
500 let (w, h) = (bw as i32, bh as i32);500 let (w, h) = (bw as i32, bh as i32);
501 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.501 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.
@@ -541,7 +541,7 @@ fn directional(
541 let above_up;541 let above_up;
542 let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above {542 let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above {
543 let n_px = (w + if need_right { h } else { 0 }) as usize;543 let n_px = (w + if need_right { h } else { 0 }) as usize;
544- above_up = upsample_intra_edge(&above[..=n_px]);544+ above_up = upsample_intra_edge(&above[..=n_px], fctx);
545 (&above_up, 2)545 (&above_up, 2)
546 } else {546 } else {
547 (&above, 1)547 (&above, 1)
@@ -549,7 +549,7 @@ fn directional(
549 let left_up;549 let left_up;
550 let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left {550 let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left {
551 let n_px = (h + if need_bottom { w } else { 0 }) as usize;551 let n_px = (h + if need_bottom { w } else { 0 }) as usize;
552- left_up = upsample_intra_edge(&left[..=n_px]);552+ left_up = upsample_intra_edge(&left[..=n_px], fctx);
553 (&left_up, 2)553 (&left_up, 2)
554 } else {554 } else {
555 (&left, 1)555 (&left, 1)
@@ -608,7 +608,7 @@ fn directional(
608 blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)608 blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)
609 }609 }
610 };610 };
611- dst[(row * w + col) as usize] = value.clamp(0, crate::decode::sample_max()) as u16;611+ dst[(row * w + col) as usize] = value.clamp(0, crate::decode::sample_max(fctx)) as u16;
612 }612 }
613 }613 }
614 }614 }
@@ -622,7 +622,7 @@ fn directional(
622 /// before `dc_predictor` averages, so a slice truncated short by the true622 /// before `dc_predictor` averages, so a slice truncated short by the true
623 /// frame edge must be extended by repetition here too, not averaged over its623 /// frame edge must be extended by repetition here too, not averaged over its
624 /// own shorter length.624 /// own shorter length.
625-fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize) -> i32 {625+fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> i32 {
626 // lane-perf4: the replication is only ever *summed*, never indexed, so626 // lane-perf4: the replication is only ever *summed*, never indexed, so
627 // the extended edge is a sum rather than the `Vec<u16>` it used to be627 // the extended edge is a sum rather than the `Vec<u16>` it used to be
628 // built as (two allocations per intra block, 0.9% of a 1080p decode's628 // built as (two allocations per intra block, 0.9% of a 1080p decode's
@@ -642,7 +642,7 @@ fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize) -> i32
642 let left = left.map(|l| extend(l, bh));642 let left = left.map(|l| extend(l, bh));
643 let average = |sum: u32, count: u32| ((sum + (count >> 1)) / count) as i32;643 let average = |sum: u32, count: u32| ((sum + (count >> 1)) / count) as i32;
644 match (above, left) {644 match (above, left) {
645- (None, None) => 1i32 << (crate::decode::bit_depth() - 1),645+ (None, None) => 1i32 << (crate::decode::bit_depth(fctx) - 1),
646 (Some(a), None) => average(a, bw as u32),646 (Some(a), None) => average(a, bw as u32),
647 (None, Some(l)) => average(l, bh as u32),647 (None, Some(l)) => average(l, bh as u32),
648 (Some(a), Some(l)) if bw == bh => {648 (Some(a), Some(l)) if bw == bh => {
@@ -772,19 +772,19 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4;
772 /// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4772 /// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4
773 /// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never773 /// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never
774 /// offers this mode past 32x32).774 /// offers this mode past 32x32).
775-pub fn predict_filter_intra(775+pub(crate) fn predict_filter_intra(
776 mode: usize,776 mode: usize,
777 above: Option<&[u16]>,777 above: Option<&[u16]>,
778 left: Option<&[u16]>,778 left: Option<&[u16]>,
779 corner: Option<u16>,779 corner: Option<u16>,
780 bw: usize,780 bw: usize,
781 bh: usize,781 bh: usize,
782- dst: &mut [u16],782+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
783 ) {783 ) {
784 assert_eq!(dst.len(), bw * bh, "the destination is the block");784 assert_eq!(dst.len(), bw * bh, "the destination is the block");
785 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");785 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
786 assert_eq!(bh % 2, 0, "filter intra patches are 2 high");786 assert_eq!(bh % 2, 0, "filter intra patches are 2 high");
787- let edges = Edges::build(above, left, corner, bw, bh);787+ let edges = Edges::build(above, left, corner, bw, bh, fctx);
788 let taps = &FILTER_INTRA_TAPS[mode];788 let taps = &FILTER_INTRA_TAPS[mode];
789 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the789 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
790 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).790 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).
@@ -812,7 +812,7 @@ pub fn predict_filter_intra(
812 for k in 0..8 {812 for k in 0..8 {
813 let (r_off, c_off) = (k >> 2, k & 3);813 let (r_off, c_off) = (k >> 2, k & 3);
814 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();814 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
815- let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max());815+ let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max(fctx));
816 let idx = (r + r_off) * (bw + 1) + c + c_off;816 let idx = (r + r_off) * (bw + 1) + c + c_off;
817 buffer[idx] = value;817 buffer[idx] = value;
818 }818 }
@@ -991,6 +991,7 @@ mod tests {
991 /// on three seeded random edges.991 /// on three seeded random edges.
992 #[test]992 #[test]
993 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {993 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {
994+ let fctx = &crate::decode::FrameCtx::new();
994 // xorshift64*: a seeded stream, so a failure names one (shape, mode,995 // xorshift64*: a seeded stream, so a failure names one (shape, mode,
995 // seed) triple that reproduces.996 // seed) triple that reproduces.
996 let mut rng = |state: &mut u64| {997 let mut rng = |state: &mut u64| {
@@ -1017,7 +1018,7 @@ mod tests {
1017 ];1018 ];
1018 let mut compared = 0u32;1019 let mut compared = 0u32;
1019 for bd in [8u32, 10] {1020 for bd in [8u32, 10] {
1020- crate::decode::set_bit_depth(bd as u8);1021+ crate::decode::set_bit_depth(bd as u8, fctx);
1021 let max = (1u32 << bd) - 1;1022 let max = (1u32 << bd) - 1;
1022 for &(bw, bh) in &shapes {1023 for &(bw, bh) in &shapes {
1023 for mode in 0..5usize {1024 for mode in 0..5usize {
@@ -1044,7 +1045,7 @@ mod tests {
1044 Some(corner),1045 Some(corner),
1045 bw,1046 bw,
1046 bh,1047 bh,
1047- &mut got,1048+ &mut got, fctx,
1048 );1049 );
1049 assert_eq!(1050 assert_eq!(
1050 got, want,1051 got, want,
@@ -1055,7 +1056,7 @@ mod tests {
1055 }1056 }
1056 }1057 }
1057 }1058 }
1058- crate::decode::set_bit_depth(8);1059+ crate::decode::set_bit_depth(8, fctx);
1059 assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared");1060 assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared");
1060 }1061 }
1061 1062
@@ -1068,6 +1069,7 @@ mod tests {
1068 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).1069 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).
1069 #[test]1070 #[test]
1070 fn rect_predictors_match_c_dump() {1071 fn rect_predictors_match_c_dump() {
1072+ let fctx = &crate::decode::FrameCtx::new();
1071 let expected_txt = std::fs::read_to_string(concat!(1073 let expected_txt = std::fs::read_to_string(concat!(
1072 env!("CARGO_MANIFEST_DIR"),1074 env!("CARGO_MANIFEST_DIR"),
1073 "/../../lanes/intrarect_dump.expected.txt"1075 "/../../lanes/intrarect_dump.expected.txt"
@@ -1156,7 +1158,7 @@ mod tests {
1156 bh,1158 bh,
1157 false,1159 false,
1158 false,1160 false,
1159- &mut dst,1161+ &mut dst, fctx,
1160 );1162 );
1161 let got = if name == "DC" {1163 let got = if name == "DC" {
1162 u64::from(dst[0])1164 u64::from(dst[0])
@@ -1184,7 +1186,7 @@ mod tests {
1184 bh,1186 bh,
1185 ef,1187 ef,
1186 sn,1188 sn,
1187- &mut dst,1189+ &mut dst, fctx,
1188 );1190 );
1189 let got = checksum(&dst);1191 let got = checksum(&dst);
1190 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));1192 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));
crates/ec-av1/src/mc.rsmodified+49 -41
@@ -663,7 +663,7 @@ fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i32], &mut
663 /// Panics when `dst` is not `block_w * block_h` long, or the reference is663 /// Panics when `dst` is not `block_w * block_h` long, or the reference is
664 /// empty.664 /// empty.
665 #[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape665 #[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
666-pub fn predict(666+pub(crate) fn predict(
667 reference: &[u16],667 reference: &[u16],
668 stride: usize,668 stride: usize,
669 true_width: usize,669 true_width: usize,
@@ -672,7 +672,7 @@ pub fn predict(
672 y_q4: i32,672 y_q4: i32,
673 block_w: usize,673 block_w: usize,
674 block_h: usize,674 block_h: usize,
675- dst: &mut [u16],675+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
676 ) {676 ) {
677 predict_with_filter(677 predict_with_filter(
678 reference,678 reference,
@@ -684,7 +684,7 @@ pub fn predict(
684 block_w,684 block_w,
685 block_h,685 block_h,
686 InterpFilterKind::Regular,686 InterpFilterKind::Regular,
687- dst,687+ dst, fctx,
688 );688 );
689 }689 }
690 690
@@ -692,7 +692,7 @@ pub fn predict(
692 /// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same692 /// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
693 /// kernel both directions.693 /// kernel both directions.
694 #[allow(clippy::too_many_arguments)]694 #[allow(clippy::too_many_arguments)]
695-pub fn predict_with_filter(695+pub(crate) fn predict_with_filter(
696 reference: &[u16],696 reference: &[u16],
697 stride: usize,697 stride: usize,
698 true_width: usize,698 true_width: usize,
@@ -702,7 +702,7 @@ pub fn predict_with_filter(
702 block_w: usize,702 block_w: usize,
703 block_h: usize,703 block_h: usize,
704 filter_kind: InterpFilterKind,704 filter_kind: InterpFilterKind,
705- dst: &mut [u16],705+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
706 ) {706 ) {
707 predict_with_filters(707 predict_with_filters(
708 reference,708 reference,
@@ -715,7 +715,7 @@ pub fn predict_with_filter(
715 block_h,715 block_h,
716 filter_kind,716 filter_kind,
717 filter_kind,717 filter_kind,
718- dst,718+ dst, fctx,
719 );719 );
720 }720 }
721 721
@@ -724,7 +724,7 @@ pub fn predict_with_filter(
724 /// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),724 /// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
725 /// so the two passes can genuinely differ.725 /// so the two passes can genuinely differ.
726 #[allow(clippy::too_many_arguments)]726 #[allow(clippy::too_many_arguments)]
727-pub fn predict_with_filters(727+pub(crate) fn predict_with_filters(
728 reference: &[u16],728 reference: &[u16],
729 stride: usize,729 stride: usize,
730 true_width: usize,730 true_width: usize,
@@ -735,11 +735,11 @@ pub fn predict_with_filters(
735 block_h: usize,735 block_h: usize,
736 h_kind: InterpFilterKind,736 h_kind: InterpFilterKind,
737 v_kind: InterpFilterKind,737 v_kind: InterpFilterKind,
738- dst: &mut [u16],738+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
739 ) {739 ) {
740 predict_with_filters_kern(740 predict_with_filters_kern(
741 reference, stride, true_width, true_height, x_q4, y_q4, block_w,741 reference, stride, true_width, true_height, x_q4, y_q4, block_w,
742- block_h, block_w, block_h, h_kind, v_kind, dst,742+ block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
743 );743 );
744 }744 }
745 745
@@ -752,7 +752,7 @@ pub fn predict_with_filters(
752 /// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask752 /// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask
753 /// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.753 /// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.
754 #[allow(clippy::too_many_arguments)]754 #[allow(clippy::too_many_arguments)]
755-pub fn predict_with_filters_kern(755+pub(crate) fn predict_with_filters_kern(
756 reference: &[u16],756 reference: &[u16],
757 stride: usize,757 stride: usize,
758 true_width: usize,758 true_width: usize,
@@ -765,7 +765,7 @@ pub fn predict_with_filters_kern(
765 kern_h: usize,765 kern_h: usize,
766 h_kind: InterpFilterKind,766 h_kind: InterpFilterKind,
767 v_kind: InterpFilterKind,767 v_kind: InterpFilterKind,
768- dst: &mut [u16],768+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
769 ) {769 ) {
770 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");770 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
771 assert!(!reference.is_empty(), "a reference plane has samples");771 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -839,7 +839,7 @@ pub fn predict_with_filters_kern(
839 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the839 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
840 // block's own first row where the pass would have put the 4th.840 // block's own first row where the pass would have put the 4th.
841 let rows = if yfrac == 0 { block_h } else { block_h + 7 };841 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
842- let max = crate::decode::sample_max();842+ let max = crate::decode::sample_max(fctx);
843 with_scratch(rows, block_w, |intermediate, acc| {843 with_scratch(rows, block_w, |intermediate, acc| {
844 horizontal_pass_unscaled(844 horizontal_pass_unscaled(
845 reference, stride, true_width, true_height, x0,845 reference, stride, true_width, true_height, x0,
@@ -1070,7 +1070,7 @@ fn horizontal_pass(
1070 /// Panics when `dst` is not `block_w * block_h` long, or the reference is1070 /// Panics when `dst` is not `block_w * block_h` long, or the reference is
1071 /// empty.1071 /// empty.
1072 #[allow(clippy::too_many_arguments)]1072 #[allow(clippy::too_many_arguments)]
1073-pub fn predict_scaled(1073+pub(crate) fn predict_scaled(
1074 reference: &[u16],1074 reference: &[u16],
1075 stride: usize,1075 stride: usize,
1076 true_width: usize,1076 true_width: usize,
@@ -1082,18 +1082,18 @@ pub fn predict_scaled(
1082 block_h: usize,1082 block_h: usize,
1083 h_kind: InterpFilterKind,1083 h_kind: InterpFilterKind,
1084 v_kind: InterpFilterKind,1084 v_kind: InterpFilterKind,
1085- dst: &mut [u16],1085+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1086 ) {1086 ) {
1087 predict_scaled_kern(1087 predict_scaled_kern(
1088 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,1088 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1089- block_w, block_h, block_w, block_h, h_kind, v_kind, dst,1089+ block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1090 );1090 );
1091 }1091 }
1092 1092
1093 /// [`predict_scaled`] with the 4-tap decision from the block's true dims1093 /// [`predict_scaled`] with the 4-tap decision from the block's true dims
1094 /// (see [`predict_with_filters_kern`]).1094 /// (see [`predict_with_filters_kern`]).
1095 #[allow(clippy::too_many_arguments)]1095 #[allow(clippy::too_many_arguments)]
1096-pub fn predict_scaled_kern(1096+pub(crate) fn predict_scaled_kern(
1097 reference: &[u16],1097 reference: &[u16],
1098 stride: usize,1098 stride: usize,
1099 true_width: usize,1099 true_width: usize,
@@ -1107,7 +1107,7 @@ pub fn predict_scaled_kern(
1107 kern_h: usize,1107 kern_h: usize,
1108 h_kind: InterpFilterKind,1108 h_kind: InterpFilterKind,
1109 v_kind: InterpFilterKind,1109 v_kind: InterpFilterKind,
1110- dst: &mut [u16],1110+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1111 ) {1111 ) {
1112 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");1112 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1113 assert!(!reference.is_empty(), "a reference plane has samples");1113 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1129,7 +1129,7 @@ pub fn predict_scaled_kern(
1129 };1129 };
1130 1130
1131 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1131 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1132- let max = crate::decode::sample_max();1132+ let max = crate::decode::sample_max(fctx);
1133 with_scratch(rows, block_w, |intermediate, acc| {1133 with_scratch(rows, block_w, |intermediate, acc| {
1134 horizontal_pass(1134 horizontal_pass(
1135 reference, stride, true_width, true_height, x_q4,1135 reference, stride, true_width, true_height, x_q4,
@@ -1156,7 +1156,7 @@ pub fn predict_scaled_kern(
1156 /// scaled (superres). `REF_NO_SCALE` takes the ordinary stride-1 path, which1156 /// scaled (superres). `REF_NO_SCALE` takes the ordinary stride-1 path, which
1157 /// keeps [`predict_scaled_hits`] a true count of scaled predictions.1157 /// keeps [`predict_scaled_hits`] a true count of scaled predictions.
1158 #[allow(clippy::too_many_arguments)]1158 #[allow(clippy::too_many_arguments)]
1159-pub fn predict_maybe_scaled(1159+pub(crate) fn predict_maybe_scaled(
1160 reference: &[u16],1160 reference: &[u16],
1161 stride: usize,1161 stride: usize,
1162 true_width: usize,1162 true_width: usize,
@@ -1168,17 +1168,17 @@ pub fn predict_maybe_scaled(
1168 block_h: usize,1168 block_h: usize,
1169 h_kind: InterpFilterKind,1169 h_kind: InterpFilterKind,
1170 v_kind: InterpFilterKind,1170 v_kind: InterpFilterKind,
1171- dst: &mut [u16],1171+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1172 ) {1172 ) {
1173 if x_scale_fp == REF_NO_SCALE {1173 if x_scale_fp == REF_NO_SCALE {
1174 predict_with_filters(1174 predict_with_filters(
1175 reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,1175 reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,
1176- v_kind, dst,1176+ v_kind, dst, fctx,
1177 );1177 );
1178 } else {1178 } else {
1179 predict_scaled(1179 predict_scaled(
1180 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,1180 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,
1181- block_h, h_kind, v_kind, dst,1181+ block_h, h_kind, v_kind, dst, fctx,
1182 );1182 );
1183 }1183 }
1184 }1184 }
@@ -1305,12 +1305,12 @@ pub fn predict_compound_intermediate_kern(
1305 /// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound1305 /// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
1306 /// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this1306 /// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
1307 /// function does not cover -- decode.rs still refuses those by name.1307 /// function does not cover -- decode.rs still refuses those by name.
1308-pub fn combine_compound(1308+pub(crate) fn combine_compound(
1309 pred0: &[i32],1309 pred0: &[i32],
1310 pred1: &[i32],1310 pred1: &[i32],
1311 fwd_weight: i32,1311 fwd_weight: i32,
1312 bck_weight: i32,1312 bck_weight: i32,
1313- dst: &mut [u16],1313+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1314 ) {1314 ) {
1315 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");1315 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1316 assert_eq!(dst.len(), pred0.len(), "the destination is the block");1316 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
@@ -1324,7 +1324,7 @@ pub fn combine_compound(
1324 // dropped low 4 bits are non-zero.1324 // dropped low 4 bits are non-zero.
1325 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;1325 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1326 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)1326 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
1327- .clamp(0, crate::decode::sample_max()) as u16;1327+ .clamp(0, crate::decode::sample_max(fctx)) as u16;
1328 }1328 }
1329 }1329 }
1330 1330
@@ -1338,7 +1338,7 @@ pub fn combine_compound(
1338 /// produces give the identical `diff` libaom computes. `round` is1338 /// produces give the identical `diff` libaom computes. `round` is
1339 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for1339 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
1340 /// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).1340 /// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
1341-pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {1341+pub(crate) fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) {
1342 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");1342 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1343 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");1343 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
1344 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS1344 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
@@ -1346,7 +1346,7 @@ pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {
1346 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`1346 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
1347 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s1347 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
1348 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.1348 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
1349- let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth()).saturating_sub(8);1349+ let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
1350 for i in 0..mask.len() {1350 for i in 0..mask.len() {
1351 let diff = round2((pred0[i] - pred1[i]).abs(), round);1351 let diff = round2((pred0[i] - pred1[i]).abs(), round);
1352 let m = (38 + diff / 16).clamp(0, 64);1352 let m = (38 + diff / 16).clamp(0, 64);
@@ -1365,7 +1365,7 @@ pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {
1365 /// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /1365 /// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /
1366 /// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.1366 /// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.
1367 #[allow(clippy::too_many_arguments)]1367 #[allow(clippy::too_many_arguments)]
1368-pub fn blend_masked_compound(1368+pub(crate) fn blend_masked_compound(
1369 pred0: &[i32],1369 pred0: &[i32],
1370 pred1: &[i32],1370 pred1: &[i32],
1371 mask: &[u8],1371 mask: &[u8],
@@ -1373,7 +1373,7 @@ pub fn blend_masked_compound(
1373 w: usize,1373 w: usize,
1374 h: usize,1374 h: usize,
1375 subsampled: bool,1375 subsampled: bool,
1376- dst: &mut [u16],1376+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1377 ) {1377 ) {
1378 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");1378 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
1379 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");1379 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
@@ -1393,7 +1393,7 @@ pub fn blend_masked_compound(
1393 i32::from(mask[i * mask_stride + j])1393 i32::from(mask[i * mask_stride + j])
1394 };1394 };
1395 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;1395 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
1396- dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max()) as u16;1396+ dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max(fctx)) as u16;
1397 }1397 }
1398 }1398 }
1399 }1399 }
@@ -1409,6 +1409,7 @@ pub fn blend_masked_compound(
1409 /// off-by-one from double rounding.1409 /// off-by-one from double rounding.
1410 #[test]1410 #[test]
1411 fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {1411 fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1412+ let fctx = &crate::decode::FrameCtx::new();
1412 let reference = vec![100u16; 16 * 16];1413 let reference = vec![100u16; 16 * 16];
1413 let mut pred0 = vec![0i32; 16];1414 let mut pred0 = vec![0i32; 16];
1414 predict_compound_intermediate(1415 predict_compound_intermediate(
@@ -1429,7 +1430,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1429 1430
1430 let pred1 = pred0.clone();1431 let pred1 = pred0.clone();
1431 let mut dst = vec![0u16; 16];1432 let mut dst = vec![0u16; 16];
1432- combine_compound(&pred0, &pred1, 8, 8, &mut dst);1433+ combine_compound(&pred0, &pred1, 8, 8, &mut dst, fctx);
1433 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");1434 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
1434 }1435 }
1435 1436
@@ -1450,6 +1451,7 @@ mod tests {
1450 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.1451 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
1451 #[test]1452 #[test]
1452 fn smooth_filter_matches_aomdec_chroma_inter_block() {1453 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1454+ let fctx = &crate::decode::FrameCtx::new();
1453 #[rustfmt::skip]1455 #[rustfmt::skip]
1454 let window: [[u8; 24]; 24] = [1456 let window: [[u8; 24]; 24] = [
1455 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],1457 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
@@ -1508,7 +1510,7 @@ mod tests {
1508 16,1510 16,
1509 16,1511 16,
1510 InterpFilterKind::Smooth,1512 InterpFilterKind::Smooth,
1511- &mut dst,1513+ &mut dst, fctx,
1512 );1514 );
1513 #[rustfmt::skip]1515 #[rustfmt::skip]
1514 let expected_row0: [u16; 16] =1516 let expected_row0: [u16; 16] =
@@ -1559,6 +1561,7 @@ mod tests {
1559 1561
1560 #[test]1562 #[test]
1561 fn integer_mv_is_identity() {1563 fn integer_mv_is_identity() {
1564+ let fctx = &crate::decode::FrameCtx::new();
1562 let width = 12;1565 let width = 12;
1563 let height = 12;1566 let height = 12;
1564 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();1567 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
@@ -1572,7 +1575,7 @@ mod tests {
1572 4 * 16,1575 4 * 16,
1573 6,1576 6,
1574 6,1577 6,
1575- &mut dst,1578+ &mut dst, fctx,
1576 );1579 );
1577 for row in 0..6 {1580 for row in 0..6 {
1578 for col in 0..6 {1581 for col in 0..6 {
@@ -1587,6 +1590,7 @@ mod tests {
1587 1590
1588 #[test]1591 #[test]
1589 fn half_pel_reproduces_the_ramp_midpoint() {1592 fn half_pel_reproduces_the_ramp_midpoint() {
1593+ let fctx = &crate::decode::FrameCtx::new();
1590 // Step 2 so every half-pel position lands on an exact integer.1594 // Step 2 so every half-pel position lands on an exact integer.
1591 let width = 16;1595 let width = 16;
1592 let height = 16;1596 let height = 16;
@@ -1604,7 +1608,7 @@ mod tests {
1604 5 * 16,1608 5 * 16,
1605 4,1609 4,
1606 4,1610 4,
1607- &mut dst,1611+ &mut dst, fctx,
1608 );1612 );
1609 for row in 0..4 {1613 for row in 0..4 {
1610 for col in 0..4 {1614 for col in 0..4 {
@@ -1620,6 +1624,7 @@ mod tests {
1620 1624
1621 #[test]1625 #[test]
1622 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {1626 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
1627+ let fctx = &crate::decode::FrameCtx::new();
1623 let width = 20;1628 let width = 20;
1624 let height = 20;1629 let height = 20;
1625 let reference = vec![142u16; width * height];1630 let reference = vec![142u16; width * height];
@@ -1635,7 +1640,7 @@ mod tests {
1635 5 * 16 + yfrac,1640 5 * 16 + yfrac,
1636 5,1641 5,
1637 5,1642 5,
1638- &mut dst,1643+ &mut dst, fctx,
1639 );1644 );
1640 assert!(1645 assert!(
1641 dst.iter().all(|&v| v == 142),1646 dst.iter().all(|&v| v == 142),
@@ -1647,6 +1652,7 @@ mod tests {
1647 1652
1648 #[test]1653 #[test]
1649 fn horizontal_and_vertical_only_filtering_differ() {1654 fn horizontal_and_vertical_only_filtering_differ() {
1655+ let fctx = &crate::decode::FrameCtx::new();
1650 // A plane linear in both x and y with different, even coefficients so1656 // A plane linear in both x and y with different, even coefficients so
1651 // each axis's half-pel interpolation lands on an exact integer: this1657 // each axis's half-pel interpolation lands on an exact integer: this
1652 // pins the actual value each pass produces, not just that the two1658 // pins the actual value each pass produces, not just that the two
@@ -1668,7 +1674,7 @@ mod tests {
1668 3 * 16,1674 3 * 16,
1669 4,1675 4,
1670 4,1676 4,
1671- &mut horiz,1677+ &mut horiz, fctx,
1672 );1678 );
1673 let mut vert = vec![0u16; 4 * 4];1679 let mut vert = vec![0u16; 4 * 4];
1674 predict(1680 predict(
@@ -1680,7 +1686,7 @@ mod tests {
1680 3 * 16 + 8,1686 3 * 16 + 8,
1681 4,1687 4,
1682 4,1688 4,
1683- &mut vert,1689+ &mut vert, fctx,
1684 );1690 );
1685 1691
1686 for row in 0..4 {1692 for row in 0..4 {
@@ -1707,6 +1713,7 @@ mod tests {
1707 1713
1708 #[test]1714 #[test]
1709 fn mv_past_the_edge_clamps_instead_of_panicking() {1715 fn mv_past_the_edge_clamps_instead_of_panicking() {
1716+ let fctx = &crate::decode::FrameCtx::new();
1710 let width = 8;1717 let width = 8;
1711 let height = 8;1718 let height = 8;
1712 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();1719 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
@@ -1722,7 +1729,7 @@ mod tests {
1722 -50 * 16 + 5,1729 -50 * 16 + 5,
1723 4,1730 4,
1724 4,1731 4,
1725- &mut dst,1732+ &mut dst, fctx,
1726 );1733 );
1727 let expected = reference[0]; // the whole plane clamps to the top-left corner1734 let expected = reference[0]; // the whole plane clamps to the top-left corner
1728 assert!(1735 assert!(
@@ -1740,7 +1747,7 @@ mod tests {
1740 50 * 16 + 5,1747 50 * 16 + 5,
1741 4,1748 4,
1742 4,1749 4,
1743- &mut dst2,1750+ &mut dst2, fctx,
1744 );1751 );
1745 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner1752 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
1746 assert!(1753 assert!(
@@ -1751,6 +1758,7 @@ mod tests {
1751 1758
1752 #[test]1759 #[test]
1753 fn predict_scaled_at_no_scale_matches_predict_with_filters() {1760 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
1761+ let fctx = &crate::decode::FrameCtx::new();
1754 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE1762 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
1755 // must reduce predict_scaled's per-column scaled walk to the exact1763 // must reduce predict_scaled's per-column scaled walk to the exact
1756 // same int_pel/filter_idx sequence predict_with_filters computes from1764 // same int_pel/filter_idx sequence predict_with_filters computes from
@@ -1774,7 +1782,7 @@ mod tests {
1774 8,1782 8,
1775 InterpFilterKind::Regular,1783 InterpFilterKind::Regular,
1776 InterpFilterKind::Regular,1784 InterpFilterKind::Regular,
1777- &mut expected,1785+ &mut expected, fctx,
1778 );1786 );
1779 let mut got = vec![0u16; block_w * 8];1787 let mut got = vec![0u16; block_w * 8];
1780 predict_scaled(1788 predict_scaled(
@@ -1789,7 +1797,7 @@ mod tests {
1789 8,1797 8,
1790 InterpFilterKind::Regular,1798 InterpFilterKind::Regular,
1791 InterpFilterKind::Regular,1799 InterpFilterKind::Regular,
1792- &mut got,1800+ &mut got, fctx,
1793 );1801 );
1794 assert_eq!(1802 assert_eq!(
1795 got, expected,1803 got, expected,
crates/ec-av1/src/motion.rsmodified+15 -11
@@ -189,7 +189,7 @@ pub struct MotionSearch {
189 /// Panics when `source` is not `block_w * block_h` long, or `reference` is189 /// Panics when `source` is not `block_w * block_h` long, or `reference` is
190 /// empty (the same contracts [`predict`] has).190 /// empty (the same contracts [`predict`] has).
191 #[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor191 #[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
192-pub fn search(192+pub(crate) fn search(
193 reference: &[u8],193 reference: &[u8],
194 stride: usize,194 stride: usize,
195 ref_width: usize,195 ref_width: usize,
@@ -200,11 +200,11 @@ pub fn search(
200 block_w: usize,200 block_w: usize,
201 block_h: usize,201 block_h: usize,
202 pred_mv: (i32, i32),202 pred_mv: (i32, i32),
203- lambda: f64,203+ lambda: f64, fctx: &crate::decode::FrameCtx,
204 ) -> MotionSearch {204 ) -> MotionSearch {
205 let (result, _trace) = search_traced(205 let (result, _trace) = search_traced(
206 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,206 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
207- pred_mv, lambda,207+ pred_mv, lambda, fctx,
208 );208 );
209 result209 result
210 }210 }
@@ -224,7 +224,7 @@ fn search_traced(
224 block_w: usize,224 block_w: usize,
225 block_h: usize,225 block_h: usize,
226 pred_mv: (i32, i32),226 pred_mv: (i32, i32),
227- lambda: f64,227+ lambda: f64, fctx: &crate::decode::FrameCtx,
228 ) -> (MotionSearch, Vec<f64>) {228 ) -> (MotionSearch, Vec<f64>) {
229 search_traced_from_step(229 search_traced_from_step(
230 reference,230 reference,
@@ -238,7 +238,7 @@ fn search_traced(
238 block_h,238 block_h,
239 pred_mv,239 pred_mv,
240 lambda,240 lambda,
241- SEARCH_INITIAL_STEP_PEL,241+ SEARCH_INITIAL_STEP_PEL, fctx,
242 )242 )
243 }243 }
244 244
@@ -258,7 +258,7 @@ fn search_traced_from_step(
258 block_h: usize,258 block_h: usize,
259 pred_mv: (i32, i32),259 pred_mv: (i32, i32),
260 lambda: f64,260 lambda: f64,
261- initial_step_pel: i32,261+ initial_step_pel: i32, fctx: &crate::decode::FrameCtx,
262 ) -> (MotionSearch, Vec<f64>) {262 ) -> (MotionSearch, Vec<f64>) {
263 assert_eq!(source.len(), block_w * block_h, "source is one block");263 assert_eq!(source.len(), block_w * block_h, "source is one block");
264 assert!(!reference.is_empty(), "a reference plane has samples");264 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -274,7 +274,7 @@ fn search_traced_from_step(
274 let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;274 let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
275 predict(275 predict(
276 &reference16, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h,276 &reference16, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h,
277- &mut dst16,277+ &mut dst16, fctx,
278 );278 );
279 let sad: f64 = source279 let sad: f64 = source
280 .iter()280 .iter()
@@ -401,6 +401,7 @@ mod tests {
401 401
402 #[test]402 #[test]
403 fn finds_exact_integer_translation_all_four_signs() {403 fn finds_exact_integer_translation_all_four_signs() {
404+ let fctx = &crate::decode::FrameCtx::new();
404 let width = 64;405 let width = 64;
405 let height = 64;406 let height = 64;
406 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);407 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -442,7 +443,7 @@ mod tests {
442 block_w,443 block_w,
443 block_h,444 block_h,
444 (0, 0),445 (0, 0),
445- 0.1,446+ 0.1, fctx,
446 );447 );
447 assert_eq!(448 assert_eq!(
448 result.mv,449 result.mv,
@@ -454,6 +455,7 @@ mod tests {
454 455
455 #[test]456 #[test]
456 fn finds_half_pel_translation() {457 fn finds_half_pel_translation() {
458+ let fctx = &crate::decode::FrameCtx::new();
457 // A ramp, doubled, so every half-pel position lands on an exact459 // A ramp, doubled, so every half-pel position lands on an exact
458 // integer average of its two neighbours.460 // integer average of its two neighbours.
459 let width = 40;461 let width = 40;
@@ -489,7 +491,7 @@ mod tests {
489 block_w,491 block_w,
490 block_h,492 block_h,
491 (0, 0),493 (0, 0),
492- 0.1,494+ 0.1, fctx,
493 );495 );
494 assert_eq!(496 assert_eq!(
495 result.mv,497 result.mv,
@@ -500,6 +502,7 @@ mod tests {
500 502
501 #[test]503 #[test]
502 fn cost_is_monotone_non_increasing_over_the_search() {504 fn cost_is_monotone_non_increasing_over_the_search() {
505+ let fctx = &crate::decode::FrameCtx::new();
503 let width = 48;506 let width = 48;
504 let height = 48;507 let height = 48;
505 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);508 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -525,7 +528,7 @@ mod tests {
525 block_w,528 block_w,
526 block_h,529 block_h,
527 (0, 0),530 (0, 0),
528- 0.1,531+ 0.1, fctx,
529 );532 );
530 assert!(trace.len() > 1, "the search must run more than one round");533 assert!(trace.len() > 1, "the search must run more than one round");
531 for pair in trace.windows(2) {534 for pair in trace.windows(2) {
@@ -559,6 +562,7 @@ mod tests {
559 /// lands.562 /// lands.
560 #[test]563 #[test]
561 fn sweep_initial_step() {564 fn sweep_initial_step() {
565+ let fctx = &crate::decode::FrameCtx::new();
562 let width = 96;566 let width = 96;
563 let height = 96;567 let height = 96;
564 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);568 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -593,7 +597,7 @@ mod tests {
593 block_h,597 block_h,
594 (0, 0),598 (0, 0),
595 0.1,599 0.1,
596- candidate_step,600+ candidate_step, fctx,
597 );601 );
598 // Every round the trace recorded is 8 neighbour evaluations,602 // Every round the trace recorded is 8 neighbour evaluations,
599 // the actual cost this starting step spent on this block.603 // the actual cost this starting step spent on this block.
crates/ec-av1/src/mvstack.rsmodified+2 -2
@@ -695,8 +695,8 @@ fn top_right_scan_allowed(bw4: usize, bh4: usize) -> bool {
695 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A695 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A
696 /// partition whose warp-sample top-right probe may answer 1 where libaom says696 /// partition whose warp-sample top-right probe may answer 1 where libaom says
697 /// 0; upgrade path = thread `partition` into this call.697 /// 0; upgrade path = thread `partition` into this call.
698-pub(crate) fn has_top_right(mi_row: usize, mi_col: usize, bw4: usize, bh4: usize) -> bool {698+pub(crate) fn has_top_right(mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, fctx: &crate::decode::FrameCtx) -> bool {
699- let sb_mi_size = crate::decode::sb_mi_cur() as usize;699+ let sb_mi_size = crate::decode::sb_mi_cur(fctx) as usize;
700 let bs0 = bw4.max(bh4);700 let bs0 = bw4.max(bh4);
701 if bs0 > 16 {701 if bs0 > 16 {
702 return false;702 return false;
crates/ec-av1/src/restoration.rsmodified+16 -16
@@ -326,7 +326,7 @@ pub(crate) fn read_lr(
326 reference: &mut [(WienerInfo, SgrprojInfo); 3],326 reference: &mut [(WienerInfo, SgrprojInfo); 3],
327 mi_row: u32,327 mi_row: u32,
328 mi_col: u32,328 mi_col: u32,
329- sb_mi: u32,329+ sb_mi: u32, fctx: &crate::decode::FrameCtx,
330 ) {330 ) {
331 if !lr.uses_lr {331 if !lr.uses_lr {
332 return;332 return;
@@ -345,7 +345,7 @@ pub(crate) fn read_lr(
345 // is in upscaled ones, so the column division scales by345 // is in upscaled ones, so the column division scales by
346 // `superres_denom / SCALE_NUMERATOR` (`mi_to_num_x`/`denom_x`). Rows346 // `superres_denom / SCALE_NUMERATOR` (`mi_to_num_x`/`denom_x`). Rows
347 // are never scaled (spec 7.16 widens columns only).347 // are never scaled (spec 7.16 widens columns only).
348- let (num_x, denom_x) = match crate::decode::superres() {348+ let (num_x, denom_x) = match crate::decode::superres(fctx) {
349 Some((_, denom)) => (mi_size * denom, unit_size * 8),349 Some((_, denom)) => (mi_size * denom, unit_size * 8),
350 None => (mi_size, unit_size),350 None => (mi_size, unit_size),
351 };351 };
@@ -571,14 +571,14 @@ fn apply_wiener_stripe(
571 h_end: usize,571 h_end: usize,
572 v_start: usize,572 v_start: usize,
573 v_end: usize,573 v_end: usize,
574- info: &WienerInfo,574+ info: &WienerInfo, fctx: &crate::decode::FrameCtx,
575 ) {575 ) {
576 let w = h_end - h_start;576 let w = h_end - h_start;
577 let h = v_end - v_start;577 let h = v_end - v_start;
578 if w == 0 || h == 0 {578 if w == 0 || h == 0 {
579 return;579 return;
580 }580 }
581- let bd = i64::from(crate::decode::bit_depth());581+ let bd = i64::from(crate::decode::bit_depth(fctx));
582 let wiener_bias = 1i64 << (bd + 3);582 let wiener_bias = 1i64 << (bd + 3);
583 let wiener_limit = 1i64 << (bd + 5);583 let wiener_limit = 1i64 << (bd + 5);
584 let rows = h + 6;584 let rows = h + 6;
@@ -622,7 +622,7 @@ fn apply_wiener_stripe(
622 WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf);622 WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf);
623 // lane-perf7: the clamp bound is the frame's, so it is read once here623 // lane-perf7: the clamp bound is the frame's, so it is read once here
624 // instead of taking a thread-local read per output sample.624 // instead of taking a thread-local read per output sample.
625- let smax = i64::from(crate::decode::sample_max());625+ let smax = i64::from(crate::decode::sample_max(fctx));
626 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves626 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves
627 // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`.627 // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`.
628 let vf = &info.vfilter;628 let vf = &info.vfilter;
@@ -732,7 +732,7 @@ fn compute_ab(
732 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every732 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every
733 // page then faulted in on first touch. Every entry is written below, so733 // page then faulted in on first touch. Every entry is written below, so
734 // the resize's fill value is never read.734 // the resize's fill value is never read.
735- ab: &mut Vec<(i32, i64)>,735+ ab: &mut Vec<(i32, i64)>, fctx: &crate::decode::FrameCtx,
736 ) {736 ) {
737 let gw = w + 2;737 let gw = w + 2;
738 let gh = h + 2;738 let gh = h + 2;
@@ -750,7 +750,7 @@ fn compute_ab(
750 let mut col_a = vec![0i64; ncols];750 let mut col_a = vec![0i64; ncols];
751 let mut col_b = vec![0i64; ncols];751 let mut col_b = vec![0i64; ncols];
752 // Hoisted out of the per-point body: one thread-local read per call.752 // Hoisted out of the per-point body: one thread-local read per call.
753- let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8);753+ let bd_shift = u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
754 let base_col = h_start as i64 - 1 - r as i64;754 let base_col = h_start as i64 - 1 - r as i64;
755 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s755 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s
756 // window is row `gi`'s minus its top source row plus one new bottom row,756 // window is row `gi`'s minus its top source row plus one new bottom row,
@@ -844,7 +844,7 @@ fn apply_sgrproj_stripe(
844 h_end: usize,844 h_end: usize,
845 v_start: usize,845 v_start: usize,
846 v_end: usize,846 v_end: usize,
847- info: &SgrprojInfo,847+ info: &SgrprojInfo, fctx: &crate::decode::FrameCtx,
848 ) {848 ) {
849 let w = h_end - h_start;849 let w = h_end - h_start;
850 let h = v_end - v_start;850 let h = v_end - v_start;
@@ -860,10 +860,10 @@ fn apply_sgrproj_stripe(
860 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))860 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))
861 });861 });
862 if r0 > 0 {862 if r0 > 0 {
863- compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, &mut buf0);863+ compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, &mut buf0, fctx);
864 }864 }
865 if r1 > 0 {865 if r1 > 0 {
866- compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, &mut buf1);866+ compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, &mut buf1, fctx);
867 }867 }
868 let ab0 = (r0 > 0).then_some(&buf0);868 let ab0 = (r0 > 0).then_some(&buf0);
869 let ab1 = (r1 > 0).then_some(&buf1);869 let ab1 = (r1 > 0).then_some(&buf1);
@@ -904,7 +904,7 @@ fn apply_sgrproj_stripe(
904 904
905 // lane-perf7: as in `apply_wiener_stripe`, the clamp bound is read once905 // lane-perf7: as in `apply_wiener_stripe`, the clamp bound is read once
906 // per stripe instead of per output sample.906 // per stripe instead of per output sample.
907- let smax = i64::from(crate::decode::sample_max());907+ let smax = i64::from(crate::decode::sample_max(fctx));
908 for i in 0..h as i64 {908 for i in 0..h as i64 {
909 for j in 0..w as i64 {909 for j in 0..w as i64 {
910 let dgd = lr_sample(910 let dgd = lr_sample(
@@ -1005,7 +1005,7 @@ fn filter_restoration_unit(
1005 v_start: usize,1005 v_start: usize,
1006 v_end: usize,1006 v_end: usize,
1007 ss_y: u32,1007 ss_y: u32,
1008- filter: UnitFilter,1008+ filter: UnitFilter, fctx: &crate::decode::FrameCtx,
1009 ) {1009 ) {
1010 let full_stripe_height = 64usize >> ss_y;1010 let full_stripe_height = 64usize >> ss_y;
1011 let runit_offset = 8usize >> ss_y;1011 let runit_offset = 8usize >> ss_y;
@@ -1027,10 +1027,10 @@ fn filter_restoration_unit(
1027 }1027 }
1028 match filter {1028 match filter {
1029 UnitFilter::Wiener(info) => apply_wiener_stripe(1029 UnitFilter::Wiener(info) => apply_wiener_stripe(
1030- out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,1030+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx,
1031 ),1031 ),
1032 UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(1032 UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(
1033- out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,1033+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx,
1034 ),1034 ),
1035 UnitFilter::None => {}1035 UnitFilter::None => {}
1036 }1036 }
@@ -1065,7 +1065,7 @@ pub(crate) fn apply_loop_restoration_plane(
1065 // lane-perf6: the destination buffer, refilled from `cdef` here. It used1065 // lane-perf6: the destination buffer, refilled from `cdef` here. It used
1066 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte1066 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
1067 // allocation whose every page then faulted in on first touch.1067 // allocation whose every page then faulted in on first touch.
1068- out: &mut Vec<u16>,1068+ out: &mut Vec<u16>, fctx: &crate::decode::FrameCtx,
1069 ) {1069 ) {
1070 out.clear();1070 out.clear();
1071 out.extend_from_slice(cdef);1071 out.extend_from_slice(cdef);
@@ -1104,7 +1104,7 @@ pub(crate) fn apply_loop_restoration_plane(
1104 v_start as usize,1104 v_start as usize,
1105 v_end as usize,1105 v_end as usize,
1106 ss_y,1106 ss_y,
1107- filter,1107+ filter, fctx,
1108 );1108 );
1109 }1109 }
1110 x0 += uw;1110 x0 += uw;
crates/ec-av1/src/stream.rsmodified+95 -29
@@ -265,6 +265,9 @@ pub fn decode_stream_with(
265 data: &[u8],265 data: &[u8],
266 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,266 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
267 ) -> Result<()> {267 ) -> Result<()> {
268+ // lane-thread1: this stream's per-frame decode state (was 38 thread_local
269+ // statics in decode.rs) -- one object, threaded down the decode call graph.
270+ let fctx = &crate::decode::FrameCtx::new();
268 let final_dump = final_dump_prefix();271 let final_dump = final_dump_prefix();
269 let mut parser = Av1Parser::new();272 let mut parser = Av1Parser::new();
270 let mut pictures_shown: usize = 0;273 let mut pictures_shown: usize = 0;
@@ -368,7 +371,7 @@ pub fn decode_stream_with(
368 &picture,371 &picture,
369 &header.film_grain,372 &header.film_grain,
370 mc_identity,373 mc_identity,
371- bit_depth as u32,374+ bit_depth as u32, fctx,
372 )375 )
373 } else {376 } else {
374 picture377 picture
@@ -493,7 +496,7 @@ pub fn decode_stream_with(
493 header.segmentation,496 header.segmentation,
494 header.mi_rows as usize,497 header.mi_rows as usize,
495 header.mi_cols as usize,498 header.mi_cols as usize,
496- prev_seg_map.as_deref(),499+ prev_seg_map.as_deref(), fctx,
497 );500 );
498 // lane-superres stage 2/3: `use_superres` adds/removes no per-block501 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
499 // symbol (spec 7.16's upscaling is a pixel-domain post-process502 // symbol (spec 7.16's upscaling is a pixel-domain post-process
@@ -666,7 +669,7 @@ pub fn decode_stream_with(
666 // the key-frame tile path used to set; without this call a stream whose669 // the key-frame tile path used to set; without this call a stream whose
667 // inter frames are decoded on a thread that previously decoded a670 // inter frames are decoded on a thread that previously decoded a
668 // different sequence would inherit that sequence's bit.671 // different sequence would inherit that sequence's bit.
669- crate::decode::set_enable_edge_filter(enable_edge_filter);672+ crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
670 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the673 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
671 // key-frame and the inter tile path read the 128 partition root and674 // key-frame and the inter tile path read the 128 partition root and
672 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and675 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
@@ -678,7 +681,7 @@ pub fn decode_stream_with(
678 .sequence_header()681 .sequence_header()
679 .is_some_and(|seq| seq.use_128x128_superblock);682 .is_some_and(|seq| seq.use_128x128_superblock);
680 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);683 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
681- crate::decode::set_sb128(sb128_active);684+ crate::decode::set_sb128(sb128_active, fctx);
682 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,685 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
683 // which every dequant/inverse-transform clamp reads -- set per frame,686 // which every dequant/inverse-transform clamp reads -- set per frame,
684 // not once per process, for the same cross-sequence-on-one-thread687 // not once per process, for the same cross-sequence-on-one-thread
@@ -700,14 +703,14 @@ pub fn decode_stream_with(
700 "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",703 "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
701 ));704 ));
702 }705 }
703- crate::decode::set_bit_depth(bit_depth);706+ crate::decode::set_bit_depth(bit_depth, fctx);
704 // spec 7.16: this frame's superres state, for the filter chain --707 // spec 7.16: this frame's superres state, for the filter chain --
705 // `decode.rs` upscales between CDEF and loop restoration and sizes708 // `decode.rs` upscales between CDEF and loop restoration and sizes
706 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an709 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
707 // unscaled frame so a later frame never inherits it.710 // unscaled frame so a later frame never inherits it.
708 crate::decode::set_superres(711 crate::decode::set_superres(
709 if header.use_superres { header.upscaled_width } else { 0 },712 if header.use_superres { header.upscaled_width } else { 0 },
710- u32::from(header.superres_denom),713+ u32::from(header.superres_denom), fctx,
711 );714 );
712 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.715 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
713 let enable_masked_compound = parser716 let enable_masked_compound = parser
@@ -808,7 +811,7 @@ pub fn decode_stream_with(
808 header.reduced_tx_set,811 header.reduced_tx_set,
809 header.allow_screen_content_tools,812 header.allow_screen_content_tools,
810 header.allow_intrabc,813 header.allow_intrabc,
811- header.delta,814+ header.delta, fctx,
812 )?;815 )?;
813 // A key frame codes no inter blocks -- its own saved motion816 // A key frame codes no inter blocks -- its own saved motion
814 // field has no cells set, matching libaom's own "intra frame817 // field has no cells set, matching libaom's own "intra frame
@@ -919,7 +922,7 @@ pub fn decode_stream_with(
919 header.allow_warped_motion,922 header.allow_warped_motion,
920 header.allow_screen_content_tools,923 header.allow_screen_content_tools,
921 header.delta,924 header.delta,
922- enable_filter_intra,925+ enable_filter_intra, fctx,
923 )?;926 )?;
924 (picture, end_cdfs, motion_field)927 (picture, end_cdfs, motion_field)
925 };928 };
@@ -1003,7 +1006,7 @@ pub fn decode_stream_with(
1003 }1006 }
1004 }1007 }
1005 pictures_decoded += 1;1008 pictures_decoded += 1;
1006- let decoded_seg_map = decode::take_segment_ids();1009+ let decoded_seg_map = decode::take_segment_ids(fctx);
1007 for i in 0..NUM_REF_FRAMES {1010 for i in 0..NUM_REF_FRAMES {
1008 if header.refresh_frame_flags & (1 << i) != 0 {1011 if header.refresh_frame_flags & (1 << i) != 0 {
1009 cdf_slots[i] = Some(stored_cdfs.clone());1012 cdf_slots[i] = Some(stored_cdfs.clone());
@@ -1033,7 +1036,7 @@ pub fn decode_stream_with(
1033 &picture,1036 &picture,
1034 &header.film_grain,1037 &header.film_grain,
1035 mc_identity,1038 mc_identity,
1036- bit_depth as u32,1039+ bit_depth as u32, fctx,
1037 )1040 )
1038 } else {1041 } else {
1039 picture1042 picture
@@ -1067,7 +1070,7 @@ pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
1067 #[cfg(test)]1070 #[cfg(test)]
1068 mod tests {1071 mod tests {
1069 use super::*;1072 use super::*;
1070- use crate::encode::{Picture as Pic, encode_key_frame, encode_sequence};1073+ use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
1071 1074
1072 fn test_card(width: usize, height: usize) -> Pic {1075 fn test_card(width: usize, height: usize) -> Pic {
1073 let mut picture = Pic::grey(width, height);1076 let mut picture = Pic::grey(width, height);
@@ -1114,8 +1117,9 @@ mod tests {
1114 /// tile payload is never reached.1117 /// tile payload is never reached.
1115 #[test]1118 #[test]
1116 fn a_twelve_bit_sequence_header_is_refused_by_name() {1119 fn a_twelve_bit_sequence_header_is_refused_by_name() {
1120+ let fctx = &crate::decode::FrameCtx::new();
1117 let picture = test_card(64, 64);1121 let picture = test_card(64, 64);
1118- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1122+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1119 let mut color = ec_av1_syntax::ColorConfig {1123 let mut color = ec_av1_syntax::ColorConfig {
1120 bit_depth: 12,1124 bit_depth: 12,
1121 ..Default::default()1125 ..Default::default()
@@ -1157,9 +1161,10 @@ mod tests {
1157 /// never reports this refusal for any of them.1161 /// never reports this refusal for any of them.
1158 #[test]1162 #[test]
1159 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {1163 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
1164+ let fctx = &crate::decode::FrameCtx::new();
1160 const REFUSAL: &str = "a frame OBU with no tile group";1165 const REFUSAL: &str = "a frame OBU with no tile group";
1161 let picture = test_card(64, 64);1166 let picture = test_card(64, 64);
1162- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1167+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1163 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();1168 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
1164 let mut frame_obus_parsed = 0;1169 let mut frame_obus_parsed = 0;
1165 for len in 0..=encoded.tile.len().min(24) {1170 for len in 0..=encoded.tile.len().min(24) {
@@ -1212,10 +1217,11 @@ mod tests {
1212 /// first, a middle and the last segment id.1217 /// first, a middle and the last segment id.
1213 #[test]1218 #[test]
1214 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {1219 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
1220+ let fctx = &crate::decode::FrameCtx::new();
1215 const REFUSAL: &str =1221 const REFUSAL: &str =
1216 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";1222 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
1217 let picture = test_card(64, 64);1223 let picture = test_card(64, 64);
1218- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1224+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1219 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();1225 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
1220 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {1226 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1221 for segment in [0usize, 3, 7] {1227 for segment in [0usize, 3, 7] {
@@ -1603,9 +1609,10 @@ mod tests {
1603 /// tile is decoded.1609 /// tile is decoded.
1604 #[test]1610 #[test]
1605 fn an_inter_frame_opening_a_stream_is_refused_by_name() {1611 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
1612+ let fctx = &crate::decode::FrameCtx::new();
1606 const REFUSAL: &str = "an inter frame with no key frame before it";1613 const REFUSAL: &str = "an inter frame with no key frame before it";
1607 let picture = test_card(64, 64);1614 let picture = test_card(64, 64);
1608- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1615+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1609 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();1616 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
1610 let inter = FrameHeader {1617 let inter = FrameHeader {
1611 frame_type: FrameType::Inter,1618 frame_type: FrameType::Inter,
@@ -1648,10 +1655,11 @@ mod tests {
1648 /// fires on the reference's dimensions before a tile symbol is read.1655 /// fires on the reference's dimensions before a tile symbol is read.
1649 #[test]1656 #[test]
1650 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {1657 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
1658+ let fctx = &crate::decode::FrameCtx::new();
1651 const REFUSAL: &str =1659 const REFUSAL: &str =
1652 "a reference picture whose height does not match this frame's own true size";1660 "a reference picture whose height does not match this frame's own true size";
1653 let picture = test_card(64, 64);1661 let picture = test_card(64, 64);
1654- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1662+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1655 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();1663 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
1656 let inter = FrameHeader {1664 let inter = FrameHeader {
1657 frame_type: FrameType::Inter,1665 frame_type: FrameType::Inter,
@@ -1699,6 +1707,7 @@ mod tests {
1699 /// before the reference pictures are looked up.1707 /// before the reference pictures are looked up.
1700 #[test]1708 #[test]
1701 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {1709 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
1710+ let fctx = &crate::decode::FrameCtx::new();
1702 const REFUSAL: &str =1711 const REFUSAL: &str =
1703 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";1712 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
1704 // The invariant above, read off the source: every line that stores a1713 // The invariant above, read off the source: every line that stores a
@@ -1727,7 +1736,7 @@ mod tests {
1727 }1736 }
1728 1737
1729 let picture = test_card(64, 64);1738 let picture = test_card(64, 64);
1730- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();1739+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1731 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();1740 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
1732 for slot in 0..NUM_REF_FRAMES as u8 {1741 for slot in 0..NUM_REF_FRAMES as u8 {
1733 let inter = FrameHeader {1742 let inter = FrameHeader {
@@ -2130,9 +2139,10 @@ mod tests {
2130 /// the encoder's own reconstruction, at an even and an odd size.2139 /// the encoder's own reconstruction, at an even and an odd size.
2131 #[test]2140 #[test]
2132 fn decode_stream_matches_the_tile_path_on_a_key_frame() {2141 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
2142+ let fctx = &crate::decode::FrameCtx::new();
2133 for &(width, height) in &[(64usize, 64usize), (216, 96)] {2143 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
2134 let picture = test_card(width, height);2144 let picture = test_card(width, height);
2135- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();2145+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2136 let via_tile = decode_key_frame_tile(2146 let via_tile = decode_key_frame_tile(
2137 &encoded.tile,2147 &encoded.tile,
2138 encoded.mi_cols,2148 encoded.mi_cols,
@@ -2147,7 +2157,7 @@ mod tests {
2147 // Our own encoder always writes `reduced_tx_set: true`.2157 // Our own encoder always writes `reduced_tx_set: true`.
2148 true,2158 true,
2149 false,2159 false,
2150- false,2160+ false, fctx,
2151 )2161 )
2152 .unwrap();2162 .unwrap();
2153 let via_stream = decode_stream(&encoded.stream).unwrap();2163 let via_stream = decode_stream(&encoded.stream).unwrap();
@@ -2165,11 +2175,11 @@ mod tests {
2165 /// A GOP (key frame plus panned inter frames, so blocks actually take2175 /// A GOP (key frame plus panned inter frames, so blocks actually take
2166 /// motion) decodes bit-exact through `decode_stream` alone, threading its2176 /// motion) decodes bit-exact through `decode_stream` alone, threading its
2167 /// own DPB rather than a test-supplied reference.2177 /// own DPB rather than a test-supplied reference.
2168- fn gop_round_trips(width: usize, height: usize) {2178+ fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
2169 let pictures: Vec<_> = (0..4)2179 let pictures: Vec<_> = (0..4)
2170 .map(|i| panned_test_card(width, height, i * 3))2180 .map(|i| panned_test_card(width, height, i * 3))
2171 .collect();2181 .collect();
2172- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();2182+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
2173 let decoded = decode_stream(&encoded.stream).unwrap();2183 let decoded = decode_stream(&encoded.stream).unwrap();
2174 assert_eq!(decoded.len(), encoded.frames.len());2184 assert_eq!(decoded.len(), encoded.frames.len());
2175 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {2185 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
@@ -2190,14 +2200,16 @@ mod tests {
2190 2200
2191 #[test]2201 #[test]
2192 fn decode_stream_round_trips_a_gop() {2202 fn decode_stream_round_trips_a_gop() {
2193- gop_round_trips(128, 64);2203+ let fctx = &crate::decode::FrameCtx::new();
2204+ gop_round_trips(128, 64, fctx);
2194 }2205 }
2195 2206
2196 /// Same claim at a size that is not a whole number of 32x32 blocks, so2207 /// Same claim at a size that is not a whole number of 32x32 blocks, so
2197 /// the inter frame's 16x16-leaf split path is exercised too.2208 /// the inter frame's 16x16-leaf split path is exercised too.
2198 #[test]2209 #[test]
2199 fn decode_stream_round_trips_an_odd_size_gop() {2210 fn decode_stream_round_trips_an_odd_size_gop() {
2200- gop_round_trips(216, 96);2211+ let fctx = &crate::decode::FrameCtx::new();
2212+ gop_round_trips(216, 96, fctx);
2201 }2213 }
2202 2214
2203 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures2215 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
@@ -2208,8 +2220,9 @@ mod tests {
2208 /// decode indices non-decreasing, and an `Err` from the sink aborting.2220 /// decode indices non-decreasing, and an `Err` from the sink aborting.
2209 #[test]2221 #[test]
2210 fn streaming_decode_matches_the_collecting_one() {2222 fn streaming_decode_matches_the_collecting_one() {
2223+ let fctx = &crate::decode::FrameCtx::new();
2211 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();2224 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
2212- let stream = encode_sequence(&pictures, 100, 0.5).unwrap().stream;2225+ let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream;
2213 let collected = decode_stream(&stream).unwrap();2226 let collected = decode_stream(&stream).unwrap();
2214 2227
2215 let mut shown = Vec::new();2228 let mut shown = Vec::new();
@@ -2444,6 +2457,7 @@ mod tests {
2444 /// independent decoder, not just this crate checking its own tile path.2457 /// independent decoder, not just this crate checking its own tile path.
2445 #[test]2458 #[test]
2446 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {2459 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
2460+ let fctx = &crate::decode::FrameCtx::new();
2447 if !have_ffmpeg() {2461 if !have_ffmpeg() {
2448 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");2462 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
2449 return;2463 return;
@@ -2452,7 +2466,7 @@ mod tests {
2452 let pictures: Vec<_> = (0..3)2466 let pictures: Vec<_> = (0..3)
2453 .map(|i| panned_test_card(width, height, i * 3))2467 .map(|i| panned_test_card(width, height, i * 3))
2454 .collect();2468 .collect();
2455- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();2469+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
2456 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);2470 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
2457 let decoded = decode_stream(&encoded.stream).unwrap();2471 let decoded = decode_stream(&encoded.stream).unwrap();
2458 assert_eq!(decoded.len(), 3);2472 assert_eq!(decoded.len(), 3);
@@ -2491,6 +2505,7 @@ mod tests {
2491 /// with itself would prove nothing.2505 /// with itself would prove nothing.
2492 #[test]2506 #[test]
2493 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {2507 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
2508+ let fctx = &crate::decode::FrameCtx::new();
2494 if !have_ffmpeg() {2509 if !have_ffmpeg() {
2495 eprintln!(2510 eprintln!(
2496 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"2511 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
@@ -2526,7 +2541,7 @@ mod tests {
2526 2541
2527 for run in 0..4 {2542 for run in 0..4 {
2528 let picture = test_card(width, height);2543 let picture = test_card(width, height);
2529- let key = encode_key_frame(&picture, base_q_idx, 0.5).unwrap();2544+ let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
2530 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();2545 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
2531 2546
2532 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat2547 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
@@ -22619,6 +22634,7 @@ mod tests {
22619 /// the real proof).22634 /// the real proof).
22620 #[test]22635 #[test]
22621 fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {22636 fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {
22637+ let fctx = &crate::decode::FrameCtx::new();
22622 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";22638 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";
22623 if !have_ffmpeg() {22639 if !have_ffmpeg() {
22624 eprintln!("SKIP {NAME}: no ffmpeg");22640 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -22806,7 +22822,7 @@ mod tests {
22806 header.reduced_tx_set,22822 header.reduced_tx_set,
22807 header.allow_screen_content_tools,22823 header.allow_screen_content_tools,
22808 header.allow_intrabc,22824 header.allow_intrabc,
22809- header.delta,22825+ header.delta, fctx,
22810 ) {22826 ) {
22811 Err(e) => {22827 Err(e) => {
22812 let msg = e.to_string();22828 let msg = e.to_string();
@@ -22870,6 +22886,7 @@ mod tests {
22870 /// already proved -- this gate is what actually proves it either way.22886 /// already proved -- this gate is what actually proves it either way.
22871 #[test]22887 #[test]
22872 fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() {22888 fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() {
22889+ let fctx = &crate::decode::FrameCtx::new();
22873 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact";22890 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact";
22874 if !have_ffmpeg() {22891 if !have_ffmpeg() {
22875 eprintln!("SKIP {NAME}: no ffmpeg");22892 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -23028,7 +23045,7 @@ mod tests {
23028 header.reduced_tx_set,23045 header.reduced_tx_set,
23029 header.allow_screen_content_tools,23046 header.allow_screen_content_tools,
23030 header.allow_intrabc,23047 header.allow_intrabc,
23031- header.delta,23048+ header.delta, fctx,
23032 ) {23049 ) {
23033 Err(e) => {23050 Err(e) => {
23034 let msg = e.to_string();23051 let msg = e.to_string();
@@ -23205,6 +23222,7 @@ mod tests {
23205 /// 2-column case's boundary-that-is-also-the-frame-edge.23222 /// 2-column case's boundary-that-is-also-the-frame-edge.
23206 #[test]23223 #[test]
23207 fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() {23224 fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() {
23225+ let fctx = &crate::decode::FrameCtx::new();
23208 const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact";23226 const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact";
23209 if !have_ffmpeg() {23227 if !have_ffmpeg() {
23210 eprintln!("SKIP {NAME}: no ffmpeg");23228 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -23350,7 +23368,7 @@ mod tests {
23350 header.reduced_tx_set,23368 header.reduced_tx_set,
23351 header.allow_screen_content_tools,23369 header.allow_screen_content_tools,
23352 header.allow_intrabc,23370 header.allow_intrabc,
23353- header.delta,23371+ header.delta, fctx,
23354 ) {23372 ) {
23355 Err(e) => {23373 Err(e) => {
23356 let msg = e.to_string();23374 let msg = e.to_string();
@@ -32875,4 +32893,52 @@ mod tests {
32875 );32893 );
32876 }32894 }
32877 32895
32896+
32897+ /// lane-thread1: every per-frame/per-stream decode state now lives in
32898+ /// [`crate::decode::FrameCtx`], not in a `thread_local!`. A static that
32899+ /// comes back would silently re-break frame-parallel decoding (a worker
32900+ /// thread sees an empty copy) without failing any pixel gate, so pin the
32901+ /// 38 names by name against the sources themselves.
32902+ #[test]
32903+ fn no_per_frame_state_is_thread_local_any_more() {
32904+ const MOVED: [&str; 38] = [
32905+ "SB128", "CDEF_BITS", "BIT_DEPTH", "SUPERRES", "CDEF_TRANSMITTED", "CDEF_SB_COLS",
32906+ "CDEF_IDX_GRID", "DELTA_Q_PRESENT", "DELTA_Q_RES", "CURRENT_Q_IDX", "QUANT_DELTAS",
32907+ "DELTA_LF_PRESENT", "DELTA_LF_RES", "DELTA_LF_MULTI", "CURRENT_DELTA_LF", "SEG",
32908+ "SEG_IDS", "PREV_SEG_IDS", "SEG_MI_DIMS", "ABOVE_SEG_PRED", "LEFT_SEG_PRED",
32909+ "CUR_SEGMENT_ID", "SEG_TILE_ORIGIN", "TX_SELECT_INTER", "REDUCED_TX_SET_INTER",
32910+ "ENABLE_FILTER_INTRA_INTER", "PALETTE_PRED", "INTRABC_MI_GRID", "INTRABC_DV",
32911+ "LUMA_TX_TYPE", "INTRABC_CHROMA_TX", "INTRA_IN_INTER_MODE", "INTER_STRIP_CHROMA",
32912+ "INTER_LAST_MC", "ENABLE_EDGE_FILTER", "LAST_FRAME_WIDE_MARGIN", "REACH_SB_PX",
32913+ "GRAIN_BIT_DEPTH",
32914+ ];
32915+ let sources = [
32916+ ("decode.rs", include_str!("decode.rs")),
32917+ ("encode.rs", include_str!("encode.rs")),
32918+ ("film_grain.rs", include_str!("film_grain.rs")),
32919+ ];
32920+ let mut back = Vec::new();
32921+ for (name, src) in sources {
32922+ for line in src.lines() {
32923+ let t = line.trim_start().trim_start_matches("pub(crate) ");
32924+ if let Some(rest) = t.strip_prefix("static ") {
32925+ let ident = rest.split(':').next().unwrap_or("").trim();
32926+ if MOVED.contains(&ident) {
32927+ back.push(format!("{name}: {ident}"));
32928+ }
32929+ }
32930+ }
32931+ }
32932+ assert!(
32933+ back.is_empty(),
32934+ "per-frame state is thread_local again (belongs in FrameCtx): {back:?}"
32935+ );
32936+ // ... and the scratch pools / gate counters DID stay thread-local:
32937+ // this file's own counter reads run on the test thread.
32938+ assert!(
32939+ include_str!("decode.rs").contains("thread_local!"),
32940+ "the scratch pools and gate hit counters are still thread_local by design"
32941+ );
32942+ }
32943+
32878 }32944 }
crates/ec-av1/src/warp.rsmodified+9 -9
@@ -417,8 +417,8 @@ pub fn global_warp_params(wmmat: [i32; 6]) -> Option<WarpParams> {
417 Some(WarpParams { wmmat, alpha, beta, gamma, delta })417 Some(WarpParams { wmmat, alpha, beta, gamma, delta })
418 }418 }
419 419
420-fn clip_pixel(v: i32) -> u16 {420+fn clip_pixel(v: i32, fctx: &crate::decode::FrameCtx) -> u16 {
421- v.clamp(0, crate::decode::sample_max()) as u16421+ v.clamp(0, crate::decode::sample_max(fctx)) as u16
422 }422 }
423 423
424 /// `av1_highbd_warp_affine_c` (`warped_motion.c`)'s non-compound branch:424 /// `av1_highbd_warp_affine_c` (`warped_motion.c`)'s non-compound branch:
@@ -429,7 +429,7 @@ fn clip_pixel(v: i32) -> u16 {
429 /// the stream (`crate::decode::bit_depth`), the same thread-local429 /// the stream (`crate::decode::bit_depth`), the same thread-local
430 /// [`clip_pixel`] already clamps against -- libaom's `bd` parameter.430 /// [`clip_pixel`] already clamps against -- libaom's `bd` parameter.
431 #[allow(clippy::too_many_arguments)]431 #[allow(clippy::too_many_arguments)]
432-pub fn warp_affine(432+pub(crate) fn warp_affine(
433 params: &WarpParams,433 params: &WarpParams,
434 reference: &[u16],434 reference: &[u16],
435 width: i32,435 width: i32,
@@ -442,12 +442,12 @@ pub fn warp_affine(
442 p_height: i32,442 p_height: i32,
443 p_stride: i32,443 p_stride: i32,
444 subsampling_x: i32,444 subsampling_x: i32,
445- subsampling_y: i32,445+ subsampling_y: i32, fctx: &crate::decode::FrameCtx,
446 ) {446 ) {
447 if crate::envflags::env_flag!("EC_MC_TRACE") {447 if crate::envflags::env_flag!("EC_MC_TRACE") {
448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");
449 }449 }
450- let bd = i32::from(crate::decode::bit_depth());450+ let bd = i32::from(crate::decode::bit_depth(fctx));
451 // `reduce_bits_vert`, non-compound: `2 * FILTER_BITS - round_0`.451 // `reduce_bits_vert`, non-compound: `2 * FILTER_BITS - round_0`.
452 let reduce_bits_vert = 2 * FILTER_BITS - REDUCE_BITS_HORIZ;452 let reduce_bits_vert = 2 * FILTER_BITS - REDUCE_BITS_HORIZ;
453 warp_inner(453 warp_inner(
@@ -455,7 +455,7 @@ pub fn warp_affine(
455 subsampling_x, subsampling_y, bd, reduce_bits_vert,455 subsampling_x, subsampling_y, bd, reduce_bits_vert,
456 |row, col, sum| {456 |row, col, sum| {
457 dst[row * p_stride as usize + col] =457 dst[row * p_stride as usize + col] =
458- clip_pixel(sum - (1 << (bd - 1)) - (1 << bd));458+ clip_pixel(sum - (1 << (bd - 1)) - (1 << bd), fctx);
459 },459 },
460 );460 );
461 }461 }
@@ -477,7 +477,7 @@ pub fn warp_affine(
477 /// [`mc::predict_compound_intermediate`]'s for477 /// [`mc::predict_compound_intermediate`]'s for
478 /// [`mc::combine_compound`]/[`mc::blend_masked_compound`].478 /// [`mc::combine_compound`]/[`mc::blend_masked_compound`].
479 #[allow(clippy::too_many_arguments)]479 #[allow(clippy::too_many_arguments)]
480-pub fn warp_affine_compound(480+pub(crate) fn warp_affine_compound(
481 params: &WarpParams,481 params: &WarpParams,
482 reference: &[u16],482 reference: &[u16],
483 width: i32,483 width: i32,
@@ -490,9 +490,9 @@ pub fn warp_affine_compound(
490 p_height: i32,490 p_height: i32,
491 p_stride: i32,491 p_stride: i32,
492 subsampling_x: i32,492 subsampling_x: i32,
493- subsampling_y: i32,493+ subsampling_y: i32, fctx: &crate::decode::FrameCtx,
494 ) {494 ) {
495- let bd = i32::from(crate::decode::bit_depth());495+ let bd = i32::from(crate::decode::bit_depth(fctx));
496 let bias = (1 << (bd + 4)) + (1 << (bd + 3));496 let bias = (1 << (bd + 4)) + (1 << (bd + 3));
497 warp_inner(497 warp_inner(
498 params, reference, width, height, stride, p_col, p_row, p_width, p_height,498 params, reference, width, height, stride, p_col, p_row, p_width, p_height,