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