forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

vp9.rs428 lines, 18.4 KiBHistoryRawDownload
1//! VP9 import: the first source codec that is not H.264.
2//!
3//! The container and refusal checks need nothing installed. The software seat
4//! (`ec-vp9`, `VE_SW` pinned) runs unignored; its fixtures are encoded by
5//! ffmpeg's `libvpx-vp9` at test time, and its reference is ffmpeg's libvpx
6//! decode, so those tests skip where ffmpeg has no libvpx. The hardware decode
7//! and export twins need a built `libengine_hw.so` and a VA-API driver with a
8//! VP9 decode entrypoint (`vainfo | grep VP9`), so they are `#[ignore]`d:
9//!
10//! ```text
11//! cargo build -p engine -p engine-hw --release
12//! LD_LIBRARY_PATH=target/release \
13//! cargo test -p engine --release --test vp9 -- --include-ignored --nocapture --test-threads=1
14//! ```
15//!
16//! `VE_SW` is process-wide: every test that pins a seat takes it through
17//! `support/seat.rs`, so the software and hardware tests here never see each
18//! other's pin, with or without `--test-threads=1`.
19
20use crate::seat;
21
22use std::path::{Path, PathBuf};
23use std::process::Command;
24use std::time::{Duration, Instant};
25
26use ec_vp9::decode::{Decoder, Picture};
27use engine::colorspace::Chroma;
28use engine::demux::{Codec, Demuxer};
29use engine::export::ExportSettings;
30use engine::scratch::Scratch;
31use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
32
33/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
34const FRAMES: u32 = 60;
35
36fn asset(name: &str) -> PathBuf {
37 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
38 .join("../../assets")
39 .join(name)
40}
41
42/// `VE_SW` is process-wide, so every test here that sets it or reads a decode
43/// that depends on it takes this pin: parallel tests then see each other's
44/// `VE_SW` only when they hold it, and a poisoned lock still serialises.
45static ENV_PIN: std::sync::Mutex<()> = std::sync::Mutex::new(());
46
47fn env_pin() -> std::sync::MutexGuard<'static, ()> {
48 ENV_PIN.lock().unwrap_or_else(|e| e.into_inner())
49}
50
51/// The container half: a vp09 track is found, described and named as VP9, and
52/// its AAC track is read exactly as any other file's -- the audio path knows
53/// nothing about the video codec and this is what says so.
54#[test]
55fn the_demuxer_reports_a_vp9_track() {
56 let _pin = env_pin();
57 let (meta, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
58 assert_eq!(meta.codec, Codec::Vp9);
59 assert_eq!((meta.width, meta.height), (1280, 720));
60 assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
61 assert_eq!(meta.frame_count, FRAMES);
62
63 let probe = AudioSession::probe(asset("test_vp9.mp4"), 0)
64 .expect("probe")
65 .expect("the fixture has an AAC track");
66 assert_eq!(
67 (probe.sample_rate, probe.channels),
68 (44_100, 2),
69 "audio is read the same whatever the picture is coded with"
70 );
71
72 // The invariant, stated as an assert: H.264 files still say H.264.
73 let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
74 assert_eq!(h264.codec, Codec::H264);
75}
76
77/// The software seat takes VP9 now: with the plugin forced off, the stream
78/// opens on `ec-vp9` in this process. H.264 is untouched by the same pin.
79#[test]
80fn the_software_path_opens_vp9() {
81 let _seat = seat::software();
82 let opened = DecodeSession::open(asset("test_vp9.mp4")).is_ok();
83 let h264 = DecodeSession::open(asset("test_baseline.mp4")).is_ok();
84 assert!(opened, "software VP9 decode opens");
85 assert!(h264, "software H.264 decode still opens");
86}
87
88/// A 4:4:4 HEVC clip, which no seat takes, encoded by ffmpeg's libx265 into the
89/// temp dir: 3 frames of 64x64. `assets/` is gitignored, so the clip is made here.
90fn hevc_444_clip() -> PathBuf {
91 let path = std::env::temp_dir().join(format!("vp9-hevc444-{}.mp4", std::process::id()));
92 let out = Command::new("ffmpeg")
93 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
94 .arg("testsrc2=size=64x64:rate=30:duration=0.1")
95 .args(["-frames:v", "3", "-c:v", "libx265", "-pix_fmt", "yuv444p"])
96 .args(["-x265-params", "log-level=error"])
97 .arg(&path)
98 .output()
99 .expect("ffmpeg runs");
100 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
101 // Mark it profile 5 (high throughput), which ec-h265 does not decode.
102 let mut bytes = std::fs::read(&path).expect("read the clip");
103 let at = bytes.windows(4).position(|w| w == b"hvcC").expect("an hvcC box");
104 bytes[at + 5] = (bytes[at + 5] & 0xe0) | 5;
105 std::fs::write(&path, bytes).expect("write the patched clip");
106 path
107}
108
109/// A timeline is *not* refused a source coded differently -- every clip opens
110/// its own decoder. With the plugin forced off, VP9 joins the timeline on
111/// `ec-vp9` and HEVC on `ec-h265`; 4:4:4 HEVC is no seat's, so it is refused at
112/// the door by the decoder's own name.
113#[test]
114fn a_timeline_takes_the_other_codec_or_names_the_refusal() {
115 let _seat = seat::software();
116 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
117 let clip = hevc_444_clip();
118 let refused = session
119 .import(&clip)
120 .expect_err("profile 5 HEVC is no seat's to decode")
121 .to_string();
122 let _ = std::fs::remove_file(&clip);
123 assert!(refused.contains("profile 5"), "{refused}");
124 assert_eq!(session.sources().len(), 1, "a refusal left no row");
125 session
126 .import(&asset("test_vp9.mp4"))
127 .expect("the software VP9 seat takes the clip beside H.264");
128 session
129 .import(&asset("test_hevc.mp4"))
130 .expect("the software HEVC seat takes the clip beside H.264");
131 assert_eq!(session.sources().len(), 3, "VP9 and HEVC beside H.264");
132}
133
134/// The refusal *at a span*, which is where it happens now: playback opens its
135/// files on the worker (`DecodeSession::open_worker_deferred`), so a clip no
136/// decoder here can take is refused there rather than on the caller's thread.
137/// What must survive that move is the behaviour a refused span always had --
138/// no pictures from that clip, and the session walks on to the end instead of
139/// stalling on it.
140///
141/// The clip is imported as H.264, because the *door* still refuses what it
142/// cannot open; the bytes under it become 4:4:4 HEVC afterwards, which is the only
143/// way to put a span the worker must refuse on a timeline. (4:4:4 HEVC, not
144/// HEVC: `ec-h265` has a software seat now and would decode 4:2:0 HEVC, and 4:2:2.)
145#[test]
146fn a_refused_codec_at_a_span_advances_instead_of_stalling() {
147 let _seat = seat::software();
148 let scratch = Scratch::file("video_editor_vp9_span", "mp4");
149 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
150 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
151 session.set_gain(0.0);
152 let first = session.meta().frame_count;
153 session.import(&scratch).expect("an H.264 file joins this timeline");
154 let end = session.timeline_duration();
155 assert!(
156 session
157 .place_stream_at(end, &scratch, 0, None)
158 .expect("a file just imported is on this timeline")
159 );
160 let refused_clip = hevc_444_clip();
161 std::fs::copy(&refused_clip, &scratch).expect("swap in the 4:4:4 HEVC bytes");
162 let _ = std::fs::remove_file(&refused_clip);
163
164 session.seek(0.0);
165 session.play();
166 let deadline = Instant::now() + Duration::from_secs(20);
167 let (mut count, mut last) = (0u32, None);
168 while !session.is_eos() {
169 session.tick();
170 while let Some(frame) = session.try_frame() {
171 count += 1;
172 last = Some(frame.index);
173 }
174 assert!(Instant::now() < deadline, "the refused span stalled playback");
175 std::thread::sleep(Duration::from_millis(4));
176 }
177
178 assert_eq!(last, Some(first - 1), "the refused clip made pictures");
179 assert_eq!(count, first, "the first source still played whole");
180 let _ = std::fs::remove_file(&scratch);
181}
182
183/// The end-to-end user path: opening the file yields pictures, all of them,
184/// through the plugin.
185#[test]
186#[ignore = "needs libengine_hw.so and a VA-API driver with VP9 decode"]
187fn the_plugin_decodes_every_vp9_frame() {
188 let _seat = seat::hardware();
189 let start = Instant::now();
190 let (meta, frames) = DecodeSession::open(asset("test_vp9.mp4")).expect("open test_vp9.mp4");
191 assert_eq!(meta.codec, Codec::Vp9);
192 let frames: Vec<_> = frames.into_iter().collect();
193 eprintln!(
194 "test_vp9.mp4: {} frames in {:?}",
195 frames.len(),
196 start.elapsed()
197 );
198
199 assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
200 for (i, frame) in frames.iter().enumerate() {
201 assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
202 assert_eq!(frame.index, i as u32, "frames arrive in display order");
203 assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
204 }
205 // A picture, not a flat surface: a driver handing back an untouched buffer
206 // would satisfy every count above.
207 let first = &frames[0].bgra;
208 assert!(
209 first.as_chunks::<4>().0.iter().any(|px| px != &first[..4]),
210 "frame 0 is a single colour -- no picture was decoded"
211 );
212}
213
214/// Export re-encodes to H.264 whatever the source was coded with: the packet
215/// copy path is audio-only, so no VP9 byte can reach an `avc1` track.
216#[test]
217#[ignore = "needs libengine_hw.so and a VA-API driver with VP9 decode"]
218fn a_vp9_source_exports_as_h264() {
219 let _seat = seat::hardware();
220 let session = PlaybackSession::open(asset("test_vp9.mp4")).expect("open test_vp9.mp4");
221 let meta = *session.meta();
222 let project = Project::single(asset("test_vp9.mp4"), meta.frame_count);
223 let out = Scratch::file("ve_export_vp9", "mp4");
224
225 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
226 let started = Instant::now();
227 while !handle.is_finished() {
228 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
229 std::thread::sleep(Duration::from_millis(20));
230 }
231 handle.result().expect("outcome").expect("export");
232
233 let (written, _) = Demuxer::open(&out).expect("reopen the export");
234 assert_eq!(written.codec, Codec::H264, "exports are always H.264");
235 assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
236 assert_eq!((written.width, written.height), (1280, 720));
237 let _ = std::fs::remove_file(&out);
238}
239
240// --- the software seat -----------------------------------------------------
241//
242// `ec-vp9` against ffmpeg's `libvpx-vp9` decode, sample for sample. The clips
243// are encoded by the same libvpx at test time: 24 frames of 352x288, a keyframe
244// every 8, so seeks have several sync points to land on.
245
246const SW_FRAMES: u32 = 24;
247const SW_KEYFRAME: u32 = 8;
248
249/// A WebM encoded by ffmpeg's libvpx at test time. `None` where ffmpeg with
250/// `libvpx-vp9` is not installed -- the skip the other ffmpeg witnesses take.
251fn ffmpeg_vp9(name: &str, profile: u8, pix_fmt: &str) -> Option<Scratch> {
252 let out = Scratch::file(name, "webm");
253 let status = Command::new("ffmpeg")
254 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
255 .arg("testsrc2=size=352x288:rate=30")
256 .args(["-frames:v", "24", "-c:v", "libvpx-vp9", "-profile:v"])
257 .arg(profile.to_string())
258 .args(["-pix_fmt", pix_fmt, "-g", "8", "-b:v", "400k", "-deadline", "good"])
259 .args(["-cpu-used", "4", "-auto-alt-ref", "1"])
260 .arg(&out)
261 .status()
262 .ok()?;
263 status.success().then_some(out)
264}
265
266/// Every picture ffmpeg's libvpx decoder releases, as raw planes of 16-bit
267/// samples (8-bit output is widened, so one comparison serves both depths).
268fn ffmpeg_libvpx_planes(path: &Path, pix_fmt: &str, bytes_per_sample: usize) -> Vec<[Vec<u16>; 3]> {
269 let out = Command::new("ffmpeg")
270 .args(["-v", "error", "-c:v", "libvpx-vp9", "-i"])
271 .arg(path)
272 .args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
273 .output()
274 .expect("run ffmpeg");
275 assert!(
276 out.status.success(),
277 "ffmpeg (libvpx-vp9) failed: {}",
278 String::from_utf8_lossy(&out.stderr)
279 );
280 let (w, h) = (352usize, 288usize);
281 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
282 let frame = (w * h + 2 * cw * ch) * bytes_per_sample;
283 assert_eq!(out.stdout.len() % frame, 0, "ffmpeg handed back a partial frame");
284 let widen = |bytes: &[u8]| -> Vec<u16> {
285 if bytes_per_sample == 1 {
286 bytes.iter().map(|&b| u16::from(b)).collect()
287 } else {
288 bytes.as_chunks::<2>().0.iter().map(|p| u16::from_le_bytes(*p)).collect()
289 }
290 };
291 out.stdout
292 .chunks_exact(frame)
293 .map(|data| {
294 let (luma, rest) = data.split_at(w * h * bytes_per_sample);
295 let (cb, cr) = rest.split_at(cw * ch * bytes_per_sample);
296 [widen(luma), widen(cb), widen(cr)]
297 })
298 .collect()
299}
300
301/// Every shown picture `ec-vp9` produces for the file's own access units,
302/// planes as 16-bit samples, the same widening as [`ffmpeg_libvpx_planes`].
303fn ec_vp9_planes(path: &Path) -> Vec<[Vec<u16>; 3]> {
304 let (_, mut demuxer) = Demuxer::open(path).expect("open the VP9 clip");
305 let mut decoder = Decoder::new();
306 let mut shown = Vec::new();
307 while let Some(au) = demuxer.next_access_unit().expect("demux") {
308 if let Some(pic) = decoder.decode(&au).expect("ec-vp9 decode") {
309 let Picture { y, u, v, .. } = pic;
310 shown.push([y, u, v]);
311 }
312 }
313 shown
314}
315
316/// The decoder, sample for sample against libvpx: profile 0 (8-bit) and profile
317/// 2 (10-bit), every picture, not a sample of them.
318#[test]
319fn ec_vp9_matches_libvpx_sample_for_sample() {
320 let cases = [(0u8, "yuv420p", 1usize), (2, "yuv420p10le", 2)];
321 for (profile, pix_fmt, bytes) in cases {
322 let Some(clip) = ffmpeg_vp9(&format!("ve_vp9_p{profile}"), profile, pix_fmt) else {
323 eprintln!("no ffmpeg with libvpx-vp9: skipping profile {profile}");
324 continue;
325 };
326 let want = ffmpeg_libvpx_planes(&clip, pix_fmt, bytes);
327 let got = ec_vp9_planes(&clip);
328 assert_eq!(want.len(), SW_FRAMES as usize, "libvpx released every frame");
329 assert_eq!(got.len(), want.len(), "profile {profile}: picture count");
330 for (i, (a, b)) in got.iter().zip(&want).enumerate() {
331 for (plane, (x, z)) in ["y", "u", "v"].iter().zip(a.iter().zip(b)) {
332 assert!(x == z, "profile {profile} picture {i} {plane} differs from libvpx");
333 }
334 }
335 eprintln!("profile {profile}: {} pictures agree sample for sample with libvpx", got.len());
336 }
337}
338
339/// Opens a clip and drains it, returning the pictures with their display
340/// indices. The caller holds the software seat: the pin is read when the span
341/// opens on its worker, so it must stay in place through the drain.
342fn software_frames(path: &Path) -> (engine::demux::VideoMeta, Vec<engine::decode::Frame>) {
343 let (meta, rx) = DecodeSession::open(path).expect("software VP9 open");
344 let frames: Vec<_> = rx.into_iter().collect();
345 (meta, frames)
346}
347
348/// The edith seat, end to end: every frame of profile 0 and profile 2 comes out
349/// through the span, in display order, at the clip's size, with pictures in
350/// them -- and a seek lands on the very bytes a linear decode delivered, at the
351/// sync points and between them.
352#[test]
353fn the_software_seat_decodes_and_seeks_vp9() {
354 let _seat = seat::software();
355 for (profile, pix_fmt) in [(0u8, "yuv420p"), (2, "yuv420p10le")] {
356 let Some(clip) = ffmpeg_vp9(&format!("ve_vp9_seat_p{profile}"), profile, pix_fmt) else {
357 eprintln!("no ffmpeg with libvpx-vp9: skipping the seat on profile {profile}");
358 continue;
359 };
360 let (meta, frames) = software_frames(&clip);
361 assert_eq!(meta.codec, Codec::Vp9);
362 assert_eq!(meta.frame_count, SW_FRAMES, "profile {profile}: container count");
363 assert_eq!(
364 frames.iter().map(|f| f.index).collect::<Vec<_>>(),
365 (0..SW_FRAMES).collect::<Vec<_>>(),
366 "profile {profile}: frames must arrive 0..n in display order"
367 );
368 assert!(
369 frames.iter().all(|f| (f.width, f.height) == (352, 288)),
370 "profile {profile}: every frame at the clip's size"
371 );
372 let first = &frames[0].bgra;
373 assert!(
374 first.as_chunks::<4>().0.iter().any(|px| px[..] != first[..4]),
375 "profile {profile}: frame 0 is a single colour -- no picture was decoded"
376 );
377
378 // Seeks: a keyframe, the frame after it, a frame just before the next
379 // keyframe, and the last frame.
380 let targets = [0, 1, SW_KEYFRAME - 1, SW_KEYFRAME, SW_KEYFRAME + 1, SW_FRAMES - 1];
381 for target in targets {
382 let want = &frames[target as usize].bgra;
383 let (_, rx, _cancel) = DecodeSession::open_at(&clip, target).expect("open_at");
384 let seeked = rx
385 .into_iter()
386 .next()
387 .unwrap_or_else(|| panic!("profile {profile}: no frame after seek to {target}"));
388 assert_eq!(seeked.index, target, "profile {profile}: first frame after seek");
389 assert!(
390 seeked.bgra == *want,
391 "profile {profile}: seek to {target} differs from a linear decode"
392 );
393 }
394 }
395}
396
397/// Profile 1 is 4:4:4 (or 4:2:2 / 4:4:0), which the GPU does not take. Such a file
398/// is not refused: the demuxer reads it, and it opens and decodes on the ec-vp9
399/// software seat, which takes all four profiles. Its pictures come out at the
400/// clip's size, in display order, with a picture in them.
401#[test]
402fn a_profile_1_444_vp9_file_opens_and_decodes_on_the_software_seat() {
403 let _seat = seat::software();
404 let Some(clip) = ffmpeg_vp9("ve_vp9_profile1", 1, "yuv444p") else {
405 eprintln!("no ffmpeg with libvpx-vp9: skipping the profile 1 seat");
406 return;
407 };
408 let (meta, demuxer) = Demuxer::open(&clip).expect("the demuxer reads profile 1");
409 assert_eq!(meta.codec, Codec::Vp9);
410 assert_eq!(demuxer.chroma(), Some(Chroma::C444), "the stream states 4:4:4");
411
412 let (meta, frames) = software_frames(&clip);
413 assert_eq!(meta.frame_count, SW_FRAMES, "container count");
414 assert_eq!(
415 frames.iter().map(|f| f.index).collect::<Vec<_>>(),
416 (0..SW_FRAMES).collect::<Vec<_>>(),
417 "profile 1: frames must arrive 0..n in display order"
418 );
419 assert!(
420 frames.iter().all(|f| (f.width, f.height) == (352, 288)),
421 "profile 1: every frame at the clip's size"
422 );
423 let first = &frames[0].bgra;
424 assert!(
425 first.as_chunks::<4>().0.iter().any(|px| px[..] != first[..4]),
426 "profile 1: frame 0 is a single colour -- no picture was decoded"
427 );
428}