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