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 +552 -120
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+546 -120
| @@ -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,6 +601,329 @@ 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`. |
| 604 | + let tile_bufs: Vec<&[u8]> = tiles | ||
| 605 | + .iter() | ||
| 606 | + .map(|t| { | ||
| 607 | + data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size) | ||
| 608 | + .ok_or(Error::NeedMore) | ||
| 609 | + }) | ||
| 610 | + .collect::<Result<_>>()?; | ||
| 611 | + let seq = SeqFlags::read(&parser); | ||
| 612 | + // A LEAF of the reference graph: shown, not a key frame, and | ||
| 613 | + // refreshing no slot -- so nothing it produces except its own picture | ||
| 614 | + // is ever read again (spec 7.20's bank update is keyed entirely on | ||
| 615 | + // `refresh_frame_flags`), and it can be decoded anywhere. | ||
| 616 | + if threads > 1 | ||
| 617 | + && header.refresh_frame_flags == 0 | ||
| 618 | + && header.show_frame | ||
| 619 | + && !header.show_existing_frame | ||
| 620 | + && header.frame_type != FrameType::Key | ||
| 621 | + { | ||
| 622 | + while in_flight >= in_flight_cap { | ||
| 623 | + collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?; | ||
| 624 | + } | ||
| 625 | + let mut arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = | ||
| 626 | + std::array::from_fn(|_| None); | ||
| 627 | + for i in 0..7 { | ||
| 628 | + let slot = header.ref_frame_idx[i] as usize; | ||
| 629 | + if arcs[slot].is_none() | ||
| 630 | + && let Some(picture) = ref_slots[slot].as_ref() | ||
| 631 | + { | ||
| 632 | + arcs[slot] = Some( | ||
| 633 | + ref_arcs[slot] | ||
| 634 | + .get_or_insert_with(|| std::sync::Arc::new(picture.clone())) | ||
| 635 | + .clone(), | ||
| 636 | + ); | ||
| 637 | + } | ||
| 638 | + } | ||
| 639 | + let snap = RefSnapshot::take( | ||
| 640 | + &header, | ||
| 641 | + seq, | ||
| 642 | + std::array::from_fn(|_| None), | ||
| 643 | + &cdf_slots, | ||
| 644 | + &seg_map_slots, | ||
| 645 | + &motion_field_slots, | ||
| 646 | + &order_hint_slots, | ||
| 647 | + ); | ||
| 648 | + let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); | ||
| 649 | + emit_seq += 1; | ||
| 650 | + pictures_decoded += 1; | ||
| 651 | + pictures_shown += 1; | ||
| 652 | + let tx = tx.clone(); | ||
| 653 | + let dump = final_dump.clone(); | ||
| 654 | + scope.spawn(move || { | ||
| 655 | + let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | ||
| 656 | + // Fresh per-thread state: every field this path reads is | ||
| 657 | + // written from this frame's own header before it is read. | ||
| 658 | + let fctx = crate::decode::FrameCtx::new(); | ||
| 659 | + let snap = RefSnapshot { | ||
| 660 | + refs: std::array::from_fn(|i| arcs[i].as_deref()), | ||
| 661 | + ..snap | ||
| 662 | + }; | ||
| 663 | + let out = decode_frame( | ||
| 664 | + &fctx, | ||
| 665 | + &header, | ||
| 666 | + &tile_bufs, | ||
| 667 | + seq, | ||
| 668 | + snap, | ||
| 669 | + decode_idx, | ||
| 670 | + shown_idx, | ||
| 671 | + dump.as_deref(), | ||
| 672 | + )?; | ||
| 673 | + let picture = if header.film_grain.apply_grain && !no_grain() { | ||
| 674 | + crate::film_grain::apply_grain( | ||
| 675 | + &out.picture, | ||
| 676 | + &header.film_grain, | ||
| 677 | + seq.mc_identity, | ||
| 678 | + u32::from(seq.bit_depth), | ||
| 679 | + &fctx, | ||
| 680 | + ) | ||
| 681 | + } else { | ||
| 682 | + out.picture | ||
| 683 | + }; | ||
| 684 | + Ok((picture, decode_idx, true)) | ||
| 685 | + })) | ||
| 686 | + .unwrap_or_else(|_| { | ||
| 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)?; | ||
| 701 | + } | ||
| 702 | + continue; | ||
| 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 | + )?; | ||
| 729 | + pictures_decoded += 1; | ||
| 730 | + for i in 0..NUM_REF_FRAMES { | ||
| 731 | + if header.refresh_frame_flags & (1 << i) != 0 { | ||
| 732 | + cdf_slots[i] = Some(stored_cdfs.clone()); | ||
| 733 | + // Spec 7.18.3.1: synthesized grain is never stored for later | ||
| 734 | + // prediction -- the reference bank always keeps the clean, | ||
| 735 | + // pre-grain decode, even though the frame pushed onto the | ||
| 736 | + // caller's output below carries the grained picture. | ||
| 737 | + ref_slots[i] = Some(picture.clone()); | ||
| 738 | + ref_arcs[i] = None; | ||
| 739 | + motion_field_slots[i] = Some(motion_field.clone()); | ||
| 740 | + seg_map_slots[i] = Some(decoded_seg_map.clone()); | ||
| 741 | + order_hint_slots[i] = header.order_hint; | ||
| 742 | + } | ||
| 743 | + } | ||
| 744 | + // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a | ||
| 745 | + // KEY frame coded with `show_frame == 0`, output later by a | ||
| 746 | + // `show_existing_frame` header -- counted only once its tiles have | ||
| 747 | + // decoded, so the gate's assert covers decoded-and-compared frames. | ||
| 748 | + if header.frame_type == FrameType::Key && !header.show_frame { | ||
| 749 | + decode::note_fwd_kf(); | ||
| 750 | + } | ||
| 751 | + if header.show_frame { | ||
| 752 | + let output = if header.film_grain.apply_grain && !no_grain() { | ||
| 753 | + let mc_identity = seq.mc_identity; | ||
| 754 | + crate::film_grain::apply_grain( | ||
| 755 | + &picture, | ||
| 756 | + &header.film_grain, | ||
| 757 | + mc_identity, | ||
| 758 | + bit_depth as u32, fctx, | ||
| 759 | + ) | ||
| 760 | + } else { | ||
| 761 | + picture | ||
| 762 | + }; | ||
| 763 | + reorder.push(emit_seq, output, pictures_decoded - 1, true); | ||
| 764 | + emit_seq += 1; | ||
| 765 | + reorder.drain(&mut sink)?; | ||
| 766 | + pictures_shown += 1; | ||
| 767 | + } else { | ||
| 768 | + // Hidden (alt-ref/forward-key) frames never reach | ||
| 769 | + // `decode_stream`'s output, but a decode-order consumer -- the | ||
| 770 | + // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs | ||
| 771 | + // them, so they are reported too, with `shown == false`. | ||
| 772 | + reorder.push(emit_seq, picture, pictures_decoded - 1, false); | ||
| 773 | + emit_seq += 1; | ||
| 774 | + reorder.drain(&mut sink)?; | ||
| 775 | + } | ||
| 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"); | ||
| 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>, | ||
| 901 | +} | ||
| 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> { | ||
| 476 | if header.segmentation.enabled { | 927 | if header.segmentation.enabled { |
| 477 | for segment in 0..MAX_SEGMENTS { | 928 | for segment in 0..MAX_SEGMENTS { |
| 478 | for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { | 929 | for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { |
| @@ -487,16 +938,11 @@ pub fn decode_stream_with( | |||
| 487 | } | 938 | } |
| 488 | // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the | 939 | // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the |
| 489 | // primary reference frame's slot, and is all-zero without one. | 940 | // 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( | 941 | decode::set_segmentation( |
| 496 | header.segmentation, | 942 | header.segmentation, |
| 497 | header.mi_rows as usize, | 943 | header.mi_rows as usize, |
| 498 | header.mi_cols as usize, | 944 | header.mi_cols as usize, |
| 499 | - prev_seg_map.as_deref(), fctx, | 945 | + snap.prev_seg_map.as_deref(), fctx, |
| 500 | ); | 946 | ); |
| 501 | // lane-superres stage 2/3: `use_superres` adds/removes no per-block | 947 | // 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 | 948 | // symbol (spec 7.16's upscaling is a pixel-domain post-process |
| @@ -649,22 +1095,9 @@ pub fn decode_stream_with( | |||
| 649 | // `Tile::offset` is relative to the buffer `parse_obu` was handed | 1095 | // `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 | 1096 | // (`&data[pos..]` at the time this OBU was parsed), so it is relative |
| 651 | // to `obu_offset`, not to `data` as a whole. | 1097 | // to `obu_offset`, not to `data` as a whole. |
| 652 | - let tile_bufs: Vec<&[u8]> = tiles | 1098 | + let enable_filter_intra = seq.enable_filter_intra; |
| 653 | - .iter() | 1099 | + let enable_dual_filter = seq.enable_dual_filter; |
| 654 | - .map(|t| { | 1100 | + let enable_edge_filter = seq.enable_edge_filter; |
| 655 | - data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size) | ||
| 656 | - .ok_or(Error::NeedMore) | ||
| 657 | - }) | ||
| 658 | - .collect::<Result<_>>()?; | ||
| 659 | - let enable_filter_intra = parser | ||
| 660 | - .sequence_header() | ||
| 661 | - .is_some_and(|seq| seq.enable_filter_intra); | ||
| 662 | - let enable_dual_filter = parser | ||
| 663 | - .sequence_header() | ||
| 664 | - .is_some_and(|seq| seq.enable_dual_filter); | ||
| 665 | - let enable_edge_filter = parser | ||
| 666 | - .sequence_header() | ||
| 667 | - .is_some_and(|seq| seq.enable_intra_edge_filter); | ||
| 668 | // Inter frames' intra blocks read this through a thread-local that only | 1101 | // Inter frames' intra blocks read this through a thread-local that only |
| 669 | // the key-frame tile path used to set; without this call a stream whose | 1102 | // the key-frame tile path used to set; without this call a stream whose |
| 670 | // inter frames are decoded on a thread that previously decoded a | 1103 | // inter frames are decoded on a thread that previously decoded a |
| @@ -677,9 +1110,7 @@ pub fn decode_stream_with( | |||
| 677 | // most 64x64 decodes identically either way (its 128 root reads no | 1110 | // most 64x64 decodes identically either way (its 128 root reads no |
| 678 | // symbol -- neither half is in frame, so SPLIT is inferred), so the | 1111 | // symbol -- neither half is in frame, so SPLIT is inferred), so the |
| 679 | // flag is only armed for frames bigger than one 64x64 superblock. | 1112 | // flag is only armed for frames bigger than one 64x64 superblock. |
| 680 | - let use_sb128 = parser | 1113 | + let use_sb128 = seq.use_sb128; |
| 681 | - .sequence_header() | ||
| 682 | - .is_some_and(|seq| seq.use_128x128_superblock); | ||
| 683 | let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16); | 1114 | let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16); |
| 684 | crate::decode::set_sb128(sb128_active, fctx); | 1115 | crate::decode::set_sb128(sb128_active, fctx); |
| 685 | // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`, | 1116 | // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`, |
| @@ -687,9 +1118,7 @@ pub fn decode_stream_with( | |||
| 687 | // not once per process, for the same cross-sequence-on-one-thread | 1118 | // 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 | 1119 | // reason as `set_enable_edge_filter` above. Defaults to 8 when no |
| 689 | // sequence header has been seen yet, matching every existing fixture. | 1120 | // sequence header has been seen yet, matching every existing fixture. |
| 690 | - let bit_depth = parser | 1121 | + let bit_depth = seq.bit_depth; |
| 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 | 1122 | // 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 | 1123 | // rounding shift below is written for 8/10-bit only -- `warp.rs`'s |
| 695 | // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses | 1124 | // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses |
| @@ -713,17 +1142,11 @@ pub fn decode_stream_with( | |||
| 713 | u32::from(header.superres_denom), fctx, | 1142 | u32::from(header.superres_denom), fctx, |
| 714 | ); | 1143 | ); |
| 715 | // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. | 1144 | // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. |
| 716 | - let enable_masked_compound = parser | 1145 | + let enable_masked_compound = seq.enable_masked_compound; |
| 717 | - .sequence_header() | 1146 | + let enable_jnt_comp = seq.enable_jnt_comp; |
| 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 | 1147 | // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's |
| 723 | // read site doc. | 1148 | // read site doc. |
| 724 | - let enable_interintra_compound = parser | 1149 | + let enable_interintra_compound = seq.enable_interintra_compound; |
| 725 | - .sequence_header() | ||
| 726 | - .is_some_and(|seq| seq.enable_interintra_compound); | ||
| 727 | let interp_fixed = match header.interpolation_filter { | 1150 | let interp_fixed = match header.interpolation_filter { |
| 728 | ec_av1_syntax::InterpolationFilter::Switchable => None, | 1151 | ec_av1_syntax::InterpolationFilter::Switchable => None, |
| 729 | fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), | 1152 | fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), |
| @@ -735,8 +1158,7 @@ pub fn decode_stream_with( | |||
| 735 | let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE { | 1158 | let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE { |
| 736 | None | 1159 | None |
| 737 | } else { | 1160 | } else { |
| 738 | - let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize; | 1161 | + Some(snap.primary_cdfs.clone().ok_or_else(|| { |
| 739 | - Some(cdf_slots[slot].clone().ok_or_else(|| { | ||
| 740 | Error::unsupported( | 1162 | Error::unsupported( |
| 741 | "AV1 decode_stream", | 1163 | "AV1 decode_stream", |
| 742 | "a frame naming primary_ref_frame at a reference slot with no saved CDF state", | 1164 | "a frame naming primary_ref_frame at a reference slot with no saved CDF state", |
| @@ -745,13 +1167,13 @@ pub fn decode_stream_with( | |||
| 745 | }; | 1167 | }; |
| 746 | let started_from = initial_cdfs.clone(); | 1168 | let started_from = initial_cdfs.clone(); |
| 747 | // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame. | 1169 | // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame. |
| 748 | - decode::set_coeff_trace_frame(pictures_decoded); | 1170 | + decode::set_coeff_trace_frame(decode_idx); |
| 749 | // lane-t900 r9: one line per DECODE-order frame naming the header | 1171 | // 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, | 1172 | // fields a desync cliff is usually keyed on (frame type, base q, |
| 751 | // primary_ref, the 7 ref slots, refresh mask, order hints). | 1173 | // primary_ref, the 7 ref slots, refresh mask, order hints). |
| 752 | if std::env::var_os("EC_PROBE_HDR").is_some() { | 1174 | if std::env::var_os("EC_PROBE_HDR").is_some() { |
| 753 | eprintln!( | 1175 | 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={:?}", | 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={:?}", |
| 755 | header.frame_type, | 1177 | header.frame_type, |
| 756 | header.show_frame, | 1178 | header.show_frame, |
| 757 | header.show_existing_frame, | 1179 | header.show_existing_frame, |
| @@ -774,16 +1196,13 @@ pub fn decode_stream_with( | |||
| 774 | ); | 1196 | ); |
| 775 | } | 1197 | } |
| 776 | 1198 | ||
| 777 | - let order_hint_bits = parser | 1199 | + let order_hint_bits = seq.order_hint_bits; |
| 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 | 1200 | // 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 | 1201 | // of the picture sitting in each of its 7 single references' DPB |
| 782 | // slots, for this frame's *own* saved [`crate::motion_field::MotionField`] | 1202 | // slots, for this frame's *own* saved [`crate::motion_field::MotionField`] |
| 783 | // (a later frame projects from it) whether or not this frame itself | 1203 | // (a later frame projects from it) whether or not this frame itself |
| 784 | // reads temporal candidates. | 1204 | // reads temporal candidates. |
| 785 | - let ref_order_hints: [u32; 7] = | 1205 | + let ref_order_hints = snap.ref_order_hints; |
| 786 | - std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]); | ||
| 787 | 1206 | ||
| 788 | let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { | 1207 | let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { |
| 789 | let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( | 1208 | let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( |
| @@ -830,7 +1249,7 @@ pub fn decode_stream_with( | |||
| 830 | (picture, end_cdfs, motion_field) | 1249 | (picture, end_cdfs, motion_field) |
| 831 | } else { | 1250 | } else { |
| 832 | let last_slot = header.ref_frame_idx[0] as usize; | 1251 | let last_slot = header.ref_frame_idx[0] as usize; |
| 833 | - let reference = ref_slots[last_slot].as_ref().ok_or_else(|| { | 1252 | + let reference = snap.refs[last_slot].ok_or_else(|| { |
| 834 | Error::unsupported( | 1253 | Error::unsupported( |
| 835 | "AV1 decode_stream", | 1254 | "AV1 decode_stream", |
| 836 | "an inter frame with no key frame before it", | 1255 | "an inter frame with no key frame before it", |
| @@ -852,33 +1271,17 @@ pub fn decode_stream_with( | |||
| 852 | if ref_frame == 0 { | 1271 | if ref_frame == 0 { |
| 853 | None | 1272 | None |
| 854 | } else { | 1273 | } else { |
| 855 | - ref_slots | 1274 | + snap.refs |
| 856 | .get(header.ref_frame_idx[ref_frame - 1] as usize) | 1275 | .get(header.ref_frame_idx[ref_frame - 1] as usize) |
| 857 | - .and_then(Option::as_ref) | 1276 | + .copied() |
| 1277 | + .flatten() | ||
| 858 | } | 1278 | } |
| 859 | }); | 1279 | }); |
| 860 | // spec 7.9's own driver, `av1_setup_motion_field`: only run when | 1280 | // spec 7.9's own driver, `av1_setup_motion_field`: only run when |
| 861 | // this frame's header actually asks for temporal candidates -- | 1281 | // this frame's header actually asks for temporal candidates -- |
| 862 | // `find_mv_stack_with_sign_bias` reproduces its old always-`None` | 1282 | // `find_mv_stack_with_sign_bias` reproduces its old always-`None` |
| 863 | // behaviour bit for bit when this is `None` (see its own doc). | 1283 | // behaviour bit for bit when this is `None` (see its own doc). |
| 864 | - let tpl_field = header.use_ref_frame_mvs.then(|| { | 1284 | + let tpl_field = &snap.tpl_field; |
| 865 | - crate::motion_field::setup_motion_field( | ||
| 866 | - &motion_field_slots, | ||
| 867 | - header.ref_frame_idx, | ||
| 868 | - header.order_hint, | ||
| 869 | - order_hint_bits, | ||
| 870 | - header.mi_rows as usize, | ||
| 871 | - header.mi_cols as usize, | ||
| 872 | - ) | ||
| 873 | - }); | ||
| 874 | - if std::env::var_os("EC_TPL").is_some() { | ||
| 875 | - eprintln!( | ||
| 876 | - "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}", | ||
| 877 | - header.order_hint, | ||
| 878 | - header.use_ref_frame_mvs, | ||
| 879 | - tpl_field.as_ref().map_or(0, crate::motion_field::TplField::filled_cells) | ||
| 880 | - ); | ||
| 881 | - } | ||
| 882 | let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( | 1285 | let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( |
| 883 | &tile_bufs, | 1286 | &tile_bufs, |
| 884 | &header.tile_info, | 1287 | &header.tile_info, |
| @@ -949,7 +1352,7 @@ pub fn decode_stream_with( | |||
| 949 | .append(true) | 1352 | .append(true) |
| 950 | .open(&path) | 1353 | .open(&path) |
| 951 | { | 1354 | { |
| 952 | - let _ = writeln!(f, "=== frame idx={} ===", pictures_shown); | 1355 | + let _ = writeln!(f, "=== frame idx={} ===", shown_idx); |
| 953 | let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64); | 1356 | let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64); |
| 954 | let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32); | 1357 | let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32); |
| 955 | let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16); | 1358 | let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16); |
| @@ -970,7 +1373,7 @@ pub fn decode_stream_with( | |||
| 970 | // reconstruction or downstream of it. | 1373 | // reconstruction or downstream of it. |
| 971 | if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") { | 1374 | if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") { |
| 972 | use std::io::Write; | 1375 | use std::io::Write; |
| 973 | - let idx = pictures_decoded; | 1376 | + let idx = decode_idx; |
| 974 | if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { | 1377 | if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { |
| 975 | // lane-hbd r4: debug dump narrows to u8 -- this diagnostic | 1378 | // lane-hbd r4: debug dump narrows to u8 -- this diagnostic |
| 976 | // predates 10-bit support and is an 8-bit-oracle comparison | 1379 | // predates 10-bit support and is an 8-bit-oracle comparison |
| @@ -989,9 +1392,9 @@ pub fn decode_stream_with( | |||
| 989 | // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte | 1392 | // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte |
| 990 | // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a | 1393 | // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a |
| 991 | // hidden frame's pixels comparable at all. | 1394 | // hidden frame's pixels comparable at all. |
| 992 | - if let Some(prefix) = &final_dump { | 1395 | + if let Some(prefix) = final_dump { |
| 993 | use std::io::Write; | 1396 | use std::io::Write; |
| 994 | - if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) { | 1397 | + if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) { |
| 995 | let mut buf = Vec::new(); | 1398 | let mut buf = Vec::new(); |
| 996 | for plane in [&picture.y, &picture.u, &picture.v] { | 1399 | for plane in [&picture.y, &picture.u, &picture.v] { |
| 997 | if bit_depth == 8 { | 1400 | if bit_depth == 8 { |
| @@ -1005,56 +1408,14 @@ pub fn decode_stream_with( | |||
| 1005 | let _ = f.write_all(&buf); | 1408 | let _ = f.write_all(&buf); |
| 1006 | } | 1409 | } |
| 1007 | } | 1410 | } |
| 1008 | - pictures_decoded += 1; | 1411 | + Ok(FrameOutput { |
| 1009 | - let decoded_seg_map = decode::take_segment_ids(fctx); | 1412 | + picture, |
| 1010 | - for i in 0..NUM_REF_FRAMES { | 1413 | + stored_cdfs, |
| 1011 | - if header.refresh_frame_flags & (1 << i) != 0 { | 1414 | + motion_field, |
| 1012 | - cdf_slots[i] = Some(stored_cdfs.clone()); | 1415 | + seg_map: decode::take_segment_ids(fctx), |
| 1013 | - // Spec 7.18.3.1: synthesized grain is never stored for later | 1416 | + }) |
| 1014 | - // prediction -- the reference bank always keeps the clean, | ||
| 1015 | - // pre-grain decode, even though the frame pushed onto the | ||
| 1016 | - // caller's output below carries the grained picture. | ||
| 1017 | - ref_slots[i] = Some(picture.clone()); | ||
| 1018 | - motion_field_slots[i] = Some(motion_field.clone()); | ||
| 1019 | - seg_map_slots[i] = Some(decoded_seg_map.clone()); | ||
| 1020 | - order_hint_slots[i] = header.order_hint; | ||
| 1021 | - } | ||
| 1022 | - } | ||
| 1023 | - // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a | ||
| 1024 | - // KEY frame coded with `show_frame == 0`, output later by a | ||
| 1025 | - // `show_existing_frame` header -- counted only once its tiles have | ||
| 1026 | - // decoded, so the gate's assert covers decoded-and-compared frames. | ||
| 1027 | - if header.frame_type == FrameType::Key && !header.show_frame { | ||
| 1028 | - decode::note_fwd_kf(); | ||
| 1029 | - } | ||
| 1030 | - if header.show_frame { | ||
| 1031 | - let output = if header.film_grain.apply_grain && !no_grain() { | ||
| 1032 | - let mc_identity = parser | ||
| 1033 | - .sequence_header() | ||
| 1034 | - .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); | ||
| 1035 | - crate::film_grain::apply_grain( | ||
| 1036 | - &picture, | ||
| 1037 | - &header.film_grain, | ||
| 1038 | - mc_identity, | ||
| 1039 | - bit_depth as u32, fctx, | ||
| 1040 | - ) | ||
| 1041 | - } else { | ||
| 1042 | - picture | ||
| 1043 | - }; | ||
| 1044 | - sink(&output, pictures_decoded - 1, true)?; | ||
| 1045 | - pictures_shown += 1; | ||
| 1046 | - } else { | ||
| 1047 | - // Hidden (alt-ref/forward-key) frames never reach | ||
| 1048 | - // `decode_stream`'s output, but a decode-order consumer -- the | ||
| 1049 | - // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs | ||
| 1050 | - // them, so they are reported too, with `shown == false`. | ||
| 1051 | - sink(&picture, pictures_decoded - 1, false)?; | ||
| 1052 | - } | ||
| 1053 | - } | ||
| 1054 | - Ok(()) | ||
| 1055 | } | 1417 | } |
| 1056 | 1418 | ||
| 1057 | - | ||
| 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 |
| 1060 | /// outside the crate. | 1421 | /// outside the crate. |
| @@ -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`: |