forge
Explore
Log in

Don't you dare go Hollow

A show_existing_frame output no longer stalls the parsing thread

Browse files at this commit

fada71e306c05c584aa083d2d106ea963a86a90eAhmet Kaan GümüşParent: fcddd9c
  • perf
    • a show_existing_frame output no longer stalls the parsing thread
Show full message
perf(av1): a show_existing_frame output no longer stalls the parsing thread

The parser waited for the named slot's promise before emitting the picture,
and that wait was where the whole decode went: 7.9 s of an 8.8 s 1080p decode
and 18.9 s of a 23.3 s 4K one, measured with a counter around the wait. A
stalled parser dispatches nothing, so every worker drained behind it.

The output job now runs on a worker too (wait for the slot, synthesise grain,
send): the parser only copies the promise into the slots the header refreshes,
which needs no value at all. The wait still points at an earlier coded frame,
so the deadlock argument at `SlotPromise` is unchanged.

Frame decodes and output jobs are bounded separately (`threads + 2` each): an
output job is a wait plus a memcpy, so letting it hold a decode's budget just
idles a core (4K 18.7 s at 244% CPU sharing one bound, 17.7 s at 287% not).

seg4k 272 frames: 35.7 s at 1 thread -> 18.7 s at 4 (was 24.2 s before this
commit); seg1080 299 frames: 10.5 s -> 8.0 s (was 9.4 s). All twelve gate
hashes unchanged at 1, 2 and 4 threads.
crates/ec-av1/src/stream.rsmodified+109 -25
@@ -422,25 +422,33 @@ impl SlotPromise {
422422 }
423423 }
424424
425-/// One finished leaf frame from a worker: its output position, and either the
426-/// (grain-synthesised) picture with the decode index to report or the error
427-/// that aborts the stream.
428-type LeafResult = (usize, Result<(Picture, usize, bool)>);
429-
430-/// Waits for one in-flight leaf frame and emits whatever that unblocks.
425+/// One finished frame from a worker: its output position, whether the job was
426+/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
427+/// waits for a slot and synthesises grain -- lane-thread3 counts the two
428+/// against separate in-flight bounds, since a waiting output job costs no
429+/// CPU), and either the (grain-synthesised) picture with the decode index to
430+/// report or the error that aborts the stream.
431+type LeafResult = (usize, bool, Result<(Picture, usize, bool)>);
432+
433+/// Waits for one in-flight job and emits whatever that unblocks.
431434 fn collect_one(
432435 rx: &std::sync::mpsc::Receiver<LeafResult>,
433- in_flight: &mut usize,
436+ decodes: &mut usize,
437+ shows: &mut usize,
434438 reorder: &mut Reorder,
435439 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
436440 ) -> Result<()> {
437441 // Every dispatched worker answers exactly once, panic included (it is
438442 // caught and turned into an error below), so the sender count cannot
439443 // reach zero while `in_flight > 0`.
440- let (seq, result) = rx
444+ let (seq, decode_job, result) = rx
441445 .recv()
442446 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
443- *in_flight -= 1;
447+ if decode_job {
448+ *decodes -= 1;
449+ } else {
450+ *shows -= 1;
451+ }
444452 let (picture, decode_idx, shown) = result?;
445453 reorder.push(seq, picture, decode_idx, shown);
446454 reorder.drain(sink)
@@ -513,7 +521,12 @@ pub fn decode_stream_with_threads(
513521 // pushed).
514522 let mut emit_seq = 0usize;
515523 let mut reorder = Reorder::default();
516- let mut in_flight = 0usize;
524+ // lane-thread3: frame decodes and `show_existing_frame` outputs are
525+ // bounded separately -- an output job is a promise wait plus a memcpy, so
526+ // letting it eat a decode's budget just idles a core (measured: sharing
527+ // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
528+ let mut in_flight_decodes = 0usize;
529+ let mut in_flight_shows = 0usize;
517530 let in_flight_cap = threads + 2;
518531 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
519532 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
@@ -569,20 +582,75 @@ pub fn decode_stream_with_threads(
569582 "a show_existing_frame header naming an empty reference slot",
570583 )
571584 };
572- let picture = if threads > 1 {
585+ if threads > 1 {
573586 // lane-thread3: the named slot may still be decoding on a
574- // worker. This is the parsing thread's ONLY promise wait, and
575- // it points at an earlier coded frame (see [`SlotPromise`]);
576- // the copy into the refreshed slots is then just the promise.
587+ // worker, and the copy into the slots this header refreshes
588+ // is then just the promise -- no value needed. The OUTPUT
589+ // does need the picture, so it is produced on a worker too:
590+ // waiting for it here would stall the parsing thread, and a
591+ // stalled parser dispatches nothing (measured before this
592+ // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
593+ // 23.3 s at 4K, spent in this one wait). The wait still
594+ // points at an earlier coded frame, so the argument in
595+ // [`SlotPromise`] is unchanged.
577596 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
578- let value = promise.wait()?;
579597 for i in 0..NUM_REF_FRAMES {
580598 if header.refresh_frame_flags & (1 << i) != 0 {
581599 slot_promises[i] = Some(promise.clone());
582600 }
583601 }
584- value.picture.as_ref().clone()
585- } else {
602+ while in_flight_shows >= in_flight_cap {
603+ collect_one(
604+ &rx,
605+ &mut in_flight_decodes,
606+ &mut in_flight_shows,
607+ &mut reorder,
608+ &mut sink,
609+ )?;
610+ }
611+ let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
612+ emit_seq += 1;
613+ pictures_shown += 1;
614+ let grain = header.film_grain;
615+ let seq = SeqFlags::read(&parser);
616+ let tx = tx.clone();
617+ scope.spawn(move || {
618+ let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
619+ let value = promise.wait()?;
620+ let output = if grain.apply_grain && !no_grain() {
621+ crate::film_grain::apply_grain(
622+ &value.picture,
623+ &grain,
624+ seq.mc_identity,
625+ u32::from(seq.bit_depth),
626+ &crate::decode::FrameCtx::new(),
627+ )
628+ } else {
629+ value.picture.as_ref().clone()
630+ };
631+ Ok((output, decode_idx, true))
632+ }))
633+ .unwrap_or_else(|_| {
634+ Err(Error::corrupt(
635+ "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
636+ ))
637+ });
638+ let _ = tx.send((job_seq, false, reply));
639+ });
640+ in_flight_shows += 1;
641+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
642+ if decode_job {
643+ in_flight_decodes -= 1;
644+ } else {
645+ in_flight_shows -= 1;
646+ }
647+ let (picture, decode_idx, shown) = result?;
648+ reorder.push(seq, picture, decode_idx, shown);
649+ reorder.drain(&mut sink)?;
650+ }
651+ continue;
652+ }
653+ let picture = {
586654 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
587655 for i in 0..NUM_REF_FRAMES {
588656 if header.refresh_frame_flags & (1 << i) != 0 {
@@ -730,8 +798,14 @@ pub fn decode_stream_with_threads(
730798 // deadlock argument). A key frame stays inline: it resets the whole
731799 // bank and reads nothing, so there is nothing to gain.
732800 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
733- while in_flight >= in_flight_cap {
734- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;
801+ while in_flight_decodes >= in_flight_cap {
802+ collect_one(
803+ &rx,
804+ &mut in_flight_decodes,
805+ &mut in_flight_shows,
806+ &mut reorder,
807+ &mut sink,
808+ )?;
735809 }
736810 // Exactly the slots this frame reads: `ref_frame_idx` names its
737811 // references, and its `primary_ref_frame` CDFs/segment map, its
@@ -843,13 +917,17 @@ pub fn decode_stream_with_threads(
843917 {
844918 promise.fail();
845919 }
846- let _ = tx.send((job_seq, reply));
920+ let _ = tx.send((job_seq, true, reply));
847921 });
848- in_flight += 1;
922+ in_flight_decodes += 1;
849923 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
850924 // Anything that finished while this frame was being set up.
851- while let Ok((seq, result)) = rx.try_recv() {
852- in_flight -= 1;
925+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
926+ if decode_job {
927+ in_flight_decodes -= 1;
928+ } else {
929+ in_flight_shows -= 1;
930+ }
853931 let (picture, decode_idx, shown) = result?;
854932 reorder.push(seq, picture, decode_idx, shown);
855933 reorder.drain(&mut sink)?;
@@ -949,8 +1027,14 @@ pub fn decode_stream_with_threads(
9491027 reorder.drain(&mut sink)?;
9501028 }
9511029 }
952- while in_flight > 0 {
953- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;
1030+ while in_flight_decodes + in_flight_shows > 0 {
1031+ collect_one(
1032+ &rx,
1033+ &mut in_flight_decodes,
1034+ &mut in_flight_shows,
1035+ &mut reorder,
1036+ &mut sink,
1037+ )?;
9541038 }
9551039 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
9561040 Ok(())