Skip to content

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

M11.1: .fcproj schema versioning + migrations, atomic saves

Brandon Thomasba4a04e03151
diff --git a/Cargo.lock b/Cargo.lock
index 845fb6db1..e0909a1b0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1396,6 +1396,7 @@ dependencies = [
"filmcraft-color",
"filmcraft-edit",
"filmcraft-export",
+ "filmcraft-format",
"filmcraft-frame",
"filmcraft-geom",
"filmcraft-interchange",
@@ -1430,6 +1431,18 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "filmcraft-format"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-media",
+ "filmcraft-project",
+ "filmcraft-time",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "filmcraft-frame"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index ee4bf1a35..d36e1fa8e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -33,6 +33,7 @@ filmcraft-interchange = { path = "crates/interchange" }
filmcraft-render = { path = "crates/render" }
filmcraft-gpu = { path = "crates/gpu" }
filmcraft-export = { path = "crates/export" }
+filmcraft-format = { path = "crates/format" }
filmcraft-engine = { path = "crates/engine" }
filmcraft-ui-egui = { path = "crates/ui-egui" }
filmcraft-automation = { path = "crates/automation" }
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 90c329c11..a4b6c3260 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -20,6 +20,7 @@ filmcraft-project = { workspace = true }
filmcraft-edit = { workspace = true }
filmcraft-render = { workspace = true }
filmcraft-export = { workspace = true }
+filmcraft-format = { workspace = true }
filmcraft-interchange = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 956dd8ca9..d24eef678 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -65,6 +65,9 @@ fn has_edit_points(s: &Session) -> std::result::Result<(), String> {
if s.state.edit_points.is_empty() { Err("no edit points selected".into()) } else { Ok(()) }
}
+fn has_saved_path(s: &Session) -> std::result::Result<(), String> {
+ if s.path.is_some() { Ok(()) } else { Err("the project has not been saved yet".into()) }
+}
fn has_seq(s: &Session) -> std::result::Result<(), String> {
s.active_sequence().map(|_| ()).ok_or_else(|| "no sequence is open".into())
}
@@ -547,36 +550,29 @@ fn build() -> Vec<CommandSpec> {
}),
cmd!("file.save", "Save", ["File"], Some("Cmd+S"), r#"{"path":str?}"#, always, |s, p| {
let path = str_p(p, "path").map(str::to_string).or_else(|| s.path.clone()).ok_or_else(|| bad("file.save", "no path (use Save As)"))?;
- let data = s.project.to_json();
- s.services.write_file(&path, data.as_bytes()).map_err(|e| EngineError::Other(e.to_string()))?;
- s.path = Some(path.clone());
- s.saved_revision = s.revision;
- Ok(json!({"path": path}))
+ write_project(s, &path, true)
}),
cmd!("file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), r#"{"path":str}"#, always, |s, p| {
let path = str_p(p, "path").ok_or_else(|| bad("file.saveAs", "need `path`"))?.to_string();
- s.services.write_file(&path, s.project.to_json().as_bytes()).map_err(|e| EngineError::Other(e.to_string()))?;
- s.path = Some(path.clone());
- s.saved_revision = s.revision;
- Ok(json!({"path": path}))
+ write_project(s, &path, true)
+ }),
+ cmd!("file.saveCopy", "Save a Copy…", ["File"], Some("Cmd+Alt+S"), r#"{"path":str}"#, always, |s, p| {
+ let path = str_p(p, "path").ok_or_else(|| bad("file.saveCopy", "need `path`"))?.to_string();
+ write_project(s, &path, false)
+ }),
+ cmd!("file.revert", "Revert", ["File"], None, "{}", has_saved_path, |s, _| {
+ let path = s.path.clone().ok_or_else(|| bad("file.revert", "project was never saved"))?;
+ let keep = s.state.active_sequence;
+ let r = open_project(s, &path)?;
+ if let Some(k) = keep.filter(|k| s.project.sequence(*k).is_some()) {
+ s.state.active_sequence = Some(k);
+ s.state.open_sequences = vec![k];
+ }
+ Ok(r)
}),
cmd!("file.open", "Open Project…", ["File"], Some("Cmd+O"), r#"{"path":str}"#, always, |s, p| {
let path = str_p(p, "path").ok_or_else(|| bad("file.open", "need `path`"))?.to_string();
- let bytes = s.services.read_file(&path).map_err(|e| EngineError::Other(e.to_string()))?;
- let proj = filmcraft_project::Project::from_json(&String::from_utf8_lossy(&bytes)).map_err(EngineError::Other)?;
- s.media = std::sync::Arc::new(crate::MediaPool::default());
- let first = proj.sequences().next().map(|i| i.id);
- s.project = std::sync::Arc::new(proj);
- s.history = Default::default();
- s.history.limit = 200;
- s.state = crate::Session::default().state;
- s.state.active_sequence = first;
- s.state.open_sequences = first.into_iter().collect();
- s.path = Some(path);
- s.revision += 1;
- s.saved_revision = s.revision;
- s.events.push(crate::Event::ProjectChanged { revision: s.revision });
- Ok(Value::Null)
+ open_project(s, &path)
}),
cmd!(
"file.exportMedia",
@@ -2111,3 +2107,66 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
pub fn secs(s: f64) -> Tick {
Tick((s * TICKS_PER_SECOND as f64).round() as i64)
}
+
+// ---------- project files ----------
+
+/// Serialize the project in the current schema and write it (atomically) to `path`. `adopt` =
+/// Save / Save As (the file becomes the project's path and the project is clean); otherwise Save a
+/// Copy. The first save over a file upgraded from an older schema keeps the original as
+/// `<name> (schema vN backup).fcproj`.
+fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
+ let t0 = std::time::Instant::now();
+ let bytes = filmcraft_format::encode(&s.project, false);
+ let mut backup = None;
+ if adopt && s.path.as_deref() == Some(path) && s.loaded_schema < filmcraft_format::SCHEMA_VERSION {
+ let b = schema_backup_path(path, s.loaded_schema);
+ if s.services.read_file(&b).is_err()
+ && let Ok(old) = s.services.read_file(path)
+ {
+ s.services.write_file(&b, &old).map_err(|e| EngineError::Other(format!("{b}: {e}")))?;
+ backup = Some(b);
+ }
+ }
+ s.services.write_file(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ if adopt {
+ s.path = Some(path.to_string());
+ s.saved_revision = s.revision;
+ s.loaded_schema = filmcraft_format::SCHEMA_VERSION;
+ }
+ Ok(json!({"path": path, "bytes": bytes.len(), "ms": t0.elapsed().as_secs_f64() * 1000.0, "backup": backup}))
+}
+
+fn schema_backup_path(path: &str, schema: u32) -> String {
+ let stem = path.strip_suffix(".fcproj").unwrap_or(path);
+ format!("{stem} (schema v{schema} backup).fcproj")
+}
+
+/// Make `proj` the session's project (fresh history, media pool and editor state).
+fn install_project(s: &mut Session, proj: filmcraft_project::Project, path: Option<String>, clean: bool) {
+ s.media = std::sync::Arc::new(crate::MediaPool::default());
+ let first = proj.sequences().next().map(|i| i.id);
+ s.project = std::sync::Arc::new(proj);
+ s.history = Default::default();
+ s.history.limit = 200;
+ s.state = crate::Session::default().state;
+ s.state.active_sequence = first;
+ s.state.open_sequences = first.into_iter().collect();
+ s.path = path;
+ s.revision += 1;
+ // A recovered project is unsaved: its saved revision is one that never existed.
+ s.saved_revision = if clean { s.revision } else { 0 };
+ s.loaded_schema = filmcraft_format::SCHEMA_VERSION;
+ s.events.push(crate::Event::ProjectChanged { revision: s.revision });
+}
+
+fn open_project(s: &mut Session, path: &str) -> Result<Value> {
+ let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ let loaded = filmcraft_format::decode(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ let (from, migrated) = (loaded.schema_version, loaded.migrated());
+ install_project(s, loaded.project, Some(path.to_string()), true);
+ s.loaded_schema = from;
+ if migrated {
+ s.toast(format!("Upgraded project from schema v{from} to v{}; the original is kept as a backup when you save", filmcraft_format::SCHEMA_VERSION));
+ }
+ Ok(json!({"path": path, "schemaVersion": from, "migrated": migrated}))
+}
diff --git a/crates/engine/src/file_tests.rs b/crates/engine/src/file_tests.rs
new file mode 100644
index 000000000..8466183c6
--- /dev/null
+++ b/crates/engine/src/file_tests.rs
@@ -0,0 +1,77 @@
+//! `.fcproj` save/open through the command interface: schema envelope, legacy upgrade, Save a Copy,
+//! Revert.
+
+use super::*;
+use serde_json::json;
+
+fn demo() -> Session {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s
+}
+
+fn temp_dir(tag: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("fc-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+#[test]
+fn saved_file_is_versioned_and_save_copy_keeps_state() {
+ let d = temp_dir("schema");
+ let path = d.join("p.fcproj").to_string_lossy().to_string();
+ let mut s = demo();
+ s.execute("file.saveAs", json!({"path": path})).unwrap();
+ let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(v["schema_version"], filmcraft_format::SCHEMA_VERSION);
+ assert_eq!(v["format"], "filmcraft.project");
+ s.execute("sequence.addEdit", json!({"seconds": 1.0})).unwrap();
+ assert!(s.is_dirty());
+ let copy = d.join("copy.fcproj").to_string_lossy().to_string();
+ s.execute("file.saveCopy", json!({"path": copy})).unwrap();
+ assert!(s.is_dirty(), "Save a Copy leaves the project unsaved");
+ assert_eq!(s.path.as_deref(), Some(path.as_str()));
+ let mut t = Session::default();
+ t.execute("file.open", json!({"path": copy})).unwrap();
+ assert_eq!(*t.project, *s.project);
+ // Revert discards the edit.
+ s.execute("file.revert", json!({})).unwrap();
+ assert!(!s.is_dirty());
+ assert_ne!(*t.project, *s.project);
+ assert!(!Session::default().is_enabled("file.revert"), "nothing to revert to before a save");
+ // No temp files left next to the project.
+ let stray: Vec<_> = std::fs::read_dir(&d).unwrap().filter_map(|e| e.ok()).filter(|e| e.file_name().to_string_lossy().ends_with(".tmp")).collect();
+ assert!(stray.is_empty());
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+#[test]
+fn legacy_project_opens_and_first_save_keeps_a_backup() {
+ let d = temp_dir("legacy");
+ let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../format/tests/fixtures/v1-edit.fcproj");
+ let path = d.join("old.fcproj");
+ std::fs::copy(&fixture, &path).unwrap();
+ let p = path.to_string_lossy().to_string();
+ let mut s = Session::default();
+ let r = s.execute("file.open", json!({"path": p})).unwrap();
+ assert_eq!(r["schemaVersion"], 1);
+ assert_eq!(r["migrated"], true);
+ assert_eq!(s.project.name, "Legacy Edit");
+ assert!(s.drain_events().iter().any(|e| matches!(e, Event::Toast { message, .. } if message.contains("Upgraded"))));
+ let r = s.execute("file.save", json!({})).unwrap();
+ let backup = r["backup"].as_str().unwrap().to_string();
+ assert!(backup.ends_with("old (schema v1 backup).fcproj"), "{backup}");
+ assert_eq!(std::fs::read(&backup).unwrap(), std::fs::read(&fixture).unwrap());
+ let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(v["schema_version"], filmcraft_format::SCHEMA_VERSION);
+ // Second save: no new backup.
+ assert!(s.execute("file.save", json!({})).unwrap()["backup"].is_null());
+ // A file from the future is refused clearly.
+ let mut v = v;
+ v["schema_version"] = json!(filmcraft_format::SCHEMA_VERSION + 1);
+ std::fs::write(&path, serde_json::to_vec(&v).unwrap()).unwrap();
+ let e = Session::default().execute("file.open", json!({"path": p})).unwrap_err().to_string();
+ assert!(e.contains("newer version of FilmCraft"), "{e}");
+ let _ = std::fs::remove_dir_all(&d);
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index afab02fb2..11d528190 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -62,10 +62,8 @@ impl Services for FsServices {
std::fs::read(path)
}
fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
- // Atomic save: write a sibling temp file then rename over the target.
- let tmp = format!("{path}.fcsave~");
- std::fs::write(&tmp, data)?;
- std::fs::rename(&tmp, path)
+ // Atomic + durable: temp file in the same directory, fsync, rename, fsync the directory.
+ filmcraft_format::atomic_write(std::path::Path::new(path), data)
}
}
@@ -148,6 +146,9 @@ pub struct Session {
pub journal: Vec<(String, Value)>,
/// Background jobs (exports, …).
pub jobs: Vec<Job>,
+ /// Schema version of the file at `path` as found on disk (older = upgraded on load; the first
+ /// save over it keeps a backup of the original).
+ pub loaded_schema: u32,
}
/// A background job with shared progress.
@@ -202,6 +203,7 @@ impl Session {
events: Vec::new(),
journal: Vec::new(),
jobs: Vec::new(),
+ loaded_schema: filmcraft_format::SCHEMA_VERSION,
}
}
@@ -380,5 +382,7 @@ pub fn media_duration(p: &Project, _pool: &MediaPool, id: ItemId) -> Option<Tick
}
}
+#[cfg(test)]
+mod file_tests;
#[cfg(test)]
mod tests;
diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml
new file mode 100644
index 000000000..cb8140ce6
--- /dev/null
+++ b/crates/format/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "filmcraft-format"
+description = "FilmCraft .fcproj files: schema versions + migrations, atomic saves, auto-save naming and rotation"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-project = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-media = { workspace = true }
diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs
new file mode 100644
index 000000000..312710877
--- /dev/null
+++ b/crates/format/src/atomic.rs
@@ -0,0 +1,99 @@
+//! Crash-safe file replacement.
+
+use std::fs::{self, File, OpenOptions};
+use std::io::{self, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+
+static COUNTER: AtomicU64 = AtomicU64::new(0);
+
+/// The temp file a save of `path` goes through (same directory, so the rename never crosses file
+/// systems). Hidden, and unique per process and call.
+fn temp_path(path: &Path) -> PathBuf {
+ let dir = parent_dir(path);
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "project".into());
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
+ dir.join(format!(".{name}.{}-{n}.tmp", std::process::id()))
+}
+
+fn parent_dir(path: &Path) -> PathBuf {
+ match path.parent() {
+ Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
+ _ => PathBuf::from("."),
+ }
+}
+
+/// Replace `path` with `data` atomically and durably:
+/// write `data` to a temp file in the same directory, `fsync` it, rename it over `path`, then
+/// `fsync` the directory so the rename itself survives a power cut. If anything fails the temp file
+/// is removed and `path` is untouched.
+pub fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> {
+ let tmp = temp_path(path);
+ let r = (|| {
+ let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
+ f.write_all(data)?;
+ f.sync_all()?;
+ drop(f);
+ fs::rename(&tmp, path)
+ })();
+ if let Err(e) = r {
+ let _ = fs::remove_file(&tmp);
+ return Err(e);
+ }
+ sync_dir(&parent_dir(path));
+ Ok(())
+}
+
+/// Best-effort directory fsync (persists the rename on POSIX; not possible on Windows, where
+/// `MoveFileEx` with write-through semantics is already durable enough).
+fn sync_dir(dir: &Path) {
+ if let Ok(d) = File::open(dir) {
+ let _ = d.sync_all();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tmpdir(tag: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("filmcraft-atomic-{tag}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&d);
+ fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn replaces_and_leaves_no_temp_files() {
+ let d = tmpdir("replace");
+ let p = d.join("a.fcproj");
+ atomic_write(&p, b"one").unwrap();
+ atomic_write(&p, b"two").unwrap();
+ assert_eq!(fs::read(&p).unwrap(), b"two");
+ let names: Vec<_> = fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name()).collect();
+ assert_eq!(names.len(), 1, "{names:?}");
+ fs::remove_dir_all(&d).unwrap();
+ }
+
+ #[test]
+ fn failed_write_keeps_old_file() {
+ let d = tmpdir("fail");
+ let p = d.join("a.fcproj");
+ atomic_write(&p, b"good").unwrap();
+ // Renaming a file over a non-empty directory fails: the original target must survive.
+ let dir_target = d.join("sub");
+ fs::create_dir_all(dir_target.join("x")).unwrap();
+ assert!(atomic_write(&dir_target, b"bad").is_err());
+ assert_eq!(fs::read(&p).unwrap(), b"good");
+ let tmp_left = fs::read_dir(&d).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".tmp")).count();
+ assert_eq!(tmp_left, 0);
+ fs::remove_dir_all(&d).unwrap();
+ }
+
+ #[test]
+ fn missing_directory_is_an_error() {
+ let d = tmpdir("missing");
+ assert!(atomic_write(&d.join("nope/a.fcproj"), b"x").is_err());
+ fs::remove_dir_all(&d).unwrap();
+ }
+}
diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs
new file mode 100644
index 000000000..4608c1061
--- /dev/null
+++ b/crates/format/src/autosave.rs
@@ -0,0 +1,154 @@
+//! Auto-save file naming and rotation (Premiere behaviour).
+//!
+//! Auto-saves go to an `Auto-Save` folder next to the project, named
+//! `<project name>-YYYY-MM-DD_HH-MM-SS.fcproj` (local wall-clock time). After each write the oldest
+//! files of that project beyond the "Maximum Project Versions" limit are deleted. Only files whose
+//! name is exactly `<name>-<timestamp>.fcproj` are ever touched.
+
+use std::fs;
+use std::io;
+use std::path::{Path, PathBuf};
+
+/// The folder name used next to a project.
+pub const AUTO_SAVE_DIR: &str = "Auto-Save";
+
+/// `Auto-Save` folder for a project file.
+pub fn auto_save_dir(project_path: &Path) -> PathBuf {
+ project_path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")).join(AUTO_SAVE_DIR)
+}
+
+/// A file-name-safe version of a project name (path separators and control characters replaced).
+pub fn file_stem(name: &str) -> String {
+ let s: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() { '_' } else { c }).collect();
+ let s = s.trim().trim_matches('.').to_string();
+ if s.is_empty() { "Untitled".into() } else { s }
+}
+
+/// Civil date-time (proleptic Gregorian) of a unix timestamp shifted by `offset_secs`.
+pub fn civil(unix: i64, offset_secs: i32) -> (i64, u32, u32, u32, u32, u32) {
+ let t = unix + offset_secs as i64;
+ let days = t.div_euclid(86_400);
+ let secs = t.rem_euclid(86_400);
+ // Howard Hinnant's days_from_civil inverse.
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z.rem_euclid(146_097);
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let y = yoe + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
+ let y = if m <= 2 { y + 1 } else { y };
+ (y, m, d, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
+}
+
+/// `YYYY-MM-DD_HH-MM-SS` (the auto-save file-name stamp).
+pub fn timestamp(unix: i64, offset_secs: i32) -> String {
+ let (y, mo, d, h, mi, s) = civil(unix, offset_secs);
+ format!("{y:04}-{mo:02}-{d:02}_{h:02}-{mi:02}-{s:02}")
+}
+
+/// `YYYY-MM-DD HH:MM:SS` for display.
+pub fn display_time(unix: i64, offset_secs: i32) -> String {
+ let (y, mo, d, h, mi, s) = civil(unix, offset_secs);
+ format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}:{s:02}")
+}
+
+/// `<stem>-YYYY-MM-DD_HH-MM-SS.fcproj`.
+pub fn auto_save_name(name: &str, unix: i64, offset_secs: i32) -> String {
+ format!("{}-{}.fcproj", file_stem(name), timestamp(unix, offset_secs))
+}
+
+fn is_stamp(s: &str) -> bool {
+ let b = s.as_bytes();
+ b.len() == 19
+ && b.iter().enumerate().all(|(i, c)| match i {
+ 4 | 7 | 13 | 16 => *c == b'-',
+ 10 => *c == b'_',
+ _ => c.is_ascii_digit(),
+ })
+}
+
+/// Auto-saves of project `name` in `dir`, oldest first.
+pub fn list_auto_saves(dir: &Path, name: &str) -> Vec<PathBuf> {
+ let prefix = format!("{}-", file_stem(name));
+ let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
+ let mut v: Vec<(String, PathBuf)> = rd
+ .filter_map(|e| e.ok())
+ .filter_map(|e| {
+ let f = e.file_name().to_string_lossy().into_owned();
+ let stamp = f.strip_prefix(&prefix)?.strip_suffix(".fcproj")?;
+ is_stamp(stamp).then(|| (stamp.to_string(), e.path()))
+ })
+ .collect();
+ v.sort();
+ v.into_iter().map(|(_, p)| p).collect()
+}
+
+/// Delete the oldest auto-saves of `name` so at most `max` remain. Returns the deleted paths.
+pub fn rotate(dir: &Path, name: &str, max: usize) -> io::Result<Vec<PathBuf>> {
+ let all = list_auto_saves(dir, name);
+ let n = all.len().saturating_sub(max.max(1));
+ let mut gone = Vec::new();
+ for p in all.into_iter().take(n) {
+ fs::remove_file(&p)?;
+ gone.push(p);
+ }
+ Ok(gone)
+}
+
+/// Write one auto-save (atomically) into `dir` and rotate. Returns the new file.
+pub fn write_auto_save(dir: &Path, name: &str, unix: i64, offset_secs: i32, data: &[u8], max: usize) -> io::Result<PathBuf> {
+ fs::create_dir_all(dir)?;
+ let path = dir.join(auto_save_name(name, unix, offset_secs));
+ crate::atomic_write(&path, data)?;
+ rotate(dir, name, max)?;
+ Ok(path)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn civil_dates() {
+ assert_eq!(timestamp(0, 0), "1970-01-01_00-00-00");
+ // 2026-09-30 13:45:07 UTC
+ assert_eq!(timestamp(1_790_775_907, 0), "2026-09-30_13-45-07");
+ assert_eq!(timestamp(1_790_775_907, 2 * 3600), "2026-09-30_15-45-07");
+ assert_eq!(timestamp(1_790_775_907, -14 * 3600), "2026-09-29_23-45-07");
+ assert_eq!(display_time(951_782_400, 0), "2000-02-29 00:00:00");
+ assert_eq!(timestamp(-1, 0), "1969-12-31_23-59-59");
+ }
+
+ #[test]
+ fn names_and_stems() {
+ assert_eq!(auto_save_name("My Film", 0, 0), "My Film-1970-01-01_00-00-00.fcproj");
+ assert_eq!(file_stem("a/b:c"), "a_b_c");
+ assert_eq!(file_stem(" "), "Untitled");
+ assert_eq!(auto_save_dir(Path::new("/x/y/p.fcproj")), Path::new("/x/y/Auto-Save"));
+ }
+
+ #[test]
+ fn rotation_keeps_newest_and_ignores_other_files() {
+ let d = std::env::temp_dir().join(format!("filmcraft-rotate-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&d);
+ for i in 0..7 {
+ write_auto_save(&d, "Cut", 1_790_000_000 + i * 60, 0, b"{}", 5).unwrap();
+ }
+ // Another project whose name starts with the same prefix, and an unrelated file.
+ fs::write(d.join("Cut-Two-2026-01-01_00-00-00.fcproj"), b"{}").unwrap();
+ fs::write(d.join("notes.txt"), b"keep").unwrap();
+ let left = list_auto_saves(&d, "Cut");
+ assert_eq!(left.len(), 5);
+ assert!(left[0].to_string_lossy().ends_with(&format!("Cut-{}.fcproj", timestamp(1_790_000_120, 0))));
+ assert!(left[4].to_string_lossy().ends_with(&format!("Cut-{}.fcproj", timestamp(1_790_000_360, 0))));
+ assert_eq!(list_auto_saves(&d, "Cut-Two").len(), 1);
+ assert!(d.join("notes.txt").exists());
+ rotate(&d, "Cut", 2).unwrap();
+ assert_eq!(list_auto_saves(&d, "Cut").len(), 2);
+ assert_eq!(list_auto_saves(&d, "Cut-Two").len(), 1);
+ fs::remove_dir_all(&d).unwrap();
+ }
+}
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
new file mode 100644
index 000000000..912322dbd
--- /dev/null
+++ b/crates/format/src/lib.rs
@@ -0,0 +1,282 @@
+//! `.fcproj` project files.
+//!
+//! A project file is UTF-8 JSON with an explicit schema version:
+//!
+//! ```json
+//! { "format": "filmcraft.project", "schema_version": 2, "generator": "FilmCraft 0.1.0", "project": { … } }
+//! ```
+//!
+//! - **Versioning.** [`SCHEMA_VERSION`] is the version this build writes. Older files are upgraded on
+//! load by a chain of single-step migrations ([`MIGRATIONS`]: v1→v2, v2→v3, …) operating on the
+//! JSON document, so every historical shape only needs one small function. Newer files are refused
+//! with [`FormatError::TooNew`] instead of being half-read (and later overwritten with data loss).
+//! - **Atomic saves.** [`atomic_write`] writes a temp file in the destination directory, fsyncs it,
+//! renames it over the target and fsyncs the directory: a crash or power cut during a save leaves
+//! either the old file or the new one, never a torn mix.
+//! - **Auto-save naming/rotation** lives in [`autosave`] (`<name>-YYYY-MM-DD_HH-MM-SS.fcproj` in an
+//! `Auto-Save` folder next to the project, oldest pruned beyond the version limit).
+//!
+//! Schema history:
+//! - **v1** (M0–M11): the bare serialized `Project` object with a `"version": 1` field.
+//! - **v2** (M11.1): the envelope above; `Project.version` dropped (the envelope carries it).
+
+pub mod atomic;
+pub mod autosave;
+
+use filmcraft_project::Project;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+pub use atomic::atomic_write;
+
+/// The `format` tag written in every envelope.
+pub const FORMAT_ID: &str = "filmcraft.project";
+
+/// A migration upgrades a whole document from schema `n` to `n + 1`.
+pub type Migration = fn(Value) -> Result<Value, String>;
+
+/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never
+/// edit a shipped one.
+pub const MIGRATIONS: &[Migration] = &[v1_to_v2];
+
+/// The schema version this build writes (and the newest it reads).
+pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1;
+
+/// Oldest schema this build can still upgrade.
+pub const OLDEST_SCHEMA: u32 = 1;
+
+#[derive(Debug, thiserror::Error)]
+pub enum FormatError {
+ #[error("not a FilmCraft project: {0}")]
+ NotAProject(String),
+ #[error(
+ "this project was saved by a newer version of FilmCraft (project schema v{found}); this build reads up to v{supported}. Update FilmCraft to open it."
+ )]
+ TooNew { found: u32, supported: u32 },
+ #[error("project schema v{found} is too old for this build (oldest supported: v{oldest})")]
+ TooOld { found: u32, oldest: u32 },
+ #[error("upgrading project from schema v{from} to v{}: {msg}", from + 1)]
+ Migration { from: u32, msg: String },
+ #[error("project file is damaged: {0}")]
+ Corrupt(String),
+}
+
+/// A project read from disk.
+#[derive(Debug)]
+pub struct Loaded {
+ pub project: Project,
+ /// Schema version found in the file (before migration).
+ pub schema_version: u32,
+ /// The `generator` string of the writer, if recorded.
+ pub generator: Option<String>,
+}
+
+impl Loaded {
+ /// True when the file was written in an older schema and upgraded on load.
+ pub fn migrated(&self) -> bool {
+ self.schema_version < SCHEMA_VERSION
+ }
+}
+
+/// Writer identification stored in the envelope.
+pub fn generator() -> String {
+ format!("FilmCraft {}", env!("CARGO_PKG_VERSION"))
+}
+
+#[derive(Serialize)]
+struct EnvelopeOut<'a> {
+ format: &'static str,
+ schema_version: u32,
+ generator: String,
+ project: &'a Project,
+}
+
+#[derive(Deserialize)]
+struct EnvelopeIn {
+ #[serde(default)]
+ generator: Option<String>,
+ project: Project,
+}
+
+/// Just enough of a document to know which schema it is.
+#[derive(Deserialize)]
+struct Probe {
+ #[serde(default)]
+ format: Option<String>,
+ #[serde(default)]
+ schema_version: Option<u32>,
+ /// v1: bare project with `version`.
+ #[serde(default)]
+ version: Option<u32>,
+ #[serde(default)]
+ items: Option<serde::de::IgnoredAny>,
+ #[serde(default)]
+ root: Option<serde::de::IgnoredAny>,
+}
+
+/// Serialize a project in the current schema. `pretty` = indented (human-diffable; used for the
+/// project file itself), compact otherwise (recovery snapshots).
+pub fn encode(project: &Project, pretty: bool) -> Vec<u8> {
+ let env = EnvelopeOut { format: FORMAT_ID, schema_version: SCHEMA_VERSION, generator: generator(), project };
+ let r = if pretty { serde_json::to_vec_pretty(&env) } else { serde_json::to_vec(&env) };
+ // Serializing plain data (string keys, finite numbers or null) cannot fail.
+ r.unwrap_or_default()
+}
+
+/// Detect the schema version of a parsed document.
+pub fn detect_version(doc: &Value) -> Result<u32, FormatError> {
+ let probe: Probe = serde_json::from_value(doc.clone()).map_err(|e| FormatError::NotAProject(e.to_string()))?;
+ probe_version(&probe)
+}
+
+fn probe_version(p: &Probe) -> Result<u32, FormatError> {
+ if let Some(v) = p.schema_version {
+ if let Some(f) = &p.format
+ && f != FORMAT_ID
+ {
+ return Err(FormatError::NotAProject(format!("format is `{f}`, expected `{FORMAT_ID}`")));
+ }
+ return Ok(v);
+ }
+ // Before the envelope (v1) a file was the bare Project object with `version`.
+ if p.items.is_some() && p.root.is_some() {
+ return Ok(p.version.unwrap_or(1));
+ }
+ Err(FormatError::NotAProject("no `schema_version` and not a legacy project".into()))
+}
+
+/// Read a project file (any supported schema).
+pub fn decode(bytes: &[u8]) -> Result<Loaded, FormatError> {
+ let probe: Probe = serde_json::from_slice(bytes)
+ .map_err(|e| if e.is_syntax() || e.is_eof() { FormatError::Corrupt(e.to_string()) } else { FormatError::NotAProject(e.to_string()) })?;
+ let found = probe_version(&probe)?;
+ check_supported(found)?;
+ if found == SCHEMA_VERSION {
+ // Fast path: deserialize straight into the model.
+ let env: EnvelopeIn = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?;
+ return Ok(Loaded { project: env.project, schema_version: found, generator: env.generator });
+ }
+ let doc: Value = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?;
+ let doc = migrate_with(MIGRATIONS, doc, found)?;
+ let env: EnvelopeIn = serde_json::from_value(doc).map_err(|e| FormatError::Corrupt(format!("after upgrading from schema v{found}: {e}")))?;
+ Ok(Loaded { project: env.project, schema_version: found, generator: env.generator })
+}
+
+fn check_supported(found: u32) -> Result<(), FormatError> {
+ if found > SCHEMA_VERSION {
+ return Err(FormatError::TooNew { found, supported: SCHEMA_VERSION });
+ }
+ if found < OLDEST_SCHEMA {
+ return Err(FormatError::TooOld { found, oldest: OLDEST_SCHEMA });
+ }
+ Ok(())
+}
+
+/// Run `table` from schema `from` up to `table.len() + 1`, stamping `schema_version` after each step.
+pub fn migrate_with(table: &[Migration], mut doc: Value, from: u32) -> Result<Value, FormatError> {
+ let target = table.len() as u32 + 1;
+ if from > target {
+ return Err(FormatError::TooNew { found: from, supported: target });
+ }
+ if from == 0 {
+ return Err(FormatError::TooOld { found: 0, oldest: 1 });
+ }
+ for v in from..target {
+ let step = table[(v - 1) as usize];
+ doc = step(doc).map_err(|msg| FormatError::Migration { from: v, msg })?;
+ match doc.as_object_mut() {
+ Some(o) => {
+ o.insert("schema_version".into(), Value::from(v + 1));
+ }
+ None => return Err(FormatError::Migration { from: v, msg: "migration produced a non-object document".into() }),
+ }
+ }
+ Ok(doc)
+}
+
+/// v1 → v2: wrap the bare project in the envelope and drop the per-project `version` field.
+fn v1_to_v2(doc: Value) -> Result<Value, String> {
+ let Value::Object(mut project) = doc else { return Err("expected a JSON object".into()) };
+ project.remove("version");
+ Ok(serde_json::json!({
+ "format": FORMAT_ID,
+ "schema_version": 2,
+ "generator": "FilmCraft (schema v1)",
+ "project": Value::Object(project),
+ }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn schema_version_matches_table() {
+ assert_eq!(SCHEMA_VERSION, 2);
+ }
+
+ #[test]
+ fn roundtrip_current() {
+ let p = Project::new("Round Trip");
+ for pretty in [true, false] {
+ let b = encode(&p, pretty);
+ let l = decode(&b).unwrap();
+ assert_eq!(l.project, p);
+ assert_eq!(l.schema_version, SCHEMA_VERSION);
+ assert!(!l.migrated());
+ assert_eq!(l.generator.as_deref(), Some(generator().as_str()));
+ }
+ }
+
+ #[test]
+ fn envelope_has_explicit_schema_version() {
+ let v: Value = serde_json::from_slice(&encode(&Project::new("x"), true)).unwrap();
+ assert_eq!(v["schema_version"], SCHEMA_VERSION);
+ assert_eq!(v["format"], FORMAT_ID);
+ assert!(v["project"]["items"].is_object());
+ assert!(v["project"].get("version").is_none());
+ }
+
+ #[test]
+ fn refuses_newer() {
+ let mut v: Value = serde_json::from_slice(&encode(&Project::new("x"), false)).unwrap();
+ v["schema_version"] = Value::from(SCHEMA_VERSION + 1);
+ let e = decode(&serde_json::to_vec(&v).unwrap()).unwrap_err();
+ assert!(matches!(e, FormatError::TooNew { .. }));
+ assert!(e.to_string().contains("newer version of FilmCraft"), "{e}");
+ }
+
+ #[test]
+ fn rejects_foreign_and_damaged() {
+ assert!(matches!(decode(br#"{"hello": 1}"#), Err(FormatError::NotAProject(_))));
+ assert!(matches!(decode(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_))));
+ let b = encode(&Project::new("x"), false);
+ assert!(matches!(decode(&b[..b.len() / 2]), Err(FormatError::Corrupt(_))));
+ }
+
+ #[test]
+ fn chain_runs_each_step_in_order() {
+ fn a(mut d: Value) -> Result<Value, String> {
+ d["trail"] = Value::from(format!("{}a", d["trail"].as_str().unwrap_or("")));
+ Ok(d)
+ }
+ fn b(mut d: Value) -> Result<Value, String> {
+ d["trail"] = Value::from(format!("{}b", d["trail"].as_str().unwrap_or("")));
+ Ok(d)
+ }
+ fn fail(_: Value) -> Result<Value, String> {
+ Err("boom".into())
+ }
+ let table: &[Migration] = &[a, b, a];
+ let out = migrate_with(table, serde_json::json!({}), 1).unwrap();
+ assert_eq!(out["trail"], "aba");
+ assert_eq!(out["schema_version"], 4);
+ let out = migrate_with(table, serde_json::json!({}), 3).unwrap();
+ assert_eq!(out["trail"], "a");
+ let out = migrate_with(table, serde_json::json!({"x": 1}), 4).unwrap();
+ assert_eq!(out, serde_json::json!({"x": 1}));
+ assert!(matches!(migrate_with(table, serde_json::json!({}), 5), Err(FormatError::TooNew { found: 5, supported: 4 })));
+ let e = migrate_with(&[a, fail], serde_json::json!({}), 1).unwrap_err();
+ assert!(matches!(e, FormatError::Migration { from: 2, .. }), "{e}");
+ }
+}
diff --git a/crates/format/tests/fixtures.rs b/crates/format/tests/fixtures.rs
new file mode 100644
index 000000000..b7d8a7db5
--- /dev/null
+++ b/crates/format/tests/fixtures.rs
@@ -0,0 +1,144 @@
+//! Old project files keep opening: hand-made fixtures of every past schema are upgraded on load.
+
+use filmcraft_format::{FormatError, SCHEMA_VERSION, decode, encode};
+use filmcraft_project::{ClipId, ItemId, ItemKind, Project};
+use filmcraft_time::Tick;
+
+fn fixture(name: &str) -> Vec<u8> {
+ std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap()
+}
+
+#[test]
+fn v1_minimal_loads() {
+ let l = decode(&fixture("v1-minimal.fcproj")).unwrap();
+ assert_eq!(l.schema_version, 1);
+ assert!(l.migrated());
+ assert_eq!(l.project.name, "Legacy Minimal");
+ assert!(l.project.items.is_empty());
+ assert_eq!(l.project.next_id, 1);
+}
+
+#[test]
+fn v1_edit_loads_with_defaults_for_later_fields() {
+ let l = decode(&fixture("v1-edit.fcproj")).unwrap();
+ assert_eq!(l.schema_version, 1);
+ let p = &l.project;
+ assert_eq!(p.name, "Legacy Edit");
+ assert_eq!(p.next_id, 48);
+ let media = p.item(ItemId(5)).unwrap();
+ assert_eq!(media.name, "Ocean_Sunset.mp4");
+ assert!(media.metadata.is_empty());
+ let seq = p.sequence(ItemId(21)).unwrap();
+ assert_eq!(seq.video_tracks.len(), 1);
+ assert_eq!(seq.audio_tracks.len(), 1);
+ assert_eq!(seq.markers.len(), 1);
+ let clip = &seq.video_tracks[0].items[0];
+ assert_eq!(clip.id, ClipId(29));
+ assert_eq!(clip.source_in, Tick(243_675_432_000));
+ assert!(!clip.reverse && clip.link.is_none() && clip.gain_db == 0.0 && !clip.scale_to_frame);
+ assert_eq!(clip.effects.len(), 3);
+ assert!(seq.audio_tracks[0].effects.is_empty());
+ seq.check().unwrap();
+}
+
+#[test]
+fn upgraded_file_resaves_in_current_schema_losslessly() {
+ let old = decode(&fixture("v1-edit.fcproj")).unwrap().project;
+ let bytes = encode(&old, true);
+ let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(v["schema_version"], SCHEMA_VERSION);
+ let again = decode(&bytes).unwrap();
+ assert!(!again.migrated());
+ assert_eq!(again.project, old);
+}
+
+#[test]
+fn future_schema_is_refused_with_a_clear_error() {
+ let mut v: serde_json::Value = serde_json::from_slice(&fixture("v1-minimal.fcproj")).unwrap();
+ // A bare v1-shaped project claiming a future `version` is refused too.
+ v["version"] = 99.into();
+ let e = decode(&serde_json::to_vec(&v).unwrap()).unwrap_err();
+ assert!(matches!(e, FormatError::TooNew { found: 99, .. }), "{e}");
+ assert!(e.to_string().contains("Update FilmCraft"));
+}
+
+/// Build a project with `n` clips (half video, half linked audio) on 4+4 tracks.
+pub fn big_project(n: usize) -> Project {
+ let mut p = decode(&fixture("v1-edit.fcproj")).unwrap().project;
+ let seq_id = ItemId(21);
+ let mut next = 1_000_000u64;
+ let seq = match &mut p.items.get_mut(&seq_id).unwrap().kind {
+ ItemKind::Sequence(s) => s,
+ _ => unreachable!(),
+ };
+ let v0 = seq.video_tracks[0].items[0].clone();
+ let a0 = seq.audio_tracks[0].items[0].clone();
+ for t in seq.video_tracks.iter_mut().chain(seq.audio_tracks.iter_mut()) {
+ t.items.clear();
+ }
+ let mut vt = seq.video_tracks[0].clone();
+ let mut at = seq.audio_tracks[0].clone();
+ for k in 1..4 {
+ vt.id = filmcraft_project::TrackId(500 + k);
+ vt.name = format!("Video {}", k + 1);
+ seq.video_tracks.push(vt.clone());
+ at.id = filmcraft_project::TrackId(600 + k);
+ at.name = format!("Audio {}", k + 1);
+ seq.audio_tracks.push(at.clone());
+ }
+ let dur = Tick(254_016_000_000); // 1 s each
+ for i in 0..n / 2 {
+ let track = i % 4;
+ let slot = (i / 4) as i64;
+ let mut v = v0.clone();
+ v.id = ClipId(next);
+ v.start = Tick(dur.0 * slot);
+ v.duration = dur;
+ v.link = Some(next);
+ let mut a = a0.clone();
+ a.id = ClipId(next + 1);
+ a.start = v.start;
+ a.duration = dur;
+ a.link = Some(next);
+ next += 2;
+ seq.video_tracks[track].items.push(v);
+ seq.audio_tracks[track].items.push(a);
+ }
+ p.next_id = next;
+ p
+}
+
+#[test]
+fn large_project_roundtrip_and_timing() {
+ let p = big_project(2000);
+ let clips: usize = p.sequence(ItemId(21)).unwrap().all_tracks().map(|t| t.items.len()).sum();
+ assert_eq!(clips, 2000);
+ let reps = 5;
+ let t0 = std::time::Instant::now();
+ let mut pretty = Vec::new();
+ for _ in 0..reps {
+ pretty = encode(&p, true);
+ }
+ let pretty_ms = t0.elapsed().as_secs_f64() * 1000.0 / reps as f64;
+ let t0 = std::time::Instant::now();
+ let mut compact = Vec::new();
+ for _ in 0..reps {
+ compact = encode(&p, false);
+ }
+ let compact_ms = t0.elapsed().as_secs_f64() * 1000.0 / reps as f64;
+ let t0 = std::time::Instant::now();
+ let back = decode(&compact).unwrap();
+ let decode_ms = t0.elapsed().as_secs_f64() * 1000.0;
+ assert_eq!(back.project, p);
+ let t0 = std::time::Instant::now();
+ let dir = std::env::temp_dir().join(format!("filmcraft-big-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ filmcraft_format::atomic_write(&dir.join("big.fcproj"), &compact).unwrap();
+ let write_ms = t0.elapsed().as_secs_f64() * 1000.0;
+ std::fs::remove_dir_all(&dir).unwrap();
+ println!(
+ "2000-clip project: pretty {:.1} KB in {pretty_ms:.2} ms, compact {:.1} KB in {compact_ms:.2} ms, decode {decode_ms:.2} ms, atomic write+fsync {write_ms:.2} ms",
+ pretty.len() as f64 / 1024.0,
+ compact.len() as f64 / 1024.0
+ );
+}
diff --git a/crates/format/tests/fixtures/v1-edit.fcproj b/crates/format/tests/fixtures/v1-edit.fcproj
new file mode 100644
index 000000000..5c311da00
--- /dev/null
+++ b/crates/format/tests/fixtures/v1-edit.fcproj
@@ -0,0 +1,324 @@
+{
+ "name": "Legacy Edit",
+ "settings": {
+ "renderer": "FilmCraft GPU Acceleration (wgpu)",
+ "video_display": "Timecode",
+ "audio_display_samples": true,
+ "default_still_duration": 1270080000000,
+ "default_transition_duration_frames": 24,
+ "default_audio_transition_duration": 254016000000
+ },
+ "root": {
+ "id": 0,
+ "name": "Legacy Edit",
+ "children": [
+ {
+ "Bin": {
+ "id": 1,
+ "name": "Footage",
+ "children": [
+ {
+ "Item": 5
+ }
+ ]
+ }
+ },
+ {
+ "Item": 21
+ }
+ ]
+ },
+ "items": {
+ "5": {
+ "id": 5,
+ "name": "Ocean_Sunset.mp4",
+ "label": "Iris",
+ "kind": {
+ "Media": {
+ "media": {
+ "Generator": {
+ "Demo": "OceanSunset"
+ }
+ },
+ "info": {
+ "name": "Ocean_Sunset.mp4",
+ "kind": "Movie",
+ "duration": 4572288000000,
+ "video": {
+ "width": 1920,
+ "height": 1080,
+ "frame_rate": {
+ "num": 24000,
+ "den": 1001
+ },
+ "par": [
+ 1,
+ 1
+ ],
+ "codec": "H.264 (synthetic)",
+ "pixel_format": "RGBA 8-bit",
+ "color": {
+ "matrix": "Bt709",
+ "transfer": "Srgb",
+ "primaries": "Bt709",
+ "range": "Full"
+ },
+ "has_alpha": false,
+ "bitrate": null
+ },
+ "audio": {
+ "sample_rate": 48000,
+ "channels": 2,
+ "codec": "PCM (synthetic)",
+ "bits_per_sample": 32
+ },
+ "container": "Synthetic MPEG-4",
+ "start_timecode": null,
+ "file_size": null
+ },
+ "interpret": {
+ "frame_rate": null,
+ "par": null,
+ "ignore_alpha": false,
+ "invert_alpha": false
+ },
+ "mark_in": null,
+ "mark_out": null,
+ "markers": [],
+ "offline": false,
+ "proxy": null
+ }
+ }
+ },
+ "21": {
+ "id": 21,
+ "name": "Assembly",
+ "label": "Forest",
+ "kind": {
+ "Sequence": {
+ "settings": {
+ "width": 1920,
+ "height": 1080,
+ "frame_rate": {
+ "num": 24000,
+ "den": 1001
+ },
+ "par": [
+ 1,
+ 1
+ ],
+ "sample_rate": 48000,
+ "drop_frame": false,
+ "preset": "HD 1080p 23.976",
+ "audio_master": "Stereo",
+ "preview_codec": "ProRes 422",
+ "max_bit_depth": false,
+ "max_render_quality": false,
+ "working_space": "Rec. 709"
+ },
+ "video_tracks": [
+ {
+ "id": 15,
+ "kind": "Video",
+ "name": "Video 1",
+ "items": [
+ {
+ "id": 29,
+ "item": 5,
+ "name": "Ocean_Sunset.mp4",
+ "label": "Iris",
+ "start": 0,
+ "duration": 1260755496000,
+ "source_in": 243675432000,
+ "speed": 1.0,
+ "enabled": true,
+ "effects": [
+ {
+ "effect": "motion",
+ "enabled": true,
+ "params": {
+ "anchor": {
+ "value": {
+ "Vec2": {
+ "x": 960.0,
+ "y": 540.0
+ }
+ }
+ },
+ "anti_flicker": {
+ "value": {
+ "Float": 0.0
+ }
+ },
+ "position": {
+ "value": {
+ "Vec2": {
+ "x": 960.0,
+ "y": 540.0
+ }
+ }
+ },
+ "rotation": {
+ "value": {
+ "Float": 0.0
+ }
+ },
+ "scale": {
+ "value": {
+ "Float": 100.0
+ }
+ },
+ "scale_width": {
+ "value": {
+ "Float": 100.0
+ }
+ },
+ "uniform_scale": {
+ "value": {
+ "Bool": true
+ }
+ }
+ }
+ },
+ {
+ "effect": "opacity",
+ "enabled": true,
+ "params": {
+ "blend": {
+ "value": {
+ "Choice": 0
+ }
+ },
+ "opacity": {
+ "value": {
+ "Float": 100.0
+ }
+ }
+ }
+ },
+ {
+ "effect": "time_remap",
+ "enabled": true,
+ "params": {
+ "speed": {
+ "value": {
+ "Float": 100.0
+ }
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "transitions": [],
+ "locked": false,
+ "sync_lock": true,
+ "enabled": true,
+ "muted": false,
+ "solo": false,
+ "channels": "Stereo",
+ "volume_db": 0.0,
+ "pan": 0.0
+ }
+ ],
+ "audio_tracks": [
+ {
+ "id": 18,
+ "kind": "Audio",
+ "name": "Audio 1",
+ "items": [
+ {
+ "id": 30,
+ "item": 5,
+ "name": "Ocean_Sunset.mp4",
+ "label": "Iris",
+ "start": 0,
+ "duration": 1260755496000,
+ "source_in": 243675432000,
+ "speed": 1.0,
+ "enabled": true,
+ "effects": [
+ {
+ "effect": "volume",
+ "enabled": true,
+ "params": {
+ "bypass": {
+ "value": {
+ "Bool": false
+ }
+ },
+ "level": {
+ "value": {
+ "Float": -8.0
+ }
+ }
+ }
+ },
+ {
+ "effect": "channel_volume",
+ "enabled": true,
+ "params": {
+ "bypass": {
+ "value": {
+ "Bool": false
+ }
+ },
+ "left": {
+ "value": {
+ "Float": 0.0
+ }
+ },
+ "right": {
+ "value": {
+ "Float": 0.0
+ }
+ }
+ }
+ },
+ {
+ "effect": "panner",
+ "enabled": true,
+ "params": {
+ "balance": {
+ "value": {
+ "Float": 0.0
+ }
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "transitions": [],
+ "locked": false,
+ "sync_lock": true,
+ "enabled": true,
+ "muted": false,
+ "solo": false,
+ "channels": "Stereo",
+ "volume_db": 0.0,
+ "pan": 0.0
+ }
+ ],
+ "markers": [
+ {
+ "id": 800000,
+ "start": 0,
+ "duration": 0,
+ "name": "Open",
+ "comment": "",
+ "kind": "Comment",
+ "color": "Green"
+ }
+ ],
+ "mark_in": null,
+ "mark_out": null,
+ "work_area": null,
+ "start_timecode": 0
+ }
+ }
+ }
+ },
+ "next_id": 48,
+ "version": 1
+}
\ No newline at end of file
diff --git a/crates/format/tests/fixtures/v1-minimal.fcproj b/crates/format/tests/fixtures/v1-minimal.fcproj
new file mode 100644
index 000000000..28a53c309
--- /dev/null
+++ b/crates/format/tests/fixtures/v1-minimal.fcproj
@@ -0,0 +1,19 @@
+{
+ "name": "Legacy Minimal",
+ "settings": {
+ "renderer": "FilmCraft GPU Acceleration (wgpu)",
+ "video_display": "Timecode",
+ "audio_display_samples": true,
+ "default_still_duration": 1270080000000,
+ "default_transition_duration_frames": 24,
+ "default_audio_transition_duration": 254016000000
+ },
+ "root": {
+ "id": 0,
+ "name": "Legacy Minimal",
+ "children": []
+ },
+ "items": {},
+ "next_id": 1,
+ "version": 1
+}
\ No newline at end of file
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index 93adb5721..54ea38205 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -730,12 +730,8 @@ pub struct Project {
pub items: BTreeMap<ItemId, ProjectItem>,
/// Monotonic id source for all id types.
pub next_id: u64,
- /// Format version of the serialized project.
- pub version: u32,
}
-pub const PROJECT_VERSION: u32 = 1;
-
impl Default for Project {
fn default() -> Self {
Self::new("Untitled")
@@ -750,7 +746,6 @@ impl Project {
root: Bin { id: BinId(0), name: name.into(), children: Vec::new() },
items: BTreeMap::new(),
next_id: 1,
- version: PROJECT_VERSION,
}
}
@@ -856,15 +851,13 @@ impl Project {
})
}
+ /// The bare model as JSON. Project *files* add a schema-versioned envelope; read and write them
+ /// with `filmcraft-format`, not with these.
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_default()
}
pub fn from_json(s: &str) -> Result<Project, String> {
- let p: Project = serde_json::from_str(s).map_err(|e| e.to_string())?;
- if p.version > PROJECT_VERSION {
- return Err(format!("project version {} is newer than this FilmCraft ({PROJECT_VERSION})", p.version));
- }
- Ok(p)
+ serde_json::from_str(s).map_err(|e| e.to_string())
}
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 6bd56fd39..4a11465fa 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -454,10 +454,12 @@ impl FilmcraftApp {
}
r
}
- "file.saveAs" | "file.save" => {
- let suggested = format!("{}.fcproj", self.session.project.name);
+ "file.saveAs" | "file.save" | "file.saveCopy" => {
+ let suggested =
+ if id == "file.saveCopy" { format!("{} copy.fcproj", self.session.project.name) } else { format!("{}.fcproj", self.session.project.name) };
let Some(path) = self.hooks.pick_save.as_mut().and_then(|f| f(&suggested)) else { return Ok(Value::Null) };
- self.session.execute("file.saveAs", json!({"path": path})).map_err(|e| e.to_string())
+ let cmd = if id == "file.saveCopy" { "file.saveCopy" } else { "file.saveAs" };
+ self.session.execute(cmd, json!({"path": path})).map_err(|e| e.to_string())
}
"file.open" => {
let Some(path) = self.hooks.pick_open_project.as_mut().and_then(|f| f()) else { return Ok(Value::Null) };
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 4c76afe69..de25a71b2 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -178,6 +178,7 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
// File dialogs for commands that need a path.
if (id == "file.import" && params.get("paths").is_none() && params.get("path").is_none())
|| (id == "file.saveAs" && params.get("path").is_none())
+ || (id == "file.saveCopy" && params.get("path").is_none())
|| (id == "file.open" && params.get("path").is_none())
|| (id == "file.save" && params.get("path").is_none() && app.session.path.is_none())
{
diff --git a/docs/project-files.md b/docs/project-files.md
new file mode 100644
index 000000000..e945b42be
--- /dev/null
+++ b/docs/project-files.md
@@ -0,0 +1,80 @@
+# Project files
+
+FilmCraft projects are `.fcproj` files: UTF-8 JSON with an explicit schema version. Reading and
+writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` commands use it.
+
+## Format
+
+```json
+{
+ "format": "filmcraft.project",
+ "schema_version": 2,
+ "generator": "FilmCraft 0.1.0",
+ "project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 }
+}
+```
+
+- `schema_version` is the version of the whole document. This build writes
+ `filmcraft_format::SCHEMA_VERSION` and reads every version from 1 up to it.
+- `project` is the serialized `filmcraft_project::Project` (bins, media clips, sequences, tracks,
+ clips, effects, keyframes, markers). Media is referenced by path, never embedded.
+- Files are written compact (no indentation). A 2,000-clip project is about 1.4 MB.
+
+### Schema history
+
+| Version | Since | Shape |
+|---|---|---|
+| 1 | M0 | the bare `Project` object with a `"version": 1` field |
+| 2 | M11.1 | the envelope above; the project's own `version` field is gone |
+
+### Migrations
+
+Older files are upgraded on load, in memory, by a chain of single-step functions
+(`filmcraft_format::MIGRATIONS`, where entry *i* upgrades v*i+1* to v*i+2*). Each step rewrites the JSON
+document; after the last one the result is deserialized into the current model. To change the schema:
+
+1. add a function `vN_to_vN1(doc: Value) -> Result<Value, String>` and append it to `MIGRATIONS`
+ (`SCHEMA_VERSION` follows automatically);
+2. add a small hand-made fixture of the old shape to `crates/format/tests/fixtures/` and a test that it
+ loads;
+3. never edit a migration that has shipped.
+
+Fields added with `#[serde(default)]` don't need a migration: missing values take their defaults.
+
+When you open an older file FilmCraft says so ("Upgraded project from schema v1 to v2"). The file
+on disk is unchanged until you save. The **first save over it** keeps the original next to it as
+`<name> (schema v1 backup).fcproj`, so an older FilmCraft can still open your work.
+
+### Newer files
+
+A file with a `schema_version` newer than the build supports is **refused**, not half-read:
+
+> this project was saved by a newer version of FilmCraft (project schema v3); this build reads up to
+> v2. Update FilmCraft to open it.
+
+Reading it partially and saving it back would silently drop whatever the newer version added.
+
+## Saving is atomic
+
+Every write of a project file, auto-save, recovery snapshot or preferences file goes through
+`filmcraft_format::atomic_write`:
+
+1. write the bytes to a hidden temp file in the **same directory** (`.<name>.<pid>-<n>.tmp`);
+2. `fsync` the temp file;
+3. rename it over the target (an atomic replace on every supported OS);
+4. `fsync` the directory so the rename itself is durable.
+
+A crash, `kill -9` or power cut at any point leaves either the complete old file or the complete new
+one. If a step fails, the temp file is removed and the old file is untouched.
+
+## Commands
+
+| Id | Menu | |
+|---|---|---|
+| `file.save {path?}` | File ▸ Save (⌘S) | write to the project's path (or `path`) |
+| `file.saveAs {path}` | File ▸ Save As… (⇧⌘S) | write and adopt the new path |
+| `file.saveCopy {path}` | File ▸ Save a Copy… (⌥⌘S) | write a copy; the project keeps its path and unsaved state |
+| `file.revert` | File ▸ Revert | reload the last saved version, discarding changes |
+| `file.open {path}` | File ▸ Open Project… (⌘O) | returns `{schemaVersion, migrated}` |
+
+In the UI, Save / Save As / Save a Copy without a `path` show a file dialog.