Skip to main content

moq/
audio.rs

1//! Raw-audio import/export via [`moq_audio`].
2//!
3//! Sibling to `moq_publish_media_*` / `moq_consume_audio`
4//! (those handle already-encoded frames). These functions accept and
5//! return raw PCM, with Opus encode/decode happening inside the FFI
6//! boundary.
7//!
8//! Format / sample rate / channel count are fixed at producer or
9//! consumer construction via [`moq_audio_encoder_input`] /
10//! [`moq_audio_encoder_output`] / [`moq_audio_decoder_output`], so
11//! each [`moq_audio_frame`] carries only payload bytes and a
12//! timestamp.
13
14use std::ffi::{c_char, c_void};
15use std::time::Duration;
16
17use bytes::Bytes;
18use tokio::sync::oneshot;
19
20use crate::ffi::OnStatus;
21use crate::{Error, Id, NonZeroSlab, State, ffi};
22
23// ---- C-visible types ----
24
25/// Raw PCM sample layout, mirroring WebCodecs `AudioData.format`.
26///
27/// The enum is exposed in the C header for readability, but ABI
28/// fields/parameters that carry it are typed `u32`. A C caller
29/// passing an unknown discriminant gets `Error::InvalidCode` instead
30/// of UB.
31///
32/// <https://developer.mozilla.org/en-US/docs/Web/API/AudioData/format>
33#[repr(C)]
34#[allow(non_camel_case_types)]
35#[derive(Clone, Copy, Debug)]
36pub enum moq_audio_format {
37	MOQ_AUDIO_FORMAT_U8 = 0,
38	MOQ_AUDIO_FORMAT_S16 = 1,
39	MOQ_AUDIO_FORMAT_S32 = 2,
40	MOQ_AUDIO_FORMAT_F32 = 3,
41	MOQ_AUDIO_FORMAT_U8_PLANAR = 4,
42	MOQ_AUDIO_FORMAT_S16_PLANAR = 5,
43	MOQ_AUDIO_FORMAT_S32_PLANAR = 6,
44	MOQ_AUDIO_FORMAT_F32_PLANAR = 7,
45}
46
47fn audio_format_from_u32(value: u32) -> Result<moq_audio::Format, Error> {
48	use moq_audio::Format;
49	Ok(match value {
50		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_U8 as u32 => Format::U8,
51		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_S16 as u32 => Format::S16,
52		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_S32 as u32 => Format::S32,
53		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_F32 as u32 => Format::F32,
54		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_U8_PLANAR as u32 => Format::U8Planar,
55		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_S16_PLANAR as u32 => Format::S16Planar,
56		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_S32_PLANAR as u32 => Format::S32Planar,
57		v if v == moq_audio_format::MOQ_AUDIO_FORMAT_F32_PLANAR as u32 => Format::F32Planar,
58		_ => return Err(Error::InvalidCode),
59	})
60}
61
62/// PCM layout the caller hands to [`moq_publish_audio_raw_frame`].
63#[repr(C)]
64#[allow(non_camel_case_types)]
65pub struct moq_audio_encoder_input {
66	/// `moq_audio_format` discriminant.
67	pub format: u32,
68	pub sample_rate: u32,
69	pub channels: u32,
70}
71
72/// Codec-side configuration. `sample_rate` / `channels` = 0 means
73/// "match the input (snapping the rate up to a libopus-supported
74/// value if necessary)".
75#[repr(C)]
76#[allow(non_camel_case_types)]
77pub struct moq_audio_encoder_output {
78	/// Codec id, UTF-8 (currently only "opus").
79	pub codec: *const c_char,
80	pub codec_len: usize,
81	/// 0 = derive from input.
82	pub sample_rate: u32,
83	/// 0 = derive from input.
84	pub channels: u32,
85	/// 0 = libopus default.
86	pub bitrate: u32,
87	/// Encoded frame duration in milliseconds. Opus accepts
88	/// 2.5/5/10/20/40/60 ms; pass 20 to match the JS publish path.
89	/// (For 2.5 ms, the caller must pre-round; integer ms only.)
90	pub frame_duration_ms: u32,
91}
92
93/// PCM layout the caller wants out of [`moq_consume_audio_raw`].
94#[repr(C)]
95#[allow(non_camel_case_types)]
96pub struct moq_audio_decoder_output {
97	pub format: u32,
98	/// 0 = deliver at the codec's native sample rate.
99	pub sample_rate: u32,
100	/// 0 = deliver at the codec's native channel count.
101	pub channels: u32,
102	/// Upper bound on buffering before skipping a stalled group, in
103	/// milliseconds. Same congestion-control knob as
104	/// `moq_consume_audio`'s `max_latency_ms`. 0 = skip
105	/// aggressively (the moq-mux default); set to your playout
106	/// buffer (tens to a few hundred ms) for a softer skip. Named
107	/// `_max` to leave room for a future `latency_min_ms`
108	/// (jitter-buffer floor).
109	pub latency_max_ms: u64,
110}
111
112/// One audio frame: payload bytes plus a presentation timestamp.
113///
114/// `data` is owned by the consume slab (see
115/// [`moq_consume_audio_raw_frame_free`]) or borrowed by the publish call
116/// (the publisher copies before returning).
117#[repr(C)]
118#[allow(non_camel_case_types)]
119pub struct moq_audio_frame {
120	pub timestamp_us: u64,
121	pub data: *const u8,
122	pub data_size: usize,
123}
124
125// ---- State extensions (used internally by lib.rs) ----
126
127#[derive(Default)]
128pub struct Audio {
129	producers: NonZeroSlab<moq_audio::encode::Producer<moq_mux::catalog::hang::Extra>>,
130	consumer_tasks: NonZeroSlab<Option<AudioTaskEntry>>,
131	frames: NonZeroSlab<moq_audio::Frame>,
132}
133
134/// A spawned task entry: `close` signals shutdown, `callback` delivers status.
135///
136/// `close` is an `Option` so `consume_close` can drop just the sender without
137/// removing the entry. The task delivers one final terminal callback and then
138/// removes itself, so `user_data` stays valid until that callback fires.
139struct AudioTaskEntry {
140	close: Option<oneshot::Sender<()>>,
141	callback: OnStatus,
142}
143
144impl Audio {
145	pub fn publish(
146		&mut self,
147		broadcast: &mut moq_net::broadcast::Producer,
148		catalog: moq_mux::catalog::Producer<moq_mux::catalog::hang::Extra>,
149		input: moq_audio::encode::Input,
150		options: moq_audio::encode::Options,
151	) -> Result<Id, Error> {
152		let producer = moq_audio::encode::Producer::new(broadcast, catalog, input, &options)?;
153		self.producers.insert(producer)
154	}
155
156	pub fn publish_frame(&mut self, id: Id, frame: moq_audio::Frame) -> Result<(), Error> {
157		let producer = self.producers.get_mut(id).ok_or(Error::MediaNotFound)?;
158		producer.write(&frame)?;
159		Ok(())
160	}
161
162	pub fn publish_finish(&mut self, id: Id) -> Result<(), Error> {
163		let producer = self.producers.remove(id).ok_or(Error::MediaNotFound)?;
164		producer.finish()?;
165		Ok(())
166	}
167
168	pub fn consume(
169		&mut self,
170		broadcast: &moq_net::broadcast::Consumer,
171		catalog: &hang::catalog::AudioConfig,
172		name: &str,
173		config: moq_audio::decode::Config,
174		on_frame: OnStatus,
175	) -> Result<Id, Error> {
176		let broadcast = broadcast.clone();
177		let catalog = catalog.clone();
178		let name = name.to_string();
179
180		let channel = oneshot::channel();
181		let entry = AudioTaskEntry {
182			close: Some(channel.0),
183			callback: on_frame,
184		};
185		let id = self.consumer_tasks.insert(Some(entry))?;
186
187		// `decode::Consumer::new` subscribes (blocking on SUBSCRIBE_OK), so run it
188		// inside the task to keep this entrypoint non-blocking.
189		tokio::spawn(async move {
190			let res = async move {
191				let consumer = moq_audio::decode::Consumer::new(&broadcast, &catalog, name, config).await?;
192				Self::run(on_frame, consumer, channel.1).await
193			}
194			.await;
195
196			// Deliver one final terminal callback (code <= 0), then drop the entry.
197			// Pull it out from under the lock so the callback never runs while held.
198			let entry = State::lock().audio.consumer_tasks.remove(id).flatten();
199			if let Some(entry) = entry {
200				entry.callback.call(res);
201			}
202		});
203
204		Ok(id)
205	}
206
207	async fn run(
208		callback: OnStatus,
209		mut consumer: moq_audio::decode::Consumer,
210		mut close: oneshot::Receiver<()>,
211	) -> Result<(), Error> {
212		loop {
213			// `biased` so a pending close always wins over a ready frame.
214			let frame = tokio::select! {
215				biased;
216				_ = &mut close => return Ok(()),
217				frame = consumer.read() => match frame? {
218					Some(frame) => frame,
219					None => return Ok(()),
220				},
221			};
222
223			// Hold the lock only to buffer the frame; release it before the callback.
224			let frame_id = State::lock().audio.frames.insert(frame)?;
225			callback.call(Ok(frame_id));
226		}
227	}
228
229	pub fn consume_close(&mut self, id: Id) -> Result<(), Error> {
230		// Signal shutdown; the task delivers a final callback and removes itself.
231		self.consumer_tasks
232			.get_mut(id)
233			.and_then(|entry| entry.as_mut())
234			.ok_or(Error::TrackNotFound)?
235			.close
236			.take()
237			.ok_or(Error::TrackNotFound)?;
238		Ok(())
239	}
240
241	pub fn frame_info(&self, id: Id, dst: &mut moq_audio_frame) -> Result<(), Error> {
242		let frame = self.frames.get(id).ok_or(Error::FrameNotFound)?;
243		*dst = moq_audio_frame {
244			// The C ABI carries plain microseconds, so flatten the scaled
245			// `Timestamp` here at the boundary. Saturating rather than erroring:
246			// this is a getter on a frame we already decoded, and a u64 overflow
247			// needs a timestamp ~580,000 years out.
248			timestamp_us: u64::try_from(frame.timestamp.as_micros()).unwrap_or(u64::MAX),
249			data: frame.data.as_ptr(),
250			data_size: frame.data.len(),
251		};
252		Ok(())
253	}
254
255	pub fn frame_free(&mut self, id: Id) -> Result<(), Error> {
256		self.frames.remove(id).ok_or(Error::FrameNotFound)?;
257		Ok(())
258	}
259}
260
261// ---- C entry points ----
262
263/// Open an audio track on a broadcast.
264///
265/// The encoder configuration is fixed at construction; subsequent
266/// frame writes pass only payload + timestamp via
267/// [`moq_publish_audio_raw_frame`].
268///
269/// Returns a non-zero handle on success or a negative error code.
270///
271/// # Safety
272/// - `name` must point to `name_len` bytes of UTF-8.
273/// - `input` / `output` must point to fully populated structs.
274/// - `output->codec` must point to `output->codec_len` bytes of UTF-8.
275#[unsafe(no_mangle)]
276pub unsafe extern "C" fn moq_publish_audio_raw(
277	broadcast: u32,
278	name: *const c_char,
279	name_len: usize,
280	input: *const moq_audio_encoder_input,
281	output: *const moq_audio_encoder_output,
282) -> i32 {
283	ffi::enter(move || {
284		let broadcast = ffi::parse_id(broadcast)?;
285		let name = unsafe { ffi::parse_str(name, name_len)? }.to_string();
286		let raw_input = unsafe { input.as_ref() }.ok_or(Error::InvalidPointer)?;
287		let raw_output = unsafe { output.as_ref() }.ok_or(Error::InvalidPointer)?;
288		let codec_str = unsafe { ffi::parse_str(raw_output.codec, raw_output.codec_len)? };
289
290		let encoder_input = moq_audio::encode::Input {
291			format: audio_format_from_u32(raw_input.format)?,
292			sample_rate: raw_input.sample_rate,
293			channels: raw_input.channels,
294		};
295
296		// The C ABI takes an explicit track name and spells "unset" as 0, so map
297		// both onto the Rust options here rather than leaking either convention.
298		let mut options = moq_audio::encode::Options::default();
299		options.track = Some(name);
300		options.codec = codec_str
301			.parse()
302			.map_err(|_| Error::UnknownFormat(codec_str.to_string()))?;
303		options.sample_rate = zeroable(raw_output.sample_rate);
304		options.channels = zeroable(raw_output.channels);
305		options.bitrate = zeroable(raw_output.bitrate);
306		options.frame_duration = Duration::from_millis(raw_output.frame_duration_ms.into());
307
308		let mut state = State::lock();
309		let State { publish, audio, .. } = &mut *state;
310		let (broadcast_producer, catalog) = publish.pair_mut(broadcast)?;
311
312		audio.publish(broadcast_producer, catalog.clone(), encoder_input, options)
313	})
314}
315
316/// The C ABI spells an unset `u32` knob as 0, which no field here accepts as a
317/// real value.
318fn zeroable(value: u32) -> Option<u32> {
319	(value != 0).then_some(value)
320}
321
322/// Push one audio frame.
323///
324/// `frame->data` is borrowed for the duration of the call; the
325/// producer copies before returning.
326///
327/// # Safety
328/// - `frame` must point to a valid [`moq_audio_frame`].
329/// - `frame->data` must point to `frame->data_size` bytes.
330#[unsafe(no_mangle)]
331pub unsafe extern "C" fn moq_publish_audio_raw_frame(producer: u32, frame: *const moq_audio_frame) -> i32 {
332	ffi::enter(move || {
333		let producer = ffi::parse_id(producer)?;
334		let frame = unsafe { frame.as_ref() }.ok_or(Error::InvalidPointer)?;
335		let data = unsafe { ffi::parse_slice(frame.data, frame.data_size)? };
336
337		let owned = moq_audio::Frame {
338			// The C ABI carries plain microseconds; scale them at the boundary.
339			timestamp: moq_net::Timestamp::from_micros(frame.timestamp_us).map_err(moq_audio::Error::from)?,
340			data: Bytes::copy_from_slice(data),
341		};
342
343		State::lock().audio.publish_frame(producer, owned)
344	})
345}
346
347/// Flush any pending samples and finalize an audio producer.
348#[unsafe(no_mangle)]
349pub extern "C" fn moq_publish_audio_raw_finish(producer: u32) -> i32 {
350	ffi::enter(move || {
351		let producer = ffi::parse_id(producer)?;
352		State::lock().audio.publish_finish(producer)
353	})
354}
355
356/// Subscribe to an audio track and decode it into PCM.
357///
358/// The catalog `index` identifies which audio rendition to subscribe
359/// to, matching the existing `moq_consume_audio` selection
360/// model. TODO: a future API will pick the right rendition
361/// automatically (ABR).
362///
363/// Returns a non-zero handle on success or a negative error code.
364///
365/// `on_frame` is called with a positive frame ID per frame, then exactly once
366/// more with a terminal code: `0` (closed cleanly) or a negative error. After
367/// the terminal (`<= 0`) callback, `on_frame` is never called again and
368/// `user_data` is never touched again, so release `user_data` there. The
369/// terminal callback fires even after [`moq_consume_audio_raw_close`].
370///
371/// # Safety
372/// - `output` must point to a valid [`moq_audio_decoder_output`].
373/// - `user_data` must stay valid until the terminal (`<= 0`) `on_frame` callback.
374#[unsafe(no_mangle)]
375pub unsafe extern "C" fn moq_consume_audio_raw(
376	catalog: u32,
377	index: u32,
378	output: *const moq_audio_decoder_output,
379	on_frame: Option<extern "C" fn(user_data: *mut c_void, frame: i32)>,
380	user_data: *mut c_void,
381) -> i32 {
382	ffi::enter(move || {
383		let catalog = ffi::parse_id(catalog)?;
384		let raw = unsafe { output.as_ref() }.ok_or(Error::InvalidPointer)?;
385
386		let mut config = moq_audio::decode::Config::default();
387		config.format = audio_format_from_u32(raw.format)?;
388		config.sample_rate = zeroable(raw.sample_rate);
389		config.channels = zeroable(raw.channels);
390		config.latency_max = (raw.latency_max_ms != 0).then(|| Duration::from_millis(raw.latency_max_ms));
391
392		let on_frame = unsafe { OnStatus::new(user_data, on_frame) };
393
394		let mut state = State::lock();
395		let (broadcast, audio_cfg, name) = state.consume.audio_rendition(catalog, index as usize)?;
396
397		let State { audio, .. } = &mut *state;
398		audio.consume(&broadcast, &audio_cfg, &name, config, on_frame)
399	})
400}
401
402/// Stop an audio (raw PCM) consumer's background task.
403///
404/// Returns immediately: zero on success, or a negative code if already closed.
405/// Does NOT free `user_data`; the on-frame callback still fires once more with a
406/// terminal `0` (or a negative error), which is where `user_data` should be
407/// released. Frame IDs already delivered to the callback are likewise not freed;
408/// release each with [`moq_consume_audio_raw_frame_free`].
409#[unsafe(no_mangle)]
410pub extern "C" fn moq_consume_audio_raw_close(consumer: u32) -> i32 {
411	ffi::enter(move || {
412		let consumer = ffi::parse_id(consumer)?;
413		State::lock().audio.consume_close(consumer)
414	})
415}
416
417/// Copy a delivered frame's metadata into `dst`.
418///
419/// The written `dst->data` pointer remains valid until the same `id`
420/// is released with [`moq_consume_audio_raw_frame_free`].
421///
422/// # Safety
423/// - `dst` must point to a writable [`moq_audio_frame`].
424#[unsafe(no_mangle)]
425pub unsafe extern "C" fn moq_consume_audio_raw_frame(id: u32, dst: *mut moq_audio_frame) -> i32 {
426	ffi::enter(move || {
427		let id = ffi::parse_id(id)?;
428		let dst = unsafe { dst.as_mut() }.ok_or(Error::InvalidPointer)?;
429		State::lock().audio.frame_info(id, dst)
430	})
431}
432
433/// Free a frame previously delivered through the consume callback.
434/// Required for every delivered frame ID; closing the parent consumer
435/// is not enough.
436#[unsafe(no_mangle)]
437pub extern "C" fn moq_consume_audio_raw_frame_free(id: u32) -> i32 {
438	ffi::enter(move || {
439		let id = ffi::parse_id(id)?;
440		State::lock().audio.frame_free(id)
441	})
442}