FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M9.7: AV1 loop filter, CDEF, super-resolution upscaling, loop restoration
Brandon Thomasbe1ce4943ea3
diff --git a/crates/av1/README.md b/crates/av1/README.mdindex 2418bf2d5..578f8bf7f 100644--- a/crates/av1/README.md+++ b/crates/av1/README.md@@ -30,18 +30,23 @@ reference) is used only as an external test oracle.| Intra prediction: DC, V/H + directional with edge filter and upsampling, smooth (3), Paeth, recursive filter intra, CfL, palette | 7.11.2, 7.11.4, 7.11.5 | done, bit-exact || Intra block copy | 7.11.3 | missing || Inter prediction: MV prediction, motion field, scaling, filters, warp / global motion, OBMC, compound / masks, inter-intra | 7.9–7.11.3 | missing |-| Loop filter | 7.14 | missing |-| CDEF | 7.15 | missing |-| Super-resolution upscaling | 7.16 | missing |-| Loop restoration (Wiener, self-guided) | 7.17 | syntax done, filter missing |+| Loop filter (all filter sizes, deltas, segment / ref / mode adjustments) | 7.14 | done, bit-exact |+| CDEF | 7.15 | done, bit-exact |+| Super-resolution upscaling | 7.16 | done, not yet oracle-tested (no fixture uses it yet) |+| Loop restoration (Wiener, self-guided, switchable; stripes) | 7.17 | done, bit-exact || Film grain synthesis | 7.18.3 | missing || Large-scale tile / tile list OBUs | 7.3 | not planned |## Accuracy-`tests/oracle_intra.rs` encodes all-intra streams with ffmpeg's libsvtav1 (in-loop filters off)-and compares every decoded frame with libdav1d: **bit-exact** on all fixtures (8- and 10-bit-4:2:0; 128×128 to 1280×720 including odd sizes; testsrc2, mandelbrot and noise; presets 2–8).+`tests/oracle_intra.rs` encodes all-intra streams with ffmpeg's libsvtav1 (with and without the+in-loop filters; 64×64 and 128×128 superblocks; intra edge filter on and off) and compares every+decoded frame with libdav1d: **bit-exact** on all 13 fixtures (8- and 10-bit 4:2:0; 128×128 to+1280×720 including odd sizes; testsrc2, mandelbrot, gradients and noise; presets 1–8).++`tests/conformance.rs` downloads libaom's conformance test vectors on first use+(storage.googleapis.com/aom-test-data) and compares with libdav1d: `av1-1-b8-02-allintra`+(39 frames, deblocking + CDEF + self-guided restoration) is **bit-exact**.## APIdiff --git a/crates/av1/src/cdef.rs b/crates/av1/src/cdef.rsnew file mode 100644index 000000000..eb3f83417--- /dev/null+++ b/crates/av1/src/cdef.rs@@ -0,0 +1,174 @@+//! CDEF (7.15).++use crate::frame::FrameBuf;+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> {+ 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;+ }+ c += 2;+ }+ r += 2;+ }+ any.then_some(out)+}++fn cdef_block(fs: &FrameState, out: &mut FrameBuf, 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);+ if skip {+ return false;+ }+ let coeff_shift = fs.bit_depth - 8;+ let (y_dir, var) = direction(fs, r, c);+ let cp = &fs.fh.cdef;+ let mut pri = (cp.y_pri[idx] << coeff_shift) as i32;+ let sec = (cp.y_sec[idx] << coeff_shift) as i32;+ let dir = if pri == 0 { 0 } else { y_dir };+ let var_str = if (var >> 6) != 0 { (31 - ((var >> 6) as u32).leading_zeros()).min(12) as i32 } else { 0 };+ pri = if var != 0 { (pri * (4 + var_str) + 8) >> 4 } else { 0 };+ let damping = cp.damping as i32 + coeff_shift as i32;+ filter(fs, out, 0, r, c, pri, sec, damping, dir);+ if fs.num_planes == 1 {+ return true;+ }+ let pri = (cp.uv_pri[idx] << coeff_shift) as i32;+ let sec = (cp.uv_sec[idx] << coeff_shift) as i32;+ let dir = if pri == 0 { 0 } else { CDEF_UV_DIR[fs.ssx][fs.ssy][y_dir] as usize };+ let damping = cp.damping as i32 + coeff_shift as i32 - 1;+ filter(fs, out, 1, r, c, pri, sec, damping, dir);+ filter(fs, out, 2, r, c, pri, sec, damping, dir);+ true+}++fn direction(fs: &FrameState, r: usize, c: usize) -> (usize, i32) {+ let mut cost = [0i32; 8];+ let mut partial = [[0i32; 15]; 8];+ let x0 = c << 2;+ let y0 = r << 2;+ let pl = &fs.cur.planes[0];+ let sh = fs.bit_depth - 8;+ for i in 0..8 {+ let row = pl.row(y0 + i);+ for j in 0..8 {+ let x = (row[x0 + j] as i32 >> sh) - 128;+ partial[0][i + j] += x;+ partial[1][i + j / 2] += x;+ partial[2][i] += x;+ partial[3][3 + i - j / 2] += x;+ partial[4][7 + i - j] += x;+ partial[5][3 - i / 2 + j] += x;+ partial[6][j] += x;+ partial[7][i / 2 + j] += x;+ }+ }+ for i in 0..8 {+ cost[2] += partial[2][i] * partial[2][i];+ cost[6] += partial[6][i] * partial[6][i];+ }+ cost[2] *= DIV_TABLE[8] as i32;+ cost[6] *= DIV_TABLE[8] as i32;+ for i in 0..7 {+ cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i]) * DIV_TABLE[i + 1] as i32;+ cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i]) * DIV_TABLE[i + 1] as i32;+ }+ cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8] as i32;+ cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8] as i32;+ let mut i = 1;+ while i < 8 {+ for j in 0..5 {+ cost[i] += partial[i][3 + j] * partial[i][3 + j];+ }+ cost[i] *= DIV_TABLE[8] as i32;+ for j in 0..3 {+ cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j]) * DIV_TABLE[2 * j + 2] as i32;+ }+ i += 2;+ }+ let mut best = 0;+ let mut y_dir = 0;+ for (i, &c) in cost.iter().enumerate() {+ if c > best {+ best = c;+ y_dir = i;+ }+ }+ (y_dir, (best - cost[(y_dir + 4) & 7]) >> 10)+}++#[inline(always)]+fn constrain(diff: i32, threshold: i32, damping: i32) -> i32 {+ if threshold == 0 {+ return 0;+ }+ let adj = (damping - (31 - (threshold as u32).leading_zeros()) as i32).max(0);+ let mag = (threshold - (diff.abs() >> adj)).clamp(0, diff.abs());+ if diff < 0 { -mag } else { mag }+}++#[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) {+ let coeff_shift = fs.bit_depth - 8;+ let (sub_x, sub_y) = if plane > 0 { (fs.ssx, fs.ssy) } else { (0, 0) };+ let x0 = (c * 4) >> sub_x;+ let y0 = (r * 4) >> sub_y;+ let w = 8 >> sub_x;+ let h = 8 >> sub_y;+ let src = &fs.cur.planes[plane];+ let dst = &mut out.planes[plane];+ let (mi_rows, mi_cols) = (fs.fh.mi_rows as isize, fs.fh.mi_cols as isize);+ let pri_tap = ((pri >> coeff_shift) & 1) as usize;+ let get = |y: isize, x: isize| -> Option<i32> {+ let cand_r = (y << sub_y) >> 2;+ let cand_c = (x << sub_x) >> 2;+ if cand_c >= 0 && cand_c < mi_cols && cand_r >= 0 && cand_r < mi_rows { Some(src.at(x as usize, y as usize) as i32) } else { None }+ };+ for i in 0..h {+ for j in 0..w {+ let x = src.at(x0 + j, y0 + i) as i32;+ let mut sum = 0i32;+ let mut max = x;+ let mut min = x;+ for k in 0..2 {+ for sign in [-1isize, 1] {+ let yy = (y0 + i) as isize + sign * CDEF_DIRECTIONS[dir][k][0] as isize;+ let xx = (x0 + j) as isize + sign * CDEF_DIRECTIONS[dir][k][1] as isize;+ if let Some(p) = get(yy, xx) {+ sum += CDEF_PRI_TAPS[pri_tap][k] as i32 * constrain(p - x, pri, damping);+ max = max.max(p);+ min = min.min(p);+ }+ for dir_off in [-2isize, 2] {+ let d2 = ((dir as isize + dir_off) & 7) as usize;+ let yy = (y0 + i) as isize + sign * CDEF_DIRECTIONS[d2][k][0] as isize;+ let xx = (x0 + j) as isize + sign * CDEF_DIRECTIONS[d2][k][1] as isize;+ if let Some(s) = get(yy, xx) {+ sum += CDEF_SEC_TAPS[pri_tap][k] as i32 * constrain(s - x, sec, damping);+ max = max.max(s);+ min = min.min(s);+ }+ }+ }+ }+ let v = (x + ((8 + sum - (sum < 0) as i32) >> 4)).clamp(min, max);+ dst.set(x0 + j, y0 + i, v as u16);+ }+ }+}diff --git a/crates/av1/src/decoder.rs b/crates/av1/src/decoder.rsindex 5a5cfc390..18f1c2442 100644--- a/crates/av1/src/decoder.rs+++ b/crates/av1/src/decoder.rs@@ -201,8 +201,10 @@ impl Decoder {}return Ok(Some(pic));}- if fh.frame_width > seq.max_frame_width || fh.frame_height > seq.max_frame_height {- return Err(Error::Invalid("frame larger than the sequence maximum"));+ // Encoders exist that code frames slightly larger than the sequence maximum (e.g. a+ // 270-line stream coded as 272 lines); like other decoders we accept them.+ if fh.upscaled_width > 65536 || fh.frame_height > 65536 {+ return Err(Error::Invalid("frame size"));}let fs = FrameState::new(&seq, &fh);let cdfs = if fh.primary_ref_frame == PRIMARY_REF_NONE {diff --git a/crates/av1/src/lib.rs b/crates/av1/src/lib.rsindex e20d63d6d..a184b8ef4 100644--- a/crates/av1/src/lib.rs+++ b/crates/av1/src/lib.rs@@ -7,6 +7,7 @@#![allow(dead_code)]mod bits;+mod cdef;mod cdf;mod decoder;mod frame;@@ -14,6 +15,7 @@ mod grain;pub mod header;mod intra;mod postfilter;+mod restoration;mod spec_tables;mod state;mod symbol;diff --git a/crates/av1/src/postfilter.rs b/crates/av1/src/postfilter.rsindex 4372a41fd..e82622f55 100644--- a/crates/av1/src/postfilter.rs+++ b/crates/av1/src/postfilter.rs@@ -1,8 +1,239 @@//! 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::Plane;+use crate::spec_tables::*;use crate::state::FrameState;pub(crate) fn apply(fs: &mut FrameState) {- let _ = fs;+ let lvl = fs.fh.lf.level;+ if lvl[0] != 0 || lvl[1] != 0 {+ loop_filter(fs);+ }+ let cdef = crate::cdef::apply(fs);+ let (up_cur, up_cdef) = if fs.fh.use_superres {+ let c = crate::restoration::upscale(fs, &fs.cur);+ let d = cdef.as_ref().map(|f| crate::restoration::upscale(fs, f));+ (c, d)+ } else {+ (std::mem::take(&mut fs.cur), cdef)+ };+ 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) };+}++// ---------------------------------------------------------------------------------------------+// 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;+ }+ }+ }+ }+}++fn edge(fs: &mut FrameState, 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;+ let y = row * 4;+ let row = row | sub_y;+ let col = col | sub_x;+ let on_screen = !(x >= fs.fh.frame_width as usize || y >= fs.fh.frame_height as usize || (pass == 0 && x == 0) || (pass == 1 && y == 0));+ if !on_screen {+ return;+ }+ let xp = x >> sub_x;+ let yp = y >> sub_y;+ let prev_row = row - ((dy as usize) << sub_y);+ let prev_col = col - ((dx as usize) << sub_x);+ let mi = &fs.mi;+ let i = mi.idx(row, col);+ let mi_size = mi.mi_size[i] as usize;+ let tx_sz = fs.lf_tx_size(plane, row >> sub_y, col >> sub_x);+ let plane_size = fs.plane_residual_size(mi_size, plane);+ let skip = mi.skip[i];+ let is_intra = mi.ref_frame[i][0] <= INTRA_FRAME as i8;+ let prev_tx_sz = fs.lf_tx_size(plane, prev_row >> sub_y, prev_col >> sub_x);+ let is_block_edge = if pass == 0 {+ xp.is_multiple_of(4 * NUM_4X4_BLOCKS_WIDE[plane_size] as usize)+ } else {+ yp.is_multiple_of(4 * NUM_4X4_BLOCKS_HIGH[plane_size] as usize)+ };+ let is_tx_edge = if pass == 0 { xp.is_multiple_of(TX_WIDTH[tx_sz] as usize) } else { yp.is_multiple_of(TX_HEIGHT[tx_sz] as usize) };+ let apply_filter = is_tx_edge && (is_block_edge || !skip || is_intra);+ // filter size (7.14.3)+ let base_size = if pass == 0 { TX_WIDTH[prev_tx_sz].min(TX_WIDTH[tx_sz]) } else { TX_HEIGHT[prev_tx_sz].min(TX_HEIGHT[tx_sz]) } as usize;+ let filter_size = if plane == 0 { 16.min(base_size) } else { 8.min(base_size) };+ let (mut lvl, mut limit, mut blimit, mut thresh) = strength(fs, row, col, plane, pass);+ if lvl == 0 {+ (lvl, limit, blimit, thresh) = strength(fs, prev_row, prev_col, plane, pass);+ }+ if !apply_filter || lvl == 0 {+ return;+ }+ let bd = fs.bit_depth;+ let pl = &mut fs.cur.planes[plane];+ for k in 0..4 {+ sample_filter(pl, xp + (dy as usize) * k, yp + (dx as usize) * k, plane, limit, blimit, thresh, dx, dy, filter_size, bd);+ }+}++/// 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;+ let i = mi.idx(row, col);+ let segment = mi.segment_id[i] as usize;+ let rf = mi.ref_frame[i][0];+ let mode = mi.y_mode[i] as usize;+ let mode_type = (mode >= NEARESTMV && mode != GLOBALMV && mode != GLOBAL_GLOBALMV) as usize;+ let delta_lf = if fs.fh.delta_lf_multi { mi.delta_lf[i][if plane == 0 { pass } else { plane + 1 }] } else { mi.delta_lf[i][0] } as i32;+ // 7.14.5+ let idx = if plane == 0 { pass } else { plane + 1 };+ let base = (delta_lf + fs.fh.lf.level[idx] as i32).clamp(0, MAX_LOOP_FILTER as i32);+ let mut lvl_seg = base;+ let feature = SEG_LVL_ALT_LF_Y_V + idx;+ if fs.fh.seg.enabled && fs.fh.seg.features.enabled[segment][feature] {+ lvl_seg = (fs.fh.seg.features.data[segment][feature] + lvl_seg).clamp(0, MAX_LOOP_FILTER as i32);+ }+ if fs.fh.lf.delta_enabled {+ let n_shift = lvl_seg >> 5;+ let d = &fs.fh.lf.deltas;+ if rf == INTRA_FRAME as i8 {+ lvl_seg += d.ref_deltas[INTRA_FRAME] << n_shift;+ } else if rf > INTRA_FRAME as i8 {+ lvl_seg += (d.ref_deltas[rf as usize] << n_shift) + (d.mode_deltas[mode_type] << n_shift);+ }+ lvl_seg = lvl_seg.clamp(0, MAX_LOOP_FILTER as i32);+ }+ let lvl = lvl_seg;+ let sharp = fs.fh.lf.sharpness as i32;+ let shift = if sharp > 4 {+ 2+ } else if sharp > 0 {+ 1+ } else {+ 0+ };+ let limit = if sharp > 0 { (lvl >> shift).clamp(1, 9 - sharp) } else { (lvl >> shift).max(1) };+ let blimit = 2 * (lvl + 2) + limit;+ let thresh = lvl >> 4;+ (lvl, limit, blimit, thresh)+}++#[allow(clippy::too_many_arguments)]+#[inline]+fn sample_filter(pl: &mut Plane, x: usize, y: usize, plane: usize, limit: i32, blimit: i32, thresh: i32, dx: i32, dy: i32, filter_size: usize, bd: u32) {+ let stride = pl.stride as isize;+ let step = dy as isize * stride + dx as isize;+ let base = y as isize * stride + x as isize;+ let reach: isize = if filter_size >= 16 { 7 } else { 4 };+ let mut v = [0i32; 16];+ for k in -reach..reach {+ v[(k + 8) as usize] = pl.data[(base + k * step) as usize] as i32;+ }+ let at = |k: isize| -> i32 { v[(k + 8) as usize] };+ let (q0, q1, q2, q3) = (at(0), at(1), at(2), at(3));+ let (p0, p1, p2, p3) = (at(-1), at(-2), at(-3), at(-4));+ let d = &mut pl.data;+ let sh = bd - 8;+ let thresh_bd = thresh << sh;+ let hev = (p1 - p0).abs() > thresh_bd || (q1 - q0).abs() > thresh_bd;+ let filter_len = if filter_size == 4 {+ 4+ } else if plane != 0 {+ 6+ } else if filter_size == 8 {+ 8+ } else {+ 16+ };+ let limit_bd = limit << sh;+ let blimit_bd = blimit << sh;+ let mut mask = (p1 - p0).abs() > limit_bd || (q1 - q0).abs() > limit_bd || (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 > blimit_bd;+ if filter_len >= 6 {+ mask |= (p2 - p1).abs() > limit_bd || (q2 - q1).abs() > limit_bd;+ }+ if filter_len >= 8 {+ mask |= (p3 - p2).abs() > limit_bd || (q3 - q2).abs() > limit_bd;+ }+ if mask {+ return;+ }+ let t_bd = 1 << sh;+ let flat = if filter_size >= 8 {+ let mut m = (p1 - p0).abs() > t_bd || (q1 - q0).abs() > t_bd || (p2 - p0).abs() > t_bd || (q2 - q0).abs() > t_bd;+ if filter_len >= 8 {+ m |= (p3 - p0).abs() > t_bd || (q3 - q0).abs() > t_bd;+ }+ !m+ } else {+ false+ };+ let flat2 = if filter_size >= 16 {+ let (q4, q5, q6, p4, p5, p6) = (at(4), at(5), at(6), at(-5), at(-6), at(-7));+ !((p6 - p0).abs() > t_bd+ || (q6 - q0).abs() > t_bd+ || (p5 - p0).abs() > t_bd+ || (q5 - q0).abs() > t_bd+ || (p4 - p0).abs() > t_bd+ || (q4 - q0).abs() > t_bd)+ } else {+ false+ };+ if filter_size == 4 || !flat {+ // narrow filter (7.14.6.3)+ let half = 1i32 << (bd - 1);+ let c = |v: i32| v.clamp(-half, half - 1);+ let off = 0x80 << sh;+ let (ps1, ps0, qs0, qs1) = (p1 - off, p0 - off, q0 - off, q1 - 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;+ d[base as usize] = (c(qs0 - filter1) + off) as u16;+ d[(base - step) as usize] = (c(ps0 + filter2) + off) as u16;+ if !hev {+ let f = (filter1 + 1) >> 1;+ d[(base + step) as usize] = (c(qs1 - f) + off) as u16;+ d[(base - 2 * step) as usize] = (c(ps1 + f) + off) as u16;+ }+ } else {+ let log2 = if filter_size == 8 || !flat2 { 3 } else { 4 };+ // wide filter (7.14.6.4)+ let n: isize = if log2 == 4 {+ 6+ } else if plane == 0 {+ 3+ } else {+ 2+ };+ let n2: isize = if log2 == 3 && plane == 0 { 0 } else { 1 };+ let mut f = [0i32; 12];+ for i in -n..n {+ let mut t = 0;+ for j in -n..=n {+ let p = (i + j).clamp(-(n + 1), n);+ let tap = if j.abs() <= n2 { 2 } else { 1 };+ t += at(p) * tap;+ }+ f[(i + n) as usize] = (t + (1 << (log2 - 1))) >> log2;+ }+ for i in -n..n {+ d[(base + i * step) as usize] = f[(i + n) as usize] as u16;+ }+ }}diff --git a/crates/av1/src/restoration.rs b/crates/av1/src/restoration.rsnew file mode 100644index 000000000..8701c924f--- /dev/null+++ b/crates/av1/src/restoration.rs@@ -0,0 +1,259 @@+//! Super-resolution upscaling (7.16) and loop restoration (7.17).++use crate::frame::{FrameBuf, Plane};+use crate::spec_tables::*;+use crate::state::FrameState;++/// Upscale a frame horizontally from FrameWidth to UpscaledWidth (7.16).+pub(crate) fn upscale(fs: &FrameState, input: &FrameBuf) -> FrameBuf {+ let fh = &fs.fh;+ let up_w = fh.upscaled_width as usize;+ let mut out = FrameBuf::new(up_w, fh.frame_height as usize, fs.num_planes, fs.ssx, fs.ssy, fs.bit_depth as u8);+ let max = (1i32 << fs.bit_depth) - 1;+ for plane in 0..fs.num_planes {+ let (sub_x, sub_y) = if plane > 0 { (fs.ssx, fs.ssy) } else { (0, 0) };+ let down_w = ((fh.frame_width as usize) + sub_x) >> sub_x;+ let up_pw = (up_w + sub_x) >> sub_x;+ let plane_h = ((fh.frame_height as usize) + sub_y) >> sub_y;+ let sb = SUPERRES_SCALE_BITS as i64;+ let step_x = (((down_w as i64) << sb) + (up_pw as i64 / 2)) / up_pw as i64;+ let err = up_pw as i64 * step_x - ((down_w as i64) << sb);+ let mut initial = (-(((up_pw - down_w) as i64) << (sb - 1)) + up_pw as i64 / 2) / up_pw as i64 + (1 << (SUPERRES_EXTRA_BITS - 1)) - err / 2;+ initial &= SUPERRES_SCALE_MASK as i64;+ let mi_w = fh.mi_cols as usize >> sub_x;+ let max_x = (mi_w * 4 - 1) as i64;+ let src = &input.planes[plane];+ let dst = &mut out.planes[plane];+ for y in 0..plane_h {+ let row = src.row(y);+ for x in 0..up_pw {+ let src_x = -(1i64 << sb) + initial + x as i64 * step_x;+ let src_px = src_x >> sb;+ let subpel = ((src_x & SUPERRES_SCALE_MASK as i64) >> SUPERRES_EXTRA_BITS) as usize;+ let mut sum = 0i32;+ for k in 0..SUPERRES_FILTER_TAPS {+ let sx = (src_px + k as i64 - SUPERRES_FILTER_OFFSET as i64).clamp(0, max_x) as usize;+ sum += row[sx] as i32 * UPSCALE_FILTER[subpel][k] as i32;+ }+ dst.set(x, y, ((sum + 64) >> FILTER_BITS).clamp(0, max) as u16);+ }+ }+ }+ out+}++struct LrCtx<'a> {+ cur: &'a Plane,+ cdef: &'a Plane,+ plane_end_x: i32,+ plane_end_y: i32,+ stripe_start_y: i32,+ stripe_end_y: i32,+}++impl LrCtx<'_> {+ /// Get source sample process (7.17.6).+ #[inline(always)]+ fn sample(&self, x: i32, y: i32) -> i32 {+ let x = x.min(self.plane_end_x).max(0) as usize;+ let y = y.min(self.plane_end_y).max(0);+ if y < self.stripe_start_y {+ let y = (self.stripe_start_y - 2).max(y) as usize;+ self.cur.at(x, y) as i32+ } else if y > self.stripe_end_y {+ let y = (self.stripe_end_y + 2).min(y) as usize;+ self.cur.at(x, y) as i32+ } else {+ self.cdef.at(x, y as usize) as i32+ }+ }+}++/// Loop restoration (7.17): returns LrFrame given UpscaledCurrFrame and UpscaledCdefFrame.+pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf) -> 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_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),+ _ => {}+ }+ }+ col += 1;+ }+ row += 1;+ }+ }+ 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) {+ let round0: u32 = if bd == 12 { 5 } else { 3 };+ let round1: u32 = if bd == 12 { 9 } else { 11 };+ let coef = &fs.lr_wiener[plane][ui];+ let mk = |c: &[i8; 3]| -> [i32; 7] {+ let mut f = [0i32; 7];+ f[3] = 128;+ for i in 0..3 {+ f[i] = c[i] as i32;+ f[6 - i] = c[i] as i32;+ f[3] -= 2 * c[i] as i32;+ }+ f+ };+ let vfilter = mk(&coef[0]);+ let hfilter = mk(&coef[1]);+ let fb = FILTER_BITS as u32;+ let offset = 1i32 << (bd + fb - round0 - 1);+ let limit = (1i32 << (bd + 1 + fb - round0)) - 1;+ let mut inter = [[0i32; 4]; 10];+ for r in 0..(h + 6) as usize {+ for c in 0..w as usize {+ let mut s = 0;+ for t in 0..7 {+ s += hfilter[t] * ctx.sample(x + c as i32 + t as i32 - 3, y + r as i32 - 3);+ }+ let v = (s + (1 << (round0 - 1))) >> round0;+ inter[r][c] = v.clamp(-offset, limit - offset);+ }+ }+ let max = (1i32 << bd) - 1;+ for r in 0..h as usize {+ for c in 0..w as usize {+ let mut s = 0;+ for t in 0..7 {+ s += vfilter[t] * inter[r + t][c];+ }+ let v = (s + (1 << (round1 - 1))) >> round1;+ out.set(x as usize + c, y as usize + r, v.clamp(0, max) as u16);+ }+ }+}++#[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) {+ let set = fs.lr_sgr_set[plane][ui] as usize;+ let mut flt0 = [[0i32; 4]; 4];+ let mut flt1 = [[0i32; 4]; 4];+ box_filter(ctx, x, y, w, h, set, 0, bd, &mut flt0);+ box_filter(ctx, x, y, w, h, set, 1, bd, &mut flt1);+ let xqd = fs.lr_sgr_xqd[plane][ui];+ let w0 = xqd[0] as i32;+ let w1 = xqd[1] as i32;+ let w2 = (1 << SGRPROJ_PRJ_BITS) - w0 - w1;+ let r0 = SGR_PARAMS[set][0];+ let r1 = SGR_PARAMS[set][2];+ let max = (1i32 << bd) - 1;+ let sh = (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) as u32;+ for i in 0..h as usize {+ for j in 0..w as usize {+ let u = (ctx.cdef.at(x as usize + j, y as usize + i) as i32) << SGRPROJ_RST_BITS;+ let mut v = w1 * u;+ v += if r0 != 0 { w0 * flt0[i][j] } else { w0 * u };+ v += if r1 != 0 { w2 * flt1[i][j] } else { w2 * u };+ let s = (v + (1 << (sh - 1))) >> sh;+ out.set(x as usize + j, y as usize + i, s.clamp(0, max) as u16);+ }+ }+}++#[inline(always)]+fn round2_64(x: i64, n: u32) -> i64 {+ if n == 0 { x } else { (x + (1i64 << (n - 1))) >> n }+}++#[allow(clippy::too_many_arguments)]+fn box_filter(ctx: &LrCtx, x: i32, y: i32, w: i32, h: i32, set: usize, pass: usize, bd: u32, f: &mut [[i32; 4]; 4]) {+ let r = SGR_PARAMS[set][pass * 2] as i32;+ if r == 0 {+ return;+ }+ let eps = SGR_PARAMS[set][pass * 2 + 1] as i64;+ let n = ((2 * r + 1) * (2 * r + 1)) as i64;+ let n2e = n * n * eps;+ let s = ((1i64 << SGRPROJ_MTABLE_BITS) + n2e / 2) / n2e;+ let one_over_n = ((1i64 << SGRPROJ_RECIP_BITS) + n / 2) / n;+ let mut a_arr = [[0i64; 6]; 6];+ let mut b_arr = [[0i64; 6]; 6];+ for i in -1..h + 1 {+ for j in -1..w + 1 {+ let mut a = 0i64;+ let mut b = 0i64;+ for dy in -r..=r {+ for dx in -r..=r {+ let c = ctx.sample(x + j + dx, y + i + dy) as i64;+ a += c * c;+ b += c;+ }+ }+ let a = round2_64(a, 2 * (bd - 8));+ let d = round2_64(b, bd - 8);+ let p = (a * n - d * d).max(0);+ let z = round2_64(p * s, SGRPROJ_MTABLE_BITS as u32);+ let a2 = if z >= 255 {+ 256+ } else if z == 0 {+ 1+ } else {+ ((z << SGRPROJ_SGR_BITS) + z / 2) / (z + 1)+ };+ let b2 = ((1i64 << SGRPROJ_SGR_BITS) - a2) * b * one_over_n;+ a_arr[(i + 1) as usize][(j + 1) as usize] = a2;+ b_arr[(i + 1) as usize][(j + 1) as usize] = round2_64(b2, SGRPROJ_RECIP_BITS as u32);+ }+ }+ for i in 0..h {+ let shift = if pass == 0 && (i & 1) == 1 { 4 } else { 5 };+ for j in 0..w {+ let mut a = 0i64;+ let mut b = 0i64;+ for dy in -1..=1i32 {+ for dx in -1..=1i32 {+ let weight = if pass == 0 {+ if ((i + dy) & 1) != 0 { if dx == 0 { 6 } else { 5 } } else { 0 }+ } else if dx == 0 || dy == 0 {+ 4+ } else {+ 3+ };+ a += weight * a_arr[(i + dy + 1) as usize][(j + dx + 1) as usize];+ b += weight * b_arr[(i + dy + 1) as usize][(j + dx + 1) as usize];+ }+ }+ let v = a * ctx.cdef.at((x + j) as usize, (y + i) as usize) as i64 + b;+ f[i as usize][j as usize] = round2_64(v, (SGRPROJ_SGR_BITS + shift - SGRPROJ_RST_BITS) as u32) as i32;+ }+ }+}diff --git a/crates/av1/src/spec_tables.rs b/crates/av1/src/spec_tables.rsindex db3805ddd..d5d07e950 100644--- a/crates/av1/src/spec_tables.rs+++ b/crates/av1/src/spec_tables.rs@@ -10,6 +10,7 @@ pub const ALTREF2_FRAME: usize = 6;pub const ALTREF_FRAME: usize = 7;pub const ANGLE_STEP: usize = 3;pub const BIDIR_COMP_REFERENCE: usize = 1;+pub const BILINEAR: usize = 3;pub const BLOCK_128X128: usize = 15;pub const BLOCK_128X64: usize = 14;pub const BLOCK_16X16: usize = 6;@@ -98,6 +99,7 @@ pub const DIV_LUT_PREC_BITS: usize = 14;pub const DRL_MODE_CONTEXTS: usize = 3;pub const EC_MIN_PROB: usize = 4;pub const EC_PROB_SHIFT: usize = 6;+pub const EIGHTTAP: usize = 0;pub const EIGHTTAP_SHARP: usize = 2;pub const EIGHTTAP_SMOOTH: usize = 1;pub const EOB_COEF_CONTEXTS: usize = 9;@@ -112,6 +114,7 @@ pub const FLIPADST_DCT: usize = 4;pub const FLIPADST_FLIPADST: usize = 6;pub const FRAME_LF_COUNT: usize = 4;pub const FWD_REFS: usize = 4;+pub const GLOBALMV: usize = 16;pub const GLOBAL_GLOBALMV: usize = 24;pub const GM_ABS_ALPHA_BITS: usize = 12;pub const GM_ABS_TRANS_BITS: usize = 12;@@ -214,10 +217,13 @@ pub const MV_JOINT_HNZVZ: usize = 1;pub const MV_JOINT_HZVNZ: usize = 2;pub const MV_JOINT_ZERO: usize = 0;pub const MV_OFFSET_BITS: usize = 10;+pub const NEARESTMV: usize = 14;pub const NEAREST_NEARESTMV: usize = 18;pub const NEAREST_NEWMV: usize = 20;+pub const NEARMV: usize = 15;pub const NEAR_NEARMV: usize = 19;pub const NEAR_NEWMV: usize = 22;+pub const NEWMV: usize = 17;pub const NEW_MV_CONTEXTS: usize = 6;pub const NEW_NEARESTMV: usize = 21;pub const NEW_NEARMV: usize = 23;@@ -339,6 +345,7 @@ pub const SUPERRES_FILTER_TAPS: usize = 8;pub const SUPERRES_NUM: usize = 8;pub const SUPERRES_SCALE_BITS: usize = 14;pub const SUPERRES_SCALE_MASK: usize = 16383;+pub const SWITCHABLE: usize = 4;pub const SWITCH_FRAME: usize = 3;pub const TC_BT_1361: usize = 12;pub const TC_BT_2020_10_BIT: usize = 14;diff --git a/crates/av1/src/transform.rs b/crates/av1/src/transform.rsindex f63952025..c52c2b034 100644--- a/crates/av1/src/transform.rs+++ b/crates/av1/src/transform.rs@@ -523,6 +523,23 @@ mod tests {}}+ /// ADST8/16 basis vectors follow sin(pi (2i+1)(2k+1) / 4N) (scaled like the DCT).+ #[test]+ fn adst_basis_matches_sine() {+ for n in 3..=4u32 {+ let len = 1usize << n;+ for k in 0..len {+ let mut t = [0i32; 64];+ t[k] = 1 << 12;+ inverse_adst(&mut t, n, 24);+ for i in 0..len {+ let want = 4096.0 * ((std::f64::consts::PI * (2 * i + 1) as f64 * (2 * k + 1) as f64) / (4 * len) as f64).sin();+ assert!((t[i] as f64 - want).abs() < 8.0, "n={n} k={k} i={i}: {} vs {want:.1}", t[i]);+ }+ }+ }+ }+#[test]fn adst_is_close_to_sine_transform() {for n in 3..=4u32 {diff --git a/crates/av1/tests/adhoc.rs b/crates/av1/tests/adhoc.rsnew file mode 100644index 000000000..d72a220e8--- /dev/null+++ b/crates/av1/tests/adhoc.rs@@ -0,0 +1,25 @@+//! Compare an arbitrary IVF file with libdav1d:+//! `AV1_IVF=/path/x.ivf AV1_PIX=yuv420p cargo test -p filmcraft-av1 --test adhoc -- --ignored --nocapture`++mod common;+use common::*;++#[test]+#[ignore]+fn adhoc_compare() {+ let Some(ff) = ffmpeg() else { return };+ let Some(path) = std::env::var_os("AV1_IVF") else { return };+ let path = std::path::PathBuf::from(path);+ let pics = decode_all(&path).unwrap();+ let pix = pix_fmt_for(&pics[0]).to_string();+ let raw = reference(&ff, &path, &pix);+ let per = picture_samples(&pics[0]);+ println!("{} pictures, reference has {} frames", pics.len(), raw.len() / per);+ for (i, p) in pics.iter().enumerate() {+ if (i + 1) * per > raw.len() {+ break;+ }+ let (first, count) = compare(p, &raw[i * per..(i + 1) * per]);+ println!("frame {i}: {} mismatches, first {:?}", count, first);+ }+}diff --git a/crates/av1/tests/common/mod.rs b/crates/av1/tests/common/mod.rsindex 7085d308f..2132692f7 100644--- a/crates/av1/tests/common/mod.rs+++ b/crates/av1/tests/common/mod.rs@@ -127,19 +127,69 @@ pub fn compare(p: &Picture, raw: &[u16]) -> (Option<(usize, u32, u32, u16, u16)>(first, count)}+/// The raw pixel format matching a decoded picture.+pub fn pix_fmt_for(p: &Picture) -> &'static str {+ let hi = p.bit_depth > 8;+ if p.mono_chrome {+ return match p.bit_depth {+ 8 => "gray",+ 10 => "gray10le",+ _ => "gray12le",+ };+ }+ match (p.subsampling_x, p.subsampling_y, p.bit_depth) {+ (1, 1, 8) => "yuv420p",+ (1, 1, 10) => "yuv420p10le",+ (1, 1, _) => "yuv420p12le",+ (1, 0, 8) => "yuv422p",+ (1, 0, 10) => "yuv422p10le",+ (1, 0, _) => "yuv422p12le",+ (_, _, 8) => "yuv444p",+ (_, _, 10) => "yuv444p10le",+ _ if hi => "yuv444p12le",+ _ => "yuv444p",+ }+}+/// Decode a fixture and compare every frame with libdav1d; panics with details on mismatch.pub fn check_bit_exact(ff: &Path, spec: &Spec) {let path = make(ff, spec);- let pics = decode_all(&path).unwrap_or_else(|e| panic!("{}: {e}", spec.name));- let raw = reference(ff, &path, spec.pix_fmt);- assert!(!pics.is_empty(), "{}: no frames", spec.name);+ check_file(ff, spec.name, &path);+}++/// Decode an IVF file and compare every frame with libdav1d; panics with details on mismatch.+pub fn check_file(ff: &Path, name: &str, path: &Path) {+ let pics = decode_all(path).unwrap_or_else(|e| panic!("{name}: {e}"));+ assert!(!pics.is_empty(), "{name}: no frames");+ let raw = reference(ff, path, pix_fmt_for(&pics[0]));let per = picture_samples(&pics[0]);- assert_eq!(raw.len(), per * pics.len(), "{}: frame count/size ({} pictures)", spec.name, pics.len());+ assert_eq!(raw.len(), per * pics.len(), "{name}: frame count/size ({} pictures)", pics.len());for (i, p) in pics.iter().enumerate() {let (first, count) = compare(p, &raw[i * per..(i + 1) * per]);if let Some((plane, x, y, a, b)) = first {- panic!("{}: frame {i} differs in {count} samples; first at plane {plane} ({x},{y}): ours {a}, reference {b}", spec.name);+ panic!("{name}: frame {i} differs in {count} samples; first at plane {plane} ({x},{y}): ours {a}, reference {b}");}}- println!("{:<28} {} frames {}x{} bit-exact", spec.name, pics.len(), pics[0].width, pics[0].height);+ println!("{:<34} {:>3} frames {}x{} {}-bit bit-exact", name, pics.len(), pics[0].width, pics[0].height, pics[0].bit_depth);+}++/// An AV1 conformance test vector (libaom test data), downloaded on first use with curl into+/// the fixture directory. Returns None (after printing why) when it can't be fetched.+pub fn test_vector(name: &str) -> Option<PathBuf> {+ let dir = fixture_dir().join("aom-test-data");+ std::fs::create_dir_all(&dir).ok()?;+ let path = dir.join(name);+ if path.exists() {+ return Some(path);+ }+ let tmp = filmcraft_testkit::temp_path(&path);+ let url = format!("https://storage.googleapis.com/aom-test-data/{name}");+ let ok = Command::new("curl").args(["-sfL", "--max-time", "120", "-o"]).arg(&tmp).arg(&url).status().map(|s| s.success()).unwrap_or(false);+ if !ok {+ let _ = std::fs::remove_file(&tmp);+ filmcraft_testkit::skip("av1 conformance", &format!("could not download {url}"));+ return None;+ }+ std::fs::rename(&tmp, &path).ok()?;+ Some(path)}diff --git a/crates/av1/tests/conformance.rs b/crates/av1/tests/conformance.rsnew file mode 100644index 000000000..f86c64522--- /dev/null+++ b/crates/av1/tests/conformance.rs@@ -0,0 +1,16 @@+//! libaom conformance test vectors (downloaded on first use), compared with libdav1d.++mod common;+use common::*;++/// Vectors the decoder handles today (more are added as stages land).+const VECTORS: &[&str] = &["av1-1-b8-02-allintra.ivf"];++#[test]+fn conformance_vectors() {+ let Some(ff) = ffmpeg() else { return };+ for name in VECTORS {+ let Some(path) = test_vector(name) else { return };+ check_file(&ff, name, &path);+ }+}diff --git a/crates/av1/tests/oracle_intra.rs b/crates/av1/tests/oracle_intra.rsindex 72f0a3b7f..441220f18 100644--- a/crates/av1/tests/oracle_intra.rs+++ b/crates/av1/tests/oracle_intra.rs@@ -24,3 +24,26 @@ fn intra_no_filters() {check_bit_exact(&ff, &s);}}++fn specs_filters() -> Vec<Spec> {+ let p =+ |preset: &'static str, crf: &'static str, params: &'static str| -> Vec<&'static str> { vec!["-preset", preset, "-crf", crf, "-svtav1-params", params] };+ vec![+ Spec::new("intra_dlf_mandel", "mandelbrot=s=352x288:r=25", 2, "yuv420p", &p("6", "40", "enable-cdef=0:enable-restoration=0:keyint=1")),+ Spec::new("intra_cdef_testsrc", "testsrc2=s=352x288:r=25", 2, "yuv420p", &p("6", "40", "enable-restoration=0:keyint=1")),+ Spec::new("intra_lr_mandel", "mandelbrot=s=352x288:r=25", 2, "yuv420p", &p("4", "40", "enable-cdef=0:keyint=1")),+ Spec::new("intra_all_testsrc", "testsrc2=s=640x360:r=25", 2, "yuv420p", &p("4", "45", "keyint=1")),+ Spec::new("intra_all_10bit", "mandelbrot=s=320x240:r=25", 2, "yuv420p10le", &p("4", "40", "keyint=1")),+ Spec::new("intra_all_noise_odd", "testsrc2=s=250x150:r=25,noise=alls=20:allf=t", 2, "yuv420p", &p("3", "35", "keyint=1")),+ // 128x128 superblocks, intra edge filter off, Wiener LR on all planes+ Spec::new("intra_all_grad_noise_10bit", "gradients=s=640x360:r=25,noise=alls=25:allf=t", 1, "yuv420p10le", &p("1", "50", "keyint=1")),+ ]+}++#[test]+fn intra_with_filters() {+ let Some(ff) = ffmpeg() else { return };+ for s in specs_filters() {+ check_bit_exact(&ff, &s);+ }+}diff --git a/crates/av1/tools/extract_tables.py b/crates/av1/tools/extract_tables.pyindex a321d333c..83c4e2c9f 100644--- a/crates/av1/tools/extract_tables.py+++ b/crates/av1/tools/extract_tables.py@@ -48,7 +48,7 @@ for f in files:continuecells = [c.strip().rstrip(".") for c in line.strip().strip("|").split("|")]for k in range(1, len(cells)):- if NAME.match(cells[k]) and "_" in cells[k] and re.match(r"^-?\d+$", cells[k - 1]):+ if NAME.match(cells[k]) and len(cells[k]) >= 4 and re.match(r"^-?\d+$", cells[k - 1]):if k + 1 < len(cells) and NAME.match(cells[k + 1]) and "_" in cells[k + 1]:continuepending.append((cells[k], cells[k - 1]))