moq-mux 0.3.7

Media muxers and demuxers for MoQ
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
use std::{fmt, str::FromStr};

use bytes::Buf;
use hang::Error;

/// The supported decoder formats.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DecoderFormat {
	/// H264 with Annex B framing (start code prefixed, inline SPS/PPS).
	#[cfg(feature = "h264")]
	Avc3,
	/// fMP4/CMAF container.
	#[cfg(feature = "mp4")]
	Fmp4,
	/// aka H265 with inline SPS/PPS
	#[cfg(feature = "h265")]
	Hev1,
	/// AV1 with inline sequence headers
	#[cfg(feature = "av1")]
	Av01,
	/// Raw AAC frames (not ADTS).
	#[cfg(feature = "aac")]
	Aac,
	/// Raw Opus frames (not Ogg).
	#[cfg(feature = "opus")]
	Opus,
	/// H264 with AVCC framing (length-prefixed NALUs, out-of-band SPS/PPS).
	#[cfg(feature = "h264")]
	Avc1,
}

impl FromStr for DecoderFormat {
	type Err = Error;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s {
			#[cfg(feature = "h264")]
			"avc1" | "avcc" => Ok(DecoderFormat::Avc1),
			#[cfg(feature = "h264")]
			"avc3" => Ok(DecoderFormat::Avc3),
			#[cfg(feature = "h264")]
			"h264" | "annex-b" => {
				tracing::warn!("format '{s}' is deprecated, use 'avc3' instead");
				Ok(DecoderFormat::Avc3)
			}
			#[cfg(feature = "h265")]
			"hev1" => Ok(DecoderFormat::Hev1),
			#[cfg(feature = "mp4")]
			"fmp4" | "cmaf" => Ok(DecoderFormat::Fmp4),
			#[cfg(feature = "av1")]
			"av01" | "av1" | "av1C" => Ok(DecoderFormat::Av01),
			#[cfg(feature = "aac")]
			"aac" => Ok(DecoderFormat::Aac),
			#[cfg(feature = "opus")]
			"opus" => Ok(DecoderFormat::Opus),
			_ => Err(Error::UnknownFormat(s.to_string())),
		}
	}
}

impl fmt::Display for DecoderFormat {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match *self {
			#[cfg(feature = "h264")]
			DecoderFormat::Avc1 => write!(f, "avc1"),
			#[cfg(feature = "h264")]
			DecoderFormat::Avc3 => write!(f, "avc3"),
			#[cfg(feature = "mp4")]
			DecoderFormat::Fmp4 => write!(f, "fmp4"),
			#[cfg(feature = "h265")]
			DecoderFormat::Hev1 => write!(f, "hev1"),
			#[cfg(feature = "av1")]
			DecoderFormat::Av01 => write!(f, "av01"),
			#[cfg(feature = "aac")]
			DecoderFormat::Aac => write!(f, "aac"),
			#[cfg(feature = "opus")]
			DecoderFormat::Opus => write!(f, "opus"),
		}
	}
}

/// Formats that support stream decoding (unknown frame boundaries).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StreamFormat {
	/// aka H264 with inline SPS/PPS
	#[cfg(feature = "h264")]
	Avc3,
	/// fMP4/CMAF container.
	#[cfg(feature = "mp4")]
	Fmp4,
	/// aka H265 with inline SPS/PPS
	#[cfg(feature = "h265")]
	Hev1,
	/// AV1 with inline sequence headers
	#[cfg(feature = "av1")]
	Av01,
}

impl FromStr for StreamFormat {
	type Err = Error;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s {
			#[cfg(feature = "h264")]
			"avc3" => Ok(StreamFormat::Avc3),
			#[cfg(feature = "h264")]
			"h264" | "annex-b" => {
				tracing::warn!("format '{s}' is deprecated, use 'avc3' instead");
				Ok(StreamFormat::Avc3)
			}
			#[cfg(feature = "h265")]
			"hev1" => Ok(StreamFormat::Hev1),
			#[cfg(feature = "mp4")]
			"fmp4" | "cmaf" => Ok(StreamFormat::Fmp4),
			#[cfg(feature = "av1")]
			"av01" | "av1" | "av1C" => Ok(StreamFormat::Av01),
			_ => Err(Error::UnknownFormat(s.to_string())),
		}
	}
}

