FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#1039: faster HEVC motion compensation and deblocking, bit-exact
vangel762fe3a5e20262
diff --git a/crates/hevc/src/decoder.rs b/crates/hevc/src/decoder.rsindex 48f500666..e58088a82 100644--- a/crates/hevc/src/decoder.rs+++ b/crates/hevc/src/decoder.rs@@ -581,19 +581,24 @@ fn output_meta(sps: &Sps, pts: i64, key: bool, draft: bool) -> OutputMeta {fn make_picture(o: &Output<FrameRef>) -> Picture {let (cx, cy, cw, ch) = o.meta.crop;let (cx, cy, cw, ch) = (cx as usize, cy as usize, cw as usize, ch as usize);- let (y, u, v) = o.frame.copy_cropped((cx, cy, cw, ch));let (ccw, cch) = (cw.div_ceil(2), ch.div_ceil(2));let bd = o.meta.bit_depth;- let conv = |p: Vec<u16>| if bd <= 8 { Plane::U8(p.into_iter().map(|v| v as u8).collect()) } else { Plane::U16(p) };+ let (y, u, v) = if bd <= 8 {+ let (y, u, v) = o.frame.copy_cropped_u8((cx, cy, cw, ch));+ (Plane::U8(y), Plane::U8(u), Plane::U8(v))+ } else {+ let (y, u, v) = o.frame.copy_cropped((cx, cy, cw, ch));+ (Plane::U16(y), Plane::U16(u), Plane::U16(v))+ };Picture {width: cw as u32,height: ch as u32,chroma_width: ccw as u32,chroma_height: cch as u32,bit_depth: bd,- y: conv(y),- u: conv(u),- v: conv(v),+ y,+ u,+ v,y_stride: cw,uv_stride: ccw,pts: o.meta.pts,diff --git a/crates/hevc/src/filter.rs b/crates/hevc/src/filter.rsindex 479e26978..8fc9e2e86 100644--- a/crates/hevc/src/filter.rs+++ b/crates/hevc/src/filter.rs@@ -51,8 +51,9 @@ fn tc_beta(q: i32, bs: i32, tc_off: i32, beta_off: i32, bd: u32) -> (i32, i32) {((TC_TABLE[qt as usize] as i32) << (bd - 8), (BETA_TABLE[qb as usize] as i32) << (bd - 8))}-/// Boundary strength (8.7.2.4) between 4x4 blocks p and q.-fn boundary_strength(pic: &PicState, pi: usize, qi: usize, tu_edge: bool) -> i32 {+/// Boundary strength (8.7.2.4) between 4x4 blocks p and q, in slices `ps` and `qs` (indices into+/// `pic.slices`, from [`edge_params`]).+fn boundary_strength(pic: &PicState, pi: usize, qi: usize, tu_edge: bool, ps: u32, qs: u32) -> i32 {let (p, q) = (&pic.blk[pi], &pic.blk[qi]);if (p.flags | q.flags) & F_INTRA != 0 {return 2;@@ -61,20 +62,22 @@ fn boundary_strength(pic: &PicState, pi: usize, qi: usize, tu_edge: bool) -> i32return 1;}let (mp, mq) = (&pic.mvf[pi], &pic.mvf[qi]);- motion_bs(pic, pi, mp, qi, mq)+ // Same motion in the same slice (same reference lists): same pictures, no motion difference.+ if mp == mq && ps == qs {+ return 0;+ }+ motion_bs(pic, ps, mp, qs, mq)}-fn ref_id(pic: &PicState, blk: usize, f: &MvField, l: usize) -> u32 {- let (x, y) = ((blk % pic.w4) * 4, (blk / pic.w4) * 4);- let ctb = (y >> pic.log2_ctb) * pic.wctb + (x >> pic.log2_ctb);- let s = pic.ctb_slice[ctb];+/// The picture referenced by list `l` of motion `f` in slice `s`.+fn ref_id(pic: &PicState, s: u32, f: &MvField, l: usize) -> u32 {if s == u32::MAX {return u32::MAX;}- pic.slices[s as usize].ref_ids[l].get(f.ref_idx[l] as usize).copied().unwrap_or(u32::MAX - 1)+ pic.slices.get(s as usize).and_then(|sl| sl.ref_ids[l].get(f.ref_idx[l] as usize)).copied().unwrap_or(u32::MAX - 1)}-fn motion_bs(pic: &PicState, pi: usize, p: &MvField, qi: usize, q: &MvField) -> i32 {+fn motion_bs(pic: &PicState, ps: u32, p: &MvField, qs: u32, q: &MvField) -> i32 {let np = p.pred(0) as u32 + p.pred(1) as u32;let nq = q.pred(0) as u32 + q.pred(1) as u32;if np != nq {@@ -84,13 +87,13 @@ fn motion_bs(pic: &PicState, pi: usize, p: &MvField, qi: usize, q: &MvField) ->if np == 1 {let lp = if p.pred(0) { 0 } else { 1 };let lq = if q.pred(0) { 0 } else { 1 };- if ref_id(pic, pi, p, lp) != ref_id(pic, qi, q, lq) {+ if ref_id(pic, ps, p, lp) != ref_id(pic, qs, q, lq) {return 1;}return far(p.mv[lp], q.mv[lq]) as i32;}- let (p0, p1) = (ref_id(pic, pi, p, 0), ref_id(pic, pi, p, 1));- let (q0, q1) = (ref_id(pic, qi, q, 0), ref_id(pic, qi, q, 1));+ let (p0, p1) = (ref_id(pic, ps, p, 0), ref_id(pic, ps, p, 1));+ let (q0, q1) = (ref_id(pic, qs, q, 0), ref_id(pic, qs, q, 1));if !((p0 == q0 && p1 == q1) || (p0 == q1 && p1 == q0)) {return 1;}@@ -102,8 +105,8 @@ fn motion_bs(pic: &PicState, pi: usize, p: &MvField, qi: usize, q: &MvField) ->}/// Whether the edge between blocks p and q (q = current block, owning the edge) is filtered, and the-/// slice-level parameters (tc offset, beta offset) of q's slice.-fn edge_params(pic: &PicState, px: usize, py: usize, qx: usize, qy: usize) -> Option<(i32, i32)> {+/// slice-level parameters (tc offset, beta offset) of q's slice, then the slices of p and q.+fn edge_params(pic: &PicState, px: usize, py: usize, qx: usize, qy: usize) -> Option<(i32, i32, u32, u32)> {let s = pic.log2_ctb;let pc = (py >> s) * pic.wctb + (px >> s);let qc = (qy >> s) * pic.wctb + (qx >> s);@@ -124,7 +127,7 @@ fn edge_params(pic: &PicState, px: usize, py: usize, qx: usize, qy: usize) -> Opreturn None;}}- Some((sq.tc_offset, sq.beta_offset))+ Some((sq.tc_offset, sq.beta_offset, ps, qs))}/// Deblock CTB row `r`: vertical edges of the row, then horizontal edges whose q side is in the row.@@ -148,8 +151,8 @@ fn deblock_row(pic: &mut PicState, r: usize) {continue;}let (x, y) = (bx * 4, by * 4);- let Some((tc_off, beta_off)) = edge_params(pic, x - 1, y, x, y) else { continue };- let bs = boundary_strength(pic, qi - 1, qi, e & E_TU_V != 0);+ let Some((tc_off, beta_off, ps, qs)) = edge_params(pic, x - 1, y, x, y) else { continue };+ let bs = boundary_strength(pic, qi - 1, qi, e & E_TU_V != 0, ps, qs);bs_v[(by - y0 / 4) * w4 + bx] = bs as i8;if bs == 0 {continue;@@ -170,7 +173,7 @@ fn deblock_row(pic: &mut PicState, r: usize) {}let (x, y) = (bx * 4, by * 4);let qi = by * w4 + bx;- let Some((tc_off, _)) = edge_params(pic, x - 1, y, x, y) else { continue };+ let Some((tc_off, ..)) = edge_params(pic, x - 1, y, x, y) else { continue };let (p, q) = (pic.blk[qi - 1], pic.blk[qi]);let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);for (c, off) in [(1, cb_off), (2, cr_off)] {@@ -191,9 +194,9 @@ fn deblock_row(pic: &mut PicState, r: usize) {continue;}let (x, y) = (bx * 4, by * 4);- let Some((tc_off, beta_off)) = edge_params(pic, x, y - 1, x, y) else { continue };+ let Some((tc_off, beta_off, ps, qs)) = edge_params(pic, x, y - 1, x, y) else { continue };let pi = qi - w4;- let bs = boundary_strength(pic, pi, qi, e & E_TU_H != 0);+ let bs = boundary_strength(pic, pi, qi, e & E_TU_H != 0, ps, qs);bs_h[(by - y0 / 4) * w4 + bx] = bs as i8;if bs == 0 {continue;@@ -212,7 +215,7 @@ fn deblock_row(pic: &mut PicState, r: usize) {}let (x, y) = (bx * 4, by * 4);let qi = by * w4 + bx;- let Some((tc_off, _)) = edge_params(pic, x, y - 1, x, y) else { continue };+ let Some((tc_off, ..)) = edge_params(pic, x, y - 1, x, y) else { continue };let (p, q) = (pic.blk[qi - w4], pic.blk[qi]);let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);for (c, off) in [(1, cb_off), (2, cr_off)] {@@ -227,46 +230,88 @@ fn deblock_row(pic: &mut PicState, r: usize) {/// Filter one 4-sample luma edge segment. `o` = offset of q0 of the first line, `step` = distance/// between p/q samples across the edge, `along` = distance between lines.+///+/// The 4 x 8 samples (p3..p0, q0..q3 of each line) are read once into an array, filtered there+/// and written back, a whole line at a time for vertical edges (`step` = 1) and a whole row of+/// the 4 lines at a time for horizontal ones (`along` = 1): no per-sample index arithmetic or+/// bounds checks in the filter itself.#[allow(clippy::too_many_arguments)]fn filter_luma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, beta: i32, nfp: bool, nfq: bool, bd: u32) {- let px = |s: &[u16], k: usize, i: usize| s[o + k * along - (i + 1) * step] as i32;- let qx = |s: &[u16], k: usize, i: usize| s[o + k * along + i * step] as i32;- let dp0 = (px(s, 0, 2) - 2 * px(s, 0, 1) + px(s, 0, 0)).abs();- let dp3 = (px(s, 3, 2) - 2 * px(s, 3, 1) + px(s, 3, 0)).abs();- let dq0 = (qx(s, 0, 2) - 2 * qx(s, 0, 1) + qx(s, 0, 0)).abs();- let dq3 = (qx(s, 3, 2) - 2 * qx(s, 3, 1) + qx(s, 3, 0)).abs();+ // l[k][i]: line k, i = 0..4 -> p3, p2, p1, p0 and i = 4..8 -> q0, q1, q2, q3+ let mut l = [[0i32; 8]; 4];+ let Some(start) = o.checked_sub(4 * step) else { return };+ if step == 1 {+ for (k, line) in l.iter_mut().enumerate() {+ let Some(src) = s.get(start + k * along..).and_then(|v| v.first_chunk::<8>()) else { return };+ for (d, &v) in line.iter_mut().zip(src) {+ *d = v as i32;+ }+ }+ } else {+ for i in 0..8 {+ let Some(src) = s.get(start + i * step..).and_then(|v| v.first_chunk::<4>()) else { return };+ for (k, &v) in src.iter().enumerate() {+ l[k][i] = v as i32;+ }+ }+ }+ if !filter_luma_lines(&mut l, tc, beta, nfp, nfq, bd) {+ return;+ }+ if step == 1 {+ for (k, line) in l.iter().enumerate() {+ let Some(dst) = s.get_mut(start + k * along..).and_then(|v| v.first_chunk_mut::<8>()) else { return };+ for (d, &v) in dst.iter_mut().zip(line) {+ *d = v as u16;+ }+ }+ } else {+ for i in 1..7 {+ let Some(dst) = s.get_mut(start + i * step..).and_then(|v| v.first_chunk_mut::<4>()) else { return };+ for (k, d) in dst.iter_mut().enumerate() {+ *d = l[k][i] as u16;+ }+ }+ }+}++/// The luma edge filter (8.7.2.5.3 decisions, 8.7.2.5.7 filtering) on the lines of+/// [`filter_luma`]; false when the edge is left unfiltered (d >= beta).+fn filter_luma_lines(l: &mut [[i32; 8]; 4], tc: i32, beta: i32, nfp: bool, nfq: bool, bd: u32) -> bool {+ let px = |l: &[[i32; 8]; 4], k: usize, i: usize| l[k][3 - i];+ let qx = |l: &[[i32; 8]; 4], k: usize, i: usize| l[k][4 + i];+ let dp0 = (px(l, 0, 2) - 2 * px(l, 0, 1) + px(l, 0, 0)).abs();+ let dp3 = (px(l, 3, 2) - 2 * px(l, 3, 1) + px(l, 3, 0)).abs();+ let dq0 = (qx(l, 0, 2) - 2 * qx(l, 0, 1) + qx(l, 0, 0)).abs();+ let dq3 = (qx(l, 3, 2) - 2 * qx(l, 3, 1) + qx(l, 3, 0)).abs();let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);let (dp, dq) = (dp0 + dp3, dq0 + dq3);let d = dpq0 + dpq3;if d >= beta {- return;+ return false;}- let dsam = |s: &[u16], k: usize, dpq: i32| -> bool {+ let dsam = |l: &[[i32; 8]; 4], k: usize, dpq: i32| -> bool {dpq < (beta >> 2)- && (px(s, k, 3) - px(s, k, 0)).abs() + (qx(s, k, 0) - qx(s, k, 3)).abs() < (beta >> 3)- && (px(s, k, 0) - qx(s, k, 0)).abs() < ((5 * tc + 1) >> 1)+ && (px(l, k, 3) - px(l, k, 0)).abs() + (qx(l, k, 0) - qx(l, k, 3)).abs() < (beta >> 3)+ && (px(l, k, 0) - qx(l, k, 0)).abs() < ((5 * tc + 1) >> 1)};- let strong = dsam(s, 0, 2 * dpq0) && dsam(s, 3, 2 * dpq3);+ let strong = dsam(l, 0, 2 * dpq0) && dsam(l, 3, 2 * dpq3);let dep = dp < ((beta + (beta >> 1)) >> 3);let deq = dq < ((beta + (beta >> 1)) >> 3);let max = (1i32 << bd) - 1;- for k in 0..4 {- let base = o + k * along;- let p = |i: usize| s[base - (i + 1) * step] as i32;- let q = |i: usize| s[base + i * step] as i32;- let (p0, p1, p2, p3) = (p(0), p(1), p(2), p(3));- let (q0, q1, q2, q3) = (q(0), q(1), q(2), q(3));+ for line in l.iter_mut() {+ let [p3, p2, p1, p0, q0, q1, q2, q3] = *line;if strong {let t2 = 2 * tc;if !nfp {- s[base - step] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3).clamp(p0 - t2, p0 + t2) as u16;- s[base - 2 * step] = ((p2 + p1 + p0 + q0 + 2) >> 2).clamp(p1 - t2, p1 + t2) as u16;- s[base - 3 * step] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3).clamp(p2 - t2, p2 + t2) as u16;+ line[3] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3).clamp(p0 - t2, p0 + t2);+ line[2] = ((p2 + p1 + p0 + q0 + 2) >> 2).clamp(p1 - t2, p1 + t2);+ line[1] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3).clamp(p2 - t2, p2 + t2);}if !nfq {- s[base] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3).clamp(q0 - t2, q0 + t2) as u16;- s[base + step] = ((p0 + q0 + q1 + q2 + 2) >> 2).clamp(q1 - t2, q1 + t2) as u16;- s[base + 2 * step] = ((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3).clamp(q2 - t2, q2 + t2) as u16;+ line[4] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3).clamp(q0 - t2, q0 + t2);+ line[5] = ((p0 + q0 + q1 + q2 + 2) >> 2).clamp(q1 - t2, q1 + t2);+ line[6] = ((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3).clamp(q2 - t2, q2 + t2);}} else {let mut delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4;@@ -275,21 +320,22 @@ fn filter_luma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, beta}delta = delta.clamp(-tc, tc);if !nfp {- s[base - step] = (p0 + delta).clamp(0, max) as u16;+ line[3] = (p0 + delta).clamp(0, max);}if !nfq {- s[base] = (q0 - delta).clamp(0, max) as u16;+ line[4] = (q0 - delta).clamp(0, max);}if dep && !nfp {let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1);- s[base - 2 * step] = (p1 + dp).clamp(0, max) as u16;+ line[2] = (p1 + dp).clamp(0, max);}if deq && !nfq {let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1);- s[base + step] = (q1 + dq).clamp(0, max) as u16;+ line[5] = (q1 + dq).clamp(0, max);}}}+ true}/// Filter one 4-sample chroma edge segment.@@ -596,3 +642,110 @@ fn publish_row(pic: &mut PicState, r: usize) {let row = FrameRow { y: oy.into(), cb: ocb.into(), cr: ocr.into(), col: col.into() };pic.frame.publish(r, row);}++#[cfg(test)]+mod luma_filter_tests {+ use super::*;++ /// The luma edge filter as it was before reading the samples into an array (indexing the+ /// picture sample by sample), as the reference.+ #[allow(clippy::too_many_arguments)]+ fn reference(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, beta: i32, nfp: bool, nfq: bool, bd: u32) {+ let px = |s: &[u16], k: usize, i: usize| s[o + k * along - (i + 1) * step] as i32;+ let qx = |s: &[u16], k: usize, i: usize| s[o + k * along + i * step] as i32;+ let dp0 = (px(s, 0, 2) - 2 * px(s, 0, 1) + px(s, 0, 0)).abs();+ let dp3 = (px(s, 3, 2) - 2 * px(s, 3, 1) + px(s, 3, 0)).abs();+ let dq0 = (qx(s, 0, 2) - 2 * qx(s, 0, 1) + qx(s, 0, 0)).abs();+ let dq3 = (qx(s, 3, 2) - 2 * qx(s, 3, 1) + qx(s, 3, 0)).abs();+ let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);+ let (dp, dq) = (dp0 + dp3, dq0 + dq3);+ let d = dpq0 + dpq3;+ if d >= beta {+ return;+ }+ let dsam = |s: &[u16], k: usize, dpq: i32| -> bool {+ dpq < (beta >> 2)+ && (px(s, k, 3) - px(s, k, 0)).abs() + (qx(s, k, 0) - qx(s, k, 3)).abs() < (beta >> 3)+ && (px(s, k, 0) - qx(s, k, 0)).abs() < ((5 * tc + 1) >> 1)+ };+ let strong = dsam(s, 0, 2 * dpq0) && dsam(s, 3, 2 * dpq3);+ let dep = dp < ((beta + (beta >> 1)) >> 3);+ let deq = dq < ((beta + (beta >> 1)) >> 3);+ let max = (1i32 << bd) - 1;+ for k in 0..4 {+ let base = o + k * along;+ let p = |i: usize| s[base - (i + 1) * step] as i32;+ let q = |i: usize| s[base + i * step] as i32;+ let (p0, p1, p2, p3) = (p(0), p(1), p(2), p(3));+ let (q0, q1, q2, q3) = (q(0), q(1), q(2), q(3));+ if strong {+ let t2 = 2 * tc;+ if !nfp {+ s[base - step] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3).clamp(p0 - t2, p0 + t2) as u16;+ s[base - 2 * step] = ((p2 + p1 + p0 + q0 + 2) >> 2).clamp(p1 - t2, p1 + t2) as u16;+ s[base - 3 * step] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3).clamp(p2 - t2, p2 + t2) as u16;+ }+ if !nfq {+ s[base] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3).clamp(q0 - t2, q0 + t2) as u16;+ s[base + step] = ((p0 + q0 + q1 + q2 + 2) >> 2).clamp(q1 - t2, q1 + t2) as u16;+ s[base + 2 * step] = ((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3).clamp(q2 - t2, q2 + t2) as u16;+ }+ } else {+ let mut delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4;+ if delta.abs() >= tc * 10 {+ continue;+ }+ delta = delta.clamp(-tc, tc);+ if !nfp {+ s[base - step] = (p0 + delta).clamp(0, max) as u16;+ }+ if !nfq {+ s[base] = (q0 - delta).clamp(0, max) as u16;+ }+ if dep && !nfp {+ let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1);+ s[base - 2 * step] = (p1 + dp).clamp(0, max) as u16;+ }+ if deq && !nfq {+ let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1);+ s[base + step] = (q1 + dq).clamp(0, max) as u16;+ }+ }+ }+ }++ /// Same samples out of the gathered-block filter as out of the reference, for vertical and+ /// horizontal edges, strong and weak filtering, both bit depths and the no-filter flags.+ #[test]+ fn gathered_luma_filter_matches_the_per_sample_filter() {+ let mut rng = 0x2545_f491_4f6c_dd1du64;+ let mut next = move || {+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ rng+ };+ let w = 16usize;+ let mut filtered = 0;+ for case in 0..4000 {+ let bd = if case % 2 == 0 { 8 } else { 10 };+ let max = (1u64 << bd) - 1;+ // smooth blocks (strong filtering) to noisy ones (no filtering)+ let base = next() % (max + 1);+ let spread = [0u64, 2, 8, 64, max][case % 5];+ let plane: Vec<u16> = (0..w * w).map(|_| (base + next() % (spread + 1)).min(max) as u16).collect();+ let tc = (next() % 40) as i32;+ let beta = (next() % 120) as i32;+ let (nfp, nfq) = (next() % 4 == 0, next() % 4 == 0);+ for vertical in [true, false] {+ let (o, step, along) = if vertical { (4 * w + 8, 1, w) } else { (8 * w + 4, w, 1) };+ let (mut a, mut b) = (plane.clone(), plane.clone());+ filter_luma(&mut a, o, step, along, tc, beta, nfp, nfq, bd);+ reference(&mut b, o, step, along, tc, beta, nfp, nfq, bd);+ assert_eq!(a, b, "case {case} vertical {vertical}");+ filtered += (a != plane) as usize;+ }+ }+ assert!(filtered > 1000, "only {filtered} edges filtered");+ }+}diff --git a/crates/hevc/src/inter.rs b/crates/hevc/src/inter.rsindex b5feeb41f..3632a60ff 100644--- a/crates/hevc/src/inter.rs+++ b/crates/hevc/src/inter.rs@@ -40,9 +40,44 @@ fn filt_w<const T: usize, const W: usize>(src: &[i16], step: usize, f: &[i8; T],}}-/// [`filt_w`] for a run of `w` outputs (prediction block widths are fixed sizes).+/// [`filt_w`] in 16-bit lanes, for a first pass over 8-bit samples (`shift` = 0): the filtered+/// value is then at most 88 * 255 and at least -24 * 255 (the positive / negative taps of any+/// luma or chroma filter, 8.5.3.3.3.1 / 8.5.3.3.3.2), so it fits in an `i16`, and wrapping sums+/// are exact whenever the final value fits. Twice the lanes of [`filt_w`] per vector.#[inline(always)]-fn filt<const T: usize>(src: &[i16], step: usize, f: &[i8; T], shift: u32, out: &mut [i16], w: usize) {+fn filt16_w<const T: usize, const W: usize>(src: &[i16], step: usize, f: &[i8; T], out: &mut [i16]) {+ let mut acc = [0i16; W];+ for k in 0..T {+ let c = f[k] as i16;+ let Some(p) = src.get(k * step..).and_then(|s| s.first_chunk::<W>()) else {+ return;+ };+ for j in 0..W {+ acc[j] = acc[j].wrapping_add(c.wrapping_mul(p[j]));+ }+ }+ if let Some(o) = out.first_chunk_mut::<W>() {+ *o = acc;+ }+}++/// [`filt_w`] for a run of `w` outputs (prediction block widths are fixed sizes); in 16-bit lanes+/// ([`filt16_w`]) when `narrow` (a first pass over 8-bit samples).+#[inline(always)]+fn filt<const T: usize>(src: &[i16], step: usize, f: &[i8; T], shift: u32, out: &mut [i16], w: usize, narrow: bool) {+ if narrow {+ match w {+ 4 => return filt16_w::<T, 4>(src, step, f, out),+ 8 => return filt16_w::<T, 8>(src, step, f, out),+ 12 => return filt16_w::<T, 12>(src, step, f, out),+ 16 => return filt16_w::<T, 16>(src, step, f, out),+ 24 => return filt16_w::<T, 24>(src, step, f, out),+ 32 => return filt16_w::<T, 32>(src, step, f, out),+ 48 => return filt16_w::<T, 48>(src, step, f, out),+ 64 => return filt16_w::<T, 64>(src, step, f, out),+ _ => {}+ }+ }match w {2 => filt_w::<T, 2>(src, step, f, shift, out),4 => filt_w::<T, 4>(src, step, f, shift, out),@@ -80,6 +115,8 @@ fn interpolate<const T: usize>(out: &mut [i16],) {let m = T / 2 - 1;+ // 8-bit samples: first passes in 16-bit lanes (see filt16_w)+ let narrow = shift1 == 0 && shift3 == 6;if fx == 0 && fy == 0 {for r in 0..h {for (o, &s) in out[r * w..r * w + w].iter_mut().zip(&win[(r + m) * WIN + m..]) {@@ -88,18 +125,18 @@ fn interpolate<const T: usize>(}} else if fy == 0 {for r in 0..h {- filt(&win[(r + m) * WIN..], 1, hf, shift1, &mut out[r * w..], w);+ filt(&win[(r + m) * WIN..], 1, hf, shift1, &mut out[r * w..], w, narrow);}} else if fx == 0 {for r in 0..h {- filt(&win[r * WIN + m..], WIN, vf, shift1, &mut out[r * w..], w);+ filt(&win[r * WIN + m..], WIN, vf, shift1, &mut out[r * w..], w, narrow);}} else {for r in 0..h + T - 1 {- filt(&win[r * WIN..], 1, hf, shift1, &mut tmp[r * WIN..], w);+ filt(&win[r * WIN..], 1, hf, shift1, &mut tmp[r * WIN..], w, narrow);}for r in 0..h {- filt(&tmp[r * WIN..], WIN, vf, 6, &mut out[r * w..], w);+ filt(&tmp[r * WIN..], WIN, vf, 6, &mut out[r * w..], w, false);}}}@@ -132,27 +169,72 @@ pub fn mc_chroma(f: &Frame, c: usize, x: i32, y: i32, mv: [i16; 2], w: usize, h:interpolate::<4>(&sc.win, &mut sc.tmp, fx, fy, &CHROMA_FILTER[fx], &CHROMA_FILTER[fy], w, h, shift1, shift3, out);}+/// Calls `$f::<W>(args)` with `W` the prediction block width `$w` as a constant (block widths are+/// fixed sizes; a constant width lets the row loops vectorise even for 4- and 8-sample rows), or+/// `$f::<0>` for any other width.+macro_rules! by_width {+ ($w:expr, $f:ident($($a:expr),*)) => {+ match $w {+ 2 => $f::<2>($($a),*),+ 4 => $f::<4>($($a),*),+ 6 => $f::<6>($($a),*),+ 8 => $f::<8>($($a),*),+ 12 => $f::<12>($($a),*),+ 16 => $f::<16>($($a),*),+ 24 => $f::<24>($($a),*),+ 32 => $f::<32>($($a),*),+ 48 => $f::<48>($($a),*),+ 64 => $f::<64>($($a),*),+ _ => $f::<0>($($a),*),+ }+ };+}+/// Default weighted prediction, one list (8-262).pub fn put_uni(p: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {+ by_width!(w, put_uni_w(p, w, h, bd, dst, ds))+}++/// [`put_uni`] for rows of `W` samples (`W` = 0: rows of `w`).+///+/// In 16-bit lanes: prediction samples are 14-bit values (8.5.3.3.3: at most about +/-27000 for any+/// bit depth, as the reference samples are within `0..2^bd`), so `s + off` and the clipped result fit+/// in an `i16` and the sums are exact. SSE2 clips 16-bit lanes in one instruction each, 32-bit lanes+/// in four.+#[inline(always)]+fn put_uni_w<const W: usize>(p: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {+ let w = if W > 0 { W } else { w };let shift = 14 - bd;- let off = if shift > 0 { 1 << (shift - 1) } else { 0 };- let max = (1i32 << bd) - 1;+ let off: i16 = if shift > 0 { 1 << (shift - 1) } else { 0 };+ let max = ((1i32 << bd) - 1) as i16;// Rows as slices and min / max clipping (`clamp` asserts its bounds) so the loop vectorises.for (d, s) in dst.chunks_mut(ds).zip(p[..w * h].chunks(w)) {for (d, &s) in d[..w].iter_mut().zip(s) {- *d = ((s as i32 + off) >> shift).max(0).min(max) as u16;+ *d = (s.wrapping_add(off) >> shift).max(0).min(max) as u16;}}}/// Default weighted prediction, bi-prediction (8-263).pub fn put_bi(p0: &[i16], p1: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {- let shift = 15 - bd;- let off = 1 << (shift - 1);- let max = (1i32 << bd) - 1;+ by_width!(w, put_bi_w(p0, p1, w, h, bd, dst, ds))+}++/// [`put_bi`] for rows of `W` samples (`W` = 0: rows of `w`).+///+/// In 16-bit lanes, exactly: with `off = 2^(shift - 1)` even, `(a + b + off) >> shift` equals+/// `((a >> 1) + (b >> 1) + (a & b & 1) + off / 2) >> (shift - 1)` (the two dropped low bits only+/// carry when both are set), and `(a >> 1) + (b >> 1)` fits in an `i16` (see [`put_uni_w`]).+#[inline(always)]+fn put_bi_w<const W: usize>(p0: &[i16], p1: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {+ let w = if W > 0 { W } else { w };+ let shift = 15 - bd; // >= 3 (bd <= 12)+ let half_off: i16 = 1 << (shift - 2);+ let max = ((1i32 << bd) - 1) as i16;for ((d, a), b) in dst.chunks_mut(ds).zip(p0[..w * h].chunks(w)).zip(p1[..w * h].chunks(w)) {for ((d, &a), &b) in d[..w].iter_mut().zip(a).zip(b) {- *d = ((a as i32 + b as i32 + off) >> shift).max(0).min(max) as u16;+ let v = (a >> 1).wrapping_add(b >> 1).wrapping_add(a & b & 1).wrapping_add(half_off) >> (shift - 1);+ *d = v.max(0).min(max) as u16;}}}@@ -180,3 +262,143 @@ pub fn put_weighted_bi(p0: &[i16], p1: &[i16], w: usize, h: usize, bd: u32, log2}}}++#[cfg(test)]+mod tests {+ use super::*;++ struct Rng(u64);+ impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn range(&mut self, lo: i32, hi: i32) -> i32 {+ lo + (self.next() % (hi - lo + 1) as u64) as i32+ }+ }++ const WIDTHS: [usize; 11] = [2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 3];++ /// The 16-bit-lane `put_uni` / `put_bi` give exactly the 32-bit formulas of 8-262 / 8-263 over+ /// the whole range of 14-bit prediction samples, for every block width and bit depth.+ #[test]+ fn default_weighted_prediction_matches_the_32_bit_formulas() {+ let mut rng = Rng(0x9e37_79b9_7f4a_7c15);+ for bd in [8u32, 10, 12] {+ let max = (1i32 << bd) - 1;+ for &w in &WIDTHS {+ let h = 3;+ let sample = |rng: &mut Rng| -> i16 {+ match rng.next() % 6 {+ 0 => -10_240,+ 1 => 26_624,+ 2 => rng.range(-1, 1) as i16,+ _ => rng.range(-10_240, 26_624) as i16,+ }+ };+ let p0: Vec<i16> = (0..w * h).map(|_| sample(&mut rng)).collect();+ let p1: Vec<i16> = (0..w * h).map(|_| sample(&mut rng)).collect();+ let ds = w + 5;+ let (mut uni, mut bi) = (vec![0u16; ds * h], vec![0u16; ds * h]);+ put_uni(&p0, w, h, bd, &mut uni, ds);+ put_bi(&p0, &p1, w, h, bd, &mut bi, ds);+ for r in 0..h {+ for c in 0..w {+ let (a, b) = (p0[r * w + c] as i32, p1[r * w + c] as i32);+ let s1 = 14 - bd;+ let o1 = if s1 > 0 { 1 << (s1 - 1) } else { 0 };+ assert_eq!(uni[r * ds + c] as i32, ((a + o1) >> s1).clamp(0, max), "uni bd {bd} w {w} a {a}");+ let s2 = 15 - bd;+ assert_eq!(bi[r * ds + c] as i32, ((a + b + (1 << (s2 - 1))) >> s2).clamp(0, max), "bi bd {bd} w {w} a {a} b {b}");+ }+ }+ }+ }+ }++ /// First passes over 8-bit samples in 16-bit lanes equal the 32-bit sums, including the+ /// extreme sample patterns of every filter.+ #[test]+ fn narrow_first_pass_matches_the_32_bit_filter() {+ let mut rng = Rng(0x2545_f491_4f6c_dd1d);+ fn check<const T: usize>(f: &[i8; T], src: &[i16], step: usize, w: usize) {+ let (mut a, mut b) = ([0i16; 64], [0i16; 64]);+ filt(src, step, f, 0, &mut a, w, true);+ filt(src, step, f, 0, &mut b, w, false);+ assert_eq!(a[..w], b[..w], "filter {f:?} step {step} w {w}");+ }+ for &w in &WIDTHS {+ for step in [1usize, WIN] {+ let len = w + 7 * step + 8;+ let mut patterns: Vec<Vec<i16>> = (0..20).map(|_| (0..len).map(|_| rng.range(0, 255) as i16).collect()).collect();+ patterns.push(vec![255; len]);+ patterns.push(vec![0; len]);+ for f in LUMA_FILTER.iter() {+ // 255 under positive taps, 0 under negative ones (maximum), and the reverse+ for sign in [1, -1] {+ let mut v = vec![0i16; len];+ for (k, &c) in f.iter().enumerate() {+ for j in 0..w {+ v[j + k * step] = if (c as i32) * sign > 0 { 255 } else { 0 };+ }+ }+ check(f, &v, step, w);+ }+ for p in &patterns {+ check(f, p, step, w);+ }+ }+ for f in CHROMA_FILTER.iter() {+ for p in &patterns {+ check(f, p, step, w);+ }+ }+ }+ }+ }++ fn frame(rng: &mut Rng, w: usize, h: usize, bd: u32) -> Frame {+ let like = Frame::new(0, 0, w, h, 4, bd, bd);+ let max = (1i32 << bd) - 1;+ let y: Vec<u16> = (0..w * h).map(|_| rng.range(0, max) as u16).collect();+ let c: Vec<u16> = (0..w * h / 4).map(|_| rng.range(0, max) as u16).collect();+ let c2: Vec<u16> = (0..w * h / 4).map(|_| rng.range(0, max) as u16).collect();+ Frame::from_planes(1, 0, &like, &y, &c, &c2)+ }++ /// The full-sample uni-prediction shortcut (`Frame::copy_block`) gives what interpolation and+ /// 8-262 give, inside the picture and across every edge.+ #[test]+ fn full_sample_copy_matches_interpolation() {+ let mut rng = Rng(0x0123_4567_89ab_cdef);+ let mut sc = McScratch::default();+ for bd in [8u32, 10] {+ let f = frame(&mut rng, 48, 40, bd);+ for _ in 0..300 {+ let (w, h) = ([4usize, 8, 12, 16, 24, 32][rng.range(0, 5) as usize], [4usize, 8, 16][rng.range(0, 2) as usize]);+ let (x, y) = (rng.range(-40, 80), rng.range(-40, 70));+ let mut pred = vec![0i16; w * h];+ let (mut a, mut b) = (vec![0u16; w * h], vec![0u16; w * h]);+ inter_luma(&f, x, y, w, h, &mut pred, &mut sc);+ put_uni(&pred, w, h, bd, &mut a, w);+ f.copy_block(0, x, y, w, h, &mut b, w);+ assert_eq!(a, b, "luma bd {bd} at ({x}, {y}) {w}x{h}");+ for c in 1..3 {+ let (cw, ch) = (w / 2, h / 2);+ mc_chroma(&f, c - 1, 0, 0, [(x * 8) as i16, (y * 8) as i16], cw, ch, &mut pred, &mut sc);+ let (mut a, mut b) = (vec![0u16; cw * ch], vec![0u16; cw * ch]);+ put_uni(&pred, cw, ch, bd, &mut a, cw);+ f.copy_block(c, x, y, cw, ch, &mut b, cw);+ assert_eq!(a, b, "chroma {c} bd {bd} at ({x}, {y}) {cw}x{ch}");+ }+ }+ }+ }++ fn inter_luma(f: &Frame, x: i32, y: i32, w: usize, h: usize, out: &mut [i16], sc: &mut McScratch) {+ mc_luma(f, 0, 0, [(x * 4) as i16, (y * 4) as i16], w, h, out, sc);+ }+}diff --git a/crates/hevc/src/picture.rs b/crates/hevc/src/picture.rsindex 55d2730fa..f1655687f 100644--- a/crates/hevc/src/picture.rs+++ b/crates/hevc/src/picture.rs@@ -138,27 +138,70 @@ impl Frame {}}+ /// Copy the w x h block at (x0, y0) of plane `c` (0 = luma, 1 = Cb, 2 = Cr) into `dst`+ /// (stride `ds`), samples outside the picture replicated from its edges (8-228, 8-229).+ #[allow(clippy::too_many_arguments)]+ pub fn copy_block(&self, c: usize, x0: i32, y0: i32, w: usize, h: usize, dst: &mut [u16], ds: usize) {+ let (pw, ph, sh) = if c == 0 { (self.width, self.height, self.log2_ctb) } else { (self.cwidth, self.cheight, self.log2_ctb - 1) };+ let inside = usize::try_from(x0).ok().filter(|&x| x.saturating_add(w) <= pw);+ for (r, d) in dst.chunks_mut(ds).take(h).enumerate() {+ let yy = y0.saturating_add(r as i32).min(ph as i32 - 1).max(0) as usize;+ let row = self.row(yy >> sh);+ let plane = match c {+ 0 => &row.y,+ 1 => &row.cb,+ _ => &row.cr,+ };+ let off = (yy & ((1 << sh) - 1)) * pw;+ let Some(line) = plane.get(off..off + pw) else { return };+ let Some(d) = d.get_mut(..w) else { return };+ match inside.and_then(|x| line.get(x..x + w)) {+ Some(s) => copy_run(s, d),+ None => {+ let max = (pw as i32 - 1).max(0);+ for (i, d) in d.iter_mut().enumerate() {+ *d = line.get(x0.saturating_add(i as i32).clamp(0, max) as usize).copied().unwrap_or(0);+ }+ }+ }+ }+ }+/// Crop and copy the frame into planar buffers (waits for completion).pub fn copy_cropped(&self, crop: (usize, usize, usize, usize)) -> (Vec<u16>, Vec<u16>, Vec<u16>) {+ let mut out = (Vec::new(), Vec::new(), Vec::new());+ self.copy_cropped_with(crop, &mut out, |o, s| o.extend_from_slice(s));+ out+ }++ /// [`copy_cropped`](Self::copy_cropped) into 8-bit planes (samples of an 8-bit picture),+ /// without an intermediate 16-bit copy.+ pub fn copy_cropped_u8(&self, crop: (usize, usize, usize, usize)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {+ let mut out = (Vec::new(), Vec::new(), Vec::new());+ self.copy_cropped_with(crop, &mut out, |o, s| o.extend(s.iter().map(|&v| v as u8)));+ out+ }++ fn copy_cropped_with<T>(&self, crop: (usize, usize, usize, usize), out: &mut (Vec<T>, Vec<T>, Vec<T>), put: impl Fn(&mut Vec<T>, &[u16])) {let (cx, cy, cw, ch) = crop;let ctb = 1usize << self.log2_ctb;- let mut y = Vec::with_capacity(cw * ch);+ let (y, u, v) = out;+ y.reserve_exact(cw * ch);for r in cy..cy + ch {let row = self.row(r / ctb);let o = (r % ctb) * self.width + cx;- y.extend_from_slice(&row.y[o..o + cw]);+ put(y, &row.y[o..o + cw]);}let (ccx, ccy, ccw, cch) = (cx / 2, cy / 2, cw.div_ceil(2), ch.div_ceil(2));let cctb = ctb / 2;- let mut u = Vec::with_capacity(ccw * cch);- let mut v = Vec::with_capacity(ccw * cch);+ u.reserve_exact(ccw * cch);+ v.reserve_exact(ccw * cch);for r in ccy..ccy + cch {let row = self.row(r / cctb);let o = (r % cctb) * self.cwidth + ccx;- u.extend_from_slice(&row.cb[o..o + ccw]);- v.extend_from_slice(&row.cr[o..o + ccw]);+ put(u, &row.cb[o..o + ccw]);+ put(v, &row.cr[o..o + ccw]);}- (y, u, v)}/// A frame with every row published from full-picture planes and no motion (used to replace missing@@ -188,13 +231,69 @@ impl Frame {}}+/// `dst.copy_from_slice(src)` for the run lengths of prediction blocks as fixed-size copies: a+/// libc `memcpy` call per short block line costs more than the copy.+#[inline(always)]+fn copy_run(src: &[u16], dst: &mut [u16]) {+ #[inline(always)]+ fn fixed<const N: usize>(src: &[u16], dst: &mut [u16]) {+ if let (Some(s), Some(d)) = (src.first_chunk::<N>(), dst.first_chunk_mut::<N>()) {+ *d = *s;+ }+ }+ match dst.len() {+ 2 => fixed::<2>(src, dst),+ 4 => fixed::<4>(src, dst),+ 6 => fixed::<6>(src, dst),+ 8 => fixed::<8>(src, dst),+ 12 => fixed::<12>(src, dst),+ 16 => fixed::<16>(src, dst),+ 24 => fixed::<24>(src, dst),+ 32 => fixed::<32>(src, dst),+ 48 => fixed::<48>(src, dst),+ 64 => fixed::<64>(src, dst),+ n => {+ if let Some(s) = src.get(..n) {+ dst.copy_from_slice(s);+ }+ }+ }+}+/// Copy `out.len()` samples of `line` starting at x0, replicating edge samples outside the line.#[inline(always)]fn copy_line(line: &[u16], x0: i32, out: &mut [i16]) {let w = out.len();if x0 >= 0 && x0 as usize + w <= line.len() {- for (o, &s) in out.iter_mut().zip(&line[x0 as usize..x0 as usize + w]) {- *o = s as i16;+ let src = &line[x0 as usize..x0 as usize + w];+ // fixed-size copies for the window widths (block width + 7 luma, + 3 chroma): see copy_run+ #[inline(always)]+ fn fixed<const N: usize>(src: &[u16], out: &mut [i16]) {+ if let (Some(s), Some(o)) = (src.first_chunk::<N>(), out.first_chunk_mut::<N>()) {+ for j in 0..N {+ o[j] = s[j] as i16;+ }+ }+ }+ match w {+ 5 => fixed::<5>(src, out),+ 7 => fixed::<7>(src, out),+ 9 => fixed::<9>(src, out),+ 11 => fixed::<11>(src, out),+ 15 => fixed::<15>(src, out),+ 19 => fixed::<19>(src, out),+ 23 => fixed::<23>(src, out),+ 27 => fixed::<27>(src, out),+ 31 => fixed::<31>(src, out),+ 35 => fixed::<35>(src, out),+ 39 => fixed::<39>(src, out),+ 55 => fixed::<55>(src, out),+ 71 => fixed::<71>(src, out),+ _ => {+ for (o, &s) in out.iter_mut().zip(src) {+ *o = s as i16;+ }+ }}} else {let max = line.len() as i32 - 1;diff --git a/crates/hevc/src/slicedec.rs b/crates/hevc/src/slicedec.rsindex 949485648..12b9d4c36 100644--- a/crates/hevc/src/slicedec.rs+++ b/crates/hevc/src/slicedec.rs@@ -1448,6 +1448,21 @@ impl<'a> SliceDecoder<'a> {let bi = f.pred(0) && f.pred(1);for c in 0..3 {let (x, y, bw, bh, bd) = if c == 0 { (xp, yp, w, h, self.pic.bd_y) } else { (xp / 2, yp / 2, w / 2, h / 2, self.pic.bd_c) };+ // Uni-prediction at a full-sample position without weighting: the prediction+ // ((s << shift3) + off) >> shift3 (8-228, 8-262) is the reference sample itself.+ if !bi && !weighted {+ let l = if f.pred(0) { 0 } else { 1 };+ let frac = if c == 0 { 3 } else { 7 };+ let mv = f.mv[l];+ if f.pred(l) && mv[0] & frac == 0 && mv[1] & frac == 0 {+ let sh = if c == 0 { 2 } else { 3 };+ let stride = if c == 0 { self.pic.width } else { self.pic.cwidth };+ let frame = &self.refs[l][f.ref_idx[l] as usize].frame;+ let dst = &mut self.pic.planes[c][y as usize * stride + x as usize..];+ frame.copy_block(c, x + (mv[0] as i32 >> sh), y + (mv[1] as i32 >> sh), bw, bh, dst, stride);+ continue;+ }+ }let mut lists = [false; 2];for l in 0..2 {if !f.pred(l) {