alpha2-host-core 0.8.0

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
//! Frame-exact video decoding over a container reader and a platform decoder session.
//!
//! [`VideoStream`] owns the policy every native backend shares: a seek answers with the last frame
//! at or before the time plus the stream's presentation slack, found by decoding from the keyframe
//! before it (stepping back a keyframe at a time when every frame from that keyframe comes later);
//! sequential reads keep one frame of lookahead; frames a session emits in decode order are put
//! back in presentation order; a failing hardware session is replaced by a software one once, and
//! a session the system takes away is reopened where the stream was.

use std::sync::Arc;

use alpha2_container::{ContainerReader, Packet, TrackInfo, TrackKind, VideoCodec};
use alpha2_media::{
    CancelToken, ChromaLocation, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest,
    DecodeResult, DecodedVideoFrame, Decoder, Orientation, PixelFormat, Plane, Rect,
    SampleAspectRatio, SourceAlpha, StreamInfo, StreamKind, YuvFormat,
};
use alpha2_time::{MediaTime, TICKS_PER_SECOND};

use crate::parameter_sets::{CropWindow, ParameterSetCodec, Vui, sequence_facts};
use crate::recovery::{DecodeFailure, DecodePolicy, Recovery, WorkBudget};

/// Whether a decoder session runs on dedicated hardware.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackendKind {
    /// A hardware decoder.
    Hardware,
    /// A software decoder.
    Software,
}

/// Why a decoder session failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BackendError {
    /// The system took the session away (app backgrounded, codec reclaimed, device lost); a new
    /// session can continue.
    SessionLost(String),
    /// The session cannot decode this stream.
    Unsupported(String),
    /// The packet just submitted is damaged.
    Corrupt(String),
    /// A hardware session could not decode a picture.
    HardwarePicture(String),
    /// Anything else.
    Failed(String),
}

impl std::fmt::Display for BackendError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SessionLost(reason) => write!(formatter, "decoder session lost: {reason}"),
            Self::Unsupported(reason)
            | Self::Corrupt(reason)
            | Self::HardwarePicture(reason)
            | Self::Failed(reason) => write!(formatter, "{reason}"),
        }
    }
}

impl From<BackendError> for DecodeError {
    fn from(error: BackendError) -> Self {
        match error {
            BackendError::Unsupported(reason) => Self::Unsupported(reason),
            error => Self::Adapter(error.to_string()),
        }
    }
}

/// What a session did with a packet.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Submit {
    /// The packet is queued.
    Accepted,
    /// The session's input is full; receive pictures, then submit the same packet again.
    Busy,
}

/// A decoded picture that stays on the platform's surface until the lease drops.
pub trait SurfaceLease: std::fmt::Debug + Send + Sync + 'static {
    /// Bytes the surface holds, charged to the frame budget.
    fn retained_bytes(&self) -> u64;

    /// Lets the platform importer recover its own lease type.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// A decoded picture's pixels.
#[derive(Clone, Debug)]
pub enum BackendImage {
    /// Planes in memory.
    Cpu {
        /// Their layout.
        format: YuvFormat,
        /// Luma, then chroma (one interleaved or two planar), then alpha.
        planes: Vec<Plane>,
    },
    /// A platform surface the renderer imports.
    Surface(Arc<dyn SurfaceLease>),
}

/// One picture a session produced, with what the session knows about it.
#[derive(Clone, Debug)]
pub struct BackendFrame {
    /// The presentation time of the packet it came from, in the track's timescale.
    pub pts: i64,
    /// Its pixels.
    pub image: BackendImage,
    /// The width and height of the image's buffer.
    pub coded: (u32, u32),
    /// The visible area, when the session applied or reported the crop.
    pub visible: Option<Rect>,
    /// The pixel aspect ratio the bitstream signals, when the session reports it.
    pub sample_aspect_ratio: Option<SampleAspectRatio>,
    /// The color the bitstream signals, when the session reports it.
    pub color: Option<ColorMetadata>,
    /// The chroma siting the bitstream signals; `None` when it signals none.
    pub chroma_location: Option<ChromaLocation>,
}

/// What a session had on a receive.
#[derive(Debug)]
pub enum Poll {
    /// A picture.
    Frame(BackendFrame),
    /// Nothing yet; submit more input.
    Pending,
    /// Input ended and every picture was given.
    Drained,
}

/// One decoder session for one video track, used from one thread at a time.
pub trait VideoDecodeBackend: Send {
    /// Whether it runs on hardware.
    fn kind(&self) -> BackendKind;

