1use crate::{
2 application_defined::*, goodbye::*, header::*,
3 payload_feedbacks::application_layer_feedback::*, payload_feedbacks::full_intra_request::*,
4 payload_feedbacks::layer_refresh_request::*, payload_feedbacks::picture_loss_indication::*,
5 payload_feedbacks::receiver_estimated_maximum_bitrate::*,
6 payload_feedbacks::reference_picture_selection_indication::*,
7 payload_feedbacks::slice_loss_indication::*, payload_feedbacks::temporal_spatial_tradeoff::*,
8 payload_feedbacks::video_back_channel_message::*, raw_packet::*, receiver_report::*,
9 sender_report::*, source_description::*, transport_feedbacks::cc_feedback_report::*,
10 transport_feedbacks::ecn_feedback::*, transport_feedbacks::pause_resume::*,
11 transport_feedbacks::rapid_resynchronization_request::*, transport_feedbacks::tmmb::*,
12 transport_feedbacks::transport_layer_cc::*, transport_feedbacks::transport_layer_nack::*,
13};
14use shared::{
15 error::{Error, Result},
16 marshal::{Marshal, Unmarshal},
17};
18
19use crate::extended_report::ExtendedReport;
20use bytes::{Buf, BufMut, Bytes, BytesMut};
21use std::any::Any;
22use std::fmt;
23
24pub trait Packet: Send + Sync + Marshal + Unmarshal + fmt::Display + fmt::Debug {
27 fn header(&self) -> Header;
29 fn destination_ssrc(&self) -> Vec<u32>;
34 fn raw_size(&self) -> usize;
36 fn as_any(&self) -> &dyn Any;
38 fn equal(&self, other: &dyn Packet) -> bool;
40 fn cloned(&self) -> Box<dyn Packet>;
42}
43
44impl PartialEq for dyn Packet {
45 fn eq(&self, other: &Self) -> bool {
46 self.equal(other)
47 }
48}
49
50impl Clone for Box<dyn Packet> {
51 fn clone(&self) -> Box<dyn Packet> {
52 self.cloned()
53 }
54}
55
56pub fn marshal(packets: &[Box<dyn Packet>]) -> Result<BytesMut> {
58 let total: usize = packets.iter().map(|p| p.marshal_size()).sum();
62 let mut out = BytesMut::new();
63 out.resize(total, 0);
64 let mut offset = 0;
65 for p in packets {
66 offset += p.marshal_to(&mut out[offset..])?;
67 }
68 Ok(out)
69}
70
71pub fn unmarshal<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
82where
83 B: Buf,
84{
85 let mut packets = vec![];
86
87 while raw_data.has_remaining() {
88 let p = unmarshaller(raw_data)?;
89 packets.push(p);
90 }
91
92 match packets.len() {
93 0 => Err(Error::InvalidHeader),
95
96 _ => Ok(packets),
98 }
99}
100
101pub fn unmarshal_lenient<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
108where
109 B: Buf,
110{
111 let mut packets: Vec<Box<dyn Packet>> = vec![];
112
113 while raw_data.has_remaining() {
114 let framed = next_packet(raw_data)?;
115 match parse_packet(&framed) {
116 Ok(p) => packets.push(p),
117 Err(_) => packets.push(Box::new(RawPacket(framed.whole()))),
118 }
119 }
120
121 if packets.is_empty() {
122 return Err(Error::InvalidHeader);
123 }
124 Ok(packets)
125}
126
127pub(crate) struct FramedPacket {
133 header: [u8; HEADER_LENGTH],
134 body: Bytes,
135}
136
137impl FramedPacket {
138 fn whole(&self) -> Bytes {
140 let mut packet = BytesMut::with_capacity(HEADER_LENGTH + self.body.len());
141 packet.put_slice(&self.header);
142 packet.put_slice(&self.body);
143 packet.freeze()
144 }
145
146 fn reader(&self) -> impl Buf + '_ {
148 self.header.as_slice().chain(self.body.clone())
149 }
150}
151
152pub(crate) fn next_packet<B>(raw_data: &mut B) -> Result<FramedPacket>
154where
155 B: Buf,
156{
157 if raw_data.remaining() < HEADER_LENGTH {
158 return Err(Error::PacketTooShort);
159 }
160 let mut header = [0u8; HEADER_LENGTH];
161 raw_data.copy_to_slice(&mut header);
162 if (header[0] >> VERSION_SHIFT) & VERSION_MASK != RTP_VERSION {
163 return Err(Error::BadVersion);
164 }
165
166 let length = u16::from_be_bytes([header[2], header[3]]) as usize * 4;
167 if length > raw_data.remaining() {
168 return Err(Error::PacketTooShort);
169 }
170
171 Ok(FramedPacket {
172 header,
173 body: raw_data.copy_to_bytes(length),
174 })
175}
176
177fn parse_packet(framed: &FramedPacket) -> Result<Box<dyn Packet>> {
179 let format = (framed.header[0] >> COUNT_SHIFT) & COUNT_MASK;
180 let in_packet = &mut framed.reader();
181
182 let p: Box<dyn Packet> = match PacketType::from(framed.header[1]) {
183 PacketType::SenderReport => Box::new(SenderReport::unmarshal(in_packet)?),
184 PacketType::ReceiverReport => Box::new(ReceiverReport::unmarshal(in_packet)?),
185 PacketType::SourceDescription => Box::new(SourceDescription::unmarshal(in_packet)?),
186 PacketType::Goodbye => Box::new(Goodbye::unmarshal(in_packet)?),
187 PacketType::ApplicationDefined => Box::new(ApplicationDefined::unmarshal(in_packet)?),
188
189 PacketType::TransportSpecificFeedback => match format {
190 FORMAT_TLN => Box::new(TransportLayerNack::unmarshal(in_packet)?),
191 FORMAT_TMMBR => Box::new(TemporaryMaximumBitrateRequest::unmarshal(in_packet)?),
192 FORMAT_TMMBN => Box::new(TemporaryMaximumBitrateNotification::unmarshal(in_packet)?),
193 FORMAT_RRR => Box::new(RapidResynchronizationRequest::unmarshal(in_packet)?),
194 FORMAT_TCC => Box::new(TransportLayerCc::unmarshal(in_packet)?),
195 FORMAT_CCFB => Box::new(CcFeedbackReport::unmarshal(in_packet)?),
196 FORMAT_ECN => Box::new(EcnFeedback::unmarshal(in_packet)?),
197 FORMAT_PAUSE_RESUME => Box::new(PauseResume::unmarshal(in_packet)?),
198 _ => Box::new(RawPacket(framed.whole())),
199 },
200 PacketType::PayloadSpecificFeedback => match format {
201 FORMAT_PLI => Box::new(PictureLossIndication::unmarshal(in_packet)?),
202 FORMAT_SLI => Box::new(SliceLossIndication::unmarshal(in_packet)?),
203 FORMAT_RPSI => Box::new(ReferencePictureSelectionIndication::unmarshal(in_packet)?),
204 FORMAT_FIR => Box::new(FullIntraRequest::unmarshal(in_packet)?),
205 FORMAT_TSTR => Box::new(TemporalSpatialTradeoffRequest::unmarshal(in_packet)?),
206 FORMAT_TSTN => Box::new(TemporalSpatialTradeoffNotification::unmarshal(in_packet)?),
207 FORMAT_VBCM => Box::new(VideoBackChannelMessage::unmarshal(in_packet)?),
208 FORMAT_LRR => Box::new(LayerRefreshRequest::unmarshal(in_packet)?),
209 FORMAT_AFB if is_remb(&framed.body) => {
212 Box::new(ReceiverEstimatedMaximumBitrate::unmarshal(in_packet)?)
213 }
214 FORMAT_AFB => Box::new(ApplicationLayerFeedback::unmarshal(in_packet)?),
215 _ => Box::new(RawPacket(framed.whole())),
216 },
217 PacketType::ExtendedReport => Box::new(ExtendedReport::unmarshal(in_packet)?),
218 _ => Box::new(RawPacket(framed.whole())),
219 };
220
221 Ok(p)
222}
223
224pub(crate) fn unmarshaller<B>(raw_data: &mut B) -> Result<Box<dyn Packet>>
227where
228 B: Buf,
229{
230 parse_packet(&next_packet(raw_data)?)
231}
232
233#[cfg(test)]
234mod test {
235 use super::*;
236 use crate::reception_report::*;
237 use bytes::Bytes;
238
239 #[test]
240 fn test_packet_unmarshal() {
241 let mut data = Bytes::from_static(&[
242 0x81, 0xc9, 0x0, 0x7, 0x90, 0x2f, 0x9e, 0x2e, 0xbc, 0x5e, 0x9a, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x46, 0xe1, 0x0, 0x0, 0x1, 0x11, 0x9, 0xf3, 0x64, 0x32, 0x0, 0x2, 0x4a, 0x79, 0x81, 0xca, 0x0, 0xc, 0x90, 0x2f, 0x9e, 0x2e, 0x1, 0x26, 0x7b, 0x39, 0x63, 0x30, 0x30, 0x65, 0x62, 0x39, 0x32, 0x2d, 0x31, 0x61, 0x66, 0x62,
256 0x2d, 0x39, 0x64, 0x34, 0x39, 0x2d, 0x61, 0x34, 0x37, 0x64, 0x2d, 0x39, 0x31, 0x66,
257 0x36, 0x34, 0x65, 0x65, 0x65, 0x36, 0x39, 0x66, 0x35,
258 0x7d, 0x0, 0x0, 0x0, 0x0, 0x81, 0xcb, 0x0, 0x1, 0x90, 0x2f, 0x9e, 0x2e, 0x81, 0xce, 0x0, 0x2, 0x90, 0x2f, 0x9e, 0x2e, 0x90, 0x2f, 0x9e, 0x2e, 0x85, 0xcd, 0x0, 0x2, 0x90, 0x2f, 0x9e, 0x2e, 0x90, 0x2f, 0x9e, 0x2e, ]);
270
271 let packet = unmarshal(&mut data).expect("Error unmarshalling packets");
272
273 let a = ReceiverReport {
274 ssrc: 0x902f9e2e,
275 reports: vec![ReceptionReport {
276 ssrc: 0xbc5e9a40,
277 fraction_lost: 0,
278 total_lost: 0,
279 last_sequence_number: 0x46e1,
280 jitter: 273,
281 last_sender_report: 0x9f36432,
282 delay: 150137,
283 }],
284 ..Default::default()
285 };
286
287 let b = SourceDescription {
288 chunks: vec![SourceDescriptionChunk {
289 source: 0x902f9e2e,
290 items: vec![SourceDescriptionItem {
291 sdes_type: SdesType::SdesCname,
292 text: Bytes::from_static(b"{9c00eb92-1afb-9d49-a47d-91f64eee69f5}"),
293 }],
294 }],
295 };
296
297 let c = Goodbye {
298 sources: vec![0x902f9e2e],
299 ..Default::default()
300 };
301
302 let d = PictureLossIndication {
303 sender_ssrc: 0x902f9e2e,
304 media_ssrc: 0x902f9e2e,
305 };
306
307 let e = RapidResynchronizationRequest {
308 sender_ssrc: 0x902f9e2e,
309 media_ssrc: 0x902f9e2e,
310 };
311
312 let expected: Vec<Box<dyn Packet>> = vec![
313 Box::new(a),
314 Box::new(b),
315 Box::new(c),
316 Box::new(d),
317 Box::new(e),
318 ];
319
320 assert!(packet == expected, "Invalid packets");
321 }
322
323 #[test]
324 fn test_packet_unmarshal_empty() -> Result<()> {
325 let result = unmarshal(&mut Bytes::new());
326 if let Err(got) = result {
327 let want = Error::InvalidHeader;
328 assert_eq!(got, want, "Unmarshal(nil) err = {got}, want {want}");
329 } else {
330 panic!("want error");
331 }
332
333 Ok(())
334 }
335
336 #[test]
337 fn test_packet_invalid_header_length() -> Result<()> {
338 let mut data = Bytes::from_static(&[
339 0x81, 0xcb, 0x0, 0x64,
342 ]);
343
344 let result = unmarshal(&mut data);
345 if let Err(got) = result {
346 let want = Error::PacketTooShort;
347 assert_eq!(
348 got, want,
349 "Unmarshal(invalid_header_length) err = {got}, want {want}"
350 );
351 } else {
352 panic!("want error");
353 }
354
355 Ok(())
356 }
357 #[test]
358 fn test_packet_unmarshal_firefox() -> Result<()> {
359 let tests = vec![
361 Bytes::from_static(&[
362 143, 205, 0, 6, 65, 227, 184, 49, 118, 243, 78, 96, 42, 63, 0, 5, 12, 162, 166, 0,
363 32, 5, 200, 4, 0, 4, 0, 0,
364 ]),
365 Bytes::from_static(&[
366 143, 205, 0, 9, 65, 227, 184, 49, 118, 243, 78, 96, 42, 68, 0, 17, 12, 162, 167, 1,
367 32, 17, 88, 0, 4, 0, 4, 8, 108, 0, 4, 0, 4, 12, 0, 4, 0, 4, 4, 0,
368 ]),
369 Bytes::from_static(&[
370 143, 205, 0, 8, 65, 227, 184, 49, 118, 243, 78, 96, 42, 91, 0, 12, 12, 162, 168, 3,
371 32, 12, 220, 4, 0, 4, 0, 8, 128, 4, 0, 4, 0, 8, 0, 0,
372 ]),
373 Bytes::from_static(&[
374 143, 205, 0, 7, 65, 227, 184, 49, 118, 243, 78, 96, 42, 103, 0, 8, 12, 162, 169, 4,
375 32, 8, 232, 4, 0, 4, 0, 4, 4, 0, 0, 0,
376 ]),
377 ];
378
379 for mut test in tests {
380 unmarshal(&mut test)?;
381 }
382
383 Ok(())
384 }
385
386 #[test]
390 fn test_marshal_compound_roundtrip() -> Result<()> {
391 use crate::reception_report::ReceptionReport;
392
393 let rr = ReceiverReport {
394 ssrc: 0x902f9e2e,
395 reports: vec![ReceptionReport {
396 ssrc: 0xbc5e9a40,
397 fraction_lost: 0,
398 total_lost: 0,
399 last_sequence_number: 0x46e1,
400 jitter: 273,
401 last_sender_report: 0x9f36432,
402 delay: 150137,
403 }],
404 ..Default::default()
405 };
406 let pli = PictureLossIndication {
407 sender_ssrc: 0x902f9e2e,
408 media_ssrc: 0x902f9e2e,
409 };
410 let packets: Vec<Box<dyn Packet>> = vec![Box::new(rr), Box::new(pli)];
411
412 let raw1 = marshal(&packets)?;
413 let out = unmarshal(&mut raw1.clone().freeze())?;
414 assert_eq!(out.len(), 2, "expected two sub-packets");
415 let raw2 = marshal(&out)?;
416 assert_eq!(raw1, raw2, "compound marshal/unmarshal round-trip mismatch");
417
418 Ok(())
419 }
420}