ez_ffmpeg/core/mod.rs
1//! The **core** module provides the foundational building blocks for configuring and running FFmpeg
2//! pipelines. It encompasses:
3//!
4//! - **Input & Output Handling** (in [`context`]): Structures and logic (`Input`, `Output`) for
5//! specifying where media data originates and where it should be written.
6//! - **Filter Descriptions**: Define filter graphs with `FilterComplex` or attach custom [`FrameFilter`](filter::frame_filter::FrameFilter)
7//! implementations at the input/output stage.
8//! - **Stream and Device Queries** (in [`stream_info`] and [`device`]): Utilities for retrieving
9//! information about media streams and available input devices.
10//! - **Hardware Acceleration** (in [`hwaccel`]): Enumerate/configure GPU-accelerated codecs (CUDA, VAAPI, etc.).
11//! - **Codec Discovery** (in [`codec`]): List encoders/decoders supported by FFmpeg.
12//! - **Custom Filters** (in [`filter`]): Implement user-defined [`FrameFilter`](filter::frame_filter::FrameFilter) logic for frames.
13//! - **Lifecycle Orchestration** (in [`scheduler`]): [`FfmpegScheduler`](scheduler::ffmpeg_scheduler::FfmpegScheduler) that runs the configured pipeline
14//! (synchronously or asynchronously if the `async` feature is enabled).
15//!
16//! # Submodules
17//!
18//! - [`context`]: Houses [`FfmpegContext`](context::ffmpeg_context::FfmpegContext)—the central struct for assembling inputs, outputs, and filters.
19//! - [`scheduler`]: Defines [`FfmpegScheduler`](scheduler::ffmpeg_scheduler::FfmpegScheduler), managing the execution of an `FfmpegContext` pipeline.
20//! - [`container_info`]: Utilities to extract information about the container, such as duration and format details.
21//! - [`stream_info`]: Inspect media streams (e.g., find video/audio streams in a file).
22//! - [`device`]: Query audio/video input devices (cameras, microphones, etc.) on various platforms.
23//! - [`hwaccel`]: Helpers for hardware-accelerated encoding/decoding setup.
24//! - [`codec`]: Tools to discover which encoders/decoders your FFmpeg build supports.
25//! - [`filter`]: Query FFmpeg's built-in filters and infrastructure for building custom frame-processing filters.
26//!
27//! # Example Workflow
28//!
29//! 1. **Build a context** using [`FfmpegContext::builder()`](crate::core::context::ffmpeg_context::FfmpegContext::builder)
30//! specifying your input, any filters, and your output.
31//! 2. **Create a scheduler** with [`FfmpegScheduler::new`](crate::core::scheduler::ffmpeg_scheduler::FfmpegScheduler::new),
32//! then call `.start()` to begin processing.
33//! 3. **Wait** (or `.await` if `async` feature is enabled) for the job to complete. Use the returned
34//! `Result` to detect success or failure.
35//!
36//! # Example
37//! ```rust,ignore
38//!
39//! fn main() -> Result<(), Box<dyn std::error::Error>> {
40//! // 1. Build an FfmpegContext with an input, a simple filter, and an output
41//! let context = FfmpegContext::builder()
42//! .input("test.mp4")
43//! .filter_desc("hue=s=0") // Example: desaturate video
44//! .output("output.mp4")
45//! .build()?;
46//!
47//! // 2. Create a scheduler and start the job
48//! let scheduler = FfmpegScheduler::new(context).start()?;
49//!
50//! // 3. Block until it's finished
51//! scheduler.wait()?;
52//! Ok(())
53//! }
54//! ```
55
56/// The **context** module provides tools for assembling an entire FFmpeg pipeline,
57/// culminating in the [`FfmpegContext`](context::ffmpeg_context::FfmpegContext). This includes:
58///
59/// - **Inputs**: [`Input`](context::input::Input) objects representing files, URLs, or custom I/O callbacks.
60/// - **Outputs**: [`Output`](context::output::Output) objects representing target files, streams, or custom sinks.
61/// - **Filter Descriptions**: Simple inline filters via `filter_desc` or more complex
62/// [`FilterComplex`](context::filter_complex::FilterComplex) graphs.
63/// - **Builders**: e.g., [`FfmpegContextBuilder`](context::ffmpeg_context_builder::FfmpegContextBuilder) for constructing a complete context
64/// with multiple inputs, outputs, and filter settings.
65///
66/// Once you’ve built an [`FfmpegContext`](context::ffmpeg_context::FfmpegContext), you can execute it via the [`FfmpegScheduler`](scheduler::ffmpeg_scheduler::FfmpegScheduler).
67///
68/// # Example
69///
70/// ```rust,ignore
71/// // Build an FFmpeg context with one input, some filter settings, and one output.
72/// let context = FfmpegContext::builder()
73/// .input("test.mp4")
74/// .filter_desc("hue=s=0")
75/// .output("output.mp4")
76/// .build()
77/// .unwrap();
78/// // The context now holds all info needed for an FFmpeg job.
79/// ```
80pub mod context;
81
82/// Push raw video frames from Rust code into a full FFmpeg pipeline
83/// ([`VideoWriter`](writer::VideoWriter)).
84pub mod writer;
85
86/// Display matrix helpers shared by stream probing and filter graph setup.
87pub(crate) mod display;
88
89/// The **scheduler** module orchestrates the execution of a configured [`FfmpegContext`](context::ffmpeg_context::FfmpegContext).
90/// It provides the [`FfmpegScheduler`](scheduler::ffmpeg_scheduler::FfmpegScheduler) struct, which:
91///
92/// - **Starts** the FFmpeg pipeline via [`FfmpegScheduler::start()`](scheduler::ffmpeg_scheduler::FfmpegScheduler<crate::core::scheduler::ffmpeg_scheduler::Initialization>::start()).
93/// - **Manages** thread or subprocess creation, ensuring all streams and filters run.
94/// - **Waits** for completion (blocking or asynchronous, depending on whether the `async` feature is enabled).
95/// - **Returns** the final result, indicating success or failure.
96///
97/// # Synchronous Example
98///
99/// ```rust,ignore
100/// let context = FfmpegContext::builder()
101/// .input("test.mp4")
102/// .filter_desc("hue=s=0")
103/// .output("output.mp4")
104/// .build()
105/// .unwrap();
106///
107/// let result = FfmpegScheduler::new(context)
108/// .start()
109/// .unwrap()
110/// .wait();
111///
112/// assert!(result.is_ok(), "FFmpeg job failed unexpectedly");
113/// ```
114///
115/// # Asynchronous Example (requires `async` feature)
116///
117/// ```rust,ignore
118/// #[tokio::main]
119/// async fn main() {
120/// let context = FfmpegContext::builder()
121/// .input("test.mp4")
122/// .output("output.mp4")
123/// .build()
124/// .unwrap();
125///
126/// let mut scheduler = FfmpegScheduler::new(context)
127/// .start()
128/// .expect("Failed to start FFmpeg job");
129///
130/// // Asynchronous wait
131/// scheduler.await.expect("FFmpeg job failed unexpectedly");
132/// }
133/// ```
134pub mod scheduler;
135
136/// The **container_info** module provides utilities for retrieving metadata related to the media container,
137/// such as duration, format, and other general properties of the media file.
138///
139/// This module helps to query the overall properties of a media container file (e.g., `.mp4`, `.avi`, `.mkv`)
140/// without diving into individual streams (audio, video, etc.). It is useful when you need information
141/// about the file as a whole, such as total duration, format type, and container-specific properties.
142///
143/// # Examples
144///
145/// ```rust,ignore
146/// // Retrieve the duration in microseconds for the media file "test.mp4"
147/// let duration = get_duration_us("test.mp4").unwrap();
148/// println!("Duration: {} us", duration);
149///
150/// // Retrieve the format name for "test.mp4"
151/// let format = get_format("test.mp4").unwrap();
152/// println!("Format: {}", format);
153///
154/// // Retrieve the metadata for "test.mp4"
155/// let metadata = get_metadata("test.mp4").unwrap();
156/// for (key, value) in metadata {
157/// println!("{}: {}", key, value);
158/// }
159/// ```
160///
161/// These helper functions return the container-level metadata, and they handle any errors that may arise
162/// (e.g., if the file can't be opened or if there is an issue reading the data).
163pub mod container_info;
164
165/// The **stream_info** module provides utilities to retrieve detailed information
166/// about media streams (video, audio, and more) from an input source (e.g., a local file
167/// path, an RTMP URL, etc.). It queries FFmpeg for metadata regarding stream types, codec
168/// parameters, duration, and other relevant details.
169///
170/// # Examples
171///
172/// ```rust,ignore
173/// // Retrieve information about the first video stream in "test.mp4"
174/// let maybe_video_info = find_video_stream_info("test.mp4").unwrap();
175/// if let Some(video_info) = maybe_video_info {
176/// println!("Found video stream: {:?}", video_info);
177/// } else {
178/// println!("No video stream found.");
179/// }
180///
181/// // Retrieve information about the first audio stream in "test.mp4"
182/// let maybe_audio_info = find_audio_stream_info("test.mp4").unwrap();
183/// if let Some(audio_info) = maybe_audio_info {
184/// println!("Found audio stream: {:?}", audio_info);
185/// } else {
186/// println!("No audio stream found.");
187/// }
188///
189/// // Retrieve information about all streams (video, audio, etc.) in "test.mp4"
190/// let all_infos = find_all_stream_infos("test.mp4").unwrap();
191/// println!("Total streams found: {}", all_infos.len());
192/// for info in all_infos {
193/// println!("{:?}", info);
194/// }
195/// ```
196///
197/// These helper functions return `Result<Option<StreamInfo>, Error>` or `Result<Vec<StreamInfo>, Error>`
198/// depending on the call, allowing you to differentiate between "no stream found" (returns `Ok(None)`)
199/// and encountering an actual error (returns `Err(...)`).
200pub mod stream_info;
201
202/// The **packet_scanner** module provides a lightweight packet-level scanner for media files.
203///
204/// Unlike the full demuxing pipeline, `PacketScanner` iterates over raw demuxed packets
205/// without any decoding. This is useful for inspecting packet metadata such as timestamps,
206/// keyframe flags, sizes, and stream indices.
207///
208/// # Examples
209///
210/// ```rust,ignore
211/// use ez_ffmpeg::packet_scanner::PacketScanner;
212///
213/// let mut scanner = PacketScanner::open("test.mp4")?;
214/// for packet in scanner.packets() {
215/// let packet = packet?;
216/// println!(
217/// "stream={} pts={:?} size={} keyframe={}",
218/// packet.stream_index(),
219/// packet.pts(),
220/// packet.size(),
221/// packet.is_keyframe(),
222/// );
223/// }
224/// ```
225pub mod packet_scanner;
226
227/// The **device** module provides cross-platform methods to query available audio and video
228/// input devices on the system. Depending on the target operating system, it internally
229/// delegates to different platform APIs or FFmpeg’s device capabilities:
230///
231/// - **macOS**: Leverages AVFoundation for enumerating devices such as cameras ("vide")
232/// and microphones ("soun").
233/// - **Other OSes**: Uses FFmpeg’s `avdevice` to list input devices for video and audio.
234///
235/// These functions can be used to programmatically discover devices before choosing one
236/// for capture or recording in an FFmpeg-based pipeline.
237///
238/// # Examples
239///
240/// ```rust,ignore
241/// // Query video input devices (e.g., cameras)
242/// let video_devices = get_input_video_devices().unwrap();
243/// for device in &video_devices {
244/// println!("Available video device: {}", device);
245/// }
246///
247/// // Query audio input devices (e.g., microphones)
248/// let audio_devices = get_input_audio_devices().unwrap();
249/// for device in &audio_devices {
250/// println!("Available audio device: {}", device);
251/// }
252/// ```
253///
254/// # Notes
255///
256/// - If the query process fails (e.g., missing permissions or no devices available),
257/// the functions return an appropriate error from `crate::error`.
258/// - On macOS, the `AVFoundation` framework is used directly. On other platforms, FFmpeg’s
259/// `avdevice` functionality is used. Implementation details differ, but the returned
260/// results have a uniform format: a list of human-readable device names.
261/// - For more advanced device details (e.g., supported formats or resolutions), you may need
262/// to perform additional FFmpeg queries or platform-specific calls.
263pub mod device;
264/// The **hwaccel** module provides functionality for working with hardware-accelerated
265/// codecs in FFmpeg. It allows you to detect and configure various hardware devices
266/// (like NVENC, VAAPI, DXVA2, or VideoToolbox) so that FFmpeg can offload encoding or
267/// decoding tasks to GPU or specialized hardware.
268///
269/// # Public API
270///
271/// - [`get_hwaccels()`](hwaccel::get_hwaccels): Enumerates the hardware acceleration backends available on the
272/// current system, returning a list of [`HWAccelInfo`](hwaccel::HWAccelInfo) items. Each item contains a
273/// readable name (e.g., `"cuda"`, `"vaapi"`) and the corresponding `AVHWDeviceType`.
274///
275/// # Example
276///
277/// ```rust,ignore
278/// // Query hardware acceleration backends
279/// let hwaccels = get_hwaccels();
280/// for accel in hwaccels {
281/// println!("Found HW Accel: {} (type: {:?})", accel.name, accel.hw_device_type);
282/// }
283/// ```
284///
285/// # Notes
286///
287/// - While only [`get_hwaccels()`](hwaccel::get_hwaccels) is directly exposed, internally the module contains
288/// various helpers to initialize and manage hardware devices (e.g., `hw_device_init_from_string`).
289/// These are used behind the scenes or in more advanced scenarios where explicit control
290/// over device creation is required.
291/// - Hardware acceleration support depends on both FFmpeg’s compilation configuration
292/// and the underlying system drivers/frameworks. Not all listed accelerations may be
293/// fully functional on every platform.
294pub mod hwaccel;
295
296/// The **codec** module provides helpers for enumerating and querying FFmpeg’s
297/// available audio/video **encoders** and **decoders**. This can be useful for
298/// discovering which codecs are supported in your current FFmpeg build, along
299/// with their core attributes.
300///
301/// # Public API
302///
303/// - [`get_encoders()`](codec::get_encoders): Returns a list of [`CodecInfo`](codec::CodecInfo) representing all
304/// encoders (e.g., H.264, AAC) recognized by FFmpeg.
305/// - [`get_decoders()`](codec::get_decoders): Returns a list of [`CodecInfo`](codec::CodecInfo) representing all
306/// decoders (e.g., H.264, AAC) recognized by FFmpeg.
307///
308/// # Example
309///
310/// ```rust,ignore
311/// // List all available encoders
312/// let encoders = get_encoders();
313/// for enc in &encoders {
314/// println!("Encoder: {} - {}", enc.codec_name, enc.codec_long_name);
315/// }
316///
317/// // List all available decoders
318/// let decoders = get_decoders();
319/// for dec in &decoders {
320/// println!("Decoder: {} - {}", dec.codec_name, dec.codec_long_name);
321/// }
322/// ```
323///
324/// # Data Structures
325///
326/// - [`CodecInfo`](codec::CodecInfo): Contains user-friendly fields such as:
327/// - `codec_name` / `codec_long_name`
328/// - `desc_name`: The descriptor name from FFmpeg.
329/// - `media_type` (audio/video/subtitle, etc.)
330/// - `codec_id` (internal FFmpeg ID)
331/// - `codec_capabilities` (bitmask indicating codec features)
332///
333/// # Notes
334///
335/// - The underlying `Codec` struct is for internal usage only (`pub(crate)`,
336/// not part of the documented API), bridging to the raw FFmpeg APIs. In most
337/// cases, you only need the higher-level [`CodecInfo`](codec::CodecInfo)
338/// data from the public functions above.
339/// - The available encoders/decoders can vary depending on your FFmpeg build
340/// and any external libraries installed on the system.
341pub mod codec;
342
343/// The **capabilities** module provides lightweight probes for what the
344/// linked FFmpeg build contains — whether a muxer (output format) or an
345/// output-capable I/O protocol was compiled in. Use these before configuring
346/// outputs that depend on optional components (e.g. `whip`, `srt`) to fail
347/// fast with an actionable error instead of a mid-pipeline failure.
348///
349/// # Public API
350///
351/// - [`is_muxer_available()`](capabilities::is_muxer_available): Checks for a
352/// muxer by short name (e.g. `"matroska"`, `"mpegts"`, `"whip"`).
353/// - [`is_output_protocol_available()`](capabilities::is_output_protocol_available):
354/// Checks for an I/O protocol that supports writing (e.g. `"file"`, `"srt"`).
355///
356/// # Example
357///
358/// ```rust,ignore
359/// if !ez_ffmpeg::capabilities::is_muxer_available("whip") {
360/// eprintln!("this FFmpeg build lacks the whip muxer");
361/// }
362/// ```
363///
364/// # Notes
365///
366/// - A `true` result only means the component is registered in the linked
367/// FFmpeg build; encoders, TLS backends, endpoint compatibility, and
368/// network reachability are separate concerns.
369/// - Muxer names and protocol names are separate namespaces (the `srt`
370/// muxer is the SubRip subtitle format, not the SRT streaming protocol).
371pub mod capabilities;
372
373/// The **filter** module provides a flexible framework for custom frame processing
374/// within the FFmpeg pipeline, along with the ability to query FFmpeg's built-in filters.
375/// It introduces the [`FrameFilter`](filter::frame_filter::FrameFilter) trait, which defines how to apply transformations
376/// (e.g., scaling, color adjustments, GPU-accelerated effects) to decoded frames.
377/// You can attach these filters to either the input or the output side
378/// (depending on your desired pipeline design) so that frames are automatically
379/// processed in your FFmpeg workflow.
380///
381/// # FFmpeg Built-in Filters
382///
383/// ```rust,ignore
384/// use ez_ffmpeg::core::filter::get_filters;
385///
386/// // Query available FFmpeg filters
387/// let filters = get_filters();
388/// for filter in filters {
389/// println!("Filter: {} - {}", filter.name, filter.description);
390/// }
391/// ```
392///
393/// # Defining and Using a Custom Filter
394///
395/// Below is a minimal example showing how to implement a custom filter and attach it to
396/// an `Output` so that every frame is processed before encoding. You could likewise
397/// attach it to an `Input` if you want the frames processed immediately after decoding.
398///
399/// ```rust,ignore
400///
401/// // 1. Define your custom filter by implementing the FrameFilter trait.
402/// struct FlipFilter;
403///
404/// impl FrameFilter for FlipFilter {
405/// fn media_type(&self) -> AVMediaType {
406/// // This filter operates on video frames.
407/// AVMediaType::AVMEDIA_TYPE_VIDEO
408/// }
409///
410/// fn filter_frame(
411/// &mut self,
412/// mut frame: Frame,
413/// _ctx: &mut FrameFilterContext,
414/// ) -> Result<Option<Frame>, Box<dyn std::error::Error + Send + Sync>> {
415/// // Forward an end-of-stream flush marker straight through.
416/// if ez_ffmpeg::util::ffmpeg_utils::frame_is_eof_marker(&frame) {
417/// return Ok(Some(frame));
418/// }
419///
420/// // Here you would implement the logic to transform the frame.
421/// // As a trivial example, we just return the original frame.
422/// // (Replace this with your actual transformation code.)
423///
424/// Ok(Some(frame))
425/// }
426/// }
427///
428/// fn main() -> Result<(), Box<dyn std::error::Error>> {
429/// // 2. Create a pipeline builder for video frames.
430/// let mut pipeline_builder: FramePipelineBuilder = AVMediaType::AVMEDIA_TYPE_VIDEO.into();
431///
432/// // 3. Add your custom filter to the pipeline, giving it a unique name.
433/// pipeline_builder = pipeline_builder.filter("flip-filter", Box::new(FlipFilter));
434///
435/// // 4. Attach the pipeline to an Output (could also attach to an Input).
436/// let mut output: Output = "output.mp4".into();
437/// output.add_frame_pipeline(pipeline_builder);
438///
439/// // 5. Build the FFmpeg context with both input and output.
440/// let context = FfmpegContext::builder()
441/// .input("input.mp4")
442/// .output(output)
443/// .build()?;
444///
445/// // 6. Run the FFmpeg job via the scheduler.
446/// FfmpegScheduler::new(context)
447/// .start()?
448/// .wait()?;
449///
450/// Ok(())
451/// }
452/// ```
453///
454/// In this example:
455/// 1. We define a **`FlipFilter`** that implements the [`FrameFilter`](filter::frame_filter::FrameFilter) trait and specifies
456/// `AVMediaType::AVMEDIA_TYPE_VIDEO`.
457/// 2. We create a **`FramePipelineBuilder`** for `VIDEO` frames and add our filter to it.
458/// 3. We attach that pipeline to the **`Output`** configuration, so frames will be processed
459/// (in this case, “flipped”) before encoding.
460/// 4. Finally, we build the FFmpeg context and run it with the **`FfmpegScheduler`**.
461///
462/// # More Advanced Filters
463///
464/// For a more complex, GPU-accelerated example, see the wgpu-based filters in the
465/// `wgpu_filter` module (feature `"wgpu"`). There, you can use custom WGSL fragment
466/// shaders to apply sophisticated transformations or visual effects on video frames.
467/// (The former `opengl` module remains available but is deprecated.)
468///
469/// # Trait Overview
470///
471/// The [`FrameFilter`](filter::frame_filter::FrameFilter) trait exposes several methods you can override:
472/// - [`FrameFilter::media_type()`](filter::frame_filter::FrameFilter::media_type): Indicates which media type (video, audio, etc.) this filter handles.
473/// - [`FrameFilter::init()`](filter::frame_filter::FrameFilter::init): Called once when the filter is first created (e.g., allocate resources).
474/// - [`FrameFilter::filter_frame()`](filter::frame_filter::FrameFilter::filter_frame): The primary method for transforming an incoming frame.
475/// - [`FrameFilter::request_frame()`](filter::frame_filter::FrameFilter::request_frame): If your filter generates frames on its own, you can override this.
476/// - [`FrameFilter::uninit()`](filter::frame_filter::FrameFilter::uninit): Called during cleanup when the filter is removed or the pipeline ends.
477///
478/// By chaining multiple filters in a pipeline, you can create sophisticated processing
479/// chains for your media data.
480pub mod filter;
481
482/// The **metadata** module provides internal metadata handling for FFmpeg operations.
483///
484/// **Internal Use Only**: This module contains unsafe FFmpeg C API wrappers.
485/// Users should use the safe public API on `Output` instead:
486/// - `Output::add_metadata()` for global metadata
487/// - `Output::add_stream_metadata()` for stream metadata
488/// - `Output::map_metadata_from_input()` for metadata mapping
489/// - `Output::disable_auto_copy_metadata()` for controlling auto-copy
490///
491/// # Example
492/// ```rust,ignore
493/// let output = Output::from("output.mp4")
494/// .add_metadata("title", "My Video")
495/// .add_metadata("author", "John Doe")
496/// .add_stream_metadata("v:0", "language", "eng")?;
497/// ```
498pub(crate) mod metadata;
499
500/// The **analysis** module surfaces the results of FFmpeg detector/measurement
501/// filters (`blackdetect`, `silencedetect`, `scdet`, `cropdetect`, `ebur128`)
502/// as typed Rust events and a folded report, instead of only FFmpeg logs.
503pub mod analysis;
504
505/// The **recipes** module provides one-shot helpers for common workflows
506/// (thumbnails/sprite sheets, animated GIF export, HLS ABR ladders) built on
507/// top of the ez-ffmpeg builder. The raw `filter_desc` escape hatch remains
508/// available for anything these do not cover.
509pub mod recipes;
510
511pub mod frame_export;
512
513static INIT_FFMPEG: std::sync::Once = std::sync::Once::new();
514
515extern "C" fn cleanup() {
516 let _ = std::panic::catch_unwind(|| {
517 unsafe {
518 hwaccel::hw_device_free_all();
519 ffmpeg_sys_next::avformat_network_deinit();
520 }
521
522 log::debug!("FFmpeg cleaned up");
523 });
524}
525
526// C adjusts an array-typed `va_list` parameter to a pointer. Bindgen preserves
527// that adjustment in FFmpeg's function signatures, while its public `va_list`
528// alias remains the original one-element array. Extract the generated element
529// type so the callback follows the same ABI without naming bindgen internals.
530#[cfg(any(
531 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
532 target_arch = "s390x",
533 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
534))]
535trait VaListArray {
536 type Element;
537}
538
539#[cfg(any(
540 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
541 target_arch = "s390x",
542 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
543))]
544impl<T, const N: usize> VaListArray for [T; N] {
545 type Element = T;
546}
547
548#[cfg(any(
549 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
550 target_arch = "s390x",
551 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
552))]
553type VaListType = *mut <ffmpeg_sys_next::va_list as VaListArray>::Element;
554
555#[cfg(not(any(
556 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
557 target_arch = "s390x",
558 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
559)))]
560type VaListType = ffmpeg_sys_next::va_list;
561
562/// Log target used for every message forwarded from FFmpeg, so applications
563/// can tune FFmpeg's verbosity independently of ez-ffmpeg's own logs,
564/// e.g. `RUST_LOG=ez_ffmpeg=info,ez_ffmpeg::ffmpeg=warn`.
565pub const FFMPEG_LOG_TARGET: &str = "ez_ffmpeg::ffmpeg";
566
567/// Highest FFmpeg log level forwarded to the Rust `log` facade.
568/// Defaults to [`FfmpegLogLevel::Info`], matching the historical behavior.
569static FFMPEG_LOG_MAX_LEVEL: std::sync::atomic::AtomicI32 =
570 std::sync::atomic::AtomicI32::new(ffmpeg_sys_next::AV_LOG_INFO);
571
572/// Verbosity levels of the FFmpeg logging system (mirrors `AV_LOG_*`).
573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
574#[non_exhaustive]
575pub enum FfmpegLogLevel {
576 Quiet,
577 Panic,
578 Fatal,
579 Error,
580 Warning,
581 Info,
582 Verbose,
583 Debug,
584 Trace,
585}
586
587impl FfmpegLogLevel {
588 fn to_av_level(self) -> libc::c_int {
589 match self {
590 FfmpegLogLevel::Quiet => ffmpeg_sys_next::AV_LOG_QUIET,
591 FfmpegLogLevel::Panic => ffmpeg_sys_next::AV_LOG_PANIC,
592 FfmpegLogLevel::Fatal => ffmpeg_sys_next::AV_LOG_FATAL,
593 FfmpegLogLevel::Error => ffmpeg_sys_next::AV_LOG_ERROR,
594 FfmpegLogLevel::Warning => ffmpeg_sys_next::AV_LOG_WARNING,
595 FfmpegLogLevel::Info => ffmpeg_sys_next::AV_LOG_INFO,
596 FfmpegLogLevel::Verbose => ffmpeg_sys_next::AV_LOG_VERBOSE,
597 FfmpegLogLevel::Debug => ffmpeg_sys_next::AV_LOG_DEBUG,
598 FfmpegLogLevel::Trace => ffmpeg_sys_next::AV_LOG_TRACE,
599 }
600 }
601}
602
603/// Sets the highest FFmpeg log level forwarded to the `log` facade
604/// (under the [`FFMPEG_LOG_TARGET`] target).
605///
606/// Messages above this level are dropped before any formatting work.
607/// Defaults to [`FfmpegLogLevel::Info`]; raise to [`FfmpegLogLevel::Trace`]
608/// to receive FFmpeg's debug/trace diagnostics (they map to `log::trace!`),
609/// or lower to [`FfmpegLogLevel::Error`] to keep only errors.
610pub fn set_ffmpeg_log_level(level: FfmpegLogLevel) {
611 FFMPEG_LOG_MAX_LEVEL.store(level.to_av_level(), std::sync::atomic::Ordering::Relaxed);
612}
613
614fn av_level_to_rust(level: libc::c_int) -> log::Level {
615 if level <= ffmpeg_sys_next::AV_LOG_ERROR {
616 log::Level::Error
617 } else if level <= ffmpeg_sys_next::AV_LOG_WARNING {
618 log::Level::Warn
619 } else if level <= ffmpeg_sys_next::AV_LOG_INFO {
620 log::Level::Info
621 } else if level <= ffmpeg_sys_next::AV_LOG_VERBOSE {
622 log::Level::Debug
623 } else {
624 log::Level::Trace
625 }
626}
627
628/// Shared formatting state for [`ffmpeg_log_callback`].
629///
630/// `print_prefix` must survive across invocations: FFmpeg emits partial log
631/// lines (not ending in '\n') and uses this flag to decide whether the next
632/// chunk starts a new prefixed line; a per-call flag broke multi-part
633/// messages. The same lock serializes `av_log_format_line` across threads
634/// and carries the duplicate-folding state (`AV_LOG_SKIP_REPEATED`
635/// semantics), mirroring FFmpeg's own default callback (libavutil/log.c).
636struct FfmpegLogState {
637 print_prefix: libc::c_int,
638 last_level: libc::c_int,
639 repeated: u64,
640 last_msg: String,
641}
642
643static FFMPEG_LOG_STATE: std::sync::Mutex<FfmpegLogState> = std::sync::Mutex::new(FfmpegLogState {
644 print_prefix: 1,
645 last_level: ffmpeg_sys_next::AV_LOG_INFO,
646 repeated: 0,
647 last_msg: String::new(),
648});
649
650unsafe extern "C" fn ffmpeg_log_callback(
651 ptr: *mut libc::c_void,
652 level: libc::c_int,
653 fmt: *const libc::c_char,
654 args: VaListType,
655) {
656 // Cheap early exits before any formatting: av_vlog does not filter by
657 // level for custom callbacks, so verbose/debug/trace chatter would
658 // otherwise be vsnprintf-formatted only to be thrown away.
659 if level > FFMPEG_LOG_MAX_LEVEL.load(std::sync::atomic::Ordering::Relaxed) {
660 return;
661 }
662 let rust_level = av_level_to_rust(level);
663 if rust_level > log::max_level() {
664 return;
665 }
666
667 // A panicked holder cannot exist (no panicking code below), but never
668 // propagate poisoning out of an extern "C" callback.
669 let mut state = FFMPEG_LOG_STATE
670 .lock()
671 .unwrap_or_else(|poisoned| poisoned.into_inner());
672
673 let mut buffer = [0u8; 1024];
674 ffmpeg_sys_next::av_log_format_line(
675 ptr,
676 level,
677 fmt,
678 args,
679 buffer.as_mut_ptr() as *mut libc::c_char,
680 buffer.len() as libc::c_int,
681 &mut state.print_prefix,
682 );
683
684 let Ok(msg) = std::ffi::CStr::from_ptr(buffer.as_ptr() as *const libc::c_char).to_str() else {
685 return;
686 };
687 let trimmed_msg = msg.trim_end_matches(['\n', '\r']);
688
689 // Fold consecutive duplicates, like ffmpeg CLI's AV_LOG_SKIP_REPEATED
690 // (e.g. per-frame h264 decode errors after a mid-GOP seek).
691 if level == state.last_level && trimmed_msg == state.last_msg {
692 state.repeated += 1;
693 return;
694 }
695 let flush_repeated = if state.repeated > 0 {
696 Some((av_level_to_rust(state.last_level), state.repeated))
697 } else {
698 None
699 };
700 state.repeated = 0;
701 state.last_level = level;
702 state.last_msg.clear();
703 state.last_msg.push_str(trimmed_msg);
704
705 // Emit outside the lock: a logger backend may itself call into FFmpeg
706 // (re-entering this callback and self-deadlocking the Mutex) or panic
707 // (which must not unwind while the state lock is held).
708 drop(state);
709
710 if let Some((repeated_level, repeated)) = flush_repeated {
711 log::log!(
712 target: FFMPEG_LOG_TARGET,
713 repeated_level,
714 "FFmpeg: last message repeated {} times",
715 repeated
716 );
717 }
718 log::log!(target: FFMPEG_LOG_TARGET, rust_level, "FFmpeg: {}", trimmed_msg);
719}
720
721fn initialize_ffmpeg() {
722 INIT_FFMPEG.call_once(|| {
723 unsafe {
724 libc::atexit(cleanup as extern "C" fn());
725 ffmpeg_sys_next::avdevice_register_all();
726 ffmpeg_sys_next::avformat_network_init();
727 ffmpeg_sys_next::av_log_set_callback(Some(ffmpeg_log_callback));
728 }
729 log::info!("FFmpeg initialized.");
730 });
731}