threers-codec 0.0.12

Pure-Rust media codecs: H.264/HEVC/VP9 encoders, H.264/HEVC/VP9/AV1 decoders, AAC/MP3/Opus/Vorbis/FLAC/WAV decoders, AAC-LC and MP3 encoders, MP4/WebM/Matroska/Ogg, GIF/APNG, captions, and VideoToolbox acceleration on macOS
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! High-level encoders for browser-friendly animated image/video containers.

use std::fmt;

#[cfg(feature = "gif")]
use crate::gif::{encode_gif, GifOptions, PaletteMode};
use crate::{
    apng::ApngEncoder,
    h264::{
        encode_compressed_mp4_from_iter as encode_h264_mp4_from_iter, encode_mp4_with_captions,
    },
    hevc::{encode_compressed_mp4, encode_compressed_mp4_from_iter, Yuv420Frame},
    webm::encode_webm,
};

/// Browser-friendly animation containers (no ffmpeg).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BrowserCodec {
    /// Animated GIF (feature `gif`): plays everywhere, 256 colours a frame.
    Gif,
    /// Animated PNG: full colour and alpha, larger files.
    Apng,
    /// VP9 in WebM, with alpha when the frames have any.
    Webm,
    /// H.264 in an MP4 container (`avc1` + `avcC`). Universally playable.
    ///
    /// Transform-coded intra, roughly a hundredth the size of the `I_PCM` path
    /// this used to take. [`Mp4Hevc`](Self::Mp4Hevc) is smaller again where its
    /// narrower playback reach is acceptable.
    Mp4,
    /// HEVC in an MP4 container (`hvc1` + `hvcC`), transform-coded.
    ///
    /// Two orders of magnitude smaller than [`Mp4`](Self::Mp4) — 0.16 MB against
    /// 47 MB on the 17-frame clip in `docs/codec-benchmark.md`. The cost is
    /// reach: HEVC in MP4 plays in Safari everywhere and in Chrome/Edge on
    /// hardware that supports it, but not universally the way H.264 does.
    Mp4Hevc,
}

impl BrowserCodec {
    /// The file extension for this codec's container.
    pub fn label(self) -> &'static str {
        match self {
            Self::Gif => "gif",
            Self::Apng => "apng",
            Self::Webm => "webm",
            Self::Mp4 | Self::Mp4Hevc => "mp4",
        }
    }
}

/// Progress phase for [`encode_animation_rgba_with_progress`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnimationExportPhase {
    /// Frames are being rendered or collected.
    Capture,
    /// Frames are being encoded.
    Encode,
    /// The file is complete.
    Done,
}

/// Progress tick for browser animation encoding.
#[derive(Clone, Debug)]
pub struct AnimationExportProgress {
    /// What is happening now.
    pub phase: AnimationExportPhase,
    /// Frames done in this phase.
    pub frame: u32,
    /// Frames in the whole animation.
    pub frames: u32,
    /// Overall progress from 0 to 1.
    pub ratio: f32,
    /// The codec being written.
    pub codec: BrowserCodec,
    /// A ready-to-display line, as [`format_animation_progress`] writes it.
    pub message: String,
}

/// Ready-to-display animation progress line.
pub fn format_animation_progress(info: &AnimationExportProgress) -> String {
    let pct = (info.ratio.clamp(0.0, 1.0) * 100.0).round() as i32;
    match info.phase {
        AnimationExportPhase::Capture => {
            format!("Rendering {}/{} ({pct}%)", info.frame, info.frames)
        }
        AnimationExportPhase::Encode => {
            format!(
                "Encoding {}… ({pct}%)",
                info.codec.label().to_ascii_uppercase()
            )
        }
        AnimationExportPhase::Done => format!("Done ({} frames)", info.frames),
    }
}

fn make_anim_progress(
    phase: AnimationExportPhase,
    frame: u32,
    frames: u32,
    ratio: f32,
    codec: BrowserCodec,
) -> AnimationExportProgress {
    let mut info = AnimationExportProgress {
        phase,
        frame,
        frames,
        ratio: ratio.clamp(0.0, 1.0),
        codec,
        message: String::new(),
    };
    info.message = format_animation_progress(&info);
    info
}

