forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

enc_p.rs2655 lines, 96.0 KiBHistoryRawDownload
1//! P pictures: the inter half of the sequence encoder.
2//!
3//! A sequence is an IDR every `keyint` pictures and P pictures in between. A P
4//! picture has one reference, the previous reconstructed picture, named by a
5//! short-term RPS in its slice header (one negative picture, one bit of
6//! delta). Every coding unit is inter and 2Nx2N; its prediction is chosen by
7//! rate-distortion among
8//!
9//! - skip, and merge with a residual, for each merge candidate of
10//! [`derive_merge`](crate::dec::merge::derive_merge),
11//! - AMVP with either predictor, with the vector the motion search found and
12//! a residual or none (`rqt_root_cbf`).
13//!
14//! Motion is searched per block ([`crate::enc_me`]) over a quadtree of 8 to 32
15//! luma samples, decided on the search costs before any coding unit is
16//! committed. The reconstruction is the decoder's own: the prediction is
17//! [`predict_pu`], the in-loop deblocking is [`deblock_picture`], and the
18//! motion the merge and AMVP candidates read is the decoder's
19//! [`MotionField`]. Sample adaptive offset is off in this stream, as it is in
20//! the intra encoder.
21
22use crate::cabac::{CabacEncoder, Contexts, ctx};
23use crate::ctu::{Pel, lambda_for};
24use crate::dec::amvp::derive_amvp;
25use crate::dec::cu_syntax::{CuGeometry, PartMode, PredictionUnit};
26use crate::dec::deblock::{deblock_picture, deblock_rows};
27use crate::dec::mc::{Block, McScratch, PlaneMut, PlaneRef, RefPicture, predict_pu};
28use crate::dec::merge::derive_merge;
29use crate::dec::motion_field::{
30 FieldCell, MotionField, MotionParams, PbMotion, SliceMotion, SliceRefs, to32,
31};
32use crate::dec::pic::{BlockInfo, EDGE_PU, EDGE_TU, PicState, PuMotion, SliceFilter};
33use crate::dec::rps::{RefEntry, RefPicLists};
34use crate::dec::shared::SharedPic;
35use crate::enc_me::{FULL_RANGE_LARGE, FULL_RANGE_SMALL, RefPlanes, Search};
36use crate::enc_rc::{BitRateControl, offset_after_batch};
37use crate::encoder::Preset;
38use crate::encoder::{
39 EncodedPicture, Encoder, PaddedSource, Progress, RateControl, bitrate_picture_bits,
40 plane_samples, wait_for_or_abort,
41};
42use crate::intra::{mpm_list, scan_index};
43use crate::residual::hide_signs;
44use crate::residual::{encode_residual, estimate_residual_bits};
45use crate::transform::{
46 chroma_qp_bd, dequantize_bd, forward_transform, inverse_transform_bd, min_nonzero_coeff,
47 quant_qp, quantize_offset, scale_forward_bd,
48};
49use ec_core::bitio::BitWriter;
50use ec_core::error::{Error, Result};
51use ec_core::frame::VideoFrame;
52use ec_h265_syntax::nal::{NalHeader, NalUnitType, escape_rbsp, write_annex_b};
53use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
54use std::sync::{Arc, Mutex};
55
56/// `MaxNumMergeCand` of the P slices this encoder writes.
57const MAX_MERGE_CAND: usize = 5;
58
59/// QP offset of the P pictures from the IDR's. A coarser P picture spends fewer
60/// bits on the residual, which the mode decision then trades better: +2 gives the
61/// best BD-rate on the natural clip (+4 is no better on the chroma-weighted metric).
62pub(crate) const P_QP_DELTA: i32 = 2;
63
64/// `MinCbLog2SizeY` of the sequence (8x8), which codes `part_mode` for intra units.
65const MIN_CB_LOG2: u32 = 3;
66
67/// Cost per sample (SSD plus lambda times bits, over the block) below which a merge
68/// candidate with no residual ends the mode search of a coding unit.
69const EARLY_SKIP_COST: f64 = 4.0;
70
71/// Mean absolute difference per sample below which a motion-searched block is not split.
72const EARLY_SPLIT_SAD: f64 = 0.25;
73
74/// Search thresholds of the P-picture decision. The defaults are the measured
75/// values; the `EC_H265_*` overrides exist for the sweep in the lane report.
76#[derive(Clone, Copy)]
77pub(crate) struct PKnobs {
78 /// Whole-sample scan half-width for blocks of 32 and up.
79 full_large: i16,
80 /// Whole-sample scan half-width for smaller blocks.
81 full_small: i16,
82 /// Mean absolute difference per sample below which a block is not split.
83 split_sad: f64,
84 /// Cost per sample below which a residual-free merge ends the search.
85 skip_cost: f64,
86 /// Cost per sample below which the whole-sample scan is skipped.
87 full_gate: f64,
88 /// Cost per sample below which the best inter candidate ends the intra search.
89 intra_gate: f64,
90 /// Intra luma modes costed in full, the best by SAD of their prediction.
91 intra_k: usize,
92 /// A transform block whose residual energy times the transform gain is below this many
93 /// squares of the smallest non-zero coefficient is taken to quantise to zero without
94 /// transforming it (1 is the bound that is exact; larger trades a little accuracy).
95 zero_alpha: f64,
96 /// First pattern step (quarter samples) of the search for 16x16 and 8x8 blocks, and halves.
97 step16: i16,
98 step8: i16,
99 step_part: i16,
100 full_stride: i16,
101 res_proxy: bool,
102 sub_passes: u32,
103 /// Most distinct merge candidates costed in full.
104 merge_max: usize,
105 /// Cost both AMVP predictor flags (otherwise only the one with the smaller vector difference).
106 amvp_both: bool,
107 /// log2 of the smallest inter coding unit the analysis searches (3 = 8x8).
108 min_log2: u32,
109 /// Smallest square (samples) whose horizontal and vertical halves are searched and costed.
110 halves_min: usize,
111 /// Most intra luma modes considered (MPMs first) before the SAD ranking.
112 intra_modes: usize,
113 /// Cost per sample below which the sub-sample refinement is skipped.
114 sub_gate: f64,
115 /// Skip the quarter-sample refinement step.
116 no_quarter: bool,
117}
118
119impl PKnobs {
120 /// The knobs of a speed preset. `Default` is the measured set; `EC_H265_*`
121 /// environment variables override any of them (sweeps only).
122 pub(crate) fn for_preset(p: Preset) -> PKnobs {
123 let f = |name: &str, d: f64| {
124 std::env::var(name)
125 .ok()
126 .and_then(|v| v.parse::<f64>().ok())
127 .unwrap_or(d)
128 };
129 // (fast, faster) values against the default.
130 let pick = |d: f64, fast: f64, faster: f64| match p {
131 Preset::Default => d,
132 Preset::Fast => fast,
133 Preset::Faster => faster,
134 };
135 PKnobs {
136 full_large: f(
137 "EC_H265_FULL_LARGE",
138 pick(f64::from(FULL_RANGE_LARGE), 8.0, 4.0),
139 ) as i16,
140 full_small: f(
141 "EC_H265_FULL_SMALL",
142 pick(f64::from(FULL_RANGE_SMALL), 4.0, 0.0),
143 ) as i16,
144 split_sad: f("EC_H265_SPLIT_SAD", pick(EARLY_SPLIT_SAD, 1.0, 2.0)),
145 skip_cost: f("EC_H265_SKIP_COST", pick(EARLY_SKIP_COST, 16.0, 32.0)),
146 full_gate: f("EC_H265_FULL_GATE", pick(4.0, 12.0, 16.0)),
147 intra_gate: f("EC_H265_INTRA_GATE", pick(0.0, 6.0, 12.0)),
148 intra_k: f("EC_H265_INTRA_K", 1.0) as usize,
149 zero_alpha: f("EC_H265_ZERO_ALPHA", pick(24.0, 24.0, 24.0)),
150 step16: f("EC_H265_STEP16", 16.0) as i16,
151 step8: f("EC_H265_STEP8", 16.0) as i16,
152 step_part: f("EC_H265_STEPP", 16.0) as i16,
153 full_stride: f("EC_H265_FULL_STRIDE", 4.0) as i16,
154 sub_passes: f("EC_H265_SUB_PASSES", pick(1.0, 1.0, 1.0)) as u32,
155 res_proxy: f("EC_H265_RES_PROXY", 1.0) != 0.0,
156 merge_max: f("EC_H265_MERGE_MAX", pick(5.0, 3.0, 2.0)) as usize,
157 amvp_both: f("EC_H265_AMVP_BOTH", pick(1.0, 0.0, 0.0)) != 0.0,
158 min_log2: f("EC_H265_MIN_LOG2", pick(3.0, 3.0, 4.0)) as u32,
159 intra_modes: f("EC_H265_INTRA_MODES", pick(7.0, 3.0, 2.0)) as usize,
160 sub_gate: f("EC_H265_SUB_GATE", pick(0.0, 1.0, 2.0)),
161 no_quarter: f("EC_H265_NO_QUARTER", pick(0.0, 0.0, 1.0)) != 0.0,
162 halves_min: f("EC_H265_HALVES_MIN", pick(16.0, 32.0, 1024.0)) as usize,
163 }
164 }
165}
166
167/// Intra luma modes tried besides the most probable ones: planar, DC,
168/// horizontal and vertical.
169const INTRA_FIXED_MODES: [u8; 4] = [0, 1, 10, 26];
170
171/// The reconstructed luma and chroma of a picture at the coded size, as the
172/// decoder holds it: one `u16` per sample, rows `width` (luma) or `width / 2`
173/// (chroma) apart.
174#[derive(Debug, Clone)]
175pub(crate) struct PRecon {
176 /// Luma samples.
177 pub y: Vec<u16>,
178 /// Cb samples.
179 pub cb: Vec<u16>,
180 /// Cr samples.
181 pub cr: Vec<u16>,
182}
183
184/// An intra coding unit's luma mode and the candidate list it is coded against.
185#[derive(Debug, Clone, Copy)]
186struct IntraCu {
187 mode: u8,
188 mpm: [u8; 3],
189}
190
191/// One candidate's prediction mode, as the syntax writes it.
192#[derive(Debug, Clone)]
193struct CuSyntax {
194 skip: bool,
195 /// The intra mode, for an intra unit (which then has no `merge`, `mvd`).
196 intra: Option<IntraCu>,
197 /// The prediction split, and for a split unit its two `(mvd, mvp_lX_flag)`
198 /// pairs and its four transform units.
199 part: Part,
200 pus: [([i32; 2], u8); 2],
201 tus: Vec<TuSyn>,
202 /// `merge_idx` when the unit is a merge unit.
203 merge: Option<u8>,
204 /// `mvd_coding` values and `mvp_lX_flag`, for AMVP.
205 mvd: [i32; 2],
206 mvp_flag: u8,
207 /// `rqt_root_cbf`, for AMVP (merge units always carry a transform tree).
208 root: bool,
209 /// `cbf_luma`, `cbf_cb`, `cbf_cr` at depth 0.
210 cbf: [bool; 3],
211 /// Quantised levels of the luma, Cb and Cr transform blocks.
212 levels: [Vec<i32>; 3],
213}
214
215/// The reconstruction and cost of one candidate motion.
216struct Eval {
217 syntax: CuSyntax,
218 recon: [Vec<u16>; 3],
219}
220
221/// The partition of one coding tree block, decided before coding it.
222#[derive(Debug)]
223enum Tree {
224 /// A coding unit of the node's size with this motion.
225 Leaf(LeafMotion),
226 /// Four children (only those whose origin is inside the picture), in
227 /// z-order.
228 Split(Vec<Tree>),
229}
230
231/// One transform block coded against its prediction.
232struct Tb {
233 cbf: bool,
234 levels: Vec<i32>,
235 recon: Vec<u16>,
236 ssd: f64,
237}
238
239/// How a coding unit's prediction is split: one block, or two halves.
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241enum Part {
242 /// 2Nx2N.
243 Square,
244 /// 2NxN: the top and the bottom half.
245 Horizontal,
246 /// Nx2N: the left and the right half.
247 Vertical,
248}
249
250/// The rectangles `(x, y, w, h)` of the two prediction blocks of a coding unit.
251fn partition_rects(x: usize, y: usize, n: usize, part: Part) -> [(usize, usize, usize, usize); 2] {
252 match part {
253 Part::Square => [(x, y, n, n), (x, y, n, n)],
254 Part::Horizontal => [(x, y, n, n / 2), (x, y + n / 2, n, n / 2)],
255 Part::Vertical => [(x, y, n / 2, n), (x + n / 2, y, n / 2, n)],
256 }
257}
258
259/// The motion analysis found for a coding unit: its square vector, and the split
260/// with the two halves' vectors when the analysis found it cheaper.
261#[derive(Debug, Clone, Copy)]
262struct LeafMotion {
263 mv: [i16; 2],
264 part: Part,
265 pmvs: [[i16; 2]; 2],
266}
267
268/// The quantised levels and coded block flags of one transform unit of a coding
269/// unit split into two halves (its four units are in z-order).
270#[derive(Debug, Clone)]
271struct TuSyn {
272 cbf: [bool; 3],
273 levels: [Vec<i32>; 3],
274}
275
276/// Quantise, reconstruct and measure one `n` x `n` block at `(sx, sy)` of
277/// `src` against the prediction in `pred` (both at the picture's stride).
278#[allow(clippy::too_many_arguments)]
279fn code_tb(
280 src: &[Pel],
281 sstride: usize,
282 pred: &[Pel],
283 pstride: usize,
284 at: (usize, usize),
285 n: usize,
286 qp: i32,
287 bd: u32,
288 sign_hiding: bool,
289 scan_dst: (usize, bool),
290 zero_alpha: f64,
291) -> Tb {
292 match n {
293 4 => code_tb_n::<16>(
294 src,
295 sstride,
296 pred,
297 pstride,
298 at,
299 n,
300 qp,
301 bd,
302 sign_hiding,
303 scan_dst,
304 zero_alpha,
305 ),
306 8 => code_tb_n::<64>(
307 src,
308 sstride,
309 pred,
310 pstride,
311 at,
312 n,
313 qp,
314 bd,
315 sign_hiding,
316 scan_dst,
317 zero_alpha,
318 ),
319 16 => code_tb_n::<256>(
320 src,
321 sstride,
322 pred,
323 pstride,
324 at,
325 n,
326 qp,
327 bd,
328 sign_hiding,
329 scan_dst,
330 zero_alpha,
331 ),
332 _ => code_tb_n::<1024>(
333 src,
334 sstride,
335 pred,
336 pstride,
337 at,
338 n,
339 qp,
340 bd,
341 sign_hiding,
342 scan_dst,
343 zero_alpha,
344 ),
345 }
346}
347
348/// [`code_tb`] with the working buffers on the stack, sized `SQ = n * n`.
349#[allow(clippy::too_many_arguments)]
350fn code_tb_n<const SQ: usize>(
351 src: &[Pel],
352 sstride: usize,
353 pred: &[Pel],
354 pstride: usize,
355 (sx, sy): (usize, usize),
356 n: usize,
357 qp: i32,
358 bd: u32,
359 sign_hiding: bool,
360 (scan, dst): (usize, bool),
361 zero_alpha: f64,
362) -> Tb {
363 let mut res = [0i32; SQ];
364 let mut energy = 0i64;
365 for r in 0..n {
366 let s = &src[(sy + r) * sstride + sx..][..n];
367 let p = &pred[(sy + r) * pstride + sx..][..n];
368 let o = &mut res[r * n..][..n];
369 let mut e = 0i32;
370 for c in 0..n {
371 let d = i32::from(s[c]) - i32::from(p[c]);
372 o[c] = d;
373 // |d| < 2^12 and n <= 32 samples per row: the row sum stays below 2^29.
374 e += d * d;
375 }
376 energy += i64::from(e);
377 }
378 // The transform scales energy by (128 / n)^2, so a residual whose energy cannot lift
379 // any coefficient to the smallest non-zero level quantises to nothing.
380 let t = min_nonzero_coeff(n, qp, 12) as f64;
381 if energy as f64 * (128.0 / n as f64).powi(2) < zero_alpha * t * t {
382 let mut recon = vec![0u16; n * n];
383 for r in 0..n {
384 recon[r * n..][..n].copy_from_slice(&pred[(sy + r) * pstride + sx..][..n]);
385 }
386 return Tb {
387 cbf: false,
388 levels: vec![0; n * n],
389 recon,
390 ssd: energy as f64,
391 };
392 }
393 let mut coeffs = [0i32; SQ];
394 forward_transform(&res, &mut coeffs, n, dst);
395 scale_forward_bd(&mut coeffs, n, bd);
396 let mut levels = vec![0i32; n * n];
397 // Round to nearest: a residual is noise-like, and the intra dead zone (1/3)
398 // throws away the small levels that carry most of the inter detail.
399 let mut nonzero = quantize_offset(&coeffs, &mut levels, n, quant_qp(qp, bd), 12);
400 if sign_hiding && nonzero > 0 {
401 nonzero = hide_signs(&coeffs, &mut levels, n, quant_qp(qp, bd), scan);
402 }
403 let cbf = nonzero > 0;
404 if cbf {
405 let mut scaled = [0i32; SQ];
406 dequantize_bd(&levels, &mut scaled, n, qp, bd);
407 inverse_transform_bd(&scaled, &mut res, n, dst, bd);
408 } else {
409 res.fill(0);
410 }
411 let mut recon = vec![0u16; n * n];
412 let max = (1i32 << bd) - 1;
413 let mut ssd = 0i64;
414 for r in 0..n {
415 let s = &src[(sy + r) * sstride + sx..][..n];
416 let p = &pred[(sy + r) * pstride + sx..][..n];
417 let rr = &res[r * n..][..n];
418 let o = &mut recon[r * n..][..n];
419 let mut e = 0i32;
420 for c in 0..n {
421 let v = (i32::from(p[c]) + rr[c]).clamp(0, max);
422 o[c] = v as u16;
423 let d = i32::from(s[c]) - v;
424 e += d * d;
425 }
426 ssd += i64::from(e);
427 }
428 Tb {
429 cbf,
430 levels,
431 recon,
432 ssd: ssd as f64,
433 }
434}
435
436/// `k`-th order exp-Golomb bins in bypass mode (9.3.3.11 with k = 1 here).
437fn write_egk(e: &mut CabacEncoder, mut value: u32, mut k: u32) {
438 loop {
439 if value >= (1 << k) {
440 e.encode_bypass(1);
441 value -= 1 << k;
442 k += 1;
443 } else {
444 e.encode_bypass(0);
445 while k > 0 {
446 k -= 1;
447 e.encode_bypass((value >> k) & 1);
448 }
449 break;
450 }
451 }
452}
453
454/// `merge_idx`: truncated unary with the first bin in context (9.3.4.2).
455fn write_merge_idx(e: &mut CabacEncoder, idx: u8) {
456 let c_max = (MAX_MERGE_CAND - 1) as u8;
457 for i in 0..c_max {
458 let bin = u32::from(i < idx);
459 if i == 0 {
460 e.encode_bin(ctx::MERGE_IDX, bin);
461 } else {
462 e.encode_bypass(bin);
463 }
464 if bin == 0 {
465 return;
466 }
467 }
468}
469
470/// `mvd_coding` (7.3.8.9) for one list-0 vector difference.
471fn write_mvd(e: &mut CabacEncoder, mvd: [i32; 2]) {
472 let abs = [mvd[0].unsigned_abs(), mvd[1].unsigned_abs()];
473 e.encode_bin(ctx::ABS_MVD_GT0, u32::from(abs[0] > 0));
474 e.encode_bin(ctx::ABS_MVD_GT0, u32::from(abs[1] > 0));
475 for a in abs {
476 if a > 0 {
477 e.encode_bin(ctx::ABS_MVD_GT1, u32::from(a > 1));
478 }
479 }
480 for (a, v) in abs.into_iter().zip(mvd) {
481 if a > 0 {
482 if a > 1 {
483 write_egk(e, a - 2, 1);
484 }
485 e.encode_bypass(u32::from(v < 0));
486 }
487 }
488}
489
490/// The previous picture, as the next P picture sees it: its motion field (which
491/// seeds the search) and the collocated view the decoder's temporal candidates
492/// read (8.5.3.2.8).
493pub(crate) struct PrevPic {
494 field: MotionField,
495 shared: Arc<SharedPic>,
496}
497
498/// The running state of one P picture.
499struct PCoder<'a> {
500 w: usize,
501 h: usize,
502 ctb_log2: u32,
503 qp: i32,
504 /// The bit depth both planes are coded at.
505 bd: u32,
506 /// qP of luma, QpY + QpBdOffset, and qP of chroma: what the quantiser takes.
507 qpd: i32,
508 qpc: i32,
509 /// Lagrange multiplier of the mode decision, in squared-error units per bit.
510 lambda: f64,
511 /// Lagrange multiplier of the motion search, in SAD units per bit: the
512 /// square root of the squared-error one (as HM sets it), because SAD grows
513 /// with the error amplitude while squared error grows with its square.
514 search_lambda: f64,
515 sign_hiding: bool,
516 /// The SPS allows one level of transform-tree split for intra units, so the
517 /// `split_transform_flag` of an intra unit is coded.
518 intra_tt_split: bool,
519 deblock: bool,
520 poc: i32,
521 src: &'a PaddedSource,
522 /// The reference picture, as the decoder's `RefPicture`.
523 ref_pic: RefPicture<'a>,
524 ref_poc: i32,
525 pic: PicState,
526 field: MotionField,
527 lists: RefPicLists,
528 params: MotionParams,
529 /// Prediction buffers at the picture size, one per component.
530 pred: [Vec<u16>; 3],
531 mc: McScratch,
532 /// The reference luma as the motion search reads it.
533 rp: &'a RefPlanes,
534 /// The previous picture: the collocated motion of the temporal candidates.
535 col: Option<Arc<PrevPic>>,
536 k: PKnobs,
537}
538
539impl<'a> PCoder<'a> {
540 #[allow(clippy::too_many_arguments)] // one picture's inputs and outputs
541 fn new(
542 enc: &Encoder,
543 src: &'a PaddedSource,
544 refp: &'a PRecon,
545 rp: &'a RefPlanes,
546 ref_poc: i32,
547 poc: i32,
548 qp: i32,
549 col: Option<Arc<PrevPic>>,
550 ) -> PCoder<'a> {
551 let (w, h) = (enc.coded_width, enc.coded_height);
552 let ctb_log2 = enc.cfg.ctb_size.trailing_zeros();
553 // qP = QpY + QpBdOffset for luma and chroma (8.6.1); the quantiser works on qP.
554 let bd = u32::from(enc.cfg.bit_depth);
555 let off = 6 * (bd as i32 - 8);
556 let (qpd, qpc) = (qp + off, chroma_qp_bd(qp, 0, bd) + off);
557 let ref_pic: RefPicture<'a> = [
558 PlaneRef {
559 samples: &refp.y,
560 stride: w,
561 width: w,
562 height: h,
563 bit_depth: bd,
564 },
565 PlaneRef {
566 samples: &refp.cb,
567 stride: w / 2,
568 width: w / 2,
569 height: h / 2,
570 bit_depth: bd,
571 },
572 PlaneRef {
573 samples: &refp.cr,
574 stride: w / 2,
575 width: w / 2,
576 height: h / 2,
577 bit_depth: bd,
578 },
579 ];
580 let mut pic = PicState::new(w, h, ctb_log2, 2, bd, bd, true);
581 pic.strong_intra_smoothing = true; // as the sequence parameter set says
582 pic.slices = vec![SliceFilter {
583 deblock_disabled: !enc.cfg.deblock,
584 beta_offset_div2: 0,
585 tc_offset_div2: 0,
586 loop_filter_across_slices: false,
587 sao_luma: false,
588 sao_chroma: false,
589 }];
590 let lists = RefPicLists {
591 l0: vec![RefEntry {
592 id: 0,
593 poc: ref_poc,
594 long_term: false,
595 }],
596 l1: Vec::new(),
597 };
598 let params = MotionParams {
599 is_b: false,
600 max_merge_cand: MAX_MERGE_CAND,
601 log2_par_mrg_level: 2,
602 ctb_log2,
603 collocated_from_l0: true,
604 // slice_temporal_mvp_enabled_flag is 1 in every P slice; with no
605 // previous picture (after an IDR) the collocated view is absent.
606 temporal_mvp: true,
607 no_backward_pred: true,
608 };
609 let mut field = MotionField::new(w, h);
610 field.slices.push(SliceRefs::from_lists(&lists));
611 PCoder {
612 w,
613 h,
614 ctb_log2,
615 qp,
616 bd,
617 qpd,
618 qpc,
619 lambda: lambda_for(qpd) * enc.cfg.inter_lambda_scale,
620 // The search measures SAD on 8-bit samples, so its lambda is the 8-bit one.
621 search_lambda: lambda_for(qp).sqrt(),
622 sign_hiding: enc.cfg.sign_hiding,
623 intra_tt_split: enc.cfg.rqt,
624 deblock: enc.cfg.deblock,
625 poc,
626 src,
627 ref_pic,
628 ref_poc,
629 pic,
630 field,
631 lists,
632 params,
633 pred: [vec![0; w * h], vec![0; w * h / 4], vec![0; w * h / 4]],
634 mc: McScratch::new(),
635 rp,
636 col,
637 k: enc.pk,
638 }
639 }
640
641 /// The motion source the decoder's merge and AMVP derivations read.
642 fn sm(&mut self) -> SliceMotion<'_> {
643 SliceMotion {
644 params: self.params,
645 lists: &self.lists,
646 cur_poc: self.poc,
647 field: &mut self.field,
648 col: self.col.as_ref().map(|p| Arc::clone(&p.shared)),
649 slice: 0,
650 publish: None,
651 }
652 }
653
654 /// `cu_skip_flag` context: the left and above units' skip flags.
655 fn skip_ctx(&self, x: usize, y: usize) -> usize {
656 let skip_at =
657 |xx: usize, yy: usize| self.pic.info[(yy >> 2) * self.pic.w4 + (xx >> 2)].skip;
658 usize::from(x > 0 && skip_at(x - 1, y)) + usize::from(y > 0 && skip_at(x, y - 1))
659 }
660
661 /// Write `split_cu_flag` for the node at `(x, y)` of size `1 << log2`.
662 fn write_split(&self, e: &mut CabacEncoder, x: usize, y: usize, log2: u32, split: bool) {
663 let depth = (self.ctb_log2 - log2) as u8;
664 let deeper =
665 |xx: usize, yy: usize| self.pic.info[(yy >> 2) * self.pic.w4 + (xx >> 2)].depth > depth;
666 let inc = usize::from(x > 0 && deeper(x - 1, y)) + usize::from(y > 0 && deeper(x, y - 1));
667 e.encode_bin(ctx::SPLIT_CU + inc, u32::from(split));
668 }
669
670 /// The vector of the neighbour at `(x, y)` when it is an inter unit of this
671 /// slice that uses list 0.
672 fn nb_mv(&mut self, x: isize, y: isize) -> Option<[i16; 2]> {
673 let m = self.sm().neighbour(x, y)?;
674 m.pred[0].then_some(m.mv[0])
675 }
676
677 /// Motion search for the `n` x `n` block at `(x, y)`: its cost and motion,
678 /// with the split into halves when that costs less (blocks of 16 and up).
679 fn search_node(
680 &mut self,
681 x: usize,
682 y: usize,
683 n: usize,
684 parent: [i16; 2],
685 ) -> Result<(f64, LeafMotion)> {
686 let mvp = {
687 let sm = self.sm();
688 let pu = PredictionUnit {
689 x,
690 y,
691 width: n,
692 height: n,
693 ..PredictionUnit::default()
694 };
695 derive_amvp(&sm, &pu).mv[0]
696 };
697 // Seeds: the zero vector, the parent's vector, the spatial neighbours
698 // (left, above, above-right, above-left), and the previous picture's
699 // vector at the block's centre.
700 let mut seeds = vec![[0i16, 0i16], parent];
701 let left = self.nb_mv(x as isize - 1, (y + n - 1) as isize);
702 let above = self.nb_mv((x + n - 1) as isize, y as isize - 1);
703 let above_right = self.nb_mv((x + n) as isize, y as isize - 1);
704 let above_left = self.nb_mv(x as isize - 1, y as isize - 1);
705 let (cx, cy) = ((x + n / 2) as isize, (y + n / 2) as isize);
706 let col = self
707 .col
708 .as_ref()
709 .and_then(|p| p.field.at(cx, cy))
710 .filter(|c| c.motion.pred[0])
711 .map(|c| c.motion.mv[0]);
712 seeds.extend(
713 left.into_iter()
714 .chain(above)
715 .chain(above_right)
716 .chain(above_left)
717 .chain(col),
718 );
719 let src: &'a PaddedSource = self.src;
720 let search = Search {
721 src: &src.y8,
722 src_stride: self.w,
723 reference: self.rp,
724 lambda: self.search_lambda,
725 full_range: if n >= 32 {
726 self.k.full_large
727 } else {
728 self.k.full_small
729 },
730 full_gate: self.k.full_gate,
731 full_stride: self.k.full_stride,
732 sub_passes: self.k.sub_passes,
733 sub_gate: self.k.sub_gate,
734 no_quarter: self.k.no_quarter,
735 first_step: match n {
736 32.. => 16,
737 16.. => self.k.step16,
738 _ => self.k.step8,
739 },
740 };
741 let best = search.run((x, y), (n, n), mvp, &seeds);
742 let mut leaf = LeafMotion {
743 mv: best.mv,
744 part: Part::Square,
745 pmvs: [best.mv; 2],
746 };
747 let mut cost = best.cost;
748 // A square that the seeds predict almost exactly is not split into halves.
749 if n >= self.k.halves_min && cost >= self.k.split_sad * (n * n) as f64 {
750 for part in [Part::Horizontal, Part::Vertical] {
751 let (pcost, pmvs) = self.search_parts(x, y, n, part, best.mv)?;
752 if pcost < cost {
753 cost = pcost;
754 leaf = LeafMotion {
755 mv: best.mv,
756 part,
757 pmvs,
758 };
759 }
760 }
761 }
762 Ok((cost, leaf))
763 }
764
765 /// Search the two halves of the `n` x `n` block at `(x, y)` split as `part`,
766 /// each on its own, the second seeded by the first. Returns the total cost and
767 /// the two vectors.
768 fn search_parts(
769 &mut self,
770 x: usize,
771 y: usize,
772 n: usize,
773 part: Part,
774 square: [i16; 2],
775 ) -> Result<(f64, [[i16; 2]; 2])> {
776 let mut total = 0f64;
777 let mut mvs = [[0i16; 2]; 2];
778 for (i, (rx, ry, rw, rh)) in partition_rects(x, y, n, part).into_iter().enumerate() {
779 let mvp = {
780 let sm = self.sm();
781 let pu = PredictionUnit {
782 x: rx,
783 y: ry,
784 width: rw,
785 height: rh,
786 ..PredictionUnit::default()
787 };
788 derive_amvp(&sm, &pu).mv[0]
789 };
790 let mut seeds = vec![[0i16, 0i16], square];
791 if i == 1 {
792 seeds.push(mvs[0]);
793 }
794 let src: &'a PaddedSource = self.src;
795 let search = Search {
796 src: &src.y8,
797 src_stride: self.w,
798 reference: self.rp,
799 lambda: self.search_lambda,
800 full_range: 0,
801 full_gate: 0.0,
802 full_stride: 1,
803 sub_passes: self.k.sub_passes,
804 sub_gate: self.k.sub_gate,
805 no_quarter: self.k.no_quarter,
806 first_step: self.k.step_part,
807 };
808 let best = search.run((rx, ry), (rw, rh), mvp, &seeds);
809 total += best.cost;
810 mvs[i] = best.mv;
811 }
812 Ok((total, mvs))
813 }
814
815 /// The quadtree analysis of the block at `(x, y)` of size `1 << log2`: the
816 /// cost of the cheapest partition and that partition.
817 ///
818 /// `parent` is the vector the enclosing node found, which seeds this one.
819 fn analyse(&mut self, x: usize, y: usize, log2: u32, parent: [i16; 2]) -> Result<(f64, Tree)> {
820 let n = 1usize << log2;
821 let inside = x + n <= self.w && y + n <= self.h;
822 let must_split = !inside || log2 > 5;
823 let floor = if must_split {
824 MIN_CB_LOG2
825 } else {
826 self.k.min_log2
827 };
828 // The node's own vector first, so its children can start from it.
829 let leaf = if must_split {
830 None
831 } else {
832 Some(self.search_node(x, y, n, parent)?)
833 };
834 // Early termination: a block that the seeds predict almost exactly is coded
835 // whole, without searching its children.
836 let near_exact =
837 leaf.filter(|(c, _)| log2 > floor && *c < self.k.split_sad * (n * n) as f64);
838 if let Some((leaf_cost, l)) = near_exact {
839 return Ok((leaf_cost, Tree::Leaf(l)));
840 }
841 let child_seed = leaf.map_or(parent, |(_, l)| l.mv);
842 let mut split_cost = 0f64;
843 let mut kids = Vec::new();
844 if log2 > floor {
845 for (dx, dy) in child_offsets(n / 2) {
846 if x + dx < self.w && y + dy < self.h {
847 let (c, t) = self.analyse(x + dx, y + dy, log2 - 1, child_seed)?;
848 split_cost += c;
849 kids.push(t);
850 }
851 }
852 }
853 match leaf {
854 Some((leaf_cost, l)) if !(log2 > floor && split_cost < leaf_cost) => {
855 Ok((leaf_cost, Tree::Leaf(l)))
856 }
857 _ => Ok((split_cost, Tree::Split(kids))),
858 }
859 }
860
861 /// Code the partition `tree` of the block at `(x, y)`.
862 fn code_tree(
863 &mut self,
864 x: usize,
865 y: usize,
866 log2: u32,
867 tree: &Tree,
868 e: &mut CabacEncoder,
869 ) -> Result<()> {
870 let n = 1usize << log2;
871 let inside = x + n <= self.w && y + n <= self.h;
872 match tree {
873 Tree::Leaf(leaf) => {
874 if log2 > 3 && inside {
875 self.write_split(e, x, y, log2, false);
876 }
877 self.code_cu(x, y, log2, *leaf, e)
878 }
879 Tree::Split(kids) => {
880 if log2 > 3 && inside {
881 self.write_split(e, x, y, log2, true);
882 }
883 let mut it = kids.iter();
884 for (dx, dy) in child_offsets(n / 2) {
885 if x + dx < self.w && y + dy < self.h {
886 let kid = it.next().ok_or_else(|| {
887 Error::corrupt("HEVC P encode: partition has too few children")
888 })?;
889 self.code_tree(x + dx, y + dy, log2 - 1, kid, e)?;
890 }
891 }
892 Ok(())
893 }
894 }
895 }
896
897 /// Choose the prediction of one coding unit by rate-distortion, then code it.
898 fn code_cu(
899 &mut self,
900 x: usize,
901 y: usize,
902 log2: u32,
903 analysis: LeafMotion,
904 e: &mut CabacEncoder,
905 ) -> Result<()> {
906 let n = 1usize << log2;
907 let analysis_mv = analysis.mv;
908 let geom = CuGeometry {
909 x,
910 y,
911 size: n,
912 part_mode: PartMode::Part2Nx2N,
913 skip: false,
914 };
915 // Candidate motions: each distinct merge candidate, then AMVP with the
916 // analysed vector under either predictor.
917 let mut merge_motions: Vec<(u8, PbMotion)> = Vec::new();
918 for idx in 0..MAX_MERGE_CAND as u8 {
919 let pu = PredictionUnit {
920 x,
921 y,
922 width: n,
923 height: n,
924 merge_flag: true,
925 merge_idx: idx,
926 ..PredictionUnit::default()
927 };
928 let m = {
929 let sm = self.sm();
930 derive_merge(&sm, &geom, 0, &pu)
931 };
932 if merge_motions.iter().all(|(_, prev)| *prev != m) {
933 merge_motions.push((idx, m));
934 }
935 }
936 let mut amvp = Vec::with_capacity(2);
937 for flag in 0..2u8 {
938 let pu = PredictionUnit {
939 x,
940 y,
941 width: n,
942 height: n,
943 mvp_flag: [flag, 0],
944 ..PredictionUnit::default()
945 };
946 let mvp = {
947 let sm = self.sm();
948 derive_amvp(&sm, &pu).mv[0]
949 };
950 let mvd = [
951 i32::from(analysis_mv[0]) - i32::from(mvp[0]),
952 i32::from(analysis_mv[1]) - i32::from(mvp[1]),
953 ];
954 amvp.push((
955 flag,
956 mvd,
957 PbMotion::new([true, false], [0, -1], [analysis_mv, [0, 0]]),
958 ));
959 }
960
961 // An AMVP candidate that predicts with the very motion of a merge candidate
962 // codes the same samples for more bits (a vector difference against a merge
963 // index), so merge has already costed it.
964 if !self.k.amvp_both && amvp.len() == 2 {
965 let size = |m: &(u8, [i32; 2], PbMotion)| m.1[0].abs() + m.1[1].abs();
966 let keep = usize::from(size(&amvp[1]) < size(&amvp[0]));
967 amvp = vec![amvp.swap_remove(keep)];
968 }
969 amvp.retain(|(_, _, m)| merge_motions.iter().all(|(_, mm)| mm != m));
970 let contexts = e.contexts.clone();
971 // The chosen prediction: the motion of each half (both equal for a square
972 // unit), and the coded unit.
973 let mut best: Option<(f64, [PbMotion; 2], Eval)> = None;
974 for (idx, motion) in merge_motions.into_iter().take(self.k.merge_max) {
975 let (cost, eval) =
976 self.eval_candidate(x, y, log2, motion, Mode::Merge(idx), &contexts)?;
977 // A residual-free merge that predicts the block almost exactly is taken
978 // at once: the later merge candidates are not costed.
979 let skip_hit = eval.syntax.skip && cost < self.k.skip_cost * (n * n) as f64;
980 if best.as_ref().is_none_or(|(c, _, _)| cost < *c) {
981 best = Some((cost, [motion; 2], eval));
982 }
983 if skip_hit {
984 break;
985 }
986 }
987 // Early skip: a merge candidate with no residual that predicts the block
988 // almost exactly ends the search. The other modes cost time for no gain.
989 let early_skip = best
990 .as_ref()
991 .is_some_and(|(c, _, eval)| eval.syntax.skip && *c < self.k.skip_cost * (n * n) as f64);
992 if !early_skip {
993 for (flag, mvd, motion) in amvp {
994 let (cost, eval) =
995 self.eval_candidate(x, y, log2, motion, Mode::Amvp { flag, mvd }, &contexts)?;
996 if best.as_ref().is_none_or(|(c, _, _)| cost < *c) {
997 best = Some((cost, [motion; 2], eval));
998 }
999 }
1000 // Intra candidates: the most probable modes, then the fixed set.
1001 let mpm = self.intra_mpm(x, y);
1002 let mut modes = mpm.to_vec();
1003 for m in INTRA_FIXED_MODES {
1004 if !modes.contains(&m) {
1005 modes.push(m);
1006 }
1007 }
1008 modes.truncate(self.k.intra_modes);
1009 let inter_best = best.as_ref().map_or(f64::MAX, |(c, _, _)| *c);
1010 if inter_best < self.k.intra_gate * (n * n) as f64 {
1011 modes.clear();
1012 } else if self.k.intra_k < modes.len() {
1013 let mut ranked: Vec<(u64, u8)> = modes
1014 .iter()
1015 .map(|&m| {
1016 self.intra_pred(x, y, log2, m);
1017 (self.luma_sad(x, y, n), m)
1018 })
1019 .collect();
1020 ranked.sort_unstable();
1021 modes = ranked
1022 .into_iter()
1023 .take(self.k.intra_k)
1024 .map(|(_, m)| m)
1025 .collect();
1026 }
1027 let no_motion = PbMotion::new([false, false], [-1, -1], [[0, 0], [0, 0]]);
1028 for mode in modes {
1029 let (cost, eval) = self.eval_intra(x, y, log2, mode, mpm, &contexts)?;
1030 if best.as_ref().is_none_or(|(c, _, _)| cost < *c) {
1031 best = Some((cost, [no_motion; 2], eval));
1032 }
1033 }
1034 // The split the analysis chose, with its own vectors.
1035 if analysis.part != Part::Square {
1036 let (cost, motions, eval) =
1037 self.eval_partition(x, y, log2, analysis.part, analysis.pmvs, &contexts)?;
1038 if best.as_ref().is_none_or(|(c, _, _)| cost < *c) {
1039 best = Some((cost, motions, eval));
1040 }
1041 }
1042 }
1043 let (_, motions, eval) =
1044 best.ok_or_else(|| Error::corrupt("HEVC P encode: no candidate for a coding unit"))?;
1045 self.write_cu(e, x, y, log2, &eval.syntax);
1046 self.commit(x, y, log2, motions, eval);
1047 Ok(())
1048 }
1049
1050 /// Sum of absolute differences of the luma `n` x `n` block at `(x, y)` between
1051 /// the source and `self.pred`.
1052 fn luma_sad(&self, x: usize, y: usize, n: usize) -> u64 {
1053 let mut sum = 0u64;
1054 for r in 0..n {
1055 let at = (y + r) * self.w + x;
1056 for c in 0..n {
1057 let d = i32::from(self.src.y[at + c]) - i32::from(self.pred[0][at + c]);
1058 sum += u64::from(d.unsigned_abs());
1059 }
1060 }
1061 sum
1062 }
1063
1064 /// Predict the `w` x `h` block at `(x, y)` with `motion` into `self.pred`.
1065 fn predict_rect(
1066 &mut self,
1067 (x, y): (usize, usize),
1068 (w, h): (usize, usize),
1069 motion: &PbMotion,
1070 ) -> Result<()> {
1071 let refs: [&[RefPicture<'_>]; 2] = [std::slice::from_ref(&self.ref_pic), &[]];
1072 let [py, pcb, pcr] = &mut self.pred;
1073 let mut outs = [
1074 PlaneMut {
1075 samples: &mut py[..],
1076 stride: self.w,
1077 bit_depth: self.bd,
1078 origin: 0,
1079 },
1080 PlaneMut {
1081 samples: &mut pcb[..],
1082 stride: self.w / 2,
1083 bit_depth: self.bd,
1084 origin: 0,
1085 },
1086 PlaneMut {
1087 samples: &mut pcr[..],
1088 stride: self.w / 2,
1089 bit_depth: self.bd,
1090 origin: 0,
1091 },
1092 ];
1093 predict_pu(
1094 refs,
1095 &motion.to_motion(),
1096 None,
1097 Block {
1098 x,
1099 y,
1100 width: w,
1101 height: h,
1102 },
1103 &mut outs,
1104 &mut self.mc,
1105 )
1106 }
1107
1108 /// Predict and quantise a coding unit split as `part`, each half with its own
1109 /// vector (AMVP, the predictor the shorter difference picks), and its four
1110 /// half-size transform units (the split an inter unit takes when it is not
1111 /// 2Nx2N and the depth is zero). Costs it as `SSD + lambda * bits`.
1112 fn eval_partition(
1113 &mut self,
1114 x: usize,
1115 y: usize,
1116 log2: u32,
1117 part: Part,
1118 pmvs: [[i16; 2]; 2],
1119 contexts: &Contexts,
1120 ) -> Result<(f64, [PbMotion; 2], Eval)> {
1121 let n = 1usize << log2;
1122 let rects = partition_rects(x, y, n, part);
1123 let mut motions = [PbMotion::new([false, false], [-1, -1], [[0, 0], [0, 0]]); 2];
1124 let mut pus = [([0i32; 2], 0u8); 2];
1125 for (i, (rx, ry, rw, rh)) in rects.into_iter().enumerate() {
1126 let mut pick: Option<(i32, [i32; 2], u8)> = None;
1127 for flag in 0..2u8 {
1128 let pu = PredictionUnit {
1129 x: rx,
1130 y: ry,
1131 width: rw,
1132 height: rh,
1133 mvp_flag: [flag, 0],
1134 ..PredictionUnit::default()
1135 };
1136 let mvp = {
1137 let sm = self.sm();
1138 derive_amvp(&sm, &pu).mv[0]
1139 };
1140 let mvd = [
1141 i32::from(pmvs[i][0]) - i32::from(mvp[0]),
1142 i32::from(pmvs[i][1]) - i32::from(mvp[1]),
1143 ];
1144 let size = mvd[0].abs() + mvd[1].abs();
1145 if pick.is_none_or(|(s, _, _)| size < s) {
1146 pick = Some((size, mvd, flag));
1147 }
1148 }
1149 let (_, mvd, flag) = pick.unwrap_or((0, [0, 0], 0));
1150 let motion = PbMotion::new([true, false], [0, -1], [pmvs[i], [0, 0]]);
1151 pus[i] = (mvd, flag);
1152 motions[i] = motion;
1153 // The first half is stored before the second derives its predictor,
1154 // as the decoder sees it.
1155 self.field.store(rx, ry, rw, rh, 0, motion);
1156 self.predict_rect((rx, ry), (rw, rh), &motion)?;
1157 }
1158 // The field holds this unit's motion only while it is being costed.
1159 self.field.clear(x, y, n, n);
1160
1161 let src: &'a PaddedSource = self.src;
1162 let sh = self.sign_hiding;
1163 let qp_c = self.qpc;
1164 let half = n / 2;
1165 let mut recon = [
1166 vec![0u16; n * n],
1167 vec![0u16; n * n / 4],
1168 vec![0u16; n * n / 4],
1169 ];
1170 let mut tus = Vec::with_capacity(4);
1171 let mut ssd = 0f64;
1172 for (dx, dy) in child_offsets(half) {
1173 let (cx, cy) = (x + dx, y + dy);
1174 let luma = code_tb(
1175 &src.y,
1176 self.w,
1177 &self.pred[0],
1178 self.w,
1179 (cx, cy),
1180 half,
1181 self.qpd,
1182 self.bd,
1183 sh,
1184 (0, false),
1185 self.k.zero_alpha,
1186 );
1187 let cb = code_tb(
1188 &src.cb,
1189 self.w / 2,
1190 &self.pred[1],
1191 self.w / 2,
1192 (cx / 2, cy / 2),
1193 half / 2,
1194 qp_c,
1195 self.bd,
1196 sh,
1197 (0, false),
1198 self.k.zero_alpha,
1199 );
1200 let cr = code_tb(
1201 &src.cr,
1202 self.w / 2,
1203 &self.pred[2],
1204 self.w / 2,
1205 (cx / 2, cy / 2),
1206 half / 2,
1207 qp_c,
1208 self.bd,
1209 sh,
1210 (0, false),
1211 self.k.zero_alpha,
1212 );
1213 ssd += luma.ssd + cb.ssd + cr.ssd;
1214 for r in 0..half {
1215 recon[0][(dy + r) * n + dx..][..half]
1216 .copy_from_slice(&luma.recon[r * half..][..half]);
1217 }
1218 for r in 0..half / 2 {
1219 let at = (dy / 2 + r) * (n / 2) + dx / 2;
1220 recon[1][at..][..half / 2].copy_from_slice(&cb.recon[r * half / 2..][..half / 2]);
1221 recon[2][at..][..half / 2].copy_from_slice(&cr.recon[r * half / 2..][..half / 2]);
1222 }
1223 tus.push(TuSyn {
1224 cbf: [luma.cbf, cb.cbf, cr.cbf],
1225 levels: [luma.levels, cb.levels, cr.levels],
1226 });
1227 }
1228 let cbf = [
1229 tus.iter().any(|t| t.cbf[0]),
1230 tus.iter().any(|t| t.cbf[1]),
1231 tus.iter().any(|t| t.cbf[2]),
1232 ];
1233 let syntax = CuSyntax {
1234 skip: false,
1235 intra: None,
1236 part,
1237 pus,
1238 tus,
1239 merge: None,
1240 mvd: [0, 0],
1241 mvp_flag: 0,
1242 root: cbf.iter().any(|&c| c),
1243 cbf,
1244 levels: [Vec::new(), Vec::new(), Vec::new()],
1245 };
1246 let mut counter = CabacEncoder::counter(contexts.clone());
1247 counter.set_estimating(true);
1248 self.write_cu(&mut counter, x, y, log2, &syntax);
1249 let cost = ssd + self.lambda * counter.bit_count_f64();
1250 let eval = Eval { syntax, recon };
1251 Ok((cost, motions, eval))
1252 }
1253
1254 /// Predict one candidate motion, quantise its residual and cost it:
1255 /// `SSD + lambda * bits` of its syntax under the coder state `contexts`.
1256 fn eval_candidate(
1257 &mut self,
1258 x: usize,
1259 y: usize,
1260 log2: u32,
1261 motion: PbMotion,
1262 mode: Mode,
1263 contexts: &Contexts,
1264 ) -> Result<(f64, Eval)> {
1265 let n = 1usize << log2;
1266 self.predict_rect((x, y), (n, n), &motion)?;
1267 let src: &'a PaddedSource = self.src;
1268 let qp_c = self.qpc;
1269 let sh = self.sign_hiding;
1270 let luma = code_tb(
1271 &src.y,
1272 self.w,
1273 &self.pred[0],
1274 self.w,
1275 (x, y),
1276 n,
1277 self.qpd,
1278 self.bd,
1279 sh,
1280 (0, false),
1281 self.k.zero_alpha,
1282 );
1283 let cb = code_tb(
1284 &src.cb,
1285 self.w / 2,
1286 &self.pred[1],
1287 self.w / 2,
1288 (x / 2, y / 2),
1289 n / 2,
1290 qp_c,
1291 self.bd,
1292 sh,
1293 (0, false),
1294 self.k.zero_alpha,
1295 );
1296 let cr = code_tb(
1297 &src.cr,
1298 self.w / 2,
1299 &self.pred[2],
1300 self.w / 2,
1301 (x / 2, y / 2),
1302 n / 2,
1303 qp_c,
1304 self.bd,
1305 sh,
1306 (0, false),
1307 self.k.zero_alpha,
1308 );
1309 let cbf = [luma.cbf, cb.cbf, cr.cbf];
1310 let any = cbf.iter().any(|&c| c);
1311 let syntax = match mode {
1312 Mode::Merge(idx) if !any => CuSyntax {
1313 skip: true,
1314 intra: None,
1315 part: Part::Square,
1316 pus: [([0, 0], 0); 2],
1317 tus: Vec::new(),
1318 merge: Some(idx),
1319 mvd: [0, 0],
1320 mvp_flag: 0,
1321 root: false,
1322 cbf,
1323 levels: [Vec::new(), Vec::new(), Vec::new()],
1324 },
1325 Mode::Merge(idx) => CuSyntax {
1326 skip: false,
1327 intra: None,
1328 part: Part::Square,
1329 pus: [([0, 0], 0); 2],
1330 tus: Vec::new(),
1331 merge: Some(idx),
1332 mvd: [0, 0],
1333 mvp_flag: 0,
1334 root: true,
1335 cbf,
1336 levels: [luma.levels.clone(), cb.levels.clone(), cr.levels.clone()],
1337 },
1338 Mode::Amvp { flag, mvd } => CuSyntax {
1339 skip: false,
1340 intra: None,
1341 part: Part::Square,
1342 pus: [([0, 0], 0); 2],
1343 tus: Vec::new(),
1344 merge: None,
1345 mvd,
1346 mvp_flag: flag,
1347 root: any,
1348 cbf,
1349 levels: [luma.levels.clone(), cb.levels.clone(), cr.levels.clone()],
1350 },
1351 };
1352 let mut counter = CabacEncoder::counter(contexts.clone());
1353 counter.set_estimating(true);
1354 self.write_cu(&mut counter, x, y, log2, &syntax);
1355 let ssd = luma.ssd + cb.ssd + cr.ssd;
1356 let cost = ssd + self.lambda * counter.bit_count_f64();
1357 let eval = Eval {
1358 syntax,
1359 recon: [luma.recon, cb.recon, cr.recon],
1360 };
1361 Ok((cost, eval))
1362 }
1363
1364 /// `candModeList` of the coding unit at `(x, y)` (8.4.2): the left and above
1365 /// units' luma modes, where a unit that is not intra, or lies outside the
1366 /// picture or slice, counts as DC, and so does the row above a CTB.
1367 fn intra_mpm(&self, x: usize, y: usize) -> [u8; 3] {
1368 let mode_at = |xn: isize, yn: isize| -> Option<u8> {
1369 if !self.pic.available(x, y, xn, yn) {
1370 return None;
1371 }
1372 let info = &self.pic.info[self.pic.unit(xn as usize, yn as usize)];
1373 info.intra.then_some(info.intra_mode)
1374 };
1375 let left = mode_at(x as isize - 1, y as isize);
1376 let ctb_top = y & ((1 << self.ctb_log2) - 1) == 0;
1377 let above = if ctb_top {
1378 None
1379 } else {
1380 mode_at(x as isize, y as isize - 1)
1381 };
1382 mpm_list(left, above)
1383 }
1384
1385 /// Copy the decoder's intra prediction of the `1 << log2` coding unit at
1386 /// `(x, y)` in `mode` from the reconstruction planes into `self.pred`.
1387 fn intra_pred(&mut self, x: usize, y: usize, log2: u32, mode: u8) {
1388 let n = 1usize << log2;
1389 let (w, cw) = (self.w, self.w / 2);
1390 self.pic.predict_intra(0, x, y, log2, mode);
1391 self.pic.predict_intra(1, x / 2, y / 2, log2 - 1, mode);
1392 self.pic.predict_intra(2, x / 2, y / 2, log2 - 1, mode);
1393 for r in 0..n {
1394 let at = (y + r) * w + x;
1395 self.pred[0][at..][..n].copy_from_slice(&self.pic.planes.y[at..][..n]);
1396 }
1397 for r in 0..n / 2 {
1398 let at = (y / 2 + r) * cw + x / 2;
1399 self.pred[1][at..][..n / 2].copy_from_slice(&self.pic.planes.cb[at..][..n / 2]);
1400 self.pred[2][at..][..n / 2].copy_from_slice(&self.pic.planes.cr[at..][..n / 2]);
1401 }
1402 }
1403
1404 /// Predict and quantise an intra coding unit in `mode` (chroma follows the
1405 /// luma mode), and cost it as `SSD + lambda * bits` like an inter candidate.
1406 fn eval_intra(
1407 &mut self,
1408 x: usize,
1409 y: usize,
1410 log2: u32,
1411 mode: u8,
1412 mpm: [u8; 3],
1413 contexts: &Contexts,
1414 ) -> Result<(f64, Eval)> {
1415 let n = 1usize << log2;
1416 self.intra_pred(x, y, log2, mode);
1417 let src: &'a PaddedSource = self.src;
1418 let sh = self.sign_hiding;
1419 let qp_c = self.qpc;
1420 let scan = scan_index(mode, log2, true);
1421 let cscan = scan_index(mode, log2 - 1, false);
1422 let luma = code_tb(
1423 &src.y,
1424 self.w,
1425 &self.pred[0],
1426 self.w,
1427 (x, y),
1428 n,
1429 self.qpd,
1430 self.bd,
1431 sh,
1432 (scan, n == 4),
1433 self.k.zero_alpha,
1434 );
1435 let cb = code_tb(
1436 &src.cb,
1437 self.w / 2,
1438 &self.pred[1],
1439 self.w / 2,
1440 (x / 2, y / 2),
1441 n / 2,
1442 qp_c,
1443 self.bd,
1444 sh,
1445 (cscan, false),
1446 self.k.zero_alpha,
1447 );
1448 let cr = code_tb(
1449 &src.cr,
1450 self.w / 2,
1451 &self.pred[2],
1452 self.w / 2,
1453 (x / 2, y / 2),
1454 n / 2,
1455 qp_c,
1456 self.bd,
1457 sh,
1458 (cscan, false),
1459 self.k.zero_alpha,
1460 );
1461 let syntax = CuSyntax {
1462 skip: false,
1463 intra: Some(IntraCu { mode, mpm }),
1464 part: Part::Square,
1465 pus: [([0, 0], 0); 2],
1466 tus: Vec::new(),
1467 merge: None,
1468 mvd: [0, 0],
1469 mvp_flag: 0,
1470 root: true,
1471 cbf: [luma.cbf, cb.cbf, cr.cbf],
1472 levels: [luma.levels.clone(), cb.levels.clone(), cr.levels.clone()],
1473 };
1474 let mut counter = CabacEncoder::counter(contexts.clone());
1475 counter.set_estimating(true);
1476 self.write_cu(&mut counter, x, y, log2, &syntax);
1477 let ssd = luma.ssd + cb.ssd + cr.ssd;
1478 let cost = ssd + self.lambda * counter.bit_count_f64();
1479 let eval = Eval {
1480 syntax,
1481 recon: [luma.recon, cb.recon, cr.recon],
1482 };
1483 Ok((cost, eval))
1484 }
1485
1486 /// Write the intra part of a coding unit (7.3.8.5 with MODE_INTRA, 2Nx2N):
1487 /// the luma mode as `prev_intra_luma_pred_flag` with `mpm_idx` or the
1488 /// remainder, `intra_chroma_pred_mode` 4 (the luma mode), then the transform
1489 /// tree at depth 0 with no split.
1490 fn write_intra_cu(&self, e: &mut CabacEncoder, log2: u32, s: &CuSyntax, im: IntraCu) {
1491 e.encode_bin(ctx::PRED_MODE, 1); // MODE_INTRA
1492 if log2 == MIN_CB_LOG2 {
1493 e.encode_bin(ctx::PART_MODE, 1); // PART_2Nx2N
1494 }
1495 let is_mpm = im.mpm.contains(&im.mode);
1496 e.encode_bin(ctx::PREV_INTRA_LUMA_PRED, u32::from(is_mpm));
1497 match im.mpm.iter().position(|&m| m == im.mode) {
1498 Some(idx) => {
1499 // mpm_idx: truncated rice, cMax 2, all bypass.
1500 e.encode_bypass(u32::from(idx > 0));
1501 if idx > 0 {
1502 e.encode_bypass(u32::from(idx == 2));
1503 }
1504 }
1505 None => {
1506 // rem_intra_luma_pred_mode: the index among the non-candidates.
1507 let mut sorted = im.mpm;
1508 sorted.sort_unstable();
1509 let mut rem = im.mode;
1510 for &m in sorted.iter().rev() {
1511 if rem > m {
1512 rem -= 1;
1513 }
1514 }
1515 e.encode_bypass_bits(u32::from(rem), 5);
1516 }
1517 }
1518 e.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0); // 4: the luma mode
1519 // split_transform_flag at depth 0, coded when the block is between the
1520 // minimum and maximum transform sizes (MaxTrafoDepth is one).
1521 if self.intra_tt_split && (3..=5).contains(&log2) {
1522 e.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
1523 }
1524 let scan = scan_index(im.mode, log2, true);
1525 let cscan = scan_index(im.mode, log2 - 1, false);
1526 let [luma, cb, cr] = s.cbf;
1527 e.encode_bin(ctx::CBF_CHROMA, u32::from(cb));
1528 e.encode_bin(ctx::CBF_CHROMA, u32::from(cr));
1529 e.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma));
1530 if luma {
1531 self.put_residual(e, &s.levels[0], log2, 0, scan);
1532 }
1533 if cb {
1534 self.put_residual(e, &s.levels[1], log2 - 1, 1, cscan);
1535 }
1536 if cr {
1537 self.put_residual(e, &s.levels[2], log2 - 1, 2, cscan);
1538 }
1539 }
1540
1541 /// Write an inter coding unit split into two halves (7.3.8.5, AMVP halves): the
1542 /// part mode (2NxN as `01`, Nx2N as `00`, with AMP off), the two AMVP
1543 /// prediction units, `rqt_root_cbf`, then the four half-size transform units
1544 /// of the inferred split, whose chroma flags are the depth-zero ones.
1545 fn write_split_cu(&self, e: &mut CabacEncoder, log2: u32, s: &CuSyntax) {
1546 e.encode_bin(ctx::PRED_MODE, 0); // MODE_INTER
1547 e.encode_bin(ctx::PART_MODE, 0);
1548 e.encode_bin(ctx::PART_MODE + 1, u32::from(s.part == Part::Horizontal));
1549 for (mvd, flag) in s.pus {
1550 e.encode_bin(ctx::MERGE_FLAG, 0);
1551 write_mvd(e, mvd);
1552 e.encode_bin(ctx::MVP_FLAG, u32::from(flag));
1553 }
1554 e.encode_bin(ctx::RQT_ROOT_CBF, u32::from(s.root));
1555 if !s.root {
1556 return;
1557 }
1558 let cb0 = s.tus.iter().any(|t| t.cbf[1]);
1559 let cr0 = s.tus.iter().any(|t| t.cbf[2]);
1560 e.encode_bin(ctx::CBF_CHROMA, u32::from(cb0));
1561 e.encode_bin(ctx::CBF_CHROMA, u32::from(cr0));
1562 for t in &s.tus {
1563 if cb0 {
1564 e.encode_bin(ctx::CBF_CHROMA + 1, u32::from(t.cbf[1]));
1565 }
1566 if cr0 {
1567 e.encode_bin(ctx::CBF_CHROMA + 1, u32::from(t.cbf[2]));
1568 }
1569 e.encode_bin(ctx::CBF_LUMA, u32::from(t.cbf[0]));
1570 if t.cbf[0] {
1571 self.put_residual(e, &t.levels[0], log2 - 1, 0, 0);
1572 }
1573 if cb0 && t.cbf[1] {
1574 self.put_residual(e, &t.levels[1], log2 - 2, 1, 0);
1575 }
1576 if cr0 && t.cbf[2] {
1577 self.put_residual(e, &t.levels[2], log2 - 2, 2, 0);
1578 }
1579 }
1580 }
1581
1582 /// Code one block's residual; while the engine only estimates a rate, the closed-form
1583 /// level estimate stands in for the per-bin walk.
1584 fn put_residual(
1585 &self,
1586 e: &mut CabacEncoder,
1587 levels: &[i32],
1588 log2: u32,
1589 c_idx: usize,
1590 scan: usize,
1591 ) {
1592 if e.is_estimating() && self.k.res_proxy {
1593 e.add_estimated_bits(estimate_residual_bits(levels, log2, scan));
1594 } else {
1595 encode_residual(e, levels, log2, c_idx, scan, self.sign_hiding, None);
1596 }
1597 }
1598
1599 /// Write one coding unit's syntax (7.3.8.5 with 2Nx2N inter units).
1600 fn write_cu(&self, e: &mut CabacEncoder, x: usize, y: usize, log2: u32, s: &CuSyntax) {
1601 e.encode_bin(ctx::CU_SKIP + self.skip_ctx(x, y), u32::from(s.skip));
1602 if s.skip {
1603 if let Some(idx) = s.merge {
1604 write_merge_idx(e, idx);
1605 }
1606 return;
1607 }
1608 if let Some(im) = s.intra {
1609 self.write_intra_cu(e, log2, s, im);
1610 return;
1611 }
1612 if s.part != Part::Square {
1613 self.write_split_cu(e, log2, s);
1614 return;
1615 }
1616 e.encode_bin(ctx::PRED_MODE, 0); // MODE_INTER
1617 e.encode_bin(ctx::PART_MODE, 1); // PART_2Nx2N
1618 match s.merge {
1619 Some(idx) => {
1620 e.encode_bin(ctx::MERGE_FLAG, 1);
1621 write_merge_idx(e, idx);
1622 }
1623 None => {
1624 e.encode_bin(ctx::MERGE_FLAG, 0);
1625 write_mvd(e, s.mvd);
1626 e.encode_bin(ctx::MVP_FLAG, u32::from(s.mvp_flag));
1627 e.encode_bin(ctx::RQT_ROOT_CBF, u32::from(s.root));
1628 if !s.root {
1629 return;
1630 }
1631 }
1632 }
1633 // transform_tree at depth 0: no split (max_transform_hierarchy_depth_inter
1634 // is 0 and the block is at most one maximum transform), so the cbf flags
1635 // of this depth and one transform unit.
1636 let [luma, cb, cr] = s.cbf;
1637 e.encode_bin(ctx::CBF_CHROMA, u32::from(cb));
1638 e.encode_bin(ctx::CBF_CHROMA, u32::from(cr));
1639 // cbf_luma is inferred to be 1 when both chroma flags are 0.
1640 if cb || cr {
1641 e.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma));
1642 }
1643 if luma {
1644 self.put_residual(e, &s.levels[0], log2, 0, 0);
1645 }
1646 if cb {
1647 self.put_residual(e, &s.levels[1], log2 - 1, 1, 0);
1648 }
1649 if cr {
1650 self.put_residual(e, &s.levels[2], log2 - 1, 2, 0);
1651 }
1652 }
1653
1654 /// Record a committed coding unit: its samples, motion, and the per-unit
1655 /// facts the context selection and the deblocking filter read.
1656 fn commit(&mut self, x: usize, y: usize, log2: u32, motions: [PbMotion; 2], eval: Eval) {
1657 let n = 1usize << log2;
1658 let (w, cw) = (self.w, self.w / 2);
1659 let [ry, rcb, rcr] = eval.recon;
1660 for r in 0..n {
1661 self.pic.planes.y[(y + r) * w + x..][..n].copy_from_slice(&ry[r * n..][..n]);
1662 }
1663 for r in 0..n / 2 {
1664 let at = (y / 2 + r) * cw + x / 2;
1665 self.pic.planes.cb[at..][..n / 2].copy_from_slice(&rcb[r * n / 2..][..n / 2]);
1666 self.pic.planes.cr[at..][..n / 2].copy_from_slice(&rcr[r * n / 2..][..n / 2]);
1667 }
1668 let intra_mode = eval.syntax.intra.map(|im| im.mode);
1669 let part = eval.syntax.part;
1670 let rects = partition_rects(x, y, n, part);
1671 if intra_mode.is_none() {
1672 for ((rx, ry, rw, rh), motion) in rects.into_iter().zip(motions) {
1673 self.field.store(rx, ry, rw, rh, 0, motion);
1674 }
1675 }
1676 let depth = (self.ctb_log2 - log2) as u8;
1677 let skip = eval.syntax.skip;
1678 let nz = eval.syntax.cbf[0];
1679 let qp = self.qp as i8;
1680 self.pic.update_info(x, y, n, n, |b| {
1681 b.intra = intra_mode.is_some();
1682 b.skip = skip;
1683 b.depth = depth;
1684 b.intra_mode = intra_mode.unwrap_or(1);
1685 b.qp = qp;
1686 b.nz_luma = nz;
1687 });
1688 self.pic.mark_edges(x, y, n, n, EDGE_TU | EDGE_PU);
1689 if part != Part::Square {
1690 // The four transform units of a split unit: their own luma flags, and
1691 // their edges, which the deblocking filter reads.
1692 for ((dx, dy), tu) in child_offsets(n / 2).into_iter().zip(&eval.syntax.tus) {
1693 let nz_tu = tu.cbf[0];
1694 self.pic
1695 .update_info(x + dx, y + dy, n / 2, n / 2, |b| b.nz_luma = nz_tu);
1696 }
1697 self.pic.mark_edges(x + n / 2, y, n / 2, n, EDGE_TU);
1698 self.pic.mark_edges(x, y + n / 2, n, n / 2, EDGE_TU);
1699 let (rx, ry, rw, rh) = rects[1];
1700 self.pic.mark_edges(rx, ry, rw, rh, EDGE_PU);
1701 }
1702 }
1703
1704 /// The deblocking filter over the finished picture, with the motion the
1705 /// decoder's filter reads; then the reconstruction and the motion field.
1706 fn finish_picture(mut self) -> (PRecon, MotionField) {
1707 let (w4, h4) = (self.pic.w4, self.pic.h4);
1708 for by in 0..h4 {
1709 for bx in 0..w4 {
1710 let at = by * w4 + bx;
1711 self.pic.motion[at] = match self.field.at((bx * 4) as isize, (by * 4) as isize) {
1712 Some(cell) => PuMotion {
1713 pred: cell.motion.pred,
1714 ref_pic: [
1715 if cell.motion.pred[0] {
1716 self.ref_poc
1717 } else {
1718 -1
1719 },
1720 -1,
1721 ],
1722 mv: [to32(cell.motion.mv[0]), to32(cell.motion.mv[1])],
1723 },
1724 None => PuMotion::default(),
1725 };
1726 }
1727 }
1728 if self.deblock {
1729 deblock_picture(&mut self.pic);
1730 }
1731 let recon = PRecon {
1732 y: std::mem::take(&mut self.pic.planes.y),
1733 cb: std::mem::take(&mut self.pic.planes.cb),
1734 cr: std::mem::take(&mut self.pic.planes.cr),
1735 };
1736 (recon, self.field)
1737 }
1738}
1739
1740/// How a candidate's motion was derived, which decides its syntax.
1741#[derive(Debug, Clone, Copy)]
1742enum Mode {
1743 /// `merge_idx` of the merge list.
1744 Merge(u8),
1745 /// AMVP: `mvp_lX_flag` and the vector difference.
1746 Amvp { flag: u8, mvd: [i32; 2] },
1747}
1748
1749/// The four child origins of a node, offsets in z-order.
1750fn child_offsets(half: usize) -> [(usize, usize); 4] {
1751 [(0, 0), (half, 0), (0, half), (half, half)]
1752}
1753
1754/// The P slice header (7.3.6.1) for a TRAIL_R picture: one reference, the
1755/// previous picture, named by an explicit short-term RPS, the slice QP, and
1756/// with a wavefront the entry points of its CTB-row substreams.
1757fn write_p_header(poc: i32, qp: i32, entry_points: Option<&[u32]>) -> Vec<u8> {
1758 let mut w = BitWriter::new();
1759 w.write_bit(true); // first_slice_segment_in_pic_flag
1760 w.write_ue(1); // slice_pic_parameter_set_id: the P picture parameter set
1761 w.write_ue(1); // slice_type: P
1762 w.write_bits((poc & 0xff) as u32, 8); // slice_pic_order_cnt_lsb
1763 w.write_bit(false); // short_term_ref_pic_set_sps_flag: explicit RPS
1764 // st_ref_pic_set(0): no prediction from an earlier set, one negative picture
1765 // at distance 1, no positive pictures.
1766 w.write_ue(1); // num_negative_pics
1767 w.write_ue(0); // num_positive_pics
1768 w.write_ue(0); // delta_poc_s0_minus1
1769 w.write_bit(true); // used_by_curr_pic_s0_flag
1770 w.write_bit(true); // slice_temporal_mvp_enabled_flag
1771 w.write_bit(false); // num_ref_idx_active_override_flag: one reference
1772 w.write_ue(0); // five_minus_max_num_merge_cand
1773 w.write_se(qp - 26); // slice_qp_delta
1774 if let Some(offsets) = entry_points {
1775 // entropy_coding_sync_enabled_flag: num_entry_point_offsets, then each
1776 // offset minus one in offset_len_minus1 + 1 bits (ceil_log2 of the largest + 1).
1777 w.write_ue(offsets.len() as u32);
1778 if let Some(&max) = offsets.iter().max() {
1779 let len = (32 - max.leading_zeros()).max(1);
1780 w.write_ue(len - 1);
1781 for &offset in offsets {
1782 w.write_bits(offset.saturating_sub(1), len);
1783 }
1784 }
1785 }
1786 w.write_bit(true); // byte_alignment(): the one bit
1787 w.align_to_byte();
1788 w.into_bytes()
1789}
1790
1791/// Code one P picture from the padded source and the reference, returning its
1792/// access unit and its reconstruction.
1793#[allow(clippy::too_many_arguments)] // one picture's inputs and outputs
1794pub(crate) fn code_p_picture(
1795 enc: &Encoder,
1796 src: &PaddedSource,
1797 refp: &PRecon,
1798 rp: &mut RefPlanes,
1799 ref_poc: i32,
1800 poc: i32,
1801 qp: i32,
1802 col: Option<PrevPic>,
1803) -> Result<(Vec<u8>, PRecon, PrevPic)> {
1804 let col = col.map(Arc::new);
1805 rp.fill(&refp.y, enc.threads);
1806 let rp = &*rp;
1807 let (substreams, recon, field) = if enc.cfg.inter_wpp {
1808 code_p_wavefront(enc, src, refp, rp, ref_poc, poc, qp, col)?
1809 } else {
1810 code_p_sequential(enc, src, refp, rp, ref_poc, poc, qp, col)?
1811 };
1812 let entry_points = enc.cfg.inter_wpp.then(|| {
1813 // Each substream is escaped on its own: it ends on a non-zero byte (its
1814 // stop bit), so escaping the picture is escaping the substreams in turn.
1815 let escaped: Vec<u32> = substreams
1816 .iter()
1817 .map(|s| {
1818 let mut out = Vec::with_capacity(s.len() + 8);
1819 escape_rbsp(s, &mut out);
1820 out.len() as u32
1821 })
1822 .collect();
1823 escaped[..escaped.len().saturating_sub(1)].to_vec()
1824 });
1825 let mut rbsp = write_p_header(poc, qp, entry_points.as_deref());
1826 for substream in &substreams {
1827 rbsp.extend_from_slice(substream);
1828 }
1829 let (w, h) = (enc.coded_width, enc.coded_height);
1830 let mut au = Vec::with_capacity(rbsp.len() + 64);
1831 write_annex_b(
1832 &mut au,
1833 NalHeader::new(NalUnitType::Pps),
1834 &enc.pps_p.to_rbsp(),
1835 true,
1836 );
1837 write_annex_b(&mut au, NalHeader::new(NalUnitType::TrailR), &rbsp, true);
1838 let shared = Arc::new(SharedPic::new(poc, w, h, (8, 8), false, 1));
1839 shared.publish_col(&field, h);
1840 Ok((au, recon, PrevPic { field, shared }))
1841}
1842
1843/// The sequential P coder: one CABAC substream for the whole picture, every CTB
1844/// in raster order on one thread. The `inter_wpp = false` layout.
1845#[allow(clippy::too_many_arguments)] // one picture's inputs and outputs
1846fn code_p_sequential(
1847 enc: &Encoder,
1848 src: &PaddedSource,
1849 refp: &PRecon,
1850 rp: &RefPlanes,
1851 ref_poc: i32,
1852 poc: i32,
1853 qp: i32,
1854 col: Option<Arc<PrevPic>>,
1855) -> Result<(Vec<Vec<u8>>, PRecon, MotionField)> {
1856 let mut pc = PCoder::new(enc, src, refp, rp, ref_poc, poc, qp, col);
1857 let ctb = 1usize << pc.ctb_log2;
1858 let (cols, rows) = (pc.w.div_ceil(ctb), pc.h.div_ceil(ctb));
1859 let mut cab = CabacEncoder::new(Contexts::for_init_type(qp, 1));
1860 for row in 0..rows {
1861 for col in 0..cols {
1862 let (x, y) = (col * ctb, row * ctb);
1863 let (_, tree) = pc.analyse(x, y, pc.ctb_log2, [0, 0])?;
1864 pc.code_tree(x, y, pc.ctb_log2, &tree, &mut cab)?;
1865 let last = row + 1 == rows && col + 1 == cols;
1866 cab.encode_terminate(u32::from(last));
1867 }
1868 }
1869 let (recon, field) = pc.finish_picture();
1870 Ok((vec![cab.finish()], recon, field))
1871}
1872
1873/// The published state of one finished CTB of a P picture: the bottom eight sample rows,
1874/// the 4x4 units and the motion cells of its bottom two unit rows. The CTB row below reads
1875/// these (its neighbours above and above-right, and the deblocking of its top edge) and
1876/// nothing else of the row above.
1877struct CtbSnapshot {
1878 y: Vec<u16>,
1879 cb: Vec<u16>,
1880 cr: Vec<u16>,
1881 info: Vec<BlockInfo>,
1882 cells: Vec<Option<FieldCell>>,
1883}
1884
1885/// Sample rows of a CTB the row below needs: the line its intra prediction reads and the
1886/// rows its deblocking filter reads across the top edge (8.7.2: eight rows, a multiple of
1887/// the 8x8 filter grid).
1888const SNAP_ROWS: usize = 8;
1889
1890/// The shared state of one wavefront-coded P picture.
1891struct Wave {
1892 cols: usize,
1893 rows: usize,
1894 ctb: usize,
1895 ctb_log2: u32,
1896 qp: i32,
1897 /// Finished CTBs per row: row `r` has published `progress[r]` of them.
1898 progress: Vec<Progress>,
1899 /// The snapshot of CTB `row * cols + col`, stored before its progress.
1900 snapshots: Vec<Mutex<Option<CtbSnapshot>>>,
1901 /// `TableStateIdxWpp` of each row: the contexts after its second CTB.
1902 sync: Vec<Mutex<Option<Contexts>>>,
1903 /// The CABAC substream of each row.
1904 substreams: Vec<Mutex<Vec<u8>>>,
1905 /// Set by a failing worker so the others stop waiting.
1906 abort: AtomicBool,
1907 failure: Mutex<Option<Error>>,
1908}
1909
1910/// Where a CTB row writes its share of the finished picture: the deblocked luma rows
1911/// `[y0, y1)` and chroma rows of the row (see [`bands`]), and the motion cells of its unit rows.
1912struct RowOut<'o> {
1913 y: &'o mut [u16],
1914 cb: &'o mut [u16],
1915 cr: &'o mut [u16],
1916 cells: &'o mut [Option<FieldCell>],
1917}
1918
1919/// The luma and chroma sample rows `(y0, y1, c0, c1)` that CTB row `row` of `rows` owns in
1920/// the deblocked picture. The filter of a row's top edge rewrites the three luma rows (one
1921/// chroma row) above it, so a row's output starts that far above its first line and the row
1922/// above ends there.
1923fn bands(row: usize, rows: usize, ctb: usize, h: usize) -> (usize, usize, usize, usize) {
1924 let start = |r: usize| {
1925 if r == 0 {
1926 (0, 0)
1927 } else {
1928 (r * ctb - 3, r * ctb / 2 - 1)
1929 }
1930 };
1931 let (y0, c0) = start(row);
1932 let (y1, c1) = if row + 1 == rows {
1933 (h, h / 2)
1934 } else {
1935 start(row + 1)
1936 };
1937 (y0, y1, c0, c1)
1938}
1939
1940/// The wavefront P coder: CTB rows as substreams, coded by `enc.threads` workers
1941/// dealt round-robin, a row two CTBs behind the row above (the prediction reach,
1942/// and the CABAC sync point of 9.3.2.2). Every worker owns full-picture scratch
1943/// state and imports the CTBs it reads from the row above, so each row sees the
1944/// same neighbours whichever worker codes it: the output does not depend on the
1945/// thread count. Each worker also deblocks its own rows (the filter of a row needs
1946/// the eight sample rows above it, which it has imported) and writes the finished rows
1947/// straight into the picture.
1948#[allow(clippy::too_many_arguments)]
1949fn code_p_wavefront(
1950 enc: &Encoder,
1951 src: &PaddedSource,
1952 refp: &PRecon,
1953 rp: &RefPlanes,
1954 ref_poc: i32,
1955 poc: i32,
1956 qp: i32,
1957 col: Option<Arc<PrevPic>>,
1958) -> Result<(Vec<Vec<u8>>, PRecon, MotionField)> {
1959 let ctb = enc.cfg.ctb_size;
1960 let (w, h) = (enc.coded_width, enc.coded_height);
1961 let (cols, rows) = (w.div_ceil(ctb), h.div_ceil(ctb));
1962 let wave = Wave {
1963 cols,
1964 rows,
1965 ctb,
1966 ctb_log2: ctb.trailing_zeros(),
1967 qp,
1968 progress: (0..rows).map(|_| Progress(AtomicUsize::new(0))).collect(),
1969 snapshots: (0..rows * cols).map(|_| Mutex::new(None)).collect(),
1970 sync: (0..rows).map(|_| Mutex::new(None)).collect(),
1971 substreams: (0..rows).map(|_| Mutex::new(Vec::new())).collect(),
1972 abort: AtomicBool::new(false),
1973 failure: Mutex::new(None),
1974 };
1975 let threads = enc.threads.min(rows).max(1);
1976
1977 let mut recon = PRecon {
1978 y: vec![0; w * h],
1979 cb: vec![0; w * h / 4],
1980 cr: vec![0; w * h / 4],
1981 };
1982 let mut field = MotionField::new(w, h);
1983 field.slices.push(SliceRefs::from_lists(&RefPicLists {
1984 l0: vec![RefEntry {
1985 id: 0,
1986 poc: ref_poc,
1987 long_term: false,
1988 }],
1989 l1: Vec::new(),
1990 }));
1991 // The picture split into one output per CTB row, dealt to the workers like the rows.
1992 let mut per_thread: Vec<Vec<(usize, RowOut<'_>)>> = (0..threads).map(|_| Vec::new()).collect();
1993 {
1994 let (mut ry, mut rcb, mut rcr) = (&mut recon.y[..], &mut recon.cb[..], &mut recon.cr[..]);
1995 let mut cell_bands = field.bands_mut(ctb / 4);
1996 for row in 0..rows {
1997 let (y0, y1, c0, c1) = bands(row, rows, ctb, h);
1998 let (y, rest) = ry.split_at_mut((y1 - y0) * w);
1999 ry = rest;
2000 let (cb, rest) = rcb.split_at_mut((c1 - c0) * (w / 2));
2001 rcb = rest;
2002 let (cr, rest) = rcr.split_at_mut((c1 - c0) * (w / 2));
2003 rcr = rest;
2004 let cells = cell_bands.next().unwrap_or_default();
2005 per_thread[row % threads].push((row, RowOut { y, cb, cr, cells }));
2006 }
2007 }
2008 std::thread::scope(|scope| {
2009 for mine in per_thread {
2010 let wave = &wave;
2011 let col = col.clone();
2012 scope.spawn(move || {
2013 let mut pc = PCoder::new(enc, src, refp, rp, ref_poc, poc, qp, col);
2014 for (row, out) in mine {
2015 if let Err(e) = code_p_row(wave, &mut pc, row, out) {
2016 wave.abort.store(true, Ordering::Release);
2017 if let Ok(mut slot) = wave.failure.lock() {
2018 slot.get_or_insert(e);
2019 }
2020 return;
2021 }
2022 }
2023 });
2024 }
2025 });
2026 if let Some(e) = wave.failure.into_inner().unwrap_or_else(|p| p.into_inner()) {
2027 return Err(e);
2028 }
2029 let mut substreams = Vec::with_capacity(rows);
2030 for stream in &wave.substreams {
2031 let mut stream = stream
2032 .lock()
2033 .map_err(|_| Error::corrupt("HEVC P wavefront: substream lock poisoned"))?;
2034 substreams.push(std::mem::take(&mut *stream));
2035 }
2036 Ok((substreams, recon, field))
2037}
2038
2039/// Code CTB row `row` of a wavefront P picture into its substream, publishing
2040/// each CTB as it finishes, then deblock it and write it to `out`.
2041fn code_p_row(wave: &Wave, pc: &mut PCoder<'_>, row: usize, out: RowOut<'_>) -> Result<()> {
2042 let (cols, ctb, qp) = (wave.cols, wave.ctb, wave.qp);
2043 let (w, h) = (pc.w, pc.h);
2044 if row > 0 && !wait_for_or_abort(&wave.progress[row - 1], 2.min(cols), &wave.abort) {
2045 return Ok(());
2046 }
2047 // The sync point is the row above's second CTB, so the contexts are read only
2048 // once that CTB is published.
2049 let contexts = if row == 0 || cols < 2 {
2050 Contexts::for_init_type(qp, 1)
2051 } else {
2052 wave.sync[row - 1]
2053 .lock()
2054 .ok()
2055 .and_then(|c| c.clone())
2056 .unwrap_or_else(|| Contexts::for_init_type(qp, 1))
2057 };
2058 let mut cab = CabacEncoder::new(contexts);
2059 for col in 0..cols {
2060 let (x0, y0) = (col * ctb, row * ctb);
2061 if row > 0 {
2062 if !wait_for_or_abort(&wave.progress[row - 1], (col + 2).min(cols), &wave.abort) {
2063 return Ok(());
2064 }
2065 // The CTBs of the row above this one reads: its own column and the next.
2066 if col == 0 {
2067 import_above(wave, pc, row - 1, 0)?;
2068 }
2069 if col + 1 < cols {
2070 import_above(wave, pc, row - 1, col + 1)?;
2071 }
2072 }
2073 let (_, tree) = pc.analyse(x0, y0, wave.ctb_log2, [0, 0])?;
2074 pc.code_tree(x0, y0, wave.ctb_log2, &tree, &mut cab)?;
2075 let (x1, y1) = ((x0 + ctb).min(w), (y0 + ctb).min(h));
2076 let snap = pc.export_ctb(x0, y0, x1, y1);
2077 if let Ok(mut slot) = wave.snapshots[row * cols + col].lock() {
2078 *slot = Some(snap);
2079 }
2080 if col == 1 {
2081 // 9.3.2.2: the row below syncs from the state after the second CTB.
2082 if let Ok(mut slot) = wave.sync[row].lock() {
2083 *slot = Some(cab.contexts.clone());
2084 }
2085 }
2086 wave.progress[row].0.store(col + 1, Ordering::Release);
2087 let last = row + 1 == wave.rows && col + 1 == cols;
2088 cab.encode_terminate(u32::from(last));
2089 if !last && col + 1 == cols {
2090 // end_of_subset_one_bit, then byte alignment.
2091 cab.encode_terminate(1);
2092 }
2093 }
2094 let bytes = cab.finish();
2095 if let Ok(mut slot) = wave.substreams[row].lock() {
2096 *slot = bytes;
2097 }
2098 pc.finish_row(row, wave.rows, out);
2099 Ok(())
2100}
2101
2102/// Copy the published CTB `(row, col)` into the worker's picture.
2103fn import_above(wave: &Wave, pc: &mut PCoder<'_>, row: usize, col: usize) -> Result<()> {
2104 let slot = wave.snapshots[row * wave.cols + col]
2105 .lock()
2106 .map_err(|_| Error::corrupt("HEVC P wavefront: snapshot lock poisoned"))?;
2107 let snap = slot
2108 .as_ref()
2109 .ok_or_else(|| Error::corrupt("HEVC P wavefront: row above not published"))?;
2110 let (x0, y0) = (col * wave.ctb, row * wave.ctb);
2111 let (x1, y1) = ((x0 + wave.ctb).min(pc.w), (y0 + wave.ctb).min(pc.h));
2112 pc.import_ctb(x0, y0, x1, y1, snap);
2113 Ok(())
2114}
2115
2116/// The `w` by `h` block of `src` at `(x, y)`, row by row.
2117fn region<T: Copy>(src: &[T], stride: usize, x: usize, y: usize, w: usize, h: usize) -> Vec<T> {
2118 let mut out = Vec::with_capacity(w * h);
2119 for r in 0..h {
2120 out.extend_from_slice(&src[(y + r) * stride + x..][..w]);
2121 }
2122 out
2123}
2124
2125/// The inverse of [`region`]: write `src` (row by row, `w` wide) at `(x, y)`.
2126fn place<T: Copy>(dst: &mut [T], stride: usize, x: usize, y: usize, w: usize, src: &[T]) {
2127 for (r, line) in src.chunks_exact(w).enumerate() {
2128 dst[(y + r) * stride + x..][..w].copy_from_slice(line);
2129 }
2130}
2131
2132impl PCoder<'_> {
2133 /// The bottom rows of the finished CTB covering luma `[x0, x1) x [y0, y1)`.
2134 fn export_ctb(&self, x0: usize, y0: usize, x1: usize, y1: usize) -> CtbSnapshot {
2135 let _ = y0;
2136 let (w, w4) = (self.w, self.pic.w4);
2137 let lw = x1 - x0;
2138 let ys = y1 - SNAP_ROWS;
2139 CtbSnapshot {
2140 y: region(&self.pic.planes.y, w, x0, ys, lw, SNAP_ROWS),
2141 cb: region(
2142 &self.pic.planes.cb,
2143 w / 2,
2144 x0 / 2,
2145 ys / 2,
2146 lw / 2,
2147 SNAP_ROWS / 2,
2148 ),
2149 cr: region(
2150 &self.pic.planes.cr,
2151 w / 2,
2152 x0 / 2,
2153 ys / 2,
2154 lw / 2,
2155 SNAP_ROWS / 2,
2156 ),
2157 info: region(&self.pic.info, w4, x0 / 4, ys / 4, lw / 4, SNAP_ROWS / 4),
2158 cells: self.field.export_cells(x0, ys, lw, SNAP_ROWS),
2159 }
2160 }
2161
2162 /// Write a snapshot of the CTB covering luma `[x0, x1) x [y0, y1)`.
2163 fn import_ctb(&mut self, x0: usize, y0: usize, x1: usize, y1: usize, snap: &CtbSnapshot) {
2164 let _ = y0;
2165 let (w, w4) = (self.w, self.pic.w4);
2166 let lw = x1 - x0;
2167 let ys = y1 - SNAP_ROWS;
2168 place(&mut self.pic.planes.y, w, x0, ys, lw, &snap.y);
2169 place(
2170 &mut self.pic.planes.cb,
2171 w / 2,
2172 x0 / 2,
2173 ys / 2,
2174 lw / 2,
2175 &snap.cb,
2176 );
2177 place(
2178 &mut self.pic.planes.cr,
2179 w / 2,
2180 x0 / 2,
2181 ys / 2,
2182 lw / 2,
2183 &snap.cr,
2184 );
2185 place(&mut self.pic.info, w4, x0 / 4, ys / 4, lw / 4, &snap.info);
2186 self.field.import_cells(x0, ys, lw, SNAP_ROWS, &snap.cells);
2187 }
2188
2189 /// Deblock CTB row `row` of `rows` in this worker's picture and write the rows it owns
2190 /// (see [`bands`]) and its motion cells to `out`. The vertical edges are filtered
2191 /// from eight rows above the row so that the horizontal filter of its top edge sees the
2192 /// rows of the row above as the whole-picture filter leaves them; the extra rows of that
2193 /// pass are not written out.
2194 fn finish_row(&mut self, row: usize, rows: usize, out: RowOut<'_>) {
2195 let (w, h, ctb) = (self.w, self.h, 1usize << self.ctb_log2);
2196 let w4 = self.pic.w4;
2197 let (f0, f1) = (
2198 (row * ctb).saturating_sub(SNAP_ROWS),
2199 ((row + 1) * ctb).min(h),
2200 );
2201 if self.deblock {
2202 for by in f0 / 4..f1 / 4 {
2203 for bx in 0..w4 {
2204 let at = by * w4 + bx;
2205 self.pic.motion[at] = match self.field.at((bx * 4) as isize, (by * 4) as isize)
2206 {
2207 Some(cell) => PuMotion {
2208 pred: cell.motion.pred,
2209 ref_pic: [
2210 if cell.motion.pred[0] {
2211 self.ref_poc
2212 } else {
2213 -1
2214 },
2215 -1,
2216 ],
2217 mv: [to32(cell.motion.mv[0]), to32(cell.motion.mv[1])],
2218 },
2219 None => PuMotion::default(),
2220 };
2221 }
2222 }
2223 deblock_rows(&mut self.pic, f0..f1);
2224 }
2225 let (y0, y1, c0, c1) = bands(row, rows, ctb, h);
2226 let cw = w / 2;
2227 out.y.copy_from_slice(&self.pic.planes.y[y0 * w..y1 * w]);
2228 out.cb
2229 .copy_from_slice(&self.pic.planes.cb[c0 * cw..c1 * cw]);
2230 out.cr
2231 .copy_from_slice(&self.pic.planes.cr[c0 * cw..c1 * cw]);
2232 let u0 = row * ctb / 4;
2233 for (i, dst) in out.cells.chunks_exact_mut(w4).enumerate() {
2234 dst.copy_from_slice(self.field.cell_row(u0 + i));
2235 }
2236 }
2237}
2238
2239/// Longest GOP (in pictures) coded as a unit by the GOP-parallel path of constant-QP sequences.
2240const GOP_PARALLEL_MAX_KEYINT: usize = 64;
2241
2242/// GOPs per batch on the bitrate path. Fixed (not the thread count), so the bytes do not
2243/// depend on the number of threads; it matches the 6 threads the encoder is tuned for.
2244const GOP_RC_BATCH: usize = 6;
2245
2246/// One GOP's pictures and the rate model at its end (bitrate sequences only).
2247type GopOut = (Vec<EncodedPicture>, Option<BitRateControl>);
2248
2249/// Join scoped GOP workers, turning a panic into an error.
2250fn join_all<T>(handles: Vec<std::thread::ScopedJoinHandle<'_, Result<T>>>) -> Vec<Result<T>> {
2251 handles
2252 .into_iter()
2253 .map(|h| {
2254 h.join()
2255 .unwrap_or_else(|_| Err(Error::corrupt("HEVC GOP worker panicked")))
2256 })
2257 .collect()
2258}
2259
2260/// How each GOP of the parallel path picks its QPs.
2261#[derive(Clone, Copy)]
2262enum GopMode {
2263 /// Constant QP: the IDR at this QP, predicted pictures at it plus the P offset.
2264 Fixed(i32),
2265 /// Bitrate control, run independently per GOP.
2266 Bitrate { kbps: u32, fps: f64 },
2267}
2268
2269impl Encoder {
2270 /// Encode a sequence of I420 frames at the configured size: an IDR every
2271 /// [`EncoderConfig::keyint`](crate::encoder::EncoderConfig::keyint) pictures
2272 /// and P pictures between them. Each frame is one access unit.
2273 pub fn encode_sequence(&self, frames: &[VideoFrame]) -> Result<Vec<EncodedPicture>> {
2274 let mut out = Vec::with_capacity(frames.len());
2275 self.encode_sequence_with(frames.iter().cloned(), |pic| {
2276 out.push(pic);
2277 Ok(())
2278 })?;
2279 Ok(out)
2280 }
2281
2282 /// Encode a sequence as [`Encoder::encode_sequence`] does, but hand each
2283 /// picture to `sink` as soon as it is coded, in order. Frames are consumed
2284 /// one at a time, so a long clip never has to fit in memory.
2285 pub fn encode_sequence_with<I, F>(&self, frames: I, sink: F) -> Result<()>
2286 where
2287 I: IntoIterator<Item = VideoFrame>,
2288 F: FnMut(EncodedPicture) -> Result<()>,
2289 {
2290 let keyint = self.cfg.keyint.max(1);
2291 if keyint > 256 {
2292 return Err(Error::unsupported(
2293 format!("HEVC GOP of {keyint} pictures"),
2294 "the picture order count is coded in 8 bits, so a GOP holds at most 256 pictures",
2295 ));
2296 }
2297 // Constant QP codes every picture at one quantiser; a bitrate runs the
2298 // frame-level model, which picks each picture's QP from what the
2299 // previous pictures cost.
2300 let fixed_qp = match self.cfg.rate_control {
2301 RateControl::ConstantQp(q) => Some(q.clamp(self.qp_min(), 51)),
2302 RateControl::Bitrate { .. } => None,
2303 RateControl::TargetBits(_) => {
2304 return Err(Error::unsupported(
2305 "HEVC sequence encode at a per-picture bit target",
2306 "use RateControl::Bitrate for a sequence",
2307 ));
2308 }
2309 };
2310 // Constant QP makes every GOP independent (an IDR resets all state), so whole GOPs
2311 // are coded concurrently and their pictures delivered in order: the stream is the
2312 // same bytes as the serial coder writes, whatever the thread count.
2313 //
2314 // A bitrate makes GOPs depend on each other through the rate model. GOPs then each
2315 // run their own model, starting from the IDR's default QP with the budget of their
2316 // own pictures (`base` bits each): the bytes differ from one serial model, but they
2317 // are the same at every thread count, the path being taken at one thread too.
2318 if keyint > 1 && keyint <= GOP_PARALLEL_MAX_KEYINT {
2319 let mode = match self.cfg.rate_control {
2320 RateControl::ConstantQp(_) if self.threads > 1 => {
2321 Some(GopMode::Fixed(fixed_qp.unwrap_or(27)))
2322 }
2323 RateControl::Bitrate { kbps, fps } => Some(GopMode::Bitrate { kbps, fps }),
2324 _ => None,
2325 };
2326 if let Some(mode) = mode {
2327 return self.encode_gops_parallel(frames.into_iter(), keyint, mode, sink);
2328 }
2329 }
2330 let mut rc = match self.cfg.rate_control {
2331 RateControl::Bitrate { kbps, fps } => Some(BitRateControl::new(
2332 kbps,
2333 fps,
2334 keyint,
2335 u32::from(self.cfg.bit_depth),
2336 )),
2337 _ => None,
2338 };
2339 self.run_sequence(frames, keyint, fixed_qp, &mut rc, sink)
2340 }
2341
2342 /// Code `frames` (a whole number of GOPs from a keyframe, except possibly the last) in
2343 /// batches of GOPs on concurrent workers, then hand the pictures to `sink` in order.
2344 ///
2345 /// Constant QP: a batch is `threads` GOPs, each on its own wavefront workers. Bitrate: a
2346 /// batch is [`GOP_RC_BATCH`] GOPs on `threads` lanes, each GOP starting from the rate model
2347 /// the previous batch ended with and the QP offset that batch's error implies. The batch
2348 /// size does not depend on the thread count, so the bytes do not either.
2349 fn encode_gops_parallel<I, F>(
2350 &self,
2351 mut frames: I,
2352 keyint: usize,
2353 mode: GopMode,
2354 mut sink: F,
2355 ) -> Result<()>
2356 where
2357 I: Iterator<Item = VideoFrame>,
2358 F: FnMut(EncodedPicture) -> Result<()>,
2359 {
2360 let bd = u32::from(self.cfg.bit_depth);
2361 let mut carry: Option<BitRateControl> = None;
2362 let mut offset = 0.0_f64;
2363 loop {
2364 // The first bitrate GOP is coded alone: it is the only one with no model to start
2365 // from, so the batches after it start from a measured complexity.
2366 let batch_size = match mode {
2367 GopMode::Fixed(_) => self.threads,
2368 GopMode::Bitrate { .. } if carry.is_none() => 1,
2369 GopMode::Bitrate { .. } => GOP_RC_BATCH,
2370 };
2371 let mut gops: Vec<Vec<VideoFrame>> = Vec::new();
2372 while gops.len() < batch_size {
2373 let gop: Vec<VideoFrame> = frames.by_ref().take(keyint).collect();
2374 if gop.is_empty() {
2375 break;
2376 }
2377 gops.push(gop);
2378 }
2379 if gops.is_empty() {
2380 return Ok(());
2381 }
2382 let results: Vec<Result<GopOut>> = match mode {
2383 GopMode::Fixed(qp) => {
2384 let per_gop = self.threads.div_ceil(gops.len()).max(1);
2385 std::thread::scope(|scope| {
2386 let handles: Vec<_> = gops
2387 .into_iter()
2388 .map(|gop| {
2389 let enc = self.with_threads(per_gop);
2390 scope.spawn(move || {
2391 let mut out = Vec::with_capacity(gop.len());
2392 let mut none = None;
2393 enc.run_sequence(gop, keyint, Some(qp), &mut none, |pic| {
2394 out.push(pic);
2395 Ok(())
2396 })?;
2397 Ok((out, None))
2398 })
2399 })
2400 .collect();
2401 join_all(handles)
2402 })
2403 }
2404 GopMode::Bitrate { kbps, fps } => {
2405 let n_gops = gops.len();
2406 let lanes = self.threads.min(n_gops).max(1);
2407 let per_gop = (self.threads / lanes).max(1);
2408 let carry_ref = carry.as_ref();
2409 std::thread::scope(|scope| {
2410 // Lane `l` codes GOPs `l`, `l + lanes`, ... in order.
2411 let mut work: Vec<Vec<(usize, Vec<VideoFrame>)>> =
2412 (0..lanes).map(|_| Vec::new()).collect();
2413 for (i, gop) in gops.into_iter().enumerate() {
2414 work[i % lanes].push((i, gop));
2415 }
2416 let handles: Vec<_> = work
2417 .into_iter()
2418 .map(|mine| {
2419 let enc = self.with_threads(per_gop);
2420 scope.spawn(move || {
2421 let mut done = Vec::with_capacity(mine.len());
2422 for (i, gop) in mine {
2423 let mut rc = BitRateControl::new(kbps, fps, keyint, bd);
2424 if let Some(prev) = carry_ref {
2425 rc.continue_from(prev, offset);
2426 }
2427 let mut slot = Some(rc);
2428 let mut out = Vec::with_capacity(gop.len());
2429 enc.run_sequence(gop, keyint, None, &mut slot, |pic| {
2430 out.push(pic);
2431 Ok(())
2432 })?;
2433 done.push((i, out, slot));
2434 }
2435 Ok(done)
2436 })
2437 })
2438 .collect();
2439 let lanes_done = join_all(handles);
2440 let mut by_gop: Vec<Option<Result<GopOut>>> =
2441 (0..n_gops).map(|_| None).collect();
2442 for lane in lanes_done {
2443 match lane {
2444 Ok(items) => {
2445 for (i, out, slot) in items {
2446 by_gop[i] = Some(Ok((out, slot)));
2447 }
2448 }
2449 Err(e) => return vec![Err(e)],
2450 }
2451 }
2452 by_gop.into_iter().flatten().collect()
2453 })
2454 }
2455 };
2456 let mut batch: Vec<GopOut> = Vec::new();
2457 for gop in results {
2458 batch.push(gop?);
2459 }
2460 if let GopMode::Bitrate { kbps, fps } = mode {
2461 let bits: f64 = batch
2462 .iter()
2463 .flat_map(|(pics, _)| pics)
2464 .map(|p| p.au.len() as f64 * 8.0)
2465 .sum();
2466 let pictures: usize = batch.iter().map(|(pics, _)| pics.len()).sum();
2467 let budget = pictures as f64 * bitrate_picture_bits(kbps, fps) as f64;
2468 offset = offset_after_batch(offset, bits, budget);
2469 carry = batch.last().and_then(|(_, rc)| rc.clone());
2470 }
2471 for (pics, _) in batch {
2472 for pic in pics {
2473 sink(pic)?;
2474 }
2475 }
2476 }
2477 }
2478
2479 /// The sequence loop: an IDR at every `keyint`-th frame, P pictures between.
2480 fn run_sequence<I, F>(
2481 &self,
2482 frames: I,
2483 keyint: usize,
2484 fixed_qp: Option<i32>,
2485 rc: &mut Option<BitRateControl>,
2486 mut sink: F,
2487 ) -> Result<()>
2488 where
2489 I: IntoIterator<Item = VideoFrame>,
2490 F: FnMut(EncodedPicture) -> Result<()>,
2491 {
2492 let mut st = self.seq_state();
2493 for frame in frames {
2494 sink(self.code_sequence_frame(&mut st, keyint, fixed_qp, rc, &frame, false)?)?;
2495 }
2496 Ok(())
2497 }
2498
2499 fn seq_state(&self) -> SeqState {
2500 SeqState {
2501 prev: None,
2502 prev_pic: None,
2503 ref_planes: RefPlanes::new(
2504 self.coded_width,
2505 self.coded_height,
2506 u32::from(self.cfg.bit_depth),
2507 ),
2508 poc: 0,
2509 }
2510 }
2511
2512 fn code_sequence_frame(
2513 &self,
2514 st: &mut SeqState,
2515 keyint: usize,
2516 fixed_qp: Option<i32>,
2517 rc: &mut Option<BitRateControl>,
2518 frame: &VideoFrame,
2519 force_idr: bool,
2520 ) -> Result<EncodedPicture> {
2521 let want = self.frame_format();
2522 if frame.format != want {
2523 return Err(Error::unsupported(
2524 format!("HEVC encode of {:?}", frame.format),
2525 format!("this encoder codes {want:?} at {} bits", self.cfg.bit_depth),
2526 ));
2527 }
2528 if frame.width != self.cfg.width || frame.height != self.cfg.height {
2529 return Err(Error::corrupt(format!(
2530 "HEVC encode: frame is {}x{}, encoder configured for {}x{}",
2531 frame.width, frame.height, self.cfg.width, self.cfg.height
2532 )));
2533 }
2534 let sixteen = self.cfg.bit_depth == 10;
2535 let (y, ys) = plane_samples(&frame.planes[0], sixteen);
2536 let (cb, cbs) = plane_samples(&frame.planes[1], sixteen);
2537 let (cr, crs) = plane_samples(&frame.planes[2], sixteen);
2538 let padded = self.pad_source(&y, ys, &cb, cbs, &cr, crs)?;
2539 let poc = if force_idr { 0 } else { st.poc as i32 };
2540 st.poc = (poc as usize + 1) % keyint;
2541 let idr = poc == 0;
2542 let qp = match (rc.as_ref(), fixed_qp) {
2543 (Some(model), _) => model.frame_qp(idr),
2544 (None, Some(q)) if idr => q,
2545 (None, Some(q)) => (q + P_QP_DELTA).clamp(self.qp_min(), 51),
2546 (None, None) => 27,
2547 };
2548 if idr {
2549 let (coded, y, cb, cr) = self.code_picture_planes(&padded, qp)?;
2550 if let Some(model) = rc.as_mut() {
2551 model.update(true, qp, coded.au.len() as u64 * 8);
2552 }
2553 st.prev = Some(PRecon { y, cb, cr });
2554 st.prev_pic = None;
2555 return Ok(coded);
2556 }
2557 let refp = st.prev.take().ok_or_else(|| {
2558 Error::corrupt("HEVC P encode: no reference picture before a P picture")
2559 })?;
2560 let col = st.prev_pic.take();
2561 let (au, recon, pp) = code_p_picture(
2562 self,
2563 &padded,
2564 &refp,
2565 &mut st.ref_planes,
2566 poc - 1,
2567 poc,
2568 qp,
2569 col,
2570 )?;
2571 if let Some(model) = rc.as_mut() {
2572 model.update(false, qp, au.len() as u64 * 8);
2573 }
2574 st.prev_pic = Some(pp);
2575 let recon_frame = self
2576 .cfg
2577 .keep_recon
2578 .then(|| self.crop_recon(&recon.y, &recon.cb, &recon.cr));
2579 st.prev = Some(recon);
2580 Ok(EncodedPicture {
2581 au,
2582 qp,
2583 recon: recon_frame,
2584 })
2585 }
2586}
2587
2588struct SeqState {
2589 prev: Option<PRecon>,
2590 prev_pic: Option<PrevPic>,
2591 ref_planes: RefPlanes,
2592 poc: usize,
2593}
2594
2595/// A push-style IDR + P encoder: one frame in, one access unit out, with an
2596/// IDR every `keyint` frames or on request.
2597pub struct SequenceEncoder {
2598 enc: Encoder,
2599 keyint: usize,
2600 fixed_qp: Option<i32>,
2601 rc: Option<BitRateControl>,
2602 st: SeqState,
2603}
2604
2605impl SequenceEncoder {
2606 /// Wrap `enc`, refusing what [`Encoder::encode_sequence`] refuses.
2607 pub fn new(enc: Encoder) -> Result<SequenceEncoder> {
2608 let keyint = enc.cfg.keyint.max(1);
2609 if keyint > 256 {
2610 return Err(Error::unsupported(
2611 format!("HEVC GOP of {keyint} pictures"),
2612 "the picture order count is coded in 8 bits, so a GOP holds at most 256 pictures",
2613 ));
2614 }
2615 let (fixed_qp, rc) = match enc.cfg.rate_control {
2616 RateControl::ConstantQp(q) => (Some(q.clamp(enc.qp_min(), 51)), None),
2617 RateControl::Bitrate { kbps, fps } => (
2618 None,
2619 Some(BitRateControl::new(
2620 kbps,
2621 fps,
2622 keyint,
2623 u32::from(enc.cfg.bit_depth),
2624 )),
2625 ),
2626 RateControl::TargetBits(_) => {
2627 return Err(Error::unsupported(
2628 "HEVC sequence encode at a per-picture bit target",
2629 "use RateControl::Bitrate for a sequence",
2630 ));
2631 }
2632 };
2633 let st = enc.seq_state();
2634 Ok(SequenceEncoder {
2635 enc,
2636 keyint,
2637 fixed_qp,
2638 rc,
2639 st,
2640 })
2641 }
2642
2643 /// Code `frame`, as an IDR when `force_keyframe` is set or the GOP is
2644 /// due; the GOP restarts from every IDR.
2645 pub fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<EncodedPicture> {
2646 self.enc.code_sequence_frame(
2647 &mut self.st,
2648 self.keyint,
2649 self.fixed_qp,
2650 &mut self.rc,
2651 frame,
2652 force_keyframe,
2653 )
2654 }
2655}