    /// Queues a packet for decoding.
    ///
    /// # Errors
    /// A lost session, a damaged packet, or a failed decoder.
    fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError>;

    /// Takes a decoded picture, in decode order or, when [`Self::presentation_order`], in
    /// presentation order. With `wait`, blocks briefly for one: the session refused input, or
    /// input ended.
    ///
    /// # Errors
    /// A lost session, an undecodable picture, or a failed decoder.
    fn receive(&mut self, wait: bool) -> Result<Poll, BackendError>;

    /// Whether pictures come out in presentation order, so the stream holds none back to reorder
    /// them. Sessions that emit decode order keep the default.
    fn presentation_order(&self) -> bool {
        false
    }

    /// No more packets follow until a [`Self::flush`]; receives then drain the session.
    ///
    /// # Errors
    /// A lost session or a failed decoder.
    fn finish_input(&mut self) -> Result<(), BackendError>;

    /// Drops every queued packet and picture, ready for packets from a keyframe.
    ///
    /// # Errors
    /// A lost session or a failed decoder.
    fn flush(&mut self) -> Result<(), BackendError>;
}

/// Opens decoder sessions for tracks.
pub trait VideoBackends: Send + Sync {
    /// A session of `kind` for `track`.
    ///
    /// # Errors
    /// [`BackendError::Unsupported`] when no decoder of that kind reads the track.
    fn open(
        &self,
        track: &TrackInfo,
        kind: BackendKind,
    ) -> Result<Box<dyn VideoDecodeBackend>, BackendError>;
}

/// What the bitstream's configuration declares beyond the container, which hardware sessions
/// do not report reliably.
#[derive(Clone, Copy, Debug, Default)]
struct Bitstream {
    vui: Vui,
    chroma_location: Option<ChromaLocation>,
}

/// The chroma siting an `av1C` record's `chroma_sample_position` declares.
fn av1_chroma_location(record: &[u8]) -> Option<ChromaLocation> {
    match record.get(2)? & 3 {
        1 => Some(ChromaLocation::Left),
        2 => Some(ChromaLocation::TopLeft),
        _ => None,
    }
}

/// Which sessions a stream may use.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DecodePreference {
    /// Hardware, then software once when hardware fails.
    #[default]
    Auto,
    /// Hardware only.
    Hardware,
    /// Software only.
    Software,
}

/// How a [`VideoStream`] is opened.
#[derive(Clone, Copy, Debug, Default)]
pub struct StreamOptions {
    /// Which sessions it may use.
    pub preference: DecodePreference,
    /// How damaged input is handled.
    pub policy: DecodePolicy,
    /// The color the project declares for the source, which every frame then carries.
    pub declared_color: Option<ColorMetadata>,
}

/// The facts every frame carries besides its pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameFacts {
    /// Presentation time.
    pub pts: MediaTime,
    /// The visible area in buffer pixels.
    pub visible_rect: Rect,
    /// How the picture is shown.
    pub orientation: Orientation,
    /// Pixel aspect ratio.
    pub sample_aspect_ratio: SampleAspectRatio,
    /// Chroma siting.
    pub chroma_location: ChromaLocation,
    /// Color, when declared or tagged.
    pub color: Option<ColorMetadata>,
}

/// A decoded frame of a [`VideoStream`].
#[derive(Clone, Debug)]
pub struct StreamFrame {
    /// Its facts.
    pub facts: FrameFacts,
    /// Its pixels.
    pub image: BackendImage,
}

impl StreamFrame {
    /// Bytes the frame holds: its planes, or what its surface retains.
    #[must_use]
    pub fn retained_bytes(&self) -> u64 {
        match &self.image {
            BackendImage::Cpu { planes, .. } => {
                planes.iter().map(|plane| plane.bytes.len() as u64).sum()
            }
            BackendImage::Surface(lease) => lease.retained_bytes(),
        }
    }

    /// The frame as a CPU frame; `None` for a surface.
    #[must_use]
    pub fn to_cpu(&self) -> Option<DecodedVideoFrame> {
        let BackendImage::Cpu { format, planes } = &self.image else {
            return None;
        };
        Some(DecodedVideoFrame {
            pts: self.facts.pts,
            dts: None,
            duration: None,
            visible_rect: self.facts.visible_rect,
            sample_aspect_ratio: self.facts.sample_aspect_ratio,
            orientation: self.facts.orientation,
            pixel_format: PixelFormat::Yuv(*format),
            chroma_location: self.facts.chroma_location,
            color: self.facts.color,
            planes: planes.clone(),
        })
    }
}

