Skip to main content

moq_mux/codec/aac/
import.rs

1use super::Config;
2use crate::catalog::hang::CatalogExt;
3use crate::container::Frame;
4use crate::import::track::Written;
5
6/// AAC importer.
7///
8/// The catalog comes from an AudioSpecificConfig (variable-length, typically extracted from an MP4
9/// ESDS atom); build the config with [`config`]. Every AAC packet is independently decodable, so
10/// [`decode`](Self::decode) marks only the first frame of each group a keyframe (the rest extend
11/// it): frames accumulate into the current group until the caller [`cut`](Self::cut)s. The [`import::Track`](crate::import::Track) facade cuts once a group (one
12/// QUIC stream) holds 100 ms, as [`Join`](crate::container::Join) says. The codec's packet loss
13/// concealment handles drops.
14pub struct Import {
15	track: crate::container::Producer<crate::catalog::hang::Wire, hang::catalog::AudioConfig>,
16	/// How long each access unit plays, from the AudioSpecificConfig, or `None` for an object type
17	/// coding frames of another length.
18	frame: Option<moq_net::Timestamp>,
19}
20
21impl Import {
22	/// Publish on an existing track producer with a resolved catalog config.
23	///
24	/// Build one from an AudioSpecificConfig with [`config`] (which keeps its bytes as the catalog
25	/// `description`), or from an out-of-band [`Config`] via `try_into()` (which synthesizes the
26	/// description, refusing a channel count that does not pick a channelConfiguration). The rendition
27	/// publishes immediately.
28	pub fn new<E: CatalogExt>(
29		track: moq_net::track::Producer,
30		reserved: crate::catalog::Reserved<E>,
31		config: hang::catalog::AudioConfig,
32	) -> crate::Result<Self> {
33		if config.description.is_none() {
34			let err = crate::Error::from(super::Error::MissingDescription);
35			track.abort(err.reason())?;
36			return Err(err);
37		}
38		tracing::debug!(name = ?track.name(), ?config, "starting track");
39		// The caller's config names the container; the writer is built from that same value so the
40		// wire cannot disagree with what the rendition advertises.
41		let wire = crate::catalog::hang::Wire::try_from(&config)?;
42		let frame = config.description.as_deref().and_then(super::frame_duration);
43		// Build the writer before advertising the rendition: it is fallible (enrolling the track in
44		// the broadcast timeline can collide), and a rendition published for a track we then fail to
45		// produce would be advertised to consumers but never served.
46		let track = reserved.audio(track, wire, config)?;
47		Ok(Self { track, frame })
48	}
49
50	/// The MoQ track name this importer publishes on.
51	pub fn name(&self) -> &str {
52		self.track.name()
53	}
54
55	/// A watch-only handle to this track's subscriber demand.
56	pub fn demand(&self) -> moq_net::track::Demand {
57		self.track.track().demand()
58	}
59
60	/// Finish the track, flushing the current group, and return the [`Finished`](crate::container::Finished)
61	/// track, which keeps it and its catalog rendition published.
62	///
63	/// A finish that fails ends the track with the cause instead, so it can't be retried.
64	pub fn finish(
65		self,
66	) -> crate::Result<crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::AudioConfig>> {
67		self.track.finish()
68	}
69
70	/// [`finish`](Self::finish) the track in place, for an owner that keeps this importer.
71	pub(crate) fn finish_in_place(&mut self) -> crate::Result<()> {
72		self.track.end_with(None)
73	}
74
75	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
76	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes this importer.
77	pub fn abort(self, err: moq_net::Error) {
78		self.track.abort(err);
79	}
80
81	/// Record the media duration emitted together by the TS importer.
82	pub(crate) fn burst(&mut self, duration: std::time::Duration) -> crate::Result<()> {
83		self.track.burst(duration)
84	}
85
86	/// Close the current group at `end`, or without declaring an end when none is known, so the
87	/// producer doesn't extrapolate one from the gap before the last frame.
88	pub(crate) fn close(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
89		match end {
90			Some(end) => self.track.cut(Some(end)),
91			None => self.track.cut_unended(),
92		}
93	}
94
95	/// Cut the current group at `end` without finishing the track.
96	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
97		self.track.cut(end)?;
98		Ok(())
99	}
100
101	/// Mark a break in the timeline by publishing a marker group. To bound the closing
102	/// group's final frame first, [`cut(end)`](Self::cut) before this. See
103	/// [`Producer::discontinuity`](crate::container::Producer::discontinuity).
104	pub fn discontinuity(&mut self) -> crate::Result<()> {
105		self.track.discontinuity()?;
106		Ok(())
107	}
108
109	/// Publish one AAC packet, stamping `pts` or a wall clock when absent.
110	///
111	/// AAC is independently decodable, so the packet is marked a keyframe only when it starts a group
112	/// (see [`Producer::needs_keyframe`](crate::container::Producer::needs_keyframe)); otherwise it
113	/// extends the current group. The caller bounds groups via [`cut`](Self::cut).
114	pub fn decode<B: moq_net::IntoBytes>(&mut self, frame: B, pts: Option<moq_net::Timestamp>) -> crate::Result<()> {
115		self.write(frame.into_bytes(), pts).map(|_| ())
116	}
117
118	/// [`decode`](Self::decode), returning the packet's timestamp and how long it plays, if known.
119	pub(crate) fn write(&mut self, payload: bytes::Bytes, pts: Option<moq_net::Timestamp>) -> crate::Result<Written> {
120		let timestamp = self.track.timestamp(pts)?;
121		// Only the first frame of each group is a keyframe, so the group spans until the caller cuts
122		// instead of opening one group (one QUIC stream) per packet.
123		let keyframe = self.track.needs_keyframe();
124		self.track.write(Frame {
125			timestamp,
126			decode: None,
127			payload,
128			keyframe,
129			duration: None,
130		})?;
131		Ok(Written {
132			timestamp,
133			duration: self.frame,
134		})
135	}
136}
137
138/// Build a catalog config from an AudioSpecificConfig, keeping `init` verbatim as the catalog
139/// `description` (re-encoding the parsed fields would drop any SBR/PS extension the parse ignores).
140/// Errors on a malformed or empty buffer.
141pub fn config(init: &[u8]) -> crate::Result<hang::catalog::AudioConfig> {
142	let mut buf = init;
143	let parsed = Config::parse(&mut buf)?;
144	// Keep the bytes verbatim. Re-encoding would refuse a program config element whose count does
145	// not pick a channelConfiguration, and would drop any SBR or PS extension the parse ignores.
146	let mut audio = catalog_config(&parsed);
147	audio.description = Some(bytes::Bytes::copy_from_slice(init));
148	Ok(audio)
149}
150
151impl TryFrom<Config> for hang::catalog::AudioConfig {
152	type Error = super::Error;
153
154	/// Build a catalog config from a config resolved out of band (an ADTS header, gstreamer caps),
155	/// synthesizing the AudioSpecificConfig `description` since no verbatim bytes are available.
156	///
157	/// Refuses a channel count that does not pick a channelConfiguration, rather than describing it as
158	/// another layout.
159	fn try_from(config: Config) -> Result<Self, Self::Error> {
160		let mut audio = catalog_config(&config);
161		audio.description = Some(config.encode()?);
162		Ok(audio)
163	}
164}
165
166fn catalog_config(config: &Config) -> hang::catalog::AudioConfig {
167	let mut audio = hang::catalog::AudioConfig::new(
168		hang::catalog::AAC {
169			profile: config.profile,
170		},
171		config.sample_rate,
172		config.channel_count,
173	);
174	audio.container = hang::catalog::Container::Legacy;
175	audio
176}
177
178#[cfg(test)]
179mod tests {
180	#[tokio::test(start_paused = true)]
181	async fn raw_publication_needs_a_description_before_advertising() {
182		let mut broadcast = moq_net::broadcast::Info::new().produce();
183		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
184		let track = broadcast
185			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
186			.unwrap();
187		let mut subscriber = track.subscribe(None);
188		let config = hang::catalog::AudioConfig::new(hang::catalog::AAC { profile: 2 }, 48_000, 2);
189		assert!(matches!(
190			super::Import::new(track, catalog.reserve(), config),
191			Err(crate::Error::Aac(super::super::Error::MissingDescription))
192		));
193		assert!(catalog.snapshot().audio.renditions.is_empty());
194		assert!(matches!(
195			subscriber.poll_finished(&kio::Waiter::noop()),
196			std::task::Poll::Ready(Err(_))
197		));
198	}
199}