#[cfg(test)]
mod application_defined_test;
use crate::{header::*, packet::*, util::*};
use shared::{
error::{Error, Result},
marshal::{Marshal, MarshalSize, Unmarshal},
};
use bytes::{Buf, BufMut, Bytes};
use std::fmt;
const APP_NAME_LENGTH: usize = 4;
#[derive(Debug, PartialEq, Eq, Default, Clone)]
pub struct ApplicationDefined {
pub subtype: u8,
pub ssrc: u32,
pub name: [u8; 4],
pub data: Bytes,
}
impl ApplicationDefined {
pub fn name_str(&self) -> Option<&str> {
if self.name.is_ascii() {
std::str::from_utf8(&self.name).ok()
} else {
None
}
}
}
impl fmt::Display for ApplicationDefined {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"ApplicationDefined {:x} subtype={} name={:?} data={} octets",
self.ssrc,
self.subtype,
self.name_str().unwrap_or("?"),
self.data.len()
)
}
}
impl Packet for ApplicationDefined {
fn header(&self) -> Header {
Header {
padding: false,
count: self.subtype,
packet_type: PacketType::ApplicationDefined,
length: ((self.marshal_size() / 4) - 1) as u16,
}
}
fn destination_ssrc(&self) -> Vec<u32> {
vec![self.ssrc]
}
fn raw_size(&self) -> usize {
HEADER_LENGTH + SSRC_LENGTH + APP_NAME_LENGTH + self.data.len()
}
packet_any!(ApplicationDefined);
}
impl MarshalSize for ApplicationDefined {
fn marshal_size(&self) -> usize {
let l = self.raw_size();
l + get_padding_size(l)
}
}
impl Marshal for ApplicationDefined {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
if self.subtype as usize > COUNT_MAX || !self.name.is_ascii() {
return Err(Error::InvalidHeader);
}
if !self.data.len().is_multiple_of(4) {
return Err(Error::WrongMarshalSize);
}
let size = self.raw_size();
if buf.remaining_mut() < size {
return Err(Error::BufferTooShort);
}
let h = header_for(PacketType::ApplicationDefined, self.subtype, size)?;
let n = h.marshal_to(buf)?;
buf = &mut buf[n..];
buf.put_u32(self.ssrc);
buf.put_slice(&self.name);
buf.put_slice(&self.data);
Ok(size)
}
}
impl Unmarshal for ApplicationDefined {
fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
let (header, mut body) = read_packet(raw_packet)?;
if header.packet_type != PacketType::ApplicationDefined {
return Err(Error::WrongType);
}
if body.len() < SSRC_LENGTH + APP_NAME_LENGTH {
return Err(Error::PacketTooShort);
}
let ssrc = body.get_u32();
let mut name = [0u8; APP_NAME_LENGTH];
body.copy_to_slice(&mut name);
if !body.len().is_multiple_of(4) {
return Err(Error::WrongPadding);
}
Ok(ApplicationDefined {
subtype: header.count,
ssrc,
name,
data: body,
})
}
}