Skip to main content

moq_mux/import/
format.rs

1//! Typed media formats.
2//!
3//! A format selects a parser, so unlike a WebCodecs codec string (`avc1.64001f`) it is a closed
4//! set. Each import entry point takes the format type for its kind, so a format belonging to
5//! another kind cannot be passed at all; the only place the two can meet is [`FromStr`], which is
6//! where a caller crossing a string boundary (a CLI flag, an FFI call, a container's codec tag)
7//! finds out.
8
9use std::fmt;
10use std::str::FromStr;
11
12/// A single audio codec an importer can parse.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum AudioFormat {
16	/// Advanced Audio Coding, configured by an AudioSpecificConfig.
17	Aac,
18	/// Opus, configured by an OpusHead.
19	Opus,
20	/// FLAC, configured by the `fLaC` marker plus its STREAMINFO block.
21	Flac,
22	/// MPEG-1/2 Audio Layer III.
23	Mp3,
24}
25
26/// A single video codec an importer can parse.
27///
28/// H.264 and H.265 each appear twice because the input framing differs: `avc1`/`hvc1` are
29/// length-prefixed NAL units with an out-of-band config record, while `h264`/`h265` are a raw Annex B
30/// elementary stream split on start codes, carrying its parameter sets inline. The raw names follow
31/// ffmpeg's `h264`/`hevc` formats rather than `avc3`/`hev1`, which say where parameter sets live, not
32/// how NAL units are framed.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum VideoFormat {
36	/// H.264, length-prefixed NALUs with an out-of-band avcC.
37	Avc1,
38	/// H.264, a raw Annex B elementary stream with inline SPS/PPS.
39	H264,
40	/// H.265, length-prefixed NALUs with an out-of-band hvcC.
41	Hvc1,
42	/// H.265, a raw Annex B elementary stream with inline parameter sets.
43	H265,
44	/// AV1.
45	Av01,
46	/// VP8.
47	Vp8,
48	/// VP9.
49	Vp9,
50}
51
52/// A container an importer can demux, which may publish more than one track.
53///
54/// Names only the input the importer parses. Every container is demuxed into its tracks' frames;
55/// republishing the input whole is a choice made on the concrete importer
56/// ([`fmp4::Import::with_cmaf`](crate::container::fmp4::Import::with_cmaf),
57/// [`ts::Passthrough`](crate::container::ts::Passthrough)), never by the format name.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
59#[non_exhaustive]
60pub enum ContainerFormat {
61	/// Fragmented MP4 / CMAF.
62	Fmp4,
63	/// Matroska / WebM.
64	Mkv,
65	/// MPEG-2 transport stream.
66	Ts,
67	/// Flash Video, as used by RTMP.
68	Flv,
69}
70
71/// Any format an importer handles, and the kind of import it selects.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum Format {
75	/// A single audio codec.
76	Audio(AudioFormat),
77	/// A single video codec.
78	Video(VideoFormat),
79	/// A container publishing its own tracks.
80	Container(ContainerFormat),
81}
82
83/// Which importer a [`Format`] selects.
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
85#[non_exhaustive]
86pub enum Kind {
87	/// A single audio codec, imported by [`Track::audio`](crate::import::Track::audio).
88	Audio,
89	/// A single video codec, imported by [`Track::video`](crate::import::Track::video).
90	Video,
91	/// A container that publishes its own tracks, imported by [`Demuxer`](crate::import::Demuxer).
92	Container,
93}
94
95impl Kind {
96	/// The name used in errors and docs.
97	pub fn name(self) -> &'static str {
98		match self {
99			Kind::Audio => "audio",
100			Kind::Video => "video",
101			Kind::Container => "container",
102		}
103	}
104}
105
106impl Format {
107	/// Which import entry point handles this format.
108	pub fn kind(self) -> Kind {
109		match self {
110			Format::Audio(_) => Kind::Audio,
111			Format::Video(_) => Kind::Video,
112			Format::Container(_) => Kind::Container,
113		}
114	}
115}
116
117impl FromStr for Format {
118	type Err = crate::Error;
119
120	/// Parse a format name, accepting each format's aliases.
121	///
122	/// The one table: every other `FromStr` here defers to it, so an alias is written down once and
123	/// a name can never mean different things to the classifier and the importer.
124	fn from_str(s: &str) -> Result<Self, Self::Err> {
125		Ok(match s {
126			"aac" => Format::Audio(AudioFormat::Aac),
127			"opus" => Format::Audio(AudioFormat::Opus),
128			"flac" => Format::Audio(AudioFormat::Flac),
129			"mp3" => Format::Audio(AudioFormat::Mp3),
130
131			"avc1" | "avcc" => Format::Video(VideoFormat::Avc1),
132			"h264" => Format::Video(VideoFormat::H264),
133			"hvc1" | "hvcc" => Format::Video(VideoFormat::Hvc1),
134			"h265" | "hevc" => Format::Video(VideoFormat::H265),
135			"av01" | "av1" | "av1c" | "av1C" => Format::Video(VideoFormat::Av01),
136			"vp8" | "vp08" => Format::Video(VideoFormat::Vp8),
137			"vp9" | "vp09" => Format::Video(VideoFormat::Vp9),
138
139			"fmp4" | "cmaf" => Format::Container(ContainerFormat::Fmp4),
140			"mkv" | "webm" | "matroska" => Format::Container(ContainerFormat::Mkv),
141			// Not `m2ts`, which names BDAV's 192-byte packets rather than 188-byte TS.
142			"ts" | "mpegts" | "mpeg2ts" => Format::Container(ContainerFormat::Ts),
143			"flv" => Format::Container(ContainerFormat::Flv),
144
145			_ => return Err(crate::Error::UnknownFormat(s.to_string())),
146		})
147	}
148}
149
150impl fmt::Display for Format {
151	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152		match self {
153			Format::Audio(format) => format.fmt(f),
154			Format::Video(format) => format.fmt(f),
155			Format::Container(format) => format.fmt(f),
156		}
157	}
158}
159
160/// Parse `s` as a format of one kind, reporting the kind that does handle it otherwise.
161///
162/// A caller that reached the wrong entry point learns which one to use, rather than being told the
163/// format is unknown when it is perfectly well known.
164fn parse_kind(s: &str, wanted: Kind) -> Result<Format, crate::Error> {
165	let format: Format = s.parse()?;
166	if format.kind() != wanted {
167		return Err(crate::Error::WrongKind {
168			format: s.to_string(),
169			actual: format.kind().name(),
170			wanted: wanted.name(),
171		});
172	}
173	Ok(format)
174}
175
176macro_rules! kind_format {
177	($ty:ident, $kind:ident, $($variant:ident => $name:literal),+ $(,)?) => {
178		impl fmt::Display for $ty {
179			fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180				f.write_str(match self {
181					$($ty::$variant => $name,)+
182				})
183			}
184		}
185
186		impl FromStr for $ty {
187			type Err = crate::Error;
188
189			/// Parse a format name of this kind, accepting its aliases. A name belonging to another
190			/// kind reports [`WrongKind`](crate::Error::WrongKind) rather than being unknown.
191			fn from_str(s: &str) -> Result<Self, Self::Err> {
192				match parse_kind(s, Kind::$kind)? {
193					Format::$kind(format) => Ok(format),
194					// `parse_kind` already rejected every other kind.
195					_ => unreachable!(),
196				}
197			}
198		}
199	};
200}
201
202kind_format!(AudioFormat, Audio,
203	Aac => "aac", Opus => "opus", Flac => "flac", Mp3 => "mp3");
204
205kind_format!(VideoFormat, Video,
206	Avc1 => "avc1", H264 => "h264", Hvc1 => "hvc1", H265 => "h265",
207	Av01 => "av01", Vp8 => "vp8", Vp9 => "vp9");
208
209kind_format!(ContainerFormat, Container,
210	Fmp4 => "fmp4", Mkv => "mkv", Ts => "ts", Flv => "flv");
211
212impl AudioFormat {
213	/// The suffix of a track named after this format, such as `.opus` in `0.opus`.
214	pub fn track_suffix(self) -> &'static str {
215		match self {
216			AudioFormat::Aac => ".aac",
217			AudioFormat::Opus => ".opus",
218			AudioFormat::Flac => ".flac",
219			AudioFormat::Mp3 => ".mp3",
220		}
221	}
222}
223
224impl VideoFormat {
225	/// The suffix of a track named after this format, such as `.avc3` in `0.avc3`.
226	///
227	/// Names the codec family the track publishes rather than the input, so a raw Annex B stream
228	/// is `.avc3` or `.hev1` like every other in-band H.26x track.
229	pub fn track_suffix(self) -> &'static str {
230		match self {
231			VideoFormat::Avc1 => ".avc1",
232			VideoFormat::H264 => ".avc3",
233			VideoFormat::Hvc1 => ".hvc1",
234			VideoFormat::H265 => ".hev1",
235			VideoFormat::Av01 => ".av01",
236			VideoFormat::Vp8 => ".vp8",
237			VideoFormat::Vp9 => ".vp9",
238		}
239	}
240}
241
242#[cfg(test)]
243mod tests {
244	use super::*;
245
246	/// Every alias resolves, and `Display` gives back the canonical name rather than the alias, so a
247	/// track named after its format is named the same whichever spelling the caller used.
248	#[test]
249	fn aliases_resolve_to_one_canonical_name() {
250		for (aliases, canonical) in [
251			(vec!["h264"], "h264"),
252			(vec!["h265", "hevc"], "h265"),
253			(vec!["avc1", "avcc"], "avc1"),
254			(vec!["hvc1", "hvcc"], "hvc1"),
255			(vec!["av01", "av1", "av1c", "av1C"], "av01"),
256			(vec!["vp8", "vp08"], "vp8"),
257			(vec!["vp9", "vp09"], "vp9"),
258			(vec!["fmp4", "cmaf"], "fmp4"),
259			(vec!["mkv", "webm", "matroska"], "mkv"),
260			(vec!["ts", "mpegts", "mpeg2ts"], "ts"),
261			(vec!["opus"], "opus"),
262		] {
263			for alias in aliases {
264				let format: Format = alias.parse().unwrap_or_else(|err| panic!("{alias}: {err}"));
265				assert_eq!(format.to_string(), canonical, "{alias} should canonicalize");
266			}
267		}
268	}
269
270	/// The whole point of the typed formats: a name of the wrong kind is caught at the string
271	/// boundary, and says which entry point does take it.
272	#[test]
273	fn a_format_of_another_kind_names_the_kind_that_takes_it() {
274		let err = "h264".parse::<AudioFormat>().unwrap_err();
275		assert!(
276			matches!(
277				&err,
278				crate::Error::WrongKind {
279					actual: "video",
280					wanted: "audio",
281					..
282				}
283			),
284			"got {err:?}"
285		);
286
287		let err = "fmp4".parse::<VideoFormat>().unwrap_err();
288		assert!(
289			matches!(
290				&err,
291				crate::Error::WrongKind {
292					actual: "container",
293					wanted: "video",
294					..
295				}
296			),
297			"got {err:?}"
298		);
299
300		let err = "opus".parse::<ContainerFormat>().unwrap_err();
301		assert!(
302			matches!(
303				&err,
304				crate::Error::WrongKind {
305					actual: "audio",
306					wanted: "container",
307					..
308				}
309			),
310			"got {err:?}"
311		);
312	}
313
314	#[test]
315	fn an_unrecognized_name_is_unknown_rather_than_wrong_kind() {
316		let err = "prores".parse::<VideoFormat>().unwrap_err();
317		assert!(
318			matches!(&err, crate::Error::UnknownFormat(f) if f == "prores"),
319			"got {err:?}"
320		);
321	}
322}