authoravatarclover caruso<git@paperclover.net>2026-12-01 15:01:32-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 15:22:03-08:00
log363e27e89e6fc142cb10daaee490f76794346570
tree6b0cd82f2216bc3b46b679e2f7b639c7224378bc
parent53404bff5dc1ccb3684ef4a655cd94d7f761d0b6
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): scale media prefetch workers to 12 and parallelize EXR f16/rgba8 conversion


2 files changed, 333 insertions(+), 63 deletions(-)

crates/engine/src/media.rs+156-31
...@@ -26,7 +26,7 @@ use std::collections::HashMap;...@@ -26,7 +26,7 @@ use std::collections::HashMap;
26use std::path::{Path, PathBuf};26use std::path::{Path, PathBuf};
27use std::process::Command;27use std::process::Command;
28#[cfg(not(target_arch = "wasm32"))]28#[cfg(not(target_arch = "wasm32"))]
29use std::sync::atomic::{AtomicUsize, Ordering};29use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
30#[cfg(not(target_arch = "wasm32"))]30#[cfg(not(target_arch = "wasm32"))]
31use std::sync::{Condvar, mpsc};31use std::sync::{Condvar, mpsc};
32use std::sync::{Arc, Mutex, RwLock};32use std::sync::{Arc, Mutex, RwLock};
...@@ -254,6 +254,11 @@ impl MediaState {...@@ -254,6 +254,11 @@ impl MediaState {
254 let _ = path;254 let _ = path;
255 }255 }
256256
257 #[cfg(not(target_arch = "wasm32"))]
258 fn is_over_soft_budget(&self) -> bool {
259 self.budget_bytes > 0 && self.total_bytes >= (self.budget_bytes * 3) / 4
260 }
261
257 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {262 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
258 let bytes = decoded.byte_size();263 let bytes = decoded.byte_size();
259 self.tick += 1;264 self.tick += 1;
...@@ -314,6 +319,8 @@ struct MediaShared {...@@ -314,6 +319,8 @@ struct MediaShared {
314 state: Mutex<MediaState>,319 state: Mutex<MediaState>,
315 #[cfg(not(target_arch = "wasm32"))]320 #[cfg(not(target_arch = "wasm32"))]
316 cv: Condvar,321 cv: Condvar,
322 #[cfg(not(target_arch = "wasm32"))]
323 soft_budget_exceeded: AtomicBool,
317}324}
318325
319impl MediaShared {326impl MediaShared {
...@@ -322,9 +329,29 @@ impl MediaShared {...@@ -322,9 +329,29 @@ impl MediaShared {
322 state: Mutex::new(MediaState::new(budget_bytes)),329 state: Mutex::new(MediaState::new(budget_bytes)),
323 #[cfg(not(target_arch = "wasm32"))]330 #[cfg(not(target_arch = "wasm32"))]
324 cv: Condvar::new(),331 cv: Condvar::new(),
332 #[cfg(not(target_arch = "wasm32"))]
333 soft_budget_exceeded: AtomicBool::new(false),
325 }334 }
326 }335 }
327336
337 fn sync_soft_budget(&self, state: &MediaState) {
338 #[cfg(not(target_arch = "wasm32"))]
339 self.soft_budget_exceeded
340 .store(state.is_over_soft_budget(), Ordering::Relaxed);
341 #[cfg(target_arch = "wasm32")]
342 let _ = state;
343 }
344
345 fn insert_cached_locked(
346 &self,
347 state: &mut MediaState,
348 cache_key: ImageCacheKey,
349 decoded: DecodedImage,
350 ) {
351 state.insert_cached(cache_key, decoded);
352 self.sync_soft_budget(state);
353 }
354
328 fn path_exists_cached(&self, path: &Path) -> bool {355 fn path_exists_cached(&self, path: &Path) -> bool {
329 if virtual_bytes(path).is_some() {356 if virtual_bytes(path).is_some() {
330 return true;357 return true;
...@@ -646,6 +673,7 @@ impl MediaCache {...@@ -646,6 +673,7 @@ impl MediaCache {
646 state.generation = state.generation.wrapping_add(1);673 state.generation = state.generation.wrapping_add(1);
647 #[cfg(not(target_arch = "wasm32"))]674 #[cfg(not(target_arch = "wasm32"))]
648 state.known_existing_paths.clear();675 state.known_existing_paths.clear();
676 self.shared.sync_soft_budget(&state);
649 }677 }
650 drop(cleared_decoders);678 drop(cleared_decoders);
651 #[cfg(not(target_arch = "wasm32"))]679 #[cfg(not(target_arch = "wasm32"))]
...@@ -698,6 +726,7 @@ impl MediaCache {...@@ -698,6 +726,7 @@ impl MediaCache {
698 state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size());726 state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size());
699 }727 }
700 }728 }
729 self.shared.sync_soft_budget(&state);
701 }730 }
702731
703 pub fn entry_count(&self) -> usize {732 pub fn entry_count(&self) -> usize {
...@@ -790,7 +819,8 @@ impl MediaCache {...@@ -790,7 +819,8 @@ impl MediaCache {
790 in_flight_guard.key = None;819 in_flight_guard.key = None;
791 }820 }
792 if state.generation == cache_gen {821 if state.generation == cache_gen {
793 state.insert_cached(cache_key, decoded.clone());822 self.shared
823 .insert_cached_locked(&mut state, cache_key, decoded.clone());
794 }824 }
795 #[cfg(not(target_arch = "wasm32"))]825 #[cfg(not(target_arch = "wasm32"))]
796 self.shared.cv.notify_all();826 self.shared.cv.notify_all();
...@@ -874,7 +904,8 @@ impl MediaCache {...@@ -874,7 +904,8 @@ impl MediaCache {
874 }904 }
875 if state.generation == cache_gen {905 if state.generation == cache_gen {
876 state.record_existing_path(&resolved);906 state.record_existing_path(&resolved);
877 state.insert_cached(cache_key, decoded.clone());907 self.shared
908 .insert_cached_locked(&mut state, cache_key, decoded.clone());
878 }909 }
879 #[cfg(not(target_arch = "wasm32"))]910 #[cfg(not(target_arch = "wasm32"))]
880 self.shared.cv.notify_all();911 self.shared.cv.notify_all();
...@@ -1020,7 +1051,7 @@ impl MediaCache {...@@ -1020,7 +1051,7 @@ impl MediaCache {
1020 return;1051 return;
1021 }1052 }
1022 let workers = std::thread::available_parallelism()1053 let workers = std::thread::available_parallelism()
1023 .map(|n| n.get().clamp(1, 8))1054 .map(|n| n.get().clamp(2, 12))
1024 .unwrap_or(4)1055 .unwrap_or(4)
1025 .min(total_units);1056 .min(total_units);
10261057
...@@ -1088,7 +1119,8 @@ impl MediaCache {...@@ -1088,7 +1119,8 @@ impl MediaCache {
1088 state.in_flight.remove(&key);1119 state.in_flight.remove(&key);
1089 guard.key = None;1120 guard.key = None;
1090 if state.generation == cache_gen {1121 if state.generation == cache_gen {
1091 state.insert_cached(key, decoded);1122 self.shared
1123 .insert_cached_locked(&mut state, key, decoded);
1092 }1124 }
1093 self.shared.cv.notify_all();1125 self.shared.cv.notify_all();
1094 }1126 }
...@@ -1143,7 +1175,7 @@ fn finish_raster_job(...@@ -1143,7 +1175,7 @@ fn finish_raster_job(
1143 if let Some(decoded) = decoded {1175 if let Some(decoded) = decoded {
1144 if state.generation == cache_gen {1176 if state.generation == cache_gen {
1145 state.record_existing_path(&key.path);1177 state.record_existing_path(&key.path);
1146 state.insert_cached(key, decoded);1178 shared.insert_cached_locked(&mut state, key, decoded);
1147 }1179 }
1148 } else {1180 } else {
1149 state.evict_existing_path(&key.path);1181 state.evict_existing_path(&key.path);
...@@ -1224,7 +1256,7 @@ impl MediaPrefetchHandle {...@@ -1224,7 +1256,7 @@ impl MediaPrefetchHandle {
1224 cv: Condvar::new(),1256 cv: Condvar::new(),
1225 });1257 });
1226 let worker_count = std::thread::available_parallelism()1258 let worker_count = std::thread::available_parallelism()
1227 .map(|n| n.get().clamp(2, 6))1259 .map(|n| n.get().clamp(2, 12))
1228 .unwrap_or(4);1260 .unwrap_or(4);
1229 let mut workers = Vec::with_capacity(worker_count);1261 let mut workers = Vec::with_capacity(worker_count);
1230 for _ in 0..worker_count {1262 for _ in 0..worker_count {
...@@ -1333,14 +1365,13 @@ impl MediaPrefetchHandle {...@@ -1333,14 +1365,13 @@ impl MediaPrefetchHandle {
1333 if q.cancelled {1365 if q.cancelled {
1334 return;1366 return;
1335 }1367 }
1336 q.prune_stale();
1337 let best_raster = q1368 let best_raster = q
1338 .raster1369 .raster
1339 .iter()1370 .iter()
1340 .enumerate()1371 .enumerate()
1341 .min_by_key(|&(_, (seq, _))| *seq)1372 .min_by_key(|&(_, (seq, _))| *seq)
1342 .map(|(idx, (seq, _))| (idx, *seq));1373 .map(|(idx, (seq, _))| (idx, *seq));
1343 let mut best_video: Option<(PathBuf, usize, usize)> = None;1374 let mut best_video: Option<(&PathBuf, usize, usize)> = None;
1344 for (path, vq) in &q.videos {1375 for (path, vq) in &q.videos {
1345 if q.active_videos.contains(path) {1376 if q.active_videos.contains(path) {
1346 continue;1377 continue;
...@@ -1349,7 +1380,7 @@ impl MediaPrefetchHandle {...@@ -1349,7 +1380,7 @@ impl MediaPrefetchHandle {
1349 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)1380 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
1350 {1381 {
1351 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {1382 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
1352 best_video = Some((path.clone(), v_idx, seq));1383 best_video = Some((path, v_idx, seq));
1353 }1384 }
1354 }1385 }
1355 }1386 }
...@@ -1375,28 +1406,27 @@ impl MediaPrefetchHandle {...@@ -1375,28 +1406,27 @@ impl MediaPrefetchHandle {
1375 continue;1406 continue;
1376 }1407 }
13771408
1378 if chosen_seq > q.current_seq.saturating_add(1) {1409 if chosen_seq > q.current_seq.saturating_add(1)
1379 let over_soft_budget = shared.state.lock().is_ok_and(|s| {1410 && shared.soft_budget_exceeded.load(Ordering::Relaxed)
1380 s.budget_bytes > 0 && s.total_bytes >= (s.budget_bytes * 3) / 41411 {
1381 });1412 q = match queue.cv.wait(q) {
1382 if over_soft_budget {1413 Ok(g) => g,
1383 q = match queue.cv.wait(q) {1414 Err(_) => return,
1384 Ok(g) => g,1415 };
1385 Err(_) => return,1416 continue;
1386 };
1387 continue;
1388 }
1389 }1417 }
13901418
1391 if let Some((path, v_idx, vs)) = best_video {1419 let chosen_video = best_video
1392 if best_raster.is_none_or(|(_, rs)| vs <= rs) {1420 .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs))
1393 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {1421 .map(|(path, v_idx, _)| (path.clone(), v_idx));
1394 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {1422
1395 q.videos.remove(&path);1423 if let Some((path, v_idx)) = chosen_video {
1396 }1424 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
1397 q.active_videos.insert(path.clone());1425 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1398 break PrefetchWorkItem::Video(path, req);1426 q.videos.remove(&path);
1399 }1427 }
1428 q.active_videos.insert(path.clone());
1429 break PrefetchWorkItem::Video(path, req);
1400 }1430 }
1401 }1431 }
1402 if let Some((r_idx, _)) = best_raster {1432 if let Some((r_idx, _)) = best_raster {
...@@ -1437,7 +1467,9 @@ impl MediaPrefetchHandle {...@@ -1437,7 +1467,9 @@ impl MediaPrefetchHandle {
1437 fn drop(&mut self) {1467 fn drop(&mut self) {
1438 if let Ok(mut q) = self.queue.state.lock() {1468 if let Ok(mut q) = self.queue.state.lock() {
1439 q.active_videos.remove(&self.path);1469 q.active_videos.remove(&self.path);
1440 self.queue.cv.notify_all();1470 if q.videos.contains_key(&self.path) || !q.raster.is_empty() {
1471 self.queue.cv.notify_one();
1472 }
1441 }1473 }
1442 }1474 }
1443 }1475 }
...@@ -1488,7 +1520,7 @@ impl MediaPrefetchHandle {...@@ -1488,7 +1520,7 @@ impl MediaPrefetchHandle {
1488 state.in_flight.remove(&key);1520 state.in_flight.remove(&key);
1489 guard.key = None;1521 guard.key = None;
1490 if state.generation == cache_gen {1522 if state.generation == cache_gen {
1491 state.insert_cached(key, decoded);1523 shared.insert_cached_locked(&mut state, key, decoded);
1492 }1524 }
1493 shared.cv.notify_all();1525 shared.cv.notify_all();
1494 }1526 }
...@@ -3136,4 +3168,97 @@ mod tests {...@@ -3136,4 +3168,97 @@ mod tests {
3136 handle.cancel();3168 handle.cancel();
3137 let _ = std::fs::remove_dir_all(&dir);3169 let _ = std::fs::remove_dir_all(&dir);
3138 }3170 }
3171
3172 #[cfg(not(target_arch = "wasm32"))]
3173 #[test]
3174 fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() {
3175 let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id()));
3176 let _ = std::fs::remove_dir_all(&dir);
3177 std::fs::create_dir_all(&dir).unwrap();
3178
3179 let v0 = dir.join("v0.mp4");
3180 let ok = Command::new("ffmpeg")
3181 .args([
3182 "-y",
3183 "-v",
3184 "error",
3185 "-f",
3186 "lavfi",
3187 "-i",
3188 "color=c=green:size=16x16:rate=24:duration=0.15",
3189 "-c:v",
3190 "libx264",
3191 "-pix_fmt",
3192 "yuv420p",
3193 ])
3194 .arg(&v0)
3195 .status()
3196 .is_ok_and(|s| s.success());
3197 if !ok {
3198 let _ = std::fs::remove_dir_all(&dir);
3199 return;
3200 }
3201
3202 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3203 let mut tools = String::new();
3204 for i in 0..9 {
3205 let vi = dir.join(format!("v{i}.mp4"));
3206 if i > 0 {
3207 std::fs::copy(&v0, &vi).unwrap();
3208 }
3209 tools.push_str(&format!(
3210 r#" V{i} = Loader {{
3211 Clips = {{
3212 Clip {{
3213 ID = "Clip1",
3214 Filename = "{}",
3215 FormatID = "QuickTimeMovies",
3216 Length = 3,
3217 GlobalStart = 0,
3218 GlobalEnd = 2,
3219 }},
3220 }},
3221 }},
3222"#,
3223 esc(&vi)
3224 ));
3225 }
3226 let mut prev = "V0".to_owned();
3227 for i in 1..9 {
3228 let mname = format!("M{i}");
3229 tools.push_str(&format!(
3230 r#" {mname} = Merge {{
3231 Inputs = {{
3232 Background = Input {{ SourceOp = "{prev}", Source = "Output", }},
3233 Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }},
3234 }},
3235 }},
3236"#
3237 ));
3238 prev = mname;
3239 }
3240 let comp_src = format!(
3241 "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}"
3242 );
3243 let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp");
3244 let target = comp.find_node("M8").expect("M8");
3245 let expr = model::ExprEngine::new();
3246 let cache = MediaCache::new(64);
3247
3248 let mut handle = cache.start_frame_prefetch(4);
3249 let expected_workers = std::thread::available_parallelism()
3250 .map(|n| n.get().clamp(2, 12))
3251 .unwrap_or(4);
3252 assert_eq!(handle.workers.len(), expected_workers);
3253
3254 handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false);
3255 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
3256 while cache.entry_count() < 9 && std::time::Instant::now() < deadline {
3257 std::thread::sleep(std::time::Duration::from_millis(5));
3258 }
3259 assert_eq!(cache.video_decoder_count(), 9);
3260 assert_eq!(cache.entry_count(), 9);
3261 handle.cancel();
3262 let _ = std::fs::remove_dir_all(&dir);
3263 }
3139}3264}
crates/engine/src/media/exr.rs+177-32
...@@ -198,6 +198,108 @@ pub(super) fn decode_exr_rgba(...@@ -198,6 +198,108 @@ pub(super) fn decode_exr_rgba(
198 }198 }
199}199}
200200
201fn convert_exr_rgba_slice(
202 raw_f32: &mut [f32],
203 raw_f16: &mut [u16],
204 raw: &mut [u8],
205 has_g: bool,
206 has_b: bool,
207 has_a: bool,
208 post_multiply: bool,
209) {
210 debug_assert_eq!(raw_f32.len(), raw_f16.len());
211 debug_assert_eq!(raw_f32.len(), raw.len());
212 debug_assert_eq!(raw_f32.len() % 4, 0);
213
214 for ((px_f32, px_f16), px_u8) in raw_f32
215 .chunks_exact_mut(4)
216 .zip(raw_f16.chunks_exact_mut(4))
217 .zip(raw.chunks_exact_mut(4))
218 {
219 let mut r_raw = px_f32[0];
220 let mut g_raw = if has_g { px_f32[1] } else { r_raw };
221 let mut b_raw = if has_b { px_f32[2] } else { r_raw };
222 let a_raw = if has_a { px_f32[3] } else { 1.0 };
223
224 if post_multiply && a_raw < 1.0 {
225 let a_mul = a_raw.clamp(0.0, 1.0);
226 r_raw *= a_mul;
227 g_raw *= a_mul;
228 b_raw *= a_mul;
229 }
230 px_f32[0] = r_raw;
231 px_f32[1] = g_raw;
232 px_f32[2] = b_raw;
233 px_f32[3] = a_raw;
234
235 px_f16[0] = f32_to_f16_bits(r_raw);
236 px_f16[1] = f32_to_f16_bits(g_raw);
237 px_f16[2] = f32_to_f16_bits(b_raw);
238 px_f16[3] = f32_to_f16_bits(a_raw);
239
240 let a = a_raw.clamp(0.0, 1.0);
241 let r = r_raw.clamp(0.0, 1.0);
242 let g = g_raw.clamp(0.0, 1.0);
243 let b = b_raw.clamp(0.0, 1.0);
244 px_u8[0] = (r * 255.0 + 0.5) as u8;
245 px_u8[1] = (g * 255.0 + 0.5) as u8;
246 px_u8[2] = (b * 255.0 + 0.5) as u8;
247 px_u8[3] = (a * 255.0 + 0.5) as u8;
248 }
249}
250
251fn convert_exr_rgba_buffers(
252 raw_f32: &mut [f32],
253 raw_f16: &mut [u16],
254 raw: &mut [u8],
255 has_g: bool,
256 has_b: bool,
257 has_a: bool,
258 post_multiply: bool,
259) {
260 #[cfg(not(target_arch = "wasm32"))]
261 {
262 const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512;
263 let total_px = raw_f32.len() / 4;
264 if total_px >= PARALLEL_THRESHOLD_PIXELS {
265 let workers = std::thread::available_parallelism()
266 .map(|n| n.get().clamp(2, 12))
267 .unwrap_or(4)
268 .min(total_px);
269 let chunk_elems = total_px.div_ceil(workers).max(1) * 4;
270 std::thread::scope(|scope| {
271 for ((f32_chunk, f16_chunk), u8_chunk) in raw_f32
272 .chunks_mut(chunk_elems)
273 .zip(raw_f16.chunks_mut(chunk_elems))
274 .zip(raw.chunks_mut(chunk_elems))
275 {
276 scope.spawn(move || {
277 convert_exr_rgba_slice(
278 f32_chunk,
279 f16_chunk,
280 u8_chunk,
281 has_g,
282 has_b,
283 has_a,
284 post_multiply,
285 );
286 });
287 }
288 });
289 return;
290 }
291 }
292 convert_exr_rgba_slice(
293 raw_f32,
294 raw_f16,
295 raw,
296 has_g,
297 has_b,
298 has_a,
299 post_multiply,
300 );
301}
302
201fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(303fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
202 reader: R,304 reader: R,
203 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],305 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],
...@@ -290,38 +392,15 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(...@@ -290,38 +392,15 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
290392
291 let mut raw = vec![0u8; w * h * 4];393 let mut raw = vec![0u8; w * h * 4];
292 let mut raw_f16 = vec![0u16; w * h * 4];394 let mut raw_f16 = vec![0u16; w * h * 4];
293 for i in 0..(w * h) {395 convert_exr_rgba_buffers(
294 let off = i * 4;396 &mut raw_f32,
295 let mut r_raw = raw_f32[off];397 &mut raw_f16,
296 let mut g_raw = if g_loc.is_some() { raw_f32[off + 1] } else { r_raw };398 &mut raw,
297 let mut b_raw = if b_loc.is_some() { raw_f32[off + 2] } else { r_raw };399 g_loc.is_some(),
298 let a_raw = if a_loc.is_some() { raw_f32[off + 3] } else { 1.0 };400 b_loc.is_some(),
299401 a_loc.is_some(),
300 if post_multiply && a_raw < 1.0 {402 post_multiply,
301 let a_mul = a_raw.clamp(0.0, 1.0);403 );
302 r_raw *= a_mul;
303 g_raw *= a_mul;
304 b_raw *= a_mul;
305 }
306 raw_f32[off] = r_raw;
307 raw_f32[off + 1] = g_raw;
308 raw_f32[off + 2] = b_raw;
309 raw_f32[off + 3] = a_raw;
310
311 raw_f16[off] = f32_to_f16_bits(r_raw);
312 raw_f16[off + 1] = f32_to_f16_bits(g_raw);
313 raw_f16[off + 2] = f32_to_f16_bits(b_raw);
314 raw_f16[off + 3] = f32_to_f16_bits(a_raw);
315
316 let a = a_raw.clamp(0.0, 1.0);
317 let r = r_raw.clamp(0.0, 1.0);
318 let g = g_raw.clamp(0.0, 1.0);
319 let b = b_raw.clamp(0.0, 1.0);
320 raw[off] = (r * 255.0 + 0.5) as u8;
321 raw[off + 1] = (g * 255.0 + 0.5) as u8;
322 raw[off + 2] = (b * 255.0 + 0.5) as u8;
323 raw[off + 3] = (a * 255.0 + 0.5) as u8;
324 }
325 Some(DecodedImage {404 Some(DecodedImage {
326 size: [w as u32, h as u32],405 size: [w as u32, h as u32],
327 rgba: Arc::new(raw),406 rgba: Arc::new(raw),
...@@ -346,4 +425,70 @@ mod tests {...@@ -346,4 +425,70 @@ mod tests {
346 assert_eq!(decoded.size, [2, 1]);425 assert_eq!(decoded.size, [2, 1]);
347 assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]);426 assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]);
348 }427 }
428
429 #[test]
430 fn parallel_exr_conversion_matches_scalar_bit_for_bit() {
431 let pixels = 512 * 512 + 17;
432 let special: [[f32; 4]; 10] = [
433 [0.0, 0.25, 0.5, 1.0],
434 [12.5, 1.0001, 65504.0, 0.5],
435 [100000.0, -0.5, -12.25, 0.25],
436 [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.75],
437 [1.0e-7, -1.0e-7, 5.960_464_5e-8, 0.0],
438 [0.3333, 0.6667, 0.9999, 1.5],
439 [-0.0, 0.0, f32::from_bits(0x7fc0_0123), -0.25],
440 [2.0, 4.0, 8.0, f32::NAN],
441 [6.103_515_6e-5, 3.051_757_8e-5, 1.525_878_9e-5, 0.999],
442 [0.5, 0.25, 0.125, f32::INFINITY],
443 ];
444 let mut base = Vec::with_capacity(pixels * 4);
445 for i in 0..pixels {
446 let s = special[i % special.len()];
447 let scale = if (i % 7) == 0 { 1.0 } else { ((i % 23) as f32) * 0.125 };
448 if s[0].is_finite() && s[1].is_finite() && s[2].is_finite() && s[3].is_finite() {
449 base.extend_from_slice(&[s[0] * scale, s[1], s[2] + 0.001 * (i % 5) as f32, s[3]]);
450 } else {
451 base.extend_from_slice(&s);
452 }
453 }
454
455 for &(has_g, has_b, has_a, post_multiply) in &[
456 (true, true, true, false),
457 (true, true, true, true),
458 (false, false, false, true),
459 (true, false, true, true),
460 ] {
461 let mut par_f32 = base.clone();
462 let mut par_f16 = vec![0u16; pixels * 4];
463 let mut par_u8 = vec![0u8; pixels * 4];
464 convert_exr_rgba_buffers(
465 &mut par_f32,
466 &mut par_f16,
467 &mut par_u8,
468 has_g,
469 has_b,
470 has_a,
471 post_multiply,
472 );
473
474 let mut seq_f32 = base.clone();
475 let mut seq_f16 = vec![0u16; pixels * 4];
476 let mut seq_u8 = vec![0u8; pixels * 4];
477 convert_exr_rgba_slice(
478 &mut seq_f32,
479 &mut seq_f16,
480 &mut seq_u8,
481 has_g,
482 has_b,
483 has_a,
484 post_multiply,
485 );
486
487 assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
488 assert_eq!(par_u8, seq_u8, "u8 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
489 let par_bits: Vec<u32> = par_f32.iter().map(|v| v.to_bits()).collect();
490 let seq_bits: Vec<u32> = seq_f32.iter().map(|v| v.to_bits()).collect();
491 assert_eq!(par_bits, seq_bits, "f32 bits mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
492 }
493 }
349}494}