use std::fmt;
pub(crate) const RATE: u32 = 48_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum OpusMode {
Silk,
Hybrid,
Celt,
}
impl OpusMode {
pub fn is_voice(self) -> bool {
match self {
Self::Silk | Self::Hybrid => true,
Self::Celt => false,
}
}
}
impl fmt::Display for OpusMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Silk => "SILK",
Self::Hybrid => "hybrid",
Self::Celt => "CELT",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum OpusBandwidth {
Narrowband,
Mediumband,
Wideband,
SuperWideband,
Fullband,
}
impl OpusBandwidth {
pub fn hz(self) -> f64 {
match self {
Self::Narrowband => 4_000.0,
Self::Mediumband => 6_000.0,
Self::Wideband => 8_000.0,
Self::SuperWideband => 12_000.0,
Self::Fullband => 20_000.0,
}
}
}
impl fmt::Display for OpusBandwidth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Narrowband => "narrowband",
Self::Mediumband => "mediumband",
Self::Wideband => "wideband",
Self::SuperWideband => "super-wideband",
Self::Fullband => "fullband",
})
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpusUse {
pub mode: OpusMode,
pub bandwidth: OpusBandwidth,
pub seconds: f64,
}
impl OpusUse {
pub fn describe(uses: &[OpusUse]) -> Option<String> {
let most = uses.first()?;
let total: f64 = uses.iter().map(|u| u.seconds).sum();
let voice = if most.mode.is_voice() {
", voice mode"
} else {
""
};
let share = if uses.len() > 1 && total > 0.0 {
format!(" for {:.0}% of the time", 100.0 * most.seconds / total)
} else {
String::new()
};
Some(format!("{} {}{voice}{share}", most.mode, most.bandwidth))
}
}
struct Toc(u8);
impl Toc {
fn coding(&self) -> (OpusMode, OpusBandwidth) {
use OpusBandwidth::{Fullband, Mediumband, Narrowband, SuperWideband, Wideband};
match self.0 >> 3 {
0..=3 => (OpusMode::Silk, Narrowband),
4..=7 => (OpusMode::Silk, Mediumband),
8..=11 => (OpusMode::Silk, Wideband),
12..=13 => (OpusMode::Hybrid, SuperWideband),
14..=15 => (OpusMode::Hybrid, Fullband),
16..=19 => (OpusMode::Celt, Narrowband),
20..=23 => (OpusMode::Celt, Wideband),
24..=27 => (OpusMode::Celt, SuperWideband),
_ => (OpusMode::Celt, Fullband),
}
}
fn frame_length(&self) -> u32 {
let config = self.0 >> 3;
match config {
0..=11 => [480, 960, 1920, 2880][usize::from(config % 4)],
12..=15 => [480, 960][usize::from(config % 2)],
_ => [120, 240, 480, 960][usize::from(config % 4)],
}
}
}
fn coding_of(packet: &[u8]) -> Option<(OpusMode, OpusBandwidth, u32)> {
let toc = Toc(*packet.first()?);
let frames = match toc.0 & 3 {
0 => 1,
1 | 2 => 2,
_ => u32::from(*packet.get(1)? & 0x3f),
};
let (mode, bandwidth) = toc.coding();
Some((mode, bandwidth, frames * toc.frame_length()))
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Tally(Vec<(OpusMode, OpusBandwidth, u64)>);
impl Tally {
pub(crate) fn count(&mut self, packet: &[u8]) {
let Some((mode, bandwidth, frames)) = coding_of(packet) else {
return;
};
match self
.0
.iter_mut()
.find(|(m, b, _)| (*m, *b) == (mode, bandwidth))
{
Some((_, _, total)) => *total += u64::from(frames),
None => self.0.push((mode, bandwidth, u64::from(frames))),
}
}
pub(crate) fn uses(&self) -> Vec<OpusUse> {
let mut counted = self.0.clone();
counted.sort_by_key(|(_, _, frames)| std::cmp::Reverse(*frames));
counted
.into_iter()
.map(|(mode, bandwidth, frames)| OpusUse {
mode,
bandwidth,
seconds: frames as f64 / f64::from(RATE),
})
.collect()
}
}
pub(crate) fn head_from_mp4(head: &[u8]) -> Vec<u8> {
let mut head = head.to_vec();
if let Some(version) = head.get_mut(8) {
*version = 1;
}
for field in [10..12, 12..16, 16..18] {
if let Some(bytes) = head.get_mut(field) {
bytes.reverse();
}
}
head
}
pub(crate) fn pre_skip(head: &[u8]) -> Option<u64> {
let bytes = head.get(10..12)?;
Some(u64::from(u16::from_le_bytes([bytes[0], bytes[1]])))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_packets_first_byte_states_its_mode_bandwidth_and_length() {
assert_eq!(
coding_of(&[31 << 3]),
Some((OpusMode::Celt, OpusBandwidth::Fullband, 960))
);
assert_eq!(
coding_of(&[(9 << 3) | 1, 0]),
Some((OpusMode::Silk, OpusBandwidth::Wideband, 1920))
);
assert_eq!(
coding_of(&[(12 << 3) | 3, 0xc3]),
Some((OpusMode::Hybrid, OpusBandwidth::SuperWideband, 1440))
);
assert_eq!(
coding_of(&[16 << 3]),
Some((OpusMode::Celt, OpusBandwidth::Narrowband, 120))
);
assert_eq!(
coding_of(&[3 << 3]),
Some((OpusMode::Silk, OpusBandwidth::Narrowband, 2880))
);
assert_eq!(coding_of(&[]), None);
assert_eq!(coding_of(&[3]), None, "a count that is not there");
}
#[test]
fn the_use_with_the_most_time_comes_first() {
let mut tally = Tally::default();
tally.count(&[14 << 3]);
for _ in 0..3 {
tally.count(&[31 << 3]);
}
tally.count(&[14 << 3]);
let uses = tally.uses();
assert_eq!(
uses,
[
OpusUse {
mode: OpusMode::Celt,
bandwidth: OpusBandwidth::Fullband,
seconds: 0.06
},
OpusUse {
mode: OpusMode::Hybrid,
bandwidth: OpusBandwidth::Fullband,
seconds: 0.02
},
]
);
assert_eq!(
OpusUse::describe(&uses).as_deref(),
Some("CELT fullband for 75% of the time")
);
assert_eq!(
OpusUse::describe(&uses[1..]).as_deref(),
Some("hybrid fullband, voice mode")
);
assert_eq!(OpusUse::describe(&[]), None);
}
#[test]
fn an_mp4s_header_is_turned_into_the_one_the_decoder_reads() {
let mut stored = b"OpusHead\x00\x02".to_vec();
stored.extend_from_slice(&312u16.to_be_bytes());
stored.extend_from_slice(&48_000u32.to_be_bytes());
stored.extend_from_slice(&(-256i16).to_be_bytes());
stored.push(0);
let mut wanted = b"OpusHead\x01\x02".to_vec();
wanted.extend_from_slice(&312u16.to_le_bytes());
wanted.extend_from_slice(&48_000u32.to_le_bytes());
wanted.extend_from_slice(&(-256i16).to_le_bytes());
wanted.push(0);
assert_eq!(head_from_mp4(&stored), wanted);
assert_eq!(pre_skip(&head_from_mp4(&stored)), Some(312));
let short = head_from_mp4(&stored[..11]);
assert_eq!((short[8], short[10]), (1, stored[10]));
}
#[test]
fn the_pre_skip_is_read_from_the_header() {
let mut head = b"OpusHead\x01\x02".to_vec();
head.extend_from_slice(&312u16.to_le_bytes());
assert_eq!(pre_skip(&head), Some(312));
assert_eq!(pre_skip(&head[..11]), None);
}
}