1const BAND_PIXELS: usize = 16_384;
6
7const BANDS_WANTED_PER_THREAD: usize = 2;
8
9type Progress = std::sync::Arc<dyn Fn() + Send + Sync>;
10
11std::thread_local! {
12 static BAND_PROGRESS: std::cell::RefCell<Option<Progress>> =
13 const { std::cell::RefCell::new(None) };
14}
15
16#[must_use = "the report ends when the guard drops"]
20pub fn report_band_progress(progress: Progress) -> BandProgress {
21 let previous = BAND_PROGRESS.with(|current| current.replace(Some(progress)));
22 BandProgress {
23 previous,
24 thread: std::marker::PhantomData,
25 }
26}
27
28pub struct BandProgress {
30 previous: Option<Progress>,
31 thread: std::marker::PhantomData<*const ()>,
32}
33
34impl Drop for BandProgress {
35 fn drop(&mut self) {
36 let previous = self.previous.take();
37 BAND_PROGRESS.with(|current| {
38 current.replace(previous);
39 });
40 }
41}
42
43fn band_progress() -> impl Fn() + Send + Sync {
44 let progress = BAND_PROGRESS.with(|current| current.borrow().clone());
45 move || {
46 if let Some(progress) = &progress {
47 progress();
48 }
49 }
50}
51
52pub(crate) struct Workers {
54 #[cfg(not(target_arch = "wasm32"))]
55 pool: Option<rayon::ThreadPool>,
56 threads: usize,
57 fixed_rows: Option<usize>,
59}
60
61impl std::fmt::Debug for Workers {
62 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 formatter
64 .debug_struct("Workers")
65 .field("threads", &self.threads)
66 .finish_non_exhaustive()
67 }
68}
69
70impl Workers {
71 pub(crate) fn new(threads: usize) -> Self {
74 Self::named(threads, "alpha2-cpu-render")
75 }
76
77 pub(crate) fn named(threads: usize, name: &'static str) -> Self {
78 let threads = threads.max(1);
79 #[cfg(not(target_arch = "wasm32"))]
80 {
81 let pool = (threads > 1)
82 .then(|| {
83 rayon::ThreadPoolBuilder::new()
84 .num_threads(threads)
85 .thread_name(move |index| format!("{name}-{index}"))
86 .build()
87 .ok()
88 })
89 .flatten();
90 let threads = if pool.is_some() { threads } else { 1 };
91 Self {
92 pool,
93 threads,
94 fixed_rows: None,
95 }
96 }
97 #[cfg(target_arch = "wasm32")]
98 {
99 let _ = (threads, name);
100 Self {
101 threads: 1,
102 fixed_rows: None,
103 }
104 }
105 }
106
107 #[cfg(test)]
109 pub(crate) fn with_band_rows(threads: usize, rows: usize) -> Self {
110 Self {
111 fixed_rows: Some(rows.max(1)),
112 ..Self::new(threads)
113 }
114 }
115
116 pub(crate) fn band_rows(&self, width: usize) -> usize {
118 self.fixed_rows.unwrap_or_else(|| band_rows(width))
119 }
120
121 pub(crate) const fn threads(&self) -> usize {
122 self.threads
123 }
124
125 #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
129 pub(crate) fn bands<T: Send>(
130 &self,
131 pixels: &mut [T],
132 width: usize,
133 draw: impl Fn(usize, &mut [T]) + Sync + Send,
134 ) {
135 if width == 0 || pixels.is_empty() {
136 return;
137 }
138 let rows = self.band_rows(width);
139 let progress = band_progress();
140 let draw = |row, chunk: &mut [T]| {
141 progress();
142 draw(row, chunk);
143 };
144 #[cfg(not(target_arch = "wasm32"))]
145 if let Some(pool) = &self.pool {
146 use rayon::prelude::*;
147 pool.install(|| {
148 pixels
149 .par_chunks_mut(rows.saturating_mul(width))
150 .enumerate()
151 .for_each(|(band, chunk)| draw(band * rows, chunk));
152 });
153 return;
154 }
155 for (band, chunk) in pixels.chunks_mut(rows.saturating_mul(width)).enumerate() {
156 draw(band * rows, chunk);
157 }
158 }
159
160 pub(crate) fn bands_with<T: Send, S: Send>(
166 &self,
167 pixels: &mut [T],
168 width: usize,
169 init: impl Fn() -> S + Sync + Send,
170 draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
171 ) {
172 if width == 0 || pixels.is_empty() {
173 return;
174 }
175 let rows = self.band_rows(width);
176 self.chunks_with(pixels, rows.saturating_mul(width), rows, init, draw);
177 }
178
179 pub(crate) fn weighted_bands_with<T: Send, S: Send>(
180 &self,
181 pixels: &mut [T],
182 width: usize,
183 row_work_pixels: usize,
184 init: impl Fn() -> S + Sync + Send,
185 draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
186 ) {
187 if width == 0 || pixels.is_empty() {
188 return;
189 }
190 let rows = self.fixed_rows.unwrap_or_else(|| {
191 weighted_band_rows(self.threads, width, pixels.len() / width, row_work_pixels)
192 });
193 self.chunks_with(pixels, rows.saturating_mul(width), rows, init, draw);
194 }
195
196 pub(crate) fn items_with<T: Send, S: Send>(
199 &self,
200 items: &mut [T],
201 item_pixels: usize,
202 init: impl Fn() -> S + Sync + Send,
203 draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
204 ) {
205 if item_pixels == 0 || items.is_empty() {
206 return;
207 }
208 let rows = self.band_rows(item_pixels);
209 self.chunks_with(items, rows, rows, init, draw);
210 }
211
212 #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
214 fn chunks_with<T: Send, S: Send>(
215 &self,
216 items: &mut [T],
217 length: usize,
218 step: usize,
219 init: impl Fn() -> S + Sync + Send,
220 draw: impl Fn(&mut S, usize, &mut [T]) + Sync + Send,
221 ) {
222 let progress = band_progress();
223 let draw = |scratch: &mut S, row, chunk: &mut [T]| {
224 progress();
225 draw(scratch, row, chunk);
226 };
227 #[cfg(not(target_arch = "wasm32"))]
228 if let Some(pool) = self.pool.as_ref().filter(|_| items.len() > length) {
229 use rayon::prelude::*;
230 use std::sync::{Mutex, TryLockError};
231 let slots = (0..=self.threads)
233 .map(|_| Mutex::new(None::<S>))
234 .collect::<Vec<_>>();
235 pool.install(|| {
236 items
237 .par_chunks_mut(length)
238 .enumerate()
239 .for_each(|(band, chunk)| {
240 let slot = rayon::current_thread_index()
241 .map_or(self.threads, |index| index.min(self.threads));
242 match slots[slot].try_lock() {
243 Ok(mut held) => {
244 let scratch = held.get_or_insert_with(&init);
245 draw(scratch, band * step, chunk);
246 }
247 Err(TryLockError::WouldBlock | TryLockError::Poisoned(_)) => {
249 draw(&mut init(), band * step, chunk);
250 }
251 }
252 });
253 });
254 return;
255 }
256 let mut scratch = init();
257 for (band, chunk) in items.chunks_mut(length).enumerate() {
258 draw(&mut scratch, band * step, chunk);
259 }
260 }
261
262 #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
264 pub(crate) fn for_each(&self, count: usize, job: &(dyn Fn(usize) + Sync)) {
265 #[cfg(not(target_arch = "wasm32"))]
266 if let Some(pool) = &self.pool {
267 use rayon::prelude::*;
268 pool.install(|| (0..count).into_par_iter().for_each(job));
269 return;
270 }
271 (0..count).for_each(job);
272 }
273
274 #[cfg_attr(target_arch = "wasm32", allow(clippy::unused_self))]
276 pub(crate) fn map<T: Send>(
277 &self,
278 count: usize,
279 work: impl Fn(usize) -> T + Sync + Send,
280 ) -> Vec<T> {
281 #[cfg(not(target_arch = "wasm32"))]
282 if let Some(pool) = &self.pool {
283 use rayon::prelude::*;
284 return pool.install(|| (0..count).into_par_iter().map(&work).collect());
285 }
286 (0..count).map(work).collect()
287 }
288}
289
290fn band_rows(width: usize) -> usize {
292 (BAND_PIXELS / width).clamp(1, 64)
293}
294
295fn weighted_band_rows(threads: usize, width: usize, rows: usize, row_work_pixels: usize) -> usize {
296 let unweighted = band_rows(width);
297 let bands_wanted = threads * BANDS_WANTED_PER_THREAD;
298 if threads == 1 || rows.div_ceil(unweighted) >= bands_wanted {
299 return unweighted;
300 }
301 let rows_of_one_band_of_work = (BAND_PIXELS / row_work_pixels.max(1)).max(1);
302 let rows_of_the_bands_wanted = rows.div_ceil(bands_wanted);
303 unweighted.min(rows_of_one_band_of_work.max(rows_of_the_bands_wanted))
304}
305
306impl crate::layout_pack::Bands for Workers {
307 fn rows_per_band(&self, _chroma_rows: usize, row_pixels: usize) -> usize {
308 self.band_rows(row_pixels)
309 }
310
311 fn run(&self, count: usize, job: &(dyn Fn(usize) + Sync)) {
312 self.for_each(count, job);
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319 use std::sync::Arc;
320 use std::sync::atomic::{AtomicUsize, Ordering};
321
322 #[test]
323 fn every_band_reports_progress_to_the_calling_threads_watcher_on_any_thread() {
324 let width = 512;
325 let rows = band_rows(width);
326 for threads in [1, 4] {
327 let workers = Workers::new(threads);
328 let reported = Arc::new(AtomicUsize::new(0));
329 let counter = Arc::clone(&reported);
330 let report = report_band_progress(Arc::new(move || {
331 counter.fetch_add(1, Ordering::Relaxed);
332 }));
333 let mut pixels = vec![0_u8; width * rows * 9];
334 workers.bands(&mut pixels, width, |_, chunk| chunk.fill(1));
335 workers.bands_with(&mut pixels, width, || (), |(), _, chunk| chunk.fill(2));
336 assert_eq!(reported.load(Ordering::Relaxed), 18, "{threads} threads");
337 drop(report);
338 workers.bands(&mut pixels, width, |_, chunk| chunk.fill(3));
339 assert_eq!(reported.load(Ordering::Relaxed), 18, "the report ended");
340 }
341 }
342
343 #[test]
344 fn rows_that_cost_more_than_their_pixels_get_lower_bands_only_while_threads_lack_bands() {
345 for width in [1, 100, 204, 256, 1280, 1920, 3840, 20_000] {
346 let unweighted = band_rows(width);
347 for rows in [1, 7, 64, 113, 720, 1080, 2160] {
348 for threads in [1, 2, 8, 24, 64] {
349 assert_eq!(
350 weighted_band_rows(threads, width, rows, width),
351 unweighted,
352 "rows that cost their pixels: {width} x {rows} on {threads} threads"
353 );
354 for row_work in [width * 2, width * 64, width * 4096] {
355 let weighted = weighted_band_rows(threads, width, rows, row_work);
356 assert!((1..=unweighted).contains(&weighted));
357 let bands_wanted = threads * BANDS_WANTED_PER_THREAD;
358 if threads == 1 || rows.div_ceil(unweighted) >= bands_wanted {
359 assert_eq!(weighted, unweighted);
360 } else {
361 assert!(rows.div_ceil(weighted) <= bands_wanted);
362 }
363 }
364 }
365 }
366 }
367 assert_eq!(weighted_band_rows(24, 204, 113, 204 * 8 * 64), 3);
368 assert_eq!(weighted_band_rows(8, 204, 113, 204 * 8 * 64), 8);
369 assert_eq!(weighted_band_rows(24, 204, 113, 204 * 4), 20);
370 }
371
372 #[test]
373 fn one_band_is_drawn_on_the_calling_thread() {
374 let workers = Workers::new(4);
375 let caller = std::thread::current().id();
376 let mut pixels = vec![0_u8; 64];
377 workers.bands_with(
378 &mut pixels,
379 8,
380 || (),
381 |(), _, chunk| {
382 assert_eq!(std::thread::current().id(), caller);
383 chunk.fill(1);
384 },
385 );
386 assert!(pixels.iter().all(|pixel| *pixel == 1));
387 }
388}