forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

par.rs731 lines, 28.0 KiBHistoryRawDownload
1//! lane-filt1: in-frame parallelism for the post-decode filter chain
2//! (deblock, CDEF, loop restoration, film grain).
3//!
4//! Every stage here is split along an axis whose per-band writes are
5//! *disjoint* and whose reads come either from an immutable snapshot or from
6//! the band's own pixels, so N bands reproduce the single-threaded output
7//! byte for byte -- gated by
8//! `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
9//!
10//! Threading is opt-in: [`filter_threads`] is 1 unless `EC_AV1_FILTER_THREADS`
11//! says otherwise, and at 1 band nothing is spawned at all (the work runs on
12//! the calling thread, so every `thread_local!` gate counter in `decode.rs`
13//! still sees it). Above 1, a worker's counter increments are lost -- which is
14//! why the default stays 1 and every existing gate is unaffected. The knob
15//! composes multiplicatively with `EC_AV1_THREADS` (frame workers), so the
16//! product of the two is what must stay inside the core count.
17//!
18//! Measured on a 12-core box, `seg4k` (272 shown frames, interleaved medians
19//! of 3, other lanes decoding alongside): 34.41 s at 1 filter thread, 30.04 s
20//! at 2, 28.41 s at 4, 28.36 s at 6, 27.70 s at 8 -- i.e. the filter chain is
21//! ~19% of frame time and 4 threads take most of what is there. Recommended:
22//! `EC_AV1_FILTER_THREADS=4` with frame threading off, and the product with
23//! `EC_AV1_THREADS` kept at or below the core count once it lands (e.g. 2
24//! frame workers x 4 filter threads on 12 cores).
25
26/// `EC_AV1_FILTER_THREADS`, the number of worker threads each in-frame filter
27/// stage splits itself across (default 1 = single-threaded, the shipped
28/// behaviour). Read once per process.
29/// 0 = "not read yet"; the env read happens once and the value is a plain
30/// atomic afterwards, so a test can flip it ([`set_filter_threads`]) without
31/// touching the process environment.
32static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
33
34thread_local! {
35 /// This thread's override of [`filter_threads`], 0 = none. The ENCODER's
36 /// frame-level filter search sets it for the span of that search
37 /// (lane-av1fpar): the tile search is over by then, so every core is
38 /// free, and each candidate's deblock/CDEF replay is exactly the banded
39 /// stage the decoder already splits -- same bands, same byte-exact
40 /// output, gated by
41 /// `a_real_stream_filters_identically_with_one_and_four_filter_threads`
42 /// on the decode side and by
43 /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count` here.
44 static FILTER_BANDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
45}
46
47/// Restores the previous [`FILTER_BANDS`] override when it drops.
48pub(crate) struct FilterBands(usize);
49
50impl Drop for FilterBands {
51 fn drop(&mut self) {
52 FILTER_BANDS.set(self.0);
53 }
54}
55
56/// Bands every filter stage on THIS thread across `n` workers until the
57/// returned guard drops; `n <= 1` leaves the process default in place.
58pub(crate) fn override_filter_threads(n: usize) -> FilterBands {
59 let previous = FILTER_BANDS.replace(if n > 1 { n.clamp(1, 64) } else { 0 });
60 FilterBands(previous)
61}
62
63pub(crate) fn filter_threads() -> usize {
64 let over = FILTER_BANDS.get();
65 if over > 0 {
66 return over;
67 }
68 match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
69 0 => {
70 let n = crate::envflags::var("EC_AV1_FILTER_THREADS")
71 .ok()
72 .and_then(|v| v.trim().parse::<usize>().ok())
73 .map(|n| n.clamp(1, 64));
74 // lane-av1recon: an unset env falls through to the split the
75 // running decode picked ([`DecodeSplit`]); only a set value (or a
76 // test override) is cached.
77 match n {
78 Some(n) => {
79 FILTER_THREADS.store(n, std::sync::atomic::Ordering::Relaxed);
80 n
81 }
82 None => AUTO_FILTER.load(std::sync::atomic::Ordering::Relaxed),
83 }
84 }
85 n => n,
86 }
87}
88
89/// Test-only override of [`filter_threads`]. Process-global, so a gate using
90/// it must hold `stream.rs`'s gate-counter lock (which also keeps the
91/// counter-delta gates from decoding while the workers are on).
92#[cfg(test)]
93pub(crate) fn set_filter_threads(n: usize) {
94 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
95}
96
97/// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
98/// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the
99/// entropy WRITE (`encode::write_tiles`); default 1 = the shipped
100/// single-threaded encode. Tiles are independent by construction (each starts
101/// from the frame's own tables, resets its own contexts, and reads no sample
102/// and no mode outside its own rectangle), so the bytes a frame comes out as
103/// do not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_
104/// thread_count` is the pin.
105///
106/// Measured (lane-av1tsearch, 12-core box, best of two interleaved passes):
107/// 1920x1080, 12 frames -- 11.49 s at one tile (any thread count), 6.98 s at
108/// 4x2 tiles and 8 threads (1.65x, 1.04 -> 1.72 fps); 3840x1608, 6 frames --
109/// 17.12 s at 4x2 tiles and one thread, 8.64 s at 8 (1.98x, 0.35 -> 0.69
110/// fps). Past ~8 tiles the extra tiles cost bytes without buying wall: what
111/// is left is the per-frame serial tail (the filter search re-decodes the
112/// whole frame), ~43% of an inter frame by Amdahl on those numbers.
113static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
114
115pub(crate) fn tile_threads() -> usize {
116 match TILE_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
117 0 => {
118 let n = crate::envflags::var("EC_AV1_TILE_THREADS")
119 .ok()
120 .and_then(|v| v.trim().parse::<usize>().ok())
121 .unwrap_or(1)
122 .clamp(1, 64);
123 TILE_THREADS.store(n, std::sync::atomic::Ordering::Relaxed);
124 n
125 }
126 n => n,
127 }
128}
129
130/// Test-only override of [`tile_threads`]; see [`set_filter_threads`].
131#[cfg(test)]
132pub(crate) fn set_tile_threads(n: usize) {
133 TILE_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
134}
135
136/// Splits `units` work units into at most `threads` contiguous, non-empty
137/// bands. The caller picks the unit so that a band boundary is always a legal
138/// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one
139/// restoration-unit row for LR, one 32-pixel block row for film grain).
140pub(crate) fn bands(units: usize, threads: usize) -> Vec<(usize, usize)> {
141 if units == 0 {
142 return Vec::new();
143 }
144 let t = threads.clamp(1, units);
145 let per = units.div_ceil(t);
146 (0..t)
147 .map(|i| (i * per, ((i + 1) * per).min(units)))
148 .filter(|(a, b)| a < b)
149 .collect()
150}
151
152/// Runs `f(lo, hi, slice, ctx)` once per band, band 0 on this thread and the
153/// rest on scoped threads, all joined before the call returns. Band `(lo, hi)`
154/// gets `data[lo * unit..hi * unit]` as its own `&mut` slice, carved with
155/// `split_at_mut`, so no `unsafe` and no shared `&mut` is needed. `bands` must
156/// be ascending and non-overlapping, and `hi * unit` must fit in `data`.
157#[inline]
158pub(crate) fn run_bands_mut<T, F>(
159 bands: &[(usize, usize)],
160 unit: usize,
161 fctx: &crate::decode::FrameCtx,
162 data: &mut [T],
163 f: F,
164) where
165 T: Send,
166 F: Fn(usize, usize, &mut [T], &crate::decode::FrameCtx) + Sync,
167{
168 let mut slices = Vec::with_capacity(bands.len());
169 let mut rest = data;
170 let mut pos = 0;
171 for &(lo, hi) in bands {
172 let (_, tail) = rest.split_at_mut((lo * unit) - pos);
173 let (mine, after) = tail.split_at_mut((hi - lo) * unit);
174 slices.push((lo, hi, mine));
175 pos = hi * unit;
176 rest = after;
177 }
178 let mut it = slices.into_iter();
179 let Some((a0, b0, first)) = it.next() else {
180 return;
181 };
182 if bands.len() == 1 {
183 f(a0, b0, first, fctx);
184 return;
185 }
186 scope("ec-av1-filter", |batch| {
187 for (a, b, mine) in it {
188 let ctx = crate::decode::filter_ctx_copy(fctx);
189 let f = &f;
190 batch.submit(move || f(a, b, mine, &ctx));
191 }
192 f(a0, b0, first, fctx);
193 });
194}
195
196/// Carves `data` into one `&mut` slice per element range, `ranges` ascending
197/// and non-overlapping (`split_at_mut` only, so no `unsafe`). Elements outside
198/// every range are left alone.
199pub(crate) fn carve_ranges<'a, T>(data: &'a mut [T], ranges: &[(usize, usize)]) -> Vec<&'a mut [T]> {
200 split_bands_mut(ranges, 1, data)
201}
202
203/// Carves `data` into the slices [`run_bands_mut`] hands out, without running
204/// anything: band `(lo, hi)` is `data[lo * unit..hi * unit]`. `bands` must be
205/// ascending and non-overlapping.
206#[inline]
207pub(crate) fn split_bands_mut<'a, T>(
208 bands: &[(usize, usize)],
209 unit: usize,
210 data: &'a mut [T],
211) -> Vec<&'a mut [T]> {
212 let mut out = Vec::with_capacity(bands.len());
213 let mut rest: &'a mut [T] = data;
214 let mut pos = 0;
215 for &(lo, hi) in bands {
216 let (_, tail) = std::mem::take(&mut rest).split_at_mut((lo * unit) - pos);
217 let (mine, after) = tail.split_at_mut((hi - lo) * unit);
218 out.push(mine);
219 pos = hi * unit;
220 rest = after;
221 }
222 out
223}
224
225/// [`run_bands_mut`] where band `i` also gets its own payload `parts[i]`
226/// (moved in, so a caller can hand each band the disjoint `&mut` slices
227/// [`carve_ranges`] made). `parts` is in the same order as `bands`.
228#[inline]
229pub(crate) fn run_bands_with<P, F>(
230 bands: &[(usize, usize)],
231 parts: Vec<P>,
232 fctx: &crate::decode::FrameCtx,
233 f: F,
234) where
235 P: Send,
236 F: Fn(usize, usize, P, &crate::decode::FrameCtx) + Sync,
237{
238 debug_assert_eq!(bands.len(), parts.len());
239 let mut it = bands.iter().zip(parts);
240 let Some(((a0, b0), first)) = it.next() else {
241 return;
242 };
243 if bands.len() == 1 {
244 f(*a0, *b0, first, fctx);
245 return;
246 }
247 scope("ec-av1-filter", |batch| {
248 for (&(a, b), p) in it {
249 let ctx = crate::decode::filter_ctx_copy(fctx);
250 let f = &f;
251 batch.submit(move || f(a, b, p, &ctx));
252 }
253 f(*a0, *b0, first, fctx);
254 });
255}
256
257/// [`run_bands_mut`] for parts the caller has already carved, each one holding
258/// its own `&mut` views: `f` runs once per part, part 0 inline and the rest on
259/// the scope's threads, the same shape as [`run_bands_mut`].
260#[inline]
261pub(crate) fn run_parts_mut<S, F>(parts: &mut [S], fctx: &crate::decode::FrameCtx, f: F)
262where
263 S: Send,
264 F: Fn(&mut S, &crate::decode::FrameCtx) + Sync,
265{
266 let Some((first, rest)) = parts.split_first_mut() else {
267 return;
268 };
269 if rest.is_empty() {
270 f(first, fctx);
271 return;
272 }
273 scope("ec-av1-filter", |batch| {
274 for part in rest.iter_mut() {
275 let ctx = crate::decode::filter_ctx_copy(fctx);
276 let f = &f;
277 batch.submit(move || f(part, &ctx));
278 }
279 f(first, fctx);
280 });
281}
282
283/// lane-av1recon: the in-frame thread split a decode at `EC_AV1_THREADS > 1`
284/// picked ([`crate::autothreads::split`]), used only while the matching env
285/// variable is unset. 1 = serial, which is what everything outside a threaded
286/// `decode_stream_with_threads` call (the encoder's own decodes, the gates)
287/// sees.
288static AUTO_RECON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
289static AUTO_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
290
291/// Holds the default in-frame split for the span of one threaded decode and
292/// restores the previous one on drop.
293pub(crate) struct DecodeSplit(usize, usize);
294
295impl DecodeSplit {
296 /// Installs the split [`crate::autothreads::split`] picks for `threads`
297 /// decode threads. Does nothing in the crate's own test build, where the
298 /// gates read thread-local counters the in-frame workers never touch (a
299 /// test forces the knobs through the env).
300 pub(crate) fn install(threads: usize) -> Self {
301 use std::sync::atomic::Ordering::Relaxed;
302 let prev = Self(AUTO_RECON.load(Relaxed), AUTO_FILTER.load(Relaxed));
303 if !cfg!(test) {
304 let (r, f) = crate::autothreads::split(threads);
305 AUTO_RECON.store(r, Relaxed);
306 AUTO_FILTER.store(f, Relaxed);
307 }
308 prev
309 }
310}
311
312impl Drop for DecodeSplit {
313 fn drop(&mut self) {
314 use std::sync::atomic::Ordering::Relaxed;
315 AUTO_RECON.store(self.0, Relaxed);
316 AUTO_FILTER.store(self.1, Relaxed);
317 }
318}
319
320/// The superblock-row reconstruction workers per tile ([`crate::decode::wave`]).
321static RECON_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
322
323/// The recon thread count: `EC_AV1_RECON_THREADS` when set, else the split a
324/// threaded decode installed ([`DecodeSplit`]). 1 means inline reconstruction.
325pub(crate) fn recon_threads() -> usize {
326 match RECON_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
327 0 => {
328 let n = crate::envflags::var("EC_AV1_RECON_THREADS")
329 .ok()
330 .and_then(|v| v.trim().parse::<usize>().ok())
331 .map(|n| n.clamp(1, 64));
332 match n {
333 Some(n) => {
334 RECON_THREADS.store(n, std::sync::atomic::Ordering::Relaxed);
335 n
336 }
337 None => AUTO_RECON.load(std::sync::atomic::Ordering::Relaxed),
338 }
339 }
340 n => n,
341 }
342}
343
344/// Test-only override of [`recon_threads`] -- see [`set_filter_threads`].
345#[cfg(test)]
346pub(crate) fn set_recon_threads(n: usize) {
347 RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
348}
349
350// --- lane-pool1: persistent worker pools ---------------------------------
351//
352// Every threaded stage of the decoder used to spawn its threads per unit of
353// work: one `thread::scope` per filter STAGE per frame, one frame worker per
354// coded frame -- 2363 distinct threads in a 13 s 4K decode. The cost is not the clone of the thread itself but what
355// dies with it: every `thread_local!` scratch pool in `decode.rs` (planes,
356// rows, dq, mc, wiener, sgr) is allocated and faulted in again on each new
357// thread, which is where the 3.65 M page faults and the 2.7x malloc traffic of
358// the composed setting came from.
359//
360// The replacement is one pool per POOL-OWNING THREAD, kept in a thread-local
361// and joined when that thread exits: the frame workers submit a [`Batch`] of
362// `'static` jobs, the pool hands each to an idle worker (growing to
363// `busy + queued` so a job never queues behind a blocking one -- a frame
364// worker blocks on its references' promises), and the batch's `Drop` waits
365// every job out. Scratch then lives as long as the worker, not as long as the
366// frame. Borrowed jobs (filter bands, tile search) go through [`scope`]
367// instead.
368type Job = Box<dyn FnOnce() + Send + 'static>;
369
370struct PoolQ {
371 jobs: std::collections::VecDeque<Job>,
372 /// Jobs handed to a worker and not yet finished.
373 busy: usize,
374 closed: bool,
375 /// lane-memfix: the pool's threads live behind the same lock as its
376 /// queue, because the thread that has to GROW the pool is whichever one
377 /// submits -- including one of the pool's own workers (see
378 /// [`pool_push`]). Joined by [`Pool::drop`] on the owning thread.
379 handles: Vec<std::thread::JoinHandle<()>>,
380}
381
382struct PoolInner {
383 q: std::sync::Mutex<PoolQ>,
384 cv: std::sync::Condvar,
385}
386
387struct Pool {
388 inner: std::sync::Arc<PoolInner>,
389}
390
391fn pool_worker(inner: &std::sync::Arc<PoolInner>) {
392 // lane-memfix: a job this worker runs submits its own sub-batches to THIS
393 // pool rather than opening a second one on the worker's thread-local --
394 // see [`Batch::submit`].
395 ON_POOL.with(|c| *c.borrow_mut() = Some(std::sync::Arc::clone(inner)));
396 let mut q = inner.q.lock().unwrap();
397 loop {
398 if let Some(job) = q.jobs.pop_front() {
399 q.busy += 1;
400 drop(q);
401 // A job's own panic is captured by the batch wrapper below, so
402 // this only guards against a wrapper that itself unwinds.
403 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job));
404 q = inner.q.lock().unwrap();
405 q.busy -= 1;
406 continue;
407 }
408 if q.closed {
409 POOL_THREADS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
410 return;
411 }
412 q = inner.cv.wait(q).unwrap();
413 }
414}
415
416impl Pool {
417 fn new() -> Self {
418 Self {
419 inner: std::sync::Arc::new(PoolInner {
420 q: std::sync::Mutex::new(PoolQ {
421 jobs: std::collections::VecDeque::new(),
422 busy: 0,
423 closed: false,
424 handles: Vec::new(),
425 }),
426 cv: std::sync::Condvar::new(),
427 }),
428 }
429 }
430}
431
432/// Queues `job` on `inner` and makes sure a worker is free for it: the pool
433/// grows to `busy + queued` threads, so a submitted job always starts, even
434/// when every other running job is blocked waiting for it.
435/// `class` names the submitting site of the job that grows the pool, so a
436/// profiler attributes the thread to the work that created it
437/// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves every
438/// class submitted to it, so later classes reuse the threads an earlier one
439/// named.
440///
441/// lane-memfix: the pool only grows for work that is queued and unserved AT
442/// THAT MOMENT, and a pool worker submits back into its own pool, so the
443/// process-wide thread count is the peak of `busy + queued` over the whole
444/// job tree -- not the product of one pool per nesting level (a filter band
445/// job used to open a third-level pool on the worker running it, and none of
446/// those pools ever shrank: 1038 threads at (16,4,2)).
447fn pool_push(inner: &std::sync::Arc<PoolInner>, job: Job, class: &'static str) {
448 let mut q = inner.q.lock().unwrap();
449 q.jobs.push_back(job);
450 let want = q.busy + q.jobs.len();
451 while q.handles.len() < want {
452 let inner = std::sync::Arc::clone(inner);
453 let name = format!("{class}-{}", q.handles.len());
454 q.handles.push(
455 std::thread::Builder::new()
456 .name(name)
457 .spawn(move || pool_worker(&inner))
458 .expect("spawning an ec-av1 pool worker"),
459 );
460 POOL_THREADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
461 }
462 drop(q);
463 inner.cv.notify_one();
464}
465
466/// Live threads across every ec-av1 pool (what a profiler counts as `ec-av1-*`).
467static POOL_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
468
469impl Drop for Pool {
470 fn drop(&mut self) {
471 let handles = {
472 let mut q = self.inner.q.lock().unwrap();
473 q.closed = true;
474 std::mem::take(&mut q.handles)
475 };
476 self.inner.cv.notify_all();
477 for h in handles {
478 let _ = h.join();
479 }
480 }
481}
482
483thread_local! {
484 /// This thread's pool, created on its first [`Batch::submit`] and joined
485 /// when the thread exits (the process's main thread may skip that
486 /// destructor, in which case the idle workers die with the process).
487 static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) };
488 /// lane-memfix: set on a pool WORKER for its whole life -- the pool it
489 /// serves. A job submitting a sub-batch (a pipeline stage banding itself
490 /// across the filter pool) then reuses that pool instead of opening a
491 /// nested one of its own.
492 static ON_POOL: std::cell::RefCell<Option<std::sync::Arc<PoolInner>>> =
493 const { std::cell::RefCell::new(None) };
494}
495
496struct BatchState {
497 left: std::sync::Mutex<usize>,
498 cv: std::sync::Condvar,
499 panic: std::sync::Mutex<Option<Box<dyn std::any::Any + Send>>>,
500}
501
502/// A set of `'static` jobs running on the submitting thread's pool. `Drop`
503/// waits for every one of them and re-raises the first panic. Jobs own what
504/// they touch (`Arc`s, moved values): a job that needs borrowed data uses
505/// [`scope`] instead, which joins on its own threads.
506pub(crate) struct Batch {
507 st: std::sync::Arc<BatchState>,
508 class: &'static str,
509}
510
511impl Batch {
512 /// `class` is the thread-name prefix for any pool worker this batch has
513 /// to spawn -- see [`pool_push`].
514 pub(crate) fn new(class: &'static str) -> Self {
515 Self {
516 class,
517 st: std::sync::Arc::new(BatchState {
518 left: std::sync::Mutex::new(0),
519 cv: std::sync::Condvar::new(),
520 panic: std::sync::Mutex::new(None),
521 }),
522 }
523 }
524
525 pub(crate) fn submit<F: FnOnce() + Send + 'static>(&self, f: F) {
526 *self.st.left.lock().unwrap() += 1;
527 let st = std::sync::Arc::clone(&self.st);
528 let job: Job = Box::new(move || {
529 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
530 if let Err(p) = r {
531 let mut slot = st.panic.lock().unwrap();
532 if slot.is_none() {
533 *slot = Some(p);
534 }
535 }
536 // Poison-tolerant (lane-av1panichang): the count must come down
537 // even if some other holder of this lock panicked, or `drop`
538 // would wait forever.
539 let mut left = st
540 .left
541 .lock()
542 .unwrap_or_else(std::sync::PoisonError::into_inner);
543 *left -= 1;
544 st.cv.notify_all();
545 });
546 // lane-memfix: on a pool worker, back into the pool it is serving; on
547 // any other thread, this thread's own pool.
548 //
549 // No deadlock: a job blocked in `Batch::drop` is counted in `busy`,
550 // so `pool_push` grows the pool by one thread for every queued job
551 // that has no idle worker -- the child of a blocked parent always
552 // gets a thread. A frame worker does wait on its references' promises,
553 // which are published by jobs that are already running (never by one
554 // still in the queue), so the growth rule covers those waits too.
555 let on = ON_POOL.with(|c| c.borrow().clone());
556 match on {
557 Some(inner) => pool_push(&inner, job, self.class),
558 None => POOL.with(|p| {
559 let mut p = p.borrow_mut();
560 let inner = std::sync::Arc::clone(&p.get_or_insert_with(Pool::new).inner);
561 drop(p);
562 pool_push(&inner, job, self.class);
563 }),
564 }
565 }
566}
567
568impl Drop for Batch {
569 fn drop(&mut self) {
570 let mut left = self
571 .st
572 .left
573 .lock()
574 .unwrap_or_else(std::sync::PoisonError::into_inner);
575 while *left > 0 {
576 left = self
577 .st
578 .cv
579 .wait(left)
580 .unwrap_or_else(std::sync::PoisonError::into_inner);
581 }
582 drop(left);
583 let panicked = self
584 .st
585 .panic
586 .lock()
587 .unwrap_or_else(std::sync::PoisonError::into_inner)
588 .take();
589 // Re-raise the first job panic on the waiting thread, unless this
590 // thread is already unwinding: a second panic here would abort the
591 // process (lane-av1panichang).
592 if let Some(p) = panicked
593 && !std::thread::panicking()
594 {
595 std::panic::resume_unwind(p);
596 }
597 }
598}
599
600/// Jobs of a [`scope`] that may borrow from the caller's stack. Each one runs
601/// on its own `std::thread::scope` thread and is joined before `scope`
602/// returns; the first job panic is re-raised after all of them have finished,
603/// as [`Batch`] does.
604pub(crate) struct Scope<'scope, 'env: 'scope> {
605 inner: &'scope std::thread::Scope<'scope, 'env>,
606 class: &'static str,
607 panic: std::sync::Arc<std::sync::Mutex<Option<Box<dyn std::any::Any + Send>>>>,
608}
609
610impl<'scope> Scope<'scope, '_> {
611 /// Runs `f` on a new thread named `class`, joined when the scope ends.
612 pub(crate) fn submit<F: FnOnce() + Send + 'scope>(&self, f: F) {
613 let panic = std::sync::Arc::clone(&self.panic);
614 std::thread::Builder::new()
615 .name(self.class.to_owned())
616 .spawn_scoped(self.inner, move || {
617 if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
618 let mut slot = panic
619 .lock()
620 .unwrap_or_else(std::sync::PoisonError::into_inner);
621 if slot.is_none() {
622 *slot = Some(p);
623 }
624 }
625 })
626 .expect("spawning an ec-av1 scoped worker");
627 }
628}
629
630/// Runs `f` with a [`Scope`] whose jobs may borrow anything that outlives the
631/// call, and returns once every job has finished. The borrowed counterpart of
632/// [`Batch`]: a job here waits on nothing but its own work, so it needs no
633/// pool growth rule, and its `thread_local!` scratch is freed with the thread.
634pub(crate) fn scope<'env, R>(
635 class: &'static str,
636 f: impl for<'scope> FnOnce(&Scope<'scope, 'env>) -> R,
637) -> R {
638 let panic = std::sync::Arc::new(std::sync::Mutex::new(None));
639 let out = std::thread::scope(|inner| {
640 f(&Scope {
641 inner,
642 class,
643 panic: std::sync::Arc::clone(&panic),
644 })
645 });
646 let panicked = panic
647 .lock()
648 .unwrap_or_else(std::sync::PoisonError::into_inner)
649 .take();
650 if let Some(p) = panicked {
651 std::panic::resume_unwind(p);
652 }
653 out
654}
655
656// --- lane-av1fpar: encoder per-stage wall breakdown -----------------------
657//
658// Amdahl on the per-tile search (lane-av1tsearch) put ~43% of an inter frame
659// OUTSIDE the tile search without saying what it was. These counters name it:
660// one accumulator per serial stage of `encode_*_frame`, added to on whatever
661// thread runs the stage and printed by `encoder::tests::filter_stage_wall_*`.
662// Off (the default) each `stage` call is one relaxed atomic load.
663
664/// The stages [`stage`] accumulates, in the order a frame runs them.
665pub(crate) const STAGES: [&str; 10] = [
666 "tile search",
667 "tile write",
668 "filter: deblock replay",
669 "filter: cdef replay",
670 "filter: sse",
671 "filter search (total)",
672 "capture decode",
673 "lr search",
674 "filter: plane copies",
675 "filter: first decode",
676];
677pub(crate) const S_TILE_SEARCH: usize = 0;
678pub(crate) const S_TILE_WRITE: usize = 1;
679pub(crate) const S_DEBLOCK: usize = 2;
680pub(crate) const S_CDEF: usize = 3;
681pub(crate) const S_SSE: usize = 4;
682pub(crate) const S_FILTER: usize = 5;
683pub(crate) const S_CAPTURE: usize = 6;
684pub(crate) const S_LR: usize = 7;
685pub(crate) const S_COPY: usize = 8;
686pub(crate) const S_FIRST: usize = 9;
687
688static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
689 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];
690/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or
691/// [`set_stage_times`] from a gate (the env snapshot is process-constant).
692static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
693
694pub(crate) fn stage_times() -> bool {
695 match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) {
696 0 => {
697 let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES"));
698 STAGE_ON.store(on, std::sync::atomic::Ordering::Relaxed);
699 on == 2
700 }
701 n => n == 2,
702 }
703}
704
705/// Test-only override of [`stage_times`]; process-global.
706#[cfg(test)]
707pub(crate) fn set_stage_times(on: bool) {
708 STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed);
709}
710
711/// A live stage measurement: added to stage `i` when it drops. `None` when
712/// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.
713pub(crate) struct Timer(usize, std::time::Instant);
714
715#[inline]
716pub(crate) fn timer(i: usize) -> Option<Timer> {
717 stage_times().then(|| Timer(i, std::time::Instant::now()))
718}
719
720impl Drop for Timer {
721 fn drop(&mut self) {
722 STAGE_NS[self.0]
723 .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
724 }
725}
726
727/// Takes and clears the breakdown, in [`STAGES`] order.
728#[cfg(test)]
729pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] {
730 std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
731}