forge
Explore
Log in

Don't you dare go Hollow

VP9 import via the VA-API plugin

Browse files at this commit

03a34d34484580f607bff6af6bbc15c3bd8cc459Ahmet Kaan GümüşParent: 771cd4a
  • feat
    • VP9 import via the VA-API plugin
Show full message
✨ feat(engine): VP9 import via the VA-API plugin

The demuxer takes a vp09 track alongside avc1 and hands its samples through
untouched -- an mp4 VP9 sample is a self-contained superframe, so there is no
avcC repack and no parameter sets to re-inject. VideoMeta carries the codec,
and the plugin picks its cros-codecs decoder from it.

The C ABI is unchanged on purpose: the plugin demuxes the file it is given,
so the codec is a property of the container rather than of the call, and a
libengine_hw.so built before this still loads and still decodes H.264 -- it
simply returns null for a VP9 path, the same no it gives for an unsupported
profile.

There is no software VP9 decoder to fall back to, so a VP9 file the plugin
will not take is refused at open, by name, where the front-end can show it --
never a black screen, and never VP9 bytes fed to rusty_h264. One timeline
stays one codec, and export re-encodes to H.264 as before; only audio is
ever copied packet for packet.
crates/engine-hw/src/lib.rsmodified+46 -9
@@ -1,5 +1,6 @@
1-//! VA-API H.264 decode and encode, shipped as a `dlopen`-able plugin so the main1+//! VA-API decode (H.264 and VP9) and H.264 encode, shipped as a `dlopen`-able
2-//! binary never gets a DT_NEEDED on libva/gbm/drm. Every entry point is2+//! plugin so the main binary never gets a DT_NEEDED on libva/gbm/drm. Every
3+//! entry point is
3 //! `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
4 //! 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
5 //! codec".6 //! codec".
@@ -18,6 +19,7 @@ use cros_codecs::backend::vaapi::decoder::VaapiBackend;
18 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;19 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
19 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};20 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
20 use cros_codecs::decoder::stateless::h264::H264;21 use cros_codecs::decoder::stateless::h264::H264;
22+use cros_codecs::decoder::stateless::vp9::Vp9;
21 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};23 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
22 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};24 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
23 use cros_codecs::encoder::h264::EncoderConfig as H264Config;25 use cros_codecs::encoder::h264::EncoderConfig as H264Config;
@@ -36,12 +38,36 @@ use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
36 use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};38 use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
37 use gbm::{BufferObjectFlags, Format as GbmFormat};39 use gbm::{BufferObjectFlags, Format as GbmFormat};
38 40
39-use engine::demux::Demuxer;41+use engine::demux::{Codec, Demuxer};
40 use engine::hw::{VhFrame, VhMeta};42 use engine::hw::{VhFrame, VhMeta};
41 43
42 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;44 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
43-type Decoder = StatelessDecoder<H264, VaapiBackend<PooledFrame>>;45+type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
44-type Handle = <Decoder as StatelessVideoDecoder>::Handle;46+type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
47+
48+/// One decoder per codec the demuxer can hand us. Both share the VA-API backend
49+/// and therefore the same [`Handle`], so everything past `decode` is common;
50+/// which one exists is decided by the container, never by the caller -- which is
51+/// why the plugin's C ABI is unchanged and an older `libengine_hw.so` still
52+/// loads and still decodes H.264 (it simply refuses VP9 files at `Demuxer`).
53+///
54+/// ponytail: VP9 profile 0 (8-bit 4:2:0) only. Profile 2 decodes 10-bit, which
55+/// the NV12 pool and the `vaGetImage` read-back here cannot carry; the upgrade
56+/// path is a P010 pool selected from the stream info.
57+enum Decoder {
58+ H264(Dec<H264>),
59+ Vp9(Dec<Vp9>),
60+}
61+
62+impl Decoder {
63+ fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
64+ match self {
65+ Self::H264(d) => d,
66+ Self::Vp9(d) => d,
67+ }
68+ }
69+}
70+
45 type Encoder = StatelessEncoder<71 type Encoder = StatelessEncoder<
46 GenericDmaVideoFrame,72 GenericDmaVideoFrame,
47 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,73 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
@@ -148,7 +174,14 @@ impl Session {
148 .ok()?174 .ok()?
149 .into_iter()175 .into_iter()
150 .find(|f| f.fourcc == VA_FOURCC_NV12)?;176 .find(|f| f.fourcc == VA_FOURCC_NV12)?;
151- let decoder = Decoder::new_vaapi(display, BlockingMode::Blocking).ok()?;177+ let decoder = match meta.codec {
178+ Codec::H264 => {
179+ Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
180+ }
181+ Codec::Vp9 => {
182+ Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
183+ }
184+ };
152 let pool = FramePool::new(move |info: &StreamInfo| {185 let pool = FramePool::new(move |info: &StreamInfo| {
153 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")186 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")
154 });187 });
@@ -191,11 +224,12 @@ impl Session {
191 // Stop draining as soon as we have a picture: every handle we hold224 // Stop draining as soon as we have a picture: every handle we hold
192 // keeps a pool buffer out of circulation.225 // keeps a pool buffer out of circulation.
193 while self.ready.is_empty() {226 while self.ready.is_empty() {
194- match self.decoder.next_event() {227+ match self.decoder.get().next_event() {
195 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),228 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
196 Some(DecoderEvent::FormatChanged) => {229 Some(DecoderEvent::FormatChanged) => {
197 let info = self230 let info = self
198 .decoder231 .decoder
232+ .get()
199 .stream_info()233 .stream_info()
200 .ok_or("format changed without stream info")?234 .ok_or("format changed without stream info")?
201 .clone();235 .clone();
@@ -222,7 +256,7 @@ impl Session {
222 match self.demuxer.next_access_unit() {256 match self.demuxer.next_access_unit() {
223 Ok(Some(au)) => self.pending = au,257 Ok(Some(au)) => self.pending = au,
224 Ok(None) => {258 Ok(None) => {
225- self.decoder.flush().map_err(|e| e.to_string())?;259+ self.decoder.get().flush().map_err(|e| e.to_string())?;
226 self.flushed = true;260 self.flushed = true;
227 continue;261 continue;
228 }262 }
@@ -237,7 +271,10 @@ impl Session {
237 timestamp,271 timestamp,
238 ..272 ..
239 } = self;273 } = self;
240- match decoder.decode(*timestamp, pending, &mut || pool.alloc()) {274+ match decoder
275+ .get()
276+ .decode(*timestamp, pending, &mut || pool.alloc())
277+ {
241 Ok(0) => return Err("decoder consumed no input".into()),278 Ok(0) => return Err("decoder consumed no input".into()),
242 Ok(n) => {279 Ok(n) => {
243 pending.drain(..n.min(pending.len()));280 pending.drain(..n.min(pending.len()));
crates/engine/src/decode.rsmodified+15 -1
@@ -10,7 +10,7 @@ use std::thread;
10 use rusty_h264::Decoder;10 use rusty_h264::Decoder;
11 11
12 use crate::convert::i420_to_bgra;12 use crate::convert::i420_to_bgra;
13-use crate::demux::{Demuxer, VideoMeta};13+use crate::demux::{Codec, Demuxer, VideoMeta};
14 use crate::hw::HwSession;14 use crate::hw::HwSession;
15 15
16 /// One decoded picture, ready to hand to a renderer.16 /// One decoded picture, ready to hand to a renderer.
@@ -181,6 +181,14 @@ 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 take
185+ // is refused *here*, where the caller still has somewhere to show it --
186+ // a worker that opened and then produced nothing is a black screen with
187+ // no explanation. The probe session is opened and dropped: it costs one
188+ // extra VA-API init (~90 ms) and only on the VP9 path.
189+ if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
190+ return Err(crate::demux::VP9_NEEDS_PLUGIN.into());
191+ }
184 let end_frame = end_frame.min(meta.frame_count);192 let end_frame = end_frame.min(meta.frame_count);
185 // 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
186 // decoder run ahead of the display without limit.194 // decoder run ahead of the display without limit.
@@ -227,6 +235,12 @@ impl DecodeSession {
227 // still a fallback case, not a dead session.235 // still a fallback case, not a dead session.
228 eprintln!("hardware decode failed before any frame, falling back to software");236 eprintln!("hardware decode failed before any frame, falling back to software");
229 }237 }
238+ // ...except where there is nothing to fall back to. Feeding VP9
239+ // bytes to `rusty_h264` would be garbage, not a fallback.
240+ if meta.codec != Codec::H264 {
241+ eprintln!("{}", crate::demux::VP9_NEEDS_PLUGIN);
242+ return;
243+ }
230 eprintln!("decode backend: software (rusty_h264)");244 eprintln!("decode backend: software (rusty_h264)");
231 run(demuxer, tx, start_frame, end_frame, &worker_cancel)245 run(demuxer, tx, start_frame, end_frame, &worker_cancel)
232 })?;246 })?;
crates/engine/src/demux.rsmodified+54 -9
@@ -1,4 +1,6 @@
1-//! MP4 demux: pulls the H.264 track out as Annex-B access units.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 is
3+//! a self-contained superframe already).
2 4
3 use std::fs::File;5 use std::fs::File;
4 use std::io::BufReader;6 use std::io::BufReader;
@@ -8,19 +10,47 @@ use mp4::{MediaType, Mp4Reader};
8 10
9 const START_CODE: [u8; 4] = [0, 0, 0, 1];11 const START_CODE: [u8; 4] = [0, 0, 0, 1];
10 12
13+/// What the video track is coded with. Not a decoder choice by itself: VP9 has
14+/// no software decoder at all, which is what [`VP9_NEEDS_PLUGIN`] says.
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+pub enum Codec {
17+ H264,
18+ Vp9,
19+}
20+
21+impl Codec {
22+ /// How a refusal names it, and how a mismatch reads to a user.
23+ pub fn name(self) -> &'static str {
24+ match self {
25+ Self::H264 => "H.264",
26+ Self::Vp9 => "VP9",
27+ }
28+ }
29+}
30+
31+/// Why a VP9 file can be refused outright: `rusty_h264` is the only software
32+/// decoder in the project and there is no pure-Rust VP9 one to fall back to, so
33+/// without the plugin there is nothing to decode with. Shared so playback and
34+/// export refuse in the same words.
35+pub const VP9_NEEDS_PLUGIN: &str =
36+ "VP9 needs the VA-API plugin (libengine_hw.so) — there is no software VP9 decoder";
37+
11 #[derive(Debug, Clone, Copy, PartialEq)]38 #[derive(Debug, Clone, Copy, PartialEq)]
12 pub struct VideoMeta {39 pub struct VideoMeta {
13 pub width: u32,40 pub width: u32,
14 pub height: u32,41 pub height: u32,
15 pub frame_rate: f64,42 pub frame_rate: f64,
16 pub frame_count: u32,43 pub frame_count: u32,
44+ pub codec: Codec,
17 }45 }
18 46
19 pub struct Demuxer {47 pub struct Demuxer {
20 reader: Mp4Reader<BufReader<File>>,48 reader: Mp4Reader<BufReader<File>>,
21 track_id: u32,49 track_id: u32,
22 sample_count: u32,50 sample_count: u32,
23- /// Annex-B SPS+PPS, re-injected ahead of every sync sample.51+ codec: Codec,
52+ /// Annex-B SPS+PPS, re-injected ahead of every sync sample. Empty for VP9,
53+ /// which carries no out-of-band parameter sets.
24 parameter_sets: Vec<u8>,54 parameter_sets: Vec<u8>,
25 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box55 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
26 /// at all, i.e. every sample is a sync sample.56 /// at all, i.e. every sample is a sync sample.
@@ -37,8 +67,13 @@ impl Demuxer {
37 let track = reader67 let track = reader
38 .tracks()68 .tracks()
39 .values()69 .values()
40- .find(|t| matches!(t.media_type(), Ok(MediaType::H264)))70+ .find_map(|t| match t.media_type() {
41- .ok_or("no H.264 video track in file")?;71+ Ok(MediaType::H264) => Some((t, Codec::H264)),
72+ Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
73+ _ => None,
74+ })
75+ .ok_or("no H.264 or VP9 video track in file")?;
76+ let (track, codec) = track;
42 77
43 let track_id = track.track_id();78 let track_id = track.track_id();
44 let meta = VideoMeta {79 let meta = VideoMeta {
@@ -46,12 +81,15 @@ impl Demuxer {
46 height: track.height() as u32,81 height: track.height() as u32,
47 frame_rate: track.frame_rate(),82 frame_rate: track.frame_rate(),
48 frame_count: 0,83 frame_count: 0,
84+ codec,
49 };85 };
50 let mut parameter_sets = Vec::new();86 let mut parameter_sets = Vec::new();
51- parameter_sets.extend_from_slice(&START_CODE);87+ if codec == Codec::H264 {
52- parameter_sets.extend_from_slice(track.sequence_parameter_set()?);88+ parameter_sets.extend_from_slice(&START_CODE);
53- parameter_sets.extend_from_slice(&START_CODE);89+ parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
54- parameter_sets.extend_from_slice(track.picture_parameter_set()?);90+ parameter_sets.extend_from_slice(&START_CODE);
91+ parameter_sets.extend_from_slice(track.picture_parameter_set()?);
92+ }
55 let sync_samples = track93 let sync_samples = track
56 .trak94 .trak
57 .mdia95 .mdia
@@ -72,6 +110,7 @@ impl Demuxer {
72 reader,110 reader,
73 track_id,111 track_id,
74 sample_count,112 sample_count,
113+ codec,
75 parameter_sets,114 parameter_sets,
76 sync_samples,115 sync_samples,
77 next_sample: 1, // sample ids are 1-based116 next_sample: 1, // sample ids are 1-based
@@ -79,7 +118,8 @@ impl Demuxer {
79 ))118 ))
80 }119 }
81 120
82- /// Next access unit in decode order, Annex-B framed. `None` at end of track.121+ /// Next access unit in decode order: Annex-B framed for H.264, the mp4
122+ /// sample verbatim for VP9. `None` at end of track.
83 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {123 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
84 if self.next_sample > self.sample_count {124 if self.next_sample > self.sample_count {
85 return Ok(None);125 return Ok(None);
@@ -89,6 +129,11 @@ impl Demuxer {
89 let Some(sample) = sample else {129 let Some(sample) = sample else {
90 return Ok(None);130 return Ok(None);
91 };131 };
132+ // A VP9 mp4 sample is one (super)frame the decoder parses on its own:
133+ // no length prefixes to strip, no parameter sets to re-inject.
134+ if self.codec == Codec::Vp9 {
135+ return Ok(Some(sample.bytes.to_vec()));
136+ }
92 137
93 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);138 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
94 if sample.is_sync {139 if sample.is_sync {
crates/engine/src/export.rsmodified+8 -1
@@ -466,7 +466,13 @@ struct SwDecoder {
466 466
467 impl SwDecoder {467 impl SwDecoder {
468 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {468 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
469- let (_, mut demuxer) = Demuxer::open(path)?;469+ let (meta, mut demuxer) = Demuxer::open(path)?;
470+ // The software decoder is H.264-only; a VP9 source that got this far
471+ // means the plugin refused it, and the export says so instead of
472+ // handing VP9 bytes to `rusty_h264`.
473+ if meta.codec != crate::demux::Codec::H264 {
474+ return Err(crate::demux::VP9_NEEDS_PLUGIN.into());
475+ }
470 // Decoding restarts at a sync sample, so pictures between it and the in476 // Decoding restarts at a sync sample, so pictures between it and the in
471 // point are decoded (the target references them) and then dropped.477 // point are decoded (the target references them) and then dropped.
472 // Sample ids are 1-based, frame indices 0-based.478 // Sample ids are 1-based, frame indices 0-based.
@@ -513,6 +519,7 @@ mod tests {
513 height,519 height,
514 frame_rate,520 frame_rate,
515 frame_count: 1,521 frame_count: 1,
522+ codec: crate::demux::Codec::H264,
516 };523 };
517 // 1280 * 720 * 30 * 0.1524 // 1280 * 720 * 30 * 0.1
518 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);525 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
crates/engine/src/hw.rsmodified+6 -0
@@ -8,6 +8,12 @@
8 //! Decode and encode resolve their symbols into *separate* tables on purpose: a8 //! Decode and encode resolve their symbols into *separate* tables on purpose: a
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+//!
12+//! The codec is *not* part of this ABI and adding VP9 did not change it: the
13+//! plugin demuxes the file it is given and picks its decoder from the container,
14+//! so a plugin older than VP9 support simply returns null for a VP9 path -- the
15+//! same "no" it gives for an unsupported profile, and the caller's honest
16+//! [`crate::demux::VP9_NEEDS_PLUGIN`] refusal covers both.
11 17
12 use std::ffi::{CString, c_char, c_void};18 use std::ffi::{CString, c_char, c_void};
13 use std::path::{Path, PathBuf};19 use std::path::{Path, PathBuf};
crates/engine/src/lib.rsmodified+1 -1
@@ -17,7 +17,7 @@ pub mod waveform;
17 pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession};17 pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession};
18 pub use clock::PlaybackClock;18 pub use clock::PlaybackClock;
19 pub use decode::{DecodeSession, Frame};19 pub use decode::{DecodeSession, Frame};
20-pub use demux::VideoMeta;20+pub use demux::{Codec, VideoMeta};
21 pub use export::ExportHandle;21 pub use export::ExportHandle;
22 pub use mux::{AudioParams, Mp4Muxer, VideoParams};22 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
23 pub use playback::PlaybackSession;23 pub use playback::PlaybackSession;
crates/engine/src/playback.rsmodified+12 -0
@@ -716,6 +716,18 @@ fn matches_timeline(
716 timeline: &VideoMeta,716 timeline: &VideoMeta,
717 first: &Option<crate::AudioProbe>,717 first: &Option<crate::AudioProbe>,
718 ) -> crate::Result<()> {718 ) -> crate::Result<()> {
719+ // Codec first: one timeline is one kind of source. Mixing them would decode
720+ // (every clip opens its own decoder) but on a machine without the VA-API
721+ // plugin the VP9 half would be black frames with the refusal only on
722+ // stderr, which is exactly what a front-end cannot show.
723+ if meta.codec != timeline.codec {
724+ return Err(format!(
725+ "{} does not match the timeline's {}",
726+ meta.codec.name(),
727+ timeline.codec.name()
728+ )
729+ .into());
730+ }
719 if (meta.width, meta.height) != (timeline.width, timeline.height) {731 if (meta.width, meta.height) != (timeline.width, timeline.height) {
720 return Err(format!(732 return Err(format!(
721 "{}x{} does not match the timeline's {}x{}",733 "{}x{} does not match the timeline's {}x{}",
crates/engine/tests/vp9.rsadded+146 -0
@@ -0,0 +1,146 @@
1+//! VP9 import: the first source codec that is not H.264.
2+//!
3+//! The container and refusal checks need nothing installed. The decode and
4+//! export twins need a built `libengine_hw.so` and a VA-API driver with a VP9
5+//! decode entrypoint (`vainfo | grep VP9`), so they are `#[ignore]`d:
6+//!
7+//! ```text
8+//! cargo build -p engine -p engine-hw --release
9+//! LD_LIBRARY_PATH=target/release \
10+//! cargo test -p engine --release --test vp9 -- --include-ignored --nocapture --test-threads=1
11+//! ```
12+//!
13+//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it
14+//! and puts it back so the hardware twins below really are hardware.
15+
16+use std::path::PathBuf;
17+use std::time::{Duration, Instant};
18+
19+use engine::demux::{Codec, Demuxer};
20+use engine::export::ExportSettings;
21+use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
22+
23+/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
24+const FRAMES: u32 = 60;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+/// The container half: a vp09 track is found, described and named as VP9, and
33+/// its AAC track is read exactly as any other file's -- the audio path knows
34+/// nothing about the video codec and this is what says so.
35+#[test]
36+fn the_demuxer_reports_a_vp9_track() {
37+ let (meta, _) = Demuxer::open(&asset("test_vp9.mp4")).expect("open test_vp9.mp4");
38+ assert_eq!(meta.codec, Codec::Vp9);
39+ assert_eq!((meta.width, meta.height), (1280, 720));
40+ assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
41+ assert_eq!(meta.frame_count, FRAMES);
42+
43+ let probe = AudioSession::probe(asset("test_vp9.mp4"))
44+ .expect("probe")
45+ .expect("the fixture has an AAC track");
46+ assert_eq!(
47+ (probe.params.sample_rate, probe.channels),
48+ (44_100, 2),
49+ "audio is read the same whatever the picture is coded with"
50+ );
51+
52+ // The invariant, stated as an assert: H.264 files still say H.264.
53+ let (h264, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open test_baseline.mp4");
54+ assert_eq!(h264.codec, Codec::H264);
55+}
56+
57+/// There is no software VP9 decoder, so the software path must refuse by name
58+/// rather than feed VP9 bytes to `rusty_h264` -- and it must refuse where a
59+/// caller can still show it, i.e. out of `open`, not from inside the worker.
60+#[test]
61+fn the_software_path_refuses_vp9_by_name() {
62+ // SAFETY: the suite is documented to run with --test-threads=1.
63+ unsafe { std::env::set_var("VE_SW", "1") };
64+ let refused =
65+ DecodeSession::open(asset("test_vp9.mp4")).expect_err("software must not accept VP9");
66+ let refused = refused.to_string();
67+ // Restored immediately: the hardware tests in this binary share the process.
68+ unsafe { std::env::remove_var("VE_SW") };
69+
70+ assert!(refused.contains("VP9"), "{refused}");
71+ assert!(refused.contains("plugin"), "{refused}");
72+ // H.264 is untouched by all of this.
73+ unsafe { std::env::set_var("VE_SW", "1") };
74+ let h264 = DecodeSession::open(asset("test_baseline.mp4")).is_ok();
75+ unsafe { std::env::remove_var("VE_SW") };
76+ assert!(h264, "software H.264 decode still opens");
77+}
78+
79+/// A VP9 timeline is refused a source coded differently, in the same words a
80+/// resolution mismatch is refused in: a front-end shows the string as it is.
81+#[test]
82+fn a_timeline_refuses_the_other_codec() {
83+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
84+ let refused = session
85+ .import(&asset("test_vp9.mp4"))
86+ .expect_err("VP9 must not join an H.264 timeline")
87+ .to_string();
88+ assert!(refused.contains("VP9"), "{refused}");
89+ assert!(refused.contains("H.264"), "{refused}");
90+}
91+
92+/// The end-to-end user path: opening the file yields pictures, all of them,
93+/// through the plugin.
94+#[test]
95+#[ignore = "needs libengine_hw.so and a VA-API driver with VP9 decode"]
96+fn the_plugin_decodes_every_vp9_frame() {
97+ let start = Instant::now();
98+ let (meta, frames) = DecodeSession::open(asset("test_vp9.mp4")).expect("open test_vp9.mp4");
99+ assert_eq!(meta.codec, Codec::Vp9);
100+ let frames: Vec<_> = frames.into_iter().collect();
101+ eprintln!(
102+ "test_vp9.mp4: {} frames in {:?}",
103+ frames.len(),
104+ start.elapsed()
105+ );
106+
107+ assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
108+ for (i, frame) in frames.iter().enumerate() {
109+ assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
110+ assert_eq!(frame.index, i as u32, "frames arrive in display order");
111+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
112+ }
113+ // A picture, not a flat surface: a driver handing back an untouched buffer
114+ // would satisfy every count above.
115+ let first = &frames[0].bgra;
116+ assert!(
117+ first.chunks_exact(4).any(|px| px != &first[..4]),
118+ "frame 0 is a single colour -- no picture was decoded"
119+ );
120+}
121+
122+/// Export re-encodes to H.264 whatever the source was coded with: the packet
123+/// copy path is audio-only, so no VP9 byte can reach an `avc1` track.
124+#[test]
125+#[ignore = "needs libengine_hw.so and a VA-API driver with VP9 decode"]
126+fn a_vp9_source_exports_as_h264() {
127+ let session = PlaybackSession::open(asset("test_vp9.mp4")).expect("open test_vp9.mp4");
128+ let meta = *session.meta();
129+ let project = Project::single(asset("test_vp9.mp4"), meta.frame_count);
130+ let out = std::env::temp_dir().join(format!("ve_export_vp9_{}.mp4", std::process::id()));
131+ let _ = std::fs::remove_file(&out);
132+
133+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
134+ let started = Instant::now();
135+ while !handle.is_finished() {
136+ assert!(started.elapsed() < Duration::from_secs(120), "export hung");
137+ std::thread::sleep(Duration::from_millis(20));
138+ }
139+ handle.result().expect("outcome").expect("export");
140+
141+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
142+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
143+ assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
144+ assert_eq!((written.width, written.height), (1280, 720));
145+ let _ = std::fs::remove_file(&out);
146+}
scripts/gen_fixtures.shmodified+9 -0
@@ -25,6 +25,15 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \
25 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \25 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
26 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \26 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
27 -c:a aac -b:a 128k assets/test_av2.mp427 -c:a aac -b:a 128k assets/test_av2.mp4
28+# VP9 fixture: the same A/V shape as test_av.mp4 (1280x720@30, AAC-LC 44.1k
29+# stereo) with a VP9 picture, so what the tests measure is the codec and
30+# nothing else. 2 s, because VP9 only ever decodes on the hardware path.
31+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
32+ -f lavfi -i "sine=frequency=440:duration=2" \
33+ -f lavfi -i "sine=frequency=880:duration=2" \
34+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
35+ -map 0:v -map "[a]" -c:v libvpx-vp9 -b:v 2M -pix_fmt yuv420p \
36+ -c:a aac -b:a 128k assets/test_vp9.mp4
28 # Mismatch fixture: different resolution and no audio track at all, so import37 # Mismatch fixture: different resolution and no audio track at all, so import
29 # has something concrete to refuse.38 # has something concrete to refuse.
30 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \39 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \