Skip to main content

rtci_rtp/codec/opus/
mod.rs

1#[cfg(test)]
2mod opus_test;
3
4use crate::packetizer::{Depacketizer, MarkerRule, Payloader};
5use shared::error::{Error, Result};
6
7use bytes::Bytes;
8
9/// The RTP clock rate of Opus, whatever the audio bandwidth coded (RFC 7587 section 4.1).
10pub const OPUS_CLOCK_RATE: u32 = 48000;
11/// The longest Opus packet, in samples at 48 kHz: 120 ms (RFC 6716 section 3.2.5).
12pub const OPUS_MAX_PACKET_SAMPLES: u32 = 5760;
13/// What DTX timestamp gaps are multiples of, in samples at 48 kHz: 2.5 ms, the shortest Opus
14/// frame (RFC 7587 section 3.1.3).
15pub const OPUS_DTX_TIMESTAMP_STEP: u32 = 120;
16
17/// The duration of an Opus packet in samples at 48 kHz, which is its length in RTP timestamp
18/// units (RFC 7587 section 4.1), read from the TOC byte and the frame count (RFC 6716 section
19/// 3.1 and 3.2).
20///
21/// `None` for an empty packet, a code 3 packet without its frame count byte, a frame count of
22/// zero, or a packet longer than 120 ms: none of them is an Opus packet (RFC 6716 section 3.4,
23/// R1 and R5).
24pub fn opus_packet_samples(packet: &[u8]) -> Option<u32> {
25    let toc = *packet.first()?;
26    let config = toc >> 3;
27    // Samples per frame at 48 kHz, by configuration number (RFC 6716 Table 2).
28    let frame_samples: u32 = match config {
29        // SILK-only: 10, 20, 40, 60 ms.
30        0..=11 => [480, 960, 1920, 2880][usize::from(config & 0x3)],
31        // Hybrid: 10, 20 ms.
32        12..=15 => [480, 960][usize::from(config & 0x1)],
33        // CELT-only: 2.5, 5, 10, 20 ms.
34        _ => [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)]
46/// Packetizes Opus audio: one RTP payload per Opus packet, never fragmented and never
47/// aggregated, whatever the MTU (RFC 7587 section 4.2).
48///
49/// The marker bit follows RFC 3551 (RFC 7587 section 4.1): set on the first packet after a
50/// silence the caller skipped with
51/// [`Packetizer::skip_samples`](crate::packetizer::Packetizer::skip_samples), which is how a
52/// DTX gap is sent, and clear otherwise.
53pub 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    /// Audio: the marker is for the first packet of a talkspurt (RFC 7587 section 4.1).
65    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/// OpusPacket represents the Opus header that is stored in the payload of an RTP Packet
75#[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}