FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Speed up the H.264 encoder without changing its output
NetterSilver6cd0518fc6fd
diff --git a/crates/h264enc/src/dsp.rs b/crates/h264enc/src/dsp.rsindex 4f211650c..ed364bf00 100644--- a/crates/h264enc/src/dsp.rs+++ b/crates/h264enc/src/dsp.rs@@ -91,6 +91,53 @@ fn satd_strip<const N: usize, const H: usize>(a: &[u8], sa: usize, b: &[u8], sb:total}+/// [`satd_strip`] for 8 and 4 columns, where its pairwise sums across neighbouring lanes do not+/// vectorise: the same sums are formed lane by lane against copies of the rows shifted by one and+/// two lanes, and only every fourth lane (the first column of a 4x4 block) is counted.+#[inline(always)]+fn satd_strip_narrow<const N: usize>(a: &[u8], sa: usize, b: &[u8], sb: usize) -> u32 {+ let mut d = [[0i16; N]; 4];+ for r in 0..4 {+ let ra = &a[r * sa..r * sa + N];+ let rb = &b[r * sb..r * sb + N];+ for i in 0..N {+ d[r][i] = ra[i] as i16 - rb[i] as i16;+ }+ }+ let mut v = [[0i16; N]; 4];+ for i in 0..N {+ let s01 = d[0][i] + d[1][i];+ let d01 = d[0][i] - d[1][i];+ let s23 = d[2][i] + d[3][i];+ let d23 = d[2][i] - d[3][i];+ v[0][i] = s01 + s23;+ v[1][i] = s01 - s23;+ v[2][i] = d01 + d23;+ v[3][i] = d01 - d23;+ }+ // per lane at most 4 rows x 2 x 2040: fits u16+ let mut acc = [0u16; N];+ for row in &v {+ let mut p = [0i16; N];+ let mut m = [0i16; N];+ p[..N - 1].copy_from_slice(&row[1..]);+ m[..N - 1].copy_from_slice(&row[1..]);+ for i in 0..N {+ p[i] += row[i];+ m[i] = row[i] - m[i];+ }+ let mut p2 = [0i16; N];+ let mut m2 = [0i16; N];+ p2[..N - 2].copy_from_slice(&p[2..]);+ m2[..N - 2].copy_from_slice(&m[2..]);+ for i in 0..N {+ let t = p[i].unsigned_abs().max(p2[i].unsigned_abs()) + m[i].unsigned_abs().max(m2[i].unsigned_abs());+ acc[i] += if i % 4 == 0 { t } else { 0 };+ }+ }+ acc.iter().map(|&x| x as u32).sum()+}+/// Sum of absolute 4x4 Hadamard-transformed differences (halved), for w, h multiples of 4.pub fn satd(a: &[u8], sa: usize, b: &[u8], sb: usize, w: usize, h: usize) -> u32 {let mut total = 0;@@ -98,11 +145,11 @@ pub fn satd(a: &[u8], sa: usize, b: &[u8], sb: usize, w: usize, h: usize) -> u32let (ao, bo) = (by * sa, by * sb);match w {16 => total += satd_strip::<16, 8>(&a[ao..], sa, &b[bo..], sb),- 8 => total += satd_strip::<8, 4>(&a[ao..], sa, &b[bo..], sb),- 4 => total += satd_strip::<4, 2>(&a[ao..], sa, &b[bo..], sb),+ 8 => total += satd_strip_narrow::<8>(&a[ao..], sa, &b[bo..], sb),+ 4 => total += satd_strip_narrow::<4>(&a[ao..], sa, &b[bo..], sb),_ => {for bx in (0..w).step_by(4) {- total += satd_strip::<4, 2>(&a[ao + bx..], sa, &b[bo + bx..], sb);+ total += satd_strip_narrow::<4>(&a[ao + bx..], sa, &b[bo + bx..], sb);}}}@@ -170,4 +217,28 @@ mod tests {assert_eq!(satd(&a, 16, &b, 16, w, h), want / 2, "{w}x{h}");}}++ #[test]+ fn satd_matches_reference_at_the_extremes() {+ // the largest differences (every lane at +-255) are where 16-bit sums could overflow+ let (zero, full) = ([0u8; 16 * 16], [255u8; 16 * 16]);+ let stripes: Vec<u8> = (0..16 * 16).map(|i| if (i / 16 + i % 16) % 2 == 0 { 255 } else { 0 }).collect();+ for (a, b) in [(&zero[..], &full[..]), (&full[..], &zero[..]), (&stripes[..], &zero[..]), (&zero[..], &stripes[..])] {+ for (w, h) in [(16, 16), (8, 8), (4, 4), (8, 16), (12, 4)] {+ let mut want = 0;+ for by in (0..h).step_by(4) {+ for bx in (0..w).step_by(4) {+ let mut d = [0i32; 16];+ for r in 0..4 {+ for c in 0..4 {+ d[r * 4 + c] = a[(by + r) * 16 + bx + c] as i32 - b[(by + r) * 16 + bx + c] as i32;+ }+ }+ want += hadamard4x4_sum(&d);+ }+ }+ assert_eq!(satd(a, 16, b, 16, w, h), want / 2, "{w}x{h}");+ }+ }+ }}diff --git a/crates/h264enc/src/lib.rs b/crates/h264enc/src/lib.rsindex e20a91d10..28705cf7f 100644--- a/crates/h264enc/src/lib.rs+++ b/crates/h264enc/src/lib.rs@@ -528,6 +528,13 @@ impl Encoder {&self.cfg}+ /// Run `f` on the encoder's worker threads (the calling thread without the `threads`+ /// feature). The pool is idle between pictures, so input preparation such as colour+ /// conversion that runs here does not queue behind work on the global rayon pool.+ pub fn install<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {+ self.pool.install(f)+ }+/// The SPS and PPS NAL units (without start codes).pub fn sps_pps(&self) -> (Vec<u8>, Vec<u8>) {(self.sps_nal.clone(), self.pps_nal.clone())@@ -573,12 +580,18 @@ impl Encoder {let use_aq = self.cfg.aq_strength > 0.0 && !matches!(self.cfg.rate, RateControl::Qp(_));let (mbw, mbh, strength) = (self.params.mbw, self.params.mbh, self.cfg.aq_strength);let prev = self.prev_lowres.take();- let (lowres, cplx, aq) = self.pool.install(|| {+ let analyse = || {let lowres = LowRes::new(&src);let cplx = lookahead::complexity(&lowres, prev.as_ref());- let aq = if use_aq { lookahead::aq_offsets(&src, mbw, mbh, strength) } else { Vec::new() };- (lowres, cplx, aq)- });+ (lowres, cplx)+ };+ let aq_of = || if use_aq { lookahead::aq_offsets(&src, mbw, mbh, strength) } else { Vec::new() };+ // the two analyses are independent: side by side, the pool's threads are not left idle+ // at the end of each+ #[cfg(feature = "threads")]+ let ((lowres, cplx), aq) = self.pool.install(|| rayon::join(analyse, aq_of));+ #[cfg(not(feature = "threads"))]+ let ((lowres, cplx), aq) = (analyse(), aq_of());self.prev_lowres = Some(lowres);let display = self.display_count;self.display_count += 1;diff --git a/crates/h264enc/src/slice/b_slices.rs b/crates/h264enc/src/slice/b_slices.rsindex 7d200e977..40e71b263 100644--- a/crates/h264enc/src/slice/b_slices.rs+++ b/crates/h264enc/src/slice/b_slices.rs@@ -48,8 +48,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}/// B 16x8 / 8x16 candidate: search each partition in both lists, choose L0/L1/Bi per partition, then derive- /// the motion vector predictors in decoding order from the chosen directions.- fn b_partition(&self, mx: usize, my: usize, part: Part, src: &Src, qp: u8, lam: u32, seeds: [Mv; 2]) -> Option<Box<Cand>> {+ /// the motion vector predictors in decoding order from the chosen directions. With `beat`, a+ /// candidate whose cost does not come below it is `None` before its residual is coded.+ fn b_partition(&self, mx: usize, my: usize, part: Part, src: &Src, qp: u8, lam: u32, seeds: [Mv; 2], beat: Option<u64>) -> Option<Box<Cand>> {let f = self.f;let rp = [f.l0?, f.l1?];let (px, py) = (mx * 16, my * 16);@@ -84,6 +85,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}cost += bestd.0;dirs[pi] = bestd.1 as u8;+ if beat.is_some_and(|b| cost >= b) {+ return None;+ }let s = srcs[bestd.1];for r in y..y + h {py_[r * 16 + x..r * 16 + x + w].copy_from_slice(&s.0[r * 16 + x..r * 16 + x + w]);@@ -244,8 +248,15 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let (py_, pu, pv) = if dir == 2 { bi } else { preds[dir] };ci.cost = costs[dir];let better_than_direct = best.as_ref().is_none_or(|b| ci.cost < b.cost);+ // Without RD only costs decide from here on: the 16x16 candidate's residual is coded at+ // the end, if it is still the best then.+ let mut deferred = false;if better_than_direct || f.p.rd {- self.code_inter(src, &py_, &pu, &pv, qp, &mut ci);+ if f.p.rd {+ self.code_inter(src, &py_, &pu, &pv, qp, &mut ci);+ } else {+ deferred = true;+ }best = Some(match best {None => ci,Some(b) => {@@ -261,10 +272,13 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// --- 16x8 / 8x16 partitions with a per-partition prediction directionif f.p.partitions && best.cost > 256 * 4 {for part in [Part::P16x8, Part::P8x16] {- if let Some(c) = self.b_partition(mx, my, part, src, qp, lam, [res[0].0, res[1].0]) {+ // without RD only the cost decides, so a losing candidate's residual is not coded+ let beat = (!f.p.rd).then_some(best.cost);+ if let Some(c) = self.b_partition(mx, my, part, src, qp, lam, [res[0].0, res[1].0], beat) {let better = if f.p.rd { self.rd_cost(mx, my, &c, src, qp) < self.rd_cost(mx, my, &best, src, qp) } else { c.cost < best.cost };if better {best = c;+ deferred = false;}}}@@ -280,6 +294,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {return ic;}}+ if deferred {+ self.code_inter(src, &py_, &pu, &pv, qp, &mut best);+ }best}}diff --git a/crates/h264enc/src/slice/motion.rs b/crates/h264enc/src/slice/motion.rsindex e4793e441..9774ff75e 100644--- a/crates/h264enc/src/slice/motion.rs+++ b/crates/h264enc/src/slice/motion.rs@@ -1,5 +1,40 @@use super::*;+/// Motion vectors already costed in one search: one bit per point of the square of+/// `2 * half + 1` points (`step` quarter samples apart) around `centre`. A point outside the+/// square, off the grid or past the `W` words always counts as new.+struct Visited<const W: usize> {+ centre: Mv,+ half: i32,+ step: i32,+ bits: [u64; W],+}++impl<const W: usize> Visited<W> {+ fn new(centre: Mv, half: i32, step: i32) -> Self {+ Visited { centre, half, step: step.max(1), bits: [0; W] }+ }++ /// Marks `m`; false when it was marked before.+ fn first(&mut self, m: Mv) -> bool {+ let (dx, dy) = (m.x as i32 - self.centre.x as i32, m.y as i32 - self.centre.y as i32);+ if dx % self.step != 0 || dy % self.step != 0 {+ return true;+ }+ let side = 2 * self.half + 1;+ let (gx, gy) = (dx / self.step + self.half, dy / self.step + self.half);+ if gx < 0 || gy < 0 || gx >= side || gy >= side {+ return true;+ }+ let i = (gy * side + gx) as usize;+ let Some(word) = self.bits.get_mut(i / 64) else { return true };+ let bit = 1u64 << (i % 64);+ let fresh = *word & bit == 0;+ *word |= bit;+ fresh+ }+}+impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ motion estimation@@ -30,13 +65,19 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// hexagon search (full-pel units = 4 quarter samples)let range = p.me_range;let centre0 = best;+ // a point costed once is never better than the best since: skip it when it comes up again+ let mut seen = Visited::<40>::new(centre0, range, 4);+ seen.first(centre0);const HEX: [(i32, i32); 6] = [(-2, 0), (2, 0), (-1, -2), (1, -2), (-1, 2), (1, 2)];for _ in 0..range {let mut moved = false;let c = best;for &(dx, dy) in &HEX {let m = Mv::new(c.x as i32 + dx * 4, c.y as i32 + dy * 4);- if ((m.x as i32 - centre0.x as i32).abs() >> 2) > range || ((m.y as i32 - centre0.y as i32).abs() >> 2) > range || !self.mv_ok(bx, by, w, h, m)+ if ((m.x as i32 - centre0.x as i32).abs() >> 2) > range+ || ((m.y as i32 - centre0.y as i32).abs() >> 2) > range+ || !self.mv_ok(bx, by, w, h, m)+ || !seen.first(m){continue;}@@ -56,7 +97,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let c = best;for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)] {let m = Mv::new(c.x as i32 + dx * 4, c.y as i32 + dy * 4);- if !self.mv_ok(bx, by, w, h, m) {+ if !self.mv_ok(bx, by, w, h, m) || !seen.first(m) {continue;}let k = fcost(m);@@ -76,6 +117,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {satd(src, sstride, buf, 16, w, h) + ((lam * mv_bits(mv, mvp)) >> 8)};let mut bs = scost(best, &mut buf);+ let mut seen = Visited::<2>::new(best, 4, 1);+ seen.first(best);if p.subpel >= 1 {for step in [2, 1] {if step == 1 && p.subpel < 2 {@@ -86,7 +129,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let c = best;for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)] {let m = Mv::new(c.x as i32 + dx * step, c.y as i32 + dy * step);- if !self.mv_ok(bx, by, w, h, m) {+ if !self.mv_ok(bx, by, w, h, m) || !seen.first(m) {continue;}let k = scost(m, &mut buf);@@ -290,9 +333,15 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}ci.code.mvd = mvds;Self::cand_inter_info(&mut ci, best_part, [[0; 4], [-1; 4]], [best_mvs, [Mv::ZERO; 4]], mvds);- self.code_inter(src, &py_, &pu, &pv, qp, &mut ci);+ // The residual decides a P_Skip and the RD comparisons; otherwise it only matters when the+ // inter candidate is kept, so it is coded after an intra candidate had its chance.+ let skip_candidate = best_part == Part::P16x16 && best_mvs[0] == skip_mv && skip_ok;+ let coded_now = skip_candidate || f.p.rd;+ if coded_now {+ self.code_inter(src, &py_, &pu, &pv, qp, &mut ci);+ }ci.cost = best_cost;- if ci.code.cbp == 0 && best_part == Part::P16x16 && best_mvs[0] == skip_mv && skip_ok {+ if skip_candidate && ci.code.cbp == 0 {ci.code.kind = MbKind::PSkip;ci.info.t8x8 = false;ci.info.mvd = [[[0; 2]; 16]; 2];@@ -310,6 +359,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {return ic;}}+ if !coded_now {+ self.code_inter(src, &py_, &pu, &pv, qp, &mut ci);+ }if f.p.rd && skip_ok && ci.code.cbp != 0 {// RD check against P_Skipif let Some((y, u, v)) = skip_pred {diff --git a/crates/h264enc/src/slice/residual.rs b/crates/h264enc/src/slice/residual.rsindex 7abfc65c2..763abc163 100644--- a/crates/h264enc/src/slice/residual.rs+++ b/crates/h264enc/src/slice/residual.rs@@ -1,5 +1,21 @@use super::*;+/// The transform trial's bit estimate of a level `v`: `0.4` for zero, `3 + 2·log2|v|` otherwise.+/// Levels below 256 (nearly all) read it from a table of exactly those values.+#[inline]+fn level_bits(table: &[f64; 256], v: i16) -> f64 {+ let a = v.unsigned_abs();+ match table.get(usize::from(a)) {+ Some(&b) => b,+ None => 3.0 + 2.0 * (a as f64).log2(),+ }+}++fn level_bits_table() -> &'static [f64; 256] {+ static T: std::sync::OnceLock<[f64; 256]> = std::sync::OnceLock::new();+ T.get_or_init(|| std::array::from_fn(|a| if a == 0 { 0.4 } else { 3.0 + 2.0 * (a as f64).log2() }))+}+impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ residual coding helpers@@ -244,45 +260,46 @@ impl<'a, 'b> SliceEnc<'a, 'b> {/// Code an inter candidate's residual given its luma/chroma prediction.pub(super) fn code_inter(&self, src: &Src, py: &[u8; 256], pu: &[u8; 64], pv: &[u8; 64], qp: u8, c: &mut Cand) {let t8_allowed = self.f.p.t8x8;- let use8 = if t8_allowed {+ let (use8, cbpl) = if t8_allowed {if self.f.p.adaptive_t8 {- // Compare 4x4 and 8x8 transform by SSD + lambda * (approximate) bits.- let mut c4 = c.clone();- let cbp4 = self.code_luma4(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, &mut c4);+ // Compare 4x4 and 8x8 transform by SSD + lambda * (approximate) bits. Neither+ // coder reads the fields it writes, so the 4x4 trial is coded into `c` itself+ // and the 8x8 trial into a copy that replaces `c` when it wins: the winner is+ // not coded a second time.let mut c8 = c.clone();let cbp8 = self.code_luma8(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, &mut c8);+ let cbp4 = self.code_luma4(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, c);let lam = self.f.lam.ssd[qp as usize];+ let lb = level_bits_table();let cost = |cc: &Cand, cbp: u8, eight: bool| {let d = ssd(&src.y, 16, &cc.ry, 16, 16, 16) as f64;let mut bits = 0f64;if eight {for b in 0..4 {if (cbp >> b) & 1 != 0 {- bits += cc.code.luma8[b].iter().map(|&v| if v == 0 { 0.4 } else { 3.0 + 2.0 * (v.unsigned_abs() as f64).log2() }).sum::<f64>();+ bits += cc.code.luma8[b].iter().map(|&v| level_bits(lb, v)).sum::<f64>();}}} else {for b in 0..16 {if (cbp >> (b / 4)) & 1 != 0 {- bits += 1.0- + cc.code.luma4[b].iter().map(|&v| if v == 0 { 0.4 } else { 3.0 + 2.0 * (v.unsigned_abs() as f64).log2() }).sum::<f64>();+ bits += 1.0 + cc.code.luma4[b].iter().map(|&v| level_bits(lb, v)).sum::<f64>();}}}d + lam * bits};- let _ = (cbp4, cbp8);- cost(&c8, cbp8, true) <= cost(&c4, cbp4, false)+ if cost(&c8, cbp8, true) <= cost(c, cbp4, false) {+ *c = c8;+ (true, cbp8)+ } else {+ (false, cbp4)+ }} else {- true+ (true, self.code_luma8(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, c))}} else {- false- };- let cbpl = if use8 {- self.code_luma8(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, c)- } else {- self.code_luma4(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, c)+ (false, self.code_luma4(&src.y, py, qp, Deadzone::INTER, self.f.p.decimate, c))};c.code.t8x8 = use8 && cbpl != 0;c.info.t8x8 = c.code.t8x8;diff --git a/crates/h264enc/tests/it/main.rs b/crates/h264enc/tests/it/main.rsindex f673a96da..5b3d73672 100644--- a/crates/h264enc/tests/it/main.rs+++ b/crates/h264enc/tests/it/main.rs@@ -1,3 +1,4 @@mod common;mod crf_level_and_note;mod ffmpeg_oracle;+mod pinned_decisions;diff --git a/crates/h264enc/tests/it/pinned_decisions.rs b/crates/h264enc/tests/it/pinned_decisions.rsnew file mode 100644index 000000000..293d84031--- /dev/null+++ b/crates/h264enc/tests/it/pinned_decisions.rs@@ -0,0 +1,59 @@+//! The encoder's decisions are pinned: the coded slices of synthetic clips hash to fixed values,+//! so a change that alters any decision (a mode, a motion vector, a quantiser), and not only one+//! that breaks decoding, fails here. Only slice NAL units are hashed: the SEI names the version.++use crate::common::{annexb_nals, synth};+use filmcraft_h264enc::*;++/// FNV-1a over the slice NAL units of `n` frames of [`synth`] encoded with `c`.+fn slices_hash(c: EncoderConfig, n: usize) -> u64 {+ let (w, h) = (c.width as usize, c.height as usize);+ let mut enc = Encoder::new(c).unwrap();+ let mut stream = Vec::new();+ for t in 0..n {+ let f = synth(w, h, t);+ for p in enc.encode(&f.frame(), t as i64).unwrap() {+ stream.extend(p.data);+ }+ }+ for p in enc.flush() {+ stream.extend(p.data);+ }+ let mut hash = 0xcbf2_9ce4_8422_2325u64;+ for r in annexb_nals(&stream) {+ let nal = &stream[r];+ if matches!(nal.get(3).map(|b| b & 31), Some(1 | 5)) {+ for &b in nal {+ hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);+ }+ }+ }+ hash+}++fn cfg(profile: Profile, preset: Preset, rate: RateControl) -> EncoderConfig {+ let mut c = EncoderConfig::new(320, 192, 24, 1);+ c.profile = profile;+ c.preset = preset;+ c.rate = rate;+ c.slices = 3;+ c.threads = 3;+ c+}++#[test]+fn coded_slices_are_pinned() {+ let cases = [+ ("high balanced crf", cfg(Profile::High, Preset::Balanced, RateControl::Crf(23.0)), 0xecd1_35a9_3a46_f7d8u64),+ ("high quality vbr", cfg(Profile::High, Preset::Quality, RateControl::Vbr { target_kbps: 800, max_kbps: 1200 }), 0x251e_c302_fd8a_ed38),+ ("main speed qp", cfg(Profile::Main, Preset::Speed, RateControl::Qp(30)), 0xa123_355d_d580_4e7b),+ ("baseline balanced cbr", cfg(Profile::Baseline, Preset::Balanced, RateControl::Cbr { kbps: 600 }), 0x13cb_e982_aee0_13f8),+ ];+ let got: Vec<u64> = cases.iter().map(|(_, c, _)| slices_hash(c.clone(), 20)).collect();+ for ((name, _, _), got) in cases.iter().zip(&got) {+ eprintln!("{name}: {got:#018x}");+ }+ for ((name, _, want), got) in cases.iter().zip(&got) {+ assert_eq!(*got, *want, "{name}: the coded slices changed");+ }+}