forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

hevc_export.rs383 lines, 15.4 KiBHistoryRawDownload
1//! HEVC export: the codec this project could read and not write until OxideAV's
2//! pure-Rust H.265 gave it an encoder -- an **intra-only** one, every frame a
3//! self-contained IDR, which is the only shape of it fast enough to wait for
4//! (the inter modes code 1080p at 0.81 fps across 12 cores; the intra path does
5//! 4.30 fps on the same picture).
6//!
7//! Three things are under test here: that the *containers* say HEVC in the
8//! words their readers expect (this project's own demuxer, and ffprobe where it
9//! is installed); that a picture whose height is not a multiple of the 64-sample
10//! coding tree block -- 1080, the resolution -- comes back out at its own size,
11//! coded padded to 1088 and cropped by the SPS conformance window; and, for the
12//! hardware seat only, that what it codes is the *picture that went in* rather
13//! than a stream that merely decodes. That last one is not a nicety: a seat
14//! whose parameter sets disagree with its coded syntax hands back the right
15//! number of frames and the wrong pixels, and nothing else here would see it.
16//!
17//! ```text
18//! cargo test -p engine --release --test hevc_export -- --test-threads=1
19//! ```
20//!
21//! Release, always: a debug intra encode is minutes a frame. The 1080p twin
22//! needs the `ffmpeg` CLI to make its source and `ffprobe` to read the coded
23//! size back; without them it says so and passes, exactly as the hardware tests
24//! here do.
25
26use std::path::{Path, PathBuf};
27use std::process::Command;
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 let settings = ExportSettings {
48 format,
49 ..Default::default()
50 };
51 let handle = session.export_to_with(out, &settings);
52 let started = Instant::now();
53 while !handle.is_finished() {
54 assert!(
55 started.elapsed() < Duration::from_secs(300),
56 "the export did not finish in 300 s"
57 );
58 std::thread::sleep(Duration::from_millis(20));
59 }
60 handle
61 .result()
62 .expect("an outcome")
63 .expect("an HEVC export");
64 assert_eq!(handle.progress(), 1.0, "finished at full progress");
65}
66
67/// Two frames of the A/V fixture: what is under test is the wiring from the
68/// format to the muxer, not how long an encoder takes.
69fn two_frames() -> PlaybackSession {
70 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
71 assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front");
72 assert!(session.delete_clip(engine::project::Lane::V1, 1));
73 session
74}
75
76/// The container half, in both boxes: an HEVC export is read back as HEVC, at
77/// the size and the count it was written at, with the timeline's sound beside
78/// it. The `hvcC` record this writes is the one `demux` parses -- Matroska in
79/// `CodecPrivate`, mp4 in the sample entry -- so this is where the writer and
80/// the reader either agree or do not.
81#[test]
82fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() {
83 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
84 let session = two_frames();
85 let out = out_path("container", ext);
86 export(&session, &out, format);
87
88 let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export");
89 assert_eq!(meta.codec, Codec::Hevc, "{ext}: an HEVC export is HEVC");
90 assert_eq!((meta.width, meta.height), (1280, 720), "{ext}");
91 assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there");
92 // Every access unit comes back, and every one of them is a sync point:
93 // that is what intra-only means, and it is what makes any frame of the
94 // file a cut point.
95 let mut count = 0;
96 while demuxer.next_access_unit().expect("read").is_some() {
97 count += 1;
98 }
99 assert_eq!(count, 2, "{ext}: every coded picture comes back out");
100 assert_eq!(
101 demuxer.seek_to_sync_at_or_before(1),
102 1,
103 "{ext}: an intra-only file syncs on every frame"
104 );
105
106 // ...and the sound with it, through the reader an import opens it by.
107 let (audio, chunks) = AudioSession::open(&out)
108 .expect("reopen for its sound")
109 .expect("an HEVC export has an audio track");
110 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
111 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
112 eprintln!(
113 "{ext}: {} Hz x{}, rms {rms:.4}, {} bytes",
114 audio.sample_rate,
115 audio.channels,
116 std::fs::metadata(&out).unwrap().len()
117 );
118 assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})");
119 std::fs::remove_file(&out).unwrap();
120 }
121}
122
123/// The %16 half, and the reason the vendored encoder carries a patch at all:
124/// 1080 is not a multiple of the 16-sample CTB, so the picture is coded at
125/// 1920x1088 and the SPS crops it back with a §7.4.3.2.1 conformance window.
126/// ffprobe is what says whether that worked -- it reads the *bitstream*, not
127/// the container's own claim -- and ffmpeg decoding the file without a
128/// complaint is what says the stream is legal.
129#[test]
130fn a_1080p_export_states_1920x1080_through_the_conformance_window() {
131 let Some(source) = fixture_1080p() else {
132 eprintln!("no ffmpeg: skipping the 1080p conformance-window twin");
133 return;
134 };
135 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
136 let mut session = PlaybackSession::open(&source).expect("open the 1080p fixture");
137 assert!(session.cut_at(2.0 / 30.0));
138 assert!(session.delete_clip(engine::project::Lane::V1, 1));
139 let out = out_path("1080p", ext);
140 export(&session, &out, format);
141
142 // The container's own claim first: this project's reader.
143 let (meta, _) = Demuxer::open(&out).expect("reopen the 1080p export");
144 assert_eq!((meta.width, meta.height), (1920, 1080), "{ext}");
145
146 // ...and the coded size, out of the SPS, by a reader that is not ours.
147 let probed = probe(&out);
148 assert_eq!(
149 probed.as_deref(),
150 Some("hevc,1920,1080"),
151 "{ext}: ffprobe reads the cropped size out of the bitstream"
152 );
153 // ...and the whole file decoded, with ffmpeg's own stderr as the test:
154 // a stream a decoder complains about is not an export.
155 let decoded = Command::new("ffmpeg")
156 .args(["-v", "error", "-i"])
157 .arg(&out)
158 .args(["-f", "null", "-"])
159 .output()
160 .expect("run ffmpeg");
161 let complaints = String::from_utf8_lossy(&decoded.stderr);
162 assert!(
163 decoded.status.success() && complaints.is_empty(),
164 "{ext}: ffmpeg complained: {complaints}"
165 );
166 std::fs::remove_file(&out).unwrap();
167 }
168 let _ = std::fs::remove_file(&source);
169}
170
171/// The loop closed where it matters to a user: the file this wrote is opened
172/// again *by edith*, picture and all. HEVC has no software decoder here at all,
173/// so the way back in is the plugin -- which is what makes this the twin that
174/// needs one, and what makes the test above (the containers, read by the
175/// demuxer) the one that does not.
176#[test]
177#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
178fn an_hevc_export_decodes_back_into_pictures_through_edith() {
179 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
180 let session = two_frames();
181 let out = out_path("roundtrip", ext);
182 export(&session, &out, format);
183
184 let (meta, frames) = engine::DecodeSession::open(&out).expect("decode the export");
185 assert_eq!(meta.codec, Codec::Hevc, "{ext}");
186 let frames: Vec<_> = frames.into_iter().collect();
187 assert_eq!(frames.len(), 2, "{ext}: every written frame decodes back");
188 // The picture is the fixture's colour pattern, not black: a conformance
189 // window read wrong would show as a shifted or empty picture.
190 for (i, frame) in frames.iter().enumerate() {
191 assert_eq!((frame.width, frame.height), (1280, 720), "{ext} frame {i}");
192 assert!(
193 frame.bgra.iter().any(|&p| p > 32),
194 "{ext} frame {i} carries picture"
195 );
196 }
197 std::fs::remove_file(&out).unwrap();
198 }
199}
200
201/// The same 1080p picture, coded by the **GPU**, and the test that would have
202/// caught what shipped: the hardware seat's file decoded frame for frame while
203/// every frame of it was a band of noise over flat green, because the parameter
204/// sets promised coding tools the driver was not using. Nothing that counts
205/// frames sees that. Three things do, and all three are asserted here --
206/// ffmpeg's decoder saying *nothing at all* on its error channel, the coded
207/// size still cropping back to 1920x1080, and the picture being the source's
208/// rather than a fill (SSIM against the very frames that went in; a desynced
209/// stream scores about 0.2, this one about 0.98).
210///
211/// `testsrc2` is what makes it bite: 1080p of it splits transform trees deep
212/// enough and pushes the rate controller hard enough to need the syntax the
213/// parameter sets have to declare. The two-frame fixtures above are flat and
214/// pass either way, which is exactly how the defect got through.
215#[test]
216#[ignore = "needs libengine_hw.so and a driver with an HEVC encode entrypoint"]
217fn a_1080p_hardware_export_leaves_a_decoder_with_nothing_to_say() {
218 let Some(source) = fixture_1080p() else {
219 eprintln!("no ffmpeg: skipping the 1080p hardware twin");
220 return;
221 };
222 let session = PlaybackSession::open(&source).expect("open the 1080p fixture");
223 let settings = ExportSettings {
224 format: Format::Hevc,
225 ..Default::default()
226 };
227 let planned = engine::export::planned_video(session.meta(), &settings);
228 assert!(
229 planned.is_some_and(|seat| seat.contains("HW encode")),
230 "this twin is the GPU's, and this box named {planned:?}"
231 );
232
233 let out = out_path("1080p_hw", "mkv");
234 export(&session, &out, Format::Hevc);
235
236 let probed = probe(&out);
237 assert_eq!(
238 probed.as_deref(),
239 Some("hevc,1920,1080"),
240 "ffprobe reads the cropped size out of the bitstream"
241 );
242
243 let decoded = Command::new("ffmpeg")
244 .args(["-v", "error", "-i"])
245 .arg(&out)
246 .args(["-f", "null", "-"])
247 .output()
248 .expect("run ffmpeg");
249 let complaints = String::from_utf8_lossy(&decoded.stderr);
250 assert!(
251 decoded.status.success() && complaints.is_empty(),
252 "a decoder complained about the GPU's stream: {complaints}"
253 );
254
255 let ssim = ssim(&source, &out).expect("ffmpeg reports an SSIM");
256 assert!(
257 ssim >= 0.90,
258 "the GPU coded the source's picture, not a fill (SSIM {ssim:.4})"
259 );
260 std::fs::remove_file(&out).unwrap();
261 let _ = std::fs::remove_file(&source);
262}
263
264/// An audio-only timeline has no picture to code, and an HEVC export says so by
265/// name exactly as the mp4 and AV1 ones do -- and writes nothing.
266#[test]
267fn an_audio_only_timeline_is_refused_an_hevc_export_by_name() {
268 let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone");
269 let out = out_path("refused", "mkv");
270 let settings = ExportSettings {
271 format: Format::Hevc,
272 ..Default::default()
273 };
274 let handle = session.export_to_with(&out, &settings);
275 while !handle.is_finished() {
276 std::thread::sleep(Duration::from_millis(10));
277 }
278 let refused = handle
279 .result()
280 .expect("an outcome")
281 .expect_err("an audio-only timeline has no picture to code")
282 .to_string();
283 assert!(refused.contains("no picture"), "{refused}");
284 assert!(refused.contains("HEVC"), "{refused}");
285 assert!(!out.exists(), "nothing is written for a refusal");
286}
287
288/// A cancelled HEVC export leaves nothing behind -- not the file and not the
289/// `.part` the worker was writing. An intra-only export of a whole fixture is
290/// long enough to catch mid-flight, and the frame loop checks for a cancel
291/// every picture, so this stops in a frame or two rather than at the end.
292#[test]
293fn a_cancelled_hevc_export_leaves_no_file_behind() {
294 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
295 let out = out_path("cancelled", "mkv");
296 let settings = ExportSettings {
297 format: Format::Hevc,
298 ..Default::default()
299 };
300 let handle = session.export_to_with(&out, &settings);
301 handle.cancel();
302 let started = Instant::now();
303 while !handle.is_finished() {
304 assert!(started.elapsed() < Duration::from_secs(60), "cancel hung");
305 std::thread::sleep(Duration::from_millis(20));
306 }
307 let stopped = handle
308 .result()
309 .expect("an outcome")
310 .expect_err("a cancelled export is an error");
311 assert!(stopped.to_string().contains("cancelled"), "{stopped}");
312 assert!(!out.exists(), "no output for a cancelled export");
313 assert!(
314 !PathBuf::from(format!("{}.part", out.display())).exists(),
315 "no partial file either"
316 );
317}
318
319/// `codec,width,height` of the file's video stream as ffprobe reads it, or
320/// `None` where ffprobe is not installed.
321fn probe(path: &Path) -> Option<String> {
322 let out = Command::new("ffprobe")
323 .args([
324 "-v",
325 "error",
326 "-select_streams",
327 "v:0",
328 "-show_entries",
329 "stream=codec_name,width,height",
330 "-of",
331 "csv=p=0",
332 ])
333 .arg(path)
334 .output()
335 .ok()?;
336 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
337}
338
339/// Mean SSIM of `out` against `source`, over the frames the two have in common,
340/// as ffmpeg's own filter measures it. `None` where ffmpeg is not installed or
341/// said nothing -- the caller decides whether that is a skip or a failure.
342fn ssim(source: &Path, out: &Path) -> Option<f64> {
343 let measured = Command::new("ffmpeg")
344 .args(["-v", "info", "-i"])
345 .arg(source)
346 .arg("-i")
347 .arg(out)
348 .args(["-filter_complex", "ssim", "-f", "null", "-"])
349 .output()
350 .ok()?;
351 String::from_utf8_lossy(&measured.stderr)
352 .rsplit("All:")
353 .next()?
354 .split_whitespace()
355 .next()?
356 .parse()
357 .ok()
358}
359
360/// A two-second 1920x1080 H.264 fixture in the temp directory -- the assets are
361/// all 720p, which is a multiple of 16 in both directions and would leave the
362/// crop path untested. `None` where ffmpeg is not installed.
363fn fixture_1080p() -> Option<Scratch> {
364 let path = out_path("source1080", "mp4");
365 let made = Command::new("ffmpeg")
366 .args([
367 "-y",
368 "-f",
369 "lavfi",
370 "-i",
371 "testsrc2=size=1920x1080:rate=30:duration=1",
372 "-c:v",
373 "libx264",
374 "-profile:v",
375 "baseline",
376 "-pix_fmt",
377 "yuv420p",
378 ])
379 .arg(&path)
380 .output()
381 .ok()?;
382 made.status.success().then_some(path)
383}