Merge branch 'lane-pool1' (3362287c): persistent per-thread worker pools replace per-frame and per-tile thread spawns; DPB slots, reorder queue and outputs carry Arc<Picture> instead of copies; byte-exact at every thread setting on four inputs; 4K reaches real time from 12 frame threads (16,2,2 = 27.5 fps)
Browse files at this commit3 changed files +239 -40
- crates/ec-av1/src/decode.rs +15 -11
- crates/ec-av1/src/par.rs +189 -8
- crates/ec-av1/src/stream.rs +35 -21
crates/ec-av1/src/decode.rsmodified+15 -11
| @@ -2425,7 +2425,13 @@ fn wave_worker(st: &WaveState) { | |||
| 2425 | /// Installs the wavefront for one tile and joins its workers on every exit | 2425 | /// Installs the wavefront for one tile and joins its workers on every exit |
| 2426 | /// from the tile decoder, including the `?` ones -- the jobs hold raw | 2426 | /// from the tile decoder, including the `?` ones -- the jobs hold raw |
| 2427 | /// pointers into the tile's planes, so no worker may outlive them. | 2427 | /// pointers into the tile's planes, so no worker may outlive them. |
| 2428 | -pub(crate) struct WaveGuard<'a>(&'a crate::decode::FrameCtx, Vec<std::thread::JoinHandle<()>>); | 2428 | +/// (lane-pool1: the workers come from this thread's persistent pool, so a |
| 2429 | +/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads | ||
| 2430 | +/// with fresh scratch.) | ||
| 2431 | +pub(crate) struct WaveGuard<'a>( | ||
| 2432 | + &'a crate::decode::FrameCtx, | ||
| 2433 | + Option<crate::par::Batch<'static>>, | ||
| 2434 | +); | ||
| 2429 | 2435 | ||
| 2430 | #[allow(unsafe_code)] | 2436 | #[allow(unsafe_code)] |
| 2431 | impl<'a> WaveGuard<'a> { | 2437 | impl<'a> WaveGuard<'a> { |
| @@ -2460,14 +2466,13 @@ impl<'a> WaveGuard<'a> { | |||
| 2460 | enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), | 2466 | enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), |
| 2461 | last_col: cols - 1, | 2467 | last_col: cols - 1, |
| 2462 | }); | 2468 | }); |
| 2463 | - let workers = (0..threads) | 2469 | + let batch = crate::par::Batch::new(); |
| 2464 | - .map(|_| { | 2470 | + for _ in 0..threads { |
| 2465 | - let st = std::sync::Arc::clone(&st); | 2471 | + let st = std::sync::Arc::clone(&st); |
| 2466 | - std::thread::spawn(move || wave_worker(&st)) | 2472 | + batch.submit(move || wave_worker(&st)); |
| 2467 | - }) | 2473 | + } |
| 2468 | - .collect(); | ||
| 2469 | fctx.wave.with(|w| *w.borrow_mut() = Some(st)); | 2474 | fctx.wave.with(|w| *w.borrow_mut() = Some(st)); |
| 2470 | - Some(Self(fctx, workers)) | 2475 | + Some(Self(fctx, Some(batch))) |
| 2471 | } | 2476 | } |
| 2472 | } | 2477 | } |
| 2473 | 2478 | ||
| @@ -2478,9 +2483,8 @@ impl Drop for WaveGuard<'_> { | |||
| 2478 | st.q.lock().unwrap().closed = true; | 2483 | st.q.lock().unwrap().closed = true; |
| 2479 | st.cv.notify_all(); | 2484 | st.cv.notify_all(); |
| 2480 | } | 2485 | } |
| 2481 | - for h in self.1.drain(..) { | 2486 | + // Dropping the batch waits every worker out, as the joins did. |
| 2482 | - let _ = h.join(); | 2487 | + drop(self.1.take()); |
| 2483 | - } | ||
| 2484 | } | 2488 | } |
| 2485 | } | 2489 | } |
| 2486 | 2490 | ||
crates/ec-av1/src/par.rsmodified+189 -8
| @@ -122,14 +122,17 @@ where | |||
| 122 | [] => {} | 122 | [] => {} |
| 123 | [(a, b)] => f(*a, *b, fctx), | 123 | [(a, b)] => f(*a, *b, fctx), |
| 124 | [(a0, b0), rest @ ..] => { | 124 | [(a0, b0), rest @ ..] => { |
| 125 | - std::thread::scope(|s| { | 125 | + // lane-pool1: same shape as the `thread::scope` this replaced -- |
| 126 | - for &(a, b) in rest { | 126 | + // band 0 inline, the rest on this thread's persistent pool, all |
| 127 | - let ctx = crate::decode::filter_ctx_copy(fctx); | 127 | + // waited out by `batch`'s drop at the end of the block. |
| 128 | - let f = &f; | 128 | + let batch = Batch::new(); |
| 129 | - s.spawn(move || f(a, b, &ctx)); | 129 | + for &(a, b) in rest { |
| 130 | - } | 130 | + let ctx = crate::decode::filter_ctx_copy(fctx); |
| 131 | - f(*a0, *b0, fctx); | 131 | + let f = &f; |
| 132 | - }); | 132 | + batch.submit(move || f(a, b, &ctx)); |
| 133 | + } | ||
| 134 | + f(*a0, *b0, fctx); | ||
| 135 | + drop(batch); | ||
| 133 | } | 136 | } |
| 134 | } | 137 | } |
| 135 | } | 138 | } |
| @@ -161,3 +164,181 @@ pub(crate) fn recon_threads() -> usize { | |||
| 161 | pub(crate) fn set_recon_threads(n: usize) { | 164 | pub(crate) fn set_recon_threads(n: usize) { |
| 162 | RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); | 165 | RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); |
| 163 | } | 166 | } |
| 167 | + | ||
| 168 | +// --- lane-pool1: persistent worker pools --------------------------------- | ||
| 169 | +// | ||
| 170 | +// Every threaded stage of the decoder used to spawn its threads per unit of | ||
| 171 | +// work: one `thread::scope` per filter STAGE per frame, `EC_AV1_RECON_THREADS` | ||
| 172 | +// workers per TILE, one frame worker per coded frame -- 2363 distinct threads | ||
| 173 | +// in a 13 s 4K decode. The cost is not the clone of the thread itself but what | ||
| 174 | +// dies with it: every `thread_local!` scratch pool in `decode.rs` (planes, | ||
| 175 | +// rows, dq, mc, wiener, sgr) is allocated and faulted in again on each new | ||
| 176 | +// thread, which is where the 3.65 M page faults and the 2.7x malloc traffic of | ||
| 177 | +// the composed setting came from. | ||
| 178 | +// | ||
| 179 | +// The replacement is one pool per POOL-OWNING THREAD, kept in a thread-local | ||
| 180 | +// and joined when that thread exits: a stage submits a [`Batch`] of jobs, the | ||
| 181 | +// pool hands each to an idle worker (growing to `busy + queued` so a job never | ||
| 182 | +// queues behind a blocking one -- the recon wavefront's workers block on their | ||
| 183 | +// dependencies), and the batch's `Drop` waits every job out. Scratch then | ||
| 184 | +// lives as long as the worker, not as long as the frame. | ||
| 185 | +type Job = Box<dyn FnOnce() + Send + 'static>; | ||
| 186 | + | ||
| 187 | +struct PoolQ { | ||
| 188 | + jobs: std::collections::VecDeque<Job>, | ||
| 189 | + /// Jobs handed to a worker and not yet finished. | ||
| 190 | + busy: usize, | ||
| 191 | + closed: bool, | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +struct PoolInner { | ||
| 195 | + q: std::sync::Mutex<PoolQ>, | ||
| 196 | + cv: std::sync::Condvar, | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +struct Pool { | ||
| 200 | + inner: std::sync::Arc<PoolInner>, | ||
| 201 | + handles: Vec<std::thread::JoinHandle<()>>, | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +fn pool_worker(inner: &PoolInner) { | ||
| 205 | + let mut q = inner.q.lock().unwrap(); | ||
| 206 | + loop { | ||
| 207 | + if let Some(job) = q.jobs.pop_front() { | ||
| 208 | + q.busy += 1; | ||
| 209 | + drop(q); | ||
| 210 | + // A job's own panic is captured by the batch wrapper below, so | ||
| 211 | + // this only guards against a wrapper that itself unwinds. | ||
| 212 | + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); | ||
| 213 | + q = inner.q.lock().unwrap(); | ||
| 214 | + q.busy -= 1; | ||
| 215 | + continue; | ||
| 216 | + } | ||
| 217 | + if q.closed { | ||
| 218 | + return; | ||
| 219 | + } | ||
| 220 | + q = inner.cv.wait(q).unwrap(); | ||
| 221 | + } | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +impl Pool { | ||
| 225 | + fn new() -> Self { | ||
| 226 | + Self { | ||
| 227 | + inner: std::sync::Arc::new(PoolInner { | ||
| 228 | + q: std::sync::Mutex::new(PoolQ { | ||
| 229 | + jobs: std::collections::VecDeque::new(), | ||
| 230 | + busy: 0, | ||
| 231 | + closed: false, | ||
| 232 | + }), | ||
| 233 | + cv: std::sync::Condvar::new(), | ||
| 234 | + }), | ||
| 235 | + handles: Vec::new(), | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + /// Queues `job` and makes sure a worker is free for it: the pool grows to | ||
| 240 | + /// `busy + queued` threads and never shrinks, so a submitted job always | ||
| 241 | + /// starts, even when every other running job is blocked waiting for it. | ||
| 242 | + fn push(&mut self, job: Job) { | ||
| 243 | + let want = { | ||
| 244 | + let mut q = self.inner.q.lock().unwrap(); | ||
| 245 | + q.jobs.push_back(job); | ||
| 246 | + q.busy + q.jobs.len() | ||
| 247 | + }; | ||
| 248 | + while self.handles.len() < want { | ||
| 249 | + let inner = std::sync::Arc::clone(&self.inner); | ||
| 250 | + self.handles | ||
| 251 | + .push(std::thread::spawn(move || pool_worker(&inner))); | ||
| 252 | + } | ||
| 253 | + self.inner.cv.notify_one(); | ||
| 254 | + } | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +impl Drop for Pool { | ||
| 258 | + fn drop(&mut self) { | ||
| 259 | + self.inner.q.lock().unwrap().closed = true; | ||
| 260 | + self.inner.cv.notify_all(); | ||
| 261 | + for h in self.handles.drain(..) { | ||
| 262 | + let _ = h.join(); | ||
| 263 | + } | ||
| 264 | + } | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +thread_local! { | ||
| 268 | + /// This thread's pool, created on its first [`Batch::submit`] and joined | ||
| 269 | + /// when the thread exits (the process's main thread may skip that | ||
| 270 | + /// destructor, in which case the idle workers die with the process). | ||
| 271 | + static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) }; | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +struct BatchState { | ||
| 275 | + left: std::sync::Mutex<usize>, | ||
| 276 | + cv: std::sync::Condvar, | ||
| 277 | + panic: std::sync::Mutex<Option<Box<dyn std::any::Any + Send>>>, | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +/// A set of jobs running on the submitting thread's pool. `Drop` waits for | ||
| 281 | +/// every one of them and re-raises the first panic, which is what makes | ||
| 282 | +/// [`Batch::submit`]'s borrow of non-`'static` data sound -- exactly | ||
| 283 | +/// `thread::scope`'s contract, minus the spawns. | ||
| 284 | +/// | ||
| 285 | +/// corner-cut: soundness rests on this `Drop` running; `std::mem::forget` of a | ||
| 286 | +/// `Batch` would let a job outlive its borrows. The type is crate-private and | ||
| 287 | +/// every construction site below binds it to a local. Upgrade path is the | ||
| 288 | +/// closure-taking `scope(|s| ...)` shape, which costs every caller a level of | ||
| 289 | +/// indentation for the same guarantee. | ||
| 290 | +pub(crate) struct Batch<'a> { | ||
| 291 | + st: std::sync::Arc<BatchState>, | ||
| 292 | + _p: std::marker::PhantomData<&'a ()>, | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +impl<'a> Batch<'a> { | ||
| 296 | + pub(crate) fn new() -> Self { | ||
| 297 | + Self { | ||
| 298 | + st: std::sync::Arc::new(BatchState { | ||
| 299 | + left: std::sync::Mutex::new(0), | ||
| 300 | + cv: std::sync::Condvar::new(), | ||
| 301 | + panic: std::sync::Mutex::new(None), | ||
| 302 | + }), | ||
| 303 | + _p: std::marker::PhantomData, | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + | ||
| 307 | + pub(crate) fn submit<F: FnOnce() + Send + 'a>(&self, f: F) { | ||
| 308 | + *self.st.left.lock().unwrap() += 1; | ||
| 309 | + let st = std::sync::Arc::clone(&self.st); | ||
| 310 | + let job: Box<dyn FnOnce() + Send + 'a> = Box::new(move || { | ||
| 311 | + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); | ||
| 312 | + if let Err(p) = r { | ||
| 313 | + let mut slot = st.panic.lock().unwrap(); | ||
| 314 | + if slot.is_none() { | ||
| 315 | + *slot = Some(p); | ||
| 316 | + } | ||
| 317 | + } | ||
| 318 | + let mut left = st.left.lock().unwrap(); | ||
| 319 | + *left -= 1; | ||
| 320 | + st.cv.notify_all(); | ||
| 321 | + }); | ||
| 322 | + // SAFETY: the job is dropped before `Batch::drop` returns (it waits | ||
| 323 | + // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the | ||
| 324 | + // laundered lifetime is never observed past the real one. | ||
| 325 | + let job: Job = unsafe { std::mem::transmute::<Box<dyn FnOnce() + Send + 'a>, Job>(job) }; | ||
| 326 | + POOL.with(|p| { | ||
| 327 | + let mut p = p.borrow_mut(); | ||
| 328 | + p.get_or_insert_with(Pool::new).push(job); | ||
| 329 | + }); | ||
| 330 | + } | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +impl Drop for Batch<'_> { | ||
| 334 | + fn drop(&mut self) { | ||
| 335 | + let mut left = self.st.left.lock().unwrap(); | ||
| 336 | + while *left > 0 { | ||
| 337 | + left = self.st.cv.wait(left).unwrap(); | ||
| 338 | + } | ||
| 339 | + drop(left); | ||
| 340 | + if let Some(p) = self.st.panic.lock().unwrap().take() { | ||
| 341 | + std::panic::resume_unwind(p); | ||
| 342 | + } | ||
| 343 | + } | ||
| 344 | +} | ||
crates/ec-av1/src/stream.rsmodified+35 -21
| @@ -296,11 +296,15 @@ fn decode_threads() -> usize { | |||
| 296 | #[derive(Default)] | 296 | #[derive(Default)] |
| 297 | struct Reorder { | 297 | struct Reorder { |
| 298 | next: usize, | 298 | next: usize, |
| 299 | - pending: std::collections::BTreeMap<usize, (Picture, usize, bool)>, | 299 | + // lane-pool1: the picture is shared, not owned -- a decoded frame that |
| 300 | + // refreshes a reference slot is already behind an `Arc` for the slot, and | ||
| 301 | + // handing the output an owned `Picture` meant copying every plane of it | ||
| 302 | + // (24 MB per 4K 10-bit frame) purely to put it in this queue. | ||
| 303 | + pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>, | ||
| 300 | } | 304 | } |
| 301 | 305 | ||
| 302 | impl Reorder { | 306 | impl Reorder { |
| 303 | - fn push(&mut self, seq: usize, picture: Picture, decode_idx: usize, shown: bool) { | 307 | + fn push(&mut self, seq: usize, picture: std::sync::Arc<Picture>, decode_idx: usize, shown: bool) { |
| 304 | self.pending.insert(seq, (picture, decode_idx, shown)); | 308 | self.pending.insert(seq, (picture, decode_idx, shown)); |
| 305 | } | 309 | } |
| 306 | 310 | ||
| @@ -431,7 +435,7 @@ impl SlotPromise { | |||
| 431 | /// against separate in-flight bounds, since a waiting output job costs no | 435 | /// against separate in-flight bounds, since a waiting output job costs no |
| 432 | /// CPU), and either the (grain-synthesised) picture with the decode index to | 436 | /// CPU), and either the (grain-synthesised) picture with the decode index to |
| 433 | /// report or the error that aborts the stream. | 437 | /// report or the error that aborts the stream. |
| 434 | -type LeafResult = (usize, bool, Result<(Picture, usize, bool)>); | 438 | +type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>); |
| 435 | 439 | ||
| 436 | /// Waits for one in-flight job and emits whatever that unblocks. | 440 | /// Waits for one in-flight job and emits whatever that unblocks. |
| 437 | fn collect_one( | 441 | fn collect_one( |
| @@ -478,7 +482,12 @@ pub fn decode_stream_with_threads( | |||
| 478 | threads: usize, | 482 | threads: usize, |
| 479 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, | 483 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, |
| 480 | ) -> Result<()> { | 484 | ) -> Result<()> { |
| 481 | - std::thread::scope(|scope| { | 485 | + // lane-pool1: this replaced a `std::thread::scope` -- frame workers now |
| 486 | + // come from a persistent pool (one per submitting thread, workers reused | ||
| 487 | + // across frames, so their `thread_local!` decode scratch survives the | ||
| 488 | + // frame). `jobs` is declared here and dropped at the end of the function, | ||
| 489 | + // including on `?`, so no job outlives the data it borrows. | ||
| 490 | + let jobs = crate::par::Batch::new(); | ||
| 482 | // lane-thread1: this stream's per-frame decode state (was 38 thread_local | 491 | // lane-thread1: this stream's per-frame decode state (was 38 thread_local |
| 483 | // statics in decode.rs) -- one object, threaded down the decode call graph. | 492 | // statics in decode.rs) -- one object, threaded down the decode call graph. |
| 484 | let fctx = &crate::decode::FrameCtx::new(); | 493 | let fctx = &crate::decode::FrameCtx::new(); |
| @@ -498,7 +507,10 @@ pub fn decode_stream_with_threads( | |||
| 498 | // luma-only (chroma coincidentally shares this fixture's flat regions) | 507 | // luma-only (chroma coincidentally shares this fixture's flat regions) |
| 499 | // and small-magnitude (the two pictures mostly agree), which is exactly | 508 | // and small-magnitude (the two pictures mostly agree), which is exactly |
| 500 | // what made it look like a rounding bug rather than a wrong reference. | 509 | // what made it look like a rounding bug rather than a wrong reference. |
| 501 | - let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); | 510 | + // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy |
| 511 | + // its whole picture k times, and its output a (k+1)-th time. | ||
| 512 | + let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] = | ||
| 513 | + std::array::from_fn(|_| None); | ||
| 502 | // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion | 514 | // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion |
| 503 | // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom | 515 | // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom |
| 504 | // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was | 516 | // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was |
| @@ -617,19 +629,19 @@ pub fn decode_stream_with_threads( | |||
| 617 | let grain = header.film_grain; | 629 | let grain = header.film_grain; |
| 618 | let seq = SeqFlags::read(&parser); | 630 | let seq = SeqFlags::read(&parser); |
| 619 | let tx = tx.clone(); | 631 | let tx = tx.clone(); |
| 620 | - scope.spawn(move || { | 632 | + jobs.submit(move || { |
| 621 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | 633 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 622 | let value = promise.wait()?; | 634 | let value = promise.wait()?; |
| 623 | let output = if grain.apply_grain && !no_grain() { | 635 | let output = if grain.apply_grain && !no_grain() { |
| 624 | - crate::film_grain::apply_grain( | 636 | + std::sync::Arc::new(crate::film_grain::apply_grain( |
| 625 | &value.picture, | 637 | &value.picture, |
| 626 | &grain, | 638 | &grain, |
| 627 | seq.mc_identity, | 639 | seq.mc_identity, |
| 628 | u32::from(seq.bit_depth), | 640 | u32::from(seq.bit_depth), |
| 629 | &crate::decode::FrameCtx::new(), | 641 | &crate::decode::FrameCtx::new(), |
| 630 | - ) | 642 | + )) |
| 631 | } else { | 643 | } else { |
| 632 | - value.picture.as_ref().clone() | 644 | + std::sync::Arc::clone(&value.picture) |
| 633 | }; | 645 | }; |
| 634 | Ok((output, decode_idx, true)) | 646 | Ok((output, decode_idx, true)) |
| 635 | })) | 647 | })) |
| @@ -675,12 +687,12 @@ pub fn decode_stream_with_threads( | |||
| 675 | let mc_identity = parser | 687 | let mc_identity = parser |
| 676 | .sequence_header() | 688 | .sequence_header() |
| 677 | .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); | 689 | .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); |
| 678 | - crate::film_grain::apply_grain( | 690 | + std::sync::Arc::new(crate::film_grain::apply_grain( |
| 679 | &picture, | 691 | &picture, |
| 680 | &header.film_grain, | 692 | &header.film_grain, |
| 681 | mc_identity, | 693 | mc_identity, |
| 682 | bit_depth as u32, fctx, | 694 | bit_depth as u32, fctx, |
| 683 | - ) | 695 | + )) |
| 684 | } else { | 696 | } else { |
| 685 | picture | 697 | picture |
| 686 | }; | 698 | }; |
| @@ -838,7 +850,7 @@ pub fn decode_stream_with_threads( | |||
| 838 | } | 850 | } |
| 839 | let tx = tx.clone(); | 851 | let tx = tx.clone(); |
| 840 | let dump = final_dump.clone(); | 852 | let dump = final_dump.clone(); |
| 841 | - scope.spawn(move || { | 853 | + jobs.submit(move || { |
| 842 | let promise = produces; | 854 | let promise = produces; |
| 843 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | 855 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 844 | // The wait happens HERE, off the parsing thread, and only | 856 | // The wait happens HERE, off the parsing thread, and only |
| @@ -896,15 +908,15 @@ pub fn decode_stream_with_threads( | |||
| 896 | // reported to the sink clean, exactly as the inline path | 908 | // reported to the sink clean, exactly as the inline path |
| 897 | // below reports it (spec 7.18.3.1). | 909 | // below reports it (spec 7.18.3.1). |
| 898 | let output = if shown && header.film_grain.apply_grain && !no_grain() { | 910 | let output = if shown && header.film_grain.apply_grain && !no_grain() { |
| 899 | - crate::film_grain::apply_grain( | 911 | + std::sync::Arc::new(crate::film_grain::apply_grain( |
| 900 | &picture, | 912 | &picture, |
| 901 | &header.film_grain, | 913 | &header.film_grain, |
| 902 | seq.mc_identity, | 914 | seq.mc_identity, |
| 903 | u32::from(seq.bit_depth), | 915 | u32::from(seq.bit_depth), |
| 904 | &fctx, | 916 | &fctx, |
| 905 | - ) | 917 | + )) |
| 906 | } else { | 918 | } else { |
| 907 | - std::sync::Arc::try_unwrap(picture).unwrap_or_else(|p| (*p).clone()) | 919 | + picture |
| 908 | }; | 920 | }; |
| 909 | Ok((output, decode_idx, shown)) | 921 | Ok((output, decode_idx, shown)) |
| 910 | })) | 922 | })) |
| @@ -940,7 +952,7 @@ pub fn decode_stream_with_threads( | |||
| 940 | let snap = RefSnapshot::take( | 952 | let snap = RefSnapshot::take( |
| 941 | &header, | 953 | &header, |
| 942 | seq, | 954 | seq, |
| 943 | - std::array::from_fn(|i| ref_slots[i].as_ref()), | 955 | + std::array::from_fn(|i| ref_slots[i].as_deref()), |
| 944 | std::array::from_fn(|i| cdf_slots[i].as_ref()), | 956 | std::array::from_fn(|i| cdf_slots[i].as_ref()), |
| 945 | std::array::from_fn(|i| seg_map_slots[i].as_deref()), | 957 | std::array::from_fn(|i| seg_map_slots[i].as_deref()), |
| 946 | &std::array::from_fn(|i| motion_field_slots[i].as_ref()), | 958 | &std::array::from_fn(|i| motion_field_slots[i].as_ref()), |
| @@ -963,13 +975,16 @@ pub fn decode_stream_with_threads( | |||
| 963 | final_dump.as_deref(), | 975 | final_dump.as_deref(), |
| 964 | )?; | 976 | )?; |
| 965 | pictures_decoded += 1; | 977 | pictures_decoded += 1; |
| 978 | + // lane-pool1: one allocation, then every slot store and the output | ||
| 979 | + // itself are refcount bumps instead of plane copies. | ||
| 980 | + let picture = std::sync::Arc::new(picture); | ||
| 966 | if threads > 1 { | 981 | if threads > 1 { |
| 967 | // lane-thread3: only a key frame reaches this inline path at | 982 | // lane-thread3: only a key frame reaches this inline path at |
| 968 | // `threads > 1`, and the bank it fills is the promise array -- | 983 | // `threads > 1`, and the bank it fills is the promise array -- |
| 969 | // already resolved, since the picture exists right here. | 984 | // already resolved, since the picture exists right here. |
| 970 | if header.refresh_frame_flags != 0 { | 985 | if header.refresh_frame_flags != 0 { |
| 971 | let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { | 986 | let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { |
| 972 | - picture: std::sync::Arc::new(picture.clone()), | 987 | + picture: std::sync::Arc::clone(&picture), |
| 973 | cdfs: stored_cdfs, | 988 | cdfs: stored_cdfs, |
| 974 | motion_field, | 989 | motion_field, |
| 975 | seg_map: decoded_seg_map, | 990 | seg_map: decoded_seg_map, |
| @@ -990,7 +1005,7 @@ pub fn decode_stream_with_threads( | |||
| 990 | // clean, pre-grain decode, even though the frame pushed | 1005 | // clean, pre-grain decode, even though the frame pushed |
| 991 | // onto the caller's output below carries the grained | 1006 | // onto the caller's output below carries the grained |
| 992 | // picture. | 1007 | // picture. |
| 993 | - ref_slots[i] = Some(picture.clone()); | 1008 | + ref_slots[i] = Some(std::sync::Arc::clone(&picture)); |
| 994 | motion_field_slots[i] = Some(motion_field.clone()); | 1009 | motion_field_slots[i] = Some(motion_field.clone()); |
| 995 | seg_map_slots[i] = Some(decoded_seg_map.clone()); | 1010 | seg_map_slots[i] = Some(decoded_seg_map.clone()); |
| 996 | order_hint_slots[i] = header.order_hint; | 1011 | order_hint_slots[i] = header.order_hint; |
| @@ -1007,12 +1022,12 @@ pub fn decode_stream_with_threads( | |||
| 1007 | if header.show_frame { | 1022 | if header.show_frame { |
| 1008 | let output = if header.film_grain.apply_grain && !no_grain() { | 1023 | let output = if header.film_grain.apply_grain && !no_grain() { |
| 1009 | let mc_identity = seq.mc_identity; | 1024 | let mc_identity = seq.mc_identity; |
| 1010 | - crate::film_grain::apply_grain( | 1025 | + std::sync::Arc::new(crate::film_grain::apply_grain( |
| 1011 | &picture, | 1026 | &picture, |
| 1012 | &header.film_grain, | 1027 | &header.film_grain, |
| 1013 | mc_identity, | 1028 | mc_identity, |
| 1014 | bit_depth as u32, fctx, | 1029 | bit_depth as u32, fctx, |
| 1015 | - ) | 1030 | + )) |
| 1016 | } else { | 1031 | } else { |
| 1017 | picture | 1032 | picture |
| 1018 | }; | 1033 | }; |
| @@ -1041,7 +1056,6 @@ pub fn decode_stream_with_threads( | |||
| 1041 | } | 1056 | } |
| 1042 | debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); | 1057 | debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); |
| 1043 | Ok(()) | 1058 | Ok(()) |
| 1044 | - }) | ||
| 1045 | } | 1059 | } |
| 1046 | 1060 | ||
| 1047 | 1061 | ||