From 6d3e3bacf6df37920fb4e7abf15a2785370042c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 10:32:14 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20AV1=20import=20via?= =?UTF-8?q?=20the=20VA-API=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 17 +- crates/engine/src/audio.rs | 23 ++ crates/engine/src/demux.rs | 618 +++++++++++++++++++++++++++++++++++- crates/engine/tests/av1.rs | 231 ++++++++++++++ scripts/gen_fixtures.sh | 14 + 5 files changed, 889 insertions(+), 14 deletions(-) create mode 100644 crates/engine/tests/av1.rs diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 9b02540..578154e 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,4 +1,4 @@ -//! VA-API decode (H.264, HEVC and VP9) and H.264 encode, shipped as a +//! VA-API decode (H.264, HEVC, VP9 and AV1) and H.264 encode, shipped as a //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on //! libva/gbm/drm. Every entry point is //! `extern "C"`, catches unwinds and reports failure as a null pointer or a @@ -18,6 +18,7 @@ use std::rc::Rc; use cros_codecs::backend::vaapi::decoder::VaapiBackend; use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend; use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile}; +use cros_codecs::decoder::stateless::av1::Av1; use cros_codecs::decoder::stateless::h264::H264; use cros_codecs::decoder::stateless::h265::H265; use cros_codecs::decoder::stateless::vp9::Vp9; @@ -53,14 +54,16 @@ type Handle = as StatelessVideoDecoder>::Handle; /// still loads and still decodes H.264 (it simply refuses the newer codecs' /// files at `Demuxer`). /// -/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0 and HEVC Main. VP9 profile 2 and -/// HEVC Main 10 decode 10-bit, which the NV12 pool and the `vaGetImage` -/// read-back here cannot carry (`Demuxer` refuses Main 10 by name); the upgrade -/// path is a P010 pool selected from the stream info. +/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP9 +/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV12 +/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses +/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool +/// selected from the stream info. enum Decoder { H264(Dec), Hevc(Dec), Vp9(Dec), + Av1(Dec), } impl Decoder { @@ -69,6 +72,7 @@ impl Decoder { Self::H264(d) => d, Self::Hevc(d) => d, Self::Vp9(d) => d, + Self::Av1(d) => d, } } } @@ -189,6 +193,9 @@ impl Session { Codec::Vp9 => { Decoder::Vp9(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) } + Codec::Av1 => { + Decoder::Av1(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) + } }; let pool = FramePool::new(move |info: &StreamInfo| { alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed") diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index d3e44cc..d59e71e 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -298,6 +298,17 @@ impl AudioSession { /// -- nothing to tell the user there. Header only, and only worth calling /// once the open has already returned no audio. pub fn unsupported(path: impl AsRef) -> crate::Result> { + // Matroska: the demuxer reads its picture and nothing else yet, so a + // file that has sound is told so by name rather than playing silent + // with no reason given. A Matroska file with no audio track at all + // returns `None` here like any other silent file. + if crate::demux::is_matroska(path.as_ref()) { + return Ok( + crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { + format!("{codec} audio in a Matroska file is not wired to the decoder yet") + }), + ); + } let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; @@ -343,6 +354,12 @@ impl AudioSession { /// and an ALAC `.m4a` only half is. pub fn probe_streams(path: impl AsRef) -> crate::Result> { let path = path.as_ref(); + // A Matroska file's audio tracks are not readable here yet ([`Track`]), + // and a stream nothing can open is not one to offer: an mkv lists as + // the silent source it currently is. + if crate::demux::is_matroska(path) { + return Ok(Vec::new()); + } if crate::is_audio(path) { let track = SymTrack::open(path)?; return Ok(vec![StreamInfo { @@ -638,6 +655,12 @@ impl Track { /// has exactly one, so any `stream` above 0 there is a promise the file /// cannot keep โ€” an `Err`, the same as naming a stream an mp4 does not have. fn open(path: &Path, stream: usize) -> crate::Result> { + // A Matroska file's sound is not wired to either reader yet: its picture + // is what this slice delivers, and the source counts as a silent one -- + // which `AudioSession::unsupported` puts into words for the user. + if crate::demux::is_matroska(path) { + return Ok(None); + } let audio_file = crate::is_audio(path); match AacTrack::open(path, stream) { Ok(Some(track)) => return Ok(Some(Self::Aac(track))), diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index bc0a081..aeda0a4 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1,6 +1,12 @@ -//! MP4 demux: pulls the video track out as access units the decoders take -- -//! Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9 -//! sample is a self-contained superframe already). +//! Container demux: pulls the video track out as access units the decoders take +//! -- Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9 +//! sample is a self-contained superframe already) and for AV1, whose Matroska +//! block is one temporal unit in the low-overhead OBU format the decoder reads. +//! +//! Two containers, one interface: mp4 through the `mp4` crate, Matroska +//! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists -- +//! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in +//! practice. use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; @@ -20,6 +26,7 @@ pub enum Codec { H264, Hevc, Vp9, + Av1, } impl Codec { @@ -29,6 +36,7 @@ impl Codec { Self::H264 => "H.264", Self::Hevc => "HEVC", Self::Vp9 => "VP9", + Self::Av1 => "AV1", } } @@ -53,7 +61,55 @@ pub struct VideoMeta { pub codec: Codec, } -pub struct Demuxer { +/// The file, whichever container it came in. Which one is decided by the +/// extension at [`Demuxer::open`] and never again: everything downstream -- +/// playback, export, the plugin -- speaks access units and display frames. +pub enum Demuxer { + Mp4(Mp4Demuxer), + Mkv(MkvDemuxer), +} + +impl Demuxer { + pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { + if is_matroska(path) { + let (meta, mkv) = MkvDemuxer::open(path)?; + return Ok((meta, Self::Mkv(mkv))); + } + let (meta, mp4) = Mp4Demuxer::open(path)?; + Ok((meta, Self::Mp4(mp4))) + } + + /// Next access unit in decode order, `None` at end of track. + pub fn next_access_unit(&mut self) -> crate::Result>> { + match self { + Self::Mp4(d) => d.next_access_unit(), + Self::Mkv(d) => d.next_access_unit(), + } + } + + /// Rewinds/forwards the read cursor to the latest sync sample at or before + /// display frame `frame` (0-based), which is the earliest point a decoder + /// can start from and still reach it. Returns the display index of the + /// first picture the caller will now be handed. + pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { + match self { + Self::Mp4(d) => d.seek_to_sync_at_or_before(frame), + Self::Mkv(d) => d.seek_to_sync_at_or_before(frame), + } + } +} + +/// Whether a path names a Matroska file, which is where AV1 arrives. Extension +/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the +/// audio path has to know before it opens anything that this file's sound is +/// not one it reads (see [`crate::audio::AudioSession::unsupported`]). +pub fn is_matroska(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm")) +} + +pub struct Mp4Demuxer { reader: Mp4Reader>, track_id: u32, sample_count: u32, @@ -75,8 +131,8 @@ pub struct Demuxer { next_sample: u32, } -impl Demuxer { - pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { +impl Mp4Demuxer { + fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { let file = File::open(path)?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; @@ -131,7 +187,10 @@ impl Demuxer { nal_length = len; parameter_sets = sets; } - Codec::Vp9 => {} + // No parameter sets: a VP9 sample is self-contained, and AV1 never + // reaches this arm at all -- `mp4 0.14` knows no `av01` sample + // entry, so AV1 only ever arrives through [`MkvDemuxer`]. + Codec::Vp9 | Codec::Av1 => {} } let sync_samples = track .trak @@ -170,7 +229,7 @@ impl Demuxer { /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the /// mp4 sample verbatim for VP9. `None` at end of track. - pub fn next_access_unit(&mut self) -> crate::Result>> { + fn next_access_unit(&mut self) -> crate::Result>> { if self.next_sample > self.sample_count { return Ok(None); } @@ -199,7 +258,7 @@ impl Demuxer { /// picture the caller will now be handed -- *negative* when the landing sync /// sample sits inside what the edit list trims, i.e. those pictures decode as /// references but are not frame 0 or later. - pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { + fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { let target = frame .saturating_add(self.first_sample) .clamp(1, self.sample_count.max(1)); @@ -209,6 +268,483 @@ impl Demuxer { } } +/// One Matroska block of the video track: where its bytes are and whether a +/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7 +/// MB of index -- the price of knowing the frame count and the sync points of a +/// container that indexes neither. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Block { + at: u64, + len: usize, + key: bool, +} + +/// AV1 out of a Matroska file (`.mkv`/`.webm`). +/// +/// The whole segment is walked once at open -- element *headers* only, the block +/// payloads are seeked over -- because Matroska carries no sample table: the +/// frame count and the sync points exist nowhere else, and Cues index only some +/// keyframes and only when a muxer bothered to write them. +pub struct MkvDemuxer { + file: File, + blocks: Vec, + /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of + /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream + /// repeats its sequence header at every keyframe anyway, and cros-codecs + /// ignores one identical to the sequence in force (`av1.rs:381`), so this is + /// free when the encoder already wrote one and load-bearing when it did not. + config: Vec, + next: usize, +} + +impl MkvDemuxer { + fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { + let mut file = File::open(path)?; + let end = file.metadata()?.len(); + let segment = mkv_segment(&mut file, end)?; + let (video, _) = mkv_tracks(&mut file, segment)?; + let video = video.ok_or( + "no AV1 video track in this Matroska file โ€” AV1 is the only codec read from one", + )?; + let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; + if blocks.is_empty() { + return Err("the AV1 track in this Matroska file has no frames".into()); + } + // Timing, in this order: what the track declares, then what its own + // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333 + // for 30 fps, 41708333 for 23.976 -- which is the whole reason it is + // preferred; the fallback measures the presentation span instead, and + // that is in `TimestampScale` ticks (a millisecond, as good as every + // muxer writes), so it lands within ~0.05 % rather than exactly. + // + // ponytail: a genuinely variable-rate file is averaged to one rate here, + // because a timeline frame is a fixed slice of a second everywhere else + // in this engine. Per-frame durations are the upgrade path, and they are + // a project-wide change, not a demuxer one. + let frame_rate = match video.default_duration { + Some(ns) => 1e9 / ns as f64, + None => match span { + Some((first, last)) if last > first && blocks.len() > 1 => { + (blocks.len() - 1) as f64 * 1e9 + / ((last - first) as f64 * video.timestamp_scale as f64) + } + // Nothing said and nothing measurable: `fps_from_stts` answers + // an mp4 with no timing the same way. + _ => 0.0, + }, + }; + let meta = VideoMeta { + width: video.width, + height: video.height, + frame_rate, + frame_count: blocks.len() as u32, + codec: Codec::Av1, + }; + Ok(( + meta, + Self { + file, + blocks, + config: video.config, + next: 0, + }, + )) + } + + fn next_access_unit(&mut self) -> crate::Result>> { + let Some(&block) = self.blocks.get(self.next) else { + return Ok(None); + }; + self.next += 1; + let head = if block.key { self.config.len() } else { 0 }; + let mut au = vec![0u8; head + block.len]; + au[..head].copy_from_slice(&self.config[..head]); + read_exact_at(&mut self.file, block.at, &mut au[head..])?; + Ok(Some(au)) + } + + /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska + /// has no edit list, so block 0 is frame 0. + fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 { + let target = (frame as usize).min(self.blocks.len().saturating_sub(1)); + // The keyframe at or before the target, or -- for a stream whose first + // block is not one -- the earliest block there is, which is the only + // place a decoder can be started from anyway. + self.next = self.blocks[..=target] + .iter() + .rposition(|b| b.key) + .unwrap_or(0); + self.next as i64 + } +} + +/// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or +/// `None` for a Matroska file with no sound at all. Header only, and only worth +/// calling once a session has come up silent: no audio track of a Matroska file +/// is decoded yet, so this exists to say which one is being left out. +pub fn matroska_audio_codec(path: &Path) -> crate::Result> { + let mut file = File::open(path)?; + let end = file.metadata()?.len(); + let segment = mkv_segment(&mut file, end)?; + Ok(mkv_tracks(&mut file, segment)?.1) +} + +/// What the `Tracks` element says about the AV1 track. +struct MkvVideo { + number: u64, + width: u32, + height: u32, + default_duration: Option, + timestamp_scale: u64, + config: Vec, +} + +// Matroska element IDs, written with the leading length marker they carry in +// the file, which is what `ebml_element` reads them back as. +const SEGMENT: u32 = 0x1853_8067; +const INFO: u32 = 0x1549_A966; +const TIMESTAMP_SCALE: u32 = 0x2AD7B1; +const TRACKS: u32 = 0x1654_AE6B; +const TRACK_ENTRY: u32 = 0xAE; +const TRACK_NUMBER: u32 = 0xD7; +const TRACK_TYPE: u32 = 0x83; +const CODEC_ID: u32 = 0x86; +const CODEC_PRIVATE: u32 = 0x63A2; +const DEFAULT_DURATION: u32 = 0x23E383; +const VIDEO: u32 = 0xE0; +const PIXEL_WIDTH: u32 = 0xB0; +const PIXEL_HEIGHT: u32 = 0xBA; +const CLUSTER: u32 = 0x1F43_B675; +const CLUSTER_TIMESTAMP: u32 = 0xE7; +const SIMPLE_BLOCK: u32 = 0xA3; +const BLOCK_GROUP: u32 = 0xA0; +const BLOCK: u32 = 0xA1; +const REFERENCE_BLOCK: u32 = 0xFB; + +/// Body range of the file's `Segment` element, which everything else lives in. +fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { + let mut at = 0; + while let Some(e) = ebml_element(file, at, end)? { + if e.0 == SEGMENT { + return Ok((e.1, e.2)); + } + at = e.2; + } + Err("no Segment element: not a Matroska file".into()) +} + +/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be +/// named -- the second is what tells a user why a file with sound plays silent +/// ([`crate::audio::AudioSession::unsupported`]). +/// +/// Header only: the walk stops at the first `Cluster`, so this costs a handful +/// of seeks whatever the file weighs. +fn mkv_tracks( + file: &mut File, + segment: (u64, u64), +) -> crate::Result<(Option, Option)> { + let (mut video, mut audio) = (None, None); + let mut timestamp_scale = 1_000_000; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + match id { + CLUSTER => break, + INFO => { + let mut at = body; + while let Some(e) = ebml_element(file, at, stop)? { + if e.0 == TIMESTAMP_SCALE { + timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1); + } + at = e.2; + } + } + TRACKS => { + let mut at = body; + while let Some(e) = ebml_element(file, at, stop)? { + if e.0 == TRACK_ENTRY { + match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { + (Some(track), _) if video.is_none() => video = Some(track), + (_, Some(codec)) if audio.is_none() => audio = Some(codec), + _ => {} + } + } + at = e.2; + } + } + _ => {} + } + at = stop; + } + Ok((video, audio)) +} + +/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id +/// of an audio track otherwise. +fn mkv_track_entry( + file: &mut File, + body: u64, + end: u64, + timestamp_scale: u64, +) -> crate::Result<(Option, Option)> { + let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); + let (mut width, mut height, mut config) = (0, 0, Vec::new()); + let mut at = body; + while let Some((id, body, stop)) = ebml_element(file, at, end)? { + match id { + TRACK_NUMBER => number = ebml_uint(file, body, stop)?, + TRACK_TYPE => kind = ebml_uint(file, body, stop)?, + DEFAULT_DURATION => { + default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) + } + CODEC_ID => { + codec = String::from_utf8_lossy(&ebml_bytes(file, body, stop)?).into_owned() + } + CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?, + VIDEO => { + let mut at = body; + while let Some(e) = ebml_element(file, at, stop)? { + match e.0 { + PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, + PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, + _ => {} + } + at = e.2; + } + } + _ => {} + } + at = stop; + } + // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here. + match (kind, codec.as_str()) { + (1, "V_AV1") => Ok(( + Some(MkvVideo { + number, + width, + height, + default_duration, + timestamp_scale, + config: parse_av1c(&config)?, + }), + None, + )), + (2, _) => Ok((None, Some(codec))), + _ => Ok((None, None)), + } +} + +/// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF +/// ยง2.3.3): four fixed bytes, then the sequence header OBU in the same +/// low-overhead format the blocks are in, so it needs no reframing. +/// +/// An empty record is not an error -- an encoder that repeats its sequence +/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for +/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage` +/// read-back are 8-bit, and the upgrade path is a P010 pool. +fn parse_av1c(rec: &[u8]) -> crate::Result> { + if rec.is_empty() { + return Ok(Vec::new()); + } + let &flags = rec + .get(2) + .ok_or("av1C record shorter than its fixed header")?; + if flags & 0x40 != 0 { + return Err(format!( + "{}-bit AV1 is not supported yet โ€” this file is not 8-bit", + if flags & 0x20 != 0 { 12 } else { 10 } + ) + .into()); + } + Ok(rec.get(4..).unwrap_or_default().to_vec()) +} + +/// Every block of track `number`, in storage order, with the presentation span +/// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback +/// needs. +/// +/// Only element headers are read: a block's payload is seeked over and fetched +/// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index +/// pass rather than a read of the whole file. +fn mkv_blocks( + file: &mut File, + segment: (u64, u64), + number: u64, +) -> crate::Result<(Vec, Option<(i64, i64)>)> { + let mut blocks = Vec::new(); + let mut span: Option<(i64, i64)> = None; + let mut at = segment.0; + while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + at = stop; + if id != CLUSTER { + continue; + } + let mut cluster_ts = 0i64; + let mut child = body; + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { + child = stop; + let (block, key) = match id { + CLUSTER_TIMESTAMP => { + cluster_ts = ebml_uint(file, body, stop)? as i64; + continue; + } + SIMPLE_BLOCK => { + let block = mkv_block(file, body, stop)?; + // Bit 7 of the flags is the keyframe bit; a `Block` inside a + // `BlockGroup` has no such bit, which is the case below. + (block, block.flags & 0x80 != 0) + } + BLOCK_GROUP => { + let (mut found, mut key) = (None, true); + let mut child = body; + while let Some(e) = ebml_element(file, child, stop)? { + match e.0 { + BLOCK => found = Some(mkv_block(file, e.1, e.2)?), + // A block that references another is not one a + // decoder can be started from. + REFERENCE_BLOCK => key = false, + _ => {} + } + child = e.2; + } + match found { + Some(block) => (block, key), + None => continue, + } + } + _ => continue, + }; + if block.number != number { + continue; + } + // Lacing packs several frames into one block. Audio muxers use it, + // video ones do not, and guessing at frame boundaries inside a laced + // block is not something to do silently. + if block.flags & 0x06 != 0 { + return Err("laced video blocks are not supported".into()); + } + let ts = cluster_ts + i64::from(block.rel); + span = Some(match span { + Some((first, last)) => (first.min(ts), last.max(ts)), + None => (ts, ts), + }); + blocks.push(Block { + at: block.at, + len: block.len, + key, + }); + } + } + Ok((blocks, span)) +} + +/// A `SimpleBlock`/`Block` header: track number, timestamp relative to the +/// cluster's, flags, and where the frame's own bytes start. +#[derive(Debug, Clone, Copy)] +struct BlockHeader { + number: u64, + rel: i16, + flags: u8, + at: u64, + len: usize, +} + +fn mkv_block(file: &mut File, body: u64, stop: u64) -> crate::Result { + let mut head = [0u8; 11]; + let n = read_at(file, body, &mut head)?; + let (number, len) = ebml_vint(&head[..n], true)?; + let rest = head[..n] + .get(len..len + 3) + .ok_or("truncated Matroska block header")?; + let at = body + (len + 3) as u64; + Ok(BlockHeader { + number, + rel: i16::from_be_bytes([rest[0], rest[1]]), + flags: rest[2], + at, + len: stop.saturating_sub(at) as usize, + }) +} + +/// The EBML element at `at`: its id (marker bit and all), where its payload +/// starts, and where it ends. `None` once `end` is reached. An element of +/// unknown length -- what a muxer writes while it is still recording -- runs to +/// the end of its parent, which is exactly how a reader is told to take it. +fn ebml_element(file: &mut File, at: u64, end: u64) -> crate::Result> { + if at + 2 > end { + return Ok(None); + } + let mut head = [0u8; 16]; + let n = read_at(file, at, &mut head[..(end - at).min(16) as usize])?; + let (id, id_len) = ebml_vint(&head[..n], false)?; + let (size, size_len) = ebml_vint(&head[id_len..n], true)?; + let body = at + (id_len + size_len) as u64; + let stop = match size { + u64::MAX => end, + size => body.saturating_add(size).min(end), + }; + if body > end { + return Err("truncated Matroska element header".into()); + } + Ok(Some((id as u32, body, stop))) +} + +/// EBML variable-length integer: the leading zeros of the first byte say how +/// many bytes it takes. `strip` clears the marker bit, which is what a *size* +/// wants and an *id* does not -- an id is written and compared with it. An +/// all-ones size means unknown length, and comes back as [`u64::MAX`]. +fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> { + let &first = buf.first().ok_or("truncated EBML integer")?; + if first == 0 { + // A 9-byte-or-longer integer; Matroska defines none. + return Err("bad EBML variable-length integer".into()); + } + let len = first.leading_zeros() as usize + 1; + let bytes = buf.get(..len).ok_or("truncated EBML integer")?; + // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off + // its own end, and the marker bit is then all the first byte was. + let mut value = u64::from(if strip { + first & (0xFFu16 >> len) as u8 + } else { + first + }); + for &b in &bytes[1..] { + value = (value << 8) | u64::from(b); + } + if strip && value == (1u64 << (7 * len)) - 1 { + return Ok((u64::MAX, len)); + } + Ok((value, len)) +} + +/// An EBML unsigned integer element: big-endian, as many bytes as it was +/// written with, and an absent one is a zero by the spec's own default. +fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result { + Ok(ebml_bytes(file, body, stop)? + .iter() + .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) +} + +/// The payload of an element, which is only ever a header field here -- 8 bytes +/// for an integer, a few hundred for a `CodecPrivate`. +fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result> { + let len = stop.saturating_sub(body); + if len > 1 << 20 { + return Err("a Matroska header field larger than a megabyte".into()); + } + let mut buf = vec![0u8; len as usize]; + read_exact_at(file, body, &mut buf)?; + Ok(buf) +} + +/// Positioned reads, so the walk never has to keep a cursor in step with itself. +fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result { + std::os::unix::fs::FileExt::read_at(file, buf, at) +} + +fn read_exact_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<()> { + std::os::unix::fs::FileExt::read_exact_at(file, buf, at) +} + /// Frames per second off the sample table. `mp4 0.14`'s own /// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds* /// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat @@ -514,6 +1050,70 @@ mod tests { assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); } + /// EBML's variable-length integers, which every Matroska read starts with: + /// the leading zeros of the first byte are the length, an *id* keeps its + /// marker bit and a *size* loses it, and an all-ones size is "unknown". + #[test] + fn ebml_integers_read_ids_and_sizes_differently() { + // The Segment id, 4 bytes, marker kept. + assert_eq!( + ebml_vint(&[0x18, 0x53, 0x80, 0x67], false).unwrap(), + (SEGMENT as u64, 4) + ); + // A one-byte id, and the same byte read as a size is its low 7 bits. + assert_eq!(ebml_vint(&[0xA3], false).unwrap(), (0xA3, 1)); + assert_eq!(ebml_vint(&[0xA3], true).unwrap(), (0x23, 1)); + // Sizes: 0x4143 is 323 bytes, not 0x4143. + assert_eq!(ebml_vint(&[0x41, 0x43], true).unwrap(), (323, 2)); + // Unknown length -- what a muxer writes while still recording. + assert_eq!(ebml_vint(&[0xFF], true).unwrap().0, u64::MAX); + assert_eq!( + ebml_vint(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], true) + .unwrap() + .0, + u64::MAX + ); + // Nothing is read past the end of the buffer, and a zero first byte is + // a 9-byte integer Matroska never writes. + assert!(ebml_vint(&[0x41], true).is_err()); + assert!(ebml_vint(&[], false).is_err()); + assert!(ebml_vint(&[0x00, 1, 2], true).is_err()); + } + + /// The `av1C` record: four fixed bytes and then the sequence header OBU, + /// which is handed to the decoder as it stands. 10-bit is refused by name + /// exactly as HEVC Main 10 is, and for the same 8-bit read-back reason. + #[test] + fn reads_the_sequence_header_out_of_an_av1c_record() { + // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a + // 13-byte sequence header OBU in low-overhead format. + let mut rec = vec![0x81, 0x05, 0x0C, 0x00]; + rec.extend_from_slice(&[ + 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00, + ]); + let config = parse_av1c(&rec).unwrap(); + assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs"); + assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header"); + + let mut ten = rec.clone(); + ten[2] |= 0x40; // high_bitdepth + let refused = parse_av1c(&ten).unwrap_err().to_string(); + assert!(refused.contains("10-bit"), "{refused}"); + let mut twelve = ten.clone(); + twelve[2] |= 0x20; // twelve_bit + assert!( + parse_av1c(&twelve) + .unwrap_err() + .to_string() + .contains("12-bit") + ); + + // An encoder that repeats its sequence header in-band writes no record + // at all, which is not an error; a truncated one is. + assert!(parse_av1c(&[]).unwrap().is_empty()); + assert!(parse_av1c(&[0x81, 0x05]).is_err()); + } + #[test] fn sync_lookup() { assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs"); diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs new file mode 100644 index 0000000..7b43c77 --- /dev/null +++ b/crates/engine/tests/av1.rs @@ -0,0 +1,231 @@ +//! AV1 import: the third source codec that is not H.264, and the first that +//! arrives in a container of its own -- `mp4 0.14` knows no `av01` sample entry +//! at all, so AV1 comes in as Matroska and the demuxer walks the EBML itself. +//! +//! The container and refusal checks need nothing installed. The decode and +//! export twins need a built `libengine_hw.so` and a VA-API driver with an AV1 +//! decode entrypoint (`vainfo | grep AV1`), so they are `#[ignore]`d: +//! +//! ```text +//! cargo build -p engine -p engine-hw --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test av1 -- --include-ignored --nocapture --test-threads=1 +//! ``` +//! +//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it +//! and puts it back so the hardware twins below really are hardware. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::export::ExportSettings; +use engine::{AudioSession, DecodeSession, PlaybackSession, Project}; + +/// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; +const KEYFRAME: u32 = 30; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The container half. Matroska indexes neither frames nor rate, so all three +/// numbers here come out of the walk: the count is the blocks of the track, the +/// rate is `DefaultDuration` in nanoseconds (33333333, i.e. 30 fps to seven +/// digits -- the millisecond timestamps beside it would say 30.30). +#[test] +fn the_demuxer_reports_an_av1_track_in_matroska() { + let (meta, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); + assert_eq!(meta.codec, Codec::Av1); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!( + (meta.frame_rate - 30.0).abs() < 1e-6, + "DefaultDuration must not truncate: {}", + meta.frame_rate + ); + assert_eq!(meta.frame_count, FRAMES); + + // The invariant, stated as an assert: the mp4 codecs still say themselves. + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); + assert_eq!(h264.codec, Codec::H264); + let (hevc, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + assert_eq!(hevc.codec, Codec::Hevc); + let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4"); + assert_eq!(vp9.codec, Codec::Vp9); +} + +/// The delivered audio scope, as an assert: this slice reads a Matroska file's +/// picture and not its sound, so the fixture's AAC track is *named* in the +/// notice a session shows rather than half-played or reported as an mp4 error. +#[test] +fn matroska_audio_is_not_wired_and_says_so() { + let path = asset("test_av1.mkv"); + assert!( + AudioSession::probe(&path, 0) + .expect("probe must not fail") + .is_none(), + "an mkv is a silent source for now, not an error" + ); + assert!( + AudioSession::probe_streams(&path) + .expect("streams") + .is_empty() + ); + let reason = AudioSession::unsupported(&path) + .expect("unsupported") + .expect("the fixture has an AAC track to name"); + assert!(reason.contains("A_AAC"), "{reason}"); + assert!(reason.contains("not wired"), "{reason}"); +} + +/// Every block comes back, keyframes carry the sequence header, and the sync +/// index is what a seek lands on. An AV1 decoder cannot start without a +/// sequence header, and `mkv` carries it in `CodecPrivate` -- so this is the +/// check that says the `av1C` record was really parsed and re-injected. +#[test] +fn every_block_comes_back_and_keyframes_carry_the_sequence_header() { + let (_, mut demuxer) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); + let first = demuxer + .next_access_unit() + .expect("read") + .expect("a first access unit"); + // OBU header: bits 6..3 are the type, and 1 is a sequence header. + assert_eq!( + (first[0] >> 3) & 0xF, + 1, + "the keyframe leads with the sequence header" + ); + assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format"); + + let mut count = 1; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!(count, FRAMES, "every block came back out"); + + // The fixture is keyed every 30 frames, and a seek may only land on one: + // anywhere in the second GOP rewinds to frame 30, anywhere in the first to + // frame 0. + assert_eq!( + demuxer.seek_to_sync_at_or_before(KEYFRAME + 15), + i64::from(KEYFRAME) + ); + assert_eq!( + demuxer.seek_to_sync_at_or_before(KEYFRAME), + i64::from(KEYFRAME) + ); + assert_eq!(demuxer.seek_to_sync_at_or_before(KEYFRAME - 1), 0); + assert_eq!(demuxer.seek_to_sync_at_or_before(0), 0); + assert_eq!( + demuxer.seek_to_sync_at_or_before(FRAMES * 10), + i64::from(KEYFRAME), + "past the end clamps to the last sync point" + ); + // And the access unit after a seek is the keyframe's, sequence header and + // all -- a decoder restarted mid-file needs it exactly as much. + let after = demuxer.next_access_unit().expect("read").expect("a unit"); + assert_eq!((after[0] >> 3) & 0xF, 1, "{}", after[0]); +} + +/// There is no software AV1 decoder, so the software path must refuse by name +/// rather than feed AV1 bytes to `rusty_h264` -- and it must refuse where a +/// caller can still show it, i.e. out of `open`, not from inside the worker. +#[test] +fn the_software_path_refuses_av1_by_name() { + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let refused = + DecodeSession::open(asset("test_av1.mkv")).expect_err("software must not accept AV1"); + let refused = refused.to_string(); + // Restored immediately: the hardware tests in this binary share the process. + unsafe { std::env::remove_var("VE_SW") }; + + assert!(refused.contains("AV1"), "{refused}"); + assert!(refused.contains("plugin"), "{refused}"); +} + +/// A timeline is refused a source coded differently, in the same words a +/// resolution mismatch is refused in: a front-end shows the string as it is. +#[test] +fn a_timeline_refuses_the_other_codec() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + let refused = session + .import(&asset("test_av1.mkv")) + .expect_err("AV1 must not join an H.264 timeline") + .to_string(); + assert!(refused.contains("AV1"), "{refused}"); + assert!(refused.contains("H.264"), "{refused}"); +} + +/// The end-to-end user path: opening the file yields pictures, all of them, +/// through the plugin. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn the_plugin_decodes_every_av1_frame() { + let start = Instant::now(); + let (meta, frames) = DecodeSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv"); + assert_eq!(meta.codec, Codec::Av1); + let frames: Vec<_> = frames.into_iter().collect(); + eprintln!( + "test_av1.mkv: {} frames in {:?}", + frames.len(), + start.elapsed() + ); + + assert_eq!(frames.len() as u32, FRAMES, "every block decoded"); + for (i, frame) in frames.iter().enumerate() { + assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims"); + assert_eq!(frame.index, i as u32, "frames arrive in display order"); + assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size"); + } + // A picture, not a flat surface: a driver handing back an untouched buffer + // would satisfy every count above. + let first = &frames[0].bgra; + assert!( + first.chunks_exact(4).any(|px| px != &first[..4]), + "frame 0 is a single colour -- no picture was decoded" + ); +} + +/// A seek into the second GOP hands back that very frame, not the keyframe it +/// had to restart from: the demuxer's sync index and the plugin's skip count +/// have to agree, and Matroska is where both are this crate's own doing. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn a_seek_lands_on_the_frame_it_asked_for() { + let (_, frames, _cancel) = + DecodeSession::open_range(asset("test_av1.mkv"), KEYFRAME + 7, FRAMES) + .expect("open at a frame inside the second GOP"); + let frames: Vec<_> = frames.into_iter().collect(); + assert_eq!(frames.len() as u32, FRAMES - KEYFRAME - 7, "to the end"); + assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for"); +} + +/// Export re-encodes to H.264 whatever the source was coded with -- and out of +/// a Matroska source it also has to write an mp4 the demuxer reads back. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn an_av1_source_exports_as_h264() { + let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv"); + let meta = *session.meta(); + let project = Project::single(asset("test_av1.mkv"), meta.frame_count); + let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id())); + let _ = std::fs::remove_file(&out); + + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(120), "export hung"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("export"); + + let (written, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(written.codec, Codec::H264, "exports are always H.264"); + assert_eq!(written.frame_count, FRAMES, "every timeline frame written"); + assert_eq!((written.width, written.height), (1280, 720)); + let _ = std::fs::remove_file(&out); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 3e8a629..b483b5d 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -85,6 +85,20 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libx265 -tag:v hev1 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_hevc.mp4 +# AV1 fixture, and the only Matroska one: `mp4 0.14` has no `av01` sample entry +# at all, so AV1 is read out of an mkv (`demux::MkvDemuxer`). Same A/V shape as +# the others so the tests measure the codec and nothing else -- but `-g 30` is +# not a preference: it puts a second keyframe at frame 30, which is what the +# sync index and the seek test are checked against. 8-bit Main profile, because +# the plugin's NV12 read-back cannot carry 10-bit. Its AAC track is deliberate +# too: Matroska audio is not wired to the decoder yet, and the notice that says +# so needs a track to name. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_av1.mkv # Mismatch fixture: different resolution and no audio track at all, so import # has something concrete to refuse. ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \