forge
Explore
Log in

Don't you dare go Hollow

One coded frame decodes from a bank snapshot alone (decode_frame)

Browse files at this commit

1241afcf53997e963425ddcb020d3b0558bbbcf2Ahmet Kaan GümüşParent: 63370ce
  • refactor
    • one coded frame decodes from a bank snapshot alone (decode_frame)
Show full message
refactor(av1): one coded frame decodes from a bank snapshot alone (decode_frame)

The body of `decode_stream_with`'s loop between "frame header parsed" and
"reference banks updated" becomes `decode_frame(fctx, header, tile_bufs,
seq, snap, ..) -> FrameOutput`, a function of the bitstream plus a
`RefSnapshot` (the 8 DPB slots, the primary reference's saved CDFs and
segment map, spec 7.9's projected motion field, the reference order
hints) and `SeqFlags` (the sequence-header bits it needs). Nothing in it
reaches for the parser or for a bank any more, which is what lets a frame
be decoded off the parsing thread at all.

Pure refactor: the four perf-gate streams hash exactly as before
(seg1080 c2d4ef66, seg4k 3ac25ee5, seg4k_lr d197dbe0, palette 2bfb6839),
and the refusal ORDER is preserved deliberately -- the "primary_ref_frame
at a slot with no saved CDF state" error still fires inside
`decode_frame`, after the segmentation and 12-bit refusals, even though
the snapshot that carries the slot is taken before the call.
crates/ec-av1/src/stream.rsmodified+660 -529
@@ -473,182 +473,6 @@ pub fn decode_stream_with(
473 // reader on the inter path, so they still refuse by name rather than473 // reader on the inter path, so they still refuse by name rather than
474 // desyncing. aomenc's `--aq-mode` segmentation only ever sets474 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
475 // `SEG_LVL_ALT_Q`.475 // `SEG_LVL_ALT_Q`.
476- if header.segmentation.enabled {
477- for segment in 0..MAX_SEGMENTS {
478- for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
479- if header.segmentation.feature_enabled[segment][feature] {
480- return Err(Error::unsupported(
481- "AV1 decode_stream",
482- "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
483- ));
484- }
485- }
486- }
487- }
488- // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
489- // primary reference frame's slot, and is all-zero without one.
490- let prev_seg_map = if header.primary_ref_frame == PRIMARY_REF_NONE {
491- None
492- } else {
493- seg_map_slots[header.ref_frame_idx[header.primary_ref_frame as usize] as usize].clone()
494- };
495- decode::set_segmentation(
496- header.segmentation,
497- header.mi_rows as usize,
498- header.mi_cols as usize,
499- prev_seg_map.as_deref(), fctx,
500- );
501- // lane-superres stage 2/3: `use_superres` adds/removes no per-block
502- // symbol (spec 7.16's upscaling is a pixel-domain post-process
503- // libaom's `decodeframe.c` runs between CDEF and loop restoration,
504- // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
505- // reads stay bit-exact in sync and `crate::superres::upscale_picture`
506- // (below, after decode) makes its `Picture` the spec-correct
507- // `upscaled_width` instead of silently staying at `frame_width`.
508- // lane-superres r10: an INTER frame under `use_superres` no longer
509- // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
510- // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
511- // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
512- // at the downscaled `frame_width` and upscales its own output the
513- // same way the key-frame branch above does (see the inter branch
514- // below). The combinations `predict_scaled` does not cover
515- // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
516- // leaf) still refuse by name, deep in `decode.rs`, rather than
517- // silently mispredicting -- see `refusal_inventory.rs`.
518- // Loop restoration carries per-restoration-unit symbols in the tile
519- // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
520- // superblock walk) -- lane-lr r2 ported the reader
521- // (`crate::restoration`), r3 moved this refusal check to AFTER the
522- // tile decode call below (was here, before it, in r2 -- meaning
523- // `read_lr` was NEVER actually reached through `decode_stream`, the
524- // gap the r3 gate caught live: 40/40 attempts hit this refusal with
525- // zero `read_lr_unit` hits). Checking post-decode instead proves the
526- // superblock walk actually survived `read_lr` (no desync) before
527- // refusing on the true remaining gap: decoded Wiener/SGR filters are
528- // stored per unit but never applied to pixels.
529- // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
530- // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
531- // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
532- // zero vector only under `GmType == IDENTITY` -- any other warp
533- // model needs the full affine/translation MV derivation this
534- // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
535- // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
536- // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
537- // to every one of the 7 single-reference slots `decode_inter_block`
538- // can now select.
539- //
540- // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
541- // exposed a real pixel mismatch --
542- // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
543- // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
544- // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
545- // is not yet provably correct end to end; keeping the refusal
546- // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
547- // root-caused rather than shipping a wrong decode.
548- //
549- // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
550- // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
551- // RANGE at the first divergent block (mi=(8,0), frame 1) matches
552- // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
553- // and this decoder's own `gm_get_motion_vector` for that block
554- // (ROTZOOM, seed 43's own header) computes the spec-correct
555- // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
556- // which found and fixed a real `- 1` omission in `warp.rs` --
557- // harmless for THIS block's rounding but a genuine spec bug fixed
558- // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
559- // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
560- // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
561- // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
562- // with the FULL per-pixel affine global-motion warp, independent
563- // of `motion_mode` -- this decoder only ever builds a warp
564- // prediction for local `WARPED_CAUSAL` motion mode and falls back
565- // to plain translational MC with the block-centre mv for every
566- // other GLOBALMV block, which is only a centre-point approximation
567- // of the true per-pixel warp. That is the entire remaining gap.
568- // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
569- // `crate::warp::global_warp_params` for every single-ref
570- // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
571- // `global_warp_allowed` branch -- ROTZOOM is pin-verified
572- // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
573- // worked (`gm_get_motion_vector`'s translation-only mv, no warp
574- // needed). AFFINE is untested this round (no aomenc fixture in the
575- // wedge gate reached a 6-parameter model) -- keep refusing it by
576- // name rather than shipping an unverified decode.
577- // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
578- // can never write a 6-parameter model -- its encoder-side search is
579- // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
580- // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
581- // which is why four rounds of `--enable-global-motion=1` recipes
582- // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
583- // exactly that search range in a side build, and
584- // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
585- // decodes its output pixel-exact against ffmpeg with
586- // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
587- // 6-parameter warp. Nothing in the decoder needed changing: the
588- // header reader already reads params 4/5 with their own subexp refs
589- // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
590- // shear-validity check + `warp_affine` are model-agnostic.
591- // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
592- // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
593- // refused the shape by name rather than guess-fix it. r5 localized
594- // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
595- // global-warp branch at all -- proving "two active slots" was a
596- // correlated symptom, not the cause. r6 range-laddered that block
597- // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
598- // mode info -- symbol consumption bit-exact) and found the real
599- // defect in `mvstack.rs`'s single-reference predictor fallback:
600- // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
601- // neighbour scan left short with this block's OWN global motion
602- // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
603- // whenever the live ref's global motion is itself
604- // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
605- // and the querying block's own stack comes up short (frame 14's
606- // mi=(0,0), the very first block decoded, has no neighbours at
607- // all). Fixed at the predictor fallback; the refusal above (single
608- // untested shape: AFFINE on a single-ref frame) stays, but the
609- // *multi-slot* refusal this comment used to guard is lifted -- the
610- // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
611- // byte-exact with it gone.
612- // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
613- // `comp_mode` per block whenever this frame's own `reference_select`
614- // header bit is set (spec 5.11.25), and refuse by name the blocks
615- // that pick `COMPOUND_REFERENCE` -- two-reference motion
616- // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
617- // is wired at the block level too (forced NEAREST_NEARESTMV compound
618- // of `skip_mode_frame`, plain average blend), so the old blanket
619- // `skip_mode_present` refusal is gone.
620- // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
621- // which tile's end-of-tile adapted CDFs become the frame's own.
622- // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
623- // "further down" -- it did not (`decode.rs` reads
624- // `tile_info.context_update_tile_id` generically at both the
625- // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
626- // never hardcoded to tile 0); stale documentation, not a real gap.
627- // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
628- // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
629- // pixel-exact, so the capability is now proven as well as described
630- // correctly.
631- //
632- // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
633- // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
634- // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
635- // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
636- // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
637- // origin receives real values at every call site (r6's
638- // `set_tile_origin` sweep). r7 proved the two remaining
639- // tile-*column* gaps closed (inter frames, >2 columns with loop
640- // filtering on). r8 proved tile *rows* the same way: the per-tile
641- // loop's row math (`tile_num / tile_info.cols`,
642- // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
643- // symmetric with the column path already proven, and
644- // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
645- // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
646- // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
647- // stream` below re-proves it through this entry point. Tile columns
648- // and tile rows (any count, loop filter on) are no longer capped.
649- // `Tile::offset` is relative to the buffer `parse_obu` was handed
650- // (`&data[pos..]` at the time this OBU was parsed), so it is relative
651- // to `obu_offset`, not to `data` as a whole.
652 let tile_bufs: Vec<&[u8]> = tiles476 let tile_bufs: Vec<&[u8]> = tiles
653 .iter()477 .iter()
654 .map(|t| {478 .map(|t| {
@@ -656,357 +480,33 @@ pub fn decode_stream_with(
656 .ok_or(Error::NeedMore)480 .ok_or(Error::NeedMore)
657 })481 })
658 .collect::<Result<_>>()?;482 .collect::<Result<_>>()?;
659- let enable_filter_intra = parser483+ let seq = SeqFlags::read(&parser);
660- .sequence_header()484+ let snap = RefSnapshot::take(
661- .is_some_and(|seq| seq.enable_filter_intra);485+ &header,
662- let enable_dual_filter = parser486+ seq,
663- .sequence_header()487+ std::array::from_fn(|i| ref_slots[i].as_ref()),
664- .is_some_and(|seq| seq.enable_dual_filter);488+ &cdf_slots,
665- let enable_edge_filter = parser489+ &seg_map_slots,
666- .sequence_header()490+ &motion_field_slots,
667- .is_some_and(|seq| seq.enable_intra_edge_filter);491+ &order_hint_slots,
668- // Inter frames' intra blocks read this through a thread-local that only492+ );
669- // the key-frame tile path used to set; without this call a stream whose493+ let bit_depth = seq.bit_depth;
670- // inter frames are decoded on a thread that previously decoded a494+ let FrameOutput {
671- // different sequence would inherit that sequence's bit.495+ picture,
672- crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);496+ stored_cdfs,
673- // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the497+ motion_field,
674- // key-frame and the inter tile path read the 128 partition root and498+ seg_map: decoded_seg_map,
675- // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and499+ } = decode_frame(
676- // libaom's quadrant visit order into the inter loop too). A frame at500+ fctx,
677- // most 64x64 decodes identically either way (its 128 root reads no501+ &header,
678- // symbol -- neither half is in frame, so SPLIT is inferred), so the502+ &tile_bufs,
679- // flag is only armed for frames bigger than one 64x64 superblock.503+ seq,
680- let use_sb128 = parser504+ snap,
681- .sequence_header()505+ pictures_decoded,
682- .is_some_and(|seq| seq.use_128x128_superblock);506+ pictures_shown,
683- let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);507+ final_dump.as_deref(),
684- crate::decode::set_sb128(sb128_active, fctx);508+ )?;
685- // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
686- // which every dequant/inverse-transform clamp reads -- set per frame,
687- // not once per process, for the same cross-sequence-on-one-thread
688- // reason as `set_enable_edge_filter` above. Defaults to 8 when no
689- // sequence header has been seen yet, matching every existing fixture.
690- let bit_depth = parser
691- .sequence_header()
692- .map_or(8, |seq| seq.color_config.bit_depth);
693- // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
694- // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
695- // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
696- // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
697- // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
698- // Wiener rounding bits change, and neither CDEF nor film grain has a
699- // 12-bit path. Refuse by name rather than decode silently wrong pixels.
700- if bit_depth == 12 {
701- return Err(Error::unsupported(
702- "AV1 decode_stream",
703- "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
704- ));
705- }
706- crate::decode::set_bit_depth(bit_depth, fctx);
707- // spec 7.16: this frame's superres state, for the filter chain --
708- // `decode.rs` upscales between CDEF and loop restoration and sizes
709- // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
710- // unscaled frame so a later frame never inherits it.
711- crate::decode::set_superres(
712- if header.use_superres { header.upscaled_width } else { 0 },
713- u32::from(header.superres_denom), fctx,
714- );
715- // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
716- let enable_masked_compound = parser
717- .sequence_header()
718- .is_some_and(|seq| seq.enable_masked_compound);
719- let enable_jnt_comp = parser
720- .sequence_header()
721- .is_some_and(|seq| seq.enable_jnt_comp);
722- // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
723- // read site doc.
724- let enable_interintra_compound = parser
725- .sequence_header()
726- .is_some_and(|seq| seq.enable_interintra_compound);
727- let interp_fixed = match header.interpolation_filter {
728- ec_av1_syntax::InterpolationFilter::Switchable => None,
729- fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
730- };
731- // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
732- // from that reference slot's saved CDF state instead of the spec 8.4
733- // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
734- // builds.
735- let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
736- None
737- } else {
738- let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize;
739- Some(cdf_slots[slot].clone().ok_or_else(|| {
740- Error::unsupported(
741- "AV1 decode_stream",
742- "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
743- )
744- })?)
745- };
746- let started_from = initial_cdfs.clone();
747- // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
748- decode::set_coeff_trace_frame(pictures_decoded);
749- // lane-t900 r9: one line per DECODE-order frame naming the header
750- // fields a desync cliff is usually keyed on (frame type, base q,
751- // primary_ref, the 7 ref slots, refresh mask, order hints).
752- if std::env::var_os("EC_PROBE_HDR").is_some() {
753- eprintln!(
754- "EC_HDR decode_idx={pictures_decoded} type={:?} show={} show_existing={} base_q={} primary_ref={} ref_idx={:?} refresh=0x{:02x} order_hint={} tiles={}x{} txmode={:?} interp={:?} reduced_tx={} allow_warp={} switchable_mo={} ref_mvs={} skip_mode={} cdef={:?} lr={:?}",
755- header.frame_type,
756- header.show_frame,
757- header.show_existing_frame,
758- header.quantization.base_q_idx,
759- header.primary_ref_frame,
760- header.ref_frame_idx,
761- header.refresh_frame_flags,
762- header.order_hint,
763- header.tile_info.cols,
764- header.tile_info.rows,
765- header.tx_mode,
766- header.interpolation_filter,
767- header.reduced_tx_set,
768- header.allow_warped_motion,
769- header.is_motion_mode_switchable,
770- header.use_ref_frame_mvs,
771- header.skip_mode_present,
772- header.cdef.bits,
773- header.loop_restoration.frame_restoration_type,
774- );
775- }
776-
777- let order_hint_bits = parser
778- .sequence_header()
779- .map_or(0, |seq| seq.order_hint_bits);
780- // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
781- // of the picture sitting in each of its 7 single references' DPB
782- // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
783- // (a later frame projects from it) whether or not this frame itself
784- // reads temporal candidates.
785- let ref_order_hints: [u32; 7] =
786- std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
787-
788- let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
789- let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
790- &tile_bufs,
791- &header.tile_info,
792- header.mi_cols,
793- header.mi_rows,
794- header.quantization.base_q_idx,
795- crate::quant::QuantDeltas {
796- y_dc: i32::from(header.quantization.delta_q_y_dc),
797- u_dc: i32::from(header.quantization.delta_q_u_dc),
798- u_ac: i32::from(header.quantization.delta_q_u_ac),
799- v_dc: i32::from(header.quantization.delta_q_v_dc),
800- v_ac: i32::from(header.quantization.delta_q_v_ac),
801- },
802- header.frame_width,
803- header.frame_height,
804- enable_filter_intra,
805- enable_edge_filter,
806- &header.cdef,
807- &header.loop_filter,
808- &header.loop_restoration,
809- initial_cdfs,
810- header.tx_mode == TxMode::Select,
811- header.reduced_tx_set,
812- header.allow_screen_content_tools,
813- header.allow_intrabc,
814- header.delta, fctx,
815- )?;
816- // A key frame codes no inter blocks -- its own saved motion
817- // field has no cells set, matching libaom's own "intra frame
818- // contributes nothing to a later projection" behaviour, but
819- // still carries `order_hint`/`ref_order_hints` for the distance
820- // arithmetic a later frame's projection needs.
821- let motion_field = crate::motion_field::MotionField::new(
822- header.mi_cols as usize,
823- header.mi_rows as usize,
824- header.order_hint,
825- ref_order_hints,
826- // `frame_type` for the DPB slot: a key (or intra-only) frame is
827- // never a projection source, and never spends a `ref_stamp`.
828- true,
829- );
830- (picture, end_cdfs, motion_field)
831- } else {
832- let last_slot = header.ref_frame_idx[0] as usize;
833- let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
834- Error::unsupported(
835- "AV1 decode_stream",
836- "an inter frame with no key frame before it",
837- )
838- })?;
839- // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
840- // (spec 7.8/7.20). Any of them having no picture yet is not a
841- // stream error on its own: `decode_inter_block` only needs a
842- // given slot when a block actually selects that reference, and
843- // refuses by name there if the slot is still empty -- widened
844- // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
845- // one of the 7 single-reference slots.
846- // lane-fimv r1: record the header state the fimv gate asserts on
847- // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
848- if header.force_integer_mv {
849- decode::note_force_integer_mv_frame();
850- }
851- let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
852- if ref_frame == 0 {
853- None
854- } else {
855- ref_slots
856- .get(header.ref_frame_idx[ref_frame - 1] as usize)
857- .and_then(Option::as_ref)
858- }
859- });
860- // spec 7.9's own driver, `av1_setup_motion_field`: only run when
861- // this frame's header actually asks for temporal candidates --
862- // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
863- // behaviour bit for bit when this is `None` (see its own doc).
864- let tpl_field = header.use_ref_frame_mvs.then(|| {
865- crate::motion_field::setup_motion_field(
866- &motion_field_slots,
867- header.ref_frame_idx,
868- header.order_hint,
869- order_hint_bits,
870- header.mi_rows as usize,
871- header.mi_cols as usize,
872- )
873- });
874- if std::env::var_os("EC_TPL").is_some() {
875- eprintln!(
876- "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
877- header.order_hint,
878- header.use_ref_frame_mvs,
879- tpl_field.as_ref().map_or(0, crate::motion_field::TplField::filled_cells)
880- );
881- }
882- let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
883- &tile_bufs,
884- &header.tile_info,
885- header.mi_cols,
886- header.mi_rows,
887- header.quantization.base_q_idx,
888- crate::quant::QuantDeltas {
889- y_dc: i32::from(header.quantization.delta_q_y_dc),
890- u_dc: i32::from(header.quantization.delta_q_u_dc),
891- u_ac: i32::from(header.quantization.delta_q_u_ac),
892- v_dc: i32::from(header.quantization.delta_q_v_dc),
893- v_ac: i32::from(header.quantization.delta_q_v_ac),
894- },
895- header.frame_width,
896- header.frame_height,
897- reference,
898- other_refs,
899- &header.cdef,
900- &header.loop_filter,
901- &header.loop_restoration,
902- initial_cdfs,
903- header.allow_high_precision_mv,
904- header.force_integer_mv,
905- header.ref_frame_sign_bias,
906- header.global_motion,
907- interp_fixed,
908- enable_dual_filter,
909- order_hint_bits,
910- header.order_hint,
911- ref_order_hints,
912- tpl_field.as_ref(),
913- header.reference_select,
914- enable_masked_compound,
915- enable_jnt_comp,
916- enable_interintra_compound,
917- header.skip_mode_present,
918- header.skip_mode_frame,
919- header.reduced_tx_set,
920- header.tx_mode == TxMode::Select,
921- header.is_motion_mode_switchable,
922- header.allow_warped_motion,
923- header.allow_screen_content_tools,
924- header.delta,
925- enable_filter_intra, fctx,
926- )?;
927- (picture, end_cdfs, motion_field)
928- };
929- // lane-lr r4: the Wiener/self-guided pixel filters are wired
930- // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
931- // `uses_lr` frames now decode all the way to pixels.
932- // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
933- // *initial* table into the slots it refreshes, not the adapted
934- // end-of-tile one.
935- let stored_cdfs = if header.disable_frame_end_update_cdf {
936- started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
937- } else {
938- // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
939- // the adapted table is saved with every symbol counter zeroed,
940- // not with the counts the tile's own decode left behind.
941- let mut end_cdfs = end_cdfs;
942- end_cdfs.reset_counts();
943- end_cdfs
944- };
945- if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
946- use std::io::Write;
947- if let Ok(mut f) = std::fs::OpenOptions::new()
948- .create(true)
949- .append(true)
950- .open(&path)
951- {
952- let _ = writeln!(f, "=== frame idx={} ===", pictures_shown);
953- let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
954- let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
955- let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
956- let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
957- let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
958- let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
959- let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
960- let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
961- }
962- }
963- // lane-comppin r3: decode-order (not display-order) dump of every
964- // frame's own post-deblock buffer -- the pre-existing pixel diff
965- // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
966- // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
967- // later shown frame is otherwise invisible; diff this byte-for-byte
968- // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
969- // build to isolate whether the defect is in a hidden frame's own
970- // reconstruction or downstream of it.
971- if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
972- use std::io::Write;
973- let idx = pictures_decoded;
974- if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
975- // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
976- // predates 10-bit support and is an 8-bit-oracle comparison
977- // only (aomdec's own dump is 8-bit here too).
978- let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
979- let _ = f.write_all(&narrow(&picture.y));
980- let _ = f.write_all(&narrow(&picture.u));
981- let _ = f.write_all(&narrow(&picture.v));
982- }
983- }
984- // lane-hidden r1: the frame exactly as it is about to be stored into
985- // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
986- // order, hidden (`show_frame == 0`) alt-ref frames included, and
987- // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
988- // u8-narrowing diagnostic dumps above. Matches the instrumented
989- // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
990- // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
991- // hidden frame's pixels comparable at all.
992- if let Some(prefix) = &final_dump {
993- use std::io::Write;
994- if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) {
995- let mut buf = Vec::new();
996- for plane in [&picture.y, &picture.u, &picture.v] {
997- if bit_depth == 8 {
998- buf.extend(plane.iter().map(|&s| s as u8));
999- } else {
1000- for &s in plane {
1001- buf.extend_from_slice(&s.to_le_bytes());
1002- }
1003- }
1004- }
1005- let _ = f.write_all(&buf);
1006- }
1007- }
1008 pictures_decoded += 1;509 pictures_decoded += 1;
1009- let decoded_seg_map = decode::take_segment_ids(fctx);
1010 for i in 0..NUM_REF_FRAMES {510 for i in 0..NUM_REF_FRAMES {
1011 if header.refresh_frame_flags & (1 << i) != 0 {511 if header.refresh_frame_flags & (1 << i) != 0 {
1012 cdf_slots[i] = Some(stored_cdfs.clone());512 cdf_slots[i] = Some(stored_cdfs.clone());
@@ -1029,9 +529,7 @@ pub fn decode_stream_with(
1029 }529 }
1030 if header.show_frame {530 if header.show_frame {
1031 let output = if header.film_grain.apply_grain && !no_grain() {531 let output = if header.film_grain.apply_grain && !no_grain() {
1032- let mc_identity = parser532+ let mc_identity = seq.mc_identity;
1033- .sequence_header()
1034- .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
1035 crate::film_grain::apply_grain(533 crate::film_grain::apply_grain(
1036 &picture,534 &picture,
1037 &header.film_grain,535 &header.film_grain,
@@ -1055,6 +553,639 @@ pub fn decode_stream_with(
1055 }553 }
1056 554
1057 555
556+
557+/// lane-thread2: the sequence-header bits a single frame's decode needs,
558+/// read once on the parsing thread so that [`decode_frame`] never touches the
559+/// [`Av1Parser`] (a worker thread has no access to it).
560+#[derive(Clone, Copy)]
561+pub(crate) struct SeqFlags {
562+ pub(crate) enable_filter_intra: bool,
563+ pub(crate) enable_dual_filter: bool,
564+ pub(crate) enable_edge_filter: bool,
565+ pub(crate) enable_masked_compound: bool,
566+ pub(crate) enable_jnt_comp: bool,
567+ pub(crate) enable_interintra_compound: bool,
568+ pub(crate) use_sb128: bool,
569+ pub(crate) bit_depth: u8,
570+ pub(crate) order_hint_bits: u32,
571+ pub(crate) mc_identity: bool,
572+}
573+
574+impl SeqFlags {
575+ fn read(parser: &Av1Parser) -> Self {
576+ let seq = parser.sequence_header();
577+ Self {
578+ enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
579+ enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
580+ enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
581+ enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
582+ enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
583+ enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
584+ use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
585+ bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
586+ order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
587+ mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
588+ }
589+ }
590+}
591+
592+/// lane-thread2: everything one frame's decode reads out of the cross-frame
593+/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
594+/// later frame can overwrite a slot, so a frame can be decoded anywhere.
595+pub(crate) struct RefSnapshot<'a> {
596+ /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`).
597+ pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES],
598+ /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
599+ /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
600+ /// second case is the refusal [`decode_frame`] raises where it always
601+ /// did, so the error order over a malformed stream is unchanged).
602+ pub(crate) primary_cdfs: Option<Cdfs>,
603+ /// Spec `load_previous_segment_ids`, from the same slot.
604+ pub(crate) prev_seg_map: Option<Vec<u8>>,
605+ /// Spec 7.9's projection, already run against `motion_field_slots`.
606+ pub(crate) tpl_field: Option<crate::motion_field::TplField>,
607+ /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
608+ pub(crate) ref_order_hints: [u32; 7],
609+}
610+
611+impl<'a> RefSnapshot<'a> {
612+ /// Reads the banks for `header`. `refs` is passed in so that the
613+ /// single-threaded path can borrow the DPB pictures in place while the
614+ /// worker path hands over its own `Arc` clones.
615+ fn take(
616+ header: &FrameHeader,
617+ seq: SeqFlags,
618+ refs: [Option<&'a Picture>; NUM_REF_FRAMES],
619+ cdf_slots: &[Option<Cdfs>; NUM_REF_FRAMES],
620+ seg_map_slots: &[Option<Vec<u8>>; NUM_REF_FRAMES],
621+ motion_field_slots: &[Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],
622+ order_hint_slots: &[u32; NUM_REF_FRAMES],
623+ ) -> Self {
624+ let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
625+ .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
626+ // spec 7.9's own driver, `av1_setup_motion_field`: only run when
627+ // this frame's header asks for it, and never for a key frame (which
628+ // codes no inter block at all).
629+ let tpl_field = (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(
630+ || {
631+ crate::motion_field::setup_motion_field(
632+ motion_field_slots,
633+ header.ref_frame_idx,
634+ header.order_hint,
635+ seq.order_hint_bits,
636+ header.mi_rows as usize,
637+ header.mi_cols as usize,
638+ )
639+ },
640+ );
641+ if std::env::var_os("EC_TPL").is_some() {
642+ eprintln!(
643+ "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
644+ header.order_hint,
645+ header.use_ref_frame_mvs,
646+ tpl_field
647+ .as_ref()
648+ .map_or(0, crate::motion_field::TplField::filled_cells)
649+ );
650+ }
651+ Self {
652+ refs,
653+ primary_cdfs: primary.and_then(|slot| cdf_slots[slot].clone()),
654+ prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].clone()),
655+ tpl_field,
656+ ref_order_hints: std::array::from_fn(|i| {
657+ order_hint_slots[header.ref_frame_idx[i] as usize]
658+ }),
659+ }
660+ }
661+}
662+
663+/// lane-thread2: what one decoded frame contributes back to the stream --
664+/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
665+/// `refresh_frame_flags` bit stores into a reference slot.
666+pub(crate) struct FrameOutput {
667+ pub(crate) picture: Picture,
668+ pub(crate) stored_cdfs: Cdfs,
669+ pub(crate) motion_field: crate::motion_field::MotionField,
670+ pub(crate) seg_map: Vec<u8>,
671+}
672+
673+/// lane-thread2: one coded frame, decoded from its header, its tile payload
674+/// and a snapshot of the reference banks -- and from nothing else. Lifted
675+/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
676+/// run on the parsing thread (a frame that refreshes a reference slot) or on
677+/// a worker (a leaf frame, see `decode_stream_with_threads`).
678+///
679+/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
680+/// is sound because every field this path reads is written by this function
681+/// (or by the tile decoders it calls) before it is read -- see the
682+/// `a_worker_context_starts_where_the_stream_context_would` gate.
683+///
684+/// # Errors
685+/// As [`decode_stream_with`], for this one frame.
686+#[allow(clippy::too_many_arguments)]
687+fn decode_frame(
688+ fctx: &crate::decode::FrameCtx,
689+ header: &FrameHeader,
690+ tile_bufs: &[&[u8]],
691+ seq: SeqFlags,
692+ snap: RefSnapshot<'_>,
693+ decode_idx: usize,
694+ shown_idx: usize,
695+ final_dump: Option<&str>,
696+) -> Result<FrameOutput> {
697+ if header.segmentation.enabled {
698+ for segment in 0..MAX_SEGMENTS {
699+ for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
700+ if header.segmentation.feature_enabled[segment][feature] {
701+ return Err(Error::unsupported(
702+ "AV1 decode_stream",
703+ "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
704+ ));
705+ }
706+ }
707+ }
708+ }
709+ // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
710+ // primary reference frame's slot, and is all-zero without one.
711+ decode::set_segmentation(
712+ header.segmentation,
713+ header.mi_rows as usize,
714+ header.mi_cols as usize,
715+ snap.prev_seg_map.as_deref(), fctx,
716+ );
717+ // lane-superres stage 2/3: `use_superres` adds/removes no per-block
718+ // symbol (spec 7.16's upscaling is a pixel-domain post-process
719+ // libaom's `decodeframe.c` runs between CDEF and loop restoration,
720+ // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
721+ // reads stay bit-exact in sync and `crate::superres::upscale_picture`
722+ // (below, after decode) makes its `Picture` the spec-correct
723+ // `upscaled_width` instead of silently staying at `frame_width`.
724+ // lane-superres r10: an INTER frame under `use_superres` no longer
725+ // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
726+ // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
727+ // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
728+ // at the downscaled `frame_width` and upscales its own output the
729+ // same way the key-frame branch above does (see the inter branch
730+ // below). The combinations `predict_scaled` does not cover
731+ // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
732+ // leaf) still refuse by name, deep in `decode.rs`, rather than
733+ // silently mispredicting -- see `refusal_inventory.rs`.
734+ // Loop restoration carries per-restoration-unit symbols in the tile
735+ // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
736+ // superblock walk) -- lane-lr r2 ported the reader
737+ // (`crate::restoration`), r3 moved this refusal check to AFTER the
738+ // tile decode call below (was here, before it, in r2 -- meaning
739+ // `read_lr` was NEVER actually reached through `decode_stream`, the
740+ // gap the r3 gate caught live: 40/40 attempts hit this refusal with
741+ // zero `read_lr_unit` hits). Checking post-decode instead proves the
742+ // superblock walk actually survived `read_lr` (no desync) before
743+ // refusing on the true remaining gap: decoded Wiener/SGR filters are
744+ // stored per unit but never applied to pixels.
745+ // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
746+ // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
747+ // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
748+ // zero vector only under `GmType == IDENTITY` -- any other warp
749+ // model needs the full affine/translation MV derivation this
750+ // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
751+ // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
752+ // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
753+ // to every one of the 7 single-reference slots `decode_inter_block`
754+ // can now select.
755+ //
756+ // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
757+ // exposed a real pixel mismatch --
758+ // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
759+ // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
760+ // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
761+ // is not yet provably correct end to end; keeping the refusal
762+ // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
763+ // root-caused rather than shipping a wrong decode.
764+ //
765+ // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
766+ // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
767+ // RANGE at the first divergent block (mi=(8,0), frame 1) matches
768+ // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
769+ // and this decoder's own `gm_get_motion_vector` for that block
770+ // (ROTZOOM, seed 43's own header) computes the spec-correct
771+ // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
772+ // which found and fixed a real `- 1` omission in `warp.rs` --
773+ // harmless for THIS block's rounding but a genuine spec bug fixed
774+ // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
775+ // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
776+ // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
777+ // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
778+ // with the FULL per-pixel affine global-motion warp, independent
779+ // of `motion_mode` -- this decoder only ever builds a warp
780+ // prediction for local `WARPED_CAUSAL` motion mode and falls back
781+ // to plain translational MC with the block-centre mv for every
782+ // other GLOBALMV block, which is only a centre-point approximation
783+ // of the true per-pixel warp. That is the entire remaining gap.
784+ // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
785+ // `crate::warp::global_warp_params` for every single-ref
786+ // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
787+ // `global_warp_allowed` branch -- ROTZOOM is pin-verified
788+ // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
789+ // worked (`gm_get_motion_vector`'s translation-only mv, no warp
790+ // needed). AFFINE is untested this round (no aomenc fixture in the
791+ // wedge gate reached a 6-parameter model) -- keep refusing it by
792+ // name rather than shipping an unverified decode.
793+ // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
794+ // can never write a 6-parameter model -- its encoder-side search is
795+ // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
796+ // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
797+ // which is why four rounds of `--enable-global-motion=1` recipes
798+ // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
799+ // exactly that search range in a side build, and
800+ // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
801+ // decodes its output pixel-exact against ffmpeg with
802+ // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
803+ // 6-parameter warp. Nothing in the decoder needed changing: the
804+ // header reader already reads params 4/5 with their own subexp refs
805+ // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
806+ // shear-validity check + `warp_affine` are model-agnostic.
807+ // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
808+ // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
809+ // refused the shape by name rather than guess-fix it. r5 localized
810+ // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
811+ // global-warp branch at all -- proving "two active slots" was a
812+ // correlated symptom, not the cause. r6 range-laddered that block
813+ // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
814+ // mode info -- symbol consumption bit-exact) and found the real
815+ // defect in `mvstack.rs`'s single-reference predictor fallback:
816+ // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
817+ // neighbour scan left short with this block's OWN global motion
818+ // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
819+ // whenever the live ref's global motion is itself
820+ // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
821+ // and the querying block's own stack comes up short (frame 14's
822+ // mi=(0,0), the very first block decoded, has no neighbours at
823+ // all). Fixed at the predictor fallback; the refusal above (single
824+ // untested shape: AFFINE on a single-ref frame) stays, but the
825+ // *multi-slot* refusal this comment used to guard is lifted -- the
826+ // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
827+ // byte-exact with it gone.
828+ // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
829+ // `comp_mode` per block whenever this frame's own `reference_select`
830+ // header bit is set (spec 5.11.25), and refuse by name the blocks
831+ // that pick `COMPOUND_REFERENCE` -- two-reference motion
832+ // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
833+ // is wired at the block level too (forced NEAREST_NEARESTMV compound
834+ // of `skip_mode_frame`, plain average blend), so the old blanket
835+ // `skip_mode_present` refusal is gone.
836+ // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
837+ // which tile's end-of-tile adapted CDFs become the frame's own.
838+ // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
839+ // "further down" -- it did not (`decode.rs` reads
840+ // `tile_info.context_update_tile_id` generically at both the
841+ // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
842+ // never hardcoded to tile 0); stale documentation, not a real gap.
843+ // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
844+ // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
845+ // pixel-exact, so the capability is now proven as well as described
846+ // correctly.
847+ //
848+ // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
849+ // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
850+ // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
851+ // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
852+ // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
853+ // origin receives real values at every call site (r6's
854+ // `set_tile_origin` sweep). r7 proved the two remaining
855+ // tile-*column* gaps closed (inter frames, >2 columns with loop
856+ // filtering on). r8 proved tile *rows* the same way: the per-tile
857+ // loop's row math (`tile_num / tile_info.cols`,
858+ // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
859+ // symmetric with the column path already proven, and
860+ // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
861+ // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
862+ // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
863+ // stream` below re-proves it through this entry point. Tile columns
864+ // and tile rows (any count, loop filter on) are no longer capped.
865+ // `Tile::offset` is relative to the buffer `parse_obu` was handed
866+ // (`&data[pos..]` at the time this OBU was parsed), so it is relative
867+ // to `obu_offset`, not to `data` as a whole.
868+ let enable_filter_intra = seq.enable_filter_intra;
869+ let enable_dual_filter = seq.enable_dual_filter;
870+ let enable_edge_filter = seq.enable_edge_filter;
871+ // Inter frames' intra blocks read this through a thread-local that only
872+ // the key-frame tile path used to set; without this call a stream whose
873+ // inter frames are decoded on a thread that previously decoded a
874+ // different sequence would inherit that sequence's bit.
875+ crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
876+ // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
877+ // key-frame and the inter tile path read the 128 partition root and
878+ // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
879+ // libaom's quadrant visit order into the inter loop too). A frame at
880+ // most 64x64 decodes identically either way (its 128 root reads no
881+ // symbol -- neither half is in frame, so SPLIT is inferred), so the
882+ // flag is only armed for frames bigger than one 64x64 superblock.
883+ let use_sb128 = seq.use_sb128;
884+ let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
885+ crate::decode::set_sb128(sb128_active, fctx);
886+ // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
887+ // which every dequant/inverse-transform clamp reads -- set per frame,
888+ // not once per process, for the same cross-sequence-on-one-thread
889+ // reason as `set_enable_edge_filter` above. Defaults to 8 when no
890+ // sequence header has been seen yet, matching every existing fixture.
891+ let bit_depth = seq.bit_depth;
892+ // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
893+ // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
894+ // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
895+ // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
896+ // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
897+ // Wiener rounding bits change, and neither CDEF nor film grain has a
898+ // 12-bit path. Refuse by name rather than decode silently wrong pixels.
899+ if bit_depth == 12 {
900+ return Err(Error::unsupported(
901+ "AV1 decode_stream",
902+ "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)",
903+ ));
904+ }
905+ crate::decode::set_bit_depth(bit_depth, fctx);
906+ // spec 7.16: this frame's superres state, for the filter chain --
907+ // `decode.rs` upscales between CDEF and loop restoration and sizes
908+ // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
909+ // unscaled frame so a later frame never inherits it.
910+ crate::decode::set_superres(
911+ if header.use_superres { header.upscaled_width } else { 0 },
912+ u32::from(header.superres_denom), fctx,
913+ );
914+ // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
915+ let enable_masked_compound = seq.enable_masked_compound;
916+ let enable_jnt_comp = seq.enable_jnt_comp;
917+ // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
918+ // read site doc.
919+ let enable_interintra_compound = seq.enable_interintra_compound;
920+ let interp_fixed = match header.interpolation_filter {
921+ ec_av1_syntax::InterpolationFilter::Switchable => None,
922+ fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
923+ };
924+ // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
925+ // from that reference slot's saved CDF state instead of the spec 8.4
926+ // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
927+ // builds.
928+ let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
929+ None
930+ } else {
931+ Some(snap.primary_cdfs.clone().ok_or_else(|| {
932+ Error::unsupported(
933+ "AV1 decode_stream",
934+ "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
935+ )
936+ })?)
937+ };
938+ let started_from = initial_cdfs.clone();
939+ // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
940+ decode::set_coeff_trace_frame(decode_idx);
941+ // lane-t900 r9: one line per DECODE-order frame naming the header
942+ // fields a desync cliff is usually keyed on (frame type, base q,
943+ // primary_ref, the 7 ref slots, refresh mask, order hints).
944+ if std::env::var_os("EC_PROBE_HDR").is_some() {
945+ eprintln!(
946+ "EC_HDR decode_idx={decode_idx} type={:?} show={} show_existing={} base_q={} primary_ref={} ref_idx={:?} refresh=0x{:02x} order_hint={} tiles={}x{} txmode={:?} interp={:?} reduced_tx={} allow_warp={} switchable_mo={} ref_mvs={} skip_mode={} cdef={:?} lr={:?}",
947+ header.frame_type,
948+ header.show_frame,
949+ header.show_existing_frame,
950+ header.quantization.base_q_idx,
951+ header.primary_ref_frame,
952+ header.ref_frame_idx,
953+ header.refresh_frame_flags,
954+ header.order_hint,
955+ header.tile_info.cols,
956+ header.tile_info.rows,
957+ header.tx_mode,
958+ header.interpolation_filter,
959+ header.reduced_tx_set,
960+ header.allow_warped_motion,
961+ header.is_motion_mode_switchable,
962+ header.use_ref_frame_mvs,
963+ header.skip_mode_present,
964+ header.cdef.bits,
965+ header.loop_restoration.frame_restoration_type,
966+ );
967+ }
968+
969+ let order_hint_bits = seq.order_hint_bits;
970+ // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
971+ // of the picture sitting in each of its 7 single references' DPB
972+ // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
973+ // (a later frame projects from it) whether or not this frame itself
974+ // reads temporal candidates.
975+ let ref_order_hints = snap.ref_order_hints;
976+
977+ let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
978+ let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
979+ &tile_bufs,
980+ &header.tile_info,
981+ header.mi_cols,
982+ header.mi_rows,
983+ header.quantization.base_q_idx,
984+ crate::quant::QuantDeltas {
985+ y_dc: i32::from(header.quantization.delta_q_y_dc),
986+ u_dc: i32::from(header.quantization.delta_q_u_dc),
987+ u_ac: i32::from(header.quantization.delta_q_u_ac),
988+ v_dc: i32::from(header.quantization.delta_q_v_dc),
989+ v_ac: i32::from(header.quantization.delta_q_v_ac),
990+ },
991+ header.frame_width,
992+ header.frame_height,
993+ enable_filter_intra,
994+ enable_edge_filter,
995+ &header.cdef,
996+ &header.loop_filter,
997+ &header.loop_restoration,
998+ initial_cdfs,
999+ header.tx_mode == TxMode::Select,
1000+ header.reduced_tx_set,
1001+ header.allow_screen_content_tools,
1002+ header.allow_intrabc,
1003+ header.delta, fctx,
1004+ )?;
1005+ // A key frame codes no inter blocks -- its own saved motion
1006+ // field has no cells set, matching libaom's own "intra frame
1007+ // contributes nothing to a later projection" behaviour, but
1008+ // still carries `order_hint`/`ref_order_hints` for the distance
1009+ // arithmetic a later frame's projection needs.
1010+ let motion_field = crate::motion_field::MotionField::new(
1011+ header.mi_cols as usize,
1012+ header.mi_rows as usize,
1013+ header.order_hint,
1014+ ref_order_hints,
1015+ // `frame_type` for the DPB slot: a key (or intra-only) frame is
1016+ // never a projection source, and never spends a `ref_stamp`.
1017+ true,
1018+ );
1019+ (picture, end_cdfs, motion_field)
1020+ } else {
1021+ let last_slot = header.ref_frame_idx[0] as usize;
1022+ let reference = snap.refs[last_slot].ok_or_else(|| {
1023+ Error::unsupported(
1024+ "AV1 decode_stream",
1025+ "an inter frame with no key frame before it",
1026+ )
1027+ })?;
1028+ // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1029+ // (spec 7.8/7.20). Any of them having no picture yet is not a
1030+ // stream error on its own: `decode_inter_block` only needs a
1031+ // given slot when a block actually selects that reference, and
1032+ // refuses by name there if the slot is still empty -- widened
1033+ // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
1034+ // one of the 7 single-reference slots.
1035+ // lane-fimv r1: record the header state the fimv gate asserts on
1036+ // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
1037+ if header.force_integer_mv {
1038+ decode::note_force_integer_mv_frame();
1039+ }
1040+ let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
1041+ if ref_frame == 0 {
1042+ None
1043+ } else {
1044+ snap.refs
1045+ .get(header.ref_frame_idx[ref_frame - 1] as usize)
1046+ .copied()
1047+ .flatten()
1048+ }
1049+ });
1050+ // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1051+ // this frame's header actually asks for temporal candidates --
1052+ // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1053+ // behaviour bit for bit when this is `None` (see its own doc).
1054+ let tpl_field = &snap.tpl_field;
1055+ let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1056+ &tile_bufs,
1057+ &header.tile_info,
1058+ header.mi_cols,
1059+ header.mi_rows,
1060+ header.quantization.base_q_idx,
1061+ crate::quant::QuantDeltas {
1062+ y_dc: i32::from(header.quantization.delta_q_y_dc),
1063+ u_dc: i32::from(header.quantization.delta_q_u_dc),
1064+ u_ac: i32::from(header.quantization.delta_q_u_ac),
1065+ v_dc: i32::from(header.quantization.delta_q_v_dc),
1066+ v_ac: i32::from(header.quantization.delta_q_v_ac),
1067+ },
1068+ header.frame_width,
1069+ header.frame_height,
1070+ reference,
1071+ other_refs,
1072+ &header.cdef,
1073+ &header.loop_filter,
1074+ &header.loop_restoration,
1075+ initial_cdfs,
1076+ header.allow_high_precision_mv,
1077+ header.force_integer_mv,
1078+ header.ref_frame_sign_bias,
1079+ header.global_motion,
1080+ interp_fixed,
1081+ enable_dual_filter,
1082+ order_hint_bits,
1083+ header.order_hint,
1084+ ref_order_hints,
1085+ tpl_field.as_ref(),
1086+ header.reference_select,
1087+ enable_masked_compound,
1088+ enable_jnt_comp,
1089+ enable_interintra_compound,
1090+ header.skip_mode_present,
1091+ header.skip_mode_frame,
1092+ header.reduced_tx_set,
1093+ header.tx_mode == TxMode::Select,
1094+ header.is_motion_mode_switchable,
1095+ header.allow_warped_motion,
1096+ header.allow_screen_content_tools,
1097+ header.delta,
1098+ enable_filter_intra, fctx,
1099+ )?;
1100+ (picture, end_cdfs, motion_field)
1101+ };
1102+ // lane-lr r4: the Wiener/self-guided pixel filters are wired
1103+ // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
1104+ // `uses_lr` frames now decode all the way to pixels.
1105+ // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
1106+ // *initial* table into the slots it refreshes, not the adapted
1107+ // end-of-tile one.
1108+ let stored_cdfs = if header.disable_frame_end_update_cdf {
1109+ started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1110+ } else {
1111+ // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
1112+ // the adapted table is saved with every symbol counter zeroed,
1113+ // not with the counts the tile's own decode left behind.
1114+ let mut end_cdfs = end_cdfs;
1115+ end_cdfs.reset_counts();
1116+ end_cdfs
1117+ };
1118+ if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
1119+ use std::io::Write;
1120+ if let Ok(mut f) = std::fs::OpenOptions::new()
1121+ .create(true)
1122+ .append(true)
1123+ .open(&path)
1124+ {
1125+ let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
1126+ let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
1127+ let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
1128+ let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
1129+ let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
1130+ let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
1131+ let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
1132+ let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
1133+ let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
1134+ }
1135+ }
1136+ // lane-comppin r3: decode-order (not display-order) dump of every
1137+ // frame's own post-deblock buffer -- the pre-existing pixel diff
1138+ // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
1139+ // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
1140+ // later shown frame is otherwise invisible; diff this byte-for-byte
1141+ // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
1142+ // build to isolate whether the defect is in a hidden frame's own
1143+ // reconstruction or downstream of it.
1144+ if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
1145+ use std::io::Write;
1146+ let idx = decode_idx;
1147+ if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
1148+ // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
1149+ // predates 10-bit support and is an 8-bit-oracle comparison
1150+ // only (aomdec's own dump is 8-bit here too).
1151+ let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
1152+ let _ = f.write_all(&narrow(&picture.y));
1153+ let _ = f.write_all(&narrow(&picture.u));
1154+ let _ = f.write_all(&narrow(&picture.v));
1155+ }
1156+ }
1157+ // lane-hidden r1: the frame exactly as it is about to be stored into
1158+ // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
1159+ // order, hidden (`show_frame == 0`) alt-ref frames included, and
1160+ // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
1161+ // u8-narrowing diagnostic dumps above. Matches the instrumented
1162+ // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
1163+ // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
1164+ // hidden frame's pixels comparable at all.
1165+ if let Some(prefix) = final_dump {
1166+ use std::io::Write;
1167+ if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
1168+ let mut buf = Vec::new();
1169+ for plane in [&picture.y, &picture.u, &picture.v] {
1170+ if bit_depth == 8 {
1171+ buf.extend(plane.iter().map(|&s| s as u8));
1172+ } else {
1173+ for &s in plane {
1174+ buf.extend_from_slice(&s.to_le_bytes());
1175+ }
1176+ }
1177+ }
1178+ let _ = f.write_all(&buf);
1179+ }
1180+ }
1181+ Ok(FrameOutput {
1182+ picture,
1183+ stored_cdfs,
1184+ motion_field,
1185+ seg_map: decode::take_segment_ids(fctx),
1186+ })
1187+}
1188+
1058 /// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path1189 /// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
1059 /// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from1190 /// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
1060 /// outside the crate.1191 /// outside the crate.