impl fmt::Display for StreamFormat {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match *self {
			#[cfg(feature = "h264")]
			StreamFormat::Avc3 => write!(f, "avc3"),
			#[cfg(feature = "mp4")]
			StreamFormat::Fmp4 => write!(f, "fmp4"),
			#[cfg(feature = "h265")]
			StreamFormat::Hev1 => write!(f, "hev1"),
			#[cfg(feature = "av1")]
			StreamFormat::Av01 => write!(f, "av01"),
		}
	}
}

impl From<StreamFormat> for DecoderFormat {
	fn from(format: StreamFormat) -> Self {
		match format {
			#[cfg(feature = "h264")]
			StreamFormat::Avc3 => DecoderFormat::Avc3,
			#[cfg(feature = "mp4")]
			StreamFormat::Fmp4 => DecoderFormat::Fmp4,
			#[cfg(feature = "h265")]
			StreamFormat::Hev1 => DecoderFormat::Hev1,
			#[cfg(feature = "av1")]
			StreamFormat::Av01 => DecoderFormat::Av01,
		}
	}
}

#[derive(derive_more::From)]
enum StreamKind {
	/// aka H264 with inline SPS/PPS
	#[cfg(feature = "h264")]
	Avc3(super::Avc3),
	// Boxed because it's a large struct and clippy complains about the size.
	#[cfg(feature = "mp4")]
	Fmp4(Box<super::Fmp4>),
	/// aka H265 with inline SPS/PPS
	#[cfg(feature = "h265")]
	Hev1(super::Hev1),
	#[cfg(feature = "av1")]
	Av01(super::Av01),
}

#[derive(derive_more::From)]
enum DecoderKind {
	/// H264 with AVCC framing
	#[cfg(feature = "h264")]
	Avc1(super::Avc1),
	/// H264 with Annex B framing
	#[cfg(feature = "h264")]
	Avc3(super::Avc3),
	// Boxed because it's a large struct and clippy complains about the size.
	#[cfg(feature = "mp4")]
	Fmp4(Box<super::Fmp4>),
	/// aka H265 with inline SPS/PPS
	#[cfg(feature = "h265")]
	Hev1(super::Hev1),
	#[cfg(feature = "av1")]
	Av01(super::Av01),
	#[cfg(feature = "aac")]
	Aac(super::Aac),
	#[cfg(feature = "opus")]
	Opus(super::Opus),
}

/// A decoder for formats that support stream decoding (unknown frame boundaries).
///
/// This includes formats like H.264 (AVC3), H.265 (HEV1), and fMP4/CMAF.
/// Use this when the caller does not know the frame boundaries.
pub struct StreamDecoder {
	decoder: StreamKind,
}

impl StreamDecoder {
	/// Create a new stream decoder with the given format.
	pub fn new(broadcast: moq_lite::BroadcastProducer, catalog: crate::CatalogProducer, format: StreamFormat) -> Self {
		let decoder = match format {
			#[cfg(feature = "h264")]
			StreamFormat::Avc3 => super::Avc3::new(broadcast, catalog).into(),
			#[cfg(feature = "mp4")]
			StreamFormat::Fmp4 => Box::new(super::Fmp4::new(broadcast, catalog, super::Fmp4Config::default())).into(),
			#[cfg(feature = "h265")]
			StreamFormat::Hev1 => super::Hev1::new(broadcast, catalog).into(),
			#[cfg(feature = "av1")]
			StreamFormat::Av01 => super::Av01::new(broadcast, catalog).into(),
		};

		Self { decoder }
	}

