FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Thumbnails decode with small decoders that are not kept
Davi Andreib485e2c180f1
diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rsindex 2c59d7297..3972998ef 100644--- a/crates/codecs/src/gop.rs+++ b/crates/codecs/src/gop.rs@@ -140,6 +140,10 @@ struct State {bytes: usize,/// When a frame was last asked of this cache.last_used: Instant,+ /// Only background requests (thumbnails, [`filmcraft_media::cancel::with_background`]) have+ /// used the decoder since it was made: it is given up as soon as another background request+ /// is done, whatever the caches' recency.+ background: bool,}impl State {@@ -349,6 +353,27 @@ impl Pool {released}+ /// Take the decoders of the caches other than `me` that only background requests have used+ /// (see [`State::background`]) and that are not decoding now. A burst of thumbnails (an import+ /// of many clips) touches every clip within moments, so the recency rules treat them all as+ /// in use; each software 4K decoder holds ~0.5 GB. The cache `me` just served keeps its+ /// decoder (hovering a clip asks for more of its frames). Drop the result with no cache lock+ /// held.+ #[must_use = "drop the released decoders with no cache lock held"]+ fn release_background(&self, me: &Shared) -> Vec<Box<dyn VideoDecoder>> {+ let all: Vec<Arc<Shared>> = self.caches.lock().unwrap_or_else(PoisonError::into_inner).iter().filter_map(Weak::upgrade).collect();+ let mut released = Vec::new();+ for c in all.iter().filter(|c| !std::ptr::eq(Arc::as_ptr(c), me)) {+ if let Some(mut st) = try_state(c)+ && st.background+ && st.decoder.is_some()+ {+ released.extend(st.release_decoder(self));+ }+ }+ released+ }+/// Evict the frames of caches idle for [`RECENT`], least recently used first, down to the/// budget. Caches in use keep theirs (each within its own budget): a frame evicted before it is shown costs a/// re-decode from the keyframe.@@ -418,6 +443,7 @@ impl GopCache {drafts: Default::default(),bytes: 0,last_used: Instant::now(),+ background: false,}),pool: pool.clone(),});@@ -508,6 +534,16 @@ impl GopCache {/// ([`VideoDecoder::set_draft`]); its draft frames are cached for draft requests only, and an/// exact request for one re-decodes it.pub fn frame_late(&self, s: &dyn VideoSamples, target: i64, late_before: Option<i64>) -> crate::Result<Arc<VideoFrame>> {+ let r = self.frame_late_locked(s, target, late_before);+ if filmcraft_media::cancel::background() {+ // Outside the cache's lock (see `release_background`). A thumbnail leaves the decoders+ // of earlier thumbnails no reason to stay: each costs hundreds of MB at 4K.+ drop(self.shared.pool.release_background(&self.shared));+ }+ r+ }++ fn frame_late_locked(&self, s: &dyn VideoSamples, target: i64, late_before: Option<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);@@ -523,11 +559,23 @@ impl GopCache {let mut st = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());let _decoding = DecodingGuard::enter(me);st.last_used = Instant::now();- if let Some(f) = st.cached(want_pts, draft) {+ let background = filmcraft_media::cancel::background();+ if let Some(f) = st.cached(want_pts, draft).cloned() {HITS.fetch_add(1, Ordering::Relaxed);- return Ok(f.clone());+ // a monitor asking for a frame of a thumbnail's clip makes its decoder one in use+ st.background &= background;+ return Ok(f);}MISSES.fetch_add(1, Ordering::Relaxed);+ if !background {+ st.background = false;+ } else if st.decoder.is_none() {+ st.background = true;+ }+ if !background && st.decoder.as_ref().is_some_and(|d| d.thread_limited()) {+ // made for a thumbnail (few threads): a monitor gets a full one+ released.extend(st.release_decoder(&self.shared.pool));+ }if st.decoder.is_none() {let d = s.make_decoder()?;st.intra = d.intra_only();@@ -724,6 +772,8 @@ mod tests {/// (pts, decoded as a draft picture)held: VecDeque<(i64, bool)>,draft: bool,+ /// made for background work (few threads, like the H.264 decoder's)+ limited: bool,resets: Arc<AtomicUsize>,decodes: Arc<AtomicUsize>,}@@ -758,6 +808,9 @@ mod tests {fn name(&self) -> &str {"test"}+ fn thread_limited(&self) -> bool {+ self.limited+ }fn intra_only(&self) -> bool {self.intra}@@ -790,6 +843,7 @@ mod tests {intra: self.intra,held: VecDeque::new(),draft: false,+ limited: filmcraft_media::cancel::background(),resets: self.resets.clone(),decodes: self.decodes.clone(),}))@@ -1011,6 +1065,58 @@ mod tests {assert_eq!(s[n - 1].resets.load(Ordering::Relaxed), resets);}+ /// The thumbnails an import queues: every clip asked once, quickly (the real caps and recency,+ /// no sleeping: all of them are "recent"). Each 4K software decoder costs ~0.5 GB, and 42+ /// clips used to hold 6+ GB at once.+ #[test]+ fn background_requests_leave_no_decoders_behind() {+ use filmcraft_media::cancel::with_background;+ let pool = Arc::new(Pool::new(MAX_LIVE_DECODERS, IDLE, FRAME_BUDGET).tiered(RECENT, HARD_DECODERS));+ let n = 24;+ let s: Vec<Samples> = (0..n).map(|_| samples(300, 250, 3, false)).collect();+ let c: Vec<GopCache> = (0..n).map(|_| GopCache::in_pool(None, pool.clone())).collect();+ // a clip in use by a monitor+ assert_eq!(index_of(&c[0].frame(&s[0], 10_000).expect("frame")), 10);+ for k in 1..n {+ assert_eq!(index_of(&with_background(true, || c[k].frame(&s[k], 10_000)).expect("frame")), 10);+ assert!(pool.decoders.load(Ordering::Relaxed) <= 2, "{} live decoders after thumbnail {k}", pool.decoders.load(Ordering::Relaxed));+ }+ // the monitor's clip and the last thumbnail keep theirs and carry on without a seek+ assert_eq!(pool.decoders.load(Ordering::Relaxed), 2);+ assert_eq!(index_of(&c[0].frame(&s[0], 11_000).expect("frame")), 11);+ assert_eq!(s[0].resets.load(Ordering::Relaxed), 1);+ assert_eq!(index_of(&with_background(true, || c[n - 1].frame(&s[n - 1], 12_000)).expect("frame")), 12);+ assert_eq!(s[n - 1].resets.load(Ordering::Relaxed), 1);+ // a monitor asking for a frame of a thumbnail's clip makes its decoder one in use+ assert_eq!(index_of(&c[n - 1].frame(&s[n - 1], 13_000).expect("frame")), 13);+ for k in 1..4 {+ with_background(true, || c[k].frame(&s[k], 20_000)).expect("frame");+ }+ assert_eq!(index_of(&c[n - 1].frame(&s[n - 1], 14_000).expect("frame")), 14);+ assert!(c[n - 1].shared.state.lock().unwrap().decoder.is_some(), "the thumbnails left its decoder");+ // a cache that lost its decoder still decodes (from the sync sample)+ assert_eq!(index_of(&with_background(true, || c[1].frame(&s[1], 30_000)).expect("frame")), 30);+ }++ #[test]+ fn a_monitor_replaces_a_decoder_made_for_a_thumbnail() {+ use filmcraft_media::cancel::with_background;+ let pool = Arc::new(Pool::new(MAX_LIVE_DECODERS, IDLE, FRAME_BUDGET).tiered(RECENT, HARD_DECODERS));+ let (s, c) = (samples(300, 250, 3, false), GopCache::in_pool(None, pool.clone()));+ assert_eq!(index_of(&with_background(true, || c.frame(&s, 10_000)).expect("frame")), 10);+ // another thumbnail of the same clip carries on with the thumbnail decoder+ assert_eq!(index_of(&with_background(true, || c.frame(&s, 12_000)).expect("frame")), 12);+ assert_eq!(s.resets.load(Ordering::Relaxed), 1);+ // a frame a monitor waits for (not cached: far ahead) is decoded by a full-thread decoder+ assert_eq!(index_of(&c.frame(&s, 100_000).expect("frame")), 100);+ assert!(!c.shared.state.lock().unwrap().decoder.as_ref().is_some_and(|d| d.thread_limited()));+ assert_eq!(pool.decoders.load(Ordering::Relaxed), 1);+ // and keeps it for the next frames+ let resets = s.resets.load(Ordering::Relaxed);+ assert_eq!(index_of(&c.frame(&s, 101_000).expect("frame")), 101);+ assert_eq!(s.resets.load(Ordering::Relaxed), resets);+ }+#[test]fn a_burst_of_single_requests_does_not_keep_every_clips_frames() {// 1×1 RGBA pictures (4 bytes): a shared budget of ten of themdiff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rsindex 8aada02e6..86b21b7d9 100644--- a/crates/codecs/src/video.rs+++ b/crates/codecs/src/video.rs@@ -45,8 +45,19 @@ pub trait VideoDecoder: Send {/// shortcuts that only change pictures nothing references, which come out flagged/// [`DecodedFrame::draft`]. Decoders without such a mode ignore it.fn set_draft(&mut self, _on: bool) {}+ /// Made with fewer worker threads than a decoder for playback gets, because it was made for+ /// background work ([`filmcraft_media::cancel::with_background`]). A request for a monitor+ /// replaces such a decoder.+ fn thread_limited(&self) -> bool {+ false+ }}+/// Worker threads of the H.264 decoders made for background work (thumbnails): a frame-threaded+/// 4K decoder holds `threads + 2` pictures in flight (~0.5 GB with 16 threads), and the frame+/// workers already decode different files in parallel.+const BACKGROUND_H264_THREADS: usize = 2;+/// NAL unit headers of a length-prefixed (avcC / hvcC) sample: the first two bytes of each unit.fn nal_headers(sample: &[u8], length_size: usize) -> impl Iterator<Item = (u8, u8)> + '_ {let mut pos = 0usize;@@ -200,19 +211,36 @@ pub struct H264Decoder {dec: filmcraft_h264::Decoder,length_size: usize,draft: bool,+ /// Worker threads (a background decoder gets fewer).+ threads: usize,}impl H264Decoder {+ /// The worker threads for a decoder made now.+ fn threads_now() -> usize {+ if filmcraft_media::cancel::background() { BACKGROUND_H264_THREADS.min(h264_threads()) } else { h264_threads() }+ }++ fn make_inner(avcc: &[u8], threads: usize) -> Result<filmcraft_h264::Decoder> {+ let mut dec = filmcraft_h264::Decoder::with_threads(threads);+ if !avcc.is_empty() {+ dec.configure_avcc(avcc).map_err(|e| CodecError::Decode(e.to_string()))?;+ }+ Ok(dec)+ }+pub fn new(avcc: Vec<u8>) -> Result<Self> {recycle_h264_planes();- let dec = filmcraft_h264::Decoder::from_avcc(&avcc).map_err(|e| CodecError::Decode(e.to_string()))?;+ let threads = Self::threads_now();+ let dec = Self::make_inner(&avcc, threads)?;let length_size = avcc_length_size(&avcc);- Ok(Self { avcc, dec, length_size, draft: false })+ Ok(Self { avcc, dec, length_size, draft: false, threads })}/// A decoder for Annex B byte-stream samples (start codes, in-band parameter sets: MXF, TS).pub fn annexb() -> Self {recycle_h264_planes();- Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::new(), length_size: 0, draft: false }+ let threads = Self::threads_now();+ Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::with_threads(threads), length_size: 0, draft: false, threads }}fn convert(p: filmcraft_h264::Picture) -> DecodedFrame {use std::sync::Arc;@@ -245,9 +273,7 @@ impl VideoDecoder for H264Decoder {self.dec.flush().into_iter().map(Self::convert).collect()}fn reset(&mut self) {- if self.avcc.is_empty() {- self.dec = filmcraft_h264::Decoder::new();- } else if let Ok(d) = filmcraft_h264::Decoder::from_avcc(&self.avcc) {+ if let Ok(d) = Self::make_inner(&self.avcc, self.threads) {self.dec = d;}self.dec.set_draft(self.draft);@@ -255,6 +281,9 @@ impl VideoDecoder for H264Decoder {fn name(&self) -> &str {"FilmCraft H.264"}+ fn thread_limited(&self) -> bool {+ self.threads < h264_threads()+ }fn set_draft(&mut self, on: bool) {self.draft = on;self.dec.set_draft(on);diff --git a/crates/media/src/cancel.rs b/crates/media/src/cancel.rsindex 7848a845f..bfb391dd2 100644--- a/crates/media/src/cancel.rs+++ b/crates/media/src/cancel.rs@@ -13,6 +13,10 @@//! [`with_draft`] marks reduced-resolution playback (opt-in): decoders may take spec-safe//! shortcuts that only change pictures nothing references (H.264: no deblocking of non-reference//! pictures). Never set for exports, renders or a frame shown while paused.+//!+//! [`with_background`] marks work nobody waits on interactively (thumbnails of the Project panel,+//! the Media Browser and the timeline): sources should not keep expensive state, such as a+//! frame-threaded 4K decoder, for it once it is done.use std::cell::{Cell, RefCell};use std::sync::Arc;@@ -24,6 +28,28 @@ thread_local! {static CURRENT: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };static CATCH_UP: Cell<Option<Tick>> = const { Cell::new(None) };static DRAFT: Cell<bool> = const { Cell::new(false) };+ static BACKGROUND: Cell<bool> = const { Cell::new(false) };+}++/// Run `f` as background work when `on` (restoring the previous hint after): a thumbnail, not a+/// frame a monitor or playback waits for.+pub fn with_background<R>(on: bool, f: impl FnOnce() -> R) -> R {+ /// Restores the previous hint however `f` ends (a panic caught further up must not leave the+ /// worker thread marked as background).+ struct Restore(bool);+ impl Drop for Restore {+ fn drop(&mut self) {+ BACKGROUND.with(|c| c.set(self.0));+ }+ }+ let _restore = Restore(BACKGROUND.with(|c| c.replace(on)));+ f()+}++/// Whether the work running on this thread is background work (off unless inside+/// [`with_background`]`(true, …)`).+pub fn background() -> bool {+ BACKGROUND.with(Cell::get)}/// Run `f` with the draft-decoding hint `on` (restoring the previous one after). Frames decoded@@ -97,6 +123,24 @@ mod tests {assert!(!draft());}+ #[test]+ fn background_is_off_by_default_and_scoped() {+ assert!(!background());+ with_background(true, || {+ assert!(background());+ with_background(false, || assert!(!background()));+ assert!(background());+ });+ assert!(!background());+ }++ #[test]+ fn a_panic_inside_background_work_does_not_leave_the_thread_marked() {+ let r = std::panic::catch_unwind(|| with_background(true, || panic!("boom")));+ assert!(r.is_err());+ assert!(!background());+ }+#[test]fn catch_up_is_scoped_to_the_closure() {assert_eq!(catch_up(), None);diff --git a/crates/ui-egui/examples/thumb_burst.rs b/crates/ui-egui/examples/thumb_burst.rsnew file mode 100644index 000000000..87b18f421--- /dev/null+++ b/crates/ui-egui/examples/thumb_burst.rs@@ -0,0 +1,88 @@+//! Memory of the thumbnail burst that follows an import (issue: 6+ GB while importing 42 4K H.264+//! clips with hardware decoding off).+//!+//! Imports every `*.mp4` of a directory one by one, as the Project panel does, and asks for each+//! clip's poster thumbnail (priority 50, 160 px) through the real [`FrameServer`] right after its+//! import. Prints the wall time until every thumbnail is ready and the peak number of live+//! decoders. Measure the process' private bytes from outside (`stress.py`'s sampler, or any+//! process monitor).+//!+//! ```sh+//! cargo run --release -p filmcraft-ui-egui --example thumb_burst -- <clips dir> [--hw off|auto] [--limit N]+//! ```++use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use filmcraft_engine::Session;+use filmcraft_project::ItemId;+use filmcraft_ui_egui::frames::{FrameKey, FrameServer, Target};+use serde_json::json;++fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let value = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();+ let Some(dir) = args.first().filter(|a| !a.starts_with("--")).map(PathBuf::from) else {+ eprintln!("usage: thumb_burst <clips dir> [--hw off|auto] [--limit N]");+ return;+ };+ filmcraft_codecs::hw::set_hardware_decoding(value("--hw").as_deref() != Some("off"));+ let limit = value("--limit").and_then(|v| v.parse().ok()).unwrap_or(usize::MAX);+ let mut clips: Vec<PathBuf> = std::fs::read_dir(&dir).map(|d| d.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default();+ clips.retain(|p| p.extension().is_some_and(|e| e == "mp4"));+ clips.sort();+ clips.truncate(limit);++ let mut s = Session::default();+ let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), FrameServer::default_workers());++ let peak = std::sync::Arc::new(AtomicUsize::new(0));+ let stop = std::sync::Arc::new(AtomicBool::new(false));+ let sampler = {+ let (peak, stop) = (peak.clone(), stop.clone());+ std::thread::spawn(move || {+ while !stop.load(Ordering::Relaxed) {+ peak.fetch_max(filmcraft_codecs::live_decoders(), Ordering::Relaxed);+ std::thread::sleep(Duration::from_millis(5));+ }+ })+ };++ let t0 = Instant::now();+ let mut keys = Vec::new();+ for path in &clips {+ let r = s.execute("file.import", json!({"paths": [path.to_string_lossy()]})).expect("import");+ let id = ItemId(r["items"][0].as_u64().expect("item"));+ let (rate, width) = match s.project.item(id).map(|i| (i.frame_rate(), &i.kind)) {+ Some((rate, filmcraft_project::ItemKind::Media(m))) => (rate, m.info.video.as_ref().map_or(1920, |v| v.width)),+ _ => continue,+ };+ let rev = {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ if let Some(filmcraft_project::ItemKind::Media(m)) = s.project.item(id).map(|i| &i.kind) {+ filmcraft_engine::media_pool::media_key(m).hash(&mut h);+ false.hash(&mut h);+ }+ h.finish()+ };+ let key = FrameKey { target: Target::Item(id), frame: 0, size: 160, revision: rev, draft: false };+ server.request(key, rate.tick_of(0), 160.0 / width.max(1) as f32, &s.project.clone(), 50);+ keys.push(key);+ }+ let imported = t0.elapsed();+ while keys.iter().any(|k| !server.is_ready(k)) && t0.elapsed() < Duration::from_secs(300) {+ std::thread::sleep(Duration::from_millis(10));+ }+ stop.store(true, Ordering::Relaxed);+ let _ = sampler.join();+ println!(+ "clips {} imported in {:.2}s, all thumbnails ready after {:.2}s, peak live decoders {}, gop frames cached {:.0} MB",+ keys.len(),+ imported.as_secs_f64(),+ t0.elapsed().as_secs_f64(),+ peak.load(Ordering::Relaxed),+ filmcraft_codecs::cached_bytes() as f64 / 1048576.0+ );+}diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rsindex 6e0ef1ef0..4f376de29 100644--- a/crates/ui-egui/src/frames.rs+++ b/crates/ui-egui/src/frames.rs@@ -35,6 +35,22 @@ pub enum Target {MulticamAngle(ItemId, u32),}+/// Item jobs at this priority or a larger number are background work: thumbnails of the Project+/// panel and the timeline (50) and the Media Browser (40). Monitors and playback use 0..=3. Their+/// decoders are small and are not kept (`filmcraft_media::cancel::with_background`).+pub const BACKGROUND_PRIO: u32 = 40;++/// Whether a job is a thumbnail: a single item at a background priority. Sequence frames are never+/// background, whatever their priority (the scopes ask for the program frame at 40 while playing,+/// and must not turn the program's decoders into small ones).+fn is_background(job: &Job) -> bool {+ background_work(job.prio, job.key.target)+}++fn background_work(prio: u32, target: Target) -> bool {+ prio >= BACKGROUND_PRIO && matches!(target, Target::Item(_))+}+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub struct FrameKey {pub target: Target,@@ -804,23 +820,25 @@ fn run_job(sh: &Shared, job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Serlet preview = filmcraft_media::cancel::with_cancel(&job.cancel, || {filmcraft_media::cancel::with_catch_up(job.catch_up, || {filmcraft_media::cancel::with_draft(job.key.draft, || {- if let Target::SequencePlan(seq) = job.key.target {- let (plan, pv) = plan_job(job, seq, pool, services, previews);- loading = filmcraft_media::pending::take();- if !job.cancel.load(Ordering::Relaxed) && !loading {- // Convert texels for upload here, not on the UI thread when the frame is shown.- let prepared = filmcraft_gpu::prepare(&plan);- sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });- }- pv- } else {- let (img, pv) = render_job(job, pool, services, previews);- loading = filmcraft_media::pending::take();- if !job.cancel.load(Ordering::Relaxed) && !loading {- sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));+ filmcraft_media::cancel::with_background(is_background(job), || {+ if let Target::SequencePlan(seq) = job.key.target {+ let (plan, pv) = plan_job(job, seq, pool, services, previews);+ loading = filmcraft_media::pending::take();+ if !job.cancel.load(Ordering::Relaxed) && !loading {+ // Convert texels for upload here, not on the UI thread when the frame is shown.+ let prepared = filmcraft_gpu::prepare(&plan);+ sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });+ }+ pv+ } else {+ let (img, pv) = render_job(job, pool, services, previews);+ loading = filmcraft_media::pending::take();+ if !job.cancel.load(Ordering::Relaxed) && !loading {+ sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));+ }+ pv}- pv- }+ })})})});@@ -949,7 +967,21 @@ fn render_job(job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Services>, pr#[cfg(test)]mod tests {- use super::{PlaybackMeter, playback_plan};+ use super::{PlaybackMeter, Target, background_work, playback_plan};+ use filmcraft_project::ItemId;++ #[test]+ fn only_item_thumbnails_are_background_work() {+ let item = Target::Item(ItemId(1));+ // thumbnails (50) and the Media Browser (40)+ assert!(background_work(50, item));+ assert!(background_work(40, item));+ // the Source monitor shows an item at a foreground priority+ assert!(!background_work(1, item));+ // the scopes ask for the program frame at 40 while playing: never background+ assert!(!background_work(40, Target::Sequence(ItemId(1))));+ assert!(!background_work(50, Target::SequencePlan(ItemId(1))));+ }#[test]fn draft_decoding_only_for_reduced_resolution_playback() {