Skip to content

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

M4.10: AV1 fixed-width MC passes, recycled planes, lean mode info, draft mode; media-stack draft test

Brandon Thomas7ce07667440b
diff --git a/crates/av1/examples/av1dec.rs b/crates/av1/examples/av1dec.rs
index b8c9047bb..025c7ce82 100644
--- a/crates/av1/examples/av1dec.rs
+++ b/crates/av1/examples/av1dec.rs
@@ -18,6 +18,8 @@ fn main() {
let t0 = std::time::Instant::now();
let mut n = 0;
let mut dec = if threads > 0 { filmcraft_av1::Decoder::with_threads(threads) } else { filmcraft_av1::Decoder::new() };
+ // AV1_DRAFT=1: draft mode (non-reference frames skip the in-loop filters).
+ dec.set_draft(std::env::var_os("AV1_DRAFT").is_some());
let mut write = |pics: Vec<filmcraft_av1::Picture>| {
for pic in pics {
n += 1;
diff --git a/crates/av1/src/decoder.rs b/crates/av1/src/decoder.rs
index c4dcfb3f3..2d97ba330 100644
--- a/crates/av1/src/decoder.rs
+++ b/crates/av1/src/decoder.rs
@@ -95,6 +95,8 @@ struct FrameJob {
picture: Option<Arc<Slot<Arc<Picture>>>>,
pts: i64,
apply_film_grain: bool,
+ /// Draft mode: the frame refreshes no reference slot, so its in-loop filters are skipped.
+ draft: bool,
}
/// A shown picture in output order.
@@ -193,6 +195,7 @@ pub struct Decoder {
seen_frame_header: bool,
/// Apply film grain synthesis to output frames (default true).
pub apply_film_grain: bool,
+ draft: bool,
stats: Arc<Mutex<DecodeStats>>,
threads: usize,
pool: Pool,
@@ -255,6 +258,7 @@ impl Decoder {
pending: None,
seen_frame_header: false,
apply_film_grain: true,
+ draft: false,
stats,
threads,
pool,
@@ -268,6 +272,14 @@ impl Decoder {
}
/// Frame / tile counts and per-stage busy time of the frames finished so far.
+ /// Draft mode for reduced-resolution playback (off by default): shown frames that refresh
+ /// no reference slot (nothing can predict from them, read their motion vectors or CDFs)
+ /// skip deblocking, CDEF and loop restoration and come out flagged [`Picture::draft`];
+ /// every other picture is unchanged.
+ pub fn set_draft(&mut self, on: bool) {
+ self.draft = on;
+ }
+
pub fn stats(&self) -> DecodeStats {
self.stats.lock().map(|s| *s).unwrap_or_default()
}
@@ -503,6 +515,7 @@ impl Decoder {
return Err(Error::Invalid("primary reference frame missing"));
}
let picture = fh.show_frame.then(Slot::new);
+ let draft = self.draft && fh.show_frame && fh.refresh_frame_flags == 0;
self.pending = Some(Box::new(FrameJob {
seq,
fh,
@@ -513,6 +526,7 @@ impl Decoder {
picture,
pts: self.pts,
apply_film_grain: self.apply_film_grain,
+ draft,
}));
Ok(None)
}
@@ -692,7 +706,8 @@ fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result<
{
cdfs = s;
}
- crate::postfilter::apply(&mut fs, stats, pool);
+ crate::postfilter::apply(&mut fs, stats, pool, job.draft);
+ stats.draft_frames += job.draft as u64;
let t = Timer::start();
stats.frames += 1;
if fh.seg.enabled && !fh.seg.update_map {
@@ -714,8 +729,11 @@ fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result<
saved_ref_frames: mf_refs,
saved_mvs: mf_mvs,
});
- let pic =
- fh.show_frame.then(|| output_picture(seq, &rf, fh.upscaled_width as usize, fh.frame_height as usize, &fh.film_grain, job.apply_film_grain, job.pts));
+ let pic = fh.show_frame.then(|| {
+ let mut p = output_picture(seq, &rf, fh.upscaled_width as usize, fh.frame_height as usize, &fh.film_grain, job.apply_film_grain, job.pts);
+ p.draft = job.draft;
+ p
+ });
stats.add(Stage::Output, t.secs());
Ok((rf, pic))
}
@@ -800,6 +818,7 @@ fn output_picture(seq: &SequenceHeader, rf: &RefFrame, w: usize, h: usize, grain
matrix_coefficients: rf.color.2,
full_range: rf.color.3,
pts,
+ draft: false,
};
if apply_film_grain && seq.film_grain_params_present && grain.apply_grain {
crate::grain::apply(&mut pic, grain, seq);
diff --git a/crates/av1/src/frame.rs b/crates/av1/src/frame.rs
index f6617105a..3cf4b9f0b 100644
--- a/crates/av1/src/frame.rs
+++ b/crates/av1/src/frame.rs
@@ -4,8 +4,32 @@
//! or [`MiInfo`] may hold a region of the frame (origin `ox`, `oy`), addressed with frame
//! coordinates throughout.
+/// Recycled plane allocations: every frame allocates (and every evicted reference frees)
+/// megabytes of planes, and fresh large allocations cost page faults and kernel calls. Buffers
+/// are zeroed again on reuse, so contents never leak between frames.
+static PLANE_POOL: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
+const POOL_MIN_LEN: usize = 1 << 16;
+/// Samples kept at most (96 M samples = 192 MB, a few 4K frames).
+const POOL_MAX_SAMPLES: usize = 96 << 20;
+
+/// A zeroed buffer of `len` samples (recycled memory for large ones).
+fn zeroed(len: usize) -> Vec<u16> {
+ if len >= POOL_MIN_LEN {
+ let found = {
+ let mut pool = PLANE_POOL.lock().unwrap_or_else(|e| e.into_inner());
+ pool.iter().position(|v| v.capacity() >= len && v.capacity() <= 2 * len).map(|i| pool.swap_remove(i))
+ };
+ if let Some(mut v) = found {
+ v.clear();
+ v.resize(len, 0);
+ return v;
+ }
+ }
+ vec![0; len]
+}
+
/// One plane of samples (u16 at every bit depth), or a rectangular region of one.
-#[derive(Clone, Default)]
+#[derive(Default)]
pub struct Plane {
pub data: Vec<u16>,
pub stride: usize,
@@ -16,13 +40,34 @@ pub struct Plane {
pub oy: usize,
}
+impl Clone for Plane {
+ fn clone(&self) -> Plane {
+ let mut data = zeroed(self.data.len());
+ data.copy_from_slice(&self.data);
+ Plane { data, stride: self.stride, rows: self.rows, ox: self.ox, oy: self.oy }
+ }
+}
+
+impl Drop for Plane {
+ fn drop(&mut self) {
+ if self.data.capacity() >= POOL_MIN_LEN {
+ let v = std::mem::take(&mut self.data);
+ let mut pool = PLANE_POOL.lock().unwrap_or_else(|e| e.into_inner());
+ let kept: usize = pool.iter().map(|b| b.capacity()).sum();
+ if kept + v.capacity() <= POOL_MAX_SAMPLES {
+ pool.push(v);
+ }
+ }
+ }
+}
+
impl Plane {
pub fn new(width: usize, height: usize) -> Plane {
- Plane { data: vec![0; width * height], stride: width, rows: height, ox: 0, oy: 0 }
+ Plane { data: zeroed(width * height), stride: width, rows: height, ox: 0, oy: 0 }
}
/// A `width` x `height` region with its top-left sample at frame position (ox, oy).
pub fn region(ox: usize, oy: usize, width: usize, height: usize) -> Plane {
- Plane { data: vec![0; width * height], stride: width, rows: height, ox, oy }
+ Plane { data: zeroed(width * height), stride: width, rows: height, ox, oy }
}
#[inline(always)]
pub fn at(&self, x: usize, y: usize) -> u16 {
@@ -173,13 +218,16 @@ pub struct MiInfo {
}
impl MiInfo {
- pub fn new(cols: usize, rows: usize) -> MiInfo {
- MiInfo::region(cols, rows, 0, 0, cols, rows)
+ /// `palette`: whether palette mode can occur (allow_screen_content_tools); without it the
+ /// palette arrays (40 bytes per unit) stay empty.
+ pub fn new(cols: usize, rows: usize, palette: bool) -> MiInfo {
+ MiInfo::region(cols, rows, 0, 0, cols, rows, palette)
}
/// Storage for the w x h mode info units at (ox, oy) of a cols x rows frame.
- pub fn region(cols: usize, rows: usize, ox: usize, oy: usize, w: usize, h: usize) -> MiInfo {
+ pub fn region(cols: usize, rows: usize, ox: usize, oy: usize, w: usize, h: usize, palette: bool) -> MiInfo {
let n = w * h;
+ let np = if palette { n } else { 0 };
MiInfo {
cols,
rows,
@@ -198,8 +246,8 @@ impl MiInfo {
inter_tx_size: vec![0; n],
mi_size: vec![0; n],
segment_id: vec![0; n],
- palette_size: [vec![0; n], vec![0; n]],
- palette_colors: [vec![[0; 8]; n], vec![[0; 8]; n]],
+ palette_size: [vec![0; np], vec![0; np]],
+ palette_colors: [vec![[0; 8]; np], vec![[0; 8]; np]],
delta_lf: vec![[0; 4]; n],
comp_group_idx: vec![0; n],
compound_idx: vec![0; n],
@@ -228,7 +276,7 @@ impl MiInfo {
)*};
}
copy!(y_mode uv_mode ref_frame mv is_inter skip_mode skip tx_size inter_tx_size mi_size segment_id delta_lf comp_group_idx compound_idx interp_filter motion_mode tx_type written);
- for k in 0..2 {
+ for k in (0..2).filter(|&k| !self.palette_size[k].is_empty()) {
for y in 0..h {
let d = dst.idx(self.oy + y, self.ox);
dst.palette_size[k][d..d + w].copy_from_slice(&self.palette_size[k][y * w..(y + 1) * w]);
diff --git a/crates/av1/src/inter.rs b/crates/av1/src/inter.rs
index 87fd80c74..e1869f508 100644
--- a/crates/av1/src/inter.rs
+++ b/crates/av1/src/inter.rs
@@ -665,6 +665,41 @@ impl TileDecoder<'_, '_> {
const IDENTITY_TAPS: [i16; 8] = [0, 0, 0, 128, 0, 0, 0, 0];
+/// Horizontal pass of one row for a block `W` wide: taps outer, columns inner, fixed width so
+/// the row stays in registers.
+#[inline(always)]
+fn hpass<const W: usize>(src: &[u16], hf: &[i16; 8], out: &mut [i32], half: i32, sh: u32) {
+ let mut acc = [half; W];
+ for t in 0..8 {
+ let f = hf[t] as i32;
+ let p: &[u16; W] = src[t..t + W].try_into().expect("row");
+ for j in 0..W {
+ acc[j] += f * p[j] as i32;
+ }
+ }
+ let o: &mut [i32; W] = (&mut out[..W]).try_into().expect("row");
+ for j in 0..W {
+ o[j] = acc[j] >> sh;
+ }
+}
+
+/// Vertical pass of one output row from 8 intermediate rows (`rows`, stride `W`).
+#[inline(always)]
+fn vpass<const W: usize>(rows: &[i32], vf: &[i16; 8], out: &mut [i32], half: i32, sh: u32) {
+ let mut acc = [half; W];
+ for t in 0..8 {
+ let f = vf[t] as i32;
+ let p: &[i32; W] = rows[t * W..t * W + W].try_into().expect("row");
+ for j in 0..W {
+ acc[j] += f * p[j];
+ }
+ }
+ let o: &mut [i32; W] = (&mut out[..W]).try_into().expect("row");
+ for j in 0..W {
+ o[j] = acc[j] >> sh;
+ }
+}
+
/// Block inter prediction without reference scaling: every column / row uses the same filter
/// phase, so the filters run over whole rows (bit-identical to the per-sample process).
#[allow(clippy::too_many_arguments)]
@@ -711,17 +746,27 @@ fn mc_unscaled(
*o = (v as i32) << (7 - r0);
}
} else {
- let acc = &mut acc[..w];
- acc.fill(0);
- for t in 0..8 {
- let f = hf[t] as i32;
- for (a, &v) in acc.iter_mut().zip(&src[t..t + w]) {
- *a += f * v as i32;
+ match w {
+ 2 => hpass::<2>(src, hf, out, half0, r0),
+ 4 => hpass::<4>(src, hf, out, half0, r0),
+ 8 => hpass::<8>(src, hf, out, half0, r0),
+ 16 => hpass::<16>(src, hf, out, half0, r0),
+ 32 => hpass::<32>(src, hf, out, half0, r0),
+ 64 => hpass::<64>(src, hf, out, half0, r0),
+ _ => {
+ let acc = &mut acc[..w];
+ acc.fill(0);
+ for t in 0..8 {
+ let f = hf[t] as i32;
+ for (a, &v) in acc.iter_mut().zip(&src[t..t + w]) {
+ *a += f * v as i32;
+ }
+ }
+ for (o, &a) in out.iter_mut().zip(acc.iter()) {
+ *o = (a + half0) >> r0;
+ }
}
}
- for (o, &a) in out.iter_mut().zip(acc.iter()) {
- *o = (a + half0) >> r0;
- }
}
}
for r in 0..h {
@@ -731,17 +776,28 @@ fn mc_unscaled(
*o = (128 * v + half1) >> r1;
}
} else {
- let acc = &mut acc[..w];
- acc.fill(0);
- for t in 0..8 {
- let f = vf[t] as i32;
- for (a, &v) in acc.iter_mut().zip(&tmp[(r + t) * w..(r + t + 1) * w]) {
- *a += f * v;
+ let rows = &tmp[r * w..(r + 8) * w];
+ match w {
+ 2 => vpass::<2>(rows, vf, out, half1, r1),
+ 4 => vpass::<4>(rows, vf, out, half1, r1),
+ 8 => vpass::<8>(rows, vf, out, half1, r1),
+ 16 => vpass::<16>(rows, vf, out, half1, r1),
+ 32 => vpass::<32>(rows, vf, out, half1, r1),
+ 64 => vpass::<64>(rows, vf, out, half1, r1),
+ _ => {
+ let acc = &mut acc[..w];
+ acc.fill(0);
+ for t in 0..8 {
+ let f = vf[t] as i32;
+ for (a, &v) in acc.iter_mut().zip(&tmp[(r + t) * w..(r + t + 1) * w]) {
+ *a += f * v;
+ }
+ }
+ for (o, &a) in out.iter_mut().zip(acc.iter()) {
+ *o = (a + half1) >> r1;
+ }
}
}
- for (o, &a) in out.iter_mut().zip(acc.iter()) {
- *o = (a + half1) >> r1;
- }
}
}
}
diff --git a/crates/av1/src/lib.rs b/crates/av1/src/lib.rs
index 43a002cb6..fd1031ee6 100644
--- a/crates/av1/src/lib.rs
+++ b/crates/av1/src/lib.rs
@@ -62,6 +62,9 @@ pub struct Picture {
pub full_range: bool,
/// Timestamp of the temporal unit that showed the picture ([`Decoder::decode_pts`]).
pub pts: i64,
+ /// Decoded in draft mode without deblocking / CDEF / loop restoration
+ /// ([`Decoder::set_draft`]): approximate, for reduced-resolution playback only.
+ pub draft: bool,
}
impl Picture {
diff --git a/crates/av1/src/postfilter.rs b/crates/av1/src/postfilter.rs
index fd0ae8be1..ea157de54 100644
--- a/crates/av1/src/postfilter.rs
+++ b/crates/av1/src/postfilter.rs
@@ -6,14 +6,15 @@ use crate::state::FrameState;
use crate::stats::{DecodeStats, Stage, Timer};
/// The post-filters run on the frame worker; `_pool` is for row-parallel filtering (not yet used).
-pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate::par::Pool) {
+/// `draft`: only super-resolution (which sets the output size) runs.
+pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate::par::Pool, draft: bool) {
let mut t = Timer::start();
let lvl = fs.fh.lf.level;
- if lvl[0] != 0 || lvl[1] != 0 {
+ if (lvl[0] != 0 || lvl[1] != 0) && !draft {
loop_filter(fs);
}
stats.add(Stage::LoopFilter, t.lap());
- let cdef = crate::cdef::apply(fs);
+ let cdef = if draft { None } else { crate::cdef::apply(fs) };
stats.add(Stage::Cdef, t.lap());
let (up_cur, up_cdef) = if fs.fh.use_superres {
let c = crate::restoration::upscale(fs, &fs.cur);
@@ -23,7 +24,11 @@ pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate:
(std::mem::take(&mut fs.cur), cdef)
};
stats.add(Stage::Superres, t.lap());
- fs.cur = if fs.fh.lr.uses_lr { crate::restoration::loop_restoration(fs, &up_cur, up_cdef.as_ref().unwrap_or(&up_cur)) } else { up_cdef.unwrap_or(up_cur) };
+ fs.cur = if fs.fh.lr.uses_lr && !draft {
+ crate::restoration::loop_restoration(fs, &up_cur, up_cdef.as_ref().unwrap_or(&up_cur))
+ } else {
+ up_cdef.unwrap_or(up_cur)
+ };
stats.add(Stage::Restoration, t.lap());
}
diff --git a/crates/av1/src/state.rs b/crates/av1/src/state.rs
index 0073f3e99..df600c6d2 100644
--- a/crates/av1/src/state.rs
+++ b/crates/av1/src/state.rs
@@ -215,7 +215,7 @@ impl FrameState {
prev_segment_ids: vec![0; mi_cols * mi_rows],
},
cur,
- mi: MiInfo::new(mi_cols, mi_rows),
+ mi: MiInfo::new(mi_cols, mi_rows, fh.allow_screen_content_tools),
cdef: vec![-1; cdef_cols * cdef_rows],
lf_tx_size: std::array::from_fn(|_| Grid8::new(0, 0, mi_cols + 32, mi_rows + 32)),
lr,
@@ -260,7 +260,7 @@ impl FrameState {
let x1 = if c1 >= mi_cols { usize::MAX } else { c1 * 4 };
let y1 = if r1 >= mi_rows { usize::MAX } else { r1 * 4 };
let cur = self.cur.region_like(c0 * 4, r0 * 4, x1, y1);
- let mi = MiInfo::region(mi_cols, mi_rows, c0, r0, c1 - c0, r1 - r0);
+ let mi = MiInfo::region(mi_cols, mi_rows, c0, r0, c1 - c0, r1 - r0, !self.mi.palette_size[0].is_empty());
let lf = std::array::from_fn(|p| {
let (sx, sy) = if p == 0 { (0, 0) } else { (self.ssx, self.ssy) };
let full = &self.lf_tx_size[p];
diff --git a/crates/av1/src/stats.rs b/crates/av1/src/stats.rs
index 7d89beac8..e3c5e0f45 100644
--- a/crates/av1/src/stats.rs
+++ b/crates/av1/src/stats.rs
@@ -43,6 +43,8 @@ impl Stage {
pub struct DecodeStats {
/// Frames decoded (excluding show_existing_frame repeats).
pub frames: u64,
+ /// Frames decoded in draft mode without in-loop filters.
+ pub draft_frames: u64,
/// Tiles decoded.
pub tiles: u64,
/// Busy seconds per [`Stage`] (index with `stage as usize`).
@@ -60,6 +62,7 @@ impl DecodeStats {
pub(crate) fn merge(&mut self, o: &DecodeStats) {
self.frames += o.frames;
+ self.draft_frames += o.draft_frames;
self.tiles += o.tiles;
for (a, b) in self.stage_secs.iter_mut().zip(o.stage_secs.iter()) {
*a += b;
diff --git a/crates/av1/src/symbol.rs b/crates/av1/src/symbol.rs
index d8b547dff..a85f7f833 100644
--- a/crates/av1/src/symbol.rs
+++ b/crates/av1/src/symbol.rs
@@ -127,17 +127,12 @@ impl<'a> SymbolDecoder<'a> {
pub(crate) fn update_cdf(cdf: &mut [u16], n: usize, symbol: usize) {
let count = cdf[n];
let rate = 3 + (count > 15) as u32 + (count > 31) as u32 + (31 - (n as u32).leading_zeros()).min(2);
- let mut tmp = 0u32;
- for i in 0..n - 1 {
- if i == symbol {
- tmp = 1 << 15;
- }
- let c = cdf[i] as u32;
- if tmp < c {
- cdf[i] = (c - ((c - tmp) >> rate)) as u16;
- } else {
- cdf[i] = (c + ((tmp - c) >> rate)) as u16;
- }
+ // Entries below `symbol` move towards 0, the others towards 1 << 15 (the specification's
+ // comparison with tmp, resolved per entry: c >= 0 and c <= 1 << 15), without branching on
+ // the decoded symbol.
+ for (i, e) in cdf[..n - 1].iter_mut().enumerate() {
+ let c = *e as u32;
+ *e = if i < symbol { c - (c >> rate) } else { c + (((1 << 15) - c) >> rate) } as u16;
}
cdf[n] += (count < 32) as u16;
}
diff --git a/crates/av1/src/tile.rs b/crates/av1/src/tile.rs
index 13278b019..9d5344652 100644
--- a/crates/av1/src/tile.rs
+++ b/crates/av1/src/tile.rs
@@ -474,10 +474,12 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
mi.tx_size[span.clone()].fill(b.tx_size as u8);
mi.mi_size[span.clone()].fill(b.mi_size as u8);
mi.segment_id[span.clone()].fill(b.segment_id as u8);
- mi.palette_size[0][span.clone()].fill(b.palette_size_y as u8);
- mi.palette_size[1][span.clone()].fill(b.palette_size_uv as u8);
- mi.palette_colors[0][span.clone()].fill(b.palette_colors_y);
- mi.palette_colors[1][span.clone()].fill(b.palette_colors_u);
+ if !mi.palette_size[0].is_empty() {
+ mi.palette_size[0][span.clone()].fill(b.palette_size_y as u8);
+ mi.palette_size[1][span.clone()].fill(b.palette_size_uv as u8);
+ mi.palette_colors[0][span.clone()].fill(b.palette_colors_y);
+ mi.palette_colors[1][span.clone()].fill(b.palette_colors_u);
+ }
mi.delta_lf[span.clone()].fill(dlf);
mi.motion_mode[span].fill(b.motion_mode);
}
diff --git a/crates/av1/tests/common/mod.rs b/crates/av1/tests/common/mod.rs
index daa9105a0..b470e9b37 100644
--- a/crates/av1/tests/common/mod.rs
+++ b/crates/av1/tests/common/mod.rs
@@ -89,7 +89,13 @@ pub fn decode_all(path: &Path) -> Result<Vec<Picture>, String> {
/// Decode every frame of an IVF file with a decoder using `threads` threads.
pub fn decode_all_threads(path: &Path, threads: usize) -> Result<Vec<Picture>, String> {
+ decode_all_opts(path, threads, false)
+}
+
+/// [`decode_all_threads`] with draft mode on or off.
+pub fn decode_all_opts(path: &Path, threads: usize, draft: bool) -> Result<Vec<Picture>, String> {
let mut dec = Decoder::with_threads(threads);
+ dec.set_draft(draft);
let mut pics = Vec::new();
for (i, f) in ivf_frames(path).iter().enumerate() {
let p = dec.decode_pts(f, i as i64).map_err(|e| format!("frame {i}: {e}"))?;
@@ -174,6 +180,7 @@ pub fn check_file(ff: &Path, name: &str, path: &Path) {
assert!(a == b, "{name}: frame {i} differs with {threads} threads");
}
assert!(!pics.is_empty(), "{name}: no frames");
+ assert!(pics.iter().all(|p| !p.draft), "{name}: picture flagged draft without draft mode");
let raw = reference(ff, path, pix_fmt_for(&pics[0]));
let per = picture_samples(&pics[0]);
assert_eq!(raw.len(), per * pics.len(), "{name}: frame count/size ({} pictures)", pics.len());
diff --git a/crates/av1/tests/oracle_inter.rs b/crates/av1/tests/oracle_inter.rs
index 80e78e45b..fcd43b087 100644
--- a/crates/av1/tests/oracle_inter.rs
+++ b/crates/av1/tests/oracle_inter.rs
@@ -40,6 +40,34 @@ fn inter_gops() {
}
}
+/// Draft mode: frames that refresh no reference slot skip the in-loop filters and are flagged;
+/// every other picture stays bit-exact, with 1 and several threads.
+#[test]
+fn draft_mode_changes_only_flagged_non_reference_frames() {
+ let Some(ff) = ffmpeg() else { return };
+ let s = &specs()[0];
+ let path = make(&ff, s);
+ let first = decode_all_threads(&path, 1).expect("decode");
+ let raw = reference(&ff, &path, pix_fmt_for(&first[0]));
+ let per = picture_samples(&first[0]);
+ for threads in [1, 4] {
+ let pics = decode_all_opts(&path, threads, true).expect("decode");
+ assert_eq!(pics.len(), first.len(), "threads {threads}");
+ let (mut draft, mut changed) = (0, 0);
+ for (i, p) in pics.iter().enumerate() {
+ let (_, count) = compare(p, &raw[i * per..(i + 1) * per]);
+ if p.draft {
+ draft += 1;
+ changed += (count > 0) as usize;
+ } else {
+ assert_eq!(count, 0, "threads {threads}: unflagged frame {i} differs");
+ }
+ }
+ assert!(draft > 0, "threads {threads}: no non-reference frames");
+ assert!(changed > 0, "threads {threads}: draft frames identical to the filtered ones");
+ }
+}
+
/// Several tiles (decoded in parallel into private buffers, then merged).
fn specs_tiles() -> Vec<Spec> {
let p = |preset: &'static str, params: &'static str| -> Vec<&'static str> { vec!["-preset", preset, "-crf", "32", "-svtav1-params", params] };
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index a9cf13df4..19fdf2968 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -496,6 +496,7 @@ impl Av1Decoder {
fn convert(p: filmcraft_av1::Picture, pts: i64) -> DecodedFrame {
use std::sync::Arc;
+ let draft = p.draft;
let w = p.width as usize;
let h = p.height as usize;
let mut color = filmcraft_color::ColorInfo::REC709;
@@ -535,7 +536,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 }, draft: false }
+ DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par: (1, 1), pts: filmcraft_time::Tick::ZERO }, draft }
}
}
@@ -574,6 +575,9 @@ impl VideoDecoder for Av1Decoder {
fn name(&self) -> &str {
"FilmCraft AV1"
}
+ fn set_draft(&mut self, on: bool) {
+ self.dec.set_draft(on);
+ }
fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
Some(filmcraft_av1::is_key_frame_unit(sample))
}
diff --git a/crates/codecs/tests/draft_decoders.rs b/crates/codecs/tests/draft_decoders.rs
new file mode 100644
index 000000000..bec6476f9
--- /dev/null
+++ b/crates/codecs/tests/draft_decoders.rs
@@ -0,0 +1,119 @@
+//! Draft decoding of VP9, HEVC and AV1 through the media stack (as `h264_draft.rs` for H.264):
+//! off by default, approximate frames only 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;
+
+/// Play `name` without and with draft decoding, then "export" it: every non-draft request must
+/// be bit-exact with ffmpeg, and draft playback must have produced some approximate frames.
+fn check(name: &str, args: &[&str], w: usize, h: usize) {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let Some(file) = fixture(&ff, name, args) else { return };
+ let raw = ffmpeg_frames(&ff, &file, "yuv420p");
+ let fsize = w * h * 3 / 2;
+ let n = raw.len() / fsize;
+ assert!(n >= 16, "{name}: {n} frames");
+ let reference = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, w / 2, h / 2, 1);
+
+ // Default: nothing is a draft, every frame exact.
+ let src = filmcraft_codecs::open_bytes(name, bytes(&file)).expect("open");
+ let rate = src.info().frame_rate();
+ 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, "{name}: frame {i} without draft mode");
+ }
+ assert_eq!(filmcraft_codecs::gop_stats().draft, g0.draft, "{name}: draft decoding is off by default");
+
+ // Draft playback at 1/2 resolution on a fresh source: non-reference frames are drafts.
+ let src = filmcraft_codecs::open_bytes(name, 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, "{name}: {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, "{name}: export frame {i} after draft playback");
+ }
+}
+
+/// One test (the GOP cache statistics are process-wide, so the codecs run one after another).
+#[test]
+fn draft_playback_never_reaches_exports() {
+ vp9();
+ hevc();
+ av1();
+}
+
+fn vp9() {
+ // Two temporal layers: every other frame refreshes no reference slot. (25 fps: WebM stores
+ // millisecond timestamps.)
+ check(
+ "draft_vp9.webm",
+ &[
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=s=320x240:r=25:d=1,noise=alls=10:allf=t",
+ "-c:v",
+ "libvpx-vp9",
+ "-deadline",
+ "realtime",
+ "-speed",
+ "8",
+ "-b:v",
+ "600k",
+ "-ts-parameters",
+ "ts_number_layers=2:ts_target_bitrate=300,600:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1:ts_layering_mode=2",
+ "-pix_fmt",
+ "yuv420p",
+ ],
+ 320,
+ 240,
+ );
+}
+
+fn hevc() {
+ // B-pyramid: non-reference B pictures (sub-layer non-reference NAL types).
+ check(
+ "draft_hevc.mp4",
+ &[
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=s=320x240:r=25:d=1,noise=alls=10:allf=t",
+ "-c:v",
+ "libx265",
+ "-preset",
+ "fast",
+ "-x265-params",
+ "bframes=4:b-pyramid=1:keyint=24:log-level=error",
+ "-pix_fmt",
+ "yuv420p",
+ "-tag:v",
+ "hvc1",
+ ],
+ 320,
+ 240,
+ );
+}
+
+fn av1() {
+ // SVT-AV1 hierarchical GOP: the top layer refreshes no reference slot.
+ check(
+ "draft_av1.mp4",
+ &["-f", "lavfi", "-i", "testsrc2=s=320x240:r=25:d=1,noise=alls=10:allf=t", "-c:v", "libsvtav1", "-preset", "8", "-crf", "35", "-pix_fmt", "yuv420p"],
+ 320,
+ 240,
+ );
+}