	/// Initialize the decoder with the given buffer and populate the broadcast.
	///
	/// This is not required for self-describing formats like fMP4 or AVC3.
	///
	/// The buffer will be fully consumed, or an error will be returned.
	pub fn initialize<T: Buf + AsRef<[u8]>>(&mut self, buf: &mut T) -> anyhow::Result<()> {
		match self.decoder {
			#[cfg(feature = "h264")]
			StreamKind::Avc3(ref mut decoder) => decoder.initialize(buf)?,
			#[cfg(feature = "mp4")]
			StreamKind::Fmp4(ref mut decoder) => decoder.decode(buf)?,
			#[cfg(feature = "h265")]
			StreamKind::Hev1(ref mut decoder) => decoder.initialize(buf)?,
			#[cfg(feature = "av1")]
			StreamKind::Av01(ref mut decoder) => decoder.initialize(buf)?,
		}

		anyhow::ensure!(!buf.has_remaining(), "buffer was not fully consumed");

		Ok(())
	}

	/// Decode a stream of data from the given buffer.
	///
	/// This method should be used when the caller does not know the frame boundaries.
	/// For example, reading a fMP4 file from disk or receiving annex.b over the network.
	///
	/// A timestamp cannot be provided because you don't even know if the buffer contains a frame.
	/// The wall clock time will be used if the format does not contain its own timestamps.
	///
	/// If the buffer is not fully consumed, more data is needed.
	pub fn decode_stream<T: Buf + AsRef<[u8]>>(&mut self, buf: &mut T) -> anyhow::Result<()> {
		match self.decoder {
			#[cfg(feature = "h264")]
			StreamKind::Avc3(ref mut decoder) => decoder.decode_stream(buf, None),
			#[cfg(feature = "mp4")]
			StreamKind::Fmp4(ref mut decoder) => decoder.decode(buf),
			#[cfg(feature = "h265")]
			StreamKind::Hev1(ref mut decoder) => decoder.decode_stream(buf, None),
			#[cfg(feature = "av1")]
			StreamKind::Av01(ref mut decoder) => decoder.decode_stream(buf, None),
		}
	}

	/// Finish the decoder, flushing any buffered data.
	///
	/// This should be called when the input stream ends to ensure the last
	/// group is properly finalized.
	pub fn finish(&mut self) -> anyhow::Result<()> {
		match self.decoder {
			#[cfg(feature = "h264")]
			StreamKind::Avc3(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "mp4")]
			StreamKind::Fmp4(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "h265")]
			StreamKind::Hev1(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "av1")]
			StreamKind::Av01(ref mut decoder) => decoder.finish(),
		}
	}

	/// Check if the decoder has read enough data to be initialized.
	pub fn is_initialized(&self) -> bool {
		match self.decoder {
			#[cfg(feature = "h264")]
			StreamKind::Avc3(ref decoder) => decoder.is_initialized(),
			#[cfg(feature = "mp4")]
			StreamKind::Fmp4(ref decoder) => decoder.is_initialized(),
			#[cfg(feature = "h265")]
			StreamKind::Hev1(ref decoder) => decoder.is_initialized(),
			#[cfg(feature = "av1")]
			StreamKind::Av01(ref decoder) => decoder.is_initialized(),
		}
	}
}

/// A decoder for formats with known frame boundaries.
///
/// This supports all formats and should be used when the caller knows the frame boundaries.
pub struct Decoder {
	decoder: DecoderKind,
}

