Skip to main content

zvidlib_core/
codec.rs

1use crate::{
2    AudioBuffer, Codec, ColorRange, Error, ErrorKind, FrameIndex, FrameSource, Limits, PixelFormat,
3    Plane, Result, VideoDimensions, VideoFrame,
4};
5use std::borrow::Cow;
6use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::time::Duration;
12
13/// A non-`Send` encoder future that works on native and single-threaded WASM.
14pub type EncoderFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
15
16/// The kind of media carried by an encoded track.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum TrackKind {
19    Video,
20    Audio,
21}
22
23/// Dependency information written to the MP4 sample dependency table.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct SampleDependency {
26    pub is_leading: u8,
27    pub depends_on: u8,
28    pub is_depended_on: u8,
29    pub has_redundancy: u8,
30}
31
32impl SampleDependency {
33    pub const INDEPENDENT: Self = Self {
34        is_leading: 0,
35        depends_on: 2,
36        is_depended_on: 0,
37        has_redundancy: 0,
38    };
39
40    pub const DEPENDENT: Self = Self {
41        is_leading: 0,
42        depends_on: 1,
43        is_depended_on: 0,
44        has_redundancy: 0,
45    };
46
47    #[doc(hidden)]
48    pub fn to_sdtp(self) -> u8 {
49        ((self.is_leading & 3) << 6)
50            | ((self.depends_on & 3) << 4)
51            | ((self.is_depended_on & 3) << 2)
52            | (self.has_redundancy & 3)
53    }
54}
55
56/// One encoded access unit with exact decode and presentation timing.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct EncodedSample {
59    pub data: Vec<u8>,
60    pub dts: i64,
61    pub pts: i64,
62    pub duration: u32,
63    pub is_sync: bool,
64    pub dependency: SampleDependency,
65}
66
67/// Codec and sample-entry information needed to declare an MP4 track.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct EncoderConfig {
70    pub codec: Codec,
71    pub timescale: u32,
72    /// Complete codec configuration box, including its size and fourcc.
73    pub decoder_config: Vec<u8>,
74}
75
76/// Video format accepted by a video encoder.
77#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78pub struct VideoEncoderFormat {
79    pub dimensions: VideoDimensions,
80    pub pixel_format: PixelFormat,
81}
82
83/// Audio format accepted by an audio encoder.
84#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub struct AudioEncoderFormat {
86    pub sample_rate: u32,
87    pub channels: u16,
88}
89
90/// Gapless audio metadata produced when an encoder is drained.
91#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
92pub struct AudioGapless {
93    pub priming: u32,
94    pub padding: u32,
95}
96
97/// Packets and metadata emitted while draining an audio encoder.
98#[derive(Clone, Debug, Default, Eq, PartialEq)]
99pub struct AudioDrain {
100    pub samples: Vec<EncodedSample>,
101    pub gapless: AudioGapless,
102}
103
104/// Backend-neutral video encoder contract.
105pub trait VideoEncoder {
106    fn config(&self) -> &EncoderConfig;
107    fn format(&self) -> VideoEncoderFormat;
108    /// Whether this encoder runs on dedicated hardware or in software.
109    ///
110    /// A factory's [`VideoEncoderFactory::capability`] answers the same
111    /// question before an encoder exists; this is the answer for the encoder
112    /// actually created, which can differ when a backend that probed as
113    /// available fails to start and a `Prefer` factory falls back. The
114    /// default is `Software`, which is what every encoder that does not
115    /// override it is.
116    fn implementation(&self) -> CodecImplementation {
117        CodecImplementation::Software
118    }
119    /// A human-readable name for the backend doing the encoding, such as a
120    /// Media Foundation encoder's friendly name. For logs and diagnostics
121    /// only; it is not stable across platforms, drivers or releases.
122    fn backend_name(&self) -> &str {
123        "zvidlib"
124    }
125    fn encode<'a>(
126        &'a mut self,
127        index: FrameIndex,
128        frame: FrameSource<'a>,
129    ) -> EncoderFuture<'a, Vec<EncodedSample>>;
130    fn finish<'a>(&'a mut self) -> EncoderFuture<'a, Vec<EncodedSample>>;
131}
132
133/// Backend-neutral audio encoder contract.
134///
135/// # Where the audio encoders come from
136///
137/// zvidlib writes no audio codec of its own design. Each encoder behind this
138/// trait is either the platform's or a faithful port of the codec's reference
139/// encoder, so the quality a caller gets is the reference's rather than a
140/// reimplementation's:
141///
142/// * AAC-LC: `native_aac_audio_encoder_factory` delegates to the operating
143///   system's encoder, AudioToolbox on macOS and Media Foundation on Windows,
144///   and reports `HardwareUnavailable` elsewhere; the browser build encodes
145///   through `WebCodecs`. A pure-Rust AAC-LC encoder is a large subsystem in
146///   its own right -- filter bank, psychoacoustic model, quantization and rate
147///   control -- with no open reference implementation to port, and the
148///   platforms already have good ones (issue #174).
149/// * Opus: `native_opus_audio_encoder_factory` runs `opus-pure`, a pure-Rust
150///   port of libopus, on every target; the browser build can also encode
151///   through `WebCodecs`.
152/// * Vorbis: `native_vorbis_audio_encoder_factory` runs zvidlib's own port of
153///   the libvorbis 1.3.7 encoder, whose packets are bit-identical to
154///   libvorbis's for the same input and quality.
155///
156/// The concern behind issue #174 was that a mediocre encoder shipped under
157/// this crate's name is worse for callers than none, because it is harder to
158/// route around. A port of the reference encoder answers that concern where an
159/// original design could not. `crate::MediaOutput` muxes an audio track
160/// given any `AudioEncoder`, so a caller with an encoder of its own still
161/// plugs it in here.
162pub trait AudioEncoder {
163    fn config(&self) -> &EncoderConfig;
164    fn format(&self) -> AudioEncoderFormat;
165    fn encode<'a>(
166        &'a mut self,
167        index: FrameIndex,
168        buffer: AudioBuffer,
169    ) -> EncoderFuture<'a, Vec<EncodedSample>>;
170    fn finish<'a>(&'a mut self) -> EncoderFuture<'a, AudioDrain>;
171}
172
173/// A normalized codec profile that can be compared across backend implementations.
174#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
175#[non_exhaustive]
176pub enum CodecProfile {
177    UncompressedGray8,
178    /// H.264 Baseline, including Constrained Baseline: 8-bit 4:2:0 without
179    /// B-slices or CABAC.
180    H264Baseline,
181    /// H.264 Main: 8-bit 4:2:0 with B-slices and CABAC.
182    H264Main,
183    /// H.264 High: Main plus 8x8 transforms and scaling matrices. zvidlib's
184    /// H.264 decoders take 8-bit 4:2:0 High streams only.
185    H264High,
186    HevcMain,
187    HevcMain10,
188    Av1Main,
189    Av1High,
190    Av1Professional,
191    /// VP8 has a single profile; the bitstream version each frame carries
192    /// selects its reconstruction and loop filters.
193    Vp8,
194    /// VP9 profile 0: 8-bit 4:2:0.
195    Vp9Profile0,
196    /// VP9 profile 1: 8-bit 4:2:2, 4:4:0 or 4:4:4.
197    Vp9Profile1,
198    /// VP9 profile 2: 10- or 12-bit 4:2:0.
199    Vp9Profile2,
200    /// VP9 profile 3: 10- or 12-bit 4:2:2, 4:4:0 or 4:4:4.
201    Vp9Profile3,
202    AacLowComplexity,
203    /// Opus has a single profile.
204    Opus,
205    /// Vorbis I has a single profile.
206    Vorbis,
207}
208
209/// Whether a caller permits or requires a hardware codec implementation.
210#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
211#[non_exhaustive]
212pub enum HardwarePreference {
213    Require,
214    Prefer,
215    Avoid,
216}
217
218/// The implementation class selected by a codec factory.
219#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
220#[non_exhaustive]
221pub enum CodecImplementation {
222    Software,
223    Hardware,
224}
225
226/// The result of querying a factory with a complete normalized configuration.
227#[derive(Clone, Debug, Eq, PartialEq)]
228#[non_exhaustive]
229pub enum CodecSupport {
230    Supported { implementation: CodecImplementation },
231    UnsupportedCodec,
232    UnsupportedProfile,
233    InvalidConfiguration { reason: String },
234    HardwareUnavailable,
235}
236
237impl CodecSupport {
238    pub const fn is_supported(&self) -> bool {
239        matches!(self, Self::Supported { .. })
240    }
241}
242
243/// Backend-neutral video decoder configuration.
244#[derive(Clone, Debug, Eq, PartialEq)]
245pub struct VideoDecoderConfig {
246    pub codec: Codec,
247    pub profile: CodecProfile,
248    pub coded_dimensions: VideoDimensions,
249    pub output_format: PixelFormat,
250    pub color_range: ColorRange,
251    pub hardware: HardwarePreference,
252    /// Container configuration bytes in the codec's standardized format.
253    pub configuration: Vec<u8>,
254}
255
256/// Backend-neutral video encoder configuration.
257#[derive(Clone, Debug, Eq, PartialEq)]
258pub struct VideoEncoderConfig {
259    pub codec: Codec,
260    pub profile: CodecProfile,
261    pub coded_dimensions: VideoDimensions,
262    pub input_format: PixelFormat,
263    pub color_range: ColorRange,
264    pub hardware: HardwarePreference,
265    /// Exact media-clock timescale used for emitted DTS and PTS values.
266    pub timescale: u32,
267    /// Exact duration, in `timescale` ticks, of every submitted frame.
268    pub frame_duration: u32,
269    pub configuration: Vec<u8>,
270}
271
272/// One owned compressed sample in decode order with its presentation identity.
273#[derive(Clone, Debug, Eq, PartialEq)]
274pub struct EncodedVideoSample {
275    pub presentation_index: FrameIndex,
276    pub random_access: bool,
277    pub data: Vec<u8>,
278}
279
280/// Supplies [`ExactFrameReader`] with compressed video samples by decode
281/// index, so a reader does not have to own every sample of a track up front.
282///
283/// An owned `Vec<EncodedVideoSample>` implements this directly and is what
284/// [`ExactFrameReader::new`] wraps, so that constructor and its callers are
285/// unchanged. [`ExactFrameReader::from_provider`] accepts any other
286/// implementation, such as one that reads through a container track's index
287/// and a [`crate::io::ByteSource`] on demand, holding only the index and a
288/// bounded cache of compressed bytes rather than the whole track.
289///
290/// `len`, `is_random_access` and `presentation_index` answer from the index
291/// alone and must not read sample data; only [`Self::read`] may do that, and
292/// only for the one sample it is asked for.
293///
294/// Implementations used from a decode thread must be `Send`, matching
295/// [`VideoDecoder`]'s own requirement.
296pub trait SampleProvider: Send {
297    /// The number of samples, in decode order.
298    fn len(&self) -> usize;
299    fn is_empty(&self) -> bool {
300        self.len() == 0
301    }
302    fn is_random_access(&self, decode_index: usize) -> bool;
303    fn presentation_index(&self, decode_index: usize) -> FrameIndex;
304    /// Returns the compressed bytes of one decode-order sample.
305    fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>>;
306}
307
308impl SampleProvider for Vec<EncodedVideoSample> {
309    fn len(&self) -> usize {
310        self.as_slice().len()
311    }
312
313    fn is_random_access(&self, decode_index: usize) -> bool {
314        self[decode_index].random_access
315    }
316
317    fn presentation_index(&self, decode_index: usize) -> FrameIndex {
318        self[decode_index].presentation_index
319    }
320
321    fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
322        Ok(Cow::Borrowed(&self[decode_index].data))
323    }
324}
325
326/// One normalized decoder output, independent of backend-private image types.
327#[derive(Clone, Debug, Eq, PartialEq)]
328pub struct DecodedVideoFrame {
329    pub presentation_index: FrameIndex,
330    pub frame: VideoFrame,
331}
332
333/// A cheap cloneable cancellation signal shared with a running codec operation.
334#[derive(Clone, Debug, Default)]
335pub struct CancellationToken {
336    canceled: Arc<AtomicBool>,
337}
338
339impl CancellationToken {
340    pub fn new() -> Self {
341        Self::default()
342    }
343
344    pub fn cancel(&self) {
345        self.canceled.store(true, Ordering::Release);
346    }
347
348    pub fn is_canceled(&self) -> bool {
349        self.canceled.load(Ordering::Acquire)
350    }
351
352    #[doc(hidden)]
353    pub fn check(&self) -> Result<()> {
354        if self.is_canceled() {
355            Err(Error::new(ErrorKind::Canceled, "codec operation canceled"))
356        } else {
357            Ok(())
358        }
359    }
360}
361
362/// A stateful video decoder that may retain reference and reorder state.
363///
364/// Requires `Send` so an [`ExactFrameReader`] (and the decoder it owns) can be moved to a
365/// background thread, which native examples rely on to decode without stalling rendering.
366pub trait VideoDecoder: Send {
367    fn submit(
368        &mut self,
369        sample: &EncodedVideoSample,
370        cancellation: &CancellationToken,
371    ) -> Result<Vec<DecodedVideoFrame>>;
372    fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>>;
373    fn reset(&mut self) -> Result<()>;
374
375    /// Whether the caller wants the pictures the next samples decode to, or is only decoding
376    /// them because a later frame references them.
377    ///
378    /// Reaching a frame in the middle of a long group of pictures means decoding every sample
379    /// before it, and on the way there nothing looks at those pictures. What they cost is not
380    /// the decoding: a hardware backend hands back NV12 and every one of these decoders then
381    /// converts a whole picture to RGBA on the CPU and allocates the frame that holds it. On
382    /// the bundled 1080p sample that conversion is 6.6 ms of the 9.6 ms a frame takes through
383    /// VideoToolbox, so a seek that skips it for the frames it passes costs a third of what it
384    /// did.
385    ///
386    /// A decoder must still *decode* a suppressed sample - the frames after it reference the
387    /// picture - and must still account for its presentation identity; what it may skip is
388    /// producing the [`DecodedVideoFrame`], which it reports by returning fewer frames than it
389    /// was given samples.
390    ///
391    /// The default implementation ignores the hint, which is always correct: a decoder that
392    /// keeps producing every frame is a decoder that is merely no faster. [`ExactFrameReader`]
393    /// tracks what it was actually handed rather than what it asked for, so a backend that
394    /// implements this and one that does not answer the same frames.
395    fn set_output_wanted(&mut self, _wanted: bool) {}
396}
397
398/// Discovers and creates video decoders without exposing backend-specific types.
399pub trait VideoDecoderFactory {
400    fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport;
401    fn create(
402        &self,
403        configuration: &VideoDecoderConfig,
404        limits: &Limits,
405    ) -> Result<Box<dyn VideoDecoder>>;
406}
407
408/// Discovers and creates video encoders using the normalized capability model.
409pub trait VideoEncoderFactory {
410    fn capability(&self, configuration: &VideoEncoderConfig) -> CodecSupport;
411    fn create(
412        &self,
413        configuration: &VideoEncoderConfig,
414        limits: &Limits,
415    ) -> Result<Box<dyn VideoEncoder>>;
416}
417
418/// Backend-neutral audio encoder configuration.
419#[derive(Clone, Debug, Eq, PartialEq)]
420pub struct AudioEncoderConfig {
421    pub codec: Codec,
422    pub profile: CodecProfile,
423    pub sample_rate: u32,
424    pub channels: u16,
425    /// Exact media-clock timescale used for emitted DTS and PTS values.
426    pub timescale: u32,
427    pub configuration: Vec<u8>,
428}
429
430/// Discovers and creates audio encoders using the normalized capability model,
431/// the audio counterpart to [`VideoEncoderFactory`].
432///
433/// The native AAC, Opus and Vorbis factories implement it (see
434/// [`AudioEncoder`] for where each encoder comes from), and a caller's own
435/// adapter can too, so a caller that wants discoverable capability reporting
436/// is not left writing the `Result<Box<dyn AudioEncoder>>` construction by
437/// hand.
438pub trait AudioEncoderFactory {
439    fn capability(&self, configuration: &AudioEncoderConfig) -> CodecSupport;
440    fn create(
441        &self,
442        configuration: &AudioEncoderConfig,
443        limits: &Limits,
444    ) -> Result<Box<dyn AudioEncoder>>;
445}
446
447/// Reads an audio encoder's backend-private configuration: `Some(None)` for
448/// an empty one (the backend's default bit rate), `Some(Some(bits_per_second))`
449/// for four big-endian bytes naming a nonzero rate, and `None` for anything
450/// else. Zero is rejected rather than read as "no target", as the HEVC encoder
451/// does. Every native audio encoder takes this form.
452#[doc(hidden)]
453pub fn parse_audio_bit_rate(configuration: &[u8]) -> Option<Option<u32>> {
454    match configuration {
455        [] => Some(None),
456        [a, b, c, d] => match u32::from_be_bytes([*a, *b, *c, *d]) {
457            0 => None,
458            bits_per_second => Some(Some(bits_per_second)),
459        },
460        _ => None,
461    }
462}
463
464/// Observable counters for validating cache and decoder reuse behavior.
465#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
466pub struct DecodeStatistics {
467    pub samples_submitted: u64,
468    /// Of those, the ones submitted only so a later frame could reference them, with the
469    /// decoder told not to produce their pictures.
470    pub samples_skipped: u64,
471    pub cache_hits: u64,
472    pub resets: u64,
473    pub drains: u64,
474}
475
476/// Presentation-indexed exact-frame access over decode-order compressed samples.
477pub struct ExactFrameReader {
478    configuration: VideoDecoderConfig,
479    decoder: Box<dyn VideoDecoder>,
480    samples: Box<dyn SampleProvider>,
481    decode_position_by_presentation: HashMap<FrameIndex, usize>,
482    cache: BTreeMap<FrameIndex, VideoFrame>,
483    lru: VecDeque<FrameIndex>,
484    /// Presentation frames the decoder has emitted since the last reset, which is how far
485    /// continuing the open session is assumed to reach: one of these that has since been
486    /// evicted from the cache is assumed unreachable without a reset. It is only that
487    /// assumption. A decoder that emits one of them again is published again and cached, not
488    /// refused (see [`publish`]).
489    ///
490    /// [`publish`]: Self::publish
491    published_since_reset: HashSet<FrameIndex>,
492    /// Frames whose sample was submitted while the decoder was told nothing wanted its picture,
493    /// so the decoder passed through them without producing one. Reaching one again needs the
494    /// same reset an evicted published frame does.
495    suppressed_since_reset: HashSet<FrameIndex>,
496    /// Frames whose sample has been submitted and whose picture has not come back yet, because a
497    /// reordering decoder holds one until the samples after it arrive. They are the frames a
498    /// decoder may drop the moment output stops being wanted, so turning it off writes them off
499    /// with the rest.
500    in_flight_since_reset: HashSet<FrameIndex>,
501    /// What the decoder was last told, so a walk toggles it once at the target rather than
502    /// on every sample.
503    output_wanted: bool,
504    next_decode_position: Option<usize>,
505    /// The random-access position the open decode session started from. Only frames at or
506    /// after it have been, or can still be, submitted without a reset.
507    session_start: Option<usize>,
508    /// The fast tier [`ExactFrameReader::seek`] answers from, when the caller has attached one.
509    seek_previews: Option<Arc<dyn SeekPreviewSource>>,
510    limits: Limits,
511    statistics: DecodeStatistics,
512}
513
514/// The longest a seek to any position of any track may take.
515///
516/// This is the requirement `ARCHITECTURE.md` section 3.2 states, kept here as a value so the
517/// tests that hold the library to it and the callers that budget against it quote one number.
518pub const SEEK_LATENCY_BUDGET: Duration = Duration::from_millis(50);
519
520/// Already-decoded pictures spread over a track, which a seek may answer from.
521///
522/// This is a trait rather than the concrete index because [`ExactFrameReader`] is portable and
523/// `zvidlib::previews::PreviewIndex` is not - its pass owns a thread, so it is native-only - and a
524/// reader that named the concrete type could not be built for the browser at all, which is the
525/// target that needs the tier most. An implementation must not decode and must not wait on a
526/// decoder: what it returns is a picture it already had, or nothing.
527///
528/// Issue #432 gave the browser its own implementation. What answers a seek on either target is
529/// now the same `zvidlib::previews::PreviewStore`; what differs is only what fills it, a thread in
530/// `zvidlib::previews::PreviewIndex` against an idle callback in `zvidlib::web_previews`.
531pub trait SeekPreviewSource: Send + Sync {
532    /// The kept picture closest to `frame` and the frame it is actually of, or `None` while
533    /// nothing near that position has been decoded.
534    fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)>;
535}
536
537/// What a constant-time [`ExactFrameReader::seek`] could answer with.
538///
539/// A seek is a question about a position on the timeline, and it has to be answered now: the
540/// exact frame at an arbitrary point of a long group of pictures is a decode of every frame
541/// before it, which on a 1080p track is seconds rather than the [`SEEK_LATENCY_BUDGET`]
542/// `ARCHITECTURE.md` section 3.2 allows. So a seek returns the best picture already decoded and
543/// the caller walks to the exact one behind it with [`ExactFrameReader::get`] if it still wants
544/// it.
545#[derive(Clone, Debug, Eq, PartialEq)]
546pub enum Seek {
547    /// The frame asked for, already decoded and cached. Nothing further is needed.
548    Exact(VideoFrame),
549    /// A picture of a different frame, the closest one the seek preview index holds.
550    Preview {
551        picture: VideoFrame,
552        /// The frame `picture` is actually of, which is within one preview stride of the frame
553        /// asked for once the pass has covered that part of the track.
554        frame: FrameIndex,
555    },
556    /// Nothing is decoded yet for anywhere near this position: no cached frame, and either no
557    /// preview index attached or an index whose pass has not produced a picture.
558    Pending,
559}
560
561/// What a caller wants out of a request, which is what decides whether the reader keeps the
562/// frames behind the one it was asked for.
563///
564/// The frames a walk passes are decoded either way - a picture cannot be decoded without its
565/// references - so this only decides which of them are converted to RGBA, which is the part of
566/// a walk that costs.
567#[derive(Clone, Copy, Debug, Eq, PartialEq)]
568enum Request {
569    /// Somewhere to be: keep the frames behind it that the cache can hold, so coming back to
570    /// one of them is free.
571    Destination,
572    /// Somewhere to pass through: keep only the frame asked for, and the reordered frames at or
573    /// after it that the next step needs anyway.
574    Step,
575}
576
577impl Request {
578    /// How far behind the target this request keeps pictures, in presentation frames.
579    fn cache_tail(self, limits: &Limits) -> u64 {
580        match self {
581            Self::Destination => u64::from(limits.max_cached_frames),
582            Self::Step => 0,
583        }
584    }
585}
586
587impl ExactFrameReader {
588    pub fn new(
589        factory: &dyn VideoDecoderFactory,
590        configuration: VideoDecoderConfig,
591        samples: Vec<EncodedVideoSample>,
592        limits: Limits,
593    ) -> Result<Self> {
594        Self::from_provider(factory, configuration, Box::new(samples), limits)
595    }
596
597    /// Builds a reader over any [`SampleProvider`], such as one that reads
598    /// compressed bytes from a container track and a
599    /// [`crate::io::ByteSource`] on demand instead of owning every sample.
600    ///
601    /// Behaves exactly as [`Self::new`], which is this constructor with an
602    /// owned `Vec<EncodedVideoSample>` as the provider.
603    pub fn from_provider(
604        factory: &dyn VideoDecoderFactory,
605        configuration: VideoDecoderConfig,
606        samples: Box<dyn SampleProvider>,
607        limits: Limits,
608    ) -> Result<Self> {
609        if limits.max_cached_frames == 0 || limits.max_decode_samples_per_seek == 0 {
610            return Err(Error::new(
611                ErrorKind::ResourceLimit,
612                "exact-frame limits must permit cached frames and decode work",
613            ));
614        }
615        let capability = factory.capability(&configuration);
616        if !capability.is_supported() {
617            return Err(capability_error(capability));
618        }
619        if samples.is_empty() {
620            return Err(Error::new(
621                ErrorKind::InvalidInput,
622                "an exact-frame reader requires at least one sample",
623            ));
624        }
625        if !samples.is_random_access(0) {
626            return Err(Error::new(
627                ErrorKind::InvalidInput,
628                "the first decode-order sample must be a random-access point",
629            ));
630        }
631        let mut positions = HashMap::with_capacity(samples.len());
632        for position in 0..samples.len() {
633            if positions
634                .insert(samples.presentation_index(position), position)
635                .is_some()
636            {
637                return Err(Error::new(
638                    ErrorKind::InvalidInput,
639                    "presentation frame identities must be unique",
640                ));
641            }
642        }
643        let decoder = factory.create(&configuration, &limits)?;
644        Ok(Self {
645            configuration,
646            decoder,
647            samples,
648            decode_position_by_presentation: positions,
649            cache: BTreeMap::new(),
650            lru: VecDeque::new(),
651            published_since_reset: HashSet::new(),
652            suppressed_since_reset: HashSet::new(),
653            in_flight_since_reset: HashSet::new(),
654            output_wanted: true,
655            next_decode_position: None,
656            session_start: None,
657            seek_previews: None,
658            limits,
659            statistics: DecodeStatistics::default(),
660        })
661    }
662
663    /// Builds the owned, transient [`EncodedVideoSample`] the decoder is
664    /// submitted for one decode-order position, reading its bytes from the
665    /// provider.
666    fn sample_at(&self, position: usize) -> Result<EncodedVideoSample> {
667        Ok(EncodedVideoSample {
668            presentation_index: self.samples.presentation_index(position),
669            random_access: self.samples.is_random_access(position),
670            data: self.samples.read(position)?.into_owned(),
671        })
672    }
673
674    /// Attaches (or, with `None`, detaches) the preview source [`Self::seek`] answers from.
675    ///
676    /// The source is normally a `zvidlib::previews::PreviewIndex` filling itself on a decoder of its
677    /// own, and it is shared rather than owned so a reader can start answering seeks from it
678    /// while its pass is still walking the track.
679    pub fn set_seek_previews(&mut self, previews: Option<Arc<dyn SeekPreviewSource>>) {
680        self.seek_previews = previews;
681    }
682
683    /// Answers "what is at this position of the timeline" without decoding anything.
684    ///
685    /// This is the seek path, and it is bounded by `ARCHITECTURE.md` section 3.2: it takes the
686    /// same time whichever position of whatever track it is asked about, because it only ever
687    /// looks at pictures that are already decoded. It reads the presentation cache first - a
688    /// seek back to somewhere the reader has just been is exact for nothing - and then the
689    /// attached seek preview index, and it returns [`Seek::Pending`] rather than blocking when
690    /// neither holds anything.
691    ///
692    /// Reaching the exact frame is [`Self::get`], which is unbounded by construction: the frame
693    /// depends on every frame back to its random-access point and they all have to be decoded.
694    /// A caller that wants both draws what this returns and walks to the exact frame behind it.
695    pub fn seek(&mut self, presentation_index: FrameIndex) -> Seek {
696        if let Some(frame) = self.cache.get(&presentation_index).cloned() {
697            self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
698            self.touch(presentation_index);
699            return Seek::Exact(frame);
700        }
701        match self
702            .seek_previews
703            .as_ref()
704            .and_then(|previews| previews.nearest_at(presentation_index))
705        {
706            Some((frame, picture)) => Seek::Preview { picture, frame },
707            None => Seek::Pending,
708        }
709    }
710
711    /// Returns exactly the requested presentation frame, and the frames behind it that the
712    /// cache can hold, so a request that comes back for one of those is answered for nothing.
713    ///
714    /// This is the destination of a seek. A walk that is going to keep walking forwards should
715    /// ask for its intermediate frames with [`get_step`] instead, which converts the frame it
716    /// was asked for and nothing else.
717    ///
718    /// [`get_step`]: Self::get_step
719    pub fn get(
720        &mut self,
721        presentation_index: FrameIndex,
722        cancellation: &CancellationToken,
723    ) -> Result<VideoFrame> {
724        self.get_request(presentation_index, Request::Destination, cancellation)
725    }
726
727    /// Returns exactly the requested presentation frame and converts nothing else.
728    ///
729    /// A step is a picture on the way to somewhere, not somewhere: the caller is going to ask
730    /// for a frame further forward next, so the frames behind this one that [`get`] would keep
731    /// are converted for a request that never comes. That tail is bounded per call and so is
732    /// affordable for one seek, but a walk that publishes as it goes pays it once per published
733    /// picture, and once the stride is shorter than the tail the tails overlap and the walk
734    /// converts every picture it passes rather than the few it publishes (issue #402).
735    ///
736    /// Frames at or after the target in presentation order are still kept, exactly as [`get`]
737    /// keeps them: on a stream with B-pictures those are the reordered frames the next request
738    /// asks for, and dropping them would reset the decoder and re-walk the group of pictures.
739    ///
740    /// [`get`]: Self::get
741    pub fn get_step(
742        &mut self,
743        presentation_index: FrameIndex,
744        cancellation: &CancellationToken,
745    ) -> Result<VideoFrame> {
746        self.get_request(presentation_index, Request::Step, cancellation)
747    }
748
749    fn get_request(
750        &mut self,
751        presentation_index: FrameIndex,
752        request: Request,
753        cancellation: &CancellationToken,
754    ) -> Result<VideoFrame> {
755        cancellation.check()?;
756        if let Some(frame) = self.cache.get(&presentation_index).cloned() {
757            self.statistics.cache_hits = self.statistics.cache_hits.saturating_add(1);
758            self.touch(presentation_index);
759            return Ok(frame);
760        }
761        let target_position = *self
762            .decode_position_by_presentation
763            .get(&presentation_index)
764            .ok_or_else(|| {
765                Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
766            })?;
767        let random_access_position = self.nearest_random_access(target_position);
768        // A decoder with output reordering (e.g. hierarchical B-frames) may need to be fed
769        // samples *past* `target_position` before the reordered frame at `target_position` is
770        // actually emitted. So `next_decode_position > target_position` does not by itself mean
771        // the frame is unreachable without a reset: it may simply still be buffered inside the
772        // decoder, pending release as more samples are submitted. The only case that truly
773        // requires a reset is when the frame was already published once and evicted from the
774        // cache, since a decoder is not expected to emit the same presentation frame twice
775        // without an intervening reset. That is an assumption about what continuing the session
776        // can reach, not a rule the decoder is held to: one that does emit the frame again is
777        // published a second time and cached rather than refused (see `publish`).
778        //
779        // A frame the decoder walked past without producing is in the same position as one that
780        // was published and evicted: the decoder will not emit it again, so only a reset can
781        // reach it.
782        //
783        // And a session that started at a later random-access point than the target's never
784        // submitted the target at all, however far it has since walked. On a track whose frames
785        // are all random-access points, a request for frame 2 opens the session at 2, and a
786        // request for frame 0 after it would otherwise walk on from 3 to the end of the track.
787        if !self.session_reaches(presentation_index, random_access_position) {
788            self.decoder.reset()?;
789            self.statistics.resets = self.statistics.resets.saturating_add(1);
790            self.published_since_reset.clear();
791            self.suppressed_since_reset.clear();
792            self.in_flight_since_reset.clear();
793            self.next_decode_position = Some(random_access_position);
794            self.session_start = Some(random_access_position);
795        }
796
797        let mut work = 0_u32;
798        while let Some(position) = self.next_decode_position {
799            cancellation.check()?;
800            if work >= self.limits.max_decode_samples_per_seek {
801                return Err(Error::new(
802                    ErrorKind::ResourceLimit,
803                    "exact-frame request exceeded the configured decode-work limit",
804                ));
805            }
806            if position == self.samples.len() {
807                self.set_output_wanted(true);
808                self.drain_internal(cancellation)?;
809                break;
810            }
811            // The sample is read before the decoder is told anything, so a provider that reports
812            // `WouldBlock` for it leaves the session exactly where it was, and asking again once
813            // the sample is loaded carries on from here (issue #672).
814            let sample = self.sample_at(position)?;
815            // Nothing looks at a picture decoded on the way to the target, and skipping the
816            // color conversion it would otherwise pay is most of what a long walk costs. Two
817            // kinds of frame are kept anyway, both because the request after this one is very
818            // likely to be for them.
819            //
820            // The first is anything at or after the target in *presentation* order. A walk
821            // arrives at its target from behind and carries on forwards, and deciding this by
822            // decode position instead discards exactly the reordered frames a stream with
823            // B-pictures asks for next: on the bundled sample every fourth request would then
824            // reset the decoder and walk the whole group of pictures again.
825            //
826            // The second is the frames immediately behind the target, as many as the cache can
827            // hold, and that one belongs to the request rather than to the reader. Walking here
828            // fills the cache with them as a side effect, and that is what makes stepping
829            // backwards a frame at a time cost nothing after a seek; skipping them would leave
830            // the cache empty behind the target and turn every backward step into another walk
831            // from the random-access point. For a destination they are a bounded charge - the
832            // last `max_cached_frames` conversions of a walk however long - against a saving
833            // that grows with the distance. For a step they are a charge with no saving behind
834            // it at all: the caller is walking forwards and will never ask for them, and paying
835            // the tail once per step is what made a 150 ms preview cadence convert 765 of the
836            // bundled sample's 768 pictures (issue #402).
837            let cache_tail = request.cache_tail(&self.limits);
838            let wanted = position >= target_position
839                || sample.presentation_index.0 >= presentation_index.0.saturating_sub(cache_tail);
840            self.set_output_wanted(wanted);
841            let suppressed = !self.output_wanted;
842            let outputs = self.decoder.submit(&sample, cancellation)?;
843            self.statistics.samples_submitted = self.statistics.samples_submitted.saturating_add(1);
844            if suppressed {
845                self.statistics.samples_skipped = self.statistics.samples_skipped.saturating_add(1);
846                self.suppressed_since_reset
847                    .insert(sample.presentation_index);
848            } else {
849                self.in_flight_since_reset.insert(sample.presentation_index);
850            }
851            self.next_decode_position = Some(position + 1);
852            work += 1;
853            self.publish(outputs)?;
854            if let Some(frame) = self.cache.get(&presentation_index).cloned() {
855                self.touch(presentation_index);
856                return Ok(frame);
857            }
858        }
859        if let Some(frame) = self.cache.get(&presentation_index).cloned() {
860            self.touch(presentation_index);
861            Ok(frame)
862        } else {
863            Err(Error::new(
864                ErrorKind::MalformedMedia,
865                "decoder did not produce the requested presentation frame",
866            ))
867        }
868    }
869
870    /// The decode-order positions whose samples [`Self::get`] of `presentation_index` reads from
871    /// the provider, as far as the index can tell, so a caller can load them before asking.
872    ///
873    /// This is empty for a cached frame. Otherwise it runs from where the walk starts - the open
874    /// session's next position when the walk continues it, or the frame's random-access point
875    /// when it resets - through the last sample of the frame's group of pictures presented no
876    /// later than the frame, since a reordering decoder holds the frame back until those have
877    /// been submitted. A decoder may still want a sample or two past that before it releases the
878    /// frame; a provider reports [`ErrorKind::WouldBlock`] for any it does not have, and the
879    /// request is resumable, so this is a prefetch hint rather than a guarantee.
880    pub fn decode_positions_for(
881        &self,
882        presentation_index: FrameIndex,
883    ) -> Result<std::ops::Range<usize>> {
884        if self.cache.contains_key(&presentation_index) {
885            return Ok(0..0);
886        }
887        let target_position = *self
888            .decode_position_by_presentation
889            .get(&presentation_index)
890            .ok_or_else(|| {
891                Error::new(ErrorKind::InvalidInput, "presentation frame is not indexed")
892            })?;
893        let random_access_position = self.nearest_random_access(target_position);
894        let start = match self.next_decode_position {
895            Some(next) if self.session_reaches(presentation_index, random_access_position) => next,
896            _ => random_access_position,
897        };
898        let len = self.samples.len();
899        let scan_end = target_position
900            .saturating_add(1)
901            .saturating_add(self.limits.max_decode_samples_per_seek as usize)
902            .min(len);
903        let mut end = target_position + 1;
904        for position in target_position + 1..scan_end {
905            let presented = self.samples.presentation_index(position);
906            if presented <= presentation_index {
907                end = position + 1;
908            } else if self.samples.is_random_access(position) {
909                break;
910            }
911        }
912        Ok(start..end.max((start + 1).min(len)))
913    }
914
915    /// Whether continuing the open decode session reaches `presentation_index`, whose walk would
916    /// otherwise start from `random_access_position`.
917    ///
918    /// A decoder with output reordering (e.g. hierarchical B-frames) may need to be fed samples
919    /// *past* the target before the reordered frame at the target is actually emitted, so a
920    /// session that has walked past the target does not by itself need a reset: the frame may
921    /// still be buffered inside the decoder. See [`Self::get_request`] for the cases that do.
922    fn session_reaches(
923        &self,
924        presentation_index: FrameIndex,
925        random_access_position: usize,
926    ) -> bool {
927        self.next_decode_position
928            .is_some_and(|position| position >= random_access_position)
929            && self
930                .session_start
931                .is_some_and(|start| start <= random_access_position)
932            && !self.published_since_reset.contains(&presentation_index)
933            && !self.suppressed_since_reset.contains(&presentation_index)
934    }
935
936    /// Drains delayed output into the bounded presentation cache.
937    pub fn drain(&mut self, cancellation: &CancellationToken) -> Result<usize> {
938        cancellation.check()?;
939        self.set_output_wanted(true);
940        self.drain_internal(cancellation)
941    }
942
943    /// Tells the decoder whether the next samples' pictures are wanted, when that has changed.
944    ///
945    /// Turning output off writes off the frames the decoder is still holding as well as the ones
946    /// it is about to be handed. A reordering decoder releases a picture several samples after
947    /// the one that carried it, so a frame submitted while output was wanted can come out - and
948    /// be dropped - during the suppressed stretch that follows. Not writing those off is a
949    /// decoder that will never produce them and a reader that still believes it can ask, which
950    /// ends in `decoder did not produce the requested presentation frame`. A picture that does
951    /// arrive after all takes itself back off the list in [`publish`].
952    ///
953    /// [`publish`]: Self::publish
954    fn set_output_wanted(&mut self, wanted: bool) {
955        if self.output_wanted == wanted {
956            return;
957        }
958        if !wanted {
959            for frame in self.in_flight_since_reset.drain() {
960                self.suppressed_since_reset.insert(frame);
961            }
962        }
963        self.decoder.set_output_wanted(wanted);
964        self.output_wanted = wanted;
965    }
966
967    /// Clears decoder, reorder, and frame-cache state.
968    pub fn reset(&mut self) -> Result<()> {
969        self.set_output_wanted(true);
970        self.decoder.reset()?;
971        self.statistics.resets = self.statistics.resets.saturating_add(1);
972        self.next_decode_position = None;
973        self.session_start = None;
974        self.cache.clear();
975        self.lru.clear();
976        self.published_since_reset.clear();
977        self.suppressed_since_reset.clear();
978        self.in_flight_since_reset.clear();
979        Ok(())
980    }
981
982    pub const fn statistics(&self) -> DecodeStatistics {
983        self.statistics
984    }
985
986    pub fn cached_frames(&self) -> usize {
987        self.cache.len()
988    }
989
990    /// The random-access point a decode reaching `target_position` starts from.
991    ///
992    /// A random-access point presented *after* the target cannot be it, even when it comes
993    /// first in decode order: the target is then one of its leading pictures, and an open-GOP
994    /// stream's leading pictures (HEVC RASL pictures) reference pictures from before the
995    /// random-access point, so a decode that starts there cannot reconstruct them (issue #506).
996    /// The walk goes back to a random-access point the target is not leading.
997    fn nearest_random_access(&self, target_position: usize) -> usize {
998        let target = self.samples.presentation_index(target_position);
999        (0..=target_position)
1000            .rev()
1001            .find(|&position| {
1002                self.samples.is_random_access(position)
1003                    && self.samples.presentation_index(position) <= target
1004            })
1005            .unwrap_or(0)
1006    }
1007
1008    fn drain_internal(&mut self, cancellation: &CancellationToken) -> Result<usize> {
1009        let outputs = self.decoder.drain(cancellation)?;
1010        let count = outputs.len();
1011        self.statistics.drains = self.statistics.drains.saturating_add(1);
1012        self.next_decode_position = Some(self.samples.len());
1013        self.publish(outputs)?;
1014        Ok(count)
1015    }
1016
1017    fn publish(&mut self, outputs: Vec<DecodedVideoFrame>) -> Result<()> {
1018        for output in outputs {
1019            // A decoder that ignores the output hint, or one that only emits a suppressed
1020            // sample's picture later, hands back a frame this reader had written off. What it
1021            // was handed is what counts, so it is a cached frame again rather than a reset.
1022            self.suppressed_since_reset
1023                .remove(&output.presentation_index);
1024            self.in_flight_since_reset
1025                .remove(&output.presentation_index);
1026            // A repeat of a frame already published since the last reset is not an error, and
1027            // was one until issue #415. Nothing here depends on a decoder emitting each
1028            // presentation frame at most once per session: `published_since_reset` only decides
1029            // whether a re-request can continue the open session or has to reset, and a decoder
1030            // that hands the frame back anyway makes that answer conservative rather than wrong.
1031            // Refusing it rejected the whole stream as `MalformedMedia` over a backend's
1032            // behavior, and rejected it for a picture the reader was about to cache and could
1033            // have answered the very request from. The `WebCodecs` backend already re-caches
1034            // such a frame, so this is also what makes the two backends agree.
1035            self.published_since_reset.insert(output.presentation_index);
1036            if !self
1037                .decode_position_by_presentation
1038                .contains_key(&output.presentation_index)
1039            {
1040                return Err(Error::new(
1041                    ErrorKind::MalformedMedia,
1042                    "decoder produced an unindexed presentation frame",
1043                ));
1044            }
1045            if output.frame.dimensions != self.configuration.coded_dimensions
1046                || output.frame.pixel_format != self.configuration.output_format
1047                || output.frame.color_range != self.configuration.color_range
1048            {
1049                return Err(Error::new(
1050                    ErrorKind::MalformedMedia,
1051                    "decoder output does not match its normalized configuration",
1052                ));
1053            }
1054            self.insert_cache(output.presentation_index, output.frame);
1055        }
1056        Ok(())
1057    }
1058
1059    fn insert_cache(&mut self, index: FrameIndex, frame: VideoFrame) {
1060        self.cache.insert(index, frame);
1061        self.touch(index);
1062        while self.cache.len() > self.limits.max_cached_frames as usize {
1063            if let Some(evicted) = self.lru.pop_front() {
1064                self.cache.remove(&evicted);
1065            }
1066        }
1067    }
1068
1069    fn touch(&mut self, index: FrameIndex) {
1070        self.lru.retain(|candidate| *candidate != index);
1071        self.lru.push_back(index);
1072    }
1073}
1074
1075fn capability_error(capability: CodecSupport) -> Error {
1076    let (kind, message) = match capability {
1077        CodecSupport::UnsupportedCodec => (
1078            ErrorKind::Unsupported,
1079            "decoder does not support the requested codec".into(),
1080        ),
1081        CodecSupport::UnsupportedProfile => (
1082            ErrorKind::Unsupported,
1083            "decoder does not support the requested profile".into(),
1084        ),
1085        CodecSupport::InvalidConfiguration { reason } => (ErrorKind::InvalidInput, reason),
1086        CodecSupport::HardwareUnavailable => (
1087            ErrorKind::Unsupported,
1088            "requested hardware decoder is unavailable".into(),
1089        ),
1090        CodecSupport::Supported { .. } => (
1091            ErrorKind::Internal,
1092            "decoder capability changed unexpectedly".into(),
1093        ),
1094    };
1095    Error::new(kind, message)
1096}
1097
1098/// Returns the portable, software-only uncompressed Gray8 decoder backend.
1099///
1100/// Each packet contains one tightly packed Gray8 image. The concrete backend
1101/// remains private while this factory provides an end-to-end reference path.
1102pub fn uncompressed_video_decoder_factory() -> impl VideoDecoderFactory {
1103    UncompressedVideoDecoderFactory
1104}
1105
1106struct UncompressedVideoDecoderFactory;
1107
1108impl VideoDecoderFactory for UncompressedVideoDecoderFactory {
1109    fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
1110        if configuration.codec != Codec::UncompressedVideo {
1111            return CodecSupport::UnsupportedCodec;
1112        }
1113        if configuration.profile != CodecProfile::UncompressedGray8 {
1114            return CodecSupport::UnsupportedProfile;
1115        }
1116        if configuration.output_format != PixelFormat::Gray8
1117            || !configuration.configuration.is_empty()
1118        {
1119            return CodecSupport::InvalidConfiguration {
1120                reason: "uncompressed Gray8 requires Gray8 output and no configuration bytes"
1121                    .into(),
1122            };
1123        }
1124        if configuration.hardware == HardwarePreference::Require {
1125            return CodecSupport::HardwareUnavailable;
1126        }
1127        CodecSupport::Supported {
1128            implementation: CodecImplementation::Software,
1129        }
1130    }
1131
1132    fn create(
1133        &self,
1134        configuration: &VideoDecoderConfig,
1135        limits: &Limits,
1136    ) -> Result<Box<dyn VideoDecoder>> {
1137        let capability = self.capability(configuration);
1138        if !capability.is_supported() {
1139            return Err(capability_error(capability));
1140        }
1141        if configuration.coded_dimensions.width > limits.max_width
1142            || configuration.coded_dimensions.height > limits.max_height
1143        {
1144            return Err(Error::new(
1145                ErrorKind::ResourceLimit,
1146                "decoded dimensions exceed the configured limits",
1147            ));
1148        }
1149        let required = u64::from(configuration.coded_dimensions.width)
1150            .checked_mul(u64::from(configuration.coded_dimensions.height))
1151            .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1152        if required > limits.max_allocation_bytes {
1153            return Err(Error::new(
1154                ErrorKind::ResourceLimit,
1155                "decoded frame exceeds the configured allocation limit",
1156            ));
1157        }
1158        Ok(Box::new(UncompressedVideoDecoder {
1159            configuration: configuration.clone(),
1160            limits: *limits,
1161        }))
1162    }
1163}
1164
1165struct UncompressedVideoDecoder {
1166    configuration: VideoDecoderConfig,
1167    limits: Limits,
1168}
1169
1170impl VideoDecoder for UncompressedVideoDecoder {
1171    fn submit(
1172        &mut self,
1173        sample: &EncodedVideoSample,
1174        cancellation: &CancellationToken,
1175    ) -> Result<Vec<DecodedVideoFrame>> {
1176        cancellation.check()?;
1177        let width = usize::try_from(self.configuration.coded_dimensions.width)
1178            .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded width is too large"))?;
1179        let height = usize::try_from(self.configuration.coded_dimensions.height)
1180            .map_err(|_| Error::new(ErrorKind::ResourceLimit, "decoded height is too large"))?;
1181        let length = width
1182            .checked_mul(height)
1183            .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "decoded frame size overflow"))?;
1184        if sample.data.len() != length {
1185            return Err(Error::new(
1186                ErrorKind::MalformedMedia,
1187                "uncompressed Gray8 packet size does not match coded dimensions",
1188            ));
1189        }
1190        let frame = VideoFrame::new(
1191            self.configuration.coded_dimensions,
1192            PixelFormat::Gray8,
1193            self.configuration.color_range,
1194            vec![Plane {
1195                data: sample.data.clone(),
1196                stride: width,
1197            }],
1198            &self.limits,
1199        )?;
1200        Ok(vec![DecodedVideoFrame {
1201            presentation_index: sample.presentation_index,
1202            frame,
1203        }])
1204    }
1205
1206    fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1207        cancellation.check()?;
1208        Ok(Vec::new())
1209    }
1210
1211    fn reset(&mut self) -> Result<()> {
1212        Ok(())
1213    }
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218    use super::*;
1219    use std::sync::Mutex;
1220
1221    fn config() -> VideoDecoderConfig {
1222        VideoDecoderConfig {
1223            codec: Codec::UncompressedVideo,
1224            profile: CodecProfile::UncompressedGray8,
1225            coded_dimensions: VideoDimensions::new(1, 1, &Limits::default()).unwrap(),
1226            output_format: PixelFormat::Gray8,
1227            color_range: ColorRange::Full,
1228            hardware: HardwarePreference::Avoid,
1229            configuration: Vec::new(),
1230        }
1231    }
1232
1233    fn sample(index: u64, value: u8, random_access: bool) -> EncodedVideoSample {
1234        EncodedVideoSample {
1235            presentation_index: FrameIndex(index),
1236            random_access,
1237            data: vec![value],
1238        }
1239    }
1240
1241    fn value(frame: &VideoFrame) -> u8 {
1242        frame.planes[0].data[0]
1243    }
1244
1245    /// Samples that answer only once the test has marked them loaded, and report
1246    /// [`ErrorKind::WouldBlock`] until then, the way a provider over a network source does.
1247    struct LoadOnDemand {
1248        samples: Vec<EncodedVideoSample>,
1249        loaded: Arc<Mutex<HashSet<usize>>>,
1250    }
1251
1252    impl SampleProvider for LoadOnDemand {
1253        fn len(&self) -> usize {
1254            self.samples.len()
1255        }
1256
1257        fn is_random_access(&self, decode_index: usize) -> bool {
1258            self.samples[decode_index].random_access
1259        }
1260
1261        fn presentation_index(&self, decode_index: usize) -> FrameIndex {
1262            self.samples[decode_index].presentation_index
1263        }
1264
1265        fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
1266            if self.loaded.lock().unwrap().contains(&decode_index) {
1267                Ok(Cow::Borrowed(&self.samples[decode_index].data))
1268            } else {
1269                Err(Error::new(ErrorKind::WouldBlock, "not loaded yet"))
1270            }
1271        }
1272    }
1273
1274    /// Issue #672: a request whose provider has not loaded a sample yet reports `WouldBlock`
1275    /// rather than failing or blocking, and asking again once it is loaded carries the same walk
1276    /// on from that sample instead of starting over from the random-access point.
1277    #[test]
1278    fn a_request_waiting_on_an_unloaded_sample_resumes_where_it_stopped() {
1279        let loaded = Arc::new(Mutex::new(HashSet::new()));
1280        let samples = (0..12)
1281            .map(|index| sample(index, index as u8, index % 4 == 0))
1282            .collect();
1283        let mut reader = ExactFrameReader::from_provider(
1284            &uncompressed_video_decoder_factory(),
1285            config(),
1286            Box::new(LoadOnDemand {
1287                samples,
1288                loaded: loaded.clone(),
1289            }),
1290            Limits::default(),
1291        )
1292        .unwrap();
1293        let cancellation = CancellationToken::new();
1294
1295        assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 4..7);
1296        let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1297        assert_eq!(error.kind(), ErrorKind::WouldBlock);
1298        assert_eq!(reader.statistics().samples_submitted, 0);
1299
1300        loaded.lock().unwrap().extend([4, 5]);
1301        let error = reader.get(FrameIndex(6), &cancellation).unwrap_err();
1302        assert_eq!(error.kind(), ErrorKind::WouldBlock);
1303        assert_eq!(reader.statistics().samples_submitted, 2);
1304        // The walk continues, so only what is left of it is still needed.
1305        assert_eq!(reader.decode_positions_for(FrameIndex(6)).unwrap(), 6..7);
1306
1307        loaded.lock().unwrap().insert(6);
1308        assert_eq!(value(&reader.get(FrameIndex(6), &cancellation).unwrap()), 6);
1309        assert_eq!(reader.statistics().samples_submitted, 3);
1310        assert_eq!(reader.statistics().resets, 1);
1311
1312        // A cached frame needs nothing; the next one needs only its own sample; a frame in
1313        // another group needs the run from its random-access point.
1314        assert!(
1315            reader
1316                .decode_positions_for(FrameIndex(6))
1317                .unwrap()
1318                .is_empty()
1319        );
1320        assert_eq!(reader.decode_positions_for(FrameIndex(7)).unwrap(), 7..8);
1321        assert_eq!(reader.decode_positions_for(FrameIndex(10)).unwrap(), 8..11);
1322        assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..2);
1323    }
1324
1325    /// With reordering, a frame's group can present it after samples that come later in decode
1326    /// order, and those have to be submitted before a reordering decoder releases it.
1327    #[test]
1328    fn decode_positions_for_a_reordered_frame_reach_the_samples_presented_before_it() {
1329        // Decode order I0 P3 B1 B2 I4: frame 1 needs P3 (decode position 1) and itself.
1330        let samples = vec![
1331            sample(0, 0, true),
1332            sample(3, 3, false),
1333            sample(1, 1, false),
1334            sample(2, 2, false),
1335            sample(4, 4, true),
1336        ];
1337        let reader = ExactFrameReader::new(
1338            &uncompressed_video_decoder_factory(),
1339            config(),
1340            samples,
1341            Limits::default(),
1342        )
1343        .unwrap();
1344        assert_eq!(reader.decode_positions_for(FrameIndex(1)).unwrap(), 0..3);
1345        assert_eq!(reader.decode_positions_for(FrameIndex(2)).unwrap(), 0..4);
1346        assert_eq!(reader.decode_positions_for(FrameIndex(3)).unwrap(), 0..4);
1347        assert_eq!(reader.decode_positions_for(FrameIndex(4)).unwrap(), 4..5);
1348    }
1349
1350    /// A reader over a single-group track: one random-access point at frame zero, so reaching
1351    /// any frame exactly means decoding every frame before it. This is the shape the bundled
1352    /// sample has and the shape the seek budget is hard for.
1353    fn single_group_reader(frames: u64) -> ExactFrameReader {
1354        let samples = (0..frames)
1355            .map(|index| sample(index, (index % 251) as u8, index == 0))
1356            .collect();
1357        ExactFrameReader::new(
1358            &uncompressed_video_decoder_factory(),
1359            config(),
1360            samples,
1361            Limits::default(),
1362        )
1363        .unwrap()
1364    }
1365
1366    /// A preview source holding one picture every `stride` frames, standing in for the pass a
1367    /// `previews::PreviewIndex` runs. The reader's contract is that a seek reads pictures and
1368    /// never decodes, and asserting that does not need a decoder behind the source.
1369    struct StridedPreviews {
1370        stride: u64,
1371        frames: u64,
1372    }
1373
1374    impl SeekPreviewSource for StridedPreviews {
1375        fn nearest_at(&self, frame: FrameIndex) -> Option<(FrameIndex, VideoFrame)> {
1376            if self.frames == 0 {
1377                return None;
1378            }
1379            let at = (frame.0 / self.stride * self.stride).min(self.frames - 1);
1380            let picture = VideoFrame::new(
1381                config().coded_dimensions,
1382                PixelFormat::Gray8,
1383                ColorRange::Full,
1384                vec![Plane {
1385                    data: vec![(at % 251) as u8],
1386                    stride: 1,
1387                }],
1388                &Limits::default(),
1389            )
1390            .ok()?;
1391            Some((FrameIndex(at), picture))
1392        }
1393    }
1394
1395    /// A seek with nothing decoded anywhere near it says so rather than deciding to decode: the
1396    /// caller falls through to its own exact request instead of the seek path silently becoming
1397    /// the walk it is bounded against.
1398    #[test]
1399    fn a_seek_with_nothing_decoded_is_pending_and_submits_no_samples() {
1400        let mut reader = single_group_reader(512);
1401        assert_eq!(reader.seek(FrameIndex(511)), Seek::Pending);
1402        assert_eq!(reader.statistics().samples_submitted, 0);
1403        assert_eq!(reader.statistics().resets, 0);
1404    }
1405
1406    /// A seek back to somewhere the reader has just been is the frame itself, from the cache.
1407    #[test]
1408    fn a_seek_into_the_cache_answers_exactly() {
1409        let mut reader = single_group_reader(64);
1410        let cancellation = CancellationToken::new();
1411        reader.get(FrameIndex(40), &cancellation).unwrap();
1412        let submitted = reader.statistics().samples_submitted;
1413        let Seek::Exact(frame) = reader.seek(FrameIndex(40)) else {
1414            panic!("a cached frame seeks exactly");
1415        };
1416        assert_eq!(value(&frame), 40);
1417        assert_eq!(
1418            reader.statistics().samples_submitted,
1419            submitted,
1420            "an exact seek decodes nothing"
1421        );
1422    }
1423
1424    /// The requirement in `ARCHITECTURE.md` section 3.2: a seek to any position of a track that
1425    /// is one group of pictures answers from an already-decoded picture and decodes nothing, so
1426    /// what it costs does not grow with how far along the track the position is.
1427    #[test]
1428    fn a_seek_anywhere_on_a_single_group_track_decodes_nothing() {
1429        let mut reader = single_group_reader(512);
1430        reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1431            stride: 12,
1432            frames: 512,
1433        })));
1434        for target in [0_u64, 1, 255, 400, 511] {
1435            match reader.seek(FrameIndex(target)) {
1436                Seek::Preview { frame, .. } => assert!(
1437                    frame.0.abs_diff(target) < 12,
1438                    "frame {target} answered by {frame:?}, further than one stride away"
1439                ),
1440                Seek::Exact(_) => {}
1441                Seek::Pending => panic!("frame {target} had no answer"),
1442            }
1443        }
1444        assert_eq!(
1445            reader.statistics().samples_submitted,
1446            0,
1447            "seeking is not decoding"
1448        );
1449        assert_eq!(reader.statistics().resets, 0);
1450    }
1451
1452    /// The 50 ms half of the same requirement, held on every run rather than only in the
1453    /// host-specific measurement over the bundled sample: a hundred positions of a single-group
1454    /// track, the far end no slower than the near one.
1455    #[test]
1456    fn a_seek_to_any_position_answers_inside_the_latency_budget() {
1457        let frames = 768;
1458        let mut reader = single_group_reader(frames);
1459        reader.set_seek_previews(Some(Arc::new(StridedPreviews { stride: 12, frames })));
1460        let mut worst = Duration::ZERO;
1461        for step in 0..=100_u64 {
1462            let target = FrameIndex(step * (frames - 1) / 100);
1463            let started = std::time::Instant::now();
1464            let answer = reader.seek(target);
1465            worst = worst.max(started.elapsed());
1466            assert_ne!(answer, Seek::Pending, "frame {} had no answer", target.0);
1467        }
1468        assert!(
1469            worst < SEEK_LATENCY_BUDGET,
1470            "the worst seek took {worst:?}, over the {SEEK_LATENCY_BUDGET:?} budget"
1471        );
1472    }
1473
1474    /// Detaching the source puts the reader back to answering out of its own cache alone, so a
1475    /// caller that drops a preview index does not keep serving its pictures.
1476    #[test]
1477    fn detaching_the_preview_source_leaves_only_the_cache() {
1478        let mut reader = single_group_reader(64);
1479        reader.set_seek_previews(Some(Arc::new(StridedPreviews {
1480            stride: 12,
1481            frames: 64,
1482        })));
1483        assert!(matches!(reader.seek(FrameIndex(63)), Seek::Preview { .. }));
1484        reader.set_seek_previews(None);
1485        assert_eq!(reader.seek(FrameIndex(63)), Seek::Pending);
1486    }
1487
1488    /// Issue #506: frame 3 follows the random-access point at frame 4 in decode order but is
1489    /// presented before it, the shape of an open-GOP stream's leading pictures. A decoder that
1490    /// starts at frame 4 cannot reconstruct it, so the reader starts from frame 0 instead. Frame
1491    /// 5 is not leading, so it is still decoded from frame 4.
1492    #[test]
1493    fn a_leading_picture_is_decoded_from_the_random_access_point_before_it() {
1494        let samples = vec![
1495            sample(0, 10, true),
1496            sample(1, 11, false),
1497            sample(2, 12, false),
1498            sample(4, 14, true),
1499            sample(3, 13, false),
1500            sample(5, 15, false),
1501        ];
1502        let mut reader = ExactFrameReader::new(
1503            &uncompressed_video_decoder_factory(),
1504            config(),
1505            samples.clone(),
1506            Limits::default(),
1507        )
1508        .unwrap();
1509        let cancellation = CancellationToken::new();
1510        assert_eq!(
1511            value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1512            13
1513        );
1514        assert_eq!(reader.statistics().samples_submitted, 5);
1515
1516        let mut reader = ExactFrameReader::new(
1517            &uncompressed_video_decoder_factory(),
1518            config(),
1519            samples,
1520            Limits::default(),
1521        )
1522        .unwrap();
1523        assert_eq!(
1524            value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1525            15
1526        );
1527        assert_eq!(reader.statistics().samples_submitted, 3);
1528    }
1529
1530    #[test]
1531    fn capability_distinguishes_codec_profile_configuration_and_hardware() {
1532        let factory = uncompressed_video_decoder_factory();
1533        assert!(factory.capability(&config()).is_supported());
1534        let mut candidate = config();
1535        candidate.codec = Codec::Av1;
1536        assert_eq!(
1537            factory.capability(&candidate),
1538            CodecSupport::UnsupportedCodec
1539        );
1540        candidate = config();
1541        candidate.profile = CodecProfile::Av1Main;
1542        assert_eq!(
1543            factory.capability(&candidate),
1544            CodecSupport::UnsupportedProfile
1545        );
1546        candidate = config();
1547        candidate.output_format = PixelFormat::Rgba8;
1548        assert!(matches!(
1549            factory.capability(&candidate),
1550            CodecSupport::InvalidConfiguration { .. }
1551        ));
1552        candidate = config();
1553        candidate.hardware = HardwarePreference::Require;
1554        assert_eq!(
1555            factory.capability(&candidate),
1556            CodecSupport::HardwareUnavailable
1557        );
1558
1559        candidate = config();
1560        candidate.output_format = PixelFormat::Rgba8;
1561        assert_eq!(
1562            factory
1563                .create(&candidate, &Limits::default())
1564                .err()
1565                .unwrap()
1566                .kind(),
1567            ErrorKind::InvalidInput
1568        );
1569
1570        let restrictive = Limits {
1571            max_width: 0,
1572            ..Limits::default()
1573        };
1574        assert_eq!(
1575            factory
1576                .create(&config(), &restrictive)
1577                .err()
1578                .unwrap()
1579                .kind(),
1580            ErrorKind::ResourceLimit
1581        );
1582    }
1583
1584    /// Issue #504: every frame of an all-intra track is a random-access point, so a request for
1585    /// frame 2 opens its decode session at frame 2. Frame 0 was never submitted in that session,
1586    /// so reaching it needs a reset rather than a walk onwards from frame 3.
1587    #[test]
1588    fn a_request_before_the_open_session_start_resets_the_decoder() {
1589        let samples = (0..4)
1590            .map(|index| sample(index, index as u8 + 10, true))
1591            .collect();
1592        let mut reader = ExactFrameReader::new(
1593            &uncompressed_video_decoder_factory(),
1594            config(),
1595            samples,
1596            Limits {
1597                max_cached_frames: 1,
1598                ..Limits::default()
1599            },
1600        )
1601        .unwrap();
1602        let cancellation = CancellationToken::new();
1603        assert_eq!(
1604            value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1605            12
1606        );
1607        assert_eq!(
1608            value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1609            10
1610        );
1611        assert_eq!(reader.statistics().resets, 2);
1612    }
1613
1614    #[test]
1615    fn conformance_vector_reorders_exact_frames_and_reuses_bounded_state() {
1616        let samples = vec![
1617            sample(0, 10, true),
1618            sample(3, 40, false),
1619            sample(1, 20, false),
1620            sample(2, 30, false),
1621            sample(4, 50, true),
1622            sample(6, 70, false),
1623            sample(5, 60, false),
1624        ];
1625        let factory = uncompressed_video_decoder_factory();
1626        let mut reader = ExactFrameReader::new(
1627            &factory,
1628            config(),
1629            samples,
1630            Limits {
1631                max_cached_frames: 3,
1632                ..Limits::default()
1633            },
1634        )
1635        .unwrap();
1636        let cancellation = CancellationToken::new();
1637        assert_eq!(
1638            value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
1639            20
1640        );
1641        let first = reader.statistics();
1642        assert_eq!(
1643            value(&reader.get(FrameIndex(2), &cancellation).unwrap()),
1644            30
1645        );
1646        assert_eq!(reader.statistics().resets, first.resets);
1647        assert_eq!(
1648            value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1649            40
1650        );
1651        assert!(reader.statistics().cache_hits > 0);
1652        assert_eq!(
1653            value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1654            60
1655        );
1656        assert_eq!(
1657            value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
1658            10
1659        );
1660        assert!(reader.statistics().resets > first.resets);
1661        assert!(reader.cached_frames() <= 3);
1662    }
1663
1664    /// Records what each sample was asked to produce, so a test can see the hint the reader
1665    /// actually gave rather than only its effect.
1666    struct HintFactory {
1667        wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1668    }
1669
1670    struct HintDecoder {
1671        configuration: VideoDecoderConfig,
1672        limits: Limits,
1673        wanted: Arc<Mutex<Vec<(u64, bool)>>>,
1674        output_wanted: bool,
1675    }
1676
1677    impl VideoDecoderFactory for HintFactory {
1678        fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1679            CodecSupport::Supported {
1680                implementation: CodecImplementation::Software,
1681            }
1682        }
1683
1684        fn create(
1685            &self,
1686            configuration: &VideoDecoderConfig,
1687            limits: &Limits,
1688        ) -> Result<Box<dyn VideoDecoder>> {
1689            Ok(Box::new(HintDecoder {
1690                configuration: configuration.clone(),
1691                limits: *limits,
1692                wanted: Arc::clone(&self.wanted),
1693                output_wanted: true,
1694            }))
1695        }
1696    }
1697
1698    impl VideoDecoder for HintDecoder {
1699        fn submit(
1700            &mut self,
1701            sample: &EncodedVideoSample,
1702            cancellation: &CancellationToken,
1703        ) -> Result<Vec<DecodedVideoFrame>> {
1704            cancellation.check()?;
1705            self.wanted
1706                .lock()
1707                .expect("hint log poisoned")
1708                .push((sample.presentation_index.0, self.output_wanted));
1709            if !self.output_wanted {
1710                return Ok(Vec::new());
1711            }
1712            Ok(vec![DecodedVideoFrame {
1713                presentation_index: sample.presentation_index,
1714                frame: VideoFrame::new(
1715                    self.configuration.coded_dimensions,
1716                    PixelFormat::Gray8,
1717                    ColorRange::Full,
1718                    vec![Plane {
1719                        data: sample.data.clone(),
1720                        stride: 1,
1721                    }],
1722                    &self.limits,
1723                )?,
1724            }])
1725        }
1726
1727        fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1728            Ok(Vec::new())
1729        }
1730
1731        fn reset(&mut self) -> Result<()> {
1732            Ok(())
1733        }
1734
1735        fn set_output_wanted(&mut self, wanted: bool) {
1736            self.output_wanted = wanted;
1737        }
1738    }
1739
1740    /// A decoder that hands back the previous sample's picture again alongside the current
1741    /// one, as a backend that does not deduplicate its output across a session does. Both
1742    /// pictures are genuine and correctly identified; the repeat is only a frame the reader has
1743    /// already seen since its last reset.
1744    struct ReplayFactory;
1745
1746    struct ReplayDecoder {
1747        configuration: VideoDecoderConfig,
1748        limits: Limits,
1749        previous: Option<(FrameIndex, u8)>,
1750    }
1751
1752    impl ReplayDecoder {
1753        fn produce(&self, presentation_index: FrameIndex, value: u8) -> Result<DecodedVideoFrame> {
1754            Ok(DecodedVideoFrame {
1755                presentation_index,
1756                frame: VideoFrame::new(
1757                    self.configuration.coded_dimensions,
1758                    PixelFormat::Gray8,
1759                    ColorRange::Full,
1760                    vec![Plane {
1761                        data: vec![value],
1762                        stride: 1,
1763                    }],
1764                    &self.limits,
1765                )?,
1766            })
1767        }
1768    }
1769
1770    impl VideoDecoderFactory for ReplayFactory {
1771        fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
1772            CodecSupport::Supported {
1773                implementation: CodecImplementation::Software,
1774            }
1775        }
1776
1777        fn create(
1778            &self,
1779            configuration: &VideoDecoderConfig,
1780            limits: &Limits,
1781        ) -> Result<Box<dyn VideoDecoder>> {
1782            Ok(Box::new(ReplayDecoder {
1783                configuration: configuration.clone(),
1784                limits: *limits,
1785                previous: None,
1786            }))
1787        }
1788    }
1789
1790    impl VideoDecoder for ReplayDecoder {
1791        fn submit(
1792            &mut self,
1793            sample: &EncodedVideoSample,
1794            cancellation: &CancellationToken,
1795        ) -> Result<Vec<DecodedVideoFrame>> {
1796            cancellation.check()?;
1797            let value = sample.data[0];
1798            let mut outputs = Vec::new();
1799            if let Some((index, previous)) = self.previous {
1800                outputs.push(self.produce(index, previous)?);
1801            }
1802            outputs.push(self.produce(sample.presentation_index, value)?);
1803            self.previous = Some((sample.presentation_index, value));
1804            Ok(outputs)
1805        }
1806
1807        fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
1808            Ok(Vec::new())
1809        }
1810
1811        fn reset(&mut self) -> Result<()> {
1812            self.previous = None;
1813            Ok(())
1814        }
1815    }
1816
1817    /// Issue #415: publishing a presentation frame twice within one decode session used to fail
1818    /// the whole request with `MalformedMedia`, which held the backend to a rule the reader does
1819    /// not depend on and threw away a picture it was about to cache.
1820    #[test]
1821    fn a_frame_the_decoder_emits_twice_is_cached_again_rather_than_refused() {
1822        let mut reader = ExactFrameReader::new(
1823            &ReplayFactory,
1824            config(),
1825            single_group_of_pictures(),
1826            Limits::default(),
1827        )
1828        .unwrap();
1829        let cancellation = CancellationToken::new();
1830
1831        // Reaching frame 3 submits samples 0 through 3, and every sample after the first
1832        // republishes its predecessor, so frames 0, 1, and 2 are each published twice.
1833        assert_eq!(
1834            value(&reader.get(FrameIndex(3), &cancellation).unwrap()),
1835            30
1836        );
1837        assert_eq!(
1838            value(&reader.get(FrameIndex(6), &cancellation).unwrap()),
1839            60
1840        );
1841
1842        // The repeats were cached rather than refused, so the frames behind the target are
1843        // still answered from the cache instead of costing another reset.
1844        let resets = reader.statistics().resets;
1845        let hits = reader.statistics().cache_hits;
1846        assert_eq!(
1847            value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
1848            50
1849        );
1850        assert_eq!(reader.statistics().resets, resets);
1851        assert!(reader.statistics().cache_hits > hits);
1852    }
1853
1854    /// Ten frames behind one random-access point, as the bundled sample's single group of
1855    /// pictures is, with `value == index * 10`.
1856    fn single_group_of_pictures() -> Vec<EncodedVideoSample> {
1857        (0..10)
1858            .map(|index| sample(index, (index * 10) as u8, index == 0))
1859            .collect()
1860    }
1861
1862    /// A cache small enough that a walk over ten frames is longer than the tail the reader
1863    /// keeps behind its target; the default cache would hold the whole group of pictures.
1864    fn small_cache() -> Limits {
1865        Limits {
1866            max_cached_frames: 2,
1867            ..Limits::default()
1868        }
1869    }
1870
1871    #[test]
1872    fn walking_to_a_distant_frame_does_not_ask_for_the_pictures_it_passes() {
1873        let log = Arc::new(Mutex::new(Vec::new()));
1874        let factory = HintFactory {
1875            wanted: Arc::clone(&log),
1876        };
1877        let mut reader = ExactFrameReader::new(
1878            &factory,
1879            config(),
1880            single_group_of_pictures(),
1881            small_cache(),
1882        )
1883        .unwrap();
1884        let cancellation = CancellationToken::new();
1885
1886        assert_eq!(
1887            value(&reader.get(FrameIndex(8), &cancellation).unwrap()),
1888            80
1889        );
1890        assert_eq!(
1891            *log.lock().unwrap(),
1892            vec![
1893                (0, false),
1894                (1, false),
1895                (2, false),
1896                (3, false),
1897                (4, false),
1898                (5, false),
1899                (6, true),
1900                (7, true),
1901                (8, true),
1902            ],
1903            "only the target and the tail the cache can hold are produced"
1904        );
1905        let statistics = reader.statistics();
1906        assert_eq!(statistics.samples_submitted, 9);
1907        assert_eq!(statistics.samples_skipped, 6);
1908        assert_eq!(statistics.resets, 1, "the walk itself is one decode");
1909    }
1910
1911    #[test]
1912    fn a_frame_the_walk_went_past_is_decoded_again_rather_than_reported_missing() {
1913        let log = Arc::new(Mutex::new(Vec::new()));
1914        let factory = HintFactory {
1915            wanted: Arc::clone(&log),
1916        };
1917        let mut reader = ExactFrameReader::new(
1918            &factory,
1919            config(),
1920            single_group_of_pictures(),
1921            small_cache(),
1922        )
1923        .unwrap();
1924        let cancellation = CancellationToken::new();
1925        reader.get(FrameIndex(8), &cancellation).unwrap();
1926        let resets = reader.statistics().resets;
1927
1928        // Frame 4 was submitted with nothing wanting its picture, so this decoder will never
1929        // emit it again. The reader has to notice that and start over, exactly as it does for a
1930        // frame it published and then evicted.
1931        assert_eq!(
1932            value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1933            40
1934        );
1935        assert_eq!(reader.statistics().resets, resets + 1);
1936        // And having decoded it, it is a cached frame again rather than a second reset.
1937        assert_eq!(
1938            value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1939            40
1940        );
1941        assert_eq!(reader.statistics().resets, resets + 1);
1942    }
1943
1944    #[test]
1945    fn a_reordered_frame_at_or_past_the_target_is_kept_for_the_request_that_follows() {
1946        // Decode order 0, 4, 2, 1, 3: reaching frame 4 means submitting samples whose own
1947        // frames are 2, 1 and 3, which is a walk *backwards* in presentation order. Skipping by
1948        // decode position would discard them and make every following request a fresh walk.
1949        let samples = vec![
1950            sample(0, 0, true),
1951            sample(4, 40, false),
1952            sample(2, 20, false),
1953            sample(1, 10, false),
1954            sample(3, 30, false),
1955            sample(8, 80, false),
1956            sample(6, 60, false),
1957            sample(5, 50, false),
1958            sample(7, 70, false),
1959        ];
1960        let log = Arc::new(Mutex::new(Vec::new()));
1961        let factory = HintFactory {
1962            wanted: Arc::clone(&log),
1963        };
1964        let mut reader = ExactFrameReader::new(&factory, config(), samples, small_cache()).unwrap();
1965        let cancellation = CancellationToken::new();
1966
1967        assert_eq!(
1968            value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
1969            40
1970        );
1971        let resets = reader.statistics().resets;
1972        for (index, expected) in [(1_u64, 10_u8), (2, 20), (3, 30)] {
1973            assert_eq!(
1974                value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
1975                expected,
1976                "frame {index} is still available"
1977            );
1978        }
1979        assert_eq!(
1980            reader.statistics().resets,
1981            resets,
1982            "a frame after the target in decode order is not skipped"
1983        );
1984        assert_eq!(
1985            reader.statistics().samples_skipped,
1986            1,
1987            "only frame 0, the random-access point the walk starts from, is behind frame 4"
1988        );
1989    }
1990
1991    #[test]
1992    fn a_walk_leaves_the_frames_behind_its_target_cached_so_stepping_back_is_free() {
1993        // Walking fills the cache with the frames just before the target as a side effect, and
1994        // that is what makes the example's previous-frame key cheap. Skipping those too would
1995        // send every backward step all the way back to the random-access point.
1996        let log = Arc::new(Mutex::new(Vec::new()));
1997        let factory = HintFactory {
1998            wanted: Arc::clone(&log),
1999        };
2000        let samples: Vec<_> = (0..40)
2001            .map(|index| sample(index, index as u8, index == 0))
2002            .collect();
2003        let mut reader = ExactFrameReader::new(
2004            &factory,
2005            config(),
2006            samples,
2007            Limits {
2008                max_cached_frames: 4,
2009                ..Limits::default()
2010            },
2011        )
2012        .unwrap();
2013        let cancellation = CancellationToken::new();
2014        reader.get(FrameIndex(32), &cancellation).unwrap();
2015        let after_walk = reader.statistics();
2016        assert_eq!(after_walk.samples_skipped, 28, "frames 0 to 27 are skipped");
2017
2018        for index in [31_u64, 30, 29] {
2019            assert_eq!(
2020                value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2021                index as u8
2022            );
2023        }
2024        assert_eq!(
2025            reader.statistics().resets,
2026            after_walk.resets,
2027            "the tail the walk kept is in the cache, so stepping back decodes nothing"
2028        );
2029        assert_eq!(
2030            reader.statistics().samples_submitted,
2031            after_walk.samples_submitted
2032        );
2033    }
2034
2035    #[test]
2036    fn a_step_converts_its_own_picture_and_no_tail_behind_it() {
2037        // The charge issue #402 is about. A destination keeps the frames behind it because the
2038        // request after it is very likely to be for one of them; a step is passed through on
2039        // the way somewhere else, so those frames are converted for a request that never comes,
2040        // and a walk that steps more often than the tail is long converts everything it passes.
2041        let log = Arc::new(Mutex::new(Vec::new()));
2042        let factory = HintFactory {
2043            wanted: Arc::clone(&log),
2044        };
2045        let samples: Vec<_> = (0..40)
2046            .map(|index| sample(index, index as u8, index == 0))
2047            .collect();
2048        let mut reader = ExactFrameReader::new(
2049            &factory,
2050            config(),
2051            samples,
2052            Limits {
2053                max_cached_frames: 4,
2054                ..Limits::default()
2055            },
2056        )
2057        .unwrap();
2058        let cancellation = CancellationToken::new();
2059
2060        assert_eq!(
2061            value(&reader.get_step(FrameIndex(32), &cancellation).unwrap()),
2062            32
2063        );
2064        let after_step = reader.statistics();
2065        assert_eq!(
2066            after_step.samples_skipped, 32,
2067            "frames 0 to 31 are all passed through, tail included"
2068        );
2069        assert_eq!(
2070            reader.cached_frames(),
2071            1,
2072            "only the picture the step asked for was converted"
2073        );
2074    }
2075
2076    #[test]
2077    fn a_walk_of_steps_converts_what_it_asks_for_rather_than_what_it_passes() {
2078        // The shape of a drag's preview walk: repeated forward steps towards a far target. Each
2079        // step used to pay its own cache tail, and with a stride shorter than the tail the tails
2080        // overlapped and covered the whole span. As steps, the walk converts one picture per
2081        // step however long the span is.
2082        let log = Arc::new(Mutex::new(Vec::new()));
2083        let factory = HintFactory {
2084            wanted: Arc::clone(&log),
2085        };
2086        let samples: Vec<_> = (0..64)
2087            .map(|index| sample(index, index as u8, index == 0))
2088            .collect();
2089        let mut reader = ExactFrameReader::new(
2090            &factory,
2091            config(),
2092            samples,
2093            Limits {
2094                max_cached_frames: 8,
2095                ..Limits::default()
2096            },
2097        )
2098        .unwrap();
2099        let cancellation = CancellationToken::new();
2100
2101        // A stride of 4 against a tail of 8: every frame in the span is within some step's tail.
2102        let steps: Vec<u64> = (4..60).step_by(4).collect();
2103        for step in &steps {
2104            reader.get_step(FrameIndex(*step), &cancellation).unwrap();
2105        }
2106        let converted = reader.statistics().samples_submitted - reader.statistics().samples_skipped;
2107        assert_eq!(
2108            converted,
2109            steps.len() as u64,
2110            "one conversion per published step, not one per frame passed"
2111        );
2112        assert_eq!(
2113            reader.statistics().resets,
2114            1,
2115            "only the cold start resets; a forward walk of steps never starts over again"
2116        );
2117    }
2118
2119    #[test]
2120    fn a_step_walk_that_ends_in_a_destination_still_leaves_a_cache_tail_to_step_back_through() {
2121        // What the request split must not cost: a committed scrub is a walk of steps that ends
2122        // at the frame under the pointer, and stepping backwards from there is still expected
2123        // to come out of the cache rather than walking from the random-access point again.
2124        let log = Arc::new(Mutex::new(Vec::new()));
2125        let factory = HintFactory {
2126            wanted: Arc::clone(&log),
2127        };
2128        let samples: Vec<_> = (0..40)
2129            .map(|index| sample(index, index as u8, index == 0))
2130            .collect();
2131        let mut reader = ExactFrameReader::new(
2132            &factory,
2133            config(),
2134            samples,
2135            Limits {
2136                max_cached_frames: 4,
2137                ..Limits::default()
2138            },
2139        )
2140        .unwrap();
2141        let cancellation = CancellationToken::new();
2142
2143        for step in [8_u64, 16, 24] {
2144            reader.get_step(FrameIndex(step), &cancellation).unwrap();
2145        }
2146        reader.get(FrameIndex(32), &cancellation).unwrap();
2147        let after_walk = reader.statistics();
2148
2149        for index in [31_u64, 30, 29] {
2150            assert_eq!(
2151                value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2152                index as u8
2153            );
2154        }
2155        assert_eq!(
2156            reader.statistics().resets,
2157            after_walk.resets,
2158            "the destination kept its tail, so stepping back decodes nothing"
2159        );
2160        assert_eq!(
2161            reader.statistics().samples_submitted,
2162            after_walk.samples_submitted
2163        );
2164    }
2165
2166    /// A decoder that releases each picture one sample late, and drops whatever it is holding
2167    /// when nothing wants its output - which is what a reordering decoder does.
2168    struct LateFactory;
2169
2170    struct LateDecoder {
2171        configuration: VideoDecoderConfig,
2172        limits: Limits,
2173        held: Option<EncodedVideoSample>,
2174        output_wanted: bool,
2175    }
2176
2177    impl VideoDecoderFactory for LateFactory {
2178        fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2179            CodecSupport::Supported {
2180                implementation: CodecImplementation::Software,
2181            }
2182        }
2183
2184        fn create(
2185            &self,
2186            configuration: &VideoDecoderConfig,
2187            limits: &Limits,
2188        ) -> Result<Box<dyn VideoDecoder>> {
2189            Ok(Box::new(LateDecoder {
2190                configuration: configuration.clone(),
2191                limits: *limits,
2192                held: None,
2193                output_wanted: true,
2194            }))
2195        }
2196    }
2197
2198    impl LateDecoder {
2199        fn release(&self, sample: EncodedVideoSample) -> Result<Vec<DecodedVideoFrame>> {
2200            if !self.output_wanted {
2201                return Ok(Vec::new());
2202            }
2203            Ok(vec![DecodedVideoFrame {
2204                presentation_index: sample.presentation_index,
2205                frame: VideoFrame::new(
2206                    self.configuration.coded_dimensions,
2207                    PixelFormat::Gray8,
2208                    ColorRange::Full,
2209                    vec![Plane {
2210                        data: sample.data,
2211                        stride: 1,
2212                    }],
2213                    &self.limits,
2214                )?,
2215            }])
2216        }
2217    }
2218
2219    impl VideoDecoder for LateDecoder {
2220        fn submit(
2221            &mut self,
2222            sample: &EncodedVideoSample,
2223            cancellation: &CancellationToken,
2224        ) -> Result<Vec<DecodedVideoFrame>> {
2225            cancellation.check()?;
2226            match self.held.replace(sample.clone()) {
2227                Some(previous) => self.release(previous),
2228                None => Ok(Vec::new()),
2229            }
2230        }
2231
2232        fn drain(&mut self, _: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2233            match self.held.take() {
2234                Some(held) => self.release(held),
2235                None => Ok(Vec::new()),
2236            }
2237        }
2238
2239        fn reset(&mut self) -> Result<()> {
2240            self.held = None;
2241            Ok(())
2242        }
2243
2244        fn set_output_wanted(&mut self, wanted: bool) {
2245            self.output_wanted = wanted;
2246        }
2247    }
2248
2249    #[test]
2250    fn a_frame_still_inside_a_reordering_decoder_when_output_stops_is_written_off_too() {
2251        // The frame a decoder is holding when output stops being wanted comes out during the
2252        // suppressed stretch and is dropped, even though its own sample was submitted while
2253        // output was still wanted. A reader that does not write it off believes it can still be
2254        // asked for and reports the decoder as malformed when it never arrives.
2255        let mut reader = ExactFrameReader::new(
2256            &LateFactory,
2257            config(),
2258            single_group_of_pictures(),
2259            small_cache(),
2260        )
2261        .unwrap();
2262        let cancellation = CancellationToken::new();
2263
2264        // Reaching frame 4 means submitting frame 5's sample to release it, so the decoder is
2265        // left holding frame 5 - which it releases, and drops, on the first suppressed submit of
2266        // the request that follows.
2267        assert_eq!(
2268            value(&reader.get(FrameIndex(4), &cancellation).unwrap()),
2269            40
2270        );
2271        assert_eq!(
2272            value(&reader.get(FrameIndex(9), &cancellation).unwrap()),
2273            90
2274        );
2275        assert_eq!(
2276            value(&reader.get(FrameIndex(5), &cancellation).unwrap()),
2277            50,
2278            "the frame that was dropped in flight is decoded again, not reported missing"
2279        );
2280    }
2281
2282    #[test]
2283    fn a_decoder_that_ignores_the_hint_still_answers_every_frame() {
2284        // `set_output_wanted` is advisory: `uncompressed_video_decoder_factory` does not
2285        // implement it, and the reader has to be no less correct for that.
2286        let factory = uncompressed_video_decoder_factory();
2287        let mut reader = ExactFrameReader::new(
2288            &factory,
2289            config(),
2290            single_group_of_pictures(),
2291            small_cache(),
2292        )
2293        .unwrap();
2294        let cancellation = CancellationToken::new();
2295        reader.get(FrameIndex(8), &cancellation).unwrap();
2296        assert_eq!(reader.statistics().samples_skipped, 6);
2297        for index in 0..9_u64 {
2298            assert_eq!(
2299                value(&reader.get(FrameIndex(index), &cancellation).unwrap()),
2300                (index * 10) as u8,
2301                "frame {index} came back from the decoder that ignored the hint"
2302            );
2303        }
2304    }
2305
2306    #[test]
2307    fn malformed_packets_and_cancellation_are_reported() {
2308        let factory = uncompressed_video_decoder_factory();
2309        let mut reader = ExactFrameReader::new(
2310            &factory,
2311            config(),
2312            vec![EncodedVideoSample {
2313                presentation_index: FrameIndex(0),
2314                random_access: true,
2315                data: Vec::new(),
2316            }],
2317            Limits::default(),
2318        )
2319        .unwrap();
2320        assert_eq!(
2321            reader
2322                .get(FrameIndex(0), &CancellationToken::new())
2323                .unwrap_err()
2324                .kind(),
2325            ErrorKind::MalformedMedia
2326        );
2327        let canceled = CancellationToken::new();
2328        canceled.cancel();
2329        assert_eq!(
2330            reader.get(FrameIndex(0), &canceled).unwrap_err().kind(),
2331            ErrorKind::Canceled
2332        );
2333    }
2334
2335    #[test]
2336    fn random_access_decode_work_obeys_the_configured_bound() {
2337        let factory = uncompressed_video_decoder_factory();
2338        let mut reader = ExactFrameReader::new(
2339            &factory,
2340            config(),
2341            vec![sample(0, 1, true), sample(1, 2, false), sample(2, 3, false)],
2342            Limits {
2343                max_decode_samples_per_seek: 2,
2344                ..Limits::default()
2345            },
2346        )
2347        .unwrap();
2348        let error = reader
2349            .get(FrameIndex(2), &CancellationToken::new())
2350            .unwrap_err();
2351        assert_eq!(error.kind(), ErrorKind::ResourceLimit);
2352        assert_eq!(reader.statistics().samples_submitted, 2);
2353    }
2354
2355    struct DelayedFactory;
2356    impl VideoDecoderFactory for DelayedFactory {
2357        fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2358            CodecSupport::Supported {
2359                implementation: CodecImplementation::Software,
2360            }
2361        }
2362        fn create(
2363            &self,
2364            configuration: &VideoDecoderConfig,
2365            limits: &Limits,
2366        ) -> Result<Box<dyn VideoDecoder>> {
2367            Ok(Box::new(DelayedDecoder {
2368                configuration: configuration.clone(),
2369                limits: *limits,
2370                delayed: None,
2371            }))
2372        }
2373    }
2374    struct DelayedDecoder {
2375        configuration: VideoDecoderConfig,
2376        limits: Limits,
2377        delayed: Option<EncodedVideoSample>,
2378    }
2379    impl DelayedDecoder {
2380        fn decode(&self, sample: EncodedVideoSample) -> Result<DecodedVideoFrame> {
2381            Ok(DecodedVideoFrame {
2382                presentation_index: sample.presentation_index,
2383                frame: VideoFrame::new(
2384                    self.configuration.coded_dimensions,
2385                    PixelFormat::Gray8,
2386                    ColorRange::Full,
2387                    vec![Plane {
2388                        data: sample.data,
2389                        stride: 1,
2390                    }],
2391                    &self.limits,
2392                )?,
2393            })
2394        }
2395    }
2396    impl VideoDecoder for DelayedDecoder {
2397        fn submit(
2398            &mut self,
2399            sample: &EncodedVideoSample,
2400            cancellation: &CancellationToken,
2401        ) -> Result<Vec<DecodedVideoFrame>> {
2402            cancellation.check()?;
2403            let previous = self.delayed.replace(sample.clone());
2404            previous
2405                .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2406                .unwrap_or(Ok(Vec::new()))
2407        }
2408        fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2409            cancellation.check()?;
2410            self.delayed
2411                .take()
2412                .map(|sample| self.decode(sample).map(|frame| vec![frame]))
2413                .unwrap_or(Ok(Vec::new()))
2414        }
2415        fn reset(&mut self) -> Result<()> {
2416            self.delayed = None;
2417            Ok(())
2418        }
2419    }
2420
2421    #[test]
2422    fn delayed_output_drains_and_reset_clears_state() {
2423        let mut reader = ExactFrameReader::new(
2424            &DelayedFactory,
2425            config(),
2426            vec![sample(0, 11, true), sample(1, 22, false)],
2427            Limits::default(),
2428        )
2429        .unwrap();
2430        let cancellation = CancellationToken::new();
2431        assert_eq!(
2432            value(&reader.get(FrameIndex(1), &cancellation).unwrap()),
2433            22
2434        );
2435        assert_eq!(reader.statistics().drains, 1);
2436        reader.reset().unwrap();
2437        assert_eq!(reader.cached_frames(), 0);
2438        assert_eq!(
2439            value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2440            11
2441        );
2442    }
2443
2444    #[test]
2445    fn sequential_playback_through_a_pipelined_decoder_does_not_reset_every_frame() {
2446        // `DelayedDecoder` only emits a frame's output on the *next* `submit` call (or on
2447        // `drain`), modeling the one-frame pipeline latency a real reordering decoder exhibits.
2448        // Even though `next_decode_position` therefore always runs one step ahead of the frame
2449        // a straightforward sequential `get(0), get(1), get(2), ...` walk is actually waiting
2450        // on, that lag must not force a full reset-and-redecode-from-keyframe on every call.
2451        let mut reader = ExactFrameReader::new(
2452            &DelayedFactory,
2453            config(),
2454            vec![
2455                sample(0, 11, true),
2456                sample(1, 22, false),
2457                sample(2, 33, false),
2458                sample(3, 44, false),
2459                sample(4, 55, false),
2460            ],
2461            Limits::default(),
2462        )
2463        .unwrap();
2464        let cancellation = CancellationToken::new();
2465
2466        assert_eq!(
2467            value(&reader.get(FrameIndex(0), &cancellation).unwrap()),
2468            11
2469        );
2470        assert_eq!(reader.statistics().resets, 1);
2471
2472        for (index, expected) in [(1, 22_u8), (2, 33), (3, 44), (4, 55)] {
2473            let frame = reader.get(FrameIndex(index), &cancellation).unwrap();
2474            assert_eq!(value(&frame), expected);
2475            assert_eq!(
2476                reader.statistics().resets,
2477                1,
2478                "sequential forward playback must not reset once decoding has started"
2479            );
2480        }
2481        assert_eq!(reader.statistics().samples_submitted, 5);
2482        assert_eq!(reader.statistics().drains, 1);
2483    }
2484
2485    struct MalformedOutputFactory;
2486
2487    impl VideoDecoderFactory for MalformedOutputFactory {
2488        fn capability(&self, _: &VideoDecoderConfig) -> CodecSupport {
2489            CodecSupport::Supported {
2490                implementation: CodecImplementation::Software,
2491            }
2492        }
2493
2494        fn create(
2495            &self,
2496            configuration: &VideoDecoderConfig,
2497            limits: &Limits,
2498        ) -> Result<Box<dyn VideoDecoder>> {
2499            let factory = UncompressedVideoDecoderFactory;
2500            factory.create(configuration, limits).map(|decoder| {
2501                Box::new(MalformedOutputDecoder {
2502                    decoder,
2503                    previous: None,
2504                }) as Box<dyn VideoDecoder>
2505            })
2506        }
2507    }
2508
2509    struct MalformedOutputDecoder {
2510        decoder: Box<dyn VideoDecoder>,
2511        previous: Option<FrameIndex>,
2512    }
2513
2514    impl VideoDecoder for MalformedOutputDecoder {
2515        fn submit(
2516            &mut self,
2517            sample: &EncodedVideoSample,
2518            cancellation: &CancellationToken,
2519        ) -> Result<Vec<DecodedVideoFrame>> {
2520            let mut output = self.decoder.submit(sample, cancellation)?;
2521            if let (Some(previous), Some(frame)) = (self.previous, output.first_mut()) {
2522                frame.presentation_index = previous;
2523            }
2524            self.previous = Some(sample.presentation_index);
2525            Ok(output)
2526        }
2527
2528        fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
2529            self.decoder.drain(cancellation)
2530        }
2531
2532        fn reset(&mut self) -> Result<()> {
2533            self.previous = None;
2534            self.decoder.reset()
2535        }
2536    }
2537
2538    #[test]
2539    fn malformed_backend_output_is_rejected() {
2540        let mut reader = ExactFrameReader::new(
2541            &MalformedOutputFactory,
2542            config(),
2543            vec![sample(0, 1, true), sample(1, 2, false)],
2544            Limits::default(),
2545        )
2546        .unwrap();
2547        let error = reader
2548            .get(FrameIndex(1), &CancellationToken::new())
2549            .unwrap_err();
2550        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
2551    }
2552}