/// Errors produced while encoding a browser animation.
#[derive(Debug)]
pub enum AnimationEncodeError {
    /// No frames were given.
    Empty,
    /// A frame is not `width * height * 4` bytes.
    FrameSize {
        /// Index of the offending frame.
        frame: usize,
        /// The size every frame should be.
        expected: usize,
        /// The size this one is.
        got: usize,
    },
    /// A zero dimension or frame rate, or options the codec cannot represent.
    Dimension,
    /// Writing the output failed.
    Io(String),
    /// The codec asked for was not compiled in: its feature (named here) is off.
    FeatureDisabled(&'static str),
}

impl fmt::Display for AnimationEncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "animation needs at least one frame"),
            Self::FrameSize {
                frame,
                expected,
                got,
            } => write!(
                f,
                "frame {frame} has {got} bytes, expected {expected} (width*height*4)"
            ),
            Self::Dimension => write!(f, "invalid dimensions, frame rate, or codec options"),
            Self::Io(message) => write!(f, "animation encoding I/O failed: {message}"),
            Self::FeatureDisabled(feature) => {
                write!(
                    f,
                    "this build has no {feature} encoder (enable the `{feature}` feature)"
                )
            }
        }
    }
}

impl std::error::Error for AnimationEncodeError {}

/// Options for [`encode_animation_rgba`].
pub struct AnimationEncodeOptions {
    /// Frame width in pixels.
    pub width: u32,
    /// Frame height in pixels.
    pub height: u32,
    /// Frames per second.
    pub fps: u32,
    /// Container and codec to write.
    pub codec: BrowserCodec,
    /// Keep the alpha channel where the codec can carry it.
    pub transparent: bool,
    /// GIF palette size (`2..=256`; normally `256`).
    pub gif_colors: u16,
}

impl Default for AnimationEncodeOptions {
    fn default() -> Self {
        Self {
            width: 0,
            height: 0,
            fps: 30,
            codec: BrowserCodec::Gif,
            transparent: false,
            gif_colors: 256,
        }
    }
}

/// Encode tightly-packed RGBA8 frames into a browser-friendly animation.
pub fn encode_animation_rgba(
    opts: &AnimationEncodeOptions,
    frames: impl IntoIterator<Item = Vec<u8>>,
) -> Result<Vec<u8>, AnimationEncodeError> {
    encode_animation_rgba_with_progress(opts, frames, |_| {})
}

