Skip to main content

moq_mux/codec/
legacy.rs

1//! Legacy broadcast audio (MP2, AC-3, E-AC-3) carried verbatim.
2//!
3//! These codecs share one model: every frame is whole and self-describing
4//! (framing header included), never decoded. The importer marks only the first frame of
5//! each group a keyframe (the rest extend it); the caller bounds groups by cutting them.
6//! Verbatim is byte-exact for complete, well-formed frames; malformed or out-of-scope input is
7//! rejected as an [`Error`], never mis-described. Each codec contributes only a header parser and
8//! a descriptor; this module owns the track lifecycle.
9
10use moq_net::Timestamp;
11
12use crate::catalog::hang::CatalogExt;
13use crate::container::Frame;
14
15/// Legacy audio (MP2 / AC-3 / E-AC-3) header parsing errors.
16#[derive(Debug, Clone, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19	/// An AC-3 header shorter than its 7 bytes.
20	#[error("AC-3 header needs 7 bytes")]
21	Ac3HeaderTooShort,
22
23	/// An AC-3 frame that does not start with its sync word.
24	#[error("missing AC-3 sync word")]
25	Ac3MissingSyncWord,
26
27	/// An AC-3 frame size code outside the table.
28	#[error("invalid AC-3 frame size code")]
29	Ac3InvalidFrameSizeCode,
30
31	/// An AC-3 bitstream ID this build does not parse.
32	#[error("unsupported AC-3 bsid {0}")]
33	Ac3UnsupportedBsid(u8),
34
35	/// An AC-3 header with the reserved sample-rate code.
36	#[error("reserved AC-3 sample-rate code")]
37	Ac3ReservedSampleRate,
38
39	/// An E-AC-3 header shorter than its 6 bytes.
40	#[error("E-AC-3 header needs 6 bytes")]
41	Eac3HeaderTooShort,
42
43	/// An E-AC-3 frame that does not start with its sync word.
44	#[error("missing E-AC-3 sync word")]
45	Eac3MissingSyncWord,
46
47	/// A bitstream ID that is not E-AC-3.
48	#[error("not an E-AC-3 bitstream (bsid {0})")]
49	Eac3NotEac3Bsid(u8),
50
51	/// An E-AC-3 header with the reserved stream type.
52	#[error("reserved E-AC-3 stream type")]
53	Eac3ReservedStreamType,
54
55	/// An E-AC-3 dependent substream, which carries a 7.1+ layout.
56	#[error("E-AC-3 dependent substream (7.1+ layout) is not supported; only a single independent substream")]
57	Eac3DependentSubstream,
58
59	/// An E-AC-3 independent substream past the first.
60	#[error("E-AC-3 additional substream {0} is not supported; only a single independent substream")]
61	Eac3AdditionalSubstream(u8),
62
63	/// An E-AC-3 frame length shorter than its header.
64	#[error("E-AC-3 frame length {0} shorter than its header")]
65	Eac3FrameShorterThanHeader(usize),
66
67	/// An E-AC-3 header with the reserved sample-rate code.
68	#[error("reserved E-AC-3 sample-rate code")]
69	Eac3ReservedSampleRate,
70
71	/// An MP2 header shorter than its 4 bytes.
72	#[error("MP2 header needs 4 bytes")]
73	Mp2HeaderTooShort,
74
75	/// An MP2 frame that does not start with its frame sync.
76	#[error("missing MP2 frame sync")]
77	Mp2MissingSync,
78
79	/// An MPEG audio header with the reserved or MPEG-2.5 version.
80	#[error("reserved or MPEG-2.5 audio version")]
81	Mp2ReservedVersion,
82
83	/// An MPEG audio header for a layer other than II.
84	#[error("not MPEG Layer II")]
85	Mp2NotLayerII,
86
87	/// An MP2 header with the reserved sample-rate index.
88	#[error("reserved MP2 sample-rate index")]
89	Mp2ReservedSampleRate,
90
91	/// An MP2 header with a free-format or invalid bitrate.
92	#[error("free-format or invalid MP2 bitrate")]
93	Mp2InvalidBitrate,
94}
95
96/// A Result type alias for legacy audio header parsing.
97pub type Result<T> = std::result::Result<T, Error>;
98
99/// A parsed legacy-audio frame header.
100#[derive(Debug)]
101pub(crate) struct Header {
102	/// Whole-frame size in bytes (header included).
103	pub len: usize,
104	pub sample_rate: u32,
105	pub channel_count: u32,
106	/// Samples in this frame. Per-frame, not per-codec: E-AC-3 varies it
107	/// (256 x numblks) while MP2/AC-3 keep it constant.
108	pub samples: u64,
109}
110
111/// What distinguishes one legacy codec from another.
112pub(crate) struct Descriptor {
113	/// Track name suffix, e.g. ".mp2".
114	pub track_suffix: &'static str,
115	/// Catalog codec for the rendition.
116	pub codec: hang::catalog::AudioCodec,
117	/// Bytes needed to attempt a header parse.
118	pub min_header_len: usize,
119	/// First byte of the frame sync word, so a demuxer that lost sync can scan for the
120	/// next candidate instead of parsing at every offset.
121	pub sync_byte: u8,
122	/// Parse one frame header at the start of the slice.
123	pub parse: fn(&[u8]) -> Result<Header>,
124}
125
126/// Catalog config for a legacy audio track. Both fields come from the frame
127/// header, never the TS stream_type.
128pub(crate) struct Config {
129	pub sample_rate: u32,
130	pub channel_count: u32,
131	pub container: hang::catalog::Container,
132}
133
134/// Legacy audio importer.
135///
136/// Publishes each whole frame as one hang frame, into the current group until the
137/// caller cuts it. The audio is never decoded; the catalog carries the codec,
138/// sample rate and channel count read from the frame header.
139pub(crate) struct Import {
140	track: crate::container::Producer<crate::catalog::hang::Wire, hang::catalog::AudioConfig>,
141}
142
143impl Import {
144	/// Publish on an existing track, reserving the rendition from `reserved`. Mint the track at
145	/// the descriptor's suffix with the catalog's
146	/// [`track_info`](crate::catalog::Producer::track_info).
147	pub fn new<E: CatalogExt>(
148		descriptor: &'static Descriptor,
149		track: moq_net::track::Producer,
150		reserved: crate::catalog::Reserved<E>,
151		config: Config,
152	) -> crate::Result<Self> {
153		let mut audio_config =
154			hang::catalog::AudioConfig::new(descriptor.codec.clone(), config.sample_rate, config.channel_count);
155		audio_config.container = config.container.clone();
156		// description stays None: legacy frames are self-describing and no in-repo
157		// consumer needs out-of-band config (TS export self-describes; WebCodecs
158		// cannot decode these codecs). Fill it only if a real consumer ever needs it.
159
160		tracing::debug!(name = ?track.name(), config = ?audio_config, "starting track");
161
162		// The caller's config names the container; the writer is built from that same value so the
163		// wire cannot disagree with what the rendition advertises.
164		let wire = crate::catalog::hang::Wire::try_from(&audio_config)?;
165		// Build the writer before advertising the rendition: it is fallible (enrolling the track in
166		// the broadcast timeline can collide), and a rendition published for a track we then fail to
167		// produce would be advertised to consumers but never served.
168		let track = reserved.audio(track, wire, audio_config)?;
169
170		Ok(Self { track })
171	}
172
173	/// The MoQ track name.
174	pub fn name(&self) -> &str {
175		self.track.name()
176	}
177
178	/// Finish the track, flushing the current group, and return the [`Finished`](crate::container::Finished)
179	/// track, which keeps it and its catalog rendition published.
180	///
181	/// A finish that fails ends the track with the cause instead, so it can't be retried.
182	pub fn finish(
183		self,
184	) -> crate::Result<crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::AudioConfig>> {
185		self.track.finish()
186	}
187
188	/// [`finish`](Self::finish) the track in place, for an owner that keeps this importer.
189	pub(crate) fn finish_in_place(&mut self) -> crate::Result<()> {
190		self.track.end_with(None)
191	}
192
193	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
194	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes this importer.
195	pub fn abort(self, err: moq_net::Error) {
196		self.track.abort(err);
197	}
198
199	/// Cut the current group at `end` without finishing the track.
200	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
201		self.track.cut(end)?;
202		Ok(())
203	}
204
205	/// Mark a break in the timeline by publishing a marker group. To bound the closing
206	/// group's final frame first, [`cut(end)`](Self::cut) before this. See
207	/// [`Producer::discontinuity`](crate::container::Producer::discontinuity).
208	pub fn discontinuity(&mut self) -> crate::Result<()> {
209		self.track.discontinuity()?;
210		Ok(())
211	}
212
213	/// Publish one whole frame, stamping `pts` or a wall clock when absent.
214	///
215	/// Legacy frames are self-describing and independently decodable, so the frame is marked a
216	/// keyframe only when it starts a group (see
217	/// [`Producer::needs_keyframe`](crate::container::Producer::needs_keyframe)); otherwise it extends
218	/// the current group. The caller bounds groups via [`cut`](Self::cut).
219	pub fn decode<B: moq_net::IntoBytes>(&mut self, frame: B, pts: Option<Timestamp>) -> crate::Result<()> {
220		let timestamp = self.track.timestamp(pts)?;
221		// Only the first frame of each group is a keyframe, so the group spans until the caller cuts
222		// instead of opening one group (one QUIC stream) per packet.
223		let keyframe = self.track.needs_keyframe();
224		self.track.write(Frame {
225			timestamp,
226			decode: None,
227			duration: None,
228			payload: frame.into_bytes(),
229			keyframe,
230		})?;
231		Ok(())
232	}
233}