authoravatarclover caruso<git@paperclover.net>2026-11-30 20:26:09-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:40:12-08:00
logaffa4033bbacab68dca669d1c550f3e7cb5e7227
tree4575f590729db7cfc31c276721972e57bf863d95
parentb963cf28697a2c2c823007e0409102b078aec931
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix MediaCache EXR/decoder leaks, RamPrefetcher race, AudioPlayer RT race, and FFmpeg export P0s


6 files changed, 1484 insertions(+), 233 deletions(-)

crates/app/src/export_ui.rs+7-1
...@@ -43,7 +43,13 @@ impl Drop for ActiveExport {...@@ -43,7 +43,13 @@ impl Drop for ActiveExport {
43 fn drop(&mut self) {43 fn drop(&mut self) {
44 self.control.cancel();44 self.control.cancel();
45 if let Some(handle) = self.handle.take() {45 if let Some(handle) = self.handle.take() {
46 let _ = handle.join();46 let deadline = Instant::now() + std::time::Duration::from_millis(250);
47 while !handle.is_finished() && Instant::now() < deadline {
48 std::thread::sleep(std::time::Duration::from_millis(5));
49 }
50 if handle.is_finished() {
51 let _ = handle.join();
52 }
47 }53 }
48 }54 }
49}55}
crates/engine/src/audio.rs+373-58
...@@ -8,7 +8,7 @@ use std::io::ErrorKind;...@@ -8,7 +8,7 @@ use std::io::ErrorKind;
8use std::path::{Path, PathBuf};8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};10use std::sync::{Arc, Mutex};
11use symphonia::core::audio::SampleBuffer;11use symphonia::core::audio::{Channels, SampleBuffer};
12use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};12use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
13use symphonia::core::errors::Error as SymphoniaError;13use symphonia::core::errors::Error as SymphoniaError;
14use symphonia::core::formats::FormatOptions;14use symphonia::core::formats::FormatOptions;
...@@ -131,10 +131,17 @@ impl AudioTrack {...@@ -131,10 +131,17 @@ impl AudioTrack {
131 stereo_samples.extend_from_slice(interleaved);131 stereo_samples.extend_from_slice(interleaved);
132 }132 }
133 n => {133 n => {
134 let weights = downmix_weights(spec.channels, n);
134 stereo_samples.reserve(frames * 2);135 stereo_samples.reserve(frames * 2);
135 for frame in interleaved.chunks_exact(n) {136 for frame in interleaved.chunks_exact(n) {
136 stereo_samples.push(frame[0]);137 let mut l = 0.0_f32;
137 stereo_samples.push(frame[1]);138 let mut r = 0.0_f32;
139 for (s, &(wl, wr)) in frame.iter().zip(weights.iter()) {
140 l += *s * wl;
141 r += *s * wr;
142 }
143 stereo_samples.push(l.clamp(-1.0, 1.0));
144 stereo_samples.push(r.clamp(-1.0, 1.0));
138 }145 }
139 }146 }
140 }147 }
...@@ -202,20 +209,140 @@ impl AudioTrack {...@@ -202,20 +209,140 @@ impl AudioTrack {
202 }209 }
203}210}
204211
212fn downmix_weights(channels: Channels, count: usize) -> Vec<(f32, f32)> {
213 use std::f32::consts::FRAC_1_SQRT_2;
214 let mut weights: Vec<(f32, f32)> = channels
215 .iter()
216 .map(|ch| {
217 if ch.intersects(
218 Channels::FRONT_LEFT
219 | Channels::TOP_FRONT_LEFT
220 | Channels::FRONT_LEFT_WIDE
221 | Channels::FRONT_LEFT_HIGH,
222 ) {
223 (1.0, 0.0)
224 } else if ch.intersects(
225 Channels::FRONT_RIGHT
226 | Channels::TOP_FRONT_RIGHT
227 | Channels::FRONT_RIGHT_WIDE
228 | Channels::FRONT_RIGHT_HIGH,
229 ) {
230 (0.0, 1.0)
231 } else if ch.intersects(
232 Channels::FRONT_CENTRE
233 | Channels::TOP_CENTRE
234 | Channels::TOP_FRONT_CENTRE
235 | Channels::FRONT_CENTRE_HIGH,
236 ) {
237 (FRAC_1_SQRT_2, FRAC_1_SQRT_2)
238 } else if ch.intersects(Channels::FRONT_LEFT_CENTRE) {
239 (FRAC_1_SQRT_2, 0.0)
240 } else if ch.intersects(Channels::FRONT_RIGHT_CENTRE) {
241 (0.0, FRAC_1_SQRT_2)
242 } else if ch.intersects(
243 Channels::REAR_LEFT
244 | Channels::SIDE_LEFT
245 | Channels::TOP_REAR_LEFT
246 | Channels::REAR_LEFT_CENTRE,
247 ) {
248 (FRAC_1_SQRT_2, 0.0)
249 } else if ch.intersects(
250 Channels::REAR_RIGHT
251 | Channels::SIDE_RIGHT
252 | Channels::TOP_REAR_RIGHT
253 | Channels::REAR_RIGHT_CENTRE,
254 ) {
255 (0.0, FRAC_1_SQRT_2)
256 } else if ch.intersects(Channels::REAR_CENTRE | Channels::TOP_REAR_CENTRE) {
257 (0.5, 0.5)
258 } else if ch.intersects(Channels::LFE1 | Channels::LFE2) {
259 (0.0, 0.0)
260 } else {
261 (0.5, 0.5)
262 }
263 })
264 .collect();
265 while weights.len() < count {
266 let idx = weights.len();
267 weights.push(match idx {
268 0 => (1.0, 0.0),
269 1 => (0.0, 1.0),
270 _ => (0.5, 0.5),
271 });
272 }
273 weights.truncate(count);
274 weights
275}
276
277const CURSOR_GEN_MASK: u64 = 0xFFFF;
278const RAMP_SAMPLES: usize = 128;
279const RAMP_STEP: f32 = 1.0 / RAMP_SAMPLES as f32;
280
281#[inline]
282fn pack_cursor(time_secs: f64, seek_gen: u16) -> u64 {
283 let clean = if time_secs == 0.0 { 0.0 } else { time_secs };
284 (clean.to_bits() & !CURSOR_GEN_MASK) | u64::from(seek_gen)
285}
286
287#[inline]
288fn unpack_cursor(packed: u64) -> (f64, u16) {
289 (f64::from_bits(packed & !CURSOR_GEN_MASK), (packed & CURSOR_GEN_MASK) as u16)
290}
291
205struct SharedState {292struct SharedState {
206 playing: AtomicBool,293 playing: AtomicBool,
207 /// Current playback time in seconds (`f64::to_bits`), may be negative for leading silence.294 /// Atomically packed `(time_secs top-48-bit f64, 16-bit seek generation)` so seeks
208 cursor_secs_bits: AtomicU64,295 /// and RT advances are synchronized via a single lock-free CAS without TOCTOU races.
209 /// Monotonic generation bumped on seek/play_from so audio thread never overwrites a fresh seek.296 cursor_packed: AtomicU64,
210 seek_gen: AtomicU64,
211 volume_bits: AtomicU32,297 volume_bits: AtomicU32,
212 track: Mutex<Option<Arc<AudioTrack>>>,298 track: Mutex<Option<Arc<AudioTrack>>>,
213}299}
214300
301impl SharedState {
302 fn new() -> Self {
303 Self {
304 playing: AtomicBool::new(false),
305 cursor_packed: AtomicU64::new(pack_cursor(0.0, 0)),
306 volume_bits: AtomicU32::new(1.0_f32.to_bits()),
307 track: Mutex::new(None),
308 }
309 }
310
311 fn seek(&self, time_secs: f64) {
312 loop {
313 let cur = self.cursor_packed.load(Ordering::Acquire);
314 let (_, seek_gen) = unpack_cursor(cur);
315 let next = pack_cursor(time_secs, seek_gen.wrapping_add(1));
316 if self
317 .cursor_packed
318 .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
319 .is_ok()
320 {
321 break;
322 }
323 }
324 }
325
326 fn current_time_secs(&self) -> f64 {
327 unpack_cursor(self.cursor_packed.load(Ordering::Acquire)).0
328 }
329}
330
331#[derive(Default)]
332struct RenderRampState {
333 gain: f32,
334 last_gen: u16,
335 last_t_sec: f64,
336 initialized: bool,
337}
338
215/// Real-time non-blocking audio player backed by `cpal` (CoreAudio on macOS).339/// Real-time non-blocking audio player backed by `cpal` (CoreAudio on macOS).
216pub struct AudioPlayer {340pub struct AudioPlayer {
341 // Keep `_stream` first so dropping `AudioPlayer` stops the RT callback before
342 // `state` and `retired_tracks` are dropped on the main thread.
217 _stream: Stream,343 _stream: Stream,
218 state: Arc<SharedState>,344 state: Arc<SharedState>,
345 retired_tracks: Vec<Arc<AudioTrack>>,
219}346}
220347
221impl AudioPlayer {348impl AudioPlayer {
...@@ -235,13 +362,7 @@ impl AudioPlayer {...@@ -235,13 +362,7 @@ impl AudioPlayer {
235 let device_sr = config.sample_rate.0.max(1);362 let device_sr = config.sample_rate.0.max(1);
236 let device_channels = config.channels.max(1) as usize;363 let device_channels = config.channels.max(1) as usize;
237364
238 let state = Arc::new(SharedState {365 let state = Arc::new(SharedState::new());
239 playing: AtomicBool::new(false),
240 cursor_secs_bits: AtomicU64::new(0.0_f64.to_bits()),
241 seek_gen: AtomicU64::new(0),
242 volume_bits: AtomicU32::new(1.0_f32.to_bits()),
243 track: Mutex::new(None),
244 });
245366
246 let stream = match sample_format {367 let stream = match sample_format {
247 SampleFormat::F32 => {368 SampleFormat::F32 => {
...@@ -265,29 +386,40 @@ impl AudioPlayer {...@@ -265,29 +386,40 @@ impl AudioPlayer {
265 Ok(Self {386 Ok(Self {
266 _stream: stream,387 _stream: stream,
267 state,388 state,
389 retired_tracks: Vec::new(),
268 })390 })
269 }391 }
270392
393 fn reclaim_retired(&mut self) {
394 self.retired_tracks.retain(|t| Arc::strong_count(t) > 1);
395 }
396
271 pub fn set_track(&mut self, track: Option<Arc<AudioTrack>>) {397 pub fn set_track(&mut self, track: Option<Arc<AudioTrack>>) {
272 if let Ok(mut guard) = self.state.track.lock() {398 let prev = if let Ok(mut guard) = self.state.track.lock() {
273 *guard = track;399 std::mem::replace(&mut *guard, track)
400 } else {
401 None
402 };
403 if let Some(old) = prev {
404 self.retired_tracks.push(old);
274 }405 }
406 self.reclaim_retired();
275 }407 }
276408
277 pub fn play_from(&mut self, time_secs: f64) {409 pub fn play_from(&mut self, time_secs: f64) {
278 self.seek(time_secs);410 self.reclaim_retired();
411 self.state.seek(time_secs);
279 self.state.playing.store(true, Ordering::Release);412 self.state.playing.store(true, Ordering::Release);
280 }413 }
281414
282 pub fn seek(&mut self, time_secs: f64) {415 pub fn seek(&mut self, time_secs: f64) {
283 self.state416 self.reclaim_retired();
284 .cursor_secs_bits417 self.state.seek(time_secs);
285 .store(time_secs.to_bits(), Ordering::Release);
286 self.state.seek_gen.fetch_add(1, Ordering::AcqRel);
287 }418 }
288419
289 pub fn pause(&mut self) {420 pub fn pause(&mut self) {
290 self.state.playing.store(false, Ordering::Release);421 self.state.playing.store(false, Ordering::Release);
422 self.reclaim_retired();
291 }423 }
292424
293 pub fn set_volume(&mut self, vol: f32) {425 pub fn set_volume(&mut self, vol: f32) {
...@@ -295,6 +427,7 @@ impl AudioPlayer {...@@ -295,6 +427,7 @@ impl AudioPlayer {
295 self.state427 self.state
296 .volume_bits428 .volume_bits
297 .store(clamped.to_bits(), Ordering::Relaxed);429 .store(clamped.to_bits(), Ordering::Relaxed);
430 self.reclaim_retired();
298 }431 }
299432
300 pub fn is_playing(&self) -> bool {433 pub fn is_playing(&self) -> bool {
...@@ -302,7 +435,7 @@ impl AudioPlayer {...@@ -302,7 +435,7 @@ impl AudioPlayer {
302 }435 }
303436
304 pub fn current_time_secs(&self) -> f64 {437 pub fn current_time_secs(&self) -> f64 {
305 f64::from_bits(self.state.cursor_secs_bits.load(Ordering::Acquire))438 self.state.current_time_secs()
306 }439 }
307}440}
308441
...@@ -320,11 +453,12 @@ where...@@ -320,11 +453,12 @@ where
320 eprintln!("audio stream error: {err}");453 eprintln!("audio stream error: {err}");
321 };454 };
322455
456 let mut ramp = RenderRampState::default();
323 device457 device
324 .build_output_stream(458 .build_output_stream(
325 config,459 config,
326 move |data: &mut [T], _: &cpal::OutputCallbackInfo| {460 move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
327 render_audio_buffer(data, device_sr, device_channels, &state);461 render_audio_buffer(data, device_sr, device_channels, &state, &mut ramp);
328 },462 },
329 err_fn,463 err_fn,
330 None,464 None,
...@@ -332,17 +466,67 @@ where...@@ -332,17 +466,67 @@ where
332 .map_err(|e| format!("failed to build audio output stream: {e}"))466 .map_err(|e| format!("failed to build audio output stream: {e}"))
333}467}
334468
469#[inline]
470fn sample_track_stereo(
471 samples: &[f32],
472 total_frames: usize,
473 track_sr: f64,
474 t_sec: f64,
475 gain: f32,
476) -> (f32, f32) {
477 if total_frames == 0 || t_sec < 0.0 || gain <= 0.0 {
478 return (0.0, 0.0);
479 }
480 let src_pos = t_sec * track_sr;
481 if src_pos >= total_frames as f64 {
482 return (0.0, 0.0);
483 }
484 let idx0 = src_pos.floor() as usize;
485 let idx1 = (idx0 + 1).min(total_frames - 1);
486 let frac = (src_pos - idx0 as f64) as f32;
487 let l0 = samples[idx0 * 2];
488 let r0 = samples[idx0 * 2 + 1];
489 let l1 = samples[idx1 * 2];
490 let r1 = samples[idx1 * 2 + 1];
491 (
492 (l0 + (l1 - l0) * frac) * gain,
493 (r0 + (r1 - r0) * frac) * gain,
494 )
495}
496
497#[inline]
498fn write_stereo_frame<T: Sample + FromSample<f32>>(frame_out: &mut [T], l: f32, r: f32) {
499 if frame_out.len() == 1 {
500 frame_out[0] = T::from_sample(((l + r) * 0.5).clamp(-1.0, 1.0));
501 } else {
502 frame_out[0] = T::from_sample(l.clamp(-1.0, 1.0));
503 frame_out[1] = T::from_sample(r.clamp(-1.0, 1.0));
504 let zero = T::from_sample(0.0_f32);
505 for ch in &mut frame_out[2..] {
506 *ch = zero;
507 }
508 }
509}
510
335fn render_audio_buffer<T>(511fn render_audio_buffer<T>(
336 data: &mut [T],512 data: &mut [T],
337 device_sr: u32,513 device_sr: u32,
338 device_channels: usize,514 device_channels: usize,
339 state: &SharedState,515 state: &SharedState,
516 ramp: &mut RenderRampState,
340) where517) where
341 T: Sample + FromSample<f32>,518 T: Sample + FromSample<f32>,
342{519{
343 if !state.playing.load(Ordering::Acquire) {520 let playing = state.playing.load(Ordering::Acquire);
521 let mut start_packed = state.cursor_packed.load(Ordering::Acquire);
522 let (mut cur_t_sec, mut cur_gen) = unpack_cursor(start_packed);
523
524 if !playing && ramp.gain <= 0.0 {
344 let zero = T::from_sample(0.0_f32);525 let zero = T::from_sample(0.0_f32);
345 data.fill(zero);526 data.fill(zero);
527 ramp.last_gen = cur_gen;
528 ramp.last_t_sec = cur_t_sec;
529 ramp.initialized = true;
346 return;530 return;
347 }531 }
348532
...@@ -354,57 +538,90 @@ fn render_audio_buffer<T>(...@@ -354,57 +538,90 @@ fn render_audio_buffer<T>(
354 let Some(track) = track_opt else {538 let Some(track) = track_opt else {
355 let zero = T::from_sample(0.0_f32);539 let zero = T::from_sample(0.0_f32);
356 data.fill(zero);540 data.fill(zero);
541 ramp.gain = 0.0;
357 return;542 return;
358 };543 };
359544
545 if !ramp.initialized {
546 ramp.last_gen = cur_gen;
547 ramp.last_t_sec = cur_t_sec;
548 ramp.initialized = true;
549 }
550
360 let total_frames = track.samples.len() / 2;551 let total_frames = track.samples.len() / 2;
361 let track_sr = track.sample_rate as f64;552 let track_sr = track.sample_rate as f64;
362 let vol = f32::from_bits(state.volume_bits.load(Ordering::Relaxed));553 let vol = f32::from_bits(state.volume_bits.load(Ordering::Relaxed));
363 let gen_before = state.seek_gen.load(Ordering::Acquire);554 let dt = 1.0 / device_sr.max(1) as f64;
364 let mut t_sec = f64::from_bits(state.cursor_secs_bits.load(Ordering::Acquire));
365 let dt = 1.0 / device_sr as f64;
366 let samples = &track.samples;555 let samples = &track.samples;
367556
368 for frame_out in data.chunks_exact_mut(device_channels) {557 for frame_out in data.chunks_exact_mut(device_channels) {
369 let (l, r) = if total_frames > 0 && t_sec >= 0.0 {558 if !playing {
370 let src_pos = t_sec * track_sr;559 if ramp.gain > 0.0 {
371 if src_pos < total_frames as f64 {560 ramp.gain = (ramp.gain - RAMP_STEP).max(0.0);
372 let idx0 = src_pos.floor() as usize;561 let (l, r) = sample_track_stereo(
373 let idx1 = (idx0 + 1).min(total_frames - 1);562 samples,
374 let frac = (src_pos - idx0 as f64) as f32;563 total_frames,
375 let l0 = samples[idx0 * 2];564 track_sr,
376 let r0 = samples[idx0 * 2 + 1];565 ramp.last_t_sec,
377 let l1 = samples[idx1 * 2];566 vol * ramp.gain,
378 let r1 = samples[idx1 * 2 + 1];567 );
379 (568 write_stereo_frame(frame_out, l, r);
380 (l0 + (l1 - l0) * frac) * vol,569 ramp.last_t_sec += dt;
381 (r0 + (r1 - r0) * frac) * vol,
382 )
383 } else {570 } else {
384 (0.0, 0.0)571 write_stereo_frame(frame_out, 0.0, 0.0);
385 }572 }
386 } else {573 continue;
387 (0.0, 0.0)574 }
388 };
389575
390 if device_channels == 1 {576 if ramp.last_gen != cur_gen {
391 frame_out[0] = T::from_sample(((l + r) * 0.5).clamp(-1.0, 1.0));577 if ramp.gain > 0.0 {
392 } else {578 // Smoothly fade out old playback position before jumping to sought cursor.
393 frame_out[0] = T::from_sample(l.clamp(-1.0, 1.0));579 ramp.gain = (ramp.gain - RAMP_STEP).max(0.0);
394 frame_out[1] = T::from_sample(r.clamp(-1.0, 1.0));580 let (l, r) = sample_track_stereo(
395 let zero = T::from_sample(0.0_f32);581 samples,
396 for ch in &mut frame_out[2..] {582 total_frames,
397 *ch = zero;583 track_sr,
584 ramp.last_t_sec,
585 vol * ramp.gain,
586 );
587 write_stereo_frame(frame_out, l, r);
588 ramp.last_t_sec += dt;
589 if ramp.gain <= 0.0 {
590 start_packed = state.cursor_packed.load(Ordering::Acquire);
591 let (new_t, new_gen) = unpack_cursor(start_packed);
592 cur_t_sec = new_t;
593 cur_gen = new_gen;
594 ramp.last_gen = new_gen;
595 ramp.last_t_sec = new_t;
596 }
597 continue;
398 }598 }
599 ramp.last_gen = cur_gen;
600 ramp.last_t_sec = cur_t_sec;
399 }601 }
400602
401 t_sec += dt;603 if ramp.gain < 1.0 {
604 ramp.gain = (ramp.gain + RAMP_STEP).min(1.0);
605 }
606 let (l, r) = sample_track_stereo(
607 samples,
608 total_frames,
609 track_sr,
610 ramp.last_t_sec,
611 vol * ramp.gain,
612 );
613 write_stereo_frame(frame_out, l, r);
614 ramp.last_t_sec += dt;
402 }615 }
403616
404 if state.seek_gen.load(Ordering::Acquire) == gen_before {617 if playing && ramp.last_gen == cur_gen {
405 state618 let next_packed = pack_cursor(ramp.last_t_sec, cur_gen);
406 .cursor_secs_bits619 let _ = state.cursor_packed.compare_exchange(
407 .store(t_sec.to_bits(), Ordering::Release);620 start_packed,
621 next_packed,
622 Ordering::AcqRel,
623 Ordering::Acquire,
624 );
408 }625 }
409}626}
410627
...@@ -520,4 +737,102 @@ mod tests {...@@ -520,4 +737,102 @@ mod tests {
520 let _ = std::fs::remove_file(&wav_path);737 let _ = std::fs::remove_file(&wav_path);
521 let _ = std::fs::remove_file(&mp3_path);738 let _ = std::fs::remove_file(&mp3_path);
522 }739 }
740
741 #[test]
742 fn test_audio_5_1_downmix_preserves_center_channel() {
743 let wav_51 = std::env::temp_dir().join(format!("engine_test_51_center_{}.wav", std::process::id()));
744 let ok = Command::new("ffmpeg")
745 .args([
746 "-y",
747 "-v",
748 "error",
749 "-filter_complex",
750 "anullsrc=r=44100:cl=mono:d=0.4,asplit=5[z0][z1][z2][z3][z4];sine=f=440:r=44100:d=0.4,volume=6[c];[z0][z1][c][z2][z3][z4]join=inputs=6:channel_layout=5.1:map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]",
751 "-map",
752 "[a]",
753 "-c:a",
754 "pcm_s16le",
755 ])
756 .arg(&wav_51)
757 .status()
758 .is_ok_and(|s| s.success());
759 assert!(ok, "ffmpeg failed to generate 5.1 test wav");
760
761 let track = AudioTrack::load(&wav_51).expect("load 5.1 wav");
762 assert_eq!(track.channels, 2);
763 let r = rms(&track.samples);
764 assert!(
765 r > 0.2,
766 "5.1 downmix must preserve center channel dialogue (got RMS={r})"
767 );
768 let _ = std::fs::remove_file(&wav_51);
769 }
770
771 #[test]
772 fn test_audio_concurrent_seek_and_render_ramp() {
773 let track = Arc::new(AudioTrack {
774 path: PathBuf::from("synthetic.wav"),
775 sample_rate: 48000,
776 channels: 2,
777 samples: Arc::new(vec![0.8_f32; 48000 * 10 * 2]),
778 duration_secs: 10.0,
779 });
780
781 let state = Arc::new(SharedState::new());
782 {
783 let mut g = state.track.lock().unwrap();
784 *g = Some(Arc::clone(&track));
785 }
786
787 // Verify play fade-in and pause fade-out ramps (~128 samples).
788 let mut ramp = RenderRampState::default();
789 let mut buf = vec![0.0_f32; 256 * 2];
790 state.seek(1.0);
791 state.playing.store(true, Ordering::Release);
792 render_audio_buffer(&mut buf, 48000, 2, &state, &mut ramp);
793 assert!(buf[0].abs() < 0.02, "first fade-in sample should be near zero, got {}", buf[0]);
794 assert!(
795 (buf[127 * 2] - 0.8).abs() < 0.02,
796 "128th sample should reach full amplitude, got {}",
797 buf[127 * 2]
798 );
799
800 state.playing.store(false, Ordering::Release);
801 render_audio_buffer(&mut buf, 48000, 2, &state, &mut ramp);
802 assert!(buf[0] > 0.7, "pause fade-out should start smoothly near 0.8, got {}", buf[0]);
803 assert_eq!(buf[128 * 2], 0.0, "pause fade-out should settle to 0.0 by sample 128");
804
805 // Concurrent stress test: seeks landing mid-render must never be overwritten backward by RT advance.
806 state.playing.store(true, Ordering::Release);
807 let stop = Arc::new(AtomicBool::new(false));
808 let state_rt = Arc::clone(&state);
809 let stop_rt = Arc::clone(&stop);
810 let rt_handle = std::thread::spawn(move || {
811 let mut rt_ramp = RenderRampState::default();
812 let mut rt_buf = vec![0.0_f32; 256 * 2];
813 while !stop_rt.load(Ordering::Acquire) {
814 render_audio_buffer(&mut rt_buf, 48000, 2, &state_rt, &mut rt_ramp);
815 std::thread::yield_now();
816 }
817 });
818
819 for i in 0..500 {
820 let target = (i % 10) as f64 * 0.4 + 0.1;
821 state.seek(target);
822 if i % 10 == 0 {
823 std::thread::yield_now();
824 }
825 }
826 let final_target = 9.0_f64;
827 state.seek(final_target);
828 std::thread::sleep(std::time::Duration::from_millis(2));
829 stop.store(true, Ordering::Release);
830 rt_handle.join().unwrap();
831
832 let observed = state.current_time_secs();
833 assert!(
834 observed >= final_target - 1e-6,
835 "RT callback overwrote final seek {final_target} backward -> {observed}"
836 );
837 }
523}838}
crates/engine/src/av_decode.m+65-27
...@@ -6,6 +6,7 @@...@@ -6,6 +6,7 @@
6#include <math.h>6#include <math.h>
7#include <stdint.h>7#include <stdint.h>
8#include <stddef.h>8#include <stddef.h>
9#include <string.h>
910
10#pragma clang diagnostic push11#pragma clang diagnostic push
11#pragma clang diagnostic ignored "-Wdeprecated-declarations"12#pragma clang diagnostic ignored "-Wdeprecated-declarations"
...@@ -21,7 +22,10 @@...@@ -21,7 +22,10 @@
21@property(nonatomic, assign) double fps;22@property(nonatomic, assign) double fps;
22@property(nonatomic, assign) int64_t nbFrames;23@property(nonatomic, assign) int64_t nbFrames;
23@property(nonatomic, assign) double trackStartSec;24@property(nonatomic, assign) double trackStartSec;
25@property(nonatomic, assign) double durSec;
24@property(nonatomic, assign) int64_t lastFrameIdx;26@property(nonatomic, assign) int64_t lastFrameIdx;
27@property(nonatomic, strong) NSMutableData *lastFrameRgba;
28@property(nonatomic, assign) BOOL hasLastFrame;
25@end29@end
2630
27@implementation AvVideoDecoderObj31@implementation AvVideoDecoderObj
...@@ -256,7 +260,10 @@ AvVideoDecoder *av_video_open(...@@ -256,7 +260,10 @@ AvVideoDecoder *av_video_open(
256 obj.fps = fps;260 obj.fps = fps;
257 obj.nbFrames = nbFrames;261 obj.nbFrames = nbFrames;
258 obj.trackStartSec = trackStartSec;262 obj.trackStartSec = trackStartSec;
263 obj.durSec = durSec;
259 obj.lastFrameIdx = -1;264 obj.lastFrameIdx = -1;
265 obj.lastFrameRgba = [NSMutableData dataWithLength:(NSUInteger)outW * (NSUInteger)outH * 4];
266 obj.hasLastFrame = NO;
260267
261 // Verify AVAssetReader can actually open and decode this asset/codec.268 // Verify AVAssetReader can actually open and decode this asset/codec.
262 if (![obj openReaderAtSeconds:0.0]) {269 if (![obj openReaderAtSeconds:0.0]) {
...@@ -271,6 +278,42 @@ AvVideoDecoder *av_video_open(...@@ -271,6 +278,42 @@ AvVideoDecoder *av_video_open(
271 }278 }
272}279}
273280
281static CMSampleBufferRef read_target_sample(
282 AvVideoDecoderObj *obj,
283 double targetPts,
284 double halfFrame
285) {
286 CMSampleBufferRef chosen = NULL;
287 CMSampleBufferRef lastSeen = NULL;
288
289 while (obj.reader.status == AVAssetReaderStatusReading) {
290 CMSampleBufferRef sb = [obj.output copyNextSampleBuffer];
291 if (!sb) {
292 break;
293 }
294 CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb);
295 double pts = CMTIME_IS_NUMERIC(ptsTime) ? CMTimeGetSeconds(ptsTime) : targetPts;
296
297 if (pts + halfFrame >= targetPts) {
298 chosen = sb;
299 break;
300 }
301 if (lastSeen) {
302 CFRelease(lastSeen);
303 }
304 lastSeen = sb;
305 }
306
307 if (!chosen && lastSeen) {
308 chosen = lastSeen;
309 lastSeen = NULL;
310 }
311 if (lastSeen) {
312 CFRelease(lastSeen);
313 }
314 return chosen;
315}
316
274int av_video_decode_frame(317int av_video_decode_frame(
275 AvVideoDecoder *dec,318 AvVideoDecoder *dec,
276 int64_t frame_idx,319 int64_t frame_idx,
...@@ -285,6 +328,10 @@ int av_video_decode_frame(...@@ -285,6 +328,10 @@ int av_video_decode_frame(
285 if (frame_idx < 0) {328 if (frame_idx < 0) {
286 frame_idx = 0;329 frame_idx = 0;
287 }330 }
331 size_t required = (size_t)obj.width * (size_t)obj.height * 4;
332 if (out_len < required) {
333 return 0;
334 }
288 double fps = obj.fps > 0.0 ? obj.fps : 30.0;335 double fps = obj.fps > 0.0 ? obj.fps : 30.0;
289 double targetPts = obj.trackStartSec + ((double)frame_idx) / fps;336 double targetPts = obj.trackStartSec + ((double)frame_idx) / fps;
290 double halfFrame = 0.45 / fps;337 double halfFrame = 0.45 / fps;
...@@ -296,45 +343,32 @@ int av_video_decode_frame(...@@ -296,45 +343,32 @@ int av_video_decode_frame(
296 (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx &&343 (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx &&
297 frame_idx <= obj.lastFrameIdx + 8));344 frame_idx <= obj.lastFrameIdx + 8));
298345
346 double seekSec = 0.0;
299 if (!canAdvance) {347 if (!canAdvance) {
300 double seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps));348 seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps));
301 if (![obj openReaderAtSeconds:seekSec]) {349 if (![obj openReaderAtSeconds:seekSec]) {
302 return 0;350 return 0;
303 }351 }
304 }352 }
305353
306 CMSampleBufferRef chosen = NULL;354 CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame);
307 CMSampleBufferRef lastSeen = NULL;
308355
309 while (obj.reader.status == AVAssetReaderStatusReading) {356 // If requesting a frame slightly past EOF (e.g., llround(durSec * fps) rounding up by 1),
310 CMSampleBufferRef sb = [obj.output copyNextSampleBuffer];357 // retry once from slightly before end if we didn't hit a sample, or hold the last valid frame.
311 if (!sb) {358 if (!chosen && !canAdvance && frame_idx > 0) {
312 break;359 double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts;
360 double fallbackSec = fmax(0.0, endAnchor - 1.0);
361 if (fallbackSec < seekSec - 0.05 && [obj openReaderAtSeconds:fallbackSec]) {
362 chosen = read_target_sample(obj, targetPts, halfFrame);
313 }363 }
314 CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb);
315 double pts = CMTIME_IS_NUMERIC(ptsTime) ? CMTimeGetSeconds(ptsTime) : targetPts;
316
317 if (pts + halfFrame >= targetPts) {
318 chosen = sb;
319 break;
320 }
321 if (lastSeen) {
322 CFRelease(lastSeen);
323 }
324 lastSeen = sb;
325 }
326
327 if (!chosen && lastSeen) {
328 chosen = lastSeen;
329 lastSeen = NULL;
330 }
331 if (lastSeen) {
332 CFRelease(lastSeen);
333 lastSeen = NULL;
334 }364 }
335365
336 if (!chosen) {366 if (!chosen) {
337 [obj closeReader];367 [obj closeReader];
368 if (obj.hasLastFrame && frame_idx > 0 && obj.lastFrameRgba.length >= required) {
369 memcpy(out_rgba, obj.lastFrameRgba.bytes, required);
370 return 1;
371 }
338 return 0;372 return 0;
339 }373 }
340374
...@@ -344,6 +378,10 @@ int av_video_decode_frame(...@@ -344,6 +378,10 @@ int av_video_decode_frame(
344 CFRelease(chosen);378 CFRelease(chosen);
345379
346 if (ok) {380 if (ok) {
381 if (obj.lastFrameRgba.length >= required) {
382 memcpy(obj.lastFrameRgba.mutableBytes, out_rgba, required);
383 obj.hasLastFrame = YES;
384 }
347 obj.lastFrameIdx = frame_idx;385 obj.lastFrameIdx = frame_idx;
348 } else {386 } else {
349 [obj closeReader];387 [obj closeReader];
crates/engine/src/export.rs+280-41
...@@ -479,6 +479,85 @@ pub fn export_node_video_ffmpeg(...@@ -479,6 +479,85 @@ pub fn export_node_video_ffmpeg(
479 export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress)479 export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress)
480}480}
481481
482fn probe_audio_duration_secs(path: &Path) -> Option<f64> {
483 let out = Command::new("ffprobe")
484 .args([
485 "-v",
486 "error",
487 "-select_streams",
488 "a:0",
489 "-show_entries",
490 "stream=codec_type,duration",
491 "-show_entries",
492 "format=duration",
493 "-of",
494 "default=noprint_wrappers=1",
495 ])
496 .arg(path)
497 .output()
498 .ok()?;
499 if !out.status.success() {
500 return None;
501 }
502 let text = String::from_utf8_lossy(&out.stdout);
503 let mut has_audio_stream = false;
504 let mut stream_dur: Option<f64> = None;
505 let mut format_dur: Option<f64> = None;
506 let mut in_stream = false;
507 for line in text.lines() {
508 let Some((k, v)) = line.split_once('=') else {
509 continue;
510 };
511 let key = k.trim();
512 let val = v.trim();
513 match key {
514 "codec_type" => {
515 in_stream = true;
516 if val == "audio" {
517 has_audio_stream = true;
518 }
519 }
520 "duration" => {
521 if let Ok(d) = val.parse::<f64>() {
522 if d.is_finite() && d >= 0.0 {
523 if in_stream && stream_dur.is_none() {
524 stream_dur = Some(d);
525 } else if !in_stream && format_dur.is_none() {
526 format_dur = Some(d);
527 }
528 }
529 }
530 in_stream = false;
531 }
532 _ => {}
533 }
534 }
535 if !has_audio_stream {
536 return Some(0.0);
537 }
538 stream_dur.or(format_dur)
539}
540
541fn fit_frame_rgba(
542 pixels: Vec<u8>,
543 src_size: [u32; 2],
544 dst_size: [u32; 2],
545 frame: i64,
546) -> Result<Vec<u8>, String> {
547 if src_size == dst_size {
548 return Ok(pixels);
549 }
550 let img = image::RgbaImage::from_raw(src_size[0], src_size[1], pixels)
551 .ok_or_else(|| format!("invalid RGBA buffer size at frame {frame}"))?;
552 Ok(image::imageops::resize(
553 &img,
554 dst_size[0],
555 dst_size[1],
556 image::imageops::FilterType::Triangle,
557 )
558 .into_raw())
559}
560
482/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames561/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
483/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.562/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.
484pub fn export_node_video_ffmpeg_with_progress(563pub fn export_node_video_ffmpeg_with_progress(
...@@ -521,13 +600,30 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -521,13 +600,30 @@ pub fn export_node_video_ffmpeg_with_progress(
521600
522 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.601 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
523 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);602 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
524 let [width, height] = first_tex.size;603 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
525 if width == 0 || height == 0 {604 return Err(format!(
526 return Err(format!("target '{}' produced empty frame {}x{}", node_name, width, height));605 "target '{}' produced empty frame {}x{}",
606 node_name, first_tex.size[0], first_tex.size[1]
607 ));
527 }608 }
528 let first_pixels = engine609 // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp
610 // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2.
611 let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 {
612 let ps = engine.proxy_scale.max(1);
613 let fw = (comp.width / ps).max(2);
614 let fh = (comp.height / ps).max(2);
615 if opts.codec == VideoCodec::H264Share {
616 (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2))
617 } else {
618 (fw, fh)
619 }
620 } else {
621 (first_tex.size[0], first_tex.size[1])
622 };
623 let raw_first = engine
529 .readback_rgba(&first_tex)624 .readback_rgba(&first_tex)
530 .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?;625 .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?;
626 let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start)?;
531 if control.is_some_and(ExportControl::is_cancelled) {627 if control.is_some_and(ExportControl::is_cancelled) {
532 return Err("Cancelled".to_owned());628 return Err("Cancelled".to_owned());
533 }629 }
...@@ -538,7 +634,17 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -538,7 +634,17 @@ pub fn export_node_video_ffmpeg_with_progress(
538 comp.audio_filename634 comp.audio_filename
539 .as_deref()635 .as_deref()
540 .map(PathBuf::from)636 .map(PathBuf::from)
541 .filter(|p| !p.as_os_str().is_empty() && p.exists() && -audio_start_secs < duration_secs)637 .filter(|p| {
638 if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs {
639 return false;
640 }
641 if let Some(audio_dur) = probe_audio_duration_secs(p) {
642 if audio_dur <= 0.0 || audio_start_secs >= audio_dur {
643 return false;
644 }
645 }
646 true
647 })
542 } else {648 } else {
543 None649 None
544 };650 };
...@@ -559,25 +665,23 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -559,25 +665,23 @@ pub fn export_node_video_ffmpeg_with_progress(
559 "pipe:0",665 "pipe:0",
560 ]);666 ]);
561667
562 if let Some(ap) = &audio_path {668 let audio_filter = if let Some(ap) = &audio_path {
563 if audio_start_secs >= 0.0 {669 if audio_start_secs >= 0.0 {
564 cmd.args([670 if audio_start_secs > 0.0 {
565 "-ss",671 cmd.args(["-ss", &format!("{audio_start_secs:.6}")]);
566 &format!("{audio_start_secs:.6}"),672 }
567 "-t",673 cmd.arg("-i").arg(ap);
568 &format!("{duration_secs:.6}"),674 Some(format!("asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}"))
569 "-i",
570 ]);
571 cmd.arg(ap);
572 } else {675 } else {
573 cmd.args([676 let delay_ms = (-audio_start_secs * 1000.0).max(0.0);
574 "-itsoffset",677 cmd.arg("-i").arg(ap);
575 &format!("{:.6}", -audio_start_secs),678 Some(format!(
576 "-i",679 "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS"
577 ]);680 ))
578 cmd.arg(ap);
579 }681 }
580 }682 } else {
683 None
684 };
581685
582 let (out_width, out_height) = match opts.codec {686 let (out_width, out_height) = match opts.codec {
583 VideoCodec::H264Share => {687 VideoCodec::H264Share => {
...@@ -635,8 +739,8 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -635,8 +739,8 @@ pub fn export_node_video_ffmpeg_with_progress(
635 }739 }
636 };740 };
637741
638 if has_audio {742 if let Some(af) = audio_filter {
639 cmd.args(["-map", "0:v:0", "-map", "1:a:0"]);743 cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]);
640 match opts.codec {744 match opts.codec {
641 VideoCodec::H264Share => {745 VideoCodec::H264Share => {
642 cmd.args(["-c:a", "aac", "-b:a", "128k"]);746 cmd.args(["-c:a", "aac", "-b:a", "128k"]);
...@@ -645,10 +749,6 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -645,10 +749,6 @@ pub fn export_node_video_ffmpeg_with_progress(
645 cmd.args(["-c:a", "pcm_s16le"]);749 cmd.args(["-c:a", "pcm_s16le"]);
646 }750 }
647 }751 }
648 if audio_start_secs < 0.0 {
649 cmd.args(["-t", &format!("{duration_secs:.6}")]);
650 }
651 cmd.arg("-shortest");
652 } else {752 } else {
653 cmd.arg("-an");753 cmd.arg("-an");
654 }754 }
...@@ -713,21 +813,12 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -713,21 +813,12 @@ pub fn export_node_video_ffmpeg_with_progress(
713 cancelled = true;813 cancelled = true;
714 break;814 break;
715 }815 }
716 let frame_bytes = if tex.size != [width, height] {816 let frame_bytes = match fit_frame_rgba(pixels, tex.size, [width, height], frame) {
717 let Some(img) = image::RgbaImage::from_raw(tex.size[0], tex.size[1], pixels)817 Ok(bytes) => bytes,
718 else {818 Err(e) => {
719 pipe_err = Some(format!("invalid RGBA buffer size at frame {frame}"));819 pipe_err = Some(e);
720 break;820 break;
721 };821 }
722 image::imageops::resize(
723 &img,
724 width,
725 height,
726 image::imageops::FilterType::Triangle,
727 )
728 .into_raw()
729 } else {
730 pixels
731 };822 };
732823
733 if let Err(e) = stdin.write_all(&frame_bytes) {824 if let Err(e) = stdin.write_all(&frame_bytes) {
...@@ -752,6 +843,9 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -752,6 +843,9 @@ pub fn export_node_video_ffmpeg_with_progress(
752 let _ = stdin.flush();843 let _ = stdin.flush();
753 }844 }
754845
846 if cancelled || pipe_err.is_some() {
847 let _ = child.kill();
848 }
755 let status = child849 let status = child
756 .wait()850 .wait()
757 .map_err(|e| format!("failed waiting on ffmpeg: {e}"))?;851 .map_err(|e| format!("failed waiting on ffmpeg: {e}"))?;
...@@ -1242,4 +1336,149 @@ mod tests {...@@ -1242,4 +1336,149 @@ mod tests {
12421336
1243 let _ = std::fs::remove_dir_all(&tmp_dir);1337 let _ = std::fs::remove_dir_all(&tmp_dir);
1244 }1338 }
1339
1340 #[test]
1341 fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() {
1342 let tmp_dir = std::env::temp_dir().join(format!(
1343 "fission-video-edge-cases-{}",
1344 std::process::id()
1345 ));
1346 let _ = std::fs::remove_dir_all(&tmp_dir);
1347 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1348
1349 let short_wav = tmp_dir.join("short.wav");
1350 write_test_wav(&short_wav, 44100, 0.15);
1351 let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\");
1352
1353 // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video.
1354 let comp_src = format!(
1355 r#"Composition {{
1356 CurrentTime = 0,
1357 RenderRange = {{ 0, 23 }},
1358 GlobalRange = {{ 0, 23 }},
1359 AudioFilename = "{wav_escaped}",
1360 AudioOffset = 0,
1361 Tools = ordered() {{
1362 BG = Background {{
1363 Inputs = {{
1364 Width = Input {{ Value = 127, }},
1365 Height = Input {{ Value = 71, }},
1366 TopLeftRed = Input {{ Value = 0.4, }},
1367 TopLeftGreen = Input {{ Value = 0.5, }},
1368 TopLeftBlue = Input {{ Value = 0.6, }},
1369 TopLeftAlpha = Input {{ Value = 1, }},
1370 }},
1371 }},
1372 }},
1373 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }},
1374}}"#
1375 );
1376 let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp");
1377 let target = comp.find_node("BG").unwrap();
1378 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1379
1380 let short_mp4 = tmp_dir.join("short_audio_odd.mp4");
1381 let summary = export_node_video_ffmpeg(
1382 &mut engine,
1383 &comp,
1384 &VideoExportOptions {
1385 target,
1386 out_path: short_mp4.clone(),
1387 range: [0, 23],
1388 codec: VideoCodec::H264Share,
1389 crf: 26,
1390 max_height: None,
1391 include_audio: true,
1392 hiq: true,
1393 proxy_scale: 1,
1394 },
1395 |_| {},
1396 )
1397 .expect("export with short audio and odd dimensions should succeed without Broken pipe");
1398 assert_eq!(summary.frames_written, 24);
1399 assert_eq!(summary.width, 126);
1400 assert_eq!(summary.height, 70);
1401 assert!(summary.has_audio);
1402
1403 // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`).
1404 let mut past_eof_comp = comp.clone();
1405 past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s
1406 let past_mp4 = tmp_dir.join("past_eof.mp4");
1407 let past_summary = export_node_video_ffmpeg(
1408 &mut engine,
1409 &past_eof_comp,
1410 &VideoExportOptions {
1411 target,
1412 out_path: past_mp4.clone(),
1413 range: [0, 5],
1414 codec: VideoCodec::H264Share,
1415 crf: 26,
1416 max_height: None,
1417 include_audio: true,
1418 hiq: true,
1419 proxy_scale: 1,
1420 },
1421 |_| {},
1422 )
1423 .expect("export with audio past EOF should skip audio and succeed");
1424 assert_eq!(past_summary.frames_written, 6);
1425 assert!(!past_summary.has_audio);
1426
1427 // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas.
1428 let seq1 = tmp_dir.join("seq_0001.png");
1429 image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255]))
1430 .save(&seq1)
1431 .unwrap();
1432 let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent
1433 let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\");
1434 let dummy_comp_src = format!(
1435 r#"Composition {{
1436 CurrentTime = 0,
1437 RenderRange = {{ 0, 1 }},
1438 GlobalRange = {{ 0, 1 }},
1439 Tools = ordered() {{
1440 LD = Loader {{
1441 Clips = {{
1442 Clip {{
1443 ID = "Clip1",
1444 Filename = "{seq0_esc}",
1445 FormatID = "PNGFormat",
1446 StartFrame = 0,
1447 Length = 2,
1448 GlobalStart = 0,
1449 GlobalEnd = 1,
1450 }},
1451 }},
1452 }},
1453 }},
1454 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }},
1455}}"#
1456 );
1457 let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp");
1458 let ld = dummy_comp.find_node("LD").unwrap();
1459 engine.bust_all_caches();
1460 let dummy_mp4 = tmp_dir.join("dummy_first.mp4");
1461 let dummy_summary = export_node_video_ffmpeg(
1462 &mut engine,
1463 &dummy_comp,
1464 &VideoExportOptions {
1465 target: ld,
1466 out_path: dummy_mp4.clone(),
1467 range: [0, 1],
1468 codec: VideoCodec::H264Share,
1469 crf: 26,
1470 max_height: None,
1471 include_audio: false,
1472 hiq: true,
1473 proxy_scale: 1,
1474 },
1475 |_| {},
1476 )
1477 .expect("export with 1x1 first frame should fall back to comp dimensions");
1478 assert_eq!(dummy_summary.frames_written, 2);
1479 assert_eq!(dummy_summary.width, 64);
1480 assert_eq!(dummy_summary.height, 36);
1481
1482 let _ = std::fs::remove_dir_all(&tmp_dir);
1483 }
1245}1484}
crates/engine/src/media.rs+568-91
...@@ -339,9 +339,113 @@ fn is_exr_path(path: &Path) -> bool {...@@ -339,9 +339,113 @@ fn is_exr_path(path: &Path) -> bool {
339 .is_some_and(|e| e.eq_ignore_ascii_case("exr"))339 .is_some_and(|e| e.eq_ignore_ascii_case("exr"))
340}340}
341341
342fn full_exr_channel_name(layer_name: Option<&str>, ch_name: &str) -> String {
343 match layer_name {
344 Some(ln) if !ln.is_empty() && !ch_name.starts_with(&format!("{ln}.")) => {
345 format!("{ln}.{ch_name}")
346 }
347 _ => ch_name.to_owned(),
348 }
349}
350
351fn normalize_channel_opt(opt: Option<&str>) -> Option<String> {
352 opt.map(str::trim)
353 .filter(|s| !s.is_empty())
354 .map(str::to_owned)
355}
356
357fn apply_post_multiply_rgba8(raw: &mut [u8]) {
358 for px in raw.chunks_exact_mut(4) {
359 let a = u16::from(px[3]);
360 if a < 255 {
361 px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8;
362 px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8;
363 px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8;
364 }
365 }
366}
367
368fn find_exr_channel_loc(
369 headers: &[exr::meta::header::Header],
370 w: usize,
371 h: usize,
372 preferred: Option<&str>,
373 beauty_upper: &str,
374 beauty_lower: &str,
375) -> Option<(usize, usize)> {
376 let valid_layer = |header: &exr::meta::header::Header| {
377 !header.deep && header.layer_size.width() == w && header.layer_size.height() == h
378 };
379
380 if let Some(pref) = preferred.map(str::trim).filter(|s| !s.is_empty()) {
381 for (li, header) in headers.iter().enumerate() {
382 if !valid_layer(header) {
383 continue;
384 }
385 let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string());
386 for (ci, ch) in header.channels.list.iter().enumerate() {
387 if ch.sampling != exr::math::Vec2(1, 1) {
388 continue;
389 }
390 let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string());
391 if full == pref {
392 return Some((li, ci));
393 }
394 }
395 }
396 let suffix = format!(".{pref}");
397 for (li, header) in headers.iter().enumerate() {
398 if !valid_layer(header) {
399 continue;
400 }
401 let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string());
402 for (ci, ch) in header.channels.list.iter().enumerate() {
403 if ch.sampling != exr::math::Vec2(1, 1) {
404 continue;
405 }
406 let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string());
407 if full.ends_with(&suffix) {
408 return Some((li, ci));
409 }
410 }
411 }
412 return None;
413 }
414
415 // Beauty pass fallback: check ViewLayer.Combined.<C>, Combined.<C>, *.Combined.<C>,
416 // then exact bare <C>/<c>. Never match non-beauty layers such as CryptoObject00.R!
417 let view_combined = format!("ViewLayer.Combined.{beauty_upper}");
418 let combined = format!("Combined.{beauty_upper}");
419 let any_combined = format!(".Combined.{beauty_upper}");
420 let matcher_passes: [&dyn Fn(&str) -> bool; 4] = [
421 &|full: &str| full == view_combined,
422 &|full: &str| full == combined || full.ends_with(&any_combined),
423 &|full: &str| full == beauty_upper,
424 &|full: &str| full == beauty_lower,
425 ];
426 for pred in matcher_passes {
427 for (li, header) in headers.iter().enumerate() {
428 if !valid_layer(header) {
429 continue;
430 }
431 let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string());
432 for (ci, ch) in header.channels.list.iter().enumerate() {
433 if ch.sampling != exr::math::Vec2(1, 1) {
434 continue;
435 }
436 let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string());
437 if pred(&full) {
438 return Some((li, ci));
439 }
440 }
441 }
442 }
443 None
444}
445
342/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR446/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR
343/// into both clamped RGBA8 (`u8`, linear [0..1] preview for Fast mode / 8-bit pipelines)447/// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR
344/// and unclamped linear HDR RGBA32F (`f32`, preserving highlights `> 1.0` and negative values).448/// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers.
345fn decode_exr_rgba(449fn decode_exr_rgba(
346 path: &Path,450 path: &Path,
347 red_name: Option<&str>,451 red_name: Option<&str>,
...@@ -350,81 +454,125 @@ fn decode_exr_rgba(...@@ -350,81 +454,125 @@ fn decode_exr_rgba(
350 alpha_name: Option<&str>,454 alpha_name: Option<&str>,
351 post_multiply: bool,455 post_multiply: bool,
352) -> Option<DecodedImage> {456) -> Option<DecodedImage> {
457 use exr::block::reader::ChunksReader;
458 use exr::meta::attribute::SampleType;
353 use exr::prelude::*;459 use exr::prelude::*;
354 let img = read_all_flat_layers_from_file(path).ok()?;460
355 let layer = img.layer_data.first()?;461 let file = std::fs::File::open(path).ok()?;
356 let w = layer.size.width();462 let chunks_reader = exr::block::read(std::io::BufReader::new(file), false).ok()?;
357 let h = layer.size.height();463 let first_header = chunks_reader.headers().first()?;
464 let w = first_header.layer_size.width();
465 let h = first_header.layer_size.height();
358 if w == 0 || h == 0 {466 if w == 0 || h == 0 {
359 return None;467 return None;
360 }468 }
361469
362 let find_channel = |preferred: Option<&str>, fallbacks: &[&str]| -> Option<Vec<f32>> {470 let r_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, red_name, "R", "r")?;
363 let mut names: Vec<&str> = Vec::new();471 let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g");
364 if let Some(p) = preferred {472 let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b");
365 names.push(p);473 let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a");
366 }474
367 names.extend_from_slice(fallbacks);475 let target_locs = [Some(r_loc), g_loc, b_loc, a_loc];
368 for target in names {476 let mut needed_layers: Vec<usize> = target_locs.iter().flatten().map(|(l, _)| *l).collect();
369 for candidate_layer in &img.layer_data {477 needed_layers.sort_unstable();
370 if candidate_layer.size.width() != w || candidate_layer.size.height() != h {478 needed_layers.dedup();
479
480 let mut raw_f32 = vec![0.0_f32; w * h * 4];
481 let mut line_f32 = Vec::<f32>::new();
482 let mut line_f16 = Vec::<f16>::new();
483 let mut line_u32 = Vec::<u32>::new();
484
485 chunks_reader
486 .filter_chunks(false, |_, tile, block| {
487 tile.is_largest_resolution_level() && needed_layers.contains(&block.layer)
488 })
489 .ok()?
490 .decompress_parallel(false, |meta, block| {
491 let header = &meta.headers[block.index.layer];
492 for line in block.lines(&header.channels) {
493 let loc = (line.location.layer, line.location.channel);
494 let mut comp_mask = [false; 4];
495 for (c, t) in target_locs.iter().enumerate() {
496 if *t == Some(loc) {
497 comp_mask[c] = true;
498 }
499 }
500 if !comp_mask.iter().any(|&m| m) {
371 continue;501 continue;
372 }502 }
373 for ch in &candidate_layer.channel_data.list {503 let y = line.location.position.y();
374 let cname = ch.name.to_string();504 let x0 = line.location.position.x();
375 if cname == target || cname.ends_with(&format!(".{target}")) {505 let len = line.location.sample_count;
376 let vals: Vec<f32> = ch.sample_data.values_as_f32().collect();506 if y >= h || x0 + len > w {
377 if vals.len() == w * h {507 continue;
378 return Some(vals);508 }
509
510 line_f32.clear();
511 match header.channels.list[line.location.channel].sample_type {
512 SampleType::F32 => {
513 line_f32.resize(len, 0.0);
514 line.read_samples_into_slice(&mut line_f32)?;
515 }
516 SampleType::F16 => {
517 line_f16.resize(len, f16::ZERO);
518 line.read_samples_into_slice(&mut line_f16)?;
519 line_f32.extend(line_f16.iter().map(|v| v.to_f32()));
520 }
521 SampleType::U32 => {
522 line_u32.resize(len, 0);
523 line.read_samples_into_slice(&mut line_u32)?;
524 line_f32.extend(line_u32.iter().map(|&v| v as f32));
525 }
526 }
527
528 let row_base = (y * w + x0) * 4;
529 for (dx, &sample) in line_f32.iter().enumerate() {
530 let val = if sample.is_nan() { 0.0 } else { sample };
531 let px_off = row_base + dx * 4;
532 for (c, &enabled) in comp_mask.iter().enumerate() {
533 if enabled {
534 raw_f32[px_off + c] = val;
379 }535 }
380 }536 }
381 }537 }
382 }538 }
383 }539 Ok(())
384 None540 })
385 };541 .ok()?;
386
387 let ch_r = find_channel(red_name, &["ViewLayer.Combined.R", "Combined.R", "R", "r"])?;
388 let ch_g = find_channel(green_name, &["ViewLayer.Combined.G", "Combined.G", "G", "g"])
389 .unwrap_or_else(|| ch_r.clone());
390 let ch_b = find_channel(blue_name, &["ViewLayer.Combined.B", "Combined.B", "B", "b"])
391 .unwrap_or_else(|| ch_r.clone());
392 let ch_a = find_channel(alpha_name, &["ViewLayer.Combined.A", "Combined.A", "A", "a"]);
393
394 let sanitize = |v: f32| if v.is_nan() { 0.0 } else { v };
395542
396 let mut raw = vec![0u8; w * h * 4];543 let mut raw = vec![0u8; w * h * 4];
397 let mut raw_f16 = vec![0u16; w * h * 4];544 let mut raw_f16 = vec![0u16; w * h * 4];
398 let mut raw_f32 = vec![0.0_f32; w * h * 4];
399 for i in 0..(w * h) {545 for i in 0..(w * h) {
400 let a_raw = sanitize(ch_a.as_ref().map_or(1.0, |v| v[i]));546 let off = i * 4;
401 let mut r_raw = sanitize(ch_r[i]);547 let mut r_raw = raw_f32[off];
402 let mut g_raw = sanitize(ch_g[i]);548 let mut g_raw = if g_loc.is_some() { raw_f32[off + 1] } else { r_raw };
403 let mut b_raw = sanitize(ch_b[i]);549 let mut b_raw = if b_loc.is_some() { raw_f32[off + 2] } else { r_raw };
550 let a_raw = if a_loc.is_some() { raw_f32[off + 3] } else { 1.0 };
551
404 if post_multiply && a_raw < 1.0 {552 if post_multiply && a_raw < 1.0 {
405 let a_mul = a_raw.clamp(0.0, 1.0);553 let a_mul = a_raw.clamp(0.0, 1.0);
406 r_raw *= a_mul;554 r_raw *= a_mul;
407 g_raw *= a_mul;555 g_raw *= a_mul;
408 b_raw *= a_mul;556 b_raw *= a_mul;
409 }557 }
410 raw_f32[i * 4] = r_raw;558 raw_f32[off] = r_raw;
411 raw_f32[i * 4 + 1] = g_raw;559 raw_f32[off + 1] = g_raw;
412 raw_f32[i * 4 + 2] = b_raw;560 raw_f32[off + 2] = b_raw;
413 raw_f32[i * 4 + 3] = a_raw;561 raw_f32[off + 3] = a_raw;
414562
415 raw_f16[i * 4] = f32_to_f16_bits(r_raw);563 raw_f16[off] = f32_to_f16_bits(r_raw);
416 raw_f16[i * 4 + 1] = f32_to_f16_bits(g_raw);564 raw_f16[off + 1] = f32_to_f16_bits(g_raw);
417 raw_f16[i * 4 + 2] = f32_to_f16_bits(b_raw);565 raw_f16[off + 2] = f32_to_f16_bits(b_raw);
418 raw_f16[i * 4 + 3] = f32_to_f16_bits(a_raw);566 raw_f16[off + 3] = f32_to_f16_bits(a_raw);
419567
420 let a = a_raw.clamp(0.0, 1.0);568 let a = a_raw.clamp(0.0, 1.0);
421 let r = r_raw.clamp(0.0, 1.0);569 let r = r_raw.clamp(0.0, 1.0);
422 let g = g_raw.clamp(0.0, 1.0);570 let g = g_raw.clamp(0.0, 1.0);
423 let b = b_raw.clamp(0.0, 1.0);571 let b = b_raw.clamp(0.0, 1.0);
424 raw[i * 4] = (r * 255.0 + 0.5) as u8;572 raw[off] = (r * 255.0 + 0.5) as u8;
425 raw[i * 4 + 1] = (g * 255.0 + 0.5) as u8;573 raw[off + 1] = (g * 255.0 + 0.5) as u8;
426 raw[i * 4 + 2] = (b * 255.0 + 0.5) as u8;574 raw[off + 2] = (b * 255.0 + 0.5) as u8;
427 raw[i * 4 + 3] = (a * 255.0 + 0.5) as u8;575 raw[off + 3] = (a * 255.0 + 0.5) as u8;
428 }576 }
429 Some(DecodedImage {577 Some(DecodedImage {
430 size: [w as u32, h as u32],578 size: [w as u32, h as u32],
...@@ -434,15 +582,27 @@ fn decode_exr_rgba(...@@ -434,15 +582,27 @@ fn decode_exr_rgba(
434 })582 })
435}583}
436584
437/// `(path, frame index or -1 for stills, post-multiplied)`; the flag is only set for decodes it changes.585const MAX_VIDEO_DECODERS: usize = 12;
438type ImageKey = (PathBuf, i64, bool);586
587#[derive(Clone, Debug, PartialEq, Eq, Hash)]
588struct ImageCacheKey {
589 path: PathBuf,
590 frame_idx: i64,
591 post_multiply: bool,
592 exr_channels: [Option<String>; 4],
593}
594
595struct VideoDecoderEntry {
596 decoder: Option<Box<dyn VideoDecoder>>,
597 last_used: u64,
598}
439599
440pub struct MediaCache {600pub struct MediaCache {
441 images: HashMap<ImageKey, DecodedImage>,601 images: HashMap<ImageCacheKey, DecodedImage>,
442 video_decoders: HashMap<PathBuf, Option<Box<dyn VideoDecoder>>>,602 video_decoders: HashMap<PathBuf, VideoDecoderEntry>,
443 total_bytes: u64,603 total_bytes: u64,
444 budget_bytes: u64,604 budget_bytes: u64,
445 lru: HashMap<ImageKey, u64>,605 lru: HashMap<ImageCacheKey, u64>,
446 tick: u64,606 tick: u64,
447}607}
448608
...@@ -461,6 +621,7 @@ impl MediaCache {...@@ -461,6 +621,7 @@ impl MediaCache {
461 pub fn clear(&mut self) {621 pub fn clear(&mut self) {
462 self.images.clear();622 self.images.clear();
463 self.lru.clear();623 self.lru.clear();
624 self.video_decoders.clear();
464 self.total_bytes = 0;625 self.total_bytes = 0;
465 }626 }
466627
...@@ -481,11 +642,15 @@ impl MediaCache {...@@ -481,11 +642,15 @@ impl MediaCache {
481 self.images.len()642 self.images.len()
482 }643 }
483644
645 pub fn video_decoder_count(&self) -> usize {
646 self.video_decoders.len()
647 }
648
484 pub fn total_mb(&self) -> f64 {649 pub fn total_mb(&self) -> f64 {
485 self.total_bytes as f64 / (1024.0 * 1024.0)650 self.total_bytes as f64 / (1024.0 * 1024.0)
486 }651 }
487652
488 fn insert_cached(&mut self, cache_key: ImageKey, decoded: DecodedImage) {653 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
489 let bytes = decoded.byte_size();654 let bytes = decoded.byte_size();
490 self.tick += 1;655 self.tick += 1;
491 if let Some(prev) = self.images.insert(cache_key.clone(), decoded) {656 if let Some(prev) = self.images.insert(cache_key.clone(), decoded) {
...@@ -505,6 +670,36 @@ impl MediaCache {...@@ -505,6 +670,36 @@ impl MediaCache {
505 }670 }
506 }671 }
507672
673 fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> {
674 self.tick += 1;
675 let now_tick = self.tick;
676 if let Some(entry) = self.video_decoders.get_mut(path) {
677 entry.last_used = now_tick;
678 return entry.decoder.as_ref().map(|d| d.info());
679 }
680 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
681 let Some(oldest_path) = self
682 .video_decoders
683 .iter()
684 .min_by_key(|(_, e)| e.last_used)
685 .map(|(p, _)| p.clone())
686 else {
687 break;
688 };
689 self.video_decoders.remove(&oldest_path);
690 }
691 let decoder = open_video_decoder(path);
692 let info = decoder.as_ref().map(|d| d.info());
693 self.video_decoders.insert(
694 path.to_path_buf(),
695 VideoDecoderEntry {
696 decoder,
697 last_used: now_tick,
698 },
699 );
700 info
701 }
702
508 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.703 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.
509 /// Returns `(resolved_path, local_frame_idx, decoded_image, loaded_from_disk)`.704 /// Returns `(resolved_path, local_frame_idx, decoded_image, loaded_from_disk)`.
510 pub fn load_clip(705 pub fn load_clip(
...@@ -519,8 +714,10 @@ impl MediaCache {...@@ -519,8 +714,10 @@ impl MediaCache {
519 if !base.exists() {714 if !base.exists() {
520 return None;715 return None;
521 }716 }
522 // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast]717 // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast].
523 if clip.global_end >= clip.global_start && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) {718 if clip.global_end >= clip.global_start
719 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)
720 {
524 let min_f = clip.global_start - clip.extend_first.max(0);721 let min_f = clip.global_start - clip.extend_first.max(0);
525 let max_f = clip.global_end + clip.extend_last.max(0);722 let max_f = clip.global_end + clip.extend_last.max(0);
526 if frame < min_f || frame > max_f {723 if frame < min_f || frame > max_f {
...@@ -528,13 +725,7 @@ impl MediaCache {...@@ -528,13 +725,7 @@ impl MediaCache {
528 }725 }
529 }726 }
530 let base_buf = base.to_path_buf();727 let base_buf = base.to_path_buf();
531 let info = {728 let info = self.get_or_open_video_decoder(base)?;
532 let entry = self
533 .video_decoders
534 .entry(base_buf.clone())
535 .or_insert_with(|| open_video_decoder(base));
536 entry.as_ref()?.info()
537 };
538729
539 let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1);730 let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1);
540 let trim_in = clip.trim_in.clamp(0, len - 1);731 let trim_in = clip.trim_in.clamp(0, len - 1);
...@@ -544,26 +735,31 @@ impl MediaCache {...@@ -544,26 +735,31 @@ impl MediaCache {
544 len - 1735 len - 1
545 };736 };
546 let span = (trim_out - trim_in + 1).max(1);737 let span = (trim_out - trim_in + 1).max(1);
547 let mut rel = frame - clip.global_start;738 let rel = if clip.loop_clip {
548 if rel < 0 {739 (frame - clip.global_start).rem_euclid(span)
549 rel = 0;
550 } else if clip.loop_clip {
551 rel = rel.rem_euclid(span);
552 } else {740 } else {
553 rel = rel.clamp(0, span - 1);741 (frame - clip.global_start).clamp(0, span - 1)
554 }742 };
555 let idx = if clip.reverse { trim_out - rel } else { trim_in + rel };743 let idx = if clip.reverse { trim_out - rel } else { trim_in + rel };
556 let cache_key = (base_buf.clone(), idx, false);744 let cache_key = ImageCacheKey {
745 path: base_buf.clone(),
746 frame_idx: idx,
747 post_multiply,
748 exr_channels: [None, None, None, None],
749 };
557 if let Some(img) = self.images.get(&cache_key).cloned() {750 if let Some(img) = self.images.get(&cache_key).cloned() {
558 self.tick += 1;751 self.tick += 1;
559 self.lru.insert(cache_key, self.tick);752 self.lru.insert(cache_key, self.tick);
560 return Some((base_buf, idx, img, false));753 return Some((base_buf, idx, img, false));
561 }754 }
562 let raw = self755 let mut raw = self
563 .video_decoders756 .video_decoders
564 .get_mut(&base_buf)757 .get_mut(&base_buf)
565 .and_then(|d| d.as_mut())?758 .and_then(|e| e.decoder.as_mut())?
566 .decode_frame(idx)?;759 .decode_frame(idx)?;
760 if post_multiply {
761 apply_post_multiply_rgba8(&mut raw);
762 }
567 let decoded = DecodedImage {763 let decoded = DecodedImage {
568 size: [info.width, info.height],764 size: [info.width, info.height],
569 rgba: Arc::new(raw),765 rgba: Arc::new(raw),
...@@ -576,7 +772,22 @@ impl MediaCache {...@@ -576,7 +772,22 @@ impl MediaCache {
576772
577 let resolved = resolve_clip_path(clip, frame)?;773 let resolved = resolve_clip_path(clip, frame)?;
578 let is_exr = is_exr_path(&resolved);774 let is_exr = is_exr_path(&resolved);
579 let cache_key = (resolved.clone(), -1, post_multiply && !is_exr);775 let key_channels = if is_exr {
776 [
777 normalize_channel_opt(exr_channels[0]),
778 normalize_channel_opt(exr_channels[1]),
779 normalize_channel_opt(exr_channels[2]),
780 normalize_channel_opt(exr_channels[3]),
781 ]
782 } else {
783 [None, None, None, None]
784 };
785 let cache_key = ImageCacheKey {
786 path: resolved.clone(),
787 frame_idx: -1,
788 post_multiply: post_multiply && !is_exr,
789 exr_channels: key_channels,
790 };
580 if let Some(img) = self.images.get(&cache_key).cloned() {791 if let Some(img) = self.images.get(&cache_key).cloned() {
581 self.tick += 1;792 self.tick += 1;
582 self.lru.insert(cache_key, self.tick);793 self.lru.insert(cache_key, self.tick);
...@@ -599,14 +810,7 @@ impl MediaCache {...@@ -599,14 +810,7 @@ impl MediaCache {
599 let size = [rgba_img.width(), rgba_img.height()];810 let size = [rgba_img.width(), rgba_img.height()];
600 let mut raw = rgba_img.into_raw();811 let mut raw = rgba_img.into_raw();
601 if post_multiply {812 if post_multiply {
602 for px in raw.chunks_exact_mut(4) {813 apply_post_multiply_rgba8(&mut raw);
603 let a = u16::from(px[3]);
604 if a < 255 {
605 px[0] = ((u16::from(px[0]) * a + 127) / 255) as u8;
606 px[1] = ((u16::from(px[1]) * a + 127) / 255) as u8;
607 px[2] = ((u16::from(px[2]) * a + 127) / 255) as u8;
608 }
609 }
610 }814 }
611 DecodedImage {815 DecodedImage {
612 size,816 size,
...@@ -659,13 +863,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {...@@ -659,13 +863,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
659 format!("{prefix}{idx:0width$}.{ext}")863 format!("{prefix}{idx:0width$}.{ext}")
660 };864 };
661 let candidate = base.with_file_name(new_name);865 let candidate = base.with_file_name(new_name);
662 if candidate.exists() {866 candidate.exists().then_some(candidate)
663 Some(candidate)
664 } else if base.exists() {
665 Some(base.to_path_buf())
666 } else {
667 None
668 }
669}867}
670868
671/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`].869/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`].
...@@ -1143,4 +1341,283 @@ mod tests {...@@ -1143,4 +1341,283 @@ mod tests {
1143 "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})"1341 "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})"
1144 );1342 );
1145 }1343 }
1344
1345 #[test]
1346 fn exr_channel_cache_isolation_and_non_beauty_guard() {
1347 use exr::prelude::*;
1348 let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id()));
1349 let _ = std::fs::remove_dir_all(&dir);
1350 std::fs::create_dir_all(&dir).unwrap();
1351
1352 let multi_exr = dir.join("multi_aov.exr");
1353 let w = 4usize;
1354 let h = 4usize;
1355 let n = w * h;
1356 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
1357 for (name, val) in [
1358 ("ViewLayer.Combined.R", 0.9_f32),
1359 ("ViewLayer.Combined.G", 0.2),
1360 ("ViewLayer.Combined.B", 0.1),
1361 ("ViewLayer.Combined.A", 1.0),
1362 ("ViewLayer.Specular.R", 0.1),
1363 ("ViewLayer.Specular.G", 0.8),
1364 ("ViewLayer.Specular.B", 0.7),
1365 ("ViewLayer.Specular.A", 1.0),
1366 ("ViewLayer.CryptoObject00.R", 0.5),
1367 ] {
1368 channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
1369 }
1370 Image::from_layer(Layer::new(
1371 (w, h),
1372 LayerAttributes::named("main"),
1373 Encoding::FAST_LOSSLESS,
1374 AnyChannels::sort(channels),
1375 ))
1376 .write()
1377 .to_file(&multi_exr)
1378 .expect("write multi-layer EXR");
1379
1380 let clip = ClipSpec {
1381 filename: multi_exr.to_string_lossy().into_owned(),
1382 alternate_filename: None,
1383 start_frame: 0,
1384 length: Some(1),
1385 trim_in: 0,
1386 trim_out: 0,
1387 global_start: 0,
1388 global_end: 0,
1389 extend_first: 0,
1390 extend_last: 0,
1391 loop_clip: false,
1392 reverse: false,
1393 };
1394 let mut cache = MediaCache::new(64);
1395 let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
1396 assert!(beauty_disk);
1397 let (_, _, spec, spec_disk) = cache
1398 .load_clip(
1399 &clip,
1400 0,
1401 false,
1402 [
1403 Some("Specular.R"),
1404 Some("Specular.G"),
1405 Some("Specular.B"),
1406 Some("Specular.A"),
1407 ],
1408 )
1409 .unwrap();
1410 assert!(spec_disk);
1411 assert_eq!(cache.entry_count(), 2);
1412
1413 let b_px = beauty.rgba_f32.as_ref().unwrap();
1414 let s_px = spec.rgba_f32.as_ref().unwrap();
1415 assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4);
1416 assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4);
1417
1418 // Warm hits keep both AOVs isolated.
1419 let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
1420 assert!(!beauty_disk2);
1421 assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4);
1422
1423 // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback.
1424 let crypto_only_exr = dir.join("crypto_only.exr");
1425 let mut crypto_channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
1426 for (name, val) in [
1427 ("CryptoObject00.R", 0.42_f32),
1428 ("CryptoObject00.G", 0.0),
1429 ("CryptoObject00.B", 0.0),
1430 ("CryptoObject00.A", 1.0),
1431 ] {
1432 crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
1433 }
1434 Image::from_layer(Layer::new(
1435 (w, h),
1436 LayerAttributes::named("crypto"),
1437 Encoding::FAST_LOSSLESS,
1438 AnyChannels::sort(crypto_channels),
1439 ))
1440 .write()
1441 .to_file(&crypto_only_exr)
1442 .expect("write crypto-only EXR");
1443
1444 let crypto_clip = ClipSpec {
1445 filename: crypto_only_exr.to_string_lossy().into_owned(),
1446 ..clip
1447 };
1448 assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none());
1449 let (_, _, explicit, _) = cache
1450 .load_clip(
1451 &crypto_clip,
1452 0,
1453 false,
1454 [
1455 Some("CryptoObject00.R"),
1456 Some("CryptoObject00.G"),
1457 Some("CryptoObject00.B"),
1458 Some("CryptoObject00.A"),
1459 ],
1460 )
1461 .expect("explicit CryptoObject00 channel selection should succeed");
1462 assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4);
1463
1464 let _ = std::fs::remove_dir_all(&dir);
1465 }
1466
1467 #[test]
1468 fn video_decoder_clear_lru_cap_post_multiply_and_loop() {
1469 let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id()));
1470 let _ = std::fs::remove_dir_all(&dir);
1471 std::fs::create_dir_all(&dir).unwrap();
1472
1473 let base_mp4 = dir.join("clip_00.mp4");
1474 let ok = Command::new("ffmpeg")
1475 .args([
1476 "-y",
1477 "-v",
1478 "error",
1479 "-f",
1480 "lavfi",
1481 "-i",
1482 "color=c=red:size=32x32:rate=24:duration=0.25",
1483 "-c:v",
1484 "libx264",
1485 "-pix_fmt",
1486 "yuv420p",
1487 ])
1488 .arg(&base_mp4)
1489 .status()
1490 .is_ok_and(|s| s.success());
1491 assert!(ok, "ffmpeg failed to create tiny mp4");
1492
1493 let mut cache = MediaCache::new(64);
1494 for i in 0..15 {
1495 let p = if i == 0 {
1496 base_mp4.clone()
1497 } else {
1498 let dst = dir.join(format!("clip_{i:02}.mp4"));
1499 std::fs::copy(&base_mp4, &dst).unwrap();
1500 dst
1501 };
1502 let clip = ClipSpec {
1503 filename: p.to_string_lossy().into_owned(),
1504 alternate_filename: None,
1505 start_frame: 0,
1506 length: Some(6),
1507 trim_in: 0,
1508 trim_out: 5,
1509 global_start: 10,
1510 global_end: 15,
1511 extend_first: 5,
1512 extend_last: 0,
1513 loop_clip: true,
1514 reverse: false,
1515 };
1516 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15], rel = -1 -> rem_euclid(6) = 5.
1517 let (_, local_idx, _, _) = cache
1518 .load_clip(&clip, 9, false, [None; 4])
1519 .expect("loop_clip negative rel inside ExtendFirst should resolve");
1520 assert_eq!(local_idx, 5);
1521 }
1522 assert!(
1523 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,
1524 "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}",
1525 cache.video_decoder_count()
1526 );
1527 assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS);
1528
1529 // Straight-alpha ProRes 4444 MOV test for post_multiply separation.
1530 let alpha_png = dir.join("straight_half.png");
1531 image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128]))
1532 .save(&alpha_png)
1533 .unwrap();
1534 let alpha_mov = dir.join("straight_half.mov");
1535 let mov_ok = Command::new("ffmpeg")
1536 .args([
1537 "-y",
1538 "-v",
1539 "error",
1540 "-loop",
1541 "1",
1542 "-i",
1543 ])
1544 .arg(&alpha_png)
1545 .args([
1546 "-t",
1547 "0.1",
1548 "-r",
1549 "24",
1550 "-c:v",
1551 "prores_ks",
1552 "-profile:v",
1553 "4",
1554 "-pix_fmt",
1555 "yuva444p10le",
1556 ])
1557 .arg(&alpha_mov)
1558 .status()
1559 .is_ok_and(|s| s.success());
1560 if mov_ok {
1561 let mov_clip = ClipSpec {
1562 filename: alpha_mov.to_string_lossy().into_owned(),
1563 alternate_filename: None,
1564 start_frame: 0,
1565 length: Some(2),
1566 trim_in: 0,
1567 trim_out: 1,
1568 global_start: 0,
1569 global_end: 1,
1570 extend_first: 0,
1571 extend_last: 0,
1572 loop_clip: false,
1573 reverse: false,
1574 };
1575 let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap();
1576 let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap();
1577 assert!(
1578 pm_vid.rgba[0] < raw_vid.rgba[0],
1579 "post_multiply should darken straight-alpha RGB ({} vs {})",
1580 pm_vid.rgba[0],
1581 raw_vid.rgba[0]
1582 );
1583 }
1584
1585 cache.clear();
1586 assert_eq!(cache.entry_count(), 0);
1587 assert_eq!(cache.video_decoder_count(), 0);
1588
1589 let _ = std::fs::remove_dir_all(&dir);
1590 }
1591
1592 #[test]
1593 fn resolve_clip_path_missing_mid_sequence_returns_none() {
1594 let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id()));
1595 let _ = std::fs::remove_dir_all(&dir);
1596 std::fs::create_dir_all(&dir).unwrap();
1597
1598 let f0 = dir.join("shot_0000.png");
1599 let f2 = dir.join("shot_0002.png");
1600 image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap();
1601 image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap();
1602
1603 let clip = ClipSpec {
1604 filename: f0.to_string_lossy().into_owned(),
1605 alternate_filename: None,
1606 start_frame: 0,
1607 length: Some(3),
1608 trim_in: 0,
1609 trim_out: 2,
1610 global_start: 0,
1611 global_end: 2,
1612 extend_first: 0,
1613 extend_last: 0,
1614 loop_clip: false,
1615 reverse: false,
1616 };
1617 assert_eq!(resolve_clip_path(&clip, 0), Some(f0));
1618 assert_eq!(resolve_clip_path(&clip, 1), None);
1619 assert_eq!(resolve_clip_path(&clip, 2), Some(f2));
1620
1621 let _ = std::fs::remove_dir_all(&dir);
1622 }
1146}1623}
crates/engine/src/ram_cache.rs+191-15
...@@ -72,6 +72,7 @@ impl RamCacheInner {...@@ -72,6 +72,7 @@ impl RamCacheInner {
72#[derive(Clone)]72#[derive(Clone)]
73pub struct RamFrameCache {73pub struct RamFrameCache {
74 inner: Arc<Mutex<RamCacheInner>>,74 inner: Arc<Mutex<RamCacheInner>>,
75 cache_epoch: Arc<AtomicU64>,
75}76}
7677
77impl Default for RamFrameCache {78impl Default for RamFrameCache {
...@@ -90,9 +91,18 @@ impl RamFrameCache {...@@ -90,9 +91,18 @@ impl RamFrameCache {
90 tick: 0,91 tick: 0,
91 evictions: 0,92 evictions: 0,
92 })),93 })),
94 cache_epoch: Arc::new(AtomicU64::new(1)),
93 }95 }
94 }96 }
9597
98 pub fn epoch(&self) -> u64 {
99 self.cache_epoch.load(Ordering::Acquire)
100 }
101
102 pub(crate) fn epoch_arc(&self) -> Arc<AtomicU64> {
103 Arc::clone(&self.cache_epoch)
104 }
105
96 pub fn set_budget_mb(&self, budget_mb: u64) {106 pub fn set_budget_mb(&self, budget_mb: u64) {
97 if let Ok(mut guard) = self.inner.lock() {107 if let Ok(mut guard) = self.inner.lock() {
98 guard.budget_bytes = budget_mb.saturating_mul(1024 * 1024);108 guard.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
...@@ -127,6 +137,21 @@ impl RamFrameCache {...@@ -127,6 +137,21 @@ impl RamFrameCache {
127 let Ok(mut guard) = self.inner.lock() else {137 let Ok(mut guard) = self.inner.lock() else {
128 return;138 return;
129 };139 };
140 Self::insert_locked(&mut guard, key, frame);
141 }
142
143 pub fn insert_if_epoch(&self, expected_epoch: u64, key: RamFrameKey, frame: RamFrame) -> bool {
144 let Ok(mut guard) = self.inner.lock() else {
145 return false;
146 };
147 if self.cache_epoch.load(Ordering::Acquire) != expected_epoch {
148 return false;
149 }
150 Self::insert_locked(&mut guard, key, frame);
151 true
152 }
153
154 fn insert_locked(guard: &mut RamCacheInner, key: RamFrameKey, frame: RamFrame) {
130 let bytes = frame.byte_size();155 let bytes = frame.byte_size();
131 if guard.budget_bytes == 0 || bytes > guard.budget_bytes {156 if guard.budget_bytes == 0 || bytes > guard.budget_bytes {
132 return;157 return;
...@@ -145,6 +170,7 @@ impl RamFrameCache {...@@ -145,6 +170,7 @@ impl RamFrameCache {
145 if let Ok(mut guard) = self.inner.lock() {170 if let Ok(mut guard) = self.inner.lock() {
146 guard.entries.clear();171 guard.entries.clear();
147 guard.total_bytes = 0;172 guard.total_bytes = 0;
173 self.cache_epoch.fetch_add(1, Ordering::AcqRel);
148 }174 }
149 }175 }
150176
...@@ -255,18 +281,22 @@ struct WorkerSlot {...@@ -255,18 +281,22 @@ struct WorkerSlot {
255/// counter so any in-flight lookahead loop aborts before evaluating another frame.281/// counter so any in-flight lookahead loop aborts before evaluating another frame.
256pub struct RamPrefetcher {282pub struct RamPrefetcher {
257 cache: RamFrameCache,283 cache: RamFrameCache,
284 cache_epoch: Arc<AtomicU64>,
258 vram_budget_mb: u64,285 vram_budget_mb: u64,
259 generation: Arc<AtomicU64>,286 generation: Arc<AtomicU64>,
260 busy: Arc<AtomicBool>,287 busy: Arc<AtomicBool>,
261 completed_frames: Arc<AtomicU64>,288 completed_frames: Arc<AtomicU64>,
262 slot: Arc<(Mutex<WorkerSlot>, Condvar)>,289 slot: Arc<(Mutex<WorkerSlot>, Condvar)>,
290 finished: Arc<(Mutex<bool>, Condvar)>,
263 worker: Option<JoinHandle<()>>,291 worker: Option<JoinHandle<()>>,
264}292}
265293
266impl RamPrefetcher {294impl RamPrefetcher {
267 pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self {295 pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self {
296 let cache_epoch = cache.epoch_arc();
268 Self {297 Self {
269 cache,298 cache,
299 cache_epoch,
270 vram_budget_mb: worker_vram_budget_mb.max(128),300 vram_budget_mb: worker_vram_budget_mb.max(128),
271 generation: Arc::new(AtomicU64::new(1)),301 generation: Arc::new(AtomicU64::new(1)),
272 busy: Arc::new(AtomicBool::new(false)),302 busy: Arc::new(AtomicBool::new(false)),
...@@ -278,6 +308,7 @@ impl RamPrefetcher {...@@ -278,6 +308,7 @@ impl RamPrefetcher {
278 }),308 }),
279 Condvar::new(),309 Condvar::new(),
280 )),310 )),
311 finished: Arc::new((Mutex::new(false), Condvar::new())),
281 worker: None,312 worker: None,
282 }313 }
283 }314 }
...@@ -294,17 +325,19 @@ impl RamPrefetcher {...@@ -294,17 +325,19 @@ impl RamPrefetcher {
294 self.completed_frames.load(Ordering::Acquire)325 self.completed_frames.load(Ordering::Acquire)
295 }326 }
296327
297 /// Cancels any active lookahead pass immediately.328 /// Cancels any active lookahead pass immediately and bumps `cache_epoch` so the
329 /// worker busts its internal caches on the next job even if `comp.revision` matches.
298 pub fn cancel(&self) {330 pub fn cancel(&self) {
299 self.generation.fetch_add(1, Ordering::AcqRel);331 self.generation.fetch_add(1, Ordering::AcqRel);
332 self.cache_epoch.fetch_add(1, Ordering::AcqRel);
300 if let Ok(mut guard) = self.slot.0.lock() {333 if let Ok(mut guard) = self.slot.0.lock() {
301 guard.job = None;334 guard.job = None;
302 }335 }
303 }336 }
304337
305 /// Schedules background lookahead rendering starting at `job.center_frame + 1`338 /// Schedules background lookahead rendering starting at `job.center_frame + 1`
306 /// through `min(job.range[1], job.center_frame + job.lookahead)`, wrapping or339 /// through `min(job.range[1], job.center_frame + job.lookahead)`, wrapping around
307 /// skipping frames that are already cached. Cancels any superseded request.340 /// `[range[0], range[1]]` and skipping frames that are already cached.
308 pub fn request_lookahead(&mut self, job: PrefetchJob) {341 pub fn request_lookahead(&mut self, job: PrefetchJob) {
309 self.ensure_worker();342 self.ensure_worker();
310 let job_gen = self.generation.fetch_add(1, Ordering::AcqRel) + 1;343 let job_gen = self.generation.fetch_add(1, Ordering::AcqRel) + 1;
...@@ -319,17 +352,34 @@ impl RamPrefetcher {...@@ -319,17 +352,34 @@ impl RamPrefetcher {
319 return;352 return;
320 }353 }
321 let cache = self.cache.clone();354 let cache = self.cache.clone();
355 let cache_epoch = self.cache_epoch.clone();
322 let vram_mb = self.vram_budget_mb;356 let vram_mb = self.vram_budget_mb;
323 let generation = self.generation.clone();357 let generation = self.generation.clone();
324 let busy = self.busy.clone();358 let busy = self.busy.clone();
325 let completed = self.completed_frames.clone();359 let completed = self.completed_frames.clone();
326 let slot = self.slot.clone();360 let slot = self.slot.clone();
361 let finished = self.finished.clone();
362 if let Ok(mut f) = finished.0.lock() {
363 *f = false;
364 }
327365
328 let handle = thread::Builder::new()366 let handle = thread::Builder::new()
329 .name("fission-ram-prefetch".to_owned())367 .name("fission-ram-prefetch".to_owned())
330 .spawn(move || {368 .spawn(move || {
369 struct FinishGuard(Arc<(Mutex<bool>, Condvar)>);
370 impl Drop for FinishGuard {
371 fn drop(&mut self) {
372 if let Ok(mut f) = self.0.0.lock() {
373 *f = true;
374 self.0.1.notify_all();
375 }
376 }
377 }
378 let _finish_guard = FinishGuard(finished);
379
331 let mut engine_opt: Option<Engine> = None;380 let mut engine_opt: Option<Engine> = None;
332 let mut last_comp_rev: Option<u64> = None;381 let mut last_comp_rev: Option<u64> = None;
382 let mut last_cache_epoch: Option<u64> = None;
333383
334 loop {384 loop {
335 let (job_gen, job) = {385 let (job_gen, job) = {
...@@ -372,7 +422,12 @@ impl RamPrefetcher {...@@ -372,7 +422,12 @@ impl RamPrefetcher {
372 continue;422 continue;
373 };423 };
374424
375 if last_comp_rev != Some(job.comp.revision) {425 let job_epoch = cache_epoch.load(Ordering::Acquire);
426 if last_cache_epoch != Some(job_epoch) {
427 engine.bust_all_caches();
428 last_cache_epoch = Some(job_epoch);
429 last_comp_rev = Some(job.comp.revision);
430 } else if last_comp_rev != Some(job.comp.revision) {
376 engine.bust_gpu_cache();431 engine.bust_gpu_cache();
377 last_comp_rev = Some(job.comp.revision);432 last_comp_rev = Some(job.comp.revision);
378 }433 }
...@@ -383,16 +438,16 @@ impl RamPrefetcher {...@@ -383,16 +438,16 @@ impl RamPrefetcher {
383 busy.store(true, Ordering::Release);438 busy.store(true, Ordering::Release);
384 let start = job.range[0].min(job.range[1]);439 let start = job.range[0].min(job.range[1]);
385 let end = job.range[0].max(job.range[1]);440 let end = job.range[0].max(job.range[1]);
386 let count = job.lookahead.max(0);441 let span = (end - start + 1).max(1);
442 let count = job.lookahead.max(0).min(span);
387443
388 for offset in 1..=count {444 for offset in 1..=count {
389 if generation.load(Ordering::Acquire) != job_gen {445 if generation.load(Ordering::Acquire) != job_gen
390 break;446 || cache_epoch.load(Ordering::Acquire) != job_epoch
391 }447 {
392 let f = job.center_frame + offset;
393 if f < start || f > end {
394 break;448 break;
395 }449 }
450 let f = start + (job.center_frame - start + offset).rem_euclid(span);
396 let key = RamFrameKey {451 let key = RamFrameKey {
397 target: job.target,452 target: job.target,
398 revision: job.comp.revision,453 revision: job.comp.revision,
...@@ -405,19 +460,29 @@ impl RamPrefetcher {...@@ -405,19 +460,29 @@ impl RamPrefetcher {
405 continue;460 continue;
406 }461 }
407 let (tex, stats) = engine.evaluate(&job.comp, job.target, f as f64);462 let (tex, stats) = engine.evaluate(&job.comp, job.target, f as f64);
408 if generation.load(Ordering::Acquire) != job_gen {463 if generation.load(Ordering::Acquire) != job_gen
464 || cache_epoch.load(Ordering::Acquire) != job_epoch
465 {
409 break;466 break;
410 }467 }
411 if let Ok(rgba) = engine.readback_rgba(&tex) {468 if let Ok(rgba) = engine.readback_rgba(&tex) {
412 cache.insert(469 // Re-check generation immediately before inserting after readback completes.
470 if generation.load(Ordering::Acquire) != job_gen {
471 break;
472 }
473 if cache.insert_if_epoch(
474 job_epoch,
413 key,475 key,
414 RamFrame {476 RamFrame {
415 size: tex.size,477 size: tex.size,
416 rgba: Arc::new(rgba),478 rgba: Arc::new(rgba),
417 eval_ms: stats.eval_ms,479 eval_ms: stats.eval_ms,
418 },480 },
419 );481 ) {
420 completed.fetch_add(1, Ordering::AcqRel);482 completed.fetch_add(1, Ordering::AcqRel);
483 } else {
484 break;
485 }
421 }486 }
422 }487 }
423 busy.store(false, Ordering::Release);488 busy.store(false, Ordering::Release);
...@@ -438,7 +503,23 @@ impl Drop for RamPrefetcher {...@@ -438,7 +503,23 @@ impl Drop for RamPrefetcher {
438 self.slot.1.notify_all();503 self.slot.1.notify_all();
439 }504 }
440 if let Some(handle) = self.worker.take() {505 if let Some(handle) = self.worker.take() {
441 let _ = handle.join();506 let done = if let Ok(guard) = self.finished.0.lock() {
507 if *guard {
508 true
509 } else {
510 let (g, _) = self
511 .finished
512 .1
513 .wait_timeout_while(guard, std::time::Duration::from_millis(200), |f| !*f)
514 .unwrap_or_else(|e| e.into_inner());
515 *g
516 }
517 } else {
518 false
519 };
520 if done {
521 let _ = handle.join();
522 }
442 }523 }
443 }524 }
444}525}
...@@ -563,4 +644,99 @@ Composition {...@@ -563,4 +644,99 @@ Composition {
563 );644 );
564 prefetcher.cancel();645 prefetcher.cancel();
565 }646 }
647
648 #[test]
649 fn ram_prefetcher_loop_wraparound_and_epoch_clear_invalidation() {
650 let comp_src = r#"
651Composition {
652 CurrentTime = 13,
653 RenderRange = { 10, 14 },
654 GlobalRange = { 10, 14 },
655 Tools = ordered() {
656 BG1 = Background {
657 Inputs = {
658 Width = Input { Value = 32, },
659 Height = Input { Value = 32, },
660 TopLeftRed = Input { Value = 0.25, },
661 TopLeftAlpha = Input { Value = 1.0, },
662 },
663 },
664 },
665}
666"#;
667 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
668 let target = comp.find_node("BG1").expect("BG1");
669
670 let cache = RamFrameCache::new(64);
671 let initial_epoch = cache.epoch();
672 let mut prefetcher = RamPrefetcher::new(cache.clone(), 128);
673
674 // Starting near end of [10, 14] at frame 13 with lookahead 4 must wrap to 14, 10, 11, 12.
675 prefetcher.request_lookahead(PrefetchJob {
676 comp: comp.clone(),
677 target,
678 center_frame: 13,
679 range: [10, 14],
680 lookahead: 4,
681 proxy_scale: 1,
682 hiq: true,
683 use_proxy_clips: false,
684 });
685
686 let deadline = Instant::now() + Duration::from_secs(10);
687 while Instant::now() < deadline {
688 if cache.cached_frame_ranges(target, comp.revision, 1, true, false)
689 == vec![(10, 12), (14, 14)]
690 {
691 break;
692 }
693 thread::sleep(Duration::from_millis(15));
694 }
695 assert_eq!(
696 cache.cached_frame_ranges(target, comp.revision, 1, true, false),
697 vec![(10, 12), (14, 14)]
698 );
699
700 // Clearing cache bumps epoch and insert_if_epoch rejects stale pre-clear writes.
701 cache.clear();
702 assert!(cache.epoch() > initial_epoch);
703 let stale_key = RamFrameKey {
704 target,
705 revision: comp.revision,
706 frame: 13,
707 proxy_scale: 1,
708 hiq: true,
709 use_proxy_clips: false,
710 };
711 assert!(!cache.insert_if_epoch(initial_epoch, stale_key, dummy_frame(32, 32)));
712 assert_eq!(cache.entry_count(), 0);
713
714 // Re-requesting with the SAME comp.revision works after epoch bump (busting worker Engine).
715 let after_clear_epoch = cache.epoch();
716 prefetcher.request_lookahead(PrefetchJob {
717 comp: comp.clone(),
718 target,
719 center_frame: 14,
720 range: [10, 14],
721 lookahead: 5,
722 proxy_scale: 1,
723 hiq: true,
724 use_proxy_clips: false,
725 });
726
727 let deadline2 = Instant::now() + Duration::from_secs(10);
728 while Instant::now() < deadline2 {
729 if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(10, 14)] {
730 break;
731 }
732 thread::sleep(Duration::from_millis(15));
733 }
734 assert_eq!(
735 cache.cached_frame_ranges(target, comp.revision, 1, true, false),
736 vec![(10, 14)]
737 );
738
739 prefetcher.cancel();
740 assert!(cache.epoch() > after_clear_epoch);
741 }
566}742}