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        Container::Wav => c"wav",
650    }
651}
652
653/// The options `container`'s muxer writes its header with.
654///
655/// Matroska and `WebM` get `fflags=+bitexact`, since otherwise `matroskaenc` writes random track
656/// and segment UIDs and a versioned writing application. MP4 and MOV are deterministic already.
657pub(crate) fn muxer_header_options(container: Container) -> Option<AVDictionary> {
658    matches!(container, Container::Mkv | Container::Webm)
659        .then(|| AVDictionary::new(c"fflags", c"+bitexact", 0))
660}
661
662/// The codec tag a stream of `codec_id` carrying `tag` is written to `container` with.
663///
664/// MP4 and MOV: encoded HEVC is `hvc1` (what browsers and Apple players expect), a copied HEVC
665/// stream keeps its entry, other copied streams are cleared for the muxer to pick, and encoded
666/// streams keep the encoder's tag. Matroska and `WebM` always clear it, since a foreign fourcc can
667/// make the muxer refuse the stream.
668pub(crate) fn container_codec_tag(
669    container: Container,
670    codec_id: ffi::AVCodecID,
671    tag: u32,
672    copied: bool,
673) -> u32 {
674    if matches!(container, Container::Mkv | Container::Webm) {
675        0
676    } else if codec_id == ffi::AV_CODEC_ID_HEVC {
677        if tag == HVC1 || tag == HEV1 {
678            tag
679        } else {
680            HVC1
681        }
682    } else if copied {
683        0
684    } else {
685        tag
686    }
687}
688
689pub(crate) fn color_metadata(
690    parameters: &rsmpeg::avcodec::AVCodecParameters,
691) -> Option<ColorMetadata> {
692    map_color(
693        parameters.color_primaries,
694        parameters.color_trc,
695        parameters.color_space,
696        parameters.color_range,
697    )
698}
699
700pub(crate) fn frame_color_metadata(frame: &AVFrame) -> Option<ColorMetadata> {
701    map_color(
702        frame.color_primaries,
703        frame.color_trc,
704        frame.colorspace,
705        frame.color_range,
706    )
707}
708
709/// The color `FFmpeg`'s tags describe, `None` when all four are unspecified.
710///
711/// `FFmpeg`'s primaries, transfer and matrix values are the ITU-T H.273 code points that
712/// [`ColorMetadata::from_h273`] reads; values past 255 (`FFmpeg`'s extensions) are unrecognized.
713pub(crate) fn map_color(
714    primaries: ffi::AVColorPrimaries,
715    transfer: ffi::AVColorTransferCharacteristic,
716    matrix: ffi::AVColorSpace,
717    range: ffi::AVColorRange,
718) -> Option<ColorMetadata> {
719    let code = |value| u8::try_from(value).unwrap_or(u8::MAX);
720    let full_range = match range {
721        ffi::AVCOL_RANGE_UNSPECIFIED => None,
722        range => Some(range == ffi::AVCOL_RANGE_JPEG),
723    };
724    ColorMetadata::from_h273(code(primaries), code(transfer), code(matrix), full_range)
725}
726
727/// Options every video decoder opens with.
728///
729/// `flags=+unaligned` lets `FFmpeg` crop software frames exactly; without it a small left crop
730/// (under 64 columns of 8-bit 4:2:0) is dropped to keep planes aligned. Hardware frames keep their
731/// crop as the visible rectangle either way.
732/// Refuses a `width` x `height` frame larger than alpha2 renders.
733pub(crate) fn check_frame_size(width: u32, height: u32) -> Result<(), DecodeError> {
734    if alpha2_media::frame_size_supported(width, height) {
735        return Ok(());
736    }
737    Err(DecodeError::Unsupported(format!(
738        "a {width}x{height} frame is larger than {} pixels or {} on a side",
739        alpha2_media::MAX_FRAME_PIXELS,
740        alpha2_media::MAX_FRAME_DIMENSION
741    )))
742}
743
744/// `max_pixels` makes the decoder refuse a picture larger than alpha2 renders before allocating
745/// it, for sizes only the bitstream states and for a size change mid-stream.
746pub(crate) fn video_decoder_options(threads: i64) -> AVDictionary {
747    let max_pixels = i64::try_from(alpha2_media::MAX_FRAME_PIXELS).unwrap_or(i64::MAX);
748    AVDictionary::new_int(c"threads", threads, 0)
749        .set(c"flags", c"+unaligned", 0)
750        .set_int(c"max_pixels", max_pixels, 0)
751}
752
753/// The `FFmpeg` pixel format of `layout`.
754pub(crate) fn pixel_format(
755    layout: alpha2_media::PixelLayout,
756) -> Result<ffi::AVPixelFormat, EncodeError> {
757    pixel_format_named(layout.ffmpeg_name())
758}
759
760pub(crate) fn pixel_format_named(name: &str) -> Result<ffi::AVPixelFormat, EncodeError> {
761    Ok(match name {
762        "yuv420p" => ffi::AV_PIX_FMT_YUV420P,
763        "yuva420p" => ffi::AV_PIX_FMT_YUVA420P,
764        "yuv420p10le" => ffi::AV_PIX_FMT_YUV420P10LE,
765        "yuva420p10le" => ffi::AV_PIX_FMT_YUVA420P10LE,
766        "yuv422p" => ffi::AV_PIX_FMT_YUV422P,
767        "yuva422p" => ffi::AV_PIX_FMT_YUVA422P,
768        "yuv422p10le" => ffi::AV_PIX_FMT_YUV422P10LE,
769        "yuva422p10le" => ffi::AV_PIX_FMT_YUVA422P10LE,
770        "yuv444p" => ffi::AV_PIX_FMT_YUV444P,
771        "yuva444p" => ffi::AV_PIX_FMT_YUVA444P,
772        "yuv444p10le" => ffi::AV_PIX_FMT_YUV444P10LE,
773        "yuva444p10le" => ffi::AV_PIX_FMT_YUVA444P10LE,
774        "p010le" => ffi::AV_PIX_FMT_P010LE,
775        _ => {
776            return Err(EncodeError::Adapter(format!(
777                "pixel layout {name} has no FFmpeg pixel format"
778            )));
779        }
780    })
781}
782
783/// A reusable encoder frame for `width` x `height` pictures of `layout`, its planes in
784/// the layout's storage order.
785///
786/// # Errors
787/// Returns an error for a size that does not fit a frame or a failed allocation.
788pub fn packed_frame(
789    width: u32,
790    height: u32,
791    layout: alpha2_media::PixelLayout,
792) -> Result<alpha2_ffmpeg_bridge::Yuv420pFrameBuffer, alpha2_ffmpeg_bridge::BridgeError> {
793    let (coded_width, coded_height) = (
794        i32::try_from(width)
795            .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("width"))?,
796        i32::try_from(height)
797            .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("height"))?,
798    );
799    let format = pixel_format(layout).map_err(|_| {
800        alpha2_ffmpeg_bridge::BridgeError::InvalidInput("pixel layout has no FFmpeg format")
801    })?;
802    alpha2_ffmpeg_bridge::Yuv420pFrameBuffer::with_format(coded_width, coded_height, format)
803}
804
805pub(crate) fn prores_options(layout: alpha2_media::PixelLayout) -> Vec<(&'static CStr, String)> {
806    let mut options = vec![
807        (
808            c"profile",
809            if layout.alpha { "4444" } else { "hq" }.to_owned(),
810        ),
811        (c"vendor", "apl0".to_owned()),
812    ];
813    if layout.alpha {
814        options.push((c"alpha_bits", "16".to_owned()));
815    }
816    options
817}
818
819pub(crate) fn video_encoder_options(
820    color: ColorMetadata,
821    codec: &AVCodec,
822    on_hardware: bool,
823    threads: i64,
824    width: u32,
825) -> AVDictionary {
826    let mut options = color_options(color);
827    // A hybrid encoder is a software transform unless told otherwise, and only hybrid encoders have
828    // `hw_encoding`, so setting it elsewhere would trip `reject_unused_encode_options`.
829    if encoder_class(codec) == NativeEncoderClass::Hybrid {
830        options = options.set_int(c"hw_encoding", i64::from(on_hardware), 0);
831    }
832    if on_hardware {
833        return options;
834    }
835    let name = codec.name().to_string_lossy();
836    for (key, value) in software_encoder_profile(&name, width, threads) {
837        options = set_encoder_option(options, key, &value);
838    }
839    options.set_int(c"threads", threads, 0)
840}
841
842/// Speed and structure options per software encoder, fixed so exports are reproducible.
843///
844/// - `libvpx-vp9`: `good` deadline, `cpu-used` 4, row multithreading, one tile column per 256
845///   pixels of width, alt-ref frames over a 25-frame look-ahead. Same bytes at any thread count.
846/// - `libsvtav1`: preset 8. SVT-AV1 sizes threads from a parallelism level, set to what it would
847///   pick for `threads` cores. Above level 1 picture order depends on thread timing, so
848///   [`deterministic_encode`] forces level 1.
849fn software_encoder_profile(name: &str, width: u32, threads: i64) -> Vec<(&'static CStr, String)> {
850    match name {
851        "libvpx-vp9" => vec![
852            (c"deadline", "good".into()),
853            (c"cpu-used", "4".into()),
854            (c"row-mt", "1".into()),
855            (c"tile-columns", vp9_tile_columns_log2(width).to_string()),
856            (c"lag-in-frames", "25".into()),
857            (c"auto-alt-ref", "1".into()),
858        ],
859        "libsvtav1" => vec![
860            (c"preset", "8".into()),
861            (
862                c"svtav1-params",
863                format!(
864                    "lp={}",
865                    if deterministic_encode() {
866                        1
867                    } else {
868                        svt_av1_parallelism(threads)
869                    }
870                ),
871            ),
872        ],
873        _ => Vec::new(),
874    }
875}
876
877/// Whether `ALPHA2_DETERMINISTIC_ENCODE=1` asks for byte-identical software encodes at the cost of
878/// speed. Only `libsvtav1` needs it.
879pub(crate) fn deterministic_encode() -> bool {
880    std::env::var_os("ALPHA2_DETERMINISTIC_ENCODE").is_some_and(|value| value == "1")
881}
882
883/// libvpx `tile-columns`: log2 of the tile columns for `width`, each at least 256 pixels.
884pub(crate) fn vp9_tile_columns_log2(width: u32) -> u32 {
885    (width / 256).max(1).ilog2().min(6)
886}
887
888/// SVT-AV1's parallelism level for `threads` workers, matching its own default for that many cores
889/// (1 to 6 for 1, 2, 3-5, 6-11, 12-23, and 24+ cores).
890pub(crate) fn svt_av1_parallelism(threads: i64) -> u32 {
891    match threads {
892        ..=1 => 1,
893        2 => 2,
894        3..=5 => 3,
895        6..=11 => 4,
896        12..=23 => 5,
897        _ => 6,
898    }
899}
900
901/// Sets `key` to `value` in an encoder's options. A list-valued option already set
902/// (`svtav1-params`, `:`-separated pairs) is appended to.
903pub(crate) fn set_encoder_option(options: AVDictionary, key: &CStr, value: &str) -> AVDictionary {
904    let value = CString::new(value).unwrap_or_default();
905    if key == c"svtav1-params" && options.get(key, None, 0).is_some() {
906        let appended = CString::new(format!(":{}", value.to_string_lossy())).unwrap_or_default();
907        options.set(key, &appended, ffi::AV_DICT_APPEND)
908    } else {
909        options.set(key, &value, 0)
910    }
911}
912
913/// Returns the worker budget for one standalone software video codec context.
914///
915/// Capped at 16 workers; by default two cores are reserved for non-codec work. Exports split up to
916/// 64 workers across contexts with [`codec_thread_allocation`].
917#[must_use]
918pub fn codec_thread_budget() -> i64 {
919    i64::try_from(configured_codec_thread_budget().min(16)).unwrap_or(1)
920}
921
922/// The software-codec worker budget `ALPHA2_FFMPEG_THREADS` sets ([`codec_thread_override`]).
923///
924/// # Errors
925/// Returns the setting when it is not a positive count; the default then applies, and callers
926/// reporting the budget's origin should not call it explicit.
927pub fn configured_codec_thread_override() -> Result<Option<usize>, String> {
928    codec_thread_override(std::env::var_os("ALPHA2_FFMPEG_THREADS").as_deref())
929}
930
931/// The worker budget `setting` names: `None` unset, or a positive count clamped to 64.
932///
933/// # Errors
934/// Returns the setting, lossily as text, when it is not a positive count.
935pub fn codec_thread_override(setting: Option<&std::ffi::OsStr>) -> Result<Option<usize>, String> {
936    let Some(setting) = setting else {
937        return Ok(None);
938    };
939    setting
940        .to_str()
941        .and_then(|value| value.parse::<usize>().ok())
942        .filter(|value| *value > 0)
943        .map(|value| Some(value.min(64)))
944        .ok_or_else(|| setting.to_string_lossy().into_owned())
945}
946
947fn configured_codec_thread_budget() -> usize {
948    configured_codec_thread_override()
949        .ok()
950        .flatten()
951        .unwrap_or_else(|| {
952            codec_thread_budget_for(
953                std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
954            )
955        })
956        .clamp(1, 64)
957}
958
959/// Codec workers for an export on `hardware_threads`: all but
960/// [`codec_thread_reserve`], at least one.
961pub(crate) fn codec_thread_budget_for(hardware_threads: usize) -> usize {
962    hardware_threads
963        .saturating_sub(codec_thread_reserve(hardware_threads))
964        .max(1)
965}
966
967/// Hardware threads left to the renderer, coordinator and system: two on 16+
968/// threads, one on 6-15, none below.
969///
970/// On a 4-core/8-thread laptop with two 4K software H.264 decodes, reserving two (and an encoder
971/// floor of four) left `h264_mf` exports waiting on decode and about 50 % slower per frame.
972pub(crate) const fn codec_thread_reserve(hardware_threads: usize) -> usize {
973    match hardware_threads {
974        16.. => 2,
975        6..=15 => 1,
976        _ => 0,
977    }
978}
979
980/// What one export needs from the shared software-codec worker budget.
981#[derive(Clone, Copy, Debug, PartialEq, Eq)]
982pub struct CodecThreadRequest {
983    /// Decoder contexts the pool may run at once.
984    pub decode_concurrency: usize,
985    /// Whether decode sessions produce device-resident frames.
986    pub hardware_decode: bool,
987    /// Luma samples in the largest video source, or zero when unknown.
988    pub source_frame_pixels: u64,
989    /// Whether the video encoder draws on this budget.
990    pub software_video_encoder: bool,
991    /// Workers a software encoder runs regardless of the offer, when the picture
992    /// fixes them (`OpenH264`'s one thread per slice). The split reserves exactly
993    /// that and gives decode the rest.
994    pub encoder_fixed_threads: Option<usize>,
995}
996
997/// Luma samples one software decoder worker is sized to carry.
998const DECODE_PIXELS_PER_THREAD: u64 = 2_000_000;
999/// Smallest worker count a software decode session is given.
1000const MIN_SOFTWARE_DECODER_THREADS: usize = 2;
1001/// Largest worker count a software decode session is given. Frame threading stops paying above this
1002/// on one stream, and extra workers only contend with the encoder.
1003const MAX_SOFTWARE_DECODER_THREADS: usize = 6;
1004/// Workers the software video encoder keeps on budgets of 12 or more; a third of
1005/// smaller budgets ([`encoder_thread_floor`]).
1006const ENCODER_THREAD_FLOOR: usize = 4;
1007
1008/// The encoder's floor: four, or a third of a budget under 12 so small machines'
1009/// decoders are not starved.
1010const fn encoder_thread_floor(total_threads: usize) -> usize {
1011    let third = total_threads / 3;
1012    if third < ENCODER_THREAD_FLOOR {
1013        if third == 0 { 1 } else { third }
1014    } else {
1015        ENCODER_THREAD_FLOOR
1016    }
1017}
1018/// `FFmpeg` workers a hardware decode session opens with, whatever the budget.
1019///
1020/// Hardware sessions decode on the device; workers only parse and submit, and each extra frame
1021/// thread holds back a packet that short cuts fill and drop. On a discrete GPU, an even share (22
1022/// workers) took nearly twice as long on a many-cut project as two to four. One worker doubles a
1023/// long source's decode time. The count changes no output byte. `VideoToolbox` and D3D12VA use
1024/// the same count unmeasured.
1025pub const HARDWARE_DECODER_THREADS: usize = 2;
1026
1027/// One export-wide software-codec allocation: `decoder_threads` per software decoder,
1028/// `hardware_decoder_threads` per hardware one, `encoder_threads` for the software encoder.
1029#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1030pub struct CodecThreadAllocation {
1031    /// Total software codec workers available to this export.
1032    pub total_threads: usize,
1033    /// Number of decoder contexts allowed to execute concurrently.
1034    pub decode_concurrency: usize,
1035    /// `FFmpeg` workers per software decoder context, including a hardware session's fallback.
1036    pub decoder_threads: i64,
1037    /// `FFmpeg` workers a hardware decode session opens with.
1038    pub hardware_decoder_threads: i64,
1039    /// `FFmpeg` worker count assigned to the software video encoder, or zero for hardware.
1040    pub encoder_threads: i64,
1041    /// Workers this allocation actually hands out, decoders plus encoder.
1042    pub allocated_threads: usize,
1043}
1044
1045/// Divides the export CPU budget across concurrently active codec contexts.
1046///
1047/// The budget is an export-wide cap and each context needs a worker, so decoder concurrency is
1048/// reduced first. Hardware video encoding does not consume this budget.
1049///
1050/// With a software encoder, which paces the run, software decoders are sized to their frame area
1051/// and the encoder takes the remainder above a floor. With a hardware encoder the even split stays,
1052/// since cutting decode workers only made decode fall behind the renderer.
1053///
1054/// Hardware decode sessions open with [`HARDWARE_DECODER_THREADS`], but their share is still
1055/// reserved for a software fallback, which also keeps the encoder's worker count (and output)
1056/// independent of how sources decode.
1057#[must_use]
1058pub fn codec_thread_allocation(request: CodecThreadRequest) -> CodecThreadAllocation {
1059    codec_thread_allocation_within(request, configured_codec_thread_budget())
1060}
1061
1062/// The most decode contexts [`codec_thread_allocation`] runs at once: the codec thread budget less
1063/// the software video encoder's slot, at least one.
1064#[must_use]
1065pub fn decode_concurrency_ceiling(software_video_encoder: bool) -> usize {
1066    decode_concurrency_ceiling_for(configured_codec_thread_budget(), software_video_encoder)
1067}
1068
1069/// [`decode_concurrency_ceiling`] for a budget of `configured` workers.
1070#[must_use]
1071pub fn decode_concurrency_ceiling_for(configured: usize, software_video_encoder: bool) -> usize {
1072    configured
1073        .saturating_sub(usize::from(software_video_encoder))
1074        .max(1)
1075}
1076
1077/// [`codec_thread_allocation`] out of a budget of `configured` workers.
1078pub(crate) fn codec_thread_allocation_within(
1079    request: CodecThreadRequest,
1080    configured: usize,
1081) -> CodecThreadAllocation {
1082    let encoder_slots = usize::from(request.software_video_encoder);
1083    let decode_concurrency = request
1084        .decode_concurrency
1085        .max(1)
1086        .min(decode_concurrency_ceiling_for(
1087            configured,
1088            request.software_video_encoder,
1089        ));
1090    let total_threads = configured.max(decode_concurrency.saturating_add(encoder_slots));
1091    // Reserve the encoder floor before sizing decode, so a small budget
1092    // starves the stage with slack.
1093    let fixed_encoder = request
1094        .encoder_fixed_threads
1095        .filter(|_| request.software_video_encoder)
1096        .map(|threads| threads.max(1));
1097    let encoder_floor = match fixed_encoder {
1098        Some(threads) => threads.min(total_threads.saturating_sub(decode_concurrency).max(1)),
1099        None if request.software_video_encoder => encoder_thread_floor(total_threads)
1100            .min(total_threads.saturating_sub(decode_concurrency).max(1)),
1101        None => 0,
1102    };
1103    let decode_budget = total_threads
1104        .saturating_sub(encoder_floor)
1105        .max(decode_concurrency);
1106    let even_share = if fixed_encoder.is_some() {
1107        // The encoder takes what it runs; decode shares the rest.
1108        (decode_budget / decode_concurrency).max(1)
1109    } else {
1110        let contexts = decode_concurrency.saturating_add(encoder_slots).max(1);
1111        (total_threads / contexts).max(1)
1112    };
1113    let decoder_threads = if request.hardware_decode || !request.software_video_encoder {
1114        // A hardware-decode fallback keeps the even share, and with a hardware encoder nothing
1115        // could use what decode gives up.
1116        even_share
1117    } else {
1118        // Never above the even share: on a small budget one large source would otherwise leave the
1119        // encoder fewer workers than a decoder.
1120        software_decoder_threads(request.source_frame_pixels)
1121            .clamp(1, (decode_budget / decode_concurrency).max(1))
1122            .min(even_share)
1123    };
1124    let decode_assigned = decoder_threads.saturating_mul(decode_concurrency);
1125    // Taking the remainder rather than the floor keeps the total inside the budget
1126    // when decode could not yield.
1127    let encoder_threads = match fixed_encoder {
1128        Some(threads) => threads,
1129        None if request.software_video_encoder => {
1130            total_threads.saturating_sub(decode_assigned).max(1)
1131        }
1132        None => 0,
1133    };
1134    CodecThreadAllocation {
1135        total_threads,
1136        decode_concurrency,
1137        decoder_threads: i64::try_from(decoder_threads).unwrap_or(1).clamp(1, 64),
1138        hardware_decoder_threads: i64::try_from(HARDWARE_DECODER_THREADS.min(total_threads))
1139            .unwrap_or(1)
1140            .max(1),
1141        encoder_threads: i64::try_from(encoder_threads).unwrap_or(0).clamp(0, 64),
1142        allocated_threads: decode_assigned.saturating_add(encoder_threads),
1143    }
1144}
1145
1146/// Workers one software decode session needs for a frame of this area. Zero (unprobed) takes the
1147/// minimum, since decoders are not the stage with the deadline.
1148fn software_decoder_threads(source_frame_pixels: u64) -> usize {
1149    usize::try_from(source_frame_pixels.div_ceil(DECODE_PIXELS_PER_THREAD))
1150        .unwrap_or(MAX_SOFTWARE_DECODER_THREADS)
1151        .clamp(MIN_SOFTWARE_DECODER_THREADS, MAX_SOFTWARE_DECODER_THREADS)
1152}
1153
1154/// The option names an `FFmpeg` open left unconsumed in its dictionary.
1155pub(crate) fn unused_option_names(options: Option<AVDictionary>) -> Option<String> {
1156    let options = options?;
1157    let names = options
1158        .iter()
1159        .map(|entry| entry.key().to_string_lossy().into_owned())
1160        .collect::<Vec<_>>();
1161    (!names.is_empty()).then(|| names.join(", "))
1162}
1163
1164pub(crate) fn reject_unused_decode_options(
1165    options: Option<AVDictionary>,
1166) -> Result<(), DecodeError> {
1167    if let Some(names) = unused_option_names(options) {
1168        Err(DecodeError::Adapter(format!(
1169            "FFmpeg decoder did not consume options: {names}"
1170        )))
1171    } else {
1172        Ok(())
1173    }
1174}
1175
1176pub(crate) fn reject_unused_encode_options(
1177    options: Option<AVDictionary>,
1178) -> Result<(), EncodeError> {
1179    if let Some(names) = unused_option_names(options) {
1180        Err(EncodeError::Adapter(format!(
1181            "FFmpeg encoder did not consume options: {names}"
1182        )))
1183    } else {
1184        Ok(())
1185    }
1186}
1187
1188/// The tags an encoder writes for `color`, as `FFmpeg` (ITU-T H.273) numbers them.
1189///
1190/// The single table behind [`color_options`], a copy's source check, and
1191/// the export bitstream filter.
1192pub(crate) fn color_tags(
1193    color: ColorMetadata,
1194) -> (
1195    ffi::AVColorPrimaries,
1196    ffi::AVColorTransferCharacteristic,
1197    ffi::AVColorSpace,
1198    ffi::AVColorRange,
1199) {
1200    (
1201        match color.primaries {
1202            ColorPrimaries::Bt601 => ffi::AVCOL_PRI_SMPTE170M,
1203            ColorPrimaries::Bt709 => ffi::AVCOL_PRI_BT709,
1204            ColorPrimaries::Bt2020 => ffi::AVCOL_PRI_BT2020,
1205            ColorPrimaries::DisplayP3 => ffi::AVCOL_PRI_SMPTE432,
1206        },
1207        match color.transfer {
1208            TransferFunction::Bt709 => ffi::AVCOL_TRC_BT709,
1209            TransferFunction::Srgb => ffi::AVCOL_TRC_IEC61966_2_1,
1210            TransferFunction::Pq => ffi::AVCOL_TRC_SMPTE2084,
1211            TransferFunction::Hlg => ffi::AVCOL_TRC_ARIB_STD_B67,
1212        },
1213        match color.matrix {
1214            ColorMatrix::Bt601 => ffi::AVCOL_SPC_SMPTE170M,
1215            ColorMatrix::Bt709 => ffi::AVCOL_SPC_BT709,
1216            ColorMatrix::Bt2020Ncl => ffi::AVCOL_SPC_BT2020_NCL,
1217            ColorMatrix::Rgb => ffi::AVCOL_SPC_RGB,
1218        },
1219        match color.range {
1220            ColorRange::Limited => ffi::AVCOL_RANGE_MPEG,
1221            ColorRange::Full => ffi::AVCOL_RANGE_JPEG,
1222        },
1223    )
1224}
1225
1226/// The colour options an encoder opens with, from [`color_tags`], so encoder fields, the `colr` box
1227/// and the bitstream filter's VUI ([`crate::bitstream`]) agree.
1228pub(crate) fn color_options(color: ColorMetadata) -> AVDictionary {
1229    let (primaries, transfer, matrix, range) = color_tags(color);
1230    AVDictionary::new_int(c"color_primaries", i64::from(primaries), 0)
1231        .set_int(c"color_trc", i64::from(transfer), 0)
1232        .set_int(c"colorspace", i64::from(matrix), 0)
1233        .set_int(c"color_range", i64::from(range), 0)
1234}
1235
1236/// The device fault in a failed native GPU call's status, if `error` is one.
1237fn gpu_fault(error: &dyn std::any::Any) -> Option<alpha2_media::GpuFault> {
1238    error
1239        .downcast_ref::<alpha2_ffmpeg_bridge::BridgeError>()
1240        .and_then(alpha2_ffmpeg_bridge::BridgeError::gpu_fault)
1241}
1242
1243/// `error` as a decoder adapter failure, keeping a GPU fault typed ([`DecodeError::Gpu`]).
1244pub(crate) fn adapter_error(error: impl std::fmt::Display + 'static) -> DecodeError {
1245    match gpu_fault(&error) {
1246        Some(fault) => DecodeError::Gpu {
1247            fault,
1248            message: error.to_string(),
1249        },
1250        None => DecodeError::Adapter(error.to_string()),
1251    }
1252}
1253
1254/// `error` as an encoder adapter failure, keeping a GPU fault typed ([`EncodeError::Gpu`]).
1255pub(crate) fn encode_adapter_error(error: impl std::fmt::Display + 'static) -> EncodeError {
1256    match gpu_fault(&error) {
1257        Some(fault) => EncodeError::Gpu {
1258            fault,
1259            message: error.to_string(),
1260        },
1261        None => EncodeError::Adapter(error.to_string()),
1262    }
1263}
1264
1265pub(crate) fn encode_adapter_error_at(
1266    context: &str,
1267    error: impl std::fmt::Display + 'static,
1268) -> EncodeError {
1269    match gpu_fault(&error) {
1270        Some(fault) => EncodeError::Gpu {
1271            fault,
1272            message: format!("{context}: {error}"),
1273        },
1274        None => EncodeError::Adapter(format!("{context}: {error}")),
1275    }
1276}