/// Like [`encode_animation_rgba`], with encode-phase progress callbacks.
pub fn encode_animation_rgba_with_progress<I, P>(
    opts: &AnimationEncodeOptions,
    frames: I,
    mut on_progress: P,
) -> Result<Vec<u8>, AnimationEncodeError>
where
    I: IntoIterator<Item = Vec<u8>>,
    P: FnMut(AnimationExportProgress),
{
    let pixels = opts
        .width
        .checked_mul(opts.height)
        .and_then(|n| n.checked_mul(4))
        .ok_or(AnimationEncodeError::Dimension)?;
    if opts.width == 0
        || opts.height == 0
        || opts.fps == 0
        || opts.fps > u16::MAX as u32
        || (matches!(opts.codec, BrowserCodec::Gif) && !(2..=256).contains(&opts.gif_colors))
    {
        return Err(AnimationEncodeError::Dimension);
    }
    if matches!(opts.codec, BrowserCodec::Gif)
        && (opts.width > u16::MAX as u32 || opts.height > u16::MAX as u32)
    {
        return Err(AnimationEncodeError::Dimension);
    }
    if matches!(opts.codec, BrowserCodec::Webm)
        && (!opts.width.is_multiple_of(8) || !opts.height.is_multiple_of(8))
    {
        return Err(AnimationEncodeError::Dimension);
    }
    if matches!(opts.codec, BrowserCodec::Mp4 | BrowserCodec::Mp4Hevc)
        && (!opts.width.is_multiple_of(2) || !opts.height.is_multiple_of(2))
    {
        return Err(AnimationEncodeError::Dimension);
    }

    let expected = pixels as usize;

    // The MP4 codecs can consume frames as they arrive. Everything else needs
    // them all at once (GIF quantizes a palette across the set, WebM and APNG
    // take slices), so only these two avoid the collect — which matters most
    // here, since an RGBA frame is 4 bytes per pixel: 133 MB each at 8K.
    if matches!(opts.codec, BrowserCodec::Mp4 | BrowserCodec::Mp4Hevc) && !opts.transparent {
        return encode_mp4_streaming(opts, frames, expected, on_progress);
    }

    let mut frames: Vec<Vec<u8>> = frames.into_iter().collect();
    if frames.is_empty() {
        return Err(AnimationEncodeError::Empty);
    }
    for (frame, rgba) in frames.iter().enumerate() {
        if rgba.len() != expected {
            return Err(AnimationEncodeError::FrameSize {
                frame,
                expected,
                got: rgba.len(),
            });
        }
    }

    let total = frames.len() as u32;
    on_progress(make_anim_progress(
        AnimationExportPhase::Encode,
        0,
        total,
        0.0,
        opts.codec,
    ));

    let delay_den = opts.fps as u16;
    let bytes = match opts.codec {
        #[cfg(not(feature = "gif"))]
        BrowserCodec::Gif => return Err(AnimationEncodeError::FeatureDisabled("gif")),
        #[cfg(feature = "gif")]
        BrowserCodec::Gif => {
            let gif_opts = GifOptions::default()
                .colors(opts.gif_colors)
                .transparency(opts.transparent)
                .dither(true)
                .diff_rects(true)
                .palette_mode(PaletteMode::Local);
            encode_gif(
                opts.width,
                opts.height,
                0,
                &gif_opts,
                frames.into_iter().map(|rgba| (rgba, 1, delay_den)),
            )
        }
        BrowserCodec::Apng => {
            let mut encoder = ApngEncoder::new(opts.width, opts.height, 0);
            let n = frames.len();
            for (i, mut rgba) in frames.into_iter().enumerate() {
                if !opts.transparent {
                    for pixel in rgba.as_chunks_mut::<4>().0 {
                        pixel[3] = 255;
                    }
                }
                encoder.add_frame(&rgba, 1, delay_den);
                let done = (i + 1) as u32;
                on_progress(make_anim_progress(
                    AnimationExportPhase::Encode,
                    done,
                    n as u32,
                    done as f32 / n as f32,
                    opts.codec,
                ));
            }
            encoder.finish()
        }
        BrowserCodec::Webm => {
            let yuv: Vec<Yuv420Frame> = frames
                .drain(..)
                .map(|rgba| {
                    let mut frame = Yuv420Frame::from_rgba(opts.width, opts.height, &rgba);
                    if !opts.transparent {
                        frame.alpha = None;
                    }
                    frame
                })
                .collect();
            let refs: Vec<&Yuv420Frame> = yuv.iter().collect();
            encode_webm(&refs, opts.fps)
        }
        BrowserCodec::Mp4 | BrowserCodec::Mp4Hevc => {
            if opts.transparent {
                return Err(AnimationEncodeError::Dimension);
            }
            let n = frames.len();
            let mut yuv = Vec::with_capacity(n);
            for rgba in frames.drain(..) {
                yuv.push(Yuv420Frame::from_rgba(opts.width, opts.height, &rgba));
                let done = yuv.len() as u32;
                on_progress(make_anim_progress(
                    AnimationExportPhase::Encode,
                    done,
                    n as u32,
                    done as f32 / n as f32,
                    opts.codec,
                ));
            }
            if matches!(opts.codec, BrowserCodec::Mp4Hevc) {
                // QP 26 is the middle of the usable range; see `encode_mp4`.
                encode_compressed_mp4(opts.width, opts.height, opts.fps, 26, &yuv)
            } else {
                encode_mp4_with_captions(opts.width, opts.height, opts.fps, &yuv, None)
            }
        }
    };

    on_progress(make_anim_progress(
        AnimationExportPhase::Done,
        total,
        total,
        1.0,
        opts.codec,
    ));
    Ok(bytes)
}

