zvidlib-vp9-decoder 0.5.11

Pure-Rust VP9 software decoder for zvidlib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! Native VP9 decoding, registered as a [`VideoDecoderFactory`]: a
//! dependency-free software decoder, and the platform's hardware decoder
//! where the host has one.
//!
//! This wraps the crate's VP9 profile 0 and 2 decoder (`crate::vp9_dec`),
//! which decodes 8-bit, 10-bit and 12-bit 4:2:0 streams bit for bit as libvpx
//! does: hidden frames,
//! superframes, `show_existing_frame`, intra-only frames, reference frames
//! of another size, tiles, segmentation, lossless coding and every
//! interpolation filter.
//!
//! A sample is one VP9 chunk as the VP9 ISO-BMFF binding defines it: a frame,
//! or a superframe whose hidden frames precede the one it shows. Each sample
//! must show a frame. Decoded pictures are converted to `Rgba8` with
//! [`convert_to_rgba8`], using the matrix the frame's `color_space` names
//! (BT.601 when it is unknown or one the conversion does not implement), at
//! the size the frame was coded at: a stream that changes resolution emits
//! frames of each size. A 10- or 12-bit picture is rounded to 8 bits before
//! that conversion.
//!
//! Profile 2 is decoded in hardware where a backend decodes its bit depth,
//! which the track's `vpcC` box or WebM `CodecPrivate` must name: NVDEC
//! decodes 10- and 12-bit streams, and Media Foundation and VideoToolbox
//! 10-bit ones. A profile 2 track without a configuration, or whose bit depth
//! no backend on the host decodes, is decoded in software by `Prefer`, and
//! `Require` reports that no hardware backend is available for it.
//!
//! The hardware backends decode the same chunks. A chunk's headers are read
//! before it reaches the platform decoder, so each sample still shows exactly
//! one frame, and the decoded picture is cropped to the size its header names
//! and converted by [`picture_to_rgba`] with the color space and range the
//! header names, exactly as a software picture is.

#[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;
// The containers the tests read their fixtures from.
#[cfg(test)]
#[allow(unused_imports)]
use zvidlib_container::*;

/// Returns the native VP9 profile 0 (8-bit 4:2:0) and profile 2 (10- and
/// 12-bit 4:2:0) decoder backend.
///
/// `Prefer` and `Require` select a hardware decoder where the host has one
/// that decodes the stream's profile and bit depth at the configured size:
/// NVIDIA NVDEC on 64-bit Windows and Linux (8-bit profile 0, and 10- and
/// 12-bit profile 2), then Media Foundation on Windows adapters that expose
/// the D3D11 VP9 profile 0 or 10-bit profile 2 decoder, and VideoToolbox on
/// Macs whose media engine decodes VP9 (profile 0, and 10-bit profile 2).
/// A profile 2 track has hardware only when its configuration names its bit
/// depth, since a hardware session is created for one bit depth.
/// `Prefer` falls back to the dependency-free software
/// decoder when none is available, and `Require` reports
/// [`CodecSupport::HardwareUnavailable`]. `Avoid` always selects software.
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 profiles 0 and 2",
                ));
            }
            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 !matches!(
            configuration.profile,
            CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2
        ) {
            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 {
    // A hardware session decodes one bit depth, which the track must name.
    let Some(_bit_depth) = zvidlib_vp9_syntax::configured_bit_depth(
        _configuration.profile,
        &_configuration.configuration,
    ) else {
        return false;
    };
    // The probes for the backends this target builds, in preference order.
    let backends: &[fn(VideoDimensions, u8) -> bool] = &[
        #[cfg(all(
            feature = "hardware",
            any(windows, target_os = "linux"),
            target_pointer_width = "64"
        ))]
        zvidlib_hardware::nvdec::is_vp9_available,
        #[cfg(all(feature = "hardware", windows))]
        zvidlib_hardware::windows_mf::is_vp9_available,
        #[cfg(all(feature = "hardware", target_os = "macos"))]
        zvidlib_hardware::videotoolbox_vp9::is_vp9_available,
    ];
    backends
        .iter()
        .any(|is_available| is_available(_configuration.coded_dimensions, _bit_depth))
}

/// Creates the first hardware decoder that accepts the configuration, in the
/// order [`hardware_available`] checks them, or says why each refused it.
fn create_hardware(
    _configuration: &VideoDecoderConfig,
    _limits: &Limits,
) -> std::result::Result<Box<dyn VideoDecoder>, Vec<String>> {
    if zvidlib_vp9_syntax::configured_bit_depth(
        _configuration.profile,
        &_configuration.configuration,
    )
    .is_none()
    {
        return Err(vec![
            "hardware VP9 profile 2 decoding needs a configuration naming the bit depth".to_owned(),
        ]);
    }
    #[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)
}

