Wavefront-parallel intra IDR encoder
Browse files at this commitfa29faa58c1f38977999776c709bdc764afa28f7Parent: d43b87f- feat
- wavefront-parallel intra IDR encoder
5 changed files +886 -1
- crates/ec-h265/src/encoder.rs +604 -0
- crates/ec-h265/src/lib.rs +2 -1
- crates/ec-h265/tests/common/mod.rs +38 -0
- crates/ec-h265/tests/conformance.rs +166 -0
- crates/ec-h265/tests/perf.rs +76 -0
crates/ec-h265/src/encoder.rsadded+604 -0
| @@ -0,0 +1,604 @@ | ||
| 1 | +//! The encoder API and the wavefront that makes one call use every core. | |
| 2 | +//! | |
| 3 | +//! # Parallelism | |
| 4 | +//! | |
| 5 | +//! `entropy_coding_sync_enabled_flag` (WPP) is on. Each CTB row is a substream | |
| 6 | +//! with its own entry point; a worker may start row `r` once row `r - 1` is two | |
| 7 | +//! CTBs ahead, which is exactly the dependency intra prediction has (a block | |
| 8 | +//! reaches at most one CTB to the right on the line above) and exactly what the | |
| 9 | +//! CABAC context sync in 9.3.2.1 assumes. Rows are handed to `threads` workers | |
| 10 | +//! round-robin, and every worker owns: | |
| 11 | +//! | |
| 12 | +//! - its own band of the reconstruction (`chunks_mut`, no sharing), | |
| 13 | +//! - its own substream buffer and CABAC engine, | |
| 14 | +//! - a published bottom line ([`RowBoundary`]) the row below reads through | |
| 15 | +//! atomics, plus a progress counter. | |
| 16 | +//! | |
| 17 | +//! No `unsafe`, no scoped raw pointers, no rayon: the only shared mutable state | |
| 18 | +//! is one atomic byte per boundary sample and one atomic counter per row. | |
| 19 | +//! | |
| 20 | +//! # What comes out | |
| 21 | +//! | |
| 22 | +//! One Annex-B access unit per picture, carrying VPS, SPS and PPS every time — | |
| 23 | +//! every picture is an IDR, so every picture is a seek point, and a seek point | |
| 24 | +//! whose parameter sets are elsewhere is not one. | |
| 25 | + | |
| 26 | +use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes}; | |
| 27 | +use ec_core::color::ContentLight; | |
| 28 | +use ec_core::error::{Error, Result}; | |
| 29 | +use ec_core::frame::{PixelFormat, Plane, VideoFrame}; | |
| 30 | +use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b}; | |
| 31 | +use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel}; | |
| 32 | +use ec_h265_syntax::slice::SliceHeader; | |
| 33 | +use ec_h265_syntax::vui::{VideoSignalType, VuiParameters}; | |
| 34 | +use ec_h265_syntax::{Pps, Sps, Vps, sei}; | |
| 35 | +use std::sync::Mutex; | |
| 36 | +use std::sync::atomic::{AtomicUsize, Ordering}; | |
| 37 | + | |
| 38 | +use crate::cabac::{CabacEncoder, Contexts}; | |
| 39 | + | |
| 40 | +/// How the encoder picks QP for a picture. | |
| 41 | +#[derive(Debug, Clone, Copy, PartialEq)] | |
| 42 | +pub enum RateControl { | |
| 43 | + /// One fixed quantiser for every picture. | |
| 44 | + ConstantQp(i32), | |
| 45 | + /// Aim for `bits` per picture: a model picks the QP, and a picture that | |
| 46 | + /// lands more than 25% off is coded a second time at a corrected QP. | |
| 47 | + TargetBits(u64), | |
| 48 | +} | |
| 49 | + | |
| 50 | +/// Encoder settings. | |
| 51 | +#[derive(Debug, Clone)] | |
| 52 | +pub struct EncoderConfig { | |
| 53 | + /// Displayed width; the coded picture is padded up to a whole number of | |
| 54 | + /// minimum coding blocks and cropped back by the conformance window. | |
| 55 | + pub width: u32, | |
| 56 | + /// Displayed height. | |
| 57 | + pub height: u32, | |
| 58 | + /// Quantiser or bit target. | |
| 59 | + pub rate_control: RateControl, | |
| 60 | + /// Worker threads; 0 means "as many as the machine has". | |
| 61 | + pub threads: usize, | |
| 62 | + /// Coding tree block size, 64 (default) or 32. | |
| 63 | + pub ctb_size: usize, | |
| 64 | + /// How many of the 35 intra modes get a full rate-distortion trial. | |
| 65 | + pub rdo_candidates: usize, | |
| 66 | + /// What the samples mean, written into the VUI. | |
| 67 | + pub video_signal_type: Option<VideoSignalType>, | |
| 68 | + /// Sample aspect ratio. | |
| 69 | + pub sample_aspect_ratio: Option<(u16, u16)>, | |
| 70 | + /// `(num_units_in_tick, time_scale)`; also picks the level. | |
| 71 | + pub timing: Option<(u32, u32)>, | |
| 72 | + /// HDR mastering metadata, written as prefix SEI. | |
| 73 | + pub content_light: ContentLight, | |
| 74 | + /// Emit the decoded picture hash SEI (MD5 of the reconstruction). | |
| 75 | + pub picture_hash: bool, | |
| 76 | + /// Return the reconstruction alongside the bitstream. | |
| 77 | + pub keep_recon: bool, | |
| 78 | +} | |
| 79 | + | |
| 80 | +impl EncoderConfig { | |
| 81 | + /// Defaults for `width x height`: constant QP 27, every core, 64x64 CTBs. | |
| 82 | + pub fn new(width: u32, height: u32) -> EncoderConfig { | |
| 83 | + EncoderConfig { | |
| 84 | + width, | |
| 85 | + height, | |
| 86 | + rate_control: RateControl::ConstantQp(27), | |
| 87 | + threads: 0, | |
| 88 | + ctb_size: 64, | |
| 89 | + rdo_candidates: 2, | |
| 90 | + video_signal_type: None, | |
| 91 | + sample_aspect_ratio: None, | |
| 92 | + timing: None, | |
| 93 | + content_light: ContentLight::default(), | |
| 94 | + picture_hash: false, | |
| 95 | + keep_recon: false, | |
| 96 | + } | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 100 | +/// One coded picture. | |
| 101 | +#[derive(Debug, Clone)] | |
| 102 | +pub struct EncodedPicture { | |
| 103 | + /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice. | |
| 104 | + pub au: Vec<u8>, | |
| 105 | + /// The quantiser the picture was coded at. | |
| 106 | + pub qp: i32, | |
| 107 | + /// The reconstruction, cropped to the displayed size, when | |
| 108 | + /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a | |
| 109 | + /// conformant decoder produces, because the in-loop filters are off. | |
| 110 | + pub recon: Option<VideoFrame>, | |
| 111 | +} | |
| 112 | + | |
| 113 | +/// An intra-only HEVC encoder. | |
| 114 | +pub struct Encoder { | |
| 115 | + cfg: EncoderConfig, | |
| 116 | + vps: Vps, | |
| 117 | + sps: Sps, | |
| 118 | + pps: Pps, | |
| 119 | + coded_width: usize, | |
| 120 | + coded_height: usize, | |
| 121 | + threads: usize, | |
| 122 | +} | |
| 123 | + | |
| 124 | +/// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model | |
| 125 | +/// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6). | |
| 126 | +const BPP_AT_QP27: f64 = 0.6; | |
| 127 | + | |
| 128 | +impl Encoder { | |
| 129 | + /// Build an encoder, refusing dimensions it cannot code. | |
| 130 | + pub fn new(cfg: EncoderConfig) -> Result<Encoder> { | |
| 131 | + if cfg.width < 16 || cfg.height < 16 { | |
| 132 | + return Err(Error::unsupported( | |
| 133 | + format!("HEVC encode of {}x{}", cfg.width, cfg.height), | |
| 134 | + "pictures below 16x16 have no coding tree", | |
| 135 | + )); | |
| 136 | + } | |
| 137 | + if cfg.ctb_size != 64 && cfg.ctb_size != 32 { | |
| 138 | + return Err(Error::unsupported( | |
| 139 | + format!("HEVC coding tree block of {}", cfg.ctb_size), | |
| 140 | + "this encoder codes 64x64 or 32x32 trees", | |
| 141 | + )); | |
| 142 | + } | |
| 143 | + // The coded picture is a whole number of minimum coding blocks (8x8); | |
| 144 | + // the conformance window crops the padding back off. | |
| 145 | + let coded_width = (cfg.width as usize).next_multiple_of(8); | |
| 146 | + let coded_height = (cfg.height as usize).next_multiple_of(8); | |
| 147 | + let fps = cfg | |
| 148 | + .timing | |
| 149 | + .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1))) | |
| 150 | + .unwrap_or(30.0); | |
| 151 | + let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for( | |
| 152 | + coded_width as u32, | |
| 153 | + coded_height as u32, | |
| 154 | + fps, | |
| 155 | + )); | |
| 156 | + let vps = Vps { | |
| 157 | + id: 0, | |
| 158 | + ptl, | |
| 159 | + max_dec_pic_buffering_minus1: 0, | |
| 160 | + max_num_reorder_pics: 0, | |
| 161 | + }; | |
| 162 | + let log2_ctb = cfg.ctb_size.trailing_zeros(); | |
| 163 | + let sps = Sps { | |
| 164 | + vps_id: 0, | |
| 165 | + id: 0, | |
| 166 | + chroma_format_idc: 1, | |
| 167 | + separate_colour_plane: false, | |
| 168 | + pic_width_in_luma_samples: coded_width as u32, | |
| 169 | + pic_height_in_luma_samples: coded_height as u32, | |
| 170 | + conf_win: ConformanceWindow { | |
| 171 | + left: 0, | |
| 172 | + right: (coded_width - cfg.width as usize) as u32 / 2, | |
| 173 | + top: 0, | |
| 174 | + bottom: (coded_height - cfg.height as usize) as u32 / 2, | |
| 175 | + }, | |
| 176 | + bit_depth_luma_minus8: 0, | |
| 177 | + bit_depth_chroma_minus8: 0, | |
| 178 | + log2_max_poc_lsb_minus4: 4, | |
| 179 | + max_dec_pic_buffering_minus1: 0, | |
| 180 | + max_num_reorder_pics: 0, | |
| 181 | + log2_min_cb_size_minus3: 0, | |
| 182 | + log2_diff_max_min_cb_size: log2_ctb - 3, | |
| 183 | + log2_min_tb_size_minus2: 0, | |
| 184 | + log2_diff_max_min_tb_size: 3, | |
| 185 | + max_transform_hierarchy_depth_inter: 0, | |
| 186 | + max_transform_hierarchy_depth_intra: 0, | |
| 187 | + scaling_list_enabled: false, | |
| 188 | + amp_enabled: false, | |
| 189 | + // No in-loop filters: see `Encoder` docs and the PPS below. | |
| 190 | + sao_enabled: false, | |
| 191 | + pcm_enabled: false, | |
| 192 | + num_short_term_ref_pic_sets: 0, | |
| 193 | + long_term_ref_pics_present: false, | |
| 194 | + num_long_term_ref_pics_sps: 0, | |
| 195 | + temporal_mvp_enabled: false, | |
| 196 | + strong_intra_smoothing: true, | |
| 197 | + ptl, | |
| 198 | + vui: Some(VuiParameters { | |
| 199 | + sample_aspect_ratio: cfg.sample_aspect_ratio, | |
| 200 | + video_signal_type: cfg.video_signal_type, | |
| 201 | + timing: cfg.timing, | |
| 202 | + }), | |
| 203 | + }; | |
| 204 | + let pps = Pps { | |
| 205 | + id: 0, | |
| 206 | + sps_id: 0, | |
| 207 | + entropy_coding_sync_enabled: true, | |
| 208 | + // Deblocking and SAO are both off, which is what makes the | |
| 209 | + // encoder's reconstruction bit-identical to a decoder's output: an | |
| 210 | + // intra-only stream predicts from its own reconstruction only, so | |
| 211 | + // an in-loop filter would change what a decoder shows without | |
| 212 | + // changing what either side predicts from. Turning them off buys | |
| 213 | + // that identity (and the picture-hash check that rides on it) | |
| 214 | + // rather than a fraction of a dB. | |
| 215 | + deblocking_filter_control_present: true, | |
| 216 | + deblocking_filter_disabled: true, | |
| 217 | + loop_filter_across_slices_enabled: false, | |
| 218 | + ..Pps::default() | |
| 219 | + }; | |
| 220 | + let threads = if cfg.threads == 0 { | |
| 221 | + std::thread::available_parallelism().map_or(1, |n| n.get()) | |
| 222 | + } else { | |
| 223 | + cfg.threads | |
| 224 | + }; | |
| 225 | + Ok(Encoder { | |
| 226 | + cfg, | |
| 227 | + vps, | |
| 228 | + sps, | |
| 229 | + pps, | |
| 230 | + coded_width, | |
| 231 | + coded_height, | |
| 232 | + threads, | |
| 233 | + }) | |
| 234 | + } | |
| 235 | + | |
| 236 | + /// The sequence parameter set this encoder writes. | |
| 237 | + pub fn sps(&self) -> &Sps { | |
| 238 | + &self.sps | |
| 239 | + } | |
| 240 | + | |
| 241 | + /// Encode one picture as an IDR access unit. | |
| 242 | + /// | |
| 243 | + /// The frame must be [`PixelFormat::I420`] at the configured size; padding | |
| 244 | + /// to the coded size is this encoder's job, not the caller's. | |
| 245 | + pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> { | |
| 246 | + if frame.format != PixelFormat::I420 { | |
| 247 | + return Err(Error::unsupported( | |
| 248 | + format!("HEVC encode of {:?}", frame.format), | |
| 249 | + "this encoder codes 8-bit 4:2:0 planar", | |
| 250 | + )); | |
| 251 | + } | |
| 252 | + if frame.width != self.cfg.width || frame.height != self.cfg.height { | |
| 253 | + return Err(Error::corrupt(format!( | |
| 254 | + "HEVC encode: frame is {}x{}, encoder configured for {}x{}", | |
| 255 | + frame.width, frame.height, self.cfg.width, self.cfg.height | |
| 256 | + ))); | |
| 257 | + } | |
| 258 | + let planes: Vec<(&[u8], usize)> = frame | |
| 259 | + .planes | |
| 260 | + .iter() | |
| 261 | + .map(|p: &Plane| (&p.data[..], p.stride)) | |
| 262 | + .collect(); | |
| 263 | + self.encode_idr_planes( | |
| 264 | + planes[0].0, | |
| 265 | + planes[0].1, | |
| 266 | + planes[1].0, | |
| 267 | + planes[1].1, | |
| 268 | + planes[2].0, | |
| 269 | + planes[2].1, | |
| 270 | + ) | |
| 271 | + } | |
| 272 | + | |
| 273 | + /// Encode one picture from raw I420 planes with their strides. | |
| 274 | + /// | |
| 275 | + /// This is the surface a compatibility shim maps onto: the planes are the | |
| 276 | + /// *displayed* picture, and the conformance window handles the rest. | |
| 277 | + pub fn encode_idr_planes( | |
| 278 | + &self, | |
| 279 | + y: &[u8], | |
| 280 | + y_stride: usize, | |
| 281 | + cb: &[u8], | |
| 282 | + cb_stride: usize, | |
| 283 | + cr: &[u8], | |
| 284 | + cr_stride: usize, | |
| 285 | + ) -> Result<EncodedPicture> { | |
| 286 | + let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?; | |
| 287 | + let (mut qp, target) = match self.cfg.rate_control { | |
| 288 | + RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None), | |
| 289 | + RateControl::TargetBits(bits) => { | |
| 290 | + let pixels = (self.cfg.width as f64) * (self.cfg.height as f64); | |
| 291 | + let target_bpp = (bits as f64 / pixels).max(1e-4); | |
| 292 | + let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2(); | |
| 293 | + ((qp.round() as i32).clamp(0, 51), Some(bits)) | |
| 294 | + } | |
| 295 | + }; | |
| 296 | + let mut coded = self.code_picture(&padded, qp)?; | |
| 297 | + if let Some(target) = target { | |
| 298 | + let actual = coded.au.len() as f64 * 8.0; | |
| 299 | + let target = target as f64; | |
| 300 | + if (actual - target).abs() / target > 0.25 { | |
| 301 | + // One correction pass, from the measured slope rather than the | |
| 302 | + // model: 6 QP steps is a factor of two in rate. | |
| 303 | + let correction = 6.0 * (actual / target).log2(); | |
| 304 | + let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32; | |
| 305 | + let corrected = corrected.clamp(0, 51); | |
| 306 | + if corrected != qp { | |
| 307 | + qp = corrected; | |
| 308 | + coded = self.code_picture(&padded, qp)?; | |
| 309 | + } | |
| 310 | + } | |
| 311 | + } | |
| 312 | + Ok(coded) | |
| 313 | + } | |
| 314 | + | |
| 315 | + /// Encode a batch of pictures, each as its own IDR access unit. | |
| 316 | + /// | |
| 317 | + /// The wavefront inside a single picture already uses every core, so this is | |
| 318 | + /// a convenience for callers with a list, not a second layer of threads. | |
| 319 | + pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>> | |
| 320 | + where | |
| 321 | + I: IntoIterator<Item = &'a VideoFrame>, | |
| 322 | + { | |
| 323 | + frames.into_iter().map(|f| self.encode_idr(f)).collect() | |
| 324 | + } | |
| 325 | + | |
| 326 | + /// Copy the source into coded-size planes, replicating the edge into the | |
| 327 | + /// padding rather than filling it with black: the padding is coded and then | |
| 328 | + /// cropped away, and a black border would bleed into the last real column | |
| 329 | + /// through the prediction and the transform that straddles it. | |
| 330 | + fn pad_source( | |
| 331 | + &self, | |
| 332 | + y: &[u8], | |
| 333 | + y_stride: usize, | |
| 334 | + cb: &[u8], | |
| 335 | + cb_stride: usize, | |
| 336 | + cr: &[u8], | |
| 337 | + cr_stride: usize, | |
| 338 | + ) -> Result<PaddedSource> { | |
| 339 | + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); | |
| 340 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 341 | + let (coded_w, coded_h) = (self.coded_width, self.coded_height); | |
| 342 | + let plane = |src: &[u8], stride: usize, width: usize, height: usize, out_w: usize, out_h: usize| -> Result<Vec<u8>> { | |
| 343 | + if stride < width || src.len() < (height - 1) * stride + width { | |
| 344 | + return Err(Error::corrupt( | |
| 345 | + "HEVC encode: source plane shorter than its stated size".to_string(), | |
| 346 | + )); | |
| 347 | + } | |
| 348 | + let mut out = vec![0u8; out_w * out_h]; | |
| 349 | + for row in 0..out_h { | |
| 350 | + let src_row = row.min(height - 1); | |
| 351 | + let line = &src[src_row * stride..src_row * stride + width]; | |
| 352 | + let dst = &mut out[row * out_w..row * out_w + out_w]; | |
| 353 | + dst[..width].copy_from_slice(line); | |
| 354 | + let edge = line[width - 1]; | |
| 355 | + dst[width..].fill(edge); | |
| 356 | + } | |
| 357 | + Ok(out) | |
| 358 | + }; | |
| 359 | + Ok(PaddedSource { | |
| 360 | + y: plane(y, y_stride, w, h, coded_w, coded_h)?, | |
| 361 | + cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?, | |
| 362 | + cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?, | |
| 363 | + }) | |
| 364 | + } | |
| 365 | + | |
| 366 | + /// Code one picture at `qp`, wavefront across CTB rows. | |
| 367 | + fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> { | |
| 368 | + let (width, height) = (self.coded_width, self.coded_height); | |
| 369 | + let ctb = self.cfg.ctb_size; | |
| 370 | + let cols = width.div_ceil(ctb); | |
| 371 | + let rows = height.div_ceil(ctb); | |
| 372 | + | |
| 373 | + let mut rec_y = vec![0u8; width * height]; | |
| 374 | + let mut rec_cb = vec![0u8; width / 2 * height / 2]; | |
| 375 | + let mut rec_cr = vec![0u8; width / 2 * height / 2]; | |
| 376 | + | |
| 377 | + let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect(); | |
| 378 | + let progress: Vec<AtomicUsize> = (0..rows).map(|_| AtomicUsize::new(0)).collect(); | |
| 379 | + let wpp_contexts: Vec<Mutex<Option<Contexts>>> = | |
| 380 | + (0..rows).map(|_| Mutex::new(None)).collect(); | |
| 381 | + let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); | |
| 382 | + | |
| 383 | + // One band of the reconstruction per CTB row, handed out by index. | |
| 384 | + let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect(); | |
| 385 | + let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect(); | |
| 386 | + let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect(); | |
| 387 | + let threads = self.threads.min(rows).max(1); | |
| 388 | + // Round-robin: worker t owns rows t, t + threads, ... Each row's | |
| 389 | + // predecessor therefore belongs to another worker that is never waiting | |
| 390 | + // on it, so the wavefront cannot deadlock. | |
| 391 | + let mut per_worker: Vec<Vec<(usize, &mut [u8], &mut [u8], &mut [u8])>> = | |
| 392 | + (0..threads).map(|_| Vec::new()).collect(); | |
| 393 | + for row in (0..rows).rev() { | |
| 394 | + let y = bands_y.pop().expect("one band per row"); | |
| 395 | + let cb = bands_cb.pop().expect("one band per row"); | |
| 396 | + let cr = bands_cr.pop().expect("one band per row"); | |
| 397 | + per_worker[row % threads].push((row, y, cb, cr)); | |
| 398 | + } | |
| 399 | + for worker in per_worker.iter_mut() { | |
| 400 | + worker.reverse(); | |
| 401 | + } | |
| 402 | + | |
| 403 | + let slice_qp = qp; | |
| 404 | + std::thread::scope(|scope| { | |
| 405 | + for worker_rows in per_worker { | |
| 406 | + let boundaries = &boundaries; | |
| 407 | + let progress = &progress; | |
| 408 | + let wpp_contexts = &wpp_contexts; | |
| 409 | + let substreams = &substreams; | |
| 410 | + let src = &src; | |
| 411 | + scope.spawn(move || { | |
| 412 | + for (row, band_y, band_cb, band_cr) in worker_rows { | |
| 413 | + let band_y0 = row * ctb; | |
| 414 | + // Wait for the row above to be two CTBs ahead, which is | |
| 415 | + // both the prediction reach and the CABAC sync point. | |
| 416 | + if row > 0 { | |
| 417 | + wait_for(&progress[row - 1], 2.min(cols)); | |
| 418 | + } | |
| 419 | + let contexts = if row == 0 || cols < 2 { | |
| 420 | + Contexts::new(slice_qp) | |
| 421 | + } else { | |
| 422 | + wpp_contexts[row - 1] | |
| 423 | + .lock() | |
| 424 | + .ok() | |
| 425 | + .and_then(|c| c.clone()) | |
| 426 | + .unwrap_or_else(|| Contexts::new(slice_qp)) | |
| 427 | + }; | |
| 428 | + let mut enc = CabacEncoder::new(contexts); | |
| 429 | + let mut coder = CtuEncoder::new( | |
| 430 | + SourcePlanes { | |
| 431 | + y: &src.y, | |
| 432 | + cb: &src.cb, | |
| 433 | + cr: &src.cr, | |
| 434 | + }, | |
| 435 | + RowState { | |
| 436 | + rec_y: band_y, | |
| 437 | + rec_cb: band_cb, | |
| 438 | + rec_cr: band_cr, | |
| 439 | + publish: &boundaries[row], | |
| 440 | + above: if row == 0 { | |
| 441 | + None | |
| 442 | + } else { | |
| 443 | + Some(&boundaries[row - 1]) | |
| 444 | + }, | |
| 445 | + }, | |
| 446 | + width, | |
| 447 | + height, | |
| 448 | + ctb, | |
| 449 | + band_y0, | |
| 450 | + slice_qp, | |
| 451 | + true, | |
| 452 | + self.cfg.rdo_candidates, | |
| 453 | + ); | |
| 454 | + for col in 0..cols { | |
| 455 | + if row > 0 { | |
| 456 | + wait_for(&progress[row - 1], (col + 2).min(cols)); | |
| 457 | + } | |
| 458 | + coder.encode_ctu(col, &mut enc); | |
| 459 | + if col == 1 { | |
| 460 | + // 9.3.2.1: the row below syncs from the state | |
| 461 | + // after the second CTB of this row. | |
| 462 | + if let Ok(mut slot) = wpp_contexts[row].lock() { | |
| 463 | + *slot = Some(enc.contexts.clone()); | |
| 464 | + } | |
| 465 | + } | |
| 466 | + progress[row].store(col + 1, Ordering::Release); | |
| 467 | + let last_in_picture = row + 1 == rows && col + 1 == cols; | |
| 468 | + enc.encode_terminate(u32::from(last_in_picture)); | |
| 469 | + if !last_in_picture && col + 1 == cols { | |
| 470 | + // end_of_subset_one_bit, then byte alignment. | |
| 471 | + enc.encode_terminate(1); | |
| 472 | + } | |
| 473 | + } | |
| 474 | + if let Ok(mut slot) = substreams[row].lock() { | |
| 475 | + *slot = enc.finish(); | |
| 476 | + } | |
| 477 | + } | |
| 478 | + }); | |
| 479 | + } | |
| 480 | + }); | |
| 481 | + | |
| 482 | + let substreams: Vec<Vec<u8>> = substreams | |
| 483 | + .into_iter() | |
| 484 | + .map(|m| m.into_inner().unwrap_or_default()) | |
| 485 | + .collect(); | |
| 486 | + let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr); | |
| 487 | + let recon = self | |
| 488 | + .cfg | |
| 489 | + .keep_recon | |
| 490 | + .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr)); | |
| 491 | + Ok(EncodedPicture { au, qp, recon }) | |
| 492 | + } | |
| 493 | + | |
| 494 | + /// Parameter sets, optional SEI, and the slice, in Annex-B framing. | |
| 495 | + fn assemble_au( | |
| 496 | + &self, | |
| 497 | + qp: i32, | |
| 498 | + substreams: &[Vec<u8>], | |
| 499 | + rec_y: &[u8], | |
| 500 | + rec_cb: &[u8], | |
| 501 | + rec_cr: &[u8], | |
| 502 | + ) -> Vec<u8> { | |
| 503 | + let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256); | |
| 504 | + write_annex_b( | |
| 505 | + &mut au, | |
| 506 | + NalHeader::new(NalUnitType::Vps), | |
| 507 | + &self.vps.to_rbsp(), | |
| 508 | + true, | |
| 509 | + ); | |
| 510 | + write_annex_b( | |
| 511 | + &mut au, | |
| 512 | + NalHeader::new(NalUnitType::Sps), | |
| 513 | + &self.sps.to_rbsp(), | |
| 514 | + true, | |
| 515 | + ); | |
| 516 | + write_annex_b( | |
| 517 | + &mut au, | |
| 518 | + NalHeader::new(NalUnitType::Pps), | |
| 519 | + &self.pps.to_rbsp(), | |
| 520 | + true, | |
| 521 | + ); | |
| 522 | + if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) { | |
| 523 | + write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); | |
| 524 | + } | |
| 525 | + | |
| 526 | + // Entry points count the bytes as they appear in the NAL, emulation | |
| 527 | + // prevention included. Each substream ends on a byte whose last written | |
| 528 | + // bit is the flush's one bit, so no escape sequence straddles a | |
| 529 | + // boundary and each substream can be measured on its own. | |
| 530 | + let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len()); | |
| 531 | + for stream in substreams { | |
| 532 | + let mut out = Vec::with_capacity(stream.len() + 8); | |
| 533 | + escape_rbsp(stream, &mut out); | |
| 534 | + escaped.push(out); | |
| 535 | + } | |
| 536 | + let mut header = SliceHeader::intra(&self.pps, qp - 26); | |
| 537 | + header.entry_point_offsets = escaped | |
| 538 | + .iter() | |
| 539 | + .take(escaped.len().saturating_sub(1)) | |
| 540 | + .map(|s| s.len() as u32) | |
| 541 | + .collect(); | |
| 542 | + let mut writer = ec_core::bitio::BitWriter::with_capacity(64); | |
| 543 | + header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl); | |
| 544 | + let mut rbsp = writer.into_bytes(); | |
| 545 | + for stream in substreams { | |
| 546 | + rbsp.extend_from_slice(stream); | |
| 547 | + } | |
| 548 | + write_annex_b( | |
| 549 | + &mut au, | |
| 550 | + NalHeader::new(NalUnitType::IdrWRadl), | |
| 551 | + &rbsp, | |
| 552 | + true, | |
| 553 | + ); | |
| 554 | + | |
| 555 | + if self.cfg.picture_hash { | |
| 556 | + let (w, h) = (self.coded_width, self.coded_height); | |
| 557 | + let rbsp = sei::decoded_picture_hash_rbsp(&[ | |
| 558 | + (rec_y, w, w, h), | |
| 559 | + (rec_cb, w / 2, w / 2, h / 2), | |
| 560 | + (rec_cr, w / 2, w / 2, h / 2), | |
| 561 | + ]); | |
| 562 | + write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); | |
| 563 | + } | |
| 564 | + au | |
| 565 | + } | |
| 566 | + | |
| 567 | + fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame { | |
| 568 | + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); | |
| 569 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 570 | + let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> { | |
| 571 | + let mut out = Vec::with_capacity(width * height); | |
| 572 | + for row in 0..height { | |
| 573 | + out.extend_from_slice(&src[row * stride..row * stride + width]); | |
| 574 | + } | |
| 575 | + out | |
| 576 | + }; | |
| 577 | + let planes = vec![ | |
| 578 | + Plane::new(crop(rec_y, self.coded_width, w, h), w), | |
| 579 | + Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw), | |
| 580 | + Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw), | |
| 581 | + ]; | |
| 582 | + VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes) | |
| 583 | + .expect("cropped planes are exactly the size I420 asks for") | |
| 584 | + } | |
| 585 | +} | |
| 586 | + | |
| 587 | +/// Spin then yield until a row's progress counter reaches `target`. | |
| 588 | +fn wait_for(counter: &AtomicUsize, target: usize) { | |
| 589 | + let mut spins = 0u32; | |
| 590 | + while counter.load(Ordering::Acquire) < target { | |
| 591 | + if spins < 64 { | |
| 592 | + std::hint::spin_loop(); | |
| 593 | + spins += 1; | |
| 594 | + } else { | |
| 595 | + std::thread::yield_now(); | |
| 596 | + } | |
| 597 | + } | |
| 598 | +} | |
| 599 | + | |
| 600 | +struct PaddedSource { | |
| 601 | + y: Vec<u8>, | |
| 602 | + cb: Vec<u8>, | |
| 603 | + cr: Vec<u8>, | |
| 604 | +} |
crates/ec-h265/src/lib.rsmodified+2 -1
| @@ -3,7 +3,8 @@ | ||
| 3 | 3 | #![warn(missing_docs)] |
| 4 | 4 | |
| 5 | 5 | pub mod cabac; |
| 6 | -pub mod ctu; | |
| 7 | 6 | pub mod intra; |
| 7 | +pub mod ctu; | |
| 8 | +pub mod encoder; | |
| 8 | 9 | pub mod residual; |
| 9 | 10 | pub mod transform; |
crates/ec-h265/tests/common/mod.rsadded+38 -0
| @@ -0,0 +1,38 @@ | ||
| 1 | +//! Shared fixtures for the integration tests. | |
| 2 | + | |
| 3 | +use ec_core::frame::{PixelFormat, Plane, VideoFrame}; | |
| 4 | + | |
| 5 | +/// A synthetic picture with gradients, edges and texture — enough structure | |
| 6 | +/// that every intra direction gets used somewhere. | |
| 7 | +pub fn test_frame(width: u32, height: u32, phase: u32) -> VideoFrame { | |
| 8 | + let (w, h) = (width as usize, height as usize); | |
| 9 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 10 | + let mut y = vec![0u8; w * h]; | |
| 11 | + for row in 0..h { | |
| 12 | + for col in 0..w { | |
| 13 | + let diag = ((row + col + phase as usize) % 64) as i32; | |
| 14 | + let ramp = (col * 200 / w) as i32; | |
| 15 | + let ring = if (row * row + col * col) % 977 < 60 { 60 } else { 0 }; | |
| 16 | + let texture = ((row * 7 + col * 13) % 17) as i32 * 3; | |
| 17 | + y[row * w + col] = (16 + ramp + diag / 2 + ring + texture).clamp(0, 255) as u8; | |
| 18 | + } | |
| 19 | + } | |
| 20 | + let mut cb = vec![0u8; cw * ch]; | |
| 21 | + let mut cr = vec![0u8; cw * ch]; | |
| 22 | + for row in 0..ch { | |
| 23 | + for col in 0..cw { | |
| 24 | + cb[row * cw + col] = | |
| 25 | + (128 + (col as i32 * 60 / (cw as i32)) - 30).clamp(0, 255) as u8; | |
| 26 | + cr[row * cw + col] = | |
| 27 | + (128 + (row as i32 * 60 / (ch as i32)) - 30).clamp(0, 255) as u8; | |
| 28 | + } | |
| 29 | + } | |
| 30 | + VideoFrame::try_new( | |
| 31 | + PixelFormat::I420, | |
| 32 | + width, | |
| 33 | + height, | |
| 34 | + vec![Plane::new(y, w), Plane::new(cb, cw), Plane::new(cr, cw)], | |
| 35 | + ) | |
| 36 | + .expect("test frame") | |
| 37 | +} | |
| 38 | + |
crates/ec-h265/tests/conformance.rsadded+166 -0
| @@ -0,0 +1,166 @@ | ||
| 1 | +//! Conformance: every access unit this encoder writes must decode in ffmpeg, | |
| 2 | +//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own | |
| 3 | +//! reconstruction. That equality is the whole point of coding with the in-loop | |
| 4 | +//! filters off: it turns "the file plays" into "the decoder and the encoder | |
| 5 | +//! agree on every sample". | |
| 6 | + | |
| 7 | +mod common; | |
| 8 | + | |
| 9 | +use common::test_frame; | |
| 10 | +use ec_core::frame::VideoFrame; | |
| 11 | +use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; | |
| 12 | +use std::io::Write; | |
| 13 | +use std::path::{Path, PathBuf}; | |
| 14 | +use std::process::Command; | |
| 15 | + | |
| 16 | +fn scratch_dir() -> PathBuf { | |
| 17 | + let dir = std::env::temp_dir().join("ec-h265-tests"); | |
| 18 | + std::fs::create_dir_all(&dir).expect("scratch dir"); | |
| 19 | + dir | |
| 20 | +} | |
| 21 | + | |
| 22 | +fn have_ffmpeg() -> bool { | |
| 23 | + Command::new("ffmpeg") | |
| 24 | + .arg("-version") | |
| 25 | + .output() | |
| 26 | + .map(|o| o.status.success()) | |
| 27 | + .unwrap_or(false) | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. | |
| 31 | +fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> { | |
| 32 | + let out = path.with_extension("yuv"); | |
| 33 | + let status = Command::new("ffmpeg") | |
| 34 | + .args(["-v", "error", "-y", "-i"]) | |
| 35 | + .arg(path) | |
| 36 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | |
| 37 | + .arg(&out) | |
| 38 | + .output() | |
| 39 | + .map_err(|e| e.to_string())?; | |
| 40 | + if !status.status.success() { | |
| 41 | + return Err(String::from_utf8_lossy(&status.stderr).to_string()); | |
| 42 | + } | |
| 43 | + let stderr = String::from_utf8_lossy(&status.stderr).to_string(); | |
| 44 | + if !stderr.trim().is_empty() { | |
| 45 | + return Err(format!("ffmpeg complained: {stderr}")); | |
| 46 | + } | |
| 47 | + std::fs::read(&out).map_err(|e| e.to_string()) | |
| 48 | +} | |
| 49 | + | |
| 50 | +fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { | |
| 51 | + let path = scratch_dir().join(format!("{name}.265")); | |
| 52 | + let mut file = std::fs::File::create(&path).expect("create bitstream"); | |
| 53 | + file.write_all(&picture.au).expect("write bitstream"); | |
| 54 | + path | |
| 55 | +} | |
| 56 | + | |
| 57 | +fn planes_of(frame: &VideoFrame) -> Vec<u8> { | |
| 58 | + let mut out = Vec::new(); | |
| 59 | + let (w, h) = (frame.width as usize, frame.height as usize); | |
| 60 | + for (i, plane) in frame.planes.iter().enumerate() { | |
| 61 | + let (pw, ph) = if i == 0 { | |
| 62 | + (w, h) | |
| 63 | + } else { | |
| 64 | + (w.div_ceil(2), h.div_ceil(2)) | |
| 65 | + }; | |
| 66 | + for row in 0..ph { | |
| 67 | + out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | |
| 68 | + } | |
| 69 | + } | |
| 70 | + out | |
| 71 | +} | |
| 72 | + | |
| 73 | +fn psnr(a: &[u8], b: &[u8]) -> f64 { | |
| 74 | + assert_eq!(a.len(), b.len()); | |
| 75 | + let mse: f64 = a | |
| 76 | + .iter() | |
| 77 | + .zip(b) | |
| 78 | + .map(|(x, y)| { | |
| 79 | + let d = f64::from(*x) - f64::from(*y); | |
| 80 | + d * d | |
| 81 | + }) | |
| 82 | + .sum::<f64>() | |
| 83 | + / a.len() as f64; | |
| 84 | + if mse == 0.0 { | |
| 85 | + 99.0 | |
| 86 | + } else { | |
| 87 | + 10.0 * (255.0 * 255.0 / mse).log10() | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +fn encode(width: u32, height: u32, qp: i32) -> (VideoFrame, EncodedPicture) { | |
| 92 | + let mut cfg = EncoderConfig::new(width, height); | |
| 93 | + cfg.rate_control = RateControl::ConstantQp(qp); | |
| 94 | + cfg.keep_recon = true; | |
| 95 | + cfg.picture_hash = true; | |
| 96 | + let encoder = Encoder::new(cfg).expect("encoder"); | |
| 97 | + let frame = test_frame(width, height, 0); | |
| 98 | + let coded = encoder.encode_idr(&frame).expect("encode"); | |
| 99 | + (frame, coded) | |
| 100 | +} | |
| 101 | + | |
| 102 | +#[test] | |
| 103 | +fn ffmpeg_decodes_bit_exactly_at_every_shape() { | |
| 104 | + if !have_ffmpeg() { | |
| 105 | + eprintln!("skipping: ffmpeg not installed"); | |
| 106 | + return; | |
| 107 | + } | |
| 108 | + // 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), 1916 | |
| 110 | + // 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)] { | |
| 112 | + let (source, coded) = encode(w, h, 27); | |
| 113 | + let path = write_au(&format!("shape-{w}x{h}"), &coded); | |
| 114 | + let decoded = match ffmpeg_decode(&path) { | |
| 115 | + Ok(bytes) => bytes, | |
| 116 | + Err(e) => panic!("{w}x{h}: ffmpeg failed: {e}"), | |
| 117 | + }; | |
| 118 | + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | |
| 119 | + assert_eq!( | |
| 120 | + decoded.len(), | |
| 121 | + recon.len(), | |
| 122 | + "{w}x{h}: decoded {} bytes, reconstruction {} bytes", | |
| 123 | + decoded.len(), | |
| 124 | + recon.len() | |
| 125 | + ); | |
| 126 | + let mismatches = decoded | |
| 127 | + .iter() | |
| 128 | + .zip(&recon) | |
| 129 | + .filter(|(a, b)| a != b) | |
| 130 | + .count(); | |
| 131 | + assert_eq!(mismatches, 0, "{w}x{h}: {mismatches} samples differ"); | |
| 132 | + // And the encode is worth something: PSNR against the source. | |
| 133 | + let quality = psnr(&planes_of(&source), &recon); | |
| 134 | + assert!(quality > 30.0, "{w}x{h}: PSNR {quality:.2} dB at QP 27"); | |
| 135 | + } | |
| 136 | +} | |
| 137 | + | |
| 138 | +#[test] | |
| 139 | +fn quality_rises_as_qp_falls() { | |
| 140 | + let mut previous = 0.0; | |
| 141 | + for &qp in &[40i32, 32, 27, 22] { | |
| 142 | + let (source, coded) = encode(256, 144, qp); | |
| 143 | + let recon = planes_of(coded.recon.as_ref().expect("recon")); | |
| 144 | + let quality = psnr(&planes_of(&source), &recon); | |
| 145 | + assert!( | |
| 146 | + quality > previous, | |
| 147 | + "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" | |
| 148 | + ); | |
| 149 | + previous = quality; | |
| 150 | + } | |
| 151 | + assert!(previous > 40.0, "QP 22 should clear 40 dB, got {previous:.2}"); | |
| 152 | +} | |
| 153 | + | |
| 154 | +#[test] | |
| 155 | +fn threads_do_not_change_the_bitstream() { | |
| 156 | + let mut cfg = EncoderConfig::new(320, 192); | |
| 157 | + cfg.rate_control = RateControl::ConstantQp(30); | |
| 158 | + cfg.threads = 1; | |
| 159 | + let single = Encoder::new(cfg.clone()).unwrap(); | |
| 160 | + cfg.threads = 8; | |
| 161 | + let many = Encoder::new(cfg).unwrap(); | |
| 162 | + let frame = test_frame(320, 192, 3); | |
| 163 | + let a = single.encode_idr(&frame).unwrap(); | |
| 164 | + let b = many.encode_idr(&frame).unwrap(); | |
| 165 | + assert_eq!(a.au, b.au, "wavefront changed the bitstream"); | |
| 166 | +} |
crates/ec-h265/tests/perf.rsadded+76 -0
| @@ -0,0 +1,76 @@ | ||
| 1 | +//! The speed bar, measured the way the claim is made: one `encode_idr` call per | |
| 2 | +//! picture, zero threads on the caller's side. | |
| 3 | +//! | |
| 4 | +//! The incumbent this replaces (`oxideav-h265`) has no threads at all inside its | |
| 5 | +//! encoder — edith fans whole access units out across twelve cores to reach 4.30 | |
| 6 | +//! fps at 1080p. The bar here is to beat that from *inside* one call, so the | |
| 7 | +//! measurement below hands one picture at a time to one encoder. | |
| 8 | +//! | |
| 9 | +//! Run under `--release`; in a debug build this prints the numbers and skips the | |
| 10 | +//! assertion, because a debug build measures the compiler, not the encoder. | |
| 11 | + | |
| 12 | +mod common; | |
| 13 | + | |
| 14 | +use common::test_frame; | |
| 15 | +use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; | |
| 16 | +use std::time::Instant; | |
| 17 | + | |
| 18 | +fn measure(width: u32, height: u32, threads: usize, frames: usize) -> f64 { | |
| 19 | + let mut cfg = EncoderConfig::new(width, height); | |
| 20 | + cfg.rate_control = RateControl::ConstantQp(27); | |
| 21 | + cfg.threads = threads; | |
| 22 | + let encoder = Encoder::new(cfg).expect("encoder"); | |
| 23 | + let pictures: Vec<_> = (0..frames) | |
| 24 | + .map(|i| test_frame(width, height, i as u32 * 7)) | |
| 25 | + .collect(); | |
| 26 | + // One untimed picture so the allocator and the caches are warm. | |
| 27 | + encoder.encode_idr(&pictures[0]).expect("warm-up encode"); | |
| 28 | + let start = Instant::now(); | |
| 29 | + for picture in &pictures { | |
| 30 | + encoder.encode_idr(picture).expect("encode"); | |
| 31 | + } | |
| 32 | + let elapsed = start.elapsed().as_secs_f64(); | |
| 33 | + frames as f64 / elapsed | |
| 34 | +} | |
| 35 | + | |
| 36 | +#[test] | |
| 37 | +fn intra_1080p_beats_the_incumbent_on_twelve_threads() { | |
| 38 | + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); | |
| 39 | + let frames = if cfg!(debug_assertions) { 1 } else { 6 }; | |
| 40 | + let single = measure(1920, 1080, 1, frames); | |
| 41 | + let many = measure(1920, 1080, cores, frames); | |
| 42 | + println!("1080p intra: {single:.2} fps on 1 thread, {many:.2} fps on {cores} threads, speed-up {:.2}x", many / single); | |
| 43 | + if cfg!(debug_assertions) { | |
| 44 | + println!("debug build: not asserting the bar"); | |
| 45 | + return; | |
| 46 | + } | |
| 47 | + assert!( | |
| 48 | + many > 4.30, | |
| 49 | + "1080p on {cores} threads: {many:.2} fps, incumbent bar is 4.30" | |
| 50 | + ); | |
| 51 | + assert!( | |
| 52 | + many > single * 2.0, | |
| 53 | + "wavefront gained only {:.2}x", | |
| 54 | + many / single | |
| 55 | + ); | |
| 56 | +} | |
| 57 | + | |
| 58 | +#[test] | |
| 59 | +fn speedup_curve() { | |
| 60 | + if cfg!(debug_assertions) { | |
| 61 | + println!("debug build: skipping the speed-up curve"); | |
| 62 | + return; | |
| 63 | + } | |
| 64 | + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); | |
| 65 | + let mut base = 0.0; | |
| 66 | + for threads in [1usize, 2, 4, 8, cores] { | |
| 67 | + if threads > cores { | |
| 68 | + continue; | |
| 69 | + } | |
| 70 | + let fps = measure(1920, 1080, threads, 4); | |
| 71 | + if threads == 1 { | |
| 72 | + base = fps; | |
| 73 | + } | |
| 74 | + println!("threads {threads:2}: {fps:6.2} fps speed-up {:.2}x", fps / base); | |
| 75 | + } | |
| 76 | +} |