forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

vp8.rs496 lines, 18.9 KiBHistoryRawDownload
1//! VP8 import: the container half, and the decode half. The software seat is
2//! `ec-vp8` in this process (`decode::vp8`), and it runs unignored: its clips
3//! are encoded by ffmpeg's `libvpx` at test time, and its reference is ffmpeg's
4//! libvpx decode, so those tests skip where ffmpeg has no libvpx. The plugin's
5//! own VP8 arm (`engine-hw`'s `vpx.rs`, the same `ec-vp8`) is the hardware-first
6//! twin and needs a built `libengine_hw.so`, but **no VA-API VP8 profile**: no
7//! such profile exists on this GPU, and none is asked for.
8//!
9//! ```text
10//! cargo build -p engine -p engine-hw --release
11//! LD_LIBRARY_PATH=target/release \
12//! cargo test -p engine --release --test vp8 -- --include-ignored --nocapture --test-threads=1
13//! ```
14//!
15//! `VE_SW` is process-wide: every test that pins a seat takes it through
16//! `support/seat.rs`, so the software and hardware tests here never see each
17//! other's pin, with or without `--test-threads=1`.
18use crate::seat;
19
20use std::path::{Path, PathBuf};
21use std::process::Command;
22use std::time::{Duration, Instant};
23
24use ec_vp8::decode::{Decoder, Picture};
25use engine::demux::{Codec, Demuxer};
26use engine::export::ExportSettings;
27use engine::scratch::Scratch;
28use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
29
30/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
31const FRAMES: u32 = 60;
32
33fn asset(name: &str) -> PathBuf {
34 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
35 .join("../../assets")
36 .join(name)
37}
38
39/// The container half: a vp08 track is found and named as VP8 out of the mp4,
40/// its `V_VP8` twin out of the `.webm`, and the AAC track is read exactly as
41/// any other file's -- the audio path knows nothing about the video codec.
42#[test]
43fn the_demuxer_reports_a_vp8_track() {
44 let (meta, _) = Demuxer::open(&asset("test_vp8.mp4")).expect("open test_vp8.mp4");
45 assert_eq!(meta.codec, Codec::Vp8);
46 assert_eq!((meta.width, meta.height), (1280, 720));
47 assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
48 assert_eq!(meta.frame_count, FRAMES);
49
50 let (webm, _) = Demuxer::open(&asset("test_vp8.webm")).expect("open test_vp8.webm");
51 assert_eq!(webm.codec, Codec::Vp8);
52
53 let probe = AudioSession::probe(asset("test_vp8.mp4"), 0)
54 .expect("probe")
55 .expect("the fixture has an AAC track");
56 assert_eq!(
57 (probe.sample_rate, probe.channels),
58 (44_100, 2),
59 "audio is read the same whatever the picture is coded with"
60 );
61}
62
63/// The software seat takes VP8 now: with the plugin forced off, the stream
64/// opens on `ec-vp8` in this process, the same way H.264 and VP9 do.
65#[test]
66fn the_software_path_opens_vp8() {
67 let _seat = seat::software();
68 let opened = DecodeSession::open(asset("test_vp8.mp4")).is_ok();
69 assert!(opened, "software VP8 decode opens");
70}
71
72/// The end-to-end user path: opening the file yields pictures, all of them,
73/// through the plugin's VP8 arm. The `.webm` is the file this decodes,
74/// the container half being the Matroska demuxer's `V_VP8` row.
75#[test]
76#[ignore = "needs a built libengine_hw.so -- no VA-API profile involved"]
77fn the_plugin_decodes_every_vp8_frame() {
78 let _seat = seat::hardware();
79 let start = Instant::now();
80 let (meta, frames) = DecodeSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm");
81 assert_eq!(meta.codec, Codec::Vp8);
82 let frames: Vec<_> = frames.into_iter().collect();
83 eprintln!(
84 "test_vp8.webm: {} frames in {:?} ({:.1} fps)",
85 frames.len(),
86 start.elapsed(),
87 frames.len() as f64 / start.elapsed().as_secs_f64().max(1e-9)
88 );
89
90 assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
91 for (i, frame) in frames.iter().enumerate() {
92 assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
93 assert_eq!(frame.index, i as u32, "frames arrive in display order");
94 assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
95 }
96 // A picture, not a flat surface: a decoder handing back an untouched
97 // buffer would satisfy every count above.
98 let first = &frames[0].bgra;
99 assert!(
100 first.as_chunks::<4>().0.iter().any(|px| px != &first[..4]),
101 "frame 0 is a single colour -- no picture was decoded"
102 );
103 // ...and a moving one, not one still: the fixture is a rendered clip, so
104 // frame 30 disagrees with frame 0 however the two are sampled.
105 let thumb = |f: &engine::Frame| -> Vec<u8> {
106 (0..f.bgra.len()).step_by(6173).map(|i| f.bgra[i]).collect()
107 };
108 assert_ne!(
109 thumb(&frames[0]),
110 thumb(&frames[FRAMES as usize / 2]),
111 "every frame identical -- nothing moved"
112 );
113}
114
115/// Export re-encodes to H.264 whatever the source was coded with: the packet
116/// copy path is audio-only, so no VP8 byte can reach an `avc1` track.
117#[test]
118#[ignore = "needs a built libengine_hw.so -- no VA-API profile involved"]
119fn a_vp8_source_exports_as_h264() {
120 let _seat = seat::hardware();
121 let session = PlaybackSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm");
122 let meta = *session.meta();
123 let project = Project::single(asset("test_vp8.webm"), meta.frame_count);
124 let out = Scratch::file("ve_export_vp8", "mp4");
125
126 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
127 let started = Instant::now();
128 while !handle.is_finished() {
129 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
130 std::thread::sleep(Duration::from_millis(20));
131 }
132 handle.result().expect("outcome").expect("export");
133
134 let (written, _) = Demuxer::open(&out).expect("reopen the export");
135 assert_eq!(written.codec, Codec::H264, "exports are always H.264");
136 // The fixture's own length and rate, back again: 60 pictures at 30 fps,
137 // which is the 2 s the source played.
138 assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
139 assert!(
140 (written.frame_rate - 30.0).abs() < 0.01,
141 "{}",
142 written.frame_rate
143 );
144 assert_eq!((written.width, written.height), (1280, 720));
145 let _ = std::fs::remove_file(&out);
146}
147
148// --- the software seat -----------------------------------------------------
149//
150// `ec-vp8` against ffmpeg's `libvpx` decode, picture for picture. The clips are
151// encoded by the same libvpx at test time. Three shapes: a plain stream with a
152// key frame every 8, a stream with hidden alt-ref frames (lag-in-frames and
153// auto-alt-ref, so the decoder's reference handling beyond the key frame is
154// exercised), and an odd-sized 99x67 stream (chroma planes of 50x34).
155
156const SW_FRAMES: u32 = 24;
157const SW_KEYFRAME: u32 = 8;
158
159/// One clip shape: name, width, height, and whether it carries alt-ref frames.
160struct Clip {
161 name: &'static str,
162 width: u32,
163 height: u32,
164 altref: bool,
165}
166
167const CLIPS: [Clip; 3] = [
168 Clip {
169 name: "ve_vp8_plain",
170 width: 352,
171 height: 288,
172 altref: false,
173 },
174 Clip {
175 name: "ve_vp8_altref",
176 width: 352,
177 height: 288,
178 altref: true,
179 },
180 Clip {
181 name: "ve_vp8_odd",
182 width: 99,
183 height: 67,
184 altref: false,
185 },
186];
187
188/// A WebM encoded by ffmpeg's libvpx at test time. `None` where ffmpeg with
189/// `libvpx` is not installed -- the skip the other ffmpeg witnesses take.
190///
191/// The alt-ref clip is two-pass: libvpx's one-pass encoder through ffmpeg never
192/// emits a hidden alt-ref frame, and the stream would not test what its name says.
193fn ffmpeg_vp8(clip: &Clip) -> Option<Scratch> {
194 if clip.width % 2 == 1 {
195 return odd_clip(clip);
196 }
197 let out = Scratch::file(clip.name, "webm");
198 let size = format!("testsrc2=size={}x{}:rate=30", clip.width, clip.height);
199 let pass_no = |n: u8| n.to_string();
200 let encode = |pass: Option<(u8, &Path)>, out: &Path| -> Option<()> {
201 let mut cmd = Command::new("ffmpeg");
202 cmd.args(["-v", "error", "-y", "-f", "lavfi", "-i"])
203 .arg(&size)
204 .args(["-frames:v", "24", "-c:v", "libvpx", "-g", "8"])
205 .args(["-b:v", "400k", "-deadline", "good", "-cpu-used", "4"]);
206 if clip.altref {
207 cmd.args(["-auto-alt-ref", "1", "-lag-in-frames", "16", "-g", "100"]);
208 }
209 if let Some((n, log)) = pass {
210 cmd.args(["-pass", &pass_no(n), "-passlogfile"]).arg(log);
211 if n == 1 {
212 cmd.args(["-f", "null", "-"]);
213 return cmd.status().ok()?.success().then_some(());
214 }
215 }
216 cmd.arg(out).status().ok()?.success().then_some(())
217 };
218 if clip.altref {
219 let log = Scratch::file(&format!("{}_pass", clip.name), "log");
220 encode(Some((1, &log)), &out)?;
221 encode(Some((2, &log)), &out)?;
222 } else {
223 encode(None, &out)?;
224 }
225 Some(out)
226}
227
228/// An odd-sized clip. ffmpeg's libvpx encoder only takes even sizes (asked for
229/// 99x67 it writes 98x66), so the 98x66 stream is re-labelled at the bitstream
230/// level: 98 and 66 round up to the same 7x5 macroblock grid as 99 and 67, so
231/// every key frame's dimension field is rewritten and the macroblock data is
232/// untouched. The result is a real 99x67 stream, which libvpx then decodes as
233/// its own. The IVF header is rewritten too, so the WebM ffmpeg muxes from it
234/// carries 99x67.
235fn odd_clip(clip: &Clip) -> Option<Scratch> {
236 let src = ffmpeg_vp8(&Clip {
237 name: "ve_vp8_odd_src",
238 width: 98,
239 height: 66,
240 altref: false,
241 })?;
242 let raw = Scratch::file(&format!("{}_raw", clip.name), "ivf");
243 let out = Scratch::file(clip.name, "webm");
244 let status = Command::new("ffmpeg")
245 .args(["-v", "error", "-y", "-i"])
246 .arg(&src)
247 .args(["-c", "copy", "-f", "ivf"])
248 .arg(&raw)
249 .status()
250 .ok()?;
251 if !status.success() {
252 return None;
253 }
254 let mut bytes = std::fs::read(&raw).ok()?;
255 let (w, h) = (clip.width as u16, clip.height as u16);
256 bytes[12..14].copy_from_slice(&w.to_le_bytes());
257 bytes[14..16].copy_from_slice(&h.to_le_bytes());
258 let mut at = 32;
259 while at + 12 <= bytes.len() {
260 let size = u32::from_le_bytes(bytes[at..at + 4].try_into().ok()?) as usize;
261 let frame = at + 12;
262 if frame + size > bytes.len() {
263 break;
264 }
265 // A key frame (bit 0 of the tag clear) carries the dimensions at 6..10,
266 // after the 3-byte start code 9d 01 2a.
267 if size >= 10 && bytes[frame] & 1 == 0 {
268 bytes[frame + 6..frame + 8].copy_from_slice(&w.to_le_bytes());
269 bytes[frame + 8..frame + 10].copy_from_slice(&h.to_le_bytes());
270 }
271 at = frame + size;
272 }
273 std::fs::write(&raw, &bytes).ok()?;
274 let status = Command::new("ffmpeg")
275 .args(["-v", "error", "-y", "-i"])
276 .arg(&raw)
277 .args(["-c", "copy"])
278 .arg(&out)
279 .status()
280 .ok()?;
281 status.success().then_some(out)
282}
283
284/// The display indices of a file's shown frames, and how many access units it
285/// has. A hidden frame is one whose `show_frame` bit (bit 4 of the first byte,
286/// RFC 6386 9.1) is clear: it takes a container slot and shows nothing.
287fn shown_samples(path: &Path) -> (Vec<u32>, usize) {
288 let (_, mut demuxer) = Demuxer::open(path).expect("open the VP8 clip");
289 let mut shown = Vec::new();
290 let mut units = 0;
291 while let Some(au) = demuxer.next_access_unit().expect("demux") {
292 if au[0] & 0x10 != 0 {
293 shown.push(units as u32);
294 }
295 units += 1;
296 }
297 (shown, units)
298}
299
300/// Every picture ffmpeg's libvpx decoder releases, as 8-bit I420 planes widened
301/// to 16 bits, so one comparison serves every shape. Chroma is `div_ceil(2)`,
302/// which is what makes the odd-sized clip's planes come out right.
303fn ffmpeg_libvpx_planes(path: &Path, width: usize, height: usize) -> Vec<[Vec<u16>; 3]> {
304 let out = Command::new("ffmpeg")
305 .args(["-v", "error", "-c:v", "libvpx", "-i"])
306 .arg(path)
307 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
308 .output()
309 .expect("run ffmpeg");
310 assert!(
311 out.status.success(),
312 "ffmpeg (libvpx) failed: {}",
313 String::from_utf8_lossy(&out.stderr)
314 );
315 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
316 let frame = width * height + 2 * cw * ch;
317 assert_eq!(
318 out.stdout.len() % frame,
319 0,
320 "ffmpeg handed back a partial frame"
321 );
322 let widen = |bytes: &[u8]| -> Vec<u16> { bytes.iter().map(|&b| u16::from(b)).collect() };
323 out.stdout
324 .chunks_exact(frame)
325 .map(|data| {
326 let (luma, rest) = data.split_at(width * height);
327 let (cb, cr) = rest.split_at(cw * ch);
328 [widen(luma), widen(cb), widen(cr)]
329 })
330 .collect()
331}
332
333/// Every shown picture `ec-vp8` produces for the file's own access units, plus
334/// how many access units it took to get them: the difference is the hidden
335/// frames, which the altref clip must have.
336fn ec_vp8_planes(path: &Path) -> (Vec<[Vec<u16>; 3]>, usize) {
337 let (_, mut demuxer) = Demuxer::open(path).expect("open the VP8 clip");
338 let mut decoder = Decoder::new();
339 let mut shown = Vec::new();
340 let mut units = 0;
341 while let Some(au) = demuxer.next_access_unit().expect("demux") {
342 units += 1;
343 if let Some(pic) = decoder.decode(&au).expect("ec-vp8 decode") {
344 let Picture { y, u, v, .. } = pic;
345 shown.push([y, u, v].map(|p| p.into_iter().map(u16::from).collect()));
346 }
347 }
348 (shown, units)
349}
350
351/// The decoder, picture for picture against libvpx: every shown frame of every
352/// clip shape, plane by plane. The altref clip must also carry hidden frames,
353/// or it would not be testing what it is named for.
354#[test]
355fn ec_vp8_matches_libvpx_picture_for_picture() {
356 for clip in CLIPS {
357 let Some(path) = ffmpeg_vp8(&clip) else {
358 eprintln!("no ffmpeg with libvpx: skipping {}", clip.name);
359 continue;
360 };
361 let (w, h) = (clip.width as usize, clip.height as usize);
362 let want = ffmpeg_libvpx_planes(&path, w, h);
363 let (got, units) = ec_vp8_planes(&path);
364 assert_eq!(
365 want.len(),
366 SW_FRAMES as usize,
367 "{}: libvpx released every frame",
368 clip.name
369 );
370 assert_eq!(got.len(), want.len(), "{}: picture count", clip.name);
371 if clip.altref {
372 assert!(
373 units > got.len(),
374 "{}: no hidden frames in the stream",
375 clip.name
376 );
377 }
378 for (i, (a, b)) in got.iter().zip(&want).enumerate() {
379 for (plane, (x, z)) in ["y", "u", "v"].iter().zip(a.iter().zip(b)) {
380 assert!(
381 x == z,
382 "{} picture {i} {plane} differs from libvpx",
383 clip.name
384 );
385 }
386 }
387 eprintln!(
388 "{}: {} pictures ({} access units) agree with libvpx sample for sample",
389 clip.name,
390 got.len(),
391 units
392 );
393 }
394}
395
396/// Opens a clip and drains it, returning the pictures with their display
397/// indices. The caller holds the software seat: the pin is read when the span
398/// opens on its worker, so it must stay in place through the drain.
399fn software_frames(path: &Path) -> (engine::demux::VideoMeta, Vec<engine::decode::Frame>) {
400 let (meta, rx) = DecodeSession::open(path).expect("software VP8 open");
401 let frames: Vec<_> = rx.into_iter().collect();
402 (meta, frames)
403}
404
405/// The edith seat, end to end: every frame of every clip shape comes out
406/// through the span, in display order, at the clip's size, with pictures in
407/// them -- and a seek lands on the very bytes a linear decode delivered, at the
408/// key frames, between them, and past the hidden frames.
409#[test]
410fn the_software_seat_decodes_and_seeks_vp8() {
411 let _seat = seat::software();
412 for clip in CLIPS {
413 let Some(path) = ffmpeg_vp8(&clip) else {
414 eprintln!("no ffmpeg with libvpx: skipping the seat on {}", clip.name);
415 continue;
416 };
417 let (shown, units) = shown_samples(&path);
418 let (meta, frames) = software_frames(&path);
419 assert_eq!(meta.codec, Codec::Vp8);
420 assert_eq!(
421 meta.frame_count as usize, units,
422 "{}: container count",
423 clip.name
424 );
425 assert_eq!(
426 shown.len(),
427 SW_FRAMES as usize,
428 "{}: shown frames",
429 clip.name
430 );
431 // Shown frames arrive at their container slots, in order: a hidden slot
432 // is skipped, so the altref clip's indices have a hole where it sits.
433 assert_eq!(
434 frames.iter().map(|f| f.index).collect::<Vec<_>>(),
435 shown,
436 "{}: frames must arrive in display order at their slots",
437 clip.name
438 );
439 assert!(
440 frames
441 .iter()
442 .all(|f| (f.width, f.height) == (clip.width, clip.height)),
443 "{}: every frame at the clip's size, got {:?}",
444 clip.name,
445 frames.first().map(|f| (f.width, f.height))
446 );
447 let first = &frames[0].bgra;
448 assert!(
449 first
450 .as_chunks::<4>()
451 .0
452 .iter()
453 .any(|px| px[..] != first[..4]),
454 "{}: frame 0 is a single colour -- no picture was decoded",
455 clip.name
456 );
457
458 // Seeks: a key frame, the frame after it, a frame just before the next
459 // key frame, the key frame itself, the last frame, and the shown frame
460 // straight after each hidden slot (a seek must not stop on the hole).
461 let last = units as u32 - 1;
462 let hidden_after: Vec<u32> = (0..units as u32)
463 .filter(|i| !shown.contains(i))
464 .map(|i| i + 1)
465 .collect();
466 let mut targets = vec![0, 1, SW_KEYFRAME - 1, SW_KEYFRAME, SW_KEYFRAME + 1, last];
467 targets.extend(hidden_after);
468 targets.retain(|t| shown.contains(t));
469 for target in targets {
470 // Looked up by display index: the linear decode's frames skip a
471 // hidden slot, so position and index part ways after it.
472 let want = &frames
473 .iter()
474 .find(|f| f.index == target)
475 .unwrap_or_else(|| panic!("{}: no linear frame {target}", clip.name))
476 .bgra;
477 let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at");
478 let seeked = rx
479 .into_iter()
480 .next()
481 .unwrap_or_else(|| panic!("{}: no frame after seek to {target}", clip.name));
482 assert_eq!(
483 seeked.index, target,
484 "{}: first frame after seek",
485 clip.name
486 );
487 let first = seeked.bgra.iter().zip(want).position(|(a, b)| a != b);
488 assert!(
489 seeked.bgra == *want,
490 "{}: seek to {target} differs from a linear decode (first byte at {first:?} of {})",
491 clip.name,
492 want.len()
493 );
494 }
495 }
496}