/// VideoToolbox, which shows a hidden frame again by replaying it through the
/// software decoder.
#[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)
}

/// Decodes `history` and then `chunk`, returning the picture `chunk` outputs.
#[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(),
    }
}

/// Validates the track's `vpcC` box (or WebM `CodecPrivate`). Either may be
/// empty or absent from a stream, since the VP9 bitstream describes itself;
/// when present it must describe a 4:2:0 stream of the configured profile:
/// 8-bit for profile 0, 10- or 12-bit for profile 2.
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"));
    }
    if configuration.configuration.is_empty() {
        return Ok(());
    }
    let record = Vp9CodecConfig::parse(&configuration.configuration)
        .map_err(|error| malformed(format!("invalid VP9 configuration: {error}")))?;
    let supported = match configuration.profile {
        CodecProfile::Vp9Profile0 => record.profile == 0 && record.bit_depth == 8,
        _ => record.profile == 2 && matches!(record.bit_depth, 10 | 12),
    };
    if !supported || !record.is_420() {
        return Err(Error::new(
            ErrorKind::Unsupported,
            "native VP9 decoder requires a profile 0 8-bit or profile 2 10- or 12-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 {
            // The caller asked not to see this frame.
            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()?;
        // Every sample shows its frame as it is decoded; nothing is held
        // back for reordering.
        Ok(Vec::new())
    }

    fn reset(&mut self) -> Result<()> {
        self.inner.reset();
        Ok(())
    }

    fn set_output_wanted(&mut self, wanted: bool) {
        // The frame is still decoded and kept as a reference; only the
        // copy out of the reference buffer and the YUV-to-RGBA pass are
        // skipped.
        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)
}

/// The SIMD dispatch sites in this crate, each with the instruction set it
/// resolves to right now. `zvidlib::simd::active_by_site` reports every crate's
/// sites together and documents what each one covers.
#[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
        );

        for profile in [CodecProfile::Vp9Profile1, CodecProfile::Vp9Profile3] {
            candidate = config();
            candidate.profile = profile;
            assert_eq!(
                factory.capability(&candidate),
                CodecSupport::UnsupportedProfile
            );
        }

        // Profile 2 (#706) decodes from a 10- or 12-bit 4:2:0 configuration
        // or none. Hardware (#727) needs the configuration to name the bit
        // depth, and a backend on this host that decodes it; `Prefer` falls
        // back to software, and `Require` agrees with `Prefer`.
        let software = CodecSupport::Supported {
            implementation: CodecImplementation::Software,
        };
        let hardware = CodecSupport::Supported {
            implementation: CodecImplementation::Hardware,
        };
        for (configuration, bit_depth) in [
            (vpcc(&[2, 10, 0xa2, 2, 2, 2, 0, 0]), Some(10)),
            (vpcc(&[2, 10, 0xc2, 2, 2, 2, 0, 0]), Some(12)),
            (Vec::new(), None),
        ] {
            candidate = config();
            candidate.profile = CodecProfile::Vp9Profile2;
            candidate.configuration = configuration;
            // VideoToolbox creates no session below 64x64.
            candidate.coded_dimensions = VideoDimensions::new(160, 90, &Limits::default()).unwrap();
            assert_eq!(
                zvidlib_vp9_syntax::configured_bit_depth(
                    candidate.profile,
                    &candidate.configuration
                ),
                bit_depth
            );
            candidate.hardware = HardwarePreference::Avoid;
            assert_eq!(factory.capability(&candidate), software);
            assert!(factory.create(&candidate, &Limits::default()).is_ok());
            let available = hardware_available(&candidate);
            if bit_depth.is_none() {
                assert!(!available);
            }
            candidate.hardware = HardwarePreference::Prefer;
            let preferred = factory.capability(&candidate);
            assert_eq!(
                preferred,
                if available { &hardware } else { &software }.clone()
            );
            assert!(factory.create(&candidate, &Limits::default()).is_ok());
            candidate.hardware = HardwarePreference::Require;
            if available {
                assert_eq!(factory.capability(&candidate), hardware);
                assert!(factory.create(&candidate, &Limits::default()).is_ok());
            } else {
                assert_eq!(
                    factory.capability(&candidate),
                    CodecSupport::HardwareUnavailable
                );
                let error = factory
                    .create(&candidate, &Limits::default())
                    .err()
                    .unwrap();
                assert_eq!(error.kind(), ErrorKind::Unsupported);
                if bit_depth.is_none() {
                    assert!(error.message().contains("profile 2"), "{error:?}");
                }
            }
        }
        // A profile 2 track configured as 8-bit or 4:4:4 is refused.
        for configuration in [
            vpcc(&[2, 10, 0x82, 2, 2, 2, 0, 0]),
            vpcc(&[2, 10, 0xa6, 2, 2, 2, 0, 0]),
        ] {
            candidate = config();
            candidate.profile = CodecProfile::Vp9Profile2;
            candidate.configuration = configuration;
            assert!(matches!(
                factory.capability(&candidate),
                CodecSupport::InvalidConfiguration { .. }
            ));
        }

        // Require and Prefer agree on whether this host has hardware.
        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 { .. }
        ));

        // A 10-bit, a 4:4:4 and a truncated configuration.
        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);
    }

    /// Each hardware backend on its own, held to the software decoder.
    ///
    /// `crates/zvidlib-vp9-encoder/tests/vp9_hardware.rs` checks whichever
    /// backend the factory selects, which is NVDEC on a host that has both it
    /// and Media Foundation; this reaches every backend the host has. For each
    /// fixture, every frame of one uninterrupted decode and of
    /// `ExactFrameReader`'s sequential, reverse and alternating seeks must
    /// match the software decoder's, and so must every reference slot shown
    /// again by `show_existing_frame`. A backend the host lacks is skipped with
    /// the reason.
    #[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, profile) in [
            (
                "VP9 256x144 with hidden frames",
                &include_bytes!("../tests/fixtures/vp9_bbb_256x144.mp4")[..],
                CodecProfile::Vp9Profile0,
            ),
            (
                "VP9 250x142",
                &include_bytes!("../tests/fixtures/vp9_bbb_250x142.mp4")[..],
                CodecProfile::Vp9Profile0,
            ),
            (
                "VP9 profile 2 10-bit 160x90 with hidden frames",
                &include_bytes!("../tests/fixtures/vp9_bbb_160x90_10bit.mp4")[..],
                CodecProfile::Vp9Profile2,
            ),
        ] {
            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,
                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));
        }
        // The 12-bit fixture is a WebM without `CodecPrivate`, so its track is
        // given the `vpcC` box that names its bit depth.
        let twelve_bit = crate::vp9_dec::tests::webm_frames(include_bytes!(
            "../tests/fixtures/vp9_bbb_160x90_12bit.webm"
        ));
        streams.push((
            "VP9 profile 2 12-bit 160x90",
            VideoDecoderConfig {
                configuration: vpcc(&[2, 10, 0xc2, 2, 2, 2, 0, 0]),
                coded_dimensions: VideoDimensions::new(160, 90, &limits).unwrap(),
                ..streams[2].1.clone()
            },
            twelve_bit
                .iter()
                .enumerate()
                .map(|(index, data)| EncodedVideoSample {
                    presentation_index: FrameIndex(index as u64),
                    random_access: index == 0,
                    data: data.to_vec(),
                })
                .collect(),
        ));
        // The first frames of the first fixture and of the 10-bit one, then
        // each reference slot shown again by a one-byte `show_existing_frame`
        // chunk: frame marker 2, the profile's two bits (low bit first),
        // show_existing_frame 1, then the slot.
        for (name, stream, marker) in [
            ("VP9 show_existing_frame", 0, 0x88),
            ("VP9 profile 2 10-bit show_existing_frame", 2, 0x98),
        ] {
            let (_, configuration, samples) = &streams[stream];
            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![marker | slot],
                });
            }
            streams.push((name, 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 {
                // A backend that does not decode a profile 2 bit depth on this
                // host is skipped for those streams, as the factory skips it.
                if configuration.profile == CodecProfile::Vp9Profile2
                    && let Err(error) = factory.create(configuration, &limits)
                {
                    eprintln!("skipping {backend} {name}: {error}");
                    continue;
                }
                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}"));
            }
            // A session is created for the bit depth the configuration names,
            // and refuses a frame of another one.
            if let Ok(mut decoder) = factory.create(&streams[2].1, &limits) {
                let error = decoder
                    .submit(&streams[0].2[0], &cancellation)
                    .err()
                    .unwrap_or_else(|| panic!("{backend} decoded 8-bit VP9 as 10-bit"));
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{backend}: {error}");
            }
            eprintln!("{backend}: every VP9 frame matches the software decoder");
        }
    }
}