forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hevc_export.rs713 lines, 26.0 KiBHistoryRawDownload
1//! HEVC export: the codec this project could read and not write until a
2//! pure-Rust encoder for it arrived -- `ec-h265` now, I+P GOPs by default and
3//! intra-only on request, the intra file every frame a self-contained IDR coded
4//! on every core at once (WPP).
5//!
6//! Three things are under test here: that the *containers* say HEVC in the
7//! words their readers expect (this project's own demuxer, and ffprobe where it
8//! is installed); that a picture whose height is not a multiple of the 64-sample
9//! coding tree block -- 1080, the resolution -- comes back out at its own size,
10//! coded padded to 1088 and cropped by the SPS conformance window; and, for the
11//! hardware seat only, that what it codes is the *picture that went in* rather
12//! than a stream that merely decodes. That last one is not a nicety: a seat
13//! whose parameter sets disagree with its coded syntax hands back the right
14//! number of frames and the wrong pixels, and nothing else here would see it.
15//!
16//! ```text
17//! cargo test -p engine --release --test hevc_export -- --test-threads=1
18//! ```
19//!
20//! Release, always: a debug intra encode is minutes a frame. The 1080p twin
21//! needs the `ffmpeg` CLI to make its source and `ffprobe` to read the coded
22//! size back; without them it says so and passes, exactly as the hardware tests
23//! here do.
24
25use std::path::{Path, PathBuf};
26use std::process::Command;
27use std::sync::OnceLock;
28use std::time::{Duration, Instant};
29
30use engine::demux::{Codec, Demuxer};
31use engine::export::{ExportSettings, Format};
32use engine::scratch::Scratch;
33use engine::{AudioSession, PlaybackSession};
34
35fn asset(name: &str) -> PathBuf {
36 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
37 .join("../../assets")
38 .join(name)
39}
40
41fn out_path(name: &str, ext: &str) -> Scratch {
42 Scratch::file(&format!("ve_hevc_{name}"), ext)
43}
44
45/// Runs an export to completion, failing on the deadline rather than hanging.
46fn export(session: &PlaybackSession, out: &Path, format: Format) {
47 export_with(
48 session,
49 out,
50 &ExportSettings {
51 format,
52 ..Default::default()
53 },
54 );
55}
56
57/// [`export`] with the settings the caller picks.
58fn export_with(session: &PlaybackSession, out: &Path, settings: &ExportSettings) {
59 let handle = session.export_to_with(out, settings);
60 let started = Instant::now();
61 while !handle.is_finished() {
62 assert!(
63 started.elapsed() < Duration::from_secs(300),
64 "the export did not finish in 300 s"
65 );
66 std::thread::sleep(Duration::from_millis(20));
67 }
68 handle
69 .result()
70 .expect("an outcome")
71 .expect("an HEVC export");
72 assert_eq!(handle.progress(), 1.0, "finished at full progress");
73}
74
75/// Two frames of the A/V fixture: what is under test is the wiring from the
76/// format to the muxer, not how long an encoder takes.
77fn two_frames() -> PlaybackSession {
78 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
79 assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front");
80 assert!(session.delete_clip(engine::project::Lane::V1, 1));
81 session
82}
83
84/// The container half, in both boxes: an HEVC export is read back as HEVC, at
85/// the size and the count it was written at, with the timeline's sound beside
86/// it. The `hvcC` record this writes is the one `demux` parses -- Matroska in
87/// `CodecPrivate`, mp4 in the sample entry -- so this is where the writer and
88/// the reader either agree or do not.
89#[test]
90fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() {
91 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
92 let session = two_frames();
93 let out = out_path("container", ext);
94 export_with(
95 &session,
96 &out,
97 &ExportSettings {
98 format,
99 intra_only: true,
100 ..Default::default()
101 },
102 );
103
104 let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export");
105 assert_eq!(meta.codec, Codec::Hevc, "{ext}: an HEVC export is HEVC");
106 assert_eq!((meta.width, meta.height), (1280, 720), "{ext}");
107 assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there");
108 // Every access unit comes back, and every one of them is a sync point:
109 // that is what intra-only means, and it is what makes any frame of the
110 // file a cut point.
111 let mut count = 0;
112 while demuxer.next_access_unit().expect("read").is_some() {
113 count += 1;
114 }
115 assert_eq!(count, 2, "{ext}: every coded picture comes back out");
116 assert_eq!(
117 demuxer.seek_to_sync_at_or_before(1),
118 1,
119 "{ext}: an intra-only file syncs on every frame"
120 );
121
122 // ...and the sound with it, through the reader an import opens it by.
123 let (audio, chunks) = AudioSession::open(&out)
124 .expect("reopen for its sound")
125 .expect("an HEVC export has an audio track");
126 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
127 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
128 eprintln!(
129 "{ext}: {} Hz x{}, rms {rms:.4}, {} bytes",
130 audio.sample_rate,
131 audio.channels,
132 std::fs::metadata(&out).unwrap().len()
133 );
134 assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})");
135 std::fs::remove_file(&out).unwrap();
136 }
137}
138
139/// The conformance-window half: the encoder pads the coded picture to whole
140/// minimum coding blocks and the SPS crops the padding back off with the
141/// §7.4.3.2.1 window -- 1080 is already a multiple of 8, so here the coded
142/// and displayed sizes agree.
143///
144/// ffprobe reads the *bitstream* rather than the container's own claim, and
145/// ffmpeg decoding the file without a complaint is what says the stream is
146/// legal.
147#[test]
148fn a_1080p_export_states_1920x1080_through_the_conformance_window() {
149 let Some(source) = fixture_1080p() else {
150 eprintln!("no ffmpeg: skipping the 1080p conformance-window twin");
151 return;
152 };
153 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
154 let mut session = PlaybackSession::open(&source).expect("open the 1080p fixture");
155 assert!(session.cut_at(2.0 / 30.0));
156 assert!(session.delete_clip(engine::project::Lane::V1, 1));
157 let out = out_path("1080p", ext);
158 export(&session, &out, format);
159
160 // The container's own claim first: this project's reader.
161 let (meta, _) = Demuxer::open(&out).expect("reopen the 1080p export");
162 assert_eq!((meta.width, meta.height), (1920, 1080), "{ext}");
163
164 // ...and the coded size, out of the SPS, by a reader that is not ours.
165 let probed = probe(&out);
166 assert_eq!(
167 probed.as_deref(),
168 Some("hevc,1920,1080"),
169 "{ext}: ffprobe reads the cropped size out of the bitstream"
170 );
171 // ...and the whole file decoded, with ffmpeg's own stderr as the test:
172 // a stream a decoder complains about is not an export.
173 let decoded = Command::new("ffmpeg")
174 .args(["-v", "error", "-i"])
175 .arg(&out)
176 .args(["-f", "null", "-"])
177 .output()
178 .expect("run ffmpeg");
179 let complaints = String::from_utf8_lossy(&decoded.stderr);
180 assert!(
181 decoded.status.success() && complaints.is_empty(),
182 "{ext}: ffmpeg complained: {complaints}"
183 );
184 std::fs::remove_file(&out).unwrap();
185 }
186 let _ = std::fs::remove_file(&source);
187}
188
189/// The loop closed where it matters to a user: the file this wrote is opened
190/// again *by edith*, picture and all. The way back in is the VA-API plugin's
191/// hardware decode, which is what makes this the twin that needs one; the test
192/// above (the containers, read by the demuxer) does not.
193#[test]
194#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
195fn an_hevc_export_decodes_back_into_pictures_through_edith() {
196 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
197 let session = two_frames();
198 let out = out_path("roundtrip", ext);
199 export(&session, &out, format);
200
201 let (meta, frames) = engine::DecodeSession::open(&out).expect("decode the export");
202 assert_eq!(meta.codec, Codec::Hevc, "{ext}");
203 let frames: Vec<_> = frames.into_iter().collect();
204 assert_eq!(frames.len(), 2, "{ext}: every written frame decodes back");
205 // The picture is the fixture's colour pattern, not black: a conformance
206 // window read wrong would show as a shifted or empty picture.
207 for (i, frame) in frames.iter().enumerate() {
208 assert_eq!((frame.width, frame.height), (1280, 720), "{ext} frame {i}");
209 assert!(
210 frame.bgra.iter().any(|&p| p > 32),
211 "{ext} frame {i} carries picture"
212 );
213 }
214 std::fs::remove_file(&out).unwrap();
215 }
216}
217
218/// The same 1080p picture, coded by the **GPU**, and the test that would have
219/// caught what shipped: the hardware seat's file decoded frame for frame while
220/// every frame of it was a band of noise over flat green, because the parameter
221/// sets promised coding tools the driver was not using. Nothing that counts
222/// frames sees that. Three things do, and all three are asserted here --
223/// ffmpeg's decoder saying *nothing at all* on its error channel, the coded
224/// size still cropping back to 1920x1080, and the picture being the source's
225/// rather than a fill (SSIM against the very frames that went in; a desynced
226/// stream scores about 0.2, this one about 0.98).
227///
228/// `testsrc2` is what makes it bite: 1080p of it splits transform trees deep
229/// enough and pushes the rate controller hard enough to need the syntax the
230/// parameter sets have to declare. The two-frame fixtures above are flat and
231/// pass either way, which is exactly how the defect got through.
232#[test]
233#[ignore = "needs libengine_hw.so and a driver with an HEVC encode entrypoint"]
234fn a_1080p_hardware_export_leaves_a_decoder_with_nothing_to_say() {
235 let Some(source) = fixture_1080p() else {
236 eprintln!("no ffmpeg: skipping the 1080p hardware twin");
237 return;
238 };
239 let session = PlaybackSession::open(&source).expect("open the 1080p fixture");
240 let settings = ExportSettings {
241 format: Format::Hevc,
242 ..Default::default()
243 };
244 let planned = engine::export::planned_video(session.meta(), &settings);
245 assert!(
246 planned.is_some_and(|seat| seat.contains("HW encode")),
247 "this twin is the GPU's, and this box named {planned:?}"
248 );
249
250 let out = out_path("1080p_hw", "mkv");
251 export(&session, &out, Format::Hevc);
252
253 let probed = probe(&out);
254 assert_eq!(
255 probed.as_deref(),
256 Some("hevc,1920,1080"),
257 "ffprobe reads the cropped size out of the bitstream"
258 );
259
260 let decoded = Command::new("ffmpeg")
261 .args(["-v", "error", "-i"])
262 .arg(&out)
263 .args(["-f", "null", "-"])
264 .output()
265 .expect("run ffmpeg");
266 let complaints = String::from_utf8_lossy(&decoded.stderr);
267 assert!(
268 decoded.status.success() && complaints.is_empty(),
269 "a decoder complained about the GPU's stream: {complaints}"
270 );
271
272 let ssim = ssim(&source, &out).expect("ffmpeg reports an SSIM");
273 assert!(
274 ssim >= 0.90,
275 "the GPU coded the source's picture, not a fill (SSIM {ssim:.4})"
276 );
277 std::fs::remove_file(&out).unwrap();
278 let _ = std::fs::remove_file(&source);
279}
280
281/// An audio-only timeline has no picture to code, and an HEVC export says so by
282/// name exactly as the mp4 and AV1 ones do -- and writes nothing.
283#[test]
284fn an_audio_only_timeline_is_refused_an_hevc_export_by_name() {
285 let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone");
286 let out = out_path("refused", "mkv");
287 let settings = ExportSettings {
288 format: Format::Hevc,
289 ..Default::default()
290 };
291 let handle = session.export_to_with(&out, &settings);
292 while !handle.is_finished() {
293 std::thread::sleep(Duration::from_millis(10));
294 }
295 let refused = handle
296 .result()
297 .expect("an outcome")
298 .expect_err("an audio-only timeline has no picture to code")
299 .to_string();
300 assert!(refused.contains("no picture"), "{refused}");
301 assert!(refused.contains("HEVC"), "{refused}");
302 assert!(!out.exists(), "nothing is written for a refusal");
303}
304
305/// A cancelled HEVC export leaves nothing behind -- not the file and not the
306/// `.part` the worker was writing. An intra-only export of a whole fixture is
307/// long enough to catch mid-flight, and the frame loop checks for a cancel
308/// every picture, so this stops in a frame or two rather than at the end.
309#[test]
310fn a_cancelled_hevc_export_leaves_no_file_behind() {
311 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
312 let out = out_path("cancelled", "mkv");
313 let settings = ExportSettings {
314 format: Format::Hevc,
315 ..Default::default()
316 };
317 let handle = session.export_to_with(&out, &settings);
318 handle.cancel();
319 let started = Instant::now();
320 while !handle.is_finished() {
321 assert!(started.elapsed() < Duration::from_secs(60), "cancel hung");
322 std::thread::sleep(Duration::from_millis(20));
323 }
324 let stopped = handle
325 .result()
326 .expect("an outcome")
327 .expect_err("a cancelled export is an error");
328 assert!(stopped.to_string().contains("cancelled"), "{stopped}");
329 assert!(!out.exists(), "no output for a cancelled export");
330 assert!(
331 !PathBuf::from(format!("{}.part", out.display())).exists(),
332 "no partial file either"
333 );
334}
335
336/// `codec,width,height` of the file's video stream as ffprobe reads it, or
337/// `None` where ffprobe is not installed.
338fn probe(path: &Path) -> Option<String> {
339 let out = Command::new("ffprobe")
340 .args([
341 "-v",
342 "error",
343 "-select_streams",
344 "v:0",
345 "-show_entries",
346 "stream=codec_name,width,height",
347 "-of",
348 "csv=p=0",
349 ])
350 .arg(path)
351 .output()
352 .ok()?;
353 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
354}
355
356/// Mean SSIM of `out` against `source`, over the frames the two have in common,
357/// as ffmpeg's own filter measures it. `None` where ffmpeg is not installed or
358/// said nothing -- the caller decides whether that is a skip or a failure.
359fn ssim(source: &Path, out: &Path) -> Option<f64> {
360 let measured = Command::new("ffmpeg")
361 .args(["-v", "info", "-i"])
362 .arg(source)
363 .arg("-i")
364 .arg(out)
365 .args(["-filter_complex", "ssim", "-f", "null", "-"])
366 .output()
367 .ok()?;
368 String::from_utf8_lossy(&measured.stderr)
369 .rsplit("All:")
370 .next()?
371 .split_whitespace()
372 .next()?
373 .parse()
374 .ok()
375}
376
377/// Mean PSNR of `out` against `source`, as ffmpeg's psnr filter measures it. The
378/// two are compared as tagged BT.709 limited range, which is what the exports
379/// are tagged as; `None` where ffmpeg is not installed or said nothing.
380fn psnr(source: &Path, out: &Path) -> Option<f64> {
381 let measured = Command::new("ffmpeg")
382 .args(["-v", "info", "-i"])
383 .arg(source)
384 .arg("-i")
385 .arg(out)
386 .args(["-filter_complex", "psnr", "-f", "null", "-"])
387 .output()
388 .ok()?;
389 String::from_utf8_lossy(&measured.stderr)
390 .rsplit("average:")
391 .next()?
392 .split_whitespace()
393 .next()?
394 .parse()
395 .ok()
396}
397
398/// A two-second 1920x1080 H.264 fixture in the temp directory -- the assets are
399/// all 720p, which is a multiple of 16 in both directions and would leave the
400/// crop path untested. `None` where ffmpeg is not installed.
401fn fixture_1080p() -> Option<Scratch> {
402 let path = out_path("source1080", "mp4");
403 let made = Command::new("ffmpeg")
404 .args([
405 "-y",
406 "-f",
407 "lavfi",
408 "-i",
409 "testsrc2=size=1920x1080:rate=30:duration=1",
410 "-c:v",
411 "libx264",
412 "-profile:v",
413 "baseline",
414 "-pix_fmt",
415 "yuv420p",
416 ])
417 .arg(&path)
418 .output()
419 .ok()?;
420 made.status.success().then_some(path)
421}
422
423/// Two seconds of 720p testsrc2 at 30 fps: 60 pictures, two GOPs at the seat's
424/// one-second key interval. `None` where ffmpeg is not installed.
425fn fixture_720p_2s() -> Option<Scratch> {
426 let path = out_path("source720_2s", "mp4");
427 let made = Command::new("ffmpeg")
428 .args([
429 "-y",
430 "-f",
431 "lavfi",
432 "-i",
433 "testsrc2=size=1280x720:rate=30:duration=2",
434 "-c:v",
435 "libx264",
436 "-profile:v",
437 "baseline",
438 "-pix_fmt",
439 "yuv420p",
440 // Tagged as the exports are (BT.709, limited range), so a PSNR
441 // against the export compares pictures, not two colour matrices.
442 "-colorspace",
443 "bt709",
444 "-color_primaries",
445 "bt709",
446 "-color_trc",
447 "bt709",
448 "-color_range",
449 "tv",
450 ])
451 .arg(&path)
452 .output()
453 .ok()?;
454 made.status.success().then_some(path)
455}
456
457/// The `ffprobe` output lines for one query over `path`, or `None` where
458/// ffprobe is not installed.
459fn ffprobe_lines(path: &Path, args: &[&str]) -> Option<Vec<String>> {
460 let out = Command::new("ffprobe")
461 .args(["-v", "error"])
462 .args(args)
463 .arg(path)
464 .output()
465 .ok()?;
466 Some(
467 String::from_utf8_lossy(&out.stdout)
468 .lines()
469 .map(|line| line.trim().trim_end_matches(',').to_string())
470 .collect(),
471 )
472}
473
474/// The picture type of every frame of the video stream, in decode order:
475/// `I`, `P` or `B`, as the bitstream says (`ffprobe -show_frames`).
476fn pict_types(path: &Path) -> Option<Vec<String>> {
477 ffprobe_lines(
478 path,
479 &[
480 "-select_streams",
481 "v:0",
482 "-show_frames",
483 "-show_entries",
484 "frame=pict_type",
485 "-of",
486 "csv=p=0",
487 ],
488 )
489}
490
491/// The number of frames ffprobe reads out of the video stream.
492fn frame_count(path: &Path) -> Option<usize> {
493 ffprobe_lines(
494 path,
495 &[
496 "-select_streams",
497 "v:0",
498 "-count_frames",
499 "-show_entries",
500 "stream=nb_read_frames",
501 "-of",
502 "csv=p=0",
503 ],
504 )?
505 .first()?
506 .parse()
507 .ok()
508}
509
510/// The container's duration in seconds, as ffprobe reads it.
511fn duration_secs(path: &Path) -> Option<f64> {
512 ffprobe_lines(
513 path,
514 &["-show_entries", "format=duration", "-of", "csv=p=0"],
515 )?
516 .first()?
517 .parse()
518 .ok()
519}
520
521/// Asserts that ffmpeg decodes the whole file with nothing on its error channel.
522fn assert_decodes_clean(path: &Path, what: &str) {
523 let decoded = Command::new("ffmpeg")
524 .args(["-v", "error", "-i"])
525 .arg(path)
526 .args(["-f", "null", "-"])
527 .output()
528 .expect("run ffmpeg");
529 let complaints = String::from_utf8_lossy(&decoded.stderr);
530 assert!(
531 decoded.status.success() && complaints.is_empty(),
532 "{what}: ffmpeg complained: {complaints}"
533 );
534}
535
536/// The 720p source and the default I+P export of it, made once for the three
537/// tests that read them. Both are `Scratch`es, and a static is never dropped, so
538/// the directories outlive the run and the next run's orphan reap takes them.
539/// No test removes either one: the tests only read them.
540struct SharedGop {
541 source: Scratch,
542 out: Scratch,
543}
544
545/// [`fixture_720p_2s`] and its default I+P export, computed on first use by
546/// whichever of the three tests gets there first; the `OnceLock` has the others
547/// wait for it. `None` where ffmpeg is not installed.
548fn shared_gop() -> Option<&'static SharedGop> {
549 static GOP: OnceLock<Option<SharedGop>> = OnceLock::new();
550 GOP.get_or_init(|| {
551 let source = fixture_720p_2s()?;
552 let session = PlaybackSession::open(&source).expect("open the 720p fixture");
553 let out = out_path("gop_shared", "mp4");
554 export(&session, &out, Format::HevcMp4);
555 Some(SharedGop { source, out })
556 })
557 .as_ref()
558}
559
560/// The default HEVC export is I+P: an IDR a second, P pictures between them,
561/// and no B pictures. The file decodes in ffmpeg with the source's frame count
562/// and duration, and the pictures are the ones the source holds.
563#[test]
564fn an_hevc_gop_export_codes_p_pictures_and_decodes_at_its_length() {
565 let Some(shared) = shared_gop() else {
566 eprintln!("no ffmpeg: skipping the I+P export test");
567 return;
568 };
569 let SharedGop { source, out } = shared;
570
571 let types = pict_types(&out).expect("ffprobe reads the export");
572 let i = types.iter().filter(|t| *t == "I").count();
573 let p = types.iter().filter(|t| *t == "P").count();
574 assert_eq!(types.len(), 60, "every timeline frame is in the file");
575 assert_eq!(i, 2, "an IDR at each one-second GOP start: {types:?}");
576 assert_eq!(p, 58, "the rest are P pictures: {types:?}");
577 assert_eq!(
578 frame_count(&out),
579 frame_count(&source),
580 "the export has the source's frame count"
581 );
582 let duration = duration_secs(&out).expect("ffprobe reads the duration");
583 assert!(
584 (duration - 2.0).abs() < 0.05,
585 "the export lasts 2 s, not {duration}"
586 );
587 assert_decodes_clean(&out, "an I+P export");
588}
589
590/// The same picture at the same quality, two ways: the default I+P export (QP 28,
591/// the GOP seat's automatic quality) and the intra-only one at QP 28 too. The
592/// intra seat maps a bitrate row through `hevc_qp`, and 14.8 Mb/s at 720p30 maps
593/// to 28, so that row is what puts both seats on one quantiser. The P pictures
594/// are the saving, so the I+P file is well under 0.6 of the intra one, and it
595/// looks like the source about as well (the SSIM check where ffmpeg is installed).
596#[test]
597fn an_hevc_gop_export_is_well_under_the_intra_export_at_the_same_quality() {
598 let Some(shared) = shared_gop() else {
599 eprintln!("no ffmpeg: skipping the I+P size test");
600 return;
601 };
602 let SharedGop { source, out: gop } = shared;
603 let session = PlaybackSession::open(source).expect("open the 720p fixture");
604 let intra = out_path("size_intra", "mp4");
605 export_with(
606 &session,
607 &intra,
608 &ExportSettings {
609 format: Format::HevcMp4,
610 intra_only: true,
611 bitrate: Some(14_800_000),
612 ..Default::default()
613 },
614 );
615
616 assert_eq!(
617 frame_count(&gop),
618 Some(60),
619 "the I+P export has every frame"
620 );
621 assert_eq!(
622 frame_count(&intra),
623 Some(60),
624 "the intra export has every frame"
625 );
626 let intra_types = pict_types(&intra).expect("ffprobe reads the intra export");
627 assert_eq!(
628 intra_types.len(),
629 60,
630 "every frame of the intra export is in it"
631 );
632 assert!(
633 intra_types.iter().all(|t| t == "I"),
634 "an intra-only export is all IDR pictures: {intra_types:?}"
635 );
636 assert_decodes_clean(&intra, "the intra-only export");
637
638 let (gop_bytes, intra_bytes) = (
639 std::fs::metadata(&gop).unwrap().len(),
640 std::fs::metadata(&intra).unwrap().len(),
641 );
642 eprintln!(
643 "720p 2 s, both at QP 28: I+P {gop_bytes} bytes, intra {intra_bytes} bytes ({:.3}x)",
644 gop_bytes as f64 / intra_bytes as f64
645 );
646 assert!(
647 (gop_bytes as f64) < 0.6 * intra_bytes as f64,
648 "I+P is {gop_bytes} bytes against intra {intra_bytes}: not under 0.6x"
649 );
650 if let (Some(gop_ssim), Some(intra_ssim)) = (ssim(&source, &gop), ssim(&source, &intra)) {
651 eprintln!("ssim vs source: I+P {gop_ssim:.4}, intra {intra_ssim:.4}");
652 assert!(
653 gop_ssim > intra_ssim - 0.02,
654 "I+P looks worse than intra: ssim {gop_ssim:.4} against {intra_ssim:.4}"
655 );
656 }
657 std::fs::remove_file(&intra).unwrap();
658}
659
660/// The default I+P export is coded at the GOP seat's own quality (QP 28), not the
661/// intra seat's mapped QP, which clamps to 40 at 1080p30: on 720p testsrc2 it
662/// looks like the source at about 41.5 dB, so 36 dB is the floor. Where ffmpeg is
663/// not installed the test is skipped.
664#[test]
665fn an_hevc_gop_export_at_its_default_quality_is_not_the_clamped_intra_qp() {
666 let Some(shared) = shared_gop() else {
667 eprintln!("no ffmpeg: skipping the I+P quality test");
668 return;
669 };
670 let SharedGop { source, out } = shared;
671 let Some(db) = psnr(source, out) else {
672 eprintln!("ffmpeg measured nothing: skipping the PSNR assertion");
673 return;
674 };
675 eprintln!("720p 2 s testsrc2, default I+P export: PSNR {db:.2} dB");
676 assert!(
677 db >= 36.0,
678 "the default I+P export is {db:.2} dB against the source, under 36 dB"
679 );
680}
681
682/// A target bitrate goes to bitrate control: the file's average lands on it.
683#[test]
684fn an_hevc_gop_export_with_a_bitrate_lands_on_it() {
685 let Some(source) = fixture_720p_2s() else {
686 eprintln!("no ffmpeg: skipping the bitrate test");
687 return;
688 };
689 let session = PlaybackSession::open(&source).expect("open the 720p fixture");
690 let target = 2_000_000_u64;
691 let out = out_path("rate", "mp4");
692 export_with(
693 &session,
694 &out,
695 &ExportSettings {
696 format: Format::HevcMp4,
697 bitrate: Some(target),
698 ..Default::default()
699 },
700 );
701 let duration = duration_secs(&out).expect("ffprobe reads the duration");
702 let achieved = std::fs::metadata(&out).unwrap().len() as f64 * 8.0 / duration;
703 eprintln!("2 Mb/s target: achieved {achieved:.0} b/s");
704 let error = (achieved - target as f64) / target as f64;
705 assert!(
706 error.abs() < 0.15,
707 "achieved {achieved:.0} b/s against {target} b/s ({:+.1}%)",
708 error * 100.0
709 );
710 assert_decodes_clean(&out, "a bitrate-controlled export");
711 let _ = std::fs::remove_file(&source);
712 std::fs::remove_file(&out).unwrap();
713}