ff-encode 0.14.1

Video and audio encoding - the Rust way
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Export preset types and predefined presets.
//!
//! [`ExportPreset`] bundles a [`VideoEncoderConfig`] and an [`AudioEncoderConfig`]
//! into a named snapshot that can be applied to a [`VideoEncoderBuilder`] before
//! calling `.build()`.
//!
//! # Examples
//!
//! ```ignore
//! use ff_encode::{ExportPreset, VideoEncoder};
//!
//! let preset = ExportPreset::youtube_1080p();
//! preset.validate()?;
//!
//! let mut encoder = preset
//!     .apply_video(VideoEncoder::create("output.mp4"))
//!     .build()?;
//! ```

mod presets;
mod validation;

use ff_format::{PixelFormat, VideoCodec};

use crate::video::codec_options::VideoCodecOptions;
use crate::{AudioCodec, BitrateMode, EncodeError, VideoEncoderBuilder};

/// Configuration for the video stream of an export preset.
///
/// Fields with `Option` type are not applied to the builder when `None`,
/// allowing the builder's existing values (or defaults) to be preserved.
#[derive(Debug, Clone)]
pub struct VideoEncoderConfig {
    /// Video codec.
    pub codec: VideoCodec,
    /// Output width in pixels. `None` = preserve source width.
    pub width: Option<u32>,
    /// Output height in pixels. `None` = preserve source height.
    pub height: Option<u32>,
    /// Output frame rate. `None` = preserve source frame rate.
    pub fps: Option<f64>,
    /// Bitrate control mode.
    pub bitrate_mode: BitrateMode,
    /// Optional pixel format override. `None` lets the encoder choose.
    pub pixel_format: Option<PixelFormat>,
    /// Optional per-codec advanced options.
    pub codec_options: Option<VideoCodecOptions>,
}

/// Configuration for the audio stream of an export preset.
#[derive(Debug, Clone)]
pub struct AudioEncoderConfig {
    /// Audio codec.
    pub codec: AudioCodec,
    /// Sample rate in Hz (e.g. 48000).
    pub sample_rate: u32,
    /// Number of audio channels (1 = mono, 2 = stereo).
    pub channels: u32,
    /// Audio bitrate in bits per second (e.g. 192_000 = 192 kbps).
    pub bitrate: u64,
}

/// A named export preset combining video and audio encoder configuration.
///
/// Create a predefined preset with [`ExportPreset::youtube_1080p()`] etc., or
/// build a custom one as a struct literal. Call [`validate()`](Self::validate)
/// before encoding to catch platform-constraint violations early.
///
/// `video: None` indicates an audio-only preset (e.g. [`podcast_mono`](Self::podcast_mono)).
///
/// # Examples
///
/// ```ignore
/// use ff_encode::{ExportPreset, VideoEncoder};
///
/// let preset = ExportPreset::youtube_1080p();
/// preset.validate()?;
///
/// let mut encoder = preset
///     .apply_video(VideoEncoder::create("output.mp4"))
///     .build()?;
/// ```
#[derive(Debug, Clone)]
pub struct ExportPreset {
    /// Human-readable name (e.g. `"youtube_1080p"`).
    pub name: String,
    /// Video encoder configuration. `None` = audio-only preset.
    pub video: Option<VideoEncoderConfig>,
    /// Audio encoder configuration.
    pub audio: AudioEncoderConfig,
}

impl ExportPreset {
    // ── Predefined presets ────────────────────────────────────────────────────

    /// YouTube 1080p preset: H.264, CRF 18, 1920×1080, 30 fps, AAC 192 kbps.
    #[must_use]
    pub fn youtube_1080p() -> Self {
        presets::youtube_1080p()
    }

    /// YouTube 4K preset: H.265, CRF 20, 3840×2160, 30 fps, AAC 256 kbps.
    #[must_use]
    pub fn youtube_4k() -> Self {
        presets::youtube_4k()
    }

    /// Twitter/X preset: H.264, CRF 23, 1280×720, 30 fps, AAC 128 kbps.
    #[must_use]
    pub fn twitter() -> Self {
        presets::twitter()
    }

    /// Instagram Square preset: H.264, CRF 23, 1080×1080, 30 fps, AAC 128 kbps.
    #[must_use]
    pub fn instagram_square() -> Self {
        presets::instagram_square()
    }

    /// Instagram Reels preset: H.264, CRF 23, 1080×1920, 30 fps, AAC 128 kbps.
    #[must_use]
    pub fn instagram_reels() -> Self {
        presets::instagram_reels()
    }

    /// Blu-ray 1080p preset: H.264, CRF 18, 1920×1080, 24 fps, AC-3 384 kbps.
    #[must_use]
    pub fn bluray_1080p() -> Self {
        presets::bluray_1080p()
    }

    /// Podcast mono preset (audio-only): AAC 128 kbps, mono, 48 kHz.
    #[must_use]
    pub fn podcast_mono() -> Self {
        presets::podcast_mono()
    }

    /// Lossless archive preset: FFV1 video (source resolution), FLAC audio.
    #[must_use]
    pub fn lossless_rgb() -> Self {
        presets::lossless_rgb()
    }

