Skip to main content

moq_audio/encode/
encoder.rs

1//! Audio encoder front end.
2//!
3//! [`Encoder`] checks [`Config`] against the codec, opens a
4//! [backend](super::backend::Backend) for it, and owns what every backend of a
5//! codec shares: framing, the terminal drain, and the catalog entry.
6
7use std::str::FromStr;
8use std::time::Duration;
9
10use bytes::Bytes;
11
12use super::Encoded;
13use super::backend;
14use crate::opus;
15use crate::pcm;
16use crate::{Error, Format, Layout};
17
18/// Samples per channel in one AAC-LC frame.
19const AAC_FRAME_SIZE: usize = 1024;
20
21/// The audioObjectType of AAC-LC (ISO 14496-3 Table 1.17), `mp4a.40.2`.
22const AAC_LC: u8 = 2;
23
24/// The widest sample rate an AudioSpecificConfig can name: the escape from the
25/// frequency table is a 24-bit field.
26const AAC_MAX_SAMPLE_RATE: u32 = 0xFF_FFFF;
27
28/// Output audio codec. `#[non_exhaustive]` so new codecs can be added without
29/// breaking external `match`es.
30#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
31#[non_exhaustive]
32pub enum Codec {
33	/// Opus (RFC 6716), and the default.
34	#[default]
35	Opus,
36	/// Uncompressed interleaved little-endian IEEE-754 binary32 PCM.
37	Pcm,
38	/// AAC-LC (`mp4a.40.2`), through the platform's encoder. A host without one
39	/// refuses it at construction.
40	Aac,
41}
42
43impl Codec {
44	/// Canonical lowercase identifier, matching the WebCodecs / RFC catalog
45	/// string. Used as the wire/FFI codec name everywhere.
46	pub fn as_str(self) -> &'static str {
47		match self {
48			Self::Opus => "opus",
49			Self::Pcm => "pcm",
50			Self::Aac => "aac",
51		}
52	}
53}
54
55impl std::fmt::Display for Codec {
56	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57		f.write_str(self.as_str())
58	}
59}
60
61impl FromStr for Codec {
62	type Err = Error;
63
64	fn from_str(s: &str) -> Result<Self, Self::Err> {
65		match s {
66			"opus" => Ok(Self::Opus),
67			"pcm" => Ok(Self::Pcm),
68			"aac" => Ok(Self::Aac),
69			other => Err(Error::Unsupported(format!("unknown codec: {other}"))),
70		}
71	}
72}
73
74/// Encoder backend selection.
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum Backend {
78	/// Prefer a platform encoder, falling back to software.
79	#[default]
80	Auto,
81	/// Require a software backend.
82	Software,
83}
84
85/// What the audio carries, which tunes the codec for it.
86///
87/// Mirrors `@moq/publish`'s audio source `kind`. Only Opus uses it; PCM and AAC
88/// encode the same either way.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum Kind {
91	/// Speech, such as a microphone: Opus codes it as VoIP voice, and a
92	/// [`Producer`](super::Producer) sends nothing while the talker is silent.
93	///
94	/// libopus decides what is silence, through its discontinuous transmission.
95	/// The bare [`Encoder`] returns its packets as they are, a no-transmit packet
96	/// for most silent frames; the producer declares the end of speech at the
97	/// first one, as a mute does, drops the rest of the silence, and opens a new
98	/// group when speech resumes.
99	Voice,
100	/// Music or mixed content, such as a screen share: Opus codes it as music.
101	Music,
102}
103
104/// PCM supplied to [`Producer::write`](super::Producer::write).
105#[derive(Clone, Debug)]
106#[non_exhaustive]
107pub struct Input {
108	/// How samples are packed in each buffer.
109	pub format: Format,
110	/// Samples per second per channel.
111	pub sample_rate: u32,
112	/// Speaker meaning and channel order.
113	pub layout: Layout,
114}
115
116impl Input {
117	/// Describe interleaved `f32` PCM at `sample_rate` in `layout`.
118	pub fn new(sample_rate: u32, layout: Layout) -> Self {
119		Self {
120			format: Format::F32,
121			sample_rate,
122			layout,
123		}
124	}
125}
126
127impl Default for Input {
128	fn default() -> Self {
129		Self::new(48_000, Layout::Stereo)
130	}
131}
132
133/// Audio codec config shared by [`Encoder`] and [`Producer`](super::Producer).
134#[derive(Clone, Debug)]
135#[non_exhaustive]
136pub struct Config {
137	/// Output codec. Defaults to [`Codec::Opus`].
138	pub codec: Codec,
139	/// Sample rate accepted by the codec.
140	pub sample_rate: u32,
141	/// Layout accepted by the codec.
142	///
143	/// AAC takes the layouts its channelConfiguration names: mono, stereo, 3.0,
144	/// 4.0, 5.0, 5.1, and 7.1.
145	pub layout: Layout,
146	/// Bitrate in bits per second. `None` lets the codec pick. PCM requires
147	/// `None` because its bitrate is fixed by the sample rate and channel count.
148	///
149	/// Rates too low for Opus to code anything at the chosen
150	/// [`frame_duration`](Self::frame_duration) are rejected. The floor is 1200
151	/// bps at the default 20 ms, rises for shorter frames, and is 2400 bps for
152	/// frames of 10 ms and longer.
153	pub bitrate: Option<moq_net::bandwidth::Rate>,
154	/// What the audio carries, or `None` when unknown, which leaves Opus at
155	/// libopus's defaults.
156	pub kind: Option<Kind>,
157	/// Encoded frame duration. Opus accepts 2.5 / 5 / 10 / 20 / 40 / 60 ms.
158	/// PCM accepts any duration containing a whole number of samples. AAC frames
159	/// are 1024 samples, so it accepts the duration that rounds to that at
160	/// [`sample_rate`](Self::sample_rate), which [`from_input`](Self::from_input)
161	/// fills in.
162	pub frame_duration: Duration,
163	/// Which encoder implementation to use.
164	pub backend: Backend,
165}
166
167impl Config {
168	/// Build default Opus config for `sample_rate` and `layout`, in 20 ms packets.
169	pub fn new(sample_rate: u32, layout: Layout) -> Self {
170		Self {
171			codec: Codec::default(),
172			sample_rate,
173			layout,
174			bitrate: None,
175			kind: None,
176			frame_duration: Duration::from_millis(20),
177			backend: Backend::Auto,
178		}
179	}
180
181	/// Derive concrete codec config from source PCM.
182	pub fn from_input(codec: Codec, input: &Input) -> Self {
183		let sample_rate = match codec {
184			Codec::Opus => opus::pick_rate(input.sample_rate),
185			Codec::Pcm | Codec::Aac => input.sample_rate,
186		};
187		let defaults = Self::new(sample_rate, input.layout);
188		let frame_duration = match codec {
189			Codec::Aac => aac_frame_duration(sample_rate),
190			Codec::Opus | Codec::Pcm => defaults.frame_duration,
191		};
192		Self {
193			codec,
194			frame_duration,
195			..defaults
196		}
197	}
198
199	/// Check the config against the codec, returning its frame size.
200	///
201	/// Codec rules live here rather than in a backend, so every backend of a
202	/// codec refuses the same config.
203	fn frame_size(&self) -> Result<usize, Error> {
204		let (rate, channels) = (self.sample_rate, self.layout.channels());
205
206		match self.codec {
207			Codec::Opus => {
208				opus::validate_rate(rate)?;
209				if !matches!(self.layout, Layout::Mono | Layout::Stereo) {
210					return Err(Error::Unsupported("opus requires a named mono or stereo layout".into()));
211				}
212				opus::frame_size(rate, self.frame_duration)
213			}
214			Codec::Pcm => {
215				if self.bitrate.is_some() {
216					return Err(Error::Unsupported(
217						"pcm bitrate is fixed; leave Config::bitrate unset".into(),
218					));
219				}
220				if rate == 0 {
221					return Err(Error::Unsupported("pcm sample rate must be greater than zero".into()));
222				}
223				let frame_size = pcm::frame_size(rate, self.frame_duration)?;
224				pcm::frame_bytes(frame_size, channels)?;
225				pcm::bitrate(rate, channels)?;
226				Ok(frame_size)
227			}
228			Codec::Aac => {
229				aac_config(self)?;
230				let frames = (self.frame_duration.as_nanos() * u128::from(rate) + 500_000_000) / 1_000_000_000;
231				if frames != AAC_FRAME_SIZE as u128 {
232					return Err(Error::Unsupported(format!(
233						"aac frames are {AAC_FRAME_SIZE} samples, {:?} at {rate} Hz (got {:?})",
234						aac_frame_duration(rate),
235						self.frame_duration
236					)));
237				}
238				Ok(AAC_FRAME_SIZE)
239			}
240		}
241	}
242}
243
244impl Default for Config {
245	fn default() -> Self {
246		Self::new(48_000, Layout::Stereo)
247	}
248}
249
250/// One AAC frame at `sample_rate`, to the nearest nanosecond.
251fn aac_frame_duration(sample_rate: u32) -> Duration {
252	if sample_rate == 0 {
253		return Duration::ZERO;
254	}
255	let rate = u64::from(sample_rate);
256	Duration::from_nanos((AAC_FRAME_SIZE as u64 * 1_000_000_000 + rate / 2) / rate)
257}
258
259/// The AudioSpecificConfig fields for AAC-LC at the config's rate and layout.
260///
261/// Only layouts with a channelConfiguration are accepted, since synthesizing
262/// one from a bare count would mislabel the rest: config 3 is 3.0 where the
263/// count's default layout is 2.1, and 6.1 has no config the encoder writes.
264/// 7.1 takes config 7, the one every decoder reads as eight channels.
265fn aac_config(config: &Config) -> Result<moq_mux::codec::aac::Config, Error> {
266	let layout = config.layout;
267	if !matches!(
268		layout,
269		Layout::Mono
270			| Layout::Stereo
271			| Layout::ThreePointZero
272			| Layout::FourPointZero
273			| Layout::FivePointZero
274			| Layout::FivePointOne
275			| Layout::SevenPointOne
276	) {
277		return Err(Error::Unsupported(format!(
278			"aac has no channelConfiguration for {layout:?}; use mono, stereo, 3.0, 4.0, 5.0, 5.1, or 7.1"
279		)));
280	}
281
282	let sample_rate = config.sample_rate;
283	if !(1..=AAC_MAX_SAMPLE_RATE).contains(&sample_rate) {
284		return Err(Error::Unsupported(format!(
285			"aac sample rate must be between 1 and {AAC_MAX_SAMPLE_RATE} Hz (got {sample_rate})"
286		)));
287	}
288
289	Ok(moq_mux::codec::aac::Config::new(AAC_LC, sample_rate, layout.channels()))
290}
291
292/// Audio encoder over codec-sized interleaved `f32` PCM.
293///
294/// Build one with [`Encoder::new`], feed full PCM frames via
295/// [`encode`](Self::encode), then pass the trailing partial frame to
296/// [`finish`](Self::finish). Publish every packet either call returns, in order,
297/// and apply the terminal [`Finish::discard_padding`] when the container
298/// supports it.
299///
300/// Every frame becomes exactly one packet, in order, though a codec that
301/// pipelines returns it from a later call, so the `n`th packet always starts
302/// `n` frames into the stream.
303pub struct Encoder {
304	backend: Box<dyn backend::Backend>,
305	config: Config,
306	frame_size: usize,
307	/// The catalog description, synthesized from the config at construction so
308	/// the rendition can be registered before the first packet exists.
309	description: Option<Bytes>,
310	/// Whether input has reached the codec, since a fresh encoder owes no drain.
311	started: bool,
312}
313
314/// Packets emitted by [`Encoder::finish`] and the decoded padding at their end.
315pub struct Finish {
316	packets: Vec<Encoded>,
317	discard_padding: usize,
318}
319
320impl Finish {
321	/// Encoded packets in decode order.
322	pub fn packets(&self) -> &[Encoded] {
323		&self.packets
324	}
325
326	/// Decoded frames per channel to discard from the end of the final packet.
327	pub fn discard_padding(&self) -> usize {
328		self.discard_padding
329	}
330
331	/// Consume the result and return its encoded packets.
332	pub fn into_packets(self) -> Vec<Encoded> {
333		self.packets
334	}
335}
336
337impl Encoder {
338	/// Open an encoder for `config`, refusing a codec no backend on this host
339	/// encodes.
340	pub fn new(config: &Config) -> Result<Self, Error> {
341		let frame_size = config.frame_size()?;
342		let backend = backend::open(config)?;
343
344		let description = match config.codec {
345			Codec::Opus => {
346				// OpusHead carries the lookahead in the 48 kHz timebase.
347				let lookahead = backend.delay() as u64;
348				let pre_skip = u16::try_from((lookahead * 48_000) / u64::from(config.sample_rate))
349					.map_err(|_| Error::Unsupported(format!("Opus lookahead {lookahead} does not fit in OpusHead")))?;
350				let head = moq_mux::codec::opus::Config::new(config.sample_rate, config.layout.channels())
351					.with_pre_skip(pre_skip)
352					.encode()
353					.map_err(moq_mux::Error::from)?;
354				Some(head)
355			}
356			Codec::Aac => Some(aac_config(config)?.encode().map_err(moq_mux::Error::from)?),
357			Codec::Pcm => None,
358		};
359
360		Ok(Self {
361			backend,
362			config: config.clone(),
363			frame_size,
364			description,
365			started: false,
366		})
367	}
368
369	/// The encoder backend name in use, e.g. `"libopus"`.
370	pub fn name(&self) -> &str {
371		self.backend.name()
372	}
373
374	/// The encoder config, including the latest accepted runtime bitrate.
375	pub fn config(&self) -> &Config {
376		&self.config
377	}
378
379	/// The codec this encoder emits. A [`Producer`](super::Producer) must be
380	/// built for the same codec to publish its packets.
381	pub fn codec(&self) -> Codec {
382		self.config.codec
383	}
384
385	/// Sample rate the codec actually runs at, which is
386	/// [`Config::sample_rate`].
387	pub fn codec_rate(&self) -> u32 {
388		self.config.sample_rate
389	}
390
391	/// Channel count the codec actually runs at, which is
392	/// [`Config::layout`]'s channel count.
393	pub fn codec_channels(&self) -> u32 {
394		self.config.layout.channels()
395	}
396
397	/// Number of samples per channel the codec consumes per call to
398	/// [`encode`](Self::encode).
399	pub fn frame_size(&self) -> usize {
400		self.frame_size
401	}
402
403	/// Current target bitrate.
404	pub fn bitrate(&self) -> moq_net::bandwidth::Rate {
405		moq_net::bandwidth::Rate::from_bps(self.backend.bitrate())
406	}
407
408	/// Retune the live encoder to `bitrate`.
409	///
410	/// # Errors
411	///
412	/// Returns [`Error::Unsupported`] when the codec's rate is fixed (PCM) or the
413	/// backend can't change it mid-stream. The encoder keeps running at its
414	/// opening rate, so a caller driving a control loop should stop adapting
415	/// rather than stop encoding.
416	pub fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
417		let previous = self.backend.bitrate();
418		self.backend.set_bitrate(bitrate.as_bps())?;
419		if bitrate.as_bps() != previous {
420			self.config.bitrate = Some(bitrate);
421		}
422		Ok(())
423	}
424
425	/// Drop all codec history, held packets included, so a later epoch cannot
426	/// emit audio from this one.
427	pub(super) fn reset(&mut self) {
428		self.backend.reset();
429		self.started = false;
430	}
431
432	/// Whether this epoch has submitted audio to the codec.
433	pub(super) fn started(&self) -> bool {
434		self.started
435	}
436
437	/// Codec priming the catalog can't signal, in codec-rate frames, which the
438	/// producer folds into its timestamps instead.
439	///
440	/// Opus declares its lookahead as OpusHead pre-skip, which the decoder trims,
441	/// so nothing is folded. An AudioSpecificConfig has no such field, so each
442	/// AAC packet is stamped that much earlier and the priming lands before the
443	/// first input sample rather than delaying it.
444	pub(super) fn folded_delay(&self) -> usize {
445		match self.config.codec {
446			Codec::Aac => self.backend.delay(),
447			Codec::Opus | Codec::Pcm => 0,
448		}
449	}
450
451	/// Submit one frame of interleaved `f32` PCM at [`codec_rate`](Self::codec_rate),
452	/// whose packet [`receive`](Self::receive) returns.
453	///
454	/// A codec that pipelines holds the packet past later frames; libopus and
455	/// PCM ready it at once.
456	///
457	/// `pcm.len()` must equal `frame_size() * codec_channels()`. The
458	/// [`Producer`](super::Producer) handles format conversion and resampling
459	/// before calling this; for direct use, the caller does the same.
460	pub fn encode(&mut self, pcm: &[f32]) -> Result<(), Error> {
461		let expected = self.frame_size * self.codec_channels() as usize;
462		if pcm.len() != expected {
463			return Err(Error::Misaligned {
464				got: std::mem::size_of_val(pcm),
465				expected: expected * std::mem::size_of::<f32>(),
466			});
467		}
468		self.backend.encode(pcm)?;
469		self.started = true;
470		Ok(())
471	}
472
473	/// Pop the oldest ready packet, or `None` while the codec holds the rest.
474	///
475	/// Call until `None` after each [`encode`](Self::encode) or [`flush`](Self::flush).
476	pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
477		self.backend.receive()
478	}
479
480	/// Mark the end of input, so [`receive`](Self::receive) returns every packet
481	/// the codec still holds. Frames encoded afterwards start new input.
482	///
483	/// Pads nothing, so the codec's lookahead stays inside it: reach for this at a
484	/// boundary the packets have to respect, and for [`finish`](Self::finish) at
485	/// the end of the stream.
486	pub fn flush(&mut self) -> Result<(), Error> {
487		self.backend.flush()
488	}
489
490	/// Finish encoding, zero-padding `pcm` as the final partial frame and
491	/// returning every packet needed to drain codec lookahead.
492	///
493	/// `pcm` is interleaved at [`codec_rate`](Self::codec_rate), may be empty,
494	/// and must contain at most one frame. The packets start with any not yet
495	/// [received](Self::receive) from earlier [`encode`](Self::encode) calls. Silence added here only drains
496	/// audio already supplied; [`Finish::discard_padding`] reports how much of
497	/// the decoded tail is artificial and must not count as source duration.
498	/// Consuming the encoder prevents encoding across the artificial terminal
499	/// padding.
500	pub fn finish(mut self, pcm: &[f32]) -> Result<Finish, Error> {
501		self.drain(pcm)
502	}
503
504	/// Same drain as [`finish`](Self::finish), without consuming the encoder.
505	pub(super) fn drain(&mut self, pcm: &[f32]) -> Result<Finish, Error> {
506		let channels = self.codec_channels() as usize;
507		let frame_samples = self.frame_size * channels;
508		if pcm.len() > frame_samples || !pcm.len().is_multiple_of(channels) {
509			return Err(Error::Misaligned {
510				got: std::mem::size_of_val(pcm),
511				expected: if pcm.len() > frame_samples {
512					frame_samples * std::mem::size_of::<f32>()
513				} else {
514					pcm.len().next_multiple_of(channels) * std::mem::size_of::<f32>()
515				},
516			});
517		}
518
519		let source_frames = pcm.len() / channels;
520		// Any packets not yet received from earlier calls come first.
521		let mut packets = Vec::new();
522		self.receive_into(&mut packets)?;
523		let padding = if pcm.is_empty() {
524			0
525		} else {
526			let mut frame = Vec::with_capacity(frame_samples);
527			frame.extend_from_slice(pcm);
528			frame.resize(frame_samples, 0.0);
529			let padding = (frame_samples - pcm.len()) / channels;
530			self.encode(&frame)?;
531			self.receive_into(&mut packets)?;
532			padding
533		};
534
535		if !self.started {
536			return Ok(Finish {
537				packets,
538				discard_padding: 0,
539			});
540		}
541
542		let lookahead = self.backend.delay();
543		let drain = lookahead.saturating_sub(padding);
544		let silence = vec![0.0; frame_samples];
545		let silent_frames = drain.div_ceil(self.frame_size);
546		for _ in 0..silent_frames {
547			self.encode(&silence)?;
548			self.receive_into(&mut packets)?;
549		}
550		self.backend.flush()?;
551		self.receive_into(&mut packets)?;
552
553		// Counted in frames submitted here rather than packets returned, which
554		// include any not yet received from earlier calls.
555		let drained = usize::from(!pcm.is_empty()) + silent_frames;
556		let discard_padding = drained
557			.saturating_mul(self.frame_size)
558			.saturating_sub(lookahead)
559			.saturating_sub(source_frames);
560
561		Ok(Finish {
562			packets,
563			discard_padding,
564		})
565	}
566
567	/// Append every packet ready now, oldest first.
568	fn receive_into(&mut self, packets: &mut Vec<Encoded>) -> Result<(), Error> {
569		while let Some(packet) = self.receive()? {
570			packets.push(packet);
571		}
572		Ok(())
573	}
574
575	/// Submit `pcm` and take every packet it readied.
576	#[cfg(test)]
577	pub(crate) fn encode_all(&mut self, pcm: &[f32]) -> Result<Vec<Encoded>, Error> {
578		self.encode(pcm)?;
579		let mut packets = Vec::new();
580		self.receive_into(&mut packets)?;
581		Ok(packets)
582	}
583
584	/// Flush and take every packet the codec held.
585	#[cfg(test)]
586	pub(crate) fn flush_all(&mut self) -> Result<Vec<Encoded>, Error> {
587		self.flush()?;
588		let mut packets = Vec::new();
589		self.receive_into(&mut packets)?;
590		Ok(packets)
591	}
592
593	/// hang catalog entry describing this encoder's output stream.
594	pub fn catalog(&self) -> hang::catalog::AudioConfig {
595		let (rate, channels) = (self.codec_rate(), self.codec_channels());
596		let codec: hang::catalog::AudioCodec = match self.config.codec {
597			Codec::Opus => hang::catalog::AudioCodec::Opus,
598			Codec::Pcm => hang::catalog::AudioCodec::Pcm,
599			Codec::Aac => hang::catalog::AAC { profile: AAC_LC }.into(),
600		};
601
602		let mut config = hang::catalog::AudioConfig::new(codec, rate, channels);
603		// The target the encoder opened at, even one it chose itself, so the catalog never waits on
604		// measuring it.
605		config.bitrate = match self.config.codec {
606			Codec::Pcm => Some(pcm::bitrate(rate, channels).expect("pcm encoder bitrate validated at construction")),
607			Codec::Opus | Codec::Aac => Some(self.bitrate().as_bps()).filter(|bps| *bps > 0),
608		};
609		config.description = self.description.clone();
610		config.container = hang::catalog::Container::Legacy;
611		// An Opus or PCM packet goes out as soon as its frame's last sample is in, stamped at its
612		// first, so it trails by its own duration and nothing else; the player adds that frame, and
613		// the catalog `delay` is a known zero. AAC folds its priming into the timestamps and a platform
614		// encoder may hold frames, so it is measured.
615		config.delay = match self.config.codec {
616			Codec::Opus | Codec::Pcm => Some(std::time::Duration::ZERO),
617			Codec::Aac => None,
618		};
619		if matches!(self.config.codec, Codec::Opus) {
620			config.warmup = Some(moq_mux::codec::opus::WARMUP);
621		}
622		config
623	}
624}
625
626#[cfg(test)]
627mod tests {
628	use super::*;
629	use crate::decode::{Config as DecodeConfig, Decoder};
630
631	fn sine(freq: f32, sample_rate: u32, channels: u32, frames: usize) -> Vec<f32> {
632		let mut out = Vec::with_capacity(frames * channels as usize);
633		for i in 0..frames {
634			let t = i as f32 / sample_rate as f32;
635			let v = (2.0 * std::f32::consts::PI * freq * t).sin() * 0.5;
636			for _ in 0..channels {
637				out.push(v);
638			}
639		}
640		out
641	}
642
643	/// The published `Encoder` was unwind safe before it boxed a backend; keep it so.
644	#[test]
645	fn encoder_is_unwind_safe() {
646		fn assert_unwind_safe<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
647		assert_unwind_safe::<Encoder>();
648	}
649
650	#[test]
651	fn opus_encode_then_decode_keeps_signal_close() {
652		let mut enc = Encoder::new(&Config {
653			bitrate: Some(moq_net::bandwidth::Rate::from_bps(96_000)),
654			..Config::default()
655		})
656		.unwrap();
657
658		let cfg = enc.catalog();
659		let mut dec = Decoder::new(&cfg, &DecodeConfig::default()).unwrap();
660
661		let frame = sine(440.0, 48_000, 2, enc.frame_size());
662		for _ in 0..5 {
663			let pkt = crate::single(enc.encode_all(&frame).unwrap());
664			let _ = crate::single(dec.decode_all(&pkt.payload).unwrap());
665		}
666
667		let pkt = crate::single(enc.encode_all(&frame).unwrap());
668		let decoded = crate::single(dec.decode_all(&pkt.payload).unwrap());
669		assert_eq!(decoded.samples.len(), frame.len());
670
671		let energy_in: f32 = frame.iter().map(|s| s * s).sum();
672		let energy_out: f32 = decoded.samples.iter().map(|s| s * s).sum();
673		let ratio = energy_out / energy_in;
674		assert!(
675			(0.5..2.0).contains(&ratio),
676			"output energy ratio {ratio:.3} should be close to 1"
677		);
678	}
679
680	#[test]
681	fn opus_rejects_unsupported_frame_duration() {
682		let err = Encoder::new(&Config {
683			frame_duration: Duration::from_millis(15),
684			..Config::default()
685		});
686		assert!(matches!(err, Err(Error::Unsupported(_))));
687	}
688
689	/// The frame duration has to reach the codec as its packet duration, read
690	/// back off the packet's TOC rather than our own config.
691	#[test]
692	fn frame_duration_reaches_the_packet() {
693		for (millis, samples) in [(10, 480), (20, 960)] {
694			let config = Config {
695				layout: Layout::Mono,
696				frame_duration: Duration::from_millis(millis),
697				..Config::default()
698			};
699			let mut enc = Encoder::new(&config).unwrap();
700			assert_eq!(enc.frame_size(), samples);
701
702			let packet = crate::single(enc.encode_all(&vec![0.0f32; samples]).unwrap());
703			let coded = kopus::packet::samples_per_frame(&packet.payload, 48_000);
704			assert_eq!(coded, Some(samples), "{millis} ms packet");
705		}
706	}
707
708	#[test]
709	fn opus_rejects_misaligned_input() {
710		let mut enc = Encoder::new(&Config::default()).unwrap();
711		assert!(matches!(enc.encode(&[0.0f32; 100]), Err(Error::Misaligned { .. })));
712	}
713
714	#[test]
715	fn opus_catalog_includes_opushead() {
716		let enc = Encoder::new(&Config {
717			bitrate: Some(moq_net::bandwidth::Rate::from_bps(64_000)),
718			..Config::default()
719		})
720		.unwrap();
721		let cfg = enc.catalog();
722		assert_eq!(cfg.sample_rate, 48_000);
723		assert_eq!(cfg.channel_count, 2);
724		assert_eq!(cfg.bitrate, Some(64_000));
725		let desc = cfg.description.expect("OpusHead should be present");
726		assert_eq!(desc.len(), 19);
727		let head = moq_mux::codec::opus::Config::parse(&mut desc.as_ref()).unwrap();
728		assert_eq!(head.pre_skip, 312);
729		assert_eq!(cfg.warmup, Some(Duration::from_millis(80)));
730	}
731
732	#[test]
733	fn opus_decoder_trims_encoder_lookahead_once() {
734		let mut enc = Encoder::new(&Config::default()).unwrap();
735		let mut dec = Decoder::new(&enc.catalog(), &DecodeConfig::default()).unwrap();
736		let frame = vec![0.0; enc.frame_size() * enc.codec_channels() as usize];
737
738		let first = crate::single(
739			dec.decode_all(&crate::single(enc.encode_all(&frame).unwrap()).payload)
740				.unwrap(),
741		);
742		assert_eq!(
743			first.samples.len(),
744			(enc.frame_size() - enc.backend.delay()) * enc.codec_channels() as usize
745		);
746
747		let second = crate::single(
748			dec.decode_all(&crate::single(enc.encode_all(&frame).unwrap()).payload)
749				.unwrap(),
750		);
751		assert_eq!(second.samples.len(), frame.len());
752	}
753
754	#[test]
755	fn opus_finish_accounts_for_partial_frame_padding() {
756		let enc = Encoder::new(&Config::new(48_000, Layout::Mono)).unwrap();
757
758		// The 360 frames of terminal padding exceed the 312-frame lookahead,
759		// so the partial packet itself completes the drain.
760		let packets = enc.finish(&vec![0.0; 600]).unwrap();
761		assert_eq!(packets.packets().len(), 1);
762		assert_eq!(packets.discard_padding(), 48);
763	}
764
765	#[test]
766	fn opus_finish_drains_lookahead_across_multiple_short_packets() {
767		let mut enc = Encoder::new(&Config {
768			frame_duration: Duration::from_micros(2_500),
769			..Config::new(48_000, Layout::Mono)
770		})
771		.unwrap();
772		let frame = vec![0.0; enc.frame_size()];
773		crate::single(enc.encode_all(&frame).unwrap());
774
775		// Three 120-frame packets are required to push out 312 frames.
776		let packets = enc.finish(&[]).unwrap();
777		assert_eq!(packets.packets().len(), 3);
778		assert_eq!(packets.discard_padding(), 48);
779	}
780
781	#[test]
782	fn reset_drops_pending_opus_lookahead() {
783		let mut enc = Encoder::new(&Config::new(48_000, Layout::Mono)).unwrap();
784		let mut old = vec![0.0; enc.frame_size()];
785		old[enc.frame_size() - 1] = 1.0;
786		crate::single(enc.encode_all(&old).unwrap());
787
788		enc.reset();
789		let next = vec![0.0; enc.frame_size()];
790		let actual = crate::single(enc.encode_all(&next).unwrap());
791		let mut decoder = Decoder::new(&enc.catalog(), &DecodeConfig::default()).unwrap();
792		let decoded = crate::single(decoder.decode_all(&actual.payload).unwrap());
793		let peak = decoded
794			.samples
795			.iter()
796			.fold(0.0f32, |peak, sample| peak.max(sample.abs()));
797		assert!(peak < 0.001, "pre-reset impulse leaked into the next epoch: {peak}");
798
799		enc.reset();
800		let finish = enc.finish(&[]).unwrap();
801		assert!(finish.packets().is_empty());
802		assert_eq!(finish.discard_padding(), 0);
803	}
804
805	#[test]
806	fn opus_runtime_bitrate_updates_encoder_state() {
807		let mut enc = Encoder::new(&Config {
808			bitrate: Some(moq_net::bandwidth::Rate::from_bps(64_000)),
809			..Config::default()
810		})
811		.unwrap();
812
813		enc.set_bitrate(moq_net::bandwidth::Rate::from_bps(32_000)).unwrap();
814		assert_eq!(enc.bitrate(), moq_net::bandwidth::Rate::from_bps(32_000));
815		assert_eq!(enc.config().bitrate, Some(moq_net::bandwidth::Rate::from_bps(32_000)));
816	}
817
818	#[test]
819	fn opus_runtime_bitrate_rejects_values_libopus_would_clamp() {
820		let mut enc = Encoder::new(&Config::default()).unwrap();
821		let original = enc.bitrate();
822		assert!(enc.set_bitrate(moq_net::bandwidth::Rate::from_bps(1)).is_err());
823		assert!(enc.set_bitrate(moq_net::bandwidth::Rate::from_bps(600_001)).is_err());
824		assert_eq!(enc.bitrate(), original);
825	}
826
827	#[test]
828	fn settings_fix_the_codec_rate() {
829		let enc = Encoder::new(&Config::new(24_000, Layout::Mono)).unwrap();
830		assert_eq!(enc.codec_rate(), 24_000);
831		let catalog = enc.catalog();
832		assert_eq!(catalog.sample_rate, 24_000);
833		let head = moq_mux::codec::opus::Config::parse(&mut catalog.description.unwrap().as_ref()).unwrap();
834		assert_eq!(head.pre_skip, 312);
835	}
836
837	#[test]
838	fn pcm_roundtrip_is_lossless() {
839		let mut enc = Encoder::new(&Config {
840			codec: Codec::Pcm,
841			..Config::default()
842		})
843		.unwrap();
844		let mut dec = Decoder::new(&enc.catalog(), &DecodeConfig::default()).unwrap();
845		let input = sine(440.0, enc.codec_rate(), enc.codec_channels(), enc.frame_size());
846
847		let packet = crate::single(enc.encode_all(&input).unwrap());
848		let output = crate::single(dec.decode_all(&packet.payload).unwrap());
849
850		assert_eq!(output.samples, input);
851	}
852
853	/// A PCM catalog names only a count, and 3 or 4 channels decode as 2.1 or
854	/// quad, so 3.0 and 4.0 are refused; discrete channels still pass through.
855	#[test]
856	fn pcm_refuses_layouts_its_count_cannot_name() {
857		for layout in [Layout::ThreePointZero, Layout::FourPointZero] {
858			let err = Encoder::new(&Config {
859				codec: Codec::Pcm,
860				..Config::new(48_000, layout)
861			});
862			assert!(matches!(err, Err(Error::Unsupported(_))), "{layout:?}");
863		}
864
865		for layout in [
866			Layout::TwoPointOne,
867			Layout::Quad,
868			Layout::Discrete(3.try_into().unwrap()),
869		] {
870			let mut enc = Encoder::new(&Config {
871				codec: Codec::Pcm,
872				..Config::new(48_000, layout)
873			})
874			.unwrap();
875			let mut dec = Decoder::new(&enc.catalog(), &DecodeConfig::default()).unwrap();
876			let input = sine(440.0, enc.codec_rate(), enc.codec_channels(), enc.frame_size());
877			let output = crate::single(
878				dec.decode_all(&crate::single(enc.encode_all(&input).unwrap()).payload)
879					.unwrap(),
880			);
881			assert_eq!(output.samples, input, "{layout:?}");
882		}
883	}
884
885	#[test]
886	fn pcm_catalog_declares_fixed_bitrate() {
887		let enc = Encoder::new(&Config {
888			codec: Codec::Pcm,
889			..Config::default()
890		})
891		.unwrap();
892		let catalog = enc.catalog();
893
894		assert_eq!(catalog.codec, hang::catalog::AudioCodec::Pcm);
895		assert_eq!(catalog.bitrate, Some(48_000 * 2 * 32));
896		assert_eq!(catalog.description, None);
897	}
898
899	#[test]
900	fn pcm_rejects_runtime_bitrate_change() {
901		let mut enc = Encoder::new(&Config {
902			codec: Codec::Pcm,
903			..Config::default()
904		})
905		.unwrap();
906		let bitrate = enc.bitrate();
907
908		assert!(matches!(enc.set_bitrate(bitrate), Err(Error::Unsupported(_))));
909		assert_eq!(enc.bitrate(), bitrate);
910	}
911
912	#[test]
913	fn pcm_rejects_fractional_sample_frame_duration() {
914		let err = Encoder::new(&Config {
915			codec: Codec::Pcm,
916			frame_duration: Duration::from_micros(2_500),
917			..Config::new(44_100, Layout::Stereo)
918		});
919		assert!(matches!(err, Err(Error::Unsupported(_))));
920	}
921
922	#[test]
923	fn pcm_rejects_bitrate_overflow() {
924		let err = Encoder::new(&Config {
925			codec: Codec::Pcm,
926			frame_duration: Duration::from_secs(1),
927			..Config::new(u32::MAX, Layout::Discrete(std::num::NonZeroU32::MAX))
928		});
929		assert!(matches!(err, Err(Error::Unsupported(_))));
930	}
931
932	/// The catalog carries only a count, so a discrete layout comes back as the
933	/// count's default one, with the samples untouched.
934	#[test]
935	fn pcm_passes_discrete_multichannel_samples_through() {
936		let config = Config {
937			codec: Codec::Pcm,
938			..Config::new(48_000, Layout::Discrete(3.try_into().unwrap()))
939		};
940		let mut encoder = Encoder::new(&config).unwrap();
941		let catalog = encoder.catalog();
942		let mut decoder = Decoder::new(&catalog, &DecodeConfig::default()).unwrap();
943		let input = [0.1, 0.2, 0.3].repeat(encoder.frame_size());
944		let output = crate::single(
945			decoder
946				.decode_all(&crate::single(encoder.encode_all(&input).unwrap()).payload)
947				.unwrap(),
948		);
949
950		assert_eq!(decoder.layout(), Layout::TwoPointOne);
951		assert_eq!(output.samples, input);
952	}
953
954	#[test]
955	fn opus_refuses_discrete_layout() {
956		let config = Config::new(48_000, Layout::Discrete(2.try_into().unwrap()));
957		assert!(matches!(Encoder::new(&config), Err(Error::Unsupported(_))));
958	}
959
960	fn aac(layout: Layout) -> Config {
961		Config::from_input(Codec::Aac, &Input::new(48_000, layout))
962	}
963
964	/// Open `config` on the test stub, since this host has no AAC encoder.
965	fn stub(config: &Config) -> Result<Encoder, Error> {
966		let _stub = backend::stub::install();
967		Encoder::new(config)
968	}
969
970	/// Without the stub, the public constructor sees the real tiers and refuses.
971	#[test]
972	fn aac_is_refused_without_an_encoder() {
973		let err = Encoder::new(&aac(Layout::Stereo))
974			.err()
975			.expect("no AAC encoder on this host");
976		assert!(matches!(err, Error::Unsupported(_)), "{err}");
977	}
978
979	/// The ASC is synthesized from the config, so it exists before any packet.
980	#[test]
981	fn aac_catalog_carries_the_synthesized_asc() {
982		let enc = stub(&aac(Layout::Stereo)).unwrap();
983		assert_eq!(enc.name(), backend::stub::NAME);
984		assert_eq!(enc.frame_size(), 1024);
985
986		let catalog = enc.catalog();
987		assert_eq!(catalog.codec, hang::catalog::AAC { profile: 2 }.into());
988		assert_eq!(catalog.codec.to_string(), "mp4a.40.2");
989		assert_eq!(catalog.sample_rate, 48_000);
990		assert_eq!(catalog.channel_count, 2);
991		assert_eq!(catalog.container, hang::catalog::Container::Legacy);
992		// AAC-LC (2), 48 kHz (index 3), stereo (config 2).
993		assert_eq!(catalog.description.as_deref(), Some(&[0x11, 0x90][..]));
994	}
995
996	#[test]
997	fn aac_takes_the_layouts_with_a_channel_configuration() {
998		for (layout, config) in [
999			(Layout::Mono, 1),
1000			(Layout::Stereo, 2),
1001			(Layout::ThreePointZero, 3),
1002			(Layout::FourPointZero, 4),
1003			(Layout::FivePointZero, 5),
1004			(Layout::FivePointOne, 6),
1005			(Layout::SevenPointOne, 7),
1006		] {
1007			let catalog = stub(&aac(layout)).unwrap().catalog();
1008			let description = catalog.description.unwrap();
1009			assert_eq!(description[1] >> 3 & 0xF, config, "{layout:?}");
1010			assert_eq!(catalog.channel_count, layout.channels(), "{layout:?}");
1011		}
1012
1013		for layout in [
1014			Layout::TwoPointOne,
1015			Layout::Quad,
1016			Layout::SixPointOne,
1017			Layout::Discrete(2.try_into().unwrap()),
1018		] {
1019			let result = stub(&aac(layout));
1020			let detail = result.as_ref().err().map(ToString::to_string);
1021			assert!(
1022				matches!(result, Err(Error::Unsupported(msg)) if msg.contains("no channelConfiguration")),
1023				"{layout:?}: {detail:?}"
1024			);
1025		}
1026	}
1027
1028	/// AAC frames are 1024 samples however the duration is spelled.
1029	#[test]
1030	fn aac_frame_duration_is_the_codecs() {
1031		assert_eq!(aac(Layout::Stereo).frame_duration, Duration::from_nanos(21_333_333));
1032		let config = Config {
1033			frame_duration: Duration::from_micros(21_333),
1034			..aac(Layout::Stereo)
1035		};
1036		assert_eq!(stub(&config).unwrap().frame_size(), 1024);
1037
1038		let config = Config {
1039			frame_duration: Duration::from_millis(20),
1040			..aac(Layout::Stereo)
1041		};
1042		let err = stub(&config).err().expect("20 ms is 960 samples");
1043		assert!(err.to_string().contains("1024"), "{err}");
1044	}
1045
1046	/// A backend that can't retune keeps its opening rate.
1047	#[test]
1048	fn fixed_rate_backend_keeps_its_opening_rate() {
1049		let mut enc = stub(&Config {
1050			bitrate: Some(moq_net::bandwidth::Rate::from_bps(96_000)),
1051			..aac(Layout::Stereo)
1052		})
1053		.unwrap();
1054
1055		let err = enc.set_bitrate(moq_net::bandwidth::Rate::from_bps(64_000));
1056		assert!(matches!(err, Err(Error::Unsupported(_))));
1057		assert_eq!(enc.bitrate(), moq_net::bandwidth::Rate::from_bps(96_000));
1058		assert_eq!(enc.config().bitrate, Some(moq_net::bandwidth::Rate::from_bps(96_000)));
1059		assert_eq!(enc.catalog().bitrate, Some(96_000));
1060	}
1061
1062	/// An encoder left to pick its own rate still declares it, so the catalog never measures it.
1063	#[test]
1064	fn a_default_rate_is_declared() {
1065		let enc = stub(&aac(Layout::Stereo)).unwrap();
1066		assert_eq!(enc.config().bitrate, None);
1067		assert_eq!(enc.catalog().bitrate, Some(128_000));
1068	}
1069
1070	/// A codec whose packets trail by their own duration alone states a zero delay; AAC, whose
1071	/// encoder may hold frames, leaves it to measurement.
1072	#[test]
1073	fn delay_is_stated_where_the_codec_fixes_it() {
1074		assert_eq!(stub(&aac(Layout::Stereo)).unwrap().catalog().delay, None);
1075		for codec in [Codec::Opus, Codec::Pcm] {
1076			let enc = Encoder::new(&Config::from_input(codec, &Input::new(48_000, Layout::Stereo))).unwrap();
1077			assert_eq!(enc.catalog().delay, Some(std::time::Duration::ZERO), "{codec:?}");
1078		}
1079	}
1080
1081	/// The drain pushes the encoder delay out through whole silent frames, after
1082	/// the packet the codec was still holding.
1083	#[test]
1084	fn aac_finish_drains_the_encoder_delay() {
1085		let mut enc = stub(&aac(Layout::Mono)).unwrap();
1086		assert_eq!(enc.folded_delay(), backend::stub::DELAY);
1087		assert!(
1088			enc.encode_all(&[0.0; 1024]).unwrap().is_empty(),
1089			"the stub holds its first frame"
1090		);
1091
1092		// 2112 frames of delay take three 1024-frame packets.
1093		let finish = enc.finish(&[]).unwrap();
1094		assert_eq!(indices(finish.packets()), [0, 1, 2, 3]);
1095		assert_eq!(finish.discard_padding(), 3 * 1024 - backend::stub::DELAY);
1096	}
1097
1098	/// The stub's frame index in each packet.
1099	fn indices(packets: &[Encoded]) -> Vec<u64> {
1100		packets
1101			.iter()
1102			.map(|packet| u64::from_be_bytes(packet.payload[..].try_into().unwrap()))
1103			.collect()
1104	}
1105
1106	/// A codec that holds frames returns none, then several, and `flush` hands
1107	/// back the rest without padding anything, leaving the encoder usable.
1108	#[test]
1109	fn held_packets_come_back_in_order() {
1110		let mut enc = stub(&aac(Layout::Mono)).unwrap();
1111		let frame = [0.0; 1024];
1112		assert!(enc.encode_all(&frame).unwrap().is_empty());
1113		assert_eq!(indices(&enc.encode_all(&frame).unwrap()), [0, 1]);
1114		assert!(enc.encode_all(&frame).unwrap().is_empty());
1115		assert_eq!(indices(&enc.flush_all().unwrap()), [2]);
1116		assert!(enc.flush_all().unwrap().is_empty());
1117
1118		assert!(enc.encode_all(&frame).unwrap().is_empty());
1119		assert_eq!(indices(&enc.encode_all(&frame).unwrap()), [3, 4]);
1120	}
1121
1122	/// A held packet belongs to the epoch that submitted it, so a reset drops it.
1123	#[test]
1124	fn reset_drops_held_packets() {
1125		let mut enc = stub(&aac(Layout::Mono)).unwrap();
1126		assert!(enc.encode_all(&[0.0; 1024]).unwrap().is_empty());
1127		enc.reset();
1128		assert!(enc.flush_all().unwrap().is_empty());
1129	}
1130
1131	/// The padding counts the frames the drain submitted, not the held packets it
1132	/// also returns, so a partial tail's padding is the same however much was held.
1133	#[test]
1134	fn finish_padding_ignores_held_packets() {
1135		let mut enc = stub(&aac(Layout::Mono)).unwrap();
1136		assert!(enc.encode_all(&[0.0; 1024]).unwrap().is_empty());
1137
1138		// 100 source frames pad 924; the remaining 1188 frames of delay take two more.
1139		let finish = enc.finish(&[0.0; 100]).unwrap();
1140		assert_eq!(indices(finish.packets()), [0, 1, 2, 3]);
1141		assert_eq!(finish.discard_padding(), 3 * 1024 - backend::stub::DELAY - 100);
1142	}
1143}