rtci_rtcp/extended_report/rle.rs
1//! Loss and Duplicate RLE report blocks.
2//!
3//! Both blocks report per-packet status over a sequence-number range, run-length encoded: a
4//! [`Chunk`] is either a run of identical values or an explicit 15-bit vector. That keeps a report
5//! covering a long range compact while still describing individual packets.
6//!
7//! The same structure serves both blocks; [`RLEReportBlock::is_loss_rle`](crate::extended_report::rle::RLEReportBlock::is_loss_rle) selects which.
8use super::*;
9
10const RLE_REPORT_BLOCK_MIN_LENGTH: u16 = 8;
11
12/// ChunkType enumerates the three kinds of chunks described in RFC 3611 section 4.1.
13#[derive(Debug, Copy, Clone, PartialEq, Eq)]
14pub enum ChunkType {
15 /// A run-length chunk: a bit value repeated a stated number of times.
16 RunLength = 0,
17 /// A bit-vector chunk: 15 explicit per-packet bits.
18 BitVector = 1,
19 /// The terminating null chunk, which pads the block to a word boundary.
20 TerminatingNull = 2,
21}
22
23/// Chunk as defined in RFC 3611, section 4.1. These represent information
24/// about packet losses and packet duplication. They have three representations:
25///
26/// Run Length Chunk:
27///
28/// 0 1
29/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
30/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
31/// |C|R| run length |
32/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
33///
34/// Bit Vector Chunk:
35///
36/// 0 1
37/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
38/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
39/// |C| bit vector |
40/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
41///
42/// Terminating Null Chunk:
43///
44/// 0 1
45/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
46/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
47/// |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
48/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
49#[derive(Debug, Default, PartialEq, Eq, Clone)]
50pub struct Chunk(pub u16);
51
52impl fmt::Display for Chunk {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self.chunk_type() {
55 ChunkType::RunLength => {
56 let run_type = self.run_type().unwrap_or(0);
57 write!(f, "[RunLength type={}, length={}]", run_type, self.value())
58 }
59 ChunkType::BitVector => write!(f, "[BitVector {:#b}", self.value()),
60 ChunkType::TerminatingNull => write!(f, "[TerminatingNull]"),
61 }
62 }
63}
64impl Chunk {
65 /// chunk_type returns the ChunkType that this Chunk represents
66 pub fn chunk_type(&self) -> ChunkType {
67 if self.0 == 0 {
68 ChunkType::TerminatingNull
69 } else if (self.0 >> 15) == 0 {
70 ChunkType::RunLength
71 } else {
72 ChunkType::BitVector
73 }
74 }
75
76 /// run_type returns the run_type that this Chunk represents. It is
77 /// only valid if ChunkType is RunLengthChunkType.
78 pub fn run_type(&self) -> Result<u8> {
79 if self.chunk_type() != ChunkType::RunLength {
80 Err(Error::WrongChunkType)
81 } else {
82 Ok((self.0 >> 14) as u8 & 0x01)
83 }
84 }
85
86 /// value returns the value represented in this Chunk
87 pub fn value(&self) -> u16 {
88 match self.chunk_type() {
89 ChunkType::RunLength => self.0 & 0x3FFF,
90 ChunkType::BitVector => self.0 & 0x7FFF,
91 ChunkType::TerminatingNull => 0,
92 }
93 }
94}
95
96/// RleReportBlock defines the common structure used by both
97/// Loss RLE report blocks (RFC 3611 §4.1) and Duplicate RLE
98/// report blocks (RFC 3611 §4.2).
99///
100/// 0 1 2 3
101/// 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
102/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103/// | BT = 1 or 2 | rsvd. | t | block length |
104/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105/// | ssrc of source |
106/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107/// | begin_seq | end_seq |
108/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109/// | chunk 1 | chunk 2 |
110/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111/// : ... :
112/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113/// | chunk n-1 | chunk n |
114/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115#[derive(Debug, Default, PartialEq, Eq, Clone)]
116pub struct RLEReportBlock {
117 //not included in marshal/unmarshal
118 /// `true` for a Loss RLE block, `false` for a Duplicate RLE block.
119 pub is_loss_rle: bool,
120 /// The block's `T` field.
121 pub t: u8,
122
123 //marshal/unmarshal
124 /// The SSRC whose packets are reported on.
125 pub ssrc: u32,
126 /// The first sequence number covered by this block.
127 pub begin_seq: u16,
128 /// One past the last sequence number covered.
129 pub end_seq: u16,
130 /// The run-length and bit-vector chunks encoding per-packet status.
131 pub chunks: Vec<Chunk>,
132}
133
134/// LossRLEReportBlock is used to report information about packet
135/// losses, as described in RFC 3611, section 4.1
136/// make sure to set is_loss_rle = true
137pub type LossRLEReportBlock = RLEReportBlock;
138
139/// DuplicateRLEReportBlock is used to report information about packet
140/// duplication, as described in RFC 3611, section 4.1
141/// make sure to set is_loss_rle = false
142pub type DuplicateRLEReportBlock = RLEReportBlock;
143
144impl RLEReportBlock {
145 /// Checks what RFC 3611 4.1 requires of the block's content.
146 fn validate(&self) -> Result<()> {
147 // "A report block MUST NOT report on a sequence number range of 65,534 or more."
148 if self.end_seq.wrapping_sub(self.begin_seq) >= 65534 {
149 return Err(Error::InvalidBlockSize);
150 }
151 for chunk in &self.chunks {
152 // The terminating null chunk "MUST NOT appear anywhere else": it is not one of
153 // the chunks here, it is added when the block is written and dropped when read.
154 if chunk.0 == 0 {
155 return Err(Error::WrongChunkType);
156 }
157 // A run length is "a value between 1 and 16,383". Zero with the run type 0 is
158 // the null chunk; zero with the run type 1 is nothing at all.
159 if chunk.chunk_type() == ChunkType::RunLength && chunk.value() == 0 {
160 return Err(Error::WrongChunkType);
161 }
162 }
163 Ok(())
164 }
165
166 /// The chunks on the wire: `chunks`, and a terminating null chunk when one is needed to
167 /// round the block up to a 32-bit boundary.
168 fn wire_chunks(&self) -> usize {
169 self.chunks.len() + self.chunks.len() % 2
170 }
171
172 /// The XR block header describing this block's type and length.
173 pub fn xr_header(&self) -> XRHeader {
174 XRHeader {
175 block_type: if self.is_loss_rle {
176 BlockType::LossRLE
177 } else {
178 BlockType::DuplicateRLE
179 },
180 type_specific: self.t & 0x0F,
181 block_length: (self.raw_size() / 4 - 1) as u16,
182 }
183 }
184}
185
186/// The longest run a run-length chunk holds (RFC 3611 section 4.1.1: 14 bits, 1 to 16,383).
187pub const MAX_RUN_LENGTH: usize = 16_383;
188/// The packets one bit-vector chunk describes (RFC 3611 section 4.1.2).
189pub const BIT_VECTOR_LENGTH: usize = 15;
190
191/// The sequence numbers of `begin_seq..end_seq` (modulo 2^16) a block with thinning `t`
192/// reports on: those that are a multiple of 2^t (RFC 3611 section 4.1).
193pub fn reported_sequence_numbers(begin_seq: u16, end_seq: u16, t: u8) -> Vec<u16> {
194 let step = 1u32 << (t & 0x0F);
195 let span = u32::from(end_seq.wrapping_sub(begin_seq));
196 (0..span)
197 .map(|offset| begin_seq.wrapping_add(offset as u16))
198 .filter(|seq| u32::from(*seq) % step == 0)
199 .collect()
200}
201
202impl RLEReportBlock {
203 /// A block reporting `flags`, one per sequence number [`reported_sequence_numbers`] gives
204 /// for `begin_seq..end_seq` and `t`: for a Loss RLE block `true` is "received", for a
205 /// Duplicate RLE block `true` is "duplicated" (RFC 3611 sections 4.1, 4.2).
206 ///
207 /// A run of 15 equal values or more is a run-length chunk, anything shorter goes into
208 /// bit vectors. The bits of a last bit vector past the end of the flags are zero (RFC 3611
209 /// section 4.1: "the remaining bits ... MUST be set to zero").
210 pub fn from_flags(
211 is_loss_rle: bool,
212 ssrc: u32,
213 begin_seq: u16,
214 end_seq: u16,
215 t: u8,
216 flags: &[bool],
217 ) -> Self {
218 let mut chunks = vec![];
219 let mut i = 0;
220 while i < flags.len() {
221 let value = flags[i];
222 let run = flags[i..].iter().take_while(|f| **f == value).count();
223 if run >= BIT_VECTOR_LENGTH {
224 let run = run.min(MAX_RUN_LENGTH);
225 chunks.push(Chunk(((value as u16) << 14) | run as u16));
226 i += run;
227 } else {
228 let mut vector = 0x8000u16;
229 for (bit, flag) in flags[i..].iter().take(BIT_VECTOR_LENGTH).enumerate() {
230 if *flag {
231 vector |= 1 << (BIT_VECTOR_LENGTH - 1 - bit);
232 }
233 }
234 chunks.push(Chunk(vector));
235 i += BIT_VECTOR_LENGTH;
236 }
237 }
238 RLEReportBlock {
239 is_loss_rle,
240 t: t & 0x0F,
241 ssrc,
242 begin_seq,
243 end_seq,
244 chunks,
245 }
246 }
247
248 /// The flag of each sequence number the block reports on, in order
249 /// ([`reported_sequence_numbers`]): what the chunks say, cut to that many. Bits of a bit
250 /// vector past the end of the range, and a terminating null chunk, are ignored (RFC 3611
251 /// section 4.1). A block whose chunks say less than the range has `false` for the rest.
252 pub fn flags(&self) -> Vec<bool> {
253 let count = reported_sequence_numbers(self.begin_seq, self.end_seq, self.t).len();
254 let mut flags = Vec::with_capacity(count);
255 for chunk in &self.chunks {
256 if flags.len() >= count {
257 break;
258 }
259 match chunk.chunk_type() {
260 ChunkType::RunLength => {
261 let value = chunk.run_type().unwrap_or(0) == 1;
262 let run = usize::from(chunk.value()).min(count - flags.len());
263 flags.extend(std::iter::repeat_n(value, run));
264 }
265 ChunkType::BitVector => {
266 for bit in 0..BIT_VECTOR_LENGTH {
267 if flags.len() >= count {
268 break;
269 }
270 flags.push(chunk.value() & (1 << (BIT_VECTOR_LENGTH - 1 - bit)) != 0);
271 }
272 }
273 ChunkType::TerminatingNull => break,
274 }
275 }
276 flags.resize(count, false);
277 flags
278 }
279}
280
281impl fmt::Display for RLEReportBlock {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 write!(f, "{self:?}")
284 }
285}
286
287impl Packet for RLEReportBlock {
288 fn header(&self) -> Header {
289 Header::default()
290 }
291
292 /// destination_ssrc returns an array of ssrc values that this report block refers to.
293 fn destination_ssrc(&self) -> Vec<u32> {
294 vec![self.ssrc]
295 }
296
297 fn raw_size(&self) -> usize {
298 XR_HEADER_LENGTH + RLE_REPORT_BLOCK_MIN_LENGTH as usize + self.wire_chunks() * 2
299 }
300
301 fn as_any(&self) -> &dyn Any {
302 self
303 }
304 fn equal(&self, other: &dyn Packet) -> bool {
305 other.as_any().downcast_ref::<RLEReportBlock>() == Some(self)
306 }
307 fn cloned(&self) -> Box<dyn Packet> {
308 Box::new(self.clone())
309 }
310}
311
312impl MarshalSize for RLEReportBlock {
313 fn marshal_size(&self) -> usize {
314 self.raw_size()
315 }
316}
317
318impl Marshal for RLEReportBlock {
319 /// marshal_to encodes the RLEReportBlock in binary
320 fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
321 self.validate()?;
322 if self.raw_size() / 4 - 1 > u16::MAX as usize {
323 return Err(Error::InvalidBlockSize);
324 }
325 if buf.remaining_mut() < self.marshal_size() {
326 return Err(Error::BufferTooShort);
327 }
328
329 let h = self.xr_header();
330 let n = h.marshal_to(buf)?;
331 buf = &mut buf[n..];
332
333 buf.put_u32(self.ssrc);
334 buf.put_u16(self.begin_seq);
335 buf.put_u16(self.end_seq);
336 for chunk in &self.chunks {
337 buf.put_u16(chunk.0);
338 }
339 if self.wire_chunks() != self.chunks.len() {
340 // The terminating null chunk.
341 buf.put_u16(0);
342 }
343
344 Ok(self.marshal_size())
345 }
346}
347
348impl Unmarshal for RLEReportBlock {
349 /// Unmarshal decodes the RLEReportBlock from binary
350 fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
351 where
352 Self: Sized,
353 B: Buf,
354 {
355 if raw_packet.remaining() < XR_HEADER_LENGTH {
356 return Err(Error::PacketTooShort);
357 }
358
359 let xr_header = XRHeader::unmarshal(raw_packet)?;
360 let block_length = match xr_header.block_length.checked_mul(4) {
361 Some(length) => length,
362 None => return Err(Error::InvalidBlockSize),
363 };
364 if block_length < RLE_REPORT_BLOCK_MIN_LENGTH
365 || !(block_length - RLE_REPORT_BLOCK_MIN_LENGTH).is_multiple_of(2)
366 || raw_packet.remaining() < block_length as usize
367 {
368 return Err(Error::PacketTooShort);
369 }
370
371 if xr_header.block_type != BlockType::LossRLE
372 && xr_header.block_type != BlockType::DuplicateRLE
373 {
374 return Err(Error::WrongType);
375 }
376 let is_loss_rle = xr_header.block_type == BlockType::LossRLE;
377 let t = xr_header.type_specific & 0x0F;
378
379 let ssrc = raw_packet.get_u32();
380 let begin_seq = raw_packet.get_u16();
381 let end_seq = raw_packet.get_u16();
382
383 let remaining = block_length - RLE_REPORT_BLOCK_MIN_LENGTH;
384 let mut chunks = vec![];
385 for _ in 0..remaining / 2 {
386 chunks.push(Chunk(raw_packet.get_u16()));
387 }
388
389 // "If the chunks do not end on a 32-bit boundary, a terminating null chunk is added":
390 // it pads, and is not one of the block's chunks.
391 while chunks.last() == Some(&Chunk(0)) {
392 chunks.pop();
393 }
394
395 let block = RLEReportBlock {
396 is_loss_rle,
397 t,
398 ssrc,
399 begin_seq,
400 end_seq,
401 chunks,
402 };
403 block.validate()?;
404
405 Ok(block)
406 }
407}