forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encoder.rs1124 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 timing: None,
490 };
491 let log2_ctb = cfg.ctb_size.trailing_zeros();
492 let sps = Sps {
493 max_latency_increase_plus1: 0,
494 extension_flags: 0,
495 range: Default::default(),
496 vps_id: 0,
497 id: 0,
498 chroma_format_idc: 1,
499 separate_colour_plane: false,
500 pic_width_in_luma_samples: coded_width as u32,
501 pic_height_in_luma_samples: coded_height as u32,
502 conf_win: ConformanceWindow {
503 left: 0,
504 right: (coded_width - cfg.width as usize) as u32 / 2,
505 top: 0,
506 bottom: (coded_height - cfg.height as usize) as u32 / 2,
507 },
508 bit_depth_luma_minus8: bd_minus8,
509 bit_depth_chroma_minus8: bd_minus8,
510 log2_max_poc_lsb_minus4: 4,
511 max_dec_pic_buffering_minus1: dpb_minus1,
512 max_num_reorder_pics: 0,
513 log2_min_cb_size_minus3: 0,
514 log2_diff_max_min_cb_size: log2_ctb - 3,
515 log2_min_tb_size_minus2: 0,
516 log2_diff_max_min_tb_size: 3,
517 max_transform_hierarchy_depth_inter: 0,
518 max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 },
519 scaling_list_enabled: false,
520 scaling_list: None,
521 amp_enabled: false,
522 // No in-loop filters: see `Encoder` docs and the PPS below.
523 sao_enabled: false,
524 pcm_enabled: false,
525 pcm: None,
526 num_short_term_ref_pic_sets: 0,
527 short_term_ref_pic_sets: Vec::new(),
528 long_term_ref_pics_present: false,
529 num_long_term_ref_pics_sps: 0,
530 long_term_ref_pics_sps: Vec::new(),
531 temporal_mvp_enabled: true,
532 strong_intra_smoothing: true,
533 ptl,
534 vui: Some(VuiParameters {
535 sample_aspect_ratio: cfg.sample_aspect_ratio,
536 video_signal_type: cfg.video_signal_type,
537 chroma_sample_loc: cfg.chroma_sample_loc,
538 timing: cfg.timing,
539 }),
540 };
541 let pps = Pps {
542 id: 0,
543 sps_id: 0,
544 entropy_coding_sync_enabled: true,
545 // SAO is off; deblocking follows `EncoderConfig::deblock`. An
546 // intra-only stream predicts from its own *unfiltered*
547 // reconstruction (8.4.4.2.1), so the deblocking filter changes
548 // neither side's prediction: running it over the finished picture
549 // here keeps the reconstruction bit-identical to a decoder's
550 // output, and the picture hash that rides on it honest.
551 sign_data_hiding_enabled: cfg.sign_hiding,
552 transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,
553 deblocking_filter_control_present: true,
554 deblocking_filter_disabled: !cfg.deblock,
555 loop_filter_across_slices_enabled: false,
556 ..Pps::default()
557 };
558 let pps_p = Pps {
559 id: 1,
560 entropy_coding_sync_enabled: cfg.inter_wpp,
561 transform_skip_enabled: false,
562 ..pps.clone()
563 };
564 let threads = if cfg.threads == 0 {
565 default_threads()
566 } else {
567 cfg.threads
568 };
569 let pk = crate::enc_p::PKnobs::for_preset(cfg.speed);
570 Ok(Encoder {
571 cfg,
572 vps,
573 sps,
574 pps,
575 pps_p,
576 coded_width,
577 coded_height,
578 threads,
579 pk,
580 })
581 }
582
583 /// A copy of this encoder that uses `threads` workers per picture.
584 pub(crate) fn with_threads(&self, threads: usize) -> Encoder {
585 Encoder {
586 threads: threads.max(1),
587 ..self.clone()
588 }
589 }
590
591 /// The sequence parameter set this encoder writes.
592 pub fn sps(&self) -> &Sps {
593 &self.sps
594 }
595
596 /// The picture parameter set (id 1) that the P pictures of a sequence refer
597 /// to, as one Annex-B NAL unit. Every P access unit carries it in-band; a
598 /// container that keeps parameter sets out of its samples needs it in its
599 /// configuration record, before the first P picture.
600 pub fn p_picture_parameter_set(&self) -> Vec<u8> {
601 let mut out = Vec::new();
602 write_annex_b(
603 &mut out,
604 NalHeader::new(NalUnitType::Pps),
605 &self.pps_p.to_rbsp(),
606 true,
607 );
608 out
609 }
610
611 /// The pixel format a frame must have: I420 at 8 bits, I010 at 10.
612 pub fn frame_format(&self) -> PixelFormat {
613 if self.cfg.bit_depth == 10 {
614 PixelFormat::I010
615 } else {
616 PixelFormat::I420
617 }
618 }
619
620 /// Encode one picture as an IDR access unit.
621 ///
622 /// The frame must be [`Encoder::frame_format`] at the configured size: I420
623 /// for 8-bit, I010 (16-bit little-endian samples) for 10-bit. Padding to the
624 /// coded size is this encoder's job, not the caller's.
625 pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> {
626 let want = self.frame_format();
627 if frame.format != want {
628 return Err(Error::unsupported(
629 format!("HEVC encode of {:?}", frame.format),
630 format!("this encoder codes {want:?} at {} bits", self.cfg.bit_depth),
631 ));
632 }
633 if frame.width != self.cfg.width || frame.height != self.cfg.height {
634 return Err(Error::corrupt(format!(
635 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
636 frame.width, frame.height, self.cfg.width, self.cfg.height
637 )));
638 }
639 let sixteen = self.cfg.bit_depth == 10;
640 let (y, ys) = plane_samples(&frame.planes[0], sixteen);
641 let (cb, cbs) = plane_samples(&frame.planes[1], sixteen);
642 let (cr, crs) = plane_samples(&frame.planes[2], sixteen);
643 self.encode_idr_samples(&y, ys, &cb, cbs, &cr, crs)
644 }
645
646 /// Encode one picture from raw 8-bit I420 planes with their strides.
647 ///
648 /// This is the surface a compatibility shim maps onto: the planes are the
649 /// *displayed* picture, and the conformance window handles the rest. It is
650 /// an error on a 10-bit encoder; use [`Encoder::encode_idr_samples`].
651 pub fn encode_idr_planes(
652 &self,
653 y: &[u8],
654 y_stride: usize,
655 cb: &[u8],
656 cb_stride: usize,
657 cr: &[u8],
658 cr_stride: usize,
659 ) -> Result<EncodedPicture> {
660 if self.cfg.bit_depth != 8 {
661 return Err(Error::unsupported(
662 format!("8-bit planes at {} bits", self.cfg.bit_depth),
663 "use encode_idr_samples for 10-bit samples",
664 ));
665 }
666 let widen = |p: &[u8]| p.iter().map(|&v| Pel::from(v)).collect::<Vec<Pel>>();
667 self.encode_idr_samples(
668 &widen(y),
669 y_stride,
670 &widen(cb),
671 cb_stride,
672 &widen(cr),
673 cr_stride,
674 )
675 }
676
677 /// Encode one picture from raw planes of samples (each `Pel` a sample of
678 /// the configured bit depth) with their strides in samples.
679 pub fn encode_idr_samples(
680 &self,
681 y: &[Pel],
682 y_stride: usize,
683 cb: &[Pel],
684 cb_stride: usize,
685 cr: &[Pel],
686 cr_stride: usize,
687 ) -> Result<EncodedPicture> {
688 let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?;
689 let (mut qp, target) = match self.cfg.rate_control {
690 RateControl::ConstantQp(qp) => (qp.clamp(self.qp_min(), 51), None),
691 RateControl::TargetBits(bits) => (self.qp_for_bits(bits), Some(bits)),
692 RateControl::Bitrate { kbps, fps } => {
693 let bits = bitrate_picture_bits(kbps, fps);
694 (self.qp_for_bits(bits), Some(bits))
695 }
696 };
697 let mut coded = self.code_picture(&padded, qp)?;
698 if let Some(target) = target {
699 let actual = coded.au.len() as f64 * 8.0;
700 let target = target as f64;
701 if (actual - target).abs() / target > 0.25 {
702 // One correction pass, from the measured slope rather than the
703 // model: 6 QP steps is a factor of two in rate.
704 let correction = 6.0 * (actual / target).log2();
705 let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32;
706 let corrected = corrected.clamp(self.qp_min(), 51);
707 if corrected != qp {
708 qp = corrected;
709 coded = self.code_picture(&padded, qp)?;
710 }
711 }
712 }
713 Ok(coded)
714 }
715
716 /// The lowest QP this encoder codes at: `-QpBdOffset`.
717 pub(crate) fn qp_min(&self) -> i32 {
718 qp_min(u32::from(self.cfg.bit_depth))
719 }
720
721 /// The QP that codes one picture of `bits` bits at the anchor rate model.
722 fn qp_for_bits(&self, bits: u64) -> i32 {
723 let pixels = (self.cfg.width as f64) * (self.cfg.height as f64);
724 let target_bpp = (bits as f64 / pixels).max(1e-4);
725 let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2();
726 (qp.round() as i32).clamp(self.qp_min(), 51)
727 }
728
729 /// Encode a batch of pictures, each as its own IDR access unit.
730 ///
731 /// The wavefront inside a single picture already uses every core, so this is
732 /// a convenience for callers with a list, not a second layer of threads.
733 pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>>
734 where
735 I: IntoIterator<Item = &'a VideoFrame>,
736 {
737 frames.into_iter().map(|f| self.encode_idr(f)).collect()
738 }
739
740 /// Copy the source into coded-size planes, replicating the edge into the
741 /// padding rather than filling it with black: the padding is coded and then
742 /// cropped away, and a black border would bleed into the last real column
743 /// through the prediction and the transform that straddles it.
744 pub(crate) fn pad_source(
745 &self,
746 y: &[Pel],
747 y_stride: usize,
748 cb: &[Pel],
749 cb_stride: usize,
750 cr: &[Pel],
751 cr_stride: usize,
752 ) -> Result<PaddedSource> {
753 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
754 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
755 let (coded_w, coded_h) = (self.coded_width, self.coded_height);
756 let plane = |src: &[Pel],
757 stride: usize,
758 width: usize,
759 height: usize,
760 out_w: usize,
761 out_h: usize|
762 -> Result<Vec<Pel>> {
763 if stride < width || src.len() < (height - 1) * stride + width {
764 return Err(Error::corrupt(
765 "HEVC encode: source plane shorter than its stated size".to_string(),
766 ));
767 }
768 let mut out = vec![0 as Pel; out_w * out_h];
769 for row in 0..out_h {
770 let src_row = row.min(height - 1);
771 let line = &src[src_row * stride..src_row * stride + width];
772 let dst = &mut out[row * out_w..row * out_w + out_w];
773 dst[..width].copy_from_slice(line);
774 let edge = line[width - 1];
775 dst[width..].fill(edge);
776 }
777 Ok(out)
778 };
779 let y = plane(y, y_stride, w, h, coded_w, coded_h)?;
780 let shift = u32::from(self.cfg.bit_depth) - 8;
781 let y8 = y.iter().map(|&v| (v >> shift) as u8).collect();
782 Ok(PaddedSource {
783 y,
784 y8,
785 cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?,
786 cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?,
787 })
788 }
789
790 /// Code one picture at `qp`, wavefront across CTB rows.
791 fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> {
792 self.code_picture_planes(src, qp)
793 .map(|(coded, _, _, _)| coded)
794 }
795
796 /// [`Encoder::code_picture`], also returning the padded reconstruction the
797 /// next picture of a sequence predicts from.
798 pub(crate) fn code_picture_planes(&self, src: &PaddedSource, qp: i32) -> Result<PictureRecon> {
799 let (width, height) = (self.coded_width, self.coded_height);
800 let ctb = self.cfg.ctb_size;
801 let cols = width.div_ceil(ctb);
802 let rows = height.div_ceil(ctb);
803
804 let mut rec_y = vec![0 as Pel; width * height];
805 let mut rec_cb = vec![0 as Pel; width / 2 * height / 2];
806 let mut rec_cr = vec![0 as Pel; width / 2 * height / 2];
807
808 let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect();
809 let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect();
810 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
811 (0..rows).map(|_| Mutex::new(None)).collect();
812 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
813 // Each row publishes the transform-block sizes of its band, which the
814 // deblocking filter reads its edges off once the picture is whole.
815 let tu_bands: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
816
817 // One band of the reconstruction per CTB row, handed out by index.
818 let mut bands_y: Vec<&mut [Pel]> = rec_y.chunks_mut(ctb * width).collect();
819 let mut bands_cb: Vec<&mut [Pel]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect();
820 let mut bands_cr: Vec<&mut [Pel]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect();
821 let threads = self.threads.min(rows).max(1);
822 // Round-robin: worker t owns rows t, t + threads, ... Each row's
823 // predecessor therefore belongs to another worker that is never waiting
824 // on it, so the wavefront cannot deadlock.
825 let mut per_worker: Vec<Vec<RowAssignment<'_>>> =
826 (0..threads).map(|_| Vec::new()).collect();
827 for row in (0..rows).rev() {
828 let y = bands_y.pop().expect("one band per row");
829 let cb = bands_cb.pop().expect("one band per row");
830 let cr = bands_cr.pop().expect("one band per row");
831 per_worker[row % threads].push((row, y, cb, cr));
832 }
833 for worker in per_worker.iter_mut() {
834 worker.reverse();
835 }
836
837 let slice_qp = qp;
838 std::thread::scope(|scope| {
839 for worker_rows in per_worker {
840 let boundaries = &boundaries;
841 let progress = &progress;
842 let wpp_contexts = &wpp_contexts;
843 let substreams = &substreams;
844 let tu_bands = &tu_bands;
845 let src = &src;
846 scope.spawn(move || {
847 for (row, band_y, band_cb, band_cr) in worker_rows {
848 let band_y0 = row * ctb;
849 // Wait for the row above to be two CTBs ahead, which is
850 // both the prediction reach and the CABAC sync point.
851 if row > 0 {
852 wait_for(&progress[row - 1], 2.min(cols));
853 }
854 let contexts = if row == 0 || cols < 2 {
855 Contexts::new(slice_qp)
856 } else {
857 wpp_contexts[row - 1]
858 .lock()
859 .ok()
860 .and_then(|c| c.clone())
861 .unwrap_or_else(|| Contexts::new(slice_qp))
862 };
863 let mut enc = CabacEncoder::new(contexts);
864 let mut coder = CtuEncoder::new(
865 SourcePlanes {
866 y: &src.y,
867 cb: &src.cb,
868 cr: &src.cr,
869 },
870 RowState {
871 rec_y: band_y,
872 rec_cb: band_cb,
873 rec_cr: band_cr,
874 publish: &boundaries[row],
875 above: if row == 0 {
876 None
877 } else {
878 Some(&boundaries[row - 1])
879 },
880 },
881 width,
882 height,
883 ctb,
884 band_y0,
885 slice_qp,
886 true,
887 self.cfg.rdo_candidates,
888 self.cfg.chroma_mode_search,
889 self.cfg.chroma_rd_weight,
890 self.cfg.intra_nxn,
891 self.cfg.sign_hiding,
892 self.cfg.rdoq,
893 self.cfg.rdoq_estimate,
894 self.cfg.transform_skip,
895 self.cfg.rqt,
896 self.cfg.cu64,
897 self.cfg.min_cu_size.max(8).trailing_zeros(),
898 u32::from(self.cfg.bit_depth),
899 );
900 for col in 0..cols {
901 if row > 0 {
902 wait_for(&progress[row - 1], (col + 2).min(cols));
903 }
904 coder.encode_ctu(col, &mut enc);
905 if col == 1 {
906 // 9.3.2.1: the row below syncs from the state
907 // after the second CTB of this row.
908 if let Ok(mut slot) = wpp_contexts[row].lock() {
909 *slot = Some(enc.contexts.clone());
910 }
911 }
912 progress[row].0.store(col + 1, Ordering::Release);
913 let last_in_picture = row + 1 == rows && col + 1 == cols;
914 enc.encode_terminate(u32::from(last_in_picture));
915 if !last_in_picture && col + 1 == cols {
916 // end_of_subset_one_bit, then byte alignment.
917 enc.encode_terminate(1);
918 }
919 }
920 if let Ok(mut slot) = substreams[row].lock() {
921 *slot = enc.finish();
922 }
923 if let Ok(mut slot) = tu_bands[row].lock() {
924 *slot = coder.tu_log2_band().to_vec();
925 }
926 }
927 });
928 }
929 });
930
931 let substreams: Vec<Vec<u8>> = substreams
932 .into_iter()
933 .map(|m| m.into_inner().unwrap_or_default())
934 .collect();
935 if self.cfg.deblock {
936 let mut tus = TuMap::new(width, height);
937 for (row, band) in tu_bands.into_iter().enumerate() {
938 let band = band.into_inner().unwrap_or_default();
939 let band_y0 = row * ctb;
940 let band_rows = (height - band_y0).min(ctb) / 4;
941 tus.absorb_band(band_y0, band_rows, &band);
942 }
943 deblock(
944 &mut rec_y,
945 &mut rec_cb,
946 &mut rec_cr,
947 width,
948 height,
949 qp,
950 u32::from(self.cfg.bit_depth),
951 &tus,
952 );
953 }
954
955 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
956 let recon = self
957 .cfg
958 .keep_recon
959 .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr));
960 Ok((EncodedPicture { au, qp, recon }, rec_y, rec_cb, rec_cr))
961 }
962
963 /// Parameter sets, optional SEI, and the slice, in Annex-B framing.
964 fn assemble_au(
965 &self,
966 qp: i32,
967 substreams: &[Vec<u8>],
968 rec_y: &[Pel],
969 rec_cb: &[Pel],
970 rec_cr: &[Pel],
971 ) -> Vec<u8> {
972 let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256);
973 write_annex_b(
974 &mut au,
975 NalHeader::new(NalUnitType::Vps),
976 &self.vps.to_rbsp(),
977 true,
978 );
979 write_annex_b(
980 &mut au,
981 NalHeader::new(NalUnitType::Sps),
982 &self.sps.to_rbsp(),
983 true,
984 );
985 write_annex_b(
986 &mut au,
987 NalHeader::new(NalUnitType::Pps),
988 &self.pps.to_rbsp(),
989 true,
990 );
991 if let Some(rbsp) =
992 sei::hdr_metadata_rbsp_with(self.cfg.mastering_display, self.cfg.content_light)
993 {
994 write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true);
995 }
996
997 // Entry points count the bytes as they appear in the NAL, emulation
998 // prevention included. Each substream ends on a byte whose last written
999 // bit is the flush's one bit, so no escape sequence straddles a
1000 // boundary and each substream can be measured on its own.
1001 let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len());
1002 for stream in substreams {
1003 let mut out = Vec::with_capacity(stream.len() + 8);
1004 escape_rbsp(stream, &mut out);
1005 escaped.push(out);
1006 }
1007 let mut header = SliceHeader::intra(&self.pps, qp - 26);
1008 header.entry_point_offsets = escaped
1009 .iter()
1010 .take(escaped.len().saturating_sub(1))
1011 .map(|s| s.len() as u32)
1012 .collect();
1013 let mut writer = ec_core::bitio::BitWriter::with_capacity(64);
1014 header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl);
1015 let mut rbsp = writer.into_bytes();
1016 for stream in substreams {
1017 rbsp.extend_from_slice(stream);
1018 }
1019 write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true);
1020
1021 if self.cfg.picture_hash {
1022 let (w, h) = (self.coded_width, self.coded_height);
1023 // The hash covers the samples as the picture stores them: one
1024 // byte each at 8 bits, two (little-endian) at 10.
1025 let bps = if self.cfg.bit_depth == 10 { 2 } else { 1 };
1026 let (by, bcb, bcr) = (
1027 sample_bytes(rec_y, self.cfg.bit_depth),
1028 sample_bytes(rec_cb, self.cfg.bit_depth),
1029 sample_bytes(rec_cr, self.cfg.bit_depth),
1030 );
1031 let rbsp = sei::decoded_picture_hash_rbsp(&[
1032 (&by, w * bps, w * bps, h),
1033 (&bcb, w / 2 * bps, w / 2 * bps, h / 2),
1034 (&bcr, w / 2 * bps, w / 2 * bps, h / 2),
1035 ]);
1036 write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false);
1037 }
1038 au
1039 }
1040
1041 pub(crate) fn crop_recon(&self, rec_y: &[Pel], rec_cb: &[Pel], rec_cr: &[Pel]) -> VideoFrame {
1042 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
1043 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
1044 let bd = self.cfg.bit_depth;
1045 let crop = |src: &[Pel], stride: usize, width: usize, height: usize| -> Vec<u8> {
1046 let mut out = Vec::with_capacity(width * height);
1047 for row in 0..height {
1048 out.extend(sample_bytes(&src[row * stride..row * stride + width], bd));
1049 }
1050 out
1051 };
1052 let bps = if bd == 10 { 2 } else { 1 };
1053 let planes = vec![
1054 Plane::new(crop(rec_y, self.coded_width, w, h), w * bps),
1055 Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw * bps),
1056 Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw * bps),
1057 ];
1058 let format = if bd == 10 {
1059 PixelFormat::I010
1060 } else {
1061 PixelFormat::I420
1062 };
1063 VideoFrame::try_new(format, w as u32, h as u32, planes)
1064 .expect("cropped planes are exactly the size the format asks for")
1065 }
1066}
1067
1068/// Samples as bytes: one byte each at 8 bits, little-endian pairs at 10.
1069pub(crate) fn sample_bytes(samples: &[Pel], bit_depth: u8) -> Vec<u8> {
1070 if bit_depth == 10 {
1071 samples.iter().flat_map(|v| v.to_le_bytes()).collect()
1072 } else {
1073 samples.iter().map(|&v| v as u8).collect()
1074 }
1075}
1076
1077/// A progress counter on its own cache line.
1078///
1079/// Twelve workers polling twelve counters packed eight to a line spend their
1080/// time invalidating each other's caches instead of coding; the padding is the
1081/// difference between a wavefront and a contention benchmark.
1082#[repr(align(64))]
1083pub(crate) struct Progress(pub(crate) AtomicUsize);
1084
1085/// Spin, then yield, then sleep until a row's progress counter reaches `target`.
1086///
1087/// A worker that spins hard is a worker holding a core the wavefront needs
1088/// somewhere else, so the wait backs off to a sleep at roughly the granularity
1089/// of one coding tree block.
1090fn wait_for(counter: &Progress, target: usize) {
1091 let never = AtomicBool::new(false);
1092 wait_for_or_abort(counter, target, &never);
1093}
1094
1095/// [`wait_for`] that gives up when `abort` is set. Returns whether the target
1096/// was reached.
1097pub(crate) fn wait_for_or_abort(counter: &Progress, target: usize, abort: &AtomicBool) -> bool {
1098 let mut spins = 0u32;
1099 while counter.0.load(Ordering::Acquire) < target {
1100 if abort.load(Ordering::Acquire) {
1101 return false;
1102 }
1103 if spins < 128 {
1104 std::hint::spin_loop();
1105 } else if spins < 256 {
1106 std::thread::yield_now();
1107 } else {
1108 std::thread::sleep(std::time::Duration::from_micros(50));
1109 }
1110 spins += 1;
1111 }
1112 true
1113}
1114
1115/// One CTB row handed to a worker: its index and its band of each plane.
1116type RowAssignment<'a> = (usize, &'a mut [Pel], &'a mut [Pel], &'a mut [Pel]);
1117
1118pub(crate) struct PaddedSource {
1119 pub(crate) y: Vec<Pel>,
1120 /// The luma as 8-bit samples (`y >> (bit_depth - 8)`): what the motion search measures.
1121 pub(crate) y8: Vec<u8>,
1122 pub(crate) cb: Vec<Pel>,
1123 pub(crate) cr: Vec<Pel>,
1124}