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//! - Frame pool types (`FramePool`, `PooledBuffer`, `SimpleFramePool`) are provided by `ff-common`
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 video;
107
108// Re-exports for convenience
109pub use audio::{AudioDecoder, AudioDecoderBuilder, AudioFrameIterator};
110pub use error::DecodeError;
111pub use ff_common::{FramePool, PooledBuffer, SimpleFramePool};
112pub use image::{ImageDecoder, ImageDecoderBuilder, ImageFrameIterator};
113pub use video::{VideoDecoder, VideoDecoderBuilder, VideoFrameIterator};
114
115/// Seek mode for positioning the decoder.
116///
117/// This enum determines how seeking is performed when navigating
118/// through a media file.
119///
120/// # Performance Considerations
121///
122/// - [`Keyframe`](Self::Keyframe) is fastest but may land slightly before or after the target
123/// - [`Exact`](Self::Exact) is slower but guarantees landing on the exact frame
124/// - [`Backward`](Self::Backward) is useful for editing workflows where the previous keyframe is needed
125///
126/// # Examples
127///
128/// ```
129/// use ff_decode::SeekMode;
130///
131/// // Default is Keyframe mode
132/// let mode = SeekMode::default();
133/// assert_eq!(mode, SeekMode::Keyframe);
134///
135/// // Use exact mode for frame-accurate positioning
136/// let exact = SeekMode::Exact;
137/// assert_eq!(format!("{:?}", exact), "Exact");
138/// ```
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
140#[repr(u8)]
141pub enum SeekMode {
142    /// Seek to nearest keyframe (fast, may have small offset).
143    ///
144    /// This mode seeks to the closest keyframe to the target position.
145    /// It's the fastest option but the actual position may differ from
146    /// the requested position by up to the GOP (Group of Pictures) size.
147    #[default]
148    Keyframe = 0,
149
150    /// Seek to exact frame (slower but precise).
151    ///
152    /// This mode first seeks to the previous keyframe, then decodes
153    /// frames until reaching the exact target position. This guarantees
154    /// frame-accurate positioning but is slower, especially for long GOPs.
155    Exact = 1,
156
157    /// Seek to keyframe at or before the target position.
158    ///
159    /// Similar to [`Keyframe`](Self::Keyframe), but guarantees the resulting
160    /// position is at or before the target. Useful for editing workflows
161    /// where you need to start decoding before a specific point.
162    Backward = 2,
163}
164
165/// Hardware acceleration configuration.
166///
167/// This enum specifies which hardware acceleration method to use for
168/// video decoding. Hardware acceleration can significantly improve
169/// decoding performance, especially for high-resolution content.
170///
171/// # Platform Support
172///
173/// | Mode | Platform | GPU Required |
174/// |------|----------|--------------|
175/// | [`Nvdec`](Self::Nvdec) | Windows/Linux | NVIDIA |
176/// | [`Qsv`](Self::Qsv) | Windows/Linux | Intel |
177/// | [`Amf`](Self::Amf) | Windows/Linux | AMD |
178/// | [`VideoToolbox`](Self::VideoToolbox) | macOS/iOS | Any |
179/// | [`Vaapi`](Self::Vaapi) | Linux | Various |
180///
181/// # Fallback Behavior
182///
183/// When [`Auto`](Self::Auto) is used, the decoder will try available
184/// accelerators in order of preference and fall back to software
185/// decoding if none are available.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
187pub enum HardwareAccel {
188    /// Automatically detect and use available hardware.
189    ///
190    /// The decoder will probe for available hardware accelerators
191    /// and use the best one available. Falls back to software decoding
192    /// if no hardware acceleration is available.
193    #[default]
194    Auto,
195
196    /// Disable hardware acceleration (CPU only).
197    ///
198    /// Forces software decoding using the CPU. This may be useful for
199    /// debugging, consistency, or when hardware acceleration causes issues.
200    None,
201
202    /// NVIDIA NVDEC.
203    ///
204    /// Uses NVIDIA's dedicated video decoding hardware. Supports most
205    /// common codecs including H.264, H.265, VP9, and AV1 (on newer GPUs).
206    /// Requires an NVIDIA GPU with NVDEC support.
207    Nvdec,
208
209    /// Intel Quick Sync Video.
210    ///
211    /// Uses Intel's integrated GPU video engine. Available on most
212    /// Intel CPUs with integrated graphics. Supports H.264, H.265,
213    /// VP9, and AV1 (on newer platforms).
214    Qsv,
215
216    /// AMD Advanced Media Framework.
217    ///
218    /// Uses AMD's dedicated video decoding hardware. Available on AMD
219    /// GPUs and APUs. Supports H.264, H.265, and VP9.
220    Amf,
221
222    /// Apple `VideoToolbox`.
223    ///
224    /// Uses Apple's hardware video decoding on macOS and iOS. Works with
225    /// both Intel and Apple Silicon Macs. Supports H.264, H.265, and `ProRes`.
226    VideoToolbox,
227
228    /// Video Acceleration API (Linux).
229    ///
230    /// A Linux-specific API that provides hardware-accelerated video
231    /// decoding across different GPU vendors. Widely supported on
232    /// Intel, AMD, and NVIDIA GPUs on Linux.
233    Vaapi,
234}
235
236impl HardwareAccel {
237    /// Returns `true` if this represents an enabled hardware accelerator.
238    ///
239    /// Returns `false` for [`None`](Self::None) and [`Auto`](Self::Auto).
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use ff_decode::HardwareAccel;
245    ///
246    /// assert!(!HardwareAccel::Auto.is_specific());
247    /// assert!(!HardwareAccel::None.is_specific());
248    /// assert!(HardwareAccel::Nvdec.is_specific());
249    /// assert!(HardwareAccel::Qsv.is_specific());
250    /// ```
251    #[must_use]
252    pub const fn is_specific(&self) -> bool {
253        !matches!(self, Self::Auto | Self::None)
254    }
255
256    /// Returns the name of the hardware accelerator.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use ff_decode::HardwareAccel;
262    ///
263    /// assert_eq!(HardwareAccel::Auto.name(), "auto");
264    /// assert_eq!(HardwareAccel::Nvdec.name(), "nvdec");
265    /// assert_eq!(HardwareAccel::VideoToolbox.name(), "videotoolbox");
266    /// ```
267    #[must_use]
268    pub const fn name(&self) -> &'static str {
269        match self {
270            Self::Auto => "auto",
271            Self::None => "none",
272            Self::Nvdec => "nvdec",
273            Self::Qsv => "qsv",
274            Self::Amf => "amf",
275            Self::VideoToolbox => "videotoolbox",
276            Self::Vaapi => "vaapi",
277        }
278    }
279}
280
281/// Prelude module for convenient imports.
282///
283/// This module re-exports all commonly used types:
284///
285/// ```ignore
286/// use ff_decode::prelude::*;
287/// ```
288pub mod prelude {
289    pub use crate::{
290        AudioDecoder, AudioDecoderBuilder, AudioFrameIterator, DecodeError, FramePool,
291        HardwareAccel, ImageDecoder, ImageDecoderBuilder, ImageFrameIterator, PooledBuffer,
292        SeekMode, SimpleFramePool, VideoDecoder, VideoDecoderBuilder, VideoFrameIterator,
293    };
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[test]
301    fn test_seek_mode_default() {
302        let mode = SeekMode::default();
303        assert_eq!(mode, SeekMode::Keyframe);
304    }
305
306    #[test]
307    fn test_hardware_accel_default() {
308        let accel = HardwareAccel::default();
309        assert_eq!(accel, HardwareAccel::Auto);
310    }
311
312    #[test]
313    fn test_hardware_accel_is_specific() {
314        assert!(!HardwareAccel::Auto.is_specific());
315        assert!(!HardwareAccel::None.is_specific());
316        assert!(HardwareAccel::Nvdec.is_specific());
317        assert!(HardwareAccel::Qsv.is_specific());
318        assert!(HardwareAccel::Amf.is_specific());
319        assert!(HardwareAccel::VideoToolbox.is_specific());
320        assert!(HardwareAccel::Vaapi.is_specific());
321    }
322
323    #[test]
324    fn test_hardware_accel_name() {
325        assert_eq!(HardwareAccel::Auto.name(), "auto");
326        assert_eq!(HardwareAccel::None.name(), "none");
327        assert_eq!(HardwareAccel::Nvdec.name(), "nvdec");
328        assert_eq!(HardwareAccel::Qsv.name(), "qsv");
329        assert_eq!(HardwareAccel::Amf.name(), "amf");
330        assert_eq!(HardwareAccel::VideoToolbox.name(), "videotoolbox");
331        assert_eq!(HardwareAccel::Vaapi.name(), "vaapi");
332    }
333
334    #[test]
335    fn test_seek_mode_variants() {
336        let modes = [SeekMode::Keyframe, SeekMode::Exact, SeekMode::Backward];
337        for mode in modes {
338            // Ensure all variants are accessible
339            let _ = format!("{mode:?}");
340        }
341    }
342
343    #[test]
344    fn test_hardware_accel_variants() {
345        let accels = [
346            HardwareAccel::Auto,
347            HardwareAccel::None,
348            HardwareAccel::Nvdec,
349            HardwareAccel::Qsv,
350            HardwareAccel::Amf,
351            HardwareAccel::VideoToolbox,
352            HardwareAccel::Vaapi,
353        ];
354        for accel in accels {
355            // Ensure all variants are accessible
356            let _ = format!("{accel:?}");
357        }
358    }
359
360    #[test]
361    fn test_decode_error_display() {
362        use std::path::PathBuf;
363
364        let error = DecodeError::FileNotFound {
365            path: PathBuf::from("/path/to/video.mp4"),
366        };
367        assert!(error.to_string().contains("File not found"));
368
369        let error = DecodeError::NoVideoStream {
370            path: PathBuf::from("/path/to/audio.mp3"),
371        };
372        assert!(error.to_string().contains("No video stream"));
373
374        let error = DecodeError::UnsupportedCodec {
375            codec: "unknown_codec".to_string(),
376        };
377        assert!(error.to_string().contains("Codec not supported"));
378
379        let error = DecodeError::EndOfStream;
380        assert_eq!(error.to_string(), "End of stream");
381    }
382
383    #[test]
384    fn test_prelude_imports() {
385        // Verify prelude exports all expected types
386        use crate::prelude::*;
387
388        let _mode: SeekMode = SeekMode::default();
389        let _accel: HardwareAccel = HardwareAccel::default();
390
391        // Video builder can be created
392        let _video_builder: VideoDecoderBuilder = VideoDecoder::open("test.mp4");
393
394        // Audio builder can be created
395        let _audio_builder: AudioDecoderBuilder = AudioDecoder::open("test.mp3");
396    }
397}