Skip to main content

zvidlib_core/
codec.rs

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