From 85c152debc47ad200eb22ad464f831d7eb5a1bd2 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 09:24:54 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20HEVC=20import=20via?= =?UTF-8?q?=20the=20VA-API=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The demuxer takes a hev1 track alongside avc1 and vp09. Its parameter sets are read out of the file by hand: mp4 0.14 reads one byte of hvcC and skips the rest, so the VPS, SPS and PPS an HEVC decoder cannot start without are unreachable through the crate. A small ISO-BMFF walk finds the track's hvcC and the record gives both the parameter sets and the NAL length prefix width -- the avcC one is now read the same way instead of assumed to be four bytes, which is one hardcoded guess less on the H.264 path too. Samples are repacked to Annex-B exactly as H.264's are, parameter sets ahead of every sync sample, because a hardware decoder that joins the stream at a seek has nothing else to configure itself from. Main 10 is refused at open by name: the plugin's NV12 pool and its vaGetImage read-back are 8-bit, and a 10-bit stream decoded into them would be garbage shown as a picture rather than an honest no. Same reasoning as the software refusal, which is now one message shared by every codec that has no software decoder at all. The C ABI is unchanged again: the plugin demuxes the file it is given, so an older libengine_hw.so still loads, still decodes H.264, and simply returns null for an HEVC path. --- crates/engine-hw/src/lib.rs | 28 ++-- crates/engine/src/decode.rs | 18 +-- crates/engine/src/demux.rs | 310 +++++++++++++++++++++++++++++++----- crates/engine/src/export.rs | 8 +- crates/engine/src/hw.rs | 10 +- crates/engine/tests/hevc.rs | 182 +++++++++++++++++++++ scripts/gen_fixtures.sh | 11 ++ 7 files changed, 498 insertions(+), 69 deletions(-) create mode 100644 crates/engine/tests/hevc.rs diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 708c7f0..9b02540 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,6 +1,6 @@ -//! VA-API decode (H.264 and VP9) 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 +//! VA-API decode (H.264, HEVC and VP9) 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 //! negative code: the caller's contract is "any failure means use the software //! codec". @@ -19,6 +19,7 @@ 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::h264::H264; +use cros_codecs::decoder::stateless::h265::H265; use cros_codecs::decoder::stateless::vp9::Vp9; use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder}; use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; @@ -45,17 +46,20 @@ type PooledFrame = PooledVideoFrame; type Dec = StatelessDecoder>; type Handle = as StatelessVideoDecoder>::Handle; -/// One decoder per codec the demuxer can hand us. Both share the VA-API backend -/// and therefore the same [`Handle`], so everything past `decode` is common; -/// which one exists is decided by the container, never by the caller -- which is -/// why the plugin's C ABI is unchanged and an older `libengine_hw.so` still -/// loads and still decodes H.264 (it simply refuses VP9 files at `Demuxer`). +/// One decoder per codec the demuxer can hand us. They all share the VA-API +/// backend and therefore the same [`Handle`], so everything past `decode` is +/// common; which one exists is decided by the container, never by the caller -- +/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so` +/// still loads and still decodes H.264 (it simply refuses the newer codecs' +/// files at `Demuxer`). /// -/// ponytail: VP9 profile 0 (8-bit 4:2:0) only. Profile 2 decodes 10-bit, which -/// the NV12 pool and the `vaGetImage` read-back here cannot carry; the upgrade +/// 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. enum Decoder { H264(Dec), + Hevc(Dec), Vp9(Dec), } @@ -63,6 +67,7 @@ impl Decoder { fn get(&mut self) -> &mut dyn StatelessVideoDecoder { match self { Self::H264(d) => d, + Self::Hevc(d) => d, Self::Vp9(d) => d, } } @@ -178,6 +183,9 @@ impl Session { Codec::H264 => { Decoder::H264(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) } + Codec::Hevc => { + Decoder::Hevc(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) + } Codec::Vp9 => { Decoder::Vp9(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index a8b571b..cea17e3 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -181,13 +181,13 @@ impl DecodeSession { ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; - // No software VP9 decoder exists, so a VP9 file the plugin will not take - // is refused *here*, where the caller still has somewhere to show it -- - // a worker that opened and then produced nothing is a black screen with - // no explanation. The probe session is opened and dropped: it costs one - // extra VA-API init (~90 ms) and only on the VP9 path. + // No software HEVC or VP9 decoder exists, so such a file the plugin will + // not take is refused *here*, where the caller still has somewhere to + // show it -- a worker that opened and then produced nothing is a black + // screen with no explanation. The probe session is opened and dropped: + // it costs one extra VA-API init (~90 ms) and only off the H.264 path. if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() { - return Err(crate::demux::VP9_NEEDS_PLUGIN.into()); + return Err(meta.codec.needs_plugin().into()); } let end_frame = end_frame.min(meta.frame_count); // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the @@ -235,10 +235,10 @@ impl DecodeSession { // still a fallback case, not a dead session. eprintln!("hardware decode failed before any frame, falling back to software"); } - // ...except where there is nothing to fall back to. Feeding VP9 - // bytes to `rusty_h264` would be garbage, not a fallback. + // ...except where there is nothing to fall back to. Feeding HEVC + // or VP9 bytes to `rusty_h264` would be garbage, not a fallback. if meta.codec != Codec::H264 { - eprintln!("{}", crate::demux::VP9_NEEDS_PLUGIN); + eprintln!("{}", meta.codec.needs_plugin()); return; } eprintln!("decode backend: software (rusty_h264)"); diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index ed0d81a..bc0a081 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1,9 +1,9 @@ //! MP4 demux: pulls the video track out as access units the decoders take -- -//! Annex-B for H.264, the sample bytes untouched for VP9 (an mp4 VP9 sample is -//! a self-contained superframe already). +//! Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9 +//! sample is a self-contained superframe already). use std::fs::File; -use std::io::BufReader; +use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::Path; use mp4::{MediaType, Mp4Reader, Mp4Track}; @@ -12,11 +12,13 @@ use crate::audio::{edit_media_time, packet_at, stts_pairs}; const START_CODE: [u8; 4] = [0, 0, 0, 1]; -/// What the video track is coded with. Not a decoder choice by itself: VP9 has -/// no software decoder at all, which is what [`VP9_NEEDS_PLUGIN`] says. +/// What the video track is coded with. Not a decoder choice by itself: only +/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`] +/// says for the others. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Codec { H264, + Hevc, Vp9, } @@ -25,17 +27,22 @@ impl Codec { pub fn name(self) -> &'static str { match self { Self::H264 => "H.264", + Self::Hevc => "HEVC", Self::Vp9 => "VP9", } } -} -/// Why a VP9 file can be refused outright: `rusty_h264` is the only software -/// decoder in the project and there is no pure-Rust VP9 one to fall back to, so -/// without the plugin there is nothing to decode with. Shared so playback and -/// export refuse in the same words. -pub const VP9_NEEDS_PLUGIN: &str = - "VP9 needs the VA-API plugin (libengine_hw.so) โ€” there is no software VP9 decoder"; + /// Why a file can be refused outright: `rusty_h264` is the only software + /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall + /// back to, so without the plugin there is nothing to decode with. Shared + /// so playback and export refuse in the same words. + pub fn needs_plugin(self) -> String { + format!( + "{name} needs the VA-API plugin (libengine_hw.so) โ€” there is no software {name} decoder", + name = self.name() + ) + } +} #[derive(Debug, Clone, Copy, PartialEq)] pub struct VideoMeta { @@ -55,9 +62,13 @@ pub struct Demuxer { /// (`audio::priming_samples`), and frame indices count from there. first_sample: u32, codec: Codec, - /// Annex-B SPS+PPS, re-injected ahead of every sync sample. Empty for VP9, - /// which carries no out-of-band parameter sets. + /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), + /// re-injected ahead of every sync sample. Empty for VP9, which carries no + /// out-of-band parameter sets. parameter_sets: Vec, + /// Bytes of the NAL length prefix each sample is written with, off `avcC` + /// or `hvcC`. Unused by VP9. + nal_length: usize, /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box /// at all, i.e. every sample is a sync sample. sync_samples: Vec, @@ -75,10 +86,11 @@ impl Demuxer { .values() .find_map(|t| match t.media_type() { Ok(MediaType::H264) => Some((t, Codec::H264)), + Ok(MediaType::H265) => Some((t, Codec::Hevc)), Ok(MediaType::VP9) => Some((t, Codec::Vp9)), _ => None, }) - .ok_or("no H.264 or VP9 video track in file")?; + .ok_or("no H.264, HEVC or VP9 video track in file")?; let (track, codec) = track; let track_id = track.track_id(); @@ -91,11 +103,35 @@ impl Demuxer { }; let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); let mut parameter_sets = Vec::new(); - if codec == Codec::H264 { - parameter_sets.extend_from_slice(&START_CODE); - parameter_sets.extend_from_slice(track.sequence_parameter_set()?); - parameter_sets.extend_from_slice(&START_CODE); - parameter_sets.extend_from_slice(track.picture_parameter_set()?); + let mut nal_length = 4; + match codec { + Codec::H264 => { + let avcc = &track + .trak + .mdia + .minf + .stbl + .stsd + .avc1 + .as_ref() + .ok_or("an H.264 track without an avc1 sample entry")? + .avcc; + nal_length = usize::from(avcc.length_size_minus_one) + 1; + parameter_sets.extend_from_slice(&START_CODE); + parameter_sets.extend_from_slice(track.sequence_parameter_set()?); + parameter_sets.extend_from_slice(&START_CODE); + parameter_sets.extend_from_slice(track.picture_parameter_set()?); + } + // `mp4 0.14` reads one byte of `hvcC` and skips the rest + // (`hev1.rs:193`), so the parameter sets an HEVC decoder cannot + // start without are read out of the file by hand. + Codec::Hevc => { + let hvcc = hvcc_record(path, track_id)?; + let (len, sets) = parse_hvcc(&hvcc)?; + nal_length = len; + parameter_sets = sets; + } + Codec::Vp9 => {} } let sync_samples = track .trak @@ -125,14 +161,15 @@ impl Demuxer { first_sample, codec, parameter_sets, + nal_length, sync_samples, next_sample, }, )) } - /// Next access unit in decode order: Annex-B framed for H.264, the mp4 - /// sample verbatim for VP9. `None` at end of track. + /// 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>> { if self.next_sample > self.sample_count { return Ok(None); @@ -152,7 +189,7 @@ impl Demuxer { if sample.is_sync { au.extend_from_slice(&self.parameter_sets); } - append_annex_b(&sample.bytes, &mut au)?; + append_annex_b(&sample.bytes, self.nal_length, &mut au)?; Ok(Some(au)) } @@ -249,32 +286,183 @@ fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 { } } -/// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which -/// mp4 0.14 does not expose; a wrong guess misparses immediately, hence the check. -/// -/// ponytail: hardcoded 4-byte NAL length prefix (lengthSizeMinusOne == 3). 1/2-byte -/// prefixes exist in the wild; upgrade path is parsing the avcC box from -/// `track.trak` instead of assuming. -fn append_annex_b(mut src: &[u8], out: &mut Vec) -> crate::Result<()> { +/// Length-prefixed NALs (`avcC` or `hvcC` framing) -> Annex-B. `n` is the +/// prefix width the sample entry declares, 1..=4; a wrong one misparses +/// immediately, hence the check. +fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec) -> crate::Result<()> { while !src.is_empty() { - if src.len() < 4 { + if src.len() < n { return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into()); } - let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize; - if len == 0 || len > src.len() - 4 { + let len = src[..n] + .iter() + .fold(0usize, |acc, &b| (acc << 8) | b as usize); + if len == 0 || len > src.len() - n { return Err(format!( - "bad NAL length {len} with {} bytes remaining (not a 4-byte-prefixed avcC sample?)", - src.len() - 4 + "bad NAL length {len} with {} bytes remaining (not a {n}-byte-prefixed sample?)", + src.len() - n ) .into()); } out.extend_from_slice(&START_CODE); - out.extend_from_slice(&src[4..4 + len]); - src = &src[4 + len..]; + out.extend_from_slice(&src[n..n + len]); + src = &src[n + len..]; } Ok(()) } +/// The `hvcC` payload of `track_id`'s sample entry, read straight out of the +/// file: `mp4 0.14`'s `HvcCBox` keeps the configuration version and skips +/// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder +/// cannot start without are unreachable through the crate. +fn hvcc_record(path: &Path, track_id: u32) -> crate::Result> { + let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?; + let trak = boxes(&moov) + .filter(|(kind, _)| *kind == b"trak") + .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id)) + .ok_or("the HEVC track has no trak box")? + .1; + let stsd = child(trak, b"mdia") + .and_then(|b| child(b, b"minf")) + .and_then(|b| child(b, b"stbl")) + .and_then(|b| child(b, b"stsd")) + .ok_or("the HEVC track has no stsd box")?; + // stsd is a FullBox (4) plus entry_count (4); then sample entries, whose + // VisualSampleEntry header is a fixed 78 bytes before the child boxes. + let entry = boxes(stsd.get(8..).unwrap_or_default()) + .next() + .ok_or("empty stsd box")? + .1; + let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC") + .ok_or("no hvcC box in the HEVC sample entry")?; + Ok(hvcc.to_vec()) +} + +/// HEVCDecoderConfigurationRecord (ISO 14496-15 ยง8.3.3.1) -> the NAL length +/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob. +fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec)> { + // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays. + let (&flags, &arrays) = rec + .get(21) + .zip(rec.get(22)) + .ok_or("hvcC box shorter than its fixed header")?; + // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and + // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into + // a surface nothing here can carry -- refused by name instead of shown as + // garbage. Upgrade path: a P010 pool chosen from the stream info. + if rec[17] & 0x7 != 0 { + return Err(format!( + "10-bit HEVC (Main 10) is not supported yet โ€” this file is {}-bit", + 8 + (rec[17] & 0x7) + ) + .into()); + } + let mut sets = Vec::new(); + let mut src = &rec[23..]; + for _ in 0..arrays { + let (&head, rest) = src.split_first().ok_or("hvcC array header past the box")?; + let count = usize::from(u16::from_be_bytes( + rest.get(..2) + .ok_or("hvcC array count past the box")? + .try_into() + .unwrap(), + )); + src = &rest[2..]; + for _ in 0..count { + let len = usize::from(u16::from_be_bytes( + src.get(..2) + .ok_or("hvcC NAL length past the box")? + .try_into() + .unwrap(), + )); + let nal = src.get(2..2 + len).ok_or("hvcC NAL past the box")?; + // 32 VPS, 33 SPS, 34 PPS -- the rest (SEI) a decoder does not need + // to start, and cros-codecs would only skip. + if matches!(head & 0x3f, 32 | 33 | 34) { + sets.extend_from_slice(&START_CODE); + sets.extend_from_slice(nal); + } + src = &src[2 + len..]; + } + } + if sets.is_empty() { + return Err("hvcC box carries no VPS/SPS/PPS".into()); + } + Ok((usize::from(flags & 0x3) + 1, sets)) +} + +/// Payload of the first top-level box of type `want`, or `None` if the file has +/// none. Only the box wanted is read; the rest is seeked over, so a `moov` at +/// the end of a two-hour film costs one seek and not a copy of the file. +fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result>> { + let mut file = File::open(path)?; + let end = file.metadata()?.len(); + let mut at = 0u64; + while at + 8 <= end { + let mut header = [0u8; 8]; + file.seek(SeekFrom::Start(at))?; + file.read_exact(&mut header)?; + let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) { + 0 => (end - at, 8), + 1 => { + let mut large = [0u8; 8]; + file.read_exact(&mut large)?; + (u64::from_be_bytes(large), 16) + } + size => (u64::from(size), 8), + }; + if size < header_len || at + size > end { + return Err("truncated box in the file's top level".into()); + } + if &header[4..8] == want { + let mut payload = vec![0u8; (size - header_len) as usize]; + file.seek(SeekFrom::Start(at + header_len))?; + file.read_exact(&mut payload)?; + return Ok(Some(payload)); + } + at += size; + } + Ok(None) +} + +/// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first +/// malformed header rather than erroring: every caller is looking for one box +/// and reports its own absence. +fn boxes(mut buf: &[u8]) -> impl Iterator { + std::iter::from_fn(move || { + let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?; + let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize + { + 0 => (buf.len(), 8), + 1 => ( + u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?) as usize, + 16, + ), + size => (size, 8), + }; + if size < header_len || size > buf.len() { + return None; + } + let (this, rest) = buf.split_at(size); + buf = rest; + Some((header[4..8].try_into().unwrap(), &this[header_len..])) + }) +} + +/// Payload of the first child box of type `want`. +fn child<'a>(buf: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> { + boxes(buf).find(|(kind, _)| *kind == want).map(|(_, p)| p) +} + +/// `track_id` out of a `tkhd` payload: a FullBox whose creation and +/// modification times are 32-bit in version 0 and 64-bit in version 1. +fn tkhd_track_id(payload: &[u8]) -> Option { + let at = if payload.first() == Some(&1) { 20 } else { 12 }; + Some(u32::from_be_bytes( + payload.get(at..at + 4)?.try_into().ok()?, + )) +} + #[cfg(test)] mod tests { use super::*; @@ -282,8 +470,48 @@ mod tests { #[test] fn splits_two_nals() { let mut out = Vec::new(); - append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], &mut out).unwrap(); + append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], 4, &mut out).unwrap(); assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]); + // The same two NALs written with a 2-byte prefix, which is what a + // `hvcC`/`avcC` with lengthSizeMinusOne == 1 declares. + let mut narrow = Vec::new(); + append_annex_b(&[0, 2, 0x65, 0xAA, 0, 1, 0x41], 2, &mut narrow).unwrap(); + assert_eq!(narrow, out, "the prefix width is the only difference"); + } + + /// The `hvcC` parse: prefix width out of byte 21 and VPS/SPS/PPS out of the + /// arrays, with an SEI array in between that must not join them. + #[test] + fn reads_parameter_sets_out_of_an_hvcc_record() { + let mut rec = vec![0u8; 23]; + rec[0] = 1; // configurationVersion + rec[21] = 0xf0 | 0x1; // lengthSizeMinusOne == 1, high bits reserved + rec[22] = 4; // numOfArrays + for (kind, nal) in [(32u8, 0xAAu8), (33, 0xBB), (39, 0xCC), (34, 0xDD)] { + rec.push(0x80 | kind); // array_completeness set + rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus + rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength + rec.extend_from_slice(&[kind << 1, nal]); + } + let (len, sets) = parse_hvcc(&rec).unwrap(); + assert_eq!(len, 2); + assert_eq!( + sets, + [ + 0, 0, 0, 1, 64, 0xAA, // VPS + 0, 0, 0, 1, 66, 0xBB, // SPS + 0, 0, 0, 1, 68, 0xDD, // PPS -- the SEI array is skipped + ] + ); + + // 10-bit is refused by name rather than decoded into an 8-bit surface. + let mut main10 = rec.clone(); + main10[17] = 0xf8 | 2; + let refused = parse_hvcc(&main10).unwrap_err().to_string(); + assert!(refused.contains("10-bit"), "{refused}"); + // Nothing is read past the end of a truncated box. + assert!(parse_hvcc(&rec[..20]).is_err()); + assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); } #[test] @@ -336,8 +564,8 @@ mod tests { #[test] fn rejects_misparse() { - assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); - assert!(append_annex_b(&[0, 0, 0], &mut Vec::new()).is_err()); - assert!(append_annex_b(&[0, 0, 0, 0], &mut Vec::new()).is_err()); + assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err()); + assert!(append_annex_b(&[0, 0, 0], 4, &mut Vec::new()).is_err()); + assert!(append_annex_b(&[0, 0, 0, 0], 4, &mut Vec::new()).is_err()); } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index b74526c..b3d2bf4 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -476,11 +476,11 @@ struct SwDecoder { impl SwDecoder { fn open(path: &Path, start_frame: u32) -> crate::Result { let (meta, mut demuxer) = Demuxer::open(path)?; - // The software decoder is H.264-only; a VP9 source that got this far - // means the plugin refused it, and the export says so instead of - // handing VP9 bytes to `rusty_h264`. + // The software decoder is H.264-only; an HEVC or VP9 source that got + // this far means the plugin refused it, and the export says so instead + // of handing those bytes to `rusty_h264`. if meta.codec != crate::demux::Codec::H264 { - return Err(crate::demux::VP9_NEEDS_PLUGIN.into()); + return Err(meta.codec.needs_plugin().into()); } // Decoding restarts at a sync sample, so pictures between it and the in // point are decoded (the target references them) and then dropped. diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index edd808d..840f8fe 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -9,11 +9,11 @@ //! plugin built before the encode entry points existed must still decode, so a //! missing `vh_enc_*` may only cost us [`HwEncoder`], never [`HwSession`]. //! -//! The codec is *not* part of this ABI and adding VP9 did not change it: the -//! plugin demuxes the file it is given and picks its decoder from the container, -//! so a plugin older than VP9 support simply returns null for a VP9 path -- the -//! same "no" it gives for an unsupported profile, and the caller's honest -//! [`crate::demux::VP9_NEEDS_PLUGIN`] refusal covers both. +//! The codec is *not* part of this ABI and adding VP9 and HEVC did not change +//! it: the plugin demuxes the file it is given and picks its decoder from the +//! container, so a plugin older than that support simply returns null for such a +//! path -- the same "no" it gives for an unsupported profile, and the caller's +//! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. use std::ffi::{CString, c_char, c_void}; use std::path::{Path, PathBuf}; diff --git a/crates/engine/tests/hevc.rs b/crates/engine/tests/hevc.rs new file mode 100644 index 0000000..db58b5a --- /dev/null +++ b/crates/engine/tests/hevc.rs @@ -0,0 +1,182 @@ +//! HEVC import: the second source codec that is not H.264, and the first whose +//! parameter sets have to be dug out of the container by hand (`mp4 0.14` reads +//! one byte of `hvcC` and skips the rest). +//! +//! 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 HEVC +//! decode entrypoint (`vainfo | grep HEVC`), 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 hevc -- --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 -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The container half: a hev1 track is found, described and named as HEVC, and +/// its AAC track is read exactly as any other file's. +#[test] +fn the_demuxer_reports_an_hevc_track() { + let (meta, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + assert_eq!(meta.codec, Codec::Hevc); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate); + assert_eq!(meta.frame_count, FRAMES); + + let probe = AudioSession::probe(asset("test_hevc.mp4"), 0) + .expect("probe") + .expect("the fixture has an AAC track"); + assert_eq!( + (probe.params.sample_rate, probe.channels), + (44_100, 2), + "audio is read the same whatever the picture is coded with" + ); + + // The invariant, stated as an assert: the older codecs still say themselves. + let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4"); + assert_eq!(h264.codec, Codec::H264); + let (vp9, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4"); + assert_eq!(vp9.codec, Codec::Vp9); +} + +/// The part `mp4 0.14` cannot do: every access unit is Annex-B framed, and the +/// sync ones carry the VPS, SPS and PPS read out of `hvcC` by hand. Without +/// those three a hardware decoder has nothing to configure itself from, so this +/// is the check that says the box was really parsed and not merely found. +#[test] +fn every_sync_sample_carries_annex_b_vps_sps_and_pps() { + let (_, mut demuxer) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + let first = demuxer + .next_access_unit() + .expect("read") + .expect("a first access unit"); + + // NAL types out of the two-byte HEVC NAL header: bits 6..1 of the first byte. + let types: Vec = first + .windows(4) + .enumerate() + .filter(|(_, w)| *w == [0, 0, 0, 1]) + .map(|(i, _)| (first[i + 4] >> 1) & 0x3f) + .collect(); + assert!(types.starts_with(&[32, 33, 34]), "{types:?}"); + assert!( + types.iter().any(|&t| (16..=21).contains(&t)), + "the first sample must also carry an IRAP slice: {types:?}" + ); + + let mut count = 1; + while let Some(au) = demuxer.next_access_unit().expect("read") { + assert_eq!(&au[..4], [0, 0, 0, 1], "sample {count} is not Annex-B"); + count += 1; + } + assert_eq!(count, FRAMES, "every sample came back out"); +} + +/// There is no software HEVC decoder, so the software path must refuse by name +/// rather than feed HEVC 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_hevc_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_hevc.mp4")).expect_err("software must not accept HEVC"); + 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("HEVC"), "{refused}"); + assert!(refused.contains("plugin"), "{refused}"); + // H.264 is untouched by all of this. + unsafe { std::env::set_var("VE_SW", "1") }; + let h264 = DecodeSession::open(asset("test_baseline.mp4")).is_ok(); + unsafe { std::env::remove_var("VE_SW") }; + assert!(h264, "software H.264 decode still opens"); +} + +/// 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_hevc.mp4")) + .expect_err("HEVC must not join an H.264 timeline") + .to_string(); + assert!(refused.contains("HEVC"), "{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 HEVC decode"] +fn the_plugin_decodes_every_hevc_frame() { + let start = Instant::now(); + let (meta, frames) = DecodeSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + assert_eq!(meta.codec, Codec::Hevc); + let frames: Vec<_> = frames.into_iter().collect(); + eprintln!( + "test_hevc.mp4: {} frames in {:?}", + frames.len(), + start.elapsed() + ); + + assert_eq!(frames.len() as u32, FRAMES, "every sample 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" + ); +} + +/// Export re-encodes to H.264 whatever the source was coded with: the packet +/// copy path is audio-only, so no HEVC byte can reach an `avc1` track. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"] +fn an_hevc_source_exports_as_h264() { + let session = PlaybackSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4"); + let meta = *session.meta(); + let project = Project::single(asset("test_hevc.mp4"), meta.frame_count); + let out = std::env::temp_dir().join(format!("ve_export_hevc_{}.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 0e6b071..8ea07c7 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -74,6 +74,17 @@ 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 libvpx-vp9 -b:v 2M -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_vp9.mp4 +# HEVC fixture: the same A/V shape again, so the tests measure the codec and +# nothing else. `-tag:v hev1` is not a preference: mp4 0.14 only recognises a +# hev1 sample entry, so an hvc1-tagged file would read back as no video track at +# all. 8-bit Main profile, because the plugin's NV12 read-back cannot carry +# Main 10. +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 libx265 -tag:v hev1 -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_hevc.mp4 # 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 \