/// Puts pictures a session emits in decode order back in presentation order.
///
/// With a reorder depth (pictures that may precede any picture in decode order and follow it in
/// presentation order), the earliest held picture is released once more than that many are held:
/// a later picture would follow every held one in decode order and precede it in presentation
/// order, exceeding the depth. Without one, held pictures are released once a picture arrives no
/// earlier than all of them, which is exact for streams that reorder at most one picture deep.
#[derive(Debug, Default)]
pub struct ReorderBuffer {
    depth: Option<usize>,
    arriving: Vec<BackendFrame>,
    ready: std::collections::VecDeque<BackendFrame>,
}

impl ReorderBuffer {
    /// An empty buffer for a stream reordered at most `depth` pictures deep; `None` when unknown.
    #[must_use]
    pub fn new(depth: Option<usize>) -> Self {
        Self {
            depth,
            ..Self::default()
        }
    }

    /// Takes a picture from the session.
    pub fn arrive(&mut self, frame: BackendFrame) {
        if self.depth.is_none()
            && self
                .arriving
                .last()
                .is_some_and(|latest| frame.pts >= latest.pts)
        {
            self.ready.extend(self.arriving.drain(..));
        }
        let at = self
            .arriving
            .iter()
            .position(|held| held.pts > frame.pts)
            .unwrap_or(self.arriving.len());
        self.arriving.insert(at, frame);
        if let Some(depth) = self.depth {
            let excess = self.arriving.len().saturating_sub(depth);
            self.ready.extend(self.arriving.drain(..excess));
        }
    }

    /// The session drained: every held picture is released.
    pub fn drain(&mut self) {
        self.ready.extend(self.arriving.drain(..));
    }

    /// The next picture in presentation order, once it is certain.
    pub fn take(&mut self) -> Option<BackendFrame> {
        self.ready.pop_front()
    }

    /// Drops everything.
    pub fn clear(&mut self) {
        self.arriving.clear();
        self.ready.clear();
    }

    /// Pictures held now.
    #[must_use]
    pub fn len(&self) -> usize {
        self.arriving.len() + self.ready.len()
    }

    /// Whether nothing is held.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Sessions the system may take from one stream in a row, with no frame decoded between them,
/// before its decode fails.
const MAX_SESSION_REOPENS: u32 = 3;

/// Where a session's input stands.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Input {
    /// Packets go in.
    Open,
    /// The session refused the pending packet until it outputs.
    Full,
    /// Every packet is in; the session drains.
    Ended,
    /// The session gave its last picture.
    Drained,
}

/// Why decoding stopped: a session to replace, or a failure for the caller.
enum Interrupt {
    Backend(BackendError),
    Decode(DecodeError),
}

impl From<DecodeError> for Interrupt {
    fn from(error: DecodeError) -> Self {
        Self::Decode(error)
    }
}

impl From<alpha2_container::DemuxError> for Interrupt {
    fn from(error: alpha2_container::DemuxError) -> Self {
        Self::Decode(error.into())
    }
}

/// Something a stream's pictures go without (they still decode), for reports.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DroppedLayer {
    /// `alpha-dropped`, the code the desktop host reports too.
    pub code: &'static str,
    /// Why, for people.
    pub reason: String,
}

/// The alpha a track declares, which the platform sessions decode opaque.
fn dropped_alpha(video: &alpha2_container::VideoTrack) -> Option<(SourceAlpha, DroppedLayer)> {
    if !video.alpha {
        return None;
    }
    let (alpha, reason) = match video.codec {
        VideoCodec::Vp9 => (
            SourceAlpha::Vp9SideData,
            "VP9 alpha in block additions is not decoded on this platform",
        ),
        VideoCodec::Hevc => (
            SourceAlpha::HevcAuxiliaryLayer,
            "alpha in an HEVC auxiliary layer is not decoded",
        ),
        _ => (
            SourceAlpha::Planar,
            "the alpha plane is not decoded on this platform",
        ),
    };
    let dropped = DroppedLayer {
        code: "alpha-dropped",
        reason: reason.into(),
    };
    Some((alpha, dropped))
}

