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