1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub enum BackendKind {
26 Hardware,
28 Software,
30}
31
32#[derive(Clone, Debug, Eq, PartialEq)]
34pub enum BackendError {
35 SessionLost(String),
38 Unsupported(String),
40 Corrupt(String),
42 HardwarePicture(String),
44 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub enum Submit {
72 Accepted,
74 Busy,
76}
77
78pub trait SurfaceLease: std::fmt::Debug + Send + Sync + 'static {
80 fn retained_bytes(&self) -> u64;
82
83 fn as_any(&self) -> &dyn std::any::Any;
85}
86
87#[derive(Clone, Debug)]
89pub enum BackendImage {
90 Cpu {
92 format: YuvFormat,
94 planes: Vec<Plane>,
96 },
97 Surface(Arc<dyn SurfaceLease>),
99}
100
101#[derive(Clone, Debug)]
103pub struct BackendFrame {
104 pub pts: i64,
106 pub image: BackendImage,
108 pub coded: (u32, u32),
110 pub visible: Option<Rect>,
112 pub sample_aspect_ratio: Option<SampleAspectRatio>,
114 pub color: Option<ColorMetadata>,
116 pub chroma_location: Option<ChromaLocation>,
118}
119
120#[derive(Debug)]
122pub enum Poll {
123 Frame(BackendFrame),
125 Pending,
127 Drained,
129}
130
131pub trait VideoDecodeBackend: Send {
133 fn kind(&self) -> BackendKind;
135
136 fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError>;
141
142 fn receive(&mut self, wait: bool) -> Result<Poll, BackendError>;
149
150 fn presentation_order(&self) -> bool {
153 false
154 }
155
156 fn finish_input(&mut self) -> Result<(), BackendError>;
161
162 fn flush(&mut self) -> Result<(), BackendError>;
167}
168
169pub trait VideoBackends: Send + Sync {
171 fn open(
176 &self,
177 track: &TrackInfo,
178 kind: BackendKind,
179 ) -> Result<Box<dyn VideoDecodeBackend>, BackendError>;
180}
181
182#[derive(Clone, Copy, Debug, Default)]
185struct Bitstream {
186 vui: Vui,
187 chroma_location: Option<ChromaLocation>,
188}
189
190fn 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
201pub enum DecodePreference {
202 #[default]
204 Auto,
205 Hardware,
207 Software,
209}
210
211#[derive(Clone, Copy, Debug, Default)]
213pub struct StreamOptions {
214 pub preference: DecodePreference,
216 pub policy: DecodePolicy,
218 pub declared_color: Option<ColorMetadata>,
220}
221
222#[derive(Clone, Copy, Debug, PartialEq)]
224pub struct FrameFacts {
225 pub pts: MediaTime,
227 pub visible_rect: Rect,
229 pub orientation: Orientation,
231 pub sample_aspect_ratio: SampleAspectRatio,
233 pub chroma_location: ChromaLocation,
235 pub color: Option<ColorMetadata>,
237}
238
239#[derive(Clone, Debug)]
241pub struct StreamFrame {
242 pub facts: FrameFacts,
244 pub image: BackendImage,
246}
247
248impl StreamFrame {
249 #[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 #[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#[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 #[must_use]
298 pub fn new(depth: Option<usize>) -> Self {
299 Self {
300 depth,
301 ..Self::default()
302 }
303 }
304
305 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 pub fn drain(&mut self) {
329 self.ready.extend(self.arriving.drain(..));
330 }
331
332 pub fn take(&mut self) -> Option<BackendFrame> {
334 self.ready.pop_front()
335 }
336
337 pub fn clear(&mut self) {
339 self.arriving.clear();
340 self.ready.clear();
341 }
342
343 #[must_use]
345 pub fn len(&self) -> usize {
346 self.arriving.len() + self.ready.len()
347 }
348
349 #[must_use]
351 pub fn is_empty(&self) -> bool {
352 self.len() == 0
353 }
354}
355
356const MAX_SESSION_REOPENS: u32 = 3;
359
360#[derive(Clone, Copy, Debug, Eq, PartialEq)]
362enum Input {
363 Open,
365 Full,
367 Ended,
369 Drained,
371}
372
373enum 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#[derive(Clone, Debug, Eq, PartialEq)]
393pub struct DroppedLayer {
394 pub code: &'static str,
396 pub reason: String,
398}
399
400fn 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
426pub 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 last_returned: Option<i64>,
442 resume_after: Option<i64>,
444 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 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 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 #[must_use]
594 pub const fn track(&self) -> &TrackInfo {
595 &self.track
596 }
597
598 #[must_use]
600 pub const fn dropped_layer(&self) -> Option<&DroppedLayer> {
601 self.dropped.as_ref()
602 }
603
604 #[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 #[must_use]
614 pub const fn presentation_slack(&self) -> MediaTime {
615 self.slack
616 }
617
618 #[must_use]
620 pub fn on_hardware(&self) -> bool {
621 self.backend.kind() == BackendKind::Hardware
622 }
623
624 #[must_use]
626 pub const fn recovery(&self) -> &Recovery {
627 &self.recovery
628 }
629
630 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 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 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 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 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 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 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 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 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 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 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 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 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
954fn 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
962fn 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(×tamps),
974 ))
975}
976
977pub(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#[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
1038impl 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;