Skip to main content

alpha2_host_core/
video_stream.rs

1//! Frame-exact video decoding over a container reader and a platform decoder session.
2//!
3//! [`VideoStream`] owns the policy every native backend shares: a seek answers with the last frame
4//! at or before the time plus the stream's presentation slack, found by decoding from the keyframe
5//! before it (stepping back a keyframe at a time when every frame from that keyframe comes later);
6//! sequential reads keep one frame of lookahead; frames a session emits in decode order are put
7//! back in presentation order; a failing hardware session is replaced by a software one once, and
8//! a session the system takes away is reopened where the stream was.
9
10use std::sync::Arc;
11
12use alpha2_container::{ContainerReader, Packet, TrackInfo, TrackKind, VideoCodec};
13use alpha2_media::{
14    CancelToken, ChromaLocation, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest,
15    DecodeResult, DecodedVideoFrame, Decoder, Orientation, PixelFormat, Plane, Rect,
16    SampleAspectRatio, SourceAlpha, StreamInfo, StreamKind, YuvFormat,
17};
18use alpha2_time::{MediaTime, TICKS_PER_SECOND};
19
20use crate::parameter_sets::{CropWindow, ParameterSetCodec, Vui, sequence_facts};
21use crate::recovery::{DecodeFailure, DecodePolicy, Recovery, WorkBudget};
22
23/// Whether a decoder session runs on dedicated hardware.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub enum BackendKind {
26    /// A hardware decoder.
27    Hardware,
28    /// A software decoder.
29    Software,
30}
31
32/// Why a decoder session failed.
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub enum BackendError {
35    /// The system took the session away (app backgrounded, codec reclaimed, device lost); a new
36    /// session can continue.
37    SessionLost(String),
38    /// The session cannot decode this stream.
39    Unsupported(String),
40    /// The packet just submitted is damaged.
41    Corrupt(String),
42    /// A hardware session could not decode a picture.
43    HardwarePicture(String),
44    /// Anything else.
45    Failed(String),
46}
47
48impl std::fmt::Display for BackendError {
49    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        match self {
51            Self::SessionLost(reason) => write!(formatter, "decoder session lost: {reason}"),
52            Self::Unsupported(reason)
53            | Self::Corrupt(reason)
54            | Self::HardwarePicture(reason)
55            | Self::Failed(reason) => write!(formatter, "{reason}"),
56        }
57    }
58}
59
60impl From<BackendError> for DecodeError {
61    fn from(error: BackendError) -> Self {
62        match error {
63            BackendError::Unsupported(reason) => Self::Unsupported(reason),
64            error => Self::Adapter(error.to_string()),
65        }
66    }
67}
68
69/// What a session did with a packet.
70#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub enum Submit {
72    /// The packet is queued.
73    Accepted,
74    /// The session's input is full; receive pictures, then submit the same packet again.
75    Busy,
76}
77
78/// A decoded picture that stays on the platform's surface until the lease drops.
79pub trait SurfaceLease: std::fmt::Debug + Send + Sync + 'static {
80    /// Bytes the surface holds, charged to the frame budget.
81    fn retained_bytes(&self) -> u64;
82
83    /// Lets the platform importer recover its own lease type.
84    fn as_any(&self) -> &dyn std::any::Any;
85}
86
87/// A decoded picture's pixels.
88#[derive(Clone, Debug)]
89pub enum BackendImage {
90    /// Planes in memory.
91    Cpu {
92        /// Their layout.
93        format: YuvFormat,
94        /// Luma, then chroma (one interleaved or two planar), then alpha.
95        planes: Vec<Plane>,
96    },
97    /// A platform surface the renderer imports.
98    Surface(Arc<dyn SurfaceLease>),
99}
100
101/// One picture a session produced, with what the session knows about it.
102#[derive(Clone, Debug)]
103pub struct BackendFrame {
104    /// The presentation time of the packet it came from, in the track's timescale.
105    pub pts: i64,
106    /// Its pixels.
107    pub image: BackendImage,
108    /// The width and height of the image's buffer.
109    pub coded: (u32, u32),
110    /// The visible area, when the session applied or reported the crop.
111    pub visible: Option<Rect>,
112    /// The pixel aspect ratio the bitstream signals, when the session reports it.
113    pub sample_aspect_ratio: Option<SampleAspectRatio>,
114    /// The color the bitstream signals, when the session reports it.
115    pub color: Option<ColorMetadata>,
116    /// The chroma siting the bitstream signals; `None` when it signals none.
117    pub chroma_location: Option<ChromaLocation>,
118}
119
120/// What a session had on a receive.
121#[derive(Debug)]
122pub enum Poll {
123    /// A picture.
124    Frame(BackendFrame),
125    /// Nothing yet; submit more input.
126    Pending,
127    /// Input ended and every picture was given.
128    Drained,
129}
130
131/// One decoder session for one video track, used from one thread at a time.
132pub trait VideoDecodeBackend: Send {
133    /// Whether it runs on hardware.
134    fn kind(&self) -> BackendKind;
135
136    /// Queues a packet for decoding.
137    ///
138    /// # Errors
139    /// A lost session, a damaged packet, or a failed decoder.
140    fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError>;
141
142    /// Takes a decoded picture, in decode order or, when [`Self::presentation_order`], in
143    /// presentation order. With `wait`, blocks briefly for one: the session refused input, or
144    /// input ended.
145    ///
146    /// # Errors
147    /// A lost session, an undecodable picture, or a failed decoder.
148    fn receive(&mut self, wait: bool) -> Result<Poll, BackendError>;
149
150    /// Whether pictures come out in presentation order, so the stream holds none back to reorder
151    /// them. Sessions that emit decode order keep the default.
152    fn presentation_order(&self) -> bool {
153        false
154    }
155
156    /// No more packets follow until a [`Self::flush`]; receives then drain the session.
157    ///
158    /// # Errors
159    /// A lost session or a failed decoder.
160    fn finish_input(&mut self) -> Result<(), BackendError>;
161
162    /// Drops every queued packet and picture, ready for packets from a keyframe.
163    ///
164    /// # Errors
165    /// A lost session or a failed decoder.
166    fn flush(&mut self) -> Result<(), BackendError>;
167}
168
169/// Opens decoder sessions for tracks.
170pub trait VideoBackends: Send + Sync {
171    /// A session of `kind` for `track`.
172    ///
173    /// # Errors
174    /// [`BackendError::Unsupported`] when no decoder of that kind reads the track.
175    fn open(
176        &self,
177        track: &TrackInfo,
178        kind: BackendKind,
179    ) -> Result<Box<dyn VideoDecodeBackend>, BackendError>;
180}
181
182/// What the bitstream's configuration declares beyond the container, which hardware sessions
183/// do not report reliably.
184#[derive(Clone, Copy, Debug, Default)]
185struct Bitstream {
186    vui: Vui,
187    chroma_location: Option<ChromaLocation>,
188}
189
190/// The chroma siting an `av1C` record's `chroma_sample_position` declares.
191fn av1_chroma_location(record: &[u8]) -> Option<ChromaLocation> {
192    match record.get(2)? & 3 {
193        1 => Some(ChromaLocation::Left),
194        2 => Some(ChromaLocation::TopLeft),
195        _ => None,
196    }
197}
198
199/// Which sessions a stream may use.
200#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
201pub enum DecodePreference {
202    /// Hardware, then software once when hardware fails.
203    #[default]
204    Auto,
205    /// Hardware only.
206    Hardware,
207    /// Software only.
208    Software,
209}
210
211/// How a [`VideoStream`] is opened.
212#[derive(Clone, Copy, Debug, Default)]
213pub struct StreamOptions {
214    /// Which sessions it may use.
215    pub preference: DecodePreference,
216    /// How damaged input is handled.
217    pub policy: DecodePolicy,
218    /// The color the project declares for the source, which every frame then carries.
219    pub declared_color: Option<ColorMetadata>,
220}
221
222/// The facts every frame carries besides its pixels.
223#[derive(Clone, Copy, Debug, PartialEq)]
224pub struct FrameFacts {
225    /// Presentation time.
226    pub pts: MediaTime,
227    /// The visible area in buffer pixels.
228    pub visible_rect: Rect,
229    /// How the picture is shown.
230    pub orientation: Orientation,
231    /// Pixel aspect ratio.
232    pub sample_aspect_ratio: SampleAspectRatio,
233    /// Chroma siting.
234    pub chroma_location: ChromaLocation,
235    /// Color, when declared or tagged.
236    pub color: Option<ColorMetadata>,
237}
238
239/// A decoded frame of a [`VideoStream`].
240#[derive(Clone, Debug)]
241pub struct StreamFrame {
242    /// Its facts.
243    pub facts: FrameFacts,
244    /// Its pixels.
245    pub image: BackendImage,
246}
247
248impl StreamFrame {
249    /// Bytes the frame holds: its planes, or what its surface retains.
250    #[must_use]
251    pub fn retained_bytes(&self) -> u64 {
252        match &self.image {
253            BackendImage::Cpu { planes, .. } => {
254                planes.iter().map(|plane| plane.bytes.len() as u64).sum()
255            }
256            BackendImage::Surface(lease) => lease.retained_bytes(),
257        }
258    }
259
260    /// The frame as a CPU frame; `None` for a surface.
261    #[must_use]
262    pub fn to_cpu(&self) -> Option<DecodedVideoFrame> {
263        let BackendImage::Cpu { format, planes } = &self.image else {
264            return None;
265        };
266        Some(DecodedVideoFrame {
267            pts: self.facts.pts,
268            dts: None,
269            duration: None,
270            visible_rect: self.facts.visible_rect,
271            sample_aspect_ratio: self.facts.sample_aspect_ratio,
272            orientation: self.facts.orientation,
273            pixel_format: PixelFormat::Yuv(*format),
274            chroma_location: self.facts.chroma_location,
275            color: self.facts.color,
276            planes: planes.clone(),
277        })
278    }
279}
280
281/// Puts pictures a session emits in decode order back in presentation order.
282///
283/// With a reorder depth (pictures that may precede any picture in decode order and follow it in
284/// presentation order), the earliest held picture is released once more than that many are held:
285/// a later picture would follow every held one in decode order and precede it in presentation
286/// order, exceeding the depth. Without one, held pictures are released once a picture arrives no
287/// earlier than all of them, which is exact for streams that reorder at most one picture deep.
288#[derive(Debug, Default)]
289pub struct ReorderBuffer {
290    depth: Option<usize>,
291    arriving: Vec<BackendFrame>,
292    ready: std::collections::VecDeque<BackendFrame>,
293}
294
295impl ReorderBuffer {
296    /// An empty buffer for a stream reordered at most `depth` pictures deep; `None` when unknown.
297    #[must_use]
298    pub fn new(depth: Option<usize>) -> Self {
299        Self {
300            depth,
301            ..Self::default()
302        }
303    }
304
305    /// Takes a picture from the session.
306    pub fn arrive(&mut self, frame: BackendFrame) {
307        if self.depth.is_none()
308            && self
309                .arriving
310                .last()
311                .is_some_and(|latest| frame.pts >= latest.pts)
312        {
313            self.ready.extend(self.arriving.drain(..));
314        }
315        let at = self
316            .arriving
317            .iter()
318            .position(|held| held.pts > frame.pts)
319            .unwrap_or(self.arriving.len());
320        self.arriving.insert(at, frame);
321        if let Some(depth) = self.depth {
322            let excess = self.arriving.len().saturating_sub(depth);
323            self.ready.extend(self.arriving.drain(..excess));
324        }
325    }
326
327    /// The session drained: every held picture is released.
328    pub fn drain(&mut self) {
329        self.ready.extend(self.arriving.drain(..));
330    }
331
332    /// The next picture in presentation order, once it is certain.
333    pub fn take(&mut self) -> Option<BackendFrame> {
334        self.ready.pop_front()
335    }
336
337    /// Drops everything.
338    pub fn clear(&mut self) {
339        self.arriving.clear();
340        self.ready.clear();
341    }
342
343    /// Pictures held now.
344    #[must_use]
345    pub fn len(&self) -> usize {
346        self.arriving.len() + self.ready.len()
347    }
348
349    /// Whether nothing is held.
350    #[must_use]
351    pub fn is_empty(&self) -> bool {
352        self.len() == 0
353    }
354}
355
356/// Sessions the system may take from one stream in a row, with no frame decoded between them,
357/// before its decode fails.
358const MAX_SESSION_REOPENS: u32 = 3;
359
360/// Where a session's input stands.
361#[derive(Clone, Copy, Debug, Eq, PartialEq)]
362enum Input {
363    /// Packets go in.
364    Open,
365    /// The session refused the pending packet until it outputs.
366    Full,
367    /// Every packet is in; the session drains.
368    Ended,
369    /// The session gave its last picture.
370    Drained,
371}
372
373/// Why decoding stopped: a session to replace, or a failure for the caller.
374enum Interrupt {
375    Backend(BackendError),
376    Decode(DecodeError),
377}
378
379impl From<DecodeError> for Interrupt {
380    fn from(error: DecodeError) -> Self {
381        Self::Decode(error)
382    }
383}
384
385impl From<alpha2_container::DemuxError> for Interrupt {
386    fn from(error: alpha2_container::DemuxError) -> Self {
387        Self::Decode(error.into())
388    }
389}
390
391/// Something a stream's pictures go without (they still decode), for reports.
392#[derive(Clone, Debug, Eq, PartialEq)]
393pub struct DroppedLayer {
394    /// `alpha-dropped`, the code the desktop host reports too.
395    pub code: &'static str,
396    /// Why, for people.
397    pub reason: String,
398}
399
400/// The alpha a track declares, which the platform sessions decode opaque.
401fn dropped_alpha(video: &alpha2_container::VideoTrack) -> Option<(SourceAlpha, DroppedLayer)> {
402    if !video.alpha {
403        return None;
404    }
405    let (alpha, reason) = match video.codec {
406        VideoCodec::Vp9 => (
407            SourceAlpha::Vp9SideData,
408            "VP9 alpha in block additions is not decoded on this platform",
409        ),
410        VideoCodec::Hevc => (
411            SourceAlpha::HevcAuxiliaryLayer,
412            "alpha in an HEVC auxiliary layer is not decoded",
413        ),
414        _ => (
415            SourceAlpha::Planar,
416            "the alpha plane is not decoded on this platform",
417        ),
418    };
419    let dropped = DroppedLayer {
420        code: "alpha-dropped",
421        reason: reason.into(),
422    };
423    Some((alpha, dropped))
424}
425
426/// A video track decoded frame-exactly.
427pub struct VideoStream {
428    reader: Box<dyn ContainerReader>,
429    track: TrackInfo,
430    backends: Arc<dyn VideoBackends>,
431    backend: Box<dyn VideoDecodeBackend>,
432    options: StreamOptions,
433    software_fallback_used: bool,
434    reopens: u32,
435    recovery: Recovery,
436    reorder: ReorderBuffer,
437    lookahead: Option<StreamFrame>,
438    pending: Option<Packet>,
439    input: Input,
440    /// The last frame handed out, which a replacement session decodes past.
441    last_returned: Option<i64>,
442    /// Frames at or before this time are dropped: they were handed out by a lost session.
443    resume_after: Option<i64>,
444    /// The stream's first keyframe, where a seek cannot step back from.
445    first_keyframe: Option<i64>,
446    slack: MediaTime,
447    crop: Option<CropWindow>,
448    bitstream: Bitstream,
449    info: Vec<StreamInfo>,
450    dropped: Option<DroppedLayer>,
451}
452
453impl std::fmt::Debug for VideoStream {
454    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455        formatter
456            .debug_struct("VideoStream")
457            .field("track", &self.track.id)
458            .field("backend", &self.backend.kind())
459            .finish_non_exhaustive()
460    }
461}
462
463impl VideoStream {
464    /// Opens track `index` of `reader` with a session from `backends`.
465    ///
466    /// # Errors
467    /// [`DecodeError::Unsupported`] for a track that is not video or that no allowed session
468    /// reads.
469    pub fn open(
470        mut reader: Box<dyn ContainerReader>,
471        index: usize,
472        backends: Arc<dyn VideoBackends>,
473        options: StreamOptions,
474    ) -> Result<Self, DecodeError> {
475        let track =
476            reader.tracks().get(index).cloned().ok_or_else(|| {
477                DecodeError::Unsupported(format!("the file has no track {index}"))
478            })?;
479        let Some(video) = track.video.clone() else {
480            return Err(DecodeError::Unsupported(format!(
481                "track {} is not video",
482                track.id.0
483            )));
484        };
485        let sequence = match video.codec {
486            VideoCodec::H264 => sequence_facts(ParameterSetCodec::H264, &video.codec_private),
487            VideoCodec::Hevc => sequence_facts(ParameterSetCodec::Hevc, &video.codec_private),
488            _ => None,
489        };
490        let crop = sequence.map(|facts| facts.crop);
491        let bitstream = Bitstream {
492            vui: sequence.map(|facts| facts.vui).unwrap_or_default(),
493            chroma_location: match video.codec {
494                VideoCodec::Av1 => av1_chroma_location(&video.codec_private),
495                _ => sequence.and_then(|facts| facts.chroma_location()),
496            },
497        };
498        let first = match options.preference {
499            DecodePreference::Software => BackendKind::Software,
500            DecodePreference::Auto | DecodePreference::Hardware => BackendKind::Hardware,
501        };
502        let (backend, software_fallback_used) = match backends.open(&track, first) {
503            Ok(backend) => (backend, false),
504            Err(hardware) if options.preference == DecodePreference::Auto => {
505                let software = backends.open(&track, BackendKind::Software).map_err(|software| {
506                    DecodeError::Unsupported(format!(
507                        "no decoder here reads this stream (hardware: {hardware}; software: {software})"
508                    ))
509                })?;
510                (software, true)
511            }
512            Err(error) => return Err(error.into()),
513        };
514        let first_keyframe = reader.seek(track.id, i64::MIN)?;
515        let timescale = i64::from(track.timescale.max(1));
516        let slack = scan_slack(reader.as_mut(), &track)?;
517        let mut recovery = Recovery::new((1, i32::try_from(timescale).unwrap_or(i32::MAX)));
518        recovery.policy = options.policy;
519        recovery.set_hardware(backend.kind() == BackendKind::Hardware);
520        let dimensions = crop
521            .and_then(|crop| crop.visible())
522            .map_or((video.width, video.height), |rect| {
523                (rect.width, rect.height)
524            });
525        let reorder = ReorderBuffer::new(reorder_depth(backend.as_ref(), &track));
526        let (alpha, dropped) = dropped_alpha(&video).unzip();
527        let info = vec![StreamInfo {
528            index,
529            kind: StreamKind::Video,
530            codec: codec_name(video.codec),
531            duration: track
532                .duration
533                .map(|duration| to_media_time(duration, track.timescale)),
534            dimensions: Some(dimensions),
535            frame_rate: video.frame_rate,
536            sample_rate: None,
537            channels: None,
538            orientation: video.orientation,
539            sample_aspect_ratio: video
540                .sample_aspect_ratio
541                .or(bitstream.vui.sample_aspect_ratio)
542                .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
543            color: options
544                .declared_color
545                .or(video.color)
546                .or(bitstream.vui.color),
547            frame_bytes: None,
548            alpha,
549            language: track.language.clone(),
550            title: track.title.clone(),
551        }];
552        Ok(Self {
553            reader,
554            backends,
555            backend,
556            options,
557            software_fallback_used,
558            reopens: 0,
559            recovery,
560            reorder,
561            lookahead: None,
562            pending: None,
563            input: Input::Open,
564            last_returned: None,
565            resume_after: None,
566            first_keyframe,
567            slack,
568            crop,
569            bitstream,
570            info,
571            dropped,
572            track,
573        })
574    }
575
576    /// Opens the default video track of the file at `path`.
577    ///
578    /// # Errors
579    /// [`DecodeError::Unsupported`] for a container this layer does not read, a file without
580    /// video, or a track no allowed session reads; read failures.
581    pub fn open_file(
582        path: &std::path::Path,
583        backends: Arc<dyn VideoBackends>,
584        options: StreamOptions,
585    ) -> Result<Self, DecodeError> {
586        let reader = alpha2_container::open(path)?;
587        let index = alpha2_container::default_track(reader.tracks(), TrackKind::Video)
588            .ok_or_else(|| DecodeError::Unsupported("the file has no video track".into()))?;
589        Self::open(reader, index, backends, options)
590    }
591
592    /// The track decoded.
593    #[must_use]
594    pub const fn track(&self) -> &TrackInfo {
595        &self.track
596    }
597
598    /// What the track declares that its pictures go without: the alpha of a track that has one.
599    #[must_use]
600    pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
601        self.dropped.as_ref()
602    }
603
604    /// Bytes of the frame decoded ahead and kept for the next [`Self::next`].
605    #[must_use]
606    pub fn lookahead_bytes(&self) -> u64 {
607        self.lookahead
608            .as_ref()
609            .map_or(0, StreamFrame::retained_bytes)
610    }
611
612    /// How far after a time a frame may be stored and still be the one shown at it.
613    #[must_use]
614    pub const fn presentation_slack(&self) -> MediaTime {
615        self.slack
616    }
617
618    /// Whether the session open now runs on hardware.
619    #[must_use]
620    pub fn on_hardware(&self) -> bool {
621        self.backend.kind() == BackendKind::Hardware
622    }
623
624    /// Damage recorded so far.
625    #[must_use]
626    pub const fn recovery(&self) -> &Recovery {
627        &self.recovery
628    }
629
630    /// The next frame in presentation order; `None` at the end.
631    ///
632    /// # Errors
633    /// Cancellation, a spent work budget, damage beyond the policy, or a decoder failure no
634    /// replacement session survives.
635    pub fn next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
636        let frame = match self.lookahead.take() {
637            Some(frame) => Some(frame),
638            None => self.decode_next(cancel)?,
639        };
640        if let Some(frame) = &frame {
641            self.last_returned = Some(self.track_units(frame.facts.pts));
642        }
643        Ok(frame)
644    }
645
646    /// When the frame [`Self::next`] returns is presented; `None` at the end. The frame is decoded
647    /// now and kept.
648    ///
649    /// # Errors
650    /// As [`Self::next`].
651    pub fn peek_pts(&mut self, cancel: &CancelToken) -> Result<Option<MediaTime>, DecodeError> {
652        if self.lookahead.is_none() {
653            self.lookahead = self.decode_next(cancel)?;
654        }
655        Ok(self.lookahead.as_ref().map(|frame| frame.facts.pts))
656    }
657
658    /// The frame shown at `time`: the last at or before `time` plus the slack, the first for an
659    /// earlier time and the last for a later one. The frame after it becomes the lookahead.
660    ///
661    /// # Errors
662    /// [`DecodeError::OutOfRange`] for a stream without frames; otherwise as [`Self::next`].
663    pub fn seek(
664        &mut self,
665        time: MediaTime,
666        cancel: &CancelToken,
667    ) -> Result<StreamFrame, DecodeError> {
668        loop {
669            match self.seek_once(time, cancel) {
670                Ok(frame) => {
671                    self.last_returned = Some(self.track_units(frame.facts.pts));
672                    return Ok(frame);
673                }
674                Err(Interrupt::Decode(error)) => return Err(error),
675                Err(Interrupt::Backend(error)) => self.replace_session(error)?,
676            }
677        }
678    }
679
680    fn seek_once(
681        &mut self,
682        time: MediaTime,
683        cancel: &CancelToken,
684    ) -> Result<StreamFrame, Interrupt> {
685        self.resume_after = None;
686        let deadline = time.presentation_deadline(self.slack);
687        let mut target = self.track_units_floor(deadline);
688        let mut keyframe = self.reader.seek(self.track.id, target)?;
689        let first = loop {
690            self.reset(None)?;
691            let Some(first) = self.decode_raw(cancel)? else {
692                return Err(DecodeError::OutOfRange.into());
693            };
694            let at_start = keyframe.is_none() || keyframe <= self.first_keyframe;
695            if first.facts.pts <= deadline || at_start {
696                break first;
697            }
698            // Every frame from this keyframe comes later (leading frames of an open GOP, or an
699            // index by decode time): decode from the keyframe before it.
700            let landed = keyframe;
701            let mut step = 1_i64;
702            while keyframe == landed && target > i64::MIN {
703                target = target.min(landed.unwrap_or(target)).saturating_sub(step);
704                keyframe = self.reader.seek(self.track.id, target)?;
705                step = step.saturating_mul(2);
706            }
707        };
708        let mut shown = first;
709        loop {
710            match self.decode_raw(cancel)? {
711                Some(frame) if frame.facts.pts <= deadline => shown = frame,
712                Some(frame) => {
713                    self.lookahead = Some(frame);
714                    break;
715                }
716                None => break,
717            }
718        }
719        Ok(shown)
720    }
721
722    fn decode_next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
723        loop {
724            match self.decode_raw(cancel) {
725                Ok(frame) => return Ok(frame),
726                Err(Interrupt::Decode(error)) => return Err(error),
727                Err(Interrupt::Backend(error)) => {
728                    self.replace_session(error)?;
729                    self.resume().map_err(|interrupt| match interrupt {
730                        Interrupt::Decode(error) => error,
731                        Interrupt::Backend(error) => error.into(),
732                    })?;
733                }
734            }
735        }
736    }
737
738    /// Decodes until the next frame in presentation order is certain.
739    fn decode_raw(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, Interrupt> {
740        let mut budget = WorkBudget::new();
741        loop {
742            if let Some(picture) = self.reorder.take() {
743                let frame = self.facts(picture);
744                let pts = self.track_units(frame.facts.pts);
745                // A frame dropped on the way back to the resume point is progress too.
746                budget.progressed();
747                if self.resume_after.is_some_and(|after| pts <= after) {
748                    continue;
749                }
750                self.resume_after = None;
751                self.reopens = 0;
752                self.recovery.progress(Some(pts))?;
753                return Ok(Some(frame));
754            }
755            if self.input == Input::Drained {
756                if self.recovery.diagnostics.corrupt_packets.is_empty() {
757                    return Ok(None);
758                }
759                self.recovery.video_eof()?;
760                return Ok(None);
761            }
762            budget.step(cancel)?;
763            if self.step()? {
764                budget.advanced();
765            }
766        }
767    }
768
769    /// One receive, or one packet in; `true` when a packet was read or accepted.
770    fn step(&mut self) -> Result<bool, Interrupt> {
771        match self.backend.receive(self.input != Input::Open) {
772            Ok(Poll::Frame(picture)) => {
773                if self.input == Input::Full {
774                    self.input = Input::Open;
775                }
776                self.reorder.arrive(picture);
777                return Ok(false);
778            }
779            Ok(Poll::Drained) => {
780                self.reorder.drain();
781                self.input = Input::Drained;
782                return Ok(false);
783            }
784            Ok(Poll::Pending) => {}
785            Err(BackendError::HardwarePicture(reason))
786                if self
787                    .recovery
788                    .counts_as_damage(DecodeFailure::HardwarePicture) =>
789            {
790                self.recovery
791                    .corrupt_with_detail("video receive", None, Some(reason))?;
792                return Ok(false);
793            }
794            Err(error) => return Err(Interrupt::Backend(error)),
795        }
796        if matches!(self.input, Input::Ended | Input::Drained) {
797            return Ok(false);
798        }
799        let mut advanced = false;
800        if self.pending.is_none() {
801            if let Some(packet) = self.reader.next_packet(self.track.id)? {
802                self.pending = Some(packet);
803                advanced = true;
804            } else {
805                self.backend.finish_input().map_err(Interrupt::Backend)?;
806                self.input = Input::Ended;
807                return Ok(false);
808            }
809        }
810        let Some(packet) = self.pending.as_ref() else {
811            return Ok(advanced);
812        };
813        match self.backend.submit(packet) {
814            Ok(Submit::Accepted) => {
815                self.pending = None;
816                self.input = Input::Open;
817                advanced = true;
818            }
819            Ok(Submit::Busy) => self.input = Input::Full,
820            Err(BackendError::Corrupt(reason))
821                if self.recovery.counts_as_damage(DecodeFailure::InvalidData) =>
822            {
823                let pts = packet.pts;
824                self.pending = None;
825                self.recovery
826                    .corrupt_with_detail("video send", Some(pts), Some(reason))?;
827            }
828            Err(error) => return Err(Interrupt::Backend(error)),
829        }
830        Ok(advanced)
831    }
832
833    /// Empties the session and the queues, keeping `lookahead`.
834    fn reset(&mut self, lookahead: Option<StreamFrame>) -> Result<(), Interrupt> {
835        self.reorder.clear();
836        self.lookahead = lookahead;
837        self.pending = None;
838        self.input = Input::Open;
839        self.recovery.reset_progress();
840        self.backend.flush().map_err(Interrupt::Backend)
841    }
842
843    /// Opens the session that continues after `error`, or fails with it.
844    fn replace_session(&mut self, error: BackendError) -> Result<(), DecodeError> {
845        let kind = match &error {
846            BackendError::SessionLost(_) if self.reopens < MAX_SESSION_REOPENS => {
847                self.reopens += 1;
848                self.backend.kind()
849            }
850            BackendError::Unsupported(_)
851            | BackendError::Failed(_)
852            | BackendError::Corrupt(_)
853            | BackendError::HardwarePicture(_)
854                if self.backend.kind() == BackendKind::Hardware
855                    && self.options.preference == DecodePreference::Auto
856                    && !self.software_fallback_used =>
857            {
858                self.software_fallback_used = true;
859                BackendKind::Software
860            }
861            _ => return Err(error.into()),
862        };
863        self.backend = self.backends.open(&self.track, kind).map_err(|reopen| {
864            DecodeError::Adapter(format!("{error}; no session replaces it: {reopen}"))
865        })?;
866        self.reorder = ReorderBuffer::new(reorder_depth(self.backend.as_ref(), &self.track));
867        self.recovery
868            .set_hardware(self.backend.kind() == BackendKind::Hardware);
869        Ok(())
870    }
871
872    /// Positions a new session after the last frame handed out.
873    fn resume(&mut self) -> Result<(), Interrupt> {
874        let lookahead = self.lookahead.take();
875        let after = lookahead
876            .as_ref()
877            .map(|frame| self.track_units(frame.facts.pts))
878            .or(self.last_returned);
879        self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
880        self.reset(lookahead)?;
881        self.resume_after = after;
882        Ok(())
883    }
884
885    fn facts(&self, picture: BackendFrame) -> StreamFrame {
886        let video = self.track.video.as_ref();
887        let whole = Rect {
888            x: 0,
889            y: 0,
890            width: picture.coded.0,
891            height: picture.coded.1,
892        };
893        // A buffer of the SPS's coded size shows the SPS's window: some sessions report the whole
894        // buffer as visible, and some apply no crop at all. A buffer of the window's size was
895        // cropped already. Any other buffer (a stream whose SPS changed in band) is the session's.
896        let window = self.crop.and_then(|crop| {
897            let visible = crop.visible()?;
898            if picture.coded == (crop.coded_width, crop.coded_height) {
899                Some(visible)
900            } else if picture.coded == (visible.width, visible.height) {
901                Some(whole)
902            } else {
903                None
904            }
905        });
906        let visible = window.or(picture.visible).unwrap_or(whole);
907        let chroma_location = picture
908            .chroma_location
909            .or(self.bitstream.chroma_location)
910            .unwrap_or(ChromaLocation::Unspecified);
911        StreamFrame {
912            facts: FrameFacts {
913                pts: to_media_time(picture.pts, self.track.timescale),
914                visible_rect: visible,
915                orientation: video.map(|video| video.orientation).unwrap_or_default(),
916                sample_aspect_ratio: video
917                    .and_then(|video| video.sample_aspect_ratio)
918                    .or(self.bitstream.vui.sample_aspect_ratio)
919                    .or(picture.sample_aspect_ratio)
920                    .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
921                chroma_location,
922                color: self
923                    .options
924                    .declared_color
925                    .or_else(|| video.and_then(|video| video.color))
926                    .or(self.bitstream.vui.color)
927                    .or(picture.color),
928            },
929            image: picture.image,
930        }
931    }
932
933    /// `time` in the track's units, rounded to nearest.
934    fn track_units(&self, time: MediaTime) -> i64 {
935        rescale(
936            time.ticks(),
937            i64::from(self.track.timescale.max(1)),
938            TICKS_PER_SECOND,
939            false,
940        )
941    }
942
943    /// `time` in the track's units, rounded down.
944    fn track_units_floor(&self, time: MediaTime) -> i64 {
945        rescale(
946            time.ticks(),
947            i64::from(self.track.timescale.max(1)),
948            TICKS_PER_SECOND,
949            true,
950        )
951    }
952}
953
954/// How deep `track`'s pictures arrive out of presentation order from `backend`.
955fn reorder_depth(backend: &dyn VideoDecodeBackend, track: &TrackInfo) -> Option<usize> {
956    if backend.presentation_order() {
957        return Some(0);
958    }
959    track.video.as_ref().and_then(|video| video.reorder_depth)
960}
961
962/// The presentation slack `track`'s first timestamps show ([`alpha2_time::presentation_slack`]),
963/// read from `reader`, which is left at the track's start.
964fn scan_slack(
965    reader: &mut dyn ContainerReader,
966    track: &TrackInfo,
967) -> Result<MediaTime, DecodeError> {
968    let timestamps = first_timestamps(reader, track)?;
969    reader.seek(track.id, i64::MIN)?;
970    Ok(alpha2_time::presentation_slack(
971        1,
972        i64::from(track.timescale.max(1)),
973        alpha2_time::rounding_quantum(&timestamps),
974    ))
975}
976
977/// The presentation times of `track`'s first packets (up to [`alpha2_time::ROUNDING_SCAN_FRAMES`]
978/// or [`alpha2_time::ROUNDING_SCAN_BYTES`]), read from `reader`, which the caller seeks back.
979pub(crate) fn first_timestamps(
980    reader: &mut dyn ContainerReader,
981    track: &TrackInfo,
982) -> Result<Vec<i64>, DecodeError> {
983    let mut timestamps = Vec::with_capacity(alpha2_time::ROUNDING_SCAN_FRAMES);
984    let mut bytes = 0_u64;
985    while timestamps.len() < alpha2_time::ROUNDING_SCAN_FRAMES
986        && bytes < alpha2_time::ROUNDING_SCAN_BYTES
987    {
988        let Some(packet) = reader.next_packet(track.id)? else {
989            break;
990        };
991        bytes = bytes.saturating_add(packet.data.len() as u64);
992        timestamps.push(packet.pts);
993    }
994    Ok(timestamps)
995}
996
997/// `units` in a track of `timescale` units per second, as ticks rounded to nearest (half away
998/// from zero, as `FFmpeg`'s `av_rescale_q` rounds).
999#[must_use]
1000pub fn to_media_time(units: i64, timescale: u32) -> MediaTime {
1001    MediaTime::from_ticks(rescale(
1002        units,
1003        TICKS_PER_SECOND,
1004        i64::from(timescale.max(1)),
1005        false,
1006    ))
1007}
1008
1009fn rescale(value: i64, numerator: i64, denominator: i64, floor: bool) -> i64 {
1010    let product = i128::from(value) * i128::from(numerator);
1011    let denominator = i128::from(denominator);
1012    let scaled = if floor {
1013        product.div_euclid(denominator)
1014    } else {
1015        let half = denominator / 2;
1016        if product >= 0 {
1017            (product + half) / denominator
1018        } else {
1019            (product - half) / denominator
1020        }
1021    };
1022    i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX })
1023}
1024
1025fn codec_name(codec: VideoCodec) -> String {
1026    match codec {
1027        VideoCodec::H264 => "h264".into(),
1028        VideoCodec::Hevc => "hevc".into(),
1029        VideoCodec::Vp8 => "vp8".into(),
1030        VideoCodec::Vp9 => "vp9".into(),
1031        VideoCodec::Av1 => "av1".into(),
1032        VideoCodec::Mpeg4Part2 => "mpeg4".into(),
1033        VideoCodec::ProRes(_) => "prores".into(),
1034        VideoCodec::Other(fourcc) => fourcc.to_string(),
1035    }
1036}
1037
1038/// The CPU-frame decoder contract, for consumers and conformance tests that take
1039/// [`alpha2_media::Decoder`]. A surface frame is refused as unsupported here.
1040impl Decoder for VideoStream {
1041    fn streams(&self) -> &[StreamInfo] {
1042        &self.info
1043    }
1044
1045    fn flush(&mut self) -> Result<(), DecodeError> {
1046        let after = self.last_returned;
1047        self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
1048        match self.reset(None) {
1049            Ok(()) => {}
1050            Err(Interrupt::Decode(error)) => return Err(error),
1051            Err(Interrupt::Backend(error)) => self.replace_session(error)?,
1052        }
1053        self.resume_after = after;
1054        Ok(())
1055    }
1056
1057    fn seek(
1058        &mut self,
1059        request: DecodeRequest,
1060        cancel: &CancelToken,
1061    ) -> Result<DecodeResult, DecodeError> {
1062        let frame = VideoStream::seek(self, request.time, cancel)?;
1063        Ok(DecodeResult {
1064            request,
1065            event: DecodeEvent::Video(cpu_frame(&frame)?),
1066        })
1067    }
1068
1069    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
1070        Ok(match self.next(cancel)? {
1071            Some(frame) => DecodeEvent::Video(cpu_frame(&frame)?),
1072            None => DecodeEvent::EndOfStream,
1073        })
1074    }
1075}
1076
1077fn cpu_frame(frame: &StreamFrame) -> Result<DecodedVideoFrame, DecodeError> {
1078    frame.to_cpu().ok_or_else(|| {
1079        DecodeError::Unsupported(
1080            "the decoder produced a surface where CPU planes were asked".into(),
1081        )
1082    })
1083}
1084
1085#[cfg(test)]
1086#[path = "video_stream_tests.rs"]
1087mod tests;