Skip to main content

alpha2_native/
capabilities.rs

1//! Codec capability discovery and encoder selection.
2
3use std::collections::HashMap;
4use std::ffi::CString;
5use std::fmt::Write as _;
6use std::sync::{LazyLock, Mutex};
7#[cfg(target_os = "linux")]
8use std::{fs, path::Path};
9
10use crate::convert::{encode_adapter_error, reject_unused_encode_options, video_encoder_options};
11use crate::video_encode::VideoEncodeConfig;
12use alpha2_ffmpeg_bridge::{EncoderContext, LogLine};
13use alpha2_media::{ColorMetadata, EncodeError, EncoderRefusal, OpenFailureKind};
14use rsmpeg::avcodec::{AVCodec, AVCodecContext, AVCodecRef};
15use rsmpeg::avutil::AVRational;
16use rsmpeg::error::RsmpegError;
17use rsmpeg::ffi;
18
19/// Configuration for transactional audio/video export.
20#[derive(Copy, Clone, Debug, PartialEq)]
21pub struct AvEncodeConfig {
22    /// Video encoder settings.
23    pub video: VideoEncodeConfig,
24    /// Project audio sample rate.
25    pub audio_sample_rate: u32,
26    /// Audio channel count.
27    pub audio_channels: u16,
28    /// Audio codec selected by the downstream host.
29    pub audio_codec: NativeAudioCodec,
30    /// Audio bitrate in bits per second.
31    pub audio_bit_rate: u32,
32}
33
34/// Video codecs implemented by the native encode sinks.
35#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
36#[non_exhaustive]
37pub enum NativeVideoCodec {
38    /// H.264/AVC, preferred for broad browser, Windows, and Apple playback.
39    H264,
40    /// H.265/HEVC.
41    Hevc,
42    /// VP9, when the linked `FFmpeg` build provides a VP9 encoder.
43    Vp9,
44    /// AV1, when the linked `FFmpeg` build provides an AV1 encoder.
45    Av1,
46    /// MPEG-4 Part 2, retained for compatibility with existing alpha2 hosts.
47    Mpeg4Part2,
48    /// Apple `ProRes`, through `prores_ks`: 422 HQ, or 4444 with alpha.
49    ProRes,
50}
51
52impl NativeVideoCodec {
53    /// Stable identifier suitable for an application protocol or settings file.
54    #[must_use]
55    pub const fn as_str(self) -> &'static str {
56        match self {
57            Self::H264 => "h264",
58            Self::Hevc => "hevc",
59            Self::Vp9 => "vp9",
60            Self::Av1 => "av1",
61            Self::Mpeg4Part2 => "mpeg4-part2",
62            Self::ProRes => "prores",
63        }
64    }
65
66    /// The pictures an encoder must take to be offered: 10-bit 4:2:2 for
67    /// `ProRes`, 8-bit 4:2:0 otherwise.
68    #[must_use]
69    pub const fn base_layout(self) -> alpha2_media::PixelLayout {
70        match self {
71            Self::ProRes => alpha2_media::PixelLayout {
72                chroma: alpha2_media::Chroma::Yuv422,
73                bit_depth: alpha2_media::BitDepth::Ten,
74                alpha: false,
75                planes: alpha2_media::PlaneLayout::Planar,
76            },
77            _ => alpha2_media::PixelLayout::YUV420P,
78        }
79    }
80
81    /// The engine's codec this encoder family implements.
82    #[must_use]
83    pub const fn model(self) -> alpha2_media::VideoCodec {
84        match self {
85            Self::H264 => alpha2_media::VideoCodec::H264,
86            Self::Hevc => alpha2_media::VideoCodec::Hevc,
87            Self::Vp9 => alpha2_media::VideoCodec::Vp9,
88            Self::Av1 => alpha2_media::VideoCodec::Av1,
89            Self::Mpeg4Part2 => alpha2_media::VideoCodec::Mpeg4Part2,
90            Self::ProRes => alpha2_media::VideoCodec::ProRes,
91        }
92    }
93
94    /// The native codec for the engine's `codec`.
95    #[must_use]
96    pub const fn from_model(codec: alpha2_media::VideoCodec) -> Self {
97        match codec {
98            alpha2_media::VideoCodec::H264 => Self::H264,
99            alpha2_media::VideoCodec::Hevc => Self::Hevc,
100            alpha2_media::VideoCodec::Vp9 => Self::Vp9,
101            alpha2_media::VideoCodec::Av1 => Self::Av1,
102            alpha2_media::VideoCodec::Mpeg4Part2 => Self::Mpeg4Part2,
103            alpha2_media::VideoCodec::ProRes => Self::ProRes,
104        }
105    }
106
107    pub(crate) const fn codec_id(self) -> ffi::AVCodecID {
108        match self {
109            Self::H264 => ffi::AV_CODEC_ID_H264,
110            Self::Hevc => ffi::AV_CODEC_ID_HEVC,
111            Self::Vp9 => ffi::AV_CODEC_ID_VP9,
112            Self::Av1 => ffi::AV_CODEC_ID_AV1,
113            Self::Mpeg4Part2 => ffi::AV_CODEC_ID_MPEG4,
114            Self::ProRes => ffi::AV_CODEC_ID_PRORES,
115        }
116    }
117}
118
119/// Audio codecs implemented by the native encode sinks.
120#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
121#[non_exhaustive]
122pub enum NativeAudioCodec {
123    /// AAC-LC compatible audio, through `FFmpeg`'s `aac`.
124    Aac,
125    /// Opus, through `libopus`.
126    Opus,
127}
128
129impl NativeAudioCodec {
130    /// Every codec, in the order the engine lists them.
131    pub const ALL: [Self; 2] = [Self::Aac, Self::Opus];
132
133    /// Stable identifier suitable for an application protocol or settings file.
134    #[must_use]
135    pub const fn as_str(self) -> &'static str {
136        match self {
137            Self::Aac => "aac",
138            Self::Opus => "opus",
139        }
140    }
141
142    /// The engine's codec this encoder family implements.
143    #[must_use]
144    pub const fn model(self) -> alpha2_media::AudioCodec {
145        match self {
146            Self::Aac => alpha2_media::AudioCodec::Aac,
147            Self::Opus => alpha2_media::AudioCodec::Opus,
148        }
149    }
150
151    /// The native codec for the engine's `codec`.
152    #[must_use]
153    pub const fn from_model(codec: alpha2_media::AudioCodec) -> Self {
154        match codec {
155            alpha2_media::AudioCodec::Aac => Self::Aac,
156            alpha2_media::AudioCodec::Opus => Self::Opus,
157        }
158    }
159
160    /// The one encoder alpha2 opens: `aac`, or the reference `libopus` (`FFmpeg`'s own `opus` is
161    /// experimental and never a candidate).
162    pub(crate) const fn encoder_name(self) -> &'static std::ffi::CStr {
163        match self {
164            Self::Aac => c"aac",
165            Self::Opus => c"libopus",
166        }
167    }
168}
169
170/// The encoder this runtime opens for `codec`, or `None` when only an experimental one exists.
171pub(crate) fn audio_encoder(codec: NativeAudioCodec) -> Option<AVCodecRef<'static>> {
172    AVCodec::find_encoder_by_name(codec.encoder_name()).filter(|encoder| {
173        u32::try_from(encoder.capabilities).unwrap_or(0) & ffi::AV_CODEC_CAP_EXPERIMENTAL == 0
174    })
175}
176
177/// How a concrete encoder executes, as the linked runtime declares it.
178///
179/// Taken from `AV_CODEC_CAP_HARDWARE` / `AV_CODEC_CAP_HYBRID` rather than the name
180/// suffix, so unknown encoders classify correctly. A few misdeclared encoders are
181/// corrected by `declared_encoder_class`.
182#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
183#[non_exhaustive]
184pub enum NativeEncoderClass {
185    /// Runs on the CPU and draws on the software codec thread budget.
186    Software,
187    /// Runs on a hardware engine and ignores the thread budget.
188    Hardware,
189    /// Can do either. `MediaFoundation`'s `_mf` encoders enumerate a synchronous software transform
190    /// with `hw_encoding=0` and an asynchronous hardware one with `hw_encoding=1`.
191    Hybrid,
192}
193
194impl NativeEncoderClass {
195    /// Stable identifier for diagnostics and the export result.
196    #[must_use]
197    pub const fn as_str(self) -> &'static str {
198        match self {
199            Self::Software => "software",
200            Self::Hardware => "hardware",
201            Self::Hybrid => "hybrid",
202        }
203    }
204
205    /// The ways alpha2 runs an encoder of this class, most preferred first (`true` = GPU). A hybrid
206    /// encoder runs on the CPU unless `hybrid_hardware` is set, and then keeps the CPU as fallback.
207    #[must_use]
208    pub const fn modes(self, hybrid_hardware: bool) -> &'static [bool] {
209        match self {
210            Self::Hardware => &[true],
211            Self::Hybrid if hybrid_hardware => &[true, false],
212            Self::Software | Self::Hybrid => &[false],
213        }
214    }
215}
216
217/// One way to run a registered encoder. Only a hybrid encoder has two.
218pub(crate) struct VideoEncoderCandidate {
219    pub(crate) encoder: AVCodecRef<'static>,
220    pub(crate) on_hardware: bool,
221}
222
223impl VideoEncoderCandidate {
224    pub(crate) fn name(&self) -> String {
225        self.encoder.name().to_string_lossy().into_owned()
226    }
227
228    pub(crate) fn codec(&self) -> NativeVideoCodec {
229        [
230            NativeVideoCodec::H264,
231            NativeVideoCodec::Hevc,
232            NativeVideoCodec::Vp9,
233            NativeVideoCodec::Av1,
234            NativeVideoCodec::Mpeg4Part2,
235            NativeVideoCodec::ProRes,
236        ]
237        .into_iter()
238        .find(|codec| codec.codec_id() == self.encoder.id)
239        .unwrap_or(NativeVideoCodec::H264)
240    }
241}
242
243/// Whether hybrid encoders are configured to run on the GPU.
244///
245/// `_mf` encoders default to `hw_encoding=0` (software MFT). `ALPHA2_VIDEO_ENCODER_HYBRID=hardware`
246/// tries `hw_encoding=1` first and keeps the software transform behind it, because `FFmpeg` does
247/// not fall back between them itself.
248#[must_use]
249pub fn hybrid_encoders_use_hardware() -> bool {
250    std::env::var("ALPHA2_VIDEO_ENCODER_HYBRID")
251        .is_ok_and(|value| value.eq_ignore_ascii_case("hardware"))
252}
253
254/// Why one candidate encoder was not the one an export opened.
255#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
256#[non_exhaustive]
257pub enum NativeEncoderRejection {
258    /// The encoder refuses an output this small.
259    Dimensions,
260    /// `avcodec_open2` failed: no device, no licence, unsupported profile.
261    OpenFailed,
262    /// The encoder silently ignored an option alpha2 requires it to honour.
263    OptionsIgnored,
264    /// The encoder takes none of the pixel formats the output can be written in.
265    PixelFormat,
266}
267
268impl NativeEncoderRejection {
269    /// Stable identifier for diagnostics and the export result.
270    #[must_use]
271    pub const fn as_str(self) -> &'static str {
272        match self {
273            Self::Dimensions => "dimensions",
274            Self::OpenFailed => "open-failed",
275            Self::OptionsIgnored => "options-ignored",
276            Self::PixelFormat => "pixel-format",
277        }
278    }
279}
280
281/// One candidate encoder an export tried and moved past.
282#[derive(Clone, Debug, Eq, PartialEq)]
283pub struct NativeVideoEncoderFallback {
284    /// `FFmpeg` short name of the candidate.
285    pub encoder_name: String,
286    /// Whether the candidate was configured to encode on the GPU.
287    pub hardware_accelerated: bool,
288    /// Typed reason it was rejected.
289    pub reason: NativeEncoderRejection,
290    /// What the rejection is evidence of; a busy device can open later.
291    pub kind: OpenFailureKind,
292    /// The runtime's own message, kept verbatim.
293    pub detail: String,
294}
295
296impl NativeVideoEncoderFallback {
297    /// This rejection as a refusal.
298    #[must_use]
299    pub fn refusal(&self) -> EncoderRefusal {
300        EncoderRefusal {
301            encoder: self.encoder_name.clone(),
302            hardware_accelerated: self.hardware_accelerated,
303            kind: self.kind,
304            reason: self.detail.clone(),
305        }
306    }
307}
308
309/// The encoder an export actually opened, and the candidates it passed over.
310///
311/// A platform can register an encoder it cannot open, so every export reports what it opened.
312#[derive(Clone, Debug, Eq, PartialEq)]
313pub struct NativeVideoEncoderSelection {
314    /// `FFmpeg` short name of the encoder that opened.
315    pub encoder_name: String,
316    /// How that encoder executes.
317    pub class: NativeEncoderClass,
318    /// Whether it is configured to encode on the GPU.
319    pub hardware_accelerated: bool,
320    /// Candidates tried first, in preference order.
321    pub rejected: Vec<NativeVideoEncoderFallback>,
322    /// Whether the encoder runs the rate control's quantizer or its bitrate.
323    pub rate_control: crate::AppliedRateControl,
324    /// Why a quantizer that was asked for is not the one running.
325    pub quantizer_refused: Option<String>,
326    /// `FFmpeg` workers the encoder was opened with on the CPU; `None` on the GPU.
327    pub software_threads: Option<i64>,
328    /// The pictures it takes: the output's layout, or its `P010` form for an encoder that takes
329    /// 10-bit 4:2:0 only that way.
330    pub pixels: alpha2_media::PixelLayout,
331}
332
333/// One linked video encoder available to the native sinks.
334#[derive(Clone, Debug, Eq, PartialEq)]
335pub struct NativeVideoEncoderCapability {
336    /// Stable logical codec requested through [`VideoEncodeConfig`].
337    pub codec: NativeVideoCodec,
338    /// Concrete `FFmpeg` encoder implementation for this codec.
339    pub encoder_name: String,
340    /// How the linked runtime declares this encoder executes.
341    pub class: NativeEncoderClass,
342    /// Whether this entry runs the encoder on the GPU. A hybrid encoder has an entry per mode.
343    pub hardware_accelerated: bool,
344    /// Whether this is the default encoder for its logical codec.
345    pub preferred: bool,
346    /// Smallest even width accepted by this concrete encoder.
347    pub minimum_width: u32,
348    /// Smallest even height accepted by this concrete encoder.
349    pub minimum_height: u32,
350    /// The user-installed library behind a non-`FFmpeg` encoder; `None` for `FFmpeg`'s own.
351    pub library: Option<NativeEncoderLibrary>,
352}
353
354/// A run-time loaded encoder library ([`crate::OPENH264_ENCODER_NAME`]).
355#[derive(Clone, Debug, Eq, PartialEq)]
356pub struct NativeEncoderLibrary {
357    /// Who provided it ([`crate::OpenH264Provider::as_str`]).
358    pub provider: &'static str,
359    /// The version it reports.
360    pub version: String,
361    /// Where it was loaded from.
362    pub path: String,
363    /// The notice its licence requires be shown.
364    pub notice: &'static str,
365}
366
367impl NativeEncoderLibrary {
368    fn openh264(library: &crate::OpenH264Library) -> Self {
369        Self {
370            provider: library.provider().as_str(),
371            version: library.version().to_owned(),
372            path: library.path().to_owned(),
373            notice: crate::OPENH264_NOTICE,
374        }
375    }
376}
377
378/// One linked audio encoder available to the native sinks.
379#[derive(Clone, Debug, Eq, PartialEq)]
380pub struct NativeAudioEncoderCapability {
381    /// Stable logical codec requested through [`AvEncodeConfig`].
382    pub codec: NativeAudioCodec,
383    /// Concrete `FFmpeg` encoder selected for that codec on this host.
384    pub encoder_name: String,
385}
386
387/// Runtime codec inventory for the native sinks.
388///
389/// Container/codec pairing is engine policy ([`alpha2_media::Container`]); this says which
390/// codecs this runtime can encode.
391#[derive(Clone, Debug, Eq, PartialEq)]
392pub struct NativeCodecCapabilities {
393    /// Video encoders accepted by [`NativeVideoEncodeSink`](crate::NativeVideoEncodeSink) and
394    /// [`NativeAvEncodeSink`](crate::NativeAvEncodeSink).
395    pub video: Vec<NativeVideoEncoderCapability>,
396    /// Audio encoders accepted by [`NativeAvEncodeSink`](crate::NativeAvEncodeSink) and the
397    /// GPU-resident and packet-copy exports.
398    pub audio: Vec<NativeAudioEncoderCapability>,
399}
400
401/// Reports the encoders usable by the native sinks: the linked `FFmpeg`'s, and
402/// `OpenH264` when installed.
403///
404/// A hybrid encoder has one entry per mode. Order is usable hardware first, then software in
405/// `FFmpeg`'s order, then `OpenH264`; exactly one entry per codec is marked preferred.
406#[must_use]
407pub fn codec_capabilities() -> NativeCodecCapabilities {
408    let video = [
409        NativeVideoCodec::H264,
410        NativeVideoCodec::Hevc,
411        NativeVideoCodec::Vp9,
412        NativeVideoCodec::Av1,
413        NativeVideoCodec::Mpeg4Part2,
414        NativeVideoCodec::ProRes,
415    ]
416    .into_iter()
417    .flat_map(|codec| video_encoder_inventory(codec).usable)
418    .collect();
419    NativeCodecCapabilities {
420        video,
421        audio: audio_encoder_capabilities(),
422    }
423}
424
425/// Whether some encoder of `codec` takes `layout`'s pictures or their `P010` form.
426#[must_use]
427pub fn encodes_pixels(
428    capabilities: &NativeCodecCapabilities,
429    codec: NativeVideoCodec,
430    layout: alpha2_media::PixelLayout,
431) -> bool {
432    capabilities
433        .video
434        .iter()
435        .filter(|capability| capability.codec == codec)
436        .any(|capability| {
437            capability.encoder_name == crate::OPENH264_ENCODER_NAME && layout.is_yuv420p()
438                || std::ffi::CString::new(capability.encoder_name.as_str())
439                    .ok()
440                    .and_then(|name| AVCodec::find_encoder_by_name(&name))
441                    .is_some_and(|encoder| encoder_layout(&encoder, layout).is_some())
442        })
443}
444
445/// The audio encoders [`codec_capabilities`] lists, without probing video encoders.
446#[must_use]
447pub fn audio_encoder_capabilities() -> Vec<NativeAudioEncoderCapability> {
448    NativeAudioCodec::ALL
449        .into_iter()
450        .filter_map(|codec| {
451            let encoder = audio_encoder(codec)?;
452            Some(NativeAudioEncoderCapability {
453                codec,
454                encoder_name: encoder.name().to_string_lossy().into_owned(),
455            })
456        })
457        .collect()
458}
459
460/// The encoders of one codec this machine runs, and the ones its open probe refused.
461#[derive(Clone, Debug, Default, Eq, PartialEq)]
462pub struct EncoderInventory {
463    /// The encoders usable for the codec, as [`codec_capabilities`] lists them.
464    pub usable: Vec<NativeVideoEncoderCapability>,
465    /// Registered encoders whose open probe failed, and why. A busy one is asked again next time.
466    pub refused: Vec<EncoderRefusal>,
467}
468
469/// The usable encoders for `codec` alone, and the ones whose probe refused.
470///
471/// Only this codec's encoders are open-probed.
472#[must_use]
473pub fn video_encoder_inventory(codec: NativeVideoCodec) -> EncoderInventory {
474    let (choices, refused) = available_video_encoders(codec);
475    let usable = choices
476        .into_iter()
477        .enumerate()
478        .map(|(index, choice)| {
479            let encoder_name = choice.name();
480            let (minimum_width, minimum_height) = encoder_minimum_dimensions(&encoder_name);
481            NativeVideoEncoderCapability {
482                codec,
483                class: choice.class(),
484                hardware_accelerated: choice.on_hardware(),
485                preferred: index == 0,
486                encoder_name,
487                minimum_width,
488                minimum_height,
489                library: match &choice {
490                    VideoEncoderChoice::Ffmpeg(_) => None,
491                    VideoEncoderChoice::OpenH264(library) => {
492                        Some(NativeEncoderLibrary::openh264(library))
493                    }
494                },
495            }
496        })
497        .collect();
498    EncoderInventory { usable, refused }
499}
500
501/// One encoder an export can try: a registered `FFmpeg` one, or `OpenH264`.
502pub(crate) enum VideoEncoderChoice {
503    Ffmpeg(VideoEncoderCandidate),
504    OpenH264(std::sync::Arc<crate::OpenH264Library>),
505}
506
507impl VideoEncoderChoice {
508    pub(crate) fn name(&self) -> String {
509        match self {
510            Self::Ffmpeg(candidate) => candidate.name(),
511            Self::OpenH264(_) => crate::OPENH264_ENCODER_NAME.to_owned(),
512        }
513    }
514
515    pub(crate) const fn on_hardware(&self) -> bool {
516        match self {
517            Self::Ffmpeg(candidate) => candidate.on_hardware,
518            Self::OpenH264(_) => false,
519        }
520    }
521
522    pub(crate) fn class(&self) -> NativeEncoderClass {
523        match self {
524            Self::Ffmpeg(candidate) => encoder_class(&candidate.encoder),
525            Self::OpenH264(_) => NativeEncoderClass::Software,
526        }
527    }
528}
529
530/// Every encoder for `codec` this machine runs, most preferred first, plus the probe refusals.
531/// `OpenH264` comes last because `libx264` compresses better where present.
532pub(crate) fn available_video_encoders(
533    codec: NativeVideoCodec,
534) -> (Vec<VideoEncoderChoice>, Vec<EncoderRefusal>) {
535    let (mut choices, refused) = compatible_encoders(registered_video_encoders(codec));
536    if codec == NativeVideoCodec::H264
537        && let Some(library) = crate::openh264_status().library()
538    {
539        choices.push(VideoEncoderChoice::OpenH264(std::sync::Arc::clone(library)));
540    }
541    (choices, refused)
542}
543
544/// `candidates` split into those that run here and probe refusals; ones the registration
545/// rules out are in neither.
546fn compatible_encoders(
547    candidates: Vec<VideoEncoderCandidate>,
548) -> (Vec<VideoEncoderChoice>, Vec<EncoderRefusal>) {
549    let mut choices = Vec::new();
550    let mut refused = Vec::new();
551    for candidate in candidates {
552        let name = candidate.name();
553        if !registration_is_compatible(&candidate, &name) {
554            continue;
555        }
556        match encoder_runs_here(&candidate, &name) {
557            Ok(()) => choices.push(VideoEncoderChoice::Ffmpeg(candidate)),
558            Err(refusal) => refused.push(refusal),
559        }
560    }
561    (choices, refused)
562}
563
564/// One codec's hardware decode registration for this platform's backend.
565#[derive(Clone, Debug, Eq, PartialEq)]
566pub struct NativeHardwareDecodeCapability {
567    /// Logical codec.
568    pub codec: NativeVideoCodec,
569    /// Concrete `FFmpeg` decoder implementation, when one is linked.
570    pub decoder_name: Option<String>,
571    /// Whether that decoder advertises this platform's hardware configuration.
572    ///
573    /// Registration only; device, profile and surface support are decided when a stream opens.
574    pub hardware_config: bool,
575    /// The decoder a software session opens, or `None` when only hardware can decode the
576    /// codec (AV1 without libdav1d).
577    pub software_decoder: Option<String>,
578}
579
580/// Hardware decode registration reported by the linked `FFmpeg` build.
581#[derive(Clone, Debug, Eq, PartialEq)]
582pub struct NativeHardwareDecodeCapabilities {
583    /// Stable backend identifier, or `none` on a build without a GPU path.
584    pub backend: &'static str,
585    /// One entry per codec alpha2 can present from a decoder surface.
586    pub codecs: Vec<NativeHardwareDecodeCapability>,
587}
588
589/// Backend this build decodes with, independent of any device being present.
590#[must_use]
591pub const fn hardware_decode_backend() -> &'static str {
592    #[cfg(feature = "hwdecode")]
593    {
594        #[cfg(target_os = "linux")]
595        {
596            "vulkan"
597        }
598        #[cfg(target_os = "macos")]
599        {
600            "videotoolbox"
601        }
602        #[cfg(target_os = "windows")]
603        {
604            "d3d12va"
605        }
606        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
607        {
608            "none"
609        }
610    }
611    #[cfg(not(feature = "hwdecode"))]
612    {
613        "none"
614    }
615}
616
617/// Reports which codecs the linked `FFmpeg` registers for this backend.
618#[must_use]
619pub fn hardware_decode_capabilities() -> NativeHardwareDecodeCapabilities {
620    let codecs = [
621        NativeVideoCodec::H264,
622        NativeVideoCodec::Hevc,
623        NativeVideoCodec::Av1,
624        NativeVideoCodec::Vp9,
625    ]
626    .into_iter()
627    .map(|codec| {
628        let decoder = AVCodec::find_decoder(codec.codec_id());
629        NativeHardwareDecodeCapability {
630            codec,
631            decoder_name: decoder
632                .as_ref()
633                .map(|decoder| decoder.name().to_string_lossy().into_owned()),
634            hardware_config: crate::decode::registered_video_decoders(codec.codec_id())
635                .any(|decoder| decoder_has_hardware_config(&decoder)),
636            software_decoder: crate::decode::software_video_decoder(codec.codec_id())
637                .ok()
638                .map(|decoder| decoder.name().to_string_lossy().into_owned()),
639        }
640    })
641    .collect();
642    NativeHardwareDecodeCapabilities {
643        backend: hardware_decode_backend(),
644        codecs,
645    }
646}
647
648/// Whether `decoder` advertises this platform's hardware device configuration.
649#[allow(unused_variables)]
650fn decoder_has_hardware_config(decoder: &AVCodecRef<'_>) -> bool {
651    #[cfg(all(
652        any(target_os = "linux", target_os = "macos", target_os = "windows"),
653        feature = "hwdecode"
654    ))]
655    {
656        #[cfg(target_os = "linux")]
657        let (device_type, pixel_format) = (ffi::AV_HWDEVICE_TYPE_VULKAN, ffi::AV_PIX_FMT_VULKAN);
658        #[cfg(target_os = "macos")]
659        let (device_type, pixel_format) = (
660            ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
661            ffi::AV_PIX_FMT_VIDEOTOOLBOX,
662        );
663        #[cfg(target_os = "windows")]
664        let (device_type, pixel_format) = (ffi::AV_HWDEVICE_TYPE_D3D12VA, ffi::AV_PIX_FMT_D3D12);
665        (0..)
666            .map_while(|index| decoder.hw_config(index))
667            .any(|config| config.device_type == device_type && config.pix_fmt == pixel_format)
668    }
669    #[cfg(not(all(
670        any(target_os = "linux", target_os = "macos", target_os = "windows"),
671        feature = "hwdecode"
672    )))]
673    {
674        false
675    }
676}
677
678/// Encoders named in `ALPHA2_TEST_SKIP_ENCODERS` (comma separated), hidden in test builds as if
679/// unregistered. Valgrind runs use it for `libsvtav1`, which reads uninitialized memory.
680#[cfg(test)]
681pub(crate) fn test_skips_encoder(name: &std::ffi::CStr) -> bool {
682    static SKIPPED: LazyLock<Vec<String>> = LazyLock::new(|| {
683        std::env::var("ALPHA2_TEST_SKIP_ENCODERS")
684            .unwrap_or_default()
685            .split(',')
686            .map(str::trim)
687            .filter(|name| !name.is_empty())
688            .map(str::to_owned)
689            .collect()
690    });
691    let name = name.to_string_lossy();
692    SKIPPED.iter().any(|skipped| *skipped == name)
693}
694
695#[cfg(not(test))]
696const fn test_skips_encoder(_name: &std::ffi::CStr) -> bool {
697    false
698}
699
700/// Every way to run each encoder registered for `codec`, GPU ones first.
701pub(crate) fn registered_video_encoders(codec: NativeVideoCodec) -> Vec<VideoEncoderCandidate> {
702    let hybrid_hardware = hybrid_encoders_use_hardware();
703    let mut candidates = AVCodec::iterate()
704        .filter(|encoder| {
705            encoder.id == codec.codec_id()
706                // Only `prores_ks` takes the 4444 alpha and vendor options alpha2 sets.
707                && (codec != NativeVideoCodec::ProRes || encoder.name() == c"prores_ks")
708                && !test_skips_encoder(encoder.name())
709                && AVCodec::find_encoder_by_name(encoder.name())
710                    .is_some_and(|found| found.as_ptr() == encoder.as_ptr())
711        })
712        .flat_map(|encoder| {
713            encoder_class(&encoder)
714                .modes(hybrid_hardware)
715                .iter()
716                .filter_map(move |&on_hardware| {
717                    AVCodec::find_encoder_by_name(encoder.name()).map(|encoder| {
718                        VideoEncoderCandidate {
719                            encoder,
720                            on_hardware,
721                        }
722                    })
723                })
724        })
725        .collect::<Vec<_>>();
726    // Stable sort: FFmpeg's registration order within each tier, hardware first.
727    candidates.sort_by_key(|candidate| !candidate.on_hardware);
728    candidates
729}
730
731/// Classifies `encoder` from the capability bits it declares.
732pub(crate) fn encoder_class(encoder: &AVCodec) -> NativeEncoderClass {
733    let name = encoder.name().to_string_lossy();
734    declared_encoder_class(&name, u32::try_from(encoder.capabilities).unwrap_or(0))
735}
736
737/// Encoders the pinned runtime declares as software although they run only on hardware.
738///
739/// `FFmpeg` 8.x declares `h264_videotoolbox` with neither `AV_CODEC_CAP_HARDWARE` nor
740/// `AV_CODEC_CAP_HYBRID` yet opens it with `allow_sw=0`. An entry applies only while the
741/// runtime declares neither bit.
742const MISDECLARED_HARDWARE_ENCODERS: &[&str] = &["h264_videotoolbox"];
743
744/// The class from `capabilities`, except that a [`MISDECLARED_HARDWARE_ENCODERS`] entry declaring
745/// neither bit is `Hardware`.
746pub(crate) fn declared_encoder_class(name: &str, capabilities: u32) -> NativeEncoderClass {
747    if capabilities & ffi::AV_CODEC_CAP_HYBRID != 0 {
748        NativeEncoderClass::Hybrid
749    } else if capabilities & ffi::AV_CODEC_CAP_HARDWARE != 0
750        || MISDECLARED_HARDWARE_ENCODERS.contains(&name)
751    {
752        NativeEncoderClass::Hardware
753    } else {
754        NativeEncoderClass::Software
755    }
756}
757
758#[cfg(test)]
759pub(crate) fn encoder_is_compatible(candidate: &VideoEncoderCandidate) -> bool {
760    let name = candidate.name();
761    registration_is_compatible(candidate, &name) && encoder_runs_here(candidate, &name).is_ok()
762}
763
764/// What the registration alone rules out: an encoder that cannot take its codec's base pictures
765/// ([`NativeVideoCodec::base_layout`]), or a hardware one whose device has no node here.
766fn registration_is_compatible(candidate: &VideoEncoderCandidate, name: &str) -> bool {
767    // The native sink submits software frames, so encoders needing an `AVHWFramesContext` are out.
768    let codec = candidate.codec();
769    if encoder_layout(&candidate.encoder, codec.base_layout()).is_none() {
770        return false;
771    }
772    !candidate.on_hardware || hardware_device_node(name) != Some(false)
773}
774
775/// The pictures `encoder` takes for `layout`: `layout` itself, or its `P010` form for an encoder
776/// that takes 10-bit 4:2:0 only that way (NVENC); `None` when neither.
777pub(crate) fn encoder_layout(
778    encoder: &AVCodec,
779    layout: alpha2_media::PixelLayout,
780) -> Option<alpha2_media::PixelLayout> {
781    let Some(formats) = encoder.pix_fmts() else {
782        return Some(layout);
783    };
784    [layout, layout.as_p010()]
785        .into_iter()
786        .find(|candidate| formats.contains(&crate::convert::pixel_format(*candidate)))
787}
788
789/// Whether the encoder is listed only after an open probe ([`encoder_runs_here`]).
790///
791/// This covers hardware encoders without a device node, NVENC, and every `_mf` or `_videotoolbox`
792/// encoder. `VideoToolbox` is probed by name because a runtime may misdeclare its class, and an
793/// NVIDIA device node does not imply NVENC (compute-only GPUs have none).
794pub(crate) fn needs_open_probe(on_hardware: bool, name: &str) -> bool {
795    (on_hardware && (hardware_device_node(name).is_none() || name.ends_with("_nvenc")))
796        || name.ends_with("_mf")
797        || name.ends_with("_videotoolbox")
798}
799
800/// Whether `encoder` encodes a frame on this machine, for encoders whose
801/// registration does not prove it.
802///
803/// `MediaFoundation` registers every `_mf` encoder whether or not a working transform exists, and
804/// hardware encoders register without their device (`VideoToolbox` in a headless VM, NVENC without
805/// the driver). Such encoders are listed only after encoding one 256x144 frame with export options.
806/// Verdicts that cannot change (ran, or absent) are cached per process and mode; busy or
807/// unclassified failures are asked again at the next export.
808///
809/// Probes run lazily per codec, since each NVENC probe creates a CUDA context (about 0.4 s).
810fn encoder_runs_here(candidate: &VideoEncoderCandidate, name: &str) -> Result<(), EncoderRefusal> {
811    probe_outcome(candidate, name, true).unwrap_or(Ok(()))
812}
813
814/// A probe answer that cannot change while the process runs.
815#[derive(Clone, Debug, Eq, PartialEq)]
816pub(crate) enum ProbeVerdict {
817    /// The encoder encoded a frame.
818    Runs,
819    /// What the encoder needs is not here, or it refuses the probe's options; why.
820    Absent(String),
821}
822
823/// The probe outcomes kept for this process, by encoder name and way it runs.
824pub(crate) type ProbeCache = Mutex<HashMap<(String, bool), ProbeVerdict>>;
825
826/// `Some(Ok)` for an encoder that needs no probe or passed one, `Some(Err)` for one that failed,
827/// and `None` for one not probed yet when `probe` is unset.
828fn probe_outcome(
829    candidate: &VideoEncoderCandidate,
830    name: &str,
831    probe: bool,
832) -> Option<Result<(), EncoderRefusal>> {
833    static VERDICTS: LazyLock<ProbeCache> = LazyLock::new(Mutex::default);
834    if !needs_open_probe(candidate.on_hardware, name) {
835        return Some(Ok(()));
836    }
837    cached_probe(
838        &VERDICTS,
839        name,
840        candidate.on_hardware,
841        probe.then_some(|| probe_open(candidate, name)),
842    )
843}
844
845/// The cached verdict for `name` and mode, else `probe`'s answer (cached only when it is a
846/// [`ProbeVerdict`]); `None` when nothing is cached and there is no `probe`.
847pub(crate) fn cached_probe(
848    cache: &ProbeCache,
849    name: &str,
850    on_hardware: bool,
851    probe: Option<impl FnOnce() -> Result<(), (OpenFailureKind, String)>>,
852) -> Option<Result<(), EncoderRefusal>> {
853    let refusal = |kind, reason| EncoderRefusal {
854        encoder: name.to_owned(),
855        hardware_accelerated: on_hardware,
856        kind,
857        reason,
858    };
859    let key = (name.to_owned(), on_hardware);
860    // Held across the probe, so two exports asking at once probe once.
861    let mut verdicts = cache
862        .lock()
863        .unwrap_or_else(std::sync::PoisonError::into_inner);
864    match verdicts.get(&key) {
865        Some(ProbeVerdict::Runs) => return Some(Ok(())),
866        Some(ProbeVerdict::Absent(reason)) => {
867            return Some(Err(refusal(OpenFailureKind::Absent, reason.clone())));
868        }
869        None => {}
870    }
871    let outcome = probe?();
872    let kept = match &outcome {
873        Ok(()) => Some(ProbeVerdict::Runs),
874        Err((OpenFailureKind::Absent | OpenFailureKind::Unsuitable, reason)) => {
875            Some(ProbeVerdict::Absent(reason.clone()))
876        }
877        Err((OpenFailureKind::Busy | OpenFailureKind::Unknown, _)) => None,
878    };
879    if let Err((kind, error)) = &outcome {
880        alpha2_os::diagnostic!(
881            "alpha2 native: video encoder {name} {} is registered but did not encode a frame on \
882             this machine, so it is not offered that way ({}{}): {error}",
883            mode_label(on_hardware),
884            kind.as_str(),
885            if kept.is_some() {
886                ""
887            } else {
888                "; asked again at the next export"
889            }
890        );
891    }
892    if let Some(verdict) = kept {
893        verdicts.insert(key, verdict);
894    }
895    Some(outcome.map_err(|(kind, reason)| refusal(kind, reason)))
896}
897
898/// Encodes one probe frame and classifies a failure from what the encoder logged.
899fn probe_open(
900    candidate: &VideoEncoderCandidate,
901    name: &str,
902) -> Result<(), (OpenFailureKind, String)> {
903    let mark = alpha2_ffmpeg_bridge::log_mark();
904    match probe_software_encode(candidate, name, 256, 144, None).0 {
905        None => Ok(()),
906        Some(error) => {
907            let lines = alpha2_ffmpeg_bridge::log_since(mark, &[name]);
908            Err((
909                classify_open_failure(name, &error, &lines),
910                format!("{error}{}", alpha2_ffmpeg_bridge::log_detail(&lines)),
911            ))
912        }
913    }
914}
915
916/// What a failed open of `encoder` is evidence of, from its error and logged `lines`.
917///
918/// Only fixed-wording statuses are read: NVENC's parenthesized status, Vulkan's `VkResult`,
919/// `VideoToolbox`'s `OSStatus`, and `MediaFoundation`'s missing transform. Anything else is
920/// [`OpenFailureKind::Unknown`], never cached and never busy, so a wording change costs a re-probe
921/// rather than a wrong class.
922pub(crate) fn classify_open_failure(
923    encoder: &str,
924    error: &str,
925    lines: &[LogLine],
926) -> OpenFailureKind {
927    let said =
928        |words: &str| error.contains(words) || lines.iter().any(|line| line.text.contains(words));
929    if encoder.ends_with("_nvenc") {
930        // OUT_OF_MEMORY, LOCK_BUSY, ENCODER_BUSY and INCOMPATIBLE_CLIENT_KEY are how a
931        // consumer GPU reports its session limit (some drivers answer 21); 1-5 mean no or
932        // unsupported device. The status decides first, since `FFmpeg` logs "No capable
933        // devices found" after any failed device.
934        return match lines.iter().find_map(|line| nvenc_status(&line.text)) {
935            Some(10 | 13 | 18 | 21) => OpenFailureKind::Busy,
936            Some(1..=5) => OpenFailureKind::Absent,
937            None if said("No capable devices found") || said("Cannot load") => {
938                OpenFailureKind::Absent
939            }
940            _ => OpenFailureKind::Unknown,
941        };
942    }
943    if encoder.ends_with("_vulkan") {
944        let busy = lines.iter().any(|line| {
945            line.text.contains("Unable to create video session")
946                && (line.text.contains("VK_ERROR_OUT_OF_DEVICE_MEMORY")
947                    || line.text.contains("VK_ERROR_TOO_MANY_OBJECTS"))
948        });
949        return if busy {
950            OpenFailureKind::Busy
951        } else {
952            OpenFailureKind::Unknown
953        };
954    }
955    if encoder.ends_with("_videotoolbox") {
956        // kVTVideoEncoderNotAvailableNowErr and kVTCouldNotFindVideoEncoderErr.
957        if said("-12915") {
958            return OpenFailureKind::Busy;
959        }
960        if said("-12908") {
961            return OpenFailureKind::Absent;
962        }
963        return OpenFailureKind::Unknown;
964    }
965    if encoder.ends_with("_mf") && (said("could not find any MFT") || said("E_FAIL")) {
966        return OpenFailureKind::Absent;
967    }
968    OpenFailureKind::Unknown
969}
970
971/// The first parenthesized number in an `nvenc_print_error` line.
972fn nvenc_status(line: &str) -> Option<u32> {
973    line.match_indices('(').find_map(|(start, _)| {
974        let rest = &line[start + 1..];
975        let end = rest.find(')')?;
976        let digits = &rest[..end];
977        (!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()))
978            .then(|| digits.parse().ok())
979            .flatten()
980    })
981}
982
983/// The encoders [`codec_capabilities`] would list from what is known so far, without running any
984/// probe; unprobed encoders are left out. For a startup log line.
985#[must_use]
986pub fn video_encoders_without_probing() -> (Vec<NativeVideoEncoderCapability>, Vec<String>) {
987    let mut unprobed = Vec::new();
988    let mut listed = Vec::new();
989    for codec in [
990        NativeVideoCodec::H264,
991        NativeVideoCodec::Hevc,
992        NativeVideoCodec::Vp9,
993        NativeVideoCodec::Av1,
994        NativeVideoCodec::Mpeg4Part2,
995        NativeVideoCodec::ProRes,
996    ] {
997        for candidate in registered_video_encoders(codec) {
998            let name = candidate.name();
999            if !registration_is_compatible(&candidate, &name) {
1000                continue;
1001            }
1002            match probe_outcome(&candidate, &name, false) {
1003                Some(Ok(())) => {
1004                    let (minimum_width, minimum_height) = encoder_minimum_dimensions(&name);
1005                    listed.push(NativeVideoEncoderCapability {
1006                        codec,
1007                        class: encoder_class(&candidate.encoder),
1008                        hardware_accelerated: candidate.on_hardware,
1009                        preferred: !listed
1010                            .iter()
1011                            .any(|listed: &NativeVideoEncoderCapability| listed.codec == codec),
1012                        encoder_name: name,
1013                        minimum_width,
1014                        minimum_height,
1015                        library: None,
1016                    });
1017                }
1018                Some(Err(_)) => {}
1019                None => unprobed.push(format!("{name} {}", mode_label(candidate.on_hardware))),
1020            }
1021        }
1022    }
1023    (listed, unprobed)
1024}
1025
1026pub(crate) const fn mode_label(on_hardware: bool) -> &'static str {
1027    if on_hardware { "on GPU" } else { "on CPU" }
1028}
1029
1030/// Whether a hardware encoder's device has a node here, for families Linux knows a node
1031/// for; `None` for the rest.
1032///
1033/// A node replaces the open probe for those families, except NVENC, where it only gates the probe
1034/// so machines without an NVIDIA GPU pay nothing.
1035#[cfg(target_os = "linux")]
1036fn hardware_device_node(name: &str) -> Option<bool> {
1037    if name.ends_with("_nvenc") {
1038        return Some(Path::new("/dev/nvidia0").exists() || Path::new("/dev/nvidiactl").exists());
1039    }
1040    if name.ends_with("_vaapi") || name.ends_with("_qsv") || name.ends_with("_amf") {
1041        return Some(fs::read_dir("/dev/dri").is_ok_and(|entries| {
1042            entries.flatten().any(|entry| {
1043                entry
1044                    .file_name()
1045                    .to_str()
1046                    .is_some_and(|name| name.starts_with("renderD") || name.starts_with("card"))
1047            })
1048        }));
1049    }
1050    if name.ends_with("_v4l2m2m") {
1051        return Some((0..64).any(|index| Path::new(&format!("/dev/video{index}")).exists()));
1052    }
1053    None
1054}
1055
1056/// Off Linux there is no device node to check; the open probe decides.
1057#[cfg(not(target_os = "linux"))]
1058const fn hardware_device_node(_name: &str) -> Option<bool> {
1059    None
1060}
1061
1062/// Why an export of `codec` has no encoder, and what to do about it.
1063///
1064/// Names why the GPU path declined (`gpu_output_unavailable`), what the runtime offers instead
1065/// (`offered`), and for H.264 whether `OpenH264` is installed.
1066#[must_use]
1067pub fn no_video_encoder_message(
1068    codec: NativeVideoCodec,
1069    offered: &[NativeVideoEncoderCapability],
1070    gpu_output_unavailable: Option<&str>,
1071) -> String {
1072    let identity = crate::ffmpeg_runtime_identity();
1073    let inventory = offered
1074        .iter()
1075        .filter(|capability| capability.library.is_none())
1076        .map(|capability| format!("{}:{}", capability.codec.as_str(), capability.encoder_name))
1077        .collect::<Vec<_>>()
1078        .join(", ");
1079    let mut message = format!("no usable {} encoder: ", codec.as_str());
1080    if let Some(reason) = gpu_output_unavailable {
1081        let _ = write!(message, "GPU output path unavailable ({reason}); ");
1082    }
1083    let _ = write!(
1084        message,
1085        "the linked FFmpeg runtime ({}, pinned SDK {}) offers [{}]",
1086        identity.version,
1087        identity.pinned_sdk_release,
1088        if inventory.is_empty() {
1089            "none"
1090        } else {
1091            inventory.as_str()
1092        }
1093    );
1094    if codec != NativeVideoCodec::H264 {
1095        return message;
1096    }
1097    let status = crate::openh264_status();
1098    if let Some(reason) = status.reason() {
1099        let _ = write!(
1100            message,
1101            "; OpenH264 is {}: {reason}",
1102            status.as_str().replace('-', " ")
1103        );
1104    }
1105    let _ = write!(message, ". To export H.264 here: {}", h264_encoder_remedy());
1106    message
1107}
1108
1109/// Remedies for a machine without a CPU-frame H.264 encoder: install `OpenH264`, use an `FFmpeg`
1110/// with `libx264`, or export another codec.
1111#[must_use]
1112pub fn h264_encoder_remedy() -> String {
1113    let openh264 = match crate::openh264_status() {
1114        crate::OpenH264Status::Disabled => {
1115            "unset ALPHA2_OPENH264=0 to use the installed OpenH264 encoder".to_owned()
1116        }
1117        _ => format!(
1118            "install the OpenH264 encoder ({})",
1119            crate::OPENH264_INSTALL_COMMAND
1120        ),
1121    };
1122    format!(
1123        "{openh264}, build alpha2-host from source against an FFmpeg 8 that has libx264, or \
1124         export VP9 (.webm) or AV1 instead"
1125    )
1126}
1127
1128/// [`no_video_encoder_message`] as an encode error, with `codec`'s probe refusals so a busy encoder
1129/// is told from a missing one.
1130fn unavailable_codec_error(codec: NativeVideoCodec, refused: Vec<EncoderRefusal>) -> EncodeError {
1131    let message = no_video_encoder_message(codec, &codec_capabilities().video, None);
1132    if refused.is_empty() {
1133        return EncodeError::Adapter(message);
1134    }
1135    EncodeError::EncodersRefused {
1136        message: format!("{}; {message}", refusal_list(&refused)),
1137        refusals: refused,
1138    }
1139}
1140
1141/// `refusals` for a message: `"h264_nvenc on GPU (busy): <reason>; ..."`.
1142fn refusal_list(refusals: &[EncoderRefusal]) -> String {
1143    refusals
1144        .iter()
1145        .map(|refusal| {
1146            format!(
1147                "{} {} ({}): {}",
1148                refusal.encoder,
1149                mode_label(refusal.hardware_accelerated),
1150                refusal.kind.as_str(),
1151                refusal.reason
1152            )
1153        })
1154        .collect::<Vec<_>>()
1155        .join("; ")
1156}
1157
1158/// [`video_encoder_candidates_and_refusals`] without the refusals.
1159#[cfg(test)]
1160pub(crate) fn video_encoder_candidates(
1161    codec: NativeVideoCodec,
1162    requested_name: Option<&str>,
1163) -> Result<Vec<VideoEncoderChoice>, EncodeError> {
1164    video_encoder_candidates_and_refusals(codec, requested_name).map(|(candidates, _)| candidates)
1165}
1166
1167/// Encoders to try for `codec`, most preferred first, and the probe refusals left out.
1168///
1169/// A pinned encoder is tried alone (no silent substitution), each way it runs.
1170fn video_encoder_candidates_and_refusals(
1171    codec: NativeVideoCodec,
1172    requested_name: Option<&str>,
1173) -> Result<(Vec<VideoEncoderChoice>, Vec<EncoderRefusal>), EncodeError> {
1174    if requested_name == Some(crate::OPENH264_ENCODER_NAME) {
1175        if codec != NativeVideoCodec::H264 {
1176            return Err(EncodeError::Adapter(format!(
1177                "video encoder {} does not implement {}",
1178                crate::OPENH264_ENCODER_NAME,
1179                codec.as_str()
1180            )));
1181        }
1182        let status = crate::openh264_status();
1183        return match status.library() {
1184            Some(library) => Ok((
1185                vec![VideoEncoderChoice::OpenH264(std::sync::Arc::clone(library))],
1186                Vec::new(),
1187            )),
1188            None => Err(EncodeError::Adapter(format!(
1189                "video encoder {} is unavailable: {}{}",
1190                crate::OPENH264_ENCODER_NAME,
1191                status.reason().unwrap_or_default(),
1192                status
1193                    .remedy()
1194                    .map(|remedy| format!("; {remedy}"))
1195                    .unwrap_or_default()
1196            ))),
1197        };
1198    }
1199    if let Some(name) = requested_name {
1200        let encoder = select_video_encoder(codec, Some(name))?;
1201        let (candidates, refused) = compatible_encoders(
1202            registered_video_encoders(codec)
1203                .into_iter()
1204                .filter(|candidate| candidate.encoder.as_ptr() == encoder.as_ptr())
1205                .collect(),
1206        );
1207        if candidates.is_empty() && !refused.is_empty() {
1208            return Err(EncodeError::EncodersRefused {
1209                message: refusal_list(&refused),
1210                refusals: refused,
1211            });
1212        }
1213        return Ok((candidates, refused));
1214    }
1215    let (candidates, refused) = available_video_encoders(codec);
1216    if candidates.is_empty() {
1217        return Err(unavailable_codec_error(codec, refused));
1218    }
1219    Ok((candidates, refused))
1220}
1221
1222/// The one encoder an export opens without fallback: the pinned `requested_name` (which must
1223/// implement `codec` and be advertised), else the codec's preferred encoder.
1224pub(crate) fn select_video_encoder(
1225    codec: NativeVideoCodec,
1226    requested_name: Option<&str>,
1227) -> Result<AVCodecRef<'static>, EncodeError> {
1228    if let Some(name) = requested_name {
1229        let name_c = CString::new(name)
1230            .map_err(|_| EncodeError::Adapter("video encoder name contains a NUL byte".into()))?;
1231        let encoder = AVCodec::find_encoder_by_name(&name_c)
1232            .ok_or_else(|| EncodeError::Adapter(format!("video encoder {name} is unavailable")))?;
1233        if encoder.id != codec.codec_id() {
1234            return Err(EncodeError::Adapter(format!(
1235                "video encoder {name} does not implement {}",
1236                codec.as_str()
1237            )));
1238        }
1239        let inventory = video_encoder_inventory(codec);
1240        if !inventory
1241            .usable
1242            .iter()
1243            .any(|capability| capability.encoder_name == name)
1244        {
1245            let refused = inventory
1246                .refused
1247                .into_iter()
1248                .filter(|refusal| refusal.encoder == name)
1249                .collect::<Vec<_>>();
1250            if !refused.is_empty() {
1251                return Err(EncodeError::EncodersRefused {
1252                    message: refusal_list(&refused),
1253                    refusals: refused,
1254                });
1255            }
1256            return Err(EncodeError::Adapter(format!(
1257                "video encoder {name} is not compatible with the native encode path"
1258            )));
1259        }
1260        return Ok(encoder);
1261    }
1262
1263    let inventory = video_encoder_inventory(codec);
1264    let Some(capability) = inventory
1265        .usable
1266        .into_iter()
1267        .find(|capability| capability.library.is_none())
1268    else {
1269        return Err(unavailable_codec_error(codec, inventory.refused));
1270    };
1271    let name = CString::new(capability.encoder_name)
1272        .map_err(|_| EncodeError::Adapter("video encoder name contains a NUL byte".into()))?;
1273    AVCodec::find_encoder_by_name(&name).ok_or_else(|| unavailable_codec_error(codec, Vec::new()))
1274}
1275
1276/// What one sink needs to open its video encoder.
1277pub(crate) struct VideoEncoderOpenRequest<'a> {
1278    /// Output format the encoder is configured for.
1279    pub config: &'a VideoEncodeConfig,
1280    /// Concrete encoder the caller pinned, if any.
1281    pub requested_name: Option<&'a str>,
1282    /// Software worker budget, asked for only when a CPU candidate opens.
1283    pub threads: SoftwareEncoderThreads<'a>,
1284    /// Whether the container wants the extradata in the stream header.
1285    pub global_header: bool,
1286    /// Coded width, already range-checked by the caller.
1287    pub width: i32,
1288    /// Coded height, already range-checked by the caller.
1289    pub height: i32,
1290}
1291
1292/// The worker count a software video encoder opens with, decided only when one opens.
1293///
1294/// The decode/encode CPU split depends on whether the encoder runs on the CPU, which is known only
1295/// after a candidate opens: a hardware encoder may fail and fall through to a software one, which
1296/// must not inherit the hardware split's zero share. Asked at most once.
1297pub(crate) struct SoftwareEncoderThreads<'a> {
1298    decide: &'a dyn Fn(Option<usize>) -> i64,
1299    decided: std::cell::OnceCell<i64>,
1300}
1301
1302impl<'a> SoftwareEncoderThreads<'a> {
1303    /// Defers the count to `decide`, which receives the encoder's own count when the picture
1304    /// fixes it ([`crate::CodecThreadRequest::encoder_fixed_threads`]).
1305    pub(crate) fn new(decide: &'a dyn Fn(Option<usize>) -> i64) -> Self {
1306        Self {
1307            decide,
1308            decided: std::cell::OnceCell::new(),
1309        }
1310    }
1311
1312    /// The decided count for an encoder that runs as many workers as it is given.
1313    pub(crate) fn get(&self) -> i64 {
1314        self.get_fixed(None)
1315    }
1316
1317    /// The decided count, for an encoder that runs `fixed` workers when it does.
1318    pub(crate) fn get_fixed(&self, fixed: Option<usize>) -> i64 {
1319        *self.decided.get_or_init(|| (self.decide)(fixed).max(1))
1320    }
1321}
1322
1323/// Opens the first candidate encoder this machine can actually run.
1324///
1325/// A registered encoder may still fail `avcodec_open2` (no MFT, no device). Each rejection is
1326/// recorded with a typed reason so the run reports which encoder it ended up on.
1327///
1328/// # Errors
1329/// Returns the last candidate's failure, prefixed with every earlier one, when none opens.
1330pub(crate) fn open_video_encoder(
1331    request: &VideoEncoderOpenRequest<'_>,
1332) -> Result<
1333    (
1334        crate::video_backend::VideoEncoderBackend,
1335        NativeVideoEncoderSelection,
1336    ),
1337    EncodeError,
1338> {
1339    let (candidates, refused) =
1340        video_encoder_candidates_and_refusals(request.config.codec, request.requested_name)?;
1341    open_first_video_encoder(request, candidates).map_err(|error| match error {
1342        // Probe refusals come first; a busy one among them decides the class.
1343        EncodeError::EncodersRefused {
1344            message,
1345            refusals: opened,
1346        } if !refused.is_empty() => EncodeError::EncodersRefused {
1347            message: format!("{}; {message}", refusal_list(&refused)),
1348            refusals: refused.into_iter().chain(opened).collect(),
1349        },
1350        error => error,
1351    })
1352}
1353
1354/// An opened encoder, how it runs the rate control, and its CPU workers.
1355struct OpenedVideoEncoder {
1356    backend: crate::video_backend::VideoEncoderBackend,
1357    rate_control: crate::AppliedRateControl,
1358    quantizer_refused: Option<String>,
1359    software_threads: Option<i64>,
1360    pixels: alpha2_media::PixelLayout,
1361}
1362
1363/// Opens the first of `candidates` that runs, recording why each earlier one did not.
1364pub(crate) fn open_first_video_encoder(
1365    request: &VideoEncoderOpenRequest<'_>,
1366    candidates: Vec<VideoEncoderChoice>,
1367) -> Result<
1368    (
1369        crate::video_backend::VideoEncoderBackend,
1370        NativeVideoEncoderSelection,
1371    ),
1372    EncodeError,
1373> {
1374    let mut rejected = Vec::new();
1375    let last = candidates.len().saturating_sub(1);
1376    for (index, candidate) in candidates.into_iter().enumerate() {
1377        let name = candidate.name();
1378        let class = candidate.class();
1379        let mark = alpha2_ffmpeg_bridge::log_mark();
1380        let opened = match &candidate {
1381            VideoEncoderChoice::Ffmpeg(candidate) => {
1382                open_one_video_encoder(request, candidate, &name).map(
1383                    |(encoder, rate_control, quantizer_refused, pixels)| OpenedVideoEncoder {
1384                        backend: crate::video_backend::VideoEncoderBackend::Ffmpeg(encoder),
1385                        rate_control,
1386                        quantizer_refused,
1387                        software_threads: (!candidate.on_hardware).then(|| request.threads.get()),
1388                        pixels,
1389                    },
1390                )
1391            }
1392            VideoEncoderChoice::OpenH264(library) => open_openh264(request, library),
1393        };
1394        match opened {
1395            Ok(opened) => {
1396                return Ok((
1397                    opened.backend,
1398                    NativeVideoEncoderSelection {
1399                        encoder_name: name,
1400                        class,
1401                        hardware_accelerated: candidate.on_hardware(),
1402                        rejected,
1403                        rate_control: opened.rate_control,
1404                        quantizer_refused: opened.quantizer_refused,
1405                        software_threads: opened.software_threads,
1406                        pixels: opened.pixels,
1407                    },
1408                ));
1409            }
1410            Err((reason, error)) => {
1411                let (kind, detail) = rejection_kind(&name, reason, &error, mark);
1412                if index == last {
1413                    let earlier = rejected
1414                        .iter()
1415                        .map(|fallback: &NativeVideoEncoderFallback| {
1416                            format!(
1417                                "{} {} ({}): {}",
1418                                fallback.encoder_name,
1419                                mode_label(fallback.hardware_accelerated),
1420                                fallback.reason.as_str(),
1421                                fallback.detail
1422                            )
1423                        })
1424                        .collect::<Vec<_>>();
1425                    let prefix = if earlier.is_empty() {
1426                        String::new()
1427                    } else {
1428                        format!("after {}; ", earlier.join("; "))
1429                    };
1430                    let message = format!(
1431                        "{prefix}{name} {} ({}): {detail}",
1432                        mode_label(candidate.on_hardware()),
1433                        reason.as_str()
1434                    );
1435                    let refusals = rejected
1436                        .iter()
1437                        .map(NativeVideoEncoderFallback::refusal)
1438                        .chain([EncoderRefusal {
1439                            encoder: name,
1440                            hardware_accelerated: candidate.on_hardware(),
1441                            kind,
1442                            reason: detail,
1443                        }])
1444                        .collect();
1445                    return Err(EncodeError::EncodersRefused { message, refusals });
1446                }
1447                alpha2_os::diagnostic!(
1448                    "alpha2 native export: video encoder {name} {} ({}) rejected: {detail}",
1449                    mode_label(candidate.on_hardware()),
1450                    reason.as_str()
1451                );
1452                rejected.push(NativeVideoEncoderFallback {
1453                    encoder_name: name,
1454                    hardware_accelerated: candidate.on_hardware(),
1455                    reason,
1456                    kind,
1457                    detail,
1458                });
1459            }
1460        }
1461    }
1462    Err(unavailable_codec_error(request.config.codec, Vec::new()))
1463}
1464
1465/// What a rejection of `name` is evidence of, and its detail. Open failures are classified from the
1466/// lines logged since `mark`.
1467fn rejection_kind(
1468    name: &str,
1469    reason: NativeEncoderRejection,
1470    error: &EncodeError,
1471    mark: alpha2_ffmpeg_bridge::LogMark,
1472) -> (OpenFailureKind, String) {
1473    match reason {
1474        NativeEncoderRejection::OpenFailed => {
1475            let lines = alpha2_ffmpeg_bridge::log_since(mark, &[name]);
1476            let detail = error.to_string();
1477            (
1478                classify_open_failure(name, &detail, &lines),
1479                format!("{detail}{}", alpha2_ffmpeg_bridge::log_detail(&lines)),
1480            )
1481        }
1482        NativeEncoderRejection::Dimensions
1483        | NativeEncoderRejection::OptionsIgnored
1484        | NativeEncoderRejection::PixelFormat => (OpenFailureKind::Unsuitable, error.to_string()),
1485    }
1486}
1487
1488/// Opens `OpenH264` on constant QP when the rate control has a quantizer, else on bitrate.
1489///
1490/// Its thread count comes from the picture height (`openh264::encoder::slice_count`). The software
1491/// budget is still decided here because the rest of the export splits the CPU from it.
1492fn open_openh264(
1493    request: &VideoEncoderOpenRequest<'_>,
1494    library: &crate::OpenH264Library,
1495) -> Result<OpenedVideoEncoder, (NativeEncoderRejection, EncodeError)> {
1496    let config = request.config;
1497    if !config.pixels.is_yuv420p() {
1498        return Err((
1499            NativeEncoderRejection::PixelFormat,
1500            EncodeError::Adapter(format!(
1501                "OpenH264 writes 8-bit 4:2:0 only, not {}",
1502                config.pixels.ffmpeg_name()
1503            )),
1504        ));
1505    }
1506    validate_encoder_dimensions(crate::OPENH264_ENCODER_NAME, config.width, config.height)
1507        .map_err(|error| (NativeEncoderRejection::Dimensions, error))?;
1508    let open_failed = |message: String| {
1509        (
1510            NativeEncoderRejection::OpenFailed,
1511            EncodeError::Adapter(message),
1512        )
1513    };
1514    if !request.global_header {
1515        return Err(open_failed(
1516            "OpenH264 writes its parameter sets into the stream header, which this container \
1517             lacks"
1518                .to_owned(),
1519        ));
1520    }
1521    let (rate, rate_control) = crate::rate_control::openh264_rate(config.rate_control);
1522    let time_base = encoder_time_base(config.frame_rate, None)
1523        .map_err(|error| (NativeEncoderRejection::OpenFailed, error))?;
1524    // OpenH264 runs one thread per slice whatever it is offered; the split reserves that count.
1525    let _ = request
1526        .threads
1527        .get_fixed(Some(usize::from(crate::openh264::thread_count(
1528            crate::openh264::slice_count(config.height),
1529        ))));
1530    let encoder = crate::openh264::OpenH264Encoder::open(
1531        library,
1532        &crate::openh264::OpenH264Settings {
1533            width: config.width,
1534            height: config.height,
1535            frame_rate: config.frame_rate,
1536            color: config.color,
1537            sample_aspect_ratio: config.display.sample_aspect_ratio,
1538            rate,
1539            keyframe_interval: u32::try_from(keyframe_interval(config.frame_rate)).unwrap_or(1),
1540        },
1541        time_base,
1542    )
1543    .map_err(open_failed)?;
1544    let threads = i64::from(encoder.threads());
1545    Ok(OpenedVideoEncoder {
1546        backend: crate::video_backend::VideoEncoderBackend::OpenH264(Box::new(encoder)),
1547        rate_control,
1548        quantizer_refused: None,
1549        software_threads: Some(threads),
1550        pixels: alpha2_media::PixelLayout::YUV420P,
1551    })
1552}
1553
1554/// An opened context, its rate control, why a quantizer was refused, and the pictures it takes.
1555type OpenedContext = (
1556    EncoderContext,
1557    crate::AppliedRateControl,
1558    Option<String>,
1559    alpha2_media::PixelLayout,
1560);
1561
1562/// Opens `candidate` on the quantizer when the encoder accepts it, otherwise on bitrate.
1563///
1564/// A refused quantizer is not a refused encoder: the export continues on
1565/// the bitrate and reports it.
1566fn open_one_video_encoder(
1567    request: &VideoEncoderOpenRequest<'_>,
1568    candidate: &VideoEncoderCandidate,
1569    name: &str,
1570) -> Result<OpenedContext, (NativeEncoderRejection, EncodeError)> {
1571    let pixels = encoder_layout(&candidate.encoder, request.config.pixels).ok_or_else(|| {
1572        (
1573            NativeEncoderRejection::PixelFormat,
1574            EncodeError::Adapter(format!(
1575                "{name} does not take {} pictures",
1576                request.config.pixels.ffmpeg_name()
1577            )),
1578        )
1579    })?;
1580    validate_encoder_dimensions(name, request.config.width, request.config.height)
1581        .map_err(|error| (NativeEncoderRejection::Dimensions, error))?;
1582    let refused = match crate::rate_control::quantizer_request(name, request.config.rate_control) {
1583        None => None,
1584        Some(Err(reason)) => Some(reason),
1585        Some(Ok(quantized)) => {
1586            match open_video_encoder_context(request, candidate, name, Some(&quantized), pixels) {
1587                Ok(encoder) => {
1588                    let applied = crate::AppliedRateControl::of_quantizer_request(name);
1589                    return Ok((encoder, applied, None, pixels));
1590                }
1591                Err((_, error)) => Some(format!("{} refused: {error}", quantized.describe())),
1592            }
1593        }
1594    };
1595    if let Some(reason) = &refused {
1596        alpha2_os::diagnostic!("alpha2 native export: {name} runs the bitrate fallback: {reason}");
1597    }
1598    open_video_encoder_context(request, candidate, name, None, pixels)
1599        .map(|encoder| (encoder, crate::AppliedRateControl::Bitrate, refused, pixels))
1600}
1601
1602fn open_video_encoder_context(
1603    request: &VideoEncoderOpenRequest<'_>,
1604    candidate: &VideoEncoderCandidate,
1605    name: &str,
1606    quantized: Option<&crate::rate_control::MechanismRequest>,
1607    pixels: alpha2_media::PixelLayout,
1608) -> Result<EncoderContext, (NativeEncoderRejection, EncodeError)> {
1609    let mut encoder = EncoderContext::from(AVCodecContext::new(&candidate.encoder));
1610    encoder.set_width(request.width);
1611    encoder.set_height(request.height);
1612    encoder.set_pix_fmt(crate::convert::pixel_format(pixels));
1613    let rate = request.config.frame_rate;
1614    let time_base = encoder_time_base(rate, max_time_base_denominator(candidate.encoder.id))
1615        .map_err(|error| (NativeEncoderRejection::OpenFailed, error))?;
1616    encoder.set_time_base(time_base);
1617    // Square pixels are the default; only another ratio is written.
1618    let sar = request.config.display.sample_aspect_ratio;
1619    if sar != alpha2_media::SampleAspectRatio::default() {
1620        encoder.set_sample_aspect_ratio(rsmpeg::avutil::ra(
1621            i32::try_from(sar.num).unwrap_or(1),
1622            i32::try_from(sar.den).unwrap_or(1),
1623        ));
1624    }
1625    encoder.set_framerate(rsmpeg::avutil::ra(
1626        i32::try_from(rate.numerator()).unwrap_or(i32::MAX),
1627        i32::try_from(rate.denominator()).unwrap_or(1),
1628    ));
1629    encoder.set_bit_rate(quantized.map_or_else(
1630        || i64::try_from(request.config.rate_control.bitrate).unwrap_or(i64::MAX),
1631        |quantized| quantized.bit_rate,
1632    ));
1633    encoder.set_gop_size(keyframe_interval(request.config.frame_rate));
1634    encoder.set_max_b_frames(encoder_max_b_frames(name));
1635    if request.global_header {
1636        let flags = encoder.flags | i32::try_from(ffi::AV_CODEC_FLAG_GLOBAL_HEADER).unwrap_or(0);
1637        encoder.set_flags(flags);
1638    }
1639    // Hardware candidates never decide the software split.
1640    let threads = if candidate.on_hardware {
1641        0
1642    } else {
1643        request.threads.get()
1644    };
1645    let mut base = video_encoder_options(
1646        request.config.color,
1647        &candidate.encoder,
1648        candidate.on_hardware,
1649        threads,
1650        request.config.width,
1651    );
1652    if candidate.codec() == NativeVideoCodec::ProRes {
1653        for (key, value) in crate::convert::prores_options(pixels) {
1654            base = crate::convert::set_encoder_option(base, key, &value);
1655        }
1656    }
1657    let options = match quantized {
1658        Some(quantized) => quantized.dictionary(base),
1659        None => crate::rate_control::rate_control_options(name, request.config.rate_control, base),
1660    };
1661    let unused =
1662        alpha2_ffmpeg_bridge::open_codec_context(&mut encoder, options).map_err(|error| {
1663            let hint = match quantized {
1664                Some(_) => "",
1665                None => crate::rate_control::constant_rate_hint(name, request.config.rate_control),
1666            };
1667            let error = match encode_adapter_error(error) {
1668                EncodeError::Adapter(message) if !hint.is_empty() => {
1669                    EncodeError::Adapter(format!("{message}{hint}"))
1670                }
1671                error => error,
1672            };
1673            (NativeEncoderRejection::OpenFailed, error)
1674        })?;
1675    reject_unused_encode_options(unused)
1676        .map_err(|error| (NativeEncoderRejection::OptionsIgnored, error))?;
1677    Ok(encoder)
1678}
1679
1680/// Frames between forced keyframes: two seconds of output.
1681///
1682/// libavcodec's default of 12 is half a second at 24 fps. Two seconds keeps nearly all of the
1683/// quality gain of longer intervals (about 0.5-0.8 dB PSNR-Y over 12 on hardware H.264) while a
1684/// player can still seek within two seconds.
1685pub(crate) fn keyframe_interval(frame_rate: alpha2_time::FrameRate) -> i32 {
1686    let frames = (2 * u64::from(frame_rate.numerator()))
1687        .div_ceil(u64::from(frame_rate.denominator()))
1688        .max(1);
1689    i32::try_from(frames).unwrap_or(i32::MAX)
1690}
1691
1692/// The largest time base denominator encoders of `codec` can write, if limited. MPEG-4 Part 2 and
1693/// H.263 store it in 16 bits, so 1001/120000 (119.88 fps) is refused.
1694pub(crate) const fn max_time_base_denominator(codec: ffi::AVCodecID) -> Option<u32> {
1695    match codec {
1696        ffi::AV_CODEC_ID_MPEG4 | ffi::AV_CODEC_ID_H263 | ffi::AV_CODEC_ID_H263P => Some(65_535),
1697        _ => None,
1698    }
1699}
1700
1701/// The time base for frames at `rate`: the frame length (1001/30000 for 29.97 fps) when its
1702/// denominator is within `limit`, else 1/D for the D within `limit` with the smallest worst-case
1703/// rounding of frame times. 119.88 fps becomes 1/64000, off by at most 7/960000 s.
1704///
1705/// # Errors
1706/// For a rate whose terms do not fit an `FFmpeg` rational.
1707pub(crate) fn encoder_time_base(
1708    rate: alpha2_time::FrameRate,
1709    limit: Option<u32>,
1710) -> Result<AVRational, EncodeError> {
1711    let out_of_range = || EncodeError::Adapter("frame rate is out of range".into());
1712    let (num, den) = (u64::from(rate.numerator()), u64::from(rate.denominator()));
1713    let exact = || {
1714        Ok(rsmpeg::avutil::ra(
1715            i32::try_from(den).map_err(|_| out_of_range())?,
1716            i32::try_from(num).map_err(|_| out_of_range())?,
1717        ))
1718    };
1719    let Some(limit) = limit.map(u64::from).filter(|limit| num > *limit) else {
1720        return exact();
1721    };
1722    // Frame k is at k*den/num s, k*den*D/num units of 1/D. Its fractional part is a multiple of
1723    // 1/q, q = num / gcd(num, den*D), so the largest rounding is floor(q/2)/q units. A unit no
1724    // longer than a frame keeps every frame its own time.
1725    let mut best: Option<(u64, u64, u64)> = None;
1726    for units in num.div_ceil(den).max(1)..=limit {
1727        let q = num / gcd_u64(num, den * units);
1728        let (error, scale) = (q / 2, q * units);
1729        if best.is_none_or(|(_, best_error, best_scale)| {
1730            u128::from(error) * u128::from(best_scale) < u128::from(best_error) * u128::from(scale)
1731        }) {
1732            best = Some((units, error, scale));
1733        }
1734    }
1735    let (units, _, _) = best.ok_or_else(out_of_range)?;
1736    Ok(rsmpeg::avutil::ra(
1737        1,
1738        i32::try_from(units).map_err(|_| out_of_range())?,
1739    ))
1740}
1741
1742const fn gcd_u64(mut a: u64, mut b: u64) -> u64 {
1743    while b != 0 {
1744        (a, b) = (b, a % b);
1745    }
1746    a
1747}
1748
1749pub(crate) fn encoder_max_b_frames(name: &str) -> i32 {
1750    // Keep VideoToolbox's default of no reordering: forced B-frames are device-dependent and can
1751    // produce invalid packet timestamps.
1752    if name.ends_with("_videotoolbox") {
1753        0
1754    } else {
1755        2
1756    }
1757}
1758
1759/// The smallest even width and height encoder `name` accepts.
1760#[must_use]
1761pub fn encoder_minimum_dimensions(name: &str) -> (u32, u32) {
1762    // NVIDIA AV1 requires at least 145x128, its H.264/HEVC encoders 145x49; sizes stay even.
1763    if name == "av1_nvenc" {
1764        (146, 128)
1765    } else if name.ends_with("_nvenc") {
1766        (146, 50)
1767    } else {
1768        (2, 2)
1769    }
1770}
1771
1772pub(crate) fn validate_encoder_dimensions(
1773    encoder_name: &str,
1774    width: u32,
1775    height: u32,
1776) -> Result<(), EncodeError> {
1777    let (minimum_width, minimum_height) = encoder_minimum_dimensions(encoder_name);
1778    if width < minimum_width || height < minimum_height {
1779        Err(EncodeError::Adapter(format!(
1780            "encoder {encoder_name} requires at least {minimum_width}x{minimum_height}, received {width}x{height}"
1781        )))
1782    } else {
1783        Ok(())
1784    }
1785}
1786
1787/// One hardware configuration a video encoder declares.
1788#[derive(Clone, Debug, Eq, PartialEq)]
1789pub struct NativeEncoderHardwareConfig {
1790    /// Hardware pixel format this configuration carries frames in.
1791    pub pixel_format: String,
1792    /// `FFmpeg` hardware device type backing it.
1793    pub device_type: String,
1794    /// `AV_CODEC_HW_CONFIG_METHOD_*` bits.
1795    pub methods: i32,
1796    /// Whether the encoder takes its frames through an `AVHWFramesContext`.
1797    pub needs_hardware_frames: bool,
1798}
1799
1800/// What one registered video encoder declares, and what happened when alpha2 opened it.
1801///
1802/// Shows registration, advertisement and instantiation side by side, per platform.
1803#[derive(Clone, Debug, Eq, PartialEq)]
1804// Independent observations of one encoder, reported side by side, not a state.
1805#[allow(clippy::struct_excessive_bools)]
1806pub struct NativeVideoEncoderProbe {
1807    /// Logical codec this encoder implements.
1808    pub codec: NativeVideoCodec,
1809    /// `FFmpeg` short name.
1810    pub encoder_name: String,
1811    /// Class taken from the encoder's own capability bits.
1812    pub class: NativeEncoderClass,
1813    /// Whether this row runs the encoder on the GPU.
1814    pub hardware_accelerated: bool,
1815    /// Raw `AV_CODEC_CAP_*` bits, so an unexpected class can be traced.
1816    pub capability_bits: u32,
1817    /// Pixel formats the encoder declares, or empty when it declares none.
1818    pub pixel_formats: Vec<String>,
1819    /// Hardware configurations the encoder declares.
1820    pub hardware_configs: Vec<NativeEncoderHardwareConfig>,
1821    /// Whether `AV_PIX_FMT_YUV420P` is among the declared formats.
1822    pub accepts_yuv420p: bool,
1823    /// Whether every declared format is a hardware one (why `h264_vulkan` is not advertised).
1824    pub requires_hardware_frames: bool,
1825    /// Whether [`codec_capabilities`] advertises it for the YUV420P sink.
1826    pub advertised: bool,
1827    /// Smallest frame the encoder accepts, as alpha2 records it.
1828    pub minimum_size: (u32, u32),
1829    /// `None` when a software YUV420P frame produced a packet; otherwise why not.
1830    pub software_open_error: Option<String>,
1831    /// Packets drained from that attempt.
1832    pub software_packets: u32,
1833    /// Which rate-control mechanisms opened, and with what options.
1834    pub rate_control: Vec<NativeRateControlProbe>,
1835}
1836
1837/// Whether one encoder opened with one rate-control mechanism.
1838#[derive(Clone, Debug, Eq, PartialEq)]
1839pub struct NativeRateControlProbe {
1840    /// The mechanism asked for.
1841    pub mechanism: crate::RateControlMechanism,
1842    /// The options that carried it, or `None` where alpha2 knows no spelling for this family.
1843    pub options: Option<String>,
1844    /// Packets drained when it opened, used every option and encoded a frame; otherwise why not.
1845    pub outcome: Result<u32, String>,
1846    /// The device a hardware-frames encoder was probed on: a Vulkan device index, or for
1847    /// `*_d3d12va` the answering adapter (`DX12 adapter <index> (<name>)`).
1848    pub device: Option<String>,
1849}
1850
1851/// A quantizer every encoder of `codec` accepts: `crf` 0-63 for
1852/// `libvpx-vp9`/`libsvtav1`, QP 0-255 for hardware.
1853pub(crate) const fn probe_quantizer(codec: NativeVideoCodec, software: bool) -> u32 {
1854    match codec {
1855        NativeVideoCodec::H264 | NativeVideoCodec::Hevc => 26,
1856        NativeVideoCodec::Av1 | NativeVideoCodec::Vp9 => {
1857            if software {
1858                32
1859            } else {
1860                100
1861            }
1862        }
1863        NativeVideoCodec::Mpeg4Part2 => 4,
1864        // Never asked: `ProRes` has no quantizer mode alpha2 opens.
1865        NativeVideoCodec::ProRes => 0,
1866    }
1867}
1868
1869/// Opens every registered video encoder and reports what it actually does.
1870///
1871/// Each candidate is opened at `width`x`height` and fed one YUV420P frame, so the report tells
1872/// registered, advertised and ran apart. A hybrid encoder has a row per mode.
1873#[must_use]
1874#[allow(clippy::too_many_lines)]
1875pub fn probe_video_encoders(width: u32, height: u32) -> Vec<NativeVideoEncoderProbe> {
1876    let advertised = codec_capabilities();
1877    [
1878        NativeVideoCodec::H264,
1879        NativeVideoCodec::Hevc,
1880        NativeVideoCodec::Vp9,
1881        NativeVideoCodec::Av1,
1882        NativeVideoCodec::Mpeg4Part2,
1883        NativeVideoCodec::ProRes,
1884    ]
1885    .into_iter()
1886    .flat_map(|codec| {
1887        registered_video_encoders(codec)
1888            .into_iter()
1889            .map(move |candidate| (codec, candidate))
1890    })
1891    .map(|(codec, candidate)| {
1892        let encoder = &candidate.encoder;
1893        let encoder_name = candidate.name();
1894        let pixel_formats = encoder.pix_fmts().map_or_else(Vec::new, |formats| {
1895            formats
1896                .iter()
1897                .map(|format| {
1898                    alpha2_ffmpeg_bridge::pixel_format_name(*format)
1899                        .unwrap_or_else(|| "unknown".to_owned())
1900                })
1901                .collect()
1902        });
1903        let hardware_configs = (0..)
1904            .map_while(|index| encoder.hw_config(index))
1905            .map(|config| NativeEncoderHardwareConfig {
1906                pixel_format: alpha2_ffmpeg_bridge::pixel_format_name(config.pix_fmt)
1907                    .unwrap_or_else(|| "unknown".to_owned()),
1908                device_type: alpha2_ffmpeg_bridge::hardware_device_type_name(config.device_type)
1909                    .unwrap_or_else(|| "none".to_owned()),
1910                methods: config.methods,
1911                needs_hardware_frames: crate::decode::has_hw_config_method(
1912                    config.methods,
1913                    ffi::AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX,
1914                ),
1915            })
1916            .collect::<Vec<_>>();
1917        let accepts_yuv420p = encoder
1918            .pix_fmts()
1919            .is_none_or(|formats| formats.contains(&ffi::AV_PIX_FMT_YUV420P));
1920        let (software_open_error, software_packets) =
1921            probe_software_encode(&candidate, &encoder_name, width, height, None);
1922        let requires_hardware_frames = !accepts_yuv420p
1923            && hardware_configs
1924                .iter()
1925                .any(|config| config.needs_hardware_frames);
1926        let rate_control = crate::RateControlMechanism::ALL
1927            .into_iter()
1928            .map(|mechanism| {
1929                let request = crate::rate_control::mechanism_request(
1930                    &encoder_name,
1931                    mechanism,
1932                    2_000_000,
1933                    // D3D12VA takes 0-52 for every codec, AV1 included.
1934                    if encoder_name.ends_with("_d3d12va") {
1935                        26
1936                    } else {
1937                        probe_quantizer(
1938                            codec,
1939                            encoder_class(encoder) == NativeEncoderClass::Software,
1940                        )
1941                    },
1942                );
1943                let mut device = None;
1944                let outcome = match &request {
1945                    None => Err("no known option for this encoder family".to_owned()),
1946                    Some(request) if requires_hardware_frames => probe_hardware_frames_encode(
1947                        encoder,
1948                        &encoder_name,
1949                        (width, height),
1950                        mechanism,
1951                        request,
1952                    )
1953                    .map(|(packets, on)| {
1954                        device = Some(on);
1955                        packets
1956                    }),
1957                    Some(request) => {
1958                        match probe_software_encode(
1959                            &candidate,
1960                            &encoder_name,
1961                            width,
1962                            height,
1963                            Some(request),
1964                        ) {
1965                            (None, packets) => Ok(packets),
1966                            (Some(error), _) => Err(error),
1967                        }
1968                    }
1969                };
1970                NativeRateControlProbe {
1971                    mechanism,
1972                    options: request
1973                        .as_ref()
1974                        .map(crate::rate_control::MechanismRequest::describe),
1975                    outcome,
1976                    device,
1977                }
1978            })
1979            .collect();
1980        NativeVideoEncoderProbe {
1981            codec,
1982            class: encoder_class(encoder),
1983            hardware_accelerated: candidate.on_hardware,
1984            capability_bits: u32::try_from(encoder.capabilities).unwrap_or(0),
1985            advertised: advertised.video.iter().any(|capability| {
1986                capability.codec == codec
1987                    && capability.encoder_name == encoder_name
1988                    && capability.hardware_accelerated == candidate.on_hardware
1989            }),
1990            minimum_size: encoder_minimum_dimensions(&encoder_name),
1991            requires_hardware_frames,
1992            accepts_yuv420p,
1993            pixel_formats,
1994            hardware_configs,
1995            encoder_name,
1996            software_open_error,
1997            software_packets,
1998            rate_control,
1999        }
2000    })
2001    .collect()
2002}
2003
2004/// Opens an encoder that only takes hardware frames, with `request`.
2005///
2006/// For `*_vulkan`, `FFmpeg` creates its own device with whatever video-encode queue is offered.
2007/// D3D12VA rows open on the first DX12 adapter whose D3D12 Video Encode reports the encoder; a mode
2008/// the device does not list is refused with its reason.
2009///
2010/// Returns the packets and the answering device (Vulkan index, or DX12 adapter index and name).
2011#[allow(unused_variables)]
2012fn probe_hardware_frames_encode(
2013    encoder: &AVCodecRef<'static>,
2014    name: &str,
2015    (width, height): (u32, u32),
2016    mechanism: crate::RateControlMechanism,
2017    request: &crate::rate_control::MechanismRequest,
2018) -> Result<(u32, String), String> {
2019    #[cfg(all(target_os = "linux", feature = "hwencode"))]
2020    if name.ends_with("_vulkan") {
2021        return crate::hwencode::probe_vulkan_rate_control(encoder, width, height, request);
2022    }
2023    #[cfg(all(target_os = "windows", feature = "hwencode"))]
2024    if name.ends_with("_d3d12va") {
2025        return crate::hwencode::probe_d3d12va_rate_control(
2026            name, width, height, mechanism, request,
2027        );
2028    }
2029    Err("takes hardware frames this probe cannot supply".to_owned())
2030}
2031
2032/// Opens `candidate` and feeds it one software YUV420P frame.
2033fn probe_software_encode(
2034    candidate: &VideoEncoderCandidate,
2035    name: &str,
2036    width: u32,
2037    height: u32,
2038    request: Option<&crate::rate_control::MechanismRequest>,
2039) -> (Option<String>, u32) {
2040    let Ok(coded_width) = i32::try_from(width) else {
2041        return (Some("width is out of range".to_owned()), 0);
2042    };
2043    let Ok(coded_height) = i32::try_from(height) else {
2044        return (Some("height is out of range".to_owned()), 0);
2045    };
2046    if let Err(error) = validate_encoder_dimensions(name, width, height) {
2047        return (Some(error.to_string()), 0);
2048    }
2049    let encoder = &candidate.encoder;
2050    let base = candidate.codec().base_layout();
2051    let format =
2052        encoder_layout(encoder, base).map_or(ffi::AV_PIX_FMT_YUV420P, crate::convert::pixel_format);
2053    let mut context = EncoderContext::from(AVCodecContext::new(encoder));
2054    context.set_width(coded_width);
2055    context.set_height(coded_height);
2056    context.set_pix_fmt(format);
2057    let time_base = rsmpeg::avutil::ra(1, 30);
2058    context.set_time_base(time_base);
2059    context.set_framerate(rsmpeg::avutil::ra(30, 1));
2060    context.set_bit_rate(request.map_or(2_000_000, |request| request.bit_rate));
2061    context.set_gop_size(12);
2062    context.set_max_b_frames(encoder_max_b_frames(name));
2063    let options = video_encoder_options(
2064        ColorMetadata::EXPORT,
2065        encoder,
2066        candidate.on_hardware,
2067        1,
2068        width,
2069    );
2070    let options = match request {
2071        Some(request) => request.dictionary(options),
2072        None => options,
2073    };
2074    match alpha2_ffmpeg_bridge::open_codec_context(&mut context, options) {
2075        Err(error) => return (Some(error.to_string()), 0),
2076        Ok(unused) => {
2077            if let Err(error) = reject_unused_encode_options(unused) {
2078                return (Some(error.to_string()), 0);
2079            }
2080        }
2081    }
2082    let Some(image) = rsmpeg::avutil::AVImage::new(format, coded_width, coded_height, 1) else {
2083        return (Some("cannot allocate a probe frame".to_owned()), 0);
2084    };
2085    let mut frame = rsmpeg::avutil::AVFrameWithImage::new(image);
2086    frame.set_pts(0);
2087    frame.set_time_base(time_base);
2088    if let Err(error) = context.send_frame(Some(&frame)) {
2089        return (Some(error.to_string()), 0);
2090    }
2091    if let Err(error) = context.send_frame(None) {
2092        return (Some(error.to_string()), 0);
2093    }
2094    let mut packets = 0;
2095    loop {
2096        match context.receive_packet() {
2097            Ok(_) => packets += 1,
2098            Err(RsmpegError::EncoderDrainError | RsmpegError::EncoderFlushedError) => break,
2099            Err(error) => return (Some(error.to_string()), packets),
2100        }
2101    }
2102    if packets == 0 {
2103        return (
2104            Some("opened but produced no packet from a software frame".to_owned()),
2105            0,
2106        );
2107    }
2108    (None, packets)
2109}