/// A video track decoded frame-exactly.
pub struct VideoStream {
    reader: Box<dyn ContainerReader>,
    track: TrackInfo,
    backends: Arc<dyn VideoBackends>,
    backend: Box<dyn VideoDecodeBackend>,
    options: StreamOptions,
    software_fallback_used: bool,
    reopens: u32,
    recovery: Recovery,
    reorder: ReorderBuffer,
    lookahead: Option<StreamFrame>,
    pending: Option<Packet>,
    input: Input,
    /// The last frame handed out, which a replacement session decodes past.
    last_returned: Option<i64>,
    /// Frames at or before this time are dropped: they were handed out by a lost session.
    resume_after: Option<i64>,
    /// The stream's first keyframe, where a seek cannot step back from.
    first_keyframe: Option<i64>,
    slack: MediaTime,
    crop: Option<CropWindow>,
    bitstream: Bitstream,
    info: Vec<StreamInfo>,
    dropped: Option<DroppedLayer>,
}

impl std::fmt::Debug for VideoStream {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("VideoStream")
            .field("track", &self.track.id)
            .field("backend", &self.backend.kind())
            .finish_non_exhaustive()
    }
}

impl VideoStream {
    /// Opens track `index` of `reader` with a session from `backends`.
    ///
    /// # Errors
    /// [`DecodeError::Unsupported`] for a track that is not video or that no allowed session
    /// reads.
    pub fn open(
        mut reader: Box<dyn ContainerReader>,
        index: usize,
        backends: Arc<dyn VideoBackends>,
        options: StreamOptions,
    ) -> Result<Self, DecodeError> {
        let track =
            reader.tracks().get(index).cloned().ok_or_else(|| {
                DecodeError::Unsupported(format!("the file has no track {index}"))
            })?;
        let Some(video) = track.video.clone() else {
            return Err(DecodeError::Unsupported(format!(
                "track {} is not video",
                track.id.0
            )));
        };
        let sequence = match video.codec {
            VideoCodec::H264 => sequence_facts(ParameterSetCodec::H264, &video.codec_private),
            VideoCodec::Hevc => sequence_facts(ParameterSetCodec::Hevc, &video.codec_private),
            _ => None,
        };
        let crop = sequence.map(|facts| facts.crop);
        let bitstream = Bitstream {
            vui: sequence.map(|facts| facts.vui).unwrap_or_default(),
            chroma_location: match video.codec {
                VideoCodec::Av1 => av1_chroma_location(&video.codec_private),
                _ => sequence.and_then(|facts| facts.chroma_location()),
            },
        };
        let first = match options.preference {
            DecodePreference::Software => BackendKind::Software,
            DecodePreference::Auto | DecodePreference::Hardware => BackendKind::Hardware,
        };
        let (backend, software_fallback_used) = match backends.open(&track, first) {
            Ok(backend) => (backend, false),
            Err(hardware) if options.preference == DecodePreference::Auto => {
                let software = backends.open(&track, BackendKind::Software).map_err(|software| {
                    DecodeError::Unsupported(format!(
                        "no decoder here reads this stream (hardware: {hardware}; software: {software})"
                    ))
                })?;
                (software, true)
            }
            Err(error) => return Err(error.into()),
        };
        let first_keyframe = reader.seek(track.id, i64::MIN)?;
        let timescale = i64::from(track.timescale.max(1));
        let slack = scan_slack(reader.as_mut(), &track)?;
        let mut recovery = Recovery::new((1, i32::try_from(timescale).unwrap_or(i32::MAX)));
        recovery.policy = options.policy;
        recovery.set_hardware(backend.kind() == BackendKind::Hardware);
        let dimensions = crop
            .and_then(|crop| crop.visible())
            .map_or((video.width, video.height), |rect| {
                (rect.width, rect.height)
            });
        let reorder = ReorderBuffer::new(reorder_depth(backend.as_ref(), &track));
        let (alpha, dropped) = dropped_alpha(&video).unzip();
        let info = vec![StreamInfo {
            index,
            kind: StreamKind::Video,
            codec: codec_name(video.codec),
            duration: track
                .duration
                .map(|duration| to_media_time(duration, track.timescale)),
            dimensions: Some(dimensions),
            frame_rate: video.frame_rate,
            sample_rate: None,
            channels: None,
            orientation: video.orientation,
            sample_aspect_ratio: video
                .sample_aspect_ratio
                .or(bitstream.vui.sample_aspect_ratio)
                .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
            color: options
                .declared_color
                .or(video.color)
                .or(bitstream.vui.color),
            frame_bytes: None,
            alpha,
            language: track.language.clone(),
            title: track.title.clone(),
        }];
        Ok(Self {
            reader,
            backends,
            backend,
            options,
            software_fallback_used,
            reopens: 0,
            recovery,
            reorder,
            lookahead: None,
            pending: None,
            input: Input::Open,
            last_returned: None,
            resume_after: None,
            first_keyframe,
            slack,
            crop,
            bitstream,
            info,
            dropped,
            track,
        })
    }

