forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

encoder.rs647 lines, 26.3 KiBHistoryRawDownload
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
26use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes};
27use ec_core::color::ContentLight;
28use ec_core::error::{Error, Result};
29use ec_core::frame::{PixelFormat, Plane, VideoFrame};
30use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b};
31use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel};
32use ec_h265_syntax::slice::SliceHeader;
33use ec_h265_syntax::vui::{VideoSignalType, VuiParameters};
34use ec_h265_syntax::{Pps, Sps, Vps, sei};
35use std::sync::Mutex;
36use std::sync::atomic::{AtomicUsize, Ordering};
37
38use crate::cabac::{CabacEncoder, Contexts};
39
40/// How the encoder picks QP for a picture.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub 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)]
52pub 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, 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.
75 pub ctb_size: usize,
76 /// How many of the 35 intra modes get a full rate-distortion trial, on top
77 /// of the most probable mode, which always gets one.
78 pub rdo_candidates: usize,
79 /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a
80 /// *coarser* search that is not always faster: on real pictures the 8x8
81 /// blocks pay for their search in residual bits (measured: -27% bits and
82 /// +1.5 dB at QP 22 on a 1080p camera frame, at the same wall time), which
83 /// is why 8 is the default.
84 pub min_cu_size: usize,
85 /// What the samples mean, written into the VUI.
86 pub video_signal_type: Option<VideoSignalType>,
87 /// Sample aspect ratio.
88 pub sample_aspect_ratio: Option<(u16, u16)>,
89 /// `(num_units_in_tick, time_scale)`; also picks the level.
90 pub timing: Option<(u32, u32)>,
91 /// HDR mastering metadata, written as prefix SEI.
92 pub content_light: ContentLight,
93 /// Emit the decoded picture hash SEI (MD5 of the reconstruction).
94 pub picture_hash: bool,
95 /// Return the reconstruction alongside the bitstream.
96 pub keep_recon: bool,
97}
98
99impl EncoderConfig {
100 /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs
101 /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64).
102 pub fn new(width: u32, height: u32) -> EncoderConfig {
103 EncoderConfig {
104 width,
105 height,
106 rate_control: RateControl::ConstantQp(27),
107 threads: 0,
108 ctb_size: 32,
109 rdo_candidates: 2,
110 min_cu_size: 8,
111 video_signal_type: None,
112 sample_aspect_ratio: None,
113 timing: None,
114 content_light: ContentLight::default(),
115 picture_hash: false,
116 keep_recon: false,
117 }
118 }
119}
120
121/// One coded picture.
122#[derive(Debug, Clone)]
123pub struct EncodedPicture {
124 /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice.
125 pub au: Vec<u8>,
126 /// The quantiser the picture was coded at.
127 pub qp: i32,
128 /// The reconstruction, cropped to the displayed size, when
129 /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a
130 /// conformant decoder produces, because the in-loop filters are off.
131 pub recon: Option<VideoFrame>,
132}
133
134/// An intra-only HEVC encoder.
135pub struct Encoder {
136 cfg: EncoderConfig,
137 vps: Vps,
138 sps: Sps,
139 pps: Pps,
140 coded_width: usize,
141 coded_height: usize,
142 threads: usize,
143}
144
145/// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model
146/// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6).
147const BPP_AT_QP27: f64 = 0.6;
148
149impl Encoder {
150 /// Build an encoder, refusing dimensions it cannot code.
151 pub fn new(cfg: EncoderConfig) -> Result<Encoder> {
152 if cfg.width < 16 || cfg.height < 16 {
153 return Err(Error::unsupported(
154 format!("HEVC encode of {}x{}", cfg.width, cfg.height),
155 "pictures below 16x16 have no coding tree",
156 ));
157 }
158 if cfg.ctb_size != 64 && cfg.ctb_size != 32 {
159 return Err(Error::unsupported(
160 format!("HEVC coding tree block of {}", cfg.ctb_size),
161 "this encoder codes 64x64 or 32x32 trees",
162 ));
163 }
164 // The coded picture is a whole number of minimum coding blocks (8x8);
165 // the conformance window crops the padding back off.
166 let coded_width = (cfg.width as usize).next_multiple_of(8);
167 let coded_height = (cfg.height as usize).next_multiple_of(8);
168 let fps = cfg
169 .timing
170 .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1)))
171 .unwrap_or(30.0);
172 let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for(
173 coded_width as u32,
174 coded_height as u32,
175 fps,
176 ));
177 let vps = Vps {
178 id: 0,
179 ptl,
180 max_dec_pic_buffering_minus1: 0,
181 max_num_reorder_pics: 0,
182 };
183 let log2_ctb = cfg.ctb_size.trailing_zeros();
184 let sps = Sps {
185 vps_id: 0,
186 id: 0,
187 chroma_format_idc: 1,
188 separate_colour_plane: false,
189 pic_width_in_luma_samples: coded_width as u32,
190 pic_height_in_luma_samples: coded_height as u32,
191 conf_win: ConformanceWindow {
192 left: 0,
193 right: (coded_width - cfg.width as usize) as u32 / 2,
194 top: 0,
195 bottom: (coded_height - cfg.height as usize) as u32 / 2,
196 },
197 bit_depth_luma_minus8: 0,
198 bit_depth_chroma_minus8: 0,
199 log2_max_poc_lsb_minus4: 4,
200 max_dec_pic_buffering_minus1: 0,
201 max_num_reorder_pics: 0,
202 log2_min_cb_size_minus3: 0,
203 log2_diff_max_min_cb_size: log2_ctb - 3,
204 log2_min_tb_size_minus2: 0,
205 log2_diff_max_min_tb_size: 3,
206 max_transform_hierarchy_depth_inter: 0,
207 max_transform_hierarchy_depth_intra: 0,
208 scaling_list_enabled: false,
209 amp_enabled: false,
210 // No in-loop filters: see `Encoder` docs and the PPS below.
211 sao_enabled: false,
212 pcm_enabled: false,
213 pcm: None,
214 num_short_term_ref_pic_sets: 0,
215 short_term_ref_pic_sets: Vec::new(),
216 long_term_ref_pics_present: false,
217 num_long_term_ref_pics_sps: 0,
218 long_term_ref_pics_sps: Vec::new(),
219 temporal_mvp_enabled: false,
220 strong_intra_smoothing: true,
221 ptl,
222 vui: Some(VuiParameters {
223 sample_aspect_ratio: cfg.sample_aspect_ratio,
224 video_signal_type: cfg.video_signal_type,
225 timing: cfg.timing,
226 }),
227 };
228 let pps = Pps {
229 id: 0,
230 sps_id: 0,
231 entropy_coding_sync_enabled: true,
232 // Deblocking and SAO are both off, which is what makes the
233 // encoder's reconstruction bit-identical to a decoder's output: an
234 // intra-only stream predicts from its own reconstruction only, so
235 // an in-loop filter would change what a decoder shows without
236 // changing what either side predicts from. Turning them off buys
237 // that identity (and the picture-hash check that rides on it)
238 // rather than a fraction of a dB.
239 deblocking_filter_control_present: true,
240 deblocking_filter_disabled: true,
241 loop_filter_across_slices_enabled: false,
242 ..Pps::default()
243 };
244 let threads = if cfg.threads == 0 {
245 std::thread::available_parallelism().map_or(1, |n| n.get())
246 } else {
247 cfg.threads
248 };
249 Ok(Encoder {
250 cfg,
251 vps,
252 sps,
253 pps,
254 coded_width,
255 coded_height,
256 threads,
257 })
258 }
259
260 /// The sequence parameter set this encoder writes.
261 pub fn sps(&self) -> &Sps {
262 &self.sps
263 }
264
265 /// Encode one picture as an IDR access unit.
266 ///
267 /// The frame must be [`PixelFormat::I420`] at the configured size; padding
268 /// to the coded size is this encoder's job, not the caller's.
269 pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> {
270 if frame.format != PixelFormat::I420 {
271 return Err(Error::unsupported(
272 format!("HEVC encode of {:?}", frame.format),
273 "this encoder codes 8-bit 4:2:0 planar",
274 ));
275 }
276 if frame.width != self.cfg.width || frame.height != self.cfg.height {
277 return Err(Error::corrupt(format!(
278 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
279 frame.width, frame.height, self.cfg.width, self.cfg.height
280 )));
281 }
282 let planes: Vec<(&[u8], usize)> = frame
283 .planes
284 .iter()
285 .map(|p: &Plane| (&p.data[..], p.stride))
286 .collect();
287 self.encode_idr_planes(
288 planes[0].0,
289 planes[0].1,
290 planes[1].0,
291 planes[1].1,
292 planes[2].0,
293 planes[2].1,
294 )
295 }
296
297 /// Encode one picture from raw I420 planes with their strides.
298 ///
299 /// This is the surface a compatibility shim maps onto: the planes are the
300 /// *displayed* picture, and the conformance window handles the rest.
301 pub fn encode_idr_planes(
302 &self,
303 y: &[u8],
304 y_stride: usize,
305 cb: &[u8],
306 cb_stride: usize,
307 cr: &[u8],
308 cr_stride: usize,
309 ) -> Result<EncodedPicture> {
310 let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?;
311 let (mut qp, target) = match self.cfg.rate_control {
312 RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None),
313 RateControl::TargetBits(bits) => {
314 let pixels = (self.cfg.width as f64) * (self.cfg.height as f64);
315 let target_bpp = (bits as f64 / pixels).max(1e-4);
316 let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2();
317 ((qp.round() as i32).clamp(0, 51), Some(bits))
318 }
319 };
320 let mut coded = self.code_picture(&padded, qp)?;
321 if let Some(target) = target {
322 let actual = coded.au.len() as f64 * 8.0;
323 let target = target as f64;
324 if (actual - target).abs() / target > 0.25 {
325 // One correction pass, from the measured slope rather than the
326 // model: 6 QP steps is a factor of two in rate.
327 let correction = 6.0 * (actual / target).log2();
328 let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32;
329 let corrected = corrected.clamp(0, 51);
330 if corrected != qp {
331 qp = corrected;
332 coded = self.code_picture(&padded, qp)?;
333 }
334 }
335 }
336 Ok(coded)
337 }
338
339 /// Encode a batch of pictures, each as its own IDR access unit.
340 ///
341 /// The wavefront inside a single picture already uses every core, so this is
342 /// a convenience for callers with a list, not a second layer of threads.
343 pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>>
344 where
345 I: IntoIterator<Item = &'a VideoFrame>,
346 {
347 frames.into_iter().map(|f| self.encode_idr(f)).collect()
348 }
349
350 /// Copy the source into coded-size planes, replicating the edge into the
351 /// padding rather than filling it with black: the padding is coded and then
352 /// cropped away, and a black border would bleed into the last real column
353 /// through the prediction and the transform that straddles it.
354 fn pad_source(
355 &self,
356 y: &[u8],
357 y_stride: usize,
358 cb: &[u8],
359 cb_stride: usize,
360 cr: &[u8],
361 cr_stride: usize,
362 ) -> Result<PaddedSource> {
363 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
364 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
365 let (coded_w, coded_h) = (self.coded_width, self.coded_height);
366 let plane = |src: &[u8],
367 stride: usize,
368 width: usize,
369 height: usize,
370 out_w: usize,
371 out_h: usize|
372 -> Result<Vec<u8>> {
373 if stride < width || src.len() < (height - 1) * stride + width {
374 return Err(Error::corrupt(
375 "HEVC encode: source plane shorter than its stated size".to_string(),
376 ));
377 }
378 let mut out = vec![0u8; out_w * out_h];
379 for row in 0..out_h {
380 let src_row = row.min(height - 1);
381 let line = &src[src_row * stride..src_row * stride + width];
382 let dst = &mut out[row * out_w..row * out_w + out_w];
383 dst[..width].copy_from_slice(line);
384 let edge = line[width - 1];
385 dst[width..].fill(edge);
386 }
387 Ok(out)
388 };
389 Ok(PaddedSource {
390 y: plane(y, y_stride, w, h, coded_w, coded_h)?,
391 cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?,
392 cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?,
393 })
394 }
395
396 /// Code one picture at `qp`, wavefront across CTB rows.
397 fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> {
398 let (width, height) = (self.coded_width, self.coded_height);
399 let ctb = self.cfg.ctb_size;
400 let cols = width.div_ceil(ctb);
401 let rows = height.div_ceil(ctb);
402
403 let mut rec_y = vec![0u8; width * height];
404 let mut rec_cb = vec![0u8; width / 2 * height / 2];
405 let mut rec_cr = vec![0u8; width / 2 * height / 2];
406
407 let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect();
408 let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect();
409 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
410 (0..rows).map(|_| Mutex::new(None)).collect();
411 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
412
413 // One band of the reconstruction per CTB row, handed out by index.
414 let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect();
415 let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect();
416 let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect();
417 let threads = self.threads.min(rows).max(1);
418 // Round-robin: worker t owns rows t, t + threads, ... Each row's
419 // predecessor therefore belongs to another worker that is never waiting
420 // on it, so the wavefront cannot deadlock.
421 let mut per_worker: Vec<Vec<RowAssignment<'_>>> =
422 (0..threads).map(|_| Vec::new()).collect();
423 for row in (0..rows).rev() {
424 let y = bands_y.pop().expect("one band per row");
425 let cb = bands_cb.pop().expect("one band per row");
426 let cr = bands_cr.pop().expect("one band per row");
427 per_worker[row % threads].push((row, y, cb, cr));
428 }
429 for worker in per_worker.iter_mut() {
430 worker.reverse();
431 }
432
433 let slice_qp = qp;
434 std::thread::scope(|scope| {
435 for worker_rows in per_worker {
436 let boundaries = &boundaries;
437 let progress = &progress;
438 let wpp_contexts = &wpp_contexts;
439 let substreams = &substreams;
440 let src = &src;
441 scope.spawn(move || {
442 for (row, band_y, band_cb, band_cr) in worker_rows {
443 let band_y0 = row * ctb;
444 // Wait for the row above to be two CTBs ahead, which is
445 // both the prediction reach and the CABAC sync point.
446 if row > 0 {
447 wait_for(&progress[row - 1], 2.min(cols));
448 }
449 let contexts = if row == 0 || cols < 2 {
450 Contexts::new(slice_qp)
451 } else {
452 wpp_contexts[row - 1]
453 .lock()
454 .ok()
455 .and_then(|c| c.clone())
456 .unwrap_or_else(|| Contexts::new(slice_qp))
457 };
458 let mut enc = CabacEncoder::new(contexts);
459 let mut coder = CtuEncoder::new(
460 SourcePlanes {
461 y: &src.y,
462 cb: &src.cb,
463 cr: &src.cr,
464 },
465 RowState {
466 rec_y: band_y,
467 rec_cb: band_cb,
468 rec_cr: band_cr,
469 publish: &boundaries[row],
470 above: if row == 0 {
471 None
472 } else {
473 Some(&boundaries[row - 1])
474 },
475 },
476 width,
477 height,
478 ctb,
479 band_y0,
480 slice_qp,
481 true,
482 self.cfg.rdo_candidates,
483 self.cfg.min_cu_size.max(8).trailing_zeros(),
484 );
485 for col in 0..cols {
486 if row > 0 {
487 wait_for(&progress[row - 1], (col + 2).min(cols));
488 }
489 coder.encode_ctu(col, &mut enc);
490 if col == 1 {
491 // 9.3.2.1: the row below syncs from the state
492 // after the second CTB of this row.
493 if let Ok(mut slot) = wpp_contexts[row].lock() {
494 *slot = Some(enc.contexts.clone());
495 }
496 }
497 progress[row].0.store(col + 1, Ordering::Release);
498 let last_in_picture = row + 1 == rows && col + 1 == cols;
499 enc.encode_terminate(u32::from(last_in_picture));
500 if !last_in_picture && col + 1 == cols {
501 // end_of_subset_one_bit, then byte alignment.
502 enc.encode_terminate(1);
503 }
504 }
505 if let Ok(mut slot) = substreams[row].lock() {
506 *slot = enc.finish();
507 }
508 }
509 });
510 }
511 });
512
513 let substreams: Vec<Vec<u8>> = substreams
514 .into_iter()
515 .map(|m| m.into_inner().unwrap_or_default())
516 .collect();
517 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
518 let recon = self
519 .cfg
520 .keep_recon
521 .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr));
522 Ok(EncodedPicture { au, qp, recon })
523 }
524
525 /// Parameter sets, optional SEI, and the slice, in Annex-B framing.
526 fn assemble_au(
527 &self,
528 qp: i32,
529 substreams: &[Vec<u8>],
530 rec_y: &[u8],
531 rec_cb: &[u8],
532 rec_cr: &[u8],
533 ) -> Vec<u8> {
534 let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256);
535 write_annex_b(
536 &mut au,
537 NalHeader::new(NalUnitType::Vps),
538 &self.vps.to_rbsp(),
539 true,
540 );
541 write_annex_b(
542 &mut au,
543 NalHeader::new(NalUnitType::Sps),
544 &self.sps.to_rbsp(),
545 true,
546 );
547 write_annex_b(
548 &mut au,
549 NalHeader::new(NalUnitType::Pps),
550 &self.pps.to_rbsp(),
551 true,
552 );
553 if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) {
554 write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true);
555 }
556
557 // Entry points count the bytes as they appear in the NAL, emulation
558 // prevention included. Each substream ends on a byte whose last written
559 // bit is the flush's one bit, so no escape sequence straddles a
560 // boundary and each substream can be measured on its own.
561 let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len());
562 for stream in substreams {
563 let mut out = Vec::with_capacity(stream.len() + 8);
564 escape_rbsp(stream, &mut out);
565 escaped.push(out);
566 }
567 let mut header = SliceHeader::intra(&self.pps, qp - 26);
568 header.entry_point_offsets = escaped
569 .iter()
570 .take(escaped.len().saturating_sub(1))
571 .map(|s| s.len() as u32)
572 .collect();
573 let mut writer = ec_core::bitio::BitWriter::with_capacity(64);
574 header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl);
575 let mut rbsp = writer.into_bytes();
576 for stream in substreams {
577 rbsp.extend_from_slice(stream);
578 }
579 write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true);
580
581 if self.cfg.picture_hash {
582 let (w, h) = (self.coded_width, self.coded_height);
583 let rbsp = sei::decoded_picture_hash_rbsp(&[
584 (rec_y, w, w, h),
585 (rec_cb, w / 2, w / 2, h / 2),
586 (rec_cr, w / 2, w / 2, h / 2),
587 ]);
588 write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false);
589 }
590 au
591 }
592
593 fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame {
594 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
595 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
596 let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> {
597 let mut out = Vec::with_capacity(width * height);
598 for row in 0..height {
599 out.extend_from_slice(&src[row * stride..row * stride + width]);
600 }
601 out
602 };
603 let planes = vec![
604 Plane::new(crop(rec_y, self.coded_width, w, h), w),
605 Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw),
606 Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw),
607 ];
608 VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)
609 .expect("cropped planes are exactly the size I420 asks for")
610 }
611}
612
613/// A progress counter on its own cache line.
614///
615/// Twelve workers polling twelve counters packed eight to a line spend their
616/// time invalidating each other's caches instead of coding; the padding is the
617/// difference between a wavefront and a contention benchmark.
618#[repr(align(64))]
619struct Progress(AtomicUsize);
620
621/// Spin, then yield, then sleep until a row's progress counter reaches `target`.
622///
623/// A worker that spins hard is a worker holding a core the wavefront needs
624/// somewhere else, so the wait backs off to a sleep at roughly the granularity
625/// of one coding tree block.
626fn wait_for(counter: &Progress, target: usize) {
627 let mut spins = 0u32;
628 while counter.0.load(Ordering::Acquire) < target {
629 if spins < 128 {
630 std::hint::spin_loop();
631 } else if spins < 256 {
632 std::thread::yield_now();
633 } else {
634 std::thread::sleep(std::time::Duration::from_micros(50));
635 }
636 spins += 1;
637 }
638}
639
640/// One CTB row handed to a worker: its index and its band of each plane.
641type RowAssignment<'a> = (usize, &'a mut [u8], &'a mut [u8], &'a mut [u8]);
642
643struct PaddedSource {
644 y: Vec<u8>,
645 cb: Vec<u8>,
646 cr: Vec<u8>,
647}