Dependency-aware frame scheduling -- every non-key frame decodes on a worker
Browse files at this commitfcddd9c4acc29642946453af5c3541355f763ccfParent: f5fdee3- feat
- dependency-aware frame scheduling -- every non-key frame decodes on a worker
3 changed files +304 -115
- crates/ec-av1/examples/decode_probe.rs +2 -2
- crates/ec-av1/src/motion_field.rs +10 -3
- crates/ec-av1/src/stream.rs +292 -110
crates/ec-av1/examples/decode_probe.rsmodified+2 -2
| @@ -154,8 +154,8 @@ fn main() { | |||
| 154 | // lane-thread2: proof the frame-parallel path actually fired (0 at | 154 | // lane-thread2: proof the frame-parallel path actually fired (0 at |
| 155 | // the default EC_AV1_THREADS=1). | 155 | // the default EC_AV1_THREADS=1). |
| 156 | println!( | 156 | println!( |
| 157 | - "leaf_frames_dispatched: {}", | 157 | + "frames_dispatched: {}", |
| 158 | - ec_av1::stream::leaf_frames_dispatched() | 158 | + ec_av1::stream::frames_dispatched() |
| 159 | ); | 159 | ); |
| 160 | }; | 160 | }; |
| 161 | // 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 |
crates/ec-av1/src/motion_field.rsmodified+10 -3
| @@ -336,8 +336,8 @@ pub fn refstamp_intra_frames() -> (usize, usize) { | |||
| 336 | /// constructed, so also `None` — motion field, contributes nothing); | 336 | /// constructed, so also `None` — motion field, contributes nothing); |
| 337 | /// `ref_frame_idx` is the current frame header's own `ref_frame_idx` | 337 | /// `ref_frame_idx` is the current frame header's own `ref_frame_idx` |
| 338 | /// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`). | 338 | /// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`). |
| 339 | -pub fn setup_motion_field( | 339 | +pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>( |
| 340 | - slots: &[Option<MotionField>; 8], | 340 | + slots: &[Option<M>; 8], |
| 341 | ref_frame_idx: [u8; 7], | 341 | ref_frame_idx: [u8; 7], |
| 342 | cur_order_hint: u32, | 342 | cur_order_hint: u32, |
| 343 | order_hint_bits: u32, | 343 | order_hint_bits: u32, |
| @@ -354,7 +354,14 @@ pub fn setup_motion_field( | |||
| 354 | } | 354 | } |
| 355 | 355 | ||
| 356 | let slot_of = | 356 | let slot_of = |
| 357 | - |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref(); | 357 | + // lane-thread3: `M` is an owned `MotionField` on the single-threaded |
| 358 | + // path and a `&MotionField` borrowed out of a resolved reference-slot | ||
| 359 | + // promise on a worker; the projection reads the same field either way. | ||
| 360 | + |ref_frame: i8| { | ||
| 361 | + slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize] | ||
| 362 | + .as_ref() | ||
| 363 | + .map(M::borrow) | ||
| 364 | + }; | ||
| 358 | let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint); | 365 | let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint); |
| 359 | 366 | ||
| 360 | let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 | 367 | let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 |
crates/ec-av1/src/stream.rsmodified+292 -110
| @@ -315,17 +315,111 @@ impl Reorder { | |||
| 315 | } | 315 | } |
| 316 | } | 316 | } |
| 317 | 317 | ||
| 318 | -/// lane-thread2: how many leaf frames this PROCESS has dispatched to a worker | 318 | +/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a |
| 319 | -/// thread (see [`decode_stream_with_threads`]). Process-global and atomic on | 319 | +/// worker thread (see [`decode_stream_with_threads`]). Process-global and |
| 320 | -/// purpose: it is the only counter here a caller can read after a threaded | 320 | +/// atomic on purpose: it is the only counter here a caller can read after a |
| 321 | -/// decode, and it is what keeps a "decodes identically with 4 threads" gate | 321 | +/// threaded decode, and it is what keeps a "decodes identically with 4 |
| 322 | -/// from silently proving nothing because every frame ran inline. | 322 | +/// threads" gate from silently proving nothing because every frame ran |
| 323 | -static LEAF_FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = | 323 | +/// inline. (lane-thread2 counted only LEAF frames, the only ones it could |
| 324 | +/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame` | ||
| 325 | +/// frame, hence the rename.) | ||
| 326 | +static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = | ||
| 324 | std::sync::atomic::AtomicUsize::new(0); | 327 | std::sync::atomic::AtomicUsize::new(0); |
| 325 | 328 | ||
| 326 | -/// Reads [`LEAF_FRAMES_DISPATCHED`]. | 329 | +/// Reads [`FRAMES_DISPATCHED`]. |
| 327 | -pub fn leaf_frames_dispatched() -> usize { | 330 | +pub fn frames_dispatched() -> usize { |
| 328 | - LEAF_FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed) | 331 | + FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed) |
| 332 | +} | ||
| 333 | + | ||
| 334 | +/// lane-thread3: what one decoded frame stores into every reference slot its | ||
| 335 | +/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated | ||
| 336 | +/// object -- so a slot costs an `Arc` clone instead of a picture copy. | ||
| 337 | +struct SlotValue { | ||
| 338 | + picture: std::sync::Arc<Picture>, | ||
| 339 | + cdfs: Cdfs, | ||
| 340 | + motion_field: crate::motion_field::MotionField, | ||
| 341 | + seg_map: Vec<u8>, | ||
| 342 | + order_hint: u32, | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1` | ||
| 346 | +/// the 8-slot bank holds these instead of values: a slot refreshed by a frame | ||
| 347 | +/// that is still decoding on a worker holds the promise from the moment the | ||
| 348 | +/// parsing thread DISPATCHES that frame, so the next frame can be dispatched | ||
| 349 | +/// straight away and waits, on its own worker, for exactly the slots it | ||
| 350 | +/// reads. This is what makes a pyramid stream (aomenc's default, where nearly | ||
| 351 | +/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched | ||
| 352 | +/// almost nothing) decode in parallel. | ||
| 353 | +/// | ||
| 354 | +/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing | ||
| 355 | +/// thread, in decode order, when its producer is dispatched; a consumer | ||
| 356 | +/// captures the promises of the slots it reads at ITS dispatch, which is | ||
| 357 | +/// strictly later in decode order. Every wait therefore points from a later | ||
| 358 | +/// coded frame to an earlier one -- the wait graph is the reference DAG, and | ||
| 359 | +/// is acyclic. The parsing thread waits only for a `show_existing_frame` | ||
| 360 | +/// output (again an earlier frame) and at the in-flight bound, where it waits | ||
| 361 | +/// for ANY worker to answer: the earliest in-flight frame has no earlier | ||
| 362 | +/// in-flight producer, so it is always runnable and the bound always clears. | ||
| 363 | +/// Each dispatched frame gets its own thread, so a blocked waiter never holds | ||
| 364 | +/// a resource its producer needs. A producer that errors or panics marks its | ||
| 365 | +/// promise `Failed`, so no consumer can wait for a value that never comes. | ||
| 366 | +struct SlotPromise { | ||
| 367 | + state: std::sync::Mutex<PromiseState>, | ||
| 368 | + ready: std::sync::Condvar, | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +enum PromiseState { | ||
| 372 | + Pending, | ||
| 373 | + Ready(std::sync::Arc<SlotValue>), | ||
| 374 | + Failed, | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +impl SlotPromise { | ||
| 378 | + fn pending() -> std::sync::Arc<Self> { | ||
| 379 | + std::sync::Arc::new(Self { | ||
| 380 | + state: std::sync::Mutex::new(PromiseState::Pending), | ||
| 381 | + ready: std::sync::Condvar::new(), | ||
| 382 | + }) | ||
| 383 | + } | ||
| 384 | + | ||
| 385 | + /// A slot filled by a frame the parsing thread decoded itself. | ||
| 386 | + fn ready(value: std::sync::Arc<SlotValue>) -> std::sync::Arc<Self> { | ||
| 387 | + std::sync::Arc::new(Self { | ||
| 388 | + state: std::sync::Mutex::new(PromiseState::Ready(value)), | ||
| 389 | + ready: std::sync::Condvar::new(), | ||
| 390 | + }) | ||
| 391 | + } | ||
| 392 | + | ||
| 393 | + fn fulfil(&self, value: std::sync::Arc<SlotValue>) { | ||
| 394 | + *self.state.lock().expect("slot promise") = PromiseState::Ready(value); | ||
| 395 | + self.ready.notify_all(); | ||
| 396 | + } | ||
| 397 | + | ||
| 398 | + fn fail(&self) { | ||
| 399 | + let mut state = self.state.lock().expect("slot promise"); | ||
| 400 | + if matches!(*state, PromiseState::Pending) { | ||
| 401 | + *state = PromiseState::Failed; | ||
| 402 | + } | ||
| 403 | + self.ready.notify_all(); | ||
| 404 | + } | ||
| 405 | + | ||
| 406 | + /// Blocks until the producing frame has published this slot. | ||
| 407 | + fn wait(&self) -> Result<std::sync::Arc<SlotValue>> { | ||
| 408 | + let mut state = self.state.lock().expect("slot promise"); | ||
| 409 | + loop { | ||
| 410 | + match &*state { | ||
| 411 | + PromiseState::Ready(value) => return Ok(value.clone()), | ||
| 412 | + PromiseState::Failed => { | ||
| 413 | + return Err(Error::corrupt( | ||
| 414 | + "AV1 decode_stream: a reference frame this frame depends on failed to decode", | ||
| 415 | + )); | ||
| 416 | + } | ||
| 417 | + PromiseState::Pending => { | ||
| 418 | + state = self.ready.wait(state).expect("slot promise"); | ||
| 419 | + } | ||
| 420 | + } | ||
| 421 | + } | ||
| 422 | + } | ||
| 329 | } | 423 | } |
| 330 | 424 | ||
| 331 | /// One finished leaf frame from a worker: its output position, and either the | 425 | /// One finished leaf frame from a worker: its output position, and either the |
| @@ -420,14 +514,15 @@ pub fn decode_stream_with_threads( | |||
| 420 | let mut emit_seq = 0usize; | 514 | let mut emit_seq = 0usize; |
| 421 | let mut reorder = Reorder::default(); | 515 | let mut reorder = Reorder::default(); |
| 422 | let mut in_flight = 0usize; | 516 | let mut in_flight = 0usize; |
| 423 | - let in_flight_cap = threads + 1; | 517 | + let in_flight_cap = threads + 2; |
| 424 | let (tx, rx) = std::sync::mpsc::channel::<LeafResult>(); | 518 | let (tx, rx) = std::sync::mpsc::channel::<LeafResult>(); |
| 425 | - // A worker needs its references to outlive the main thread's next | 519 | + // lane-thread3: at `threads > 1` THIS is the reference bank -- one |
| 426 | - // `refresh_frame_flags` write, so a dispatched slot is copied once into an | 520 | + // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled |
| 427 | - // `Arc` and re-shared until that slot is overwritten (cleared alongside | 521 | + // itself and pending for one an in-flight frame will fill. The owned |
| 428 | - // every `ref_slots` write below). The DPB itself stays owned `Picture`s: | 522 | + // arrays above are then untouched (and the single-threaded path never |
| 429 | - // an `Arc` DPB measured ~1% SLOWER single-threaded (lane-perf9). | 523 | + // creates a promise: it stays exactly the decoder it was, which is what |
| 430 | - let mut ref_arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = | 524 | + // keeps every counter-reading gate meaningful). |
| 525 | + let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] = | ||
| 431 | std::array::from_fn(|_| None); | 526 | std::array::from_fn(|_| None); |
| 432 | 527 | ||
| 433 | let mut pos = 0usize; | 528 | let mut pos = 0usize; |
| @@ -468,22 +563,38 @@ pub fn decode_stream_with_threads( | |||
| 468 | // was emitted (wrongly, in decode order) and its real | 563 | // was emitted (wrongly, in decode order) and its real |
| 469 | // `show_existing_frame` output was silently dropped. | 564 | // `show_existing_frame` output was silently dropped. |
| 470 | let slot = header.frame_to_show_map_idx as usize; | 565 | let slot = header.frame_to_show_map_idx as usize; |
| 471 | - let picture = ref_slots[slot].clone().ok_or_else(|| { | 566 | + let empty_slot = || { |
| 472 | Error::unsupported( | 567 | Error::unsupported( |
| 473 | "AV1 decode_stream", | 568 | "AV1 decode_stream", |
| 474 | "a show_existing_frame header naming an empty reference slot", | 569 | "a show_existing_frame header naming an empty reference slot", |
| 475 | ) | 570 | ) |
| 476 | - })?; | 571 | + }; |
| 477 | - for i in 0..NUM_REF_FRAMES { | 572 | + let picture = if threads > 1 { |
| 478 | - if header.refresh_frame_flags & (1 << i) != 0 { | 573 | + // lane-thread3: the named slot may still be decoding on a |
| 479 | - cdf_slots[i] = cdf_slots[slot].clone(); | 574 | + // worker. This is the parsing thread's ONLY promise wait, and |
| 480 | - ref_slots[i] = Some(picture.clone()); | 575 | + // it points at an earlier coded frame (see [`SlotPromise`]); |
| 481 | - ref_arcs[i] = None; | 576 | + // the copy into the refreshed slots is then just the promise. |
| 482 | - motion_field_slots[i] = motion_field_slots[slot].clone(); | 577 | + let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?; |
| 483 | - seg_map_slots[i] = seg_map_slots[slot].clone(); | 578 | + let value = promise.wait()?; |
| 484 | - order_hint_slots[i] = order_hint_slots[slot]; | 579 | + for i in 0..NUM_REF_FRAMES { |
| 580 | + if header.refresh_frame_flags & (1 << i) != 0 { | ||
| 581 | + slot_promises[i] = Some(promise.clone()); | ||
| 582 | + } | ||
| 485 | } | 583 | } |
| 486 | - } | 584 | + value.picture.as_ref().clone() |
| 585 | + } else { | ||
| 586 | + let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?; | ||
| 587 | + for i in 0..NUM_REF_FRAMES { | ||
| 588 | + if header.refresh_frame_flags & (1 << i) != 0 { | ||
| 589 | + cdf_slots[i] = cdf_slots[slot].clone(); | ||
| 590 | + ref_slots[i] = Some(picture.clone()); | ||
| 591 | + motion_field_slots[i] = motion_field_slots[slot].clone(); | ||
| 592 | + seg_map_slots[i] = seg_map_slots[slot].clone(); | ||
| 593 | + order_hint_slots[i] = order_hint_slots[slot]; | ||
| 594 | + } | ||
| 595 | + } | ||
| 596 | + picture | ||
| 597 | + }; | ||
| 487 | let output = if header.film_grain.apply_grain && !no_grain() { | 598 | let output = if header.film_grain.apply_grain && !no_grain() { |
| 488 | // lane-hbd10 r1: grain synthesis is bit-depth generic | 599 | // lane-hbd10 r1: grain synthesis is bit-depth generic |
| 489 | // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). | 600 | // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). |
| @@ -609,57 +720,78 @@ pub fn decode_stream_with_threads( | |||
| 609 | }) | 720 | }) |
| 610 | .collect::<Result<_>>()?; | 721 | .collect::<Result<_>>()?; |
| 611 | let seq = SeqFlags::read(&parser); | 722 | let seq = SeqFlags::read(&parser); |
| 612 | - // A LEAF of the reference graph: shown, not a key frame, and | 723 | + // lane-thread3: at `threads > 1` every coded frame that is not a key |
| 613 | - // refreshing no slot -- so nothing it produces except its own picture | 724 | + // frame is decoded on a worker -- frames that refresh reference slots |
| 614 | - // is ever read again (spec 7.20's bank update is keyed entirely on | 725 | + // included, which on a pyramid stream is nearly all of them. Its |
| 615 | - // `refresh_frame_flags`), and it can be decoded anywhere. | 726 | + // inputs are taken as promises and its output is published as one, |
| 616 | - if threads > 1 | 727 | + // installed into the slots it refreshes HERE, on the parsing thread, |
| 617 | - && header.refresh_frame_flags == 0 | 728 | + // in decode order, so the next frame's dependencies are known without |
| 618 | - && header.show_frame | 729 | + // waiting for this one to finish (see [`SlotPromise`] for the |
| 619 | - && !header.show_existing_frame | 730 | + // deadlock argument). A key frame stays inline: it resets the whole |
| 620 | - && header.frame_type != FrameType::Key | 731 | + // bank and reads nothing, so there is nothing to gain. |
| 621 | - { | 732 | + if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame { |
| 622 | while in_flight >= in_flight_cap { | 733 | while in_flight >= in_flight_cap { |
| 623 | collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?; | 734 | collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?; |
| 624 | } | 735 | } |
| 625 | - let mut arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = | 736 | + // Exactly the slots this frame reads: `ref_frame_idx` names its |
| 737 | + // references, and its `primary_ref_frame` CDFs/segment map, its | ||
| 738 | + // reference order hints and every field `setup_motion_field` | ||
| 739 | + // projects all come from those same slots. Nothing else is | ||
| 740 | + // waited on. | ||
| 741 | + let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] = | ||
| 626 | std::array::from_fn(|_| None); | 742 | std::array::from_fn(|_| None); |
| 627 | for i in 0..7 { | 743 | for i in 0..7 { |
| 628 | let slot = header.ref_frame_idx[i] as usize; | 744 | let slot = header.ref_frame_idx[i] as usize; |
| 629 | - if arcs[slot].is_none() | 745 | + deps[slot] = slot_promises[slot].clone(); |
| 630 | - && let Some(picture) = ref_slots[slot].as_ref() | 746 | + } |
| 631 | - { | 747 | + let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending); |
| 632 | - arcs[slot] = Some( | 748 | + if let Some(promise) = &produces { |
| 633 | - ref_arcs[slot] | 749 | + for i in 0..NUM_REF_FRAMES { |
| 634 | - .get_or_insert_with(|| std::sync::Arc::new(picture.clone())) | 750 | + if header.refresh_frame_flags & (1 << i) != 0 { |
| 635 | - .clone(), | 751 | + slot_promises[i] = Some(promise.clone()); |
| 636 | - ); | 752 | + } |
| 637 | } | 753 | } |
| 638 | } | 754 | } |
| 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); | 755 | let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); |
| 649 | emit_seq += 1; | 756 | emit_seq += 1; |
| 650 | pictures_decoded += 1; | 757 | pictures_decoded += 1; |
| 651 | - pictures_shown += 1; | 758 | + let shown = header.show_frame; |
| 759 | + if shown { | ||
| 760 | + pictures_shown += 1; | ||
| 761 | + } | ||
| 652 | let tx = tx.clone(); | 762 | let tx = tx.clone(); |
| 653 | let dump = final_dump.clone(); | 763 | let dump = final_dump.clone(); |
| 654 | scope.spawn(move || { | 764 | scope.spawn(move || { |
| 765 | + let promise = produces; | ||
| 655 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | 766 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 767 | + // The wait happens HERE, off the parsing thread, and only | ||
| 768 | + // for this frame's own references. | ||
| 769 | + let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] = | ||
| 770 | + std::array::from_fn(|_| None); | ||
| 771 | + for (slot, dep) in deps.iter().enumerate() { | ||
| 772 | + if let Some(dep) = dep { | ||
| 773 | + resolved[slot] = Some(dep.wait()?); | ||
| 774 | + } | ||
| 775 | + } | ||
| 656 | // Fresh per-thread state: every field this path reads is | 776 | // Fresh per-thread state: every field this path reads is |
| 657 | // written from this frame's own header before it is read. | 777 | // written from this frame's own header before it is read. |
| 658 | let fctx = crate::decode::FrameCtx::new(); | 778 | let fctx = crate::decode::FrameCtx::new(); |
| 659 | - let snap = RefSnapshot { | 779 | + // spec 7.9's `av1_setup_motion_field` runs inside |
| 660 | - refs: std::array::from_fn(|i| arcs[i].as_deref()), | 780 | + // `RefSnapshot::take`, i.e. here, after those waits -- |
| 661 | - ..snap | 781 | + // it reads the referenced slots' saved motion fields. |
| 662 | - }; | 782 | + let motion_fields = |
| 783 | + std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field)); | ||
| 784 | + let snap = RefSnapshot::take( | ||
| 785 | + &header, | ||
| 786 | + seq, | ||
| 787 | + std::array::from_fn(|i| resolved[i].as_ref().map(|v| &*v.picture)), | ||
| 788 | + std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)), | ||
| 789 | + std::array::from_fn(|i| { | ||
| 790 | + resolved[i].as_ref().map(|v| v.seg_map.as_slice()) | ||
| 791 | + }), | ||
| 792 | + &motion_fields, | ||
| 793 | + std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)), | ||
| 794 | + ); | ||
| 663 | let out = decode_frame( | 795 | let out = decode_frame( |
| 664 | &fctx, | 796 | &fctx, |
| 665 | &header, | 797 | &header, |
| @@ -670,28 +802,51 @@ pub fn decode_stream_with_threads( | |||
| 670 | shown_idx, | 802 | shown_idx, |
| 671 | dump.as_deref(), | 803 | dump.as_deref(), |
| 672 | )?; | 804 | )?; |
| 673 | - let picture = if header.film_grain.apply_grain && !no_grain() { | 805 | + // Publish before grain synthesis: every frame waiting on |
| 806 | + // this slot can start the moment the clean picture exists | ||
| 807 | + // (spec 7.18.3.1 -- the bank never stores grain). | ||
| 808 | + let picture = std::sync::Arc::new(out.picture); | ||
| 809 | + if let Some(promise) = &promise { | ||
| 810 | + promise.fulfil(std::sync::Arc::new(SlotValue { | ||
| 811 | + picture: picture.clone(), | ||
| 812 | + cdfs: out.stored_cdfs, | ||
| 813 | + motion_field: out.motion_field, | ||
| 814 | + seg_map: out.seg_map, | ||
| 815 | + order_hint: header.order_hint, | ||
| 816 | + })); | ||
| 817 | + } | ||
| 818 | + // Grain is synthesised for OUTPUT only: a hidden frame is | ||
| 819 | + // reported to the sink clean, exactly as the inline path | ||
| 820 | + // below reports it (spec 7.18.3.1). | ||
| 821 | + let output = if shown && header.film_grain.apply_grain && !no_grain() { | ||
| 674 | crate::film_grain::apply_grain( | 822 | crate::film_grain::apply_grain( |
| 675 | - &out.picture, | 823 | + &picture, |
| 676 | &header.film_grain, | 824 | &header.film_grain, |
| 677 | seq.mc_identity, | 825 | seq.mc_identity, |
| 678 | u32::from(seq.bit_depth), | 826 | u32::from(seq.bit_depth), |
| 679 | &fctx, | 827 | &fctx, |
| 680 | ) | 828 | ) |
| 681 | } else { | 829 | } else { |
| 682 | - out.picture | 830 | + std::sync::Arc::try_unwrap(picture).unwrap_or_else(|p| (*p).clone()) |
| 683 | }; | 831 | }; |
| 684 | - Ok((picture, decode_idx, true)) | 832 | + Ok((output, decode_idx, shown)) |
| 685 | })) | 833 | })) |
| 686 | .unwrap_or_else(|_| { | 834 | .unwrap_or_else(|_| { |
| 687 | Err(Error::corrupt( | 835 | Err(Error::corrupt( |
| 688 | - "AV1 decode_stream: a worker thread panicked decoding a leaf frame", | 836 | + "AV1 decode_stream: a worker thread panicked decoding a frame", |
| 689 | )) | 837 | )) |
| 690 | }); | 838 | }); |
| 839 | + // A frame nobody can decode must not leave its consumers | ||
| 840 | + // waiting for a slot that will never be filled. | ||
| 841 | + if reply.is_err() | ||
| 842 | + && let Some(promise) = &promise | ||
| 843 | + { | ||
| 844 | + promise.fail(); | ||
| 845 | + } | ||
| 691 | let _ = tx.send((job_seq, reply)); | 846 | let _ = tx.send((job_seq, reply)); |
| 692 | }); | 847 | }); |
| 693 | in_flight += 1; | 848 | in_flight += 1; |
| 694 | - LEAF_FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | 849 | + FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 695 | // Anything that finished while this frame was being set up. | 850 | // Anything that finished while this frame was being set up. |
| 696 | while let Ok((seq, result)) = rx.try_recv() { | 851 | while let Ok((seq, result)) = rx.try_recv() { |
| 697 | in_flight -= 1; | 852 | in_flight -= 1; |
| @@ -705,10 +860,10 @@ pub fn decode_stream_with_threads( | |||
| 705 | &header, | 860 | &header, |
| 706 | seq, | 861 | seq, |
| 707 | std::array::from_fn(|i| ref_slots[i].as_ref()), | 862 | std::array::from_fn(|i| ref_slots[i].as_ref()), |
| 708 | - &cdf_slots, | 863 | + std::array::from_fn(|i| cdf_slots[i].as_ref()), |
| 709 | - &seg_map_slots, | 864 | + std::array::from_fn(|i| seg_map_slots[i].as_deref()), |
| 710 | - &motion_field_slots, | 865 | + &std::array::from_fn(|i| motion_field_slots[i].as_ref()), |
| 711 | - &order_hint_slots, | 866 | + order_hint_slots, |
| 712 | ); | 867 | ); |
| 713 | let bit_depth = seq.bit_depth; | 868 | let bit_depth = seq.bit_depth; |
| 714 | let FrameOutput { | 869 | let FrameOutput { |
| @@ -727,18 +882,38 @@ pub fn decode_stream_with_threads( | |||
| 727 | final_dump.as_deref(), | 882 | final_dump.as_deref(), |
| 728 | )?; | 883 | )?; |
| 729 | pictures_decoded += 1; | 884 | pictures_decoded += 1; |
| 730 | - for i in 0..NUM_REF_FRAMES { | 885 | + if threads > 1 { |
| 731 | - if header.refresh_frame_flags & (1 << i) != 0 { | 886 | + // lane-thread3: only a key frame reaches this inline path at |
| 732 | - cdf_slots[i] = Some(stored_cdfs.clone()); | 887 | + // `threads > 1`, and the bank it fills is the promise array -- |
| 733 | - // Spec 7.18.3.1: synthesized grain is never stored for later | 888 | + // already resolved, since the picture exists right here. |
| 734 | - // prediction -- the reference bank always keeps the clean, | 889 | + if header.refresh_frame_flags != 0 { |
| 735 | - // pre-grain decode, even though the frame pushed onto the | 890 | + let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { |
| 736 | - // caller's output below carries the grained picture. | 891 | + picture: std::sync::Arc::new(picture.clone()), |
| 737 | - ref_slots[i] = Some(picture.clone()); | 892 | + cdfs: stored_cdfs, |
| 738 | - ref_arcs[i] = None; | 893 | + motion_field, |
| 739 | - motion_field_slots[i] = Some(motion_field.clone()); | 894 | + seg_map: decoded_seg_map, |
| 740 | - seg_map_slots[i] = Some(decoded_seg_map.clone()); | 895 | + order_hint: header.order_hint, |
| 741 | - order_hint_slots[i] = header.order_hint; | 896 | + })); |
| 897 | + for i in 0..NUM_REF_FRAMES { | ||
| 898 | + if header.refresh_frame_flags & (1 << i) != 0 { | ||
| 899 | + slot_promises[i] = Some(promise.clone()); | ||
| 900 | + } | ||
| 901 | + } | ||
| 902 | + } | ||
| 903 | + } else { | ||
| 904 | + for i in 0..NUM_REF_FRAMES { | ||
| 905 | + if header.refresh_frame_flags & (1 << i) != 0 { | ||
| 906 | + cdf_slots[i] = Some(stored_cdfs.clone()); | ||
| 907 | + // Spec 7.18.3.1: synthesized grain is never stored for | ||
| 908 | + // later prediction -- the reference bank always keeps the | ||
| 909 | + // clean, pre-grain decode, even though the frame pushed | ||
| 910 | + // onto the caller's output below carries the grained | ||
| 911 | + // picture. | ||
| 912 | + ref_slots[i] = Some(picture.clone()); | ||
| 913 | + motion_field_slots[i] = Some(motion_field.clone()); | ||
| 914 | + seg_map_slots[i] = Some(decoded_seg_map.clone()); | ||
| 915 | + order_hint_slots[i] = header.order_hint; | ||
| 916 | + } | ||
| 742 | } | 917 | } |
| 743 | } | 918 | } |
| 744 | // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a | 919 | // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a |
| @@ -839,17 +1014,19 @@ pub(crate) struct RefSnapshot<'a> { | |||
| 839 | } | 1014 | } |
| 840 | 1015 | ||
| 841 | impl<'a> RefSnapshot<'a> { | 1016 | impl<'a> RefSnapshot<'a> { |
| 842 | - /// Reads the banks for `header`. `refs` is passed in so that the | 1017 | + /// Reads the banks for `header`. Every slot is passed in by reference so |
| 843 | - /// single-threaded path can borrow the DPB pictures in place while the | 1018 | + /// that the single-threaded path can borrow the DPB in place while a |
| 844 | - /// worker path hands over its own `Arc` clones. | 1019 | + /// worker borrows the resolved [`SlotPromise`] values it waited on -- |
| 1020 | + /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread | ||
| 1021 | + /// (lane-thread3), after those waits. | ||
| 845 | fn take( | 1022 | fn take( |
| 846 | header: &FrameHeader, | 1023 | header: &FrameHeader, |
| 847 | seq: SeqFlags, | 1024 | seq: SeqFlags, |
| 848 | refs: [Option<&'a Picture>; NUM_REF_FRAMES], | 1025 | refs: [Option<&'a Picture>; NUM_REF_FRAMES], |
| 849 | - cdf_slots: &[Option<Cdfs>; NUM_REF_FRAMES], | 1026 | + cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES], |
| 850 | - seg_map_slots: &[Option<Vec<u8>>; NUM_REF_FRAMES], | 1027 | + seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES], |
| 851 | - motion_field_slots: &[Option<crate::motion_field::MotionField>; NUM_REF_FRAMES], | 1028 | + motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES], |
| 852 | - order_hint_slots: &[u32; NUM_REF_FRAMES], | 1029 | + order_hint_slots: [u32; NUM_REF_FRAMES], |
| 853 | ) -> Self { | 1030 | ) -> Self { |
| 854 | let primary = (header.primary_ref_frame != PRIMARY_REF_NONE) | 1031 | let primary = (header.primary_ref_frame != PRIMARY_REF_NONE) |
| 855 | .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize); | 1032 | .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize); |
| @@ -880,8 +1057,8 @@ impl<'a> RefSnapshot<'a> { | |||
| 880 | } | 1057 | } |
| 881 | Self { | 1058 | Self { |
| 882 | refs, | 1059 | refs, |
| 883 | - primary_cdfs: primary.and_then(|slot| cdf_slots[slot].clone()), | 1060 | + primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()), |
| 884 | - prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].clone()), | 1061 | + prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)), |
| 885 | tpl_field, | 1062 | tpl_field, |
| 886 | ref_order_hints: std::array::from_fn(|i| { | 1063 | ref_order_hints: std::array::from_fn(|i| { |
| 887 | order_hint_slots[header.ref_frame_idx[i] as usize] | 1064 | order_hint_slots[header.ref_frame_idx[i] as usize] |
| @@ -32141,24 +32318,25 @@ mod tests { | |||
| 32141 | /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink | 32318 | /// [`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. | 32319 | /// call is compared -- decode index, shown flag, and all three planes. |
| 32143 | /// | 32320 | /// |
| 32144 | - /// `reelb_arf_witness.obu` is the one that proves the parallel path: 18 of | 32321 | + /// `reelb_arf_witness.obu` is the one that proves the parallel path: it |
| 32145 | - /// its 40 coded frames are leaves of the reference graph (shown, | 32322 | + /// carries hidden alt-refs, which is exactly the case where "output in |
| 32146 | - /// non-key, `refresh_frame_flags == 0`), so 18 frames really are decoded | 32323 | + /// coded order" is not the same as "output in the order workers finish", |
| 32147 | - /// off the main thread, and it carries hidden alt-refs, which is exactly | 32324 | + /// and under lane-thread3's dependency-aware scheduling 39 of its 40 |
| 32148 | - /// the case where "output in coded order" is not the same as "output in | 32325 | + /// coded frames (all but the key frame) are decoded off the main thread |
| 32149 | - /// the order workers finish". `palette_screen_witness.obu` is the | 32326 | + /// -- MORE than its 37 shown frames, which is the point: lane-thread2's |
| 32150 | - /// complement: an 8-bit screen stream whose every coded frame refreshes a | 32327 | + /// leaf rule dispatched 18. `palette_screen_witness.obu` is the |
| 32151 | - /// slot, so at 4 threads it dispatches NOTHING and pins that the threaded | 32328 | + /// complement, an 8-bit screen stream whose every coded frame refreshes a |
| 32152 | - /// entry point is byte-identical on the inline path too. The dispatch | 32329 | + /// slot: lane-thread2 dispatched NOTHING for it, lane-thread3 dispatches |
| 32153 | - /// counter is asserted in both directions, so neither arm can pass | 32330 | + /// all 14 of its non-key frames. Both counts are asserted exactly, plus |
| 32154 | - /// vacuously. | 32331 | + /// the "more than half the shown frames really ran on a worker" bound, so |
| 32332 | + /// neither arm can pass vacuously. | ||
| 32155 | #[test] | 32333 | #[test] |
| 32156 | fn a_real_stream_decodes_identically_with_one_and_four_threads() { | 32334 | 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"; | 32335 | 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) | 32336 | + // (fixture, shown frames, frames a 4-thread run must dispatch) |
| 32159 | - for (fixture, shown_frames, want_leaves) in [ | 32337 | + for (fixture, shown_frames, want_dispatched) in [ |
| 32160 | - ("fixtures/reelb_arf_witness.obu", 37usize, 18usize), | 32338 | + ("fixtures/reelb_arf_witness.obu", 37usize, 39usize), |
| 32161 | - ("fixtures/palette_screen_witness.obu", 15, 0), | 32339 | + ("fixtures/palette_screen_witness.obu", 15, 14), |
| 32162 | ] { | 32340 | ] { |
| 32163 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture); | 32341 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture); |
| 32164 | let stream = std::fs::read(&path) | 32342 | let stream = std::fs::read(&path) |
| @@ -32173,12 +32351,16 @@ mod tests { | |||
| 32173 | out | 32351 | out |
| 32174 | }; | 32352 | }; |
| 32175 | let serial = run(1); | 32353 | let serial = run(1); |
| 32176 | - let before = leaf_frames_dispatched(); | 32354 | + let before = frames_dispatched(); |
| 32177 | let parallel = run(4); | 32355 | let parallel = run(4); |
| 32178 | - let dispatched = leaf_frames_dispatched() - before; | 32356 | + let dispatched = frames_dispatched() - before; |
| 32179 | assert_eq!( | 32357 | assert_eq!( |
| 32180 | - dispatched, want_leaves, | 32358 | + dispatched, want_dispatched, |
| 32181 | - "{NAME}: {fixture} dispatched {dispatched} leaf frames to workers, expected {want_leaves}" | 32359 | + "{NAME}: {fixture} dispatched {dispatched} frames to workers, expected {want_dispatched}" |
| 32360 | + ); | ||
| 32361 | + assert!( | ||
| 32362 | + dispatched * 2 > shown_frames, | ||
| 32363 | + "{NAME}: {fixture} dispatched {dispatched} frames, not even half of its {shown_frames} shown frames -- the parallel path is barely exercised" | ||
| 32182 | ); | 32364 | ); |
| 32183 | assert_eq!( | 32365 | assert_eq!( |
| 32184 | serial.iter().filter(|f| f.1).count(), | 32366 | serial.iter().filter(|f| f.1).count(), |