1use 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#[derive(Copy, Clone, Debug, PartialEq)]
21pub struct AvEncodeConfig {
22 pub video: VideoEncodeConfig,
24 pub audio_sample_rate: u32,
26 pub audio_channels: u16,
28 pub audio_codec: NativeAudioCodec,
30 pub audio_bit_rate: u32,
32}
33
34#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
36#[non_exhaustive]
37pub enum NativeVideoCodec {
38 H264,
40 Hevc,
42 Vp9,
44 Av1,
46 Mpeg4Part2,
48 ProRes,
50}
51
52impl NativeVideoCodec {
53 #[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 #[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 #[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 #[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#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
121#[non_exhaustive]
122pub enum NativeAudioCodec {
123 Aac,
125 Opus,
127}
128
129impl NativeAudioCodec {
130 pub const ALL: [Self; 2] = [Self::Aac, Self::Opus];
132
133 #[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 #[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 #[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 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
170pub(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#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
183#[non_exhaustive]
184pub enum NativeEncoderClass {
185 Software,
187 Hardware,
189 Hybrid,
192}
193
194impl NativeEncoderClass {
195 #[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 #[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
217pub(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#[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#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
256#[non_exhaustive]
257pub enum NativeEncoderRejection {
258 Dimensions,
260 OpenFailed,
262 OptionsIgnored,
264 PixelFormat,
266}
267
268impl NativeEncoderRejection {
269 #[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#[derive(Clone, Debug, Eq, PartialEq)]
283pub struct NativeVideoEncoderFallback {
284 pub encoder_name: String,
286 pub hardware_accelerated: bool,
288 pub reason: NativeEncoderRejection,
290 pub kind: OpenFailureKind,
292 pub detail: String,
294}
295
296impl NativeVideoEncoderFallback {
297 #[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#[derive(Clone, Debug, Eq, PartialEq)]
313pub struct NativeVideoEncoderSelection {
314 pub encoder_name: String,
316 pub class: NativeEncoderClass,
318 pub hardware_accelerated: bool,
320 pub rejected: Vec<NativeVideoEncoderFallback>,
322 pub rate_control: crate::AppliedRateControl,
324 pub quantizer_refused: Option<String>,
326 pub software_threads: Option<i64>,
328 pub pixels: alpha2_media::PixelLayout,
331}
332
333#[derive(Clone, Debug, Eq, PartialEq)]
335pub struct NativeVideoEncoderCapability {
336 pub codec: NativeVideoCodec,
338 pub encoder_name: String,
340 pub class: NativeEncoderClass,
342 pub hardware_accelerated: bool,
344 pub preferred: bool,
346 pub minimum_width: u32,
348 pub minimum_height: u32,
350 pub library: Option<NativeEncoderLibrary>,
352}
353
354#[derive(Clone, Debug, Eq, PartialEq)]
356pub struct NativeEncoderLibrary {
357 pub provider: &'static str,
359 pub version: String,
361 pub path: String,
363 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#[derive(Clone, Debug, Eq, PartialEq)]
380pub struct NativeAudioEncoderCapability {
381 pub codec: NativeAudioCodec,
383 pub encoder_name: String,
385}
386
387#[derive(Clone, Debug, Eq, PartialEq)]
392pub struct NativeCodecCapabilities {
393 pub video: Vec<NativeVideoEncoderCapability>,
396 pub audio: Vec<NativeAudioEncoderCapability>,
399}
400
401#[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#[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#[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#[derive(Clone, Debug, Default, Eq, PartialEq)]
462pub struct EncoderInventory {
463 pub usable: Vec<NativeVideoEncoderCapability>,
465 pub refused: Vec<EncoderRefusal>,
467}
468
469#[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
501pub(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
530pub(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
544fn 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#[derive(Clone, Debug, Eq, PartialEq)]
566pub struct NativeHardwareDecodeCapability {
567 pub codec: NativeVideoCodec,
569 pub decoder_name: Option<String>,
571 pub hardware_config: bool,
575 pub software_decoder: Option<String>,
578}
579
580#[derive(Clone, Debug, Eq, PartialEq)]
582pub struct NativeHardwareDecodeCapabilities {
583 pub backend: &'static str,
585 pub codecs: Vec<NativeHardwareDecodeCapability>,
587}
588
589#[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#[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#[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#[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
700pub(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 && (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 candidates.sort_by_key(|candidate| !candidate.on_hardware);
728 candidates
729}
730
731pub(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
737const MISDECLARED_HARDWARE_ENCODERS: &[&str] = &["h264_videotoolbox"];
743
744pub(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
764fn registration_is_compatible(candidate: &VideoEncoderCandidate, name: &str) -> bool {
767 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
775pub(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
789pub(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
800fn encoder_runs_here(candidate: &VideoEncoderCandidate, name: &str) -> Result<(), EncoderRefusal> {
811 probe_outcome(candidate, name, true).unwrap_or(Ok(()))
812}
813
814#[derive(Clone, Debug, Eq, PartialEq)]
816pub(crate) enum ProbeVerdict {
817 Runs,
819 Absent(String),
821}
822
823pub(crate) type ProbeCache = Mutex<HashMap<(String, bool), ProbeVerdict>>;
825
826fn 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
845pub(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 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
898fn 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
916pub(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 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 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
971fn 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#[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#[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#[cfg(not(target_os = "linux"))]
1058const fn hardware_device_node(_name: &str) -> Option<bool> {
1059 None
1060}
1061
1062#[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#[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
1128fn 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
1141fn 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#[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
1167fn 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
1222pub(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
1276pub(crate) struct VideoEncoderOpenRequest<'a> {
1278 pub config: &'a VideoEncodeConfig,
1280 pub requested_name: Option<&'a str>,
1282 pub threads: SoftwareEncoderThreads<'a>,
1284 pub global_header: bool,
1286 pub width: i32,
1288 pub height: i32,
1290}
1291
1292pub(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 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 pub(crate) fn get(&self) -> i64 {
1314 self.get_fixed(None)
1315 }
1316
1317 pub(crate) fn get_fixed(&self, fixed: Option<usize>) -> i64 {
1319 *self.decided.get_or_init(|| (self.decide)(fixed).max(1))
1320 }
1321}
1322
1323pub(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 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
1354struct 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
1363pub(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
1465fn 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
1488fn 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 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
1554type OpenedContext = (
1556 EncoderContext,
1557 crate::AppliedRateControl,
1558 Option<String>,
1559 alpha2_media::PixelLayout,
1560);
1561
1562fn 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 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 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
1680pub(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
1692pub(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
1701pub(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 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 if name.ends_with("_videotoolbox") {
1753 0
1754 } else {
1755 2
1756 }
1757}
1758
1759#[must_use]
1761pub fn encoder_minimum_dimensions(name: &str) -> (u32, u32) {
1762 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#[derive(Clone, Debug, Eq, PartialEq)]
1789pub struct NativeEncoderHardwareConfig {
1790 pub pixel_format: String,
1792 pub device_type: String,
1794 pub methods: i32,
1796 pub needs_hardware_frames: bool,
1798}
1799
1800#[derive(Clone, Debug, Eq, PartialEq)]
1804#[allow(clippy::struct_excessive_bools)]
1806pub struct NativeVideoEncoderProbe {
1807 pub codec: NativeVideoCodec,
1809 pub encoder_name: String,
1811 pub class: NativeEncoderClass,
1813 pub hardware_accelerated: bool,
1815 pub capability_bits: u32,
1817 pub pixel_formats: Vec<String>,
1819 pub hardware_configs: Vec<NativeEncoderHardwareConfig>,
1821 pub accepts_yuv420p: bool,
1823 pub requires_hardware_frames: bool,
1825 pub advertised: bool,
1827 pub minimum_size: (u32, u32),
1829 pub software_open_error: Option<String>,
1831 pub software_packets: u32,
1833 pub rate_control: Vec<NativeRateControlProbe>,
1835}
1836
1837#[derive(Clone, Debug, Eq, PartialEq)]
1839pub struct NativeRateControlProbe {
1840 pub mechanism: crate::RateControlMechanism,
1842 pub options: Option<String>,
1844 pub outcome: Result<u32, String>,
1846 pub device: Option<String>,
1849}
1850
1851pub(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 NativeVideoCodec::ProRes => 0,
1866 }
1867}
1868
1869#[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 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#[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
2032fn 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}