Skip to main content

alpha2_native/
convert.rs

1//! Frame conversion, colour mapping, and codec options.
2
3use crate::capabilities::{NativeEncoderClass, encoder_class};
4use alpha2_ffmpeg_bridge::{DecodedFrame, DisplayRotation, PackedScaler};
5use std::ffi::{CStr, CString};
6
7use alpha2_media::{
8    ChromaLocation, ColorMatrix, ColorMetadata, ColorPrimaries, ColorRange, Container, DecodeError,
9    DecodedVideoFrame, EncodeError, Orientation, PixelFormat, Plane, Rect, Rotation,
10    SampleAspectRatio, TransferFunction, YuvFormat,
11};
12use alpha2_time::{MediaTime, TICKS_PER_SECOND};
13use rsmpeg::avcodec::AVCodec;
14use rsmpeg::avutil::{AVDictionary, AVFrame, AVRational, av_rescale_q, ra};
15use rsmpeg::ffi;
16
17#[allow(clippy::too_many_lines)]
18pub(crate) fn convert_video_frame(
19    frame: &DecodedFrame,
20    codec: ffi::AVCodecID,
21    time_base: AVRational,
22    color: ColorMetadata,
23    scaler: &mut FrameScaler,
24) -> Result<DecodedVideoFrame, DecodeError> {
25    let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
26    let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
27    let pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
28        frame.pts
29    } else {
30        frame.best_effort_timestamp
31    };
32    let visible_rect = Rect {
33        x: u32::try_from(frame.crop_left).unwrap_or(0),
34        y: u32::try_from(frame.crop_top).unwrap_or(0),
35        width: width.saturating_sub(
36            u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
37        ),
38        height: height.saturating_sub(
39            u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
40        ),
41    };
42    check_frame_size(width, height)?;
43    // YCbCr layouts the renderer samples go as planes (shared when fully written, else copied); the
44    // GPU applies subsampling, depth, crop, rotation and aspect ratio.
45    if let Some(planes) = frame.yuv_planes().map_err(adapter_error)? {
46        let layout = planes.layout;
47        return Ok(DecodedVideoFrame {
48            pts: timestamp(pts, time_base).ok_or(DecodeError::OutOfRange)?,
49            dts: None,
50            duration: timestamp(frame.duration, time_base),
51            visible_rect,
52            sample_aspect_ratio: declared_sar(frame.sample_aspect_ratio).unwrap_or_default(),
53            orientation: Orientation::UPRIGHT,
54            pixel_format: PixelFormat::Yuv(YuvFormat {
55                chroma_shift_x: layout.chroma_shift_x,
56                chroma_shift_y: layout.chroma_shift_y,
57                bit_depth: layout.bit_depth,
58                interleaved_chroma: layout.interleaved_chroma,
59                msb_aligned: layout.msb_aligned,
60                alpha: false,
61            }),
62            chroma_location: decoded_chroma_location(codec, frame.chroma_location),
63            color: Some(color),
64            planes: planes
65                .planes
66                .into_iter()
67                .map(|plane| Plane {
68                    bytes: plane.bytes,
69                    stride: plane.stride,
70                    width: plane.width,
71                    height: plane.height,
72                })
73                .collect(),
74        });
75    }
76    let (pixel_format, planes, color) = if converts_like_rgba8(color) {
77        (
78            PixelFormat::Rgba8,
79            vec![rgba8_plane(frame, color, scaler)?],
80            color,
81        )
82    } else {
83        full_resolution_planes(frame, color, scaler)?
84    };
85    Ok(DecodedVideoFrame {
86        pts: timestamp(pts, time_base).ok_or(DecodeError::OutOfRange)?,
87        dts: None,
88        duration: timestamp(frame.duration, time_base),
89        visible_rect,
90        sample_aspect_ratio: declared_sar(frame.sample_aspect_ratio).unwrap_or_default(),
91        orientation: Orientation::UPRIGHT,
92        pixel_format,
93        // Neither layout is subsampled.
94        chroma_location: ChromaLocation::Unspecified,
95        color: Some(color),
96        planes,
97    })
98}
99
100/// Whether an unsampleable frame of `color` may reach the renderer as 8-bit sRGB RGBA: SDR BT.709,
101/// where conversion is matrix and range alone. Other frames keep their components so the renderer
102/// can still tone-map, convert gamut, or refuse them.
103fn converts_like_rgba8(color: ColorMetadata) -> bool {
104    !color.is_hdr() && color.primaries == ColorPrimaries::Bt709
105}
106
107/// Converts `frame` to one plane of straight 8-bit RGBA with `color`'s matrix and range.
108fn rgba8_plane(
109    frame: &AVFrame,
110    color: ColorMetadata,
111    scaler: &mut FrameScaler,
112) -> Result<Plane, DecodeError> {
113    let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
114    let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
115    let active = scaler.for_frame(frame, ffi::AV_PIX_FMT_RGBA)?;
116    configure_yuv_to_rgba(active, color).map_err(adapter_error)?;
117    let bytes = active.convert(frame).map_err(adapter_error)?;
118    if bytes.len() != packed_len(width, height, 4)? {
119        return Err(DecodeError::OutOfRange);
120    }
121    Ok(Plane {
122        bytes: bytes.into(),
123        stride: width.saturating_mul(4),
124        width,
125        height,
126    })
127}
128
129/// Repacks `frame` into 4:4:4 planes at its own depth (alpha last) without converting color, tagged
130/// with the identity matrix. Staying at its own depth avoids swscale's inexact depth rescaling.
131fn full_resolution_planes(
132    frame: &AVFrame,
133    color: ColorMetadata,
134    scaler: &mut FrameScaler,
135) -> Result<(PixelFormat, Vec<Plane>, ColorMetadata), DecodeError> {
136    let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
137    let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
138    let profile = alpha2_ffmpeg_bridge::sample_profile(frame.format)
139        .ok_or_else(|| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))?;
140    let depth = match profile.bit_depth {
141        0..=8 => 8,
142        9..=10 => 10,
143        11..=12 => 12,
144        _ => 16,
145    };
146    let target = planar_444_format(profile.is_rgb, profile.has_alpha, depth);
147    let active = scaler.for_frame(frame, target)?;
148    if !profile.is_rgb {
149        // Same matrix and range on both sides: swscale changes only depth, subsampling and layout.
150        let coefficients = sws_coefficients(color.matrix);
151        let full = color.range == ColorRange::Full;
152        active
153            .configure_colorspace(coefficients, full, coefficients, full)
154            .map_err(adapter_error)?;
155    }
156    let plane_count = if profile.has_alpha { 4 } else { 3 };
157    let sample_bytes = if depth > 8 { 2 } else { 1 };
158    let plane_len = packed_len(width, height, sample_bytes)?;
159    let bytes = active.convert(frame).map_err(adapter_error)?;
160    if bytes.len() != plane_len * plane_count {
161        return Err(DecodeError::OutOfRange);
162    }
163    let bytes = bytes::Bytes::from(bytes);
164    let stride = width.saturating_mul(u32::try_from(sample_bytes).unwrap_or(2));
165    let plane = |index: usize| Plane {
166        bytes: bytes.slice(index * plane_len..(index + 1) * plane_len),
167        stride,
168        width,
169        height,
170    };
171    // `gbrp` stores green, blue, red; the identity matrix reads red, green, blue.
172    let order: &[usize] = if profile.is_rgb {
173        &[2, 0, 1]
174    } else {
175        &[0, 1, 2]
176    };
177    let mut planes = order.iter().map(|&index| plane(index)).collect::<Vec<_>>();
178    if profile.has_alpha {
179        planes.push(plane(3));
180    }
181    let format = YuvFormat::planar(0, 0, depth);
182    let format = if profile.has_alpha {
183        format.with_alpha()
184    } else {
185        format
186    };
187    let color = if profile.is_rgb {
188        ColorMetadata {
189            matrix: ColorMatrix::Rgb,
190            range: ColorRange::Full,
191            ..color
192        }
193    } else {
194        color
195    };
196    Ok((PixelFormat::Yuv(format), planes, color))
197}
198
199/// The planar 4:4:4 format for RGB or YCbCr, with or without alpha, at
200/// `depth` in native byte order.
201const fn planar_444_format(rgb: bool, alpha: bool, depth: u8) -> ffi::AVPixelFormat {
202    match (rgb, alpha, depth) {
203        (true, false, 8) => ffi::AV_PIX_FMT_GBRP,
204        (true, true, 8) => ffi::AV_PIX_FMT_GBRAP,
205        (true, false, 10) => ffi::AV_PIX_FMT_GBRP10LE,
206        (true, true, 10) => ffi::AV_PIX_FMT_GBRAP10LE,
207        (true, false, 12) => ffi::AV_PIX_FMT_GBRP12LE,
208        (true, true, 12) => ffi::AV_PIX_FMT_GBRAP12LE,
209        (true, false, _) => ffi::AV_PIX_FMT_GBRP16LE,
210        (true, true, _) => ffi::AV_PIX_FMT_GBRAP16LE,
211        (false, false, 8) => ffi::AV_PIX_FMT_YUV444P,
212        (false, true, 8) => ffi::AV_PIX_FMT_YUVA444P,
213        (false, false, 10) => ffi::AV_PIX_FMT_YUV444P10LE,
214        (false, true, 10) => ffi::AV_PIX_FMT_YUVA444P10LE,
215        (false, false, 12) => ffi::AV_PIX_FMT_YUV444P12LE,
216        (false, true, 12) => ffi::AV_PIX_FMT_YUVA444P12LE,
217        (false, false, _) => ffi::AV_PIX_FMT_YUV444P16LE,
218        (false, true, _) => ffi::AV_PIX_FMT_YUVA444P16LE,
219    }
220}
221
222/// The scaler a stream's frames convert with, kept while size and format stay the same.
223///
224/// `sws_getCachedContext` would remake it every frame here, because `FFmpeg` rewrites the stored
225/// flags and source format during init (full chroma interpolation, `RGB0`-style alpha twins).
226#[derive(Default)]
227pub(crate) struct FrameScaler {
228    context: Option<(ScalerShape, PackedScaler)>,
229    made: u64,
230}
231
232#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233struct ScalerShape {
234    width: i32,
235    height: i32,
236    source: ffi::AVPixelFormat,
237    target: ffi::AVPixelFormat,
238}
239
240impl FrameScaler {
241    /// The scaler from `frame`'s size and format to `target`, remade only when those change.
242    fn for_frame(
243        &mut self,
244        frame: &AVFrame,
245        target: ffi::AVPixelFormat,
246    ) -> Result<&mut PackedScaler, DecodeError> {
247        let shape = ScalerShape {
248            width: frame.width,
249            height: frame.height,
250            source: frame.format,
251            target,
252        };
253        if self
254            .context
255            .as_ref()
256            .is_none_or(|(made_for, _)| *made_for != shape)
257        {
258            self.context = None;
259            let context = PackedScaler::new(frame.width, frame.height, frame.format, target)
260                .map_err(|_| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))?;
261            self.made += 1;
262            self.context = Some((shape, context));
263        }
264        self.context
265            .as_mut()
266            .map(|(_, context)| context)
267            .ok_or_else(|| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))
268    }
269
270    #[cfg(test)]
271    pub(crate) const fn made(&self) -> u64 {
272        self.made
273    }
274
275    #[cfg(test)]
276    pub(crate) const fn is_empty(&self) -> bool {
277        self.context.is_none()
278    }
279}
280
281fn packed_len(width: u32, height: u32, sample_bytes: usize) -> Result<usize, DecodeError> {
282    usize::try_from(width)
283        .ok()
284        .and_then(|width| {
285            usize::try_from(height)
286                .ok()
287                .and_then(|height| width.checked_mul(height))
288        })
289        .and_then(|pixels| pixels.checked_mul(sample_bytes))
290        .ok_or(DecodeError::OutOfRange)
291}
292
293/// Where the chroma of a `codec` stream or frame sits, given what `FFmpeg` reports.
294///
295/// H.264 infers location type 0 (left) when the SPS declares none (E.2.1), but `FFmpeg` reports
296/// unspecified, which the renderer samples centred for 4:2:0. HEVC 4:2:0 already reports left;
297/// unspecified 4:2:2 and 4:1:1 the renderer reads as left by itself.
298pub(crate) fn decoded_chroma_location(
299    codec: ffi::AVCodecID,
300    location: ffi::AVChromaLocation,
301) -> ChromaLocation {
302    if codec == ffi::AV_CODEC_ID_H264 && location == ffi::AVCHROMA_LOC_UNSPECIFIED {
303        ChromaLocation::Left
304    } else {
305        chroma_location(location)
306    }
307}
308
309pub(crate) fn chroma_location(location: ffi::AVChromaLocation) -> ChromaLocation {
310    match location {
311        ffi::AVCHROMA_LOC_LEFT => ChromaLocation::Left,
312        ffi::AVCHROMA_LOC_CENTER => ChromaLocation::Center,
313        ffi::AVCHROMA_LOC_TOPLEFT => ChromaLocation::TopLeft,
314        _ => ChromaLocation::Unspecified,
315    }
316}
317
318/// Sets `scaler` to convert full-range RGB into `color`'s YCbCr matrix and range.
319pub(crate) fn configure_rgba_to_yuv(
320    scaler: &mut PackedScaler,
321    color: ColorMetadata,
322) -> Result<(), alpha2_ffmpeg_bridge::BridgeError> {
323    scaler.configure_colorspace(
324        i32::try_from(ffi::SWS_CS_ITU709).expect("color coefficient fits i32"),
325        true,
326        sws_coefficients(color.matrix),
327        color.range == ColorRange::Full,
328    )
329}
330
331/// Sets `scaler` to convert `color`'s YCbCr matrix and range into full-range RGB.
332pub(crate) fn configure_yuv_to_rgba(
333    scaler: &mut PackedScaler,
334    color: ColorMetadata,
335) -> Result<(), alpha2_ffmpeg_bridge::BridgeError> {
336    scaler.configure_colorspace(
337        sws_coefficients(color.matrix),
338        color.range == ColorRange::Full,
339        i32::try_from(ffi::SWS_CS_ITU709).expect("color coefficient fits i32"),
340        true,
341    )
342}
343
344pub(crate) fn sws_coefficients(matrix: ColorMatrix) -> i32 {
345    let value = match matrix {
346        ColorMatrix::Bt601 => ffi::SWS_CS_ITU601,
347        ColorMatrix::Bt709 | ColorMatrix::Rgb => ffi::SWS_CS_ITU709,
348        ColorMatrix::Bt2020Ncl => ffi::SWS_CS_BT2020,
349    };
350    i32::try_from(value).expect("color coefficient fits i32")
351}
352
353/// The engine's tick clock as an `FFmpeg` time base.
354pub(crate) fn tick_base() -> AVRational {
355    ra(
356        1,
357        i32::try_from(TICKS_PER_SECOND).expect("tick rate fits i32"),
358    )
359}
360
361/// `frame` as an encoder `AVFrame` built from its own planes, or `None` when it is not I420.
362///
363/// # Errors
364/// For an I420 frame that is cropped or not `width`x`height`.
365pub(crate) fn direct_yuv420p_frame(
366    frame: &DecodedVideoFrame,
367    width: i32,
368    height: i32,
369) -> Result<Option<AVFrame>, EncodeError> {
370    if frame.pixel_format != PixelFormat::Yuv(YuvFormat::I420) {
371        return Ok(None);
372    }
373    if frame.planes.len() != 3
374        || frame.visible_rect.x != 0
375        || frame.visible_rect.y != 0
376        || frame.planes[0].width != u32::try_from(width).unwrap_or(0)
377        || frame.planes[0].height != u32::try_from(height).unwrap_or(0)
378    {
379        return Err(EncodeError::Adapter(
380            "direct YUV encoder input must contain one uncropped coded frame".into(),
381        ));
382    }
383    alpha2_ffmpeg_bridge::yuv420p_frame(
384        &frame.planes[0].bytes,
385        frame.planes[0].stride,
386        &frame.planes[1].bytes,
387        frame.planes[1].stride,
388        &frame.planes[2].bytes,
389        frame.planes[2].stride,
390        width,
391        height,
392    )
393    .map(Some)
394    .map_err(encode_adapter_error)
395}
396
397/// Turns a decoded YUV frame of any layout into the encoder's 8-bit 4:2:0.
398///
399/// `Y'CbCr` keeps its codes and colour, changing only depth and chroma resolution. RGB planes
400/// (identity matrix) are converted into the output's matrix and range like RGBA, gamut untouched.
401/// Alpha is dropped. One stream's frames share one scaler.
402pub(crate) struct Yuv420pConverter {
403    output: ColorMetadata,
404    scaler: Option<(ffi::AVPixelFormat, u32, u32, PackedScaler)>,
405}
406
407impl Yuv420pConverter {
408    /// A converter into 4:2:0 of `output`'s matrix and range.
409    pub(crate) const fn new(output: ColorMetadata) -> Self {
410        Self {
411            output,
412            scaler: None,
413        }
414    }
415
416    /// `frame` as YUV420P, `None` for a frame that is not YUV.
417    ///
418    /// # Errors
419    /// For a cropped frame, a size other than the encoder's, or a layout `FFmpeg` cannot represent.
420    pub(crate) fn convert(
421        &mut self,
422        frame: &DecodedVideoFrame,
423        width: i32,
424        height: i32,
425    ) -> Result<Option<AVFrame>, EncodeError> {
426        let PixelFormat::Yuv(format) = frame.pixel_format else {
427            return Ok(None);
428        };
429        let rgb = frame
430            .color
431            .is_some_and(|color| color.matrix == ColorMatrix::Rgb);
432        if format == YuvFormat::I420 && !rgb {
433            return direct_yuv420p_frame(frame, width, height);
434        }
435        let (width, height) = (
436            u32::try_from(width).unwrap_or(0),
437            u32::try_from(height).unwrap_or(0),
438        );
439        let stored = if format.interleaved_chroma { 2 } else { 3 };
440        if frame.visible_rect.x != 0
441            || frame.visible_rect.y != 0
442            || frame.planes.len() < stored
443            || frame.planes[0].width != width
444            || frame.planes[0].height != height
445        {
446            return Err(EncodeError::Adapter(
447                "YUV encoder input must contain one uncropped frame of the encoder's size".into(),
448            ));
449        }
450        let (source_format, planes) = if rgb {
451            if format.chroma_shift_x != 0
452                || format.chroma_shift_y != 0
453                || format.interleaved_chroma
454                || format.msb_aligned
455                || !matches!(format.bit_depth, 8 | 10 | 12 | 16)
456            {
457                return Err(EncodeError::Adapter(format!(
458                    "no FFmpeg pixel format stores red, green, and blue as {format:?}"
459                )));
460            }
461            // `gbrp` stores green, blue, red; the identity matrix's planes are red, green, blue.
462            let planes = [1, 2, 0]
463                .iter()
464                .map(|&index: &usize| (&frame.planes[index].bytes[..], frame.planes[index].stride))
465                .collect::<Vec<_>>();
466            (planar_444_format(true, false, format.bit_depth), planes)
467        } else {
468            let layout = alpha2_ffmpeg_bridge::YuvPlaneLayout {
469                chroma_shift_x: format.chroma_shift_x,
470                chroma_shift_y: format.chroma_shift_y,
471                bit_depth: format.bit_depth,
472                interleaved_chroma: format.interleaved_chroma,
473                msb_aligned: format.msb_aligned,
474            };
475            let source_format =
476                alpha2_ffmpeg_bridge::yuv_pixel_format(layout).ok_or_else(|| {
477                    EncodeError::Adapter(format!("no FFmpeg pixel format stores {format:?}"))
478                })?;
479            let planes = frame.planes[..stored]
480                .iter()
481                .map(|plane| (&plane.bytes[..], plane.stride))
482                .collect::<Vec<_>>();
483            (source_format, planes)
484        };
485        let source = alpha2_ffmpeg_bridge::planar_frame(source_format, &planes, width, height)
486            .map_err(encode_adapter_error)?;
487        if self
488            .scaler
489            .as_ref()
490            .is_none_or(|(cached, w, h, _)| (*cached, *w, *h) != (source_format, width, height))
491        {
492            let (signed_width, signed_height) = (
493                i32::try_from(width).map_err(|_| EncodeError::Adapter("width overflow".into()))?,
494                i32::try_from(height)
495                    .map_err(|_| EncodeError::Adapter("height overflow".into()))?,
496            );
497            let mut scaler = PackedScaler::new(
498                signed_width,
499                signed_height,
500                source_format,
501                ffi::AV_PIX_FMT_YUV420P,
502            )
503            .map_err(|_| EncodeError::Adapter("cannot create a YUV to YUV420P scaler".into()))?;
504            if rgb {
505                configure_rgba_to_yuv(&mut scaler, self.output).map_err(encode_adapter_error)?;
506            }
507            self.scaler = Some((source_format, width, height, scaler));
508        }
509        let Some((_, _, _, scaler)) = self.scaler.as_mut() else {
510            unreachable!("the scaler was just made");
511        };
512        let output = scaler
513            .convert_to_frame(&source)
514            .map_err(encode_adapter_error)?;
515        Ok(Some(output))
516    }
517}
518
519/// `value` in `base` as engine ticks; `None` for `AV_NOPTS_VALUE` or an invalid base.
520pub(crate) fn timestamp(value: i64, base: AVRational) -> Option<MediaTime> {
521    (value != ffi::AV_NOPTS_VALUE && base.den > 0)
522        .then(|| MediaTime::from_ticks(av_rescale_q(value, base, tick_base())))
523}
524
525/// A declared pixel aspect ratio in lowest terms, or `None` when undeclared (`FFmpeg` uses a
526/// numerator of zero or less, and 0/1 by default).
527pub(crate) fn declared_sar(value: AVRational) -> Option<SampleAspectRatio> {
528    SampleAspectRatio::new(
529        u64::try_from(value.num).ok()?,
530        u64::try_from(value.den).ok()?,
531    )
532}
533
534/// A stream's pixel aspect ratio by `av_guess_sample_aspect_ratio`'s rule: the container's, else
535/// the pictures' (codec parameters, or a decoded picture's own), else square.
536pub(crate) fn guess_sar(container: AVRational, pictures: AVRational) -> SampleAspectRatio {
537    declared_sar(container)
538        .or_else(|| declared_sar(pictures))
539        .unwrap_or_default()
540}
541
542/// The rotation a stream's legacy `rotate` metadata tag declares, `Deg0` without one.
543pub(crate) fn stream_rotation(metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>) -> Rotation {
544    let Some(metadata) = metadata else {
545        return Rotation::Deg0;
546    };
547    let Some(entry) = metadata.get(c"rotate", None, 0) else {
548        return Rotation::Deg0;
549    };
550    match entry
551        .value()
552        .to_string_lossy()
553        .parse::<i32>()
554        .unwrap_or(0)
555        .rem_euclid(360)
556    {
557        90 => Rotation::Deg90,
558        180 => Rotation::Deg180,
559        270 => Rotation::Deg270,
560        _ => Rotation::Deg0,
561    }
562}
563
564/// The clockwise [`Rotation`] for `FFmpeg`'s counter-clockwise display angle.
565///
566/// `FFmpeg`'s angle turns the other way, so `-display_rotation 90` shows turned 270 degrees.
567pub(crate) fn rotation_from_display(counter_clockwise: f64) -> Option<Rotation> {
568    let normalized = (-counter_clockwise).rem_euclid(360.0);
569    if !(0.5..359.5).contains(&normalized) {
570        Some(Rotation::Deg0)
571    } else if (normalized - 90.0).abs() < 0.5 {
572        Some(Rotation::Deg90)
573    } else if (normalized - 180.0).abs() < 0.5 {
574        Some(Rotation::Deg180)
575    } else if (normalized - 270.0).abs() < 0.5 {
576        Some(Rotation::Deg270)
577    } else {
578        None
579    }
580}
581
582/// The [`Orientation`] a display matrix declares; `None` for an angle that is not a multiple of 90.
583///
584/// `FFmpeg` reads a mirroring matrix as rotation then horizontal flip, which equals flipping before
585/// the opposite turn: Exif `Orientation` 5 is a mirror turned 270 degrees.
586pub(crate) fn orientation_from_display(display: DisplayRotation) -> Option<Orientation> {
587    if display.flipped {
588        rotation_from_display(-display.counter_clockwise_degrees).map(|rotation| Orientation {
589            rotation,
590            mirror: true,
591        })
592    } else {
593        rotation_from_display(display.counter_clockwise_degrees).map(Orientation::rotated)
594    }
595}
596
597/// The display matrix for `orientation`, the inverse of [`orientation_from_display`];
598/// `None` when shown as stored.
599pub(crate) fn display_of(orientation: Orientation) -> Option<DisplayRotation> {
600    if orientation == Orientation::default() {
601        return None;
602    }
603    let clockwise = match orientation.rotation {
604        Rotation::Deg0 => 0.0,
605        Rotation::Deg90 => 90.0,
606        Rotation::Deg180 => 180.0,
607        Rotation::Deg270 => 270.0,
608    };
609    Some(DisplayRotation {
610        counter_clockwise_degrees: if orientation.mirror {
611            clockwise
612        } else {
613            -clockwise
614        },
615        flipped: orientation.mirror,
616    })
617}
618
619/// `hvc1`: an HEVC sample entry with all parameter sets in its `hvcC`.
620const HVC1: u32 = u32::from_le_bytes(*b"hvc1");
621/// `hev1`: parameter sets may also be in the stream.
622const HEV1: u32 = u32::from_le_bytes(*b"hev1");
623
624/// The `FFmpeg` muxer that writes `container`.
625pub(crate) const fn muxer_name(container: Container) -> &'static CStr {
626    match container {
627        Container::Mp4 => c"mp4",
628        Container::Mov => c"mov",
629        Container::Mkv => c"matroska",
630        Container::Webm => c"webm",
631    }
632}
633
634/// The options `container`'s muxer writes its header with.
635///
636/// Matroska and `WebM` get `fflags=+bitexact`, since otherwise `matroskaenc` writes random track
637/// and segment UIDs and a versioned writing application. MP4 and MOV are deterministic already.
638pub(crate) fn muxer_header_options(container: Container) -> Option<AVDictionary> {
639    matches!(container, Container::Mkv | Container::Webm)
640        .then(|| AVDictionary::new(c"fflags", c"+bitexact", 0))
641}
642
643/// The codec tag a stream of `codec_id` carrying `tag` is written to `container` with.
644///
645/// MP4 and MOV: encoded HEVC is `hvc1` (what browsers and Apple players expect), a copied HEVC
646/// stream keeps its entry, other copied streams are cleared for the muxer to pick, and encoded
647/// streams keep the encoder's tag. Matroska and `WebM` always clear it, since a foreign fourcc can
648/// make the muxer refuse the stream.
649pub(crate) fn container_codec_tag(
650    container: Container,
651    codec_id: ffi::AVCodecID,
652    tag: u32,
653    copied: bool,
654) -> u32 {
655    if matches!(container, Container::Mkv | Container::Webm) {
656        0
657    } else if codec_id == ffi::AV_CODEC_ID_HEVC {
658        if tag == HVC1 || tag == HEV1 {
659            tag
660        } else {
661            HVC1
662        }
663    } else if copied {
664        0
665    } else {
666        tag
667    }
668}
669
670pub(crate) fn color_metadata(
671    parameters: &rsmpeg::avcodec::AVCodecParameters,
672) -> Option<ColorMetadata> {
673    map_color(
674        parameters.color_primaries,
675        parameters.color_trc,
676        parameters.color_space,
677        parameters.color_range,
678    )
679}
680
681pub(crate) fn frame_color_metadata(frame: &AVFrame) -> Option<ColorMetadata> {
682    map_color(
683        frame.color_primaries,
684        frame.color_trc,
685        frame.colorspace,
686        frame.color_range,
687    )
688}
689
690/// The color `FFmpeg`'s tags describe, `None` when all four are unspecified.
691///
692/// `FFmpeg`'s primaries, transfer and matrix values are the ITU-T H.273 code points that
693/// [`ColorMetadata::from_h273`] reads; values past 255 (`FFmpeg`'s extensions) are unrecognized.
694pub(crate) fn map_color(
695    primaries: ffi::AVColorPrimaries,
696    transfer: ffi::AVColorTransferCharacteristic,
697    matrix: ffi::AVColorSpace,
698    range: ffi::AVColorRange,
699) -> Option<ColorMetadata> {
700    let code = |value| u8::try_from(value).unwrap_or(u8::MAX);
701    let full_range = match range {
702        ffi::AVCOL_RANGE_UNSPECIFIED => None,
703        range => Some(range == ffi::AVCOL_RANGE_JPEG),
704    };
705    ColorMetadata::from_h273(code(primaries), code(transfer), code(matrix), full_range)
706}
707
708/// Options every video decoder opens with.
709///
710/// `flags=+unaligned` lets `FFmpeg` crop software frames exactly; without it a small left crop
711/// (under 64 columns of 8-bit 4:2:0) is dropped to keep planes aligned. Hardware frames keep their
712/// crop as the visible rectangle either way.
713/// Refuses a `width` x `height` frame larger than alpha2 renders.
714pub(crate) fn check_frame_size(width: u32, height: u32) -> Result<(), DecodeError> {
715    if alpha2_media::frame_size_supported(width, height) {
716        return Ok(());
717    }
718    Err(DecodeError::Unsupported(format!(
719        "a {width}x{height} frame is larger than {} pixels or {} on a side",
720        alpha2_media::MAX_FRAME_PIXELS,
721        alpha2_media::MAX_FRAME_DIMENSION
722    )))
723}
724
725/// `max_pixels` makes the decoder refuse a picture larger than alpha2 renders before allocating
726/// it, for sizes only the bitstream states and for a size change mid-stream.
727pub(crate) fn video_decoder_options(threads: i64) -> AVDictionary {
728    let max_pixels = i64::try_from(alpha2_media::MAX_FRAME_PIXELS).unwrap_or(i64::MAX);
729    AVDictionary::new_int(c"threads", threads, 0)
730        .set(c"flags", c"+unaligned", 0)
731        .set_int(c"max_pixels", max_pixels, 0)
732}
733
734/// The `FFmpeg` pixel format of `layout`.
735pub(crate) fn pixel_format(
736    layout: alpha2_media::PixelLayout,
737) -> Result<ffi::AVPixelFormat, EncodeError> {
738    pixel_format_named(layout.ffmpeg_name())
739}
740
741pub(crate) fn pixel_format_named(name: &str) -> Result<ffi::AVPixelFormat, EncodeError> {
742    Ok(match name {
743        "yuv420p" => ffi::AV_PIX_FMT_YUV420P,
744        "yuva420p" => ffi::AV_PIX_FMT_YUVA420P,
745        "yuv420p10le" => ffi::AV_PIX_FMT_YUV420P10LE,
746        "yuva420p10le" => ffi::AV_PIX_FMT_YUVA420P10LE,
747        "yuv422p" => ffi::AV_PIX_FMT_YUV422P,
748        "yuva422p" => ffi::AV_PIX_FMT_YUVA422P,
749        "yuv422p10le" => ffi::AV_PIX_FMT_YUV422P10LE,
750        "yuva422p10le" => ffi::AV_PIX_FMT_YUVA422P10LE,
751        "yuv444p" => ffi::AV_PIX_FMT_YUV444P,
752        "yuva444p" => ffi::AV_PIX_FMT_YUVA444P,
753        "yuv444p10le" => ffi::AV_PIX_FMT_YUV444P10LE,
754        "yuva444p10le" => ffi::AV_PIX_FMT_YUVA444P10LE,
755        "p010le" => ffi::AV_PIX_FMT_P010LE,
756        _ => {
757            return Err(EncodeError::Adapter(format!(
758                "pixel layout {name} has no FFmpeg pixel format"
759            )));
760        }
761    })
762}
763
764/// A reusable encoder frame for `width` x `height` pictures of `layout`, its planes in
765/// the layout's storage order.
766///
767/// # Errors
768/// Returns an error for a size that does not fit a frame or a failed allocation.
769pub fn packed_frame(
770    width: u32,
771    height: u32,
772    layout: alpha2_media::PixelLayout,
773) -> Result<alpha2_ffmpeg_bridge::Yuv420pFrameBuffer, alpha2_ffmpeg_bridge::BridgeError> {
774    let (coded_width, coded_height) = (
775        i32::try_from(width)
776            .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("width"))?,
777        i32::try_from(height)
778            .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("height"))?,
779    );
780    let format = pixel_format(layout).map_err(|_| {
781        alpha2_ffmpeg_bridge::BridgeError::InvalidInput("pixel layout has no FFmpeg format")
782    })?;
783    alpha2_ffmpeg_bridge::Yuv420pFrameBuffer::with_format(coded_width, coded_height, format)
784}
785
786pub(crate) fn prores_options(layout: alpha2_media::PixelLayout) -> Vec<(&'static CStr, String)> {
787    let mut options = vec![
788        (
789            c"profile",
790            if layout.alpha { "4444" } else { "hq" }.to_owned(),
791        ),
792        (c"vendor", "apl0".to_owned()),
793    ];
794    if layout.alpha {
795        options.push((c"alpha_bits", "16".to_owned()));
796    }
797    options
798}
799
800pub(crate) fn video_encoder_options(
801    color: ColorMetadata,
802    codec: &AVCodec,
803    on_hardware: bool,
804    threads: i64,
805    width: u32,
806) -> AVDictionary {
807    let mut options = color_options(color);
808    // A hybrid encoder is a software transform unless told otherwise, and only hybrid encoders have
809    // `hw_encoding`, so setting it elsewhere would trip `reject_unused_encode_options`.
810    if encoder_class(codec) == NativeEncoderClass::Hybrid {
811        options = options.set_int(c"hw_encoding", i64::from(on_hardware), 0);
812    }
813    if on_hardware {
814        return options;
815    }
816    let name = codec.name().to_string_lossy();
817    for (key, value) in software_encoder_profile(&name, width, threads) {
818        options = set_encoder_option(options, key, &value);
819    }
820    options.set_int(c"threads", threads, 0)
821}
822
823/// Speed and structure options per software encoder, fixed so exports are reproducible.
824///
825/// - `libvpx-vp9`: `good` deadline, `cpu-used` 4, row multithreading, one tile column per 256
826///   pixels of width, alt-ref frames over a 25-frame look-ahead. Same bytes at any thread count.
827/// - `libsvtav1`: preset 8. SVT-AV1 sizes threads from a parallelism level, set to what it would
828///   pick for `threads` cores. Above level 1 picture order depends on thread timing, so
829///   [`deterministic_encode`] forces level 1.
830fn software_encoder_profile(name: &str, width: u32, threads: i64) -> Vec<(&'static CStr, String)> {
831    match name {
832        "libvpx-vp9" => vec![
833            (c"deadline", "good".into()),
834            (c"cpu-used", "4".into()),
835            (c"row-mt", "1".into()),
836            (c"tile-columns", vp9_tile_columns_log2(width).to_string()),
837            (c"lag-in-frames", "25".into()),
838            (c"auto-alt-ref", "1".into()),
839        ],
840        "libsvtav1" => vec![
841            (c"preset", "8".into()),
842            (
843                c"svtav1-params",
844                format!(
845                    "lp={}",
846                    if deterministic_encode() {
847                        1
848                    } else {
849                        svt_av1_parallelism(threads)
850                    }
851                ),
852            ),
853        ],
854        _ => Vec::new(),
855    }
856}
857
858/// Whether `ALPHA2_DETERMINISTIC_ENCODE=1` asks for byte-identical software encodes at the cost of
859/// speed. Only `libsvtav1` needs it.
860pub(crate) fn deterministic_encode() -> bool {
861    std::env::var_os("ALPHA2_DETERMINISTIC_ENCODE").is_some_and(|value| value == "1")
862}
863
864/// libvpx `tile-columns`: log2 of the tile columns for `width`, each at least 256 pixels.
865pub(crate) fn vp9_tile_columns_log2(width: u32) -> u32 {
866    (width / 256).max(1).ilog2().min(6)
867}
868
869/// SVT-AV1's parallelism level for `threads` workers, matching its own default for that many cores
870/// (1 to 6 for 1, 2, 3-5, 6-11, 12-23, and 24+ cores).
871pub(crate) fn svt_av1_parallelism(threads: i64) -> u32 {
872    match threads {
873        ..=1 => 1,
874        2 => 2,
875        3..=5 => 3,
876        6..=11 => 4,
877        12..=23 => 5,
878        _ => 6,
879    }
880}
881
882/// Sets `key` to `value` in an encoder's options. A list-valued option already set
883/// (`svtav1-params`, `:`-separated pairs) is appended to.
884pub(crate) fn set_encoder_option(options: AVDictionary, key: &CStr, value: &str) -> AVDictionary {
885    let value = CString::new(value).unwrap_or_default();
886    if key == c"svtav1-params" && options.get(key, None, 0).is_some() {
887        let appended = CString::new(format!(":{}", value.to_string_lossy())).unwrap_or_default();
888        options.set(key, &appended, ffi::AV_DICT_APPEND)
889    } else {
890        options.set(key, &value, 0)
891    }
892}
893
894/// Returns the worker budget for one standalone software video codec context.
895///
896/// Capped at 16 workers; by default two cores are reserved for non-codec work. Exports split up to
897/// 64 workers across contexts with [`codec_thread_allocation`].
898#[must_use]
899pub fn codec_thread_budget() -> i64 {
900    i64::try_from(configured_codec_thread_budget().min(16)).unwrap_or(1)
901}
902
903/// The software-codec worker budget `ALPHA2_FFMPEG_THREADS` sets ([`codec_thread_override`]).
904///
905/// # Errors
906/// Returns the setting when it is not a positive count; the default then applies, and callers
907/// reporting the budget's origin should not call it explicit.
908pub fn configured_codec_thread_override() -> Result<Option<usize>, String> {
909    codec_thread_override(std::env::var_os("ALPHA2_FFMPEG_THREADS").as_deref())
910}
911
912/// The worker budget `setting` names: `None` unset, or a positive count clamped to 64.
913///
914/// # Errors
915/// Returns the setting, lossily as text, when it is not a positive count.
916pub fn codec_thread_override(setting: Option<&std::ffi::OsStr>) -> Result<Option<usize>, String> {
917    let Some(setting) = setting else {
918        return Ok(None);
919    };
920    setting
921        .to_str()
922        .and_then(|value| value.parse::<usize>().ok())
923        .filter(|value| *value > 0)
924        .map(|value| Some(value.min(64)))
925        .ok_or_else(|| setting.to_string_lossy().into_owned())
926}
927
928fn configured_codec_thread_budget() -> usize {
929    configured_codec_thread_override()
930        .ok()
931        .flatten()
932        .unwrap_or_else(|| {
933            codec_thread_budget_for(
934                std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
935            )
936        })
937        .clamp(1, 64)
938}
939
940/// Codec workers for an export on `hardware_threads`: all but
941/// [`codec_thread_reserve`], at least one.
942pub(crate) fn codec_thread_budget_for(hardware_threads: usize) -> usize {
943    hardware_threads
944        .saturating_sub(codec_thread_reserve(hardware_threads))
945        .max(1)
946}
947
948/// Hardware threads left to the renderer, coordinator and system: two on 16+
949/// threads, one on 6-15, none below.
950///
951/// On a 4-core/8-thread laptop with two 4K software H.264 decodes, reserving two (and an encoder
952/// floor of four) left `h264_mf` exports waiting on decode and about 50 % slower per frame.
953pub(crate) const fn codec_thread_reserve(hardware_threads: usize) -> usize {
954    match hardware_threads {
955        16.. => 2,
956        6..=15 => 1,
957        _ => 0,
958    }
959}
960
961/// What one export needs from the shared software-codec worker budget.
962#[derive(Clone, Copy, Debug, PartialEq, Eq)]
963pub struct CodecThreadRequest {
964    /// Decoder contexts the pool may run at once.
965    pub decode_concurrency: usize,
966    /// Whether decode sessions produce device-resident frames.
967    pub hardware_decode: bool,
968    /// Luma samples in the largest video source, or zero when unknown.
969    pub source_frame_pixels: u64,
970    /// Whether the video encoder draws on this budget.
971    pub software_video_encoder: bool,
972    /// Workers a software encoder runs regardless of the offer, when the picture
973    /// fixes them (`OpenH264`'s one thread per slice). The split reserves exactly
974    /// that and gives decode the rest.
975    pub encoder_fixed_threads: Option<usize>,
976}
977
978/// Luma samples one software decoder worker is sized to carry.
979const DECODE_PIXELS_PER_THREAD: u64 = 2_000_000;
980/// Smallest worker count a software decode session is given.
981const MIN_SOFTWARE_DECODER_THREADS: usize = 2;
982/// Largest worker count a software decode session is given. Frame threading stops paying above this
983/// on one stream, and extra workers only contend with the encoder.
984const MAX_SOFTWARE_DECODER_THREADS: usize = 6;
985/// Workers the software video encoder keeps on budgets of 12 or more; a third of
986/// smaller budgets ([`encoder_thread_floor`]).
987const ENCODER_THREAD_FLOOR: usize = 4;
988
989/// The encoder's floor: four, or a third of a budget under 12 so small machines'
990/// decoders are not starved.
991const fn encoder_thread_floor(total_threads: usize) -> usize {
992    let third = total_threads / 3;
993    if third < ENCODER_THREAD_FLOOR {
994        if third == 0 { 1 } else { third }
995    } else {
996        ENCODER_THREAD_FLOOR
997    }
998}
999/// `FFmpeg` workers a hardware decode session opens with, whatever the budget.
1000///
1001/// Hardware sessions decode on the device; workers only parse and submit, and each extra frame
1002/// thread holds back a packet that short cuts fill and drop. On a discrete GPU, an even share (22
1003/// workers) took nearly twice as long on a many-cut project as two to four. One worker doubles a
1004/// long source's decode time. The count changes no output byte. `VideoToolbox` and D3D12VA use
1005/// the same count unmeasured.
1006pub const HARDWARE_DECODER_THREADS: usize = 2;
1007
1008/// One export-wide software-codec allocation: `decoder_threads` per software decoder,
1009/// `hardware_decoder_threads` per hardware one, `encoder_threads` for the software encoder.
1010#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1011pub struct CodecThreadAllocation {
1012    /// Total software codec workers available to this export.
1013    pub total_threads: usize,
1014    /// Number of decoder contexts allowed to execute concurrently.
1015    pub decode_concurrency: usize,
1016    /// `FFmpeg` workers per software decoder context, including a hardware session's fallback.
1017    pub decoder_threads: i64,
1018    /// `FFmpeg` workers a hardware decode session opens with.
1019    pub hardware_decoder_threads: i64,
1020    /// `FFmpeg` worker count assigned to the software video encoder, or zero for hardware.
1021    pub encoder_threads: i64,
1022    /// Workers this allocation actually hands out, decoders plus encoder.
1023    pub allocated_threads: usize,
1024}
1025
1026/// Divides the export CPU budget across concurrently active codec contexts.
1027///
1028/// The budget is an export-wide cap and each context needs a worker, so decoder concurrency is
1029/// reduced first. Hardware video encoding does not consume this budget.
1030///
1031/// With a software encoder, which paces the run, software decoders are sized to their frame area
1032/// and the encoder takes the remainder above a floor. With a hardware encoder the even split stays,
1033/// since cutting decode workers only made decode fall behind the renderer.
1034///
1035/// Hardware decode sessions open with [`HARDWARE_DECODER_THREADS`], but their share is still
1036/// reserved for a software fallback, which also keeps the encoder's worker count (and output)
1037/// independent of how sources decode.
1038#[must_use]
1039pub fn codec_thread_allocation(request: CodecThreadRequest) -> CodecThreadAllocation {
1040    codec_thread_allocation_within(request, configured_codec_thread_budget())
1041}
1042
1043/// [`codec_thread_allocation`] out of a budget of `configured` workers.
1044pub(crate) fn codec_thread_allocation_within(
1045    request: CodecThreadRequest,
1046    configured: usize,
1047) -> CodecThreadAllocation {
1048    let encoder_slots = usize::from(request.software_video_encoder);
1049    let decode_concurrency = request
1050        .decode_concurrency
1051        .max(1)
1052        .min(configured.saturating_sub(encoder_slots).max(1));
1053    let total_threads = configured.max(decode_concurrency.saturating_add(encoder_slots));
1054    // Reserve the encoder floor before sizing decode, so a small budget
1055    // starves the stage with slack.
1056    let fixed_encoder = request
1057        .encoder_fixed_threads
1058        .filter(|_| request.software_video_encoder)
1059        .map(|threads| threads.max(1));
1060    let encoder_floor = match fixed_encoder {
1061        Some(threads) => threads.min(total_threads.saturating_sub(decode_concurrency).max(1)),
1062        None if request.software_video_encoder => encoder_thread_floor(total_threads)
1063            .min(total_threads.saturating_sub(decode_concurrency).max(1)),
1064        None => 0,
1065    };
1066    let decode_budget = total_threads
1067        .saturating_sub(encoder_floor)
1068        .max(decode_concurrency);
1069    let even_share = if fixed_encoder.is_some() {
1070        // The encoder takes what it runs; decode shares the rest.
1071        (decode_budget / decode_concurrency).max(1)
1072    } else {
1073        let contexts = decode_concurrency.saturating_add(encoder_slots).max(1);
1074        (total_threads / contexts).max(1)
1075    };
1076    let decoder_threads = if request.hardware_decode || !request.software_video_encoder {
1077        // A hardware-decode fallback keeps the even share, and with a hardware encoder nothing
1078        // could use what decode gives up.
1079        even_share
1080    } else {
1081        // Never above the even share: on a small budget one large source would otherwise leave the
1082        // encoder fewer workers than a decoder.
1083        software_decoder_threads(request.source_frame_pixels)
1084            .clamp(1, (decode_budget / decode_concurrency).max(1))
1085            .min(even_share)
1086    };
1087    let decode_assigned = decoder_threads.saturating_mul(decode_concurrency);
1088    // Taking the remainder rather than the floor keeps the total inside the budget
1089    // when decode could not yield.
1090    let encoder_threads = match fixed_encoder {
1091        Some(threads) => threads,
1092        None if request.software_video_encoder => {
1093            total_threads.saturating_sub(decode_assigned).max(1)
1094        }
1095        None => 0,
1096    };
1097    CodecThreadAllocation {
1098        total_threads,
1099        decode_concurrency,
1100        decoder_threads: i64::try_from(decoder_threads).unwrap_or(1).clamp(1, 64),
1101        hardware_decoder_threads: i64::try_from(HARDWARE_DECODER_THREADS.min(total_threads))
1102            .unwrap_or(1)
1103            .max(1),
1104        encoder_threads: i64::try_from(encoder_threads).unwrap_or(0).clamp(0, 64),
1105        allocated_threads: decode_assigned.saturating_add(encoder_threads),
1106    }
1107}
1108
1109/// Workers one software decode session needs for a frame of this area. Zero (unprobed) takes the
1110/// minimum, since decoders are not the stage with the deadline.
1111fn software_decoder_threads(source_frame_pixels: u64) -> usize {
1112    usize::try_from(source_frame_pixels.div_ceil(DECODE_PIXELS_PER_THREAD))
1113        .unwrap_or(MAX_SOFTWARE_DECODER_THREADS)
1114        .clamp(MIN_SOFTWARE_DECODER_THREADS, MAX_SOFTWARE_DECODER_THREADS)
1115}
1116
1117/// The option names an `FFmpeg` open left unconsumed in its dictionary.
1118pub(crate) fn unused_option_names(options: Option<AVDictionary>) -> Option<String> {
1119    let options = options?;
1120    let names = options
1121        .iter()
1122        .map(|entry| entry.key().to_string_lossy().into_owned())
1123        .collect::<Vec<_>>();
1124    (!names.is_empty()).then(|| names.join(", "))
1125}
1126
1127pub(crate) fn reject_unused_decode_options(
1128    options: Option<AVDictionary>,
1129) -> Result<(), DecodeError> {
1130    if let Some(names) = unused_option_names(options) {
1131        Err(DecodeError::Adapter(format!(
1132            "FFmpeg decoder did not consume options: {names}"
1133        )))
1134    } else {
1135        Ok(())
1136    }
1137}
1138
1139pub(crate) fn reject_unused_encode_options(
1140    options: Option<AVDictionary>,
1141) -> Result<(), EncodeError> {
1142    if let Some(names) = unused_option_names(options) {
1143        Err(EncodeError::Adapter(format!(
1144            "FFmpeg encoder did not consume options: {names}"
1145        )))
1146    } else {
1147        Ok(())
1148    }
1149}
1150
1151/// The tags an encoder writes for `color`, as `FFmpeg` (ITU-T H.273) numbers them.
1152///
1153/// The single table behind [`color_options`], a copy's source check, and
1154/// the export bitstream filter.
1155pub(crate) fn color_tags(
1156    color: ColorMetadata,
1157) -> (
1158    ffi::AVColorPrimaries,
1159    ffi::AVColorTransferCharacteristic,
1160    ffi::AVColorSpace,
1161    ffi::AVColorRange,
1162) {
1163    (
1164        match color.primaries {
1165            ColorPrimaries::Bt601 => ffi::AVCOL_PRI_SMPTE170M,
1166            ColorPrimaries::Bt709 => ffi::AVCOL_PRI_BT709,
1167            ColorPrimaries::Bt2020 => ffi::AVCOL_PRI_BT2020,
1168        },
1169        match color.transfer {
1170            TransferFunction::Bt709 => ffi::AVCOL_TRC_BT709,
1171            TransferFunction::Srgb => ffi::AVCOL_TRC_IEC61966_2_1,
1172            TransferFunction::Pq => ffi::AVCOL_TRC_SMPTE2084,
1173            TransferFunction::Hlg => ffi::AVCOL_TRC_ARIB_STD_B67,
1174        },
1175        match color.matrix {
1176            ColorMatrix::Bt601 => ffi::AVCOL_SPC_SMPTE170M,
1177            ColorMatrix::Bt709 => ffi::AVCOL_SPC_BT709,
1178            ColorMatrix::Bt2020Ncl => ffi::AVCOL_SPC_BT2020_NCL,
1179            ColorMatrix::Rgb => ffi::AVCOL_SPC_RGB,
1180        },
1181        match color.range {
1182            ColorRange::Limited => ffi::AVCOL_RANGE_MPEG,
1183            ColorRange::Full => ffi::AVCOL_RANGE_JPEG,
1184        },
1185    )
1186}
1187
1188/// The colour options an encoder opens with, from [`color_tags`], so encoder fields, the `colr` box
1189/// and the bitstream filter's VUI ([`crate::bitstream`]) agree.
1190pub(crate) fn color_options(color: ColorMetadata) -> AVDictionary {
1191    let (primaries, transfer, matrix, range) = color_tags(color);
1192    AVDictionary::new_int(c"color_primaries", i64::from(primaries), 0)
1193        .set_int(c"color_trc", i64::from(transfer), 0)
1194        .set_int(c"colorspace", i64::from(matrix), 0)
1195        .set_int(c"color_range", i64::from(range), 0)
1196}
1197
1198/// The device fault in a failed native GPU call's status, if `error` is one.
1199fn gpu_fault(error: &dyn std::any::Any) -> Option<alpha2_media::GpuFault> {
1200    error
1201        .downcast_ref::<alpha2_ffmpeg_bridge::BridgeError>()
1202        .and_then(alpha2_ffmpeg_bridge::BridgeError::gpu_fault)
1203}
1204
1205/// `error` as a decoder adapter failure, keeping a GPU fault typed ([`DecodeError::Gpu`]).
1206pub(crate) fn adapter_error(error: impl std::fmt::Display + 'static) -> DecodeError {
1207    match gpu_fault(&error) {
1208        Some(fault) => DecodeError::Gpu {
1209            fault,
1210            message: error.to_string(),
1211        },
1212        None => DecodeError::Adapter(error.to_string()),
1213    }
1214}
1215
1216/// `error` as an encoder adapter failure, keeping a GPU fault typed ([`EncodeError::Gpu`]).
1217pub(crate) fn encode_adapter_error(error: impl std::fmt::Display + 'static) -> EncodeError {
1218    match gpu_fault(&error) {
1219        Some(fault) => EncodeError::Gpu {
1220            fault,
1221            message: error.to_string(),
1222        },
1223        None => EncodeError::Adapter(error.to_string()),
1224    }
1225}
1226
1227pub(crate) fn encode_adapter_error_at(
1228    context: &str,
1229    error: impl std::fmt::Display + 'static,
1230) -> EncodeError {
1231    match gpu_fault(&error) {
1232        Some(fault) => EncodeError::Gpu {
1233            fault,
1234            message: format!("{context}: {error}"),
1235        },
1236        None => EncodeError::Adapter(format!("{context}: {error}")),
1237    }
1238}