    /// Opens the default video track of the file at `path`.
    ///
    /// # Errors
    /// [`DecodeError::Unsupported`] for a container this layer does not read, a file without
    /// video, or a track no allowed session reads; read failures.
    pub fn open_file(
        path: &std::path::Path,
        backends: Arc<dyn VideoBackends>,
        options: StreamOptions,
    ) -> Result<Self, DecodeError> {
        let reader = alpha2_container::open(path)?;
        let index = alpha2_container::default_track(reader.tracks(), TrackKind::Video)
            .ok_or_else(|| DecodeError::Unsupported("the file has no video track".into()))?;
        Self::open(reader, index, backends, options)
    }

    /// The track decoded.
    #[must_use]
    pub const fn track(&self) -> &TrackInfo {
        &self.track
    }

    /// What the track declares that its pictures go without: the alpha of a track that has one.
    #[must_use]
    pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
        self.dropped.as_ref()
    }

    /// Bytes of the frame decoded ahead and kept for the next [`Self::next`].
    #[must_use]
    pub fn lookahead_bytes(&self) -> u64 {
        self.lookahead
            .as_ref()
            .map_or(0, StreamFrame::retained_bytes)
    }

    /// How far after a time a frame may be stored and still be the one shown at it.
    #[must_use]
    pub const fn presentation_slack(&self) -> MediaTime {
        self.slack
    }

    /// Whether the session open now runs on hardware.
    #[must_use]
    pub fn on_hardware(&self) -> bool {
        self.backend.kind() == BackendKind::Hardware
    }

    /// Damage recorded so far.
    #[must_use]
    pub const fn recovery(&self) -> &Recovery {
        &self.recovery
    }

    /// The next frame in presentation order; `None` at the end.
    ///
    /// # Errors
    /// Cancellation, a spent work budget, damage beyond the policy, or a decoder failure no
    /// replacement session survives.
    pub fn next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
        let frame = match self.lookahead.take() {
            Some(frame) => Some(frame),
            None => self.decode_next(cancel)?,
        };
        if let Some(frame) = &frame {
            self.last_returned = Some(self.track_units(frame.facts.pts));
        }
        Ok(frame)
    }

    /// When the frame [`Self::next`] returns is presented; `None` at the end. The frame is decoded
    /// now and kept.
    ///
    /// # Errors
    /// As [`Self::next`].
    pub fn peek_pts(&mut self, cancel: &CancelToken) -> Result<Option<MediaTime>, DecodeError> {
        if self.lookahead.is_none() {
            self.lookahead = self.decode_next(cancel)?;
        }
        Ok(self.lookahead.as_ref().map(|frame| frame.facts.pts))
    }

    /// The frame shown at `time`: the last at or before `time` plus the slack, the first for an
    /// earlier time and the last for a later one. The frame after it becomes the lookahead.
    ///
    /// # Errors
    /// [`DecodeError::OutOfRange`] for a stream without frames; otherwise as [`Self::next`].
    pub fn seek(
        &mut self,
        time: MediaTime,
        cancel: &CancelToken,
    ) -> Result<StreamFrame, DecodeError> {
        loop {
            match self.seek_once(time, cancel) {
                Ok(frame) => {
                    self.last_returned = Some(self.track_units(frame.facts.pts));
                    return Ok(frame);
                }
                Err(Interrupt::Decode(error)) => return Err(error),
                Err(Interrupt::Backend(error)) => self.replace_session(error)?,
            }
        }
    }

    fn seek_once(
        &mut self,
        time: MediaTime,
        cancel: &CancelToken,
    ) -> Result<StreamFrame, Interrupt> {
        self.resume_after = None;
        let deadline = time.presentation_deadline(self.slack);
        let mut target = self.track_units_floor(deadline);
        let mut keyframe = self.reader.seek(self.track.id, target)?;
        let first = loop {
            self.reset(None)?;
            let Some(first) = self.decode_raw(cancel)? else {
                return Err(DecodeError::OutOfRange.into());
            };
            let at_start = keyframe.is_none() || keyframe <= self.first_keyframe;
            if first.facts.pts <= deadline || at_start {
                break first;
            }
            // Every frame from this keyframe comes later (leading frames of an open GOP, or an
            // index by decode time): decode from the keyframe before it.
            let landed = keyframe;
            let mut step = 1_i64;
            while keyframe == landed && target > i64::MIN {
                target = target.min(landed.unwrap_or(target)).saturating_sub(step);
                keyframe = self.reader.seek(self.track.id, target)?;
                step = step.saturating_mul(2);
            }
        };
        let mut shown = first;
        loop {
            match self.decode_raw(cancel)? {
                Some(frame) if frame.facts.pts <= deadline => shown = frame,
                Some(frame) => {
                    self.lookahead = Some(frame);
                    break;
                }
                None => break,
            }
        }
        Ok(shown)
    }

    fn decode_next(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, DecodeError> {
        loop {
            match self.decode_raw(cancel) {
                Ok(frame) => return Ok(frame),
                Err(Interrupt::Decode(error)) => return Err(error),
                Err(Interrupt::Backend(error)) => {
                    self.replace_session(error)?;
                    self.resume().map_err(|interrupt| match interrupt {
                        Interrupt::Decode(error) => error,
                        Interrupt::Backend(error) => error.into(),
                    })?;
                }
            }
        }
    }

    /// Decodes until the next frame in presentation order is certain.
    fn decode_raw(&mut self, cancel: &CancelToken) -> Result<Option<StreamFrame>, Interrupt> {
        let mut budget = WorkBudget::new();
        loop {
            if let Some(picture) = self.reorder.take() {
                let frame = self.facts(picture);
                let pts = self.track_units(frame.facts.pts);
                // A frame dropped on the way back to the resume point is progress too.
                budget.progressed();
                if self.resume_after.is_some_and(|after| pts <= after) {
                    continue;
                }
                self.resume_after = None;
                self.reopens = 0;
                self.recovery.progress(Some(pts))?;
                return Ok(Some(frame));
            }
            if self.input == Input::Drained {
                if self.recovery.diagnostics.corrupt_packets.is_empty() {
                    return Ok(None);
                }
                self.recovery.video_eof()?;
                return Ok(None);
            }
            budget.step(cancel)?;
            if self.step()? {
                budget.advanced();
            }
        }
    }

    /// One receive, or one packet in; `true` when a packet was read or accepted.
    fn step(&mut self) -> Result<bool, Interrupt> {
        match self.backend.receive(self.input != Input::Open) {
            Ok(Poll::Frame(picture)) => {
                if self.input == Input::Full {
                    self.input = Input::Open;
                }
                self.reorder.arrive(picture);
                return Ok(false);
            }
            Ok(Poll::Drained) => {
                self.reorder.drain();
                self.input = Input::Drained;
                return Ok(false);
            }
            Ok(Poll::Pending) => {}
            Err(BackendError::HardwarePicture(reason))
                if self
                    .recovery
                    .counts_as_damage(DecodeFailure::HardwarePicture) =>
            {
                self.recovery
                    .corrupt_with_detail("video receive", None, Some(reason))?;
                return Ok(false);
            }
            Err(error) => return Err(Interrupt::Backend(error)),
        }
        if matches!(self.input, Input::Ended | Input::Drained) {
            return Ok(false);
        }
        let mut advanced = false;
        if self.pending.is_none() {
            if let Some(packet) = self.reader.next_packet(self.track.id)? {
                self.pending = Some(packet);
                advanced = true;
            } else {
                self.backend.finish_input().map_err(Interrupt::Backend)?;
                self.input = Input::Ended;
                return Ok(false);
            }
        }
        let Some(packet) = self.pending.as_ref() else {
            return Ok(advanced);
        };
        match self.backend.submit(packet) {
            Ok(Submit::Accepted) => {
                self.pending = None;
                self.input = Input::Open;
                advanced = true;
            }
            Ok(Submit::Busy) => self.input = Input::Full,
            Err(BackendError::Corrupt(reason))
                if self.recovery.counts_as_damage(DecodeFailure::InvalidData) =>
            {
                let pts = packet.pts;
                self.pending = None;
                self.recovery
                    .corrupt_with_detail("video send", Some(pts), Some(reason))?;
            }
            Err(error) => return Err(Interrupt::Backend(error)),
        }
        Ok(advanced)
    }

    /// Empties the session and the queues, keeping `lookahead`.
    fn reset(&mut self, lookahead: Option<StreamFrame>) -> Result<(), Interrupt> {
        self.reorder.clear();
        self.lookahead = lookahead;
        self.pending = None;
        self.input = Input::Open;
        self.recovery.reset_progress();
        self.backend.flush().map_err(Interrupt::Backend)
    }

    /// Opens the session that continues after `error`, or fails with it.
    fn replace_session(&mut self, error: BackendError) -> Result<(), DecodeError> {
        let kind = match &error {
            BackendError::SessionLost(_) if self.reopens < MAX_SESSION_REOPENS => {
                self.reopens += 1;
                self.backend.kind()
            }
            BackendError::Unsupported(_)
            | BackendError::Failed(_)
            | BackendError::Corrupt(_)
            | BackendError::HardwarePicture(_)
                if self.backend.kind() == BackendKind::Hardware
                    && self.options.preference == DecodePreference::Auto
                    && !self.software_fallback_used =>
            {
                self.software_fallback_used = true;
                BackendKind::Software
            }
            _ => return Err(error.into()),
        };
        self.backend = self.backends.open(&self.track, kind).map_err(|reopen| {
            DecodeError::Adapter(format!("{error}; no session replaces it: {reopen}"))
        })?;
        self.reorder = ReorderBuffer::new(reorder_depth(self.backend.as_ref(), &self.track));
        self.recovery
            .set_hardware(self.backend.kind() == BackendKind::Hardware);
        Ok(())
    }

    /// Positions a new session after the last frame handed out.
    fn resume(&mut self) -> Result<(), Interrupt> {
        let lookahead = self.lookahead.take();
        let after = lookahead
            .as_ref()
            .map(|frame| self.track_units(frame.facts.pts))
            .or(self.last_returned);
        self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
        self.reset(lookahead)?;
        self.resume_after = after;
        Ok(())
    }

    fn facts(&self, picture: BackendFrame) -> StreamFrame {
        let video = self.track.video.as_ref();
        let whole = Rect {
            x: 0,
            y: 0,
            width: picture.coded.0,
            height: picture.coded.1,
        };
        // A buffer of the SPS's coded size shows the SPS's window: some sessions report the whole
        // buffer as visible, and some apply no crop at all. A buffer of the window's size was
        // cropped already. Any other buffer (a stream whose SPS changed in band) is the session's.
        let window = self.crop.and_then(|crop| {
            let visible = crop.visible()?;
            if picture.coded == (crop.coded_width, crop.coded_height) {
                Some(visible)
            } else if picture.coded == (visible.width, visible.height) {
                Some(whole)
            } else {
                None
            }
        });
        let visible = window.or(picture.visible).unwrap_or(whole);
        let chroma_location = picture
            .chroma_location
            .or(self.bitstream.chroma_location)
            .unwrap_or(ChromaLocation::Unspecified);
        StreamFrame {
            facts: FrameFacts {
                pts: to_media_time(picture.pts, self.track.timescale),
                visible_rect: visible,
                orientation: video.map(|video| video.orientation).unwrap_or_default(),
                sample_aspect_ratio: video
                    .and_then(|video| video.sample_aspect_ratio)
                    .or(self.bitstream.vui.sample_aspect_ratio)
                    .or(picture.sample_aspect_ratio)
                    .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
                chroma_location,
                color: self
                    .options
                    .declared_color
                    .or_else(|| video.and_then(|video| video.color))
                    .or(self.bitstream.vui.color)
                    .or(picture.color),
            },
            image: picture.image,
        }
    }

    /// `time` in the track's units, rounded to nearest.
    fn track_units(&self, time: MediaTime) -> i64 {
        rescale(
            time.ticks(),
            i64::from(self.track.timescale.max(1)),
            TICKS_PER_SECOND,
            false,
        )
    }

    /// `time` in the track's units, rounded down.
    fn track_units_floor(&self, time: MediaTime) -> i64 {
        rescale(
            time.ticks(),
            i64::from(self.track.timescale.max(1)),
            TICKS_PER_SECOND,
            true,
        )
    }
}

