forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

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