Merge branch 'lane-thread2' (2eee637d): per-frame decode lifted into decode_frame; leaf frames decoded on scoped worker threads with a reorder queue (EC_AV1_THREADS, default 1); byte-exact at 1 and 4 threads on four inputs, 4K 1.51x at 2 threads
Browse files at this commit2 changed files +959 -527
crates/ec-av1/examples/decode_probe.rsmodified+6 -0
| @@ -151,6 +151,12 @@ fn main() { | |||
| 151 | "uv_mode_grid_override: {}", | 151 | "uv_mode_grid_override: {}", |
| 152 | ec_av1::decode::uv_mode_grid_override_hits() | 152 | ec_av1::decode::uv_mode_grid_override_hits() |
| 153 | ); | 153 | ); |
| 154 | + // lane-thread2: proof the frame-parallel path actually fired (0 at | ||
| 155 | + // the default EC_AV1_THREADS=1). | ||
| 156 | + println!( | ||
| 157 | + "leaf_frames_dispatched: {}", | ||
| 158 | + ec_av1::stream::leaf_frames_dispatched() | ||
| 159 | + ); | ||
| 154 | }; | 160 | }; |
| 155 | // lane-tiles: the tiling a real stream actually uses is a decision input | 161 | // lane-tiles: the tiling a real stream actually uses is a decision input |
| 156 | // (every gate in `stream.rs` picks its own `--tile-columns`), so report it | 162 | // (every gate in `stream.rs` picks its own `--tile-columns`), so report it |
crates/ec-av1/src/stream.rsmodified+953 -527
| @@ -263,8 +263,117 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | |||
| 263 | /// As [`decode_stream`], plus whatever `sink` returns. | 263 | /// As [`decode_stream`], plus whatever `sink` returns. |
| 264 | pub fn decode_stream_with( | 264 | pub fn decode_stream_with( |
| 265 | data: &[u8], | 265 | data: &[u8], |
| 266 | + sink: impl FnMut(&Picture, usize, bool) -> Result<()>, | ||
| 267 | +) -> Result<()> { | ||
| 268 | + decode_stream_with_threads(data, decode_threads(), sink) | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/// lane-thread2: how many threads [`decode_stream_with`] decodes with -- | ||
| 272 | +/// `EC_AV1_THREADS`, default 1. One is not "threading with a pool of one": | ||
| 273 | +/// it is the single-threaded decoder unchanged, which is what keeps every | ||
| 274 | +/// gate that reads this crate's per-thread counters meaningful. | ||
| 275 | +fn decode_threads() -> usize { | ||
| 276 | + static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| { | ||
| 277 | + crate::envflags::var("EC_AV1_THREADS") | ||
| 278 | + .ok() | ||
| 279 | + .and_then(|v| v.parse::<usize>().ok()) | ||
| 280 | + .filter(|&n| n > 0) | ||
| 281 | + .unwrap_or(1) | ||
| 282 | + }); | ||
| 283 | + *N | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// lane-thread2: output-order queue. A leaf frame decoded on a worker | ||
| 287 | +/// finishes whenever it finishes; `sink` must still see every picture in the | ||
| 288 | +/// order the stream codes them, so each sink call gets an `emit_seq` when the | ||
| 289 | +/// main thread reaches its frame header and is held here until every earlier | ||
| 290 | +/// one has been emitted. (The decode index the sink is TOLD is unchanged, and | ||
| 291 | +/// is deliberately not unique: a `show_existing_frame` re-output reports the | ||
| 292 | +/// count of frames decoded before it, per this function's contract.) | ||
| 293 | +#[derive(Default)] | ||
| 294 | +struct Reorder { | ||
| 295 | + next: usize, | ||
| 296 | + pending: std::collections::BTreeMap<usize, (Picture, usize, bool)>, | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +impl Reorder { | ||
| 300 | + fn push(&mut self, seq: usize, picture: Picture, decode_idx: usize, shown: bool) { | ||
| 301 | + self.pending.insert(seq, (picture, decode_idx, shown)); | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + /// Emits every queued picture whose turn has come. An `Err` from `sink` | ||
| 305 | + /// aborts the decode, unchanged, exactly as the serial path did. | ||
| 306 | + fn drain( | ||
| 307 | + &mut self, | ||
| 308 | + sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>, | ||
| 309 | + ) -> Result<()> { | ||
| 310 | + while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) { | ||
| 311 | + self.next += 1; | ||
| 312 | + sink(&picture, decode_idx, shown)?; | ||
| 313 | + } | ||
| 314 | + Ok(()) | ||
| 315 | + } | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +/// lane-thread2: how many leaf frames this PROCESS has dispatched to a worker | ||
| 319 | +/// thread (see [`decode_stream_with_threads`]). Process-global and atomic on | ||
| 320 | +/// purpose: it is the only counter here a caller can read after a threaded | ||
| 321 | +/// decode, and it is what keeps a "decodes identically with 4 threads" gate | ||
| 322 | +/// from silently proving nothing because every frame ran inline. | ||
| 323 | +static LEAF_FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = | ||
| 324 | + std::sync::atomic::AtomicUsize::new(0); | ||
| 325 | + | ||
| 326 | +/// Reads [`LEAF_FRAMES_DISPATCHED`]. | ||
| 327 | +pub fn leaf_frames_dispatched() -> usize { | ||
| 328 | + LEAF_FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed) | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +/// One finished leaf frame from a worker: its output position, and either the | ||
| 332 | +/// (grain-synthesised) picture with the decode index to report or the error | ||
| 333 | +/// that aborts the stream. | ||
| 334 | +type LeafResult = (usize, Result<(Picture, usize, bool)>); | ||
| 335 | + | ||
| 336 | +/// Waits for one in-flight leaf frame and emits whatever that unblocks. | ||
| 337 | +fn collect_one( | ||
| 338 | + rx: &std::sync::mpsc::Receiver<LeafResult>, | ||
| 339 | + in_flight: &mut usize, | ||
| 340 | + reorder: &mut Reorder, | ||
| 341 | + sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>, | ||
| 342 | +) -> Result<()> { | ||
| 343 | + // Every dispatched worker answers exactly once, panic included (it is | ||
| 344 | + // caught and turned into an error below), so the sender count cannot | ||
| 345 | + // reach zero while `in_flight > 0`. | ||
| 346 | + let (seq, result) = rx | ||
| 347 | + .recv() | ||
| 348 | + .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?; | ||
| 349 | + *in_flight -= 1; | ||
| 350 | + let (picture, decode_idx, shown) = result?; | ||
| 351 | + reorder.push(seq, picture, decode_idx, shown); | ||
| 352 | + reorder.drain(sink) | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +/// [`decode_stream_with`] with an explicit worker count (lane-thread2). | ||
| 356 | +/// | ||
| 357 | +/// `threads == 1` is the serial decoder. Above that, frames that no later | ||
| 358 | +/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags` | ||
| 359 | +/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads | ||
| 360 | +/// while the main thread keeps parsing headers and decoding the frames that | ||
| 361 | +/// DO feed the reference banks; `sink` still sees every picture in coded | ||
| 362 | +/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot | ||
| 363 | +/// of the banks taken before dispatch, so no decode state is shared. | ||
| 364 | +/// | ||
| 365 | +/// The per-decode counters this crate's gates read are thread-local, so at | ||
| 366 | +/// `threads > 1` a leaf frame's counts land on the worker and are invisible | ||
| 367 | +/// to the caller; that is why the default is 1. | ||
| 368 | +/// | ||
| 369 | +/// # Errors | ||
| 370 | +/// As [`decode_stream_with`]; a worker's error aborts the stream. | ||
| 371 | +pub fn decode_stream_with_threads( | ||
| 372 | + data: &[u8], | ||
| 373 | + threads: usize, | ||
| 266 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, | 374 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, |
| 267 | ) -> Result<()> { | 375 | ) -> Result<()> { |
| 376 | + std::thread::scope(|scope| { | ||
| 268 | // lane-thread1: this stream's per-frame decode state (was 38 thread_local | 377 | // 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. | 378 | // statics in decode.rs) -- one object, threaded down the decode call graph. |
| 270 | let fctx = &crate::decode::FrameCtx::new(); | 379 | let fctx = &crate::decode::FrameCtx::new(); |
| @@ -305,6 +414,22 @@ pub fn decode_stream_with( | |||
| 305 | // and for a `segmentation_update_map == 0` frame's inherited map. | 414 | // and for a `segmentation_update_map == 0` frame's inherited map. |
| 306 | let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); | 415 | let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); |
| 307 | 416 | ||
| 417 | + // lane-thread2: output plumbing (inert at `threads == 1`, where nothing | ||
| 418 | + // is ever dispatched and `reorder` emits each picture the moment it is | ||
| 419 | + // pushed). | ||
| 420 | + let mut emit_seq = 0usize; | ||
| 421 | + let mut reorder = Reorder::default(); | ||
| 422 | + let mut in_flight = 0usize; | ||
| 423 | + let in_flight_cap = threads + 1; | ||
| 424 | + let (tx, rx) = std::sync::mpsc::channel::<LeafResult>(); | ||
| 425 | + // A worker needs its references to outlive the main thread's next | ||
| 426 | + // `refresh_frame_flags` write, so a dispatched slot is copied once into an | ||
| 427 | + // `Arc` and re-shared until that slot is overwritten (cleared alongside | ||
| 428 | + // every `ref_slots` write below). The DPB itself stays owned `Picture`s: | ||
| 429 | + // an `Arc` DPB measured ~1% SLOWER single-threaded (lane-perf9). | ||
| 430 | + let mut ref_arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = | ||
| 431 | + std::array::from_fn(|_| None); | ||
| 432 | + | ||
| 308 | let mut pos = 0usize; | 433 | let mut pos = 0usize; |
| 309 | // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec | 434 | // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec |
| 310 | // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone | 435 | // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone |
| @@ -353,6 +478,7 @@ pub fn decode_stream_with( | |||
| 353 | if header.refresh_frame_flags & (1 << i) != 0 { | 478 | if header.refresh_frame_flags & (1 << i) != 0 { |
| 354 | cdf_slots[i] = cdf_slots[slot].clone(); | 479 | cdf_slots[i] = cdf_slots[slot].clone(); |
| 355 | ref_slots[i] = Some(picture.clone()); | 480 | ref_slots[i] = Some(picture.clone()); |
| 481 | + ref_arcs[i] = None; | ||
| 356 | motion_field_slots[i] = motion_field_slots[slot].clone(); | 482 | motion_field_slots[i] = motion_field_slots[slot].clone(); |
| 357 | seg_map_slots[i] = seg_map_slots[slot].clone(); | 483 | seg_map_slots[i] = seg_map_slots[slot].clone(); |
| 358 | order_hint_slots[i] = order_hint_slots[slot]; | 484 | order_hint_slots[i] = order_hint_slots[slot]; |
| @@ -376,7 +502,9 @@ pub fn decode_stream_with( | |||
| 376 | } else { | 502 | } else { |
| 377 | picture | 503 | picture |
| 378 | }; | 504 | }; |
| 379 | - sink(&output, pictures_decoded, true)?; | 505 | + reorder.push(emit_seq, output, pictures_decoded, true); |
| 506 | + emit_seq += 1; | ||
| 507 | + reorder.drain(&mut sink)?; | ||
| 380 | pictures_shown += 1; | 508 | pictures_shown += 1; |
| 381 | continue; | 509 | continue; |
| 382 | } | 510 | } |
| @@ -473,182 +601,6 @@ pub fn decode_stream_with( | |||
| 473 | // reader on the inter path, so they still refuse by name rather than | 601 | // reader on the inter path, so they still refuse by name rather than |
| 474 | // desyncing. aomenc's `--aq-mode` segmentation only ever sets | 602 | // desyncing. aomenc's `--aq-mode` segmentation only ever sets |
| 475 | // `SEG_LVL_ALT_Q`. | 603 | // `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]> = tiles | 604 | let tile_bufs: Vec<&[u8]> = tiles |
| 653 | .iter() | 605 | .iter() |
| 654 | .map(|t| { | 606 | .map(|t| { |
| @@ -656,357 +608,125 @@ pub fn decode_stream_with( | |||
| 656 | .ok_or(Error::NeedMore) | 608 | .ok_or(Error::NeedMore) |
| 657 | }) | 609 | }) |
| 658 | .collect::<Result<_>>()?; | 610 | .collect::<Result<_>>()?; |
| 659 | - let enable_filter_intra = parser | 611 | + let seq = SeqFlags::read(&parser); |
| 660 | - .sequence_header() | 612 | + // A LEAF of the reference graph: shown, not a key frame, and |
| 661 | - .is_some_and(|seq| seq.enable_filter_intra); | 613 | + // refreshing no slot -- so nothing it produces except its own picture |
| 662 | - let enable_dual_filter = parser | 614 | + // is ever read again (spec 7.20's bank update is keyed entirely on |
| 663 | - .sequence_header() | 615 | + // `refresh_frame_flags`), and it can be decoded anywhere. |
| 664 | - .is_some_and(|seq| seq.enable_dual_filter); | 616 | + if threads > 1 |
| 665 | - let enable_edge_filter = parser | 617 | + && header.refresh_frame_flags == 0 |
| 666 | - .sequence_header() | 618 | + && header.show_frame |
| 667 | - .is_some_and(|seq| seq.enable_intra_edge_filter); | 619 | + && !header.show_existing_frame |
| 668 | - // Inter frames' intra blocks read this through a thread-local that only | 620 | + && header.frame_type != FrameType::Key |
| 669 | - // the key-frame tile path used to set; without this call a stream whose | 621 | + { |
| 670 | - // inter frames are decoded on a thread that previously decoded a | 622 | + while in_flight >= in_flight_cap { |
| 671 | - // different sequence would inherit that sequence's bit. | 623 | + collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?; |
| 672 | - crate::decode::set_enable_edge_filter(enable_edge_filter, fctx); | 624 | + } |
| 673 | - // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the | 625 | + let mut arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = |
| 674 | - // key-frame and the inter tile path read the 128 partition root and | 626 | + std::array::from_fn(|_| None); |
| 675 | - // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and | 627 | + for i in 0..7 { |
| 676 | - // libaom's quadrant visit order into the inter loop too). A frame at | 628 | + let slot = header.ref_frame_idx[i] as usize; |
| 677 | - // most 64x64 decodes identically either way (its 128 root reads no | 629 | + if arcs[slot].is_none() |
| 678 | - // symbol -- neither half is in frame, so SPLIT is inferred), so the | 630 | + && let Some(picture) = ref_slots[slot].as_ref() |
| 679 | - // flag is only armed for frames bigger than one 64x64 superblock. | 631 | + { |
| 680 | - let use_sb128 = parser | 632 | + arcs[slot] = Some( |
| 681 | - .sequence_header() | 633 | + ref_arcs[slot] |
| 682 | - .is_some_and(|seq| seq.use_128x128_superblock); | 634 | + .get_or_insert_with(|| std::sync::Arc::new(picture.clone())) |
| 683 | - let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16); | 635 | + .clone(), |
| 684 | - crate::decode::set_sb128(sb128_active, fctx); | 636 | + ); |
| 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 | } | 637 | } |
| 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 | } | 638 | } |
| 882 | - let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( | 639 | + let snap = RefSnapshot::take( |
| 883 | - &tile_bufs, | 640 | + &header, |
| 884 | - &header.tile_info, | 641 | + seq, |
| 885 | - header.mi_cols, | 642 | + std::array::from_fn(|_| None), |
| 886 | - header.mi_rows, | 643 | + &cdf_slots, |
| 887 | - header.quantization.base_q_idx, | 644 | + &seg_map_slots, |
| 888 | - crate::quant::QuantDeltas { | 645 | + &motion_field_slots, |
| 889 | - y_dc: i32::from(header.quantization.delta_q_y_dc), | 646 | + &order_hint_slots, |
| 890 | - u_dc: i32::from(header.quantization.delta_q_u_dc), | 647 | + ); |
| 891 | - u_ac: i32::from(header.quantization.delta_q_u_ac), | 648 | + let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); |
| 892 | - v_dc: i32::from(header.quantization.delta_q_v_dc), | 649 | + emit_seq += 1; |
| 893 | - v_ac: i32::from(header.quantization.delta_q_v_ac), | 650 | + pictures_decoded += 1; |
| 894 | - }, | 651 | + pictures_shown += 1; |
| 895 | - header.frame_width, | 652 | + let tx = tx.clone(); |
| 896 | - header.frame_height, | 653 | + let dump = final_dump.clone(); |
| 897 | - reference, | 654 | + scope.spawn(move || { |
| 898 | - other_refs, | 655 | + let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 899 | - &header.cdef, | 656 | + // Fresh per-thread state: every field this path reads is |
| 900 | - &header.loop_filter, | 657 | + // written from this frame's own header before it is read. |
| 901 | - &header.loop_restoration, | 658 | + let fctx = crate::decode::FrameCtx::new(); |
| 902 | - initial_cdfs, | 659 | + let snap = RefSnapshot { |
| 903 | - header.allow_high_precision_mv, | 660 | + refs: std::array::from_fn(|i| arcs[i].as_deref()), |
| 904 | - header.force_integer_mv, | 661 | + ..snap |
| 905 | - header.ref_frame_sign_bias, | 662 | + }; |
| 906 | - header.global_motion, | 663 | + let out = decode_frame( |
| 907 | - interp_fixed, | 664 | + &fctx, |
| 908 | - enable_dual_filter, | 665 | + &header, |
| 909 | - order_hint_bits, | 666 | + &tile_bufs, |
| 910 | - header.order_hint, | 667 | + seq, |
| 911 | - ref_order_hints, | 668 | + snap, |
| 912 | - tpl_field.as_ref(), | 669 | + decode_idx, |
| 913 | - header.reference_select, | 670 | + shown_idx, |
| 914 | - enable_masked_compound, | 671 | + dump.as_deref(), |
| 915 | - enable_jnt_comp, | 672 | + )?; |
| 916 | - enable_interintra_compound, | 673 | + let picture = if header.film_grain.apply_grain && !no_grain() { |
| 917 | - header.skip_mode_present, | 674 | + crate::film_grain::apply_grain( |
| 918 | - header.skip_mode_frame, | 675 | + &out.picture, |
| 919 | - header.reduced_tx_set, | 676 | + &header.film_grain, |
| 920 | - header.tx_mode == TxMode::Select, | 677 | + seq.mc_identity, |
| 921 | - header.is_motion_mode_switchable, | 678 | + u32::from(seq.bit_depth), |
| 922 | - header.allow_warped_motion, | 679 | + &fctx, |
| 923 | - header.allow_screen_content_tools, | 680 | + ) |
| 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 { | 681 | } else { |
| 1000 | - for &s in plane { | 682 | + out.picture |
| 1001 | - buf.extend_from_slice(&s.to_le_bytes()); | 683 | + }; |
| 1002 | - } | 684 | + Ok((picture, decode_idx, true)) |
| 1003 | - } | 685 | + })) |
| 1004 | - } | 686 | + .unwrap_or_else(|_| { |
| 1005 | - let _ = f.write_all(&buf); | 687 | + Err(Error::corrupt( |
| 688 | + "AV1 decode_stream: a worker thread panicked decoding a leaf frame", | ||
| 689 | + )) | ||
| 690 | + }); | ||
| 691 | + let _ = tx.send((job_seq, reply)); | ||
| 692 | + }); | ||
| 693 | + in_flight += 1; | ||
| 694 | + LEAF_FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 695 | + // Anything that finished while this frame was being set up. | ||
| 696 | + while let Ok((seq, result)) = rx.try_recv() { | ||
| 697 | + in_flight -= 1; | ||
| 698 | + let (picture, decode_idx, shown) = result?; | ||
| 699 | + reorder.push(seq, picture, decode_idx, shown); | ||
| 700 | + reorder.drain(&mut sink)?; | ||
| 1006 | } | 701 | } |
| 702 | + continue; | ||
| 1007 | } | 703 | } |
| 704 | + let snap = RefSnapshot::take( | ||
| 705 | + &header, | ||
| 706 | + seq, | ||
| 707 | + std::array::from_fn(|i| ref_slots[i].as_ref()), | ||
| 708 | + &cdf_slots, | ||
| 709 | + &seg_map_slots, | ||
| 710 | + &motion_field_slots, | ||
| 711 | + &order_hint_slots, | ||
| 712 | + ); | ||
| 713 | + let bit_depth = seq.bit_depth; | ||
| 714 | + let FrameOutput { | ||
| 715 | + picture, | ||
| 716 | + stored_cdfs, | ||
| 717 | + motion_field, | ||
| 718 | + seg_map: decoded_seg_map, | ||
| 719 | + } = decode_frame( | ||
| 720 | + fctx, | ||
| 721 | + &header, | ||
| 722 | + &tile_bufs, | ||
| 723 | + seq, | ||
| 724 | + snap, | ||
| 725 | + pictures_decoded, | ||
| 726 | + pictures_shown, | ||
| 727 | + final_dump.as_deref(), | ||
| 728 | + )?; | ||
| 1008 | pictures_decoded += 1; | 729 | pictures_decoded += 1; |
| 1009 | - let decoded_seg_map = decode::take_segment_ids(fctx); | ||
| 1010 | for i in 0..NUM_REF_FRAMES { | 730 | for i in 0..NUM_REF_FRAMES { |
| 1011 | if header.refresh_frame_flags & (1 << i) != 0 { | 731 | if header.refresh_frame_flags & (1 << i) != 0 { |
| 1012 | cdf_slots[i] = Some(stored_cdfs.clone()); | 732 | cdf_slots[i] = Some(stored_cdfs.clone()); |
| @@ -1015,6 +735,7 @@ pub fn decode_stream_with( | |||
| 1015 | // pre-grain decode, even though the frame pushed onto the | 735 | // pre-grain decode, even though the frame pushed onto the |
| 1016 | // caller's output below carries the grained picture. | 736 | // caller's output below carries the grained picture. |
| 1017 | ref_slots[i] = Some(picture.clone()); | 737 | ref_slots[i] = Some(picture.clone()); |
| 738 | + ref_arcs[i] = None; | ||
| 1018 | motion_field_slots[i] = Some(motion_field.clone()); | 739 | motion_field_slots[i] = Some(motion_field.clone()); |
| 1019 | seg_map_slots[i] = Some(decoded_seg_map.clone()); | 740 | seg_map_slots[i] = Some(decoded_seg_map.clone()); |
| 1020 | order_hint_slots[i] = header.order_hint; | 741 | order_hint_slots[i] = header.order_hint; |
| @@ -1029,9 +750,7 @@ pub fn decode_stream_with( | |||
| 1029 | } | 750 | } |
| 1030 | if header.show_frame { | 751 | if header.show_frame { |
| 1031 | let output = if header.film_grain.apply_grain && !no_grain() { | 752 | let output = if header.film_grain.apply_grain && !no_grain() { |
| 1032 | - let mc_identity = parser | 753 | + 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( | 754 | crate::film_grain::apply_grain( |
| 1036 | &picture, | 755 | &picture, |
| 1037 | &header.film_grain, | 756 | &header.film_grain, |
| @@ -1041,19 +760,661 @@ pub fn decode_stream_with( | |||
| 1041 | } else { | 760 | } else { |
| 1042 | picture | 761 | picture |
| 1043 | }; | 762 | }; |
| 1044 | - sink(&output, pictures_decoded - 1, true)?; | 763 | + reorder.push(emit_seq, output, pictures_decoded - 1, true); |
| 764 | + emit_seq += 1; | ||
| 765 | + reorder.drain(&mut sink)?; | ||
| 1045 | pictures_shown += 1; | 766 | pictures_shown += 1; |
| 1046 | } else { | 767 | } else { |
| 1047 | // Hidden (alt-ref/forward-key) frames never reach | 768 | // Hidden (alt-ref/forward-key) frames never reach |
| 1048 | // `decode_stream`'s output, but a decode-order consumer -- the | 769 | // `decode_stream`'s output, but a decode-order consumer -- the |
| 1049 | // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs | 770 | // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs |
| 1050 | // them, so they are reported too, with `shown == false`. | 771 | // them, so they are reported too, with `shown == false`. |
| 1051 | - sink(&picture, pictures_decoded - 1, false)?; | 772 | + reorder.push(emit_seq, picture, pictures_decoded - 1, false); |
| 773 | + emit_seq += 1; | ||
| 774 | + reorder.drain(&mut sink)?; | ||
| 1052 | } | 775 | } |
| 1053 | } | 776 | } |
| 777 | + while in_flight > 0 { | ||
| 778 | + collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?; | ||
| 779 | + } | ||
| 780 | + debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); | ||
| 1054 | Ok(()) | 781 | Ok(()) |
| 782 | + }) | ||
| 783 | +} | ||
| 784 | + | ||
| 785 | + | ||
| 786 | + | ||
| 787 | +/// lane-thread2: the sequence-header bits a single frame's decode needs, | ||
| 788 | +/// read once on the parsing thread so that [`decode_frame`] never touches the | ||
| 789 | +/// [`Av1Parser`] (a worker thread has no access to it). | ||
| 790 | +#[derive(Clone, Copy)] | ||
| 791 | +pub(crate) struct SeqFlags { | ||
| 792 | + pub(crate) enable_filter_intra: bool, | ||
| 793 | + pub(crate) enable_dual_filter: bool, | ||
| 794 | + pub(crate) enable_edge_filter: bool, | ||
| 795 | + pub(crate) enable_masked_compound: bool, | ||
| 796 | + pub(crate) enable_jnt_comp: bool, | ||
| 797 | + pub(crate) enable_interintra_compound: bool, | ||
| 798 | + pub(crate) use_sb128: bool, | ||
| 799 | + pub(crate) bit_depth: u8, | ||
| 800 | + pub(crate) order_hint_bits: u32, | ||
| 801 | + pub(crate) mc_identity: bool, | ||
| 802 | +} | ||
| 803 | + | ||
| 804 | +impl SeqFlags { | ||
| 805 | + fn read(parser: &Av1Parser) -> Self { | ||
| 806 | + let seq = parser.sequence_header(); | ||
| 807 | + Self { | ||
| 808 | + enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra), | ||
| 809 | + enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter), | ||
| 810 | + enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter), | ||
| 811 | + enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound), | ||
| 812 | + enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp), | ||
| 813 | + enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound), | ||
| 814 | + use_sb128: seq.is_some_and(|s| s.use_128x128_superblock), | ||
| 815 | + bit_depth: seq.map_or(8, |s| s.color_config.bit_depth), | ||
| 816 | + order_hint_bits: seq.map_or(0, |s| s.order_hint_bits), | ||
| 817 | + mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0), | ||
| 818 | + } | ||
| 819 | + } | ||
| 820 | +} | ||
| 821 | + | ||
| 822 | +/// lane-thread2: everything one frame's decode reads out of the cross-frame | ||
| 823 | +/// banks `decode_stream_with` owns -- taken on the parsing thread, before any | ||
| 824 | +/// later frame can overwrite a slot, so a frame can be decoded anywhere. | ||
| 825 | +pub(crate) struct RefSnapshot<'a> { | ||
| 826 | + /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`). | ||
| 827 | + pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES], | ||
| 828 | + /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame | ||
| 829 | + /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the | ||
| 830 | + /// second case is the refusal [`decode_frame`] raises where it always | ||
| 831 | + /// did, so the error order over a malformed stream is unchanged). | ||
| 832 | + pub(crate) primary_cdfs: Option<Cdfs>, | ||
| 833 | + /// Spec `load_previous_segment_ids`, from the same slot. | ||
| 834 | + pub(crate) prev_seg_map: Option<Vec<u8>>, | ||
| 835 | + /// Spec 7.9's projection, already run against `motion_field_slots`. | ||
| 836 | + pub(crate) tpl_field: Option<crate::motion_field::TplField>, | ||
| 837 | + /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`. | ||
| 838 | + pub(crate) ref_order_hints: [u32; 7], | ||
| 839 | +} | ||
| 840 | + | ||
| 841 | +impl<'a> RefSnapshot<'a> { | ||
| 842 | + /// Reads the banks for `header`. `refs` is passed in so that the | ||
| 843 | + /// single-threaded path can borrow the DPB pictures in place while the | ||
| 844 | + /// worker path hands over its own `Arc` clones. | ||
| 845 | + fn take( | ||
| 846 | + header: &FrameHeader, | ||
| 847 | + seq: SeqFlags, | ||
| 848 | + refs: [Option<&'a Picture>; NUM_REF_FRAMES], | ||
| 849 | + cdf_slots: &[Option<Cdfs>; NUM_REF_FRAMES], | ||
| 850 | + seg_map_slots: &[Option<Vec<u8>>; NUM_REF_FRAMES], | ||
| 851 | + motion_field_slots: &[Option<crate::motion_field::MotionField>; NUM_REF_FRAMES], | ||
| 852 | + order_hint_slots: &[u32; NUM_REF_FRAMES], | ||
| 853 | + ) -> Self { | ||
| 854 | + let primary = (header.primary_ref_frame != PRIMARY_REF_NONE) | ||
| 855 | + .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize); | ||
| 856 | + // spec 7.9's own driver, `av1_setup_motion_field`: only run when | ||
| 857 | + // this frame's header asks for it, and never for a key frame (which | ||
| 858 | + // codes no inter block at all). | ||
| 859 | + let tpl_field = (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then( | ||
| 860 | + || { | ||
| 861 | + crate::motion_field::setup_motion_field( | ||
| 862 | + motion_field_slots, | ||
| 863 | + header.ref_frame_idx, | ||
| 864 | + header.order_hint, | ||
| 865 | + seq.order_hint_bits, | ||
| 866 | + header.mi_rows as usize, | ||
| 867 | + header.mi_cols as usize, | ||
| 868 | + ) | ||
| 869 | + }, | ||
| 870 | + ); | ||
| 871 | + if std::env::var_os("EC_TPL").is_some() { | ||
| 872 | + eprintln!( | ||
| 873 | + "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}", | ||
| 874 | + header.order_hint, | ||
| 875 | + header.use_ref_frame_mvs, | ||
| 876 | + tpl_field | ||
| 877 | + .as_ref() | ||
| 878 | + .map_or(0, crate::motion_field::TplField::filled_cells) | ||
| 879 | + ); | ||
| 880 | + } | ||
| 881 | + Self { | ||
| 882 | + refs, | ||
| 883 | + primary_cdfs: primary.and_then(|slot| cdf_slots[slot].clone()), | ||
| 884 | + prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].clone()), | ||
| 885 | + tpl_field, | ||
| 886 | + ref_order_hints: std::array::from_fn(|i| { | ||
| 887 | + order_hint_slots[header.ref_frame_idx[i] as usize] | ||
| 888 | + }), | ||
| 889 | + } | ||
| 890 | + } | ||
| 891 | +} | ||
| 892 | + | ||
| 893 | +/// lane-thread2: what one decoded frame contributes back to the stream -- | ||
| 894 | +/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a | ||
| 895 | +/// `refresh_frame_flags` bit stores into a reference slot. | ||
| 896 | +pub(crate) struct FrameOutput { | ||
| 897 | + pub(crate) picture: Picture, | ||
| 898 | + pub(crate) stored_cdfs: Cdfs, | ||
| 899 | + pub(crate) motion_field: crate::motion_field::MotionField, | ||
| 900 | + pub(crate) seg_map: Vec<u8>, | ||
| 1055 | } | 901 | } |
| 1056 | 902 | ||
| 903 | +/// lane-thread2: one coded frame, decoded from its header, its tile payload | ||
| 904 | +/// and a snapshot of the reference banks -- and from nothing else. Lifted | ||
| 905 | +/// verbatim out of [`decode_stream_with`]'s loop so that the same code can | ||
| 906 | +/// run on the parsing thread (a frame that refreshes a reference slot) or on | ||
| 907 | +/// a worker (a leaf frame, see `decode_stream_with_threads`). | ||
| 908 | +/// | ||
| 909 | +/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which | ||
| 910 | +/// is sound because every field this path reads is written by this function | ||
| 911 | +/// (or by the tile decoders it calls) before it is read -- see the | ||
| 912 | +/// `a_worker_context_starts_where_the_stream_context_would` gate. | ||
| 913 | +/// | ||
| 914 | +/// # Errors | ||
| 915 | +/// As [`decode_stream_with`], for this one frame. | ||
| 916 | +#[allow(clippy::too_many_arguments)] | ||
| 917 | +fn decode_frame( | ||
| 918 | + fctx: &crate::decode::FrameCtx, | ||
| 919 | + header: &FrameHeader, | ||
| 920 | + tile_bufs: &[&[u8]], | ||
| 921 | + seq: SeqFlags, | ||
| 922 | + snap: RefSnapshot<'_>, | ||
| 923 | + decode_idx: usize, | ||
| 924 | + shown_idx: usize, | ||
| 925 | + final_dump: Option<&str>, | ||
| 926 | +) -> Result<FrameOutput> { | ||
| 927 | + if header.segmentation.enabled { | ||
| 928 | + for segment in 0..MAX_SEGMENTS { | ||
| 929 | + for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { | ||
| 930 | + if header.segmentation.feature_enabled[segment][feature] { | ||
| 931 | + return Err(Error::unsupported( | ||
| 932 | + "AV1 decode_stream", | ||
| 933 | + "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)", | ||
| 934 | + )); | ||
| 935 | + } | ||
| 936 | + } | ||
| 937 | + } | ||
| 938 | + } | ||
| 939 | + // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the | ||
| 940 | + // primary reference frame's slot, and is all-zero without one. | ||
| 941 | + decode::set_segmentation( | ||
| 942 | + header.segmentation, | ||
| 943 | + header.mi_rows as usize, | ||
| 944 | + header.mi_cols as usize, | ||
| 945 | + snap.prev_seg_map.as_deref(), fctx, | ||
| 946 | + ); | ||
| 947 | + // lane-superres stage 2/3: `use_superres` adds/removes no per-block | ||
| 948 | + // symbol (spec 7.16's upscaling is a pixel-domain post-process | ||
| 949 | + // libaom's `decodeframe.c` runs between CDEF and loop restoration, | ||
| 950 | + // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile | ||
| 951 | + // reads stay bit-exact in sync and `crate::superres::upscale_picture` | ||
| 952 | + // (below, after decode) makes its `Picture` the spec-correct | ||
| 953 | + // `upscaled_width` instead of silently staying at `frame_width`. | ||
| 954 | + // lane-superres r10: an INTER frame under `use_superres` no longer | ||
| 955 | + // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3) | ||
| 956 | + // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/ | ||
| 957 | + // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes | ||
| 958 | + // at the downscaled `frame_width` and upscales its own output the | ||
| 959 | + // same way the key-frame branch above does (see the inter branch | ||
| 960 | + // below). The combinations `predict_scaled` does not cover | ||
| 961 | + // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8 | ||
| 962 | + // leaf) still refuse by name, deep in `decode.rs`, rather than | ||
| 963 | + // silently mispredicting -- see `refusal_inventory.rs`. | ||
| 964 | + // Loop restoration carries per-restoration-unit symbols in the tile | ||
| 965 | + // (spec 5.11.57 `read_lr`, one group per LR unit reached from the | ||
| 966 | + // superblock walk) -- lane-lr r2 ported the reader | ||
| 967 | + // (`crate::restoration`), r3 moved this refusal check to AFTER the | ||
| 968 | + // tile decode call below (was here, before it, in r2 -- meaning | ||
| 969 | + // `read_lr` was NEVER actually reached through `decode_stream`, the | ||
| 970 | + // gap the r3 gate caught live: 40/40 attempts hit this refusal with | ||
| 971 | + // zero `read_lr_unit` hits). Checking post-decode instead proves the | ||
| 972 | + // superblock walk actually survived `read_lr` (no desync) before | ||
| 973 | + // refusing on the true remaining gap: decoded Wiener/SGR filters are | ||
| 974 | + // stored per unit but never applied to pixels. | ||
| 975 | + // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec | ||
| 976 | + // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV` | ||
| 977 | + // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the | ||
| 978 | + // zero vector only under `GmType == IDENTITY` -- any other warp | ||
| 979 | + // model needs the full affine/translation MV derivation this | ||
| 980 | + // decoder does not carry. `global_motion` is indexed `ref_frame - 1` | ||
| 981 | + // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`); | ||
| 982 | + // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME) | ||
| 983 | + // to every one of the 7 single-reference slots `decode_inter_block` | ||
| 984 | + // can now select. | ||
| 985 | + // | ||
| 986 | + // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal | ||
| 987 | + // exposed a real pixel mismatch -- | ||
| 988 | + // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact | ||
| 989 | + // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20 | ||
| 990 | + // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring | ||
| 991 | + // is not yet provably correct end to end; keeping the refusal | ||
| 992 | + // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and | ||
| 993 | + // root-caused rather than shipping a wrong decode. | ||
| 994 | + // | ||
| 995 | + // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not | ||
| 996 | + // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac | ||
| 997 | + // RANGE at the first divergent block (mi=(8,0), frame 1) matches | ||
| 998 | + // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides), | ||
| 999 | + // and this decoder's own `gm_get_motion_vector` for that block | ||
| 1000 | + // (ROTZOOM, seed 43's own header) computes the spec-correct | ||
| 1001 | + // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`, | ||
| 1002 | + // which found and fixed a real `- 1` omission in `warp.rs` -- | ||
| 1003 | + // harmless for THIS block's rounding but a genuine spec bug fixed | ||
| 1004 | + // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a | ||
| 1005 | + // `global_warp_allowed` branch (`warp_types.global_warp_allowed = | ||
| 1006 | + // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts | ||
| 1007 | + // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8) | ||
| 1008 | + // with the FULL per-pixel affine global-motion warp, independent | ||
| 1009 | + // of `motion_mode` -- this decoder only ever builds a warp | ||
| 1010 | + // prediction for local `WARPED_CAUSAL` motion mode and falls back | ||
| 1011 | + // to plain translational MC with the block-centre mv for every | ||
| 1012 | + // other GLOBALMV block, which is only a centre-point approximation | ||
| 1013 | + // of the true per-pixel warp. That is the entire remaining gap. | ||
| 1014 | + // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into | ||
| 1015 | + // `crate::warp::global_warp_params` for every single-ref | ||
| 1016 | + // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s | ||
| 1017 | + // `global_warp_allowed` branch -- ROTZOOM is pin-verified | ||
| 1018 | + // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already | ||
| 1019 | + // worked (`gm_get_motion_vector`'s translation-only mv, no warp | ||
| 1020 | + // needed). AFFINE is untested this round (no aomenc fixture in the | ||
| 1021 | + // wedge gate reached a 6-parameter model) -- keep refusing it by | ||
| 1022 | + // name rather than shipping an unverified decode. | ||
| 1023 | + // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom | ||
| 1024 | + // can never write a 6-parameter model -- its encoder-side search is | ||
| 1025 | + // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`, | ||
| 1026 | + // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) -- | ||
| 1027 | + // which is why four rounds of `--enable-global-motion=1` recipes | ||
| 1028 | + // never reached the case. `scripts/build-aom-affine-oracle.sh` widens | ||
| 1029 | + // exactly that search range in a side build, and | ||
| 1030 | + // `a_real_affine_global_motion_stream_decodes_pixel_exact` below | ||
| 1031 | + // decodes its output pixel-exact against ffmpeg with | ||
| 1032 | + // `affine_gm_hits() > 0`, i.e. real blocks predicted through the | ||
| 1033 | + // 6-parameter warp. Nothing in the decoder needed changing: the | ||
| 1034 | + // header reader already reads params 4/5 with their own subexp refs | ||
| 1035 | + // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s | ||
| 1036 | + // shear-validity check + `warp_affine` are model-agnostic. | ||
| 1037 | + // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two | ||
| 1038 | + // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and | ||
| 1039 | + // refused the shape by name rather than guess-fix it. r5 localized | ||
| 1040 | + // the mismatch to an ordinary NEWMV/GOLDEN block, not the new | ||
| 1041 | + // global-warp branch at all -- proving "two active slots" was a | ||
| 1042 | + // correlated symptom, not the cause. r6 range-laddered that block | ||
| 1043 | + // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after | ||
| 1044 | + // mode info -- symbol consumption bit-exact) and found the real | ||
| 1045 | + // defect in `mvstack.rs`'s single-reference predictor fallback: | ||
| 1046 | + // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real | ||
| 1047 | + // neighbour scan left short with this block's OWN global motion | ||
| 1048 | + // vector for its ref (`gm_get_motion_vector`), not zero -- invisible | ||
| 1049 | + // whenever the live ref's global motion is itself | ||
| 1050 | + // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE | ||
| 1051 | + // and the querying block's own stack comes up short (frame 14's | ||
| 1052 | + // mi=(0,0), the very first block decoded, has no neighbours at | ||
| 1053 | + // all). Fixed at the predictor fallback; the refusal above (single | ||
| 1054 | + // untested shape: AFFINE on a single-ref frame) stays, but the | ||
| 1055 | + // *multi-slot* refusal this comment used to guard is lifted -- the | ||
| 1056 | + // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames | ||
| 1057 | + // byte-exact with it gone. | ||
| 1058 | + // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read | ||
| 1059 | + // `comp_mode` per block whenever this frame's own `reference_select` | ||
| 1060 | + // header bit is set (spec 5.11.25), and refuse by name the blocks | ||
| 1061 | + // that pick `COMPOUND_REFERENCE` -- two-reference motion | ||
| 1062 | + // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22) | ||
| 1063 | + // is wired at the block level too (forced NEAREST_NEARESTMV compound | ||
| 1064 | + // of `skip_mode_frame`, plain average blend), so the old blanket | ||
| 1065 | + // `skip_mode_present` refusal is gone. | ||
| 1066 | + // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names | ||
| 1067 | + // which tile's end-of-tile adapted CDFs become the frame's own. | ||
| 1068 | + // lane-tiles r8: this comment used to claim a `!= 0` refusal existed | ||
| 1069 | + // "further down" -- it did not (`decode.rs` reads | ||
| 1070 | + // `tile_info.context_update_tile_id` generically at both the | ||
| 1071 | + // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites, | ||
| 1072 | + // never hardcoded to tile 0); stale documentation, not a real gap. | ||
| 1073 | + // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact` | ||
| 1074 | + // hard-asserts a live aomenc stream naming tile 1/2/3 decodes | ||
| 1075 | + // pixel-exact, so the capability is now proven as well as described | ||
| 1076 | + // correctly. | ||
| 1077 | + // | ||
| 1078 | + // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped, | ||
| 1079 | + // not blanket. `decode_key_frame_tile_with_cdfs` and (r6) | ||
| 1080 | + // `decode_inter_frame_tile_with_cdfs` both genuinely loop every | ||
| 1081 | + // tile, `mvstack.rs`'s `MiGrid` is bounded per tile | ||
| 1082 | + // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1` | ||
| 1083 | + // origin receives real values at every call site (r6's | ||
| 1084 | + // `set_tile_origin` sweep). r7 proved the two remaining | ||
| 1085 | + // tile-*column* gaps closed (inter frames, >2 columns with loop | ||
| 1086 | + // filtering on). r8 proved tile *rows* the same way: the per-tile | ||
| 1087 | + // loop's row math (`tile_num / tile_info.cols`, | ||
| 1088 | + // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly | ||
| 1089 | + // symmetric with the column path already proven, and | ||
| 1090 | + // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact` | ||
| 1091 | + // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact. | ||
| 1092 | + // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_ | ||
| 1093 | + // stream` below re-proves it through this entry point. Tile columns | ||
| 1094 | + // and tile rows (any count, loop filter on) are no longer capped. | ||
| 1095 | + // `Tile::offset` is relative to the buffer `parse_obu` was handed | ||
| 1096 | + // (`&data[pos..]` at the time this OBU was parsed), so it is relative | ||
| 1097 | + // to `obu_offset`, not to `data` as a whole. | ||
| 1098 | + let enable_filter_intra = seq.enable_filter_intra; | ||
| 1099 | + let enable_dual_filter = seq.enable_dual_filter; | ||
| 1100 | + let enable_edge_filter = seq.enable_edge_filter; | ||
| 1101 | + // Inter frames' intra blocks read this through a thread-local that only | ||
| 1102 | + // the key-frame tile path used to set; without this call a stream whose | ||
| 1103 | + // inter frames are decoded on a thread that previously decoded a | ||
| 1104 | + // different sequence would inherit that sequence's bit. | ||
| 1105 | + crate::decode::set_enable_edge_filter(enable_edge_filter, fctx); | ||
| 1106 | + // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the | ||
| 1107 | + // key-frame and the inter tile path read the 128 partition root and | ||
| 1108 | + // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and | ||
| 1109 | + // libaom's quadrant visit order into the inter loop too). A frame at | ||
| 1110 | + // most 64x64 decodes identically either way (its 128 root reads no | ||
| 1111 | + // symbol -- neither half is in frame, so SPLIT is inferred), so the | ||
| 1112 | + // flag is only armed for frames bigger than one 64x64 superblock. | ||
| 1113 | + let use_sb128 = seq.use_sb128; | ||
| 1114 | + let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16); | ||
| 1115 | + crate::decode::set_sb128(sb128_active, fctx); | ||
| 1116 | + // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`, | ||
| 1117 | + // which every dequant/inverse-transform clamp reads -- set per frame, | ||
| 1118 | + // not once per process, for the same cross-sequence-on-one-thread | ||
| 1119 | + // reason as `set_enable_edge_filter` above. Defaults to 8 when no | ||
| 1120 | + // sequence header has been seen yet, matching every existing fixture. | ||
| 1121 | + let bit_depth = seq.bit_depth; | ||
| 1122 | + // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every | ||
| 1123 | + // rounding shift below is written for 8/10-bit only -- `warp.rs`'s | ||
| 1124 | + // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses | ||
| 1125 | + // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the | ||
| 1126 | + // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the | ||
| 1127 | + // Wiener rounding bits change, and neither CDEF nor film grain has a | ||
| 1128 | + // 12-bit path. Refuse by name rather than decode silently wrong pixels. | ||
| 1129 | + if bit_depth == 12 { | ||
| 1130 | + return Err(Error::unsupported( | ||
| 1131 | + "AV1 decode_stream", | ||
| 1132 | + "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)", | ||
| 1133 | + )); | ||
| 1134 | + } | ||
| 1135 | + crate::decode::set_bit_depth(bit_depth, fctx); | ||
| 1136 | + // spec 7.16: this frame's superres state, for the filter chain -- | ||
| 1137 | + // `decode.rs` upscales between CDEF and loop restoration and sizes | ||
| 1138 | + // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an | ||
| 1139 | + // unscaled frame so a later frame never inherits it. | ||
| 1140 | + crate::decode::set_superres( | ||
| 1141 | + if header.use_superres { header.upscaled_width } else { 0 }, | ||
| 1142 | + u32::from(header.superres_denom), fctx, | ||
| 1143 | + ); | ||
| 1144 | + // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. | ||
| 1145 | + let enable_masked_compound = seq.enable_masked_compound; | ||
| 1146 | + let enable_jnt_comp = seq.enable_jnt_comp; | ||
| 1147 | + // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's | ||
| 1148 | + // read site doc. | ||
| 1149 | + let enable_interintra_compound = seq.enable_interintra_compound; | ||
| 1150 | + let interp_fixed = match header.interpolation_filter { | ||
| 1151 | + ec_av1_syntax::InterpolationFilter::Switchable => None, | ||
| 1152 | + fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), | ||
| 1153 | + }; | ||
| 1154 | + // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes | ||
| 1155 | + // from that reference slot's saved CDF state instead of the spec 8.4 | ||
| 1156 | + // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case | ||
| 1157 | + // builds. | ||
| 1158 | + let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE { | ||
| 1159 | + None | ||
| 1160 | + } else { | ||
| 1161 | + Some(snap.primary_cdfs.clone().ok_or_else(|| { | ||
| 1162 | + Error::unsupported( | ||
| 1163 | + "AV1 decode_stream", | ||
| 1164 | + "a frame naming primary_ref_frame at a reference slot with no saved CDF state", | ||
| 1165 | + ) | ||
| 1166 | + })?) | ||
| 1167 | + }; | ||
| 1168 | + let started_from = initial_cdfs.clone(); | ||
| 1169 | + // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame. | ||
| 1170 | + decode::set_coeff_trace_frame(decode_idx); | ||
| 1171 | + // lane-t900 r9: one line per DECODE-order frame naming the header | ||
| 1172 | + // fields a desync cliff is usually keyed on (frame type, base q, | ||
| 1173 | + // primary_ref, the 7 ref slots, refresh mask, order hints). | ||
| 1174 | + if std::env::var_os("EC_PROBE_HDR").is_some() { | ||
| 1175 | + eprintln!( | ||
| 1176 | + "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={:?}", | ||
| 1177 | + header.frame_type, | ||
| 1178 | + header.show_frame, | ||
| 1179 | + header.show_existing_frame, | ||
| 1180 | + header.quantization.base_q_idx, | ||
| 1181 | + header.primary_ref_frame, | ||
| 1182 | + header.ref_frame_idx, | ||
| 1183 | + header.refresh_frame_flags, | ||
| 1184 | + header.order_hint, | ||
| 1185 | + header.tile_info.cols, | ||
| 1186 | + header.tile_info.rows, | ||
| 1187 | + header.tx_mode, | ||
| 1188 | + header.interpolation_filter, | ||
| 1189 | + header.reduced_tx_set, | ||
| 1190 | + header.allow_warped_motion, | ||
| 1191 | + header.is_motion_mode_switchable, | ||
| 1192 | + header.use_ref_frame_mvs, | ||
| 1193 | + header.skip_mode_present, | ||
| 1194 | + header.cdef.bits, | ||
| 1195 | + header.loop_restoration.frame_restoration_type, | ||
| 1196 | + ); | ||
| 1197 | + } | ||
| 1198 | + | ||
| 1199 | + let order_hint_bits = seq.order_hint_bits; | ||
| 1200 | + // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint | ||
| 1201 | + // of the picture sitting in each of its 7 single references' DPB | ||
| 1202 | + // slots, for this frame's *own* saved [`crate::motion_field::MotionField`] | ||
| 1203 | + // (a later frame projects from it) whether or not this frame itself | ||
| 1204 | + // reads temporal candidates. | ||
| 1205 | + let ref_order_hints = snap.ref_order_hints; | ||
| 1206 | + | ||
| 1207 | + let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { | ||
| 1208 | + let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( | ||
| 1209 | + &tile_bufs, | ||
| 1210 | + &header.tile_info, | ||
| 1211 | + header.mi_cols, | ||
| 1212 | + header.mi_rows, | ||
| 1213 | + header.quantization.base_q_idx, | ||
| 1214 | + crate::quant::QuantDeltas { | ||
| 1215 | + y_dc: i32::from(header.quantization.delta_q_y_dc), | ||
| 1216 | + u_dc: i32::from(header.quantization.delta_q_u_dc), | ||
| 1217 | + u_ac: i32::from(header.quantization.delta_q_u_ac), | ||
| 1218 | + v_dc: i32::from(header.quantization.delta_q_v_dc), | ||
| 1219 | + v_ac: i32::from(header.quantization.delta_q_v_ac), | ||
| 1220 | + }, | ||
| 1221 | + header.frame_width, | ||
| 1222 | + header.frame_height, | ||
| 1223 | + enable_filter_intra, | ||
| 1224 | + enable_edge_filter, | ||
| 1225 | + &header.cdef, | ||
| 1226 | + &header.loop_filter, | ||
| 1227 | + &header.loop_restoration, | ||
| 1228 | + initial_cdfs, | ||
| 1229 | + header.tx_mode == TxMode::Select, | ||
| 1230 | + header.reduced_tx_set, | ||
| 1231 | + header.allow_screen_content_tools, | ||
| 1232 | + header.allow_intrabc, | ||
| 1233 | + header.delta, fctx, | ||
| 1234 | + )?; | ||
| 1235 | + // A key frame codes no inter blocks -- its own saved motion | ||
| 1236 | + // field has no cells set, matching libaom's own "intra frame | ||
| 1237 | + // contributes nothing to a later projection" behaviour, but | ||
| 1238 | + // still carries `order_hint`/`ref_order_hints` for the distance | ||
| 1239 | + // arithmetic a later frame's projection needs. | ||
| 1240 | + let motion_field = crate::motion_field::MotionField::new( | ||
| 1241 | + header.mi_cols as usize, | ||
| 1242 | + header.mi_rows as usize, | ||
| 1243 | + header.order_hint, | ||
| 1244 | + ref_order_hints, | ||
| 1245 | + // `frame_type` for the DPB slot: a key (or intra-only) frame is | ||
| 1246 | + // never a projection source, and never spends a `ref_stamp`. | ||
| 1247 | + true, | ||
| 1248 | + ); | ||
| 1249 | + (picture, end_cdfs, motion_field) | ||
| 1250 | + } else { | ||
| 1251 | + let last_slot = header.ref_frame_idx[0] as usize; | ||
| 1252 | + let reference = snap.refs[last_slot].ok_or_else(|| { | ||
| 1253 | + Error::unsupported( | ||
| 1254 | + "AV1 decode_stream", | ||
| 1255 | + "an inter frame with no key frame before it", | ||
| 1256 | + ) | ||
| 1257 | + })?; | ||
| 1258 | + // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i` | ||
| 1259 | + // (spec 7.8/7.20). Any of them having no picture yet is not a | ||
| 1260 | + // stream error on its own: `decode_inter_block` only needs a | ||
| 1261 | + // given slot when a block actually selects that reference, and | ||
| 1262 | + // refuses by name there if the slot is still empty -- widened | ||
| 1263 | + // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every | ||
| 1264 | + // one of the 7 single-reference slots. | ||
| 1265 | + // lane-fimv r1: record the header state the fimv gate asserts on | ||
| 1266 | + // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause). | ||
| 1267 | + if header.force_integer_mv { | ||
| 1268 | + decode::note_force_integer_mv_frame(); | ||
| 1269 | + } | ||
| 1270 | + let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| { | ||
| 1271 | + if ref_frame == 0 { | ||
| 1272 | + None | ||
| 1273 | + } else { | ||
| 1274 | + snap.refs | ||
| 1275 | + .get(header.ref_frame_idx[ref_frame - 1] as usize) | ||
| 1276 | + .copied() | ||
| 1277 | + .flatten() | ||
| 1278 | + } | ||
| 1279 | + }); | ||
| 1280 | + // spec 7.9's own driver, `av1_setup_motion_field`: only run when | ||
| 1281 | + // this frame's header actually asks for temporal candidates -- | ||
| 1282 | + // `find_mv_stack_with_sign_bias` reproduces its old always-`None` | ||
| 1283 | + // behaviour bit for bit when this is `None` (see its own doc). | ||
| 1284 | + let tpl_field = &snap.tpl_field; | ||
| 1285 | + let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( | ||
| 1286 | + &tile_bufs, | ||
| 1287 | + &header.tile_info, | ||
| 1288 | + header.mi_cols, | ||
| 1289 | + header.mi_rows, | ||
| 1290 | + header.quantization.base_q_idx, | ||
| 1291 | + crate::quant::QuantDeltas { | ||
| 1292 | + y_dc: i32::from(header.quantization.delta_q_y_dc), | ||
| 1293 | + u_dc: i32::from(header.quantization.delta_q_u_dc), | ||
| 1294 | + u_ac: i32::from(header.quantization.delta_q_u_ac), | ||
| 1295 | + v_dc: i32::from(header.quantization.delta_q_v_dc), | ||
| 1296 | + v_ac: i32::from(header.quantization.delta_q_v_ac), | ||
| 1297 | + }, | ||
| 1298 | + header.frame_width, | ||
| 1299 | + header.frame_height, | ||
| 1300 | + reference, | ||
| 1301 | + other_refs, | ||
| 1302 | + &header.cdef, | ||
| 1303 | + &header.loop_filter, | ||
| 1304 | + &header.loop_restoration, | ||
| 1305 | + initial_cdfs, | ||
| 1306 | + header.allow_high_precision_mv, | ||
| 1307 | + header.force_integer_mv, | ||
| 1308 | + header.ref_frame_sign_bias, | ||
| 1309 | + header.global_motion, | ||
| 1310 | + interp_fixed, | ||
| 1311 | + enable_dual_filter, | ||
| 1312 | + order_hint_bits, | ||
| 1313 | + header.order_hint, | ||
| 1314 | + ref_order_hints, | ||
| 1315 | + tpl_field.as_ref(), | ||
| 1316 | + header.reference_select, | ||
| 1317 | + enable_masked_compound, | ||
| 1318 | + enable_jnt_comp, | ||
| 1319 | + enable_interintra_compound, | ||
| 1320 | + header.skip_mode_present, | ||
| 1321 | + header.skip_mode_frame, | ||
| 1322 | + header.reduced_tx_set, | ||
| 1323 | + header.tx_mode == TxMode::Select, | ||
| 1324 | + header.is_motion_mode_switchable, | ||
| 1325 | + header.allow_warped_motion, | ||
| 1326 | + header.allow_screen_content_tools, | ||
| 1327 | + header.delta, | ||
| 1328 | + enable_filter_intra, fctx, | ||
| 1329 | + )?; | ||
| 1330 | + (picture, end_cdfs, motion_field) | ||
| 1331 | + }; | ||
| 1332 | + // lane-lr r4: the Wiener/self-guided pixel filters are wired | ||
| 1333 | + // (`decode.rs::apply_loop_restoration`) -- no more refusal here, | ||
| 1334 | + // `uses_lr` frames now decode all the way to pixels. | ||
| 1335 | + // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's | ||
| 1336 | + // *initial* table into the slots it refreshes, not the adapted | ||
| 1337 | + // end-of-tile one. | ||
| 1338 | + let stored_cdfs = if header.disable_frame_end_update_cdf { | ||
| 1339 | + started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx))) | ||
| 1340 | + } else { | ||
| 1341 | + // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`): | ||
| 1342 | + // the adapted table is saved with every symbol counter zeroed, | ||
| 1343 | + // not with the counts the tile's own decode left behind. | ||
| 1344 | + let mut end_cdfs = end_cdfs; | ||
| 1345 | + end_cdfs.reset_counts(); | ||
| 1346 | + end_cdfs | ||
| 1347 | + }; | ||
| 1348 | + if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") { | ||
| 1349 | + use std::io::Write; | ||
| 1350 | + if let Ok(mut f) = std::fs::OpenOptions::new() | ||
| 1351 | + .create(true) | ||
| 1352 | + .append(true) | ||
| 1353 | + .open(&path) | ||
| 1354 | + { | ||
| 1355 | + let _ = writeln!(f, "=== frame idx={} ===", shown_idx); | ||
| 1356 | + let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64); | ||
| 1357 | + let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32); | ||
| 1358 | + let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16); | ||
| 1359 | + let _ = writeln!(f, "skip {:?}", stored_cdfs.skip); | ||
| 1360 | + let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv); | ||
| 1361 | + let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv); | ||
| 1362 | + let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv); | ||
| 1363 | + let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint); | ||
| 1364 | + } | ||
| 1365 | + } | ||
| 1366 | + // lane-comppin r3: decode-order (not display-order) dump of every | ||
| 1367 | + // frame's own post-deblock buffer -- the pre-existing pixel diff | ||
| 1368 | + // (`scratch_isolate_pinned_mismatch`) only ever compares *shown* | ||
| 1369 | + // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a | ||
| 1370 | + // later shown frame is otherwise invisible; diff this byte-for-byte | ||
| 1371 | + // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec | ||
| 1372 | + // build to isolate whether the defect is in a hidden frame's own | ||
| 1373 | + // reconstruction or downstream of it. | ||
| 1374 | + if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") { | ||
| 1375 | + use std::io::Write; | ||
| 1376 | + let idx = decode_idx; | ||
| 1377 | + if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { | ||
| 1378 | + // lane-hbd r4: debug dump narrows to u8 -- this diagnostic | ||
| 1379 | + // predates 10-bit support and is an 8-bit-oracle comparison | ||
| 1380 | + // only (aomdec's own dump is 8-bit here too). | ||
| 1381 | + let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() }; | ||
| 1382 | + let _ = f.write_all(&narrow(&picture.y)); | ||
| 1383 | + let _ = f.write_all(&narrow(&picture.u)); | ||
| 1384 | + let _ = f.write_all(&narrow(&picture.v)); | ||
| 1385 | + } | ||
| 1386 | + } | ||
| 1387 | + // lane-hidden r1: the frame exactly as it is about to be stored into | ||
| 1388 | + // the reference slots -- after deblock/CDEF/LR/superres, in DECODE | ||
| 1389 | + // order, hidden (`show_frame == 0`) alt-ref frames included, and | ||
| 1390 | + // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the | ||
| 1391 | + // u8-narrowing diagnostic dumps above. Matches the instrumented | ||
| 1392 | + // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte | ||
| 1393 | + // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a | ||
| 1394 | + // hidden frame's pixels comparable at all. | ||
| 1395 | + if let Some(prefix) = final_dump { | ||
| 1396 | + use std::io::Write; | ||
| 1397 | + if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) { | ||
| 1398 | + let mut buf = Vec::new(); | ||
| 1399 | + for plane in [&picture.y, &picture.u, &picture.v] { | ||
| 1400 | + if bit_depth == 8 { | ||
| 1401 | + buf.extend(plane.iter().map(|&s| s as u8)); | ||
| 1402 | + } else { | ||
| 1403 | + for &s in plane { | ||
| 1404 | + buf.extend_from_slice(&s.to_le_bytes()); | ||
| 1405 | + } | ||
| 1406 | + } | ||
| 1407 | + } | ||
| 1408 | + let _ = f.write_all(&buf); | ||
| 1409 | + } | ||
| 1410 | + } | ||
| 1411 | + Ok(FrameOutput { | ||
| 1412 | + picture, | ||
| 1413 | + stored_cdfs, | ||
| 1414 | + motion_field, | ||
| 1415 | + seg_map: decode::take_segment_ids(fctx), | ||
| 1416 | + }) | ||
| 1417 | +} | ||
| 1057 | 1418 | ||
| 1058 | /// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path | 1419 | /// 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 from | 1420 | /// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from |
| @@ -31775,6 +32136,71 @@ mod tests { | |||
| 31775 | ); | 32136 | ); |
| 31776 | } | 32137 | } |
| 31777 | 32138 | ||
| 32139 | + /// lane-thread2 (iv): frame-parallel decoding changes nothing a caller | ||
| 32140 | + /// can observe. Two real streams are decoded through | ||
| 32141 | + /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink | ||
| 32142 | + /// call is compared -- decode index, shown flag, and all three planes. | ||
| 32143 | + /// | ||
| 32144 | + /// `reelb_arf_witness.obu` is the one that proves the parallel path: 18 of | ||
| 32145 | + /// its 40 coded frames are leaves of the reference graph (shown, | ||
| 32146 | + /// non-key, `refresh_frame_flags == 0`), so 18 frames really are decoded | ||
| 32147 | + /// off the main thread, and it carries hidden alt-refs, which is exactly | ||
| 32148 | + /// the case where "output in coded order" is not the same as "output in | ||
| 32149 | + /// the order workers finish". `palette_screen_witness.obu` is the | ||
| 32150 | + /// complement: an 8-bit screen stream whose every coded frame refreshes a | ||
| 32151 | + /// slot, so at 4 threads it dispatches NOTHING and pins that the threaded | ||
| 32152 | + /// entry point is byte-identical on the inline path too. The dispatch | ||
| 32153 | + /// counter is asserted in both directions, so neither arm can pass | ||
| 32154 | + /// vacuously. | ||
| 32155 | + #[test] | ||
| 32156 | + fn a_real_stream_decodes_identically_with_one_and_four_threads() { | ||
| 32157 | + const NAME: &str = "a_real_stream_decodes_identically_with_one_and_four_threads"; | ||
| 32158 | + // (fixture, shown frames, leaf frames a 4-thread run must dispatch) | ||
| 32159 | + for (fixture, shown_frames, want_leaves) in [ | ||
| 32160 | + ("fixtures/reelb_arf_witness.obu", 37usize, 18usize), | ||
| 32161 | + ("fixtures/palette_screen_witness.obu", 15, 0), | ||
| 32162 | + ] { | ||
| 32163 | + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture); | ||
| 32164 | + let stream = std::fs::read(&path) | ||
| 32165 | + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); | ||
| 32166 | + let run = |threads: usize| -> Vec<(usize, bool, Picture)> { | ||
| 32167 | + let mut out = Vec::new(); | ||
| 32168 | + decode_stream_with_threads(&stream, threads, |p, idx, shown| { | ||
| 32169 | + out.push((idx, shown, p.clone())); | ||
| 32170 | + Ok(()) | ||
| 32171 | + }) | ||
| 32172 | + .unwrap_or_else(|e| panic!("{NAME}: {fixture} at {threads} threads refused: {e}")); | ||
| 32173 | + out | ||
| 32174 | + }; | ||
| 32175 | + let serial = run(1); | ||
| 32176 | + let before = leaf_frames_dispatched(); | ||
| 32177 | + let parallel = run(4); | ||
| 32178 | + let dispatched = leaf_frames_dispatched() - before; | ||
| 32179 | + assert_eq!( | ||
| 32180 | + dispatched, want_leaves, | ||
| 32181 | + "{NAME}: {fixture} dispatched {dispatched} leaf frames to workers, expected {want_leaves}" | ||
| 32182 | + ); | ||
| 32183 | + assert_eq!( | ||
| 32184 | + serial.iter().filter(|f| f.1).count(), | ||
| 32185 | + shown_frames, | ||
| 32186 | + "{NAME}: {fixture} shown frames" | ||
| 32187 | + ); | ||
| 32188 | + assert_eq!( | ||
| 32189 | + serial.len(), | ||
| 32190 | + parallel.len(), | ||
| 32191 | + "{NAME}: {fixture} sink call count differs" | ||
| 32192 | + ); | ||
| 32193 | + for (i, (a, b)) in serial.iter().zip(¶llel).enumerate() { | ||
| 32194 | + assert_eq!(a.0, b.0, "{NAME}: {fixture} sink {i} decode index"); | ||
| 32195 | + assert_eq!(a.1, b.1, "{NAME}: {fixture} sink {i} shown flag"); | ||
| 32196 | + assert_eq!(a.2.y, b.2.y, "{NAME}: {fixture} sink {i} luma"); | ||
| 32197 | + assert_eq!(a.2.u, b.2.u, "{NAME}: {fixture} sink {i} U"); | ||
| 32198 | + assert_eq!(a.2.v, b.2.v, "{NAME}: {fixture} sink {i} V"); | ||
| 32199 | + } | ||
| 32200 | + eprintln!("{NAME}: {fixture} {} sink calls identical, {dispatched} decoded on workers", serial.len()); | ||
| 32201 | + } | ||
| 32202 | + } | ||
| 32203 | + | ||
| 31778 | /// lane-frame36 r2: the hidden-ARF witness. `crates/ec-av1/fixtures/ | 32204 | /// lane-frame36 r2: the hidden-ARF witness. `crates/ec-av1/fixtures/ |
| 31779 | /// reelb_arf_witness.obu`, 32126 bytes, sha256 | 32205 | /// reelb_arf_witness.obu`, 32126 bytes, sha256 |
| 31780 | /// `7f3b060da5aa9c537633e760c4af71316237db7692f6ae0d459bd2c2dd867d37`: | 32206 | /// `7f3b060da5aa9c537633e760c4af71316237db7692f6ae0d459bd2c2dd867d37`: |