Skip to content

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

M4.9: draft decoding for reduced-resolution playback (opt-in preference)

Brandon Thomas1f4546d54986
diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rs
index 9acdbde3e..52c29ecb9 100644
--- a/crates/codecs/src/gop.rs
+++ b/crates/codecs/src/gop.rs
@@ -31,6 +31,8 @@ pub struct GopStats {
pub decode_ns: u64,
/// Non-reference samples left out while catching up (frames already late).
pub skipped: u64,
+ /// Frames decoded in draft mode (reduced-resolution playback, [`VideoDecoder::set_draft`]).
+ pub draft: u64,
}
impl GopStats {
@@ -53,6 +55,7 @@ static DECODED: AtomicU64 = AtomicU64::new(0);
static EVICTED: AtomicU64 = AtomicU64::new(0);
static DECODE_NS: AtomicU64 = AtomicU64::new(0);
static SKIPPED: AtomicU64 = AtomicU64::new(0);
+static DRAFT: AtomicU64 = AtomicU64::new(0);
/// Run a decoder call, adding its wall time to the process-wide counter.
fn timed<R>(f: impl FnOnce() -> R) -> R {
@@ -72,6 +75,7 @@ pub fn gop_stats() -> GopStats {
evicted: EVICTED.load(Ordering::Relaxed),
decode_ns: DECODE_NS.load(Ordering::Relaxed),
skipped: SKIPPED.load(Ordering::Relaxed),
+ draft: DRAFT.load(Ordering::Relaxed),
}
}
@@ -86,6 +90,7 @@ impl std::ops::Sub for GopStats {
evicted: self.evicted - o.evicted,
decode_ns: self.decode_ns - o.decode_ns,
skipped: self.skipped - o.skipped,
+ draft: self.draft - o.draft,
}
}
}
@@ -116,9 +121,23 @@ struct State {
out_max: i64,
/// Decoded frames by presentation pts (bounded).
frames: BTreeMap<i64, Arc<VideoFrame>>,
+ /// The cached frames that were decoded in draft mode: served to draft requests only.
+ drafts: std::collections::BTreeSet<i64>,
bytes: usize,
}
+impl State {
+ /// The cached frame at `pts`, unless it is a draft frame and the request wants the exact one.
+ fn cached(&self, pts: i64, draft_ok: bool) -> Option<&Arc<VideoFrame>> {
+ self.frames.get(&pts).filter(|_| draft_ok || !self.drafts.contains(&pts))
+ }
+
+ /// The nearest usable frame at or before `pts` (robust to decoder pts quirks).
+ fn at_or_before(&self, pts: i64, draft_ok: bool) -> Option<Arc<VideoFrame>> {
+ self.cached(pts, draft_ok).or_else(|| self.frames.range(..=pts).rev().find(|(p, _)| draft_ok || !self.drafts.contains(p)).map(|(_, f)| f)).cloned()
+ }
+}
+
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()) };
@@ -177,6 +196,7 @@ impl GopCache {
start: 0,
out_max: i64::MIN,
frames: BTreeMap::new(),
+ drafts: Default::default(),
bytes: 0,
}),
explicit_color,
@@ -193,8 +213,14 @@ impl GopCache {
}
}
- fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame) {
+ fn store(&self, st: &mut State, pts: i64, mut f: VideoFrame, draft: bool) {
self.apply_color(&mut f);
+ if draft {
+ st.drafts.insert(pts);
+ DRAFT.fetch_add(1, Ordering::Relaxed);
+ } else {
+ st.drafts.remove(&pts);
+ }
let budget = self.budget.max(MIN_FRAMES * f.byte_size());
st.bytes += f.byte_size();
if let Some(old) = st.frames.insert(pts, Arc::new(f)) {
@@ -206,6 +232,7 @@ impl GopCache {
let last = *st.frames.keys().next_back().expect("non-empty");
let victim = if pts - first > last - pts { first } else { last };
if let Some(v) = st.frames.remove(&victim) {
+ st.drafts.remove(&victim);
st.bytes -= v.byte_size();
EVICTED.fetch_add(1, Ordering::Relaxed);
}
@@ -216,7 +243,7 @@ impl GopCache {
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);
+ self.store(st, d.pts, d.frame, d.draft);
}
}
@@ -234,6 +261,10 @@ impl GopCache {
/// late. Non-reference samples of late frames are left out on the way to the wanted frame
/// (no other picture depends on them, so the wanted frame decodes exactly as it would
/// otherwise; a later request for a skipped frame re-seeks).
+ ///
+ /// Inside [`filmcraft_media::cancel::with_draft`]`(true, …)` the decoder runs in draft mode
+ /// ([`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 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()))?;
@@ -242,9 +273,10 @@ impl GopCache {
if DecodingGuard::active(me) {
return self.private_frame(s, i, want_pts, n);
}
+ let draft = filmcraft_media::cancel::draft();
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) {
+ if let Some(f) = st.cached(want_pts, draft) {
HITS.fetch_add(1, Ordering::Relaxed);
return Ok(f.clone());
}
@@ -293,6 +325,7 @@ impl GopCache {
}
let limit = (i.max(st.next) + 64).min(n);
let late = late_before.unwrap_or(i64::MIN).min(want_pts);
+ st.decoder.as_mut().expect("decoder").set_draft(draft);
while st.next < limit {
if filmcraft_media::cancel::cancelled() {
// The decoder state stays consistent (`next`, `out_max`): a later request continues.
@@ -309,21 +342,17 @@ impl GopCache {
st.next += 1;
DECODED.fetch_add(1, Ordering::Relaxed);
self.store_output(&mut st, out);
- if st.frames.contains_key(&want_pts) {
+ if st.cached(want_pts, draft).is_some() {
break;
}
}
- if !st.frames.contains_key(&want_pts) {
+ if st.cached(want_pts, draft).is_none() {
let out = timed(|| 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
- .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()))
+ st.at_or_before(want_pts, draft).ok_or_else(|| CodecError::Decode("frame not produced".into()))
}
/// A nested request (see [`Self::frame`]): decode from the sync sample with a fresh decoder,
@@ -407,13 +436,9 @@ impl GopCache {
st.spare.push(dec);
}
for d in res? {
- self.store(&mut st, d.pts, d.frame);
+ self.store(&mut st, d.pts, d.frame, d.draft);
}
- 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()))
+ st.at_or_before(want_pts, true).ok_or_else(|| CodecError::Decode("frame not produced".into()))
}
}
@@ -438,20 +463,24 @@ mod tests {
struct Dec {
delay: usize,
intra: bool,
- held: VecDeque<i64>,
+ /// (pts, decoded as a draft picture)
+ held: VecDeque<(i64, bool)>,
+ draft: bool,
resets: Arc<AtomicUsize>,
decodes: Arc<AtomicUsize>,
}
- fn picture(pts: i64) -> DecodedFrame {
+ /// A picture whose pixel encodes its index (and, in blue, whether it is a draft picture).
+ fn picture((pts, draft): (i64, bool)) -> DecodedFrame {
let i = (pts / 1000) as u32;
- DecodedFrame { pts, frame: VideoFrame::rgba8(1, 1, vec![i as u8, (i >> 8) as u8, 0, 255]) }
+ DecodedFrame { pts, frame: VideoFrame::rgba8(1, 1, vec![i as u8, (i >> 8) as u8, draft as u8, 255]), draft }
}
impl VideoDecoder for Dec {
- fn decode(&mut self, _sample: &[u8], pts: i64) -> crate::Result<Vec<DecodedFrame>> {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> crate::Result<Vec<DecodedFrame>> {
self.decodes.fetch_add(1, Ordering::Relaxed);
- self.held.push_back(pts);
+ // like H.264 draft mode: only non-reference (odd) pictures are approximate
+ self.held.push_back((pts, self.draft && sample[0] % 2 == 1));
let mut out = Vec::new();
while self.held.len() > self.delay {
out.push(picture(self.held.pop_front().expect("held")));
@@ -465,6 +494,9 @@ mod tests {
self.resets.fetch_add(1, Ordering::Relaxed);
self.held.clear();
}
+ fn set_draft(&mut self, on: bool) {
+ self.draft = on;
+ }
fn name(&self) -> &str {
"test"
}
@@ -495,7 +527,14 @@ mod tests {
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() }))
+ Ok(Box::new(Dec {
+ delay: self.delay,
+ intra: self.intra,
+ held: VecDeque::new(),
+ draft: false,
+ resets: self.resets.clone(),
+ decodes: self.decodes.clone(),
+ }))
}
}
@@ -592,6 +631,43 @@ mod tests {
assert_eq!(s3.resets.load(Ordering::Relaxed), 1);
}
+ fn is_draft(f: &VideoFrame) -> bool {
+ match &f.data {
+ filmcraft_frame::PixelData::Rgba8(d) => d[2] == 1,
+ _ => unreachable!(),
+ }
+ }
+
+ #[test]
+ fn draft_frames_are_served_to_draft_requests_only() {
+ let s = samples(300, 250, 3, false);
+ let c = GopCache::new(None);
+ let before = gop_stats().draft;
+ // reduced-resolution playback: odd (non-reference) pictures come out as drafts
+ for i in 0..12usize {
+ let f = filmcraft_media::cancel::with_draft(true, || c.frame(&s, i as i64 * 1000)).expect("frame");
+ assert_eq!(index_of(&f), i);
+ assert_eq!(is_draft(&f), i % 2 == 1, "frame {i}");
+ }
+ assert!(gop_stats().draft - before >= 6);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 1);
+ // paused / export (no draft hint): an even frame is exact and cached
+ let f = c.frame(&s, 4_000).expect("frame");
+ assert!(!is_draft(&f) && index_of(&f) == 4);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 1, "exact frames are served from the cache");
+ // a draft frame is decoded again, exactly
+ let f = c.frame(&s, 5_000).expect("frame");
+ assert!(!is_draft(&f) && index_of(&f) == 5);
+ assert_eq!(s.resets.load(Ordering::Relaxed), 2, "re-decoded from the sync sample");
+ // and a draft request takes the exact frame now cached
+ let f = filmcraft_media::cancel::with_draft(true, || c.frame(&s, 5_000)).expect("frame");
+ assert!(!is_draft(&f));
+ // without the hint nothing is ever a draft
+ let s2 = samples(300, 250, 3, false);
+ let c2 = GopCache::new(None);
+ assert!((0..12).all(|i| !is_draft(&c2.frame(&s2, i * 1000).expect("frame"))));
+ }
+
#[test]
fn cancelled_request_stops_decoding_and_keeps_state() {
let s = samples(300, 250, 0, false);
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index be39c6adb..20cfe49b3 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -9,6 +9,9 @@ use crate::{CodecError, Result};
pub struct DecodedFrame {
pub pts: i64,
pub frame: VideoFrame,
+ /// Decoded in draft mode ([`VideoDecoder::set_draft`]): approximate, for reduced-resolution
+ /// playback only.
+ pub draft: bool,
}
/// A stateful video decoder. Samples are fed in decode order; pictures come out in
@@ -37,6 +40,11 @@ pub trait VideoDecoder: Send {
fn is_disposable(&self, _sample: &[u8]) -> bool {
false
}
+ /// Draft decoding for reduced-resolution playback (off by default; see
+ /// [`filmcraft_media::cancel::with_draft`]): samples fed from now on may be decoded with
+ /// 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) {}
}
/// NAL unit headers of a length-prefixed (avcC / hvcC) sample: the first two bytes of each unit.
@@ -132,7 +140,7 @@ impl VideoDecoder for MjpegDecoder {
let img = image::load_from_memory_with_format(sample, image::ImageFormat::Jpeg).map_err(|e| CodecError::Decode(e.to_string()))?;
let rgba = img.to_rgba8();
let (w, h) = rgba.dimensions();
- Ok(vec![DecodedFrame { pts, frame: VideoFrame::rgba8(w, h, rgba.into_raw()) }])
+ Ok(vec![DecodedFrame { pts, frame: VideoFrame::rgba8(w, h, rgba.into_raw()), draft: false }])
}
fn flush(&mut self) -> Vec<DecodedFrame> {
Vec::new()
@@ -155,20 +163,22 @@ pub struct H264Decoder {
avcc: Vec<u8>,
dec: filmcraft_h264::Decoder,
length_size: usize,
+ draft: bool,
}
impl H264Decoder {
pub fn new(avcc: Vec<u8>) -> Result<Self> {
let dec = filmcraft_h264::Decoder::from_avcc(&avcc).map_err(|e| CodecError::Decode(e.to_string()))?;
let length_size = avcc.get(4).map_or(4, |b| (b & 3) as usize + 1);
- Ok(Self { avcc, dec, length_size })
+ Ok(Self { avcc, dec, length_size, draft: false })
}
/// A decoder for Annex B byte-stream samples (start codes, in-band parameter sets: MXF, TS).
pub fn annexb() -> Self {
- Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::new(), length_size: 0 }
+ Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::new(), length_size: 0, draft: false }
}
fn convert(p: filmcraft_h264::Picture) -> DecodedFrame {
use std::sync::Arc;
+ let draft = p.draft;
let (w, h) = (p.width as usize, p.height as usize);
let (cw, ch) = (p.chroma_width as usize, p.chroma_height as usize);
let y = tight_plane(p.y, p.y_stride, w, h);
@@ -193,7 +203,7 @@ impl H264Decoder {
par,
pts: filmcraft_time::Tick::ZERO,
};
- DecodedFrame { pts: p.pts, frame }
+ DecodedFrame { pts: p.pts, frame, draft }
}
}
@@ -211,10 +221,15 @@ impl VideoDecoder for H264Decoder {
} else if let Ok(d) = filmcraft_h264::Decoder::from_avcc(&self.avcc) {
self.dec = d;
}
+ self.dec.set_draft(self.draft);
}
fn name(&self) -> &str {
"FilmCraft H.264"
}
+ fn set_draft(&mut self, on: bool) {
+ self.draft = on;
+ self.dec.set_draft(on);
+ }
fn is_disposable(&self, sample: &[u8]) -> bool {
if self.length_size == 0 {
return h264_disposable_annexb(sample);
@@ -227,6 +242,11 @@ impl VideoDecoder for H264Decoder {
}
}
+/// Worker threads each H.264 decoder uses (frame threading; 1 on wasm).
+pub fn h264_threads() -> usize {
+ filmcraft_h264::default_threads()
+}
+
pub fn h264_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
match &e.codec {
CodecConfig::Avc(a) => Some(H264Decoder::new(a.to_bytes()).map(|d| Box::new(d) as Box<dyn VideoDecoder>)),
@@ -287,7 +307,7 @@ impl HevcDecoder {
}
let par = if p.sar.0 > 0 && p.sar.1 > 0 { (p.sar.0 as u32, p.sar.1 as u32) } else { (1, 1) };
let frame = VideoFrame { width: p.width, height: p.height, data, color, par, pts: filmcraft_time::Tick::ZERO };
- DecodedFrame { pts: p.pts, frame }
+ DecodedFrame { pts: p.pts, frame, draft: false }
}
}
@@ -388,7 +408,7 @@ impl Vp9Decoder {
}
let mut frame = VideoFrame::rgba8(p.width, p.height, rgba);
frame.color = filmcraft_color::ColorInfo { range: Range::Full, transfer: filmcraft_color::Transfer::Srgb, ..color };
- return DecodedFrame { pts, frame };
+ return DecodedFrame { pts, frame, draft: false };
}
// 4:4:0 has no frame format of its own: chroma rows are repeated to 4:4:4.
let (chroma, rows_440) = match (p.subsampling_x, p.subsampling_y) {
@@ -425,7 +445,7 @@ impl Vp9Decoder {
// render_size (the intended display size) is not applied: the container's display
// dimensions / pixel aspect describe the presentation.
let par = (1, 1);
- DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par, pts: filmcraft_time::Tick::ZERO } }
+ DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par, pts: filmcraft_time::Tick::ZERO }, draft: false }
}
}
@@ -509,7 +529,7 @@ impl Av1Decoder {
} else {
filmcraft_frame::PixelData::Yuv16 { planes: [Arc::new(y), Arc::new(u), Arc::new(v)], chroma, bits: p.bit_depth as u32, alpha: None }
};
- DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par: (1, 1), pts: filmcraft_time::Tick::ZERO } }
+ DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par: (1, 1), pts: filmcraft_time::Tick::ZERO }, draft: false }
}
}
@@ -591,7 +611,7 @@ impl VideoDecoder for ProResDecoder {
par: (1, 1),
pts: filmcraft_time::Tick::ZERO,
};
- Ok(vec![DecodedFrame { pts, frame }])
+ Ok(vec![DecodedFrame { pts, frame, draft: false }])
}
fn flush(&mut self) -> Vec<DecodedFrame> {
Vec::new()
@@ -663,7 +683,7 @@ pub fn dnx_to_video_frame(f: filmcraft_dnx::Frame) -> VideoFrame {
impl VideoDecoder for DnxDecoder {
fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
let f = filmcraft_dnx::decode_frame(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
- Ok(vec![DecodedFrame { pts, frame: dnx_to_video_frame(f) }])
+ Ok(vec![DecodedFrame { pts, frame: dnx_to_video_frame(f), draft: false }])
}
fn flush(&mut self) -> Vec<DecodedFrame> {
Vec::new()
diff --git a/crates/codecs/tests/h264_draft.rs b/crates/codecs/tests/h264_draft.rs
new file mode 100644
index 000000000..81e8c3bb8
--- /dev/null
+++ b/crates/codecs/tests/h264_draft.rs
@@ -0,0 +1,68 @@
+//! H.264 draft decoding (opt-in, reduced-resolution playback) through the media stack: it is off
+//! by default, its approximate frames only ever reach draft requests, and decoding for an export
+//! after draft playback (same source, same GOP cache) still matches ffmpeg bit for bit.
+
+mod common;
+
+use common::*;
+use filmcraft_media::FrameRequest;
+use filmcraft_media::cancel::with_draft;
+
+#[test]
+fn draft_playback_never_reaches_exports() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ // B-pyramid: references and non-reference B pictures (the ones draft mode leaves unfiltered)
+ let Some(file) = fixture(
+ &ff,
+ "draft_h264.mp4",
+ &[
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=s=320x240:r=24:d=2,noise=alls=10:allf=t",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "fast",
+ "-x264-params",
+ "bframes=3:b-pyramid=normal:keyint=48",
+ "-pix_fmt",
+ "yuv420p",
+ ],
+ ) else {
+ return;
+ };
+ let raw = ffmpeg_frames(&ff, &file, "yuv420p");
+ let (w, h) = (320usize, 240usize);
+ let fsize = w * h * 3 / 2;
+ let n = raw.len() / fsize;
+ assert!(n >= 40, "{n} frames");
+ let reference = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, w / 2, h / 2, 1);
+ let src = filmcraft_codecs::open_bytes("draft_h264.mp4", bytes(&file)).expect("open");
+ let rate = src.info().frame_rate();
+
+ // Default: nothing is a draft, every frame exact.
+ let g0 = filmcraft_codecs::gop_stats();
+ for i in 0..n {
+ let f = src.video_frame(FrameRequest { time: rate.tick_of(i as i64), scale: 0.5 }).expect("frame");
+ assert_eq!(max_diff(&planes(&f), &reference(i)), 0, "frame {i} without draft mode");
+ }
+ assert_eq!(filmcraft_codecs::gop_stats().draft, g0.draft, "draft decoding is off by default");
+
+ // Draft playback at 1/2 resolution on a fresh source: non-reference pictures are drafts.
+ let src = filmcraft_codecs::open_bytes("draft_h264.mp4", bytes(&file)).expect("open");
+ let g1 = filmcraft_codecs::gop_stats();
+ let mut approximate = 0;
+ for i in 0..n {
+ let f = with_draft(true, || src.video_frame(FrameRequest { time: rate.tick_of(i as i64), scale: 0.5 })).expect("frame");
+ approximate += (max_diff(&planes(&f), &reference(i)) > 0) as usize;
+ }
+ let drafts = filmcraft_codecs::gop_stats().draft - g1.draft;
+ assert!(drafts > 0 && approximate > 0 && approximate as u64 <= drafts, "{drafts} draft frames, {approximate} differ");
+
+ // Then an export from the same source (no draft hint): every frame is exact again.
+ 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, "export frame {i} after draft playback");
+ }
+}
diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs
index 211bf7b90..3e870b363 100644
--- a/crates/engine/src/autosave.rs
+++ b/crates/engine/src/autosave.rs
@@ -78,6 +78,10 @@ pub struct PlaybackPrefs {
pub pause_encoder_queue: bool,
pub enable_transmit: bool,
pub disable_video_in_background: bool,
+ /// Draft decoding while playing at 1/2 resolution or lower: H.264 non-reference pictures
+ /// skip deblocking (faster; those frames are approximate). Never used for exports, renders or
+ /// a paused frame. Off by default.
+ pub draft_decode: bool,
}
impl Default for PlaybackPrefs {
@@ -89,6 +93,7 @@ impl Default for PlaybackPrefs {
pause_encoder_queue: true,
enable_transmit: false,
disable_video_in_background: true,
+ draft_decode: false,
}
}
}
diff --git a/crates/engine/src/perf.rs b/crates/engine/src/perf.rs
index de656bc3c..c9eafbf95 100644
--- a/crates/engine/src/perf.rs
+++ b/crates/engine/src/perf.rs
@@ -17,6 +17,8 @@ pub fn decode_json() -> Value {
"seeks": g.seeks,
"samplesDecoded": g.decoded,
"samplesSkipped": g.skipped,
+ "draftFrames": g.draft,
+ "h264Threads": filmcraft_codecs::video::h264_threads(),
"evicted": g.evicted,
"decodeMs": g.decode_ns as f64 / 1e6,
"decodeMsPerSample": g.decode_ms_per_sample(),
@@ -46,7 +48,7 @@ mod tests {
s.execute("file.openDemoProject", json!({})).unwrap();
let undo = s.history.undo.len();
let v = s.execute("perf.stats", json!({})).unwrap();
- for k in ["requests", "cacheHitRate", "seeks", "samplesDecoded", "samplesSkipped", "decodeMs", "decodeMsPerSample"] {
+ for k in ["requests", "cacheHitRate", "seeks", "samplesDecoded", "samplesSkipped", "draftFrames", "h264Threads", "decodeMs", "decodeMsPerSample"] {
assert!(v["decode"][k].is_number(), "decode.{k} in {v}");
}
assert!(v["media"]["openSources"].is_number());
diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs
index 4f6d0eb31..57586d77c 100644
--- a/crates/engine/src/settings.rs
+++ b/crates/engine/src/settings.rs
@@ -951,6 +951,7 @@ static CATEGORIES: &[Category] = &[
b("playback.pauseEncoderQueue", "Pause Media Encoder queue during playback", false),
b("playback.enableTransmit", "Enable Mercury Transmit", false),
b("playback.disableVideoInBackground", "Disable video output when in the background", false),
+ b("playback.draftDecode", "Draft decoding at reduced playback resolution (H.264: faster, some frames less filtered)", true),
],
},
Category {
diff --git a/crates/frame/src/lib.rs b/crates/frame/src/lib.rs
index f7bfbe305..6a6670480 100644
--- a/crates/frame/src/lib.rs
+++ b/crates/frame/src/lib.rs
@@ -98,6 +98,51 @@ impl VideoFrame {
}
}
+ /// A planar Y'CbCr frame reduced by `n` (2, 4, 8…) in each direction: every sample (luma,
+ /// chroma at its own resolution, alpha) is the rounded mean of an `n`×`n` block, chroma format
+ /// and bit depth unchanged. Reduced-resolution playback hands the GPU this instead of the full
+ /// picture (a quarter / sixteenth of the upload). None for RGBA frames or `n` < 2.
+ pub fn box_decimated(&self, n: usize) -> Option<VideoFrame> {
+ if n < 2 {
+ return None;
+ }
+ let (w, h) = (self.width as usize, self.height as usize);
+ let (ow, oh) = ((w / n).max(1), (h / n).max(1));
+ let data = match &self.data {
+ PixelData::Yuv8 { planes, chroma, alpha } => {
+ let (sx, sy) = chroma.shifts();
+ let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy));
+ let (ocw, och) = (ow.div_ceil(1 << sx), oh.div_ceil(1 << sy));
+ PixelData::Yuv8 {
+ planes: [
+ Arc::new(box_plane(&planes[0], w, h, ow, oh, n)),
+ Arc::new(box_plane(&planes[1], cw, ch, ocw, och, n)),
+ Arc::new(box_plane(&planes[2], cw, ch, ocw, och, n)),
+ ],
+ chroma: *chroma,
+ alpha: alpha.as_ref().map(|a| Arc::new(box_plane(a, w, h, ow, oh, n))),
+ }
+ }
+ PixelData::Yuv16 { planes, chroma, bits, alpha } => {
+ let (sx, sy) = chroma.shifts();
+ let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy));
+ let (ocw, och) = (ow.div_ceil(1 << sx), oh.div_ceil(1 << sy));
+ PixelData::Yuv16 {
+ planes: [
+ Arc::new(box_plane(&planes[0], w, h, ow, oh, n)),
+ Arc::new(box_plane(&planes[1], cw, ch, ocw, och, n)),
+ Arc::new(box_plane(&planes[2], cw, ch, ocw, och, n)),
+ ],
+ chroma: *chroma,
+ bits: *bits,
+ alpha: alpha.as_ref().map(|a| Arc::new(box_plane(a, w, h, ow, oh, n))),
+ }
+ }
+ PixelData::Rgba8(_) | PixelData::RgbaF32(_) => return None,
+ };
+ Some(VideoFrame { width: ow as u32, height: oh as u32, data, color: self.color, par: self.par, pts: self.pts })
+ }
+
/// Convert to premultiplied linear RGBA f32 (the compositor's working format).
pub fn to_linear_f32(&self) -> Vec<f32> {
self.to_linear_f32_decimated(1).2
@@ -376,8 +421,59 @@ pub fn default_matrix(width: u32, height: u32) -> Matrix {
if width <= 1024 && height <= 576 { Matrix::Bt601 } else { Matrix::Bt709 }
}
+/// `n`×`n` box mean of a `w`×`h` plane into `ow`×`oh` (blocks clamped at the right / bottom).
+fn box_plane<T: Copy + Into<u32> + TryFrom<u32> + Send + Sync + Default>(src: &[T], w: usize, h: usize, ow: usize, oh: usize, n: usize) -> Vec<T> {
+ let mut out = vec![T::default(); ow * oh];
+ if w == 0 || h == 0 || src.len() < w * h {
+ return out;
+ }
+ out.par_chunks_mut(ow).enumerate().for_each(|(oy, row)| {
+ let mut acc = vec![0u32; ow];
+ let mut cnt = vec![0u32; ow];
+ for y in (oy * n..(oy + 1) * n).filter(|&y| y < h) {
+ let line = &src[y * w..y * w + w];
+ for ((a, c), chunk) in acc.iter_mut().zip(cnt.iter_mut()).zip(line.chunks(n)) {
+ *a += chunk.iter().map(|&v| v.into()).sum::<u32>();
+ *c += chunk.len() as u32;
+ }
+ }
+ for ((o, a), c) in row.iter_mut().zip(&acc).zip(&cnt) {
+ let c = (*c).max(1);
+ *o = T::try_from((a + c / 2) / c).unwrap_or_default();
+ }
+ });
+ out
+}
+
#[cfg(test)]
mod tests {
+
+ #[test]
+ fn box_decimation_averages_blocks_per_plane() {
+ // 6x4 4:2:0: luma ramp, chroma 3x2
+ let y: Vec<u8> = (0..24).map(|i| (i * 10) as u8).collect();
+ let u = vec![10, 20, 30, 40, 50, 60];
+ let v = vec![200; 6];
+ let f = VideoFrame {
+ width: 6,
+ height: 4,
+ data: PixelData::Yuv8 { planes: [Arc::new(y), Arc::new(u), Arc::new(v)], chroma: Chroma::C420, alpha: None },
+ color: ColorInfo::REC709,
+ par: (1, 1),
+ pts: Tick::ZERO,
+ };
+ let d = f.box_decimated(2).expect("yuv");
+ assert_eq!((d.width, d.height), (3, 2));
+ let PixelData::Yuv8 { planes, .. } = &d.data else { panic!() };
+ // luma block (0,0): 0, 10, 60, 70 -> 35
+ assert_eq!(planes[0][0], 35);
+ assert_eq!(planes[0].len(), 6);
+ // chroma 3x2 -> 2x1: blocks {10,20,40,50} = 30 and the clamped edge block {30,60} = 45
+ assert_eq!(&planes[1][..], &[30, 45]);
+ assert_eq!(&planes[2][..], &[200, 200]);
+ assert!(f.box_decimated(1).is_none());
+ assert!(VideoFrame::rgba8(2, 2, vec![0; 16]).box_decimated(2).is_none());
+ }
use super::*;
#[test]
diff --git a/crates/media/src/cancel.rs b/crates/media/src/cancel.rs
index b6622dadb..7848a845f 100644
--- a/crates/media/src/cancel.rs
+++ b/crates/media/src/cancel.rs
@@ -9,6 +9,10 @@
//! The same way, [`with_catch_up`] tells sources which frames before the requested one are late
//! (playback has passed them): a decoder that has to decode forward to the frame may skip
//! pictures that only produce late frames and that nothing else references.
+//!
+//! [`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.
use std::cell::{Cell, RefCell};
use std::sync::Arc;
@@ -19,6 +23,22 @@ use filmcraft_time::Tick;
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) };
+}
+
+/// Run `f` with the draft-decoding hint `on` (restoring the previous one after). Frames decoded
+/// in draft mode are only handed to requests made in draft mode.
+pub fn with_draft<R>(on: bool, f: impl FnOnce() -> R) -> R {
+ let prev = DRAFT.with(|c| c.replace(on));
+ let r = f();
+ DRAFT.with(|c| c.set(prev));
+ r
+}
+
+/// Whether the work running on this thread accepts draft-quality decoding (off unless inside
+/// [`with_draft`]`(true, …)`).
+pub fn draft() -> bool {
+ DRAFT.with(Cell::get)
}
/// Run `f` with the catch-up hint `margin` (restoring the previous one after): frames shown more
@@ -66,6 +86,17 @@ mod tests {
assert!(!cancelled());
}
+ #[test]
+ fn draft_is_off_by_default_and_scoped() {
+ assert!(!draft());
+ with_draft(true, || {
+ assert!(draft());
+ with_draft(false, || assert!(!draft()));
+ assert!(draft());
+ });
+ assert!(!draft());
+ }
+
#[test]
fn catch_up_is_scoped_to_the_closure() {
assert_eq!(catch_up(), None);
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 6f117a698..5c6a35e27 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -441,7 +441,7 @@ pub fn interpolation_blend(item: &TrackItem, t: Tick, src_rate: filmcraft_time::
}
/// Largest power-of-two box decimation that keeps at least `target_w` pixels of width.
-fn decimation(have_w: f32, target_w: f32) -> usize {
+pub(crate) fn decimation(have_w: f32, target_w: f32) -> usize {
let mut n = 1usize;
while n < 16 && have_w / (n as f32 * 2.0) >= target_w.max(1.0) {
n *= 2;
diff --git a/crates/render/src/plan.rs b/crates/render/src/plan.rs
index 76e74ab87..9f5202dd8 100644
--- a/crates/render/src/plan.rs
+++ b/crates/render/src/plan.rs
@@ -187,6 +187,15 @@ fn push_item(
// log / HDR / wide-gamut media is converted on the CPU (below), and so are blended
// in-between frames (Frame Blending / Optical Flow on speed-changed clips)
if !crate::colorman::needs_management(&seq.settings.color, cs, &frame) && crate::interpolation_blend(item, t, src.info().frame_rate()).is_none() {
+ // Draft playback at reduced resolution: hand over planes box-filtered to the size
+ // drawn instead of the full picture (a quarter at 1/2, a sixteenth at 1/4 of the
+ // upload and sampling). The mean is taken over Y'CbCr codes, not linear light as
+ // the shader's supersampling does, so this stays limited to the opt-in draft mode.
+ let n = if filmcraft_media::cancel::draft() { crate::decimation(frame.width as f32, size.0 as f32 * want) } else { 1 };
+ let frame = match frame.box_decimated(n) {
+ Some(small) => Arc::new(small),
+ None => frame,
+ };
let px_scale = frame.width as f64 / size.0.max(1) as f64;
let m = Affine::scale(opts.scale as f64, opts.scale as f64).then_apply(&motion).then_apply(&Affine::scale(1.0 / px_scale, 1.0 / px_scale));
out.push(PlanLayer { frame, matrix: m, opacity: op * extra_opacity });
diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs
index 36ada7ea8..4489447d8 100644
--- a/crates/render/src/tests.rs
+++ b/crates/render/src/tests.rs
@@ -299,3 +299,54 @@ fn offline_slate_is_deterministic_and_marked() {
::image::save_buffer(p, &a, 640, 360, ::image::ExtendedColorType::Rgba8).unwrap();
}
}
+
+/// A 320×180 4:2:0 source with smooth gradients (what decoders hand the renderer).
+struct YuvSource(GeneratorSource);
+
+impl MediaSource for YuvSource {
+ fn info(&self) -> &filmcraft_media::MediaInfo {
+ self.0.info()
+ }
+ fn video_frame(&self, _req: FrameRequest) -> filmcraft_media::Result<Arc<filmcraft_frame::VideoFrame>> {
+ let (w, h) = (320usize, 180usize);
+ let y = (0..w * h).map(|i| (16 + (i % w) * 200 / w + (i / w) * 20 / h) as u8).collect();
+ let u = (0..w * h / 4).map(|i| (90 + (i % (w / 2)) * 60 / (w / 2)) as u8).collect();
+ let v = (0..w * h / 4).map(|i| (100 + (i / (w / 2)) * 50 / (h / 2)) as u8).collect();
+ Ok(Arc::new(filmcraft_frame::VideoFrame {
+ width: w as u32,
+ height: h as u32,
+ data: filmcraft_frame::PixelData::Yuv8 { planes: [Arc::new(y), Arc::new(u), Arc::new(v)], chroma: filmcraft_frame::Chroma::C420, alpha: None },
+ color: filmcraft_color::ColorInfo::REC709,
+ par: (1, 1),
+ pts: Tick::ZERO,
+ }))
+ }
+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<filmcraft_frame::AudioBuffer> {
+ self.0.audio(start, frames, sample_rate)
+ }
+}
+
+#[test]
+fn draft_reduced_resolution_plans_carry_decimated_yuv() {
+ let (mut p, red, _ocean, seq, mut map) = setup();
+ let matte = GeneratorSource::new(Generator::ColorMatte { color: [0.0, 0.0, 0.0, 1.0] }, 320, 180, FrameRate::FPS_24, Tick(10 * TICKS_PER_SECOND));
+ map.0.insert(red, Arc::new(YuvSource(matte)) as SharedSource);
+ place(&mut p, seq, 0, red, 0, 48);
+ let t = FrameRate::FPS_24.tick_of(3);
+ for draft in [false, true] {
+ for (scale, small_w) in [(1.0f32, 320u32), (0.5, 160), (0.25, 80)] {
+ let opts = RenderOptions { scale, ..Default::default() };
+ let plan = filmcraft_media::cancel::with_draft(draft, || plan::plan_frame(&p, seq, t, opts, &map));
+ let plan::FramePlan::Layers { layers, .. } = &plan else { panic!("GPU-drawable") };
+ // exact playback hands over the decoded picture; draft playback planes at the drawn size
+ assert_eq!(layers[0].frame.width, if draft { small_w } else { 320 }, "scale {scale}, draft {draft}");
+ assert!(matches!(layers[0].frame.data, filmcraft_frame::PixelData::Yuv8 { .. }));
+ let got = plan::execute_cpu(&plan);
+ let reference = render_sequence(&p, seq, t, opts, &map);
+ assert_eq!((got.w, got.h), (reference.w, reference.h));
+ let max = got.px.iter().zip(&reference.px).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
+ // the Y'CbCr-code mean differs from a linear-light mean by a little on gradients
+ assert!(max < if draft { 0.03 } else { 1e-5 }, "scale {scale}, draft {draft}: max diff {max}");
+ }
+ }
+}
diff --git a/crates/ui-egui/examples/bench/main.rs b/crates/ui-egui/examples/bench/main.rs
index 597472ea3..89dd64d2c 100644
--- a/crates/ui-egui/examples/bench/main.rs
+++ b/crates/ui-egui/examples/bench/main.rs
@@ -258,6 +258,7 @@ pub fn section_markdown(v: &Value) -> String {
("ui_p95_ms", "UI p95 ms"),
("seeks", "seeks"),
("skipped", "skipped"),
+ ("draft_frames", "draft"),
("load", "load"),
],
1,
diff --git a/crates/ui-egui/examples/bench/playback.rs b/crates/ui-egui/examples/bench/playback.rs
index e412332a2..22710a7b3 100644
--- a/crates/ui-egui/examples/bench/playback.rs
+++ b/crates/ui-egui/examples/bench/playback.rs
@@ -229,6 +229,9 @@ pub struct Bench {
pub server: FrameServer,
pub refresh_hz: f64,
pub seconds: f64,
+ /// Play with draft decoding (Settings ▸ Playback ▸ Draft decoding), as the monitor does at
+ /// 1/2 resolution or lower.
+ pub draft: bool,
}
impl Bench {
@@ -253,7 +256,7 @@ impl Bench {
let last_frame = rate.frame_at(q.duration()) - 1;
let t_pre = Instant::now();
loop {
- let key = FrameKey { target, frame: first, size, revision: s.revision };
+ let key = FrameKey { target, frame: first, size, revision: s.revision, draft: self.draft };
self.server.schedule_playback(key, rate, scale, &project, 1.0, true);
let exact = display.refresh(&self.server, key);
meter.refresh(first, exact);
@@ -275,7 +278,7 @@ impl Bench {
}
frame = rate.frame_at(t);
due_at.entry(frame).or_insert(now);
- let key = FrameKey { target, frame, size, revision: s.revision };
+ let key = FrameKey { target, frame, size, revision: s.revision, draft: self.draft };
self.server.schedule_playback(key, rate, scale, &project, 1.0, false);
let exact = display.refresh(&self.server, key);
meter.refresh(frame, exact);
@@ -368,7 +371,7 @@ impl Bench {
rng ^= rng >> 7;
rng ^= rng << 17;
let frame = (rng % frames as u64) as i64;
- let key = FrameKey { target, frame, size, revision: s.revision };
+ let key = FrameKey { target, frame, size, revision: s.revision, draft: false };
let start = Instant::now();
rep.due += 1;
loop {
@@ -454,7 +457,7 @@ impl Bench {
};
for _ in 0..seeks {
let frame = (next() % frames as u64) as i64;
- let key = FrameKey { target, frame, size, revision: s.revision };
+ let key = FrameKey { target, frame, size, revision: s.revision, draft: false };
match wait(display, key, Instant::now()) {
Some(l) => rep.seek_ms.push(l),
None => rep.timeouts += 1,
@@ -463,7 +466,7 @@ impl Bench {
for _ in 0..drags {
let from = (next() % (frames - drag_frames).max(1) as u64) as i64;
for f in from..from + drag_frames {
- let key = FrameKey { target, frame: f.min(frames - 1), size, revision: s.revision };
+ let key = FrameKey { target, frame: f.min(frames - 1), size, revision: s.revision, draft: false };
self.server.request(key, rate.tick_of(key.frame), scale, &project, 0);
if display.refresh(&self.server, key) {
rep.drag_shown += 1;
@@ -471,7 +474,7 @@ impl Bench {
rep.drag_steps += 1;
std::thread::sleep(period);
}
- let key = FrameKey { target, frame: (from + drag_frames).min(frames - 1), size, revision: s.revision };
+ let key = FrameKey { target, frame: (from + drag_frames).min(frames - 1), size, revision: s.revision, draft: false };
match wait(display, key, Instant::now()) {
Some(l) => rep.settle_ms.push(l),
None => rep.timeouts += 1,
@@ -720,7 +723,7 @@ pub fn cli_main() {
// A fresh frame server per run so caches start cold, as after opening a project.
let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), args.workers);
server.set_profiling(true);
- let bench = Bench { server, refresh_hz: args.refresh, seconds: args.seconds };
+ let bench = Bench { server, refresh_hz: args.refresh, seconds: args.seconds, draft: false };
let mut display = Display::new(args.gpu);
if args.gpu && display.gpu.is_none() {
eprintln!("no GPU adapter; using the CPU path");
diff --git a/crates/ui-egui/examples/bench/sections.rs b/crates/ui-egui/examples/bench/sections.rs
index d25c2057f..95c47f452 100644
--- a/crates/ui-egui/examples/bench/sections.rs
+++ b/crates/ui-egui/examples/bench/sections.rs
@@ -149,23 +149,27 @@ pub fn seek(o: &Opts) -> Vec<Value> {
fn new_bench(s: &Session, seconds: f64) -> Bench {
let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), FrameServer::default_workers());
server.set_profiling(true);
- Bench { server, refresh_hz: 60.0, seconds }
+ Bench { server, refresh_hz: 60.0, seconds, draft: false }
}
/// Program-monitor playback through the real scheduler (see `playback.rs`), frames shown vs
/// dropped over N seconds.
pub fn playback(o: &Opts) -> Vec<Value> {
let seconds = if o.quick { 4.0 } else { 8.0 };
- let cases: &[(&str, &str, f32)] = &[
- ("h264-1080", "full", 1.0),
- ("stack3", "full", 1.0),
- ("h264-2160", "full", 1.0),
- ("h264-2160", "half", 0.5),
- ("hevc-2160", "full", 1.0),
- ("hevc-2160", "half", 0.5),
+ // (scenario, resolution, scale, draft decoding)
+ let cases: &[(&str, &str, f32, bool)] = &[
+ ("h264-1080", "full", 1.0, false),
+ ("stack3", "full", 1.0, false),
+ ("h264-2160", "full", 1.0, false),
+ ("h264-2160", "half", 0.5, false),
+ ("h264-2160", "half draft", 0.5, true),
+ ("h264-2160", "quarter", 0.25, false),
+ ("h264-2160", "quarter draft", 0.25, true),
+ ("hevc-2160", "full", 1.0, false),
+ ("hevc-2160", "half", 0.5, false),
];
let mut rows = Vec::new();
- for &(scenario, res, scale) in cases.iter().filter(|c| o.wants(&format!("{} {}", c.0, c.1))) {
+ for &(scenario, res, scale, draft) in cases.iter().filter(|c| o.wants(&format!("{} {}", c.0, c.1))) {
let Some((s, seq)) = playback::scenario_session(scenario) else {
eprintln!("playback {scenario}: skipped (fixtures unavailable)");
continue;
@@ -173,7 +177,8 @@ pub fn playback(o: &Opts) -> Vec<Value> {
let fps = s.project.sequence(seq).map(|q| q.settings.frame_rate.as_f64()).unwrap_or(24.0);
for rep in 0..o.repeat {
// A fresh frame server per run: caches start cold, as after opening a project.
- let bench = new_bench(&s, seconds);
+ let mut bench = new_bench(&s, seconds);
+ bench.draft = draft;
let mut display = Display::new(o.gpu);
let path = if display.gpu_available() { "gpu" } else { "cpu" };
let r = bench.play(&s, seq, &mut display, scale, Tick::ZERO, &format!("{scenario} {res} #{}", rep + 1));
@@ -184,6 +189,7 @@ pub fn playback(o: &Opts) -> Vec<Value> {
v["ui_p95_ms"] = json!(pct(&r.present, 0.95));
v["seeks"] = json!(r.gop.seeks);
v["skipped"] = json!(r.gop.skipped);
+ v["draft_frames"] = json!(r.gop.draft);
v["load"] = json!(r.load);
v["cores_needed"] = json!(r.process_cpu / frames * fps / 1000.0);
eprintln!("playback {scenario} {res}: {}/{} shown/dropped (load {})", r.shown, r.dropped, r.load);
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs
index 01810b374..b195cfbaa 100644
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@ -40,6 +40,17 @@ pub struct FrameKey {
/// Output width in pixels (thumbnails) or scale ×1000 (monitors).
pub size: u32,
pub revision: u64,
+ /// Draft decoding (reduced-resolution playback with Settings ▸ Playback ▸ Draft decoding):
+ /// sources may decode approximate non-reference pictures
+ /// ([`filmcraft_media::cancel::with_draft`]). Draft frames have their own keys, so a paused
+ /// monitor, an export or a render never shows one.
+ pub draft: bool,
+}
+
+/// Whether a monitor frame is requested with draft decoding ([`FrameKey::draft`]): only while
+/// playing, at 1/2 resolution or lower, with the preference on.
+pub fn draft_playback(playing: bool, scale: f32, enabled: bool) -> bool {
+ enabled && playing && scale <= 0.5
}
pub struct Rgba {
@@ -597,7 +608,7 @@ impl FrameServer {
/// The most recent cached frame for `target` at or before `frame` within `max_back` frames.
pub fn nearest(&self, target: Target, frame: i64, size: u32, revision: u64, max_back: i64) -> Option<Arc<Rgba>> {
for d in 0..=max_back {
- if let Some(v) = self.get(&FrameKey { target, frame: frame - d, size, revision }) {
+ if let Some(v) = self.get(&FrameKey { target, frame: frame - d, size, revision, draft: false }) {
return Some(v);
}
}
@@ -756,23 +767,25 @@ fn run_job(sh: &Shared, job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Ser
let mut loading = false;
let preview = filmcraft_media::cancel::with_cancel(&job.cancel, || {
filmcraft_media::cancel::with_catch_up(job.catch_up, || {
- 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_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));
+ }
+ pv
}
- pv
- }
+ })
})
});
let cancelled = job.cancel.load(Ordering::Relaxed);
@@ -894,6 +907,16 @@ fn render_job(job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Services>, pr
mod tests {
use super::{PlaybackMeter, playback_plan};
+ #[test]
+ fn draft_decoding_only_for_reduced_resolution_playback() {
+ use super::draft_playback;
+ assert!(draft_playback(true, 0.5, true) && draft_playback(true, 0.25, true));
+ assert!(!draft_playback(true, 1.0, true), "full resolution is never draft");
+ assert!(!draft_playback(false, 0.5, true), "a paused frame is never draft");
+ assert!(!draft_playback(true, 0.5, false), "off unless enabled");
+ assert!(!filmcraft_engine::autosave::Preferences::default().playback.draft_decode, "off by default");
+ }
+
#[test]
fn playback_plan_skips_frames_only_when_workers_cannot_keep_up() {
// decode-only / light frames: every frame from the playhead on
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index d603e23c2..c240e3765 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -625,7 +625,7 @@ impl FilmcraftApp {
let rate = pi.frame_rate();
let frame = rate.frame_at(t);
let rev = self.item_revision(item);
- let key = FrameKey { target: Target::Item(item), frame, size: width, revision: rev };
+ let key = FrameKey { target: Target::Item(item), frame, size: width, revision: rev, draft: false };
let name = format!("thumb-{}-{}-{}", item.0, frame, width);
if let Some(img) = self.frames.get(&key) {
let id = self.texture_for(ctx, &name, key, &img);
diff --git a/crates/ui-egui/src/panels/export_mode.rs b/crates/ui-egui/src/panels/export_mode.rs
index 5d8061bea..47accba57 100644
--- a/crates/ui-egui/src/panels/export_mode.rs
+++ b/crates/ui-egui/src/panels/export_mode.rs
@@ -820,7 +820,7 @@ fn preview_column(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, seq_id:
ui.painter().rect_filled(pic, 0.0, Color32::BLACK);
if app.ui.export.settings.has_video() {
let frame = rate.frame_at(app.session.playhead());
- let key = FrameKey { target: Target::Sequence(seq_id), frame, size: 500, revision: app.session.revision };
+ let key = FrameKey { target: Target::Sequence(seq_id), frame, size: 500, revision: app.session.revision, draft: false };
let project = app.session.project.clone();
app.frames.request(key, rate.tick_of(frame), 0.5, &project, 0);
if let Some(img) = app.frames.get(&key) {
diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rs
index 12e013e0e..3d264b402 100644
--- a/crates/ui-egui/src/panels/monitor.rs
+++ b/crates/ui-egui/src/panels/monitor.rs
@@ -154,7 +154,9 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
(true, Target::Sequence(s)) => Target::SequencePlan(s),
(_, t) => t,
};
- let key = FrameKey { target, frame, size: size_key, revision: rev };
+ // Draft decoding (opt-in): only while playing at 1/2 resolution or lower.
+ let draft = crate::frames::draft_playback(playing, scale, app.session.prefs.playback.draft_decode);
+ let key = FrameKey { target, frame, size: size_key, revision: rev, draft };
let project = app.session.project.clone();
if playing {
let preroll = app.playback.preroll.is_some();
@@ -190,7 +192,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
if let Some(ra) = ref_area {
// the reference frame (CPU path)
let rf = rate.frame_at(Tick(mv.compare_ref.unwrap_or(time.0)));
- let rkey = FrameKey { target: cpu_target, frame: rf, size: size_key, revision: rev };
+ let rkey = FrameKey { target: cpu_target, frame: rf, size: size_key, revision: rev, draft: false };
app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);
let rpic = fit(ra, frame_size.0 as f32, frame_size.1 as f32);
ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);
diff --git a/crates/ui-egui/src/panels/multicam.rs b/crates/ui-egui/src/panels/multicam.rs
index 51a0c9336..e2f7b6529 100644
--- a/crates/ui-egui/src/panels/multicam.rs
+++ b/crates/ui-egui/src/panels/multicam.rs
@@ -285,7 +285,7 @@ pub fn grid(app: &mut FilmcraftApp, ui: &mut egui::Ui, area: Rect) {
let scale = crate::panels::monitor::quantize_scale(app.ui.program.res.scale().min((cell_px / sw).max(1.0 / 32.0)));
let mt = Tick(info["sourceTime"].as_i64().unwrap_or(0));
let frame = rate.frame_at(mt);
- let key = FrameKey { target: Target::MulticamGrid(src), frame, size: (scale * 1000.0) as u32, revision: grid_revision(app, src) };
+ let key = FrameKey { target: Target::MulticamGrid(src), frame, size: (scale * 1000.0) as u32, revision: grid_revision(app, src), draft: false };
let project = app.session.project.clone();
if app.playback.playing {
app.frames.schedule_playback(key, rate, scale, &project, app.playback.speed, app.playback.preroll.is_some());
diff --git a/crates/ui-egui/src/panels/reference.rs b/crates/ui-egui/src/panels/reference.rs
index 21f46543e..e2e2404c6 100644
--- a/crates/ui-egui/src/panels/reference.rs
+++ b/crates/ui-egui/src/panels/reference.rs
@@ -48,7 +48,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui.painter().rect_filled(pic, 0.0, t.monitor_bg);
let ppp = ctx.pixels_per_point();
let scale = crate::panels::monitor::quantize_scale((pic.width() * ppp / w).clamp(1.0 / 32.0, 1.0));
- let key = FrameKey { target: Target::Sequence(seq_id), frame, size: (scale * 1000.0) as u32, revision: app.session.revision };
+ let key = FrameKey { target: Target::Sequence(seq_id), frame, size: (scale * 1000.0) as u32, revision: app.session.revision, draft: false };
let project = app.session.project.clone();
app.frames.request(key, rate.tick_of(frame), scale, &project, 3);
let tex = match app.frames.get(&key) {
diff --git a/crates/ui-egui/src/panels/scopes.rs b/crates/ui-egui/src/panels/scopes.rs
index bbb0e8934..c5a81519e 100644
--- a/crates/ui-egui/src/panels/scopes.rs
+++ b/crates/ui-egui/src/panels/scopes.rs
@@ -68,7 +68,7 @@ pub fn frame_signal(app: &mut FilmcraftApp, ctx: &egui::Context, slot: &str, fra
let fresh = if pq {
filmcraft_engine::scopes::scope_signal(&app.session, rate.tick_of(frame), 0.125, true)
} else {
- let fkey = FrameKey { target: Target::Sequence(seq_id), frame, size: 250, revision: rev };
+ let fkey = FrameKey { target: Target::Sequence(seq_id), frame, size: 250, revision: rev, draft: false };
let project = app.session.project.clone();
app.frames.request(fkey, rate.tick_of(frame), 0.25, &project, prio);
app.frames.get(&fkey).map(|img| Signal::from_rgba8(img.w, img.h, &img.px))
diff --git a/crates/ui-egui/src/panels/trim_monitor.rs b/crates/ui-egui/src/panels/trim_monitor.rs
index d813a2a5e..4347bf6ff 100644
--- a/crates/ui-egui/src/panels/trim_monitor.rs
+++ b/crates/ui-egui/src/panels/trim_monitor.rs
@@ -126,7 +126,7 @@ fn picture(app: &mut FilmcraftApp, ui: &mut egui::Ui, area: Rect, side: &Value,
let scale = scale.min(app.ui.program.res.scale());
let size_key = (scale * 1000.0) as u32;
let rev = app.item_revision(item);
- let key = FrameKey { target: Target::Item(item), frame, size: size_key, revision: rev };
+ let key = FrameKey { target: Target::Item(item), frame, size: size_key, revision: rev, draft: false };
let project = app.session.project.clone();
app.frames.request(key, rate.tick_of(frame), scale, &project, 0);
let ctx = ui.ctx().clone();
diff --git a/crates/ui-egui/src/perf.rs b/crates/ui-egui/src/perf.rs
index 59e0658c9..6164faa04 100644
--- a/crates/ui-egui/src/perf.rs
+++ b/crates/ui-egui/src/perf.rs
@@ -18,6 +18,7 @@ pub fn stats(app: &FilmcraftApp) -> Value {
"dropped": dropped,
"dropRate": if shown + dropped == 0 { 0.0 } else { dropped as f64 / (shown + dropped) as f64 },
"resolution": app.ui.program.res.label(),
+ "draftDecode": app.session.prefs.playback.draft_decode,
});
let mut frames = app.frames.stats().to_json();
frames["workers"] = json!(app.frames.workers());