Skip to content

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

Merge main into M11.1–2 (autosave/recovery): previews follow save/open/recover; bare pre-envelope projects with version 1 or 2 load as schema v1 (regression test)

Brandon Thomas34f53fe9cf98
diff --cc ROADMAP.md
index fda760064,ffdd7a60f..f86088ad3
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -37,9 -37,9 +37,9 @@@ Status: ✅ done · 🟡 in progress �
| M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 |
| M7 | Audio | 🟡 | Mixer basics, peak meters, BS.1770 loudness meters (M/S/I LUFS, true peak; matches ffmpeg), DSP crate, 12 clip audio effects running on it (EQ, filters, dynamics, limiter, delay, reverb, DeNoise, DeHum, pitch) with keyframes | Effects UI polish (EQ curve), remaining effects (multiband, convolution reverb), track effects/mixers with automation, Essential Sound, audio transitions, 5.1 | 6–10 |
| M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette; basic scopes | LUT import UI, colour match, colour management + HDR (PQ/HLG, log, tone mapping) | 8–12 |
- | M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), Matroska/WebM import (H.264/HEVC/ProRes/MJPEG + AAC/FLAC/MP3/Vorbis/PCM) | VP9 and Opus (in progress), AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
- | M10 | Graphics & captions | ⬜ | — | Text engine, Type tool, Essential Graphics, captions (SRT/VTT/SCC), speech-to-text | 20–30 |
+ | M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), Matroska/WebM import (H.264/HEVC/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4) | VP9 (in progress), Ogg Opus files, AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
+ | M10 | Graphics & captions | 🟡 | Caption tracks (Subtitle/CEA-608/708/Teletext formats, track style), SRT/WebVTT/SCC import+export (frame-exact, property-tested), caption editing (add/split/merge/trim/move, sync-locked insert/extract), Text panel Captions tab, burn-in in Program monitor and export | Text engine with shaping, Type tool, Essential Graphics, rolls/crawls, MCC/STL/TTML, 608/708 embedding, speech-to-text | 18–27 |
-| M11 | Interchange & project management | 🟡 | `.fcproj` save/open | Autosave/recovery, FCP7 XML, FCPXML, EDL, OTIO, relink, project manager, proxies | 15 |
+| M11 | Interchange & project management | 🟡 | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO | Relink/offline, project manager, proxies | 8 |
| M12–M16 | Web (WASM), platform, long tail | 🟡 | L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), ~850 remaining commands and dialogs, performance hardening | 40–65 |
## Running now
diff --cc crates/engine/Cargo.toml
index a4b6c3260,ce60fb2c7..b8fb90c7d
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@@ -20,8 -20,8 +20,9 @@@ filmcraft-project = { workspace = true
filmcraft-edit = { workspace = true }
filmcraft-render = { workspace = true }
filmcraft-export = { workspace = true }
+filmcraft-format = { workspace = true }
filmcraft-interchange = { workspace = true }
+ filmcraft-captions = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --cc crates/engine/src/commands.rs
index 5ad6657e4,76cd6dd55..687721f3b
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@@ -65,14 -65,7 +65,14 @@@ fn has_edit_points(s: &Session) -> std:
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_recovery(s: &Session) -> std::result::Result<(), String> {
+ if s.recovery_candidates().is_empty() { Err("there are no unsaved changes to recover".into()) } else { Ok(()) }
+}
+
- fn has_seq(s: &Session) -> std::result::Result<(), String> {
+ pub(crate) fn has_seq(s: &Session) -> std::result::Result<(), String> {
s.active_sequence().map(|_| ()).ok_or_else(|| "no sequence is open".into())
}
fn has_selection(s: &Session) -> std::result::Result<(), String> {
@@@ -2182,101 -2166,3 +2232,107 @@@ pub fn inspect_sequence(s: &Session, id
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.previews_follow_path();
+ 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();
++ if let Some(p) = &path
++ && !cfg!(target_arch = "wasm32")
++ {
++ s.previews.set_dir(Some(crate::previews::dir_for_project(p)));
++ }
+ 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}))
+}
+
+/// Load a recovery candidate (newest when `id` is None) as the current, unsaved project.
+fn recover(s: &mut Session, id: Option<&str>) -> Result<Value> {
+ let per = s.persistence.as_ref().ok_or_else(|| EngineError::Other("recovery is not running".into()))?;
+ let idx = match id {
+ Some(id) => per.candidates.iter().position(|c| c.id == id).ok_or_else(|| bad("file.recover", format!("no recovery session `{id}`")))?,
+ None => 0,
+ };
+ let c = per.candidates[idx].clone();
+ let saved_at = per.local_time(c.meta.saved_unix);
+ let loaded = crate::autosave::load_candidate(&c).map_err(EngineError::Other)?;
+ install_project(s, loaded.project, c.meta.project_path.clone(), false);
+ // Our own journal must hold the recovered state before the old one is deleted.
+ s.sync_persistence();
+ if let Some(per) = s.persistence.as_mut() {
+ per.flush();
+ per.candidates.remove(idx);
+ }
+ crate::autosave::discard_candidate(&c).map_err(|e| EngineError::Other(e.to_string()))?;
+ s.toast(format!("Recovered unsaved changes to {} from {saved_at}", c.meta.project_name));
+ Ok(json!({"id": c.id, "name": c.meta.project_name, "path": c.meta.project_path, "savedAt": saved_at, "revision": c.meta.revision}))
+}
+
+/// Where auto-saves of the current project go.
+fn auto_save_dir(s: &Session) -> std::path::PathBuf {
+ match (&s.path, &s.persistence) {
+ (Some(p), _) => filmcraft_format::autosave::auto_save_dir(std::path::Path::new(p)),
+ (None, Some(per)) => per.data_dir.join(filmcraft_format::autosave::AUTO_SAVE_DIR),
+ (None, None) => std::path::PathBuf::from(filmcraft_format::autosave::AUTO_SAVE_DIR),
+ }
+}
+
+fn auto_save_name(s: &Session) -> String {
+ s.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| s.project.name.clone())
+}
diff --cc crates/engine/src/lib.rs
index c06371a93,a3b28715a..dfaba163b
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -8,7 -8,7 +8,8 @@@
//! The project is an `Arc<Project>` edited copy-on-write; undo keeps whole-project snapshots (cheap
//! thanks to structural sharing of untouched items).
+pub mod autosave;
+ pub mod captions;
pub mod commands;
pub mod demo;
pub mod interchange;
@@@ -145,16 -151,10 +150,18 @@@ pub struct Session
pub events: Vec<Event>,
/// Commands executed (for macros/debugging): (id, params).
pub journal: Vec<(String, Value)>,
- /// Background jobs (exports, …).
+ /// Background jobs (exports, render previews…).
pub jobs: Vec<Job>,
+ /// User preferences (`prefs.*` commands) and where they persist (None = not persisted).
+ pub prefs: autosave::Preferences,
+ pub prefs_path: Option<std::path::PathBuf>,
+ /// Auto-save ring + crash-recovery journal (native frontends start it; None = off).
+ pub persistence: Option<autosave::Persistence>,
+ /// 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,
+ /// Render preview files + render-bar segments (shared with the frontend's frame workers).
+ pub previews: Arc<previews::PreviewStore>,
}
/// A background job with shared progress.
@@@ -209,84 -209,19 +216,94 @@@ impl Session
events: Vec::new(),
journal: Vec::new(),
jobs: Vec::new(),
+ prefs: Default::default(),
+ prefs_path: None,
+ persistence: None,
+ loaded_schema: filmcraft_format::SCHEMA_VERSION,
+ previews: Arc::new(previews::PreviewStore::temp()),
}
}
+ /// Start auto-save and the crash-recovery journal (native frontends). Loads preferences from
+ /// the data directory and finds unsaved changes left by sessions that died
+ /// ([`Session::recovery_candidates`]).
+ pub fn start_autosave(&mut self, cfg: autosave::AutosaveConfig) -> std::io::Result<()> {
+ let prefs_path = cfg.data_dir.join("preferences.json");
+ self.prefs = autosave::Preferences::load(&prefs_path);
+ self.prefs_path = Some(prefs_path);
+ self.persistence = Some(autosave::Persistence::start(&cfg, self.prefs.auto_save.clone())?);
+ self.sync_persistence();
+ Ok(())
+ }
+
+ /// Clean shutdown: flush and stop the worker. Unsaved changes stay in the journal (offered on
+ /// the next launch); otherwise the session's journal directory is removed.
+ pub fn shutdown(&mut self) {
+ self.sync_persistence();
+ if let Some(p) = self.persistence.take() {
+ p.close();
+ }
+ }
+
+ pub fn recovery_candidates(&self) -> &[autosave::RecoveryCandidate] {
+ self.persistence.as_ref().map(|p| p.candidates.as_slice()).unwrap_or(&[])
+ }
+
+ /// Tell the worker about the current project state if it changed (cheap: an `Arc` clone and a
+ /// channel send; serialization happens on the worker). Called after every command.
+ pub fn sync_persistence(&mut self) {
+ let dirty = self.is_dirty();
+ let Some(p) = self.persistence.as_mut() else { return };
+ let cur = autosave::Sent { revision: self.revision, saved_revision: self.saved_revision, path: self.path.clone() };
+ if p.last_sent.as_ref() == Some(&cur) {
+ return;
+ }
+ if dirty {
+ p.send_dirty(self.project.clone(), self.revision, self.path.clone());
+ } else {
+ p.send_clean();
+ }
+ p.last_sent = Some(cur);
+ }
+
+ /// Apply worker notifications (call regularly, e.g. once per UI frame).
+ pub fn poll_persistence(&mut self) {
+ let Some(p) = self.persistence.as_mut() else { return };
+ for ev in p.drain_events() {
+ match ev {
+ autosave::WorkerEvent::SavedProject { path, revision } => {
+ if self.path.as_deref() == Some(path.as_str()) && revision > self.saved_revision && revision <= self.revision {
+ self.saved_revision = revision;
+ }
+ }
+ autosave::WorkerEvent::Error(m) => self.events.push(Event::Toast { message: m, error: true }),
+ _ => {}
+ }
+ }
+ self.sync_persistence();
+ }
+
+ /// Replace preferences (persisting them and updating the worker).
+ pub fn set_prefs(&mut self, p: autosave::Preferences) -> std::io::Result<()> {
+ self.prefs = p;
+ if let Some(w) = &self.persistence {
+ w.set_prefs(self.prefs.auto_save.clone());
+ }
+ match &self.prefs_path {
+ Some(path) => self.prefs.save(path),
+ None => Ok(()),
+ }
+ }
+
+ /// Keep render previews next to the saved project (moves an unsaved project's previews).
+ pub fn previews_follow_path(&mut self) {
+ if let Some(p) = &self.path
+ && !cfg!(target_arch = "wasm32")
+ {
+ self.previews.move_to(previews::dir_for_project(p));
+ }
+ }
+
pub fn is_dirty(&self) -> bool {
self.revision != self.saved_revision
}
@@@ -463,9 -400,7 +483,11 @@@ pub fn media_duration(p: &Project, _poo
}
}
+#[cfg(test)]
+mod autosave_tests;
+#[cfg(test)]
+mod file_tests;
#[cfg(test)]
+ mod previews_tests;
+ #[cfg(test)]
mod tests;
diff --cc crates/format/src/lib.rs
index 912322dbd,000000000..29a955473
mode 100644,000000..100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@@ -1,282 -1,0 +1,287 @@@
+//! `.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`.
++ /// Bare (pre-envelope) project: its `version` field.
+ #[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`.
++ // Its `version` was 1, or 2 on builds that briefly bumped it when caption tracks were added
++ // (same shape; the new field loads with its default). Anything higher is from the future.
+ if p.items.is_some() && p.root.is_some() {
- return Ok(p.version.unwrap_or(1));
++ return Ok(match p.version.unwrap_or(1) {
++ 0..=2 => 1,
++ v => v,
++ });
+ }
+ 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 --cc crates/format/tests/fixtures.rs
index b7d8a7db5,000000000..e49d3bcc1
mode 100644,000000..100644
--- a/crates/format/tests/fixtures.rs
+++ b/crates/format/tests/fixtures.rs
@@@ -1,144 -1,0 +1,155 @@@
+//! 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);
+}
+
++/// Main briefly wrote bare projects with `"version": 2` (caption tracks) before the envelope landed.
++#[test]
++fn bare_version_2_loads_as_schema_v1() {
++ let mut v: serde_json::Value = serde_json::from_slice(&fixture("v1-edit.fcproj")).unwrap();
++ v["version"] = 2.into();
++ let l = decode(&serde_json::to_vec(&v).unwrap()).unwrap();
++ assert_eq!(l.schema_version, 1);
++ assert!(l.migrated());
++ assert_eq!(l.project.name, decode(&fixture("v1-edit.fcproj")).unwrap().project.name);
++}
++
+#[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 --cc crates/project/src/lib.rs
index 54ea38205,af6d3876f..20d7ac5e8
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@@ -640,6 -642,9 +642,9 @@@ pub struct Sequence
pub master_volume_db: f64,
#[serde(default)]
pub master_effects: Vec<EffectInstance>,
- /// Caption tracks (drawn above the video tracks; first = top). Added in project version 2.
++ /// Caption tracks (drawn above the video tracks; first = top). Older files have none (serde default).
+ #[serde(default)]
+ pub caption_tracks: Vec<CaptionTrack>,
}
impl Sequence {
@@@ -933,6 -963,43 +953,41 @@@ mod tests
assert_eq!(a.source_time_at(rate.tick_of(10)), Tick(1000) + rate.tick_of(20));
}
+ #[test]
- fn version1_projects_load_without_captions() {
- let (mut p, _, seq) = demo_project();
- p.version = 1;
++ fn projects_without_caption_tracks_load() {
++ let (p, _, seq) = demo_project();
+ let mut v: serde_json::Value = serde_json::from_str(&p.to_json()).unwrap();
+ // a v1 file has no `caption_tracks` key
+ let items = v["items"].as_object_mut().unwrap();
+ for it in items.values_mut() {
+ if let Some(s) = it["kind"].get_mut("Sequence") {
+ s.as_object_mut().unwrap().remove("caption_tracks");
+ }
+ }
+ let q = Project::from_json(&v.to_string()).unwrap();
- assert_eq!(q.version, PROJECT_VERSION);
+ assert!(q.sequence(seq).unwrap().caption_tracks.is_empty());
+ }
+
+ #[test]
+ fn caption_tracks_roundtrip() {
+ let (mut p, _, seq) = demo_project();
+ let id = TrackId(p.alloc_id());
+ let mut ct = CaptionTrack::new(id, "Subtitle".into(), CaptionFormat::Cea608);
+ ct.captions.push(Caption {
+ id: ClipId(p.alloc_id()),
+ start: Tick(10),
+ duration: Tick(TICKS_PER_SECOND),
+ text: "Hello\n<i>world</i>".into(),
+ speaker: Some("Ann".into()),
+ cue_id: Some("1".into()),
+ settings: "line:90%".into(),
+ });
+ p.sequence_mut(seq).unwrap().caption_tracks.push(ct);
+ let q = Project::from_json(&p.to_json()).unwrap();
+ assert_eq!(p, q);
+ assert_eq!(q.sequence(seq).unwrap().duration(), Tick(10 + TICKS_PER_SECOND));
+ }
+
#[test]
fn bins() {
let mut p = Project::new("x");
diff --cc crates/ui-egui/src/menus.rs
index db32244e8,950212a37..ef10d0013
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -200,11 -178,11 +200,12 @@@ pub fn invoke(app: &mut FilmcraftApp, c
// 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())
+ || (matches!(id, "captions.import" | "captions.export") && params.get("path").is_none())
{
- return app.file_dialog(id);
+ return app.file_dialog(id, &params);
}
let r = app.session.execute(id, params).map_err(|e| e.to_string());
if let Err(e) = &r {