From 7a75a9b8186f9baf4f50ca0b1a0ef9c477952a9e 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 19:47:59 +0300 Subject: [PATCH] perf(h265): 32x32 coding trees by default, for the wavefront rows The wavefront hands one CTB row to a worker, so the tree size sets the parallelism: 1080 lines are 17 rows at CTB 64 but 34 at 32, and 17 rows dealt round-robin over twelve workers leaves seven of them holding half the work of the other five. Measured at 1080p QP 27: the sizes are identical on one thread (1.80 fps each) and 9.03 vs 7.92 fps on twelve, for 1.0% more bits and 0.02 dB less PSNR. Both numbers are now tests: perf.rs measures the two sizes alternately so a drifting machine load cannot favour whichever ran first, and conformance.rs bounds the bits and the PSNR against 64. The ffmpeg bit-exactness oracle now codes shapes at both tree sizes. The bigger figure that prompted this (3.5 vs 11.8 fps) was an end-to-end export at QP 40 on real content, not this crate's pure-encode harness. --- crates/ec-h265/src/encoder.rs | 19 +++++-- crates/ec-h265/tests/conformance.rs | 78 ++++++++++++++++++++++++----- crates/ec-h265/tests/perf.rs | 44 +++++++++++++++- 3 files changed, 124 insertions(+), 17 deletions(-) diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index 1cb53f46..a7ac1251 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -59,7 +59,19 @@ pub struct EncoderConfig { 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. + /// Coding tree block size, 32 (default) or 64. + /// + /// The wavefront hands one CTB *row* to a worker, so the row count is the + /// parallelism this encoder has: 1080 lines are 17 rows at 64 but 34 at 32. + /// Rows are dealt round-robin, so on a twelve-core machine 17 rows means + /// five workers take two rows while seven take one — half the machine idles + /// through the second half of the picture. 34 rows deal three-and-three. + /// Measured on 1080p at QP 27: the two sizes encode at the same speed on one + /// thread (1.80 fps each), but on twelve 32 runs 9.03 fps against 64's 7.92, + /// for 1.0% more bits and 0.02 dB less PSNR — the whole difference is + /// wavefront occupancy, which is why 32 is the default. 64 takes its bits + /// back when the picture is tall enough to fill the workers anyway (2160 + /// lines are 34 rows at 64) or when nothing is waiting for the encode. pub ctb_size: usize, /// How many of the 35 intra modes get a full rate-distortion trial, on top /// of the most probable mode, which always gets one. @@ -85,14 +97,15 @@ pub struct EncoderConfig { } impl EncoderConfig { - /// Defaults for `width x height`: constant QP 27, every core, 64x64 CTBs. + /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs + /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64). pub fn new(width: u32, height: u32) -> EncoderConfig { EncoderConfig { width, height, rate_control: RateControl::ConstantQp(27), threads: 0, - ctb_size: 64, + ctb_size: 32, rdo_candidates: 2, min_cu_size: 8, video_signal_type: None, diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs index 538776cd..d64f3310 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -6,7 +6,7 @@ mod common; -use common::test_frame; +use common::{natural_frame, test_frame}; use ec_core::frame::VideoFrame; use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; use std::io::Write; @@ -88,9 +88,13 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { } } -fn encode(width: u32, height: u32, qp: i32) -> (VideoFrame, EncodedPicture) { +/// Encode one picture; `ctb` of `None` takes the configured default. +fn encode(width: u32, height: u32, qp: i32, ctb: Option) -> (VideoFrame, EncodedPicture) { let mut cfg = EncoderConfig::new(width, height); cfg.rate_control = RateControl::ConstantQp(qp); + if let Some(ctb) = ctb { + cfg.ctb_size = ctb; + } cfg.keep_recon = true; cfg.picture_hash = true; let encoder = Encoder::new(cfg).expect("encoder"); @@ -108,29 +112,79 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() { // 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); + // Both tree sizes are coded: the default is 32, and 64 is still offered. + for &(w, h, ctb) in &[ + (64u32, 64u32, None), + (130, 66, None), + (1916, 1080, None), + (352, 288, None), + (1916, 1080, Some(64)), + (130, 66, Some(64)), + ] { + let (source, coded) = encode(w, h, 27, ctb); + let name = format!( + "shape-{w}x{h}-ctb{}", + ctb.map_or("default".to_string(), |c| c.to_string()) + ); + let path = write_au(&name, &coded); let decoded = match ffmpeg_decode(&path) { Ok(bytes) => bytes, - Err(e) => panic!("{w}x{h}: ffmpeg failed: {e}"), + Err(e) => panic!("{name}: 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", + "{name}: 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"); + assert_eq!(mismatches, 0, "{name}: {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"); + assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); } } +/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower +/// tree; that trade is only worth taking if the bits it costs are noise. +#[test] +fn the_default_tree_costs_almost_nothing_against_64() { + let source = natural_frame(1920, 1080, 0); + let mut coded = Vec::new(); + for ctb in [32usize, 64] { + let mut cfg = EncoderConfig::new(1920, 1080); + cfg.rate_control = RateControl::ConstantQp(27); + cfg.ctb_size = ctb; + cfg.keep_recon = true; + let encoder = Encoder::new(cfg).expect("encoder"); + let picture = encoder.encode_idr(&source).expect("encode"); + let quality = psnr( + &planes_of(&source), + &planes_of(picture.recon.as_ref().unwrap()), + ); + coded.push((picture.au.len(), quality)); + } + let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); + println!( + "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ + ({:+.1}% bits, {:+.2} dB)", + (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, + psnr32 - psnr64 + ); + assert!( + // Measured 1.0% on this fixture; the bound leaves room for the shape of + // the picture, not for a change of coding behaviour. + (bits32 as f64) < bits64 as f64 * 1.03, + "CTB 32 spent {bits32} bytes against 64's {bits64}" + ); + assert!( + (psnr32 - psnr64).abs() < 0.1, + "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" + ); +} + #[test] fn ffmpeg_verifies_the_decoded_picture_hash() { // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's @@ -141,7 +195,7 @@ fn ffmpeg_verifies_the_decoded_picture_hash() { eprintln!("skipping: ffmpeg not installed"); return; } - let (_, coded) = encode(352, 288, 30); + let (_, coded) = encode(352, 288, 30, None); let path = write_au("hash-352x288", &coded); let output = Command::new("ffmpeg") .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) @@ -169,7 +223,7 @@ fn vaapi_hardware_decodes_the_stream() { eprintln!("skipping: no ffmpeg or no VA-API render node"); return; } - let (_, coded) = encode(1920, 1080, 27); + let (_, coded) = encode(1920, 1080, 27, None); let path = write_au("vaapi-1080p", &coded); let output = Command::new("ffmpeg") .args([ @@ -203,7 +257,7 @@ fn vaapi_hardware_decodes_the_stream() { 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 (source, coded) = encode(256, 144, qp, None); let recon = planes_of(coded.recon.as_ref().expect("recon")); let quality = psnr(&planes_of(&source), &recon); assert!( diff --git a/crates/ec-h265/tests/perf.rs b/crates/ec-h265/tests/perf.rs index 877ebdfd..aeaa6853 100644 --- a/crates/ec-h265/tests/perf.rs +++ b/crates/ec-h265/tests/perf.rs @@ -16,7 +16,7 @@ use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; use std::time::Instant; fn measure(width: u32, height: u32, threads: usize, frames: usize) -> f64 { - measure_with(width, height, threads, frames, natural_frame) + measure_with(width, height, threads, frames, natural_frame, None) } /// The 1-minute load average, which decides whether a number measured here @@ -34,10 +34,14 @@ fn measure_with( threads: usize, frames: usize, make: fn(u32, u32, u32) -> ec_core::frame::VideoFrame, + ctb: Option, ) -> f64 { let mut cfg = EncoderConfig::new(width, height); cfg.rate_control = RateControl::ConstantQp(27); cfg.threads = threads; + if let Some(ctb) = ctb { + cfg.ctb_size = ctb; + } let encoder = Encoder::new(cfg).expect("encoder"); let pictures: Vec<_> = (0..frames) .map(|i| make(width, height, i as u32 * 7)) @@ -69,7 +73,7 @@ fn intra_1080p_beats_the_incumbent_on_twelve_threads() { ); // The same measurement on the worst-case noise fixture, printed rather than // asserted: it is not what the 4.30 fps bar was measured on. - let noisy = measure_with(1920, 1080, cores, frames, test_frame); + let noisy = measure_with(1920, 1080, cores, frames, test_frame, None); println!("1080p intra, noise fixture: {noisy:.2} fps on {cores} threads"); if cfg!(debug_assertions) { println!("debug build: not asserting the bar"); @@ -93,6 +97,42 @@ fn intra_1080p_beats_the_incumbent_on_twelve_threads() { ); } +/// Why [`EncoderConfig::new`] defaults to 32x32 trees: the wavefront hands one +/// CTB *row* to a worker, so 1080 lines are 34 rows at 32 against 17 at 64, and +/// 17 rows dealt round-robin over twelve workers leaves seven of them with half +/// the work of the other five. Sizes are measured alternately so a machine whose +/// load drifts during the run cannot favour whichever went first. +#[test] +fn ctb_32_is_the_faster_tree_at_1080p() { + if cfg!(debug_assertions) { + println!("debug build: not measuring the tree size"); + return; + } + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); + let (mut at32, mut at64) = (0.0f64, 0.0f64); + for _ in 0..2 { + at32 = at32.max(measure_with(1920, 1080, cores, 4, natural_frame, Some(32))); + at64 = at64.max(measure_with(1920, 1080, cores, 4, natural_frame, Some(64))); + } + let single64 = measure_with(1920, 1080, 1, 4, natural_frame, Some(64)); + let single32 = measure_with(1920, 1080, 1, 4, natural_frame, Some(32)); + println!( + "1080p on {cores} threads: CTB 32 {at32:.2} fps, CTB 64 {at64:.2} fps ({:.2}x); \ + on 1 thread: 32 {single32:.2} fps, 64 {single64:.2} fps ({:.2}x)", + at32 / at64, + single32 / single64 + ); + let load = load_average(); + if load > cores as f64 / 2.0 { + println!("load average {load:.1} on {cores} cores: not asserting against a busy machine"); + return; + } + assert!( + at32 > at64, + "CTB 32 {at32:.2} fps did not beat CTB 64 {at64:.2} fps on {cores} threads" + ); +} + #[test] fn speedup_curve() { if cfg!(debug_assertions) {