From 6d2222858f45f42c011ffd30fef0d36036437f30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 16:17:30 +0300 Subject: [PATCH] feat(h264): software encoder, I and P pictures, CAVLC, slice-parallel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The encoder shares the decoder's reconstruction rather than owning one: prediction (pred, inter), dequantisation and the inverse transforms (transform), the deblocking filter and the per-macroblock metadata are the decoder's own code and the decoder's own Picture. What is new here is the forward direction — forward transforms and quantisation (quant), CAVLC writing derived at compile time from the decoder's tables (vlc), parameter sets and slice headers (headers), mode decision and macroblock coding (mb), and rate control (rc). Scope: Baseline-profile syntax (8-bit 4:2:0 progressive, CAVLC, one reference, pic_order_cnt_type 2), intra 16x16 and 4x4 with chroma modes, P_Skip and P_L0_16x16 with a diamond search to quarter sample, and CBR rate control with a per-macroblock-row correction. Coding a picture as one slice per worker gives the parallelism inside the encoder: a slice is independent by definition, so every worker owns its picture buffer and its bitstream, and the bands are stitched and filtered once at the end. B pictures and CABAC are not coded yet; the bframes field is accepted and coded as zero rather than refused. --- crates/ec-h264/src/decoder.rs | 166 +++- crates/ec-h264/src/enc/headers.rs | 271 ++++++ crates/ec-h264/src/enc/mb.rs | 1332 +++++++++++++++++++++++++++++ crates/ec-h264/src/enc/mod.rs | 657 ++++++++++++++ crates/ec-h264/src/enc/quant.rs | 258 ++++++ crates/ec-h264/src/enc/rc.rs | 172 ++++ crates/ec-h264/src/enc/vlc.rs | 323 +++++++ crates/ec-h264/src/inter.rs | 240 ++++-- crates/ec-h264/src/lib.rs | 6 +- 9 files changed, 3338 insertions(+), 87 deletions(-) create mode 100644 crates/ec-h264/src/enc/headers.rs create mode 100644 crates/ec-h264/src/enc/mb.rs create mode 100644 crates/ec-h264/src/enc/mod.rs create mode 100644 crates/ec-h264/src/enc/quant.rs create mode 100644 crates/ec-h264/src/enc/rc.rs create mode 100644 crates/ec-h264/src/enc/vlc.rs diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 664c0442..a9facb1f 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -886,14 +886,14 @@ impl SliceCtx { /// filter of 8.3.2.2.1, which changes its end taps when the corner sample is /// missing. #[derive(Clone, Copy)] -struct MbNeighbors { - a: bool, - b: bool, - c: bool, - d: bool, +pub(crate) struct MbNeighbors { + pub a: bool, + pub b: bool, + pub c: bool, + pub d: bool, } -fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { +pub(crate) fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { let w = pic.mb_w; let addr = mb_y * w + mb_x; let same = |a: usize| pic.mb_slice[a] == slice_id; @@ -923,7 +923,12 @@ fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> M /// global block coords `(bx, by)`, `None` when that neighbour is unavailable /// (clause 6.4.11.4 plus the availability rules of 6.4.8). #[inline] -fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option, Option) { +pub(crate) fn luma_nz_pair( + pic: &Picture, + n: &MbNeighbors, + bx: usize, + by: usize, +) -> (Option, Option) { let w4 = pic.mb_w * 4; let left_avail = if bx.is_multiple_of(4) { n.a } else { true }; let top_avail = if by.is_multiple_of(4) { n.b } else { true }; @@ -935,7 +940,7 @@ fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option /// The same for a chroma AC 4x4 block at global chroma block coords. #[inline] -fn chroma_nz_pair( +pub(crate) fn chroma_nz_pair( pic: &Picture, n: &MbNeighbors, comp: usize, @@ -2083,6 +2088,12 @@ fn compensate( let y0 = (mb_y * 16 + py * 4) as i32; let (w, h) = (pw * 4, ph * 4); + let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); + // 8.4.2.3.1 over one list is the identity, so the interpolation of that one + // list IS the prediction: it is written straight into the picture at the + // picture's own pitch, rather than into a temporary that is combined into a + // second temporary and copied a third time. + let direct = wt.is_default() && (use0 != use1); let mut part = [[0u8; 256]; 2]; for list in 0..2 { if ref_idx[list] < 0 { @@ -2099,17 +2110,33 @@ fn compensate( height: rp.y.height, pad: rp.y.pad, }; - mc_luma(&plane, x0, y0, mv[list], w, h, &mut part[list]); + if direct { + let stride = pic.y.stride; + let origin = pic.y.at(x0 as usize, y0 as usize); + mc_luma( + &plane, + x0, + y0, + mv[list], + w, + h, + stride, + &mut pic.y.data[origin..], + ); + } else { + mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list]); + } } - let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); - let mut out = [0u8; 256]; - let (p0, p1) = part.split_at(1); - combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); - let stride = pic.y.stride; - let origin = pic.y.at(x0 as usize, y0 as usize); - for row in 0..h { - let dst = origin + row * stride; - pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); + if !direct { + let mut out = [0u8; 256]; + let (p0, p1) = part.split_at(1); + combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); + let stride = pic.y.stride; + let origin = pic.y.at(x0 as usize, y0 as usize); + for row in 0..h { + let dst = origin + row * stride; + pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); + } } // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma @@ -2117,6 +2144,8 @@ fn compensate( let (cw, ch) = (w / 2, h / 2); let (cx0, cy0) = (x0 / 2, y0 / 2); for comp in 0..2 { + let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); + let direct = wt.is_default() && (use0 != use1); let mut cpart = [[0u8; 64]; 2]; for list in 0..2 { if ref_idx[list] < 0 { @@ -2134,18 +2163,35 @@ fn compensate( height: src.height, pad: src.pad, }; - mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, &mut cpart[list]); + if direct { + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = dst.stride; + let origin = dst.at(cx0 as usize, cy0 as usize); + mc_chroma( + &plane, + cx0, + cy0, + mv[list], + cw, + ch, + stride, + &mut dst.data[origin..], + ); + } else { + mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, cw, &mut cpart[list]); + } } - let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); - let mut cout = [0u8; 64]; - let (c0, c1) = cpart.split_at(1); - combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = plane.stride; - let origin = plane.at(cx0 as usize, cy0 as usize); - for row in 0..ch { - let dst = origin + row * stride; - plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); + if !direct { + let mut cout = [0u8; 64]; + let (c0, c1) = cpart.split_at(1); + combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + let origin = plane.at(cx0 as usize, cy0 as usize); + for row in 0..ch { + let dst = origin + row * stride; + plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); + } } } Ok(()) @@ -2153,7 +2199,13 @@ fn compensate( /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), /// including the top-right substitution rule. -fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { +pub(crate) fn gather_nbr4( + pic: &Picture, + nbr: &MbNeighbors, + blk: usize, + x: usize, + y: usize, +) -> Nbr4 { let (dx, dy) = BLK4_POS[blk]; let stride = pic.y.stride; let o = pic.y.at(x, y); @@ -2239,7 +2291,7 @@ fn gather_nbr8(pic: &Picture, nbr: &MbNeighbors, blk8: usize, x: usize, y: usize // index the plane as well as the strength arrays; iterating the arrays would // hide which geometry each one names. #[allow(clippy::needless_range_loop)] -fn deblock_picture(pic: &mut Picture) { +pub(crate) fn deblock_picture(pic: &mut Picture) { let mb_w = pic.mb_w; for mb_y in 0..pic.mb_h { for mb_x in 0..mb_w { @@ -2272,15 +2324,42 @@ fn deblock_picture(pic: &mut Picture) { |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0; // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). + // + // Both sides of an internal edge live in this macroblock, so the + // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra + // macroblock gives 3 everywhere, and an inter macroblock with no + // luma coefficients and one motion vector over the whole 16x16 + // gives 0 everywhere. Only the two macroblock edges then need the + // per-segment derivation. let mut bs_v = [[0u8; 4]; 4]; let mut bs_h = [[0u8; 4]; 4]; - for e in 0..4 { - for k in 0..4 { - if e > 0 || filter_left { - bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); + let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0; + let internal_uniform = if cur_intra { + Some(3) + } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) { + Some(0) + } else { + None + }; + for k in 0..4 { + if filter_left { + bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true); + } + if filter_top { + bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false); + } + } + for e in 1..4 { + match internal_uniform { + Some(bs) => { + bs_v[e] = [bs; 4]; + bs_h[e] = [bs; 4]; } - if e > 0 || filter_top { - bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); + None => { + for k in 0..4 { + bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); + bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); + } } } } @@ -2441,6 +2520,19 @@ fn deblock_picture(pic: &mut Picture) { } } +/// True when every 4x4 block of this macroblock predicts from the same +/// pictures with the same motion, so no internal edge can reach the motion +/// clauses of 8.7.2.1. +fn uniform_motion(pic: &Picture, mb_x: usize, mb_y: usize) -> bool { + let w4 = pic.mb_w * 4; + let first = mb_y * 4 * w4 + mb_x * 4; + let (mv, id) = (pic.mv[first], pic.ref_id[first]); + (0..4).all(|by| { + let row = first + by * w4; + (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id) + }) +} + /// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). /// /// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the diff --git a/crates/ec-h264/src/enc/headers.rs b/crates/ec-h264/src/enc/headers.rs new file mode 100644 index 00000000..f02a0d84 --- /dev/null +++ b/crates/ec-h264/src/enc/headers.rs @@ -0,0 +1,271 @@ +//! Parameter sets and slice headers on the writing side (spec 7.3.2, 7.3.3). +//! +//! Only the subset this encoder emits is written: 8-bit 4:2:0 progressive, +//! CAVLC, one slice group, one reference, `pic_order_cnt_type` 2 — which is +//! the type that says decode order *is* output order, and costs no bits in +//! any slice header. The test at the bottom parses everything back through +//! [`ec_h264_syntax`], which is the same parser the decoder uses. + +use ec_core::BitWriter; +use ec_h264_syntax::SliceType; + +/// Geometry and timing of the sequence, everything the parameter sets need. +#[derive(Debug, Clone, Copy)] +pub(crate) struct SeqParams { + /// Displayed luma width. + pub width: u32, + /// Displayed luma height. + pub height: u32, + /// Coded width in macroblocks. + pub mb_w: u32, + /// Coded height in macroblocks. + pub mb_h: u32, + /// `(num_units_in_tick, time_scale)`; `time_scale` is twice the frame rate. + pub timing: (u32, u32), + /// Bits per second the level has to carry. + pub bitrate: u32, +} + +/// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one +/// reference picture this encoder keeps. +pub(crate) const LOG2_MAX_FRAME_NUM: u32 = 8; + +/// Annex A levels as `(level_idc, MaxMBPS, MaxFS, MaxBR in kbit/s)`, in +/// ascending order; the first one that fits is what the SPS advertises. +const LEVELS: [(u8, u64, u64, u64); 16] = [ + (10, 1485, 99, 64), + (11, 3000, 396, 192), + (12, 6000, 396, 384), + (13, 11880, 396, 768), + (20, 11880, 396, 2000), + (21, 19800, 792, 4000), + (22, 20250, 1620, 4000), + (30, 40500, 1620, 10000), + (31, 108000, 3600, 14000), + (32, 216000, 5120, 20000), + (40, 245760, 8192, 20000), + (42, 522240, 8704, 50000), + (50, 589824, 22080, 135000), + (51, 983040, 36864, 240000), + (52, 2073600, 36864, 240000), + (62, 16711680, 139264, 800000), +]; + +fn level_idc(p: &SeqParams) -> u8 { + let frame_mbs = u64::from(p.mb_w) * u64::from(p.mb_h); + let fps = f64::from(p.timing.1) / (2.0 * f64::from(p.timing.0).max(1.0)); + let mbps = (frame_mbs as f64 * fps).ceil() as u64; + let kbps = u64::from(p.bitrate) / 1000; + for &(idc, max_mbps, max_fs, max_br) in &LEVELS { + if mbps <= max_mbps && frame_mbs <= max_fs && kbps <= max_br { + return idc; + } + } + 62 +} + +/// Write the sequence parameter set RBSP (7.3.2.1), Baseline profile with the +/// Main-profile constraint flag set: this encoder emits nothing (no FMO, no +/// ASO, no redundant slices, no interlace) that either profile forbids. +pub(crate) fn write_sps(p: &SeqParams) -> Vec { + let mut w = BitWriter::with_capacity(32); + w.write_bits(66, 8); // profile_idc: Baseline + w.write_bits(0b1100_0000, 8); // constraint_set0_flag, constraint_set1_flag + w.write_bits(u32::from(level_idc(p)), 8); + w.write_ue(0); // seq_parameter_set_id + w.write_ue(LOG2_MAX_FRAME_NUM - 4); + w.write_ue(2); // pic_order_cnt_type 2: output order is decode order + w.write_ue(1); // max_num_ref_frames + w.write_bit(false); // gaps_in_frame_num_value_allowed_flag + w.write_ue(p.mb_w - 1); + w.write_ue(p.mb_h - 1); + w.write_bit(true); // frame_mbs_only_flag + w.write_bit(true); // direct_8x8_inference_flag + let crop_right = (p.mb_w * 16 - p.width) / 2; // CropUnitX = 2 for 4:2:0 + let crop_bottom = (p.mb_h * 16 - p.height) / 2; // CropUnitY = 2, frame only + let cropping = crop_right != 0 || crop_bottom != 0; + w.write_bit(cropping); + if cropping { + w.write_ue(0); + w.write_ue(crop_right); + w.write_ue(0); + w.write_ue(crop_bottom); + } + // VUI: timing only, so a container-less stream still states its frame rate. + w.write_bit(true); // vui_parameters_present_flag + w.write_bit(false); // aspect_ratio_info_present_flag + w.write_bit(false); // overscan_info_present_flag + w.write_bit(false); // video_signal_type_present_flag + w.write_bit(false); // chroma_loc_info_present_flag + w.write_bit(true); // timing_info_present_flag + w.write_bits(p.timing.0, 32); + w.write_bits(p.timing.1, 32); + w.write_bit(true); // fixed_frame_rate_flag + w.write_bit(false); // nal_hrd_parameters_present_flag + w.write_bit(false); // vcl_hrd_parameters_present_flag + w.write_bit(false); // pic_struct_present_flag + w.write_bit(false); // bitstream_restriction_flag + trailing(&mut w); + w.into_bytes() +} + +/// Write the picture parameter set RBSP (7.3.2.2). +pub(crate) fn write_pps() -> Vec { + let mut w = BitWriter::with_capacity(8); + w.write_ue(0); // pic_parameter_set_id + w.write_ue(0); // seq_parameter_set_id + w.write_bit(false); // entropy_coding_mode_flag: CAVLC + w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag + w.write_ue(0); // num_slice_groups_minus1 + w.write_ue(0); // num_ref_idx_l0_default_active_minus1 + w.write_ue(0); // num_ref_idx_l1_default_active_minus1 + w.write_bit(false); // weighted_pred_flag + w.write_bits(0, 2); // weighted_bipred_idc + w.write_se(0); // pic_init_qp_minus26 + w.write_se(0); // pic_init_qs_minus26 + w.write_se(0); // chroma_qp_index_offset + w.write_bit(false); // deblocking_filter_control_present_flag + w.write_bit(false); // constrained_intra_pred_flag + w.write_bit(false); // redundant_pic_cnt_present_flag + trailing(&mut w); + w.into_bytes() +} + +/// What one slice header says about the picture it opens. +#[derive(Debug, Clone, Copy)] +pub(crate) struct SliceParams { + pub first_mb: u32, + pub slice_type: SliceType, + pub frame_num: u32, + pub idr: bool, + /// `idr_pic_id`, alternating between consecutive IDR pictures. + pub idr_pic_id: u32, + pub qp: i32, +} + +/// Write a slice header (7.3.3) into `w`; slice data follows immediately. +pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) { + w.write_ue(s.first_mb); + // 5..=9 assert that every slice of this picture has the same type, which + // is true here: the picture is coded in one pass at one type. + w.write_ue(if s.slice_type == SliceType::I { 7 } else { 5 }); + w.write_ue(0); // pic_parameter_set_id + w.write_bits(s.frame_num, LOG2_MAX_FRAME_NUM); + if s.idr { + w.write_ue(s.idr_pic_id); + } + // pic_order_cnt_type 2: no picture order count in the header at all. + if s.slice_type == SliceType::P { + w.write_bit(false); // num_ref_idx_active_override_flag + w.write_bit(false); // ref_pic_list_modification_flag_l0 + } + // Every picture here is a reference picture (nal_ref_idc != 0). + if s.idr { + w.write_bit(false); // no_output_of_prior_pics_flag + w.write_bit(false); // long_term_reference_flag + } else { + w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window + } + w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0 + // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0. +} + +/// `rbsp_trailing_bits` (7.3.2.11). +pub(crate) fn trailing(w: &mut BitWriter) { + w.write_bit(true); + w.align_to_byte(); +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_h264_syntax::{Pps, Sps}; + + fn params(width: u32, height: u32) -> SeqParams { + SeqParams { + width, + height, + mb_w: width.div_ceil(16), + mb_h: height.div_ceil(16), + timing: (1000, 60000), + bitrate: 8_000_000, + } + } + + /// The parameter sets this encoder writes are the ones the decoder's own + /// parser reads back, geometry, cropping and all. + #[test] + fn parameter_sets_parse_back() { + for (w, h) in [(1920, 1080), (640, 480), (854, 482), (16, 16)] { + let p = params(w, h); + let sps = Sps::parse(&write_sps(&p)).expect("SPS parses"); + assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop"); + assert_eq!(sps.mb_width, p.mb_w); + assert_eq!(sps.mb_height, p.mb_h); + assert_eq!(sps.pic_order_cnt_type, 2); + assert_eq!(sps.max_num_ref_frames, 1); + assert!(sps.frame_mbs_only); + let vui = sps.vui.as_ref().expect("VUI present"); + assert_eq!(vui.timing_info, Some((1000, 60000, true))); + let pps = Pps::parse(&write_pps(), |_| Some(&sps)).expect("PPS parses"); + assert!(!pps.entropy_coding_mode); + assert_eq!(pps.pic_init_qp, 26); + } + } + + /// 1080p60 at 8 Mbit/s needs level 4.0; a small clip needs far less. + #[test] + fn level_follows_the_load() { + assert_eq!(level_idc(¶ms(1920, 1080)), 40); + let mut small = params(320, 240); + small.timing = (1000, 30000); + small.bitrate = 300_000; + assert!(level_idc(&small) <= 21); + } + + /// A slice header reads back at the values that were written. + #[test] + fn slice_header_parses_back() { + let p = params(320, 240); + let sps = Sps::parse(&write_sps(&p)).unwrap(); + let pps = Pps::parse(&write_pps(), |_| Some(&sps)).unwrap(); + for (idr, slice_type, first_mb, qp) in [ + (true, SliceType::I, 0u32, 30i32), + (false, SliceType::P, 40, 18), + ] { + let mut w = BitWriter::new(); + write_slice_header( + &mut w, + &SliceParams { + first_mb, + slice_type, + frame_num: 7, + idr, + idr_pic_id: 1, + qp, + }, + ); + trailing(&mut w); + let rbsp = w.into_bytes(); + let header = ec_h264_syntax::SliceHeader::parse( + &rbsp, + ec_h264_syntax::nal::NalHeader { + ref_idc: 1, + unit_type: if idr { + ec_h264_syntax::nal::NalUnitType::SliceIdr + } else { + ec_h264_syntax::nal::NalUnitType::Slice + }, + }, + &sps, + &pps, + ) + .expect("slice header parses"); + assert_eq!(header.first_mb_in_slice, first_mb); + assert_eq!(header.slice_type, slice_type); + assert!(header.all_slices_same_type); + assert_eq!(header.frame_num, 7); + assert_eq!(header.slice_qp, qp); + } + } +} diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs new file mode 100644 index 00000000..9f981bfd --- /dev/null +++ b/crates/ec-h264/src/enc/mb.rs @@ -0,0 +1,1332 @@ +//! Macroblock coding: mode decision, quantisation, reconstruction and syntax. +//! +//! Reconstruction here is the decoder's own: prediction comes from +//! [`crate::pred`] and [`crate::inter`], dequantisation and the inverse +//! transforms from [`crate::transform`], and the metadata every block writes +//! into [`crate::dpb::Picture`] is what the decoder writes at the same point. +//! The encoder therefore cannot drift from the decoder by construction — the +//! only thing it adds is the *choice* of mode and the forward quantiser. + +// A block index is simultaneously a bitstream position, a geometry key +// (BLK4_POS) and a grid coordinate here, exactly as in the decoder; iterating +// the arrays instead would hide which geometry each loop names. +#![allow(clippy::needless_range_loop)] + +use ec_core::BitWriter; +use ec_h264_syntax::SliceType; +use wide::i16x16; + +use crate::decoder::{MbNeighbors, chroma_nz_pair, gather_nbr4, luma_nz_pair, mb_neighbors}; +use crate::dpb::{BLK_SKIP, Picture}; +use crate::entropy::{FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP}; +use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; +use crate::mv::{MvCtx, predict_mv, write_block, write_intra_mb, write_mvd}; +use crate::pred::{PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; +use crate::tables::{BLK4_POS, CHROMA_QP}; +use crate::transform::{ + LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform, + unzigzag, unzigzag_ac15, +}; + +use super::quant::{ + forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_chroma_dc, + quant_luma_dc, +}; +use super::vlc::{write_cbp, write_residual_block}; + +/// Speed/quality ladder. Two rungs, because the two the incumbent exposed are +/// the two edith actually picks between. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Preset { + /// Diamond motion search, 16x16 partitions, intra 4x4 in I pictures only. + #[default] + Fast, + /// Wider search with a hexagon refinement and intra 4x4 everywhere. + Balanced, +} + +/// Source planes of one picture, edge-padded out to whole macroblocks. +pub(crate) struct Source { + pub y: Vec, + pub u: Vec, + pub v: Vec, + /// Luma row pitch, equal to the coded width. + pub stride: usize, + /// Chroma row pitch. + pub c_stride: usize, +} + +/// Everything one macroblock's coding reads and updates. +pub(crate) struct MbEnc<'a> { + pub src: &'a Source, + /// The single list-0 reference, absent in an I slice. + pub reference: Option<&'a Picture>, + pub slice_type: SliceType, + pub slice_id: u16, + /// QPY of the previous macroblock: the prediction chain of 7.4.5. + pub qp: i32, + /// What rate control wants this macroblock coded at. + pub target_qp: i32, + /// Lagrangian multiplier in the SATD domain. + pub lambda: i32, + pub preset: Preset, + /// Macroblocks skipped since the last coded one (`mb_skip_run`, 7.3.4). + pub skip_run: u32, + pub ls: LevelScale4x4, +} + +/// Quantised levels of one macroblock, scan order per block. +#[derive(Default)] +struct Levels { + /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. + luma: [[i32; 16]; 16], + /// Non-zero count per luma block, Z-order. + luma_nz: [u8; 16], + /// Intra_16x16 luma DC, scan order. + dc: [i32; 16], + /// Chroma DC per component. + chroma_dc: [[i32; 16]; 2], + /// Chroma AC per component and block. + chroma: [[[i32; 16]; 4]; 2], + chroma_nz: [[u8; 4]; 2], + cbp_luma: u8, + cbp_chroma: u8, +} + +/// 4x4 Hadamard sum of absolute transformed differences between the source at +/// `(sx, sy)` and a 4x4 prediction. +fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { + let mut d = [0i32; 16]; + for y in 0..4 { + for x in 0..4 { + d[y * 4 + x] = + i32::from(src[(sy + y) * sstride + sx + x]) - i32::from(pred[y * pstride + x]); + } + } + for i in 0..4 { + let o = i * 4; + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); + d[o] = s0 + s1; + d[o + 1] = s0 - s1; + d[o + 2] = s2 + s3; + d[o + 3] = s2 - s3; + } + let mut sum = 0; + for j in 0..4 { + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); + sum += (s0 + s1).abs() + (s0 - s1).abs() + (s2 + s3).abs() + (s2 - s3).abs(); + } + (sum + 2) >> 2 +} + +/// SATD of a whole 16x16 luma macroblock against the prediction already in the +/// picture plane. +fn satd16( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + plane: &[u8], + pstride: usize, + po: usize, +) -> i32 { + let mut sum = 0; + for by in 0..4 { + for bx in 0..4 { + sum += satd4( + src, + sstride, + sx + bx * 4, + sy + by * 4, + &plane[po + by * 4 * pstride + bx * 4..], + pstride, + ); + } + } + sum +} + +#[allow(clippy::too_many_arguments)] +/// Sum of absolute differences of a 16x16 macroblock against a prediction of +/// any pitch, sixteen samples at a time: this is the motion search's inner +/// loop and nothing else in the encoder is called as often. +fn sad16( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + pred: &[u8], + po: usize, + pstride: usize, +) -> i32 { + let mut acc = i16x16::ZERO; + for row in 0..16 { + let a = load16(src, (sy + row) * sstride + sx); + let b = load16(pred, po + row * pstride); + acc += (a - b).abs(); + } + let lanes = acc.to_array(); + lanes.iter().map(|&v| i32::from(v)).sum() +} + +/// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero, +/// which only a caller reading past the plane could reach. +#[inline] +fn load16(data: &[u8], at: usize) -> i16x16 { + let mut a = [0i16; 16]; + if let Some(row) = data.get(at..at + 16) { + for (o, &b) in a.iter_mut().zip(row) { + *o = i16::from(b); + } + } + i16x16::from(a) +} + +/// Sum of absolute differences of a `w` x `h` block against a prediction with +/// its own pitch. +#[allow(clippy::too_many_arguments)] +fn sad( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + pred: &[u8], + pstride: usize, + w: usize, + h: usize, +) -> i32 { + let mut sum = 0; + for y in 0..h { + let s = &src[(sy + y) * sstride + sx..]; + let p = &pred[y * pstride..]; + for x in 0..w { + sum += (i32::from(s[x]) - i32::from(p[x])).abs(); + } + } + sum +} + +/// Bits an exp-Golomb `se(v)` costs, for the motion-vector cost term. +#[inline] +pub(crate) fn se_bits(v: i32) -> i32 { + let k = if v > 0 { 2 * v - 1 } else { -2 * v } as u32; + (32 - (k + 1).leading_zeros()) as i32 * 2 - 1 +} + +/// Chroma QP of a luma QP under a zero `chroma_qp_index_offset`. +#[inline] +fn chroma_qp(qp: i32) -> i32 { + i32::from(CHROMA_QP[qp.clamp(0, 51) as usize]) +} + +/// Which intra 4x4 modes the available neighbours allow (8.3.1.2). +fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { + [ + have_top, + have_left, + true, + have_top, + have_top && have_left && have_tl, + have_top && have_left && have_tl, + have_top && have_left && have_tl, + have_top, + have_left, + ] +} + +/// Code one macroblock: decide its mode, reconstruct it into `pic` and write +/// its syntax into `w`. +pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut BitWriter, mb_addr: usize) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let nbr = mb_neighbors(pic, mb_x, mb_y, e.slice_id); + + // Clear this macroblock's motion state, as the decoder does before parsing. + let w4 = pic.mb_w * 4; + for py in 0..4 { + let base = (mb_y * 4 + py) * w4 + mb_x * 4; + for idx in base..base + 4 { + pic.mv[idx] = [[0; 2]; 2]; + pic.ref_idx[idx] = [-1; 2]; + pic.ref_id[idx] = [-1; 2]; + pic.mvd_abs[idx] = [0; 4]; + pic.blk[idx] = 0; + } + } + + let mut inter: Option = None; + if e.slice_type == SliceType::P { + inter = Some(choose_inter(pic, e, mb_x, mb_y)); + } + + // Intra cost against the inter one: a P macroblock goes intra only when it + // is clearly cheaper, because an intra macroblock in a P picture also costs + // the next picture's prediction quality. Skipping the intra trial when the + // inter cost is already low was measured and dropped: it cost 0.7 dB on + // screen capture and bought no measurable time. + let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); + let go_intra = match &inter { + None => true, + Some(i) => intra_cost.best() + e.lambda * 8 < i.cost, + }; + + if go_intra { + encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost); + } else { + let choice = inter.expect("a P macroblock has an inter choice"); + encode_inter_mb(pic, e, w, mb_addr, nbr, choice); + } +} + +/// The intra decision taken before any reconstruction: best Intra_16x16 mode, +/// and whether the 4x4 modes look cheaper. +struct IntraCost { + i16_mode: u8, + i16_cost: i32, + i4_cost: i32, + /// True when Intra_4x4 is allowed at all for this picture and preset. + allow_i4: bool, +} + +impl IntraCost { + fn best(&self) -> i32 { + if self.allow_i4 { + self.i16_cost.min(self.i4_cost) + } else { + self.i16_cost + } + } + + fn use_i4(&self) -> bool { + self.allow_i4 && self.i4_cost < self.i16_cost + } +} + +/// Estimate both intra costs. The 4x4 estimate predicts from the *source* +/// samples inside the macroblock (they are written into the plane first), which +/// is the standard approximation: reconstruction is not available until the +/// mode is chosen, and the two differ by less than the decision margin. +fn intra_pre_cost( + pic: &mut Picture, + e: &MbEnc<'_>, + nbr: &MbNeighbors, + mb_x: usize, + mb_y: usize, +) -> IntraCost { + let (sx, sy) = (mb_x * 16, mb_y * 16); + let stride = pic.y.stride; + let origin = pic.y.at(sx, sy); + let mut best = (i32::MAX, 2u8); + for mode in [2u8, 0, 1, 3] { + let ok = match mode { + 0 => nbr.b, + 1 => nbr.a, + 3 => nbr.a && nbr.b && nbr.d, + _ => true, + }; + if !ok { + continue; + } + let mut win = PlaneWindow { + data: &mut pic.y.data, + stride, + origin, + }; + pred_16x16(mode, &mut win, nbr.b, nbr.a); + let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin); + if cost < best.0 { + best = (cost, mode); + } + } + + let allow_i4 = e.slice_type == SliceType::I || e.preset == Preset::Balanced; + let mut i4_cost = i32::MAX; + if allow_i4 { + // Source samples stand in for the not-yet-reconstructed neighbours. + for y in 0..16 { + let dst = origin + y * stride; + let s = (sy + y) * e.src.stride + sx; + pic.y.data[dst..dst + 16].copy_from_slice(&e.src.y[s..s + 16]); + } + let mut sum = 0; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (sx + dx as usize * 4, sy + dy as usize * 4); + let n = gather_nbr4(pic, nbr, blk, x, y); + let have_tl = match (dx, dy) { + (0, 0) => nbr.d, + (0, _) => nbr.a, + (_, 0) => nbr.b, + _ => true, + }; + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); + let mut best4 = i32::MAX; + let mut p = [0u8; 16]; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_4x4(mode, &n, &mut p); + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * 3; + best4 = best4.min(c); + } + sum += best4; + } + // Sixteen mode signals and a coded_block_pattern the 16x16 form does + // not pay for. + i4_cost = sum + e.lambda * 16; + } + IntraCost { + i16_mode: best.1, + i16_cost: best.0, + i4_cost, + allow_i4, + } +} + +/// The inter decision for a P macroblock. +struct InterChoice { + mv: [i16; 2], + mvp: [i16; 2], + /// The P_Skip motion vector of 8.4.1.1. + skip_mv: [i16; 2], + cost: i32, + /// The skip candidate is at least as good as the searched one. + prefer_skip: bool, +} + +/// Motion search plus the skip candidate. +fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> InterChoice { + let reference = e.reference.expect("a P slice has a reference"); + let ctx = MvCtx { + mb_x, + mb_y, + slice_id: e.slice_id, + written: 0, + }; + let n = ctx.neighbours(pic, 0, 0, 4, 0); + let mvp = predict_mv(&n, 0, 4, 4, 0); + // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a + // zero-motion reference-0 partition. + let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0); + let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0); + let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0]; + let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) { + [0, 0] + } else { + mvp + }; + + let plane = RefPlane { + data: &reference.y.data, + stride: reference.y.stride, + origin: reference.y.origin, + width: reference.y.width, + height: reference.y.height, + pad: reference.y.pad, + }; + let (sx, sy) = (mb_x * 16, mb_y * 16); + let mut buf = [0u8; 256]; + let sw = e.src.stride; + // Whole-sample candidates read the reference plane in place; only the + // sub-sample refinement pays for interpolation. The search runs on SAD, + // which is what a search can afford; the winner is re-costed on SATD below + // because the intra candidates are SATD and the two scales differ. + let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { + let bits = e.lambda + * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) + / 2; + if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { + let o = integer_origin( + &plane, + sx as i32 + (mv[0] >> 2) as i32, + sy as i32 + (mv[1] >> 2) as i32, + 16, + 16, + ); + return sad16(&e.src.y, sw, sx, sy, plane.data, o, plane.stride) + bits; + } + mc_luma(&plane, sx as i32, sy as i32, mv, 16, 16, 16, &mut buf); + let d = if satd { + satd16(&e.src.y, sw, sx, sy, &buf, 16, 0) + } else { + sad16(&e.src.y, sw, sx, sy, &buf, 0, 16) + }; + d + bits + }; + + // Candidates: the predictor, the skip vector, zero, and the vectors of the + // neighbouring partitions. + let mut best = ([0i16; 2], i32::MAX); + for cand in [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv] { + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + } + } + // A macroblock the prediction already fits is not searched further: on real + // content most of them are, and the search is the encoder's hot loop. + // A macroblock the prediction already fits within half a level a sample is + // not searched further: on real content most of them are, and this doubles + // the encoder's speed for 0.2 dB (measured, 1080p screen capture; camera + // content shows no loss at all). + const GOOD_ENOUGH: i32 = 16 * 16 / 2; + if best.1 > GOOD_ENOUGH { + // Diamond refinement at whole samples, coarse to fine. + let range = match e.preset { + Preset::Fast => 16i16, + Preset::Balanced => 48, + }; + let mut step = 4i16 * 4; // four whole samples, in quarter units + while step >= 4 { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + if (cand[0] - mvp[0]).abs() > range * 4 || (cand[1] - mvp[1]).abs() > range * 4 + { + continue; + } + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; + } + } + } + step /= 2; + } + // Half then quarter sample. + for step in [2i16, 1] { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [ + (step, 0), + (-step, 0), + (0, step), + (0, -step), + (step, step), + (-step, -step), + (step, -step), + (-step, step), + ] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; + } + } + if e.preset == Preset::Fast { + break; + } + } + } + } + + // Re-cost both candidates on SATD for the comparison against intra, and + // for the skip decision (which trades a whole macroblock of bits). + let searched = cost_of(best.0, true); + let skip_cost = cost_of(skip_mv, true) - e.lambda * 4; + InterChoice { + mv: best.0, + mvp, + skip_mv, + cost: searched.min(skip_cost), + prefer_skip: skip_cost <= searched, + } +} + +/// Motion-compensate a whole macroblock into the picture planes. +fn compensate_mb(pic: &mut Picture, reference: &Picture, mb_x: usize, mb_y: usize, mv: [i16; 2]) { + let (x0, y0) = ((mb_x * 16) as i32, (mb_y * 16) as i32); + let plane = RefPlane { + data: &reference.y.data, + stride: reference.y.stride, + origin: reference.y.origin, + width: reference.y.width, + height: reference.y.height, + pad: reference.y.pad, + }; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + mc_luma( + &plane, + x0, + y0, + mv, + 16, + 16, + stride, + &mut pic.y.data[origin..], + ); + for comp in 0..2 { + let src = if comp == 0 { + &reference.cb + } else { + &reference.cr + }; + let plane = RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }; + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = dst.stride; + let origin = dst.at(mb_x * 8, mb_y * 8); + mc_chroma( + &plane, + x0 / 2, + y0 / 2, + mv, + 8, + 8, + stride, + &mut dst.data[origin..], + ); + } +} + +/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock, +/// prediction already in the plane. +fn code_luma_4x4( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + intra: bool, + lv: &mut Levels, +) { + let stride = pic.y.stride; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let origin = pic.y.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + forward_4x4(&mut d); + let nz = quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + if nz > 0 { + lv.cbp_luma |= 1 << (blk >> 2); + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + } + } +} + +/// The Intra_16x16 luma path (8.5.10 in reverse then forward again). +fn code_luma_i16( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + lv: &mut Levels, +) { + let stride = pic.y.stride; + let mut dc = [0i32; 16]; + let mut ac = [[0i32; 16]; 16]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let origin = pic.y.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + forward_4x4(&mut d); + dc[dy as usize * 4 + dx as usize] = d[0]; + let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + ac[blk] = lv.luma[blk]; + if nz > 0 { + lv.cbp_luma = 15; + } + } + if lv.cbp_luma == 0 { + for blk in 0..16 { + lv.luma[blk] = [0; 16]; + lv.luma_nz[blk] = 0; + } + } + forward_hadamard_4x4(&mut dc); + quant_luma_dc(&dc, qp, &mut lv.dc); + + // Reconstruct exactly as the decoder does: DC through 8.5.10, then each + // block's AC with the DC substituted at raster position 0. + let mut raster = [0i32; 16]; + unzigzag(&lv.dc, &mut raster); + luma_dc_transform(&mut raster, &e.ls, qp); + let dc_recon = raster; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let dc_blk = dc_recon[dy as usize * 4 + dx as usize]; + let tc = lv.luma_nz[blk]; + if tc == 0 && dc_blk == 0 { + continue; + } + let mut raster = [0i32; 16]; + if tc > 0 { + unzigzag_ac15(&ac[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, true); + } + raster[0] = dc_blk; + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let origin = pic + .y + .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + } +} + +/// Chroma residual for both components (8.5.11 + the AC path). +fn code_chroma( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp_y: i32, + intra: bool, + lv: &mut Levels, +) { + let qp_c = chroma_qp(qp_y); + let mut dc_lists = [[0i32; 4]; 2]; + let mut ac = [[[0i32; 16]; 4]; 2]; + let mut any_ac = false; + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&pic.cb, &e.src.u) + } else { + (&pic.cr, &e.src.v) + }; + let stride = plane.stride; + for blk in 0..4 { + let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); + let origin = plane.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx]) + - i32::from(plane.data[origin + ry * stride + rx]); + } + } + forward_4x4(&mut d); + dc_lists[comp][blk] = d[0]; + let nz = quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]); + lv.chroma_nz[comp][blk] = nz; + if nz > 0 { + any_ac = true; + } + } + } + let mut any_dc = false; + for comp in 0..2 { + forward_hadamard_2x2(&mut dc_lists[comp]); + let nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]); + if nz > 0 { + any_dc = true; + } + } + lv.cbp_chroma = if any_ac { + 2 + } else if any_dc { + 1 + } else { + 0 + }; + if lv.cbp_chroma < 2 { + lv.chroma_nz = [[0; 4]; 2]; + } else { + lv.chroma = ac; + } + if lv.cbp_chroma == 0 { + return; + } + for comp in 0..2 { + let mut dc = [ + lv.chroma_dc[comp][0], + lv.chroma_dc[comp][1], + lv.chroma_dc[comp][2], + lv.chroma_dc[comp][3], + ]; + chroma_dc_transform_420(&mut dc, &e.ls, qp_c); + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + for blk in 0..4 { + let tc = lv.chroma_nz[comp][blk]; + if tc == 0 && dc[blk] == 0 { + continue; + } + let mut raster = [0i32; 16]; + if tc > 0 { + unzigzag_ac15(&lv.chroma[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + } + raster[0] = dc[blk]; + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); + add_residual_4x4(&mut plane.data, stride, origin, &resid); + } + } +} + +/// Pick the chroma prediction mode by SATD, leaving the winner in the planes. +fn choose_chroma_mode( + pic: &mut Picture, + e: &MbEnc<'_>, + nbr: &MbNeighbors, + mb_x: usize, + mb_y: usize, +) -> u8 { + let mut best = (i32::MAX, 0u8); + for mode in [0u8, 1, 2, 3] { + let ok = match mode { + 1 => nbr.a, + 2 => nbr.b, + 3 => nbr.a && nbr.b && nbr.d, + _ => true, + }; + if !ok { + continue; + } + let mut cost = 0; + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&mut pic.cb, &e.src.u) + } else { + (&mut pic.cr, &e.src.v) + }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + let mut win = PlaneWindow { + data: &mut plane.data, + stride, + origin, + }; + pred_chroma_8x8(mode, &mut win, nbr.b, nbr.a); + cost += sad( + src, + e.src.c_stride, + mb_x * 8, + mb_y * 8, + &plane.data[origin..], + stride, + 8, + 8, + ); + } + if cost < best.0 { + best = (cost, mode); + } + } + // Leave the chosen mode's prediction in place. + for comp in 0..2 { + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + let mut win = PlaneWindow { + data: &mut plane.data, + stride, + origin, + }; + pred_chroma_8x8(best.1, &mut win, nbr.b, nbr.a); + } + best.1 +} + +/// Code an intra macroblock, Intra_16x16 or Intra_4x4. +fn encode_intra_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut BitWriter, + mb_addr: usize, + nbr: MbNeighbors, + cost: IntraCost, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let w4 = pic.mb_w * 4; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let qp = e.target_qp; + write_intra_mb(pic, mb_x, mb_y); + let mut lv = Levels::default(); + let use_i4 = cost.use_i4(); + let mut modes = [2u8; 16]; + let mut pred_modes = [2u8; 16]; + + if use_i4 { + // Per block: choose the mode against reconstructed neighbours, then + // reconstruct it immediately — the next block predicts from it. + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let left_avail = if dx == 0 { nbr.a } else { true }; + let top_avail = if dy == 0 { nbr.b } else { true }; + let predicted = if left_avail && top_avail { + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) + } else { + 2 + }; + pred_modes[blk] = predicted; + let n = gather_nbr4(pic, &nbr, blk, x, y); + let have_tl = match (dx, dy) { + (0, 0) => nbr.d, + (0, _) => nbr.a, + (_, 0) => nbr.b, + _ => true, + }; + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); + let mut best = (i32::MAX, predicted.min(2)); + let mut p = [0u8; 16]; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_4x4(mode, &n, &mut p); + let bits = if mode == predicted { 1 } else { 4 }; + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; + if c < best.0 { + best = (c, mode); + } + } + let mode = best.1; + modes[blk] = mode; + pic.i4_modes[by * w4 + bx] = mode; + // Prediction into the plane, then residual and reconstruction. + pred_4x4(mode, &n, &mut p); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + for ry in 0..4 { + let row = origin + ry * stride; + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(p[ry * 4 + rx]); + } + } + forward_4x4(&mut d); + let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + if nz > 0 { + lv.cbp_luma |= 1 << (blk >> 2); + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); + } + } + } else { + for dy in 0..4 { + let base = (by0 + dy) * w4 + bx0; + pic.i4_modes[base..base + 4].fill(2); + } + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + let mut win = PlaneWindow { + data: &mut pic.y.data, + stride, + origin, + }; + pred_16x16(cost.i16_mode, &mut win, nbr.b, nbr.a); + code_luma_i16(pic, e, mb_x, mb_y, qp, &mut lv); + } + + let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); + code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv); + + // ---- syntax ---- + if e.slice_type == SliceType::P { + w.write_ue(e.skip_run); + e.skip_run = 0; + } + let intra_type = if use_i4 { + 0 + } else { + 1 + u32::from(cost.i16_mode) + + 4 * u32::from(lv.cbp_chroma) + + if lv.cbp_luma != 0 { 12 } else { 0 } + }; + let offset = if e.slice_type == SliceType::P { 5 } else { 0 }; + w.write_ue(intra_type + offset); + if use_i4 { + for blk in 0..16 { + if modes[blk] == pred_modes[blk] { + w.write_bit(true); + } else { + w.write_bit(false); + let rem = if modes[blk] > pred_modes[blk] { + modes[blk] - 1 + } else { + modes[blk] + }; + w.write_bits(u32::from(rem), 3); + } + } + } + w.write_ue(u32::from(chroma_mode)); + if use_i4 { + write_cbp(w, lv.cbp_luma, lv.cbp_chroma, true); + } + finish_mb( + pic, + e, + w, + mb_addr, + &nbr, + &lv, + MbRecord { + intra: true, + is_i16: !use_i4, + chroma_mode, + qp, + }, + ); +} + +/// Squared error of the whole macroblock against the source, luma and chroma: +/// the distortion term of the skip decision. +fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { + let mut sum = 0i64; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + for x in 0..16 { + let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); + sum += d * d; + } + } + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&pic.cb, &e.src.u) + } else { + (&pic.cr, &e.src.v) + }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + for row in 0..8 { + let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8; + for x in 0..8 { + let d = i64::from(src[s + x]) - i64::from(plane.data[origin + row * stride + x]); + sum += d * d; + } + } + } + sum +} + +/// Rough bit cost of a macroblock's residual, for the skip decision: a level +/// costs its magnitude's exp-Golomb-ish width, a coded block its token. +fn estimate_bits(lv: &Levels) -> i64 { + let mut bits = 10i64; + let block = |b: &[i32]| -> i64 { + let mut n = 0i64; + for &l in b { + if l != 0 { + n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; + } + } + if n > 0 { n + 6 } else { 2 } + }; + for blk in 0..16 { + if lv.cbp_luma & (1 << (blk >> 2)) != 0 { + bits += block(&lv.luma[blk]); + } + } + if lv.cbp_chroma != 0 { + for comp in 0..2 { + bits += block(&lv.chroma_dc[comp][..4]); + if lv.cbp_chroma == 2 { + for blk in 0..4 { + bits += block(&lv.chroma[comp][blk][..15]); + } + } + } + } + bits +} + +/// Lagrangian multiplier in the squared-error domain, paired with +/// [`super::lambda_for`] in the SATD one. +fn lambda_ssd(qp: i32) -> f64 { + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() +} + +/// Code a P macroblock: skip, or one 16x16 partition. +fn encode_inter_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut BitWriter, + mb_addr: usize, + nbr: MbNeighbors, + choice: InterChoice, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let reference = e.reference.expect("a P macroblock has a reference"); + let ref_id = reference.id; + let qp = e.target_qp; + let mv = if choice.prefer_skip { + choice.skip_mv + } else { + choice.mv + }; + + compensate_mb(pic, reference, mb_x, mb_y, mv); + // Skipping is only *available* on the P_Skip vector, and only worth taking + // when the residual it drops is worth less than the bits it saves: on + // static content a macroblock whose residual is pure quantisation churn + // costs bits every picture and improves nothing. + let may_skip = mv == choice.skip_mv; + let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); + let mut lv = Levels::default(); + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); + code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv); + let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; + let skip = match ssd_skip { + None => false, + Some(_) if empty => true, + Some(ssd_skip) => { + let coded = + ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64; + if ssd_skip as f64 <= coded { + // Put the prediction back: the residual has been added to it. + compensate_mb(pic, reference, mb_x, mb_y, mv); + true + } else { + false + } + } + }; + + let mut ctx = MvCtx { + mb_x, + mb_y, + slice_id: e.slice_id, + written: 0, + }; + let w4 = pic.mb_w * 4; + if skip { + for py in 0..4 { + for px in 0..4 { + write_block( + pic, + &mut ctx, + px, + py, + [mv, [0, 0]], + [0, -1], + [ref_id, -1], + BLK_SKIP, + ); + } + } + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.nz_y[base..base + 4].fill(0); + pic.i4_modes[base..base + 4].fill(2); + } + for comp in 0..2 { + for dy in 0..2 { + let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2; + pic.nz_c[comp][base..base + 2].fill(0); + } + } + pic.mb_qp[mb_addr] = e.qp as u8; + pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP; + pic.mb_cbp[mb_addr] = 0; + pic.mb_dc_cbf[mb_addr] = 0; + pic.mb_slice[mb_addr] = e.slice_id; + pic.decoded_mbs += 1; + e.skip_run += 1; + return; + } + + let mvd = [mv[0] - choice.mvp[0], mv[1] - choice.mvp[1]]; + for py in 0..4 { + for px in 0..4 { + write_block( + pic, + &mut ctx, + px, + py, + [mv, [0, 0]], + [0, -1], + [ref_id, -1], + 0, + ); + write_mvd(pic, mb_x, mb_y, px, py, 0, mvd); + } + } + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.i4_modes[base..base + 4].fill(2); + } + + // ---- syntax ---- + w.write_ue(e.skip_run); + e.skip_run = 0; + w.write_ue(0); // mb_type P_L0_16x16 + // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. + w.write_se(i32::from(mvd[0])); + w.write_se(i32::from(mvd[1])); + write_cbp(w, lv.cbp_luma, lv.cbp_chroma, false); + finish_mb( + pic, + e, + w, + mb_addr, + &nbr, + &lv, + MbRecord { + intra: false, + is_i16: false, + chroma_mode: 0, + qp, + }, + ); +} + +/// What the residual writer needs to know about the macroblock it closes. +struct MbRecord { + intra: bool, + is_i16: bool, + chroma_mode: u8, + /// The QP the residual was quantised at. + qp: i32, +} + +/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the +/// writing half of [`crate::decoder::finish_macroblock`]. +fn finish_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut BitWriter, + mb_addr: usize, + nbr: &MbNeighbors, + lv: &Levels, + m: MbRecord, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let w4 = pic.mb_w * 4; + let w2 = pic.mb_w * 2; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16; + let qp_y = if coded { + w.write_se(m.qp - e.qp); + e.qp = m.qp; + m.qp + } else { + // No residual: the QP prediction chain is untouched (7.4.5), and the + // deblocking filter uses the chain value. + e.qp + }; + pic.mb_qp[mb_addr] = qp_y as u8; + pic.mb_flags[mb_addr] = FLAG_DECODED + | if m.is_i16 { FLAG_I16 } else { 0 } + | if m.intra { 0 } else { FLAG_INTER } + | if m.intra && m.chroma_mode != 0 { + FLAG_CHROMA_PRED + } else { + 0 + }; + pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4); + pic.mb_slice[mb_addr] = e.slice_id; + pic.decoded_mbs += 1; + + let mut dc_cbf = 0u8; + // Luma DC (Intra_16x16 only), then the luma blocks in Z-order. + if m.is_i16 { + let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); + let nc = nc_of(na, nb); + let tc = write_residual_block(w, &lv.dc, 16, nc); + dc_cbf |= u8::from(tc != 0); + } + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let group = 1 << (blk >> 2); + let coded_block = if m.is_i16 { + lv.cbp_luma != 0 + } else { + lv.cbp_luma & group != 0 + }; + let tc = if coded_block { + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); + let nc = nc_of(na, nb); + let (levels, max) = if m.is_i16 { + (&lv.luma[blk][..15], 15) + } else { + (&lv.luma[blk][..16], 16) + }; + write_residual_block(w, levels, max, nc) + } else { + 0 + }; + pic.nz_y[by * w4 + bx] = tc; + } + // Chroma DC then chroma AC, in bitstream order. + if lv.cbp_chroma != 0 { + for comp in 0..2 { + let tc = write_residual_block(w, &lv.chroma_dc[comp][..4], 4, -1); + dc_cbf |= u8::from(tc != 0) << (1 + comp); + } + } + for comp in 0..2 { + for blk in 0..4 { + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); + let tc = if lv.cbp_chroma == 2 { + let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); + let nc = nc_of(na, nb); + write_residual_block(w, &lv.chroma[comp][blk][..15], 15, nc) + } else { + 0 + }; + pic.nz_c[comp][cy * w2 + cx] = tc; + } + } + pic.mb_dc_cbf[mb_addr] = dc_cbf; +} + +/// nC from the two neighbouring non-zero counts (9.2.1). +#[inline] +fn nc_of(na: Option, nb: Option) -> i32 { + match (na, nb) { + (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1, + (Some(a), None) => i32::from(a), + (None, Some(b)) => i32::from(b), + (None, None) => 0, + } +} diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs new file mode 100644 index 00000000..7efa7df7 --- /dev/null +++ b/crates/ec-h264/src/enc/mod.rs @@ -0,0 +1,657 @@ +//! The H.264 encoder: I and P pictures, CAVLC, 8-bit 4:2:0 progressive. +//! +//! # Shared reconstruction +//! +//! There is no second reconstruction path here. Prediction, dequantisation, +//! the inverse transforms and the deblocking filter are the decoder's own +//! modules, and the encoder fills the very same [`Picture`] the decoder fills, +//! macroblock metadata included. Encoder and decoder therefore agree on every +//! reconstructed sample by construction, not by testing — the tests only check +//! that nothing broke the property. +//! +//! # Parallelism +//! +//! A picture is cut into one slice per worker, each slice a band of whole +//! macroblock rows. A slice is independent by definition (no prediction +//! crosses its boundary), so each worker owns a private picture buffer, writes +//! its own bitstream and never reads another worker's samples; motion +//! compensation reads the *previous* picture, which is finished and immutable. +//! The bands are stitched together afterwards and the deblocking filter runs +//! once over the whole picture, across slice boundaries exactly as a decoder +//! runs it. No `unsafe`, no shared mutable state at all. + +mod headers; +mod mb; +mod quant; +mod rc; +mod vlc; + +use ec_core::BitWriter; +use ec_core::error::{Error, Result}; +use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; +use ec_h264_syntax::{SliceType, Sps}; + +use crate::decoder::deblock_picture; +use crate::dpb::{Picture, SliceParams as DeblockParams}; +use crate::transform::LevelScale4x4; + +use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; +use mb::{MbEnc, Source, encode_mb}; +use rc::RateControl; + +pub use mb::Preset; + +/// Encoder settings. +#[derive(Debug, Clone)] +pub struct EncoderConfig { + /// Displayed luma width; must be even. + pub width: u32, + /// Displayed luma height; must be even. + pub height: u32, + /// Frames per second, for the VUI timing and the bit budget. + pub framerate: f32, + /// Target bits per second. Zero means constant quantiser ([`Self::qp`]). + pub bitrate: u32, + /// Pictures between IDR pictures; 1 codes every picture as an IDR. + pub gop_size: u32, + /// Consecutive B pictures. Only 0 is coded today (see the crate note); + /// a non-zero value is accepted and coded as 0 rather than refused. + pub bframes: u32, + /// Speed/quality rung. + pub preset: Preset, + /// Worker threads, which is also the number of slices per picture; 0 means + /// as many as the machine has. + pub threads: usize, + /// Quantiser for constant-QP mode (`bitrate` zero). + pub qp: i32, +} + +impl EncoderConfig { + /// Defaults for `width x height`: 30 fps, constant QP 26, every core. + pub fn new(width: u32, height: u32) -> EncoderConfig { + EncoderConfig { + width, + height, + framerate: 30.0, + bitrate: 0, + gop_size: 250, + bframes: 0, + preset: Preset::Fast, + threads: 0, + qp: 26, + } + } +} + +/// One coded picture: an Annex-B access unit and what it cost. +#[derive(Debug, Clone, Default)] +pub struct EncodedPicture { + /// The access unit, with 4-byte start codes; parameter sets ride along on + /// every IDR so that every IDR is a seek point. + pub au: Vec, + /// True when the picture is an IDR. + pub key_frame: bool, + /// The quantiser the picture was coded at. + pub qp: i32, +} + +/// A software H.264 encoder. +pub struct Encoder { + cfg: EncoderConfig, + sps: Sps, + sps_nal: Vec, + pps_nal: Vec, + /// The previous reconstruction, which every P picture predicts from. + reference: Picture, + /// One private picture per worker; worker 0's doubles as the picture the + /// other bands are stitched into. + workers: Vec, + src: Source, + rc: RateControl, + threads: usize, + coded_width: usize, + coded_height: usize, + frames: u64, + frame_num: u32, + idr_pic_id: u32, + next_id: i32, + /// True once a reference picture exists. + have_reference: bool, +} + +/// A picture handed to the encoder: three planes, no padding assumptions. +#[derive(Debug, Clone, Copy)] +pub struct PictureView<'a> { + pub width: u32, + pub height: u32, + /// Luma plane, `width` samples per row unless `y_stride` says otherwise. + pub y: &'a [u8], + pub u: &'a [u8], + pub v: &'a [u8], + /// Row pitches; zero means "tightly packed". + pub y_stride: usize, + pub c_stride: usize, +} + +impl<'a> PictureView<'a> { + /// A tightly packed I420 picture. + pub fn i420(width: u32, height: u32, y: &'a [u8], u: &'a [u8], v: &'a [u8]) -> PictureView<'a> { + PictureView { + width, + height, + y, + u, + v, + y_stride: width as usize, + c_stride: width.div_ceil(2) as usize, + } + } +} + +impl Encoder { + /// Build an encoder for `cfg`, refusing what it cannot code. + pub fn new(cfg: EncoderConfig) -> Result { + if cfg.width < 16 || cfg.height < 16 { + return Err(Error::unsupported( + "picture smaller than one macroblock", + "H.264 codes 16x16 macroblocks; encode at 16x16 or larger", + )); + } + if !cfg.width.is_multiple_of(2) || !cfg.height.is_multiple_of(2) { + return Err(Error::unsupported( + "odd picture dimensions", + "4:2:0 chroma is half resolution in both directions, and the \ + frame cropping offsets are in two-sample units (7.4.2.1.1); \ + encode at even width and height", + )); + } + if cfg.width > 8192 || cfg.height > 8192 { + return Err(Error::unsupported( + "picture larger than 8192 samples", + "no level defines a picture this large for this profile", + )); + } + let mb_w = cfg.width.div_ceil(16); + let mb_h = cfg.height.div_ceil(16); + let fps = f64::from(cfg.framerate.max(1.0)); + // A rational tick close to the requested rate; time_scale is twice the + // frame rate for progressive frames (E.2.1). + let timing = rational_timing(fps); + let seq = SeqParams { + width: cfg.width, + height: cfg.height, + mb_w, + mb_h, + timing, + bitrate: cfg.bitrate, + }; + let sps_rbsp = write_sps(&seq); + let sps = Sps::parse(&sps_rbsp)?; + let pps_rbsp = write_pps(); + let threads = if cfg.threads == 0 { + std::thread::available_parallelism().map_or(1, |n| n.get()) + } else { + cfg.threads + } + .clamp(1, mb_h as usize); + let workers = (0..threads).map(|_| Picture::default()).collect(); + let fixed_qp = (cfg.bitrate == 0).then_some(cfg.qp.clamp(0, 51)); + Ok(Encoder { + sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp), + pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp), + sps, + reference: Picture::default(), + workers, + src: Source { + y: Vec::new(), + u: Vec::new(), + v: Vec::new(), + stride: mb_w as usize * 16, + c_stride: mb_w as usize * 8, + }, + rc: RateControl::new(cfg.bitrate, fps, cfg.gop_size, fixed_qp), + threads, + coded_width: mb_w as usize * 16, + coded_height: mb_h as usize * 16, + frames: 0, + frame_num: 0, + idr_pic_id: 0, + next_id: 0, + have_reference: false, + cfg, + }) + } + + /// The configuration in force. + pub fn config(&self) -> &EncoderConfig { + &self.cfg + } + + /// The reconstruction of the last coded picture, cropped, as I420 planes. + /// This is what a conformant decoder produces for that picture — the tests + /// compare it against this crate's decoder and against ffmpeg. + pub fn reconstruction(&self) -> Option<(Vec, Vec, Vec)> { + if !self.have_reference { + return None; + } + let pic = &self.reference; + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); + let mut y = Vec::with_capacity(w * h); + for row in 0..h { + let o = pic.y.at(0, row); + y.extend_from_slice(&pic.y.data[o..o + w]); + } + let (cw, ch) = (w / 2, h / 2); + let mut planes = [Vec::with_capacity(cw * ch), Vec::with_capacity(cw * ch)]; + for (comp, out) in planes.iter_mut().enumerate() { + let plane = if comp == 0 { &pic.cb } else { &pic.cr }; + for row in 0..ch { + let o = plane.at(0, row); + out.extend_from_slice(&plane.data[o..o + cw]); + } + } + let [u, v] = planes; + Some((y, u, v)) + } + + /// Code one picture, in display order, and hand back its access unit. + pub fn encode(&mut self, frame: &PictureView<'_>) -> Result { + if frame.width != self.cfg.width || frame.height != self.cfg.height { + return Err(Error::corrupt("frame size differs from the encoder's")); + } + self.pad_source(frame)?; + let idr = self.cfg.gop_size <= 1 + || self + .frames + .is_multiple_of(u64::from(self.cfg.gop_size.max(1))); + let idr = idr || !self.have_reference; + let qp = self.rc.frame_qp(idr); + if idr { + self.frame_num = 0; + } + let slice_type = if idr { SliceType::I } else { SliceType::P }; + + let mb_w = self.sps.mb_width as usize; + let mb_h = self.sps.mb_height as usize; + let bands = split_bands(mb_h, self.threads); + let picture_id = self.next_id; + self.next_id = self.next_id.wrapping_add(1); + + // Per-band coding. Every worker owns its picture and its bitstream; + // the only shared state is the immutable reference picture and source. + let sps = &self.sps; + let src = &self.src; + let cfg = &self.cfg; + let rc = &self.rc; + let reference = (!idr).then_some(&self.reference); + let frame_num = self.frame_num; + let idr_pic_id = self.idr_pic_id; + let target = rc.frame_target(idr); + let total_mbs = (mb_w * mb_h) as f64; + + let mut outputs: Vec> = Vec::new(); + std::thread::scope(|scope| { + let mut handles = Vec::with_capacity(bands.len()); + for (slice_id, (&(row0, row1), worker)) in + bands.iter().zip(self.workers.iter_mut()).enumerate() + { + handles.push(scope.spawn(move || { + worker.start(sps); + worker.id = picture_id; + let band_mbs = ((row1 - row0) * mb_w) as f64; + code_band( + worker, + BandJob { + src, + reference, + cfg, + rc, + slice_id: slice_id as u16, + slice_type, + first_mb: (row0 * mb_w) as u32, + rows: (row0, row1), + qp, + frame_num, + idr, + idr_pic_id, + band_target: target * band_mbs / total_mbs, + }, + ) + })); + } + for h in handles { + outputs.push(h.join().expect("a band worker panicked")); + } + }); + + // Stitch the bands into worker 0's picture, then filter the whole + // picture the way a decoder does. + let (first, rest) = self.workers.split_at_mut(1); + let master = &mut first[0]; + master.slices.clear(); + for _ in 0..bands.len() { + master.slices.push(DeblockParams { + disable_deblock_idc: 0, + alpha_offset: 0, + beta_offset: 0, + cb_qp_offset: 0, + cr_qp_offset: 0, + }); + } + for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { + merge_band(master, worker, *band); + } + deblock_picture(master); + master.extend_borders(); + master.complete = true; + std::mem::swap(master, &mut self.reference); + self.have_reference = true; + + // Assemble the access unit. + let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::() + 64); + if idr { + au.extend_from_slice(&self.sps_nal); + au.extend_from_slice(&self.pps_nal); + } + let unit = if idr { + NalUnitType::SliceIdr + } else { + NalUnitType::Slice + }; + for rbsp in &outputs { + au.extend_from_slice(&annex_b(unit, 3, rbsp)); + } + + let bits = au.len() as u64 * 8; + self.rc.update(idr, qp, bits); + self.frames += 1; + self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM); + if idr { + self.idr_pic_id ^= 1; + } + Ok(EncodedPicture { + au, + key_frame: idr, + qp, + }) + } + + /// Copy the caller's planes into whole-macroblock buffers, replicating the + /// edge where the picture does not fill the last macroblock. + fn pad_source(&mut self, f: &PictureView<'_>) -> Result<()> { + let (w, h) = (f.width as usize, f.height as usize); + let (cw, ch) = (w / 2, h / 2); + let y_stride = if f.y_stride == 0 { w } else { f.y_stride }; + let c_stride = if f.c_stride == 0 { cw } else { f.c_stride }; + if f.y.len() < y_stride * (h - 1) + w + || f.u.len() < c_stride * (ch - 1) + cw + || f.v.len() < c_stride * (ch - 1) + cw + { + return Err(Error::corrupt("source plane shorter than its stated size")); + } + pad_plane( + &mut self.src.y, + f.y, + y_stride, + w, + h, + self.coded_width, + self.coded_height, + ); + pad_plane( + &mut self.src.u, + f.u, + c_stride, + cw, + ch, + self.coded_width / 2, + self.coded_height / 2, + ); + pad_plane( + &mut self.src.v, + f.v, + c_stride, + cw, + ch, + self.coded_width / 2, + self.coded_height / 2, + ); + self.src.stride = self.coded_width; + self.src.c_stride = self.coded_width / 2; + Ok(()) + } +} + +/// Everything one band worker needs. +struct BandJob<'a> { + src: &'a Source, + reference: Option<&'a Picture>, + cfg: &'a EncoderConfig, + rc: &'a RateControl, + slice_id: u16, + slice_type: SliceType, + first_mb: u32, + /// Macroblock rows `[start, end)`. + rows: (usize, usize), + qp: i32, + frame_num: u32, + idr: bool, + idr_pic_id: u32, + band_target: f64, +} + +/// Code one slice into its own RBSP. +fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { + let mb_w = pic.mb_w; + let mut w = BitWriter::with_capacity(4096); + write_slice_header( + &mut w, + &SliceParams { + first_mb: job.first_mb, + slice_type: job.slice_type, + frame_num: job.frame_num, + idr: job.idr, + idr_pic_id: job.idr_pic_id, + qp: job.qp, + }, + ); + let header_bits = w.bit_len(); + let mut e = MbEnc { + src: job.src, + reference: job.reference, + slice_type: job.slice_type, + slice_id: job.slice_id, + qp: job.qp, + target_qp: job.qp, + lambda: lambda_for(job.qp), + preset: job.cfg.preset, + skip_run: 0, + ls: LevelScale4x4::new(&[16; 16]), + }; + let rows = job.rows.1 - job.rows.0; + for (n, mb_y) in (job.rows.0..job.rows.1).enumerate() { + // Row-level rate control: what this band has spent against its + // pro-rata budget. + if n > 0 { + let spent = w.bit_len() - header_bits; + let expected = job.band_target * n as f64 / rows as f64; + let delta = job.rc.row_delta(spent, expected); + e.target_qp = (job.qp + delta).clamp(10, 51); + e.lambda = lambda_for(e.target_qp); + } + for mb_x in 0..mb_w { + encode_mb(pic, &mut e, &mut w, mb_y * mb_w + mb_x); + } + } + if job.slice_type == SliceType::P && e.skip_run > 0 { + // A slice that ends in skipped macroblocks says so with a final + // mb_skip_run; writing one when nothing was skipped would instead tell + // the decoder another macroblock follows (7.3.4). + w.write_ue(e.skip_run); + } + headers::trailing(&mut w); + w.into_bytes() +} + +/// Lagrangian multiplier for mode decision in the SATD domain. +fn lambda_for(qp: i32) -> i32 { + // 2^((qp - 12) / 6), the usual ladder, floored at 1. + (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1) +} + +/// Split `mb_h` macroblock rows into at most `n` contiguous bands. +fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { + let n = n.clamp(1, mb_h); + let mut out = Vec::with_capacity(n); + let mut row = 0; + for i in 0..n { + let end = (i + 1) * mb_h / n; + out.push((row, end)); + row = end; + } + out +} + +/// Copy one band's samples and macroblock metadata from a worker picture into +/// the picture the deblocking filter will run over. +fn merge_band(dst: &mut Picture, src: &Picture, (row0, row1): (usize, usize)) { + let mb_w = dst.mb_w; + // Planes. + for (d, s, mb_size) in [ + (&mut dst.y, &src.y, 16usize), + (&mut dst.cb, &src.cb, 8), + (&mut dst.cr, &src.cr, 8), + ] { + let stride = d.stride; + let start = d.at(0, row0 * mb_size); + let rows = (row1 - row0) * mb_size; + let width = d.width; + for r in 0..rows { + let o = start + r * stride; + d.data[o..o + width].copy_from_slice(&s.data[o..o + width]); + } + } + // Per-macroblock arrays. + let mb_range = row0 * mb_w..row1 * mb_w; + dst.mb_qp[mb_range.clone()].copy_from_slice(&src.mb_qp[mb_range.clone()]); + dst.mb_flags[mb_range.clone()].copy_from_slice(&src.mb_flags[mb_range.clone()]); + dst.mb_cbp[mb_range.clone()].copy_from_slice(&src.mb_cbp[mb_range.clone()]); + dst.mb_dc_cbf[mb_range.clone()].copy_from_slice(&src.mb_dc_cbf[mb_range.clone()]); + dst.mb_slice[mb_range.clone()].copy_from_slice(&src.mb_slice[mb_range]); + // Per-4x4-block arrays. + let b = row0 * 4 * mb_w * 4..row1 * 4 * mb_w * 4; + dst.nz_y[b.clone()].copy_from_slice(&src.nz_y[b.clone()]); + dst.i4_modes[b.clone()].copy_from_slice(&src.i4_modes[b.clone()]); + dst.mv[b.clone()].copy_from_slice(&src.mv[b.clone()]); + dst.ref_idx[b.clone()].copy_from_slice(&src.ref_idx[b.clone()]); + dst.ref_id[b.clone()].copy_from_slice(&src.ref_id[b.clone()]); + dst.mvd_abs[b.clone()].copy_from_slice(&src.mvd_abs[b.clone()]); + dst.blk[b.clone()].copy_from_slice(&src.blk[b]); + // Per-chroma-block arrays. + let c = row0 * 2 * mb_w * 2..row1 * 2 * mb_w * 2; + for comp in 0..2 { + let (d, s) = (&mut dst.nz_c[comp], &src.nz_c[comp]); + d[c.clone()].copy_from_slice(&s[c.clone()]); + } + dst.decoded_mbs += (row1 - row0) * mb_w; +} + +/// Copy `src` into a `out_w` x `out_h` buffer, replicating the right and +/// bottom edges into the padding. +fn pad_plane( + out: &mut Vec, + src: &[u8], + stride: usize, + w: usize, + h: usize, + out_w: usize, + out_h: usize, +) { + out.clear(); + out.resize(out_w * out_h, 0); + for row in 0..out_h { + let sr = row.min(h - 1); + let line = &src[sr * stride..sr * stride + w]; + let dst = &mut out[row * out_w..row * out_w + out_w]; + dst[..w].copy_from_slice(line); + if out_w > w { + let edge = line[w - 1]; + dst[w..].fill(edge); + } + } +} + +/// Wrap an RBSP as one Annex-B NAL unit with a 4-byte start code. +fn annex_b(unit: NalUnitType, ref_idc: u8, rbsp: &[u8]) -> Vec { + let mut out = Vec::with_capacity(rbsp.len() + 8); + out.extend_from_slice(&[0, 0, 0, 1]); + out.push((ref_idc << 5) | unit_code(unit)); + escape_rbsp(rbsp, &mut out); + out +} + +/// `nal_unit_type` of the units this encoder emits. +fn unit_code(unit: NalUnitType) -> u8 { + match unit { + NalUnitType::Slice => 1, + NalUnitType::SliceIdr => 5, + NalUnitType::Sps => 7, + NalUnitType::Pps => 8, + _ => 0, + } +} + +/// A `(num_units_in_tick, time_scale)` pair for a frame rate, exact for the +/// broadcast rates (23.976, 29.97, 59.94) and within a part in 10^5 otherwise. +fn rational_timing(fps: f64) -> (u32, u32) { + for (num, den) in [ + (24000u32, 1001u32), + (30000, 1001), + (60000, 1001), + (120000, 1001), + ] { + if (fps - f64::from(num) / f64::from(den)).abs() < 1e-3 { + return (den, num * 2); + } + } + let scaled = (fps * 1000.0).round().max(1.0); + (1000, (scaled * 2.0).min(f64::from(u32::MAX)) as u32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bands_cover_every_row_once() { + for mb_h in [1usize, 5, 68, 135] { + for threads in [1usize, 3, 12, 200] { + let bands = split_bands(mb_h, threads); + assert!(!bands.is_empty()); + assert_eq!(bands[0].0, 0); + assert_eq!(bands.last().unwrap().1, mb_h); + for pair in bands.windows(2) { + assert_eq!(pair[0].1, pair[1].0); + } + assert!(bands.iter().all(|&(a, b)| a < b), "empty band: {bands:?}"); + } + } + } + + #[test] + fn timing_is_exact_for_broadcast_rates() { + assert_eq!(rational_timing(24000.0 / 1001.0), (1001, 48000)); + assert_eq!(rational_timing(30000.0 / 1001.0), (1001, 60000)); + assert_eq!(rational_timing(25.0), (1000, 50000)); + } + + /// Odd dimensions are refused by name rather than coded wrong. + #[test] + fn odd_dimensions_are_refused() { + let Err(err) = Encoder::new(EncoderConfig::new(641, 480)) else { + panic!("an odd width must be refused"); + }; + assert!(matches!(err, Error::Unsupported { .. }), "{err}"); + assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok()); + } +} diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs new file mode 100644 index 00000000..483d405b --- /dev/null +++ b/crates/ec-h264/src/enc/quant.rs @@ -0,0 +1,258 @@ +//! Forward transforms and quantisation. +//! +//! Nothing here is normative: the standard specifies only the *inverse* +//! transforms, which the decoder side of this crate already implements +//! ([`crate::transform`]). The forward direction is chosen so that the +//! round trip through the normative inverse lands back on the source, and +//! that is what the tests at the bottom check across the whole QP range. +//! +//! The multiplier table pairs with `normAdjust4x4` (Table 8-15 through the +//! `LevelScale` of Equation 8-313): `MF[m][class] * normAdjust4x4[m][class] * +//! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)` +//! invert the decoder's dequantisation. + +use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; + +/// Quantisation multipliers per `qp % 6`, indexed by the same position class +/// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed). +const MF: [[i32; 3]; 6] = [ + [13107, 5243, 8066], + [11916, 4660, 7490], + [10082, 4194, 6554], + [9362, 3647, 5825], + [8192, 3355, 5243], + [7282, 2893, 4559], +]; + +/// Rounding offset numerator: an intra block rounds at 1/3 of a step, an inter +/// block at 1/6 — the classic asymmetry, which spends bits where prediction is +/// weakest. Measured against 1/3 and 1/2 for the inter case on 1080p camera +/// and screen-capture clips: 1/6 is level or ahead at matched bitrate. +#[inline] +fn round_offset(qbits: u32, intra: bool) -> i32 { + (1i32 << qbits) / if intra { 3 } else { 6 } +} + +/// Forward 4x4 core transform (the inverse of spec 8.5.12.2), raster in and +/// out, integer and exact. +pub(crate) fn forward_4x4(d: &mut [i32; 16]) { + for i in 0..4 { + let o = i * 4; + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); + let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e); + d[o] = s0 + s1; + d[o + 1] = 2 * s3 + s2; + d[o + 2] = s0 - s1; + d[o + 3] = s3 - 2 * s2; + } + for j in 0..4 { + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); + let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e); + d[j] = s0 + s1; + d[4 + j] = 2 * s3 + s2; + d[8 + j] = s0 - s1; + d[12 + j] = s3 - 2 * s2; + } +} + +/// Forward 4x4 Hadamard over the sixteen luma DC coefficients of an +/// Intra_16x16 macroblock (the inverse of spec 8.5.10), raster in and out. +pub(crate) fn forward_hadamard_4x4(d: &mut [i32; 16]) { + for i in 0..4 { + let o = i * 4; + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); + d[o] = a + b + c + e; + d[o + 1] = a + b - c - e; + d[o + 2] = a - b - c + e; + d[o + 3] = a - b + c - e; + } + for j in 0..4 { + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); + d[j] = a + b + c + e; + d[4 + j] = a + b - c - e; + d[8 + j] = a - b - c + e; + d[12 + j] = a - b + c - e; + } +} + +/// Forward 2x2 Hadamard over the four chroma DC coefficients (the inverse of +/// spec 8.5.11). +pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) { + let (a, b, c, e) = (d[0], d[1], d[2], d[3]); + d[0] = a + b + c + e; + d[1] = a - b + c - e; + d[2] = a + b - c - e; + d[3] = a - b - c + e; +} + +/// Quantise a transformed 4x4 block into scan (zig-zag) order. +/// +/// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into +/// `out[0..15]`, which is the layout the AC residual blocks of Intra_16x16 and +/// chroma use. Returns the number of non-zero levels. +pub(crate) fn quant_4x4( + coef: &[i32; 16], + qp: i32, + intra: bool, + skip_dc: bool, + out: &mut [i32; 16], +) -> u8 { + let m = (qp % 6) as usize; + let qbits = 15 + (qp / 6) as u32; + let f = round_offset(qbits, intra); + let start = usize::from(skip_dc); + let mut nz = 0; + *out = [0; 16]; + for k in start..16 { + let raster = ZIGZAG_4X4[k] as usize; + let c = coef[raster]; + let mf = MF[m][NORM_ADJUST_CLASS_4X4[raster] as usize]; + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; + if level != 0 { + nz += 1; + } + out[k - start] = if c < 0 { -level } else { level }; + } + nz +} + +/// Quantise the sixteen Hadamard-transformed luma DC coefficients into scan +/// order. Two extra bits of shift pay for the gain of the forward Hadamard, +/// which the decoder's inverse (8.5.10, a `>> 6` where the AC path shifts by +/// four) takes back out. +pub(crate) fn quant_luma_dc(coef: &[i32; 16], qp: i32, out: &mut [i32; 16]) -> u8 { + let qbits = 17 + (qp / 6) as u32; + let mf = MF[(qp % 6) as usize][0]; + let f = round_offset(qbits, true); + let mut nz = 0; + *out = [0; 16]; + for k in 0..16 { + let c = coef[ZIGZAG_4X4[k] as usize]; + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; + if level != 0 { + nz += 1; + } + out[k] = if c < 0 { -level } else { level }; + } + nz +} + +/// Quantise the four Hadamard-transformed chroma DC coefficients (raster +/// order, which is also their scan order). +pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [i32; 16]) -> u8 { + let qbits = 16 + (qp / 6) as u32; + let mf = MF[(qp % 6) as usize][0]; + let f = round_offset(qbits, intra); + let mut nz = 0; + *out = [0; 16]; + for k in 0..4 { + let c = coef[k]; + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; + if level != 0 { + nz += 1; + } + out[k] = if c < 0 { -level } else { level }; + } + nz +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::transform::{ + LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, + luma_dc_transform, unzigzag, + }; + + fn ls() -> LevelScale4x4 { + LevelScale4x4::new(&[16; 16]) + } + + /// A residual quantised at QP and put back through the *normative* inverse + /// comes back within the quantiser step, at every QP: this is the property + /// that makes the forward direction a valid inverse of clause 8.5, and a + /// wrong multiplier or shift breaks it by orders of magnitude. + #[test] + fn ac_round_trip_within_a_quantiser_step() { + let ls = ls(); + for qp in 0..52 { + let mut worst = 0i32; + for seed in 0..8u32 { + let src: [i32; 16] = std::array::from_fn(|i| { + let v = (seed.wrapping_mul(2654435761).wrapping_add(i as u32 * 40503)) >> 24; + (v as i32 % 61) - 30 + }); + let mut coef = src; + forward_4x4(&mut coef); + let mut scan = [0i32; 16]; + quant_4x4(&coef, qp, true, false, &mut scan); + let mut raster = [0i32; 16]; + unzigzag(&scan, &mut raster); + dequant_4x4(&mut raster, &ls, qp, false); + let mut out = [0i32; 16]; + inverse_transform_4x4(&raster, &mut out); + for i in 0..16 { + worst = worst.max((out[i] - src[i]).abs()); + } + } + // The reconstruction error of a dead-zone quantiser is bounded by + // one step, which doubles every six QP. + let step = 1 << (qp / 6); + assert!( + worst <= 2 + 2 * step, + "qp {qp}: worst error {worst} over step {step}" + ); + } + } + + /// The same for the Intra_16x16 luma DC path: a flat residual across the + /// whole macroblock survives Hadamard, quantisation and the decoder's + /// 8.5.10 inverse. + #[test] + fn luma_dc_round_trip() { + let ls = ls(); + for qp in 0..52 { + for &x in &[-40i32, -7, 3, 25] { + // Every 4x4 block of a flat macroblock has DC = 16 * x. + let dc: [i32; 16] = [16 * x; 16]; + let mut had = dc; + forward_hadamard_4x4(&mut had); + let mut scan = [0i32; 16]; + quant_luma_dc(&had, qp, &mut scan); + let mut raster = [0i32; 16]; + unzigzag(&scan, &mut raster); + luma_dc_transform(&mut raster, &ls, qp); + // Each block reconstructs (dc + 32) >> 6 flat samples. + let recon = (raster[0] + 32) >> 6; + let step = 1 << (qp / 6); + assert!( + (recon - x).abs() <= 2 + 2 * step, + "qp {qp} x {x}: recon {recon}" + ); + } + } + } + + /// And the chroma DC path (2x2 Hadamard, 8.5.11). + #[test] + fn chroma_dc_round_trip() { + let ls = ls(); + for qp in 0..40 { + for &x in &[-30i32, -4, 9, 21] { + let dc: [i32; 4] = [16 * x; 4]; + let mut had = dc; + forward_hadamard_2x2(&mut had); + let mut scan = [0i32; 16]; + quant_chroma_dc(&had, qp, true, &mut scan); + let mut c: [i32; 4] = [scan[0], scan[1], scan[2], scan[3]]; + chroma_dc_transform_420(&mut c, &ls, qp); + let recon = (c[0] + 32) >> 6; + let step = 1 << (qp / 6); + assert!( + (recon - x).abs() <= 2 + 2 * step, + "qp {qp} x {x}: recon {recon}" + ); + } + } + } +} diff --git a/crates/ec-h264/src/enc/rc.rs b/crates/ec-h264/src/enc/rc.rs new file mode 100644 index 00000000..b0e247ab --- /dev/null +++ b/crates/ec-h264/src/enc/rc.rs @@ -0,0 +1,172 @@ +//! Rate control: one QP per picture from a bit model, refined per macroblock +//! row inside each slice. +//! +//! The model is the classic one: at a fixed complexity a picture's size scales +//! as `2^(-QP/6)`, so `complexity = bits * 2^(QP/6)` measured on the last +//! picture of the same type predicts the QP that hits the next target. A +//! leaky-bucket term pulls the stream back when the model is wrong, which is +//! what makes the average bitrate hold over a clip rather than per picture. + +/// Constant-quantiser mode is a bitrate of zero: nothing to control. +#[derive(Debug, Clone)] +pub(crate) struct RateControl { + /// Bits per picture at the configured bitrate and frame rate. + base: f64, + /// Virtual buffer occupancy in bits, positive when the stream is ahead of + /// its budget. + buffer: f64, + /// `bits * 2^(qp / 6)` of the last coded picture, per type (0 = I, 1 = P). + complexity: [f64; 2], + /// The QP the last picture of each type was coded at. + last_qp: [f64; 2], + /// Extra share of the group of pictures an IDR is allowed to borrow, as a + /// multiple of one picture's budget. + i_share: f64, + /// Pictures per group, over which that share is repaid. + gop: f64, + fixed: Option, +} + +impl RateControl { + pub(crate) fn new(bitrate: u32, fps: f64, gop: u32, fixed_qp: Option) -> RateControl { + let base = if bitrate == 0 || fps <= 0.0 { + 0.0 + } else { + f64::from(bitrate) / fps + }; + // An intra picture costs many times a predicted one and every picture + // of the group predicts from it, so it borrows a slice of each of them + // — without this the bucket saturates on the IDR alone and the next + // half second is coded at a quantiser nothing justifies. + let i_share = (0.15 * f64::from(gop.saturating_sub(1))).clamp(0.0, 8.0); + RateControl { + base, + i_share, + gop: f64::from(gop.max(1)), + buffer: 0.0, + complexity: [0.0; 2], + last_qp: [26.0; 2], + fixed: fixed_qp.or(if base == 0.0 { Some(26) } else { None }), + } + } + + /// QP for the next picture. + pub(crate) fn frame_qp(&self, idr: bool) -> i32 { + if let Some(qp) = self.fixed { + return qp; + } + let kind = usize::from(!idr); + let target = self.frame_target(idr); + let mut qp = if self.complexity[kind] > 0.0 { + 6.0 * (self.complexity[kind] / target).log2() + } else if idr { + self.last_qp[1] + } else { + // First P picture: start from the I picture's quantiser. + self.last_qp[0] + 2.0 + }; + // Never move far in one step; a jumpy quantiser looks worse than a + // slightly wrong one. + // Asymmetric: a picture that costs less than its budget should reach + // the quantiser it can afford quickly (on static content that is where + // all the quality comes from), while a picture that overspends is + // pulled back gently, because a visible quantiser jump costs more than + // a few frames of debt. + let (down, up) = if idr { (6.0, 6.0) } else { (4.0, 2.0) }; + qp = qp.clamp(self.last_qp[kind] - down, self.last_qp[kind] + up); + // Leaky bucket: 1.5 QP per picture of debt, capped. + qp += (self.buffer / (self.base.max(1.0) * 4.0) * 2.0).clamp(-2.0, 2.0); + qp.round().clamp(10.0, 51.0) as i32 + } + + /// Record what the picture actually cost. + pub(crate) fn update(&mut self, idr: bool, qp: i32, bits: u64) { + if self.fixed.is_some() { + return; + } + let kind = usize::from(!idr); + let bits = bits as f64; + let c = bits * (f64::from(qp) / 6.0).exp2(); + self.complexity[kind] = if self.complexity[kind] == 0.0 { + c + } else { + // Smoothed: one anomalous picture must not whipsaw the next. + 0.7 * self.complexity[kind] + 0.3 * c + }; + self.last_qp[kind] = f64::from(qp); + // The budget a picture of this type was given, not the flat average: + // an IDR that lands on its (large) target must not push the bucket. + let target = self.frame_target(idr); + self.buffer = (self.buffer + bits - target).clamp(-4.0 * self.base, 8.0 * self.base); + } + + /// Per-macroblock-row correction inside a slice: `spent` and `expected` are + /// bits so far and the pro-rata budget. + /// + /// This is the *fast* loop, and it has to be: on content whose bit cost + /// falls off a cliff with the quantiser — a screen capture, where dropping + /// one QP step re-codes half the picture — the picture-level model can + /// mispredict by an order of magnitude, and only a correction inside the + /// picture keeps that from blowing the budget and whipsawing the next + /// second of video. Asymmetric on purpose: overspending is capped hard, + /// underspending is given back gently. + pub(crate) fn row_delta(&self, spent: u64, expected: f64) -> i32 { + if self.fixed.is_some() || expected <= 0.0 { + return 0; + } + let ratio = (spent as f64 / expected).max(1e-3); + let delta = 6.0 * ratio.log2(); + delta.round().clamp(-2.0, 6.0) as i32 + } + + /// Bits the picture is aiming for, for the per-row budget. + pub(crate) fn frame_target(&self, idr: bool) -> f64 { + if idr { + self.base * (1.0 + self.i_share) + } else { + // What each predicted picture of the group gives back to the IDR, + // so that the group as a whole still costs `gop * base`. + self.base * (1.0 - self.i_share / (self.gop - 1.0).max(1.0)).max(0.3) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A constant-bitrate run converges: fed pictures that always cost what the + /// model says, the quantiser settles and the buffer does not run away. + #[test] + fn converges_to_the_target() { + let mut rc = RateControl::new(4_000_000, 25.0, 25, None); + // A synthetic source whose complexity is fixed. + let complexity = 8.0e6; + let mut qps = Vec::new(); + for f in 0..60 { + let idr = f == 0; + let qp = rc.frame_qp(idr); + let bits = (complexity * (-f64::from(qp) / 6.0).exp2()) as u64; + rc.update(idr, qp, bits); + qps.push(qp); + } + let tail = &qps[40..]; + let spread = tail.iter().max().unwrap() - tail.iter().min().unwrap(); + assert!(spread <= 2, "quantiser still hunting: {tail:?}"); + assert!( + rc.buffer.abs() < 2.0 * rc.base, + "buffer ran away: {}", + rc.buffer + ); + } + + /// A bitrate of zero is constant-QP mode, and nothing moves it. + #[test] + fn zero_bitrate_is_constant_qp() { + let mut rc = RateControl::new(0, 25.0, 25, Some(31)); + assert_eq!(rc.frame_qp(true), 31); + rc.update(true, 31, 10_000_000); + assert_eq!(rc.frame_qp(false), 31); + assert_eq!(rc.row_delta(1_000_000, 1.0), 0); + } +} diff --git a/crates/ec-h264/src/enc/vlc.rs b/crates/ec-h264/src/enc/vlc.rs new file mode 100644 index 00000000..dfaa780c --- /dev/null +++ b/crates/ec-h264/src/enc/vlc.rs @@ -0,0 +1,323 @@ +//! CAVLC writing (spec 9.2): the exact inverse of [`crate::cavlc`]. +//! +//! Every code table here is *derived at compile time from the decoder's own +//! tables* — the reverse maps below are `const fn` walks of +//! [`crate::tables`], so an encoder code and the decoder code it must match +//! cannot drift apart. The round-trip test at the bottom re-decodes what this +//! module writes with [`crate::cavlc::residual_block`]. + +use ec_core::BitWriter; + +use crate::tables::{ + CBP_INTER_420, CBP_INTRA_420, COEFF_TOKEN_CHROMA_DC, COEFF_TOKEN_NC0, COEFF_TOKEN_NC2, + COEFF_TOKEN_NC4, CoeffTokenEntry, RUN_BEFORE, TOTAL_ZEROS_4X4, TOTAL_ZEROS_CHROMA_DC, VlcEntry, +}; + +/// `(length, code)` of one VLC codeword; length 0 marks a combination the +/// table does not contain. +type Code = (u8, u16); + +/// Reverse `coeff_token` table: `[total_coeff][trailing_ones]`. +type CoeffTokenRev = [[Code; 4]; 17]; + +const fn rev_coeff_token(t: &[CoeffTokenEntry]) -> CoeffTokenRev { + let mut out = [[(0u8, 0u16); 4]; 17]; + let mut i = 0; + while i < t.len() { + let (len, code, tc, t1) = t[i]; + out[tc as usize][t1 as usize] = (len, code); + i += 1; + } + out +} + +const fn rev_vlc(t: &[VlcEntry]) -> [Code; N] { + let mut out = [(0u8, 0u16); N]; + let mut i = 0; + while i < t.len() { + let (len, code, value) = t[i]; + out[value as usize] = (len, code); + i += 1; + } + out +} + +const fn rev_vlc_table(t: &[&[VlcEntry]; R]) -> [[Code; N]; R] { + let mut out = [[(0u8, 0u16); N]; R]; + let mut i = 0; + while i < R { + out[i] = rev_vlc::(t[i]); + i += 1; + } + out +} + +static COEFF_TOKEN: [CoeffTokenRev; 3] = [ + rev_coeff_token(COEFF_TOKEN_NC0), + rev_coeff_token(COEFF_TOKEN_NC2), + rev_coeff_token(COEFF_TOKEN_NC4), +]; +static COEFF_TOKEN_CDC: CoeffTokenRev = rev_coeff_token(COEFF_TOKEN_CHROMA_DC); +static TOTAL_ZEROS: [[Code; 16]; 15] = rev_vlc_table(&TOTAL_ZEROS_4X4); +static TOTAL_ZEROS_CDC: [[Code; 4]; 3] = rev_vlc_table(&TOTAL_ZEROS_CHROMA_DC); +static RUNS: [[Code; 15]; 7] = rev_vlc_table(&RUN_BEFORE); + +#[inline] +fn write_code(w: &mut BitWriter, c: Code) { + debug_assert!(c.0 > 0, "VLC combination absent from the table"); + w.write_bits(u32::from(c.1), u32::from(c.0)); +} + +/// `coeff_token` (9.2.1). `nc` is the neighbour count, -1 for 4:2:0 chroma DC. +fn write_coeff_token(w: &mut BitWriter, nc: i32, total_coeff: u8, trailing_ones: u8) { + if nc == -1 { + write_code( + w, + COEFF_TOKEN_CDC[total_coeff as usize][trailing_ones as usize], + ); + return; + } + if nc >= 8 { + // Fixed-length 6-bit form. + let v = if total_coeff == 0 { + 3 + } else { + u32::from(total_coeff - 1) * 4 + u32::from(trailing_ones) + }; + w.write_bits(v, 6); + return; + } + let table = match nc { + 0..=1 => 0, + 2..=3 => 1, + _ => 2, + }; + write_code( + w, + COEFF_TOKEN[table][total_coeff as usize][trailing_ones as usize], + ); +} + +/// Base value and suffix width of one `level_prefix` under `suffix_length`, +/// read straight off the decoder's reconstruction in [`crate::cavlc`]. +#[inline] +fn level_range(prefix: u32, suffix_length: u32) -> (i64, u32) { + if prefix >= 15 { + let mut base = (15i64 << suffix_length) + if suffix_length == 0 { 15 } else { 0 }; + if prefix >= 16 { + base += (1i64 << (prefix - 3)) - 4096; + } + (base, prefix - 3) + } else if prefix == 14 && suffix_length == 0 { + (14, 4) + } else { + ((i64::from(prefix)) << suffix_length, suffix_length) + } +} + +/// `level_prefix` + `level_suffix` (9.2.2.1) for one `levelCode`, choosing the +/// shortest prefix whose range contains it. +fn write_level_code(w: &mut BitWriter, level_code: i64, suffix_length: u32) { + for prefix in 0..=25u32 { + let (base, size) = level_range(prefix, suffix_length); + if level_code >= base && level_code < base + (1i64 << size) { + w.write_bits64(0, prefix); + w.write_bit(true); + if size > 0 { + w.write_bits64((level_code - base) as u64, size); + } + return; + } + } + debug_assert!(false, "level {level_code} outside every level_prefix range"); +} + +/// Write one CAVLC residual block (9.2) from `coeff[0..max_num_coeff]` in scan +/// order. Returns TotalCoeff, which the caller records as the block's non-zero +/// count for its neighbours. +pub(crate) fn write_residual_block( + w: &mut BitWriter, + coeff: &[i32], + max_num_coeff: usize, + nc: i32, +) -> u8 { + debug_assert!(max_num_coeff <= 16); + // Scan positions of the non-zero levels, lowest frequency first. + let mut pos = [0usize; 16]; + let mut total_coeff = 0usize; + for (k, &c) in coeff.iter().take(max_num_coeff).enumerate() { + if c != 0 { + pos[total_coeff] = k; + total_coeff += 1; + } + } + if total_coeff == 0 { + write_coeff_token(w, nc, 0, 0); + return 0; + } + // Trailing ones: up to three +-1 levels at the high-frequency end. + let mut trailing_ones = 0usize; + while trailing_ones < 3 + && trailing_ones < total_coeff + && coeff[pos[total_coeff - 1 - trailing_ones]].abs() == 1 + { + trailing_ones += 1; + } + write_coeff_token(w, nc, total_coeff as u8, trailing_ones as u8); + + // 9.2.2: levels, highest frequency first. + for i in 0..trailing_ones { + w.write_bit(coeff[pos[total_coeff - 1 - i]] < 0); + } + let mut suffix_length = u32::from(total_coeff > 10 && trailing_ones < 3); + for i in trailing_ones..total_coeff { + let level = i64::from(coeff[pos[total_coeff - 1 - i]]); + let mut level_code = if level > 0 { + 2 * level - 2 + } else { + -2 * level - 1 + }; + if i == trailing_ones && trailing_ones < 3 { + level_code -= 2; + } + write_level_code(w, level_code, suffix_length); + if suffix_length == 0 { + suffix_length = 1; + } + if level.unsigned_abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { + suffix_length += 1; + } + } + + // 9.2.3 / 9.2.4: total_zeros then the runs, highest frequency first. + let total_zeros = pos[total_coeff - 1] + 1 - total_coeff; + if total_coeff < max_num_coeff { + if nc == -1 { + write_code(w, TOTAL_ZEROS_CDC[total_coeff - 1][total_zeros]); + } else { + write_code(w, TOTAL_ZEROS[total_coeff - 1][total_zeros]); + } + } + let mut zeros_left = total_zeros; + for i in 0..total_coeff - 1 { + if zeros_left == 0 { + break; + } + let k = total_coeff - 1 - i; + let run = pos[k] - pos[k - 1] - 1; + write_code(w, RUNS[zeros_left.min(7) - 1][run]); + zeros_left -= run; + } + total_coeff as u8 +} + +/// `coded_block_pattern` as me(v) (9.1.2, Table 9-4). +pub(crate) fn write_cbp(w: &mut BitWriter, cbp_luma: u8, cbp_chroma: u8, intra: bool) { + let cbp = cbp_luma | (cbp_chroma << 4); + let table: &[u8] = if intra { + &CBP_INTRA_420 + } else { + &CBP_INTER_420 + }; + let code = table + .iter() + .position(|&v| v == cbp) + .expect("every 4:2:0 coded_block_pattern has a code number"); + w.write_ue(code as u32); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bits::BitCursor; + use crate::cavlc::residual_block; + + fn round_trip(levels: &[i32], max_num_coeff: usize, nc: i32) { + let mut w = BitWriter::new(); + let tc = write_residual_block(&mut w, levels, max_num_coeff, nc); + // A stop bit keeps `more_rbsp_data` honest and gives the reader room. + w.write_bit(true); + w.align_to_byte(); + let bytes = w.into_bytes(); + let mut r = BitCursor::new(&bytes, 0); + let mut out = [0i32; 16]; + let got = residual_block(&mut r, &mut out, max_num_coeff, nc).expect("decodes"); + assert_eq!(got, tc, "TotalCoeff mismatch for {levels:?}"); + for (k, &want) in levels.iter().take(max_num_coeff).enumerate() { + assert_eq!(out[k], want, "position {k} of {levels:?}"); + } + } + + /// Every block this writer emits decodes back to the same levels, over a + /// spread that covers empty blocks, trailing ones, long runs, the + /// suffix-length ladder and the escape codes. + #[test] + fn residual_blocks_round_trip() { + let mut state = 0x1234_5678u32; + let mut rand = move |m: u32| { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + (state >> 16) % m + }; + for &(max, nc) in &[ + (16usize, 0i32), + (16, 2), + (16, 5), + (16, 9), + (15, 0), + (15, 3), + (4, -1), + ] { + for trial in 0..400 { + let mut levels = [0i32; 16]; + let density = 1 + rand(max as u32); + for level in levels.iter_mut().take(max) { + if rand(max as u32) < density { + // Magnitudes spread over the whole ladder including + // the 4096-wide escape. + let mag = match trial % 5 { + 0 => 1, + 1 => 1 + rand(3) as i32, + 2 => 1 + rand(40) as i32, + 3 => 1 + rand(600) as i32, + _ => 1 + rand(9000) as i32, + }; + *level = if rand(2) == 0 { mag } else { -mag }; + } + } + round_trip(&levels, max, nc); + } + } + } + + /// The all-zero block, the single-coefficient block and a fully populated + /// block are the boundary cases of 9.2.3 (no total_zeros is written when + /// TotalCoeff = maxNumCoeff). + #[test] + fn boundary_blocks_round_trip() { + round_trip(&[0; 16], 16, 0); + let mut one = [0i32; 16]; + one[15] = -1; + round_trip(&one, 16, 4); + round_trip(&[1; 16], 16, 0); + round_trip(&[-3; 16], 16, 8); + round_trip(&[2, 0, 0, -1], 4, -1); + } + + /// The coded_block_pattern code numbers invert the decoder's tables. + #[test] + fn cbp_codes_invert() { + for &(luma, chroma) in &[(0u8, 0u8), (15, 2), (3, 1), (5, 0), (15, 0)] { + for intra in [true, false] { + let mut w = BitWriter::new(); + write_cbp(&mut w, luma, chroma, intra); + w.write_bit(true); + w.align_to_byte(); + let bytes = w.into_bytes(); + let mut r = BitCursor::new(&bytes, 0); + let code = r.read_ue().unwrap() as usize; + let table = if intra { CBP_INTRA_420 } else { CBP_INTER_420 }; + assert_eq!(table[code], luma | (chroma << 4)); + } + } + } +} diff --git a/crates/ec-h264/src/inter.rs b/crates/ec-h264/src/inter.rs index 70eb480e..0cd1c9df 100644 --- a/crates/ec-h264/src/inter.rs +++ b/crates/ec-h264/src/inter.rs @@ -98,11 +98,22 @@ fn load8(data: &[u8], at: usize) -> i16x8 { i16x8::from(a) } -/// The 6-tap half-sample filter of Equations 8-241/8-242 over sixteen -/// neighbouring positions at once, the taps spaced `step` apart. +/// The same 6-tap filter over eight neighbouring positions. /// -/// The unrounded result of Equation 8-241 spans -2550..10710, so 16-bit lanes -/// hold it exactly and one row of a partition is one vector. +/// Eight lanes is one SSE2 register, which is the widest vector this crate can +/// assume without a target feature it is not allowed to require. A partition +/// narrower than sixteen samples therefore costs half or a quarter as much +/// here as it does in the sixteen-lane form, where the surplus lanes are +/// computed and then discarded. +#[inline] +fn tap6_8(data: &[u8], at: usize, step: usize) -> i16x8 { + let l = |k: isize| load8(data, (at as isize + k * step as isize) as usize); + let five = i16x8::splat(5); + let twenty = i16x8::splat(20); + l(-2) - five * l(-1) + twenty * l(0) + twenty * l(1) - five * l(2) + l(3) +} + +/// The same filter over sixteen positions, for a full-width partition. #[inline] fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 { let l = |k: isize| load16(data, (at as isize + k * step as isize) as usize); @@ -113,7 +124,18 @@ fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 { /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes. #[inline] -fn store_half(dst: &mut [u8], v: i16x16) { +fn store_half8(dst: &mut [u8], v: i16x8) { + let c = ((v + i16x8::splat(16)) >> 5u32) + .max(i16x8::ZERO) + .min(i16x8::splat(255)); + for (o, &s) in dst.iter_mut().zip(c.as_array()) { + *o = s as u8; + } +} + +/// The same over sixteen lanes. +#[inline] +fn store_half16(dst: &mut [u8], v: i16x16) { let c = ((v + i16x16::splat(16)) >> 5u32) .max(i16x16::ZERO) .min(i16x16::splat(255)); @@ -122,6 +144,40 @@ fn store_half(dst: &mut [u8], v: i16x16) { } } +/// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is +/// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the +/// horizontal filter, the plane stride for the vertical one. +/// +/// A partition is 16, 8 or 4 samples wide, so the narrow widths take a single +/// eight-lane vector rather than a sixteen-lane one whose upper half is +/// discarded. +#[inline] +fn half_block( + dst: &mut [u8], + data: &[u8], + base: usize, + stride: usize, + step: usize, + w: usize, + h: usize, +) { + if w == 16 { + for row in 0..h { + store_half16( + &mut dst[row * 16..row * 16 + 16], + tap6_16(data, base + row * stride, step), + ); + } + } else { + for row in 0..h { + store_half8( + &mut dst[row * w..row * w + w], + tap6_8(data, base + row * stride, step), + ); + } + } +} + /// Eight intermediate values as 32-bit lanes, zero past the end. #[inline] fn load_inter8(v: &[i16], at: usize) -> i32x8 { @@ -170,6 +226,33 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) { } } +/// The same average, written into a destination of pitch `os` from two +/// `w`-pitch sources. +#[inline] +fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize) { + if os == w { + avg_rows(out, a, b, w * h); + return; + } + for row in 0..h { + avg_rows( + &mut out[row * os..row * os + w], + &a[row * w..], + &b[row * w..], + w, + ); + } +} + +/// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch +/// destination. +#[inline] +fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize) { + for row in 0..h { + out[row * os..row * os + w].copy_from_slice(&src[row * w..row * w + w]); + } +} + #[inline] fn clip8(v: i32) -> u8 { v.clamp(0, 255) as u8 @@ -184,9 +267,27 @@ fn avg(a: u8, b: u8) -> u8 { /// plus the five taps of the horizontal filter. const TMP_W: usize = 16 + 5; +/// Index of the top-left sample of a whole-sample block, clamped exactly as +/// [`mc_luma`] clamps it. +/// +/// A motion search spends most of its time on whole-sample positions, where +/// prediction is a copy; this lets it read the reference plane in place +/// instead of copying every candidate into a buffer first. +#[inline] +pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usize) -> usize { + let xi = clamp_origin(x, w, r.width, r.pad, 2, 3); + let yi = clamp_origin(y, h, r.height, r.pad, 2, 3); + r.at(xi, yi) +} + /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter -/// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. +/// samples. Writes `w` x `h` prediction samples into `out` at pitch `os`. +/// +/// The pitch is a parameter so that the single-list, default-weight case — +/// which is most of a P slice — interpolates straight into the picture instead +/// of into a temporary that is then copied there. +#[allow(clippy::too_many_arguments)] pub(crate) fn mc_luma( r: &RefPlane<'_>, x: i32, @@ -194,6 +295,7 @@ pub(crate) fn mc_luma( mv: [i16; 2], w: usize, h: usize, + os: usize, out: &mut [u8], ) { let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); @@ -206,7 +308,7 @@ pub(crate) fn mc_luma( if fx == 0 && fy == 0 { for row in 0..h { let src = base + row * stride; - out[row * w..row * w + w].copy_from_slice(&r.data[src..src + w]); + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); } return; } @@ -221,19 +323,13 @@ pub(crate) fn mc_luma( if need_b { // "s" is the same filter one row down, so row fy>>1 selects b or s. let row0 = yi + if fy == 3 { 1 } else { 0 }; - for row in 0..h { - let src = r.at(xi, row0 + row as i32); - store_half(&mut bb[row * w..row * w + w], tap6_16(r.data, src, 1)); - } + half_block(&mut bb, r.data, r.at(xi, row0), stride, 1, w, h); } let mut hh = [0u8; 16 * 17]; if need_h { // "m" is the same filter one column right, so column fx>>1 selects h or m. let col0 = xi + if fx == 3 { 1 } else { 0 }; - for row in 0..h { - let src = r.at(col0, yi + row as i32); - store_half(&mut hh[row * w..row * w + w], tap6_16(r.data, src, stride)); - } + half_block(&mut hh, r.data, r.at(col0, yi), stride, stride, w, h); } let mut jj = [0u8; 16 * 16]; if need_j { @@ -243,10 +339,15 @@ pub(crate) fn mc_luma( let mut inter = [0i16; TMP_W * (16 + 5)]; for row in 0..h + 5 { let src = r.at(xi, yi + row as i32 - 2); - let v = tap6_16(r.data, src, 1); let base = row * TMP_W; - for (o, &t) in inter[base..base + w].iter_mut().zip(v.as_array()) { - *o = t; + if w == 16 { + let v = tap6_16(r.data, src, 1); + inter[base..base + 16].copy_from_slice(v.as_array()); + } else { + let v = tap6_8(r.data, src, 1); + for (o, &t) in inter[base..base + w].iter_mut().zip(v.as_array()) { + *o = t; + } } } for row in 0..h { @@ -261,13 +362,12 @@ pub(crate) fn mc_luma( // Table 8-12: each quarter position is one of the half-sample arrays, or // the average of two of them. Resolving it once per partition rather than // once per sample is what keeps the copy loops straight. - let n = w * h; match (fx, fy) { - (2, 0) => out[..n].copy_from_slice(&bb[..n]), - (0, 2) => out[..n].copy_from_slice(&hh[..n]), - (2, 2) => out[..n].copy_from_slice(&jj[..n]), - (2, 1) | (2, 3) => avg_rows(out, &bb, &jj, n), - (1, 2) | (3, 2) => avg_rows(out, &hh, &jj, n), + (2, 0) => copy_rows(out, os, &bb, w, h), + (0, 2) => copy_rows(out, os, &hh, w, h), + (2, 2) => copy_rows(out, os, &jj, w, h), + (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h), + (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h), (1, 0) | (3, 0) | (0, 1) | (0, 3) => { // Averaged with an integer sample one row or column over. let (dx, dy) = match (fx, fy) { @@ -278,17 +378,54 @@ pub(crate) fn mc_luma( let half: &[u8] = if fy == 0 { &bb } else { &hh }; for row in 0..h { let src = base + (row + dy) * stride + dx; + let s = &r.data[src..src + w]; + let hl = &half[row * w..row * w + w]; + let dst = &mut out[row * os..row * os + w]; for col in 0..w { - out[row * w + col] = avg(r.data[src + col], half[row * w + col]); + dst[col] = avg(s[col], hl[col]); } } } // Diagonal quarter positions: the two nearest half samples. - _ => avg_rows(out, &bb, &hh, n), + _ => avg_rows_to(out, os, &bb, &hh, w, h), + } +} + +/// Equation 8-270 over a block of statically known width. +/// +/// The width is a const parameter because a chroma block is 2, 4 or 8 samples +/// wide and the 2x2 case dominates real streams: with `W` known the row slices +/// have constant length, which drops the bounds checks and lets the smallest +/// blocks compile to a handful of scalar multiplies instead of a vector setup +/// whose lanes are then thrown away. +#[inline] +fn chroma_rows( + data: &[u8], + base: usize, + stride: usize, + h: usize, + wt: [u16; 4], + os: usize, + out: &mut [u8], +) { + for row in 0..h { + let src = base + row * stride; + let p = &data[src..src + W + 1]; + let q = &data[src + stride..src + stride + W + 1]; + let dst = &mut out[row * os..row * os + W]; + for c in 0..W { + let v = u16::from(p[c]) * wt[0] + + u16::from(p[c + 1]) * wt[1] + + u16::from(q[c]) * wt[2] + + u16::from(q[c + 1]) * wt[3] + + 32; + dst[c] = (v >> 6) as u8; + } } } /// Chroma eighth-sample interpolation (Equation 8-270) of a `w` x `h` block. +#[allow(clippy::too_many_arguments)] pub(crate) fn mc_chroma( r: &RefPlane<'_>, x: i32, @@ -296,32 +433,32 @@ pub(crate) fn mc_chroma( mv: [i16; 2], w: usize, h: usize, + os: usize, out: &mut [u8], ) { - let (fx, fy) = ((mv[0] & 7) as i16, (mv[1] & 7) as i16); + let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16); let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1); let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); let stride = r.stride; let base = r.at(xi, yi); - // The four weights sum to 64, so the weighted sum of Equation 8-270 never - // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes. A chroma - // block is at most eight samples wide, which is one vector per row. - let wa = i16x8::splat((8 - fx) * (8 - fy)); - let wb = i16x8::splat(fx * (8 - fy)); - let wc = i16x8::splat((8 - fx) * fy); - let wd = i16x8::splat(fx * fy); - let round = i16x8::splat(32); - for row in 0..h { - let src = base + row * stride; - let v = (load8(r.data, src) * wa - + load8(r.data, src + 1) * wb - + load8(r.data, src + stride) * wc - + load8(r.data, src + stride + 1) * wd - + round) - >> 6u32; - for (o, &s) in out[row * w..row * w + w].iter_mut().zip(v.as_array()) { - *o = s as u8; + + // Full sample: a straight copy. A zero motion vector is the most common + // vector in real content, and it lands here. + if fx == 0 && fy == 0 { + for row in 0..h { + let src = base + row * stride; + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); } + return; + } + + // The four weights sum to 64, so the weighted sum of Equation 8-270 never + // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes. + let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy]; + match w { + 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out), + 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out), + _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out), } } @@ -345,7 +482,9 @@ impl Weights { o: [0, 0], }; - fn is_default(&self) -> bool { + /// True when 8.4.2.3.1 applies, so a single-list prediction is its own + /// final prediction and needs no combining pass at all. + pub(crate) fn is_default(&self) -> bool { *self == Weights::DEFAULT } } @@ -353,6 +492,11 @@ impl Weights { /// Combine the list predictions of one partition into the final prediction /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that /// is not used is ignored. +/// +/// The result is contiguous rather than written at the picture's pitch: the +/// bi-predictive average is the one case where the samples of several rows are +/// adjacent, and vectors that span the row boundary measured 6 to 9 per cent +/// fewer instructions on 1080p than a per-row average at picture pitch. pub(crate) fn combine( out: &mut [u8], p0: &[u8], @@ -534,7 +678,7 @@ mod tests { for fx in 0..4i16 { for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { let mv = [fx - 20 * 4, fy + 12]; - mc_luma(&r, px, py, mv, pw, ph, &mut ours); + mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours); spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs); assert_eq!( ours[..pw * ph], @@ -557,7 +701,7 @@ mod tests { for fy in 0..8i16 { for fx in 0..8i16 { let mv = [fx, fy]; - mc_chroma(&r, px, py, mv, 8, 8, &mut ours); + mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours); for row in 0..8i32 { for col in 0..8i32 { let s = |dx: i32, dy: i32| -> i32 { diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index fc1e06f3..13d96255 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -1,6 +1,6 @@ -//! H.264 software decoder. +//! H.264 software decoder and encoder. //! -//! Current scope: I, P and B slices under both entropy coders (CAVLC and +//! Decoder scope: I, P and B slices under both entropy coders (CAVLC and //! CABAC) of 8-bit 4:2:0 progressive streams — intra prediction, inter //! prediction with the full decoded picture buffer of clause 8.2, weighted //! prediction, and the in-loop deblocking filter — decoded bit-exactly against @@ -41,6 +41,7 @@ mod codec; mod deblock; mod decoder; mod dpb; +mod enc; mod entropy; mod inter; mod mv; @@ -51,3 +52,4 @@ mod transform; pub use codec::H264Decoder; pub use decoder::{Decoder, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; +pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset};