forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust378.6 MiBe63caffTahinli3 months ago103 commits

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