Skip to main content

str0m/format/
codec.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4use crate::packet::MediaKind;
5use crate::rtp_::Frequency;
6
7use super::format_params::FormatParams;
8
9/// Codec specification
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
11pub struct CodecSpec {
12    /// The codec identifier.
13    pub codec: Codec,
14
15    /// Clock rate of the codec.
16    pub clock_rate: Frequency,
17
18    /// Number of audio channels (if any).
19    pub channels: Option<u8>,
20
21    /// Codec specific format parameters. This might carry additional config for
22    /// things like h264.
23    pub format: FormatParams,
24}
25
26impl CodecSpec {
27    /// The RTP clock rate used on the wire for this codec.
28    ///
29    /// For most codecs this is the same as [`CodecSpec::clock_rate`]. G722 is a
30    /// special case: although the codec samples audio at 16 kHz, its RTP timestamp
31    /// clock is 8000 Hz (to remain backwards compatible with RFC 1890, which
32    /// incorrectly used this value). str0m treats G722 as a 16 kHz codec everywhere
33    /// user facing, and only maps to 8 kHz when converting to and from RTP timestamps
34    /// (and in the SDP `a=rtpmap` line).
35    ///
36    /// See RFC 3551 ยง4.5.2 and
37    /// <https://en.wikipedia.org/wiki/RTP_payload_formats#cite_note-55>
38    pub(crate) fn rtp_clock_rate(&self) -> Frequency {
39        if self.codec == Codec::G722 {
40            Frequency::EIGHT_KHZ
41        } else {
42            self.clock_rate
43        }
44    }
45}
46
47/// Known codecs and RTP payload formats.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[non_exhaustive]
50#[allow(missing_docs)]
51pub enum Codec {
52    Opus,
53    PCMU,
54    PCMA,
55    G722,
56    /// Comfort Noise payload, per RFC 3389.
57    CN,
58    AmrWb,
59    H264,
60    // TODO show this when we support h265.
61    #[doc(hidden)]
62    H265,
63    /// H266/VVC.
64    H266,
65    Vp8,
66    Vp9,
67    // TODO show this when we support Av1.
68    #[doc(hidden)]
69    Av1,
70    /// Telephone events (DTMF) RTP payload, per RFC 4733.
71    ///
72    /// Negotiated alongside audio on the same SDP m-line. See
73    /// [`CodecConfig::add_config`][super::CodecConfig::add_config] for explicit
74    /// payload configuration, offer clock-rate preferences and fallbacks.
75    ///
76    /// Targets libwebrtc-compatible DTMF, defaulting to events `0-16`, not full
77    /// RFC 4733 event handling. Only `0-X` SDP ranges are supported.
78    ///
79    /// Frame mode uses [`Writer::telephone_event`][crate::media::Writer::telephone_event]
80    /// and [`CodecExtra::Tele`][super::CodecExtra::Tele]. For RTP mode, see
81    /// [`TelephoneEvent`][crate::media::TelephoneEvent].
82    Tele,
83    /// Technically not a codec, but used in places where codecs go
84    /// in `a=rtpmap` lines.
85    #[doc(hidden)]
86    Rtx,
87    /// RFC 2198 redundant encoding (RED). Like `Rtx`, technically not a codec;
88    /// it appears in `a=rtpmap` lines and wraps a primary audio codec.
89    #[doc(hidden)]
90    Red,
91    /// For RTP mode. No codec.
92    #[doc(hidden)]
93    Null,
94    #[doc(hidden)]
95    Unknown,
96}
97
98#[cfg(feature = "drv")]
99crate::drv_identity_copy!(Codec, CodecSpec);
100
101impl Codec {
102    /// Tells if codec is audio.
103    pub fn is_audio(&self) -> bool {
104        use Codec::*;
105        matches!(self, Opus | PCMU | PCMA | G722 | CN | AmrWb)
106    }
107
108    /// Tells if codec is video.
109    pub fn is_video(&self) -> bool {
110        use Codec::*;
111        matches!(self, H266 | H265 | H264 | Vp8 | Vp9 | Av1)
112    }
113
114    /// Tells if this is the telephone-event RTP payload format.
115    pub fn is_tele(&self) -> bool {
116        *self == Codec::Tele
117    }
118
119    /// Audio/Video.
120    pub fn kind(&self) -> MediaKind {
121        if self.is_audio() || self.is_tele() {
122            MediaKind::Audio
123        } else {
124            MediaKind::Video
125        }
126    }
127}
128
129impl<'a> From<&'a str> for Codec {
130    fn from(v: &'a str) -> Self {
131        let lc = v.to_ascii_lowercase();
132        match &lc[..] {
133            "opus" => Codec::Opus,
134            "pcmu" => Codec::PCMU,
135            "pcma" => Codec::PCMA,
136            "g722" => Codec::G722,
137            "cn" => Codec::CN,
138            "amr-wb" => Codec::AmrWb,
139            "h264" => Codec::H264,
140            "h265" => Codec::H265,
141            "h266" => Codec::H266,
142            "vp8" => Codec::Vp8,
143            "vp9" => Codec::Vp9,
144            "av1" => Codec::Av1,
145            "telephone-event" => Codec::Tele,
146            "rtx" => Codec::Rtx, // resends
147            "red" => Codec::Red, // RFC 2198 redundancy
148            _ => Codec::Unknown,
149        }
150    }
151}
152
153impl fmt::Display for Codec {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        match self {
156            Codec::Opus => write!(f, "opus"),
157            Codec::PCMU => write!(f, "PCMU"),
158            Codec::PCMA => write!(f, "PCMA"),
159            Codec::G722 => write!(f, "G722"),
160            Codec::CN => write!(f, "CN"),
161            Codec::AmrWb => write!(f, "AMR-WB"),
162            Codec::H264 => write!(f, "H264"),
163            Codec::H265 => write!(f, "H265"),
164            Codec::H266 => write!(f, "H266"),
165            Codec::Vp8 => write!(f, "VP8"),
166            Codec::Vp9 => write!(f, "VP9"),
167            Codec::Av1 => write!(f, "AV1"),
168            Codec::Tele => write!(f, "telephone-event"),
169            Codec::Rtx => write!(f, "rtx"),
170            Codec::Red => write!(f, "red"),
171            Codec::Null => write!(f, "null"),
172            Codec::Unknown => write!(f, "unknown"),
173        }
174    }
175}
176
177#[cfg(test)]
178mod test {
179    use super::*;
180    use crate::format::FormatParams;
181    use crate::rtp_::{Frequency, MediaTime};
182
183    fn g722_spec() -> CodecSpec {
184        CodecSpec {
185            codec: Codec::G722,
186            clock_rate: Frequency::SIXTEEN_KHZ,
187            channels: None,
188            format: FormatParams::default(),
189        }
190    }
191
192    #[test]
193    fn g722_is_audio_and_parses() {
194        assert!(Codec::G722.is_audio());
195        assert!(!Codec::G722.is_video());
196        assert_eq!(Codec::from("G722"), Codec::G722);
197        assert_eq!(Codec::from("g722"), Codec::G722);
198        assert_eq!(Codec::G722.to_string(), "G722");
199    }
200
201    #[test]
202    fn comfort_noise_is_audio_and_parses() {
203        assert!(Codec::CN.is_audio());
204        assert!(!Codec::CN.is_video());
205        assert_eq!(Codec::from("CN"), Codec::CN);
206        assert_eq!(Codec::from("cn"), Codec::CN);
207        assert_eq!(Codec::CN.to_string(), "CN");
208    }
209
210    #[test]
211    fn telephone_event_payload() {
212        assert_eq!(Codec::from("telephone-event"), Codec::Tele);
213        assert_eq!(Codec::from("TELEPHONE-EVENT"), Codec::Tele);
214        assert_eq!(Codec::Tele.to_string(), "telephone-event");
215        assert_eq!(Codec::Tele.kind(), MediaKind::Audio);
216        assert!(!Codec::Tele.is_audio());
217        assert!(!Codec::Tele.is_video());
218    }
219
220    #[test]
221    fn g722_rtp_clock_rate_is_8khz() {
222        let spec = g722_spec();
223        // User facing clock rate is 16 kHz ...
224        assert_eq!(spec.clock_rate, Frequency::SIXTEEN_KHZ);
225        // ... but the RTP wire clock rate is 8 kHz (RFC 3551).
226        assert_eq!(spec.rtp_clock_rate(), Frequency::EIGHT_KHZ);
227    }
228
229    #[test]
230    fn g722_16khz_media_time_halves_on_the_wire() {
231        // 20 ms of 16 kHz audio is 320 samples. On the wire the RTP timestamp must
232        // advance by 160 (8000 Hz clock), i.e. the 16 kHz media time is halved when
233        // converted to an RTP timestamp.
234        let spec = g722_spec();
235        let media_time = MediaTime::new(320, spec.clock_rate);
236        let wire = media_time.rebase(spec.rtp_clock_rate());
237        assert_eq!(wire.numer(), 160);
238    }
239
240    #[test]
241    fn non_g722_rtp_clock_rate_equals_clock_rate() {
242        let spec = CodecSpec {
243            codec: Codec::Opus,
244            clock_rate: Frequency::FORTY_EIGHT_KHZ,
245            channels: Some(2),
246            format: FormatParams::default(),
247        };
248        assert_eq!(spec.rtp_clock_rate(), Frequency::FORTY_EIGHT_KHZ);
249    }
250
251    #[test]
252    fn red_codec_string_roundtrip() {
253        assert_eq!(Codec::from("red"), Codec::Red);
254        assert_eq!(Codec::Red.to_string(), "red");
255        assert!(!Codec::Red.is_audio());
256        assert!(!Codec::Red.is_video());
257    }
258}