use shared::{
error::{Error, Result},
marshal::{Marshal, MarshalSize, Unmarshal},
};
use bytes::{Buf, BufMut, Bytes};
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PacketType {
#[default]
Unsupported,
SenderReport, ReceiverReport, SourceDescription, Goodbye, ApplicationDefined, TransportSpecificFeedback, PayloadSpecificFeedback, ExtendedReport, Other(u8),
}
pub const FORMAT_SLI: u8 = 2;
pub const FORMAT_PLI: u8 = 1;
pub const FORMAT_RPSI: u8 = 3;
pub const FORMAT_FIR: u8 = 4;
pub const FORMAT_TSTR: u8 = 5;
pub const FORMAT_TSTN: u8 = 6;
pub const FORMAT_VBCM: u8 = 7;
pub const FORMAT_LRR: u8 = 10;
pub const FORMAT_AFB: u8 = 15;
pub const FORMAT_TLN: u8 = 1;
pub const FORMAT_TMMBR: u8 = 3;
pub const FORMAT_TMMBN: u8 = 4;
pub const FORMAT_RRR: u8 = 5;
pub const FORMAT_REMB: u8 = 15;
pub const FORMAT_TCC: u8 = 15;
pub const FORMAT_CCFB: u8 = 11;
pub const FORMAT_ECN: u8 = 8;
pub const FORMAT_PAUSE_RESUME: u8 = 9;
impl std::fmt::Display for PacketType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
PacketType::Unsupported => "Unsupported",
PacketType::Other(pt) => return write!(f, "PT{pt}"),
PacketType::SenderReport => "SR",
PacketType::ReceiverReport => "RR",
PacketType::SourceDescription => "SDES",
PacketType::Goodbye => "BYE",
PacketType::ApplicationDefined => "APP",
PacketType::TransportSpecificFeedback => "TSFB",
PacketType::PayloadSpecificFeedback => "PSFB",
PacketType::ExtendedReport => "XR",
};
write!(f, "{s}")
}
}
impl From<u8> for PacketType {
fn from(b: u8) -> Self {
match b {
0 => PacketType::Unsupported,
200 => PacketType::SenderReport, 201 => PacketType::ReceiverReport, 202 => PacketType::SourceDescription, 203 => PacketType::Goodbye, 204 => PacketType::ApplicationDefined, 205 => PacketType::TransportSpecificFeedback, 206 => PacketType::PayloadSpecificFeedback, 207 => PacketType::ExtendedReport, other => PacketType::Other(other),
}
}
}
impl From<PacketType> for u8 {
fn from(t: PacketType) -> Self {
match t {
PacketType::Unsupported => 0,
PacketType::SenderReport => 200,
PacketType::ReceiverReport => 201,
PacketType::SourceDescription => 202,
PacketType::Goodbye => 203,
PacketType::ApplicationDefined => 204,
PacketType::TransportSpecificFeedback => 205,
PacketType::PayloadSpecificFeedback => 206,
PacketType::ExtendedReport => 207,
PacketType::Other(other) => other,
}
}
}
pub const RTP_VERSION: u8 = 2;
pub const VERSION_SHIFT: u8 = 6;
pub const VERSION_MASK: u8 = 0x3;
pub const PADDING_SHIFT: u8 = 5;
pub const PADDING_MASK: u8 = 0x1;
pub const COUNT_SHIFT: u8 = 0;
pub const COUNT_MASK: u8 = 0x1f;
pub const HEADER_LENGTH: usize = 4;
pub const COUNT_MAX: usize = (1 << 5) - 1;
pub const SSRC_LENGTH: usize = 4;
pub const SDES_MAX_OCTET_COUNT: usize = (1 << 8) - 1;
pub const FIR_MIN_OCTET_COUNT: usize = 20;
#[derive(Debug, PartialEq, Eq, Default, Clone)]
pub struct Header {
pub padding: bool,
pub count: u8,
pub packet_type: PacketType,
pub length: u16,
}
impl MarshalSize for Header {
fn marshal_size(&self) -> usize {
HEADER_LENGTH
}
}
impl Marshal for Header {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
if self.count > 31 {
return Err(Error::InvalidHeader);
}
if buf.remaining_mut() < HEADER_LENGTH {
return Err(Error::BufferTooShort);
}
let b0 = (RTP_VERSION << VERSION_SHIFT)
| ((self.padding as u8) << PADDING_SHIFT)
| (self.count << COUNT_SHIFT);
buf.put_u8(b0);
buf.put_u8(self.packet_type.into());
buf.put_u16(self.length);
Ok(HEADER_LENGTH)
}
}
impl Unmarshal for Header {
fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
if raw_packet.remaining() < HEADER_LENGTH {
return Err(Error::PacketTooShort);
}
let b0 = raw_packet.get_u8();
let version = (b0 >> VERSION_SHIFT) & VERSION_MASK;
if version != RTP_VERSION {
return Err(Error::BadVersion);
}
let padding = ((b0 >> PADDING_SHIFT) & PADDING_MASK) > 0;
let count = (b0 >> COUNT_SHIFT) & COUNT_MASK;
let packet_type = PacketType::from(raw_packet.get_u8());
let length = raw_packet.get_u16();
Ok(Header {
padding,
count,
packet_type,
length,
})
}
}
pub(crate) const FEEDBACK_SSRCS_LENGTH: usize = 2 * SSRC_LENGTH;
pub(crate) fn read_packet<B>(raw: &mut B) -> Result<(Header, Bytes)>
where
B: Buf,
{
let header = Header::unmarshal(raw)?;
let length = header.length as usize * 4;
if raw.remaining() < length {
return Err(Error::PacketTooShort);
}
let mut body = raw.copy_to_bytes(length);
if header.padding {
let padding = body.last().copied().unwrap_or(0) as usize;
if padding == 0 || padding > body.len() {
return Err(Error::WrongPadding);
}
body.truncate(body.len() - padding);
}
Ok((header, body))
}
pub(crate) fn read_feedback<B>(
raw: &mut B,
packet_type: PacketType,
format: u8,
) -> Result<(u32, u32, Bytes)>
where
B: Buf,
{
let (header, mut body) = read_packet(raw)?;
if header.packet_type != packet_type || header.count != format {
return Err(Error::WrongType);
}
if body.len() < FEEDBACK_SSRCS_LENGTH {
return Err(Error::PacketTooShort);
}
let sender_ssrc = body.get_u32();
let media_ssrc = body.get_u32();
Ok((sender_ssrc, media_ssrc, body))
}
pub(crate) fn header_for(packet_type: PacketType, count: u8, size: usize) -> Result<Header> {
if !size.is_multiple_of(4) || size < HEADER_LENGTH {
return Err(Error::WrongMarshalSize);
}
let length = u16::try_from(size / 4 - 1).map_err(|_| Error::TooManyReports)?;
Ok(Header {
padding: false,
count,
packet_type,
length,
})
}
pub(crate) fn put_feedback_start(
buf: &mut [u8],
packet_type: PacketType,
format: u8,
size: usize,
sender_ssrc: u32,
media_ssrc: u32,
) -> Result<&mut [u8]> {
if buf.len() < size {
return Err(Error::BufferTooShort);
}
let n = header_for(packet_type, format, size)?.marshal_to(buf)?;
let mut rest = &mut buf[n..];
rest.put_u32(sender_ssrc);
rest.put_u32(media_ssrc);
Ok(rest)
}
#[cfg(test)]
mod test {
use super::*;
use bytes::Bytes;
#[test]
fn test_header_unmarshal() {
let tests = vec![
(
"valid",
Bytes::from_static(&[
0x81u8, 0xc9, 0x00, 0x07,
]),
Header {
padding: false,
count: 1,
packet_type: PacketType::ReceiverReport,
length: 7,
},
None,
),
(
"also valid",
Bytes::from_static(&[
0xa1, 0xcc, 0x00, 0x07,
]),
Header {
padding: true,
count: 1,
packet_type: PacketType::ApplicationDefined,
length: 7,
},
None,
),
(
"bad version",
Bytes::from_static(&[
0x00, 0xc9, 0x00, 0x04,
]),
Header {
padding: false,
count: 0,
packet_type: PacketType::Unsupported,
length: 0,
},
Some(Error::BadVersion),
),
];
for (name, data, want, want_error) in tests {
let buf = &mut data.clone();
let got = Header::unmarshal(buf);
assert_eq!(
got.is_err(),
want_error.is_some(),
"Unmarshal {name}: err = {got:?}, want {want_error:?}"
);
if let Some(want_error) = want_error {
let got_err = got.err().unwrap();
assert_eq!(
want_error, got_err,
"Unmarshal {name}: err = {got_err:?}, want {want_error:?}",
);
} else {
let actual = got.unwrap();
assert_eq!(
actual, want,
"Unmarshal {name}: got {actual:?}, want {want:?}"
);
}
}
}
#[test]
fn test_header_roundtrip() {
let tests = vec![
(
"valid",
Header {
padding: true,
count: 31,
packet_type: PacketType::SenderReport,
length: 4,
},
None,
),
(
"also valid",
Header {
padding: false,
count: 28,
packet_type: PacketType::ReceiverReport,
length: 65535,
},
None,
),
(
"invalid count",
Header {
padding: false,
count: 40,
packet_type: PacketType::Unsupported,
length: 0,
},
Some(Error::InvalidHeader),
),
];
for (name, want, want_error) in tests {
let got = want.marshal();
assert_eq!(
got.is_ok(),
want_error.is_none(),
"Marshal {name}: err = {got:?}, want {want_error:?}"
);
if let Some(err) = want_error {
let got_err = got.err().unwrap();
assert_eq!(
err, got_err,
"Unmarshal {name} rr: err = {got_err:?}, want {err:?}",
);
} else {
let data = got.ok().unwrap();
let buf = &mut data.clone();
let actual = Header::unmarshal(buf).unwrap_or_else(|_| panic!("Unmarshal {name}"));
assert_eq!(
actual, want,
"{name} round trip: got {actual:?}, want {want:?}"
)
}
}
}
}