forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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