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