Skip to main content

rtci_rtcp/
reception_report.rs

1use crate::{header::*, packet::*, util::*};
2use shared::{
3    error::{Error, Result},
4    marshal::{Marshal, MarshalSize, Unmarshal},
5};
6
7use bytes::{Buf, BufMut};
8use std::any::Any;
9use std::fmt;
10
11#[cfg(test)]
12#[path = "reception_report_lost_test.rs"]
13mod reception_report_lost_test;
14
15pub(crate) const RECEPTION_REPORT_LENGTH: usize = 24;
16pub(crate) const FRACTION_LOST_OFFSET: usize = 4;
17pub(crate) const TOTAL_LOST_OFFSET: usize = 5;
18pub(crate) const LAST_SEQ_OFFSET: usize = 8;
19pub(crate) const JITTER_OFFSET: usize = 12;
20pub(crate) const LAST_SR_OFFSET: usize = 16;
21pub(crate) const DELAY_OFFSET: usize = 20;
22
23/// A ReceptionReport block conveys statistics on the reception of RTP packets
24/// from a single synchronization source.
25#[derive(Debug, PartialEq, Eq, Default, Clone)]
26pub struct ReceptionReport {
27    /// The SSRC identifier of the source to which the information in this
28    /// reception report block pertains.
29    pub ssrc: u32,
30    /// The fraction of RTP data packets from source SSRC lost since the
31    /// previous SR or RR packet was sent, expressed as a fixed point
32    /// number with the binary point at the left edge of the field.
33    pub fraction_lost: u8,
34    /// The total number of RTP data packets from source SSRC that have
35    /// been lost since the beginning of reception.
36    ///
37    /// RFC 3550 §6.4.1 defines this as a signed 24-bit integer on the wire
38    /// (negative values can occur when duplicates arrive). This field holds the
39    /// 24 bits as they are; read the signed count with
40    /// [`cumulative_lost`](Self::cumulative_lost) and write one with
41    /// [`set_cumulative_lost`](Self::set_cumulative_lost).
42    pub total_lost: u32,
43    /// The least significant 16 bits contain the highest sequence number received
44    /// in an RTP data packet from source SSRC, and the most significant 16 bits extend
45    /// that sequence number with the corresponding count of sequence number cycles.
46    pub last_sequence_number: u32,
47    /// An estimate of the statistical variance of the RTP data packet
48    /// interarrival time, measured in timestamp units and expressed as an
49    /// unsigned integer.
50    pub jitter: u32,
51    /// The middle 32 bits out of 64 in the NTP timestamp received as part of
52    /// the most recent RTCP sender report (SR) packet from source SSRC. If no
53    /// SR has been received yet, the field is set to zero.
54    pub last_sender_report: u32,
55    /// The delay, expressed in units of 1/65536 seconds, between receiving the
56    /// last SR packet from source SSRC and sending this reception report block.
57    /// If no SR packet has been received yet from SSRC, the field is set to zero.
58    pub delay: u32,
59}
60
61impl ReceptionReport {
62    /// The cumulative number of packets lost, as the signed 24-bit integer RFC 3550 6.4.1 defines.
63    ///
64    /// `total_lost` holds the 24 bits as they are on the wire. Duplicates make the count
65    /// negative, which reads there as a value near 2^24; this sign-extends it.
66    pub fn cumulative_lost(&self) -> i32 {
67        let bits = (self.total_lost & 0xFF_FFFF) as i32;
68        if bits & 0x80_0000 != 0 {
69            bits - 0x100_0000
70        } else {
71            bits
72        }
73    }
74
75    /// Store a signed cumulative loss as its 24-bit two's complement, clamped to the range the
76    /// field can carry (RFC 3550 6.4.1).
77    pub fn set_cumulative_lost(&mut self, lost: i32) {
78        let clamped = lost.clamp(-0x80_0000, 0x7F_FFFF);
79        self.total_lost = (clamped as u32) & 0xFF_FFFF;
80    }
81}
82
83impl fmt::Display for ReceptionReport {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        write!(f, "{self:?}")
86    }
87}
88
89impl Packet for ReceptionReport {
90    fn header(&self) -> Header {
91        Header::default()
92    }
93
94    fn destination_ssrc(&self) -> Vec<u32> {
95        vec![]
96    }
97
98    fn raw_size(&self) -> usize {
99        RECEPTION_REPORT_LENGTH
100    }
101
102    fn as_any(&self) -> &dyn Any {
103        self
104    }
105
106    fn equal(&self, other: &dyn Packet) -> bool {
107        other.as_any().downcast_ref::<ReceptionReport>() == Some(self)
108    }
109
110    fn cloned(&self) -> Box<dyn Packet> {
111        Box::new(self.clone())
112    }
113}
114
115impl MarshalSize for ReceptionReport {
116    fn marshal_size(&self) -> usize {
117        let l = self.raw_size();
118        // align to 32-bit boundary
119        l + get_padding_size(l)
120    }
121}
122
123impl Marshal for ReceptionReport {
124    /// marshal_to encodes the ReceptionReport in binary
125    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
126        /*
127         *  0                   1                   2                   3
128         *  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
129         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
130         * |                              SSRC                             |
131         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
132         * | fraction lost |       cumulative number of packets lost       |
133         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
134         * |           extended highest sequence number received           |
135         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
136         * |                      interarrival jitter                      |
137         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
138         * |                         last SR (LSR)                         |
139         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
140         * |                   delay since last SR (DLSR)                  |
141         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
142         */
143        if buf.remaining_mut() < self.marshal_size() {
144            return Err(Error::BufferTooShort);
145        }
146
147        buf.put_u32(self.ssrc);
148
149        buf.put_u8(self.fraction_lost);
150
151        // Pack TotalLost into 24 bits (RFC 3550 §6.4.1).
152        // Values above 0xFF_FFFF cannot be represented in 24 bits.
153        if self.total_lost > 0xFF_FFFF {
154            return Err(Error::InvalidTotalLost);
155        }
156
157        buf.put_u8(((self.total_lost >> 16) & 0xFF) as u8);
158        buf.put_u8(((self.total_lost >> 8) & 0xFF) as u8);
159        buf.put_u8((self.total_lost & 0xFF) as u8);
160
161        buf.put_u32(self.last_sequence_number);
162        buf.put_u32(self.jitter);
163        buf.put_u32(self.last_sender_report);
164        buf.put_u32(self.delay);
165
166        put_padding(buf, self.raw_size());
167
168        Ok(self.marshal_size())
169    }
170}
171
172impl Unmarshal for ReceptionReport {
173    /// unmarshal decodes the ReceptionReport from binary
174    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
175    where
176        Self: Sized,
177        B: Buf,
178    {
179        let raw_packet_len = raw_packet.remaining();
180        if raw_packet_len < RECEPTION_REPORT_LENGTH {
181            return Err(Error::PacketTooShort);
182        }
183
184        /*
185         *  0                   1                   2                   3
186         *  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
187         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
188         * |                              SSRC                             |
189         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
190         * | fraction lost |       cumulative number of packets lost       |
191         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
192         * |           extended highest sequence number received           |
193         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
194         * |                      interarrival jitter                      |
195         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
196         * |                         last SR (LSR)                         |
197         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
198         * |                   delay since last SR (DLSR)                  |
199         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
200         */
201        let ssrc = raw_packet.get_u32();
202        let fraction_lost = raw_packet.get_u8();
203
204        let t0 = raw_packet.get_u8();
205        let t1 = raw_packet.get_u8();
206        let t2 = raw_packet.get_u8();
207        // The 24 bits are kept as they are; `cumulative_lost()` reads them signed, per the RFC:
208        // The total number of RTP data packets from source SSRC_n that have
209        // been lost since the beginning of reception.  This number is
210        // defined to be the number of packets expected less the number of
211        // packets actually received, where the number of packets received
212        // includes any which are late or duplicates.  Thus, packets that
213        // arrive late are not counted as lost, and the loss may be negative
214        // if there are duplicates.  The number of packets expected is
215        // defined to be the extended last sequence number received, as
216        // defined next, less the initial sequence number received.  This may
217        // be calculated as shown in Appendix A.3.
218        let total_lost = (t2 as u32) | (t1 as u32) << 8 | (t0 as u32) << 16;
219
220        let last_sequence_number = raw_packet.get_u32();
221        let jitter = raw_packet.get_u32();
222        let last_sender_report = raw_packet.get_u32();
223        let delay = raw_packet.get_u32();
224
225        Ok(ReceptionReport {
226            ssrc,
227            fraction_lost,
228            total_lost,
229            last_sequence_number,
230            jitter,
231            last_sender_report,
232            delay,
233        })
234    }
235}