forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.9 MiB98eeb6cTahinli3 months ago90 commits

encoder.rs632 lines, 25.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, 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 long_term_ref_pics_present: false,
203 num_long_term_ref_pics_sps: 0,
204 temporal_mvp_enabled: false,
205 strong_intra_smoothing: true,
206 ptl,
207 vui: Some(VuiParameters {
208 sample_aspect_ratio: cfg.sample_aspect_ratio,
209 video_signal_type: cfg.video_signal_type,
210 timing: cfg.timing,
211 }),
212 };
213 let pps = Pps {
214 id: 0,
215 sps_id: 0,
216 entropy_coding_sync_enabled: true,
217 // Deblocking and SAO are both off, which is what makes the
218 // encoder's reconstruction bit-identical to a decoder's output: an
219 // intra-only stream predicts from its own reconstruction only, so
220 // an in-loop filter would change what a decoder shows without
221 // changing what either side predicts from. Turning them off buys
222 // that identity (and the picture-hash check that rides on it)
223 // rather than a fraction of a dB.
224 deblocking_filter_control_present: true,
225 deblocking_filter_disabled: true,
226 loop_filter_across_slices_enabled: false,
227 ..Pps::default()
228 };
229 let threads = if cfg.threads == 0 {
230 std::thread::available_parallelism().map_or(1, |n| n.get())
231 } else {
232 cfg.threads
233 };
234 Ok(Encoder {
235 cfg,
236 vps,
237 sps,
238 pps,
239 coded_width,
240 coded_height,
241 threads,
242 })
243 }
244
245 /// The sequence parameter set this encoder writes.
246 pub fn sps(&self) -> &Sps {
247 &self.sps
248 }
249
250 /// Encode one picture as an IDR access unit.
251 ///
252 /// The frame must be [`PixelFormat::I420`] at the configured size; padding
253 /// to the coded size is this encoder's job, not the caller's.
254 pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> {
255 if frame.format != PixelFormat::I420 {
256 return Err(Error::unsupported(
257 format!("HEVC encode of {:?}", frame.format),
258 "this encoder codes 8-bit 4:2:0 planar",
259 ));
260 }
261 if frame.width != self.cfg.width || frame.height != self.cfg.height {
262 return Err(Error::corrupt(format!(
263 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
264 frame.width, frame.height, self.cfg.width, self.cfg.height
265 )));
266 }
267 let planes: Vec<(&[u8], usize)> = frame
268 .planes
269 .iter()
270 .map(|p: &Plane| (&p.data[..], p.stride))
271 .collect();
272 self.encode_idr_planes(
273 planes[0].0,
274 planes[0].1,
275 planes[1].0,
276 planes[1].1,
277 planes[2].0,
278 planes[2].1,
279 )
280 }
281
282 /// Encode one picture from raw I420 planes with their strides.
283 ///
284 /// This is the surface a compatibility shim maps onto: the planes are the
285 /// *displayed* picture, and the conformance window handles the rest.
286 pub fn encode_idr_planes(
287 &self,
288 y: &[u8],
289 y_stride: usize,
290 cb: &[u8],
291 cb_stride: usize,
292 cr: &[u8],
293 cr_stride: usize,
294 ) -> Result<EncodedPicture> {
295 let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?;
296 let (mut qp, target) = match self.cfg.rate_control {
297 RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None),
298 RateControl::TargetBits(bits) => {
299 let pixels = (self.cfg.width as f64) * (self.cfg.height as f64);
300 let target_bpp = (bits as f64 / pixels).max(1e-4);
301 let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2();
302 ((qp.round() as i32).clamp(0, 51), Some(bits))
303 }
304 };
305 let mut coded = self.code_picture(&padded, qp)?;
306 if let Some(target) = target {
307 let actual = coded.au.len() as f64 * 8.0;
308 let target = target as f64;
309 if (actual - target).abs() / target > 0.25 {
310 // One correction pass, from the measured slope rather than the
311 // model: 6 QP steps is a factor of two in rate.
312 let correction = 6.0 * (actual / target).log2();
313 let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32;
314 let corrected = corrected.clamp(0, 51);
315 if corrected != qp {
316 qp = corrected;
317 coded = self.code_picture(&padded, qp)?;
318 }
319 }
320 }
321 Ok(coded)
322 }
323
324 /// Encode a batch of pictures, each as its own IDR access unit.
325 ///
326 /// The wavefront inside a single picture already uses every core, so this is
327 /// a convenience for callers with a list, not a second layer of threads.
328 pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>>
329 where
330 I: IntoIterator<Item = &'a VideoFrame>,
331 {
332 frames.into_iter().map(|f| self.encode_idr(f)).collect()
333 }
334
335 /// Copy the source into coded-size planes, replicating the edge into the
336 /// padding rather than filling it with black: the padding is coded and then
337 /// cropped away, and a black border would bleed into the last real column
338 /// through the prediction and the transform that straddles it.
339 fn pad_source(
340 &self,
341 y: &[u8],
342 y_stride: usize,
343 cb: &[u8],
344 cb_stride: usize,
345 cr: &[u8],
346 cr_stride: usize,
347 ) -> Result<PaddedSource> {
348 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
349 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
350 let (coded_w, coded_h) = (self.coded_width, self.coded_height);
351 let plane = |src: &[u8],
352 stride: usize,
353 width: usize,
354 height: usize,
355 out_w: usize,
356 out_h: usize|
357 -> Result<Vec<u8>> {
358 if stride < width || src.len() < (height - 1) * stride + width {
359 return Err(Error::corrupt(
360 "HEVC encode: source plane shorter than its stated size".to_string(),
361 ));
362 }
363 let mut out = vec![0u8; out_w * out_h];
364 for row in 0..out_h {
365 let src_row = row.min(height - 1);
366 let line = &src[src_row * stride..src_row * stride + width];
367 let dst = &mut out[row * out_w..row * out_w + out_w];
368 dst[..width].copy_from_slice(line);
369 let edge = line[width - 1];
370 dst[width..].fill(edge);
371 }
372 Ok(out)
373 };
374 Ok(PaddedSource {
375 y: plane(y, y_stride, w, h, coded_w, coded_h)?,
376 cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?,
377 cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?,
378 })
379 }
380
381 /// Code one picture at `qp`, wavefront across CTB rows.
382 fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> {
383 let (width, height) = (self.coded_width, self.coded_height);
384 let ctb = self.cfg.ctb_size;
385 let cols = width.div_ceil(ctb);
386 let rows = height.div_ceil(ctb);
387
388 let mut rec_y = vec![0u8; width * height];
389 let mut rec_cb = vec![0u8; width / 2 * height / 2];
390 let mut rec_cr = vec![0u8; width / 2 * height / 2];
391
392 let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect();
393 let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect();
394 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
395 (0..rows).map(|_| Mutex::new(None)).collect();
396 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
397
398 // One band of the reconstruction per CTB row, handed out by index.
399 let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect();
400 let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect();
401 let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect();
402 let threads = self.threads.min(rows).max(1);
403 // Round-robin: worker t owns rows t, t + threads, ... Each row's
404 // predecessor therefore belongs to another worker that is never waiting
405 // on it, so the wavefront cannot deadlock.
406 let mut per_worker: Vec<Vec<RowAssignment<'_>>> =
407 (0..threads).map(|_| Vec::new()).collect();
408 for row in (0..rows).rev() {
409 let y = bands_y.pop().expect("one band per row");
410 let cb = bands_cb.pop().expect("one band per row");
411 let cr = bands_cr.pop().expect("one band per row");
412 per_worker[row % threads].push((row, y, cb, cr));
413 }
414 for worker in per_worker.iter_mut() {
415 worker.reverse();
416 }
417
418 let slice_qp = qp;
419 std::thread::scope(|scope| {
420 for worker_rows in per_worker {
421 let boundaries = &boundaries;
422 let progress = &progress;
423 let wpp_contexts = &wpp_contexts;
424 let substreams = &substreams;
425 let src = &src;
426 scope.spawn(move || {
427 for (row, band_y, band_cb, band_cr) in worker_rows {
428 let band_y0 = row * ctb;
429 // Wait for the row above to be two CTBs ahead, which is
430 // both the prediction reach and the CABAC sync point.
431 if row > 0 {
432 wait_for(&progress[row - 1], 2.min(cols));
433 }
434 let contexts = if row == 0 || cols < 2 {
435 Contexts::new(slice_qp)
436 } else {
437 wpp_contexts[row - 1]
438 .lock()
439 .ok()
440 .and_then(|c| c.clone())
441 .unwrap_or_else(|| Contexts::new(slice_qp))
442 };
443 let mut enc = CabacEncoder::new(contexts);
444 let mut coder = CtuEncoder::new(
445 SourcePlanes {
446 y: &src.y,
447 cb: &src.cb,
448 cr: &src.cr,
449 },
450 RowState {
451 rec_y: band_y,
452 rec_cb: band_cb,
453 rec_cr: band_cr,
454 publish: &boundaries[row],
455 above: if row == 0 {
456 None
457 } else {
458 Some(&boundaries[row - 1])
459 },
460 },
461 width,
462 height,
463 ctb,
464 band_y0,
465 slice_qp,
466 true,
467 self.cfg.rdo_candidates,
468 self.cfg.min_cu_size.max(8).trailing_zeros(),
469 );
470 for col in 0..cols {
471 if row > 0 {
472 wait_for(&progress[row - 1], (col + 2).min(cols));
473 }
474 coder.encode_ctu(col, &mut enc);
475 if col == 1 {
476 // 9.3.2.1: the row below syncs from the state
477 // after the second CTB of this row.
478 if let Ok(mut slot) = wpp_contexts[row].lock() {
479 *slot = Some(enc.contexts.clone());
480 }
481 }
482 progress[row].0.store(col + 1, Ordering::Release);
483 let last_in_picture = row + 1 == rows && col + 1 == cols;
484 enc.encode_terminate(u32::from(last_in_picture));
485 if !last_in_picture && col + 1 == cols {
486 // end_of_subset_one_bit, then byte alignment.
487 enc.encode_terminate(1);
488 }
489 }
490 if let Ok(mut slot) = substreams[row].lock() {
491 *slot = enc.finish();
492 }
493 }
494 });
495 }
496 });
497
498 let substreams: Vec<Vec<u8>> = substreams
499 .into_iter()
500 .map(|m| m.into_inner().unwrap_or_default())
501 .collect();
502 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
503 let recon = self
504 .cfg
505 .keep_recon
506 .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr));
507 Ok(EncodedPicture { au, qp, recon })
508 }
509
510 /// Parameter sets, optional SEI, and the slice, in Annex-B framing.
511 fn assemble_au(
512 &self,
513 qp: i32,
514 substreams: &[Vec<u8>],
515 rec_y: &[u8],
516 rec_cb: &[u8],
517 rec_cr: &[u8],
518 ) -> Vec<u8> {
519 let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256);
520 write_annex_b(
521 &mut au,
522 NalHeader::new(NalUnitType::Vps),
523 &self.vps.to_rbsp(),
524 true,
525 );
526 write_annex_b(
527 &mut au,
528 NalHeader::new(NalUnitType::Sps),
529 &self.sps.to_rbsp(),
530 true,
531 );
532 write_annex_b(
533 &mut au,
534 NalHeader::new(NalUnitType::Pps),
535 &self.pps.to_rbsp(),
536 true,
537 );
538 if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) {
539 write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true);
540 }
541
542 // Entry points count the bytes as they appear in the NAL, emulation
543 // prevention included. Each substream ends on a byte whose last written
544 // bit is the flush's one bit, so no escape sequence straddles a
545 // boundary and each substream can be measured on its own.
546 let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len());
547 for stream in substreams {
548 let mut out = Vec::with_capacity(stream.len() + 8);
549 escape_rbsp(stream, &mut out);
550 escaped.push(out);
551 }
552 let mut header = SliceHeader::intra(&self.pps, qp - 26);
553 header.entry_point_offsets = escaped
554 .iter()
555 .take(escaped.len().saturating_sub(1))
556 .map(|s| s.len() as u32)
557 .collect();
558 let mut writer = ec_core::bitio::BitWriter::with_capacity(64);
559 header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl);
560 let mut rbsp = writer.into_bytes();
561 for stream in substreams {
562 rbsp.extend_from_slice(stream);
563 }
564 write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true);
565
566 if self.cfg.picture_hash {
567 let (w, h) = (self.coded_width, self.coded_height);
568 let rbsp = sei::decoded_picture_hash_rbsp(&[
569 (rec_y, w, w, h),
570 (rec_cb, w / 2, w / 2, h / 2),
571 (rec_cr, w / 2, w / 2, h / 2),
572 ]);
573 write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false);
574 }
575 au
576 }
577
578 fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame {
579 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
580 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
581 let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> {
582 let mut out = Vec::with_capacity(width * height);
583 for row in 0..height {
584 out.extend_from_slice(&src[row * stride..row * stride + width]);
585 }
586 out
587 };
588 let planes = vec![
589 Plane::new(crop(rec_y, self.coded_width, w, h), w),
590 Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw),
591 Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw),
592 ];
593 VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)
594 .expect("cropped planes are exactly the size I420 asks for")
595 }
596}
597
598/// A progress counter on its own cache line.
599///
600/// Twelve workers polling twelve counters packed eight to a line spend their
601/// time invalidating each other's caches instead of coding; the padding is the
602/// difference between a wavefront and a contention benchmark.
603#[repr(align(64))]
604struct Progress(AtomicUsize);
605
606/// Spin, then yield, then sleep until a row's progress counter reaches `target`.
607///
608/// A worker that spins hard is a worker holding a core the wavefront needs
609/// somewhere else, so the wait backs off to a sleep at roughly the granularity
610/// of one coding tree block.
611fn wait_for(counter: &Progress, target: usize) {
612 let mut spins = 0u32;
613 while counter.0.load(Ordering::Acquire) < target {
614 if spins < 128 {
615 std::hint::spin_loop();
616 } else if spins < 256 {
617 std::thread::yield_now();
618 } else {
619 std::thread::sleep(std::time::Duration::from_micros(50));
620 }
621 spins += 1;
622 }
623}
624
625/// One CTB row handed to a worker: its index and its band of each plane.
626type RowAssignment<'a> = (usize, &'a mut [u8], &'a mut [u8], &'a mut [u8]);
627
628struct PaddedSource {
629 y: Vec<u8>,
630 cb: Vec<u8>,
631 cr: Vec<u8>,
632}