use std::collections::VecDeque;
use crate::rtp_::Pt;
use super::PacketError;
const F_BIT: u8 = 0x80;
const MAX_TS_OFFSET: u32 = 0x3fff;
const MAX_BLOCK_LEN: usize = 0x3ff;
const MAX_REDUNDANT_BLOCKS: usize = 32;
pub(crate) const MAX_RED_RECOVERY_DEPTH: u64 = 8;
#[derive(Debug, Clone)]
pub struct RedundantBlock {
pub pt: u8,
pub timestamp_offset: u32,
pub payload: Vec<u8>,
}
impl RedundantBlock {
pub fn fits(&self) -> bool {
self.timestamp_offset <= MAX_TS_OFFSET && self.payload.len() <= MAX_BLOCK_LEN
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedBlock<'a> {
pub pt: u8,
pub timestamp_offset: u32,
pub payload: &'a [u8],
pub is_primary: bool,
}
pub struct RedEncoder;
impl RedEncoder {
pub fn encode(primary_pt: u8, primary: &[u8], redundant: &[RedundantBlock]) -> Vec<u8> {
let blocks: Vec<&RedundantBlock> = redundant
.iter()
.filter(|b| b.fits())
.take(MAX_REDUNDANT_BLOCKS)
.collect();
let mut out = Vec::with_capacity(primary.len() + blocks.len() * 4 + 1);
for b in &blocks {
let ts = b.timestamp_offset;
let len = b.payload.len() as u32;
out.push(F_BIT | (b.pt & 0x7f));
out.push((ts >> 6) as u8);
out.push((((ts & 0x3f) << 2) | (len >> 8)) as u8);
out.push((len & 0xff) as u8);
}
out.push(primary_pt & 0x7f);
for b in &blocks {
out.extend_from_slice(&b.payload);
}
out.extend_from_slice(primary);
out
}
}
pub struct RedDecoder;
impl RedDecoder {
pub fn decode(data: &[u8]) -> Result<Vec<RedBlock<'_>>, PacketError> {
struct Hdr {
pt: u8,
ts_offset: u32,
len: Option<usize>,
}
let mut hdrs: Vec<Hdr> = Vec::new();
let mut i = 0;
loop {
let first = *data.get(i).ok_or(PacketError::ErrRedCorruptedPacket)?;
if first & F_BIT == 0 {
hdrs.push(Hdr {
pt: first & 0x7f,
ts_offset: 0,
len: None,
});
i += 1;
break;
}
if hdrs.len() >= MAX_REDUNDANT_BLOCKS {
return Err(PacketError::ErrRedCorruptedPacket);
}
let h = data
.get(i..i + 4)
.ok_or(PacketError::ErrRedCorruptedPacket)?;
let ts_offset = ((h[1] as u32) << 6) | ((h[2] as u32) >> 2);
let len = (((h[2] as usize) & 0x03) << 8) | (h[3] as usize);
hdrs.push(Hdr {
pt: h[0] & 0x7f,
ts_offset,
len: Some(len),
});
i += 4;
}
let mut out = Vec::with_capacity(hdrs.len());
for h in &hdrs {
match h.len {
Some(len) => {
let payload = data
.get(i..i + len)
.ok_or(PacketError::ErrRedCorruptedPacket)?;
out.push(RedBlock {
pt: h.pt,
timestamp_offset: h.ts_offset,
payload,
is_primary: false,
});
i += len;
}
None => {
out.push(RedBlock {
pt: h.pt,
timestamp_offset: 0,
payload: &data[i..],
is_primary: true,
});
}
}
}
Ok(out)
}
}
pub(crate) fn red_same_pt_blocks<'a>(
redundant: &'a [RedBlock<'a>],
primary_pt: u8,
) -> impl Iterator<Item = &'a RedBlock<'a>> {
redundant
.iter()
.filter(move |b| b.pt == primary_pt && b.timestamp_offset > 0)
}
#[derive(Debug)]
pub(crate) struct RedSender {
red_pt: Pt,
primary_pt: Pt,
distances: Box<[u32]>,
history: VecDeque<(Vec<u8>, u32)>,
}
impl RedSender {
pub(crate) fn new(red_pt: Pt, primary_pt: Pt, distances: &[u32]) -> Self {
RedSender {
red_pt,
primary_pt,
distances: distances.into(),
history: VecDeque::new(),
}
}
pub(crate) fn red_pt(&self) -> Pt {
self.red_pt
}
pub(crate) fn sync(&mut self, red_pt: Pt, primary_pt: Pt, distances: &[u32]) {
self.red_pt = red_pt;
self.primary_pt = primary_pt;
if *self.distances != *distances {
self.distances = distances.into();
self.trim_history();
}
}
pub(crate) fn wrap(&mut self, payload: Vec<u8>, rtp_time: u32, budget: usize) -> Vec<u8> {
let primary_pt = *self.primary_pt;
let len = self.history.len();
if payload.len() + 1 > budget {
self.history.push_back((payload.clone(), rtp_time));
self.trim_history();
return payload;
}
let mut remaining = budget - payload.len() - 1;
let mut kept: Vec<RedundantBlock> = Vec::new();
for &d in self.distances.iter() {
let Some((prev, prev_time)) = len
.checked_sub(d as usize)
.and_then(|i| self.history.get(i))
else {
continue;
};
let block = RedundantBlock {
pt: primary_pt,
timestamp_offset: rtp_time.wrapping_sub(*prev_time),
payload: prev.clone(),
};
if !block.fits() {
continue;
}
let cost = 4 + block.payload.len();
if cost > remaining {
break;
}
remaining -= cost;
kept.push(block);
}
kept.reverse();
let bytes = RedEncoder::encode(primary_pt, &payload, &kept);
self.history.push_back((payload, rtp_time));
self.trim_history();
bytes
}
fn trim_history(&mut self) {
let max_distance = self.distances.last().copied().unwrap_or(1) as usize;
while self.history.len() > max_distance {
self.history.pop_front();
}
}
}
#[cfg(test)]
mod test {
use super::*;
fn red_sender(distances: &[u32]) -> RedSender {
RedSender::new(Pt::new_with_value(63), Pt::new_with_value(111), distances)
}
const WRAP_BUDGET: usize = 1200;
#[test]
fn red_sender_wrap_builds_redundancy_from_history() {
let mut red = red_sender(&[1]);
let first = red.wrap(vec![1, 2, 3], 1000, WRAP_BUDGET);
let blocks = RedDecoder::decode(&first).unwrap();
assert_eq!(blocks.len(), 1);
assert!(blocks[0].is_primary);
assert_eq!(blocks[0].payload, &[1, 2, 3]);
let second = red.wrap(vec![4, 5], 1960, WRAP_BUDGET);
let blocks = RedDecoder::decode(&second).unwrap();
assert_eq!(blocks.len(), 2);
assert!(!blocks[0].is_primary);
assert_eq!(blocks[0].pt, 111);
assert_eq!(blocks[0].timestamp_offset, 960); assert_eq!(blocks[0].payload, &[1, 2, 3]);
assert!(blocks[1].is_primary);
assert_eq!(blocks[1].payload, &[4, 5]);
}
#[test]
fn red_sender_wrap_multi_distance_emits_levels_oldest_first() {
let mut red = red_sender(&[1, 3]);
for i in 0..4u32 {
red.wrap(vec![i as u8], i * 960, WRAP_BUDGET);
}
let fifth = red.wrap(vec![42], 4 * 960, WRAP_BUDGET);
let blocks = RedDecoder::decode(&fifth).unwrap();
assert_eq!(blocks.len(), 3);
assert!(!blocks[0].is_primary);
assert_eq!(blocks[0].timestamp_offset, 3 * 960);
assert_eq!(blocks[0].payload, &[1]);
assert!(!blocks[1].is_primary);
assert_eq!(blocks[1].timestamp_offset, 960);
assert_eq!(blocks[1].payload, &[3]);
assert!(blocks[2].is_primary);
assert_eq!(blocks[2].payload, &[42]);
}
#[test]
fn red_sender_wrap_skips_redundancy_that_overflows_rfc_fields() {
let mut red = red_sender(&[1]);
red.wrap(vec![1], 0, WRAP_BUDGET);
let out = red.wrap(vec![2], 0x4000, WRAP_BUDGET);
let blocks = RedDecoder::decode(&out).unwrap();
assert_eq!(blocks.len(), 1);
assert!(blocks[0].is_primary);
}
#[test]
fn red_sender_wrap_sheds_deepest_redundancy_to_fit_budget() {
let mut red = red_sender(&[1, 2]);
let budget = 300;
let frame = |b: u8| vec![b; 100];
red.wrap(frame(0xAA), 0, budget); red.wrap(frame(0xBB), 960, budget); let out = red.wrap(frame(0xCC), 1920, budget);
assert!(
out.len() <= budget,
"encoded RED {} > budget {budget}",
out.len()
);
let blocks = RedDecoder::decode(&out).unwrap();
assert_eq!(blocks.len(), 2, "distance 2 shed to fit budget");
assert!(!blocks[0].is_primary);
assert_eq!(
blocks[0].payload,
&frame(0xBB)[..],
"kept the shallowest (distance 1)"
);
assert!(blocks[1].is_primary);
assert_eq!(blocks[1].payload, &frame(0xCC)[..]);
let mut red = red_sender(&[1, 2]);
red.wrap(frame(0xAA), 0, WRAP_BUDGET);
red.wrap(frame(0xBB), 960, WRAP_BUDGET);
let out = red.wrap(frame(0xCC), 1920, WRAP_BUDGET);
assert_eq!(
RedDecoder::decode(&out).unwrap().len(),
3,
"all levels fit a large budget"
);
}
#[test]
fn red_sender_wrap_primary_header_does_not_exceed_budget() {
let mut red = red_sender(&[1]);
let out = red.wrap(vec![0xAA; WRAP_BUDGET], 960, WRAP_BUDGET);
assert!(
out.len() <= WRAP_BUDGET,
"RED payload {} > budget {WRAP_BUDGET}",
out.len()
);
}
#[test]
fn red_sender_sync_trims_history_on_pattern_change() {
let mut red = red_sender(&[1, 3]);
for i in 0..4u32 {
red.wrap(vec![i as u8], i * 960, WRAP_BUDGET);
}
red.sync(Pt::new_with_value(63), Pt::new_with_value(111), &[1]);
let out = red.wrap(vec![42], 4 * 960, WRAP_BUDGET);
let blocks = RedDecoder::decode(&out).unwrap();
assert_eq!(blocks.len(), 2, "only distance 1 survives the trim");
assert_eq!(blocks[0].timestamp_offset, 960);
}
#[test]
fn primary_only_roundtrip() {
let bytes = RedEncoder::encode(96, &[1, 2, 3], &[]);
assert_eq!(bytes, vec![96, 1, 2, 3]);
let blocks = RedDecoder::decode(&bytes).unwrap();
assert_eq!(blocks.len(), 1);
assert!(blocks[0].is_primary);
assert_eq!(blocks[0].pt, 96);
assert_eq!(blocks[0].timestamp_offset, 0);
assert_eq!(blocks[0].payload, &[1, 2, 3]);
}
#[test]
fn one_redundant_block_roundtrip() {
let red = [RedundantBlock {
pt: 96,
timestamp_offset: 960,
payload: vec![9, 9],
}];
let bytes = RedEncoder::encode(96, &[1, 2, 3], &red);
assert_eq!(&bytes[..4], &[0xE0, 15, 0, 2]);
assert_eq!(bytes[4], 96); assert_eq!(&bytes[5..], &[9, 9, 1, 2, 3]);
let blocks = RedDecoder::decode(&bytes).unwrap();
assert_eq!(blocks.len(), 2);
assert!(!blocks[0].is_primary);
assert_eq!(blocks[0].timestamp_offset, 960);
assert_eq!(blocks[0].payload, &[9, 9]);
assert!(blocks[1].is_primary);
assert_eq!(blocks[1].payload, &[1, 2, 3]);
}
#[test]
fn encode_skips_oversized_blocks() {
let bad_offset = RedundantBlock {
pt: 96,
timestamp_offset: 0x4000, payload: vec![1, 2],
};
let bad_len = RedundantBlock {
pt: 96,
timestamp_offset: 100,
payload: vec![0u8; 2000], };
let bytes = RedEncoder::encode(96, &[7, 7], &[bad_offset, bad_len]);
let blocks = RedDecoder::decode(&bytes).unwrap();
assert_eq!(blocks.len(), 1, "oversized blocks must be skipped");
assert!(blocks[0].is_primary);
assert_eq!(blocks[0].payload, &[7, 7]);
}
#[test]
fn truncated_header_is_error_not_panic() {
assert!(RedDecoder::decode(&[0x80, 0x00]).is_err()); assert!(RedDecoder::decode(&[]).is_err()); }
#[test]
fn block_length_past_end_is_error() {
let b = [0x80 | 96, 0, 0, 200, 96];
assert!(RedDecoder::decode(&b).is_err());
}
#[test]
fn never_panics_on_arbitrary_input() {
for a in 0u16..=255 {
for b in 0u16..=255 {
let _ = RedDecoder::decode(&[a as u8, b as u8]);
}
}
}
#[test]
fn decode_rejects_too_many_redundant_blocks() {
fn red_with_redundant_blocks(n: usize) -> Vec<u8> {
let mut data = Vec::with_capacity(n * 4 + 1);
for _ in 0..n {
data.extend_from_slice(&[F_BIT | 96, 0, 0, 0]); }
data.push(96); data
}
let ok = red_with_redundant_blocks(MAX_REDUNDANT_BLOCKS);
let blocks = RedDecoder::decode(&ok).expect("max redundant blocks is allowed");
assert_eq!(blocks.len(), MAX_REDUNDANT_BLOCKS + 1);
assert!(RedDecoder::decode(&red_with_redundant_blocks(MAX_REDUNDANT_BLOCKS + 1)).is_err());
assert!(RedDecoder::decode(&red_with_redundant_blocks(360)).is_err());
}
#[test]
fn same_pt_blocks_skip_foreign_pt_and_primary_offset() {
let block = |pt, ts| RedBlock {
pt,
timestamp_offset: ts,
payload: &[0u8],
is_primary: false,
};
let redundant = vec![
block(111, 1920),
block(96, 960),
block(111, 0),
block(111, 960),
];
let offsets: Vec<u32> = red_same_pt_blocks(&redundant, 111)
.map(|b| b.timestamp_offset)
.collect();
assert_eq!(offsets, vec![1920, 960]);
}
#[test]
fn public_encoder_output_is_accepted_by_public_decoder() {
let redundant: Vec<_> = (0..33)
.map(|i| RedundantBlock {
pt: 111,
timestamp_offset: i + 1,
payload: vec![i as u8],
})
.collect();
let encoded = RedEncoder::encode(111, &[0xAA], &redundant);
assert!(
RedDecoder::decode(&encoded).is_ok(),
"the public decoder must accept packets produced by the public encoder"
);
}
}