FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Media: Automatically refresh growing files works (and catches re-renders)
Katta72d3fe1b974
diff --git a/ROADMAP.md b/ROADMAP.mdindex bd80f88bf..f3865ea02 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -159,6 +159,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining## Log+- **2026-10-10 (changed media):** Settings ▸ Media ▸ Automatically refresh growing files works: media files that change on disk while the project is open (a recording still being written, a render written over the file a clip uses) are read again every *Refresh growing files every* seconds and as soon as the window comes back to the front: the new length, picture and identity, without an undo step (`media.refreshChanged`, `media_watch`).- **2026-10-08 (Source range dragging):** implicit full-clip In/Out, video-only/audio-only/linked both controls, picture/waveform drag gestures and one-command undoable timeline placement. Shared Source/Program draggable frame-bounded handles and range translation, cancellation, Source marker/navigation routing and marked-range playback/looping.- **2026-10-08 (Source playback):** normal forward playback for video/audio media and subclips in the Source monitor, an independent Source clock, Play/Pause and focused Space, frame stepping, device-clock audio with wall-clock fallback, seeking, and end-of-clip stopping. Windows desktop review verified a real video file and standalone WAV, including In/Out marking. Reverse/shuttle Source playback and source sequences remain unsupported; no parity percentage changed.- **2026-10-08 (night):** HDR H.265 (HEVC Main 10, PQ and HLG, BT.2020, limited range) export on Windows through NVENC (#30): an HDR sequence now exports as real 10-bit HDR (`rgbf_to_yuv420_10` into P010 input buffers; VUI BT.2020 + PQ / HLG; the HDR10 mastering-display and content-light messages as SEI on every IDR for PQ, through the generic SEI payload array because NVENC 12.1 has no mastering-display field; `colr` / `mdcv` / `clli` in the sample entry), where the GPU reports 10-bit HEVC (new `register_hdr_probe` / `hdr_available` in the export crate; elsewhere, and on macOS, HDR sequences still tone-map to 8-bit SDR HEVC, and `settings.sdr` forces that). ffprobe reads `hevc` / `Main 10` / `hvc1` / `yuv420p10le` / `bt2020` / `smpte2084` or `arib-std-b67` / `bt2020nc` / `tv` with the mastering-display and content-light side data for PQ; ffmpeg's decode equals ours code for code; the in-process round trip is at 71.1 dB luma PSNR on the 10-bit scale with 803 distinct levels on a ramp and the peak code 940 intact (RTX 5060). 8-bit SDR H.265 is unchanged.diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 26df0e699..13b482270 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -27,6 +27,7 @@ mod marker_export;pub mod masks;pub mod media_browser;pub mod media_pool;+pub mod media_watch;pub mod mixer;pub mod multicam;pub mod panels;@@ -382,6 +383,11 @@ pub struct Session {pub browser: media_browser::BrowserState,/// Nesting depth of [`Session::execute`] (commands that run other commands).exec_depth: u32,+ /// Each media file's size and modification time when last seen (Settings ▸ Media ▸+ /// Automatically refresh growing files, [`media_watch`]).+ pub media_stamps: std::collections::HashMap<String, media_watch::Stamp>,+ /// The stamps being taken on a worker thread ([`Session::start_media_scan`]).+ pub media_scan: Option<media_watch::MediaScan>,}/// An export advanced a batch at a time on the host's thread ([`Session::pump_jobs`]).@@ -469,6 +475,8 @@ impl Session {log: Default::default(),browser: Default::default(),exec_depth: 0,+ media_stamps: Default::default(),+ media_scan: None,}}@@ -1065,6 +1073,8 @@ mod media_browser_tests;#[cfg(test)]mod media_test_util;#[cfg(test)]+mod media_watch_tests;+#[cfg(test)]mod mixer_tests;#[cfg(test)]mod multicam_tests;diff --git a/crates/engine/src/media_watch.rs b/crates/engine/src/media_watch.rsnew file mode 100644index 000000000..b951f1f40--- /dev/null+++ b/crates/engine/src/media_watch.rs@@ -0,0 +1,169 @@+//! Settings ▸ Media ▸ Automatically refresh growing files: media files that change on disk while+//! the project is open are read again, whether they are still being written (a recording, an+//! ingest) or were replaced (a render from EffectCraft or After Effects written over the file a+//! clip uses).+//!+//! Each file media item's file is compared by size and modification time with what it was when+//! last seen. The desktop app takes the stamps every *Refresh growing files every* seconds and as+//! soon as its window comes back to the front, on a worker thread so a file on a slow network share+//! never holds up the interface ([`Session::start_media_scan`], [`Session::poll_media_scan`]);+//! `media.refreshChanged` takes them on the spot (CLI, agents).+//!+//! Refreshing opens the file again: the item gets the file's new [`MediaInfo`] (a longer+//! duration, another frame size) and identity (so relinking compares against the new file), the+//! media pool swaps in the new source (the old one still indexes the file as it was), and the+//! view is refreshed without an undo step or modifying a clean project ([`Session::bump_view`]):+//! the file changed, not the edit. A file seen for the first time is only remembered; one that+//! can't be opened yet keeps its old stamp, so the next look tries again.+//!+//! [`MediaInfo`]: filmcraft_media::MediaInfo++use std::collections::{BTreeSet, HashMap};+use std::sync::{Arc, Mutex, PoisonError};++use filmcraft_project::{ItemId, ItemKind, MediaRef, Project};+use serde_json::{Value, json};++use crate::{Result, Session};++/// A file's size and modification time (nanoseconds since 1970).+pub type Stamp = (u64, u128);++/// Stamps of the project's media files taken on a worker thread.+pub type MediaScan = Arc<Mutex<Option<Vec<(String, Option<Stamp>)>>>>;++#[cfg(not(target_arch = "wasm32"))]+fn stamp(path: &str) -> Option<Stamp> {+ let meta = std::fs::metadata(path).ok()?;+ let modified = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;+ Some((meta.len(), modified.as_nanos()))+}++#[cfg(target_arch = "wasm32")]+fn stamp(_: &str) -> Option<Stamp> {+ None+}++/// The files of `p`'s file media items (made-offline ones aside).+pub fn media_files(p: &Project) -> BTreeSet<String> {+ p.items+ .values()+ .filter_map(|i| match &i.kind {+ ItemKind::Media(m) if !m.offline => match &m.media {+ MediaRef::File { path } => Some(path.clone()),+ _ => None,+ },+ _ => None,+ })+ .collect()+}++/// `media.refreshChanged`: stamp the project's media files now and read the changed ones again.+pub(crate) fn refresh_changed(s: &mut Session, _: &Value) -> Result<Value> {+ let now = media_files(&s.project).into_iter().map(|p| (p.clone(), stamp(&p))).collect();+ s.apply_media_stamps(now)+}++impl Session {+ /// Start stamping the project's media files on a worker thread, unless a look is still+ /// running (or the build has no files to look at: the web app).+ pub fn start_media_scan(&mut self) {+ if self.media_scan.is_some() || cfg!(target_arch = "wasm32") {+ return;+ }+ let files = media_files(&self.project);+ if files.is_empty() {+ return;+ }+ let slot: MediaScan = Arc::default();+ let out = slot.clone();+ let spawned = std::thread::Builder::new().name("media-watch".into()).spawn(move || {+ let stamps = files.into_iter().map(|p| (p.clone(), stamp(&p))).collect();+ *out.lock().unwrap_or_else(PoisonError::into_inner) = Some(stamps);+ });+ if spawned.is_ok() {+ self.media_scan = Some(slot);+ }+ }++ /// Apply a finished look (`None` while there is none, or it is still running).+ pub fn poll_media_scan(&mut self) -> Option<Result<Value>> {+ let stamps = self.media_scan.as_ref()?.lock().unwrap_or_else(PoisonError::into_inner).take()?;+ self.media_scan = None;+ Some(self.apply_media_stamps(stamps))+ }++ /// Compare the media files' stamps with the ones last seen and read the changed files+ /// again. Returns `{refreshed: [item ids]}`.+ fn apply_media_stamps(&mut self, now: Vec<(String, Option<Stamp>)>) -> Result<Value> {+ // Only the files the project uses now are remembered.+ let before: HashMap<String, Stamp> = std::mem::take(&mut self.media_stamps);+ let mut changed = BTreeSet::new();+ for (path, stamp) in now {+ match (before.get(&path), stamp) {+ // Not there right now (an app saving by delete and rename): keep the last stamp.+ (Some(old), None) => {+ self.media_stamps.insert(path, *old);+ }+ (old, Some(new)) => {+ if old.is_some_and(|o| *o != new) {+ changed.insert(path.clone());+ }+ self.media_stamps.insert(path, new);+ }+ (None, None) => {}+ }+ }+ if changed.is_empty() {+ return Ok(json!({"refreshed": []}));+ }+ let mut fresh = Vec::new();+ let mut failed = BTreeSet::new();+ for (id, it) in &self.project.items {+ let Some(m) = it.as_media().filter(|m| !m.offline) else { continue };+ let MediaRef::File { path } = &m.media else { continue };+ if !changed.contains(path) || failed.contains(path) {+ continue;+ }+ // Opened the way import opens it, so the info is what a new import would get.+ match self.media.open_file(path, &*self.services) {+ Ok(src) => {+ let mut info = src.info().clone();+ if info.kind == filmcraft_media::MediaKind::Still+ && let Some(v) = info.video.as_mut()+ {+ v.frame_rate = crate::settings::timebase_rate(&self.prefs.media.indeterminate_timebase);+ }+ let identity = crate::relink::identity_of(&*self.services, path).ok();+ fresh.push((*id, path.clone(), info, identity, src));+ }+ Err(_) => {+ failed.insert(path.clone());+ }+ }+ }+ // Not readable yet (still being written): the next look tries again.+ for path in &failed {+ if let Some(old) = before.get(path) {+ self.media_stamps.insert(path.clone(), *old);+ }+ }+ if fresh.is_empty() {+ return Ok(json!({"refreshed": []}));+ }+ let p = Arc::make_mut(&mut self.project);+ let mut refreshed: Vec<ItemId> = Vec::new();+ for (id, path, info, identity, src) in fresh {+ if let Some(m) = p.item_mut(id).and_then(|i| i.as_media_mut()) {+ m.info = info;+ if identity.is_some() {+ m.identity = identity;+ }+ }+ self.media.insert_file(id, &path, src);+ refreshed.push(id);+ }+ self.bump_view();+ Ok(json!({"refreshed": refreshed.iter().map(|i| i.0).collect::<Vec<_>>()}))+ }+}diff --git a/crates/engine/src/media_watch_tests.rs b/crates/engine/src/media_watch_tests.rsnew file mode 100644index 000000000..44c9b409e--- /dev/null+++ b/crates/engine/src/media_watch_tests.rs@@ -0,0 +1,100 @@+//! Media files changing on disk while the project is open (Settings ▸ Media ▸ Automatically+//! refresh growing files, `media_watch`): a re-rendered movie is read again (new length, new+//! picture, new identity) without an undo step, a file still being written is tried again, and+//! the background look does the same.++use filmcraft_media::DemoScene;+use serde_json::json;++use crate::Session;+use crate::media_test_util::{frame_rgba, make_movie, psnr, session_with, tmp_dir};++const W: u32 = 160;+const H: u32 = 90;++/// Write a movie over `path` so its modification time moves even on coarse file systems.+fn rerender(path: &std::path::Path, scene: DemoScene, frames: i64) {+ std::thread::sleep(std::time::Duration::from_millis(30));+ make_movie(path, scene, W, H, frames);+}++fn refresh(s: &mut Session) -> serde_json::Value {+ s.execute("media.refreshChanged", json!({})).unwrap()+}++/// What frame 3 of a fresh import of `scene` looks like.+fn reference(name: &str, scene: DemoScene, frames: i64) -> Vec<u8> {+ let root = tmp_dir(name);+ let f = root.join("ref.mov");+ make_movie(&f, scene, W, H, frames);+ let (mut r, _, _) = session_with(&[&f]);+ frame_rgba(&mut r, 3, 1.0).2+}++#[test]+fn a_rerendered_movie_is_read_again_without_an_undo_step() {+ let root = tmp_dir("watch-rerender");+ let a = root.join("a.mov");+ make_movie(&a, DemoScene::Aurora, W, H, 12);+ let (mut s, items, _) = session_with(&[&a]);+ let item = items[0];+ let before = frame_rgba(&mut s, 3, 1.0).2;+ let length = s.project.item(item).unwrap().duration();+ s.saved_revision = s.revision;+ let undo = s.history.undo.len();+ // First look: remembered, nothing to read.+ assert_eq!(refresh(&mut s), json!({"refreshed": []}));+ rerender(&a, DemoScene::CityNight, 24);+ assert_eq!(refresh(&mut s), json!({"refreshed": [item.0]}));+ let m = s.project.item(item).unwrap().as_media().unwrap().clone();+ assert_eq!(m.info.duration.0, length.0 * 2, "the new length");+ assert_eq!(m.identity, crate::relink::identity_of(&*s.services, &a.to_string_lossy()).ok(), "relinking compares with the new file");+ let after = frame_rgba(&mut s, 3, 1.0).2;+ assert!(psnr(&after, &reference("watch-rerender-ref", DemoScene::CityNight, 24)) > 40.0, "the new picture");+ assert!(psnr(&after, &before) < 30.0, "not the old one");+ assert_eq!(s.history.undo.len(), undo, "the file changed, not the edit");+ assert!(!s.is_dirty());+ assert_eq!(refresh(&mut s), json!({"refreshed": []}), "acted on once");+}++#[test]+fn a_file_still_being_written_is_tried_again() {+ let root = tmp_dir("watch-partial");+ let a = root.join("a.mov");+ make_movie(&a, DemoScene::Aurora, W, H, 12);+ let (mut s, items, _) = session_with(&[&a]);+ refresh(&mut s);+ // The other app has only written the start of the file so far.+ let full = root.join("full.mov");+ make_movie(&full, DemoScene::CityNight, W, H, 24);+ let bytes = std::fs::read(&full).unwrap();+ std::thread::sleep(std::time::Duration::from_millis(30));+ std::fs::write(&a, &bytes[..64]).unwrap();+ assert_eq!(refresh(&mut s), json!({"refreshed": []}));+ std::thread::sleep(std::time::Duration::from_millis(30));+ std::fs::write(&a, &bytes).unwrap();+ assert_eq!(refresh(&mut s), json!({"refreshed": [items[0].0]}));+}++#[test]+fn a_background_look_reads_changed_media_again() {+ let root = tmp_dir("watch-scan");+ let a = root.join("a.mov");+ make_movie(&a, DemoScene::Aurora, W, H, 12);+ let (mut s, items, _) = session_with(&[&a]);+ let look = |s: &mut Session| {+ s.start_media_scan();+ let t0 = std::time::Instant::now();+ loop {+ if let Some(r) = s.poll_media_scan() {+ return r.unwrap();+ }+ assert!(t0.elapsed().as_secs() < 10, "the look never finished");+ std::thread::yield_now();+ }+ };+ assert_eq!(look(&mut s), json!({"refreshed": []}));+ rerender(&a, DemoScene::CityNight, 24);+ assert_eq!(look(&mut s), json!({"refreshed": [items[0].0]}));+ assert!(s.media_scan.is_none());+}diff --git a/crates/engine/src/relink.rs b/crates/engine/src/relink.rsindex 7037404ab..95c8a7efa 100644--- a/crates/engine/src/relink.rs+++ b/crates/engine/src/relink.rs@@ -653,6 +653,16 @@ pub fn commands() -> Vec<CommandSpec> {run: relink,journal: true,},+ CommandSpec {+ id: "media.refreshChanged",+ label: "Refresh Changed Media",+ menu: &[],+ shortcut: None,+ params: "{}",+ enabled: always,+ run: crate::media_watch::refresh_changed,+ journal: true,+ },CommandSpec {id: "media.replaceFootage",label: "Replace Footage…",diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rsindex 2f020835f..10db5c873 100644--- a/crates/engine/src/settings.rs+++ b/crates/engine/src/settings.rs@@ -964,9 +964,9 @@ static CATEGORIES: &[Category] = &[Row::Group("Growing Files",&[- b("media.refreshGrowingFiles", "Automatically refresh growing files", false),+ b("media.refreshGrowingFiles", "Automatically refresh growing files", true),b("media.resumeGrowingPlayback", "Automatically resume playback for growing files in Source Monitor", false),- sub("media.growingRefreshSeconds", "Refresh growing Files Every", int(1.0, 3600.0, "seconds"), "media.refreshGrowingFiles", false),+ sub("media.growingRefreshSeconds", "Refresh growing Files Every", int(1.0, 3600.0, "seconds"), "media.refreshGrowingFiles", true),],),b("media.hardwareDecoding", "Enable hardware accelerated decoding (requires restart)", false),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d5437e972..f3cf83c34 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1384,6 +1384,41 @@ impl FilmcraftApp {// ---------------------------------------------------------------- frame+ /// Settings ▸ Media ▸ Automatically refresh growing files: every *Refresh growing files every*+ /// seconds, and as soon as the window comes back to the front (after a render in another app),+ /// stamp the project's media files on a worker thread and read the changed ones again+ /// ([`filmcraft_engine::media_watch`]).+ #[cfg(not(target_arch = "wasm32"))]+ fn tick_media_refresh(&mut self, ctx: &egui::Context) {+ if let Some(r) = self.session.poll_media_scan() {+ match r {+ Ok(r) => {+ if let Some(n) = r["refreshed"].as_array().map(Vec::len).filter(|n| *n > 0) {+ self.toast = Some((format!("Refreshed {n} media item(s) changed on disk"), ctx.input(|i| i.time)));+ }+ }+ Err(e) => self.toast = Some((e.to_string(), ctx.input(|i| i.time))),+ }+ }+ let media = &self.session.prefs.media;+ let (on, every) = (media.refresh_growing_files, f64::from(media.growing_refresh_seconds.max(1)));+ let (last_key, focus_key) = (egui::Id::new("mediaWatch.lastScan"), egui::Id::new("mediaWatch.focused"));+ let now = ctx.input(|i| i.time);+ let focused = ctx.input(|i| i.focused);+ let was_focused: bool = ctx.data(|d| d.get_temp(focus_key)).unwrap_or(focused);+ ctx.data_mut(|d| d.insert_temp(focus_key, focused));+ if !on || filmcraft_engine::media_watch::media_files(&self.session.project).is_empty() {+ return;+ }+ let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(f64::NEG_INFINITY);+ if now - last >= every || (focused && !was_focused) {+ ctx.data_mut(|d| d.insert_temp(last_key, now));+ self.session.start_media_scan();+ }+ let wait = if self.session.media_scan.is_some() { 0.1 } else { (every - (now - last)).clamp(0.1, every) };+ ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));+ }+fn frame(&mut self, ui: &mut egui::Ui) {i18n::set_current(self.ui.language);if std::mem::take(&mut self.panic_next_frame) {@@ -1400,6 +1435,8 @@ impl FilmcraftApp {}self.sync_pool();self.apply_prefs(&ctx);+ #[cfg(not(target_arch = "wasm32"))]+ self.tick_media_refresh(&ctx);for ev in self.session.drain_events() {match ev {filmcraft_engine::Event::OpenSequence(_) => {