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