forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

av1.rs890 lines, 38.3 KiBHistoryRawDownload
1//! AV1 import: the third source codec that is not H.264, and the first that
2//! arrives in a container of its own -- `mp4 0.14` knows no `av01` sample entry
3//! at all, so AV1 comes in as Matroska and the demuxer walks the EBML itself.
4//!
5//! Decoding has two seats: the project's own `ec-av1` in this process, and the
6//! VA-API plugin's (`vainfo | grep AV1`) in front of it. The software seat needs
7//! nothing installed, so its witnesses run unignored (`VE_SW` pins it); the
8//! hardware twins need a built `libengine_hw.so` and 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 av1 -- --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::PathBuf;
23use std::time::{Duration, Instant};
24
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, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.
31const FRAMES: u32 = 60;
32const KEYFRAME: u32 = 30;
33/// The film grain twin is 3 s of the same shape, for the reason its own test
34/// gives.
35const GRAIN_FRAMES: u32 = 90;
36
37fn asset(name: &str) -> PathBuf {
38 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
39 .join("../../assets")
40 .join(name)
41}
42
43/// The container half. Matroska indexes neither frames nor rate, so all three
44/// numbers here come out of the walk: the count is the blocks of the track, the
45/// rate is `DefaultDuration` in nanoseconds (33333333, i.e. 30 fps to seven
46/// digits -- the millisecond timestamps beside it would say 30.30).
47#[test]
48fn the_demuxer_reports_an_av1_track_in_matroska() {
49 let (meta, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
50 assert_eq!(meta.codec, Codec::Av1);
51 assert_eq!((meta.width, meta.height), (1280, 720));
52 assert!(
53 (meta.frame_rate - 30.0).abs() < 1e-6,
54 "DefaultDuration must not truncate: {}",
55 meta.frame_rate
56 );
57 assert_eq!(meta.frame_count, FRAMES);
58
59 // The invariant, stated as an assert: the mp4 codecs still say themselves.
60 let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
61 assert_eq!(h264.codec, Codec::H264);
62 let (hevc, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
63 assert_eq!(hevc.codec, Codec::Hevc);
64 let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
65 assert_eq!(vp9.codec, Codec::Vp9);
66}
67
68/// The depth, which is what picks the surface pool the plugin decodes into: an
69/// `av1C` with `high_bitdepth` set reads as 10 and takes the P010 pool HEVC Main
70/// 10 already goes through, and the 8-bit fixture beside it still reads as 8.
71/// It used to be an outright refusal at open ("10-bit AV1 is not supported").
72#[test]
73fn a_ten_bit_av1_track_is_read_as_ten_bit() {
74 let (meta, ten) = Demuxer::open(&asset("test_av1_10.mkv")).expect("open test_av1_10.mkv");
75 assert_eq!(meta.codec, Codec::Av1);
76 assert_eq!((meta.width, meta.height), (1280, 720));
77 assert_eq!(meta.frame_count, FRAMES);
78 assert_eq!(ten.bit_depth(), 10, "what picks the P010 surface pool");
79
80 // The invariant: the 8-bit file is untouched by any of it.
81 let (_, eight) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
82 assert_eq!(eight.bit_depth(), 8);
83}
84
85/// The delivered audio scope, as an assert: a Matroska file's AAC track is read
86/// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its
87/// *picture* being AV1 changes nothing about it.
88#[test]
89fn matroska_audio_is_read_whatever_the_picture_is() {
90 let path = asset("test_av1.mkv");
91 let probe = AudioSession::probe(&path, 0)
92 .expect("probe must not fail")
93 .expect("the fixture has an AAC track");
94 assert_eq!((probe.sample_rate, probe.channels), (44_100, 2));
95 let streams = AudioSession::probe_streams(&path).expect("streams");
96 assert_eq!(streams.len(), 1, "one readable audio stream: {streams:?}");
97 assert!(streams[0].decodable);
98}
99
100/// Every block comes back, keyframes carry the sequence header, and the sync
101/// index is what a seek lands on. An AV1 decoder cannot start without a
102/// sequence header, and `mkv` carries it in `CodecPrivate` -- so this is the
103/// check that says the `av1C` record was really parsed and re-injected.
104#[test]
105fn every_block_comes_back_and_keyframes_carry_the_sequence_header() {
106 let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
107 let first = demuxer
108 .next_access_unit()
109 .expect("read")
110 .expect("a first access unit");
111 // OBU header: bits 6..3 are the type, and 1 is a sequence header.
112 assert_eq!(
113 (first[0] >> 3) & 0xF,
114 1,
115 "the keyframe leads with the sequence header"
116 );
117 assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
118
119 let mut count = 1;
120 while demuxer.next_access_unit().expect("read").is_some() {
121 count += 1;
122 }
123 assert_eq!(count, FRAMES, "every block came back out");
124
125 // The fixture is keyed every 30 frames, and a seek may only land on one:
126 // anywhere in the second GOP rewinds to frame 30, anywhere in the first to
127 // frame 0.
128 assert_eq!(
129 demuxer.seek_to_sync_at_or_before(KEYFRAME + 15),
130 i64::from(KEYFRAME)
131 );
132 assert_eq!(
133 demuxer.seek_to_sync_at_or_before(KEYFRAME),
134 i64::from(KEYFRAME)
135 );
136 assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0);
137 assert_eq!(demuxer.seek_to_sync_at_or_before(0), 0);
138 assert_eq!(
139 demuxer.seek_to_sync_at_or_before(FRAMES * 10),
140 i64::from(KEYFRAME),
141 "past the end clamps to the last sync point"
142 );
143 // And the access unit after a seek is the keyframe's, sequence header and
144 // all -- a decoder restarted mid-file needs it exactly as much.
145 let after = demuxer.next_access_unit().expect("read").expect("a unit");
146 assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]);
147}
148
149/// The seat this file used to refuse by name now exists: `ec-av1`, in this
150/// process, behind the same `VE_SW` pin the H.264 seat takes. A linear open
151/// delivers every frame the container indexes, labelled `0..n` in display
152/// order -- the contract the transport reads and the one the hardware seat
153/// always kept.
154#[test]
155fn the_software_seat_decodes_every_frame() {
156 let _seat = seat::software();
157 let (meta, rx) = DecodeSession::open(asset("test_av1.mkv")).expect("software AV1 open");
158 assert_eq!(meta.frame_count, FRAMES);
159 let indices: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
160 assert_eq!(indices, (0..FRAMES).collect::<Vec<_>>(), "frames must arrive 0..n in display order");
161}
162
163/// ...and the 10-bit twin, whose samples arrive as `u16` in `0..=1023` and
164/// narrow to the same 8-bit planes the plugin's P010 read-back produces.
165#[test]
166fn the_software_seat_decodes_ten_bit_av1() {
167 let _seat = seat::software();
168 let (meta, rx) = DecodeSession::open(asset("test_av1_10.mkv")).expect("software AV1 open");
169 assert_eq!(meta.frame_count, FRAMES);
170 let count = rx.into_iter().count();
171 assert_eq!(count, FRAMES as usize, "every 10-bit frame came out");
172}
173
174/// Seeking may only change *when* a picture arrives, never the picture: a seek
175/// onto the software seat lands on the very bytes a linear decode of the same
176/// index delivered, on either side of and away from a keyframe. The promise
177/// `hw_decode::seek_matches_linear_every_container` makes of the hardware
178/// seat, made here of the software one -- which is why this runs unignored.
179#[test]
180fn seek_lands_on_the_picture_a_linear_software_decode_delivered() {
181 let _seat = seat::software();
182 let path = asset("test_av1.mkv");
183 let (meta, rx) = DecodeSession::open(&path).expect("software open");
184 let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1];
185 targets.retain(|&t| t < meta.frame_count);
186 targets.sort_unstable();
187 targets.dedup();
188 let linear: Vec<(u32, Vec<u8>)> = rx
189 .into_iter()
190 .filter(|f| targets.contains(&f.index))
191 .map(|f| (f.index, f.bgra))
192 .collect();
193 assert_eq!(
194 linear.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
195 targets,
196 "linear decode never delivered every target"
197 );
198 for (target, want) in linear {
199 let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at");
200 let seeked = rx
201 .into_iter()
202 .next()
203 .unwrap_or_else(|| panic!("no frame after seek to {target}"));
204 assert_eq!(seeked.index, target, "first frame after seek is not the target");
205 assert!(
206 seeked.bgra == want,
207 "seek to {target} handed back a different picture than a linear decode of {target}"
208 );
209 }
210}
211
212/// A timeline is *not* refused a source coded differently -- every clip opens
213/// its own decoder, and since the `ec-av1` seat that is true with no plugin
214/// and no driver in the room: the no-plugin machine, forced, takes the AV1
215/// source beside its H.264 one.
216#[test]
217fn a_timeline_takes_av1_on_a_machine_with_no_plugin() {
218 let _seat = seat::software();
219 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
220 let imported = session
221 .import(&asset("test_av1.mkv"))
222 .is_ok();
223 assert!(imported, "the software seat is a seat: the timeline takes AV1");
224 assert_eq!(session.sources().len(), 2, "both sources stand");
225}
226
227// --- the refusal witness ---------------------------------------------------
228//
229// The minimal EBML this file's refusal fixture is written with -- the same
230// builders `mkv_encodings.rs` uses, kept local because test binaries do not
231// share code. Every size goes out in the 8-byte long form, legal everywhere
232// and arithmetic-free.
233
234const SEGMENT: u32 = 0x1853_8067;
235const INFO: u32 = 0x1549_A966;
236const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
237const TRACKS: u32 = 0x1654_AE6B;
238const TRACK_ENTRY: u32 = 0xAE;
239const TRACK_NUMBER: u32 = 0xD7;
240const TRACK_TYPE: u32 = 0x83;
241const CODEC_ID: u32 = 0x86;
242const CODEC_PRIVATE: u32 = 0x63A2;
243const DEFAULT_DURATION: u32 = 0x23E383;
244const VIDEO: u32 = 0xE0;
245const PIXEL_WIDTH: u32 = 0xB0;
246const PIXEL_HEIGHT: u32 = 0xBA;
247const CLUSTER: u32 = 0x1F43_B675;
248const CLUSTER_TIMESTAMP: u32 = 0xE7;
249const SIMPLE_BLOCK: u32 = 0xA3;
250
251fn el(id: u32, body: &[u8]) -> Vec<u8> {
252 let mut out: Vec<u8> = id.to_be_bytes()[(id.leading_zeros() / 8) as usize..].to_vec();
253 out.push(0x01);
254 out.extend_from_slice(&(body.len() as u64).to_be_bytes()[1..]);
255 out.extend_from_slice(body);
256 out
257}
258
259fn uint(id: u32, value: u64) -> Vec<u8> {
260 el(id, &value.to_be_bytes())
261}
262
263/// A `SimpleBlock` of `track`, `rel` ticks into its cluster; `flags` carries
264/// the keyframe bit (0x80).
265fn block(track: u8, rel: i16, flags: u8, body: &[u8]) -> Vec<u8> {
266 let mut b = vec![0x80 | track];
267 b.extend_from_slice(&rel.to_be_bytes());
268 b.push(flags);
269 b.extend_from_slice(body);
270 el(SIMPLE_BLOCK, &b)
271}
272
273/// One OBU's total length inside a low-overhead stream: the header byte (plus
274/// its extension byte, which this fixture format never writes) and the
275/// leb128 size that `obu_has_size_field` promises.
276fn obu_len(stream: &[u8]) -> usize {
277 assert_eq!(stream[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
278 let mut len = 1;
279 let mut size: usize = 0;
280 loop {
281 let byte = stream[len];
282 len += 1;
283 size = size << 7 | usize::from(byte & 0x7F);
284 if byte & 0x80 == 0 {
285 break;
286 }
287 }
288 len + size
289}
290
291/// A stream whose GOP structure is broken in a way the container cannot see:
292/// the second keyframe-flagged block carries an *inter* frame's bytes, as a
293/// remux that trusted the wrong key index would write one. The demuxer opens
294/// it, injects the sequence header ahead of it, and `ec-av1` refuses it by
295/// name -- an inter frame with no key frame behind it finds no saved CDF state
296/// to resume from, one of the live refusals its inventory pins -- and the seat
297/// fails the span in words instead of a panic or a garbage picture: the frames
298/// decoded so far stand, then the channel closes.
299#[test]
300fn a_broken_gop_is_refused_in_words_and_never_a_panic() {
301 let _seat = seat::software();
302 // The pieces, off the real fixture: the sequence header OBU the demuxer
303 // injects (the `av1C` payload) and a real inter frame's block bytes.
304 let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
305 let key_au = demuxer.next_access_unit().expect("read").expect("key au");
306 let seq_len = obu_len(&key_au);
307 let seq_header = &key_au[..seq_len];
308 let key_body = &key_au[seq_len..];
309 // The very next access unit is frame 1, a real inter frame: no injection
310 // ahead of a non-sync sample, so its bytes are the block verbatim.
311 let inter_body = demuxer.next_access_unit().expect("read").expect("inter au");
312
313 // The words first, at the decoder's own door: the crafted chunk is
314 // refused, and the refusal is a sentence, not a panic.
315 let mut broken = seq_header.to_vec();
316 broken.extend_from_slice(&inter_body);
317 let refused = ec_av1::stream::decode_stream(&broken)
318 .expect_err("an inter frame with no key frame behind it is refused");
319 assert!(
320 refused.to_string().contains("no saved CDF state"),
321 "the refusal names its reason: {refused}"
322 );
323
324 // The same broken stream as a file, through the seat: open succeeds (the
325 // container is valid), the first GOP decodes, the second chunk refuses,
326 // and the span ends cleanly with exactly the pictures decoded so far.
327 let av1c = [0x81u8, 0x00, 0x0C, 0x00];
328 let mut private = av1c.to_vec();
329 private.extend_from_slice(seq_header);
330 let track = el(
331 TRACK_ENTRY,
332 &[
333 uint(TRACK_NUMBER, 1),
334 uint(TRACK_TYPE, 1),
335 el(CODEC_ID, b"V_AV1"),
336 el(CODEC_PRIVATE, &private),
337 uint(DEFAULT_DURATION, 33_333_333),
338 el(VIDEO, &[uint(PIXEL_WIDTH, 1280), uint(PIXEL_HEIGHT, 720)].concat()),
339 ]
340 .concat(),
341 );
342 let cluster = el(
343 CLUSTER,
344 &[
345 uint(CLUSTER_TIMESTAMP, 0),
346 block(1, 0, 0x80, key_body),
347 block(1, 33, 0x80, &inter_body),
348 ]
349 .concat(),
350 );
351 let segment = [
352 el(INFO, &uint(TIMESTAMP_SCALE, 1_000_000)),
353 el(TRACKS, &track),
354 cluster,
355 ]
356 .concat();
357 let file = [
358 el(0x1A45_DFA3, &[]),
359 el(SEGMENT, &segment),
360 ]
361 .concat();
362 let scratch = Scratch::file("broken_gop_av1", "mkv");
363 std::fs::write(&scratch, &file).expect("write fixture");
364
365 let (meta, mut opened) = Demuxer::open(&scratch).expect("the container itself is valid");
366 assert_eq!(meta.codec, Codec::Av1);
367 assert_eq!(meta.frame_count, 2);
368 // Both blocks are key-flagged, so both lead with the injected sequence
369 // header -- which is what makes the second one a chunk boundary, and the
370 // refusal the decoder's own answer to what it finds there.
371 let first = opened.next_access_unit().expect("read").expect("au");
372 assert_eq!((first[0] >> 3) & 0xF, 1);
373
374 let (_, rx) = DecodeSession::open(&scratch).expect("open succeeds; the container is fine");
375 let frames: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
376 assert_eq!(frames, vec![0], "the first GOP stands, the broken one refuses");
377}
378
379/// The end-to-end user path: opening the file yields pictures, all of them,
380/// through the plugin.
381#[test]
382#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
383fn the_plugin_decodes_every_av1_frame() {
384 let _seat = seat::hardware();
385 let start = Instant::now();
386 let (meta, frames) = DecodeSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
387 assert_eq!(meta.codec, Codec::Av1);
388 let frames: Vec<_> = frames.into_iter().collect();
389 eprintln!(
390 "test_av1.mkv: {} frames in {:?}",
391 frames.len(),
392 start.elapsed()
393 );
394
395 assert_eq!(frames.len() as u32, FRAMES, "every block decoded");
396 for (i, frame) in frames.iter().enumerate() {
397 assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
398 assert_eq!(frame.index, i as u32, "frames arrive in display order");
399 assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
400 }
401 // A picture, not a flat surface: a driver handing back an untouched buffer
402 // would satisfy every count above.
403 let first = &frames[0].bgra;
404 assert!(
405 first.as_chunks::<4>().0.iter().any(|px| px != &first[..4]),
406 "frame 0 is a single colour -- no picture was decoded"
407 );
408}
409
410/// The picture's flattest 8x8 block, as a standard deviation of its green
411/// channel: 0 where the decoder handed back a smooth picture, well above it
412/// where every pixel carries synthesized grain.
413fn flattest_block(bgra: &[u8], width: u32, height: u32) -> f64 {
414 let (w, h) = (width as usize, height as usize);
415 let mut flattest = f64::MAX;
416 for y in (0..h - 8).step_by(8) {
417 for x in (0..w - 8).step_by(8) {
418 let block = (0..8).flat_map(|dy| {
419 (0..8).map(move |dx| f64::from(bgra[((y + dy) * w + x + dx) * 4 + 1]))
420 });
421 let values: Vec<f64> = block.collect();
422 let mean = values.iter().sum::<f64>() / values.len() as f64;
423 let var =
424 values.iter().map(|v| (v - mean) * (v - mean)).sum::<f64>() / values.len() as f64;
425 flattest = flattest.min(var.sqrt());
426 }
427 }
428 flattest
429}
430
431/// The defect none of the fixtures above could see: an AV1 frame that asks for
432/// film grain is *displayed* from a second surface, which the driver
433/// synthesizes the grain into and which the decoder has to give it. Handing it
434/// none gets the picture refused outright -- radeonsi answers `vaEndPicture`
435/// with VA_STATUS_ERROR_INVALID_SURFACE -- and that killed a real 1080p AV1
436/// film at frame 49, the first of its pictures with `apply_grain` set. Every
437/// fixture beside this one is grainless, and every one of them passed.
438///
439/// Ninety frames, all of them: a grainy picture costs two pool buffers rather
440/// than one, so this turns the pool over several times and cycles the eight
441/// reference slots -- decoding "the first handful" is exactly what let the
442/// defect live.
443#[test]
444#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
445fn a_film_grain_av1_file_decodes_whole_and_keeps_its_grain() {
446 let _seat = seat::hardware();
447 let (meta, frames) =
448 DecodeSession::open(asset("test_av1_grain.mkv")).expect("open test_av1_grain.mkv");
449 assert_eq!(meta.codec, Codec::Av1);
450 let frames: Vec<_> = frames.into_iter().collect();
451 assert_eq!(frames.len() as u32, GRAIN_FRAMES, "every frame decoded");
452
453 // ...and the grain is *in* the picture, which is the half "it did not fail"
454 // cannot say: telling the driver `apply_grain = 0` also makes every frame
455 // decode, and silently strips the film of the texture it was graded with.
456 // Grain is noise on every pixel, so no block of a grainy picture is flat;
457 // this source has plenty of flat ones without it (measured on the fixture:
458 // 0.00 with the grain off, 1.58 with it on).
459 let frame = &frames[GRAIN_FRAMES as usize - 30];
460 let flattest = flattest_block(&frame.bgra, frame.width, frame.height);
461 assert!(
462 flattest > 0.5,
463 "the grain never reached the picture: flattest 8x8 block deviation {flattest:.3}"
464 );
465}
466
467/// ...and the 10-bit file through the very call the window's open door makes: a
468/// user opens it and the timeline shows a picture, read back off the P010 pool
469/// to the same 8-bit BGRA every other frame arrives in. The whole point of the
470/// slice, and the half a container test cannot say anything about.
471#[test]
472#[ignore = "needs libengine_hw.so and a VA-API driver with 10-bit AV1 decode"]
473fn opening_a_ten_bit_av1_file_shows_frames() {
474 let _seat = seat::hardware();
475 let mut session =
476 PlaybackSession::open(asset("test_av1_10.mkv")).expect("open the 10-bit file");
477 assert_eq!(session.meta().codec, Codec::Av1);
478 assert_eq!(session.meta().frame_count, FRAMES);
479
480 // The decoder is a thread behind the door, so a frame is waited for exactly
481 // as the window's own pump waits for one.
482 let deadline = Instant::now() + Duration::from_secs(60);
483 let frame = loop {
484 if let Some(frame) = session.try_frame() {
485 break frame;
486 }
487 assert!(Instant::now() < deadline, "no frame in 60 s");
488 std::thread::sleep(Duration::from_millis(10));
489 };
490 assert_eq!((frame.width, frame.height), (1280, 720));
491 // A picture, not a flat surface: a P010 surface read back through the NV12
492 // path would come out as noise or as nothing at all.
493 assert!(
494 frame.bgra.as_chunks::<4>().0.iter().any(|px| px != &frame.bgra[..4]),
495 "the first frame is a single colour -- no picture was decoded"
496 );
497}
498
499/// A seek into the second GOP hands back that very frame, not the keyframe it
500/// had to restart from: the demuxer's sync index and the plugin's skip count
501/// have to agree, and Matroska is where both are this crate's own doing.
502#[test]
503#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
504fn a_seek_lands_on_the_frame_it_asked_for() {
505 let _seat = seat::hardware();
506 let (_, frames, _cancel) =
507 DecodeSession::open_range(asset("test_av1.mkv"), KEYFRAME + 7, FRAMES)
508 .expect("open at a frame inside the second GOP");
509 let frames: Vec<_> = frames.into_iter().collect();
510 assert_eq!(frames.len() as u32, FRAMES - KEYFRAME - 7, "to the end");
511 assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");
512}
513
514/// An mp4 export of a Matroska source carries its sound.
515///
516/// Three lives, this one. It used to *succeed* silently and write picture with
517/// no sound, because this engine could not read a Matroska file's audio at all.
518/// Then the sound became readable and this became a refusal by name, because
519/// the mp4 path could only *copy* AAC out of an mp4's own sample table and a
520/// Matroska file has none. Now the copy that cannot be made is a decode and a
521/// re-encode (`export::copy_audio` -> `encode_audio`), so the export carries the
522/// film's sound instead of naming what it cannot do with it. The picture half of
523/// the same export is [`an_av1_export_reopens_through_our_own_demuxer`].
524#[test]
525#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
526fn an_mp4_export_of_a_matroska_source_carries_its_sound() {
527 let _seat = seat::hardware();
528 let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
529 let meta = *session.meta();
530 // A short one: the picture is re-encoded frame by frame and what is under
531 // test here is the sound reaching the file, not H.264 throughput.
532 let project = Project::single(asset("test_av1.mkv"), 15);
533 let out = Scratch::file("ve_export_av1", "mp4");
534
535 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
536 let started = Instant::now();
537 while !handle.is_finished() {
538 assert!(started.elapsed() < Duration::from_secs(900), "export hung");
539 std::thread::sleep(Duration::from_millis(20));
540 }
541 handle
542 .result()
543 .expect("outcome")
544 .expect("an mkv's AAC is decoded and encoded again into the mp4");
545 let (audio, chunks) = AudioSession::open(&out)
546 .expect("reopen the export")
547 .expect("the export has an audio track");
548 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
549 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
550 println!("mkv -> mp4: {} Hz, rms {rms:.4}", audio.sample_rate);
551 assert!(rms > 0.001, "the film's sound is in the mp4 (rms {rms})");
552 std::fs::remove_file(&out).unwrap();
553}
554
555/// A short timeline out of the H.264 fixture, which is what the AV1 export tests
556/// below write: `rav1e` is built here without its assembly, so the length of the
557/// timeline is the length of the test.
558fn short_timeline(frames: f64) -> PlaybackSession {
559 let mut session = PlaybackSession::open(asset("test_baseline.mp4")).expect("open the fixture");
560 assert!(session.cut_at(frames / 30.0), "cut at frame {frames}");
561 assert!(
562 session.delete_clip(engine::project::Lane::V1, 1),
563 "drop everything after it"
564 );
565 session
566}
567
568fn av1_settings() -> ExportSettings {
569 ExportSettings {
570 format: engine::export::Format::Av1,
571 // The software encoder, on every machine: the hardware twin below is
572 // where the plugin's AV1 seat is exercised.
573 seat: engine::export::EncoderSeat::Software,
574 ..Default::default()
575 }
576}
577
578fn exported(
579 session: &PlaybackSession,
580 name: &str,
581 settings: &ExportSettings,
582 limit: Duration,
583) -> Scratch {
584 let out = Scratch::file(&format!("ve_av1_{name}"), "mkv");
585 let started = Instant::now();
586 let handle = session.export_to_with(&out, settings);
587 while !handle.is_finished() {
588 assert!(
589 started.elapsed() < limit,
590 "export did not finish in {limit:?}"
591 );
592 std::thread::sleep(Duration::from_millis(20));
593 }
594 handle.result().expect("outcome").expect("export");
595 assert_eq!(handle.progress(), 1.0, "finished at full progress");
596 let spent = started.elapsed().as_secs_f64();
597 let frames = (session.timeline_duration() * 30.0).round().max(1.0);
598 eprintln!(
599 "{name}: {frames} frames in {spent:.2} s = {:.2} ms/frame",
600 spent * 1000.0 / frames
601 );
602 out
603}
604
605/// The export half of this slice: AV1 out of the software encoder, into a
606/// Matroska file this project's own demuxer walks back. Nothing installed is
607/// needed -- the file is *read* as a container here, which is where the
608/// hand-written EBML either agrees with the hand-written EBML reader or does not.
609#[test]
610fn an_av1_export_reopens_through_our_own_demuxer() {
611 let session = short_timeline(30.0);
612 // The software encoder alone costs ~270 s for these 30 frames on the
613 // machine of record: 300 s left it one co-running test away from a
614 // timeout, so the budget is a hang guard, not a speed claim.
615 let out = exported(&session, "sw", &av1_settings(), Duration::from_secs(900));
616
617 let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export");
618 assert_eq!(meta.codec, Codec::Av1, "an AV1 export is AV1");
619 assert_eq!((meta.width, meta.height), (1280, 720));
620 assert!(
621 (meta.frame_rate - 30.0).abs() < 1e-6,
622 "DefaultDuration must state the rate exactly: {}",
623 meta.frame_rate
624 );
625 assert_eq!(meta.frame_count, 30, "every timeline frame is a block");
626
627 // The first block is a keyframe and leads with the sequence header -- the
628 // demuxer prepends `CodecPrivate` to every keyframe, so this is also the
629 // check that the `av1C` record was written and parsed back.
630 let first = demuxer.next_access_unit().expect("read").expect("a unit");
631 assert_eq!(
632 (first[0] >> 3) & 0xF,
633 1,
634 "the keyframe leads with the sequence header"
635 );
636 assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
637 let mut count = 1;
638 while demuxer.next_access_unit().expect("read").is_some() {
639 count += 1;
640 }
641 assert_eq!(count, 30, "every block comes back out");
642 assert_eq!(
643 demuxer.seek_to_sync_at_or_before(29),
644 0,
645 "one GOP, one sync point"
646 );
647 std::fs::remove_file(&out).unwrap();
648}
649
650/// A timeline with sound, exported as AV1 into **both** containers: the file
651/// carries the picture *and* the timeline's audio, and this project's own
652/// readers are what say so -- the demuxer for the picture, the audio session for
653/// the sound. An AV1 export used to be picture only, which is a file whose sound
654/// went missing with nobody told.
655///
656/// Two frames of 720p: `rav1e` is built here without its assembly, so the length
657/// of the timeline is the length of the test, and what is under test is the
658/// wiring from the format to the muxer, not the encoder.
659#[test]
660fn an_av1_export_carries_the_timelines_sound_in_either_container() {
661 for (format, ext) in [
662 (engine::export::Format::Av1, "mkv"),
663 (engine::export::Format::Av1Mp4, "mp4"),
664 ] {
665 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av");
666 assert!(session.cut_at(2.0 / 30.0), "two frames of it");
667 assert!(session.delete_clip(engine::project::Lane::V1, 1));
668 let out = Scratch::file("ve_av1_sound", ext);
669 let settings = ExportSettings {
670 format,
671 seat: engine::export::EncoderSeat::Software,
672 ..Default::default()
673 };
674 let handle = session.export_to_with(&out, &settings);
675 let started = Instant::now();
676 while !handle.is_finished() {
677 assert!(started.elapsed() < Duration::from_secs(900), "export hung");
678 std::thread::sleep(Duration::from_millis(20));
679 }
680 handle.result().expect("outcome").expect("an AV1 export");
681
682 // The picture, through the demuxer an import comes in by -- an `av01`
683 // sample entry in the mp4 and a `V_AV1` track in the Matroska file, both
684 // of them written by hand and read back by hand.
685 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
686 assert_eq!(meta.codec, Codec::Av1, "{ext}: an AV1 export is AV1");
687 assert_eq!((meta.width, meta.height), (1280, 720), "{ext}");
688 assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there");
689
690 // ...and the sound beside it, which is the half that used to be absent.
691 let (audio, chunks) = AudioSession::open(&out)
692 .expect("reopen for its sound")
693 .expect("an AV1 export has an audio track");
694 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
695 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
696 println!(
697 "{ext}: {} Hz x{}, rms {rms:.4}",
698 audio.sample_rate, audio.channels
699 );
700 assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})");
701 std::fs::remove_file(&out).unwrap();
702 }
703}
704
705/// A WebM export is the AV1 picture with Opus sound, and says so in its header:
706/// the EBML doc type is `webm`, the tracks are `V_AV1` and `A_OPUS` and no AAC
707/// track is written anywhere. Two frames, as above.
708#[test]
709fn a_webm_export_is_av1_with_opus_sound_under_a_webm_doc_type() {
710 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av");
711 assert!(session.cut_at(2.0 / 30.0), "two frames of it");
712 assert!(session.delete_clip(engine::project::Lane::V1, 1));
713 let out = Scratch::file("ve_webm", "webm");
714 let settings = ExportSettings {
715 format: engine::export::Format::Webm,
716 seat: engine::export::EncoderSeat::Software,
717 ..Default::default()
718 };
719 let handle = session.export_to_with(&out, &settings);
720 let started = Instant::now();
721 while !handle.is_finished() {
722 assert!(started.elapsed() < Duration::from_secs(900), "export hung");
723 std::thread::sleep(Duration::from_millis(20));
724 }
725 handle.result().expect("outcome").expect("a WebM export");
726
727 // The header, read by hand: the first element is EBML, and its DocType is
728 // the string `webm`, not `matroska`.
729 let bytes = std::fs::read(&out).unwrap();
730 assert_eq!(&bytes[..4], &[0x1A, 0x45, 0xDF, 0xA3], "an EBML file");
731 let head = &bytes[..bytes.len().min(64)];
732 assert!(
733 head.windows(4).any(|w| w == b"webm"),
734 "the EBML doc type is webm"
735 );
736 assert!(
737 !bytes.windows(8).any(|w| w == b"matroska"),
738 "no matroska doc type anywhere"
739 );
740 let has = |id: &[u8]| bytes.windows(id.len()).any(|w| w == id);
741 assert!(has(b"V_AV1"), "an AV1 track");
742 assert!(has(b"A_OPUS"), "an Opus track");
743 assert!(!has(b"A_AAC"), "no AAC track in a WebM");
744
745 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
746 assert_eq!(meta.codec, Codec::Av1, "the picture is AV1");
747 assert_eq!(meta.frame_count, 2, "every timeline frame is there");
748 let (audio, chunks) = AudioSession::open(&out)
749 .expect("reopen for its sound")
750 .expect("a WebM export has an audio track");
751 assert_eq!(audio.sample_rate, 48_000, "Opus codes at 48 kHz");
752 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
753 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
754 assert!(rms > 0.001, "the sound is in the file (rms {rms})");
755 std::fs::remove_file(&out).unwrap();
756}
757
758/// An audio-only timeline is refused an AV1 export by name, exactly as it is
759/// refused an mp4: every frame of it is a gap, so the file would be black.
760#[test]
761fn an_av1_export_of_an_audio_only_timeline_is_refused_by_name() {
762 let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone");
763 let out = Scratch::file("ve_av1_refused", "mkv");
764 let handle = session.export_to_with(&out, &av1_settings());
765 while !handle.is_finished() {
766 std::thread::sleep(Duration::from_millis(10));
767 }
768 let refused = handle
769 .result()
770 .expect("outcome")
771 .expect_err("an audio-only timeline has no picture to code")
772 .to_string();
773 assert!(refused.contains("no picture"), "{refused}");
774 assert!(refused.contains("AV1"), "{refused}");
775 assert!(!out.exists(), "nothing is written for a refusal");
776}
777
778/// The whole loop, and the only place it is closed: the file the export wrote is
779/// decoded back into pictures, and those pictures are the source's.
780#[test]
781#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
782fn an_av1_export_decodes_back_into_the_pictures_that_went_in() {
783 let _seat = seat::hardware();
784 let session = short_timeline(30.0);
785 let out = exported(
786 &session,
787 "roundtrip",
788 &av1_settings(),
789 Duration::from_secs(900),
790 );
791
792 let (_, frames) = DecodeSession::open(&out).expect("decode the export");
793 let frames: Vec<_> = frames.into_iter().collect();
794 assert_eq!(frames.len(), 30, "every written frame decodes back");
795 let (_, source, _) = DecodeSession::open_range(asset("test_baseline.mp4"), 0, 30)
796 .expect("open the source again");
797 let source: Vec<_> = source.into_iter().collect();
798 for (i, (written, original)) in frames.iter().zip(&source).enumerate() {
799 let diff: f64 = written
800 .bgra
801 .iter()
802 .zip(&original.bgra)
803 .map(|(a, b)| f64::from(a.abs_diff(*b)))
804 .sum::<f64>()
805 / written.bgra.len() as f64;
806 assert!(
807 diff < 12.0,
808 "frame {i} drifted by {diff:.2} from the source"
809 );
810 }
811 std::fs::remove_file(&out).unwrap();
812}
813
814/// The hardware seat of the same pair, which is opt-in: `VE_HW_AV1=1` is what
815/// enters it, because the vendored encoder reset the GPU of the box this was
816/// written on (see `export::Enc::open_av1`). Without that variable this measures
817/// the software encoder again, which is the honest outcome rather than a
818/// failure, so what it asserts is the file.
819#[test]
820#[ignore = "needs libengine_hw.so, VE_HW_AV1=1 and a driver whose AV1 encoder survives it"]
821fn an_av1_export_runs_on_the_plugin_where_the_gpu_has_one() {
822 let _seat = seat::hardware();
823 let session = short_timeline(60.0);
824 let settings = ExportSettings {
825 format: engine::export::Format::Av1,
826 ..Default::default()
827 };
828 let out = exported(&session, "hw", &settings, Duration::from_secs(600));
829 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
830 assert_eq!(meta.codec, Codec::Av1);
831 assert_eq!(meta.frame_count, 60);
832 std::fs::remove_file(&out).unwrap();
833}
834
835/// 4:4:4, 4:2:2 and 12-bit AV1 open in both containers and decode every frame
836/// on the software seat, their chroma averaged down to 4:2:0 and 12 bits
837/// narrowed (see `av1_chroma_edith.rs` for the match against ffmpeg).
838#[test]
839fn a_non_420_av1_file_opens_and_decodes() {
840 let _seat = seat::software();
841 for (name, depth) in [("test_av1_444", 8), ("test_av1_422", 8), ("test_av1_12bit", 12)] {
842 for ext in ["mkv", "mp4"] {
843 let file = asset(&format!("{name}.{ext}"));
844 let (meta, demuxer) = Demuxer::open(&file).unwrap_or_else(|e| panic!("{name}.{ext}: {e}"));
845 assert_eq!(meta.codec, Codec::Av1, "{name}.{ext}");
846 assert!(demuxer.bit_depth() >= depth, "{name}.{ext}");
847 let (_, rx) = DecodeSession::open(file).unwrap_or_else(|e| panic!("{name}.{ext}: {e}"));
848 assert_eq!(rx.into_iter().count(), meta.frame_count as usize, "{name}.{ext}");
849 }
850 }
851}
852
853/// 8-bit and 10-bit 4:2:0
854/// open with the right depth and decode every frame on the software seat.
855#[test]
856fn a_420_av1_file_in_either_container_opens_and_decodes() {
857 let _seat = seat::software();
858 for name in [
859 "test_av1_420.mkv",
860 "test_av1_420.mp4",
861 "test_av1_420_10.mkv",
862 "test_av1_420_10.mp4",
863 ] {
864 let (meta, demuxer) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
865 assert_eq!(meta.codec, Codec::Av1, "{name}");
866 assert_eq!((meta.width, meta.height), (64, 64), "{name}");
867 assert_eq!(meta.frame_count, 3, "{name}");
868 let depth = if name.contains("_10.") { 10 } else { 8 };
869 assert_eq!(demuxer.bit_depth(), depth, "{name}");
870
871 let (_, rx) = DecodeSession::open(asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
872 let count = rx.into_iter().count();
873 assert_eq!(count, 3, "{name}: every frame came out");
874 }
875}
876
877/// Monochrome (`gray`, the `av1C` mono flag): the one chroma-less shape edith
878/// is still willing to open. It is taken only if the seat decodes it into the
879/// I420 planes every converter reads; this asserts it does, frame for frame.
880#[test]
881fn a_monochrome_av1_file_opens_and_decodes() {
882 let _seat = seat::software();
883 for name in ["test_av1_gray.mkv", "test_av1_gray.mp4"] {
884 let (meta, _) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
885 assert_eq!(meta.codec, Codec::Av1, "{name}");
886 let (_, rx) = DecodeSession::open(asset(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
887 let count = rx.into_iter().count();
888 assert_eq!(count, 3, "{name}: every frame came out");
889 }
890}