    /// Web H.264 preset (VP9): VP9, CRF 33, 1280×720, 30 fps, Opus 128 kbps.
    #[must_use]
    pub fn web_h264() -> Self {
        presets::web_h264()
    }

    // ── Validation ────────────────────────────────────────────────────────────

    /// Validates this preset against platform-specific constraints.
    ///
    /// Call this before passing the preset to [`apply_video`](Self::apply_video)
    /// or [`apply_audio`](Self::apply_audio) to surface constraint violations
    /// before encoding begins.
    ///
    /// # Errors
    ///
    /// Returns [`EncodeError::PresetConstraintViolation`] when a platform rule
    /// is violated (e.g. fps > 60 on a YouTube preset, or wrong aspect ratio
    /// on an Instagram preset).
    pub fn validate(&self) -> Result<(), EncodeError> {
        validation::validate_preset(self)
    }

    // ── Builder helpers ───────────────────────────────────────────────────────

    /// Applies the video configuration to a [`VideoEncoderBuilder`].
    ///
    /// Sets the codec and bitrate mode unconditionally. Resolution and frame
    /// rate are only applied when all three (`width`, `height`, `fps`) are
    /// `Some`. Pixel format and per-codec options are applied when present.
    ///
    /// Returns `builder` unchanged when [`video`](Self::video) is `None`
    /// (audio-only preset).
    #[must_use]
    pub fn apply_video(&self, builder: VideoEncoderBuilder) -> VideoEncoderBuilder {
        let Some(ref v) = self.video else {
            return builder;
        };
        let mut b = builder
            .video_codec(v.codec)
            .bitrate_mode(v.bitrate_mode.clone());
        if let (Some(w), Some(h), Some(fps)) = (v.width, v.height, v.fps) {
            b = b.video(w, h, fps);
        }
        if let Some(pf) = v.pixel_format {
            b = b.pixel_format(pf);
        }
        if let Some(opts) = v.codec_options.clone() {
            b = b.codec_options(opts);
        }
        b
    }

