forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hevc10_export.rs389 lines, 18.1 KiBHistoryRawDownload
1//! HEVC Main 10 with HDR signalling (`ExportSettings::hdr`): a PQ or HLG export
2//! of a PQ or HLG source is Main 10, `yuv420p10le`, tagged BT.2020 with the
3//! right transfer in the stream and in the container (mp4 `colr`, Matroska
4//! `Colour`), carries the mastering display and content light SEIs, and decodes
5//! back within a PSNR floor of the source with *no* tone map in between. The
6//! refusals (HDR in 8 bits, HDR in H.264, one HDR curve into the other) are by
7//! name. And an export that asks for none of it is the file it always was: the
8//! default exports' bytes are pinned by hash.
9//!
10//! Sources are synthetic (ffmpeg `testsrc2`). Without ffmpeg and a 10-bit source
11//! encoder the tests say so and pass.
12//!
13//! ```text
14//! cargo test -p engine --release --test hevc10_export -- --nocapture
15//! ```
16
17use std::path::{Path, PathBuf};
18use std::process::Command;
19use std::time::{Duration, Instant};
20
21use engine::PlaybackSession;
22use engine::export::{ExportSettings, Format, HdrOutput, HdrTransfer, MasteringDisplay};
23
24use crate::seat;
25
26const WIDTH: u32 = 320;
27const HEIGHT: u32 = 240;
28const FPS: u32 = 25;
29
30fn scratch(name: &str) -> PathBuf {
31 let dir = std::env::temp_dir().join(format!("edith-{name}-{}", std::process::id()));
32 let _ = std::fs::remove_dir_all(&dir);
33 std::fs::create_dir_all(&dir).expect("scratch directory");
34 dir
35}
36
37fn have(tool: &str) -> bool {
38 Command::new(tool).arg("-version").output().is_ok_and(|o| o.status.success())
39}
40
41fn source_encoder() -> Option<&'static str> {
42 let out = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output().ok()?;
43 let list = String::from_utf8_lossy(&out.stdout);
44 if list.contains("libx265") {
45 Some("libx265")
46 } else if list.contains("libaom-av1") {
47 Some("libaom-av1")
48 } else {
49 None
50 }
51}
52
53fn codec_args(encoder: &str) -> Vec<&str> {
54 match encoder {
55 "libx265" => vec!["-c:v", "libx265", "-preset", "ultrafast", "-x265-params", "log-level=error"],
56 _ => vec!["-c:v", "libaom-av1", "-cpu-used", "8", "-crf", "30", "-b:v", "0"],
57 }
58}
59
60/// A 1-second `testsrc2` at `pix_fmt` in Matroska, tagged BT.2020 with `trc`
61/// (`smpte2084`, `arib-std-b67`) where one is given.
62fn make_source(out: &Path, pix_fmt: &str, trc: Option<&str>, codec: &[&str]) -> bool {
63 let mut cmd = Command::new("ffmpeg");
64 cmd.args(["-v", "error", "-y", "-f", "lavfi", "-i"])
65 .arg(format!("testsrc2=size={WIDTH}x{HEIGHT}:rate={FPS}:duration=1"))
66 .args(["-pix_fmt", pix_fmt])
67 .args(codec);
68 if let Some(trc) = trc {
69 // The frame properties as well as the encoder's flags: a filter graph's
70 // unspecified frames would otherwise override the flags.
71 cmd.args(["-vf", &format!("setparams=colorspace=bt2020nc:color_primaries=bt2020:color_trc={trc}:range=tv")]);
72 cmd.args(["-colorspace", "bt2020nc", "-color_primaries", "bt2020", "-color_trc", trc, "-color_range", "tv"]);
73 }
74 matches!(cmd.arg(out).status(), Ok(s) if s.success())
75}
76
77fn probe(path: &Path, field: &str) -> String {
78 let out = Command::new("ffprobe")
79 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
80 .arg(format!("stream={field}"))
81 .args(["-of", "csv=p=0"])
82 .arg(path)
83 .output()
84 .expect("ffprobe runs");
85 assert!(out.status.success(), "ffprobe reads {}", path.display());
86 // The container's static metadata is side data, which csv prints after the field.
87 let text = String::from_utf8_lossy(&out.stdout).into_owned();
88 text.lines().next().unwrap_or("").trim_end_matches(',').to_owned()
89}
90
91/// ffprobe's first-frame side data, as text.
92fn first_frame_side_data(path: &Path) -> String {
93 let out = Command::new("ffprobe")
94 .args(["-v", "error", "-select_streams", "v:0", "-read_intervals", "%+#1", "-show_frames"])
95 .arg(path)
96 .output()
97 .expect("ffprobe runs");
98 String::from_utf8_lossy(&out.stdout).into_owned()
99}
100
101fn decoded(path: &Path) -> Vec<u8> {
102 let out = Command::new("ffmpeg")
103 .args(["-v", "error", "-i"])
104 .arg(path)
105 .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"])
106 .output()
107 .expect("ffmpeg runs");
108 assert!(out.status.success(), "ffmpeg decodes {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));
109 out.stdout
110}
111
112fn psnr_10(a: &[u8], b: &[u8]) -> f64 {
113 assert_eq!(a.len(), b.len(), "the same number of samples");
114 let mut squared = 0f64;
115 for (x, y) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) {
116 let d = f64::from(u16::from_le_bytes(*x)) - f64::from(u16::from_le_bytes(*y));
117 squared += d * d;
118 }
119 if squared == 0.0 {
120 return f64::INFINITY;
121 }
122 10.0 * (1023.0f64 * 1023.0 * (a.len() / 2) as f64 / squared).log10()
123}
124
125fn run(source: &Path, out: &Path, settings: &ExportSettings) -> Result<(), String> {
126 let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display()));
127 let handle = session.export_to_with(out, settings);
128 let started = Instant::now();
129 while !handle.is_finished() {
130 assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
131 std::thread::sleep(Duration::from_millis(20));
132 }
133 handle.result().expect("an outcome").map_err(|e| e.to_string())
134}
135
136fn hdr(transfer: HdrTransfer) -> HdrOutput {
137 HdrOutput {
138 transfer,
139 mastering_display: Some(MasteringDisplay::p3_d65(1000.0, 0.005)),
140 max_cll: Some(900),
141 max_fall: Some(300),
142 }
143}
144
145#[test]
146fn pq_and_hlg_exports_are_main_10_bt2020_and_decode_back() {
147 let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else {
148 eprintln!("no ffmpeg with a 10-bit source encoder: skipping the HDR export test");
149 return;
150 };
151 let _seat = seat::software();
152 let dir = scratch("hevc10-hdr");
153 let frame_bytes = (WIDTH * HEIGHT * 3 / 2 * 2) as usize;
154 for (transfer, trc, tag) in [(HdrTransfer::Pq, "smpte2084", "smpte2084"), (HdrTransfer::Hlg, "arib-std-b67", "arib-std-b67")] {
155 let source = dir.join(format!("source-{tag}.mkv"));
156 assert!(make_source(&source, "yuv420p10le", Some(trc), &codec_args(encoder)), "ffmpeg makes the HDR source");
157 assert_eq!(probe(&source, "color_transfer"), tag, "the source is tagged {tag}");
158 let reference = decoded(&source);
159 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
160 let out = dir.join(format!("{tag}.{ext}"));
161 let settings = ExportSettings { format, hdr: hdr(transfer), ..Default::default() };
162 run(&source, &out, &settings).unwrap_or_else(|e| panic!("{tag} {ext}: {e}"));
163
164 assert_eq!(probe(&out, "profile"), "Main 10", "{tag} {ext}");
165 assert_eq!(probe(&out, "pix_fmt"), "yuv420p10le", "{tag} {ext}");
166 assert_eq!(probe(&out, "color_transfer"), tag, "{tag} {ext}: transfer");
167 assert_eq!(probe(&out, "color_primaries"), "bt2020", "{tag} {ext}: primaries");
168 assert_eq!(probe(&out, "color_space"), "bt2020nc", "{tag} {ext}: matrix");
169 assert_eq!(probe(&out, "color_range"), "tv", "{tag} {ext}: range");
170 // The bitstream says top-left (type 2); an mp4 reads it from there. A
171 // Matroska reader answers for the container, which states no siting.
172 if ext == "mp4" {
173 assert_eq!(probe(&out, "chroma_location"), "topleft", "{tag} {ext}: chroma location");
174 }
175 let side = first_frame_side_data(&out);
176 assert!(side.contains("Mastering display metadata"), "{tag} {ext}: mastering display SEI\n{side}");
177 assert!(side.contains("Content light level metadata"), "{tag} {ext}: content light SEI");
178 assert!(side.contains("max_content=900") && side.contains("max_average=300"), "{tag} {ext}: MaxCLL/MaxFALL");
179
180 let back = decoded(&out);
181 assert_eq!(back.len(), reference.len(), "{tag} {ext}: every picture reads back");
182 assert!(back.len() / frame_bytes >= FPS as usize - 1);
183 let psnr = psnr_10(&reference, &back);
184 eprintln!("{tag} {ext}: {psnr:.2} dB against the HDR source");
185 // No tone map and no matrix remap: the 10-bit pictures pass through untouched.
186 assert!(psnr > 30.0, "{tag} {ext}: {psnr:.2} dB against the source");
187 }
188 }
189 let _ = std::fs::remove_dir_all(&dir);
190}
191
192#[test]
193fn an_sdr_source_can_be_tagged_hdr_and_hdr_without_the_extras_has_no_sei() {
194 let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else {
195 eprintln!("no ffmpeg with a 10-bit source encoder: skipping");
196 return;
197 };
198 let _seat = seat::software();
199 let dir = scratch("hevc10-sdr-as-hdr");
200 let source = dir.join("sdr.mkv");
201 assert!(make_source(&source, "yuv420p", None, &codec_args(encoder)));
202 let out = dir.join("sdr-as-pq.mp4");
203 let settings = ExportSettings {
204 format: Format::HevcMp4,
205 hdr: HdrOutput { transfer: HdrTransfer::Pq, ..Default::default() },
206 ..Default::default()
207 };
208 run(&source, &out, &settings).expect("an SDR source exports tagged PQ: a user choice");
209 assert_eq!(probe(&out, "profile"), "Main 10", "HDR is 10-bit even from 8-bit pictures");
210 assert_eq!(probe(&out, "color_transfer"), "smpte2084");
211 assert_eq!(probe(&out, "color_primaries"), "bt2020");
212 let side = first_frame_side_data(&out);
213 assert!(!side.contains("Mastering display metadata"), "no mastering display SEI unless asked");
214 assert!(!side.contains("Content light level metadata"), "no content light SEI unless asked");
215 let _ = std::fs::remove_dir_all(&dir);
216}
217
218#[test]
219fn hdr_that_cannot_be_written_is_refused_by_name() {
220 let (Some(encoder), true) = (source_encoder(), have("ffmpeg")) else {
221 eprintln!("no ffmpeg with a 10-bit source encoder: skipping");
222 return;
223 };
224 let _seat = seat::software();
225 let dir = scratch("hevc10-refusals");
226 let source = dir.join("pq.mkv");
227 assert!(make_source(&source, "yuv420p10le", Some("smpte2084"), &codec_args(encoder)));
228 let out = dir.join("refused.mp4");
229
230 let eight = ExportSettings { format: Format::HevcMp4, hdr: hdr(HdrTransfer::Pq), video_bit_depth: Some(8), ..Default::default() };
231 let why = run(&source, &out, &eight).expect_err("HDR in 8 bits");
232 assert!(why.contains("10-bit"), "{why}");
233
234 let h264 = ExportSettings { format: Format::Mp4, hdr: hdr(HdrTransfer::Pq), ..Default::default() };
235 let why = run(&source, &out, &h264).expect_err("HDR in H.264");
236 assert!(why.contains("only HEVC"), "{why}");
237
238 let curve = ExportSettings { format: Format::HevcMp4, hdr: hdr(HdrTransfer::Hlg), ..Default::default() };
239 let why = run(&source, &out, &curve).expect_err("PQ source into an HLG export");
240 assert!(why.contains("PQ") && why.contains("HLG"), "{why}");
241
242 let stray = ExportSettings {
243 format: Format::HevcMp4,
244 hdr: HdrOutput { max_cll: Some(1000), ..Default::default() },
245 ..Default::default()
246 };
247 let why = run(&source, &out, &stray).expect_err("light levels without an HDR transfer");
248 assert!(why.contains("HDR transfer"), "{why}");
249 assert!(!out.exists(), "a refused export leaves no file");
250 let _ = std::fs::remove_dir_all(&dir);
251}
252
253/// ffprobe's `-show_streams` text of the video stream (container-level side data).
254fn stream_side_data(path: &Path) -> String {
255 let out = Command::new("ffprobe")
256 .args(["-v", "error", "-select_streams", "v:0", "-show_streams"])
257 .arg(path)
258 .output()
259 .expect("ffprobe runs");
260 String::from_utf8_lossy(&out.stdout).into_owned()
261}
262
263#[test]
264fn hdr_static_metadata_is_in_the_container_as_well_as_the_sei() {
265 let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else {
266 eprintln!("no ffmpeg with a 10-bit source encoder: skipping the container HDR test");
267 return;
268 };
269 let _seat = seat::software();
270 let dir = scratch("hevc10-container-hdr");
271 let source = dir.join("source.mkv");
272 assert!(make_source(&source, "yuv420p10le", Some("smpte2084"), &codec_args(encoder)), "ffmpeg makes the HDR source");
273 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
274 let out = dir.join(format!("hdr.{ext}"));
275 run(&source, &out, &ExportSettings { format, hdr: hdr(HdrTransfer::Pq), ..Default::default() })
276 .unwrap_or_else(|e| panic!("{ext}: {e}"));
277 let streams = stream_side_data(&out);
278 let frames = first_frame_side_data(&out);
279 for (what, text) in [("show_streams", &streams), ("show_frames", &frames)] {
280 assert!(text.contains("Mastering display metadata"), "{ext} {what}: mastering display");
281 assert!(text.contains("Content light level metadata"), "{ext} {what}: content light");
282 assert!(text.contains("max_content=900") && text.contains("max_average=300"), "{ext} {what}: MaxCLL/FALL");
283 // P3 D65 at 1000 / 0.005 nits (red 0.68,0.32 green 0.265,0.69 blue 0.15,0.06
284 // white 0.3127,0.329). ffprobe prints a Matroska's floats as reduced rationals, an mp4's boxes and
285 // the SEI's as the bitstream codes them (0.00002 and 0.0001 steps).
286 let want: [&str; 10] = if what == "show_streams" && ext == "mkv" {
287 [
288 "red_x=17/25", "red_y=8/25", "green_x=53/200", "green_y=69/100", "blue_x=3/20", "blue_y=3/50",
289 "white_point_x=3127/10000", "white_point_y=329/1000", "min_luminance=1/200", "max_luminance=1000/1",
290 ]
291 } else {
292 [
293 "red_x=34000/50000", "red_y=16000/50000", "green_x=13250/50000", "green_y=34500/50000",
294 "blue_x=7500/50000", "blue_y=3000/50000", "white_point_x=15635/50000", "white_point_y=16450/50000",
295 "min_luminance=50/10000", "max_luminance=10000000/10000",
296 ]
297 };
298 for v in want {
299 assert!(text.contains(v), "{ext} {what}: {v}\n{text}");
300 }
301 }
302 }
303 // Not HDR: nothing new in the container.
304 let sdr = dir.join("sdr.mp4");
305 let sdr_source = dir.join("sdr-source.mkv");
306 assert!(make_source(&sdr_source, "yuv420p10le", None, &codec_args(encoder)));
307 run(&sdr_source, &sdr, &ExportSettings { format: Format::HevcMp4, video_bit_depth: Some(10), ..Default::default() }).expect("sdr");
308 let text = stream_side_data(&sdr);
309 assert!(!text.contains("Mastering display") && !text.contains("Content light"), "sdr stream:\n{text}");
310 let _ = std::fs::remove_dir_all(&dir);
311}
312
313/// Planar 4:2:0 PSNR of two byte streams of `bytes_per_sample`-wide samples.
314fn psnr_planar(a: &[u8], b: &[u8], ten: bool) -> f64 {
315 if ten {
316 return psnr_10(a, b);
317 }
318 assert_eq!(a.len(), b.len(), "the same number of samples");
319 let squared: f64 = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(*y)).powi(2)).sum();
320 if squared == 0.0 {
321 return f64::INFINITY;
322 }
323 10.0 * (255.0f64 * 255.0 * a.len() as f64 / squared).log10()
324}
325
326fn frame_count(path: &Path) -> usize {
327 let out = Command::new("ffprobe")
328 .args(["-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"])
329 .arg(path)
330 .output()
331 .expect("ffprobe runs");
332 String::from_utf8_lossy(&out.stdout).trim().trim_end_matches(',').parse().expect("a packet count")
333}
334
335fn decoded_as(path: &Path, pix_fmt: &str) -> Vec<u8> {
336 let out = Command::new("ffmpeg")
337 .args(["-v", "error", "-i"])
338 .arg(path)
339 .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
340 .output()
341 .expect("ffmpeg runs");
342 assert!(out.status.success(), "ffmpeg decodes {}", path.display());
343 out.stdout
344}
345
346/// The speed presets (`ExportSettings::hevc_speed`) write streams that decode: the same
347/// number of pictures as the default export, at a PSNR close to its, in 8 and 10 bits.
348#[test]
349fn hevc_speed_presets_decode_close_to_the_default() {
350 use engine::export::HevcSpeed;
351 let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else {
352 eprintln!("no ffmpeg with a source encoder: skipping the HEVC speed test");
353 return;
354 };
355 let _seat = seat::software();
356 let dir = scratch("hevc-speed");
357 for (pix_fmt, ten) in [("yuv420p", false), ("yuv420p10le", true)] {
358 let source = dir.join(format!("source-{pix_fmt}.mkv"));
359 assert!(make_source(&source, pix_fmt, None, &codec_args(encoder)), "ffmpeg makes the source");
360 let reference = decoded_as(&source, pix_fmt);
361 let mut base: Option<(f64, usize)> = None;
362 for (name, speed) in [("default", None), ("fast", Some(HevcSpeed::Fast)), ("faster", Some(HevcSpeed::Faster))] {
363 let out = dir.join(format!("{pix_fmt}-{name}.mkv"));
364 let settings = ExportSettings {
365 format: Format::Hevc,
366 video_bit_depth: Some(if ten { 10 } else { 8 }),
367 hevc_speed: speed,
368 ..Default::default()
369 };
370 run(&source, &out, &settings).unwrap_or_else(|e| panic!("{pix_fmt} {name}: {e}"));
371 assert_eq!(probe(&out, "pix_fmt"), pix_fmt, "{pix_fmt} {name}");
372 let back = decoded_as(&out, pix_fmt);
373 assert_eq!(back.len(), reference.len(), "{pix_fmt} {name}: every picture reads back");
374 let frames = frame_count(&out);
375 let psnr = psnr_planar(&reference, &back, ten);
376 eprintln!("{pix_fmt} {name}: {frames} frames, {psnr:.2} dB");
377 assert!(psnr > 25.0, "{pix_fmt} {name}: {psnr:.2} dB");
378 match base {
379 None => base = Some((psnr, frames)),
380 Some((p0, f0)) => {
381 assert_eq!(frames, f0, "{pix_fmt} {name}: the frame count of the default");
382 let slack = if speed == Some(HevcSpeed::Fast) { 1.0 } else { 3.0 };
383 assert!(p0 - psnr < slack, "{pix_fmt} {name}: {psnr:.2} dB against the default's {p0:.2}");
384 }
385 }
386 }
387 }
388 let _ = std::fs::remove_dir_all(&dir);
389}