/// How deep `track`'s pictures arrive out of presentation order from `backend`.
fn reorder_depth(backend: &dyn VideoDecodeBackend, track: &TrackInfo) -> Option<usize> {
    if backend.presentation_order() {
        return Some(0);
    }
    track.video.as_ref().and_then(|video| video.reorder_depth)
}

/// The presentation slack `track`'s first timestamps show ([`alpha2_time::presentation_slack`]),
/// read from `reader`, which is left at the track's start.
fn scan_slack(
    reader: &mut dyn ContainerReader,
    track: &TrackInfo,
) -> Result<MediaTime, DecodeError> {
    let timestamps = first_timestamps(reader, track)?;
    reader.seek(track.id, i64::MIN)?;
    Ok(alpha2_time::presentation_slack(
        1,
        i64::from(track.timescale.max(1)),
        alpha2_time::rounding_quantum(&timestamps),
    ))
}

/// The presentation times of `track`'s first packets (up to [`alpha2_time::ROUNDING_SCAN_FRAMES`]
/// or [`alpha2_time::ROUNDING_SCAN_BYTES`]), read from `reader`, which the caller seeks back.
pub(crate) fn first_timestamps(
    reader: &mut dyn ContainerReader,
    track: &TrackInfo,
) -> Result<Vec<i64>, DecodeError> {
    let mut timestamps = Vec::with_capacity(alpha2_time::ROUNDING_SCAN_FRAMES);
    let mut bytes = 0_u64;
    while timestamps.len() < alpha2_time::ROUNDING_SCAN_FRAMES
        && bytes < alpha2_time::ROUNDING_SCAN_BYTES
    {
        let Some(packet) = reader.next_packet(track.id)? else {
            break;
        };
        bytes = bytes.saturating_add(packet.data.len() as u64);
        timestamps.push(packet.pts);
    }
    Ok(timestamps)
}

