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 **packet_sink** module delivers **encoded packets** to user callbacks
228/// instead of muxing them into container bytes — the packet-domain
229/// counterpart of the byte-domain `write_callback` output.
230///
231/// Build a [`PacketSink`](packet_sink::PacketSink) (or a
232/// [`PacketSink::channel`](packet_sink::PacketSink::channel) adapter) and hand
233/// it to [`Output::new_by_packet_sink`](crate::Output::new_by_packet_sink).
234/// The v1 strict tier is WebCodecs-aligned: avcC H.264 access units
235/// (libx264) and raw AAC frames with their AudioSpecificConfig. See the
236/// module documentation for the callback order and the blocking-backpressure
237/// contract.
238pub mod packet_sink;
239
240/// The **device** module provides cross-platform methods to query available audio and video
241/// input devices on the system. Depending on the target operating system, it internally
242/// delegates to different platform APIs or FFmpeg’s device capabilities:
243///
244/// - **macOS**: Leverages AVFoundation for enumerating devices such as cameras ("vide")
245/// and microphones ("soun").
246/// - **Other OSes**: Uses FFmpeg’s `avdevice` to list input devices for video and audio.
247///
248/// These functions can be used to programmatically discover devices before choosing one
249/// for capture or recording in an FFmpeg-based pipeline.
250///
251/// # Examples
252///
253/// ```rust,ignore
254/// // Query video input devices (e.g., cameras)
255/// let video_devices = get_input_video_devices().unwrap();
256/// for device in &video_devices {
257/// println!("Available video device: {}", device);
258/// }
259///
260/// // Query audio input devices (e.g., microphones)
261/// let audio_devices = get_input_audio_devices().unwrap();
262/// for device in &audio_devices {
263/// println!("Available audio device: {}", device);
264/// }
265/// ```
266///
267/// # Notes
268///
269/// - If the query process fails (e.g., missing permissions or no devices available),
270/// the functions return an appropriate error from `crate::error`.
271/// - On macOS, the `AVFoundation` framework is used directly. On other platforms, FFmpeg’s
272/// `avdevice` functionality is used. Implementation details differ, but the returned
273/// results have a uniform format: a list of human-readable device names.
274/// - For more advanced device details (e.g., supported formats or resolutions), you may need
275/// to perform additional FFmpeg queries or platform-specific calls.
276pub mod device;
277/// The **hwaccel** module provides functionality for working with hardware-accelerated
278/// codecs in FFmpeg. It allows you to detect and configure various hardware devices
279/// (like NVENC, VAAPI, DXVA2, or VideoToolbox) so that FFmpeg can offload encoding or
280/// decoding tasks to GPU or specialized hardware.
281///
282/// # Public API
283///
284/// - [`get_hwaccels()`](hwaccel::get_hwaccels): Enumerates the hardware acceleration backends available on the
285/// current system, returning a list of [`HWAccelInfo`](hwaccel::HWAccelInfo) items. Each item contains a
286/// readable name (e.g., `"cuda"`, `"vaapi"`) and the corresponding `AVHWDeviceType`.
287///
288/// # Example
289///
290/// ```rust,ignore
291/// // Query hardware acceleration backends
292/// let hwaccels = get_hwaccels();
293/// for accel in hwaccels {
294/// println!("Found HW Accel: {} (type: {:?})", accel.name, accel.hw_device_type);
295/// }
296/// ```
297///
298/// # Notes
299///
300/// - While only [`get_hwaccels()`](hwaccel::get_hwaccels) is directly exposed, internally the module contains
301/// various helpers to initialize and manage hardware devices (e.g., `hw_device_init_from_string`).
302/// These are used behind the scenes or in more advanced scenarios where explicit control
303/// over device creation is required.
304/// - Hardware acceleration support depends on both FFmpeg’s compilation configuration
305/// and the underlying system drivers/frameworks. Not all listed accelerations may be
306/// fully functional on every platform.
307pub mod hwaccel;
308
309/// The **codec** module provides helpers for enumerating and querying FFmpeg’s
310/// available audio/video **encoders** and **decoders**. This can be useful for
311/// discovering which codecs are supported in your current FFmpeg build, along
312/// with their core attributes.
313///
314/// # Public API
315///
316/// - [`get_encoders()`](codec::get_encoders): Returns a list of [`CodecInfo`](codec::CodecInfo) representing all
317/// encoders (e.g., H.264, AAC) recognized by FFmpeg.
318/// - [`get_decoders()`](codec::get_decoders): Returns a list of [`CodecInfo`](codec::CodecInfo) representing all
319/// decoders (e.g., H.264, AAC) recognized by FFmpeg.
320///
321/// # Example
322///
323/// ```rust,ignore
324/// // List all available encoders
325/// let encoders = get_encoders();
326/// for enc in &encoders {
327/// println!("Encoder: {} - {}", enc.codec_name, enc.codec_long_name);
328/// }
329///
330/// // List all available decoders
331/// let decoders = get_decoders();
332/// for dec in &decoders {
333/// println!("Decoder: {} - {}", dec.codec_name, dec.codec_long_name);
334/// }
335/// ```
336///
337/// # Data Structures
338///
339/// - [`CodecInfo`](codec::CodecInfo): Contains user-friendly fields such as:
340/// - `codec_name` / `codec_long_name`
341/// - `desc_name`: The descriptor name from FFmpeg.
342/// - `media_type` (audio/video/subtitle, etc.)
343/// - `codec_id` (internal FFmpeg ID)
344/// - `codec_capabilities` (bitmask indicating codec features)
345///
346/// # Notes
347///
348/// - The underlying `Codec` struct is for internal usage only (`pub(crate)`,
349/// not part of the documented API), bridging to the raw FFmpeg APIs. In most
350/// cases, you only need the higher-level [`CodecInfo`](codec::CodecInfo)
351/// data from the public functions above.
352/// - The available encoders/decoders can vary depending on your FFmpeg build
353/// and any external libraries installed on the system.
354pub mod codec;
355
356/// The **capabilities** module provides lightweight probes for what the
357/// linked FFmpeg build contains — whether a muxer (output format) or an
358/// output-capable I/O protocol was compiled in. Use these before configuring
359/// outputs that depend on optional components (e.g. `whip`, `srt`) to fail
360/// fast with an actionable error instead of a mid-pipeline failure.
361///
362/// # Public API
363///
364/// - [`is_muxer_available()`](capabilities::is_muxer_available): Checks for a
365/// muxer by short name (e.g. `"matroska"`, `"mpegts"`, `"whip"`).
366/// - [`is_output_protocol_available()`](capabilities::is_output_protocol_available):
367/// Checks for an I/O protocol that supports writing (e.g. `"file"`, `"srt"`).
368///
369/// # Example
370///
371/// ```rust,ignore
372/// if !ez_ffmpeg::capabilities::is_muxer_available("whip") {
373/// eprintln!("this FFmpeg build lacks the whip muxer");
374/// }
375/// ```
376///
377/// # Notes
378///
379/// - A `true` result only means the component is registered in the linked
380/// FFmpeg build; encoders, TLS backends, endpoint compatibility, and
381/// network reachability are separate concerns.
382/// - Muxer names and protocol names are separate namespaces (the `srt`
383/// muxer is the SubRip subtitle format, not the SRT streaming protocol).
384pub mod capabilities;
385
386/// The **filter** module provides a flexible framework for custom frame processing
387/// within the FFmpeg pipeline, along with the ability to query FFmpeg's built-in filters.
388/// It introduces the [`FrameFilter`](filter::frame_filter::FrameFilter) trait, which defines how to apply transformations
389/// (e.g., scaling, color adjustments, GPU-accelerated effects) to decoded frames.
390/// You can attach these filters to either the input or the output side
391/// (depending on your desired pipeline design) so that frames are automatically
392/// processed in your FFmpeg workflow.
393///
394/// # FFmpeg Built-in Filters
395///
396/// ```rust,ignore
397/// use ez_ffmpeg::core::filter::get_filters;
398///
399/// // Query available FFmpeg filters
400/// let filters = get_filters();
401/// for filter in filters {
402/// println!("Filter: {} - {}", filter.name, filter.description);
403/// }
404/// ```
405///
406/// # Defining and Using a Custom Filter
407///
408/// Below is a minimal example showing how to implement a custom filter and attach it to
409/// an `Output` so that every frame is processed before encoding. You could likewise
410/// attach it to an `Input` if you want the frames processed immediately after decoding.
411///
412/// ```rust,ignore
413///
414/// // 1. Define your custom filter by implementing the FrameFilter trait.
415/// struct FlipFilter;
416///
417/// impl FrameFilter for FlipFilter {
418/// fn media_type(&self) -> AVMediaType {
419/// // This filter operates on video frames.
420/// AVMediaType::AVMEDIA_TYPE_VIDEO
421/// }
422///
423/// fn filter_frame(
424/// &mut self,
425/// mut frame: Frame,
426/// _ctx: &mut FrameFilterContext,
427/// ) -> Result<Option<Frame>, Box<dyn std::error::Error + Send + Sync>> {
428/// // Forward an end-of-stream flush marker straight through.
429/// if ez_ffmpeg::util::ffmpeg_utils::frame_is_eof_marker(&frame) {
430/// return Ok(Some(frame));
431/// }
432///
433/// // Here you would implement the logic to transform the frame.
434/// // As a trivial example, we just return the original frame.
435/// // (Replace this with your actual transformation code.)
436///
437/// Ok(Some(frame))
438/// }
439/// }
440///
441/// fn main() -> Result<(), Box<dyn std::error::Error>> {
442/// // 2. Create a pipeline builder for video frames.
443/// let mut pipeline_builder: FramePipelineBuilder = AVMediaType::AVMEDIA_TYPE_VIDEO.into();
444///
445/// // 3. Add your custom filter to the pipeline, giving it a unique name.
446/// pipeline_builder = pipeline_builder.filter("flip-filter", Box::new(FlipFilter));
447///
448/// // 4. Attach the pipeline to an Output (could also attach to an Input).
449/// let mut output: Output = "output.mp4".into();
450/// output.add_frame_pipeline(pipeline_builder);
451///
452/// // 5. Build the FFmpeg context with both input and output.
453/// let context = FfmpegContext::builder()
454/// .input("input.mp4")
455/// .output(output)
456/// .build()?;
457///
458/// // 6. Run the FFmpeg job via the scheduler.
459/// FfmpegScheduler::new(context)
460/// .start()?
461/// .wait()?;
462///
463/// Ok(())
464/// }
465/// ```
466///
467/// In this example:
468/// 1. We define a **`FlipFilter`** that implements the [`FrameFilter`](filter::frame_filter::FrameFilter) trait and specifies
469/// `AVMediaType::AVMEDIA_TYPE_VIDEO`.
470/// 2. We create a **`FramePipelineBuilder`** for `VIDEO` frames and add our filter to it.
471/// 3. We attach that pipeline to the **`Output`** configuration, so frames will be processed
472/// (in this case, “flipped”) before encoding.
473/// 4. Finally, we build the FFmpeg context and run it with the **`FfmpegScheduler`**.
474///
475/// # More Advanced Filters
476///
477/// For a more complex, GPU-accelerated example, see the wgpu-based filters in the
478/// `wgpu_filter` module (feature `"wgpu"`). There, you can use custom WGSL fragment
479/// shaders to apply sophisticated transformations or visual effects on video frames.
480/// (The former `opengl` module remains available but is deprecated.)
481///
482/// # Trait Overview
483///
484/// The [`FrameFilter`](filter::frame_filter::FrameFilter) trait exposes several methods you can override:
485/// - [`FrameFilter::media_type()`](filter::frame_filter::FrameFilter::media_type): Indicates which media type (video, audio, etc.) this filter handles.
486/// - [`FrameFilter::init()`](filter::frame_filter::FrameFilter::init): Called once when the filter is first created (e.g., allocate resources).
487/// - [`FrameFilter::filter_frame()`](filter::frame_filter::FrameFilter::filter_frame): The primary method for transforming an incoming frame.
488/// - [`FrameFilter::request_frame()`](filter::frame_filter::FrameFilter::request_frame): If your filter generates frames on its own, you can override this.
489/// - [`FrameFilter::uninit()`](filter::frame_filter::FrameFilter::uninit): Called during cleanup when the filter is removed or the pipeline ends.
490///
491/// By chaining multiple filters in a pipeline, you can create sophisticated processing
492/// chains for your media data.
493pub mod filter;
494
495/// The **metadata** module provides internal metadata handling for FFmpeg operations.
496///
497/// **Internal Use Only**: This module contains unsafe FFmpeg C API wrappers.
498/// Users should use the safe public API on `Output` instead:
499/// - `Output::add_metadata()` for global metadata
500/// - `Output::add_stream_metadata()` for stream metadata
501/// - `Output::map_metadata_from_input()` for metadata mapping
502/// - `Output::disable_auto_copy_metadata()` for controlling auto-copy
503///
504/// # Example
505/// ```rust,ignore
506/// let output = Output::from("output.mp4")
507/// .add_metadata("title", "My Video")
508/// .add_metadata("author", "John Doe")
509/// .add_stream_metadata("v:0", "language", "eng")?;
510/// ```
511pub(crate) mod metadata;
512
513/// The **analysis** module surfaces the results of FFmpeg detector/measurement
514/// filters (`blackdetect`, `silencedetect`, `scdet`, `cropdetect`, `ebur128`)
515/// as typed Rust events and a folded report, instead of only FFmpeg logs.
516pub mod analysis;
517
518/// The **recipes** module provides one-shot helpers for common workflows
519/// (thumbnails/sprite sheets, animated GIF export, HLS ABR ladders) built on
520/// top of the ez-ffmpeg builder. The raw `filter_desc` escape hatch remains
521/// available for anything these do not cover.
522pub mod recipes;
523
524pub mod frame_export;
525
526#[cfg(feature = "cli")]
527pub mod cli;
528
529static INIT_FFMPEG: std::sync::Once = std::sync::Once::new();
530
531extern "C" fn cleanup() {
532 let _ = std::panic::catch_unwind(|| {
533 unsafe {
534 hwaccel::hw_device_free_all();
535 ffmpeg_sys_next::avformat_network_deinit();
536 }
537
538 log::debug!("FFmpeg cleaned up");
539 });
540}
541
542// C adjusts an array-typed `va_list` parameter to a pointer. Bindgen preserves
543// that adjustment in FFmpeg's function signatures, while its public `va_list`
544// alias remains the original one-element array. Extract the generated element
545// type so the callback follows the same ABI without naming bindgen internals.
546#[cfg(any(
547 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
548 target_arch = "s390x",
549 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
550))]
551trait VaListArray {
552 type Element;
553}
554
555#[cfg(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))]
560impl<T, const N: usize> VaListArray for [T; N] {
561 type Element = T;
562}
563
564#[cfg(any(
565 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
566 target_arch = "s390x",
567 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
568))]
569type VaListType = *mut <ffmpeg_sys_next::va_list as VaListArray>::Element;
570
571#[cfg(not(any(
572 all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)),
573 target_arch = "s390x",
574 all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)),
575)))]
576type VaListType = ffmpeg_sys_next::va_list;
577
578/// Log target used for every message forwarded from FFmpeg, so applications
579/// can tune FFmpeg's verbosity independently of ez-ffmpeg's own logs,
580/// e.g. `RUST_LOG=ez_ffmpeg=info,ez_ffmpeg::ffmpeg=warn`.
581pub const FFMPEG_LOG_TARGET: &str = "ez_ffmpeg::ffmpeg";
582
583/// Highest FFmpeg log level forwarded to the Rust `log` facade.
584/// Defaults to [`FfmpegLogLevel::Info`], matching the historical behavior.
585static FFMPEG_LOG_MAX_LEVEL: std::sync::atomic::AtomicI32 =
586 std::sync::atomic::AtomicI32::new(ffmpeg_sys_next::AV_LOG_INFO);
587
588/// Verbosity levels of the FFmpeg logging system (mirrors `AV_LOG_*`).
589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590#[non_exhaustive]
591pub enum FfmpegLogLevel {
592 Quiet,
593 Panic,
594 Fatal,
595 Error,
596 Warning,
597 Info,
598 Verbose,
599 Debug,
600 Trace,
601}
602
603impl FfmpegLogLevel {
604 fn to_av_level(self) -> libc::c_int {
605 match self {
606 FfmpegLogLevel::Quiet => ffmpeg_sys_next::AV_LOG_QUIET,
607 FfmpegLogLevel::Panic => ffmpeg_sys_next::AV_LOG_PANIC,
608 FfmpegLogLevel::Fatal => ffmpeg_sys_next::AV_LOG_FATAL,
609 FfmpegLogLevel::Error => ffmpeg_sys_next::AV_LOG_ERROR,
610 FfmpegLogLevel::Warning => ffmpeg_sys_next::AV_LOG_WARNING,
611 FfmpegLogLevel::Info => ffmpeg_sys_next::AV_LOG_INFO,
612 FfmpegLogLevel::Verbose => ffmpeg_sys_next::AV_LOG_VERBOSE,
613 FfmpegLogLevel::Debug => ffmpeg_sys_next::AV_LOG_DEBUG,
614 FfmpegLogLevel::Trace => ffmpeg_sys_next::AV_LOG_TRACE,
615 }
616 }
617}
618
619/// Sets the highest FFmpeg log level forwarded to the `log` facade
620/// (under the [`FFMPEG_LOG_TARGET`] target).
621///
622/// Messages above this level are dropped before any formatting work.
623/// Defaults to [`FfmpegLogLevel::Info`]; raise to [`FfmpegLogLevel::Trace`]
624/// to receive FFmpeg's debug/trace diagnostics (they map to `log::trace!`),
625/// or lower to [`FfmpegLogLevel::Error`] to keep only errors.
626pub fn set_ffmpeg_log_level(level: FfmpegLogLevel) {
627 FFMPEG_LOG_MAX_LEVEL.store(level.to_av_level(), std::sync::atomic::Ordering::Relaxed);
628}
629
630fn av_level_to_rust(level: libc::c_int) -> log::Level {
631 if level <= ffmpeg_sys_next::AV_LOG_ERROR {
632 log::Level::Error
633 } else if level <= ffmpeg_sys_next::AV_LOG_WARNING {
634 log::Level::Warn
635 } else if level <= ffmpeg_sys_next::AV_LOG_INFO {
636 log::Level::Info
637 } else if level <= ffmpeg_sys_next::AV_LOG_VERBOSE {
638 log::Level::Debug
639 } else {
640 log::Level::Trace
641 }
642}
643
644/// Shared formatting state for [`ffmpeg_log_callback`].
645///
646/// `print_prefix` must survive across invocations: FFmpeg emits partial log
647/// lines (not ending in '\n') and uses this flag to decide whether the next
648/// chunk starts a new prefixed line; a per-call flag broke multi-part
649/// messages. The same lock serializes `av_log_format_line` across threads
650/// and carries the duplicate-folding state (`AV_LOG_SKIP_REPEATED`
651/// semantics), mirroring FFmpeg's own default callback (libavutil/log.c).
652struct FfmpegLogState {
653 print_prefix: libc::c_int,
654 last_level: libc::c_int,
655 repeated: u64,
656 last_msg: String,
657}
658
659static FFMPEG_LOG_STATE: std::sync::Mutex<FfmpegLogState> = std::sync::Mutex::new(FfmpegLogState {
660 print_prefix: 1,
661 last_level: ffmpeg_sys_next::AV_LOG_INFO,
662 repeated: 0,
663 last_msg: String::new(),
664});
665
666unsafe extern "C" fn ffmpeg_log_callback(
667 ptr: *mut libc::c_void,
668 level: libc::c_int,
669 fmt: *const libc::c_char,
670 args: VaListType,
671) {
672 // Cheap early exits before any formatting: av_vlog does not filter by
673 // level for custom callbacks, so verbose/debug/trace chatter would
674 // otherwise be vsnprintf-formatted only to be thrown away.
675 if level > FFMPEG_LOG_MAX_LEVEL.load(std::sync::atomic::Ordering::Relaxed) {
676 return;
677 }
678 let rust_level = av_level_to_rust(level);
679 if rust_level > log::max_level() {
680 return;
681 }
682
683 // A panicked holder cannot exist (no panicking code below), but never
684 // propagate poisoning out of an extern "C" callback.
685 let mut state = FFMPEG_LOG_STATE
686 .lock()
687 .unwrap_or_else(|poisoned| poisoned.into_inner());
688
689 let mut buffer = [0u8; 1024];
690 ffmpeg_sys_next::av_log_format_line(
691 ptr,
692 level,
693 fmt,
694 args,
695 buffer.as_mut_ptr() as *mut libc::c_char,
696 buffer.len() as libc::c_int,
697 &mut state.print_prefix,
698 );
699
700 let Ok(msg) = std::ffi::CStr::from_ptr(buffer.as_ptr() as *const libc::c_char).to_str() else {
701 return;
702 };
703 let trimmed_msg = msg.trim_end_matches(['\n', '\r']);
704
705 // Fold consecutive duplicates, like ffmpeg CLI's AV_LOG_SKIP_REPEATED
706 // (e.g. per-frame h264 decode errors after a mid-GOP seek).
707 if level == state.last_level && trimmed_msg == state.last_msg {
708 state.repeated += 1;
709 return;
710 }
711 let flush_repeated = if state.repeated > 0 {
712 Some((av_level_to_rust(state.last_level), state.repeated))
713 } else {
714 None
715 };
716 state.repeated = 0;
717 state.last_level = level;
718 state.last_msg.clear();
719 state.last_msg.push_str(trimmed_msg);
720
721 // Emit outside the lock: a logger backend may itself call into FFmpeg
722 // (re-entering this callback and self-deadlocking the Mutex) or panic
723 // (which must not unwind while the state lock is held).
724 drop(state);
725
726 if let Some((repeated_level, repeated)) = flush_repeated {
727 log::log!(
728 target: FFMPEG_LOG_TARGET,
729 repeated_level,
730 "FFmpeg: last message repeated {} times",
731 repeated
732 );
733 }
734 log::log!(target: FFMPEG_LOG_TARGET, rust_level, "FFmpeg: {}", trimmed_msg);
735}
736
737fn initialize_ffmpeg() {
738 INIT_FFMPEG.call_once(|| {
739 unsafe {
740 libc::atexit(cleanup as extern "C" fn());
741 ffmpeg_sys_next::avdevice_register_all();
742 ffmpeg_sys_next::avformat_network_init();
743 ffmpeg_sys_next::av_log_set_callback(Some(ffmpeg_log_callback));
744 }
745 log::info!("FFmpeg initialized.");
746 });
747}