Skip to main content

rff_core/
media.rs

1//! Core media enumerations: media types, codec identifiers, and raw sample
2//! layouts (pixel formats for video, sample formats for audio).
3//!
4//! These deliberately cover only a small, growing subset of what FFmpeg
5//! supports. Add variants as new codecs land — every variant is `#[non_exhaustive]`
6//! friendly so downstream `match`es must keep a wildcard arm.
7
8use std::fmt;
9
10/// The broad category of an elementary stream.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum MediaType {
13    Video,
14    Audio,
15    Subtitle,
16    Data,
17    Attachment,
18}
19
20impl fmt::Display for MediaType {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        let s = match self {
23            MediaType::Video => "video",
24            MediaType::Audio => "audio",
25            MediaType::Subtitle => "subtitle",
26            MediaType::Data => "data",
27            MediaType::Attachment => "attachment",
28        };
29        f.write_str(s)
30    }
31}
32
33/// Identifier for a specific codec (the *what*, independent of any particular
34/// encoder/decoder *implementation*).
35///
36/// Marked `#[non_exhaustive]`: we add codecs over time, and external matchers
37/// must handle the open-ended set.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39#[non_exhaustive]
40pub enum CodecId {
41    /// Sentinel for "no/unknown codec".
42    #[default]
43    None,
44    /// H.264 / AVC video.
45    H264,
46    /// H.265 / HEVC video. Decode only.
47    Hevc,
48    /// Opus audio.
49    Opus,
50    /// AVIF still image (an AV1 intra frame in a HEIF box).
51    Avif,
52    /// PNG still image (DEFLATE-compressed RGB/RGBA).
53    Png,
54    /// JPEG still image (a.k.a. MJPEG).
55    Jpeg,
56    /// GIF image (first frame; palette-based).
57    Gif,
58    /// WebP image (VP8 / VP8L).
59    Webp,
60    /// Linear PCM audio (uncompressed; layout in the stream's sample format).
61    Pcm,
62    /// Vorbis audio (Ogg Vorbis).
63    Vorbis,
64    /// FLAC lossless audio.
65    Flac,
66    /// JPEG XL image.
67    Jxl,
68    /// AAC audio (Advanced Audio Coding).
69    Aac,
70    /// VP9 video.
71    Vp9,
72    /// AV2 video (AOMedia's successor to AV1). Decode only.
73    Av2,
74    /// MP3 audio (MPEG-1/2 Audio Layer III).
75    Mp3,
76    /// Raw uncompressed video (planar/packed pixels; layout in the stream's
77    /// pixel format). The video analog of [`CodecId::Pcm`].
78    RawVideo,
79    /// SubRip subtitle (`.srt`): plain-text cues with `HH:MM:SS,mmm` timing.
80    Subrip,
81    /// WebVTT subtitle (`.vtt`): plain-text cues with `HH:MM:SS.mmm` timing.
82    WebVtt,
83    /// Apple ProRes video (422 Proxy/LT/standard/HQ, 4444, 4444 XQ). Stream
84    /// copy only; the profile travels as the stream's `codec_tag`.
85    ProRes,
86    /// Avid DNxHD / DNxHR video. Stream copy only.
87    DnxHd,
88    /// APV (Advanced Professional Video). Stream copy only.
89    Apv,
90    /// VP8 video. Stream copy only.
91    Vp8,
92    /// Apple Lossless (ALAC) audio. Stream copy only.
93    Alac,
94    /// Dolby Digital (AC-3) audio. Stream copy only.
95    Ac3,
96    /// Dolby Digital Plus (E-AC-3) audio. Stream copy only.
97    Eac3,
98    /// G.711 A-law audio (WAV format 0x0006, AIFF-C/CAF `alaw`).
99    PcmAlaw,
100    /// G.711 µ-law audio (WAV format 0x0007, AIFF-C/CAF `ulaw`).
101    PcmMulaw,
102    /// Microsoft ADPCM (WAV format 0x0002). One block per packet.
103    AdpcmMs,
104    /// IMA/DVI ADPCM as WAV stores it (format 0x0011). One block per packet.
105    AdpcmImaWav,
106    /// IMA ADPCM as QuickTime stores it (`ima4`: 34-byte blocks of 64 samples
107    /// per channel), in AIFF-C, CAF and MOV.
108    AdpcmImaQt,
109    /// MPEG-1/2 Audio Layer II (MP2). Decode only.
110    Mp2,
111    /// MPEG-1/2 Audio Layer I (MP1). Decode only.
112    Mp1,
113    /// MPEG-1 video. Identified (Matroska `V_MPEG1`), no codec.
114    Mpeg1Video,
115    /// MPEG-2 video (H.262). Identified (Matroska `V_MPEG2`), no codec.
116    Mpeg2Video,
117    /// DTS / DTS-HD audio. Identified (Matroska `A_DTS`), no codec.
118    Dts,
119    /// Dolby TrueHD audio. Identified (Matroska `A_TRUEHD`), no codec.
120    TrueHd,
121    /// OpenEXR still image (half/float/uint channels, many compressions).
122    Exr,
123}
124
125impl CodecId {
126    /// Short canonical name, matching the token used on the `ffmpeg` command
127    /// line (`-c:v h264`, `-c:a opus`, ...).
128    pub fn name(self) -> &'static str {
129        match self {
130            CodecId::None => "none",
131            CodecId::H264 => "h264",
132            CodecId::Hevc => "hevc",
133            CodecId::Opus => "opus",
134            CodecId::Avif => "avif",
135            CodecId::Png => "png",
136            CodecId::Jpeg => "mjpeg",
137            CodecId::Gif => "gif",
138            CodecId::Webp => "webp",
139            CodecId::Pcm => "pcm",
140            CodecId::Vorbis => "vorbis",
141            CodecId::Flac => "flac",
142            CodecId::Jxl => "jpegxl",
143            CodecId::Aac => "aac",
144            CodecId::Vp9 => "vp9",
145            CodecId::Av2 => "av2",
146            CodecId::Mp3 => "mp3",
147            CodecId::RawVideo => "rawvideo",
148            CodecId::Subrip => "subrip",
149            CodecId::WebVtt => "webvtt",
150            CodecId::ProRes => "prores",
151            CodecId::DnxHd => "dnxhd",
152            CodecId::Apv => "apv",
153            CodecId::Vp8 => "vp8",
154            CodecId::Alac => "alac",
155            CodecId::Ac3 => "ac3",
156            CodecId::Eac3 => "eac3",
157            CodecId::PcmAlaw => "pcm_alaw",
158            CodecId::PcmMulaw => "pcm_mulaw",
159            CodecId::AdpcmMs => "adpcm_ms",
160            CodecId::AdpcmImaWav => "adpcm_ima_wav",
161            CodecId::AdpcmImaQt => "adpcm_ima_qt",
162            CodecId::Mp2 => "mp2",
163            CodecId::Mp1 => "mp1",
164            CodecId::Mpeg1Video => "mpeg1video",
165            CodecId::Mpeg2Video => "mpeg2video",
166            CodecId::Dts => "dts",
167            CodecId::TrueHd => "truehd",
168            CodecId::Exr => "exr",
169        }
170    }
171
172    /// The media category this codec produces.
173    pub fn media_type(self) -> MediaType {
174        match self {
175            CodecId::None => MediaType::Data,
176            CodecId::H264 | CodecId::Hevc => MediaType::Video,
177            CodecId::Opus => MediaType::Audio,
178            // Image codecs carry pixel data; we model them as (single-frame) video.
179            CodecId::Avif => MediaType::Video,
180            CodecId::Png => MediaType::Video,
181            CodecId::Jpeg => MediaType::Video,
182            CodecId::Gif => MediaType::Video,
183            CodecId::Webp => MediaType::Video,
184            CodecId::Pcm => MediaType::Audio,
185            CodecId::Vorbis => MediaType::Audio,
186            CodecId::Flac => MediaType::Audio,
187            CodecId::Jxl => MediaType::Video,
188            CodecId::Aac => MediaType::Audio,
189            CodecId::Vp9 => MediaType::Video,
190            CodecId::Av2 => MediaType::Video,
191            CodecId::Mp3 => MediaType::Audio,
192            CodecId::RawVideo => MediaType::Video,
193            CodecId::Subrip => MediaType::Subtitle,
194            CodecId::WebVtt => MediaType::Subtitle,
195            CodecId::ProRes | CodecId::DnxHd | CodecId::Apv | CodecId::Vp8 => MediaType::Video,
196            CodecId::Alac | CodecId::Ac3 | CodecId::Eac3 => MediaType::Audio,
197            CodecId::PcmAlaw
198            | CodecId::PcmMulaw
199            | CodecId::AdpcmMs
200            | CodecId::AdpcmImaWav
201            | CodecId::AdpcmImaQt => MediaType::Audio,
202            CodecId::Mp2 | CodecId::Mp1 => MediaType::Audio,
203            CodecId::Mpeg1Video | CodecId::Mpeg2Video => MediaType::Video,
204            CodecId::Dts | CodecId::TrueHd => MediaType::Audio,
205            CodecId::Exr => MediaType::Video,
206        }
207    }
208
209    /// The sample format a codec NAME pins, when the name carries one.
210    ///
211    /// `CodecId` is deliberately format-agnostic — `pcm_s16le` and `pcm_f32le`
212    /// are both [`CodecId::Pcm`] — but for raw PCM the name IS the format, and
213    /// dropping it means `-c:a pcm_s16le` silently writes whatever the decoder
214    /// happened to emit. Compressed codecs return `None`: their sample format is
215    /// an internal detail, not something the CLI name selects.
216    pub fn sample_format_from_name(name: &str) -> Option<SampleFormat> {
217        match name {
218            "pcm_u8" => Some(SampleFormat::U8),
219            "pcm_s16le" => Some(SampleFormat::S16),
220            "pcm_s24le" => Some(SampleFormat::S24),
221            "pcm_s32le" => Some(SampleFormat::S32),
222            "pcm_f32le" => Some(SampleFormat::F32),
223            "pcm_f64le" => Some(SampleFormat::F64),
224            _ => None,
225        }
226    }
227
228    /// Look up a codec id from its canonical CLI name.
229    pub fn from_name(name: &str) -> Option<CodecId> {
230        match name {
231            "h264" | "avc" | "libx264" => Some(CodecId::H264),
232            "hevc" | "h265" | "x265" | "libx265" => Some(CodecId::Hevc),
233            "opus" | "libopus" => Some(CodecId::Opus),
234            "avif" => Some(CodecId::Avif),
235            "png" => Some(CodecId::Png),
236            "mjpeg" | "jpeg" | "jpg" => Some(CodecId::Jpeg),
237            "gif" => Some(CodecId::Gif),
238            "webp" => Some(CodecId::Webp),
239            "pcm" | "pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_f32le"
240            | "pcm_f64le" => Some(CodecId::Pcm),
241            "vorbis" => Some(CodecId::Vorbis),
242            "flac" => Some(CodecId::Flac),
243            "jpegxl" | "jxl" => Some(CodecId::Jxl),
244            "aac" => Some(CodecId::Aac),
245            "vp9" | "libvpx-vp9" => Some(CodecId::Vp9),
246            "av2" | "libavm" => Some(CodecId::Av2),
247            "mp3" | "mp3float" | "libmp3lame" => Some(CodecId::Mp3),
248            "rawvideo" | "yuv4mpegpipe" => Some(CodecId::RawVideo),
249            "srt" | "subrip" => Some(CodecId::Subrip),
250            "vtt" | "webvtt" => Some(CodecId::WebVtt),
251            "prores" | "prores_ks" => Some(CodecId::ProRes),
252            "dnxhd" | "dnxhr" => Some(CodecId::DnxHd),
253            "apv" => Some(CodecId::Apv),
254            "vp8" | "libvpx" => Some(CodecId::Vp8),
255            "alac" => Some(CodecId::Alac),
256            "ac3" => Some(CodecId::Ac3),
257            "eac3" => Some(CodecId::Eac3),
258            "pcm_alaw" | "alaw" => Some(CodecId::PcmAlaw),
259            "pcm_mulaw" | "mulaw" | "ulaw" => Some(CodecId::PcmMulaw),
260            "adpcm_ms" => Some(CodecId::AdpcmMs),
261            "adpcm_ima_wav" => Some(CodecId::AdpcmImaWav),
262            "adpcm_ima_qt" | "ima4" => Some(CodecId::AdpcmImaQt),
263            "mp2" | "mp2float" => Some(CodecId::Mp2),
264            "mp1" | "mp1float" => Some(CodecId::Mp1),
265            "mpeg1video" => Some(CodecId::Mpeg1Video),
266            "mpeg2video" | "mpeg2" => Some(CodecId::Mpeg2Video),
267            "dts" | "dca" => Some(CodecId::Dts),
268            "truehd" | "mlp" => Some(CodecId::TrueHd),
269            "exr" => Some(CodecId::Exr),
270            _ => None,
271        }
272    }
273}
274
275impl fmt::Display for CodecId {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        f.write_str(self.name())
278    }
279}
280
281/// Luma/chroma value range of a Y'CbCr stream.
282///
283/// This is metadata, not a conversion: it records how the samples in a plane
284/// should be interpreted, so containers can label them and consumers can avoid
285/// re-scaling data that is already in the range they want.
286///
287/// Getting it wrong is expensive and silent. Writing full-range samples into a
288/// y4m without an `XCOLORRANGE=FULL` tag makes every reader treat them as
289/// limited-range; on real content that fabricated **12 dB** of error between two
290/// byte-identical payloads (41.3 dB compared raw, 29.0 dB compared through the
291/// mislabelled container).
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
293pub enum ColorRange {
294    /// Not known. Consumers apply their own default — for Y'CbCr that is
295    /// conventionally limited range, which is why leaving this unset on
296    /// full-range data is a bug rather than a neutral choice.
297    #[default]
298    Unspecified,
299    /// "TV" / MPEG range: Y 16–235, Cb/Cr 16–240.
300    Limited,
301    /// "PC" / JPEG range: all components 0–255. JPEG and PNG are always this.
302    Full,
303}
304
305impl ColorRange {
306    /// The y4m `XCOLORRANGE` tag value, or `None` when unspecified.
307    pub fn y4m_tag(self) -> Option<&'static str> {
308        match self {
309            ColorRange::Unspecified => None,
310            ColorRange::Limited => Some("LIMITED"),
311            ColorRange::Full => Some("FULL"),
312        }
313    }
314
315    /// Parse a y4m `XCOLORRANGE` value.
316    pub fn from_y4m_tag(tag: &str) -> ColorRange {
317        match tag.trim().to_ascii_uppercase().as_str() {
318            "FULL" => ColorRange::Full,
319            "LIMITED" => ColorRange::Limited,
320            _ => ColorRange::Unspecified,
321        }
322    }
323}
324
325/// Raw pixel layout of a decoded video frame. A small starter subset.
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
327#[non_exhaustive]
328pub enum PixelFormat {
329    /// Planar Y'CbCr 4:2:0, 8-bit (the workhorse for H.264).
330    Yuv420p,
331    /// Planar Y'CbCr 4:2:2, 8-bit.
332    Yuv422p,
333    /// Planar Y'CbCr 4:4:4, 8-bit.
334    Yuv444p,
335    /// Planar Y'CbCr 4:2:0, 10-bit (each sample stored as little-endian u16).
336    Yuv420p10,
337    /// Planar Y'CbCr 4:2:2, 10-bit (little-endian u16 samples).
338    Yuv422p10,
339    /// Planar Y'CbCr 4:4:4, 10-bit (little-endian u16 samples).
340    Yuv444p10,
341    /// Planar Y'CbCr 4:2:0, 12-bit (little-endian u16 samples).
342    Yuv420p12,
343    /// Planar Y'CbCr 4:2:2, 12-bit (little-endian u16 samples).
344    Yuv422p12,
345    /// Planar Y'CbCr 4:4:4, 12-bit (little-endian u16 samples).
346    Yuv444p12,
347    /// Packed RGB, 8 bits per channel.
348    Rgb24,
349    /// Packed RGBA, 8 bits per channel.
350    Rgba,
351}
352
353impl PixelFormat {
354    pub fn name(self) -> &'static str {
355        match self {
356            PixelFormat::Yuv420p => "yuv420p",
357            PixelFormat::Yuv422p => "yuv422p",
358            PixelFormat::Yuv444p => "yuv444p",
359            PixelFormat::Yuv420p10 => "yuv420p10le",
360            PixelFormat::Yuv422p10 => "yuv422p10le",
361            PixelFormat::Yuv444p10 => "yuv444p10le",
362            PixelFormat::Yuv420p12 => "yuv420p12le",
363            PixelFormat::Yuv422p12 => "yuv422p12le",
364            PixelFormat::Yuv444p12 => "yuv444p12le",
365            PixelFormat::Rgb24 => "rgb24",
366            PixelFormat::Rgba => "rgba",
367        }
368    }
369
370    /// The format FFmpeg calls `name` (`-pix_fmt yuv420p`, `format=yuv444p`).
371    /// High-bit-depth names take FFmpeg's `le` spelling or the bare one
372    /// (`yuv420p10le` / `yuv420p10`), since every sample here is little-endian.
373    pub fn from_name(name: &str) -> Option<PixelFormat> {
374        let name = name.trim().to_ascii_lowercase();
375        let name = name.strip_suffix("le").unwrap_or(&name);
376        Some(match name {
377            "yuv420p" => PixelFormat::Yuv420p,
378            "yuv422p" => PixelFormat::Yuv422p,
379            "yuv444p" => PixelFormat::Yuv444p,
380            "yuv420p10" => PixelFormat::Yuv420p10,
381            "yuv422p10" => PixelFormat::Yuv422p10,
382            "yuv444p10" => PixelFormat::Yuv444p10,
383            "yuv420p12" => PixelFormat::Yuv420p12,
384            "yuv422p12" => PixelFormat::Yuv422p12,
385            "yuv444p12" => PixelFormat::Yuv444p12,
386            "rgb24" => PixelFormat::Rgb24,
387            "rgba" => PixelFormat::Rgba,
388            _ => return None,
389        })
390    }
391
392    /// Packed RGB(A), as opposed to planar Y'CbCr.
393    pub fn is_rgb(self) -> bool {
394        matches!(self, PixelFormat::Rgb24 | PixelFormat::Rgba)
395    }
396
397    /// Carries an alpha channel.
398    pub fn has_alpha(self) -> bool {
399        matches!(self, PixelFormat::Rgba)
400    }
401
402    /// Bits per component sample (8 for the 8-bit formats, 10 for the 10-bit
403    /// planar ones).
404    pub fn bit_depth(self) -> u32 {
405        match self {
406            PixelFormat::Yuv420p10 | PixelFormat::Yuv422p10 | PixelFormat::Yuv444p10 => 10,
407            PixelFormat::Yuv420p12 | PixelFormat::Yuv422p12 | PixelFormat::Yuv444p12 => 12,
408            _ => 8,
409        }
410    }
411
412    /// Bytes used to store one component sample: 1 for 8-bit, 2 for the 10-bit
413    /// formats (whose samples live in the low bits of a little-endian `u16`).
414    pub fn bytes_per_sample(self) -> usize {
415        if self.bit_depth() > 8 {
416            2
417        } else {
418            1
419        }
420    }
421}
422
423/// Raw audio sample layout. Multi-byte samples are little-endian; containers
424/// that store big-endian PCM (QuickTime `twos`, `in24`, ...) swap on the way
425/// in and out, so a buffer of a given format always means one byte order.
426#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
427#[non_exhaustive]
428pub enum SampleFormat {
429    /// Signed 16-bit, interleaved.
430    S16,
431    /// 32-bit float, interleaved.
432    F32,
433    /// 32-bit float, planar (one buffer per channel).
434    F32Planar,
435    /// Unsigned 8-bit (128 = silence), interleaved.
436    U8,
437    /// Signed 24-bit packed in 3 bytes, interleaved.
438    S24,
439    /// Signed 32-bit, interleaved.
440    S32,
441    /// 64-bit float, interleaved.
442    F64,
443}
444
445impl SampleFormat {
446    pub fn name(self) -> &'static str {
447        match self {
448            SampleFormat::S16 => "s16",
449            SampleFormat::F32 => "flt",
450            SampleFormat::F32Planar => "fltp",
451            SampleFormat::U8 => "u8",
452            SampleFormat::S24 => "s24",
453            SampleFormat::S32 => "s32",
454            SampleFormat::F64 => "dbl",
455        }
456    }
457
458    /// Bytes occupied by one sample of one channel.
459    pub fn bytes_per_sample(self) -> usize {
460        match self {
461            SampleFormat::U8 => 1,
462            SampleFormat::S16 => 2,
463            SampleFormat::S24 => 3,
464            SampleFormat::S32 | SampleFormat::F32 | SampleFormat::F32Planar => 4,
465            SampleFormat::F64 => 8,
466        }
467    }
468}