Skip to content

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

Refactor h264 for strict Clippy checks

Dylan M. Taylor5069c311a507
diff --git a/crates/h264/src/cabac_mb.rs b/crates/h264/src/cabac_mb.rs
index df4848ab0..6f854f8d7 100644
--- a/crates/h264/src/cabac_mb.rs
+++ b/crates/h264/src/cabac_mb.rs
@@ -3,7 +3,7 @@
use crate::cabac::Cabac;
use crate::error::{Result, ensure, invalid};
-use crate::mbtypes::*;
+use crate::mbtypes::{MbTypeInfo, Part, SubMbInfo, b_mb_type, b_sub_mb_type, intra_mb_type, p_mb_type, p_sub_mb_type};
use crate::picture::MbKind;
use crate::slice::SliceType;
use crate::slicedec::{MbCur, SliceDecoder};
diff --git a/crates/h264/src/cavlc.rs b/crates/h264/src/cavlc.rs
index 7aed522cc..c92da3d54 100644
--- a/crates/h264/src/cavlc.rs
+++ b/crates/h264/src/cavlc.rs
@@ -1,6 +1,6 @@
//! CAVLC residual block parsing (9.2).
-use crate::cavlc_tables::*;
+use crate::cavlc_tables::{COEFF_TOKEN, RUN_BEFORE, TOTAL_ZEROS_2X2, TOTAL_ZEROS_2X4, TOTAL_ZEROS_4X4};
use crate::error::{Result, ensure};
use filmcraft_bitstream::BitReader;
use std::sync::OnceLock;
diff --git a/crates/h264/src/deblock.rs b/crates/h264/src/deblock.rs
index 063e83e8f..0dd369fc1 100644
--- a/crates/h264/src/deblock.rs
+++ b/crates/h264/src/deblock.rs
@@ -1,6 +1,6 @@
//! Deblocking filter (8.7) for progressive frames, 4:2:0, 8-bit.
-use crate::picture::{MbKind, MbState};
+use crate::picture::{MbKind, MbState, Planes};
use crate::slicedec::{PicState, SliceInfo};
use crate::tables::{ALPHA, BETA, TC0};
@@ -278,138 +278,192 @@ fn filter_horizontal<const N: usize>(pix: &mut [u8], stride: usize, x: usize, y:
}
}
-/// Deblock one macroblock (macroblocks must be processed in raster order).
-#[allow(clippy::needless_range_loop)]
-pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) {
- let q = &pic.mbs[addr];
- if q.slice_num == u32::MAX {
- return;
+/// Boundary strengths `[dir][edge][segment]`; dir 0 = vertical edges (x), 1 = horizontal edges (y).
+type MbBs = [[[u8; 4]; 4]; 2];
+
+/// Boundary strengths of an intra macroblock (8.7.2.1).
+fn intra_mb_bs(t8: bool, left: Option<usize>, top: Option<usize>) -> MbBs {
+ let mut bs = [[[0u8; 4]; 4]; 2];
+ for (dir, neighbor) in [left, top].into_iter().enumerate() {
+ if neighbor.is_some() {
+ bs[dir][0] = [4; 4];
+ }
+ for e in 1..4 {
+ if !(t8 && e % 2 == 1) {
+ bs[dir][e] = [3; 4];
+ }
+ }
}
- let sq = &pic.slices[q.slice_num as usize];
- if sq.disable_deblocking_filter_idc == 1 {
- return;
+ bs
+}
+
+/// Boundary strengths of the macroblock edge between neighbour `p` and the inter macroblock `q`.
+fn inter_outer_edge_bs(pic: &PicState, p: &MbState, q: &MbState, qm: &[Motion; 16], dir: usize) -> [u8; 4] {
+ if p.kind.is_intra() {
+ return [4; 4];
}
- let (mx, my) = (addr % mb_w, addr / mb_w);
- let usable = |n: Option<usize>| -> Option<usize> {
- let n = n?;
- let st = &pic.mbs[n];
- if st.slice_num == u32::MAX || (sq.disable_deblocking_filter_idc == 2 && st.slice_num != q.slice_num) {
- return None;
- }
- Some(n)
- };
- let left = usable(if mx > 0 { Some(addr - 1) } else { None });
- let top = usable(if my > 0 { Some(addr - mb_w) } else { None });
- let alpha_off = sq.alpha_offset;
- let beta_off = sq.beta_offset;
- let t8 = q.transform_8x8;
- // bS[dir][edge][segment]; dir 0 = vertical edges (x), 1 = horizontal edges (y)
+ let pids = ref_ids8(p, &pic.slices[p.slice_num as usize]);
+ let mut out = [0u8; 4];
+ for (k, o) in out.iter_mut().enumerate() {
+ let (rq, rp) = if dir == 0 { (k * 4, k * 4 + 3) } else { (k, 12 + k) };
+ *o = if (p.nz_mask >> rp) & 1 != 0 || (q.nz_mask >> rq) & 1 != 0 { 2 } else { motion_bs(&block_motion(p, &pids, rp), &qm[rq]) };
+ }
+ out
+}
+
+/// Boundary strengths of internal edge `e` (1..4) of the inter macroblock `q`.
+fn inter_inner_edge_bs(q: &MbState, qm: &[Motion; 16], dir: usize, e: usize) -> [u8; 4] {
+ let mut out = [0u8; 4];
+ for (k, o) in out.iter_mut().enumerate() {
+ let (rq, rp) = if dir == 0 { (k * 4 + e, k * 4 + e - 1) } else { (e * 4 + k, e * 4 + k - 4) };
+ *o = if (q.nz_mask >> rp) & 1 != 0 || (q.nz_mask >> rq) & 1 != 0 { 2 } else { motion_bs(&qm[rp], &qm[rq]) };
+ }
+ out
+}
+
+/// Boundary strengths of an inter macroblock (8.7.2.1).
+fn inter_mb_bs(pic: &PicState, q: &MbState, sq: &SliceInfo, left: Option<usize>, top: Option<usize>) -> MbBs {
let mut bs = [[[0u8; 4]; 4]; 2];
- if q.kind.is_intra() {
- for dir in 0..2 {
- if (if dir == 0 { left } else { top }).is_some() {
- bs[dir][0] = [4; 4];
- }
- for e in 1..4 {
- if !(t8 && e % 2 == 1) {
- bs[dir][e] = [3; 4];
- }
- }
+ let t8 = q.transform_8x8;
+ let qids = ref_ids8(q, sq);
+ let q_uniform = (0..2).all(|l| {
+ let r = q.ref_idx[l];
+ r[1] == r[0] && r[2] == r[0] && r[3] == r[0] && q.mv[l].iter().all(|m| *m == q.mv[l][0])
+ });
+ let qm: [Motion; 16] = std::array::from_fn(|r| block_motion(q, &qids, r));
+ for (dir, neighbor) in [left, top].into_iter().enumerate() {
+ if let Some(n) = neighbor {
+ bs[dir][0] = inter_outer_edge_bs(pic, &pic.mbs[n], q, &qm, dir);
}
- } else {
- let qids = ref_ids8(q, sq);
- let q_uniform = (0..2).all(|l| {
- let r = q.ref_idx[l];
- r[1] == r[0] && r[2] == r[0] && r[3] == r[0] && q.mv[l].iter().all(|m| *m == q.mv[l][0])
- });
- let qm: [Motion; 16] = std::array::from_fn(|r| block_motion(q, &qids, r));
- for dir in 0..2 {
- let neighbor = if dir == 0 { left } else { top };
- if let Some(n) = neighbor {
- let p = &pic.mbs[n];
- if p.kind.is_intra() {
- bs[dir][0] = [4; 4];
- } else {
- let pids = ref_ids8(p, &pic.slices[p.slice_num as usize]);
- for k in 0..4 {
- let (rq, rp) = if dir == 0 { (k * 4, k * 4 + 3) } else { (k, 12 + k) };
- bs[dir][0][k] =
- if (p.nz_mask >> rp) & 1 != 0 || (q.nz_mask >> rq) & 1 != 0 { 2 } else { motion_bs(&block_motion(p, &pids, rp), &qm[rq]) };
- }
- }
- }
- if q_uniform && q.nz_mask == 0 {
- // one motion for the whole MB and no coefficients: all internal edges have bS 0
- continue;
- }
- for e in 1..4 {
- if t8 && e % 2 == 1 {
- continue;
- }
- for k in 0..4 {
- let (rq, rp) = if dir == 0 { (k * 4 + e, k * 4 + e - 1) } else { (e * 4 + k, e * 4 + k - 4) };
- bs[dir][e][k] = if (q.nz_mask >> rp) & 1 != 0 || (q.nz_mask >> rq) & 1 != 0 { 2 } else { motion_bs(&qm[rp], &qm[rq]) };
- }
+ if q_uniform && q.nz_mask == 0 {
+ // one motion for the whole MB and no coefficients: all internal edges have bS 0
+ continue;
+ }
+ for e in 1..4 {
+ if !(t8 && e % 2 == 1) {
+ bs[dir][e] = inter_inner_edge_bs(q, &qm, dir, e);
}
}
}
- let qp_of = |st: &MbState| if st.kind == MbKind::IPcm { 0 } else { st.qp as i32 };
- let q_qp = qp_of(q);
- let q_qpc = q.qpc;
- let p_qp = [left.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc)), top.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc))];
- let params = |qpp: i32, qpq: i32, b: [u8; 4]| {
- let qpav = (qpp + qpq + 1) >> 1;
- let index_a = (qpav + alpha_off).clamp(0, 51) as usize;
- let index_b = (qpav + beta_off).clamp(0, 51) as usize;
- let tc = |b: u8| if (1..4).contains(&b) { TC0[index_a][b as usize - 1] as i32 } else { 0 };
- EdgeParams { bs: b, tc0: [tc(b[0]), tc(b[1]), tc(b[2]), tc(b[3])], alpha: ALPHA[index_a] as i32, beta: BETA[index_b] as i32 }
- };
- let width = pic.planes.width;
- let cwidth = pic.planes.cwidth;
- // luma
+ bs
+}
+
+/// Slice-level filter offsets (`FilterOffsetA` / `FilterOffsetB`).
+#[derive(Clone, Copy)]
+struct FilterOffsets {
+ alpha: i32,
+ beta: i32,
+}
+
+/// Edge filter parameters for neighbouring QPs `qpp` / `qpq` (8.7.2.2).
+fn edge_params(qpp: i32, qpq: i32, b: [u8; 4], off: FilterOffsets) -> EdgeParams {
+ let qpav = (qpp + qpq + 1) >> 1;
+ let index_a = (qpav + off.alpha).clamp(0, 51) as usize;
+ let index_b = (qpav + off.beta).clamp(0, 51) as usize;
+ let tc = |b: u8| if (1..4).contains(&b) { TC0[index_a][b as usize - 1] as i32 } else { 0 };
+ EdgeParams { bs: b, tc0: [tc(b[0]), tc(b[1]), tc(b[2]), tc(b[3])], alpha: ALPHA[index_a] as i32, beta: BETA[index_b] as i32 }
+}
+
+/// Everything the per-plane edge filters need to know about one macroblock.
+struct MbEdges {
+ bs: MbBs,
+ offsets: FilterOffsets,
+ mx: usize,
+ my: usize,
+ q_qp: i32,
+ q_qpc: [u8; 2],
+ /// (luma QP, chroma QPs) of the left and top neighbours.
+ p_qp: [Option<(i32, [u8; 2])>; 2],
+}
+
+/// Filter the luma edges of one macroblock.
+fn filter_luma_edges(planes: &mut Planes, m: &MbEdges) {
+ let width = planes.width;
for dir in 0..2 {
for e in 0..4 {
- if bs[dir][e] == [0; 4] {
+ if m.bs[dir][e] == [0; 4] {
continue;
}
- let qpp = if e == 0 { p_qp[dir].map(|p| p.0).unwrap_or(q_qp) } else { q_qp };
- let ep = params(qpp, q_qp, bs[dir][e]);
+ let qpp = if e == 0 { m.p_qp[dir].map(|p| p.0).unwrap_or(m.q_qp) } else { m.q_qp };
+ let ep = edge_params(qpp, m.q_qp, m.bs[dir][e], m.offsets);
if ep.alpha == 0 || ep.beta == 0 {
// filterSamplesFlag needs |p0 - q0| < alpha and |p1 - p0| < beta (8.7.2.2): no
// sample of the edge changes (low QPs)
continue;
}
if dir == 0 {
- filter_vertical::<16>(&mut pic.planes.y, width, mx * 16 + e * 4, my * 16, &ep, false);
+ filter_vertical::<16>(&mut planes.y, width, m.mx * 16 + e * 4, m.my * 16, &ep, false);
} else {
- filter_horizontal::<16>(&mut pic.planes.y, width, mx * 16, my * 16 + e * 4, &ep, false);
+ filter_horizontal::<16>(&mut planes.y, width, m.mx * 16, m.my * 16 + e * 4, &ep, false);
}
}
}
- // chroma (4:2:0): edges at chroma samples 0 and 4 use the bS of luma edges 0 and 2
+}
+
+/// Filter the chroma (4:2:0) edges of one macroblock: edges at chroma samples 0 and 4 use the bS of
+/// luma edges 0 and 2.
+fn filter_chroma_edges(planes: &mut Planes, m: &MbEdges) {
+ let cwidth = planes.cwidth;
for c in 0..2 {
for dir in 0..2 {
for ce in 0..2 {
let e = ce * 2;
- if bs[dir][e] == [0; 4] {
+ if m.bs[dir][e] == [0; 4] {
continue;
}
- let qpp = if e == 0 { p_qp[dir].map(|p| p.1[c]).unwrap_or(q_qpc[c]) } else { q_qpc[c] } as i32;
- let ep = params(qpp, q_qpc[c] as i32, bs[dir][e]);
+ let qpp = if e == 0 { m.p_qp[dir].map(|p| p.1[c]).unwrap_or(m.q_qpc[c]) } else { m.q_qpc[c] } as i32;
+ let ep = edge_params(qpp, m.q_qpc[c] as i32, m.bs[dir][e], m.offsets);
if ep.alpha == 0 || ep.beta == 0 {
continue;
}
- let plane = if c == 0 { &mut pic.planes.cb } else { &mut pic.planes.cr };
+ let plane = if c == 0 { &mut planes.cb } else { &mut planes.cr };
if dir == 0 {
- filter_vertical::<8>(plane, cwidth, mx * 8 + ce * 4, my * 8, &ep, true);
+ filter_vertical::<8>(plane, cwidth, m.mx * 8 + ce * 4, m.my * 8, &ep, true);
} else {
- filter_horizontal::<8>(plane, cwidth, mx * 8, my * 8 + ce * 4, &ep, true);
+ filter_horizontal::<8>(plane, cwidth, m.mx * 8, m.my * 8 + ce * 4, &ep, true);
}
}
}
}
}
+/// Deblock one macroblock (macroblocks must be processed in raster order).
+pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) {
+ let q = &pic.mbs[addr];
+ if q.slice_num == u32::MAX {
+ return;
+ }
+ let sq = &pic.slices[q.slice_num as usize];
+ if sq.disable_deblocking_filter_idc == 1 {
+ return;
+ }
+ let (mx, my) = (addr % mb_w, addr / mb_w);
+ let usable = |n: Option<usize>| -> Option<usize> {
+ let n = n?;
+ let st = &pic.mbs[n];
+ if st.slice_num == u32::MAX || (sq.disable_deblocking_filter_idc == 2 && st.slice_num != q.slice_num) {
+ return None;
+ }
+ Some(n)
+ };
+ let left = usable(if mx > 0 { Some(addr - 1) } else { None });
+ let top = usable(if my > 0 { Some(addr - mb_w) } else { None });
+ let bs = if q.kind.is_intra() { intra_mb_bs(q.transform_8x8, left, top) } else { inter_mb_bs(pic, q, sq, left, top) };
+ let qp_of = |st: &MbState| if st.kind == MbKind::IPcm { 0 } else { st.qp as i32 };
+ let neighbor_qp = |n: Option<usize>| n.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc));
+ let edges = MbEdges {
+ bs,
+ offsets: FilterOffsets { alpha: sq.alpha_offset, beta: sq.beta_offset },
+ mx,
+ my,
+ q_qp: qp_of(q),
+ q_qpc: q.qpc,
+ p_qp: [neighbor_qp(left), neighbor_qp(top)],
+ };
+ filter_luma_edges(&mut pic.planes, &edges);
+ filter_chroma_edges(&mut pic.planes, &edges);
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/h264/src/decoder.rs b/crates/h264/src/decoder.rs
index 135ebfa59..0bfbe0e6f 100644
--- a/crates/h264/src/decoder.rs
+++ b/crates/h264/src/decoder.rs
@@ -484,7 +484,7 @@ impl Decoder {
let meta = Arc::new(OutputMeta { draft, ..output_meta(&sps, pts, key) });
let mut outs = Vec::new();
let fpoc = frame.poc;
- self.dpb.store_picture(&first, frame, fpoc, sps.max_frame_num(), sps.max_num_ref_frames as usize, meta, &mut outs)?;
+ self.dpb.store_picture(&first, frame, fpoc, (sps.max_frame_num(), sps.max_num_ref_frames as usize), meta, &mut outs)?;
self.emit(outs);
Ok(())
}
diff --git a/crates/h264/src/dpb.rs b/crates/h264/src/dpb.rs
index c712b0424..f8b0183bc 100644
--- a/crates/h264/src/dpb.rs
+++ b/crates/h264/src/dpb.rs
@@ -127,7 +127,6 @@ impl<F: Clone> Dpb<F> {
/// Insert "non-existing" frames for a frame_num gap (8.2.5.2). `make_frame` gives each one's
/// picture and POC.
- #[allow(clippy::too_many_arguments)]
pub fn fill_frame_num_gap(
&mut self,
prev_ref_frame_num: u32,
@@ -340,14 +339,12 @@ impl<F: Clone> Dpb<F> {
/// Reference marking for the just-decoded picture and insertion into the DPB with output bumping.
/// Returns pictures ready for output.
- #[allow(clippy::too_many_arguments)]
pub fn store_picture(
&mut self,
sh: &SliceHeader,
frame: F,
poc: i32,
- max_frame_num: u32,
- max_num_ref_frames: usize,
+ (max_frame_num, max_num_ref_frames): (u32, usize),
meta: Arc<OutputMeta>,
out: &mut Vec<Output<F>>,
) -> Result<()> {
diff --git a/crates/h264/src/inter.rs b/crates/h264/src/inter.rs
index 030d5ddd0..487f013dc 100644
--- a/crates/h264/src/inter.rs
+++ b/crates/h264/src/inter.rs
@@ -93,8 +93,8 @@ fn vtap_row(rows: [&[u8]; 6], out: &mut [i32], n: usize) {
/// Luma sample interpolation for a bw x bh block (8.4.2.2.1). (x, y) is the integer sample position
/// (block position + (mv >> 2)); (fx, fy) the quarter-sample fraction. Output stride is `os`.
#[cfg(test)]
-#[allow(clippy::too_many_arguments)]
-pub fn mc_luma(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: usize, out: &mut [u8], os: usize) {
+pub fn mc_luma(p: PlaneRef, x: i32, y: i32, blk: McBlock, out: &mut [u8], os: usize) {
+ let McBlock { bw, bh, .. } = blk;
let mut win = [0u8; WIN * WIN];
let (x0, y0) = (x - 2, y - 2);
let inside = x0 >= 0 && y0 >= 0 && x0 as usize + bw + 5 <= p.width && y0 as usize + bh + 5 <= p.height;
@@ -104,13 +104,13 @@ pub fn mc_luma(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: usi
fetch_window(p, x, y, bw, bh, &mut win);
(&win[..], WIN)
};
- mc_luma_win(src, ss, fx, fy, bw, bh, out, os);
+ mc_luma_win(src, ss, blk, out, os);
}
/// Luma interpolation from a prepared window: `src[0]` is the sample at (x - 2, y - 2) and `ss` the
/// window stride; the window covers (bw + 5) x (bh + 5) samples.
-#[allow(clippy::too_many_arguments)]
-pub fn mc_luma_win(src: &[u8], ss: usize, fx: u32, fy: u32, bw: usize, bh: usize, out: &mut [u8], os: usize) {
+pub fn mc_luma_win(src: &[u8], ss: usize, blk: McBlock, out: &mut [u8], os: usize) {
+ let McBlock { fx, fy, bw, bh } = blk;
// window row r (0..bh+5) starts at src[r * ss]; sample G of block (r, c) is at window (r + 2, c + 2)
let wrow = |r: usize| &src[r * ss..r * ss + bw + 5];
let mut t = [0i32; 16];
@@ -218,8 +218,8 @@ pub fn mc_luma_win(src: &[u8], ss: usize, fx: u32, fy: u32, bw: usize, bh: usize
/// Chroma sample interpolation (8.4.2.2.2) for a bw x bh block at integer position (x, y) with
/// eighth-sample fraction (fx, fy).
#[cfg(test)]
-#[allow(clippy::too_many_arguments)]
-pub fn mc_chroma(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: usize, out: &mut [u8], os: usize) {
+pub fn mc_chroma(p: PlaneRef, x: i32, y: i32, blk: McBlock, out: &mut [u8], os: usize) {
+ let McBlock { bw, bh, .. } = blk;
let maxx = p.width as i32 - 1;
let maxy = p.height as i32 - 1;
let inside = x >= 0 && y >= 0 && x + bw as i32 <= maxx && y + bh as i32 <= maxy;
@@ -236,13 +236,13 @@ pub fn mc_chroma(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: u
}
(&win[..], 9)
};
- mc_chroma_win(src, ss, fx, fy, bw, bh, out, os);
+ mc_chroma_win(src, ss, blk, out, os);
}
/// Chroma interpolation from a prepared (bw + 1) x (bh + 1) window whose first sample is the integer
/// position of the block.
-#[allow(clippy::too_many_arguments)]
-pub fn mc_chroma_win(src: &[u8], ss: usize, fx: u32, fy: u32, bw: usize, bh: usize, out: &mut [u8], os: usize) {
+pub fn mc_chroma_win(src: &[u8], ss: usize, blk: McBlock, out: &mut [u8], os: usize) {
+ let McBlock { fx, fy, bw, bh } = blk;
let (fx, fy) = (fx as u16, fy as u16);
let (w00, w10, w01, w11) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy);
if fx == 0 && fy == 0 {
@@ -262,6 +262,15 @@ pub fn mc_chroma_win(src: &[u8], ss: usize, fx: u32, fy: u32, bw: usize, bh: usi
}
}
+/// Fractional offset and size of one motion-compensated block.
+#[derive(Clone, Copy, Debug)]
+pub struct McBlock {
+ pub fx: u32,
+ pub fy: u32,
+ pub bw: usize,
+ pub bh: usize,
+}
+
/// Weights for one prediction direction or pair.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Weight {
@@ -272,8 +281,7 @@ pub enum Weight {
}
/// Combine prediction(s) into `dst` (stride `ds`). `p0`/`p1` have stride `ps`.
-#[allow(clippy::too_many_arguments)]
-pub fn weighted_store(dst: &mut [u8], ds: usize, p0: Option<&[u8]>, p1: Option<&[u8]>, ps: usize, bw: usize, bh: usize, w: Weight) {
+pub fn weighted_store(dst: &mut [u8], ds: usize, p0: Option<&[u8]>, p1: Option<&[u8]>, ps: usize, (bw, bh): (usize, usize), w: Weight) {
match (p0, p1, w) {
(Some(a), Some(b), Weight::Default) => {
for r in 0..bh {
@@ -328,8 +336,8 @@ mod reference {
/// Luma sample interpolation for a bw x bh block. (x, y) is the integer sample position
/// (block position + (mv >> 2)); (fx, fy) the quarter-sample fraction. Output stride is `os`.
- #[allow(clippy::too_many_arguments)]
- pub fn mc_luma_ref(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: usize, out: &mut [u8], os: usize) {
+ pub fn mc_luma_ref(p: PlaneRef, x: i32, y: i32, blk: McBlock, out: &mut [u8], os: usize) {
+ let McBlock { fx, fy, bw, bh } = blk;
let mut win = [0u8; WIN * WIN];
fetch_window(p, x, y, bw, bh, &mut win);
// sample G at (r, c) in block coordinates is win[(r + 2) * WIN + c + 2]
@@ -441,10 +449,10 @@ mod tests {
let d = plane(16, 16, |x, y| (x + 16 * y) as u8);
let p = PlaneRef { data: &d, width: 16, height: 16, stride: 16 };
let mut out = [0u8; 16];
- mc_luma(p, 2, 3, 0, 0, 4, 4, &mut out, 4);
+ mc_luma(p, 2, 3, McBlock { fx: 0, fy: 0, bw: 4, bh: 4 }, &mut out, 4);
assert_eq!(&out[..4], &[50, 51, 52, 53]);
// clamped: far outside to the top-left gives sample (0,0)
- mc_luma(p, -40, -40, 0, 0, 4, 4, &mut out, 4);
+ mc_luma(p, -40, -40, McBlock { fx: 0, fy: 0, bw: 4, bh: 4 }, &mut out, 4);
assert!(out.iter().all(|&v| v == 0));
}
@@ -455,9 +463,9 @@ mod tests {
for fx in 0..4 {
for fy in 0..4 {
let mut out = [0u8; 64];
- mc_luma(p, 8, 8, fx, fy, 8, 8, &mut out, 8);
+ mc_luma(p, 8, 8, McBlock { fx, fy, bw: 8, bh: 8 }, &mut out, 8);
assert!(out.iter().all(|&v| v == 100), "{fx},{fy}");
- mc_chroma(p, 8, 8, fx * 2, fy * 2, 8, 8, &mut out, 8);
+ mc_chroma(p, 8, 8, McBlock { fx: fx * 2, fy: fy * 2, bw: 8, bh: 8 }, &mut out, 8);
assert!(out.iter().all(|&v| v == 100));
}
}
@@ -469,9 +477,9 @@ mod tests {
let d = plane(32, 32, |x, _| (x * 4) as u8);
let p = PlaneRef { data: &d, width: 32, height: 32, stride: 32 };
let mut out = [0u8; 16];
- mc_luma(p, 8, 8, 2, 0, 4, 4, &mut out, 4);
+ mc_luma(p, 8, 8, McBlock { fx: 2, fy: 0, bw: 4, bh: 4 }, &mut out, 4);
assert_eq!(&out[..4], &[34, 38, 42, 46]);
- mc_luma(p, 8, 8, 1, 0, 4, 4, &mut out, 4);
+ mc_luma(p, 8, 8, McBlock { fx: 1, fy: 0, bw: 4, bh: 4 }, &mut out, 4);
assert_eq!(&out[..4], &[33, 37, 41, 45]);
}
@@ -491,8 +499,8 @@ mod tests {
for &(x, y) in &[(10, 9), (-3, -5), (30, 30), (0, 0), (2, 2), (38, 1)] {
let mut a = [0u8; 256];
let mut b = [0u8; 256];
- mc_luma(p, x, y, fx, fy, bw, bh, &mut a, 16);
- reference::mc_luma_ref(p, x, y, fx, fy, bw, bh, &mut b, 16);
+ mc_luma(p, x, y, McBlock { fx, fy, bw, bh }, &mut a, 16);
+ reference::mc_luma_ref(p, x, y, McBlock { fx, fy, bw, bh }, &mut b, 16);
assert_eq!(a, b, "{bw}x{bh} frac {fx},{fy} at {x},{y}");
}
}
@@ -505,9 +513,9 @@ mod tests {
let a = [100u8; 4];
let b = [50u8; 4];
let mut d = [0u8; 4];
- weighted_store(&mut d, 4, Some(&a), Some(&b), 4, 4, 1, Weight::Default);
+ weighted_store(&mut d, 4, Some(&a), Some(&b), 4, (4, 1), Weight::Default);
assert_eq!(d, [75; 4]);
- weighted_store(&mut d, 4, Some(&a), None, 4, 4, 1, Weight::Weighted { log_wd: 5, w0: 16, w1: 0, o0: 3, o1: 0 });
+ weighted_store(&mut d, 4, Some(&a), None, 4, (4, 1), Weight::Weighted { log_wd: 5, w0: 16, w1: 0, o0: 3, o1: 0 });
assert_eq!(d, [53; 4]);
}
}
diff --git a/crates/h264/src/intra.rs b/crates/h264/src/intra.rs
index decf29658..bf8abfe95 100644
--- a/crates/h264/src/intra.rs
+++ b/crates/h264/src/intra.rs
@@ -59,128 +59,109 @@ fn load_edge(plane: &[u8], stride: usize, x: usize, y: usize, n: usize, a: Avail
e
}
+/// Fill an `n`x`n` block at `out` with `f(x, y)`.
+fn fill_nxn(n: i32, out: &mut [u8], stride: usize, f: impl Fn(i32, i32) -> i32) {
+ for y in 0..n {
+ for x in 0..n {
+ out[y as usize * stride + x as usize] = f(x, y) as u8;
+ }
+ }
+}
+
+/// DC value of Intra_NxN prediction (mode 2).
+fn dc_nxn(e: &Edge, n: i32, a: Avail) -> i32 {
+ let shift = if n == 4 { 2 } else { 3 };
+ let st: i32 = (0..n).map(|x| e.t(x)).sum();
+ let sl: i32 = (0..n).map(|y| e.l(y)).sum();
+ match (a.top, a.left) {
+ (true, true) => (st + sl + n) >> (shift + 1),
+ (false, true) => (sl + (n >> 1)) >> shift,
+ (true, false) => (st + (n >> 1)) >> shift,
+ _ => 128,
+ }
+}
+
+/// Diagonal down-left sample (mode 3).
+fn diag_down_left(e: &Edge, n: i32, x: i32, y: i32) -> i32 {
+ if x == n - 1 && y == n - 1 { (e.t(2 * n - 2) + 3 * e.t(2 * n - 1) + 2) >> 2 } else { (e.t(x + y) + 2 * e.t(x + y + 1) + e.t(x + y + 2) + 2) >> 2 }
+}
+
+/// Diagonal down-right sample (mode 4).
+fn diag_down_right(e: &Edge, x: i32, y: i32) -> i32 {
+ if x > y {
+ (e.t(x - y - 2) + 2 * e.t(x - y - 1) + e.t(x - y) + 2) >> 2
+ } else if x < y {
+ (e.l(y - x - 2) + 2 * e.l(y - x - 1) + e.l(y - x) + 2) >> 2
+ } else {
+ (e.t(0) + 2 * e.tl + e.l(0) + 2) >> 2
+ }
+}
+
+/// Vertical-right sample (mode 5).
+fn vertical_right(e: &Edge, x: i32, y: i32) -> i32 {
+ let z = 2 * x - y;
+ if z >= 0 && z % 2 == 0 {
+ (e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 1) >> 1
+ } else if z > 0 {
+ (e.t(x - (y >> 1) - 2) + 2 * e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 2) >> 2
+ } else if z == -1 {
+ (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2
+ } else {
+ (e.l(y - 2 * x - 1) + 2 * e.l(y - 2 * x - 2) + e.l(y - 2 * x - 3) + 2) >> 2
+ }
+}
+
+/// Horizontal-down sample (mode 6).
+fn horizontal_down(e: &Edge, x: i32, y: i32) -> i32 {
+ let z = 2 * y - x;
+ if z >= 0 && z % 2 == 0 {
+ (e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 1) >> 1
+ } else if z > 0 {
+ (e.l(y - (x >> 1) - 2) + 2 * e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 2) >> 2
+ } else if z == -1 {
+ (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2
+ } else {
+ (e.t(x - 2 * y - 1) + 2 * e.t(x - 2 * y - 2) + e.t(x - 2 * y - 3) + 2) >> 2
+ }
+}
+
+/// Vertical-left sample (mode 7).
+fn vertical_left(e: &Edge, x: i32, y: i32) -> i32 {
+ let i = x + (y >> 1);
+ if y % 2 == 0 { (e.t(i) + e.t(i + 1) + 1) >> 1 } else { (e.t(i) + 2 * e.t(i + 1) + e.t(i + 2) + 2) >> 2 }
+}
+
+/// Horizontal-up sample (mode 8).
+fn horizontal_up(e: &Edge, n: i32, x: i32, y: i32) -> i32 {
+ let zmax = 2 * n - 3;
+ let z = x + 2 * y;
+ let i = y + (x >> 1);
+ if z < zmax && z % 2 == 0 {
+ (e.l(i) + e.l(i + 1) + 1) >> 1
+ } else if z < zmax {
+ (e.l(i) + 2 * e.l(i + 1) + e.l(i + 2) + 2) >> 2
+ } else if z == zmax {
+ (e.l(n - 2) + 3 * e.l(n - 1) + 2) >> 2
+ } else {
+ e.l(n - 1)
+ }
+}
+
/// Directional / DC prediction shared by Intra_4x4 and Intra_8x8 (8.3.1.2.x, 8.3.2.2.x).
fn pred_nxn(mode: u8, e: &Edge, n: i32, a: Avail, out: &mut [u8], stride: usize) {
- let mut put = |x: i32, y: i32, v: i32| out[y as usize * stride + x as usize] = v as u8;
match mode {
- 0 => {
- for y in 0..n {
- for x in 0..n {
- put(x, y, e.t(x));
- }
- }
- }
- 1 => {
- for y in 0..n {
- for x in 0..n {
- put(x, y, e.l(y));
- }
- }
- }
+ 0 => fill_nxn(n, out, stride, |x, _| e.t(x)),
+ 1 => fill_nxn(n, out, stride, |_, y| e.l(y)),
2 => {
- let shift = if n == 4 { 2 } else { 3 };
- let st: i32 = (0..n).map(|x| e.t(x)).sum();
- let sl: i32 = (0..n).map(|y| e.l(y)).sum();
- let dc = match (a.top, a.left) {
- (true, true) => (st + sl + n) >> (shift + 1),
- (false, true) => (sl + (n >> 1)) >> shift,
- (true, false) => (st + (n >> 1)) >> shift,
- _ => 128,
- };
- for y in 0..n {
- for x in 0..n {
- put(x, y, dc);
- }
- }
- }
- 3 => {
- for y in 0..n {
- for x in 0..n {
- let v = if x == n - 1 && y == n - 1 {
- (e.t(2 * n - 2) + 3 * e.t(2 * n - 1) + 2) >> 2
- } else {
- (e.t(x + y) + 2 * e.t(x + y + 1) + e.t(x + y + 2) + 2) >> 2
- };
- put(x, y, v);
- }
- }
- }
- 4 => {
- for y in 0..n {
- for x in 0..n {
- let v = if x > y {
- (e.t(x - y - 2) + 2 * e.t(x - y - 1) + e.t(x - y) + 2) >> 2
- } else if x < y {
- (e.l(y - x - 2) + 2 * e.l(y - x - 1) + e.l(y - x) + 2) >> 2
- } else {
- (e.t(0) + 2 * e.tl + e.l(0) + 2) >> 2
- };
- put(x, y, v);
- }
- }
- }
- 5 => {
- for y in 0..n {
- for x in 0..n {
- let z = 2 * x - y;
- let v = if z >= 0 && z % 2 == 0 {
- (e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 1) >> 1
- } else if z > 0 {
- (e.t(x - (y >> 1) - 2) + 2 * e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 2) >> 2
- } else if z == -1 {
- (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2
- } else {
- (e.l(y - 2 * x - 1) + 2 * e.l(y - 2 * x - 2) + e.l(y - 2 * x - 3) + 2) >> 2
- };
- put(x, y, v);
- }
- }
- }
- 6 => {
- for y in 0..n {
- for x in 0..n {
- let z = 2 * y - x;
- let v = if z >= 0 && z % 2 == 0 {
- (e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 1) >> 1
- } else if z > 0 {
- (e.l(y - (x >> 1) - 2) + 2 * e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 2) >> 2
- } else if z == -1 {
- (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2
- } else {
- (e.t(x - 2 * y - 1) + 2 * e.t(x - 2 * y - 2) + e.t(x - 2 * y - 3) + 2) >> 2
- };
- put(x, y, v);
- }
- }
- }
- 7 => {
- for y in 0..n {
- for x in 0..n {
- let i = x + (y >> 1);
- let v = if y % 2 == 0 { (e.t(i) + e.t(i + 1) + 1) >> 1 } else { (e.t(i) + 2 * e.t(i + 1) + e.t(i + 2) + 2) >> 2 };
- put(x, y, v);
- }
- }
- }
- _ => {
- let zmax = 2 * n - 3;
- for y in 0..n {
- for x in 0..n {
- let z = x + 2 * y;
- let i = y + (x >> 1);
- let v = if z < zmax && z % 2 == 0 {
- (e.l(i) + e.l(i + 1) + 1) >> 1
- } else if z < zmax {
- (e.l(i) + 2 * e.l(i + 1) + e.l(i + 2) + 2) >> 2
- } else if z == zmax {
- (e.l(n - 2) + 3 * e.l(n - 1) + 2) >> 2
- } else {
- e.l(n - 1)
- };
- put(x, y, v);
- }
- }
+ let dc = dc_nxn(e, n, a);
+ fill_nxn(n, out, stride, |_, _| dc);
}
+ 3 => fill_nxn(n, out, stride, |x, y| diag_down_left(e, n, x, y)),
+ 4 => fill_nxn(n, out, stride, |x, y| diag_down_right(e, x, y)),
+ 5 => fill_nxn(n, out, stride, |x, y| vertical_right(e, x, y)),
+ 6 => fill_nxn(n, out, stride, |x, y| horizontal_down(e, x, y)),
+ 7 => fill_nxn(n, out, stride, |x, y| vertical_left(e, x, y)),
+ _ => fill_nxn(n, out, stride, |x, y| horizontal_up(e, n, x, y)),
}
}
diff --git a/crates/h264/src/lib.rs b/crates/h264/src/lib.rs
index c70e8b0fb..361321b5a 100644
--- a/crates/h264/src/lib.rs
+++ b/crates/h264/src/lib.rs
@@ -15,8 +15,6 @@
//! }
//! ```
-// Index loops over fixed-size blocks read more clearly than iterator chains in codec code.
-#![allow(clippy::needless_range_loop, clippy::too_many_arguments)]
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
mod cabac;
diff --git a/crates/h264/src/params.rs b/crates/h264/src/params.rs
index 236b7b928..c0cda1adb 100644
--- a/crates/h264/src/params.rs
+++ b/crates/h264/src/params.rs
@@ -1,7 +1,7 @@
//! Sequence and picture parameter sets (7.3.2.1, 7.3.2.2) including VUI and scaling lists.
use crate::error::{Result, ensure, unsupported};
-use crate::tables::*;
+use crate::tables::{DEFAULT_4X4_INTER, DEFAULT_4X4_INTRA, DEFAULT_8X8_INTER, DEFAULT_8X8_INTRA, ZIGZAG4, ZIGZAG8};
use filmcraft_bitstream::BitReader;
/// Maximum supported reconstructed luma area. 8K UHD fits comfortably while
diff --git a/crates/h264/src/picture.rs b/crates/h264/src/picture.rs
index 65a34d650..6ff9bb191 100644
--- a/crates/h264/src/picture.rs
+++ b/crates/h264/src/picture.rs
@@ -229,7 +229,7 @@ impl Frame {
/// Copy the w x h luma window at (x0, y0) (clamped to the picture) into `out` (stride `os`).
#[inline]
- pub fn luma_window(&self, x0: i32, y0: i32, w: usize, h: usize, out: &mut [u8], os: usize) {
+ pub fn luma_window(&self, (x0, y0): (i32, i32), w: usize, h: usize, out: &mut [u8], os: usize) {
let (width, height) = (self.width, self.height);
for r in 0..h {
let yy = (y0 + r as i32).clamp(0, height as i32 - 1) as usize;
@@ -241,7 +241,7 @@ impl Frame {
/// Copy the w x h window of chroma component `c` at (x0, y0) (clamped) into `out`.
#[inline]
- pub fn chroma_window(&self, c: usize, x0: i32, y0: i32, w: usize, h: usize, out: &mut [u8], os: usize) {
+ pub fn chroma_window(&self, c: usize, (x0, y0): (i32, i32), w: usize, h: usize, out: &mut [u8], os: usize) {
let (cw, ch) = (self.cwidth, self.cheight);
for r in 0..h {
let yy = (y0 + r as i32).clamp(0, ch as i32 - 1) as usize;
diff --git a/crates/h264/src/slice.rs b/crates/h264/src/slice.rs
index f832bc9d6..e7a7cd803 100644
--- a/crates/h264/src/slice.rs
+++ b/crates/h264/src/slice.rs
@@ -150,6 +150,95 @@ impl SliceHeader {
self.mmcos.iter().any(|m| m.op == 5)
}
+ /// ref_pic_list_modification() for both lists (7.3.3.1).
+ fn parse_ref_pic_list_mods(r: &mut BitReader, slice_type: SliceType) -> Result<[Vec<RefPicListMod>; 2]> {
+ let mut ref_pic_list_mod = [Vec::new(), Vec::new()];
+ for (list, mods) in ref_pic_list_mod.iter_mut().enumerate() {
+ let present = if list == 0 { !slice_type.is_intra() } else { slice_type.is_b() };
+ if present && r.read_flag()? {
+ loop {
+ let idc = r.read_ue()?;
+ ensure!(idc <= 5, "modification_of_pic_nums_idc out of range");
+ if idc == 3 {
+ break;
+ }
+ let value = r.read_ue()?;
+ mods.push(RefPicListMod { idc, value });
+ ensure!(mods.len() <= 66, "too many ref_pic_list_modification entries");
+ }
+ }
+ }
+ Ok(ref_pic_list_mod)
+ }
+
+ /// One pred_weight_table() entry (7.3.3.2).
+ fn parse_weight_entry(r: &mut BitReader, has_chroma: bool, luma_log2_denom: u32, chroma_log2_denom: u32) -> Result<WeightEntry> {
+ let mut e = WeightEntry { luma_weight: 1 << luma_log2_denom, chroma_weight: [1 << chroma_log2_denom; 2], ..Default::default() };
+ if r.read_flag()? {
+ e.luma_flag = true;
+ e.luma_weight = r.read_se()?;
+ e.luma_offset = r.read_se()?;
+ ensure!((-128..=127).contains(&e.luma_weight) && (-128..=127).contains(&e.luma_offset), "luma weight out of range");
+ }
+ if has_chroma && r.read_flag()? {
+ e.chroma_flag = true;
+ for j in 0..2 {
+ e.chroma_weight[j] = r.read_se()?;
+ e.chroma_offset[j] = r.read_se()?;
+ ensure!((-128..=127).contains(&e.chroma_weight[j]) && (-128..=127).contains(&e.chroma_offset[j]), "chroma weight out of range");
+ }
+ }
+ Ok(e)
+ }
+
+ /// pred_weight_table() (7.3.3.2).
+ fn parse_pred_weight_table(r: &mut BitReader, sps: &Sps, slice_type: SliceType, num_ref_idx_active: [u32; 2]) -> Result<PredWeightTable> {
+ let luma_log2_denom = r.read_ue()?;
+ ensure!(luma_log2_denom <= 7, "luma_log2_weight_denom out of range");
+ let has_chroma = sps.chroma_array_type() != 0;
+ let mut chroma_log2_denom = 0;
+ if has_chroma {
+ chroma_log2_denom = r.read_ue()?;
+ ensure!(chroma_log2_denom <= 7, "chroma_log2_weight_denom out of range");
+ }
+ let mut lists = [Vec::new(), Vec::new()];
+ let nlists = if slice_type.is_b() { 2 } else { 1 };
+ for (l, entries) in lists.iter_mut().enumerate().take(nlists) {
+ for _ in 0..num_ref_idx_active[l] {
+ entries.push(Self::parse_weight_entry(r, has_chroma, luma_log2_denom, chroma_log2_denom)?);
+ }
+ }
+ let [l0, l1] = lists;
+ Ok(PredWeightTable { luma_log2_denom, chroma_log2_denom, l0, l1 })
+ }
+
+ /// The memory_management_control_operation list of dec_ref_pic_marking() (7.3.3.3).
+ fn parse_mmcos(r: &mut BitReader) -> Result<Vec<Mmco>> {
+ let mut mmcos = Vec::new();
+ loop {
+ let op = r.read_ue()?;
+ ensure!(op <= 6, "memory_management_control_operation out of range");
+ if op == 0 {
+ return Ok(mmcos);
+ }
+ let mut m = Mmco { op, difference_of_pic_nums_minus1: 0, long_term_pic_num: 0, long_term_frame_idx: 0, max_long_term_frame_idx_plus1: 0 };
+ if op == 1 || op == 3 {
+ m.difference_of_pic_nums_minus1 = r.read_ue()?;
+ }
+ if op == 2 {
+ m.long_term_pic_num = r.read_ue()?;
+ }
+ if op == 3 || op == 6 {
+ m.long_term_frame_idx = r.read_ue()?;
+ }
+ if op == 4 {
+ m.max_long_term_frame_idx_plus1 = r.read_ue()?;
+ }
+ mmcos.push(m);
+ ensure!(mmcos.len() <= 66, "too many MMCOs");
+ }
+ }
+
/// Parse the slice header. `pps_lookup` resolves pic_parameter_set_id to (PPS, SPS).
pub fn parse<'a>(rbsp: &[u8], nal: NalHeader, pps_lookup: impl FnOnce(u32) -> Result<(&'a Pps, &'a Sps)>) -> Result<(SliceHeader, &'a Pps, &'a Sps)> {
let mut r = BitReader::new(rbsp);
@@ -210,55 +299,10 @@ impl SliceHeader {
num_ref_idx_active[0] = 0;
}
ensure!(nal.nal_unit_type != 20 && nal.nal_unit_type != 21, "MVC slices are not supported");
- let mut ref_pic_list_mod = [Vec::new(), Vec::new()];
- for (list, mods) in ref_pic_list_mod.iter_mut().enumerate() {
- let present = if list == 0 { !slice_type.is_intra() } else { slice_type.is_b() };
- if present && r.read_flag()? {
- loop {
- let idc = r.read_ue()?;
- ensure!(idc <= 5, "modification_of_pic_nums_idc out of range");
- if idc == 3 {
- break;
- }
- let value = r.read_ue()?;
- mods.push(RefPicListMod { idc, value });
- ensure!(mods.len() <= 66, "too many ref_pic_list_modification entries");
- }
- }
- }
+ let ref_pic_list_mod = Self::parse_ref_pic_list_mods(&mut r, slice_type)?;
let mut pred_weight_table = None;
if (pps.weighted_pred && slice_type.is_p()) || (pps.weighted_bipred_idc == 1 && slice_type.is_b()) {
- let luma_log2_denom = r.read_ue()?;
- ensure!(luma_log2_denom <= 7, "luma_log2_weight_denom out of range");
- let mut chroma_log2_denom = 0;
- if sps.chroma_array_type() != 0 {
- chroma_log2_denom = r.read_ue()?;
- ensure!(chroma_log2_denom <= 7, "chroma_log2_weight_denom out of range");
- }
- let mut lists = [Vec::new(), Vec::new()];
- let nlists = if slice_type.is_b() { 2 } else { 1 };
- for (l, entries) in lists.iter_mut().enumerate().take(nlists) {
- for _ in 0..num_ref_idx_active[l] {
- let mut e = WeightEntry { luma_weight: 1 << luma_log2_denom, chroma_weight: [1 << chroma_log2_denom; 2], ..Default::default() };
- if r.read_flag()? {
- e.luma_flag = true;
- e.luma_weight = r.read_se()?;
- e.luma_offset = r.read_se()?;
- ensure!((-128..=127).contains(&e.luma_weight) && (-128..=127).contains(&e.luma_offset), "luma weight out of range");
- }
- if sps.chroma_array_type() != 0 && r.read_flag()? {
- e.chroma_flag = true;
- for j in 0..2 {
- e.chroma_weight[j] = r.read_se()?;
- e.chroma_offset[j] = r.read_se()?;
- ensure!((-128..=127).contains(&e.chroma_weight[j]) && (-128..=127).contains(&e.chroma_offset[j]), "chroma weight out of range");
- }
- }
- entries.push(e);
- }
- }
- let [l0, l1] = lists;
- pred_weight_table = Some(PredWeightTable { luma_log2_denom, chroma_log2_denom, l0, l1 });
+ pred_weight_table = Some(Self::parse_pred_weight_table(&mut r, sps, slice_type, num_ref_idx_active)?);
}
let mut no_output_of_prior_pics = false;
let mut long_term_reference = false;
@@ -271,29 +315,7 @@ impl SliceHeader {
} else {
adaptive_ref_pic_marking = r.read_flag()?;
if adaptive_ref_pic_marking {
- loop {
- let op = r.read_ue()?;
- ensure!(op <= 6, "memory_management_control_operation out of range");
- if op == 0 {
- break;
- }
- let mut m =
- Mmco { op, difference_of_pic_nums_minus1: 0, long_term_pic_num: 0, long_term_frame_idx: 0, max_long_term_frame_idx_plus1: 0 };
- if op == 1 || op == 3 {
- m.difference_of_pic_nums_minus1 = r.read_ue()?;
- }
- if op == 2 {
- m.long_term_pic_num = r.read_ue()?;
- }
- if op == 3 || op == 6 {
- m.long_term_frame_idx = r.read_ue()?;
- }
- if op == 4 {
- m.max_long_term_frame_idx_plus1 = r.read_ue()?;
- }
- mmcos.push(m);
- ensure!(mmcos.len() <= 66, "too many MMCOs");
- }
+ mmcos = Self::parse_mmcos(&mut r)?;
}
}
}
diff --git a/crates/h264/src/slicedec.rs b/crates/h264/src/slicedec.rs
index 2d6e3c6da..631645250 100644
--- a/crates/h264/src/slicedec.rs
+++ b/crates/h264/src/slicedec.rs
@@ -3,13 +3,13 @@
use crate::cavlc;
use crate::deblock;
use crate::error::{Result, ensure, invalid};
-use crate::inter::{self, Weight};
+use crate::inter::{self, McBlock, Weight};
use crate::intra::{self, Avail};
-use crate::mbtypes::*;
+use crate::mbtypes::{CBP_ME, MbTypeInfo, Part, SubMbInfo, SubPart, b_mb_type, b_sub_mb_type, intra_mb_type, p_mb_type, p_sub_mb_type};
use crate::params::{Pps, Sps};
-use crate::picture::*;
+use crate::picture::{Frame, FrameRef, MbKind, MbState, Planes, RefPic};
use crate::slice::{SliceHeader, SliceType};
-use crate::tables::*;
+use crate::tables::{BLK4_XY, QPC_TABLE, RASTER_TO_BLK4, ZIGZAG4, ZIGZAG8};
use crate::transform::{self, LevelScale};
use filmcraft_bitstream::BitReader;
@@ -216,23 +216,22 @@ pub struct SliceDecoder<'a> {
/// Interpolate a bw x bh luma block at (px, py) with motion vector `mv` from reference `f` into `y`,
/// and the corresponding chroma blocks into `c` (stride `cs`).
-#[allow(clippy::too_many_arguments)]
#[inline]
-fn predict_block(f: &Frame, mv: [i16; 2], px: usize, py: usize, bw: usize, bh: usize, y: (&mut [u8], usize), c: [&mut [u8]; 2], cs: usize) {
+fn predict_block(f: &Frame, mv: [i16; 2], (px, py): (usize, usize), (bw, bh): (usize, usize), y: (&mut [u8], usize), c: [&mut [u8]; 2], cs: usize) {
const LW: usize = 24;
let mut win = [0u8; LW * 21];
let ix = px as i32 + (mv[0] as i32 >> 2);
let iy = py as i32 + (mv[1] as i32 >> 2);
- f.luma_window(ix - 2, iy - 2, bw + 5, bh + 5, &mut win, LW);
- inter::mc_luma_win(&win, LW, (mv[0] & 3) as u32, (mv[1] & 3) as u32, bw, bh, y.0, y.1);
+ f.luma_window((ix - 2, iy - 2), bw + 5, bh + 5, &mut win, LW);
+ inter::mc_luma_win(&win, LW, McBlock { fx: (mv[0] & 3) as u32, fy: (mv[1] & 3) as u32, bw, bh }, y.0, y.1);
let cx = (px / 2) as i32 + (mv[0] as i32 >> 3);
let cy = (py / 2) as i32 + (mv[1] as i32 >> 3);
let (cw, ch) = (bw / 2, bh / 2);
let (fx, fy) = ((mv[0] & 7) as u32, (mv[1] & 7) as u32);
for (comp, out) in c.into_iter().enumerate() {
let mut w = [0u8; 16 * 9];
- f.chroma_window(comp, cx, cy, cw + 1, ch + 1, &mut w, 16);
- inter::mc_chroma_win(&w, 16, fx, fy, cw, ch, out, cs);
+ f.chroma_window(comp, (cx, cy), cw + 1, ch + 1, &mut w, 16);
+ inter::mc_chroma_win(&w, 16, McBlock { fx, fy, bw: cw, bh: ch }, out, cs);
}
}
@@ -450,8 +449,7 @@ impl<'a> SliceDecoder<'a> {
}
/// Luma motion vector prediction (8.4.1.3). `shape`: 1 = 16x8, 2 = 8x16, 0 = other.
- #[allow(clippy::too_many_arguments)]
- fn mvp(&self, list: usize, x: usize, y: usize, w: usize, ref_idx: i8, shape: u8, part: usize) -> [i16; 2] {
+ fn mvp(&self, list: usize, (x, y): (usize, usize), w: usize, ref_idx: i8, shape: u8, part: usize) -> [i16; 2] {
let (a, b, c) = self.nb_abc(list, x, y, w);
if shape == 1 {
if part == 0 && b.ref_idx == ref_idx {
@@ -619,7 +617,7 @@ impl<'a> SliceDecoder<'a> {
let mv = if self.nb[0].is_none() || self.nb[1].is_none() || (a.ref_idx == 0 && a.mv == [0, 0]) || (b.ref_idx == 0 && b.mv == [0, 0]) {
[0, 0]
} else {
- self.mvp(0, 0, 0, 4, 0, 0, 0)
+ self.mvp(0, (0, 0), 4, 0, 0, 0)
};
self.set_motion(0, 0, 4, 4, [0, -1], [mv, [0, 0]]);
}
@@ -645,7 +643,7 @@ impl<'a> SliceDecoder<'a> {
if info.pred[p] & (1 << l) != 0 {
let r = self.cur.ref_idx[l][p];
ensure!((r as usize) < n[l], "ref_idx {r} out of range (list {l}, size {})", n[l]);
- let mvp = self.mvp(l, x, y, w, r, shape, p);
+ let mvp = self.mvp(l, (x, y), w, r, shape, p);
let d = self.cur.mvd[l][p * 4];
refs[l] = r;
mvs[l] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])];
@@ -676,7 +674,7 @@ impl<'a> SliceDecoder<'a> {
let mut mvs = [[0i16; 2]; 2];
for l in 0..2 {
if refs[l] >= 0 {
- let mvp = self.mvp(l, x, y, w, refs[l], 0, 0);
+ let mvp = self.mvp(l, (x, y), w, refs[l], 0, 0);
let d = self.cur.mvd[l][p * 4 + j];
mvs[l] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])];
}
@@ -744,7 +742,15 @@ impl<'a> SliceDecoder<'a> {
let l = if use0 { 0 } else { 1 };
let f = &self.refs[l][refs[l] as usize].frame;
let planes = &mut self.pic.planes;
- predict_block(f, mvs[l], px, py, bw, bh, (&mut planes.y[py * ys + px..], ys), [&mut planes.cb[cy * cs + cx..], &mut planes.cr[cy * cs + cx..]], cs);
+ predict_block(
+ f,
+ mvs[l],
+ (px, py),
+ (bw, bh),
+ (&mut planes.y[py * ys + px..], ys),
+ [&mut planes.cb[cy * cs + cx..], &mut planes.cr[cy * cs + cx..]],
+ cs,
+ );
return;
}
let s = &mut *self.s;
@@ -754,7 +760,7 @@ impl<'a> SliceDecoder<'a> {
}
let Some(rp) = self.refs[l].get(refs[l] as usize) else { continue };
let [pc0, pc1] = &mut s.pred_c[l];
- predict_block(&rp.frame, mvs[l], px, py, bw, bh, (&mut s.pred[l][..], 16), [&mut pc0[..], &mut pc1[..]], 8);
+ predict_block(&rp.frame, mvs[l], (px, py), (bw, bh), (&mut s.pred[l][..], 16), [&mut pc0[..], &mut pc1[..]], 8);
}
inter::weighted_store(
&mut self.pic.planes.y[py * ys + px..],
@@ -762,8 +768,7 @@ impl<'a> SliceDecoder<'a> {
if use0 { Some(&s.pred[0][..]) } else { None },
if use1 { Some(&s.pred[1][..]) } else { None },
16,
- bw,
- bh,
+ (bw, bh),
wts[0],
);
for c in 0..2 {
@@ -771,7 +776,7 @@ impl<'a> SliceDecoder<'a> {
let a = if use0 { Some(&s.pred_c[0][c][..]) } else { None };
let b = if use1 { Some(&s.pred_c[1][c][..]) } else { None };
let plane = if c == 0 { &mut self.pic.planes.cb } else { &mut self.pic.planes.cr };
- inter::weighted_store(&mut plane[cy * cs + cx..], cs, a, b, 8, bw / 2, bh / 2, wc);
+ inter::weighted_store(&mut plane[cy * cs + cx..], cs, a, b, 8, (bw / 2, bh / 2), wc);
}
}