impl Decoder {
	/// Create a new decoder with the given format and initialization data.
	///
	/// The buffer will be fully consumed, or an error will be returned.
	pub fn new<T: Buf + AsRef<[u8]>>(
		broadcast: moq_lite::BroadcastProducer,
		catalog: crate::CatalogProducer,
		format: DecoderFormat,
		buf: &mut T,
	) -> anyhow::Result<Self> {
		let decoder = match format {
			#[cfg(feature = "h264")]
			DecoderFormat::Avc1 => {
				let mut decoder = super::Avc1::new(broadcast, catalog);
				decoder.initialize(buf)?;
				decoder.into()
			}
			#[cfg(feature = "h264")]
			DecoderFormat::Avc3 => {
				let mut decoder = super::Avc3::new(broadcast, catalog);
				decoder.initialize(buf)?;
				decoder.into()
			}
			#[cfg(feature = "mp4")]
			DecoderFormat::Fmp4 => {
				let mut decoder = Box::new(super::Fmp4::new(broadcast, catalog, super::Fmp4Config::default()));
				decoder.decode(buf)?;
				decoder.into()
			}
			#[cfg(feature = "h265")]
			DecoderFormat::Hev1 => {
				let mut decoder = super::Hev1::new(broadcast, catalog);
				decoder.initialize(buf)?;
				decoder.into()
			}
			#[cfg(feature = "av1")]
			DecoderFormat::Av01 => {
				let mut decoder = super::Av01::new(broadcast, catalog);
				decoder.initialize(buf)?;
				decoder.into()
			}
			#[cfg(feature = "aac")]
			DecoderFormat::Aac => {
				let config = super::AacConfig::parse(buf)?;
				super::Aac::new(broadcast, catalog, config)?.into()
			}
			#[cfg(feature = "opus")]
			DecoderFormat::Opus => {
				let config = super::OpusConfig::parse(buf)?;
				super::Opus::new(broadcast, catalog, config)?.into()
			}
		};

		anyhow::ensure!(!buf.has_remaining(), "buffer was not fully consumed");

		Ok(Self { decoder })
	}

	/// Finish the decoder, flushing any buffered data.
	///
	/// This should be called when the input stream ends to ensure the last
	/// group is properly finalized.
	pub fn finish(&mut self) -> anyhow::Result<()> {
		match self.decoder {
			#[cfg(feature = "h264")]
			DecoderKind::Avc1(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "h264")]
			DecoderKind::Avc3(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "mp4")]
			DecoderKind::Fmp4(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "h265")]
			DecoderKind::Hev1(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "av1")]
			DecoderKind::Av01(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "aac")]
			DecoderKind::Aac(ref mut decoder) => decoder.finish(),
			#[cfg(feature = "opus")]
			DecoderKind::Opus(ref mut decoder) => decoder.finish(),
		}
	}

	/// Decode a frame from the given buffer.
	///
	/// This method should be used when the caller knows the buffer consists of an entire frame.
	///
	/// A timestamp may be provided if the format does not contain its own timestamps.
	/// Otherwise, a value of [None] will use the wall clock time.
	///
	/// The buffer will be fully consumed, or an error will be returned.
	/// If the buffer did not contain a frame, future decode calls may fail.
	pub fn decode_frame<T: Buf + AsRef<[u8]>>(
		&mut self,
		buf: &mut T,
		pts: Option<hang::container::Timestamp>,
	) -> anyhow::Result<()> {
		match self.decoder {
			#[cfg(feature = "h264")]
			DecoderKind::Avc1(ref mut decoder) => decoder.decode(buf, pts)?,
			#[cfg(feature = "h264")]
			DecoderKind::Avc3(ref mut decoder) => decoder.decode_frame(buf, pts)?,
			#[cfg(feature = "mp4")]
			DecoderKind::Fmp4(ref mut decoder) => decoder.decode(buf)?,
			#[cfg(feature = "h265")]
			DecoderKind::Hev1(ref mut decoder) => decoder.decode_frame(buf, pts)?,
			#[cfg(feature = "av1")]
			DecoderKind::Av01(ref mut decoder) => decoder.decode_frame(buf, pts)?,
			#[cfg(feature = "aac")]
			DecoderKind::Aac(ref mut decoder) => decoder.decode(buf, pts)?,
			#[cfg(feature = "opus")]
			DecoderKind::Opus(ref mut decoder) => decoder.decode(buf, pts)?,
		}

		anyhow::ensure!(!buf.has_remaining(), "buffer was not fully consumed");

		Ok(())
	}
}

#[cfg(feature = "opus")]
impl From<super::Opus> for Decoder {
	fn from(opus: super::Opus) -> Self {
		Self { decoder: opus.into() }
	}
}

#[cfg(feature = "aac")]
impl From<super::Aac> for Decoder {
	fn from(aac: super::Aac) -> Self {
		Self { decoder: aac.into() }
	}
}