Skip to content

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

Merge main into M11.7–9 (relink, proxies, project manager): GopCache keeps main's continuation algorithm with a same-thread reentrancy guard (nested rayon requests decode privately instead of deadlocking); ProRes export combines profile choice with HDR signalling; project schema v6

Brandon Thomas9f4208bb0804
diff --cc ROADMAP.md
index fdbf2b86e,037b3306a..5e9b603c3
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -35,11 -35,11 +35,11 @@@ Status: ✅ done · 🟡 in progress �
| M4 | Playback | 🟡 | Audio-clock master, prefetch, J/K/L, dropped-frame stats, playback resolution | Render previews, render bar, 4K/8K tuning | 8–12 |
| M5 | Effects, keyframes, GPU | 🟡 | ~60 CPU effects, 30 transitions, keyframes + value/velocity graphs, wgpu compositor | Full ~150-effect catalogue, WGSL parity for all, masks + tracking, adjustment layers, presets, Warp Stabilizer, Morph Cut | 30–45 |
| M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 |
- | M7 | Audio | 🟡 | Mixer graph (tracks → submixes → Mix, pre/post-fader inserts and sends, latency-compensated, sample-accurate, ~6× realtime for 24 tracks × 3 effects on one core), Audio Track Mixer + Audio Clip Mixer panels, track automation (Off/Read/Latch/Touch/Write, recorded live while playing, thinned to keyframes, timeline lanes with pen editing), solo/solo-safe, channel mapping basics, peak + BS.1770 loudness meters (match ffmpeg), DSP crate with 12 clip/track effects, Audio Gain (set/adjust/normalize), Constant Power / Constant Gain / Exponential Fade | Essential Sound, 5.1 panner and multichannel buses, voice-over record, effect editor windows (EQ curve), remaining effects (multiband, convolution reverb), clip-mixer automation recording | 6–9 |
- | M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette; basic scopes | LUT import UI, colour match, colour management + HDR (PQ/HLG, log, tone mapping) | 8–12 |
+ | M7 | Audio | 🟡 | Mixer graph (tracks → submixes → Mix, pre/post-fader inserts and sends, latency-compensated, sample-accurate, ~6× realtime for 24 tracks × 3 effects on one core), Audio Track Mixer + Audio Clip Mixer panels, track automation (Off/Read/Latch/Touch/Write, recorded live while playing, thinned to keyframes, timeline lanes with pen editing), solo/solo-safe, channel mapping basics, peak + BS.1770 loudness meters (match ffmpeg), DSP crate with 16 clip/track effects, Audio Gain (set/adjust/normalize), Constant Power / Constant Gain / Exponential Fade, Essential Sound (types, Loudness auto-match, Repair incl. DeEss/DeReverb, Clarity, Creative, Ducking keyframes, presets; full Dialogue chain 22× realtime) | Music duration remix, ML speech enhancement, 5.1 panner and multichannel buses, voice-over record, effect editor windows (EQ curve), remaining effects (multiband, convolution reverb), clip-mixer automation recording | 6–9 |
+ | M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette, section bypass; Input LUT / Look LUT (.cube 1D/3D/shaper, .3dl; tetrahedral CPU + WGSL; project LUT library; built-in camera conversions); Colour Match (Oklab tonal-range statistics, skin protection, solved in Lumetri wheels); colour management: Rec. 709 / Rec. 2100 PQ / HLG working spaces + wide gamut, Interpret Footage colour space (S-Log3, V-Log, Canon Log 2/3, LogC3/4, Apple Log, D-Log from published specs), metadata auto-detect, BT.2390 tone mapping, gamut mapping, HDR export signalling (VUI/colr/mdcv/clli/SEI, ffprobe-verified); scopes incl. HDR nits waveform | Parade/histogram/HLS scopes, HDR-aware Lumetri maths, macOS EDR monitors, mastering metadata → tone-map peak, D-Log M (no published formula), HSL Secondary refine | 3–5 |
| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4) | VP9 frame threading, Ogg Opus files, AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |
| M10 | Graphics & captions | 🟡 | Caption tracks (Subtitle/CEA-608/708/Teletext formats, track style), SRT/WebVTT/SCC import+export (frame-exact, property-tested), caption editing (add/split/merge/trim/move, sync-locked insert/extract), Text panel Captions tab, burn-in in Program monitor and export; text engine (`crates/text`: bundled + system fonts, harfrust shaping, bidi, line breaking, paragraph layout, glyph cache; 3-line 1080p title ≈ 0.15 ms warm); graphic clips with text + shape layers (fill, 2 strokes, background, shadow, keyframable transform), Type tool with on-monitor editing, shape/pen tools, Properties/Essential Graphics editor, align/distribute | Responsive design pins, rolls/crawls, per-character styles, motion graphics templates, MCC/STL/TTML, 608/708 embedding, speech-to-text | 12–18 |
-| M11 | Interchange & project management | 🟡 | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO | Relink/offline, project manager, proxies | 8 |
+| M11 | Interchange & project management | ✅ | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO; offline media (own slate) + Link Media (fingerprint-checked relink, folder remap, search, Align Timecode, Make Offline); proxies (ProRes Proxy/LT, H.264 ¼/½ background jobs, attach/detach/reconnect, monitor toggle, export full-res) + ingest (copy/transcode/proxies); Project Manager (collect, consolidate + transcode with handles, size estimate) | Rename media to clip names, image-sequence conversion, Media Browser-driven relink, smart (cross-drive) path tracking | 1–2 |
| M12–M16 | Web (WASM), platform, long tail | 🟡 | L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), ~850 remaining commands and dialogs, performance hardening | 40–65 |
## Running now
@@@ -48,7 -48,9 +48,10 @@@
## Log
+- **2026-10-01 (evening):** M11 done: offline media with our own slate and the Link Media dialog (fingerprint-checked relink, folder remap, search), proxies (create in background / attach / toggle; export stays full-res) with ingest settings, Project Manager (collect, consolidate + transcode). Fixed: GOP cache deadlock when a rayon decoder inside a parallel export re-entered the same source.
+ - **2026-10-01 (M7.4):** Essential Sound panel: Dialogue/Music/SFX/Ambience types, Loudness auto-match (BS.1770, exact to the target), Repair (noise, rumble, hum, new DeEsser and spectral DeReverb), Clarity (dynamics, EQ presets, Enhance Speech DSP chain), Creative reverb / stereo width, ducking that writes Volume keyframes, presets; all `essentialSound.*` commands, effects visible and keyframable in Effect Controls.
+ - **2026-10-01 (night):** M8 colour: camera log curves and gamuts from published specs, colour-managed pipeline (PQ/HLG working spaces, Interpret Footage, BT.2390 tone mapping), HDR export signalling verified with ffprobe, LUTs (.cube/.3dl, tetrahedral CPU + WGSL, project library, Lumetri Input LUT / Look), Colour Match, Lumetri section bypass, HDR scopes.
+
- **2026-10-01 (later):** text engine (shaping, bidi, line breaking) + Type/Shape/Pen tools + graphic clips + graphics panel; Trim Monitor + dynamic trimming; Keyboard Shortcuts editor; audio mixer with automation. Fixed: MP4 muxer wrote unreadable all-empty sample tables; system font scan race.
- **2026-10-01:** Audio mixing (M7.2/M7.5/M7.6 basics): mixer graph with submixes, sends, inserts and latency compensation; Audio Track / Clip Mixer panels; Latch/Touch/Write automation recorded live; timeline track keyframes; Audio Gain dialog.
diff --cc crates/codecs/src/gop.rs
index 051a337ad,34a603882..5e0b038be
--- a/crates/codecs/src/gop.rs
+++ b/crates/codecs/src/gop.rs
@@@ -33,10 -86,8 +86,37 @@@ 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,
+ }
+
++thread_local! {
++ /// Caches whose lock this thread holds while decoding (see [`GopCache::frame`]).
++ static DECODING: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
++}
++
++/// Marks a cache as decoding on this thread until dropped (also on early return / `?`).
++struct DecodingGuard(usize);
++
++impl DecodingGuard {
++ fn enter(cache: usize) -> Self {
++ DECODING.with(|d| d.borrow_mut().push(cache));
++ Self(cache)
++ }
++ fn active(cache: usize) -> bool {
++ DECODING.with(|d| d.borrow().contains(&cache))
++ }
++}
++
++impl Drop for DecodingGuard {
++ fn drop(&mut self) {
++ DECODING.with(|d| {
++ let mut d = d.borrow_mut();
++ if let Some(k) = d.iter().rposition(|&c| c == self.0) {
++ d.remove(k);
++ }
++ });
++ }
+}
+
/// Decoder + decoded-frame cache for one video track.
pub struct GopCache {
state: Mutex<State>,
@@@ -45,21 -96,47 +125,52 @@@
budget: usize,
}
+ /// The cache always has room for this many frames, whatever their size: a frame-threaded decoder
+ /// runs up to ~2x its thread count ahead of the frame it returns, and playback prefetches ahead
+ /// of the playhead, so a byte budget alone would evict 4K frames before they are shown and force
+ /// a re-decode from the keyframe.
+ const MIN_FRAMES: usize = 64;
+
+ /// A running decoder up to this many samples before the wanted sample's sync sample keeps going
+ /// rather than restarting at the sync sample.
+ const CONTINUE_THROUGH: usize = 48;
+
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, busy: false }), explicit_color, budget: 384 << 20 }
+ Self {
+ state: Mutex::new(State {
+ decoder: None,
+ intra: false,
+ spare: Vec::new(),
+ next: usize::MAX,
+ start: 0,
+ out_max: i64::MIN,
+ frames: BTreeMap::new(),
+ bytes: 0,
+ }),
+ explicit_color,
+ budget: 384 << 20,
+ }
}
-- fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame) {
++ /// Colour signalled by the container wins over the bitstream's (YUV frames only).
++ fn apply_color(&self, f: &mut VideoFrame) {
if let Some(c) = self.explicit_color
&& !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_) | filmcraft_frame::PixelData::RgbaF32(_))
{
f.color = c;
}
++ }
++
++ fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame) {
++ self.apply_color(&mut f);
+ let budget = self.budget.max(MIN_FRAMES * f.byte_size());
st.bytes += f.byte_size();
- st.frames.insert(pts, Arc::new(f));
+ if let Some(old) = st.frames.insert(pts, Arc::new(f)) {
+ st.bytes -= old.byte_size();
+ }
// evict frames far from the most recent (keep a window around the working position)
- while st.bytes > self.budget && st.frames.len() > 2 {
+ while st.bytes > budget && st.frames.len() > 2 {
let first = *st.frames.keys().next().expect("non-empty");
let last = *st.frames.keys().next_back().expect("non-empty");
let victim = if pts - first > last - pts { first } else { last };
@@@ -69,45 -147,87 +181,97 @@@
}
}
+ /// Store decoder output (in presentation order) and advance `out_max`.
+ fn store_output(&self, st: &mut State, out: Vec<crate::video::DecodedFrame>) {
+ for d in out {
+ st.out_max = st.out_max.max(d.pts);
+ self.store(st, d.pts, d.frame);
+ }
+ }
+
/// 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.
++ /// Decoders may run slices on rayon, and a rayon thread waiting inside a decode can pick up
++ /// another render job that asks this same source for a frame — on the thread that holds this
++ /// cache's lock. Such a nested request must not lock again (deadlock): it decodes the frame
++ /// with a private decoder instead ([`Self::private_frame`]).
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()))?;
let want_pts = s.pts(i);
++ let me = self as *const Self as usize;
++ if DecodingGuard::active(me) {
++ return self.private_frame(s, i, want_pts, n);
++ }
let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
++ let _decoding = DecodingGuard::enter(me);
if let Some(f) = st.frames.get(&want_pts) {
+ HITS.fetch_add(1, Ordering::Relaxed);
return Ok(f.clone());
}
- 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;
+ MISSES.fetch_add(1, Ordering::Relaxed);
+ if st.decoder.is_none() {
+ let d = s.make_decoder()?;
+ st.intra = d.intra_only();
+ st.decoder = Some(d);
+ st.next = usize::MAX;
+ }
+ // Nothing cached: the work ahead (possibly a seek and a GOP of decoding) is only worth it
+ // while someone still wants the frame.
+ if filmcraft_media::cancel::cancelled() {
+ return Err(CodecError::Cancelled);
+ }
+ if st.intra {
+ return self.intra_frame(st, s, i, want_pts);
+ }
+ let mut key = s.sync_before(i);
+ // Continue the running decoder when it has passed the wanted sample's sync sample and
+ // either has not reached the sample yet or has been fed it without outputting it yet
+ // (a frame-threaded decoder holds many pictures in flight). Otherwise the frame was
+ // evicted or lies in another GOP: restart at the sync sample.
+ let running = st.next != usize::MAX && st.next <= n;
+ // Decoding on through a short stretch into the next GOP is cheaper than a restart, and
+ // playback wants those frames anyway.
+ let near = st.next <= key && key - st.next <= CONTINUE_THROUGH;
+ let continuing = running && (st.next > key || near) && (i >= st.next || (st.start <= i && want_pts > st.out_max));
+ if !continuing {
+ SEEKS.fetch_add(1, Ordering::Relaxed);
+ // 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) {
+ break;
+ }
+ key = s.sync_before(key - 1);
}
- 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 };
+ if let Some(d) = st.decoder.as_mut() {
+ d.reset();
+ }
+ st.next = key;
+ st.start = key;
+ st.out_max = i64::MIN;
}
- let out = decoded?;
- for d in out {
- self.store(&mut st, d.pts, d.frame);
+ let limit = (i.max(st.next) + 64).min(n);
+ while st.next < limit {
+ if filmcraft_media::cancel::cancelled() {
+ // The decoder state stays consistent (`next`, `out_max`): a later request continues.
+ return Err(CodecError::Cancelled);
+ }
+ let k = st.next;
+ let data = s.read(k)?;
+ let out = st.decoder.as_mut().expect("decoder").decode(&data, s.pts(k))?;
+ st.next += 1;
+ DECODED.fetch_add(1, Ordering::Relaxed);
+ self.store_output(&mut st, out);
+ if st.frames.contains_key(&want_pts) {
+ break;
+ }
+ }
+ if !st.frames.contains_key(&want_pts) {
+ let out = st.decoder.as_mut().expect("decoder").flush();
+ self.store_output(&mut st, out);
+ st.next = usize::MAX;
}
// nearest decoded frame at or before the wanted pts (robust to decoder pts quirks)
st.frames
@@@ -116,50 -236,187 +280,249 @@@
.or_else(|| st.frames.range(..=want_pts).next_back().map(|(_, f)| f.clone()))
.ok_or_else(|| CodecError::Decode("frame not produced".into()))
}
+
++ /// A nested request (see [`Self::frame`]): decode from the sync sample with a fresh decoder,
++ /// without touching the shared state.
++ fn private_frame(&self, s: &dyn VideoSamples, i: usize, want_pts: i64, n: usize) -> crate::Result<Arc<VideoFrame>> {
++ let mut d = s.make_decoder()?;
++ let mut next = usize::MAX;
++ let out = Self::decode_to(s, d.as_mut(), &mut next, i, want_pts, n)?;
++ let mut f = out
++ .into_iter()
++ .filter(|p| p.pts <= want_pts)
++ .max_by_key(|p| p.pts)
++ .map(|p| p.frame)
++ .ok_or_else(|| CodecError::Decode("frame not produced".into()))?;
++ self.apply_color(&mut f);
++ Ok(Arc::new(f))
++ }
++
+ /// 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 = *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 d.is_random_access(&data) != Some(false) {
+ break;
+ }
+ key = s.sync_before(key - 1);
+ }
+ d.reset();
+ *next = key;
+ }
+ let limit = (i + 64).min(n);
+ let mut out = Vec::new();
+ let mut found = false;
+ while *next < limit {
+ let k = *next;
+ let data = s.read(k)?;
+ 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 !found {
+ out.extend(d.flush());
+ *next = usize::MAX;
+ }
+ Ok(out)
+ }
+
+ /// Intra-only streams: decode the one sample outside the lock, so several frame workers
+ /// decode different frames of the same source at once.
+ fn intra_frame(&self, st: std::sync::MutexGuard<'_, State>, s: &dyn VideoSamples, i: usize, want_pts: i64) -> crate::Result<Arc<VideoFrame>> {
+ let mut st = st;
+ let spare = st.spare.pop();
+ drop(st);
+ let mut dec = match spare {
+ Some(d) => d,
+ None => s.make_decoder()?,
+ };
+ let res = s.read(i).and_then(|data| {
+ DECODED.fetch_add(1, Ordering::Relaxed);
+ dec.decode(&data, want_pts)
+ });
+ let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ if st.spare.len() < 16 {
+ st.spare.push(dec);
+ }
+ for d in res? {
+ self.store(&mut st, d.pts, d.frame);
+ }
+ 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()))
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use crate::video::DecodedFrame;
+ use std::collections::VecDeque;
+ use std::sync::atomic::AtomicUsize;
+
+ /// `n` samples, a sync sample every `gop`, pts = 1000 · index (no reordering).
+ struct Samples {
+ n: usize,
+ gop: usize,
+ delay: usize,
+ intra: bool,
+ resets: Arc<AtomicUsize>,
+ decodes: Arc<AtomicUsize>,
+ }
+
+ /// Outputs each picture `delay` samples late, like a frame-threaded decoder.
+ struct Dec {
+ delay: usize,
+ intra: bool,
+ held: VecDeque<i64>,
+ resets: Arc<AtomicUsize>,
+ decodes: Arc<AtomicUsize>,
+ }
+
+ fn picture(pts: i64) -> DecodedFrame {
+ let i = (pts / 1000) as u32;
+ DecodedFrame { pts, frame: VideoFrame::rgba8(1, 1, vec![i as u8, (i >> 8) as u8, 0, 255]) }
+ }
+
+ impl VideoDecoder for Dec {
+ fn decode(&mut self, _sample: &[u8], pts: i64) -> crate::Result<Vec<DecodedFrame>> {
+ self.decodes.fetch_add(1, Ordering::Relaxed);
+ self.held.push_back(pts);
+ let mut out = Vec::new();
+ while self.held.len() > self.delay {
+ out.push(picture(self.held.pop_front().expect("held")));
+ }
+ Ok(out)
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ self.held.drain(..).map(picture).collect()
+ }
+ fn reset(&mut self) {
+ self.resets.fetch_add(1, Ordering::Relaxed);
+ self.held.clear();
+ }
+ fn name(&self) -> &str {
+ "test"
+ }
+ fn intra_only(&self) -> bool {
+ self.intra
+ }
+ }
+
+ impl VideoSamples for Samples {
+ fn count(&self) -> usize {
+ self.n
+ }
+ fn pts(&self, i: usize) -> i64 {
+ i as i64 * 1000
+ }
+ fn sync_before(&self, i: usize) -> usize {
+ if self.intra { i } else { i / self.gop * self.gop }
+ }
+ fn sample_at(&self, t: i64) -> Option<usize> {
+ let i = (t / 1000) as usize;
+ (i < self.n).then_some(i)
+ }
+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
+ Ok(vec![i as u8])
+ }
+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
+ Ok(Box::new(Dec { delay: self.delay, intra: self.intra, held: VecDeque::new(), resets: self.resets.clone(), decodes: self.decodes.clone() }))
+ }
+ }
+
+ fn samples(n: usize, gop: usize, delay: usize, intra: bool) -> Samples {
+ Samples { n, gop, delay, intra, resets: Default::default(), decodes: Default::default() }
+ }
+
+ fn index_of(f: &VideoFrame) -> usize {
+ match &f.data {
+ filmcraft_frame::PixelData::Rgba8(d) => d[0] as usize | (d[1] as usize) << 8,
+ _ => unreachable!(),
+ }
+ }
+
+ #[test]
+ fn frames_held_by_a_threaded_decoder_do_not_restart_it() {
+ // 24 pictures in flight (more than any fixed look-ahead margin), one long GOP.
+ let s = samples(300, 250, 24, false);
+ let c = GopCache::new(None);
+ // Playback order with prefetch running ahead: a later frame first, then earlier ones the
+ // decoder has been fed but not output yet.
+ for i in [10usize, 11, 40, 12, 30, 13, 60, 14, 15] {
+ assert_eq!(index_of(&c.frame(&s, i as i64 * 1000).expect("frame")), i);
+ }
+ assert_eq!(s.resets.load(Ordering::Relaxed), 1, "only the first request seeks");
+ assert!(s.decodes.load(Ordering::Relaxed) <= 60 + 24 + 1);
+ }
+
+ #[test]
+ fn running_decoder_continues_through_a_nearby_sync_sample() {
+ let s = samples(200, 30, 0, false);
+ let c = GopCache::new(None);
+ assert_eq!(index_of(&c.frame(&s, 25_000).expect("frame")), 25);
+ // frame 40 lies in the next GOP (sync sample 30): decode 26..40 instead of restarting at 30
+ assert_eq!(index_of(&c.frame(&s, 40_000).expect("frame")), 40);
+ assert_eq!(index_of(&c.frame(&s, 28_000).expect("frame")), 28);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 1);
+ // far ahead: restart at the sync sample rather than decode everything in between
+ assert_eq!(index_of(&c.frame(&s, 150_000).expect("frame")), 150);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 2);
+ assert!(s.decodes.load(Ordering::Relaxed) <= 41 + 1);
+ }
+
+ #[test]
+ fn intra_frames_decode_in_parallel_once_each() {
+ let s = Arc::new(samples(64, 1, 0, true));
+ let c = Arc::new(GopCache::new(None));
+ std::thread::scope(|scope| {
+ for t in 0..4usize {
+ let (s, c) = (s.clone(), c.clone());
+ scope.spawn(move || {
+ for k in 0..64usize {
+ let i = (k * 7 + t * 16) % 64;
+ assert_eq!(index_of(&c.frame(&*s, i as i64 * 1000).expect("frame")), i);
+ }
+ });
+ }
+ });
+ // a frame two threads miss at the same moment may decode twice; nothing more
+ assert!(s.decodes.load(Ordering::Relaxed) <= 64 + 4 * 4);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 0);
+ }
+
+ #[test]
+ fn cancelled_request_stops_decoding_and_keeps_state() {
+ let s = samples(300, 250, 0, false);
+ let c = GopCache::new(None);
+ assert_eq!(index_of(&c.frame(&s, 5_000).expect("frame")), 5);
+ let flag = Arc::new(std::sync::atomic::AtomicBool::new(true));
+ let r = filmcraft_media::cancel::with_cancel(&flag, || c.frame(&s, 200_000));
+ assert!(matches!(r, Err(CodecError::Cancelled)));
+ assert_eq!(s.decodes.load(Ordering::Relaxed), 6);
+ // cached frames are still served, and the decoder carries on from where it was
+ let r = filmcraft_media::cancel::with_cancel(&flag, || c.frame(&s, 3_000));
+ assert_eq!(index_of(&r.expect("cached")), 3);
+ assert_eq!(index_of(&c.frame(&s, 7_000).expect("frame")), 7);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 1);
+ }
}
diff --cc crates/engine/src/autosave.rs
index 05c2355e6,64c154b80..6c1327ccb
--- a/crates/engine/src/autosave.rs
+++ b/crates/engine/src/autosave.rs
@@@ -104,18 -104,23 +104,33 @@@ pub struct Preferences
pub audio: AudioPrefs,
pub playback: PlaybackPrefs,
pub trim: TrimPrefs,
+ pub media: MediaPrefs,
+ pub essential_sound: EssentialSoundPrefs,
}
+/// Preferences ▸ Media.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct MediaPrefs {
+ /// "Enable proxies": playback and monitors read attached proxies (the monitors' Toggle
+ /// Proxies button). Export always uses full-resolution media.
+ pub enable_proxies: bool,
+}
+
+ /// Essential Sound: user presets saved from the panel (built-in presets live in
+ /// `filmcraft_project::essential`).
+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase", default)]
+ pub struct EssentialSoundPrefs {
+ pub user_presets: Vec<UserSoundPreset>,
+ }
+
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub struct UserSoundPreset {
+ pub name: String,
+ pub settings: filmcraft_project::EssentialSound,
+ }
+
/// Preferences ▸ Audio (the mixer-automation part) and the Track Mixer panel-menu toggle.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
diff --cc crates/engine/src/commands.rs
index 464205871,6dc4fa6a4..26e315515
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@@ -1863,11 -1855,10 +1869,13 @@@ fn build() -> Vec<CommandSpec>
];
v.extend(crate::captions::commands());
v.extend(crate::mixer::commands());
+ v.extend(crate::essential_sound::commands());
+ v.extend(crate::color::commands());
v.extend(crate::graphics::commands());
v.extend(crate::shortcuts::commands());
+ v.extend(crate::relink::commands());
+ v.extend(crate::proxies::commands());
+ v.extend(crate::project_manager::commands());
// Labels as individual commands (Edit ▸ Label ▸ <name>)
for l in Label::ALL {
let _ = l;
@@@ -1893,7 -1884,8 +1901,9 @@@ fn export_media(s: &mut Session, p: &Va
bitrate_kbps: u64_p(p, "bitrateKbps").unwrap_or(20_000) as u32,
burn_captions: bool_p(p, "burnCaptions").unwrap_or(false),
part_of_batch: false,
+ prores_profile: str_p(p, "proresProfile").unwrap_or_default().to_string(),
+ sdr: bool_p(p, "sdr").unwrap_or(false),
+ ..Default::default()
};
let id = s.jobs.len() as u64 + 1;
let job = crate::Job {
diff --cc crates/engine/src/lib.rs
index b242f901e,15cea6811..391f4d00a
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -604,10 -566,12 +615,14 @@@ pub fn media_duration(p: &Project, _poo
#[cfg(test)]
mod autosave_tests;
#[cfg(test)]
+ mod color_tests;
+ #[cfg(test)]
+ mod essential_sound_tests;
+ #[cfg(test)]
mod file_tests;
#[cfg(test)]
+mod media_test_util;
+#[cfg(test)]
mod mixer_tests;
#[cfg(test)]
mod previews_tests;
diff --cc crates/export/src/lib.rs
index 4cece607c,5e1cc5806..0119aaa97
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@@ -101,9 -101,59 +101,62 @@@ pub struct ExportSettings
/// `progress.total`, `finished` and the final status; this call only adds to `done`.
#[serde(default)]
pub part_of_batch: bool,
+ /// ProRes flavour: `proxy`, `lt`, `standard` or `hq` (empty = HQ).
+ #[serde(default)]
+ pub prores_profile: String,
+ /// Encode display-referred SDR (Rec. 709, tone mapped) even when the sequence works in
+ /// Rec. 2100 PQ/HLG. Otherwise H.264 and ProRes exports of an HDR sequence are encoded in the
+ /// sequence's HDR space and signal it (VUI / `colr` / `mdcv` / `clli` / SEI).
+ #[serde(default)]
+ pub sdr: bool,
+ /// Colour signalling chosen by [`export`] for the encoders (not set by callers).
+ #[serde(skip)]
+ pub signal: ColorSignal,
+ }
+
+ /// Colour description of the encoded stream (ITU-T H.273 code points).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub struct ColorSignal {
+ pub primaries: u8,
+ pub transfer: u8,
+ pub matrix: u8,
+ }
+
+ impl Default for ColorSignal {
+ fn default() -> Self {
+ ColorSignal { primaries: 1, transfer: 1, matrix: 1 }
+ }
+ }
+
+ impl ColorSignal {
+ pub const PQ: ColorSignal = ColorSignal { primaries: 9, transfer: 16, matrix: 9 };
+ pub const HLG: ColorSignal = ColorSignal { primaries: 9, transfer: 18, matrix: 9 };
+ pub fn is_hdr(&self) -> bool {
+ matches!(self.transfer, 16 | 18)
+ }
+ /// (Kr, Kb) of the matrix.
+ pub fn kr_kb(&self) -> (f32, f32) {
+ if self.matrix == 9 { (0.2627, 0.0593) } else { (0.2126, 0.0722) }
+ }
+ /// Sample-entry boxes: `colr` (nclx for MP4, nclc for MOV) plus `mdcv`/`clli` for PQ
+ /// (mastering display BT.2020/D65, 1000/0.0001 cd/m²; MaxCLL/MaxFALL 0 = unknown).
+ pub fn apply_to(&self, e: &mut SampleEntry, mov: bool) {
+ if !self.is_hdr() {
+ return;
+ }
+ if let Some(v) = e.video.as_mut() {
+ let (p, t, m) = (self.primaries as u16, self.transfer as u16, self.matrix as u16);
+ v.color = Some(if mov {
+ filmcraft_isobmff::ColorInfo::Nclc { primaries: p, transfer: t, matrix: m }
+ } else {
+ filmcraft_isobmff::ColorInfo::Nclx { primaries: p, transfer: t, matrix: m, full_range: false }
+ });
+ if self.transfer == 16 {
+ v.mastering_display = Some(filmcraft_isobmff::MasteringDisplay::bt2020(1000.0, 0.0001));
+ v.content_light = Some((0, 0));
+ }
+ }
+ }
}
impl Default for ExportSettings {
@@@ -118,7 -168,8 +171,9 @@@
bitrate_kbps: 20_000,
burn_captions: false,
part_of_batch: false,
+ prores_profile: String::new(),
+ sdr: false,
+ signal: ColorSignal::default(),
}
}
}
@@@ -294,7 -347,9 +352,9 @@@ struct ProResEncoder
impl VideoEncoder for ProResEncoder {
fn sample_entry(&self) -> SampleEntry {
- SampleEntry::prores(filmcraft_isobmff::FourCc(self.profile.fourcc()), self.w as u16, self.h as u16)
- let mut e = SampleEntry::prores(filmcraft_isobmff::FourCc(*b"apch"), self.w as u16, self.h as u16);
++ let mut e = SampleEntry::prores(filmcraft_isobmff::FourCc(self.profile.fourcc()), self.w as u16, self.h as u16);
+ self.signal.apply_to(&mut e, true);
+ e
}
fn timescale(&self) -> u32 {
self.rate.num as u32
@@@ -336,21 -397,41 +402,53 @@@ pub fn rgba_to_yuv422_10(rgba: &[u8], w
});
}
+/// The ProRes profile named by [`ExportSettings::prores_profile`].
+pub fn prores_profile(name: &str) -> filmcraft_prores::Profile {
+ use filmcraft_prores::Profile;
+ match name.to_ascii_lowercase().as_str() {
+ "proxy" => Profile::Proxy,
+ "lt" => Profile::Lt,
+ "standard" | "422" => Profile::Standard,
+ _ => Profile::Hq,
+ }
+}
+
+ /// Limited-range 10-bit 4:2:2 from encoded R'G'B' floats with matrix (Kr, Kb).
+ #[allow(clippy::too_many_arguments)]
+ pub fn rgbf_to_yuv422_10(rgb: &[f32], w: usize, h: usize, kr: f32, kb: f32, y: &mut [u16], cb: &mut [u16], cr: &mut [u16]) {
+ let cw = w.div_ceil(2);
+ debug_assert!(rgb.len() >= w * h * 3 && y.len() >= w * h);
+ let kg = 1.0 - kr - kb;
+ let (sb, sr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr));
+ y.par_chunks_mut(w).zip(cb.par_chunks_mut(cw).zip(cr.par_chunks_mut(cw))).enumerate().for_each(|(row, (yr, (cbr, crr)))| {
+ let src = &rgb[row * w * 3..(row + 1) * w * 3];
+ let mut us = vec![0f32; w];
+ let mut vs = vec![0f32; w];
+ for x in 0..w {
+ let (r, g, b) = (src[x * 3], src[x * 3 + 1], src[x * 3 + 2]);
+ let yy = kr * r + kg * g + kb * b;
+ yr[x] = (64.0 + 876.0 * yy).round().clamp(4.0, 1019.0) as u16;
+ us[x] = (b - yy) / sb;
+ vs[x] = (r - yy) / sr;
+ }
+ for cx in 0..cw {
+ let a = cx * 2;
+ let b2 = (a + 1).min(w - 1);
+ cbr[cx] = (512.0 + 896.0 * (us[a] + us[b2]) * 0.5).round().clamp(4.0, 1019.0) as u16;
+ crr[cx] = (512.0 + 896.0 * (vs[a] + vs[b2]) * 0.5).round().clamp(4.0, 1019.0) as u16;
+ }
+ });
+ }
+
fn prores_factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSettings) -> Option<Result<Box<dyn VideoEncoder>>> {
- let profile = prores_profile(&s.prores_profile);
- (format == Format::ProRes)
- .then(|| Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::new(profile, w, h), profile, w, h, rate }) as Box<dyn VideoEncoder>))
+ (format == Format::ProRes).then(|| {
- let mut cfg = filmcraft_prores::EncoderConfig::new(filmcraft_prores::Profile::Hq, w, h);
++ let profile = prores_profile(&s.prores_profile);
++ let mut cfg = filmcraft_prores::EncoderConfig::new(profile, w, h);
+ if s.signal.is_hdr() {
+ cfg.color = filmcraft_prores::ColorInfo { primaries: s.signal.primaries, transfer: s.signal.transfer, matrix: s.signal.matrix };
+ }
- Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::with_config(cfg), w, h, rate, signal: s.signal }) as Box<dyn VideoEncoder>)
++ Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::with_config(cfg), profile, w, h, rate, signal: s.signal }) as Box<dyn VideoEncoder>)
+ })
}
/// H.264 High (our encoder): sRGB/709 RGBA8 → 8-bit limited-range BT.709 4:2:0, VBR at the
diff --cc crates/format/src/lib.rs
index d81da80e6,3fedfeefa..3bda2295b
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@@ -22,6 -22,10 +22,11 @@@
//! - **v3** (M10.2): graphic clips (`ItemKind::Graphic`, text/shape layers). The shape of older
//! data is unchanged (no-op step); the bump makes builds without graphics refuse such files
//! cleanly instead of failing to parse them.
+ //! - **v4** (M7.4): Essential Sound (clip audio types and settings, `EffectInstance::essential`).
+ //! No-op step; older builds would otherwise drop these fields silently when saving.
+ //! - **v5** (M8.8): colour management (sequence working space, Interpret Footage colour space,
+ //! project LUT library). No-op step, for the same reason.
++//! - **v6** (M11.7/M11.9): media identity fingerprints and ingest settings. No-op step.
pub mod atomic;
pub mod autosave;
@@@ -40,7 -44,7 +45,7 @@@ pub type Migration = fn(Value) -> Resul
/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never
/// edit a shipped one.
- pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3];
-pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5];
++pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6];
/// The schema version this build writes (and the newest it reads).
pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1;
@@@ -219,13 -223,23 +224,28 @@@ fn v2_to_v3(doc: Value) -> Result<Value
Ok(doc)
}
+ /// v3 → v4: Essential Sound fields added; existing data needs no change.
+ fn v3_to_v4(doc: Value) -> Result<Value, String> {
+ Ok(doc)
+ }
+
+ /// v4 → v5: colour-management fields added; existing data needs no change.
+ fn v4_to_v5(doc: Value) -> Result<Value, String> {
+ Ok(doc)
+ }
+
++/// v5 → v6: media identity and ingest settings added; existing data needs no change.
++fn v5_to_v6(doc: Value) -> Result<Value, String> {
++ Ok(doc)
++}
++
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_version_matches_table() {
- assert_eq!(SCHEMA_VERSION, 3);
- assert_eq!(SCHEMA_VERSION, 5);
++ assert_eq!(SCHEMA_VERSION, 6);
}
#[test]
diff --cc crates/render/src/lib.rs
index a199cf495,f34713563..b23125223
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -14,8 -16,8 +16,9 @@@ pub mod effects
pub mod graphic_clip;
pub mod graphics;
pub mod image;
+ pub mod luts;
pub mod mixer;
+pub mod offline;
pub mod plan;
pub mod preview;
pub mod transitions;
diff --cc crates/ui-egui/src/panels/dialogs.rs
index acc2a37c5,699661367..eed562c72
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@@ -4,7 -4,7 +4,8 @@@
use crate::{Dialog, FilmcraftApp};
pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
+ crate::panels::media_dialogs::show(app, ctx);
+ crate::panels::color_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 --cc crates/ui-egui/src/state.rs
index 459552b40,bd01fc372..927395ef9
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@@ -292,112 -295,20 +295,124 @@@ 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>,
+ /// Create Proxies dialog (open when Some).
+ #[serde(default)]
+ pub create_proxies: Option<ProxyDraft>,
+ /// Project Manager dialog (open when Some).
+ #[serde(default)]
+ pub project_manager: Option<ProjectManagerDraft>,
+ /// Make Offline dialog: Some(delete files?) while open.
+ #[serde(default)]
+ pub make_offline: Option<bool>,
+ /// Open colour dialog (Interpret Footage ▸ Color Management, Sequence ▸ Color Management).
+ #[serde(default)]
+ pub color_dialog: Option<ColorDialog>,
}
+/// 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(),
+ }
+ }
+}
+
+/// Clip ▸ Proxy ▸ Create Proxies….
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ProxyDraft {
+ pub items: Vec<u64>,
+ pub preset: String,
+ /// Empty = a Proxies folder next to the original media.
+ pub destination: String,
+}
+
+/// File ▸ Project Manager….
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ProjectManagerDraft {
+ pub sequences: Vec<u64>,
+ /// "collect" | "consolidate"
+ pub mode: String,
+ pub preset: String,
+ pub exclude_unused: bool,
+ pub handles: u32,
+ pub include_proxies: bool,
+ pub include_previews: bool,
+ pub destination: String,
+ /// Last dry-run estimate: (original bytes, resulting bytes, files).
+ pub estimate: Option<(u64, u64, usize)>,
+ pub message: String,
+}
+
+impl Default for ProjectManagerDraft {
+ fn default() -> Self {
+ Self {
+ sequences: vec![],
+ mode: "collect".into(),
+ preset: "prores_lt".into(),
+ exclude_unused: true,
+ handles: 30,
+ include_proxies: true,
+ include_previews: false,
+ destination: String::new(),
+ estimate: None,
+ message: String::new(),
+ }
+ }
+}
+
+ /// Colour dialogs: drafts are applied with one engine command on OK.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub enum ColorDialog {
+ /// `clip.interpretFootage`: the media items and the chosen colour space id ("auto" = metadata).
+ Interpret { items: Vec<u64>, color_space: String },
+ /// `sequence.colorSettings`.
+ Sequence { working_space: String, wide_gamut: bool, auto_tone_map: bool },
+ }
+
/// The Audio Gain dialog (Clip ▸ Audio Gain…, G).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@@ -460,10 -372,7 +476,11 @@@ impl Default for UiState
audio_gain: AudioGainDraft::default(),
gfx_edit: None,
pen_points: vec![],
+ link_media: None,
+ create_proxies: None,
+ project_manager: None,
+ make_offline: None,
+ color_dialog: None,
}
}
}
diff --cc docs/control-protocol.md
index 4dc919fbc,74c47cc62..423995d17
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@@ -45,12 -47,22 +47,26 @@@ record|soloSafe|output|input|fx.<n>|sen
`clipMixer.A1.<fader|pan|mute|solo|keyframe|value>`, `timeline.track.A1.keyframes[.<lane>|.clip]`,
`timeline.track.A1.lane[.kf.<n>]`, `audioGain.<set|adjust|normalizeMax|normalizeAll|ok|cancel|peak>`.
+ Essential Sound: `essentialSound.inspect`, `essentialSound.setType {type: dialogue|music|sfx|ambience}`,
+ `essentialSound.clearType`, `essentialSound.set {key, value}` or `{values: {key: value}}` (keys such as
+ `repair.noise.on`, `repair.noise.amount` (0–10), `repair.humHz`, `clarity.eqPreset`, `clarity.enhanceTone`,
+ `creative.reverbPreset`, `ducking.against`, `ducking.reduceDb`, `ducking.fadeS`, `pan.value`,
+ `volume.levelDb`, `mute`, section switches `<section>.enabled`), `essentialSound.applyPreset {preset, type?}`,
+ `essentialSound.savePreset {name}`, `essentialSound.deletePreset {name}`, `essentialSound.autoMatch {target?}`,
+ `essentialSound.generateDucking`; all take `clips` (default: the selected audio clips). UI ids:
+ `essentialSound.tab.<Browse|Edit>`, `essentialSound.type.<Dialogue|Music|SFX|Ambience>`,
+ `essentialSound.clearType`, `essentialSound.preset[.save|.delete|.name|.ok]`,
+ `essentialSound.section.<Name>[.toggle]`, a row per setting key (`essentialSound.repair.noise.on`,
+ `essentialSound.repair.noise.amount`, `essentialSound.repair.humHz.<i>`), `essentialSound.autoMatch`,
+ `essentialSound.ducking.against.<Type>`, `essentialSound.generateDucking`, `essentialSound.volume.on`,
+ `essentialSound.volume.levelDb`, `essentialSound.mute`, `essentialSound.browse.<Type>.<preset>`.
+
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 media
+management commands and dialog ids: offline media and relinking (`media.findMissing`,
+`media.relink`, `media.autoRelink`, `media.search`, `media.makeOffline`, `media.status`, `linkMedia.*`),
+proxies (`media.createProxies`, `media.attachProxies`, `media.toggleProxies`, `proxies.*`), ingest
+(`project.ingestSettings`) and the Project Manager (`file.projectManager`, `pm.*`).
**Trim mode** (`crates/engine/src/trim.rs`): `trim.selectEditPoint` / `trim.selectNearest` enter trim
mode (the Program monitor becomes the Trim Monitor, ids `trimMonitor.*`); `trim.monitor` returns what
diff --cc docs/project-files.md
index 7a049ed64,827c97295..ca9da2843
--- a/docs/project-files.md
+++ b/docs/project-files.md
@@@ -8,7 -8,7 +8,7 @@@ writing them is `crates/format` (`filmc
```json
{
"format": "filmcraft.project",
- "schema_version": 3,
- "schema_version": 5,
++ "schema_version": 6,
"generator": "FilmCraft 0.1.0",
"project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 }
}
@@@ -27,6 -27,8 +27,9 @@@
| 1 | M0 | the bare `Project` object with a `"version": 1` field |
| 2 | M11.1 | the envelope above; the project's own `version` field is gone |
| 3 | M10.2 | graphic clips (`ItemKind::Graphic` with text/shape layers); a no-op step for older data |
+ | 4 | M7.4 | Essential Sound: clip audio types and settings; no-op step |
+ | 5 | M8.8 | colour management: working space, Interpret Footage colour space, LUT library; no-op step |
++| 6 | M11.7/M11.9 | media identity fingerprints, ingest settings; no-op step |
### Migrations
@@@ -53,8 -56,8 +57,8 @@@ on disk is unchanged until you save. Th
A file with a `schema_version` newer than the build supports is **refused**, not half-read:
- > this project was saved by a newer version of FilmCraft (project schema v4); this build reads up to
- > v3. Update FilmCraft to open it.
-> this project was saved by a newer version of FilmCraft (project schema v6); this build reads up to
-> v5. Update FilmCraft to open it.
++> this project was saved by a newer version of FilmCraft (project schema v7); this build reads up to
++> v6. Update FilmCraft to open it.
Reading it partially and saving it back would silently drop whatever the newer version added.
@@@ -169,151 -172,3 +173,151 @@@ UI automation ids: `prefs.autoSave.enab
`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, relinking, proxies, ingest
+
+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. The same applies to `ProjectSettings::ingest`. Projects from older builds
++the same name. The field is optional (`skip_serializing_if`); it and `ProjectSettings::ingest` came with schema
++v6, so builds that would drop them on save refuse the file instead. 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), and items with a proxy get a **P**
+badge (`project.item.<id>.proxy`).
+
+### Proxies
+
+| Command | Menu | |
+|---|---|---|
+| `media.createProxies {items?, preset?, destination?, attach?=true, wait?}` | Clip ▸ Proxy ▸ Create Proxies… | background job; attaches when done |
+| `media.attachProxies {item, path}` / `{items, paths}` | Attach Proxies… | duration within one frame and the same frame rate are required; size and aspect may differ |
+| `media.detachProxies {items?}` | Detach Proxies | |
+| `media.reconnectFullRes {item, path}` | Reconnect Full Resolution Media… | link the full-resolution file of a clip that has a proxy |
+| `media.toggleProxies {enabled?}` | View ▸ Toggle Proxies, monitor button | Preferences ▸ Media ▸ `media.enableProxies` |
+| `media.proxyPresets` | | |
+
+The presets use our own encoders:
+
+- `prores_proxy_quarter` (default), `prores_proxy_half`, `prores_lt_half`: ProRes 422 Proxy or LT
+ in MOV with PCM audio;
+- `h264_quarter`, `h264_half`: H.264 + AAC in MP4.
+
+Proxies go to `<media folder>/Proxies/<name>_Proxy.<ext>`, or to the chosen folder. Job progress is
+in `jobs.list`. `Session::poll_persistence`, which the app calls every frame, attaches finished
+proxies.
+
+With proxies enabled, monitors, thumbnails and playback read the proxy. The proxy source reports
+the original's size. The compositor derives its pixel scale from the frame it gets, so Motion and
+pixel-size effect parameters (blur radii…) give the same picture at the proxy's resolution. A
+320×180 clip with Motion and Gaussian Blur and a ½-size ProRes Proxy measures 44 dB PSNR against
+full resolution (48 dB at ½ playback resolution). **Export always uses full resolution**
+(`MediaPool::full_res_provider`). Toggling proxies bumps the revision so caches refresh, but it is
+not an edit and doesn't mark the project as modified.
+
+**Cost.** These numbers are from `proxy_playback_perf_4k`, an ignored test: `RAYON_NUM_THREADS=1
+cargo test --release -p filmcraft-engine proxy_playback_perf_4k -- --ignored --nocapture`. It plays a
+2 s 3840×2160 H.264 clip (ffmpeg `testsrc2`, libx264) on one core of the development Mac and reports
+milliseconds per frame:
+
+| | decode (GPU path) | CPU composite at ½ | CPU composite at ¼ | proxy creation |
+|---|---|---|---|---|
+| full resolution | 9.2 | 277 | 201 | |
+| ProRes Proxy ¼ | 8.9 | 150 | 35 | 17.8 s |
+| H.264 ¼ | 0.7 | 131 | 48 | 8.9 s |
+
+The test pattern is unusually cheap for H.264 to decode, so real camera footage gains more from
+proxies. The CPU composite (YUV→linear conversion and resampling) is what proxies cut most:
+5.7× at ¼ resolution, where the proxy needs no resampling.
+
+Create Proxies dialog ids: `proxies.preset.<id>`, `proxies.destination`, `proxies.browse`,
+`proxies.ok`, `proxies.cancel`. Monitor button: `program.transport.media.toggleProxies` (and
+`source.…`). It is lit while proxies are on.
+
+### Ingest settings
+
+`project.ingestSettings {enabled, action: copy|transcode|createProxies|copyAndCreateProxies,
+destination?, preset?}` (Project Settings ▸ Ingest) acts on every `file.import`:
+
+- **copy** copies the file to the destination (default `<media folder>/Ingested Media`), checks the
+ copy's fingerprint against the original, and then uses the copy;
+- **transcode** writes the preset's format (default ProRes 422 LT) in the background and switches the
+ clip to the result when it is done;
+- **createProxies** makes proxies in the background and attaches them;
+- **copyAndCreateProxies** does both.
+
+`file.import` reports this under `ingest`.
+
+## Project Manager
+
+`file.projectManager` (File ▸ Project Manager…) makes a self-contained copy of a project:
+
+```json
+{"destination": "/path/Folder", "mode": "collect|consolidate", "sequences": [id], "excludeUnused": true,
+ "handles": 30, "preset": "prores_lt", "includeProxies": true, "includePreviews": false,
+ "projectName": "…", "dryRun": false, "overwrite": false, "wait": false}
+```
+
+- **collect** copies every media file that the chosen sequences use (following nested sequences and
+ subclips), plus their proxies and render previews if asked.
+- **consolidate** writes only the used range of each movie or audio file, plus `handles` frames on
+ each side, with a transcode preset (`prores_lt`, `prores_hq`, `h264`). It then re-bases the clips'
+ media time, so every edit, keyframe and marker stays in place. Stills are copied.
+- **excludeUnused** drops media items and sequences that the chosen sequences don't use.
+- **dryRun** returns the plan and the disk-space estimate (`originalBytes`, `resultBytes`, `files`)
+ without writing anything.
+
+The copy runs as a job. The project file (`<destination>/<name>.fcproj`) is written last, with the
+new paths and fingerprints, so it opens with no missing media.
+
+Dialog ids: `pm.seq.<id>`, `pm.mode.<collect|consolidate>`, `pm.preset.<id>`, `pm.excludeUnused`,
+`pm.handles`, `pm.includeProxies`, `pm.includePreviews`, `pm.destination`, `pm.browse`,
+`pm.calculate`, `pm.sizes`, `pm.ok`, `pm.cancel`.