Skip to main content

ff_decode/
lib.rs

1//! # ff-decode
2//!
3//! Video and audio decoding - the Rust way.
4//!
5//! This crate provides frame-by-frame video/audio decoding, efficient seeking,
6//! and thumbnail generation. It completely hides `FFmpeg` internals and provides
7//! a safe, ergonomic Rust API.
8//!
9//! ## Features
10//!
11//! - **Video Decoding**: Frame-by-frame decoding with Iterator pattern
12//! - **Audio Decoding**: Sample-level audio extraction
13//! - **Seeking**: Fast keyframe and exact seeking without file re-open
14//! - **Thumbnails**: Efficient thumbnail generation for timelines
15//! - **Hardware Acceleration**: Optional NVDEC, QSV, AMF, `VideoToolbox`, VAAPI support
16//! - **Frame Pooling**: Memory reuse for reduced allocation overhead
17//!
18//! ## Usage
19//!
20//! ### Video Decoding
21//!
22//! ```ignore
23//! use ff_decode::{VideoDecoder, SeekMode};
24//! use ff_format::PixelFormat;
25//! use std::time::Duration;
26//!
27//! // Open a video file and create decoder
28//! let mut decoder = VideoDecoder::open("video.mp4")?
29//!     .output_format(PixelFormat::Rgba)
30//!     .build()?;
31//!
32//! // Get basic info
33//! println!("Duration: {:?}", decoder.duration());
34//! println!("Resolution: {}x{}", decoder.width(), decoder.height());
35//!
36//! // Decode frames sequentially
37//! for frame in decoder.frames().take(100) {
38//!     let frame = frame?;
39//!     println!("Frame at {:?}", frame.timestamp().as_duration());
40//! }
41//!
42//! // Seek to specific position
43//! decoder.seek(Duration::from_secs(30), SeekMode::Keyframe)?;
44//! ```
45//!
46//! ### Audio Decoding
47//!
48//! ```ignore
49//! use ff_decode::AudioDecoder;
50//! use ff_format::SampleFormat;
51//!
52//! let mut decoder = AudioDecoder::open("audio.mp3")?
53//!     .output_format(SampleFormat::F32)
54//!     .output_sample_rate(48000)
55//!     .build()?;
56//!
57//! // Decode all audio samples
58//! for frame in decoder.frames().take(100) {
59//!     let frame = frame?;
60//!     println!("Audio frame with {} samples", frame.samples());
61//! }
62//! ```
63//!
64//! ### Hardware Acceleration (Video)
65//!
66//! ```ignore
67//! use ff_decode::{VideoDecoder, HardwareAccel};
68//!
69//! let decoder = VideoDecoder::open("video.mp4")?
70//!     .hardware_accel(HardwareAccel::Auto)  // Auto-detect GPU
71//!     .build()?;
72//! ```
73//!
74//! ### Frame Pooling (Video)
75//!
76//! ```ignore
77//! use ff_decode::{VideoDecoder, FramePool};
78//! use std::sync::Arc;
79//!
80//! // Use a frame pool for memory reuse
81//! let pool: Arc<dyn FramePool> = create_frame_pool(32);
82//! let decoder = VideoDecoder::open("video.mp4")?
83//!     .frame_pool(pool)
84//!     .build()?;
85//! ```
86//!
87//! ## Module Structure
88//!
89//! - [`audio`] - Audio decoder for extracting audio frames
90//! - [`video`] - Video decoder for extracting video frames
91//! - [`error`] - Error types for decoding operations
92//! - [`pool`] - Frame pool trait for memory reuse
93//!
94//! ## Re-exports
95//!
96//! This crate re-exports commonly used types from `ff-format` for convenience.
97
98#![warn(missing_docs)]
99#![warn(clippy::all)]
100#![warn(clippy::pedantic)]
101
102// Module declarations
103pub mod audio;
104pub mod error;
105pub mod image;
106pub mod pool;
107pub mod video;
108
109// Re-exports for convenience
110pub use audio::{AudioDecoder, AudioDecoderBuilder, AudioFrameIterator};
111pub use error::DecodeError;
112pub use image::{ImageDecoder, ImageDecoderBuilder, ImageFrameIterator};
113pub use pool::{FramePool, PooledBuffer, SimpleFramePool};
114pub use video::{VideoDecoder, VideoDecoderBuilder, VideoFrameIterator};
115
116/// Seek mode for positioning the decoder.
117///
118/// This enum determines how seeking is performed when navigating
119/// through a media file.
120///
121/// # Performance Considerations
122///
123/// - [`Keyframe`](Self::Keyframe) is fastest but may land slightly before or after the target
124/// - [`Exact`](Self::Exact) is slower but guarantees landing on the exact frame
125/// - [`Backward`](Self::Backward) is useful for editing workflows where the previous keyframe is needed
126///
127/// # Examples
128///
129/// ```
130/// use ff_decode::SeekMode;
131///
132/// // Default is Keyframe mode
133/// let mode = SeekMode::default();
134/// assert_eq!(mode, SeekMode::Keyframe);
135///
136/// // Use exact mode for frame-accurate positioning
137/// let exact = SeekMode::Exact;
138/// assert_eq!(format!("{:?}", exact), "Exact");
139/// ```
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
141#[repr(u8)]
142pub enum SeekMode {
143    /// Seek to nearest keyframe (fast, may have small offset).
144    ///
145    /// This mode seeks to the closest keyframe to the target position.
146    /// It's the fastest option but the actual position may differ from
147    /// the requested position by up to the GOP (Group of Pictures) size.
148    #[default]
149    Keyframe = 0,
150
151    /// Seek to exact frame (slower but precise).
152    ///
153    /// This mode first seeks to the previous keyframe, then decodes
154    /// frames until reaching the exact target position. This guarantees
155    /// frame-accurate positioning but is slower, especially for long GOPs.
156    Exact = 1,
157
158    /// Seek to keyframe at or before the target position.
159    ///
160    /// Similar to [`Keyframe`](Self::Keyframe), but guarantees the resulting
161    /// position is at or before the target. Useful for editing workflows
162    /// where you need to start decoding before a specific point.
163    Backward = 2,
164}
165
166/// Hardware acceleration configuration.
167///
168/// This enum specifies which hardware acceleration method to use for
169/// video decoding. Hardware acceleration can significantly improve
170/// decoding performance, especially for high-resolution content.
171///
172/// # Platform Support
173///
174/// | Mode | Platform | GPU Required |
175/// |------|----------|--------------|
176/// | [`Nvdec`](Self::Nvdec) | Windows/Linux | NVIDIA |
177/// | [`Qsv`](Self::Qsv) | Windows/Linux | Intel |
178/// | [`Amf`](Self::Amf) | Windows/Linux | AMD |
179/// | [`VideoToolbox`](Self::VideoToolbox) | macOS/iOS | Any |
180/// | [`Vaapi`](Self::Vaapi) | Linux | Various |
181///
182/// # Fallback Behavior
183///
184/// When [`Auto`](Self::Auto) is used, the decoder will try available
185/// accelerators in order of preference and fall back to software
186/// decoding if none are available.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
188pub enum HardwareAccel {
189    /// Automatically detect and use available hardware.
190    ///
191    /// The decoder will probe for available hardware accelerators
192    /// and use the best one available. Falls back to software decoding
193    /// if no hardware acceleration is available.
194    #[default]
195    Auto,
196
197    /// Disable hardware acceleration (CPU only).
198    ///
199    /// Forces software decoding using the CPU. This may be useful for
200    /// debugging, consistency, or when hardware acceleration causes issues.
201    None,
202
203    /// NVIDIA NVDEC.
204    ///
205    /// Uses NVIDIA's dedicated video decoding hardware. Supports most
206    /// common codecs including H.264, H.265, VP9, and AV1 (on newer GPUs).
207    /// Requires an NVIDIA GPU with NVDEC support.
208    Nvdec,
209
210    /// Intel Quick Sync Video.
211    ///
212    /// Uses Intel's integrated GPU video engine. Available on most
213    /// Intel CPUs with integrated graphics. Supports H.264, H.265,
214    /// VP9, and AV1 (on newer platforms).
215    Qsv,
216
217    /// AMD Advanced Media Framework.
218    ///
219    /// Uses AMD's dedicated video decoding hardware. Available on AMD
220    /// GPUs and APUs. Supports H.264, H.265, and VP9.
221    Amf,
222
223    /// Apple `VideoToolbox`.
224    ///
225    /// Uses Apple's hardware video decoding on macOS and iOS. Works with
226    /// both Intel and Apple Silicon Macs. Supports H.264, H.265, and `ProRes`.
227    VideoToolbox,
228
229    /// Video Acceleration API (Linux).
230    ///
231    /// A Linux-specific API that provides hardware-accelerated video
232    /// decoding across different GPU vendors. Widely supported on
233    /// Intel, AMD, and NVIDIA GPUs on Linux.
234    Vaapi,
235}
236
237impl HardwareAccel {
238    /// Returns `true` if this represents an enabled hardware accelerator.
239    ///
240    /// Returns `false` for [`None`](Self::None) and [`Auto`](Self::Auto).
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use ff_decode::HardwareAccel;
246    ///
247    /// assert!(!HardwareAccel::Auto.is_specific());
248    /// assert!(!HardwareAccel::None.is_specific());
249    /// assert!(HardwareAccel::Nvdec.is_specific());
250    /// assert!(HardwareAccel::Qsv.is_specific());
251    /// ```
252    #[must_use]
253    pub const fn is_specific(&self) -> bool {
254        !matches!(self, Self::Auto | Self::None)
255    }
256
257    /// Returns the name of the hardware accelerator.
258    ///
259    /// # Examples
260    ///
261    /// ```
262    /// use ff_decode::HardwareAccel;
263    ///
264    /// assert_eq!(HardwareAccel::Auto.name(), "auto");
265    /// assert_eq!(HardwareAccel::Nvdec.name(), "nvdec");
266    /// assert_eq!(HardwareAccel::VideoToolbox.name(), "videotoolbox");
267    /// ```
268    #[must_use]
269    pub const fn name(&self) -> &'static str {
270        match self {
271            Self::Auto => "auto",
272            Self::None => "none",
273            Self::Nvdec => "nvdec",
274            Self::Qsv => "qsv",
275            Self::Amf => "amf",
276            Self::VideoToolbox => "videotoolbox",
277            Self::Vaapi => "vaapi",
278        }
279    }
280}
281
282/// Prelude module for convenient imports.
283///
284/// This module re-exports all commonly used types:
285///
286/// ```ignore
287/// use ff_decode::prelude::*;
288/// ```
289pub mod prelude {
290    pub use crate::{
291        AudioDecoder, AudioDecoderBuilder, AudioFrameIterator, DecodeError, FramePool,
292        HardwareAccel, ImageDecoder, ImageDecoderBuilder, ImageFrameIterator, PooledBuffer,
293        SeekMode, SimpleFramePool, VideoDecoder, VideoDecoderBuilder, VideoFrameIterator,
294    };
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn test_seek_mode_default() {
303        let mode = SeekMode::default();
304        assert_eq!(mode, SeekMode::Keyframe);
305    }
306
307    #[test]
308    fn test_hardware_accel_default() {
309        let accel = HardwareAccel::default();
310        assert_eq!(accel, HardwareAccel::Auto);
311    }
312
313    #[test]
314    fn test_hardware_accel_is_specific() {
315        assert!(!HardwareAccel::Auto.is_specific());
316        assert!(!HardwareAccel::None.is_specific());
317        assert!(HardwareAccel::Nvdec.is_specific());
318        assert!(HardwareAccel::Qsv.is_specific());
319        assert!(HardwareAccel::Amf.is_specific());
320        assert!(HardwareAccel::VideoToolbox.is_specific());
321        assert!(HardwareAccel::Vaapi.is_specific());
322    }
323
324    #[test]
325    fn test_hardware_accel_name() {
326        assert_eq!(HardwareAccel::Auto.name(), "auto");
327        assert_eq!(HardwareAccel::None.name(), "none");
328        assert_eq!(HardwareAccel::Nvdec.name(), "nvdec");
329        assert_eq!(HardwareAccel::Qsv.name(), "qsv");
330        assert_eq!(HardwareAccel::Amf.name(), "amf");
331        assert_eq!(HardwareAccel::VideoToolbox.name(), "videotoolbox");
332        assert_eq!(HardwareAccel::Vaapi.name(), "vaapi");
333    }
334
335    #[test]
336    fn test_seek_mode_variants() {
337        let modes = [SeekMode::Keyframe, SeekMode::Exact, SeekMode::Backward];
338        for mode in modes {
339            // Ensure all variants are accessible
340            let _ = format!("{mode:?}");
341        }
342    }
343
344    #[test]
345    fn test_hardware_accel_variants() {
346        let accels = [
347            HardwareAccel::Auto,
348            HardwareAccel::None,
349            HardwareAccel::Nvdec,
350            HardwareAccel::Qsv,
351            HardwareAccel::Amf,
352            HardwareAccel::VideoToolbox,
353            HardwareAccel::Vaapi,
354        ];
355        for accel in accels {
356            // Ensure all variants are accessible
357            let _ = format!("{accel:?}");
358        }
359    }
360
361    #[test]
362    fn test_decode_error_display() {
363        use std::path::PathBuf;
364
365        let error = DecodeError::FileNotFound {
366            path: PathBuf::from("/path/to/video.mp4"),
367        };
368        assert!(error.to_string().contains("File not found"));
369
370        let error = DecodeError::NoVideoStream {
371            path: PathBuf::from("/path/to/audio.mp3"),
372        };
373        assert!(error.to_string().contains("No video stream"));
374
375        let error = DecodeError::UnsupportedCodec {
376            codec: "unknown_codec".to_string(),
377        };
378        assert!(error.to_string().contains("Codec not supported"));
379
380        let error = DecodeError::EndOfStream;
381        assert_eq!(error.to_string(), "End of stream");
382    }
383
384    #[test]
385    fn test_prelude_imports() {
386        // Verify prelude exports all expected types
387        use crate::prelude::*;
388
389        let _mode: SeekMode = SeekMode::default();
390        let _accel: HardwareAccel = HardwareAccel::default();
391
392        // Video builder can be created
393        let _video_builder: VideoDecoderBuilder = VideoDecoder::open("test.mp4");
394
395        // Audio builder can be created
396        let _audio_builder: AudioDecoderBuilder = AudioDecoder::open("test.mp3");
397    }
398}