forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

encoder.rs842 lines, 36.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 `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 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::{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}
50
51/// Whether 4x4 transform units may skip the transform and code residual
52/// samples directly (`transform_skip_enabled_flag`).
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum TransformSkip {
55 /// No transform skip; every default stream is byte-identical.
56 Off,
57 /// Skip the transform on every 4x4 TU that has non-zero residual.
58 AlwaysFor4x4,
59 /// Decide per 4x4 luma transform block by rate-distortion: quantise and
60 /// reconstruct the block both ways and keep the cheaper one. Unconditional
61 /// skip is a big win on screen capture and a loss on camera content
62 /// (measured, see `transform_skip`), which is exactly what a per-block
63 /// decision resolves.
64 Rd,
65}
66
67/// Encoder settings.
68#[derive(Debug, Clone)]
69pub struct EncoderConfig {
70 /// Displayed width; the coded picture is padded up to a whole number of
71 /// minimum coding blocks and cropped back by the conformance window.
72 pub width: u32,
73 /// Displayed height.
74 pub height: u32,
75 /// Quantiser or bit target.
76 pub rate_control: RateControl,
77 /// Worker threads; 0 means "as many as the machine has".
78 pub threads: usize,
79 /// Coding tree block size, 32 (default) or 64.
80 ///
81 /// The wavefront hands one CTB *row* to a worker, so the row count is the
82 /// parallelism this encoder has: 1080 lines are 17 rows at 64 but 34 at 32.
83 /// Rows are dealt round-robin, so on a twelve-core machine 17 rows means
84 /// five workers take two rows while seven take one — half the machine idles
85 /// through the second half of the picture. 34 rows deal three-and-three.
86 /// Measured on 1080p at QP 27: the two sizes encode at the same speed on one
87 /// thread (1.80 fps each), but on twelve 32 runs 9.03 fps against 64's 7.92,
88 /// for 1.0% more bits and 0.02 dB less PSNR — the whole difference is
89 /// wavefront occupancy, which is why 32 is the default. 64 takes its bits
90 /// back when the picture is tall enough to fill the workers anyway (2160
91 /// lines are 34 rows at 64) or when nothing is waiting for the encode.
92 pub ctb_size: usize,
93 /// How many of the 35 intra modes get a full rate-distortion trial, on top
94 /// of the most probable mode, which always gets one.
95 ///
96 /// Swept against x265 at matched features on four real clips (BD-PSNR
97 /// luma / all-plane, wall time for the whole four-QP ladder):
98 ///
99 /// | k | film 3840x1608 | web 1138x640 | screen 2560x1440 | phone 1080p |
100 /// |---|----------------|-------------------|------------------|-------------|
101 /// | 1 | -0.840 / -0.815 38s | -0.728 / -0.733 8s | | |
102 /// | 2 | -0.731 / -0.730 40s | -0.603 / -0.632 9s | -2.521 / -2.420 29s | -0.435 / -0.444 11s |
103 /// | 3 | -0.703 / -0.709 43s | -0.556 / -0.596 10s | -2.493 / -2.402 31s | -0.401 / -0.416 11s |
104 /// | 4 | -0.693 / -0.705 46s | -0.530 / -0.574 10s | | |
105 /// | 5 | -0.685 / -0.703 49s | -0.507 / -0.556 11s | -2.465 / -2.360 35s | -0.366 / -0.387 13s |
106 /// | 8 | -0.684 / -0.710 59s | -0.471 / -0.525 14s | -2.453 / -2.368 41s | -0.340 / -0.361 16s |
107 ///
108 /// Every clip improves monotonically up to 5, which is why 5 is the
109 /// default. Eight buys nothing on the film clip (+0.001 luma, and its
110 /// all-plane figure goes *backwards*) for another 20% of wall time, so the
111 /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate
112 /// test re-runs the sweep.
113 pub rdo_candidates: usize,
114 /// Whether the chroma prediction mode is chosen by rate-distortion over the
115 /// five modes the syntax allows, instead of always taking the derived mode.
116 ///
117 /// Off by default: measured against x265 on four real clips it is a wash,
118 /// and on screen capture it is a loss (BD-PSNR luma / all-plane, derived
119 /// mode -> search, `chroma_rd_weight: 1.0`):
120 ///
121 /// | clip | derived | search |
122 /// |------|---------|--------|
123 /// | 4K film | -0.685 / -0.703 | -0.757 / **-0.606** |
124 /// | 1138x640 web | -0.507 / -0.556 | -0.584 / **-0.505** |
125 /// | 1440p screen capture | **-2.465 / -2.360** | -2.617 / -2.460 |
126 /// | 1080p phone | -0.366 / **-0.387** | -0.477 / -0.384 |
127 ///
128 /// Luma falls on every clip because the extra chroma bits come out of the
129 /// same budget at a fixed QP; all-plane gains 0.10 dB and 0.05 dB on the two
130 /// camera clips, is flat on the third and loses 0.10 dB on the screen
131 /// capture, for 10-15% more encode time. The average is +0.01 dB all-plane,
132 /// which is not a default. [`EncoderConfig::chroma_rd_weight`] was swept at
133 /// 0.25/0.5/1.0/2.0 and did not change the shape of that table: the screen
134 /// capture loses at every weight, so the cause is not the lambda.
135 pub chroma_mode_search: bool,
136 /// Weight on chroma SSD in that decision, against the luma lambda. Swept
137 /// at 0.25/0.5/1.0/2.0 on three clips; 1.0 is the best of them everywhere
138 /// the search wins at all (4K film all-plane: -0.606 at 1.0 against -0.649
139 /// at 0.25, -0.619 at 0.5, -0.657 at 2.0).
140 pub chroma_rd_weight: f64,
141 /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a
142 /// *coarser* search that is not always faster: on real pictures the 8x8
143 /// blocks pay for their search in residual bits (measured: -27% bits and
144 /// +1.5 dB at QP 22 on a 1080p camera frame, at the same wall time), which
145 /// is why 8 is the default.
146 pub min_cu_size: usize,
147 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions
148 /// (PART_NxN). On: measured at +2.14 dB BD-PSNR on a 2560x1440 screen
149 /// capture (-2.619 dB against x265 without it, -0.479 dB with) and
150 /// +0.007 dB on 1080p film, so it never loses.
151 pub intra_nxn: bool,
152
153 /// Whether a sub-block's first sign is hidden in the parity of its
154 /// absolute levels (`sign_data_hiding_enabled_flag`). Buys one bypass bin
155 /// per qualifying sub-block for a level nudged by one.
156 ///
157 /// Off: measured at -0.033 dB BD-PSNR on a 2560x1440 screen capture and
158 /// -0.043 dB on 1080p film. Hiding is not optional per sub-block, so every
159 /// qualifying one pays for the bin whether the nudge is cheap or not, and
160 /// with levels that come straight from the quantiser's rounding the nudges
161 /// cost more than the signs save. Worth re-measuring once RDOQ lands: that
162 /// is where the gain in other encoders comes from.
163 pub sign_hiding: bool,
164
165 /// Whether quantised levels get a rate-distortion search (RDOQ) that
166 /// offers each small level the magnitudes below it and takes one when the
167 /// squared error it gives up costs less than the bits it saves.
168 ///
169 /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 ->
170 /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360),
171 /// with the all-plane figures moving the same way. The rate is the CABAC
172 /// coder's own price for the whole block, so dropping a level is priced
173 /// with the significance map and last position that follow from it.
174 pub rdoq: bool,
175 /// Whether RDOQ's per-candidate bit cost comes from an estimated
176 /// per-context fractional-bit table (x265/HM `entropyBits`-style: the
177 /// entropy of the bin under its context's current probability state)
178 /// instead of replaying the exact adaptive-CABAC coder for every trial.
179 /// Changes output bytes (the estimate is not exact). On by default:
180 /// measured 1.6x faster on `ec-bench`'s h265 encode row and, on the
181 /// synthetic `bd_psnr_vs_x265` clip, a small BD-PSNR-YUV *gain* over the
182 /// exact-replay path (+7.948 vs +7.880 dB against x265) rather than a
183 /// loss. `false` restores exact per-trial CABAC replay for A/B.
184 pub rdoq_estimate: bool,
185 /// Whether 4x4 TUs may skip the integer transform.
186 ///
187 /// `Rd` by default: the tool is the screen-content lever, and it wants a
188 /// per-block decision, not a switch. BD-PSNR luma / all-plane against x265
189 /// at matched features over the four-QP ladder (`EC_H265_TSKIP=0|always|rd`
190 /// in `bd_psnr_vs_x265`, real clips, 24 pictures each):
191 ///
192 /// | clip | `Off` | `AlwaysFor4x4` | `Rd` |
193 /// |------|-------|----------------|------|
194 /// | 1440p screen capture A | -0.381 / -0.438 | +1.485 / +1.373 | +1.034 / +0.918 |
195 /// | 1440p screen capture B | +0.716 / +0.561 | +0.783 / +0.222 | +1.133 / +0.781 |
196 /// | 1440p screen capture C | +0.213 / +0.099 | | +0.124 / +0.008 |
197 /// | 1080p film | +0.584 / +0.468 | | +0.580 / +0.460 |
198 ///
199 /// Unconditional skip is worth +1.8 dB all-plane on A and -0.34 dB on B, so
200 /// neither setting of a switch is right; the per-block trial takes A's win
201 /// without B's loss and leaves film where it was (-0.008 dB, the estimate
202 /// proxy's noise). The cost is the second quantise-and-reconstruct pass on
203 /// every committed 4x4 luma block: the whole four-QP ladder went 111s ->
204 /// 290s on screen capture A and 427s -> 494s on film. Set `Off` to buy that
205 /// time back.
206 pub transform_skip: TransformSkip,
207 /// Whether the transform tree may split once (rate-quantisation transform):
208 /// the luma TU of a 2Nx2N coding unit may be coded as four half-size
209 /// children when that costs less in `J = SSD + lambda * bits`.
210 ///
211 /// On by default: measured against x265 over the four-point ladder it is
212 /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which
213 /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`).
214 pub rqt: bool,
215 /// Whether a 64x64 coding tree block may stay one coding unit instead of
216 /// always splitting to 32x32. Only reachable with `ctb_size` 64.
217 ///
218 /// A 64x64 intra coding unit still predicts and transforms in four 32x32
219 /// blocks -- 32x32 is HEVC's largest transform -- so what it buys is three
220 /// split flags and three mode signallings, and what it costs is one luma
221 /// direction for the whole 64x64. Measured in `lanes/h265-cu64-r1.report.md`.
222 ///
223 /// On by default: against x265 over the four-point ladder it is worth
224 /// +0.007 dB BD-PSNR on film and +0.098 dB on screen capture over always
225 /// splitting a 64x64 tree block, and the default `ctb_size` of 32 leaves
226 /// it unreachable anyway.
227 pub cu64: bool,
228 /// What the samples mean, written into the VUI.
229 pub video_signal_type: Option<VideoSignalType>,
230 /// Sample aspect ratio.
231 pub sample_aspect_ratio: Option<(u16, u16)>,
232 /// `(num_units_in_tick, time_scale)`; also picks the level.
233 pub timing: Option<(u32, u32)>,
234 /// HDR mastering metadata, written as prefix SEI.
235 pub content_light: ContentLight,
236 /// Run the in-loop deblocking filter over the finished picture.
237 ///
238 /// An intra picture predicts from its unfiltered reconstruction, so this
239 /// changes only what a decoder shows -- and what the reconstruction and its
240 /// picture hash therefore have to say.
241 pub deblock: bool,
242 /// Emit the decoded picture hash SEI (MD5 of the reconstruction).
243 pub picture_hash: bool,
244 /// Return the reconstruction alongside the bitstream.
245 pub keep_recon: bool,
246}
247
248impl EncoderConfig {
249 /// Defaults for `width x height`: constant QP 27, every core, 32x32 CTBs
250 /// (see [`EncoderConfig::ctb_size`] for why 32 and not 64).
251 pub fn new(width: u32, height: u32) -> EncoderConfig {
252 EncoderConfig {
253 width,
254 height,
255 rate_control: RateControl::ConstantQp(27),
256 threads: 0,
257 ctb_size: 32,
258 rdo_candidates: 5,
259 chroma_mode_search: false,
260 chroma_rd_weight: 1.0,
261 min_cu_size: 8,
262 intra_nxn: true,
263 sign_hiding: false,
264 rdoq: true,
265 rdoq_estimate: true,
266 transform_skip: TransformSkip::Rd,
267 rqt: true,
268 cu64: true,
269 video_signal_type: None,
270 sample_aspect_ratio: None,
271 timing: None,
272 content_light: ContentLight::default(),
273 deblock: true,
274 picture_hash: false,
275 keep_recon: false,
276 }
277 }
278}
279
280/// One coded picture.
281#[derive(Debug, Clone)]
282pub struct EncodedPicture {
283 /// The access unit, Annex-B framed: VPS, SPS, PPS, optional SEI, IDR slice.
284 pub au: Vec<u8>,
285 /// The quantiser the picture was coded at.
286 pub qp: i32,
287 /// The reconstruction, cropped to the displayed size, when
288 /// [`EncoderConfig::keep_recon`] asked for it. Bit-identical to what a
289 /// conformant decoder produces, because the in-loop filters are off.
290 pub recon: Option<VideoFrame>,
291}
292
293/// An intra-only HEVC encoder.
294pub struct Encoder {
295 cfg: EncoderConfig,
296 vps: Vps,
297 sps: Sps,
298 pps: Pps,
299 coded_width: usize,
300 coded_height: usize,
301 threads: usize,
302}
303
304/// Bits per pixel this encoder spends at QP 27, the anchor the bit-target model
305/// walks from (measured on 1080p fixtures; the incumbent's own figure was 0.6).
306const BPP_AT_QP27: f64 = 0.6;
307
308impl Encoder {
309 /// Build an encoder, refusing dimensions it cannot code.
310 pub fn new(cfg: EncoderConfig) -> Result<Encoder> {
311 if cfg.width < 16 || cfg.height < 16 {
312 return Err(Error::unsupported(
313 format!("HEVC encode of {}x{}", cfg.width, cfg.height),
314 "pictures below 16x16 have no coding tree",
315 ));
316 }
317 if cfg.ctb_size != 64 && cfg.ctb_size != 32 {
318 return Err(Error::unsupported(
319 format!("HEVC coding tree block of {}", cfg.ctb_size),
320 "this encoder codes 64x64 or 32x32 trees",
321 ));
322 }
323 // The coded picture is a whole number of minimum coding blocks (8x8);
324 // the conformance window crops the padding back off.
325 let coded_width = (cfg.width as usize).next_multiple_of(8);
326 let coded_height = (cfg.height as usize).next_multiple_of(8);
327 let fps = cfg
328 .timing
329 .map(|(units, scale)| f64::from(scale) / f64::from(units.max(1)))
330 .unwrap_or(30.0);
331 let ptl = ProfileTierLevel::main(ProfileTierLevel::level_for(
332 coded_width as u32,
333 coded_height as u32,
334 fps,
335 ));
336 let vps = Vps {
337 id: 0,
338 ptl,
339 max_dec_pic_buffering_minus1: 0,
340 max_num_reorder_pics: 0,
341 };
342 let log2_ctb = cfg.ctb_size.trailing_zeros();
343 let sps = Sps {
344 vps_id: 0,
345 id: 0,
346 chroma_format_idc: 1,
347 separate_colour_plane: false,
348 pic_width_in_luma_samples: coded_width as u32,
349 pic_height_in_luma_samples: coded_height as u32,
350 conf_win: ConformanceWindow {
351 left: 0,
352 right: (coded_width - cfg.width as usize) as u32 / 2,
353 top: 0,
354 bottom: (coded_height - cfg.height as usize) as u32 / 2,
355 },
356 bit_depth_luma_minus8: 0,
357 bit_depth_chroma_minus8: 0,
358 log2_max_poc_lsb_minus4: 4,
359 max_dec_pic_buffering_minus1: 0,
360 max_num_reorder_pics: 0,
361 log2_min_cb_size_minus3: 0,
362 log2_diff_max_min_cb_size: log2_ctb - 3,
363 log2_min_tb_size_minus2: 0,
364 log2_diff_max_min_tb_size: 3,
365 max_transform_hierarchy_depth_inter: 0,
366 max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 },
367 scaling_list_enabled: false,
368 amp_enabled: false,
369 // No in-loop filters: see `Encoder` docs and the PPS below.
370 sao_enabled: false,
371 pcm_enabled: false,
372 pcm: None,
373 num_short_term_ref_pic_sets: 0,
374 short_term_ref_pic_sets: Vec::new(),
375 long_term_ref_pics_present: false,
376 num_long_term_ref_pics_sps: 0,
377 long_term_ref_pics_sps: Vec::new(),
378 temporal_mvp_enabled: false,
379 strong_intra_smoothing: true,
380 ptl,
381 vui: Some(VuiParameters {
382 sample_aspect_ratio: cfg.sample_aspect_ratio,
383 video_signal_type: cfg.video_signal_type,
384 timing: cfg.timing,
385 }),
386 };
387 let pps = Pps {
388 id: 0,
389 sps_id: 0,
390 entropy_coding_sync_enabled: true,
391 // SAO is off; deblocking follows `EncoderConfig::deblock`. An
392 // intra-only stream predicts from its own *unfiltered*
393 // reconstruction (8.4.4.2.1), so the deblocking filter changes
394 // neither side's prediction: running it over the finished picture
395 // here keeps the reconstruction bit-identical to a decoder's
396 // output, and the picture hash that rides on it honest.
397 sign_data_hiding_enabled: cfg.sign_hiding,
398 transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,
399 deblocking_filter_control_present: true,
400 deblocking_filter_disabled: !cfg.deblock,
401 loop_filter_across_slices_enabled: false,
402 ..Pps::default()
403 };
404 let threads = if cfg.threads == 0 {
405 std::thread::available_parallelism().map_or(1, |n| n.get())
406 } else {
407 cfg.threads
408 };
409 Ok(Encoder {
410 cfg,
411 vps,
412 sps,
413 pps,
414 coded_width,
415 coded_height,
416 threads,
417 })
418 }
419
420 /// The sequence parameter set this encoder writes.
421 pub fn sps(&self) -> &Sps {
422 &self.sps
423 }
424
425 /// Encode one picture as an IDR access unit.
426 ///
427 /// The frame must be [`PixelFormat::I420`] at the configured size; padding
428 /// to the coded size is this encoder's job, not the caller's.
429 pub fn encode_idr(&self, frame: &VideoFrame) -> Result<EncodedPicture> {
430 if frame.format != PixelFormat::I420 {
431 return Err(Error::unsupported(
432 format!("HEVC encode of {:?}", frame.format),
433 "this encoder codes 8-bit 4:2:0 planar",
434 ));
435 }
436 if frame.width != self.cfg.width || frame.height != self.cfg.height {
437 return Err(Error::corrupt(format!(
438 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
439 frame.width, frame.height, self.cfg.width, self.cfg.height
440 )));
441 }
442 let planes: Vec<(&[u8], usize)> = frame
443 .planes
444 .iter()
445 .map(|p: &Plane| (&p.data[..], p.stride))
446 .collect();
447 self.encode_idr_planes(
448 planes[0].0,
449 planes[0].1,
450 planes[1].0,
451 planes[1].1,
452 planes[2].0,
453 planes[2].1,
454 )
455 }
456
457 /// Encode one picture from raw I420 planes with their strides.
458 ///
459 /// This is the surface a compatibility shim maps onto: the planes are the
460 /// *displayed* picture, and the conformance window handles the rest.
461 pub fn encode_idr_planes(
462 &self,
463 y: &[u8],
464 y_stride: usize,
465 cb: &[u8],
466 cb_stride: usize,
467 cr: &[u8],
468 cr_stride: usize,
469 ) -> Result<EncodedPicture> {
470 let padded = self.pad_source(y, y_stride, cb, cb_stride, cr, cr_stride)?;
471 let (mut qp, target) = match self.cfg.rate_control {
472 RateControl::ConstantQp(qp) => (qp.clamp(0, 51), None),
473 RateControl::TargetBits(bits) => {
474 let pixels = (self.cfg.width as f64) * (self.cfg.height as f64);
475 let target_bpp = (bits as f64 / pixels).max(1e-4);
476 let qp = 27.0 + 6.0 * (BPP_AT_QP27 / target_bpp).log2();
477 ((qp.round() as i32).clamp(0, 51), Some(bits))
478 }
479 };
480 let mut coded = self.code_picture(&padded, qp)?;
481 if let Some(target) = target {
482 let actual = coded.au.len() as f64 * 8.0;
483 let target = target as f64;
484 if (actual - target).abs() / target > 0.25 {
485 // One correction pass, from the measured slope rather than the
486 // model: 6 QP steps is a factor of two in rate.
487 let correction = 6.0 * (actual / target).log2();
488 let corrected = (qp as f64 + correction.clamp(-12.0, 12.0)).round() as i32;
489 let corrected = corrected.clamp(0, 51);
490 if corrected != qp {
491 qp = corrected;
492 coded = self.code_picture(&padded, qp)?;
493 }
494 }
495 }
496 Ok(coded)
497 }
498
499 /// Encode a batch of pictures, each as its own IDR access unit.
500 ///
501 /// The wavefront inside a single picture already uses every core, so this is
502 /// a convenience for callers with a list, not a second layer of threads.
503 pub fn encode_batch<'a, I>(&self, frames: I) -> Result<Vec<EncodedPicture>>
504 where
505 I: IntoIterator<Item = &'a VideoFrame>,
506 {
507 frames.into_iter().map(|f| self.encode_idr(f)).collect()
508 }
509
510 /// Copy the source into coded-size planes, replicating the edge into the
511 /// padding rather than filling it with black: the padding is coded and then
512 /// cropped away, and a black border would bleed into the last real column
513 /// through the prediction and the transform that straddles it.
514 fn pad_source(
515 &self,
516 y: &[u8],
517 y_stride: usize,
518 cb: &[u8],
519 cb_stride: usize,
520 cr: &[u8],
521 cr_stride: usize,
522 ) -> Result<PaddedSource> {
523 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
524 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
525 let (coded_w, coded_h) = (self.coded_width, self.coded_height);
526 let plane = |src: &[u8],
527 stride: usize,
528 width: usize,
529 height: usize,
530 out_w: usize,
531 out_h: usize|
532 -> Result<Vec<u8>> {
533 if stride < width || src.len() < (height - 1) * stride + width {
534 return Err(Error::corrupt(
535 "HEVC encode: source plane shorter than its stated size".to_string(),
536 ));
537 }
538 let mut out = vec![0u8; out_w * out_h];
539 for row in 0..out_h {
540 let src_row = row.min(height - 1);
541 let line = &src[src_row * stride..src_row * stride + width];
542 let dst = &mut out[row * out_w..row * out_w + out_w];
543 dst[..width].copy_from_slice(line);
544 let edge = line[width - 1];
545 dst[width..].fill(edge);
546 }
547 Ok(out)
548 };
549 Ok(PaddedSource {
550 y: plane(y, y_stride, w, h, coded_w, coded_h)?,
551 cb: plane(cb, cb_stride, cw, ch, coded_w / 2, coded_h / 2)?,
552 cr: plane(cr, cr_stride, cw, ch, coded_w / 2, coded_h / 2)?,
553 })
554 }
555
556 /// Code one picture at `qp`, wavefront across CTB rows.
557 fn code_picture(&self, src: &PaddedSource, qp: i32) -> Result<EncodedPicture> {
558 let (width, height) = (self.coded_width, self.coded_height);
559 let ctb = self.cfg.ctb_size;
560 let cols = width.div_ceil(ctb);
561 let rows = height.div_ceil(ctb);
562
563 let mut rec_y = vec![0u8; width * height];
564 let mut rec_cb = vec![0u8; width / 2 * height / 2];
565 let mut rec_cr = vec![0u8; width / 2 * height / 2];
566
567 let boundaries: Vec<RowBoundary> = (0..rows).map(|_| RowBoundary::new(width)).collect();
568 let progress: Vec<Progress> = (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect();
569 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
570 (0..rows).map(|_| Mutex::new(None)).collect();
571 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
572 // Each row publishes the transform-block sizes of its band, which the
573 // deblocking filter reads its edges off once the picture is whole.
574 let tu_bands: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
575
576 // One band of the reconstruction per CTB row, handed out by index.
577 let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect();
578 let mut bands_cb: Vec<&mut [u8]> = rec_cb.chunks_mut(ctb / 2 * (width / 2)).collect();
579 let mut bands_cr: Vec<&mut [u8]> = rec_cr.chunks_mut(ctb / 2 * (width / 2)).collect();
580 let threads = self.threads.min(rows).max(1);
581 // Round-robin: worker t owns rows t, t + threads, ... Each row's
582 // predecessor therefore belongs to another worker that is never waiting
583 // on it, so the wavefront cannot deadlock.
584 let mut per_worker: Vec<Vec<RowAssignment<'_>>> =
585 (0..threads).map(|_| Vec::new()).collect();
586 for row in (0..rows).rev() {
587 let y = bands_y.pop().expect("one band per row");
588 let cb = bands_cb.pop().expect("one band per row");
589 let cr = bands_cr.pop().expect("one band per row");
590 per_worker[row % threads].push((row, y, cb, cr));
591 }
592 for worker in per_worker.iter_mut() {
593 worker.reverse();
594 }
595
596 let slice_qp = qp;
597 std::thread::scope(|scope| {
598 for worker_rows in per_worker {
599 let boundaries = &boundaries;
600 let progress = &progress;
601 let wpp_contexts = &wpp_contexts;
602 let substreams = &substreams;
603 let tu_bands = &tu_bands;
604 let src = &src;
605 scope.spawn(move || {
606 for (row, band_y, band_cb, band_cr) in worker_rows {
607 let band_y0 = row * ctb;
608 // Wait for the row above to be two CTBs ahead, which is
609 // both the prediction reach and the CABAC sync point.
610 if row > 0 {
611 wait_for(&progress[row - 1], 2.min(cols));
612 }
613 let contexts = if row == 0 || cols < 2 {
614 Contexts::new(slice_qp)
615 } else {
616 wpp_contexts[row - 1]
617 .lock()
618 .ok()
619 .and_then(|c| c.clone())
620 .unwrap_or_else(|| Contexts::new(slice_qp))
621 };
622 let mut enc = CabacEncoder::new(contexts);
623 let mut coder = CtuEncoder::new(
624 SourcePlanes {
625 y: &src.y,
626 cb: &src.cb,
627 cr: &src.cr,
628 },
629 RowState {
630 rec_y: band_y,
631 rec_cb: band_cb,
632 rec_cr: band_cr,
633 publish: &boundaries[row],
634 above: if row == 0 {
635 None
636 } else {
637 Some(&boundaries[row - 1])
638 },
639 },
640 width,
641 height,
642 ctb,
643 band_y0,
644 slice_qp,
645 true,
646 self.cfg.rdo_candidates,
647 self.cfg.chroma_mode_search,
648 self.cfg.chroma_rd_weight,
649 self.cfg.intra_nxn,
650 self.cfg.sign_hiding,
651 self.cfg.rdoq,
652 self.cfg.rdoq_estimate,
653 self.cfg.transform_skip,
654 self.cfg.rqt,
655 self.cfg.cu64,
656 self.cfg.min_cu_size.max(8).trailing_zeros(),
657 );
658 for col in 0..cols {
659 if row > 0 {
660 wait_for(&progress[row - 1], (col + 2).min(cols));
661 }
662 coder.encode_ctu(col, &mut enc);
663 if col == 1 {
664 // 9.3.2.1: the row below syncs from the state
665 // after the second CTB of this row.
666 if let Ok(mut slot) = wpp_contexts[row].lock() {
667 *slot = Some(enc.contexts.clone());
668 }
669 }
670 progress[row].0.store(col + 1, Ordering::Release);
671 let last_in_picture = row + 1 == rows && col + 1 == cols;
672 enc.encode_terminate(u32::from(last_in_picture));
673 if !last_in_picture && col + 1 == cols {
674 // end_of_subset_one_bit, then byte alignment.
675 enc.encode_terminate(1);
676 }
677 }
678 if let Ok(mut slot) = substreams[row].lock() {
679 *slot = enc.finish();
680 }
681 if let Ok(mut slot) = tu_bands[row].lock() {
682 *slot = coder.tu_log2_band().to_vec();
683 }
684 }
685 });
686 }
687 });
688
689 let substreams: Vec<Vec<u8>> = substreams
690 .into_iter()
691 .map(|m| m.into_inner().unwrap_or_default())
692 .collect();
693 if self.cfg.deblock {
694 let mut tus = TuMap::new(width, height);
695 for (row, band) in tu_bands.into_iter().enumerate() {
696 let band = band.into_inner().unwrap_or_default();
697 let band_y0 = row * ctb;
698 let band_rows = (height - band_y0).min(ctb) / 4;
699 tus.absorb_band(band_y0, band_rows, &band);
700 }
701 deblock(
702 &mut rec_y,
703 &mut rec_cb,
704 &mut rec_cr,
705 width,
706 height,
707 qp,
708 &tus,
709 );
710 }
711
712 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
713 let recon = self
714 .cfg
715 .keep_recon
716 .then(|| self.crop_recon(&rec_y, &rec_cb, &rec_cr));
717 Ok(EncodedPicture { au, qp, recon })
718 }
719
720 /// Parameter sets, optional SEI, and the slice, in Annex-B framing.
721 fn assemble_au(
722 &self,
723 qp: i32,
724 substreams: &[Vec<u8>],
725 rec_y: &[u8],
726 rec_cb: &[u8],
727 rec_cr: &[u8],
728 ) -> Vec<u8> {
729 let mut au = Vec::with_capacity(substreams.iter().map(|s| s.len()).sum::<usize>() + 256);
730 write_annex_b(
731 &mut au,
732 NalHeader::new(NalUnitType::Vps),
733 &self.vps.to_rbsp(),
734 true,
735 );
736 write_annex_b(
737 &mut au,
738 NalHeader::new(NalUnitType::Sps),
739 &self.sps.to_rbsp(),
740 true,
741 );
742 write_annex_b(
743 &mut au,
744 NalHeader::new(NalUnitType::Pps),
745 &self.pps.to_rbsp(),
746 true,
747 );
748 if let Some(rbsp) = sei::hdr_metadata_rbsp(self.cfg.content_light) {
749 write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true);
750 }
751
752 // Entry points count the bytes as they appear in the NAL, emulation
753 // prevention included. Each substream ends on a byte whose last written
754 // bit is the flush's one bit, so no escape sequence straddles a
755 // boundary and each substream can be measured on its own.
756 let mut escaped: Vec<Vec<u8>> = Vec::with_capacity(substreams.len());
757 for stream in substreams {
758 let mut out = Vec::with_capacity(stream.len() + 8);
759 escape_rbsp(stream, &mut out);
760 escaped.push(out);
761 }
762 let mut header = SliceHeader::intra(&self.pps, qp - 26);
763 header.entry_point_offsets = escaped
764 .iter()
765 .take(escaped.len().saturating_sub(1))
766 .map(|s| s.len() as u32)
767 .collect();
768 let mut writer = ec_core::bitio::BitWriter::with_capacity(64);
769 header.write(&mut writer, &self.sps, &self.pps, NalUnitType::IdrWRadl);
770 let mut rbsp = writer.into_bytes();
771 for stream in substreams {
772 rbsp.extend_from_slice(stream);
773 }
774 write_annex_b(&mut au, NalHeader::new(NalUnitType::IdrWRadl), &rbsp, true);
775
776 if self.cfg.picture_hash {
777 let (w, h) = (self.coded_width, self.coded_height);
778 let rbsp = sei::decoded_picture_hash_rbsp(&[
779 (rec_y, w, w, h),
780 (rec_cb, w / 2, w / 2, h / 2),
781 (rec_cr, w / 2, w / 2, h / 2),
782 ]);
783 write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false);
784 }
785 au
786 }
787
788 fn crop_recon(&self, rec_y: &[u8], rec_cb: &[u8], rec_cr: &[u8]) -> VideoFrame {
789 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
790 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
791 let crop = |src: &[u8], stride: usize, width: usize, height: usize| -> Vec<u8> {
792 let mut out = Vec::with_capacity(width * height);
793 for row in 0..height {
794 out.extend_from_slice(&src[row * stride..row * stride + width]);
795 }
796 out
797 };
798 let planes = vec![
799 Plane::new(crop(rec_y, self.coded_width, w, h), w),
800 Plane::new(crop(rec_cb, self.coded_width / 2, cw, ch), cw),
801 Plane::new(crop(rec_cr, self.coded_width / 2, cw, ch), cw),
802 ];
803 VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)
804 .expect("cropped planes are exactly the size I420 asks for")
805 }
806}
807
808/// A progress counter on its own cache line.
809///
810/// Twelve workers polling twelve counters packed eight to a line spend their
811/// time invalidating each other's caches instead of coding; the padding is the
812/// difference between a wavefront and a contention benchmark.
813#[repr(align(64))]
814struct Progress(AtomicUsize);
815
816/// Spin, then yield, then sleep until a row's progress counter reaches `target`.
817///
818/// A worker that spins hard is a worker holding a core the wavefront needs
819/// somewhere else, so the wait backs off to a sleep at roughly the granularity
820/// of one coding tree block.
821fn wait_for(counter: &Progress, target: usize) {
822 let mut spins = 0u32;
823 while counter.0.load(Ordering::Acquire) < target {
824 if spins < 128 {
825 std::hint::spin_loop();
826 } else if spins < 256 {
827 std::thread::yield_now();
828 } else {
829 std::thread::sleep(std::time::Duration::from_micros(50));
830 }
831 spins += 1;
832 }
833}
834
835/// One CTB row handed to a worker: its index and its band of each plane.
836type RowAssignment<'a> = (usize, &'a mut [u8], &'a mut [u8], &'a mut [u8]);
837
838struct PaddedSource {
839 y: Vec<u8>,
840 cb: Vec<u8>,
841 cr: Vec<u8>,
842}