Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M3.12: Export frames from Source and Program monitors

Cathy Shapiro9f0ed51b4917
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rs
index b9b279a12..5974310fa 100644
--- a/apps/filmcraft/src/main.rs
+++ b/apps/filmcraft/src/main.rs
@@ -180,6 +180,8 @@ fn main() -> eframe::Result {
rfd::FileDialog::new().add_filter(filter, exts).set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string())
}));
app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));
+ app.hooks.pick_folder_at =
+ Some(Box::new(|dir: &str| rfd::FileDialog::new().set_directory(dir).pick_folder().map(|p| p.to_string_lossy().into_owned())));
app.hooks.open_path = Some(Box::new(open_path));
app.hooks.raise_without_focus = Some(Box::new(|| {
window_raise::raise_without_focus();
diff --git a/crates/engine/src/frame_export_tests.rs b/crates/engine/src/frame_export_tests.rs
new file mode 100644
index 000000000..12702ba6b
--- /dev/null
+++ b/crates/engine/src/frame_export_tests.rs
@@ -0,0 +1,103 @@
+use crate::{Session, keyboard};
+use filmcraft_media::{DemoScene, Generator, generators::GeneratorSource};
+use filmcraft_project::{ItemId, Label};
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
+use serde_json::json;
+use std::sync::Arc;
+
+fn session() -> (Session, ItemId) {
+ let mut s = Session::default();
+ s.execute("file.newSequence", json!({"width":128,"height":72,"fps":24})).unwrap();
+ let item = crate::demo::add_generator(
+ Arc::make_mut(&mut s.project),
+ &s.media,
+ GeneratorSource::new(Generator::Demo(DemoScene::Aurora), 128, 72, FrameRate::FPS_24, Tick(5 * TICKS_PER_SECOND)),
+ "Source clip",
+ Label::Iris,
+ None,
+ );
+ s.execute("timeline.place", json!({"item":item.0,"track":"V1"})).unwrap();
+ s.execute("source.open", json!({"item":item.0})).unwrap();
+ (s, item)
+}
+
+#[test]
+fn frame_export_selects_the_correct_monitor_time_and_original_media() {
+ let (mut s, item) = session();
+ let dir = std::env::temp_dir().join(format!("fc-frame-original-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let proxy = dir.join("proxy.png");
+ image::RgbaImage::from_pixel(16, 9, image::Rgba([255, 0, 0, 255])).save(&proxy).unwrap();
+ Arc::make_mut(&mut s.project).item_mut(item).unwrap().as_media_mut().unwrap().proxy =
+ Some(filmcraft_project::MediaRef::File { path: proxy.to_string_lossy().into_owned() });
+ s.media.set_use_proxies(true);
+ s.state.source_playhead = FrameRate::FPS_24.tick_of(20);
+ s.set_playhead(FrameRate::FPS_24.tick_of(35));
+ let before = s.project.to_json();
+ let revision = s.revision;
+ let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());
+ let expected_source = filmcraft_render::render_item(&s.project, item, s.state.source_playhead, 1.0, &provider).unwrap().to_rgba8();
+ let preview_provider = s.media.provider(s.project.clone(), s.services.clone());
+ let preview = filmcraft_render::render_item(&s.project, item, s.state.source_playhead, 1.0, &preview_provider).unwrap().to_rgba8();
+ assert_ne!(preview, expected_source, "the preview really uses the red proxy");
+ let seq = s.state.active_sequence.unwrap();
+ let expected_program =
+ filmcraft_render::render_sequence(&s.project, seq, s.playhead(), filmcraft_render::RenderOptions { captions: true, ..Default::default() }, &provider)
+ .to_rgba8();
+ assert_ne!(expected_source, expected_program);
+ for (target, time, expected) in [("source", s.state.source_playhead, expected_source), ("program", s.playhead(), expected_program)] {
+ let path = dir.join(format!("{target}.png"));
+ let result = s.execute("file.exportFrame", json!({"target":target,"path":path.to_string_lossy()})).unwrap();
+ assert_eq!(result["time"], json!(time.0));
+ let image = image::load_from_memory(&std::fs::read(path).unwrap()).unwrap().to_rgba8();
+ assert_eq!(image.dimensions(), (128, 72));
+ assert_eq!(image.into_raw(), expected);
+ }
+ assert_eq!(s.project.to_json(), before);
+ assert_eq!(s.revision, revision);
+ assert!(s.media.use_proxies());
+ drop(s);
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn source_frame_export_works_without_an_active_sequence_and_rejects_bad_params() {
+ let (mut s, item) = session();
+ s.state.active_sequence = None;
+ let path = std::env::temp_dir().join(format!("fc-source-frame-{}.png", std::process::id()));
+ let r = s.execute("file.exportFrame", json!({"target":"source","path":path.to_string_lossy()})).unwrap();
+ assert_eq!(r["width"], 128);
+ assert!(s.execute("file.exportFrame", json!({"path":path.to_string_lossy()})).is_err());
+ for params in [
+ json!({"target":"wrong"}),
+ json!({"target":3}),
+ json!({"target":"source","time":-1}),
+ json!({"target":"source","time":"bad"}),
+ json!({"target":"source","item":0}),
+ json!({"target":"source","format":false}),
+ json!({"target":"source","import":"yes"}),
+ json!({"target":"source","path":""}),
+ ] {
+ assert!(s.execute("file.exportFrame", params.clone()).is_err(), "{params}");
+ }
+ Arc::make_mut(&mut s.project).item_mut(item).unwrap().as_media_mut().unwrap().info.video = None;
+ assert!(s.execute("file.exportFrame", json!({"target":"source","path":path.to_string_lossy()})).is_err());
+ std::fs::remove_file(path).unwrap();
+}
+
+#[test]
+fn frame_export_snapshots_are_independent_of_later_monitor_selection() {
+ let (mut s, item) = session();
+ s.state.source_playhead = FrameRate::FPS_24.tick_of(19);
+ let target = keyboard::frame_export_target(&s, &json!({"target":"source"})).unwrap();
+ s.state.source_item = None;
+ s.state.source_playhead = Tick::ZERO;
+ let path = std::env::temp_dir().join(format!("fc-captured-frame-{}.bmp", std::process::id()));
+ let r = s.execute("file.exportFrame", json!({"target":"source","item":item.0,"time":target.time.0,"format":"bmp","path":path.to_string_lossy()})).unwrap();
+ assert_eq!(r["time"], json!(target.time.0));
+ assert_eq!(&std::fs::read(&path).unwrap()[..2], b"BM");
+ std::fs::remove_file(path).unwrap();
+ let seq = s.state.active_sequence.unwrap();
+ Arc::make_mut(&mut s.project).sequence_mut(seq).unwrap().settings.frame_rate = FrameRate { num: 1, den: i64::MAX };
+ assert!(keyboard::frame_export_target(&s, &json!({})).is_err());
+}
diff --git a/crates/engine/src/keyboard.rs b/crates/engine/src/keyboard.rs
index d6af66dc3..d8487251c 100644
--- a/crates/engine/src/keyboard.rs
+++ b/crates/engine/src/keyboard.rs
@@ -34,12 +34,13 @@
//! changes the project is one undo step.
use filmcraft_edit as edit;
+pub use filmcraft_export::still::StillFormat;
use filmcraft_geom::Vec2;
use filmcraft_project::{ClipId, ItemKind, ParamValue, Sequence, TrackId, TrackKind};
use filmcraft_time::Tick;
use serde_json::{Value, json};
-use crate::commands::{CommandSpec, always, bad, has_selection, has_seq, item_p, str_p, time_p, with_links};
+use crate::commands::{CommandSpec, always, bad, has_selection, has_seq, item_p, time_p, with_links};
use crate::{EngineError, Result, Session};
type Run = fn(&mut Session, &Value) -> Result<Value>;
@@ -530,39 +531,119 @@ fn sanitize(name: &str) -> String {
name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect()
}
-/// Export Frame: render the Program monitor frame at the playhead to a still image.
+/// A monitor frame captured when Export Frame opens. Export uses original media, never proxies.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FrameExportTarget {
+ pub source: bool,
+ pub item: filmcraft_project::ItemId,
+ pub time: Tick,
+ pub name: String,
+ pub width: u32,
+ pub height: u32,
+}
+
+/// Resolve the requested monitor, item and exact frame without changing either playhead.
+pub fn frame_export_target(s: &Session, p: &Value) -> Result<FrameExportTarget> {
+ const CMD: &str = "file.exportFrame";
+ let source = match p.get("target") {
+ None => false,
+ Some(Value::String(t)) if t == "program" => false,
+ Some(Value::String(t)) if t == "source" => true,
+ _ => return Err(bad(CMD, "target must be source or program")),
+ };
+ let key = if source { "item" } else { "sequence" };
+ let item = match p.get(key) {
+ Some(v) => filmcraft_project::ItemId(v.as_u64().ok_or_else(|| bad(CMD, format!("{key} must be an item id")))?),
+ None => if source { s.state.source_item } else { s.state.active_sequence }
+ .ok_or_else(|| bad(CMD, "open a video clip or sequence in the requested monitor"))?,
+ };
+ let pi = s.project.item(item).ok_or_else(|| bad(CMD, "the requested item is unavailable"))?;
+ let (width, height) = s.project.source_size(item).ok_or_else(|| bad(CMD, "the requested Source clip has no video frame"))?;
+ filmcraft_project::validate_frame_size(width, height).map_err(|e| bad(CMD, e.to_string()))?;
+ let (rate, current, bounds) = if source {
+ let v = crate::clip_ops::source_view(s, item).ok_or_else(|| bad(CMD, "Source clip is unavailable"))?;
+ if v.start.0 < 0 || v.end <= v.start {
+ return Err(bad(CMD, "Source clip has invalid bounds"));
+ }
+ (v.rate, s.state.source_playhead, Some((v.start, v.end)))
+ } else {
+ let q = s.project.sequence(item).ok_or(EngineError::NoSequence)?;
+ (q.settings.frame_rate, s.state.playheads.get(&item).copied().unwrap_or_default(), None)
+ };
+ let requested = match p.get("time") {
+ None => current,
+ Some(v) => Tick(v.as_i64().ok_or_else(|| bad(CMD, "time must be integer ticks"))?),
+ };
+ if rate.num <= 0 || rate.den <= 0 || requested.0 < 0 {
+ return Err(bad(CMD, "frame rate must be positive and time non-negative"));
+ }
+ let invalid = || bad(CMD, "frame time exceeds the supported range");
+ let unit = i128::from(filmcraft_time::TICKS_PER_SECOND).checked_mul(i128::from(rate.den)).ok_or_else(invalid)?;
+ let fd = unit / i128::from(rate.num);
+ if fd <= 0 || fd > i128::from(i64::MAX) {
+ return Err(invalid());
+ }
+ let t = bounds.map(|(a, b)| requested.clamp(a, Tick(b.0.saturating_sub(1)).max(a))).unwrap_or(requested);
+ let frame = i128::from(t.0).checked_mul(i128::from(rate.num)).ok_or_else(invalid)? / unit;
+ let snapped = frame.checked_mul(unit).ok_or_else(invalid)? / i128::from(rate.num);
+ let mut time = Tick(i64::try_from(snapped).map_err(|_| invalid())?);
+ if let Some((a, _)) = bounds {
+ time = time.max(a);
+ }
+ Ok(FrameExportTarget { source, item, time, name: pi.name.clone(), width, height })
+}
+
+/// Export the captured Source or Program frame as a full-resolution SDR still.
fn export_frame(s: &mut Session, p: &Value) -> Result<Value> {
- let fmt = str_p(p, "format").unwrap_or("png").to_ascii_lowercase();
- let format = match fmt.as_str() {
- "png" => filmcraft_export::Format::PngSequence,
- "tif" | "tiff" => filmcraft_export::Format::TiffSequence,
- "bmp" => filmcraft_export::Format::BmpSequence,
- _ => return Err(bad("file.exportFrame", "format must be png, tiff or bmp")),
+ let target = frame_export_target(s, p)?;
+ let fmt = match p.get("format") {
+ None => "png".to_string(),
+ Some(v) => v.as_str().ok_or_else(|| bad("file.exportFrame", "format must be a string"))?.to_ascii_lowercase(),
+ };
+ let format = filmcraft_export::still::StillFormat::parse(&fmt).map_err(|e| bad("file.exportFrame", e.to_string()))?;
+ let depth = match p.get("depth") {
+ None => 8,
+ Some(v) => u8::try_from(v.as_u64().ok_or_else(|| bad("file.exportFrame", "depth must be 8 or 16"))?)
+ .map_err(|_| bad("file.exportFrame", "depth must be 8 or 16"))?,
};
- let ext = if fmt == "tif" { "tiff" } else { fmt.as_str() };
- let seq_name = s.state.active_sequence.and_then(|i| s.project.item(i)).map(|i| i.name.clone()).unwrap_or_else(|| "Sequence".into());
- let path = match str_p(p, "path") {
- Some(path) => path.to_string(),
+ if !matches!(depth, 8 | 16) || (depth == 16 && !format.supports_16()) {
+ return Err(bad("file.exportFrame", "16-bit output requires PNG or TIFF; JPEG and BMP require 8-bit output"));
+ }
+ let import = match p.get("import") {
+ None => false,
+ Some(v) => v.as_bool().ok_or_else(|| bad("file.exportFrame", "import must be true or false"))?,
+ };
+ let ext = format.extension();
+ let path = match p.get("path") {
+ Some(v) => {
+ let path = v.as_str().filter(|v| !v.trim().is_empty()).ok_or_else(|| bad("file.exportFrame", "path must be a non-empty string"))?;
+ crate::export_tools::expand_home(path)
+ }
None => {
- let dir = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|d| d.to_string_lossy().to_string()).unwrap_or_default();
- let base = sanitize(&seq_name);
- let mut n = 1;
- loop {
- let name = format!("{base}.Still{n:03}.{ext}");
- let cand = if dir.is_empty() { name } else { format!("{dir}/{name}") };
- if s.services.file_size(&cand).is_err() || n > 9999 {
- break cand;
- }
- n += 1;
- }
+ let dir = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).unwrap_or_else(|| std::path::Path::new(""));
+ let base = sanitize(&target.name);
+ let candidate =
+ (1..=9999).map(|n| dir.join(format!("{base}.Still{n:03}.{ext}")).to_string_lossy().into_owned()).find(|p| s.services.file_size(p).is_err());
+ candidate.ok_or_else(|| bad("file.exportFrame", "choose a path: all default still names already exist"))?
}
};
- let img = s.render_program(1.0).ok_or(EngineError::NoSequence)?;
- let (w, h) = (img.w as u32, img.h as u32);
- let bytes = filmcraft_export::encode_still(format, img.to_rgba8(), w, h).map_err(|e| EngineError::Other(e.to_string()))?;
+ let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());
+ let img = if target.source {
+ filmcraft_render::render_item(&s.project, target.item, target.time, 1.0, &provider)
+ .ok_or_else(|| bad("file.exportFrame", "cannot decode the Source video frame"))?
+ } else {
+ let opts = filmcraft_render::RenderOptions { scale: 1.0, captions: true, ..Default::default() };
+ filmcraft_render::render_sequence(&s.project, target.item, target.time, opts, &provider)
+ };
+ let (w, h) = (
+ u32::try_from(img.w).map_err(|_| bad("file.exportFrame", "image width exceeds limits"))?,
+ u32::try_from(img.h).map_err(|_| bad("file.exportFrame", "image height exceeds limits"))?,
+ );
+ let bytes = filmcraft_export::still::encode(&img, format, depth).map_err(|e| EngineError::Other(e.to_string()))?;
s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- let mut out = json!({"path": path, "width": w, "height": h});
- if p.get("import").and_then(Value::as_bool).unwrap_or(false) {
+ let mut out =
+ json!({"path": path, "width": w, "height": h, "depth": depth, "target": if target.source { "source" } else { "program" }, "time": target.time.0});
+ if import {
out["import"] = s.execute("file.import", json!({"paths": [path]}))?;
}
s.toast(format!("Exported frame to {path}"));
@@ -704,7 +785,14 @@ pub fn commands() -> Vec<CommandSpec> {
spec("graphics.nudgeDown5", "Nudge Selected Object down by five", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 0.0, 5.0)),
// ---- export frame, poster frame
// Shift+E is Clip > Enable in FilmCraft Default; the Premiere preset moves it here
- spec("file.exportFrame", "Export Frame", None, r#"{"path":str?,"format":"png|tiff|bmp"?,"import":bool?}"#, has_seq, export_frame),
+ spec(
+ "file.exportFrame",
+ "Export Frame",
+ None,
+ r#"{"path":str?,"format":"png|jpeg|tiff|bmp"?,"depth":8|16?,"import":bool?,"target":"source|program"?,"item":id?,"sequence":id?,"time":ticks?}"#,
+ always,
+ export_frame,
+ ),
spec("clip.setPosterFrame", "Set Poster Frame", Some("Cmd+P"), r#"{"item":id?,"time":ticks?}"#, has_poster_target, |s, p| set_poster(s, p, false)),
spec("clip.clearPosterFrame", "Clear Poster Frame", Some("Alt+P"), r#"{"item":id?}"#, has_poster_target, |s, p| set_poster(s, p, true)),
];
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 109abc3ff..df204ac98 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1109,3 +1109,6 @@ mod voiceover_tests;
#[cfg(test)]
mod source_placement_tests;
+
+#[cfg(test)]
+mod frame_export_tests;
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 419a7368c..c35e147cb 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -23,6 +23,7 @@ mod pcm;
mod pipeline;
pub mod presets;
pub mod settings;
+pub mod still;
pub use audio_out::LoudnessReport;
pub use job::{Exporter, Step, stepped};
pub use mxf_out::opatom_audio_paths;
diff --git a/crates/export/src/still.rs b/crates/export/src/still.rs
new file mode 100644
index 000000000..758c523de
--- /dev/null
+++ b/crates/export/src/still.rs
@@ -0,0 +1,137 @@
+//! Single-frame formats and true per-channel depth, separate from sequence export settings.
+use crate::{ExportError, Format, Result};
+use filmcraft_render::Image;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StillFormat {
+ Png,
+ Tiff,
+ Bmp,
+ Jpeg,
+}
+impl StillFormat {
+ pub const ALL: [Self; 4] = [Self::Png, Self::Jpeg, Self::Tiff, Self::Bmp];
+ pub fn parse(name: &str) -> Result<Self> {
+ match name.to_ascii_lowercase().as_str() {
+ "png" => Ok(Self::Png),
+ "tif" | "tiff" => Ok(Self::Tiff),
+ "bmp" => Ok(Self::Bmp),
+ "jpg" | "jpeg" => Ok(Self::Jpeg),
+ _ => Err(ExportError::Unsupported("still format must be png, jpeg, tiff or bmp".into())),
+ }
+ }
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Png => "PNG",
+ Self::Tiff => "TIFF",
+ Self::Bmp => "BMP",
+ Self::Jpeg => "JPEG",
+ }
+ }
+ pub fn extension(self) -> &'static str {
+ match self {
+ Self::Png => "png",
+ Self::Tiff => "tiff",
+ Self::Bmp => "bmp",
+ Self::Jpeg => "jpg",
+ }
+ }
+ pub fn supports_16(self) -> bool {
+ matches!(self, Self::Png | Self::Tiff)
+ }
+}
+
+/// Quantize the original float image directly, never pad an 8-bit image to 16 bits.
+pub fn encode(image: &Image, format: StillFormat, depth: u8) -> Result<Vec<u8>> {
+ if !matches!(depth, 8 | 16) || (depth == 16 && !format.supports_16()) {
+ return Err(ExportError::Unsupported("16-bit stills require PNG or TIFF; JPEG and BMP support 8 bits per channel".into()));
+ }
+ let bad = || ExportError::Encode("invalid still image dimensions or pixel buffer".into());
+ let w = u32::try_from(image.w).map_err(|_| bad())?;
+ let h = u32::try_from(image.h).map_err(|_| bad())?;
+ filmcraft_project::validate_frame_size(w, h).map_err(|_| bad())?;
+ let samples = image.w.checked_mul(image.h).and_then(|n| n.checked_mul(4)).ok_or_else(bad)?;
+ if image.px.len() != samples {
+ return Err(bad());
+ }
+ let err = |e: image::ImageError| ExportError::Encode(e.to_string());
+ if depth == 8 {
+ let rgba = image.to_rgba8();
+ if format == StillFormat::Jpeg {
+ let rgb: Vec<u8> = rgba
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .flat_map(|p| {
+ let [r, g, b, _] = *p;
+ [r, g, b]
+ })
+ .collect();
+ let mut out = Vec::new();
+ image::ImageEncoder::write_image(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95), &rgb, w, h, image::ExtendedColorType::Rgb8)
+ .map_err(err)?;
+ return Ok(out);
+ }
+ let f = match format {
+ StillFormat::Png => Format::PngSequence,
+ StillFormat::Tiff => Format::TiffSequence,
+ _ => Format::BmpSequence,
+ };
+ return crate::encode_still(f, rgba, w, h);
+ }
+ let capacity = samples.checked_mul(2).ok_or_else(bad)?;
+ let mut bytes = Vec::with_capacity(capacity);
+ for pixel in image.px.as_chunks::<4>().0 {
+ let [r, g, b, a] = *pixel;
+ let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 0.0 };
+ let encode_channel = |v: f32| {
+ let v = if a > 0.0 && v.is_finite() { filmcraft_color::linear_to_srgb(v / a).clamp(0.0, 1.0) } else { 0.0 };
+ (v * 65535.0 + 0.5) as u16
+ };
+ for v in [encode_channel(r), encode_channel(g), encode_channel(b), (a * 65535.0 + 0.5) as u16] {
+ bytes.extend_from_slice(&v.to_ne_bytes());
+ }
+ }
+ let mut out = std::io::Cursor::new(Vec::new());
+ match format {
+ StillFormat::Png => {
+ image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &bytes, w, h, image::ExtendedColorType::Rgba16).map_err(err)?
+ }
+ StillFormat::Tiff => {
+ image::ImageEncoder::write_image(image::codecs::tiff::TiffEncoder::new(&mut out), &bytes, w, h, image::ExtendedColorType::Rgba16).map_err(err)?
+ }
+ _ => return Err(ExportError::Unsupported("16-bit still format".into())),
+ }
+ Ok(out.into_inner())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn sixteen_bit_stills_preserve_sub_eight_bit_precision_and_alpha() {
+ let img = Image { w: 2, h: 1, px: vec![0.101, 0.203, 0.307, 1.0, 0.101 / 2.0, 0.203 / 2.0, 0.307 / 2.0, 0.5] };
+ for format in [StillFormat::Png, StillFormat::Tiff] {
+ let bytes = encode(&img, format, 16).unwrap();
+ let decoded = image::load_from_memory(&bytes).unwrap();
+ assert_eq!(decoded.color(), image::ColorType::Rgba16);
+ let px = decoded.to_rgba16();
+ let a = px.get_pixel(0, 0).0;
+ let b = px.get_pixel(1, 0).0;
+ assert_ne!(a[0] % 257, 0, "must not be padded 8-bit values");
+ assert_eq!(&a[..3], &b[..3]);
+ assert_eq!(b[3], 32768);
+ }
+ }
+ #[test]
+ fn jpeg_and_bmp_are_eight_bit_and_invalid_buffers_are_errors() {
+ let image = Image::filled(2, 2, [0.2, 0.3, 0.4, 1.0]);
+ for format in [StillFormat::Jpeg, StillFormat::Bmp] {
+ let bytes = encode(&image, format, 8).unwrap();
+ assert_eq!(image::load_from_memory(&bytes).unwrap().color(), image::ColorType::Rgb8);
+ assert!(encode(&image, format, 16).is_err());
+ }
+ assert!(encode(&Image { w: 2, h: 2, px: vec![] }, StillFormat::Png, 16).is_err());
+ assert!(encode(&image, StillFormat::Png, 12).is_err());
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 73b469383..ddfd9f70f 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -90,6 +90,8 @@ pub struct HostHooks {
pub pick_open_file: Option<Box<dyn FnMut(&str, &[&str]) -> Option<String>>>,
/// Folder picker (Link Media search, proxy and Project Manager destinations).
pub pick_folder: Option<Box<dyn FnMut() -> Option<String>>>,
+ /// Folder picker starting at the current destination (Export Frame).
+ pub pick_folder_at: Option<Box<dyn FnMut(&str) -> Option<String>>>,
/// Pick one file for a command that relinks to it (Link Media ▸ Locate…, Attach Proxies,
/// Reconnect Full Resolution) instead of importing it, as [`Self::pick_files`] does. Native
/// hosts return the path. A host whose picker is asynchronous (the web) returns `None` and
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 103a96aff..67679fe97 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -186,6 +186,15 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut params:
ctx.request_repaint();
return Ok(json!(app.ui.language));
}
+ if id == "file.exportFrame" {
+ if params.get("target").is_none() {
+ let source = targets_source(app, &params);
+ params.as_object_mut().ok_or("command parameters must be an object")?.insert("target".into(), json!(if source { "source" } else { "program" }));
+ }
+ if params.get("path").is_none() {
+ return crate::panels::frame_export::open(app, ctx, &params);
+ }
+ }
if id == "perf.stats" {
// the engine's counters plus playback, frame workers and UI timings
return Ok(crate::perf::stats(app));
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index 46136e79c..da15a7b1b 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -19,6 +19,7 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
crate::panels::voiceover::show(app, ctx);
crate::panels::remix::show(app, ctx);
crate::panels::interchange_export::show(app, ctx);
+ crate::panels::frame_export::show(app, ctx);
crate::panels::project_dialogs::show(app, ctx);
crate::panels::media_browser::dialogs(app, ctx);
let Some(d) = app.dialog else { return };
diff --git a/crates/ui-egui/src/panels/frame_export.rs b/crates/ui-egui/src/panels/frame_export.rs
new file mode 100644
index 000000000..47444a8f4
--- /dev/null
+++ b/crates/ui-egui/src/panels/frame_export.rs
@@ -0,0 +1,235 @@
+//! Monitor Export Frame settings, with captured target/time and a destination folder.
+use crate::{
+ FilmcraftApp,
+ icons::{self, Icon},
+};
+use filmcraft_engine::keyboard::StillFormat;
+use filmcraft_engine::keyboard::{FrameExportTarget, frame_export_target};
+use serde_json::{Value, json};
+
+#[derive(Clone)]
+struct Draft {
+ target: FrameExportTarget,
+ name: String,
+ format: StillFormat,
+ depth: u8,
+ folder: String,
+ import: bool,
+ replace: Option<String>,
+}
+fn draft_id() -> egui::Id {
+ egui::Id::new("frame-export-draft")
+}
+fn clean(name: &str) -> String {
+ name.trim().chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect()
+}
+
+pub fn open(app: &mut FilmcraftApp, ctx: &egui::Context, params: &Value) -> Result<Value, String> {
+ let target = frame_export_target(&app.session, params).map_err(|e| e.to_string())?;
+ if target.source {
+ app.stop_source();
+ } else if app.playback.playing {
+ app.stop();
+ }
+ let folder = ctx.data(|m| m.get_temp::<String>(egui::Id::new("frame-export-folder"))).unwrap_or_else(|| {
+ if cfg!(target_arch = "wasm32") {
+ return "/exports".into();
+ }
+ app.session.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| ".".into())
+ });
+ let name = if target.source { std::path::Path::new(&target.name).file_stem().and_then(|s| s.to_str()).unwrap_or(&target.name) } else { &target.name };
+ let name = clean(name);
+ ctx.data_mut(|m| m.insert_temp(draft_id(), Some(Draft { target, name, format: StillFormat::Png, depth: 8, folder, import: false, replace: None })));
+ ctx.request_repaint();
+ Ok(json!({"dialog":"exportFrame"}))
+}
+
+pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
+ let Some(Some(mut d)) = ctx.data(|m| m.get_temp::<Option<Draft>>(draft_id())) else { return };
+ let mut close = false;
+ let mut apply = false;
+ let mut browse = false;
+ let mut replace = false;
+ let mut elems = Vec::new();
+ let frame = egui::Frame::new().fill(app.tokens.panel_bg).inner_margin(0).corner_radius(6);
+ let position_id = egui::Id::new("frame-export-position");
+ let position = ctx.data(|m| m.get_temp::<egui::Pos2>(position_id));
+ let mut movement = egui::Vec2::ZERO;
+ // Only the custom white header moves the window; form controls keep their own gestures.
+ let window_id = egui::Id::new("frame-export-window");
+ let mut window = egui::Window::new("Export Frame")
+ .id(window_id)
+ .title_bar(false)
+ .movable(false)
+ .collapsible(false)
+ .resizable(false)
+ .frame(frame)
+ .pivot(egui::Align2::CENTER_CENTER)
+ .default_pos(ctx.content_rect().center());
+ if let Some(position) = position {
+ window = window.current_pos(position);
+ }
+ let shown = window.show(ctx, |ui| {
+ ui.set_width(440.0);
+ let (bar, _) = ui.allocate_exact_size(egui::vec2(440.0, 30.0), egui::Sense::hover());
+ ui.painter().rect_filled(bar, egui::CornerRadius { nw: 6, ne: 6, sw: 0, se: 0 }, egui::Color32::WHITE);
+ ui.painter().text(
+ bar.left_center() + egui::vec2(10.0, 0.0),
+ egui::Align2::LEFT_CENTER,
+ "Export Frame",
+ egui::FontId::proportional(13.0),
+ egui::Color32::from_gray(90),
+ );
+ let x = egui::Rect::from_center_size(bar.right_center() - egui::vec2(16.0, 0.0), egui::vec2(24.0, 24.0));
+ let header = egui::Rect::from_min_max(bar.min, egui::pos2(x.left(), bar.bottom()));
+ let drag = ui.interact(header, egui::Id::new("export-frame-header"), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab);
+ if drag.dragged() {
+ movement = drag.drag_delta();
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
+ }
+ elems.push(("exportFrame.header".into(), header, "Move Export Frame".into()));
+ let response = ui.interact(x, egui::Id::new("export-frame-close"), egui::Sense::click()).on_hover_text("Close");
+ icons::paint(ui.painter(), x.shrink(7.0), Icon::Close, egui::Color32::from_gray(90));
+ elems.push(("exportFrame.close".to_string(), x, "Close".to_string()));
+ close = response.clicked();
+ egui::Frame::NONE.inner_margin(14).show(ui, |ui| {
+ egui::Grid::new("frame-export-settings").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| {
+ ui.label("Name:");
+ let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(300.0));
+ elems.push(("exportFrame.name".into(), r.rect, d.name.clone()));
+ ui.end_row();
+ ui.label("Format:");
+ let combo = egui::ComboBox::from_id_salt("frame-export-format").width(292.0).selected_text(d.format.label()).show_ui(ui, |ui| {
+ for format in StillFormat::ALL {
+ let r = ui.selectable_value(&mut d.format, format, format.label());
+ elems.push((format!("exportFrame.format.{}", format.extension()), r.rect, format.label().into()));
+ }
+ });
+ elems.push(("exportFrame.format".into(), combo.response.rect, d.format.label().into()));
+ ui.end_row();
+ if !d.format.supports_16() {
+ d.depth = 8;
+ }
+ ui.label("Depth:");
+ let combo = egui::ComboBox::from_id_salt("frame-export-depth").width(292.0).selected_text(format!("{} Bit", d.depth)).show_ui(ui, |ui| {
+ for bits in [8, 16] {
+ let r = ui.add_enabled(bits == 8 || d.format.supports_16(), egui::Button::selectable(d.depth == bits, format!("{bits} Bit")));
+ if r.clicked() {
+ d.depth = bits;
+ }
+ elems.push((format!("exportFrame.depth.{bits}"), r.rect, format!("{bits} Bit")));
+ }
+ });
+ elems.push(("exportFrame.depth".into(), combo.response.rect, format!("{} Bit", d.depth)));
+ ui.end_row();
+ ui.label("Path:");
+ let r = ui.add(egui::TextEdit::singleline(&mut d.folder).desired_width(300.0));
+ elems.push(("exportFrame.path".into(), r.rect, d.folder.clone()));
+ ui.end_row();
+ });
+ ui.add_space(12.0);
+ ui.horizontal(|ui| {
+ let r = ui.checkbox(&mut d.import, "Import into project");
+ elems.push(("exportFrame.import".into(), r.rect, d.import.to_string()));
+ ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 26.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let r = ui.add_enabled(app.hooks.pick_folder_at.is_some() || app.hooks.pick_folder.is_some(), egui::Button::new("Browse…"));
+ browse = r.clicked();
+ elems.push(("exportFrame.browse".into(), r.rect, "Browse".into()));
+ });
+ });
+ ui.add_space(12.0);
+ if let Some(path) = d.replace.clone() {
+ ui.label(format!("This file already exists: {path}"));
+ ui.horizontal(|ui| {
+ let r = ui.button("Replace");
+ replace = r.clicked();
+ elems.push(("exportFrame.replace".into(), r.rect, "Replace".into()));
+ let r = ui.button("Keep existing file");
+ if r.clicked() {
+ d.replace = None;
+ }
+ elems.push(("exportFrame.keep".into(), r.rect, "Keep existing file".into()));
+ });
+ } else {
+ ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 26.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let r = ui.button("Cancel");
+ close |= r.clicked();
+ elems.push(("exportFrame.cancel".into(), r.rect, "Cancel".into()));
+ let r = ui.add_enabled(
+ !d.name.trim().is_empty() && !d.folder.trim().is_empty(),
+ egui::Button::new(egui::RichText::new("OK").color(egui::Color32::WHITE)).fill(app.tokens.accent),
+ );
+ apply = r.clicked();
+ elems.push(("exportFrame.export".into(), r.rect, "OK".into()));
+ });
+ }
+ ui.add_space(12.0);
+ ui.separator();
+ ui.label(format!("{} — {} × {}", if d.target.source { "Source" } else { "Program" }, d.target.width, d.target.height));
+ ui.label(&d.target.name);
+ ui.label(format!("Frame time: {:.3} seconds", d.target.time.seconds()));
+ });
+ });
+ if shown.is_some() && movement != egui::Vec2::ZERO {
+ // Keep the unrounded requested pivot between drag frames so subpixel deltas cannot accumulate rounding drift.
+ if let Some(pivot) = position.or_else(|| egui::containers::AreaState::load(ctx, window_id).and_then(|state| state.pivot_pos)) {
+ ctx.data_mut(|m| m.insert_temp(position_id, pivot + movement));
+ }
+ ctx.request_repaint();
+ }
+ for (id, rect, label) in elems {
+ app.auto.add(&id, rect, &label);
+ }
+ close |= ctx.input(|i| i.key_pressed(egui::Key::Escape));
+ if browse && !close {
+ let folder = filmcraft_engine::export_tools::expand_home(d.folder.trim());
+ let picked = match app.hooks.pick_folder_at.as_mut() {
+ Some(pick) => pick(&folder),
+ None => app.hooks.pick_folder.as_mut().and_then(|pick| pick()),
+ };
+ if let Some(path) = picked {
+ d.folder = path;
+ d.replace = None;
+ }
+ }
+ if (apply || replace) && !close {
+ let mut stem = clean(&d.name);
+ let lower = stem.to_ascii_lowercase();
+ for suffix in [".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp"] {
+ if lower.ends_with(suffix) {
+ stem.truncate(stem.len().saturating_sub(suffix.len()));
+ break;
+ }
+ }
+ let ext = d.format.extension();
+ let suffix = format!(".{ext}");
+ let name = if stem.to_ascii_lowercase().ends_with(&suffix) { stem } else { format!("{stem}{suffix}") };
+ let folder = filmcraft_engine::export_tools::expand_home(d.folder.trim());
+ let path = std::path::Path::new(&folder).join(name).to_string_lossy().into_owned();
+ let allowed = match app.session.services.file_size(&path) {
+ Ok(_) => replace && d.replace.as_deref() == Some(path.as_str()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
+ Err(e) => {
+ app.ui.status = format!("Cannot check export destination: {e}");
+ false
+ }
+ };
+ if !allowed && app.session.services.file_size(&path).is_ok() {
+ d.replace = Some(path.clone());
+ }
+ if allowed {
+ let mut params =
+ json!({"path":path,"format":ext,"depth":d.depth,"import":d.import,"target":if d.target.source{"source"}else{"program"},"time":d.target.time.0});
+ params[if d.target.source { "item" } else { "sequence" }] = json!(d.target.item.0);
+ match app.session.execute("file.exportFrame", params) {
+ Ok(result) => {
+ app.ui.status = format!("Exported frame to {}", result["path"].as_str().unwrap_or_default());
+ ctx.data_mut(|m| m.insert_temp(egui::Id::new("frame-export-folder"), d.folder.clone()));
+ close = true;
+ }
+ Err(e) => app.ui.status = e.to_string(),
+ }
+ }
+ }
+ ctx.data_mut(|m| m.insert_temp(draft_id(), if close { None } else { Some(d) }));
+}
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 6fc2b0b41..dbd514d9f 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -11,6 +11,7 @@ pub mod essential_sound;
pub mod events;
pub mod export_mode;
pub mod file_dialogs;
+pub mod frame_export;
pub mod graphics;
pub mod graphics_templates;
pub mod import_mode;
diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rs
index 9c6bb1261..3f7a7fc0a 100644
--- a/crates/ui-egui/src/panels/monitor.rs
+++ b/crates/ui-egui/src/panels/monitor.rs
@@ -538,7 +538,7 @@ fn transport(app: &mut FilmcraftApp, ui: &mut egui::Ui, row: Rect, which: Which)
(Icon::GoToOut, "src.goOut", "Go to Out (Shift+O)"),
(Icon::Insert, "source.insert", "Insert (,)"),
(Icon::Overwrite, "source.overwrite", "Overwrite (.)"),
- (Icon::Camera, "exportFrame", "Export Frame (Shift+E)"),
+ (Icon::Camera, "exportFrame", "Export Frame"),
(Icon::Proxy, "media.toggleProxies", "Toggle Proxies"),
]
} else {
@@ -553,7 +553,7 @@ fn transport(app: &mut FilmcraftApp, ui: &mut egui::Ui, row: Rect, which: Which)
(Icon::GoToOut, "markers.goToOut", "Go to Out (Shift+O)"),
(Icon::Lift, "sequence.lift", "Lift (;)"),
(Icon::Extract, "sequence.extract", "Extract (')"),
- (Icon::Camera, "exportFrame", "Export Frame (Shift+E)"),
+ (Icon::Camera, "exportFrame", "Export Frame"),
(Icon::Proxy, "media.toggleProxies", "Toggle Proxies"),
]
};
@@ -589,10 +589,7 @@ fn transport(app: &mut FilmcraftApp, ui: &mut egui::Ui, row: Rect, which: Which)
Ok(serde_json::Value::Null)
}
- "exportFrame" => {
- app.ui.status = "Export Frame: use Export mode (M6)".into();
- Ok(serde_json::Value::Null)
- }
+ "exportFrame" => crate::menus::invoke(app, &ctx, "file.exportFrame", json!({"monitor": if src { "source" } else { "program" }})),
c => crate::menus::invoke(app, &ctx, c, json!({"monitor": if src { "source" } else { "program" }})),
};
if let Err(e) = r {
diff --git a/crates/ui-egui/tests/frame_export_ui.rs b/crates/ui-egui/tests/frame_export_ui.rs
new file mode 100644
index 000000000..47c9a8d71
--- /dev/null
+++ b/crates/ui-egui/tests/frame_export_ui.rs
@@ -0,0 +1,224 @@
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_time::{FrameRate, Tick};
+use filmcraft_ui_egui::{FilmcraftApp, dock::PanelKind, menus};
+use serde_json::json;
+use std::sync::{Arc, Mutex};
+
+fn step(h: &mut Harness<'static, FilmcraftApp>) {
+ let ctx = h.ctx.clone();
+ let mut raw = std::mem::take(h.input_mut());
+ eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw);
+ *h.input_mut() = raw;
+ ctx.request_repaint();
+ h.step();
+}
+fn harness() -> Harness<'static, FilmcraftApp> {
+ let mut s = Session::default();
+ s.execute("file.newSequence", json!({"name":"Program clip","width":128,"height":72,"fps":24})).unwrap();
+ let item = filmcraft_engine::demo::add_generator(
+ Arc::make_mut(&mut s.project),
+ &s.media,
+ filmcraft_media::generators::GeneratorSource::new(
+ filmcraft_media::Generator::Demo(filmcraft_media::DemoScene::Aurora),
+ 128,
+ 72,
+ FrameRate::FPS_24,
+ Tick::from_seconds_f64(5.0),
+ ),
+ "Source clip",
+ filmcraft_project::Label::Iris,
+ None,
+ );
+ s.execute("source.open", json!({"item":item.0})).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).build_eframe(move |_cc| FilmcraftApp::new(s));
+ for _ in 0..3 {
+ step(&mut h);
+ }
+ h
+}
+fn click(h: &mut Harness<'static, FilmcraftApp>, id: &str) {
+ fn center(h: &Harness<'static, FilmcraftApp>, id: &str) -> egui::Pos2 {
+ let e = h.state().auto.elements.iter().find(|e| e.id == id).or_else(|| h.state().auto.find(id)).unwrap_or_else(|| {
+ panic!(
+ "missing {id}; available {:?}",
+ h.state().auto.elements.iter().filter(|e| e.id.starts_with("exportFrame")).map(|e| (&e.id, &e.rect, &e.label)).collect::<Vec<_>>()
+ )
+ });
+ let [x, y, w, height] = e.rect;
+ egui::pos2(x + w / 2.0, y + height / 2.0)
+ }
+ step(h);
+ let pos = center(h, id);
+ h.input_mut().events.push(egui::Event::PointerMoved(pos));
+ step(h);
+ let pos = center(h, id);
+ h.input_mut().events.push(egui::Event::PointerMoved(pos));
+ for pressed in [true, false] {
+ h.input_mut().events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
+ step(h);
+ }
+ step(h);
+}
+fn has(h: &Harness<'static, FilmcraftApp>, id: &str) -> bool {
+ h.state().auto.elements.iter().any(|e| e.id == id)
+}
+
+#[test]
+fn both_camera_buttons_open_the_dialog_and_cancel_writes_nothing() {
+ for monitor in ["source", "program"] {
+ let mut h = harness();
+ let saves = Arc::new(Mutex::new(0));
+ let saved = saves.clone();
+ h.state_mut().hooks.pick_save_as = Some(Box::new(move |_, _, _| {
+ *saved.lock().unwrap() += 1;
+ None
+ }));
+ click(&mut h, &format!("{monitor}.transport.exportFrame"));
+ assert!(has(&h, "exportFrame.name"), "{monitor}: {}", h.state().ui.status);
+ let top = h.state().auto.elements.iter().find(|e| e.id == "exportFrame.close").unwrap().rect[1];
+ let bottom = h.state().auto.elements.iter().find(|e| e.id == "exportFrame.export").unwrap().rect[1];
+ assert!(top >= 0.0 && bottom - top < 350.0, "dialog must stay compact and on screen: {top}..{bottom}");
+ click(&mut h, "exportFrame.cancel");
+ step(&mut h);
+ assert!(!has(&h, "exportFrame.name"));
+ assert_eq!(*saves.lock().unwrap(), 0);
+ }
+}
+
+#[test]
+fn program_export_ignores_source_focus_and_imports_the_saved_still() {
+ let mut h = harness();
+ h.state_mut().ui.focused = PanelKind::Source;
+ let folder = std::env::temp_dir().join(format!("fc-program-frame-ui-{}", std::process::id()));
+ std::fs::create_dir_all(&folder).unwrap();
+ let path = folder.join("Program clip.bmp");
+ let out = folder.clone();
+ h.state_mut().hooks.pick_folder = Some(Box::new(move || Some(out.to_string_lossy().into_owned())));
+ let ctx = h.ctx.clone();
+ menus::invoke(h.state_mut(), &ctx, "file.exportFrame", json!({"monitor":"program"})).unwrap();
+ step(&mut h);
+ let before = h.state().session.project.items.len();
+ click(&mut h, "exportFrame.format");
+ click(&mut h, "exportFrame.format.bmp");
+ click(&mut h, "exportFrame.browse");
+ click(&mut h, "exportFrame.import");
+ click(&mut h, "exportFrame.export");
+ assert!(path.exists(), "{}", h.state().ui.status);
+ assert_eq!(h.state().session.project.items.len(), before + 1);
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(i32::from_le_bytes(bytes[18..22].try_into().unwrap()), 128);
+ assert_eq!(i32::from_le_bytes(bytes[22..26].try_into().unwrap()).abs(), 72);
+ assert!(!has(&h, "exportFrame.name"));
+ drop(h);
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_dir(folder).unwrap();
+}
+
+#[test]
+fn focused_source_command_captures_the_frame_and_save_cancel_keeps_the_dialog() {
+ let mut h = harness();
+ h.state_mut().ui.focused = PanelKind::Source;
+ h.state_mut().session.state.source_playhead = FrameRate::FPS_24.tick_of(12);
+ let expected_path = std::env::temp_dir().join(format!("fc-source-frame-ui-{}.expected.png", std::process::id()));
+ h.state_mut().session.execute("file.exportFrame", json!({"target":"source","path":expected_path.to_string_lossy()})).unwrap();
+ let expected = std::fs::read(&expected_path).unwrap();
+ std::fs::remove_file(expected_path).unwrap();
+ let ctx = h.ctx.clone();
+ menus::invoke(h.state_mut(), &ctx, "file.exportFrame", json!({})).unwrap();
+ step(&mut h);
+ h.state_mut().session.state.source_playhead = Tick::ZERO;
+ h.state_mut().hooks.pick_folder = Some(Box::new(|| None));
+ click(&mut h, "exportFrame.browse");
+ assert!(has(&h, "exportFrame.name"));
+ let folder = std::env::temp_dir().join(format!("fc-source-frame-ui-{}", std::process::id()));
+ std::fs::create_dir_all(&folder).unwrap();
+ let path = folder.join("Source clip.png");
+ let out = folder.clone();
+ h.state_mut().hooks.pick_folder = Some(Box::new(move || Some(out.to_string_lossy().into_owned())));
+ click(&mut h, "exportFrame.browse");
+ click(&mut h, "exportFrame.export");
+ assert!(path.exists(), "{}", h.state().ui.status);
+ assert_eq!(h.state().session.state.source_playhead, Tick::ZERO);
+ assert_eq!(std::fs::read(&path).unwrap(), expected, "the dialog must export its captured frame");
+ drop(h);
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_dir(folder).unwrap();
+}
+
+#[test]
+fn depth_dropdown_is_format_aware_and_existing_files_require_confirmation() {
+ let mut h = harness();
+ let ctx = h.ctx.clone();
+ menus::invoke(h.state_mut(), &ctx, "file.exportFrame", json!({"monitor":"source"})).unwrap();
+ step(&mut h);
+ click(&mut h, "exportFrame.depth");
+ click(&mut h, "exportFrame.depth.16");
+ let folder = std::env::temp_dir().join(format!("fc-frame-depth-ui-{}", std::process::id()));
+ std::fs::create_dir_all(&folder).unwrap();
+ let path = folder.join("Source clip.png");
+ std::fs::write(&path, b"keep me").unwrap();
+ let out = folder.clone();
+ h.state_mut().hooks.pick_folder = Some(Box::new(move || Some(out.to_string_lossy().into_owned())));
+ click(&mut h, "exportFrame.browse");
+ click(&mut h, "exportFrame.export");
+ assert!(has(&h, "exportFrame.replace"));
+ assert_eq!(std::fs::read(&path).unwrap(), b"keep me");
+ click(&mut h, "exportFrame.replace");
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(bytes[24], 16);
+ menus::invoke(h.state_mut(), &ctx, "file.exportFrame", json!({"monitor":"source"})).unwrap();
+ step(&mut h);
+ click(&mut h, "exportFrame.format");
+ click(&mut h, "exportFrame.format.jpg");
+ click(&mut h, "exportFrame.depth");
+ click(&mut h, "exportFrame.depth.16");
+ assert!(h.state().auto.elements.iter().any(|e| e.id == "exportFrame.depth" && e.label == "8 Bit"));
+ drop(h);
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_dir(folder).unwrap();
+}
+
+#[test]
+fn white_header_moves_both_dialogs_and_controls_still_work() {
+ for monitor in ["source", "program"] {
+ let mut h = harness();
+ click(&mut h, &format!("{monitor}.transport.exportFrame"));
+ step(&mut h);
+ let header = h.state().auto.elements.iter().find(|e| e.id == "exportFrame.header").unwrap().rect;
+ let name = h.state().auto.elements.iter().find(|e| e.id == "exportFrame.name").unwrap().label.clone();
+ assert_eq!(name, if monitor == "source" { "Source clip" } else { "Program clip" });
+ let from = egui::pos2(header[0] + header[2] / 2.0, header[1] + header[3] / 2.0);
+ h.input_mut().events.push(egui::Event::PointerMoved(from));
+ step(&mut h);
+ h.input_mut().events.push(egui::Event::PointerButton {
+ pos: from,
+ button: egui::PointerButton::Primary,
+ pressed: true,
+ modifiers: egui::Modifiers::NONE,
+ });
+ step(&mut h);
+ for i in 1..=8 {
+ let offset = egui::vec2(15.0 * i as f32, 7.5 * i as f32);
+ h.input_mut().events.push(egui::Event::PointerMoved(from + offset));
+ step(&mut h);
+ }
+ let to = from + egui::vec2(120.0, 60.0);
+ h.input_mut().events.push(egui::Event::PointerButton {
+ pos: to,
+ button: egui::PointerButton::Primary,
+ pressed: false,
+ modifiers: egui::Modifiers::NONE,
+ });
+ step(&mut h);
+ step(&mut h);
+ let moved = h.state().auto.elements.iter().find(|e| e.id == "exportFrame.header").unwrap().rect;
+ assert!((moved[0] - header[0] - 120.0).abs() < 2.0 && (moved[1] - header[1] - 60.0).abs() < 2.0, "{monitor}: {header:?} -> {moved:?}");
+ assert_eq!(h.state().auto.elements.iter().find(|e| e.id == "exportFrame.name").unwrap().label, name);
+ click(&mut h, "exportFrame.format");
+ click(&mut h, "exportFrame.format.bmp");
+ assert_eq!(h.state().auto.elements.iter().find(|e| e.id == "exportFrame.format").unwrap().label, "BMP");
+ click(&mut h, "exportFrame.close");
+ assert!(!has(&h, "exportFrame.name"));
+ }
+}
diff --git a/docs/monitors.md b/docs/monitors.md
index 989aae9bd..2952304ca 100644
--- a/docs/monitors.md
+++ b/docs/monitors.md
@@ -120,3 +120,29 @@ playhead-blue color and translucent gray band. Runtime review remains Windows-on
The playhead has drag priority above the range band and trim handles, including a full-span
selection. Drag it to scrub; the unoccupied upper ruler can also scrub. Drag the gray band away
from the playhead to translate the marked range.
+
+## Export Frame
+
+The camera button in either monitor opens Export Frame. Drag its white header to move the dialog.
+The suggested name is the source filename without its extension, or the sequence name, without an added `.Still` suffix. Choose a name, format and depth,
+use Browse to choose the destination folder (or edit Path), and click OK. Existing files require
+an explicit Replace confirmation. Cancel and the header close button write nothing. The white
+header and dark body use original generic controls. Source details and frame time appear below
+the settings. The last successful folder is reused during the current app session.
+
+PNG and TIFF support 8 or 16 bits per channel. The 16-bit path quantizes directly from the
+float image, preserving precision beyond 8 bits. JPEG (quality 95) and BMP support 8-bit output;
+choosing either resets Depth to 8 Bit and disables 16 Bit. The command rejects unsupported
+format/depth combinations. In the browser the still is offered as a download. Import into project
+adds the saved still as one undoable edit. Failed writes retain the settings and report an error.
+
+The monitor, item and frame time are captured when the settings open. Export uses the original
+full-resolution media, even with proxies or reduced preview resolution enabled. Source exports
+the source picture at its media playhead; Program exports the sequence composite, effects and
+captions at its timeline playhead. Audio-only Source clips have no picture to export.
+
+The shared `file.exportFrame` command accepts `target: "source" | "program"` (Program by default),
+`format: "png" | "jpeg" | "tiff" | "bmp"`, `depth: 8 | 16` (default 8),
+optional `item` for Source or `sequence` for Program, and an exact integer `time` in ticks.
+Supplying `path` executes directly; invoking it through the UI without a path opens settings,
+routed to the focused monitor unless an explicit monitor/target is provided.