/// `units` in a track of `timescale` units per second, as ticks rounded to nearest (half away
/// from zero, as `FFmpeg`'s `av_rescale_q` rounds).
#[must_use]
pub fn to_media_time(units: i64, timescale: u32) -> MediaTime {
    MediaTime::from_ticks(rescale(
        units,
        TICKS_PER_SECOND,
        i64::from(timescale.max(1)),
        false,
    ))
}

fn rescale(value: i64, numerator: i64, denominator: i64, floor: bool) -> i64 {
    let product = i128::from(value) * i128::from(numerator);
    let denominator = i128::from(denominator);
    let scaled = if floor {
        product.div_euclid(denominator)
    } else {
        let half = denominator / 2;
        if product >= 0 {
            (product + half) / denominator
        } else {
            (product - half) / denominator
        }
    };
    i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX })
}

fn codec_name(codec: VideoCodec) -> String {
    match codec {
        VideoCodec::H264 => "h264".into(),
        VideoCodec::Hevc => "hevc".into(),
        VideoCodec::Vp8 => "vp8".into(),
        VideoCodec::Vp9 => "vp9".into(),
        VideoCodec::Av1 => "av1".into(),
        VideoCodec::Mpeg4Part2 => "mpeg4".into(),
        VideoCodec::ProRes(_) => "prores".into(),
        VideoCodec::Other(fourcc) => fourcc.to_string(),
    }
}

