Skip to main content

alpha2_native/
lib.rs

1//! Native `FFmpeg` 8 media adapter.
2//!
3//! rsmpeg and `FFmpeg` types stay private; callers see only `alpha2-media` contracts. Timeline
4//! audio mixing needs the `timeline` feature, the only part that links the engine.
5
6// Diagnostics go through `alpha2_os::diagnostic!` so a closed stderr cannot panic the process.
7#![cfg_attr(not(test), warn(clippy::print_stderr))]
8
9mod alpha;
10mod audio_encode;
11mod audio_input;
12pub use audio_input::AudioStreamConfig;
13mod bitstream;
14mod capabilities;
15mod convert;
16mod decode;
17mod recovery;
18pub use alpha2_host_core::recovery::{
19    ConcealedAudioGap, CorruptPacket, DECODE_WORK_LIMIT, DecodeDiagnostic, DecodeDiagnosticCounts,
20    DecodeDiagnostics, DecodePolicy, DecodeProgressWatch, DroppedAudioOverlap, VideoRecoveryGap,
21    watch_decode_progress,
22};
23mod encode;
24mod mux;
25mod partial;
26pub use alpha2_host_core::partial::{
27    ExistingOutput, OutputTarget, PARTIAL_OUTPUT_IN_USE, PublishReport,
28    remove_stale_partial_output, write_png, write_whole,
29};
30pub use alpha2_os::PublishMethod;
31mod passthrough;
32pub use passthrough::{
33    AudioBlockFeed, CopyAudio, PacketCopy, PacketCopyAudio, PacketCopyPlan, PacketCopyPlanner,
34    PacketCopyReport, PacketCopyRequest, check_yuv_transcode, copy_packets, plan_packet_copy,
35    same_chroma_siting,
36};
37#[cfg(all(target_os = "linux", feature = "hwdecode"))]
38mod hwdecode;
39#[cfg(feature = "hwencode")]
40mod hwencode;
41mod openh264;
42pub use openh264::{
43    OPENH264_ENCODER_NAME, OPENH264_INSTALL_COMMAND, OPENH264_NOTICE, OPENH264_VERSION,
44    OpenH264Library, OpenH264Provider, OpenH264Status, openh264_status,
45};
46mod rate_control;
47pub use alpha2_host_core::rate_control::{AppliedRateControl, RateControlMechanism};
48#[cfg(test)]
49mod tests;
50pub use alpha2_host_core::{
51    FrameScore, THUMBNAIL_LUMA_RANGE, choose_thumbnail, downscale_frame, resize_rgba, score_frame,
52};
53mod video_backend;
54mod video_encode;
55mod video_frame;
56mod vt_sei;
57pub use alpha2_ffmpeg_bridge::Yuv420pFrameBuffer;
58pub use alpha2_host_core::encode_watch::{EncodeCallWatch, watch_encode_calls};
59#[cfg(feature = "cpal-host")]
60pub use alpha2_host_core::{CpalHostError, CpalOutputHost, RealtimeAudioSource};
61pub use alpha2_host_core::{
62    DecodedAudioSources, HostAudioConfig, HostSampleFormat, OfflineAudioError,
63    negotiate_output_config, render_offline,
64};
65#[cfg(feature = "timeline")]
66pub use alpha2_host_core::{ProjectAudioRequest, render_project_audio};
67pub use alpha2_media::{EncoderRefusal, OpenFailureKind};
68pub use audio_encode::{
69    AudioFileCodec, AudioFileConfig, NativeAudioEncodeSink, NativeAudioFileSink,
70};
71pub use capabilities::{
72    AvEncodeConfig, EncoderInventory, NativeAudioCodec, NativeAudioEncoderCapability,
73    NativeCodecCapabilities, NativeEncoderClass, NativeEncoderHardwareConfig, NativeEncoderLibrary,
74    NativeEncoderRejection, NativeHardwareDecodeCapabilities, NativeHardwareDecodeCapability,
75    NativeRateControlProbe, NativeVideoCodec, NativeVideoEncoderCapability,
76    NativeVideoEncoderFallback, NativeVideoEncoderProbe, NativeVideoEncoderSelection,
77    audio_encoder_capabilities, codec_capabilities, encoder_minimum_dimensions, encodes_pixels,
78    h264_encoder_remedy, hardware_decode_backend, hardware_decode_capabilities,
79    hybrid_encoders_use_hardware, no_video_encoder_message, probe_video_encoders,
80    video_encoder_inventory, video_encoders_without_probing,
81};
82pub use convert::packed_frame;
83pub use convert::{
84    CodecThreadAllocation, CodecThreadRequest, HARDWARE_DECODER_THREADS, codec_thread_allocation,
85    codec_thread_budget, codec_thread_override, configured_codec_thread_override,
86    decode_concurrency_ceiling, decode_concurrency_ceiling_for,
87};
88pub use decode::{
89    DecodeStageTimings, DroppedLayer, NativeAudioDecoder, NativeDecoder, ProbeResult,
90    SOURCE_DECODERS, SOURCE_SAMPLE_RATES, allow_every_decoder, alpha_dropped_reason,
91    every_decoder_allowed, probe, software_decode_unsupported, source_decoders, visit_packet_times,
92};
93pub use encode::{EncodeStageTimings, NativeAvEncodeSink, NativeWavEncodeSink};
94#[cfg(all(target_os = "linux", feature = "hwdecode"))]
95pub use hwdecode::{VulkanDecodeProbe, probe_vulkan_decode};
96#[cfg(all(target_os = "windows", feature = "hwencode"))]
97pub use hwencode::{
98    D3D12EncodeProbe, D3D12RateControlOpen, D3D12RateControlRunner, D3D12TestEncodeRunner,
99    D3D12VA_TEST_ENCODE_SIZE, d3d12va_busy, d3d12va_encoder, d3d12va_timeouts,
100    open_d3d12va_rate_control, probe_d3d12va_encode, set_d3d12va_rate_control_runner,
101    set_d3d12va_test_encode_runner,
102};
103#[cfg(feature = "hwencode")]
104pub use hwencode::{
105    EncoderInputHandoff, EncoderInputLayout, EncoderPoolStats, EncoderSurface,
106    EncoderSurfaceDescriptor, HardwareEncodeBackend, HardwareEncodeCapability,
107    HardwareEncodeDevice, HardwareEncodeInput, HardwareEncodeOpenError, HardwareEncodeRequest,
108    HardwareEncodeSession, InputFrame,
109};
110#[cfg(all(target_os = "macos", feature = "hwencode"))]
111pub use hwencode::{VideoToolboxEncodeProbe, probe_videotoolbox_encode};
112#[cfg(all(target_os = "linux", feature = "hwencode"))]
113pub use hwencode::{VulkanEncodeProbe, probe_vulkan_encode};
114pub use video_encode::{NativeVideoEncodeSink, VideoDisplay, VideoEncodeConfig};
115pub use video_frame::{
116    HardwareDecodeFallback, HardwareFrameLease, HardwareOpenError, NativeExportDecoder,
117    NativePlaneLayout, NativeVideoFrame, NativeVideoFrameMetadata,
118};
119
120/// `FFmpeg` runtime and pinned SDK identity used by native diagnostics.
121#[derive(Clone, Debug, Eq, PartialEq)]
122pub struct FfmpegRuntimeIdentity {
123    /// Version reported by the loaded `FFmpeg` shared library.
124    pub version: String,
125    /// Configure flags reported by the loaded libavcodec.
126    pub configuration: String,
127    /// SDK release used by alpha2 release builds.
128    pub pinned_sdk_release: &'static str,
129    /// Why hardware decode and encode interop is off, set when the loaded libavutil is another
130    /// minor release than the one the `FFmpeg` shims were compiled for.
131    pub interop_refusal: Option<&'static str>,
132}
133
134impl FfmpegRuntimeIdentity {
135    /// Why the loaded runtime is not the pinned SDK, or `None` when it is.
136    ///
137    /// Cargo links whichever `FFmpeg` `pkg-config` finds, and a system build offers different
138    /// encoders than the release. Besides the version, the configuration must match the SDK's
139    /// `manifest.toml`: no GPL, nonfree or version 3 code, exactly the required external
140    /// `--enable-lib*` codecs, and `--disable-autodetect`.
141    #[must_use]
142    pub fn pinned_sdk_mismatch(&self) -> Option<String> {
143        let mut reasons = Vec::new();
144        if self.version != PINNED_SDK_SOURCE_TAG {
145            reasons.push(format!(
146                "version {} is not {PINNED_SDK_SOURCE_TAG}",
147                self.version
148            ));
149        }
150        let flags = || self.configuration.split_whitespace();
151        for flag in flags().filter(|flag| {
152            ["--enable-gpl", "--enable-nonfree", "--enable-version3"].contains(flag)
153                || (flag.starts_with("--enable-lib")
154                    && !PINNED_SDK_EXTERNAL_LIBRARIES.contains(flag))
155        }) {
156            reasons.push(format!("configured with {flag}"));
157        }
158        for library in PINNED_SDK_EXTERNAL_LIBRARIES {
159            if !flags().any(|flag| flag == *library) {
160                reasons.push(format!("not configured with {library}"));
161            }
162        }
163        if !flags().any(|flag| flag == "--disable-autodetect") {
164            reasons.push("not configured with --disable-autodetect".to_owned());
165        }
166        (!reasons.is_empty()).then(|| reasons.join(", "))
167    }
168}
169
170/// Panics unless the loaded `FFmpeg` is the pinned SDK, for tests to call before they use it.
171///
172/// A test linked against a system `FFmpeg` exercises different encoders than the release.
173/// `ALPHA2_ALLOW_UNPINNED_FFMPEG=1` runs them anyway. The runtime is checked once per process.
174///
175/// # Panics
176/// When the runtime is not the pinned SDK and the variable is not `1`.
177pub fn require_pinned_ffmpeg_for_tests() {
178    static MISMATCH: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
179    let mismatch = MISMATCH.get_or_init(|| {
180        let identity = ffmpeg_runtime_identity();
181        let reason = identity.pinned_sdk_mismatch()?;
182        if std::env::var_os("ALPHA2_ALLOW_UNPINNED_FFMPEG").is_some_and(|value| value == "1") {
183            alpha2_os::diagnostic!(
184                "alpha2: testing against FFmpeg {} although it is not the pinned SDK ({reason}): \
185                 ALPHA2_ALLOW_UNPINNED_FFMPEG=1",
186                identity.version
187            );
188            return None;
189        }
190        Some(format!(
191            "these tests loaded FFmpeg {}, not the pinned SDK {}: {reason}. The build \
192             linked whatever FFmpeg pkg-config found. Rebuild with \
193             FFMPEG_PKG_CONFIG_PATH=\"$(scripts/fetch-ffmpeg-sdk.sh)/lib/pkgconfig\" \
194             (on Windows, FFMPEG_INCLUDE_DIR and FFMPEG_LIBS_DIR). \
195             ALPHA2_ALLOW_UNPINNED_FFMPEG=1 runs them against this FFmpeg anyway.",
196            identity.version, identity.pinned_sdk_release,
197        ))
198    });
199    if let Some(message) = mismatch {
200        panic!("{message}");
201    }
202}
203
204/// `source_tag` of `release/ffmpeg-lgpl/manifest.toml`, as `av_version_info` reports it.
205const PINNED_SDK_SOURCE_TAG: &str = "n8.1.3";
206
207/// The `--enable-lib*` flags in `required_configure` of `release/ffmpeg-lgpl/manifest.toml`.
208const PINNED_SDK_EXTERNAL_LIBRARIES: &[&str] = &[
209    "--enable-libdav1d",
210    "--enable-libopus",
211    "--enable-libsvtav1",
212    "--enable-libvpx",
213];
214
215/// Returns the loaded `FFmpeg` identity together with the release SDK pin.
216#[must_use]
217pub fn ffmpeg_runtime_identity() -> FfmpegRuntimeIdentity {
218    FfmpegRuntimeIdentity {
219        version: alpha2_ffmpeg_bridge::runtime_version(),
220        configuration: alpha2_ffmpeg_bridge::runtime_configuration(),
221        pinned_sdk_release: "ffmpeg-8.1.3-shared-build5",
222        interop_refusal: alpha2_ffmpeg_bridge::hardware_interop_refusal(),
223    }
224}