mediadecode_ffmpeg/codec_id.rs
1//! `CodecId` newtype wrapping FFmpeg's `AVCodecID` discriminant.
2//!
3//! Constructed from hardcoded `AVCodecID` enum variants in our build's
4//! bindgen-generated bindings, so we never cast an arbitrary `i32` into
5//! the bindgen enum (that cast is UB when the value isn't in the enum's
6//! discriminant set — the same hazard `crate::pix_fmt` documents). The
7//! raw `i32` stored inside is what ends up passed to FFmpeg's C API
8//! (which declares the codec id as `c_int`), so the boundary is sound.
9
10use core::fmt;
11
12use ffmpeg_next::ffi::AVCodecID;
13use smol_str::SmolStr;
14
15/// Upper bound on the NUL search in [`CodecId::name`] and
16/// [`CodecId::long_name`].
17///
18/// FFmpeg's longest codec name is a couple of dozen bytes and its
19/// longest description a couple of hundred; the cap is generous for
20/// both and exists only so that a version-skewed descriptor table
21/// cannot turn the walk into an unbounded read — the discipline the
22/// rest of this crate's FFI text handling follows.
23const DESCRIPTOR_TEXT_MAX_BYTES: usize = 1024;
24
25/// Codec identifier. Wraps the integer value of an `AVCodecID` enum
26/// variant; comparisons and storage work without ever transmuting back
27/// into the bindgen enum.
28///
29/// # The number is the identity; the name is a rendering of it
30///
31/// [`raw`](Self::raw) is what this type *is* — what FFmpeg passed, what
32/// a store keys on, what equality compares. [`name`](Self::name) and
33/// [`long_name`](Self::long_name) read libavcodec's descriptor table for
34/// the word beside that number, so a consumer can cross into a typed
35/// codec vocabulary (`mediaframe`'s, say) or write a human row without
36/// this crate owning a second table that could come to disagree with
37/// FFmpeg's. Neither is a key: two builds of FFmpeg agree on the number
38/// long before they agree on every string.
39#[repr(transparent)]
40#[derive(Copy, Clone, Eq, PartialEq, Hash)]
41pub struct CodecId(i32);
42
43impl CodecId {
44 /// Constructs a `CodecId` from the raw integer FFmpeg uses for
45 /// `AVCodecContext::codec_id` etc. Use this only when you have a
46 /// value that came from FFmpeg or that you know maps to a real
47 /// codec; arbitrary integers are still legal but `Debug` will fall
48 /// back to printing the raw value.
49 #[inline]
50 pub const fn from_raw(raw: i32) -> Self {
51 Self(raw)
52 }
53
54 /// Returns the underlying integer.
55 #[inline]
56 pub const fn raw(self) -> i32 {
57 self.0
58 }
59
60 // --- The descriptor's words ------------------------------------------
61
62 /// FFmpeg's own short name for this codec — `"h264"`, `"aac"`,
63 /// `"subrip"` — or `None` where this build's libavcodec has no
64 /// descriptor for the id.
65 ///
66 /// **An open vocabulary, deliberately.** The answer is whatever the
67 /// linked libavcodec's `codec_descriptors[]` says, not a set this
68 /// crate enumerates: a codec FFmpeg learns in its next release names
69 /// itself here with no change on this side, which an `enum` of codecs
70 /// could never do. The constants above are the ids this crate has
71 /// reason to *compare* against; they are not the roster of what this
72 /// method can answer.
73 ///
74 /// **`None` is a real answer**, and it is why the descriptor table is
75 /// read rather than `avcodec_get_name`: that function never fails, and
76 /// for an id it cannot place it hands back the string
77 /// `"unknown_codec"` — a sentinel a consumer would store as if it were
78 /// a codec's word. Here an id with no descriptor has no name, said
79 /// plainly.
80 ///
81 /// The word is the one FFmpeg's CLI and its containers use, which is
82 /// what makes it the right thing to cross a typed vocabulary with;
83 /// [`raw`](Self::raw) stays the identity.
84 pub fn name(self) -> Option<SmolStr> {
85 let descriptor = self.descriptor();
86 if descriptor.is_null() {
87 return None;
88 }
89 // SAFETY: `descriptor` is non-null and points into libavcodec's
90 // `static const codec_descriptors[]`, so the field read is in
91 // bounds; `addr_of!` reaches it **without forming a reference** —
92 // see [`Self::descriptor`] for why that matters here. The pointer
93 // it yields is null or a NUL-terminated string literal in that same
94 // table, which is the reader's contract.
95 let name = unsafe { core::ptr::addr_of!((*descriptor).name).read() };
96 // SAFETY: as above — the name is a static, NUL-terminated literal.
97 unsafe { crate::ffi::table_text(name, DESCRIPTOR_TEXT_MAX_BYTES) }
98 }
99
100 /// FFmpeg's human description for this codec — `"H.264 / AVC / MPEG-4
101 /// AVC / MPEG-4 part 10"` — or `None` where the build has no
102 /// descriptor, or the descriptor carries no description.
103 ///
104 /// A display string and nothing more: it is FFmpeg's prose, it is not
105 /// stable across releases, and nothing should key on it. Use
106 /// [`name`](Self::name) to cross vocabularies and [`raw`](Self::raw)
107 /// to identify.
108 pub fn long_name(self) -> Option<SmolStr> {
109 let descriptor = self.descriptor();
110 if descriptor.is_null() {
111 return None;
112 }
113 // SAFETY: as [`Self::name`], for the same table and the same
114 // reason. `long_name` is independently nullable — a descriptor may
115 // carry a name and no description — which the reader answers with
116 // `None`.
117 let long_name = unsafe { core::ptr::addr_of!((*descriptor).long_name).read() };
118 // SAFETY: as above.
119 unsafe { crate::ffi::table_text(long_name, DESCRIPTOR_TEXT_MAX_BYTES) }
120 }
121
122 /// libavcodec's descriptor for this id, or null where this build
123 /// names no codec for it.
124 ///
125 /// # Two enum hazards, and both are kept out
126 ///
127 /// **Going in**, the id crosses as the `c_int` it is — through the
128 /// crate's own `avcodec_descriptor_get` redeclaration in
129 /// `decoder::c_shims` — so no `AVCodecID` is ever constructed from a
130 /// value that may not be in this build's discriminant set. libavcodec
131 /// bounds-checks the id itself and answers null for anything outside
132 /// its table, so every `i32` this type can hold is a defined call.
133 ///
134 /// **Coming back**, the pointer is left raw and the callers read
135 /// their one field through `addr_of!`. `AVCodecDescriptor` embeds an
136 /// `AVCodecID` and an `AVMediaType`, and forming a
137 /// `&AVCodecDescriptor` would assert every field valid — including
138 /// those two, which come from the *linked* library and need not lie
139 /// inside the discriminant set the *bindings* were generated from.
140 /// That is the same skew `crate::ffi`'s module note is about, met on
141 /// the way out of C rather than on the way in.
142 fn descriptor(self) -> *const ffmpeg_next::ffi::AVCodecDescriptor {
143 // SAFETY: the redeclared shim takes a plain `c_int`, so no bindgen
144 // enum is formed from `self.0`, and libavcodec answers null for an
145 // id it cannot place.
146 unsafe { crate::decoder::c_shims::avcodec_descriptor_get(self.0) }
147 }
148
149 // --- Sentinels -------------------------------------------------------
150
151 /// `AV_CODEC_ID_NONE` — sentinel for "no codec."
152 pub const NONE: Self = Self(AVCodecID::AV_CODEC_ID_NONE as i32);
153
154 // --- Video codecs ----------------------------------------------------
155
156 /// H.264 / AVC (ITU-T H.264 / ISO/IEC 14496-10).
157 pub const H264: Self = Self(AVCodecID::AV_CODEC_ID_H264 as i32);
158 /// H.265 / HEVC (ITU-T H.265 / ISO/IEC 23008-2).
159 pub const HEVC: Self = Self(AVCodecID::AV_CODEC_ID_HEVC as i32);
160 /// AV1 (Alliance for Open Media).
161 pub const AV1: Self = Self(AVCodecID::AV_CODEC_ID_AV1 as i32);
162 /// VP9 (Google).
163 pub const VP9: Self = Self(AVCodecID::AV_CODEC_ID_VP9 as i32);
164 /// VP8 (Google).
165 pub const VP8: Self = Self(AVCodecID::AV_CODEC_ID_VP8 as i32);
166 /// MPEG-2 Video (ITU-T H.262 / ISO/IEC 13818-2).
167 pub const MPEG2VIDEO: Self = Self(AVCodecID::AV_CODEC_ID_MPEG2VIDEO as i32);
168 /// MPEG-4 Part 2 Visual (ISO/IEC 14496-2).
169 pub const MPEG4: Self = Self(AVCodecID::AV_CODEC_ID_MPEG4 as i32);
170 /// Apple ProRes.
171 pub const PRORES: Self = Self(AVCodecID::AV_CODEC_ID_PRORES as i32);
172 /// Avid DNxHD / DNxHR (SMPTE VC-3).
173 pub const DNXHD: Self = Self(AVCodecID::AV_CODEC_ID_DNXHD as i32);
174 /// FFV1 — lossless intra-frame.
175 pub const FFV1: Self = Self(AVCodecID::AV_CODEC_ID_FFV1 as i32);
176 /// JPEG 2000.
177 pub const JPEG2000: Self = Self(AVCodecID::AV_CODEC_ID_JPEG2000 as i32);
178 /// MJPEG.
179 pub const MJPEG: Self = Self(AVCodecID::AV_CODEC_ID_MJPEG as i32);
180 /// VC-1 (SMPTE 421M, Microsoft Windows Media Video 9).
181 pub const VC1: Self = Self(AVCodecID::AV_CODEC_ID_VC1 as i32);
182 /// VVC / H.266 (ITU-T H.266).
183 pub const VVC: Self = Self(AVCodecID::AV_CODEC_ID_VVC as i32);
184
185 // --- Audio codecs ----------------------------------------------------
186
187 /// AAC (ISO/IEC 14496-3).
188 pub const AAC: Self = Self(AVCodecID::AV_CODEC_ID_AAC as i32);
189 /// MP3 (MPEG-1/2 Audio Layer III).
190 pub const MP3: Self = Self(AVCodecID::AV_CODEC_ID_MP3 as i32);
191 /// Opus (RFC 6716).
192 pub const OPUS: Self = Self(AVCodecID::AV_CODEC_ID_OPUS as i32);
193 /// FLAC — Free Lossless Audio Codec.
194 pub const FLAC: Self = Self(AVCodecID::AV_CODEC_ID_FLAC as i32);
195 /// AC-3 (ATSC A/52, Dolby Digital).
196 pub const AC3: Self = Self(AVCodecID::AV_CODEC_ID_AC3 as i32);
197 /// E-AC-3 (Dolby Digital Plus).
198 pub const EAC3: Self = Self(AVCodecID::AV_CODEC_ID_EAC3 as i32);
199 /// Apple Lossless Audio Codec.
200 pub const ALAC: Self = Self(AVCodecID::AV_CODEC_ID_ALAC as i32);
201 /// DTS / DTS-HD.
202 pub const DTS: Self = Self(AVCodecID::AV_CODEC_ID_DTS as i32);
203 /// Vorbis.
204 pub const VORBIS: Self = Self(AVCodecID::AV_CODEC_ID_VORBIS as i32);
205 /// PCM signed 16-bit little-endian.
206 pub const PCM_S16LE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_S16LE as i32);
207 /// PCM signed 16-bit big-endian.
208 pub const PCM_S16BE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_S16BE as i32);
209 /// PCM signed 24-bit little-endian.
210 pub const PCM_S24LE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_S24LE as i32);
211 /// PCM signed 32-bit little-endian.
212 pub const PCM_S32LE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_S32LE as i32);
213 /// PCM 32-bit float little-endian.
214 pub const PCM_F32LE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_F32LE as i32);
215 /// PCM 64-bit float little-endian.
216 pub const PCM_F64LE: Self = Self(AVCodecID::AV_CODEC_ID_PCM_F64LE as i32);
217
218 // --- Subtitle codecs -------------------------------------------------
219
220 /// SubRip (.srt).
221 pub const SUBRIP: Self = Self(AVCodecID::AV_CODEC_ID_SUBRIP as i32);
222 /// Advanced SubStation Alpha (.ass / .ssa).
223 pub const ASS: Self = Self(AVCodecID::AV_CODEC_ID_ASS as i32);
224 /// WebVTT (.vtt).
225 pub const WEBVTT: Self = Self(AVCodecID::AV_CODEC_ID_WEBVTT as i32);
226 /// 3GPP Timed Text / MOV text track.
227 pub const MOV_TEXT: Self = Self(AVCodecID::AV_CODEC_ID_MOV_TEXT as i32);
228 /// DVB subtitle (bitmap).
229 pub const DVB_SUBTITLE: Self = Self(AVCodecID::AV_CODEC_ID_DVB_SUBTITLE as i32);
230 /// HDMV / Blu-ray PGS subtitle (bitmap).
231 pub const HDMV_PGS_SUBTITLE: Self = Self(AVCodecID::AV_CODEC_ID_HDMV_PGS_SUBTITLE as i32);
232 /// DVD VOBSUB subtitle (bitmap).
233 pub const DVD_SUBTITLE: Self = Self(AVCodecID::AV_CODEC_ID_DVD_SUBTITLE as i32);
234}
235
236impl fmt::Debug for CodecId {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 let name = match *self {
239 Self::NONE => "NONE",
240 Self::H264 => "H264",
241 Self::HEVC => "HEVC",
242 Self::AV1 => "AV1",
243 Self::VP9 => "VP9",
244 Self::VP8 => "VP8",
245 Self::MPEG2VIDEO => "MPEG2VIDEO",
246 Self::MPEG4 => "MPEG4",
247 Self::PRORES => "PRORES",
248 Self::DNXHD => "DNXHD",
249 Self::FFV1 => "FFV1",
250 Self::JPEG2000 => "JPEG2000",
251 Self::MJPEG => "MJPEG",
252 Self::VC1 => "VC1",
253 Self::VVC => "VVC",
254 Self::AAC => "AAC",
255 Self::MP3 => "MP3",
256 Self::OPUS => "OPUS",
257 Self::FLAC => "FLAC",
258 Self::AC3 => "AC3",
259 Self::EAC3 => "EAC3",
260 Self::ALAC => "ALAC",
261 Self::DTS => "DTS",
262 Self::VORBIS => "VORBIS",
263 Self::PCM_S16LE => "PCM_S16LE",
264 Self::PCM_S16BE => "PCM_S16BE",
265 Self::PCM_S24LE => "PCM_S24LE",
266 Self::PCM_S32LE => "PCM_S32LE",
267 Self::PCM_F32LE => "PCM_F32LE",
268 Self::PCM_F64LE => "PCM_F64LE",
269 Self::SUBRIP => "SUBRIP",
270 Self::ASS => "ASS",
271 Self::WEBVTT => "WEBVTT",
272 Self::MOV_TEXT => "MOV_TEXT",
273 Self::DVB_SUBTITLE => "DVB_SUBTITLE",
274 Self::HDMV_PGS_SUBTITLE => "HDMV_PGS_SUBTITLE",
275 Self::DVD_SUBTITLE => "DVD_SUBTITLE",
276 _ => return write!(f, "CodecId({})", self.0),
277 };
278 write!(f, "CodecId::{name}")
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn from_raw_round_trips() {
288 let id = CodecId::from_raw(27);
289 assert_eq!(id.raw(), 27);
290 }
291
292 #[test]
293 fn known_constants_match_av_values() {
294 assert_eq!(CodecId::H264.raw(), AVCodecID::AV_CODEC_ID_H264 as i32);
295 assert_eq!(CodecId::AAC.raw(), AVCodecID::AV_CODEC_ID_AAC as i32);
296 assert_eq!(CodecId::SUBRIP.raw(), AVCodecID::AV_CODEC_ID_SUBRIP as i32);
297 }
298
299 #[test]
300 fn debug_uses_name_for_known_codecs() {
301 assert_eq!(format!("{:?}", CodecId::H264), "CodecId::H264");
302 assert_eq!(format!("{:?}", CodecId::AAC), "CodecId::AAC");
303 }
304
305 #[test]
306 fn debug_falls_back_to_raw_for_unknown() {
307 let unknown = CodecId::from_raw(-99_999);
308 assert_eq!(format!("{:?}", unknown), "CodecId(-99999)");
309 }
310
311 #[test]
312 fn equality_is_value_based() {
313 assert_eq!(CodecId::H264, CodecId::from_raw(CodecId::H264.raw()));
314 assert_ne!(CodecId::H264, CodecId::HEVC);
315 }
316
317 /// **The name producer, against the linked libavcodec** — the whole of
318 /// issue #43's ask: a codec id two crates deep now renders as the word
319 /// FFmpeg itself spells it with.
320 ///
321 /// The three arms span the media kinds, because the descriptor table
322 /// is one table and a consumer crossing into a typed vocabulary
323 /// crosses on all three.
324 #[test]
325 fn known_codecs_name_themselves() {
326 assert_eq!(CodecId::H264.name().as_deref(), Some("h264"));
327 assert_eq!(CodecId::AAC.name().as_deref(), Some("aac"));
328 assert_eq!(CodecId::SUBRIP.name().as_deref(), Some("subrip"));
329 }
330
331 /// The long name is prose and is only asked to *be* there — pinning
332 /// FFmpeg's wording would pin a string its next release may reword,
333 /// which is exactly why nothing should key on it.
334 #[test]
335 fn a_known_codec_carries_a_description_too() {
336 let long = CodecId::H264.long_name().expect("h264 has a description");
337 assert!(
338 long.contains("H.264"),
339 "libavcodec's description for h264 should name the standard, got {long:?}",
340 );
341 }
342
343 /// **An id with no descriptor has no name**, which is the reason the
344 /// descriptor table is read rather than `avcodec_get_name` — that
345 /// function answers `"unknown_codec"` here, a sentinel a consumer
346 /// would store as though it were a codec's word.
347 ///
348 /// Two shapes, both reachable through the public `from_raw` door: a
349 /// negative id, and one far past the end of any table.
350 #[test]
351 fn an_id_with_no_descriptor_has_no_name() {
352 for unknown in [CodecId::from_raw(-99_999), CodecId::from_raw(i32::MAX)] {
353 assert_eq!(unknown.name(), None, "{unknown:?} named itself");
354 assert_eq!(unknown.long_name(), None, "{unknown:?} described itself");
355 }
356 }
357
358 /// `AV_CODEC_ID_NONE` is a **sentinel, not a codec**, and libavcodec
359 /// keeps no descriptor for it — so the "no codec" row reads as absent
360 /// rather than as a track coded with something called `none`.
361 #[test]
362 fn the_none_sentinel_names_no_codec() {
363 assert_eq!(CodecId::NONE.name(), None);
364 }
365
366 /// The number stays the key. A name is read *off* the id and never
367 /// back into it: two ids that name differently are two ids, and the
368 /// identity a store writes is [`CodecId::raw`].
369 #[test]
370 fn the_name_is_a_rendering_and_the_number_is_the_identity() {
371 let from_number = CodecId::from_raw(CodecId::H264.raw());
372 assert_eq!(from_number, CodecId::H264);
373 assert_eq!(from_number.name(), CodecId::H264.name());
374 assert_ne!(CodecId::H264.name(), CodecId::HEVC.name());
375 }
376}