From fa29faa58c1f38977999776c709bdc764afa28f7 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 12:44:07 +0300 Subject: [PATCH] feat(h265): wavefront-parallel intra IDR encoder One encode_idr call uses every core: entropy_coding_sync (WPP) makes each CTB row a substream, a worker starts a row once the row above is two CTBs ahead, and the only shared mutable state is one atomic byte per boundary sample plus a progress counter. No unsafe, no rayon, and the bitstream is identical whatever the thread count - a test asserts that. Deblocking and SAO are signalled off. An intra-only stream predicts from its own reconstruction, so an in-loop filter changes what a decoder shows without changing what either side predicts from; off, the encoder's reconstruction is bit-identical to ffmpeg's decode, which the conformance test checks at four picture shapes including 1916x1080. --- crates/ec-h265/src/encoder.rs | 604 ++++++++++++++++++++++++++++ crates/ec-h265/src/lib.rs | 3 +- crates/ec-h265/tests/common/mod.rs | 38 ++ crates/ec-h265/tests/conformance.rs | 166 ++++++++ crates/ec-h265/tests/perf.rs | 76 ++++ 5 files changed, 886 insertions(+), 1 deletion(-) create mode 100644 crates/ec-h265/src/encoder.rs create mode 100644 crates/ec-h265/tests/common/mod.rs create mode 100644 crates/ec-h265/tests/conformance.rs create mode 100644 crates/ec-h265/tests/perf.rs diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs new file mode 100644 index 00000000..761790c7 --- /dev/null +++ b/crates/ec-h265/src/encoder.rs @@ -0,0 +1,604 @@ +//! The encoder API and the wavefront that makes one call use every core. +//! +//! # Parallelism +//! +//! `entropy_coding_sync_enabled_flag` (WPP) is on. Each CTB row is a substream +//! with its own entry point; a worker may start row `r` once row `r - 1` is two +//! CTBs ahead, which is exactly the dependency intra prediction has (a block +//! reaches at most one CTB to the right on the line above) and exactly what the +//! CABAC context sync in 9.3.2.1 assumes. Rows are handed to `threads` workers +//! round-robin, and every worker owns: +//! +//! - its own band of the reconstruction (`chunks_mut`, no sharing), +//! - its own substream buffer and CABAC engine, +//! - a published bottom line ([`RowBoundary`]) the row below reads through +//! atomics, plus a progress counter. +//! +//! No `unsafe`, no scoped raw pointers, no rayon: the only shared mutable state +//! is one atomic byte per boundary sample and one atomic counter per row. +//! +//! # What comes out +//! +//! One Annex-B access unit per picture, carrying VPS, SPS and PPS every time — +//! every picture is an IDR, so every picture is a seek point, and a seek point +//! whose parameter sets are elsewhere is not one. + +use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes}; +use ec_core::color::ContentLight; +use ec_core::error::{Error, Result}; +use ec_core::frame::{PixelFormat, Plane, VideoFrame}; +use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b}; +use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel}; +use ec_h265_syntax::slice::SliceHeader; +use ec_h265_syntax::vui::{VideoSignalType, VuiParameters}; +use ec_h265_syntax::{Pps, Sps, Vps, sei}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crate::cabac::{CabacEncoder, Contexts}; + +/// How the encoder picks QP for a picture. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RateControl { + /// One fixed quantiser for every picture. + ConstantQp(i32), + /// Aim for `bits` per picture: a model picks the QP, and a picture that + /// lands more than 25% off is coded a second time at a corrected QP. + TargetBits(u64), +} + +/// Encoder settings. +#[derive(Debug, Clone)] +pub struct EncoderConfig { + /// Displayed width; the coded picture is padded up to a whole number of + /// minimum coding blocks and cropped back by the conformance window. + pub width: u32, + /// Displayed height. + pub height: u32, + /// Quantiser or bit target. + pub rate_control: RateControl, + /// Worker threads; 0 means "as many as the machine has". + pub threads: usize, + /// Coding tree block size, 64 (default) or 32. + pub ctb_size: usize, + /// How many of the 35 intra modes get a full rate-distortion trial. + pub rdo_candidates: usize, + /// What the samples mean, written into the VUI. + pub video_signal_type: Option, + /// Sample aspect ratio. + pub sample_aspect_ratio: Option<(u16, u16)>, + /// `(num_units_in_tick, time_scale)`; also picks the level. + pub timing: Option<(u32, u32)>, + /// HDR mastering metadata, written as prefix SEI. + pub content_light: ContentLight, + /// Emit the decoded picture hash SEI (MD5 of the reconstruction). + pub picture_hash: bool, + /// Return the reconstruction alongside the bitstream. + pub keep_recon: bool, +} + +impl EncoderConfig { + /// Defaults for `width x height`: constant QP 27, every core, 64x64 CTBs. + pub fn new(width: u32, height: u32) -> EncoderConfig { + EncoderConfig { + width, + height, + rate_control: RateControl::ConstantQp(27), + threads: 0, + ctb_size: 64, + rdo_candidates: 2, + video_signal_type: None, + sample_aspect_ratio: None, + timing: None, + content_light: ContentLight::default(), + picture_hash: false, + keep_recon: false, + } + } +} + +/// One coded picture. +#[derive(Debug, Clone)] +pub struct EncodedPicture { + /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice. + pub au: Vec, + /// The quantiser the picture was coded at. + pub qp: i32, + /// The reconstruction, cropped to the displayed size, when + /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a + /// conformant decoder produces, because the in-loop filters are off. + pub recon: Option, +} + +/// An intra-only HEVC encoder. +pub struct Encoder { + cfg: EncoderConfig, + vps: Vps, + sps: Sps, + pps: Pps, + coded_width: usize, + coded_height: usize, + threads: usize, +} + +/// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model +/// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6). +const BPP_AT_QP27: f64 = 0.6; + +impl Encoder { + /// Build an encoder, refusing dimensions it cannot code. + pub fn new(cfg: EncoderConfig) -> Result { + if cfg.width < 16 || cfg.height < 16 { + return Err(Error::unsupported( + format!("HEVC encode of {}x{}", cfg.width, cfg.height), + "pictures below 16x16 have no coding tree", + )); + } + if cfg.ctb_size != 64 && cfg.ctb_size != 32 { + return Err(Error::unsupported( + format!("HEVC coding tree block of {}", cfg.ctb_size), + "this encoder codes 64x64 or 32x32 trees", + )); + } + // The coded picture is a whole number of minimum coding blocks (8x8); + // the conformance window crops the padding back off. + let coded_width = (cfg.width as usize).next_multiple_of(8); + let coded_height = (cfg.height as usize).next_multiple_of(8); + let fps = cfg + .timing + .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1))) + .unwrap_or(30.0); + let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for( + coded_width as u32, + coded_height as u32, + fps, + )); + let vps = Vps { + id: 0, + ptl, + max_dec_pic_buffering_minus1: 0, + max_num_reorder_pics: 0, + }; + let log2_ctb = cfg.ctb_size.trailing_zeros(); + let sps = Sps { + vps_id: 0, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + pic_width_in_luma_samples: coded_width as u32, + pic_height_in_luma_samples: coded_height as u32, + conf_win: ConformanceWindow { + left: 0, + right: (coded_width - cfg.width as usize) as u32 / 2, + top: 0, + bottom: (coded_height - cfg.height as usize) as u32 / 2, + }, + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + log2_max_poc_lsb_minus4: 4, + max_dec_pic_buffering_minus1: 0, + max_num_reorder_pics: 0, + log2_min_cb_size_minus3: 0, + log2_diff_max_min_cb_size: log2_ctb - 3, + log2_min_tb_size_minus2: 0, + log2_diff_max_min_tb_size: 3, + max_transform_hierarchy_depth_inter: 0, + max_transform_hierarchy_depth_intra: 0, + scaling_list_enabled: false, + amp_enabled: false, + // No in-loop filters: see `Encoder` docs and the PPS below. + sao_enabled: false, + pcm_enabled: false, + num_short_term_ref_pic_sets: 0, + long_term_ref_pics_present: false, + num_long_term_ref_pics_sps: 0, + temporal_mvp_enabled: false, + strong_intra_smoothing: true, + ptl, + vui: Some(VuiParameters { + sample_aspect_ratio: cfg.sample_aspect_ratio, + video_signal_type: cfg.video_signal_type, + timing: cfg.timing, + }), + }; + let pps = Pps { + id: 0, + sps_id: 0, + entropy_coding_sync_enabled: true, + // Deblocking and SAO are both off, which is what makes the + // encoder's reconstruction bit-identical to a decoder's output: an + // intra-only stream predicts from its own reconstruction only, so + // an in-loop filter would change what a decoder shows without + // changing what either side predicts from. Turning them off buys + // that identity (and the picture-hash check that rides on it) + // rather than a fraction of a dB. + deblocking_filter_control_present: true, + deblocking_filter_disabled: true, + loop_filter_across_slices_enabled: false, + ..Pps::default() + }; + let threads = if cfg.threads == 0 { + std::thread::available_parallelism().map_or(1, |n| n.get()) + } else { + cfg.threads + }; + Ok(Encoder { + cfg, + vps, + sps, + pps, + coded_width, + coded_height, + threads, + }) + } + + /// The sequence parameter set this encoder writes. + pub fn sps(&self) -> &Sps { + &self.sps + } + + /// Encode one picture as an IDR access unit. + /// + /// The frame must be [`PixelFormat::I420`] at the configured size; padding + /// to the coded size is this encoder's job, not the caller's. + pub fn encode_idr(&self, frame: &VideoFrame) -> Result { + if frame.format != PixelFormat::I420 { + return Err(Error::unsupported( + format!("HEVC encode of {:?}", frame.format), + "this encoder codes 8-bit 4:2:0 planar", + )); + } + if frame.width != self.cfg.width || frame.height != self.cfg.height { + return Err(Error::corrupt(format!( + "HEVC encode: frame is {}x{}, encoder configured for {}x{}", + frame.width, frame.height, self.cfg.width, self.cfg.height + ))); + } + let planes: Vec<(&[u8], usize)> = frame + .planes + .iter() + .map(|p: &Plane| (&p.data[..], p.stride)) + .collect(); + self.encode_idr_planes( + planes[0].0, + planes[0].1, + planes[1].0, + planes[1].1, + planes[2].0, + planes[2].1, + ) + } + + /// Encode one picture from raw I420 planes with their strides. + /// + /// This is the surface a compatibility shim maps onto: the planes are the + /// *displayed* picture, and the conformance window handles the rest. + pub fn encode_idr_planes( + &self, + y: &[u8], + y_stride: usize, + cb: &[u8], + cb_stride: usize, + cr: &[u8], + cr_stride: usize, + ) -> Result { + let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?; + let (mut qp, target) = match self.cfg.rate_control { + RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None), + RateControl::TargetBits(bits) => { + let pixels = (self.cfg.width as f64) * (self.cfg.height as f64); + let target_bpp = (bits as f64 / pixels).max(1e-4); + let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2(); + ((qp.round() as i32).clamp(0, 51), Some(bits)) + } + }; + let mut coded = self.code_picture(&padded, qp)?; + if let Some(target) = target { + let actual = coded.au.len() as f64 * 8.0; + let target = target as f64; + if (actual - target).abs() / target > 0.25 { + // One correction pass, from the measured slope rather than the + // model: 6 QP steps is a factor of two in rate. + let correction = 6.0 * (actual / target).log2(); + let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32; + let corrected = corrected.clamp(0, 51); + if corrected != qp { + qp = corrected; + coded = self.code_picture(&padded, qp)?; + } + } + } + Ok(coded) + } + + /// Encode a batch of pictures, each as its own IDR access unit. + /// + /// The wavefront inside a single picture already uses every core, so this is + /// a convenience for callers with a list, not a second layer of threads. + pub fn encode_batch<'a, I>(&self, frames: I) -> Result> + where + I: IntoIterator, + { + frames.into_iter().map(|f| self.encode_idr(f)).collect() + } + + /// Copy the source into coded-size planes, replicating the edge into the + /// padding rather than filling it with black: the padding is coded and then + /// cropped away, and a black border would bleed into the last real column + /// through the prediction and the transform that straddles it. + fn pad_source( + &self, + y: &[u8], + y_stride: usize, + cb: &[u8], + cb_stride: usize, + cr: &[u8], + cr_stride: usize, + ) -> Result { + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let (coded_w, coded_h) = (self.coded_width, self.coded_height); + let plane = |src: &[u8], stride: usize, width: usize, height: usize, out_w: usize, out_h: usize| -> Result> { + if stride < width || src.len() < (height - 1) * stride + width { + return Err(Error::corrupt( + "HEVC encode: source plane shorter than its stated size".to_string(), + )); + } + let mut out = vec![0u8; out_w * out_h]; + for row in 0..out_h { + let src_row = row.min(height - 1); + let line = &src[src_row * stride..src_row * stride + width]; + let dst = &mut out[row * out_w..row * out_w + out_w]; + dst[..width].copy_from_slice(line); + let edge = line[width - 1]; + dst[width..].fill(edge); + } + Ok(out) + }; + Ok(PaddedSource { + y: plane(y, y_stride, w, h, coded_w, coded_h)?, + cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?, + cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?, + }) + } + + /// Code one picture at `qp`, wavefront across CTB rows. + fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result { + let (width, height) = (self.coded_width, self.coded_height); + let ctb = self.cfg.ctb_size; + let cols = width.div_ceil(ctb); + let rows = height.div_ceil(ctb); + + let mut rec_y = vec![0u8; width * height]; + let mut rec_cb = vec![0u8; width / 2 * height / 2]; + let mut rec_cr = vec![0u8; width / 2 * height / 2]; + + let boundaries: Vec = (0..rows).map(|_| RowBoundary::new(width)).collect(); + let progress: Vec = (0..rows).map(|_| AtomicUsize::new(0)).collect(); + let wpp_contexts: Vec>> = + (0..rows).map(|_| Mutex::new(None)).collect(); + let substreams: Vec>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); + + // One band of the reconstruction per CTB row, handed out by index. + let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect(); + let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect(); + let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect(); + let threads = self.threads.min(rows).max(1); + // Round-robin: worker t owns rows t, t + threads, ... Each row's + // predecessor therefore belongs to another worker that is never waiting + // on it, so the wavefront cannot deadlock. + let mut per_worker: Vec> = + (0..threads).map(|_| Vec::new()).collect(); + for row in (0..rows).rev() { + let y = bands_y.pop().expect("one band per row"); + let cb = bands_cb.pop().expect("one band per row"); + let cr = bands_cr.pop().expect("one band per row"); + per_worker[row % threads].push((row, y, cb, cr)); + } + for worker in per_worker.iter_mut() { + worker.reverse(); + } + + let slice_qp = qp; + std::thread::scope(|scope| { + for worker_rows in per_worker { + let boundaries = &boundaries; + let progress = &progress; + let wpp_contexts = &wpp_contexts; + let substreams = &substreams; + let src = &src; + scope.spawn(move || { + for (row, band_y, band_cb, band_cr) in worker_rows { + let band_y0 = row * ctb; + // Wait for the row above to be two CTBs ahead, which is + // both the prediction reach and the CABAC sync point. + if row > 0 { + wait_for(&progress[row - 1], 2.min(cols)); + } + let contexts = if row == 0 || cols < 2 { + Contexts::new(slice_qp) + } else { + wpp_contexts[row - 1] + .lock() + .ok() + .and_then(|c| c.clone()) + .unwrap_or_else(|| Contexts::new(slice_qp)) + }; + let mut enc = CabacEncoder::new(contexts); + let mut coder = CtuEncoder::new( + SourcePlanes { + y: &src.y, + cb: &src.cb, + cr: &src.cr, + }, + RowState { + rec_y: band_y, + rec_cb: band_cb, + rec_cr: band_cr, + publish: &boundaries[row], + above: if row == 0 { + None + } else { + Some(&boundaries[row - 1]) + }, + }, + width, + height, + ctb, + band_y0, + slice_qp, + true, + self.cfg.rdo_candidates, + ); + for col in 0..cols { + if row > 0 { + wait_for(&progress[row - 1], (col + 2).min(cols)); + } + coder.encode_ctu(col, &mut enc); + if col == 1 { + // 9.3.2.1: the row below syncs from the state + // after the second CTB of this row. + if let Ok(mut slot) = wpp_contexts[row].lock() { + *slot = Some(enc.contexts.clone()); + } + } + progress[row].store(col + 1, Ordering::Release); + let last_in_picture = row + 1 == rows && col + 1 == cols; + enc.encode_terminate(u32::from(last_in_picture)); + if !last_in_picture && col + 1 == cols { + // end_of_subset_one_bit, then byte alignment. + enc.encode_terminate(1); + } + } + if let Ok(mut slot) = substreams[row].lock() { + *slot = enc.finish(); + } + } + }); + } + }); + + let substreams: Vec> = substreams + .into_iter() + .map(|m| m.into_inner().unwrap_or_default()) + .collect(); + let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr); + let recon = self + .cfg + .keep_recon + .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr)); + Ok(EncodedPicture { au, qp, recon }) + } + + /// Parameter sets, optional SEI, and the slice, in Annex-B framing. + fn assemble_au( + &self, + qp: i32, + substreams: &[Vec], + rec_y: &[u8], + rec_cb: &[u8], + rec_cr: &[u8], + ) -> Vec { + let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::() + 256); + write_annex_b( + &mut au, + NalHeader::new(NalUnitType::Vps), + &self.vps.to_rbsp(), + true, + ); + write_annex_b( + &mut au, + NalHeader::new(NalUnitType::Sps), + &self.sps.to_rbsp(), + true, + ); + write_annex_b( + &mut au, + NalHeader::new(NalUnitType::Pps), + &self.pps.to_rbsp(), + true, + ); + if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) { + write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); + } + + // Entry points count the bytes as they appear in the NAL, emulation + // prevention included. Each substream ends on a byte whose last written + // bit is the flush's one bit, so no escape sequence straddles a + // boundary and each substream can be measured on its own. + let mut escaped: Vec> = Vec::with_capacity(substreams.len()); + for stream in substreams { + let mut out = Vec::with_capacity(stream.len() + 8); + escape_rbsp(stream, &mut out); + escaped.push(out); + } + let mut header = SliceHeader::intra(&self.pps, qp - 26); + header.entry_point_offsets = escaped + .iter() + .take(escaped.len().saturating_sub(1)) + .map(|s| s.len() as u32) + .collect(); + let mut writer = ec_core::bitio::BitWriter::with_capacity(64); + header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl); + let mut rbsp = writer.into_bytes(); + for stream in substreams { + rbsp.extend_from_slice(stream); + } + write_annex_b( + &mut au, + NalHeader::new(NalUnitType::IdrWRadl), + &rbsp, + true, + ); + + if self.cfg.picture_hash { + let (w, h) = (self.coded_width, self.coded_height); + let rbsp = sei::decoded_picture_hash_rbsp(&[ + (rec_y, w, w, h), + (rec_cb, w / 2, w / 2, h / 2), + (rec_cr, w / 2, w / 2, h / 2), + ]); + write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); + } + au + } + + fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame { + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec { + let mut out = Vec::with_capacity(width * height); + for row in 0..height { + out.extend_from_slice(&src[row * stride..row * stride + width]); + } + out + }; + let planes = vec![ + Plane::new(crop(rec_y, self.coded_width, w, h), w), + Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw), + Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw), + ]; + VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes) + .expect("cropped planes are exactly the size I420 asks for") + } +} + +/// Spin then yield until a row's progress counter reaches `target`. +fn wait_for(counter: &AtomicUsize, target: usize) { + let mut spins = 0u32; + while counter.load(Ordering::Acquire) < target { + if spins < 64 { + std::hint::spin_loop(); + spins += 1; + } else { + std::thread::yield_now(); + } + } +} + +struct PaddedSource { + y: Vec, + cb: Vec, + cr: Vec, +} diff --git a/crates/ec-h265/src/lib.rs b/crates/ec-h265/src/lib.rs index a6f06297..6842c2e1 100644 --- a/crates/ec-h265/src/lib.rs +++ b/crates/ec-h265/src/lib.rs @@ -3,7 +3,8 @@ #![warn(missing_docs)] pub mod cabac; -pub mod ctu; pub mod intra; +pub mod ctu; +pub mod encoder; pub mod residual; pub mod transform; diff --git a/crates/ec-h265/tests/common/mod.rs b/crates/ec-h265/tests/common/mod.rs new file mode 100644 index 00000000..9aa66028 --- /dev/null +++ b/crates/ec-h265/tests/common/mod.rs @@ -0,0 +1,38 @@ +//! Shared fixtures for the integration tests. + +use ec_core::frame::{PixelFormat, Plane, VideoFrame}; + +/// A synthetic picture with gradients, edges and texture — enough structure +/// that every intra direction gets used somewhere. +pub fn test_frame(width: u32, height: u32, phase: u32) -> VideoFrame { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let mut y = vec![0u8; w * h]; + for row in 0..h { + for col in 0..w { + let diag = ((row + col + phase as usize) % 64) as i32; + let ramp = (col * 200 / w) as i32; + let ring = if (row * row + col * col) % 977 < 60 { 60 } else { 0 }; + let texture = ((row * 7 + col * 13) % 17) as i32 * 3; + y[row * w + col] = (16 + ramp + diag / 2 + ring + texture).clamp(0, 255) as u8; + } + } + let mut cb = vec![0u8; cw * ch]; + let mut cr = vec![0u8; cw * ch]; + for row in 0..ch { + for col in 0..cw { + cb[row * cw + col] = + (128 + (col as i32 * 60 / (cw as i32)) - 30).clamp(0, 255) as u8; + cr[row * cw + col] = + (128 + (row as i32 * 60 / (ch as i32)) - 30).clamp(0, 255) as u8; + } + } + VideoFrame::try_new( + PixelFormat::I420, + width, + height, + vec![Plane::new(y, w), Plane::new(cb, cw), Plane::new(cr, cw)], + ) + .expect("test frame") +} + diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs new file mode 100644 index 00000000..1732b36c --- /dev/null +++ b/crates/ec-h265/tests/conformance.rs @@ -0,0 +1,166 @@ +//! Conformance: every access unit this encoder writes must decode in ffmpeg, +//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own +//! reconstruction. That equality is the whole point of coding with the in-loop +//! filters off: it turns "the file plays" into "the decoder and the encoder +//! agree on every sample". + +mod common; + +use common::test_frame; +use ec_core::frame::VideoFrame; +use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn scratch_dir() -> PathBuf { + let dir = std::env::temp_dir().join("ec-h265-tests"); + std::fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. +fn ffmpeg_decode(path: &Path) -> Result, String> { + let out = path.with_extension("yuv"); + let status = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .arg(&out) + .output() + .map_err(|e| e.to_string())?; + if !status.status.success() { + return Err(String::from_utf8_lossy(&status.stderr).to_string()); + } + let stderr = String::from_utf8_lossy(&status.stderr).to_string(); + if !stderr.trim().is_empty() { + return Err(format!("ffmpeg complained: {stderr}")); + } + std::fs::read(&out).map_err(|e| e.to_string()) +} + +fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { + let path = scratch_dir().join(format!("{name}.265")); + let mut file = std::fs::File::create(&path).expect("create bitstream"); + file.write_all(&picture.au).expect("write bitstream"); + path +} + +fn planes_of(frame: &VideoFrame) -> Vec { + let mut out = Vec::new(); + let (w, h) = (frame.width as usize, frame.height as usize); + for (i, plane) in frame.planes.iter().enumerate() { + let (pw, ph) = if i == 0 { + (w, h) + } else { + (w.div_ceil(2), h.div_ceil(2)) + }; + for row in 0..ph { + out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); + } + } + out +} + +fn psnr(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + let mse: f64 = a + .iter() + .zip(b) + .map(|(x, y)| { + let d = f64::from(*x) - f64::from(*y); + d * d + }) + .sum::() + / a.len() as f64; + if mse == 0.0 { + 99.0 + } else { + 10.0 * (255.0 * 255.0 / mse).log10() + } +} + +fn encode(width: u32, height: u32, qp: i32) -> (VideoFrame, EncodedPicture) { + let mut cfg = EncoderConfig::new(width, height); + cfg.rate_control = RateControl::ConstantQp(qp); + cfg.keep_recon = true; + cfg.picture_hash = true; + let encoder = Encoder::new(cfg).expect("encoder"); + let frame = test_frame(width, height, 0); + let coded = encoder.encode_idr(&frame).expect("encode"); + (frame, coded) +} + +#[test] +fn ffmpeg_decodes_bit_exactly_at_every_shape() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not installed"); + return; + } + // 1920x1080 needs the conformance window on the bottom (1088 coded rows are + // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916 + // needs it on the right, 130x66 exercises a partial CTB in both directions. + for &(w, h) in &[(64u32, 64u32), (130, 66), (1916, 1080), (352, 288)] { + let (source, coded) = encode(w, h, 27); + let path = write_au(&format!("shape-{w}x{h}"), &coded); + let decoded = match ffmpeg_decode(&path) { + Ok(bytes) => bytes, + Err(e) => panic!("{w}x{h}: ffmpeg failed: {e}"), + }; + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); + assert_eq!( + decoded.len(), + recon.len(), + "{w}x{h}: decoded {} bytes, reconstruction {} bytes", + decoded.len(), + recon.len() + ); + let mismatches = decoded + .iter() + .zip(&recon) + .filter(|(a, b)| a != b) + .count(); + assert_eq!(mismatches, 0, "{w}x{h}: {mismatches} samples differ"); + // And the encode is worth something: PSNR against the source. + let quality = psnr(&planes_of(&source), &recon); + assert!(quality > 30.0, "{w}x{h}: PSNR {quality:.2} dB at QP 27"); + } +} + +#[test] +fn quality_rises_as_qp_falls() { + let mut previous = 0.0; + for &qp in &[40i32, 32, 27, 22] { + let (source, coded) = encode(256, 144, qp); + let recon = planes_of(coded.recon.as_ref().expect("recon")); + let quality = psnr(&planes_of(&source), &recon); + assert!( + quality > previous, + "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" + ); + previous = quality; + } + assert!(previous > 40.0, "QP 22 should clear 40 dB, got {previous:.2}"); +} + +#[test] +fn threads_do_not_change_the_bitstream() { + let mut cfg = EncoderConfig::new(320, 192); + cfg.rate_control = RateControl::ConstantQp(30); + cfg.threads = 1; + let single = Encoder::new(cfg.clone()).unwrap(); + cfg.threads = 8; + let many = Encoder::new(cfg).unwrap(); + let frame = test_frame(320, 192, 3); + let a = single.encode_idr(&frame).unwrap(); + let b = many.encode_idr(&frame).unwrap(); + assert_eq!(a.au, b.au, "wavefront changed the bitstream"); +} diff --git a/crates/ec-h265/tests/perf.rs b/crates/ec-h265/tests/perf.rs new file mode 100644 index 00000000..6c255005 --- /dev/null +++ b/crates/ec-h265/tests/perf.rs @@ -0,0 +1,76 @@ +//! The speed bar, measured the way the claim is made: one `encode_idr` call per +//! picture, zero threads on the caller's side. +//! +//! The incumbent this replaces (`oxideav-h265`) has no threads at all inside its +//! encoder — edith fans whole access units out across twelve cores to reach 4.30 +//! fps at 1080p. The bar here is to beat that from *inside* one call, so the +//! measurement below hands one picture at a time to one encoder. +//! +//! Run under `--release`; in a debug build this prints the numbers and skips the +//! assertion, because a debug build measures the compiler, not the encoder. + +mod common; + +use common::test_frame; +use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; +use std::time::Instant; + +fn measure(width: u32, height: u32, threads: usize, frames: usize) -> f64 { + let mut cfg = EncoderConfig::new(width, height); + cfg.rate_control = RateControl::ConstantQp(27); + cfg.threads = threads; + let encoder = Encoder::new(cfg).expect("encoder"); + let pictures: Vec<_> = (0..frames) + .map(|i| test_frame(width, height, i as u32 * 7)) + .collect(); + // One untimed picture so the allocator and the caches are warm. + encoder.encode_idr(&pictures[0]).expect("warm-up encode"); + let start = Instant::now(); + for picture in &pictures { + encoder.encode_idr(picture).expect("encode"); + } + let elapsed = start.elapsed().as_secs_f64(); + frames as f64 / elapsed +} + +#[test] +fn intra_1080p_beats_the_incumbent_on_twelve_threads() { + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); + let frames = if cfg!(debug_assertions) { 1 } else { 6 }; + let single = measure(1920, 1080, 1, frames); + let many = measure(1920, 1080, cores, frames); + println!("1080p intra: {single:.2} fps on 1 thread, {many:.2} fps on {cores} threads, speed-up {:.2}x", many / single); + if cfg!(debug_assertions) { + println!("debug build: not asserting the bar"); + return; + } + assert!( + many > 4.30, + "1080p on {cores} threads: {many:.2} fps, incumbent bar is 4.30" + ); + assert!( + many > single * 2.0, + "wavefront gained only {:.2}x", + many / single + ); +} + +#[test] +fn speedup_curve() { + if cfg!(debug_assertions) { + println!("debug build: skipping the speed-up curve"); + return; + } + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); + let mut base = 0.0; + for threads in [1usize, 2, 4, 8, cores] { + if threads > cores { + continue; + } + let fps = measure(1920, 1080, threads, 4); + if threads == 1 { + base = fps; + } + println!("threads {threads:2}: {fps:6.2} fps speed-up {:.2}x", fps / base); + } +}