Skip to main content

alpha2_native/
capabilities.rs

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