Skip to main content

rtci_rtp/extension/audio_level_extension/
mod.rs

1#[cfg(test)]
2mod audio_level_extension_test;
3
4use serde::{Deserialize, Serialize};
5use shared::{
6    error::{Error, Result},
7    marshal::{Marshal, MarshalSize, Unmarshal},
8};
9
10use bytes::{Buf, BufMut};
11
12// AUDIO_LEVEL_EXTENSION_SIZE One byte header size
13/// The extension's encoded size in bytes.
14pub const AUDIO_LEVEL_EXTENSION_SIZE: usize = 1;
15
16/// AudioLevelExtension is a extension payload format described in
17/// <https://tools.ietf.org/html/rfc6464>
18///
19/// Implementation based on:
20/// <https://chromium.googlesource.com/external/webrtc/+/e2a017725570ead5946a4ca8235af27470ca0df9/webrtc/modules/rtp_rtcp/source/rtp_header_extensions.cc#49>
21///
22/// One byte format:
23/// 0                   1
24/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
25/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
26/// |  ID   | len=0 |V| level       |
27/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
28///
29/// Two byte format:
30/// 0                   1                   2                   3
31/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
32/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
33/// |      ID       |     len=1     |V|    level    |    0 (pad)    |
34/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
35///
36/// ## Specifications
37///
38/// * [RFC 6464]
39///
40/// [RFC 6464]: https://tools.ietf.org/html/rfc6464
41#[derive(PartialEq, Eq, Debug, Default, Copy, Clone, Serialize, Deserialize)]
42pub struct AudioLevelExtension {
43    /// Loudness in −dBov, from 0 (loudest) to 127 (silence).
44    pub level: u8,
45    /// Whether the sender detected voice activity in this packet.
46    pub voice: bool,
47}
48
49/// The level of digital silence, which a muted source sends (RFC 6464 section 3).
50pub const AUDIO_LEVEL_SILENCE: u8 = 127;
51
52/// Reads the `vad` extension attribute of an `a=extmap` line for this extension (RFC 6464
53/// section 4): `vad=on` or `vad=off`, and `vad=on` when there is none. The answer says whether
54/// the V bit is in use.
55///
56/// # Errors
57///
58/// Fails for an attribute that is neither.
59pub fn parse_vad_attribute(extension_attributes: Option<&str>) -> Result<bool> {
60    match extension_attributes.map(str::trim) {
61        None | Some("") | Some("vad=on") => Ok(true),
62        Some("vad=off") => Ok(false),
63        Some(other) => Err(Error::Other(format!(
64            "ssrc-audio-level: unknown extension attribute {other:?}"
65        ))),
66    }
67}
68
69impl AudioLevelExtension {
70    /// The voice activity flag, for a stream negotiated with this `vad` (see
71    /// [`parse_vad_attribute`]): `None` with `vad=off`, where the V bit means nothing and a
72    /// receiver ignores it (RFC 6464 sections 3 and 4).
73    pub fn voice_activity(&self, vad: bool) -> Option<bool> {
74        vad.then_some(self.voice)
75    }
76}
77
78impl Unmarshal for AudioLevelExtension {
79    /// Unmarshal parses the passed byte slice and stores the result in the members
80    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
81    where
82        Self: Sized,
83        B: Buf,
84    {
85        if raw_packet.remaining() < AUDIO_LEVEL_EXTENSION_SIZE {
86            return Err(Error::ErrBufferTooSmall);
87        }
88
89        let b = raw_packet.get_u8();
90
91        Ok(AudioLevelExtension {
92            level: b & 0x7F,
93            voice: (b & 0x80) != 0,
94        })
95    }
96}
97
98impl MarshalSize for AudioLevelExtension {
99    /// MarshalSize returns the size of the AudioLevelExtension once marshaled.
100    fn marshal_size(&self) -> usize {
101        AUDIO_LEVEL_EXTENSION_SIZE
102    }
103}
104
105impl Marshal for AudioLevelExtension {
106    /// MarshalTo serializes the members to buffer
107    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
108        if buf.remaining_mut() < AUDIO_LEVEL_EXTENSION_SIZE {
109            return Err(Error::ErrBufferTooSmall);
110        }
111        if self.level > 127 {
112            return Err(Error::AudioLevelOverflow);
113        }
114        let voice = if self.voice { 0x80u8 } else { 0u8 };
115
116        buf.put_u8(voice | self.level);
117
118        Ok(AUDIO_LEVEL_EXTENSION_SIZE)
119    }
120}