#[doc(hidden)]
pub mod vp9_dec;
#[doc(hidden)]
pub mod vp9_simd;
use crate::vp9_dec::Decoder;
use crate::{
CancellationToken, Codec, CodecImplementation, CodecProfile, CodecSupport, DecodedVideoFrame,
EncodedVideoSample, Error, ErrorKind, HardwarePreference, Limits, PixelFormat, Result,
VideoDecoder, VideoDecoderConfig, VideoDecoderFactory, Vp9CodecConfig,
};
#[allow(unused_imports)]
use zvidlib_color::*;
#[allow(unused_imports)]
use zvidlib_core::*;
pub(crate) use zvidlib_vp9_syntax::picture_to_rgba;
#[cfg(test)]
#[allow(unused_imports)]
use zvidlib_container::*;
pub fn native_vp9_video_decoder_factory() -> impl VideoDecoderFactory {
Vp9DecoderFactory
}
#[derive(Clone, Copy, Debug)]
struct Vp9DecoderFactory;
impl VideoDecoderFactory for Vp9DecoderFactory {
fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
match self.capability_without_parsing(configuration) {
CodecSupport::Supported { .. } => {}
other => return other,
}
if let Err(error) = parse_configuration(configuration, &Limits::default()) {
return invalid_configuration(error.message());
}
if configuration.hardware != HardwarePreference::Avoid && hardware_available(configuration)
{
return CodecSupport::Supported {
implementation: CodecImplementation::Hardware,
};
}
if configuration.hardware == HardwarePreference::Require {
return CodecSupport::HardwareUnavailable;
}
CodecSupport::Supported {
implementation: CodecImplementation::Software,
}
}
fn create(
&self,
configuration: &VideoDecoderConfig,
limits: &Limits,
) -> Result<Box<dyn VideoDecoder>> {
match self.capability_without_parsing(configuration) {
CodecSupport::Supported { .. } => {}
CodecSupport::UnsupportedCodec => {
return Err(Error::new(
ErrorKind::Unsupported,
"native VP9 decoder requires VP9",
));
}
CodecSupport::UnsupportedProfile => {
return Err(Error::new(
ErrorKind::Unsupported,
"native VP9 decoder supports profile 0",
));
}
CodecSupport::HardwareUnavailable => unreachable!("hardware is not checked here"),
CodecSupport::InvalidConfiguration { reason } => {
return Err(Error::new(ErrorKind::InvalidInput, reason));
}
_ => {
return Err(Error::new(
ErrorKind::Unsupported,
"native VP9 decoder does not support this configuration",
));
}
}
parse_configuration(configuration, limits)?;
if configuration.hardware != HardwarePreference::Avoid {
let hardware_errors = match create_hardware(configuration, limits) {
Ok(decoder) => return Ok(decoder),
Err(errors) => errors,
};
if configuration.hardware == HardwarePreference::Require {
let detail = if hardware_errors.is_empty() {
"no accelerated backend exists for this target".to_owned()
} else {
hardware_errors.join("; ")
};
return Err(Error::new(
ErrorKind::Unsupported,
format!("hardware VP9 decoding is unavailable ({detail})"),
));
}
}
Ok(Box::new(Vp9Decoder {
limits: *limits,
inner: Decoder::new(*limits),
}))
}
}
impl Vp9DecoderFactory {
fn capability_without_parsing(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
if configuration.codec != Codec::Vp9 {
return CodecSupport::UnsupportedCodec;
}
if configuration.profile != CodecProfile::Vp9Profile0 {
return CodecSupport::UnsupportedProfile;
}
if configuration.output_format != PixelFormat::Rgba8 {
return invalid_configuration("native VP9 decoding currently outputs RGBA8");
}
CodecSupport::Supported {
implementation: CodecImplementation::Software,
}
}
}
fn hardware_available(_configuration: &VideoDecoderConfig) -> bool {
#[cfg(all(
feature = "hardware",
any(windows, target_os = "linux"),
target_pointer_width = "64"
))]
if zvidlib_hardware::nvdec::is_vp9_available(_configuration.coded_dimensions) {
return true;
}
#[cfg(all(feature = "hardware", windows))]
if zvidlib_hardware::windows_mf::is_vp9_available(_configuration.coded_dimensions) {
return true;
}
#[cfg(all(feature = "hardware", target_os = "macos"))]
if zvidlib_hardware::videotoolbox_vp9::is_vp9_available(_configuration.coded_dimensions) {
return true;
}
false
}
fn create_hardware(
_configuration: &VideoDecoderConfig,
_limits: &Limits,
) -> std::result::Result<Box<dyn VideoDecoder>, Vec<String>> {
#[cfg_attr(
not(all(
feature = "hardware",
any(
windows,
all(target_os = "linux", target_pointer_width = "64"),
target_os = "macos"
)
)),
allow(unused_mut)
)]
let mut errors = Vec::new();
#[cfg(all(
feature = "hardware",
any(windows, target_os = "linux"),
target_pointer_width = "64"
))]
match zvidlib_hardware::nvdec::create_vp9(_configuration, _limits) {
Ok(decoder) => return Ok(decoder),
Err(error) => errors.push(format!("NVDEC: {}", error.message())),
}
#[cfg(all(feature = "hardware", windows))]
match zvidlib_hardware::windows_mf::create_vp9(_configuration, _limits) {
Ok(decoder) => return Ok(decoder),
Err(error) => errors.push(format!("Media Foundation: {}", error.message())),
}
#[cfg(all(feature = "hardware", target_os = "macos"))]
match create_videotoolbox(_configuration, _limits) {
Ok(decoder) => return Ok(decoder),
Err(error) => errors.push(format!("VideoToolbox: {}", error.message())),
}
Err(errors)
}
#[cfg(all(feature = "hardware", target_os = "macos"))]
fn create_videotoolbox(
configuration: &VideoDecoderConfig,
limits: &Limits,
) -> Result<Box<dyn VideoDecoder>> {
zvidlib_hardware::videotoolbox_vp9::create_vp9(configuration, limits, replay)
}
#[cfg(all(feature = "hardware", target_os = "macos"))]
fn replay(
limits: &Limits,
history: &[Vec<u8>],
chunk: &[u8],
) -> Result<zvidlib_vp9_syntax::DecodedPicture> {
let mut decoder = Decoder::new(*limits);
decoder.set_output_wanted(false);
for earlier in history {
decoder.decode_chunk(earlier)?;
}
decoder.set_output_wanted(true);
decoder.decode_chunk(chunk)?.ok_or_else(|| {
Error::new(
ErrorKind::Codec,
"the VP9 frame shown again was not decoded",
)
})
}
fn invalid_configuration(reason: impl Into<String>) -> CodecSupport {
CodecSupport::InvalidConfiguration {
reason: reason.into(),
}
}
fn parse_configuration(configuration: &VideoDecoderConfig, limits: &Limits) -> Result<()> {
if configuration.configuration.len() as u64 > limits.max_allocation_bytes {
return Err(limit("VP9 configuration exceeds the allocation limit"));
}
let record = Vp9CodecConfig::parse(&configuration.configuration)
.map_err(|error| malformed(format!("invalid VP9 configuration: {error}")))?;
if record.profile != 0 || record.bit_depth != 8 || !record.is_420() {
return Err(Error::new(
ErrorKind::Unsupported,
"native VP9 decoder requires a profile 0, 8-bit 4:2:0 configuration",
));
}
Ok(())
}
struct Vp9Decoder {
limits: Limits,
inner: Decoder,
}
impl VideoDecoder for Vp9Decoder {
fn submit(
&mut self,
sample: &EncodedVideoSample,
cancellation: &CancellationToken,
) -> Result<Vec<DecodedVideoFrame>> {
cancellation.check()?;
if sample.data.len() as u64 > self.limits.max_allocation_bytes {
return Err(limit("VP9 sample exceeds the allocation limit"));
}
let shown_before = self.inner.frames_shown();
let picture = self.inner.decode_chunk(&sample.data)?;
if self.inner.frames_shown() == shown_before {
return Err(malformed("VP9 sample does not show a frame"));
}
let Some(picture) = picture else {
return Ok(Vec::new());
};
Ok(vec![DecodedVideoFrame {
presentation_index: sample.presentation_index,
frame: picture_to_rgba(&picture, &self.limits)?,
}])
}
fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
cancellation.check()?;
Ok(Vec::new())
}
fn reset(&mut self) -> Result<()> {
self.inner.reset();
Ok(())
}
fn set_output_wanted(&mut self, wanted: bool) {
self.inner.set_output_wanted(wanted);
}
}
fn malformed(message: impl Into<String>) -> Error {
Error::new(ErrorKind::MalformedMedia, message)
}
fn limit(message: impl Into<String>) -> Error {
Error::new(ErrorKind::ResourceLimit, message)
}
#[doc(hidden)]
#[must_use]
pub fn simd_sites() -> Vec<(&'static str, zvidlib_core::SimdIsa)> {
vec![("vp9_decode", vp9_simd::active_isa())]
}
#[cfg(test)]
mod tests {
use super::*;
use zvidlib_vp9_syntax::matrix_for;
fn vpcc(record: &[u8]) -> Vec<u8> {
let mut bytes = (12u32 + record.len() as u32).to_be_bytes().to_vec();
bytes.extend_from_slice(b"vpcC");
bytes.extend_from_slice(&[1, 0, 0, 0]);
bytes.extend_from_slice(record);
bytes
}
fn config() -> VideoDecoderConfig {
VideoDecoderConfig {
codec: Codec::Vp9,
profile: CodecProfile::Vp9Profile0,
coded_dimensions: VideoDimensions::new(16, 16, &Limits::default()).unwrap(),
output_format: PixelFormat::Rgba8,
color_range: ColorRange::Limited,
hardware: HardwarePreference::Avoid,
configuration: vpcc(&[0, 10, 0x80, 2, 2, 2, 0, 0]),
}
}
#[test]
fn capability_distinguishes_codec_profile_configuration_and_hardware() {
let factory = native_vp9_video_decoder_factory();
assert!(factory.capability(&config()).is_supported());
let mut candidate = config();
candidate.configuration = Vec::new();
assert!(factory.capability(&candidate).is_supported());
candidate = config();
candidate.codec = Codec::Av1;
assert_eq!(
factory.capability(&candidate),
CodecSupport::UnsupportedCodec
);
candidate = config();
candidate.profile = CodecProfile::Vp9Profile2;
assert_eq!(
factory.capability(&candidate),
CodecSupport::UnsupportedProfile
);
candidate = config();
candidate.hardware = HardwarePreference::Require;
let required = factory.capability(&candidate);
candidate.hardware = HardwarePreference::Prefer;
let preferred = factory.capability(&candidate);
if hardware_available(&candidate) {
let hardware = CodecSupport::Supported {
implementation: CodecImplementation::Hardware,
};
assert_eq!((required, preferred), (hardware.clone(), hardware));
} else {
assert_eq!(required, CodecSupport::HardwareUnavailable);
assert_eq!(
preferred,
CodecSupport::Supported {
implementation: CodecImplementation::Software
}
);
}
candidate = config();
candidate.output_format = PixelFormat::Yuv420p8;
assert!(matches!(
factory.capability(&candidate),
CodecSupport::InvalidConfiguration { .. }
));
for configuration in [
vpcc(&[0, 10, 0xa0, 2, 2, 2, 0, 0]),
vpcc(&[1, 10, 0x86, 2, 2, 2, 0, 0]),
vec![1, 2, 3],
] {
candidate = config();
candidate.configuration = configuration;
assert!(matches!(
factory.capability(&candidate),
CodecSupport::InvalidConfiguration { .. }
));
}
}
#[test]
fn create_rejects_malformed_configuration_and_samples() {
let mut candidate = config();
candidate.configuration = vec![1, 2, 3];
let error = native_vp9_video_decoder_factory()
.create(&candidate, &Limits::default())
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::MalformedMedia);
let mut decoder = native_vp9_video_decoder_factory()
.create(&config(), &Limits::default())
.unwrap();
for data in [vec![], vec![0xff, 0xff], vec![0x82, 0x49, 0x83]] {
let sample = EncodedVideoSample {
presentation_index: crate::FrameIndex(0),
random_access: true,
data,
};
let error = decoder
.submit(&sample, &CancellationToken::new())
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::MalformedMedia);
}
}
#[test]
fn create_enforces_allocation_limit() {
let restrictive = Limits {
max_allocation_bytes: 0,
..Limits::default()
};
let error = native_vp9_video_decoder_factory()
.create(&config(), &restrictive)
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::ResourceLimit);
}
#[test]
fn color_spaces_pick_their_matrix() {
assert_eq!(matrix_for(0), MatrixCoefficients::Bt601);
assert_eq!(matrix_for(1), MatrixCoefficients::Bt601);
assert_eq!(matrix_for(2), MatrixCoefficients::Bt709);
assert_eq!(matrix_for(3), MatrixCoefficients::Bt601);
assert_eq!(matrix_for(5), MatrixCoefficients::Bt2020Ncl);
}
#[cfg(any(
windows,
all(target_os = "linux", target_pointer_width = "64"),
target_os = "macos"
))]
#[test]
fn each_hardware_backend_matches_the_software_decoder_and_seeks_exactly() {
use crate::{
ExpectedVideoFrame, FrameDigest, FrameIndex, VideoDecoderConformanceVector,
verify_video_decoder_conformance,
};
type Create = fn(&VideoDecoderConfig, &Limits) -> Result<Box<dyn VideoDecoder>>;
struct Backend(Create);
impl VideoDecoderFactory for Backend {
fn capability(&self, _configuration: &VideoDecoderConfig) -> CodecSupport {
CodecSupport::Supported {
implementation: CodecImplementation::Hardware,
}
}
fn create(
&self,
configuration: &VideoDecoderConfig,
limits: &Limits,
) -> Result<Box<dyn VideoDecoder>> {
(self.0)(configuration, limits)
}
}
fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
use std::task::{Context, Poll, Waker};
let mut context = Context::from_waker(Waker::noop());
let mut future = Box::pin(future);
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
return value;
}
}
}
let backends: [(&str, Create); _] = [
#[cfg(all(
feature = "hardware",
any(windows, target_os = "linux"),
target_pointer_width = "64"
))]
("NVDEC", zvidlib_hardware::nvdec::create_vp9),
#[cfg(all(feature = "hardware", windows))]
("Media Foundation", zvidlib_hardware::windows_mf::create_vp9),
#[cfg(all(feature = "hardware", target_os = "macos"))]
("VideoToolbox", create_videotoolbox),
];
let limits = Limits::default();
let mut streams = Vec::new();
for (name, file) in [
(
"VP9 256x144 with hidden frames",
&include_bytes!("../tests/fixtures/vp9_bbb_256x144.mp4")[..],
),
(
"VP9 250x142",
&include_bytes!("../tests/fixtures/vp9_bbb_250x142.mp4")[..],
),
] {
let source = crate::io::MemorySource::new(file.to_vec());
let movie = block_on(crate::Mp4Demuxer::open(&source, Default::default())).unwrap();
let track = movie.track(1).unwrap();
let configuration = VideoDecoderConfig {
codec: Codec::Vp9,
profile: CodecProfile::Vp9Profile0,
coded_dimensions: track.dimensions.unwrap(),
output_format: PixelFormat::Rgba8,
color_range: ColorRange::Limited,
hardware: HardwarePreference::Avoid,
configuration: track.decoder_config.clone(),
};
let samples = block_on(track.to_encoded_video_samples(&source, &limits)).unwrap();
streams.push((name, configuration, samples));
}
let (_, configuration, samples) = &streams[0];
let mut existing = samples[..4].to_vec();
for slot in 0..8u8 {
existing.push(EncodedVideoSample {
presentation_index: FrameIndex(existing.len() as u64),
random_access: false,
data: vec![0x88 | slot],
});
}
streams.push(("VP9 show_existing_frame", configuration.clone(), existing));
let cancellation = CancellationToken::new();
let software = native_vp9_video_decoder_factory();
for (backend, create) in backends {
let factory = Backend(create);
if let Err(error) = factory.create(&streams[0].1, &limits) {
eprintln!("skipping {backend}: hardware VP9 decoding unavailable: {error}");
continue;
}
for (name, configuration, samples) in &streams {
let decode = |factory: &dyn VideoDecoderFactory| {
let mut decoder = factory.create(configuration, &limits).unwrap();
let mut digests = Vec::new();
for sample in samples {
let outputs = decoder
.submit(sample, &cancellation)
.unwrap_or_else(|error| panic!("{backend} {name}: {error}"));
assert_eq!(outputs.len(), 1, "{backend} {name}");
assert_eq!(outputs[0].presentation_index, sample.presentation_index);
digests.push(FrameDigest::from_frame(&outputs[0].frame).unwrap());
}
assert!(decoder.drain(&cancellation).unwrap().is_empty());
digests
};
let expected = decode(&software);
assert_eq!(decode(&factory), expected, "{backend} {name}");
let vector = VideoDecoderConformanceVector {
name: (*name).into(),
configuration: configuration.clone(),
expected_frames: expected
.iter()
.enumerate()
.map(|(index, &digest)| ExpectedVideoFrame {
presentation_index: FrameIndex(index as u64),
digest,
})
.collect(),
samples: samples.clone(),
};
verify_video_decoder_conformance(&factory, &vector, limits)
.unwrap_or_else(|error| panic!("{backend} {name}: {error}"));
}
eprintln!("{backend}: every VP9 frame matches the software decoder");
}
}
}