FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
codecs: released decoders are dropped off the cache lock; dirty-pool bit-exact test
Brandon Thomas6a9fdce2ef5e
diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rsindex 8b49a97fc..b1ddd9a2e 100644--- a/crates/codecs/src/gop.rs+++ b/crates/codecs/src/gop.rs@@ -273,9 +273,8 @@ impl Pool {g.push(Arc::downgrade(c));}- /// The idle caches other than `me` that `keep` selects, least recently used first. Called- /// with `me` locked: other caches are only ever try-locked, so two caches trimming each other- /// cannot deadlock.+ /// The idle caches other than `me` that `keep` selects, least recently used first. Other+ /// caches are only ever try-locked, so two caches trimming each other cannot deadlock.fn idle_others(&self, me: &Shared, keep: impl Fn(&State) -> bool) -> Vec<Arc<Shared>> {let all: Vec<Arc<Shared>> = self.caches.lock().unwrap_or_else(PoisonError::into_inner).iter().filter_map(Weak::upgrade).collect();let mut idle: Vec<(Instant, Arc<Shared>)> = all@@ -290,18 +289,24 @@ impl Pool {idle.into_iter().map(|(_, c)| c).collect()}- /// Drop the decoders of idle caches, least recently used first, down to the cap.- fn trim_decoders(&self, me: &Shared) {+ /// Take the decoders of idle caches, least recently used first, down to the cap. The caller+ /// drops them with no cache lock held: dropping a decoder can block (a hardware session waits+ /// for its frames in flight).+ #[must_use = "drop the released decoders with no cache lock held"]+ fn trim_decoders(&self, me: &Shared) -> Vec<Box<dyn VideoDecoder>> {+ let mut released = Vec::new();if self.decoders.load(Ordering::Relaxed) <= self.max_decoders {- return;+ return released;}for c in self.idle_others(me, |st| st.decoder.is_some()) {if self.decoders.load(Ordering::Relaxed) <= self.max_decoders {break;}- let released = try_state(&c).map(|mut st| st.release_decoder(self));- drop(released);+ if let Some(mut st) = try_state(&c) {+ released.extend(st.release_decoder(self));+ }}+ released}/// Evict the frames of idle caches, least recently used first, down to the budget. Caches in@@ -470,6 +475,10 @@ impl GopCache {return self.private_frame(s, i, want_pts, n);}let draft = filmcraft_media::cancel::draft();+ // Idle caches' decoders released below. Declared before the lock guard, so it is dropped+ // after the guard on every return path: dropping a decoder can block (a hardware session+ // waits for its frames in flight) and must not hold this cache's lock.+ let mut released: Vec<Box<dyn VideoDecoder>> = Vec::new();let mut st = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());let _decoding = DecodingGuard::enter(me);st.last_used = Instant::now();@@ -485,7 +494,7 @@ impl GopCache {st.next = usize::MAX;self.shared.pool.decoders.fetch_add(1, Ordering::Relaxed);}- self.shared.pool.trim_decoders(&self.shared);+ released.extend(self.shared.pool.trim_decoders(&self.shared));// 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() {diff --git a/crates/codecs/tests/pool_bitexact.rs b/crates/codecs/tests/pool_bitexact.rsnew file mode 100644index 000000000..a90ec658e--- /dev/null+++ b/crates/codecs/tests/pool_bitexact.rs@@ -0,0 +1,63 @@+//! Decoded pictures are written into recycled plane buffers (`filmcraft_frame::pool`). A recycled+//! buffer still holds an old picture, so the decoder must overwrite every byte: here the pool is+//! primed with buffers full of 0xAA before decoding, and every frame must still match ffmpeg bit+//! for bit. (Its own process: the pool is global.)++mod common;++use std::sync::Arc;++use common::*;+use filmcraft_frame::{Chroma, PixelData, VideoFrame};+use filmcraft_media::FrameRequest;++#[test]+fn dirty_recycled_planes_decode_bit_exact() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ // 640×480: luma and chroma planes are both large enough to be pooled+ let Some(file) = fixture(+ &ff,+ "pool_h264.mp4",+ &[+ "-f",+ "lavfi",+ "-i",+ "testsrc2=s=640x480:r=24:d=1,noise=alls=10:allf=t",+ "-c:v",+ "libx264",+ "-preset",+ "fast",+ "-x264-params",+ "bframes=2:keyint=12",+ "-pix_fmt",+ "yuv420p",+ ],+ ) else {+ return;+ };+ let (w, h) = (640usize, 480usize);+ let raw = ffmpeg_frames(&ff, &file, "yuv420p");+ let fsize = w * h * 3 / 2;+ let n = raw.len() / fsize;+ assert!(n >= 20, "{n} frames");+ let reference = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, w / 2, h / 2, 1);++ // prime the pool with dirty buffers of exactly the plane sizes the decoder asks for+ for _ in 0..8 {+ let dirty = |len: usize| Arc::new(vec![0xAAu8; len]);+ let f = VideoFrame {+ data: PixelData::Yuv8 { planes: [dirty(w * h), dirty(w * h / 4), dirty(w * h / 4)], chroma: Chroma::C420, alpha: None },+ ..VideoFrame::rgba8(w as u32, h as u32, vec![0; w * h * 4])+ };+ filmcraft_frame::pool::recycle(Arc::new(f));+ }+ let reused_before = filmcraft_frame::pool::stats().reused;++ let src = filmcraft_codecs::open_bytes("pool_h264.mp4", bytes(&file)).expect("open");+ let rate = src.info().frame_rate();+ for i in 0..n {+ let f = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).expect("frame");+ assert_eq!(max_diff(&planes(&f), &reference(i)), 0, "frame {i} decoded into a recycled buffer");+ }+ assert!(filmcraft_frame::pool::stats().reused > reused_before, "the decoder took the dirty pooled buffers");+}