1const 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#[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
26pub 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
50pub(crate) struct Workers {
52 #[cfg(not(target_arch = "wasm32"))]
53 pool: Option<rayon::ThreadPool>,
54 threads: usize,
55 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 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 #[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 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 #[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 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 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 #[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 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 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 #[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 #[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
271fn 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}