Skip to main content

moq_mux/codec/opus/
import.rs

1use super::Config;
2use crate::catalog::hang::CatalogExt;
3use crate::container::Frame;
4use crate::import::track::Written;
5
6/// Opus importer.
7///
8/// Publishes raw Opus frames (no Ogg framing) to a single moq track. Build it with
9/// [`new`](Self::new), passing the track producer and the
10/// [`catalog::Reserved`](crate::catalog::Reserved) it reserves its rendition from.
11///
12/// Every Opus packet is independently decodable, so [`decode`](Self::decode) marks only the first
13/// frame of each group a keyframe (the rest extend it): frames accumulate into the current group
14/// until the caller [`cut`](Self::cut)s. The
15/// [`import::Track`](crate::import::Track) facade cuts once a group (one QUIC stream) holds 100 ms,
16/// as [`Join`](crate::container::Join) says. Opus' packet loss concealment handles drops.
17pub struct Import {
18	track: crate::container::Producer<crate::catalog::hang::Wire, hang::catalog::AudioConfig>,
19}
20
21impl Import {
22	/// Publish on an existing track producer with a resolved catalog config.
23	///
24	/// Audio can't derive its config from frames, so the caller passes a complete
25	/// [`AudioConfig`](hang::catalog::AudioConfig) (build one from an OpusHead with [`config`], or
26	/// from an out-of-band [`Config`] via `into()`). The rendition publishes immediately.
27	pub fn new<E: CatalogExt>(
28		track: moq_net::track::Producer,
29		reserved: crate::catalog::Reserved<E>,
30		config: hang::catalog::AudioConfig,
31	) -> crate::Result<Self> {
32		tracing::debug!(name = ?track.name(), ?config, "starting track");
33		// The caller's config names the container; the writer is built from that same value so the
34		// wire cannot disagree with what the rendition advertises.
35		let wire = crate::catalog::hang::Wire::try_from(&config)?;
36		let track = reserved.audio(track, wire, config)?;
37		Ok(Self { track })
38	}
39
40	/// The MoQ track name this importer publishes on.
41	pub fn name(&self) -> &str {
42		self.track.track().name()
43	}
44
45	/// A watch-only handle to this track's subscriber demand.
46	pub fn demand(&self) -> moq_net::track::Demand {
47		self.track.track().demand()
48	}
49
50	/// Finish the track, flushing the current group, and return the [`Finished`](crate::container::Finished)
51	/// track, which keeps it and its catalog rendition published.
52	///
53	/// A finish that fails ends the track with the cause instead, so it can't be retried.
54	pub fn finish(
55		self,
56	) -> crate::Result<crate::container::Finished<crate::catalog::hang::Wire, hang::catalog::AudioConfig>> {
57		self.track.finish()
58	}
59
60	/// [`finish`](Self::finish) the track in place, for an owner that keeps this importer.
61	pub(crate) fn finish_in_place(&mut self) -> crate::Result<()> {
62		self.track.end_with(None)
63	}
64
65	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
66	/// see the real cause rather than [`moq_net::Error::Dropped`]. Consumes this importer.
67	pub fn abort(self, err: moq_net::Error) {
68		self.track.abort(err);
69	}
70
71	/// Close the current group at `end`, or without declaring an end when none is known, so the
72	/// producer doesn't extrapolate one from the gap before the last frame.
73	pub(crate) fn close(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
74		match end {
75			Some(end) => self.track.cut(Some(end)),
76			None => self.track.cut_unended(),
77		}
78	}
79
80	/// Cut the current group at `end` without finishing the track.
81	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
82		self.track.cut(end)?;
83		Ok(())
84	}
85
86	/// Mark a break in the timeline by publishing a marker group. To bound the closing
87	/// group's final frame first, [`cut(end)`](Self::cut) before this. See
88	/// [`Producer::discontinuity`](crate::container::Producer::discontinuity).
89	pub fn discontinuity(&mut self) -> crate::Result<()> {
90		self.track.discontinuity()?;
91		Ok(())
92	}
93
94	/// Publish one Opus packet, stamping `pts` or a wall clock when absent.
95	///
96	/// Opus is independently decodable, so the packet is marked a keyframe only when it starts a group
97	/// (see [`Producer::needs_keyframe`](crate::container::Producer::needs_keyframe)); otherwise it
98	/// extends the current group. The caller bounds groups via [`cut`](Self::cut).
99	pub fn decode<B: moq_net::IntoBytes>(&mut self, frame: B, pts: Option<moq_net::Timestamp>) -> crate::Result<()> {
100		self.write(frame.into_bytes(), pts).map(|_| ())
101	}
102
103	/// The timestamp a packet at `pts` is written at: `pts`, or the broadcast clock's reading.
104	pub(crate) fn timestamp(&self, pts: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
105		self.track.timestamp(pts)
106	}
107
108	/// [`decode`](Self::decode), returning the packet's timestamp and how long it plays, if known.
109	pub(crate) fn write(&mut self, payload: bytes::Bytes, pts: Option<moq_net::Timestamp>) -> crate::Result<Written> {
110		let timestamp = self.track.timestamp(pts)?;
111		// Only the first frame of each group is a keyframe, so the group spans until the caller cuts
112		// instead of opening one group (one QUIC stream) per packet.
113		let keyframe = self.track.needs_keyframe();
114		// The packet states its own duration, so a pause's marker lands where its audio stops.
115		let duration = super::packet_samples(&payload)
116			.and_then(|samples| moq_net::Timestamp::from_scale(samples.into(), 48_000).ok());
117		self.track.write(Frame {
118			timestamp,
119			decode: None,
120			payload,
121			keyframe,
122			duration,
123		})?;
124		Ok(Written { timestamp, duration })
125	}
126}
127
128/// Build a catalog config from an OpusHead. Errors on a malformed or empty buffer.
129///
130/// The catalog rate is the decoder's 48 kHz output, not the OpusHead's informational input rate.
131pub fn config(init: &[u8]) -> crate::Result<hang::catalog::AudioConfig> {
132	let mut buf = init;
133	let mut config: hang::catalog::AudioConfig = Config::parse(&mut buf)?.into();
134	// Publish the head as given: a re-encode would rewrite its version byte.
135	config.description = Some(bytes::Bytes::copy_from_slice(init));
136	Ok(config)
137}
138
139impl From<Config> for hang::catalog::AudioConfig {
140	/// Build a catalog config from a config resolved out of band (e.g. gstreamer caps).
141	///
142	/// The catalog describes the decoder's output: Opus always decodes at 48 kHz, whatever the
143	/// informational input rate in [`Config::sample_rate`] claims.
144	fn from(config: Config) -> Self {
145		let mut audio = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, config.channel_count);
146		audio.warmup = Some(super::WARMUP);
147		// Family 2 is ambisonics in AmbiX order (RFC 8486 ยง3.1); its mapping refuses the channel
148		// counts the catalog's layout cannot carry.
149		if config.mapping.is_some_and(|mapping| mapping.family() == 2) {
150			audio.layout = Some(hang::catalog::AudioLayout::Ambisonic);
151		}
152		audio.description = config.encode().ok();
153		audio.container = hang::catalog::Container::Legacy;
154		audio
155	}
156}
157
158#[cfg(test)]
159mod tests {
160	use std::time::Duration;
161
162	use moq_net::Timestamp;
163
164	#[test]
165	fn catalog_rate_is_decoder_rate() {
166		// A 44.1 kHz input rate is informational; the description keeps it, the catalog does not.
167		let head = super::Config::new(44_100, 2).encode().unwrap();
168		let config = super::config(&head).unwrap();
169		assert_eq!(config.sample_rate, 48_000);
170		assert_eq!(config.description.as_deref(), Some(head.as_ref()));
171		assert_eq!(config.warmup, Some(Duration::from_millis(80)));
172
173		let config: hang::catalog::AudioConfig = super::Config::new(44_100, 2).into();
174		assert_eq!(config.sample_rate, 48_000);
175	}
176
177	#[test]
178	fn family_two_is_ambisonic() {
179		// First order ambisonics, one stream per channel, in ACN order.
180		let mapping = crate::codec::opus::Mapping::new(crate::codec::opus::mapping::Config {
181			family: 2,
182			streams: 4,
183			coupled: 0,
184			table: &[0, 1, 2, 3],
185		})
186		.unwrap();
187		let mut head = super::Config::new(48_000, 4);
188		head.mapping = Some(mapping);
189		let config = super::config(&head.encode().unwrap()).unwrap();
190		assert_eq!(config.layout, Some(hang::catalog::AudioLayout::Ambisonic));
191		assert_eq!(config.channel_count, 4);
192
193		// Family 1 surround and family 0 stereo stay plain channels.
194		let mut head = super::Config::new(48_000, 6);
195		head.mapping = Some(crate::codec::opus::Mapping::vorbis(6).unwrap());
196		assert_eq!(super::config(&head.encode().unwrap()).unwrap().layout, None);
197		let head = super::Config::new(48_000, 2).encode().unwrap();
198		assert_eq!(super::config(&head).unwrap().layout, None);
199	}
200
201	#[tokio::test(start_paused = true)]
202	async fn a_loc_reservation_reaches_the_wire_and_the_catalog() {
203		let mut broadcast = moq_net::broadcast::Info::new().produce();
204		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
205		let track = broadcast
206			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
207			.unwrap();
208		let subscriber = track.subscribe(None);
209		let reserved = catalog.reserve();
210		let config = crate::codec::opus::Config::new(48_000, 2);
211		let mut config: hang::catalog::AudioConfig = config.into();
212		config.container = hang::catalog::Container::Loc;
213		let mut import = super::Import::new(track, reserved, config).unwrap();
214
215		let audio = catalog.snapshot().audio.renditions.get("audio").cloned().unwrap();
216		assert_eq!(audio.container, hang::catalog::Container::Loc);
217
218		let payload = b"opus payload";
219		import
220			.decode(payload, Some(Timestamp::from_micros(1_000).unwrap()))
221			.unwrap();
222		let mut media = crate::container::Consumer::new(
223			subscriber,
224			crate::catalog::hang::Wire::loc(crate::container::Kind::Data),
225		);
226		let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame())
227			.await
228			.unwrap()
229			.unwrap()
230			.unwrap();
231		assert_eq!(frame.payload.as_ref(), payload);
232		assert_eq!(frame.timestamp, Timestamp::from_micros(1_000).unwrap());
233
234		let _finished = import.finish().unwrap();
235	}
236
237	/// A pause ends where the last packet's audio does, as its TOC byte says, not where the packet
238	/// starts: hang's marker is the only place a reader learns where a group's audio stops.
239	#[tokio::test(start_paused = true)]
240	async fn a_pause_ends_where_the_last_packet_does() {
241		let mut broadcast = moq_net::broadcast::Info::new().produce();
242		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
243		let track = broadcast
244			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
245			.unwrap();
246		// Delayed, so the reader starts from the first group rather than the newest.
247		let subscriber =
248			track.subscribe(
249				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
250					moq_net::track::Start::Live {
251						min: Some(Duration::from_secs(5)),
252						max: Some(Duration::from_secs(5)),
253					},
254				)]),
255			);
256		let config: hang::catalog::AudioConfig = crate::codec::opus::Config::new(48_000, 2).into();
257		let wire = crate::catalog::hang::Wire::try_from(&config).unwrap();
258		let mut import = super::Import::new(track, catalog.reserve(), config).unwrap();
259
260		// Two 20 ms CELT packets, then a pause.
261		for start in [0, 20_000] {
262			import
263				.decode(&[31 << 3, 0][..], Some(Timestamp::from_micros(start).unwrap()))
264				.unwrap();
265		}
266		import.discontinuity().unwrap();
267		let _finished = import.finish().unwrap();
268
269		let mut media = crate::container::Consumer::new(subscriber, wire);
270		let mut reads = Vec::new();
271		while let Some(read) = kio::clock::timeout(Duration::from_secs(1), media.read())
272			.await
273			.unwrap()
274			.unwrap()
275		{
276			reads.push(match read {
277				crate::container::Read::Frame { frame, .. } => {
278					format!("frame {}", frame.timestamp.as_micros().unwrap())
279				}
280				crate::container::Read::End { end, .. } => format!("end {}", end.as_micros().unwrap()),
281				crate::container::Read::Gap { .. } => continue,
282			});
283		}
284		// The marker sits one unit of the track's timescale before the packet's end, so what resumes
285		// right there still starts after it.
286		assert_eq!(reads, ["frame 0", "frame 20000", "end 39999"]);
287	}
288}