    /// Applies the audio configuration to a [`VideoEncoderBuilder`].
    ///
    /// Sets sample rate, channel count, codec, and bitrate.
    #[must_use]
    pub fn apply_audio(&self, builder: VideoEncoderBuilder) -> VideoEncoderBuilder {
        builder
            .audio(self.audio.sample_rate, self.audio.channels)
            .audio_codec(self.audio.codec)
            .audio_bitrate(self.audio.bitrate)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── youtube_1080p ─────────────────────────────────────────────────────────

    #[test]
    fn youtube_1080p_preset_should_have_correct_codec() {
        let preset = ExportPreset::youtube_1080p();
        let video = preset
            .video
            .as_ref()
            .expect("youtube_1080p must have video");
        assert_eq!(video.codec, VideoCodec::H264);
    }

    #[test]
    fn youtube_1080p_preset_should_have_correct_resolution() {
        let preset = ExportPreset::youtube_1080p();
        let video = preset
            .video
            .as_ref()
            .expect("youtube_1080p must have video");
        assert_eq!(video.width, Some(1920));
        assert_eq!(video.height, Some(1080));
    }

    #[test]
    fn youtube_1080p_preset_audio_should_be_aac_192kbps() {
        let preset = ExportPreset::youtube_1080p();
        assert_eq!(preset.audio.codec, AudioCodec::Aac);
        assert_eq!(preset.audio.bitrate, 192_000);
    }

    // ── youtube_4k ───────────────────────────────────────────────────────────

    #[test]
    fn youtube_4k_preset_should_have_h265_codec() {
        let preset = ExportPreset::youtube_4k();
        let video = preset.video.as_ref().expect("youtube_4k must have video");
        assert_eq!(video.codec, VideoCodec::H265);
    }

    #[test]
    fn youtube_4k_preset_should_have_correct_resolution() {
        let preset = ExportPreset::youtube_4k();
        let video = preset.video.as_ref().expect("youtube_4k must have video");
        assert_eq!(video.width, Some(3840));
        assert_eq!(video.height, Some(2160));
    }

    #[test]
    fn youtube_4k_preset_audio_should_be_aac_256kbps() {
        let preset = ExportPreset::youtube_4k();
        assert_eq!(preset.audio.codec, AudioCodec::Aac);
        assert_eq!(preset.audio.bitrate, 256_000);
    }

    // ── lossless_rgb ─────────────────────────────────────────────────────────

    #[test]
    fn lossless_rgb_preset_should_have_ffv1_codec() {
        let preset = ExportPreset::lossless_rgb();
        let video = preset.video.as_ref().expect("lossless_rgb must have video");
        assert_eq!(video.codec, VideoCodec::Ffv1);
    }

    #[test]
    fn lossless_rgb_preset_should_preserve_source_resolution() {
        let preset = ExportPreset::lossless_rgb();
        let video = preset.video.as_ref().expect("lossless_rgb must have video");
        assert!(video.width.is_none(), "lossless_rgb should not fix width");
        assert!(video.height.is_none(), "lossless_rgb should not fix height");
        assert!(video.fps.is_none(), "lossless_rgb should not fix fps");
    }

    // ── podcast_mono ─────────────────────────────────────────────────────────

    #[test]
    fn podcast_mono_preset_should_have_no_video() {
        let preset = ExportPreset::podcast_mono();
        assert!(
            preset.video.is_none(),
            "podcast_mono must be audio-only (video=None)"
        );
    }

    #[test]
    fn podcast_mono_preset_should_have_mono_audio() {
        let preset = ExportPreset::podcast_mono();
        assert_eq!(preset.audio.channels, 1);
    }

    // ── web_h264 ─────────────────────────────────────────────────────────────

    #[test]
    fn web_h264_preset_should_use_vp9_codec() {
        let preset = ExportPreset::web_h264();
        let video = preset.video.as_ref().expect("web_h264 must have video");
        assert_eq!(video.codec, VideoCodec::Vp9);
    }

    // ── human-readable names ──────────────────────────────────────────────────

    #[test]
    fn all_presets_should_have_non_empty_names() {
        let presets = [
            ExportPreset::youtube_1080p(),
            ExportPreset::youtube_4k(),
            ExportPreset::twitter(),
            ExportPreset::instagram_square(),
            ExportPreset::instagram_reels(),
            ExportPreset::bluray_1080p(),
            ExportPreset::podcast_mono(),
            ExportPreset::lossless_rgb(),
            ExportPreset::web_h264(),
        ];
        for preset in &presets {
            assert!(!preset.name.is_empty(), "preset name must not be empty");
        }
    }

    // ── apply_video / apply_audio ─────────────────────────────────────────────

    #[test]
    fn custom_preset_should_apply_codec_to_builder() {
        use crate::VideoEncoder;

        let preset = ExportPreset {
            name: "custom".to_string(),
            video: Some(VideoEncoderConfig {
                codec: VideoCodec::H264,
                width: Some(1280),
                height: Some(720),
                fps: Some(24.0),
                bitrate_mode: BitrateMode::Crf(23),
                pixel_format: None,
                codec_options: None,
            }),
            audio: AudioEncoderConfig {
                codec: AudioCodec::Aac,
                sample_rate: 44100,
                channels: 2,
                bitrate: 128_000,
            },
        };

        let builder = preset.apply_video(VideoEncoder::create("out.mp4"));
        assert_eq!(builder.video_codec, VideoCodec::H264);
        assert_eq!(builder.video_width, Some(1280));
        assert_eq!(builder.video_height, Some(720));
    }

    #[test]
    fn preset_with_no_resolution_should_not_override_builder_resolution() {
        use crate::VideoEncoder;

        let preset = ExportPreset {
            name: "no-res".to_string(),
            video: Some(VideoEncoderConfig {
                codec: VideoCodec::Ffv1,
                width: None,
                height: None,
                fps: None,
                bitrate_mode: BitrateMode::Crf(0),
                pixel_format: None,
                codec_options: None,
            }),
            audio: AudioEncoderConfig {
                codec: AudioCodec::Flac,
                sample_rate: 48000,
                channels: 2,
                bitrate: 0,
            },
        };

        // The builder starts with no video dimensions set.
        let builder = preset.apply_video(VideoEncoder::create("out.mkv"));
        assert!(
            builder.video_width.is_none(),
            "apply_video should not set width when VideoEncoderConfig.width is None"
        );
        assert!(
            builder.video_height.is_none(),
            "apply_video should not set height when VideoEncoderConfig.height is None"
        );
    }

    #[test]
    fn audio_only_preset_apply_video_should_return_builder_unchanged() {
        use crate::VideoEncoder;

        let preset = ExportPreset::podcast_mono();
        let builder_before = VideoEncoder::create("out.m4a");
        let builder_after = preset.apply_video(VideoEncoder::create("out.m4a"));
        // Both start from the same state; codec should still be default.
        assert_eq!(
            builder_before.video_codec, builder_after.video_codec,
            "apply_video on audio-only preset must leave builder unchanged"
        );
    }

    #[test]
    fn apply_audio_should_set_sample_rate_and_bitrate() {
        use crate::VideoEncoder;

        let preset = ExportPreset::youtube_1080p();
        let builder = preset.apply_audio(VideoEncoder::create("out.mp4"));
        assert_eq!(builder.audio_sample_rate, Some(48000));
        assert_eq!(builder.audio_bitrate, Some(192_000));
    }

    // ── validation ───────────────────────────────────────────────────────────

    #[test]
    fn youtube_1080p_preset_should_pass_validation() {
        assert!(ExportPreset::youtube_1080p().validate().is_ok());
    }

    #[test]
    fn youtube_4k_preset_should_pass_validation() {
        assert!(ExportPreset::youtube_4k().validate().is_ok());
    }

    #[test]
    fn instagram_square_preset_should_pass_validation() {
        assert!(ExportPreset::instagram_square().validate().is_ok());
    }

    #[test]
    fn instagram_reels_preset_should_pass_validation() {
        assert!(ExportPreset::instagram_reels().validate().is_ok());
    }
}