FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Refactor h264enc for strict Clippy checks
Dylan M. Taylor1654de85224d
diff --git a/crates/h264enc/examples/h264enc_synth.rs b/crates/h264enc/examples/h264enc_synth.rsindex 3d1b25f4c..e8be233c8 100644--- a/crates/h264enc/examples/h264enc_synth.rs+++ b/crates/h264enc/examples/h264enc_synth.rs@@ -5,7 +5,7 @@#[path = "../tests/it/common/mod.rs"]mod common;-use filmcraft_h264enc::*;+use filmcraft_h264enc::{Encoder, EncoderConfig, Preset, Profile, RateControl};use std::time::Instant;fn main() {diff --git a/crates/h264enc/src/cabac_mb.rs b/crates/h264enc/src/cabac_mb.rsindex df240fa7c..864f6186b 100644--- a/crates/h264enc/src/cabac_mb.rs+++ b/crates/h264enc/src/cabac_mb.rs@@ -278,10 +278,8 @@ fn cbf_dc(nb: &NbCtx, bit: u8) -> u32 {f(nb.left) + 2 * f(nb.top)}-/// Write the whole macroblock layer (after mb_skip_flag = 0 in P/B slices).-pub fn write_mb<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {- let cur = nb.cur;- // ---- mb_type+/// mb_type (and the P_L0_8x8 sub_mb_types of a P_8x8 macroblock).+fn write_mb_type<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {match c.kind {MbKind::I4x4 | MbKind::I8x8 | MbKind::I16x16 => write_intra_type(s, nb, c),MbKind::PInter => {@@ -299,78 +297,77 @@ pub fn write_mb<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {// Skip / none macroblocks are not written with write_mb._ => debug_assert!(false, "write_mb on a skipped macroblock"),}- let is_inxn = c.kind.is_inxn();if c.kind == MbKind::PInter && c.part == Part::P8x8 {for _ in 0..4 {s.decision(21, 1); // P_L0_8x8}}- // ---- mb_pred- if is_inxn {- if nb.t8x8_mode {- let cond = |m: Option<&MbInfo>| m.is_some_and(|m| m.t8x8) as usize;- s.decision(399 + cond(nb.left) + cond(nb.top), c.t8x8 as u32);- }- let n = if c.t8x8 { 4 } else { 16 };- for i in 0..n {- let p = c.ipred[i];- if p < 0 {- s.decision(68, 1);- } else {- s.decision(68, 0);- s.decision(69, (p & 1) as u32);- s.decision(69, ((p >> 1) & 1) as u32);- s.decision(69, ((p >> 2) & 1) as u32);- }+}++/// transform_size_8x8_flag.+fn write_transform_size_flag<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {+ let cond = |m: Option<&MbInfo>| m.is_some_and(|m| m.t8x8) as usize;+ s.decision(399 + cond(nb.left) + cond(nb.top), c.t8x8 as u32);+}++/// prev_intra_NxN_pred_mode flags / rem_intra_NxN_pred_mode values.+fn write_intra_pred_modes<S: BinSink>(s: &mut S, c: &MbCode) {+ let n = if c.t8x8 { 4 } else { 16 };+ for i in 0..n {+ let p = c.ipred[i];+ if p < 0 {+ s.decision(68, 1);+ } else {+ s.decision(68, 0);+ s.decision(69, (p & 1) as u32);+ s.decision(69, ((p >> 1) & 1) as u32);+ s.decision(69, ((p >> 2) & 1) as u32);}}- if c.kind.is_intra() {- let cond = |m: Option<&MbInfo>| m.is_some_and(|m| m.kind.is_intra() && m.chroma_mode != 0) as usize;- let m = c.chroma_mode as u32;- s.decision(64 + cond(nb.left) + cond(nb.top), (m > 0) as u32);- if m > 0 {- s.decision(64 + 3, (m > 1) as u32);- if m > 1 {- s.decision(64 + 3, (m > 2) as u32);- }+}++/// intra_chroma_pred_mode.+fn write_chroma_pred_mode<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {+ let cond = |m: Option<&MbInfo>| m.is_some_and(|m| m.kind.is_intra() && m.chroma_mode != 0) as usize;+ let m = c.chroma_mode as u32;+ s.decision(64 + cond(nb.left) + cond(nb.top), (m > 0) as u32);+ if m > 0 {+ s.decision(64 + 3, (m > 1) as u32);+ if m > 1 {+ s.decision(64 + 3, (m > 2) as u32);}}- if matches!(c.kind, MbKind::PInter | MbKind::BInter) {- for list in 0..2 {- for p in 0..c.part.count() {- if !c.uses_list(p, list) {- continue;- }- let (px, py, _, _) = c.part.rect(p);- let r = (py / 4) * 4 + px / 4;- let mvd = c.mvd[list][p];- write_mvd(s, 0, mvd.x as i32, mvd_sum(nb, r, list, 0));- write_mvd(s, 1, mvd.y as i32, mvd_sum(nb, r, list, 1));+}++/// mvd_lX components of every partition that uses each list.+fn write_mvds<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {+ for list in 0..2 {+ for p in 0..c.part.count() {+ if !c.uses_list(p, list) {+ continue;}+ let (px, py, _, _) = c.part.rect(p);+ let r = (py / 4) * 4 + px / 4;+ let mvd = c.mvd[list][p];+ write_mvd(s, 0, mvd.x as i32, mvd_sum(nb, r, list, 0));+ write_mvd(s, 1, mvd.y as i32, mvd_sum(nb, r, list, 1));}}- // ---- cbp, transform size, qp delta- if c.kind != MbKind::I16x16 {- write_cbp(s, nb, c.cbp);- if c.cbp & 15 != 0 && nb.t8x8_mode && !is_inxn {- let cond = |m: Option<&MbInfo>| m.is_some_and(|m| m.t8x8) as usize;- s.decision(399 + cond(nb.left) + cond(nb.top), c.t8x8 as u32);- }- }- if c.cbp == 0 && c.kind != MbKind::I16x16 {- return;- }- {- let v = c.qp_delta;- let m = if v > 0 { 2 * v as u32 - 1 } else { (-2 * v) as u32 };- s.decision(60 + nb.prev_dqp_nz as usize, (m > 0) as u32);- if m > 0 {- for k in 1..=m {- s.decision(if k == 1 { 62 } else { 63 }, (k < m) as u32);- }+}++/// mb_qp_delta.+fn write_qp_delta<S: BinSink>(s: &mut S, nb: &NbCtx, v: i32) {+ let m = if v > 0 { 2 * v as u32 - 1 } else { (-2 * v) as u32 };+ s.decision(60 + nb.prev_dqp_nz as usize, (m > 0) as u32);+ if m > 0 {+ for k in 1..=m {+ s.decision(if k == 1 { 62 } else { 63 }, (k < m) as u32);}}- // ---- residual+}++/// Luma residual blocks of the macroblock.+fn write_luma_residual<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {if c.kind == MbKind::I16x16 {write_residual(s, Cat::LumaDc, &c.luma_dc, cbf_dc(nb, 0));if c.cbp & 15 != 0 {@@ -379,22 +376,26 @@ pub fn write_mb<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {write_residual(s, Cat::LumaAc, &c.luma4[blk][1..16], cbf_luma(nb, y * 4 + x));}}- } else {- for b8 in 0..4 {- if (c.cbp >> b8) & 1 == 0 {- continue;- }- if c.t8x8 {- write_residual(s, Cat::Luma8x8, &c.luma8[b8], 0);- } else {- for i in 0..4 {- let blk = b8 * 4 + i;- let (x, y) = BLK4_XY[blk];- write_residual(s, Cat::Luma4x4, &c.luma4[blk], cbf_luma(nb, y * 4 + x));- }+ return;+ }+ for b8 in 0..4 {+ if (c.cbp >> b8) & 1 == 0 {+ continue;+ }+ if c.t8x8 {+ write_residual(s, Cat::Luma8x8, &c.luma8[b8], 0);+ } else {+ for i in 0..4 {+ let blk = b8 * 4 + i;+ let (x, y) = BLK4_XY[blk];+ write_residual(s, Cat::Luma4x4, &c.luma4[blk], cbf_luma(nb, y * 4 + x));}}}+}++/// Chroma DC / AC residual blocks of the macroblock.+fn write_chroma_residual<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {let chroma = c.cbp >> 4;if chroma != 0 {for comp in 0..2 {@@ -408,5 +409,37 @@ pub fn write_mb<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {}}}- let _ = cur;+}++/// Write the whole macroblock layer (after mb_skip_flag = 0 in P/B slices).+pub fn write_mb<S: BinSink>(s: &mut S, nb: &NbCtx, c: &MbCode) {+ write_mb_type(s, nb, c);+ let is_inxn = c.kind.is_inxn();+ // ---- mb_pred+ if is_inxn {+ if nb.t8x8_mode {+ write_transform_size_flag(s, nb, c);+ }+ write_intra_pred_modes(s, c);+ }+ if c.kind.is_intra() {+ write_chroma_pred_mode(s, nb, c);+ }+ if matches!(c.kind, MbKind::PInter | MbKind::BInter) {+ write_mvds(s, nb, c);+ }+ // ---- cbp, transform size, qp delta+ if c.kind != MbKind::I16x16 {+ write_cbp(s, nb, c.cbp);+ if c.cbp & 15 != 0 && nb.t8x8_mode && !is_inxn {+ write_transform_size_flag(s, nb, c);+ }+ }+ if c.cbp == 0 && c.kind != MbKind::I16x16 {+ return;+ }+ write_qp_delta(s, nb, c.qp_delta);+ // ---- residual+ write_luma_residual(s, nb, c);+ write_chroma_residual(s, nb, c);}diff --git a/crates/h264enc/src/cavlc.rs b/crates/h264enc/src/cavlc.rsindex a3eeb0b4a..3d959a6a0 100644--- a/crates/h264enc/src/cavlc.rs+++ b/crates/h264enc/src/cavlc.rs@@ -131,8 +131,8 @@ fn nc_of(a: Option<u8>, b: Option<u8>) -> i32 {}}-/// Write the macroblock layer in CAVLC. For P/B slices the caller writes mb_skip_run first.-pub fn write_mb(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {+/// mb_type (and the P_8x8 sub_mb_types).+fn write_mb_type(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {let intra_base = match nb.slice_type {SliceType::I => 0,SliceType::P => 5,@@ -159,47 +159,32 @@ pub fn write_mb(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {w.write_ue(0);}}- if c.kind.is_inxn() {- if nb.t8x8_mode {- w.write_bit(c.t8x8);- }- let n = if c.t8x8 { 4 } else { 16 };- for i in 0..n {- let p = c.ipred[i];- if p < 0 {- w.write_bit(true);- } else {- w.write_bit(false);- w.write_bits(p as u32, 3);- }- }- }- if c.kind.is_intra() {- w.write_ue(c.chroma_mode as u32);- }- if matches!(c.kind, MbKind::PInter | MbKind::BInter) {- for list in 0..2 {- for p in 0..c.part.count() {- if c.uses_list(p, list) {- w.write_se(c.mvd[list][p].x as i32);- w.write_se(c.mvd[list][p].y as i32);- }- }- }- }- if c.kind != MbKind::I16x16 {- let code = if c.kind.is_intra() { CBP_INTRA_TO_CODE[c.cbp as usize] } else { CBP_INTER_TO_CODE[c.cbp as usize] };- let cbp_idx = (c.cbp & 15) | ((c.cbp >> 4) << 4);- debug_assert_eq!(cbp_idx, c.cbp);- w.write_ue(code as u32);- if c.cbp & 15 != 0 && nb.t8x8_mode && !c.kind.is_inxn() {- w.write_bit(c.t8x8);+}++/// prev_intra_NxN_pred_mode flags / rem_intra_NxN_pred_mode values.+fn write_intra_pred_modes(w: &mut BitWriter, c: &MbCode) {+ let n = if c.t8x8 { 4 } else { 16 };+ for i in 0..n {+ let p = c.ipred[i];+ if p < 0 {+ w.write_bit(true);+ } else {+ w.write_bit(false);+ w.write_bits(p as u32, 3);}}- if c.cbp == 0 && c.kind != MbKind::I16x16 {- return;- }- w.write_se(c.qp_delta);+}++/// coded_block_pattern.+fn write_cbp(w: &mut BitWriter, c: &MbCode) {+ let code = if c.kind.is_intra() { CBP_INTRA_TO_CODE[c.cbp as usize] } else { CBP_INTER_TO_CODE[c.cbp as usize] };+ let cbp_idx = (c.cbp & 15) | ((c.cbp >> 4) << 4);+ debug_assert_eq!(cbp_idx, c.cbp);+ w.write_ue(code as u32);+}++/// Luma residual blocks of the macroblock.+fn write_luma_residual(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {let luma_nc = |r: usize| nc_of(nb.luma_nnz(r, true), nb.luma_nnz(r, false));if c.kind == MbKind::I16x16 {write_residual(w, &c.luma_dc, luma_nc(0));@@ -209,26 +194,30 @@ pub fn write_mb(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {write_residual(w, &c.luma4[blk][1..16], luma_nc(y * 4 + x));}}- } else {- for b8 in 0..4 {- if (c.cbp >> b8) & 1 == 0 {- continue;- }- for i in 0..4 {- let blk = b8 * 4 + i;- let (x, y) = BLK4_XY[blk];- if c.t8x8 {- let mut sub = [0i16; 16];- for k in 0..16 {- sub[k] = c.luma8[b8][4 * k + i];- }- write_residual(w, &sub, luma_nc(y * 4 + x));- } else {- write_residual(w, &c.luma4[blk], luma_nc(y * 4 + x));+ return;+ }+ for b8 in 0..4 {+ if (c.cbp >> b8) & 1 == 0 {+ continue;+ }+ for i in 0..4 {+ let blk = b8 * 4 + i;+ let (x, y) = BLK4_XY[blk];+ if c.t8x8 {+ let mut sub = [0i16; 16];+ for k in 0..16 {+ sub[k] = c.luma8[b8][4 * k + i];}+ write_residual(w, &sub, luma_nc(y * 4 + x));+ } else {+ write_residual(w, &c.luma4[blk], luma_nc(y * 4 + x));}}}+}++/// Chroma DC / AC residual blocks of the macroblock.+fn write_chroma_residual(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {let chroma = c.cbp >> 4;if chroma != 0 {for comp in 0..2 {@@ -245,6 +234,42 @@ pub fn write_mb(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {}}+/// Write the macroblock layer in CAVLC. For P/B slices the caller writes mb_skip_run first.+pub fn write_mb(w: &mut BitWriter, nb: &NbCtx, c: &MbCode) {+ write_mb_type(w, nb, c);+ if c.kind.is_inxn() {+ if nb.t8x8_mode {+ w.write_bit(c.t8x8);+ }+ write_intra_pred_modes(w, c);+ }+ if c.kind.is_intra() {+ w.write_ue(c.chroma_mode as u32);+ }+ if matches!(c.kind, MbKind::PInter | MbKind::BInter) {+ for list in 0..2 {+ for p in 0..c.part.count() {+ if c.uses_list(p, list) {+ w.write_se(c.mvd[list][p].x as i32);+ w.write_se(c.mvd[list][p].y as i32);+ }+ }+ }+ }+ if c.kind != MbKind::I16x16 {+ write_cbp(w, c);+ if c.cbp & 15 != 0 && nb.t8x8_mode && !c.kind.is_inxn() {+ w.write_bit(c.t8x8);+ }+ }+ if c.cbp == 0 && c.kind != MbKind::I16x16 {+ return;+ }+ w.write_se(c.qp_delta);+ write_luma_residual(w, nb, c);+ write_chroma_residual(w, nb, c);+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/h264enc/src/lib.rs b/crates/h264enc/src/lib.rsindex 28705cf7f..a8ad87088 100644--- a/crates/h264enc/src/lib.rs+++ b/crates/h264enc/src/lib.rs@@ -699,92 +699,91 @@ impl Encoder {/// Encode a batch of pictures that do not reference each other (a single I/P picture, or the B-frames of a/// mini-GOP). Slices of all pictures in the batch are encoded in parallel.fn encode_batch(&mut self, pics: Vec<(Input, SliceType, bool)>, out: &mut Vec<Packet>) {- struct Job {- input: Input,- st: SliceType,- idr: bool,- qpf: f64,- qp: u8,- cplx: f64,- aq: Vec<i8>,- hdr: SliceHeader,- nal_ref_idc: u8,- l0: Option<usize>,- l1: Option<usize>,- poc: i32,- rec: Option<Frame>,- mbs: Vec<MbInfo>,- results: Vec<SliceOut>,- }let mut jobs: Vec<Job> = Vec::with_capacity(pics.len());- for (input, mut st, idr) in pics {- if idr {- let old: Vec<RefPic> = std::mem::take(&mut self.dpb);- for r in old {- self.recycle_ref(r);- }- self.next_frame_num = 0;- }- let poc = 2 * (input.display as i64 - self.last_idr as i64) as i32;- let by_id = self.dpb.iter().enumerate().max_by_key(|(_, r)| r.id).map(|(i, _)| i);- let (mut l0, mut l1) = match st {- SliceType::I => (None, None),- SliceType::P => (by_id, None),- SliceType::B => (- self.dpb.iter().enumerate().filter(|(_, r)| r.poc < poc).max_by_key(|(_, r)| r.poc).map(|(i, _)| i),- self.dpb.iter().enumerate().filter(|(_, r)| r.poc > poc).min_by_key(|(_, r)| r.poc).map(|(i, _)| i),- ),- };- if st == SliceType::B && (l0.is_none() || l1.is_none()) {- st = SliceType::P;- l0 = by_id;- l1 = None;- }- if st == SliceType::P && l0.is_none() {- st = SliceType::I;+ for (input, st, idr) in pics {+ let job = self.plan_job(input, st, idr, jobs.len());+ jobs.push(job);+ }+ self.encode_slices(&mut jobs);+ // ---- finalise each picture in coding order+ for job in jobs {+ self.finalise_job(job, out);+ }+ }++ /// Choose the final slice type and references of one picture, derive its quantiser and slice header,+ /// and allocate its reconstruction buffers. `queued` is the number of pictures already planned in the batch.+ fn plan_job(&mut self, input: Input, mut st: SliceType, idr: bool, queued: usize) -> Job {+ if idr {+ let old: Vec<RefPic> = std::mem::take(&mut self.dpb);+ for r in old {+ self.recycle_ref(r);}- let is_ref = st != SliceType::B;- let cplx = match st {- SliceType::I => input.cplx.intra,- _ => input.cplx.inter,- } as f64;- let qpf = self.rc.frame_qp(st, cplx, self.coded_count as usize + jobs.len());- let qp = qpf.round().clamp(0.0, 51.0) as u8;- let aq: Vec<i8> = if input.aq.is_empty() {- Vec::new()- } else {- input.aq.iter().map(|&o| ((qpf + o as f64).round().clamp(0.0, 51.0) as i32 - qp as i32) as i8).collect()- };- let nal_ref_idc = if idr {- 3- } else if is_ref {- 2- } else {- 0- };- let hdr = SliceHeader {- first_mb: 0,- slice_type: st,- nal_ref_idc,- idr,- idr_pic_id: self.idr_count % 2,- frame_num: self.next_frame_num % (1 << LOG2_MAX_FRAME_NUM),- log2_max_frame_num: LOG2_MAX_FRAME_NUM,- poc_lsb: (poc as u32) % (1 << LOG2_MAX_POC_LSB),- log2_max_poc_lsb: LOG2_MAX_POC_LSB,- l0_modification: None,- cabac: self.params.cabac,- slice_qp: qp as i32,- pic_init_qp: 26,- disable_deblocking: if self.slices > 1 { 2 } else { 0 },- alpha_offset_div2: 0,- beta_offset_div2: 0,- };- let rec = self.new_frame();- let mbs = vec![MbInfo::default(); self.params.mbw * self.params.mbh];- jobs.push(Job { input, st, idr, qpf, qp, cplx, aq, hdr, nal_ref_idc, l0, l1, poc, rec: Some(rec), mbs, results: Vec::new() });+ self.next_frame_num = 0;+ }+ let poc = 2 * (input.display as i64 - self.last_idr as i64) as i32;+ let by_id = self.dpb.iter().enumerate().max_by_key(|(_, r)| r.id).map(|(i, _)| i);+ let (mut l0, mut l1) = match st {+ SliceType::I => (None, None),+ SliceType::P => (by_id, None),+ SliceType::B => (+ self.dpb.iter().enumerate().filter(|(_, r)| r.poc < poc).max_by_key(|(_, r)| r.poc).map(|(i, _)| i),+ self.dpb.iter().enumerate().filter(|(_, r)| r.poc > poc).min_by_key(|(_, r)| r.poc).map(|(i, _)| i),+ ),+ };+ if st == SliceType::B && (l0.is_none() || l1.is_none()) {+ st = SliceType::P;+ l0 = by_id;+ l1 = None;}+ if st == SliceType::P && l0.is_none() {+ st = SliceType::I;+ }+ let is_ref = st != SliceType::B;+ let cplx = match st {+ SliceType::I => input.cplx.intra,+ _ => input.cplx.inter,+ } as f64;+ let qpf = self.rc.frame_qp(st, cplx, self.coded_count as usize + queued);+ let qp = qpf.round().clamp(0.0, 51.0) as u8;+ let aq: Vec<i8> = if input.aq.is_empty() {+ Vec::new()+ } else {+ input.aq.iter().map(|&o| ((qpf + o as f64).round().clamp(0.0, 51.0) as i32 - qp as i32) as i8).collect()+ };+ let nal_ref_idc = if idr {+ 3+ } else if is_ref {+ 2+ } else {+ 0+ };+ let hdr = SliceHeader {+ first_mb: 0,+ slice_type: st,+ nal_ref_idc,+ idr,+ idr_pic_id: self.idr_count % 2,+ frame_num: self.next_frame_num % (1 << LOG2_MAX_FRAME_NUM),+ log2_max_frame_num: LOG2_MAX_FRAME_NUM,+ poc_lsb: (poc as u32) % (1 << LOG2_MAX_POC_LSB),+ log2_max_poc_lsb: LOG2_MAX_POC_LSB,+ l0_modification: None,+ cabac: self.params.cabac,+ slice_qp: qp as i32,+ pic_init_qp: 26,+ disable_deblocking: if self.slices > 1 { 2 } else { 0 },+ alpha_offset_div2: 0,+ beta_offset_div2: 0,+ };+ let rec = self.new_frame();+ let mbs = vec![MbInfo::default(); self.params.mbw * self.params.mbh];+ Job { input, st, idr, qpf, qp, cplx, aq, hdr, nal_ref_idc, l0, l1, poc, rec: Some(rec), mbs, results: Vec::new() }+ }+ /// Encode all slices of the batch's pictures in parallel (with deblocking of each slice band), storing+ /// the results and reconstructions back into `jobs`.+ fn encode_slices(&self, jobs: &mut [Job]) {// ---- parallel slice encoding (+ deblocking of each slice band)let (mbw, mbh) = (self.params.mbw, self.params.mbh);let n = self.slices;@@ -794,7 +793,7 @@ impl Encoder {// Every job carries its reconstruction buffer (`rec: Some(..)` above).let mut bufs: Vec<(Frame, Vec<MbInfo>)> = jobs.iter_mut().filter_map(|j| Some((j.rec.take()?, std::mem::take(&mut j.mbs)))).collect();{- let this = &*self;+ let this = self;let fencs: Vec<FrameEnc> = jobs.iter().map(|j| FrameEnc {@@ -876,101 +875,101 @@ impl Encoder {j.mbs = mbs;j.results = res;}+ }- // ---- finalise each picture in coding order- for job in jobs {- let Job { input, st, idr, qpf, qp, cplx, hdr: _, nal_ref_idc: _, l0: _, l1: _, poc, rec, mbs, results, aq: _ } = job;- let Some(mut rec) = rec else { continue };- let is_ref = st != SliceType::B;- let annexb = self.cfg.format == PacketFormat::AnnexB;- let mut nals: Vec<Vec<u8>> = Vec::new();- if annexb && self.cfg.aud {- let t = match st {- SliceType::I => 0,- SliceType::P => 1,- SliceType::B => 2,- };- nals.push(nal::nal(0, NAL_AUD, &nal::aud_rbsp(t)));- }- if idr && annexb {- nals.push(self.sps_nal.clone());- nals.push(self.pps_nal.clone());- }- if !self.sei_sent {- self.sei_sent = true;- let text = format!("filmcraft-h264enc {} - clean-room H.264 encoder - options: {}", env!("CARGO_PKG_VERSION"), self.options());- nals.push(nal::nal(0, NAL_SEI, &nal::sei_user_data_rbsp(&text)));- if self.cfg.mastering_display.is_some() || self.cfg.content_light.is_some() {- nals.push(nal::nal(0, NAL_SEI, &nal::sei_hdr_rbsp(self.cfg.mastering_display.as_ref(), self.cfg.content_light)));- }- }- for r in results {- nals.push(r.nal);- }- let mut data = Vec::with_capacity(nals.iter().map(|n| n.len() + 4).sum());- for n in &nals {- if annexb {- data.extend_from_slice(&[0, 0, 0, 1]);- } else {- data.extend_from_slice(&(n.len() as u32).to_be_bytes());- }- data.extend_from_slice(n);- }- let total_bits = data.len() as u64 * 8;- self.rc.update(st, qpf, cplx, total_bits);- if self.record_pass1 {- self.rc.record_pass1(st, qpf, cplx, total_bits);- }- if let Some(rv) = self.recon.as_mut() {- let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);- let mut y = Vec::with_capacity(w * h);- let mut u = Vec::with_capacity(w * h / 4);- let mut v = Vec::with_capacity(w * h / 4);- rec.y.copy_out(w, h, &mut y);- rec.u.copy_out(w / 2, h / 2, &mut u);- rec.v.copy_out(w / 2, h / 2, &mut v);- rv.push(ReconFrame { pts: input.pts, y, u, v });+ /// Assemble the packet of one coded picture, update rate control and the reference state.+ fn finalise_job(&mut self, job: Job, out: &mut Vec<Packet>) {+ let Job { input, st, idr, qpf, qp, cplx, hdr: _, nal_ref_idc: _, l0: _, l1: _, poc, rec, mbs, results, aq: _ } = job;+ let Some(mut rec) = rec else { return };+ let is_ref = st != SliceType::B;+ let annexb = self.cfg.format == PacketFormat::AnnexB;+ let mut nals: Vec<Vec<u8>> = Vec::new();+ if annexb && self.cfg.aud {+ let t = match st {+ SliceType::I => 0,+ SliceType::P => 1,+ SliceType::B => 2,+ };+ nals.push(nal::nal(0, NAL_AUD, &nal::aud_rbsp(t)));+ }+ if idr && annexb {+ nals.push(self.sps_nal.clone());+ nals.push(self.pps_nal.clone());+ }+ if !self.sei_sent {+ self.sei_sent = true;+ let text = format!("filmcraft-h264enc {} - clean-room H.264 encoder - options: {}", env!("CARGO_PKG_VERSION"), self.options());+ nals.push(nal::nal(0, NAL_SEI, &nal::sei_user_data_rbsp(&text)));+ if self.cfg.mastering_display.is_some() || self.cfg.content_light.is_some() {+ nals.push(nal::nal(0, NAL_SEI, &nal::sei_hdr_rbsp(self.cfg.mastering_display.as_ref(), self.cfg.content_light)));}- if is_ref {- let hp = self.hpel_pool.pop();- let hpel = self.pool.install(|| {- rec.extend_edges();- build_hpel(&rec.y, hp)- });- self.ref_uid += 1;- let rp = RefPic { frame: rec, hpel, mbs, poc, id: self.ref_uid };- if self.dpb.len() >= self.max_refs {- // sliding window: drop the oldest- if let Some(oldest) = self.dpb.iter().enumerate().min_by_key(|(_, r)| r.id).map(|(i, _)| i) {- let r = self.dpb.remove(oldest);- self.recycle_ref(r);- }- }- self.dpb.push(rp);- self.next_frame_num = (self.next_frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM);+ }+ for r in results {+ nals.push(r.nal);+ }+ let mut data = Vec::with_capacity(nals.iter().map(|n| n.len() + 4).sum());+ for n in &nals {+ if annexb {+ data.extend_from_slice(&[0, 0, 0, 1]);} else {- self.recycle(rec);- }- if idr {- self.idr_count += 1;+ data.extend_from_slice(&(n.len() as u32).to_be_bytes());}- // decoding timestamp base: the k-th smallest presentation time (offset applied in `release`)- // One display time is queued per input picture, so the queue is never empty here.- let pos = self.display_pts.iter().enumerate().min_by_key(|(_, p)| **p).map(|(i, _)| i);- let dts_base = pos.and_then(|p| self.display_pts.remove(p)).unwrap_or(input.pts);- self.coded_count += 1;- let frame_type = if idr {- FrameType::Idr- } else {- match st {- SliceType::I => FrameType::I,- SliceType::P => FrameType::P,- SliceType::B => FrameType::B,+ data.extend_from_slice(n);+ }+ let total_bits = data.len() as u64 * 8;+ self.rc.update(st, qpf, cplx, total_bits);+ if self.record_pass1 {+ self.rc.record_pass1(st, qpf, cplx, total_bits);+ }+ if let Some(rv) = self.recon.as_mut() {+ let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);+ let mut y = Vec::with_capacity(w * h);+ let mut u = Vec::with_capacity(w * h / 4);+ let mut v = Vec::with_capacity(w * h / 4);+ rec.y.copy_out(w, h, &mut y);+ rec.u.copy_out(w / 2, h / 2, &mut u);+ rec.v.copy_out(w / 2, h / 2, &mut v);+ rv.push(ReconFrame { pts: input.pts, y, u, v });+ }+ if is_ref {+ let hp = self.hpel_pool.pop();+ let hpel = self.pool.install(|| {+ rec.extend_edges();+ build_hpel(&rec.y, hp)+ });+ self.ref_uid += 1;+ let rp = RefPic { frame: rec, hpel, mbs, poc, id: self.ref_uid };+ if self.dpb.len() >= self.max_refs {+ // sliding window: drop the oldest+ if let Some(oldest) = self.dpb.iter().enumerate().min_by_key(|(_, r)| r.id).map(|(i, _)| i) {+ let r = self.dpb.remove(oldest);+ self.recycle_ref(r);}- };- self.recycle(input.frame);- out.push(Packet { data, pts: input.pts, dts: dts_base, keyframe: idr, frame_type, qp });+ }+ self.dpb.push(rp);+ self.next_frame_num = (self.next_frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM);+ } else {+ self.recycle(rec);}+ if idr {+ self.idr_count += 1;+ }+ // decoding timestamp base: the k-th smallest presentation time (offset applied in `release`)+ // One display time is queued per input picture, so the queue is never empty here.+ let pos = self.display_pts.iter().enumerate().min_by_key(|(_, p)| **p).map(|(i, _)| i);+ let dts_base = pos.and_then(|p| self.display_pts.remove(p)).unwrap_or(input.pts);+ self.coded_count += 1;+ let frame_type = if idr {+ FrameType::Idr+ } else {+ match st {+ SliceType::I => FrameType::I,+ SliceType::P => FrameType::P,+ SliceType::B => FrameType::B,+ }+ };+ self.recycle(input.frame);+ out.push(Packet { data, pts: input.pts, dts: dts_base, keyframe: idr, frame_type, qp });}fn recycle_ref(&mut self, r: RefPic) {@@ -981,6 +980,25 @@ impl Encoder {}}+/// One picture of a batch while it is planned, sliced and finalised.+struct Job {+ input: Input,+ st: SliceType,+ idr: bool,+ qpf: f64,+ qp: u8,+ cplx: f64,+ aq: Vec<i8>,+ hdr: SliceHeader,+ nal_ref_idc: u8,+ l0: Option<usize>,+ l1: Option<usize>,+ poc: i32,+ rec: Option<Frame>,+ mbs: Vec<MbInfo>,+ results: Vec<SliceOut>,+}+fn jobs_stride_y(mbw: usize) -> usize {mbw * 16 + 2 * LUMA_PAD}diff --git a/crates/h264enc/src/picture.rs b/crates/h264enc/src/picture.rsindex ee385ee91..a18a96471 100644--- a/crates/h264enc/src/picture.rs+++ b/crates/h264enc/src/picture.rs@@ -189,6 +189,15 @@ const QPEL_SRC: [[(u8, u8, u8); 2]; 16] = [[(2, 1, 0), (1, 0, 1)],];+/// A `w` x `h` block at sample position (`x`, `y`) of a plane.+#[derive(Clone, Copy, Debug)]+pub struct McBlock {+ pub x: usize,+ pub y: usize,+ pub w: usize,+ pub h: usize,+}+impl RefPic {#[inline]fn plane(&self, p: u8) -> &Plane {@@ -199,7 +208,8 @@ impl RefPic {}/// Luma prediction of a w x h block at picture position (x, y) displaced by `mv` (quarter samples).- pub fn mc_luma(&self, x: usize, y: usize, mv: Mv, w: usize, h: usize, out: &mut [u8], ostride: usize) {+ pub fn mc_luma(&self, blk: McBlock, mv: Mv, out: &mut [u8], ostride: usize) {+ let McBlock { x, y, w, h } = blk;let xi = x as isize + (mv.x as isize >> 2);let yi = y as isize + (mv.y as isize >> 2);let q = ((mv.y & 3) * 4 + (mv.x & 3)) as usize;@@ -226,7 +236,9 @@ impl RefPic {}/// Chroma prediction (both planes) of a w x h chroma block at chroma position (x, y); mv in luma quarter units.- pub fn mc_chroma(&self, x: usize, y: usize, mv: Mv, w: usize, h: usize, out_u: &mut [u8], out_v: &mut [u8], ostride: usize) {+ pub fn mc_chroma(&self, blk: McBlock, mv: Mv, out: (&mut [u8], &mut [u8]), ostride: usize) {+ let McBlock { x, y, w, h } = blk;+ let (out_u, out_v) = out;let xi = x as isize + (mv.x as isize >> 3);let yi = y as isize + (mv.y as isize >> 3);let fx = (mv.x & 7) as u32;diff --git a/crates/h264enc/src/slice.rs b/crates/h264enc/src/slice.rsindex ae328ccb5..4b2b70a6e 100644--- a/crates/h264enc/src/slice.rs+++ b/crates/h264enc/src/slice.rs@@ -311,7 +311,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {/// Neighbouring partition data at 4x4 offset (bx, by) relative to the MB (range -1..=4)./// None = not available; Some((ref, mv)) with ref = -1 for intra / list unused.- fn nb_part(&self, cur: &MbInfo, mask: u16, mx: usize, my: usize, bx: i32, by: i32, list: usize) -> Option<(i8, Mv)> {+ fn nb_part(&self, nb: MvNb, bx: i32, by: i32, list: usize) -> Option<(i8, Mv)> {+ let MvNb { cur, mask, mx, my } = nb;if (0..4).contains(&bx) && (0..4).contains(&by) {let r = (by * 4 + bx) as usize;if mask & (1 << r) != 0 {@@ -345,12 +346,13 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}/// Motion vector predictor (§8.4.1.3) for a partition at 4x4 coords (x, y) of size (w, h) (in 4x4 units).- fn mvp(&self, cur: &MbInfo, mask: u16, mx: usize, my: usize, x: i32, y: i32, w: i32, list: usize, rf: i8, shape: Shape) -> Mv {- let a = self.nb_part(cur, mask, mx, my, x - 1, y, list);- let b = self.nb_part(cur, mask, mx, my, x, y - 1, list);- let mut c = self.nb_part(cur, mask, mx, my, x + w, y - 1, list);+ fn mvp(&self, nb: MvNb, geom: PartGeom, list: usize, rf: i8) -> Mv {+ let PartGeom { x, y, w, shape } = geom;+ let a = self.nb_part(nb, x - 1, y, list);+ let b = self.nb_part(nb, x, y - 1, list);+ let mut c = self.nb_part(nb, x + w, y - 1, list);if c.is_none() {- c = self.nb_part(cur, mask, mx, my, x - 1, y - 1, list);+ c = self.nb_part(nb, x - 1, y - 1, list);}let (mut b, mut c) = (b, c);if b.is_none() && c.is_none() && a.is_some() {@@ -382,13 +384,14 @@ impl<'a, 'b> SliceEnc<'a, 'b> {fn pskip_mv(&self, mx: usize, my: usize) -> Mv {let cur = MbInfo::default();- let a = self.nb_part(&cur, 0, mx, my, -1, 0, 0);- let b = self.nb_part(&cur, 0, mx, my, 0, -1, 0);+ let nb = MvNb { cur: &cur, mask: 0, mx, my };+ let a = self.nb_part(nb, -1, 0, 0);+ let b = self.nb_part(nb, 0, -1, 0);match (a, b) {(None, _) | (_, None) => Mv::ZERO,(Some((0, m)), _) if m == Mv::ZERO => Mv::ZERO,(_, Some((0, m))) if m == Mv::ZERO => Mv::ZERO,- _ => self.mvp(&cur, 0, mx, my, 0, 0, 4, 0, 0, Shape::Normal),+ _ => self.mvp(nb, PartGeom { x: 0, y: 0, w: 4, shape: Shape::Normal }, 0, 0),}}@@ -403,6 +406,65 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}}+/// The macroblock (`mx`, `my`) being analysed: quantiser, neighbour availability and edge samples, and source.+#[derive(Clone, Copy)]+struct MbCtx<'x> {+ mx: usize,+ my: usize,+ qp: u8,+ av: Avail,+ e: &'x MbEdges,+ src: &'x Src,+}++/// Where a motion-vector-predictor neighbour lookup happens: the macroblock (`mx`, `my`) whose already+/// decided partitions (`mask` over the 4x4 blocks of `cur`) are visible.+#[derive(Clone, Copy)]+struct MvNb<'c> {+ cur: &'c MbInfo,+ mask: u16,+ mx: usize,+ my: usize,+}++/// A partition for motion-vector prediction: 4x4-block origin (`x`, `y`), width `w` (in 4x4 units), and shape.+#[derive(Clone, Copy)]+struct PartGeom {+ x: i32,+ y: i32,+ w: i32,+ shape: Shape,+}++/// A luma block to motion-search at picture position (`x`, `y`) against `src` (row stride `sstride`).+#[derive(Clone, Copy)]+struct SearchBlock<'s> {+ x: usize,+ y: usize,+ w: usize,+ h: usize,+ src: &'s [u8],+ sstride: usize,+}++/// Parameters of a sequential per-partition search of macroblock (`mx`, `my`) for one reference list.+#[derive(Clone, Copy)]+struct PartSearch {+ mx: usize,+ my: usize,+ part: Part,+ list: usize,+ lam: u32,+ seed: Mv,+}++/// Destination buffers (luma 16x16, chroma 8x8 each) of a motion-compensated prediction.+struct PredOut<'p> {+ y: &'p mut [u8; 256],+ u: &'p mut [u8; 64],+ v: &'p mut [u8; 64],+}+struct Src {y: [u8; 256],u: [u8; 64],diff --git a/crates/h264enc/src/slice/b_slices.rs b/crates/h264enc/src/slice/b_slices.rsindex 40e71b263..f540b31ee 100644--- a/crates/h264enc/src/slice/b_slices.rs+++ b/crates/h264enc/src/slice/b_slices.rs@@ -1,4 +1,4 @@-use super::*;+use super::{Avail, Cand, MbCtx, MbEdges, MbInfo, MbKind, Mv, MvNb, Part, PartGeom, PartSearch, PredOut, Shape, SliceEnc, Src, avg_into, mv_bits, sad16, satd};impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ B slices@@ -6,12 +6,13 @@ impl<'a, 'b> SliceEnc<'a, 'b> {/// Spatial direct prediction (§8.4.1.2.2) with direct_8x8_inference. Returns per-8x8 refs and mvs.fn direct_spatial(&self, mx: usize, my: usize) -> ([[i8; 4]; 2], [[Mv; 4]; 2]) {let cur = MbInfo::default();+ let nb = MvNb { cur: &cur, mask: 0, mx, my };let mut refs = [-1i8; 2];let mut mvp = [Mv::ZERO; 2];for l in 0..2 {- let a = self.nb_part(&cur, 0, mx, my, -1, 0, l).map_or(-1, |v| v.0);- let b = self.nb_part(&cur, 0, mx, my, 0, -1, l).map_or(-1, |v| v.0);- let c = self.nb_part(&cur, 0, mx, my, 4, -1, l).or_else(|| self.nb_part(&cur, 0, mx, my, -1, -1, l)).map_or(-1, |v| v.0);+ let a = self.nb_part(nb, -1, 0, l).map_or(-1, |v| v.0);+ let b = self.nb_part(nb, 0, -1, l).map_or(-1, |v| v.0);+ let c = self.nb_part(nb, 4, -1, l).or_else(|| self.nb_part(nb, -1, -1, l)).map_or(-1, |v| v.0);let minp = |x: i8, y: i8| if x >= 0 && y >= 0 { x.min(y) } else { x.max(y) };refs[l] = minp(a, minp(b, c));}@@ -21,7 +22,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {} else {for l in 0..2 {if refs[l] >= 0 {- mvp[l] = self.mvp(&cur, 0, mx, my, 0, 0, 4, l, refs[l], Shape::Normal);+ mvp[l] = self.mvp(nb, PartGeom { x: 0, y: 0, w: 4, shape: Shape::Normal }, l, refs[l]);}}}@@ -50,19 +51,20 @@ 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. 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>> {+ fn b_partition(&self, m: &MbCtx, part: Part, lam: u32, seeds: [Mv; 2], beat: Option<u64>) -> Option<Box<Cand>> {+ let MbCtx { mx, my, qp, src, .. } = *m;let f = self.f;let rp = [f.l0?, f.l1?];let (px, py) = (mx * 16, my * 16);let mut mvs = [[Mv::ZERO; 4]; 2];for l in 0..2 {- mvs[l] = self.search_part(mx, my, rp[l], part, l, src, lam, seeds[l]).0;+ mvs[l] = self.search_part(rp[l], &PartSearch { mx, my, part, list: l, lam, seed: seeds[l] }, src).0;}let mut preds = [([0u8; 256], [0u8; 64], [0u8; 64]), ([0u8; 256], [0u8; 64], [0u8; 64])];for l in 0..2 {let (a, b, c) = &mut preds[l];for pi in 0..2 {- self.pred_block(rp[l], px, py, part.rect(pi), mvs[l][pi], a, b, c);+ self.pred_block(rp[l], (px, py), part.rect(pi), mvs[l][pi], PredOut { y: a, u: b, v: c });}}let mut bi = preds[0];@@ -88,6 +90,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {if beat.is_some_and(|b| cost >= b) {return None;}+ 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]);@@ -108,7 +113,12 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let mask = Self::mask_of(part, pi);for l in 0..2 {if dirs[pi] == 2 || dirs[pi] as usize == l {- let mvp = self.mvp(&info, mask, mx, my, (x / 4) as i32, (y / 4) as i32, (w / 4) as i32, l, 0, Self::shape_of(part, pi));+ let mvp = self.mvp(+ MvNb { cur: &info, mask, mx, my },+ PartGeom { x: (x / 4) as i32, y: (y / 4) as i32, w: (w / 4) as i32, shape: Self::shape_of(part, pi) },+ l,+ 0,+ );let mv = mvs[l][pi];mvds[l][pi] = Mv::new(mv.x as i32 - mvp.x as i32, mv.y as i32 - mvp.y as i32);refs[l][pi] = 0;@@ -142,7 +152,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {pub(super) fn analyse_b(&self, mx: usize, my: usize, qp: u8, av: Avail, e: &MbEdges, src: &Src) -> Box<Cand> {let f = self.f;// B slices always have both references; without them the macroblock is coded intra.- let (Some(r0), Some(r1)) = (f.l0, f.l1) else { return self.analyse_intra(mx, my, qp, av, e, src, u64::MAX) };+ let (Some(r0), Some(r1)) = (f.l0, f.l1) else { return self.analyse_intra(&MbCtx { mx, my, qp, av, e, src }, u64::MAX) };let lam = f.lam.sad[qp as usize];let (px, py) = (mx * 16, my * 16);// --- direct@@ -168,11 +178,11 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let rect = Part::P8x8.rect(q);let (u0, u1) = (dref[0][q] >= 0, dref[1][q] >= 0);if u0 {- self.pred_block(r0, px, py, rect, dmv[0][q], &mut y, &mut u, &mut v);+ self.pred_block(r0, (px, py), rect, dmv[0][q], PredOut { y: &mut y, u: &mut u, v: &mut v });}if u1 {if u0 {- self.pred_block(r1, px, py, rect, dmv[1][q], &mut ty, &mut tu, &mut tv);+ self.pred_block(r1, (px, py), rect, dmv[1][q], PredOut { y: &mut ty, u: &mut tu, v: &mut tv });let (x, yy, w, h) = rect;for rr in 0..h {avg_into(&mut y[(yy + rr) * 16 + x..(yy + rr) * 16 + x + w], &ty[(yy + rr) * 16 + x..(yy + rr) * 16 + x + w]);@@ -183,7 +193,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {avg_into(&mut v[o..o + w / 2], &tv[o..o + w / 2]);}} else {- self.pred_block(r1, px, py, rect, dmv[1][q], &mut y, &mut u, &mut v);+ self.pred_block(r1, (px, py), rect, dmv[1][q], PredOut { y: &mut y, u: &mut u, v: &mut v });}}}@@ -210,13 +220,13 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// --- L0 / L1 16x16let mut res = [(Mv::ZERO, Mv::ZERO, u32::MAX); 2];for (l, rp) in [(0usize, r0), (1usize, r1)] {- let (m, p, c) = self.search_part(mx, my, rp, Part::P16x16, l, src, lam, if l == 0 { dmv[0][0] } else { dmv[1][0] });+ let (m, p, c) = self.search_part(rp, &PartSearch { mx, my, part: Part::P16x16, list: l, lam, seed: dmv[l][0] }, src);res[l] = (m[0], p[0], c);}let mut preds = [([0u8; 256], [0u8; 64], [0u8; 64]), ([0u8; 256], [0u8; 64], [0u8; 64])];for (l, rp) in [(0usize, r0), (1usize, r1)] {let (a, b, c) = &mut preds[l];- self.pred_block(rp, px, py, (0, 0, 16, 16), res[l].0, a, b, c);+ self.pred_block(rp, (px, py), (0, 0, 16, 16), res[l].0, PredOut { y: a, u: b, v: c });}let mut bi = preds[0];avg_into(&mut bi.0, &preds[1].0);@@ -268,13 +278,13 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}});}- let mut best = best.unwrap_or_else(|| self.analyse_intra(mx, my, qp, av, e, src, u64::MAX));+ let mut best = best.unwrap_or_else(|| self.analyse_intra(&MbCtx { mx, my, qp, av, e, src }, u64::MAX));// --- 16x8 / 8x16 partitions with a per-partition prediction directionif f.p.partitions && best.cost > 256 * 4 {for part in [Part::P16x8, Part::P8x16] {- // without RD only the cost decides, so a losing candidate's residual is not coded+ // 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) {+ if let Some(c) = self.b_partition(&MbCtx { mx, my, qp, av, e, src }, part, 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;@@ -283,20 +293,27 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}}}- let need_intra = f.p.always_intra || best.cost > (256 * 3 + 16 * lam as u64 / 256) * 3;- if need_intra {- let ic = self.analyse_intra(mx, my, qp, av, e, src, best.cost);- if f.p.rd {- if self.rd_cost(mx, my, &ic, src, qp) < self.rd_cost(mx, my, &best, src, qp) {- return ic;- }- } else if ic.cost < best.cost {- return ic;- }+ let ctx = MbCtx { mx, my, qp, av, e, src };+ if let Some(intra) = self.better_intra_candidate(&ctx, &best, lam) {+ return intra;}if deferred {self.code_inter(src, &py_, &pu, &pv, qp, &mut best);}best}++ fn better_intra_candidate(&self, ctx: &MbCtx<'_>, best: &Cand, lam: u32) -> Option<Box<Cand>> {+ let threshold = (256 * 3 + 16 * lam as u64 / 256) * 3;+ if !self.f.p.always_intra && best.cost <= threshold {+ return None;+ }+ let intra = self.analyse_intra(ctx, best.cost);+ let improves = if self.f.p.rd {+ self.rd_cost(ctx.mx, ctx.my, &intra, ctx.src, ctx.qp) < self.rd_cost(ctx.mx, ctx.my, best, ctx.src, ctx.qp)+ } else {+ intra.cost < best.cost+ };+ improves.then_some(intra)+ }}diff --git a/crates/h264enc/src/slice/intra.rs b/crates/h264enc/src/slice/intra.rsindex 8137e8f4d..d62a03ddf 100644--- a/crates/h264enc/src/slice/intra.rs+++ b/crates/h264enc/src/slice/intra.rs@@ -1,4 +1,7 @@-use super::*;+use super::{+ Avail, BLK4_XY, Cand, Deadzone, Edge4, Edge8, MbCtx, MbEdges, MbKind, RASTER_TO_BLK4, SliceEnc, Src, ZIGZAG4, ZIGZAG8, cavlc, dequant_luma_dc, dequant4,+ dequant8, fdct4, fdct8, filter8, idct4, idct8, mode_available, pred_chroma, pred4x4, pred8x8, pred16x16, quant_luma_dc, quant4, quant8, satd,+};impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ intra@@ -210,7 +213,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}/// Intra 4x4 analysis + coding. Returns cost (SATD domain) or None if it exceeded `limit`.- fn intra4x4(&self, mx: usize, my: usize, qp: u8, av: Avail, e: &MbEdges, src: &Src, c: &mut Cand, limit: u64) -> Option<u64> {+ fn intra4x4(&self, m: &MbCtx, c: &mut Cand, limit: u64) -> Option<u64> {+ let MbCtx { mx, my, qp, av, e, src } = *m;let qt = self.f.qt;let lam = self.f.lam.sad[qp as usize];let mut modes = [-1i8; 16];@@ -297,7 +301,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}/// Intra 8x8 analysis + coding.- fn intra8x8(&self, mx: usize, my: usize, qp: u8, av: Avail, e: &MbEdges, src: &Src, c: &mut Cand, limit: u64) -> Option<u64> {+ fn intra8x8(&self, m: &MbCtx, c: &mut Cand, limit: u64) -> Option<u64> {+ let MbCtx { mx, my, qp, av, e, src } = *m;let qt = self.f.qt;let lam = self.f.lam.sad[qp as usize];let mut modes = [-1i8; 16];@@ -383,7 +388,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}/// Full intra analysis; returns the best coded intra candidate. `inter_cost` lets P/B skip expensive modes.- pub(super) fn analyse_intra(&self, mx: usize, my: usize, qp: u8, av: Avail, e: &MbEdges, src: &Src, inter_cost: u64) -> Box<Cand> {+ pub(super) fn analyse_intra(&self, m: &MbCtx, inter_cost: u64) -> Box<Cand> {+ let MbCtx { mx, my, qp, av, e, src } = *m;let lam = self.f.lam.sad[qp as usize];let p = self.f.p;// I16x16 mode@@ -431,7 +437,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let mut limit = if p.rd { cost16 + cost16 / 4 } else { limit };if p.i8x8 && p.t8x8 {let mut c = Cand::new();- if let Some(cost) = self.intra8x8(mx, my, qp, av, e, src, &mut c, limit) {+ if let Some(cost) = self.intra8x8(m, &mut c, limit) {c.cost = cost;limit = limit.min(cost);best = Some(c);@@ -439,7 +445,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}{let mut c = Cand::new();- if let Some(cost) = self.intra4x4(mx, my, qp, av, e, src, &mut c, limit) {+ if let Some(cost) = self.intra4x4(m, &mut c, limit) {c.cost = cost;if best.as_ref().is_none_or(|b| cost < b.cost) {best = Some(c);diff --git a/crates/h264enc/src/slice/macroblock.rs b/crates/h264enc/src/slice/macroblock.rsindex 2cd79af7b..42151bace 100644--- a/crates/h264enc/src/slice/macroblock.rs+++ b/crates/h264enc/src/slice/macroblock.rs@@ -1,4 +1,4 @@-use super::*;+use super::{BitWriter, CabacEstimator, Cand, MbCtx, MbKind, NbCtx, SliceEnc, SliceType, Src, cabac_mb, cavlc, ssd};impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ macroblock@@ -29,7 +29,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let src = Src { y: src_y, u: src_u, v: src_v };let edges = self.edges(mx, my, av);let best = match f.st {- SliceType::I => self.analyse_intra(mx, my, qp, av, &edges, &src, u64::MAX),+ SliceType::I => self.analyse_intra(&MbCtx { mx, my, qp, av, e: &edges, src: &src }, u64::MAX),SliceType::P => self.analyse_p(mx, my, qp, av, &edges, &src),SliceType::B => self.analyse_b(mx, my, qp, av, &edges, &src),};diff --git a/crates/h264enc/src/slice/motion.rs b/crates/h264enc/src/slice/motion.rsindex 9774ff75e..1c06f1cc9 100644--- a/crates/h264enc/src/slice/motion.rs+++ b/crates/h264enc/src/slice/motion.rs@@ -1,4 +1,8 @@-use super::*;+use super::{+ Avail, Cand, MbCtx, MbEdges, MbInfo, MbKind, Mv, MvNb, Part, PartGeom, PartSearch, PredOut, RefPic, SearchBlock, Shape, SliceEnc, Src, mv_bits, sad, sad16,+ satd,+};+use crate::picture::McBlock;/// 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@@ -39,7 +43,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ motion estimation/// Integer + sub-pel search for a w x h block at picture (bx, by). Returns (mv, cost, satd).- fn search(&self, r: &RefPic, bx: usize, by: usize, w: usize, h: usize, src: &[u8], sstride: usize, mvp: Mv, cands: &[Mv], lam: u32) -> (Mv, u32) {+ fn search(&self, r: &RefPic, blk: &SearchBlock, mvp: Mv, cands: &[Mv], lam: u32) -> (Mv, u32) {+ let SearchBlock { x: bx, y: by, w, h, src, sstride } = *blk;let pl = &r.frame.y;let p = self.f.p;let fcost = |mv: Mv| -> u32 {@@ -113,7 +118,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// sub-pel refinement with SATDlet mut buf = [0u8; 256];let scost = |mv: Mv, buf: &mut [u8; 256]| -> u32 {- r.mc_luma(bx, by, mv, w, h, buf, 16);+ r.mc_luma(McBlock { x: bx, y: by, w, h }, mv, buf, 16);satd(src, sstride, buf, 16, w, h) + ((lam * mv_bits(mv, mvp)) >> 8)};let mut bs = scost(best, &mut buf);@@ -147,21 +152,14 @@ impl<'a, 'b> SliceEnc<'a, 'b> {(best, bs)}- pub(super) fn pred_block(- &self,- r: &RefPic,- px: usize,- py: usize,- rect: (usize, usize, usize, usize),- mv: Mv,- y: &mut [u8; 256],- u: &mut [u8; 64],- v: &mut [u8; 64],- ) {+ /// Motion-compensated luma + chroma prediction of `rect` (x, y, w, h within the macroblock whose+ /// top-left luma sample is `origin`) into `out`.+ pub(super) fn pred_block(&self, r: &RefPic, origin: (usize, usize), rect: (usize, usize, usize, usize), mv: Mv, out: PredOut) {+ let (px, py) = origin;let (x, yy, w, h) = rect;- r.mc_luma(px + x, py + yy, mv, w, h, &mut y[yy * 16 + x..], 16);+ r.mc_luma(McBlock { x: px + x, y: py + yy, w, h }, mv, &mut out.y[yy * 16 + x..], 16);let co = (yy / 2) * 8 + x / 2;- r.mc_chroma((px + x) / 2, (py + yy) / 2, mv, w / 2, h / 2, &mut u[co..], &mut v[co..], 8);+ r.mc_chroma(McBlock { x: (px + x) / 2, y: (py + yy) / 2, w: w / 2, h: h / 2 }, mv, (&mut out.u[co..], &mut out.v[co..]), 8);}pub(super) fn cand_inter_info(c: &mut Cand, part: Part, refs: [[i8; 4]; 2], mvs: [[Mv; 4]; 2], mvds: [[Mv; 4]; 2]) {@@ -210,8 +208,9 @@ impl<'a, 'b> SliceEnc<'a, 'b> {}}- /// Search each partition of `part` for list `list` sequentially (mvp depends on earlier partitions).- pub(super) fn search_part(&self, mx: usize, my: usize, r: &RefPic, part: Part, list: usize, src: &Src, lam: u32, seed: Mv) -> ([Mv; 4], [Mv; 4], u32) {+ /// Search each partition of `ps.part` for list `ps.list` sequentially (mvp depends on earlier partitions).+ pub(super) fn search_part(&self, r: &RefPic, ps: &PartSearch, src: &Src) -> ([Mv; 4], [Mv; 4], u32) {+ let PartSearch { mx, my, part, list, lam, seed } = *ps;let (px, py) = (mx * 16, my * 16);let mut info = MbInfo::default();let mut mvs = [Mv::ZERO; 4];@@ -219,9 +218,11 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let mut total = 0;for p in 0..part.count() {let (x, y, w, h) = part.rect(p);- let mask = Self::mask_of(part, p);- let mvp = self.mvp(&info, mask, mx, my, (x / 4) as i32, (y / 4) as i32, (w / 4) as i32, list, 0, Self::shape_of(part, p));- let (mv, cost) = self.search(r, px + x, py + y, w, h, &src.y[y * 16 + x..], 16, mvp, &[seed, mvs[0]], lam);+ let nb = MvNb { cur: &info, mask: Self::mask_of(part, p), mx, my };+ let geom = PartGeom { x: (x / 4) as i32, y: (y / 4) as i32, w: (w / 4) as i32, shape: Self::shape_of(part, p) };+ let mvp = self.mvp(nb, geom, list, 0);+ let blk = SearchBlock { x: px + x, y: py + y, w, h, src: &src.y[y * 16 + x..], sstride: 16 };+ let (mv, cost) = self.search(r, &blk, mvp, &[seed, mvs[0]], lam);mvs[p] = mv;mvps[p] = mvp;total += cost;@@ -243,7 +244,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {pub(super) fn analyse_p(&self, mx: usize, my: usize, qp: u8, av: Avail, e: &MbEdges, src: &Src) -> Box<Cand> {let f = self.f;// P slices always have a reference; without one the macroblock is coded intra.- let Some(r) = f.l0 else { return self.analyse_intra(mx, my, qp, av, e, src, u64::MAX) };+ let Some(r) = f.l0 else { return self.analyse_intra(&MbCtx { mx, my, qp, av, e, src }, u64::MAX) };let lam = f.lam.sad[qp as usize];let (px, py) = (mx * 16, my * 16);let skip_mv = self.pskip_mv(mx, my);@@ -254,7 +255,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let mut y = [0u8; 256];let mut u = [0u8; 64];let mut v = [0u8; 64];- self.pred_block(r, px, py, (0, 0, 16, 16), skip_mv, &mut y, &mut u, &mut v);+ self.pred_block(r, (px, py), (0, 0, 16, 16), skip_mv, PredOut { y: &mut y, u: &mut u, v: &mut v });let s = sad16(&src.y, 16, &y, 16, 16);let qstep_thresh = (f.qt.v4[(qp % 6) as usize][0] << (qp / 6)) as u32 * 16;if s < qstep_thresh * 2 {@@ -284,7 +285,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {cands.push(colo.mv[0][0]);}let (mv16, mvp16, cost16) = {- let (m, p, c) = self.search_part(mx, my, r, Part::P16x16, 0, src, lam, skip_mv);+ let (m, p, c) = self.search_part(r, &PartSearch { mx, my, part: Part::P16x16, list: 0, lam, seed: skip_mv }, src);(m, p, c)};let _ = cands;@@ -296,7 +297,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let big = cost16 as u64 > (256 * 4) as u64;if big {for part in [Part::P16x8, Part::P8x16, Part::P8x8] {- let (m, p, c) = self.search_part(mx, my, r, part, 0, src, lam, mv16[0]);+ let (m, p, c) = self.search_part(r, &PartSearch { mx, my, part, list: 0, lam, seed: mv16[0] }, src);let extra = match part {Part::P8x8 => 10,_ => 3,@@ -324,7 +325,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {pv = c;} else {for p in 0..best_part.count() {- self.pred_block(r, px, py, best_part.rect(p), best_mvs[p], &mut py_, &mut pu, &mut pv);+ self.pred_block(r, (px, py), best_part.rect(p), best_mvs[p], PredOut { y: &mut py_, u: &mut pu, v: &mut pv });}}let mut mvds = [[Mv::ZERO; 4]; 2];@@ -350,7 +351,7 @@ impl<'a, 'b> SliceEnc<'a, 'b> {// --- intralet need_intra = f.p.always_intra || best_cost > (256 * 3 + 16 * lam as u64 / 256) * 2;if need_intra {- let ic = self.analyse_intra(mx, my, qp, av, e, src, best_cost);+ let ic = self.analyse_intra(&MbCtx { mx, my, qp, av, e, src }, best_cost);if f.p.rd {if self.rd_cost(mx, my, &ic, src, qp) < self.rd_cost(mx, my, &ci, src, qp) {return ic;diff --git a/crates/h264enc/src/slice/residual.rs b/crates/h264enc/src/slice/residual.rsindex 763abc163..9e9ebb55b 100644--- a/crates/h264enc/src/slice/residual.rs+++ b/crates/h264enc/src/slice/residual.rs@@ -1,4 +1,7 @@-use super::*;+use super::{+ BLK4_XY, Cand, Deadzone, SliceEnc, Src, ZIGZAG4, ZIGZAG8, cavlc, chroma_qp, decimate_score, dequant_chroma_dc, dequant4, dequant8, fdct4, fdct8, idct4,+ idct8, quant_chroma_dc, quant4, quant8, ssd,+};/// 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.@@ -16,9 +19,44 @@ fn level_bits_table() -> &'static [f64; 256] {T.get_or_init(|| std::array::from_fn(|a| if a == 0 { 0.4 } else { 3.0 + 2.0 * (a as f64).log2() }))}+/// `rec = clamp(pred + residual(x, y))` for the 4x4 chroma block at (`bx`, `by`) of an 8x8 chroma plane.+fn add_chroma_residual(rec: &mut [u8], pred: &[u8; 64], bx: usize, by: usize, residual: impl Fn(usize, usize) -> i32) {+ for y in 0..4 {+ for x in 0..4 {+ let i = (by + y) * 8 + bx + x;+ rec[i] = (pred[i] as i32 + residual(x, y)).clamp(0, 255) as u8;+ }+ }+}+impl<'a, 'b> SliceEnc<'a, 'b> {// ------------------------------------------------------------------ residual coding helpers+ /// Transform + quantise chroma 4x4 block `b` of a component. Returns (unquantised DC, quantised+ /// coefficients in raster order, AC coefficients in scan order).+ fn quant_chroma_ac_block(&self, s: &[u8; 64], p: &[u8; 64], b: usize, qpc: u8, dz: Deadzone) -> (i32, [i32; 16], [i16; 16]) {+ let (bx, by) = ((b & 1) * 4, (b >> 1) * 4);+ let mut d = [0i32; 16];+ for y in 0..4 {+ for x in 0..4 {+ d[y * 4 + x] = s[(by + y) * 8 + bx + x] as i32 - p[(by + y) * 8 + bx + x] as i32;+ }+ }+ let mut t = fdct4(&d);+ let dc = t[0];+ quant4(&mut t, self.f.qt, qpc, dz, true);+ if self.f.p.cavlc_clamp {+ for v in t.iter_mut().skip(1) {+ *v = (*v).clamp(-cavlc::MAX_LEVEL, cavlc::MAX_LEVEL);+ }+ }+ let mut scan = [0i16; 16];+ for k in 1..16 {+ scan[k] = t[ZIGZAG4[k]] as i16;+ }+ (dc, t, scan)+ }+/// Code chroma residual for prediction `pu`, `pv`; fills code/info and reconstruction. Returns chroma cbp.pub(super) fn code_chroma(&self, src: &Src, pu: &[u8; 64], pv: &[u8; 64], qp: u8, intra: bool, c: &mut Cand) -> u8 {let qt = self.f.qt;@@ -33,25 +71,8 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let mut dc = [0i32; 4];let mut ac_score = 0;for b in 0..4 {- let (bx, by) = ((b & 1) * 4, (b >> 1) * 4);- let mut d = [0i32; 16];- for y in 0..4 {- for x in 0..4 {- d[y * 4 + x] = s[(by + y) * 8 + bx + x] as i32 - p[(by + y) * 8 + bx + x] as i32;- }- }- let mut t = fdct4(&d);- dc[b] = t[0];- quant4(&mut t, qt, qpc, dz, true);- if self.f.p.cavlc_clamp {- for v in t.iter_mut().skip(1) {- *v = (*v).clamp(-cavlc::MAX_LEVEL, cavlc::MAX_LEVEL);- }- }- let mut scan = [0i16; 16];- for k in 1..16 {- scan[k] = t[ZIGZAG4[k]] as i16;- }+ let (dc_coef, t, scan) = self.quant_chroma_ac_block(s, p, b, qpc, dz);+ dc[b] = dc_coef;ac_score += decimate_score(&scan[1..]);c.code.cac[comp * 4 + b] = scan;coefs[comp][b] = t;@@ -105,20 +126,10 @@ impl<'a, 'b> SliceEnc<'a, 'b> {let rec = if comp == 0 { &mut c.ru } else { &mut c.rv };if nz == 0 {let dcv = (t[0] + 32) >> 6;- for y in 0..4 {- for x in 0..4 {- let i = (by + y) * 8 + bx + x;- rec[i] = (p[i] as i32 + dcv).clamp(0, 255) as u8;- }- }+ add_chroma_residual(rec, p, bx, by, |_, _| dcv);} else {let r = idct4(&t);- for y in 0..4 {- for x in 0..4 {- let i = (by + y) * 8 + bx + x;- rec[i] = (p[i] as i32 + r[y * 4 + x]).clamp(0, 255) as u8;- }- }+ add_chroma_residual(rec, p, bx, by, |x, y| r[y * 4 + x]);}}}