/// Encode the MP4 codecs without holding every source frame.
///
/// Frames are pulled from the iterator, converted, encoded and dropped one at a
/// time, so peak memory is one RGBA frame plus one YUV frame plus the encoded
/// samples — rather than every RGBA frame at once. Output is byte-identical to
/// the collecting path.
fn encode_mp4_streaming<I, P>(
    opts: &AnimationEncodeOptions,
    frames: I,
    expected: usize,
    mut on_progress: P,
) -> Result<Vec<u8>, AnimationEncodeError>
where
    I: IntoIterator<Item = Vec<u8>>,
    P: FnMut(AnimationExportProgress),
{
    let mut iter = frames.into_iter().peekable();
    if iter.peek().is_none() {
        return Err(AnimationEncodeError::Empty);
    }
    // Only used to report a ratio; an unsized iterator just reports against the
    // count so far, which still moves monotonically.
    let hint = iter.size_hint().1.unwrap_or(0) as u32;

    let mut err = None;
    let mut done = 0u32;
    let (w, h) = (opts.width, opts.height);
    let codec = opts.codec;
    let yuv = std::iter::from_fn(|| {
        if err.is_some() {
            return None;
        }
        let rgba = iter.next()?;
        if rgba.len() != expected {
            err = Some(AnimationEncodeError::FrameSize {
                frame: done as usize,
                expected,
                got: rgba.len(),
            });
            return None;
        }
        done += 1;
        on_progress(make_anim_progress(
            AnimationExportPhase::Encode,
            done,
            hint.max(done),
            done as f32 / hint.max(done) as f32,
            codec,
        ));
        Some(Yuv420Frame::from_rgba(w, h, &rgba))
    });

    let bytes = if matches!(codec, BrowserCodec::Mp4Hevc) {
        // QP 26 is the middle of the usable range; see `encode_mp4`.
        encode_compressed_mp4_from_iter(w, h, opts.fps, 26, None, yuv)
    } else {
        // QP 26 is the middle of the usable range, matching the HEVC path.
        encode_h264_mp4_from_iter(w, h, opts.fps, 26, None, yuv)
    };
    if let Some(e) = err {
        return Err(e);
    }

    on_progress(make_anim_progress(
        AnimationExportPhase::Done,
        done,
        done,
        1.0,
        codec,
    ));
    Ok(bytes)
}

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

    fn solid(r: u8, g: u8, b: u8, a: u8) -> Vec<u8> {
        let mut frame = vec![0; 8 * 8 * 4];
        for pixel in frame.as_chunks_mut::<4>().0 {
            pixel.copy_from_slice(&[r, g, b, a]);
        }
        frame
    }

    #[test]
    fn encodes_browser_animation_headers() {
        for (codec, header) in [
            (BrowserCodec::Gif, b"GIF8".as_slice()),
            (BrowserCodec::Apng, &[0x89, b'P', b'N', b'G']),
            (BrowserCodec::Webm, &[0x1a, 0x45, 0xdf, 0xa3]),
            (BrowserCodec::Mp4, b"ftyp".as_slice()),
        ] {
            let transparent = !matches!(codec, BrowserCodec::Mp4);
            let options = AnimationEncodeOptions {
                width: 8,
                height: 8,
                fps: 10,
                codec,
                transparent,
                gif_colors: 256,
            };
            let result =
                encode_animation_rgba(&options, [solid(255, 0, 0, 255), solid(0, 0, 255, 128)]);
            // Without the `gif` feature GIF is an error naming it, not a panic.
            if cfg!(not(feature = "gif")) && matches!(codec, BrowserCodec::Gif) {
                assert!(matches!(
                    result,
                    Err(AnimationEncodeError::FeatureDisabled("gif"))
                ));
                continue;
            }
            let bytes = result.unwrap();
            assert!(bytes.len() > header.len());
            if matches!(codec, BrowserCodec::Mp4) {
                assert_eq!(&bytes[4..8], header);
            } else {
                assert_eq!(&bytes[..header.len()], header);
            }
        }
    }
}