rtci_rtcp/compound_packet/mod.rs
1#[cfg(test)]
2mod compound_packet_test;
3#[cfg(test)]
4mod validation_test;
5
6use crate::{
7 header::*, packet::*, receiver_report::*, sender_report::*, source_description::*, util::*,
8};
9use shared::{
10 error::{Error, Result},
11 marshal::{Marshal, MarshalSize, Unmarshal},
12};
13
14use bytes::{Buf, Bytes};
15use std::any::Any;
16use std::fmt;
17
18/// A CompoundPacket is a collection of RTCP packets transmitted as a single packet with
19/// the underlying protocol (for example UDP).
20///
21/// To maximize the resolution of receiption statistics, the first Packet in a CompoundPacket
22/// must always be either a SenderReport or a ReceiverReport. This is true even if no data
23/// has been sent or received, in which case an empty ReceiverReport must be sent, and even
24/// if the only other RTCP packet in the compound packet is a Goodbye.
25///
26/// Next, a SourceDescription containing a CNAME item must be included in each CompoundPacket
27/// to identify the source and to begin associating media for purposes such as lip-sync.
28///
29/// Other RTCP packet types may follow in any order. Packet types may appear more than once.
30#[derive(Debug, Default, PartialEq, Clone)]
31pub struct CompoundPacket(pub Vec<Box<dyn Packet>>);
32
33impl fmt::Display for CompoundPacket {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "{self:?}")
36 }
37}
38
39impl Packet for CompoundPacket {
40 fn header(&self) -> Header {
41 Header::default()
42 }
43
44 /// destination_ssrc returns the synchronization sources associated with this
45 /// CompoundPacket's reception report.
46 fn destination_ssrc(&self) -> Vec<u32> {
47 if self.0.is_empty() {
48 vec![]
49 } else {
50 self.0[0].destination_ssrc()
51 }
52 }
53
54 fn raw_size(&self) -> usize {
55 let mut l = 0;
56 for packet in &self.0 {
57 l += packet.marshal_size();
58 }
59 l
60 }
61
62 fn as_any(&self) -> &dyn Any {
63 self
64 }
65
66 fn equal(&self, other: &dyn Packet) -> bool {
67 other.as_any().downcast_ref::<CompoundPacket>() == Some(self)
68 }
69
70 fn cloned(&self) -> Box<dyn Packet> {
71 Box::new(self.clone())
72 }
73}
74
75impl MarshalSize for CompoundPacket {
76 fn marshal_size(&self) -> usize {
77 let l = self.raw_size();
78 // align to 32-bit boundary
79 l + get_padding_size(l)
80 }
81}
82
83impl Marshal for CompoundPacket {
84 /// Marshal encodes the CompoundPacket as binary.
85 fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
86 self.validate()?;
87
88 for packet in &self.0 {
89 let n = packet.marshal_to(buf)?;
90 buf = &mut buf[n..];
91 }
92
93 Ok(self.marshal_size())
94 }
95}
96
97impl Unmarshal for CompoundPacket {
98 /// Reads a datagram as the compound packet RFC 3550 defines, and nothing less: the header
99 /// checks of Appendix A.2 ([`validate_compound`]), then every packet, then the rules of
100 /// §6.1 ([`CompoundPacket::validate`]). A reduced-size datagram (RFC 5506) fails here; read
101 /// one with [`crate::packet::unmarshal`].
102 fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
103 where
104 Self: Sized,
105 B: Buf,
106 {
107 let mut raw = raw_packet.copy_to_bytes(raw_packet.remaining());
108 validate_headers(&raw, Datagram::Compound)?;
109
110 let mut packets = vec![];
111 while raw.has_remaining() {
112 let p = unmarshaller(&mut raw)?;
113 packets.push(p);
114 }
115
116 let c = CompoundPacket(packets);
117 c.validate()?;
118
119 Ok(c)
120 }
121}
122
123/// The two kinds of RTCP datagram.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125enum Datagram {
126 /// A compound packet, RFC 3550 §6.1.
127 Compound,
128 /// A reduced-size packet, RFC 5506 §4.1.
129 ReducedSize,
130}
131
132/// Walks the headers of the packets in a datagram without parsing what they carry.
133fn validate_headers(raw: &[u8], kind: Datagram) -> Result<()> {
134 if raw.is_empty() {
135 return Err(Error::EmptyCompound);
136 }
137
138 let mut rest = raw;
139 let mut first = true;
140 while !rest.is_empty() {
141 // "The length fields of the individual RTCP packets must add up to the overall length
142 // of the compound RTCP packet as received."
143 if rest.len() < HEADER_LENGTH {
144 return Err(Error::PacketTooShort);
145 }
146 // "RTP version field must equal 2", on every packet (the loop of the A.2 code).
147 if (rest[0] >> VERSION_SHIFT) & VERSION_MASK != RTP_VERSION {
148 return Err(Error::BadVersion);
149 }
150 let padding = (rest[0] >> PADDING_SHIFT) & PADDING_MASK != 0;
151 let packet_type = rest[1];
152 let length = u16::from_be_bytes([rest[2], rest[3]]) as usize * 4;
153 if rest.len() < HEADER_LENGTH + length {
154 return Err(Error::PacketTooShort);
155 }
156 let last = rest.len() == HEADER_LENGTH + length;
157
158 if first {
159 match kind {
160 // "The payload type field of the first RTCP packet in a compound packet must
161 // be equal to SR or RR."
162 Datagram::Compound => {
163 if packet_type != u8::from(PacketType::SenderReport)
164 && packet_type != u8::from(PacketType::ReceiverReport)
165 {
166 return Err(Error::BadFirstPacket);
167 }
168 // "The padding bit (P) should be zero for the first packet of a compound
169 // RTCP packet", also when it is the only one.
170 if padding {
171 return Err(Error::WrongPadding);
172 }
173 }
174 // RFC 5506 3.4.2: any RTCP packet type may come first, which leaves little to
175 // tell RTCP from anything else; "the best possible validation" left is that
176 // the type is one RTCP can have next to RTP (RFC 5761 4).
177 Datagram::ReducedSize => {
178 if !(192..=223).contains(&packet_type) {
179 return Err(Error::BadFirstPacket);
180 }
181 }
182 }
183 }
184
185 // RFC 3550 6.4.1: "padding MUST only be added to the last individual packet, and if
186 // padding is added to that packet, the padding bit MUST be set only on that packet."
187 if padding {
188 if !last {
189 return Err(Error::WrongPadding);
190 }
191 // The last octet counts the padding octets, itself included.
192 let count = rest[HEADER_LENGTH + length - 1] as usize;
193 if count == 0 || count > length {
194 return Err(Error::WrongPadding);
195 }
196 }
197
198 rest = &rest[HEADER_LENGTH + length..];
199 first = false;
200 }
201
202 Ok(())
203}
204
205/// Checks that `raw`, one datagram, is a compound RTCP packet as RFC 3550 defines it.
206///
207/// Appendix A.2: every packet is version 2, the first is an SR or an RR with the padding bit
208/// clear, and the lengths add up to the datagram. §6.4.1: only the last packet is padded.
209/// §6.1: an SDES packet with a CNAME follows the reports.
210///
211/// A receiver that negotiated reduced-size RTCP (RFC 5506) does not apply this to what it
212/// receives: see [`validate_reduced_size`].
213pub fn validate_compound(raw: &[u8]) -> Result<()> {
214 CompoundPacket::unmarshal(&mut &raw[..]).map(|_| ())
215}
216
217/// The header checks of RFC 3550 Appendix A.2 on `raw`, one datagram, as a compound packet:
218/// every packet is version 2, the first is an SR or an RR with the padding bit clear, the
219/// lengths add up to the datagram, and only the last packet is padded (section 6.4.1).
220///
221/// Unlike [`validate_compound`] it does not parse what the packets carry, so a packet of an
222/// unknown type or one that does not parse is left to the caller (RFC 3550 section 6.1: such a
223/// packet is ignored, the others processed).
224pub fn validate_compound_headers(raw: &[u8]) -> Result<()> {
225 validate_headers(raw, Datagram::Compound)
226}
227
228/// Checks that `raw`, one datagram, is acceptable as reduced-size RTCP (RFC 5506 §4.1): one
229/// or more RTCP packets of any type, with no SR or RR in front and no SDES required.
230///
231/// What is left of the checks of RFC 3550 Appendix A.2 (RFC 5506 §3.4.2): every packet is
232/// version 2, the lengths add up to the datagram, only the last packet is padded, and the
233/// first packet's type is in the RTCP range 192 to 223. A compound packet passes too.
234pub fn validate_reduced_size(raw: &[u8]) -> Result<()> {
235 validate_headers(raw, Datagram::ReducedSize)
236}
237
238impl CompoundPacket {
239 /// Validate returns an error if this is not an RFC-compliant CompoundPacket.
240 pub fn validate(&self) -> Result<()> {
241 if self.0.is_empty() {
242 return Err(Error::EmptyCompound);
243 }
244
245 // SenderReport and ReceiverReport are the only types that
246 // are allowed to be the first packet in a compound datagram
247 if self.0[0].as_any().downcast_ref::<SenderReport>().is_none()
248 && self.0[0]
249 .as_any()
250 .downcast_ref::<ReceiverReport>()
251 .is_none()
252 {
253 return Err(Error::BadFirstPacket);
254 }
255
256 // RFC 3550 6.4.1: only the last packet of a compound packet is padded.
257 if let Some((_, all_but_last)) = self.0.split_last()
258 && all_but_last.iter().any(|pkt| pkt.header().padding)
259 {
260 return Err(Error::WrongPadding);
261 }
262
263 for pkt in &self.0[1..] {
264 // If the number of RRs exceeds 31 additional ReceiverReports
265 // can be included here.
266 if pkt.as_any().downcast_ref::<ReceiverReport>().is_some() {
267 continue;
268 // A SourceDescription containing a CNAME must be included in every
269 // CompoundPacket.
270 } else if let Some(e) = pkt.as_any().downcast_ref::<SourceDescription>() {
271 let mut has_cname = false;
272 for c in &e.chunks {
273 for it in &c.items {
274 if it.sdes_type == SdesType::SdesCname {
275 has_cname = true
276 }
277 }
278 }
279
280 if !has_cname {
281 return Err(Error::MissingCname);
282 }
283
284 return Ok(());
285
286 // Other packets are not permitted before the CNAME
287 } else {
288 return Err(Error::PacketBeforeCname);
289 }
290 }
291
292 // CNAME never reached
293 Err(Error::MissingCname)
294 }
295
296 /// CNAME returns the CNAME that *must* be present in every CompoundPacket
297 pub fn cname(&self) -> Result<Bytes> {
298 if self.0.is_empty() {
299 return Err(Error::EmptyCompound);
300 }
301
302 for pkt in &self.0[1..] {
303 if let Some(sdes) = pkt.as_any().downcast_ref::<SourceDescription>() {
304 for c in &sdes.chunks {
305 for it in &c.items {
306 if it.sdes_type == SdesType::SdesCname {
307 return Ok(it.text.clone());
308 }
309 }
310 }
311 } else if pkt.as_any().downcast_ref::<ReceiverReport>().is_none() {
312 return Err(Error::PacketBeforeCname);
313 }
314 }
315
316 Err(Error::MissingCname)
317 }
318}