forge
Explore
Log in

Don't you dare go Hollow

32x32 coding trees by default, for the wavefront rows

Browse files at this commit

7a75a9b8186f9baf4f50ca0b1a0ef9c477952a9eAhmet Kaan GümüşParent: d8c174c
  • perf
    • 32x32 coding trees by default, for the wavefront rows
Show full message
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.rsmodified+16 -3
@@ -59,7 +59,19 @@ pub struct EncoderConfig {
59 pub rate_control: RateControl,59 pub rate_control: RateControl,
60 /// Worker threads; 0 means "as many as the machine has".60 /// Worker threads; 0 means "as many as the machine has".
61 pub threads: usize,61 pub threads: usize,
62- /// Coding tree block size, 64 (default) or 32.62+ /// Coding tree block size, 32 (default) or 64.
63+ ///
64+ /// The wavefront hands one CTB *row* to a worker, so the row count is the
65+ /// parallelism this encoder has: 1080 lines are 17 rows at 64 but 34 at 32.
66+ /// Rows are dealt round-robin, so on a twelve-core machine 17 rows means
67+ /// five workers take two rows while seven take one — half the machine idles
68+ /// through the second half of the picture. 34 rows deal three-and-three.
69+ /// Measured on 1080p at QP 27: the two sizes encode at the same speed on one
70+ /// thread (1.80 fps each), but on twelve 32 runs 9.03 fps against 64's 7.92,
71+ /// for 1.0% more bits and 0.02 dB less PSNR — the whole difference is
72+ /// wavefront occupancy, which is why 32 is the default. 64 takes its bits
73+ /// back when the picture is tall enough to fill the workers anyway (2160
74+ /// lines are 34 rows at 64) or when nothing is waiting for the encode.
63 pub ctb_size: usize,75 pub ctb_size: usize,
64 /// How many of the 35 intra modes get a full rate-distortion trial, on top76 /// How many of the 35 intra modes get a full rate-distortion trial, on top
65 /// of the most probable mode, which always gets one.77 /// of the most probable mode, which always gets one.
@@ -85,14 +97,15 @@ pub struct EncoderConfig {
85 }97 }
86 98
87 impl EncoderConfig {99 impl EncoderConfig {
88- /// Defaults for `width x height`: constant QP 27, every core, 64x64 CTBs.100+ /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs
101+ /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64).
89 pub fn new(width: u32, height: u32) -> EncoderConfig {102 pub fn new(width: u32, height: u32) -> EncoderConfig {
90 EncoderConfig {103 EncoderConfig {
91 width,104 width,
92 height,105 height,
93 rate_control: RateControl::ConstantQp(27),106 rate_control: RateControl::ConstantQp(27),
94 threads: 0,107 threads: 0,
95- ctb_size: 64,108+ ctb_size: 32,
96 rdo_candidates: 2,109 rdo_candidates: 2,
97 min_cu_size: 8,110 min_cu_size: 8,
98 video_signal_type: None,111 video_signal_type: None,
crates/ec-h265/tests/conformance.rsmodified+66 -12
@@ -6,7 +6,7 @@
6 6
7 mod common;7 mod common;
8 8
9-use common::test_frame;9+use common::{natural_frame, test_frame};
10 use ec_core::frame::VideoFrame;10 use ec_core::frame::VideoFrame;
11 use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl};11 use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl};
12 use std::io::Write;12 use std::io::Write;
@@ -88,9 +88,13 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 {
88 }88 }
89 }89 }
90 90
91-fn encode(width: u32, height: u32, qp: i32) -> (VideoFrame, EncodedPicture) {91+/// Encode one picture; `ctb` of `None` takes the configured default.
92+fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) {
92 let mut cfg = EncoderConfig::new(width, height);93 let mut cfg = EncoderConfig::new(width, height);
93 cfg.rate_control = RateControl::ConstantQp(qp);94 cfg.rate_control = RateControl::ConstantQp(qp);
95+ if let Some(ctb) = ctb {
96+ cfg.ctb_size = ctb;
97+ }
94 cfg.keep_recon = true;98 cfg.keep_recon = true;
95 cfg.picture_hash = true;99 cfg.picture_hash = true;
96 let encoder = Encoder::new(cfg).expect("encoder");100 let encoder = Encoder::new(cfg).expect("encoder");
@@ -108,29 +112,79 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() {
108 // 1920x1080 needs the conformance window on the bottom (1088 coded rows are112 // 1920x1080 needs the conformance window on the bottom (1088 coded rows are
109 // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916113 // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916
110 // needs it on the right, 130x66 exercises a partial CTB in both directions.114 // needs it on the right, 130x66 exercises a partial CTB in both directions.
111- for &(w, h) in &[(64u32, 64u32), (130, 66), (1916, 1080), (352, 288)] {115+ // Both tree sizes are coded: the default is 32, and 64 is still offered.
112- let (source, coded) = encode(w, h, 27);116+ for &(w, h, ctb) in &[
113- let path = write_au(&format!("shape-{w}x{h}"), &coded);117+ (64u32, 64u32, None),
118+ (130, 66, None),
119+ (1916, 1080, None),
120+ (352, 288, None),
121+ (1916, 1080, Some(64)),
122+ (130, 66, Some(64)),
123+ ] {
124+ let (source, coded) = encode(w, h, 27, ctb);
125+ let name = format!(
126+ "shape-{w}x{h}-ctb{}",
127+ ctb.map_or("default".to_string(), |c| c.to_string())
128+ );
129+ let path = write_au(&name, &coded);
114 let decoded = match ffmpeg_decode(&path) {130 let decoded = match ffmpeg_decode(&path) {
115 Ok(bytes) => bytes,131 Ok(bytes) => bytes,
116- Err(e) => panic!("{w}x{h}: ffmpeg failed: {e}"),132+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
117 };133 };
118 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));134 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
119 assert_eq!(135 assert_eq!(
120 decoded.len(),136 decoded.len(),
121 recon.len(),137 recon.len(),
122- "{w}x{h}: decoded {} bytes, reconstruction {} bytes",138+ "{name}: decoded {} bytes, reconstruction {} bytes",
123 decoded.len(),139 decoded.len(),
124 recon.len()140 recon.len()
125 );141 );
126 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();142 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
127- assert_eq!(mismatches, 0, "{w}x{h}: {mismatches} samples differ");143+ assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");
128 // And the encode is worth something: PSNR against the source.144 // And the encode is worth something: PSNR against the source.
129 let quality = psnr(&planes_of(&source), &recon);145 let quality = psnr(&planes_of(&source), &recon);
130- assert!(quality > 30.0, "{w}x{h}: PSNR {quality:.2} dB at QP 27");146+ assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");
131 }147 }
132 }148 }
133 149
150+/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower
151+/// tree; that trade is only worth taking if the bits it costs are noise.
152+#[test]
153+fn the_default_tree_costs_almost_nothing_against_64() {
154+ let source = natural_frame(1920, 1080, 0);
155+ let mut coded = Vec::new();
156+ for ctb in [32usize, 64] {
157+ let mut cfg = EncoderConfig::new(1920, 1080);
158+ cfg.rate_control = RateControl::ConstantQp(27);
159+ cfg.ctb_size = ctb;
160+ cfg.keep_recon = true;
161+ let encoder = Encoder::new(cfg).expect("encoder");
162+ let picture = encoder.encode_idr(&source).expect("encode");
163+ let quality = psnr(
164+ &planes_of(&source),
165+ &planes_of(picture.recon.as_ref().unwrap()),
166+ );
167+ coded.push((picture.au.len(), quality));
168+ }
169+ let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]);
170+ println!(
171+ "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \
172+ ({:+.1}% bits, {:+.2} dB)",
173+ (bits32 as f64 / bits64 as f64 - 1.0) * 100.0,
174+ psnr32 - psnr64
175+ );
176+ assert!(
177+ // Measured 1.0% on this fixture; the bound leaves room for the shape of
178+ // the picture, not for a change of coding behaviour.
179+ (bits32 as f64) < bits64 as f64 * 1.03,
180+ "CTB 32 spent {bits32} bytes against 64's {bits64}"
181+ );
182+ assert!(
183+ (psnr32 - psnr64).abs() < 0.1,
184+ "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB"
185+ );
186+}
187+
134 #[test]188 #[test]
135 fn ffmpeg_verifies_the_decoded_picture_hash() {189 fn ffmpeg_verifies_the_decoded_picture_hash() {
136 // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's190 // 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() {
141 eprintln!("skipping: ffmpeg not installed");195 eprintln!("skipping: ffmpeg not installed");
142 return;196 return;
143 }197 }
144- let (_, coded) = encode(352, 288, 30);198+ let (_, coded) = encode(352, 288, 30, None);
145 let path = write_au("hash-352x288", &coded);199 let path = write_au("hash-352x288", &coded);
146 let output = Command::new("ffmpeg")200 let output = Command::new("ffmpeg")
147 .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"])201 .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"])
@@ -169,7 +223,7 @@ fn vaapi_hardware_decodes_the_stream() {
169 eprintln!("skipping: no ffmpeg or no VA-API render node");223 eprintln!("skipping: no ffmpeg or no VA-API render node");
170 return;224 return;
171 }225 }
172- let (_, coded) = encode(1920, 1080, 27);226+ let (_, coded) = encode(1920, 1080, 27, None);
173 let path = write_au("vaapi-1080p", &coded);227 let path = write_au("vaapi-1080p", &coded);
174 let output = Command::new("ffmpeg")228 let output = Command::new("ffmpeg")
175 .args([229 .args([
@@ -203,7 +257,7 @@ fn vaapi_hardware_decodes_the_stream() {
203 fn quality_rises_as_qp_falls() {257 fn quality_rises_as_qp_falls() {
204 let mut previous = 0.0;258 let mut previous = 0.0;
205 for &qp in &[40i32, 32, 27, 22] {259 for &qp in &[40i32, 32, 27, 22] {
206- let (source, coded) = encode(256, 144, qp);260+ let (source, coded) = encode(256, 144, qp, None);
207 let recon = planes_of(coded.recon.as_ref().expect("recon"));261 let recon = planes_of(coded.recon.as_ref().expect("recon"));
208 let quality = psnr(&planes_of(&source), &recon);262 let quality = psnr(&planes_of(&source), &recon);
209 assert!(263 assert!(
crates/ec-h265/tests/perf.rsmodified+42 -2
@@ -16,7 +16,7 @@ use ec_h265::encoder::{Encoder, EncoderConfig, RateControl};
16 use std::time::Instant;16 use std::time::Instant;
17 17
18 fn measure(width: u32, height: u32, threads: usize, frames: usize) -> f64 {18 fn measure(width: u32, height: u32, threads: usize, frames: usize) -> f64 {
19- measure_with(width, height, threads, frames, natural_frame)19+ measure_with(width, height, threads, frames, natural_frame, None)
20 }20 }
21 21
22 /// The 1-minute load average, which decides whether a number measured here22 /// The 1-minute load average, which decides whether a number measured here
@@ -34,10 +34,14 @@ fn measure_with(
34 threads: usize,34 threads: usize,
35 frames: usize,35 frames: usize,
36 make: fn(u32, u32, u32) -> ec_core::frame::VideoFrame,36 make: fn(u32, u32, u32) -> ec_core::frame::VideoFrame,
37+ ctb: Option<usize>,
37 ) -> f64 {38 ) -> f64 {
38 let mut cfg = EncoderConfig::new(width, height);39 let mut cfg = EncoderConfig::new(width, height);
39 cfg.rate_control = RateControl::ConstantQp(27);40 cfg.rate_control = RateControl::ConstantQp(27);
40 cfg.threads = threads;41 cfg.threads = threads;
42+ if let Some(ctb) = ctb {
43+ cfg.ctb_size = ctb;
44+ }
41 let encoder = Encoder::new(cfg).expect("encoder");45 let encoder = Encoder::new(cfg).expect("encoder");
42 let pictures: Vec<_> = (0..frames)46 let pictures: Vec<_> = (0..frames)
43 .map(|i| make(width, height, i as u32 * 7))47 .map(|i| make(width, height, i as u32 * 7))
@@ -69,7 +73,7 @@ fn intra_1080p_beats_the_incumbent_on_twelve_threads() {
69 );73 );
70 // The same measurement on the worst-case noise fixture, printed rather than74 // The same measurement on the worst-case noise fixture, printed rather than
71 // asserted: it is not what the 4.30 fps bar was measured on.75 // asserted: it is not what the 4.30 fps bar was measured on.
72- let noisy = measure_with(1920, 1080, cores, frames, test_frame);76+ let noisy = measure_with(1920, 1080, cores, frames, test_frame, None);
73 println!("1080p intra, noise fixture: {noisy:.2} fps on {cores} threads");77 println!("1080p intra, noise fixture: {noisy:.2} fps on {cores} threads");
74 if cfg!(debug_assertions) {78 if cfg!(debug_assertions) {
75 println!("debug build: not asserting the bar");79 println!("debug build: not asserting the bar");
@@ -93,6 +97,42 @@ fn intra_1080p_beats_the_incumbent_on_twelve_threads() {
93 );97 );
94 }98 }
95 99
100+/// Why [`EncoderConfig::new`] defaults to 32x32 trees: the wavefront hands one
101+/// CTB *row* to a worker, so 1080 lines are 34 rows at 32 against 17 at 64, and
102+/// 17 rows dealt round-robin over twelve workers leaves seven of them with half
103+/// the work of the other five. Sizes are measured alternately so a machine whose
104+/// load drifts during the run cannot favour whichever went first.
105+#[test]
106+fn ctb_32_is_the_faster_tree_at_1080p() {
107+ if cfg!(debug_assertions) {
108+ println!("debug build: not measuring the tree size");
109+ return;
110+ }
111+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
112+ let (mut at32, mut at64) = (0.0f64, 0.0f64);
113+ for _ in 0..2 {
114+ at32 = at32.max(measure_with(1920, 1080, cores, 4, natural_frame, Some(32)));
115+ at64 = at64.max(measure_with(1920, 1080, cores, 4, natural_frame, Some(64)));
116+ }
117+ let single64 = measure_with(1920, 1080, 1, 4, natural_frame, Some(64));
118+ let single32 = measure_with(1920, 1080, 1, 4, natural_frame, Some(32));
119+ println!(
120+ "1080p on {cores} threads: CTB 32 {at32:.2} fps, CTB 64 {at64:.2} fps ({:.2}x); \
121+ on 1 thread: 32 {single32:.2} fps, 64 {single64:.2} fps ({:.2}x)",
122+ at32 / at64,
123+ single32 / single64
124+ );
125+ let load = load_average();
126+ if load > cores as f64 / 2.0 {
127+ println!("load average {load:.1} on {cores} cores: not asserting against a busy machine");
128+ return;
129+ }
130+ assert!(
131+ at32 > at64,
132+ "CTB 32 {at32:.2} fps did not beat CTB 64 {at64:.2} fps on {cores} threads"
133+ );
134+}
135+
96 #[test]136 #[test]
97 fn speedup_curve() {137 fn speedup_curve() {
98 if cfg!(debug_assertions) {138 if cfg!(debug_assertions) {