FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Merge main into the playback branch (mixer recordStart moves to the end of preroll; GopCache keeps main's random-access key walk-back)
Brandon Thomas4b83e088ebc5
diff --cc Cargo.lockindex aca993685,72dbdba55..4097c7b84--- a/Cargo.lock+++ b/Cargo.lock@@@ -1625,8 -1691,8 +1693,9 @@@ version = "0.1.0dependencies = ["eframe","egui",+ "egui_kittest","filmcraft-audio-dsp",+ "filmcraft-codecs","filmcraft-color","filmcraft-edit","filmcraft-engine",@@@ -1636,11 -1702,11 +1705,13 @@@"filmcraft-media","filmcraft-project","filmcraft-render",+ "filmcraft-text","filmcraft-time",+ "image","log",+ "pollster 0.4.0","rayon",+ "rustix 1.1.5","serde","serde_json",]diff --cc crates/codecs/src/gop.rsindex 16c6ef59f,deafcf257..34a603882--- a/crates/codecs/src/gop.rs+++ b/crates/codecs/src/gop.rs@@@ -162,36 -74,25 +162,45 @@@ impl GopCachelet want_pts = s.pts(i);let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());if let Some(f) = st.frames.get(&want_pts) {+ HITS.fetch_add(1, Ordering::Relaxed);return Ok(f.clone());}+ MISSES.fetch_add(1, Ordering::Relaxed);if st.decoder.is_none() {- st.decoder = Some(s.make_decoder()?);+ 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 key = s.sync_before(i);+ 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;+ // 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);+ }if let Some(d) = st.decoder.as_mut() {d.reset();}diff --cc crates/codecs/src/video.rsindex 16d1ad38f,7f62a3c51..9542951d1--- a/crates/codecs/src/video.rs+++ b/crates/codecs/src/video.rs@@@ -20,11 -20,12 +20,17 @@@ pub trait VideoDecoder: Send/// Forget all state (called after seeking to a sync sample).fn reset(&mut self);fn name(&self) -> &str;+ /// Every picture is coded independently (no reordering, no references), so frames can be+ /// decoded in any order and in parallel by separate decoder instances.+ fn intra_only(&self) -> bool {+ false+ }+ /// Whether decoding can start at `sample` (`None`: unknown, trust the container's sync flags).+ /// Containers may flag samples as sync that the codec cannot start from (an MP4 without+ /// `stss` marks every sample), so codecs that can tell say so.+ fn is_random_access(&self, _sample: &[u8]) -> Option<bool> {+ None+ }}/// A factory returns `None` when it does not handle the entry.diff --cc crates/gpu/src/lib.rsindex 792f8d471,790861692..3dfe56699--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@@ -330,19 -248,12 +333,19 @@@ impl GpuCompositorlet up = match &f.data {PixelData::Rgba8(d) => {let v = self.plane_texture(w, h, wgpu::TextureFormat::Rgba8UnormSrgb, d, 4);- Uploaded { views: [v, dummy(), dummy()], kind: 0, code_scale: 1.0, chroma: (w, h), last_used: self.clock }+ Uploaded { views: [v, dummy(), dummy()], kind: 0, code_scale: 1.0, chroma: (w, h), last_used: self.clock, _pixels: f.data.clone() }}PixelData::RgbaF32(d) => {- let half: Vec<u8> = d.iter().flat_map(|v| f32_to_f16(*v).to_le_bytes()).collect();- let v = self.plane_texture(w, h, wgpu::TextureFormat::Rgba16Float, &half, 8);+ let owned;+ let half = match prep {+ Some(p) => &p.planes[0],+ None => {+ owned = f32_to_f16_bytes(d);+ &owned+ }+ };+ let v = self.plane_texture(w, h, wgpu::TextureFormat::Rgba16Float, half, 8);- Uploaded { views: [v, dummy(), dummy()], kind: 1, code_scale: 1.0, chroma: (w, h), last_used: self.clock }+ Uploaded { views: [v, dummy(), dummy()], kind: 1, code_scale: 1.0, chroma: (w, h), last_used: self.clock, _pixels: f.data.clone() }}PixelData::Yuv8 { planes, chroma, .. } => {let (sx, sy) = chroma.shifts();@@@ -356,19 -267,13 +359,19 @@@let (sx, sy) = chroma.shifts();let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy));let scale = (1u32 << bits) as f32;- let conv = |p: &[u16]| -> Vec<u8> { p.iter().flat_map(|v| f32_to_f16(*v as f32 / scale).to_le_bytes()).collect() };- let (py, pu, pv) = (conv(&planes[0]), conv(&planes[1]), conv(&planes[2]));- let y = self.plane_texture(w, h, wgpu::TextureFormat::R16Float, &py, 2);- let u = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &pu, 2);- let v = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &pv, 2);+ let owned;+ let p = match prep {+ Some(p) => p,+ None => {+ owned = Prepared { planes: planes.iter().map(|p| codes_to_f16_bytes(p, *bits)).collect() };+ &owned+ }+ };+ let y = self.plane_texture(w, h, wgpu::TextureFormat::R16Float, &p.planes[0], 2);+ let u = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &p.planes[1], 2);+ let v = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &p.planes[2], 2);let _ = Chroma::C420;- Uploaded { views: [y, u, v], kind: 2, code_scale: scale, chroma: (cw, ch), last_used: self.clock }+ Uploaded { views: [y, u, v], kind: 2, code_scale: scale, chroma: (cw, ch), last_used: self.clock, _pixels: f.data.clone() }}};self.uploads.insert(key, up);diff --cc crates/gpu/src/tests.rsindex f0013da4a,f787d7056..479d49e29--- a/crates/gpu/src/tests.rs+++ b/crates/gpu/src/tests.rs@@@ -78,50 -78,20 +78,68 @@@ fn half_float_conversion()}}+#[test]+fn prepared_upload_matches_inline_conversion() {+ let Some((dev, q)) = device() else {+ eprintln!("no GPU adapter; skipping");+ return;+ };+ let (w, h) = (64u32, 36u32);+ let yuv16 = Arc::new(VideoFrame {+ width: w,+ height: h,+ data: PixelData::Yuv16 {+ planes: [+ Arc::new((0..w * h).map(|i| (64 + (i * 7) % 876) as u16).collect()),+ Arc::new((0..w * h / 2).map(|i| (64 + (i * 13) % 896) as u16).collect()),+ Arc::new((0..w * h / 2).map(|i| (960 - (i * 5) % 896) as u16).collect()),+ ],+ chroma: Chroma::C422,+ bits: 10,+ alpha: None,+ },+ color: filmcraft_color::ColorInfo::REC709,+ par: (1, 1),+ pts: Default::default(),+ });+ let f32_layer: Vec<f32> = (0..w * h * 4).map(|i| ((i * 37) % 1000) as f32 / 1000.0 * if i % 4 == 3 { 1.0 } else { 0.6 }).collect();+ let rgbaf = Arc::new(VideoFrame::rgba_f32(w, h, f32_layer.clone()));+ let layers = FramePlan::Layers {+ width: w as usize,+ height: h as usize,+ layers: vec![+ PlanLayer { frame: yuv16, matrix: Affine::IDENTITY, opacity: 1.0 },+ PlanLayer { frame: rgbaf, matrix: Affine::scale(0.5, 0.5), opacity: 0.8 },+ ],+ };+ let image = FramePlan::Image(filmcraft_render::Image { w: w as usize, h: h as usize, px: f32_layer });+ for plan in [layers, image] {+ let mut a = GpuCompositor::new(&dev, &q);+ a.composite(&plan);+ let inline = a.read_output().expect("readback");+ let mut b = GpuCompositor::new(&dev, &q);+ let prep = prepare(&plan);+ assert!(prep.bytes() > 0);+ b.composite_prepared(&plan, Some(&prep));+ let prepared = b.read_output().expect("readback");+ assert!(inline == prepared, "prepared upload differs");+ }+}+++ /// The upload cache is keyed by pixel-buffer address, so it must keep the buffer alive: otherwise+ /// a new frame allocated at a freed frame's address is drawn with the stale texture (seen as+ /// whole frames from a previous composite in `crates/golden` GPU parity).+ #[test]+ fn upload_cache_keeps_buffers_alive() {+ let Some((dev, q)) = device() else {+ eprintln!("no GPU adapter; skipping");+ return;+ };+ let mut c = GpuCompositor::new(&dev, &q);+ let px = Arc::new(vec![200u8; 16 * 8 * 4]);+ let frame = Arc::new(VideoFrame { width: 16, height: 8, data: PixelData::Rgba8(px.clone()), ..(*yuv_frame(16, 8)).clone() });+ let plan = FramePlan::Layers { width: 16, height: 8, layers: vec![PlanLayer { frame, matrix: Affine::IDENTITY, opacity: 1.0 }] };+ c.composite(&plan);+ drop(plan);+ assert!(Arc::strong_count(&px) > 1, "cached upload must own its pixel buffer");+ }diff --cc crates/render/src/lib.rsindex 0c36a42d8,f221e7f44..a0ab6060c--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@@ -243,10 -257,7 +261,10 @@@ pub(crate) fn item_layerlet px_scale = layer.w as f32 / src_size.0.max(1) as f32;if opts.effects {let cx = effects::FxCtx { t: mt, px_scale, seconds: (t - item.start).seconds(), timecode: tc, clip_name: &item.name };- for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic)) {+ for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic) && !filmcraft_project::graphic::is_layer(e)) {+ if filmcraft_media::cancel::cancelled() {+ return None;+ }effects::apply(&mut layer, e, &cx);}}diff --cc crates/ui-egui/Cargo.tomlindex c832b76b3,7f1436757..bba3e4ed7--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@@ -28,10 -29,6 +29,12 @@@ serde_json = { workspace = truelog = { workspace = true }rayon = { workspace = true }+# Thread/process CPU clocks for frame-job profiling (safe wrappers; see frames.rs).+[target.'cfg(unix)'.dependencies]+rustix = { version = "1", default-features = false, features = ["std", "time"] }+[dev-dependencies]+pollster = "0.4"+filmcraft-codecs = { workspace = true }+ egui_kittest = { workspace = true, features = ["eframe", "wgpu"] }+ image = { version = "0.25", default-features = false, features = ["png"] }diff --cc crates/ui-egui/src/lib.rsindex d69a5d2e8,97bf22017..9142652aa--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -177,9 -178,15 +187,10 @@@ impl FilmcraftApp}impl FilmcraftApp {- pub fn new(session: Session) -> Self {+ pub fn new(mut session: Session) -> Self {+ session.shortcuts.register_external(menus::external_commands());let recovery = !session.recovery_candidates().is_empty();- let frames = Arc::new(FrameServer::new(- session.media.clone(),- session.services.clone(),- session.previews.clone(),- std::thread::available_parallelism().map(|n| n.get().clamp(2, 6)).unwrap_or(3),- ));+ let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers()));Self {session,ui: UiState::default(),@@@ -303,21 -308,15 +316,26 @@@self.playback.playing = true;self.playback.speed = speed;self.playback.anchor_tick = self.session.playhead();- self.playback.anchor_time = -1.0; // set on next frame- self.playback.dropped = 0;- self.playback.shown = 0;+ self.playback.anchor_time = -1.0; // set when the preroll ends+ self.playback.preroll = Some(-1.0);+ self.playback.preroll_ready = false;+ if let Some(a) = self.audio.as_mut() {+ a.stop();+ }+ self.playback.audio_clock = false;+ }++ /// Start the clock (and audio) once the first frames are ready or the preroll timed out.+ fn end_preroll(&mut self, now: f64) {+ self.playback.preroll = None;+ self.playback.anchor_time = now;+ self.playback.anchor_tick = self.session.playhead();self.start_audio();+ // Audio Track Mixer: an automation pass runs while playing forward in real time- if (speed - 1.0).abs() < 1e-9 && !self.session.mixrec.active() {++ if (self.playback.speed - 1.0).abs() < 1e-9 && !self.session.mixrec.active() {+ let t = self.session.playhead();+ let _ = self.session.execute("mixer.recordStart", json!({"time": t.0}));+ }}pub fn stop(&mut self) {diff --cc docs/architecture.mdindex 8bbe22a3e,b53241a16..115ccfb88--- a/docs/architecture.md+++ b/docs/architecture.md@@@ -203,21 -211,53 +211,63 @@@ file ──► codecs (MP4/MOV, MKV, au- **Frame scheduling.** `crates/ui-egui/src/frames.rs` runs a small pool of worker threads withprioritised jobs: the frame on screen first, then playback prefetch, then thumbnails. The UI neverdecodes. It shows the exact frame when it is ready and holds the nearest cached frame meanwhile.+ Play waits for the first frames (`PREROLL_FRAMES`, at most 0.5 s) before starting the clock.+ Every refresh, `schedule_playback` asks for the next frames and drops (or cancels, through+ `filmcraft_media::cancel`) jobs for frames the playhead has passed; a new on-screen frame+ replaces the one asked for before (scrubbing); Stop cancels the prefetch. When frames cost more+ than the workers can render in real time (CPU effects), it starts only frames that can still be+ on time and spaces them evenly (`playback_plan`). GPU plans carry their texels already+ converted for upload (`filmcraft_gpu::prepare`), so the UI thread only copies them.- **Audio clock.** The desktop app passes a cpal output (`apps/filmcraft/src/audio.rs`) to the UI as`AudioOut`. While playing, the samples played by the sound card drive the playhead and video follows.- Without an audio device, playback falls back to the wall clock. Dropped frames are counted.+ Without an audio device, playback falls back to the wall clock. `PlaybackMeter` counts timeline+ frames: shown when the exact picture was on screen while due, dropped otherwise (including frames+ passed over without a refresh, not while the window is hidden). `cargo xtask bench-playback`+ measures the whole path headlessly ([testing.md](testing.md) §5).- Sequence audio is mixed in `render::audio`, and clip audio effects run on `audio-dsp` via- `render::audio_fx`.+ Sequence audio goes through the mixer graph (`render::mixer`, §5.1); clip audio effects run on+ `audio-dsp` via `render::audio_fx`.++ ### 5.1 Audio mixer++ ```text+ clip: gain → clip effects → Volume / Channel Volume / Panner (clip keyframes, media time)+ → audio transitions → summed per track render::audio::track_input+ track / submix strip: input map, mono fold → pre-fader inserts → pre-fader sends → mute+ → fader (volume) → meter → post-fader inserts → post-fader sends → pan / balance → output+ Mix: bus sum → pre-fader inserts → fader → meter → post-fader inserts → out render::mixer+ ```++ - **Model** (`project::mixer`). Every audio track, submix and the Mix has a `MixerStrip`. Static+ values stay in `Track::volume_db`, `pan`, `muted` and the send/effect parameters; automation is+ keyframes in sequence ticks: lanes `volume`, `pan`, `mute` (hold), `send.<i>.level` in+ `MixerStrip::lanes`, and insert parameters (`fx.<slot>.<param>`) in the effect's own keyframes.+ Up to 5 inserts (`EffectInstance::post_fader` picks the side) and 5 sends per strip. Submixes feed+ the Mix or a submix after them (no feedback). All fields have serde defaults, so older projects+ load unchanged.+ - **Graph** (`render::mixer::mix_graph`). Lanes are evaluated per sample; effect parameters update+ on an absolute 64-sample grid, so the output does not depend on how callers cut the timeline into+ requests (export batches and device callbacks give identical samples). Inserts that report+ latency delay their strip; each route into a bus gets a compensation delay and the graph is read+ ahead by its total latency. Graph state (DSP, delay lines) is cached per structure and continued by+ sequential readers; other requests start fresh with a pre-roll (effect tails, ≤ 3 s). Tracks run+ in parallel (rayon), buses in order. Mono tracks pan with the −3 dB constant-power law; stereo+ tracks and sends use balance. Solo keeps soloed and solo-safe strips plus everything feeding them+ or fed by them. 24 tracks × (EQ + Dynamics + Studio Reverb) + a compressed submix renders at+ ~6× realtime on one core (release).+ - **Automation modes** (Premiere semantics). Off ignores lanes; Read plays them; Latch records from+ the first touch and holds the last value until playback stops; Touch records while held and ramps+ back to the existing automation over the **automatch time** (Preferences ▸ Audio, 1 s); Write+ records every control from playback start (then switches to Touch unless "Switch to Touch after+ Write" is off).+ - **Recording** (`engine::mixer`). Playback start runs `mixer.recordStart`, stop runs+ `mixer.recordStop`. Fader and knob drags send `mixer.touch` (value, playhead) while held and+ `mixer.release` when let go. Held values go to `render::mixer::LiveMix`, which the playing mix+ reads, so moves are heard at once. At stop each gesture stream is thinned (linear keyframe+ thinning, optional minimum time interval) and written over its time range as one undo step,+ with boundary keyframes that keep the automation outside the range unchanged.+ - **Live state.** `PreviewStore::live` (`LiveMix`) also carries per-strip meter peaks posted by the+ mix (Track Mixer and Audio Meters read them) and the newest project snapshot, which the audio+ callback uses, so edits made during playback are heard.## 6. Export jobs (`filmcraft-export`)diff --cc xtask/src/main.rsindex 2ebde188d,9e5ce8bc1..b5094c775--- a/xtask/src/main.rs+++ b/xtask/src/main.rs@@@ -259,9 -299,9 +306,10 @@@ fn main() -> ExitCode"layers" => layers(),"wasm" => wasm(),"assets" => assets(),+ "fixtures" => fixtures(&std::env::args().skip(2).collect::<Vec<_>>()),"ci" => ci(),- _ => Err("usage: cargo xtask <layers|assets|wasm|fixtures [crate…]|ci>".into()),+ "bench-playback" => bench_playback(),- _ => Err("usage: cargo xtask <layers|assets|wasm|ci|bench-playback [args]>".into()),++ _ => Err("usage: cargo xtask <layers|assets|wasm|fixtures [crate…]|ci|bench-playback [args]>".into()),};match r {Ok(()) => ExitCode::SUCCESS,