Skip to main content

str0m/packet/
mod.rs

1#![allow(clippy::type_complexity)]
2
3use std::fmt;
4use std::panic::UnwindSafe;
5
6use crate::format::Codec;
7use crate::sdp::MediaType;
8
9use crate::rtp::vla::encode_leb_u63;
10
11mod av1;
12pub use av1::Av1CodecExtra;
13pub use av1::detect_av1_keyframe;
14use av1::{Av1Depacketizer, Av1Packetizer};
15
16mod amr_wb;
17use amr_wb::{AmrWbDepacketizer, AmrWbPacketizer};
18
19mod g7xx;
20use g7xx::{G711Depacketizer, G711Packetizer, G722Packetizer};
21
22mod h264;
23pub use h264::H264CodecExtra;
24pub use h264::{H264Depacketizer, H264Packetizer};
25pub use h264::{detect_h264_keyframe, detect_h264_nalu};
26
27mod h264_profile;
28pub(crate) use h264_profile::H264ProfileLevel;
29
30mod h265;
31pub use h265::H265CodecExtra;
32use h265::H265Depacketizer;
33pub use h265::H265Packetizer;
34pub use h265::detect_h265_keyframe;
35
36mod h265_profile;
37pub use h265_profile::{H265Level, H265Profile, H265ProfileTierLevel, H265Tier};
38
39mod h266;
40pub use h266::H266CodecExtra;
41use h266::H266Depacketizer;
42pub use h266::H266Packetizer;
43pub use h266::detect_h266_keyframe;
44
45mod h266_profile;
46pub use h266_profile::{H266Level, H266Profile, H266ProfileTierLevel, H266Tier};
47
48mod opus;
49pub use opus::{OpusDepacketizer, OpusPacketizer};
50
51mod red;
52pub(crate) use red::{MAX_RED_RECOVERY_DEPTH, RedSender, red_same_pt_blocks};
53pub use red::{RedBlock, RedDecoder, RedEncoder, RedundantBlock};
54
55mod vp8;
56pub use vp8::Vp8CodecExtra;
57pub use vp8::Vp8Descriptor;
58pub use vp8::Vp8DescriptorError;
59pub use vp8::Vp8Patch;
60pub use vp8::Vp8PatchBuilder;
61pub use vp8::Vp8PatchError;
62pub use vp8::detect_vp8_keyframe;
63pub use vp8::{Vp8Depacketizer, Vp8Packetizer};
64
65mod vp9;
66pub use vp9::Vp9CodecExtra;
67pub use vp9::Vp9PacketizerMode;
68pub use vp9::detect_vp9_keyframe;
69use vp9::{Vp9Depacketizer, Vp9Packetizer};
70
71mod null;
72use null::{NullDepacketizer, NullPacketizer};
73
74mod comfort_noise;
75use comfort_noise::{ComfortNoiseDepacketizer, ComfortNoisePacketizer};
76
77mod tele;
78pub use tele::TelephoneEvent;
79pub(crate) use tele::duration_from_units;
80use tele::{TelephoneEventDepacketizer, TelephoneEventPacketizer};
81
82mod buffer_rx;
83pub(crate) use buffer_rx::{DepacketizingBuffer, RtpMeta};
84
85mod contiguity;
86mod contiguity_vp8;
87mod contiguity_vp9;
88mod error;
89
90mod payload;
91pub(crate) use payload::{Payloader, RedSink};
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94/// Types of media.
95pub enum MediaKind {
96    /// Audio media.
97    Audio,
98    /// Video media.
99    Video,
100}
101
102#[cfg(feature = "drv")]
103crate::drv_identity_copy!(MediaKind);
104
105impl MediaKind {
106    /// Tests if this is `MediaKind::Audio`
107    pub fn is_audio(&self) -> bool {
108        *self == MediaKind::Audio
109    }
110
111    /// Tests if this is `MediaKind::Video`
112    pub fn is_video(&self) -> bool {
113        *self == MediaKind::Video
114    }
115}
116
117/// Packetizes some bytes for use as RTP packet.
118///
119/// ## Unversioned API surface
120///
121/// This trait is not currently versioned according to semver rules.
122/// Breaking changes may be made in minor or patch releases.
123pub trait Packetizer: fmt::Debug {
124    /// Chunk the data up into RTP packets.
125    fn packetize(&mut self, mtu: usize, b: &[u8]) -> Result<Vec<Vec<u8>>, PacketError>;
126
127    /// Tell if this is the last packet of a frame.
128    fn is_marker(&mut self, data: &[u8], previous: Option<&[u8]>, last: bool) -> bool;
129
130    /// Whether a start-of-talkspurt should set the RTP marker bit for this codec. Audio codecs
131    /// that mark talkspurt boundaries return `true`; video and comfort noise return `false`.
132    fn marks_talkspurt(&self) -> bool {
133        false
134    }
135
136    /// Default nackability of packets this packetizer produces. Video is nackable (answered via
137    /// RTX); audio is not, so audio packetizers override this to `false`.
138    fn nackable(&self) -> bool {
139        true
140    }
141}
142
143/// Codec specific information
144///
145/// Contains additional codec specific information which are deemed useful for
146/// managing and repackaging the frame
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum CodecExtra {
150    /// No extra information available
151    None,
152    /// Codec extra parameters for VP8.
153    Vp8(Vp8CodecExtra),
154    /// Codec extra parameters for VP9.
155    Vp9(Vp9CodecExtra),
156    /// Codec extra parameters for H264.
157    H264(H264CodecExtra),
158    /// Codec extra parameters for AV1,
159    Av1(Av1CodecExtra),
160    /// Codec extra parameters for H265.
161    H265(H265CodecExtra),
162    /// Codec extra parameters for H266 (VVC). Prototype.
163    H266(H266CodecExtra),
164    /// The telephone-event (RFC 4733) value in this media sample.
165    Tele(TelephoneEvent),
166}
167
168/// Depacketizes an RTP payload.
169///
170/// Removes any RTP specific data from the payload.
171///
172/// ## Unversioned API surface
173///
174/// This trait is not currently versioned according to semver rules.
175/// Breaking changes may be made in minor or patch releases.
176pub trait Depacketizer: fmt::Debug {
177    /// Provide a size hint for the `out: &mut Vec<u8>` parameter in [`Depacketizer::depacketize`].
178    /// The [`packets_size`] parameter is the sum of the size of all packets that will be processed in
179    /// subsequent calls to [`Depacketizer::depacketize`].
180    /// This is used to allocate the vector with upfront capacity.
181    /// Return [`None`] if it cannot be determined.
182    fn out_size_hint(&self, packets_size: usize) -> Option<usize>;
183
184    /// Unpack the RTP packet into a provided `Vec<u8>`.
185    fn depacketize(
186        &mut self,
187        packet: &[u8],
188        out: &mut Vec<u8>,
189        codec_extra: &mut CodecExtra,
190    ) -> Result<(), PacketError>;
191
192    /// Checks if the packet is at the beginning of a partition.
193    ///
194    /// Returns false if the result could not be determined.
195    fn is_partition_head(&self, packet: &[u8]) -> bool;
196
197    /// Checks if the packet is at the end of a partition.
198    ///
199    /// Returns false if the result could not be determined.
200    fn is_partition_tail(&self, marker: bool, packet: &[u8]) -> bool;
201}
202
203pub use error::PacketError;
204
205/// Helper to replace Bytes. Provides get_u8 and get_u16 over some buffer of bytes.
206pub(crate) trait BitRead {
207    fn remaining_bits(&self) -> usize;
208    fn remaining_bytes(&self) -> usize;
209    fn byte_offset(&self) -> usize;
210    fn get_u8(&mut self) -> Option<u8>;
211    fn get_u16(&mut self) -> Option<u16>;
212    /// Reads `count` bits, at most 8, right-aligned in the result.
213    fn get_bits(&mut self, count: usize) -> Option<u8>;
214    fn get_remaining(&mut self) -> &[u8];
215    fn get_bytes(&mut self, count: usize) -> Option<&[u8]>;
216    fn get_leb128(&mut self) -> Option<usize>;
217    fn skip_bytes(&mut self, count: usize);
218}
219
220impl BitRead for (&[u8], usize) {
221    #[inline(always)]
222    fn remaining_bits(&self) -> usize {
223        (self.0.len() * 8).saturating_sub(self.1)
224    }
225
226    #[inline(always)]
227    fn remaining_bytes(&self) -> usize {
228        self.remaining_bits() / 8
229    }
230
231    #[inline(always)]
232    fn byte_offset(&self) -> usize {
233        self.1 / 8
234    }
235
236    #[inline(always)]
237    fn get_u8(&mut self) -> Option<u8> {
238        if self.remaining_bits() < 8 {
239            return None;
240        }
241
242        let offs = self.1 / 8;
243        let shift = (self.1 % 8) as u32;
244        self.1 += 8;
245
246        let mut n = self.0[offs];
247
248        if shift > 0 {
249            n <<= shift;
250            n |= self.0[offs + 1] >> (8 - shift)
251        }
252
253        Some(n)
254    }
255
256    fn get_u16(&mut self) -> Option<u16> {
257        if self.remaining_bits() < 16 {
258            return None;
259        }
260        Some(u16::from_be_bytes([self.get_u8()?, self.get_u8()?]))
261    }
262
263    fn get_bits(&mut self, count: usize) -> Option<u8> {
264        if count > 8 || self.remaining_bits() < count {
265            return None;
266        }
267        if count == 0 {
268            return Some(0);
269        }
270
271        let offs = self.1 / 8;
272        let next = self.0.get(offs + 1).copied().unwrap_or(0);
273        let window = u16::from_be_bytes([self.0[offs], next]) << (self.1 % 8);
274        self.1 += count;
275
276        Some((window >> (16 - count)) as u8)
277    }
278
279    fn get_remaining(&mut self) -> &[u8] {
280        let offset = self.1 / 8;
281        self.1 = self.0.len() * 8;
282        &self.0[offset..]
283    }
284
285    fn get_bytes(&mut self, count: usize) -> Option<&[u8]> {
286        let count_bits = count.saturating_mul(8);
287        if self.remaining_bits() < count_bits {
288            return None;
289        }
290        let offset = self.1 / 8;
291        self.1 += count_bits;
292        Some(&self.0[offset..offset + count])
293    }
294
295    fn get_leb128(&mut self) -> Option<usize> {
296        let mut temp_value: usize = 0;
297
298        for i in (0..64).step_by(7) {
299            if self.remaining_bits() < 8 {
300                return None;
301            }
302            let byte = self.get_u8().unwrap();
303            temp_value |= ((byte & 0x7f) as usize) << i;
304
305            if byte < 0x80 {
306                return Some(temp_value);
307            }
308        }
309
310        None
311    }
312
313    fn skip_bytes(&mut self, count: usize) {
314        let bits = count.saturating_mul(8);
315        if self.remaining_bits() < bits {
316            return;
317        }
318
319        self.1 += bits;
320    }
321}
322
323#[derive(Debug)]
324pub(crate) enum CodecPacketizer {
325    #[allow(unused)]
326    G711(G711Packetizer),
327    #[allow(unused)]
328    G722(G722Packetizer),
329    H264(H264Packetizer),
330    H265(H265Packetizer),
331    H266(H266Packetizer),
332    Opus(OpusPacketizer),
333    ComfortNoise(ComfortNoisePacketizer),
334    Tele(TelephoneEventPacketizer),
335    Vp8(Vp8Packetizer),
336    Vp9(Vp9Packetizer),
337    Av1(Av1Packetizer),
338    AmrWb(AmrWbPacketizer),
339    Null(NullPacketizer),
340    #[allow(unused)]
341    Boxed(Box<dyn Packetizer + Send + Sync + UnwindSafe>),
342}
343
344#[derive(Debug)]
345pub(crate) enum CodecDepacketizer {
346    G711(G711Depacketizer),
347    H264(H264Depacketizer),
348    H265(H265Depacketizer),
349    H266(H266Depacketizer),
350    Opus(OpusDepacketizer),
351    ComfortNoise(ComfortNoiseDepacketizer),
352    Tele(TelephoneEventDepacketizer),
353    Vp8(Vp8Depacketizer),
354    Vp9(Vp9Depacketizer),
355    Av1(Av1Depacketizer),
356    AmrWb(AmrWbDepacketizer),
357    Null(NullDepacketizer),
358    #[allow(unused)]
359    Boxed(Box<dyn Depacketizer + Send + Sync + UnwindSafe>),
360}
361
362impl CodecPacketizer {
363    pub(crate) fn new(codec: Codec, vp9_mode: Vp9PacketizerMode) -> Self {
364        match codec {
365            Codec::Opus => CodecPacketizer::Opus(OpusPacketizer),
366            Codec::PCMU => CodecPacketizer::G711(G711Packetizer::default()),
367            Codec::PCMA => CodecPacketizer::G711(G711Packetizer::default()),
368            Codec::G722 => CodecPacketizer::G722(G722Packetizer::default()),
369            Codec::CN => CodecPacketizer::ComfortNoise(ComfortNoisePacketizer),
370            Codec::AmrWb => CodecPacketizer::AmrWb(AmrWbPacketizer::default()),
371            Codec::H264 => CodecPacketizer::H264(H264Packetizer::default()),
372            Codec::H265 => CodecPacketizer::H265(H265Packetizer::default()),
373            Codec::H266 => CodecPacketizer::H266(H266Packetizer::default()),
374            Codec::Vp8 => CodecPacketizer::Vp8(Vp8Packetizer::default()),
375            Codec::Vp9 => CodecPacketizer::Vp9(Vp9Packetizer::with_mode(vp9_mode)),
376            Codec::Av1 => CodecPacketizer::Av1(Av1Packetizer::default()),
377            Codec::Null => CodecPacketizer::Null(NullPacketizer),
378            Codec::Tele => CodecPacketizer::Tele(TelephoneEventPacketizer),
379            Codec::Rtx => panic!("Cant instantiate packetizer for RTX codec"),
380            Codec::Red => panic!("Cant instantiate packetizer for RED codec"),
381            Codec::Unknown => panic!("Cant instantiate packetizer for unknown codec"),
382        }
383    }
384
385    /// Apply codec-specific configuration derived from the negotiated [`CodecSpec`]. Keeps this
386    /// knowledge inside the codec-aware packetizer so the generic [`Payloader`] never has to name
387    /// concrete packetizer variants.
388    pub(crate) fn configure_for(&mut self, spec: &crate::format::CodecSpec) {
389        // Enable DONL for H.265 when sprop-max-don-diff > 0 (RFC 7798 §7.1).
390        if let CodecPacketizer::H265(h265) = self {
391            if spec.format.sprop_max_don_diff.unwrap_or(0) > 0 {
392                h265.with_donl(true);
393            }
394        }
395        // Enable DONL for H.266 when sprop-max-don-diff > 0 (RFC 9328 §7.2).
396        if let CodecPacketizer::H266(h266) = self {
397            if spec.format.sprop_max_don_diff.unwrap_or(0) > 0 {
398                h266.with_donl(true);
399            }
400        }
401        if let CodecPacketizer::AmrWb(amr) = self {
402            amr.octet_align = spec.format.octet_align.unwrap_or(false);
403        }
404    }
405}
406
407impl From<Codec> for CodecPacketizer {
408    fn from(c: Codec) -> Self {
409        CodecPacketizer::new(c, Vp9PacketizerMode::default())
410    }
411}
412
413impl From<Codec> for CodecDepacketizer {
414    fn from(c: Codec) -> Self {
415        match c {
416            Codec::Opus => CodecDepacketizer::Opus(OpusDepacketizer),
417            Codec::PCMU => CodecDepacketizer::G711(G711Depacketizer),
418            Codec::PCMA => CodecDepacketizer::G711(G711Depacketizer),
419            Codec::G722 => CodecDepacketizer::G711(G711Depacketizer),
420            Codec::CN => CodecDepacketizer::ComfortNoise(ComfortNoiseDepacketizer),
421            Codec::AmrWb => CodecDepacketizer::AmrWb(AmrWbDepacketizer::default()),
422            Codec::H264 => CodecDepacketizer::H264(H264Depacketizer::default()),
423            Codec::H265 => CodecDepacketizer::H265(H265Depacketizer::default()),
424            Codec::H266 => CodecDepacketizer::H266(H266Depacketizer::default()),
425            Codec::Vp8 => CodecDepacketizer::Vp8(Vp8Depacketizer::default()),
426            Codec::Vp9 => CodecDepacketizer::Vp9(Vp9Depacketizer::default()),
427            Codec::Av1 => CodecDepacketizer::Av1(Av1Depacketizer::default()),
428            Codec::Null => CodecDepacketizer::Null(NullDepacketizer),
429            Codec::Tele => CodecDepacketizer::Tele(TelephoneEventDepacketizer::default()),
430            Codec::Rtx => panic!("Cant instantiate depacketizer for RTX codec"),
431            Codec::Red => panic!("Cant instantiate depacketizer for RED codec"),
432            Codec::Unknown => panic!("Cant instantiate depacketizer for unknown codec"),
433        }
434    }
435}
436
437impl Packetizer for CodecPacketizer {
438    fn packetize(&mut self, mtu: usize, b: &[u8]) -> Result<Vec<Vec<u8>>, PacketError> {
439        use CodecPacketizer::*;
440        match self {
441            G711(v) => v.packetize(mtu, b),
442            G722(v) => v.packetize(mtu, b),
443            H264(v) => v.packetize(mtu, b),
444            H265(v) => v.packetize(mtu, b),
445            H266(v) => v.packetize(mtu, b),
446            Opus(v) => v.packetize(mtu, b),
447            ComfortNoise(v) => v.packetize(mtu, b),
448            Tele(v) => v.packetize(mtu, b),
449            Vp8(v) => v.packetize(mtu, b),
450            Vp9(v) => v.packetize(mtu, b),
451            Av1(v) => v.packetize(mtu, b),
452            AmrWb(v) => v.packetize(mtu, b),
453            Null(v) => v.packetize(mtu, b),
454            Boxed(v) => v.packetize(mtu, b),
455        }
456    }
457
458    fn is_marker(&mut self, data: &[u8], previous: Option<&[u8]>, last: bool) -> bool {
459        match self {
460            CodecPacketizer::G711(v) => v.is_marker(data, previous, last),
461            CodecPacketizer::G722(v) => v.is_marker(data, previous, last),
462            CodecPacketizer::Opus(v) => v.is_marker(data, previous, last),
463            CodecPacketizer::ComfortNoise(v) => v.is_marker(data, previous, last),
464            CodecPacketizer::Tele(v) => v.is_marker(data, previous, last),
465            CodecPacketizer::H264(v) => v.is_marker(data, previous, last),
466            CodecPacketizer::H265(v) => v.is_marker(data, previous, last),
467            CodecPacketizer::H266(v) => v.is_marker(data, previous, last),
468            CodecPacketizer::Vp8(v) => v.is_marker(data, previous, last),
469            CodecPacketizer::Vp9(v) => v.is_marker(data, previous, last),
470            CodecPacketizer::Av1(v) => v.is_marker(data, previous, last),
471            CodecPacketizer::AmrWb(v) => v.is_marker(data, previous, last),
472            CodecPacketizer::Null(v) => v.is_marker(data, previous, last),
473            CodecPacketizer::Boxed(v) => v.is_marker(data, previous, last),
474        }
475    }
476
477    fn marks_talkspurt(&self) -> bool {
478        use CodecPacketizer::*;
479        match self {
480            G711(v) => v.marks_talkspurt(),
481            G722(v) => v.marks_talkspurt(),
482            H264(v) => v.marks_talkspurt(),
483            H265(v) => v.marks_talkspurt(),
484            H266(v) => v.marks_talkspurt(),
485            Opus(v) => v.marks_talkspurt(),
486            ComfortNoise(v) => v.marks_talkspurt(),
487            Tele(v) => v.marks_talkspurt(),
488            Vp8(v) => v.marks_talkspurt(),
489            Vp9(v) => v.marks_talkspurt(),
490            Av1(v) => v.marks_talkspurt(),
491            AmrWb(v) => v.marks_talkspurt(),
492            Null(v) => v.marks_talkspurt(),
493            Boxed(v) => v.marks_talkspurt(),
494        }
495    }
496
497    fn nackable(&self) -> bool {
498        use CodecPacketizer::*;
499        match self {
500            G711(v) => v.nackable(),
501            G722(v) => v.nackable(),
502            H264(v) => v.nackable(),
503            H265(v) => v.nackable(),
504            H266(v) => v.nackable(),
505            Opus(v) => v.nackable(),
506            ComfortNoise(v) => v.nackable(),
507            Tele(v) => v.nackable(),
508            Vp8(v) => v.nackable(),
509            Vp9(v) => v.nackable(),
510            Av1(v) => v.nackable(),
511            AmrWb(v) => v.nackable(),
512            Null(v) => v.nackable(),
513            Boxed(v) => v.nackable(),
514        }
515    }
516}
517
518impl Depacketizer for CodecDepacketizer {
519    fn out_size_hint(&self, packets_size: usize) -> Option<usize> {
520        use CodecDepacketizer::*;
521        match self {
522            H264(v) => v.out_size_hint(packets_size),
523            H265(v) => v.out_size_hint(packets_size),
524            H266(v) => v.out_size_hint(packets_size),
525            Opus(v) => v.out_size_hint(packets_size),
526            ComfortNoise(v) => v.out_size_hint(packets_size),
527            Tele(v) => v.out_size_hint(packets_size),
528            G711(v) => v.out_size_hint(packets_size),
529            Vp8(v) => v.out_size_hint(packets_size),
530            Vp9(v) => v.out_size_hint(packets_size),
531            Av1(v) => v.out_size_hint(packets_size),
532            AmrWb(v) => v.out_size_hint(packets_size),
533            Null(v) => v.out_size_hint(packets_size),
534            Boxed(v) => v.out_size_hint(packets_size),
535        }
536    }
537
538    fn depacketize(
539        &mut self,
540        packet: &[u8],
541        out: &mut Vec<u8>,
542        extra: &mut CodecExtra,
543    ) -> Result<(), PacketError> {
544        use CodecDepacketizer::*;
545        match self {
546            H264(v) => v.depacketize(packet, out, extra),
547            H265(v) => v.depacketize(packet, out, extra),
548            H266(v) => v.depacketize(packet, out, extra),
549            Opus(v) => v.depacketize(packet, out, extra),
550            ComfortNoise(v) => v.depacketize(packet, out, extra),
551            Tele(v) => v.depacketize(packet, out, extra),
552            G711(v) => v.depacketize(packet, out, extra),
553            Vp8(v) => v.depacketize(packet, out, extra),
554            Vp9(v) => v.depacketize(packet, out, extra),
555            Av1(v) => v.depacketize(packet, out, extra),
556            AmrWb(v) => v.depacketize(packet, out, extra),
557            Null(v) => v.depacketize(packet, out, extra),
558            Boxed(v) => v.depacketize(packet, out, extra),
559        }
560    }
561
562    fn is_partition_head(&self, packet: &[u8]) -> bool {
563        use CodecDepacketizer::*;
564        match self {
565            H264(v) => v.is_partition_head(packet),
566            H265(v) => v.is_partition_head(packet),
567            H266(v) => v.is_partition_head(packet),
568            Opus(v) => v.is_partition_head(packet),
569            ComfortNoise(v) => v.is_partition_head(packet),
570            Tele(v) => v.is_partition_head(packet),
571            G711(v) => v.is_partition_head(packet),
572            Vp8(v) => v.is_partition_head(packet),
573            Vp9(v) => v.is_partition_head(packet),
574            Av1(v) => v.is_partition_head(packet),
575            AmrWb(v) => v.is_partition_head(packet),
576            Null(v) => v.is_partition_head(packet),
577            Boxed(v) => v.is_partition_head(packet),
578        }
579    }
580
581    fn is_partition_tail(&self, marker: bool, packet: &[u8]) -> bool {
582        use CodecDepacketizer::*;
583        match self {
584            H264(v) => v.is_partition_tail(marker, packet),
585            H265(v) => v.is_partition_tail(marker, packet),
586            H266(v) => v.is_partition_tail(marker, packet),
587            Opus(v) => v.is_partition_tail(marker, packet),
588            ComfortNoise(v) => v.is_partition_tail(marker, packet),
589            Tele(v) => v.is_partition_tail(marker, packet),
590            G711(v) => v.is_partition_tail(marker, packet),
591            Vp8(v) => v.is_partition_tail(marker, packet),
592            Vp9(v) => v.is_partition_tail(marker, packet),
593            Av1(v) => v.is_partition_tail(marker, packet),
594            AmrWb(v) => v.is_partition_tail(marker, packet),
595            Null(v) => v.is_partition_tail(marker, packet),
596            Boxed(v) => v.is_partition_tail(marker, packet),
597        }
598    }
599}
600
601impl From<MediaType> for MediaKind {
602    fn from(v: MediaType) -> Self {
603        match v {
604            MediaType::Audio => MediaKind::Audio,
605            MediaType::Video => MediaKind::Video,
606            _ => panic!("Not MediaType::Audio or Video"),
607        }
608    }
609}
610
611impl fmt::Display for MediaKind {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        match self {
614            MediaKind::Audio => write!(f, "audio"),
615            MediaKind::Video => write!(f, "video"),
616        }
617    }
618}
619
620#[cfg(test)]
621mod test {
622    use super::*;
623
624    #[test]
625    fn bit_read_get_bits() {
626        let mut reader: (&[u8], usize) = (&[0b1010_1100, 0b0101_0000], 4);
627        assert_eq!(reader.get_bits(6), Some(0b110001));
628        assert_eq!(reader.get_bits(3), Some(0b010));
629        assert_eq!(reader.get_bits(9), None);
630        assert_eq!(reader.get_bits(4), None);
631        assert_eq!(reader.get_bits(3), Some(0));
632        assert_eq!(reader.get_bits(0), Some(0));
633    }
634
635    #[test]
636    fn comfort_noise_packetizer_preserves_payload_and_clears_marker() {
637        let payload = [42, 128, 64];
638        let mut packetizer = CodecPacketizer::from(Codec::CN);
639
640        assert_eq!(
641            packetizer.packetize(1200, &payload).unwrap(),
642            vec![payload.to_vec()]
643        );
644        assert!(!packetizer.is_marker(&payload, None, true));
645
646        let mut depacketizer = CodecDepacketizer::from(Codec::CN);
647        let mut output = Vec::new();
648        depacketizer
649            .depacketize(&payload, &mut output, &mut CodecExtra::None)
650            .unwrap();
651        assert_eq!(output, payload);
652        assert!(depacketizer.is_partition_head(&payload));
653        assert!(depacketizer.is_partition_tail(false, &payload));
654    }
655
656    #[test]
657    fn telephone_event_codec_uses_telephone_event_packetizers() {
658        let payload = [5, 0x80, 0, 160];
659        let mut packetizer = CodecPacketizer::from(Codec::Tele);
660        assert_eq!(
661            packetizer.packetize(1200, &payload).unwrap(),
662            vec![payload.to_vec()]
663        );
664        assert!(!packetizer.is_marker(&payload, None, true));
665        assert!(packetizer.marks_talkspurt());
666        assert!(!packetizer.nackable());
667
668        let mut depacketizer = CodecDepacketizer::from(Codec::Tele);
669        let mut output = Vec::new();
670        let mut extra = CodecExtra::None;
671        depacketizer
672            .depacketize(&payload, &mut output, &mut extra)
673            .unwrap();
674        assert_eq!(output, payload);
675        let report = TelephoneEvent::parse(&payload, crate::rtp_::Frequency::EIGHT_KHZ).unwrap();
676        assert_eq!(extra, CodecExtra::Tele(report));
677    }
678}