rtci-rtp 0.2.0

RTP packets, header extensions (RFC 3550, RFC 8285) and codec payload formats for WebRTC
Documentation
#[cfg(test)]
mod audio_level_extension_test;

use serde::{Deserialize, Serialize};
use shared::{
    error::{Error, Result},
    marshal::{Marshal, MarshalSize, Unmarshal},
};

use bytes::{Buf, BufMut};

// AUDIO_LEVEL_EXTENSION_SIZE One byte header size
/// The extension's encoded size in bytes.
pub const AUDIO_LEVEL_EXTENSION_SIZE: usize = 1;

/// AudioLevelExtension is a extension payload format described in
/// <https://tools.ietf.org/html/rfc6464>
///
/// Implementation based on:
/// <https://chromium.googlesource.com/external/webrtc/+/e2a017725570ead5946a4ca8235af27470ca0df9/webrtc/modules/rtp_rtcp/source/rtp_header_extensions.cc#49>
///
/// One byte format:
/// 0                   1
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |  ID   | len=0 |V| level       |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Two byte format:
/// 0                   1                   2                   3
/// 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
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |      ID       |     len=1     |V|    level    |    0 (pad)    |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// ## Specifications
///
/// * [RFC 6464]
///
/// [RFC 6464]: https://tools.ietf.org/html/rfc6464
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct AudioLevelExtension {
    /// Loudness in −dBov, from 0 (loudest) to 127 (silence).
    pub level: u8,
    /// Whether the sender detected voice activity in this packet.
    pub voice: bool,
}

/// The level of digital silence, which a muted source sends (RFC 6464 section 3).
pub const AUDIO_LEVEL_SILENCE: u8 = 127;

/// Reads the `vad` extension attribute of an `a=extmap` line for this extension (RFC 6464
/// section 4): `vad=on` or `vad=off`, and `vad=on` when there is none. The answer says whether
/// the V bit is in use.
///
/// # Errors
///
/// Fails for an attribute that is neither.
pub fn parse_vad_attribute(extension_attributes: Option<&str>) -> Result<bool> {
    match extension_attributes.map(str::trim) {
        None | Some("") | Some("vad=on") => Ok(true),
        Some("vad=off") => Ok(false),
        Some(other) => Err(Error::Other(format!(
            "ssrc-audio-level: unknown extension attribute {other:?}"
        ))),
    }
}

impl AudioLevelExtension {
    /// The voice activity flag, for a stream negotiated with this `vad` (see
    /// [`parse_vad_attribute`]): `None` with `vad=off`, where the V bit means nothing and a
    /// receiver ignores it (RFC 6464 sections 3 and 4).
    pub fn voice_activity(&self, vad: bool) -> Option<bool> {
        vad.then_some(self.voice)
    }
}

impl Unmarshal for AudioLevelExtension {
    /// Unmarshal parses the passed byte slice and stores the result in the members
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        if raw_packet.remaining() < AUDIO_LEVEL_EXTENSION_SIZE {
            return Err(Error::ErrBufferTooSmall);
        }

        let b = raw_packet.get_u8();

        Ok(AudioLevelExtension {
            level: b & 0x7F,
            voice: (b & 0x80) != 0,
        })
    }
}

impl MarshalSize for AudioLevelExtension {
    /// MarshalSize returns the size of the AudioLevelExtension once marshaled.
    fn marshal_size(&self) -> usize {
        AUDIO_LEVEL_EXTENSION_SIZE
    }
}

impl Marshal for AudioLevelExtension {
    /// MarshalTo serializes the members to buffer
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        if buf.remaining_mut() < AUDIO_LEVEL_EXTENSION_SIZE {
            return Err(Error::ErrBufferTooSmall);
        }
        if self.level > 127 {
            return Err(Error::AudioLevelOverflow);
        }
        let voice = if self.voice { 0x80u8 } else { 0u8 };

        buf.put_u8(voice | self.level);

        Ok(AUDIO_LEVEL_EXTENSION_SIZE)
    }
}