1use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::{error::Error, fmt};
9
10use alpha2_time::{FrameRate, MediaTime};
11
12use crate::{ColorMetadata, SourceId};
13
14#[derive(Copy, Clone, Debug, Eq, PartialEq)]
16pub struct Rect {
17 pub x: u32,
19 pub y: u32,
21 pub width: u32,
23 pub height: u32,
25}
26
27#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
32pub enum Rotation {
33 #[default]
35 Deg0,
36 Deg90,
38 Deg180,
40 Deg270,
42}
43
44impl Rotation {
45 #[must_use]
47 pub const fn quarter_turns(self) -> u32 {
48 match self {
49 Self::Deg0 => 0,
50 Self::Deg90 => 1,
51 Self::Deg180 => 2,
52 Self::Deg270 => 3,
53 }
54 }
55
56 #[must_use]
58 pub const fn from_quarter_turns(quarter_turns: i32) -> Self {
59 match quarter_turns.rem_euclid(4) {
60 0 => Self::Deg0,
61 1 => Self::Deg90,
62 2 => Self::Deg180,
63 _ => Self::Deg270,
64 }
65 }
66
67 #[must_use]
69 pub const fn swaps_axes(self) -> bool {
70 matches!(self, Self::Deg90 | Self::Deg270)
71 }
72}
73
74#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
81pub struct Orientation {
82 pub rotation: Rotation,
84 pub mirror: bool,
86}
87
88impl Orientation {
89 pub const UPRIGHT: Self = Self {
91 rotation: Rotation::Deg0,
92 mirror: false,
93 };
94
95 #[must_use]
97 pub const fn rotated(rotation: Rotation) -> Self {
98 Self {
99 rotation,
100 mirror: false,
101 }
102 }
103
104 #[must_use]
106 pub const fn from_exif(value: u16) -> Option<Self> {
107 let (rotation, mirror) = match value {
108 1 => (Rotation::Deg0, false),
109 2 => (Rotation::Deg0, true),
110 3 => (Rotation::Deg180, false),
111 4 => (Rotation::Deg180, true),
112 5 => (Rotation::Deg270, true),
113 6 => (Rotation::Deg90, false),
114 7 => (Rotation::Deg90, true),
115 8 => (Rotation::Deg270, false),
116 _ => return None,
117 };
118 Some(Self { rotation, mirror })
119 }
120
121 #[must_use]
123 pub const fn is_upright(self) -> bool {
124 matches!(self.rotation, Rotation::Deg0) && !self.mirror
125 }
126
127 #[must_use]
129 pub const fn displayed_size(self, width: u32, height: u32) -> (u32, u32) {
130 if self.rotation.swaps_axes() {
131 (height, width)
132 } else {
133 (width, height)
134 }
135 }
136}
137
138#[derive(Copy, Clone, Debug, Eq, PartialEq)]
140pub struct SampleAspectRatio {
141 pub num: u32,
143 pub den: u32,
145}
146
147impl Default for SampleAspectRatio {
148 fn default() -> Self {
149 Self { num: 1, den: 1 }
150 }
151}
152
153impl SampleAspectRatio {
154 #[must_use]
157 pub fn new(num: u64, den: u64) -> Option<Self> {
158 if num == 0 || den == 0 {
159 return None;
160 }
161 let divisor = greatest_common_divisor(num, den);
162 Some(Self {
163 num: u32::try_from(num / divisor).ok()?,
164 den: u32::try_from(den / divisor).ok()?,
165 })
166 }
167
168 #[must_use]
175 pub fn of_display(visible: (u32, u32), displayed: (u32, u32)) -> Option<Self> {
176 let [
177 visible_width,
178 visible_height,
179 displayed_width,
180 displayed_height,
181 ] = [visible.0, visible.1, displayed.0, displayed.1].map(u128::from);
182 if visible_width == 0
183 || visible_height == 0
184 || displayed_width == 0
185 || displayed_height == 0
186 {
187 return None;
188 }
189 let slack = |shown: u128, stored: u128| u128::from(shown != stored);
191 let width_slack = slack(displayed_width, visible_width);
192 let height_slack = slack(displayed_height, visible_height);
193 let low = (
196 (2 * displayed_width - width_slack) * visible_height,
197 (2 * displayed_height + height_slack) * visible_width,
198 );
199 let high = (
200 (2 * displayed_width + width_slack) * visible_height,
201 (2 * displayed_height - height_slack) * visible_width,
202 );
203 let (num, den) = simplest_fraction_between(low, high)?;
204 Self::new(u64::try_from(num).ok()?, u64::try_from(den).ok()?)
205 }
206
207 #[must_use]
210 pub fn square_pixel_size(self, width: u32, height: u32) -> (u32, u32) {
211 let stretch = |side: u32, by: u32, of: u32| {
212 let scaled =
213 (u64::from(side) * u64::from(by) * 2 + u64::from(of)) / (2 * u64::from(of));
214 u32::try_from(scaled).unwrap_or(u32::MAX)
215 };
216 if self.num == 0 || self.den == 0 {
217 return (width, height);
218 }
219 match self.num.cmp(&self.den) {
220 std::cmp::Ordering::Greater => (stretch(width, self.num, self.den), height),
221 std::cmp::Ordering::Less => (width, stretch(height, self.den, self.num)),
222 std::cmp::Ordering::Equal => (width, height),
223 }
224 }
225}
226
227fn simplest_fraction_between(low: (u128, u128), high: (u128, u128)) -> Option<(u128, u128)> {
229 let ((low_num, low_den), (high_num, high_den)) = (low, high);
230 if low_den == 0 || high_den == 0 || low_num * high_den > high_num * low_den {
231 return None;
232 }
233 let whole = low_num / low_den;
234 if whole * low_den == low_num {
235 return Some((whole, 1));
236 }
237 if (whole + 1) * high_den <= high_num {
238 return Some((whole + 1, 1));
239 }
240 let (num, den) = simplest_fraction_between(
243 (high_den, high_num - whole * high_den),
244 (low_den, low_num - whole * low_den),
245 )?;
246 Some((whole * num + den, num))
247}
248
249fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 {
250 while b != 0 {
251 (a, b) = (b, a % b);
252 }
253 a
254}
255
256#[derive(Copy, Clone, Debug, Eq, PartialEq)]
262#[non_exhaustive]
263pub enum PixelFormat {
264 Yuv(YuvFormat),
266 Rgba8,
268 Rgba8Premultiplied,
271 LinearRgbaF16,
275}
276
277#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
284pub struct YuvFormat {
285 pub chroma_shift_x: u8,
287 pub chroma_shift_y: u8,
289 pub bit_depth: u8,
291 pub interleaved_chroma: bool,
293 pub msb_aligned: bool,
296 pub alpha: bool,
298}
299
300impl YuvFormat {
301 pub const I420: Self = Self::planar(1, 1, 8);
303 pub const NV12: Self = Self {
305 interleaved_chroma: true,
306 ..Self::I420
307 };
308 pub const P010: Self = Self {
310 bit_depth: 10,
311 msb_aligned: true,
312 ..Self::NV12
313 };
314
315 #[must_use]
317 pub const fn planar(chroma_shift_x: u8, chroma_shift_y: u8, bit_depth: u8) -> Self {
318 Self {
319 chroma_shift_x,
320 chroma_shift_y,
321 bit_depth,
322 interleaved_chroma: false,
323 msb_aligned: false,
324 alpha: false,
325 }
326 }
327
328 #[must_use]
330 pub const fn with_alpha(self) -> Self {
331 Self {
332 alpha: true,
333 ..self
334 }
335 }
336
337 #[must_use]
340 pub const fn is_supported(self) -> bool {
341 self.bit_depth >= 8
342 && self.bit_depth <= 16
343 && self.chroma_shift_x <= 2
344 && self.chroma_shift_y <= 2
345 && (!self.msb_aligned || self.bit_depth > 8)
346 }
347
348 #[must_use]
350 pub const fn bytes_per_sample(self) -> u32 {
351 if self.bit_depth > 8 { 2 } else { 1 }
352 }
353
354 #[must_use]
356 pub const fn plane_count(self) -> usize {
357 self.color_plane_count() + if self.alpha { 1 } else { 0 }
358 }
359
360 #[must_use]
362 pub const fn color_plane_count(self) -> usize {
363 if self.interleaved_chroma { 2 } else { 3 }
364 }
365
366 #[must_use]
368 pub const fn chroma_size(self, width: u32, height: u32) -> (u32, u32) {
369 (
370 width.div_ceil(1 << self.chroma_shift_x),
371 height.div_ceil(1 << self.chroma_shift_y),
372 )
373 }
374}
375
376#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
378pub enum ChromaLocation {
379 #[default]
381 Unspecified,
382 Left,
384 Center,
386 TopLeft,
388}
389
390impl ChromaLocation {
391 #[must_use]
395 pub const fn resolved_for(self, format: YuvFormat) -> Self {
396 match self {
397 Self::Unspecified if format.chroma_shift_x > 0 && format.chroma_shift_y == 0 => {
398 Self::Left
399 }
400 other => other,
401 }
402 }
403}
404
405#[derive(Clone, Debug, Eq, PartialEq)]
409pub struct Plane {
410 pub bytes: bytes::Bytes,
412 pub stride: u32,
414 pub width: u32,
416 pub height: u32,
418}
419
420pub const MAX_FRAME_DIMENSION: u32 = 16_384;
422pub const MAX_FRAME_PIXELS: u64 = 67_108_864;
424
425#[must_use]
428pub const fn frame_size_supported(width: u32, height: u32) -> bool {
429 width <= MAX_FRAME_DIMENSION
430 && height <= MAX_FRAME_DIMENSION
431 && (width as u64) * (height as u64) <= MAX_FRAME_PIXELS
432}
433
434#[derive(Clone, Debug, PartialEq)]
436pub struct DecodedVideoFrame {
437 pub pts: MediaTime,
439 pub dts: Option<MediaTime>,
441 pub duration: Option<MediaTime>,
443 pub visible_rect: Rect,
445 pub sample_aspect_ratio: SampleAspectRatio,
447 pub orientation: Orientation,
449 pub pixel_format: PixelFormat,
451 pub chroma_location: ChromaLocation,
453 pub color: Option<ColorMetadata>,
456 pub planes: Vec<Plane>,
458}
459
460pub const MAX_AUDIO_CHANNELS: usize = 24;
463
464#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
469pub enum Speaker {
470 FrontLeft,
472 FrontRight,
474 FrontCenter,
476 LowFrequency,
478 BackLeft,
480 BackRight,
482 FrontLeftOfCenter,
484 FrontRightOfCenter,
486 BackCenter,
488 SideLeft,
490 SideRight,
492 TopCenter,
494 TopFrontLeft,
496 TopFrontCenter,
498 TopFrontRight,
500 TopBackLeft,
502 TopBackCenter,
504 TopBackRight,
506 DownmixLeft,
508 DownmixRight,
510 WideLeft,
512 WideRight,
514 SurroundDirectLeft,
516 SurroundDirectRight,
518 LowFrequency2,
520 TopSideLeft,
522 TopSideRight,
524 BottomFrontCenter,
526 BottomFrontLeft,
528 BottomFrontRight,
530 SideSurroundLeft,
532 SideSurroundRight,
534 TopSurroundLeft,
536 TopSurroundRight,
538 BinauralLeft,
540 BinauralRight,
542 Unnamed,
545}
546
547impl Speaker {
548 const TABLE: [(Self, &'static str, u32); 37] = [
551 (Self::FrontLeft, "FL", 0),
552 (Self::FrontRight, "FR", 1),
553 (Self::FrontCenter, "FC", 2),
554 (Self::LowFrequency, "LFE", 3),
555 (Self::BackLeft, "BL", 4),
556 (Self::BackRight, "BR", 5),
557 (Self::FrontLeftOfCenter, "FLC", 6),
558 (Self::FrontRightOfCenter, "FRC", 7),
559 (Self::BackCenter, "BC", 8),
560 (Self::SideLeft, "SL", 9),
561 (Self::SideRight, "SR", 10),
562 (Self::TopCenter, "TC", 11),
563 (Self::TopFrontLeft, "TFL", 12),
564 (Self::TopFrontCenter, "TFC", 13),
565 (Self::TopFrontRight, "TFR", 14),
566 (Self::TopBackLeft, "TBL", 15),
567 (Self::TopBackCenter, "TBC", 16),
568 (Self::TopBackRight, "TBR", 17),
569 (Self::DownmixLeft, "DL", 29),
570 (Self::DownmixRight, "DR", 30),
571 (Self::WideLeft, "WL", 31),
572 (Self::WideRight, "WR", 32),
573 (Self::SurroundDirectLeft, "SDL", 33),
574 (Self::SurroundDirectRight, "SDR", 34),
575 (Self::LowFrequency2, "LFE2", 35),
576 (Self::TopSideLeft, "TSL", 36),
577 (Self::TopSideRight, "TSR", 37),
578 (Self::BottomFrontCenter, "BFC", 38),
579 (Self::BottomFrontLeft, "BFL", 39),
580 (Self::BottomFrontRight, "BFR", 40),
581 (Self::SideSurroundLeft, "SSL", 41),
582 (Self::SideSurroundRight, "SSR", 42),
583 (Self::TopSurroundLeft, "TTL", 43),
584 (Self::TopSurroundRight, "TTR", 44),
585 (Self::BinauralLeft, "BIL", 61),
586 (Self::BinauralRight, "BIR", 62),
587 (Self::Unnamed, "UNK", 0x300),
588 ];
589
590 #[must_use]
592 pub fn name(self) -> &'static str {
593 Self::TABLE
594 .iter()
595 .find(|(speaker, _, _)| *speaker == self)
596 .map_or("UNK", |(_, name, _)| name)
597 }
598
599 #[must_use]
601 pub fn from_name(name: &str) -> Option<Self> {
602 Self::TABLE
603 .iter()
604 .find(|(_, known, _)| *known == name)
605 .map(|(speaker, _, _)| *speaker)
606 }
607
608 #[must_use]
610 pub fn ffmpeg_channel(self) -> u32 {
611 Self::TABLE
612 .iter()
613 .find(|(speaker, _, _)| *speaker == self)
614 .map_or(0x300, |(_, _, channel)| *channel)
615 }
616
617 #[must_use]
620 pub fn from_ffmpeg_channel(channel: i64) -> Self {
621 Self::TABLE
622 .iter()
623 .find(|(_, _, number)| i64::from(*number) == channel)
624 .map_or(Self::Unnamed, |(speaker, _, _)| *speaker)
625 }
626}
627
628#[derive(Copy, Clone, Eq, Hash, PartialEq)]
633pub struct SpeakerLayout {
634 speakers: [Speaker; MAX_AUDIO_CHANNELS],
635 count: u8,
636}
637
638impl std::fmt::Debug for SpeakerLayout {
639 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
640 formatter
641 .debug_list()
642 .entries(self.speakers().iter().map(|speaker| speaker.name()))
643 .finish()
644 }
645}
646
647impl SpeakerLayout {
648 pub const MONO: Self = Self::fixed(&[Speaker::FrontCenter]);
650 pub const STEREO: Self = Self::fixed(&[Speaker::FrontLeft, Speaker::FrontRight]);
652
653 const fn fixed(speakers: &[Speaker]) -> Self {
654 let mut layout = [Speaker::Unnamed; MAX_AUDIO_CHANNELS];
655 let mut index = 0;
656 while index < speakers.len() {
657 layout[index] = speakers[index];
658 index += 1;
659 }
660 #[allow(clippy::cast_possible_truncation)]
661 Self {
662 speakers: layout,
663 count: speakers.len() as u8,
664 }
665 }
666
667 #[must_use]
670 pub fn new(speakers: &[Speaker]) -> Option<Self> {
671 if speakers.is_empty() || speakers.len() > MAX_AUDIO_CHANNELS {
672 return None;
673 }
674 let mut layout = Self {
675 speakers: [Speaker::Unnamed; MAX_AUDIO_CHANNELS],
676 count: u8::try_from(speakers.len()).ok()?,
677 };
678 layout.speakers[..speakers.len()].copy_from_slice(speakers);
679 Some(layout)
680 }
681
682 #[must_use]
687 pub fn default_for(channels: usize) -> Option<Self> {
688 const SEVEN_ONE: u64 = 0x63f;
690 let mask: u64 = match channels {
691 1 => 0x4,
692 2 => 0x3,
693 3 => 0xb,
694 4 => 0x107,
695 5 => 0x37,
696 6 => 0x3f,
697 7 => 0x70f,
698 10 => 0x2_d60f,
699 12 => 0x2_d63f,
700 14 => 0x2_d6ff,
701 16 => 0x30_0002_d6ff,
702 24 => 0x1f8_0003_ffff,
703 8..=MAX_AUDIO_CHANNELS => SEVEN_ONE,
704 _ => return None,
705 };
706 let mut layout = Self::of_mask(mask)?;
707 layout.count = u8::try_from(channels).ok()?;
709 Some(layout)
710 }
711
712 fn of_mask(mask: u64) -> Option<Self> {
714 let speakers = (0..64_i64)
715 .filter(|bit| mask & (1 << bit) != 0)
716 .map(Speaker::from_ffmpeg_channel)
717 .collect::<Vec<_>>();
718 Self::new(&speakers)
719 }
720
721 #[must_use]
724 pub fn declared_or_default(speakers: &[Speaker]) -> Option<(Self, bool)> {
725 if speakers.iter().all(|speaker| *speaker == Speaker::Unnamed) {
726 return Self::default_for(speakers.len()).map(|layout| (layout, true));
727 }
728 Self::new(speakers).map(|layout| (layout, false))
729 }
730
731 #[must_use]
733 pub fn speakers(&self) -> &[Speaker] {
734 &self.speakers[..usize::from(self.count)]
735 }
736
737 #[must_use]
739 pub fn channels(&self) -> usize {
740 usize::from(self.count)
741 }
742
743 #[must_use]
746 pub fn describe(&self) -> String {
747 self.speakers()
748 .iter()
749 .map(|speaker| speaker.name())
750 .collect::<Vec<_>>()
751 .join("+")
752 }
753}
754
755#[derive(Clone, Debug, PartialEq)]
764pub struct AudioBlock {
765 pub start_sample: i64,
767 pub sample_rate: u32,
769 pub speakers: SpeakerLayout,
771 pub channels: Vec<Vec<f32>>,
773}
774
775impl AudioBlock {
776 #[must_use]
778 pub fn frames(&self) -> usize {
779 self.channels.first().map_or(0, Vec::len)
780 }
781
782 #[must_use]
784 pub fn end_sample(&self) -> i64 {
785 self.start_sample
786 .saturating_add(i64::try_from(self.frames()).unwrap_or(i64::MAX))
787 }
788
789 #[must_use]
791 pub fn start_time(&self) -> MediaTime {
792 MediaTime::from_ticks(sample_ticks_floor(self.start_sample, self.sample_rate))
793 }
794}
795
796#[must_use]
798pub fn sample_ticks_floor(sample: i64, sample_rate: u32) -> i64 {
799 let ticks = (i128::from(sample) * i128::from(alpha2_time::TICKS_PER_SECOND))
800 .div_euclid(i128::from(sample_rate.max(1)));
801 i64::try_from(ticks).unwrap_or(if ticks < 0 { i64::MIN } else { i64::MAX })
802}
803
804#[derive(Copy, Clone, Debug, Eq, PartialEq)]
806pub enum RasterColorSpace {
807 Srgb,
809 LinearSrgb,
811}
812
813#[derive(Copy, Clone, Debug, Eq, PartialEq)]
815pub enum Premultiplication {
816 Premultiplied,
818 Straight,
820 Opaque,
822}
823
824#[derive(Clone, Debug, Eq, PartialEq)]
826pub struct HostTexture {
827 pub content_version: u64,
829 pub width: u32,
831 pub height: u32,
833 pub premultiplication: Premultiplication,
835 pub color_space: RasterColorSpace,
837}
838
839#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
841pub enum TextAlign {
842 #[default]
844 Start,
845 Center,
847 End,
849}
850
851#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
853pub enum EmojiPolicy {
854 #[default]
857 Color,
858 Monochrome,
861 Replace,
864}
865
866#[derive(Clone, Debug, PartialEq)]
871pub struct TextTexture {
872 pub texture: HostTexture,
874 pub layout_x: f32,
877 pub layout_y: f32,
879 pub layout_width: f32,
881 pub layout_height: f32,
883 pub first_baseline: f32,
885 pub ascent: f32,
887 pub descent: f32,
889 pub line_count: u32,
891}
892
893impl TextTexture {
894 #[must_use]
896 pub fn is_valid(&self) -> bool {
897 self.texture.width > 0
898 && self.texture.height > 0
899 && self.line_count > 0
900 && [
901 self.layout_x,
902 self.layout_y,
903 self.layout_width,
904 self.layout_height,
905 self.first_baseline,
906 self.ascent,
907 self.descent,
908 ]
909 .into_iter()
910 .all(|value| value.is_finite() && value >= 0.0)
911 && self.first_baseline <= self.layout_height
912 && f64::from(self.layout_x) + f64::from(self.layout_width)
913 <= f64::from(self.texture.width)
914 && f64::from(self.layout_y) + f64::from(self.layout_height)
915 <= f64::from(self.texture.height)
916 }
917}
918
919#[derive(Clone, Debug, PartialEq)]
921pub struct HostTexturePixels {
922 pub texture: HostTexture,
924 pub rgba8: Vec<u8>,
926}
927
928impl HostTexturePixels {
929 #[must_use]
931 pub fn is_valid(&self) -> bool {
932 usize::try_from(self.texture.width)
933 .ok()
934 .and_then(|width| {
935 usize::try_from(self.texture.height)
936 .ok()
937 .and_then(|height| width.checked_mul(height))
938 })
939 .and_then(|pixels| pixels.checked_mul(4))
940 == Some(self.rgba8.len())
941 }
942}
943
944#[derive(Copy, Clone, Debug, Eq, PartialEq)]
946pub enum StreamKind {
947 Video,
949 Audio,
951}
952
953#[derive(Clone, Debug, PartialEq)]
955pub struct StreamInfo {
956 pub index: usize,
958 pub kind: StreamKind,
960 pub codec: String,
962 pub duration: Option<MediaTime>,
964 pub dimensions: Option<(u32, u32)>,
966 pub frame_rate: Option<FrameRate>,
968 pub sample_rate: Option<u32>,
970 pub channels: Option<u32>,
972 pub orientation: Orientation,
974 pub sample_aspect_ratio: SampleAspectRatio,
976 pub color: Option<ColorMetadata>,
978 pub frame_bytes: Option<u64>,
981 pub alpha: Option<SourceAlpha>,
983 pub language: Option<String>,
985 pub title: Option<String>,
987}
988
989#[derive(Copy, Clone, Debug, Eq, PartialEq)]
991pub enum SourceAlpha {
992 Vp9SideData,
995 HevcAuxiliaryLayer,
998 Planar,
1000}
1001
1002impl SourceAlpha {
1003 #[must_use]
1005 pub const fn as_str(self) -> &'static str {
1006 match self {
1007 Self::Vp9SideData => "vp9-side-data",
1008 Self::HevcAuxiliaryLayer => "hevc-auxiliary-layer",
1009 Self::Planar => "planar",
1010 }
1011 }
1012}
1013
1014#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1016pub enum DecodeRequestKind {
1017 Prefetch,
1019 Seek,
1021 Evicted,
1023 DeviceRecovery,
1025}
1026
1027#[derive(Clone, Debug, Eq, PartialEq)]
1029pub struct DecodeRequest {
1030 pub source: SourceId,
1032 pub time: MediaTime,
1034 pub kind: DecodeRequestKind,
1036 pub generation: u64,
1038}
1039
1040#[derive(Clone, Debug, PartialEq)]
1042pub struct DecodeResult {
1043 pub request: DecodeRequest,
1045 pub event: DecodeEvent,
1047}
1048
1049#[derive(Clone, Debug, PartialEq)]
1051pub enum DecodeEvent {
1052 Video(DecodedVideoFrame),
1054 Audio(AudioBlock),
1056 Retry,
1058 EndOfStream,
1060}
1061
1062#[derive(Clone, Debug, Default)]
1064pub struct CancelToken(Arc<AtomicBool>);
1065
1066impl CancelToken {
1067 pub fn cancel(&self) {
1069 self.0.store(true, Ordering::Release);
1070 }
1071
1072 #[must_use]
1074 pub fn is_cancelled(&self) -> bool {
1075 self.0.load(Ordering::Acquire)
1076 }
1077}
1078
1079pub const GPU_TIMEOUT_MESSAGE: &str = "GPU work did not complete within the wait timeout";
1082
1083#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1086#[non_exhaustive]
1087pub enum GpuFault {
1088 DeviceLost,
1090 DeviceHung,
1092 DeviceMemory,
1094 HostMemory,
1096 Timeout,
1098}
1099
1100impl GpuFault {
1101 #[must_use]
1103 pub const fn as_str(self) -> &'static str {
1104 match self {
1105 Self::DeviceLost => "device-lost",
1106 Self::DeviceHung => "device-hung",
1107 Self::DeviceMemory => "device-memory",
1108 Self::HostMemory => "host-memory",
1109 Self::Timeout => "timeout",
1110 }
1111 }
1112}
1113
1114#[derive(Clone, Debug, Eq, PartialEq)]
1119#[non_exhaustive]
1120pub enum DecodeError {
1121 Cancelled,
1123 OutOfRange,
1125 Unsupported(String),
1127 Adapter(String),
1129 Gpu {
1131 fault: GpuFault,
1133 message: String,
1135 },
1136 Source(SourceFailure),
1139}
1140
1141#[derive(Clone, Debug, Eq, PartialEq)]
1143pub struct SourceFailure {
1144 pub code: &'static str,
1146 pub message: String,
1148 pub url: Option<String>,
1150 pub status: Option<u16>,
1152 pub retry_after_ms: Option<u64>,
1154 pub policy: Option<&'static str>,
1156}
1157
1158#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
1160pub enum OpenFailureKind {
1161 Absent,
1163 Busy,
1166 Unsuitable,
1168 Unknown,
1170}
1171
1172impl OpenFailureKind {
1173 #[must_use]
1175 pub const fn as_str(self) -> &'static str {
1176 match self {
1177 Self::Absent => "absent",
1178 Self::Busy => "busy",
1179 Self::Unsuitable => "unsuitable",
1180 Self::Unknown => "unknown",
1181 }
1182 }
1183}
1184
1185#[derive(Clone, Debug, Eq, PartialEq)]
1187pub struct EncoderRefusal {
1188 pub encoder: String,
1190 pub hardware_accelerated: bool,
1192 pub kind: OpenFailureKind,
1194 pub reason: String,
1196}
1197
1198impl DecodeError {
1199 #[must_use]
1201 pub const fn is_fatal(&self) -> bool {
1202 matches!(
1203 self,
1204 Self::Unsupported(_) | Self::Adapter(_) | Self::Gpu { .. }
1205 )
1206 }
1207}
1208
1209impl fmt::Display for DecodeError {
1210 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1211 match self {
1212 Self::Cancelled => formatter.write_str("decode was cancelled"),
1213 Self::OutOfRange => formatter.write_str("decode request is out of range"),
1214 Self::Unsupported(message) => write!(formatter, "unsupported media: {message}"),
1215 Self::Adapter(message) | Self::Gpu { message, .. } => {
1216 write!(formatter, "decoder adapter failed: {message}")
1217 }
1218 Self::Source(failure) => formatter.write_str(&failure.message),
1219 }
1220 }
1221}
1222
1223impl Error for DecodeError {}
1224
1225pub trait Decoder {
1227 fn streams(&self) -> &[StreamInfo];
1229 fn flush(&mut self) -> Result<(), DecodeError>;
1234 fn seek(
1246 &mut self,
1247 request: DecodeRequest,
1248 cancel: &CancelToken,
1249 ) -> Result<DecodeResult, DecodeError>;
1250 fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError>;
1255}
1256
1257#[derive(Clone, Copy, Debug, PartialEq)]
1259pub struct AudioSpan<'a> {
1260 pub block: &'a AudioBlock,
1262 pub starts_source: bool,
1264 pub ends_source: bool,
1266}
1267
1268impl<'a> AudioSpan<'a> {
1269 #[must_use]
1271 pub const fn whole(block: &'a AudioBlock) -> Self {
1272 Self {
1273 block,
1274 starts_source: true,
1275 ends_source: true,
1276 }
1277 }
1278
1279 #[must_use]
1282 pub fn covers(&self, start: i64, end: i64) -> bool {
1283 (self.starts_source || self.block.start_sample <= start)
1284 && (self.ends_source || self.block.end_sample() >= end)
1285 }
1286}
1287
1288pub trait AudioBlockProvider {
1290 fn block(
1301 &self,
1302 source: &SourceId,
1303 stream: Option<u32>,
1304 start_sample: i64,
1305 frames: usize,
1306 ) -> Option<AudioSpan<'_>>;
1307}
1308
1309pub trait AudioBlockSink {
1311 fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError>;
1317
1318 fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError>;
1324
1325 fn abort_audio(&mut self) -> Result<(), EncodeError>;
1330}
1331
1332#[derive(Clone, Debug, PartialEq)]
1334pub enum EncodeEvent {
1335 Video(DecodedVideoFrame),
1337 Audio(AudioBlock),
1339}
1340
1341#[derive(Clone, Debug, Eq, PartialEq)]
1343#[non_exhaustive]
1344pub enum EncodeError {
1345 Cancelled,
1347 InvalidTimestamp,
1349 Adapter(String),
1351 Output(String),
1353 OutputInUse(String),
1356 Publish {
1359 message: String,
1361 kept: Option<std::path::PathBuf>,
1363 },
1364 EncoderRejected {
1366 encoder: String,
1368 frame: u64,
1370 message: String,
1372 },
1373 Gpu {
1375 fault: GpuFault,
1377 message: String,
1379 },
1380 EncodersRefused {
1382 message: String,
1384 refusals: Vec<EncoderRefusal>,
1386 },
1387}
1388
1389impl EncodeError {
1390 #[must_use]
1392 pub fn gpu_timeout(what: impl fmt::Display) -> Self {
1393 Self::Gpu {
1394 fault: GpuFault::Timeout,
1395 message: format!("{what}: {GPU_TIMEOUT_MESSAGE}"),
1396 }
1397 }
1398}
1399
1400impl fmt::Display for EncodeError {
1401 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1402 match self {
1403 Self::Cancelled => formatter.write_str("encode was cancelled"),
1404 Self::InvalidTimestamp => formatter.write_str("encode timestamp is invalid"),
1405 Self::Adapter(message)
1406 | Self::Gpu { message, .. }
1407 | Self::EncodersRefused { message, .. } => {
1408 write!(formatter, "encoder adapter failed: {message}")
1409 }
1410 Self::EncoderRejected { message, .. } => formatter.write_str(message),
1411 Self::Output(message) | Self::OutputInUse(message) => {
1412 write!(formatter, "cannot create the output: {message}")
1413 }
1414 Self::Publish {
1415 message,
1416 kept: Some(kept),
1417 } => write!(
1418 formatter,
1419 "cannot publish the output: {message}; the finished render is kept at {}",
1420 kept.display()
1421 ),
1422 Self::Publish {
1423 message,
1424 kept: None,
1425 } => write!(
1426 formatter,
1427 "cannot publish the output: {message}; the finished render could not be kept"
1428 ),
1429 }
1430 }
1431}
1432
1433impl Error for EncodeError {}
1434
1435pub trait EncodeSink {
1437 fn write(&mut self, event: EncodeEvent, cancel: &CancelToken) -> Result<(), EncodeError>;
1442 fn finish(&mut self, cancel: &CancelToken) -> Result<(), EncodeError>;
1447 fn abort(&mut self) -> Result<(), EncodeError>;
1452}
1453
1454#[cfg(test)]
1455mod tests {
1456 use super::SampleAspectRatio;
1457
1458 #[test]
1459 fn a_pixel_aspect_ratio_is_kept_in_lowest_terms_and_shows_as_a_browser_shows_it() {
1460 let ratio = |num, den| SampleAspectRatio { num, den };
1461 assert_eq!(SampleAspectRatio::new(8, 6), Some(ratio(4, 3)));
1462 assert_eq!(SampleAspectRatio::new(0, 1), None);
1463 assert_eq!(SampleAspectRatio::new(1, 0), None);
1464 assert_eq!(SampleAspectRatio::new(u64::from(u32::MAX) + 1, 1), None);
1465 let shown = |visible, displayed| SampleAspectRatio::of_display(visible, displayed);
1467 assert_eq!(shown((128, 96), (171, 96)), Some(ratio(4, 3)));
1468 assert_eq!(shown((96, 128), (96, 171)), Some(ratio(3, 4)));
1469 assert_eq!(shown((720, 576), (1024, 576)), Some(ratio(64, 45)));
1470 assert_eq!(shown((720, 480), (655, 480)), Some(ratio(10, 11)));
1471 assert_eq!(shown((720, 480), (720, 524)), Some(ratio(11, 12)));
1472 assert_eq!(shown((1440, 1080), (1920, 1080)), Some(ratio(4, 3)));
1473 assert_eq!(shown((128, 96), (128, 96)), Some(ratio(1, 1)));
1474 for (visible, displayed) in [
1476 ((128, 96), (170, 96)),
1477 ((1000, 999), (1777, 999)),
1478 ((3, 2), (5, 2)),
1479 ] {
1480 let found = shown(visible, displayed).expect("a ratio");
1481 assert_eq!(
1482 found.square_pixel_size(visible.0, visible.1),
1483 displayed,
1484 "{visible:?} {displayed:?}"
1485 );
1486 }
1487 assert_eq!(shown((0, 96), (171, 96)), None);
1488 assert_eq!(ratio(4, 3).square_pixel_size(128, 96), (171, 96));
1490 assert_eq!(ratio(64, 45).square_pixel_size(720, 576), (1024, 576));
1491 assert_eq!(ratio(3, 4).square_pixel_size(96, 128), (96, 171));
1492 assert_eq!(ratio(1, 1).square_pixel_size(65, 49), (65, 49));
1493 assert_eq!(ratio(3, 2).square_pixel_size(3, 7), (5, 7));
1495 }
1496
1497 use super::*;
1498
1499 #[test]
1500 fn a_frame_size_is_bounded_on_each_side_and_in_area() {
1501 assert!(frame_size_supported(16_384, 4_096));
1502 assert!(frame_size_supported(8_192, 8_192));
1503 assert!(!frame_size_supported(8_193, 8_192));
1504 assert!(!frame_size_supported(16_385, 1));
1505 assert!(!frame_size_supported(1, 16_385));
1506 assert!(!frame_size_supported(u32::MAX, u32::MAX));
1507 }
1508
1509 #[test]
1510 fn cancellation_is_shared_and_monotonic() {
1511 let token = CancelToken::default();
1512 let other = token.clone();
1513 assert!(!other.is_cancelled());
1514 token.cancel();
1515 assert!(other.is_cancelled());
1516 }
1517
1518 #[test]
1519 fn a_layout_names_each_plane_by_ffmpegs_channel_names() {
1520 let lcr = SpeakerLayout::new(&[
1521 Speaker::FrontCenter,
1522 Speaker::FrontLeft,
1523 Speaker::FrontRight,
1524 ])
1525 .expect("layout");
1526 assert_eq!(lcr.channels(), 3);
1527 assert_eq!(lcr.describe(), "FC+FL+FR");
1528 assert_eq!(format!("{lcr:?}"), r#"["FC", "FL", "FR"]"#);
1529 for (speaker, name, channel) in Speaker::TABLE {
1530 assert_eq!(speaker.name(), name);
1531 assert_eq!(Speaker::from_name(name), Some(speaker));
1532 assert_eq!(speaker.ffmpeg_channel(), channel);
1533 assert_eq!(Speaker::from_ffmpeg_channel(i64::from(channel)), speaker);
1534 }
1535 for channel in [-1, 18, 0x200, 0x400, 0x401, 0x7ff, 1_000] {
1537 assert_eq!(Speaker::from_ffmpeg_channel(channel), Speaker::Unnamed);
1538 }
1539 assert_eq!(Speaker::from_name("front left"), None);
1540 assert!(SpeakerLayout::new(&[]).is_none());
1541 assert!(SpeakerLayout::new(&[Speaker::FrontLeft; MAX_AUDIO_CHANNELS + 1]).is_none());
1542 }
1543
1544 #[test]
1545 fn a_source_that_declares_no_speaker_has_ffmpegs_default_for_its_count() {
1546 let names = |channels| {
1547 SpeakerLayout::default_for(channels)
1548 .expect("a default")
1549 .describe()
1550 };
1551 assert_eq!(names(1), "FC");
1552 assert_eq!(names(3), "FL+FR+LFE");
1553 assert_eq!(names(4), "FL+FR+FC+BC");
1554 assert_eq!(names(8), "FL+FR+FC+LFE+BL+BR+SL+SR");
1555 assert_eq!(names(9), "FL+FR+FC+LFE+BL+BR+SL+SR+UNK");
1556 assert_eq!(names(10), "FL+FR+FC+LFE+SL+SR+TFL+TFR+TBL+TBR");
1557 assert_eq!(SpeakerLayout::default_for(24).expect("22.2").channels(), 24);
1558 assert!(SpeakerLayout::default_for(0).is_none());
1559 assert!(SpeakerLayout::default_for(MAX_AUDIO_CHANNELS + 1).is_none());
1560 let unnamed = [Speaker::Unnamed; 2];
1561 assert_eq!(
1562 SpeakerLayout::declared_or_default(&unnamed),
1563 Some((SpeakerLayout::default_for(2).expect("stereo"), true))
1564 );
1565 let partly = [Speaker::FrontCenter, Speaker::Unnamed];
1566 assert_eq!(
1567 SpeakerLayout::declared_or_default(&partly),
1568 Some((SpeakerLayout::new(&partly).expect("layout"), false))
1569 );
1570 }
1571
1572 #[test]
1573 fn a_span_covers_a_request_only_where_it_holds_samples_or_knows_silence() {
1574 let block = AudioBlock {
1575 start_sample: 100,
1576 sample_rate: 48_000,
1577 speakers: SpeakerLayout::default_for(1).expect("mono"),
1578 channels: vec![vec![0.5; 50]],
1579 };
1580 let partial = AudioSpan {
1581 block: &block,
1582 starts_source: false,
1583 ends_source: false,
1584 };
1585 assert!(partial.covers(100, 150));
1586 assert!(partial.covers(120, 130));
1587 assert!(!partial.covers(99, 150), "a sample before the block");
1588 assert!(!partial.covers(100, 151), "a sample after the block");
1589 let starts = AudioSpan {
1590 starts_source: true,
1591 ..partial
1592 };
1593 assert!(starts.covers(0, 150));
1594 assert!(!starts.covers(0, 151));
1595 assert!(AudioSpan::whole(&block).covers(-5, 1_000));
1596 }
1597
1598 #[test]
1599 fn text_descriptor_and_generic_pixels_validate_without_compositor_types() {
1600 let texture = HostTexture {
1601 content_version: 2,
1602 width: 4,
1603 height: 3,
1604 premultiplication: Premultiplication::Premultiplied,
1605 color_space: RasterColorSpace::Srgb,
1606 };
1607 let text = TextTexture {
1608 texture: texture.clone(),
1609 layout_x: 0.0,
1610 layout_y: 0.0,
1611 layout_width: 4.0,
1612 layout_height: 3.0,
1613 first_baseline: 2.0,
1614 ascent: 2.0,
1615 descent: 1.0,
1616 line_count: 1,
1617 };
1618 assert!(text.is_valid());
1619 assert!(
1620 HostTexturePixels {
1621 texture,
1622 rgba8: vec![0; 4 * 3 * 4],
1623 }
1624 .is_valid()
1625 );
1626 }
1627}