/// The CPU-frame decoder contract, for consumers and conformance tests that take
/// [`alpha2_media::Decoder`]. A surface frame is refused as unsupported here.
impl Decoder for VideoStream {
    fn streams(&self) -> &[StreamInfo] {
        &self.info
    }

    fn flush(&mut self) -> Result<(), DecodeError> {
        let after = self.last_returned;
        self.reader.seek(self.track.id, after.unwrap_or(i64::MIN))?;
        match self.reset(None) {
            Ok(()) => {}
            Err(Interrupt::Decode(error)) => return Err(error),
            Err(Interrupt::Backend(error)) => self.replace_session(error)?,
        }
        self.resume_after = after;
        Ok(())
    }

    fn seek(
        &mut self,
        request: DecodeRequest,
        cancel: &CancelToken,
    ) -> Result<DecodeResult, DecodeError> {
        let frame = VideoStream::seek(self, request.time, cancel)?;
        Ok(DecodeResult {
            request,
            event: DecodeEvent::Video(cpu_frame(&frame)?),
        })
    }

    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
        Ok(match self.next(cancel)? {
            Some(frame) => DecodeEvent::Video(cpu_frame(&frame)?),
            None => DecodeEvent::EndOfStream,
        })
    }
}

fn cpu_frame(frame: &StreamFrame) -> Result<DecodedVideoFrame, DecodeError> {
    frame.to_cpu().ok_or_else(|| {
        DecodeError::Unsupported(
            "the decoder produced a surface where CPU planes were asked".into(),
        )
    })
}

#[cfg(test)]
#[path = "video_stream_tests.rs"]
mod tests;