forge
Explore
Log in

Don't you dare go Hollow

The 38 per-frame decode-state thread_locals become one FrameCtx

Browse files at this commit

b9a9498fb34ffa3f7934ee26488179e6d9162f74Ahmet Kaan GümüşParent: d0c8191
  • refactor
    • the 38 per-frame decode-state thread_locals become one FrameCtx
Show full message
refactor(av1): the 38 per-frame decode-state thread_locals become one FrameCtx

Every per-frame/per-stream decode state in ec-av1 lived in a thread_local!
static, so a decode was a function of the calling THREAD's history rather
than of the bitstream, and a worker thread saw empty state -- the blocker
for frame-parallel decoding.

All 38 (SB128, BIT_DEPTH, SUPERRES, CDEF_*, DELTA_Q_*/DELTA_LF_*,
CURRENT_Q_IDX, QUANT_DELTAS, the 9 SEG* maps, TX_SELECT_INTER,
REDUCED_TX_SET_INTER, ENABLE_FILTER_INTRA_INTER, PALETTE_PRED, INTRABC_*,
LUMA_TX_TYPE, INTRA_IN_INTER_MODE, INTER_STRIP_CHROMA, INTER_LAST_MC,
ENABLE_EDGE_FILTER, LAST_FRAME_WIDE_MARGIN, REACH_SB_PX, GRAIN_BIT_DEPTH)
are now fields of decode::FrameCtx, owned by decode_stream_with and threaded
as `fctx: &FrameCtx` down the decode call graph (~1200 call sites).

The fields keep the Cell/RefCell interior mutability the statics had, so
every read/write site is byte-identical and this is a pure ownership move;
Cell/RefCell also make FrameCtx !Sync on purpose -- one context per decoding
thread, never shared. The scratch pools, gate hit counters and trace
switches stay thread_local by design.

11 changed files +1585 -1458

crates/ec-av1/src/decode.rsmodified+1185 -1135

Diff too large; view file

