Skip to main content

alpha2_render/cpu/
workers.rs

1//! The CPU renderer's threads. Each pass splits rows into bands, each written by one thread, so
2//! results do not depend on the thread count.
3
4/// Approximate pixels per band: enough to amortize scheduling, small enough to stay in cache.
5const BAND_PIXELS: usize = 16_384;
6
7type Progress = std::sync::Arc<dyn Fn() + Send + Sync>;
8
9std::thread_local! {
10    static BAND_PROGRESS: std::cell::RefCell<Option<Progress>> =
11        const { std::cell::RefCell::new(None) };
12}
13
14/// Calls `progress` once per band of every pass the CPU renderer draws for the calling thread,
15/// from whichever thread draws the band, until the guard drops. A watcher of the caller then sees
16/// a long frame progress.
17#[must_use = "the report ends when the guard drops"]
18pub fn report_band_progress(progress: Progress) -> BandProgress {
19    let previous = BAND_PROGRESS.with(|current| current.replace(Some(progress)));
20    BandProgress {
21        previous,
22        thread: std::marker::PhantomData,
23    }
24}
25
26/// Ends a [`report_band_progress`] report, restoring the one before it.
27pub struct BandProgress {
28    previous: Option<Progress>,
29    thread: std::marker::PhantomData<*const ()>,
30}
31
32impl Drop for BandProgress {
33    fn drop(&mut self) {
34        let previous = self.previous.take();
35        BAND_PROGRESS.with(|current| {
36            current.replace(previous);
37        });
38    }
39}
40
41fn band_progress() -> impl Fn() + Send + Sync {
42    let progress = BAND_PROGRESS.with(|current| current.borrow().clone());
43    move || {
44        if let Some(progress) = &progress {
45            progress();
46        }
47    }
48}
49
50/// The threads one CPU renderer draws with.
51pub(crate) struct Workers {
52    #[cfg(not(target_arch = "wasm32"))]
53    pool: Option<rayon::ThreadPool>,
54    threads: usize,
55    /// Rows of every band in place of [`band_rows`], so tests can move band seams.
56    fixed_rows: Option<usize>,
57}
58
59impl std::fmt::Debug for Workers {
60    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        formatter
62            .debug_struct("Workers")
63            .field("threads", &self.threads)
64            .finish_non_exhaustive()
65    }
66}
67
68impl Workers {
69    /// `threads` workers (one means the calling thread); falls back to the calling thread if the
70    /// pool cannot start.
71    pub(crate) fn new(threads: usize) -> Self {
72        Self::named(threads, "alpha2-cpu-render")
73    }
74
75    pub(crate) fn named(threads: usize, name: &'static str) -> Self {
76        let threads = threads.max(1);
77        #[cfg(not(target_arch = "wasm32"))]
78        {
79            let pool = (threads > 1)
80                .then(|| {
81                    rayon::ThreadPoolBuilder::new()
82                        .num_threads(threads)
83                        .thread_name(move |index| format!("{name}-{index}"))
84                        .build()
85                        .ok()
86                })
87                .flatten();
88            let threads = if pool.is_some() { threads } else { 1 };
89            Self {
90                pool,
91                threads,
92                fixed_rows: None,
93            }
94        }
95        #[cfg(target_arch = "wasm32")]
96        {
97            let _ = (threads, name);
98            Self {
99                threads: 1,
100                fixed_rows: None,
101            }
102        }
103    }
104
105    /// As [`Self::new`], with every band `rows` rows high (`usize::MAX` for one band).
106    #[cfg(test)]
107    pub(crate) fn with_band_rows(threads: usize, rows: usize) -> Self {
108        Self {
109            fixed_rows: Some(rows.max(1)),
110            ..Self::new(threads)
111        }
112    }
113
114    /// Rows per band for an image `width` pixels wide.
115    pub(crate) fn band_rows(&self, width: usize) -> usize {
116        self.fixed_rows.unwrap_or_else(|| band_rows(width))
117    }
118
119    pub(crate) const fn threads(&self) -> usize {
120        self.threads
121    }
122
123    /// Calls `draw(first_row, rows)` in parallel for each band of whole rows of `pixels`, an image
124    /// `width` wide; `first_row` counts from the start of `pixels`.
125    // On wasm there is no pool: every band runs on the calling thread.
126    #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
127    pub(crate) fn bands<T: Send>(
128        &self,
129        pixels: &mut [T],
130        width: usize,
131        draw: impl Fn(usize, &mut [T]) + Sync + Send,
132    ) {
133        if width == 0 || pixels.is_empty() {
134            return;
135        }
136        let rows = self.band_rows(width);
137        let progress = band_progress();
138        let draw = |row, chunk: &mut [T]| {
139            progress();
140            draw(row, chunk);
141        };
142        #[cfg(not(target_arch = "wasm32"))]
143        if let Some(pool) = &self.pool {
144            use rayon::prelude::*;
145            pool.install(|| {
146                pixels
147                    .par_chunks_mut(rows.saturating_mul(width))
148                    .enumerate()
149                    .for_each(|(band, chunk)| draw(band * rows, chunk));
150            });
151            return;
152        }
153        for (band, chunk) in pixels.chunks_mut(rows.saturating_mul(width)).enumerate() {
154            draw(band * rows, chunk);
155        }
156    }
157
158    /// As [`Self::bands`], with `draw(scratch, first_row, rows)` reusing one `init()` scratch per
159    /// thread for the bands it draws in this pass.
160    ///
161    /// Which bands share a scratch depends on scheduling, so `draw` must reset everything it
162    /// reads from the scratch at the start of each band.
163    pub(crate) fn bands_with<T: Send, S: Send>(
164        &self,
165        pixels: &mut [T],
166        width: usize,
167        init: impl Fn() -> S + Sync + Send,
168        draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
169    ) {
170        if width == 0 || pixels.is_empty() {
171            return;
172        }
173        let rows = self.band_rows(width);
174        self.chunks_with(pixels, rows.saturating_mul(width), rows, init, draw);
175    }
176
177    /// As [`Self::bands_with`] over `items` that each cover `item_pixels` pixels (one row of
178    /// chroma, say): bands hold whole items, `draw` gets the index of its first item.
179    pub(crate) fn items_with<T: Send, S: Send>(
180        &self,
181        items: &mut [T],
182        item_pixels: usize,
183        init: impl Fn() -> S + Sync + Send,
184        draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
185    ) {
186        if item_pixels == 0 || items.is_empty() {
187            return;
188        }
189        let rows = self.band_rows(item_pixels);
190        self.chunks_with(items, rows, rows, init, draw);
191    }
192
193    /// Calls `draw(scratch, band * step, chunk)` for each `length`-long chunk of `items`.
194    #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
195    fn chunks_with<T: Send, S: Send>(
196        &self,
197        items: &mut [T],
198        length: usize,
199        step: usize,
200        init: impl Fn() -> S + Sync + Send,
201        draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
202    ) {
203        let progress = band_progress();
204        let draw = |scratch: &mut S, row, chunk: &mut [T]| {
205            progress();
206            draw(scratch, row, chunk);
207        };
208        #[cfg(not(target_arch = "wasm32"))]
209        if let Some(pool) = &self.pool {
210            use rayon::prelude::*;
211            use std::sync::{Mutex, TryLockError};
212            // The last slot serves a caller outside the pool.
213            let slots = (0..=self.threads)
214                .map(|_| Mutex::new(None::<S>))
215                .collect::<Vec<_>>();
216            pool.install(|| {
217                items
218                    .par_chunks_mut(length)
219                    .enumerate()
220                    .for_each(|(band, chunk)| {
221                        let slot = rayon::current_thread_index()
222                            .map_or(self.threads, |index| index.min(self.threads));
223                        match slots[slot].try_lock() {
224                            Ok(mut held) => {
225                                let scratch = held.get_or_insert_with(&init);
226                                draw(scratch, band * step, chunk);
227                            }
228                            // A thread that re-entered the pool while drawing: a scratch of its own.
229                            Err(TryLockError::WouldBlock | TryLockError::Poisoned(_)) => {
230                                draw(&mut init(), band * step, chunk);
231                            }
232                        }
233                    });
234            });
235            return;
236        }
237        let mut scratch = init();
238        for (band, chunk) in items.chunks_mut(length).enumerate() {
239            draw(&mut scratch, band * step, chunk);
240        }
241    }
242
243    /// Calls `job(index)` for every index below `count`, in parallel and in any order.
244    #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
245    pub(crate) fn for_each(&self, count: usize, job: &(dyn Fn(usize) + Sync)) {
246        #[cfg(not(target_arch = "wasm32"))]
247        if let Some(pool) = &self.pool {
248            use rayon::prelude::*;
249            pool.install(|| (0..count).into_par_iter().for_each(job));
250            return;
251        }
252        (0..count).for_each(job);
253    }
254
255    /// Calls `work(index)` in parallel for every index below `count`, collecting in index order.
256    #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
257    pub(crate) fn map<T: Send>(
258        &self,
259        count: usize,
260        work: impl Fn(usize) -> T + Sync + Send,
261    ) -> Vec<T> {
262        #[cfg(not(target_arch = "wasm32"))]
263        if let Some(pool) = &self.pool {
264            use rayon::prelude::*;
265            return pool.install(|| (0..count).into_par_iter().map(&work).collect());
266        }
267        (0..count).map(work).collect()
268    }
269}
270
271/// Rows per band for an image `width` pixels wide.
272fn band_rows(width: usize) -> usize {
273    (BAND_PIXELS / width).clamp(1, 64)
274}
275
276impl crate::layout_pack::Bands for Workers {
277    fn rows_per_band(&self, _chroma_rows: usize, row_pixels: usize) -> usize {
278        self.band_rows(row_pixels)
279    }
280
281    fn run(&self, count: usize, job: &(dyn Fn(usize) + Sync)) {
282        self.for_each(count, job);
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use std::sync::Arc;
290    use std::sync::atomic::{AtomicUsize, Ordering};
291
292    #[test]
293    fn every_band_reports_progress_to_the_calling_threads_watcher_on_any_thread() {
294        let width = 512;
295        let rows = band_rows(width);
296        for threads in [1, 4] {
297            let workers = Workers::new(threads);
298            let reported = Arc::new(AtomicUsize::new(0));
299            let counter = Arc::clone(&reported);
300            let report = report_band_progress(Arc::new(move || {
301                counter.fetch_add(1, Ordering::Relaxed);
302            }));
303            let mut pixels = vec![0_u8; width * rows * 9];
304            workers.bands(&mut pixels, width, |_, chunk| chunk.fill(1));
305            workers.bands_with(&mut pixels, width, || (), |(), _, chunk| chunk.fill(2));
306            assert_eq!(reported.load(Ordering::Relaxed), 18, "{threads} threads");
307            drop(report);
308            workers.bands(&mut pixels, width, |_, chunk| chunk.fill(3));
309            assert_eq!(reported.load(Ordering::Relaxed), 18, "the report ended");
310        }
311    }
312}