FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M9.7: AV1 hot loops: vectorisable MC, CDEF, transforms; faster deblocking and entropy decoding
Brandon Thomas31f8b3dadf62
diff --git a/crates/av1/src/cdef.rs b/crates/av1/src/cdef.rsindex eb3f83417..8acd8b1d9 100644--- a/crates/av1/src/cdef.rs+++ b/crates/av1/src/cdef.rs@@ -1,6 +1,6 @@//! CDEF (7.15).-use crate::frame::FrameBuf;+use crate::frame::{FrameBuf, Plane};use crate::spec_tables::*;use crate::state::FrameState;@@ -113,18 +113,23 @@ fn direction(fs: &FrameState, r: usize, c: usize) -> (usize, i32) {(y_dir, (best - cost[(y_dir + 4) & 7]) >> 10)}+/// Marks a sample outside the frame (CdefAvailable = 0) in the padded block.+const CDEF_NA: i32 = i32::MIN;+/// Padded block: 8x8 plus 2 samples on every side, row stride 12.+const PAD_STRIDE: usize = 12;+#[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);+fn constrain(diff: i32, threshold: i32, adj: u32) -> i32 {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) {+ if pri == 0 && sec == 0 {+ // Every tap contributes 0 and the clamp to [min, max] keeps x: CdefFrame = CurrFrame.+ return;+ }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;@@ -132,43 +137,128 @@ fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, r: usize, c: usize,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> {+ // CdefAvailable per sample: its 4x4 block is inside the frame.+ let mut buf = [CDEF_NA; PAD_STRIDE * PAD_STRIDE];+ let mut all_avail = true;+ for i in 0..h + 4 {+ let y = (y0 + i) as isize - 2;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 }- };+ if y < 0 || cand_r >= mi_rows {+ all_avail = false;+ continue;+ }+ let row = src.row(y as usize);+ for j in 0..w + 4 {+ let x = (x0 + j) as isize - 2;+ let cand_c = (x << sub_x) >> 2;+ if x >= 0 && cand_c < mi_cols {+ buf[i * PAD_STRIDE + j] = row[x as usize] as i32;+ } else {+ all_avail = false;+ }+ }+ }+ let pri_tap = ((pri >> coeff_shift) & 1) as usize;+ let off = |d: usize, k: usize| CDEF_DIRECTIONS[d][k][0] as isize * PAD_STRIDE as isize + CDEF_DIRECTIONS[d][k][1] as isize;+ let pri_off = [off(dir, 0), off(dir, 1)];+ let d_lo = (dir + 6) & 7;+ let d_hi = (dir + 2) & 7;+ let sec_off = [[off(d_lo, 0), off(d_hi, 0)], [off(d_lo, 1), off(d_hi, 1)]];+ let pri_taps = [CDEF_PRI_TAPS[pri_tap][0] as i32, CDEF_PRI_TAPS[pri_tap][1] as i32];+ 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];+ 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];+ let mut n = 0;+ for k in 0..2 {+ for sign in [-1isize, 1] {+ taps[n] = (sign * pri_off[k], pri_taps[k], pri, pri_adj);+ taps[n + 1] = (sign * sec_off[k][0], sec_taps[k], sec, sec_adj);+ taps[n + 2] = (sign * sec_off[k][1], sec_taps[k], sec, sec_adj);+ n += 3;+ }+ }+ let rows = (y0, x0, h);+ match w {+ 8 => filter_rows::<8>(&buf, &taps, dst, rows),+ _ => filter_rows::<4>(&buf, &taps, dst, rows),+ }+ return;+ }for i in 0..h {+ // The centre sample is read even where CdefAvailable is 0 (8x8 blocks straddling an odd+ // MiRows / MiCols edge).+ let srow = &src.row(y0 + i)[x0..x0 + w];+ let drow = &mut dst.row_mut(y0 + i)[x0..x0 + w];for j in 0..w {- let x = src.at(x0 + j, y0 + i) as i32;+ let ci = ((i + 2) * PAD_STRIDE + j + 2) as isize;+ let x = srow[j] 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);+ let p = buf[(ci + sign * pri_off[k]) as usize];+ if p != CDEF_NA {+ if pri != 0 {+ sum += pri_taps[k] * constrain(p - x, pri, pri_adj);+ }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);+ for s in 0..2 {+ let q = buf[(ci + sign * sec_off[k][s]) as usize];+ if q != CDEF_NA {+ if sec != 0 {+ sum += sec_taps[k] * constrain(q - x, sec, sec_adj);+ }+ max = max.max(q);+ min = min.min(q);}}}}- let v = (x + ((8 + sum - (sum < 0) as i32) >> 4)).clamp(min, max);- dst.set(x0 + j, y0 + i, v as u16);+ drow[j] = (x + ((8 + sum - (sum < 0) as i32) >> 4)).clamp(min, max) as u16;+ }+ }+}++/// 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)) {+ let mut b16 = [0i16; PAD_STRIDE * PAD_STRIDE];+ for (d, &s) in b16.iter_mut().zip(buf.iter()) {+ *d = s as i16;+ }+ for i in 0..h {+ let ci = ((i + 2) * PAD_STRIDE + 2) as isize;+ let x: [i16; W] = b16[ci as usize..ci as usize + W].try_into().expect("centre row");+ let (mut sum, mut max, mut min) = ([0i16; W], x, x);+ for &(off, weight, thr, adj) in taps {+ let (weight, thr) = (weight as i16, thr as i16);+ let start = (ci + off) as usize;+ let p: &[i16; W] = b16[start..start + W].try_into().expect("tap row");+ for j in 0..W {+ // constrain(): .max / .min instead of clamp (whose bound check panics), and+ // the sign applied branch-free, so the loop vectorises.+ let d = p[j] - x[j];+ let ad = d.abs();+ let mag = (thr - (ad >> adj)).max(0).min(ad);+ let sign = d >> 15;+ sum[j] += weight * ((mag ^ sign) - sign);+ max[j] = max[j].max(p[j]);+ min[j] = min[j].min(p[j]);+ }+ }+ let drow = &mut dst.row_mut(y0 + i)[x0..x0 + W];+ for j in 0..W {+ let s = sum[j];+ drow[j] = (x[j] + ((8 + s - (s < 0) as i16) >> 4)).max(min[j]).min(max[j]) as u16;}}}diff --git a/crates/av1/src/inter.rs b/crates/av1/src/inter.rsindex cb223ee1e..bbe5da443 100644--- a/crates/av1/src/inter.rs+++ b/crates/av1/src/inter.rs@@ -183,7 +183,8 @@ impl TileDecoder<'_, '_> {if ref_idx < 0 { &self.fs.cur.planes[plane] } else { &self.fs.refs[ref_idx as usize].as_ref().expect("reference frame").buf.planes[plane] }}- /// Block inter prediction process (7.11.3.4) into `pred` (stride PRED_STRIDE).+ /// Block inter prediction process (7.11.3.4) into `pred` (stride PRED_STRIDE); `tmp` holds+ /// the intermediate (horizontally filtered) rows.#[allow(clippy::too_many_arguments)]fn block_inter_prediction(&self,@@ -198,10 +199,10 @@ impl TileDecoder<'_, '_> {filters: [u8; 2],rnd: (u32, u32, u32),pred: &mut [i32],+ tmp: &mut [i32],) {let refp = self.ref_plane(ref_idx, plane);let (last_x, last_y) = self.ref_plane_dims(ref_idx, plane);- let inter_h = ((((h as i32 - 1) * y_step + (1 << SCALE_SUBPEL_BITS) - 1) >> SCALE_SUBPEL_BITS) + 8) as usize;let mut fh = filters[1] as usize;if w <= 4 {if fh == EIGHTTAP || fh == EIGHTTAP_SHARP {@@ -218,7 +219,25 @@ impl TileDecoder<'_, '_> {fv = 5;}}- let mut inter = vec![0i32; inter_h * w];+ let unit = 1 << SCALE_SUBPEL_BITS;+ if x_step == unit && y_step == unit {+ mc_unscaled(+ refp,+ last_x,+ last_y,+ x,+ y,+ w,+ h,+ &SUBPEL_FILTERS[fh][((x >> 6) & SUBPEL_MASK as i32) as usize],+ &SUBPEL_FILTERS[fv][((y >> 6) & SUBPEL_MASK as i32) as usize],+ rnd,+ pred,+ tmp,+ );+ return;+ }+ let inter_h = ((((h as i32 - 1) * y_step + (1 << SCALE_SUBPEL_BITS) - 1) >> SCALE_SUBPEL_BITS) + 8) as usize;for r in 0..inter_h {let ry = ((y >> 10) + r as i32 - 3).clamp(0, last_y) as usize;let row = refp.row(ry);@@ -230,7 +249,7 @@ impl TileDecoder<'_, '_> {for t in 0..8 {s += filt[t] as i32 * row[(bx + t as i32).clamp(0, last_x) as usize] as i32;}- inter[r * w + c] = round2(s, rnd.0);+ tmp[r * w + c] = round2(s, rnd.0);}}for r in 0..h {@@ -240,7 +259,7 @@ impl TileDecoder<'_, '_> {let base = (p >> 10) as usize;let mut s = 0i32;for t in 0..8 {- s += filt[t] as i32 * inter[(base + t) * w + c];+ s += filt[t] as i32 * tmp[(base + t) * w + c];}pred[r * PRED_STRIDE + c] = round2(s, rnd.1);}@@ -383,6 +402,7 @@ impl TileDecoder<'_, '_> {}}let mut preds = [std::mem::take(&mut self.pred_buf[0]), std::mem::take(&mut self.pred_buf[1])];+ let mut tmp = std::mem::take(&mut self.mc_tmp);let fh = &self.fs.fh;for ref_list in 0..1 + is_compound as usize {let ref_frame = cand_refs[ref_list];@@ -409,7 +429,7 @@ impl TileDecoder<'_, '_> {}} else {let (sx, sy, stx, sty) = self.mv_scaling(plane, ref_idx, x as i32, y as i32, mv);- self.block_inter_prediction(plane, ref_idx, sx, sy, stx, sty, w, h, filters, rnd, &mut preds[ref_list]);+ self.block_inter_prediction(plane, ref_idx, sx, sy, stx, sty, w, h, filters, rnd, &mut preds[ref_list], &mut tmp);}}let ct = self.b.compound_type;@@ -480,6 +500,7 @@ impl TileDecoder<'_, '_> {self.mask_blend(&preds, plane, x, y, w, h, rnd.2, max);}self.pred_buf = preds;+ self.mc_tmp = tmp;if self.b.motion_mode as usize == OBMC {self.overlapped_motion_compensation(plane, w, h);}@@ -561,6 +582,7 @@ impl TileDecoder<'_, '_> {let bd = self.fs.bit_depth;let max = (1i32 << bd) - 1;let mut obmc = std::mem::take(&mut self.pred_buf[0]);+ let mut tmp = std::mem::take(&mut self.mc_tmp);let get_mask = |len: usize| -> &'static [u8] {match len {2 => &OBMC_MASK_2,@@ -624,7 +646,7 @@ impl TileDecoder<'_, '_> {let (stx, sty, sxs, sys) = self.mv_scaling(plane, ref_idx, px as i32, py as i32, mv);let filters = self.fs.mi.interp_filter[ci];let rnd = rounding(false, bd);- self.block_inter_prediction(plane, ref_idx, stx, sty, sxs, sys, pw, ph, filters, rnd, &mut obmc);+ self.block_inter_prediction(plane, ref_idx, stx, sty, sxs, sys, pw, ph, filters, rnd, &mut obmc, &mut tmp);let mask = get_mask(if pass == 0 { ph } else { pw });let pl = &mut self.fs.cur.planes[plane];for i in 0..ph {@@ -637,5 +659,89 @@ impl TileDecoder<'_, '_> {}}self.pred_buf[0] = obmc;+ self.mc_tmp = tmp;+ }+}++const IDENTITY_TAPS: [i16; 8] = [0, 0, 0, 128, 0, 0, 0, 0];++/// Block inter prediction without reference scaling: every column / row uses the same filter+/// phase, so the filters run over whole rows (bit-identical to the per-sample process).+#[allow(clippy::too_many_arguments)]+fn mc_unscaled(+ refp: &Plane,+ last_x: i32,+ last_y: i32,+ x: i32,+ y: i32,+ w: usize,+ h: usize,+ hf: &[i16; 8],+ vf: &[i16; 8],+ rnd: (u32, u32, u32),+ pred: &mut [i32],+ tmp: &mut [i32],+) {+ let x0 = (x >> 10) - 3;+ let y0 = (y >> 10) - 3;+ let h_copy = *hf == IDENTITY_TAPS;+ let v_copy = *vf == IDENTITY_TAPS;+ // With the identity vertical phase only intermediate rows 3 .. 3 + h have a non-zero tap.+ let (r_lo, r_hi) = if v_copy { (3, 3 + h) } else { (0, h + 7) };+ let inside = x0 >= 0 && x0 + w as i32 + 7 <= last_x + 1;+ let mut edge = [0u16; 128 + 8];+ let mut acc = [0i32; 128];+ let (r0, r1) = (rnd.0, rnd.1);+ let (half0, half1) = (1i32 << (r0 - 1), 1i32 << (r1 - 1));+ for r in r_lo..r_hi {+ let ry = (y0 + r as i32).clamp(0, last_y) as usize;+ let row = refp.row(ry);+ let src: &[u16] = if inside {+ &row[x0 as usize..x0 as usize + w + 7]+ } else {+ for (k, e) in edge[..w + 7].iter_mut().enumerate() {+ *e = row[(x0 + k as i32).clamp(0, last_x) as usize];+ }+ &edge[..w + 7]+ };+ let out = &mut tmp[r * w..r * w + w];+ if h_copy {+ // Round2(128 * v, InterRound0) is exact.+ for (o, &v) in out.iter_mut().zip(&src[3..3 + w]) {+ *o = (v as i32) << (7 - r0);+ }+ } else {+ let acc = &mut acc[..w];+ acc.fill(0);+ for t in 0..8 {+ let f = hf[t] as i32;+ for (a, &v) in acc.iter_mut().zip(&src[t..t + w]) {+ *a += f * v as i32;+ }+ }+ for (o, &a) in out.iter_mut().zip(acc.iter()) {+ *o = (a + half0) >> r0;+ }+ }+ }+ for r in 0..h {+ let out = &mut pred[r * PRED_STRIDE..r * PRED_STRIDE + w];+ if v_copy {+ for (o, &v) in out.iter_mut().zip(&tmp[(r + 3) * w..(r + 4) * w]) {+ *o = (128 * v + half1) >> r1;+ }+ } else {+ let acc = &mut acc[..w];+ acc.fill(0);+ for t in 0..8 {+ let f = vf[t] as i32;+ for (a, &v) in acc.iter_mut().zip(&tmp[(r + t) * w..(r + t + 1) * w]) {+ *a += f * v;+ }+ }+ for (o, &a) in out.iter_mut().zip(acc.iter()) {+ *o = (a + half1) >> r1;+ }+ }}}diff --git a/crates/av1/src/postfilter.rs b/crates/av1/src/postfilter.rsindex f88f7bfa5..24358c580 100644--- a/crates/av1/src/postfilter.rs+++ b/crates/av1/src/postfilter.rs@@ -1,7 +1,6 @@//! 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;use crate::stats::{DecodeStats, Stage, Timer};@@ -66,21 +65,26 @@ fn edge(fs: &mut FrameState, plane: usize, pass: usize, row: usize, col: usize)let yp = y >> sub_y;let prev_row = row - ((dy as usize) << sub_y);let prev_col = col - ((dx as usize) << sub_x);+ let tx_sz = fs.lf_tx_size(plane, row >> sub_y, col >> sub_x);+ 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) };+ if !is_tx_edge {+ return;+ }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);+ if !(is_block_edge || !skip || is_intra) {+ return;+ }+ let prev_tx_sz = fs.lf_tx_size(plane, prev_row >> sub_y, prev_col >> sub_x);// 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) };@@ -88,13 +92,17 @@ fn edge(fs: &mut FrameState, plane: usize, pass: usize, row: usize, col: usize)if lvl == 0 {(lvl, limit, blimit, thresh) = strength(fs, prev_row, prev_col, plane, pass);}- if !apply_filter || lvl == 0 {+ if lvl == 0 {return;}- let bd = fs.bit_depth;+ 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;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);+ sample_filter(&mut pl.data, base + k * along, step, chroma, filter_size, t);}}@@ -140,106 +148,113 @@ fn strength(fs: &FrameState, row: usize, col: usize, plane: usize, pass: usize)(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;+/// Per-edge thresholds of the sample filter, scaled to the bit depth.+#[derive(Clone, Copy)]+struct LfThresh {+ limit: i32,+ blimit: i32,+ thresh: i32,+ /// Flatness threshold 1 << (BitDepth - 8).+ flat: i32,+ /// 0x80 << (BitDepth - 8) and 1 << (BitDepth - 1).+ off: i32,+ half: i32,+}++impl LfThresh {+ fn new(limit: i32, blimit: i32, thresh: i32, bd: u32) -> LfThresh {+ let sh = bd - 8;+ LfThresh { limit: limit << sh, blimit: blimit << sh, thresh: thresh << sh, flat: 1 << sh, off: 0x80 << sh, half: 1 << (bd - 1) }}- if mask {+}++/// Sample filtering process (7.14.6) for one line across the edge: `base` indexes q0 and+/// `step` is the distance between samples across the edge.+#[allow(clippy::too_many_arguments)]+#[inline(always)]+fn sample_filter(d: &mut [u16], base: usize, step: usize, chroma: bool, filter_size: usize, t: LfThresh) {+ let at = |d: &[u16], k: isize| -> i32 { d[(base as isize + k * step as isize) as usize] as i32 };+ let (q0, q1, p0, p1) = (at(d, 0), at(d, 1), at(d, -1), at(d, -2));+ let lim = t.limit;+ // filter mask (7.14.6.2)+ if (p1 - p0).abs() > lim || (q1 - q0).abs() > lim || (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 > t.blimit {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;+ let hev = (p1 - p0).abs() > t.thresh || (q1 - q0).abs() > t.thresh;+ let mut flat = false;+ if filter_size > 4 {+ let (q2, p2) = (at(d, 2), at(d, -3));+ if (p2 - p1).abs() > lim || (q2 - q1).abs() > lim {+ return;}- !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 {+ let tf = t.flat;+ flat = (p1 - p0).abs() <= tf && (q1 - q0).abs() <= tf && (p2 - p0).abs() <= tf && (q2 - q0).abs() <= tf;+ if !chroma {+ // filterLen >= 8+ let (q3, p3) = (at(d, 3), at(d, -4));+ if (p3 - p2).abs() > lim || (q3 - q2).abs() > lim {+ return;+ }+ flat = flat && (p3 - p0).abs() <= tf && (q3 - q0).abs() <= tf;+ }+ }+ if !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 c = |v: i32| v.clamp(-t.half, t.half - 1);+ let off = t.off;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;+ d[base] = (c(qs0 - filter1) + off) as u16;+ d[base - step] = (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;+ d[base + step] = (c(qs1 - f) + off) as u16;+ d[base - 2 * step] = (c(ps1 + f) + off) as u16;}+ return;+ }+ if chroma {+ wide::<2, 1, 3>(d, base, step);+ } else if filter_size == 8 {+ wide::<3, 0, 3>(d, base, step);} 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;+ let tf = t.flat;+ let q0 = at(d, 0);+ let p0 = at(d, -1);+ let flat2 = (4..7).all(|k| (at(d, k) - q0).abs() <= tf && (at(d, -k - 1) - p0).abs() <= tf);+ if flat2 { wide::<6, 1, 4>(d, base, step) } else { wide::<3, 0, 3>(d, base, step) }+ }+}++/// Wide filter process (7.14.6.4) with n = N, the 2-weight taps |j| <= N2 and log2Size = LOG2.+#[inline(always)]+fn wide<const N: usize, const N2: usize, const LOG2: u32>(d: &mut [u16], base: usize, step: usize) {+ // v[k] = sample at offset k - (N + 1) from q0, k in 0 .. 2N + 2+ let mut v = [0i32; 14];+ let first = base - (N + 1) * step;+ for (k, x) in v[..2 * N + 2].iter_mut().enumerate() {+ *x = d[first + k * step] as i32;+ }+ // e[m] = v[clamp(m - N, 0, 2N + 1)]: the clamped tap positions as one array, so+ // F[i] = sum_{jj = 0}^{2N} e[i + 1 + jj] * (2 if |jj - N| <= N2 else 1), a sliding window.+ let mut e = [0i32; 25];+ for (m, x) in e[..4 * N + 1].iter_mut().enumerate() {+ *x = v[m.saturating_sub(N).min(2 * N + 1)];+ }+ let mut f = [0i32; 12];+ let mut win: i32 = e[1..2 * N + 2].iter().sum();+ for i in 0..2 * N {+ if i > 0 {+ win += e[i + 1 + 2 * N] - e[i];}+ let centre: i32 = e[i + 1 + N - N2..=i + 1 + N + N2].iter().sum();+ f[i] = (win + centre + (1 << (LOG2 - 1))) >> LOG2;+ }+ let out = base - N * step;+ for i in 0..2 * N {+ d[out + i * step] = f[i] as u16;}}diff --git a/crates/av1/src/symbol.rs b/crates/av1/src/symbol.rsindex f522f451f..d8b547dff 100644--- a/crates/av1/src/symbol.rs+++ b/crates/av1/src/symbol.rs@@ -9,36 +9,36 @@ const EC_MIN_PROB: u32 = 4;pub(crate) struct SymbolDecoder<'a> {data: &'a [u8],- /// Bit position of the next bit to read.- pos: usize,- end: usize,- value: u32,+ /// Next byte of `data` to load into the window.+ next: usize,+ /// SymbolValue followed by `k` look-ahead bits: the bitstream with every bit inverted+ /// (the spec's renormalisation XORs the new bits with ones), zero bits past the end of+ /// the data reading as ones. SymbolValue = win >> k.+ win: u64,+ k: u32,range: u32,- max_bits: i64,pub disable_update: bool,}impl<'a> SymbolDecoder<'a> {/// `init_symbol( sz )` over `data` (the tile's bytes).pub fn new(data: &'a [u8], disable_update: bool) -> Self {- let sz = data.len();- let mut d = SymbolDecoder { data, pos: 0, end: sz * 8, value: 0, range: 1 << 15, max_bits: 8 * sz as i64 - 15, disable_update };- let num_bits = (sz * 8).min(15) as u32;- let buf = d.read_bits(num_bits);- let padded = buf << (15 - num_bits);- d.value = ((1 << 15) - 1) ^ padded;+ let mut d = SymbolDecoder { data, next: 0, win: 0, k: 0, range: 1 << 15, disable_update };+ // SymbolValue = ((1 << 15) - 1) ^ (first 15 bits): 15 inverted bits.+ let mut filled = 0;+ while filled < 15 + 32 {+ d.win = (d.win << 8) | d.inverted_byte() as u64;+ filled += 8;+ }+ d.k = filled - 15;d}#[inline(always)]- fn read_bits(&mut self, n: u32) -> u32 {- let mut x = 0u32;- for _ in 0..n {- let bit = if self.pos < self.end { (self.data[self.pos >> 3] >> (7 - (self.pos & 7))) & 1 } else { 0 };- self.pos += 1;- x = (x << 1) | bit as u32;- }- x+ fn inverted_byte(&mut self) -> u8 {+ let b = self.data.get(self.next).copied().unwrap_or(0);+ self.next += 1;+ !b}/// `read_symbol( cdf )`: `cdf` has N + 1 entries (the last is the adaptation counter).@@ -54,6 +54,7 @@ impl<'a> SymbolDecoder<'a> {#[inline(always)]fn decode(&mut self, cdf: &[u16], n: usize) -> usize {+ let value = (self.win >> self.k) as u32;let mut cur = self.range;let mut symbol = 0usize;let mut prev;@@ -62,29 +63,31 @@ impl<'a> SymbolDecoder<'a> {let f = (1u32 << 15) - cdf[symbol] as u32;cur = ((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT);cur += EC_MIN_PROB * (n - symbol - 1) as u32;- if self.value >= cur {+ if value >= cur {break;}symbol += 1;}self.range = prev - cur;- self.value -= cur;+ self.win -= (cur as u64) << self.k;self.renormalize();symbol}+ /// Renormalisation (8.2.6): SymbolValue takes `bits` more (inverted) bits, which are+ /// already in the window.#[inline(always)]fn renormalize(&mut self) {let bits = 15 - (31 - self.range.leading_zeros());- if bits == 0 {- return;- }self.range <<= bits;- let num_bits = (bits as i64).min(self.max_bits.max(0)) as u32;- let new_data = self.read_bits(num_bits);- let padded = new_data << (bits - num_bits);- self.value = padded ^ (((self.value + 1) << bits) - 1);- self.max_bits -= bits as i64;+ self.k -= bits;+ if self.k < 16 {+ // SymbolValue < 2^16, so 16 + k <= 64 bits stay in the window.+ while self.k <= 40 {+ self.win = (self.win << 8) | self.inverted_byte() as u64;+ self.k += 8;+ }+ }}/// `read_bool()`@@ -117,11 +120,6 @@ impl<'a> SymbolDecoder<'a> {let extra = self.read_literal(1);(v << 1) - m + extra}-- /// SymbolMaxBits (for the exit process checks).- pub fn max_bits(&self) -> i64 {- self.max_bits- }}/// CDF adaptation (8.2.6).diff --git a/crates/av1/src/tile.rs b/crates/av1/src/tile.rsindex e0e35d929..14bce6903 100644--- a/crates/av1/src/tile.rs+++ b/crates/av1/src/tile.rs@@ -95,6 +95,10 @@ pub(crate) struct TileDecoder<'a, 'f> {plane_tx_type: usize,pub pred_buf: [Vec<i32>; 2],pub mask: Vec<i32>,+ /// Intermediate rows of the sub-pixel filters (up to 2 x 128 + 8 rows of 128 with 2:1 scaled references).+ pub mc_tmp: Vec<i32>,+ /// Coefficient levels of the current transform block, padded (see TX_PAD).+ levels: Vec<u8>,}const SB_MAX: usize = 32; // superblock size in 4x4 units (128 / 4)@@ -138,6 +142,8 @@ impl<'a, 'f> TileDecoder<'a, 'f> {plane_tx_type: 0,pred_buf: [vec![0; 128 * 128], vec![0; 128 * 128]],mask: vec![0; 128 * 128],+ mc_tmp: vec![0; (2 * 128 + 8) * 128],+ levels: vec![0; (32 + TX_PAD) * (32 + TX_PAD)],}}@@ -423,24 +429,27 @@ impl<'a, 'f> TileDecoder<'a, 'f> {let mi = &mut self.fs.mi;let rows = b.bh4.min(mi.rows.saturating_sub(r));let cols = b.bw4.min(mi.cols.saturating_sub(c));+ let set_uv = b.ref_frame[0] == INTRA_FRAME as i8 && b.has_chroma;+ let mvs = [Mv::new(b.mv_i[0][0], b.mv_i[0][1]), Mv::new(b.mv_i[1][0], b.mv_i[1][1])];for y in 0..rows {- for x in 0..cols {- let i = mi.idx(r + y, c + x);- mi.y_mode[i] = b.y_mode as u8;- if b.ref_frame[0] == INTRA_FRAME as i8 && b.has_chroma {- mi.uv_mode[i] = b.uv_mode as u8;+ let i = mi.idx(r + y, c);+ let span = i..i + cols;+ mi.y_mode[span.clone()].fill(b.y_mode as u8);+ if set_uv {+ mi.uv_mode[span.clone()].fill(b.uv_mode as u8);+ }+ mi.ref_frame[span.clone()].fill(b.ref_frame);+ mi.written[span.clone()].fill(true);+ if b.is_inter {+ if !b.use_intrabc {+ mi.comp_group_idx[span.clone()].fill(b.comp_group_idx);+ mi.compound_idx[span.clone()].fill(b.compound_idx);}- mi.ref_frame[i] = b.ref_frame;- mi.written[i] = true;- if b.is_inter {- if !b.use_intrabc {- mi.comp_group_idx[i] = b.comp_group_idx;- mi.compound_idx[i] = b.compound_idx;- }- mi.interp_filter[i] = b.interp_filter;- mi.mv[i][0] = Mv::new(b.mv_i[0][0], b.mv_i[0][1]);+ mi.interp_filter[span.clone()].fill(b.interp_filter);+ for m in mi.mv[span].iter_mut() {+ m[0] = mvs[0];if is_compound {- mi.mv[i][1] = Mv::new(b.mv_i[1][0], b.mv_i[1][1]);+ m[1] = mvs[1];}}}@@ -453,22 +462,22 @@ impl<'a, 'f> TileDecoder<'a, 'f> {let mi = &mut self.fs.mi;let rows = b.bh4.min(mi.rows.saturating_sub(r));let cols = b.bw4.min(mi.cols.saturating_sub(c));+ let dlf = [delta_lf[0] as i8, delta_lf[1] as i8, delta_lf[2] as i8, delta_lf[3] as i8];for y in 0..rows {- for x in 0..cols {- let i = mi.idx(r + y, c + x);- mi.is_inter[i] = b.is_inter;- mi.skip_mode[i] = b.skip_mode;- mi.skip[i] = b.skip;- mi.tx_size[i] = b.tx_size as u8;- mi.mi_size[i] = b.mi_size as u8;- mi.segment_id[i] = b.segment_id as u8;- mi.palette_size[0][i] = b.palette_size_y as u8;- mi.palette_size[1][i] = b.palette_size_uv as u8;- mi.palette_colors[0][i] = b.palette_colors_y;- mi.palette_colors[1][i] = b.palette_colors_u;- mi.delta_lf[i] = [delta_lf[0] as i8, delta_lf[1] as i8, delta_lf[2] as i8, delta_lf[3] as i8];- mi.motion_mode[i] = b.motion_mode;- }+ let i = mi.idx(r + y, c);+ let span = i..i + cols;+ mi.is_inter[span.clone()].fill(b.is_inter);+ mi.skip_mode[span.clone()].fill(b.skip_mode);+ mi.skip[span.clone()].fill(b.skip);+ mi.tx_size[span.clone()].fill(b.tx_size as u8);+ mi.mi_size[span.clone()].fill(b.mi_size as u8);+ mi.segment_id[span.clone()].fill(b.segment_id as u8);+ mi.palette_size[0][span.clone()].fill(b.palette_size_y as u8);+ mi.palette_size[1][span.clone()].fill(b.palette_size_uv as u8);+ mi.palette_colors[0][span.clone()].fill(b.palette_colors_y);+ mi.palette_colors[1][span.clone()].fill(b.palette_colors_u);+ mi.delta_lf[span.clone()].fill(dlf);+ mi.motion_mode[span].fill(b.motion_mode);}Ok(())}@@ -1689,18 +1698,37 @@ impl<'a, 'f> TileDecoder<'a, 'f> {let bwl = TX_WIDTH_LOG2[adj] as usize;let height = TX_HEIGHT[adj] as usize;let width = 1usize << bwl;+ // Levels with TX_PAD zero columns / rows past the right / bottom edge, so the+ // neighbourhood sums need no bounds checks (out-of-range neighbours count as 0).+ let stride = width + TX_PAD;+ let mut lev = std::mem::take(&mut self.levels);+ lev[..(height + TX_PAD) * stride].fill(0);+ let sig = &SIG_REF_DIFF_OFFSET[tx_class];+ let sig_off: [usize; SIG_REF_DIFF_OFFSET_NUM] = std::array::from_fn(|i| sig[i][0] as usize * stride + sig[i][1] as usize);+ let magr = &MAG_REF_OFFSET_WITH_TX_CLASS[tx_class];+ let mag_off: [usize; 3] = std::array::from_fn(|i| magr[i][0] as usize * stride + magr[i][1] as usize);for c in (0..eob).rev() {let pos = scan[c] as usize;- let level = if c == eob - 1 {+ let row = pos >> bwl;+ let col = pos & (width - 1);+ let li = row * stride + col;+ let mut level = if c == eob - 1 {let ctx = coeff_base_eob_ctx(c, bwl, height);self.sd.read_symbol(&mut self.cdf.coeff_base_eob[tx_sz_ctx][ptype][ctx]) as i32 + 1} else {- let ctx = self.coeff_base_ctx(tx_sz, tx_class, bwl, width, height, pos);+ let mut mag = 0u32;+ for o in sig_off {+ mag += (lev[li + o] as u32).min(3);+ }+ let ctx = coeff_base_ctx(tx_sz, tx_class, row, col, mag);self.sd.read_symbol(&mut self.cdf.coeff_base[tx_sz_ctx][ptype][ctx]) as i32};- let mut level = level;if level > NUM_BASE_LEVELS as i32 {- let ctx = self.coeff_br_ctx(tx_class, bwl, height, pos);+ let mut mag = 0u32;+ for o in mag_off {+ mag += (lev[li + o] as u32).min((COEFF_BASE_RANGE + NUM_BASE_LEVELS + 1) as u32);+ }+ let ctx = coeff_br_ctx(tx_class, row, col, pos, mag);for _ in 0..(COEFF_BASE_RANGE / (BR_CDF_SIZE - 1)) {let br = self.sd.read_symbol(&mut self.cdf.coeff_br[tx_sz_ctx.min(TX_32X32)][ptype][ctx]) as i32;level += br;@@ -1710,7 +1738,9 @@ impl<'a, 'f> TileDecoder<'a, 'f> {}}self.quant[pos] = level;+ lev[li] = level as u8;}+ self.levels = lev;for c in 0..eob {let pos = scan[c] as usize;let sign = if self.quant[pos] != 0 {@@ -1834,54 +1864,6 @@ impl<'a, 'f> TileDecoder<'a, 'f> {}}- fn coeff_base_ctx(&self, tx_sz: usize, tx_class: usize, bwl: usize, width: usize, height: usize, pos: usize) -> usize {- let row = pos >> bwl;- let col = pos - (row << bwl);- let mut mag = 0i32;- for idx in 0..SIG_REF_DIFF_OFFSET_NUM {- let ref_row = row + SIG_REF_DIFF_OFFSET[tx_class][idx][0] as usize;- let ref_col = col + SIG_REF_DIFF_OFFSET[tx_class][idx][1] as usize;- if ref_row < height && ref_col < width {- mag += self.quant[(ref_row << bwl) + ref_col].abs().min(3);- }- }- let ctx = ((mag + 1) >> 1).min(4) as usize;- if tx_class == TX_CLASS_2D {- if row == 0 && col == 0 {- return 0;- }- return ctx + COEFF_BASE_CTX_OFFSET[tx_sz][row.min(4)][col.min(4)] as usize;- }- let idx = if tx_class == TX_CLASS_VERT { row } else { col };- ctx + COEFF_BASE_POS_CTX_OFFSET[idx.min(2)] as usize- }-- fn coeff_br_ctx(&self, tx_class: usize, bwl: usize, txh: usize, pos: usize) -> usize {- let txw = 1usize << bwl;- let row = pos >> bwl;- let col = pos - (row << bwl);- let mut mag = 0i32;- for idx in 0..3 {- let ref_row = row + MAG_REF_OFFSET_WITH_TX_CLASS[tx_class][idx][0] as usize;- let ref_col = col + MAG_REF_OFFSET_WITH_TX_CLASS[tx_class][idx][1] as usize;- if ref_row < txh && ref_col < (1 << bwl) {- mag += self.quant[ref_row * txw + ref_col].min((COEFF_BASE_RANGE + NUM_BASE_LEVELS + 1) as i32);- }- }- let mag = ((mag + 1) >> 1).min(6) as usize;- if pos == 0 {- mag- } else if tx_class == 0 {- if row < 2 && col < 2 { mag + 7 } else { mag + 14 }- } else if tx_class == 1 {- if col == 0 { mag + 7 } else { mag + 14 }- } else if row == 0 {- mag + 7- } else {- mag + 14- }- }-fn dc_sign_ctx(&self, plane: usize, x4: usize, y4: usize, w4: usize, h4: usize) -> usize {let mut max_x4 = self.fs.fh.mi_cols as usize;let mut max_y4 = self.fs.fh.mi_rows as usize;@@ -1945,8 +1927,9 @@ impl<'a, 'f> TileDecoder<'a, 'f> {let qm_level = if fh.quant.using_qmatrix { fh.seg_qm_level[plane][self.b.segment_id] } else { 15 };let use_qm = fh.quant.using_qmatrix && t < IDTX && qm_level < 15;let lim = 1i64 << (7 + bd);- for v in self.dequant.iter_mut() {- *v = 0;+ // inverse_transform_2d reads only the top-left tw x th coefficients (stride 64)+ for i in 0..th {+ self.dequant[i * 64..i * 64 + tw].fill(0);}for i in 0..th {for j in 0..tw {@@ -1973,10 +1956,16 @@ impl<'a, 'f> TileDecoder<'a, 'f> {let max = (1i32 << bd) - 1;for i in 0..h {let yy = if flip_ud { h - i - 1 } else { i };- for j in 0..w {- let xx = if flip_lr { w - j - 1 } else { j };- let cur = pl.at(x + xx, y + yy) as i32;- pl.set(x + xx, y + yy, (cur + self.residual[i * w + j]).clamp(0, max) as u16);+ let row = &mut pl.row_mut(y + yy)[x..x + w];+ let res = &self.residual[i * w..i * w + w];+ if flip_lr {+ for (o, &r) in row.iter_mut().rev().zip(res) {+ *o = (*o as i32 + r).max(0).min(max) as u16;+ }+ } else {+ for (o, &r) in row.iter_mut().zip(res) {+ *o = (*o as i32 + r).max(0).min(max) as u16;+ }}}}@@ -2135,6 +2124,40 @@ fn get_tx_class(t: usize) -> usize {}}+/// Coefficient base context from the neighbourhood magnitude `mag` (get_coeff_base_ctx).+#[inline(always)]+fn coeff_base_ctx(tx_sz: usize, tx_class: usize, row: usize, col: usize, mag: u32) -> usize {+ let ctx = ((mag + 1) >> 1).min(4) as usize;+ if tx_class == TX_CLASS_2D {+ if row == 0 && col == 0 {+ return 0;+ }+ return ctx + COEFF_BASE_CTX_OFFSET[tx_sz][row.min(4)][col.min(4)] as usize;+ }+ let idx = if tx_class == TX_CLASS_VERT { row } else { col };+ ctx + COEFF_BASE_POS_CTX_OFFSET[idx.min(2)] as usize+}++/// coeff_br context from the neighbourhood magnitude `mag`.+#[inline(always)]+fn coeff_br_ctx(tx_class: usize, row: usize, col: usize, pos: usize, mag: u32) -> usize {+ let mag = ((mag + 1) >> 1).min(6) as usize;+ if pos == 0 {+ mag+ } else if tx_class == 0 {+ if row < 2 && col < 2 { mag + 7 } else { mag + 14 }+ } else if tx_class == 1 {+ if col == 0 { mag + 7 } else { mag + 14 }+ } else if row == 0 {+ mag + 7+ } else {+ mag + 14+ }+}++/// Zero padding (columns and rows) of the coefficient level buffer.+const TX_PAD: usize = 4;+fn coeff_base_eob_ctx(c: usize, bwl: usize, height: usize) -> usize {if c == 0 {return 0;diff --git a/crates/av1/src/transform.rs b/crates/av1/src/transform.rsindex c52c2b034..626cefe8c 100644--- a/crates/av1/src/transform.rs+++ b/crates/av1/src/transform.rs@@ -28,6 +28,100 @@ fn sin128(angle: i32) -> i64 {cos128(angle - 64)}+/// One value of the 1D transforms, or `L` independent columns / rows of them processed+/// together (lane-wise, so the steps vectorise).+pub(crate) trait Lane: Copy {+ const ZERO: Self;+ /// (Round2( a * cos - b * sin, 12 ), Round2( a * sin + b * cos, 12 ))+ fn rotate(a: Self, b: Self, cos: i32, sin: i32) -> (Self, Self);+ /// (Clamp( x + y ), Clamp( x - y )) to [lo, hi]+ fn hadamard(x: Self, y: Self, lo: i32, hi: i32) -> (Self, Self);+ fn neg(self) -> Self;+ /// Round2( v * m, 12 )+ fn mul_round12(self, m: i32) -> Self;+ fn mul(self, k: i32) -> Self;+ fn adst4(t: &mut [Self]);+}++impl Lane for i32 {+ const ZERO: i32 = 0;+ #[inline(always)]+ fn rotate(a: i32, b: i32, cos: i32, sin: i32) -> (i32, i32) {+ let (a, b, c, s) = (a as i64, b as i64, cos as i64, sin as i64);+ (round2_64(a * c - b * s, 12), round2_64(a * s + b * c, 12))+ }+ #[inline(always)]+ fn hadamard(x: i32, y: i32, lo: i32, hi: i32) -> (i32, i32) {+ ((x + y).clamp(lo, hi), (x - y).clamp(lo, hi))+ }+ #[inline(always)]+ fn neg(self) -> i32 {+ -self+ }+ #[inline(always)]+ fn mul_round12(self, m: i32) -> i32 {+ round2_64(self as i64 * m as i64, 12)+ }+ #[inline(always)]+ fn mul(self, k: i32) -> i32 {+ self * k+ }+ fn adst4(t: &mut [i32]) {+ inverse_adst4_scalar(t);+ }+}++/// Lanes in 32-bit arithmetic: exact for conforming streams up to 10 bits per sample (the+/// spec requires every intermediate value to fit in 8 + BitDepth <= 18 bits, so products with+/// the 12-bit cosines stay below 2^31). Wrapping operations keep corrupt streams from+/// panicking.+impl<const L: usize> Lane for [i32; L] {+ const ZERO: Self = [0; L];+ #[inline(always)]+ fn rotate(a: Self, b: Self, cos: i32, sin: i32) -> (Self, Self) {+ let mut x = [0; L];+ let mut y = [0; L];+ for l in 0..L {+ let p = a[l].wrapping_mul(cos).wrapping_sub(b[l].wrapping_mul(sin));+ let q = a[l].wrapping_mul(sin).wrapping_add(b[l].wrapping_mul(cos));+ x[l] = p.wrapping_add(1 << 11) >> 12;+ y[l] = q.wrapping_add(1 << 11) >> 12;+ }+ (x, y)+ }+ #[inline(always)]+ fn hadamard(x: Self, y: Self, lo: i32, hi: i32) -> (Self, Self) {+ let mut a = [0; L];+ let mut b = [0; L];+ for l in 0..L {+ a[l] = x[l].wrapping_add(y[l]).max(lo).min(hi);+ b[l] = x[l].wrapping_sub(y[l]).max(lo).min(hi);+ }+ (a, b)+ }+ #[inline(always)]+ fn neg(self) -> Self {+ self.map(|v| v.wrapping_neg())+ }+ #[inline(always)]+ fn mul_round12(self, m: i32) -> Self {+ self.map(|v| v.wrapping_mul(m).wrapping_add(1 << 11) >> 12)+ }+ #[inline(always)]+ fn mul(self, k: i32) -> Self {+ self.map(|v| v.wrapping_mul(k))+ }+ fn adst4(t: &mut [Self]) {+ for l in 0..L {+ let mut v = [t[0][l], t[1][l], t[2][l], t[3][l]];+ inverse_adst4_scalar(&mut v);+ for k in 0..4 {+ t[k][l] = v[k];+ }+ }+ }+}+fn brev(num_bits: u32, x: usize) -> usize {let mut t = 0;for i in 0..num_bits {@@ -39,11 +133,10 @@ fn brev(num_bits: u32, x: usize) -> usize {/// Butterfly rotation B( a, b, angle, flip ).#[inline(always)]-fn bf(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool) {- let x = t[a] as i64 * cos128(angle) - t[b] as i64 * sin128(angle);- let y = t[a] as i64 * sin128(angle) + t[b] as i64 * cos128(angle);- t[a] = round2_64(x, 12);- t[b] = round2_64(y, 12);+fn bf<T: Lane>(t: &mut [T], a: usize, b: usize, angle: i32, flip: bool) {+ let (x, y) = T::rotate(t[a], t[b], cos128(angle) as i32, sin128(angle) as i32);+ t[a] = x;+ t[b] = y;if flip {t.swap(a, b);}@@ -51,21 +144,20 @@ fn bf(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool) {/// Hadamard rotation H( a, b, flip, r ).#[inline(always)]-fn hd(t: &mut [i32], a: usize, b: usize, flip: bool, r: u32) {+fn hd<T: Lane>(t: &mut [T], a: usize, b: usize, flip: bool, r: u32) {let (a, b) = if flip { (b, a) } else { (a, b) };- let x = t[a];- let y = t[b];let lo = -(1i32 << (r - 1));let hi = (1i32 << (r - 1)) - 1;- t[a] = (x + y).clamp(lo, hi);- t[b] = (x - y).clamp(lo, hi);+ let (x, y) = T::hadamard(t[a], t[b], lo, hi);+ t[a] = x;+ t[b] = y;}/// Inverse DCT of length 2^n (7.13.2.3), in place.-pub(crate) fn inverse_dct(t: &mut [i32], n: u32, r: u32) {+pub(crate) fn inverse_dct<T: Lane>(t: &mut [T], n: u32, r: u32) {// 7.13.2.2 permutationlet len = 1usize << n;- let mut copy = [0i32; 64];+ let mut copy = [T::ZERO; 64];copy[..len].copy_from_slice(&t[..len]);for i in 0..len {t[i] = copy[brev(n, i)];@@ -238,7 +330,7 @@ const SINPI_2_9: i64 = 2482;const SINPI_3_9: i64 = 3344;const SINPI_4_9: i64 = 3803;-fn inverse_adst4(t: &mut [i32]) {+fn inverse_adst4_scalar(t: &mut [i32]) {let mut s = [0i64; 7];let mut x = [0i64; 4];let t0 = t[0] as i64;@@ -270,9 +362,9 @@ fn inverse_adst4(t: &mut [i32]) {}}-fn adst_in_permute(t: &mut [i32], n: u32) {+fn adst_in_permute<T: Lane>(t: &mut [T], n: u32) {let n0 = 1usize << n;- let mut copy = [0i32; 16];+ let mut copy = [T::ZERO; 16];copy[..n0].copy_from_slice(&t[..n0]);for i in 0..n0 {let idx = if i & 1 == 1 { i - 1 } else { n0 - i - 1 };@@ -280,9 +372,9 @@ fn adst_in_permute(t: &mut [i32], n: u32) {}}-fn adst_out_permute(t: &mut [i32], n: u32) {+fn adst_out_permute<T: Lane>(t: &mut [T], n: u32) {let n0 = 1usize << n;- let mut copy = [0i32; 16];+ let mut copy = [T::ZERO; 16];copy[..n0].copy_from_slice(&t[..n0]);for i in 0..n0 {let a = (i >> 3) & 1;@@ -290,11 +382,11 @@ fn adst_out_permute(t: &mut [i32], n: u32) {let c = ((i >> 1) & 1) ^ ((i >> 2) & 1);let d = (i & 1) ^ ((i >> 1) & 1);let idx = ((d << 3) | (c << 2) | (b << 1) | a) >> (4 - n);- t[i] = if i & 1 == 1 { -copy[idx] } else { copy[idx] };+ t[i] = if i & 1 == 1 { copy[idx].neg() } else { copy[idx] };}}-fn inverse_adst8(t: &mut [i32], r: u32) {+fn inverse_adst8<T: Lane>(t: &mut [T], r: u32) {adst_in_permute(t, 3);for i in 0..4 {bf(t, 2 * i, 2 * i + 1, 60 - 16 * i as i32, true);@@ -316,7 +408,7 @@ fn inverse_adst8(t: &mut [i32], r: u32) {adst_out_permute(t, 3);}-fn inverse_adst16(t: &mut [i32], r: u32) {+fn inverse_adst16<T: Lane>(t: &mut [T], r: u32) {adst_in_permute(t, 4);for i in 0..8 {bf(t, 2 * i, 2 * i + 1, 62 - 8 * i as i32, true);@@ -349,34 +441,34 @@ fn inverse_adst16(t: &mut [i32], r: u32) {adst_out_permute(t, 4);}-fn inverse_adst(t: &mut [i32], n: u32, r: u32) {+fn inverse_adst<T: Lane>(t: &mut [T], n: u32, r: u32) {match n {- 2 => inverse_adst4(t),+ 2 => T::adst4(t),3 => inverse_adst8(t, r),_ => inverse_adst16(t, r),}}-fn inverse_identity(t: &mut [i32], n: u32) {+fn inverse_identity<T: Lane>(t: &mut [T], n: u32) {match n {2 => {for v in t[..4].iter_mut() {- *v = round2_64(*v as i64 * 5793, 12);+ *v = v.mul_round12(5793);}}3 => {for v in t[..8].iter_mut() {- *v *= 2;+ *v = v.mul(2);}}4 => {for v in t[..16].iter_mut() {- *v = round2_64(*v as i64 * 11586, 12);+ *v = v.mul_round12(11586);}}_ => {for v in t[..32].iter_mut() {- *v *= 4;+ *v = v.mul(4);}}}@@ -438,15 +530,25 @@ pub(crate) fn inverse_transform_2d(dequant: &[i32], residual: &mut [i32], tx_sz:let ck = col_kind(tx_type);let mut t = [0i32; 64];let rect2 = log2w.abs_diff(log2h) == 1;- for i in 0..h {- if i >= 32 {- // rows beyond 32 have no coefficients but still go through the transform- t[..w].iter_mut().for_each(|v| *v = 0);+ if !lossless && bit_depth <= 10 {+ let p = Tx2d { w, h, log2w, log2h, row_shift, col_shift, row_clamp, col_clamp, rk, ck, rect2 };+ if w >= 8 && h >= 8 {+ transform_lanes::<8>(dequant, residual, &p);} else {- for j in 0..w {- t[j] = if j < 32 { dequant[i * 64 + j] } else { 0 };- }+ transform_lanes::<4>(dequant, residual, &p);}+ return;+ }+ let in_w = w.min(32);+ for i in 0..h {+ // Every 1D transform maps an all-zero row to zeros (each step is linear with+ // Round2( 0 ) = 0), so rows without coefficients (including rows 32..63) are zero.+ if i >= 32 || dequant[i * 64..i * 64 + in_w].iter().all(|&v| v == 0) {+ residual[i * w..i * w + w].fill(0);+ continue;+ }+ t[..in_w].copy_from_slice(&dequant[i * 64..i * 64 + in_w]);+ t[in_w..w].fill(0);if rect2 {for v in t[..w].iter_mut() {*v = round2_64(*v as i64 * 2896, 12);@@ -486,6 +588,80 @@ pub(crate) fn inverse_transform_2d(dequant: &[i32], residual: &mut [i32], tx_sz:}}+struct Tx2d {+ w: usize,+ h: usize,+ log2w: u32,+ log2h: u32,+ row_shift: u32,+ col_shift: u32,+ row_clamp: u32,+ col_clamp: u32,+ rk: Kind1d,+ ck: Kind1d,+ rect2: bool,+}++#[inline(always)]+fn transform_1d<T: Lane>(t: &mut [T], kind: Kind1d, n: u32, r: u32) {+ match kind {+ Kind1d::Dct => inverse_dct(t, n, r),+ Kind1d::Adst => inverse_adst(t, n, r),+ Kind1d::Identity => inverse_identity(t, n),+ }+}++/// The 2D inverse transform with `L` rows (row pass) or columns (column pass) at a time;+/// bit-identical to the one-at-a-time process for bit depths up to 10.+fn transform_lanes<const L: usize>(dequant: &[i32], residual: &mut [i32], p: &Tx2d) {+ let (w, h) = (p.w, p.h);+ let in_w = w.min(32);+ let lo = -(1i32 << (p.col_clamp - 1));+ let hi = (1i32 << (p.col_clamp - 1)) - 1;+ let mut t = [[0i32; L]; 64];+ let mut i0 = 0;+ while i0 < h {+ // Rows without coefficients (and rows 32..63) transform to zeros.+ if i0 >= 32 || (i0..i0 + L).all(|i| dequant[i * 64..i * 64 + in_w].iter().all(|&v| v == 0)) {+ residual[i0 * w..(i0 + L) * w].fill(0);+ i0 += L;+ continue;+ }+ for (j, tj) in t[..w].iter_mut().enumerate() {+ for l in 0..L {+ tj[l] = if j < in_w { dequant[(i0 + l) * 64 + j] } else { 0 };+ }+ }+ if p.rect2 {+ for v in t[..w].iter_mut() {+ *v = v.mul_round12(2896);+ }+ }+ transform_1d(&mut t[..], p.rk, p.log2w, p.row_clamp);+ for l in 0..L {+ let out = &mut residual[(i0 + l) * w..(i0 + l + 1) * w];+ for j in 0..w {+ out[j] = round2(t[j][l], p.row_shift).clamp(lo, hi);+ }+ }+ i0 += L;+ }+ let mut j0 = 0;+ while j0 < w {+ for i in 0..h {+ t[i].copy_from_slice(&residual[i * w + j0..i * w + j0 + L]);+ }+ transform_1d(&mut t[..], p.ck, p.log2h, p.col_clamp);+ for i in 0..h {+ let out = &mut residual[i * w + j0..i * w + j0 + L];+ for l in 0..L {+ out[l] = round2(t[i][l], p.col_shift);+ }+ }+ j0 += L;+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/av1/tests/perf.rs b/crates/av1/tests/perf.rsindex 3c472eb70..dd36a10e3 100644--- a/crates/av1/tests/perf.rs+++ b/crates/av1/tests/perf.rs@@ -51,6 +51,10 @@ 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())) {+ return;+ }let Some(ff) = ffmpeg() else { return };let path = make(&ff, spec);let frames = ivf_frames(&path);