Decode leaf frames on worker threads (EC_AV1_THREADS, default 1)
Browse files at this commitb3a78b463337c29f02dbb55d644bc28b765960d9Parent: 1241afc- feat
- decode leaf frames on worker threads (EC_AV1_THREADS, default 1)
2 changed files +239 -3
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+233 -3
| @@ -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 | } |
| @@ -481,6 +609,98 @@ pub fn decode_stream_with( | |||
| 481 | }) | 609 | }) |
| 482 | .collect::<Result<_>>()?; | 610 | .collect::<Result<_>>()?; |
| 483 | let seq = SeqFlags::read(&parser); | 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 | + } | ||
| 484 | let snap = RefSnapshot::take( | 704 | let snap = RefSnapshot::take( |
| 485 | &header, | 705 | &header, |
| 486 | seq, | 706 | seq, |
| @@ -515,6 +735,7 @@ pub fn decode_stream_with( | |||
| 515 | // pre-grain decode, even though the frame pushed onto the | 735 | // pre-grain decode, even though the frame pushed onto the |
| 516 | // caller's output below carries the grained picture. | 736 | // caller's output below carries the grained picture. |
| 517 | ref_slots[i] = Some(picture.clone()); | 737 | ref_slots[i] = Some(picture.clone()); |
| 738 | + ref_arcs[i] = None; | ||
| 518 | motion_field_slots[i] = Some(motion_field.clone()); | 739 | motion_field_slots[i] = Some(motion_field.clone()); |
| 519 | seg_map_slots[i] = Some(decoded_seg_map.clone()); | 740 | seg_map_slots[i] = Some(decoded_seg_map.clone()); |
| 520 | order_hint_slots[i] = header.order_hint; | 741 | order_hint_slots[i] = header.order_hint; |
| @@ -539,17 +760,26 @@ pub fn decode_stream_with( | |||
| 539 | } else { | 760 | } else { |
| 540 | picture | 761 | picture |
| 541 | }; | 762 | }; |
| 542 | - 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)?; | ||
| 543 | pictures_shown += 1; | 766 | pictures_shown += 1; |
| 544 | } else { | 767 | } else { |
| 545 | // Hidden (alt-ref/forward-key) frames never reach | 768 | // Hidden (alt-ref/forward-key) frames never reach |
| 546 | // `decode_stream`'s output, but a decode-order consumer -- the | 769 | // `decode_stream`'s output, but a decode-order consumer -- the |
| 547 | // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs | 770 | // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs |
| 548 | // them, so they are reported too, with `shown == false`. | 771 | // them, so they are reported too, with `shown == false`. |
| 549 | - 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)?; | ||
| 550 | } | 775 | } |
| 551 | } | 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"); | ||
| 552 | Ok(()) | 781 | Ok(()) |
| 782 | + }) | ||
| 553 | } | 783 | } |
| 554 | 784 | ||
| 555 | 785 | ||