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