Skip to main content

rtci_rtcp/extended_report/
mod.rs

1#[cfg(test)]
2mod extended_report_test;
3#[cfg(test)]
4mod report_blocks_test;
5
6/// Delay Since Last Receiver Report blocks, for round-trip time between receivers.
7pub mod dlrr;
8/// ECN Summary Report blocks (RFC 6679 section 5.2).
9pub mod ecn;
10/// Packet Receipt Times blocks.
11pub mod prt;
12pub mod rle;
13/// Receiver Reference Time blocks, which anchor DLRR round-trip calculations.
14pub mod rrt;
15/// Statistics Summary blocks: loss, duplicate, jitter and TTL ranges.
16pub mod ssr;
17/// An unparsed block, for types this crate does not model.
18pub mod unknown;
19/// VoIP Metrics blocks, which carry call-quality estimates.
20pub mod vm;
21
22pub use dlrr::{DLRRReport, DLRRReportBlock};
23pub use ecn::{EcnSummaryReport, EcnSummaryReportBlock};
24pub use prt::PacketReceiptTimesReportBlock;
25pub use rle::{
26    Chunk, ChunkType, DuplicateRLEReportBlock, LossRLEReportBlock, RLEReportBlock,
27    reported_sequence_numbers,
28};
29pub use rrt::ReceiverReferenceTimeReportBlock;
30pub use ssr::{StatisticsSummaryReportBlock, TTLorHopLimitType};
31pub use unknown::UnknownReportBlock;
32pub use vm::VoIPMetricsReportBlock;
33
34use crate::Packet;
35use crate::header::{HEADER_LENGTH, Header, PacketType, SSRC_LENGTH, read_packet};
36use crate::util::get_padding_size;
37use bytes::{Buf, BufMut, Bytes};
38use shared::{
39    error::{Error, Result},
40    marshal::{Marshal, MarshalSize, Unmarshal},
41};
42use std::any::Any;
43use std::fmt;
44
45const XR_HEADER_LENGTH: usize = 4;
46
47/// BlockType specifies the type of report in a report block
48/// Extended Report block types from RFC 3611.
49///
50/// The enum converts to and from the type octet with `u8::from` / `BlockType::from`. A type
51/// that later documents define is kept as [`BlockType::Other`], so such a block is written
52/// back as what it was.
53#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum BlockType {
56    #[default]
57    /// No block type: the type octet 0.
58    Unknown,
59    /// Loss RLE report block ([RFC 3611] §4.1).
60    LossRLE, // 1, RFC 3611, section 4.1
61    /// Duplicate RLE report block ([RFC 3611] §4.2).
62    DuplicateRLE, // 2, RFC 3611, section 4.2
63    /// Packet Receipt Times report block ([RFC 3611] §4.3).
64    PacketReceiptTimes, // 3, RFC 3611, section 4.3
65    /// Receiver Reference Time report block ([RFC 3611] §4.4).
66    ReceiverReferenceTime, // 4, RFC 3611, section 4.4
67    /// Delay Since Last Receiver Report block ([RFC 3611] §4.5).
68    DLRR, // 5, RFC 3611, section 4.5
69    /// Statistics Summary report block ([RFC 3611] §4.6).
70    StatisticsSummary, // 6, RFC 3611, section 4.6
71    /// VoIP Metrics report block ([RFC 3611] §4.7).
72    VoIPMetrics, // 7, RFC 3611, section 4.7
73    /// ECN Summary Report block ([RFC 6679] §5.2).
74    EcnSummary, // 13, RFC 6679, section 5.2
75    /// A block type this crate does not model, with its type octet.
76    Other(u8),
77}
78
79impl From<u8> for BlockType {
80    fn from(v: u8) -> Self {
81        match v {
82            0 => BlockType::Unknown,
83            1 => BlockType::LossRLE,
84            2 => BlockType::DuplicateRLE,
85            3 => BlockType::PacketReceiptTimes,
86            4 => BlockType::ReceiverReferenceTime,
87            5 => BlockType::DLRR,
88            6 => BlockType::StatisticsSummary,
89            7 => BlockType::VoIPMetrics,
90            13 => BlockType::EcnSummary,
91            other => BlockType::Other(other),
92        }
93    }
94}
95
96impl From<BlockType> for u8 {
97    fn from(t: BlockType) -> Self {
98        match t {
99            BlockType::Unknown => 0,
100            BlockType::LossRLE => 1,
101            BlockType::DuplicateRLE => 2,
102            BlockType::PacketReceiptTimes => 3,
103            BlockType::ReceiverReferenceTime => 4,
104            BlockType::DLRR => 5,
105            BlockType::StatisticsSummary => 6,
106            BlockType::VoIPMetrics => 7,
107            BlockType::EcnSummary => 13,
108            BlockType::Other(other) => other,
109        }
110    }
111}
112
113/// converts the Extended report block types into readable strings
114impl fmt::Display for BlockType {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        let s = match *self {
117            BlockType::LossRLE => "LossRLEReportBlockType",
118            BlockType::DuplicateRLE => "DuplicateRLEReportBlockType",
119            BlockType::PacketReceiptTimes => "PacketReceiptTimesReportBlockType",
120            BlockType::ReceiverReferenceTime => "ReceiverReferenceTimeReportBlockType",
121            BlockType::DLRR => "DLRRReportBlockType",
122            BlockType::StatisticsSummary => "StatisticsSummaryReportBlockType",
123            BlockType::VoIPMetrics => "VoIPMetricsReportBlockType",
124            BlockType::EcnSummary => "EcnSummaryReportBlockType",
125            _ => "UnknownReportBlockType",
126        };
127        write!(f, "{s}")
128    }
129}
130
131/// TypeSpecificField as described in RFC 3611 section 4.5. In typical
132/// cases, users of ExtendedReports shouldn't need to access this,
133/// and should instead use the corresponding fields in the actual
134/// report blocks themselves.
135pub type TypeSpecificField = u8;
136
137/// XRHeader defines the common fields that must appear at the start
138/// of each report block. In typical cases, users of ExtendedReports
139/// shouldn't need to access this. For locally-constructed report
140/// blocks, these values will not be accurate until the corresponding
141/// packet is marshaled.
142#[derive(Debug, Default, PartialEq, Eq, Clone)]
143pub struct XRHeader {
144    /// Which kind of report block follows.
145    pub block_type: BlockType,
146    /// Bits whose meaning depends on the block type.
147    pub type_specific: TypeSpecificField,
148    /// The block's length in 32-bit words, excluding this header.
149    pub block_length: u16,
150}
151
152impl MarshalSize for XRHeader {
153    fn marshal_size(&self) -> usize {
154        XR_HEADER_LENGTH
155    }
156}
157
158impl Marshal for XRHeader {
159    /// marshal_to encodes the ExtendedReport in binary
160    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
161        if buf.remaining_mut() < XR_HEADER_LENGTH {
162            return Err(Error::BufferTooShort);
163        }
164
165        buf.put_u8(self.block_type.into());
166        buf.put_u8(self.type_specific);
167        buf.put_u16(self.block_length);
168
169        Ok(XR_HEADER_LENGTH)
170    }
171}
172
173impl Unmarshal for XRHeader {
174    /// Unmarshal decodes the ExtendedReport from binary
175    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
176    where
177        Self: Sized,
178        B: Buf,
179    {
180        if raw_packet.remaining() < XR_HEADER_LENGTH {
181            return Err(Error::PacketTooShort);
182        }
183
184        let block_type: BlockType = raw_packet.get_u8().into();
185        let type_specific = raw_packet.get_u8();
186        let block_length = raw_packet.get_u16();
187
188        Ok(XRHeader {
189            block_type,
190            type_specific,
191            block_length,
192        })
193    }
194}
195/// The ExtendedReport packet is an Implementation of RTCP Extended
196/// reports defined in RFC 3611. It is used to convey detailed
197/// information about an RTP stream. Each packet contains one or
198/// more report blocks, each of which conveys a different kind of
199/// information.
200///
201///  0                   1                   2                   3
202///  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
203/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
204/// |V=2|P|reserved |   PT=XR=207   |             length            |
205/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206/// |                              ssrc                             |
207/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208/// :                         report blocks                         :
209/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210#[derive(Debug, PartialEq, Default, Clone)]
211pub struct ExtendedReport {
212    /// The SSRC of the sender of this extended report.
213    pub sender_ssrc: u32,
214    /// The report blocks this packet carries.
215    pub reports: Vec<Box<dyn Packet>>,
216}
217
218impl fmt::Display for ExtendedReport {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        write!(f, "{self:?}")
221    }
222}
223
224impl Packet for ExtendedReport {
225    /// Header returns the Header associated with this packet.
226    fn header(&self) -> Header {
227        Header {
228            // Every report block is a whole number of 32-bit words (RFC 3611 3).
229            padding: false,
230            count: 0,
231            packet_type: PacketType::ExtendedReport,
232            length: ((self.marshal_size() / 4) - 1) as u16,
233        }
234    }
235
236    /// destination_ssrc returns an array of ssrc values that this packet refers to.
237    fn destination_ssrc(&self) -> Vec<u32> {
238        let mut ssrc = vec![];
239        for p in &self.reports {
240            ssrc.extend(p.destination_ssrc());
241        }
242        ssrc
243    }
244
245    fn raw_size(&self) -> usize {
246        let mut reps_length = 0;
247        for rep in &self.reports {
248            reps_length += rep.marshal_size();
249        }
250        HEADER_LENGTH + SSRC_LENGTH + reps_length
251    }
252
253    fn as_any(&self) -> &dyn Any {
254        self
255    }
256
257    fn equal(&self, other: &dyn Packet) -> bool {
258        other.as_any().downcast_ref::<ExtendedReport>() == Some(self)
259    }
260
261    fn cloned(&self) -> Box<dyn Packet> {
262        Box::new(self.clone())
263    }
264}
265
266impl MarshalSize for ExtendedReport {
267    fn marshal_size(&self) -> usize {
268        let l = self.raw_size();
269        // align to 32-bit boundary
270        l + get_padding_size(l)
271    }
272}
273
274impl Marshal for ExtendedReport {
275    /// marshal_to encodes the ExtendedReport in binary
276    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
277        if buf.remaining_mut() < self.marshal_size() {
278            return Err(Error::BufferTooShort);
279        }
280
281        let h = self.header();
282        let n = h.marshal_to(buf)?;
283        buf = &mut buf[n..];
284
285        buf.put_u32(self.sender_ssrc);
286
287        for report in &self.reports {
288            let n = report.marshal_to(buf)?;
289            buf = &mut buf[n..];
290        }
291
292        Ok(self.marshal_size())
293    }
294}
295
296impl ExtendedReport {
297    /// Parses one report block, `block` holding exactly that block.
298    ///
299    /// A block of a type this crate does not model, and a block of a known type that fails its
300    /// own parse (a length its type does not allow, a value its type forbids), is kept as an
301    /// [`UnknownReportBlock`] with its type and bytes: one such block costs neither the blocks
302    /// around it nor the packets around this one (RFC 3611 4: a receiver skips what it cannot
303    /// use by the block length).
304    fn unmarshal_block(block_type: BlockType, block: Bytes) -> Result<Box<dyn Packet>> {
305        let raw_block = &mut block.clone();
306        let parsed: Result<Box<dyn Packet>> = match block_type {
307            BlockType::LossRLE => {
308                LossRLEReportBlock::unmarshal(raw_block).map(|b| Box::new(b) as Box<dyn Packet>)
309            }
310            BlockType::DuplicateRLE => DuplicateRLEReportBlock::unmarshal(raw_block)
311                .map(|b| Box::new(b) as Box<dyn Packet>),
312            BlockType::PacketReceiptTimes => PacketReceiptTimesReportBlock::unmarshal(raw_block)
313                .map(|b| Box::new(b) as Box<dyn Packet>),
314            BlockType::ReceiverReferenceTime => {
315                ReceiverReferenceTimeReportBlock::unmarshal(raw_block)
316                    .map(|b| Box::new(b) as Box<dyn Packet>)
317            }
318            BlockType::DLRR => {
319                DLRRReportBlock::unmarshal(raw_block).map(|b| Box::new(b) as Box<dyn Packet>)
320            }
321            BlockType::StatisticsSummary => StatisticsSummaryReportBlock::unmarshal(raw_block)
322                .map(|b| Box::new(b) as Box<dyn Packet>),
323            BlockType::VoIPMetrics => {
324                VoIPMetricsReportBlock::unmarshal(raw_block).map(|b| Box::new(b) as Box<dyn Packet>)
325            }
326            BlockType::EcnSummary => {
327                EcnSummaryReportBlock::unmarshal(raw_block).map(|b| Box::new(b) as Box<dyn Packet>)
328            }
329            _ => Err(Error::WrongType),
330        };
331
332        match parsed {
333            Ok(report) => Ok(report),
334            Err(_) => Ok(Box::new(UnknownReportBlock::unmarshal(&mut block.clone())?)),
335        }
336    }
337}
338
339impl Unmarshal for ExtendedReport {
340    /// Unmarshal decodes the ExtendedReport from binary
341    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
342    where
343        Self: Sized,
344        B: Buf,
345    {
346        // The padding the P bit announces ends the packet before the report blocks do. The
347        // five reserved bits that share the first octet are ignored (RFC 3611 2).
348        let (header, mut body) = read_packet(raw_packet)?;
349        if header.packet_type != PacketType::ExtendedReport {
350            return Err(Error::WrongType);
351        }
352        if body.len() < SSRC_LENGTH {
353            return Err(Error::PacketTooShort);
354        }
355
356        let sender_ssrc = body.get_u32();
357
358        let mut reports = vec![];
359        while body.has_remaining() {
360            // Every block says how long it is, whatever its type, and that is what frames it.
361            if body.len() < XR_HEADER_LENGTH {
362                return Err(Error::PacketTooShort);
363            }
364            let block_length = u16::from_be_bytes([body[2], body[3]]) as usize * 4;
365            if body.len() < XR_HEADER_LENGTH + block_length {
366                return Err(Error::PacketTooShort);
367            }
368            let block_type: BlockType = body[0].into();
369            let block = body.split_to(XR_HEADER_LENGTH + block_length);
370
371            reports.push(Self::unmarshal_block(block_type, block)?);
372        }
373
374        Ok(ExtendedReport {
375            sender_ssrc,
376            reports,
377        })
378    }
379}