Skip to content

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

Refactor hevc for strict Clippy checks

Dylan M. Taylor0216c8b06719
diff --git a/crates/hevc/src/decoder.rs b/crates/hevc/src/decoder.rs
index f3a56f2d7..60955970c 100644
--- a/crates/hevc/src/decoder.rs
+++ b/crates/hevc/src/decoder.rs
@@ -484,24 +484,14 @@ impl Decoder {
let Some(p) = self.pending.take() else { return };
let PendingPic { frame, sps, pps, layout, first_sh, poc, output, meta, slices, .. } = p;
let scaling = self.layout_cache.iter().find(|(pp, ss, _, _)| Arc::ptr_eq(pp, &pps) && Arc::ptr_eq(ss, &sps)).and_then(|(_, _, _, s)| s.clone());
- self.dispatch(frame.clone(), sps, pps, layout, scaling, slices, meta.draft);
+ self.dispatch(PicJob { frame: frame.clone(), sps, pps, layout, scaling, slices, draft: meta.draft });
self.poc_state.update(&first_sh, poc);
let mut outs = Vec::new();
self.dpb.insert(frame, poc, output, meta, &mut outs);
self.out_queue.extend(outs);
}
- #[allow(clippy::too_many_arguments)]
- fn dispatch(
- &mut self,
- frame: FrameRef,
- sps: Arc<Sps>,
- pps: Arc<Pps>,
- layout: Arc<Layout>,
- scaling: Option<Arc<Vec<Vec<u8>>>>,
- slices: Vec<SliceJob>,
- draft: bool,
- ) {
+ fn dispatch(&mut self, job: PicJob) {
let shared = self.shared.clone();
#[cfg(feature = "threads")]
if let Some(pool) = &self.pool {
@@ -511,17 +501,16 @@ impl Decoder {
f.wait_complete();
}
}
- self.in_flight.push_back(frame.clone());
- pool.spawn_fifo(move || run_job(frame, sps, pps, layout, scaling, slices, draft, &shared));
+ self.in_flight.push_back(job.frame.clone());
+ pool.spawn_fifo(move || run_job(job, &shared));
return;
}
- run_job(frame, sps, pps, layout, scaling, slices, draft, &shared);
+ run_job(job, &shared);
}
}
-/// Decode all slices of one picture and publish its rows, in the picture's sample type.
-#[allow(clippy::too_many_arguments)]
-fn run_job(
+/// Everything needed to decode one picture on a worker.
+struct PicJob {
frame: FrameRef,
sps: Arc<Sps>,
pps: Arc<Pps>,
@@ -529,26 +518,15 @@ fn run_job(
scaling: Option<Arc<Vec<Vec<u8>>>>,
slices: Vec<SliceJob>,
draft: bool,
- shared: &Shared,
-) {
- if stores_u8(frame.bit_depth, frame.bit_depth_c) {
- run_job_as::<u8>(frame, sps, pps, layout, scaling, slices, draft, shared)
- } else {
- run_job_as::<u16>(frame, sps, pps, layout, scaling, slices, draft, shared)
- }
}
-#[allow(clippy::too_many_arguments)]
-fn run_job_as<S: Sample>(
- frame: FrameRef,
- sps: Arc<Sps>,
- pps: Arc<Pps>,
- layout: Arc<Layout>,
- scaling: Option<Arc<Vec<Vec<u8>>>>,
- slices: Vec<SliceJob>,
- draft: bool,
- shared: &Shared,
-) {
+/// Decode all slices of one picture and publish its rows, in the picture's sample type.
+fn run_job(job: PicJob, shared: &Shared) {
+ if stores_u8(job.frame.bit_depth, job.frame.bit_depth_c) { run_job_as::<u8>(job, shared) } else { run_job_as::<u16>(job, shared) }
+}
+
+fn run_job_as<S: Sample>(job: PicJob, shared: &Shared) {
+ let PicJob { frame, sps, pps, layout, scaling, slices, draft } = job;
let mut pic = PicState::<S>::new(frame.clone(), sps, pps, layout, scaling);
pic.draft = draft;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
diff --git a/crates/hevc/src/filter.rs b/crates/hevc/src/filter.rs
index e916ab2bd..a1cdc00cd 100644
--- a/crates/hevc/src/filter.rs
+++ b/crates/hevc/src/filter.rs
@@ -161,7 +161,7 @@ fn deblock_row<S: Sample>(pic: &mut PicState<S>, r: usize) {
let qpl = (p.qp as i32 + q.qp as i32 + 1) >> 1;
let (tc, beta) = tc_beta(qpl, bs, tc_off, beta_off, bd);
let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
- filter_luma(&mut pic.planes[0], y * w + x, 1, w, tc, beta, nfp, nfq, bd);
+ filter_luma(&mut pic.planes[0], EdgeSeg { o: y * w + x, step: 1, along: w }, beta, EdgeFilter { tc, nfp, nfq, bd });
}
}
// chroma vertical edges (8x8 chroma grid = 16 luma samples), bS == 2 only
@@ -180,7 +180,7 @@ fn deblock_row<S: Sample>(pic: &mut PicState<S>, r: usize) {
let qpi = ((p.qp as i32 + q.qp as i32 + 1) >> 1) + off;
let qt = (qpc_420(qpi) + 2 + tc_off).clamp(0, 53);
let tc = (TC_TABLE[qt as usize] as i32) << (bdc - 8);
- filter_chroma(&mut pic.planes[c], (y / 2) * cw + x / 2, 1, cw, tc, nfp, nfq, bdc);
+ filter_chroma(&mut pic.planes[c], EdgeSeg { o: (y / 2) * cw + x / 2, step: 1, along: cw }, EdgeFilter { tc, nfp, nfq, bd: bdc });
}
}
}
@@ -205,7 +205,7 @@ fn deblock_row<S: Sample>(pic: &mut PicState<S>, r: usize) {
let qpl = (p.qp as i32 + q.qp as i32 + 1) >> 1;
let (tc, beta) = tc_beta(qpl, bs, tc_off, beta_off, bd);
let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
- filter_luma(&mut pic.planes[0], y * w + x, w, 1, tc, beta, nfp, nfq, bd);
+ filter_luma(&mut pic.planes[0], EdgeSeg { o: y * w + x, step: w, along: 1 }, beta, EdgeFilter { tc, nfp, nfq, bd });
}
}
for by in (y0 / 4..y1 / 4).filter(|b| b % 4 == 0 && *b > 0) {
@@ -222,21 +222,40 @@ fn deblock_row<S: Sample>(pic: &mut PicState<S>, r: usize) {
let qpi = ((p.qp as i32 + q.qp as i32 + 1) >> 1) + off;
let qt = (qpc_420(qpi) + 2 + tc_off).clamp(0, 53);
let tc = (TC_TABLE[qt as usize] as i32) << (bdc - 8);
- filter_chroma(&mut pic.planes[c], (y / 2) * cw + x / 2, cw, 1, tc, nfp, nfq, bdc);
+ filter_chroma(&mut pic.planes[c], EdgeSeg { o: (y / 2) * cw + x / 2, step: cw, along: 1 }, EdgeFilter { tc, nfp, nfq, bd: bdc });
}
}
}
}
-/// 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.
+/// Where a 4-line edge segment lies in a plane: `o` = offset of q0 of the first line, `step` =
+/// distance between p/q samples across the edge, `along` = distance between lines.
+#[derive(Clone, Copy)]
+struct EdgeSeg {
+ o: usize,
+ step: usize,
+ along: usize,
+}
+
+/// How an edge segment is filtered: the clipping threshold `tc`, the no-filter flags of the p and
+/// q sides and the bit depth.
+#[derive(Clone, Copy)]
+struct EdgeFilter {
+ tc: i32,
+ nfp: bool,
+ nfq: bool,
+ bd: u32,
+}
+
+/// Filter one 4-sample luma edge segment.
///
/// 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: Sample>(s: &mut [S], o: usize, step: usize, along: usize, tc: i32, beta: i32, nfp: bool, nfq: bool, bd: u32) {
+fn filter_luma<S: Sample>(s: &mut [S], seg: EdgeSeg, beta: i32, ef: EdgeFilter) {
+ let EdgeSeg { o, step, along } = seg;
+ let EdgeFilter { tc, nfp, nfq, bd } = ef;
// 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 };
@@ -339,8 +358,9 @@ fn filter_luma_lines(l: &mut [[i32; 8]; 4], tc: i32, beta: i32, nfp: bool, nfq:
}
/// Filter one 4-sample chroma edge segment.
-#[allow(clippy::too_many_arguments)]
-fn filter_chroma<S: Sample>(s: &mut [S], o: usize, step: usize, along: usize, tc: i32, nfp: bool, nfq: bool, bd: u32) {
+fn filter_chroma<S: Sample>(s: &mut [S], seg: EdgeSeg, ef: EdgeFilter) {
+ let EdgeSeg { o, step, along } = seg;
+ let EdgeFilter { tc, nfp, nfq, bd } = ef;
let max = (1i32 << bd) - 1;
for k in 0..4 {
let base = o + k * along;
@@ -381,15 +401,16 @@ fn sao_row<S: Sample>(pic: &PicState<S>, r: usize) -> [Vec<S>; 3] {
}
let x0 = rx * cs;
let x1 = (x0 + cs).min(w);
- sao_ctb(pic, c, rs, x0, x1, y0, y1, w, h, &p, &mut out[c]);
+ sao_ctb(pic, &SaoBlock { c, rs, x0, x1, y0, y1, w, h }, &p, &mut out[c]);
}
}
out
}
-#[allow(clippy::too_many_arguments)]
-fn sao_ctb<S: Sample>(
- pic: &PicState<S>,
+/// A CTB of plane `c` (CTB raster address `rs`) to apply SAO to: columns `x0..x1` and rows
+/// `y0..y1` of a plane `w` x `h` samples.
+#[derive(Clone, Copy)]
+struct SaoBlock {
c: usize,
rs: usize,
x0: usize,
@@ -398,9 +419,10 @@ fn sao_ctb<S: Sample>(
y1: usize,
w: usize,
h: usize,
- p: &crate::slicedec::SaoParams,
- dst: &mut [S],
-) {
+}
+
+fn sao_ctb<S: Sample>(pic: &PicState<S>, blk: &SaoBlock, p: &crate::slicedec::SaoParams, dst: &mut [S]) {
+ let SaoBlock { c, rs, x0, x1, y0, y1, w, h } = *blk;
let bd = if c == 0 { pic.bd_y } else { pic.bd_c };
let max = (1i32 << bd) - 1;
let sc = if c == 0 { 0 } else { 1 };
@@ -649,8 +671,9 @@ mod luma_filter_tests {
/// 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) {
+ fn reference(s: &mut [u16], seg: EdgeSeg, beta: i32, ef: EdgeFilter) {
+ let EdgeSeg { o, step, along } = seg;
+ let EdgeFilter { tc, nfp, nfq, bd } = ef;
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();
@@ -740,8 +763,9 @@ mod luma_filter_tests {
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);
+ let (seg, ef) = (EdgeSeg { o, step, along }, EdgeFilter { tc, nfp, nfq, bd });
+ filter_luma(&mut a, seg, beta, ef);
+ reference(&mut b, seg, beta, ef);
assert_eq!(a, b, "case {case} vertical {vertical}");
filtered += (a != plane) as usize;
}
diff --git a/crates/hevc/src/inter.rs b/crates/hevc/src/inter.rs
index 5292b65b7..7f89e7bb6 100644
--- a/crates/hevc/src/inter.rs
+++ b/crates/hevc/src/inter.rs
@@ -141,24 +141,26 @@ fn v_taps<'a, P>(rows: &'a [&'a [P]], r: usize, x: usize) -> impl Fn(usize) -> O
move |k| rows.get(r + k).and_then(|row| row.get(x..))
}
-/// Separable sub-sample interpolation of a w x h block from the window `rows` (h + T - 1 rows of
-/// at least w + T - 1 samples; the block's top-left sample at (m, m) for a T-tap filter with
-/// m = T / 2 - 1). The window rows are the reference picture's own lines when the window lies
-/// inside it horizontally, or lines of an edge-replicated copy.
-#[allow(clippy::too_many_arguments)]
-fn interpolate<P: Px, const T: usize>(
- rows: &[&[P]],
- tmp: &mut [i16],
+/// Parameters of one [`interpolate`] call: the fractional sample position (`fx`, `fy`), the
+/// horizontal and vertical `T`-tap filters, the block size and the two intermediate shifts.
+#[derive(Clone, Copy)]
+struct Interp<'a, const T: usize> {
fx: usize,
fy: usize,
- hf: &[i8; T],
- vf: &[i8; T],
+ hf: &'a [i8; T],
+ vf: &'a [i8; T],
w: usize,
h: usize,
shift1: u32,
shift3: u32,
- out: &mut [i16],
-) {
+}
+
+/// Separable sub-sample interpolation of a w x h block from the window `rows` (h + T - 1 rows of
+/// at least w + T - 1 samples; the block's top-left sample at (m, m) for a T-tap filter with
+/// m = T / 2 - 1). The window rows are the reference picture's own lines when the window lies
+/// inside it horizontally, or lines of an edge-replicated copy.
+fn interpolate<P: Px, const T: usize>(rows: &[&[P]], tmp: &mut [i16], k: &Interp<T>, out: &mut [i16]) {
+ let Interp { fx, fy, hf, vf, w, h, shift1, shift3 } = *k;
let m = T / 2 - 1;
// 8-bit samples: first passes in 16-bit lanes (see filt16_w)
let narrow = shift1 == 0 && shift3 == 6;
@@ -196,63 +198,52 @@ fn interpolate<P: Px, const T: usize>(
/// Prediction samples of a w x h block of plane `c` whose filter window (`T`-tap filters) starts
/// at (x0, y0): read straight from the reference lines when the window is inside the picture
/// horizontally, else from an edge-replicated copy.
-#[allow(clippy::too_many_arguments)]
-fn predict_block<S: Sample, const T: usize>(
- f: &Frame,
- c: usize,
- (x0, y0): (i32, i32),
- (fx, fy): (usize, usize),
- filters: (&[i8; T], &[i8; T]),
- (w, h): (usize, usize),
- (shift1, shift3): (u32, u32),
- out: &mut [i16],
- sc: &mut McScratch,
-) {
- let (ww, wh) = (w + T - 1, h + T - 1);
+fn predict_block<S: Sample, const T: usize>(f: &Frame, c: usize, (x0, y0): (i32, i32), k: &Interp<T>, out: &mut [i16], sc: &mut McScratch) {
+ let (ww, wh) = (k.w + T - 1, k.h + T - 1);
let McScratch { win, tmp } = sc;
let mut rows: [&[S]; WIN] = [&[]; WIN];
if let Some(rows) = rows.get_mut(..wh)
&& f.window_rows(c, x0, y0, ww, rows)
{
- interpolate::<S, T>(rows, tmp, fx, fy, filters.0, filters.1, w, h, shift1, shift3, out);
+ interpolate::<S, T>(rows, tmp, k, out);
return;
}
if c == 0 {
- f.luma_window::<S>(x0, y0, ww, wh, win, WIN);
+ f.luma_window::<S>((x0, y0), (ww, wh), win, WIN);
} else {
- f.chroma_window::<S>(c - 1, x0, y0, ww, wh, win, WIN);
+ f.chroma_window::<S>(c - 1, (x0, y0), (ww, wh), win, WIN);
}
let mut wrows: [&[i16]; WIN] = [&[]; WIN];
for (r, row) in wrows.iter_mut().zip(win.chunks(WIN)).take(wh) {
*r = row;
}
- interpolate::<i16, T>(&wrows[..wh.min(WIN)], tmp, fx, fy, filters.0, filters.1, w, h, shift1, shift3, out);
+ interpolate::<i16, T>(&wrows[..wh.min(WIN)], tmp, k, out);
}
/// Luma prediction samples (14-bit intermediate precision) of a w x h block at (x, y) displaced by the
/// quarter-sample motion vector `mv`, into `out` (stride w).
-#[allow(clippy::too_many_arguments)]
-pub fn mc_luma<S: Sample>(f: &Frame, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [i16], sc: &mut McScratch) {
+pub fn mc_luma<S: Sample>(f: &Frame, (x, y): (i32, i32), mv: [i16; 2], (w, h): (usize, usize), out: &mut [i16], sc: &mut McScratch) {
let bd = f.bit_depth;
let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
let xi = x + (mv[0] as i32 >> 2);
let yi = y + (mv[1] as i32 >> 2);
let shift1 = bd.min(12) - 8;
let shift3 = 14 - bd;
- predict_block::<S, 8>(f, 0, (xi - 3, yi - 3), (fx, fy), (&LUMA_FILTER[fx], &LUMA_FILTER[fy]), (w, h), (shift1, shift3), out, sc);
+ let k = Interp { fx, fy, hf: &LUMA_FILTER[fx], vf: &LUMA_FILTER[fy], w, h, shift1, shift3 };
+ predict_block::<S, 8>(f, 0, (xi - 3, yi - 3), &k, out, sc);
}
/// Chroma prediction samples of a w x h chroma block at chroma position (x, y) with a 1/8-sample
/// vector (4:2:0).
-#[allow(clippy::too_many_arguments)]
-pub fn mc_chroma<S: Sample>(f: &Frame, c: usize, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [i16], sc: &mut McScratch) {
+pub fn mc_chroma<S: Sample>(f: &Frame, c: usize, (x, y): (i32, i32), mv: [i16; 2], (w, h): (usize, usize), out: &mut [i16], sc: &mut McScratch) {
let bd = f.bit_depth_c;
let (fx, fy) = ((mv[0] & 7) as usize, (mv[1] & 7) as usize);
let xi = x + (mv[0] as i32 >> 3);
let yi = y + (mv[1] as i32 >> 3);
let shift1 = bd.min(12) - 8;
let shift3 = 14 - bd;
- predict_block::<S, 4>(f, c + 1, (xi - 1, yi - 1), (fx, fy), (&CHROMA_FILTER[fx], &CHROMA_FILTER[fy]), (w, h), (shift1, shift3), out, sc);
+ let k = Interp { fx, fy, hf: &CHROMA_FILTER[fx], vf: &CHROMA_FILTER[fy], w, h, shift1, shift3 };
+ predict_block::<S, 4>(f, c + 1, (xi - 1, yi - 1), &k, out, sc);
}
/// Calls `$f::<_, W>(args)` with `W` the prediction block width `$w` as a constant (block widths are
@@ -325,8 +316,9 @@ fn put_bi_w<S: Sample, const W: usize>(p0: &[i16], p1: &[i16], w: usize, h: usiz
}
}
-/// Explicit weighted prediction, one list (8-265). `o` is the offset already scaled to the bit depth.
-pub fn put_weighted_uni<S: Sample>(p: &[i16], w: usize, h: usize, bd: u32, log2wd: u32, wt: i32, o: i32, dst: &mut [S], ds: usize) {
+/// Explicit weighted prediction, one list (8-265). `(wt, o)` is the weight and the offset already
+/// scaled to the bit depth.
+pub fn put_weighted_uni<S: Sample>(p: &[i16], (w, h): (usize, usize), bd: u32, log2wd: u32, (wt, o): (i32, i32), dst: &mut [S], ds: usize) {
let max = (1i32 << bd) - 1;
for r in 0..h {
for c in 0..w {
@@ -337,18 +329,13 @@ pub fn put_weighted_uni<S: Sample>(p: &[i16], w: usize, h: usize, bd: u32, log2w
}
}
-/// Explicit weighted bi-prediction (8-266).
+/// Explicit weighted bi-prediction (8-266), with a (weight, offset) pair per list.
pub fn put_weighted_bi<S: Sample>(
- p0: &[i16],
- p1: &[i16],
- w: usize,
- h: usize,
+ [p0, p1]: [&[i16]; 2],
+ (w, h): (usize, usize),
bd: u32,
log2wd: u32,
- w0: i32,
- w1: i32,
- o0: i32,
- o1: i32,
+ [(w0, o0), (w1, o1)]: [(i32, i32); 2],
dst: &mut [S],
ds: usize,
) {
@@ -438,12 +425,12 @@ mod tests {
let (o0, o1) = (off(&mut rng), off(&mut rng));
let ds = w + 3;
let (mut uni, mut bi) = (vec![0u16; ds * h], vec![0u16; ds * h]);
- put_weighted_uni(&p0, w, h, bd, log2wd, w0, o0, &mut uni, ds);
- put_weighted_bi(&p0, &p1, w, h, bd, log2wd, w0, w1, o0, o1, &mut bi, ds);
+ put_weighted_uni(&p0, (w, h), bd, log2wd, (w0, o0), &mut uni, ds);
+ put_weighted_bi([&p0, &p1], (w, h), bd, log2wd, [(w0, o0), (w1, o1)], &mut bi, ds);
let denom = log2wd - (14 - bd);
let (mut duni, mut dbi) = (vec![0u16; ds * h], vec![0u16; ds * h]);
- put_weighted_uni(&p0, w, h, bd, log2wd, 1 << denom, 0, &mut duni, ds);
- put_weighted_bi(&p0, &p1, w, h, bd, log2wd, 1 << denom, 1 << denom, 0, 0, &mut dbi, ds);
+ put_weighted_uni(&p0, (w, h), bd, log2wd, (1 << denom, 0), &mut duni, ds);
+ put_weighted_bi([&p0, &p1], (w, h), bd, log2wd, [(1 << denom, 0); 2], &mut dbi, ds);
let (mut uni0, mut bi0) = (vec![0u16; ds * h], vec![0u16; ds * h]);
put_uni(&p0, w, h, bd, &mut uni0, ds);
put_bi(&p0, &p1, w, h, bd, &mut bi0, ds);
@@ -545,17 +532,19 @@ mod tests {
let mut win = vec![0i16; WIN * WIN];
let mut tmp = vec![0i16; WIN * WIN];
if c == 0 {
- f.luma_window::<S>(x0, y0, w + t - 1, h + t - 1, &mut win, WIN);
+ f.luma_window::<S>((x0, y0), (w + t - 1, h + t - 1), &mut win, WIN);
} else {
- f.chroma_window::<S>(c - 1, x0, y0, w + t - 1, h + t - 1, &mut win, WIN);
+ f.chroma_window::<S>(c - 1, (x0, y0), (w + t - 1, h + t - 1), &mut win, WIN);
}
let wrows: Vec<&[i16]> = win.chunks(WIN).take(h + t - 1).collect();
if c == 0 {
- mc_luma::<S>(&f, x, y, mv, w, h, &mut a, &mut sc);
- interpolate::<i16, 8>(&wrows, &mut tmp, fx, fy, &LUMA_FILTER[fx], &LUMA_FILTER[fy], w, h, shift1, shift3, &mut b);
+ mc_luma::<S>(&f, (x, y), mv, (w, h), &mut a, &mut sc);
+ let k = Interp { fx, fy, hf: &LUMA_FILTER[fx], vf: &LUMA_FILTER[fy], w, h, shift1, shift3 };
+ interpolate::<i16, 8>(&wrows, &mut tmp, &k, &mut b);
} else {
- mc_chroma::<S>(&f, c - 1, x, y, mv, w, h, &mut a, &mut sc);
- interpolate::<i16, 4>(&wrows, &mut tmp, fx, fy, &CHROMA_FILTER[fx], &CHROMA_FILTER[fy], w, h, shift1, shift3, &mut b);
+ mc_chroma::<S>(&f, c - 1, (x, y), mv, (w, h), &mut a, &mut sc);
+ let k = Interp { fx, fy, hf: &CHROMA_FILTER[fx], vf: &CHROMA_FILTER[fy], w, h, shift1, shift3 };
+ interpolate::<i16, 4>(&wrows, &mut tmp, &k, &mut b);
}
assert_eq!(a, b, "plane {c} bd {bd} at ({x}, {y}) mv {mv:?} {w}x{h}");
}
@@ -579,18 +568,18 @@ mod tests {
let (x, y) = (rng.range(-40, 80), rng.range(-40, 70));
let mut pred = vec![0i16; w * h];
let (mut a, mut b) = (vec![S::default(); w * h], vec![S::default(); w * h]);
- mc_luma::<S>(&f, 0, 0, [(x * 4) as i16, (y * 4) as i16], w, h, &mut pred, &mut sc);
+ mc_luma::<S>(&f, (0, 0), [(x * 4) as i16, (y * 4) as i16], (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);
+ f.copy_block(0, (x, y), (w, h), &mut b, w);
assert_eq!(a, b, "luma bd {bd} at ({x}, {y}) {w}x{h}");
// (the window really was read: not all samples equal the default)
assert!(a.iter().any(|&v| v != S::default()) || w * h < 8);
for c in 1..3 {
let (cw, ch) = (w / 2, h / 2);
- mc_chroma::<S>(&f, c - 1, 0, 0, [(x * 8) as i16, (y * 8) as i16], cw, ch, &mut pred, &mut sc);
+ mc_chroma::<S>(&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![S::default(); cw * ch], vec![S::default(); cw * ch]);
put_uni(&pred, cw, ch, bd, &mut a, cw);
- f.copy_block(c, x, y, cw, ch, &mut b, 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}");
}
}
diff --git a/crates/hevc/src/lib.rs b/crates/hevc/src/lib.rs
index c6a6484c6..367a50f1f 100644
--- a/crates/hevc/src/lib.rs
+++ b/crates/hevc/src/lib.rs
@@ -18,7 +18,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/hevc/src/mvpred.rs b/crates/hevc/src/mvpred.rs
index b56f441e8..1d38d1346 100644
--- a/crates/hevc/src/mvpred.rs
+++ b/crates/hevc/src/mvpred.rs
@@ -36,9 +36,26 @@ fn same_motion(a: &MvField, b: &MvField) -> bool {
true
}
+/// A prediction block: the coding block (`xc`, `yc`, size `ncb`) it belongs to, its own position
+/// (`xp`, `yp`), size (`w` x `h`) and index `part_idx` within the coding block, and the coding
+/// block's partitioning mode.
+#[derive(Clone, Copy)]
+pub struct PredBlock {
+ pub xc: i32,
+ pub yc: i32,
+ pub ncb: i32,
+ pub xp: i32,
+ pub yp: i32,
+ pub w: i32,
+ pub h: i32,
+ pub part_idx: usize,
+ pub part: PartMode,
+}
+
impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
- /// Prediction block availability (6.4.2).
- fn pb_avail(&self, xc: i32, yc: i32, ncb: i32, xp: i32, yp: i32, w: i32, h: i32, part_idx: usize, xn: i32, yn: i32) -> bool {
+ /// Prediction block availability (6.4.2) of the neighbouring location (`xn`, `yn`).
+ fn pb_avail(&self, pb: &PredBlock, xn: i32, yn: i32) -> bool {
+ let PredBlock { xc, yc, ncb, xp, yp, w, h, part_idx, .. } = *pb;
let same_cb = xc <= xn && yc <= yn && xc + ncb > xn && yc + ncb > yn;
let avail = if !same_cb {
self.pic.zavail(xp, yp, xn, yn, self.slice_addr)
@@ -59,23 +76,14 @@ impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
}
/// Merge mode motion (8.5.3.2.2).
- pub fn derive_merge(
- &self,
- xc: i32,
- yc: i32,
- ncb: i32,
- xp0: i32,
- yp0: i32,
- w0: i32,
- h0: i32,
- part_idx0: usize,
- part: PartMode,
- merge_idx: usize,
- ) -> MvField {
+ pub fn derive_merge(&self, pb: &PredBlock, merge_idx: usize) -> MvField {
+ let PredBlock { xc, yc, ncb, w: w0, h: h0, part, .. } = *pb;
let pml = self.pps.log2_parallel_merge_level;
- let (xp, yp, w, h, part_idx) = if pml > 2 && ncb == 8 { (xc, yc, ncb, ncb, 0) } else { (xp0, yp0, w0, h0, part_idx0) };
+ // with a parallel merge level above 4x4, the 8x8 coding block's 2Nx2N candidates are shared
+ let pb = if pml > 2 && ncb == 8 { PredBlock { xp: xc, yp: yc, w: ncb, h: ncb, part_idx: 0, ..*pb } } else { *pb };
+ let PredBlock { xp, yp, w, h, part_idx, .. } = pb;
let same_mer = |xn: i32, yn: i32| (xp >> pml) == (xn >> pml) && (yp >> pml) == (yn >> pml);
- let avail = |xn: i32, yn: i32| self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, xn, yn) && !same_mer(xn, yn);
+ let avail = |xn: i32, yn: i32| self.pb_avail(&pb, xn, yn) && !same_mer(xn, yn);
let mut list: [MvField; 5] = [MvField::default(); 5];
let mut n = 0;
let max = self.sh.max_num_merge_cand as usize;
@@ -236,20 +244,8 @@ impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
}
/// AMVP predictor (8.5.3.2.6, 8.5.3.2.7).
- pub fn derive_amvp(
- &self,
- xc: i32,
- yc: i32,
- ncb: i32,
- xp: i32,
- yp: i32,
- w: i32,
- h: i32,
- part_idx: usize,
- l: usize,
- ref_idx: usize,
- mvp_flag: usize,
- ) -> [i16; 2] {
+ pub fn derive_amvp(&self, pb: &PredBlock, l: usize, ref_idx: usize, mvp_flag: usize) -> [i16; 2] {
+ let PredBlock { xp, yp, w, h, .. } = *pb;
let target = &self.refs[l][ref_idx];
let (tpoc, tlt) = (target.poc, target.long_term);
let cur_poc = self.pic.poc;
@@ -276,7 +272,7 @@ impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
pick.map(|(mv, r)| if r.poc != tpoc && !r.long_term && !tlt { scale_mv(mv, cur_poc - r.poc, cur_poc - tpoc) } else { mv })
};
let pa = [(xp - 1, yp + h), (xp - 1, yp + h - 1)];
- let av_a = [self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pa[0].0, pa[0].1), self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pa[1].0, pa[1].1)];
+ let av_a = [self.pb_avail(pb, pa[0].0, pa[0].1), self.pb_avail(pb, pa[1].0, pa[1].1)];
let is_scaled = av_a[0] || av_a[1];
let mut a = None;
for k in 0..2 {
@@ -291,12 +287,12 @@ impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
}
}
}
- let pb = [(xp + w, yp - 1), (xp + w - 1, yp - 1), (xp - 1, yp - 1)];
- let av_b = [0, 1, 2].map(|k| self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pb[k].0, pb[k].1));
+ let pbk = [(xp + w, yp - 1), (xp + w - 1, yp - 1), (xp - 1, yp - 1)];
+ let av_b = [0, 1, 2].map(|k| self.pb_avail(pb, pbk[k].0, pbk[k].1));
let mut b = None;
for k in 0..3 {
if av_b[k] && b.is_none() {
- b = unscaled(&self.mv_at(pb[k].0, pb[k].1));
+ b = unscaled(&self.mv_at(pbk[k].0, pbk[k].1));
}
}
if !is_scaled && b.is_some() {
@@ -306,7 +302,7 @@ impl<'a, S: crate::picture::Sample> SliceDecoder<'a, S> {
b = None;
for k in 0..3 {
if av_b[k] && b.is_none() {
- b = scaled(&self.mv_at(pb[k].0, pb[k].1));
+ b = scaled(&self.mv_at(pbk[k].0, pbk[k].1));
}
}
}
diff --git a/crates/hevc/src/picture.rs b/crates/hevc/src/picture.rs
index c87f919f5..1f63607b0 100644
--- a/crates/hevc/src/picture.rs
+++ b/crates/hevc/src/picture.rs
@@ -224,7 +224,7 @@ impl Frame {
}
/// Copy a w x h luma window at (x0, y0) with edge replication into `out` (stride `os`).
- pub fn luma_window<S: Sample>(&self, x0: i32, y0: i32, w: usize, h: usize, out: &mut [i16], os: usize) {
+ pub fn luma_window<S: Sample>(&self, (x0, y0): (i32, i32), (w, h): (usize, usize), out: &mut [i16], os: usize) {
let (width, height) = (self.width as i32, self.height as i32);
let sh = self.log2_ctb;
let mask = (1i32 << sh) - 1;
@@ -237,7 +237,7 @@ impl Frame {
}
/// Copy a w x h window of chroma component `c` (0 = Cb, 1 = Cr) with edge replication.
- pub fn chroma_window<S: Sample>(&self, c: usize, x0: i32, y0: i32, w: usize, h: usize, out: &mut [i16], os: usize) {
+ pub fn chroma_window<S: Sample>(&self, c: usize, (x0, y0): (i32, i32), (w, h): (usize, usize), out: &mut [i16], os: usize) {
let (cw, ch) = (self.cwidth as i32, self.cheight as i32);
let sh = self.log2_ctb - 1;
let mask = (1i32 << sh) - 1;
@@ -284,8 +284,7 @@ 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<S: Sample>(&self, c: usize, x0: i32, y0: i32, w: usize, h: usize, dst: &mut [S], ds: usize) {
+ pub fn copy_block<S: Sample>(&self, c: usize, (x0, y0): (i32, i32), (w, h): (usize, usize), dst: &mut [S], 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() {
@@ -605,10 +604,10 @@ mod tests {
assert!(f.row::<u16>(0).is_none());
assert_eq!(f.row::<u8>(1).map(|r| r.y[0]), Some(128));
let mut win = [7i16; 64];
- f.luma_window::<u16>(-3, -3, 8, 8, &mut win, 8);
+ f.luma_window::<u16>((-3, -3), (8, 8), &mut win, 8);
assert!(win.iter().all(|&v| v == 7));
let mut dst = [5u16; 16];
- f.copy_block::<u16>(0, 0, 0, 4, 4, &mut dst, 4);
+ f.copy_block::<u16>(0, (0, 0), (4, 4), &mut dst, 4);
assert!(dst.iter().all(|&v| v == 5));
let g = Frame::gray(1, 0, &Frame::new(0, 0, 16, 8, 4, 10, 10));
assert!(g.is_complete());
diff --git a/crates/hevc/src/slice.rs b/crates/hevc/src/slice.rs
index 084eec8f3..61c08f094 100644
--- a/crates/hevc/src/slice.rs
+++ b/crates/hevc/src/slice.rs
@@ -184,40 +184,7 @@ impl SliceHeader {
s.nal = nal;
s
} else {
- SliceHeader {
- nal,
- first_slice_segment_in_pic: first,
- no_output_of_prior_pics,
- pps_id,
- dependent: false,
- segment_address,
- slice_type: SliceType::I,
- pic_output: true,
- poc_lsb: 0,
- st_rps: StRps::default(),
- st_rps_bits: 0,
- lt: Vec::new(),
- temporal_mvp: false,
- sao_luma: false,
- sao_chroma: false,
- num_ref_idx: [0, 0],
- list_entry: [None, None],
- mvd_l1_zero: false,
- cabac_init_flag: false,
- collocated_from_l0: true,
- collocated_ref_idx: 0,
- pwt: None,
- max_num_merge_cand: 5,
- qp_delta: 0,
- cb_qp_offset: 0,
- cr_qp_offset: 0,
- deblocking_disabled: pps.deblocking_disabled,
- beta_offset_div2: pps.beta_offset_div2,
- tc_offset_div2: pps.tc_offset_div2,
- loop_filter_across_slices: pps.loop_filter_across_slices,
- entry_points: Vec::new(),
- data_offset: 0,
- }
+ SliceHeader::with_pps_defaults(nal, first, no_output_of_prior_pics, pps_id, segment_address, &pps)
};
sh.first_slice_segment_in_pic = first;
sh.no_output_of_prior_pics = no_output_of_prior_pics;
@@ -225,158 +192,9 @@ impl SliceHeader {
sh.dependent = dependent;
sh.segment_address = segment_address;
if !dependent {
- r.skip(pps.num_extra_slice_header_bits as usize)?;
- let st = r.read_ue()?;
- sh.slice_type = match st {
- 0 => SliceType::B,
- 1 => SliceType::P,
- 2 => SliceType::I,
- _ => return invalid(format!("slice_type {st}")),
- };
- if nal.is_irap() {
- ensure!(sh.slice_type == SliceType::I, "IRAP picture with inter slice");
- }
- if pps.output_flag_present {
- sh.pic_output = r.read_flag()?;
- }
- if sps.separate_colour_plane {
- r.skip(2)?;
- }
- if !nal.is_idr() {
- sh.poc_lsb = r.read_bits(sps.log2_max_poc_lsb)?;
- let from_sps = r.read_flag()?;
- if !from_sps {
- let start = r.position();
- sh.st_rps = StRps::parse(&mut r, sps.st_rps.len(), &sps.st_rps, sps.st_rps.len())?;
- sh.st_rps_bits = r.position() - start;
- } else {
- ensure!(!sps.st_rps.is_empty(), "no short-term RPS in the SPS");
- let idx = if sps.st_rps.len() > 1 { r.read_bits(ceil_log2(sps.st_rps.len() as u32))? as usize } else { 0 };
- ensure!(idx < sps.st_rps.len(), "short_term_ref_pic_set_idx out of range");
- sh.st_rps = sps.st_rps[idx].clone();
- }
- if sps.long_term_refs_present {
- let num_lt_sps = if !sps.lt_ref_pics.is_empty() { r.read_ue()? } else { 0 };
- ensure!(num_lt_sps as usize <= sps.lt_ref_pics.len(), "num_long_term_sps out of range");
- let num_lt_pics = r.read_ue()?;
- ensure!(num_lt_sps + num_lt_pics <= 32, "too many long-term pictures");
- let mut msb_acc = 0u32;
- for i in 0..num_lt_sps + num_lt_pics {
- let (lsb, used) = if i < num_lt_sps {
- let idx = if sps.lt_ref_pics.len() > 1 { r.read_bits(ceil_log2(sps.lt_ref_pics.len() as u32))? } else { 0 };
- ensure!((idx as usize) < sps.lt_ref_pics.len(), "lt_idx_sps out of range");
- sps.lt_ref_pics[idx as usize]
- } else {
- (r.read_bits(sps.log2_max_poc_lsb)?, r.read_flag()?)
- };
- let msb_present = r.read_flag()?;
- let cycle = if msb_present { r.read_ue()? } else { 0 };
- // DeltaPocMsbCycleLt accumulates within each of the two groups (7-52)
- if i == 0 || i == num_lt_sps {
- msb_acc = cycle;
- } else {
- msb_acc = msb_acc.wrapping_add(cycle);
- }
- sh.lt.push((lsb, used, msb_present, msb_acc));
- }
- }
- if sps.temporal_mvp {
- sh.temporal_mvp = r.read_flag()?;
- }
- }
- if sps.sao {
- sh.sao_luma = r.read_flag()?;
- if sps.chroma_array_type() != 0 {
- sh.sao_chroma = r.read_flag()?;
- }
- }
- if sh.slice_type != SliceType::I {
- sh.num_ref_idx = [pps.num_ref_idx_l0_default, if sh.is_b() { pps.num_ref_idx_l1_default } else { 0 }];
- if r.read_flag()? {
- sh.num_ref_idx[0] = r.read_ue()? + 1;
- if sh.is_b() {
- sh.num_ref_idx[1] = r.read_ue()? + 1;
- }
- }
- ensure!(sh.num_ref_idx[0] <= 15 && sh.num_ref_idx[1] <= 15, "num_ref_idx_active out of range");
- let total = sh.num_pic_total_curr();
- ensure!(total > 0, "inter slice without reference pictures in the RPS");
- if pps.lists_modification_present && total > 1 {
- let bits = ceil_log2(total);
- for l in 0..if sh.is_b() { 2 } else { 1 } {
- if r.read_flag()? {
- let mut e = Vec::new();
- for _ in 0..sh.num_ref_idx[l] {
- let v = r.read_bits(bits)?;
- ensure!(v < total, "list_entry out of range");
- e.push(v);
- }
- sh.list_entry[l] = Some(e);
- }
- }
- }
- if sh.is_b() {
- sh.mvd_l1_zero = r.read_flag()?;
- }
- if pps.cabac_init_present {
- sh.cabac_init_flag = r.read_flag()?;
- }
- if sh.temporal_mvp {
- if sh.is_b() {
- sh.collocated_from_l0 = r.read_flag()?;
- }
- let l = if sh.collocated_from_l0 { 0 } else { 1 };
- if sh.num_ref_idx[l] > 1 {
- sh.collocated_ref_idx = r.read_ue()?;
- ensure!(sh.collocated_ref_idx < sh.num_ref_idx[l], "collocated_ref_idx out of range");
- }
- }
- if (pps.weighted_pred && sh.slice_type == SliceType::P) || (pps.weighted_bipred && sh.is_b()) {
- sh.pwt = Some(parse_pwt(&mut r, &sh, &sps)?);
- }
- let five_minus = r.read_ue()?;
- ensure!(five_minus <= 4, "five_minus_max_num_merge_cand out of range");
- sh.max_num_merge_cand = 5 - five_minus;
- }
- sh.qp_delta = r.read_se()?;
- let qp = pps.init_qp + sh.qp_delta;
- let qp_bd = 6 * (sps.bit_depth_luma as i32 - 8);
- ensure!((-qp_bd..=51).contains(&qp), "SliceQpY {qp} out of range");
- if pps.slice_chroma_qp_offsets_present {
- sh.cb_qp_offset = r.read_se()?;
- sh.cr_qp_offset = r.read_se()?;
- ensure!((-12..=12).contains(&sh.cb_qp_offset) && (-12..=12).contains(&sh.cr_qp_offset), "slice chroma QP offset out of range");
- }
- let override_flag = if pps.deblocking_override_enabled { r.read_flag()? } else { false };
- if override_flag {
- sh.deblocking_disabled = r.read_flag()?;
- if !sh.deblocking_disabled {
- sh.beta_offset_div2 = r.read_se()?;
- sh.tc_offset_div2 = r.read_se()?;
- ensure!((-6..=6).contains(&sh.beta_offset_div2) && (-6..=6).contains(&sh.tc_offset_div2), "deblocking offsets out of range");
- }
- }
- if pps.loop_filter_across_slices && (sh.sao_luma || sh.sao_chroma || !sh.deblocking_disabled) {
- sh.loop_filter_across_slices = r.read_flag()?;
- }
- }
- sh.entry_points.clear();
- if pps.tiles_enabled || pps.entropy_coding_sync {
- let n = r.read_ue()?;
- ensure!(n <= sps.pic_width_in_ctbs() * sps.pic_height_in_ctbs(), "num_entry_point_offsets out of range");
- if n > 0 {
- let len = r.read_ue()? + 1;
- ensure!(len <= 32, "offset_len_minus1 out of range");
- for _ in 0..n {
- sh.entry_points.push(r.read_bits(len)? + 1);
- }
- }
- }
- if pps.slice_header_extension_present {
- let len = r.read_ue()?;
- ensure!(len <= 256, "slice_segment_header_extension_length out of range");
- r.skip(8 * len as usize)?;
+ parse_independent_fields(&mut r, &mut sh, nal, &pps, &sps)?;
}
+ parse_entry_points_and_extension(&mut r, &mut sh, &pps, &sps)?;
// byte_alignment(): alignment_bit_equal_to_one then zeros
ensure!(r.read_flag()?, "missing alignment_bit_equal_to_one");
r.byte_align();
@@ -386,6 +204,238 @@ impl SliceHeader {
}
}
+impl SliceHeader {
+ /// A fresh independent slice header: syntax elements not yet parsed take their inferred
+ /// values, the deblocking parameters those of the PPS.
+ fn with_pps_defaults(nal: NalHeader, first: bool, no_output_of_prior_pics: bool, pps_id: u32, segment_address: u32, pps: &Pps) -> SliceHeader {
+ SliceHeader {
+ nal,
+ first_slice_segment_in_pic: first,
+ no_output_of_prior_pics,
+ pps_id,
+ dependent: false,
+ segment_address,
+ slice_type: SliceType::I,
+ pic_output: true,
+ poc_lsb: 0,
+ st_rps: StRps::default(),
+ st_rps_bits: 0,
+ lt: Vec::new(),
+ temporal_mvp: false,
+ sao_luma: false,
+ sao_chroma: false,
+ num_ref_idx: [0, 0],
+ list_entry: [None, None],
+ mvd_l1_zero: false,
+ cabac_init_flag: false,
+ collocated_from_l0: true,
+ collocated_ref_idx: 0,
+ pwt: None,
+ max_num_merge_cand: 5,
+ qp_delta: 0,
+ cb_qp_offset: 0,
+ cr_qp_offset: 0,
+ deblocking_disabled: pps.deblocking_disabled,
+ beta_offset_div2: pps.beta_offset_div2,
+ tc_offset_div2: pps.tc_offset_div2,
+ loop_filter_across_slices: pps.loop_filter_across_slices,
+ entry_points: Vec::new(),
+ data_offset: 0,
+ }
+ }
+}
+
+/// Fields present only in independent slice segments, up to the entry points.
+fn parse_independent_fields(r: &mut BitReader, sh: &mut SliceHeader, nal: NalHeader, pps: &Pps, sps: &Sps) -> Result<()> {
+ r.skip(pps.num_extra_slice_header_bits as usize)?;
+ let st = r.read_ue()?;
+ sh.slice_type = match st {
+ 0 => SliceType::B,
+ 1 => SliceType::P,
+ 2 => SliceType::I,
+ _ => return invalid(format!("slice_type {st}")),
+ };
+ if nal.is_irap() {
+ ensure!(sh.slice_type == SliceType::I, "IRAP picture with inter slice");
+ }
+ if pps.output_flag_present {
+ sh.pic_output = r.read_flag()?;
+ }
+ if sps.separate_colour_plane {
+ r.skip(2)?;
+ }
+ if !nal.is_idr() {
+ parse_reference_pictures(r, sh, sps)?;
+ }
+ if sps.sao {
+ sh.sao_luma = r.read_flag()?;
+ if sps.chroma_array_type() != 0 {
+ sh.sao_chroma = r.read_flag()?;
+ }
+ }
+ if sh.slice_type != SliceType::I {
+ parse_inter_slice_params(r, sh, pps, sps)?;
+ }
+ parse_qp_and_loop_filter(r, sh, pps, sps)
+}
+
+/// POC LSB, short-term and long-term reference picture sets and the temporal MVP flag.
+fn parse_reference_pictures(r: &mut BitReader, sh: &mut SliceHeader, sps: &Sps) -> Result<()> {
+ sh.poc_lsb = r.read_bits(sps.log2_max_poc_lsb)?;
+ let from_sps = r.read_flag()?;
+ if !from_sps {
+ let start = r.position();
+ sh.st_rps = StRps::parse(r, sps.st_rps.len(), &sps.st_rps, sps.st_rps.len())?;
+ sh.st_rps_bits = r.position() - start;
+ } else {
+ ensure!(!sps.st_rps.is_empty(), "no short-term RPS in the SPS");
+ let idx = if sps.st_rps.len() > 1 { r.read_bits(ceil_log2(sps.st_rps.len() as u32))? as usize } else { 0 };
+ ensure!(idx < sps.st_rps.len(), "short_term_ref_pic_set_idx out of range");
+ sh.st_rps = sps.st_rps[idx].clone();
+ }
+ if sps.long_term_refs_present {
+ parse_long_term_refs(r, sh, sps)?;
+ }
+ if sps.temporal_mvp {
+ sh.temporal_mvp = r.read_flag()?;
+ }
+ Ok(())
+}
+
+/// Long-term reference pictures (num_long_term_sps .. delta_poc_msb_cycle_lt).
+fn parse_long_term_refs(r: &mut BitReader, sh: &mut SliceHeader, sps: &Sps) -> Result<()> {
+ let num_lt_sps = if !sps.lt_ref_pics.is_empty() { r.read_ue()? } else { 0 };
+ ensure!(num_lt_sps as usize <= sps.lt_ref_pics.len(), "num_long_term_sps out of range");
+ let num_lt_pics = r.read_ue()?;
+ ensure!(num_lt_sps + num_lt_pics <= 32, "too many long-term pictures");
+ let mut msb_acc = 0u32;
+ for i in 0..num_lt_sps + num_lt_pics {
+ let (lsb, used) = if i < num_lt_sps {
+ let idx = if sps.lt_ref_pics.len() > 1 { r.read_bits(ceil_log2(sps.lt_ref_pics.len() as u32))? } else { 0 };
+ ensure!((idx as usize) < sps.lt_ref_pics.len(), "lt_idx_sps out of range");
+ sps.lt_ref_pics[idx as usize]
+ } else {
+ (r.read_bits(sps.log2_max_poc_lsb)?, r.read_flag()?)
+ };
+ let msb_present = r.read_flag()?;
+ let cycle = if msb_present { r.read_ue()? } else { 0 };
+ // DeltaPocMsbCycleLt accumulates within each of the two groups (7-52)
+ if i == 0 || i == num_lt_sps {
+ msb_acc = cycle;
+ } else {
+ msb_acc = msb_acc.wrapping_add(cycle);
+ }
+ sh.lt.push((lsb, used, msb_present, msb_acc));
+ }
+ Ok(())
+}
+
+/// ref_pic_lists_modification: list_entry_lX for each list.
+fn parse_list_modification(r: &mut BitReader, sh: &mut SliceHeader, total: u32) -> Result<()> {
+ let bits = ceil_log2(total);
+ for l in 0..if sh.is_b() { 2 } else { 1 } {
+ if r.read_flag()? {
+ let mut e = Vec::new();
+ for _ in 0..sh.num_ref_idx[l] {
+ let v = r.read_bits(bits)?;
+ ensure!(v < total, "list_entry out of range");
+ e.push(v);
+ }
+ sh.list_entry[l] = Some(e);
+ }
+ }
+ Ok(())
+}
+
+/// Inter-slice parameters: active reference counts, list modification, collocated picture,
+/// weighted prediction and merge candidates.
+fn parse_inter_slice_params(r: &mut BitReader, sh: &mut SliceHeader, pps: &Pps, sps: &Sps) -> Result<()> {
+ sh.num_ref_idx = [pps.num_ref_idx_l0_default, if sh.is_b() { pps.num_ref_idx_l1_default } else { 0 }];
+ if r.read_flag()? {
+ sh.num_ref_idx[0] = r.read_ue()? + 1;
+ if sh.is_b() {
+ sh.num_ref_idx[1] = r.read_ue()? + 1;
+ }
+ }
+ ensure!(sh.num_ref_idx[0] <= 15 && sh.num_ref_idx[1] <= 15, "num_ref_idx_active out of range");
+ let total = sh.num_pic_total_curr();
+ ensure!(total > 0, "inter slice without reference pictures in the RPS");
+ if pps.lists_modification_present && total > 1 {
+ parse_list_modification(r, sh, total)?;
+ }
+ if sh.is_b() {
+ sh.mvd_l1_zero = r.read_flag()?;
+ }
+ if pps.cabac_init_present {
+ sh.cabac_init_flag = r.read_flag()?;
+ }
+ if sh.temporal_mvp {
+ if sh.is_b() {
+ sh.collocated_from_l0 = r.read_flag()?;
+ }
+ let l = if sh.collocated_from_l0 { 0 } else { 1 };
+ if sh.num_ref_idx[l] > 1 {
+ sh.collocated_ref_idx = r.read_ue()?;
+ ensure!(sh.collocated_ref_idx < sh.num_ref_idx[l], "collocated_ref_idx out of range");
+ }
+ }
+ if (pps.weighted_pred && sh.slice_type == SliceType::P) || (pps.weighted_bipred && sh.is_b()) {
+ sh.pwt = Some(parse_pwt(r, sh, sps)?);
+ }
+ let five_minus = r.read_ue()?;
+ ensure!(five_minus <= 4, "five_minus_max_num_merge_cand out of range");
+ sh.max_num_merge_cand = 5 - five_minus;
+ Ok(())
+}
+
+/// Slice QP delta, chroma QP offsets and deblocking / in-loop filter controls.
+fn parse_qp_and_loop_filter(r: &mut BitReader, sh: &mut SliceHeader, pps: &Pps, sps: &Sps) -> Result<()> {
+ sh.qp_delta = r.read_se()?;
+ let qp = pps.init_qp + sh.qp_delta;
+ let qp_bd = 6 * (sps.bit_depth_luma as i32 - 8);
+ ensure!((-qp_bd..=51).contains(&qp), "SliceQpY {qp} out of range");
+ if pps.slice_chroma_qp_offsets_present {
+ sh.cb_qp_offset = r.read_se()?;
+ sh.cr_qp_offset = r.read_se()?;
+ ensure!((-12..=12).contains(&sh.cb_qp_offset) && (-12..=12).contains(&sh.cr_qp_offset), "slice chroma QP offset out of range");
+ }
+ let override_flag = if pps.deblocking_override_enabled { r.read_flag()? } else { false };
+ if override_flag {
+ sh.deblocking_disabled = r.read_flag()?;
+ if !sh.deblocking_disabled {
+ sh.beta_offset_div2 = r.read_se()?;
+ sh.tc_offset_div2 = r.read_se()?;
+ ensure!((-6..=6).contains(&sh.beta_offset_div2) && (-6..=6).contains(&sh.tc_offset_div2), "deblocking offsets out of range");
+ }
+ }
+ if pps.loop_filter_across_slices && (sh.sao_luma || sh.sao_chroma || !sh.deblocking_disabled) {
+ sh.loop_filter_across_slices = r.read_flag()?;
+ }
+ Ok(())
+}
+
+/// Entry point offsets and the slice header extension.
+fn parse_entry_points_and_extension(r: &mut BitReader, sh: &mut SliceHeader, pps: &Pps, sps: &Sps) -> Result<()> {
+ sh.entry_points.clear();
+ if pps.tiles_enabled || pps.entropy_coding_sync {
+ let n = r.read_ue()?;
+ ensure!(n <= sps.pic_width_in_ctbs() * sps.pic_height_in_ctbs(), "num_entry_point_offsets out of range");
+ if n > 0 {
+ let len = r.read_ue()? + 1;
+ ensure!(len <= 32, "offset_len_minus1 out of range");
+ for _ in 0..n {
+ sh.entry_points.push(r.read_bits(len)? + 1);
+ }
+ }
+ }
+ if pps.slice_header_extension_present {
+ let len = r.read_ue()?;
+ ensure!(len <= 256, "slice_segment_header_extension_length out of range");
+ r.skip(8 * len as usize)?;
+ }
+ Ok(())
+}
+
fn parse_pwt(r: &mut BitReader, sh: &SliceHeader, sps: &Sps) -> Result<PredWeightTable> {
let mut t = PredWeightTable { luma_log2_denom: r.read_ue()?, ..Default::default() };
ensure!(t.luma_log2_denom <= 7, "luma_log2_weight_denom out of range");
diff --git a/crates/hevc/src/slicedec.rs b/crates/hevc/src/slicedec.rs
index b76ae6a92..7a100758c 100644
--- a/crates/hevc/src/slicedec.rs
+++ b/crates/hevc/src/slicedec.rs
@@ -10,7 +10,11 @@ use crate::intra::{self, Refs};
use crate::params::{Layout, Pps, Sps};
use crate::picture::{FrameRef, RefPic, Sample};
use crate::slice::{SliceHeader, SliceType};
-use crate::spec_tables::*;
+use crate::spec_tables::{
+ ABS_MVD_GT0, ABS_MVD_GT1, CBF_CHROMA, CBF_LUMA, CODED_SUB_BLOCK, CU_QP_DELTA_ABS, CU_SKIP, CU_TRANSQUANT_BYPASS, GT1, GT2, INTER_PRED_IDC, INTRA_CHROMA,
+ LAST_X_PREFIX, LAST_Y_PREFIX, MERGE_FLAG, MERGE_IDX, MVP_FLAG, PART_MODE, PRED_MODE, PREV_INTRA_LUMA, REF_IDX, RQT_ROOT_CBF, SAO_MERGE, SAO_TYPE,
+ SIG_COEFF, SPLIT_CU, SPLIT_TRANSFORM, TRANSFORM_SKIP,
+};
use crate::tables::{CTX_IDX_MAP, LEVEL_SCALE, SCAN_4, qpc_420, scan_order};
use crate::transform;
use std::sync::Arc;
diff --git a/crates/hevc/src/slicedec/coding_unit.rs b/crates/hevc/src/slicedec/coding_unit.rs
index 4cf3418f3..d735451ed 100644
--- a/crates/hevc/src/slicedec/coding_unit.rs
+++ b/crates/hevc/src/slicedec/coding_unit.rs
@@ -1,4 +1,9 @@
-use super::*;
+use super::transform_tree::TtNode;
+use super::{
+ Blk, CU_SKIP, CU_TRANSQUANT_BYPASS, E_PU_H, E_PU_V, E_TU_H, E_TU_V, F_CODED, F_INTRA, F_NOFILTER, F_SKIP, INTRA_CHROMA, PART_MODE, PRED_MODE,
+ PREV_INTRA_LUMA, PartMode, RQT_ROOT_CBF, Result, SPLIT_CU, Sample, SliceDecoder, ensure, qpc_420,
+};
+use crate::mvpred::PredBlock;
impl<'a, S: Sample> SliceDecoder<'a, S> {
pub(super) fn coding_quadtree(&mut self, x0: i32, y0: i32, log2: u32, depth: u32) -> Result<()> {
@@ -113,7 +118,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
self.mark_edges(x0, y0, n, n, E_TU_V | E_PU_V, E_TU_H | E_PU_H);
if skip {
self.cu_intra = false;
- self.prediction_unit(x0, y0, n, x0, y0, n, n, 0, PartMode::P2Nx2N, true)?;
+ self.prediction_unit(&PredBlock { xc: x0, yc: y0, ncb: n, xp: x0, yp: y0, w: n, h: n, part_idx: 0, part: PartMode::P2Nx2N }, true)?;
self.finish_cu(x0, y0, n);
return Ok(());
}
@@ -139,7 +144,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
}
self.parse_intra_modes(x0, y0, n, part)?;
self.max_trafo_depth = self.sps.max_th_depth_intra + self.intra_split as u32;
- self.transform_tree(x0, y0, x0, y0, log2, 0, 0, [true, true])?;
+ self.transform_tree(TtNode { x0, y0, xb: x0, yb: y0, log2, blk_idx: 0 }, 0, [true, true])?;
} else {
self.intra_split = false;
let mut merge2nx2n = false;
@@ -156,7 +161,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
PartMode::PNxN => &[(0, 0, h, h), (h, 0, h, h), (0, h, h, h), (h, h, h, h)],
};
for (i, &(px, py, pw, ph)) in parts.iter().enumerate() {
- let merge = self.prediction_unit(x0, y0, n, x0 + px, y0 + py, pw, ph, i, part, false)?;
+ let merge = self.prediction_unit(&PredBlock { xc: x0, yc: y0, ncb: n, xp: x0 + px, yp: y0 + py, w: pw, h: ph, part_idx: i, part }, false)?;
if part == PartMode::P2Nx2N {
merge2nx2n = merge;
}
@@ -170,7 +175,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
let root_cbf = if !merge2nx2n { self.dd(RQT_ROOT_CBF) == 1 } else { true };
if root_cbf {
self.max_trafo_depth = self.sps.max_th_depth_inter;
- self.transform_tree(x0, y0, x0, y0, log2, 0, 0, [true, true])?;
+ self.transform_tree(TtNode { x0, y0, xb: x0, yb: y0, log2, blk_idx: 0 }, 0, [true, true])?;
}
}
self.finish_cu(x0, y0, n);
diff --git a/crates/hevc/src/slicedec/prediction_unit.rs b/crates/hevc/src/slicedec/prediction_unit.rs
index 5c36449da..ce9414ff9 100644
--- a/crates/hevc/src/slicedec/prediction_unit.rs
+++ b/crates/hevc/src/slicedec/prediction_unit.rs
@@ -1,20 +1,12 @@
-use super::*;
+use super::{
+ ABS_MVD_GT0, ABS_MVD_GT1, INTER_PRED_IDC, MERGE_FLAG, MERGE_IDX, MVP_FLAG, MvField, REF_IDX, Result, Sample, SliceDecoder, SliceType, ensure, inter,
+};
+use crate::mvpred::PredBlock;
impl<'a, S: Sample> SliceDecoder<'a, S> {
/// prediction_unit(): parse, derive motion, store it and predict. Returns merge_flag.
- pub(super) fn prediction_unit(
- &mut self,
- xc: i32,
- yc: i32,
- ncb: i32,
- xp: i32,
- yp: i32,
- w: i32,
- h: i32,
- part_idx: usize,
- part: PartMode,
- skip: bool,
- ) -> Result<bool> {
+ pub(super) fn prediction_unit(&mut self, pb: &PredBlock, skip: bool) -> Result<bool> {
+ let PredBlock { xc, yc, xp, yp, w, h, .. } = *pb;
let merge = if skip { true } else { self.dd(MERGE_FLAG) == 1 };
let mvf = if merge {
let idx = if self.sh.max_num_merge_cand > 1 {
@@ -29,7 +21,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
} else {
0
};
- self.derive_merge(xc, yc, ncb, xp, yp, w, h, part_idx, part, idx as usize)
+ self.derive_merge(pb, idx as usize)
} else {
let pred_idc = if self.sh.is_b() {
if w + h != 12 {
@@ -73,7 +65,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
if ref_idx[l] < 0 {
continue;
}
- let mvp = self.derive_amvp(xc, yc, ncb, xp, yp, w, h, part_idx, l, ref_idx[l] as usize, mvp_flag[l] as usize);
+ let mvp = self.derive_amvp(pb, l, ref_idx[l] as usize, mvp_flag[l] as usize);
// mvLX = (mvp + mvd) wrapped to 16 bits (8-94)
f.mv[l] = [(mvp[0] as i32 + mvd[l][0]) as i16, (mvp[1] as i32 + mvd[l][1]) as i16];
}
@@ -154,7 +146,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
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);
+ frame.copy_block(c, (x + (mv[0] as i32 >> sh), y + (mv[1] as i32 >> sh)), (bw, bh), dst, stride);
continue;
}
}
@@ -167,9 +159,9 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
let frame = &self.refs[l][f.ref_idx[l] as usize].frame;
let buf = if l == 0 || !bi { &mut self.pred0 } else { &mut self.pred1 };
if c == 0 {
- inter::mc_luma::<S>(frame, x, y, f.mv[l], bw, bh, buf, &mut self.mc);
+ inter::mc_luma::<S>(frame, (x, y), f.mv[l], (bw, bh), buf, &mut self.mc);
} else {
- inter::mc_chroma::<S>(frame, c - 1, x, y, f.mv[l], bw, bh, buf, &mut self.mc);
+ inter::mc_chroma::<S>(frame, c - 1, (x, y), f.mv[l], (bw, bh), buf, &mut self.mc);
}
}
let stride = if c == 0 { self.pic.width } else { self.pic.cwidth };
@@ -190,13 +182,10 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
(wt, o << (bd - 8))
};
if bi {
- let (w0, o0) = get(0);
- let (w1, o1) = get(1);
- inter::put_weighted_bi(&self.pred0, &self.pred1, bw, bh, bd, log2wd, w0, w1, o0, o1, dst, stride);
+ inter::put_weighted_bi([&self.pred0, &self.pred1], (bw, bh), bd, log2wd, [get(0), get(1)], dst, stride);
} else {
let l = if lists[0] { 0 } else { 1 };
- let (wt, o) = get(l);
- inter::put_weighted_uni(&self.pred0, bw, bh, bd, log2wd, wt, o, dst, stride);
+ inter::put_weighted_uni(&self.pred0, (bw, bh), bd, log2wd, get(l), dst, stride);
}
}
}
diff --git a/crates/hevc/src/slicedec/transform_tree.rs b/crates/hevc/src/slicedec/transform_tree.rs
index 394f3dcca..895674750 100644
--- a/crates/hevc/src/slicedec/transform_tree.rs
+++ b/crates/hevc/src/slicedec/transform_tree.rs
@@ -1,7 +1,113 @@
-use super::*;
+use super::{
+ CBF_CHROMA, CBF_LUMA, CODED_SUB_BLOCK, CTX_IDX_MAP, CU_QP_DELTA_ABS, E_TU_H, E_TU_V, F_CBF, F_INTRA, GT1, GT2, LAST_X_PREFIX, LAST_Y_PREFIX, LEVEL_SCALE,
+ PartMode, PicState, Result, SCAN_4, SIG_COEFF, SPLIT_TRANSFORM, Sample, SliceDecoder, TRANSFORM_SKIP, ensure, intra, scan_order, transform,
+};
+
+/// Significant scan positions of one sub-block, in decoding (descending) order.
+#[derive(Default)]
+struct SigList {
+ pos: [u8; 16],
+ n: usize,
+}
+
+impl SigList {
+ fn push(&mut self, p: u8) {
+ self.pos[self.n] = p;
+ self.n += 1;
+ }
+}
+
+/// Context of the significance map of one coded sub-block.
+struct SigMapParams {
+ log2: u32,
+ c: usize,
+ scan_idx: usize,
+ /// Sub-block position.
+ xs: usize,
+ ys: usize,
+ /// coded_sub_block_flag of the right neighbour plus twice that of the one below.
+ prev_csbf: u8,
+ /// inferSbDcSigCoeffFlag.
+ infer_dc: bool,
+ /// First scan position to decode (descending).
+ start: i32,
+}
+
+/// coeff_abs_level_greater1_flag / greater2_flag results of one sub-block.
+#[derive(Default)]
+struct GreaterFlags {
+ gt1: [u8; 16],
+ first_g1: Option<usize>,
+ gt2: u8,
+ /// Final greater1 context state, which selects the next sub-block's context set.
+ g1ctx: u32,
+}
+
+/// sigCtx increment of sig_coeff_flag (9.3.4.2.5) for the position `(xp, yp)` inside the sub-block.
+fn sig_ctx_inc(p: &SigMapParams, (xp, yp): (usize, usize)) -> usize {
+ let (xc, yc) = (p.xs * 4 + xp, p.ys * 4 + yp);
+ if p.log2 == 2 {
+ return CTX_IDX_MAP[(yc << 2) + xc] as usize;
+ }
+ if xc + yc == 0 {
+ return 0;
+ }
+ let mut s = match p.prev_csbf {
+ 0 => {
+ if xp + yp == 0 {
+ 2
+ } else if xp + yp < 3 {
+ 1
+ } else {
+ 0
+ }
+ }
+ 1 => {
+ if yp == 0 {
+ 2
+ } else if yp == 1 {
+ 1
+ } else {
+ 0
+ }
+ }
+ 2 => {
+ if xp == 0 {
+ 2
+ } else if xp == 1 {
+ 1
+ } else {
+ 0
+ }
+ }
+ _ => 2,
+ };
+ if p.c == 0 {
+ if p.xs + p.ys > 0 {
+ s += 3;
+ }
+ s += if p.log2 == 3 { if p.scan_idx == 0 { 9 } else { 15 } } else { 21 };
+ } else {
+ s += if p.log2 == 3 { 9 } else { 12 };
+ }
+ s
+}
+
+/// A node of the transform tree: the block at (`x0`, `y0`) of size 2^`log2`, its parent's origin
+/// (`xb`, `yb`) and its index `blk_idx` among the parent's four children.
+#[derive(Clone, Copy)]
+pub(super) struct TtNode {
+ pub x0: i32,
+ pub y0: i32,
+ pub xb: i32,
+ pub yb: i32,
+ pub log2: u32,
+ pub blk_idx: u32,
+}
impl<'a, S: Sample> SliceDecoder<'a, S> {
- pub(super) fn transform_tree(&mut self, x0: i32, y0: i32, xb: i32, yb: i32, log2: u32, depth: u32, blk_idx: u32, parent_cbf_c: [bool; 2]) -> Result<()> {
+ pub(super) fn transform_tree(&mut self, node: TtNode, depth: u32, parent_cbf_c: [bool; 2]) -> Result<()> {
+ let TtNode { x0, y0, log2, .. } = node;
let split = if log2 <= self.sps.log2_max_tb && log2 > self.sps.log2_min_tb && depth < self.max_trafo_depth && !(self.intra_split && depth == 0) {
self.dd(SPLIT_TRANSFORM + (5 - log2 as usize)) == 1
} else {
@@ -25,10 +131,10 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
}
if split {
let h = 1 << (log2 - 1);
- self.transform_tree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbf_c)?;
- self.transform_tree(x0 + h, y0, x0, y0, log2 - 1, depth + 1, 1, cbf_c)?;
- self.transform_tree(x0, y0 + h, x0, y0, log2 - 1, depth + 1, 2, cbf_c)?;
- self.transform_tree(x0 + h, y0 + h, x0, y0, log2 - 1, depth + 1, 3, cbf_c)?;
+ for (blk_idx, (dx, dy)) in [(0, 0), (h, 0), (0, h), (h, h)].into_iter().enumerate() {
+ let child = TtNode { x0: x0 + dx, y0: y0 + dy, xb: x0, yb: y0, log2: log2 - 1, blk_idx: blk_idx as u32 };
+ self.transform_tree(child, depth + 1, cbf_c)?;
+ }
return Ok(());
}
let cbf_luma = if self.cu_intra || depth != 0 || cbf_c[0] || cbf_c[1] { self.dd(CBF_LUMA + if depth == 0 { 1 } else { 0 }) == 1 } else { true };
@@ -36,10 +142,11 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
if depth > 0 {
self.mark_edges(x0, y0, n, n, E_TU_V, E_TU_H);
}
- self.transform_unit(x0, y0, xb, yb, log2, blk_idx, cbf_luma, cbf_c)
+ self.transform_unit(node, cbf_luma, cbf_c)
}
- fn transform_unit(&mut self, x0: i32, y0: i32, xb: i32, yb: i32, log2: u32, blk_idx: u32, cbf_luma: bool, cbf_c: [bool; 2]) -> Result<()> {
+ fn transform_unit(&mut self, node: TtNode, cbf_luma: bool, cbf_c: [bool; 2]) -> Result<()> {
+ let TtNode { x0, y0, xb, yb, log2, blk_idx } = node;
let n = 1i32 << log2;
let chroma_here = log2 > 2 || blk_idx == 3;
let cbf_chroma = cbf_c[0] || cbf_c[1];
@@ -146,12 +253,9 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
intra::predict(r, mode, n, c == 0, bd, &mut self.pic.planes[c][off..], stride);
}
- /// residual_coding() + scaling + transform + reconstruction for one transform block.
- fn residual(&mut self, x0: i32, y0: i32, log2: u32, c: usize, qp: i32) -> Result<()> {
- let n = 1usize << log2;
- let bypass = self.cu_transquant_bypass;
- let ts = if self.pps.transform_skip && !bypass && log2 == 2 { self.dd(TRANSFORM_SKIP + (c > 0) as usize) == 1 } else { false };
- // last significant coefficient
+ /// last_sig_coeff_{x,y}_{prefix,suffix}: the position of the last significant coefficient
+ /// (before the vertical-scan swap).
+ fn last_sig_coeff_pos(&mut self, log2: u32, c: usize) -> (u32, u32) {
let cmax = (log2 << 1) - 1;
let (off, shift) = if c == 0 { (3 * (log2 - 2) + ((log2 - 1) >> 2), (log2 + 1) >> 2) } else { (15, log2 - 2) };
let mut px = 0;
@@ -172,19 +276,124 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
let nb = (py >> 1) - 1;
ly = (1 << nb) * (2 + (py & 1)) + self.bypass_bits(nb);
}
- // scanIdx (7.4.9.11)
- let scan_idx = if self.cu_intra && (log2 == 2 || (log2 == 3 && c == 0)) {
- let m = if c == 0 { self.pic.blk_at(x0, y0).ipm as u32 } else { self.intra_chroma_mode };
- if (6..=14).contains(&m) {
- 2
- } else if (22..=30).contains(&m) {
- 1
- } else {
- 0
- }
+ (lx, ly)
+ }
+
+ /// scanIdx (7.4.9.11): 0 diagonal, 1 horizontal, 2 vertical.
+ fn scan_idx(&self, x0: i32, y0: i32, log2: u32, c: usize) -> usize {
+ if !(self.cu_intra && (log2 == 2 || (log2 == 3 && c == 0))) {
+ return 0;
+ }
+ let m = if c == 0 { self.pic.blk_at(x0, y0).ipm as u32 } else { self.intra_chroma_mode };
+ if (6..=14).contains(&m) {
+ 2
+ } else if (22..=30).contains(&m) {
+ 1
} else {
0
- };
+ }
+ }
+
+ /// sig_coeff_flag decoding of one coded sub-block, appending the significant scan positions
+ /// (descending) to `list`.
+ fn read_sig_map(&mut self, p: &SigMapParams, list: &mut SigList) {
+ let pos_scan = &SCAN_4[p.scan_idx];
+ let c_off_sig = if p.c == 0 { 0 } else { 27 };
+ let mut infer_dc = p.infer_dc;
+ let mut np = p.start;
+ while np >= 0 {
+ let (xp, yp) = (pos_scan[np as usize].0 as usize, pos_scan[np as usize].1 as usize);
+ if np > 0 || !infer_dc {
+ let sig_ctx = sig_ctx_inc(p, (xp, yp));
+ if self.c.decode_decision(SIG_COEFF + c_off_sig + sig_ctx) == 1 {
+ list.push(np as u8);
+ infer_dc = false;
+ }
+ } else {
+ // np == 0 with inferSbDcSigCoeffFlag
+ list.push(0);
+ }
+ np -= 1;
+ }
+ }
+
+ /// coeff_abs_level_greater1_flag / greater2_flag of one sub-block with `nsig` significant
+ /// coefficients; `ctx_set` as derived in 9.3.4.2.6.
+ fn read_greater_flags(&mut self, c: usize, ctx_set: usize, nsig: usize) -> GreaterFlags {
+ let mut g1ctx = 1u32;
+ let mut f = GreaterFlags::default();
+ let c_off_g1 = if c > 0 { 16 } else { 0 };
+ for k in 0..nsig.min(8) {
+ let inc = ctx_set * 4 + g1ctx.min(3) as usize + c_off_g1;
+ let flag = self.c.decode_decision(GT1 + inc);
+ f.gt1[k] = flag as u8;
+ if flag == 1 {
+ g1ctx = 0;
+ if f.first_g1.is_none() {
+ f.first_g1 = Some(k);
+ }
+ } else if g1ctx > 0 {
+ g1ctx += 1;
+ }
+ }
+ f.g1ctx = g1ctx;
+ if f.first_g1.is_some() {
+ f.gt2 = self.c.decode_decision(GT2 + ctx_set + if c > 0 { 4 } else { 0 }) as u8;
+ }
+ f
+ }
+
+ /// Signs and remaining levels of one sub-block: the signed coefficient value of each
+ /// significant position, in the order of `list`.
+ fn read_levels(&mut self, list: &SigList, flags: &GreaterFlags, sdh: bool) -> Result<[i32; 16]> {
+ let nsig = list.n;
+ let last_sig_pos = list.pos[0] as i32;
+ let first_sig_pos = list.pos[nsig - 1] as i32;
+ let sign_hidden = sdh && last_sig_pos - first_sig_pos > 3;
+ let nsigns = if sign_hidden { nsig - 1 } else { nsig };
+ let mut signs = if nsigns > 0 { self.bypass_bits(nsigns as u32) << (32 - nsigns) } else { 0 };
+ let mut values = [0i32; 16];
+ let mut rice = 0u32;
+ let mut sum_abs = 0i32;
+ for k in 0..nsig {
+ let mut base = 1 + flags.gt1[k] as i32;
+ if Some(k) == flags.first_g1 {
+ base += flags.gt2 as i32;
+ }
+ let thresh = if k < 8 { if Some(k) == flags.first_g1 { 3 } else { 2 } } else { 1 };
+ let mut level = base;
+ if base == thresh {
+ let rem = self.coeff_abs_level_remaining(rice)?;
+ level = base + rem;
+ if level > 3 * (1 << rice) {
+ rice = (rice + 1).min(4);
+ }
+ }
+ let mut v = level;
+ if !(sign_hidden && k == nsig - 1) {
+ if signs & 0x8000_0000 != 0 {
+ v = -v;
+ }
+ signs <<= 1;
+ }
+ if sign_hidden {
+ sum_abs += level;
+ if k == nsig - 1 && sum_abs & 1 == 1 {
+ v = -v;
+ }
+ }
+ values[k] = v;
+ }
+ Ok(values)
+ }
+
+ /// residual_coding() + scaling + transform + reconstruction for one transform block.
+ fn residual(&mut self, x0: i32, y0: i32, log2: u32, c: usize, qp: i32) -> Result<()> {
+ let n = 1usize << log2;
+ let bypass = self.cu_transquant_bypass;
+ let ts = if self.pps.transform_skip && !bypass && log2 == 2 { self.dd(TRANSFORM_SKIP + (c > 0) as usize) == 1 } else { false };
+ let (mut lx, mut ly) = self.last_sig_coeff_pos(log2, c);
+ let scan_idx = self.scan_idx(x0, y0, log2, c);
if scan_idx == 2 {
std::mem::swap(&mut lx, &mut ly);
}
@@ -200,7 +409,6 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
let mut prev_g1: Option<u32> = None;
let sdh = self.pps.sign_data_hiding && !bypass;
let (mut max_x, mut max_y) = (0usize, 0usize);
- let c_off_sig = if c == 0 { 0 } else { 27 };
for i in (0..=last_sb).rev() {
let (xs, ys) = (sb_scan[i].0 as usize, sb_scan[i].1 as usize);
let mut infer_dc = false;
@@ -214,81 +422,18 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
csbf[ys * 8 + xs] = 1;
}
// significance map
- let mut sig = [0u8; 16]; // scan positions n of significant coefficients, descending
- let mut nsig = 0;
+ let mut list = SigList::default();
let start: i32 = if i == last_sb {
- sig[0] = last_pos as u8;
- nsig = 1;
+ list.push(last_pos as u8);
last_pos as i32 - 1
} else {
15
};
if csbf[ys * 8 + xs] != 0 {
- let prev_csbf = right + (below << 1);
- let mut np = start;
- while np >= 0 {
- let (xp, yp) = (pos_scan[np as usize].0 as usize, pos_scan[np as usize].1 as usize);
- let (xc, yc) = (xs * 4 + xp, ys * 4 + yp);
- if np > 0 || !infer_dc {
- let sig_ctx = if log2 == 2 {
- CTX_IDX_MAP[(yc << 2) + xc] as usize
- } else if xc + yc == 0 {
- 0
- } else {
- let mut s = match prev_csbf {
- 0 => {
- if xp + yp == 0 {
- 2
- } else if xp + yp < 3 {
- 1
- } else {
- 0
- }
- }
- 1 => {
- if yp == 0 {
- 2
- } else if yp == 1 {
- 1
- } else {
- 0
- }
- }
- 2 => {
- if xp == 0 {
- 2
- } else if xp == 1 {
- 1
- } else {
- 0
- }
- }
- _ => 2,
- };
- if c == 0 {
- if xs + ys > 0 {
- s += 3;
- }
- s += if log2 == 3 { if scan_idx == 0 { 9 } else { 15 } } else { 21 };
- } else {
- s += if log2 == 3 { 9 } else { 12 };
- }
- s
- };
- if self.c.decode_decision(SIG_COEFF + c_off_sig + sig_ctx) == 1 {
- sig[nsig] = np as u8;
- nsig += 1;
- infer_dc = false;
- }
- } else {
- // np == 0 with inferSbDcSigCoeffFlag
- sig[nsig] = 0;
- nsig += 1;
- }
- np -= 1;
- }
+ let params = SigMapParams { log2, c, scan_idx, xs, ys, prev_csbf: right + (below << 1), infer_dc, start };
+ self.read_sig_map(&params, &mut list);
}
- if nsig == 0 {
+ if list.n == 0 {
continue;
}
// greater1 / greater2 flags
@@ -298,73 +443,18 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
{
ctx_set += 1;
}
- let mut g1ctx = 1u32;
- let mut gt1 = [0u8; 16];
- let mut first_g1: Option<usize> = None;
- let c_off_g1 = if c > 0 { 16 } else { 0 };
- for k in 0..nsig.min(8) {
- let inc = ctx_set * 4 + g1ctx.min(3) as usize + c_off_g1;
- let f = self.c.decode_decision(GT1 + inc);
- gt1[k] = f as u8;
- if f == 1 {
- g1ctx = 0;
- if first_g1.is_none() {
- first_g1 = Some(k);
- }
- } else if g1ctx > 0 {
- g1ctx += 1;
- }
- }
- prev_g1 = Some(g1ctx);
- let mut gt2 = 0u8;
- if let Some(k) = first_g1 {
- gt2 = self.c.decode_decision(GT2 + ctx_set + if c > 0 { 4 } else { 0 }) as u8;
- let _ = k;
- }
- // signs
- let last_sig_pos = sig[0] as i32;
- let first_sig_pos = sig[nsig - 1] as i32;
- let sign_hidden = sdh && last_sig_pos - first_sig_pos > 3;
- let nsigns = if sign_hidden { nsig - 1 } else { nsig };
- let mut signs = if nsigns > 0 { self.bypass_bits(nsigns as u32) << (32 - nsigns) } else { 0 };
- // remaining levels
- let mut rice = 0u32;
- let mut sum_abs = 0i32;
- for k in 0..nsig {
- let mut base = 1 + gt1[k] as i32;
- if Some(k) == first_g1 {
- base += gt2 as i32;
- }
- let thresh = if k < 8 { if Some(k) == first_g1 { 3 } else { 2 } } else { 1 };
- let mut level = base;
- if base == thresh {
- let rem = self.coeff_abs_level_remaining(rice)?;
- level = base + rem;
- if level > 3 * (1 << rice) {
- rice = (rice + 1).min(4);
- }
- }
- let np = sig[k] as usize;
+ let flags = self.read_greater_flags(c, ctx_set, list.n);
+ prev_g1 = Some(flags.g1ctx);
+ let values = self.read_levels(&list, &flags, sdh)?;
+ for k in 0..list.n {
+ let np = list.pos[k] as usize;
let (xc, yc) = (xs * 4 + pos_scan[np].0 as usize, ys * 4 + pos_scan[np].1 as usize);
- let mut v = level;
- if !(sign_hidden && k == nsig - 1) {
- if signs & 0x8000_0000 != 0 {
- v = -v;
- }
- signs <<= 1;
- }
- if sign_hidden {
- sum_abs += level;
- if k == nsig - 1 && sum_abs & 1 == 1 {
- v = -v;
- }
- }
- self.coeffs[yc * n + xc] = v;
+ self.coeffs[yc * n + xc] = values[k];
max_x = max_x.max(xc);
max_y = max_y.max(yc);
}
}
- self.reconstruct(x0, y0, log2, c, qp, ts, max_x, max_y)
+ self.reconstruct((x0, y0), log2, c, qp, ts, (max_x, max_y))
}
fn coeff_abs_level_remaining(&mut self, rice: u32) -> Result<i32> {
@@ -383,7 +473,7 @@ impl<'a, S: Sample> SliceDecoder<'a, S> {
}
/// Scaling, transform and addition to the prediction.
- fn reconstruct(&mut self, x0: i32, y0: i32, log2: u32, c: usize, qp: i32, ts: bool, max_x: usize, max_y: usize) -> Result<()> {
+ fn reconstruct(&mut self, (x0, y0): (i32, i32), log2: u32, c: usize, qp: i32, ts: bool, (max_x, max_y): (usize, usize)) -> Result<()> {
let n = 1usize << log2;
let bd = if c == 0 { self.pic.bd_y } else { self.pic.bd_c };
let coeffs = &mut self.coeffs[..n * n];