#[cfg(test)]
mod opus_test;
use crate::packetizer::{Depacketizer, MarkerRule, Payloader};
use shared::error::{Error, Result};
use bytes::Bytes;
pub const OPUS_CLOCK_RATE: u32 = 48000;
pub const OPUS_MAX_PACKET_SAMPLES: u32 = 5760;
pub const OPUS_DTX_TIMESTAMP_STEP: u32 = 120;
pub fn opus_packet_samples(packet: &[u8]) -> Option<u32> {
let toc = *packet.first()?;
let config = toc >> 3;
let frame_samples: u32 = match config {
0..=11 => [480, 960, 1920, 2880][usize::from(config & 0x3)],
12..=15 => [480, 960][usize::from(config & 0x1)],
_ => [120, 240, 480, 960][usize::from(config & 0x3)],
};
let frames = match toc & 0x3 {
0 => 1,
1 | 2 => 2,
_ => u32::from(*packet.get(1)? & 0x3F),
};
let samples = frame_samples * frames;
(frames > 0 && samples <= OPUS_MAX_PACKET_SAMPLES).then_some(samples)
}
#[derive(Default, Debug, Copy, Clone)]
pub struct OpusPayloader;
impl Payloader for OpusPayloader {
fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
if payload.is_empty() || mtu == 0 {
return Ok(vec![]);
}
Ok(vec![payload.clone()])
}
fn marker_rule(&self) -> MarkerRule {
MarkerRule::FirstPacketOfTalkspurt
}
fn clone_to(&self) -> Box<dyn Payloader> {
Box::new(*self)
}
}
#[derive(PartialEq, Eq, Debug, Default, Clone)]
pub struct OpusPacket;
impl Depacketizer for OpusPacket {
fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
if packet.is_empty() {
Err(Error::ErrShortPacket)
} else {
Ok(packet.clone())
}
}
fn is_partition_head(&self, _payload: &Bytes) -> bool {
true
}
fn is_partition_tail(&self, _marker: bool, _payload: &Bytes) -> bool {
true
}
}