1use 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
18const AAC_FRAME_SIZE: usize = 1024;
20
21const AAC_LC: u8 = 2;
23
24const AAC_MAX_SAMPLE_RATE: u32 = 0xFF_FFFF;
27
28#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
31#[non_exhaustive]
32pub enum Codec {
33 #[default]
35 Opus,
36 Pcm,
38 Aac,
41}
42
43impl Codec {
44 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum Backend {
78 #[default]
80 Auto,
81 Software,
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum Kind {
91 Voice,
100 Music,
102}
103
104#[derive(Clone, Debug)]
106#[non_exhaustive]
107pub struct Input {
108 pub format: Format,
110 pub sample_rate: u32,
112 pub layout: Layout,
114}
115
116impl Input {
117 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#[derive(Clone, Debug)]
135#[non_exhaustive]
136pub struct Config {
137 pub codec: Codec,
139 pub sample_rate: u32,
141 pub layout: Layout,
146 pub bitrate: Option<moq_net::bandwidth::Rate>,
154 pub kind: Option<Kind>,
157 pub frame_duration: Duration,
163 pub backend: Backend,
165}
166
167impl Config {
168 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 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 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
250fn 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
259fn 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
292pub struct Encoder {
304 backend: Box<dyn backend::Backend>,
305 config: Config,
306 frame_size: usize,
307 description: Option<Bytes>,
310 started: bool,
312}
313
314pub struct Finish {
316 packets: Vec<Encoded>,
317 discard_padding: usize,
318}
319
320impl Finish {
321 pub fn packets(&self) -> &[Encoded] {
323 &self.packets
324 }
325
326 pub fn discard_padding(&self) -> usize {
328 self.discard_padding
329 }
330
331 pub fn into_packets(self) -> Vec<Encoded> {
333 self.packets
334 }
335}
336
337impl Encoder {
338 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 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 pub fn name(&self) -> &str {
371 self.backend.name()
372 }
373
374 pub fn config(&self) -> &Config {
376 &self.config
377 }
378
379 pub fn codec(&self) -> Codec {
382 self.config.codec
383 }
384
385 pub fn codec_rate(&self) -> u32 {
388 self.config.sample_rate
389 }
390
391 pub fn codec_channels(&self) -> u32 {
394 self.config.layout.channels()
395 }
396
397 pub fn frame_size(&self) -> usize {
400 self.frame_size
401 }
402
403 pub fn bitrate(&self) -> moq_net::bandwidth::Rate {
405 moq_net::bandwidth::Rate::from_bps(self.backend.bitrate())
406 }
407
408 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 pub(super) fn reset(&mut self) {
428 self.backend.reset();
429 self.started = false;
430 }
431
432 pub(super) fn started(&self) -> bool {
434 self.started
435 }
436
437 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 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 pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
477 self.backend.receive()
478 }
479
480 pub fn flush(&mut self) -> Result<(), Error> {
487 self.backend.flush()
488 }
489
490 pub fn finish(mut self, pcm: &[f32]) -> Result<Finish, Error> {
501 self.drain(pcm)
502 }
503
504 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 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 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 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 #[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 #[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 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 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 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 #[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 #[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 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 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 #[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 #[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 fn stub(config: &Config) -> Result<Encoder, Error> {
966 let _stub = backend::stub::install();
967 Encoder::new(config)
968 }
969
970 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 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}