Skip to content

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

M9.8: VP9 decode speedup — lane-parallel loop filter (i16/i32 lanes), banded parallel loop filter, vectorizable MC filters, per-size transform buffers, buffer pools, parallel strip assembly and picture output

Brandon Thomas0d1f21d393ef
diff --git a/crates/vp9/README.md b/crates/vp9/README.md
index b307893e6..67c444694 100644
--- a/crates/vp9/README.md
+++ b/crates/vp9/README.md
@@ -120,25 +120,42 @@ Backward adaptation is on (`-frame-parallel 0`) unless noted.
## Performance
`cargo test --release -p filmcraft-vp9 --test perf -- --ignored --nocapture` (bit-exactness is
-verified first). Apple M4 Pro (14 cores). The machine was heavily shared during measurement (load
-average 130-170), so wall-clock figures are far below what an idle machine gives; single-thread
-CPU time is the more meaningful number.
+verified first), or `VP9_THREADS=n VP9_LOOPS=k cargo run --release -p filmcraft-vp9 --example
+vp9dec -- in.ivf` (decodes the file k times and prints the statistics).
-| stream | 1 thread (CPU time) | 1 thread (wall, loaded) | 14 threads (wall, loaded) |
-|---|---|---|---|
-| 1080p 8-bit, libvpx speed 4, 4 MB/s, 4 tile columns, 60 frames | ~47 fps | ~11-17 fps | ~26-35 fps |
-| 2160p 8-bit, libvpx speed 6, 12 MB/s, 8 tile columns, 20 frames | ~13 fps | ~7-13 fps | ~15-21 fps |
+Apple M4 Pro (14 cores), 1080p 8-bit `bench_1080p` fixture (libvpx speed 4, 4 MB/s, 4 tile
+columns, 60 frames). The machine was shared with other builds during measurement (load average
+140-210), so wall-clock numbers are the best of several runs and still far below what an idle
+machine gives; single-thread CPU time is the stable figure.
-No SIMD-specific code yet; interpolation, transforms and loop filter are plain loops (the loop
-filter is still the largest cost). `cargo run --release -p filmcraft-vp9 --example vp9dec --
-in.ivf [out.yuv]` decodes an IVF file (`VP9_THREADS=n` selects the thread count) and prints the
-statistics.
+| | before (5e9d7d9) | now |
+|---|---|---|
+| 1 thread, CPU time | 55 fps | 98 fps |
+| 14 threads, wall clock (best of 4, loaded machine) | 45 fps | 115 fps |
+
+What made the difference:
+
+- Loop filter: each group of 8 samples along an edge is filtered as 8 lanes at once (16-bit lanes
+ for 8 / 10-bit, 32-bit for 12-bit); the mask / flat / flat2 decisions are lane-wise and every
+ filter result is selected per lane, so the arithmetic vectorizes. Per-group decisions use masks
+ instead of divisions and skip groups with no edge before looking up levels. The parallel loop
+ filter (superblock wavefront) locks per superblock-row band only while copying, instead of
+ holding one frame-wide lock.
+- Motion compensation: the 8-tap filters run tap-outer over fixed-width rows (4..64) and no longer
+ zero a 10 KB edge window per block; the 2D inverse transform buffers are sized per transform.
+- Memory: strip / frame planes and mode-info grids are recycled through a pool (no per-frame
+ multi-megabyte allocations and page faults); assembling tile strips into the frame and the
+ cropping / 8-bit narrowing of output pictures run in parallel chunks of rows.
+
+The loop filter is still the largest single cost (~30% single-threaded), followed by inter
+prediction and coefficient decoding.
## Known gaps
-- No frame-level threading: parallelism is tile columns + loop filter wavefront, so streams with
- a single tile column (narrower than 512 pixels or encoded without tile columns) decode mostly on
- one thread.
+- No frame-level threading: parallelism is tile columns + loop filter wavefront + row-parallel
+ copies, so streams with a single tile column (narrower than 512 pixels or encoded without tile
+ columns) decode mostly on one thread, and 1080p (at most 4 tile columns) uses 4 threads for
+ coefficient decoding and prediction.
- Scaled references combined with compound prediction are not covered by a fixture (both are
verified separately; libvpx through ffmpeg cannot change size mid-stream and the synthetic
splice cannot keep the compound streams' probability contexts intact).
diff --git a/crates/vp9/examples/vp9dec.rs b/crates/vp9/examples/vp9dec.rs
index 376d7f1b1..cf44408b5 100644
--- a/crates/vp9/examples/vp9dec.rs
+++ b/crates/vp9/examples/vp9dec.rs
@@ -9,30 +9,34 @@ fn main() {
let mut out = args.get(2).map(|p| std::io::BufWriter::new(std::fs::File::create(p).expect("create output")));
let threads = std::env::var("VP9_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(0);
let mut dec = if threads > 0 { filmcraft_vp9::Decoder::with_threads(threads) } else { filmcraft_vp9::Decoder::new() };
+ // VP9_LOOPS=n decodes the file n times (for profiling; the stream starts with a key frame).
+ let loops = std::env::var("VP9_LOOPS").ok().and_then(|s| s.parse().ok()).unwrap_or(1usize);
let hl = u16::from_le_bytes([data[6], data[7]]) as usize;
- let mut p = hl;
let mut i = 0i64;
let t0 = std::time::Instant::now();
let mut n = 0;
- while p + 12 <= data.len() {
- let sz = u32::from_le_bytes(data[p..p + 4].try_into().unwrap()) as usize;
- p += 12;
- let Some(frame) = data.get(p..p + sz) else { break };
- p += sz;
- match dec.decode(frame, i) {
- Ok(pics) => {
- for pic in pics {
- n += 1;
- if let Some(o) = out.as_mut() {
- for pl in [&pic.y, &pic.u, &pic.v] {
- o.write_all(&pl.to_le_bytes()).unwrap();
+ for _ in 0..loops {
+ let mut p = hl;
+ while p + 12 <= data.len() {
+ let sz = u32::from_le_bytes(data[p..p + 4].try_into().unwrap()) as usize;
+ p += 12;
+ let Some(frame) = data.get(p..p + sz) else { break };
+ p += sz;
+ match dec.decode(frame, i) {
+ Ok(pics) => {
+ for pic in pics {
+ n += 1;
+ if let Some(o) = out.as_mut() {
+ for pl in [&pic.y, &pic.u, &pic.v] {
+ o.write_all(&pl.to_le_bytes()).unwrap();
+ }
}
}
}
+ Err(e) => eprintln!("chunk {i}: {e}"),
}
- Err(e) => eprintln!("chunk {i}: {e}"),
+ i += 1;
}
- i += 1;
}
eprintln!("{n} pictures in {:.3}s", t0.elapsed().as_secs_f64());
eprintln!("{:#?}", dec.stats());
diff --git a/crates/vp9/src/decoder.rs b/crates/vp9/src/decoder.rs
index d6541eed5..3de847525 100644
--- a/crates/vp9/src/decoder.rs
+++ b/crates/vp9/src/decoder.rs
@@ -3,7 +3,7 @@
//! adaptation and reference frame management.
use crate::error::{Error, Result, ensure};
-use crate::frame::{Frame, MiGrid, MiInfo, Plane as FPlane, plane_geometry};
+use crate::frame::{Frame, MiGrid, MiInfo, Plane as FPlane, Pools, plane_geometry};
use crate::header::{FrameHeader, HeaderState, KEY_FRAME, RefInfo, parse_compressed, parse_uncompressed, split_superframe};
use crate::loopfilter::{LfFrame, PlaneView, filter_superblock};
use crate::probs::{Counts, adapt_coef_probs, adapt_noncoef_probs};
@@ -52,6 +52,7 @@ pub struct Decoder {
last_show_frame: bool,
stats: DecodeStats,
threads: usize,
+ bufs: Pools,
#[cfg(feature = "threads")]
pool: Option<rayon::ThreadPool>,
}
@@ -102,6 +103,7 @@ impl Decoder {
last_show_frame: false,
stats: DecodeStats::default(),
threads: threads.max(1),
+ bufs: Pools::default(),
#[cfg(feature = "threads")]
pool,
}
@@ -125,7 +127,7 @@ impl Decoder {
continue;
}
if let Some(frame) = self.decode_frame(f)? {
- out.push(make_picture(&frame, pts));
+ out.push(make_picture(&frame, pts, self.par()));
}
}
Ok(out)
@@ -236,7 +238,8 @@ impl Decoder {
}
let counting = !h.error_resilient_mode && !h.frame_parallel_decoding_mode;
let prev_mi = if use_prev { self.prev_mi.clone() } else { None };
- let shared = FrameShared { h: &h, fc: &fc, seg: &seg, prev_seg_ids: &self.prev_seg_ids, prev_mi: prev_mi.as_deref(), refs, seg_q, counting };
+ let shared =
+ FrameShared { h: &h, fc: &fc, seg: &seg, prev_seg_ids: &self.prev_seg_ids, prev_mi: prev_mi.as_deref(), refs, seg_q, counting, pools: &self.bufs };
let col_bounds: Vec<(usize, usize)> =
(0..tile_cols).map(|i| (tile_offset(i, mi_cols, h.tile_cols_log2), tile_offset(i + 1, mi_cols, h.tile_cols_log2))).collect();
let row_bounds: Vec<(usize, usize)> =
@@ -272,9 +275,13 @@ impl Decoder {
self.stats.inter_blocks += s.inter_blocks;
strips.push(s);
}
+ // Release the references before the slots are refreshed, so that evicted frames can be
+ // recycled.
+ drop(ref_frames);
+ drop(prev_mi);
// Assemble the frame and mode info.
let geo = plane_geometry(h.width, h.height, h.color.subsampling_x, h.color.subsampling_y);
- let (planes, mi, seg_ids) = assemble(strips, &geo, mi_rows, mi_cols);
+ let (planes, mi, seg_ids) = assemble(strips, &geo, mi_rows, mi_cols, &self.bufs, self.par());
let mut frame = Frame {
planes,
width: h.width,
@@ -315,12 +322,25 @@ impl Decoder {
self.prev_seg_ids = seg_ids;
}
let frame = Arc::new(frame);
+ let mut evicted = Vec::new();
for i in 0..8 {
if (h.refresh_frame_flags >> i) & 1 == 1 {
- self.slots[i] = Some(frame.clone());
+ evicted.extend(self.slots[i].replace(frame.clone()));
}
}
- self.prev_mi = Some(Arc::new(mi));
+ // Recycle the planes of frames no longer referenced anywhere.
+ for f in evicted {
+ if let Ok(f) = Arc::try_unwrap(f) {
+ for p in f.planes {
+ self.bufs.samples.put(p.data);
+ }
+ }
+ }
+ if let Some(old) = self.prev_mi.replace(Arc::new(mi))
+ && let Ok(old) = Arc::try_unwrap(old)
+ {
+ self.bufs.mi.put(old.mi);
+ }
if h.show_frame {
self.stats.shown += 1;
Ok(Some(frame))
@@ -354,6 +374,17 @@ impl Decoder {
s.profiles[h.profile as usize] += 1;
}
+ fn par(&self) -> Par<'_> {
+ #[cfg(feature = "threads")]
+ {
+ Par(self.pool.as_ref())
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ Par(std::marker::PhantomData)
+ }
+ }
+
/// Run `f(0..n)`, in parallel when a pool is available.
fn run_parallel<T: Send>(&self, n: usize, f: &(dyn Fn(usize) -> T + Sync)) -> Vec<T> {
#[cfg(feature = "threads")]
@@ -392,20 +423,53 @@ impl Decoder {
}
/// Loop filter with a superblock wavefront: superblock (r, c) runs once (r - 1, c + 1) is done.
-/// Each superblock copies the samples it may touch (its area plus 8 samples above / left) out of
-/// the shared frame, filters them locally and writes them back.
+/// The planes are split into superblock-row bands, each behind its own lock. Each superblock
+/// copies the samples it may touch (its area plus 8 samples above / left, i.e. the bottom rows
+/// of band r - 1 and its own band) out, filters them locally and writes them back; the locks are
+/// only held while copying, and only neighbouring rows ever contend.
#[cfg(feature = "threads")]
fn lf_parallel(pool: &rayon::ThreadPool, threads: usize, frame: &mut Frame, mi: &MiGrid, lf: &LfFrame, sb_rows: usize, sb_cols: usize) {
use rayon::prelude::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Condvar, Mutex};
let strides = [frame.planes[0].stride, frame.planes[1].stride, frame.planes[2].stride];
- let heights = [frame.planes[0].data.len() / strides[0], frame.planes[1].data.len() / strides[1], frame.planes[2].data.len() / strides[2]];
- let planes = Mutex::new([std::mem::take(&mut frame.planes[0].data), std::mem::take(&mut frame.planes[1].data), std::mem::take(&mut frame.planes[2].data)]);
+ let sub = [(0usize, 0usize), (lf.ss_x, lf.ss_y), (lf.ss_x, lf.ss_y)];
+ let band_h = [64usize, 64 >> lf.ss_y, 64 >> lf.ss_y];
+ // bands[r][p]: rows [r * band_h[p], (r + 1) * band_h[p]) of plane p.
+ let bands: Vec<Mutex<[&mut [u16]; 3]>> = {
+ let [a, b, c] = &mut frame.planes;
+ let mut ia = a.data.chunks_mut(band_h[0] * strides[0]);
+ let mut ib = b.data.chunks_mut(band_h[1] * strides[1]);
+ let mut ic = c.data.chunks_mut(band_h[2] * strides[2]);
+ (0..sb_rows).map(|_| Mutex::new([ia.next().unwrap_or_default(), ib.next().unwrap_or_default(), ic.next().unwrap_or_default()])).collect()
+ };
let progress = Mutex::new(vec![0usize; sb_rows]);
let cv = Condvar::new();
let next = AtomicUsize::new(0);
- let sub = [(0usize, 0usize), (lf.ss_x, lf.ss_y), (lf.ss_x, lf.ss_y)];
+ // Copy rows [ry, ry + rh) x [rx, rx + rw) of plane p between the bands and `buf` (row-major,
+ // stride rw); `to_buf` selects the direction.
+ let xfer = |r: usize, p: usize, rx: usize, ry: usize, rw: usize, rh: usize, buf: &mut [u16], to_buf: bool| {
+ let bh = band_h[p];
+ let mut yy = 0;
+ while yy < rh {
+ let y = ry + yy;
+ let br = y / bh;
+ let n = ((br + 1) * bh - y).min(rh - yy);
+ debug_assert!(br + 1 >= r && br <= r);
+ let mut g = bands[br].lock().expect("lf band");
+ let band = &mut g[p];
+ for k in 0..n {
+ let s = (y + k - br * bh) * strides[p] + rx;
+ let b = (yy + k) * rw;
+ if to_buf {
+ buf[b..b + rw].copy_from_slice(&band[s..s + rw]);
+ } else {
+ band[s..s + rw].copy_from_slice(&buf[b..b + rw]);
+ }
+ }
+ yy += n;
+ }
+ };
pool.install(|| {
(0..threads.min(sb_rows)).into_par_iter().for_each(|_| {
let mut bufs: [Vec<u16>; 3] = [vec![0; 72 * 72], vec![0; 72 * 72], vec![0; 72 * 72]];
@@ -424,20 +488,14 @@ fn lf_parallel(pool: &rayon::ThreadPool, threads: usize, frame: &mut Frame, mi:
}
// Region of each plane: [x0 - 8, x0 + size) x [y0 - 8, y0 + size).
let mut regions = [(0usize, 0usize, 0usize, 0usize); 3];
- {
- let pl = planes.lock().expect("lf planes");
- for p in 0..3 {
- let (sx, sy) = sub[p];
- let (x0, y0) = ((c * 64) >> sx, (r * 64) >> sy);
- let (rx, ry) = (x0.saturating_sub(8), y0.saturating_sub(8));
- let rw = (x0 + (64 >> sx)).min(strides[p]) - rx;
- let rh = (y0 + (64 >> sy)).min(heights[p]) - ry;
- regions[p] = (rx, ry, rw, rh);
- for yy in 0..rh {
- let s = (ry + yy) * strides[p] + rx;
- bufs[p][yy * rw..yy * rw + rw].copy_from_slice(&pl[p][s..s + rw]);
- }
- }
+ for p in 0..3 {
+ let (sx, sy) = sub[p];
+ let (x0, y0) = ((c * 64) >> sx, (r * 64) >> sy);
+ let (rx, ry) = (x0.saturating_sub(8), y0.saturating_sub(8));
+ let rw = (x0 + (64 >> sx)).min(strides[p]) - rx;
+ let rh = (y0 + band_h[p]) - ry;
+ regions[p] = (rx, ry, rw, rh);
+ xfer(r, p, rx, ry, rw, rh, &mut bufs[p], true);
}
{
let [b0, b1, b2] = &mut bufs;
@@ -448,15 +506,9 @@ fn lf_parallel(pool: &rayon::ThreadPool, threads: usize, frame: &mut Frame, mi:
];
filter_superblock(&mut views, mi, lf, r * 8, c * 8);
}
- {
- let mut pl = planes.lock().expect("lf planes");
- for p in 0..3 {
- let (rx, ry, rw, rh) = regions[p];
- for yy in 0..rh {
- let s = (ry + yy) * strides[p] + rx;
- pl[p][s..s + rw].copy_from_slice(&bufs[p][yy * rw..yy * rw + rw]);
- }
- }
+ for p in 0..3 {
+ let (rx, ry, rw, rh) = regions[p];
+ xfer(r, p, rx, ry, rw, rh, &mut bufs[p], false);
}
let mut p = progress.lock().expect("lf progress");
p[r] = c + 1;
@@ -465,56 +517,113 @@ fn lf_parallel(pool: &rayon::ThreadPool, threads: usize, frame: &mut Frame, mi:
}
});
});
- let [a, b, c] = planes.into_inner().expect("lf planes");
- frame.planes[0].data = a;
- frame.planes[1].data = b;
- frame.planes[2].data = c;
}
+/// Optional thread pool for data-parallel copies.
+#[derive(Clone, Copy)]
+struct Par<'a>(#[cfg(feature = "threads")] Option<&'a rayon::ThreadPool>, #[cfg(not(feature = "threads"))] std::marker::PhantomData<&'a ()>);
+
+impl Par<'_> {
+ /// `f(i, chunk)` for the consecutive `chunk_len`-element chunks of `data`.
+ fn chunks<T: Send>(self, data: &mut [T], chunk_len: usize, f: impl Fn(usize, &mut [T]) + Sync) {
+ let chunk_len = chunk_len.max(1);
+ #[cfg(feature = "threads")]
+ if let Some(pool) = self.0
+ && data.len() > chunk_len
+ {
+ use rayon::prelude::*;
+ pool.install(|| data.par_chunks_mut(chunk_len).enumerate().for_each(|(i, c)| f(i, c)));
+ return;
+ }
+ for (i, c) in data.chunks_mut(chunk_len).enumerate() {
+ f(i, c);
+ }
+ }
+}
+
+/// Rows per chunk of the parallel frame copies.
+const COPY_ROWS: usize = 64;
+
/// Build full-frame planes, mode info and segment ids from the tile column strips.
-fn assemble(mut strips: Vec<Strip>, geo: &[(usize, usize, usize, usize); 3], mi_rows: usize, mi_cols: usize) -> ([FPlane; 3], MiGrid, Vec<u8>) {
+fn assemble(
+ mut strips: Vec<Strip>,
+ geo: &[(usize, usize, usize, usize); 3],
+ mi_rows: usize,
+ mi_cols: usize,
+ pools: &Pools,
+ par: Par,
+) -> ([FPlane; 3], MiGrid, Vec<u8>) {
if strips.len() == 1 {
let s = strips.pop().expect("one strip");
let [a, b, c] = s.planes;
let mk = |d: Vec<u16>, g: (usize, usize, usize, usize)| FPlane { data: d, stride: g.0, width: g.2, height: g.3 };
return ([mk(a, geo[0]), mk(b, geo[1]), mk(c, geo[2])], MiGrid { cols: mi_cols, rows: mi_rows, mi: s.mi }, s.seg_ids);
}
- let mut planes = [
- FPlane::new(geo[0].0, geo[0].1, geo[0].2, geo[0].3),
- FPlane::new(geo[1].0, geo[1].1, geo[1].2, geo[1].3),
- FPlane::new(geo[2].0, geo[2].1, geo[2].2, geo[2].3),
- ];
- let mut mi = vec![MiInfo::default(); mi_rows * mi_cols];
+ let mk = |g: (usize, usize, usize, usize)| FPlane { data: pools.samples.take(g.0 * g.1, 0), stride: g.0, width: g.2, height: g.3 };
+ let mut planes = [mk(geo[0]), mk(geo[1]), mk(geo[2])];
+ let mut mi = pools.mi.take(mi_rows * mi_cols, MiInfo::default());
let mut seg = vec![0u8; mi_rows * mi_cols];
- for s in &strips {
- for p in 0..3 {
- let ss = s.strides[p];
- let fs = planes[p].stride;
- let x0 = s.x_off[p];
- let w = ss.min(fs - x0);
- let rows = s.planes[p].len() / ss;
- for y in 0..rows {
- planes[p].data[y * fs + x0..y * fs + x0 + w].copy_from_slice(&s.planes[p][y * ss..y * ss + w]);
+ for (p, plane) in planes.iter_mut().enumerate() {
+ let fs = plane.stride;
+ // Each chunk of destination rows gathers its part of every strip.
+ par.chunks(&mut plane.data, COPY_ROWS * fs, |ci, dst| {
+ let y0 = ci * COPY_ROWS;
+ for s in &strips {
+ let ss = s.strides[p];
+ let x0 = s.x_off[p];
+ let w = ss.min(fs - x0);
+ for (k, row) in dst.chunks_mut(fs).enumerate() {
+ let y = y0 + k;
+ if let Some(src) = s.planes[p].get(y * ss..y * ss + w) {
+ row[x0..x0 + w].copy_from_slice(src);
+ }
+ }
}
- }
+ });
+ }
+ for s in &strips {
let mw = s.mi_col_end - s.mi_col_start;
for r in 0..mi_rows {
mi[r * mi_cols + s.mi_col_start..r * mi_cols + s.mi_col_end].copy_from_slice(&s.mi[r * mw..r * mw + mw]);
seg[r * mi_cols + s.mi_col_start..r * mi_cols + s.mi_col_end].copy_from_slice(&s.seg_ids[r * mw..r * mw + mw]);
}
}
+ for s in strips {
+ for p in s.planes {
+ pools.samples.put(p);
+ }
+ pools.mi.put(s.mi);
+ }
(planes, MiGrid { cols: mi_cols, rows: mi_rows, mi }, seg)
}
-fn make_picture(f: &Frame, pts: i64) -> Picture {
- let crop = |p: &FPlane| -> Vec<u16> {
- let mut v = Vec::with_capacity(p.width * p.height);
- for y in 0..p.height {
- v.extend_from_slice(&p.row(y)[..p.width]);
+fn make_picture(f: &Frame, pts: i64, par: Par) -> Picture {
+ // Crop (and narrow 8-bit samples), in parallel chunks of rows.
+ let conv = |p: &FPlane| -> Plane {
+ let w = p.width;
+ if w == 0 || p.height == 0 {
+ return if f.bit_depth == 8 { Plane::U8(Vec::new()) } else { Plane::U16(Vec::new()) };
+ }
+ if f.bit_depth == 8 {
+ let mut out = vec![0u8; w * p.height];
+ par.chunks(&mut out, COPY_ROWS * w, |ci, dst| {
+ for (k, row) in dst.chunks_mut(w).enumerate() {
+ for (d, &s) in row.iter_mut().zip(&p.row(ci * COPY_ROWS + k)[..w]) {
+ *d = s as u8;
+ }
+ }
+ });
+ Plane::U8(out)
+ } else {
+ let mut out = vec![0u16; w * p.height];
+ par.chunks(&mut out, COPY_ROWS * w, |ci, dst| {
+ for (k, row) in dst.chunks_mut(w).enumerate() {
+ row.copy_from_slice(&p.row(ci * COPY_ROWS + k)[..w]);
+ }
+ });
+ Plane::U16(out)
}
- v
};
- let conv = |v: Vec<u16>| if f.bit_depth == 8 { Plane::U8(v.into_iter().map(|s| s as u8).collect()) } else { Plane::U16(v) };
let [y, u, v] = &f.planes;
Picture {
width: f.width,
@@ -524,9 +633,9 @@ fn make_picture(f: &Frame, pts: i64) -> Picture {
bit_depth: f.bit_depth as u32,
subsampling_x: f.ss_x,
subsampling_y: f.ss_y,
- y: conv(crop(y)),
- u: conv(crop(u)),
- v: conv(crop(v)),
+ y: conv(y),
+ u: conv(u),
+ v: conv(v),
y_stride: y.width,
uv_stride: u.width,
pts,
diff --git a/crates/vp9/src/frame.rs b/crates/vp9/src/frame.rs
index a6ed51b26..3b2a6861e 100644
--- a/crates/vp9/src/frame.rs
+++ b/crates/vp9/src/frame.rs
@@ -74,10 +74,6 @@ pub struct Plane {
}
impl Plane {
- pub fn new(alloc_w: usize, alloc_h: usize, width: usize, height: usize) -> Plane {
- Plane { data: vec![0; alloc_w * alloc_h], stride: alloc_w, width, height }
- }
-
#[inline]
pub fn row(&self, y: usize) -> &[u16] {
&self.data[y * self.stride..(y + 1) * self.stride]
@@ -111,3 +107,52 @@ pub fn plane_geometry(width: u32, height: u32, ss_x: bool, ss_y: bool) -> [(usiz
let ch = (height as usize + sy) >> sy;
[(aw, ah, width as usize, height as usize), (aw >> sx, ah >> sy, cw, ch), (aw >> sx, ah >> sy, cw, ch)]
}
+
+/// Recycled buffers (strip / frame planes, mode info), so that steady-state decoding does not
+/// allocate (and page-fault) megabytes per frame.
+pub struct Pool<T> {
+ bufs: std::sync::Mutex<Vec<Vec<T>>>,
+}
+
+impl<T> Default for Pool<T> {
+ fn default() -> Self {
+ Pool { bufs: Default::default() }
+ }
+}
+
+impl<T: Clone> Pool<T> {
+ const MAX: usize = 32;
+
+ /// A buffer of `len` copies of `fill` (recycled memory when available).
+ pub fn take(&self, len: usize, fill: T) -> Vec<T> {
+ let found = {
+ let mut b = self.bufs.lock().expect("buffer pool");
+ b.iter().position(|v| v.capacity() >= len).map(|i| b.swap_remove(i))
+ };
+ match found {
+ Some(mut v) => {
+ v.resize(len, fill);
+ v
+ }
+ None => vec![fill; len],
+ }
+ }
+
+ pub fn put(&self, mut v: Vec<T>) {
+ if v.capacity() == 0 {
+ return;
+ }
+ v.clear();
+ let mut b = self.bufs.lock().expect("buffer pool");
+ if b.len() < Self::MAX {
+ b.push(v);
+ }
+ }
+}
+
+/// The decoder's buffer pools.
+#[derive(Default)]
+pub struct Pools {
+ pub samples: Pool<u16>,
+ pub mi: Pool<MiInfo>,
+}
diff --git a/crates/vp9/src/inter.rs b/crates/vp9/src/inter.rs
index 5b3a7266b..0598c5d87 100644
--- a/crates/vp9/src/inter.rs
+++ b/crates/vp9/src/inter.rs
@@ -20,11 +20,25 @@ pub struct RefPlane<'a> {
/// Predict a `w` x `h` block whose top-left sample is at (`x`, `y`) in 1/16 sample units of the
/// reference, stepping `step_x` / `step_y` (16 = unscaled). Output samples go to `out` (stride
-/// `w`). `tmp` must hold at least `(h * step_y / 16 + 8) * w` entries.
+/// `w`). `tmp` must hold at least `(h * step_y / 16 + 8) * w` entries, `win` at least
+/// `(w + 7) * (h + 7)` (edge-clamped source window).
#[allow(clippy::too_many_arguments)]
-pub fn predict(r: &RefPlane, x: i32, y: i32, step_x: i32, step_y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16]) {
+pub fn predict(
+ r: &RefPlane,
+ x: i32,
+ y: i32,
+ step_x: i32,
+ step_y: i32,
+ w: usize,
+ h: usize,
+ filter: u8,
+ bit_depth: u8,
+ out: &mut [u16],
+ tmp: &mut [u16],
+ win: &mut [u16],
+) {
if step_x == 16 && step_y == 16 {
- predict_unscaled(r, x, y, w, h, filter, bit_depth, out, tmp);
+ predict_unscaled(r, x, y, w, h, filter, bit_depth, out, tmp, win);
} else {
predict_scaled(r, x, y, step_x, step_y, w, h, filter, bit_depth, out, tmp);
}
@@ -50,17 +64,16 @@ fn fetch_window(r: &RefPlane, x0: i32, y0: i32, w: usize, h: usize, win: &mut [u
}
#[allow(clippy::too_many_arguments)]
-fn predict_unscaled(r: &RefPlane, x: i32, y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16]) {
+fn predict_unscaled(r: &RefPlane, x: i32, y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16], win: &mut [u16]) {
let (x0, y0) = (x >> 4, y >> 4);
let (fx, fy) = ((x & 15) as usize, (y & 15) as usize);
let max = (1i32 << bit_depth) - 1;
let inside = x0 - 3 >= 0 && y0 - 3 >= 0 && x0 + w as i32 + 4 <= r.last_x && y0 + h as i32 + 4 <= r.last_y;
// Source view with origin at (x0 - 3, y0 - 3).
- let mut win = [0u16; 71 * 71];
let (src, ss, so): (&[u16], usize, usize) = if inside {
(r.data, r.stride, (y0 - 3) as usize * r.stride + (x0 - 3) as usize)
} else {
- let ws = fetch_window(r, x0, y0, w, h, &mut win);
+ let ws = fetch_window(r, x0, y0, w, h, win);
(&win[..], ws, 0)
};
match (fx, fy) {
@@ -73,61 +86,97 @@ fn predict_unscaled(r: &RefPlane, x: i32, y: i32, w: usize, h: usize, filter: u8
(_, 0) => {
let f = taps(filter, fx);
for i in 0..h {
- let s = &src[so + (i + 3) * ss..];
- let o = &mut out[i * w..i * w + w];
- for (j, d) in o.iter_mut().enumerate() {
- let p = &s[j..j + 8];
- let mut acc = 0i32;
- for t in 0..8 {
- acc += f[t] as i32 * p[t] as i32;
- }
- *d = ((acc + 64) >> 7).clamp(0, max) as u16;
- }
+ filter_h(&src[so + (i + 3) * ss..], f, max, &mut out[i * w..i * w + w]);
}
}
(0, _) => {
let f = taps(filter, fy);
for i in 0..h {
- let o = &mut out[i * w..i * w + w];
- for (j, d) in o.iter_mut().enumerate() {
- let base = so + i * ss + j + 3;
- let mut acc = 0i32;
- for t in 0..8 {
- acc += f[t] as i32 * src[base + t * ss] as i32;
- }
- *d = ((acc + 64) >> 7).clamp(0, max) as u16;
- }
+ filter_v(&src[so + i * ss + 3..], ss, f, max, &mut out[i * w..i * w + w]);
}
}
_ => {
let fh = taps(filter, fx);
let fv = taps(filter, fy);
for i in 0..h + 7 {
- let s = &src[so + i * ss..];
- let o = &mut tmp[i * w..i * w + w];
- for (j, d) in o.iter_mut().enumerate() {
- let p = &s[j..j + 8];
- let mut acc = 0i32;
- for t in 0..8 {
- acc += fh[t] as i32 * p[t] as i32;
- }
- *d = ((acc + 64) >> 7).clamp(0, max) as u16;
- }
+ filter_h(&src[so + i * ss..], fh, max, &mut tmp[i * w..i * w + w]);
}
for i in 0..h {
- let o = &mut out[i * w..i * w + w];
- for (j, d) in o.iter_mut().enumerate() {
- let mut acc = 0i32;
- for t in 0..8 {
- acc += fv[t] as i32 * tmp[(i + t) * w + j] as i32;
- }
- *d = ((acc + 64) >> 7).clamp(0, max) as u16;
- }
+ filter_v(&tmp[i * w..], w, fv, max, &mut out[i * w..i * w + w]);
+ }
+ }
+ }
+}
+
+/// Horizontal 8-tap filter of one row: `o[j]` from `s[j..j + 8]`. The taps are the outer loop
+/// so that the row vectorizes (same sums, same order of the exact integer additions).
+#[inline(always)]
+fn filter_h(s: &[u16], f: &[i16], max: i32, o: &mut [u16]) {
+ match o.len() {
+ 4 => filter_h_n::<4>(s, f, max, o),
+ 8 => filter_h_n::<8>(s, f, max, o),
+ 16 => filter_h_n::<16>(s, f, max, o),
+ 32 => filter_h_n::<32>(s, f, max, o),
+ 64 => filter_h_n::<64>(s, f, max, o),
+ _ => {
+ for (j, d) in o.iter_mut().enumerate() {
+ let acc: i32 = (0..8).map(|t| f[t] as i32 * s[j + t] as i32).sum();
+ *d = ((acc + 64) >> 7).clamp(0, max) as u16;
+ }
+ }
+ }
+}
+
+#[inline(always)]
+fn filter_h_n<const W: usize>(s: &[u16], f: &[i16], max: i32, o: &mut [u16]) {
+ let o: &mut [u16; W] = (&mut o[..W]).try_into().expect("row");
+ let mut acc = [64i32; W];
+ for t in 0..8 {
+ let c = f[t] as i32;
+ let p: &[u16; W] = s[t..t + W].try_into().expect("row");
+ for j in 0..W {
+ acc[j] += c * p[j] as i32;
+ }
+ }
+ for j in 0..W {
+ o[j] = (acc[j] >> 7).clamp(0, max) as u16;
+ }
+}
+
+/// Vertical 8-tap filter of one row: `o[j]` from `s[j + t * ss]`, t = 0..8.
+#[inline(always)]
+fn filter_v(s: &[u16], ss: usize, f: &[i16], max: i32, o: &mut [u16]) {
+ match o.len() {
+ 4 => filter_v_n::<4>(s, ss, f, max, o),
+ 8 => filter_v_n::<8>(s, ss, f, max, o),
+ 16 => filter_v_n::<16>(s, ss, f, max, o),
+ 32 => filter_v_n::<32>(s, ss, f, max, o),
+ 64 => filter_v_n::<64>(s, ss, f, max, o),
+ _ => {
+ for (j, d) in o.iter_mut().enumerate() {
+ let acc: i32 = (0..8).map(|t| f[t] as i32 * s[j + t * ss] as i32).sum();
+ *d = ((acc + 64) >> 7).clamp(0, max) as u16;
}
}
}
}
+#[inline(always)]
+fn filter_v_n<const W: usize>(s: &[u16], ss: usize, f: &[i16], max: i32, o: &mut [u16]) {
+ let o: &mut [u16; W] = (&mut o[..W]).try_into().expect("row");
+ let mut acc = [64i32; W];
+ for t in 0..8 {
+ let c = f[t] as i32;
+ let p: &[u16; W] = s[t * ss..t * ss + W].try_into().expect("row");
+ for j in 0..W {
+ acc[j] += c * p[j] as i32;
+ }
+ }
+ for j in 0..W {
+ o[j] = (acc[j] >> 7).clamp(0, max) as u16;
+ }
+}
+
/// General process of 8.5.2.4 (any step).
#[allow(clippy::too_many_arguments)]
fn predict_scaled(r: &RefPlane, x: i32, y: i32, step_x: i32, step_y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16]) {
@@ -175,7 +224,7 @@ mod tests {
for &(bw, bh) in &[(4usize, 4usize), (8, 8), (16, 8)] {
let mut a = vec![0u16; bw * bh];
let mut b = vec![0u16; bw * bh];
- predict_unscaled(&r, x, y, bw, bh, filter, 8, &mut a, &mut tmp);
+ predict_unscaled(&r, x, y, bw, bh, filter, 8, &mut a, &mut tmp, &mut [0u16; 71 * 71]);
predict_scaled(&r, x, y, 16, 16, bw, bh, filter, 8, &mut b, &mut tmp);
assert_eq!(a, b, "filter {filter} pos ({x},{y}) {bw}x{bh}");
}
diff --git a/crates/vp9/src/loopfilter.rs b/crates/vp9/src/loopfilter.rs
index a3de046f5..21ad99b4f 100644
--- a/crates/vp9/src/loopfilter.rs
+++ b/crates/vp9/src/loopfilter.rs
@@ -109,15 +109,20 @@ fn filter_sb_plane(v: &mut PlaneView, mi: &MiGrid, f: &LfFrame, plane: usize, pa
m.tx_size
};
let sb_size = if sub == 0 { m.sb_size } else { m.sb_size.max(BLOCK_16X16) } as usize;
- let skip = m.skip;
let is_intra = m.ref_frame[0] <= INTRA_FRAME;
- let is_block_edge = if pass == 0 { x % (8 * NUM_8X8_WIDE[sb_size] as usize) == 0 } else { y % (8 * NUM_8X8_HIGH[sb_size] as usize) == 0 };
- let is32 = edge % 8 == 0;
+ // Block sizes are powers of two, so the modulo is a mask.
+ let is_block_edge = if pass == 0 { x & (8 * NUM_8X8_WIDE[sb_size] as usize - 1) == 0 } else { y & (8 * NUM_8X8_HIGH[sb_size] as usize - 1) == 0 };
+ let tx_ok = edge & ((1 << tx_sz) - 1) == 0 && (is_intra || !m.skip);
+ if !is_block_edge && !tx_ok {
+ i += 8;
+ continue;
+ }
let lvl = f.level(m);
if lvl == 0 {
i += 8;
continue;
}
+ let is32 = edge % 8 == 0;
let base_size = if tx_sz == TX_4X4 && is32 { TX_8X8 } else { tx_sz.min(TX_16X16) };
let filter_size =
if base_size == TX_16X16 && ((pass == 0 && sub_x == 1 && (x >> 3) == mi_cols - 1) || (pass == 1 && sub_y == 1 && (y >> 3) == mi_rows - 1)) {
@@ -126,119 +131,238 @@ fn filter_sb_plane(v: &mut PlaneView, mi: &MiGrid, f: &LfFrame, plane: usize, pa
base_size
};
let (limit, blimit, thresh) = f.limits[lvl as usize];
- let tx_edge_normal = edge % (1 << tx_sz) == 0;
- for k in i..(i + 8).min(edge_len) {
- let (sx, sy) = if pass == 0 { (x, row * 8 + (k << sub_y)) } else { (col * 8 + (k << sub_x), y) };
- if sx >= 8 * mi_cols || sy >= 8 * mi_rows {
- continue;
- }
- let is_tx_edge = if pass == 1 && sub_x == 1 && mi_cols & 1 == 1 && edge & 1 == 1 && sx + 8 >= mi_cols * 8 { false } else { tx_edge_normal };
- let apply = is_block_edge || (is_tx_edge && (is_intra || !skip));
- if !apply {
- continue;
+ // Lanes of the group (the 8 samples along the edge) inside the MI grid.
+ let n = if pass == 0 { (8 * mi_rows - y).div_ceil(1 << sub_y) } else { (8 * mi_cols - x).div_ceil(1 << sub_x) }.min(LANES).min(edge_len - i);
+ // A transform edge is not filtered in the last odd chroma column (8.8.2).
+ let odd_last = pass == 1 && sub_x == 1 && mi_cols & 1 == 1 && edge & 1 == 1;
+ let mut apply = [false; LANES];
+ for (l, a) in apply.iter_mut().enumerate().take(n) {
+ let is_tx_edge = tx_ok && !(odd_last && x + (l << sub_x) + 8 >= mi_cols * 8);
+ *a = is_block_edge || is_tx_edge;
+ }
+ if apply.iter().any(|&a| a) {
+ let px = x >> sub_x;
+ let py = y >> sub_y;
+ let pos = (py - v.oy) * v.stride + px - v.ox;
+ let along = if pass == 0 { v.stride } else { 1 };
+ let lim = Limits { apply, limit, blimit, thresh, filter_size, bit_depth: f.bit_depth };
+ let (d, st) = (&mut *v.data, across as usize);
+ match (f.bit_depth <= 10, filter_size == TX_16X16, pass == 1) {
+ (true, false, false) => lanes16::filter_group::<4, false>(d, pos, along, st, &lim),
+ (true, false, true) => lanes16::filter_group::<4, true>(d, pos, along, st, &lim),
+ (true, true, false) => lanes16::filter_group::<8, false>(d, pos, along, st, &lim),
+ (true, true, true) => lanes16::filter_group::<8, true>(d, pos, along, st, &lim),
+ (false, false, false) => lanes32::filter_group::<4, false>(d, pos, along, st, &lim),
+ (false, false, true) => lanes32::filter_group::<4, true>(d, pos, along, st, &lim),
+ (false, true, false) => lanes32::filter_group::<8, false>(d, pos, along, st, &lim),
+ (false, true, true) => lanes32::filter_group::<8, true>(d, pos, along, st, &lim),
}
- let px = sx >> sub_x;
- let py = sy >> sub_y;
- let pos = ((py - v.oy) * v.stride + px - v.ox) as isize;
- filter_sample(v.data, pos, across, limit, blimit, thresh, filter_size, f.bit_depth);
}
i += 8;
}
}
}
-/// Sample filtering process (8.8.5) at `pos` (the q0 sample), samples across the edge `step`
-/// apart. The samples are gathered into `v` (`v[8 + k]` = sample at offset k) and only modified
-/// samples are written back.
-#[allow(clippy::too_many_arguments)]
-#[inline]
-fn filter_sample(d: &mut [u16], pos: isize, step: isize, limit: i32, blimit: i32, thresh: i32, filter_size: u8, bit_depth: u8) {
- let reach: usize = if filter_size == TX_16X16 { 8 } else { 4 };
- let step = step as usize;
- let start = pos as usize - reach * step;
- let mut v = [0i32; 16];
- {
- let span = &d[start..start + (2 * reach - 1) * step + 1];
- for k in 0..2 * reach {
- v[8 - reach + k] = span[k * step] as i32;
- }
- }
- let (p3, p2, p1, p0, q0, q1, q2, q3) = (v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]);
- let shift = bit_depth as u32 - 8;
- // Filter mask process (8.8.5.1).
- let limit_bd = limit << shift;
- let blimit_bd = blimit << shift;
- if (p3 - p2).abs() > limit_bd
- || (p2 - p1).abs() > limit_bd
- || (p1 - p0).abs() > limit_bd
- || (q1 - q0).abs() > limit_bd
- || (q2 - q1).abs() > limit_bd
- || (q3 - q2).abs() > limit_bd
- || (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 > blimit_bd
- {
- return;
- }
- let thresh_bd = thresh << shift;
- let hev = (p1 - p0).abs() > thresh_bd || (q1 - q0).abs() > thresh_bd;
- let one = 1 << shift;
- let flat = filter_size >= TX_8X8
- && (p1 - p0).abs() <= one
- && (q1 - q0).abs() <= one
- && (p2 - p0).abs() <= one
- && (q2 - q0).abs() <= one
- && (p3 - p0).abs() <= one
- && (q3 - q0).abs() <= one;
- let (lo, hi) = if filter_size == TX_4X4 || !flat {
- narrow_filter(&mut v, hev, bit_depth);
- (6, 10)
- } else {
- let flat2 = filter_size >= TX_16X16 && (0..4).all(|k| (v[3 - k] - p0).abs() <= one && (v[12 + k] - q0).abs() <= one);
- if flat2 {
- wide_filter(&mut v, 4);
- (1, 15)
- } else {
- wide_filter(&mut v, 3);
- (5, 11)
- }
- };
- for k in lo..hi {
- d[(pos + (k as isize - 8) * step as isize) as usize] = v[k] as u16;
- }
-}
+/// Samples along an edge filtered together.
+const LANES: usize = 8;
-/// Narrow filter process (8.8.5.2) on gathered samples.
-#[inline]
-fn narrow_filter(v: &mut [i32; 16], hev: bool, bit_depth: u8) {
- let shift = bit_depth as u32 - 8;
- let lo = -(1 << (bit_depth - 1));
- let hi = (1 << (bit_depth - 1)) - 1;
- let c = |x: i32| x.clamp(lo, hi);
- let off = 0x80 << shift;
- let (ps1, ps0, qs0, qs1) = (v[6] - off, v[7] - off, v[8] - off, v[9] - off);
- let mut filter = if hev { c(ps1 - qs1) } else { 0 };
- filter = c(filter + 3 * (qs0 - ps0));
- let filter1 = c(filter + 4) >> 3;
- let filter2 = c(filter + 3) >> 3;
- v[8] = c(qs0 - filter1) + off;
- v[7] = c(ps0 + filter2) + off;
- if !hev {
- let f = (filter1 + 1) >> 1;
- v[9] = c(qs1 - f) + off;
- v[6] = c(ps1 + f) + off;
- }
+/// Per-group filter parameters.
+struct Limits {
+ apply: [bool; LANES],
+ limit: i32,
+ blimit: i32,
+ thresh: i32,
+ filter_size: u8,
+ bit_depth: u8,
}
-/// Wide filter process (8.8.5.3) with 2^log2 taps on gathered samples; the sum over j of the
-/// specification is computed as a sliding window over the clamped indices (identical results).
-#[inline]
-fn wide_filter(v: &mut [i32; 16], log2: u32) {
- let n = (1isize << (log2 - 1)) - 1;
- let src = *v;
- let s = |k: isize| src[(k.clamp(-(n + 1), n) + 8) as usize];
- let mut sum: i32 = (-n..=n).map(|j| s(-n + j)).sum();
- let round = 1i32 << (log2 - 1);
- for i in -n..n {
- v[(i + 8) as usize] = (sum + s(i) + round) >> log2;
- sum += s(i + 1 + n) - s(i - n);
- }
+/// The group filter, instantiated for 16-bit lanes (bit depths 8 and 10: every intermediate,
+/// including the 16-tap sums of at most 16 * 1023 + 8, fits) and 32-bit lanes (12-bit).
+macro_rules! group_filter {
+ ($m:ident, $t:ty) => {
+ mod $m {
+ use super::{LANES, Limits};
+ use crate::tables::*;
+ type T = $t;
+
+ /// Sample filtering process (8.8.5) for the up to 8 lanes of a group whose `apply` flag is set.
+ /// Lane `l` has its q0 sample at `pos + l * along`; samples across the edge are `step` apart
+ /// (`ROWS`: `along` is 1, i.e. a horizontal edge). `R` samples on each side are read (8 for
+ /// 16x16 filters, else 4). Every lane is computed with every filter and the result chosen per
+ /// lane (8.8.5.1 decides which), so the arithmetic is branch-free and vectorizes; unmodified
+ /// samples are written back unchanged.
+ #[inline(always)]
+ pub(super) fn filter_group<const R: usize, const ROWS: bool>(d: &mut [u16], pos: usize, along: usize, step: usize, g: &Limits) {
+ let Limits { apply, limit, blimit, thresh, filter_size, bit_depth } = *g;
+ let (limit, blimit, thresh) = (limit as T, blimit as T, thresh as T);
+ // v[8 + k][l] = sample at offset k across the edge in lane l.
+ let mut v = [[0 as T; LANES]; 16];
+ let start = pos - R * step;
+ if ROWS {
+ for k in 0..2 * R {
+ let row: &[u16; LANES] = d[start + k * step..start + k * step + LANES].try_into().expect("lanes");
+ v[8 - R + k] = std::array::from_fn(|l| row[l] as T);
+ }
+ } else {
+ for l in 0..LANES {
+ let s = start + l * along;
+ let line: &[u16] = &d[s..s + 2 * R];
+ for k in 0..2 * R {
+ v[8 - R + k][l] = line[k] as T;
+ }
+ }
+ }
+ let shift = bit_depth as u32 - 8;
+ let limit_bd = limit << shift;
+ let blimit_bd = blimit << shift;
+ let thresh_bd = thresh << shift;
+ let one = 1 << shift;
+ let (p3, p2, p1, p0, q0, q1, q2, q3) = (&v[4], &v[5], &v[6], &v[7], &v[8], &v[9], &v[10], &v[11]);
+ // Filter mask process (8.8.5.1), with non-short-circuit `&` so that it vectorizes.
+ let mut mask = [false; LANES];
+ let mut hev = [false; LANES];
+ let mut flat = [false; LANES];
+ let mut flat2 = [false; LANES];
+ let can_flat = filter_size >= TX_8X8;
+ let can_flat2 = R == 8 && filter_size >= TX_16X16;
+ for l in 0..LANES {
+ let d_p1p0 = (p1[l] - p0[l]).abs();
+ let d_q1q0 = (q1[l] - q0[l]).abs();
+ mask[l] = apply[l]
+ & ((p3[l] - p2[l]).abs() <= limit_bd)
+ & ((p2[l] - p1[l]).abs() <= limit_bd)
+ & (d_p1p0 <= limit_bd)
+ & (d_q1q0 <= limit_bd)
+ & ((q2[l] - q1[l]).abs() <= limit_bd)
+ & ((q3[l] - q2[l]).abs() <= limit_bd)
+ & ((p0[l] - q0[l]).abs() * 2 + (p1[l] - q1[l]).abs() / 2 <= blimit_bd);
+ hev[l] = (d_p1p0 > thresh_bd) | (d_q1q0 > thresh_bd);
+ flat[l] = can_flat
+ & mask[l]
+ & (d_p1p0 <= one)
+ & (d_q1q0 <= one)
+ & ((p2[l] - p0[l]).abs() <= one)
+ & ((q2[l] - q0[l]).abs() <= one)
+ & ((p3[l] - p0[l]).abs() <= one)
+ & ((q3[l] - q0[l]).abs() <= one);
+ }
+ if !mask.iter().fold(false, |a, &m| a | m) {
+ return;
+ }
+ if can_flat2 {
+ for l in 0..LANES {
+ flat2[l] = flat[l]
+ & ((v[0][l] - p0[l]).abs() <= one)
+ & ((v[1][l] - p0[l]).abs() <= one)
+ & ((v[2][l] - p0[l]).abs() <= one)
+ & ((v[3][l] - p0[l]).abs() <= one)
+ & ((v[12][l] - q0[l]).abs() <= one)
+ & ((v[13][l] - q0[l]).abs() <= one)
+ & ((v[14][l] - q0[l]).abs() <= one)
+ & ((v[15][l] - q0[l]).abs() <= one);
+ }
+ }
+ let any_flat = flat.iter().fold(false, |a, &f| a | f);
+ let any_flat2 = flat2.iter().fold(false, |a, &f| a | f);
+ // Results per position across the edge; start from the unfiltered samples.
+ let mut out = v;
+ // Narrow filter (8.8.5.2) for lanes that are masked but not flat.
+ {
+ let lo = -(1 << (bit_depth - 1)) as T;
+ let hi = ((1 << (bit_depth - 1)) - 1) as T;
+ let c = |x: T| x.clamp(lo, hi);
+ let off: T = 0x80 << shift;
+ for l in 0..LANES {
+ let (ps1, ps0, qs0, qs1) = (p1[l] - off, p0[l] - off, q0[l] - off, q1[l] - off);
+ let filter = c(if hev[l] { c(ps1 - qs1) } else { 0 } + 3 * (qs0 - ps0));
+ let filter1 = c(filter + 4) >> 3;
+ let filter2 = c(filter + 3) >> 3;
+ let f = (filter1 + 1) >> 1;
+ let narrow = mask[l] && !flat[l];
+ let outer = narrow && !hev[l];
+ out[8][l] = if narrow { c(qs0 - filter1) + off } else { out[8][l] };
+ out[7][l] = if narrow { c(ps0 + filter2) + off } else { out[7][l] };
+ out[9][l] = if outer { c(qs1 - f) + off } else { out[9][l] };
+ out[6][l] = if outer { c(ps1 + f) + off } else { out[6][l] };
+ }
+ }
+ // Wide filter (8.8.5.3) with 8 taps for flat lanes (p2..q2) ...
+ if any_flat {
+ let w8 = wide_filter::<3>(&v);
+ for k in 5..11 {
+ for l in 0..LANES {
+ if flat[l] && !flat2[l] {
+ out[k][l] = w8[k][l];
+ }
+ }
+ }
+ }
+ // ... and 16 taps for flat2 lanes (p6..q6).
+ if any_flat2 {
+ let w16 = wide_filter::<4>(&v);
+ for k in 1..15 {
+ for l in 0..LANES {
+ if flat2[l] {
+ out[k][l] = w16[k][l];
+ }
+ }
+ }
+ }
+ let (lo, hi) = if any_flat2 {
+ (1, 15)
+ } else if any_flat {
+ (5, 11)
+ } else {
+ (6, 10)
+ };
+ if ROWS {
+ for k in lo..hi {
+ let o = start + (k + R - 8) * step; // k >= 8 - R
+ let row: &mut [u16; LANES] = (&mut d[o..o + LANES]).try_into().expect("lanes");
+ for l in 0..LANES {
+ row[l] = out[k][l] as u16;
+ }
+ }
+ } else {
+ // Whole lines: unmodified samples are rewritten with their own value.
+ for l in 0..LANES {
+ let s = start + l * along;
+ let line: &mut [u16] = &mut d[s..s + 2 * R];
+ for k in 0..2 * R {
+ line[k] = out[8 - R + k][l] as u16;
+ }
+ }
+ }
+ }
+
+ /// Wide filter process (8.8.5.3) with 2^LOG2 taps on gathered lanes (positions 8 - 2^(LOG2-1)
+ /// .. 8 + 2^(LOG2-1) - 2 are produced); the sum over j of the specification is computed as a
+ /// sliding window over the clamped indices (identical results).
+ #[inline(always)]
+ fn wide_filter<const LOG2: u32>(v: &[[T; LANES]; 16]) -> [[T; LANES]; 16] {
+ let n = (1isize << (LOG2 - 1)) - 1;
+ let s = |k: isize| &v[(k.clamp(-(n + 1), n) + 8) as usize];
+ let mut out = [[0 as T; LANES]; 16];
+ let mut sum = [0 as T; LANES];
+ for j in -n..=n {
+ let a = s(-n + j);
+ for l in 0..LANES {
+ sum[l] += a[l];
+ }
+ }
+ let round: T = 1 << (LOG2 - 1);
+ for i in -n..n {
+ let (cur, add, sub) = (s(i), s(i + 1 + n), s(i - n));
+ let o = &mut out[(i + 8) as usize];
+ for l in 0..LANES {
+ o[l] = (sum[l] + cur[l] + round) >> LOG2;
+ sum[l] += add[l] - sub[l];
+ }
+ }
+ out
+ }
+ }
+ };
}
+group_filter!(lanes16, i16);
+group_filter!(lanes32, i32);
diff --git a/crates/vp9/src/tile.rs b/crates/vp9/src/tile.rs
index bf117672a..0c2ca02b5 100644
--- a/crates/vp9/src/tile.rs
+++ b/crates/vp9/src/tile.rs
@@ -34,6 +34,7 @@ pub struct FrameShared<'a> {
pub seg_q: [[[i32; 2]; 2]; 8],
/// Whether syntax elements need to be counted (backward adaptation enabled).
pub counting: bool,
+ pub pools: &'a crate::frame::Pools,
}
/// Output of one tile column: samples, mode info and segment ids of its columns.
@@ -112,6 +113,7 @@ pub struct TileDecoder<'a> {
pred: Vec<u16>,
pred2: Vec<u16>,
mc_tmp: Vec<u16>,
+ mc_win: Vec<u16>,
/// First error met while decoding (e.g. a block referencing an unusable reference frame).
pub error: Option<crate::error::Error>,
}
@@ -126,12 +128,13 @@ impl<'a> TileDecoder<'a> {
let strip_w = (mi_col_end - mi_col_start).div_ceil(8) * 64;
let strip_h = sb_rows * 64;
let x0 = mi_col_start * 8;
- let planes = [vec![0u16; strip_w * strip_h], vec![0u16; (strip_w >> ss_x) * (strip_h >> ss_y)], vec![0u16; (strip_w >> ss_x) * (strip_h >> ss_y)]];
+ let uv_len = (strip_w >> ss_x) * (strip_h >> ss_y);
+ let planes = [s.pools.samples.take(strip_w * strip_h, 0), s.pools.samples.take(uv_len, 0), s.pools.samples.take(uv_len, 0)];
let mi_w = mi_col_end - mi_col_start;
let strip = Strip {
mi_col_start,
mi_col_end,
- mi: vec![MiInfo::default(); mi_w * mi_rows],
+ mi: s.pools.mi.take(mi_w * mi_rows, MiInfo::default()),
seg_ids: vec![0; mi_w * mi_rows],
planes,
strides: [strip_w, strip_w >> ss_x, strip_w >> ss_x],
@@ -170,7 +173,9 @@ impl<'a> TileDecoder<'a> {
token_cache: vec![0; 1024],
pred: vec![0; 64 * 64],
pred2: vec![0; 64 * 64],
- mc_tmp: vec![0; 64 * (64 * 5 + 16)],
+ // Scaled prediction reads up to 5x the block height (8.5.2.3), unscaled h + 7 rows.
+ mc_tmp: vec![0; if s.refs.iter().flatten().any(|r| r.x_scale != 1 << 14 || r.y_scale != 1 << 14) { 64 * (64 * 5 + 16) } else { 64 * 71 }],
+ mc_win: vec![0; 71 * 71],
error: None,
}
}
diff --git a/crates/vp9/src/tile/recon.rs b/crates/vp9/src/tile/recon.rs
index dc52b99f5..4ab72118b 100644
--- a/crates/vp9/src/tile/recon.rs
+++ b/crates/vp9/src/tile/recon.rs
@@ -317,7 +317,7 @@ impl<'a> TileDecoder<'a> {
last_y: ((f.height as i32 + sy as i32) >> sy) - 1,
};
let out = if rl == 0 { &mut self.pred } else { &mut self.pred2 };
- inter::predict(&rp, start_x, start_y, step_x, step_y, w, h, b.interp_filter, self.bit_depth, out, &mut self.mc_tmp);
+ inter::predict(&rp, start_x, start_y, step_x, step_y, w, h, b.interp_filter, self.bit_depth, out, &mut self.mc_tmp, &mut self.mc_win);
}
let (stride, x_off) = (self.strip.strides[plane], self.strip.x_off[plane]);
let dst = &mut self.strip.planes[plane];
diff --git a/crates/vp9/src/transform.rs b/crates/vp9/src/transform.rs
index 3792a81b6..f0daf1fd5 100644
--- a/crates/vp9/src/transform.rs
+++ b/crates/vp9/src/transform.rs
@@ -167,54 +167,77 @@ pub fn inverse_transform_add(coefs: &[i32], tx_size: u8, tx_type: u8, lossless:
}
let row_adst = matches!(tx_type, DCT_ADST | ADST_ADST);
let col_adst = matches!(tx_type, ADST_DCT | ADST_ADST);
- if bit_depth == 8 {
- let lim = 1 << 24;
- let mut t = [0i32; 1024];
- for i in 0..rows.min(n) {
- let row = &mut t[i * n..i * n + n];
- for (d, s) in row.iter_mut().zip(&coefs[i * n..i * n + n]) {
- *d = sat(*s, lim);
- }
- tx1d_narrow(row, n, row_adst);
- for v in row.iter_mut() {
- *v = sat(*v, lim);
- }
+ let p = TxParams { row_adst, col_adst, rows, shift, round, max };
+ match (tx_size, bit_depth == 8) {
+ (0, true) => itx_narrow::<4>(coefs, &p, dst, stride),
+ (1, true) => itx_narrow::<8>(coefs, &p, dst, stride),
+ (2, true) => itx_narrow::<16>(coefs, &p, dst, stride),
+ (_, true) => itx_narrow::<32>(coefs, &p, dst, stride),
+ (0, false) => itx_wide::<4>(coefs, &p, dst, stride),
+ (1, false) => itx_wide::<8>(coefs, &p, dst, stride),
+ (2, false) => itx_wide::<16>(coefs, &p, dst, stride),
+ (_, false) => itx_wide::<32>(coefs, &p, dst, stride),
+ }
+}
+
+struct TxParams {
+ row_adst: bool,
+ col_adst: bool,
+ rows: usize,
+ shift: u32,
+ round: i32,
+ max: i32,
+}
+
+/// 2D inverse transform of size N with 32-bit intermediates (8-bit streams).
+fn itx_narrow<const N: usize>(coefs: &[i32], p: &TxParams, dst: &mut [u16], stride: usize) {
+ let lim = 1 << 24;
+ let mut t = [[0i32; N]; N];
+ for (i, row) in t.iter_mut().enumerate().take(p.rows.min(N)) {
+ for (d, s) in row.iter_mut().zip(&coefs[i * N..i * N + N]) {
+ *d = sat(*s, lim);
}
- let mut col = [0i32; 32];
- for j in 0..n {
- for i in 0..n {
- col[i] = t[i * n + j];
- }
- tx1d_narrow(&mut col[..n], n, col_adst);
- for i in 0..n {
- let p = &mut dst[i * stride + j];
- *p = (*p as i32 + (col[i].wrapping_add(round) >> shift).clamp(-(1 << 20), 1 << 20)).clamp(0, max) as u16;
- }
+ tx1d_narrow(row, N, p.row_adst);
+ for v in row.iter_mut() {
+ *v = sat(*v, lim);
}
- } else {
- let lim = 1i64 << 40;
- let mut t = [0i64; 1024];
- for i in 0..rows.min(n) {
- let row = &mut t[i * n..i * n + n];
- for (d, s) in row.iter_mut().zip(&coefs[i * n..i * n + n]) {
- *d = *s as i64;
- }
- tx1d_wide(row, n, row_adst);
- for v in row.iter_mut() {
- *v = (*v).clamp(-lim, lim);
- }
+ }
+ let mut col = [0i32; N];
+ for j in 0..N {
+ for i in 0..N {
+ col[i] = t[i][j];
}
- let mut col = [0i64; 32];
- for j in 0..n {
- for i in 0..n {
- col[i] = t[i * n + j];
- }
- tx1d_wide(&mut col[..n], n, col_adst);
- for i in 0..n {
- let p = &mut dst[i * stride + j];
- let r = ((col[i].clamp(-lim, lim) + round as i64) >> shift).clamp(-(1 << 30), 1 << 30) as i32;
- *p = (*p as i32 + r).clamp(0, max) as u16;
- }
+ tx1d_narrow(&mut col, N, p.col_adst);
+ for i in 0..N {
+ let d = &mut dst[i * stride + j];
+ *d = (*d as i32 + (col[i].wrapping_add(p.round) >> p.shift).clamp(-(1 << 20), 1 << 20)).clamp(0, p.max) as u16;
+ }
+ }
+}
+
+/// 2D inverse transform of size N with 64-bit intermediates (high bit depth).
+fn itx_wide<const N: usize>(coefs: &[i32], p: &TxParams, dst: &mut [u16], stride: usize) {
+ let lim = 1i64 << 40;
+ let mut t = [[0i64; N]; N];
+ for (i, row) in t.iter_mut().enumerate().take(p.rows.min(N)) {
+ for (d, s) in row.iter_mut().zip(&coefs[i * N..i * N + N]) {
+ *d = *s as i64;
+ }
+ tx1d_wide(row, N, p.row_adst);
+ for v in row.iter_mut() {
+ *v = (*v).clamp(-lim, lim);
+ }
+ }
+ let mut col = [0i64; N];
+ for j in 0..N {
+ for i in 0..N {
+ col[i] = t[i][j];
+ }
+ tx1d_wide(&mut col, N, p.col_adst);
+ for i in 0..N {
+ let d = &mut dst[i * stride + j];
+ let r = ((col[i].clamp(-lim, lim) + p.round as i64) >> p.shift).clamp(-(1 << 30), 1 << 30) as i32;
+ *d = (*d as i32 + r).clamp(0, p.max) as u16;
}
}
}
diff --git a/crates/vp9/tests/common/mod.rs b/crates/vp9/tests/common/mod.rs
index 1eed03afc..fad515e9d 100644
--- a/crates/vp9/tests/common/mod.rs
+++ b/crates/vp9/tests/common/mod.rs
@@ -153,6 +153,14 @@ pub fn fixtures_dir() -> PathBuf {
d
}
+/// Unique suffix for temporary files: tests run on several threads of one process and may
+/// generate the same fixture concurrently.
+pub fn unique() -> String {
+ static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ format!("{}-{n}", std::process::id())
+}
+
pub fn run(cmd: &mut Command) -> bool {
match cmd.output() {
Ok(o) if o.status.success() => true,
@@ -185,14 +193,14 @@ pub fn format_info(pix_fmt: &str) -> (usize, u32, u32) {
/// Reference decode of `ivf` with ffmpeg (native vp9 decoder, every frame, no fps conversion).
pub fn reference_decode(ivf: &Path, yuv: &Path, pix_fmt: &str) -> bool {
let Some(ff) = ffmpeg() else { return false };
- let tmp = yuv.with_extension(format!("tmp.{}.yuv", std::process::id()));
+ let tmp = yuv.with_extension(format!("tmp.{}.yuv", unique()));
let mut c = Command::new(&ff);
c.args(["-hide_banner", "-loglevel", "error", "-y", "-c:v", "vp9", "-i"]).arg(ivf);
c.args(["-fps_mode", "passthrough", "-noautoscale", "-f", "rawvideo", "-pix_fmt", pix_fmt]).arg(&tmp);
if !run(&mut c) {
return false;
}
- std::fs::rename(&tmp, yuv).is_ok()
+ std::fs::rename(&tmp, yuv).is_ok() || yuv.exists()
}
/// Generate (if needed) the fixture stream and its ffmpeg reference decode.
@@ -205,7 +213,7 @@ pub fn ensure(f: &Fixture) -> Option<(PathBuf, PathBuf)> {
let ivf = dir.join(format!("{}.ivf", f.name));
let yuv = dir.join(format!("{}.yuv", f.name));
if !ivf.exists() {
- let tmp = dir.join(format!("{}.tmp.{}.ivf", f.name, std::process::id()));
+ let tmp = dir.join(format!("{}.tmp.{}.ivf", f.name, unique()));
let mut vf = format!("{}=size={}x{}:rate=25,format={}", f.source, f.width, f.height, f.pix_fmt);
if !f.filter.is_empty() {
vf.push(',');
@@ -213,7 +221,7 @@ pub fn ensure(f: &Fixture) -> Option<(PathBuf, PathBuf)> {
}
let two_pass = f.args.first() == Some(&"2pass");
let args: Vec<&str> = f.args.iter().copied().filter(|a| *a != "2pass").collect();
- let log = dir.join(format!("{}.{}.passlog", f.name, std::process::id()));
+ let log = dir.join(format!("{}.{}.passlog", f.name, unique()));
let enc = |pass: Option<u32>, out: &Path| {
let mut c = Command::new(&ff);
c.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", &vf]);
@@ -240,7 +248,9 @@ pub fn ensure(f: &Fixture) -> Option<(PathBuf, PathBuf)> {
return None;
}
let _ = std::fs::remove_file(format!("{}-0.log", log.display()));
- std::fs::rename(&tmp, &ivf).unwrap();
+ if std::fs::rename(&tmp, &ivf).is_err() && !ivf.exists() {
+ panic!("could not store fixture {}", ivf.display());
+ }
}
if !yuv.exists() {
assert!(reference_decode(&ivf, &yuv, f.pix_fmt), "reference decode failed for {}", f.name);