@@ -27,6 +27,124 @@ use ec_av1_syntax::{
2727 };
2828 use ec_core::{Error, Result};
2929
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 FrameCtx {
85+ /// A fresh context, every field at the default its thread-local
86+ /// predecessor was born with.
87+ pub(crate) fn new() -> Self {
88+ Self {
89+ sb128_flag: std::cell::Cell::new(false),
90+ cdef_bits: std::cell::Cell::new(0),
91+ bit_depth: std::cell::Cell::new(8),
92+ superres: std::cell::Cell::new((0, 8)),
93+ cdef_transmitted: std::cell::Cell::new(false),
94+ cdef_sb_cols: std::cell::Cell::new(0),
95+ cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
96+ delta_q_present: std::cell::Cell::new(false),
97+ delta_q_res: std::cell::Cell::new(1),
98+ current_q_idx: std::cell::Cell::new(0),
99+ quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
100+ y_dc: 0,
101+ u_dc: 0,
102+ u_ac: 0,
103+ v_dc: 0,
104+ v_ac: 0,
105+ }),
106+ delta_lf_present: std::cell::Cell::new(false),
107+ delta_lf_res: std::cell::Cell::new(1),
108+ delta_lf_multi: std::cell::Cell::new(false),
109+ current_delta_lf: std::cell::Cell::new([0; 4]),
110+ seg: std::cell::RefCell::new(SegmentationParams::default()),
111+ seg_ids: std::cell::RefCell::new(Vec::new()),
112+ prev_seg_ids: std::cell::RefCell::new(Vec::new()),
113+ seg_mi_dims: std::cell::Cell::new((0, 0)),
114+ above_seg_pred: std::cell::RefCell::new(Vec::new()),
115+ left_seg_pred: std::cell::RefCell::new(Vec::new()),
116+ cur_segment_id: std::cell::Cell::new(0),
117+ seg_tile_origin: std::cell::Cell::new((0, 0)),
118+ tx_select_inter: std::cell::Cell::new(false),
119+ reduced_tx_set_inter: std::cell::Cell::new(true),
120+ enable_filter_intra_inter: std::cell::Cell::new(false),
121+ palette_pred: std::cell::RefCell::new(None),
122+ intrabc_mi_grid: std::cell::RefCell::new(None),
123+ intrabc_dv: std::cell::Cell::new(None),
124+ luma_tx_type: std::cell::Cell::new(TxType::DctDct),
125+ intrabc_chroma_tx: std::cell::Cell::new(None),
126+ intra_in_inter_mode: std::cell::Cell::new(None),
127+ inter_strip_chroma: std::cell::Cell::new(None),
128+ inter_last_mc: std::cell::Cell::new(None),
129+ enable_edge_filter: std::cell::Cell::new(false),
130+ last_frame_wide_margin: std::cell::RefCell::new(None),
131+ reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
132+ grain_bit_depth: std::cell::Cell::new(8),
133+ }
134+ }
135+}
136+
137+/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
138+/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
139+/// `with` still wins for the scratch pools and gate counters that stay
140+/// thread-local.
141+pub(crate) trait WithRef {
142+ fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
143+ f(self)
144+ }
145+}
146+impl<T: ?Sized> WithRef for T {}
147+
30148 use crate::cdf;
31149 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
32150 use crate::encode::{Picture, Reach};
@@ -103,23 +221,20 @@ pub(crate) fn coeff_trace_on() -> bool {
103221 }
104222 }
105223
106-thread_local! {
107- static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
108-}
109224
110225 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
111-pub(crate) fn set_sb128(v: bool) {
112- SB128.with(|c| c.set(v));
113- crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });
226+pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
227+ fctx.sb128_flag.with(|c| c.set(v));
228+ crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
114229 }
115230
116-fn sb128() -> bool {
117- SB128.with(|c| c.get())
231+fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
232+ fctx.sb128_flag.with(|c| c.get())
118233 }
119234
120235 /// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
121-pub(crate) fn sb_mi_cur() -> u32 {
122- if sb128() { SB_MI * 2 } else { SB_MI }
236+pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
237+ if sb128(fctx) { SB_MI * 2 } else { SB_MI }
123238 }
124239
125240 /// How many real 128-level partition symbols this decoder has read, and how
@@ -246,9 +361,6 @@ pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
246361 // frame-level flag through the recursive block decode -- `0` (the default)
247362 // makes every call a true no-op, matching every existing gate stream's
248363 // `cdef_bits == 0` behaviour exactly.
249-thread_local! {
250- static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
251-}
252364 // lane-realworld r8: the sequence header's `color_config.bit_depth`, set
253365 // once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
254366 // call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
@@ -257,26 +369,22 @@ thread_local! {
257369 // `8`) is stage 1 of widening past that refusal without re-deriving every
258370 // clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
259371 // 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-}
263372 /// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
264373 /// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
265-pub(crate) fn sample_max() -> i32 {
266- (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
374+pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
375+ (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
267376 }
268377 /// The current stream's bit depth, for callers (e.g. dequant) that need the
269378 /// raw value rather than the derived clamp bound.
270-pub(crate) fn bit_depth() -> u8 {
271- BIT_DEPTH.with(std::cell::Cell::get)
379+pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
380+ fctx.bit_depth.with(std::cell::Cell::get)
272381 }
273382 /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
274383 /// [`crate::stream`]'s decode loop.
275-pub(crate) fn set_bit_depth(bit_depth: u8) {
276- BIT_DEPTH.with(|c| c.set(bit_depth));
384+pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
385+ fctx.bit_depth.with(|c| c.set(bit_depth));
277386 }
278387
279-thread_local! {
280388 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
281389 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
282390 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
@@ -287,40 +395,29 @@ thread_local! {
287395 /// superres arms). Set once per frame from [`crate::stream`]'s decode
288396 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
289397 /// so a later frame never inherits it.
290- static SUPERRES: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 8)) };
291-}
292398
293399 /// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
294400 /// `denom` 8) for a frame that is not superres-scaled.
295-pub(crate) fn set_superres(upscaled_width: u32, denom: u32) {
296- SUPERRES.with(|c| c.set((upscaled_width, denom)));
401+pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
402+ fctx.superres.with(|c| c.set((upscaled_width, denom)));
297403 }
298404
299405 /// `(upscaled_width, superres_denom)` when this frame is superres-scaled
300406 /// (libaom `av1_superres_scaled`), else `None`.
301-pub(crate) fn superres() -> Option<(u32, u32)> {
302- let (w, d) = SUPERRES.with(std::cell::Cell::get);
407+pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
408+ let (w, d) = fctx.superres.with(std::cell::Cell::get);
303409 (w > 0 && d != 8).then_some((w, d))
304410 }
305411 // Whether this superblock's single CDEF unit (this decoder has no 128x128
306412 // SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
307413 // read -- reset to `false` at the top of each superblock in the two tile
308414 // 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-}
312415 // Number of superblock columns in the current tile's grid, so
313416 // [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
314417 // [`CDEF_IDX_GRID`].
315-thread_local! {
316- static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
317-}
318418 // One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
319419 // which of the header's `1 << cdef.bits` strength pairs applies to that
320420 // superblock's samples.
321-thread_local! {
322- static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
323-}
324421 // How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
325422 // has read, across every call on the current thread -- the gate's proof that a
326423 // `cdef_bits > 0` stream actually reached the new reader rather than every
@@ -392,33 +489,15 @@ pub(crate) fn edge_filter_mi_fix_hits() -> usize {
392489 // 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
393490 // true no-op, matching every existing gate stream's `delta_q_present == 0`
394491 // 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-}
399492 // The running quantizer index (spec `CurrentQIndex`, libaom
400493 // `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
401494 // top of every tile (spec `decode_tile`), carried across superblocks within
402495 // that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
403496 // 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-}
407497 // This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
408498 // spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
409499 // per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
410500 // 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-}
422501 // How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
423502 // read, across every call on the current thread -- the gate's proof that a
424503 // `delta_q_present` stream actually reached the new reader.
@@ -434,8 +513,8 @@ pub(crate) fn delta_q_hits() -> usize {
434513 /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
435514 /// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
436515 /// one), so it is always `0` here.
437-fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
438- let d = QUANT_DELTAS.with(|c| c.get());
516+fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
517+ let d = fctx.quant_deltas.with(|c| c.get());
439518 match plane_idx {
440519 0 => (d.y_dc, 0),
441520 1 => (d.u_dc, d.u_ac),
@@ -452,11 +531,11 @@ fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
452531 /// top-left leaf is the only block that can ever land there), or when that
453532 /// leaf both *is* the whole superblock and is `skip` (the one case libaom
454533 /// 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) {
456- if !DELTA_Q_PRESENT.with(|c| c.get()) {
534+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) {
535+ if !fctx.delta_q_present.with(|c| c.get()) {
457536 return;
458537 }
459- let sb_mi = sb_mi_cur() as usize;
538+ let sb_mi = sb_mi_cur(fctx) as usize;
460539 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
461540 return;
462541 }
@@ -478,25 +557,17 @@ fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_
478557 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
479558 let reduced = if sign_negative { -abs } else { abs };
480559 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
481- let res = DELTA_Q_RES.with(|c| c.get());
482- CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
560+ let res = fctx.delta_q_res.with(|c| c.get());
561+ fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
483562 }
484563
485564 // lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
486565 // (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-}
492566 // The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
493567 // `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
494568 // mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
495569 // updates index 0 and every reader treats that as the value for all 4
496570 // 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-}
500571 // How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
501572 // read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
502573 thread_local! {
@@ -513,11 +584,11 @@ pub(crate) fn delta_lf_hits() -> usize {
513584 /// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
514585 /// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
515586 /// 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) {
517- if !DELTA_LF_PRESENT.with(|c| c.get()) {
587+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) {
588+ if !fctx.delta_lf_present.with(|c| c.get()) {
518589 return;
519590 }
520- let sb_mi = sb_mi_cur() as usize;
591+ let sb_mi = sb_mi_cur(fctx) as usize;
521592 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
522593 return;
523594 }
@@ -529,10 +600,10 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
529600 if is_whole_sb && skip {
530601 return;
531602 }
532- let multi = DELTA_LF_MULTI.with(|c| c.get());
533- let res = DELTA_LF_RES.with(|c| c.get());
603+ let multi = fctx.delta_lf_multi.with(|c| c.get());
604+ let res = fctx.delta_lf_res.with(|c| c.get());
534605 let count = if multi { 4 } else { 1 };
535- let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
606+ let mut cur = fctx.current_delta_lf.with(|c| c.get());
536607 for i in 0..count {
537608 let mut abs = if multi {
538609 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
@@ -550,7 +621,7 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
550621 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
551622 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
552623 }
553- CURRENT_DELTA_LF.with(|c| c.set(cur));
624+ fctx.current_delta_lf.with(|c| c.set(cur));
554625 }
555626
556627 /// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
@@ -559,18 +630,18 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
559630 /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
560631 /// `allow_intrabc`, so neither needs a separate check here. Reads once per
561632 /// superblock, at the first non-skip block.
562-fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
563- let bits = CDEF_BITS.with(|c| c.get());
564- if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
633+fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
634+ let bits = fctx.cdef_bits.with(|c| c.get());
635+ if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
565636 return;
566637 }
567638 let idx = dec.literal(u32::from(bits)) as u8;
568- CDEF_TRANSMITTED.with(|c| c.set(true));
639+ fctx.cdef_transmitted.with(|c| c.set(true));
569640 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
570641 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());
642+ let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
572643 if sb_cols > 0 {
573- CDEF_IDX_GRID.with(|g| {
644+ fctx.cdef_idx_grid.with(|g| {
574645 let mut g = g.borrow_mut();
575646 let i = sb_r * sb_cols + sb_c;
576647 if i < g.len() {
@@ -591,25 +662,16 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip:
591662 // PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
592663 // is what the oracle every gate here compares against actually does.
593664 thread_local! {
594- static SEG: std::cell::RefCell<SegmentationParams> =
595- std::cell::RefCell::new(SegmentationParams::default());
596665 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
597666 /// 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()) };
599667 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
600668 /// 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()) };
602669 /// `(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)) };
604670 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
605671 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
606672 /// 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()) };
609673 /// 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) };
611674 /// 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)) };
613675 /// How many real `segment_id` symbols were read, and the set of segment
614676 /// ids any block ended up with -- the gate's proof the feature fired.
615677 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
@@ -626,12 +688,12 @@ pub(crate) fn set_segmentation(
626688 seg: SegmentationParams,
627689 mi_rows: usize,
628690 mi_cols: usize,
629- prev: Option<&[u8]>,
691+ prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
630692 ) {
631- SEG.with(|s| *s.borrow_mut() = seg);
632- 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]);
634- PREV_SEG_IDS.with(|m| {
693+ fctx.seg.with(|s| *s.borrow_mut() = seg);
694+ fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
695+ fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
696+ fctx.prev_seg_ids.with(|m| {
635697 let mut m = m.borrow_mut();
636698 m.clear();
637699 if let Some(p) = prev {
@@ -640,15 +702,15 @@ pub(crate) fn set_segmentation(
640702 }
641703 }
642704 });
643- 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]);
645- CUR_SEGMENT_ID.with(|c| c.set(0));
705+ fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
706+ fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
707+ fctx.cur_segment_id.with(|c| c.set(0));
646708 }
647709
648710 /// This frame's decoded segment map, to be stored into whichever reference
649711 /// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
650-pub(crate) fn take_segment_ids() -> Vec<u8> {
651- SEG_IDS.with(|m| m.borrow().clone())
712+pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
713+ fctx.seg_ids.with(|m| m.borrow().clone())
652714 }
653715
654716 /// How many `segment_id` symbols have been read (never reset per frame).
@@ -675,8 +737,8 @@ pub(crate) fn reset_segment_hits() {
675737
676738 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently
677739 /// being decoded, with its `FeatureData` value.
678-fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
679- SEG.with(|s| {
740+fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
741+ fctx.seg.with(|s| {
680742 let s = s.borrow();
681743 s.feature_active(segment_id, feature)
682744 .then(|| i32::from(s.feature_data[segment_id][feature]))
@@ -687,29 +749,29 @@ fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
687749 /// `av1_get_qindex`) for the block currently being decoded: the running
688750 /// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
689751 /// Every dequant call site reads the block's quantizer through here.
690-fn block_q_idx() -> i32 {
691- let base = CURRENT_Q_IDX.with(|c| c.get());
692- let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
693- match seg_feature(seg_id, SEG_LVL_ALT_Q) {
752+fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
753+ let base = fctx.current_q_idx.with(|c| c.get());
754+ let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
755+ match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
694756 Some(data) => (base + data).clamp(0, 255),
695757 None => base,
696758 }
697759 }
698760
699761 /// 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 {
701- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
762+fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
763+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
702764 if mi_r >= mi_rows || mi_c >= mi_cols {
703765 return 0;
704766 }
705- SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
767+ fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
706768 }
707769
708770 /// `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) {
710- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
771+fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
772+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
711773 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| {
774+ fctx.seg_ids.with(|m| {
713775 let mut m = m.borrow_mut();
714776 for y in 0..y_mis {
715777 for x in 0..x_mis {
@@ -717,16 +779,16 @@ fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8)
717779 }
718780 }
719781 });
720- CUR_SEGMENT_ID.with(|c| c.set(id));
782+ fctx.cur_segment_id.with(|c| c.set(id));
721783 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
722784 }
723785
724786 /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
725787 /// `last_frame_seg_map`): the minimum previous-frame segment id over the
726788 /// 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 {
728- let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
729- PREV_SEG_IDS.with(|m| {
789+fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
790+ let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
791+ fctx.prev_seg_ids.with(|m| {
730792 let m = m.borrow();
731793 if m.is_empty() {
732794 return 0;
@@ -767,12 +829,12 @@ fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
767829
768830 /// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
769831 /// frame's already-decoded above/left/above-left neighbours.
770-fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
771- let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
832+fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
833+ let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
772834 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)));
774- let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
775- let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
835+ let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
836+ let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
837+ let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
776838 let ctx = match prev_ul {
777839 None => 0,
778840 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
@@ -796,14 +858,14 @@ fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
796858 /// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
797859 /// when `skip`, otherwise one `segment_id` symbol de-interleaved against
798860 /// 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 {
800- let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
861+fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
862+ let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
801863 if skip {
802864 return pred as u8;
803865 }
804866 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
805867 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));
868+ let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
807869 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
808870 }
809871
@@ -817,19 +879,19 @@ fn intra_segment_id(
817879 mi_c: usize,
818880 w_mi: usize,
819881 h_mi: usize,
820- skip: bool,
882+ skip: bool, fctx: &crate::decode::FrameCtx,
821883 ) {
822- if !SEG.with(|s| s.borrow().enabled) {
884+ if !fctx.seg.with(|s| s.borrow().enabled) {
823885 return;
824886 }
825- let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
826- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
887+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
888+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
827889 }
828890
829891 /// Whether this frame's intra blocks read their `segment_id` before `skip`
830892 /// (`SegIdPreSkip`); `false` also when segmentation is off.
831-fn seg_id_pre_skip() -> bool {
832- SEG.with(|s| {
893+fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
894+ fctx.seg.with(|s| {
833895 let s = s.borrow();
834896 s.enabled && s.seg_id_pre_skip
835897 })
@@ -846,9 +908,9 @@ fn inter_segment_id(
846908 w_mi: usize,
847909 h_mi: usize,
848910 skip: bool,
849- pre_skip: bool,
911+ pre_skip: bool, fctx: &crate::decode::FrameCtx,
850912 ) {
851- let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
913+ let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
852914 let s = s.borrow();
853915 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
854916 });
@@ -857,8 +919,8 @@ fn inter_segment_id(
857919 }
858920 if !update_map {
859921 // The map is inherited wholesale from the previous frame.
860- let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
861- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
922+ let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
923+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
862924 return;
863925 }
864926 if pre_skip && !pre_skip_frame {
@@ -867,40 +929,40 @@ fn inter_segment_id(
867929 if !pre_skip && skip {
868930 // libaom: a skipped block never codes `seg_id_predicted`, and its
869931 // segment id is the spatial prediction.
870- stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
871- let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
872- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
932+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
933+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
934+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
873935 return;
874936 }
875937 let id = if temporal_update {
876- let ctx = seg_pred_ctx(mi_r, mi_c);
938+ let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
877939 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
878940 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));
941+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
880942 if predicted {
881- predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
943+ predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
882944 } else {
883- read_segment_id(dec, cdfs, mi_r, mi_c, false)
945+ read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
884946 }
885947 } else {
886- read_segment_id(dec, cdfs, mi_r, mi_c, false)
948+ read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
887949 };
888- write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
950+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
889951 }
890952
891953 /// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
892-fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
954+fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
893955 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
894956 // so contribute 0) outside the tile -- the availability check here is
895957 // what keeps a previous tile's stamps out of this tile's context.
896- let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
958+ let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
897959 let above = if mi_r > row0 {
898- ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
960+ fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
899961 } else {
900962 0
901963 };
902964 let left = if mi_c > col0 {
903- LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
965+ fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
904966 } else {
905967 0
906968 };
@@ -908,8 +970,8 @@ fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
908970 }
909971
910972 /// 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) {
912- ABOVE_SEG_PRED.with(|m| {
973+fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
974+ fctx.above_seg_pred.with(|m| {
913975 let mut m = m.borrow_mut();
914976 for i in 0..w_mi {
915977 if let Some(cell) = m.get_mut(mi_c + i) {
@@ -917,7 +979,7 @@ fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8)
917979 }
918980 }
919981 });
920- LEFT_SEG_PRED.with(|m| {
982+ fctx.left_seg_pred.with(|m| {
921983 let mut m = m.borrow_mut();
922984 for i in 0..h_mi {
923985 if let Some(cell) = m.get_mut(mi_r + i) {
@@ -974,10 +1036,10 @@ fn tu_reach(
9741036 px: usize,
9751037 py: usize,
9761038 width: usize,
977- height: usize,
1039+ height: usize, fctx: &crate::decode::FrameCtx,
9781040 ) -> Reach {
9791041 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);
1042+ let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
9811043 if fixed != standalone {
9821044 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
9831045 }
@@ -1163,13 +1225,9 @@ thread_local! {
11631225 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
11641226 // `decode_inter_block` already carries forty parameters and both are
11651227 // 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) };
11681228 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
11691229 // frame-constant like the two above and stashed the same way -- an intra
11701230 // 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) };
11731231 }
11741232
11751233 /// Current value of [`TXFM_SPLIT_READS`].
@@ -1243,11 +1301,11 @@ fn vartx_rect_leaf_hit(tw: usize, th: usize) {
12431301 pub(crate) fn set_inter_tx_mode(
12441302 tx_select: bool,
12451303 reduced_tx_set: bool,
1246- enable_filter_intra: bool,
1304+ enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
12471305 ) {
1248- TX_SELECT_INTER.with(|c| c.set(tx_select));
1249- REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
1250- ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
1306+ fctx.tx_select_inter.with(|c| c.set(tx_select));
1307+ fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1308+ fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
12511309 }
12521310
12531311 // How many `partition_w16` reads (a 16x16 block's own partition symbol, key
@@ -1817,7 +1875,6 @@ pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
18171875 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
18181876 }
18191877
1820-thread_local! {
18211878 /// A just-decoded palette-Y block's own predicted pixels
18221879 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
18231880 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
@@ -1826,9 +1883,6 @@ thread_local! {
18261883 /// alternative this avoids). Always empty again once that call consumes
18271884 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
18281885 /// sees stale state.
1829- static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1830- const { std::cell::RefCell::new(None) };
1831-}
18321886
18331887
18341888 /// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
@@ -1837,21 +1891,21 @@ thread_local! {
18371891 /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
18381892 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
18391893 #[track_caller]
1840-fn set_palette_pred(buf: Vec<u16>) {
1894+fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
18411895 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1842- let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1896+ let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
18431897 eprintln!(
18441898 "PALSET len={} stale={stale} at {}",
18451899 buf.len(),
18461900 std::panic::Location::caller()
18471901 );
18481902 }
1849- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1903+ fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
18501904 }
18511905
18521906 #[track_caller]
1853-fn take_palette_pred() -> Option<Vec<u16>> {
1854- let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1907+fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
1908+ let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
18551909 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
18561910 eprintln!(
18571911 "PALTAKE len={:?} at {}",
@@ -1874,37 +1928,32 @@ thread_local! {
18741928 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
18751929 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
18761930 /// 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) };
18791931 /// The block vector [`read_intra_mode`] just decoded, handed to
18801932 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
18811933 /// which the alternative -- a tenth tuple member through every caller --
18821934 /// 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) };
18841935 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
18851936 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) };
19011937 }
1938+ // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1939+ // an intrabc block's chroma reads can inherit it (see
1940+ // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1941+ // through that one arming site.
1942+ // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1943+ // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1944+ // satisfies (`blockd.h:373`) -- and takes the *colocated luma
1945+ // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1946+ // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1947+ // intrabc block's two chroma [`read_plane`] calls; the type decides the
1948+ // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1949+ // -- getting it wrong desyncs the chroma coefficients, it is not a
1950+ // reconstruction-only detail.
19021951
19031952 /// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
19041953 /// `Some` exactly then (set once per frame in `decode_frame`), so the flag
19051954 /// needs no separate plumbing to reach the rect-strip mode reader.
1906-fn allow_intrabc_frame() -> bool {
1907- INTRABC_MI_GRID.with(|g| g.borrow().is_some())
1955+fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
1956+ fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
19081957 }
19091958
19101959 thread_local! {
@@ -1954,8 +2003,8 @@ pub(crate) fn reset_intrabc_hits() {
19542003 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
19552004 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
19562005 /// `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)>) {
1958- INTRABC_MI_GRID.with(|g| {
2006+fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
2007+ fctx.intrabc_mi_grid.with(|g| {
19592008 let mut g = g.borrow_mut();
19602009 let Some((grid, _, _)) = g.as_mut() else {
19612010 return;
@@ -2680,10 +2729,6 @@ pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
26802729 // already read by [`decode_inter_block`] and (b) the luma mode comes off
26812730 // `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
26822731 // 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-}
26872732
26882733 // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
26892734 // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
@@ -3081,15 +3126,8 @@ struct InterStripChroma {
30813126 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
30823127 }
30833128
3084-thread_local! {
3085- static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
3086- const { std::cell::Cell::new(None) };
30873129 /// The single-reference MC parameters of the inter block that decoded
30883130 /// 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-}
30933131
30943132 fn bump_ab16_inter(arm: usize) {
30953133 AB16_INTER_HITS.with(|c| {
@@ -3417,14 +3455,11 @@ pub(crate) fn ref_hits(ref_frame: i8) -> usize {
34173455 c.with(|v| v.get())
34183456 }
34193457
3420-thread_local! {
34213458 /// The sequence header's `enable_intra_edge_filter`, set once per
34223459 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
34233460 /// own read of it, kept off the call stack (see that function's own doc
34243461 /// comment for why) rather than threaded through every `read_plane`/
34253462 /// `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-}
34283463
34293464 /// Set [`ENABLE_EDGE_FILTER`] for this thread.
34303465 ///
@@ -3436,8 +3471,8 @@ thread_local! {
34363471 /// thread, inherits a foreign sequence's bit: decode stops being a pure
34373472 /// function of the bitstream. `decode_stream` now calls this once per stream
34383473 /// from the sequence header, which covers every frame including inter ones.
3439-pub(crate) fn set_enable_edge_filter(value: bool) {
3440- ENABLE_EDGE_FILTER.with(|f| f.set(value));
3474+pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
3475+ fctx.enable_edge_filter.with(|f| f.set(value));
34413476 }
34423477
34433478 /// Current value of [`ANGLE_DELTA_HITS`].
@@ -4959,7 +4994,7 @@ struct Neighbours {
49594994 impl Neighbours {
49604995 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
49614996 /// true (unpadded) size in 4x4 mode-info units.
4962- fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
4997+ fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
49634998 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
49644999 // neighbour state over the whole 64-row extent, past the frame's last
49655000 // mi row (mi_rows 198, block rows 192..208). libaom's own context
@@ -4967,7 +5002,7 @@ impl Neighbours {
49675002 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
49685003 // side arrays to a superblock multiple and leave those cells unread --
49695004 // every availability check uses the true `mi_rows`/`mi_cols` below.
4970- let sb_sub = (sb_mi_cur() as usize) / (SUB / MI);
5005+ let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
49715006 let (cols, rows) = (
49725007 cols.next_multiple_of(sb_sub),
49735008 rows.next_multiple_of(sb_sub),
@@ -5043,10 +5078,10 @@ impl Neighbours {
50435078 /// availability check below. Left context resets every superblock row
50445079 /// regardless of tile ([`Self::start_row`], already called once per SB
50455080 /// 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) {
5081+ fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
50475082 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
50485083 // are tile-relative, same as every other neighbour lookup here.
5049- SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
5084+ fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
50505085 self.tile_row0_mi = row0_mi;
50515086 self.tile_col0_mi = col0_mi;
50525087 let end = col1_mi.min(self.above.len());
@@ -5317,8 +5352,8 @@ impl Neighbours {
53175352 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
53185353 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
53195354 /// 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) {
5321- self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
5355+ fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
5356+ self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
53225357 }
53235358
53245359 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
@@ -5359,7 +5394,7 @@ impl Neighbours {
53595394 h_mi: usize,
53605395 tx_px: u8,
53615396 tx_h_px: u8,
5362- ref_frame: i8,
5397+ ref_frame: i8, fctx: &crate::decode::FrameCtx,
53635398 ) {
53645399 let (mi_r, mi_c) = at_mi;
53655400 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
@@ -5370,8 +5405,8 @@ impl Neighbours {
53705405 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
53715406 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}");
53725407 }
5373- let cur = CURRENT_DELTA_LF.with(|c| c.get());
5374- let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
5408+ let cur = fctx.current_delta_lf.with(|c| c.get());
5409+ let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
53755410 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
53765411 } else {
53775412 [cur[0].clamp(-63, 63) as i8; 4]
@@ -6594,7 +6629,7 @@ fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
65946629 /// (one flag bit each, in cache order), then delta-codes the remainder
65956630 /// (first value raw, each following delta `>= 1` off a shrinking bit width),
65966631 /// and merges the two ascending lists back together.
6597-fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
6632+fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
65986633 let mut cached = Vec::with_capacity(n);
65996634 for &c in cache {
66006635 if cached.len() >= n {
@@ -6604,7 +6639,7 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u
66046639 cached.push(c);
66056640 }
66066641 }
6607- let bd = u32::from(bit_depth());
6642+ let bd = u32::from(bit_depth(fctx));
66086643 let max_val = (1i32 << bd) - 1;
66096644 let mut colors = [0u16; 8];
66106645 let n_cached = cached.len();
@@ -6641,7 +6676,7 @@ fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u
66416676 /// side by side). V never uses a cache: a leading bit picks either `n` raw
66426677 /// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
66436678 /// rather than clamp.
6644-fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
6679+fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
66456680 let mut cached = Vec::with_capacity(n);
66466681 for &c in cache {
66476682 if cached.len() >= n {
@@ -6651,7 +6686,7 @@ fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> (
66516686 cached.push(c);
66526687 }
66536688 }
6654- let bd = u32::from(bit_depth());
6689+ let bd = u32::from(bit_depth(fctx));
66556690 let max_val = 1i32 << bd;
66566691 let mut u_colors = [0u16; 8];
66576692 let n_cached = cached.len();
@@ -6869,7 +6904,7 @@ fn read_intra_mode_rect(
68696904 palette: Option<(usize, &[u16])>,
68706905 palette_uv_cache: &[u16],
68716906 mi_r: usize,
6872- mi_c: usize,
6907+ mi_c: usize, fctx: &crate::decode::FrameCtx,
68736908 ) -> Result<(
68746909 bool,
68756910 usize,
@@ -6914,27 +6949,27 @@ fn read_intra_mode_rect(
69146949 // lane-intra14 r1: on the INTER block path everything up to and including
69156950 // `is_inter` was already read by [`decode_inter_block`], so this reader
69166951 // starts at the mode syntax with the `skip` that caller read.
6917- let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);
6952+ let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
69186953 let skip = if let Some((_, skip)) = inter {
69196954 skip
69206955 } else {
69216956 // Same `intra_segment_id` placement as the square reader above.
69226957 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6923- if seg_id_pre_skip() {
6924- intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6958+ if seg_id_pre_skip(fctx) {
6959+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
69256960 }
69266961 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
69276962 istep!("skip", skip as i32);
6928- if !seg_id_pre_skip() {
6929- intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6963+ if !seg_id_pre_skip(fctx) {
6964+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
69306965 }
6931- maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6966+ maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
69326967 istep!("cdef", 0);
69336968 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
69346969 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
69356970 // `false`.
6936- maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
6937- maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
6971+ maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
6972+ maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
69386973 istep!("dq", 0);
69396974 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
69406975 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
@@ -6946,7 +6981,7 @@ fn read_intra_mode_rect(
69466981 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
69476982 // block at this shape is out of scope, so the flag is consumed and
69486983 // refused by name when it fires.
6949- if allow_intrabc_frame() {
6984+ if allow_intrabc_frame(fctx) {
69506985 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
69516986 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
69526987 istep!("intrabc", use_intrabc as i32);
@@ -7036,7 +7071,7 @@ fn read_intra_mode_rect(
70367071 ));
70377072 }
70387073 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7039- let colors = read_palette_colors_y(dec, n, cache);
7074+ let colors = read_palette_colors_y(dec, n, cache, fctx);
70407075 palette_y_pending = Some((n, colors));
70417076 }
70427077 let palette_uv_mode_ctx = usize::from(use_palette_y);
@@ -7046,7 +7081,7 @@ fn read_intra_mode_rect(
70467081 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
70477082 {
70487083 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);
7084+ let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
70507085 palette_uv_pending = Some((n, u_colors, v_colors));
70517086 }
70527087 }
@@ -7302,7 +7337,7 @@ fn decode_rect_split(
73027337 u: &mut PlaneBuf,
73037338 v: &mut PlaneBuf,
73047339 base_q_idx: u8,
7305- reduced_tx_set: bool,
7340+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
73067341 ) -> Result<()> {
73077342 let (mi_r, mi_c) = at_mi;
73087343 let (px, py) = (mi_c * MI, mi_r * MI);
@@ -7422,7 +7457,7 @@ fn decode_rect_split(
74227457 let zero_tu = vec![0i32; tx_w * tx_h];
74237458 // The strip's OWN edge availability, the fallback for a transform unit
74247459 // 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);
7460+ let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
74267461 for tu_row in 0..bh / tx_h {
74277462 for tu_col in 0..bw / tx_w {
74287463 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
@@ -7462,7 +7497,7 @@ fn decode_rect_split(
74627497 buf[base..base + tx_w].iter().copied()
74637498 })
74647499 .collect();
7465- set_palette_pred(tu_buf);
7500+ set_palette_pred(tu_buf, fctx);
74667501 }
74677502 if m.skip {
74687503 y.reconstruct_rect(
@@ -7476,7 +7511,7 @@ fn decode_rect_split(
74767511 &zero_tu,
74777512 None,
74787513 m.filter_intra,
7479- m.smooth_neighbor,
7514+ m.smooth_neighbor, fctx,
74807515 );
74817516 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
74827517 } else if luma_64corner && luma_rect.is_none() {
@@ -7517,10 +7552,10 @@ fn decode_rect_split(
75177552 &tu_grid,
75187553 tx_w,
75197554 tx_h,
7520- crate::decode::bit_depth(),
7521- block_q_idx(),
7522- plane_q_delta(0).0,
7523- plane_q_delta(0).1,
7555+ crate::decode::bit_depth(fctx),
7556+ block_q_idx(fctx),
7557+ plane_q_delta(0, fctx).0,
7558+ plane_q_delta(0, fctx).1,
75247559 tu_tx_type,
75257560 );
75267561 y.reconstruct_rect(
@@ -7534,7 +7569,7 @@ fn decode_rect_split(
75347569 &residual,
75357570 None,
75367571 m.filter_intra,
7537- m.smooth_neighbor,
7572+ m.smooth_neighbor, fctx,
75387573 );
75397574 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
75407575 } else if let Some((rect_set, rect_scan)) = luma_rect {
@@ -7573,10 +7608,10 @@ fn decode_rect_split(
75737608 &tu_grid,
75747609 tx_w,
75757610 tx_h,
7576- crate::decode::bit_depth(),
7577- block_q_idx(),
7578- plane_q_delta(0).0,
7579- plane_q_delta(0).1,
7611+ crate::decode::bit_depth(fctx),
7612+ block_q_idx(fctx),
7613+ plane_q_delta(0, fctx).0,
7614+ plane_q_delta(0, fctx).1,
75807615 tu_tx_type,
75817616 );
75827617 y.reconstruct_rect(
@@ -7590,7 +7625,7 @@ fn decode_rect_split(
75907625 &residual,
75917626 None,
75927627 m.filter_intra,
7593- m.smooth_neighbor,
7628+ m.smooth_neighbor, fctx,
75947629 );
75957630 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
75967631 } else {
@@ -7619,7 +7654,7 @@ fn decode_rect_split(
76197654 None,
76207655 m.filter_intra,
76217656 Some(tu_skip_ctx),
7622- m.smooth_neighbor,
7657+ m.smooth_neighbor, fctx,
76237658 )?;
76247659 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
76257660 }
@@ -7631,18 +7666,18 @@ fn decode_rect_split(
76317666 let (u_grid, v_grid) = if m.skip {
76327667 let zero = vec![0i32; chroma_w * chroma_h];
76337668 if let Some((ub, _)) = &m.palette_uv {
7634- set_palette_pred(ub.clone());
7669+ set_palette_pred(ub.clone(), fctx);
76357670 }
76367671 u.reconstruct_rect(
76377672 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,
7673+ m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
76397674 );
76407675 if let Some((_, vb)) = &m.palette_uv {
7641- set_palette_pred(vb.clone());
7676+ set_palette_pred(vb.clone(), fctx);
76427677 }
76437678 v.reconstruct_rect(
76447679 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,
7680+ m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
76467681 );
76477682 (zero.clone(), zero)
76487683 } else {
@@ -7675,17 +7710,17 @@ fn decode_rect_split(
76757710 // (lane-rectsplit r4: lifting the split-transform refusal moved
76767711 // superblock strips onto this path, so only counting there would
76777712 // 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) {
7713+ if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
76797714 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
76807715 }
76817716 let residual = dequant_and_inverse_typed_wh(
76827717 &levels,
76837718 chroma_w,
76847719 chroma_h,
7685- crate::decode::bit_depth(),
7686- CURRENT_Q_IDX.with(|c| c.get()),
7687- plane_q_delta(plane_idx).0,
7688- plane_q_delta(plane_idx).1,
7720+ crate::decode::bit_depth(fctx),
7721+ fctx.current_q_idx.with(|c| c.get()),
7722+ plane_q_delta(plane_idx, fctx).0,
7723+ plane_q_delta(plane_idx, fctx).1,
76897724 tx_type,
76907725 );
76917726 let cfl = m
@@ -7695,7 +7730,7 @@ fn decode_rect_split(
76957730 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
76967731 if let Some((ub, vb)) = &m.palette_uv {
76977732 let buf = if plane_idx == 1 { ub } else { vb };
7698- set_palette_pred(buf.clone());
7733+ set_palette_pred(buf.clone(), fctx);
76997734 }
77007735 plane.reconstruct_rect(
77017736 cpx,
@@ -7708,7 +7743,7 @@ fn decode_rect_split(
77087743 &residual,
77097744 cfl,
77107745 None,
7711- m.smooth_neighbor_uv,
7746+ m.smooth_neighbor_uv, fctx,
77127747 );
77137748 grids.push(levels);
77147749 }
@@ -7724,7 +7759,7 @@ fn decode_rect_split(
77247759 [&u_grid, &v_grid],
77257760 );
77267761 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);
7762+ neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
77287763 if crate::envflags::env_flag!("EC_AV1_TRACE") {
77297764 let (rng, _) = dec.debug_state();
77307765 eprintln!(
@@ -7930,7 +7965,7 @@ fn decode_intra_rect_in_inter(
79307965 y: &mut PlaneBuf,
79317966 u: &mut PlaneBuf,
79327967 v: &mut PlaneBuf,
7933- base_q_idx: u8,
7968+ base_q_idx: u8, fctx: &crate::decode::FrameCtx,
79347969 ) -> Result<()> {
79357970 // `at` is in MI units (the inter path's own unit since lane-inter4);
79367971 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
@@ -7962,7 +7997,7 @@ fn decode_intra_rect_in_inter(
79627997 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
79637998 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
79647999 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
7965- INTRA_IN_INTER_MODE.with(|c| c.set(Some((0, skip))));
8000+ fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
79668001 let res = decode_rect4_16_strip(
79678002 dec,
79688003 cdfs,
@@ -7977,13 +8012,13 @@ fn decode_intra_rect_in_inter(
79778012 y,
79788013 u,
79798014 v,
7980- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8015+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
79818016 allow_screen_content_tools,
79828017 base_q_idx,
7983- TX_SELECT_INTER.with(std::cell::Cell::get),
7984- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8018+ fctx.tx_select_inter.with(std::cell::Cell::get),
8019+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
79858020 );
7986- INTRA_IN_INTER_MODE.with(|c| c.set(None));
8021+ fctx.intra_in_inter_mode.with(|c| c.set(None));
79878022 let (mode, uv, (tx_w, tx_h)) = res?;
79888023 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
79898024 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
@@ -8074,7 +8109,7 @@ fn decode_intra_rect_in_inter(
80748109 // (class `counter-from-refused-stream`).
80758110 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
80768111 }
8077- INTRA_IN_INTER_MODE.with(|c| c.set(Some((3, skip))));
8112+ fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
80788113 let res = decode_block_128rect(
80798114 dec,
80808115 cdfs,
@@ -8086,12 +8121,12 @@ fn decode_intra_rect_in_inter(
80868121 u,
80878122 v,
80888123 base_q_idx,
8089- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8124+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
80908125 allow_screen_content_tools,
8091- TX_SELECT_INTER.with(std::cell::Cell::get),
8092- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8126+ fctx.tx_select_inter.with(std::cell::Cell::get),
8127+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
80938128 );
8094- INTRA_IN_INTER_MODE.with(|c| c.set(None));
8129+ fctx.intra_in_inter_mode.with(|c| c.set(None));
80958130 return res;
80968131 }
80978132 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
@@ -8131,7 +8166,7 @@ fn decode_intra_rect_in_inter(
81318166 // `decode_block_rect64`), asserted here so a future shape cannot drift.
81328167 if bw.max(bh) == 4 * bw.min(bh) {
81338168 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))));
8169+ fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
81358170 let res = if bw.max(bh) == 64 {
81368171 decode_block_rect64(
81378172 dec,
@@ -8143,11 +8178,11 @@ fn decode_intra_rect_in_inter(
81438178 y,
81448179 u,
81458180 v,
8146- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8181+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
81478182 allow_screen_content_tools,
81488183 base_q_idx,
8149- TX_SELECT_INTER.with(std::cell::Cell::get),
8150- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8184+ fctx.tx_select_inter.with(std::cell::Cell::get),
8185+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
81518186 )
81528187 } else {
81538188 decode_block_rect4(
@@ -8161,14 +8196,14 @@ fn decode_intra_rect_in_inter(
81618196 y,
81628197 u,
81638198 v,
8164- ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8199+ fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
81658200 allow_screen_content_tools,
81668201 base_q_idx,
8167- TX_SELECT_INTER.with(std::cell::Cell::get),
8202+ fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
81688203 )
81698204 .map(|_| ())
81708205 };
8171- INTRA_IN_INTER_MODE.with(|c| c.set(None));
8206+ fctx.intra_in_inter_mode.with(|c| c.set(None));
81728207 res?;
81738208 let shape = match (bw, bh) {
81748209 (64, 16) => 0,
@@ -8271,7 +8306,7 @@ fn decode_intra_rect_in_inter(
82718306 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
82728307 if use_palette_y {
82738308 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)));
8309+ palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
82758310 }
82768311 // A 2:1 strip of at least 8x8 is always a chroma reference, so
82778312 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
@@ -8282,7 +8317,7 @@ fn decode_intra_rect_in_inter(
82828317 }
82838318 if use_palette_uv {
82848319 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);
8320+ let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
82868321 palette_uv_pending = Some((n, u_colors, v_colors));
82878322 }
82888323 }
@@ -8294,7 +8329,7 @@ fn decode_intra_rect_in_inter(
82948329 // ([`filter_intra_size_class_rect`]).
82958330 let mut filter_intra = None;
82968331 if mode == DC_PRED
8297- && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
8332+ && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
82988333 // `av1_filter_intra_allowed` excludes a palette-Y block.
82998334 && palette_y_pending.is_none()
83008335 && let Some(class) = filter_intra_size_class_rect(bw, bh)
@@ -8338,10 +8373,10 @@ fn decode_intra_rect_in_inter(
83388373 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
83398374 }
83408375 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) {
8376+ let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
83428377 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
83438378 // 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));
8379+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
83458380 let d = match tx_cat {
83468381 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
83478382 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
@@ -8419,7 +8454,7 @@ fn decode_intra_rect_in_inter(
84198454 u,
84208455 v,
84218456 base_q_idx,
8422- REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8457+ fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
84238458 )?;
84248459 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
84258460 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
@@ -8487,7 +8522,7 @@ fn decode_block_rect(
84878522 allow_screen_content_tools: bool,
84888523 base_q_idx: u8,
84898524 tx_select: bool,
8490- reduced_tx_set: bool,
8525+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
84918526 ) -> Result<()> {
84928527 let (r, c) = at;
84938528 let (px, py) = (c * SUB, r * SUB);
@@ -8510,7 +8545,7 @@ fn decode_block_rect(
85108545 Some((palette_ctx, &palette_cache)),
85118546 &palette_uv_cache,
85128547 r * (SUB / MI),
8513- c * (SUB / MI),
8548+ c * (SUB / MI), fctx,
85148549 )?;
85158550 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
85168551 if smooth_neighbor {
@@ -8550,8 +8585,8 @@ fn decode_block_rect(
85508585 // written. Measured on the 10-bit 1920x792 128-superblock stream,
85518586 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
85528587 // `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() {
8554- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
8588+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
8589+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
85558590 } else {
85568591 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
85578592 };
@@ -8617,7 +8652,7 @@ fn decode_block_rect(
86178652 u,
86188653 v,
86198654 base_q_idx,
8620- reduced_tx_set,
8655+ reduced_tx_set, fctx,
86218656 )?;
86228657 // This early return skips this fn's own tail, so the palette
86238658 // neighbour state has to be stamped HERE too: without it a split-tx
@@ -8637,7 +8672,7 @@ fn decode_block_rect(
86378672 let (tx_w, tx_h) = (bw, bh);
86388673 let (cpx, cpy) = (px / 2, py / 2);
86398674 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8640- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8675+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
86418676 if crate::envflags::env_flag!("EC_AV1_TRACE") {
86428677 let (rng, _) = dec.debug_state();
86438678 eprintln!(
@@ -8651,7 +8686,7 @@ fn decode_block_rect(
86518686 // right before each `reconstruct_rect` call below (lane-palette2 r4).
86528687 if let Some(ref pyv) = palette_y {
86538688 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
8654- set_palette_pred(buf);
8689+ set_palette_pred(buf, fctx);
86558690 }
86568691 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
86578692 (
@@ -8671,11 +8706,11 @@ fn decode_block_rect(
86718706 &vec![0i32; bw * bh],
86728707 None,
86738708 filter_intra,
8674- smooth_neighbor,
8709+ smooth_neighbor, fctx,
86758710 );
86768711 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
86778712 if let Some((ub, _)) = &palette_uv_bufs {
8678- set_palette_pred(ub.clone());
8713+ set_palette_pred(ub.clone(), fctx);
86798714 }
86808715 u.reconstruct_rect(
86818716 cpx,
@@ -8688,10 +8723,10 @@ fn decode_block_rect(
86888723 &vec![0i32; chroma_w * chroma_h],
86898724 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
86908725 None,
8691- smooth_neighbor_uv,
8726+ smooth_neighbor_uv, fctx,
86928727 );
86938728 if let Some((_, vb)) = &palette_uv_bufs {
8694- set_palette_pred(vb.clone());
8729+ set_palette_pred(vb.clone(), fctx);
86958730 }
86968731 v.reconstruct_rect(
86978732 cpx,
@@ -8704,7 +8739,7 @@ fn decode_block_rect(
87048739 &vec![0i32; chroma_w * chroma_h],
87058740 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
87068741 None,
8707- smooth_neighbor_uv,
8742+ smooth_neighbor_uv, fctx,
87088743 );
87098744 neighbours.record_rect(
87108745 at,
@@ -8784,10 +8819,10 @@ fn decode_block_rect(
87848819 &luma_levels,
87858820 bw,
87868821 bh,
8787- crate::decode::bit_depth(),
8788- block_q_idx(),
8789- plane_q_delta(0).0,
8790- plane_q_delta(0).1,
8822+ crate::decode::bit_depth(fctx),
8823+ block_q_idx(fctx),
8824+ plane_q_delta(0, fctx).0,
8825+ plane_q_delta(0, fctx).1,
87918826 luma_tx_type,
87928827 );
87938828 y.reconstruct_rect(
@@ -8801,11 +8836,11 @@ fn decode_block_rect(
88018836 &luma_residual,
88028837 None,
88038838 filter_intra,
8804- smooth_neighbor,
8839+ smooth_neighbor, fctx,
88058840 );
88068841 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
88078842 if let Some((ub, _)) = &palette_uv_bufs {
8808- set_palette_pred(ub.clone());
8843+ set_palette_pred(ub.clone(), fctx);
88098844 }
88108845 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
88118846 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
@@ -8828,10 +8863,10 @@ fn decode_block_rect(
88288863 &u_levels,
88298864 chroma_w,
88308865 chroma_h,
8831- crate::decode::bit_depth(),
8832- block_q_idx(),
8833- plane_q_delta(1).0,
8834- plane_q_delta(1).1,
8866+ crate::decode::bit_depth(fctx),
8867+ block_q_idx(fctx),
8868+ plane_q_delta(1, fctx).0,
8869+ plane_q_delta(1, fctx).1,
88358870 u_tx_type,
88368871 );
88378872 u.reconstruct_rect(
@@ -8845,10 +8880,10 @@ fn decode_block_rect(
88458880 &u_residual,
88468881 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
88478882 None,
8848- smooth_neighbor_uv,
8883+ smooth_neighbor_uv, fctx,
88498884 );
88508885 if let Some((_, vb)) = &palette_uv_bufs {
8851- set_palette_pred(vb.clone());
8886+ set_palette_pred(vb.clone(), fctx);
88528887 }
88538888 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
88548889 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
@@ -8871,10 +8906,10 @@ fn decode_block_rect(
88718906 &v_levels,
88728907 chroma_w,
88738908 chroma_h,
8874- crate::decode::bit_depth(),
8875- block_q_idx(),
8876- plane_q_delta(2).0,
8877- plane_q_delta(2).1,
8909+ crate::decode::bit_depth(fctx),
8910+ block_q_idx(fctx),
8911+ plane_q_delta(2, fctx).0,
8912+ plane_q_delta(2, fctx).1,
88788913 v_tx_type,
88798914 );
88808915 v.reconstruct_rect(
@@ -8888,7 +8923,7 @@ fn decode_block_rect(
88888923 &v_residual,
88898924 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
88908925 None,
8891- smooth_neighbor_uv,
8926+ smooth_neighbor_uv, fctx,
88928927 );
88938928 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
88948929 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
@@ -8900,7 +8935,7 @@ fn decode_block_rect(
89008935 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
89018936 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
89028937 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);
8938+ neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
89048939 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
89058940 if crate::envflags::env_flag!("EC_AV1_TRACE") {
89068941 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
@@ -8943,7 +8978,7 @@ fn decode_leaf_rect(
89438978 allow_screen_content_tools: bool,
89448979 base_q_idx: u8,
89458980 tx_select: bool,
8946- reduced_tx_set: bool,
8981+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
89478982 ) -> Result<usize> {
89488983 let _ = base_q_idx;
89498984 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
@@ -9007,7 +9042,7 @@ fn decode_leaf_rect(
90079042 Some((palette_ctx, &palette_cache)),
90089043 &palette_uv_cache,
90099044 leaf_mi.0,
9010- leaf_mi.1,
9045+ leaf_mi.1, fctx,
90119046 )?;
90129047 // lane-kf900 r4: palette prediction on this shape, the same colour-index
90139048 // map -> base colours buffer [`decode_block_rect`] hands each
@@ -9047,8 +9082,8 @@ fn decode_leaf_rect(
90479082 let depth = if tx_select {
90489083 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
90499084 // 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() {
9051- tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh)
9085+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9086+ tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
90529087 } else {
90539088 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
90549089 };
@@ -9112,7 +9147,7 @@ fn decode_leaf_rect(
91129147 u,
91139148 v,
91149149 base_q_idx,
9115- reduced_tx_set,
9150+ reduced_tx_set, fctx,
91169151 )?;
91179152 record_strip_palette(
91189153 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
@@ -9120,7 +9155,7 @@ fn decode_leaf_rect(
91209155 return Ok(mode);
91219156 }
91229157 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);
9158+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
91249159 let (cpx, cpy) = (px / 2, py / 2);
91259160 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
91269161 let (luma_levels, u_levels, v_levels);
@@ -9129,26 +9164,26 @@ fn decode_leaf_rect(
91299164 u_levels = vec![0i32; chroma_w * chroma_h];
91309165 v_levels = vec![0i32; chroma_w * chroma_h];
91319166 if let Some(b) = &palette_y_buf {
9132- set_palette_pred(b.clone());
9167+ set_palette_pred(b.clone(), fctx);
91339168 }
91349169 y.reconstruct_rect(
91359170 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
9136- smooth_neighbor,
9171+ smooth_neighbor, fctx,
91379172 );
91389173 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
91399174 if let Some((ub, _)) = &palette_uv_bufs {
9140- set_palette_pred(ub.clone());
9175+ set_palette_pred(ub.clone(), fctx);
91419176 }
91429177 u.reconstruct_rect(
91439178 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,
9179+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
91459180 );
91469181 if let Some((_, vb)) = &palette_uv_bufs {
9147- set_palette_pred(vb.clone());
9182+ set_palette_pred(vb.clone(), fctx);
91489183 }
91499184 v.reconstruct_rect(
91509185 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,
9186+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
91529187 );
91539188 } else {
91549189 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
@@ -9178,15 +9213,15 @@ fn decode_leaf_rect(
91789213 }
91799214 luma_levels = l_levels;
91809215 let luma_residual = dequant_and_inverse_typed_wh(
9181- &luma_levels, bw, bh, crate::decode::bit_depth(),
9182- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
9216+ &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
9217+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
91839218 );
91849219 if let Some(b) = &palette_y_buf {
9185- set_palette_pred(b.clone());
9220+ set_palette_pred(b.clone(), fctx);
91869221 }
91879222 y.reconstruct_rect(
91889223 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
9189- smooth_neighbor,
9224+ smooth_neighbor, fctx,
91909225 );
91919226 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
91929227 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
@@ -9198,15 +9233,15 @@ fn decode_leaf_rect(
91989233 )?;
91999234 u_levels = u_l;
92009235 let u_residual = dequant_and_inverse_typed_wh(
9201- &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9202- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
9236+ &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
9237+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
92039238 );
92049239 if let Some((ub, _)) = &palette_uv_bufs {
9205- set_palette_pred(ub.clone());
9240+ set_palette_pred(ub.clone(), fctx);
92069241 }
92079242 u.reconstruct_rect(
92089243 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,
9244+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
92109245 );
92119246 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
92129247 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
@@ -9217,21 +9252,21 @@ fn decode_leaf_rect(
92179252 )?;
92189253 v_levels = v_l;
92199254 let v_residual = dequant_and_inverse_typed_wh(
9220- &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9221- CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
9255+ &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
9256+ fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
92229257 );
92239258 if let Some((_, vb)) = &palette_uv_bufs {
9224- set_palette_pred(vb.clone());
9259+ set_palette_pred(vb.clone(), fctx);
92259260 }
92269261 v.reconstruct_rect(
92279262 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,
9263+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
92299264 );
92309265 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
92319266 }
92329267 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
92339268 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);
9269+ neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
92359270 // The leaf's own palette state (`0` clears, as this site always did
92369271 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
92379272 // AXIS only until the pair's closing leaf: the coarse cell holds one
@@ -9282,7 +9317,7 @@ fn decode_block_rect4(
92829317 enable_filter_intra: bool,
92839318 allow_screen_content_tools: bool,
92849319 base_q_idx: u8,
9285- tx_select: bool,
9320+ tx_select: bool, fctx: &crate::decode::FrameCtx,
92869321 ) -> Result<(usize, usize)> {
92879322 let _ = base_q_idx;
92889323 let (mi_r, mi_c) = strip_mi;
@@ -9336,7 +9371,7 @@ fn decode_block_rect4(
93369371 Some((palette_ctx, &palette_cache)),
93379372 &palette_uv_cache,
93389373 mi_r,
9339- mi_c,
9374+ mi_c, fctx,
93409375 )?;
93419376 // lane-kf900 r4: palette prediction on this shape, exactly as
93429377 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
@@ -9390,8 +9425,8 @@ fn decode_block_rect4(
93909425 // written. Measured on the 10-bit 1920x792 128-superblock stream,
93919426 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
93929427 // `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() {
9394- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
9428+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9429+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
93959430 } else {
93969431 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
93979432 };
@@ -9412,7 +9447,7 @@ fn decode_block_rect4(
94129447 neighbours,
94139448 (mi_r, mi_c),
94149449 depth_to_tx_wh(bw, bh, depth),
9415- (bw, bh),
9450+ (bw, bh), fctx,
94169451 );
94179452 if depth != 0 {
94189453 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
@@ -9463,7 +9498,7 @@ fn decode_block_rect4(
94639498 u,
94649499 v,
94659500 base_q_idx,
9466- false,
9501+ false, fctx,
94679502 )?;
94689503 record_strip_palette(
94699504 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
@@ -9512,7 +9547,7 @@ fn decode_block_rect4(
95129547 let (px, py) = (mi_c * MI, mi_r * MI);
95139548 let (cpx, cpy) = (px / 2, py / 2);
95149549 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9515- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9550+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
95169551 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
95179552 (&SCAN_32X8, &SCAN_16X4)
95189553 } else {
@@ -9561,14 +9596,14 @@ fn decode_block_rect4(
95619596 &luma_levels,
95629597 bw,
95639598 bh,
9564- crate::decode::bit_depth(),
9565- block_q_idx(),
9566- plane_q_delta(0).0,
9567- plane_q_delta(0).1,
9599+ crate::decode::bit_depth(fctx),
9600+ block_q_idx(fctx),
9601+ plane_q_delta(0, fctx).0,
9602+ plane_q_delta(0, fctx).1,
95689603 luma_tx_type,
95699604 );
95709605 if let Some(b) = &palette_y_buf {
9571- set_palette_pred(b.clone());
9606+ set_palette_pred(b.clone(), fctx);
95729607 }
95739608 y.reconstruct_rect(
95749609 px,
@@ -9581,7 +9616,7 @@ fn decode_block_rect4(
95819616 &luma_residual,
95829617 None,
95839618 filter_intra,
9584- smooth_neighbor,
9619+ smooth_neighbor, fctx,
95859620 );
95869621 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
95879622 for (plane, buf, levels, tx_type) in [
@@ -9592,14 +9627,14 @@ fn decode_block_rect4(
95929627 levels,
95939628 chroma_w,
95949629 chroma_h,
9595- crate::decode::bit_depth(),
9596- block_q_idx(),
9597- plane_q_delta(plane).0,
9598- plane_q_delta(plane).1,
9630+ crate::decode::bit_depth(fctx),
9631+ block_q_idx(fctx),
9632+ plane_q_delta(plane, fctx).0,
9633+ plane_q_delta(plane, fctx).1,
95999634 tx_type,
96009635 );
96019636 if let Some((ub, vb)) = &palette_uv_bufs {
9602- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9637+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
96039638 }
96049639 buf.reconstruct_rect(
96059640 cpx,
@@ -9614,7 +9649,7 @@ fn decode_block_rect4(
96149649 .zip(ac.as_deref())
96159650 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
96169651 None,
9617- smooth_neighbor_uv,
9652+ smooth_neighbor_uv, fctx,
96189653 );
96199654 }
96209655 neighbours.record_mi_rect(
@@ -9624,7 +9659,7 @@ fn decode_block_rect4(
96249659 &[luma_levels, u_levels, v_levels],
96259660 );
96269661 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);
9662+ neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
96289663 record_strip_palette(
96299664 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
96309665 pal_uv_colors,
@@ -9644,7 +9679,7 @@ fn decode_block_rect4(
96449679 return Ok((mode, uv_predict_mode));
96459680 };
96469681 if let Some(b) = &palette_y_buf {
9647- set_palette_pred(b.clone());
9682+ set_palette_pred(b.clone(), fctx);
96489683 }
96499684 y.reconstruct_rect(
96509685 px,
@@ -9657,11 +9692,11 @@ fn decode_block_rect4(
96579692 &luma_levels,
96589693 None,
96599694 filter_intra,
9660- smooth_neighbor,
9695+ smooth_neighbor, fctx,
96619696 );
96629697 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
96639698 if let Some((ub, _)) = &palette_uv_bufs {
9664- set_palette_pred(ub.clone());
9699+ set_palette_pred(ub.clone(), fctx);
96659700 }
96669701 u.reconstruct_rect(
96679702 cpx,
@@ -9674,10 +9709,10 @@ fn decode_block_rect4(
96749709 &u_levels,
96759710 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
96769711 None,
9677- smooth_neighbor_uv,
9712+ smooth_neighbor_uv, fctx,
96789713 );
96799714 if let Some((_, vb)) = &palette_uv_bufs {
9680- set_palette_pred(vb.clone());
9715+ set_palette_pred(vb.clone(), fctx);
96819716 }
96829717 v.reconstruct_rect(
96839718 cpx,
@@ -9690,11 +9725,11 @@ fn decode_block_rect4(
96909725 &v_levels,
96919726 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
96929727 None,
9693- smooth_neighbor_uv,
9728+ smooth_neighbor_uv, fctx,
96949729 );
96959730 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
96969731 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);
9732+ neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
96989733 record_strip_palette(
96999734 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
97009735 );
@@ -9752,7 +9787,7 @@ fn decode_rect4_16(
97529787 allow_screen_content_tools: bool,
97539788 base_q_idx: u8,
97549789 tx_select: bool,
9755- reduced_tx_set: bool,
9790+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
97569791 ) -> Result<()> {
97579792 let (r, c) = at16;
97589793 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
@@ -9785,7 +9820,7 @@ fn decode_rect4_16(
97859820 allow_screen_content_tools,
97869821 base_q_idx,
97879822 tx_select,
9788- reduced_tx_set,
9823+ reduced_tx_set, fctx,
97899824 )?;
97909825 if let Some(m) = uv {
97919826 last_uv_mode = m;
@@ -9828,7 +9863,7 @@ fn decode_rect4_16_strip(
98289863 allow_screen_content_tools: bool,
98299864 base_q_idx: u8,
98309865 tx_select: bool,
9831- reduced_tx_set: bool,
9866+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
98329867 ) -> Result<(usize, Option<usize>, (usize, usize))> {
98339868 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
98349869 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
@@ -9880,7 +9915,7 @@ fn decode_rect4_16_strip(
98809915 Some((palette_ctx, &palette_cache)),
98819916 &palette_uv_cache,
98829917 lmi.0,
9883- lmi.1,
9918+ lmi.1, fctx,
98849919 )?;
98859920 if palette_y.is_some() || palette_uv.is_some() {
98869921 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
@@ -9914,8 +9949,8 @@ fn decode_rect4_16_strip(
99149949 // the 2:1 intra-in-inter strip already does); the key frame's
99159950 // deblock-grid approximation is only right where those bands were
99169951 // never written.
9917- let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9918- tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
9952+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9953+ tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
99199954 } else {
99209955 tx_size_context_rect(neighbours, lmi, bw, bh)
99219956 };
@@ -9938,7 +9973,7 @@ fn decode_rect4_16_strip(
99389973 }
99399974 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
99409975 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9941- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9976+ let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
99429977 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
99439978 if depth != 0 {
99449979 // [`decode_rect_split`]'s per-unit walk, inlined because the
@@ -9969,12 +10004,12 @@ fn decode_rect4_16_strip(
996910004 b[base..base + tx_w].iter().copied()
997010005 })
997110006 .collect();
9972- set_palette_pred(tu_buf);
10007+ set_palette_pred(tu_buf, fctx);
997310008 }
997410009 if skip {
997510010 y.reconstruct_rect(
997610011 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
9977- None, filter_intra, smooth_neighbor,
10012+ None, filter_intra, smooth_neighbor, fctx,
997810013 );
997910014 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
998010015 } else if rect_unit {
@@ -10005,15 +10040,15 @@ fn decode_rect4_16_strip(
1000510040 &tu_grid,
1000610041 tx_w,
1000710042 tx_h,
10008- crate::decode::bit_depth(),
10009- block_q_idx(),
10010- plane_q_delta(0).0,
10011- plane_q_delta(0).1,
10043+ crate::decode::bit_depth(fctx),
10044+ block_q_idx(fctx),
10045+ plane_q_delta(0, fctx).0,
10046+ plane_q_delta(0, fctx).1,
1001210047 tu_tx_type,
1001310048 );
1001410049 y.reconstruct_rect(
1001510050 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
10016- None, filter_intra, smooth_neighbor,
10051+ None, filter_intra, smooth_neighbor, fctx,
1001710052 );
1001810053 if tu_grid.iter().any(|&l| l != 0) {
1001910054 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
@@ -10042,7 +10077,7 @@ fn decode_rect4_16_strip(
1004210077 None,
1004310078 filter_intra,
1004410079 Some(tu_skip_ctx),
10045- smooth_neighbor,
10080+ smooth_neighbor, fctx,
1004610081 )?;
1004710082 if tu_grid.iter().any(|&l| l != 0) {
1004810083 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
@@ -10055,11 +10090,11 @@ fn decode_rect4_16_strip(
1005510090 let levels = if skip {
1005610091 let zeros = vec![0i32; bw * bh];
1005710092 if let Some(b) = &palette_y_buf {
10058- set_palette_pred(b.clone());
10093+ set_palette_pred(b.clone(), fctx);
1005910094 }
1006010095 y.reconstruct_rect(
1006110096 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
10062- smooth_neighbor,
10097+ smooth_neighbor, fctx,
1006310098 );
1006410099 zeros
1006510100 } else {
@@ -10087,18 +10122,18 @@ fn decode_rect4_16_strip(
1008710122 &levels,
1008810123 bw,
1008910124 bh,
10090- crate::decode::bit_depth(),
10091- block_q_idx(),
10092- plane_q_delta(0).0,
10093- plane_q_delta(0).1,
10125+ crate::decode::bit_depth(fctx),
10126+ block_q_idx(fctx),
10127+ plane_q_delta(0, fctx).0,
10128+ plane_q_delta(0, fctx).1,
1009410129 tx_type,
1009510130 );
1009610131 if let Some(b) = &palette_y_buf {
10097- set_palette_pred(b.clone());
10132+ set_palette_pred(b.clone(), fctx);
1009810133 }
1009910134 y.reconstruct_rect(
1010010135 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
10101- smooth_neighbor,
10136+ smooth_neighbor, fctx,
1010210137 );
1010310138 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
1010410139 levels
@@ -10106,7 +10141,7 @@ fn decode_rect4_16_strip(
1010610141 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
1010710142 }
1010810143 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);
10144+ neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
1011010145 // `update_partition_context` writes `partition_context_lookup[
1011110146 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
1011210147 // the left (mirrored under VERT_4).
@@ -10135,7 +10170,7 @@ fn decode_rect4_16_strip(
1013510170 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
1013610171 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
1013710172 }
10138- let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);
10173+ let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
1013910174 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
1014010175 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
1014110176 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
@@ -10166,7 +10201,7 @@ fn decode_rect4_16_strip(
1016610201 }
1016710202 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
1016810203 if let Some((ub, vb)) = &palette_uv_bufs {
10169- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
10204+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
1017010205 }
1017110206 buf.reconstruct_rect(
1017210207 cpx,
@@ -10181,7 +10216,7 @@ fn decode_rect4_16_strip(
1018110216 .zip(ac.as_deref())
1018210217 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
1018310218 None,
10184- smooth_neighbor_uv,
10219+ smooth_neighbor_uv, fctx,
1018510220 );
1018610221 }
1018710222 (zeros.clone(), zeros)
@@ -10217,14 +10252,14 @@ fn decode_rect4_16_strip(
1021710252 levels,
1021810253 cw,
1021910254 ch,
10220- crate::decode::bit_depth(),
10221- block_q_idx(),
10222- plane_q_delta(plane).0,
10223- plane_q_delta(plane).1,
10255+ crate::decode::bit_depth(fctx),
10256+ block_q_idx(fctx),
10257+ plane_q_delta(plane, fctx).0,
10258+ plane_q_delta(plane, fctx).1,
1022410259 tx_type,
1022510260 );
1022610261 if let Some((ub, vb)) = &palette_uv_bufs {
10227- set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
10262+ set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
1022810263 }
1022910264 buf.reconstruct_rect(
1023010265 cpx,
@@ -10239,7 +10274,7 @@ fn decode_rect4_16_strip(
1023910274 .zip(ac.as_deref())
1024010275 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
1024110276 None,
10242- smooth_neighbor_uv,
10277+ smooth_neighbor_uv, fctx,
1024310278 );
1024410279 }
1024510280 (u_levels, v_levels)
@@ -10330,7 +10365,7 @@ fn decode_block_rect64(
1033010365 allow_screen_content_tools: bool,
1033110366 base_q_idx: u8,
1033210367 tx_select: bool,
10333- reduced_tx_set: bool,
10368+ reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
1033410369 ) -> Result<()> {
1033510370 let (r, c) = at;
1033610371 let (px, py) = (c * SUB, r * SUB);
@@ -10360,7 +10395,7 @@ fn decode_block_rect64(
1036010395 Some((palette_ctx, &palette_cache)),
1036110396 &palette_uv_cache,
1036210397 r * (SUB / MI),
10363- c * (SUB / MI),
10398+ c * (SUB / MI), fctx,
1036410399 )?;
1036510400 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
1036610401 // The luma coefficient path here is the corner-cropped 32x32 real
@@ -10412,8 +10447,8 @@ fn decode_block_rect64(
1041210447 // written. Measured on the 10-bit 1920x792 128-superblock stream,
1041310448 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
1041410449 // `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() {
10416- tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
10450+ let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10451+ tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
1041710452 } else {
1041810453 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
1041910454 };
@@ -10441,7 +10476,7 @@ fn decode_block_rect64(
1044110476 neighbours,
1044210477 (mi_r, mi_c),
1044310478 depth_to_tx_wh(bw, bh, depth),
10444- (bw, bh),
10479+ (bw, bh), fctx,
1044510480 );
1044610481 if depth != 0 {
1044710482 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
@@ -10503,7 +10538,7 @@ fn decode_block_rect64(
1050310538 u,
1050410539 v,
1050510540 base_q_idx,
10506- reduced_tx_set,
10541+ reduced_tx_set, fctx,
1050710542 )?;
1050810543 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
1050910544 // (lane-palette2 r10): this return skips the fn's own tail, so a
@@ -10530,10 +10565,10 @@ fn decode_block_rect64(
1053010565 let (tx_w, tx_h) = (bw, bh);
1053110566 let (cpx, cpy) = (px / 2, py / 2);
1053210567 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10533- let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
crates/ec-av1/src/encode.rsmodified+184 -146
@@ -14,6 +14,7 @@
1414 //! as the decoder will. That makes the reconstruction a claim about what a
1515 //! decoder produces, and it is gated as one — sample for sample against ffmpeg.
1616
17+use crate::decode::WithRef;
1718 use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
1819 use ec_av1_syntax::{
1920 ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
@@ -54,17 +55,14 @@ pub(crate) const SUPERBLOCK: usize = 64;
5455 // superblock changes every answer inside it (the tables themselves are
5556 // already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
5657 // 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-}
6058
6159 /// Sets the superblock size [`Reach`] answers against (64 or 128).
62-pub(crate) fn set_reach_superblock_px(px: usize) {
63- REACH_SB_PX.with(|c| c.set(px));
60+pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
61+ fctx.reach_sb_px.with(|c| c.set(px));
6462 }
6563
66-fn reach_sb_px() -> usize {
67- REACH_SB_PX.with(|c| c.get())
64+fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
65+ fctx.reach_sb_px.with(|c| c.get())
6866 }
6967
7068 /// How heavily the mode search weighs rate against squared error, in units of
@@ -241,7 +239,7 @@ fn intra_predict_u8(
241239 bh: usize,
242240 enable_edge_filter: bool,
243241 smooth_neighbor: bool,
244- dst: &mut [u8],
242+ dst: &mut [u8], fctx: &crate::decode::FrameCtx,
245243 ) {
246244 let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());
247245 let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());
@@ -256,7 +254,7 @@ fn intra_predict_u8(
256254 bh,
257255 enable_edge_filter,
258256 smooth_neighbor,
259- &mut dst16,
257+ &mut dst16, fctx,
260258 );
261259 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
262260 *d = s as u8;
@@ -658,7 +656,7 @@ impl Plane<'_> {
658656 /// Codes one block under one mode without committing it: hands back the
659657 /// levels, the block the decoder would reconstruct, the squared error
660658 /// 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 {
662660 let At {
663661 x, y, side, reach, ..
664662 } = at;
@@ -674,7 +672,7 @@ impl Plane<'_> {
674672 side,
675673 false,
676674 false,
677- &mut prediction,
675+ &mut prediction, fctx,
678676 );
679677
680678 let mut residual = vec![0i32; side * side];
@@ -832,9 +830,9 @@ impl Plane<'_> {
832830 at: At,
833831 mode: u8,
834832 base_q_idx: u8,
835- deadzone: f64,
833+ deadzone: f64, fctx: &crate::decode::FrameCtx,
836834 ) -> (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);
838836 self.commit(at.x, at.y, at.side, &trial);
839837 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
840838 }
@@ -874,7 +872,7 @@ impl Plane<'_> {
874872 at: At,
875873 modes: &[u8],
876874 mode_bits: &[f64; 13],
877- lambda: f64,
875+ lambda: f64, fctx: &crate::decode::FrameCtx,
878876 ) -> Vec<(f64, u8)> {
879877 let At {
880878 x, y, side, reach, ..
@@ -894,7 +892,7 @@ impl Plane<'_> {
894892 side,
895893 false,
896894 false,
897- &mut prediction,
895+ &mut prediction, fctx,
898896 );
899897 let sad: f64 = (0..side * side)
900898 .map(|i| {
@@ -925,7 +923,7 @@ impl Plane<'_> {
925923 &mut self,
926924 at: At,
927925 search: &Search,
928- mode_bits: &[f64; 13],
926+ mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
929927 ) -> (Vec<Coeff>, u8, f64) {
930928 let At {
931929 x, y, side, reach, ..
@@ -946,7 +944,7 @@ impl Plane<'_> {
946944 side,
947945 false,
948946 false,
949- &mut prediction,
947+ &mut prediction, fctx,
950948 );
951949 let sad: f64 = (0..side * side)
952950 .map(|i| {
@@ -1298,10 +1296,10 @@ impl Reach {
12981296
12991297 /// What a block of `side` samples at `(x, y)` may read past its own edges,
13001298 /// 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 {
13021300 Self {
1303- above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
1304- below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
1301+ above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
1302+ below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
13051303 }
13061304 }
13071305
@@ -1316,11 +1314,11 @@ impl Reach {
13161314 x: usize,
13171315 y: usize,
13181316 width: usize,
1319- height: usize,
1317+ height: usize, fctx: &crate::decode::FrameCtx,
13201318 ) -> Self {
13211319 Self {
1322- above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y),
1323- below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y),
1320+ above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
1321+ below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
13241322 }
13251323 }
13261324
@@ -1338,8 +1336,8 @@ impl Reach {
13381336 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
13391337 /// the transform covering the whole block, luma): everything before the
13401338 /// table lookup is that function's own early-exit ladder.
1341- fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {
1342- let sb_mi: usize = reach_sb_px() / 4;
1339+ fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1340+ let sb_mi: usize = reach_sb_px(fctx) / 4;
13431341 let (mi_row, mi_col) = (y / 4, x / 4);
13441342 let bw_log2 = (bw / 4).trailing_zeros() as usize;
13451343 let bh_log2 = (bh / 4).trailing_zeros() as usize;
@@ -1371,8 +1369,8 @@ impl Reach {
13711369 }
13721370
13731371 /// 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 {
1375- let sb_mi: usize = reach_sb_px() / 4;
1372+ fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1373+ let sb_mi: usize = reach_sb_px(fctx) / 4;
13761374 let (mi_row, mi_col) = (y / 4, x / 4);
13771375 let bw_log2 = (bw / 4).trailing_zeros() as usize;
13781376 let bh_log2 = (bh / 4).trailing_zeros() as usize;
@@ -1421,8 +1419,8 @@ impl Reach {
14211419 /// row of a superblock reads into the superblock above, which is decoded;
14221420 /// the rightmost column would read into the superblock to the right, which
14231421 /// is not; and everything between is the table's to answer.
1424- fn top_right(side: usize, x: usize, y: usize) -> bool {
1425- let (row, col, per_side) = Self::position(side, x, y);
1422+ fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1423+ let (row, col, per_side) = Self::position(side, x, y, fctx);
14261424 if row == 0 {
14271425 return true;
14281426 }
@@ -1456,10 +1454,10 @@ impl Reach {
14561454 /// reads into the superblock to its left, which is decoded only as far
14571455 /// down as its own bottom; the bottom row would read into the superblock
14581456 /// below, which is not decoded at all; and the table answers the rest.
1459- fn bottom_left(side: usize, x: usize, y: usize) -> bool {
1460- let (row, col, per_side) = Self::position(side, x, y);
1457+ fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1458+ let (row, col, per_side) = Self::position(side, x, y, fctx);
14611459 if col == 0 {
1462- return row * side + side < reach_sb_px();
1460+ return row * side + side < reach_sb_px(fctx);
14631461 }
14641462 if row + 1 == per_side {
14651463 return false;
@@ -1489,8 +1487,8 @@ impl Reach {
14891487
14901488 /// Where a block sits inside its superblock, in blocks of its own size,
14911489 /// and how many of them a superblock is across.
1492- fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {
1493- let sb = reach_sb_px();
1490+ fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
1491+ let sb = reach_sb_px(fctx);
14941492 ((y % sb) / side, (x % sb) / side, sb / side)
14951493 }
14961494
@@ -1550,7 +1548,7 @@ fn code_square(
15501548 (x, y): (usize, usize),
15511549 side: usize,
15521550 search: &Search,
1553- mode_bits: &[f64; 13],
1551+ mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
15541552 ) -> (BlockCoeffs, f64) {
15551553 let (luma_set, chroma_set) = if side == BLOCK {
15561554 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -1571,11 +1569,11 @@ fn code_square(
15711569 x,
15721570 y,
15731571 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),
15751573 set: luma_set,
15761574 },
15771575 search,
1578- mode_bits,
1576+ mode_bits, fctx,
15791577 );
15801578 // Chroma is predicted DC because that is the mode the tile writer codes
15811579 // for it; what it costs still counts towards the partition decision.
@@ -1591,7 +1589,7 @@ fn code_square(
15911589 },
15921590 DC_PRED,
15931591 search.base_q_idx,
1594- search.deadzone,
1592+ search.deadzone, fctx,
15951593 );
15961594 *coeffs = levels;
15971595 cost += sse + search.lambda * bits;
@@ -1629,9 +1627,9 @@ fn code_square_inter(
16291627 search: &Search,
16301628 mode_bits: &[f64; 13],
16311629 reference: &Picture,
1632- stack: &MvStack,
1630+ stack: &MvStack, fctx: &crate::decode::FrameCtx,
16331631 ) -> 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);
16351633 let luma_set = if side == 8 {
16361634 TxbSet::Luma8Inter
16371635 } else {
@@ -1685,7 +1683,7 @@ fn code_square_inter(
16851683 false,
16861684 search.base_q_idx,
16871685 search.deadzone,
1688- luma_set,
1686+ luma_set, fctx,
16891687 );
16901688 let u = mc_trial(
16911689 &chroma[0],
@@ -1701,7 +1699,7 @@ fn code_square_inter(
17011699 false,
17021700 search.base_q_idx,
17031701 search.deadzone,
1704- chroma_set,
1702+ chroma_set, fctx,
17051703 );
17061704 let v = mc_trial(
17071705 &chroma[1],
@@ -1717,7 +1715,7 @@ fn code_square_inter(
17171715 false,
17181716 search.base_q_idx,
17191717 search.deadzone,
1720- chroma_set,
1718+ chroma_set, fctx,
17211719 );
17221720 let skip = luma_trial.levels.iter().all(|&l| l == 0)
17231721 && u.levels.iter().all(|&l| l == 0)
@@ -1997,8 +1995,8 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
19971995 /// # Errors
19981996 /// Returns an error when the picture's width or height is zero or odd, or
19991997 /// when its planes are not 4:2:0 of that size.
2000-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)
1998+pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
1999+ encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
20022000 }
20032001
20042002 /// Encodes one picture as a key frame, choosing each block's luma mode from
@@ -2016,7 +2014,7 @@ pub fn encode_key_frame_with_modes(
20162014 picture: &Picture,
20172015 base_q_idx: u8,
20182016 deadzone: f64,
2019- modes: &[u8],
2017+ modes: &[u8], fctx: &crate::decode::FrameCtx,
20202018 ) -> Result<Encoded> {
20212019 picture.check_even()?;
20222020 let padded = picture.padded_to(BLOCK);
@@ -2027,7 +2025,7 @@ pub fn encode_key_frame_with_modes(
20272025 modes,
20282026 split_blocks(),
20292027 (picture.width, picture.height),
2030- unspecified_color_config(),
2028+ unspecified_color_config(), fctx,
20312029 )?;
20322030 Ok(crop_encoded(&encoded, picture.width, picture.height))
20332031 }
@@ -2043,7 +2041,7 @@ pub(crate) fn encode_key_frame_inner(
20432041 modes: &[u8],
20442042 split_blocks: bool,
20452043 render: (usize, usize),
2046- color_config: ColorConfig,
2044+ color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
20472045 ) -> Result<Encoded> {
20482046 picture.check()?;
20492047 if modes.is_empty() {
@@ -2220,7 +2218,7 @@ pub(crate) fn encode_key_frame_inner(
22202218 (x, y),
22212219 BLOCK,
22222220 &search,
2223- &mode_bits(above_mode[c0], left_mode[r0]),
2221+ &mode_bits(above_mode[c0], left_mode[r0]), fctx,
22242222 );
22252223 cost_whole += search.lambda * partition_bits(BLOCK, false);
22262224 let after_whole = snapshot(&luma, &chroma, (x, y));
@@ -2253,7 +2251,7 @@ pub(crate) fn encode_key_frame_inner(
22532251 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
22542252 SUB,
22552253 &search,
2256- &mode_bits(above_mode[sc], left_mode[sr]),
2254+ &mode_bits(above_mode[sc], left_mode[sr]), fctx,
22572255 );
22582256 cost_split += cost;
22592257 split_modes.push(block.mode);
@@ -2284,7 +2282,7 @@ pub(crate) fn encode_key_frame_inner(
22842282 (leaf_x, leaf_y),
22852283 8,
22862284 &search,
2287- &leaf_mode_bits,
2285+ &leaf_mode_bits, fctx,
22882286 );
22892287 cost_split += cost;
22902288 split_modes.push(leaf.mode);
@@ -2500,7 +2498,7 @@ fn mc_trial(
25002498 skip: bool,
25012499 base_q_idx: u8,
25022500 deadzone: f64,
2503- set: TxbSet,
2501+ set: TxbSet, fctx: &crate::decode::FrameCtx,
25042502 ) -> Trial {
25052503 let x_q4 = mv_to_q4(x, mv.1, luma);
25062504 let y_q4 = mv_to_q4(y, mv.0, luma);
@@ -2517,7 +2515,7 @@ fn mc_trial(
25172515 y_q4,
25182516 side,
25192517 side,
2520- &mut prediction16,
2518+ &mut prediction16, fctx,
25212519 );
25222520 let prediction: Vec<u8> = prediction16.iter().map(|&v| v as u8).collect();
25232521 plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set)
@@ -2549,10 +2547,10 @@ fn search_inter_block(
25492547 search: &Search,
25502548 mode_bits: &[f64; 13],
25512549 reference: &Picture,
2552- stack: &MvStack,
2550+ stack: &MvStack, fctx: &crate::decode::FrameCtx,
25532551 ) -> BlockCoeffs {
25542552 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
2555- let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height);
2553+ let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
25562554
25572555 // skip / intra_inter symbol costs at a fixed context -- see this
25582556 // function's doc comment.
@@ -2596,7 +2594,7 @@ fn search_inter_block(
25962594 },
25972595 DC_PRED,
25982596 search.base_q_idx,
2599- search.deadzone,
2597+ search.deadzone, fctx,
26002598 );
26012599 let v_trial = chroma[1].trial(
26022600 At {
@@ -2608,7 +2606,7 @@ fn search_inter_block(
26082606 },
26092607 DC_PRED,
26102608 search.base_q_idx,
2611- search.deadzone,
2609+ search.deadzone, fctx,
26122610 );
26132611
26142612 let intra_modes: Vec<u8> = match search.top_k {
@@ -2623,7 +2621,7 @@ fn search_inter_block(
26232621 },
26242622 search.modes,
26252623 mode_bits,
2626- search.lambda,
2624+ search.lambda, fctx,
26272625 );
26282626 prune_by_sad(search.modes, scored, k)
26292627 }
@@ -2640,7 +2638,7 @@ fn search_inter_block(
26402638 },
26412639 mode,
26422640 search.base_q_idx,
2643- search.deadzone,
2641+ search.deadzone, fctx,
26442642 );
26452643 let u = u_trial.clone();
26462644 let v = v_trial.clone();
@@ -2716,7 +2714,7 @@ fn search_inter_block(
27162714 false,
27172715 search.base_q_idx,
27182716 search.deadzone,
2719- luma_set,
2717+ luma_set, fctx,
27202718 );
27212719 let u = mc_trial(
27222720 &chroma[0],
@@ -2732,7 +2730,7 @@ fn search_inter_block(
27322730 false,
27332731 search.base_q_idx,
27342732 search.deadzone,
2735- chroma_set,
2733+ chroma_set, fctx,
27362734 );
27372735 let v = mc_trial(
27382736 &chroma[1],
@@ -2748,7 +2746,7 @@ fn search_inter_block(
27482746 false,
27492747 search.base_q_idx,
27502748 search.deadzone,
2751- chroma_set,
2749+ chroma_set, fctx,
27522750 );
27532751 let skip = luma_trial.levels.iter().all(|&l| l == 0)
27542752 && u.levels.iter().all(|&l| l == 0)
@@ -2797,7 +2795,7 @@ fn search_inter_block(
27972795 BLOCK,
27982796 BLOCK,
27992797 stack.pred_mv,
2800- search.lambda,
2798+ search.lambda, fctx,
28012799 );
28022800 #[cfg(test)]
28032801 stage_add(0, t.elapsed());
@@ -2817,7 +2815,7 @@ fn search_inter_block(
28172815 false,
28182816 search.base_q_idx,
28192817 search.deadzone,
2820- luma_set,
2818+ luma_set, fctx,
28212819 );
28222820 let u = mc_trial(
28232821 &chroma[0],
@@ -2833,7 +2831,7 @@ fn search_inter_block(
28332831 false,
28342832 search.base_q_idx,
28352833 search.deadzone,
2836- chroma_set,
2834+ chroma_set, fctx,
28372835 );
28382836 let v = mc_trial(
28392837 &chroma[1],
@@ -2849,7 +2847,7 @@ fn search_inter_block(
28492847 false,
28502848 search.base_q_idx,
28512849 search.deadzone,
2852- chroma_set,
2850+ chroma_set, fctx,
28532851 );
28542852 let drl_bits = if stack.entries.len() > 1 {
28552853 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
@@ -2912,7 +2910,7 @@ pub(crate) fn encode_inter_frame(
29122910 base_q_idx: u8,
29132911 deadzone: f64,
29142912 order_hint: u32,
2915- render: (usize, usize),
2913+ render: (usize, usize), fctx: &crate::decode::FrameCtx,
29162914 ) -> Result<Encoded> {
29172915 picture.check()?;
29182916 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -3043,7 +3041,7 @@ pub(crate) fn encode_inter_frame(
30433041 &search,
30443042 &mode_bits_table,
30453043 reference,
3046- &stack,
3044+ &stack, fctx,
30473045 );
30483046
30493047 for dr in 0..8 {
@@ -3142,7 +3140,7 @@ pub(crate) fn encode_inter_frame(
31423140 &search,
31433141 &mode_bits_table,
31443142 reference,
3145- &stack,
3143+ &stack, fctx,
31463144 );
31473145 for dr in 0..4 {
31483146 for dc in 0..4 {
@@ -3202,7 +3200,7 @@ pub(crate) fn encode_inter_frame(
32023200 &search,
32033201 &mode_bits_table,
32043202 reference,
3205- &stack,
3203+ &stack, fctx,
32063204 );
32073205 for dr in 0..2 {
32083206 for dc in 0..2 {
@@ -3319,7 +3317,7 @@ pub struct EncodedSequence {
33193317 pub fn encode_sequence(
33203318 pictures: &[Picture],
33213319 base_q_idx: u8,
3322- deadzone: f64,
3320+ deadzone: f64, fctx: &crate::decode::FrameCtx,
33233321 ) -> Result<EncodedSequence> {
33243322 let Some((first, rest)) = pictures.split_first() else {
33253323 return Err(Error::unsupported(
@@ -3341,7 +3339,7 @@ pub fn encode_sequence(
33413339 &KEY_FRAME_MODES,
33423340 split_blocks(),
33433341 render,
3344- unspecified_color_config(),
3342+ unspecified_color_config(), fctx,
33453343 )?;
33463344 let mut stream = key.stream.clone();
33473345 let mut reference = key.reconstruction.clone();
@@ -3361,7 +3359,7 @@ pub fn encode_sequence(
33613359 base_q_idx,
33623360 deadzone,
33633361 order_hint,
3364- render,
3362+ render, fctx,
33653363 )?;
33663364 stream.extend_from_slice(&inter.stream);
33673365 reference = inter.reconstruction.clone();
@@ -3442,6 +3440,7 @@ mod tests {
34423440 /// (the horizontal shapes, which those partitions never produce).
34433441 #[test]
34443442 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
3443+ let fctx = &crate::decode::FrameCtx::new();
34453444 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
34463445 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
34473446 (4, 8, 64, 9280, 64, 550),
@@ -3469,7 +3468,7 @@ mod tests {
34693468 x: usize,
34703469 y: usize,
34713470 width: usize,
3472- height: usize,
3471+ height: usize, fctx: &crate::decode::FrameCtx,
34733472 ) -> (bool, bool) {
34743473 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
34753474 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
@@ -3518,8 +3517,8 @@ mod tests {
35183517 for sb_x in [0usize, 64] {
35193518 for y in (sb_y..sb_y + 64).step_by(bh) {
35203519 for x in (sb_x..sb_x + 64).step_by(bw) {
3521- let got = Reach::of_rect(bw, bh, x, y, 256, 256);
3522- let want = libaom_reach(bw, bh, x, y, 256, 256);
3520+ let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
3521+ let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
35233522 assert_eq!(
35243523 (got.above_right, got.below_left),
35253524 want,
@@ -3653,13 +3652,14 @@ mod tests {
36533652 /// which is why this is an equality and not a tolerance.
36543653 #[test]
36553654 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
3655+ let fctx = &crate::decode::FrameCtx::new();
36563656 if !have_ffmpeg() {
36573657 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
36583658 return;
36593659 }
36603660 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
36613661 let picture = test_card(width, height);
3662- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3662+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
36633663 let decoded = ffmpeg_decode(&encoded.stream, width, height);
36643664 assert_eq!(
36653665 decoded.y, encoded.reconstruction.y,
@@ -3673,7 +3673,7 @@ mod tests {
36733673 let (width, height) = (64usize, 64usize);
36743674 let picture = test_card(width, height);
36753675 for &q in &[15u8, 45, 100, 200] {
3676- let encoded = encode_key_frame(&picture, q, 0.5).unwrap();
3676+ let encoded = encode_key_frame(&picture, q, 0.5, fctx).unwrap();
36773677 let decoded = ffmpeg_decode(&encoded.stream, width, height);
36783678 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
36793679 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
@@ -3691,6 +3691,7 @@ mod tests {
36913691 /// same coefficient syntax decodes clean on every intra key-frame gate).
36923692 #[test]
36933693 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
3694+ let fctx = &crate::decode::FrameCtx::new();
36943695 if !have_ffmpeg() {
36953696 eprintln!(
36963697 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
@@ -3699,7 +3700,7 @@ mod tests {
36993700 }
37003701 let (width, height) = (64usize, 64usize);
37013702 let picture = Picture::grey(width, height);
3702- let key = encode_key_frame(&picture, 100, 0.5).unwrap();
3703+ let key = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
37033704
37043705 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
37053706 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
@@ -3810,6 +3811,7 @@ mod tests {
38103811 /// `ffprobe` is asserted to report below.
38113812 #[test]
38123813 fn a_frame_round_trips_at_its_own_size() {
3814+ let fctx = &crate::decode::FrameCtx::new();
38133815 if !have_ffmpeg() {
38143816 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
38153817 return;
@@ -3827,7 +3829,7 @@ mod tests {
38273829 (192, 120),
38283830 ] {
38293831 let picture = test_card(width, height);
3830- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3832+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
38313833 assert_eq!(
38323834 (encoded.reconstruction.width, encoded.reconstruction.height),
38333835 (width, height),
@@ -3875,12 +3877,13 @@ mod tests {
38753877 /// the header's own size before output).
38763878 #[test]
38773879 fn an_854x480_picture_round_trips_through_its_padding() {
3880+ let fctx = &crate::decode::FrameCtx::new();
38783881 if !have_ffmpeg() {
38793882 return;
38803883 }
38813884 let (width, height) = (854usize, 480usize);
38823885 let picture = test_card(width, height);
3883- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3886+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
38843887 let decoded = ffmpeg_decode(&encoded.stream, width, height);
38853888 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
38863889 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
@@ -3905,19 +3908,20 @@ mod tests {
39053908 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
39063909 #[test]
39073910 fn of_tu_follows_the_block_row_including_under_vert_ab() {
3911+ let fctx = &crate::decode::FrameCtx::new();
39083912 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
39093913 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
39103914 // above-right answer is the BLOCK's, which is the whole reason a unit
39113915 // asks the block instead of looking itself up (the
39123916 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
3913- let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);
3917+ let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
39143918 assert_eq!(
39153919 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
39163920 plain.above_right,
39173921 "ordinary table: the top-right TX4 unit takes the block's row"
39183922 );
39193923 let guard = Reach::vert_ab_partition();
3920- let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);
3924+ let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
39213925 assert_eq!(
39223926 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
39233927 vert.above_right,
@@ -3939,6 +3943,7 @@ mod tests {
39393943 /// wrong for one block size while looking plausible for the other.
39403944 #[test]
39413945 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
3946+ let fctx = &crate::decode::FrameCtx::new();
39423947 // Transcribed from has_top_right/has_bottom_left's row_off==0,
39433948 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
39443949 // 128px reference grid) pinned as libaom pins it, independent of the
@@ -3968,7 +3973,7 @@ mod tests {
39683973 (table[index / 8] >> (index % 8)) & 1 != 0
39693974 }
39703975
3971- fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize) -> bool {
3976+ fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, fctx: &crate::decode::FrameCtx) -> bool {
39723977 if x == 0 || y + side >= height {
39733978 return false;
39743979 }
@@ -3997,7 +4002,7 @@ mod tests {
39974002 for side in [16usize, BLOCK] {
39984003 for y in (0..height).step_by(side) {
39994004 for x in (0..width).step_by(side) {
4000- let reach = Reach::of(side, x, y, width, height);
4005+ let reach = Reach::of(side, x, y, width, height, fctx);
40014006 assert_eq!(
40024007 reach.above_right,
40034008 libaom_top_right(side, x, y, width, height),
@@ -4005,7 +4010,7 @@ mod tests {
40054010 );
40064011 assert_eq!(
40074012 reach.below_left,
4008- libaom_bottom_left(side, x, y, height),
4013+ libaom_bottom_left(side, x, y, height, fctx),
40094014 "side={side} x={x} y={y}: below_left"
40104015 );
40114016 }
@@ -4083,6 +4088,7 @@ mod tests {
40834088
40844089 #[test]
40854090 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
4091+ let fctx = &crate::decode::FrameCtx::new();
40864092 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
40874093 // Interior superblock, so neither the frame edge nor the col == 0 /
40884094 // last-row early returns answer instead of the table.
@@ -4091,10 +4097,10 @@ mod tests {
40914097 for row in 0..8 {
40924098 for col in 1..8 {
40934099 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
4094- let raster = Reach::of(8, x, y, width, height).below_left;
4100+ let raster = Reach::of(8, x, y, width, height, fctx).below_left;
40954101 let vert = {
40964102 let _guard = Reach::vert_ab_partition();
4097- Reach::of(8, x, y, width, height).below_left
4103+ Reach::of(8, x, y, width, height, fctx).below_left
40984104 };
40994105 // The TR square of a VERT_A/_B sits at an even row, odd
41004106 // column; every other slot must be untouched by the guard.
@@ -4109,16 +4115,17 @@ mod tests {
41094115 }
41104116 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
41114117 // 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);
4118+ assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
41134119 }
41144120
41154121 /// An odd width or height is refused by name, not by however the padder
41164122 /// or the block coder would happen to fail on it.
41174123 #[test]
41184124 fn odd_dimensions_are_refused() {
4125+ let fctx = &crate::decode::FrameCtx::new();
41194126 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
41204127 let picture = Picture::grey(width, height);
4121- let err = encode_key_frame(&picture, 100, 0.5)
4128+ let err = encode_key_frame(&picture, 100, 0.5, fctx)
41224129 .expect_err(&format!("{width}x{height} is odd and must be refused"));
41234130 assert!(
41244131 err.to_string().contains("even"),
@@ -4133,6 +4140,7 @@ mod tests {
41334140 /// own (padded) reconstruction.
41344141 #[test]
41354142 fn sequence_round_trips_at_a_non_multiple_size() {
4143+ let fctx = &crate::decode::FrameCtx::new();
41364144 if !have_ffmpeg() {
41374145 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
41384146 return;
@@ -4141,7 +4149,7 @@ mod tests {
41414149 let pictures: Vec<Picture> = (0..3)
41424150 .map(|i| panned_test_card(width, height, i * 3))
41434151 .collect();
4144- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4152+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
41454153 assert_eq!(encoded.frames.len(), 3);
41464154 for (i, frame) in encoded.frames.iter().enumerate() {
41474155 assert_eq!(
@@ -4175,6 +4183,7 @@ mod tests {
41754183 /// inter tile writer's parity with it across a real multi-frame export.
41764184 #[test]
41774185 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
4186+ let fctx = &crate::decode::FrameCtx::new();
41784187 if !have_ffmpeg() {
41794188 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
41804189 return;
@@ -4183,7 +4192,7 @@ mod tests {
41834192 let pictures: Vec<Picture> = (0..3)
41844193 .map(|i| panned_test_card(width, height, i * 3))
41854194 .collect();
4186- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4195+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
41874196 assert_eq!(encoded.frames.len(), 3);
41884197 for (i, frame) in encoded.frames.iter().enumerate() {
41894198 assert_eq!(
@@ -4219,14 +4228,15 @@ mod tests {
42194228 /// actually exercised).
42204229 #[test]
42214230 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
4231+ let fctx = &crate::decode::FrameCtx::new();
42224232 let (width, height) = (640usize, 360usize);
42234233 let picture = Picture::grey(width, height);
4224- encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle");
4234+ encode_key_frame(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
42254235
42264236 // `encode_sequence`'s second frame is the inter path: same size, now
42274237 // wired the same way.
42284238 let pictures = vec![picture.clone(), picture];
4229- encode_sequence(&pictures, 100, 0.5)
4239+ encode_sequence(&pictures, 100, 0.5, fctx)
42304240 .expect("inter frame now codes the mod-32==8 straddle too");
42314241 }
42324242
@@ -4237,6 +4247,7 @@ mod tests {
42374247 /// only encoder-clean.
42384248 #[test]
42394249 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
4250+ let fctx = &crate::decode::FrameCtx::new();
42404251 if !have_ffmpeg() {
42414252 eprintln!(
42424253 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
@@ -4247,7 +4258,7 @@ mod tests {
42474258 let (width, height) = (640usize, 360usize);
42484259 for shift in [0i64, 7, 19] {
42494260 let picture = panned_test_card(width, height, shift);
4250- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4261+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
42514262 let decoded = ffmpeg_decode(&encoded.stream, width, height);
42524263 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
42534264 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
@@ -4261,6 +4272,7 @@ mod tests {
42614272 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
42624273 #[test]
42634274 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
4275+ let fctx = &crate::decode::FrameCtx::new();
42644276 if !have_ffmpeg() {
42654277 eprintln!(
42664278 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
@@ -4271,7 +4283,7 @@ mod tests {
42714283 let pictures: Vec<Picture> = (0..4)
42724284 .map(|i| panned_test_card(width, height, i * 3))
42734285 .collect();
4274- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4286+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
42754287 assert_eq!(encoded.frames.len(), 4);
42764288 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
42774289 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
@@ -4319,6 +4331,7 @@ mod tests {
43194331 #[test]
43204332 #[ignore = "a sweep, not a gate"]
43214333 fn probe_lambda() {
4334+ let fctx = &crate::decode::FrameCtx::new();
43224335 let mut pictures = vec![
43234336 ("test card".to_string(), test_card(160, 96)),
43244337 ("stripes".to_string(), stripes(160, 96, true)),
@@ -4331,8 +4344,8 @@ mod tests {
43314344 }
43324345 }
43334346 for (name, picture) in pictures {
4334- let dc = ladder(&picture, &[DC_PRED]);
4335- let searched = ladder(&picture, &NON_DIRECTIONAL);
4347+ let dc = ladder(&picture, &[DC_PRED], fctx);
4348+ let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
43364349 println!(
43374350 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
43384351 bd_rate(&dc, &searched) * 100.0,
@@ -4349,8 +4362,9 @@ mod tests {
43494362 #[test]
43504363 #[ignore = "a sweep, not a gate"]
43514364 fn probe_ladder() {
4365+ let fctx = &crate::decode::FrameCtx::new();
43524366 for (name, picture) in sweep_pictures() {
4353- let all = ladder(&picture, &KEY_FRAME_MODES);
4367+ let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
43544368 let points = all
43554369 .iter()
43564370 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
@@ -4366,6 +4380,7 @@ mod tests {
43664380 #[test]
43674381 #[ignore = "a sweep, not a gate"]
43684382 fn probe_split() {
4383+ let fctx = &crate::decode::FrameCtx::new();
43694384 for (name, picture) in sweep_pictures() {
43704385 let ladder = |split: bool| {
43714386 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
@@ -4378,7 +4393,7 @@ mod tests {
43784393 &KEY_FRAME_MODES,
43794394 split,
43804395 (picture.width, picture.height),
4381- unspecified_color_config(),
4396+ unspecified_color_config(), fctx,
43824397 )
43834398 .unwrap();
43844399 (
@@ -4398,7 +4413,7 @@ mod tests {
43984413 &KEY_FRAME_MODES,
43994414 true,
44004415 (picture.width, picture.height),
4401- unspecified_color_config(),
4416+ unspecified_color_config(), fctx,
44024417 )
44034418 .unwrap()
44044419 .modes
@@ -4446,6 +4461,7 @@ mod tests {
44464461 /// over a whole picture and the reconstruction gated against ffmpeg.
44474462 #[test]
44484463 fn every_mode_decodes_to_what_the_encoder_predicted() {
4464+ let fctx = &crate::decode::FrameCtx::new();
44494465 if !have_ffmpeg() {
44504466 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
44514467 return;
@@ -4456,7 +4472,7 @@ mod tests {
44564472 for (width, height) in [(128, 96), (160, 96)] {
44574473 let picture = test_card(width, height);
44584474 for mode in KEY_FRAME_MODES {
4459- let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();
4475+ let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode], fctx).unwrap();
44604476 let decoded = ffmpeg_decode(&encoded.stream, width, height);
44614477 for (plane, ours, theirs, stride) in [
44624478 ("luma", &encoded.reconstruction.y, &decoded.y, width),
@@ -4483,6 +4499,7 @@ mod tests {
44834499 /// while leaving every fidelity gate intact.
44844500 #[test]
44854501 fn the_search_picks_the_direction_the_picture_runs() {
4502+ let fctx = &crate::decode::FrameCtx::new();
44864503 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
44874504 let picture = stripes(128, 96, vertical);
44884505 // Only the pair, because on stripes a third mode predicts exactly
@@ -4491,7 +4508,7 @@ mod tests {
44914508 // tie then goes to whichever is cheaper to name, which is not what
44924509 // this gate is about.
44934510 let encoded =
4494- encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap();
4511+ encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
44954512 // The first block of the picture has neither neighbour, so it
44964513 // cannot tell the modes apart; every other one can.
44974514 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
@@ -4536,11 +4553,11 @@ mod tests {
45364553
45374554 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
45384555 /// fidelity.
4539- fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> {
4556+ fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
45404557 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
45414558 .iter()
45424559 .map(|&q| {
4543- let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap();
4560+ let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes, fctx).unwrap();
45444561 (
45454562 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
45464563 (encoded.stream.len() as f64).log10(),
@@ -4557,13 +4574,14 @@ mod tests {
45574574 /// directional pair has.
45584575 #[test]
45594576 fn the_search_beats_dc_alone() {
4577+ let fctx = &crate::decode::FrameCtx::new();
45604578 for (name, picture, want) in [
45614579 ("test card", test_card(160, 96), -0.05),
45624580 ("stripes", stripes(160, 96, true), -0.40),
45634581 ] {
45644582 let saved = bd_rate(
4565- &ladder(&picture, &[DC_PRED]),
4566- &ladder(&picture, &NON_DIRECTIONAL),
4583+ &ladder(&picture, &[DC_PRED], fctx),
4584+ &ladder(&picture, &NON_DIRECTIONAL, fctx),
45674585 );
45684586 assert!(
45694587 saved < want,
@@ -4598,11 +4616,12 @@ mod tests {
45984616 #[test]
45994617 #[ignore = "a sweep, not a gate"]
46004618 fn probe_directional() {
4619+ let fctx = &crate::decode::FrameCtx::new();
46014620 for (name, picture) in sweep_pictures() {
4602- let dc = ladder(&picture, &[DC_PRED]);
4603- let flat = ladder(&picture, &NON_DIRECTIONAL);
4604- let all = ladder(&picture, &KEY_FRAME_MODES);
4605- let encoded = encode_key_frame(&picture, 90, 0.5).unwrap();
4621+ let dc = ladder(&picture, &[DC_PRED], fctx);
4622+ let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
4623+ let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
4624+ let encoded = encode_key_frame(&picture, 90, 0.5, fctx).unwrap();
46064625 let directional = encoded
46074626 .modes
46084627 .iter()
@@ -4646,8 +4665,8 @@ mod tests {
46464665
46474666 /// The mode picked by the most blocks of a picture, ignoring the first
46484667 /// block, which has no neighbours to tell the modes apart with.
4649- fn favourite_mode(picture: &Picture) -> (u8, usize, usize) {
4650- let encoded = encode_key_frame(picture, 100, 0.5).unwrap();
4668+ fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
4669+ let encoded = encode_key_frame(picture, 100, 0.5, fctx).unwrap();
46514670 let blocks = &encoded.modes[1..];
46524671 let mut counts = [0usize; 13];
46534672 for &mode in blocks {
@@ -4667,9 +4686,10 @@ mod tests {
46674686 /// the above row where it should read the left column, would swap these.
46684687 #[test]
46694688 fn the_search_picks_the_diagonal_the_picture_runs() {
4689+ let fctx = &crate::decode::FrameCtx::new();
46704690 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
46714691 let picture = diagonal(160, 96, down_right);
4672- let (mode, count, blocks) = favourite_mode(&picture);
4692+ let (mode, count, blocks) = favourite_mode(&picture, fctx);
46734693 assert_eq!(
46744694 mode, want,
46754695 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
@@ -4685,14 +4705,15 @@ mod tests {
46854705 /// it, which is what costing the mode symbol is for.
46864706 #[test]
46874707 fn the_diagonals_beat_the_modes_that_read_no_further() {
4708+ let fctx = &crate::decode::FrameCtx::new();
46884709 for (name, picture, want) in [
46894710 ("down-right", diagonal(160, 96, true), -0.20),
46904711 ("down-left", diagonal(160, 96, false), -0.20),
46914712 ("test card", test_card(160, 96), 0.01),
46924713 ] {
46934714 let saved = bd_rate(
4694- &ladder(&picture, &NON_DIRECTIONAL),
4695- &ladder(&picture, &KEY_FRAME_MODES),
4715+ &ladder(&picture, &NON_DIRECTIONAL, fctx),
4716+ &ladder(&picture, &KEY_FRAME_MODES, fctx),
46964717 );
46974718 assert!(
46984719 saved < want,
@@ -4707,15 +4728,16 @@ mod tests {
47074728 /// something else, and a search with nothing to choose from likewise.
47084729 #[test]
47094730 fn a_mode_the_encoder_cannot_predict_is_refused() {
4731+ let fctx = &crate::decode::FrameCtx::new();
47104732 let picture = test_card(64, 64);
4711- let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13])
4733+ let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13], fctx)
47124734 .unwrap_err()
47134735 .to_string();
47144736 assert!(
47154737 message.contains("intra mode 13"),
47164738 "the refusal must name the mode, got {message}"
47174739 );
4718- assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());
4740+ assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[], fctx).is_err());
47194741 }
47204742
47214743 /// The picture that comes back is the picture that went in, to within the
@@ -4725,8 +4747,9 @@ mod tests {
47254747 /// right picture.
47264748 #[test]
47274749 fn the_encoded_picture_is_the_one_that_went_in() {
4750+ let fctx = &crate::decode::FrameCtx::new();
47284751 let picture = test_card(160, 96);
4729- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4752+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
47304753 let luma = psnr(&encoded.reconstruction.y, &picture.y);
47314754 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
47324755 for (plane, (got, want)) in [
@@ -4746,10 +4769,11 @@ mod tests {
47464769 /// loop above this will assume.
47474770 #[test]
47484771 fn fidelity_and_rate_move_with_the_quantizer() {
4772+ let fctx = &crate::decode::FrameCtx::new();
47494773 let picture = test_card(128, 128);
47504774 let mut previous: Option<(usize, f64)> = None;
47514775 for &q in &[70u8, 90, 110] {
4752- let encoded = encode_key_frame(&picture, q, 0.5).unwrap();
4776+ let encoded = encode_key_frame(&picture, q, 0.5, fctx).unwrap();
47534777 let quality = psnr(&encoded.reconstruction.y, &picture.y);
47544778 if let Some((bytes, better)) = previous {
47554779 assert!(
@@ -4764,7 +4788,7 @@ mod tests {
47644788
47654789 let mut previous = None;
47664790 for &deadzone in &[0.5f64, 0.3, 0.15] {
4767- let encoded = encode_key_frame(&picture, 100, deadzone).unwrap();
4791+ let encoded = encode_key_frame(&picture, 100, deadzone, fctx).unwrap();
47684792 let quality = psnr(&encoded.reconstruction.y, &picture.y);
47694793 if let Some((bytes, better)) = previous {
47704794 assert!(
@@ -4782,8 +4806,8 @@ mod tests {
47824806 // even though a coarser quantizer always codes no more than a finer
47834807 // one on the same picture.
47844808 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
4785- let lo_bytes = encode_key_frame(&picture, lo, 0.5).unwrap().stream.len();
4786- let hi_bytes = encode_key_frame(&picture, hi, 0.5).unwrap().stream.len();
4809+ let lo_bytes = encode_key_frame(&picture, lo, 0.5, fctx).unwrap().stream.len();
4810+ let hi_bytes = encode_key_frame(&picture, hi, 0.5, fctx).unwrap().stream.len();
47874811 assert!(
47884812 hi_bytes <= lo_bytes,
47894813 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
@@ -4795,9 +4819,10 @@ mod tests {
47954819 /// average, which is the picture's own value, and codes nothing.
47964820 #[test]
47974821 fn a_flat_picture_costs_almost_nothing() {
4822+ let fctx = &crate::decode::FrameCtx::new();
47984823 let mut picture = Picture::grey(128, 128);
47994824 picture.y.fill(97);
4800- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4825+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
48014826 // The first block has no neighbour and predicts 128, so it carries a
48024827 // DC; every block after it predicts 97 and carries nothing.
48034828 assert!(
@@ -4824,14 +4849,15 @@ mod tests {
48244849 /// corrupting the stream.
48254850 #[test]
48264851 fn a_picture_off_the_block_grid_is_refused() {
4827- let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5)
4852+ let fctx = &crate::decode::FrameCtx::new();
4853+ let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5, fctx)
48284854 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")
48294855 .to_string();
48304856 assert!(msg.contains("rectangular"), "refusal: {msg}");
48314857
48324858 let mut short = Picture::grey(64, 64);
48334859 short.u.truncate(10);
4834- assert!(encode_key_frame(&short, 100, 0.5).is_err());
4860+ assert!(encode_key_frame(&short, 100, 0.5, fctx).is_err());
48354861 }
48364862
48374863 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
@@ -4906,13 +4932,14 @@ mod tests {
49064932 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
49074933 #[test]
49084934 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
4935+ let fctx = &crate::decode::FrameCtx::new();
49094936 if !have_ffmpeg() {
49104937 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
49114938 return;
49124939 }
49134940 let (width, height) = (40usize, 32usize);
49144941 let picture = test_card(width, height);
4915- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4942+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
49164943 assert_eq!(
49174944 (encoded.reconstruction.width, encoded.reconstruction.height),
49184945 (width, height)
@@ -4934,6 +4961,7 @@ mod tests {
49344961 /// synthetic pictures — real video reaches contexts a test card does not.
49354962 #[test]
49364963 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
4964+ let fctx = &crate::decode::FrameCtx::new();
49374965 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
49384966 eprintln!(
49394967 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
@@ -4953,7 +4981,7 @@ mod tests {
49534981 let (width, height) = (640usize, 352usize);
49544982 let picture = clip_frame(&clip, &skip, width, height);
49554983
4956- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4984+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
49574985 let decoded = ffmpeg_decode(&encoded.stream, width, height);
49584986 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
49594987 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
@@ -5064,6 +5092,7 @@ mod tests {
50645092 /// just the last one, and why this is an equality and not a tolerance.
50655093 #[test]
50665094 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
5095+ let fctx = &crate::decode::FrameCtx::new();
50675096 if !have_ffmpeg() {
50685097 eprintln!(
50695098 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
@@ -5074,7 +5103,7 @@ mod tests {
50745103 let pictures: Vec<Picture> = (0..5)
50755104 .map(|i| panned_test_card(width, height, i * 3))
50765105 .collect();
5077- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
5106+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
50785107 assert_eq!(encoded.frames.len(), 5);
50795108
50805109 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
@@ -5104,11 +5133,12 @@ mod tests {
51045133 /// asserted on beyond being reachable at all.
51055134 #[test]
51065135 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
5136+ let fctx = &crate::decode::FrameCtx::new();
51075137 let (width, height) = (256usize, 128usize);
51085138 let pictures: Vec<Picture> = (0..5)
51095139 .map(|i| panned_test_card(width, height, i * 2))
51105140 .collect();
5111- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
5141+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
51125142
51135143 let key_bytes = encoded.frames[0].stream.len();
51145144 eprintln!("frame bytes inter share");
@@ -5140,22 +5170,23 @@ mod tests {
51405170 #[test]
51415171 #[ignore = "a perf probe, not a gate"]
51425172 fn stage_timing_breakdown() {
5173+ let fctx = &crate::decode::FrameCtx::new();
51435174 use std::time::Instant;
51445175
51455176 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
51465177 let picture = test_card(width, height);
51475178
51485179 let t = Instant::now();
5149- let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap();
5180+ let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
51505181 let dc_only_t = t.elapsed();
51515182
51525183 let t = Instant::now();
51535184 let non_directional =
5154- encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap();
5185+ encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
51555186 let non_directional_t = t.elapsed();
51565187
51575188 let t = Instant::now();
5158- let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap();
5189+ let all_modes = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
51595190 let all_modes_t = t.elapsed();
51605191
51615192 eprintln!(
@@ -5175,7 +5206,7 @@ mod tests {
51755206 let padded_pic = picture.padded_to(SUPERBLOCK);
51765207 let t = Instant::now();
51775208 let inter =
5178- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
5209+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
51795210 let inter_t = t.elapsed();
51805211 eprintln!(
51815212 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -5233,7 +5264,7 @@ mod tests {
52335264 side,
52345265 false,
52355266 false,
5236- &mut prediction,
5267+ &mut prediction, fctx,
52375268 );
52385269 }
52395270 let predict_t = t.elapsed() / N;
@@ -5261,18 +5292,19 @@ mod tests {
52615292 #[test]
52625293 #[ignore = "a perf probe, not a gate"]
52635294 fn stage_timing_breakdown_inter() {
5295+ let fctx = &crate::decode::FrameCtx::new();
52645296 use std::time::Instant;
52655297
52665298 let (width, height) = (1280usize, 720);
52675299 let picture = test_card(width, height);
5268- let key = encode_key_frame(&picture, 100, 0.5).unwrap();
5300+ let key = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
52695301 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
52705302 let padded_pic = picture.padded_to(SUPERBLOCK);
52715303
52725304 stage_reset();
52735305 let t = Instant::now();
52745306 let inter =
5275- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
5307+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
52765308 let total_t = t.elapsed();
52775309 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
52785310 let accounted = motion_search + transform_quant + entropy;
@@ -5308,6 +5340,7 @@ mod tests {
53085340 #[test]
53095341 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
53105342 fn prune_k_quality_sweep() {
5343+ let fctx = &crate::decode::FrameCtx::new();
53115344 if !have_ffmpeg() {
53125345 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
53135346 return;
@@ -5343,7 +5376,7 @@ mod tests {
53435376 // a single-threaded #[ignore] probe, run by hand, never
53445377 // alongside other tests that read Search::top_k.
53455378 set_test_top_k_override(None);
5346- let baseline = encode_key_frame(&picture, q, 0.5).unwrap();
5379+ let baseline = encode_key_frame(&picture, q, 0.5, fctx).unwrap();
53475380 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
53485381 eprint!(
53495382 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
@@ -5352,7 +5385,7 @@ mod tests {
53525385 );
53535386 for &k in &[3usize, 4, 6] {
53545387 set_test_top_k_override(Some(k));
5355- let pruned = encode_key_frame(&picture, q, 0.5).unwrap();
5388+ let pruned = encode_key_frame(&picture, q, 0.5, fctx).unwrap();
53565389 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
53575390 eprint!(
53585391 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
@@ -5407,6 +5440,7 @@ mod tests {
54075440 #[test]
54085441 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
54095442 fn prune_k_quality_sweep_inter() {
5443+ let fctx = &crate::decode::FrameCtx::new();
54105444 if !have_ffmpeg() {
54115445 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
54125446 return;
@@ -5440,14 +5474,14 @@ mod tests {
54405474 // single-threaded #[ignore] probe, run by hand, never
54415475 // alongside other tests that read Search::top_k.
54425476 set_test_top_k_override_inter(None);
5443- let key = encode_key_frame(&key_source, q, 0.5).unwrap();
5477+ let key = encode_key_frame(&key_source, q, 0.5, fctx).unwrap();
54445478 let baseline = encode_inter_frame(
54455479 &inter_source,
54465480 &key.reconstruction,
54475481 q,
54485482 0.5,
54495483 1,
5450- (width, height),
5484+ (width, height), fctx,
54515485 )
54525486 .unwrap();
54535487 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -5464,7 +5498,7 @@ mod tests {
54645498 q,
54655499 0.5,
54665500 1,
5467- (width, height),
5501+ (width, height), fctx,
54685502 )
54695503 .unwrap();
54705504 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
@@ -5544,6 +5578,7 @@ mod tests {
55445578 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
55455579 #[test]
55465580 fn real_clip_encodes_within_its_quality_and_size_budget() {
5581+ let fctx = &crate::decode::FrameCtx::new();
55475582 if !have_ffmpeg() {
55485583 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
55495584 return;
@@ -5559,7 +5594,7 @@ mod tests {
55595594 }
55605595 let (width, height, frame_count) = (640usize, 384usize, 12usize);
55615596 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
5562- let encoded = encode_sequence(&source, 100, 0.5).unwrap();
5597+ let encoded = encode_sequence(&source, 100, 0.5, fctx).unwrap();
55635598 assert_eq!(encoded.frames.len(), frame_count);
55645599
55655600 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
@@ -5604,6 +5639,7 @@ mod tests {
56045639 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
56055640 #[test]
56065641 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
5642+ let fctx = &crate::decode::FrameCtx::new();
56075643 if !have_ffmpeg() {
56085644 eprintln!(
56095645 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
@@ -5623,7 +5659,7 @@ mod tests {
56235659 }
56245660 let (width, height, frame_count) = (704usize, 400usize, 8usize);
56255661 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
5626- let encoded = encode_sequence(&source, 100, 0.5).unwrap();
5662+ let encoded = encode_sequence(&source, 100, 0.5, fctx).unwrap();
56275663 assert_eq!(encoded.frames.len(), frame_count);
56285664
56295665 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
@@ -5660,13 +5696,14 @@ mod tests {
56605696 #[test]
56615697 #[ignore = "a perf probe, not a gate"]
56625698 fn sequence_bench_sanity() {
5699+ let fctx = &crate::decode::FrameCtx::new();
56635700 use std::time::Instant;
56645701 let (width, height) = (1280usize, 720usize);
56655702 let pictures: Vec<Picture> = (0..24)
56665703 .map(|i| panned_test_card(width, height, i * 3))
56675704 .collect();
56685705 let t = Instant::now();
5669- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
5706+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
56705707 let elapsed = t.elapsed();
56715708 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
56725709 eprintln!(
@@ -5682,6 +5719,7 @@ mod tests {
56825719 #[test]
56835720 #[ignore = "a calibration probe, not a gate"]
56845721 fn calibration_sweep_base_q_idx() {
5722+ let fctx = &crate::decode::FrameCtx::new();
56855723 if !have_ffmpeg() {
56865724 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
56875725 return;
@@ -5701,7 +5739,7 @@ mod tests {
57015739 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
57025740 eprintln!("--- {clip} ---");
57035741 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
5704- let encoded = encode_sequence(&source, q, 0.5).unwrap();
5742+ let encoded = encode_sequence(&source, q, 0.5, fctx).unwrap();
57055743 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
57065744 let mean_psnr: f64 = decoded
57075745 .iter()
crates/ec-av1/src/encoder.rsmodified+21 -12
@@ -297,7 +297,7 @@ impl Av1Encoder {
297297 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same
298298 /// conditions [`crate::encode::encode_key_frame`]/
299299 /// [`crate::encode::encode_sequence`] do.
300- pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
300+ pub fn encode(&mut self, picture: &Picture, fctx: &crate::decode::FrameCtx) -> Result<Packet> {
301301 if (picture.width, picture.height) != (self.config.width, self.config.height) {
302302 return Err(Error::unsupported(
303303 "AV1 encode",
@@ -324,7 +324,7 @@ impl Av1Encoder {
324324 &KEY_FRAME_MODES,
325325 split_blocks(),
326326 render,
327- self.color_config,
327+ self.color_config, fctx,
328328 )?
329329 } else {
330330 let reference = self.reference.as_ref().ok_or_else(|| {
@@ -339,7 +339,7 @@ impl Av1Encoder {
339339 base_q_idx,
340340 DEADZONE,
341341 order as u32,
342- render,
342+ render, fctx,
343343 )?
344344 };
345345
@@ -414,6 +414,7 @@ mod tests {
414414 /// ffmpeg since it is a property of the return type, not the bytes.
415415 #[test]
416416 fn one_in_one_out() {
417+ let fctx = &crate::decode::FrameCtx::new();
417418 let config = EncoderConfig {
418419 width: 64,
419420 height: 64,
@@ -423,7 +424,7 @@ mod tests {
423424 };
424425 let mut enc = Av1Encoder::new(config).unwrap();
425426 for t in 0..5u64 {
426- let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
427+ let packet = enc.encode(&test_card(64, 64, t as usize), fctx).unwrap();
427428 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
428429 assert_eq!(packet.order, t, "picture {t}: order");
429430 }
@@ -434,6 +435,7 @@ mod tests {
434435 /// reads back out of the coded bytes.
435436 #[test]
436437 fn gop_cadence_is_honored() {
438+ let fctx = &crate::decode::FrameCtx::new();
437439 let config = EncoderConfig {
438440 width: 64,
439441 height: 64,
@@ -443,7 +445,7 @@ mod tests {
443445 };
444446 let mut enc = Av1Encoder::new(config).unwrap();
445447 let keys: Vec<bool> = (0..7)
446- .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
448+ .map(|t| enc.encode(&test_card(64, 64, t), fctx).unwrap().key)
447449 .collect();
448450 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
449451 }
@@ -527,6 +529,7 @@ mod tests {
527529 /// coded size confirm what the facade already reported.
528530 #[test]
529531 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
532+ let fctx = &crate::decode::FrameCtx::new();
530533 if !have_ffmpeg() {
531534 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
532535 return;
@@ -551,7 +554,7 @@ mod tests {
551554 );
552555
553556 let packets: Vec<Packet> = (0..30)
554- .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
557+ .map(|t| enc.encode(&test_card(width, height, t), fctx).unwrap())
555558 .collect();
556559 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
557560 assert_eq!(
@@ -581,6 +584,7 @@ mod tests {
581584 /// which is a visibly different string).
582585 #[test]
583586 fn bt709_limited_colour_is_reported_by_ffprobe() {
587+ let fctx = &crate::decode::FrameCtx::new();
584588 if !have_ffmpeg() {
585589 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
586590 return;
@@ -593,7 +597,7 @@ mod tests {
593597 colour: Colour::Bt709Limited,
594598 };
595599 let mut enc = Av1Encoder::new(config).unwrap();
596- let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
600+ let packet = enc.encode(&test_card(64, 64, 0), fctx).unwrap();
597601 let colour = ffprobe_colour(&packet.data);
598602 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
599603 }
@@ -603,6 +607,7 @@ mod tests {
603607 /// as BT.709 for every input.
604608 #[test]
605609 fn bt601_limited_colour_is_reported_by_ffprobe() {
610+ let fctx = &crate::decode::FrameCtx::new();
606611 if !have_ffmpeg() {
607612 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
608613 return;
@@ -615,7 +620,7 @@ mod tests {
615620 colour: Colour::Bt601Limited,
616621 };
617622 let mut enc = Av1Encoder::new(config).unwrap();
618- let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
623+ let packet = enc.encode(&test_card(64, 64, 0), fctx).unwrap();
619624 let colour = ffprobe_colour(&packet.data);
620625 assert_eq!(
621626 colour, "tv,smpte170m,smpte170m,smpte170m",
@@ -627,6 +632,7 @@ mod tests {
627632 /// is refused by name.
628633 #[test]
629634 fn geometry_mismatch_is_refused() {
635+ let fctx = &crate::decode::FrameCtx::new();
630636 let config = EncoderConfig {
631637 width: 64,
632638 height: 64,
@@ -635,7 +641,7 @@ mod tests {
635641 colour: Colour::Bt709Limited,
636642 };
637643 let mut enc = Av1Encoder::new(config).unwrap();
638- let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
644+ let err = enc.encode(&Picture::grey(32, 32), fctx).unwrap_err();
639645 assert!(err.to_string().contains("64x64"), "{err}");
640646 }
641647
@@ -708,6 +714,7 @@ mod tests {
708714 /// state and the controller's first couple of steps).
709715 #[test]
710716 fn bytes_per_frame_target_settles_within_20_percent() {
717+ let fctx = &crate::decode::FrameCtx::new();
711718 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
712719 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
713720 return;
@@ -724,7 +731,7 @@ mod tests {
724731 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
725732 let sizes: Vec<usize> = pictures
726733 .iter()
727- .map(|p| enc.encode(p).unwrap().data.len())
734+ .map(|p| enc.encode(p, fctx).unwrap().data.len())
728735 .collect();
729736 // Discard the key frame (always far larger than an inter target) and
730737 // the next 4 inter frames the loop needs to step toward it.
@@ -744,6 +751,7 @@ mod tests {
744751 /// that breaks the bound).
745752 #[test]
746753 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
754+ let fctx = &crate::decode::FrameCtx::new();
747755 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
748756 eprintln!(
749757 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
@@ -761,7 +769,7 @@ mod tests {
761769 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
762770 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();
763771 for picture in &pictures {
764- enc.encode(picture).unwrap();
772+ enc.encode(picture, fctx).unwrap();
765773 let q = enc.rate_loop.as_ref().unwrap().q_idx();
766774 let step = (i32::from(q) - i32::from(prev_q)).abs();
767775 assert!(
@@ -824,6 +832,7 @@ mod tests {
824832 /// the same real clip.
825833 #[test]
826834 fn quality_target_is_monotone_in_bytes_and_psnr() {
835+ let fctx = &crate::decode::FrameCtx::new();
827836 if !have_ffmpeg() {
828837 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
829838 return;
@@ -848,7 +857,7 @@ mod tests {
848857 let mut stream = Vec::new();
849858 let mut total_bytes = 0usize;
850859 for picture in &pictures {
851- let packet = enc.encode(picture).unwrap();
860+ let packet = enc.encode(picture, fctx).unwrap();
852861 total_bytes += packet.data.len();
853862 stream.extend_from_slice(&packet.data);
854863 }
crates/ec-av1/src/film_grain.rsmodified+45 -47
@@ -13,6 +13,7 @@
1313 //! the frame it pushes onto its output `Vec<Picture>`, after saving the
1414 //! clean decode into the reference slot bank.
1515
16+use crate::decode::WithRef;
1617 use crate::encode::Picture;
1718 use ec_av1_syntax::FilmGrainParams;
1819
@@ -43,23 +44,20 @@ const LUMA_BLOCK_W: i32 =
4344 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
4445 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
4546
46-thread_local! {
4747 /// `params->bit_depth` of the picture currently being grained. libaom
4848 /// keeps `grain_min`/`grain_max` as file statics set once per
4949 /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors
5050 /// 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-}
5351
5452 /// `params->bit_depth` for the [`apply_grain`] call in progress.
55-fn grain_bit_depth() -> u32 {
56- GRAIN_BIT_DEPTH.with(|c| c.get())
53+fn grain_bit_depth(fctx: &crate::decode::FrameCtx) -> u32 {
54+ fctx.grain_bit_depth.with(|c| c.get())
5755 }
5856
5957 /// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`):
6058 /// `grain_center = 128 << (bit_depth - 8)`.
61-fn grain_range() -> (i32, i32) {
62- let center = 128i32 << (grain_bit_depth() - 8);
59+fn grain_range(fctx: &crate::decode::FrameCtx) -> (i32, i32) {
60+ let center = 128i32 << (grain_bit_depth(fctx) - 8);
6361 (-center, center - 1)
6462 }
6563
@@ -135,14 +133,14 @@ fn build_pred_pos(lag: i32, has_luma_avg: bool) -> Vec<(i32, i32, i32)> {
135133 fn generate_luma_grain_block(
136134 fg: &FilmGrainParams,
137135 pred_pos: &[(i32, i32, i32)],
138- rng: &mut Rng,
136+ rng: &mut Rng, fctx: &crate::decode::FrameCtx,
139137 ) -> Vec<i32> {
140- let (grain_min, grain_max) = grain_range();
138+ let (grain_min, grain_max) = grain_range(fctx);
141139 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
142140 if fg.num_y_points == 0 {
143141 return block;
144142 }
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;
146144 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
147145 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
148146
@@ -172,12 +170,12 @@ fn generate_chroma_grain_blocks(
172170 fg: &FilmGrainParams,
173171 pred_pos: &[(i32, i32, i32)],
174172 luma_block: &[i32],
175- seed: u16,
173+ seed: u16, fctx: &crate::decode::FrameCtx,
176174 ) -> (Vec<i32>, Vec<i32>) {
177- let (grain_min, grain_max) = grain_range();
175+ let (grain_min, grain_max) = grain_range(fctx);
178176 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
179177 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;
181179 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
182180 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
183181
@@ -336,12 +334,12 @@ fn add_noise_to_block(
336334 cg_row0: i32,
337335 cg_col0: i32,
338336 half_h: i32,
339- half_w: i32,
337+ half_w: i32, fctx: &crate::decode::FrameCtx,
340338 ) {
341339 let y_stride = picture.width as i32;
342340 let c_stride = (picture.width / 2) as i32;
343341 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);
345343 let bd_shift = bit_depth - 8;
346344 // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp.
347345 let index_max = (256i32 << bd_shift) - 1;
@@ -700,9 +698,9 @@ fn ver_overlap_inplace(
700698 right_row0: i32,
701699 right_col0: i32,
702700 width: i32,
703- height: i32,
701+ height: i32, fctx: &crate::decode::FrameCtx,
704702 ) {
705- let (grain_min, grain_max) = grain_range();
703+ let (grain_min, grain_max) = grain_range(fctx);
706704 for h in 0..height {
707705 if width == 1 {
708706 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -750,9 +748,9 @@ fn hor_overlap_inplace(
750748 bot_row0: i32,
751749 bot_col0: i32,
752750 width: i32,
753- height: i32,
751+ height: i32, fctx: &crate::decode::FrameCtx,
754752 ) {
755- let (grain_min, grain_max) = grain_range();
753+ let (grain_min, grain_max) = grain_range(fctx);
756754 if height == 1 {
757755 for w in 0..width {
758756 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);
@@ -800,9 +798,9 @@ fn copy_area(
800798 src_row0: i32,
801799 src_col0: i32,
802800 width: i32,
803- height: i32,
801+ height: i32, fctx: &crate::decode::FrameCtx,
804802 ) {
805- let (grain_min, grain_max) = grain_range();
803+ let (grain_min, grain_max) = grain_range(fctx);
806804 for h in 0..height {
807805 for w in 0..width {
808806 let v = at(src, src_stride, src_row0 + h, src_col0 + w);
@@ -830,13 +828,13 @@ pub(crate) fn apply_grain(
830828 picture: &Picture,
831829 fg: &FilmGrainParams,
832830 mc_identity: bool,
833- bit_depth: u32,
831+ bit_depth: u32, fctx: &crate::decode::FrameCtx,
834832 ) -> Picture {
835833 let mut out = picture.clone();
836834 if !fg.apply_grain {
837835 return out;
838836 }
839- GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth));
837+ fctx.grain_bit_depth.with(|c| c.set(bit_depth));
840838 GRAIN_HITS.with(|c| c.set(c.get() + 1));
841839 let width = out.width as i32;
842840 let height = out.height as i32;
@@ -848,9 +846,9 @@ pub(crate) fn apply_grain(
848846 let pred_chroma = build_pred_pos(lag, fg.num_y_points > 0);
849847
850848 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);
852850 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);
854852
855853 let scaling_y = build_scaling_lut(
856854 &fg.point_y_value,
@@ -874,7 +872,7 @@ pub(crate) fn apply_grain(
874872 )
875873 };
876874
877- let expand_bd = grain_bit_depth();
875+ let expand_bd = grain_bit_depth(fctx);
878876 let scaling_y = expand_scaling_lut(&scaling_y, expand_bd);
879877 let scaling_cb = expand_scaling_lut(&scaling_cb, expand_bd);
880878 let scaling_cr = expand_scaling_lut(&scaling_cr, expand_bd);
@@ -914,7 +912,7 @@ pub(crate) fn apply_grain(
914912 luma_off_y,
915913 luma_off_x,
916914 2,
917- h_count,
915+ h_count, fctx,
918916 );
919917 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
920918 ver_overlap_inplace(
@@ -927,7 +925,7 @@ pub(crate) fn apply_grain(
927925 chroma_off_y,
928926 chroma_off_x,
929927 1,
930- hc_count,
928+ hc_count, fctx,
931929 );
932930 ver_overlap_inplace(
933931 &mut cr_col_buf,
@@ -939,7 +937,7 @@ pub(crate) fn apply_grain(
939937 chroma_off_y,
940938 chroma_off_x,
941939 1,
942- hc_count,
940+ hc_count, fctx,
943941 );
944942
945943 let i = if y != 0 { 1 } else { 0 };
@@ -962,7 +960,7 @@ pub(crate) fn apply_grain(
962960 i,
963961 0,
964962 (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i,
965- 1,
963+ 1, fctx,
966964 );
967965 }
968966
@@ -978,7 +976,7 @@ pub(crate) fn apply_grain(
978976 0,
979977 0,
980978 2,
981- 2,
979+ 2, fctx,
982980 );
983981 hor_overlap_inplace(
984982 &mut cb_line_buf,
@@ -990,7 +988,7 @@ pub(crate) fn apply_grain(
990988 0,
991989 0,
992990 1,
993- 1,
991+ 1, fctx,
994992 );
995993 hor_overlap_inplace(
996994 &mut cr_line_buf,
@@ -1002,7 +1000,7 @@ pub(crate) fn apply_grain(
10021000 0,
10031001 0,
10041002 1,
1005- 1,
1003+ 1, fctx,
10061004 );
10071005 }
10081006 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
@@ -1018,7 +1016,7 @@ pub(crate) fn apply_grain(
10181016 luma_off_y,
10191017 luma_off_x + if x != 0 { 2 } else { 0 },
10201018 lw,
1021- 2,
1019+ 2, fctx,
10221020 );
10231021 let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1);
10241022 hor_overlap_inplace(
@@ -1031,7 +1029,7 @@ pub(crate) fn apply_grain(
10311029 chroma_off_y,
10321030 chroma_off_x + if x != 0 { 1 } else { 0 },
10331031 cw,
1034- 1,
1032+ 1, fctx,
10351033 );
10361034 hor_overlap_inplace(
10371035 &mut cr_line_buf,
@@ -1043,7 +1041,7 @@ pub(crate) fn apply_grain(
10431041 chroma_off_y,
10441042 chroma_off_x + if x != 0 { 1 } else { 0 },
10451043 cw,
1046- 1,
1044+ 1, fctx,
10471045 );
10481046
10491047 add_noise_to_block(
@@ -1065,7 +1063,7 @@ pub(crate) fn apply_grain(
10651063 0,
10661064 x,
10671065 1,
1068- (LUMA_SUBBLOCK >> 1).min(width / 2 - x),
1066+ (LUMA_SUBBLOCK >> 1).min(width / 2 - x), fctx,
10691067 );
10701068 }
10711069
@@ -1090,7 +1088,7 @@ pub(crate) fn apply_grain(
10901088 chroma_off_y + i,
10911089 chroma_off_x + j,
10921090 (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,
10941092 );
10951093
10961094 if overlap {
@@ -1105,7 +1103,7 @@ pub(crate) fn apply_grain(
11051103 LUMA_SUBBLOCK,
11061104 0,
11071105 2,
1108- 2,
1106+ 2, fctx,
11091107 );
11101108 copy_area(
11111109 &mut cb_line_buf,
@@ -1117,7 +1115,7 @@ pub(crate) fn apply_grain(
11171115 CHROMA_SUBBLOCK,
11181116 0,
11191117 1,
1120- 1,
1118+ 1, fctx,
11211119 );
11221120 copy_area(
11231121 &mut cr_line_buf,
@@ -1129,7 +1127,7 @@ pub(crate) fn apply_grain(
11291127 CHROMA_SUBBLOCK,
11301128 0,
11311129 1,
1132- 1,
1130+ 1, fctx,
11331131 );
11341132 }
11351133 let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 };
@@ -1146,7 +1144,7 @@ pub(crate) fn apply_grain(
11461144 luma_off_y + LUMA_SUBBLOCK,
11471145 luma_off_x + lcut,
11481146 LUMA_SUBBLOCK.min(width - (x << 1)) - lcut,
1149- 2,
1147+ 2, fctx,
11501148 );
11511149 copy_area(
11521150 &mut cb_line_buf,
@@ -1158,7 +1156,7 @@ pub(crate) fn apply_grain(
11581156 chroma_off_y + CHROMA_SUBBLOCK,
11591157 chroma_off_x + ccut,
11601158 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1161- 1,
1159+ 1, fctx,
11621160 );
11631161 copy_area(
11641162 &mut cr_line_buf,
@@ -1170,7 +1168,7 @@ pub(crate) fn apply_grain(
11701168 chroma_off_y + CHROMA_SUBBLOCK,
11711169 chroma_off_x + ccut,
11721170 CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut,
1173- 1,
1171+ 1, fctx,
11741172 );
11751173
11761174 let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1));
@@ -1184,7 +1182,7 @@ pub(crate) fn apply_grain(
11841182 luma_off_y,
11851183 luma_off_x + LUMA_SUBBLOCK,
11861184 2,
1187- h_count,
1185+ h_count, fctx,
11881186 );
11891187 let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1);
11901188 copy_area(
@@ -1197,7 +1195,7 @@ pub(crate) fn apply_grain(
11971195 chroma_off_y,
11981196 chroma_off_x + CHROMA_SUBBLOCK,
11991197 1,
1200- hc_count,
1198+ hc_count, fctx,
12011199 );
12021200 copy_area(
12031201 &mut cr_col_buf,
@@ -1209,7 +1207,7 @@ pub(crate) fn apply_grain(
12091207 chroma_off_y,
12101208 chroma_off_x + CHROMA_SUBBLOCK,
12111209 1,
1212- hc_count,
1210+ hc_count, fctx,
12131211 );
12141212 }
12151213
crates/ec-av1/src/intra.rsmodified+25 -23
@@ -149,7 +149,7 @@ impl Edges {
149149 left: Option<&[u16]>,
150150 corner: Option<u16>,
151151 bw: usize,
152- bh: usize,
152+ bh: usize, fctx: &crate::decode::FrameCtx,
153153 ) -> Self {
154154 let want = bw + bh;
155155 let extend = |samples: &[u16]| {
@@ -166,7 +166,7 @@ impl Edges {
166166 // comment block, lane-tiny r1; an earlier attempt at this fix used
167167 // 127/129 for the corner instead and made a passing 16x16 fixture
168168 // 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);
170170 let above_row = match (above, left) {
171171 (Some(a), _) => extend(a),
172172 (None, Some(l)) => vec![i32::from(l[0]); want],
@@ -272,7 +272,7 @@ pub fn predict(
272272 bh: usize,
273273 enable_edge_filter: bool,
274274 smooth_neighbor: bool,
275- dst: &mut [u16],
275+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
276276 ) {
277277 assert_eq!(dst.len(), bw * bh, "the destination is the block");
278278 match mode {
@@ -282,7 +282,7 @@ pub fn predict(
282282 PAETH_PRED => PAETH_PRED_HITS.with(|c| c.set(c.get() + 1)),
283283 _ => {}
284284 }
285- let edges = Edges::build(above, left, corner, bw, bh);
285+ let edges = Edges::build(above, left, corner, bw, bh, fctx);
286286 let is_directional = matches!(
287287 mode,
288288 V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
@@ -306,7 +306,7 @@ pub fn predict(
306306 smooth_neighbor,
307307 n_top,
308308 n_left,
309- dst,
309+ dst, fctx,
310310 );
311311 return;
312312 }
@@ -323,7 +323,7 @@ pub fn predict(
323323 let last_w = bw as i32 - 1;
324324 let last_h = bh as i32 - 1;
325325 let value = match mode {
326- DC_PRED => dc(above, left, bw, bh),
326+ DC_PRED => dc(above, left, bw, bh, fctx),
327327 V_PRED => edges.above(c),
328328 H_PRED => edges.left(r),
329329 SMOOTH_PRED => round2(
@@ -346,7 +346,7 @@ pub fn predict(
346346 PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),
347347 other => panic!("intra mode {other} is not one this module predicts"),
348348 };
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;
350350 }
351351 }
352352 }
@@ -463,7 +463,7 @@ fn filter_intra_edge(buf: &mut [i32], strength: i32) {
463463 /// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between
464464 /// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled
465465 /// slot.
466-fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {
466+fn upsample_intra_edge(buf: &[i32], fctx: &crate::decode::FrameCtx) -> Vec<i32> {
467467 let sz = buf.len() - 1;
468468 let mut inp = vec![0i32; sz + 3];
469469 inp[0] = buf[0];
@@ -474,7 +474,7 @@ fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {
474474 out[0] = inp[0];
475475 for i in 0..sz {
476476 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));
478478 out[2 * i + 2] = inp[i + 2];
479479 }
480480 out
@@ -495,7 +495,7 @@ fn directional(
495495 smooth_neighbor: bool,
496496 n_top: usize,
497497 n_left: usize,
498- dst: &mut [u16],
498+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
499499 ) {
500500 let (w, h) = (bw as i32, bh as i32);
501501 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.
@@ -541,7 +541,7 @@ fn directional(
541541 let above_up;
542542 let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above {
543543 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);
545545 (&above_up, 2)
546546 } else {
547547 (&above, 1)
@@ -549,7 +549,7 @@ fn directional(
549549 let left_up;
550550 let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left {
551551 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);
553553 (&left_up, 2)
554554 } else {
555555 (&left, 1)
@@ -608,7 +608,7 @@ fn directional(
608608 blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)
609609 }
610610 };
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;
612612 }
613613 }
614614 }
@@ -622,7 +622,7 @@ fn directional(
622622 /// before `dc_predictor` averages, so a slice truncated short by the true
623623 /// frame edge must be extended by repetition here too, not averaged over its
624624 /// 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 {
626626 // lane-perf4: the replication is only ever *summed*, never indexed, so
627627 // the extended edge is a sum rather than the `Vec<u16>` it used to be
628628 // 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
642642 let left = left.map(|l| extend(l, bh));
643643 let average = |sum: u32, count: u32| ((sum + (count >> 1)) / count) as i32;
644644 match (above, left) {
645- (None, None) => 1i32 << (crate::decode::bit_depth() - 1),
645+ (None, None) => 1i32 << (crate::decode::bit_depth(fctx) - 1),
646646 (Some(a), None) => average(a, bw as u32),
647647 (None, Some(l)) => average(l, bh as u32),
648648 (Some(a), Some(l)) if bw == bh => {
@@ -779,12 +779,12 @@ pub fn predict_filter_intra(
779779 corner: Option<u16>,
780780 bw: usize,
781781 bh: usize,
782- dst: &mut [u16],
782+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
783783 ) {
784784 assert_eq!(dst.len(), bw * bh, "the destination is the block");
785785 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
786786 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);
788788 let taps = &FILTER_INTRA_TAPS[mode];
789789 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
790790 // 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(
812812 for k in 0..8 {
813813 let (r_off, c_off) = (k >> 2, k & 3);
814814 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));
816816 let idx = (r + r_off) * (bw + 1) + c + c_off;
817817 buffer[idx] = value;
818818 }
@@ -991,6 +991,7 @@ mod tests {
991991 /// on three seeded random edges.
992992 #[test]
993993 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {
994+ let fctx = &crate::decode::FrameCtx::new();
994995 // xorshift64*: a seeded stream, so a failure names one (shape, mode,
995996 // seed) triple that reproduces.
996997 let mut rng = |state: &mut u64| {
@@ -1017,7 +1018,7 @@ mod tests {
10171018 ];
10181019 let mut compared = 0u32;
10191020 for bd in [8u32, 10] {
1020- crate::decode::set_bit_depth(bd as u8);
1021+ crate::decode::set_bit_depth(bd as u8, fctx);
10211022 let max = (1u32 << bd) - 1;
10221023 for &(bw, bh) in &shapes {
10231024 for mode in 0..5usize {
@@ -1044,7 +1045,7 @@ mod tests {
10441045 Some(corner),
10451046 bw,
10461047 bh,
1047- &mut got,
1048+ &mut got, fctx,
10481049 );
10491050 assert_eq!(
10501051 got, want,
@@ -1055,7 +1056,7 @@ mod tests {
10551056 }
10561057 }
10571058 }
1058- crate::decode::set_bit_depth(8);
1059+ crate::decode::set_bit_depth(8, fctx);
10591060 assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared");
10601061 }
10611062
@@ -1068,6 +1069,7 @@ mod tests {
10681069 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).
10691070 #[test]
10701071 fn rect_predictors_match_c_dump() {
1072+ let fctx = &crate::decode::FrameCtx::new();
10711073 let expected_txt = std::fs::read_to_string(concat!(
10721074 env!("CARGO_MANIFEST_DIR"),
10731075 "/../../lanes/intrarect_dump.expected.txt"
@@ -1156,7 +1158,7 @@ mod tests {
11561158 bh,
11571159 false,
11581160 false,
1159- &mut dst,
1161+ &mut dst, fctx,
11601162 );
11611163 let got = if name == "DC" {
11621164 u64::from(dst[0])
@@ -1184,7 +1186,7 @@ mod tests {
11841186 bh,
11851187 ef,
11861188 sn,
1187- &mut dst,
1189+ &mut dst, fctx,
11881190 );
11891191 let got = checksum(&dst);
11901192 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));
crates/ec-av1/src/mc.rsmodified+40 -32
@@ -672,7 +672,7 @@ pub fn predict(
672672 y_q4: i32,
673673 block_w: usize,
674674 block_h: usize,
675- dst: &mut [u16],
675+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
676676 ) {
677677 predict_with_filter(
678678 reference,
@@ -684,7 +684,7 @@ pub fn predict(
684684 block_w,
685685 block_h,
686686 InterpFilterKind::Regular,
687- dst,
687+ dst, fctx,
688688 );
689689 }
690690
@@ -702,7 +702,7 @@ pub fn predict_with_filter(
702702 block_w: usize,
703703 block_h: usize,
704704 filter_kind: InterpFilterKind,
705- dst: &mut [u16],
705+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
706706 ) {
707707 predict_with_filters(
708708 reference,
@@ -715,7 +715,7 @@ pub fn predict_with_filter(
715715 block_h,
716716 filter_kind,
717717 filter_kind,
718- dst,
718+ dst, fctx,
719719 );
720720 }
721721
@@ -735,11 +735,11 @@ pub fn predict_with_filters(
735735 block_h: usize,
736736 h_kind: InterpFilterKind,
737737 v_kind: InterpFilterKind,
738- dst: &mut [u16],
738+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
739739 ) {
740740 predict_with_filters_kern(
741741 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,
743743 );
744744 }
745745
@@ -765,7 +765,7 @@ pub fn predict_with_filters_kern(
765765 kern_h: usize,
766766 h_kind: InterpFilterKind,
767767 v_kind: InterpFilterKind,
768- dst: &mut [u16],
768+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
769769 ) {
770770 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
771771 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -839,7 +839,7 @@ pub fn predict_with_filters_kern(
839839 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
840840 // block's own first row where the pass would have put the 4th.
841841 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);
843843 with_scratch(rows, block_w, |intermediate, acc| {
844844 horizontal_pass_unscaled(
845845 reference, stride, true_width, true_height, x0,
@@ -1082,11 +1082,11 @@ pub fn predict_scaled(
10821082 block_h: usize,
10831083 h_kind: InterpFilterKind,
10841084 v_kind: InterpFilterKind,
1085- dst: &mut [u16],
1085+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
10861086 ) {
10871087 predict_scaled_kern(
10881088 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,
10901090 );
10911091 }
10921092
@@ -1107,7 +1107,7 @@ pub fn predict_scaled_kern(
11071107 kern_h: usize,
11081108 h_kind: InterpFilterKind,
11091109 v_kind: InterpFilterKind,
1110- dst: &mut [u16],
1110+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
11111111 ) {
11121112 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
11131113 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1129,7 +1129,7 @@ pub fn predict_scaled_kern(
11291129 };
11301130
11311131 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);
11331133 with_scratch(rows, block_w, |intermediate, acc| {
11341134 horizontal_pass(
11351135 reference, stride, true_width, true_height, x_q4,
@@ -1168,17 +1168,17 @@ pub fn predict_maybe_scaled(
11681168 block_h: usize,
11691169 h_kind: InterpFilterKind,
11701170 v_kind: InterpFilterKind,
1171- dst: &mut [u16],
1171+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
11721172 ) {
11731173 if x_scale_fp == REF_NO_SCALE {
11741174 predict_with_filters(
11751175 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,
11771177 );
11781178 } else {
11791179 predict_scaled(
11801180 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,
11821182 );
11831183 }
11841184 }
@@ -1310,7 +1310,7 @@ pub fn combine_compound(
13101310 pred1: &[i32],
13111311 fwd_weight: i32,
13121312 bck_weight: i32,
1313- dst: &mut [u16],
1313+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
13141314 ) {
13151315 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
13161316 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
@@ -1324,7 +1324,7 @@ pub fn combine_compound(
13241324 // dropped low 4 bits are non-zero.
13251325 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
13261326 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;
13281328 }
13291329 }
13301330
@@ -1338,7 +1338,7 @@ pub fn combine_compound(
13381338 /// produces give the identical `diff` libaom computes. `round` is
13391339 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
13401340 /// 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 fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) {
13421342 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
13431343 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
13441344 // 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]) {
13461346 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
13471347 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
13481348 // `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);
13501350 for i in 0..mask.len() {
13511351 let diff = round2((pred0[i] - pred1[i]).abs(), round);
13521352 let m = (38 + diff / 16).clamp(0, 64);
@@ -1373,7 +1373,7 @@ pub fn blend_masked_compound(
13731373 w: usize,
13741374 h: usize,
13751375 subsampled: bool,
1376- dst: &mut [u16],
1376+ dst: &mut [u16], fctx: &crate::decode::FrameCtx,
13771377 ) {
13781378 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
13791379 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
@@ -1393,7 +1393,7 @@ pub fn blend_masked_compound(
13931393 i32::from(mask[i * mask_stride + j])
13941394 };
13951395 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;
13971397 }
13981398 }
13991399 }
@@ -1409,6 +1409,7 @@ pub fn blend_masked_compound(
14091409 /// off-by-one from double rounding.
14101410 #[test]
14111411 fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1412+ let fctx = &crate::decode::FrameCtx::new();
14121413 let reference = vec![100u16; 16 * 16];
14131414 let mut pred0 = vec![0i32; 16];
14141415 predict_compound_intermediate(
@@ -1429,7 +1430,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
14291430
14301431 let pred1 = pred0.clone();
14311432 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);
14331434 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
14341435 }
14351436
@@ -1450,6 +1451,7 @@ mod tests {
14501451 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
14511452 #[test]
14521453 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1454+ let fctx = &crate::decode::FrameCtx::new();
14531455 #[rustfmt::skip]
14541456 let window: [[u8; 24]; 24] = [
14551457 [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 {
15081510 16,
15091511 16,
15101512 InterpFilterKind::Smooth,
1511- &mut dst,
1513+ &mut dst, fctx,
15121514 );
15131515 #[rustfmt::skip]
15141516 let expected_row0: [u16; 16] =
@@ -1559,6 +1561,7 @@ mod tests {
15591561
15601562 #[test]
15611563 fn integer_mv_is_identity() {
1564+ let fctx = &crate::decode::FrameCtx::new();
15621565 let width = 12;
15631566 let height = 12;
15641567 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
@@ -1572,7 +1575,7 @@ mod tests {
15721575 4 * 16,
15731576 6,
15741577 6,
1575- &mut dst,
1578+ &mut dst, fctx,
15761579 );
15771580 for row in 0..6 {
15781581 for col in 0..6 {
@@ -1587,6 +1590,7 @@ mod tests {
15871590
15881591 #[test]
15891592 fn half_pel_reproduces_the_ramp_midpoint() {
1593+ let fctx = &crate::decode::FrameCtx::new();
15901594 // Step 2 so every half-pel position lands on an exact integer.
15911595 let width = 16;
15921596 let height = 16;
@@ -1604,7 +1608,7 @@ mod tests {
16041608 5 * 16,
16051609 4,
16061610 4,
1607- &mut dst,
1611+ &mut dst, fctx,
16081612 );
16091613 for row in 0..4 {
16101614 for col in 0..4 {
@@ -1620,6 +1624,7 @@ mod tests {
16201624
16211625 #[test]
16221626 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
1627+ let fctx = &crate::decode::FrameCtx::new();
16231628 let width = 20;
16241629 let height = 20;
16251630 let reference = vec![142u16; width * height];
@@ -1635,7 +1640,7 @@ mod tests {
16351640 5 * 16 + yfrac,
16361641 5,
16371642 5,
1638- &mut dst,
1643+ &mut dst, fctx,
16391644 );
16401645 assert!(
16411646 dst.iter().all(|&v| v == 142),
@@ -1647,6 +1652,7 @@ mod tests {
16471652
16481653 #[test]
16491654 fn horizontal_and_vertical_only_filtering_differ() {
1655+ let fctx = &crate::decode::FrameCtx::new();
16501656 // A plane linear in both x and y with different, even coefficients so
16511657 // each axis's half-pel interpolation lands on an exact integer: this
16521658 // pins the actual value each pass produces, not just that the two
@@ -1668,7 +1674,7 @@ mod tests {
16681674 3 * 16,
16691675 4,
16701676 4,
1671- &mut horiz,
1677+ &mut horiz, fctx,
16721678 );
16731679 let mut vert = vec![0u16; 4 * 4];
16741680 predict(
@@ -1680,7 +1686,7 @@ mod tests {
16801686 3 * 16 + 8,
16811687 4,
16821688 4,
1683- &mut vert,
1689+ &mut vert, fctx,
16841690 );
16851691
16861692 for row in 0..4 {
@@ -1707,6 +1713,7 @@ mod tests {
17071713
17081714 #[test]
17091715 fn mv_past_the_edge_clamps_instead_of_panicking() {
1716+ let fctx = &crate::decode::FrameCtx::new();
17101717 let width = 8;
17111718 let height = 8;
17121719 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
@@ -1722,7 +1729,7 @@ mod tests {
17221729 -50 * 16 + 5,
17231730 4,
17241731 4,
1725- &mut dst,
1732+ &mut dst, fctx,
17261733 );
17271734 let expected = reference[0]; // the whole plane clamps to the top-left corner
17281735 assert!(
@@ -1740,7 +1747,7 @@ mod tests {
17401747 50 * 16 + 5,
17411748 4,
17421749 4,
1743- &mut dst2,
1750+ &mut dst2, fctx,
17441751 );
17451752 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
17461753 assert!(
@@ -1751,6 +1758,7 @@ mod tests {
17511758
17521759 #[test]
17531760 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
1761+ let fctx = &crate::decode::FrameCtx::new();
17541762 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
17551763 // must reduce predict_scaled's per-column scaled walk to the exact
17561764 // same int_pel/filter_idx sequence predict_with_filters computes from
@@ -1774,7 +1782,7 @@ mod tests {
17741782 8,
17751783 InterpFilterKind::Regular,
17761784 InterpFilterKind::Regular,
1777- &mut expected,
1785+ &mut expected, fctx,
17781786 );
17791787 let mut got = vec![0u16; block_w * 8];
17801788 predict_scaled(
@@ -1789,7 +1797,7 @@ mod tests {
17891797 8,
17901798 InterpFilterKind::Regular,
17911799 InterpFilterKind::Regular,
1792- &mut got,
1800+ &mut got, fctx,
17931801 );
17941802 assert_eq!(
17951803 got, expected,
crates/ec-av1/src/motion.rsmodified+14 -10
@@ -200,11 +200,11 @@ pub fn search(
200200 block_w: usize,
201201 block_h: usize,
202202 pred_mv: (i32, i32),
203- lambda: f64,
203+ lambda: f64, fctx: &crate::decode::FrameCtx,
204204 ) -> MotionSearch {
205205 let (result, _trace) = search_traced(
206206 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
207- pred_mv, lambda,
207+ pred_mv, lambda, fctx,
208208 );
209209 result
210210 }
@@ -224,7 +224,7 @@ fn search_traced(
224224 block_w: usize,
225225 block_h: usize,
226226 pred_mv: (i32, i32),
227- lambda: f64,
227+ lambda: f64, fctx: &crate::decode::FrameCtx,
228228 ) -> (MotionSearch, Vec<f64>) {
229229 search_traced_from_step(
230230 reference,
@@ -238,7 +238,7 @@ fn search_traced(
238238 block_h,
239239 pred_mv,
240240 lambda,
241- SEARCH_INITIAL_STEP_PEL,
241+ SEARCH_INITIAL_STEP_PEL, fctx,
242242 )
243243 }
244244
@@ -258,7 +258,7 @@ fn search_traced_from_step(
258258 block_h: usize,
259259 pred_mv: (i32, i32),
260260 lambda: f64,
261- initial_step_pel: i32,
261+ initial_step_pel: i32, fctx: &crate::decode::FrameCtx,
262262 ) -> (MotionSearch, Vec<f64>) {
263263 assert_eq!(source.len(), block_w * block_h, "source is one block");
264264 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -274,7 +274,7 @@ fn search_traced_from_step(
274274 let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
275275 predict(
276276 &reference16, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h,
277- &mut dst16,
277+ &mut dst16, fctx,
278278 );
279279 let sad: f64 = source
280280 .iter()
@@ -401,6 +401,7 @@ mod tests {
401401
402402 #[test]
403403 fn finds_exact_integer_translation_all_four_signs() {
404+ let fctx = &crate::decode::FrameCtx::new();
404405 let width = 64;
405406 let height = 64;
406407 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -442,7 +443,7 @@ mod tests {
442443 block_w,
443444 block_h,
444445 (0, 0),
445- 0.1,
446+ 0.1, fctx,
446447 );
447448 assert_eq!(
448449 result.mv,
@@ -454,6 +455,7 @@ mod tests {
454455
455456 #[test]
456457 fn finds_half_pel_translation() {
458+ let fctx = &crate::decode::FrameCtx::new();
457459 // A ramp, doubled, so every half-pel position lands on an exact
458460 // integer average of its two neighbours.
459461 let width = 40;
@@ -489,7 +491,7 @@ mod tests {
489491 block_w,
490492 block_h,
491493 (0, 0),
492- 0.1,
494+ 0.1, fctx,
493495 );
494496 assert_eq!(
495497 result.mv,
@@ -500,6 +502,7 @@ mod tests {
500502
501503 #[test]
502504 fn cost_is_monotone_non_increasing_over_the_search() {
505+ let fctx = &crate::decode::FrameCtx::new();
503506 let width = 48;
504507 let height = 48;
505508 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -525,7 +528,7 @@ mod tests {
525528 block_w,
526529 block_h,
527530 (0, 0),
528- 0.1,
531+ 0.1, fctx,
529532 );
530533 assert!(trace.len() > 1, "the search must run more than one round");
531534 for pair in trace.windows(2) {
@@ -559,6 +562,7 @@ mod tests {
559562 /// lands.
560563 #[test]
561564 fn sweep_initial_step() {
565+ let fctx = &crate::decode::FrameCtx::new();
562566 let width = 96;
563567 let height = 96;
564568 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
@@ -593,7 +597,7 @@ mod tests {
593597 block_h,
594598 (0, 0),
595599 0.1,
596- candidate_step,
600+ candidate_step, fctx,
597601 );
598602 // Every round the trace recorded is 8 neighbour evaluations,
599603 // 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 {
695695 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A
696696 /// partition whose warp-sample top-right probe may answer 1 where libaom says
697697 /// 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 {
699- let sb_mi_size = crate::decode::sb_mi_cur() as usize;
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(fctx) as usize;
700700 let bs0 = bw4.max(bh4);
701701 if bs0 > 16 {
702702 return false;
crates/ec-av1/src/restoration.rsmodified+16 -16
@@ -326,7 +326,7 @@ pub(crate) fn read_lr(
326326 reference: &mut [(WienerInfo, SgrprojInfo); 3],
327327 mi_row: u32,
328328 mi_col: u32,
329- sb_mi: u32,
329+ sb_mi: u32, fctx: &crate::decode::FrameCtx,
330330 ) {
331331 if !lr.uses_lr {
332332 return;
@@ -345,7 +345,7 @@ pub(crate) fn read_lr(
345345 // is in upscaled ones, so the column division scales by
346346 // `superres_denom / SCALE_NUMERATOR` (`mi_to_num_x`/`denom_x`). Rows
347347 // 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) {
349349 Some((_, denom)) => (mi_size * denom, unit_size * 8),
350350 None => (mi_size, unit_size),
351351 };
@@ -571,14 +571,14 @@ fn apply_wiener_stripe(
571571 h_end: usize,
572572 v_start: usize,
573573 v_end: usize,
574- info: &WienerInfo,
574+ info: &WienerInfo, fctx: &crate::decode::FrameCtx,
575575 ) {
576576 let w = h_end - h_start;
577577 let h = v_end - v_start;
578578 if w == 0 || h == 0 {
579579 return;
580580 }
581- let bd = i64::from(crate::decode::bit_depth());
581+ let bd = i64::from(crate::decode::bit_depth(fctx));
582582 let wiener_bias = 1i64 << (bd + 3);
583583 let wiener_limit = 1i64 << (bd + 5);
584584 let rows = h + 6;
@@ -622,7 +622,7 @@ fn apply_wiener_stripe(
622622 WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf);
623623 // lane-perf7: the clamp bound is the frame's, so it is read once here
624624 // 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));
626626 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves
627627 // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`.
628628 let vf = &info.vfilter;
@@ -732,7 +732,7 @@ fn compute_ab(
732732 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every
733733 // page then faulted in on first touch. Every entry is written below, so
734734 // the resize's fill value is never read.
735- ab: &mut Vec<(i32, i64)>,
735+ ab: &mut Vec<(i32, i64)>, fctx: &crate::decode::FrameCtx,
736736 ) {
737737 let gw = w + 2;
738738 let gh = h + 2;
@@ -750,7 +750,7 @@ fn compute_ab(
750750 let mut col_a = vec![0i64; ncols];
751751 let mut col_b = vec![0i64; ncols];
752752 // 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);
754754 let base_col = h_start as i64 - 1 - r as i64;
755755 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s
756756 // window is row `gi`'s minus its top source row plus one new bottom row,
@@ -844,7 +844,7 @@ fn apply_sgrproj_stripe(
844844 h_end: usize,
845845 v_start: usize,
846846 v_end: usize,
847- info: &SgrprojInfo,
847+ info: &SgrprojInfo, fctx: &crate::decode::FrameCtx,
848848 ) {
849849 let w = h_end - h_start;
850850 let h = v_end - v_start;
@@ -860,10 +860,10 @@ fn apply_sgrproj_stripe(
860860 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))
861861 });
862862 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);
864864 }
865865 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);
867867 }
868868 let ab0 = (r0 > 0).then_some(&buf0);
869869 let ab1 = (r1 > 0).then_some(&buf1);
@@ -904,7 +904,7 @@ fn apply_sgrproj_stripe(
904904
905905 // lane-perf7: as in `apply_wiener_stripe`, the clamp bound is read once
906906 // 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));
908908 for i in 0..h as i64 {
909909 for j in 0..w as i64 {
910910 let dgd = lr_sample(
@@ -1005,7 +1005,7 @@ fn filter_restoration_unit(
10051005 v_start: usize,
10061006 v_end: usize,
10071007 ss_y: u32,
1008- filter: UnitFilter,
1008+ filter: UnitFilter, fctx: &crate::decode::FrameCtx,
10091009 ) {
10101010 let full_stripe_height = 64usize >> ss_y;
10111011 let runit_offset = 8usize >> ss_y;
@@ -1027,10 +1027,10 @@ fn filter_restoration_unit(
10271027 }
10281028 match filter {
10291029 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,
10311031 ),
10321032 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,
10341034 ),
10351035 UnitFilter::None => {}
10361036 }
@@ -1065,7 +1065,7 @@ pub(crate) fn apply_loop_restoration_plane(
10651065 // lane-perf6: the destination buffer, refilled from `cdef` here. It used
10661066 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
10671067 // allocation whose every page then faulted in on first touch.
1068- out: &mut Vec<u16>,
1068+ out: &mut Vec<u16>, fctx: &crate::decode::FrameCtx,
10691069 ) {
10701070 out.clear();
10711071 out.extend_from_slice(cdef);
@@ -1104,7 +1104,7 @@ pub(crate) fn apply_loop_restoration_plane(
11041104 v_start as usize,
11051105 v_end as usize,
11061106 ss_y,
1107- filter,
1107+ filter, fctx,
11081108 );
11091109 }
11101110 x0 += uw;
crates/ec-av1/src/stream.rsmodified+46 -28
@@ -265,6 +265,9 @@ pub fn decode_stream_with(
265265 data: &[u8],
266266 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
267267 ) -> 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();
268271 let final_dump = final_dump_prefix();
269272 let mut parser = Av1Parser::new();
270273 let mut pictures_shown: usize = 0;
@@ -368,7 +371,7 @@ pub fn decode_stream_with(
368371 &picture,
369372 &header.film_grain,
370373 mc_identity,
371- bit_depth as u32,
374+ bit_depth as u32, fctx,
372375 )
373376 } else {
374377 picture
@@ -493,7 +496,7 @@ pub fn decode_stream_with(
493496 header.segmentation,
494497 header.mi_rows as usize,
495498 header.mi_cols as usize,
496- prev_seg_map.as_deref(),
499+ prev_seg_map.as_deref(), fctx,
497500 );
498501 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
499502 // symbol (spec 7.16's upscaling is a pixel-domain post-process
@@ -666,7 +669,7 @@ pub fn decode_stream_with(
666669 // the key-frame tile path used to set; without this call a stream whose
667670 // inter frames are decoded on a thread that previously decoded a
668671 // 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);
670673 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
671674 // key-frame and the inter tile path read the 128 partition root and
672675 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
@@ -678,7 +681,7 @@ pub fn decode_stream_with(
678681 .sequence_header()
679682 .is_some_and(|seq| seq.use_128x128_superblock);
680683 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);
682685 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
683686 // which every dequant/inverse-transform clamp reads -- set per frame,
684687 // not once per process, for the same cross-sequence-on-one-thread
@@ -700,14 +703,14 @@ pub fn decode_stream_with(
700703 "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)",
701704 ));
702705 }
703- crate::decode::set_bit_depth(bit_depth);
706+ crate::decode::set_bit_depth(bit_depth, fctx);
704707 // spec 7.16: this frame's superres state, for the filter chain --
705708 // `decode.rs` upscales between CDEF and loop restoration and sizes
706709 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
707710 // unscaled frame so a later frame never inherits it.
708711 crate::decode::set_superres(
709712 if header.use_superres { header.upscaled_width } else { 0 },
710- u32::from(header.superres_denom),
713+ u32::from(header.superres_denom), fctx,
711714 );
712715 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
713716 let enable_masked_compound = parser
@@ -808,7 +811,7 @@ pub fn decode_stream_with(
808811 header.reduced_tx_set,
809812 header.allow_screen_content_tools,
810813 header.allow_intrabc,
811- header.delta,
814+ header.delta, fctx,
812815 )?;
813816 // A key frame codes no inter blocks -- its own saved motion
814817 // field has no cells set, matching libaom's own "intra frame
@@ -919,7 +922,7 @@ pub fn decode_stream_with(
919922 header.allow_warped_motion,
920923 header.allow_screen_content_tools,
921924 header.delta,
922- enable_filter_intra,
925+ enable_filter_intra, fctx,
923926 )?;
924927 (picture, end_cdfs, motion_field)
925928 };
@@ -1003,7 +1006,7 @@ pub fn decode_stream_with(
10031006 }
10041007 }
10051008 pictures_decoded += 1;
1006- let decoded_seg_map = decode::take_segment_ids();
1009+ let decoded_seg_map = decode::take_segment_ids(fctx);
10071010 for i in 0..NUM_REF_FRAMES {
10081011 if header.refresh_frame_flags & (1 << i) != 0 {
10091012 cdf_slots[i] = Some(stored_cdfs.clone());
@@ -1033,7 +1036,7 @@ pub fn decode_stream_with(
10331036 &picture,
10341037 &header.film_grain,
10351038 mc_identity,
1036- bit_depth as u32,
1039+ bit_depth as u32, fctx,
10371040 )
10381041 } else {
10391042 picture
@@ -1114,8 +1117,9 @@ mod tests {
11141117 /// tile payload is never reached.
11151118 #[test]
11161119 fn a_twelve_bit_sequence_header_is_refused_by_name() {
1120+ let fctx = &crate::decode::FrameCtx::new();
11171121 let picture = test_card(64, 64);
1118- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1122+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
11191123 let mut color = ec_av1_syntax::ColorConfig {
11201124 bit_depth: 12,
11211125 ..Default::default()
@@ -1157,9 +1161,10 @@ mod tests {
11571161 /// never reports this refusal for any of them.
11581162 #[test]
11591163 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
1164+ let fctx = &crate::decode::FrameCtx::new();
11601165 const REFUSAL: &str = "a frame OBU with no tile group";
11611166 let picture = test_card(64, 64);
1162- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1167+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
11631168 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
11641169 let mut frame_obus_parsed = 0;
11651170 for len in 0..=encoded.tile.len().min(24) {
@@ -1212,10 +1217,11 @@ mod tests {
12121217 /// first, a middle and the last segment id.
12131218 #[test]
12141219 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
1220+ let fctx = &crate::decode::FrameCtx::new();
12151221 const REFUSAL: &str =
12161222 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
12171223 let picture = test_card(64, 64);
1218- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1224+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
12191225 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
12201226 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
12211227 for segment in [0usize, 3, 7] {
@@ -1603,9 +1609,10 @@ mod tests {
16031609 /// tile is decoded.
16041610 #[test]
16051611 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
1612+ let fctx = &crate::decode::FrameCtx::new();
16061613 const REFUSAL: &str = "an inter frame with no key frame before it";
16071614 let picture = test_card(64, 64);
1608- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1615+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
16091616 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
16101617 let inter = FrameHeader {
16111618 frame_type: FrameType::Inter,
@@ -1648,10 +1655,11 @@ mod tests {
16481655 /// fires on the reference's dimensions before a tile symbol is read.
16491656 #[test]
16501657 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
1658+ let fctx = &crate::decode::FrameCtx::new();
16511659 const REFUSAL: &str =
16521660 "a reference picture whose height does not match this frame's own true size";
16531661 let picture = test_card(64, 64);
1654- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1662+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
16551663 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
16561664 let inter = FrameHeader {
16571665 frame_type: FrameType::Inter,
@@ -1699,6 +1707,7 @@ mod tests {
16991707 /// before the reference pictures are looked up.
17001708 #[test]
17011709 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
1710+ let fctx = &crate::decode::FrameCtx::new();
17021711 const REFUSAL: &str =
17031712 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
17041713 // The invariant above, read off the source: every line that stores a
@@ -1727,7 +1736,7 @@ mod tests {
17271736 }
17281737
17291738 let picture = test_card(64, 64);
1730- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
1739+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
17311740 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
17321741 for slot in 0..NUM_REF_FRAMES as u8 {
17331742 let inter = FrameHeader {
@@ -2130,9 +2139,10 @@ mod tests {
21302139 /// the encoder's own reconstruction, at an even and an odd size.
21312140 #[test]
21322141 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
2142+ let fctx = &crate::decode::FrameCtx::new();
21332143 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
21342144 let picture = test_card(width, height);
2135- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
2145+ let encoded = encode_key_frame(&picture, 100, 0.5, fctx).unwrap();
21362146 let via_tile = decode_key_frame_tile(
21372147 &encoded.tile,
21382148 encoded.mi_cols,
@@ -2147,7 +2157,7 @@ mod tests {
21472157 // Our own encoder always writes `reduced_tx_set: true`.
21482158 true,
21492159 false,
2150- false,
2160+ false, fctx,
21512161 )
21522162 .unwrap();
21532163 let via_stream = decode_stream(&encoded.stream).unwrap();
@@ -2165,11 +2175,11 @@ mod tests {
21652175 /// A GOP (key frame plus panned inter frames, so blocks actually take
21662176 /// motion) decodes bit-exact through `decode_stream` alone, threading its
21672177 /// 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) {
21692179 let pictures: Vec<_> = (0..4)
21702180 .map(|i| panned_test_card(width, height, i * 3))
21712181 .collect();
2172- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
2182+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
21732183 let decoded = decode_stream(&encoded.stream).unwrap();
21742184 assert_eq!(decoded.len(), encoded.frames.len());
21752185 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
@@ -2190,14 +2200,16 @@ mod tests {
21902200
21912201 #[test]
21922202 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);
21942205 }
21952206
21962207 /// Same claim at a size that is not a whole number of 32x32 blocks, so
21972208 /// the inter frame's 16x16-leaf split path is exercised too.
21982209 #[test]
21992210 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);
22012213 }
22022214
22032215 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
@@ -2208,8 +2220,9 @@ mod tests {
22082220 /// decode indices non-decreasing, and an `Err` from the sink aborting.
22092221 #[test]
22102222 fn streaming_decode_matches_the_collecting_one() {
2223+ let fctx = &crate::decode::FrameCtx::new();
22112224 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(&pictures, 100, 0.5, fctx).unwrap().stream;
22132226 let collected = decode_stream(&stream).unwrap();
22142227
22152228 let mut shown = Vec::new();
@@ -2444,6 +2457,7 @@ mod tests {
24442457 /// independent decoder, not just this crate checking its own tile path.
24452458 #[test]
24462459 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
2460+ let fctx = &crate::decode::FrameCtx::new();
24472461 if !have_ffmpeg() {
24482462 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
24492463 return;
@@ -2452,7 +2466,7 @@ mod tests {
24522466 let pictures: Vec<_> = (0..3)
24532467 .map(|i| panned_test_card(width, height, i * 3))
24542468 .collect();
2455- let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
2469+ let encoded = encode_sequence(&pictures, 100, 0.5, fctx).unwrap();
24562470 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
24572471 let decoded = decode_stream(&encoded.stream).unwrap();
24582472 assert_eq!(decoded.len(), 3);
@@ -2491,6 +2505,7 @@ mod tests {
24912505 /// with itself would prove nothing.
24922506 #[test]
24932507 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
2508+ let fctx = &crate::decode::FrameCtx::new();
24942509 if !have_ffmpeg() {
24952510 eprintln!(
24962511 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
@@ -2526,7 +2541,7 @@ mod tests {
25262541
25272542 for run in 0..4 {
25282543 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(&picture, base_q_idx, 0.5, fctx).unwrap();
25302545 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
25312546
25322547 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
@@ -22313,6 +22328,7 @@ mod tests {
2231322328 /// the real proof).
2231422329 #[test]
2231522330 fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {
22331+ let fctx = &crate::decode::FrameCtx::new();
2231622332 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";
2231722333 if !have_ffmpeg() {
2231822334 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -22500,7 +22516,7 @@ mod tests {
2250022516 header.reduced_tx_set,
2250122517 header.allow_screen_content_tools,
2250222518 header.allow_intrabc,
22503- header.delta,
22519+ header.delta, fctx,
2250422520 ) {
2250522521 Err(e) => {
2250622522 let msg = e.to_string();
@@ -22564,6 +22580,7 @@ mod tests {
2256422580 /// already proved -- this gate is what actually proves it either way.
2256522581 #[test]
2256622582 fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() {
22583+ let fctx = &crate::decode::FrameCtx::new();
2256722584 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact";
2256822585 if !have_ffmpeg() {
2256922586 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -22722,7 +22739,7 @@ mod tests {
2272222739 header.reduced_tx_set,
2272322740 header.allow_screen_content_tools,
2272422741 header.allow_intrabc,
22725- header.delta,
22742+ header.delta, fctx,
2272622743 ) {
2272722744 Err(e) => {
2272822745 let msg = e.to_string();
@@ -22899,6 +22916,7 @@ mod tests {
2289922916 /// 2-column case's boundary-that-is-also-the-frame-edge.
2290022917 #[test]
2290122918 fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() {
22919+ let fctx = &crate::decode::FrameCtx::new();
2290222920 const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact";
2290322921 if !have_ffmpeg() {
2290422922 eprintln!("SKIP {NAME}: no ffmpeg");
@@ -23044,7 +23062,7 @@ mod tests {
2304423062 header.reduced_tx_set,
2304523063 header.allow_screen_content_tools,
2304623064 header.allow_intrabc,
23047- header.delta,
23065+ header.delta, fctx,
2304823066 ) {
2304923067 Err(e) => {
2305023068 let msg = e.to_string();
crates/ec-av1/src/warp.rsmodified+7 -7
@@ -417,8 +417,8 @@ pub fn global_warp_params(wmmat: [i32; 6]) -> Option<WarpParams> {
417417 Some(WarpParams { wmmat, alpha, beta, gamma, delta })
418418 }
419419
420-fn clip_pixel(v: i32) -> u16 {
421- v.clamp(0, crate::decode::sample_max()) as u16
420+fn clip_pixel(v: i32, fctx: &crate::decode::FrameCtx) -> u16 {
421+ v.clamp(0, crate::decode::sample_max(fctx)) as u16
422422 }
423423
424424 /// `av1_highbd_warp_affine_c` (`warped_motion.c`)'s non-compound branch:
@@ -442,12 +442,12 @@ pub fn warp_affine(
442442 p_height: i32,
443443 p_stride: i32,
444444 subsampling_x: i32,
445- subsampling_y: i32,
445+ subsampling_y: i32, fctx: &crate::decode::FrameCtx,
446446 ) {
447447 if crate::envflags::env_flag!("EC_MC_TRACE") {
448448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");
449449 }
450- let bd = i32::from(crate::decode::bit_depth());
450+ let bd = i32::from(crate::decode::bit_depth(fctx));
451451 // `reduce_bits_vert`, non-compound: `2 * FILTER_BITS - round_0`.
452452 let reduce_bits_vert = 2 * FILTER_BITS - REDUCE_BITS_HORIZ;
453453 warp_inner(
@@ -455,7 +455,7 @@ pub fn warp_affine(
455455 subsampling_x, subsampling_y, bd, reduce_bits_vert,
456456 |row, col, sum| {
457457 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);
459459 },
460460 );
461461 }
@@ -490,9 +490,9 @@ pub fn warp_affine_compound(
490490 p_height: i32,
491491 p_stride: i32,
492492 subsampling_x: i32,
493- subsampling_y: i32,
493+ subsampling_y: i32, fctx: &crate::decode::FrameCtx,
494494 ) {
495- let bd = i32::from(crate::decode::bit_depth());
495+ let bd = i32::from(crate::decode::bit_depth(fctx));
496496 let bias = (1 << (bd + 4)) + (1 << (bd + 3));
497497 warp_inner(
498498 params, reference, width, height, stride, p_col, p_row, p_width, p_height,