Skip to main content

alpha2_media/
io.rs

1//! Platform-neutral media I/O contracts.
2//!
3//! Adapters translate `FFmpeg`, `WebCodecs`, or other host objects at this boundary;
4//! none of those platform types are part of these contracts.
5
6use 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/// Rectangle inside a coded video frame.
15#[derive(Copy, Clone, Debug, Eq, PartialEq)]
16pub struct Rect {
17    /// Horizontal origin in coded pixels.
18    pub x: u32,
19    /// Vertical origin in coded pixels.
20    pub y: u32,
21    /// Visible width.
22    pub width: u32,
23    /// Visible height.
24    pub height: u32,
25}
26
27/// Clockwise rotation to apply when displaying a frame.
28///
29/// Matches `WebCodecs` `VideoFrame.rotation`. `FFmpeg`'s display matrix angle is
30/// counter-clockwise, so bindings report `(-angle) mod 360`.
31#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
32pub enum Rotation {
33    /// No rotation.
34    #[default]
35    Deg0,
36    /// Clockwise quarter turn.
37    Deg90,
38    /// Half turn.
39    Deg180,
40    /// Clockwise three-quarter turn, i.e. a counter-clockwise quarter turn.
41    Deg270,
42}
43
44impl Rotation {
45    /// Clockwise quarter turns, `0..4`.
46    #[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    /// The rotation of `quarter_turns` clockwise quarter turns, of any sign.
57    #[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    /// Whether the rotation exchanges width and height.
68    #[must_use]
69    pub const fn swaps_axes(self) -> bool {
70        matches!(self, Self::Deg90 | Self::Deg270)
71    }
72}
73
74/// How to show a decoded picture upright: mirror left to right when `mirror` is set, then
75/// rotate clockwise by `rotation`.
76///
77/// This covers all eight Exif orientations, display matrices at multiples of 90 degrees, and
78/// Matroska projection poses. `FFmpeg`'s display matrix mirrors after rotating, counter-clockwise,
79/// so bindings must convert it.
80#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
81pub struct Orientation {
82    /// Clockwise rotation, applied after the mirror.
83    pub rotation: Rotation,
84    /// Whether the stored picture is mirrored left to right before it turns.
85    pub mirror: bool,
86}
87
88impl Orientation {
89    /// Shown as stored.
90    pub const UPRIGHT: Self = Self {
91        rotation: Rotation::Deg0,
92        mirror: false,
93    };
94
95    /// A rotation without a mirror.
96    #[must_use]
97    pub const fn rotated(rotation: Rotation) -> Self {
98        Self {
99            rotation,
100            mirror: false,
101        }
102    }
103
104    /// The orientation of an Exif `Orientation` value (1 to 8). 2, 4, 5 and 7 mirror.
105    #[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    /// Whether the picture is shown as stored.
122    #[must_use]
123    pub const fn is_upright(self) -> bool {
124        matches!(self.rotation, Rotation::Deg0) && !self.mirror
125    }
126
127    /// The displayed size of a stored `width` x `height` picture.
128    #[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/// Reduced pixel-width to pixel-height ratio.
139#[derive(Copy, Clone, Debug, Eq, PartialEq)]
140pub struct SampleAspectRatio {
141    /// Ratio numerator.
142    pub num: u32,
143    /// Ratio denominator, never zero.
144    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    /// The ratio `num`:`den` in lowest terms, or `None` when either term is zero (`FFmpeg`
155    /// writes an unknown ratio as 0/1).
156    #[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    /// The pixel aspect ratio of a `visible` picture shown at `displayed` size, as a `WebCodecs`
169    /// display size gives it.
170    ///
171    /// Display sizes are rounded to whole pixels (128x96 at 4:3 shows 171x96, not 170 2/3), so
172    /// this returns the simplest fraction that rounds to that size. That recovers small declared
173    /// ratios such as 4:3, 64:45 and 10:11 exactly.
174    #[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        // A side the display stretched is known to half a pixel; one it kept is exact.
190        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        // ratio = (displayed_width / visible_width) / (displayed_height / visible_height), in
194        // half pixels.
195        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    /// The square-pixel display size of a stored `width` x `height` picture: the longer pixel
208    /// side stretched, rounded half up, as browser demuxers report it.
209    #[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
227/// The fraction with the smallest denominator in `low..=high`, by continued fractions.
228fn 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    // Both ends lie strictly between `whole` and `whole + 1`: x = whole + 1/y, with y between the
241    // reciprocals of the fractional parts.
242    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/// Plane organization delivered by a decoder.
257///
258/// A [`Decoder`] delivers only layouts the renderer consumes directly: [`YuvFormat`] YCbCr,
259/// 8-bit RGBA, and linear half-float RGBA for high-range sources. Decoders must convert any
260/// other layout (packed RGB, palettes and so on) and report it as [`PixelFormat::Rgba8`].
261#[derive(Copy, Clone, Debug, Eq, PartialEq)]
262#[non_exhaustive]
263pub enum PixelFormat {
264    /// Planar or semi-planar YCbCr, one [`Plane`] per stored plane.
265    Yuv(YuvFormat),
266    /// Straight-alpha 8-bit red, green, blue, alpha in one plane.
267    Rgba8,
268    /// Premultiplied, sRGB-encoded 8-bit red, green, blue, alpha in one plane, as an extension
269    /// provider renders it. Decoders deliver [`Self::Rgba8`].
270    Rgba8Premultiplied,
271    /// Premultiplied linear RGBA in one plane of little-endian half floats, BT.709 primaries,
272    /// `1.0` at SDR white. Values outside `0..=1` are allowed, and the frame's color metadata
273    /// does not apply.
274    LinearRgbaF16,
275}
276
277/// How a planar or semi-planar YCbCr frame stores its samples.
278///
279/// Luma comes first, then separate U and V planes or one interleaved UV plane, each
280/// `ceil(width / 2^chroma_shift_x)` by `ceil(height / 2^chroma_shift_y)`. Samples over eight
281/// bits are little-endian `u16`. With [`alpha`](Self::alpha), a straight full-range alpha plane
282/// at luma size and depth follows.
283#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
284pub struct YuvFormat {
285    /// Log2 of the horizontal chroma subsampling: 0 for 4:4:4, 1 for 4:2:x.
286    pub chroma_shift_x: u8,
287    /// Log2 of the vertical chroma subsampling: 1 for 4:2:0, 0 otherwise.
288    pub chroma_shift_y: u8,
289    /// Significant bits per sample, 8 through 16.
290    pub bit_depth: u8,
291    /// Whether U and V interleave in one plane, as NV12 and P010 do.
292    pub interleaved_chroma: bool,
293    /// Whether samples sit in the high bits of their `u16` (P010) rather than the low bits
294    /// (`yuv420p10le`).
295    pub msb_aligned: bool,
296    /// Whether an alpha plane follows the chroma, as `yuva444p16le`'s does.
297    pub alpha: bool,
298}
299
300impl YuvFormat {
301    /// 8-bit planar 4:2:0 (`yuv420p`).
302    pub const I420: Self = Self::planar(1, 1, 8);
303    /// 8-bit 4:2:0 with interleaved chroma (`nv12`).
304    pub const NV12: Self = Self {
305        interleaved_chroma: true,
306        ..Self::I420
307    };
308    /// 10-bit 4:2:0 with interleaved, high-aligned chroma (`p010le`).
309    pub const P010: Self = Self {
310        bit_depth: 10,
311        msb_aligned: true,
312        ..Self::NV12
313    };
314
315    /// Planar YCbCr with low-aligned samples.
316    #[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    /// The same format with an alpha plane after the chroma.
329    #[must_use]
330    pub const fn with_alpha(self) -> Self {
331        Self {
332            alpha: true,
333            ..self
334        }
335    }
336
337    /// Whether the renderer can sample this format: 8 to 16 bits, chroma subsampling of at most
338    /// four per axis, and high alignment only below 16 bits.
339    #[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    /// Bytes each stored sample takes: one up to 8 bits, two above.
349    #[must_use]
350    pub const fn bytes_per_sample(self) -> u32 {
351        if self.bit_depth > 8 { 2 } else { 1 }
352    }
353
354    /// Number of stored planes, alpha included.
355    #[must_use]
356    pub const fn plane_count(self) -> usize {
357        self.color_plane_count() + if self.alpha { 1 } else { 0 }
358    }
359
360    /// Number of luma and chroma planes; the alpha plane, if any, follows them.
361    #[must_use]
362    pub const fn color_plane_count(self) -> usize {
363        if self.interleaved_chroma { 2 } else { 3 }
364    }
365
366    /// Chroma plane dimensions, in sample positions, for a coded frame size.
367    #[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/// Chroma sample location for subsampled YUV.
377#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
378pub enum ChromaLocation {
379    /// Adapter could not determine a location.
380    #[default]
381    Unspecified,
382    /// MPEG-2/most video: horizontally left, vertically centered.
383    Left,
384    /// JPEG-style centered chroma.
385    Center,
386    /// Top-left co-sited chroma.
387    TopLeft,
388}
389
390impl ChromaLocation {
391    /// The siting chroma of `format` is read at. An unspecified siting of chroma subsampled
392    /// horizontally only (4:2:2, 4:1:1) is [`Self::Left`], co-sited with even luma columns as
393    /// BT.601 and BT.709 site it; otherwise it is kept (unspecified 4:2:0 reads as centred).
394    #[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/// One decoded image plane.
406///
407/// Bytes are shared so decoders can hand over reference-counted memory without copying.
408#[derive(Clone, Debug, Eq, PartialEq)]
409pub struct Plane {
410    /// Plane bytes, including row padding: `stride * height` of them.
411    pub bytes: bytes::Bytes,
412    /// Bytes between adjacent rows.
413    pub stride: u32,
414    /// Plane width in sample positions (a UV pair each for interleaved chroma).
415    pub width: u32,
416    /// Plane height in samples.
417    pub height: u32,
418}
419
420/// Largest frame edge, in pixels, that alpha2 decodes, renders or composes.
421pub const MAX_FRAME_DIMENSION: u32 = 16_384;
422/// Largest frame area, in pixels. Decoders refuse larger frames before allocating.
423pub const MAX_FRAME_PIXELS: u64 = 67_108_864;
424
425/// Whether a `width` x `height` frame is within [`MAX_FRAME_DIMENSION`] and
426/// [`MAX_FRAME_PIXELS`].
427#[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/// Host-independent decoded video frame.
435#[derive(Clone, Debug, PartialEq)]
436pub struct DecodedVideoFrame {
437    /// Presentation timestamp.
438    pub pts: MediaTime,
439    /// Optional decode timestamp.
440    pub dts: Option<MediaTime>,
441    /// Nominal frame duration when known.
442    pub duration: Option<MediaTime>,
443    /// The visible crop within the coded picture, in coded pixels.
444    pub visible_rect: Rect,
445    /// Pixel aspect ratio.
446    pub sample_aspect_ratio: SampleAspectRatio,
447    /// How the picture is shown upright.
448    pub orientation: Orientation,
449    /// Plane layout.
450    pub pixel_format: PixelFormat,
451    /// Chroma siting.
452    pub chroma_location: ChromaLocation,
453    /// Declared color: the project's declaration, else the frame or stream tags. When `None`,
454    /// the renderer applies [`crate::ColorMetadata::UNDECLARED`] and reports it.
455    pub color: Option<ColorMetadata>,
456    /// Image planes in the order [`Self::pixel_format`] stores them.
457    pub planes: Vec<Plane>,
458}
459
460/// Most planes an [`AudioBlock`] carries: 24, for 22.2, the largest `FFmpeg` layout. Sources
461/// with more are refused rather than downmixed.
462pub const MAX_AUDIO_CHANNELS: usize = 24;
463
464/// The loudspeaker one plane of an [`AudioBlock`] feeds.
465///
466/// Positions are `FFmpeg`'s named channels (`AVChannel`), a superset of the WAVE mask, Apple
467/// channel labels and ISO/IEC 23001-8. [`Speaker::name`] is `FFmpeg`'s abbreviation.
468#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
469pub enum Speaker {
470    /// Front left (`FL`).
471    FrontLeft,
472    /// Front right (`FR`).
473    FrontRight,
474    /// Front center (`FC`), also a mono source's channel.
475    FrontCenter,
476    /// Low-frequency effects (`LFE`).
477    LowFrequency,
478    /// Back left (`BL`).
479    BackLeft,
480    /// Back right (`BR`).
481    BackRight,
482    /// Front left of center (`FLC`).
483    FrontLeftOfCenter,
484    /// Front right of center (`FRC`).
485    FrontRightOfCenter,
486    /// Back center (`BC`).
487    BackCenter,
488    /// Side left (`SL`).
489    SideLeft,
490    /// Side right (`SR`).
491    SideRight,
492    /// Top center (`TC`).
493    TopCenter,
494    /// Top front left (`TFL`).
495    TopFrontLeft,
496    /// Top front center (`TFC`).
497    TopFrontCenter,
498    /// Top front right (`TFR`).
499    TopFrontRight,
500    /// Top back left (`TBL`).
501    TopBackLeft,
502    /// Top back center (`TBC`).
503    TopBackCenter,
504    /// Top back right (`TBR`).
505    TopBackRight,
506    /// Left of a matrix-encoded stereo downmix (`DL`, Lt).
507    DownmixLeft,
508    /// Right of a matrix-encoded stereo downmix (`DR`, Rt).
509    DownmixRight,
510    /// Wide left (`WL`).
511    WideLeft,
512    /// Wide right (`WR`).
513    WideRight,
514    /// Surround direct left (`SDL`).
515    SurroundDirectLeft,
516    /// Surround direct right (`SDR`).
517    SurroundDirectRight,
518    /// Second low-frequency effects (`LFE2`).
519    LowFrequency2,
520    /// Top side left (`TSL`).
521    TopSideLeft,
522    /// Top side right (`TSR`).
523    TopSideRight,
524    /// Bottom front center (`BFC`).
525    BottomFrontCenter,
526    /// Bottom front left (`BFL`).
527    BottomFrontLeft,
528    /// Bottom front right (`BFR`).
529    BottomFrontRight,
530    /// Side surround left (`SSL`).
531    SideSurroundLeft,
532    /// Side surround right (`SSR`).
533    SideSurroundRight,
534    /// Top surround left (`TTL`).
535    TopSurroundLeft,
536    /// Top surround right (`TTR`).
537    TopSurroundRight,
538    /// Binaural left (`BIL`).
539    BinauralLeft,
540    /// Binaural right (`BIR`).
541    BinauralRight,
542    /// A channel without a loudspeaker position (`UNK`), such as an ambisonic component. The
543    /// fold leaves it out.
544    Unnamed,
545}
546
547impl Speaker {
548    /// Every speaker with its `FFmpeg` name and channel number (`AVChannel`);
549    /// [`Speaker::Unnamed`] is `FFmpeg`'s `AV_CHAN_UNKNOWN`.
550    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    /// `FFmpeg`'s abbreviation (`FL`, `FR`, `LFE`, ...), `UNK` for [`Speaker::Unnamed`].
591    #[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    /// The speaker `FFmpeg` names `name` (`UNK` is [`Speaker::Unnamed`]).
600    #[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    /// `FFmpeg`'s channel number (`enum AVChannel`) for this speaker.
609    #[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    /// The speaker of `FFmpeg` channel number `channel`, or [`Speaker::Unnamed`] for channels
618    /// without a loudspeaker position.
619    #[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/// The speakers an [`AudioBlock`]'s planes feed, in plane order (1 to [`MAX_AUDIO_CHANNELS`]).
629///
630/// Providers report the layout their source declares, in plane order, without rematrixing.
631/// Sources that declare none get [`SpeakerLayout::default_for`] their channel count.
632#[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    /// One front-center plane.
649    pub const MONO: Self = Self::fixed(&[Speaker::FrontCenter]);
650    /// Front left and right.
651    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    /// The layout of these speakers in plane order, or `None` for zero or more than
668    /// [`MAX_AUDIO_CHANNELS`].
669    #[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    /// `FFmpeg`'s default layout for `channels` (`av_channel_layout_default`), in WAVE order:
683    /// mono through 7.1 up to 8, and 5.1.4, 7.1.4, 9.1.4, 9.1.6 and 22.2 for 10, 12, 14, 16 and
684    /// 24. Other counts are 7.1 plus unnamed channels. `None` for zero or more than
685    /// [`MAX_AUDIO_CHANNELS`].
686    #[must_use]
687    pub fn default_for(channels: usize) -> Option<Self> {
688        /// `FFmpeg`'s native-order channel masks (`AV_CH_LAYOUT_*`).
689        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        // No layout for this count: 7.1 plus unnamed channels.
708        layout.count = u8::try_from(channels).ok()?;
709        Some(layout)
710    }
711
712    /// The speakers of a native-order channel mask, in bit order.
713    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    /// The declared layout, or [`SpeakerLayout::default_for`] the channel count when it names no
722    /// speaker. The flag reports whether the default was assumed.
723    #[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    /// The speakers, in plane order.
732    #[must_use]
733    pub fn speakers(&self) -> &[Speaker] {
734        &self.speakers[..usize::from(self.count)]
735    }
736
737    /// How many planes the layout has.
738    #[must_use]
739    pub fn channels(&self) -> usize {
740        usize::from(self.count)
741    }
742
743    /// The speakers' `FFmpeg` names joined by `+` (`FL+FR+FC`), as
744    /// `av_channel_layout_from_string` reads them.
745    #[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/// Planar floating-point audio at the project sample rate.
756///
757/// Positions are sample indices, never ticks, because a tick is not a whole number of samples
758/// at 44.1 kHz. Sample `n` is at `n / sample_rate` seconds on the block's timeline (the
759/// source's for a decoder, the project's for a mixer).
760///
761/// Decoder and [`AudioBlockProvider`] blocks keep the source's channels and speakers; the mixer
762/// folds them into the project layout.
763#[derive(Clone, Debug, PartialEq)]
764pub struct AudioBlock {
765    /// Index of the first sample, at `sample_rate`.
766    pub start_sample: i64,
767    /// Project sample rate used by every returned block.
768    pub sample_rate: u32,
769    /// The speaker each of `channels` feeds, one per plane.
770    pub speakers: SpeakerLayout,
771    /// One vector per channel, all with equal lengths, in `speakers`' order.
772    pub channels: Vec<Vec<f32>>,
773}
774
775impl AudioBlock {
776    /// Samples per channel.
777    #[must_use]
778    pub fn frames(&self) -> usize {
779        self.channels.first().map_or(0, Vec::len)
780    }
781
782    /// Index one past the last sample.
783    #[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    /// The first sample's time, rounded down to the tick grid. Audio positions stay in samples.
790    #[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/// The tick at or before sample `sample` at `sample_rate`.
797#[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/// Generic color declaration for a host-rasterized texture.
805#[derive(Copy, Clone, Debug, Eq, PartialEq)]
806pub enum RasterColorSpace {
807    /// IEC sRGB encoded RGB.
808    Srgb,
809    /// Linear-light RGB with BT.709/sRGB primaries.
810    LinearSrgb,
811}
812
813/// Alpha representation of host pixels.
814#[derive(Copy, Clone, Debug, Eq, PartialEq)]
815pub enum Premultiplication {
816    /// RGB has already been multiplied by alpha.
817    Premultiplied,
818    /// RGB is straight and must be premultiplied at upload.
819    Straight,
820    /// Pixels are opaque.
821    Opaque,
822}
823
824/// Generic image/video/text texture descriptor owned by a host.
825#[derive(Clone, Debug, Eq, PartialEq)]
826pub struct HostTexture {
827    /// Host-defined cache identity.
828    pub content_version: u64,
829    /// Width in pixels.
830    pub width: u32,
831    /// Height in pixels.
832    pub height: u32,
833    /// Alpha representation.
834    pub premultiplication: Premultiplication,
835    /// RGB encoding.
836    pub color_space: RasterColorSpace,
837}
838
839/// Horizontal alignment applied by a host text layout engine.
840#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
841pub enum TextAlign {
842    /// Align each line to its paragraph's leading edge (left for LTR, right for RTL).
843    #[default]
844    Start,
845    /// Center each line in the requested layout width.
846    Center,
847    /// Align each line to its paragraph's trailing edge.
848    End,
849}
850
851/// How a text host draws emoji and other color glyphs.
852#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
853pub enum EmojiPolicy {
854    /// Draw color glyphs (COLR, CBDT or sbix) in their own colors. Emoji-presentation graphemes
855    /// try color fonts first, and U+FE0E text presentation tries the others first.
856    #[default]
857    Color,
858    /// Draw every glyph as an outline in the text color, trying fonts without color glyphs first
859    /// for emoji.
860    Monochrome,
861    /// Draw each emoji-presentation grapheme (per UTS #51), with its sequence and modifiers, as
862    /// one U+FFFD. Symbols shown as text by default, such as (c), stay.
863    Replace,
864}
865
866/// Layout facts attached to a host-rasterized text texture.
867///
868/// The compositor treats [`Self::texture`] like any image texture; the metrics serve placement,
869/// cache validation and cross-host tests.
870#[derive(Clone, Debug, PartialEq)]
871pub struct TextTexture {
872    /// Generic texture identity and pixel declaration.
873    pub texture: HostTexture,
874    /// The layout box's left edge in the texture, in pixels. The same margin is added on both
875    /// sides for overhanging ink.
876    pub layout_x: f32,
877    /// The layout box's top edge in the texture, in pixels, with the same margin below.
878    pub layout_y: f32,
879    /// Logical layout width before integer pixel rounding.
880    pub layout_width: f32,
881    /// Logical layout height before integer pixel rounding.
882    pub layout_height: f32,
883    /// Distance from the layout box's top edge to the first alphabetic baseline.
884    pub first_baseline: f32,
885    /// Maximum ink extent above a baseline, at least the nominal ascent.
886    pub ascent: f32,
887    /// Maximum ink extent below a baseline, at least the nominal descent.
888    pub descent: f32,
889    /// Number of laid-out lines.
890    pub line_count: u32,
891}
892
893impl TextTexture {
894    /// Checks dimensions and finite layout metrics at the public boundary.
895    #[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/// RGBA8 pixels returned by an image, video, or text rasterization host.
920#[derive(Clone, Debug, PartialEq)]
921pub struct HostTexturePixels {
922    /// Shared texture descriptor. Text hosts additionally return [`TextTexture`].
923    pub texture: HostTexture,
924    /// Tightly packed top-to-bottom RGBA8 rows.
925    pub rgba8: Vec<u8>,
926}
927
928impl HostTexturePixels {
929    /// Checks that the owned bytes exactly cover the declared texture.
930    #[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/// Media stream domain.
945#[derive(Copy, Clone, Debug, Eq, PartialEq)]
946pub enum StreamKind {
947    /// Video stream.
948    Video,
949    /// Audio stream.
950    Audio,
951}
952
953/// Platform-neutral probe result for one stream.
954#[derive(Clone, Debug, PartialEq)]
955pub struct StreamInfo {
956    /// Demuxer stream index.
957    pub index: usize,
958    /// Stream domain.
959    pub kind: StreamKind,
960    /// Codec short name when available.
961    pub codec: String,
962    /// Stream duration when known.
963    pub duration: Option<MediaTime>,
964    /// Video dimensions.
965    pub dimensions: Option<(u32, u32)>,
966    /// Video frame rate.
967    pub frame_rate: Option<FrameRate>,
968    /// Audio sample rate.
969    pub sample_rate: Option<u32>,
970    /// Audio channel count.
971    pub channels: Option<u32>,
972    /// How the stream's pictures are shown upright.
973    pub orientation: Orientation,
974    /// Sample aspect ratio.
975    pub sample_aspect_ratio: SampleAspectRatio,
976    /// Declared video color.
977    pub color: Option<ColorMetadata>,
978    /// Bytes per decoded picture in the decoder's output format (`av_image_get_buffer_size` at
979    /// the coded size), or `None` when the format is unknown.
980    pub frame_bytes: Option<u64>,
981    /// How a video stream carries alpha, when it does; `None` for an opaque stream.
982    pub alpha: Option<SourceAlpha>,
983    /// The stream's `language` tag, when tagged.
984    pub language: Option<String>,
985    /// The stream's `title` tag, when tagged.
986    pub title: Option<String>,
987}
988
989/// How a video stream carries an alpha channel.
990#[derive(Copy, Clone, Debug, Eq, PartialEq)]
991pub enum SourceAlpha {
992    /// VP9 in Matroska or `WebM` with `alpha_mode` 1: the alpha plane is the luma of a second VP9
993    /// stream in each block's addition 1.
994    Vp9SideData,
995    /// HEVC with an auxiliary alpha layer (Apple's HEVC with alpha). No supported decoder reads
996    /// it, so the base layer decodes opaque.
997    HevcAuxiliaryLayer,
998    /// A pixel format with an alpha plane (`ProRes` 4444, PNG, `QuickTime` Animation).
999    Planar,
1000}
1001
1002impl SourceAlpha {
1003    /// The name used in reports.
1004    #[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/// Kind of decoder cache/refill operation.
1015#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1016pub enum DecodeRequestKind {
1017    /// Normal look-ahead fill.
1018    Prefetch,
1019    /// Exact seek: flush decoder state and begin at/before the requested time.
1020    Seek,
1021    /// Refill after cache eviction.
1022    Evicted,
1023    /// Refill every referenced input after GPU device recovery.
1024    DeviceRecovery,
1025}
1026
1027/// One idempotent decoder request. Hosts discard results with an old generation.
1028#[derive(Clone, Debug, Eq, PartialEq)]
1029pub struct DecodeRequest {
1030    /// Source identity.
1031    pub source: SourceId,
1032    /// Requested source timestamp.
1033    pub time: MediaTime,
1034    /// Why the engine needs the input.
1035    pub kind: DecodeRequestKind,
1036    /// Monotonically increasing seek/recovery generation.
1037    pub generation: u64,
1038}
1039
1040/// Result correlated to a decoder request, safe for out-of-order completion.
1041#[derive(Clone, Debug, PartialEq)]
1042pub struct DecodeResult {
1043    /// Original request.
1044    pub request: DecodeRequest,
1045    /// Decoder outcome.
1046    pub event: DecodeEvent,
1047}
1048
1049/// Decoder output and terminal states.
1050#[derive(Clone, Debug, PartialEq)]
1051pub enum DecodeEvent {
1052    /// Decoded video became available.
1053    Video(DecodedVideoFrame),
1054    /// Decoded audio became available.
1055    Audio(AudioBlock),
1056    /// No exact frame is available yet; retry after feeding more input.
1057    Retry,
1058    /// The selected stream has ended.
1059    EndOfStream,
1060}
1061
1062/// Cancellation flag shared across adapter operations.
1063#[derive(Clone, Debug, Default)]
1064pub struct CancelToken(Arc<AtomicBool>);
1065
1066impl CancelToken {
1067    /// Requests cancellation. The operation must stop at its next adapter boundary.
1068    pub fn cancel(&self) {
1069        self.0.store(true, Ordering::Release);
1070    }
1071
1072    /// Returns whether cancellation was requested.
1073    #[must_use]
1074    pub fn is_cancelled(&self) -> bool {
1075        self.0.load(Ordering::Acquire)
1076    }
1077}
1078
1079/// The message every timed-out GPU wait carries, so hosts that see only error text can classify
1080/// it as `GPU_TIMEOUT`.
1081pub const GPU_TIMEOUT_MESSAGE: &str = "GPU work did not complete within the wait timeout";
1082
1083/// What a failed GPU call says about its device, read from the platform status (`VkResult`,
1084/// `HRESULT` or `CVReturn`) rather than from any message.
1085#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1086#[non_exhaustive]
1087pub enum GpuFault {
1088    /// The device was lost or removed; nothing more runs on it.
1089    DeviceLost,
1090    /// The device was reset because work ran too long (`DXGI_ERROR_DEVICE_HUNG`).
1091    DeviceHung,
1092    /// The device could not allocate memory of its own.
1093    DeviceMemory,
1094    /// The driver could not allocate host (CPU) memory for the call.
1095    HostMemory,
1096    /// GPU work the call waited on did not complete within the wait timeout.
1097    Timeout,
1098}
1099
1100impl GpuFault {
1101    /// A stable name for logs and reports.
1102    #[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/// Typed decoder failure.
1115///
1116/// Damage the decoder policy skips is reported through diagnostics, not as an error; damage it
1117/// does not skip is an adapter failure.
1118#[derive(Clone, Debug, Eq, PartialEq)]
1119#[non_exhaustive]
1120pub enum DecodeError {
1121    /// The operation was cancelled.
1122    Cancelled,
1123    /// The requested stream or timestamp is outside the resource.
1124    OutOfRange,
1125    /// The adapter does not support this media representation.
1126    Unsupported(String),
1127    /// Adapter-specific failure, represented as stable text rather than a platform type.
1128    Adapter(String),
1129    /// A GPU call failed; `message` names the call and its platform status.
1130    Gpu {
1131        /// What the status says about the device.
1132        fault: GpuFault,
1133        /// The failed call and its platform status.
1134        message: String,
1135    },
1136    /// The source's bytes could not be read, outside the decoder: a remote source that was
1137    /// refused, changed or could not be reached.
1138    Source(SourceFailure),
1139}
1140
1141/// Why a source's bytes could not be read, as the host protocol answers it.
1142#[derive(Clone, Debug, Eq, PartialEq)]
1143pub struct SourceFailure {
1144    /// The protocol code, such as `MEDIA_CHANGED` or `MEDIA_UNREACHABLE`.
1145    pub code: &'static str,
1146    /// What failed, naming the source without credentials.
1147    pub message: String,
1148    /// The source's URL without user info, query or fragment.
1149    pub url: Option<String>,
1150    /// The status the server answered, when it answered.
1151    pub status: Option<u16>,
1152    /// How long a busy server asks to wait, in milliseconds.
1153    pub retry_after_ms: Option<u64>,
1154    /// The operator rule that refused the source.
1155    pub policy: Option<&'static str>,
1156}
1157
1158/// Why an encoder did not open, as far as its own status and log say.
1159#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
1160pub enum OpenFailureKind {
1161    /// The machine lacks the device, driver or transform; retrying will not help.
1162    Absent,
1163    /// All sessions are taken (such as an NVENC session limit); retrying after another export
1164    /// ends can succeed.
1165    Busy,
1166    /// The encoder runs here but refuses this output's size, pixels or options.
1167    Unsuitable,
1168    /// Nothing typed says which.
1169    Unknown,
1170}
1171
1172impl OpenFailureKind {
1173    /// A stable name for logs and reports.
1174    #[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/// One encoder that did not open, and why.
1186#[derive(Clone, Debug, Eq, PartialEq)]
1187pub struct EncoderRefusal {
1188    /// The encoder, as `FFmpeg` names it (`h264_nvenc`).
1189    pub encoder: String,
1190    /// Whether it was tried on the GPU.
1191    pub hardware_accelerated: bool,
1192    /// What the refusal is evidence of.
1193    pub kind: OpenFailureKind,
1194    /// The encoder's own words, with the log lines it wrote.
1195    pub reason: String,
1196}
1197
1198impl DecodeError {
1199    /// Returns whether the decoder must be discarded instead of retried.
1200    #[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
1225/// Stateful media decoder implemented by a platform binding.
1226pub trait Decoder {
1227    /// Returns deterministic stream metadata and stream selection.
1228    fn streams(&self) -> &[StreamInfo];
1229    /// Flushes queued packets and frames without changing stream selection.
1230    ///
1231    /// # Errors
1232    /// Returns a platform-neutral adapter failure when flushing fails.
1233    fn flush(&mut self) -> Result<(), DecodeError>;
1234    /// Seeks and returns what is presented at the request's time.
1235    ///
1236    /// For video this is the last frame at or before the time plus the stream's
1237    /// [`alpha2_time::presentation_slack`], which absorbs timestamp rounding. Finding it
1238    /// decodes the following frame, which the next [`Self::decode_next`] returns. Times before
1239    /// the first frame return the first, times after the last return the last, and a stream
1240    /// without frames is [`DecodeError::OutOfRange`]. For audio it is the block holding the
1241    /// time's sample.
1242    ///
1243    /// # Errors
1244    /// Returns cancellation, range, unsupported-media, or adapter failures.
1245    fn seek(
1246        &mut self,
1247        request: DecodeRequest,
1248        cancel: &CancelToken,
1249    ) -> Result<DecodeResult, DecodeError>;
1250    /// Advances packet draining by one observable event.
1251    ///
1252    /// # Errors
1253    /// Returns cancellation, unsupported-media, or adapter failures.
1254    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError>;
1255}
1256
1257/// A provider's answer to one request: source samples and whether the source extends past them.
1258#[derive(Clone, Copy, Debug, PartialEq)]
1259pub struct AudioSpan<'a> {
1260    /// Source samples at the project rate, read by their own `start_sample`.
1261    pub block: &'a AudioBlock,
1262    /// Whether the source has no samples before `block.start_sample`.
1263    pub starts_source: bool,
1264    /// Whether the source has no samples from `block.end_sample()` on.
1265    pub ends_source: bool,
1266}
1267
1268impl<'a> AudioSpan<'a> {
1269    /// A block holding the source's entire audio.
1270    #[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    /// Whether every sample of `[start, end)` is in the block or in silence implied by
1280    /// [`Self::starts_source`] or [`Self::ends_source`].
1281    #[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
1288/// Retrieves project-rate planar audio without exposing its backing cache.
1289pub trait AudioBlockProvider {
1290    /// Returns source samples `[start_sample, start_sample + frames)` at the
1291    /// project rate, as a span that [covers](AudioSpan::covers) all of them.
1292    ///
1293    /// The block may extend past the request. Outside the source's audio the provider either
1294    /// holds zeros or sets [`AudioSpan::starts_source`] / [`AudioSpan::ends_source`]. A provider
1295    /// that cannot yet cover the request returns `None` or a non-covering span, and the mixer
1296    /// reports the source missing rather than mixing silence.
1297    ///
1298    /// `stream` counts over the source's audio streams in container order; `None` is the stream
1299    /// the host plays by default.
1300    fn block(
1301        &self,
1302        source: &SourceId,
1303        stream: Option<u32>,
1304        start_sample: i64,
1305        frames: usize,
1306    ) -> Option<AudioSpan<'_>>;
1307}
1308
1309/// Receives project-rate planar audio from offline or realtime graph hosts.
1310pub trait AudioBlockSink {
1311    /// Writes one monotonic audio block.
1312    ///
1313    /// # Errors
1314    /// Returns a platform-neutral encode error on cancellation, invalid timing,
1315    /// or host failure.
1316    fn write_audio(&mut self, block: &AudioBlock, cancel: &CancelToken) -> Result<(), EncodeError>;
1317
1318    /// Drains and commits the sink.
1319    ///
1320    /// # Errors
1321    /// Returns cancellation or host failures; success means all delayed
1322    /// samples were committed.
1323    fn finish_audio(&mut self, cancel: &CancelToken) -> Result<(), EncodeError>;
1324
1325    /// Discards partial output.
1326    ///
1327    /// # Errors
1328    /// Returns an error when cleanup fails.
1329    fn abort_audio(&mut self) -> Result<(), EncodeError>;
1330}
1331
1332/// One input accepted by an encoding/mux adapter.
1333#[derive(Clone, Debug, PartialEq)]
1334pub enum EncodeEvent {
1335    /// Premultiplied rendered video.
1336    Video(DecodedVideoFrame),
1337    /// Project-rate planar audio.
1338    Audio(AudioBlock),
1339}
1340
1341/// Typed encoding failure.
1342#[derive(Clone, Debug, Eq, PartialEq)]
1343#[non_exhaustive]
1344pub enum EncodeError {
1345    /// The operation was cancelled; partial output must be removed by policy.
1346    Cancelled,
1347    /// Input timestamps violated monotonic/interleave requirements.
1348    InvalidTimestamp,
1349    /// Adapter failure without leaking a platform error type.
1350    Adapter(String),
1351    /// The output file could not be created or claimed. Nothing was encoded.
1352    Output(String),
1353    /// Another live export, in any process, holds the output's partial file. Nothing was
1354    /// encoded.
1355    OutputInUse(String),
1356    /// The output was encoded but could not be moved to its final path. The finished file is
1357    /// kept beside the target under another name.
1358    Publish {
1359        /// The target, the step that failed and the operating system's error.
1360        message: String,
1361        /// Where the finished file is now; `None` when that move also failed.
1362        kept: Option<std::path::PathBuf>,
1363    },
1364    /// The encoder refused an input frame on a still-usable device; another path may succeed.
1365    EncoderRejected {
1366        /// The encoder that refused, as `FFmpeg` names it (`h264_d3d12va`).
1367        encoder: String,
1368        /// The frame it refused, counted from 0 in the order frames were sent.
1369        frame: u64,
1370        /// The encoder's message and session state.
1371        message: String,
1372    },
1373    /// A GPU call failed; `message` names the call and its platform status.
1374    Gpu {
1375        /// What the status says about the device.
1376        fault: GpuFault,
1377        /// The failed call and its platform status.
1378        message: String,
1379    },
1380    /// No encoder candidate opened. Each refusal's kind tells whether retrying can help.
1381    EncodersRefused {
1382        /// Every candidate's refusal, in the order they were tried.
1383        message: String,
1384        /// The refusals themselves, most preferred candidate first.
1385        refusals: Vec<EncoderRefusal>,
1386    },
1387}
1388
1389impl EncodeError {
1390    /// A timed-out GPU wait for `what`, carrying [`GPU_TIMEOUT_MESSAGE`].
1391    #[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
1435/// Host encoding and muxing boundary.
1436pub trait EncodeSink {
1437    /// Queues one timestamped media item.
1438    ///
1439    /// # Errors
1440    /// Returns cancellation, invalid timestamp, or adapter failures.
1441    fn write(&mut self, event: EncodeEvent, cancel: &CancelToken) -> Result<(), EncodeError>;
1442    /// Drains encoder delay, interleaves remaining packets, and writes the trailer.
1443    ///
1444    /// # Errors
1445    /// Returns cancellation or adapter failures; success means the trailer exists.
1446    fn finish(&mut self, cancel: &CancelToken) -> Result<(), EncodeError>;
1447    /// Aborts and applies the adapter's partial-output cleanup policy.
1448    ///
1449    /// # Errors
1450    /// Returns an adapter failure if partial output could not be cleaned up.
1451    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        // The declared ratio is the simplest one that rounds to the display size.
1466        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        // Whatever it finds rounds to the size shown.
1475        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        // Math.round(128 * 4 / 3) = 171, and a narrow pixel stretches the height.
1489        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        // Half a pixel rounds up: 3 * 3 / 2 = 4.5.
1494        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        // Unused (0x200), ambisonic (0x400 and up) and user channels name no speaker.
1536        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}