forge
Explore
Log in

Don't you dare go Hollow

AV1 import via the VA-API plugin

Browse files at this commit

6d3e3bacf6df37920fb4e7abf15a2785370042c8Ahmet Kaan GümüşParent: 3395f94
  • feat
    • AV1 import via the VA-API plugin
Show full message
✨ feat(engine): AV1 import via the VA-API plugin

AV1 arrives in Matroska, never in an mp4 -- `mp4 0.14` knows no `av01`
sample entry at all -- so the demuxer grows a second container:
`MkvDemuxer` walks the EBML itself, indexes every block of the AV1 track
in one header-only pass (payloads are seeked over) and hands each block
to the decoder as the temporal unit it is, with the `av1C` sequence
header re-injected ahead of every keyframe the way the H.264 parameter
sets are.

Matroska indexes neither the frame count nor the frame rate, which is why
that walk exists: the count is the blocks of the track and the rate is
`DefaultDuration` in nanoseconds (33333333 = 30 fps to seven digits,
where the millisecond block timestamps beside it would say 30.30).
Keyframe flags come out of the same pass, so a seek lands on a sync point
without a Cues element and without guessing at the bitstream.

Audio is picture-only for now: a Matroska file is a silent source and
says so by name ("A_AAC audio in a Matroska file is not wired to the
decoder yet") rather than failing in the mp4 reader's words. 10- and
12-bit AV1 are refused at open like HEVC Main 10, for the same 8-bit
read-back reason.

No new dependency: symphonia's mkv reader drops the keyframe flag and
`DefaultDuration` and offers no frame count, so it could not have done
the job. edith keeps its 7 DT_NEEDED entries.
crates/engine-hw/src/lib.rsmodified+12 -5
@@ -1,4 +1,4 @@
1-//! VA-API decode (H.264, HEVC and VP9) and H.264 encode, shipped as a1+//! VA-API decode (H.264, HEVC, VP9 and AV1) and H.264 encode, shipped as a
2 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on2 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
3 //! libva/gbm/drm. Every entry point is3 //! libva/gbm/drm. Every entry point is
4 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a4 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a
@@ -18,6 +18,7 @@ use std::rc::Rc;
18 use cros_codecs::backend::vaapi::decoder::VaapiBackend;18 use cros_codecs::backend::vaapi::decoder::VaapiBackend;
19 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;19 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
20 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};20 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
21+use cros_codecs::decoder::stateless::av1::Av1;
21 use cros_codecs::decoder::stateless::h264::H264;22 use cros_codecs::decoder::stateless::h264::H264;
22 use cros_codecs::decoder::stateless::h265::H265;23 use cros_codecs::decoder::stateless::h265::H265;
23 use cros_codecs::decoder::stateless::vp9::Vp9;24 use cros_codecs::decoder::stateless::vp9::Vp9;
@@ -53,14 +54,16 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
53 /// still loads and still decodes H.264 (it simply refuses the newer codecs'54 /// still loads and still decodes H.264 (it simply refuses the newer codecs'
54 /// files at `Demuxer`).55 /// files at `Demuxer`).
55 ///56 ///
56-/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0 and HEVC Main. VP9 profile 2 and57+/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP9
57-/// HEVC Main 10 decode 10-bit, which the NV12 pool and the `vaGetImage`58+/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV12
58-/// read-back here cannot carry (`Demuxer` refuses Main 10 by name); the upgrade59+/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses
59-/// path is a P010 pool selected from the stream info.60+/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool
61+/// selected from the stream info.
60 enum Decoder {62 enum Decoder {
61 H264(Dec<H264>),63 H264(Dec<H264>),
62 Hevc(Dec<H265>),64 Hevc(Dec<H265>),
63 Vp9(Dec<Vp9>),65 Vp9(Dec<Vp9>),
66+ Av1(Dec<Av1>),
64 }67 }
65 68
66 impl Decoder {69 impl Decoder {
@@ -69,6 +72,7 @@ impl Decoder {
69 Self::H264(d) => d,72 Self::H264(d) => d,
70 Self::Hevc(d) => d,73 Self::Hevc(d) => d,
71 Self::Vp9(d) => d,74 Self::Vp9(d) => d,
75+ Self::Av1(d) => d,
72 }76 }
73 }77 }
74 }78 }
@@ -189,6 +193,9 @@ impl Session {
189 Codec::Vp9 => {193 Codec::Vp9 => {
190 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)194 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
191 }195 }
196+ Codec::Av1 => {
197+ Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
198+ }
192 };199 };
193 let pool = FramePool::new(move |info: &StreamInfo| {200 let pool = FramePool::new(move |info: &StreamInfo| {
194 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")201 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")
crates/engine/src/audio.rsmodified+23 -0
@@ -298,6 +298,17 @@ impl AudioSession {
298 /// -- nothing to tell the user there. Header only, and only worth calling298 /// -- nothing to tell the user there. Header only, and only worth calling
299 /// once the open has already returned no audio.299 /// once the open has already returned no audio.
300 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {300 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
301+ // Matroska: the demuxer reads its picture and nothing else yet, so a
302+ // file that has sound is told so by name rather than playing silent
303+ // with no reason given. A Matroska file with no audio track at all
304+ // returns `None` here like any other silent file.
305+ if crate::demux::is_matroska(path.as_ref()) {
306+ return Ok(
307+ crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {
308+ format!("{codec} audio in a Matroska file is not wired to the decoder yet")
309+ }),
310+ );
311+ }
301 let file = File::open(path.as_ref())?;312 let file = File::open(path.as_ref())?;
302 let size = file.metadata()?.len();313 let size = file.metadata()?.len();
303 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;314 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
@@ -343,6 +354,12 @@ impl AudioSession {
343 /// and an ALAC `.m4a` only half is.354 /// and an ALAC `.m4a` only half is.
344 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {355 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
345 let path = path.as_ref();356 let path = path.as_ref();
357+ // A Matroska file's audio tracks are not readable here yet ([`Track`]),
358+ // and a stream nothing can open is not one to offer: an mkv lists as
359+ // the silent source it currently is.
360+ if crate::demux::is_matroska(path) {
361+ return Ok(Vec::new());
362+ }
346 if crate::is_audio(path) {363 if crate::is_audio(path) {
347 let track = SymTrack::open(path)?;364 let track = SymTrack::open(path)?;
348 return Ok(vec![StreamInfo {365 return Ok(vec![StreamInfo {
@@ -638,6 +655,12 @@ impl Track {
638 /// has exactly one, so any `stream` above 0 there is a promise the file655 /// has exactly one, so any `stream` above 0 there is a promise the file
639 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.656 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
640 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {657 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
658+ // A Matroska file's sound is not wired to either reader yet: its picture
659+ // is what this slice delivers, and the source counts as a silent one --
660+ // which `AudioSession::unsupported` puts into words for the user.
661+ if crate::demux::is_matroska(path) {
662+ return Ok(None);
663+ }
641 let audio_file = crate::is_audio(path);664 let audio_file = crate::is_audio(path);
642 match AacTrack::open(path, stream) {665 match AacTrack::open(path, stream) {
643 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),666 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
crates/engine/src/demux.rsmodified+609 -9
@@ -1,6 +1,12 @@
1-//! MP4 demux: pulls the video track out as access units the decoders take --1+//! Container demux: pulls the video track out as access units the decoders take
2-//! Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP92+//! -- Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9
3-//! sample is a self-contained superframe already).3+//! sample is a self-contained superframe already) and for AV1, whose Matroska
4+//! block is one temporal unit in the low-overhead OBU format the decoder reads.
5+//!
6+//! Two containers, one interface: mp4 through the `mp4` crate, Matroska
7+//! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --
8+//! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in
9+//! practice.
4 10
5 use std::fs::File;11 use std::fs::File;
6 use std::io::{BufReader, Read, Seek, SeekFrom};12 use std::io::{BufReader, Read, Seek, SeekFrom};
@@ -20,6 +26,7 @@ pub enum Codec {
20 H264,26 H264,
21 Hevc,27 Hevc,
22 Vp9,28 Vp9,
29+ Av1,
23 }30 }
24 31
25 impl Codec {32 impl Codec {
@@ -29,6 +36,7 @@ impl Codec {
29 Self::H264 => "H.264",36 Self::H264 => "H.264",
30 Self::Hevc => "HEVC",37 Self::Hevc => "HEVC",
31 Self::Vp9 => "VP9",38 Self::Vp9 => "VP9",
39+ Self::Av1 => "AV1",
32 }40 }
33 }41 }
34 42
@@ -53,7 +61,55 @@ pub struct VideoMeta {
53 pub codec: Codec,61 pub codec: Codec,
54 }62 }
55 63
56-pub struct Demuxer {64+/// The file, whichever container it came in. Which one is decided by the
65+/// extension at [`Demuxer::open`] and never again: everything downstream --
66+/// playback, export, the plugin -- speaks access units and display frames.
67+pub enum Demuxer {
68+ Mp4(Mp4Demuxer),
69+ Mkv(MkvDemuxer),
70+}
71+
72+impl Demuxer {
73+ pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
74+ if is_matroska(path) {
75+ let (meta, mkv) = MkvDemuxer::open(path)?;
76+ return Ok((meta, Self::Mkv(mkv)));
77+ }
78+ let (meta, mp4) = Mp4Demuxer::open(path)?;
79+ Ok((meta, Self::Mp4(mp4)))
80+ }
81+
82+ /// Next access unit in decode order, `None` at end of track.
83+ pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
84+ match self {
85+ Self::Mp4(d) => d.next_access_unit(),
86+ Self::Mkv(d) => d.next_access_unit(),
87+ }
88+ }
89+
90+ /// Rewinds/forwards the read cursor to the latest sync sample at or before
91+ /// display frame `frame` (0-based), which is the earliest point a decoder
92+ /// can start from and still reach it. Returns the display index of the
93+ /// first picture the caller will now be handed.
94+ pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
95+ match self {
96+ Self::Mp4(d) => d.seek_to_sync_at_or_before(frame),
97+ Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),
98+ }
99+ }
100+}
101+
102+/// Whether a path names a Matroska file, which is where AV1 arrives. Extension
103+/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the
104+/// audio path has to know before it opens anything that this file's sound is
105+/// not one it reads (see [`crate::audio::AudioSession::unsupported`]).
106+pub fn is_matroska(path: &Path) -> bool {
107+ path.extension()
108+ .and_then(|e| e.to_str())
109+ .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm"))
110+}
111+
112+pub struct Mp4Demuxer {
57 reader: Mp4Reader<BufReader<File>>,113 reader: Mp4Reader<BufReader<File>>,
58 track_id: u32,114 track_id: u32,
59 sample_count: u32,115 sample_count: u32,
@@ -75,8 +131,8 @@ pub struct Demuxer {
75 next_sample: u32,131 next_sample: u32,
76 }132 }
77 133
78-impl Demuxer {134+impl Mp4Demuxer {
79- pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {135+ fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
80 let file = File::open(path)?;136 let file = File::open(path)?;
81 let size = file.metadata()?.len();137 let size = file.metadata()?.len();
82 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;138 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
@@ -131,7 +187,10 @@ impl Demuxer {
131 nal_length = len;187 nal_length = len;
132 parameter_sets = sets;188 parameter_sets = sets;
133 }189 }
134- Codec::Vp9 => {}190+ // No parameter sets: a VP9 sample is self-contained, and AV1 never
191+ // reaches this arm at all -- `mp4 0.14` knows no `av01` sample
192+ // entry, so AV1 only ever arrives through [`MkvDemuxer`].
193+ Codec::Vp9 | Codec::Av1 => {}
135 }194 }
136 let sync_samples = track195 let sync_samples = track
137 .trak196 .trak
@@ -170,7 +229,7 @@ impl Demuxer {
170 229
171 /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the230 /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the
172 /// mp4 sample verbatim for VP9. `None` at end of track.231 /// mp4 sample verbatim for VP9. `None` at end of track.
173- pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {232+ fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
174 if self.next_sample > self.sample_count {233 if self.next_sample > self.sample_count {
175 return Ok(None);234 return Ok(None);
176 }235 }
@@ -199,7 +258,7 @@ impl Demuxer {
199 /// picture the caller will now be handed -- *negative* when the landing sync258 /// picture the caller will now be handed -- *negative* when the landing sync
200 /// sample sits inside what the edit list trims, i.e. those pictures decode as259 /// sample sits inside what the edit list trims, i.e. those pictures decode as
201 /// references but are not frame 0 or later.260 /// references but are not frame 0 or later.
202- pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {261+ fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
203 let target = frame262 let target = frame
204 .saturating_add(self.first_sample)263 .saturating_add(self.first_sample)
205 .clamp(1, self.sample_count.max(1));264 .clamp(1, self.sample_count.max(1));
@@ -209,6 +268,483 @@ impl Demuxer {
209 }268 }
210 }269 }
211 270
271+/// One Matroska block of the video track: where its bytes are and whether a
272+/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7
273+/// MB of index -- the price of knowing the frame count and the sync points of a
274+/// container that indexes neither.
275+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276+struct Block {
277+ at: u64,
278+ len: usize,
279+ key: bool,
280+}
281+
282+/// AV1 out of a Matroska file (`.mkv`/`.webm`).
283+///
284+/// The whole segment is walked once at open -- element *headers* only, the block
285+/// payloads are seeked over -- because Matroska carries no sample table: the
286+/// frame count and the sync points exist nowhere else, and Cues index only some
287+/// keyframes and only when a muxer bothered to write them.
288+pub struct MkvDemuxer {
289+ file: File,
290+ blocks: Vec<Block>,
291+ /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
292+ /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream
293+ /// repeats its sequence header at every keyframe anyway, and cros-codecs
294+ /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
295+ /// free when the encoder already wrote one and load-bearing when it did not.
296+ config: Vec<u8>,
297+ next: usize,
298+}
299+
300+impl MkvDemuxer {
301+ fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
302+ let mut file = File::open(path)?;
303+ let end = file.metadata()?.len();
304+ let segment = mkv_segment(&mut file, end)?;
305+ let (video, _) = mkv_tracks(&mut file, segment)?;
306+ let video = video.ok_or(
307+ "no AV1 video track in this Matroska file — AV1 is the only codec read from one",
308+ )?;
309+ let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;
310+ if blocks.is_empty() {
311+ return Err("the AV1 track in this Matroska file has no frames".into());
312+ }
313+ // Timing, in this order: what the track declares, then what its own
314+ // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333
315+ // for 30 fps, 41708333 for 23.976 -- which is the whole reason it is
316+ // preferred; the fallback measures the presentation span instead, and
317+ // that is in `TimestampScale` ticks (a millisecond, as good as every
318+ // muxer writes), so it lands within ~0.05 % rather than exactly.
319+ //
320+ // ponytail: a genuinely variable-rate file is averaged to one rate here,
321+ // because a timeline frame is a fixed slice of a second everywhere else
322+ // in this engine. Per-frame durations are the upgrade path, and they are
323+ // a project-wide change, not a demuxer one.
324+ let frame_rate = match video.default_duration {
325+ Some(ns) => 1e9 / ns as f64,
326+ None => match span {
327+ Some((first, last)) if last > first && blocks.len() > 1 => {
328+ (blocks.len() - 1) as f64 * 1e9
329+ / ((last - first) as f64 * video.timestamp_scale as f64)
330+ }
331+ // Nothing said and nothing measurable: `fps_from_stts` answers
332+ // an mp4 with no timing the same way.
333+ _ => 0.0,
334+ },
335+ };
336+ let meta = VideoMeta {
337+ width: video.width,
338+ height: video.height,
339+ frame_rate,
340+ frame_count: blocks.len() as u32,
341+ codec: Codec::Av1,
342+ };
343+ Ok((
344+ meta,
345+ Self {
346+ file,
347+ blocks,
348+ config: video.config,
349+ next: 0,
350+ },
351+ ))
352+ }
353+
354+ fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
355+ let Some(&block) = self.blocks.get(self.next) else {
356+ return Ok(None);
357+ };
358+ self.next += 1;
359+ let head = if block.key { self.config.len() } else { 0 };
360+ let mut au = vec![0u8; head + block.len];
361+ au[..head].copy_from_slice(&self.config[..head]);
362+ read_exact_at(&mut self.file, block.at, &mut au[head..])?;
363+ Ok(Some(au))
364+ }
365+
366+ /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska
367+ /// has no edit list, so block 0 is frame 0.
368+ fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
369+ let target = (frame as usize).min(self.blocks.len().saturating_sub(1));
370+ // The keyframe at or before the target, or -- for a stream whose first
371+ // block is not one -- the earliest block there is, which is the only
372+ // place a decoder can be started from anyway.
373+ self.next = self.blocks[..=target]
374+ .iter()
375+ .rposition(|b| b.key)
376+ .unwrap_or(0);
377+ self.next as i64
378+ }
379+}
380+
381+/// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
382+/// `None` for a Matroska file with no sound at all. Header only, and only worth
383+/// calling once a session has come up silent: no audio track of a Matroska file
384+/// is decoded yet, so this exists to say which one is being left out.
385+pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
386+ let mut file = File::open(path)?;
387+ let end = file.metadata()?.len();
388+ let segment = mkv_segment(&mut file, end)?;
389+ Ok(mkv_tracks(&mut file, segment)?.1)
390+}
391+
392+/// What the `Tracks` element says about the AV1 track.
393+struct MkvVideo {
394+ number: u64,
395+ width: u32,
396+ height: u32,
397+ default_duration: Option<u64>,
398+ timestamp_scale: u64,
399+ config: Vec<u8>,
400+}
401+
402+// Matroska element IDs, written with the leading length marker they carry in
403+// the file, which is what `ebml_element` reads them back as.
404+const SEGMENT: u32 = 0x1853_8067;
405+const INFO: u32 = 0x1549_A966;
406+const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
407+const TRACKS: u32 = 0x1654_AE6B;
408+const TRACK_ENTRY: u32 = 0xAE;
409+const TRACK_NUMBER: u32 = 0xD7;
410+const TRACK_TYPE: u32 = 0x83;
411+const CODEC_ID: u32 = 0x86;
412+const CODEC_PRIVATE: u32 = 0x63A2;
413+const DEFAULT_DURATION: u32 = 0x23E383;
414+const VIDEO: u32 = 0xE0;
415+const PIXEL_WIDTH: u32 = 0xB0;
416+const PIXEL_HEIGHT: u32 = 0xBA;
417+const CLUSTER: u32 = 0x1F43_B675;
418+const CLUSTER_TIMESTAMP: u32 = 0xE7;
419+const SIMPLE_BLOCK: u32 = 0xA3;
420+const BLOCK_GROUP: u32 = 0xA0;
421+const BLOCK: u32 = 0xA1;
422+const REFERENCE_BLOCK: u32 = 0xFB;
423+
424+/// Body range of the file's `Segment` element, which everything else lives in.
425+fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
426+ let mut at = 0;
427+ while let Some(e) = ebml_element(file, at, end)? {
428+ if e.0 == SEGMENT {
429+ return Ok((e.1, e.2));
430+ }
431+ at = e.2;
432+ }
433+ Err("no Segment element: not a Matroska file".into())
434+}
435+
436+/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be
437+/// named -- the second is what tells a user why a file with sound plays silent
438+/// ([`crate::audio::AudioSession::unsupported`]).
439+///
440+/// Header only: the walk stops at the first `Cluster`, so this costs a handful
441+/// of seeks whatever the file weighs.
442+fn mkv_tracks(
443+ file: &mut File,
444+ segment: (u64, u64),
445+) -> crate::Result<(Option<MkvVideo>, Option<String>)> {
446+ let (mut video, mut audio) = (None, None);
447+ let mut timestamp_scale = 1_000_000;
448+ let mut at = segment.0;
449+ while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
450+ match id {
451+ CLUSTER => break,
452+ INFO => {
453+ let mut at = body;
454+ while let Some(e) = ebml_element(file, at, stop)? {
455+ if e.0 == TIMESTAMP_SCALE {
456+ timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1);
457+ }
458+ at = e.2;
459+ }
460+ }
461+ TRACKS => {
462+ let mut at = body;
463+ while let Some(e) = ebml_element(file, at, stop)? {
464+ if e.0 == TRACK_ENTRY {
465+ match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
466+ (Some(track), _) if video.is_none() => video = Some(track),
467+ (_, Some(codec)) if audio.is_none() => audio = Some(codec),
468+ _ => {}
469+ }
470+ }
471+ at = e.2;
472+ }
473+ }
474+ _ => {}
475+ }
476+ at = stop;
477+ }
478+ Ok((video, audio))
479+}
480+
481+/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id
482+/// of an audio track otherwise.
483+fn mkv_track_entry(
484+ file: &mut File,
485+ body: u64,
486+ end: u64,
487+ timestamp_scale: u64,
488+) -> crate::Result<(Option<MkvVideo>, Option<String>)> {
489+ let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
490+ let (mut width, mut height, mut config) = (0, 0, Vec::new());
491+ let mut at = body;
492+ while let Some((id, body, stop)) = ebml_element(file, at, end)? {
493+ match id {
494+ TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
495+ TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
496+ DEFAULT_DURATION => {
497+ default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
498+ }
499+ CODEC_ID => {
500+ codec = String::from_utf8_lossy(&ebml_bytes(file, body, stop)?).into_owned()
501+ }
502+ CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?,
503+ VIDEO => {
504+ let mut at = body;
505+ while let Some(e) = ebml_element(file, at, stop)? {
506+ match e.0 {
507+ PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
508+ PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,
509+ _ => {}
510+ }
511+ at = e.2;
512+ }
513+ }
514+ _ => {}
515+ }
516+ at = stop;
517+ }
518+ // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
519+ match (kind, codec.as_str()) {
520+ (1, "V_AV1") => Ok((
521+ Some(MkvVideo {
522+ number,
523+ width,
524+ height,
525+ default_duration,
526+ timestamp_scale,
527+ config: parse_av1c(&config)?,
528+ }),
529+ None,
530+ )),
531+ (2, _) => Ok((None, Some(codec))),
532+ _ => Ok((None, None)),
533+ }
534+}
535+
536+/// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
537+/// §2.3.3): four fixed bytes, then the sequence header OBU in the same
538+/// low-overhead format the blocks are in, so it needs no reframing.
539+///
540+/// An empty record is not an error -- an encoder that repeats its sequence
541+/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for
542+/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage`
543+/// read-back are 8-bit, and the upgrade path is a P010 pool.
544+fn parse_av1c(rec: &[u8]) -> crate::Result<Vec<u8>> {
545+ if rec.is_empty() {
546+ return Ok(Vec::new());
547+ }
548+ let &flags = rec
549+ .get(2)
550+ .ok_or("av1C record shorter than its fixed header")?;
551+ if flags & 0x40 != 0 {
552+ return Err(format!(
553+ "{}-bit AV1 is not supported yet — this file is not 8-bit",
554+ if flags & 0x20 != 0 { 12 } else { 10 }
555+ )
556+ .into());
557+ }
558+ Ok(rec.get(4..).unwrap_or_default().to_vec())
559+}
560+
561+/// Every block of track `number`, in storage order, with the presentation span
562+/// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
563+/// needs.
564+///
565+/// Only element headers are read: a block's payload is seeked over and fetched
566+/// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
567+/// pass rather than a read of the whole file.
568+fn mkv_blocks(
569+ file: &mut File,
570+ segment: (u64, u64),
571+ number: u64,
572+) -> crate::Result<(Vec<Block>, Option<(i64, i64)>)> {
573+ let mut blocks = Vec::new();
574+ let mut span: Option<(i64, i64)> = None;
575+ let mut at = segment.0;
576+ while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
577+ at = stop;
578+ if id != CLUSTER {
579+ continue;
580+ }
581+ let mut cluster_ts = 0i64;
582+ let mut child = body;
583+ while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
584+ child = stop;
585+ let (block, key) = match id {
586+ CLUSTER_TIMESTAMP => {
587+ cluster_ts = ebml_uint(file, body, stop)? as i64;
588+ continue;
589+ }
590+ SIMPLE_BLOCK => {
591+ let block = mkv_block(file, body, stop)?;
592+ // Bit 7 of the flags is the keyframe bit; a `Block` inside a
593+ // `BlockGroup` has no such bit, which is the case below.
594+ (block, block.flags & 0x80 != 0)
595+ }
596+ BLOCK_GROUP => {
597+ let (mut found, mut key) = (None, true);
598+ let mut child = body;
599+ while let Some(e) = ebml_element(file, child, stop)? {
600+ match e.0 {
601+ BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
602+ // A block that references another is not one a
603+ // decoder can be started from.
604+ REFERENCE_BLOCK => key = false,
605+ _ => {}
606+ }
607+ child = e.2;
608+ }
609+ match found {
610+ Some(block) => (block, key),
611+ None => continue,
612+ }
613+ }
614+ _ => continue,
615+ };
616+ if block.number != number {
617+ continue;
618+ }
619+ // Lacing packs several frames into one block. Audio muxers use it,
620+ // video ones do not, and guessing at frame boundaries inside a laced
621+ // block is not something to do silently.
622+ if block.flags & 0x06 != 0 {
623+ return Err("laced video blocks are not supported".into());
624+ }
625+ let ts = cluster_ts + i64::from(block.rel);
626+ span = Some(match span {
627+ Some((first, last)) => (first.min(ts), last.max(ts)),
628+ None => (ts, ts),
629+ });
630+ blocks.push(Block {
631+ at: block.at,
632+ len: block.len,
633+ key,
634+ });
635+ }
636+ }
637+ Ok((blocks, span))
638+}
639+
640+/// A `SimpleBlock`/`Block` header: track number, timestamp relative to the
641+/// cluster's, flags, and where the frame's own bytes start.
642+#[derive(Debug, Clone, Copy)]
643+struct BlockHeader {
644+ number: u64,
645+ rel: i16,
646+ flags: u8,
647+ at: u64,
648+ len: usize,
649+}
650+
651+fn mkv_block(file: &mut File, body: u64, stop: u64) -> crate::Result<BlockHeader> {
652+ let mut head = [0u8; 11];
653+ let n = read_at(file, body, &mut head)?;
654+ let (number, len) = ebml_vint(&head[..n], true)?;
655+ let rest = head[..n]
656+ .get(len..len + 3)
657+ .ok_or("truncated Matroska block header")?;
658+ let at = body + (len + 3) as u64;
659+ Ok(BlockHeader {
660+ number,
661+ rel: i16::from_be_bytes([rest[0], rest[1]]),
662+ flags: rest[2],
663+ at,
664+ len: stop.saturating_sub(at) as usize,
665+ })
666+}
667+
668+/// The EBML element at `at`: its id (marker bit and all), where its payload
669+/// starts, and where it ends. `None` once `end` is reached. An element of
670+/// unknown length -- what a muxer writes while it is still recording -- runs to
671+/// the end of its parent, which is exactly how a reader is told to take it.
672+fn ebml_element(file: &mut File, at: u64, end: u64) -> crate::Result<Option<(u32, u64, u64)>> {
673+ if at + 2 > end {
674+ return Ok(None);
675+ }
676+ let mut head = [0u8; 16];
677+ let n = read_at(file, at, &mut head[..(end - at).min(16) as usize])?;
678+ let (id, id_len) = ebml_vint(&head[..n], false)?;
679+ let (size, size_len) = ebml_vint(&head[id_len..n], true)?;
680+ let body = at + (id_len + size_len) as u64;
681+ let stop = match size {
682+ u64::MAX => end,
683+ size => body.saturating_add(size).min(end),
684+ };
685+ if body > end {
686+ return Err("truncated Matroska element header".into());
687+ }
688+ Ok(Some((id as u32, body, stop)))
689+}
690+
691+/// EBML variable-length integer: the leading zeros of the first byte say how
692+/// many bytes it takes. `strip` clears the marker bit, which is what a *size*
693+/// wants and an *id* does not -- an id is written and compared with it. An
694+/// all-ones size means unknown length, and comes back as [`u64::MAX`].
695+fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> {
696+ let &first = buf.first().ok_or("truncated EBML integer")?;
697+ if first == 0 {
698+ // A 9-byte-or-longer integer; Matroska defines none.
699+ return Err("bad EBML variable-length integer".into());
700+ }
701+ let len = first.leading_zeros() as usize + 1;
702+ let bytes = buf.get(..len).ok_or("truncated EBML integer")?;
703+ // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off
704+ // its own end, and the marker bit is then all the first byte was.
705+ let mut value = u64::from(if strip {
706+ first & (0xFFu16 >> len) as u8
707+ } else {
708+ first
709+ });
710+ for &b in &bytes[1..] {
711+ value = (value << 8) | u64::from(b);
712+ }
713+ if strip && value == (1u64 << (7 * len)) - 1 {
714+ return Ok((u64::MAX, len));
715+ }
716+ Ok((value, len))
717+}
718+
719+/// An EBML unsigned integer element: big-endian, as many bytes as it was
720+/// written with, and an absent one is a zero by the spec's own default.
721+fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
722+ Ok(ebml_bytes(file, body, stop)?
723+ .iter()
724+ .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
725+}
726+
727+/// The payload of an element, which is only ever a header field here -- 8 bytes
728+/// for an integer, a few hundred for a `CodecPrivate`.
729+fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {
730+ let len = stop.saturating_sub(body);
731+ if len > 1 << 20 {
732+ return Err("a Matroska header field larger than a megabyte".into());
733+ }
734+ let mut buf = vec![0u8; len as usize];
735+ read_exact_at(file, body, &mut buf)?;
736+ Ok(buf)
737+}
738+
739+/// Positioned reads, so the walk never has to keep a cursor in step with itself.
740+fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<usize> {
741+ std::os::unix::fs::FileExt::read_at(file, buf, at)
742+}
743+
744+fn read_exact_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
745+ std::os::unix::fs::FileExt::read_exact_at(file, buf, at)
746+}
747+
212 /// Frames per second off the sample table. `mp4 0.14`'s own748 /// Frames per second off the sample table. `mp4 0.14`'s own
213 /// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds*749 /// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds*
214 /// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat750 /// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat
@@ -514,6 +1050,70 @@ mod tests {
514 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());1050 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
515 }1051 }
516 1052
1053+ /// EBML's variable-length integers, which every Matroska read starts with:
1054+ /// the leading zeros of the first byte are the length, an *id* keeps its
1055+ /// marker bit and a *size* loses it, and an all-ones size is "unknown".
1056+ #[test]
1057+ fn ebml_integers_read_ids_and_sizes_differently() {
1058+ // The Segment id, 4 bytes, marker kept.
1059+ assert_eq!(
1060+ ebml_vint(&[0x18, 0x53, 0x80, 0x67], false).unwrap(),
1061+ (SEGMENT as u64, 4)
1062+ );
1063+ // A one-byte id, and the same byte read as a size is its low 7 bits.
1064+ assert_eq!(ebml_vint(&[0xA3], false).unwrap(), (0xA3, 1));
1065+ assert_eq!(ebml_vint(&[0xA3], true).unwrap(), (0x23, 1));
1066+ // Sizes: 0x4143 is 323 bytes, not 0x4143.
1067+ assert_eq!(ebml_vint(&[0x41, 0x43], true).unwrap(), (323, 2));
1068+ // Unknown length -- what a muxer writes while still recording.
1069+ assert_eq!(ebml_vint(&[0xFF], true).unwrap().0, u64::MAX);
1070+ assert_eq!(
1071+ ebml_vint(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], true)
1072+ .unwrap()
1073+ .0,
1074+ u64::MAX
1075+ );
1076+ // Nothing is read past the end of the buffer, and a zero first byte is
1077+ // a 9-byte integer Matroska never writes.
1078+ assert!(ebml_vint(&[0x41], true).is_err());
1079+ assert!(ebml_vint(&[], false).is_err());
1080+ assert!(ebml_vint(&[0x00, 1, 2], true).is_err());
1081+ }
1082+
1083+ /// The `av1C` record: four fixed bytes and then the sequence header OBU,
1084+ /// which is handed to the decoder as it stands. 10-bit is refused by name
1085+ /// exactly as HEVC Main 10 is, and for the same 8-bit read-back reason.
1086+ #[test]
1087+ fn reads_the_sequence_header_out_of_an_av1c_record() {
1088+ // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
1089+ // 13-byte sequence header OBU in low-overhead format.
1090+ let mut rec = vec![0x81, 0x05, 0x0C, 0x00];
1091+ rec.extend_from_slice(&[
1092+ 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
1093+ ]);
1094+ let config = parse_av1c(&rec).unwrap();
1095+ assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
1096+ assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
1097+
1098+ let mut ten = rec.clone();
1099+ ten[2] |= 0x40; // high_bitdepth
1100+ let refused = parse_av1c(&ten).unwrap_err().to_string();
1101+ assert!(refused.contains("10-bit"), "{refused}");
1102+ let mut twelve = ten.clone();
1103+ twelve[2] |= 0x20; // twelve_bit
1104+ assert!(
1105+ parse_av1c(&twelve)
1106+ .unwrap_err()
1107+ .to_string()
1108+ .contains("12-bit")
1109+ );
1110+
1111+ // An encoder that repeats its sequence header in-band writes no record
1112+ // at all, which is not an error; a truncated one is.
1113+ assert!(parse_av1c(&[]).unwrap().is_empty());
1114+ assert!(parse_av1c(&[0x81, 0x05]).is_err());
1115+ }
1116+
517 #[test]1117 #[test]
518 fn sync_lookup() {1118 fn sync_lookup() {
519 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");1119 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
crates/engine/tests/av1.rsadded+231 -0
@@ -0,0 +1,231 @@
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+//! The container and refusal checks need nothing installed. The decode and
6+//! export twins need a built `libengine_hw.so` and a VA-API driver with an AV1
7+//! decode entrypoint (`vainfo | grep AV1`), so they are `#[ignore]`d:
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 av1 -- --include-ignored --nocapture --test-threads=1
13+//! ```
14+//!
15+//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it
16+//! and puts it back so the hardware twins below really are hardware.
17+
18+use std::path::PathBuf;
19+use std::time::{Duration, Instant};
20+
21+use engine::demux::{Codec, Demuxer};
22+use engine::export::ExportSettings;
23+use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
24+
25+/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.
26+const FRAMES: u32 = 60;
27+const KEYFRAME: u32 = 30;
28+
29+fn asset(name: &str) -> PathBuf {
30+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31+ .join("../../assets")
32+ .join(name)
33+}
34+
35+/// The container half. Matroska indexes neither frames nor rate, so all three
36+/// numbers here come out of the walk: the count is the blocks of the track, the
37+/// rate is `DefaultDuration` in nanoseconds (33333333, i.e. 30 fps to seven
38+/// digits -- the millisecond timestamps beside it would say 30.30).
39+#[test]
40+fn the_demuxer_reports_an_av1_track_in_matroska() {
41+ let (meta, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
42+ assert_eq!(meta.codec, Codec::Av1);
43+ assert_eq!((meta.width, meta.height), (1280, 720));
44+ assert!(
45+ (meta.frame_rate - 30.0).abs() < 1e-6,
46+ "DefaultDuration must not truncate: {}",
47+ meta.frame_rate
48+ );
49+ assert_eq!(meta.frame_count, FRAMES);
50+
51+ // The invariant, stated as an assert: the mp4 codecs still say themselves.
52+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
53+ assert_eq!(h264.codec, Codec::H264);
54+ let (hevc, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
55+ assert_eq!(hevc.codec, Codec::Hevc);
56+ let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
57+ assert_eq!(vp9.codec, Codec::Vp9);
58+}
59+
60+/// The delivered audio scope, as an assert: this slice reads a Matroska file's
61+/// picture and not its sound, so the fixture's AAC track is *named* in the
62+/// notice a session shows rather than half-played or reported as an mp4 error.
63+#[test]
64+fn matroska_audio_is_not_wired_and_says_so() {
65+ let path = asset("test_av1.mkv");
66+ assert!(
67+ AudioSession::probe(&path, 0)
68+ .expect("probe must not fail")
69+ .is_none(),
70+ "an mkv is a silent source for now, not an error"
71+ );
72+ assert!(
73+ AudioSession::probe_streams(&path)
74+ .expect("streams")
75+ .is_empty()
76+ );
77+ let reason = AudioSession::unsupported(&path)
78+ .expect("unsupported")
79+ .expect("the fixture has an AAC track to name");
80+ assert!(reason.contains("A_AAC"), "{reason}");
81+ assert!(reason.contains("not wired"), "{reason}");
82+}
83+
84+/// Every block comes back, keyframes carry the sequence header, and the sync
85+/// index is what a seek lands on. An AV1 decoder cannot start without a
86+/// sequence header, and `mkv` carries it in `CodecPrivate` -- so this is the
87+/// check that says the `av1C` record was really parsed and re-injected.
88+#[test]
89+fn every_block_comes_back_and_keyframes_carry_the_sequence_header() {
90+ let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv");
91+ let first = demuxer
92+ .next_access_unit()
93+ .expect("read")
94+ .expect("a first access unit");
95+ // OBU header: bits 6..3 are the type, and 1 is a sequence header.
96+ assert_eq!(
97+ (first[0] >> 3) & 0xF,
98+ 1,
99+ "the keyframe leads with the sequence header"
100+ );
101+ assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
102+
103+ let mut count = 1;
104+ while demuxer.next_access_unit().expect("read").is_some() {
105+ count += 1;
106+ }
107+ assert_eq!(count, FRAMES, "every block came back out");
108+
109+ // The fixture is keyed every 30 frames, and a seek may only land on one:
110+ // anywhere in the second GOP rewinds to frame 30, anywhere in the first to
111+ // frame 0.
112+ assert_eq!(
113+ demuxer.seek_to_sync_at_or_before(KEYFRAME + 15),
114+ i64::from(KEYFRAME)
115+ );
116+ assert_eq!(
117+ demuxer.seek_to_sync_at_or_before(KEYFRAME),
118+ i64::from(KEYFRAME)
119+ );
120+ assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0);
121+ assert_eq!(demuxer.seek_to_sync_at_or_before(0), 0);
122+ assert_eq!(
123+ demuxer.seek_to_sync_at_or_before(FRAMES * 10),
124+ i64::from(KEYFRAME),
125+ "past the end clamps to the last sync point"
126+ );
127+ // And the access unit after a seek is the keyframe's, sequence header and
128+ // all -- a decoder restarted mid-file needs it exactly as much.
129+ let after = demuxer.next_access_unit().expect("read").expect("a unit");
130+ assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]);
131+}
132+
133+/// There is no software AV1 decoder, so the software path must refuse by name
134+/// rather than feed AV1 bytes to `rusty_h264` -- and it must refuse where a
135+/// caller can still show it, i.e. out of `open`, not from inside the worker.
136+#[test]
137+fn the_software_path_refuses_av1_by_name() {
138+ // SAFETY: the suite is documented to run with --test-threads=1.
139+ unsafe { std::env::set_var("VE_SW", "1") };
140+ let refused =
141+ DecodeSession::open(asset("test_av1.mkv")).expect_err("software must not accept AV1");
142+ let refused = refused.to_string();
143+ // Restored immediately: the hardware tests in this binary share the process.
144+ unsafe { std::env::remove_var("VE_SW") };
145+
146+ assert!(refused.contains("AV1"), "{refused}");
147+ assert!(refused.contains("plugin"), "{refused}");
148+}
149+
150+/// A timeline is refused a source coded differently, in the same words a
151+/// resolution mismatch is refused in: a front-end shows the string as it is.
152+#[test]
153+fn a_timeline_refuses_the_other_codec() {
154+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
155+ let refused = session
156+ .import(&asset("test_av1.mkv"))
157+ .expect_err("AV1 must not join an H.264 timeline")
158+ .to_string();
159+ assert!(refused.contains("AV1"), "{refused}");
160+ assert!(refused.contains("H.264"), "{refused}");
161+}
162+
163+/// The end-to-end user path: opening the file yields pictures, all of them,
164+/// through the plugin.
165+#[test]
166+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
167+fn the_plugin_decodes_every_av1_frame() {
168+ let start = Instant::now();
169+ let (meta, frames) = DecodeSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
170+ assert_eq!(meta.codec, Codec::Av1);
171+ let frames: Vec<_> = frames.into_iter().collect();
172+ eprintln!(
173+ "test_av1.mkv: {} frames in {:?}",
174+ frames.len(),
175+ start.elapsed()
176+ );
177+
178+ assert_eq!(frames.len() as u32, FRAMES, "every block decoded");
179+ for (i, frame) in frames.iter().enumerate() {
180+ assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
181+ assert_eq!(frame.index, i as u32, "frames arrive in display order");
182+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
183+ }
184+ // A picture, not a flat surface: a driver handing back an untouched buffer
185+ // would satisfy every count above.
186+ let first = &frames[0].bgra;
187+ assert!(
188+ first.chunks_exact(4).any(|px| px != &first[..4]),
189+ "frame 0 is a single colour -- no picture was decoded"
190+ );
191+}
192+
193+/// A seek into the second GOP hands back that very frame, not the keyframe it
194+/// had to restart from: the demuxer's sync index and the plugin's skip count
195+/// have to agree, and Matroska is where both are this crate's own doing.
196+#[test]
197+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
198+fn a_seek_lands_on_the_frame_it_asked_for() {
199+ let (_, frames, _cancel) =
200+ DecodeSession::open_range(asset("test_av1.mkv"), KEYFRAME + 7, FRAMES)
201+ .expect("open at a frame inside the second GOP");
202+ let frames: Vec<_> = frames.into_iter().collect();
203+ assert_eq!(frames.len() as u32, FRAMES - KEYFRAME - 7, "to the end");
204+ assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for");
205+}
206+
207+/// Export re-encodes to H.264 whatever the source was coded with -- and out of
208+/// a Matroska source it also has to write an mp4 the demuxer reads back.
209+#[test]
210+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
211+fn an_av1_source_exports_as_h264() {
212+ let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv");
213+ let meta = *session.meta();
214+ let project = Project::single(asset("test_av1.mkv"), meta.frame_count);
215+ let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id()));
216+ let _ = std::fs::remove_file(&out);
217+
218+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
219+ let started = Instant::now();
220+ while !handle.is_finished() {
221+ assert!(started.elapsed() < Duration::from_secs(120), "export hung");
222+ std::thread::sleep(Duration::from_millis(20));
223+ }
224+ handle.result().expect("outcome").expect("export");
225+
226+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
227+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
228+ assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
229+ assert_eq!((written.width, written.height), (1280, 720));
230+ let _ = std::fs::remove_file(&out);
231+}
scripts/gen_fixtures.shmodified+14 -0
@@ -85,6 +85,20 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
85 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \85 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
86 -map 0:v -map "[a]" -c:v libx265 -tag:v hev1 -pix_fmt yuv420p \86 -map 0:v -map "[a]" -c:v libx265 -tag:v hev1 -pix_fmt yuv420p \
87 -c:a aac -b:a 128k assets/test_hevc.mp487 -c:a aac -b:a 128k assets/test_hevc.mp4
88+# AV1 fixture, and the only Matroska one: `mp4 0.14` has no `av01` sample entry
89+# at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as
90+# the others so the tests measure the codec and nothing else -- but `-g 30` is
91+# not a preference: it puts a second keyframe at frame 30, which is what the
92+# sync index and the seek test are checked against. 8-bit Main profile, because
93+# the plugin's NV12 read-back cannot carry 10-bit. Its AAC track is deliberate
94+# too: Matroska audio is not wired to the decoder yet, and the notice that says
95+# so needs a track to name.
96+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
97+ -f lavfi -i "sine=frequency=440:duration=2" \
98+ -f lavfi -i "sine=frequency=880:duration=2" \
99+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
100+ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
101+ -c:a aac -b:a 128k assets/test_av1.mkv
88 # Mismatch fixture: different resolution and no audio track at all, so import102 # Mismatch fixture: different resolution and no audio track at all, so import
89 # has something concrete to refuse.103 # has something concrete to refuse.
90 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \104 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \