Skip to main content

zvidlib_vp9_decoder/
lib.rs

1//! Native VP9 decoding, registered as a [`VideoDecoderFactory`]: a
2//! dependency-free software decoder, and the platform's hardware decoder
3//! where the host has one.
4//!
5//! This wraps the crate's VP9 profile 0 decoder (`crate::vp9_dec`), which
6//! decodes 8-bit 4:2:0 streams bit for bit as libvpx does: hidden frames,
7//! superframes, `show_existing_frame`, intra-only frames, reference frames
8//! of another size, tiles, segmentation, lossless coding and every
9//! interpolation filter.
10//!
11//! A sample is one VP9 chunk as the VP9 ISO-BMFF binding defines it: a frame,
12//! or a superframe whose hidden frames precede the one it shows. Each sample
13//! must show a frame. Decoded pictures are converted to `Rgba8` with
14//! [`convert_to_rgba8`], using the matrix the frame's `color_space` names
15//! (BT.601 when it is unknown or one the conversion does not implement), at
16//! the size the frame was coded at: a stream that changes resolution emits
17//! frames of each size.
18//!
19//! The hardware backends decode the same chunks. A chunk's headers are read
20//! before it reaches the platform decoder, so each sample still shows exactly
21//! one frame, and the decoded picture is cropped to the size its header names
22//! and converted by [`picture_to_rgba`] with the colour space and range the
23//! header names, exactly as a software picture is.
24
25#[doc(hidden)]
26pub mod vp9_dec;
27#[doc(hidden)]
28pub mod vp9_simd;
29
30use crate::vp9_dec::Decoder;
31use crate::{
32    CancellationToken, Codec, CodecImplementation, CodecProfile, CodecSupport, DecodedVideoFrame,
33    EncodedVideoSample, Error, ErrorKind, HardwarePreference, Limits, PixelFormat, Result,
34    VideoDecoder, VideoDecoderConfig, VideoDecoderFactory, Vp9CodecConfig,
35};
36#[allow(unused_imports)]
37use zvidlib_color::*;
38#[allow(unused_imports)]
39use zvidlib_core::*;
40pub(crate) use zvidlib_vp9_syntax::picture_to_rgba;
41// The containers the tests read their fixtures from.
42#[cfg(test)]
43#[allow(unused_imports)]
44use zvidlib_container::*;
45
46/// Returns the native VP9 profile 0 (8-bit 4:2:0) decoder backend.
47///
48/// `Prefer` and `Require` select a hardware decoder where the host has one
49/// that decodes VP9 profile 0 at the configured size: NVIDIA NVDEC on 64-bit
50/// Windows and Linux, then Media Foundation on Windows adapters that expose the
51/// D3D11 VP9 profile 0 decoder, and VideoToolbox on Macs whose media engine
52/// decodes VP9.
53/// `Prefer` falls back to the dependency-free software
54/// decoder when none is available, and `Require` reports
55/// [`CodecSupport::HardwareUnavailable`]. `Avoid` always selects software.
56pub fn native_vp9_video_decoder_factory() -> impl VideoDecoderFactory {
57    Vp9DecoderFactory
58}
59
60#[derive(Clone, Copy, Debug)]
61struct Vp9DecoderFactory;
62
63impl VideoDecoderFactory for Vp9DecoderFactory {
64    fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
65        match self.capability_without_parsing(configuration) {
66            CodecSupport::Supported { .. } => {}
67            other => return other,
68        }
69        if let Err(error) = parse_configuration(configuration, &Limits::default()) {
70            return invalid_configuration(error.message());
71        }
72        if configuration.hardware != HardwarePreference::Avoid && hardware_available(configuration)
73        {
74            return CodecSupport::Supported {
75                implementation: CodecImplementation::Hardware,
76            };
77        }
78        if configuration.hardware == HardwarePreference::Require {
79            return CodecSupport::HardwareUnavailable;
80        }
81        CodecSupport::Supported {
82            implementation: CodecImplementation::Software,
83        }
84    }
85
86    fn create(
87        &self,
88        configuration: &VideoDecoderConfig,
89        limits: &Limits,
90    ) -> Result<Box<dyn VideoDecoder>> {
91        match self.capability_without_parsing(configuration) {
92            CodecSupport::Supported { .. } => {}
93            CodecSupport::UnsupportedCodec => {
94                return Err(Error::new(
95                    ErrorKind::Unsupported,
96                    "native VP9 decoder requires VP9",
97                ));
98            }
99            CodecSupport::UnsupportedProfile => {
100                return Err(Error::new(
101                    ErrorKind::Unsupported,
102                    "native VP9 decoder supports profile 0",
103                ));
104            }
105            CodecSupport::HardwareUnavailable => unreachable!("hardware is not checked here"),
106            CodecSupport::InvalidConfiguration { reason } => {
107                return Err(Error::new(ErrorKind::InvalidInput, reason));
108            }
109            _ => {
110                return Err(Error::new(
111                    ErrorKind::Unsupported,
112                    "native VP9 decoder does not support this configuration",
113                ));
114            }
115        }
116        parse_configuration(configuration, limits)?;
117        if configuration.hardware != HardwarePreference::Avoid {
118            let hardware_errors = match create_hardware(configuration, limits) {
119                Ok(decoder) => return Ok(decoder),
120                Err(errors) => errors,
121            };
122            if configuration.hardware == HardwarePreference::Require {
123                let detail = if hardware_errors.is_empty() {
124                    "no accelerated backend exists for this target".to_owned()
125                } else {
126                    hardware_errors.join("; ")
127                };
128                return Err(Error::new(
129                    ErrorKind::Unsupported,
130                    format!("hardware VP9 decoding is unavailable ({detail})"),
131                ));
132            }
133        }
134        Ok(Box::new(Vp9Decoder {
135            limits: *limits,
136            inner: Decoder::new(*limits),
137        }))
138    }
139}
140
141impl Vp9DecoderFactory {
142    fn capability_without_parsing(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
143        if configuration.codec != Codec::Vp9 {
144            return CodecSupport::UnsupportedCodec;
145        }
146        if configuration.profile != CodecProfile::Vp9Profile0 {
147            return CodecSupport::UnsupportedProfile;
148        }
149        if configuration.output_format != PixelFormat::Rgba8 {
150            return invalid_configuration("native VP9 decoding currently outputs RGBA8");
151        }
152        CodecSupport::Supported {
153            implementation: CodecImplementation::Software,
154        }
155    }
156}
157
158fn hardware_available(_configuration: &VideoDecoderConfig) -> bool {
159    #[cfg(all(
160        feature = "hardware",
161        any(windows, target_os = "linux"),
162        target_pointer_width = "64"
163    ))]
164    if zvidlib_hardware::nvdec::is_vp9_available(_configuration.coded_dimensions) {
165        return true;
166    }
167    #[cfg(all(feature = "hardware", windows))]
168    if zvidlib_hardware::windows_mf::is_vp9_available(_configuration.coded_dimensions) {
169        return true;
170    }
171    #[cfg(all(feature = "hardware", target_os = "macos"))]
172    if zvidlib_hardware::videotoolbox_vp9::is_vp9_available(_configuration.coded_dimensions) {
173        return true;
174    }
175    false
176}
177
178/// Creates the first hardware decoder that accepts the configuration, in the
179/// order [`hardware_available`] checks them, or says why each refused it.
180fn create_hardware(
181    _configuration: &VideoDecoderConfig,
182    _limits: &Limits,
183) -> std::result::Result<Box<dyn VideoDecoder>, Vec<String>> {
184    #[cfg_attr(
185        not(all(
186            feature = "hardware",
187            any(
188                windows,
189                all(target_os = "linux", target_pointer_width = "64"),
190                target_os = "macos"
191            )
192        )),
193        allow(unused_mut)
194    )]
195    let mut errors = Vec::new();
196    #[cfg(all(
197        feature = "hardware",
198        any(windows, target_os = "linux"),
199        target_pointer_width = "64"
200    ))]
201    match zvidlib_hardware::nvdec::create_vp9(_configuration, _limits) {
202        Ok(decoder) => return Ok(decoder),
203        Err(error) => errors.push(format!("NVDEC: {}", error.message())),
204    }
205    #[cfg(all(feature = "hardware", windows))]
206    match zvidlib_hardware::windows_mf::create_vp9(_configuration, _limits) {
207        Ok(decoder) => return Ok(decoder),
208        Err(error) => errors.push(format!("Media Foundation: {}", error.message())),
209    }
210    #[cfg(all(feature = "hardware", target_os = "macos"))]
211    match create_videotoolbox(_configuration, _limits) {
212        Ok(decoder) => return Ok(decoder),
213        Err(error) => errors.push(format!("VideoToolbox: {}", error.message())),
214    }
215    Err(errors)
216}
217
218/// VideoToolbox, which shows a hidden frame again by replaying it through the
219/// software decoder.
220#[cfg(all(feature = "hardware", target_os = "macos"))]
221fn create_videotoolbox(
222    configuration: &VideoDecoderConfig,
223    limits: &Limits,
224) -> Result<Box<dyn VideoDecoder>> {
225    zvidlib_hardware::videotoolbox_vp9::create_vp9(configuration, limits, replay)
226}
227
228/// Decodes `history` and then `chunk`, returning the picture `chunk` outputs.
229#[cfg(all(feature = "hardware", target_os = "macos"))]
230fn replay(
231    limits: &Limits,
232    history: &[Vec<u8>],
233    chunk: &[u8],
234) -> Result<zvidlib_vp9_syntax::DecodedPicture> {
235    let mut decoder = Decoder::new(*limits);
236    decoder.set_output_wanted(false);
237    for earlier in history {
238        decoder.decode_chunk(earlier)?;
239    }
240    decoder.set_output_wanted(true);
241    decoder.decode_chunk(chunk)?.ok_or_else(|| {
242        Error::new(
243            ErrorKind::Codec,
244            "the VP9 frame shown again was not decoded",
245        )
246    })
247}
248
249fn invalid_configuration(reason: impl Into<String>) -> CodecSupport {
250    CodecSupport::InvalidConfiguration {
251        reason: reason.into(),
252    }
253}
254
255/// Validates the track's `vpcC` box (or WebM `CodecPrivate`). Either may be
256/// empty or absent from a stream, since the VP9 bitstream describes itself;
257/// when present it must describe a profile 0 8-bit 4:2:0 stream.
258fn parse_configuration(configuration: &VideoDecoderConfig, limits: &Limits) -> Result<()> {
259    if configuration.configuration.len() as u64 > limits.max_allocation_bytes {
260        return Err(limit("VP9 configuration exceeds the allocation limit"));
261    }
262    let record = Vp9CodecConfig::parse(&configuration.configuration)
263        .map_err(|error| malformed(format!("invalid VP9 configuration: {error}")))?;
264    if record.profile != 0 || record.bit_depth != 8 || !record.is_420() {
265        return Err(Error::new(
266            ErrorKind::Unsupported,
267            "native VP9 decoder requires a profile 0, 8-bit 4:2:0 configuration",
268        ));
269    }
270    Ok(())
271}
272
273struct Vp9Decoder {
274    limits: Limits,
275    inner: Decoder,
276}
277
278impl VideoDecoder for Vp9Decoder {
279    fn submit(
280        &mut self,
281        sample: &EncodedVideoSample,
282        cancellation: &CancellationToken,
283    ) -> Result<Vec<DecodedVideoFrame>> {
284        cancellation.check()?;
285        if sample.data.len() as u64 > self.limits.max_allocation_bytes {
286            return Err(limit("VP9 sample exceeds the allocation limit"));
287        }
288        let shown_before = self.inner.frames_shown();
289        let picture = self.inner.decode_chunk(&sample.data)?;
290        if self.inner.frames_shown() == shown_before {
291            return Err(malformed("VP9 sample does not show a frame"));
292        }
293        let Some(picture) = picture else {
294            // The caller asked not to see this frame.
295            return Ok(Vec::new());
296        };
297        Ok(vec![DecodedVideoFrame {
298            presentation_index: sample.presentation_index,
299            frame: picture_to_rgba(&picture, &self.limits)?,
300        }])
301    }
302
303    fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
304        cancellation.check()?;
305        // Every sample shows its frame as it is decoded; nothing is held
306        // back for reordering.
307        Ok(Vec::new())
308    }
309
310    fn reset(&mut self) -> Result<()> {
311        self.inner.reset();
312        Ok(())
313    }
314
315    fn set_output_wanted(&mut self, wanted: bool) {
316        // The frame is still decoded and kept as a reference; only the
317        // copy out of the reference buffer and the YUV-to-RGBA pass are
318        // skipped.
319        self.inner.set_output_wanted(wanted);
320    }
321}
322
323fn malformed(message: impl Into<String>) -> Error {
324    Error::new(ErrorKind::MalformedMedia, message)
325}
326
327fn limit(message: impl Into<String>) -> Error {
328    Error::new(ErrorKind::ResourceLimit, message)
329}
330
331/// The SIMD dispatch sites in this crate, each with the instruction set it
332/// resolves to right now. `zvidlib::simd::active_by_site` reports every crate's
333/// sites together and documents what each one covers.
334#[doc(hidden)]
335#[must_use]
336pub fn simd_sites() -> Vec<(&'static str, zvidlib_core::SimdIsa)> {
337    vec![("vp9_decode", vp9_simd::active_isa())]
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use zvidlib_vp9_syntax::matrix_for;
344
345    fn vpcc(record: &[u8]) -> Vec<u8> {
346        let mut bytes = (12u32 + record.len() as u32).to_be_bytes().to_vec();
347        bytes.extend_from_slice(b"vpcC");
348        bytes.extend_from_slice(&[1, 0, 0, 0]);
349        bytes.extend_from_slice(record);
350        bytes
351    }
352
353    fn config() -> VideoDecoderConfig {
354        VideoDecoderConfig {
355            codec: Codec::Vp9,
356            profile: CodecProfile::Vp9Profile0,
357            coded_dimensions: VideoDimensions::new(16, 16, &Limits::default()).unwrap(),
358            output_format: PixelFormat::Rgba8,
359            color_range: ColorRange::Limited,
360            hardware: HardwarePreference::Avoid,
361            configuration: vpcc(&[0, 10, 0x80, 2, 2, 2, 0, 0]),
362        }
363    }
364
365    #[test]
366    fn capability_distinguishes_codec_profile_configuration_and_hardware() {
367        let factory = native_vp9_video_decoder_factory();
368        assert!(factory.capability(&config()).is_supported());
369
370        let mut candidate = config();
371        candidate.configuration = Vec::new();
372        assert!(factory.capability(&candidate).is_supported());
373
374        candidate = config();
375        candidate.codec = Codec::Av1;
376        assert_eq!(
377            factory.capability(&candidate),
378            CodecSupport::UnsupportedCodec
379        );
380
381        candidate = config();
382        candidate.profile = CodecProfile::Vp9Profile2;
383        assert_eq!(
384            factory.capability(&candidate),
385            CodecSupport::UnsupportedProfile
386        );
387
388        // Require and Prefer agree on whether this host has hardware.
389        candidate = config();
390        candidate.hardware = HardwarePreference::Require;
391        let required = factory.capability(&candidate);
392        candidate.hardware = HardwarePreference::Prefer;
393        let preferred = factory.capability(&candidate);
394        if hardware_available(&candidate) {
395            let hardware = CodecSupport::Supported {
396                implementation: CodecImplementation::Hardware,
397            };
398            assert_eq!((required, preferred), (hardware.clone(), hardware));
399        } else {
400            assert_eq!(required, CodecSupport::HardwareUnavailable);
401            assert_eq!(
402                preferred,
403                CodecSupport::Supported {
404                    implementation: CodecImplementation::Software
405                }
406            );
407        }
408
409        candidate = config();
410        candidate.output_format = PixelFormat::Yuv420p8;
411        assert!(matches!(
412            factory.capability(&candidate),
413            CodecSupport::InvalidConfiguration { .. }
414        ));
415
416        // A 10-bit, a 4:4:4 and a truncated configuration.
417        for configuration in [
418            vpcc(&[0, 10, 0xa0, 2, 2, 2, 0, 0]),
419            vpcc(&[1, 10, 0x86, 2, 2, 2, 0, 0]),
420            vec![1, 2, 3],
421        ] {
422            candidate = config();
423            candidate.configuration = configuration;
424            assert!(matches!(
425                factory.capability(&candidate),
426                CodecSupport::InvalidConfiguration { .. }
427            ));
428        }
429    }
430
431    #[test]
432    fn create_rejects_malformed_configuration_and_samples() {
433        let mut candidate = config();
434        candidate.configuration = vec![1, 2, 3];
435        let error = native_vp9_video_decoder_factory()
436            .create(&candidate, &Limits::default())
437            .err()
438            .unwrap();
439        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
440
441        let mut decoder = native_vp9_video_decoder_factory()
442            .create(&config(), &Limits::default())
443            .unwrap();
444        for data in [vec![], vec![0xff, 0xff], vec![0x82, 0x49, 0x83]] {
445            let sample = EncodedVideoSample {
446                presentation_index: crate::FrameIndex(0),
447                random_access: true,
448                data,
449            };
450            let error = decoder
451                .submit(&sample, &CancellationToken::new())
452                .unwrap_err();
453            assert_eq!(error.kind(), ErrorKind::MalformedMedia);
454        }
455    }
456
457    #[test]
458    fn create_enforces_allocation_limit() {
459        let restrictive = Limits {
460            max_allocation_bytes: 0,
461            ..Limits::default()
462        };
463        let error = native_vp9_video_decoder_factory()
464            .create(&config(), &restrictive)
465            .err()
466            .unwrap();
467        assert_eq!(error.kind(), ErrorKind::ResourceLimit);
468    }
469
470    #[test]
471    fn color_spaces_pick_their_matrix() {
472        assert_eq!(matrix_for(0), MatrixCoefficients::Bt601);
473        assert_eq!(matrix_for(1), MatrixCoefficients::Bt601);
474        assert_eq!(matrix_for(2), MatrixCoefficients::Bt709);
475        assert_eq!(matrix_for(3), MatrixCoefficients::Bt601);
476        assert_eq!(matrix_for(5), MatrixCoefficients::Bt2020Ncl);
477    }
478
479    /// Each hardware backend on its own, held to the software decoder.
480    ///
481    /// `crates/zvidlib-vp9-encoder/tests/vp9_hardware.rs` checks whichever
482    /// backend the factory selects, which is NVDEC on a host that has both it
483    /// and Media Foundation; this reaches every backend the host has. For each
484    /// fixture, every frame of one uninterrupted decode and of
485    /// `ExactFrameReader`'s sequential, reverse and alternating seeks must
486    /// match the software decoder's, and so must every reference slot shown
487    /// again by `show_existing_frame`. A backend the host lacks is skipped with
488    /// the reason.
489    #[cfg(any(
490        windows,
491        all(target_os = "linux", target_pointer_width = "64"),
492        target_os = "macos"
493    ))]
494    #[test]
495    fn each_hardware_backend_matches_the_software_decoder_and_seeks_exactly() {
496        use crate::{
497            ExpectedVideoFrame, FrameDigest, FrameIndex, VideoDecoderConformanceVector,
498            verify_video_decoder_conformance,
499        };
500
501        type Create = fn(&VideoDecoderConfig, &Limits) -> Result<Box<dyn VideoDecoder>>;
502
503        struct Backend(Create);
504
505        impl VideoDecoderFactory for Backend {
506            fn capability(&self, _configuration: &VideoDecoderConfig) -> CodecSupport {
507                CodecSupport::Supported {
508                    implementation: CodecImplementation::Hardware,
509                }
510            }
511
512            fn create(
513                &self,
514                configuration: &VideoDecoderConfig,
515                limits: &Limits,
516            ) -> Result<Box<dyn VideoDecoder>> {
517                (self.0)(configuration, limits)
518            }
519        }
520
521        fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
522            use std::task::{Context, Poll, Waker};
523            let mut context = Context::from_waker(Waker::noop());
524            let mut future = Box::pin(future);
525            loop {
526                if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
527                    return value;
528                }
529            }
530        }
531
532        let backends: [(&str, Create); _] = [
533            #[cfg(all(
534                feature = "hardware",
535                any(windows, target_os = "linux"),
536                target_pointer_width = "64"
537            ))]
538            ("NVDEC", zvidlib_hardware::nvdec::create_vp9),
539            #[cfg(all(feature = "hardware", windows))]
540            ("Media Foundation", zvidlib_hardware::windows_mf::create_vp9),
541            #[cfg(all(feature = "hardware", target_os = "macos"))]
542            ("VideoToolbox", create_videotoolbox),
543        ];
544
545        let limits = Limits::default();
546        let mut streams = Vec::new();
547        for (name, file) in [
548            (
549                "VP9 256x144 with hidden frames",
550                &include_bytes!("../tests/fixtures/vp9_bbb_256x144.mp4")[..],
551            ),
552            (
553                "VP9 250x142",
554                &include_bytes!("../tests/fixtures/vp9_bbb_250x142.mp4")[..],
555            ),
556        ] {
557            let source = crate::io::MemorySource::new(file.to_vec());
558            let movie = block_on(crate::Mp4Demuxer::open(&source, Default::default())).unwrap();
559            let track = movie.track(1).unwrap();
560            let configuration = VideoDecoderConfig {
561                codec: Codec::Vp9,
562                profile: CodecProfile::Vp9Profile0,
563                coded_dimensions: track.dimensions.unwrap(),
564                output_format: PixelFormat::Rgba8,
565                color_range: ColorRange::Limited,
566                hardware: HardwarePreference::Avoid,
567                configuration: track.decoder_config.clone(),
568            };
569            let samples = block_on(track.to_encoded_video_samples(&source, &limits)).unwrap();
570            streams.push((name, configuration, samples));
571        }
572        // The first frames of the first fixture, then each reference slot shown
573        // again by a one-byte `show_existing_frame` chunk: frame marker 2,
574        // profile 0, show_existing_frame 1, then the slot.
575        let (_, configuration, samples) = &streams[0];
576        let mut existing = samples[..4].to_vec();
577        for slot in 0..8u8 {
578            existing.push(EncodedVideoSample {
579                presentation_index: FrameIndex(existing.len() as u64),
580                random_access: false,
581                data: vec![0x88 | slot],
582            });
583        }
584        streams.push(("VP9 show_existing_frame", configuration.clone(), existing));
585
586        let cancellation = CancellationToken::new();
587        let software = native_vp9_video_decoder_factory();
588        for (backend, create) in backends {
589            let factory = Backend(create);
590            if let Err(error) = factory.create(&streams[0].1, &limits) {
591                eprintln!("skipping {backend}: hardware VP9 decoding unavailable: {error}");
592                continue;
593            }
594            for (name, configuration, samples) in &streams {
595                let decode = |factory: &dyn VideoDecoderFactory| {
596                    let mut decoder = factory.create(configuration, &limits).unwrap();
597                    let mut digests = Vec::new();
598                    for sample in samples {
599                        let outputs = decoder
600                            .submit(sample, &cancellation)
601                            .unwrap_or_else(|error| panic!("{backend} {name}: {error}"));
602                        assert_eq!(outputs.len(), 1, "{backend} {name}");
603                        assert_eq!(outputs[0].presentation_index, sample.presentation_index);
604                        digests.push(FrameDigest::from_frame(&outputs[0].frame).unwrap());
605                    }
606                    assert!(decoder.drain(&cancellation).unwrap().is_empty());
607                    digests
608                };
609                let expected = decode(&software);
610                assert_eq!(decode(&factory), expected, "{backend} {name}");
611                let vector = VideoDecoderConformanceVector {
612                    name: (*name).into(),
613                    configuration: configuration.clone(),
614                    expected_frames: expected
615                        .iter()
616                        .enumerate()
617                        .map(|(index, &digest)| ExpectedVideoFrame {
618                            presentation_index: FrameIndex(index as u64),
619                            digest,
620                        })
621                        .collect(),
622                    samples: samples.clone(),
623                };
624                verify_video_decoder_conformance(&factory, &vector, limits)
625                    .unwrap_or_else(|error| panic!("{backend} {name}: {error}"));
626            }
627            eprintln!("{backend}: every VP9 frame matches the software decoder");
628        }
629    }
630}