forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

mod.rs1057 lines, 37.0 KiBHistoryRawDownload
1//! The H.264 encoder: I and P pictures, CAVLC, 8-bit 4:2:0 progressive.
2//!
3//! # Shared reconstruction
4//!
5//! There is no second reconstruction path here. Prediction, dequantisation,
6//! the inverse transforms and the deblocking filter are the decoder's own
7//! modules, and the encoder fills the very same [`Picture`] the decoder fills,
8//! macroblock metadata included. Encoder and decoder therefore agree on every
9//! reconstructed sample by construction, not by testing — the tests only check
10//! that nothing broke the property.
11//!
12//! # Parallelism
13//!
14//! A picture is cut into one slice per worker, each slice a band of whole
15//! macroblock rows. A slice is independent by definition (no prediction
16//! crosses its boundary), so each worker owns a private picture buffer, writes
17//! its own bitstream and never reads another worker's samples; motion
18//! compensation reads the *previous* picture, which is finished and immutable.
19//! The bands are stitched together afterwards and the deblocking filter runs
20//! once over the whole picture, across slice boundaries exactly as a decoder
21//! runs it. No `unsafe`, no shared mutable state at all.
22
23mod cabac_enc;
24mod entropy;
25mod headers;
26mod mb;
27mod quant;
28mod rc;
29mod vlc;
30
31use ec_core::BitWriter;
32use ec_core::error::{Error, Result};
33use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};
34use ec_h264_syntax::{SliceType, Sps};
35
36use crate::decoder::deblock_picture;
37use crate::dpb::{Picture, SliceParams as DeblockParams};
38#[cfg(feature = "rd-ablation")]
39use crate::entropy::FLAG_SKIP;
40use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
41use crate::transform::{LevelScale4x4, LevelScale8x8};
42
43use entropy::EncEntropy;
44use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
45use mb::{MbEnc, Source, encode_mb};
46use rc::RateControl;
47
48pub use mb::Preset;
49
50/// Encoder settings.
51#[derive(Debug, Clone)]
52pub struct EncoderConfig {
53 /// Displayed luma width; must be even.
54 pub width: u32,
55 /// Displayed luma height; must be even.
56 pub height: u32,
57 /// Frames per second, for the VUI timing and the bit budget.
58 pub framerate: f32,
59 /// Target bits per second. Zero means constant quantiser ([`Self::qp`]).
60 pub bitrate: u32,
61 /// Pictures between IDR pictures; 1 codes every picture as an IDR.
62 pub gop_size: u32,
63 /// Consecutive B pictures. Only 0 is coded today (see the crate note);
64 /// a non-zero value is accepted and coded as 0 rather than refused.
65 pub bframes: u32,
66 /// Speed/quality rung.
67 pub preset: Preset,
68 /// Entropy coder: CABAC (Main profile) or CAVLC (Baseline). CABAC costs
69 /// roughly 12% fewer bits at the same reconstruction, which is why it is
70 /// the default; CAVLC is there for a decoder that cannot do better.
71 pub cabac: bool,
72 /// Worker threads, which is also the number of slices per picture; 0 means
73 /// as many as the machine has.
74 pub threads: usize,
75 /// Quantiser for constant-QP mode (`bitrate` zero).
76 pub qp: i32,
77 /// 8x8 transform (High profile). On by default, as it is in x264.
78 ///
79 /// Eligible intra and inter luma macroblocks write `transform_size_8x8_flag`
80 /// and choose the 8x8 path with a squared-error rate-distortion cost.
81 /// Turning it off restricts the stream to the Baseline/Main-profile 4x4
82 /// path, which costs 0.7 dB BD-PSNR on film and 0.2 dB on screen capture.
83 pub transform_8x8: bool,
84 #[cfg(feature = "rd-ablation")]
85 rd_lambda_standard: bool,
86 #[cfg(feature = "rd-ablation")]
87 rd_transform_8x8_intra: bool,
88 #[cfg(feature = "rd-ablation")]
89 rd_transform_8x8_inter: bool,
90 #[cfg(feature = "rd-ablation")]
91 rd_transform_8x8_roweven: bool,
92 #[cfg(feature = "rd-ablation")]
93 rd_transform_8x8_margin_bits: f64,
94}
95
96impl EncoderConfig {
97 /// Defaults for `width x height`: 30 fps, constant QP 26, every core.
98 pub fn new(width: u32, height: u32) -> EncoderConfig {
99 EncoderConfig {
100 width,
101 height,
102 framerate: 30.0,
103 bitrate: 0,
104 gop_size: 250,
105 bframes: 0,
106 preset: Preset::Fast,
107 cabac: true,
108 threads: 0,
109 qp: 26,
110 transform_8x8: true,
111 #[cfg(feature = "rd-ablation")]
112 rd_lambda_standard: false,
113 #[cfg(feature = "rd-ablation")]
114 rd_transform_8x8_intra: false,
115 #[cfg(feature = "rd-ablation")]
116 rd_transform_8x8_inter: false,
117 #[cfg(feature = "rd-ablation")]
118 rd_transform_8x8_roweven: false,
119 #[cfg(feature = "rd-ablation")]
120 rd_transform_8x8_margin_bits: 0.0,
121 }
122 }
123}
124
125/// One coded picture: an Annex-B access unit and what it cost.
126#[derive(Debug, Clone, Default)]
127pub struct EncodedPicture {
128 /// The access unit, with 4-byte start codes; parameter sets ride along on
129 /// every IDR so that every IDR is a seek point.
130 pub au: Vec<u8>,
131 /// True when the picture is an IDR.
132 pub key_frame: bool,
133 /// The quantiser the picture was coded at.
134 pub qp: i32,
135}
136
137/// A software H.264 encoder.
138pub struct Encoder {
139 cfg: EncoderConfig,
140 sps: Sps,
141 sps_nal: Vec<u8>,
142 pps_nal: Vec<u8>,
143 /// `chroma_qp_index_offset`, decided from the first source picture.
144 cqo: i32,
145 /// The previous reconstruction, which every P picture predicts from.
146 reference: Picture,
147 /// One private picture per worker; worker 0's doubles as the picture the
148 /// other bands are stitched into.
149 workers: Vec<Picture>,
150 src: Source,
151 rc: RateControl,
152 threads: usize,
153 coded_width: usize,
154 coded_height: usize,
155 frames: u64,
156 frame_num: u32,
157 idr_pic_id: u32,
158 next_id: i32,
159 /// True once a reference picture exists.
160 have_reference: bool,
161 /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter).
162 t8x8_mbs: (u64, u64),
163}
164
165/// A picture handed to the encoder: three planes, no padding assumptions.
166#[derive(Debug, Clone, Copy)]
167pub struct PictureView<'a> {
168 pub width: u32,
169 pub height: u32,
170 /// Luma plane, `width` samples per row unless `y_stride` says otherwise.
171 pub y: &'a [u8],
172 pub u: &'a [u8],
173 pub v: &'a [u8],
174 /// Row pitches; zero means "tightly packed".
175 pub y_stride: usize,
176 pub c_stride: usize,
177}
178
179impl<'a> PictureView<'a> {
180 /// A tightly packed I420 picture.
181 pub fn i420(width: u32, height: u32, y: &'a [u8], u: &'a [u8], v: &'a [u8]) -> PictureView<'a> {
182 PictureView {
183 width,
184 height,
185 y,
186 u,
187 v,
188 y_stride: width as usize,
189 c_stride: width.div_ceil(2) as usize,
190 }
191 }
192}
193
194impl Encoder {
195 /// Build an encoder for `cfg`, refusing what it cannot code.
196 pub fn new(cfg: EncoderConfig) -> Result<Encoder> {
197 #[cfg(feature = "rd-ablation")]
198 let mut cfg = cfg;
199 #[cfg(feature = "rd-ablation")]
200 apply_rd_ablation(&mut cfg);
201 if cfg.width < 16 || cfg.height < 16 {
202 return Err(Error::unsupported(
203 "picture smaller than one macroblock",
204 "H.264 codes 16x16 macroblocks; encode at 16x16 or larger",
205 ));
206 }
207 if !cfg.width.is_multiple_of(2) || !cfg.height.is_multiple_of(2) {
208 return Err(Error::unsupported(
209 "odd picture dimensions",
210 "4:2:0 chroma is half resolution in both directions, and the \
211 frame cropping offsets are in two-sample units (7.4.2.1.1); \
212 encode at even width and height",
213 ));
214 }
215 if cfg.width > 8192 || cfg.height > 8192 {
216 return Err(Error::unsupported(
217 "picture larger than 8192 samples",
218 "no level defines a picture this large for this profile",
219 ));
220 }
221 let mb_w = cfg.width.div_ceil(16);
222 let mb_h = cfg.height.div_ceil(16);
223 let fps = f64::from(cfg.framerate.max(1.0));
224 // A rational tick close to the requested rate; time_scale is twice the
225 // frame rate for progressive frames (E.2.1).
226 let timing = rational_timing(fps);
227 let seq = SeqParams {
228 width: cfg.width,
229 height: cfg.height,
230 mb_w,
231 mb_h,
232 timing,
233 bitrate: cfg.bitrate,
234 cabac: cfg.cabac,
235 transform_8x8: cfg.transform_8x8,
236 };
237 let sps_rbsp = write_sps(&seq);
238 let sps = Sps::parse(&sps_rbsp)?;
239 // Rewritten once the first source picture has been measured.
240 let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8, 0);
241 let threads = if cfg.threads == 0 {
242 std::thread::available_parallelism().map_or(1, |n| n.get())
243 } else {
244 cfg.threads
245 }
246 .clamp(1, mb_h as usize);
247 let workers = (0..threads).map(|_| Picture::default()).collect();
248 let fixed_qp = (cfg.bitrate == 0).then_some(cfg.qp.clamp(0, 51));
249 Ok(Encoder {
250 sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp),
251 pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp),
252 cqo: 0,
253 sps,
254 reference: Picture::default(),
255 workers,
256 src: Source {
257 y: Vec::new(),
258 u: Vec::new(),
259 v: Vec::new(),
260 stride: mb_w as usize * 16,
261 c_stride: mb_w as usize * 8,
262 },
263 rc: RateControl::new(cfg.bitrate, fps, cfg.gop_size, fixed_qp),
264 threads,
265 coded_width: mb_w as usize * 16,
266 coded_height: mb_h as usize * 16,
267 frames: 0,
268 frame_num: 0,
269 idr_pic_id: 0,
270 next_id: 0,
271 have_reference: false,
272 t8x8_mbs: (0, 0),
273 cfg,
274 })
275 }
276
277 /// The configuration in force.
278 /// Macroblocks coded so far with `transform_size_8x8_flag` set, as
279 /// `(intra, inter)`: the 8x8 transform's share of the stream.
280 pub fn transform_8x8_mbs(&self) -> (u64, u64) {
281 self.t8x8_mbs
282 }
283
284 pub fn config(&self) -> &EncoderConfig {
285 &self.cfg
286 }
287
288 /// The reconstruction of the last coded picture, cropped, as I420 planes.
289 /// This is what a conformant decoder produces for that picture — the tests
290 /// compare it against this crate's decoder and against the oracle.
291 pub fn reconstruction(&self) -> Option<(Vec<u8>, Vec<u8>, Vec<u8>)> {
292 if !self.have_reference {
293 return None;
294 }
295 let pic = &self.reference;
296 let (w, h) = (self.cfg.width as usize, self.cfg.height as usize);
297 let mut y = Vec::with_capacity(w * h);
298 for row in 0..h {
299 let o = pic.y.at(0, row);
300 y.extend_from_slice(&pic.y.data[o..o + w]);
301 }
302 let (cw, ch) = (w / 2, h / 2);
303 let mut planes = [Vec::with_capacity(cw * ch), Vec::with_capacity(cw * ch)];
304 for (comp, out) in planes.iter_mut().enumerate() {
305 let plane = if comp == 0 { &pic.cb } else { &pic.cr };
306 for row in 0..ch {
307 let o = plane.at(0, row);
308 out.extend_from_slice(&plane.data[o..o + cw]);
309 }
310 }
311 let [u, v] = planes;
312 Some((y, u, v))
313 }
314
315 /// Code one picture, in display order, and hand back its access unit.
316 pub fn encode(&mut self, frame: &PictureView<'_>) -> Result<EncodedPicture> {
317 if frame.width != self.cfg.width || frame.height != self.cfg.height {
318 return Err(Error::corrupt("frame size differs from the encoder's"));
319 }
320 self.pad_source(frame)?;
321 if self.frames == 0 {
322 self.cqo = chroma_qp_offset_for_source(&self.src, self.cfg.width, self.cfg.height);
323 let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo);
324 self.pps_nal = annex_b(NalUnitType::Pps, 3, &pps_rbsp);
325 }
326 let idr = self.cfg.gop_size <= 1
327 || self
328 .frames
329 .is_multiple_of(u64::from(self.cfg.gop_size.max(1)));
330 let idr = idr || !self.have_reference;
331 let qp = self.rc.frame_qp(idr);
332 if idr {
333 self.frame_num = 0;
334 }
335 let slice_type = if idr { SliceType::I } else { SliceType::P };
336
337 let mb_w = self.sps.mb_width as usize;
338 let mb_h = self.sps.mb_height as usize;
339 let bands = split_bands(mb_h, self.threads);
340 let picture_id = self.next_id;
341 self.next_id = self.next_id.wrapping_add(1);
342
343 // Per-band coding. Every worker owns its picture and its bitstream;
344 // the only shared state is the immutable reference picture and source.
345 let sps = &self.sps;
346 let src = &self.src;
347 let cfg = &self.cfg;
348 let rc = &self.rc;
349 let reference = (!idr).then_some(&self.reference);
350 let frame_num = self.frame_num;
351 let idr_pic_id = self.idr_pic_id;
352 let target = rc.frame_target(idr);
353 let cqo = self.cqo;
354 let total_mbs = (mb_w * mb_h) as f64;
355
356 let mut outputs: Vec<Vec<u8>> = Vec::new();
357 std::thread::scope(|scope| {
358 let mut handles = Vec::with_capacity(bands.len());
359 for (slice_id, (&(row0, row1), worker)) in
360 bands.iter().zip(self.workers.iter_mut()).enumerate()
361 {
362 handles.push(scope.spawn(move || {
363 worker.start(sps);
364 worker.id = picture_id;
365 let band_mbs = ((row1 - row0) * mb_w) as f64;
366 code_band(
367 worker,
368 BandJob {
369 src,
370 reference,
371 cfg,
372 rc,
373 slice_id: slice_id as u16,
374 slice_type,
375 first_mb: (row0 * mb_w) as u32,
376 rows: (row0, row1),
377 qp,
378 cabac: cfg.cabac,
379 frame_num,
380 idr,
381 idr_pic_id,
382 band_target: target * band_mbs / total_mbs,
383 cqo,
384 },
385 )
386 }));
387 }
388 for h in handles {
389 outputs.push(h.join().expect("a band worker panicked"));
390 }
391 });
392
393 // Stitch the bands into worker 0's picture, then filter the whole
394 // picture the way a decoder does.
395 let (first, rest) = self.workers.split_at_mut(1);
396 let master = &mut first[0];
397 master.slices.clear();
398 for _ in 0..bands.len() {
399 master.slices.push(DeblockParams {
400 disable_deblock_idc: 0,
401 alpha_offset: 0,
402 beta_offset: 0,
403 cb_qp_offset: self.cqo,
404 cr_qp_offset: self.cqo,
405 });
406 }
407 for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {
408 merge_band(master, worker, *band);
409 }
410 for &f in &master.mb_flags {
411 if f & FLAG_TRANS8X8 != 0 {
412 if f & FLAG_INTER != 0 {
413 self.t8x8_mbs.1 += 1;
414 } else {
415 self.t8x8_mbs.0 += 1;
416 }
417 }
418 }
419 // H5 measurement hook: the chosen candidate's trial SSD is the
420 // pre-deblock SSD of the macroblock in this picture (round 4 verified
421 // trial bits and SSD against the final picture), so capturing the
422 // per-macroblock SSD right before and right after the filter is the
423 // exact pre/post comparison with no hooks inside the RD trials.
424 #[cfg(feature = "rd-ablation")]
425 let rd_pre = rd_trace_capture(master, &self.src);
426 deblock_picture(master);
427 #[cfg(feature = "rd-ablation")]
428 rd_trace_write(master, &self.src, self.frames, rd_pre);
429 master.extend_borders();
430 master.complete = true;
431 std::mem::swap(master, &mut self.reference);
432 self.have_reference = true;
433
434 // Assemble the access unit.
435 let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::<usize>() + 64);
436 if idr {
437 au.extend_from_slice(&self.sps_nal);
438 au.extend_from_slice(&self.pps_nal);
439 }
440 let unit = if idr {
441 NalUnitType::SliceIdr
442 } else {
443 NalUnitType::Slice
444 };
445 for rbsp in &outputs {
446 au.extend_from_slice(&annex_b(unit, 3, rbsp));
447 }
448
449 let bits = au.len() as u64 * 8;
450 self.rc.update(idr, qp, bits);
451 self.frames += 1;
452 self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM);
453 if idr {
454 self.idr_pic_id ^= 1;
455 }
456 Ok(EncodedPicture {
457 au,
458 key_frame: idr,
459 qp,
460 })
461 }
462
463 /// Copy the caller's planes into whole-macroblock buffers, replicating the
464 /// edge where the picture does not fill the last macroblock.
465 fn pad_source(&mut self, f: &PictureView<'_>) -> Result<()> {
466 let (w, h) = (f.width as usize, f.height as usize);
467 let (cw, ch) = (w / 2, h / 2);
468 let y_stride = if f.y_stride == 0 { w } else { f.y_stride };
469 let c_stride = if f.c_stride == 0 { cw } else { f.c_stride };
470 if f.y.len() < y_stride * (h - 1) + w
471 || f.u.len() < c_stride * (ch - 1) + cw
472 || f.v.len() < c_stride * (ch - 1) + cw
473 {
474 return Err(Error::corrupt("source plane shorter than its stated size"));
475 }
476 pad_plane(
477 &mut self.src.y,
478 f.y,
479 y_stride,
480 w,
481 h,
482 self.coded_width,
483 self.coded_height,
484 );
485 pad_plane(
486 &mut self.src.u,
487 f.u,
488 c_stride,
489 cw,
490 ch,
491 self.coded_width / 2,
492 self.coded_height / 2,
493 );
494 pad_plane(
495 &mut self.src.v,
496 f.v,
497 c_stride,
498 cw,
499 ch,
500 self.coded_width / 2,
501 self.coded_height / 2,
502 );
503 self.src.stride = self.coded_width;
504 self.src.c_stride = self.coded_width / 2;
505 Ok(())
506 }
507}
508
509/// Everything one band worker needs.
510/// Mean absolute neighbour difference of one plane, horizontal and vertical
511/// averaged, over the `w` by `h` samples at the top left of `plane`.
512fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {
513 let (mut sum, mut n) = (0u64, 0u64);
514 for y in 0..h {
515 let row = &plane[y * stride..y * stride + w];
516 for x in 1..w {
517 sum += u64::from(row[x].abs_diff(row[x - 1]));
518 n += 1;
519 }
520 if y > 0 {
521 let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
522 for x in 0..w {
523 sum += u64::from(row[x].abs_diff(prev[x]));
524 n += 1;
525 }
526 }
527 }
528 if n == 0 { 0.0 } else { sum as f64 / n as f64 }
529}
530
531/// `chroma_qp_index_offset` for a source, from how textured its chroma is
532/// relative to its luma.
533///
534/// A negative offset spends bits on chroma that luma would otherwise take.
535/// That pays when the chroma planes are flat — screen capture, phone video,
536/// anything with large constant-hue areas — because their few edges are what
537/// the eye reads, and it loses on film, whose chroma carries as much detail as
538/// its luma and whose luma is the better place for the same bits. The
539/// separating statistic is the mean absolute sample gradient of the chroma
540/// planes over that of luma, measured on the first source picture.
541/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
542/// nine clips of the user's library, offset 0 against offset -2:
543///
544/// ```text
545/// chroma/luma gradient 0 -> -2 (dB)
546/// 0.013 +0.019
547/// 0.092 +0.181
548/// 0.094 +0.228
549/// 0.098 +0.014
550/// 0.118 +0.081
551/// 0.122 +0.045
552/// 0.128 +0.065
553/// 0.286 +0.011
554/// 0.911 -0.158
555/// ```
556///
557/// Every clip whose chroma is flatter than its luma gains; the one film clip,
558/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
559/// the middle of the gap the data leaves.
560fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
561 let (w, h) = (width as usize, height as usize);
562 let (cw, ch) = (w / 2, h / 2);
563 let luma = mean_gradient(&src.y, src.stride, w, h);
564 if luma <= 0.0 {
565 return 0;
566 }
567 let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
568 + mean_gradient(&src.v, src.c_stride, cw, ch))
569 / 2.0;
570 if chroma / luma < CHROMA_FLAT_RATIO {
571 CHROMA_FLAT_QP_OFFSET
572 } else {
573 0
574 }
575}
576
577/// Chroma is "flat" below this share of the luma gradient.
578const CHROMA_FLAT_RATIO: f64 = 0.5;
579
580/// The offset flat chroma is coded with.
581const CHROMA_FLAT_QP_OFFSET: i32 = -2;
582
583struct BandJob<'a> {
584 src: &'a Source,
585 reference: Option<&'a Picture>,
586 cfg: &'a EncoderConfig,
587 rc: &'a RateControl,
588 slice_id: u16,
589 slice_type: SliceType,
590 first_mb: u32,
591 /// Macroblock rows `[start, end)`.
592 rows: (usize, usize),
593 qp: i32,
594 cabac: bool,
595 frame_num: u32,
596 idr: bool,
597 idr_pic_id: u32,
598 band_target: f64,
599 cqo: i32,
600}
601
602/// Code one slice into its own RBSP.
603fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
604 let mb_w = pic.mb_w;
605 let mut w = BitWriter::with_capacity(4096);
606 write_slice_header(
607 &mut w,
608 &SliceParams {
609 first_mb: job.first_mb,
610 slice_type: job.slice_type,
611 frame_num: job.frame_num,
612 idr: job.idr,
613 idr_pic_id: job.idr_pic_id,
614 qp: job.qp,
615 cabac: job.cabac,
616 },
617 );
618 // CABAC starts on a byte boundary after cabac_alignment_one_bit (7.3.4).
619 let mut w = if job.cabac {
620 // cabac_init_idc 0 is the initialisation column this encoder writes.
621 EncEntropy::cabac(w, job.qp, usize::from(job.slice_type != SliceType::I))
622 } else {
623 EncEntropy::cavlc(w)
624 };
625 let header_bits = w.bit_len();
626 let mut e = MbEnc {
627 src: job.src,
628 reference: job.reference,
629 slice_type: job.slice_type,
630 slice_id: job.slice_id,
631 qp: job.qp,
632 target_qp: job.qp,
633 lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)),
634 t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg),
635 preset: job.cfg.preset,
636 lambda_standard: rd_lambda_standard(job.cfg),
637 transform_8x8: job.cfg.transform_8x8,
638 transform_8x8_intra: rd_transform_8x8_intra(job.cfg),
639 transform_8x8_inter: rd_transform_8x8_inter(job.cfg),
640 transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg),
641 ls: LevelScale4x4::new(&[16; 16]),
642 ls8: LevelScale8x8::new(&[16; 64]),
643 mb_ctx: crate::entropy::MbCtx::default(),
644 cqo: job.cqo,
645 skip_inc: 0,
646 qp_delta_inc: 0,
647 };
648 let rows = job.rows.1 - job.rows.0;
649 for (n, mb_y) in (job.rows.0..job.rows.1).enumerate() {
650 // Row-level rate control: what this band has spent against its
651 // pro-rata budget.
652 if n > 0 {
653 let spent = w.bit_len() - header_bits;
654 let expected = job.band_target * n as f64 / rows as f64;
655 let delta = job.rc.row_delta(spent, expected);
656 e.target_qp = (job.qp + delta).clamp(10, 51);
657 e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg));
658 }
659 for mb_x in 0..mb_w {
660 let addr = mb_y * mb_w + mb_x;
661 encode_mb(pic, &mut e, &mut w, addr);
662 // end_of_slice_flag, which CABAC codes after every macroblock.
663 w.end_of_slice(mb_y + 1 == job.rows.1 && mb_x + 1 == mb_w);
664 }
665 }
666 w.finish(job.slice_type == SliceType::P)
667}
668
669/// Standard Lagrangian multiplier in the squared-error domain.
670pub(crate) fn lambda_ssd(qp: i32) -> f64 {
671 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
672}
673
674/// Lagrangian multiplier. Production uses the established byte-stable ladder;
675/// the ablation feature can select the standard squared-error multiplier.
676fn lambda_for(qp: i32, standard: bool) -> f64 {
677 if standard {
678 lambda_ssd(qp)
679 } else {
680 (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
681 }
682}
683
684#[cfg(feature = "rd-ablation")]
685fn apply_rd_ablation(cfg: &mut EncoderConfig) {
686 if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") {
687 cfg.rd_lambda_standard = match lambda.as_str() {
688 "ladder" => false,
689 "standard" => true,
690 _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"),
691 };
692 }
693 if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") {
694 let (intra, inter, roweven) = match transform.as_str() {
695 "off" => (false, false, false),
696 "on" => (true, true, false),
697 "roweven" => (true, true, true),
698 "intra" => (true, false, false),
699 "inter" => (false, true, false),
700 _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"),
701 };
702 cfg.rd_transform_8x8_intra = intra;
703 cfg.rd_transform_8x8_inter = inter;
704 cfg.rd_transform_8x8_roweven = roweven;
705 cfg.transform_8x8 = intra || inter;
706 } else if cfg.transform_8x8 {
707 cfg.rd_transform_8x8_intra = true;
708 cfg.rd_transform_8x8_inter = true;
709 }
710 if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") {
711 cfg.rd_transform_8x8_margin_bits = margin
712 .parse()
713 .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number");
714 }
715}
716
717/// Luma and chroma SSD of every macroblock against the source, before the
718/// deblocking filter — the distortion the RD decision actually paid.
719#[cfg(feature = "rd-ablation")]
720fn rd_trace_capture(pic: &Picture, src: &Source) -> Option<Vec<(i64, i64)>> {
721 if std::env::var_os("EC_H264_RD_TRACE").is_none() {
722 return None;
723 }
724 let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h);
725 for mb_y in 0..pic.mb_h {
726 for mb_x in 0..pic.mb_w {
727 out.push(rd_trace_ssd(pic, src, mb_x, mb_y));
728 }
729 }
730 Some(out)
731}
732
733/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma
734/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`.
735#[cfg(feature = "rd-ablation")]
736fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64, i64)>>) {
737 use std::io::Write;
738 let Some(pre) = pre else { return };
739 let mut out = std::fs::OpenOptions::new()
740 .create(true)
741 .append(true)
742 .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture"))
743 .expect("open EC_H264_RD_TRACE");
744 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {
745 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);
746 let f = pic.mb_flags[addr];
747 let _ = writeln!(
748 out,
749 "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}",
750 u8::from(f & FLAG_INTER == 0),
751 u8::from(f & FLAG_TRANS8X8 != 0),
752 u8::from(f & FLAG_SKIP != 0),
753 pic.mb_qp[addr]
754 );
755 }
756}
757
758/// Luma and chroma SSD of one macroblock against the source planes.
759#[cfg(feature = "rd-ablation")]
760fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) {
761 let mut luma = 0i64;
762 let stride = pic.y.stride;
763 let origin = pic.y.at(mb_x * 16, mb_y * 16);
764 for row in 0..16 {
765 let s = (mb_y * 16 + row) * src.stride + mb_x * 16;
766 for x in 0..16 {
767 let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]);
768 luma += d * d;
769 }
770 }
771 let mut chroma = 0i64;
772 for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] {
773 let stride = plane.stride;
774 let origin = plane.at(mb_x * 8, mb_y * 8);
775 for row in 0..8 {
776 let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8;
777 for x in 0..8 {
778 let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]);
779 chroma += d * d;
780 }
781 }
782 }
783 (luma, chroma)
784}
785
786#[cfg(feature = "rd-ablation")]
787fn rd_lambda_standard(cfg: &EncoderConfig) -> bool {
788 cfg.rd_lambda_standard
789}
790
791#[cfg(not(feature = "rd-ablation"))]
792fn rd_lambda_standard(cfg: &EncoderConfig) -> bool {
793 cfg.transform_8x8
794}
795
796#[cfg(feature = "rd-ablation")]
797fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool {
798 cfg.rd_transform_8x8_intra
799}
800
801#[cfg(not(feature = "rd-ablation"))]
802fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool {
803 cfg.transform_8x8
804}
805
806#[cfg(feature = "rd-ablation")]
807fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool {
808 cfg.rd_transform_8x8_inter
809}
810
811#[cfg(not(feature = "rd-ablation"))]
812fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool {
813 cfg.transform_8x8
814}
815
816#[cfg(feature = "rd-ablation")]
817fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool {
818 cfg.rd_transform_8x8_roweven
819}
820
821#[cfg(not(feature = "rd-ablation"))]
822fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool {
823 false
824}
825
826#[cfg(not(feature = "rd-ablation"))]
827const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0;
828
829#[cfg(feature = "rd-ablation")]
830fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 {
831 cfg.rd_transform_8x8_margin_bits
832}
833
834#[cfg(not(feature = "rd-ablation"))]
835fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 {
836 TRANSFORM_8X8_MARGIN_BITS
837}
838
839/// Split `mb_h` macroblock rows into at most `n` contiguous bands.
840fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> {
841 let n = n.clamp(1, mb_h);
842 let mut out = Vec::with_capacity(n);
843 let mut row = 0;
844 for i in 0..n {
845 let end = (i + 1) * mb_h / n;
846 out.push((row, end));
847 row = end;
848 }
849 out
850}
851
852/// Copy one band's samples and macroblock metadata from a worker picture into
853/// the picture the deblocking filter will run over.
854fn merge_band(dst: &mut Picture, src: &Picture, (row0, row1): (usize, usize)) {
855 let mb_w = dst.mb_w;
856 // Planes.
857 for (d, s, mb_size) in [
858 (&mut dst.y, &src.y, 16usize),
859 (&mut dst.cb, &src.cb, 8),
860 (&mut dst.cr, &src.cr, 8),
861 ] {
862 let stride = d.stride;
863 let start = d.at(0, row0 * mb_size);
864 let rows = (row1 - row0) * mb_size;
865 let width = d.width;
866 for r in 0..rows {
867 let o = start + r * stride;
868 d.data[o..o + width].copy_from_slice(&s.data[o..o + width]);
869 }
870 }
871 // Per-macroblock arrays.
872 let mb_range = row0 * mb_w..row1 * mb_w;
873 dst.mb_qp[mb_range.clone()].copy_from_slice(&src.mb_qp[mb_range.clone()]);
874 dst.mb_flags[mb_range.clone()].copy_from_slice(&src.mb_flags[mb_range.clone()]);
875 dst.mb_cbp[mb_range.clone()].copy_from_slice(&src.mb_cbp[mb_range.clone()]);
876 dst.mb_dc_cbf[mb_range.clone()].copy_from_slice(&src.mb_dc_cbf[mb_range.clone()]);
877 dst.mb_slice[mb_range.clone()].copy_from_slice(&src.mb_slice[mb_range]);
878 // Per-4x4-block arrays.
879 let b = row0 * 4 * mb_w * 4..row1 * 4 * mb_w * 4;
880 dst.nz_y[b.clone()].copy_from_slice(&src.nz_y[b.clone()]);
881 dst.i4_modes[b.clone()].copy_from_slice(&src.i4_modes[b.clone()]);
882 dst.mv[b.clone()].copy_from_slice(&src.mv[b.clone()]);
883 dst.ref_idx[b.clone()].copy_from_slice(&src.ref_idx[b.clone()]);
884 dst.ref_id[b.clone()].copy_from_slice(&src.ref_id[b.clone()]);
885 dst.mvd_abs[b.clone()].copy_from_slice(&src.mvd_abs[b.clone()]);
886 dst.blk[b.clone()].copy_from_slice(&src.blk[b]);
887 // Per-chroma-block arrays.
888 let c = row0 * 2 * mb_w * 2..row1 * 2 * mb_w * 2;
889 for comp in 0..2 {
890 let (d, s) = (&mut dst.nz_c[comp], &src.nz_c[comp]);
891 d[c.clone()].copy_from_slice(&s[c.clone()]);
892 }
893 dst.decoded_mbs += (row1 - row0) * mb_w;
894}
895
896/// Copy `src` into a `out_w` x `out_h` buffer, replicating the right and
897/// bottom edges into the padding.
898fn pad_plane(
899 out: &mut Vec<u8>,
900 src: &[u8],
901 stride: usize,
902 w: usize,
903 h: usize,
904 out_w: usize,
905 out_h: usize,
906) {
907 out.clear();
908 out.resize(out_w * out_h, 0);
909 for row in 0..out_h {
910 let sr = row.min(h - 1);
911 let line = &src[sr * stride..sr * stride + w];
912 let dst = &mut out[row * out_w..row * out_w + out_w];
913 dst[..w].copy_from_slice(line);
914 if out_w > w {
915 let edge = line[w - 1];
916 dst[w..].fill(edge);
917 }
918 }
919}
920
921/// Wrap an RBSP as one Annex-B NAL unit with a 4-byte start code.
922fn annex_b(unit: NalUnitType, ref_idc: u8, rbsp: &[u8]) -> Vec<u8> {
923 let mut out = Vec::with_capacity(rbsp.len() + 8);
924 out.extend_from_slice(&[0, 0, 0, 1]);
925 out.push((ref_idc << 5) | unit_code(unit));
926 escape_rbsp(rbsp, &mut out);
927 out
928}
929
930/// `nal_unit_type` of the units this encoder emits.
931fn unit_code(unit: NalUnitType) -> u8 {
932 match unit {
933 NalUnitType::Slice => 1,
934 NalUnitType::SliceIdr => 5,
935 NalUnitType::Sps => 7,
936 NalUnitType::Pps => 8,
937 _ => 0,
938 }
939}
940
941/// A `(num_units_in_tick, time_scale)` pair for a frame rate, exact for the
942/// broadcast rates (23.976, 29.97, 59.94) and within a part in 10^5 otherwise.
943fn rational_timing(fps: f64) -> (u32, u32) {
944 for (num, den) in [
945 (24000u32, 1001u32),
946 (30000, 1001),
947 (60000, 1001),
948 (120000, 1001),
949 ] {
950 if (fps - f64::from(num) / f64::from(den)).abs() < 1e-3 {
951 return (den, num * 2);
952 }
953 }
954 let scaled = (fps * 1000.0).round().max(1.0);
955 (1000, (scaled * 2.0).min(f64::from(u32::MAX)) as u32)
956}
957
958#[cfg(test)]
959mod tests {
960 use super::*;
961
962 #[test]
963 fn bands_cover_every_row_once() {
964 for mb_h in [1usize, 5, 68, 135] {
965 for threads in [1usize, 3, 12, 200] {
966 let bands = split_bands(mb_h, threads);
967 assert!(!bands.is_empty());
968 assert_eq!(bands[0].0, 0);
969 assert_eq!(bands.last().unwrap().1, mb_h);
970 for pair in bands.windows(2) {
971 assert_eq!(pair[0].1, pair[1].0);
972 }
973 assert!(bands.iter().all(|&(a, b)| a < b), "empty band: {bands:?}");
974 }
975 }
976 }
977
978 #[test]
979 fn timing_is_exact_for_broadcast_rates() {
980 assert_eq!(rational_timing(24000.0 / 1001.0), (1001, 48000));
981 assert_eq!(rational_timing(30000.0 / 1001.0), (1001, 60000));
982 assert_eq!(rational_timing(25.0), (1000, 50000));
983 }
984
985 /// Odd dimensions are refused by name rather than coded wrong.
986 #[test]
987 fn odd_dimensions_are_refused() {
988 let Err(err) = Encoder::new(EncoderConfig::new(641, 480)) else {
989 panic!("an odd width must be refused");
990 };
991 assert!(matches!(err, Error::Unsupported { .. }), "{err}");
992 assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok());
993 }
994 #[test]
995 fn production_lambda_tracks_transform_mode() {
996 let mut cfg = EncoderConfig::new(640, 480);
997 cfg.transform_8x8 = false;
998 assert_eq!(
999 lambda_for(26, rd_lambda_standard(&cfg)),
1000 lambda_for(26, false)
1001 );
1002 cfg.transform_8x8 = true;
1003 assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26));
1004 }
1005
1006 /// Flat chroma over textured luma picks the negative chroma QP offset, and
1007 /// it reaches the PPS the encoder emits; chroma as textured as the luma
1008 /// keeps 0. The nine-clip measurement behind the rule is in
1009 /// [`chroma_qp_offset_for_source`].
1010 #[test]
1011 fn chroma_offset_follows_the_source() {
1012 let (w, h) = (64usize, 64usize);
1013 let noise = |i: usize| ((i * 2654435761) >> 13) as u8;
1014 let mut src = Source {
1015 y: (0..w * h).map(noise).collect(),
1016 u: vec![110; w * h / 4],
1017 v: vec![130; w * h / 4],
1018 stride: w,
1019 c_stride: w / 2,
1020 };
1021 assert_eq!(
1022 chroma_qp_offset_for_source(&src, w as u32, h as u32),
1023 CHROMA_FLAT_QP_OFFSET,
1024 "flat chroma must take the negative offset"
1025 );
1026 src.u = (0..w * h / 4).map(noise).collect();
1027 src.v = (0..w * h / 4).map(|i| noise(i + 7)).collect();
1028 assert_eq!(
1029 chroma_qp_offset_for_source(&src, w as u32, h as u32),
1030 0,
1031 "chroma as textured as the luma must keep 0"
1032 );
1033
1034 // The chosen offset is what the decoder will read.
1035 let mut enc = Encoder::new(EncoderConfig::new(w as u32, h as u32)).expect("encoder");
1036 let y: Vec<u8> = (0..w * h).map(noise).collect();
1037 let (u, v) = (vec![110u8; w * h / 4], vec![130u8; w * h / 4]);
1038 let au = enc
1039 .encode(&PictureView {
1040 width: w as u32,
1041 height: h as u32,
1042 y: &y,
1043 u: &u,
1044 v: &v,
1045 y_stride: w,
1046 c_stride: w / 2,
1047 })
1048 .expect("first picture encodes");
1049 assert!(
1050 au.au
1051 .windows(5)
1052 .any(|n| n[..4] == [0, 0, 0, 1] && n[4] & 0x1f == 8),
1053 "the IDR access unit carries a PPS"
1054 );
1055 assert_eq!(enc.cqo, CHROMA_FLAT_QP_OFFSET);
1056 }
1057}