forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust379.9 MiB86fb0f3Tahinli7 days ago3927 commits

encoder.rs1123 lines, 48.8 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 raw memory access, 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, Pel, RowBoundary, RowState, SourcePlanes};
27use crate::deblock::{TuMap, deblock};
28use ec_core::color::ContentLight;
29use ec_core::error::{Error, Result};
30use ec_core::frame::{PixelFormat, Plane, VideoFrame};
31use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b};
32use ec_h265_syntax::ps::{ConformanceWindow, ProfileTierLevel};
33use ec_h265_syntax::slice::SliceHeader;
34use ec_h265_syntax::vui::{VideoSignalType, VuiParameters};
35use ec_h265_syntax::{Pps, Sps, Vps, sei};
36use std::sync::Mutex;
37use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
38
39use crate::cabac::{CabacEncoder, Contexts};
40
41/// How the encoder picks QP for a picture.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub enum RateControl {
44 /// One fixed quantiser for every picture.
45 ConstantQp(i32),
46 /// Aim for `bits` per picture: a model picks the QP, and a picture that
47 /// lands more than 25% off is coded a second time at a corrected QP.
48 TargetBits(u64),
49 /// Aim for `kbps` kilobits per second at `fps` frames per second. A sequence
50 /// ([`Encoder::encode_sequence`]) runs a frame-level model with feedback, so
51 /// the clip's average lands on the target; a single IDR picture gets the
52 /// per-picture share of it, as [`RateControl::TargetBits`] does.
53 Bitrate {
54 /// Target bitrate in kilobits per second.
55 kbps: u32,
56 /// Frame rate the bitrate is spread over.
57 fps: f64,
58 },
59}
60
61/// Whether 4x4 transform units may skip the transform and code residual
62/// samples directly (`transform_skip_enabled_flag`).
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum TransformSkip {
65 /// No transform skip; every default stream is byte-identical.
66 Off,
67 /// Skip the transform on every 4x4 TU that has non-zero residual.
68 AlwaysFor4x4,
69 /// Decide per 4x4 luma transform block by rate-distortion: quantise and
70 /// reconstruct the block both ways and keep the cheaper one. Unconditional
71 /// skip is a big win on screen capture and a loss on camera content
72 /// (measured, see `transform_skip`), which is exactly what a per-block
73 /// decision resolves.
74 Rd,
75}
76
77/// Encoder settings.
78#[derive(Debug, Clone)]
79pub struct EncoderConfig {
80 /// Displayed width; the coded picture is padded up to a whole number of
81 /// minimum coding blocks and cropped back by the conformance window.
82 pub width: u32,
83 /// Displayed height.
84 pub height: u32,
85 /// Quantiser or bit target.
86 pub rate_control: RateControl,
87 /// Worker threads. Output is byte-identical for every value: each CTB row is
88 /// a substream with its own context state, and rows are dealt to workers
89 /// round-robin, so the thread count changes only the schedule.
90 ///
91 /// 0 and the default mean `min(available_parallelism, 6)`, see
92 /// [`default_threads`].
93 pub threads: usize,
94 /// Coding tree block size, 32 (default) or 64.
95 ///
96 /// The wavefront hands one CTB *row* to a worker, so the row count is the
97 /// parallelism this encoder has: 1080 lines are 17 rows at 64 but 34 at 32.
98 /// Rows are dealt round-robin, so on a twelve-core machine 17 rows means
99 /// five workers take two rows while seven take one — half the machine idles
100 /// through the second half of the picture. 34 rows deal three-and-three.
101 /// Measured on 1080p at QP 27: the two sizes encode at the same speed on one
102 /// thread (1.80 fps each), but on twelve 32 runs 9.03 fps against 64's 7.92,
103 /// for 1.0% more bits and 0.02 dB less PSNR — the whole difference is
104 /// wavefront occupancy, which is why 32 is the default. 64 takes its bits
105 /// back when the picture is tall enough to fill the workers anyway (2160
106 /// lines are 34 rows at 64) or when nothing is waiting for the encode.
107 pub ctb_size: usize,
108 /// How many of the 35 intra modes get a full rate-distortion trial, on top
109 /// of the most probable mode, which always gets one.
110 ///
111 /// Swept against x265 at matched features on four real clips (BD-PSNR
112 /// luma / all-plane, wall time for the whole four-QP ladder):
113 ///
114 /// | k | film 3840x1608 | web 1138x640 | screen 2560x1440 | phone 1080p |
115 /// |---|----------------|-------------------|------------------|-------------|
116 /// | 1 | -0.840 / -0.815 38s | -0.728 / -0.733 8s | | |
117 /// | 2 | -0.731 / -0.730 40s | -0.603 / -0.632 9s | -2.521 / -2.420 29s | -0.435 / -0.444 11s |
118 /// | 3 | -0.703 / -0.709 43s | -0.556 / -0.596 10s | -2.493 / -2.402 31s | -0.401 / -0.416 11s |
119 /// | 4 | -0.693 / -0.705 46s | -0.530 / -0.574 10s | | |
120 /// | 5 | -0.685 / -0.703 49s | -0.507 / -0.556 11s | -2.465 / -2.360 35s | -0.366 / -0.387 13s |
121 /// | 8 | -0.684 / -0.710 59s | -0.471 / -0.525 14s | -2.453 / -2.368 41s | -0.340 / -0.361 16s |
122 ///
123 /// Every clip improves monotonically up to 5, which is why 5 is the
124 /// default. Eight buys nothing on the film clip (+0.001 luma, and its
125 /// all-plane figure goes *backwards*) for another 20% of wall time, so the
126 /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate
127 /// test re-runs the sweep.
128 pub rdo_candidates: usize,
129 /// Whether the chroma prediction mode is chosen by rate-distortion over the
130 /// five modes the syntax allows, instead of always taking the derived mode.
131 ///
132 /// Off by default: measured against x265 on four real clips it is a wash,
133 /// and on screen capture it is a loss (BD-PSNR luma / all-plane, derived
134 /// mode -> search, `chroma_rd_weight: 1.0`):
135 ///
136 /// | clip | derived | search |
137 /// |------|---------|--------|
138 /// | 4K film | -0.685 / -0.703 | -0.757 / **-0.606** |
139 /// | 1138x640 web | -0.507 / -0.556 | -0.584 / **-0.505** |
140 /// | 1440p screen capture | **-2.465 / -2.360** | -2.617 / -2.460 |
141 /// | 1080p phone | -0.366 / **-0.387** | -0.477 / -0.384 |
142 ///
143 /// Luma falls on every clip because the extra chroma bits come out of the
144 /// same budget at a fixed QP; all-plane gains 0.10 dB and 0.05 dB on the two
145 /// camera clips, is flat on the third and loses 0.10 dB on the screen
146 /// capture, for 10-15% more encode time. The average is +0.01 dB all-plane,
147 /// which is not a default. [`EncoderConfig::chroma_rd_weight`] was swept at
148 /// 0.25/0.5/1.0/2.0 and did not change the shape of that table: the screen
149 /// capture loses at every weight, so the cause is not the lambda.
150 pub chroma_mode_search: bool,
151 /// Weight on chroma SSD in that decision, against the luma lambda. Swept
152 /// at 0.25/0.5/1.0/2.0 on three clips; 1.0 is the best of them everywhere
153 /// the search wins at all (4K film all-plane: -0.606 at 1.0 against -0.649
154 /// at 0.25, -0.619 at 0.5, -0.657 at 2.0).
155 pub chroma_rd_weight: f64,
156 /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a
157 /// *coarser* search that is not always faster: on real pictures the 8x8
158 /// blocks pay for their search in residual bits (measured: -27% bits and
159 /// +1.5 dB at QP 22 on a 1080p camera frame, at the same wall time), which
160 /// is why 8 is the default.
161 pub min_cu_size: usize,
162 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions
163 /// (PART_NxN). On: measured at +2.14 dB BD-PSNR on a 2560x1440 screen
164 /// capture (-2.619 dB against x265 without it, -0.479 dB with) and
165 /// +0.007 dB on 1080p film, so it never loses.
166 pub intra_nxn: bool,
167
168 /// Whether a sub-block's first sign is hidden in the parity of its
169 /// absolute levels (`sign_data_hiding_enabled_flag`). Buys one bypass bin
170 /// per qualifying sub-block for a level nudged by one.
171 ///
172 /// Off: measured at -0.033 dB BD-PSNR on a 2560x1440 screen capture and
173 /// -0.043 dB on 1080p film. Hiding is not optional per sub-block, so every
174 /// qualifying one pays for the bin whether the nudge is cheap or not, and
175 /// with levels that come straight from the quantiser's rounding the nudges
176 /// cost more than the signs save. Worth re-measuring once RDOQ lands: that
177 /// is where the gain in other encoders comes from.
178 pub sign_hiding: bool,
179
180 /// Whether quantised levels get a rate-distortion search (RDOQ) that
181 /// offers each small level the magnitudes below it and takes one when the
182 /// squared error it gives up costs less than the bits it saves.
183 ///
184 /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 ->
185 /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360),
186 /// with the all-plane figures moving the same way. The rate is the CABAC
187 /// coder's own price for the whole block, so dropping a level is priced
188 /// with the significance map and last position that follow from it.
189 pub rdoq: bool,
190 /// Whether RDOQ's per-candidate bit cost comes from an estimated
191 /// per-context fractional-bit table (x265/HM `entropyBits`-style: the
192 /// entropy of the bin under its context's current probability state)
193 /// instead of replaying the exact adaptive-CABAC coder for every trial.
194 /// Changes output bytes (the estimate is not exact). On by default:
195 /// measured 1.6x faster on `ec-bench`'s h265 encode row and, on the
196 /// synthetic `bd_psnr_vs_x265` clip, a small BD-PSNR-YUV *gain* over the
197 /// exact-replay path (+7.948 vs +7.880 dB against x265) rather than a
198 /// loss. `false` restores exact per-trial CABAC replay for A/B.
199 pub rdoq_estimate: bool,
200 /// Whether 4x4 TUs may skip the integer transform.
201 ///
202 /// `Rd` by default: the tool is the screen-content lever, and it wants a
203 /// per-block decision, not a switch. BD-PSNR luma / all-plane against x265
204 /// at matched features over the four-QP ladder (`EC_H265_TSKIP=0|always|rd`
205 /// in `bd_psnr_vs_x265`, real clips, 24 pictures each):
206 ///
207 /// | clip | `Off` | `AlwaysFor4x4` | `Rd` |
208 /// |------|-------|----------------|------|
209 /// | 1440p screen capture A | -0.381 / -0.438 | +1.485 / +1.373 | +1.034 / +0.918 |
210 /// | 1440p screen capture B | +0.716 / +0.561 | +0.783 / +0.222 | +1.133 / +0.781 |
211 /// | 1440p screen capture C | +0.213 / +0.099 | | +0.124 / +0.008 |
212 /// | 1080p film | +0.584 / +0.468 | | +0.580 / +0.460 |
213 ///
214 /// Unconditional skip is worth +1.8 dB all-plane on A and -0.34 dB on B, so
215 /// neither setting of a switch is right; the per-block trial takes A's win
216 /// without B's loss and leaves film where it was (-0.008 dB, the estimate
217 /// proxy's noise). The cost is the second quantise-and-reconstruct pass on
218 /// every committed 4x4 luma block: the whole four-QP ladder went 111s ->
219 /// 290s on screen capture A and 427s -> 494s on film. Set `Off` to buy that
220 /// time back.
221 pub transform_skip: TransformSkip,
222 /// Whether the transform tree may split once (rate-quantisation transform):
223 /// the luma TU of a 2Nx2N coding unit may be coded as four half-size
224 /// children when that costs less in `J = SSD + lambda * bits`.
225 ///
226 /// On by default: measured against x265 over the four-point ladder it is
227 /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which
228 /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`).
229 pub rqt: bool,
230 /// Whether a 64x64 coding tree block may stay one coding unit instead of
231 /// always splitting to 32x32. Only reachable with `ctb_size` 64.
232 ///
233 /// A 64x64 intra coding unit still predicts and transforms in four 32x32
234 /// blocks -- 32x32 is HEVC's largest transform -- so what it buys is three
235 /// split flags and three mode signallings, and what it costs is one luma
236 /// direction for the whole 64x64. Measured in `lanes/h265-cu64-r1.report.md`.
237 ///
238 /// On by default: against x265 over the four-point ladder it is worth
239 /// +0.007 dB BD-PSNR on film and +0.098 dB on screen capture over always
240 /// splitting a 64x64 tree block, and the default `ctb_size` of 32 leaves
241 /// it unreachable anyway.
242 pub cu64: bool,
243 /// What the samples mean, written into the VUI.
244 pub video_signal_type: Option<VideoSignalType>,
245 /// Sample aspect ratio.
246 pub sample_aspect_ratio: Option<(u16, u16)>,
247 /// `(num_units_in_tick, time_scale)`; also picks the level.
248 pub timing: Option<(u32, u32)>,
249 /// `chroma_sample_loc_type` (top, bottom field), each 0..=5, written into the VUI.
250 /// BT.2020 4:2:0 material is type 2. Default absent.
251 pub chroma_sample_loc: Option<(u8, u8)>,
252 /// Content light level (MaxCLL/MaxFALL) and, when `mastering_display` is
253 /// absent, the mastering luminance pair, written as prefix SEI.
254 pub content_light: ContentLight,
255 /// Full `mastering_display_colour_volume` (primaries, white point,
256 /// luminances), written as prefix SEI. Takes precedence over the mastering
257 /// pair in `content_light`. Default absent.
258 pub mastering_display: Option<ec_h265_syntax::sei::MasteringDisplay>,
259 /// Run the in-loop deblocking filter over the finished picture.
260 ///
261 /// An intra picture predicts from its unfiltered reconstruction, so this
262 /// changes only what a decoder shows -- and what the reconstruction and its
263 /// picture hash therefore have to say.
264 pub deblock: bool,
265 /// Emit the decoded picture hash SEI (MD5 of the reconstruction).
266 pub picture_hash: bool,
267 /// Return the reconstruction alongside the bitstream.
268 pub keep_recon: bool,
269 /// Picture interval of [`Encoder::encode_sequence`]: an IDR, then
270 /// `keyint - 1` P pictures, repeating. 1 (the default) makes every picture
271 /// an IDR, as [`Encoder::encode_batch`] does.
272 pub keyint: usize,
273 /// Whether P pictures are coded as a wavefront (`entropy_coding_sync`): one
274 /// substream per CTB row, contexts synced from the row above after its second
275 /// CTB, and rows coded by up to [`EncoderConfig::threads`] workers.
276 ///
277 /// On by default. The cost is the substream boundary (contexts resynced per
278 /// row, and one entry point per row), which is measured in the lane report
279 /// against off, the single continuous substream the sequential coder writes.
280 /// Off also makes P pictures single-threaded.
281 pub inter_wpp: bool,
282 /// Scale on the lambda the P-picture mode decisions use, against
283 /// `lambda_for(qp)` (the intra lambda, in squared-error units per bit). The
284 /// motion search uses `sqrt(lambda_for(qp))` instead, because it costs SAD.
285 ///
286 /// Measured with `scripts/hevc-bdrate.sh` (ffmpeg PSNR, bframes=0 x265
287 /// anchor, 352x288, QPs 22/27/32/37), BD-rate against x265: +21.9% at scale 1,
288 /// +23.4% at 1/4, +28.9% at 1/16. Scale 1 is the default.
289 pub inter_lambda_scale: f64,
290 /// Whether a sequence with P pictures (`keyint > 1`) codes its IDR pictures with the
291 /// fast intra tool set: no RDOQ, one full-RD intra candidate, no NxN split, no transform
292 /// skip trial, no transform-tree split. An IDR is one picture in `keyint`, so what
293 /// it gives up costs the sequence little (BD-rate within about 1.5 points, measured in
294 /// `lanes/hevcencspeed4.report.md`) while the IDR takes about a third of the
295 /// single-thread time otherwise. Intra-only streams (`keyint == 1`) are not affected.
296 pub gop_fast_idr: bool,
297 /// Luma and chroma bit depth: 8 (Main, the default) or 10 (Main 10).
298 ///
299 /// At 10 bits the input is [`PixelFormat::I010`] (or `u16` planes through
300 /// [`Encoder::encode_idr_samples`]), QP runs from `-QpBdOffset` (-12) to 51,
301 /// and the SPS and VPS carry the Main 10 profile.
302 pub bit_depth: u8,
303 /// Speed/quality trade of the P-picture search and decisions; see [`Preset`].
304 /// `Default` is the reference behaviour and its output never changes.
305 pub speed: Preset,
306}
307
308/// Encoder speed preset. `Default` is the measured reference set. `Fast` and `Faster`
309/// trade rate for speed with coarser motion search, earlier terminations and fewer
310/// candidates; streams stay conforming Main/Main 10.
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
312pub enum Preset {
313 /// Reference search; output is bit-identical to releases before presets existed.
314 #[default]
315 Default,
316 /// About 2x faster, small rate loss.
317 Fast,
318 /// Faster still, larger rate loss.
319 Faster,
320}
321
322impl EncoderConfig {
323 /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs
324 /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64).
325 pub fn new(width: u32, height: u32) -> EncoderConfig {
326 EncoderConfig {
327 width,
328 height,
329 rate_control: RateControl::ConstantQp(27),
330 threads: default_threads(),
331 ctb_size: 32,
332 rdo_candidates: 5,
333 chroma_mode_search: false,
334 chroma_rd_weight: 1.0,
335 min_cu_size: 8,
336 intra_nxn: true,
337 sign_hiding: false,
338 rdoq: true,
339 rdoq_estimate: true,
340 transform_skip: TransformSkip::Rd,
341 rqt: true,
342 cu64: true,
343 video_signal_type: None,
344 sample_aspect_ratio: None,
345 timing: None,
346 chroma_sample_loc: None,
347 content_light: ContentLight::default(),
348 mastering_display: None,
349 deblock: true,
350 picture_hash: false,
351 keep_recon: false,
352 keyint: 1,
353 inter_wpp: true,
354 inter_lambda_scale: 1.0,
355 gop_fast_idr: true,
356 bit_depth: 8,
357 speed: Preset::Default,
358 }
359 }
360}
361
362/// The worker count the encoder uses when none is asked for: the machine's
363/// parallelism, capped at 6 (the 1080p30 target's thread budget).
364pub fn default_threads() -> usize {
365 std::thread::available_parallelism()
366 .map_or(1, |n| n.get())
367 .min(6)
368}
369
370/// One coded picture.
371#[derive(Debug, Clone)]
372pub struct EncodedPicture {
373 /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice.
374 pub au: Vec<u8>,
375 /// The quantiser the picture was coded at.
376 pub qp: i32,
377 /// The reconstruction, cropped to the displayed size, when
378 /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a
379 /// conformant decoder produces, because the in-loop filters are off.
380 pub recon: Option<VideoFrame>,
381}
382
383/// An intra-only HEVC encoder.
384#[derive(Clone)]
385pub struct Encoder {
386 pub(crate) cfg: EncoderConfig,
387 vps: Vps,
388 sps: Sps,
389 pps: Pps,
390 /// The picture parameter set of P pictures: the same as `pps`, with
391 /// wavefronts and transform skip off, and id 1.
392 pub(crate) pps_p: Pps,
393 pub(crate) coded_width: usize,
394 pub(crate) coded_height: usize,
395 pub(crate) threads: usize,
396 pub(crate) pk: crate::enc_p::PKnobs,
397}
398
399/// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model
400/// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6).
401const BPP_AT_QP27: f64 = 0.6;
402
403/// Bits one picture may spend at `kbps` kilobits per second and `fps` frames per
404/// second.
405pub(crate) fn bitrate_picture_bits(kbps: u32, fps: f64) -> u64 {
406 let bits = f64::from(kbps) * 1000.0 / fps.max(1e-3);
407 (bits.round() as u64).max(1)
408}
409
410/// An encoded picture with its reconstructed Y, Cb and Cr planes.
411pub(crate) type PictureRecon = (EncodedPicture, Vec<Pel>, Vec<Pel>, Vec<Pel>);
412
413/// The smallest QP the encoder codes at: `-QpBdOffset`, which is `-6 * (bit_depth - 8)`.
414pub(crate) fn qp_min(bit_depth: u32) -> i32 {
415 -6 * (bit_depth as i32 - 8)
416}
417
418/// The samples of one plane as `Pel`s, with the stride in samples. An 8-bit
419/// plane widens; a 16-bit plane is little-endian pairs of bytes.
420pub(crate) fn plane_samples(plane: &Plane, sixteen: bool) -> (Vec<Pel>, usize) {
421 if sixteen {
422 let samples = plane
423 .data
424 .as_chunks::<2>()
425 .0
426 .iter()
427 .map(|c| Pel::from_le_bytes(*c))
428 .collect();
429 (samples, plane.stride / 2)
430 } else {
431 (
432 plane.data.iter().map(|&v| Pel::from(v)).collect(),
433 plane.stride,
434 )
435 }
436}
437
438impl Encoder {
439 /// Build an encoder, refusing dimensions it cannot code.
440 pub fn new(mut cfg: EncoderConfig) -> Result<Encoder> {
441 if cfg.keyint > 1 && cfg.gop_fast_idr {
442 cfg.rdoq = false;
443 cfg.rdo_candidates = cfg.rdo_candidates.min(1);
444 cfg.intra_nxn = false;
445 cfg.transform_skip = TransformSkip::Off;
446 cfg.rqt = false;
447 }
448 if cfg.bit_depth != 8 && cfg.bit_depth != 10 {
449 return Err(Error::unsupported(
450 format!("HEVC encode at {} bits", cfg.bit_depth),
451 "this encoder codes 8-bit and 10-bit 4:2:0",
452 ));
453 }
454 if cfg.width < 16 || cfg.height < 16 {
455 return Err(Error::unsupported(
456 format!("HEVC encode of {}x{}", cfg.width, cfg.height),
457 "pictures below 16x16 have no coding tree",
458 ));
459 }
460 if cfg.ctb_size != 64 && cfg.ctb_size != 32 {
461 return Err(Error::unsupported(
462 format!("HEVC coding tree block of {}", cfg.ctb_size),
463 "this encoder codes 64x64 or 32x32 trees",
464 ));
465 }
466 // The coded picture is a whole number of minimum coding blocks (8x8);
467 // the conformance window crops the padding back off.
468 let coded_width = (cfg.width as usize).next_multiple_of(8);
469 let coded_height = (cfg.height as usize).next_multiple_of(8);
470 let fps = cfg
471 .timing
472 .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1)))
473 .unwrap_or(30.0);
474 let level = ProfileTierLevel::level_for(coded_width as u32, coded_height as u32, fps);
475 let ptl = if cfg.bit_depth == 10 {
476 ProfileTierLevel::main10(level)
477 } else {
478 ProfileTierLevel::main(level)
479 };
480 let bd_minus8 = u32::from(cfg.bit_depth) - 8;
481 // A GOP with P pictures keeps the previous picture as a reference, so the
482 // decoded picture buffer holds two pictures.
483 let dpb_minus1 = if cfg.keyint > 1 { 1 } else { 0 };
484 let vps = Vps {
485 id: 0,
486 ptl,
487 max_dec_pic_buffering_minus1: dpb_minus1,
488 max_num_reorder_pics: 0,
489 };
490 let log2_ctb = cfg.ctb_size.trailing_zeros();
491 let sps = Sps {
492 max_latency_increase_plus1: 0,
493 extension_flags: 0,
494 range: Default::default(),
495 vps_id: 0,
496 id: 0,
497 chroma_format_idc: 1,
498 separate_colour_plane: false,
499 pic_width_in_luma_samples: coded_width as u32,
500 pic_height_in_luma_samples: coded_height as u32,
501 conf_win: ConformanceWindow {
502 left: 0,
503 right: (coded_width - cfg.width as usize) as u32 / 2,
504 top: 0,
505 bottom: (coded_height - cfg.height as usize) as u32 / 2,
506 },
507 bit_depth_luma_minus8: bd_minus8,
508 bit_depth_chroma_minus8: bd_minus8,
509 log2_max_poc_lsb_minus4: 4,
510 max_dec_pic_buffering_minus1: dpb_minus1,
511 max_num_reorder_pics: 0,
512 log2_min_cb_size_minus3: 0,
513 log2_diff_max_min_cb_size: log2_ctb - 3,
514 log2_min_tb_size_minus2: 0,
515 log2_diff_max_min_tb_size: 3,
516 max_transform_hierarchy_depth_inter: 0,
517 max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 },
518 scaling_list_enabled: false,
519 scaling_list: None,
520 amp_enabled: false,
521 // No in-loop filters: see `Encoder` docs and the PPS below.
522 sao_enabled: false,
523 pcm_enabled: false,
524 pcm: None,
525 num_short_term_ref_pic_sets: 0,
526 short_term_ref_pic_sets: Vec::new(),
527 long_term_ref_pics_present: false,
528 num_long_term_ref_pics_sps: 0,
529 long_term_ref_pics_sps: Vec::new(),
530 temporal_mvp_enabled: true,
531 strong_intra_smoothing: true,
532 ptl,
533 vui: Some(VuiParameters {
534 sample_aspect_ratio: cfg.sample_aspect_ratio,
535 video_signal_type: cfg.video_signal_type,
536 chroma_sample_loc: cfg.chroma_sample_loc,
537 timing: cfg.timing,
538 }),
539 };
540 let pps = Pps {
541 id: 0,
542 sps_id: 0,
543 entropy_coding_sync_enabled: true,
544 // SAO is off; deblocking follows `EncoderConfig::deblock`. An
545 // intra-only stream predicts from its own *unfiltered*
546 // reconstruction (8.4.4.2.1), so the deblocking filter changes
547 // neither side's prediction: running it over the finished picture
548 // here keeps the reconstruction bit-identical to a decoder's
549 // output, and the picture hash that rides on it honest.
550 sign_data_hiding_enabled: cfg.sign_hiding,
551 transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,
552 deblocking_filter_control_present: true,
553 deblocking_filter_disabled: !cfg.deblock,
554 loop_filter_across_slices_enabled: false,
555 ..Pps::default()
556 };
557 let pps_p = Pps {
558 id: 1,
559 entropy_coding_sync_enabled: cfg.inter_wpp,
560 transform_skip_enabled: false,
561 ..pps.clone()
562 };
563 let threads = if cfg.threads == 0 {
564 default_threads()
565 } else {
566 cfg.threads
567 };
568 let pk = crate::enc_p::PKnobs::for_preset(cfg.speed);
569 Ok(Encoder {
570 cfg,
571 vps,
572 sps,
573 pps,
574 pps_p,
575 coded_width,
576 coded_height,
577 threads,
578 pk,
579 })
580 }
581
582 /// A copy of this encoder that uses `threads` workers per picture.
583 pub(crate) fn with_threads(&self, threads: usize) -> Encoder {
584 Encoder {
585 threads: threads.max(1),
586 ..self.clone()
587 }
588 }
589
590 /// The sequence parameter set this encoder writes.
591 pub fn sps(&self) -> &Sps {
592 &self.sps
593 }
594
595 /// The picture parameter set (id 1) that the P pictures of a sequence refer
596 /// to, as one Annex-B NAL unit. Every P access unit carries it in-band; a
597 /// container that keeps parameter sets out of its samples needs it in its
598 /// configuration record, before the first P picture.
599 pub fn p_picture_parameter_set(&self) -> Vec<u8> {
600 let mut out = Vec::new();
601 write_annex_b(
602 &mut out,
603 NalHeader::new(NalUnitType::Pps),
604 &self.pps_p.to_rbsp(),
605 true,
606 );
607 out
608 }
609
610 /// The pixel format a frame must have: I420 at 8 bits, I010 at 10.
611 pub fn frame_format(&self) -> PixelFormat {
612 if self.cfg.bit_depth == 10 {
613 PixelFormat::I010
614 } else {
615 PixelFormat::I420
616 }
617 }
618
619 /// Encode one picture as an IDR access unit.
620 ///
621 /// The frame must be [`Encoder::frame_format`] at the configured size: I420
622 /// for 8-bit, I010 (16-bit little-endian samples) for 10-bit. Padding to the
623 /// coded size is this encoder's job, not the caller's.
624 pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> {
625 let want = self.frame_format();
626 if frame.format != want {
627 return Err(Error::unsupported(
628 format!("HEVC encode of {:?}", frame.format),
629 format!("this encoder codes {want:?} at {} bits", self.cfg.bit_depth),
630 ));
631 }
632 if frame.width != self.cfg.width || frame.height != self.cfg.height {
633 return Err(Error::corrupt(format!(
634 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
635 frame.width, frame.height, self.cfg.width, self.cfg.height
636 )));
637 }
638 let sixteen = self.cfg.bit_depth == 10;
639 let (y, ys) = plane_samples(&frame.planes[0], sixteen);
640 let (cb, cbs) = plane_samples(&frame.planes[1], sixteen);
641 let (cr, crs) = plane_samples(&frame.planes[2], sixteen);
642 self.encode_idr_samples(&y, ys, &cb, cbs, &cr, crs)
643 }
644
645 /// Encode one picture from raw 8-bit I420 planes with their strides.
646 ///
647 /// This is the surface a compatibility shim maps onto: the planes are the
648 /// *displayed* picture, and the conformance window handles the rest. It is
649 /// an error on a 10-bit encoder; use [`Encoder::encode_idr_samples`].
650 pub fn encode_idr_planes(
651 &self,
652 y: &[u8],
653 y_stride: usize,
654 cb: &[u8],
655 cb_stride: usize,
656 cr: &[u8],
657 cr_stride: usize,
658 ) -> Result<EncodedPicture> {
659 if self.cfg.bit_depth != 8 {
660 return Err(Error::unsupported(
661 format!("8-bit planes at {} bits", self.cfg.bit_depth),
662 "use encode_idr_samples for 10-bit samples",
663 ));
664 }
665 let widen = |p: &[u8]| p.iter().map(|&v| Pel::from(v)).collect::<Vec<Pel>>();
666 self.encode_idr_samples(
667 &widen(y),
668 y_stride,
669 &widen(cb),
670 cb_stride,
671 &widen(cr),
672 cr_stride,
673 )
674 }
675
676 /// Encode one picture from raw planes of samples (each `Pel` a sample of
677 /// the configured bit depth) with their strides in samples.
678 pub fn encode_idr_samples(
679 &self,
680 y: &[Pel],
681 y_stride: usize,
682 cb: &[Pel],
683 cb_stride: usize,
684 cr: &[Pel],
685 cr_stride: usize,
686 ) -> Result<EncodedPicture> {
687 let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?;
688 let (mut qp, target) = match self.cfg.rate_control {
689 RateControl::ConstantQp(qp) => (qp.clamp(self.qp_min(), 51), None),
690 RateControl::TargetBits(bits) => (self.qp_for_bits(bits), Some(bits)),
691 RateControl::Bitrate { kbps, fps } => {
692 let bits = bitrate_picture_bits(kbps, fps);
693 (self.qp_for_bits(bits), Some(bits))
694 }
695 };
696 let mut coded = self.code_picture(&padded, qp)?;
697 if let Some(target) = target {
698 let actual = coded.au.len() as f64 * 8.0;
699 let target = target as f64;
700 if (actual - target).abs() / target > 0.25 {
701 // One correction pass, from the measured slope rather than the
702 // model: 6 QP steps is a factor of two in rate.
703 let correction = 6.0 * (actual / target).log2();
704 let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32;
705 let corrected = corrected.clamp(self.qp_min(), 51);
706 if corrected != qp {
707 qp = corrected;
708 coded = self.code_picture(&padded, qp)?;
709 }
710 }
711 }
712 Ok(coded)
713 }
714
715 /// The lowest QP this encoder codes at: `-QpBdOffset`.
716 pub(crate) fn qp_min(&self) -> i32 {
717 qp_min(u32::from(self.cfg.bit_depth))
718 }
719
720 /// The QP that codes one picture of `bits` bits at the anchor rate model.
721 fn qp_for_bits(&self, bits: u64) -> i32 {
722 let pixels = (self.cfg.width as f64) * (self.cfg.height as f64);
723 let target_bpp = (bits as f64 / pixels).max(1e-4);
724 let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2();
725 (qp.round() as i32).clamp(self.qp_min(), 51)
726 }
727
728 /// Encode a batch of pictures, each as its own IDR access unit.
729 ///
730 /// The wavefront inside a single picture already uses every core, so this is
731 /// a convenience for callers with a list, not a second layer of threads.
732 pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>>
733 where
734 I: IntoIterator<Item = &'a VideoFrame>,
735 {
736 frames.into_iter().map(|f| self.encode_idr(f)).collect()
737 }
738
739 /// Copy the source into coded-size planes, replicating the edge into the
740 /// padding rather than filling it with black: the padding is coded and then
741 /// cropped away, and a black border would bleed into the last real column
742 /// through the prediction and the transform that straddles it.
743 pub(crate) fn pad_source(
744 &self,
745 y: &[Pel],
746 y_stride: usize,
747 cb: &[Pel],
748 cb_stride: usize,
749 cr: &[Pel],
750 cr_stride: usize,
751 ) -> Result<PaddedSource> {
752 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
753 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
754 let (coded_w, coded_h) = (self.coded_width, self.coded_height);
755 let plane = |src: &[Pel],
756 stride: usize,
757 width: usize,
758 height: usize,
759 out_w: usize,
760 out_h: usize|
761 -> Result<Vec<Pel>> {
762 if stride < width || src.len() < (height - 1) * stride + width {
763 return Err(Error::corrupt(
764 "HEVC encode: source plane shorter than its stated size".to_string(),
765 ));
766 }
767 let mut out = vec![0 as Pel; out_w * out_h];
768 for row in 0..out_h {
769 let src_row = row.min(height - 1);
770 let line = &src[src_row * stride..src_row * stride + width];
771 let dst = &mut out[row * out_w..row * out_w + out_w];
772 dst[..width].copy_from_slice(line);
773 let edge = line[width - 1];
774 dst[width..].fill(edge);
775 }
776 Ok(out)
777 };
778 let y = plane(y, y_stride, w, h, coded_w, coded_h)?;
779 let shift = u32::from(self.cfg.bit_depth) - 8;
780 let y8 = y.iter().map(|&v| (v >> shift) as u8).collect();
781 Ok(PaddedSource {
782 y,
783 y8,
784 cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?,
785 cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?,
786 })
787 }
788
789 /// Code one picture at `qp`, wavefront across CTB rows.
790 fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> {
791 self.code_picture_planes(src, qp)
792 .map(|(coded, _, _, _)| coded)
793 }
794
795 /// [`Encoder::code_picture`], also returning the padded reconstruction the
796 /// next picture of a sequence predicts from.
797 pub(crate) fn code_picture_planes(&self, src: &PaddedSource, qp: i32) -> Result<PictureRecon> {
798 let (width, height) = (self.coded_width, self.coded_height);
799 let ctb = self.cfg.ctb_size;
800 let cols = width.div_ceil(ctb);
801 let rows = height.div_ceil(ctb);
802
803 let mut rec_y = vec![0 as Pel; width * height];
804 let mut rec_cb = vec![0 as Pel; width / 2 * height / 2];
805 let mut rec_cr = vec![0 as Pel; width / 2 * height / 2];
806
807 let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect();
808 let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect();
809 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
810 (0..rows).map(|_| Mutex::new(None)).collect();
811 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
812 // Each row publishes the transform-block sizes of its band, which the
813 // deblocking filter reads its edges off once the picture is whole.
814 let tu_bands: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
815
816 // One band of the reconstruction per CTB row, handed out by index.
817 let mut bands_y: Vec<&mut [Pel]> = rec_y.chunks_mut(ctb * width).collect();
818 let mut bands_cb: Vec<&mut [Pel]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect();
819 let mut bands_cr: Vec<&mut [Pel]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect();
820 let threads = self.threads.min(rows).max(1);
821 // Round-robin: worker t owns rows t, t + threads, ... Each row's
822 // predecessor therefore belongs to another worker that is never waiting
823 // on it, so the wavefront cannot deadlock.
824 let mut per_worker: Vec<Vec<RowAssignment<'_>>> =
825 (0..threads).map(|_| Vec::new()).collect();
826 for row in (0..rows).rev() {
827 let y = bands_y.pop().expect("one band per row");
828 let cb = bands_cb.pop().expect("one band per row");
829 let cr = bands_cr.pop().expect("one band per row");
830 per_worker[row % threads].push((row, y, cb, cr));
831 }
832 for worker in per_worker.iter_mut() {
833 worker.reverse();
834 }
835
836 let slice_qp = qp;
837 std::thread::scope(|scope| {
838 for worker_rows in per_worker {
839 let boundaries = &boundaries;
840 let progress = &progress;
841 let wpp_contexts = &wpp_contexts;
842 let substreams = &substreams;
843 let tu_bands = &tu_bands;
844 let src = &src;
845 scope.spawn(move || {
846 for (row, band_y, band_cb, band_cr) in worker_rows {
847 let band_y0 = row * ctb;
848 // Wait for the row above to be two CTBs ahead, which is
849 // both the prediction reach and the CABAC sync point.
850 if row > 0 {
851 wait_for(&progress[row - 1], 2.min(cols));
852 }
853 let contexts = if row == 0 || cols < 2 {
854 Contexts::new(slice_qp)
855 } else {
856 wpp_contexts[row - 1]
857 .lock()
858 .ok()
859 .and_then(|c| c.clone())
860 .unwrap_or_else(|| Contexts::new(slice_qp))
861 };
862 let mut enc = CabacEncoder::new(contexts);
863 let mut coder = CtuEncoder::new(
864 SourcePlanes {
865 y: &src.y,
866 cb: &src.cb,
867 cr: &src.cr,
868 },
869 RowState {
870 rec_y: band_y,
871 rec_cb: band_cb,
872 rec_cr: band_cr,
873 publish: &boundaries[row],
874 above: if row == 0 {
875 None
876 } else {
877 Some(&boundaries[row - 1])
878 },
879 },
880 width,
881 height,
882 ctb,
883 band_y0,
884 slice_qp,
885 true,
886 self.cfg.rdo_candidates,
887 self.cfg.chroma_mode_search,
888 self.cfg.chroma_rd_weight,
889 self.cfg.intra_nxn,
890 self.cfg.sign_hiding,
891 self.cfg.rdoq,
892 self.cfg.rdoq_estimate,
893 self.cfg.transform_skip,
894 self.cfg.rqt,
895 self.cfg.cu64,
896 self.cfg.min_cu_size.max(8).trailing_zeros(),
897 u32::from(self.cfg.bit_depth),
898 );
899 for col in 0..cols {
900 if row > 0 {
901 wait_for(&progress[row - 1], (col + 2).min(cols));
902 }
903 coder.encode_ctu(col, &mut enc);
904 if col == 1 {
905 // 9.3.2.1: the row below syncs from the state
906 // after the second CTB of this row.
907 if let Ok(mut slot) = wpp_contexts[row].lock() {
908 *slot = Some(enc.contexts.clone());
909 }
910 }
911 progress[row].0.store(col + 1, Ordering::Release);
912 let last_in_picture = row + 1 == rows && col + 1 == cols;
913 enc.encode_terminate(u32::from(last_in_picture));
914 if !last_in_picture && col + 1 == cols {
915 // end_of_subset_one_bit, then byte alignment.
916 enc.encode_terminate(1);
917 }
918 }
919 if let Ok(mut slot) = substreams[row].lock() {
920 *slot = enc.finish();
921 }
922 if let Ok(mut slot) = tu_bands[row].lock() {
923 *slot = coder.tu_log2_band().to_vec();
924 }
925 }
926 });
927 }
928 });
929
930 let substreams: Vec<Vec<u8>> = substreams
931 .into_iter()
932 .map(|m| m.into_inner().unwrap_or_default())
933 .collect();
934 if self.cfg.deblock {
935 let mut tus = TuMap::new(width, height);
936 for (row, band) in tu_bands.into_iter().enumerate() {
937 let band = band.into_inner().unwrap_or_default();
938 let band_y0 = row * ctb;
939 let band_rows = (height - band_y0).min(ctb) / 4;
940 tus.absorb_band(band_y0, band_rows, &band);
941 }
942 deblock(
943 &mut rec_y,
944 &mut rec_cb,
945 &mut rec_cr,
946 width,
947 height,
948 qp,
949 u32::from(self.cfg.bit_depth),
950 &tus,
951 );
952 }
953
954 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
955 let recon = self
956 .cfg
957 .keep_recon
958 .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr));
959 Ok((EncodedPicture { au, qp, recon }, rec_y, rec_cb, rec_cr))
960 }
961
962 /// Parameter sets, optional SEI, and the slice, in Annex-B framing.
963 fn assemble_au(
964 &self,
965 qp: i32,
966 substreams: &[Vec<u8>],
967 rec_y: &[Pel],
968 rec_cb: &[Pel],
969 rec_cr: &[Pel],
970 ) -> Vec<u8> {
971 let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256);
972 write_annex_b(
973 &mut au,
974 NalHeader::new(NalUnitType::Vps),
975 &self.vps.to_rbsp(),
976 true,
977 );
978 write_annex_b(
979 &mut au,
980 NalHeader::new(NalUnitType::Sps),
981 &self.sps.to_rbsp(),
982 true,
983 );
984 write_annex_b(
985 &mut au,
986 NalHeader::new(NalUnitType::Pps),
987 &self.pps.to_rbsp(),
988 true,
989 );
990 if let Some(rbsp) =
991 sei::hdr_metadata_rbsp_with(self.cfg.mastering_display, self.cfg.content_light)
992 {
993 write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true);
994 }
995
996 // Entry points count the bytes as they appear in the NAL, emulation
997 // prevention included. Each substream ends on a byte whose last written
998 // bit is the flush's one bit, so no escape sequence straddles a
999 // boundary and each substream can be measured on its own.
1000 let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len());
1001 for stream in substreams {
1002 let mut out = Vec::with_capacity(stream.len() + 8);
1003 escape_rbsp(stream, &mut out);
1004 escaped.push(out);
1005 }
1006 let mut header = SliceHeader::intra(&self.pps, qp - 26);
1007 header.entry_point_offsets = escaped
1008 .iter()
1009 .take(escaped.len().saturating_sub(1))
1010 .map(|s| s.len() as u32)
1011 .collect();
1012 let mut writer = ec_core::bitio::BitWriter::with_capacity(64);
1013 header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl);
1014 let mut rbsp = writer.into_bytes();
1015 for stream in substreams {
1016 rbsp.extend_from_slice(stream);
1017 }
1018 write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true);
1019
1020 if self.cfg.picture_hash {
1021 let (w, h) = (self.coded_width, self.coded_height);
1022 // The hash covers the samples as the picture stores them: one
1023 // byte each at 8 bits, two (little-endian) at 10.
1024 let bps = if self.cfg.bit_depth == 10 { 2 } else { 1 };
1025 let (by, bcb, bcr) = (
1026 sample_bytes(rec_y, self.cfg.bit_depth),
1027 sample_bytes(rec_cb, self.cfg.bit_depth),
1028 sample_bytes(rec_cr, self.cfg.bit_depth),
1029 );
1030 let rbsp = sei::decoded_picture_hash_rbsp(&[
1031 (&by, w * bps, w * bps, h),
1032 (&bcb, w / 2 * bps, w / 2 * bps, h / 2),
1033 (&bcr, w / 2 * bps, w / 2 * bps, h / 2),
1034 ]);
1035 write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false);
1036 }
1037 au
1038 }
1039
1040 pub(crate) fn crop_recon(&self, rec_y: &[Pel], rec_cb: &[Pel], rec_cr: &[Pel]) -> VideoFrame {
1041 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
1042 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
1043 let bd = self.cfg.bit_depth;
1044 let crop = |src: &[Pel], stride: usize, width: usize, height: usize| -> Vec<u8> {
1045 let mut out = Vec::with_capacity(width * height);
1046 for row in 0..height {
1047 out.extend(sample_bytes(&src[row * stride..row * stride + width], bd));
1048 }
1049 out
1050 };
1051 let bps = if bd == 10 { 2 } else { 1 };
1052 let planes = vec![
1053 Plane::new(crop(rec_y, self.coded_width, w, h), w * bps),
1054 Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw * bps),
1055 Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw * bps),
1056 ];
1057 let format = if bd == 10 {
1058 PixelFormat::I010
1059 } else {
1060 PixelFormat::I420
1061 };
1062 VideoFrame::try_new(format, w as u32, h as u32, planes)
1063 .expect("cropped planes are exactly the size the format asks for")
1064 }
1065}
1066
1067/// Samples as bytes: one byte each at 8 bits, little-endian pairs at 10.
1068pub(crate) fn sample_bytes(samples: &[Pel], bit_depth: u8) -> Vec<u8> {
1069 if bit_depth == 10 {
1070 samples.iter().flat_map(|v| v.to_le_bytes()).collect()
1071 } else {
1072 samples.iter().map(|&v| v as u8).collect()
1073 }
1074}
1075
1076/// A progress counter on its own cache line.
1077///
1078/// Twelve workers polling twelve counters packed eight to a line spend their
1079/// time invalidating each other's caches instead of coding; the padding is the
1080/// difference between a wavefront and a contention benchmark.
1081#[repr(align(64))]
1082pub(crate) struct Progress(pub(crate) AtomicUsize);
1083
1084/// Spin, then yield, then sleep until a row's progress counter reaches `target`.
1085///
1086/// A worker that spins hard is a worker holding a core the wavefront needs
1087/// somewhere else, so the wait backs off to a sleep at roughly the granularity
1088/// of one coding tree block.
1089fn wait_for(counter: &Progress, target: usize) {
1090 let never = AtomicBool::new(false);
1091 wait_for_or_abort(counter, target, &never);
1092}
1093
1094/// [`wait_for`] that gives up when `abort` is set. Returns whether the target
1095/// was reached.
1096pub(crate) fn wait_for_or_abort(counter: &Progress, target: usize, abort: &AtomicBool) -> bool {
1097 let mut spins = 0u32;
1098 while counter.0.load(Ordering::Acquire) < target {
1099 if abort.load(Ordering::Acquire) {
1100 return false;
1101 }
1102 if spins < 128 {
1103 std::hint::spin_loop();
1104 } else if spins < 256 {
1105 std::thread::yield_now();
1106 } else {
1107 std::thread::sleep(std::time::Duration::from_micros(50));
1108 }
1109 spins += 1;
1110 }
1111 true
1112}
1113
1114/// One CTB row handed to a worker: its index and its band of each plane.
1115type RowAssignment<'a> = (usize, &'a mut [Pel], &'a mut [Pel], &'a mut [Pel]);
1116
1117pub(crate) struct PaddedSource {
1118 pub(crate) y: Vec<Pel>,
1119 /// The luma as 8-bit samples (`y >> (bit_depth - 8)`): what the motion search measures.
1120 pub(crate) y8: Vec<u8>,
1121 pub(crate) cb: Vec<Pel>,
1122 pub(crate) cr: Vec<Pel>,
1123}