use super::*;
const RLE_REPORT_BLOCK_MIN_LENGTH: u16 = 8;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ChunkType {
RunLength = 0,
BitVector = 1,
TerminatingNull = 2,
}
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct Chunk(pub u16);
impl fmt::Display for Chunk {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.chunk_type() {
ChunkType::RunLength => {
let run_type = self.run_type().unwrap_or(0);
write!(f, "[RunLength type={}, length={}]", run_type, self.value())
}
ChunkType::BitVector => write!(f, "[BitVector {:#b}", self.value()),
ChunkType::TerminatingNull => write!(f, "[TerminatingNull]"),
}
}
}
impl Chunk {
pub fn chunk_type(&self) -> ChunkType {
if self.0 == 0 {
ChunkType::TerminatingNull
} else if (self.0 >> 15) == 0 {
ChunkType::RunLength
} else {
ChunkType::BitVector
}
}
pub fn run_type(&self) -> Result<u8> {
if self.chunk_type() != ChunkType::RunLength {
Err(Error::WrongChunkType)
} else {
Ok((self.0 >> 14) as u8 & 0x01)
}
}
pub fn value(&self) -> u16 {
match self.chunk_type() {
ChunkType::RunLength => self.0 & 0x3FFF,
ChunkType::BitVector => self.0 & 0x7FFF,
ChunkType::TerminatingNull => 0,
}
}
}
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct RLEReportBlock {
pub is_loss_rle: bool,
pub t: u8,
pub ssrc: u32,
pub begin_seq: u16,
pub end_seq: u16,
pub chunks: Vec<Chunk>,
}
pub type LossRLEReportBlock = RLEReportBlock;
pub type DuplicateRLEReportBlock = RLEReportBlock;
impl RLEReportBlock {
fn validate(&self) -> Result<()> {
if self.end_seq.wrapping_sub(self.begin_seq) >= 65534 {
return Err(Error::InvalidBlockSize);
}
for chunk in &self.chunks {
if chunk.0 == 0 {
return Err(Error::WrongChunkType);
}
if chunk.chunk_type() == ChunkType::RunLength && chunk.value() == 0 {
return Err(Error::WrongChunkType);
}
}
Ok(())
}
fn wire_chunks(&self) -> usize {
self.chunks.len() + self.chunks.len() % 2
}
pub fn xr_header(&self) -> XRHeader {
XRHeader {
block_type: if self.is_loss_rle {
BlockType::LossRLE
} else {
BlockType::DuplicateRLE
},
type_specific: self.t & 0x0F,
block_length: (self.raw_size() / 4 - 1) as u16,
}
}
}
pub const MAX_RUN_LENGTH: usize = 16_383;
pub const BIT_VECTOR_LENGTH: usize = 15;
pub fn reported_sequence_numbers(begin_seq: u16, end_seq: u16, t: u8) -> Vec<u16> {
let step = 1u32 << (t & 0x0F);
let span = u32::from(end_seq.wrapping_sub(begin_seq));
(0..span)
.map(|offset| begin_seq.wrapping_add(offset as u16))
.filter(|seq| u32::from(*seq) % step == 0)
.collect()
}
impl RLEReportBlock {
pub fn from_flags(
is_loss_rle: bool,
ssrc: u32,
begin_seq: u16,
end_seq: u16,
t: u8,
flags: &[bool],
) -> Self {
let mut chunks = vec![];
let mut i = 0;
while i < flags.len() {
let value = flags[i];
let run = flags[i..].iter().take_while(|f| **f == value).count();
if run >= BIT_VECTOR_LENGTH {
let run = run.min(MAX_RUN_LENGTH);
chunks.push(Chunk(((value as u16) << 14) | run as u16));
i += run;
} else {
let mut vector = 0x8000u16;
for (bit, flag) in flags[i..].iter().take(BIT_VECTOR_LENGTH).enumerate() {
if *flag {
vector |= 1 << (BIT_VECTOR_LENGTH - 1 - bit);
}
}
chunks.push(Chunk(vector));
i += BIT_VECTOR_LENGTH;
}
}
RLEReportBlock {
is_loss_rle,
t: t & 0x0F,
ssrc,
begin_seq,
end_seq,
chunks,
}
}
pub fn flags(&self) -> Vec<bool> {
let count = reported_sequence_numbers(self.begin_seq, self.end_seq, self.t).len();
let mut flags = Vec::with_capacity(count);
for chunk in &self.chunks {
if flags.len() >= count {
break;
}
match chunk.chunk_type() {
ChunkType::RunLength => {
let value = chunk.run_type().unwrap_or(0) == 1;
let run = usize::from(chunk.value()).min(count - flags.len());
flags.extend(std::iter::repeat_n(value, run));
}
ChunkType::BitVector => {
for bit in 0..BIT_VECTOR_LENGTH {
if flags.len() >= count {
break;
}
flags.push(chunk.value() & (1 << (BIT_VECTOR_LENGTH - 1 - bit)) != 0);
}
}
ChunkType::TerminatingNull => break,
}
}
flags.resize(count, false);
flags
}
}
impl fmt::Display for RLEReportBlock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl Packet for RLEReportBlock {
fn header(&self) -> Header {
Header::default()
}
fn destination_ssrc(&self) -> Vec<u32> {
vec![self.ssrc]
}
fn raw_size(&self) -> usize {
XR_HEADER_LENGTH + RLE_REPORT_BLOCK_MIN_LENGTH as usize + self.wire_chunks() * 2
}
fn as_any(&self) -> &dyn Any {
self
}
fn equal(&self, other: &dyn Packet) -> bool {
other.as_any().downcast_ref::<RLEReportBlock>() == Some(self)
}
fn cloned(&self) -> Box<dyn Packet> {
Box::new(self.clone())
}
}
impl MarshalSize for RLEReportBlock {
fn marshal_size(&self) -> usize {
self.raw_size()
}
}
impl Marshal for RLEReportBlock {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
self.validate()?;
if self.raw_size() / 4 - 1 > u16::MAX as usize {
return Err(Error::InvalidBlockSize);
}
if buf.remaining_mut() < self.marshal_size() {
return Err(Error::BufferTooShort);
}
let h = self.xr_header();
let n = h.marshal_to(buf)?;
buf = &mut buf[n..];
buf.put_u32(self.ssrc);
buf.put_u16(self.begin_seq);
buf.put_u16(self.end_seq);
for chunk in &self.chunks {
buf.put_u16(chunk.0);
}
if self.wire_chunks() != self.chunks.len() {
buf.put_u16(0);
}
Ok(self.marshal_size())
}
}
impl Unmarshal for RLEReportBlock {
fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
if raw_packet.remaining() < XR_HEADER_LENGTH {
return Err(Error::PacketTooShort);
}
let xr_header = XRHeader::unmarshal(raw_packet)?;
let block_length = match xr_header.block_length.checked_mul(4) {
Some(length) => length,
None => return Err(Error::InvalidBlockSize),
};
if block_length < RLE_REPORT_BLOCK_MIN_LENGTH
|| !(block_length - RLE_REPORT_BLOCK_MIN_LENGTH).is_multiple_of(2)
|| raw_packet.remaining() < block_length as usize
{
return Err(Error::PacketTooShort);
}
if xr_header.block_type != BlockType::LossRLE
&& xr_header.block_type != BlockType::DuplicateRLE
{
return Err(Error::WrongType);
}
let is_loss_rle = xr_header.block_type == BlockType::LossRLE;
let t = xr_header.type_specific & 0x0F;
let ssrc = raw_packet.get_u32();
let begin_seq = raw_packet.get_u16();
let end_seq = raw_packet.get_u16();
let remaining = block_length - RLE_REPORT_BLOCK_MIN_LENGTH;
let mut chunks = vec![];
for _ in 0..remaining / 2 {
chunks.push(Chunk(raw_packet.get_u16()));
}
while chunks.last() == Some(&Chunk(0)) {
chunks.pop();
}
let block = RLEReportBlock {
is_loss_rle,
t,
ssrc,
begin_seq,
end_seq,
chunks,
};
block.validate()?;
Ok(block)
}
}