rtci_rtp/codec/opus/
mod.rs1#[cfg(test)]
2mod opus_test;
3
4use crate::packetizer::{Depacketizer, MarkerRule, Payloader};
5use shared::error::{Error, Result};
6
7use bytes::Bytes;
8
9pub const OPUS_CLOCK_RATE: u32 = 48000;
11pub const OPUS_MAX_PACKET_SAMPLES: u32 = 5760;
13pub const OPUS_DTX_TIMESTAMP_STEP: u32 = 120;
16
17pub fn opus_packet_samples(packet: &[u8]) -> Option<u32> {
25 let toc = *packet.first()?;
26 let config = toc >> 3;
27 let frame_samples: u32 = match config {
29 0..=11 => [480, 960, 1920, 2880][usize::from(config & 0x3)],
31 12..=15 => [480, 960][usize::from(config & 0x1)],
33 _ => [120, 240, 480, 960][usize::from(config & 0x3)],
35 };
36 let frames = match toc & 0x3 {
37 0 => 1,
38 1 | 2 => 2,
39 _ => u32::from(*packet.get(1)? & 0x3F),
40 };
41 let samples = frame_samples * frames;
42 (frames > 0 && samples <= OPUS_MAX_PACKET_SAMPLES).then_some(samples)
43}
44
45#[derive(Default, Debug, Copy, Clone)]
46pub struct OpusPayloader;
54
55impl Payloader for OpusPayloader {
56 fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
57 if payload.is_empty() || mtu == 0 {
58 return Ok(vec![]);
59 }
60
61 Ok(vec![payload.clone()])
62 }
63
64 fn marker_rule(&self) -> MarkerRule {
66 MarkerRule::FirstPacketOfTalkspurt
67 }
68
69 fn clone_to(&self) -> Box<dyn Payloader> {
70 Box::new(*self)
71 }
72}
73
74#[derive(PartialEq, Eq, Debug, Default, Clone)]
76pub struct OpusPacket;
77
78impl Depacketizer for OpusPacket {
79 fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
80 if packet.is_empty() {
81 Err(Error::ErrShortPacket)
82 } else {
83 Ok(packet.clone())
84 }
85 }
86
87 fn is_partition_head(&self, _payload: &Bytes) -> bool {
88 true
89 }
90
91 fn is_partition_tail(&self, _marker: bool, _payload: &Bytes) -> bool {
92 true
93 }
94}