authoravatarclover caruso<git@paperclover.net>2026-11-30 18:24:10-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 19:14:04-08:00
log10c172828f801d8935b0fba75f715dda3b75e935
tree313c1edbe25c47932317ca7cdcb1bbd486e5b91c
parent70d3b873a073d0d88aeca1b79cee99b90743ea4a
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add non-blocking background export with progress/cancel UI and tight audio sync (#40)


3 files changed, 1068 insertions(+), 137 deletions(-)

crates/app/src/main.rs+473-99
...@@ -8,11 +8,12 @@ mod keyframes;...@@ -8,11 +8,12 @@ mod keyframes;
8use add_tool::{AddToolLauncher, ToolEntry};8use add_tool::{AddToolLauncher, ToolEntry};
9use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};9use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};
10use engine::export::{10use engine::export::{
11 VideoCodec, VideoExportOptions, export_node_frame_png, export_node_video_ffmpeg,11 ExportControl, ExportProgress, VideoCodec, VideoExportOptions, export_node_frame_png,
12 export_node_video_ffmpeg_with_progress, export_saver_png_sequence_with_progress, select_saver,
12};13};
13use engine::{14use engine::{
14 AudioPlayer, AudioTrack, CacheMode, DEFAULT_RAM_CACHE_MB, Engine, ExportOptions, PrefetchJob,15 AudioPlayer, AudioTrack, CacheMode, DEFAULT_RAM_CACHE_MB, Engine, ExportOptions, PrefetchJob,
15 RamFrameCache, RamPrefetcher, export_saver_png_sequence,16 RamFrameCache, RamPrefetcher,
16};17};
17use flow::{FlowAction, FlowView};18use flow::{FlowAction, FlowView};
18use inspector::{InspectorAction, InspectorState};19use inspector::{InspectorAction, InspectorState};
...@@ -114,6 +115,28 @@ fn main() {...@@ -114,6 +115,28 @@ fn main() {
114 }115 }
115}116}
116117
118enum ExportOutcome {
119 Completed(String),
120 Cancelled,
121 Failed(String),
122}
123
124struct ActiveExport {
125 control: ExportControl,
126 rx: mpsc::Receiver<ExportOutcome>,
127 cancelling: bool,
128 handle: Option<std::thread::JoinHandle<()>>,
129}
130
131impl Drop for ActiveExport {
132 fn drop(&mut self) {
133 self.control.cancel();
134 if let Some(handle) = self.handle.take() {
135 let _ = handle.join();
136 }
137 }
138}
139
117struct Studio {140struct Studio {
118 ui: ui::Ui,141 ui: ui::Ui,
119 dock: Dock<String>,142 dock: Dock<String>,
...@@ -127,6 +150,12 @@ struct Studio {...@@ -127,6 +150,12 @@ struct Studio {
127 enable_audio: bool,150 enable_audio: bool,
128 audio_player: Option<AudioPlayer>,151 audio_player: Option<AudioPlayer>,
129 audio_rx: Option<mpsc::Receiver<Result<AudioTrack, String>>>,152 audio_rx: Option<mpsc::Receiver<Result<AudioTrack, String>>>,
153 loaded_audio_track: Option<Arc<AudioTrack>>,
154 last_audio_offset: f64,
155 last_fps: f64,
156 last_audio_filename: Option<String>,
157 redraw_proxy: Option<EventLoopProxy<UserEvent>>,
158 active_export: Option<ActiveExport>,
130 status_notice: Option<(String, Instant)>,159 status_notice: Option<(String, Instant)>,
131 viewers: [ViewerState; 2],160 viewers: [ViewerState; 2],
132 flow: FlowView,161 flow: FlowView,
...@@ -312,6 +341,9 @@ impl Studio {...@@ -312,6 +341,9 @@ impl Studio {
312341
313 let mut history = CompHistory::new();342 let mut history = CompHistory::new();
314 history.mark_saved(&comp);343 history.mark_saved(&comp);
344 let last_audio_offset = comp.audio_offset;
345 let last_fps = comp.fps;
346 let last_audio_filename = comp.audio_filename.clone();
315347
316 Self {348 Self {
317 ui,349 ui,
...@@ -326,6 +358,12 @@ impl Studio {...@@ -326,6 +358,12 @@ impl Studio {
326 enable_audio,358 enable_audio,
327 audio_player,359 audio_player,
328 audio_rx,360 audio_rx,
361 loaded_audio_track: None,
362 last_audio_offset,
363 last_fps,
364 last_audio_filename,
365 redraw_proxy: None,
366 active_export: None,
329 status_notice: None,367 status_notice: None,
330 viewers: [v1, v2],368 viewers: [v1, v2],
331 flow,369 flow,
...@@ -346,7 +384,21 @@ impl Studio {...@@ -346,7 +384,21 @@ impl Studio {
346 }384 }
347385
348 fn audio_time_secs(&self) -> f64 {386 fn audio_time_secs(&self) -> f64 {
349 (self.playback.current_frame - self.comp.audio_offset) / self.comp.fps.max(1.0)387 self.playback.audio_target_secs(&self.comp)
388 }
389
390 fn refresh_audio_peaks(&mut self) {
391 if let Some(track) = &self.loaded_audio_track {
392 let peaks = track.waveform_peaks(
393 self.comp.fps,
394 self.comp.audio_offset,
395 self.comp.render_range[0],
396 self.comp.render_range[1],
397 );
398 self.viewers[0].audio_peaks = peaks.clone();
399 self.keyframes.audio_peaks = peaks;
400 self.keyframes.audio_range = self.comp.render_range;
401 }
350 }402 }
351403
352 fn poll_audio_load(&mut self) {404 fn poll_audio_load(&mut self) {
...@@ -359,21 +411,17 @@ impl Studio {...@@ -359,21 +411,17 @@ impl Studio {
359 track.duration_secs,411 track.duration_secs,
360 track.sample_rate412 track.sample_rate
361 );413 );
362 let peaks = track.waveform_peaks(414 let arc_track = Arc::new(track);
363 self.comp.fps,415 self.loaded_audio_track = Some(Arc::clone(&arc_track));
364 self.comp.audio_offset,416 self.refresh_audio_peaks();
365 self.comp.render_range[0],
366 self.comp.render_range[1],
367 );
368 self.viewers[0].audio_peaks = peaks.clone();
369 self.keyframes.audio_peaks = peaks;
370 self.keyframes.audio_range = self.comp.render_range;
371 let t = self.audio_time_secs();417 let t = self.audio_time_secs();
372 let playing = self.playback.playing;418 let playing = self.playback.playing;
373 if let Some(player) = &mut self.audio_player {419 if let Some(player) = &mut self.audio_player {
374 player.set_track(Some(Arc::new(track)));420 player.set_track(Some(arc_track));
375 if playing {421 if playing {
376 player.play_from(t);422 player.play_from(t);
423 } else {
424 player.seek(t);
377 }425 }
378 }426 }
379 self.audio_rx = None;427 self.audio_rx = None;
...@@ -399,8 +447,52 @@ impl Studio {...@@ -399,8 +447,52 @@ impl Studio {
399 } else if seeked {447 } else if seeked {
400 player.seek(t);448 player.seek(t);
401 }449 }
402 } else if state_changed || player.is_playing() {450 } else {
403 player.pause();451 if state_changed || player.is_playing() {
452 player.pause();
453 }
454 if seeked || state_changed {
455 player.seek(t);
456 }
457 }
458 }
459 }
460
461 fn check_audio_sync_and_metadata(&mut self, now: Instant) {
462 if self.comp.audio_filename != self.last_audio_filename {
463 self.last_audio_filename = self.comp.audio_filename.clone();
464 self.loaded_audio_track = None;
465 self.viewers[0].audio_peaks.clear();
466 self.keyframes.audio_peaks.clear();
467 if self.enable_audio {
468 if let Some(player) = &mut self.audio_player {
469 player.set_track(None);
470 }
471 self.audio_rx = spawn_audio_loader(&self.comp);
472 }
473 }
474 let offset_changed = (self.comp.audio_offset - self.last_audio_offset).abs() > 1e-6;
475 let fps_changed = (self.comp.fps - self.last_fps).abs() > 1e-6;
476 if offset_changed || fps_changed {
477 self.last_audio_offset = self.comp.audio_offset;
478 self.last_fps = self.comp.fps;
479 self.refresh_audio_peaks();
480 self.sync_audio(false, true);
481 }
482
483 if self.playback.playing {
484 if let Some(player) = &mut self.audio_player {
485 let expected = self.playback.expected_audio_secs(&self.comp, now);
486 if !player.is_playing() {
487 player.play_from(expected);
488 } else {
489 let actual = player.current_time_secs();
490 let frame_dur = 1.0 / self.comp.fps.max(1.0);
491 let max_drift = (frame_dur * 1.25).max(0.045);
492 if (actual - expected).abs() > max_drift {
493 player.seek(expected);
494 }
495 }
404 }496 }
405 }497 }
406 }498 }
...@@ -625,6 +717,10 @@ impl Studio {...@@ -625,6 +717,10 @@ impl Studio {
625 self.last_prefetch_sig = None;717 self.last_prefetch_sig = None;
626 self.inspector.reset();718 self.inspector.reset();
627 self.renaming_node = None;719 self.renaming_node = None;
720 self.loaded_audio_track = None;
721 self.last_audio_offset = self.comp.audio_offset;
722 self.last_fps = self.comp.fps;
723 self.last_audio_filename = self.comp.audio_filename.clone();
628724
629 if self.enable_audio {725 if self.enable_audio {
630 if let Some(player) = &mut self.audio_player {726 if let Some(player) = &mut self.audio_player {
...@@ -690,50 +786,151 @@ impl Studio {...@@ -690,50 +786,151 @@ impl Studio {
690 self.rename_needs_focus = true;786 self.rename_needs_focus = true;
691 }787 }
692788
789 fn poll_export(&mut self) {
790 let Some(exp) = &self.active_export else {
791 return;
792 };
793 match exp.rx.try_recv() {
794 Ok(outcome) => {
795 let mut finished = self.active_export.take().unwrap();
796 if let Some(handle) = finished.handle.take() {
797 let _ = handle.join();
798 }
799 match outcome {
800 ExportOutcome::Completed(msg) => {
801 eprintln!("{msg}");
802 self.set_notice(msg);
803 }
804 ExportOutcome::Cancelled => {
805 eprintln!("Export cancelled");
806 self.set_notice("Export cancelled");
807 }
808 ExportOutcome::Failed(err) => {
809 eprintln!("{err}");
810 self.set_notice(err);
811 }
812 }
813 }
814 Err(mpsc::TryRecvError::Disconnected) => {
815 let mut finished = self.active_export.take().unwrap();
816 if let Some(handle) = finished.handle.take() {
817 let _ = handle.join();
818 }
819 self.set_notice("Export worker stopped unexpectedly");
820 }
821 Err(mpsc::TryRecvError::Empty) => {}
822 }
823 }
824
825 fn spawn_export_worker<F>(&mut self, initial_progress: ExportProgress, job: F) -> Result<String, String>
826 where
827 F: FnOnce(&mut Engine, &ExportControl, &dyn Fn()) -> Result<String, String> + Send + 'static,
828 {
829 let control = ExportControl::new();
830 control.update_progress(&initial_progress);
831 let ctrl_worker = control.clone();
832 let proxy = self.redraw_proxy.clone();
833 let (tx, rx) = mpsc::channel();
834
835 let handle = std::thread::Builder::new()
836 .name("fission-export".to_owned())
837 .spawn(move || {
838 let notify_redraw = move || {
839 if let Some(p) = &proxy {
840 let _ = p.send_event(UserEvent::Redraw);
841 }
842 };
843 let outcome = match Engine::new_headless() {
844 Ok(mut export_engine) => match job(&mut export_engine, &ctrl_worker, &notify_redraw) {
845 Ok(msg) => ExportOutcome::Completed(msg),
846 Err(e) if e == "Cancelled" => ExportOutcome::Cancelled,
847 Err(e) => ExportOutcome::Failed(e),
848 },
849 Err(e) => ExportOutcome::Failed(format!("Failed to initialize export GPU: {e}")),
850 };
851 let _ = tx.send(outcome);
852 notify_redraw();
853 })
854 .map_err(|e| format!("Failed to start export thread: {e}"))?;
855
856 self.active_export = Some(ActiveExport {
857 control,
858 rx,
859 cancelling: false,
860 handle: Some(handle),
861 });
862 Ok("Export started".to_owned())
863 }
864
693 fn export_saver_pngs(&mut self) -> Result<String, String> {865 fn export_saver_pngs(&mut self) -> Result<String, String> {
694 if self.playback.playing {866 if self.active_export.is_some() {
695 self.playback.toggle_play(Instant::now());867 let msg = "Export already in progress".to_owned();
696 self.sync_audio(true, false);868 self.set_notice(msg.clone());
869 return Err(msg);
870 }
871 let saver = match select_saver(&self.comp, None) {
872 Ok(s) => s,
873 Err(e) => {
874 let err = format!("Export failed: {e}");
875 self.set_notice(err.clone());
876 return Err(err);
877 }
878 };
879 let [start, end] = saver.range;
880 if end < start {
881 let err = format!("Invalid Saver frame range {start}..={end}");
882 self.set_notice(err.clone());
883 return Err(err);
697 }884 }
885
886 let comp_snapshot = self.comp.clone();
698 let opts = ExportOptions {887 let opts = ExportOptions {
699 hiq: self.engine.hiq,888 hiq: self.engine.hiq,
700 proxy_scale: self.engine.proxy_scale,889 proxy_scale: self.engine.proxy_scale,
701 ..Default::default()890 ..Default::default()
702 };891 };
703 let t0 = Instant::now();892 let total = (end - start + 1) as u32;
704 match export_saver_png_sequence(&mut self.engine, &self.comp, &opts, |p| {893 let initial = ExportProgress {
705 if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total {894 frame: start,
706 let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6);895 total: total as usize,
707 eprintln!(896 saver_name: saver.name.clone(),
708 " [export {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}",897 current_frame: start.max(0) as u32,
709 p.index + 1,898 total_frames: total,
710 p.total,899 label: saver.name,
711 p.saver_name,900 ..Default::default()
712 p.frame,901 };
713 p.eval_ms,902
714 fps,903 self.spawn_export_worker(initial, move |engine, control, notify| {
715 p.out_path.display()904 let t0 = Instant::now();
716 );905 match export_saver_png_sequence_with_progress(engine, &comp_snapshot, &opts, Some(control), |p| {
717 }906 if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total {
718 }) {907 let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6);
719 Ok(summary) => {908 eprintln!(
720 let secs = (summary.total_ms / 1000.0).max(1e-6);909 " [export {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}",
721 let msg = format!(910 p.index + 1,
722 "Exported {} PNGs ({:.1} fps)",911 p.total,
723 summary.frames_written,912 p.saver_name,
724 summary.frames_written as f64 / secs913 p.frame,
725 );914 p.eval_ms,
726 eprintln!("{msg} via {}", summary.saver_name);915 fps,
727 self.status_notice = Some((msg.clone(), Instant::now()));916 p.out_path.display()
728 Ok(msg)917 );
729 }918 }
730 Err(e) => {919 notify();
731 let err = format!("Export failed: {e}");920 }) {
732 eprintln!("{err}");921 Ok(summary) => {
733 self.status_notice = Some((err.clone(), Instant::now()));922 let secs = (summary.total_ms / 1000.0).max(1e-6);
734 Err(err)923 Ok(format!(
924 "Exported {} PNGs via {} ({:.1} fps)",
925 summary.frames_written,
926 summary.saver_name,
927 summary.frames_written as f64 / secs
928 ))
929 }
930 Err(e) if e == "Cancelled" => Err(e),
931 Err(e) => Err(format!("Export failed: {e}")),
735 }932 }
736 }933 })
737 }934 }
738935
739 fn active_viewer_slot(&self) -> usize {936 fn active_viewer_slot(&self) -> usize {
...@@ -746,9 +943,10 @@ impl Studio {...@@ -746,9 +943,10 @@ impl Studio {
746 }943 }
747944
748 fn export_viewer_mp4(&mut self, slot: usize) -> Result<String, String> {945 fn export_viewer_mp4(&mut self, slot: usize) -> Result<String, String> {
749 if self.playback.playing {946 if self.active_export.is_some() {
750 self.playback.toggle_play(Instant::now());947 let msg = "Export already in progress".to_owned();
751 self.sync_audio(true, false);948 self.set_notice(msg.clone());
949 return Err(msg);
752 }950 }
753 let Some(target) = self.viewers[slot].viewed_node else {951 let Some(target) = self.viewers[slot].viewed_node else {
754 let msg = format!("Viewer {} has no node loaded", slot + 1);952 let msg = format!("Viewer {} has no node loaded", slot + 1);
...@@ -764,57 +962,81 @@ impl Studio {...@@ -764,57 +962,81 @@ impl Studio {
764 in_f,962 in_f,
765 out_f963 out_f
766 );964 );
767 let Some(mut path) = native_save_file_dialog("Export Preview MP4", &default_name) else {965 let Some(mut path) = native_save_file_dialog("Export Preview MP4 / ProRes", &default_name) else {
768 return Err("Export cancelled".to_owned());966 return Err("Export cancelled".to_owned());
769 };967 };
770 if path.extension().is_none() {968 if path.extension().is_none() {
771 path.set_extension("mp4");969 path.set_extension("mp4");
772 }970 }
971 let codec = if path
972 .extension()
973 .and_then(|e| e.to_str())
974 .is_some_and(|e| e.eq_ignore_ascii_case("mov"))
975 {
976 VideoCodec::ProRes422
977 } else {
978 VideoCodec::H264Share
979 };
980
981 let comp_snapshot = self.comp.clone();
773 let opts = VideoExportOptions {982 let opts = VideoExportOptions {
774 target,983 target,
775 out_path: path.clone(),984 out_path: path.clone(),
776 range: [in_f, out_f],985 range: [in_f, out_f],
777 codec: VideoCodec::H264Share,986 codec,
778 crf: 26,987 crf: 26,
779 max_height: None,988 max_height: None,
780 include_audio: true,989 include_audio: true,
781 hiq: self.engine.hiq,990 hiq: self.engine.hiq,
782 proxy_scale: self.engine.proxy_scale,991 proxy_scale: self.engine.proxy_scale,
783 };992 };
784 let t0 = Instant::now();993 let total = (out_f - in_f + 1).max(1) as u32;
785 match export_node_video_ffmpeg(&mut self.engine, &self.comp, &opts, |p| {994 let label = match codec {
786 if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total {995 VideoCodec::ProRes422 | VideoCodec::ProRes4444 => format!("{node_name} (ProRes)"),
787 let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6);996 VideoCodec::H264Share => format!("{node_name} (MP4)"),
788 eprintln!(997 };
789 " [mp4 {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}",998 let initial = ExportProgress {
790 p.index + 1,999 frame: in_f,
791 p.total,1000 total: total as usize,
792 p.saver_name,1001 out_path: path,
793 p.frame,1002 saver_name: node_name,
794 p.eval_ms,1003 current_frame: in_f.max(0) as u32,
795 fps,1004 total_frames: total,
796 p.out_path.display()1005 label,
797 );1006 ..Default::default()
798 }1007 };
799 }) {1008
800 Ok(summary) => {1009 self.spawn_export_worker(initial, move |engine, control, notify| {
801 let mb = summary.file_bytes as f64 / (1024.0 * 1024.0);1010 let t0 = Instant::now();
802 let audio_tag = if summary.has_audio { " + audio" } else { "" };1011 match export_node_video_ffmpeg_with_progress(engine, &comp_snapshot, &opts, Some(control), |p| {
803 let msg = format!(1012 if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total {
804 "Exported {} frames{audio_tag} ({mb:.2} MB)",1013 let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6);
805 summary.frames_written1014 eprintln!(
806 );1015 " [video {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}",
807 eprintln!("{msg} -> {}", summary.out_path.display());1016 p.index + 1,
808 self.set_notice(msg.clone());1017 p.total,
809 Ok(msg)1018 p.saver_name,
810 }1019 p.frame,
811 Err(e) => {1020 p.eval_ms,
812 let err = format!("MP4 export failed: {e}");1021 fps,
813 eprintln!("{err}");1022 p.out_path.display()
814 self.set_notice(err.clone());1023 );
815 Err(err)1024 }
1025 notify();
1026 }) {
1027 Ok(summary) => {
1028 let mb = summary.file_bytes as f64 / (1024.0 * 1024.0);
1029 let audio_tag = if summary.has_audio { " + audio" } else { "" };
1030 Ok(format!(
1031 "Exported {} frames{audio_tag} ({mb:.2} MB) -> {}",
1032 summary.frames_written,
1033 summary.out_path.file_name().and_then(|n| n.to_str()).unwrap_or("video")
1034 ))
1035 }
1036 Err(e) if e == "Cancelled" => Err(e),
1037 Err(e) => Err(format!("Video export failed: {e}")),
816 }1038 }
817 }1039 })
818 }1040 }
8191041
820 fn save_viewer_frame_png(&mut self, slot: usize) -> Result<String, String> {1042 fn save_viewer_frame_png(&mut self, slot: usize) -> Result<String, String> {
...@@ -887,17 +1109,18 @@ impl Studio {...@@ -887,17 +1109,18 @@ impl Studio {
887 fn frame(&mut self, now: Instant) -> bool {1109 fn frame(&mut self, now: Instant) -> bool {
888 self.clock = now;1110 self.clock = now;
889 self.poll_audio_load();1111 self.poll_audio_load();
890 let prev_frame = self.playback.current_frame;1112 self.poll_export();
891 let (animating, frame_changed) = self.playback.tick(&self.comp, now);1113 let tick = self.playback.tick_synced(&self.comp, now);
892 if frame_changed {1114 if tick.frame_changed {
893 // Re-sync audio when playback loops back to start of render range
894 if self.playback.playing && self.playback.current_frame < prev_frame {
895 self.sync_audio(false, true);
896 }
897 for v in &mut self.viewers {1115 for v in &mut self.viewers {
898 v.dirty = true;1116 v.dirty = true;
899 }1117 }
900 }1118 }
1119 if tick.looped {
1120 self.sync_audio(false, true);
1121 }
1122 self.check_audio_sync_and_metadata(now);
1123 let animating = tick.playing;
9011124
902 self.sync_ram_ranges_and_prefetch();1125 self.sync_ram_ranges_and_prefetch();
903 let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();1126 let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();
...@@ -931,6 +1154,24 @@ impl Studio {...@@ -931,6 +1154,24 @@ impl Studio {
931 let can_undo = self.history.can_undo();1154 let can_undo = self.history.can_undo();
932 let can_redo = self.history.can_redo();1155 let can_redo = self.history.can_redo();
933 let primary_sel = self.flow.primary;1156 let primary_sel = self.flow.primary;
1157 let export_snapshot = self
1158 .active_export
1159 .as_ref()
1160 .map(|exp| (exp.control.snapshot_progress(), exp.cancelling));
1161 let notice_banner = if export_snapshot.is_none() {
1162 self.status_notice.as_ref().and_then(|(msg, at)| {
1163 if at.elapsed() < Duration::from_secs(8) {
1164 Some(msg.clone())
1165 } else {
1166 None
1167 }
1168 })
1169 } else {
1170 None
1171 };
1172 let show_status_strip = export_snapshot.is_some() || notice_banner.is_some();
1173 let strip_h = if show_status_strip { 28.0 } else { 0.0 };
1174
934 let Studio {1175 let Studio {
935 ui,1176 ui,
936 dock,1177 dock,
...@@ -967,15 +1208,27 @@ impl Studio {...@@ -967,15 +1208,27 @@ impl Studio {
967 let mut req_open = false;1208 let mut req_open = false;
968 let mut req_save = false;1209 let mut req_save = false;
969 let mut req_save_as = false;1210 let mut req_save_as = false;
1211 let mut req_cancel_export = false;
1212 let mut req_dismiss_notice = false;
970 let mut req_exit_to_depth: Option<usize> = None;1213 let mut req_exit_to_depth: Option<usize> = None;
971 let mut commit_rename: Option<(NodeId, String)> = None;1214 let mut commit_rename: Option<(NodeId, String)> = None;
972 let mut cancel_rename = false;1215 let mut cancel_rename = false;
9731216
1217 ui.open(
1218 "studio-root",
1219 ui::Spec {
1220 size: [ui::fill(), ui::fill()],
1221 axis: ui::Axis::Y,
1222 ..ui::Spec::default()
1223 },
1224 );
1225
1226 let dock_size = [size[0], (size[1] - strip_h).max(120.0)];
974 let mut d = dock.at(layout, seen, &String::clone);1227 let mut d = dock.at(layout, seen, &String::clone);
975 let events = d.build(1228 let events = d.build(
976 ui,1229 ui,
977 "studio-dock",1230 "studio-dock",
978 *size,1231 dock_size,
979 |_| Plus::Menu("Open Pane", &choices),1232 |_| Plus::Menu("Open Pane", &choices),
980 &(),1233 &(),
981 |name: &String, _| {1234 |name: &String, _| {
...@@ -1183,9 +1436,115 @@ impl Studio {...@@ -1183,9 +1436,115 @@ impl Studio {
1183 },1436 },
1184 );1437 );
11851438
1439 if show_status_strip {
1440 ui.open(
1441 "studio-status-strip",
1442 ui::Spec {
1443 size: [ui::fill(), ui::px(strip_h)],
1444 axis: ui::Axis::X,
1445 pad: [10.0, 3.0],
1446 gap: 8.0,
1447 fill: Some(ui.theme.strip),
1448 border: Some(ui.theme.rule),
1449 ..ui::Spec::default()
1450 },
1451 );
1452 if let Some((prog, cancelling)) = &export_snapshot {
1453 let total = prog.total_frames.max(1);
1454 let frac = (prog.completed_frames as f32 / total as f32).clamp(0.0, 1.0);
1455 let pct = (frac * 100.0).round() as u32;
1456 let fill_w = (frac * 176.0).round();
1457 let bar_bg = ui.theme.base;
1458 let bar_border = ui.theme.rule;
1459 let bar_accent = ui.theme.accent;
1460 ui.open(
1461 "export-progress-track",
1462 ui::Spec {
1463 size: [ui::px(180.0), ui::px(12.0)],
1464 axis: ui::Axis::X,
1465 pad: [2.0, 2.0],
1466 fill: Some(bar_bg),
1467 border: Some(bar_border),
1468 radius: 4.0,
1469 ..ui::Spec::default()
1470 },
1471 );
1472 if fill_w > 0.0 {
1473 ui.leaf(
1474 "export-progress-fill",
1475 ui::Spec {
1476 size: [ui::px(fill_w), ui::fill()],
1477 fill: Some(bar_accent),
1478 radius: 2.0,
1479 ..ui::Spec::default()
1480 },
1481 );
1482 }
1483 ui.close();
1484
1485 let status_txt = if *cancelling {
1486 format!(
1487 "Cancelling {} ({}/{})…",
1488 prog.label, prog.completed_frames, prog.total_frames
1489 )
1490 } else {
1491 format!(
1492 "Exporting {} {}/{} ({pct}%) · f{:04} · {:.1}s",
1493 prog.label,
1494 prog.completed_frames,
1495 prog.total_frames,
1496 prog.frame,
1497 prog.elapsed_secs
1498 )
1499 };
1500 let ink = ui.theme.text;
1501 ui.leaf(
1502 "export-progress-label",
1503 ui::Spec {
1504 size: [ui::fill(), ui::fill()],
1505 text: Some(&status_txt),
1506 font_size: Some(11.0),
1507 medium: true,
1508 color: Some(ink),
1509 ..ui::Spec::default()
1510 },
1511 );
1512 let cancel_lbl = if *cancelling { "Cancelling…" } else { "Cancel" };
1513 if studio_btn(ui, "export-cancel-btn", cancel_lbl, *cancelling).clicked && !*cancelling {
1514 req_cancel_export = true;
1515 }
1516 } else if let Some(msg) = &notice_banner {
1517 let ink = ui.theme.text;
1518 ui.leaf(
1519 "status-notice-label",
1520 ui::Spec {
1521 size: [ui::fill(), ui::fill()],
1522 text: Some(msg),
1523 font_size: Some(11.0),
1524 color: Some(ink),
1525 ..ui::Spec::default()
1526 },
1527 );
1528 if studio_btn(ui, "status-notice-dismiss", "×", false).clicked {
1529 req_dismiss_notice = true;
1530 }
1531 }
1532 ui.close();
1533 }
1534 ui.close(); // studio-root
1535
1186 let picked_tool = add_tool.build_ui(ui, *size);1536 let picked_tool = add_tool.build_ui(ui, *size);
1187 self.ui.end();1537 self.ui.end();
11881538
1539 if req_cancel_export {
1540 if let Some(exp) = &mut self.active_export {
1541 exp.control.cancel();
1542 exp.cancelling = true;
1543 }
1544 }
1545 if req_dismiss_notice {
1546 self.status_notice = None;
1547 }
1189 if req_open_add_tool {1548 if req_open_add_tool {
1190 self.add_tool.open();1549 self.add_tool.open();
1191 }1550 }
...@@ -1437,7 +1796,7 @@ impl Studio {...@@ -1437,7 +1796,7 @@ impl Studio {
1437 for (slot, a) in actions {1796 for (slot, a) in actions {
1438 match a {1797 match a {
1439 ViewerAction::TogglePlay => {1798 ViewerAction::TogglePlay => {
1440 self.playback.toggle_play(now);1799 self.playback.toggle_play_with_comp(&self.comp, now);
1441 self.sync_audio(true, false);1800 self.sync_audio(true, false);
1442 }1801 }
1443 ViewerAction::SetFrame(f) => {1802 ViewerAction::SetFrame(f) => {
...@@ -1538,6 +1897,9 @@ impl Studio {...@@ -1538,6 +1897,9 @@ impl Studio {
1538 }1897 }
1539 ViewerAction::SetInPoint => {1898 ViewerAction::SetInPoint => {
1540 self.playback.set_in_point(&self.comp);1899 self.playback.set_in_point(&self.comp);
1900 if self.playback.playing {
1901 self.sync_audio(false, true);
1902 }
1541 let [a, b] = self.playback.effective_preview_range(&self.comp);1903 let [a, b] = self.playback.effective_preview_range(&self.comp);
1542 self.set_notice(format!(1904 self.set_notice(format!(
1543 "In: f{} (preview f{a}..f{b})",1905 "In: f{} (preview f{a}..f{b})",
...@@ -1549,6 +1911,9 @@ impl Studio {...@@ -1549,6 +1911,9 @@ impl Studio {
1549 }1911 }
1550 ViewerAction::SetOutPoint => {1912 ViewerAction::SetOutPoint => {
1551 self.playback.set_out_point(&self.comp);1913 self.playback.set_out_point(&self.comp);
1914 if self.playback.playing {
1915 self.sync_audio(false, true);
1916 }
1552 let [a, b] = self.playback.effective_preview_range(&self.comp);1917 let [a, b] = self.playback.effective_preview_range(&self.comp);
1553 self.set_notice(format!(1918 self.set_notice(format!(
1554 "Out: f{} (preview f{a}..f{b})",1919 "Out: f{} (preview f{a}..f{b})",
...@@ -1560,6 +1925,9 @@ impl Studio {...@@ -1560,6 +1925,9 @@ impl Studio {
1560 }1925 }
1561 ViewerAction::ClearInOut => {1926 ViewerAction::ClearInOut => {
1562 self.playback.clear_in_out();1927 self.playback.clear_in_out();
1928 if self.playback.playing {
1929 self.sync_audio(false, true);
1930 }
1563 self.set_notice("Reset In/Out range");1931 self.set_notice("Reset In/Out range");
1564 for v in &mut self.viewers {1932 for v in &mut self.viewers {
1565 v.prepare_hud(&self.comp, &self.engine, &self.playback);1933 v.prepare_hud(&self.comp, &self.engine, &self.playback);
...@@ -1767,6 +2135,7 @@ impl WindowHost {...@@ -1767,6 +2135,7 @@ impl WindowHost {
1767 cli.show_keyframes,2135 cli.show_keyframes,
1768 true,2136 true,
1769 );2137 );
2138 studio.redraw_proxy = Some(proxy.clone());
1770 studio.ui.window_focused = window.has_focus();2139 studio.ui.window_focused = window.has_focus();
1771 studio.ui.clipboard = Clipboard::system();2140 studio.ui.clipboard = Clipboard::system();
1772 window.request_redraw();2141 window.request_redraw();
...@@ -1900,7 +2269,7 @@ impl WindowHost {...@@ -1900,7 +2269,7 @@ impl WindowHost {
1900 _ => false,2269 _ => false,
1901 };2270 };
1902 if is_space && !self.studio.add_tool.open {2271 if is_space && !self.studio.add_tool.open {
1903 self.studio.playback.toggle_play(Instant::now());2272 self.studio.playback.toggle_play_with_comp(&self.studio.comp, Instant::now());
1904 self.studio.sync_audio(true, false);2273 self.studio.sync_audio(true, false);
1905 self.window.request_redraw();2274 self.window.request_redraw();
1906 return;2275 return;
...@@ -2021,6 +2390,11 @@ impl ApplicationHandler<UserEvent> for App {...@@ -2021,6 +2390,11 @@ impl ApplicationHandler<UserEvent> for App {
2021 host.window.request_redraw();2390 host.window.request_redraw();
2022 return;2391 return;
2023 }2392 }
2393 if host.studio.active_export.is_some() {
2394 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(100)));
2395 host.window.request_redraw();
2396 return;
2397 }
2024 if host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) {2398 if host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) {
2025 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(200)));2399 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(200)));
2026 host.window.request_redraw();2400 host.window.request_redraw();
crates/engine/src/export.rs+341-26
...@@ -43,7 +43,7 @@ impl Default for ExportOptions {...@@ -43,7 +43,7 @@ impl Default for ExportOptions {
43 }43 }
44}44}
4545
46#[derive(Clone, Debug)]46#[derive(Clone, Debug, Default)]
47pub struct ExportProgress {47pub struct ExportProgress {
48 pub frame: i64,48 pub frame: i64,
49 pub index: usize,49 pub index: usize,
...@@ -51,6 +51,85 @@ pub struct ExportProgress {...@@ -51,6 +51,85 @@ pub struct ExportProgress {
51 pub eval_ms: f64,51 pub eval_ms: f64,
52 pub out_path: PathBuf,52 pub out_path: PathBuf,
53 pub saver_name: String,53 pub saver_name: String,
54 pub current_frame: u32,
55 pub total_frames: u32,
56 pub completed_frames: u32,
57 pub elapsed_secs: f32,
58 pub label: String,
59}
60
61/// Cooperative cancellation token and shared progress state for background exports.
62#[derive(Clone, Debug)]
63pub struct ExportControl {
64 pub cancel: Arc<AtomicBool>,
65 pub progress: Arc<Mutex<ExportProgress>>,
66}
67
68impl Default for ExportControl {
69 fn default() -> Self {
70 Self::new()
71 }
72}
73
74impl ExportControl {
75 pub fn new() -> Self {
76 Self {
77 cancel: Arc::new(AtomicBool::new(false)),
78 progress: Arc::new(Mutex::new(ExportProgress::default())),
79 }
80 }
81
82 pub fn with_cancel(cancel: Arc<AtomicBool>) -> Self {
83 Self {
84 cancel,
85 progress: Arc::new(Mutex::new(ExportProgress::default())),
86 }
87 }
88
89 pub fn cancel(&self) {
90 self.cancel.store(true, Ordering::Release);
91 }
92
93 pub fn is_cancelled(&self) -> bool {
94 self.cancel.load(Ordering::Acquire)
95 }
96
97 pub fn update_progress(&self, progress: &ExportProgress) {
98 if let Ok(mut guard) = self.progress.lock() {
99 *guard = progress.clone();
100 }
101 }
102
103 pub fn snapshot_progress(&self) -> ExportProgress {
104 self.progress
105 .lock()
106 .map(|guard| guard.clone())
107 .unwrap_or_default()
108 }
109}
110
111fn make_progress(
112 frame: i64,
113 index: usize,
114 total: usize,
115 eval_ms: f64,
116 out_path: PathBuf,
117 label: String,
118 started_at: Instant,
119) -> ExportProgress {
120 ExportProgress {
121 frame,
122 index,
123 total,
124 eval_ms,
125 out_path,
126 saver_name: label.clone(),
127 current_frame: frame.max(0) as u32,
128 total_frames: total as u32,
129 completed_frames: (index + 1) as u32,
130 elapsed_secs: started_at.elapsed().as_secs_f32(),
131 label,
132 }
54}133}
55134
56#[derive(Clone, Debug)]135#[derive(Clone, Debug)]
...@@ -145,8 +224,23 @@ pub fn export_saver_png_sequence(...@@ -145,8 +224,23 @@ pub fn export_saver_png_sequence(
145 engine: &mut Engine,224 engine: &mut Engine,
146 comp: &Comp,225 comp: &Comp,
147 opts: &ExportOptions,226 opts: &ExportOptions,
227 on_progress: impl FnMut(&ExportProgress),
228) -> Result<ExportSummary, String> {
229 export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress)
230}
231
232/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative
233/// cancellation and live progress reporting via `ExportControl`.
234pub fn export_saver_png_sequence_with_progress(
235 engine: &mut Engine,
236 comp: &Comp,
237 opts: &ExportOptions,
238 control: Option<&ExportControl>,
148 mut on_progress: impl FnMut(&ExportProgress),239 mut on_progress: impl FnMut(&ExportProgress),
149) -> Result<ExportSummary, String> {240) -> Result<ExportSummary, String> {
241 if control.is_some_and(ExportControl::is_cancelled) {
242 return Err("Cancelled".to_owned());
243 }
150 let saver = select_saver(comp, opts.saver_name.as_deref())?;244 let saver = select_saver(comp, opts.saver_name.as_deref())?;
151 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);245 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);
152 let [start, end] = opts.range_override.unwrap_or(saver.range);246 let [start, end] = opts.range_override.unwrap_or(saver.range);
...@@ -171,9 +265,11 @@ pub fn export_saver_png_sequence(...@@ -171,9 +265,11 @@ pub fn export_saver_png_sequence(
171 let t0 = Instant::now();265 let t0 = Instant::now();
172 let mut first_path: Option<PathBuf> = None;266 let mut first_path: Option<PathBuf> = None;
173 let mut last_path: Option<PathBuf> = None;267 let mut last_path: Option<PathBuf> = None;
268 let mut frames_written: usize = 0;
174269
175 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));270 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
176 let failed = Arc::new(AtomicBool::new(false));271 let failed = Arc::new(AtomicBool::new(false));
272 let cancelled = Arc::new(AtomicBool::new(false));
177273
178 let eval_result: Result<(), String> = std::thread::scope(|scope| {274 let eval_result: Result<(), String> = std::thread::scope(|scope| {
179 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(workers * 2);275 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(workers * 2);
...@@ -184,6 +280,7 @@ pub fn export_saver_png_sequence(...@@ -184,6 +280,7 @@ pub fn export_saver_png_sequence(
184 let rx_c = Arc::clone(&shared_rx);280 let rx_c = Arc::clone(&shared_rx);
185 let err_c = Arc::clone(&first_err);281 let err_c = Arc::clone(&first_err);
186 let fail_c = Arc::clone(&failed);282 let fail_c = Arc::clone(&failed);
283 let cancel_c = Arc::clone(&cancelled);
187 handles.push(scope.spawn(move || {284 handles.push(scope.spawn(move || {
188 loop {285 loop {
189 let job = {286 let job = {
...@@ -191,7 +288,7 @@ pub fn export_saver_png_sequence(...@@ -191,7 +288,7 @@ pub fn export_saver_png_sequence(
191 guard.recv()288 guard.recv()
192 };289 };
193 let Ok(job) = job else { break };290 let Ok(job) = job else { break };
194 if fail_c.load(Ordering::Acquire) {291 if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) {
195 continue;292 continue;
196 }293 }
197 if let Err(e) = write_png_fast(&job.path, job.size, &job.pixels) {294 if let Err(e) = write_png_fast(&job.path, job.size, &job.pixels) {
...@@ -211,6 +308,10 @@ pub fn export_saver_png_sequence(...@@ -211,6 +308,10 @@ pub fn export_saver_png_sequence(
211 if failed.load(Ordering::Acquire) {308 if failed.load(Ordering::Acquire) {
212 break;309 break;
213 }310 }
311 if control.is_some_and(ExportControl::is_cancelled) {
312 cancelled.store(true, Ordering::Release);
313 break;
314 }
214 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {315 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {
215 Ok(p) => p,316 Ok(p) => p,
216 Err(e) => {317 Err(e) => {
...@@ -218,10 +319,6 @@ pub fn export_saver_png_sequence(...@@ -218,10 +319,6 @@ pub fn export_saver_png_sequence(
218 break;319 break;
219 }320 }
220 };321 };
221 if first_path.is_none() {
222 first_path = Some(out_path.clone());
223 }
224 last_path = Some(out_path.clone());
225322
226 let (tex, stats) = engine.evaluate(comp, target, frame as f64);323 let (tex, stats) = engine.evaluate(comp, target, frame as f64);
227 let pixels = match engine.readback_rgba(&tex) {324 let pixels = match engine.readback_rgba(&tex) {
...@@ -231,15 +328,29 @@ pub fn export_saver_png_sequence(...@@ -231,15 +328,29 @@ pub fn export_saver_png_sequence(
231 break;328 break;
232 }329 }
233 };330 };
331 if control.is_some_and(ExportControl::is_cancelled) {
332 cancelled.store(true, Ordering::Release);
333 break;
334 }
335
336 if first_path.is_none() {
337 first_path = Some(out_path.clone());
338 }
339 last_path = Some(out_path.clone());
234340
235 on_progress(&ExportProgress {341 let prog = make_progress(
236 frame,342 frame,
237 index: idx,343 idx,
238 total,344 total,
239 eval_ms: stats.eval_ms,345 stats.eval_ms,
240 out_path: out_path.clone(),346 out_path.clone(),
241 saver_name: saver.name.clone(),347 saver.name.clone(),
242 });348 t0,
349 );
350 if let Some(ctrl) = control {
351 ctrl.update_progress(&prog);
352 }
353 on_progress(&prog);
243354
244 if tx355 if tx
245 .send(EncodeJob {356 .send(EncodeJob {
...@@ -251,6 +362,7 @@ pub fn export_saver_png_sequence(...@@ -251,6 +362,7 @@ pub fn export_saver_png_sequence(
251 {362 {
252 break;363 break;
253 }364 }
365 frames_written += 1;
254 }366 }
255367
256 drop(tx);368 drop(tx);
...@@ -266,6 +378,9 @@ pub fn export_saver_png_sequence(...@@ -266,6 +378,9 @@ pub fn export_saver_png_sequence(
266 return Err(e);378 return Err(e);
267 }379 }
268 }380 }
381 if cancelled.load(Ordering::Acquire) {
382 return Err("Cancelled".to_owned());
383 }
269 Ok(())384 Ok(())
270 });385 });
271386
...@@ -276,7 +391,7 @@ pub fn export_saver_png_sequence(...@@ -276,7 +391,7 @@ pub fn export_saver_png_sequence(
276391
277 Ok(ExportSummary {392 Ok(ExportSummary {
278 saver_name: saver.name,393 saver_name: saver.name,
279 frames_written: total,394 frames_written,
280 total_ms: t0.elapsed().as_secs_f64() * 1000.0,395 total_ms: t0.elapsed().as_secs_f64() * 1000.0,
281 first_path,396 first_path,
282 last_path,397 last_path,
...@@ -359,8 +474,23 @@ pub fn export_node_video_ffmpeg(...@@ -359,8 +474,23 @@ pub fn export_node_video_ffmpeg(
359 engine: &mut Engine,474 engine: &mut Engine,
360 comp: &Comp,475 comp: &Comp,
361 opts: &VideoExportOptions,476 opts: &VideoExportOptions,
477 on_progress: impl FnMut(ExportProgress),
478) -> Result<VideoExportSummary, String> {
479 export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress)
480}
481
482/// 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`.
484pub fn export_node_video_ffmpeg_with_progress(
485 engine: &mut Engine,
486 comp: &Comp,
487 opts: &VideoExportOptions,
488 control: Option<&ExportControl>,
362 mut on_progress: impl FnMut(ExportProgress),489 mut on_progress: impl FnMut(ExportProgress),
363) -> Result<VideoExportSummary, String> {490) -> Result<VideoExportSummary, String> {
491 if control.is_some_and(ExportControl::is_cancelled) {
492 return Err("Cancelled".to_owned());
493 }
364 let [start, end] = opts.range;494 let [start, end] = opts.range;
365 if end < start {495 if end < start {
366 return Err(format!("invalid export frame range {start}..={end}"));496 return Err(format!("invalid export frame range {start}..={end}"));
...@@ -398,6 +528,9 @@ pub fn export_node_video_ffmpeg(...@@ -398,6 +528,9 @@ pub fn export_node_video_ffmpeg(
398 let first_pixels = engine528 let first_pixels = engine
399 .readback_rgba(&first_tex)529 .readback_rgba(&first_tex)
400 .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?;530 .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?;
531 if control.is_some_and(ExportControl::is_cancelled) {
532 return Err("Cancelled".to_owned());
533 }
401534
402 let duration_secs = total as f64 / fps;535 let duration_secs = total as f64 / fps;
403 let audio_start_secs = (start as f64 - comp.audio_offset) / fps;536 let audio_start_secs = (start as f64 - comp.audio_offset) / fps;
...@@ -539,6 +672,7 @@ pub fn export_node_video_ffmpeg(...@@ -539,6 +672,7 @@ pub fn export_node_video_ffmpeg(
539 });672 });
540673
541 let mut pipe_err: Option<String> = None;674 let mut pipe_err: Option<String> = None;
675 let mut cancelled = false;
542 {676 {
543 let mut stdin = child677 let mut stdin = child
544 .stdin678 .stdin
...@@ -548,16 +682,25 @@ pub fn export_node_video_ffmpeg(...@@ -548,16 +682,25 @@ pub fn export_node_video_ffmpeg(
548 if let Err(e) = stdin.write_all(&first_pixels) {682 if let Err(e) = stdin.write_all(&first_pixels) {
549 pipe_err = Some(format!("failed writing frame {start} to ffmpeg: {e}"));683 pipe_err = Some(format!("failed writing frame {start} to ffmpeg: {e}"));
550 } else {684 } else {
551 on_progress(ExportProgress {685 let first_prog = make_progress(
552 frame: start,686 start,
553 index: 0,687 0,
554 total,688 total,
555 eval_ms: first_stats.eval_ms,689 first_stats.eval_ms,
556 out_path: opts.out_path.clone(),690 opts.out_path.clone(),
557 saver_name: node_name.clone(),691 node_name.clone(),
558 });692 t0,
693 );
694 if let Some(ctrl) = control {
695 ctrl.update_progress(&first_prog);
696 }
697 on_progress(first_prog);
559698
560 for (idx, frame) in ((start + 1)..=end).enumerate() {699 for (idx, frame) in ((start + 1)..=end).enumerate() {
700 if control.is_some_and(ExportControl::is_cancelled) {
701 cancelled = true;
702 break;
703 }
561 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);704 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
562 let pixels = match engine.readback_rgba(&tex) {705 let pixels = match engine.readback_rgba(&tex) {
563 Ok(px) => px,706 Ok(px) => px,
...@@ -566,6 +709,10 @@ pub fn export_node_video_ffmpeg(...@@ -566,6 +709,10 @@ pub fn export_node_video_ffmpeg(
566 break;709 break;
567 }710 }
568 };711 };
712 if control.is_some_and(ExportControl::is_cancelled) {
713 cancelled = true;
714 break;
715 }
569 let frame_bytes = if tex.size != [width, height] {716 let frame_bytes = if tex.size != [width, height] {
570 let Some(img) = image::RgbaImage::from_raw(tex.size[0], tex.size[1], pixels)717 let Some(img) = image::RgbaImage::from_raw(tex.size[0], tex.size[1], pixels)
571 else {718 else {
...@@ -587,14 +734,19 @@ pub fn export_node_video_ffmpeg(...@@ -587,14 +734,19 @@ pub fn export_node_video_ffmpeg(
587 pipe_err = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));734 pipe_err = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));
588 break;735 break;
589 }736 }
590 on_progress(ExportProgress {737 let prog = make_progress(
591 frame,738 frame,
592 index: idx + 1,739 idx + 1,
593 total,740 total,
594 eval_ms: stats.eval_ms,741 stats.eval_ms,
595 out_path: opts.out_path.clone(),742 opts.out_path.clone(),
596 saver_name: node_name.clone(),743 node_name.clone(),
597 });744 t0,
745 );
746 if let Some(ctrl) = control {
747 ctrl.update_progress(&prog);
748 }
749 on_progress(prog);
598 }750 }
599 }751 }
600 let _ = stdin.flush();752 let _ = stdin.flush();
...@@ -606,6 +758,10 @@ pub fn export_node_video_ffmpeg(...@@ -606,6 +758,10 @@ pub fn export_node_video_ffmpeg(
606 let stderr_text = stderr_thread.join().unwrap_or_default();758 let stderr_text = stderr_thread.join().unwrap_or_default();
607 let stderr_trim = stderr_text.trim();759 let stderr_trim = stderr_text.trim();
608760
761 if cancelled {
762 let _ = std::fs::remove_file(&opts.out_path);
763 return Err("Cancelled".to_owned());
764 }
609 if let Some(err) = pipe_err {765 if let Some(err) = pipe_err {
610 if !stderr_trim.is_empty() {766 if !stderr_trim.is_empty() {
611 return Err(format!("{err} (ffmpeg: {stderr_trim})"));767 return Err(format!("{err} (ffmpeg: {stderr_trim})"));
...@@ -927,4 +1083,163 @@ mod tests {...@@ -927,4 +1083,163 @@ mod tests {
9271083
928 let _ = std::fs::remove_dir_all(&tmp_dir);1084 let _ = std::fs::remove_dir_all(&tmp_dir);
929 }1085 }
1086
1087 #[test]
1088 fn saver_export_reports_progress_and_stops_on_cancel() {
1089 let tmp_dir = std::env::temp_dir().join(format!(
1090 "fission-saver-cancel-test-{}",
1091 std::process::id()
1092 ));
1093 let _ = std::fs::remove_dir_all(&tmp_dir);
1094 let saver_path = tmp_dir.join("shot_0000.png");
1095 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
1096
1097 let comp_src = format!(
1098 r#"Composition {{
1099 CurrentTime = 10,
1100 RenderRange = {{ 10, 15 }},
1101 GlobalRange = {{ 0, 100 }},
1102 Tools = ordered() {{
1103 BG = Background {{
1104 Inputs = {{
1105 Width = Input {{ Value = 64, }},
1106 Height = Input {{ Value = 32, }},
1107 TopLeftRed = Input {{ Value = 0.7, }},
1108 TopLeftAlpha = Input {{ Value = 1, }},
1109 }},
1110 }},
1111 Saver1 = Saver {{
1112 Inputs = {{
1113 Clip = Input {{
1114 Value = Clip {{
1115 Filename = "{saver_path_escaped}",
1116 FormatID = "PNGFormat",
1117 Saving = true,
1118 }},
1119 }},
1120 Input = Input {{
1121 SourceOp = "BG",
1122 Source = "Output",
1123 }},
1124 }},
1125 }},
1126 }},
1127 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }},
1128}}"#
1129 );
1130
1131 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp");
1132 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1133 let control = ExportControl::new();
1134 let ctrl_cb = control.clone();
1135 let mut reported = Vec::new();
1136
1137 let err = export_saver_png_sequence_with_progress(
1138 &mut engine,
1139 &comp,
1140 &ExportOptions::default(),
1141 Some(&control),
1142 |p| {
1143 reported.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone()));
1144 if p.completed_frames >= 2 {
1145 ctrl_cb.cancel();
1146 }
1147 },
1148 )
1149 .expect_err("saver export should cancel early");
1150
1151 assert_eq!(err, "Cancelled");
1152 assert_eq!(reported.len(), 2);
1153 assert_eq!(reported[0].0, 10);
1154 assert_eq!(reported[0].1, 1);
1155 assert_eq!(reported[0].2, 6);
1156 assert_eq!(reported[0].3, "Saver1");
1157 assert_eq!(reported[1].0, 11);
1158 assert_eq!(reported[1].1, 2);
1159
1160 let snap = control.snapshot_progress();
1161 assert_eq!(snap.completed_frames, 2);
1162 assert_eq!(snap.total_frames, 6);
1163 assert!(snap.elapsed_secs >= 0.0);
1164 assert!(!tmp_dir.join("shot_0015.png").exists());
1165
1166 let _ = std::fs::remove_dir_all(&tmp_dir);
1167 }
1168
1169 #[test]
1170 fn video_export_reports_progress_and_cleans_up_on_cancel() {
1171 let tmp_dir = std::env::temp_dir().join(format!(
1172 "fission-video-cancel-test-{}",
1173 std::process::id()
1174 ));
1175 let _ = std::fs::remove_dir_all(&tmp_dir);
1176 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1177
1178 let comp_src = r#"Composition {
1179 CurrentTime = 1,
1180 RenderRange = { 1, 12 },
1181 GlobalRange = { 0, 100 },
1182 Tools = ordered() {
1183 BG = Background {
1184 Inputs = {
1185 Width = Input { Value = 128, },
1186 Height = Input { Value = 72, },
1187 TopLeftRed = Input { Value = 0.2, },
1188 TopLeftGreen = Input { Value = 0.6, },
1189 TopLeftBlue = Input { Value = 0.9, },
1190 TopLeftAlpha = Input { Value = 1, },
1191 },
1192 },
1193 },
1194 Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } },
1195}"#;
1196
1197 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp");
1198 let target = comp.find_node("BG").expect("find BG node");
1199 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1200 let out_mp4 = tmp_dir.join("cancelled.mp4");
1201 let control = ExportControl::new();
1202 let ctrl_cb = control.clone();
1203 let mut seen = Vec::new();
1204
1205 let err = export_node_video_ffmpeg_with_progress(
1206 &mut engine,
1207 &comp,
1208 &VideoExportOptions {
1209 target,
1210 out_path: out_mp4.clone(),
1211 range: [1, 12],
1212 codec: VideoCodec::H264Share,
1213 crf: 26,
1214 max_height: None,
1215 include_audio: false,
1216 hiq: true,
1217 proxy_scale: 1,
1218 },
1219 Some(&control),
1220 |p| {
1221 seen.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone()));
1222 if p.completed_frames >= 3 {
1223 ctrl_cb.cancel();
1224 }
1225 },
1226 )
1227 .expect_err("video export should cancel early");
1228
1229 assert_eq!(err, "Cancelled");
1230 assert_eq!(seen.len(), 3);
1231 assert_eq!(seen[0].0, 1);
1232 assert_eq!(seen[0].1, 1);
1233 assert_eq!(seen[0].2, 12);
1234 assert_eq!(seen[0].3, "BG");
1235 assert_eq!(seen[2].0, 3);
1236 assert_eq!(seen[2].1, 3);
1237
1238 let snap = control.snapshot_progress();
1239 assert_eq!(snap.completed_frames, 3);
1240 assert_eq!(snap.total_frames, 12);
1241 assert!(!out_mp4.exists(), "partial mp4 should be removed after cancellation");
1242
1243 let _ = std::fs::remove_dir_all(&tmp_dir);
1244 }
930}1245}
crates/viewer/src/lib.rs+254-12
...@@ -27,6 +27,14 @@ pub enum SyncMode {...@@ -27,6 +27,14 @@ pub enum SyncMode {
27 EveryFrame,27 EveryFrame,
28}28}
2929
30/// Outcome of advancing [`PlaybackClock::tick_synced`].
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct TickResult {
33 pub playing: bool,
34 pub frame_changed: bool,
35 pub looped: bool,
36}
37
30/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline).38/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline).
31pub struct PlaybackClock {39pub struct PlaybackClock {
32 pub current_frame: f64,40 pub current_frame: f64,
...@@ -85,6 +93,16 @@ impl PlaybackClock {...@@ -85,6 +93,16 @@ impl PlaybackClock {
85 let r1 = comp.render_range[1].max(r0);93 let r1 = comp.render_range[1].max(r0);
86 let f = (self.current_frame.round() as i64).clamp(r0, r1);94 let f = (self.current_frame.round() as i64).clamp(r0, r1);
87 self.in_out_range[0] = Some(f);95 self.in_out_range[0] = Some(f);
96 if self.playing {
97 let [p0, p1] = self.effective_preview_range(comp);
98 if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 {
99 self.current_frame = p0 as f64;
100 }
101 let now = Instant::now();
102 self.anchor_time = now;
103 self.anchor_frame = self.current_frame;
104 self.last_every_step = now;
105 }
88 }106 }
89107
90 pub fn set_out_point(&mut self, comp: &Comp) {108 pub fn set_out_point(&mut self, comp: &Comp) {
...@@ -92,10 +110,75 @@ impl PlaybackClock {...@@ -92,10 +110,75 @@ impl PlaybackClock {
92 let r1 = comp.render_range[1].max(r0);110 let r1 = comp.render_range[1].max(r0);
93 let f = (self.current_frame.round() as i64).clamp(r0, r1);111 let f = (self.current_frame.round() as i64).clamp(r0, r1);
94 self.in_out_range[1] = Some(f);112 self.in_out_range[1] = Some(f);
113 if self.playing {
114 let [p0, p1] = self.effective_preview_range(comp);
115 if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 {
116 self.current_frame = p0 as f64;
117 }
118 let now = Instant::now();
119 self.anchor_time = now;
120 self.anchor_frame = self.current_frame;
121 self.last_every_step = now;
122 }
95 }123 }
96124
97 pub fn clear_in_out(&mut self) {125 pub fn clear_in_out(&mut self) {
98 self.in_out_range = [None, None];126 self.in_out_range = [None, None];
127 if self.playing {
128 let now = Instant::now();
129 self.anchor_time = now;
130 self.anchor_frame = self.current_frame;
131 self.last_every_step = now;
132 }
133 }
134
135 /// Exact audio track timestamp (in seconds) for `frame` under `comp.fps` and `comp.audio_offset`.
136 pub fn audio_time_for_frame(comp: &Comp, frame: f64) -> f64 {
137 (frame - comp.audio_offset) / comp.fps.max(1.0)
138 }
139
140 /// Exact audio track timestamp (in seconds) for the current playhead frame.
141 pub fn audio_target_secs(&self, comp: &Comp) -> f64 {
142 Self::audio_time_for_frame(comp, self.current_frame)
143 }
144
145 /// Expected live audio playback timestamp (in seconds) at wall-clock `now`.
146 ///
147 /// In `RealtimeDrop`, tracks continuous wall-clock frame progress across the preview range.
148 /// In `EveryFrame`, bounds sub-frame progress to `[0, 1/fps]` so slow frame renders do not
149 /// let the audio stream drift ahead of the displayed frame.
150 pub fn expected_audio_secs(&self, comp: &Comp, now: Instant) -> f64 {
151 let fps = comp.fps.max(1.0);
152 if !self.playing {
153 return Self::audio_time_for_frame(comp, self.current_frame);
154 }
155 match self.sync_mode {
156 SyncMode::RealtimeDrop => {
157 let [p0, p1] = self.effective_preview_range(comp);
158 let r0 = p0 as f64;
159 let r1 = p1.max(p0) as f64;
160 let span = (r1 - r0 + 1.0).max(1.0);
161 if span <= 1.0 {
162 return Self::audio_time_for_frame(comp, r0);
163 }
164 let base = if self.anchor_frame < r0 || self.anchor_frame > r1 {
165 r0
166 } else {
167 self.anchor_frame
168 };
169 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();
170 let continuous = r0 + (base - r0 + elapsed * fps).rem_euclid(span);
171 Self::audio_time_for_frame(comp, continuous)
172 }
173 SyncMode::EveryFrame => {
174 let frame_dur = 1.0 / fps;
175 let sub = now
176 .saturating_duration_since(self.last_every_step)
177 .as_secs_f64()
178 .clamp(0.0, frame_dur);
179 Self::audio_time_for_frame(comp, self.current_frame) + sub
180 }
181 }
99 }182 }
100183
101 pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool {184 pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool {
...@@ -119,11 +202,38 @@ impl PlaybackClock {...@@ -119,11 +202,38 @@ impl PlaybackClock {
119 self.last_every_step = now;202 self.last_every_step = now;
120 }203 }
121204
205 /// Toggles playback and, when starting, snaps playhead into `effective_preview_range(comp)`
206 /// if it was outside so video and audio start locked on the same frame.
207 pub fn toggle_play_with_comp(&mut self, comp: &Comp, now: Instant) {
208 self.playing = !self.playing;
209 if self.playing {
210 let [p0, p1] = self.effective_preview_range(comp);
211 let r0 = p0 as f64;
212 let r1 = p1.max(p0) as f64;
213 if self.current_frame < r0 || self.current_frame > r1 {
214 self.current_frame = r0;
215 }
216 }
217 self.anchor_time = now;
218 self.anchor_frame = self.current_frame;
219 self.last_every_step = now;
220 }
221
122 /// Advances the playback clock; returns `(still_playing, frame_changed)`.222 /// Advances the playback clock; returns `(still_playing, frame_changed)`.
123 /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime!223 /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime!
124 pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) {224 pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) {
225 let res = self.tick_synced(comp, now);
226 (res.playing, res.frame_changed)
227 }
228
229 /// Advances the playback clock and reports frame change plus exact loop wraparound.
230 pub fn tick_synced(&mut self, comp: &Comp, now: Instant) -> TickResult {
125 if !self.playing {231 if !self.playing {
126 return (false, false);232 return TickResult {
233 playing: false,
234 frame_changed: false,
235 looped: false,
236 };
127 }237 }
128 let [p0, p1] = self.effective_preview_range(comp);238 let [p0, p1] = self.effective_preview_range(comp);
129 let r0 = p0 as f64;239 let r0 = p0 as f64;
...@@ -133,30 +243,72 @@ impl PlaybackClock {...@@ -133,30 +243,72 @@ impl PlaybackClock {
133 let frame_dur = Duration::from_secs_f64(1.0 / fps);243 let frame_dur = Duration::from_secs_f64(1.0 / fps);
134244
135 let mut changed = false;245 let mut changed = false;
246 let mut looped = false;
136 match self.sync_mode {247 match self.sync_mode {
137 SyncMode::RealtimeDrop => {248 SyncMode::RealtimeDrop => {
138 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();249 if span <= 1.0 {
139 let adv = (elapsed * fps).floor();250 if (self.current_frame - r0).abs() >= 1.0 {
140 let next = r0 + (self.anchor_frame - r0 + adv).rem_euclid(span);251 self.current_frame = r0;
141 if (next - self.current_frame).abs() >= 1.0 {252 changed = true;
142 self.current_frame = next;253 }
143 changed = true;254 self.anchor_frame = r0;
255 self.anchor_time = now;
256 } else {
257 if self.anchor_frame < r0 || self.anchor_frame > r1 {
258 self.anchor_frame = r0;
259 self.anchor_time = now;
260 if (self.current_frame - r0).abs() >= 1.0 {
261 self.current_frame = r0;
262 changed = true;
263 looped = true;
264 }
265 }
266 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();
267 let adv = (elapsed * fps).floor();
268 let raw = (self.anchor_frame - r0) + adv;
269 let wrapped = raw >= span;
270 let next = r0 + raw.rem_euclid(span);
271 if wrapped {
272 self.anchor_frame = next;
273 self.anchor_time = now;
274 looped = true;
275 }
276 if (next - self.current_frame).abs() >= 1.0 {
277 self.current_frame = next;
278 changed = true;
279 }
144 }280 }
145 }281 }
146 SyncMode::EveryFrame => {282 SyncMode::EveryFrame => {
147 if now.saturating_duration_since(self.last_every_step) >= frame_dur {283 let elapsed = now.saturating_duration_since(self.last_every_step);
148 let next = if self.current_frame + 1.0 > r1 || self.current_frame < r0 {284 if elapsed >= frame_dur {
285 let out_or_end = self.current_frame + 1.0 > r1 || self.current_frame < r0;
286 let next = if out_or_end {
287 if span > 1.0 {
288 looped = true;
289 }
149 r0290 r0
150 } else {291 } else {
151 self.current_frame + 1.0292 self.current_frame + 1.0
152 };293 };
294 if (next - self.current_frame).abs() >= 1.0 {
295 changed = true;
296 }
153 self.current_frame = next;297 self.current_frame = next;
154 self.last_every_step = now;298 // Preserve exact cadence under minor timer jitter while avoiding catch-up bursts after stalls.
155 changed = true;299 if elapsed < frame_dur.mul_f64(2.0) {
300 self.last_every_step += frame_dur;
301 } else {
302 self.last_every_step = now;
303 }
156 }304 }
157 }305 }
158 }306 }
159 (true, changed)307 TickResult {
308 playing: true,
309 frame_changed: changed,
310 looped,
311 }
160 }312 }
161313
162 pub fn next_wake(&self, comp: &Comp) -> Duration {314 pub fn next_wake(&self, comp: &Comp) -> Duration {
...@@ -1378,4 +1530,94 @@ mod tests {...@@ -1378,4 +1530,94 @@ mod tests {
1378 );1530 );
1379 assert!(!viewer.is_context_menu_open());1531 assert!(!viewer.is_context_menu_open());
1380 }1532 }
1533
1534 #[test]
1535 fn playback_clock_in_out_wraparound_realtime_and_every_frame() {
1536 let comp = test_comp(); // fps = 30, render_range = [10, 50]
1537 let t0 = Instant::now();
1538
1539 // RealtimeDrop: starting outside [20, 24] snaps cleanly to 20, then wraps 24 -> 20
1540 let mut rt = PlaybackClock::new();
1541 rt.init_from_comp(&comp);
1542 rt.in_out_range = [Some(20), Some(24)];
1543 rt.set_frame(&comp, 12.0, t0); // outside In/Out range
1544 rt.toggle_play_with_comp(&comp, t0);
1545 assert_eq!(rt.current_frame, 20.0);
1546
1547 let step = Duration::from_secs_f64(1.0 / 30.0);
1548 // Advance 4 frames -> frame 24 (last frame in [20..=24])
1549 let r4 = rt.tick_synced(&comp, t0 + step * 4 + Duration::from_millis(2));
1550 assert!(r4.playing);
1551 assert!(r4.frame_changed);
1552 assert!(!r4.looped);
1553 assert_eq!(rt.current_frame, 24.0);
1554
1555 // Advance 5th frame -> wraps cleanly back to 20 and reports looped = true
1556 let r5 = rt.tick_synced(&comp, t0 + step * 5 + Duration::from_millis(2));
1557 assert!(r5.playing);
1558 assert!(r5.frame_changed);
1559 assert!(r5.looped);
1560 assert_eq!(rt.current_frame, 20.0);
1561
1562 // Next frame after wrap advances from 20 -> 21 without double-looping
1563 let r6 = rt.tick_synced(&comp, t0 + step * 6 + Duration::from_millis(4));
1564 assert!(r6.frame_changed);
1565 assert!(!r6.looped);
1566 assert_eq!(rt.current_frame, 21.0);
1567
1568 // EveryFrame: steps +1 per >=1/fps, preserves cadence across minor jitter, wraps 22 -> 20
1569 let mut ef = PlaybackClock::new();
1570 ef.init_from_comp(&comp);
1571 ef.sync_mode = SyncMode::EveryFrame;
1572 ef.in_out_range = [Some(20), Some(22)];
1573 ef.set_frame(&comp, 20.0, t0);
1574 ef.toggle_play_with_comp(&comp, t0);
1575
1576 // Minor 4ms jitter on step 1
1577 let e1 = ef.tick_synced(&comp, t0 + step + Duration::from_millis(4));
1578 assert_eq!((e1.frame_changed, e1.looped, ef.current_frame), (true, false, 21.0));
1579 // Step 2 fires at t0 + 2*step (doesn't lose the 4ms jitter!)
1580 let e2 = ef.tick_synced(&comp, t0 + step * 2 + Duration::from_millis(1));
1581 assert_eq!((e2.frame_changed, e2.looped, ef.current_frame), (true, false, 22.0));
1582 // Step 3 wraps 22 -> 20 with looped = true
1583 let e3 = ef.tick_synced(&comp, t0 + step * 3 + Duration::from_millis(1));
1584 assert_eq!((e3.frame_changed, e3.looped, ef.current_frame), (true, true, 20.0));
1585 }
1586
1587 #[test]
1588 fn audio_sync_target_time_computation() {
1589 let mut comp = test_comp();
1590 comp.fps = 24.0;
1591 comp.audio_offset = 12.0;
1592
1593 let t0 = Instant::now();
1594 let mut clock = PlaybackClock::new();
1595 clock.init_from_comp(&comp);
1596 clock.in_out_range = [Some(12), Some(36)];
1597 clock.set_frame(&comp, 0.0, t0);
1598 assert!((clock.audio_target_secs(&comp) - (-0.5)).abs() < 1e-9);
1599
1600 clock.set_frame(&comp, 12.0, t0);
1601 assert!((clock.audio_target_secs(&comp) - 0.0).abs() < 1e-9);
1602
1603 clock.set_frame(&comp, 36.0, t0);
1604 assert!((clock.audio_target_secs(&comp) - 1.0).abs() < 1e-9);
1605
1606 // RealtimeDrop expected_audio_secs tracks continuous sub-frame progress & wraparound
1607 clock.set_frame(&comp, 24.0, t0);
1608 clock.toggle_play_with_comp(&comp, t0);
1609 let half_sec = Duration::from_millis(500);
1610 let exp_rt = clock.expected_audio_secs(&comp, t0 + half_sec);
1611 assert!((exp_rt - 1.0).abs() < 1e-6, "expected 1.0s at frame 36, got {exp_rt}");
1612
1613 // EveryFrame expected_audio_secs caps sub-frame progress at 1/fps when a frame stalls
1614 clock.sync_mode = SyncMode::EveryFrame;
1615 clock.set_frame(&comp, 24.0, t0); // expected base = (24 - 12) / 24 = 0.5s
1616 let exp_stalled = clock.expected_audio_secs(&comp, t0 + Duration::from_millis(400));
1617 let max_expected = 0.5 + (1.0 / 24.0);
1618 assert!(
1619 (exp_stalled - max_expected).abs() < 1e-6,
1620 "EveryFrame stalled expected_audio_secs should cap at {max_expected}, got {exp_stalled}"
1621 );
1622 }
1381}1623}