FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#847: AV1 decode runs deblocking, CDEF and loop restoration in parallel row bands
vangel761e6f42eda2d8
diff --git a/crates/av1/README.md b/crates/av1/README.mdindex 5d4d5c50f..354484158 100644--- a/crates/av1/README.md+++ b/crates/av1/README.md@@ -70,12 +70,15 @@ with libdav1d: **bit-exact** on all 6 fixtures.wasm32, or without the default `threads` feature, everything runs on the calling thread). Headers are parsed in order; each frame isthen decoded by a frame worker once the reference frames it reads are finished, so independentframes (hierarchical GOP layers) decode concurrently; tiles of a frame decode in parallel into-private buffers that are merged afterwards. Results never depend on scheduling (the oracle tests-compare 1 thread, many threads and libdav1d). With frame threads, pictures may be returned by a+private buffers that are merged afterwards; the in-loop filters (deblocking, CDEF, loop+restoration) each run in parallel bands of 64 rows (`postfilter.rs` explains why the bands are+independent). Results never depend on scheduling (the oracle tests compare 1 thread, many threads+and libdav1d). With frame threads, pictures may be returned by alater `decode_pts` call or by `flush`; each carries the `pts` of the temporal unit that showed it.`tests/perf.rs` (ignored) prints single-threaded fps (thread CPU time), per-stage ms/frame-(`Decoder::stats()`) and all-core fps for 1080p fixtures. The hot loops (sub-pixel filters,+(`Decoder::stats()`) and all-core fps with its per-stage ms/frame for 1080p fixtures (key frames,+GOPs, tiles, low delay) and a single-tile 2160p GOP; `AV1_PERF_ONLY=a,b` picks fixtures. The hot loops (sub-pixel filters,CDEF, inverse transforms, deblocking, entropy decoding) are written for auto-vectorisation.Measured 2026-10-01 on a 14-core Apple Silicon Mac (release build, SVT-AV1 preset 8 1080pdiff --git a/crates/av1/src/cdef.rs b/crates/av1/src/cdef.rsindex 13efa75db..4038a0f02 100644--- a/crates/av1/src/cdef.rs+++ b/crates/av1/src/cdef.rs@@ -1,35 +1,45 @@//! CDEF (7.15).-use crate::frame::{FrameBuf, Plane};+use crate::frame::{FrameBuf, RowBand};+use crate::par::Pool;+use crate::postfilter::bands;use crate::spec_tables::*;use crate::state::FrameState;/// Run CDEF on `fs.cur`; returns the CdefFrame, or None when no block is filtered (CdefFrame-/// equals CurrFrame).-pub(crate) fn apply(fs: &FrameState) -> Option<FrameBuf> {+/// equals CurrFrame). Bands of 64 luma rows (whole 8x8 blocks) are filtered in parallel: every+/// block reads only CurrFrame and writes only its own samples.+pub(crate) fn apply(fs: &FrameState, pool: &Pool) -> Option<FrameBuf> {let fh = &fs.fh;if fh.coded_lossless || fh.allow_intrabc || !fs.seq.enable_cdef {return None;}let (mi_rows, mi_cols) = (fh.mi_rows as usize, fh.mi_cols as usize);let mut out = fs.cur.clone();- let mut any = false;- let mut r = 0;- while r < mi_rows {- let mut c = 0;- while c < mi_cols {- let idx = fs.cdef_idx(r & !15, c & !15);- if idx >= 0 && cdef_block(fs, &mut out, r, c, idx as usize) {- any = true;+ let ranges = bands(pool, mi_rows * 4);+ let mut planes = out.row_bands(&ranges);+ let any = pool.map_mut(&mut planes, |b, band| {+ let (start, end) = ranges[b];+ let mut any = false;+ let mut r = start / 4;+ while r < mi_rows.min(end / 4) {+ let mut c = 0;+ while c < mi_cols {+ let idx = fs.cdef_idx(r & !15, c & !15);+ if idx >= 0 && cdef_block(fs, band, r, c, idx as usize) {+ any = true;+ }+ c += 2;}- c += 2;+ r += 2;}- r += 2;- }- any.then_some(out)+ any+ });+ drop(planes);+ any.contains(&true).then_some(out)}-fn cdef_block(fs: &FrameState, out: &mut FrameBuf, r: usize, c: usize, idx: usize) -> bool {+fn cdef_block(fs: &FrameState, out: &mut [RowBand; 3], r: usize, c: usize, idx: usize) -> bool {let mi = &fs.mi;let sk = |rr: usize, cc: usize| -> bool { if rr < mi.rows && cc < mi.cols { mi.skip[mi.idx(rr, cc)] } else { true } };let skip = sk(r, c) && sk(r + 1, c) && sk(r, c + 1) && sk(r + 1, c + 1);@@ -125,7 +135,7 @@ fn constrain(diff: i32, threshold: i32, adj: u32) -> i32 {}#[allow(clippy::too_many_arguments)]-fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, r: usize, c: usize, pri: i32, sec: i32, damping: i32, dir: usize) {+fn filter(fs: &FrameState, out: &mut [RowBand; 3], plane: usize, r: usize, c: usize, pri: i32, sec: i32, damping: i32, dir: usize) {if pri == 0 && sec == 0 {// Every tap contributes 0 and the clamp to [min, max] keeps x: CdefFrame = CurrFrame.return;@@ -169,7 +179,7 @@ fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, r: usize, c: usize,let sec_taps = [CDEF_SEC_TAPS[pri_tap][0] as i32, CDEF_SEC_TAPS[pri_tap][1] as i32];let adj = |t: i32| if t == 0 { 0 } else { (damping - (31 - (t as u32).leading_zeros()) as i32).max(0) as u32 };let (pri_adj, sec_adj) = (adj(pri), adj(sec));- let dst = &mut out.planes[plane];+ let dst = &mut out[plane];if all_avail {// Every tap is available: whole rows at a time (constrain() with threshold 0 is 0).let mut taps = [(0isize, 0i32, 0i32, 0u32); 12];@@ -230,7 +240,12 @@ fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, r: usize, c: usize,/// CDEF of a block whose taps are all available, `W` samples per row. Samples (at most 12/// bits), differences and the weighted tap sum all fit in i16, which doubles the SIMD width.#[inline(always)]-fn filter_rows<const W: usize>(buf: &[i32; PAD_STRIDE * PAD_STRIDE], taps: &[(isize, i32, i32, u32); 12], dst: &mut Plane, (y0, x0, h): (usize, usize, usize)) {+fn filter_rows<const W: usize>(+ buf: &[i32; PAD_STRIDE * PAD_STRIDE],+ taps: &[(isize, i32, i32, u32); 12],+ dst: &mut RowBand,+ (y0, x0, h): (usize, usize, usize),+) {let mut b16 = [0i16; PAD_STRIDE * PAD_STRIDE];for (d, &s) in b16.iter_mut().zip(buf.iter()) {*d = s as i16;diff --git a/crates/av1/src/frame.rs b/crates/av1/src/frame.rsindex 3cf4b9f0b..a0e242345 100644--- a/crates/av1/src/frame.rs+++ b/crates/av1/src/frame.rs@@ -106,6 +106,48 @@ impl Plane {dst.row_from_mut(self.oy + y, self.ox)[..self.stride].copy_from_slice(s);}}++ /// Disjoint mutable bands of whole rows, for filtering in parallel: one per `[start, end)`+ /// range of rows (relative to `oy`; ascending and not overlapping, else the later band is+ /// cut to what is left). Ranges are clipped to the stored rows.+ pub fn row_bands(&mut self, ranges: &[(usize, usize)]) -> Vec<RowBand<'_>> {+ let (stride, oy) = (self.stride.max(1), self.oy);+ let mut out = Vec::with_capacity(ranges.len());+ let mut rest = self.data.as_mut_slice();+ // First row of `rest`.+ let mut y = 0usize;+ for &(start, end) in ranges {+ let skip = start.saturating_sub(y).saturating_mul(stride).min(rest.len());+ rest = std::mem::take(&mut rest).split_at_mut(skip).1;+ y = y.saturating_add(skip / stride);+ let len = end.saturating_sub(y).saturating_mul(stride).min(rest.len());+ let (band, tail) = std::mem::take(&mut rest).split_at_mut(len);+ out.push(RowBand { data: band, stride, y0: oy.saturating_add(y) });+ y = y.saturating_add(len / stride);+ rest = tail;+ }+ out+ }+}++/// Mutable whole rows [y0, y0 + data.len() / stride) of a plane, addressed with the plane's+/// coordinates (see [`Plane::row_bands`]).+pub struct RowBand<'a> {+ pub data: &'a mut [u16],+ pub stride: usize,+ pub y0: usize,+}++impl RowBand<'_> {+ #[inline(always)]+ pub fn set(&mut self, x: usize, y: usize, v: u16) {+ self.data[(y - self.y0) * self.stride + x] = v;+ }+ #[inline(always)]+ pub fn row_mut(&mut self, y: usize) -> &mut [u16] {+ let o = (y - self.y0) * self.stride;+ &mut self.data[o..o + self.stride]+ }}/// A frame's three planes, sized to the macroblock-aligned coded area plus margins.@@ -158,6 +200,16 @@ impl FrameBuf {}}+ /// [`Plane::row_bands`] of all three planes for ranges of luma rows (chroma rows scaled+ /// down): element `i` holds the bands of range `i`.+ pub fn row_bands(&mut self, luma: &[(usize, usize)]) -> Vec<[RowBand<'_>; 3]> {+ let ssy = self.subsampling_y;+ let chroma: Vec<(usize, usize)> = luma.iter().map(|&(s, e)| (s >> ssy, e >> ssy)).collect();+ let [p0, p1, p2] = &mut self.planes;+ let (b1, b2) = (p1.row_bands(&chroma), p2.row_bands(&chroma));+ p0.row_bands(luma).into_iter().zip(b1).zip(b2).map(|((y, u), v)| [y, u, v]).collect()+ }+pub fn plane_width(&self, plane: usize) -> usize {if plane == 0 { self.width } else { (self.width + self.subsampling_x) >> self.subsampling_x }}@@ -285,3 +337,40 @@ impl MiInfo {}}}++#[cfg(test)]+mod tests {+ use super::*;++ fn rows(b: &RowBand) -> (usize, usize) {+ (b.y0, b.data.len() / b.stride)+ }++ #[test]+ fn row_bands_split_whole_rows() {+ let mut p = Plane::new(8, 20);+ for (i, v) in p.data.iter_mut().enumerate() {+ *v = (i / 8) as u16;+ }+ let bands = p.row_bands(&[(0, 8), (8, 16), (16, usize::MAX)]);+ assert_eq!(bands.iter().map(rows).collect::<Vec<_>>(), [(0, 8), (8, 8), (16, 4)]);+ // Each band's row y holds the samples of plane row y.+ for mut b in bands {+ let y = b.y0 + 1;+ assert!(b.row_mut(y).iter().all(|&v| v as usize == y));+ }+ // Gaps between bands (the loop filter's even / odd turns).+ let bands = p.row_bands(&[(0, 4), (10, 14), (18, 30)]);+ assert_eq!(bands.iter().map(rows).collect::<Vec<_>>(), [(0, 4), (10, 4), (18, 2)]);+ }++ #[test]+ fn row_bands_never_overlap_or_panic() {+ let mut p = Plane::new(4, 10);+ // Overlapping, descending and out-of-range ranges are cut to what is left.+ let bands = p.row_bands(&[(2, 6), (4, 8), (1, 3), (9, 2), (50, 60), (usize::MAX, usize::MAX)]);+ assert_eq!(bands.iter().map(rows).collect::<Vec<_>>(), [(2, 4), (6, 2), (8, 0), (9, 0), (10, 0), (10, 0)]);+ let mut empty = Plane::default();+ assert!(empty.row_bands(&[(0, 64), (64, usize::MAX)]).iter().all(|b| b.data.is_empty()));+ }+}diff --git a/crates/av1/src/postfilter.rs b/crates/av1/src/postfilter.rsindex ea157de54..46bf83562 100644--- a/crates/av1/src/postfilter.rs+++ b/crates/av1/src/postfilter.rs@@ -1,20 +1,33 @@//! In-loop post filters run by decode_frame_wrapup: loop filter (7.14), CDEF (7.15),//! super-resolution upscaling (7.16) and loop restoration (7.17).+use crate::frame::RowBand;use crate::spec_tables::*;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).-/// `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) {+/// Luma rows per band of the row-parallel filters: whole 64x64 CDEF filter blocks, and no+/// transform block crosses a band edge.+const BAND_ROWS: usize = 64;++/// The [start, end) luma rows of the bands covering `rows`: [`BAND_ROWS`] each (the last one+/// runs to the end of the plane), or one band for everything when `pool` is sequential.+pub(crate) fn bands(pool: &crate::par::Pool, rows: usize) -> Vec<(usize, usize)> {+ let n = if pool.is_parallel() { rows.div_ceil(BAND_ROWS).max(1) } else { 1 };+ (0..n).map(|b| (b * BAND_ROWS, if b + 1 == n { usize::MAX } else { (b + 1) * BAND_ROWS })).collect()+}++/// The post-filters run on the frame worker, each in row bands on `pool` (the result does not+/// depend on how the bands are scheduled). `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) && !draft {- loop_filter(fs);+ loop_filter(fs, pool);}stats.add(Stage::LoopFilter, t.lap());- let cdef = if draft { None } else { crate::cdef::apply(fs) };+ let cdef = if draft { None } else { crate::cdef::apply(fs, pool) };stats.add(Stage::Cdef, t.lap());let (up_cur, up_cdef) = if fs.fh.use_superres {let c = crate::restoration::upscale(fs, &fs.cur);@@ -25,7 +38,7 @@ pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate:};stats.add(Stage::Superres, t.lap());fs.cur = if fs.fh.lr.uses_lr && !draft {- crate::restoration::loop_restoration(fs, &up_cur, up_cdef.as_ref().unwrap_or(&up_cur))+ crate::restoration::loop_restoration(fs, &up_cur, up_cdef.as_ref().unwrap_or(&up_cur), pool)} else {up_cdef.unwrap_or(up_cur)};@@ -35,28 +48,102 @@ pub(crate) fn apply(fs: &mut FrameState, stats: &mut DecodeStats, _pool: &crate:// ---------------------------------------------------------------------------------------------// Loop filter (7.14)-fn loop_filter(fs: &mut FrameState) {- let (mi_rows, mi_cols) = (fs.fh.mi_rows as usize, fs.fh.mi_cols as usize);- for plane in 0..fs.num_planes {- if plane == 0 || fs.fh.lf.level[1 + plane] != 0 {- for pass in 0..2 {- let row_step = if plane == 0 { 1 } else { 1 << fs.ssy };- let col_step = if plane == 0 { 1 } else { 1 << fs.ssx };- let mut row = 0;- while row < mi_rows {- let mut col = 0;- while col < mi_cols {- edge(fs, plane, pass, row, col);- col += col_step;- }- row += row_step;+/// Luma rows above a band that its horizontal edges read or write (p6 .. p0 of the widest+/// filter, rounded up to whole 4x4 rows); chroma: `LF_MARGIN >> subsampling_y`.+const LF_MARGIN: usize = 8;++/// The loop filter in row bands, all of a frame's in one parallel pass (each join costs a+/// worker wake-up, which is slow on a busy machine).+///+/// Vertical edges (pass 0) only touch the 4 rows of their own edge. A horizontal edge (pass 1)+/// reads and writes at most `filter_size / 2` samples on each side, never more than the+/// transform blocks on either side are high, so no two edges touch the same sample and+/// any order gives the spec's raster-order result. Transform blocks never cross a band edge, so+/// the only edges reaching outside a band are those on its top row, whose p side lies in the+/// band above. Each band therefore also filters the vertical edges of a copy of the+/// `LF_MARGIN` rows above it (the same work as the band above does on them), runs its top+/// horizontal edges against that copy, and afterwards the samples those edges changed are+/// written back; the band above never touches them.+fn loop_filter(fs: &mut FrameState, pool: &crate::par::Pool) {+ let luma = bands(pool, fs.fh.mi_rows as usize * 4);+ let planes: Vec<usize> = (0..fs.num_planes).filter(|&p| p == 0 || fs.fh.lf.level[1 + p] != 0).collect();+ let mut cur = std::mem::take(&mut fs.cur);+ let f: &FrameState = fs;+ // Unfiltered copies of the rows above each band but the first.+ let margins: Vec<[Vec<u16>; 3]> = luma+ .iter()+ .map(|&(start, _)| {+ std::array::from_fn(|p| {+ let sub_y = if p == 0 { 0 } else { f.ssy };+ let pl = &cur.planes[p];+ let (y0, y1) = ((start.saturating_sub(LF_MARGIN)) >> sub_y, start >> sub_y);+ let rows = pl.data.get(y0 * pl.stride..y1 * pl.stride);+ if start == 0 || !planes.contains(&p) { Vec::new() } else { rows.map(<[u16]>::to_vec).unwrap_or_default() }+ })+ })+ .collect();+ let mut bands: Vec<([RowBand; 3], [Vec<u16>; 3])> = cur.row_bands(&luma).into_iter().zip(margins).collect();+ let changed = pool.map_mut(&mut bands, |b, (band, margin)| {+ let mut changed: [Vec<(usize, u16)>; 3] = Default::default();+ for &p in &planes {+ changed[p] = filter_band(f, p, luma[b], &mut band[p], &mut margin[p]);+ }+ changed+ });+ drop(bands);+ for (&(start, _), ch) in luma.iter().zip(&changed) {+ for (p, list) in ch.iter().enumerate() {+ let sub_y = if p == 0 { 0 } else { f.ssy };+ let pl = &mut cur.planes[p];+ let first = (start.saturating_sub(LF_MARGIN) >> sub_y) * pl.stride;+ for &(i, v) in list {+ if let Some(d) = pl.data.get_mut(first + i) {+ *d = v;}}}}+ fs.cur = cur;+}++/// Both loop filter passes over the band of `plane` holding luma rows [start, end); `margin` is+/// an unfiltered copy of the rows above the band (empty for the first band). Returns the samples+/// of `margin` that the band's top horizontal edges changed, as (index, value).+fn filter_band(fs: &FrameState, plane: usize, (start, end): (usize, usize), band: &mut RowBand, margin: &mut [u16]) -> Vec<(usize, u16)> {+ let mi_rows = fs.fh.mi_rows as usize;+ let (r0, r1) = (start / 4, mi_rows.min(end / 4));+ let sub_y = if plane == 0 { 0 } else { fs.ssy };+ let edges = |band: &mut RowBand, mut above: Option<&mut RowBand>, pass: usize, rows: std::ops::Range<usize>| {+ let row_step = if plane == 0 { 1 } else { 1 << fs.ssy };+ let col_step = if plane == 0 { 1 } else { 1 << fs.ssx };+ let mi_cols = fs.fh.mi_cols as usize;+ let mut row = rows.start;+ while row < rows.end {+ let mut col = 0;+ while col < mi_cols {+ edge(fs, band, above.as_deref_mut(), plane, pass, row, col);+ col += col_step;+ }+ row += row_step;+ }+ };+ edges(band, None, 0, r0..r1);+ if margin.is_empty() {+ edges(band, None, 1, r0..r1);+ return Vec::new();+ }+ let stride = band.stride;+ let y0 = start.saturating_sub(LF_MARGIN) >> sub_y;+ let mut above = RowBand { data: margin, stride, y0 };+ edges(&mut above, None, 0, r0.saturating_sub(LF_MARGIN / 4)..r0);+ let before = above.data.to_vec();+ edges(band, Some(&mut above), 1, r0..r1);+ above.data.iter().zip(&before).enumerate().filter(|(_, (a, b))| a != b).map(|(i, (&a, _))| (i, a)).collect()}-fn edge(fs: &mut FrameState, plane: usize, pass: usize, row: usize, col: usize) {+/// One loop filter edge (7.14.2) at mode info position (row, col): 4 lines of samples across+/// it. `above` holds the rows above `band` for horizontal edges on the band's top row.+fn edge(fs: &FrameState, band: &mut RowBand, above: Option<&mut RowBand>, plane: usize, pass: usize, row: usize, col: usize) {let (sub_x, sub_y) = if plane == 0 { (0, 0) } else { (fs.ssx, fs.ssy) };let (dx, dy) = if pass == 0 { (1i32, 0i32) } else { (0, 1) };let x = col * 4;@@ -102,16 +189,40 @@ fn edge(fs: &mut FrameState, plane: usize, pass: usize, row: usize, col: usize)return;}let t = LfThresh::new(limit, blimit, thresh, fs.bit_depth);- let pl = &mut fs.cur.planes[plane];- let stride = pl.stride;- let (step, along) = if pass == 0 { (1, stride) } else { (stride, 1) };- let base = yp * stride + xp;let chroma = plane > 0;+ let stride = band.stride;+ if let Some(above) = above.filter(|_| pass == 1 && yp == band.y0) {+ // The p side is in the rows above the band: filter each line in a copy that spans both.+ let (n_above, n_band) = (above.data.len() / stride.max(1), band.data.len() / stride.max(1));+ for k in 0..4 {+ let x = xp + k;+ let mut line = [0u16; 2 * LF_LINE];+ for j in 1..=n_above.min(LF_LINE) {+ line[LF_LINE - j] = above.data[(n_above - j) * stride + x];+ }+ for j in 0..n_band.min(LF_LINE) {+ line[LF_LINE + j] = band.data[j * stride + x];+ }+ sample_filter(&mut line, LF_LINE, 1, chroma, filter_size, t);+ for j in 1..=n_above.min(LF_LINE) {+ above.data[(n_above - j) * stride + x] = line[LF_LINE - j];+ }+ for j in 0..n_band.min(LF_LINE) {+ band.data[j * stride + x] = line[LF_LINE + j];+ }+ }+ return;+ }+ let (step, along) = if pass == 0 { (1, stride) } else { (stride, 1) };+ let base = (yp - band.y0) * stride + xp;for k in 0..4 {- sample_filter(&mut pl.data, base + k * along, step, chroma, filter_size, t);+ sample_filter(band.data, base + k * along, step, chroma, filter_size, t);}}+/// Samples on each side of an edge that the sample filter can read (at most p6 .. q6).+const LF_LINE: usize = 8;+/// Adaptive filter strength (7.14.4): (lvl, limit, blimit, thresh).fn strength(fs: &FrameState, row: usize, col: usize, plane: usize, pass: usize) -> (i32, i32, i32, i32) {let mi = &fs.mi;diff --git a/crates/av1/src/restoration.rs b/crates/av1/src/restoration.rsindex 693e27284..923d25957 100644--- a/crates/av1/src/restoration.rs+++ b/crates/av1/src/restoration.rs@@ -1,6 +1,8 @@//! Super-resolution upscaling (7.16) and loop restoration (7.17).-use crate::frame::{FrameBuf, Plane};+use crate::frame::{FrameBuf, Plane, RowBand};+use crate::par::Pool;+use crate::postfilter::bands;use crate::spec_tables::*;use crate::state::FrameState;@@ -70,56 +72,66 @@ impl LrCtx<'_> {}/// Loop restoration (7.17): returns LrFrame given UpscaledCurrFrame and UpscaledCdefFrame.-pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf) -> FrameBuf {+/// Bands of 64 luma rows are restored in parallel: every unit reads only the two input frames+/// and writes only its own samples.+pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf, pool: &Pool) -> FrameBuf {let fh = &fs.fh;let mut lr = cdef.clone();let up_w = fh.upscaled_width as i32;let fr_h = fh.frame_height as i32;let bd = fs.bit_depth;- for plane in 0..fs.num_planes {- let rtype_frame = fh.lr.frame_restoration_type[plane];- if rtype_frame == RESTORE_NONE as u8 {- continue;- }- let (sub_x, sub_y) = if plane > 0 { (fs.ssx as i32, fs.ssy as i32) } else { (0, 0) };- let unit_size = fh.lr.loop_restoration_size[plane] as i32;- let unit_rows = fs.lr_unit_rows[plane] as i32;- let unit_cols = fs.lr_unit_cols[plane] as i32;- let plane_end_x = ((up_w + sub_x) >> sub_x) - 1;- let plane_end_y = ((fr_h + sub_y) >> sub_y) - 1;- let mut row = 0;- while row * 4 < fr_h {- let luma_y = row * 4;- let stripe_num = (luma_y + 8) / 64;- let stripe_start_y = (-8 + stripe_num * 64) >> sub_y;- let stripe_end_y = stripe_start_y + (64 >> sub_y) - 1;- let ctx = LrCtx { cur: &cur.planes[plane], cdef: &cdef.planes[plane], plane_end_x, plane_end_y, stripe_start_y, stripe_end_y };- let unit_row = (unit_rows - 1).min(((row * 4 + 8) >> sub_y) / unit_size);- let mut col = 0;- while col * 4 < up_w {- let unit_col = (unit_cols - 1).min(((col * 4) >> sub_x) / unit_size);- let x = (col * 4) >> sub_x;- let y = (row * 4) >> sub_y;- let w = (4 >> sub_x).min(plane_end_x - x + 1);- let h = (4 >> sub_y).min(plane_end_y - y + 1);- if w > 0 && h > 0 {- let ui = (unit_row * unit_cols + unit_col) as usize;- match fs.lr.lr_type[plane][ui] {- t if t == RESTORE_WIENER as u8 => wiener(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),- t if t == RESTORE_SGRPROJ as u8 => self_guided(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),- _ => {}+ let ranges = bands(pool, fh.frame_height as usize);+ let mut planes = lr.row_bands(&ranges);+ pool.map_mut(&mut planes, |b, band| {+ // Rows of 4 luma samples in this band.+ let (start, end) = ranges[b];+ let (row0, row1) = ((start / 4) as i32, (end / 4).min(fh.frame_height as usize) as i32);+ for (plane, out) in band.iter_mut().enumerate().take(fs.num_planes) {+ let rtype_frame = fh.lr.frame_restoration_type[plane];+ if rtype_frame == RESTORE_NONE as u8 {+ continue;+ }+ let (sub_x, sub_y) = if plane > 0 { (fs.ssx as i32, fs.ssy as i32) } else { (0, 0) };+ let unit_size = fh.lr.loop_restoration_size[plane] as i32;+ let unit_rows = fs.lr_unit_rows[plane] as i32;+ let unit_cols = fs.lr_unit_cols[plane] as i32;+ let plane_end_x = ((up_w + sub_x) >> sub_x) - 1;+ let plane_end_y = ((fr_h + sub_y) >> sub_y) - 1;+ let mut row = row0;+ while row < row1 && row * 4 < fr_h {+ let luma_y = row * 4;+ let stripe_num = (luma_y + 8) / 64;+ let stripe_start_y = (-8 + stripe_num * 64) >> sub_y;+ let stripe_end_y = stripe_start_y + (64 >> sub_y) - 1;+ let ctx = LrCtx { cur: &cur.planes[plane], cdef: &cdef.planes[plane], plane_end_x, plane_end_y, stripe_start_y, stripe_end_y };+ let unit_row = (unit_rows - 1).min(((row * 4 + 8) >> sub_y) / unit_size);+ let mut col = 0;+ while col * 4 < up_w {+ let unit_col = (unit_cols - 1).min(((col * 4) >> sub_x) / unit_size);+ let x = (col * 4) >> sub_x;+ let y = (row * 4) >> sub_y;+ let w = (4 >> sub_x).min(plane_end_x - x + 1);+ let h = (4 >> sub_y).min(plane_end_y - y + 1);+ if w > 0 && h > 0 {+ let ui = (unit_row * unit_cols + unit_col) as usize;+ match fs.lr.lr_type[plane][ui] {+ t if t == RESTORE_WIENER as u8 => wiener(fs, &ctx, out, plane, ui, x, y, w, h, bd),+ t if t == RESTORE_SGRPROJ as u8 => self_guided(fs, &ctx, out, plane, ui, x, y, w, h, bd),+ _ => {}+ }}+ col += 1;}- col += 1;+ row += 1;}- row += 1;}- }+ });+ drop(planes);lr}#[allow(clippy::too_many_arguments)]-fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {+fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut RowBand, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {let round0: u32 = if bd == 12 { 5 } else { 3 };let round1: u32 = if bd == 12 { 9 } else { 11 };let coef = &fs.lr.lr_wiener[plane][ui];@@ -163,7 +175,7 @@ fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize}#[allow(clippy::too_many_arguments)]-fn self_guided(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {+fn self_guided(fs: &FrameState, ctx: &LrCtx, out: &mut RowBand, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {let set = fs.lr.lr_sgr_set[plane][ui] as usize;let mut flt0 = [[0i32; 4]; 4];let mut flt1 = [[0i32; 4]; 4];diff --git a/crates/av1/tests/common/mod.rs b/crates/av1/tests/common/mod.rsindex 0892fd697..13b4567d6 100644--- a/crates/av1/tests/common/mod.rs+++ b/crates/av1/tests/common/mod.rs@@ -16,6 +16,11 @@ pub fn ffmpeg_dav1d() -> Option<PathBuf> {ffmpeg_with(&[("-decoders", "libdav1d")])}+/// ffmpeg with libaom (4:2:2 and 4:4:4 fixtures, which SVT-AV1 cannot make) and libdav1d.+pub fn ffmpeg_libaom() -> Option<PathBuf> {+ ffmpeg_with(&[("-encoders", "libaom-av1"), ("-decoders", "libdav1d")])+}+/// Builds such as the Windows "essentials" ones lack these libraries; skip rather than fail.fn ffmpeg_with(needs: &[(&str, &str)]) -> Option<PathBuf> {let ff = filmcraft_testkit::ffmpeg_or_skip("av1 oracle")?;@@ -38,9 +43,11 @@ pub fn run(ff: &Path, args: &[&str]) {assert!(out.status.success(), "ffmpeg {:?} failed: {}", args, String::from_utf8_lossy(&out.stderr));}-/// An AV1 fixture: a lavfi source encoded by ffmpeg's libsvtav1 into IVF.+/// An AV1 fixture: a lavfi source encoded by ffmpeg (libsvtav1 unless [`Spec::encoder`] says+/// otherwise) into IVF.pub struct Spec {pub name: &'static str,+ pub encoder: &'static str,pub lavfi: String,pub frames: u32,pub pix_fmt: &'static str,@@ -50,7 +57,12 @@ pub struct Spec {impl Spec {pub fn new(name: &'static str, lavfi: impl Into<String>, frames: u32, pix_fmt: &'static str, enc: &[&str]) -> Spec {- Spec { name, lavfi: lavfi.into(), frames, pix_fmt, enc: enc.iter().map(|s| s.to_string()).collect() }+ Spec { name, encoder: "libsvtav1", lavfi: lavfi.into(), frames, pix_fmt, enc: enc.iter().map(|s| s.to_string()).collect() }+ }++ pub fn encoder(mut self, encoder: &'static str) -> Spec {+ self.encoder = encoder;+ self}}@@ -60,7 +72,7 @@ pub fn make(ff: &Path, spec: &Spec) -> PathBuf {let tmp = filmcraft_testkit::temp_path(&path);let frames = spec.frames.to_string();let t = tmp.to_str().unwrap().to_string();- let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", spec.lavfi.as_str(), "-frames:v", frames.as_str(), "-pix_fmt", spec.pix_fmt, "-c:v", "libsvtav1"];+ let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", spec.lavfi.as_str(), "-frames:v", frames.as_str(), "-pix_fmt", spec.pix_fmt, "-c:v", spec.encoder];args.extend(spec.enc.iter().map(String::as_str));args.extend(["-f", "ivf", t.as_str()]);run(ff, &args);diff --git a/crates/av1/tests/oracle_inter.rs b/crates/av1/tests/oracle_inter.rsindex fcd43b087..06a4d88fe 100644--- a/crates/av1/tests/oracle_inter.rs+++ b/crates/av1/tests/oracle_inter.rs@@ -101,3 +101,19 @@ fn inter_1080p() {check_bit_exact(&ff, &s);}}++/// 4:2:2 and 4:4:4 (libaom; SVT-AV1 only makes 4:2:0): the post-filters run in row bands whose+/// chroma rows depend on the vertical subsampling, so these check the band edges there too.+#[test]+fn inter_chroma_444_422() {+ let Some(ff) = ffmpeg_libaom() else { return };+ let p = ["-cpu-used", "8", "-crf", "40", "-enable-restoration", "1"];+ let src = "testsrc2=s=416x400:r=25,noise=alls=8:allf=t";+ for s in [+ Spec::new("inter_aom_444", src, 6, "yuv444p", &p).encoder("libaom-av1"),+ Spec::new("inter_aom_422", src, 6, "yuv422p", &p).encoder("libaom-av1"),+ Spec::new("inter_aom_444_10bit", src, 6, "yuv444p10le", &p).encoder("libaom-av1"),+ ] {+ check_bit_exact(&ff, &s);+ }+}diff --git a/crates/av1/tests/perf.rs b/crates/av1/tests/perf.rsindex dd36a10e3..9047605aa 100644--- a/crates/av1/tests/perf.rs+++ b/crates/av1/tests/perf.rs@@ -51,8 +51,8 @@ fn run(frames: &[Vec<u8>], threads: usize) -> Run {}fn bench(spec: &Spec) {- // AV1_PERF_ONLY=<substring> limits the run to matching fixtures.- if std::env::var("AV1_PERF_ONLY").is_ok_and(|f| !spec.name.contains(f.as_str())) {+ // AV1_PERF_ONLY=<substring>[,<substring>...] limits the run to matching fixtures.+ if std::env::var("AV1_PERF_ONLY").is_ok_and(|f| !f.split(',').any(|f| spec.name.contains(f))) {return;}let Some(ff) = ffmpeg() else { return };@@ -68,7 +68,6 @@ fn bench(spec: &Spec) {}}let b = best.unwrap();- let n = b.stats.frames.max(1) as f64;let cpu_fps = b.cpu.map(|c| format!("{:6.1}", b.shown as f64 / c)).unwrap_or_else(|| " ?".into());println!("{:<26} {:>3} shown {:>3} decoded {:>3} tiles/frame | 1 thread: {} fps (thread CPU) {:6.1} fps (wall)",@@ -79,24 +78,35 @@ fn bench(spec: &Spec) {cpu_fps,b.shown as f64 / b.wall);- let total = b.stats.total_secs();- let mut line = String::from(" ms/frame:");- for s in Stage::ALL {- let v = b.stats.secs(s);- if v > 0.0005 {- line += &format!(" {} {:.2} ({:.0}%)", s.name(), 1e3 * v / n, 100.0 * v / total);- }- }- println!("{line}");+ println!("{}", stage_line(" ms/frame:", &b.stats));// All cores: best of 3 by wall time.let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);- let mut best_wall = f64::INFINITY;+ let mut best: Option<Run> = None;for _ in 0..3 {let r = run(&frames, threads);assert_eq!(r.shown, b.shown);- best_wall = best_wall.min(r.wall);+ if best.as_ref().is_none_or(|b| r.wall < b.wall) {+ best = Some(r);+ }+ }+ let m = best.unwrap();+ println!(" {threads} threads: {:6.1} fps (wall, load average {})", b.shown as f64 / m.wall, load_average());+ // Per-stage wall time on the frame workers (stages of different frames overlap).+ println!("{}", stage_line(&format!(" {threads} threads, ms/frame:"), &m.stats));+}++/// Per-stage milliseconds per frame and share of the total.+fn stage_line(label: &str, stats: &DecodeStats) -> String {+ let n = stats.frames.max(1) as f64;+ let total = stats.total_secs();+ let mut line = String::from(label);+ for s in Stage::ALL {+ let v = stats.secs(s);+ if v > 0.0005 {+ line += &format!(" {} {:.2} ({:.0}%)", s.name(), 1e3 * v / n, 100.0 * v / total);+ }}- println!(" {threads} threads: {:6.1} fps (wall, load average {})", b.shown as f64 / best_wall, load_average());+ line}#[test]@@ -110,4 +120,9 @@ fn decode_throughput() {// Higher quality (more coefficients, finer partitions) and a multi-tile stream (4x2 tiles).bench(&Spec::new("perf_1080p_gop_hq", src, 60, "yuv420p", &p("18", "keyint=60")));bench(&Spec::new("perf_1080p_gop_tiles", src, 60, "yuv420p", &p("30", "keyint=60:tile-columns=2:tile-rows=1")));+ // Low delay (each frame references the previous one, as screen and camera recorders encode):+ // frames cannot overlap, so a frame's own parallelism decides the speed.+ bench(&Spec::new("perf_1080p_lowdelay", src, 60, "yuv420p", &p("30", "keyint=60:pred-struct=1")));+ // One tile at 2160p: the post-filters' row bands are most of the parallelism there.+ bench(&Spec::new("perf_2160p_gop", "testsrc2=s=3840x2160:r=25,noise=alls=6:allf=t", 30, "yuv420p", &p("30", "keyint=30")));}diff --git a/docs/gaps.md b/docs/gaps.mdindex 564541067..956d03a2b 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -219,10 +219,14 @@ platforms** G4, G9, G17; **performance** G16; **ecosystem** G11; **measurement**## G16. Performance reports on 0.5.0- **Missing:** steady UI under load. Constant lag after 0.4 → 0.5 (#525), ~100% CPU (#523). AV1- software decode is ~4 fps at 1080p single-threaded; 8K is not real time.+ software decode of a single-tile stream is bound by its serial tile decode (65–80 % of a+ frame; no row-level frame threading, references are waited for as whole frames); 8K is not+ real time.- **Done:** Render (Effects) In to Out renders only the frames between In and Out, as partialpreviews named by segment hash and relative frames, instead of every segment In/Out touches- (#424); Render Audio still renders whole audio segments.+ (#424); Render Audio still renders whole audio segments. AV1 software decode runs deblocking,+ CDEF and loop restoration in parallel 64-row bands, bit-exact (#847; 1080p GOP 1.16–1.30×,+ low delay 1.28×, 2160p 1.14× at 16 threads).- **Estimate:** 30–60 h. Doc: [performance.md](performance.md).## G17. Audio device and playback reliabilitydiff --git a/docs/performance.md b/docs/performance.mdindex 96cb5f625..4b2c588b1 100644--- a/docs/performance.md+++ b/docs/performance.md@@ -518,6 +518,49 @@ decode, and the UI-thread present (upload and draw, including the backdrop copieblended layers) stays at 9–10 ms p50, as for `stack3`. Before, every frame was composited on theCPU (≈ 2 cores more at 23.976 fps) and Full resolution could not keep up at this load.+## Results (#847: AV1 in-loop filters in parallel row bands, before → after)++The AV1 decoder ran deblocking, CDEF and loop restoration on one thread per frame. A single-tile+stream (what SVT-AV1 and most encoders write by default) has no other parallelism inside a+frame, and a frame's references are waited for as whole frames, so this serial tail sat on the+critical path of every frame that references it. The three filters now run in bands of 64 luma+rows on the decoder's rayon pool, one join per filter per frame (the loop filter recomputes the+8 rows above each band rather than splitting into two passes, because every join costs a worker+wake-up, which is slow on a busy machine). Output is bit-exact with the single-threaded path and+with libdav1d (all oracle and conformance tests, plus new 4:2:2 / 4:4:4 libaom fixtures); with+one thread the code path is the old one.++Linux, AMD Ryzen 7 7800X3D (8 cores / 16 threads), 2026-10-11, shared with other agents' builds;+base = `2ff3f5e`, after = this change, 16 decoder threads, SVT-AV1 preset 8 fixtures from+`crates/av1/tests/perf.rs` (`perf_1080p_lowdelay` and `perf_2160p_gop` are new there).++`av1dec` example (`AV1_LOOPS=2 AV1_THREADS=16`), 8 rounds alternating base / after per fixture,+load average 11–27; speed-up = base wall time / after wall time of the adjacent pair:++| fixture | fps base → after (median) | paired speed-up, median (range) | after faster | CPU ms / frame (all threads) |+|---|---|---|---|---|+| `perf_1080p_lowdelay` (each frame refs the last) | 31.0 → **39.9** | 1.28 (0.85–1.48) | 6 / 8 | 44.2 → 55.0 |+| `perf_1080p_gop` (crf 30) | 74.8 → **97.7** | 1.30 (1.06–1.41) | 8 / 8 | 30.2 → 35.9 |+| `perf_1080p_gop_hq` (crf 18) | 32.0 → **37.5** | 1.16 (1.04–1.29) | 8 / 8 | 66.9 → 77.1 |+| `perf_2160p_gop` (one tile) | 23.0 → **25.3** | 1.14 (1.08–1.41) | 8 / 8 | 103.1 → 115.5 |+| `perf_1080p_intra` (10 key frames) | 121.3 → 138.1 | 1.03 (0.92–1.21) | 4 / 8 | 40.8 → 45.5 |++Per-stage wall time on the frame worker (`tests/perf.rs`, 16 threads, ms per frame, median of 2+alternating rounds at load average 8–11):++| fixture | 16 threads fps | deblock | CDEF | restoration |+|---|---|---|---|---|+| `perf_1080p_lowdelay` | 31.8 → **48.7** | 2.03 → 0.63 | 5.16 → 1.62 | 5.81 → 1.40 |+| `perf_2160p_gop` | 24.0 → **31.9** | 2.78 → 0.81 | 7.38 → 3.74 | 7.84 → 2.70 |+| `perf_1080p_gop_hq` | 34.8 → 33.6 | 1.10 → 0.55 | 6.53 → 3.08 | 4.94 → 1.65 |++One thread is unchanged (`perf_1080p_lowdelay`, 8 pairs: 2.19–2.20 s both). The extra CPU time+is mostly rayon workers spinning briefly before they sleep after each join, plus the loop+filter's recomputed margin rows. Key-frame-only streams gain little: their frames are+independent, so frame threads already keep every core busy. What remains is the tile decode+itself (entropy decoding and reconstruction of a single tile, 65–80 % of a frame), which only+row-level frame threading (waiting for reference rows instead of whole frames) can overlap.+## Results (M4.10: 4K VP9, AV1 and HEVC, before → after)Baseline = commit `a814ff6` (decoders unchanged since M4.8); after = M4.10. Interleaved runs on