FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M11.7: offline media and relinking
Brandon Thomasb98c88613381
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rsindex 07e9359ff..322922b5d 100644--- a/apps/filmcraft/src/main.rs+++ b/apps/filmcraft/src/main.rs@@ -109,6 +109,7 @@ fn main() -> eframe::Result {app.hooks.pick_save_as = Some(Box::new(|filter: &str, exts: &[&str], name: &str| {rfd::FileDialog::new().add_filter(filter, exts).set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string())}));+ app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));app.hooks.pick_open_file = Some(Box::new(|filter: &str, exts: &[&str]| {rfd::FileDialog::new().add_filter(filter, exts).pick_file().map(|p| p.to_string_lossy().to_string())}));diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rsindex deafcf257..051a337ad 100644--- a/crates/codecs/src/gop.rs+++ b/crates/codecs/src/gop.rs@@ -33,6 +33,8 @@ struct State {/// Decoded frames by presentation pts (bounded).frames: BTreeMap<i64, Arc<VideoFrame>>,bytes: usize,+ /// The shared decoder is out decoding (see [`GopCache::frame`]).+ busy: bool,}/// Decoder + decoded-frame cache for one video track.@@ -45,7 +47,7 @@ pub struct GopCache {impl GopCache {pub fn new(explicit_color: Option<ColorInfo>) -> Self {- Self { state: Mutex::new(State { decoder: None, next: usize::MAX, frames: BTreeMap::new(), bytes: 0 }), explicit_color, budget: 384 << 20 }+ Self { state: Mutex::new(State { decoder: None, next: usize::MAX, frames: BTreeMap::new(), bytes: 0, busy: false }), explicit_color, budget: 384 << 20 }}fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame) {@@ -68,6 +70,11 @@ impl GopCache {}/// The frame presented at `target` (track units, clamped to the stream).+ ///+ /// The decoder is taken out of the shared state while it decodes, so the lock is never held+ /// across a decode: decoders may run slices on rayon, and a rayon worker waiting in a decode+ /// can pick up another render job that asks this same source for a frame. A request that+ /// finds the shared decoder busy decodes with a private decoder instead of waiting.pub fn frame(&self, s: &dyn VideoSamples, target: i64) -> crate::Result<Arc<VideoFrame>> {let n = s.count();let i = s.sample_at(target.max(0)).or_else(|| (n > 0).then(|| n - 1)).ok_or_else(|| CodecError::Decode("empty track".into()))?;@@ -76,53 +83,83 @@ impl GopCache {if let Some(f) = st.frames.get(&want_pts) {return Ok(f.clone());}- if st.decoder.is_none() {- st.decoder = Some(s.make_decoder()?);- st.next = usize::MAX;+ let shared = !st.busy;+ let (mut dec, mut next) = if shared {+ st.busy = true;+ (st.decoder.take(), st.next)+ } else {+ (None, usize::MAX)+ };+ drop(st);+ let decoded = (|| -> crate::Result<Vec<crate::video::DecodedFrame>> {+ if dec.is_none() {+ dec = Some(s.make_decoder()?);+ next = usize::MAX;+ }+ let d = dec.as_mut().expect("decoder");+ Self::decode_to(s, d.as_mut(), &mut next, i, want_pts, n)+ })();+ let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());+ if shared {+ st.busy = false;+ st.decoder = dec;+ st.next = if decoded.is_ok() { next } else { usize::MAX };+ }+ let out = decoded?;+ for d in out {+ self.store(&mut st, d.pts, d.frame);}+ // nearest decoded frame at or before the wanted pts (robust to decoder pts quirks)+ st.frames+ .get(&want_pts)+ .cloned()+ .or_else(|| st.frames.range(..=want_pts).next_back().map(|(_, f)| f.clone()))+ .ok_or_else(|| CodecError::Decode("frame not produced".into()))+ }++ /// Decode with `d` (positioned at `next`) until the picture with `want_pts` (sample `i`) comes out.+ fn decode_to(+ s: &dyn VideoSamples,+ d: &mut dyn VideoDecoder,+ next: &mut usize,+ i: usize,+ want_pts: i64,+ n: usize,+ ) -> crate::Result<Vec<crate::video::DecodedFrame>> {let mut key = s.sync_before(i);// Continue the running decoder when the wanted sample is ahead within this GOP run.- let continuing = st.next != usize::MAX && st.next > key && st.next <= i + 16 && st.next <= n;+ let continuing = *next != usize::MAX && *next > key && *next <= i + 16 && *next <= n;if !continuing {// The container's sync flags may be wrong for the codec (an MP4 without `stss` marks// every sample): step back to a sample the decoder can start from.while key > 0 {let data = s.read(key)?;- if st.decoder.as_ref().expect("decoder").is_random_access(&data) != Some(false) {+ if d.is_random_access(&data) != Some(false) {break;}key = s.sync_before(key - 1);}- if let Some(d) = st.decoder.as_mut() {- d.reset();- }- st.next = key;+ d.reset();+ *next = key;}let limit = (i + 64).min(n);- while st.next < limit {- let k = st.next;+ let mut out = Vec::new();+ let mut found = false;+ while *next < limit {+ let k = *next;let data = s.read(k)?;- let out = st.decoder.as_mut().expect("decoder").decode(&data, s.pts(k))?;- st.next += 1;- for d in out {- self.store(&mut st, d.pts, d.frame);- }- if st.frames.contains_key(&want_pts) {+ let pics = d.decode(&data, s.pts(k))?;+ *next += 1;+ found |= pics.iter().any(|p| p.pts == want_pts);+ out.extend(pics);+ if found {break;}}- if !st.frames.contains_key(&want_pts) {- let out = st.decoder.as_mut().expect("decoder").flush();- for d in out {- self.store(&mut st, d.pts, d.frame);- }- st.next = usize::MAX;+ if !found {+ out.extend(d.flush());+ *next = usize::MAX;}- // nearest decoded frame at or before the wanted pts (robust to decoder pts quirks)- st.frames- .get(&want_pts)- .cloned()- .or_else(|| st.frames.range(..=want_pts).next_back().map(|(_, f)| f.clone()))- .ok_or_else(|| CodecError::Decode("frame not produced".into()))+ Ok(out)}}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 7f3ae7e09..abb85973d 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -209,6 +209,7 @@ fn default_seq_settings_for(info: &filmcraft_media::MediaInfo) -> SequenceSettin/// Import bytes as a media item (engine-level; the UI reads files through services).pub fn import_bytes(s: &mut Session, path: &str, bytes: std::sync::Arc<[u8]>, bin: Option<filmcraft_project::BinId>) -> Result<ItemId> {let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ let identity = crate::relink::identity_of_bytes(&bytes);let src = s.media.open_bytes(&name, bytes)?;let info = src.info().clone();let label = match info.kind {@@ -230,11 +231,12 @@ pub fn import_bytes(s: &mut Session, path: &str, bytes: std::sync::Arc<[u8]>, bimarkers: vec![],offline: false,proxy: None,+ identity: Some(identity),}),bin,))})?;- s.media.insert(id, src);+ s.media.insert_file(id, path, src);Ok(id)}@@ -1851,6 +1853,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::mixer::commands());v.extend(crate::graphics::commands());v.extend(crate::shortcuts::commands());+ v.extend(crate::relink::commands());// Labels as individual commands (Edit ▸ Label ▸ <name>)for l in Label::ALL {let _ = l;@@ -1885,7 +1888,8 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {result: Default::default(),};let project = s.project.clone();- let provider = s.media.provider(project.clone(), s.services.clone());+ // Export always renders full-resolution media, whatever the proxy toggle says.+ let provider = s.media.full_res_provider(project.clone(), s.services.clone());let (prog, res) = (job.progress.clone(), job.result.clone());let run = move || {let r = filmcraft_export::export(&project, seq, &settings, &provider, &prog).map_err(|e| e.to_string());@@ -2306,7 +2310,10 @@ fn schema_backup_path(path: &str, schema: u32) -> String {/// 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) {+ let proxies = s.media.use_proxies();s.media = std::sync::Arc::new(crate::MediaPool::default());+ s.media.set_use_proxies(proxies);+ s.offline = Default::default();let first = proj.sequences().next().map(|i| i.id);s.project = std::sync::Arc::new(proj);s.history = Default::default();@@ -2336,7 +2343,8 @@ fn open_project(s: &mut Session, path: &str) -> Result<Value> {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}))+ let missing = crate::relink::on_open(s);+ Ok(json!({"path": path, "schemaVersion": from, "migrated": migrated, "missingMedia": missing}))}/// Load a recovery candidate (newest when `id` is None) as the current, unsaved project.@@ -2350,6 +2358,7 @@ fn recover(s: &mut Session, id: Option<&str>) -> Result<Value> {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);+ crate::relink::on_open(s);// 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() {diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rsindex 2161b4df3..5b5998ff8 100644--- a/crates/engine/src/demo.rs+++ b/crates/engine/src/demo.rs@@ -34,6 +34,7 @@ pub fn add_generator(p: &mut Project, pool: &MediaPool, src: GeneratorSource, namarkers: vec![],offline: false,proxy: None,+ identity: None,}),bin,);diff --git a/crates/engine/src/interchange.rs b/crates/engine/src/interchange.rsindex b79c338d9..c84693b2c 100644--- a/crates/engine/src/interchange.rs+++ b/crates/engine/src/interchange.rs@@ -57,6 +57,7 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Resumatch opened {Some(src) => {let info = src.info().clone();+ let identity = crate::relink::identity_of(&*s.services, &mpath).ok();let rebase = (format == Format::Edl).then_some(info.start_timecode).flatten();s.edit("Link Media", |proj, _| {if let Some(item) = proj.items.get_mut(&id)@@ -65,13 +66,14 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Resulet rate = info.video.as_ref().map(|v| v.frame_rate);m.info = info.clone();m.offline = false;+ m.identity = identity;if let (Some(tc), Some(rate)) = (rebase, rate) {filmcraft_interchange::rebase_source_timecode(proj, id, tc, rate);}}Ok(())})?;- s.media.insert(id, src);+ s.media.insert_file(id, &mpath, src);linked += 1;}None => offline.push(mpath),diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e9a9f2788..3b183117f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -17,6 +17,7 @@ pub mod interchange;pub mod media_pool;pub mod mixer;pub mod previews;+pub mod relink;pub mod shortcut_presets;pub mod shortcuts;pub mod trim;@@ -60,6 +61,17 @@ pub type Result<T> = std::result::Result<T, EngineError>;pub trait Services: Send + Sync {fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>>;fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()>;+ /// Size of a file in bytes (an error when it is missing). Hosts should override this: the+ /// default reads the whole file.+ fn file_size(&self, path: &str) -> std::io::Result<u64> {+ self.read_file(path).map(|b| b.len() as u64)+ }+ /// Up to `len` bytes of a file starting at `offset` (fewer at the end of the file).+ fn read_range(&self, path: &str, offset: u64, len: usize) -> std::io::Result<Vec<u8>> {+ let b = self.read_file(path)?;+ let a = (offset as usize).min(b.len());+ Ok(b[a..(a + len).min(b.len())].to_vec())+ }}/// Native filesystem services.@@ -72,6 +84,18 @@ impl Services for FsServices {// Atomic + durable: temp file in the same directory, fsync, rename, fsync the directory.filmcraft_format::atomic_write(std::path::Path::new(path), data)}+ fn file_size(&self, path: &str) -> std::io::Result<u64> {+ let m = std::fs::metadata(path)?;+ if m.is_file() { Ok(m.len()) } else { Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path} is not a file"))) }+ }+ fn read_range(&self, path: &str, offset: u64, len: usize) -> std::io::Result<Vec<u8>> {+ use std::io::{Read, Seek, SeekFrom};+ let mut f = std::fs::File::open(path)?;+ f.seek(SeekFrom::Start(offset))?;+ let mut out = Vec::with_capacity(len);+ f.take(len as u64).read_to_end(&mut out)?;+ Ok(out)+ }}/// Undo history of whole-project snapshots.@@ -181,6 +205,8 @@ pub struct Session {pub trim_play: trim::TrimPlayback,/// Keyboard shortcuts (active bindings, presets; `shortcuts.*` commands).pub shortcuts: shortcuts::Shortcuts,+ /// Missing / offline media found by the last scan (Link Media dialog).+ pub offline: relink::OfflineState,/// Nesting depth of [`Session::execute`] (commands that run other commands).exec_depth: u32,}@@ -245,6 +271,7 @@ impl Session {mixrec: Default::default(),trim_play: Default::default(),shortcuts: shortcuts::Shortcuts::new(),+ offline: Default::default(),exec_depth: 0,}}@@ -557,10 +584,14 @@ mod autosave_tests;#[cfg(test)]mod file_tests;#[cfg(test)]+mod media_test_util;+#[cfg(test)]mod mixer_tests;#[cfg(test)]mod previews_tests;#[cfg(test)]+mod relink_tests;+#[cfg(test)]mod shortcuts_tests;#[cfg(test)]mod tests;diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rsindex 634ed8add..5b4a587fd 100644--- a/crates/engine/src/media_pool.rs+++ b/crates/engine/src/media_pool.rs@@ -1,17 +1,41 @@//! The media pool: one shared [`MediaSource`] per project item, created lazily from its//! [`MediaRef`], plus the registry of container/codec openers.+//!+//! - Sources are cached per item **and per reference** (the file path, the offline flag), so a+//! relink, Make Offline or their undo picks up the right file on the next frame.+//! - Media that can't be opened (missing, unreadable) or was made offline renders the offline+//! slate ([`filmcraft_render::offline`]) instead of failing; the reason is kept for the UI.+//! - With proxies enabled ([`MediaPool::set_use_proxies`]) items with an attached proxy are read+//! from it. Proxy frames are smaller; the source still reports the full-resolution size, and the+//! compositor derives its pixel scale from the frame it gets, so effects and Motion render the+//! same picture at lower resolution. Export asks for [`MediaPool::full_res_provider`].use std::collections::HashMap;-use std::sync::{Arc, RwLock};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, RwLock};+use filmcraft_frame::{AudioBuffer, VideoFrame};use filmcraft_media::generators::GeneratorSource;-use filmcraft_media::{MediaError, OfflineSource, Opener, SharedSource};-use filmcraft_project::{ItemId, ItemKind, MediaRef, Project};+use filmcraft_media::{FrameRequest, MediaError, MediaInfo, MediaSource, Opener, SharedSource};+use filmcraft_project::{ItemId, ItemKind, MediaClip, MediaRef, Project};+use filmcraft_render::offline::OfflineReason;use crate::Services;+/// Why an item renders the offline slate, as last seen by the pool.+#[derive(Clone, Debug, PartialEq)]+pub struct OfflineStatus {+ pub reason: OfflineReason,+ pub path: String,+ pub error: String,+}+pub struct MediaPool {- sources: RwLock<HashMap<ItemId, SharedSource>>,+ /// item → (reference key, source)+ sources: RwLock<HashMap<ItemId, (String, SharedSource)>>,+ proxies: RwLock<HashMap<ItemId, (String, SharedSource)>>,+ offline: RwLock<HashMap<ItemId, OfflineStatus>>,+ use_proxies: AtomicBool,/// Openers tried before the built-in ones (MP4/MOV + codecs register here).pub openers: RwLock<Vec<Opener>>,}@@ -19,25 +43,74 @@ pub struct MediaPool {impl Default for MediaPool {/// A pool with the built-in container/codec openers registered.fn default() -> Self {- Self { sources: RwLock::new(HashMap::new()), openers: RwLock::new(filmcraft_codecs::openers()) }+ Self {+ sources: RwLock::new(HashMap::new()),+ proxies: RwLock::new(HashMap::new()),+ offline: RwLock::new(HashMap::new()),+ use_proxies: AtomicBool::new(false),+ openers: RwLock::new(filmcraft_codecs::openers()),+ }+ }+}++/// Cache key of a media clip's full-resolution reference ("" matches anything: generators and+/// sources inserted without a key).+pub fn media_key(m: &MediaClip) -> String {+ match &m.media {+ MediaRef::File { path } if m.offline => format!("offline:{path}"),+ MediaRef::File { path } => format!("file:{path}"),+ MediaRef::Generator(_) => String::new(),}}+fn file_name(path: &str) -> String {+ path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()+}+impl MediaPool {pub fn register_opener(&self, o: Opener) {self.openers.write().unwrap_or_else(|e| e.into_inner()).push(o);}+ /// Cache a source for an item, valid whatever the item's reference (generators).pub fn insert(&self, item: ItemId, src: SharedSource) {- self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(item, src);+ self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(item, (String::new(), src));+ }++ /// Cache a source opened from `path` for an item.+ pub fn insert_file(&self, item: ItemId, path: &str, src: SharedSource) {+ self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(item, (format!("file:{path}"), src));+ self.offline.write().unwrap_or_else(|e| e.into_inner()).remove(&item);}pub fn remove(&self, item: ItemId) {self.sources.write().unwrap_or_else(|e| e.into_inner()).remove(&item);+ self.proxies.write().unwrap_or_else(|e| e.into_inner()).remove(&item);+ self.offline.write().unwrap_or_else(|e| e.into_inner()).remove(&item);+ }++ /// Forget every opened source (files are re-read on next use).+ pub fn clear(&self) {+ self.sources.write().unwrap_or_else(|e| e.into_inner()).clear();+ self.proxies.write().unwrap_or_else(|e| e.into_inner()).clear();+ self.offline.write().unwrap_or_else(|e| e.into_inner()).clear();}pub fn cached(&self, item: ItemId) -> Option<SharedSource> {- self.sources.read().unwrap_or_else(|e| e.into_inner()).get(&item).cloned()+ self.sources.read().unwrap_or_else(|e| e.into_inner()).get(&item).map(|(_, s)| s.clone())+ }++ pub fn use_proxies(&self) -> bool {+ self.use_proxies.load(Ordering::Relaxed)+ }++ pub fn set_use_proxies(&self, on: bool) {+ self.use_proxies.store(on, Ordering::Relaxed);+ }++ /// Why an item last rendered offline (None = online or not opened yet).+ pub fn offline_status(&self, item: ItemId) -> Option<OfflineStatus> {+ self.offline.read().unwrap_or_else(|e| e.into_inner()).get(&item).cloned()}/// Open a file through the registered openers.@@ -46,43 +119,104 @@ impl MediaPool {filmcraft_media::open_bytes(name, bytes, &openers)}- /// Resolve (and cache) the source for a project item.+ /// Read and open a file through `services`.+ pub fn open_file(&self, path: &str, services: &dyn Services) -> Result<SharedSource, MediaError> {+ let bytes = services+ .read_file(path)+ .map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(e.to_string()) } else { MediaError::Io(e.to_string()) })?;+ self.open_bytes(&file_name(path), bytes.into())+ }++ /// Resolve (and cache) the source for a project item, using proxies when they are enabled.pub fn source_for(&self, p: &Project, item: ItemId, services: &dyn Services) -> Option<SharedSource> {- if let Some(s) = self.cached(item) {+ self.resolve(p, item, services, self.use_proxies())+ }++ /// Resolve the full-resolution source for an item (never a proxy).+ pub fn full_res_source(&self, p: &Project, item: ItemId, services: &dyn Services) -> Option<SharedSource> {+ self.resolve(p, item, services, false)+ }++ fn resolve(&self, p: &Project, item: ItemId, services: &dyn Services, proxies: bool) -> Option<SharedSource> {+ let it = p.item(item)?;+ let m = match &it.kind {+ ItemKind::Media(m) => m,+ ItemKind::Subclip { parent, .. } => return self.resolve(p, *parent, services, proxies),+ _ => return None,+ };+ if proxies+ && !m.offline+ && let Some(MediaRef::File { path }) = &m.proxy+ && let Some(s) = self.proxy_source(item, path, m, services)+ {return Some(s);}- let it = p.item(item)?;- let src: SharedSource = match &it.kind {- ItemKind::Media(m) => match &m.media {- MediaRef::Generator(g) => {- let v = m.info.video.as_ref();- let (w, h, r) = v.map(|v| (v.width, v.height, v.frame_rate)).unwrap_or((1920, 1080, Default::default()));- Arc::new(GeneratorSource::new(g.clone(), w, h, r, m.info.duration).with_name(&it.name))+ let key = media_key(m);+ if let Some((k, s)) = self.sources.read().unwrap_or_else(|e| e.into_inner()).get(&item)+ && (k.is_empty() || *k == key)+ {+ return Some(s.clone());+ }+ let src: SharedSource = match &m.media {+ MediaRef::Generator(g) => {+ let v = m.info.video.as_ref();+ let (w, h, r) = v.map(|v| (v.width, v.height, v.frame_rate)).unwrap_or((1920, 1080, Default::default()));+ Arc::new(GeneratorSource::new(g.clone(), w, h, r, m.info.duration).with_name(&it.name))+ }+ MediaRef::File { path } if m.offline => {+ self.set_offline(item, OfflineReason::MadeOffline, path, "made offline");+ Arc::new(SlateSource::new(m.info.clone(), &file_name(path), OfflineReason::MadeOffline))+ }+ MediaRef::File { path } => match self.open_file(path, services) {+ Ok(s) => {+ self.offline.write().unwrap_or_else(|e| e.into_inner()).remove(&item);+ s}- MediaRef::File { path } => {- let opened = services.read_file(path).map_err(|e| MediaError::Io(e.to_string())).and_then(|b| {- let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();- self.open_bytes(&name, b.into())- });- match opened {- Ok(s) => s,- Err(e) => {- log::warn!("media offline: {path}: {e}");- Arc::new(OfflineSource { info: m.info.clone() })- }- }+ Err(e) => {+ log::warn!("media offline: {path}: {e}");+ let reason = if matches!(e, MediaError::Offline(_)) { OfflineReason::Missing } else { OfflineReason::Unreadable };+ self.set_offline(item, reason, path, &e.to_string());+ Arc::new(SlateSource::new(m.info.clone(), &file_name(path), reason))}},- ItemKind::Subclip { parent, .. } => return self.source_for(p, *parent, services),- _ => return None,};- self.insert(item, src.clone());+ self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(item, (key, src.clone()));Some(src)}- /// A render-side provider bound to a project snapshot.+ fn set_offline(&self, item: ItemId, reason: OfflineReason, path: &str, error: &str) {+ self.offline.write().unwrap_or_else(|e| e.into_inner()).insert(item, OfflineStatus { reason, path: path.to_string(), error: error.to_string() });+ }++ fn proxy_source(&self, item: ItemId, path: &str, m: &MediaClip, services: &dyn Services) -> Option<SharedSource> {+ let key = format!("proxy:{path}");+ if let Some((k, s)) = self.proxies.read().unwrap_or_else(|e| e.into_inner()).get(&item)+ && *k == key+ {+ return Some(s.clone());+ }+ match self.open_file(path, services) {+ Ok(s) => {+ let src: SharedSource = Arc::new(ProxySource { proxy: s, info: m.info.clone() });+ self.proxies.write().unwrap_or_else(|e| e.into_inner()).insert(item, (key, src.clone()));+ Some(src)+ }+ Err(e) => {+ // a missing proxy falls back to the full-resolution media+ log::warn!("proxy offline: {path}: {e}");+ None+ }+ }+ }++ /// A render-side provider bound to a project snapshot (proxies when enabled).pub fn provider(self: &Arc<Self>, project: Arc<Project>, services: Arc<dyn Services>) -> PoolProvider {- PoolProvider { pool: self.clone(), project, services }+ PoolProvider { pool: self.clone(), project, services, full_res: false }+ }++ /// A provider that always reads full-resolution media (export).+ pub fn full_res_provider(self: &Arc<Self>, project: Arc<Project>, services: Arc<dyn Services>) -> PoolProvider {+ PoolProvider { pool: self.clone(), project, services, full_res: true }}}@@ -91,10 +225,93 @@ pub struct PoolProvider {pub pool: Arc<MediaPool>,pub project: Arc<Project>,pub services: Arc<dyn Services>,+ /// Ignore proxies (export always renders full resolution).+ pub full_res: bool,}impl filmcraft_render::SourceProvider for PoolProvider {fn source(&self, item: ItemId) -> Option<SharedSource> {- self.pool.source_for(&self.project, item, &*self.services)+ if self.full_res { self.pool.full_res_source(&self.project, item, &*self.services) } else { self.pool.source_for(&self.project, item, &*self.services) }+ }+}++/// The offline slate as a media source: video frames are the slate at the requested scale of the+/// item's frame size; audio is silence.+pub struct SlateSource {+ info: MediaInfo,+ name: String,+ reason: OfflineReason,+ last: Mutex<Option<Arc<VideoFrame>>>,+}++impl SlateSource {+ pub fn new(info: MediaInfo, name: &str, reason: OfflineReason) -> Self {+ Self { info, name: name.to_string(), reason, last: Mutex::new(None) }+ }+ pub fn reason(&self) -> OfflineReason {+ self.reason+ }+}++impl MediaSource for SlateSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }+ fn video_frame(&self, req: FrameRequest) -> filmcraft_media::Result<Arc<VideoFrame>> {+ let v = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?;+ let s = req.scale.clamp(1.0 / 64.0, 1.0);+ let (w, h) = (((v.width as f32 * s).round() as u32).max(2), ((v.height as f32 * s).round() as u32).max(2));+ let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(f) = last.as_ref()+ && f.width == w+ && f.height == h+ {+ return Ok(Arc::new((**f).clone().with_pts(req.time)));+ }+ let px = filmcraft_render::offline::slate_rgba8(w as usize, h as usize, &self.name, self.reason);+ let f = Arc::new(VideoFrame::rgba8(w, h, px));+ *last = Some(f.clone());+ Ok(Arc::new((*f).clone().with_pts(req.time)))+ }+ fn audio(&self, _start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<AudioBuffer> {+ Ok(AudioBuffer::silence(sample_rate, self.info.audio.as_ref().map_or(2, |a| a.channels as usize), frames))+ }+}++/// A proxy standing in for its full-resolution media: reports the full-resolution info and hands+/// out the proxy's (smaller) frames. A proxy whose aspect ratio differs from the original is+/// resampled to the original's aspect so it lines up exactly.+pub struct ProxySource {+ pub proxy: SharedSource,+ pub info: MediaInfo,+}++impl MediaSource for ProxySource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }+ fn video_frame(&self, req: FrameRequest) -> filmcraft_media::Result<Arc<VideoFrame>> {+ let full = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?;+ let pv = self.proxy.info().video.as_ref().map(|v| (v.width, v.height)).unwrap_or((full.width, full.height));+ // ask the proxy for the scale relative to its own size+ let k = (full.width as f32 / pv.0.max(1) as f32).max(1.0);+ let f = self.proxy.video_frame(FrameRequest { time: req.time, scale: (req.scale * k).min(1.0) })?;+ let want_h = (f.width as f64 * full.height as f64 / full.width.max(1) as f64).round() as u32;+ if want_h.abs_diff(f.height) <= 1 {+ return Ok(f);+ }+ // different aspect: resample (nearest) to the original's aspect at the proxy's width+ let src = f.to_rgba8();+ let (w, h) = (f.width as usize, want_h.max(1) as usize);+ let mut out = vec![0u8; w * h * 4];+ for y in 0..h {+ let sy = ((y as f64 + 0.5) * f.height as f64 / h as f64) as usize;+ let row = &src[sy.min(f.height as usize - 1) * w * 4..][..w * 4];+ out[y * w * 4..(y + 1) * w * 4].copy_from_slice(row);+ }+ Ok(Arc::new(VideoFrame::rgba8(w as u32, h as u32, out).with_pts(f.pts)))+ }+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<AudioBuffer> {+ self.proxy.audio(start, frames, sample_rate)}}diff --git a/crates/engine/src/media_test_util.rs b/crates/engine/src/media_test_util.rsnew file mode 100644index 000000000..b32038320--- /dev/null+++ b/crates/engine/src/media_test_util.rs@@ -0,0 +1,112 @@+//! Test media made with our own encoders (no ffmpeg needed): short movies of the procedural demo+//! scenes, written to temporary folders.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use filmcraft_media::generators::GeneratorSource;+use filmcraft_media::{DemoScene, Generator, MediaSource};+use filmcraft_project::{ItemId, ItemKind, Label, MediaClip, MediaRef, Project, SequenceSettings, TrackKind};+use filmcraft_time::{FrameRate, Tick, TimeRange};+use serde_json::json;++use crate::Session;++pub fn tmp_dir(name: &str) -> PathBuf {+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let d = std::env::temp_dir().join(format!("filmcraft-{name}-{}-{nanos}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ d+}++/// Write a `frames`-frame `w`×`h` 24 fps movie of a demo scene (with its audio) to `path`.+/// `.mov` = ProRes 422 HQ + PCM, `.mp4` = H.264 + AAC.+pub fn make_movie(path: &Path, scene: DemoScene, w: u32, h: u32, frames: i64) {+ let rate = FrameRate::FPS_24;+ let dur = rate.tick_of(frames);+ let src = GeneratorSource::new(Generator::Demo(scene), w, h, rate, dur);+ let info = src.info().clone();+ let mut p = Project::new("fixture");+ let clip = MediaClip {+ media: MediaRef::Generator(Generator::Demo(scene)),+ info,+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: false,+ proxy: None,+ identity: None,+ };+ let item = p.add_item("scene", Label::Iris, ItemKind::Media(clip), None);+ let seq = p.new_sequence("s", SequenceSettings { width: w, height: h, frame_rate: rate, ..Default::default() }, 1, 1, None);+ let r = TimeRange::new(Tick::ZERO, dur);+ let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, r, rate).unwrap();+ for e in &mut v.effects {+ filmcraft_project::resolve_auto_points(e, (w, h), (w, h));+ }+ let a = p.make_track_item(item, TrackKind::Audio, Tick::ZERO, r, rate).unwrap();+ let q = p.sequence_mut(seq).unwrap();+ q.video_tracks[0].items.push(v);+ q.audio_tracks[0].items.push(a);+ let fmt = if path.extension().is_some_and(|e| e == "mp4") { filmcraft_export::Format::H264 } else { filmcraft_export::Format::ProRes };+ let settings = filmcraft_export::ExportSettings { format: fmt, path: path.to_string_lossy().into_owned(), bitrate_kbps: 4000, ..Default::default() };+ let shared: filmcraft_media::SharedSource = Arc::new(src);+ let provider = move |id: ItemId| (id == item).then(|| shared.clone());+ filmcraft_export::export(&Arc::new(p), seq, &settings, &provider, &Default::default()).unwrap();+}++/// A session with `files` imported and a sequence (sized like the first file) holding each file+/// in turn on V1/A1. Returns (session, item ids, sequence id).+pub fn session_with(files: &[&Path]) -> (Session, Vec<ItemId>, ItemId) {+ let mut s = Session::default();+ let paths: Vec<String> = files.iter().map(|p| p.to_string_lossy().into_owned()).collect();+ let r = s.execute("file.import", json!({"paths": paths})).unwrap();+ let items: Vec<ItemId> = r["items"].as_array().unwrap().iter().map(|v| ItemId(v.as_u64().unwrap())).collect();+ assert_eq!(items.len(), files.len(), "{r}");+ let info = s.project.item(items[0]).unwrap().as_media().unwrap().info.clone();+ let v = info.video.clone().unwrap();+ let rate = v.frame_rate;+ let mut p = (*s.project).clone();+ let seq = p.new_sequence("Seq", SequenceSettings { width: v.width, height: v.height, frame_rate: rate, ..Default::default() }, 1, 1, None);+ let mut at = Tick::ZERO;+ for &it in &items {+ let d = p.item(it).unwrap().duration();+ let range = TimeRange::new(Tick::ZERO, d);+ let mut vi = p.make_track_item(it, TrackKind::Video, at, range, rate).unwrap();+ for e in &mut vi.effects {+ filmcraft_project::resolve_auto_points(e, (v.width, v.height), (v.width, v.height));+ }+ let ai = p.make_track_item(it, TrackKind::Audio, at, range, rate).unwrap();+ let q = p.sequence_mut(seq).unwrap();+ q.video_tracks[0].items.push(vi);+ q.audio_tracks[0].items.push(ai);+ at += d;+ }+ s.project = Arc::new(p);+ s.state.active_sequence = Some(seq);+ s.state.open_sequences = vec![seq];+ (s, items, seq)+}++/// Render the active sequence at `frame` (scale 1) as straight RGBA8 over black.+pub fn frame_rgba(s: &mut Session, frame: i64, scale: f32) -> (usize, usize, Vec<u8>) {+ let t = s.sequence_rate().tick_of(frame);+ s.set_playhead(t);+ let img = s.render_program(scale).unwrap();+ (img.w, img.h, img.over_black_rgba8())+}++pub fn psnr(a: &[u8], b: &[u8]) -> f64 {+ assert_eq!(a.len(), b.len());+ let mut se = 0.0;+ let mut n = 0.0;+ for (x, y) in a.chunks_exact(4).zip(b.chunks_exact(4)) {+ for c in 0..3 {+ let d = x[c] as f64 - y[c] as f64;+ se += d * d;+ n += 1.0;+ }+ }+ if se == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64 * 255.0 / (se / n)).log10() }+}diff --git a/crates/engine/src/relink.rs b/crates/engine/src/relink.rsnew file mode 100644index 000000000..72708a9bf--- /dev/null+++ b/crates/engine/src/relink.rs@@ -0,0 +1,720 @@+//! Offline media and relinking (File ▸ Link Media…, Make Offline…).+//!+//! - **Identity.** Imports record each file's size and a fast content fingerprint+//! ([`MediaIdentity`]: a hash of the size, the first MiB and the last MiB). A relink candidate+//! whose fingerprint differs is refused unless forced, so a different take with the same name+//! can't silently replace the original.+//! - **Offline detection.** Opening a project checks that every file exists ([`scan`]); missing+//! items render the offline slate (the media pool) and the frontend shows the Link Media dialog.+//! - **Matching.** [`check_candidate`] compares a candidate with the clip: file name, extension,+//! fingerprint ("Clip ID"), duration, media start (timecode) and stream metadata.+//! - **Relink others automatically.** Linking one file derives a folder remap (the old path's+//! prefix → the new one) and applies it to every other missing file, checking each one.+//! - **Search.** [`search`] walks a folder for files named like the missing ones.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++use filmcraft_media::MediaInfo;+use filmcraft_project::{ItemId, ItemKind, MediaIdentity, MediaRef, Project};+use filmcraft_time::Tick;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use crate::commands::{CommandSpec, always, bad, bool_p, str_p, u64_p};+use crate::{EngineError, Result, Services, Session};++/// Bytes hashed at each end of the file.+pub const FINGERPRINT_SPAN: usize = 1 << 20;++/// 64-bit hash of `size`, `head` and `tail` (a simple multiply–xorshift over 8-byte words).+pub fn fingerprint(size: u64, head: &[u8], tail: &[u8]) -> u64 {+ let mut h: u64 = 0x243f_6a88_85a3_08d3 ^ size.wrapping_mul(0x9e37_79b9_7f4a_7c15);+ let mut mix = |w: u64| {+ h = (h ^ w).wrapping_mul(0x9e37_79b9_7f4a_7c15);+ h ^= h >> 29;+ };+ for part in [head, tail] {+ let mut chunks = part.chunks_exact(8);+ for c in &mut chunks {+ mix(u64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]));+ }+ let mut last = [0u8; 8];+ let r = chunks.remainder();+ last[..r.len()].copy_from_slice(r);+ mix(u64::from_le_bytes(last) ^ (r.len() as u64) << 56);+ mix(part.len() as u64);+ }+ h+}++/// Identity of bytes already in memory (import).+pub fn identity_of_bytes(b: &[u8]) -> MediaIdentity {+ let size = b.len() as u64;+ let head = &b[..b.len().min(FINGERPRINT_SPAN)];+ let tail = if b.len() > 2 * FINGERPRINT_SPAN { &b[b.len() - FINGERPRINT_SPAN..] } else { &b[head.len()..] };+ MediaIdentity { size, fingerprint: fingerprint(size, head, tail) }+}++/// Identity of a file, reading at most 2 MiB of it.+pub fn identity_of(services: &dyn Services, path: &str) -> std::io::Result<MediaIdentity> {+ let size = services.file_size(path)?;+ let n = FINGERPRINT_SPAN as u64;+ let head = services.read_range(path, 0, FINGERPRINT_SPAN)?;+ let tail =+ if size > 2 * n { services.read_range(path, size - n, FINGERPRINT_SPAN)? } else { services.read_range(path, head.len() as u64, FINGERPRINT_SPAN)? };+ Ok(MediaIdentity { size, fingerprint: fingerprint(size, &head, &tail) })+}++/// What the Link Media dialog lists.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct OfflineState {+ /// Missing or offline items found by the last scan (by item id).+ pub missing: Vec<ItemId>,+ /// The frontend should show the Link Media dialog (set when a project opens with missing+ /// media; cleared by relinking everything, Offline All or Cancel).+ pub prompt: bool,+}++/// One missing / offline media item.+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Missing {+ pub item: u64,+ pub name: String,+ pub file_name: String,+ pub path: String,+ /// `missing` (file not found), `offline` (made offline) or `proxyMissing` (only the proxy).+ pub status: &'static str,+ pub duration: i64,+ pub start_timecode: Option<i64>,+}++fn file_name(path: &str) -> &str {+ path.rsplit(['/', '\\']).next().unwrap_or(path)+}++fn split_ext(name: &str) -> (&str, &str) {+ match name.rfind('.') {+ Some(i) if i > 0 => (&name[..i], &name[i + 1..]),+ _ => (name, ""),+ }+}++/// Every media item whose file is missing (or that was made offline), in project order.+pub fn scan(p: &Project, services: &dyn Services) -> Vec<Missing> {+ let mut out = Vec::new();+ for it in p.items.values() {+ let ItemKind::Media(m) = &it.kind else { continue };+ let MediaRef::File { path } = &m.media else { continue };+ let status = if m.offline {+ "offline"+ } else if services.file_size(path).is_err() {+ "missing"+ } else if let Some(MediaRef::File { path: pp }) = &m.proxy+ && services.file_size(pp).is_err()+ {+ "proxyMissing"+ } else {+ continue;+ };+ out.push(Missing {+ item: it.id.0,+ name: it.name.clone(),+ file_name: file_name(path).to_string(),+ path: path.clone(),+ status,+ duration: m.info.duration.0,+ start_timecode: m.info.start_timecode,+ });+ }+ out+}++/// Rescan and remember the result. Returns the list.+pub fn refresh(s: &mut Session) -> Vec<Missing> {+ let list = scan(&s.project, &*s.services);+ s.offline.missing = list.iter().filter(|m| m.status != "proxyMissing").map(|m| ItemId(m.item)).collect();+ list+}++/// Which properties must match (Link Media ▸ Match File Properties) and how to relink.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct MatchOptions {+ pub file_name: bool,+ pub extension: bool,+ /// The content fingerprint recorded at import ("Clip ID"). Items without one skip this.+ pub clip_id: bool,+ pub duration: bool,+ /// Media start timecode.+ pub media_start: bool,+ /// Frame size, frame rate and audio channel count.+ pub metadata: bool,+ /// Keep clips on the same timecode when the new file's start timecode differs.+ pub align_timecode: bool,+ /// After one file is found, apply its folder remap to the other missing files.+ pub relink_others: bool,+}++impl Default for MatchOptions {+ fn default() -> Self {+ Self { file_name: true, extension: true, clip_id: true, duration: true, media_start: false, metadata: true, align_timecode: false, relink_others: true }+ }+}++impl MatchOptions {+ pub fn from_params(p: &Value) -> Self {+ let mut o: MatchOptions = p.get("match").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();+ if let Some(b) = bool_p(p, "relinkOthers") {+ o.relink_others = b;+ }+ if let Some(b) = bool_p(p, "alignTimecode") {+ o.align_timecode = b;+ }+ o+ }+}++/// The result of checking one candidate file against a clip.+#[derive(Clone, Default, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Candidate {+ pub path: String,+ /// Passes every enabled check.+ pub ok: bool,+ /// The fingerprint matched the one recorded at import (None = nothing recorded / not read).+ pub identity_match: Option<bool>,+ pub problems: Vec<String>,+ /// Ranking: identity match first, then name, extension, duration.+ pub score: u32,+ #[serde(skip)]+ pub info: Option<MediaInfo>,+ #[serde(skip)]+ pub identity: Option<MediaIdentity>,+ #[serde(skip)]+ pub source: Option<filmcraft_media::SharedSource>,+}++/// Check `path` as the new file of media item `item`. Opening the file (needed for duration,+/// timecode and metadata) is skipped when a cheap check already failed.+pub fn check_candidate(s: &Session, item: ItemId, path: &str, o: &MatchOptions) -> Result<Candidate> {+ let it = s.project.item(item).ok_or_else(|| bad("media.relink", format!("no item {}", item.0)))?;+ let m = it.as_media().ok_or_else(|| bad("media.relink", format!("item {} is not media", item.0)))?;+ let old = match &m.media {+ MediaRef::File { path } => path.clone(),+ MediaRef::Generator(_) => return Err(bad("media.relink", "generated media has no file to link")),+ };+ let mut c = Candidate { path: path.to_string(), ..Default::default() };+ let (on, oe) = split_ext(file_name(&old));+ let (nn, ne) = split_ext(file_name(path));+ let name_ok = on.eq_ignore_ascii_case(nn);+ let ext_ok = oe.eq_ignore_ascii_case(ne);+ if o.file_name && !name_ok {+ c.problems.push(format!("file name differs ({nn} vs {on})"));+ }+ if o.extension && !ext_ok {+ c.problems.push(format!("extension differs (.{ne} vs .{oe})"));+ }+ match identity_of(&*s.services, path) {+ Ok(id) => {+ c.identity = Some(id);+ if let Some(want) = m.identity {+ let same = want == id;+ c.identity_match = Some(same);+ if o.clip_id && !same {+ c.problems.push(if want.size != id.size {+ format!("not the same file: {} bytes, the original had {}", id.size, want.size)+ } else {+ "not the same file: the content fingerprint differs".to_string()+ });+ }+ }+ }+ Err(e) => {+ c.problems.push(format!("can't read {path}: {e}"));+ return Ok(c);+ }+ }+ if c.problems.is_empty() {+ match s.media.open_file(path, &*s.services) {+ Ok(src) => {+ let info = src.info().clone();+ let fd = m.info.frame_rate().frame_duration();+ if o.duration && m.info.duration > Tick::ZERO && (info.duration - m.info.duration).0.abs() > fd.0 {+ c.problems.push(format!("duration differs ({:.3}s vs {:.3}s)", info.duration.seconds(), m.info.duration.seconds()));+ }+ if o.media_start && info.start_timecode != m.info.start_timecode {+ c.problems.push(format!("media start differs ({:?} vs {:?})", info.start_timecode, m.info.start_timecode));+ }+ if o.metadata {+ if let (Some(a), Some(b)) = (&info.video, &m.info.video)+ && ((a.width, a.height) != (b.width, b.height) || a.frame_rate != b.frame_rate)+ {+ c.problems.push(format!(+ "video differs ({}×{} {} vs {}×{} {})",+ a.width,+ a.height,+ a.frame_rate.label(),+ b.width,+ b.height,+ b.frame_rate.label()+ ));+ }+ if info.video.is_some() != m.info.video.is_some() {+ c.problems.push("video stream presence differs".into());+ }+ if let (Some(a), Some(b)) = (&info.audio, &m.info.audio)+ && a.channels != b.channels+ {+ c.problems.push(format!("audio channels differ ({} vs {})", a.channels, b.channels));+ }+ }+ c.info = Some(info);+ c.source = Some(src);+ }+ Err(e) => c.problems.push(format!("can't open {path}: {e}")),+ }+ }+ c.ok = c.problems.is_empty();+ c.score = u32::from(c.identity_match == Some(true)) * 8 + u32::from(name_ok) * 4 + u32::from(ext_ok) * 2 + u32::from(c.ok);+ Ok(c)+}++/// The folder remap implied by a file moving from `old` to `new`: the longest common trailing+/// path components are dropped, the rest is (old prefix, new prefix). Separators are normalised+/// to `/` for matching, so a Windows path can be remapped to a macOS one.+pub fn derive_remap(old: &str, new: &str) -> Option<(String, String)> {+ let norm = |p: &str| p.replace('\\', "/");+ let (o, n) = (norm(old), norm(new));+ let oc: Vec<&str> = o.split('/').collect();+ let nc: Vec<&str> = n.split('/').collect();+ let mut k = 0;+ while k < oc.len().min(nc.len()) && oc[oc.len() - 1 - k] == nc[nc.len() - 1 - k] {+ k += 1;+ }+ if k == 0 {+ return None;+ }+ let op = oc[..oc.len() - k].join("/");+ let np = nc[..nc.len() - k].join("/");+ (op != np).then_some((op, np))+}++/// Apply a remap to a path (None when it doesn't start with the old prefix).+pub fn apply_remap(path: &str, from: &str, to: &str) -> Option<String> {+ let p = path.replace('\\', "/");+ let from = from.trim_end_matches('/');+ let rest = p.strip_prefix(from)?;+ if !(rest.is_empty() || rest.starts_with('/')) {+ return None;+ }+ Some(format!("{}{rest}", to.trim_end_matches('/')))+}++/// One planned relink: item → (new path, checked candidate).+struct Plan {+ item: ItemId,+ cand: Candidate,+}++/// Apply planned relinks as one undo step.+fn apply(s: &mut Session, plans: Vec<Plan>, align_timecode: bool, label: &str) -> Result<Vec<Value>> {+ let rows: Vec<Value> = plans.iter().map(|p| json!({"item": p.item.0, "path": p.cand.path})).collect();+ let sources: Vec<(ItemId, String, filmcraft_media::SharedSource)> =+ plans.iter().filter_map(|p| p.cand.source.clone().map(|src| (p.item, p.cand.path.clone(), src))).collect();+ s.edit(label, |proj, _| {+ for p in &plans {+ let Some(m) = proj.item_mut(p.item).and_then(|i| i.as_media_mut()) else { continue };+ let old_tc = m.info.start_timecode;+ let rate = m.info.frame_rate();+ m.media = MediaRef::File { path: p.cand.path.clone() };+ m.offline = false;+ if p.cand.identity.is_some() {+ m.identity = p.cand.identity;+ }+ let mut shift = Tick::ZERO;+ if let Some(info) = &p.cand.info {+ let new_tc = info.start_timecode;+ if align_timecode && let (Some(a), Some(b)) = (old_tc, new_tc) {+ // what was at old timecode a + t sits at new media time t + (a - b)+ shift = rate.tick_of(b - a);+ }+ m.info = info.clone();+ }+ proj.shift_media_time(p.item, shift);+ }+ Ok(())+ })?;+ for (item, path, src) in sources {+ s.media.insert_file(item, &path, src);+ }+ let gone: Vec<ItemId> = plans.iter().map(|p| p.item).collect();+ s.offline.missing.retain(|i| !gone.contains(i));+ if s.offline.missing.is_empty() {+ s.offline.prompt = false;+ }+ Ok(rows)+}++/// Other missing items that the remap (or the new file's folder) finds, checked.+fn others(s: &Session, skip: ItemId, old: &str, new: &str, o: &MatchOptions) -> Vec<Plan> {+ let remap = derive_remap(old, new);+ let new_dir = Path::new(new).parent().map(Path::to_path_buf);+ let mut out = Vec::new();+ for m in scan(&s.project, &*s.services) {+ let id = ItemId(m.item);+ if id == skip || m.status != "missing" {+ continue;+ }+ let mut tries = Vec::new();+ if let Some((f, t)) = &remap+ && let Some(p) = apply_remap(&m.path, f, t)+ {+ tries.push(p);+ }+ if let Some(d) = &new_dir {+ tries.push(d.join(&m.file_name).to_string_lossy().into_owned());+ }+ for p in tries {+ if s.services.file_size(&p).is_err() {+ continue;+ }+ if let Ok(c) = check_candidate(s, id, &p, o)+ && c.ok+ {+ out.push(Plan { item: id, cand: c });+ break;+ }+ }+ }+ out+}++/// `media.relink`: link `item` to `path` (checked unless `force`), then the others.+pub fn relink(s: &mut Session, p: &Value) -> Result<Value> {+ let item = u64_p(p, "item").map(ItemId).ok_or_else(|| bad("media.relink", "need `item`"))?;+ let path = str_p(p, "path").ok_or_else(|| bad("media.relink", "need `path`"))?.to_string();+ let force = bool_p(p, "force").unwrap_or(false);+ let o = MatchOptions::from_params(p);+ let old = match s.project.item(item).and_then(|i| i.as_media()).map(|m| m.media.clone()) {+ Some(MediaRef::File { path }) => path,+ _ => return Err(bad("media.relink", format!("item {} is not file media", item.0))),+ };+ let c = check_candidate(s, item, &path, &o)?;+ if !c.ok && !force {+ return Err(EngineError::Other(format!("{} doesn't match {}: {}", file_name(&path), file_name(&old), c.problems.join("; "))));+ }+ if c.source.is_none() && s.media.open_file(&path, &*s.services).is_err() {+ return Err(EngineError::Other(format!("{path} can't be opened")));+ }+ let mut plans = vec![Plan { item, cand: c }];+ if o.relink_others {+ plans.extend(others(s, item, &old, &path, &o));+ }+ let rows = apply(s, plans, o.align_timecode, "Link Media")?;+ Ok(json!({"relinked": rows, "remaining": s.offline.missing.iter().map(|i| i.0).collect::<Vec<_>>()}))+}++/// `media.autoRelink`: `{from, to}` remaps a folder prefix; `{folder}` searches a folder tree.+pub fn auto_relink(s: &mut Session, p: &Value) -> Result<Value> {+ let o = MatchOptions::from_params(p);+ let missing: Vec<Missing> = scan(&s.project, &*s.services).into_iter().filter(|m| m.status == "missing").collect();+ let mut plans = Vec::new();+ let mut failed = Vec::new();+ if let (Some(from), Some(to)) = (str_p(p, "from"), str_p(p, "to")) {+ for m in &missing {+ let Some(np) = apply_remap(&m.path, from, to) else { continue };+ match check_candidate(s, ItemId(m.item), &np, &o) {+ Ok(c) if c.ok => plans.push(Plan { item: ItemId(m.item), cand: c }),+ Ok(c) => failed.push(json!({"item": m.item, "path": np, "problems": c.problems})),+ Err(e) => failed.push(json!({"item": m.item, "path": np, "problems": [e.to_string()]})),+ }+ }+ } else if let Some(folder) = str_p(p, "folder") {+ let index = index_folder(Path::new(folder), 20_000);+ for m in &missing {+ let key = m.file_name.to_ascii_lowercase();+ let mut best: Option<Candidate> = None;+ for cand in index.get(&key).into_iter().flatten() {+ if let Ok(c) = check_candidate(s, ItemId(m.item), &cand.to_string_lossy(), &o)+ && c.ok+ && best.as_ref().is_none_or(|b| c.score > b.score)+ {+ best = Some(c);+ }+ }+ match best {+ Some(c) => plans.push(Plan { item: ItemId(m.item), cand: c }),+ None => failed.push(json!({"item": m.item, "path": m.path, "problems": ["no matching file found"]})),+ }+ }+ } else {+ return Err(bad("media.autoRelink", "need `from` and `to`, or `folder`"));+ }+ let rows = if plans.is_empty() { Vec::new() } else { apply(s, plans, o.align_timecode, "Link Media")? };+ refresh(s);+ Ok(json!({"relinked": rows, "failed": failed, "remaining": s.offline.missing.iter().map(|i| i.0).collect::<Vec<_>>()}))+}++/// Files under `root` by lower-case file name (breadth-first, at most `limit` files).+pub fn index_folder(root: &Path, limit: usize) -> BTreeMap<String, Vec<PathBuf>> {+ let mut out: BTreeMap<String, Vec<PathBuf>> = BTreeMap::new();+ let mut queue = std::collections::VecDeque::from([root.to_path_buf()]);+ let mut n = 0;+ while let Some(d) = queue.pop_front() {+ let Ok(rd) = std::fs::read_dir(&d) else { continue };+ let mut entries: Vec<_> = rd.filter_map(|e| e.ok()).collect();+ entries.sort_by_key(|e| e.file_name());+ for e in entries {+ let p = e.path();+ let name = e.file_name().to_string_lossy().into_owned();+ if name.starts_with('.') {+ continue;+ }+ if p.is_dir() {+ queue.push_back(p);+ } else {+ out.entry(name.to_ascii_lowercase()).or_default().push(p);+ n += 1;+ if n >= limit {+ return out;+ }+ }+ }+ }+ out+}++/// `media.search {folder, item?, exactName?}`: candidate files for one missing item (or all).+pub fn search(s: &Session, p: &Value) -> Result<Value> {+ let folder = str_p(p, "folder").ok_or_else(|| bad("media.search", "need `folder`"))?;+ let exact = bool_p(p, "exactName").unwrap_or(true);+ let o = MatchOptions::from_params(p);+ let items: Vec<ItemId> = match u64_p(p, "item") {+ Some(i) => vec![ItemId(i)],+ None => scan(&s.project, &*s.services).into_iter().filter(|m| m.status == "missing").map(|m| ItemId(m.item)).collect(),+ };+ let index = index_folder(Path::new(folder), 20_000);+ let mut out = Vec::new();+ for id in items {+ let Some(MediaRef::File { path }) = s.project.item(id).and_then(|i| i.as_media()).map(|m| m.media.clone()) else { continue };+ let fname = file_name(&path).to_ascii_lowercase();+ let stem = split_ext(&fname).0.to_string();+ let mut cands: Vec<Candidate> = Vec::new();+ for (name, paths) in &index {+ let hit = if exact { *name == fname } else { split_ext(name).0 == stem || name.contains(&stem) };+ if !hit {+ continue;+ }+ for f in paths {+ if let Ok(c) = check_candidate(s, id, &f.to_string_lossy(), &o) {+ cands.push(c);+ }+ }+ }+ cands.sort_by(|a, b| b.score.cmp(&a.score).then(a.path.cmp(&b.path)));+ out.push(json!({"item": id.0, "candidates": cands}));+ }+ Ok(json!({"results": out}))+}++/// `media.makeOffline {items?, deleteFiles?}`.+pub fn make_offline(s: &mut Session, p: &Value) -> Result<Value> {+ let items: Vec<ItemId> = match p.get("items").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(Value::as_u64).map(ItemId).collect(),+ None => u64_p(p, "item").map(|i| vec![ItemId(i)]).unwrap_or_else(|| s.state.project_selection.clone()),+ };+ let files: Vec<(ItemId, String)> = items+ .iter()+ .filter_map(|i| match s.project.item(*i).and_then(|it| it.as_media()).map(|m| &m.media) {+ Some(MediaRef::File { path }) => Some((*i, path.clone())),+ _ => None,+ })+ .collect();+ if files.is_empty() {+ return Err(bad("media.makeOffline", "select file-based media items"));+ }+ let delete = bool_p(p, "deleteFiles").unwrap_or(false);+ s.edit("Make Offline", |proj, _| {+ for (i, _) in &files {+ if let Some(m) = proj.item_mut(*i).and_then(|it| it.as_media_mut()) {+ m.offline = true;+ }+ }+ Ok(())+ })?;+ let mut deleted = Vec::new();+ if delete {+ for (_, path) in &files {+ if std::fs::remove_file(path).is_ok() {+ deleted.push(path.clone());+ }+ }+ }+ refresh(s);+ Ok(json!({"offline": files.iter().map(|f| f.0.0).collect::<Vec<_>>(), "deleted": deleted}))+}++fn status_json(s: &Session, id: ItemId) -> Option<Value> {+ let it = s.project.item(id)?;+ let m = it.as_media()?;+ let path = match &m.media {+ MediaRef::File { path } => Some(path.clone()),+ MediaRef::Generator(_) => None,+ };+ let status = match &path {+ None => "generated",+ Some(_) if m.offline => "offline",+ Some(p) if s.services.file_size(p).is_err() => "missing",+ Some(_) => match s.media.offline_status(id) {+ Some(o) if o.reason == filmcraft_render::offline::OfflineReason::Unreadable => "unreadable",+ _ => "online",+ },+ };+ let proxy = match &m.proxy {+ Some(MediaRef::File { path }) => json!({"path": path, "online": s.services.file_size(path).is_ok()}),+ _ => Value::Null,+ };+ Some(json!({+ "item": id.0,+ "name": it.name,+ "path": path,+ "status": status,+ "identity": m.identity,+ "proxy": proxy,+ }))+}++pub fn commands() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "media.findMissing",+ label: "Find Missing Media",+ menu: &[],+ shortcut: None,+ params: "{}",+ enabled: always,+ run: |s, _| {+ let list = refresh(s);+ Ok(json!({"missing": list}))+ },+ journal: false,+ },+ CommandSpec {+ id: "media.status",+ label: "Media Status",+ menu: &[],+ shortcut: None,+ params: r#"{"item":id?}"#,+ enabled: always,+ run: |s, p| {+ let ids: Vec<ItemId> = match u64_p(p, "item") {+ Some(i) => vec![ItemId(i)],+ None => s.project.items.values().filter(|i| i.as_media().is_some()).map(|i| i.id).collect(),+ };+ Ok(Value::Array(ids.into_iter().filter_map(|i| status_json(s, i)).collect()))+ },+ journal: false,+ },+ CommandSpec {+ id: "media.linkMedia",+ label: "Link Media…",+ menu: &["File"],+ shortcut: None,+ params: r#"{} (opens the Link Media dialog; agents use media.relink / media.autoRelink)"#,+ enabled: always,+ run: |s, _| {+ let list = refresh(s);+ s.offline.prompt = !list.is_empty();+ Ok(json!({"missing": list}))+ },+ journal: false,+ },+ CommandSpec {+ id: "media.relink",+ label: "Relink Media",+ menu: &[],+ shortcut: None,+ params: r#"{"item":id,"path":str,"force":bool=false,"relinkOthers":bool=true,"alignTimecode":bool=false,"match":{"fileName":bool,"extension":bool,"clipId":bool,"duration":bool,"mediaStart":bool,"metadata":bool}?}"#,+ enabled: always,+ run: relink,+ journal: true,+ },+ CommandSpec {+ id: "media.replaceFootage",+ label: "Replace Footage…",+ menu: &[],+ shortcut: None,+ params: r#"{"item":id,"path":str}"#,+ enabled: always,+ run: |s, p| {+ let mut q = p.clone();+ q["force"] = json!(true);+ q["relinkOthers"] = json!(false);+ relink(s, &q)+ },+ journal: true,+ },+ CommandSpec {+ id: "media.autoRelink",+ label: "Relink Moved Media",+ menu: &[],+ shortcut: None,+ params: r#"{"from":str,"to":str}|{"folder":str} + match options"#,+ enabled: always,+ run: auto_relink,+ journal: true,+ },+ CommandSpec {+ id: "media.search",+ label: "Search for Media",+ menu: &[],+ shortcut: None,+ params: r#"{"folder":str,"item":id?,"exactName":bool=true}"#,+ enabled: always,+ run: |s, p| search(s, p),+ journal: false,+ },+ CommandSpec {+ id: "media.makeOffline",+ label: "Make Offline…",+ menu: &["File"],+ shortcut: None,+ params: r#"{"items":[id]?,"deleteFiles":bool=false}"#,+ enabled: |s| {+ let any = s+ .state+ .project_selection+ .iter()+ .any(|i| s.project.item(*i).and_then(|x| x.as_media()).is_some_and(|m| matches!(m.media, MediaRef::File { .. })));+ if any { Ok(()) } else { Err("select file-based media in the Project panel".into()) }+ },+ run: make_offline,+ journal: true,+ },+ CommandSpec {+ id: "media.offlineAll",+ label: "Offline All",+ menu: &[],+ shortcut: None,+ params: "{} (leave every missing file offline and close the Link Media dialog)",+ enabled: always,+ run: |s, _| {+ s.offline.prompt = false;+ Ok(json!({"offline": s.offline.missing.iter().map(|i| i.0).collect::<Vec<_>>()}))+ },+ journal: false,+ },+ ]+}++/// After a project opens: find missing files and ask for them.+pub fn on_open(s: &mut Session) -> usize {+ let list = refresh(s);+ s.offline.prompt = !s.offline.missing.is_empty();+ if !s.offline.missing.is_empty() {+ s.toast(format!("{} media file(s) are missing; File ▸ Link Media… reconnects them", s.offline.missing.len()));+ }+ list.len()+}diff --git a/crates/engine/src/relink_tests.rs b/crates/engine/src/relink_tests.rsnew file mode 100644index 000000000..81c85d013--- /dev/null+++ b/crates/engine/src/relink_tests.rs@@ -0,0 +1,147 @@+//! Offline media and relinking end to end: moved media opens offline (the slate renders),+//! relinking one file finds the others by folder remap, fingerprint mismatches are refused,+//! Make Offline, folder search and undo.++use filmcraft_media::DemoScene;+use filmcraft_project::ItemId;+use filmcraft_render::offline::{OfflineReason, slate_rgba8};+use serde_json::json;++use crate::Session;+use crate::media_test_util::{frame_rgba, make_movie, psnr, session_with, tmp_dir};+use crate::relink::{apply_remap, derive_remap};++const W: u32 = 160;+const H: u32 = 90;++/// A saved project at `<root>/Project/p.fcproj` using `<root>/Media/{a,b}.mov`.+fn saved_project(root: &std::path::Path) -> (String, Vec<ItemId>) {+ let media = root.join("Media");+ std::fs::create_dir_all(&media).unwrap();+ let (a, b) = (media.join("a.mov"), media.join("b.mov"));+ make_movie(&a, DemoScene::Aurora, W, H, 12);+ make_movie(&b, DemoScene::CityNight, W, H, 12);+ let (mut s, items, _) = session_with(&[&a, &b]);+ let proj = root.join("Project");+ std::fs::create_dir_all(&proj).unwrap();+ let path = proj.join("p.fcproj").to_string_lossy().into_owned();+ s.execute("file.save", json!({"path": path})).unwrap();+ (path, items)+}++fn open(path: &str) -> Session {+ let mut s = Session::default();+ s.execute("file.open", json!({"path": path})).unwrap();+ s+}++#[test]+fn identity_and_remap_helpers() {+ let a = crate::relink::identity_of_bytes(&vec![7u8; 3 << 20]);+ let mut v = vec![7u8; 3 << 20];+ v[(3 << 20) - 5] = 1;+ let b = crate::relink::identity_of_bytes(&v);+ assert_eq!(a.size, b.size);+ assert_ne!(a.fingerprint, b.fingerprint, "a change in the last MiB changes the fingerprint");+ assert_eq!(derive_remap("/Volumes/A/shoot/day1/a.mov", "/Users/me/shoot/day1/a.mov"), Some(("/Volumes/A".into(), "/Users/me".into())));+ assert_eq!(derive_remap(r"D:\proj\media\a.mov", "/Volumes/D/proj/media/a.mov"), Some(("D:".into(), "/Volumes/D".into())));+ assert_eq!(apply_remap(r"D:\proj\media\b.mov", "D:", "/Volumes/D").as_deref(), Some("/Volumes/D/proj/media/b.mov"));+ assert_eq!(apply_remap("/Volumes/AB/x.mov", "/Volumes/A", "/x"), None, "prefix must end at a separator");+}++#[test]+fn moved_media_opens_offline_and_relinks_others_by_folder() {+ let root = tmp_dir("relink-moved");+ let (path, items) = saved_project(&root);+ let online = frame_rgba(&mut open(&path), 3, 1.0).2;+ // move the media folder+ let moved = root.join("Moved").join("Media");+ std::fs::create_dir_all(moved.parent().unwrap()).unwrap();+ std::fs::rename(root.join("Media"), &moved).unwrap();++ let mut s = Session::default();+ let r = s.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!(r["missingMedia"], json!(2), "{r}");+ assert!(s.offline.prompt, "the Link Media dialog is requested");+ let (w, h, px) = frame_rgba(&mut s, 3, 1.0);+ let slate = slate_rgba8(w, h, "a.mov", OfflineReason::Missing);+ assert!(psnr(&px, &slate) > 40.0, "offline clip renders the offline slate");+ let m = s.execute("media.findMissing", json!({})).unwrap();+ assert_eq!(m["missing"].as_array().unwrap().len(), 2);++ // link a; b follows by the derived folder remap+ let r = s.execute("media.relink", json!({"item": items[0].0, "path": moved.join("a.mov").to_string_lossy()})).unwrap();+ assert_eq!(r["relinked"].as_array().unwrap().len(), 2, "{r}");+ assert_eq!(r["remaining"], json!([]));+ assert!(!s.offline.prompt);+ assert_eq!(frame_rgba(&mut s, 3, 1.0).2, online, "relinked media renders as before the move");+ let b_path = s.project.item(items[1]).unwrap().as_media().unwrap().media.clone();+ assert_eq!(b_path, filmcraft_project::MediaRef::File { path: moved.join("b.mov").to_string_lossy().into_owned() });+ // undo brings the old (missing) paths back, and the slate with them+ s.execute("edit.undo", json!({})).unwrap();+ assert!(psnr(&frame_rgba(&mut s, 3, 1.0).2, &slate) > 40.0);+ s.execute("edit.redo", json!({})).unwrap();+ assert_eq!(frame_rgba(&mut s, 3, 1.0).2, online);+ let _ = std::fs::remove_dir_all(&root);+}++#[test]+fn auto_relink_by_prefix_and_by_folder_search() {+ let root = tmp_dir("relink-auto");+ let (path, items) = saved_project(&root);+ let dest = root.join("Archive").join("2026");+ std::fs::create_dir_all(&dest).unwrap();+ std::fs::rename(root.join("Media"), dest.join("Media")).unwrap();+ let mut s = open(&path);+ let r = s.execute("media.autoRelink", json!({"from": root.join("Media").to_string_lossy(), "to": dest.join("Media").to_string_lossy()})).unwrap();+ assert_eq!(r["relinked"].as_array().unwrap().len(), 2, "{r}");+ assert!(s.execute("media.findMissing", json!({})).unwrap()["missing"].as_array().unwrap().is_empty());++ // again, this time searching a folder tree+ let mut s = open(&path);+ let r = s.execute("media.search", json!({"folder": root.to_string_lossy(), "item": items[1].0})).unwrap();+ let c = &r["results"][0]["candidates"][0];+ assert_eq!(c["identityMatch"], json!(true), "{r}");+ let r = s.execute("media.autoRelink", json!({"folder": root.to_string_lossy()})).unwrap();+ assert_eq!(r["relinked"].as_array().unwrap().len(), 2, "{r}");+ let _ = std::fs::remove_dir_all(&root);+}++#[test]+fn fingerprint_mismatch_is_refused_unless_forced() {+ let root = tmp_dir("relink-mismatch");+ let (path, items) = saved_project(&root);+ std::fs::remove_dir_all(root.join("Media")).unwrap();+ // same name, duration, size and rate — different pictures+ let other = root.join("Other");+ std::fs::create_dir_all(&other).unwrap();+ make_movie(&other.join("a.mov"), DemoScene::Dunes, W, H, 12);+ let mut s = open(&path);+ let e = s.execute("media.relink", json!({"item": items[0].0, "path": other.join("a.mov").to_string_lossy()})).unwrap_err().to_string();+ assert!(e.contains("not the same file"), "{e}");+ assert_eq!(s.offline.missing.len(), 2, "nothing changed");+ let r =+ s.execute("media.relink", json!({"item": items[0].0, "path": other.join("a.mov").to_string_lossy(), "force": true, "relinkOthers": false})).unwrap();+ assert_eq!(r["relinked"].as_array().unwrap().len(), 1);+ assert_eq!(r["remaining"], json!([items[1].0]));+ let _ = std::fs::remove_dir_all(&root);+}++#[test]+fn make_offline_shows_the_slate_until_relinked() {+ let root = tmp_dir("relink-offline");+ let (path, items) = saved_project(&root);+ let mut s = open(&path);+ let online = frame_rgba(&mut s, 3, 1.0);+ s.execute("project.select", json!({"items": [items[0].0]})).unwrap();+ s.execute("media.makeOffline", json!({})).unwrap();+ let (w, h, px) = frame_rgba(&mut s, 3, 1.0);+ assert!(psnr(&px, &slate_rgba8(w, h, "a.mov", OfflineReason::MadeOffline)) > 40.0);+ let st = s.execute("media.status", json!({"item": items[0].0})).unwrap();+ assert_eq!(st[0]["status"], json!("offline"));+ assert!(root.join("Media/a.mov").exists(), "media stays on disk by default");+ let a = root.join("Media/a.mov").to_string_lossy().into_owned();+ s.execute("media.relink", json!({"item": items[0].0, "path": a})).unwrap();+ assert_eq!(frame_rgba(&mut s, 3, 1.0), online);+ let _ = std::fs::remove_dir_all(&root);+}diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex b25ea805f..c3a926ebc 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -279,9 +279,10 @@ fn aac_factory(_format: Format, sample_rate: u32, channels: u32, _s: &ExportSett)}-/// ProRes 422 HQ encoder: sRGB/709 RGBA8 → 10-bit limited-range BT.709 4:2:2.+/// ProRes 422 encoder (HQ unless the settings pick another flavour): sRGB/709 RGBA8 → 10-bit limited-range BT.709 4:2:2.struct ProResEncoder {enc: filmcraft_prores::Encoder,+ profile: filmcraft_prores::Profile,w: u32,h: u32,rate: FrameRate,@@ -289,7 +290,7 @@ struct ProResEncoder {impl VideoEncoder for ProResEncoder {fn sample_entry(&self) -> SampleEntry {- SampleEntry::prores(filmcraft_isobmff::FourCc(*b"apch"), self.w as u16, self.h as u16)+ SampleEntry::prores(filmcraft_isobmff::FourCc(self.profile.fourcc()), self.w as u16, self.h as u16)}fn timescale(&self) -> u32 {self.rate.num as u32@@ -332,8 +333,9 @@ pub fn rgba_to_yuv422_10(rgba: &[u8], w: usize, h: usize, y: &mut [u16], cb: &mu}fn prores_factory(format: Format, w: u32, h: u32, rate: FrameRate, _s: &ExportSettings) -> Option<Result<Box<dyn VideoEncoder>>> {+ let profile = filmcraft_prores::Profile::Hq;(format == Format::ProRes)- .then(|| Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::new(filmcraft_prores::Profile::Hq, w, h), w, h, rate }) as Box<dyn VideoEncoder>))+ .then(|| Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::new(profile, w, h), profile, w, h, rate }) as Box<dyn VideoEncoder>))}/// H.264 High (our encoder): sRGB/709 RGBA8 → 8-bit limited-range BT.709 4:2:0, VBR at thediff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rsindex a77111249..ea268b09c 100644--- a/crates/export/src/tests.rs+++ b/crates/export/src/tests.rs@@ -23,6 +23,7 @@ fn project() -> (Arc<Project>, ItemId, SourceMap) {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,)@@ -125,6 +126,7 @@ fn caption_burn_in_h264_ffmpeg_oracle() {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);diff --git a/crates/golden/tests/golden.rs b/crates/golden/tests/golden.rsindex d007c69c6..42ef44555 100644--- a/crates/golden/tests/golden.rs+++ b/crates/golden/tests/golden.rs@@ -63,6 +63,7 @@ impl Builder {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);diff --git a/crates/interchange/src/common.rs b/crates/interchange/src/common.rsindex d2adb920c..e600113dc 100644--- a/crates/interchange/src/common.rs+++ b/crates/interchange/src/common.rs@@ -258,7 +258,17 @@ pub(crate) fn media_info(name: &str, spec: &MediaSpec) -> MediaInfo {}pub(crate) fn media_clip(media: MediaRef, info: MediaInfo) -> MediaClip {- MediaClip { media, info, interpret: Interpretation::default(), mark_in: None, mark_out: None, markers: Vec::new(), offline: false, proxy: None }+ MediaClip {+ media,+ info,+ interpret: Interpretation::default(),+ mark_in: None,+ mark_out: None,+ markers: Vec::new(),+ offline: false,+ proxy: None,+ identity: None,+ }}/// The file path behind an item (following subclips), if it is file media.diff --git a/crates/interchange/tests/support/mod.rs b/crates/interchange/tests/support/mod.rsindex 33a7fabfe..43e30e68d 100644--- a/crates/interchange/tests/support/mod.rs+++ b/crates/interchange/tests/support/mod.rs@@ -46,6 +46,7 @@ pub fn media(p: &mut Project, path: &str, video: bool, audio: bool, rate: FrameRmarkers: vec![],offline: false,proxy: None,+ identity: None,}),None,)@@ -66,6 +67,7 @@ pub fn generator(p: &mut Project, name: &str, g: Generator) -> ItemId {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,)diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex b502794fd..3c0c678b8 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -164,9 +164,38 @@ pub struct MediaClip {pub mark_in: Option<Tick>,pub mark_out: Option<Tick>,pub markers: Vec<Marker>,+ /// Made offline on purpose (Make Offline / Offline All): renders the offline slate even if+ /// the file exists. Files that are merely missing are detected at run time instead (the+ /// engine's media pool), so a project whose media comes back needs no change.pub offline: bool,/// Proxy media, if attached.pub proxy: Option<MediaRef>,+ /// Size and content fingerprint of the file when it was imported (or last linked); relinking+ /// checks a candidate against it. None for generators and projects from older builds.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub identity: Option<MediaIdentity>,+}++/// What a media file looked like when it was linked: its size plus a fast content fingerprint+/// (a 64-bit hash of the size, the first MiB and the last MiB). Cheap to compute on any file and+/// enough to tell a moved original from a different file with the same name.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct MediaIdentity {+ pub size: u64,+ /// Hex-encoded in JSON (`"9f3c…"`), so the value survives JavaScript readers.+ #[serde(with = "hex_u64")]+ pub fingerprint: u64,+}++mod hex_u64 {+ use serde::{Deserialize, Deserializer, Serializer};+ pub fn serialize<S: Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {+ s.serialize_str(&format!("{v:016x}"))+ }+ pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {+ let s = String::deserialize(d)?;+ u64::from_str_radix(&s, 16).map_err(serde::de::Error::custom)+ }}impl MediaClip {@@ -870,6 +899,49 @@ impl Project {self.add_item(name, Label::Forest, ItemKind::Sequence(Box::new(seq)), bin)}+ /// Re-base an item's media time: whatever was at media time `t` is at `t - delta` afterwards+ /// (a relink with Align Timecode, a consolidated file that starts later). Moves the source+ /// in-points, frame holds and keyframes of every track item that shows the item or one of its+ /// subclips, the subclip ranges, and the clip's own marks and markers.+ pub fn shift_media_time(&mut self, item: ItemId, delta: Tick) {+ if delta == Tick::ZERO {+ return;+ }+ let mut users = vec![item];+ for it in self.items.values_mut() {+ if let ItemKind::Subclip { parent, range } = &mut it.kind+ && *parent == item+ {+ range.start -= delta;+ users.push(it.id);+ }+ }+ for it in self.items.values_mut() {+ if let ItemKind::Sequence(seq) = &mut it.kind {+ for t in seq.all_tracks_mut() {+ for ti in t.items.iter_mut().filter(|ti| users.contains(&ti.item)) {+ ti.source_in -= delta;+ if let Some(h) = &mut ti.frame_hold {+ *h -= delta;+ }+ for e in &mut ti.effects {+ for p in e.params.values_mut() {+ for k in &mut p.keyframes {+ k.time -= delta;+ }+ }+ }+ }+ }+ }+ }+ if let Some(m) = self.item_mut(item).and_then(|i| i.as_media_mut()) {+ m.mark_in = m.mark_in.map(|t| t - delta);+ m.mark_out = m.mark_out.map(|t| t - delta);+ m.markers.iter_mut().for_each(|mk| mk.start -= delta);+ }+ }+/// Build a track item for `item` placed at `start` covering `source` range (media time).pub fn make_track_item(&mut self, item: ItemId, kind: TrackKind, start: Tick, source: TimeRange, seq_rate: FrameRate) -> Option<TrackItem> {let it = self.items.get(&item)?;@@ -949,6 +1021,7 @@ mod tests {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex f221e7f44..a199cf495 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -15,6 +15,7 @@ pub mod graphic_clip;pub mod graphics;pub mod image;pub mod mixer;+pub mod offline;pub mod plan;pub mod preview;pub mod transitions;diff --git a/crates/render/src/mixer_tests.rs b/crates/render/src/mixer_tests.rsindex 154b98298..e1a1d1de9 100644--- a/crates/render/src/mixer_tests.rs+++ b/crates/render/src/mixer_tests.rs@@ -70,6 +70,7 @@ impl Rig {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);diff --git a/crates/render/src/offline.rs b/crates/render/src/offline.rsnew file mode 100644index 000000000..248670db2--- /dev/null+++ b/crates/render/src/offline.rs@@ -0,0 +1,123 @@+//! The offline slate: what a clip whose media is missing (or was made offline) shows instead of+//! its pictures. Our own design, drawn in code: a dark red field with diagonal hazard stripes, a+//! dark panel with a warning triangle, "MEDIA NOT FOUND", the file name and how to fix it.+//!+//! The slate is drawn at the size the caller asks for, so a 4K clip's slate scales with playback+//! resolution like any other frame, and it is deterministic (tests compare renders against it).++use filmcraft_geom::Vec2;+use filmcraft_text::{Align, ParagraphStyle, TextStyle, layout, render};++use crate::graphics::{paint_mask, premul_linear};+use crate::image::Image;++/// Base colour (sRGB) of the slate field and of its lighter stripes.+pub const FIELD: [u8; 3] = [0x5c, 0x10, 0x16];+const STRIPE: [u8; 3] = [0x6e, 0x17, 0x1e];+const PANEL: [f32; 4] = [0.06, 0.025, 0.03, 0.93];+const AMBER: [f32; 4] = [0.98, 0.72, 0.18, 1.0];++/// Why a clip is offline (picks the headline).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OfflineReason {+ /// The file isn't where the project says (moved, renamed, drive not mounted).+ Missing,+ /// Made offline on purpose (Make Offline / Offline All).+ MadeOffline,+ /// The file is there but couldn't be read or decoded.+ Unreadable,+}++impl OfflineReason {+ pub fn headline(self) -> &'static str {+ match self {+ OfflineReason::Missing => "MEDIA NOT FOUND",+ OfflineReason::MadeOffline => "MEDIA SET OFFLINE",+ OfflineReason::Unreadable => "MEDIA UNREADABLE",+ }+ }+}++fn srgb(c: [u8; 3]) -> [f32; 4] {+ premul_linear([c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0])+}++/// Draw the slate at `w`×`h` (premultiplied linear-light, opaque).+pub fn slate(w: usize, h: usize, file_name: &str, reason: OfflineReason) -> Image {+ let (w, h) = (w.max(1), h.max(1));+ let field = srgb(FIELD);+ let stripe = srgb(STRIPE);+ let period = (h as f32 / 9.0).max(4.0);+ let mut img = Image::new(w, h);+ for y in 0..h {+ for x in 0..w {+ // 45° stripes, half the period wide+ let d = ((x + y) as f32 / period).fract();+ let c = if d < 0.5 { stripe } else { field };+ let i = (y * w + x) * 4;+ img.px[i..i + 4].copy_from_slice(&c);+ }+ }+ let s = h as f32;+ // centre panel+ let (pw, ph) = ((w as f32 * 0.78).min(s * 1.9), s * 0.46);+ let (px0, py0) = ((w as f32 - pw) / 2.0, (s - ph) / 2.0);+ fill_path(&mut img, &filmcraft_text::Path::rect(px0, py0, px0 + pw, py0 + ph), PANEL);+ // warning triangle with a "!" (two fills: amber outline, panel-coloured inside, amber bar + dot)+ let tri_h = s * 0.13;+ let (tcx, ty0) = (w as f32 / 2.0, py0 + s * 0.045);+ let tri = |inset: f32| {+ let k = inset * 1.9;+ filmcraft_text::Path::polygon(&[+ (tcx, ty0 + k),+ (tcx + tri_h * 0.62 - k * 0.9, ty0 + tri_h - inset),+ (tcx - tri_h * 0.62 + k * 0.9, ty0 + tri_h - inset),+ ])+ };+ fill_path(&mut img, &tri(0.0), AMBER);+ fill_path(&mut img, &tri(tri_h * 0.11), [PANEL[0], PANEL[1], PANEL[2], 1.0]);+ let bar_w = (tri_h * 0.09).max(1.0);+ fill_path(&mut img, &filmcraft_text::Path::rect(tcx - bar_w / 2.0, ty0 + tri_h * 0.36, tcx + bar_w / 2.0, ty0 + tri_h * 0.70), AMBER);+ fill_path(&mut img, &filmcraft_text::Path::rect(tcx - bar_w / 2.0, ty0 + tri_h * 0.76, tcx + bar_w / 2.0, ty0 + tri_h * 0.76 + bar_w), AMBER);+ // text+ let cx = w as f32 / 2.0;+ text(&mut img, reason.headline(), "Bold", Vec2::new(cx as f64, (ty0 + tri_h + s * 0.085) as f64), s * 0.062, [1.0, 1.0, 1.0, 1.0], pw * 0.94);+ if !file_name.is_empty() {+ text(&mut img, file_name, "Regular", Vec2::new(cx as f64, (ty0 + tri_h + s * 0.15) as f64), s * 0.036, [1.0, 0.80, 0.80, 1.0], pw * 0.94);+ }+ let hint = match reason {+ OfflineReason::MadeOffline => "Link Media… brings it back",+ _ => "File ▸ Link Media… reconnects it",+ };+ text(&mut img, hint, "Regular", Vec2::new(cx as f64, (ty0 + tri_h + s * 0.205) as f64), s * 0.028, [0.85, 0.72, 0.72, 1.0], pw * 0.94);+ img+}++/// The slate as straight sRGB RGBA8 (what offline sources hand to the compositor).+pub fn slate_rgba8(w: usize, h: usize, file_name: &str, reason: OfflineReason) -> Vec<u8> {+ slate(w, h, file_name, reason).to_rgba8()+}++fn fill_path(img: &mut Image, p: &filmcraft_text::Path, color: [f32; 4]) {+ let Some(bb) = p.bounds() else { return };+ let (x0, y0) = (bb.0.floor() as i32, bb.1.floor() as i32);+ let m = filmcraft_text::raster::fill(p, (bb.2.ceil() as i32 - x0).max(1) as usize, (bb.3.ceil() as i32 - y0).max(1) as usize, -x0 as f32, -y0 as f32);+ paint_mask(img, &m, x0, y0, color, 1.0);+}++/// One line of text centred on `pos.x` with its baseline at `pos.y`, shrunk to fit `max_w`.+fn text(img: &mut Image, s: &str, style: &str, pos: Vec2, px: f32, color: [f32; 4], max_w: f32) {+ if px < 3.0 {+ return;+ }+ let mut st = TextStyle { family: filmcraft_text::fonts::DEFAULT_FAMILY.into(), style: style.into(), size: px, ..Default::default() };+ let para = ParagraphStyle { align: Align::Center, ..Default::default() };+ let mut l = layout(s, &st, ¶);+ let wid = l.bounds[2] - l.bounds[0];+ if wid > max_w && wid > 0.0 {+ st.size = px * max_w / wid;+ l = layout(s, &st, ¶);+ }+ let (m, x0, y0) = render::rasterize(&l, &render::at(pos.x as f32, pos.y as f32));+ paint_mask(img, &m, x0, y0, premul_linear(color), 1.0);+}diff --git a/crates/render/src/preview_tests.rs b/crates/render/src/preview_tests.rsindex 3acfb1ec5..c02d4e9ec 100644--- a/crates/render/src/preview_tests.rs+++ b/crates/render/src/preview_tests.rs@@ -21,6 +21,7 @@ fn add_gen(p: &mut Project, g: GeneratorSource) -> ItemId {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,)diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rsindex 4200575ab..d22ca4409 100644--- a/crates/render/src/tests.rs+++ b/crates/render/src/tests.rs@@ -22,6 +22,7 @@ fn setup() -> (Project, ItemId, ItemId, ItemId, SourceMap) {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);@@ -111,6 +112,7 @@ fn cross_dissolve_midpoint() {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);@@ -151,6 +153,7 @@ fn audio_mix_bars_tone() {markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);@@ -211,6 +214,7 @@ fn tone_with(effects: &[(&str, &[(&str, f64)])]) -> (Project, ItemId, SourceMap)markers: vec![],offline: false,proxy: None,+ identity: None,}),None,);@@ -267,3 +271,20 @@ fn audio_fx_chain_is_continuous_and_random_access_matches() {let diff = whole.iter().zip(&dry).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);assert!(diff > 1e-3, "delay had no effect");}++#[test]+fn offline_slate_is_deterministic_and_marked() {+ use crate::offline::{FIELD, OfflineReason, slate_rgba8};+ let a = slate_rgba8(640, 360, "A001_C002.mov", OfflineReason::Missing);+ assert_eq!(a, slate_rgba8(640, 360, "A001_C002.mov", OfflineReason::Missing));+ assert_ne!(a, slate_rgba8(640, 360, "A001_C002.mov", OfflineReason::MadeOffline), "the headline names the reason");+ // corners are the red field / stripes, opaque+ let px = |x: usize, y: usize| &a[(y * 640 + x) * 4..(y * 640 + x) * 4 + 4];+ assert_eq!(px(0, 359)[3], 255);+ assert!(px(0, 359)[0] >= FIELD[0] && px(0, 359)[1] <= 0x20, "{:?}", px(0, 359));+ // tiny sizes work (thumbnails)+ assert_eq!(slate_rgba8(8, 4, "x", OfflineReason::Unreadable).len(), 8 * 4 * 4);+ if let Some(p) = std::env::var_os("FILMCRAFT_SLATE_PNG") {+ ::image::save_buffer(p, &a, 640, 360, ::image::ExtendedColorType::Rgba8).unwrap();+ }+}diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex 796d6b4aa..fdb8cc7de 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -83,6 +83,8 @@ pub enum Icon {Sparkle,Grid,Square,+ /// Offline media: a broken link.+ Offline,}pub struct Pen16<'a> {@@ -490,6 +492,14 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {pen.line(&[(2.0, 10.0), (14.0, 10.0)]);}Square => pen.rect(3.0, 3.0, 13.0, 13.0),+ Offline => {+ pen.line(&[(7.0, 4.0), (4.5, 4.0), (2.5, 6.0), (2.5, 7.5), (4.0, 9.0)]);+ pen.line(&[(9.0, 12.0), (11.5, 12.0), (13.5, 10.0), (13.5, 8.5), (12.0, 7.0)]);+ pen.line(&[(5.5, 2.0), (6.5, 0.8)]);+ pen.line(&[(10.5, 14.0), (9.5, 15.2)]);+ pen.line(&[(3.0, 1.5), (3.5, 2.8)]);+ pen.line(&[(13.0, 14.5), (12.5, 13.2)]);+ }}}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 97bf22017..df6bdd559 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -54,6 +54,8 @@ pub struct HostHooks {pub shortcuts_changed: Option<Box<dyn FnMut(&[menus::MenuItem])>>,/// Open dialog for a JSON file (shortcut preset import): filter name, extensions → path.pub pick_open_file: Option<Box<dyn FnMut(&str, &[&str]) -> Option<String>>>,+ /// Folder picker (Link Media search, proxy and Project Manager destinations).+ pub pick_folder: Option<Box<dyn FnMut() -> Option<String>>>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -452,6 +454,27 @@ impl FilmcraftApp {}/// Get a thumbnail texture for an item at a media time (requested at low priority).+ /// Cache revision of a project item's own frames: media changes only when its file does+ /// (relink, Make Offline, proxies on/off), so its frames survive unrelated edits; other items+ /// (sequences) follow the project revision.+ pub fn item_revision(&self, item: filmcraft_project::ItemId) -> u64 {+ let p = &self.session.project;+ let target = match p.item(item).map(|i| &i.kind) {+ Some(filmcraft_project::ItemKind::Subclip { parent, .. }) => *parent,+ _ => item,+ };+ match p.item(target).map(|i| &i.kind) {+ Some(filmcraft_project::ItemKind::Media(m)) => {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ filmcraft_engine::media_pool::media_key(m).hash(&mut h);+ (m.proxy.is_some() && self.session.media.use_proxies()).hash(&mut h);+ h.finish()+ }+ _ => self.session.revision,+ }+ }+pub fn thumbnail(&mut self, ctx: &egui::Context, item: filmcraft_project::ItemId, t: Tick, width: u32) -> Option<(egui::TextureId, egui::Vec2)> {let pi = self.session.project.item(item)?;let src_w = match &pi.kind {@@ -461,8 +484,7 @@ impl FilmcraftApp {};let rate = pi.frame_rate();let frame = rate.frame_at(t);- // Thumbnails ignore project revision (media content doesn't change); sequences use it.- let rev = if matches!(pi.kind, filmcraft_project::ItemKind::Sequence(_)) { self.session.revision } else { 0 };+ let rev = self.item_revision(item);let key = FrameKey { target: Target::Item(item), frame, size: width, revision: rev };let name = format!("thumb-{}-{}-{}", item.0, frame, width);if let Some(img) = self.frames.get(&key) {diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 482119a56..e0dd2da9d 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -100,6 +100,12 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Valif let Some(r) = crate::panels::trim_monitor::route_transport(app, ctx, id) {return r;}+ if let Some(r) = crate::panels::media_dialogs::route(app, id, ¶ms) {+ if let Err(e) = &r {+ app.ui.status = e.clone();+ }+ return r;+ }match id {"playback.slowForward" | "playback.slowReverse" => {app.play(if id == "playback.slowForward" { 0.25 } else { -0.25 });diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex 43b7b8fea..acc2a37c5 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -4,6 +4,7 @@use crate::{Dialog, FilmcraftApp};pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {+ crate::panels::media_dialogs::show(app, ctx);let Some(d) = app.dialog else { return };if let Some(still_open) = crate::panels::file_dialogs::show(app, ctx, d) {if !still_open && app.dialog == Some(d) {diff --git a/crates/ui-egui/src/panels/media_dialogs.rs b/crates/ui-egui/src/panels/media_dialogs.rsnew file mode 100644index 000000000..c9f929564--- /dev/null+++ b/crates/ui-egui/src/panels/media_dialogs.rs@@ -0,0 +1,350 @@+//! Media management dialogs: Link Media (offline media / relink) and Make Offline.+//! Their state lives in `UiState` (serde), so agents can open and fill them as well as click them;+//! the actions run engine commands (`media.*`).+//!+//! Automation ids:+//! - Link Media: `linkMedia.row.<n>`, `linkMedia.match.<fileName|extension|clipId|duration|mediaStart|metadata>`,+//! `linkMedia.alignTimecode`, `linkMedia.relinkOthers`, `linkMedia.folder`, `linkMedia.browse`,+//! `linkMedia.exactName`, `linkMedia.search`, `linkMedia.candidate.<n>`, `linkMedia.preview`,+//! `linkMedia.link`, `linkMedia.locate`, `linkMedia.offline`, `linkMedia.offlineAll`, `linkMedia.cancel`.+//! - Make Offline: `makeOffline.keep`, `makeOffline.delete`, `makeOffline.ok`, `makeOffline.cancel`.++use egui::{Color32, RichText};+use serde_json::{Value, json};++use crate::FilmcraftApp;+use crate::state::LinkMediaDraft;++type Elems = Vec<(String, egui::Rect, String)>;++fn push(elems: &mut Elems, id: impl Into<String>, r: &egui::Response, label: impl Into<String>) {+ elems.push((id.into(), r.rect, label.into()));+}++/// Draw whichever media dialogs are open; open Link Media when a project needs it.+pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {+ if app.session.offline.prompt && app.ui.link_media.is_none() {+ app.ui.link_media = Some(LinkMediaDraft::default());+ }+ if app.ui.link_media.is_some() {+ link_media(app, ctx);+ }+ if app.ui.make_offline.is_some() {+ make_offline(app, ctx);+ }+}++/// Menu / shortcut entry points without params open a dialog. Returns None for other ids.+pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {+ let empty = params.as_object().is_none_or(|m| m.is_empty());+ if !empty {+ return None;+ }+ let enabled = |app: &FilmcraftApp, id: &str| filmcraft_engine::find_command(id).map_or(Ok(()), |c| (c.enabled)(&app.session));+ match id {+ "media.linkMedia" => {+ let r = app.session.execute("media.linkMedia", json!({})).map_err(|e| e.to_string());+ if let Ok(v) = &r+ && v["missing"].as_array().is_some_and(|a| a.is_empty())+ {+ app.ui.status = "All media is online.".into();+ return Some(r);+ }+ app.ui.link_media = Some(LinkMediaDraft::default());+ Some(r)+ }+ "media.makeOffline" => Some(enabled(app, id).map(|_| {+ app.ui.make_offline = Some(false);+ json!({"dialog": "makeOffline"})+ })),+ _ => None,+ }+}++fn missing_list(app: &FilmcraftApp) -> Vec<(u64, String, String, String, &'static str)> {+ app.session+ .offline+ .missing+ .iter()+ .filter_map(|id| {+ let it = app.session.project.item(*id)?;+ let m = it.as_media()?;+ let filmcraft_project::MediaRef::File { path } = &m.media else { return None };+ let fname = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();+ Some((id.0, it.name.clone(), fname, path.clone(), if m.offline { "Offline" } else { "Missing" }))+ })+ .collect()+}++fn match_params(d: &LinkMediaDraft) -> Value {+ json!({+ "match": {"fileName": d.file_name, "extension": d.extension, "clipId": d.clip_id, "duration": d.duration, "mediaStart": d.media_start, "metadata": d.metadata},+ "alignTimecode": d.align_timecode,+ "relinkOthers": d.relink_others,+ })+}++fn preview_texture(app: &FilmcraftApp, ctx: &egui::Context, path: &str) -> Option<egui::TextureHandle> {+ let key = egui::Id::new(("link-preview", path));+ if let Some(t) = ctx.data(|d| d.get_temp::<Option<egui::TextureHandle>>(key)) {+ return t;+ }+ let tex = app.session.media.open_file(path, &*app.session.services).ok().and_then(|src| {+ let t = filmcraft_time::Tick(src.info().duration.0 / 3);+ let f = src.video_frame(filmcraft_media::FrameRequest { time: t, scale: 0.25 }).ok()?;+ let img = egui::ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.to_rgba8());+ Some(ctx.load_texture(format!("link-preview-{path}"), img, egui::TextureOptions::LINEAR))+ });+ ctx.data_mut(|d| d.insert_temp(key, tex.clone()));+ tex+}++fn link_media(app: &mut FilmcraftApp, ctx: &egui::Context) {+ let Some(mut d) = app.ui.link_media.clone() else { return };+ let rows: Vec<_> = missing_list(app).into_iter().filter(|r| !d.skipped.contains(&r.0)).collect();+ if rows.is_empty() {+ app.ui.link_media = None;+ app.session.offline.prompt = false;+ return;+ }+ d.row = d.row.min(rows.len() - 1);+ let mut elems: Elems = Vec::new();+ let mut keep = true;+ let mut action: Option<&str> = None;+ let accent = app.tokens.accent;+ let sel_path = d.candidate.and_then(|c| d.candidates.get(c)).map(|c| c.0.clone());+ let preview = sel_path.as_deref().and_then(|p| preview_texture(app, ctx, p));+ egui::Window::new("Link Media").collapsible(false).resizable(false).default_width(760.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {+ ui.label(format!("{} clip(s) can't find their media. Locate them, search a folder, or leave them offline.", rows.len()));+ ui.add_space(6.0);+ egui::Grid::new("link-media-rows").num_columns(4).striped(true).spacing([14.0, 4.0]).show(ui, |ui| {+ for h in ["Clip Name", "File Name", "File Path", "Status"] {+ ui.label(RichText::new(h).strong());+ }+ ui.end_row();+ for (k, (_, name, fname, path, status)) in rows.iter().enumerate() {+ let r = ui.selectable_label(d.row == k, name);+ push(&mut elems, format!("linkMedia.row.{k}"), &r, name.clone());+ if r.clicked() && d.row != k {+ d.row = k;+ d.candidates.clear();+ d.candidate = None;+ }+ ui.label(fname);+ ui.label(RichText::new(path).small());+ ui.label(RichText::new(*status).color(Color32::from_rgb(0xe0, 0x5a, 0x5a)));+ ui.end_row();+ }+ });+ ui.separator();+ ui.horizontal(|ui| {+ ui.label("Match file properties:");+ for (id, label, v) in [+ ("fileName", "File Name", &mut d.file_name),+ ("extension", "File Extension", &mut d.extension),+ ("clipId", "Clip ID (fingerprint)", &mut d.clip_id),+ ("duration", "Duration", &mut d.duration),+ ("mediaStart", "Media Start", &mut d.media_start),+ ("metadata", "Frame Size / Rate", &mut d.metadata),+ ] {+ let r = ui.checkbox(v, label);+ push(&mut elems, format!("linkMedia.match.{id}"), &r, label);+ }+ });+ ui.horizontal(|ui| {+ let r = ui.checkbox(&mut d.align_timecode, "Align Timecode");+ push(&mut elems, "linkMedia.alignTimecode", &r, "Align Timecode");+ let r = ui.checkbox(&mut d.relink_others, "Relink others automatically");+ push(&mut elems, "linkMedia.relinkOthers", &r, "Relink others automatically");+ });+ ui.separator();+ ui.horizontal(|ui| {+ ui.label("Search in:");+ let r = ui.add(egui::TextEdit::singleline(&mut d.folder).desired_width(360.0).hint_text("folder"));+ push(&mut elems, "linkMedia.folder", &r, "folder");+ let r = ui.button("Browse…");+ push(&mut elems, "linkMedia.browse", &r, "Browse…");+ if r.clicked() {+ action = Some("browse");+ }+ let r = ui.checkbox(&mut d.exact_name, "Exact name matches only");+ push(&mut elems, "linkMedia.exactName", &r, "Exact name matches only");+ let r = ui.button("Search");+ push(&mut elems, "linkMedia.search", &r, "Search");+ if r.clicked() {+ action = Some("search");+ }+ });+ ui.horizontal(|ui| {+ ui.vertical(|ui| {+ ui.set_width(520.0);+ if d.candidates.is_empty() {+ ui.label(RichText::new("No candidates yet — Search a folder or Locate the file.").weak());+ }+ for (k, (path, ok, idm, problems)) in d.candidates.iter().enumerate() {+ let mark = match (ok, idm) {+ (true, Some(true)) => "✔ same file",+ (true, _) => "✔ matches",+ (false, Some(false)) => "✖ different file",+ _ => "✖",+ };+ let text = format!("{mark} {path}");+ let r = ui.selectable_label(+ d.candidate == Some(k),+ RichText::new(&text).color(if *ok { Color32::LIGHT_GREEN } else { Color32::from_rgb(0xe0, 0x8a, 0x6a) }),+ );+ let r = if problems.is_empty() { r } else { r.on_hover_text(problems) };+ push(&mut elems, format!("linkMedia.candidate.{k}"), &r, text);+ if r.clicked() {+ d.candidate = Some(k);+ }+ }+ });+ let (rect, _) = ui.allocate_exact_size(egui::vec2(192.0, 108.0), egui::Sense::hover());+ ui.painter().rect_filled(rect, 3.0, Color32::from_rgb(12, 12, 12));+ match &preview {+ Some(t) => {+ let fitted = crate::panels::monitor::fit(rect, t.size()[0] as f32, t.size()[1] as f32);+ ui.painter().image(t.id(), fitted, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);+ }+ None => {+ ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, "Preview", crate::theme::Tokens::ui(11.0), Color32::GRAY);+ }+ }+ elems.push(("linkMedia.preview".into(), rect, "preview".into()));+ });+ if !d.message.is_empty() {+ ui.colored_label(Color32::from_rgb(0xe0, 0x8a, 0x6a), &d.message);+ }+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ for (id, label) in [("offlineAll", "Offline All"), ("offline", "Offline"), ("cancel", "Cancel"), ("locate", "Locate…")] {+ let r = ui.button(label);+ push(&mut elems, format!("linkMedia.{id}"), &r, label);+ if r.clicked() {+ action = Some(id);+ }+ }+ let r = ui.add_enabled(d.candidate.is_some(), egui::Button::new(RichText::new("Link").color(Color32::WHITE)).fill(accent));+ push(&mut elems, "linkMedia.link", &r, "Link");+ if r.clicked() {+ action = Some("link");+ }+ });+ });+ for (id, r, l) in elems {+ app.auto.add(&id, r, &l);+ }+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {+ action = Some("cancel");+ }+ let (item, ..) = rows[d.row].clone();+ let relink = |app: &mut FilmcraftApp, d: &mut LinkMediaDraft, path: String| {+ let mut p = match_params(d);+ p["item"] = json!(item);+ p["path"] = json!(path);+ match app.session.execute("media.relink", p) {+ Ok(v) => {+ d.message.clear();+ d.candidates.clear();+ d.candidate = None;+ app.ui.status = format!("Linked {} clip(s)", v["relinked"].as_array().map_or(0, Vec::len));+ }+ Err(e) => d.message = e.to_string(),+ }+ };+ match action {+ Some("browse") => {+ if let Some(f) = app.hooks.pick_folder.as_mut().and_then(|f| f()) {+ d.folder = f;+ }+ }+ Some("search") => {+ let mut p = match_params(&d);+ p["folder"] = json!(d.folder);+ p["item"] = json!(item);+ p["exactName"] = json!(d.exact_name);+ match app.session.execute("media.search", p) {+ Ok(v) => {+ d.candidates = v["results"][0]["candidates"]+ .as_array()+ .map(|a| {+ a.iter()+ .map(|c| {+ let probs =+ c["problems"].as_array().map(|p| p.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();+ (c["path"].as_str().unwrap_or_default().to_string(), c["ok"] == json!(true), c["identityMatch"].as_bool(), probs)+ })+ .collect()+ })+ .unwrap_or_default();+ d.candidate = d.candidates.iter().position(|c| c.1);+ d.message = if d.candidates.is_empty() { "Nothing found with that name.".into() } else { String::new() };+ }+ Err(e) => d.message = e.to_string(),+ }+ }+ Some("locate") => {+ let exts: Vec<&str> =+ filmcraft_media::VIDEO_EXTENSIONS.iter().chain(filmcraft_media::AUDIO_EXTENSIONS).chain(filmcraft_media::STILL_EXTENSIONS).copied().collect();+ if let Some(path) = app.hooks.pick_files.as_mut().and_then(|f| f(&exts).into_iter().next()) {+ relink(app, &mut d, path);+ }+ }+ Some("link") => {+ if let Some(path) = d.candidate.and_then(|c| d.candidates.get(c)).map(|c| c.0.clone()) {+ relink(app, &mut d, path);+ }+ }+ Some("offline") => {+ d.skipped.push(item);+ d.candidates.clear();+ d.candidate = None;+ }+ Some("offlineAll") | Some("cancel") => {+ let _ = app.session.execute("media.offlineAll", json!({}));+ keep = false;+ }+ _ => {}+ }+ app.ui.link_media = keep.then_some(d);+}++fn make_offline(app: &mut FilmcraftApp, ctx: &egui::Context) {+ let Some(mut delete) = app.ui.make_offline else { return };+ let mut elems: Elems = Vec::new();+ let mut keep = true;+ let mut ok = false;+ let n = app.session.state.project_selection.len();+ egui::Window::new("Make Offline").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {+ ui.label(format!("Make {n} selected clip(s) offline. Their clips show the offline slate until you link them again."));+ let r = ui.radio(!delete, "Media files remain on disk");+ push(&mut elems, "makeOffline.keep", &r, "Media files remain on disk");+ if r.clicked() {+ delete = false;+ }+ let r = ui.radio(delete, "Media files are deleted");+ push(&mut elems, "makeOffline.delete", &r, "Media files are deleted");+ if r.clicked() {+ delete = true;+ }+ ui.horizontal(|ui| {+ let r = ui.button("Cancel");+ push(&mut elems, "makeOffline.cancel", &r, "Cancel");+ keep &= !r.clicked();+ let r = ui.button("OK");+ push(&mut elems, "makeOffline.ok", &r, "OK");+ ok = r.clicked();+ });+ });+ for (id, r, l) in elems {+ app.auto.add(&id, r, &l);+ }+ if ok {+ if let Err(e) = app.session.execute("media.makeOffline", json!({"deleteFiles": delete})) {+ app.ui.status = e.to_string();+ }+ keep = false;+ }+ app.ui.make_offline = (keep && !ctx.input(|i| i.key_pressed(egui::Key::Escape))).then_some(delete);+}diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex ccb6ec9b2..a5da86954 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -9,6 +9,7 @@ pub mod file_dialogs;pub mod graphics;pub mod import_mode;pub mod lumetri;+pub mod media_dialogs;pub mod meters;pub mod misc;pub mod mixer;diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rsindex c8272605d..362b6f2fc 100644--- a/crates/ui-egui/src/panels/monitor.rs+++ b/crates/ui-egui/src/panels/monitor.rs@@ -77,19 +77,9 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)let screen_scale = (pic.width() * ppp / frame_size.0 as f32).min(1.0);let scale = quantize_scale(res.scale().min(screen_scale.max(1.0 / 32.0)));let frame = rate.frame_at(time);- let rev = if matches!(target, Target::Item(_))- && app- .session- .project- .item(match target {- Target::Item(i) => i,- Target::Sequence(s) | Target::SequencePlan(s) => s,- })- .is_some_and(|i| !matches!(i.kind, ItemKind::Sequence(_)))- {- 0- } else {- app.session.revision+ let rev = match target {+ Target::Item(i) => app.item_revision(i),+ _ => app.session.revision,};let size_key = (scale * 1000.0) as u32;let use_gpu = which == Which::Program && app.gpu.is_some();@@ -362,7 +352,15 @@ fn transport(app: &mut FilmcraftApp, ui: &mut egui::Ui, row: Rect, which: Which)ui.painter().rect_filled(r, 4.0, t.hover);}let sz = if is_play { 16.0 } else { 14.0 };- icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(sz, sz)), icon, if resp.hovered() { t.tab_text_active } else { t.icon });+ let on = cmd == "media.toggleProxies" && app.session.media.use_proxies();+ let col = if on {+ t.accent+ } else if resp.hovered() {+ t.tab_text_active+ } else {+ t.icon+ };+ icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(sz, sz)), icon, col);if resp.clicked() {let r = match cmd {"src.markIn" => app.session.execute("markers.markIn", json!({"target": "source"})).map_err(|e| e.to_string()),diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rsindex e9bfb3241..7c40c40ae 100644--- a/crates/ui-egui/src/panels/project.rs+++ b/crates/ui-egui/src/panels/project.rs@@ -159,6 +159,51 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {}}+const OFFLINE: Color32 = Color32::from_rgb(0xe8, 0x5c, 0x5c);++/// Offline / proxy state of a project item for the badges.+struct Badge {+ offline: bool,+ offline_text: &'static str,+ proxy: bool,+ /// Proxies are enabled (the badge is lit).+ proxy_on: bool,+}++fn media_badge(app: &FilmcraftApp, it: &filmcraft_project::ProjectItem) -> Badge {+ let mut b = Badge { offline: false, offline_text: "", proxy: false, proxy_on: false };+ let target = match &it.kind {+ ItemKind::Subclip { parent, .. } => app.session.project.item(*parent),+ _ => Some(it),+ };+ let Some(m) = target.and_then(|t| t.as_media()) else { return b };+ let id = target.map(|t| t.id).unwrap_or(it.id);+ if m.offline {+ (b.offline, b.offline_text) = (true, "Offline");+ } else if app.session.offline.missing.contains(&id) {+ (b.offline, b.offline_text) = (true, "Media missing");+ } else if let Some(st) = app.session.media.offline_status(id) {+ b.offline = true;+ b.offline_text = if st.reason == filmcraft_render::offline::OfflineReason::Unreadable { "Unreadable" } else { "Media missing" };+ }+ b.proxy = m.proxy.is_some();+ b.proxy_on = app.session.media.use_proxies();+ b+}++fn paint_badges(ui: &egui::Ui, b: &Badge, at: egui::Pos2, t: &Tokens) {+ let mut x = at.x;+ if b.offline {+ icons::paint(ui.painter(), Rect::from_center_size(pos2(x + 7.0, at.y), vec2(13.0, 13.0)), Icon::Offline, OFFLINE);+ x += 18.0;+ }+ if b.proxy {+ let pr = Rect::from_min_size(pos2(x, at.y - 7.0), vec2(16.0, 14.0));+ ui.painter().rect_filled(pr, 2.0, if b.proxy_on { t.accent } else { Color32::from_gray(70) });+ ui.painter().text(pr.center(), Align2::CENTER_CENTER, "P", Tokens::ui(10.0), Color32::WHITE);+ }+}+fn columns(r: Rect) -> [f32; 4] {let w = r.width();let name_w = (w * 0.46).max(160.0);@@ -238,7 +283,10 @@ fn list_bin(ui.painter().rect_filled(Rect::from_center_size(pos2(x + 5.0, r.center().y), vec2(8.0, 12.0)), 1.5, Color32::from_rgb(lc[0], lc[1], lc[2]));icons::paint(ui.painter(), Rect::from_center_size(pos2(x + 20.0, r.center().y), vec2(14.0, 14.0)), item_icon(&it.kind), t.icon);let name_clip = ui.painter().with_clip_rect(Rect::from_min_max(r.min, pos2(cols[1] - 6.0, r.max.y)));- name_clip.text(pos2(x + 32.0, r.center().y), Align2::LEFT_CENTER, &it.name, Tokens::ui(12.0), t.text);+ let badge = media_badge(app, &it);+ let name_col = if badge.offline { OFFLINE } else { t.text };+ let nr = name_clip.text(pos2(x + 32.0, r.center().y), Align2::LEFT_CENTER, &it.name, Tokens::ui(12.0), name_col);+ paint_badges(ui, &badge, pos2(nr.max.x + 6.0, r.center().y), &t);let rate = it.frame_rate();let has_v = it.has_video();let cells = [@@ -310,6 +358,17 @@ fn item_interactions(}}});+ if matches!(kind, ItemKind::Media(m) if matches!(m.media, filmcraft_project::MediaRef::File { .. })) {+ ui.separator();+ for (label, cmd) in [("Link Media…", "media.linkMedia"), ("Make Offline…", "media.makeOffline")] {+ if ui.button(label).clicked() {+ actions.push(("project.select".into(), json!({"items": [id.0]})));+ actions.push((cmd.into(), json!({})));+ ui.close();+ }+ }+ ui.separator();+ }if ui.button("Clear").clicked() {actions.push(("project.delete".into(), json!({"items": [id.0]})));ui.close();@@ -348,6 +407,21 @@ fn icon_view(app: &mut FilmcraftApp, ui: &mut egui::Ui, root: &Bin, filter: &str} else {icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(28.0, 28.0)), item_icon(&it.kind), t.text_faint);}+ let badge = media_badge(app, &it);+ if badge.offline {+ // our own offline marker over the thumbnail: dark red band with a broken link+ let band = Rect::from_min_max(pos2(r.min.x, r.max.y - 20.0), r.max);+ ui.painter().rect_filled(band, 0.0, Color32::from_rgba_unmultiplied(0x5c, 0x10, 0x16, 230));+ icons::paint(ui.painter(), Rect::from_center_size(pos2(band.min.x + 12.0, band.center().y), vec2(13.0, 13.0)), Icon::Offline, Color32::WHITE);+ ui.painter().text(pos2(band.min.x + 24.0, band.center().y), Align2::LEFT_CENTER, badge.offline_text, Tokens::ui(10.5), Color32::WHITE);+ app.auto.add(&format!("project.item.{}.offline", id.0), band, badge.offline_text);+ }+ if badge.proxy {+ let pr = Rect::from_min_size(pos2(r.max.x - 22.0, r.min.y + 4.0), vec2(18.0, 14.0));+ ui.painter().rect_filled(pr, 2.0, if badge.proxy_on { t.accent } else { Color32::from_gray(70) });+ ui.painter().text(pr.center(), Align2::CENTER_CENTER, "P", Tokens::ui(10.0), Color32::WHITE);+ app.auto.add(&format!("project.item.{}.proxy", id.0), pr, "Proxy attached");+ }let selected = app.session.state.project_selection.contains(id);if selected {ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, t.accent), StrokeKind::Outside);diff --git a/crates/ui-egui/src/panels/trim_monitor.rs b/crates/ui-egui/src/panels/trim_monitor.rsindex 92b5e836b..d813a2a5e 100644--- a/crates/ui-egui/src/panels/trim_monitor.rs+++ b/crates/ui-egui/src/panels/trim_monitor.rs@@ -125,14 +125,15 @@ fn picture(app: &mut FilmcraftApp, ui: &mut egui::Ui, area: Rect, side: &Value,let scale = *buckets.iter().find(|b| **b >= want - 1e-4).unwrap_or(&1.0);let scale = scale.min(app.ui.program.res.scale());let size_key = (scale * 1000.0) as u32;- let key = FrameKey { target: Target::Item(item), frame, size: size_key, revision: 0 };+ let rev = app.item_revision(item);+ let key = FrameKey { target: Target::Item(item), frame, size: size_key, revision: rev };let project = app.session.project.clone();app.frames.request(key, rate.tick_of(frame), scale, &project, 0);let ctx = ui.ctx().clone();let tex = if let Some(img) = app.frames.get(&key) {Some(app.texture_for(&ctx, tex_name, key, &img))} else {- match app.frames.nearest(Target::Item(item), frame, size_key, 0, 48) {+ match app.frames.nearest(Target::Item(item), frame, size_key, rev, 48) {Some(img) => Some(app.texture_for(&ctx, tex_name, FrameKey { frame: frame - 1, ..key }, &img)),None => app.texture_existing(tex_name).map(|(id, _)| id),}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex d90aeaadb..56d157c87 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -292,6 +292,59 @@ pub struct UiState {/// Pen tool: path points placed so far (sequence pixels).#[serde(default)]pub pen_points: Vec<[f64; 2]>,+ /// Link Media dialog (open when Some).+ #[serde(default)]+ pub link_media: Option<LinkMediaDraft>,+ /// Make Offline dialog: Some(delete files?) while open.+ #[serde(default)]+ pub make_offline: Option<bool>,+}++/// File ▸ Link Media… (shown automatically when a project opens with missing media).+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct LinkMediaDraft {+ /// Selected row (index into the missing list).+ pub row: usize,+ pub file_name: bool,+ pub extension: bool,+ pub clip_id: bool,+ pub duration: bool,+ pub media_start: bool,+ pub metadata: bool,+ pub align_timecode: bool,+ pub relink_others: bool,+ /// Search: folder and "Display only exact name matches".+ pub folder: String,+ pub exact_name: bool,+ /// Search results for the selected row: (path, ok, identity match, problems).+ pub candidates: Vec<(String, bool, Option<bool>, String)>,+ pub candidate: Option<usize>,+ /// Rows the user set offline in this session of the dialog (item ids).+ pub skipped: Vec<u64>,+ pub message: String,+}++impl Default for LinkMediaDraft {+ fn default() -> Self {+ Self {+ row: 0,+ file_name: true,+ extension: true,+ clip_id: true,+ duration: true,+ media_start: false,+ metadata: true,+ align_timecode: false,+ relink_others: true,+ folder: String::new(),+ exact_name: true,+ candidates: vec![],+ candidate: None,+ skipped: vec![],+ message: String::new(),+ }+ }}/// The Audio Gain dialog (Clip ▸ Audio Gain…, G).@@ -356,6 +409,8 @@ impl Default for UiState {audio_gain: AudioGainDraft::default(),gfx_edit: None,pen_points: vec![],+ link_media: None,+ make_offline: None,}}}diff --git a/crates/ui-egui/tests/media_ui.rs b/crates/ui-egui/tests/media_ui.rsnew file mode 100644index 000000000..14b1eea29--- /dev/null+++ b/crates/ui-egui/tests/media_ui.rs@@ -0,0 +1,229 @@+//! Headless UI tests of media management: the Link Media dialog opening for a project whose media+//! moved (search a folder, link, the others follow) and the Project panel's offline markers.+//!+//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render the window offscreen with wgpu and write PNGs+//! there (`media-*.png`).++use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_engine::project::{ItemKind, Label, MediaClip, MediaRef, Project, SequenceSettings, TrackKind};+use filmcraft_media::generators::GeneratorSource;+use filmcraft_media::{DemoScene, Generator, MediaSource};+use filmcraft_time::{FrameRate, Tick, TimeRange};+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++fn tmp_dir(name: &str) -> PathBuf {+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let d = std::env::temp_dir().join(format!("filmcraft-ui-{name}-{}-{nanos}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ d+}++/// A 24 fps ProRes movie of a demo scene (our own encoder).+fn make_movie(path: &Path, scene: DemoScene, w: u32, h: u32, frames: i64) {+ let rate = FrameRate::FPS_24;+ let dur = rate.tick_of(frames);+ let src = GeneratorSource::new(Generator::Demo(scene), w, h, rate, dur);+ let clip = MediaClip {+ media: MediaRef::Generator(Generator::Demo(scene)),+ info: src.info().clone(),+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: false,+ proxy: None,+ identity: None,+ };+ let mut p = Project::new("fixture");+ let item = p.add_item("scene", Label::Iris, ItemKind::Media(clip), None);+ let seq = p.new_sequence("s", SequenceSettings { width: w, height: h, frame_rate: rate, ..Default::default() }, 1, 0, None);+ let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, dur), rate).unwrap();+ for e in &mut v.effects {+ filmcraft_engine::project::resolve_auto_points(e, (w, h), (w, h));+ }+ p.sequence_mut(seq).unwrap().video_tracks[0].items.push(v);+ let settings = filmcraft_engine::export::ExportSettings {+ format: filmcraft_engine::export::Format::ProRes,+ path: path.to_string_lossy().into_owned(),+ include_audio: false,+ ..Default::default()+ };+ let shared: filmcraft_media::SharedSource = Arc::new(src);+ let provider = move |id| (id == item).then(|| shared.clone());+ filmcraft_engine::export::export(&Arc::new(p), seq, &settings, &provider, &Default::default()).unwrap();+}++/// `<root>/p.fcproj` with a sequence of `<root>/Media/{Harbour,Night}.mov`; the media folder is+/// then moved to `<root>/Moved/Media`.+fn moved_project(root: &Path) -> String {+ let media = root.join("Media");+ std::fs::create_dir_all(&media).unwrap();+ let files = [media.join("Harbour.mov"), media.join("Night.mov")];+ make_movie(&files[0], DemoScene::OceanSunset, 640, 360, 24);+ make_movie(&files[1], DemoScene::CityNight, 640, 360, 24);+ let mut s = Session::default();+ let r = s.execute("file.import", json!({"paths": files.iter().map(|f| f.to_string_lossy()).collect::<Vec<_>>()})).unwrap();+ let items: Vec<u64> = r["items"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();+ let rate = FrameRate::FPS_24;+ let mut p = (*s.project).clone();+ let seq = p.new_sequence("Harbour Cut", SequenceSettings { width: 640, height: 360, frame_rate: rate, ..Default::default() }, 1, 1, None);+ let mut at = Tick::ZERO;+ for it in items {+ let it = filmcraft_engine::project::ItemId(it);+ let d = rate.tick_of(24);+ let mut v = p.make_track_item(it, TrackKind::Video, at, TimeRange::new(Tick::ZERO, d), rate).unwrap();+ for e in &mut v.effects {+ filmcraft_engine::project::resolve_auto_points(e, (640, 360), (640, 360));+ }+ p.sequence_mut(seq).unwrap().video_tracks[0].items.push(v);+ at += d;+ }+ s.project = Arc::new(p);+ let path = root.join("p.fcproj").to_string_lossy().into_owned();+ s.execute("file.save", json!({"path": path})).unwrap();+ std::fs::create_dir_all(root.join("Moved")).unwrap();+ std::fs::rename(&media, root.join("Moved").join("Media")).unwrap();+ path+}++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+ snapshots: Option<PathBuf>,+}++impl Driver {+ fn new(session: Session) -> Self {+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(session).with_control(rx);+ let snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(PathBuf::from);+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);+ if snapshots.is_some() {+ b = b.wgpu();+ }+ let harness = b.build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx, snapshots };+ d.frames(4);+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn call(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ return v;+ }+ }+ panic!("no reply to {method} {params}");+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let v = self.call(method, params.clone());+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");+ v["result"].clone()+ }++ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }++ fn click(&mut self, id: &str) {+ self.ok("ui.click", json!({"id": id}));+ self.frames(3);+ }++ fn ids(&mut self, prefix: &str) -> Vec<String> {+ let v = self.ok("ui.elements", json!({"prefix": prefix}));+ v.as_array().unwrap().iter().filter_map(|e| e["id"].as_str().map(str::to_string)).collect()+ }++ fn app(&mut self) -> &mut FilmcraftApp {+ self.harness.state_mut()+ }++ fn snapshot(&mut self, name: &str) {+ let Some(dir) = self.snapshots.clone() else { return };+ self.frames(3);+ let img = match self.harness.render() {+ Ok(i) => i,+ Err(e) => {+ eprintln!("snapshot {name} skipped: {e}");+ return;+ }+ };+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join(format!("{name}.png"));+ img.save(&path).unwrap();+ eprintln!("snapshot: {}", path.display());+ }+}++#[test]+fn link_media_dialog_relinks_moved_media() {+ let root = tmp_dir("link");+ let path = moved_project(&root);+ let mut s = Session::default();+ s.execute("file.open", json!({"path": path})).unwrap();+ let mut d = Driver::new(s);+ d.frames(6);+ // the dialog opened by itself, listing both clips; the Project panel marks them+ let rows = d.ids("linkMedia.row.");+ assert_eq!(rows.len(), 2, "{rows:?}");+ assert!(!d.ids("linkMedia.locate").is_empty() && !d.ids("linkMedia.offlineAll").is_empty());+ d.snapshot("media-link-dialog");+ // search the moved folder for the selected clip+ let folder = root.join("Moved").to_string_lossy().into_owned();+ d.app().ui.link_media.as_mut().unwrap().folder = folder;+ d.click("linkMedia.search");+ assert_eq!(d.ids("linkMedia.candidate.").len(), 1);+ d.frames(4);+ d.snapshot("media-link-search");+ d.click("linkMedia.link");+ d.frames(4);+ assert!(d.app().ui.link_media.is_none(), "both clips relinked (the second by folder remap), dialog closed");+ let st = d.exec("media.status", json!({}));+ assert!(st.as_array().unwrap().iter().all(|m| m["status"] == "online"), "{st}");+ let _ = std::fs::remove_dir_all(&root);+}++#[test]+fn offline_markers_in_the_project_panel() {+ let root = tmp_dir("badges");+ let path = moved_project(&root);+ let mut s = Session::default();+ s.execute("file.open", json!({"path": path})).unwrap();+ let mut d = Driver::new(s);+ d.frames(4);+ d.click("linkMedia.cancel");+ assert!(d.app().ui.link_media.is_none());+ // the Program monitor shows the offline slate; the project panel marks offline items+ d.exec("playhead.set", json!({"frame": 6}));+ d.frames(30);+ let offline_badges = d.ids("project.item.").into_iter().filter(|i| i.ends_with(".offline")).count();+ assert_eq!(offline_badges, 2, "icon-view offline markers");+ d.snapshot("media-offline-project");+ // relinking clears the markers+ d.exec("media.autoRelink", json!({"from": root.join("Media").to_string_lossy(), "to": root.join("Moved/Media").to_string_lossy()}));+ d.frames(10);+ assert_eq!(d.ids("project.item.").into_iter().filter(|i| i.ends_with(".offline")).count(), 0);+ let _ = std::fs::remove_dir_all(&root);+}diff --git a/docs/architecture.md b/docs/architecture.mdindex b53241a16..84bfd35a6 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -199,10 +199,18 @@ file ──► codecs (MP4/MOV, MKV, audio) demux + decode, GOP-aware see`audio(start, frames, rate)` in media time. Sources are `Send + Sync` and shared by monitors,thumbnails, playback and export. The engine's `MediaPool` creates one per project item, lazily,through registered openers (`codecs::openers()`: MP4/MOV, MKV/WebM, audio files).+- **Offline media and proxies.** The pool caches each item's source per reference (path, offline+ flag), so relinking and undo take effect at once. Media that can't be opened renders the offline+ slate (`render::offline`) instead of failing. With proxies enabled, an item with a proxy reads+ it through `ProxySource`, which reports the original's size. Export always uses+ `MediaPool::full_res_provider`. See [project-files.md](project-files.md#media-offline-and-relinking).- **Seeking.** `codecs::Mp4Source` seeks to the preceding sync sample and decodes forward, cachingevery frame of the GOP. Sequential playback reuses the decoder. Decoders implement`codecs::VideoDecoder`. `register_video_decoder` puts a factory in front of the built-in ones, so a- hardware decoder can take precedence.+ hardware decoder can take precedence. The GOP cache never holds its lock while decoding.+ Decoders run slices on rayon, so an export worker waiting inside a decode can pick up another+ frame of the same source. A request that finds the shared decoder busy decodes with a private+ decoder.- **Compositor.** `render` is the reference for monitors, thumbnails and export. `render::plan`turns a frame into GPU layers. Non-Normal blend modes, standard effects, adjustment layers, nestedsequences and non-dissolve transitions are rendered on the CPU for that layer or frame and handed todiff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 065034d25..b45cecbad 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -46,7 +46,9 @@ record|soloSafe|output|input|fx.<n>|send.<n>|meter|name>` (popup entries below t`timeline.track.A1.lane[.kf.<n>]`, `audioGain.<set|adjust|normalizeMax|normalizeAll|ok|cancel|peak>`.Project files, auto-save, crash recovery and preferences commands (`file.recover`, `prefs.set`, …) and their-automation ids are listed in [project-files.md](project-files.md).+automation ids are listed in [project-files.md](project-files.md). That file also lists the offline+media and relinking commands and dialog ids (`media.findMissing`,+`media.relink`, `media.autoRelink`, `media.search`, `media.makeOffline`, `media.status`, `linkMedia.*`).**Trim mode** (`crates/engine/src/trim.rs`): `trim.selectEditPoint` / `trim.selectNearest` enter trimmode (the Program monitor becomes the Trim Monitor, ids `trimMonitor.*`); `trim.monitor` returns whatdiff --git a/docs/project-files.md b/docs/project-files.mdindex 9b6dfc6ae..41938f7b0 100644--- a/docs/project-files.md+++ b/docs/project-files.md@@ -169,3 +169,63 @@ UI automation ids: `prefs.autoSave.enabled`, `prefs.autoSave.intervalMinutes`,`prefs.autoSave.recoveryIntervalSeconds`, `prefs.ok`, `prefs.cancel`, `prefs.reset`;`recovery.recover`, `recovery.later`, `recovery.discard`, `recovery.item.<n>`; `revert.yes`,`revert.no` (File ▸ Revert asks first when invoked without params).++## Media: offline and relinking++Media is referenced by path. Each imported file also records its **identity**+(`MediaClip::identity`): the size and a 64-bit fingerprint of the size, the first MiB and the last+MiB. Reading 2 MiB is cheap on any file, and it tells a moved original from a different take with+the same name. The field is optional (`skip_serializing_if`), and older builds ignore it, so it+needed no schema bump. Projects from older builds+have no identity, so relinking them skips the fingerprint check.++### Offline media++- **Opening a project** checks every file (`media.findMissing`). Missing items don't stop the open.+ They render the **offline slate** (`crates/render/src/offline.rs`, our own design: a red striped+ field, a warning triangle, "MEDIA NOT FOUND", the file name and a hint), their audio is silent,+ and the app opens the **Link Media** dialog. `file.open` returns `missingMedia`.+- **Make Offline** (`media.makeOffline {items?, deleteFiles?}`) sets `MediaClip::offline`. The clip+ then shows "MEDIA SET OFFLINE" even though the file exists, until it is linked again. Files are+ deleted only with `deleteFiles: true`.+- The media pool caches sources per item **and** per reference (path, offline flag). So relinking,+ Make Offline and undoing either take effect on the next frame.++### Link Media++| Command | |+|---|---|+| `media.findMissing` | `{missing: [{item, name, fileName, path, status: missing\|offline\|proxyMissing, duration, startTimecode}]}` |+| `media.status {item?}` | per item: `online`, `missing`, `offline`, `unreadable` or `generated`, plus identity and proxy |+| `media.linkMedia` | File ▸ Link Media… (rescans; the UI opens the dialog) |+| `media.relink {item, path, force?, relinkOthers?=true, alignTimecode?, match?}` | check, link, then the others |+| `media.autoRelink {from, to}` / `{folder}` | batch relink: a folder-prefix remap, or a search of a folder tree |+| `media.search {folder, item?, exactName?=true}` | ranked candidates with `ok`, `identityMatch`, `problems` |+| `media.replaceFootage {item, path}` | relink without checks (Replace Footage) |+| `media.offlineAll` | close the dialog and leave the rest offline |++`match` selects which properties must agree. Each defaults as shown:++- `fileName` (true): the file name stem;+- `extension` (true);+- `clipId` (true): the fingerprint; a mismatch is refused with "not the same file…";+- `duration` (true): within one frame;+- `mediaStart` (false): the start timecode;+- `metadata` (true): frame size, frame rate and audio channels.++`force: true` links regardless. **Relink others automatically** works out the folder remap from the+file just linked, by dropping the common trailing path components (`/Volumes/A/shoot/a.mov` →+`/Users/me/shoot/a.mov` gives `/Volumes/A` → `/Users/me`). It applies the remap to the other missing+files and checks each one. It also looks in the new file's folder. Windows and macOS separators both+work. **Align Timecode** keeps clips on the same timecode when the new file starts at a different+timecode: the clips' source in-points, keyframes, marks and markers move with it+(`Project::shift_media_time`). One relink, together with the files it pulls along, is one undo step.++Link Media dialog automation ids: `linkMedia.row.<n>`,+`linkMedia.match.<fileName|extension|clipId|duration|mediaStart|metadata>`, `linkMedia.alignTimecode`,+`linkMedia.relinkOthers`, `linkMedia.folder`, `linkMedia.browse`, `linkMedia.exactName`,+`linkMedia.search`, `linkMedia.candidate.<n>`, `linkMedia.preview`, `linkMedia.link`,+`linkMedia.locate`, `linkMedia.offline`, `linkMedia.offlineAll`, `linkMedia.cancel`.+Make Offline: `makeOffline.keep|delete|ok|cancel`. In the Project panel, offline items get a+broken-link badge (`project.item.<id>.offline` in Icon view).+