diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 61482e40..763f4d77 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2425,7 +2425,13 @@ fn wave_worker(st: &WaveState) { /// Installs the wavefront for one tile and joins its workers on every exit /// from the tile decoder, including the `?` ones -- the jobs hold raw /// pointers into the tile's planes, so no worker may outlive them. -pub(crate) struct WaveGuard<'a>(&'a crate::decode::FrameCtx, Vec>); +/// (lane-pool1: the workers come from this thread's persistent pool, so a +/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads +/// with fresh scratch.) +pub(crate) struct WaveGuard<'a>( + &'a crate::decode::FrameCtx, + Option>, +); #[allow(unsafe_code)] impl<'a> WaveGuard<'a> { @@ -2460,14 +2466,13 @@ impl<'a> WaveGuard<'a> { enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), last_col: cols - 1, }); - let workers = (0..threads) - .map(|_| { - let st = std::sync::Arc::clone(&st); - std::thread::spawn(move || wave_worker(&st)) - }) - .collect(); + let batch = crate::par::Batch::new(); + for _ in 0..threads { + let st = std::sync::Arc::clone(&st); + batch.submit(move || wave_worker(&st)); + } fctx.wave.with(|w| *w.borrow_mut() = Some(st)); - Some(Self(fctx, workers)) + Some(Self(fctx, Some(batch))) } } @@ -2478,9 +2483,8 @@ impl Drop for WaveGuard<'_> { st.q.lock().unwrap().closed = true; st.cv.notify_all(); } - for h in self.1.drain(..) { - let _ = h.join(); - } + // Dropping the batch waits every worker out, as the joins did. + drop(self.1.take()); } } diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index f77dde51..911d1009 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -122,14 +122,17 @@ where [] => {} [(a, b)] => f(*a, *b, fctx), [(a0, b0), rest @ ..] => { - std::thread::scope(|s| { - for &(a, b) in rest { - let ctx = crate::decode::filter_ctx_copy(fctx); - let f = &f; - s.spawn(move || f(a, b, &ctx)); - } - f(*a0, *b0, fctx); - }); + // lane-pool1: same shape as the `thread::scope` this replaced -- + // band 0 inline, the rest on this thread's persistent pool, all + // waited out by `batch`'s drop at the end of the block. + let batch = Batch::new(); + for &(a, b) in rest { + let ctx = crate::decode::filter_ctx_copy(fctx); + let f = &f; + batch.submit(move || f(a, b, &ctx)); + } + f(*a0, *b0, fctx); + drop(batch); } } } @@ -161,3 +164,181 @@ pub(crate) fn recon_threads() -> usize { pub(crate) fn set_recon_threads(n: usize) { RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); } + +// --- lane-pool1: persistent worker pools --------------------------------- +// +// Every threaded stage of the decoder used to spawn its threads per unit of +// work: one `thread::scope` per filter STAGE per frame, `EC_AV1_RECON_THREADS` +// workers per TILE, one frame worker per coded frame -- 2363 distinct threads +// in a 13 s 4K decode. The cost is not the clone of the thread itself but what +// dies with it: every `thread_local!` scratch pool in `decode.rs` (planes, +// rows, dq, mc, wiener, sgr) is allocated and faulted in again on each new +// thread, which is where the 3.65 M page faults and the 2.7x malloc traffic of +// the composed setting came from. +// +// The replacement is one pool per POOL-OWNING THREAD, kept in a thread-local +// and joined when that thread exits: a stage submits a [`Batch`] of jobs, the +// pool hands each to an idle worker (growing to `busy + queued` so a job never +// queues behind a blocking one -- the recon wavefront's workers block on their +// dependencies), and the batch's `Drop` waits every job out. Scratch then +// lives as long as the worker, not as long as the frame. +type Job = Box; + +struct PoolQ { + jobs: std::collections::VecDeque, + /// Jobs handed to a worker and not yet finished. + busy: usize, + closed: bool, +} + +struct PoolInner { + q: std::sync::Mutex, + cv: std::sync::Condvar, +} + +struct Pool { + inner: std::sync::Arc, + handles: Vec>, +} + +fn pool_worker(inner: &PoolInner) { + let mut q = inner.q.lock().unwrap(); + loop { + if let Some(job) = q.jobs.pop_front() { + q.busy += 1; + drop(q); + // A job's own panic is captured by the batch wrapper below, so + // this only guards against a wrapper that itself unwinds. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + q = inner.q.lock().unwrap(); + q.busy -= 1; + continue; + } + if q.closed { + return; + } + q = inner.cv.wait(q).unwrap(); + } +} + +impl Pool { + fn new() -> Self { + Self { + inner: std::sync::Arc::new(PoolInner { + q: std::sync::Mutex::new(PoolQ { + jobs: std::collections::VecDeque::new(), + busy: 0, + closed: false, + }), + cv: std::sync::Condvar::new(), + }), + handles: Vec::new(), + } + } + + /// Queues `job` and makes sure a worker is free for it: the pool grows to + /// `busy + queued` threads and never shrinks, so a submitted job always + /// starts, even when every other running job is blocked waiting for it. + fn push(&mut self, job: Job) { + let want = { + let mut q = self.inner.q.lock().unwrap(); + q.jobs.push_back(job); + q.busy + q.jobs.len() + }; + while self.handles.len() < want { + let inner = std::sync::Arc::clone(&self.inner); + self.handles + .push(std::thread::spawn(move || pool_worker(&inner))); + } + self.inner.cv.notify_one(); + } +} + +impl Drop for Pool { + fn drop(&mut self) { + self.inner.q.lock().unwrap().closed = true; + self.inner.cv.notify_all(); + for h in self.handles.drain(..) { + let _ = h.join(); + } + } +} + +thread_local! { + /// This thread's pool, created on its first [`Batch::submit`] and joined + /// when the thread exits (the process's main thread may skip that + /// destructor, in which case the idle workers die with the process). + static POOL: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +struct BatchState { + left: std::sync::Mutex, + cv: std::sync::Condvar, + panic: std::sync::Mutex>>, +} + +/// A set of jobs running on the submitting thread's pool. `Drop` waits for +/// every one of them and re-raises the first panic, which is what makes +/// [`Batch::submit`]'s borrow of non-`'static` data sound -- exactly +/// `thread::scope`'s contract, minus the spawns. +/// +/// corner-cut: soundness rests on this `Drop` running; `std::mem::forget` of a +/// `Batch` would let a job outlive its borrows. The type is crate-private and +/// every construction site below binds it to a local. Upgrade path is the +/// closure-taking `scope(|s| ...)` shape, which costs every caller a level of +/// indentation for the same guarantee. +pub(crate) struct Batch<'a> { + st: std::sync::Arc, + _p: std::marker::PhantomData<&'a ()>, +} + +impl<'a> Batch<'a> { + pub(crate) fn new() -> Self { + Self { + st: std::sync::Arc::new(BatchState { + left: std::sync::Mutex::new(0), + cv: std::sync::Condvar::new(), + panic: std::sync::Mutex::new(None), + }), + _p: std::marker::PhantomData, + } + } + + pub(crate) fn submit(&self, f: F) { + *self.st.left.lock().unwrap() += 1; + let st = std::sync::Arc::clone(&self.st); + let job: Box = Box::new(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + if let Err(p) = r { + let mut slot = st.panic.lock().unwrap(); + if slot.is_none() { + *slot = Some(p); + } + } + let mut left = st.left.lock().unwrap(); + *left -= 1; + st.cv.notify_all(); + }); + // SAFETY: the job is dropped before `Batch::drop` returns (it waits + // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the + // laundered lifetime is never observed past the real one. + let job: Job = unsafe { std::mem::transmute::, Job>(job) }; + POOL.with(|p| { + let mut p = p.borrow_mut(); + p.get_or_insert_with(Pool::new).push(job); + }); + } +} + +impl Drop for Batch<'_> { + fn drop(&mut self) { + let mut left = self.st.left.lock().unwrap(); + while *left > 0 { + left = self.st.cv.wait(left).unwrap(); + } + drop(left); + if let Some(p) = self.st.panic.lock().unwrap().take() { + std::panic::resume_unwind(p); + } + } +} diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 6cb22e04..b02bd714 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -296,11 +296,15 @@ fn decode_threads() -> usize { #[derive(Default)] struct Reorder { next: usize, - pending: std::collections::BTreeMap, + // lane-pool1: the picture is shared, not owned -- a decoded frame that + // refreshes a reference slot is already behind an `Arc` for the slot, and + // handing the output an owned `Picture` meant copying every plane of it + // (24 MB per 4K 10-bit frame) purely to put it in this queue. + pending: std::collections::BTreeMap, usize, bool)>, } impl Reorder { - fn push(&mut self, seq: usize, picture: Picture, decode_idx: usize, shown: bool) { + fn push(&mut self, seq: usize, picture: std::sync::Arc, decode_idx: usize, shown: bool) { self.pending.insert(seq, (picture, decode_idx, shown)); } @@ -431,7 +435,7 @@ impl SlotPromise { /// against separate in-flight bounds, since a waiting output job costs no /// CPU), and either the (grain-synthesised) picture with the decode index to /// report or the error that aborts the stream. -type LeafResult = (usize, bool, Result<(Picture, usize, bool)>); +type LeafResult = (usize, bool, Result<(std::sync::Arc, usize, bool)>); /// Waits for one in-flight job and emits whatever that unblocks. fn collect_one( @@ -478,7 +482,12 @@ pub fn decode_stream_with_threads( threads: usize, mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, ) -> Result<()> { - std::thread::scope(|scope| { + // lane-pool1: this replaced a `std::thread::scope` -- frame workers now + // come from a persistent pool (one per submitting thread, workers reused + // across frames, so their `thread_local!` decode scratch survives the + // frame). `jobs` is declared here and dropped at the end of the function, + // including on `?`, so no job outlives the data it borrows. + let jobs = crate::par::Batch::new(); // lane-thread1: this stream's per-frame decode state (was 38 thread_local // statics in decode.rs) -- one object, threaded down the decode call graph. let fctx = &crate::decode::FrameCtx::new(); @@ -498,7 +507,10 @@ pub fn decode_stream_with_threads( // luma-only (chroma coincidentally shares this fixture's flat regions) // and small-magnitude (the two pictures mostly agree), which is exactly // what made it look like a rounding bug rather than a wrong reference. - let mut ref_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy + // its whole picture k times, and its output a (k+1)-th time. + let mut ref_slots: [Option>; NUM_REF_FRAMES] = + std::array::from_fn(|_| None); // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was @@ -617,19 +629,19 @@ pub fn decode_stream_with_threads( let grain = header.film_grain; let seq = SeqFlags::read(&parser); let tx = tx.clone(); - scope.spawn(move || { + jobs.submit(move || { let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let value = promise.wait()?; let output = if grain.apply_grain && !no_grain() { - crate::film_grain::apply_grain( + std::sync::Arc::new(crate::film_grain::apply_grain( &value.picture, &grain, seq.mc_identity, u32::from(seq.bit_depth), &crate::decode::FrameCtx::new(), - ) + )) } else { - value.picture.as_ref().clone() + std::sync::Arc::clone(&value.picture) }; Ok((output, decode_idx, true)) })) @@ -675,12 +687,12 @@ pub fn decode_stream_with_threads( let mc_identity = parser .sequence_header() .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain( + std::sync::Arc::new(crate::film_grain::apply_grain( &picture, &header.film_grain, mc_identity, bit_depth as u32, fctx, - ) + )) } else { picture }; @@ -838,7 +850,7 @@ pub fn decode_stream_with_threads( } let tx = tx.clone(); let dump = final_dump.clone(); - scope.spawn(move || { + jobs.submit(move || { let promise = produces; let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // The wait happens HERE, off the parsing thread, and only @@ -896,15 +908,15 @@ pub fn decode_stream_with_threads( // reported to the sink clean, exactly as the inline path // below reports it (spec 7.18.3.1). let output = if shown && header.film_grain.apply_grain && !no_grain() { - crate::film_grain::apply_grain( + std::sync::Arc::new(crate::film_grain::apply_grain( &picture, &header.film_grain, seq.mc_identity, u32::from(seq.bit_depth), &fctx, - ) + )) } else { - std::sync::Arc::try_unwrap(picture).unwrap_or_else(|p| (*p).clone()) + picture }; Ok((output, decode_idx, shown)) })) @@ -940,7 +952,7 @@ pub fn decode_stream_with_threads( let snap = RefSnapshot::take( &header, seq, - std::array::from_fn(|i| ref_slots[i].as_ref()), + std::array::from_fn(|i| ref_slots[i].as_deref()), std::array::from_fn(|i| cdf_slots[i].as_ref()), std::array::from_fn(|i| seg_map_slots[i].as_deref()), &std::array::from_fn(|i| motion_field_slots[i].as_ref()), @@ -963,13 +975,16 @@ pub fn decode_stream_with_threads( final_dump.as_deref(), )?; pictures_decoded += 1; + // lane-pool1: one allocation, then every slot store and the output + // itself are refcount bumps instead of plane copies. + let picture = std::sync::Arc::new(picture); if threads > 1 { // lane-thread3: only a key frame reaches this inline path at // `threads > 1`, and the bank it fills is the promise array -- // already resolved, since the picture exists right here. if header.refresh_frame_flags != 0 { let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { - picture: std::sync::Arc::new(picture.clone()), + picture: std::sync::Arc::clone(&picture), cdfs: stored_cdfs, motion_field, seg_map: decoded_seg_map, @@ -990,7 +1005,7 @@ pub fn decode_stream_with_threads( // clean, pre-grain decode, even though the frame pushed // onto the caller's output below carries the grained // picture. - ref_slots[i] = Some(picture.clone()); + ref_slots[i] = Some(std::sync::Arc::clone(&picture)); motion_field_slots[i] = Some(motion_field.clone()); seg_map_slots[i] = Some(decoded_seg_map.clone()); order_hint_slots[i] = header.order_hint; @@ -1007,12 +1022,12 @@ pub fn decode_stream_with_threads( if header.show_frame { let output = if header.film_grain.apply_grain && !no_grain() { let mc_identity = seq.mc_identity; - crate::film_grain::apply_grain( + std::sync::Arc::new(crate::film_grain::apply_grain( &picture, &header.film_grain, mc_identity, bit_depth as u32, fctx, - ) + )) } else { picture }; @@ -1041,7 +1056,6 @@ pub fn decode_stream_with_threads( } debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); Ok(()) - }) }