forge
Explore
Log in

Don't you dare go Hollow

HEVC import via the VA-API plugin

Browse files at this commit

85c152debc47ad200eb22ad464f831d7eb5a1bd2Ahmet Kaan GümüşParent: a195ea4
  • feat
    • HEVC import via the VA-API plugin
Show full message
✨ feat(engine): HEVC import via the VA-API plugin

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.rsmodified+18 -10
@@ -1,6 +1,6 @@
1-//! VA-API decode (H.264 and VP9) and H.264 encode, shipped as a `dlopen`-able1+//! VA-API decode (H.264, HEVC and VP9) and H.264 encode, shipped as a
2-//! plugin so the main binary never gets a DT_NEEDED on libva/gbm/drm. Every2+//! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
3-//! 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
5 //! negative code: the caller's contract is "any failure means use the software5 //! negative code: the caller's contract is "any failure means use the software
6 //! codec".6 //! codec".
@@ -19,6 +19,7 @@ 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::h264::H264;21 use cros_codecs::decoder::stateless::h264::H264;
22+use cros_codecs::decoder::stateless::h265::H265;
22 use cros_codecs::decoder::stateless::vp9::Vp9;23 use cros_codecs::decoder::stateless::vp9::Vp9;
23 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};24 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
24 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};25 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
@@ -45,17 +46,20 @@ type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
45 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;46 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
46 type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;47 type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
47 48
48-/// One decoder per codec the demuxer can hand us. Both share the VA-API backend49+/// One decoder per codec the demuxer can hand us. They all share the VA-API
49-/// and therefore the same [`Handle`], so everything past `decode` is common;50+/// backend and therefore the same [`Handle`], so everything past `decode` is
50-/// which one exists is decided by the container, never by the caller -- which is51+/// common; which one exists is decided by the container, never by the caller --
51-/// why the plugin's C ABI is unchanged and an older `libengine_hw.so` still52+/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so`
52-/// loads and still decodes H.264 (it simply refuses VP9 files at `Demuxer`).53+/// still loads and still decodes H.264 (it simply refuses the newer codecs'
54+/// files at `Demuxer`).
53 ///55 ///
54-/// ponytail: VP9 profile 0 (8-bit 4:2:0) only. Profile 2 decodes 10-bit, which56+/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0 and HEVC Main. VP9 profile 2 and
55-/// the NV12 pool and the `vaGetImage` read-back here cannot carry; the upgrade57+/// HEVC Main 10 decode 10-bit, which the NV12 pool and the `vaGetImage`
58+/// read-back here cannot carry (`Demuxer` refuses Main 10 by name); the upgrade
56 /// path is a P010 pool selected from the stream info.59 /// path is a P010 pool selected from the stream info.
57 enum Decoder {60 enum Decoder {
58 H264(Dec<H264>),61 H264(Dec<H264>),
62+ Hevc(Dec<H265>),
59 Vp9(Dec<Vp9>),63 Vp9(Dec<Vp9>),
60 }64 }
61 65
@@ -63,6 +67,7 @@ impl Decoder {
63 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {67 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
64 match self {68 match self {
65 Self::H264(d) => d,69 Self::H264(d) => d,
70+ Self::Hevc(d) => d,
66 Self::Vp9(d) => d,71 Self::Vp9(d) => d,
67 }72 }
68 }73 }
@@ -178,6 +183,9 @@ impl Session {
178 Codec::H264 => {183 Codec::H264 => {
179 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)184 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
180 }185 }
186+ Codec::Hevc => {
187+ Decoder::Hevc(Dec::<H265>::new_vaapi(display, BlockingMode::Blocking).ok()?)
188+ }
181 Codec::Vp9 => {189 Codec::Vp9 => {
182 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)190 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
183 }191 }
crates/engine/src/decode.rsmodified+9 -9
@@ -181,13 +181,13 @@ impl DecodeSession {
181 ) -> crate::Result<(VideoMeta, FrameStream)> {181 ) -> crate::Result<(VideoMeta, FrameStream)> {
182 let path = path.as_ref().to_path_buf();182 let path = path.as_ref().to_path_buf();
183 let (meta, demuxer) = Demuxer::open(&path)?;183 let (meta, demuxer) = Demuxer::open(&path)?;
184- // No software VP9 decoder exists, so a VP9 file the plugin will not take184+ // No software HEVC or VP9 decoder exists, so such a file the plugin will
185- // is refused *here*, where the caller still has somewhere to show it --185+ // not take is refused *here*, where the caller still has somewhere to
186- // a worker that opened and then produced nothing is a black screen with186+ // show it -- a worker that opened and then produced nothing is a black
187- // no explanation. The probe session is opened and dropped: it costs one187+ // screen with no explanation. The probe session is opened and dropped:
188- // extra VA-API init (~90 ms) and only on the VP9 path.188+ // it costs one extra VA-API init (~90 ms) and only off the H.264 path.
189 if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {189 if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
190- return Err(crate::demux::VP9_NEEDS_PLUGIN.into());190+ return Err(meta.codec.needs_plugin().into());
191 }191 }
192 let end_frame = end_frame.min(meta.frame_count);192 let end_frame = end_frame.min(meta.frame_count);
193 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the193 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
@@ -235,10 +235,10 @@ impl DecodeSession {
235 // still a fallback case, not a dead session.235 // still a fallback case, not a dead session.
236 eprintln!("hardware decode failed before any frame, falling back to software");236 eprintln!("hardware decode failed before any frame, falling back to software");
237 }237 }
238- // ...except where there is nothing to fall back to. Feeding VP9238+ // ...except where there is nothing to fall back to. Feeding HEVC
239- // bytes to `rusty_h264` would be garbage, not a fallback.239+ // or VP9 bytes to `rusty_h264` would be garbage, not a fallback.
240 if meta.codec != Codec::H264 {240 if meta.codec != Codec::H264 {
241- eprintln!("{}", crate::demux::VP9_NEEDS_PLUGIN);241+ eprintln!("{}", meta.codec.needs_plugin());
242 return;242 return;
243 }243 }
244 eprintln!("decode backend: software (rusty_h264)");244 eprintln!("decode backend: software (rusty_h264)");
crates/engine/src/demux.rsmodified+269 -41
@@ -1,9 +1,9 @@
1 //! MP4 demux: pulls the video track out as access units the decoders take --1 //! MP4 demux: pulls the video track out as access units the decoders take --
2-//! Annex-B for H.264, the sample bytes untouched for VP9 (an mp4 VP9 sample is2+//! Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9
3-//! a self-contained superframe already).3+//! sample is a self-contained superframe already).
4 4
5 use std::fs::File;5 use std::fs::File;
6-use std::io::BufReader;6+use std::io::{BufReader, Read, Seek, SeekFrom};
7 use std::path::Path;7 use std::path::Path;
8 8
9 use mp4::{MediaType, Mp4Reader, Mp4Track};9 use mp4::{MediaType, Mp4Reader, Mp4Track};
@@ -12,11 +12,13 @@ use crate::audio::{edit_media_time, packet_at, stts_pairs};
12 12
13 const START_CODE: [u8; 4] = [0, 0, 0, 1];13 const START_CODE: [u8; 4] = [0, 0, 0, 1];
14 14
15-/// What the video track is coded with. Not a decoder choice by itself: VP9 has15+/// What the video track is coded with. Not a decoder choice by itself: only
16-/// no software decoder at all, which is what [`VP9_NEEDS_PLUGIN`] says.16+/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`]
17+/// says for the others.
17 #[derive(Debug, Clone, Copy, PartialEq, Eq)]18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18 pub enum Codec {19 pub enum Codec {
19 H264,20 H264,
21+ Hevc,
20 Vp9,22 Vp9,
21 }23 }
22 24
@@ -25,17 +27,22 @@ impl Codec {
25 pub fn name(self) -> &'static str {27 pub fn name(self) -> &'static str {
26 match self {28 match self {
27 Self::H264 => "H.264",29 Self::H264 => "H.264",
30+ Self::Hevc => "HEVC",
28 Self::Vp9 => "VP9",31 Self::Vp9 => "VP9",
29 }32 }
30 }33 }
31-}
32 34
33-/// Why a VP9 file can be refused outright: `rusty_h264` is the only software35+ /// Why a file can be refused outright: `rusty_h264` is the only software
34-/// decoder in the project and there is no pure-Rust VP9 one to fall back to, so36+ /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall
35-/// without the plugin there is nothing to decode with. Shared so playback and37+ /// back to, so without the plugin there is nothing to decode with. Shared
36-/// export refuse in the same words.38+ /// so playback and export refuse in the same words.
37-pub const VP9_NEEDS_PLUGIN: &str =39+ pub fn needs_plugin(self) -> String {
38- "VP9 needs the VA-API plugin (libengine_hw.so) — there is no software VP9 decoder";40+ format!(
41+ "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
42+ name = self.name()
43+ )
44+ }
45+}
39 46
40 #[derive(Debug, Clone, Copy, PartialEq)]47 #[derive(Debug, Clone, Copy, PartialEq)]
41 pub struct VideoMeta {48 pub struct VideoMeta {
@@ -55,9 +62,13 @@ pub struct Demuxer {
55 /// (`audio::priming_samples`), and frame indices count from there.62 /// (`audio::priming_samples`), and frame indices count from there.
56 first_sample: u32,63 first_sample: u32,
57 codec: Codec,64 codec: Codec,
58- /// Annex-B SPS+PPS, re-injected ahead of every sync sample. Empty for VP9,65+ /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC),
59- /// which carries no out-of-band parameter sets.66+ /// re-injected ahead of every sync sample. Empty for VP9, which carries no
67+ /// out-of-band parameter sets.
60 parameter_sets: Vec<u8>,68 parameter_sets: Vec<u8>,
69+ /// Bytes of the NAL length prefix each sample is written with, off `avcC`
70+ /// or `hvcC`. Unused by VP9.
71+ nal_length: usize,
61 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box72 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
62 /// at all, i.e. every sample is a sync sample.73 /// at all, i.e. every sample is a sync sample.
63 sync_samples: Vec<u32>,74 sync_samples: Vec<u32>,
@@ -75,10 +86,11 @@ impl Demuxer {
75 .values()86 .values()
76 .find_map(|t| match t.media_type() {87 .find_map(|t| match t.media_type() {
77 Ok(MediaType::H264) => Some((t, Codec::H264)),88 Ok(MediaType::H264) => Some((t, Codec::H264)),
89+ Ok(MediaType::H265) => Some((t, Codec::Hevc)),
78 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),90 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
79 _ => None,91 _ => None,
80 })92 })
81- .ok_or("no H.264 or VP9 video track in file")?;93+ .ok_or("no H.264, HEVC or VP9 video track in file")?;
82 let (track, codec) = track;94 let (track, codec) = track;
83 95
84 let track_id = track.track_id();96 let track_id = track.track_id();
@@ -91,11 +103,35 @@ impl Demuxer {
91 };103 };
92 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));104 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
93 let mut parameter_sets = Vec::new();105 let mut parameter_sets = Vec::new();
94- if codec == Codec::H264 {106+ let mut nal_length = 4;
95- parameter_sets.extend_from_slice(&START_CODE);107+ match codec {
96- parameter_sets.extend_from_slice(track.sequence_parameter_set()?);108+ Codec::H264 => {
97- parameter_sets.extend_from_slice(&START_CODE);109+ let avcc = &track
98- parameter_sets.extend_from_slice(track.picture_parameter_set()?);110+ .trak
111+ .mdia
112+ .minf
113+ .stbl
114+ .stsd
115+ .avc1
116+ .as_ref()
117+ .ok_or("an H.264 track without an avc1 sample entry")?
118+ .avcc;
119+ nal_length = usize::from(avcc.length_size_minus_one) + 1;
120+ parameter_sets.extend_from_slice(&START_CODE);
121+ parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
122+ parameter_sets.extend_from_slice(&START_CODE);
123+ parameter_sets.extend_from_slice(track.picture_parameter_set()?);
124+ }
125+ // `mp4 0.14` reads one byte of `hvcC` and skips the rest
126+ // (`hev1.rs:193`), so the parameter sets an HEVC decoder cannot
127+ // start without are read out of the file by hand.
128+ Codec::Hevc => {
129+ let hvcc = hvcc_record(path, track_id)?;
130+ let (len, sets) = parse_hvcc(&hvcc)?;
131+ nal_length = len;
132+ parameter_sets = sets;
133+ }
134+ Codec::Vp9 => {}
99 }135 }
100 let sync_samples = track136 let sync_samples = track
101 .trak137 .trak
@@ -125,14 +161,15 @@ impl Demuxer {
125 first_sample,161 first_sample,
126 codec,162 codec,
127 parameter_sets,163 parameter_sets,
164+ nal_length,
128 sync_samples,165 sync_samples,
129 next_sample,166 next_sample,
130 },167 },
131 ))168 ))
132 }169 }
133 170
134- /// Next access unit in decode order: Annex-B framed for H.264, the mp4171+ /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the
135- /// sample verbatim for VP9. `None` at end of track.172+ /// mp4 sample verbatim for VP9. `None` at end of track.
136 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {173 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
137 if self.next_sample > self.sample_count {174 if self.next_sample > self.sample_count {
138 return Ok(None);175 return Ok(None);
@@ -152,7 +189,7 @@ impl Demuxer {
152 if sample.is_sync {189 if sample.is_sync {
153 au.extend_from_slice(&self.parameter_sets);190 au.extend_from_slice(&self.parameter_sets);
154 }191 }
155- append_annex_b(&sample.bytes, &mut au)?;192+ append_annex_b(&sample.bytes, self.nal_length, &mut au)?;
156 Ok(Some(au))193 Ok(Some(au))
157 }194 }
158 195
@@ -249,32 +286,183 @@ fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
249 }286 }
250 }287 }
251 288
252-/// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which289+/// Length-prefixed NALs (`avcC` or `hvcC` framing) -> Annex-B. `n` is the
253-/// mp4 0.14 does not expose; a wrong guess misparses immediately, hence the check.290+/// prefix width the sample entry declares, 1..=4; a wrong one misparses
254-///291+/// immediately, hence the check.
255-/// ponytail: hardcoded 4-byte NAL length prefix (lengthSizeMinusOne == 3). 1/2-byte292+fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec<u8>) -> crate::Result<()> {
256-/// prefixes exist in the wild; upgrade path is parsing the avcC box from
257-/// `track.trak` instead of assuming.
258-fn append_annex_b(mut src: &[u8], out: &mut Vec<u8>) -> crate::Result<()> {
259 while !src.is_empty() {293 while !src.is_empty() {
260- if src.len() < 4 {294+ if src.len() < n {
261 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());295 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
262 }296 }
263- let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize;297+ let len = src[..n]
264- if len == 0 || len > src.len() - 4 {298+ .iter()
299+ .fold(0usize, |acc, &b| (acc << 8) | b as usize);
300+ if len == 0 || len > src.len() - n {
265 return Err(format!(301 return Err(format!(
266- "bad NAL length {len} with {} bytes remaining (not a 4-byte-prefixed avcC sample?)",302+ "bad NAL length {len} with {} bytes remaining (not a {n}-byte-prefixed sample?)",
267- src.len() - 4303+ src.len() - n
268 )304 )
269 .into());305 .into());
270 }306 }
271 out.extend_from_slice(&START_CODE);307 out.extend_from_slice(&START_CODE);
272- out.extend_from_slice(&src[4..4 + len]);308+ out.extend_from_slice(&src[n..n + len]);
273- src = &src[4 + len..];309+ src = &src[n + len..];
274 }310 }
275 Ok(())311 Ok(())
276 }312 }
277 313
314+/// The `hvcC` payload of `track_id`'s sample entry, read straight out of the
315+/// file: `mp4 0.14`'s `HvcCBox` keeps the configuration version and skips
316+/// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder
317+/// cannot start without are unreachable through the crate.
318+fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
319+ let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
320+ let trak = boxes(&moov)
321+ .filter(|(kind, _)| *kind == b"trak")
322+ .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id))
323+ .ok_or("the HEVC track has no trak box")?
324+ .1;
325+ let stsd = child(trak, b"mdia")
326+ .and_then(|b| child(b, b"minf"))
327+ .and_then(|b| child(b, b"stbl"))
328+ .and_then(|b| child(b, b"stsd"))
329+ .ok_or("the HEVC track has no stsd box")?;
330+ // stsd is a FullBox (4) plus entry_count (4); then sample entries, whose
331+ // VisualSampleEntry header is a fixed 78 bytes before the child boxes.
332+ let entry = boxes(stsd.get(8..).unwrap_or_default())
333+ .next()
334+ .ok_or("empty stsd box")?
335+ .1;
336+ let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
337+ .ok_or("no hvcC box in the HEVC sample entry")?;
338+ Ok(hvcc.to_vec())
339+}
340+
341+/// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
342+/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob.
343+fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
344+ // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.
345+ let (&flags, &arrays) = rec
346+ .get(21)
347+ .zip(rec.get(22))
348+ .ok_or("hvcC box shorter than its fixed header")?;
349+ // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and
350+ // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into
351+ // a surface nothing here can carry -- refused by name instead of shown as
352+ // garbage. Upgrade path: a P010 pool chosen from the stream info.
353+ if rec[17] & 0x7 != 0 {
354+ return Err(format!(
355+ "10-bit HEVC (Main 10) is not supported yet — this file is {}-bit",
356+ 8 + (rec[17] & 0x7)
357+ )
358+ .into());
359+ }
360+ let mut sets = Vec::new();
361+ let mut src = &rec[23..];
362+ for _ in 0..arrays {
363+ let (&head, rest) = src.split_first().ok_or("hvcC array header past the box")?;
364+ let count = usize::from(u16::from_be_bytes(
365+ rest.get(..2)
366+ .ok_or("hvcC array count past the box")?
367+ .try_into()
368+ .unwrap(),
369+ ));
370+ src = &rest[2..];
371+ for _ in 0..count {
372+ let len = usize::from(u16::from_be_bytes(
373+ src.get(..2)
374+ .ok_or("hvcC NAL length past the box")?
375+ .try_into()
376+ .unwrap(),
377+ ));
378+ let nal = src.get(2..2 + len).ok_or("hvcC NAL past the box")?;
379+ // 32 VPS, 33 SPS, 34 PPS -- the rest (SEI) a decoder does not need
380+ // to start, and cros-codecs would only skip.
381+ if matches!(head & 0x3f, 32 | 33 | 34) {
382+ sets.extend_from_slice(&START_CODE);
383+ sets.extend_from_slice(nal);
384+ }
385+ src = &src[2 + len..];
386+ }
387+ }
388+ if sets.is_empty() {
389+ return Err("hvcC box carries no VPS/SPS/PPS".into());
390+ }
391+ Ok((usize::from(flags & 0x3) + 1, sets))
392+}
393+
394+/// Payload of the first top-level box of type `want`, or `None` if the file has
395+/// none. Only the box wanted is read; the rest is seeked over, so a `moov` at
396+/// the end of a two-hour film costs one seek and not a copy of the file.
397+fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>> {
398+ let mut file = File::open(path)?;
399+ let end = file.metadata()?.len();
400+ let mut at = 0u64;
401+ while at + 8 <= end {
402+ let mut header = [0u8; 8];
403+ file.seek(SeekFrom::Start(at))?;
404+ file.read_exact(&mut header)?;
405+ let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
406+ 0 => (end - at, 8),
407+ 1 => {
408+ let mut large = [0u8; 8];
409+ file.read_exact(&mut large)?;
410+ (u64::from_be_bytes(large), 16)
411+ }
412+ size => (u64::from(size), 8),
413+ };
414+ if size < header_len || at + size > end {
415+ return Err("truncated box in the file's top level".into());
416+ }
417+ if &header[4..8] == want {
418+ let mut payload = vec![0u8; (size - header_len) as usize];
419+ file.seek(SeekFrom::Start(at + header_len))?;
420+ file.read_exact(&mut payload)?;
421+ return Ok(Some(payload));
422+ }
423+ at += size;
424+ }
425+ Ok(None)
426+}
427+
428+/// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
429+/// malformed header rather than erroring: every caller is looking for one box
430+/// and reports its own absence.
431+fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
432+ std::iter::from_fn(move || {
433+ let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
434+ let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
435+ {
436+ 0 => (buf.len(), 8),
437+ 1 => (
438+ u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?) as usize,
439+ 16,
440+ ),
441+ size => (size, 8),
442+ };
443+ if size < header_len || size > buf.len() {
444+ return None;
445+ }
446+ let (this, rest) = buf.split_at(size);
447+ buf = rest;
448+ Some((header[4..8].try_into().unwrap(), &this[header_len..]))
449+ })
450+}
451+
452+/// Payload of the first child box of type `want`.
453+fn child<'a>(buf: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> {
454+ boxes(buf).find(|(kind, _)| *kind == want).map(|(_, p)| p)
455+}
456+
457+/// `track_id` out of a `tkhd` payload: a FullBox whose creation and
458+/// modification times are 32-bit in version 0 and 64-bit in version 1.
459+fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
460+ let at = if payload.first() == Some(&1) { 20 } else { 12 };
461+ Some(u32::from_be_bytes(
462+ payload.get(at..at + 4)?.try_into().ok()?,
463+ ))
464+}
465+
278 #[cfg(test)]466 #[cfg(test)]
279 mod tests {467 mod tests {
280 use super::*;468 use super::*;
@@ -282,8 +470,48 @@ mod tests {
282 #[test]470 #[test]
283 fn splits_two_nals() {471 fn splits_two_nals() {
284 let mut out = Vec::new();472 let mut out = Vec::new();
285- append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], &mut out).unwrap();473+ append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], 4, &mut out).unwrap();
286 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);474 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
475+ // The same two NALs written with a 2-byte prefix, which is what a
476+ // `hvcC`/`avcC` with lengthSizeMinusOne == 1 declares.
477+ let mut narrow = Vec::new();
478+ append_annex_b(&[0, 2, 0x65, 0xAA, 0, 1, 0x41], 2, &mut narrow).unwrap();
479+ assert_eq!(narrow, out, "the prefix width is the only difference");
480+ }
481+
482+ /// The `hvcC` parse: prefix width out of byte 21 and VPS/SPS/PPS out of the
483+ /// arrays, with an SEI array in between that must not join them.
484+ #[test]
485+ fn reads_parameter_sets_out_of_an_hvcc_record() {
486+ let mut rec = vec![0u8; 23];
487+ rec[0] = 1; // configurationVersion
488+ rec[21] = 0xf0 | 0x1; // lengthSizeMinusOne == 1, high bits reserved
489+ rec[22] = 4; // numOfArrays
490+ for (kind, nal) in [(32u8, 0xAAu8), (33, 0xBB), (39, 0xCC), (34, 0xDD)] {
491+ rec.push(0x80 | kind); // array_completeness set
492+ rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
493+ rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength
494+ rec.extend_from_slice(&[kind << 1, nal]);
495+ }
496+ let (len, sets) = parse_hvcc(&rec).unwrap();
497+ assert_eq!(len, 2);
498+ assert_eq!(
499+ sets,
500+ [
501+ 0, 0, 0, 1, 64, 0xAA, // VPS
502+ 0, 0, 0, 1, 66, 0xBB, // SPS
503+ 0, 0, 0, 1, 68, 0xDD, // PPS -- the SEI array is skipped
504+ ]
505+ );
506+
507+ // 10-bit is refused by name rather than decoded into an 8-bit surface.
508+ let mut main10 = rec.clone();
509+ main10[17] = 0xf8 | 2;
510+ let refused = parse_hvcc(&main10).unwrap_err().to_string();
511+ assert!(refused.contains("10-bit"), "{refused}");
512+ // Nothing is read past the end of a truncated box.
513+ assert!(parse_hvcc(&rec[..20]).is_err());
514+ assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
287 }515 }
288 516
289 #[test]517 #[test]
@@ -336,8 +564,8 @@ mod tests {
336 564
337 #[test]565 #[test]
338 fn rejects_misparse() {566 fn rejects_misparse() {
339- assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err());567+ assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());
340- assert!(append_annex_b(&[0, 0, 0], &mut Vec::new()).is_err());568+ assert!(append_annex_b(&[0, 0, 0], 4, &mut Vec::new()).is_err());
341- assert!(append_annex_b(&[0, 0, 0, 0], &mut Vec::new()).is_err());569+ assert!(append_annex_b(&[0, 0, 0, 0], 4, &mut Vec::new()).is_err());
342 }570 }
343 }571 }
crates/engine/src/export.rsmodified+4 -4
@@ -476,11 +476,11 @@ struct SwDecoder {
476 impl SwDecoder {476 impl SwDecoder {
477 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {477 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
478 let (meta, mut demuxer) = Demuxer::open(path)?;478 let (meta, mut demuxer) = Demuxer::open(path)?;
479- // The software decoder is H.264-only; a VP9 source that got this far479+ // The software decoder is H.264-only; an HEVC or VP9 source that got
480- // means the plugin refused it, and the export says so instead of480+ // this far means the plugin refused it, and the export says so instead
481- // handing VP9 bytes to `rusty_h264`.481+ // of handing those bytes to `rusty_h264`.
482 if meta.codec != crate::demux::Codec::H264 {482 if meta.codec != crate::demux::Codec::H264 {
483- return Err(crate::demux::VP9_NEEDS_PLUGIN.into());483+ return Err(meta.codec.needs_plugin().into());
484 }484 }
485 // Decoding restarts at a sync sample, so pictures between it and the in485 // Decoding restarts at a sync sample, so pictures between it and the in
486 // point are decoded (the target references them) and then dropped.486 // point are decoded (the target references them) and then dropped.
crates/engine/src/hw.rsmodified+5 -5
@@ -9,11 +9,11 @@
9 //! plugin built before the encode entry points existed must still decode, so a9 //! plugin built before the encode entry points existed must still decode, so a
10 //! missing `vh_enc_*` may only cost us [`HwEncoder`], never [`HwSession`].10 //! missing `vh_enc_*` may only cost us [`HwEncoder`], never [`HwSession`].
11 //!11 //!
12-//! The codec is *not* part of this ABI and adding VP9 did not change it: the12+//! The codec is *not* part of this ABI and adding VP9 and HEVC did not change
13-//! plugin demuxes the file it is given and picks its decoder from the container,13+//! it: the plugin demuxes the file it is given and picks its decoder from the
14-//! so a plugin older than VP9 support simply returns null for a VP9 path -- the14+//! container, so a plugin older than that support simply returns null for such a
15-//! same "no" it gives for an unsupported profile, and the caller's honest15+//! path -- the same "no" it gives for an unsupported profile, and the caller's
16-//! [`crate::demux::VP9_NEEDS_PLUGIN`] refusal covers both.16+//! honest [`crate::demux::Codec::needs_plugin`] refusal covers both.
17 17
18 use std::ffi::{CString, c_char, c_void};18 use std::ffi::{CString, c_char, c_void};
19 use std::path::{Path, PathBuf};19 use std::path::{Path, PathBuf};
crates/engine/tests/hevc.rsadded+182 -0
@@ -0,0 +1,182 @@
1+//! HEVC import: the second source codec that is not H.264, and the first whose
2+//! parameter sets have to be dug out of the container by hand (`mp4 0.14` reads
3+//! one byte of `hvcC` and skips the rest).
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 HEVC
7+//! decode entrypoint (`vainfo | grep HEVC`), 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 hevc -- --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 -- see `scripts/gen_fixtures.sh`.
26+const FRAMES: u32 = 60;
27+
28+fn asset(name: &str) -> PathBuf {
29+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
30+ .join("../../assets")
31+ .join(name)
32+}
33+
34+/// The container half: a hev1 track is found, described and named as HEVC, and
35+/// its AAC track is read exactly as any other file's.
36+#[test]
37+fn the_demuxer_reports_an_hevc_track() {
38+ let (meta, _) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
39+ assert_eq!(meta.codec, Codec::Hevc);
40+ assert_eq!((meta.width, meta.height), (1280, 720));
41+ assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
42+ assert_eq!(meta.frame_count, FRAMES);
43+
44+ let probe = AudioSession::probe(asset("test_hevc.mp4"), 0)
45+ .expect("probe")
46+ .expect("the fixture has an AAC track");
47+ assert_eq!(
48+ (probe.params.sample_rate, probe.channels),
49+ (44_100, 2),
50+ "audio is read the same whatever the picture is coded with"
51+ );
52+
53+ // The invariant, stated as an assert: the older codecs still say themselves.
54+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
55+ assert_eq!(h264.codec, Codec::H264);
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 part `mp4 0.14` cannot do: every access unit is Annex-B framed, and the
61+/// sync ones carry the VPS, SPS and PPS read out of `hvcC` by hand. Without
62+/// those three a hardware decoder has nothing to configure itself from, so this
63+/// is the check that says the box was really parsed and not merely found.
64+#[test]
65+fn every_sync_sample_carries_annex_b_vps_sps_and_pps() {
66+ let (_, mut demuxer) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4");
67+ let first = demuxer
68+ .next_access_unit()
69+ .expect("read")
70+ .expect("a first access unit");
71+
72+ // NAL types out of the two-byte HEVC NAL header: bits 6..1 of the first byte.
73+ let types: Vec<u8> = first
74+ .windows(4)
75+ .enumerate()
76+ .filter(|(_, w)| *w == [0, 0, 0, 1])
77+ .map(|(i, _)| (first[i + 4] >> 1) & 0x3f)
78+ .collect();
79+ assert!(types.starts_with(&[32, 33, 34]), "{types:?}");
80+ assert!(
81+ types.iter().any(|&t| (16..=21).contains(&t)),
82+ "the first sample must also carry an IRAP slice: {types:?}"
83+ );
84+
85+ let mut count = 1;
86+ while let Some(au) = demuxer.next_access_unit().expect("read") {
87+ assert_eq!(&au[..4], [0, 0, 0, 1], "sample {count} is not Annex-B");
88+ count += 1;
89+ }
90+ assert_eq!(count, FRAMES, "every sample came back out");
91+}
92+
93+/// There is no software HEVC decoder, so the software path must refuse by name
94+/// rather than feed HEVC bytes to `rusty_h264` -- and it must refuse where a
95+/// caller can still show it, i.e. out of `open`, not from inside the worker.
96+#[test]
97+fn the_software_path_refuses_hevc_by_name() {
98+ // SAFETY: the suite is documented to run with --test-threads=1.
99+ unsafe { std::env::set_var("VE_SW", "1") };
100+ let refused =
101+ DecodeSession::open(asset("test_hevc.mp4")).expect_err("software must not accept HEVC");
102+ let refused = refused.to_string();
103+ // Restored immediately: the hardware tests in this binary share the process.
104+ unsafe { std::env::remove_var("VE_SW") };
105+
106+ assert!(refused.contains("HEVC"), "{refused}");
107+ assert!(refused.contains("plugin"), "{refused}");
108+ // H.264 is untouched by all of this.
109+ unsafe { std::env::set_var("VE_SW", "1") };
110+ let h264 = DecodeSession::open(asset("test_baseline.mp4")).is_ok();
111+ unsafe { std::env::remove_var("VE_SW") };
112+ assert!(h264, "software H.264 decode still opens");
113+}
114+
115+/// A timeline is refused a source coded differently, in the same words a
116+/// resolution mismatch is refused in: a front-end shows the string as it is.
117+#[test]
118+fn a_timeline_refuses_the_other_codec() {
119+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
120+ let refused = session
121+ .import(&asset("test_hevc.mp4"))
122+ .expect_err("HEVC must not join an H.264 timeline")
123+ .to_string();
124+ assert!(refused.contains("HEVC"), "{refused}");
125+ assert!(refused.contains("H.264"), "{refused}");
126+}
127+
128+/// The end-to-end user path: opening the file yields pictures, all of them,
129+/// through the plugin.
130+#[test]
131+#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
132+fn the_plugin_decodes_every_hevc_frame() {
133+ let start = Instant::now();
134+ let (meta, frames) = DecodeSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4");
135+ assert_eq!(meta.codec, Codec::Hevc);
136+ let frames: Vec<_> = frames.into_iter().collect();
137+ eprintln!(
138+ "test_hevc.mp4: {} frames in {:?}",
139+ frames.len(),
140+ start.elapsed()
141+ );
142+
143+ assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
144+ for (i, frame) in frames.iter().enumerate() {
145+ assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
146+ assert_eq!(frame.index, i as u32, "frames arrive in display order");
147+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
148+ }
149+ // A picture, not a flat surface: a driver handing back an untouched buffer
150+ // would satisfy every count above.
151+ let first = &frames[0].bgra;
152+ assert!(
153+ first.chunks_exact(4).any(|px| px != &first[..4]),
154+ "frame 0 is a single colour -- no picture was decoded"
155+ );
156+}
157+
158+/// Export re-encodes to H.264 whatever the source was coded with: the packet
159+/// copy path is audio-only, so no HEVC byte can reach an `avc1` track.
160+#[test]
161+#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"]
162+fn an_hevc_source_exports_as_h264() {
163+ let session = PlaybackSession::open(asset("test_hevc.mp4")).expect("open test_hevc.mp4");
164+ let meta = *session.meta();
165+ let project = Project::single(asset("test_hevc.mp4"), meta.frame_count);
166+ let out = std::env::temp_dir().join(format!("ve_export_hevc_{}.mp4", std::process::id()));
167+ let _ = std::fs::remove_file(&out);
168+
169+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
170+ let started = Instant::now();
171+ while !handle.is_finished() {
172+ assert!(started.elapsed() < Duration::from_secs(120), "export hung");
173+ std::thread::sleep(Duration::from_millis(20));
174+ }
175+ handle.result().expect("outcome").expect("export");
176+
177+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
178+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
179+ assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
180+ assert_eq!((written.width, written.height), (1280, 720));
181+ let _ = std::fs::remove_file(&out);
182+}
scripts/gen_fixtures.shmodified+11 -0
@@ -74,6 +74,17 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
74 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \74 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
75 -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \75 -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \
76 -c:a aac -b:a 128k assets/test_vp9.mp476 -c:a aac -b:a 128k assets/test_vp9.mp4
77+# HEVC fixture: the same A/V shape again, so the tests measure the codec and
78+# nothing else. `-tag:v hev1` is not a preference: mp4 0.14 only recognises a
79+# hev1 sample entry, so an hvc1-tagged file would read back as no video track at
80+# all. 8-bit Main profile, because the plugin's NV12 read-back cannot carry
81+# Main 10.
82+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
83+ -f lavfi -i "sine=frequency=440:duration=2" \
84+ -f lavfi -i "sine=frequency=880: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]" \
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.mp4
77 # Mismatch fixture: different resolution and no audio track at all, so import88 # Mismatch fixture: different resolution and no audio track at all, so import
78 # has something concrete to refuse.89 # has something concrete to refuse.
79 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \90 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \