| author | |
| committer | |
| log | 714f0307996641d4c23d9de8cfaedbc00282a00b |
| tree | db6badc0b7f8c4e25ef664aef33f1345de78e62d |
| parent | 76545ca44fc6ea68304c7bd900bf449842534b23 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
4 files changed, 1376 insertions(+), 13 deletions(-)
crates/app/src/main.rs+192-4| ... | ... | @@ -7,6 +7,9 @@ mod keyframes; |
| 7 | 7 | |
| 8 | 8 | use add_tool::{AddToolLauncher, ToolEntry}; |
| 9 | 9 | use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab}; |
| 10 | use engine::export::{ | |
| 11 | VideoCodec, VideoExportOptions, export_node_frame_png, export_node_video_ffmpeg, | |
| 12 | }; | |
| 10 | 13 | use engine::{ |
| 11 | 14 | AudioPlayer, AudioTrack, CacheMode, DEFAULT_RAM_CACHE_MB, Engine, ExportOptions, PrefetchJob, |
| 12 | 15 | RamFrameCache, RamPrefetcher, export_saver_png_sequence, |
| ... | ... | @@ -705,6 +708,124 @@ impl Studio { |
| 705 | 708 | } |
| 706 | 709 | } |
| 707 | 710 | |
| 711 | fn active_viewer_slot(&self) -> usize { | |
| 712 | if let Some(focused) = self.seen.focused { | |
| 713 | if self.layout.group_of(&"Viewer 2".to_owned(), String::clone) == Some(focused) { | |
| 714 | return 1; | |
| 715 | } | |
| 716 | } | |
| 717 | 0 | |
| 718 | } | |
| 719 | ||
| 720 | fn export_viewer_mp4(&mut self, slot: usize) -> Result<String, String> { | |
| 721 | if self.playback.playing { | |
| 722 | self.playback.toggle_play(Instant::now()); | |
| 723 | self.sync_audio(true, false); | |
| 724 | } | |
| 725 | let Some(target) = self.viewers[slot].viewed_node else { | |
| 726 | let msg = format!("Viewer {} has no node loaded", slot + 1); | |
| 727 | self.set_notice(msg.clone()); | |
| 728 | return Err(msg); | |
| 729 | }; | |
| 730 | let [in_f, out_f] = self.playback.effective_preview_range(&self.comp); | |
| 731 | let node_name = self.comp.node(target).name.clone(); | |
| 732 | let default_name = format!( | |
| 733 | "{}_{}_f{}-{}.mp4", | |
| 734 | sanitize_filename(&self.comp.name), | |
| 735 | sanitize_filename(&node_name), | |
| 736 | in_f, | |
| 737 | out_f | |
| 738 | ); | |
| 739 | let Some(mut path) = native_save_file_dialog("Export Preview MP4", &default_name) else { | |
| 740 | return Err("Export cancelled".to_owned()); | |
| 741 | }; | |
| 742 | if path.extension().is_none() { | |
| 743 | path.set_extension("mp4"); | |
| 744 | } | |
| 745 | let opts = VideoExportOptions { | |
| 746 | target, | |
| 747 | out_path: path.clone(), | |
| 748 | range: [in_f, out_f], | |
| 749 | codec: VideoCodec::H264Share, | |
| 750 | crf: 26, | |
| 751 | max_height: None, | |
| 752 | include_audio: true, | |
| 753 | hiq: self.engine.hiq, | |
| 754 | proxy_scale: self.engine.proxy_scale, | |
| 755 | }; | |
| 756 | let t0 = Instant::now(); | |
| 757 | match export_node_video_ffmpeg(&mut self.engine, &self.comp, &opts, |p| { | |
| 758 | if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { | |
| 759 | let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6); | |
| 760 | eprintln!( | |
| 761 | " [mp4 {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}", | |
| 762 | p.index + 1, | |
| 763 | p.total, | |
| 764 | p.saver_name, | |
| 765 | p.frame, | |
| 766 | p.eval_ms, | |
| 767 | fps, | |
| 768 | p.out_path.display() | |
| 769 | ); | |
| 770 | } | |
| 771 | }) { | |
| 772 | Ok(summary) => { | |
| 773 | let mb = summary.file_bytes as f64 / (1024.0 * 1024.0); | |
| 774 | let audio_tag = if summary.has_audio { " + audio" } else { "" }; | |
| 775 | let msg = format!( | |
| 776 | "Exported {} frames{audio_tag} ({mb:.2} MB)", | |
| 777 | summary.frames_written | |
| 778 | ); | |
| 779 | eprintln!("{msg} -> {}", summary.out_path.display()); | |
| 780 | self.set_notice(msg.clone()); | |
| 781 | Ok(msg) | |
| 782 | } | |
| 783 | Err(e) => { | |
| 784 | let err = format!("MP4 export failed: {e}"); | |
| 785 | eprintln!("{err}"); | |
| 786 | self.set_notice(err.clone()); | |
| 787 | Err(err) | |
| 788 | } | |
| 789 | } | |
| 790 | } | |
| 791 | ||
| 792 | fn save_viewer_frame_png(&mut self, slot: usize) -> Result<String, String> { | |
| 793 | let Some(target) = self.viewers[slot].viewed_node else { | |
| 794 | let msg = format!("Viewer {} has no node loaded", slot + 1); | |
| 795 | self.set_notice(msg.clone()); | |
| 796 | return Err(msg); | |
| 797 | }; | |
| 798 | let frame_f = self.playback.current_frame; | |
| 799 | let frame_i = frame_f.round() as i64; | |
| 800 | let node_name = self.comp.node(target).name.clone(); | |
| 801 | let default_name = format!( | |
| 802 | "{}_{}_f{}.png", | |
| 803 | sanitize_filename(&self.comp.name), | |
| 804 | sanitize_filename(&node_name), | |
| 805 | frame_i | |
| 806 | ); | |
| 807 | let Some(mut path) = native_save_file_dialog("Save Frame PNG", &default_name) else { | |
| 808 | return Err("Save Frame cancelled".to_owned()); | |
| 809 | }; | |
| 810 | if path.extension().is_none() { | |
| 811 | path.set_extension("png"); | |
| 812 | } | |
| 813 | match export_node_frame_png(&mut self.engine, &self.comp, target, frame_f, &path) { | |
| 814 | Ok(saved) => { | |
| 815 | let msg = format!("Saved frame f{frame_i} PNG"); | |
| 816 | eprintln!("{msg} -> {}", saved.display()); | |
| 817 | self.set_notice(msg.clone()); | |
| 818 | Ok(msg) | |
| 819 | } | |
| 820 | Err(e) => { | |
| 821 | let err = format!("Save PNG failed: {e}"); | |
| 822 | eprintln!("{err}"); | |
| 823 | self.set_notice(err.clone()); | |
| 824 | Err(err) | |
| 825 | } | |
| 826 | } | |
| 827 | } | |
| 828 | ||
| 708 | 829 | fn window_title(&self) -> String { |
| 709 | 830 | let dirty = if self.history.is_dirty(&self.comp) { "*" } else { "" }; |
| 710 | 831 | if let Some((msg, at)) = &self.status_notice { |
| ... | ... | @@ -1077,12 +1198,16 @@ impl Studio { |
| 1077 | 1198 | let sig = self.ui.signal(cid); |
| 1078 | 1199 | let ptr = self.ui.last_pointer(); |
| 1079 | 1200 | let mods = self.ui.modifiers(); |
| 1201 | let was_open = self.viewers[slot].is_context_menu_open(); | |
| 1080 | 1202 | let mut acts = Vec::new(); |
| 1081 | 1203 | for ev in sig.events { |
| 1082 | 1204 | for a in self.viewers[slot].input(&self.comp, &self.playback, ev, rect, ptr, mods) { |
| 1083 | 1205 | acts.push((slot, a)); |
| 1084 | 1206 | } |
| 1085 | 1207 | } |
| 1208 | if !was_open && self.viewers[slot].is_context_menu_open() { | |
| 1209 | self.viewers[1 - slot].close_context_menu(); | |
| 1210 | } | |
| 1086 | 1211 | self.route_viewer_actions(acts, now); |
| 1087 | 1212 | } |
| 1088 | 1213 | } |
| ... | ... | @@ -1325,6 +1450,41 @@ impl Studio { |
| 1325 | 1450 | self.comp.set_input_value(edit.node_id, edit.input, edit.value); |
| 1326 | 1451 | self.invalidate_node(Some(edit.node_id)); |
| 1327 | 1452 | } |
| 1453 | ViewerAction::ExportPreviewMp4(v_slot) => { | |
| 1454 | let _ = self.export_viewer_mp4(v_slot); | |
| 1455 | } | |
| 1456 | ViewerAction::SaveFramePng(v_slot) => { | |
| 1457 | let _ = self.save_viewer_frame_png(v_slot); | |
| 1458 | } | |
| 1459 | ViewerAction::SetInPoint => { | |
| 1460 | self.playback.set_in_point(&self.comp); | |
| 1461 | let [a, b] = self.playback.effective_preview_range(&self.comp); | |
| 1462 | self.set_notice(format!( | |
| 1463 | "In: f{} (preview f{a}..f{b})", | |
| 1464 | self.playback.current_frame.round() as i64 | |
| 1465 | )); | |
| 1466 | for v in &mut self.viewers { | |
| 1467 | v.prepare_hud(&self.comp, &self.engine, &self.playback); | |
| 1468 | } | |
| 1469 | } | |
| 1470 | ViewerAction::SetOutPoint => { | |
| 1471 | self.playback.set_out_point(&self.comp); | |
| 1472 | let [a, b] = self.playback.effective_preview_range(&self.comp); | |
| 1473 | self.set_notice(format!( | |
| 1474 | "Out: f{} (preview f{a}..f{b})", | |
| 1475 | self.playback.current_frame.round() as i64 | |
| 1476 | )); | |
| 1477 | for v in &mut self.viewers { | |
| 1478 | v.prepare_hud(&self.comp, &self.engine, &self.playback); | |
| 1479 | } | |
| 1480 | } | |
| 1481 | ViewerAction::ClearInOut => { | |
| 1482 | self.playback.clear_in_out(); | |
| 1483 | self.set_notice("Reset In/Out range"); | |
| 1484 | for v in &mut self.viewers { | |
| 1485 | v.prepare_hud(&self.comp, &self.engine, &self.playback); | |
| 1486 | } | |
| 1487 | } | |
| 1328 | 1488 | } |
| 1329 | 1489 | } |
| 1330 | 1490 | } |
| ... | ... | @@ -1568,7 +1728,7 @@ impl WindowHost { |
| 1568 | 1728 | |
| 1569 | 1729 | fn input(&mut self, event: ui::Event) { |
| 1570 | 1730 | let typing = self.studio.ui.typing(); |
| 1571 | // Global file & history shortcuts: Cmd+S, Cmd+Shift+S, Cmd+O, Cmd+Z, Cmd+Shift+Z / Cmd+Y, Cmd+Shift+R | |
| 1731 | // Global file & history shortcuts: Cmd+S, Cmd+Shift+S, Cmd+O, Cmd+Z, Cmd+Shift+Z / Cmd+Y, Cmd+Shift+R, Cmd+Shift+E | |
| 1572 | 1732 | let key_cmd = match &event { |
| 1573 | 1733 | ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => { |
| 1574 | 1734 | let cmd = modifiers.super_key() || modifiers.control_key(); |
| ... | ... | @@ -1587,6 +1747,8 @@ impl WindowHost { |
| 1587 | 1747 | Some("redo") |
| 1588 | 1748 | } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyR) { |
| 1589 | 1749 | Some("export") |
| 1750 | } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyE) { | |
| 1751 | Some("export_preview_mp4") | |
| 1590 | 1752 | } else { |
| 1591 | 1753 | None |
| 1592 | 1754 | } |
| ... | ... | @@ -1608,6 +1770,8 @@ impl WindowHost { |
| 1608 | 1770 | Some("redo") |
| 1609 | 1771 | } else if cmd && shift && c.eq_ignore_ascii_case("r") { |
| 1610 | 1772 | Some("export") |
| 1773 | } else if cmd && shift && c.eq_ignore_ascii_case("e") { | |
| 1774 | Some("export_preview_mp4") | |
| 1611 | 1775 | } else { |
| 1612 | 1776 | None |
| 1613 | 1777 | } |
| ... | ... | @@ -1622,6 +1786,10 @@ impl WindowHost { |
| 1622 | 1786 | "undo" => self.studio.undo(), |
| 1623 | 1787 | "redo" => self.studio.redo(), |
| 1624 | 1788 | "export" => { let _ = self.studio.export_saver_pngs(); } |
| 1789 | "export_preview_mp4" => { | |
| 1790 | let slot = self.studio.active_viewer_slot(); | |
| 1791 | let _ = self.studio.export_viewer_mp4(slot); | |
| 1792 | } | |
| 1625 | 1793 | _ => {} |
| 1626 | 1794 | } |
| 1627 | 1795 | self.window.set_title(&self.studio.window_title()); |
| ... | ... | @@ -1843,10 +2011,26 @@ fn native_open_comp_dialog() -> Option<PathBuf> { |
| 1843 | 2011 | if s.is_empty() { None } else { Some(PathBuf::from(s)) } |
| 1844 | 2012 | } |
| 1845 | 2013 | |
| 1846 | fn native_save_comp_dialog(default_name: &str) -> Option<PathBuf> { | |
| 1847 | let safe = default_name.replace('"', ""); | |
| 2014 | fn sanitize_filename(name: &str) -> String { | |
| 2015 | let cleaned: String = name | |
| 2016 | .chars() | |
| 2017 | .map(|c| match c { | |
| 2018 | '/' | '\\' | ':' | '"' | '\n' | '\r' => '_', | |
| 2019 | other => other, | |
| 2020 | }) | |
| 2021 | .collect(); | |
| 2022 | if cleaned.is_empty() { | |
| 2023 | "untitled".to_owned() | |
| 2024 | } else { | |
| 2025 | cleaned | |
| 2026 | } | |
| 2027 | } | |
| 2028 | ||
| 2029 | fn native_save_file_dialog(prompt: &str, default_name: &str) -> Option<PathBuf> { | |
| 2030 | let safe_prompt = prompt.replace('"', ""); | |
| 2031 | let safe_name = default_name.replace('"', ""); | |
| 1848 | 2032 | let script = format!( |
| 1849 | r#"POSIX path of (choose file name with prompt "Save Fusion Composition As" default name "{safe}")"# | |
| 2033 | r#"POSIX path of (choose file name with prompt "{safe_prompt}" default name "{safe_name}")"# | |
| 1850 | 2034 | ); |
| 1851 | 2035 | let out = ProcessCommand::new("osascript").args(["-e", &script]).output().ok()?; |
| 1852 | 2036 | if !out.status.success() { |
| ... | ... | @@ -1855,3 +2039,7 @@ fn native_save_comp_dialog(default_name: &str) -> Option<PathBuf> { |
| 1855 | 2039 | let s = String::from_utf8_lossy(&out.stdout).trim().to_owned(); |
| 1856 | 2040 | if s.is_empty() { None } else { Some(PathBuf::from(s)) } |
| 1857 | 2041 | } |
| 2042 | ||
| 2043 | fn native_save_comp_dialog(default_name: &str) -> Option<PathBuf> { | |
| 2044 | native_save_file_dialog("Save Fusion Composition As", default_name) | |
| 2045 | } |
crates/engine/src/bin/render_check.rs+151-1| ... | ... | @@ -1,5 +1,6 @@ |
| 1 | 1 | //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. |
| 2 | 2 | |
| 3 | use engine::export::{VideoCodec, VideoExportOptions, export_node_video_ffmpeg}; | |
| 3 | 4 | use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; |
| 4 | 5 | use model::Comp; |
| 5 | 6 | use std::collections::HashMap; |
| ... | ... | @@ -252,6 +253,80 @@ fn run_saver_export( |
| 252 | 253 | Ok(()) |
| 253 | 254 | } |
| 254 | 255 | |
| 256 | #[allow(clippy::too_many_arguments)] | |
| 257 | fn run_video_export( | |
| 258 | comp_path: &Path, | |
| 259 | out_path: PathBuf, | |
| 260 | codec: VideoCodec, | |
| 261 | node_name: Option<&str>, | |
| 262 | range_str: Option<&str>, | |
| 263 | crf: u8, | |
| 264 | max_height: Option<u32>, | |
| 265 | include_audio: bool, | |
| 266 | proxy_scale: u32, | |
| 267 | hiq: bool, | |
| 268 | ) -> Result<(), Box<dyn std::error::Error>> { | |
| 269 | let comp = Comp::from_fusion_file(comp_path)?; | |
| 270 | let target = match node_name { | |
| 271 | Some(n) => comp.find_node(n).ok_or_else(|| format!("no such node {n}"))?, | |
| 272 | None => comp.default_output_node().ok_or("comp has no nodes")?, | |
| 273 | }; | |
| 274 | let range = match range_str { | |
| 275 | Some(r) if !r.is_empty() => { | |
| 276 | if let Some((a, b)) = r.split_once("..") { | |
| 277 | [a.parse::<i64>()?, b.parse::<i64>()?] | |
| 278 | } else { | |
| 279 | let single = r.parse::<i64>()?; | |
| 280 | [single, single] | |
| 281 | } | |
| 282 | } | |
| 283 | _ => comp.render_range, | |
| 284 | }; | |
| 285 | let mut engine = Engine::new_headless()?; | |
| 286 | let opts = VideoExportOptions { | |
| 287 | target, | |
| 288 | out_path: out_path.clone(), | |
| 289 | range, | |
| 290 | codec, | |
| 291 | crf, | |
| 292 | max_height, | |
| 293 | include_audio, | |
| 294 | hiq, | |
| 295 | proxy_scale, | |
| 296 | }; | |
| 297 | let t_start = Instant::now(); | |
| 298 | let summary = export_node_video_ffmpeg(&mut engine, &comp, &opts, |p| { | |
| 299 | if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { | |
| 300 | let elapsed = t_start.elapsed().as_secs_f64().max(1e-6); | |
| 301 | let fps = (p.index + 1) as f64 / elapsed; | |
| 302 | eprintln!( | |
| 303 | " [{:>4}/{}] {} f{:04} | eval={:.1}ms | avg={fps:.1} fps -> {}", | |
| 304 | p.index + 1, | |
| 305 | p.total, | |
| 306 | p.saver_name, | |
| 307 | p.frame, | |
| 308 | p.eval_ms, | |
| 309 | p.out_path.display() | |
| 310 | ); | |
| 311 | } | |
| 312 | }) | |
| 313 | .map_err(|e| format!("video export failed: {e}"))?; | |
| 314 | let secs = (summary.total_ms / 1000.0).max(1e-6); | |
| 315 | let mb = summary.file_bytes as f64 / (1024.0 * 1024.0); | |
| 316 | eprintln!( | |
| 317 | "Exported {} frames ({}x{}, {}, {:.2} MB) in {:.2}s ({:.1} fps) -> {}", | |
| 318 | summary.frames_written, | |
| 319 | summary.width, | |
| 320 | summary.height, | |
| 321 | if summary.has_audio { "with audio" } else { "no audio" }, | |
| 322 | mb, | |
| 323 | secs, | |
| 324 | summary.frames_written as f64 / secs, | |
| 325 | summary.out_path.display() | |
| 326 | ); | |
| 327 | Ok(()) | |
| 328 | } | |
| 329 | ||
| 255 | 330 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 256 | 331 | let args: Vec<String> = std::env::args().collect(); |
| 257 | 332 | if args.len() >= 3 && args[1] == "--suite" { |
| ... | ... | @@ -260,12 +335,87 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 260 | 335 | } |
| 261 | 336 | if args.len() < 3 { |
| 262 | 337 | eprintln!( |
| 263 | "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]" | |
| 338 | "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-mp4 <out.mp4> [--node <name>] [--range <start>..<end>] [--crf <u8>] [--max-height <u32>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-prores <out.mov> [--node <name>] [--range <start>..<end>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]" | |
| 264 | 339 | ); |
| 265 | 340 | std::process::exit(2); |
| 266 | 341 | } |
| 267 | 342 | |
| 268 | 343 | let comp_path = PathBuf::from(&args[1]); |
| 344 | if args[2..].iter().any(|a| a == "--export-mp4" || a == "--export-prores") { | |
| 345 | let mut out_path: Option<PathBuf> = None; | |
| 346 | let mut codec = VideoCodec::H264Share; | |
| 347 | let mut node_name: Option<String> = None; | |
| 348 | let mut range_str: Option<String> = None; | |
| 349 | let mut crf: u8 = 26; | |
| 350 | let mut max_height: Option<u32> = None; | |
| 351 | let mut include_audio = true; | |
| 352 | let mut proxy_scale = 1u32; | |
| 353 | let mut hiq = true; | |
| 354 | let mut i = 2; | |
| 355 | while i < args.len() { | |
| 356 | match args[i].as_str() { | |
| 357 | "--export-mp4" if i + 1 < args.len() => { | |
| 358 | out_path = Some(PathBuf::from(&args[i + 1])); | |
| 359 | codec = VideoCodec::H264Share; | |
| 360 | i += 2; | |
| 361 | } | |
| 362 | "--export-prores" if i + 1 < args.len() => { | |
| 363 | out_path = Some(PathBuf::from(&args[i + 1])); | |
| 364 | codec = VideoCodec::ProRes422; | |
| 365 | i += 2; | |
| 366 | } | |
| 367 | "--prores-4444" => { | |
| 368 | codec = VideoCodec::ProRes4444; | |
| 369 | i += 1; | |
| 370 | } | |
| 371 | "--node" if i + 1 < args.len() => { | |
| 372 | node_name = Some(args[i + 1].clone()); | |
| 373 | i += 2; | |
| 374 | } | |
| 375 | "--range" if i + 1 < args.len() => { | |
| 376 | range_str = Some(args[i + 1].clone()); | |
| 377 | i += 2; | |
| 378 | } | |
| 379 | "--crf" if i + 1 < args.len() => { | |
| 380 | crf = args[i + 1].parse()?; | |
| 381 | i += 2; | |
| 382 | } | |
| 383 | "--max-height" if i + 1 < args.len() => { | |
| 384 | max_height = Some(args[i + 1].parse()?); | |
| 385 | i += 2; | |
| 386 | } | |
| 387 | "--no-audio" => { | |
| 388 | include_audio = false; | |
| 389 | i += 1; | |
| 390 | } | |
| 391 | "--proxy" if i + 1 < args.len() => { | |
| 392 | proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); | |
| 393 | i += 2; | |
| 394 | } | |
| 395 | "--fast" => { | |
| 396 | hiq = false; | |
| 397 | i += 1; | |
| 398 | } | |
| 399 | other => { | |
| 400 | eprintln!("unexpected argument '{other}'"); | |
| 401 | std::process::exit(2); | |
| 402 | } | |
| 403 | } | |
| 404 | } | |
| 405 | let out_path = out_path.ok_or("--export-mp4 or --export-prores requires an output path")?; | |
| 406 | return run_video_export( | |
| 407 | &comp_path, | |
| 408 | out_path, | |
| 409 | codec, | |
| 410 | node_name.as_deref(), | |
| 411 | range_str.as_deref(), | |
| 412 | crf, | |
| 413 | max_height, | |
| 414 | include_audio, | |
| 415 | proxy_scale, | |
| 416 | hiq, | |
| 417 | ); | |
| 418 | } | |
| 269 | 419 | if args[2] == "--roundtrip" { |
| 270 | 420 | if args.len() < 4 { |
| 271 | 421 | return Err("--roundtrip requires <out.comp>".into()); |
crates/engine/src/export.rs+549-1| ... | ... | @@ -6,8 +6,9 @@ |
| 6 | 6 | use crate::eval::Engine; |
| 7 | 7 | use model::{Comp, NodeId, SaverSpec}; |
| 8 | 8 | use std::fs::File; |
| 9 | use std::io::BufWriter; | |
| 9 | use std::io::{BufWriter, Read, Write}; | |
| 10 | 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::{Command, Stdio}; | |
| 11 | 12 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 12 | 13 | use std::sync::{Arc, Mutex, mpsc}; |
| 13 | 14 | use std::time::Instant; |
| ... | ... | @@ -282,6 +283,363 @@ pub fn export_saver_png_sequence( |
| 282 | 283 | }) |
| 283 | 284 | } |
| 284 | 285 | |
| 286 | /// Output video codec profile for direct viewer / node ffmpeg export. | |
| 287 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 288 | pub enum VideoCodec { | |
| 289 | /// H.264 (`libx264`, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets. | |
| 290 | H264Share, | |
| 291 | /// Apple ProRes 422 (`prores_ks -profile:v 2 -pix_fmt yuv422p10le`). | |
| 292 | ProRes422, | |
| 293 | /// Apple ProRes 4444 with alpha (`prores_ks -profile:v 4 -pix_fmt yuva444p10le`). | |
| 294 | ProRes4444, | |
| 295 | } | |
| 296 | ||
| 297 | #[derive(Clone, Debug)] | |
| 298 | pub struct VideoExportOptions { | |
| 299 | pub target: NodeId, | |
| 300 | pub out_path: PathBuf, | |
| 301 | pub range: [i64; 2], | |
| 302 | pub codec: VideoCodec, | |
| 303 | pub crf: u8, | |
| 304 | pub max_height: Option<u32>, | |
| 305 | pub include_audio: bool, | |
| 306 | pub hiq: bool, | |
| 307 | pub proxy_scale: u32, | |
| 308 | } | |
| 309 | ||
| 310 | impl Default for VideoExportOptions { | |
| 311 | fn default() -> Self { | |
| 312 | Self { | |
| 313 | target: NodeId(0), | |
| 314 | out_path: PathBuf::new(), | |
| 315 | range: [0, 0], | |
| 316 | codec: VideoCodec::H264Share, | |
| 317 | crf: 26, | |
| 318 | max_height: None, | |
| 319 | include_audio: true, | |
| 320 | hiq: true, | |
| 321 | proxy_scale: 1, | |
| 322 | } | |
| 323 | } | |
| 324 | } | |
| 325 | ||
| 326 | #[derive(Clone, Debug)] | |
| 327 | pub struct VideoExportSummary { | |
| 328 | pub out_path: PathBuf, | |
| 329 | pub frames_written: usize, | |
| 330 | pub width: u32, | |
| 331 | pub height: u32, | |
| 332 | pub has_audio: bool, | |
| 333 | pub total_ms: f64, | |
| 334 | pub file_bytes: u64, | |
| 335 | } | |
| 336 | ||
| 337 | /// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`. | |
| 338 | pub fn export_node_frame_png( | |
| 339 | engine: &mut Engine, | |
| 340 | comp: &Comp, | |
| 341 | target: NodeId, | |
| 342 | frame: f64, | |
| 343 | out_path: &Path, | |
| 344 | ) -> Result<PathBuf, String> { | |
| 345 | if target.0 >= comp.nodes.len() { | |
| 346 | return Err(format!("invalid target node id {}", target.0)); | |
| 347 | } | |
| 348 | let (tex, _) = engine.evaluate(comp, target, frame); | |
| 349 | let pixels = engine | |
| 350 | .readback_rgba(&tex) | |
| 351 | .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?; | |
| 352 | write_png_fast(out_path, tex.size, &pixels)?; | |
| 353 | Ok(out_path.to_path_buf()) | |
| 354 | } | |
| 355 | ||
| 356 | /// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames | |
| 357 | /// directly into `ffmpeg`, and muxes synced comp audio when `opts.include_audio` is enabled. | |
| 358 | pub fn export_node_video_ffmpeg( | |
| 359 | engine: &mut Engine, | |
| 360 | comp: &Comp, | |
| 361 | opts: &VideoExportOptions, | |
| 362 | mut on_progress: impl FnMut(ExportProgress), | |
| 363 | ) -> Result<VideoExportSummary, String> { | |
| 364 | let [start, end] = opts.range; | |
| 365 | if end < start { | |
| 366 | return Err(format!("invalid export frame range {start}..={end}")); | |
| 367 | } | |
| 368 | if opts.target.0 >= comp.nodes.len() { | |
| 369 | return Err(format!("invalid target node id {}", opts.target.0)); | |
| 370 | } | |
| 371 | if opts.out_path.as_os_str().is_empty() { | |
| 372 | return Err("video export output path is empty".to_owned()); | |
| 373 | } | |
| 374 | if let Some(parent) = opts.out_path.parent() { | |
| 375 | if !parent.as_os_str().is_empty() { | |
| 376 | std::fs::create_dir_all(parent) | |
| 377 | .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; | |
| 378 | } | |
| 379 | } | |
| 380 | ||
| 381 | let prev_hiq = engine.hiq; | |
| 382 | let prev_proxy = engine.proxy_scale; | |
| 383 | engine.hiq = opts.hiq; | |
| 384 | engine.proxy_scale = opts.proxy_scale.max(1); | |
| 385 | ||
| 386 | let res = (|| -> Result<VideoExportSummary, String> { | |
| 387 | let t0 = Instant::now(); | |
| 388 | let total = (end - start + 1) as usize; | |
| 389 | let fps = comp.fps.max(1.0); | |
| 390 | let node_name = comp.node(opts.target).name.clone(); | |
| 391 | ||
| 392 | // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. | |
| 393 | let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); | |
| 394 | let [width, height] = first_tex.size; | |
| 395 | if width == 0 || height == 0 { | |
| 396 | return Err(format!("target '{}' produced empty frame {}x{}", node_name, width, height)); | |
| 397 | } | |
| 398 | let first_pixels = engine | |
| 399 | .readback_rgba(&first_tex) | |
| 400 | .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?; | |
| 401 | ||
| 402 | let duration_secs = total as f64 / fps; | |
| 403 | let audio_start_secs = (start as f64 - comp.audio_offset) / fps; | |
| 404 | let audio_path = if opts.include_audio { | |
| 405 | comp.audio_filename | |
| 406 | .as_deref() | |
| 407 | .map(PathBuf::from) | |
| 408 | .filter(|p| !p.as_os_str().is_empty() && p.exists() && -audio_start_secs < duration_secs) | |
| 409 | } else { | |
| 410 | None | |
| 411 | }; | |
| 412 | let has_audio = audio_path.is_some(); | |
| 413 | ||
| 414 | let mut cmd = Command::new("ffmpeg"); | |
| 415 | cmd.args(["-y", "-hide_banner", "-loglevel", "error"]); | |
| 416 | cmd.args([ | |
| 417 | "-f", | |
| 418 | "rawvideo", | |
| 419 | "-pix_fmt", | |
| 420 | "rgba", | |
| 421 | "-s", | |
| 422 | &format!("{width}x{height}"), | |
| 423 | "-r", | |
| 424 | &format!("{fps:.6}"), | |
| 425 | "-i", | |
| 426 | "pipe:0", | |
| 427 | ]); | |
| 428 | ||
| 429 | if let Some(ap) = &audio_path { | |
| 430 | if audio_start_secs >= 0.0 { | |
| 431 | cmd.args([ | |
| 432 | "-ss", | |
| 433 | &format!("{audio_start_secs:.6}"), | |
| 434 | "-t", | |
| 435 | &format!("{duration_secs:.6}"), | |
| 436 | "-i", | |
| 437 | ]); | |
| 438 | cmd.arg(ap); | |
| 439 | } else { | |
| 440 | cmd.args([ | |
| 441 | "-itsoffset", | |
| 442 | &format!("{:.6}", -audio_start_secs), | |
| 443 | "-i", | |
| 444 | ]); | |
| 445 | cmd.arg(ap); | |
| 446 | } | |
| 447 | } | |
| 448 | ||
| 449 | let (out_width, out_height) = match opts.codec { | |
| 450 | VideoCodec::H264Share => { | |
| 451 | let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { | |
| 452 | let oh = (height.min(max_h) & !1).max(2); | |
| 453 | let ow = if height > max_h { | |
| 454 | let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; | |
| 455 | (scaled & !1).max(2) | |
| 456 | } else { | |
| 457 | (width & !1).max(2) | |
| 458 | }; | |
| 459 | (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) | |
| 460 | } else { | |
| 461 | let ow = (width & !1).max(2); | |
| 462 | let oh = (height & !1).max(2); | |
| 463 | ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) | |
| 464 | }; | |
| 465 | cmd.args([ | |
| 466 | "-vf", | |
| 467 | &vf, | |
| 468 | "-c:v", | |
| 469 | "libx264", | |
| 470 | "-preset", | |
| 471 | "medium", | |
| 472 | "-crf", | |
| 473 | &opts.crf.to_string(), | |
| 474 | "-pix_fmt", | |
| 475 | "yuv420p", | |
| 476 | "-movflags", | |
| 477 | "+faststart", | |
| 478 | ]); | |
| 479 | (ow, oh) | |
| 480 | } | |
| 481 | VideoCodec::ProRes422 => { | |
| 482 | cmd.args([ | |
| 483 | "-c:v", | |
| 484 | "prores_ks", | |
| 485 | "-profile:v", | |
| 486 | "2", | |
| 487 | "-pix_fmt", | |
| 488 | "yuv422p10le", | |
| 489 | ]); | |
| 490 | (width, height) | |
| 491 | } | |
| 492 | VideoCodec::ProRes4444 => { | |
| 493 | cmd.args([ | |
| 494 | "-c:v", | |
| 495 | "prores_ks", | |
| 496 | "-profile:v", | |
| 497 | "4", | |
| 498 | "-pix_fmt", | |
| 499 | "yuva444p10le", | |
| 500 | ]); | |
| 501 | (width, height) | |
| 502 | } | |
| 503 | }; | |
| 504 | ||
| 505 | if has_audio { | |
| 506 | cmd.args(["-map", "0:v:0", "-map", "1:a:0"]); | |
| 507 | match opts.codec { | |
| 508 | VideoCodec::H264Share => { | |
| 509 | cmd.args(["-c:a", "aac", "-b:a", "128k"]); | |
| 510 | } | |
| 511 | VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { | |
| 512 | cmd.args(["-c:a", "pcm_s16le"]); | |
| 513 | } | |
| 514 | } | |
| 515 | if audio_start_secs < 0.0 { | |
| 516 | cmd.args(["-t", &format!("{duration_secs:.6}")]); | |
| 517 | } | |
| 518 | cmd.arg("-shortest"); | |
| 519 | } else { | |
| 520 | cmd.arg("-an"); | |
| 521 | } | |
| 522 | ||
| 523 | cmd.arg(&opts.out_path); | |
| 524 | cmd.stdin(Stdio::piped()) | |
| 525 | .stdout(Stdio::null()) | |
| 526 | .stderr(Stdio::piped()); | |
| 527 | ||
| 528 | let mut child = cmd | |
| 529 | .spawn() | |
| 530 | .map_err(|e| format!("failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"))?; | |
| 531 | ||
| 532 | let mut stderr_pipe = child.stderr.take(); | |
| 533 | let stderr_thread = std::thread::spawn(move || { | |
| 534 | let mut buf = String::new(); | |
| 535 | if let Some(ref mut pipe) = stderr_pipe { | |
| 536 | let _ = pipe.read_to_string(&mut buf); | |
| 537 | } | |
| 538 | buf | |
| 539 | }); | |
| 540 | ||
| 541 | let mut pipe_err: Option<String> = None; | |
| 542 | { | |
| 543 | let mut stdin = child | |
| 544 | .stdin | |
| 545 | .take() | |
| 546 | .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?; | |
| 547 | ||
| 548 | if let Err(e) = stdin.write_all(&first_pixels) { | |
| 549 | pipe_err = Some(format!("failed writing frame {start} to ffmpeg: {e}")); | |
| 550 | } else { | |
| 551 | on_progress(ExportProgress { | |
| 552 | frame: start, | |
| 553 | index: 0, | |
| 554 | total, | |
| 555 | eval_ms: first_stats.eval_ms, | |
| 556 | out_path: opts.out_path.clone(), | |
| 557 | saver_name: node_name.clone(), | |
| 558 | }); | |
| 559 | ||
| 560 | for (idx, frame) in ((start + 1)..=end).enumerate() { | |
| 561 | let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); | |
| 562 | let pixels = match engine.readback_rgba(&tex) { | |
| 563 | Ok(px) => px, | |
| 564 | Err(e) => { | |
| 565 | pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); | |
| 566 | break; | |
| 567 | } | |
| 568 | }; | |
| 569 | let frame_bytes = if tex.size != [width, height] { | |
| 570 | let Some(img) = image::RgbaImage::from_raw(tex.size[0], tex.size[1], pixels) | |
| 571 | else { | |
| 572 | pipe_err = Some(format!("invalid RGBA buffer size at frame {frame}")); | |
| 573 | break; | |
| 574 | }; | |
| 575 | image::imageops::resize( | |
| 576 | &img, | |
| 577 | width, | |
| 578 | height, | |
| 579 | image::imageops::FilterType::Triangle, | |
| 580 | ) | |
| 581 | .into_raw() | |
| 582 | } else { | |
| 583 | pixels | |
| 584 | }; | |
| 585 | ||
| 586 | if let Err(e) = stdin.write_all(&frame_bytes) { | |
| 587 | pipe_err = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); | |
| 588 | break; | |
| 589 | } | |
| 590 | on_progress(ExportProgress { | |
| 591 | frame, | |
| 592 | index: idx + 1, | |
| 593 | total, | |
| 594 | eval_ms: stats.eval_ms, | |
| 595 | out_path: opts.out_path.clone(), | |
| 596 | saver_name: node_name.clone(), | |
| 597 | }); | |
| 598 | } | |
| 599 | } | |
| 600 | let _ = stdin.flush(); | |
| 601 | } | |
| 602 | ||
| 603 | let status = child | |
| 604 | .wait() | |
| 605 | .map_err(|e| format!("failed waiting on ffmpeg: {e}"))?; | |
| 606 | let stderr_text = stderr_thread.join().unwrap_or_default(); | |
| 607 | let stderr_trim = stderr_text.trim(); | |
| 608 | ||
| 609 | if let Some(err) = pipe_err { | |
| 610 | if !stderr_trim.is_empty() { | |
| 611 | return Err(format!("{err} (ffmpeg: {stderr_trim})")); | |
| 612 | } | |
| 613 | return Err(err); | |
| 614 | } | |
| 615 | if !status.success() { | |
| 616 | return Err(if stderr_trim.is_empty() { | |
| 617 | format!("ffmpeg exited with {status}") | |
| 618 | } else { | |
| 619 | format!("ffmpeg exited with {status}: {stderr_trim}") | |
| 620 | }); | |
| 621 | } | |
| 622 | ||
| 623 | let file_bytes = std::fs::metadata(&opts.out_path) | |
| 624 | .map(|m| m.len()) | |
| 625 | .unwrap_or(0); | |
| 626 | ||
| 627 | Ok(VideoExportSummary { | |
| 628 | out_path: opts.out_path.clone(), | |
| 629 | frames_written: total, | |
| 630 | width: out_width, | |
| 631 | height: out_height, | |
| 632 | has_audio, | |
| 633 | total_ms: t0.elapsed().as_secs_f64() * 1000.0, | |
| 634 | file_bytes, | |
| 635 | }) | |
| 636 | })(); | |
| 637 | ||
| 638 | engine.hiq = prev_hiq; | |
| 639 | engine.proxy_scale = prev_proxy; | |
| 640 | res | |
| 641 | } | |
| 642 | ||
| 285 | 643 | #[cfg(test)] |
| 286 | 644 | mod tests { |
| 287 | 645 | use super::*; |
| ... | ... | @@ -379,4 +737,194 @@ mod tests { |
| 379 | 737 | |
| 380 | 738 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 381 | 739 | } |
| 740 | ||
| 741 | fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) { | |
| 742 | let num_channels: u16 = 2; | |
| 743 | let bits_per_sample: u16 = 16; | |
| 744 | let num_samples = (sample_rate as f64 * duration_secs) as u32; | |
| 745 | let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8; | |
| 746 | let block_align = num_channels * bits_per_sample / 8; | |
| 747 | let data_bytes = num_samples * u32::from(block_align); | |
| 748 | let riff_chunk_size = 36 + data_bytes; | |
| 749 | ||
| 750 | let mut buf = Vec::with_capacity((44 + data_bytes) as usize); | |
| 751 | buf.extend_from_slice(b"RIFF"); | |
| 752 | buf.extend_from_slice(&riff_chunk_size.to_le_bytes()); | |
| 753 | buf.extend_from_slice(b"WAVE"); | |
| 754 | buf.extend_from_slice(b"fmt "); | |
| 755 | buf.extend_from_slice(&16u32.to_le_bytes()); | |
| 756 | buf.extend_from_slice(&1u16.to_le_bytes()); // PCM | |
| 757 | buf.extend_from_slice(&num_channels.to_le_bytes()); | |
| 758 | buf.extend_from_slice(&sample_rate.to_le_bytes()); | |
| 759 | buf.extend_from_slice(&byte_rate.to_le_bytes()); | |
| 760 | buf.extend_from_slice(&block_align.to_le_bytes()); | |
| 761 | buf.extend_from_slice(&bits_per_sample.to_le_bytes()); | |
| 762 | buf.extend_from_slice(b"data"); | |
| 763 | buf.extend_from_slice(&data_bytes.to_le_bytes()); | |
| 764 | for i in 0..num_samples { | |
| 765 | let t = i as f64 / sample_rate as f64; | |
| 766 | let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16; | |
| 767 | buf.extend_from_slice(&sample.to_le_bytes()); | |
| 768 | buf.extend_from_slice(&sample.to_le_bytes()); | |
| 769 | } | |
| 770 | std::fs::write(path, buf).expect("write synthetic wav"); | |
| 771 | } | |
| 772 | ||
| 773 | #[test] | |
| 774 | fn exports_snippet_mp4_with_synced_audio() { | |
| 775 | let tmp_dir = std::env::temp_dir().join(format!( | |
| 776 | "fission-video-export-test-{}", | |
| 777 | std::process::id() | |
| 778 | )); | |
| 779 | let _ = std::fs::remove_dir_all(&tmp_dir); | |
| 780 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); | |
| 781 | ||
| 782 | let wav_path = tmp_dir.join("tone.wav"); | |
| 783 | write_test_wav(&wav_path, 44100, 2.0); | |
| 784 | let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\"); | |
| 785 | ||
| 786 | let comp_src = format!( | |
| 787 | r#"Composition {{ | |
| 788 | 	CurrentTime = 10, | |
| 789 | 	RenderRange = {{ 10, 21 }}, | |
| 790 | 	GlobalRange = {{ 0, 100 }}, | |
| 791 | 	AudioFilename = "{wav_escaped}", | |
| 792 | 	AudioOffset = 10, | |
| 793 | 	Tools = ordered() {{ | |
| 794 | 		BG = Background {{ | |
| 795 | 			Inputs = {{ | |
| 796 | 				Width = Input {{ Value = 128, }}, | |
| 797 | 				Height = Input {{ Value = 72, }}, | |
| 798 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, | |
| 799 | 				TopLeftGreen = Input {{ Value = 0.25, }}, | |
| 800 | 				TopLeftBlue = Input {{ Value = 0.75, }}, | |
| 801 | 				TopLeftAlpha = Input {{ Value = 1, }}, | |
| 802 | 			}}, | |
| 803 | 		}}, | |
| 804 | 		BGRed = BezierSpline {{ | |
| 805 | 			KeyFrames = {{ | |
| 806 | 				[10] = {{ 0.0, Flags = {{ Linear = true }} }}, | |
| 807 | 				[21] = {{ 1.0, Flags = {{ Linear = true }} }}, | |
| 808 | 			}}, | |
| 809 | 		}}, | |
| 810 | 	}}, | |
| 811 | 	Prefs = {{ | |
| 812 | 		Comp = {{ | |
| 813 | 			FrameFormat = {{ | |
| 814 | 				Width = 128, | |
| 815 | 				Height = 72, | |
| 816 | 				Rate = 30, | |
| 817 | 				DepthFull = 1, | |
| 818 | 			}}, | |
| 819 | 		}}, | |
| 820 | 	}}, | |
| 821 | }}"# | |
| 822 | ); | |
| 823 | ||
| 824 | let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp"); | |
| 825 | let target = comp.find_node("BG").expect("find BG node"); | |
| 826 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); | |
| 827 | ||
| 828 | let mp4_path = tmp_dir.join("snippet.mp4"); | |
| 829 | let mut seen_frames = Vec::new(); | |
| 830 | let summary = export_node_video_ffmpeg( | |
| 831 | &mut engine, | |
| 832 | &comp, | |
| 833 | &VideoExportOptions { | |
| 834 | target, | |
| 835 | out_path: mp4_path.clone(), | |
| 836 | range: [10, 21], | |
| 837 | codec: VideoCodec::H264Share, | |
| 838 | crf: 26, | |
| 839 | max_height: None, | |
| 840 | include_audio: true, | |
| 841 | hiq: true, | |
| 842 | proxy_scale: 1, | |
| 843 | }, | |
| 844 | |p| seen_frames.push(p.frame), | |
| 845 | ) | |
| 846 | .expect("export snippet mp4"); | |
| 847 | ||
| 848 | assert_eq!(summary.frames_written, 12); | |
| 849 | assert_eq!(summary.width, 128); | |
| 850 | assert_eq!(summary.height, 72); | |
| 851 | assert!(summary.has_audio); | |
| 852 | assert!(summary.file_bytes > 0); | |
| 853 | assert_eq!(seen_frames.len(), 12); | |
| 854 | assert!(mp4_path.exists()); | |
| 855 | ||
| 856 | // Verify streams and exact video frame count via ffprobe | |
| 857 | let probe = Command::new("ffprobe") | |
| 858 | .args([ | |
| 859 | "-v", | |
| 860 | "error", | |
| 861 | "-count_frames", | |
| 862 | "-show_entries", | |
| 863 | "stream=codec_type,codec_name,nb_read_frames", | |
| 864 | "-of", | |
| 865 | "csv=p=0", | |
| 866 | ]) | |
| 867 | .arg(&mp4_path) | |
| 868 | .output() | |
| 869 | .expect("run ffprobe"); | |
| 870 | assert!( | |
| 871 | probe.status.success(), | |
| 872 | "ffprobe failed: {}", | |
| 873 | String::from_utf8_lossy(&probe.stderr) | |
| 874 | ); | |
| 875 | let stdout = String::from_utf8_lossy(&probe.stdout); | |
| 876 | let mut saw_h264_12 = false; | |
| 877 | let mut saw_aac = false; | |
| 878 | for line in stdout.lines() { | |
| 879 | let cols: Vec<&str> = line.split(',').map(str::trim).collect(); | |
| 880 | if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" { | |
| 881 | saw_h264_12 = true; | |
| 882 | } | |
| 883 | if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" { | |
| 884 | saw_aac = true; | |
| 885 | } | |
| 886 | } | |
| 887 | assert!( | |
| 888 | saw_h264_12, | |
| 889 | "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}" | |
| 890 | ); | |
| 891 | assert!( | |
| 892 | saw_aac, | |
| 893 | "expected aac audio stream, ffprobe output:\n{stdout}" | |
| 894 | ); | |
| 895 | ||
| 896 | // Also verify negative audio_start_secs (range starts before AudioOffset = 10) | |
| 897 | let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4"); | |
| 898 | let pre_summary = export_node_video_ffmpeg( | |
| 899 | &mut engine, | |
| 900 | &comp, | |
| 901 | &VideoExportOptions { | |
| 902 | target, | |
| 903 | out_path: pre_mp4_path.clone(), | |
| 904 | range: [6, 17], | |
| 905 | codec: VideoCodec::H264Share, | |
| 906 | crf: 26, | |
| 907 | max_height: Some(64), | |
| 908 | include_audio: true, | |
| 909 | hiq: true, | |
| 910 | proxy_scale: 1, | |
| 911 | }, | |
| 912 | |_| {}, | |
| 913 | ) | |
| 914 | .expect("export snippet mp4 with negative audio_start_secs"); | |
| 915 | assert_eq!(pre_summary.frames_written, 12); | |
| 916 | assert!(pre_summary.has_audio); | |
| 917 | assert!(pre_summary.file_bytes > 0); | |
| 918 | assert!(pre_mp4_path.exists()); | |
| 919 | ||
| 920 | // Verify single-frame PNG helper | |
| 921 | let png_path = tmp_dir.join("frame_10.png"); | |
| 922 | let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path) | |
| 923 | .expect("export single frame png"); | |
| 924 | assert_eq!(saved, png_path); | |
| 925 | let img = image::open(&png_path).expect("decode exported frame png").to_rgba8(); | |
| 926 | assert_eq!(img.dimensions(), (128, 72)); | |
| 927 | ||
| 928 | let _ = std::fs::remove_dir_all(&tmp_dir); | |
| 929 | } | |
| 382 | 930 | } |
crates/viewer/src/lib.rs+484-7| ... | ... | @@ -32,6 +32,8 @@ pub struct PlaybackClock { |
| 32 | 32 | pub current_frame: f64, |
| 33 | 33 | pub playing: bool, |
| 34 | 34 | pub sync_mode: SyncMode, |
| 35 | /// Optional user-defined preview/export `[in, out]` frame markers (inclusive). | |
| 36 | pub in_out_range: [Option<i64>; 2], | |
| 35 | 37 | anchor_time: Instant, |
| 36 | 38 | anchor_frame: f64, |
| 37 | 39 | last_every_step: Instant, |
| ... | ... | @@ -50,6 +52,7 @@ impl PlaybackClock { |
| 50 | 52 | current_frame: 0.0, |
| 51 | 53 | playing: false, |
| 52 | 54 | sync_mode: SyncMode::RealtimeDrop, |
| 55 | in_out_range: [None, None], | |
| 53 | 56 | anchor_time: now, |
| 54 | 57 | anchor_frame: 0.0, |
| 55 | 58 | last_every_step: now, |
| ... | ... | @@ -61,11 +64,40 @@ impl PlaybackClock { |
| 61 | 64 | let r0 = comp.render_range[0] as f64; |
| 62 | 65 | let r1 = comp.render_range[1] as f64; |
| 63 | 66 | self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 }; |
| 67 | self.in_out_range = [None, None]; | |
| 64 | 68 | self.anchor_frame = self.current_frame; |
| 65 | 69 | self.anchor_time = Instant::now(); |
| 66 | 70 | self.last_every_step = self.anchor_time; |
| 67 | 71 | } |
| 68 | 72 | |
| 73 | /// Returns the active inclusive preview/export range `[in.unwrap_or(r0), out.unwrap_or(r1)]`, | |
| 74 | /// clamped to `comp.render_range` and sorted ascending. | |
| 75 | pub fn effective_preview_range(&self, comp: &Comp) -> [i64; 2] { | |
| 76 | let r0 = comp.render_range[0]; | |
| 77 | let r1 = comp.render_range[1].max(r0); | |
| 78 | let a = self.in_out_range[0].unwrap_or(r0).clamp(r0, r1); | |
| 79 | let b = self.in_out_range[1].unwrap_or(r1).clamp(r0, r1); | |
| 80 | if a <= b { [a, b] } else { [b, a] } | |
| 81 | } | |
| 82 | ||
| 83 | pub fn set_in_point(&mut self, comp: &Comp) { | |
| 84 | let r0 = comp.render_range[0]; | |
| 85 | let r1 = comp.render_range[1].max(r0); | |
| 86 | let f = (self.current_frame.round() as i64).clamp(r0, r1); | |
| 87 | self.in_out_range[0] = Some(f); | |
| 88 | } | |
| 89 | ||
| 90 | pub fn set_out_point(&mut self, comp: &Comp) { | |
| 91 | let r0 = comp.render_range[0]; | |
| 92 | let r1 = comp.render_range[1].max(r0); | |
| 93 | let f = (self.current_frame.round() as i64).clamp(r0, r1); | |
| 94 | self.in_out_range[1] = Some(f); | |
| 95 | } | |
| 96 | ||
| 97 | pub fn clear_in_out(&mut self) { | |
| 98 | self.in_out_range = [None, None]; | |
| 99 | } | |
| 100 | ||
| 69 | 101 | pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool { |
| 70 | 102 | let clamped = frame |
| 71 | 103 | .round() |
| ... | ... | @@ -93,8 +125,9 @@ impl PlaybackClock { |
| 93 | 125 | if !self.playing { |
| 94 | 126 | return (false, false); |
| 95 | 127 | } |
| 96 | let r0 = comp.render_range[0] as f64; | |
| 97 | let r1 = comp.render_range[1].max(comp.render_range[0] + 1) as f64; | |
| 128 | let [p0, p1] = self.effective_preview_range(comp); | |
| 129 | let r0 = p0 as f64; | |
| 130 | let r1 = p1.max(p0) as f64; | |
| 98 | 131 | let span = (r1 - r0 + 1.0).max(1.0); |
| 99 | 132 | let fps = comp.fps.max(1.0); |
| 100 | 133 | let frame_dur = Duration::from_secs_f64(1.0 / fps); |
| ... | ... | @@ -112,7 +145,7 @@ impl PlaybackClock { |
| 112 | 145 | } |
| 113 | 146 | SyncMode::EveryFrame => { |
| 114 | 147 | if now.saturating_duration_since(self.last_every_step) >= frame_dur { |
| 115 | let next = if self.current_frame + 1.0 > r1 { | |
| 148 | let next = if self.current_frame + 1.0 > r1 || self.current_frame < r0 { | |
| 116 | 149 | r0 |
| 117 | 150 | } else { |
| 118 | 151 | self.current_frame + 1.0 |
| ... | ... | @@ -146,8 +179,35 @@ pub enum ViewerAction { |
| 146 | 179 | ToggleHiQ, |
| 147 | 180 | ClearViewers, |
| 148 | 181 | GizmoEdited(GizmoEdit), |
| 182 | ExportPreviewMp4(usize), | |
| 183 | SaveFramePng(usize), | |
| 184 | SetInPoint, | |
| 185 | SetOutPoint, | |
| 186 | ClearInOut, | |
| 187 | } | |
| 188 | ||
| 189 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 190 | enum ContextMenuItem { | |
| 191 | ExportPreviewMp4, | |
| 192 | SaveFramePng, | |
| 193 | SetInPoint, | |
| 194 | SetOutPoint, | |
| 195 | ClearInOut, | |
| 149 | 196 | } |
| 150 | 197 | |
| 198 | const CONTEXT_MENU_ITEMS: &[(ContextMenuItem, &str)] = &[ | |
| 199 | (ContextMenuItem::ExportPreviewMp4, "Export Preview MP4 (with Audio)..."), | |
| 200 | (ContextMenuItem::SaveFramePng, "Save Frame PNG..."), | |
| 201 | (ContextMenuItem::SetInPoint, "Set In Point (I)"), | |
| 202 | (ContextMenuItem::SetOutPoint, "Set Out Point (O)"), | |
| 203 | (ContextMenuItem::ClearInOut, "Reset In/Out Range"), | |
| 204 | ]; | |
| 205 | const CONTEXT_MENU_W: f32 = 248.0; | |
| 206 | const CONTEXT_MENU_ITEM_H: f32 = 26.0; | |
| 207 | const CONTEXT_MENU_PAD_Y: f32 = 5.0; | |
| 208 | const CONTEXT_MENU_SEP_AFTER: usize = 1; | |
| 209 | const CONTEXT_MENU_SEP_H: f32 = 7.0; | |
| 210 | ||
| 151 | 211 | #[derive(Clone, Copy, Debug)] |
| 152 | 212 | pub struct ViewerPalette { |
| 153 | 213 | pub bg: [f32; 4], |
| ... | ... | @@ -202,6 +262,10 @@ pub struct ViewerState { |
| 202 | 262 | scrubbing: bool, |
| 203 | 263 | pointer_local: [f32; 2], |
| 204 | 264 | hud_layout: Option<(String, text::Layout)>, |
| 265 | in_out_range: [Option<i64>; 2], | |
| 266 | context_menu: Option<[f32; 2]>, | |
| 267 | context_menu_hover: Option<usize>, | |
| 268 | menu_item_layouts: Vec<text::Layout>, | |
| 205 | 269 | } |
| 206 | 270 | |
| 207 | 271 | impl ViewerState { |
| ... | ... | @@ -233,9 +297,22 @@ impl ViewerState { |
| 233 | 297 | scrubbing: false, |
| 234 | 298 | pointer_local: [0.0, 0.0], |
| 235 | 299 | hud_layout: None, |
| 300 | in_out_range: [None, None], | |
| 301 | context_menu: None, | |
| 302 | context_menu_hover: None, | |
| 303 | menu_item_layouts: Vec::new(), | |
| 236 | 304 | } |
| 237 | 305 | } |
| 238 | 306 | |
| 307 | pub fn close_context_menu(&mut self) { | |
| 308 | self.context_menu = None; | |
| 309 | self.context_menu_hover = None; | |
| 310 | } | |
| 311 | ||
| 312 | pub fn is_context_menu_open(&self) -> bool { | |
| 313 | self.context_menu.is_some() | |
| 314 | } | |
| 315 | ||
| 239 | 316 | pub fn background(&self) -> [f32; 4] { |
| 240 | 317 | self.palette.bg |
| 241 | 318 | } |
| ... | ... | @@ -416,6 +493,7 @@ impl ViewerState { |
| 416 | 493 | } |
| 417 | 494 | |
| 418 | 495 | pub fn prepare_hud(&mut self, comp: &Comp, engine: &Engine, clock: &PlaybackClock) { |
| 496 | self.in_out_range = clock.in_out_range; | |
| 419 | 497 | let node_name = self |
| 420 | 498 | .viewed_node |
| 421 | 499 | .map(|id| comp.node(id).name.as_str()) |
| ... | ... | @@ -432,11 +510,18 @@ impl ViewerState { |
| 432 | 510 | let (_, _, _, eff_scale) = self.image_layout(comp); |
| 433 | 511 | let zoom_pct = (eff_scale * 100.0).round() as i32; |
| 434 | 512 | let s = &self.last_stats; |
| 513 | let io_suffix = if clock.in_out_range[0].is_some() || clock.in_out_range[1].is_some() { | |
| 514 | let [a, b] = clock.effective_preview_range(comp); | |
| 515 | format!(" · [{a}..{b}]") | |
| 516 | } else { | |
| 517 | String::new() | |
| 518 | }; | |
| 435 | 519 | let line = format!( |
| 436 | "[V{}] {} · f{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}", | |
| 520 | "[V{}] {} · f{}{} · {}% · {:.1}ms · ev:{} h:{} m:{} · {:.0}MB · 1:{} · {} · {} · {}", | |
| 437 | 521 | self.slot + 1, |
| 438 | 522 | node_name, |
| 439 | 523 | clock.current_frame.round() as i64, |
| 524 | io_suffix, | |
| 440 | 525 | zoom_pct, |
| 441 | 526 | s.eval_ms, |
| 442 | 527 | s.nodes_evaluated, |
| ... | ... | @@ -470,6 +555,33 @@ impl ViewerState { |
| 470 | 555 | .layout(); |
| 471 | 556 | self.hud_layout = Some((line, layout)); |
| 472 | 557 | } |
| 558 | ||
| 559 | if self.menu_item_layouts.len() != CONTEXT_MENU_ITEMS.len() { | |
| 560 | let font = text::Font { | |
| 561 | families: Arc::from([text::Family::Sans]), | |
| 562 | size: 12.0, | |
| 563 | weight: 500, | |
| 564 | italic: false, | |
| 565 | }; | |
| 566 | let styles = [text::Style::new(font)]; | |
| 567 | self.menu_item_layouts = CONTEXT_MENU_ITEMS | |
| 568 | .iter() | |
| 569 | .map(|(_, label)| { | |
| 570 | text::Paragraph { | |
| 571 | text: label, | |
| 572 | styles: &styles, | |
| 573 | spans: &[], | |
| 574 | replacements: &[], | |
| 575 | width: None, | |
| 576 | indent: 0.0, | |
| 577 | line_height: 1.2, | |
| 578 | align: text::Align::Left, | |
| 579 | tab: 32.0, | |
| 580 | } | |
| 581 | .layout() | |
| 582 | }) | |
| 583 | .collect(); | |
| 584 | } | |
| 473 | 585 | } |
| 474 | 586 | |
| 475 | 587 | pub fn build_ui( |
| ... | ... | @@ -480,6 +592,7 @@ impl ViewerState { |
| 480 | 592 | engine: &Engine, |
| 481 | 593 | clock: &PlaybackClock, |
| 482 | 594 | ) -> Vec<ViewerAction> { |
| 595 | self.in_out_range = clock.in_out_range; | |
| 483 | 596 | let mut actions = Vec::new(); |
| 484 | 597 | ui.open_as( |
| 485 | 598 | pane_id, |
| ... | ... | @@ -620,7 +733,58 @@ impl ViewerState { |
| 620 | 733 | (r0 + f64::from(frac) * (r1 - r0)).round() |
| 621 | 734 | } |
| 622 | 735 | |
| 736 | fn context_menu_rect(&self, anchor: [f32; 2]) -> [f32; 4] { | |
| 737 | let total_h = CONTEXT_MENU_PAD_Y * 2.0 | |
| 738 | + CONTEXT_MENU_ITEMS.len() as f32 * CONTEXT_MENU_ITEM_H | |
| 739 | + CONTEXT_MENU_SEP_H; | |
| 740 | let max_x = (self.size[0] - CONTEXT_MENU_W - 6.0).max(6.0); | |
| 741 | let max_y = (self.size[1] - total_h - 6.0).max(6.0); | |
| 742 | let x0 = anchor[0].clamp(6.0, max_x); | |
| 743 | let y0 = anchor[1].clamp(6.0, max_y); | |
| 744 | [x0, y0, x0 + CONTEXT_MENU_W, y0 + total_h] | |
| 745 | } | |
| 746 | ||
| 747 | fn context_menu_item_rect(&self, menu_rect: [f32; 4], idx: usize) -> [f32; 4] { | |
| 748 | let sep_extra = if idx > CONTEXT_MENU_SEP_AFTER { | |
| 749 | CONTEXT_MENU_SEP_H | |
| 750 | } else { | |
| 751 | 0.0 | |
| 752 | }; | |
| 753 | let y0 = menu_rect[1] + CONTEXT_MENU_PAD_Y + idx as f32 * CONTEXT_MENU_ITEM_H + sep_extra; | |
| 754 | [menu_rect[0] + 4.0, y0, menu_rect[2] - 4.0, y0 + CONTEXT_MENU_ITEM_H] | |
| 755 | } | |
| 756 | ||
| 757 | fn hit_context_menu_item(&self, anchor: [f32; 2], pt: [f32; 2]) -> Option<usize> { | |
| 758 | let mr = self.context_menu_rect(anchor); | |
| 759 | if pt[0] < mr[0] || pt[0] > mr[2] || pt[1] < mr[1] || pt[1] > mr[3] { | |
| 760 | return None; | |
| 761 | } | |
| 762 | for idx in 0..CONTEXT_MENU_ITEMS.len() { | |
| 763 | let r = self.context_menu_item_rect(mr, idx); | |
| 764 | if pt[0] >= r[0] && pt[0] <= r[2] && pt[1] >= r[1] && pt[1] <= r[3] { | |
| 765 | return Some(idx); | |
| 766 | } | |
| 767 | } | |
| 768 | None | |
| 769 | } | |
| 770 | ||
| 771 | fn context_menu_action(&self, item: ContextMenuItem) -> ViewerAction { | |
| 772 | match item { | |
| 773 | ContextMenuItem::ExportPreviewMp4 => ViewerAction::ExportPreviewMp4(self.slot), | |
| 774 | ContextMenuItem::SaveFramePng => ViewerAction::SaveFramePng(self.slot), | |
| 775 | ContextMenuItem::SetInPoint => ViewerAction::SetInPoint, | |
| 776 | ContextMenuItem::SetOutPoint => ViewerAction::SetOutPoint, | |
| 777 | ContextMenuItem::ClearInOut => ViewerAction::ClearInOut, | |
| 778 | } | |
| 779 | } | |
| 780 | ||
| 623 | 781 | fn handle_key(&mut self, clock: &PlaybackClock, physical: Option<PhysicalKey>, key: &Key, kmod: ModifiersState, actions: &mut Vec<ViewerAction>) { |
| 782 | if matches!(key, Key::Named(NamedKey::Escape)) { | |
| 783 | if self.context_menu.is_some() { | |
| 784 | self.close_context_menu(); | |
| 785 | } | |
| 786 | return; | |
| 787 | } | |
| 624 | 788 | if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { |
| 625 | 789 | self.fit(); |
| 626 | 790 | return; |
| ... | ... | @@ -629,12 +793,29 @@ impl ViewerState { |
| 629 | 793 | actions.push(ViewerAction::ClearViewers); |
| 630 | 794 | return; |
| 631 | 795 | } |
| 796 | if physical == Some(PhysicalKey::Code(KeyCode::KeyX)) | |
| 797 | && kmod.alt_key() | |
| 798 | && !kmod.super_key() | |
| 799 | && !kmod.control_key() | |
| 800 | { | |
| 801 | actions.push(ViewerAction::ClearInOut); | |
| 802 | return; | |
| 803 | } | |
| 632 | 804 | match key { |
| 633 | 805 | Key::Named(NamedKey::Space) => actions.push(ViewerAction::TogglePlay), |
| 634 | 806 | Key::Named(NamedKey::ArrowLeft) => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), |
| 635 | 807 | Key::Named(NamedKey::ArrowRight) => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), |
| 636 | 808 | Key::Character(c) => match c.to_ascii_lowercase().as_str() { |
| 637 | 809 | "`" | "~" => actions.push(ViewerAction::ClearViewers), |
| 810 | "i" if !kmod.super_key() && !kmod.control_key() && !kmod.alt_key() => { | |
| 811 | actions.push(ViewerAction::SetInPoint); | |
| 812 | } | |
| 813 | "o" if !kmod.super_key() && !kmod.control_key() && !kmod.alt_key() => { | |
| 814 | actions.push(ViewerAction::SetOutPoint); | |
| 815 | } | |
| 816 | "x" | "≈" if kmod.alt_key() && !kmod.super_key() && !kmod.control_key() => { | |
| 817 | actions.push(ViewerAction::ClearInOut); | |
| 818 | } | |
| 638 | 819 | "f" if kmod.super_key() => self.fit(), |
| 639 | 820 | "f" | "." if !kmod.super_key() => self.fit(), |
| 640 | 821 | "0" => { |
| ... | ... | @@ -661,13 +842,16 @@ impl ViewerState { |
| 661 | 842 | modifiers: ModifiersState, |
| 662 | 843 | ) -> Vec<ViewerAction> { |
| 663 | 844 | let mut actions = Vec::new(); |
| 845 | self.in_out_range = clock.in_out_range; | |
| 664 | 846 | self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; |
| 665 | 847 | let scrub = self.scrubber_rect(); |
| 666 | 848 | |
| 667 | 849 | match event { |
| 668 | 850 | ui::Event::PointerMoved(p) => { |
| 669 | 851 | self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; |
| 670 | if self.scrubbing { | |
| 852 | if let Some(anchor) = self.context_menu { | |
| 853 | self.context_menu_hover = self.hit_context_menu_item(anchor, self.pointer_local); | |
| 854 | } else if self.scrubbing { | |
| 671 | 855 | actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); |
| 672 | 856 | } else if self.gizmos.is_dragging() { |
| 673 | 857 | let (img_rect, _, _, _) = self.image_layout(comp); |
| ... | ... | @@ -687,8 +871,18 @@ impl ViewerState { |
| 687 | 871 | } |
| 688 | 872 | } |
| 689 | 873 | ui::Event::Button { button, pressed, .. } => { |
| 690 | if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { | |
| 874 | if button == MouseButton::Right { | |
| 875 | if pressed { | |
| 876 | self.scrubbing = false; | |
| 877 | self.panning = None; | |
| 878 | self.gizmos.end_drag(); | |
| 879 | self.context_menu = Some(self.pointer_local); | |
| 880 | self.context_menu_hover = | |
| 881 | self.hit_context_menu_item(self.pointer_local, self.pointer_local); | |
| 882 | } | |
| 883 | } else if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { | |
| 691 | 884 | if pressed { |
| 885 | self.close_context_menu(); | |
| 692 | 886 | if self.fit_mode { |
| 693 | 887 | let (_, _, _, cur_scale) = self.image_layout(comp); |
| 694 | 888 | self.zoom = cur_scale; |
| ... | ... | @@ -701,7 +895,13 @@ impl ViewerState { |
| 701 | 895 | } |
| 702 | 896 | } else if button == MouseButton::Left { |
| 703 | 897 | if pressed { |
| 704 | if self.pointer_local[1] >= scrub[1] - 6.0 { | |
| 898 | if let Some(anchor) = self.context_menu { | |
| 899 | let picked = self.hit_context_menu_item(anchor, self.pointer_local); | |
| 900 | self.close_context_menu(); | |
| 901 | if let Some(idx) = picked { | |
| 902 | actions.push(self.context_menu_action(CONTEXT_MENU_ITEMS[idx].0)); | |
| 903 | } | |
| 904 | } else if self.pointer_local[1] >= scrub[1] - 6.0 { | |
| 705 | 905 | self.scrubbing = true; |
| 706 | 906 | actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); |
| 707 | 907 | } else if let Some(sel) = self.selected_node { |
| ... | ... | @@ -847,6 +1047,62 @@ impl ViewerState { |
| 847 | 1047 | } |
| 848 | 1048 | } |
| 849 | 1049 | |
| 1050 | // Crisp In/Out preview range highlight & bracket markers | |
| 1051 | if self.in_out_range[0].is_some() || self.in_out_range[1].is_some() { | |
| 1052 | let rr0 = comp.render_range[0]; | |
| 1053 | let rr1 = comp.render_range[1].max(rr0); | |
| 1054 | let raw_a = self.in_out_range[0].unwrap_or(rr0).clamp(rr0, rr1); | |
| 1055 | let raw_b = self.in_out_range[1].unwrap_or(rr1).clamp(rr0, rr1); | |
| 1056 | let (in_f, out_f) = if raw_a <= raw_b { (raw_a, raw_b) } else { (raw_b, raw_a) }; | |
| 1057 | let ix0 = sr[0] + ((in_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; | |
| 1058 | let ix1 = sr[0] + ((out_f as f64 - r0) / span).clamp(0.0, 1.0) as f32 * bar_w; | |
| 1059 | let span_x1 = ix1.max(ix0 + 2.0).min(sr[2]); | |
| 1060 | let acc = self.palette.accent; | |
| 1061 | out.push(Primitive::RoundedRect { | |
| 1062 | rect: [ix0, sr[1], span_x1, sr[3]], | |
| 1063 | radius: 3.0, | |
| 1064 | stroke: None, | |
| 1065 | color: [acc[0], acc[1], acc[2], 0.22], | |
| 1066 | }); | |
| 1067 | out.push(Primitive::Rect { | |
| 1068 | rect: [ix0, sr[1], span_x1, sr[1] + 2.0], | |
| 1069 | color: [acc[0], acc[1], acc[2], 0.85], | |
| 1070 | }); | |
| 1071 | let bracket_col = [ | |
| 1072 | (acc[0] + 0.16).min(1.0), | |
| 1073 | (acc[1] + 0.16).min(1.0), | |
| 1074 | (acc[2] + 0.16).min(1.0), | |
| 1075 | 0.98, | |
| 1076 | ]; | |
| 1077 | // In bracket `[` | |
| 1078 | out.push(Primitive::Rect { | |
| 1079 | rect: [ix0, sr[1] - 1.0, (ix0 + 2.0).min(sr[2]), sr[3] + 1.0], | |
| 1080 | color: bracket_col, | |
| 1081 | }); | |
| 1082 | out.push(Primitive::Rect { | |
| 1083 | rect: [ix0, sr[1] - 1.0, (ix0 + 6.0).min(sr[2]), sr[1] + 1.0], | |
| 1084 | color: bracket_col, | |
| 1085 | }); | |
| 1086 | out.push(Primitive::Rect { | |
| 1087 | rect: [ix0, sr[3] - 1.0, (ix0 + 6.0).min(sr[2]), sr[3] + 1.0], | |
| 1088 | color: bracket_col, | |
| 1089 | }); | |
| 1090 | // Out bracket `]` | |
| 1091 | let ox = span_x1; | |
| 1092 | out.push(Primitive::Rect { | |
| 1093 | rect: [(ox - 2.0).max(sr[0]), sr[1] - 1.0, ox, sr[3] + 1.0], | |
| 1094 | color: bracket_col, | |
| 1095 | }); | |
| 1096 | out.push(Primitive::Rect { | |
| 1097 | rect: [(ox - 6.0).max(sr[0]), sr[1] - 1.0, ox, sr[1] + 1.0], | |
| 1098 | color: bracket_col, | |
| 1099 | }); | |
| 1100 | out.push(Primitive::Rect { | |
| 1101 | rect: [(ox - 6.0).max(sr[0]), sr[3] - 1.0, ox, sr[3] + 1.0], | |
| 1102 | color: bracket_col, | |
| 1103 | }); | |
| 1104 | } | |
| 1105 | ||
| 850 | 1106 | let frac = ((current_frame - r0) / span).clamp(0.0, 1.0) as f32; |
| 851 | 1107 | let px = sr[0] + frac * bar_w; |
| 852 | 1108 | out.push(Primitive::RoundedRect { |
| ... | ... | @@ -862,6 +1118,66 @@ impl ViewerState { |
| 862 | 1118 | color: [0.98, 0.40, 0.36, 1.0], |
| 863 | 1119 | }); |
| 864 | 1120 | |
| 1121 | // Knife-styled right-click floating context menu | |
| 1122 | if let Some(anchor) = self.context_menu { | |
| 1123 | let mr = self.context_menu_rect(anchor); | |
| 1124 | // Soft drop shadow | |
| 1125 | out.push(Primitive::RoundedRect { | |
| 1126 | rect: [mr[0] + 2.0, mr[1] + 4.0, mr[2] + 2.0, mr[3] + 4.0], | |
| 1127 | radius: 8.0, | |
| 1128 | stroke: None, | |
| 1129 | color: [0.0, 0.0, 0.0, 0.38], | |
| 1130 | }); | |
| 1131 | let bg = self.palette.bar; | |
| 1132 | let panel_fill = [ | |
| 1133 | (bg[0] + 0.03).min(1.0), | |
| 1134 | (bg[1] + 0.03).min(1.0), | |
| 1135 | (bg[2] + 0.035).min(1.0), | |
| 1136 | 0.97, | |
| 1137 | ]; | |
| 1138 | out.push(Primitive::RoundedRect { | |
| 1139 | rect: mr, | |
| 1140 | radius: 7.0, | |
| 1141 | stroke: None, | |
| 1142 | color: panel_fill, | |
| 1143 | }); | |
| 1144 | out.push(Primitive::RoundedRect { | |
| 1145 | rect: mr, | |
| 1146 | radius: 7.0, | |
| 1147 | stroke: Some(1.0), | |
| 1148 | color: self.palette.border, | |
| 1149 | }); | |
| 1150 | ||
| 1151 | // Hairline separator after export actions | |
| 1152 | let sep_y = mr[1] | |
| 1153 | + CONTEXT_MENU_PAD_Y | |
| 1154 | + (CONTEXT_MENU_SEP_AFTER + 1) as f32 * CONTEXT_MENU_ITEM_H | |
| 1155 | + CONTEXT_MENU_SEP_H * 0.5; | |
| 1156 | out.push(Primitive::Rect { | |
| 1157 | rect: [mr[0] + 8.0, sep_y - 0.5, mr[2] - 8.0, sep_y + 0.5], | |
| 1158 | color: self.palette.border, | |
| 1159 | }); | |
| 1160 | ||
| 1161 | let acc = self.palette.accent; | |
| 1162 | for (idx, layout) in self.menu_item_layouts.iter().enumerate() { | |
| 1163 | let item_r = self.context_menu_item_rect(mr, idx); | |
| 1164 | if self.context_menu_hover == Some(idx) { | |
| 1165 | out.push(Primitive::RoundedRect { | |
| 1166 | rect: item_r, | |
| 1167 | radius: 4.0, | |
| 1168 | stroke: None, | |
| 1169 | color: [acc[0], acc[1], acc[2], 0.24], | |
| 1170 | }); | |
| 1171 | } | |
| 1172 | out.push(Primitive::Text { | |
| 1173 | text: layout as &dyn Glyphs, | |
| 1174 | origin: [item_r[0] + 10.0, item_r[1] + 5.0], | |
| 1175 | clip: Some([item_r[0] + 4.0, item_r[1], item_r[2] - 4.0, item_r[3]]), | |
| 1176 | ink: self.palette.text, | |
| 1177 | }); | |
| 1178 | } | |
| 1179 | } | |
| 1180 | ||
| 865 | 1181 | out |
| 866 | 1182 | } |
| 867 | 1183 | } |
| ... | ... | @@ -902,3 +1218,164 @@ fn tool_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bo |
| 902 | 1218 | }, |
| 903 | 1219 | ) |
| 904 | 1220 | } |
| 1221 | ||
| 1222 | #[cfg(test)] | |
| 1223 | mod tests { | |
| 1224 | use super::*; | |
| 1225 | ||
| 1226 | fn test_comp() -> Comp { | |
| 1227 | let src = r#"Composition { | |
| 1228 | CurrentTime = 15, | |
| 1229 | RenderRange = { 10, 50 }, | |
| 1230 | GlobalRange = { 0, 100 }, | |
| 1231 | Tools = ordered() { | |
| 1232 | BG = Background { | |
| 1233 | Inputs = { | |
| 1234 | Width = Input { Value = 320, }, | |
| 1235 | Height = Input { Value = 180, }, | |
| 1236 | }, | |
| 1237 | }, | |
| 1238 | }, | |
| 1239 | Prefs = { Comp = { FrameFormat = { Width = 320, Height = 180, Rate = 30 } } }, | |
| 1240 | }"#; | |
| 1241 | Comp::from_fusion_str(src).expect("parse test comp") | |
| 1242 | } | |
| 1243 | ||
| 1244 | #[test] | |
| 1245 | fn effective_preview_range_sorts_and_clamps() { | |
| 1246 | let comp = test_comp(); | |
| 1247 | let mut clock = PlaybackClock::new(); | |
| 1248 | clock.init_from_comp(&comp); | |
| 1249 | assert_eq!(clock.effective_preview_range(&comp), [10, 50]); | |
| 1250 | ||
| 1251 | clock.in_out_range = [Some(20), None]; | |
| 1252 | assert_eq!(clock.effective_preview_range(&comp), [20, 50]); | |
| 1253 | ||
| 1254 | clock.in_out_range = [None, Some(30)]; | |
| 1255 | assert_eq!(clock.effective_preview_range(&comp), [10, 30]); | |
| 1256 | ||
| 1257 | // Reversed and out-of-bounds points get clamped and sorted cleanly | |
| 1258 | clock.in_out_range = [Some(99), Some(2)]; | |
| 1259 | assert_eq!(clock.effective_preview_range(&comp), [10, 50]); | |
| 1260 | ||
| 1261 | clock.in_out_range = [Some(35), Some(18)]; | |
| 1262 | assert_eq!(clock.effective_preview_range(&comp), [18, 35]); | |
| 1263 | } | |
| 1264 | ||
| 1265 | #[test] | |
| 1266 | fn hotkeys_and_right_click_menu_emit_actions() { | |
| 1267 | let comp = test_comp(); | |
| 1268 | let mut clock = PlaybackClock::new(); | |
| 1269 | clock.init_from_comp(&comp); | |
| 1270 | let ui_theme = ui::Theme::new(&theme::KNIFE, true); | |
| 1271 | let mut viewer = ViewerState::new(1, &ui_theme); | |
| 1272 | viewer.resize([640.0, 400.0]); | |
| 1273 | let rect = [0.0, 0.0, 640.0, 400.0]; | |
| 1274 | ||
| 1275 | // Hotkeys: I, O, Alt+X | |
| 1276 | let acts_i = viewer.input( | |
| 1277 | &comp, | |
| 1278 | &clock, | |
| 1279 | ui::Event::Key { | |
| 1280 | key: Key::Character("i".into()), | |
| 1281 | modifiers: ModifiersState::empty(), | |
| 1282 | text: None, | |
| 1283 | }, | |
| 1284 | rect, | |
| 1285 | [100.0, 100.0], | |
| 1286 | ModifiersState::empty(), | |
| 1287 | ); | |
| 1288 | assert!(matches!(acts_i.as_slice(), [ViewerAction::SetInPoint])); | |
| 1289 | ||
| 1290 | let acts_o = viewer.input( | |
| 1291 | &comp, | |
| 1292 | &clock, | |
| 1293 | ui::Event::Key { | |
| 1294 | key: Key::Character("o".into()), | |
| 1295 | modifiers: ModifiersState::empty(), | |
| 1296 | text: None, | |
| 1297 | }, | |
| 1298 | rect, | |
| 1299 | [100.0, 100.0], | |
| 1300 | ModifiersState::empty(), | |
| 1301 | ); | |
| 1302 | assert!(matches!(acts_o.as_slice(), [ViewerAction::SetOutPoint])); | |
| 1303 | ||
| 1304 | let acts_clear = viewer.input( | |
| 1305 | &comp, | |
| 1306 | &clock, | |
| 1307 | ui::Event::KeyInput { | |
| 1308 | physical: PhysicalKey::Code(KeyCode::KeyX), | |
| 1309 | key: Key::Character("≈".into()), | |
| 1310 | text: None, | |
| 1311 | unshifted: Key::Character("x".into()), | |
| 1312 | modifiers: ModifiersState::ALT, | |
| 1313 | state: ElementState::Pressed, | |
| 1314 | repeat: false, | |
| 1315 | }, | |
| 1316 | rect, | |
| 1317 | [100.0, 100.0], | |
| 1318 | ModifiersState::ALT, | |
| 1319 | ); | |
| 1320 | assert!(matches!(acts_clear.as_slice(), [ViewerAction::ClearInOut])); | |
| 1321 | ||
| 1322 | let now = Instant::now(); | |
| 1323 | // Right-click opens context menu, left-click on first item emits ExportPreviewMp4(1) | |
| 1324 | let _ = viewer.input( | |
| 1325 | &comp, | |
| 1326 | &clock, | |
| 1327 | ui::Event::Button { | |
| 1328 | button: MouseButton::Right, | |
| 1329 | pressed: true, | |
| 1330 | at: now, | |
| 1331 | }, | |
| 1332 | rect, | |
| 1333 | [120.0, 120.0], | |
| 1334 | ModifiersState::empty(), | |
| 1335 | ); | |
| 1336 | assert!(viewer.is_context_menu_open()); | |
| 1337 | ||
| 1338 | let acts_export = viewer.input( | |
| 1339 | &comp, | |
| 1340 | &clock, | |
| 1341 | ui::Event::Button { | |
| 1342 | button: MouseButton::Left, | |
| 1343 | pressed: true, | |
| 1344 | at: now, | |
| 1345 | }, | |
| 1346 | rect, | |
| 1347 | [140.0, 135.0], | |
| 1348 | ModifiersState::empty(), | |
| 1349 | ); | |
| 1350 | assert!(!viewer.is_context_menu_open()); | |
| 1351 | assert!(matches!(acts_export.as_slice(), [ViewerAction::ExportPreviewMp4(1)])); | |
| 1352 | ||
| 1353 | // Right-click again, then Escape dismisses cleanly | |
| 1354 | let _ = viewer.input( | |
| 1355 | &comp, | |
| 1356 | &clock, | |
| 1357 | ui::Event::Button { | |
| 1358 | button: MouseButton::Right, | |
| 1359 | pressed: true, | |
| 1360 | at: now, | |
| 1361 | }, | |
| 1362 | rect, | |
| 1363 | [120.0, 120.0], | |
| 1364 | ModifiersState::empty(), | |
| 1365 | ); | |
| 1366 | assert!(viewer.is_context_menu_open()); | |
| 1367 | let _ = viewer.input( | |
| 1368 | &comp, | |
| 1369 | &clock, | |
| 1370 | ui::Event::Key { | |
| 1371 | key: Key::Named(NamedKey::Escape), | |
| 1372 | modifiers: ModifiersState::empty(), | |
| 1373 | text: None, | |
| 1374 | }, | |
| 1375 | rect, | |
| 1376 | [120.0, 120.0], | |
| 1377 | ModifiersState::empty(), | |
| 1378 | ); | |
| 1379 | assert!(!viewer.is_context_menu_open()); | |
| 1380 | } | |
| 1381 | } |