Skip to content

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

M2 perf: frame-threaded H.264 decoding and hot-path optimisation

Brandon Thomas374569e65e12
diff --git a/crates/h264/examples/h264dec.rs b/crates/h264/examples/h264dec.rs
index 052b8a1b0..3a93ed6f7 100644
--- a/crates/h264/examples/h264dec.rs
+++ b/crates/h264/examples/h264dec.rs
@@ -11,6 +11,20 @@ fn main() {
std::process::exit(2);
}
let data = std::fs::read(&args[1]).expect("read input");
+ // H264_BENCH_ITERS=n: decode n times without output and report the best run
+ if let Some(n) = std::env::var("H264_BENCH_ITERS").ok().and_then(|v| v.parse::<usize>().ok()) {
+ let mut best = f64::MAX;
+ let mut frames = 0;
+ let threads = std::env::var("H264_THREADS").ok().and_then(|v| v.parse::<usize>().ok());
+ for _ in 0..n {
+ let mut dec = threads.map(Decoder::with_threads).unwrap_or_default();
+ let t0 = std::time::Instant::now();
+ frames = dec.decode(&data, 0).expect("decode").len() + dec.flush().len();
+ best = best.min(t0.elapsed().as_secs_f64());
+ }
+ eprintln!("best of {n}: {frames} frames in {best:.3}s ({:.1} fps)", frames as f64 / best);
+ return;
+ }
let mut out = args.get(2).map(|p| std::io::BufWriter::new(std::fs::File::create(p).expect("create output")));
let mut dec = Decoder::new();
let t0 = std::time::Instant::now();
diff --git a/crates/h264/src/cabac_mb.rs b/crates/h264/src/cabac_mb.rs
index 201e53944..87b8dede1 100644
--- a/crates/h264/src/cabac_mb.rs
+++ b/crates/h264/src/cabac_mb.rs
@@ -42,7 +42,7 @@ impl SliceDecoder<'_> {
} else {
self.decode_mb_cabac(&mut c)?;
}
- self.pic.decoded_mbs += 1;
+ self.pic.mb_done(addr);
ensure!(!c.overrun(), "CABAC read past end of slice data");
if c.decode_terminate() == 1 {
break;
diff --git a/crates/h264/src/deblock.rs b/crates/h264/src/deblock.rs
index 8c7c1b0c1..9ef61cfb9 100644
--- a/crates/h264/src/deblock.rs
+++ b/crates/h264/src/deblock.rs
@@ -12,18 +12,22 @@ struct Motion {
count: u8,
}
-fn block_motion(st: &MbState, sl: &SliceInfo, raster: usize) -> Motion {
+/// Referenced picture ids per 8x8 block and list (u32::MAX = list unused).
+fn ref_ids8(st: &MbState, sl: &SliceInfo) -> [[u32; 2]; 4] {
+ std::array::from_fn(|b8| {
+ std::array::from_fn(|l| {
+ let r = st.ref_idx[l][b8];
+ if r >= 0 { sl.ref_ids[l].get(r as usize).copied().unwrap_or(u32::MAX - 1) } else { u32::MAX }
+ })
+ })
+}
+
+#[inline(always)]
+fn block_motion(st: &MbState, ids8: &[[u32; 2]; 4], raster: usize) -> Motion {
let b8 = (raster >> 3) * 2 + ((raster & 3) >> 1);
- let mut m = Motion { ids: [u32::MAX; 2], mv: [[0; 2]; 2], count: 0 };
- for l in 0..2 {
- let r = st.ref_idx[l][b8];
- if r >= 0 {
- m.ids[l] = sl.ref_ids[l].get(r as usize).copied().unwrap_or(u32::MAX - 1);
- m.mv[l] = st.mv[l][raster];
- m.count += 1;
- }
- }
- m
+ let ids = ids8[b8];
+ let count = (ids[0] != u32::MAX) as u8 + (ids[1] != u32::MAX) as u8;
+ Motion { ids, mv: [st.mv[0][raster], st.mv[1][raster]], count }
}
#[inline(always)]
@@ -31,7 +35,11 @@ fn mv_far(a: [i16; 2], b: [i16; 2]) -> bool {
(a[0] as i32 - b[0] as i32).abs() >= 4 || (a[1] as i32 - b[1] as i32).abs() >= 4
}
+#[inline]
fn motion_bs(p: &Motion, q: &Motion) -> u8 {
+ if p.ids == q.ids && p.mv == q.mv {
+ return 0;
+ }
if p.count != q.count {
return 1;
}
@@ -64,96 +72,129 @@ fn motion_bs(p: &Motion, q: &Motion) -> u8 {
}
}
-/// bS for the edge between 4x4 block `rp` of MB `p` and 4x4 block `rq` of MB `q`.
-#[allow(clippy::too_many_arguments)]
-fn compute_bs(p: &MbState, sp: &SliceInfo, rp: usize, q: &MbState, sq: &SliceInfo, rq: usize, mb_edge: bool) -> u8 {
- if p.kind.is_intra() || q.kind.is_intra() {
- return if mb_edge { 4 } else { 3 };
- }
- if (p.nz_mask >> rp) & 1 != 0 || (q.nz_mask >> rq) & 1 != 0 {
- return 2;
- }
- motion_bs(&block_motion(p, sp, rp), &block_motion(q, sq, rq))
-}
-
#[inline(always)]
fn clip3(lo: i32, hi: i32, v: i32) -> i32 {
v.clamp(lo, hi)
}
-/// Filter one line of samples across an edge. `pix` is the plane, `q0` the index of q0 and `step` the
-/// distance between successive samples across the edge.
+/// Filter one set of eight samples p3 p2 p1 p0 | q0 q1 q2 q3 across an edge (8.7.2.3 / 8.7.2.4).
#[inline(always)]
-#[allow(clippy::too_many_arguments)]
-fn filter_line(pix: &mut [u8], q0: usize, step: usize, bs: u8, alpha: i32, beta: i32, tc0: i32, chroma: bool) {
- let p0i = q0 - step;
- let p0 = pix[p0i] as i32;
- let q0v = pix[q0] as i32;
- let p1 = pix[p0i - step] as i32;
- let q1 = pix[q0 + step] as i32;
- if (p0 - q0v).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0v).abs() >= beta {
+fn filter8(v: &mut [u8; 8], bs: u8, alpha: i32, beta: i32, tc0: i32, chroma: bool) {
+ let p0 = v[3] as i32;
+ let q0 = v[4] as i32;
+ let p1 = v[2] as i32;
+ let q1 = v[5] as i32;
+ if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta {
return;
}
if chroma {
if bs < 4 {
let tc = tc0 + 1;
- let delta = clip3(-tc, tc, (((q0v - p0) << 2) + (p1 - q1) + 4) >> 3);
- pix[p0i] = (p0 + delta).clamp(0, 255) as u8;
- pix[q0] = (q0v - delta).clamp(0, 255) as u8;
+ let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3);
+ v[3] = (p0 + delta).clamp(0, 255) as u8;
+ v[4] = (q0 - delta).clamp(0, 255) as u8;
} else {
- pix[p0i] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
- pix[q0] = ((2 * q1 + q0v + p1 + 2) >> 2) as u8;
+ v[3] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
+ v[4] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8;
}
return;
}
- let p2 = pix[p0i - 2 * step] as i32;
- let q2 = pix[q0 + 2 * step] as i32;
+ let p2 = v[1] as i32;
+ let q2 = v[6] as i32;
let ap = (p2 - p0).abs();
- let aq = (q2 - q0v).abs();
+ let aq = (q2 - q0).abs();
if bs < 4 {
let tc = tc0 + (ap < beta) as i32 + (aq < beta) as i32;
- let delta = clip3(-tc, tc, (((q0v - p0) << 2) + (p1 - q1) + 4) >> 3);
- pix[p0i] = (p0 + delta).clamp(0, 255) as u8;
- pix[q0] = (q0v - delta).clamp(0, 255) as u8;
+ let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3);
+ v[3] = (p0 + delta).clamp(0, 255) as u8;
+ v[4] = (q0 - delta).clamp(0, 255) as u8;
if ap < beta {
- pix[p0i - step] = (p1 + clip3(-tc0, tc0, (p2 + ((p0 + q0v + 1) >> 1) - (p1 << 1)) >> 1)) as u8;
+ v[2] = (p1 + clip3(-tc0, tc0, (p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1)) as u8;
}
if aq < beta {
- pix[q0 + step] = (q1 + clip3(-tc0, tc0, (q2 + ((p0 + q0v + 1) >> 1) - (q1 << 1)) >> 1)) as u8;
+ v[5] = (q1 + clip3(-tc0, tc0, (q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1)) as u8;
}
} else {
- let strong = (p0 - q0v).abs() < ((alpha >> 2) + 2);
+ let strong = (p0 - q0).abs() < ((alpha >> 2) + 2);
if ap < beta && strong {
- let p3 = pix[p0i - 3 * step] as i32;
- pix[p0i] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0v + q1 + 4) >> 3) as u8;
- pix[p0i - step] = ((p2 + p1 + p0 + q0v + 2) >> 2) as u8;
- pix[p0i - 2 * step] = ((2 * p3 + 3 * p2 + p1 + p0 + q0v + 4) >> 3) as u8;
+ let p3 = v[0] as i32;
+ v[3] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3) as u8;
+ v[2] = ((p2 + p1 + p0 + q0 + 2) >> 2) as u8;
+ v[1] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3) as u8;
} else {
- pix[p0i] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
+ v[3] = ((2 * p1 + p0 + q1 + 2) >> 2) as u8;
}
if aq < beta && strong {
- let q3 = pix[q0 + 3 * step] as i32;
- pix[q0] = ((p1 + 2 * p0 + 2 * q0v + 2 * q1 + q2 + 4) >> 3) as u8;
- pix[q0 + step] = ((p0 + q0v + q1 + q2 + 2) >> 2) as u8;
- pix[q0 + 2 * step] = ((2 * q3 + 3 * q2 + q1 + q0v + p0 + 4) >> 3) as u8;
+ let q3 = v[7] as i32;
+ v[4] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3) as u8;
+ v[5] = ((p0 + q0 + q1 + q2 + 2) >> 2) as u8;
+ v[6] = ((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3) as u8;
} else {
- pix[q0] = ((2 * q1 + q0v + p1 + 2) >> 2) as u8;
+ v[4] = ((2 * q1 + q0 + p1 + 2) >> 2) as u8;
+ }
+ }
+}
+
+/// Edge filter parameters for `n` lines; `bs[i]` / `tc0[i]` apply to lines `i * n / 4 .. (i + 1) * n / 4`.
+struct EdgeParams {
+ bs: [u8; 4],
+ tc0: [i32; 4],
+ alpha: i32,
+ beta: i32,
+}
+
+/// Filter a vertical edge whose q0 column is at `x`, for `n` lines starting at row `y`.
+#[inline(always)]
+fn filter_vertical(pix: &mut [u8], stride: usize, x: usize, y: usize, n: usize, ep: &EdgeParams, chroma: bool) {
+ let per = n / 4;
+ for i in 0..n {
+ let k = i / per;
+ let b = ep.bs[k];
+ if b == 0 {
+ continue;
}
+ let o = (y + i) * stride + x - 4;
+ let v: &mut [u8; 8] = (&mut pix[o..o + 8]).try_into().unwrap();
+ filter8(v, b, ep.alpha, ep.beta, ep.tc0[k], chroma);
}
}
-/// Deblock the whole picture in place.
-pub fn deblock_picture(pic: &mut PicState) {
- let mb_w = pic.mb_w;
- for addr in 0..pic.mbs.len() {
- deblock_mb(pic, addr, mb_w);
+/// Filter a horizontal edge whose q0 row is `y`, for `n` columns starting at `x`.
+#[inline(always)]
+fn filter_horizontal(pix: &mut [u8], stride: usize, x: usize, y: usize, n: usize, ep: &EdgeParams, chroma: bool) {
+ let base = (y - 4) * stride + x;
+ let rest = &mut pix[base..];
+ let (r0, rest) = rest.split_at_mut(stride);
+ let (r1, rest) = rest.split_at_mut(stride);
+ let (r2, rest) = rest.split_at_mut(stride);
+ let (r3, rest) = rest.split_at_mut(stride);
+ let (r4, rest) = rest.split_at_mut(stride);
+ let (r5, rest) = rest.split_at_mut(stride);
+ let (r6, rest) = rest.split_at_mut(stride);
+ let r7 = &mut rest[..n];
+ let (r0, r1, r2, r3, r4, r5, r6) = (&mut r0[..n], &mut r1[..n], &mut r2[..n], &mut r3[..n], &mut r4[..n], &mut r5[..n], &mut r6[..n]);
+ let per = n / 4;
+ for c in 0..n {
+ let k = c / per;
+ let b = ep.bs[k];
+ if b == 0 {
+ continue;
+ }
+ let mut v = [r0[c], r1[c], r2[c], r3[c], r4[c], r5[c], r6[c], r7[c]];
+ filter8(&mut v, b, ep.alpha, ep.beta, ep.tc0[k], chroma);
+ r1[c] = v[1];
+ r2[c] = v[2];
+ r3[c] = v[3];
+ r4[c] = v[4];
+ r5[c] = v[5];
+ r6[c] = v[6];
}
}
/// 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];
+ let q = &pic.mbs[addr];
if q.slice_num == u32::MAX {
return;
}
@@ -162,79 +203,90 @@ pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) {
return;
}
let (mx, my) = (addr % mb_w, addr / mb_w);
- let left = if mx > 0 { Some(addr - 1) } else { None };
- let top = if my > 0 { Some(addr - mb_w) } else { None };
let usable = |n: Option<usize>| -> Option<usize> {
let n = n?;
let st = &pic.mbs[n];
- if st.slice_num == u32::MAX {
- return None;
- }
- if sq.disable_deblocking_filter_idc == 2 && st.slice_num != q.slice_num {
+ 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(left);
- let top = usable(top);
+ 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 mut bs = [[[0u8; 4]; 4]; 2];
- for dir in 0..2 {
- for e in 0..4 {
- if e > 0 && t8 && e % 2 == 1 {
- continue;
+ if q.kind.is_intra() {
+ for dir in 0..2 {
+ if (if dir == 0 { left } else { top }).is_some() {
+ bs[dir][0] = [4; 4];
}
- let neighbor = if dir == 0 { left } else { top };
- if e == 0 && neighbor.is_none() {
- continue;
+ for e in 1..4 {
+ if !(t8 && e % 2 == 1) {
+ bs[dir][e] = [3; 4];
+ }
}
- for k in 0..4 {
- let (rq, rp, pmb) = if dir == 0 {
- let rq = k * 4 + e;
- if e == 0 { (rq, k * 4 + 3, neighbor.unwrap()) } else { (rq, rq - 1, addr) }
+ }
+ } else {
+ let qids = ref_ids8(q, sq);
+ 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 rq = e * 4 + k;
- if e == 0 { (rq, 12 + k, neighbor.unwrap()) } else { (rq, rq - 4, addr) }
- };
- let p = &pic.mbs[pmb];
- let sp = &pic.slices[p.slice_num as usize];
- bs[dir][e][k] = compute_bs(p, sp, rp, &q, sq, rq, e == 0);
+ 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]) };
+ }
+ }
+ }
+ 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]) };
+ }
}
}
}
+ 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;
- let qp_of = |st: &MbState| if st.kind == MbKind::IPcm { 0 } else { st.qp as i32 };
// luma
for dir in 0..2 {
for e in 0..4 {
if bs[dir][e] == [0; 4] {
continue;
}
- let pmb = if e == 0 { if dir == 0 { left.unwrap() } else { top.unwrap() } } else { addr };
- let qpav = (qp_of(&pic.mbs[pmb]) + qp_of(&q) + 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 alpha = ALPHA[index_a] as i32;
- let beta = BETA[index_b] as i32;
- for k in 0..4 {
- let b = bs[dir][e][k];
- if b == 0 {
- continue;
- }
- let tc0 = if b < 4 { TC0[index_a][b as usize - 1] as i32 } else { 0 };
- for i in 0..4 {
- let (x, y) = if dir == 0 { (mx * 16 + e * 4, my * 16 + k * 4 + i) } else { (mx * 16 + k * 4 + i, my * 16 + e * 4) };
- let step = if dir == 0 { 1 } else { width };
- filter_line(&mut pic.planes.y, y * width + x, step, b, alpha, beta, tc0, false);
- }
+ 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]);
+ if dir == 0 {
+ filter_vertical(&mut pic.planes.y, width, mx * 16 + e * 4, my * 16, 16, &ep, false);
+ } else {
+ filter_horizontal(&mut pic.planes.y, width, mx * 16, my * 16 + e * 4, 16, &ep, false);
}
}
}
- // chroma: edges 0 and 2 (in 4x4 luma edge units), 8 lines each (4:2:0: chroma edge at 0 and 4 samples)
+ // chroma (4:2:0): edges at chroma samples 0 and 4 use the bS of luma edges 0 and 2
for c in 0..2 {
for dir in 0..2 {
for ce in 0..2 {
@@ -242,23 +294,13 @@ pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) {
if bs[dir][e] == [0; 4] {
continue;
}
- let pmb = if e == 0 { if dir == 0 { left.unwrap() } else { top.unwrap() } } else { addr };
- let qpp = pic.mbs[pmb].qpc[c] as i32;
- let qpav = (qpp + q.qpc[c] as i32 + 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 alpha = ALPHA[index_a] as i32;
- let beta = BETA[index_b] as i32;
- for i in 0..8 {
- let b = bs[dir][e][i / 2];
- if b == 0 {
- continue;
- }
- let tc0 = if b < 4 { TC0[index_a][b as usize - 1] as i32 } else { 0 };
- let (x, y) = if dir == 0 { (mx * 8 + ce * 4, my * 8 + i) } else { (mx * 8 + i, my * 8 + ce * 4) };
- let step = if dir == 0 { 1 } else { cwidth };
- let plane = if c == 0 { &mut pic.planes.cb } else { &mut pic.planes.cr };
- filter_line(plane, y * cwidth + x, step, b, alpha, beta, tc0, true);
+ 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 plane = if c == 0 { &mut pic.planes.cb } else { &mut pic.planes.cr };
+ if dir == 0 {
+ filter_vertical(plane, cwidth, mx * 8 + ce * 4, my * 8, 8, &ep, true);
+ } else {
+ filter_horizontal(plane, cwidth, mx * 8, my * 8 + ce * 4, 8, &ep, true);
}
}
}
diff --git a/crates/h264/src/decoder.rs b/crates/h264/src/decoder.rs
index 6e11824c0..4b83b1014 100644
--- a/crates/h264/src/decoder.rs
+++ b/crates/h264/src/decoder.rs
@@ -1,25 +1,50 @@
-//! Top-level decoder: NAL dispatch, picture boundaries, POC, DPB, output.
+//! Top-level decoder: NAL dispatch, picture boundaries, POC, DPB and output.
+//!
+//! The calling thread parses headers and does all DPB / reference list bookkeeping (which only needs
+//! header information). Macroblock decoding of each picture runs as a job — on a thread pool with the
+//! `threads` feature — that publishes finished macroblock rows into the picture's shared [`Frame`];
+//! jobs of later pictures block per row on the reference data they need, so several pictures decode
+//! concurrently (frame-level parallelism).
-use crate::deblock;
use crate::dpb::{Dpb, Output, OutputMeta};
-use crate::error::{Error, Result, ensure, unsupported};
+use crate::error::{Error, Result, ensure, invalid, unsupported};
use crate::params::{Pps, Sps};
-use crate::picture::{Frame, MotionField, Planes};
-use crate::slice::{NalHeader, Poc, PocState, SliceHeader, nal_type};
+use crate::picture::{Frame, FrameRef, MbState, Planes, RefPic};
+use crate::slice::{NalHeader, Poc, PocState, SliceHeader, SliceType, nal_type};
use crate::slicedec::{PicState, SliceDecoder};
use crate::transform::LevelScale;
use crate::{ColorInfo, Picture};
use filmcraft_bitstream::{BitReader, annexb_nals, length_prefixed_nals, unescape_rbsp};
-use std::sync::Arc;
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
-struct CurPic {
- pic: PicState,
- first: SliceHeader,
+/// One slice of a picture job.
+struct SliceJob {
+ sh: SliceHeader,
+ pps: Arc<Pps>,
sps: Arc<Sps>,
+ rbsp: Vec<u8>,
+ refs: [Vec<RefPic>; 2],
+ ls: Arc<LevelScale>,
+}
+
+/// A picture whose slices are being collected.
+struct PendingPic {
+ frame: FrameRef,
+ sps: Arc<Sps>,
+ first: SliceHeader,
poc: Poc,
pts: i64,
key: bool,
- has_mmco5: bool,
+ slices: Vec<SliceJob>,
+}
+
+/// State shared with decoding jobs.
+#[derive(Default)]
+struct Shared {
+ error: Mutex<Option<Error>>,
+ /// Recycled picture buffers.
+ pool: Mutex<Vec<PicState>>,
}
/// H.264 decoder.
@@ -30,11 +55,17 @@ pub struct Decoder {
dpb: Dpb,
poc_state: PocState,
prev_ref_frame_num: u32,
- cur: Option<CurPic>,
+ pending: Option<PendingPic>,
next_id: u32,
active_sps: Option<Arc<Sps>>,
ls_cache: Vec<(Arc<Pps>, Arc<LevelScale>)>,
- out: Vec<Picture>,
+ /// Pictures leaving the DPB, converted once their decoding job has finished.
+ out_queue: VecDeque<Output>,
+ shared: Arc<Shared>,
+ #[cfg(feature = "threads")]
+ pool: Option<rayon::ThreadPool>,
+ in_flight: VecDeque<FrameRef>,
+ max_in_flight: usize,
}
impl Default for Decoder {
@@ -64,9 +95,32 @@ fn is_new_picture(prev: &SliceHeader, sh: &SliceHeader, sps: &Sps) -> bool {
false
}
+fn default_threads() -> usize {
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ {
+ std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).min(16)
+ }
+ #[cfg(not(all(feature = "threads", not(target_arch = "wasm32"))))]
+ {
+ 1
+ }
+}
+
impl Decoder {
+ /// A decoder using all available cores (with the `threads` feature).
pub fn new() -> Self {
+ Self::with_threads(default_threads())
+ }
+
+ /// A decoder using up to `threads` worker threads (1 = decode on the calling thread).
+ pub fn with_threads(threads: usize) -> Self {
crate::cavlc::init_tables();
+ #[cfg(feature = "threads")]
+ let pool = if threads > 1 && cfg!(not(target_arch = "wasm32")) {
+ rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("h264-{i}")).build().ok()
+ } else {
+ None
+ };
Decoder {
spss: vec![None; 32],
ppss: vec![None; 256],
@@ -74,20 +128,31 @@ impl Decoder {
dpb: Dpb::new(),
poc_state: PocState::default(),
prev_ref_frame_num: 0,
- cur: None,
+ pending: None,
next_id: 1,
active_sps: None,
ls_cache: Vec::new(),
- out: Vec::new(),
+ out_queue: VecDeque::new(),
+ shared: Arc::new(Shared::default()),
+ #[cfg(feature = "threads")]
+ pool,
+ in_flight: VecDeque::new(),
+ max_in_flight: threads.max(1) + 2,
}
}
/// Configure from an `avcC` (AVCDecoderConfigurationRecord) box payload.
pub fn from_avcc(avcc: &[u8]) -> Result<Self> {
let mut d = Decoder::new();
+ d.configure_avcc(avcc)?;
+ Ok(d)
+ }
+
+ /// Parse an `avcC` record: SPS/PPS and the NAL length size used by [`Decoder::decode`].
+ pub fn configure_avcc(&mut self, avcc: &[u8]) -> Result<()> {
ensure!(avcc.len() >= 7, "avcC too short");
ensure!(avcc[0] == 1, "unsupported avcC version {}", avcc[0]);
- d.nal_length_size = Some((avcc[4] & 3) as usize + 1);
+ self.nal_length_size = Some((avcc[4] & 3) as usize + 1);
let mut pos = 5;
let read_sets = |pos: &mut usize, count: usize, d: &mut Decoder| -> Result<()> {
for _ in 0..count {
@@ -102,12 +167,11 @@ impl Decoder {
};
let nsps = (avcc[pos] & 0x1f) as usize;
pos += 1;
- read_sets(&mut pos, nsps, &mut d)?;
+ read_sets(&mut pos, nsps, self)?;
ensure!(pos < avcc.len(), "avcC truncated");
let npps = avcc[pos] as usize;
pos += 1;
- read_sets(&mut pos, npps, &mut d)?;
- Ok(d)
+ read_sets(&mut pos, npps, self)
}
/// Length of NAL length prefixes (from avcC), or None for Annex-B input.
@@ -115,7 +179,10 @@ impl Decoder {
self.nal_length_size
}
- /// Decode one access unit. Returns pictures that became ready for output, in output order.
+ /// Decode one access unit (all NAL units of one picture, Annex-B or length-prefixed per
+ /// configuration; a byte stream with several complete access units is accepted too). Returns
+ /// pictures that became ready for output, in output order; `pts` travels with the picture of
+ /// this access unit through reordering.
pub fn decode(&mut self, data: &[u8], pts: i64) -> Result<Vec<Picture>> {
let nals = match self.nal_length_size {
Some(n) => length_prefixed_nals(data, n)?,
@@ -128,23 +195,42 @@ impl Decoder {
break;
}
}
- // Finish a complete picture at the end of the access unit.
- if self.cur.as_ref().is_some_and(|c| c.pic.decoded_mbs >= c.pic.mbs.len()) {
- self.finish_picture();
+ // The access unit is complete: hand its picture to a decoding job.
+ self.submit_pending();
+ if let Some(e) = self.take_error() {
+ result = result.and(Err(e));
}
result?;
- Ok(std::mem::take(&mut self.out))
+ // Return finished pictures without blocking on frames still being decoded (bounded latency).
+ let max_queue = self.max_in_flight * 2;
+ let mut pics = Vec::new();
+ while let Some(o) = self.out_queue.front() {
+ if !o.frame.is_published(o.frame.mb_h() - 1) && self.out_queue.len() <= max_queue {
+ break;
+ }
+ let o = self.out_queue.pop_front().expect("front exists");
+ pics.push(make_picture(&o));
+ }
+ Ok(pics)
}
- /// Output all remaining pictures.
+ /// Output all remaining pictures (end of stream).
pub fn flush(&mut self) -> Vec<Picture> {
- if self.cur.is_some() {
- self.finish_picture();
- }
+ self.submit_pending();
let mut outs = Vec::new();
self.dpb.flush(&mut outs);
self.emit(outs);
- std::mem::take(&mut self.out)
+ let pics = self.out_queue.drain(..).map(|o| make_picture(&o)).collect();
+ while let Some(f) = self.in_flight.pop_front() {
+ f.wait_complete();
+ }
+ pics
+ }
+
+ /// First error reported by a decoding job since the last call (also returned by
+ /// [`Decoder::decode`]); useful after [`Decoder::flush`].
+ pub fn take_error(&mut self) -> Option<Error> {
+ self.shared.error.lock().ok().and_then(|mut e| e.take())
}
fn handle_nal(&mut self, nal: &[u8], pts: i64) -> Result<()> {
@@ -160,7 +246,8 @@ impl Decoder {
}
nal_type::PPS => {
let rbsp = unescape_rbsp(&nal[1..]);
- let pps = Pps::parse(&rbsp, &self.spss_plain())?;
+ let spss: Vec<Option<Sps>> = self.spss.iter().map(|s| s.as_ref().map(|s| (**s).clone())).collect();
+ let pps = Pps::parse(&rbsp, &spss)?;
let id = pps.id as usize;
self.ppss[id] = Some(Arc::new(pps));
}
@@ -168,17 +255,13 @@ impl Decoder {
nal_type::SLICE_DPA | nal_type::SLICE_DPB | nal_type::SLICE_DPC => {
return unsupported("data partitioning (Extended profile)");
}
- nal_type::END_SEQ | nal_type::END_STREAM if self.cur.is_some() => self.finish_picture(),
+ nal_type::END_SEQ | nal_type::END_STREAM => self.submit_pending(),
// SEI, AUD, filler, SPS extension, prefix NAL, subset SPS, auxiliary and extension slices: skipped.
_ => {}
}
Ok(())
}
- fn spss_plain(&self) -> Vec<Option<Sps>> {
- self.spss.iter().map(|s| s.as_ref().map(|s| (**s).clone())).collect()
- }
-
fn level_scale(&mut self, pps: &Arc<Pps>) -> Arc<LevelScale> {
if let Some((_, ls)) = self.ls_cache.iter().find(|(p, _)| Arc::ptr_eq(p, pps)) {
return ls.clone();
@@ -208,42 +291,33 @@ impl Decoder {
if sh.field_pic {
return unsupported("field pictures");
}
- if matches!(sh.slice_type, crate::slice::SliceType::Sp | crate::slice::SliceType::Si) {
+ if matches!(sh.slice_type, SliceType::Sp | SliceType::Si) {
return unsupported("SP/SI slices");
}
if sh.redundant_pic_cnt > 0 {
return Ok(()); // redundant slices are ignored
}
- let new_pic = match &self.cur {
+ let new_pic = match &self.pending {
None => true,
- Some(c) => is_new_picture(&c.first, &sh, &sps) || (sh.first_mb_in_slice == 0 && c.pic.decoded_mbs > 0) || !Arc::ptr_eq(&c.sps, &sps),
+ Some(p) => is_new_picture(&p.first, &sh, &sps) || sh.first_mb_in_slice == 0 || !Arc::ptr_eq(&p.sps, &sps),
};
if new_pic {
- if self.cur.is_some() {
- self.finish_picture();
+ self.submit_pending();
+ if sh.first_mb_in_slice != 0 && self.active_sps.is_none() {
+ return invalid("stream does not start with the first slice of a picture");
}
self.start_picture(&sh, &sps, pts)?;
}
let ls = self.level_scale(&pps);
- let cur = self.cur.as_mut().expect("picture started");
- if sh.has_mmco5() {
- cur.has_mmco5 = true;
- }
- let refs = self.dpb.build_ref_lists(&sh, cur.poc.frame(), sps.max_frame_num())?;
+ let pending = self.pending.as_mut().expect("picture started");
+ let refs = self.dpb.build_ref_lists(&sh, pending.poc.frame(), sps.max_frame_num())?;
if !sh.slice_type.is_intra() {
ensure!(!refs[0].is_empty(), "no reference pictures available for inter slice");
if sh.slice_type.is_b() {
ensure!(!refs[1].is_empty(), "empty RefPicList1 in B slice");
}
}
- let mut sd = SliceDecoder::new(&sh, &pps, &sps, &mut cur.pic, &refs, &ls)?;
- if pps.entropy_coding_mode {
- sd.decode_cabac(&rbsp)?;
- } else {
- let mut r = BitReader::new(&rbsp);
- r.seek_bits(sh.header_bits);
- sd.decode_cavlc(&mut r)?;
- }
+ pending.slices.push(SliceJob { sh, pps, sps, rbsp, refs, ls });
Ok(())
}
@@ -270,26 +344,29 @@ impl Decoder {
self.emit(outs);
self.prev_ref_frame_num = 0;
} else {
- if self.dpb.entries.iter().all(|e| e.mark == crate::dpb::RefMark::Unused) && !sh.slice_type.is_intra() {
- // Stream starts without an IDR: nothing to reference; decoding will conceal.
- }
let max = sps.max_frame_num();
if sh.frame_num != self.prev_ref_frame_num && sh.frame_num != (self.prev_ref_frame_num + 1) % max {
- // frame_num gap (8.2.5.2)
- let (w, h) = (mb_w * 16, mb_h * 16);
+ // frame_num gap (8.2.5.2): insert "non-existing" frames. Their samples are never used by
+ // conforming streams; copy the latest decoded frame for concealment.
let meta = Arc::new(output_meta(sps, pts, false));
let next_id = &mut self.next_id;
let poc_state = &mut self.poc_state;
- let prev_last = self.dpb.entries.iter().filter(|e| !e.non_existing).max_by_key(|e| e.frame.id).map(|e| e.frame.clone());
+ let last = self.dpb.entries.iter().filter(|e| !e.non_existing).max_by_key(|e| e.frame.id).map(|e| e.frame.clone());
let mut make = |_fnum: u32| {
let id = *next_id;
*next_id += 1;
- let planes = match &prev_last {
- Some(f) => f.planes.clone(),
- None => Planes::gray(w, h),
+ let planes = match &last {
+ Some(f) if f.mb_w == mb_w && f.mb_h() == mb_h => {
+ let mut p = Planes::new(mb_w * 16, mb_h * 16);
+ let (y, u, v) = f.copy_cropped((0, 0, mb_w * 16, mb_h * 16));
+ p.y = y;
+ p.cb = u;
+ p.cr = v;
+ p
+ }
+ _ => Planes::gray(mb_w * 16, mb_h * 16),
};
- let frame = Arc::new(Frame { id, poc: 0, planes, motion: MotionField::default() });
- (frame, meta.clone())
+ (Arc::new(Frame::from_planes(id, 0, &planes)), meta.clone())
};
let mut upd = |fnum: u32| poc_state.update_gap_frame(fnum, sps);
self.dpb.fill_frame_num_gap(self.prev_ref_frame_num, sh.frame_num, max, sps.max_num_ref_frames as usize, &mut make, &mut upd);
@@ -297,99 +374,128 @@ impl Decoder {
}
}
let poc = self.poc_state.compute(sh, sps);
- let pic = PicState::new(mb_w, mb_h, poc.frame());
- self.cur = Some(CurPic { pic, first: sh.clone(), sps: sps.clone(), poc, pts, key: sh.idr, has_mmco5: false });
+ // MMCO5: the picture's POC becomes relative to itself (tempPicOrderCnt, 8.2.1).
+ let frame_poc = if sh.has_mmco5() { 0 } else { poc.frame() };
+ let id = self.next_id;
+ self.next_id += 1;
+ let frame = Arc::new(Frame::new(id, frame_poc, mb_w, mb_h));
+ self.pending = Some(PendingPic { frame, sps: sps.clone(), first: sh.clone(), poc, pts, key: sh.idr, slices: Vec::new() });
Ok(())
}
-}
-fn output_meta(sps: &Sps, pts: i64, key: bool) -> OutputMeta {
- {
- let vui = sps.vui.clone().unwrap_or_default();
- OutputMeta {
- pts,
- key,
- crop: sps.crop_rect(),
- full_range: vui.full_range,
- colour_primaries: vui.colour_primaries,
- transfer_characteristics: vui.transfer_characteristics,
- matrix_coefficients: vui.matrix_coefficients,
- sar: vui.sar,
+ /// Start decoding the pending picture and do its reference marking / DPB insertion.
+ fn submit_pending(&mut self) {
+ let Some(p) = self.pending.take() else { return };
+ let PendingPic { frame, sps, first, poc, pts, key, slices } = p;
+ self.dispatch(frame.clone(), slices);
+ self.poc_state.update(&first, &poc);
+ if first.nal_ref_idc != 0 {
+ self.prev_ref_frame_num = if first.has_mmco5() { 0 } else { first.frame_num };
}
+ let meta = Arc::new(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.emit(outs);
}
-}
-impl Decoder {
- fn finish_picture(&mut self) {
- let Some(mut cur) = self.cur.take() else { return };
- deblock::deblock_picture(&mut cur.pic);
- // motion field for co-located use
- let n = cur.pic.mbs.len();
- let mut motion = MotionField {
- mv: [vec![[0; 2]; n * 16], vec![[0; 2]; n * 16]],
- ref_idx: [vec![-1; n * 4], vec![-1; n * 4]],
- ref_id: [vec![u32::MAX; n * 4], vec![u32::MAX; n * 4]],
- intra: vec![true; n],
- };
- for (i, st) in cur.pic.mbs.iter().enumerate() {
- if st.slice_num == u32::MAX {
- continue;
- }
- motion.intra[i] = st.kind.is_intra();
- let sl = &cur.pic.slices[st.slice_num as usize];
- for l in 0..2 {
- motion.mv[l][i * 16..i * 16 + 16].copy_from_slice(&st.mv[l]);
- for b in 0..4 {
- let r = st.ref_idx[l][b];
- motion.ref_idx[l][i * 4 + b] = r;
- if r >= 0 {
- motion.ref_id[l][i * 4 + b] = sl.ref_ids[l].get(r as usize).copied().unwrap_or(u32::MAX);
- }
+ fn dispatch(&mut self, frame: FrameRef, slices: Vec<SliceJob>) {
+ let shared = self.shared.clone();
+ #[cfg(feature = "threads")]
+ if let Some(pool) = &self.pool {
+ self.in_flight.retain(|f| !f.is_published(f.mb_h() - 1));
+ while self.in_flight.len() >= self.max_in_flight {
+ if let Some(f) = self.in_flight.pop_front() {
+ f.wait_complete();
}
}
+ self.in_flight.push_back(frame.clone());
+ pool.spawn_fifo(move || run_job(frame, slices, &shared));
+ return;
}
- let mut poc = cur.poc.frame();
- let sh = cur.first.clone();
- if cur.has_mmco5 {
- // tempPicOrderCnt adjustment (8.2.1): the picture's POC becomes relative to itself.
- poc -= cur.poc.frame();
- }
- let id = self.next_id;
- self.next_id += 1;
- let frame = Arc::new(Frame { id, poc, planes: cur.pic.planes, motion });
- let meta = Arc::new(output_meta(&cur.sps, cur.pts, cur.key));
- let sh_eff = sh.clone();
- self.poc_state.update(&sh_eff, &cur.poc);
- if sh.nal_ref_idc != 0 {
- self.prev_ref_frame_num = if cur.has_mmco5 { 0 } else { sh.frame_num };
- }
- let mut outs = Vec::new();
- self.dpb.store_picture(&sh_eff, frame, poc, cur.sps.max_frame_num(), cur.sps.max_num_ref_frames as usize, meta, &mut outs);
- self.emit(outs);
+ run_job(frame, slices, &shared);
}
fn emit(&mut self, outs: Vec<Output>) {
- for o in outs {
- self.out.push(make_picture(&o));
+ self.out_queue.extend(outs);
+ }
+}
+
+/// Decode all slices of one picture and publish its rows.
+fn run_job(frame: FrameRef, slices: Vec<SliceJob>, shared: &Shared) {
+ let reuse = shared.pool.lock().ok().and_then(|mut p| p.pop());
+ let mut pic = match reuse {
+ Some(mut p) if p.mb_w == frame.mb_w && p.mb_h == frame.mb_h() => {
+ p.reset(frame.clone());
+ p
+ }
+ _ => PicState::new(frame.clone()),
+ };
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let mut first_err = None;
+ for s in &slices {
+ if let Err(e) = decode_slice(s, &mut pic) {
+ first_err.get_or_insert(e);
+ }
}
+ pic.flush_rows(true);
+ first_err
+ }));
+ let err = match result {
+ Ok(e) => e,
+ Err(_) => {
+ // Make sure readers never block on this frame.
+ let fallback = Planes::gray(frame.width, frame.height);
+ let blank = vec![MbState::default(); frame.mb_w * frame.mb_h()];
+ for r in 0..frame.mb_h() {
+ if !frame.is_published(r) {
+ frame.publish(r, Frame::make_row(&fallback, r, &blank, &|_, _, _| u32::MAX));
+ }
+ }
+ pic = PicState::new(frame.clone());
+ Some(Error::Invalid("internal error while decoding a picture".into()))
+ }
+ };
+ if let (Some(e), Ok(mut slot)) = (err, shared.error.lock()) {
+ slot.get_or_insert(e);
+ }
+ if let Ok(mut p) = shared.pool.lock()
+ && p.len() < 4
+ {
+ p.push(pic);
+ }
+}
+
+fn decode_slice(s: &SliceJob, pic: &mut PicState) -> Result<()> {
+ let mut sd = SliceDecoder::new(&s.sh, &s.pps, &s.sps, pic, &s.refs, &s.ls)?;
+ if s.pps.entropy_coding_mode {
+ sd.decode_cabac(&s.rbsp)
+ } else {
+ let mut r = BitReader::new(&s.rbsp);
+ r.seek_bits(s.sh.header_bits);
+ sd.decode_cavlc(&mut r)
+ }
+}
+
+fn output_meta(sps: &Sps, pts: i64, key: bool) -> OutputMeta {
+ let vui = sps.vui.clone().unwrap_or_default();
+ OutputMeta {
+ pts,
+ key,
+ crop: sps.crop_rect(),
+ full_range: vui.full_range,
+ colour_primaries: vui.colour_primaries,
+ transfer_characteristics: vui.transfer_characteristics,
+ matrix_coefficients: vui.matrix_coefficients,
+ sar: vui.sar,
}
}
fn make_picture(o: &Output) -> Picture {
- let p = &o.frame.planes;
let (cx, cy, cw, ch) = o.meta.crop;
let (cx, cy, cw, ch) = (cx as usize, cy as usize, cw as usize, ch as usize);
- let mut y = Vec::with_capacity(cw * ch);
- for r in cy..cy + ch {
- y.extend_from_slice(&p.y[r * p.width + cx..r * p.width + cx + cw]);
- }
- let (ccx, ccy, ccw, cch) = (cx / 2, cy / 2, cw.div_ceil(2), ch.div_ceil(2));
- let mut u = Vec::with_capacity(ccw * cch);
- let mut v = Vec::with_capacity(ccw * cch);
- for r in ccy..ccy + cch {
- u.extend_from_slice(&p.cb[r * p.cwidth + ccx..r * p.cwidth + ccx + ccw]);
- v.extend_from_slice(&p.cr[r * p.cwidth + ccx..r * p.cwidth + ccx + ccw]);
- }
+ let (y, u, v) = o.frame.copy_cropped((cx, cy, cw, ch));
+ let (ccw, cch) = (cw.div_ceil(2), ch.div_ceil(2));
Picture {
width: cw as u32,
height: ch as u32,
diff --git a/crates/h264/src/inter.rs b/crates/h264/src/inter.rs
index fb73f2d9b..4e3b5699c 100644
--- a/crates/h264/src/inter.rs
+++ b/crates/h264/src/inter.rs
@@ -1,6 +1,7 @@
//! Inter prediction sample interpolation (8.4.2.2) and weighted sample prediction (8.4.2.3).
-/// A reference plane.
+/// A reference plane (used by the plane-based helpers in tests).
+#[cfg(test)]
#[derive(Clone, Copy)]
pub struct PlaneRef<'a> {
pub data: &'a [u8],
@@ -13,6 +14,7 @@ const WIN: usize = 16 + 5;
/// Copy the (bw+5)x(bh+5) window whose top-left is (x-2, y-2) into `win` (stride WIN), clamping
/// coordinates to the picture.
+#[cfg(test)]
#[inline]
fn fetch_window(p: PlaneRef, x: i32, y: i32, bw: usize, bh: usize, win: &mut [u8; WIN * WIN]) {
let x0 = x - 2;
@@ -48,101 +50,148 @@ fn clip1(v: i32) -> u8 {
v.clamp(0, 255) as u8
}
-/// Luma sample interpolation for a bw x bh block. (x, y) is the integer sample position
+#[inline(always)]
+fn avg(a: u8, b: u8) -> u8 {
+ ((a as u16 + b as u16 + 1) >> 1) as u8
+}
+
+/// Horizontal 6-tap (unclipped) at every position of `row` for `n` outputs: out[c] uses row[c..c + 6].
+#[inline(always)]
+fn htap_row(row: &[u8], out: &mut [i32], n: usize) {
+ let row = &row[..n + 5];
+ for (o, w) in out[..n].iter_mut().zip(row.windows(6)) {
+ *o = tap6(w[0] as i32, w[1] as i32, w[2] as i32, w[3] as i32, w[4] as i32, w[5] as i32);
+ }
+}
+
+/// Vertical 6-tap (unclipped) over six rows at columns 0..n.
+#[inline(always)]
+fn vtap_row(rows: [&[u8]; 6], out: &mut [i32], n: usize) {
+ let [a, b, c, d, e, f] = rows.map(|r| &r[..n]);
+ for i in 0..n {
+ out[i] = tap6(a[i] as i32, b[i] as i32, c[i] as i32, d[i] as i32, e[i] as i32, f[i] as i32);
+ }
+}
+
+/// 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) {
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]
- let g = |r: usize, c: usize| win[(r + 2) * WIN + c + 2] as i32;
- // unclipped horizontal half-sample b1 at block row r (-2..bh+3 via offset) and column c
- let b1 = |r: isize, c: usize| {
- let base = ((r + 2) as usize) * WIN + c;
- tap6(win[base] as i32, win[base + 1] as i32, win[base + 2] as i32, win[base + 3] as i32, win[base + 4] as i32, win[base + 5] as i32)
- };
- let h1 = |r: usize, c: isize| {
- let col = (c + 2) as usize;
- tap6(
- win[r * WIN + col] as i32,
- win[(r + 1) * WIN + col] as i32,
- win[(r + 2) * WIN + col] as i32,
- win[(r + 3) * WIN + col] as i32,
- win[(r + 4) * WIN + col] as i32,
- win[(r + 5) * WIN + col] as i32,
- )
+ 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;
+ let (src, ss): (&[u8], usize) = if inside {
+ (&p.data[y0 as usize * p.stride + x0 as usize..], p.stride)
+ } else {
+ fetch_window(p, x, y, bw, bh, &mut win);
+ (&win[..], WIN)
};
+ mc_luma_win(src, ss, fx, fy, bw, bh, 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) {
+ // 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];
match (fx, fy) {
(0, 0) => {
for r in 0..bh {
- out[r * os..r * os + bw].copy_from_slice(&win[(r + 2) * WIN + 2..(r + 2) * WIN + 2 + bw]);
+ out[r * os..r * os + bw].copy_from_slice(&wrow(r + 2)[2..2 + bw]);
}
}
(_, 0) => {
- // a, b, c
for r in 0..bh {
- for c in 0..bw {
- let b = clip1((b1(r as isize, c) + 16) >> 5) as i32;
- out[r * os + c] = match fx {
- 1 => ((g(r, c) + b + 1) >> 1) as u8,
- 2 => b as u8,
- _ => ((g(r, c + 1) + b + 1) >> 1) as u8,
- };
+ let row = wrow(r + 2);
+ htap_row(row, &mut t, bw);
+ let o = &mut out[r * os..r * os + bw];
+ match fx {
+ 1 => {
+ for c in 0..bw {
+ o[c] = avg(row[c + 2], clip1((t[c] + 16) >> 5));
+ }
+ }
+ 2 => {
+ for c in 0..bw {
+ o[c] = clip1((t[c] + 16) >> 5);
+ }
+ }
+ _ => {
+ for c in 0..bw {
+ o[c] = avg(row[c + 3], clip1((t[c] + 16) >> 5));
+ }
+ }
}
}
}
(0, _) => {
- // d, h, n
for r in 0..bh {
- for c in 0..bw {
- let h = clip1((h1(r, c as isize) + 16) >> 5) as i32;
- out[r * os + c] = match fy {
- 1 => ((g(r, c) + h + 1) >> 1) as u8,
- 2 => h as u8,
- _ => ((g(r + 1, c) + h + 1) >> 1) as u8,
- };
+ let rows = [wrow(r), wrow(r + 1), wrow(r + 2), wrow(r + 3), wrow(r + 4), wrow(r + 5)].map(|x| &x[2..]);
+ vtap_row(rows, &mut t, bw);
+ let g = if fy == 1 { rows[2] } else { rows[3] };
+ let o = &mut out[r * os..r * os + bw];
+ if fy == 2 {
+ for c in 0..bw {
+ o[c] = clip1((t[c] + 16) >> 5);
+ }
+ } else {
+ for c in 0..bw {
+ o[c] = avg(g[c], clip1((t[c] + 16) >> 5));
+ }
}
}
}
(2, _) | (_, 2) => {
- // j-based: j needs b1 for rows -2..bh+3
- let mut bcol = [0i32; WIN * WIN];
- for r in 0..bh + 5 {
- for c in 0..bw {
- bcol[r * WIN + c] = b1(r as isize - 2, c);
- }
+ // unclipped horizontal half samples b1 for window rows 0..bh+5
+ let mut b1 = [[0i32; 16]; WIN];
+ for (r, bt) in b1.iter_mut().enumerate().take(bh + 5) {
+ htap_row(wrow(r), bt, bw);
}
+ let mut v = [0i32; 16];
for r in 0..bh {
+ let o = &mut out[r * os..r * os + bw];
+ let (b0, b1r, b2, b3, b4, b5) = (&b1[r], &b1[r + 1], &b1[r + 2], &b1[r + 3], &b1[r + 4], &b1[r + 5]);
for c in 0..bw {
- let j1 = tap6(
- bcol[r * WIN + c],
- bcol[(r + 1) * WIN + c],
- bcol[(r + 2) * WIN + c],
- bcol[(r + 3) * WIN + c],
- bcol[(r + 4) * WIN + c],
- bcol[(r + 5) * WIN + c],
- );
- let j = clip1((j1 + 512) >> 10) as i32;
- let v = match (fx, fy) {
- (2, 2) => j,
- (2, 1) => (clip1((bcol[(r + 2) * WIN + c] + 16) >> 5) as i32 + j + 1) >> 1, // f
- (2, 3) => (clip1((bcol[(r + 3) * WIN + c] + 16) >> 5) as i32 + j + 1) >> 1, // q
- (1, 2) => (clip1((h1(r, c as isize) + 16) >> 5) as i32 + j + 1) >> 1, // i
- _ => (clip1((h1(r, c as isize + 1) + 16) >> 5) as i32 + j + 1) >> 1, // k
- };
- out[r * os + c] = v as u8;
+ t[c] = tap6(b0[c], b1r[c], b2[c], b3[c], b4[c], b5[c]);
+ }
+ match (fx, fy) {
+ (2, 2) => {
+ for c in 0..bw {
+ o[c] = clip1((t[c] + 512) >> 10);
+ }
+ }
+ (2, 1) | (2, 3) => {
+ let bh_ = if fy == 1 { b2 } else { b3 };
+ for c in 0..bw {
+ o[c] = avg(clip1((bh_[c] + 16) >> 5), clip1((t[c] + 512) >> 10));
+ }
+ }
+ _ => {
+ let off = if fx == 1 { 2 } else { 3 };
+ let rows = [wrow(r), wrow(r + 1), wrow(r + 2), wrow(r + 3), wrow(r + 4), wrow(r + 5)].map(|x| &x[off..]);
+ vtap_row(rows, &mut v, bw);
+ for c in 0..bw {
+ o[c] = avg(clip1((v[c] + 16) >> 5), clip1((t[c] + 512) >> 10));
+ }
+ }
}
}
}
_ => {
- // e, g, p, r: average of a horizontal half-sample (b or s) and a vertical one (h or m)
+ // e, g, p, r: average of a horizontal half sample (row r or r + 1) and a vertical one (col c or c + 1)
+ let hoff = if fy == 1 { 2 } else { 3 };
+ let voff = if fx == 1 { 2 } else { 3 };
+ let mut v = [0i32; 16];
for r in 0..bh {
+ htap_row(wrow(r + hoff), &mut t, bw);
+ let rows = [wrow(r), wrow(r + 1), wrow(r + 2), wrow(r + 3), wrow(r + 4), wrow(r + 5)].map(|x| &x[voff..]);
+ vtap_row(rows, &mut v, bw);
+ let o = &mut out[r * os..r * os + bw];
for c in 0..bw {
- let hr = if fy == 1 { r as isize } else { r as isize + 1 };
- let vc = if fx == 1 { c as isize } else { c as isize + 1 };
- let bh_ = clip1((b1(hr, c) + 16) >> 5) as i32;
- let vv = clip1((h1(r, vc) + 16) >> 5) as i32;
- out[r * os + c] = ((bh_ + vv + 1) >> 1) as u8;
+ o[c] = avg(clip1((t[c] + 16) >> 5), clip1((v[c] + 16) >> 5));
}
}
}
@@ -151,35 +200,48 @@ pub fn mc_luma(p: PlaneRef, x: i32, y: i32, fx: u32, fy: u32, bw: usize, bh: usi
/// 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) {
let maxx = p.width as i32 - 1;
let maxy = p.height as i32 - 1;
- let fx = fx as i32;
- let fy = fy as i32;
- let w00 = (8 - fx) * (8 - fy);
- let w10 = fx * (8 - fy);
- let w01 = (8 - fx) * fy;
- let w11 = fx * fy;
let inside = x >= 0 && y >= 0 && x + bw as i32 <= maxx && y + bh as i32 <= maxy;
- if inside {
- let (x, y) = (x as usize, y as usize);
- for r in 0..bh {
- let r0 = &p.data[(y + r) * p.stride + x..];
- let r1 = &p.data[(y + r + 1) * p.stride + x..];
- for c in 0..bw {
- let v = w00 * r0[c] as i32 + w10 * r0[c + 1] as i32 + w01 * r1[c] as i32 + w11 * r1[c + 1] as i32;
- out[r * os + c] = ((v + 32) >> 6) as u8;
- }
- }
+ // (bw+1) x (bh+1) source window; copied with edge clamping when it crosses the picture border
+ let mut win = [0u8; 9 * 9];
+ let (src, ss): (&[u8], usize) = if inside {
+ (&p.data[y as usize * p.stride + x as usize..], p.stride)
} else {
- let at = |xx: i32, yy: i32| p.data[yy.clamp(0, maxy) as usize * p.stride + xx.clamp(0, maxx) as usize] as i32;
- for r in 0..bh as i32 {
- for c in 0..bw as i32 {
- let v = w00 * at(x + c, y + r) + w10 * at(x + c + 1, y + r) + w01 * at(x + c, y + r + 1) + w11 * at(x + c + 1, y + r + 1);
- out[(r as usize) * os + c as usize] = ((v + 32) >> 6) as u8;
+ for r in 0..=bh {
+ let yy = (y + r as i32).clamp(0, maxy) as usize;
+ for c in 0..=bw {
+ win[r * 9 + c] = p.data[yy * p.stride + (x + c as i32).clamp(0, maxx) as usize];
}
}
+ (&win[..], 9)
+ };
+ mc_chroma_win(src, ss, fx, fy, bw, bh, 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) {
+ 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 {
+ for r in 0..bh {
+ out[r * os..r * os + bw].copy_from_slice(&src[r * ss..r * ss + bw]);
+ }
+ return;
+ }
+ for r in 0..bh {
+ let r0 = &src[r * ss..r * ss + bw + 1];
+ let r1 = &src[(r + 1) * ss..(r + 1) * ss + bw + 1];
+ let o = &mut out[r * os..r * os + bw];
+ for (c, o) in o.iter_mut().enumerate() {
+ let v = w00 * r0[c] as u16 + w10 * r0[c + 1] as u16 + w01 * r1[c] as u16 + w11 * r1[c + 1] as u16;
+ *o = ((v + 32) >> 6) as u8;
+ }
}
}
@@ -209,33 +271,33 @@ pub fn weighted_store(dst: &mut [u8], ds: usize, p0: Option<&[u8]>, p1: Option<&
(Some(a), Some(b), Weight::Weighted { log_wd, w0, w1, o0, o1 }) => {
let round = 1 << log_wd;
let off = (o0 + o1 + 1) >> 1;
+ let sh = log_wd + 1;
for r in 0..bh {
- for c in 0..bw {
- let v = ((a[r * ps + c] as i32 * w0 + b[r * ps + c] as i32 * w1 + round) >> (log_wd + 1)) + off;
- dst[r * ds + c] = clip1(v);
+ let d = &mut dst[r * ds..r * ds + bw];
+ let ra = &a[r * ps..r * ps + bw];
+ let rb = &b[r * ps..r * ps + bw];
+ for ((d, &x), &y) in d.iter_mut().zip(ra).zip(rb) {
+ *d = clip1(((x as i32 * w0 + y as i32 * w1 + round) >> sh) + off);
}
}
}
(Some(a), None, w) | (None, Some(a), w) => {
- let (wt, o) = match (w, p0.is_some()) {
+ let (wt, o, log_wd) = match (w, p0.is_some()) {
(Weight::Default, _) => {
for r in 0..bh {
dst[r * ds..r * ds + bw].copy_from_slice(&a[r * ps..r * ps + bw]);
}
return;
}
- (Weight::Weighted { w0, o0, .. }, true) => (w0, o0),
- (Weight::Weighted { w1, o1, .. }, false) => (w1, o1),
- };
- let log_wd = match w {
- Weight::Weighted { log_wd, .. } => log_wd,
- Weight::Default => 0,
+ (Weight::Weighted { w0, o0, log_wd, .. }, true) => (w0, o0, log_wd),
+ (Weight::Weighted { w1, o1, log_wd, .. }, false) => (w1, o1, log_wd),
};
+ let round = if log_wd >= 1 { 1 << (log_wd - 1) } else { 0 };
for r in 0..bh {
- for c in 0..bw {
- let s = a[r * ps + c] as i32;
- let v = if log_wd >= 1 { ((s * wt + (1 << (log_wd - 1))) >> log_wd) + o } else { s * wt + o };
- dst[r * ds + c] = clip1(v);
+ let d = &mut dst[r * ds..r * ds + bw];
+ let ra = &a[r * ps..r * ps + bw];
+ for (d, &x) in d.iter_mut().zip(ra) {
+ *d = clip1(((x as i32 * wt + round) >> log_wd) + o);
}
}
}
@@ -243,6 +305,112 @@ pub fn weighted_store(dst: &mut [u8], ds: usize, p0: Option<&[u8]>, p1: Option<&
}
}
+#[cfg(test)]
+mod reference {
+ use super::*;
+
+ /// 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) {
+ 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]
+ let g = |r: usize, c: usize| win[(r + 2) * WIN + c + 2] as i32;
+ // unclipped horizontal half-sample b1 at block row r (-2..bh+3 via offset) and column c
+ let b1 = |r: isize, c: usize| {
+ let base = ((r + 2) as usize) * WIN + c;
+ tap6(win[base] as i32, win[base + 1] as i32, win[base + 2] as i32, win[base + 3] as i32, win[base + 4] as i32, win[base + 5] as i32)
+ };
+ let h1 = |r: usize, c: isize| {
+ let col = (c + 2) as usize;
+ tap6(
+ win[r * WIN + col] as i32,
+ win[(r + 1) * WIN + col] as i32,
+ win[(r + 2) * WIN + col] as i32,
+ win[(r + 3) * WIN + col] as i32,
+ win[(r + 4) * WIN + col] as i32,
+ win[(r + 5) * WIN + col] as i32,
+ )
+ };
+ match (fx, fy) {
+ (0, 0) => {
+ for r in 0..bh {
+ out[r * os..r * os + bw].copy_from_slice(&win[(r + 2) * WIN + 2..(r + 2) * WIN + 2 + bw]);
+ }
+ }
+ (_, 0) => {
+ // a, b, c
+ for r in 0..bh {
+ for c in 0..bw {
+ let b = clip1((b1(r as isize, c) + 16) >> 5) as i32;
+ out[r * os + c] = match fx {
+ 1 => ((g(r, c) + b + 1) >> 1) as u8,
+ 2 => b as u8,
+ _ => ((g(r, c + 1) + b + 1) >> 1) as u8,
+ };
+ }
+ }
+ }
+ (0, _) => {
+ // d, h, n
+ for r in 0..bh {
+ for c in 0..bw {
+ let h = clip1((h1(r, c as isize) + 16) >> 5) as i32;
+ out[r * os + c] = match fy {
+ 1 => ((g(r, c) + h + 1) >> 1) as u8,
+ 2 => h as u8,
+ _ => ((g(r + 1, c) + h + 1) >> 1) as u8,
+ };
+ }
+ }
+ }
+ (2, _) | (_, 2) => {
+ // j-based: j needs b1 for rows -2..bh+3
+ let mut bcol = [0i32; WIN * WIN];
+ for r in 0..bh + 5 {
+ for c in 0..bw {
+ bcol[r * WIN + c] = b1(r as isize - 2, c);
+ }
+ }
+ for r in 0..bh {
+ for c in 0..bw {
+ let j1 = tap6(
+ bcol[r * WIN + c],
+ bcol[(r + 1) * WIN + c],
+ bcol[(r + 2) * WIN + c],
+ bcol[(r + 3) * WIN + c],
+ bcol[(r + 4) * WIN + c],
+ bcol[(r + 5) * WIN + c],
+ );
+ let j = clip1((j1 + 512) >> 10) as i32;
+ let v = match (fx, fy) {
+ (2, 2) => j,
+ (2, 1) => (clip1((bcol[(r + 2) * WIN + c] + 16) >> 5) as i32 + j + 1) >> 1, // f
+ (2, 3) => (clip1((bcol[(r + 3) * WIN + c] + 16) >> 5) as i32 + j + 1) >> 1, // q
+ (1, 2) => (clip1((h1(r, c as isize) + 16) >> 5) as i32 + j + 1) >> 1, // i
+ _ => (clip1((h1(r, c as isize + 1) + 16) >> 5) as i32 + j + 1) >> 1, // k
+ };
+ out[r * os + c] = v as u8;
+ }
+ }
+ }
+ _ => {
+ // e, g, p, r: average of a horizontal half-sample (b or s) and a vertical one (h or m)
+ for r in 0..bh {
+ for c in 0..bw {
+ let hr = if fy == 1 { r as isize } else { r as isize + 1 };
+ let vc = if fx == 1 { c as isize } else { c as isize + 1 };
+ let bh_ = clip1((b1(hr, c) + 16) >> 5) as i32;
+ let vv = clip1((h1(r, vc) + 16) >> 5) as i32;
+ out[r * os + c] = ((bh_ + vv + 1) >> 1) as u8;
+ }
+ }
+ }
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -290,6 +458,31 @@ mod tests {
assert_eq!(&out[..4], &[33, 37, 41, 45]);
}
+ #[test]
+ fn fast_luma_matches_reference() {
+ let mut seed = 7u32;
+ let d: Vec<u8> = (0..40 * 36)
+ .map(|_| {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (seed >> 24) as u8
+ })
+ .collect();
+ let p = PlaneRef { data: &d, width: 40, height: 36, stride: 40 };
+ for &(bw, bh) in &[(16, 16), (16, 8), (8, 16), (8, 8), (8, 4), (4, 8), (4, 4)] {
+ for fx in 0..4 {
+ for fy in 0..4 {
+ 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);
+ assert_eq!(a, b, "{bw}x{bh} frac {fx},{fy} at {x},{y}");
+ }
+ }
+ }
+ }
+ }
+
#[test]
fn weighting() {
let a = [100u8; 4];
diff --git a/crates/h264/src/picture.rs b/crates/h264/src/picture.rs
index 60bd97cb3..8cf9c59b0 100644
--- a/crates/h264/src/picture.rs
+++ b/crates/h264/src/picture.rs
@@ -1,6 +1,6 @@
//! Picture buffers and per-macroblock state.
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
/// Planar 4:2:0 8-bit sample buffers (MB-aligned dimensions, stride == width).
#[derive(Clone)]
@@ -11,13 +11,12 @@ pub struct Planes {
pub width: usize,
pub height: usize,
pub cwidth: usize,
- pub cheight: usize,
}
impl Planes {
pub fn new(width: usize, height: usize) -> Self {
let (cw, ch) = (width / 2, height / 2);
- Planes { y: vec![0; width * height], cb: vec![128; cw * ch], cr: vec![128; cw * ch], width, height, cwidth: cw, cheight: ch }
+ Planes { y: vec![0; width * height], cb: vec![128; cw * ch], cr: vec![128; cw * ch], width, height, cwidth: cw }
}
pub fn gray(width: usize, height: usize) -> Self {
let mut p = Self::new(width, height);
@@ -111,24 +110,181 @@ impl Default for MbState {
}
}
-/// Motion data of a decoded picture, used as co-located data for direct prediction.
-#[derive(Clone, Default)]
-pub struct MotionField {
- /// Per 4x4 block: index mb * 16 + raster.
- pub mv: [Vec<[i16; 2]>; 2],
- /// Per 8x8 block: index mb * 4 + b8.
- pub ref_idx: [Vec<i8>; 2],
+/// One published macroblock row of a decoded frame: final (deblocked) samples plus the motion data
+/// needed as co-located information for direct prediction.
+pub struct FrameRow {
+ /// 16 luma lines.
+ pub y: Box<[u8]>,
+ /// 8 lines per chroma component.
+ pub cb: Box<[u8]>,
+ pub cr: Box<[u8]>,
+ /// Per 4x4 block: index mb_x * 16 + raster.
+ pub mv: [Box<[[i16; 2]]>; 2],
+ /// Per 8x8 block: index mb_x * 4 + b8.
+ pub ref_idx: [Box<[i8]>; 2],
/// Unique id of the referenced picture per 8x8 block (u32::MAX = none).
- pub ref_id: [Vec<u32>; 2],
- pub intra: Vec<bool>,
+ pub ref_id: [Box<[u32]>; 2],
+ pub intra: Box<[bool]>,
}
-/// A decoded frame as stored in the DPB and referenced by later pictures.
+/// A decoded (or in-progress) frame as stored in the DPB and referenced by later pictures.
+///
+/// Rows are published in order by the thread decoding the picture; readers block (per row) until the
+/// data they need is available, which lets several pictures decode concurrently.
pub struct Frame {
pub id: u32,
pub poc: i32,
- pub planes: Planes,
- pub motion: MotionField,
+ pub width: usize,
+ pub height: usize,
+ pub cwidth: usize,
+ pub cheight: usize,
+ pub mb_w: usize,
+ rows: Box<[OnceLock<FrameRow>]>,
+}
+
+impl Frame {
+ pub fn new(id: u32, poc: i32, mb_w: usize, mb_h: usize) -> Self {
+ Frame { id, poc, width: mb_w * 16, height: mb_h * 16, cwidth: mb_w * 8, cheight: mb_h * 8, mb_w, rows: (0..mb_h).map(|_| OnceLock::new()).collect() }
+ }
+
+ pub fn mb_h(&self) -> usize {
+ self.rows.len()
+ }
+
+ /// Publish MB row `r` (ignored if already published).
+ pub fn publish(&self, r: usize, row: FrameRow) {
+ let _ = self.rows[r].set(row);
+ }
+
+ pub fn is_published(&self, r: usize) -> bool {
+ self.rows[r].get().is_some()
+ }
+
+ /// MB row `r`, waiting until it has been published.
+ #[inline]
+ pub fn row(&self, r: usize) -> &FrameRow {
+ #[cfg(feature = "threads")]
+ {
+ self.rows[r].wait()
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ self.rows[r].get().expect("reference row decoded before use")
+ }
+ }
+
+ /// Wait until the whole frame is available.
+ pub fn wait_complete(&self) {
+ for r in 0..self.rows.len() {
+ self.row(r);
+ }
+ }
+
+ /// Build a published row from a contiguous plane set (rows of MB row `r`) and motion data.
+ pub fn make_row(planes: &Planes, r: usize, mbs: &[MbState], ref_ids: &dyn Fn(&MbState, usize, i8) -> u32) -> FrameRow {
+ let w = planes.width;
+ let cw = planes.cwidth;
+ let mb_w = w / 16;
+ let y = planes.y[r * 16 * w..(r + 1) * 16 * w].into();
+ let cb = planes.cb[r * 8 * cw..(r + 1) * 8 * cw].into();
+ let cr = planes.cr[r * 8 * cw..(r + 1) * 8 * cw].into();
+ let row_mbs = &mbs[r * mb_w..(r + 1) * mb_w];
+ let mut mv = [vec![[0i16; 2]; mb_w * 16], vec![[0i16; 2]; mb_w * 16]];
+ let mut ref_idx = [vec![-1i8; mb_w * 4], vec![-1i8; mb_w * 4]];
+ let mut ref_id = [vec![u32::MAX; mb_w * 4], vec![u32::MAX; mb_w * 4]];
+ let mut intra = vec![true; mb_w];
+ for (x, st) in row_mbs.iter().enumerate() {
+ if st.slice_num == u32::MAX {
+ continue;
+ }
+ intra[x] = st.kind.is_intra();
+ for l in 0..2 {
+ mv[l][x * 16..x * 16 + 16].copy_from_slice(&st.mv[l]);
+ for b in 0..4 {
+ let ri = st.ref_idx[l][b];
+ ref_idx[l][x * 4 + b] = ri;
+ if ri >= 0 {
+ ref_id[l][x * 4 + b] = ref_ids(st, l, ri);
+ }
+ }
+ }
+ }
+ let [mv0, mv1] = mv;
+ let [ri0, ri1] = ref_idx;
+ let [id0, id1] = ref_id;
+ FrameRow { y, cb, cr, mv: [mv0.into(), mv1.into()], ref_idx: [ri0.into(), ri1.into()], ref_id: [id0.into(), id1.into()], intra: intra.into() }
+ }
+
+ /// A frame with every row published from `planes` and no motion (intra), e.g. "non-existing"
+ /// frames inferred for frame_num gaps.
+ pub fn from_planes(id: u32, poc: i32, planes: &Planes) -> Self {
+ let (mb_w, mb_h) = (planes.width / 16, planes.height / 16);
+ let f = Frame::new(id, poc, mb_w, mb_h);
+ let blank = vec![MbState::default(); mb_w * mb_h];
+ for r in 0..mb_h {
+ f.publish(r, Frame::make_row(planes, r, &blank, &|_, _, _| u32::MAX));
+ }
+ f
+ }
+
+ /// 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) {
+ 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;
+ let row = self.row(yy >> 4);
+ let line = &row.y[(yy & 15) * width..(yy & 15) * width + width];
+ copy_clamped(line, x0, &mut out[r * os..r * os + w]);
+ }
+ }
+
+ /// 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) {
+ 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;
+ let row = self.row(yy >> 3);
+ let plane = if c == 0 { &row.cb } else { &row.cr };
+ let line = &plane[(yy & 7) * cw..(yy & 7) * cw + cw];
+ copy_clamped(line, x0, &mut out[r * os..r * os + w]);
+ }
+ }
+
+ /// Crop and copy the frame into planar buffers (waits for completion).
+ pub fn copy_cropped(&self, crop: (usize, usize, usize, usize)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
+ let (cx, cy, cw, ch) = crop;
+ let mut y = Vec::with_capacity(cw * ch);
+ for r in cy..cy + ch {
+ let row = self.row(r >> 4);
+ y.extend_from_slice(&row.y[(r & 15) * self.width + cx..(r & 15) * self.width + cx + cw]);
+ }
+ let (ccx, ccy, ccw, cch) = (cx / 2, cy / 2, cw.div_ceil(2), ch.div_ceil(2));
+ let mut u = Vec::with_capacity(ccw * cch);
+ let mut v = Vec::with_capacity(ccw * cch);
+ for r in ccy..ccy + cch {
+ let row = self.row(r >> 3);
+ let o = (r & 7) * self.cwidth + ccx;
+ u.extend_from_slice(&row.cb[o..o + ccw]);
+ v.extend_from_slice(&row.cr[o..o + ccw]);
+ }
+ (y, u, v)
+ }
+}
+
+/// Copy `out.len()` samples of `line` starting at x0, replicating edge samples outside the line.
+#[inline(always)]
+fn copy_clamped(line: &[u8], x0: i32, out: &mut [u8]) {
+ let w = out.len();
+ if x0 >= 0 && x0 as usize + w <= line.len() {
+ out.copy_from_slice(&line[x0 as usize..x0 as usize + w]);
+ } else {
+ let max = line.len() as i32 - 1;
+ for (c, o) in out.iter_mut().enumerate() {
+ *o = line[(x0 + c as i32).clamp(0, max) as usize];
+ }
+ }
}
pub type FrameRef = Arc<Frame>;
diff --git a/crates/h264/src/slicedec.rs b/crates/h264/src/slicedec.rs
index 4b693f441..4fa34e537 100644
--- a/crates/h264/src/slicedec.rs
+++ b/crates/h264/src/slicedec.rs
@@ -1,8 +1,9 @@
//! Slice data decoding: macroblock parsing (CAVLC), motion vector derivation, and reconstruction.
use crate::cavlc;
+use crate::deblock;
use crate::error::{Result, ensure, invalid};
-use crate::inter::{self, PlaneRef, Weight};
+use crate::inter::{self, Weight};
use crate::intra::{self, Avail};
use crate::mbtypes::*;
use crate::params::{Pps, Sps};
@@ -22,7 +23,8 @@ pub struct SliceInfo {
pub ref_ids: [Vec<u32>; 2],
}
-/// The picture under construction.
+/// The picture under construction: private reconstruction buffers plus the shared [`Frame`] that
+/// finished (deblocked) macroblock rows are published into.
pub struct PicState {
pub planes: Planes,
pub mbs: Vec<MbState>,
@@ -31,11 +33,85 @@ pub struct PicState {
pub mb_h: usize,
pub poc: i32,
pub decoded_mbs: usize,
+ pub frame: FrameRef,
+ /// Decoded macroblocks per MB row.
+ row_count: Vec<u16>,
+ /// Leading MB rows that are fully reconstructed / deblocked / published.
+ rows_recon: usize,
+ rows_deblocked: usize,
+ rows_published: usize,
}
impl PicState {
- pub fn new(mb_w: usize, mb_h: usize, poc: i32) -> Self {
- PicState { planes: Planes::new(mb_w * 16, mb_h * 16), mbs: vec![MbState::default(); mb_w * mb_h], slices: Vec::new(), mb_w, mb_h, poc, decoded_mbs: 0 }
+ pub fn new(frame: FrameRef) -> Self {
+ let (mb_w, mb_h) = (frame.mb_w, frame.mb_h());
+ PicState {
+ planes: Planes::new(mb_w * 16, mb_h * 16),
+ mbs: vec![MbState::default(); mb_w * mb_h],
+ slices: Vec::new(),
+ mb_w,
+ mb_h,
+ poc: frame.poc,
+ decoded_mbs: 0,
+ frame,
+ row_count: vec![0; mb_h],
+ rows_recon: 0,
+ rows_deblocked: 0,
+ rows_published: 0,
+ }
+ }
+
+ /// Reuse the buffers of a finished picture of the same size for a new frame.
+ pub fn reset(&mut self, frame: FrameRef) {
+ debug_assert_eq!((self.mb_w, self.mb_h), (frame.mb_w, frame.mb_h()));
+ self.mbs.fill(MbState::default());
+ self.slices.clear();
+ self.poc = frame.poc;
+ self.decoded_mbs = 0;
+ self.frame = frame;
+ self.row_count.fill(0);
+ self.rows_recon = 0;
+ self.rows_deblocked = 0;
+ self.rows_published = 0;
+ }
+
+ /// Record a decoded macroblock and deblock / publish rows that became final.
+ #[inline]
+ pub fn mb_done(&mut self, addr: usize) {
+ self.decoded_mbs += 1;
+ let r = addr / self.mb_w;
+ self.row_count[r] += 1;
+ if self.row_count[r] as usize >= self.mb_w && r == self.rows_recon {
+ while self.rows_recon < self.mb_h && self.row_count[self.rows_recon] as usize >= self.mb_w {
+ self.rows_recon += 1;
+ }
+ self.flush_rows(false);
+ }
+ }
+
+ /// Deblock and publish rows. With `finished`, everything remaining is processed (also rows with
+ /// missing macroblocks, so that waiting readers never block forever).
+ pub fn flush_rows(&mut self, finished: bool) {
+ // Deblocking row r must wait until row r + 1 is reconstructed (its intra prediction reads the
+ // unfiltered bottom line of row r); row r is final once row r + 1 is deblocked.
+ let deblock_limit = if finished { self.mb_h } else { self.rows_recon.saturating_sub(1) };
+ while self.rows_deblocked < deblock_limit {
+ let r = self.rows_deblocked;
+ for addr in r * self.mb_w..(r + 1) * self.mb_w {
+ deblock::deblock_mb(self, addr, self.mb_w);
+ }
+ self.rows_deblocked += 1;
+ }
+ let publish_limit = if finished { self.mb_h } else { self.rows_deblocked.saturating_sub(1) };
+ while self.rows_published < publish_limit {
+ let r = self.rows_published;
+ let slices = &self.slices;
+ let ids =
+ |st: &MbState, l: usize, ri: i8| slices.get(st.slice_num as usize).and_then(|s| s.ref_ids[l].get(ri as usize).copied()).unwrap_or(u32::MAX);
+ let row = Frame::make_row(&self.planes, r, &self.mbs, &ids);
+ self.frame.publish(r, row);
+ self.rows_published += 1;
+ }
}
}
@@ -129,6 +205,28 @@ pub struct SliceDecoder<'a> {
pub prev_qp_delta_nz: bool,
}
+/// 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) {
+ const LW: usize = 21;
+ let mut win = [0u8; LW * LW];
+ 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);
+ 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; 9 * 9];
+ f.chroma_window(comp, cx, cy, cw + 1, ch + 1, &mut w, 9);
+ inter::mc_chroma_win(&w, 9, fx, fy, cw, ch, out, cs);
+ }
+}
+
#[inline(always)]
fn median(a: i16, b: i16, c: i16) -> i16 {
a.max(b).min(a.min(b).max(c))
@@ -409,15 +507,18 @@ impl<'a> SliceDecoder<'a> {
/// Co-located (mvCol, refIdxCol, referenced picture id) for 4x4 block `raster` of the current MB.
fn colocated(&self, raster: usize) -> ([i16; 2], i8, u32) {
let Some(col) = self.refs[1].first() else { return ([0, 0], -1, u32::MAX) };
- let m = &col.frame.motion;
let raster = if self.sps.direct_8x8_inference {
let (bx, by) = (raster & 3, raster >> 2);
(if by >= 2 { 12 } else { 0 }) + if bx >= 2 { 3 } else { 0 }
} else {
raster
};
- let mb = self.mb_addr;
- if m.intra.get(mb).copied().unwrap_or(true) {
+ if col.frame.mb_w != self.mb_w || self.mb_y >= col.frame.mb_h() {
+ return ([0, 0], -1, u32::MAX);
+ }
+ let m = col.frame.row(self.mb_y);
+ let mb = self.mb_x;
+ if m.intra[mb] {
return ([0, 0], -1, u32::MAX);
}
let b8 = mb * 4 + (raster >> 3) * 2 + ((raster & 3) >> 1);
@@ -457,7 +558,8 @@ impl<'a> SliceDecoder<'a> {
continue;
}
let (x8, y8) = ((b8 & 1) * 2, (b8 >> 1) * 2);
- for sub in 0..4 {
+ let unit = if self.sps.direct_8x8_inference { 2 } else { 1 };
+ for sub in (0..4).filter(|s| unit == 1 || *s == 0) {
let (x, y) = (x8 + (sub & 1), y8 + (sub >> 1));
let raster = y * 4 + x;
let (mv_col, ref_col, id_col) = self.colocated(raster);
@@ -489,7 +591,7 @@ impl<'a> SliceDecoder<'a> {
};
([ref0, 0], [mv0, mv1])
};
- self.set_motion(x, y, 1, 1, refs, mvs);
+ self.set_motion(x, y, unit, unit, refs, mvs);
}
}
let st = &mut self.pic.mbs[self.mb_addr];
@@ -623,48 +725,31 @@ impl<'a> SliceDecoder<'a> {
let wts = [self.weight_for(refs, 0), self.weight_for(refs, 1), self.weight_for(refs, 2)];
let px = self.mb_x * 16 + x4 * 4;
let py = self.mb_y * 16 + y4 * 4;
+ let use0 = refs[0] >= 0 && self.refs[0].get(refs[0] as usize).is_some();
+ let use1 = refs[1] >= 0 && self.refs[1].get(refs[1] as usize).is_some();
+ let ys = self.pic.planes.width;
+ let cs = self.pic.planes.cwidth;
+ let (cx, cy) = (px / 2, py / 2);
+ if use0 != use1 && wts.iter().all(|w| *w == Weight::Default) {
+ // single-list unweighted prediction: interpolate straight into the picture
+ 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);
+ return;
+ }
let s = &mut *self.s;
for l in 0..2 {
if refs[l] < 0 {
continue;
}
let Some(rp) = self.refs[l].get(refs[l] as usize) else { continue };
- let f = &rp.frame.planes;
- let mv = mvs[l];
- let yref = PlaneRef { data: &f.y, width: f.width, height: f.height, stride: f.width };
- inter::mc_luma(
- yref,
- px as i32 + (mv[0] as i32 >> 2),
- py as i32 + (mv[1] as i32 >> 2),
- (mv[0] & 3) as u32,
- (mv[1] & 3) as u32,
- bw,
- bh,
- &mut s.pred[l],
- 16,
- );
- let (cx, cy) = (px as i32 / 2, py as i32 / 2);
- for (c, plane) in [&f.cb, &f.cr].into_iter().enumerate() {
- let cref = PlaneRef { data: plane, width: f.cwidth, height: f.cheight, stride: f.cwidth };
- inter::mc_chroma(
- cref,
- cx + (mv[0] as i32 >> 3),
- cy + (mv[1] as i32 >> 3),
- (mv[0] & 7) as u32,
- (mv[1] & 7) as u32,
- bw / 2,
- bh / 2,
- &mut s.pred_c[l][c],
- 8,
- );
- }
+ 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);
}
- let use0 = refs[0] >= 0 && self.refs[0].get(refs[0] as usize).is_some();
- let use1 = refs[1] >= 0 && self.refs[1].get(refs[1] as usize).is_some();
- let stride = self.pic.planes.width;
inter::weighted_store(
- &mut self.pic.planes.y[py * stride + px..],
- stride,
+ &mut self.pic.planes.y[py * ys + px..],
+ ys,
if use0 { Some(&s.pred[0][..]) } else { None },
if use1 { Some(&s.pred[1][..]) } else { None },
16,
@@ -672,23 +757,31 @@ impl<'a> SliceDecoder<'a> {
bh,
wts[0],
);
- let cstride = self.pic.planes.cwidth;
- let (cx, cy) = (px / 2, py / 2);
for c in 0..2 {
let wc = wts[c + 1];
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 * cstride + cx..], cstride, 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);
}
}
+ /// All 16 blocks of the current MB share references and motion vectors.
+ fn uniform_motion(&self) -> bool {
+ let st = self.mb();
+ (0..2).all(|l| {
+ let r = st.ref_idx[l];
+ r[1] == r[0] && r[2] == r[0] && r[3] == r[0] && st.mv[l].iter().all(|m| *m == st.mv[l][0])
+ })
+ }
+
/// Inter prediction for the whole current MB, using the stored motion.
pub fn predict_inter(&mut self) {
let info = self.cur.info;
let direct_unit = if self.sps.direct_8x8_inference { 2 } else { 1 };
match info.kind {
MbKind::PSkip => self.mc_rect(0, 0, 4, 4),
+ MbKind::BSkip | MbKind::BDirect16x16 if self.uniform_motion() => self.mc_rect(0, 0, 4, 4),
MbKind::BSkip | MbKind::BDirect16x16 => {
for y in (0..4).step_by(direct_unit) {
for x in (0..4).step_by(direct_unit) {
@@ -1319,7 +1412,7 @@ impl<'a> SliceDecoder<'a> {
for _ in 0..run {
self.start_mb(addr);
self.decode_skip()?;
- self.pic.decoded_mbs += 1;
+ self.pic.mb_done(addr);
addr += 1;
}
if run > 0 && !r.more_rbsp_data() {
@@ -1329,7 +1422,7 @@ impl<'a> SliceDecoder<'a> {
}
self.start_mb(addr);
self.decode_mb_cavlc(r)?;
- self.pic.decoded_mbs += 1;
+ self.pic.mb_done(addr);
addr += 1;
if !r.more_rbsp_data() {
break;
diff --git a/crates/h264/tests/common/mod.rs b/crates/h264/tests/common/mod.rs
index 7b51b4cbc..eddc2dddb 100644
--- a/crates/h264/tests/common/mod.rs
+++ b/crates/h264/tests/common/mod.rs
@@ -22,6 +22,16 @@ pub struct Fixture {
const NOISE: &str = "noise=alls=12:allf=t+u";
pub const FIXTURES: &[Fixture] = &[
+ // performance reference stream (see tests/perf.rs)
+ Fixture {
+ name: "bench_1080p",
+ source: "testsrc2",
+ width: 1920,
+ height: 1080,
+ frames: 120,
+ filter: "noise=alls=3:allf=t",
+ args: &["-preset", "medium", "-crf", "20"],
+ },
Fixture {
name: "intra_cavlc",
source: "testsrc2",
@@ -371,8 +381,13 @@ pub fn split_access_units(data: &[u8]) -> Vec<&[u8]> {
pub type DecodeFailure = (usize, filmcraft_h264::Error, Vec<Picture>);
pub fn decode_file(path: &Path) -> Result<Vec<Picture>, DecodeFailure> {
+ decode_file_threads(path, 0)
+}
+
+/// Decode with `threads` worker threads (0 = decoder default).
+pub fn decode_file_threads(path: &Path, threads: usize) -> Result<Vec<Picture>, DecodeFailure> {
let data = std::fs::read(path).unwrap();
- let mut dec = Decoder::new();
+ let mut dec = if threads == 0 { Decoder::new() } else { Decoder::with_threads(threads) };
let mut out = Vec::new();
for (i, au) in split_access_units(&data).into_iter().enumerate() {
match dec.decode(au, i as i64) {
@@ -381,6 +396,9 @@ pub fn decode_file(path: &Path) -> Result<Vec<Picture>, DecodeFailure> {
}
}
out.extend(dec.flush());
+ if let Some(e) = dec.take_error() {
+ return Err((usize::MAX, e, out));
+ }
Ok(out)
}
@@ -440,14 +458,37 @@ pub fn check_fixture(name: &str) -> Result<bool, String> {
let f = fixture(name);
let Some((h264, yuv)) = ensure(f) else { return Ok(false) };
let reference = std::fs::read(&yuv).unwrap();
- let pics = match decode_file(&h264) {
- Ok(p) => p,
- Err((au, e, partial)) => {
- // still report comparison of what was decoded
- let cmp = compare(&partial, &reference, f.width as usize, f.height as usize).err().unwrap_or_default();
- return Err(format!("{name}: decode error at access unit {au}: {e} (after {} pictures) {cmp}", partial.len()));
- }
- };
- compare(&pics, &reference, f.width as usize, f.height as usize).map_err(|e| format!("{name}: {e}"))?;
+ // single-threaded and frame-threaded decoding must both be bit-exact
+ for threads in [1, 0] {
+ let pics = match decode_file_threads(&h264, threads) {
+ Ok(p) => p,
+ Err((au, e, partial)) => {
+ // still report comparison of what was decoded
+ let cmp = compare(&partial, &reference, f.width as usize, f.height as usize).err().unwrap_or_default();
+ return Err(format!("{name} (threads {threads}): decode error at access unit {au}: {e} (after {} pictures) {cmp}", partial.len()));
+ }
+ };
+ compare(&pics, &reference, f.width as usize, f.height as usize).map_err(|e| format!("{name} (threads {threads}): {e}"))?;
+ check_pts(&pics).map_err(|e| format!("{name} (threads {threads}): {e}"))?;
+ }
Ok(true)
}
+
+/// Output pts values (= access unit index) must be a permutation of 0..n, and follow POC order
+/// between IDR pictures.
+pub fn check_pts(pics: &[Picture]) -> Result<(), String> {
+ let mut seen = vec![false; pics.len()];
+ for p in pics {
+ let i = p.pts as usize;
+ if i >= seen.len() || seen[i] {
+ return Err(format!("unexpected pts {} in output", p.pts));
+ }
+ seen[i] = true;
+ }
+ for w in pics.windows(2) {
+ if !w[1].key && w[1].poc <= w[0].poc {
+ return Err(format!("output POC order violated: {} then {}", w[0].poc, w[1].poc));
+ }
+ }
+ Ok(())
+}
diff --git a/crates/h264/tests/perf.rs b/crates/h264/tests/perf.rs
new file mode 100644
index 000000000..c8ed4beb8
--- /dev/null
+++ b/crates/h264/tests/perf.rs
@@ -0,0 +1,34 @@
+//! Decode speed on a 1080p High-profile stream (ignored by default; run with
+//! `cargo test --release -p filmcraft-h264 --test perf -- --ignored --nocapture`).
+
+mod common;
+
+use filmcraft_h264::Decoder;
+use std::time::Instant;
+
+fn bench(data: &[u8], threads: usize, iters: usize) -> (usize, f64) {
+ let mut best = f64::MAX;
+ let mut frames = 0;
+ for _ in 0..iters {
+ let mut dec = Decoder::with_threads(threads);
+ let t0 = Instant::now();
+ frames = dec.decode(data, 0).expect("decode").len() + dec.flush().len();
+ best = best.min(t0.elapsed().as_secs_f64());
+ }
+ (frames, best)
+}
+
+#[test]
+#[ignore]
+fn perf_1080p() {
+ let f = common::fixture("bench_1080p");
+ let Some((h264, _)) = common::ensure(f) else { return };
+ // correctness first
+ common::check_fixture("bench_1080p").unwrap();
+ let data = std::fs::read(h264).unwrap();
+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
+ for threads in [1, cores.min(16)] {
+ let (frames, secs) = bench(&data, threads, 5);
+ println!("1080p High CRF20 ({} KB): {threads} thread(s): {frames} frames in {secs:.3}s = {:.1} fps", data.len() / 1024, frames as f64 / secs);
+ }
+}