forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hevc.rs670 lines, 26.3 KiBHistoryRawDownload
1//! The HEVC software seat: one span of `ec-h265` through the same [`Render`]
2//! door every other seat's pictures go through, and the same way a refusal is
3//! named on stderr. Export reads the same [`Stream`] to decode its sources.
4//!
5//! `ec-h265` takes one access unit at a time in Annex B framing, which is what
6//! the demuxer hands out: the config record's VPS, SPS and PPS ride in front of
7//! every sync sample, so a span can start on any of them. Pictures leave the
8//! decoder in display (POC) order through its bumping process, so `index` counts
9//! them as they come out -- the count the demuxer's landing index is made of. The
10//! last pictures of a stream wait in the reorder buffer until the decoder is
11//! flushed at end of stream.
12//!
13//! A span starts on an IRAP. A fresh decoder treats the picture it starts on as
14//! a random-access point with NoRaslOutputFlag set, so the RASL pictures of a CRA
15//! are skipped (8.1.3) and never come out. The RADL pictures of that IRAP do come
16//! out, but ahead of it in display order: they sit before the landing picture on
17//! the timeline, and so before any span target. They are dropped, and the index
18//! counts from the landing picture on, where the demuxer put it.
19//!
20//! Each picture is cropped to its SPS conformance window and handed on as 8-bit
21//! I420. A 10-bit picture downshifts by two (a 12-bit one by four), the same
22//! truncation the AV1 seat and the hardware seat's P010 read-back take, so the
23//! seats hand the renderer the same bytes off the same file. A 4:2:2 or 4:4:4
24//! picture has its chroma averaged down to 4:2:0 by the export's `chroma_420`,
25//! and a monochrome one gets neutral chroma.
26
27use std::sync::mpsc::SyncSender;
28
29use ec_h265::decode::DecodedPicture;
30use ec_h265::{Decoder, Frame as Decoded};
31use ec_h265_syntax::ConformanceWindow;
32
33use super::{Abort, DecodeFailure, Frame, I420, LATE_RUN, Render, Wide, skip_for_speed};
34use crate::demux::Demuxer;
35use crate::project::Speed;
36
37/// One HEVC decode, pulled a picture at a time: the decoder, the display index
38/// of the next picture out, and the reusable crop buffers of the whole stream.
39pub(crate) struct Stream {
40 decoder: Decoder,
41 /// Display index of the next picture out. Signed: the landing sync sample can
42 /// sit inside what an mp4's edit list trims, i.e. before frame 0.
43 index: i64,
44 /// Set by the first picture out whose decode-order index is 0: the landing
45 /// picture. Everything out before it is a leading picture of the landing IRAP.
46 landed: bool,
47 /// Set once the demuxer runs dry and the decoder has been flushed.
48 flushed: bool,
49 /// The cropped samples at their own depth, before they narrow to 8 bits.
50 wide: [Vec<u16>; 3],
51}
52
53impl Stream {
54 /// A decoder positioned at the sync sample at or before `start_frame`.
55 pub(crate) fn open(demuxer: &mut Demuxer, start_frame: u32) -> Self {
56 Self {
57 decoder: Decoder::new(),
58 index: demuxer.seek_to_sync_at_or_before(start_frame),
59 landed: false,
60 flushed: false,
61 wide: Default::default(),
62 }
63 }
64
65 /// The next picture in display order, narrowed into `out`, with its display
66 /// index. `None` at end of stream. A refusal is named in words, and the
67 /// pictures before it stand.
68 pub(crate) fn next(
69 &mut self,
70 demuxer: &mut Demuxer,
71 out: &mut I420,
72 ) -> Result<Option<i64>, String> {
73 self.next_with(demuxer, |decoded, due, wide| fill(decoded, due, wide, out))
74 }
75
76 /// The next picture in display order at its own depth, scaled to 10 bits
77 /// (an 8-bit picture is shifted up by two), into `out`. The same stream and
78 /// the same refusals as [`Stream::next`]; the export's 10-bit seat takes these
79 /// planes, so nothing is lost to a narrowing that the file could carry.
80 pub(crate) fn next_wide(
81 &mut self,
82 demuxer: &mut Demuxer,
83 out: &mut Wide,
84 ) -> Result<Option<i64>, String> {
85 self.next_with(demuxer, |decoded, due, _| fill_wide(decoded, due, out))
86 }
87
88 /// The decode loop both outputs share: `sink` takes each picture with the
89 /// stream's crop scratch, and the display index is returned once it has.
90 fn next_with(
91 &mut self,
92 demuxer: &mut Demuxer,
93 mut sink: impl FnMut(&Decoded, i64, &mut [Vec<u16>; 3]) -> Result<(), String>,
94 ) -> Result<Option<i64>, String> {
95 loop {
96 if let Some(decoded) = self.decoder.next_frame() {
97 if !self.landed {
98 if decoded.au_index != 0 {
99 continue;
100 }
101 self.landed = true;
102 }
103 if !carried(&decoded.picture) {
104 return Err(format!(
105 "software HEVC frame {} is {}/{}-bit luma/chroma, and only 8, 10 and 12 bits are carried",
106 self.index, decoded.picture.bit_depth, decoded.picture.bit_depth_c,
107 ));
108 }
109 let due = self.index;
110 self.index += 1;
111 sink(&decoded, due, &mut self.wide)?;
112 return Ok(Some(due));
113 }
114 if self.flushed {
115 return Ok(None);
116 }
117 match demuxer.next_access_unit() {
118 Ok(Some(au)) => {
119 if let Err(e) = self.decoder.decode_annex_b(&au) {
120 return Err(format!(
121 "software HEVC decode failed at frame {}: {e}",
122 self.index
123 ));
124 }
125 }
126 // The demuxer is dry: flush releases every picture the reorder
127 // delay still holds, and the loop above hands them out.
128 Ok(None) => {
129 self.flushed = true;
130 if let Err(e) = self.decoder.flush() {
131 return Err(format!("software HEVC decode failed at end of stream: {e}"));
132 }
133 }
134 Err(e) => return Err(format!("demux error: {e}")),
135 }
136 }
137 }
138}
139
140/// The HEVC software seat over `[start_frame, end_frame)`. A span decodes from
141/// the sync sample at or before `start_frame`; pictures before the target are
142/// decoded (the target references them) but never sent.
143///
144/// A refusal out of `ec-h265`, or a picture outside what edith carries (anything
145/// but 4:2:0 at 8 or 10 bits), fails the span in words: named on stderr, the
146/// pictures decoded so far stand, and no garbage is sent.
147// The eight inputs every software span takes (`run_vp9` has the same shape); a
148// one-off struct would only ever be built and taken apart here.
149#[allow(clippy::too_many_arguments)]
150pub(super) fn run_hevc(
151 demuxer: &mut Demuxer,
152 tx: &SyncSender<Frame>,
153 start_frame: u32,
154 end_frame: u32,
155 render: &mut Render,
156 abort: &Abort,
157 speed: Speed,
158 failure: &DecodeFailure,
159) {
160 let mut stream = Stream::open(demuxer, start_frame);
161 let mut out = I420::default();
162 let mut skipped = 0;
163 while !abort.hit() {
164 let due = match stream.next(demuxer, &mut out) {
165 Ok(Some(due)) => due,
166 Ok(None) => break,
167 Err(e) => {
168 failure.set(e);
169 break;
170 }
171 };
172 if due < i64::from(start_frame) {
173 continue;
174 }
175 let due = due as u32;
176 // The three ends [`super::run`] reaches per picture: late for the
177 // playhead (one in [`LATE_RUN`] still goes through), redundant by
178 // construction at speed, or a conversion and a send.
179 let sent = if abort.late(due) {
180 if skipped < LATE_RUN {
181 skipped += 1;
182 false
183 } else {
184 skipped = 0;
185 send(&out, due, render, tx)
186 }
187 } else if skip_for_speed(speed, start_frame, due, end_frame) {
188 // Redundant by construction, not by lateness (see `skip_for_speed`).
189 false
190 } else {
191 skipped = 0;
192 send(&out, due, render, tx)
193 };
194 // The consumer went away, or the range is out: nothing left to decode for.
195 if sent || i64::from(due) + 1 >= i64::from(end_frame) {
196 break;
197 }
198 }
199}
200
201/// Queues one narrowed picture through the shared [`Render`]. `true` when the
202/// consumer went away, so the span stops rather than keeps decoding into a void.
203fn send(out: &I420, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
204 let frame = render.frame(due, &out.y, &out.u, &out.v, out.width, out.height);
205 tx.send(frame).is_err()
206}
207
208/// Whether edith carries this picture's shape: any chroma format `ec-h265`
209/// decodes (4:0:0, 4:2:0, 4:2:2, 4:4:4) at 8, 10 or 12 bits for luma and chroma.
210/// What `ec-h265` refuses (extended precision, above 12 bits, separate colour
211/// planes) never reaches here.
212fn carried(picture: &DecodedPicture) -> bool {
213 picture.chroma_format_idc <= 3
214 && matches!(picture.bit_depth, 8 | 10 | 12)
215 && matches!(chroma_depth(picture), 8 | 10 | 12)
216}
217
218/// The depth of the chroma samples: a monochrome picture has none of its own, and
219/// its neutral chroma is made at the luma depth.
220fn chroma_depth(picture: &DecodedPicture) -> u32 {
221 if picture.chroma_format_idc == 0 {
222 picture.bit_depth
223 } else {
224 picture.bit_depth_c
225 }
226}
227
228/// Crops `picture` to its conformance window, plane by plane, into 16-bit
229/// samples at their own depth, with the chroma at 4:2:0 whatever the stream
230/// codes: a 4:2:2 or 4:4:4 plane is averaged down by the export's `chroma_420`,
231/// and a monochrome picture gets neutral chroma. The window's offsets are in
232/// chroma units: `SubWidthC` by `SubHeightC` luma samples (2x2 in 4:2:0, 2x1 in
233/// 4:2:2, 1x1 in 4:4:4 and 4:0:0). `None` when the window does not fit the
234/// picture, which a corrupt SPS can say.
235fn crop(
236 picture: &DecodedPicture,
237 window: &ConformanceWindow,
238 y: &mut Vec<u16>,
239 u: &mut Vec<u16>,
240 v: &mut Vec<u16>,
241) -> Option<(u32, u32)> {
242 let (left, right) = (window.left as usize, window.right as usize);
243 let (top, bottom) = (window.top as usize, window.bottom as usize);
244 let (width, height) = (picture.width, picture.height);
245 let idc = picture.chroma_format_idc;
246 let sub_w = if matches!(idc, 1 | 2) { 2 } else { 1 };
247 let sub_h = if idc == 1 { 2 } else { 1 };
248 let out_w = width.checked_sub(sub_w * (left + right))?;
249 let out_h = height.checked_sub(sub_h * (top + bottom))?;
250 if out_w == 0 || out_h == 0 {
251 return None;
252 }
253 region(
254 &picture.y,
255 width,
256 (sub_w * left, sub_h * top),
257 (out_w, out_h),
258 y,
259 )?;
260 let (ow, oh) = (out_w.div_ceil(2), out_h.div_ceil(2));
261 if idc == 0 {
262 let neutral = 1u16 << (picture.bit_depth - 1);
263 for plane in [&mut *u, &mut *v] {
264 plane.clear();
265 plane.resize(ow * oh, neutral);
266 }
267 return Some((out_w as u32, out_h as u32));
268 }
269 let chroma_stride = width.div_ceil(sub_w);
270 let (cw, ch) = (out_w.div_ceil(sub_w), out_h.div_ceil(sub_h));
271 for (src, dst) in [(&picture.cb, &mut *u), (&picture.cr, &mut *v)] {
272 region(src, chroma_stride, (left, top), (cw, ch), dst)?;
273 if (cw, ch) != (ow, oh) {
274 let narrowed = crate::export::chroma_420(dst, cw, ch, ow, oh);
275 dst.clear();
276 dst.extend(narrowed.into_iter().map(|s| s as u16));
277 }
278 }
279 Some((out_w as u32, out_h as u32))
280}
281
282/// One rectangle of a plane, copied row by row into `dst`. `None` when it runs
283/// past the plane's samples.
284fn region(
285 src: &[u16],
286 stride: usize,
287 (x0, y0): (usize, usize),
288 (w, h): (usize, usize),
289 dst: &mut Vec<u16>,
290) -> Option<()> {
291 dst.clear();
292 for row in y0..y0.checked_add(h)? {
293 let start = row.checked_mul(stride)?.checked_add(x0)?;
294 dst.extend_from_slice(src.get(start..start.checked_add(w)?)?);
295 }
296 Some(())
297}
298
299/// Narrows one cropped plane to 8 bits by the depth's downshift.
300fn to_8bit(src: &[u16], shift: u32, dst: &mut Vec<u8>) {
301 dst.clear();
302 dst.extend(src.iter().map(|&sample| (sample >> shift) as u8));
303}
304
305/// Crops and narrows one picture into `out`. `Err` when the window does not fit
306/// the picture.
307/// One cropped picture at 10-bit scale, into the caller's planes. The crop is
308/// the same as [`fill`]'s; an 8-bit picture is shifted up to the 10-bit scale.
309fn fill_wide(decoded: &Decoded, due: i64, out: &mut Wide) -> Result<(), String> {
310 let picture = &decoded.picture;
311 let Some((w, h)) = crop(picture, &decoded.window, &mut out.y, &mut out.u, &mut out.v) else {
312 return Err(format!(
313 "software HEVC frame {due}: its conformance window does not fit the {}x{} picture",
314 picture.width, picture.height,
315 ));
316 };
317 // To the 10-bit scale: 8-bit shifts up by two, 12-bit down by two.
318 let to_10 = |s: &mut u16, depth: u32| {
319 *s = if depth <= 10 { *s << (10 - depth) } else { *s >> (depth - 10) };
320 };
321 for s in &mut out.y {
322 to_10(s, picture.bit_depth);
323 }
324 for s in out.u.iter_mut().chain(out.v.iter_mut()) {
325 to_10(s, chroma_depth(picture));
326 }
327 out.width = w;
328 out.height = h;
329 Ok(())
330}
331
332fn fill(
333 decoded: &Decoded,
334 due: i64,
335 wide: &mut [Vec<u16>; 3],
336 out: &mut I420,
337) -> Result<(), String> {
338 let picture = &decoded.picture;
339 let [wy, wu, wv] = wide;
340 let Some((w, h)) = crop(picture, &decoded.window, wy, wu, wv) else {
341 return Err(format!(
342 "software HEVC frame {due}: its conformance window does not fit the {}x{} picture",
343 picture.width, picture.height,
344 ));
345 };
346 let shift_luma = picture.bit_depth.saturating_sub(8);
347 let shift_chroma = chroma_depth(picture).saturating_sub(8);
348 to_8bit(wy, shift_luma, &mut out.y);
349 to_8bit(wu, shift_chroma, &mut out.u);
350 to_8bit(wv, shift_chroma, &mut out.v);
351 out.width = w;
352 out.height = h;
353 Ok(())
354}
355
356#[cfg(test)]
357mod tests {
358 use std::path::PathBuf;
359 use std::process::Command;
360
361 use super::*;
362
363 fn asset(name: &str) -> PathBuf {
364 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
365 .join("../../assets")
366 .join(name)
367 }
368
369 /// The window's crop is taken off each plane in its own units: luma by two
370 /// samples a chroma unit, chroma by one, and the samples are the ones that
371 /// sat inside the window.
372 #[test]
373 fn crop_takes_the_conformance_window_out_of_the_coded_picture() {
374 // A 16x8 coded picture whose luma sample at (x, y) is x + 16 * y.
375 let luma: Vec<u16> = (0..8u16)
376 .flat_map(|y| (0..16u16).map(move |x| x + 16 * y))
377 .collect();
378 let picture = DecodedPicture {
379 width: 16,
380 height: 8,
381 bit_depth: 8,
382 bit_depth_c: 8,
383 chroma_format_idc: 1,
384 y: luma,
385 cb: vec![7; 8 * 4],
386 cr: vec![9; 8 * 4],
387 };
388 // One chroma unit off the left and right, one off the bottom: luma loses
389 // two samples each side and two off the bottom.
390 let window = ConformanceWindow {
391 left: 1,
392 right: 1,
393 top: 0,
394 bottom: 1,
395 };
396 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
397 assert_eq!(
398 crop(&picture, &window, &mut y, &mut u, &mut v),
399 Some((12, 6))
400 );
401 assert_eq!(y.len(), 12 * 6);
402 assert_eq!(&y[..12], &[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
403 assert_eq!(y[12], 18, "the second row starts two samples in, at y = 1");
404 assert_eq!(
405 (u.len(), v.len()),
406 (6 * 3, 6 * 3),
407 "chroma crops by the same units"
408 );
409 assert!(u.iter().all(|&s| s == 7) && v.iter().all(|&s| s == 9));
410
411 // A window that eats the whole picture is refused, not cropped to nothing.
412 let all = ConformanceWindow {
413 left: 4,
414 right: 4,
415 top: 0,
416 bottom: 0,
417 };
418 assert_eq!(crop(&picture, &all, &mut y, &mut u, &mut v), None);
419 }
420
421 /// Every picture a linear decode releases, cropped to its window at its own
422 /// depth, equals ffmpeg's decode plane for plane. The fixtures run from the
423 /// 8-bit and Main 10 4:2:0 cases through an odd size and a CRA-led GOP.
424 #[test]
425 fn decoded_planes_match_ffmpeg_sample_for_sample() {
426 let cases = [
427 ("test_hevcsw_8.mp4", 352, 288, "yuv420p", 1),
428 ("test_hevcsw_8.mkv", 352, 288, "yuv420p", 1),
429 ("test_hevcsw_10.mp4", 352, 288, "yuv420p10le", 2),
430 ("test_hevcsw_10.mkv", 352, 288, "yuv420p10le", 2),
431 ("test_hevcsw_odd.mp4", 350, 286, "yuv420p", 1),
432 ("test_hevcsw_cra.mp4", 352, 288, "yuv420p", 1),
433 ];
434 for (name, w, h, pix_fmt, bytes) in cases {
435 let path = asset(name);
436 let want = ffmpeg_planes(&path, w, h, pix_fmt, bytes);
437 let got = ec_planes(&path);
438 assert_eq!(got.len(), want.len(), "{name}: picture count");
439 for (i, (g, e)) in got.iter().zip(&want).enumerate() {
440 assert!(g == e, "{name}: picture {i} differs from ffmpeg");
441 }
442 }
443 }
444
445 /// A 4:2:2 picture crops with full-height chroma and comes out 4:2:0: the
446 /// window's vertical offsets are luma rows, and each pair of chroma rows
447 /// averages to one, an odd last row with itself.
448 #[test]
449 fn crop_takes_422_to_420_by_averaging_chroma_row_pairs() {
450 let (w, h) = (16usize, 8usize);
451 // Chroma is 8 wide and 8 tall here: row r holds 10 * r.
452 let chroma: Vec<u16> = (0..8u16)
453 .flat_map(|r| std::iter::repeat_n(10 * r, 8))
454 .collect();
455 let picture = DecodedPicture {
456 width: w,
457 height: h,
458 bit_depth: 8,
459 bit_depth_c: 8,
460 chroma_format_idc: 2,
461 y: vec![3; w * h],
462 cb: chroma.clone(),
463 cr: chroma,
464 };
465 assert!(carried(&picture));
466 // One chroma unit off each side: luma loses two columns each side, and one
467 // luma row off the bottom, as 4:2:2 has no vertical chroma unit.
468 let window = ConformanceWindow {
469 left: 1,
470 right: 1,
471 top: 0,
472 bottom: 1,
473 };
474 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
475 assert_eq!(
476 crop(&picture, &window, &mut y, &mut u, &mut v),
477 Some((12, 7))
478 );
479 assert_eq!(y.len(), 12 * 7);
480 // Cropped chroma rows 0..7 hold 0, 10, .., 60; pairs (0,10), (20,30),
481 // (40,50) and the odd row 60 with itself.
482 let want: Vec<u16> = [5u16, 25, 45, 60]
483 .iter()
484 .flat_map(|&r| std::iter::repeat_n(r, 6))
485 .collect();
486 assert_eq!(u, want);
487 assert_eq!(v, want);
488 }
489
490 /// The seat's own pictures for a whole file, each as 4:2:0 planes widened to
491 /// 16 bits: 8-bit through the same [`Stream::next`] the span uses, 10-bit
492 /// through [`Stream::next_wide`].
493 fn seat_planes(path: &std::path::Path, bits: u32) -> Vec<[Vec<u16>; 3]> {
494 let (_, mut demuxer) = crate::demux::Demuxer::open(path).expect("open the clip");
495 let mut stream = Stream::open(&mut demuxer, 0);
496 let mut out = Vec::new();
497 if bits == 8 {
498 let mut picture = I420::default();
499 while stream
500 .next(&mut demuxer, &mut picture)
501 .expect("decode")
502 .is_some()
503 {
504 out.push([
505 picture.y.iter().map(|&s| u16::from(s)).collect(),
506 picture.u.iter().map(|&s| u16::from(s)).collect(),
507 picture.v.iter().map(|&s| u16::from(s)).collect(),
508 ]);
509 }
510 } else {
511 let mut picture = Wide::default();
512 while stream
513 .next_wide(&mut demuxer, &mut picture)
514 .expect("decode")
515 .is_some()
516 {
517 out.push([picture.y.clone(), picture.u.clone(), picture.v.clone()]);
518 }
519 }
520 out
521 }
522
523 /// Peak signal-to-noise ratio over every sample of every plane of every frame.
524 fn psnr(got: &[[Vec<u16>; 3]], want: &[[Vec<u16>; 3]], peak: f64) -> f64 {
525 let (mut squared, mut n) = (0f64, 0usize);
526 for (g, w) in got.iter().zip(want) {
527 for (gp, wp) in g.iter().zip(w) {
528 for (&a, &b) in gp.iter().zip(wp) {
529 let d = f64::from(a) - f64::from(b);
530 squared += d * d;
531 n += 1;
532 }
533 }
534 }
535 10.0 * (peak * peak * n as f64 / squared).log10()
536 }
537
538 /// A 4:2:2 clip at `pix_fmt`, encoded by ffmpeg's libx265 into the temp dir:
539 /// 30 frames of 352x288. `assets/` is gitignored, so the clip is made here.
540 fn gen_422(name: &str, pix_fmt: &str) -> PathBuf {
541 let path = std::env::temp_dir().join(format!("{name}-{}.mp4", std::process::id()));
542 let out = Command::new("ffmpeg")
543 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
544 .arg("testsrc2=size=352x288:rate=30:duration=1")
545 .args(["-frames:v", "30", "-c:v", "libx265", "-pix_fmt", pix_fmt])
546 .args(["-x265-params", "log-level=error"])
547 .arg(&path)
548 .output()
549 .expect("run ffmpeg: the clips are encoded with it");
550 assert!(
551 out.status.success(),
552 "ffmpeg: {}",
553 String::from_utf8_lossy(&out.stderr)
554 );
555 path
556 }
557
558 /// Every range-extensions shape decodes on the seat to 4:2:0 planes within a
559 /// PSNR of ffmpeg's own decode of the same file at the same narrowing, frame
560 /// for frame, every frame there is. 8-bit pictures compare at 8 bits; 10 and
561 /// 12-bit ones at the 10-bit scale `next_wide` hands on. Monochrome chroma is
562 /// the neutral value exactly.
563 #[test]
564 fn rext_streams_decode_to_420_within_psnr_of_ffmpeg() {
565 for (src, dst, bits, bytes, floor) in [
566 ("yuv422p", "yuv420p", 8, 1, 45.0),
567 ("yuv422p10le", "yuv420p10le", 10, 2, 45.0),
568 ("yuv422p12le", "yuv420p10le", 10, 2, 45.0),
569 ("yuv444p", "yuv420p", 8, 1, 38.0),
570 ("yuv444p10le", "yuv420p10le", 10, 2, 38.0),
571 ("yuv444p12le", "yuv420p10le", 10, 2, 38.0),
572 ("gray", "gray", 8, 1, 45.0),
573 ("gray10le", "gray10le", 10, 2, 45.0),
574 ("gray12le", "gray10le", 10, 2, 45.0),
575 ] {
576 let clip = gen_422(&format!("hevcrext-unit-{src}"), src);
577 let got = seat_planes(&clip, bits);
578 let want = ffmpeg_planes(&clip, 352, 288, dst, bytes);
579 let _ = std::fs::remove_file(&clip);
580 assert_eq!(got.len(), 30, "{src}: every frame comes out");
581 assert_eq!(got.len(), want.len(), "{src}: picture count");
582 let db = psnr(&got, &want, f64::from((1u32 << bits) - 1));
583 eprintln!("{src} -> {dst} against ffmpeg: {db:.2} dB");
584 assert!(db > floor, "{src} is {db:.2} dB from ffmpeg, want above {floor}");
585 if src.starts_with("gray") {
586 let neutral = 1u16 << (bits - 1);
587 assert!(
588 got.iter().all(|f| f[1].iter().chain(&f[2]).all(|&s| s == neutral)),
589 "{src}: chroma is neutral"
590 );
591 }
592 }
593 }
594
595 /// Every picture a linear decode releases, cropped as the seat crops it.
596 fn ec_planes(path: &std::path::Path) -> Vec<[Vec<u16>; 3]> {
597 let (_, mut demuxer) = crate::demux::Demuxer::open(path).expect("open the fixture");
598 let mut decoder = Decoder::new();
599 let mut out = Vec::new();
600 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
601 let mut take = |decoder: &mut Decoder, out: &mut Vec<[Vec<u16>; 3]>| {
602 while let Some(decoded) = decoder.next_frame() {
603 assert!(carried(&decoded.picture), "fixture outside 8/10-bit 4:2:0");
604 crop(&decoded.picture, &decoded.window, &mut y, &mut u, &mut v)
605 .expect("the window fits the picture");
606 out.push([y.clone(), u.clone(), v.clone()]);
607 }
608 };
609 while let Some(au) = demuxer.next_access_unit().expect("read") {
610 decoder.decode_annex_b(&au).expect("decode");
611 take(&mut decoder, &mut out);
612 }
613 decoder.flush().expect("flush");
614 take(&mut decoder, &mut out);
615 out
616 }
617
618 /// ffmpeg's own decode of the same file, split into planes, each sample
619 /// widened to 16 bits so it compares with [`ec_planes`] directly.
620 fn ffmpeg_planes(
621 path: &std::path::Path,
622 w: usize,
623 h: usize,
624 pix_fmt: &str,
625 bytes: usize,
626 ) -> Vec<[Vec<u16>; 3]> {
627 let out = Command::new("ffmpeg")
628 .args(["-v", "error", "-i"])
629 .arg(path)
630 .args([
631 "-f",
632 "rawvideo",
633 "-pix_fmt",
634 pix_fmt,
635 "-fps_mode",
636 "passthrough",
637 "-",
638 ])
639 .output()
640 .expect("run ffmpeg: the fixtures are made with it, see scripts/gen_fixtures.sh");
641 assert!(out.status.success(), "ffmpeg failed on {}", path.display());
642 // A gray target is luma alone (ffmpeg's yuv420p of gray would also move
643 // the range), so the chroma planes come back empty and are not compared.
644 let gray = pix_fmt.starts_with("gray");
645 let (cw, ch) = if gray { (0, 0) } else { (w.div_ceil(2), h.div_ceil(2)) };
646 let frame = (w * h + 2 * cw * ch) * bytes;
647 assert_eq!(
648 out.stdout.len() % frame,
649 0,
650 "ffmpeg handed back a partial frame"
651 );
652 out.stdout
653 .chunks_exact(frame)
654 .map(|f| {
655 let wide: Vec<u16> = if bytes == 1 {
656 f.iter().map(|&s| u16::from(s)).collect()
657 } else {
658 f.as_chunks::<2>()
659 .0
660 .iter()
661 .map(|p| u16::from_le_bytes(*p))
662 .collect()
663 };
664 let (y, uv) = wide.split_at(w * h);
665 let (u, v) = uv.split_at(cw * ch);
666 [y.to_vec(), u.to_vec(), v.to_vec()]
667 })
668 .collect()
669 }
670}