Merge branch 'worktree-agent-a61cebf8c084145fe'
Browse files at this commit9 changed files +297 -21
- crates/engine-hw/src/lib.rs +46 -9
- crates/engine/src/decode.rs +15 -1
- crates/engine/src/demux.rs +54 -9
- crates/engine/src/export.rs +8 -1
- crates/engine/src/hw.rs +6 -0
- crates/engine/src/lib.rs +1 -1
- crates/engine/src/playback.rs +12 -0
- crates/engine/tests/vp9.rs +146 -0
- scripts/gen_fixtures.sh +9 -0
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 main | 1 | +//! 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 is | 2 | +//! 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 a | 4 | //! `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 software | 5 | //! 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 | }); |
| @@ -195,11 +228,12 @@ impl Session { | |||
| 195 | // Stop draining as soon as we have a picture: every handle we hold | 228 | // Stop draining as soon as we have a picture: every handle we hold |
| 196 | // keeps a pool buffer out of circulation. | 229 | // keeps a pool buffer out of circulation. |
| 197 | while self.ready.is_empty() { | 230 | while self.ready.is_empty() { |
| 198 | - match self.decoder.next_event() { | 231 | + match self.decoder.get().next_event() { |
| 199 | Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), | 232 | Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), |
| 200 | Some(DecoderEvent::FormatChanged) => { | 233 | Some(DecoderEvent::FormatChanged) => { |
| 201 | let info = self | 234 | let info = self |
| 202 | .decoder | 235 | .decoder |
| 236 | + .get() | ||
| 203 | .stream_info() | 237 | .stream_info() |
| 204 | .ok_or("format changed without stream info")? | 238 | .ok_or("format changed without stream info")? |
| 205 | .clone(); | 239 | .clone(); |
| @@ -226,7 +260,7 @@ impl Session { | |||
| 226 | match self.demuxer.next_access_unit() { | 260 | match self.demuxer.next_access_unit() { |
| 227 | Ok(Some(au)) => self.pending = au, | 261 | Ok(Some(au)) => self.pending = au, |
| 228 | Ok(None) => { | 262 | Ok(None) => { |
| 229 | - self.decoder.flush().map_err(|e| e.to_string())?; | 263 | + self.decoder.get().flush().map_err(|e| e.to_string())?; |
| 230 | self.flushed = true; | 264 | self.flushed = true; |
| 231 | continue; | 265 | continue; |
| 232 | } | 266 | } |
| @@ -241,7 +275,10 @@ impl Session { | |||
| 241 | timestamp, | 275 | timestamp, |
| 242 | .. | 276 | .. |
| 243 | } = self; | 277 | } = self; |
| 244 | - match decoder.decode(*timestamp, pending, &mut || pool.alloc()) { | 278 | + match decoder |
| 279 | + .get() | ||
| 280 | + .decode(*timestamp, pending, &mut || pool.alloc()) | ||
| 281 | + { | ||
| 245 | Ok(0) => return Err("decoder consumed no input".into()), | 282 | Ok(0) => return Err("decoder consumed no input".into()), |
| 246 | Ok(n) => { | 283 | Ok(n) => { |
| 247 | pending.drain(..n.min(pending.len())); | 284 | 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 the | 193 | // 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; |
| @@ -10,12 +12,38 @@ use crate::audio::{edit_media_time, packet_at, stts_pairs}; | |||
| 10 | 12 | ||
| 11 | const START_CODE: [u8; 4] = [0, 0, 0, 1]; | 13 | const START_CODE: [u8; 4] = [0, 0, 0, 1]; |
| 12 | 14 | ||
| 15 | +/// What the video track is coded with. Not a decoder choice by itself: VP9 has | ||
| 16 | +/// no software decoder at all, which is what [`VP9_NEEDS_PLUGIN`] says. | ||
| 17 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 18 | +pub enum Codec { | ||
| 19 | + H264, | ||
| 20 | + Vp9, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +impl Codec { | ||
| 24 | + /// How a refusal names it, and how a mismatch reads to a user. | ||
| 25 | + pub fn name(self) -> &'static str { | ||
| 26 | + match self { | ||
| 27 | + Self::H264 => "H.264", | ||
| 28 | + Self::Vp9 => "VP9", | ||
| 29 | + } | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// Why a VP9 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, so | ||
| 35 | +/// without the plugin there is nothing to decode with. Shared so playback and | ||
| 36 | +/// export refuse in the same words. | ||
| 37 | +pub const VP9_NEEDS_PLUGIN: &str = | ||
| 38 | + "VP9 needs the VA-API plugin (libengine_hw.so) — there is no software VP9 decoder"; | ||
| 39 | + | ||
| 13 | #[derive(Debug, Clone, Copy, PartialEq)] | 40 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 14 | pub struct VideoMeta { | 41 | pub struct VideoMeta { |
| 15 | pub width: u32, | 42 | pub width: u32, |
| 16 | pub height: u32, | 43 | pub height: u32, |
| 17 | pub frame_rate: f64, | 44 | pub frame_rate: f64, |
| 18 | pub frame_count: u32, | 45 | pub frame_count: u32, |
| 46 | + pub codec: Codec, | ||
| 19 | } | 47 | } |
| 20 | 48 | ||
| 21 | pub struct Demuxer { | 49 | pub struct Demuxer { |
| @@ -26,7 +54,9 @@ pub struct Demuxer { | |||
| 26 | /// a couple of frames into the media, exactly as it does for audio priming | 54 | /// a couple of frames into the media, exactly as it does for audio priming |
| 27 | /// (`audio::priming_samples`), and frame indices count from there. | 55 | /// (`audio::priming_samples`), and frame indices count from there. |
| 28 | first_sample: u32, | 56 | first_sample: u32, |
| 29 | - /// Annex-B SPS+PPS, re-injected ahead of every sync sample. | 57 | + codec: Codec, |
| 58 | + /// Annex-B SPS+PPS, re-injected ahead of every sync sample. Empty for VP9, | ||
| 59 | + /// which carries no out-of-band parameter sets. | ||
| 30 | parameter_sets: Vec<u8>, | 60 | parameter_sets: Vec<u8>, |
| 31 | /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box | 61 | /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box |
| 32 | /// at all, i.e. every sample is a sync sample. | 62 | /// at all, i.e. every sample is a sync sample. |
| @@ -43,8 +73,13 @@ impl Demuxer { | |||
| 43 | let track = reader | 73 | let track = reader |
| 44 | .tracks() | 74 | .tracks() |
| 45 | .values() | 75 | .values() |
| 46 | - .find(|t| matches!(t.media_type(), Ok(MediaType::H264))) | 76 | + .find_map(|t| match t.media_type() { |
| 47 | - .ok_or("no H.264 video track in file")?; | 77 | + Ok(MediaType::H264) => Some((t, Codec::H264)), |
| 78 | + Ok(MediaType::VP9) => Some((t, Codec::Vp9)), | ||
| 79 | + _ => None, | ||
| 80 | + }) | ||
| 81 | + .ok_or("no H.264 or VP9 video track in file")?; | ||
| 82 | + let (track, codec) = track; | ||
| 48 | 83 | ||
| 49 | let track_id = track.track_id(); | 84 | let track_id = track.track_id(); |
| 50 | let meta = VideoMeta { | 85 | let meta = VideoMeta { |
| @@ -52,13 +87,16 @@ impl Demuxer { | |||
| 52 | height: track.height() as u32, | 87 | height: track.height() as u32, |
| 53 | frame_rate: frame_rate(track), | 88 | frame_rate: frame_rate(track), |
| 54 | frame_count: 0, | 89 | frame_count: 0, |
| 90 | + codec, | ||
| 55 | }; | 91 | }; |
| 56 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); | 92 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); |
| 57 | let mut parameter_sets = Vec::new(); | 93 | let mut parameter_sets = Vec::new(); |
| 58 | - parameter_sets.extend_from_slice(&START_CODE); | 94 | + if codec == Codec::H264 { |
| 59 | - parameter_sets.extend_from_slice(track.sequence_parameter_set()?); | 95 | + parameter_sets.extend_from_slice(&START_CODE); |
| 60 | - parameter_sets.extend_from_slice(&START_CODE); | 96 | + parameter_sets.extend_from_slice(track.sequence_parameter_set()?); |
| 61 | - parameter_sets.extend_from_slice(track.picture_parameter_set()?); | 97 | + parameter_sets.extend_from_slice(&START_CODE); |
| 98 | + parameter_sets.extend_from_slice(track.picture_parameter_set()?); | ||
| 99 | + } | ||
| 62 | let sync_samples = track | 100 | let sync_samples = track |
| 63 | .trak | 101 | .trak |
| 64 | .mdia | 102 | .mdia |
| @@ -85,6 +123,7 @@ impl Demuxer { | |||
| 85 | track_id, | 123 | track_id, |
| 86 | sample_count, | 124 | sample_count, |
| 87 | first_sample, | 125 | first_sample, |
| 126 | + codec, | ||
| 88 | parameter_sets, | 127 | parameter_sets, |
| 89 | sync_samples, | 128 | sync_samples, |
| 90 | next_sample, | 129 | next_sample, |
| @@ -92,7 +131,8 @@ impl Demuxer { | |||
| 92 | )) | 131 | )) |
| 93 | } | 132 | } |
| 94 | 133 | ||
| 95 | - /// Next access unit in decode order, Annex-B framed. `None` at end of track. | 134 | + /// Next access unit in decode order: Annex-B framed for H.264, the mp4 |
| 135 | + /// sample verbatim for VP9. `None` at end of track. | ||
| 96 | pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { | 136 | pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { |
| 97 | if self.next_sample > self.sample_count { | 137 | if self.next_sample > self.sample_count { |
| 98 | return Ok(None); | 138 | return Ok(None); |
| @@ -102,6 +142,11 @@ impl Demuxer { | |||
| 102 | let Some(sample) = sample else { | 142 | let Some(sample) = sample else { |
| 103 | return Ok(None); | 143 | return Ok(None); |
| 104 | }; | 144 | }; |
| 145 | + // A VP9 mp4 sample is one (super)frame the decoder parses on its own: | ||
| 146 | + // no length prefixes to strip, no parameter sets to re-inject. | ||
| 147 | + if self.codec == Codec::Vp9 { | ||
| 148 | + return Ok(Some(sample.bytes.to_vec())); | ||
| 149 | + } | ||
| 105 | 150 | ||
| 106 | let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); | 151 | let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); |
| 107 | if sample.is_sync { | 152 | if sample.is_sync { |
crates/engine/src/export.rsmodified+8 -1
| @@ -475,7 +475,13 @@ struct SwDecoder { | |||
| 475 | 475 | ||
| 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 (_, 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 far | ||
| 480 | + // means the plugin refused it, and the export says so instead of | ||
| 481 | + // handing VP9 bytes to `rusty_h264`. | ||
| 482 | + if meta.codec != crate::demux::Codec::H264 { | ||
| 483 | + return Err(crate::demux::VP9_NEEDS_PLUGIN.into()); | ||
| 484 | + } | ||
| 479 | // Decoding restarts at a sync sample, so pictures between it and the in | 485 | // Decoding restarts at a sync sample, so pictures between it and the in |
| 480 | // point are decoded (the target references them) and then dropped. | 486 | // point are decoded (the target references them) and then dropped. |
| 481 | let index = demuxer.seek_to_sync_at_or_before(start_frame); | 487 | let index = demuxer.seek_to_sync_at_or_before(start_frame); |
| @@ -521,6 +527,7 @@ mod tests { | |||
| 521 | height, | 527 | height, |
| 522 | frame_rate, | 528 | frame_rate, |
| 523 | frame_count: 1, | 529 | frame_count: 1, |
| 530 | + codec: crate::demux::Codec::H264, | ||
| 524 | }; | 531 | }; |
| 525 | // 1280 * 720 * 30 * 0.1 | 532 | // 1280 * 720 * 30 * 0.1 |
| 526 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); | 533 | 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: a | 8 | //! 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 a | 9 | //! 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
| @@ -20,7 +20,7 @@ pub use audio::{ | |||
| 20 | }; | 20 | }; |
| 21 | pub use clock::PlaybackClock; | 21 | pub use clock::PlaybackClock; |
| 22 | pub use decode::{DecodeSession, Frame}; | 22 | pub use decode::{DecodeSession, Frame}; |
| 23 | -pub use demux::VideoMeta; | 23 | +pub use demux::{Codec, VideoMeta}; |
| 24 | pub use export::ExportHandle; | 24 | pub use export::ExportHandle; |
| 25 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | 25 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 26 | pub use playback::PlaybackSession; | 26 | pub use playback::PlaybackSession; |
crates/engine/src/playback.rsmodified+12 -0
| @@ -789,6 +789,18 @@ fn matches_timeline( | |||
| 789 | timeline: &VideoMeta, | 789 | timeline: &VideoMeta, |
| 790 | first: &Option<crate::AudioProbe>, | 790 | first: &Option<crate::AudioProbe>, |
| 791 | ) -> crate::Result<()> { | 791 | ) -> crate::Result<()> { |
| 792 | + // Codec first: one timeline is one kind of source. Mixing them would decode | ||
| 793 | + // (every clip opens its own decoder) but on a machine without the VA-API | ||
| 794 | + // plugin the VP9 half would be black frames with the refusal only on | ||
| 795 | + // stderr, which is exactly what a front-end cannot show. | ||
| 796 | + if meta.codec != timeline.codec { | ||
| 797 | + return Err(format!( | ||
| 798 | + "{} does not match the timeline's {}", | ||
| 799 | + meta.codec.name(), | ||
| 800 | + timeline.codec.name() | ||
| 801 | + ) | ||
| 802 | + .into()); | ||
| 803 | + } | ||
| 792 | if (meta.width, meta.height) != (timeline.width, timeline.height) { | 804 | if (meta.width, meta.height) != (timeline.width, timeline.height) { |
| 793 | return Err(format!( | 805 | return Err(format!( |
| 794 | "{}x{} does not match the timeline's {}x{}", | 806 | "{}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"), 0) | ||
| 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
| @@ -65,6 +65,15 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | |||
| 65 | -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 65 | -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 66 | -c:a aac -ar 44100 -ac 2 \ | 66 | -c:a aac -ar 44100 -ac 2 \ |
| 67 | -metadata:s:a:1 language=fra assets/test_multilang.mp4 | 67 | -metadata:s:a:1 language=fra assets/test_multilang.mp4 |
| 68 | +# VP9 fixture: the same A/V shape as test_av.mp4 (1280x720@30, AAC-LC 44.1k | ||
| 69 | +# stereo) with a VP9 picture, so what the tests measure is the codec and | ||
| 70 | +# nothing else. 2 s, because VP9 only ever decodes on the hardware path. | ||
| 71 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 72 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 73 | + -f lavfi -i "sine=frequency=880: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]" \ | ||
| 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.mp4 | ||
| 68 | # Mismatch fixture: different resolution and no audio track at all, so import | 77 | # Mismatch fixture: different resolution and no audio track at all, so import |
| 69 | # has something concrete to refuse. | 78 | # has something concrete to refuse. |
| 70 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ | 79 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |