1use anyhow::{format_err, Error};
6use bitfield::bitfield;
7use std::cmp::min;
8use std::collections::VecDeque;
9
10bitfield! {
11 struct RtpHeader(MSB0 [u8]);
14 u8, version, set_version: 1, 0;
15 bool, padding, set_padding: 2;
16 bool, extension, set_extension: 3;
17 u8, csrc_count, set_csrc_count: 7, 4;
18 bool, marker, set_marker: 8;
19 u8, payload_type, set_payload_type: 15, 9;
20 u16, sequence_number, set_sequence_number: 31, 16;
21 u32, timestamp, set_timestamp: 63, 32;
22 u32, ssrc, set_ssrc: 95, 64;
23}
24
25const RTP_HEADER_LEN: usize = 12;
26
27const RTP_VERSION: u8 = 2;
29
30const RTP_PAYLOAD_DYNAMIC: u8 = 96;
32
33pub trait RtpPacketBuilder: Send {
34 fn add_frame(&mut self, frame: Vec<u8>, samples: u32) -> Result<Vec<Vec<u8>>, Error>;
38}
39
40pub(crate) struct SbcRtpPacketBuilder {
43 max_packet_size: usize,
45 next_sequence: u16,
47 timestamp: u32,
49 frames: VecDeque<Vec<u8>>,
51 samples: u32,
53}
54
55impl SbcRtpPacketBuilder {
56 const MAX_FRAMES_PER_PACKET: usize = 15;
57
58 pub fn new(max_packet_size: usize) -> Self {
59 Self {
60 max_packet_size,
61 next_sequence: 1,
62 timestamp: 0,
63 frames: VecDeque::new(),
64 samples: 0,
65 }
66 }
67
68 fn header_len(&self) -> usize {
71 RTP_HEADER_LEN + 1
72 }
73
74 fn frame_bytes_len(&self) -> usize {
76 self.frames.iter().map(Vec::len).sum()
77 }
78
79 fn build_packet(&mut self) -> Vec<u8> {
84 if self.frames.is_empty() {
85 panic!("Can't build an empty RTP SBC packet: no frames");
86 }
87 let mut header = RtpHeader([0; RTP_HEADER_LEN]);
88 header.set_version(RTP_VERSION);
89 header.set_payload_type(RTP_PAYLOAD_DYNAMIC);
90 header.set_sequence_number(self.next_sequence);
91 header.set_timestamp(self.timestamp);
92 let mut packet: Vec<u8> = header.0.iter().cloned().collect();
93 packet.push(self.frames.len() as u8);
94 let mut frames_bytes = self.frames.drain(..).flatten().collect();
95 packet.append(&mut frames_bytes);
96
97 self.next_sequence = self.next_sequence.wrapping_add(1);
98 self.timestamp = self.timestamp.wrapping_add(self.samples);
99 self.samples = 0;
100
101 packet
102 }
103}
104
105impl RtpPacketBuilder for SbcRtpPacketBuilder {
106 fn add_frame(&mut self, frame: Vec<u8>, samples: u32) -> Result<Vec<Vec<u8>>, Error> {
107 if (frame.len() + self.header_len()) > self.max_packet_size {
108 return Err(format_err!("Media packet too large for RTP max size"));
109 }
110 let mut packets = Vec::new();
111 let packet_size_with_new = self.header_len() + self.frame_bytes_len() + frame.len();
112 if packet_size_with_new > self.max_packet_size {
113 packets.push(self.build_packet());
114 }
115 self.frames.push_back(frame);
116 self.samples = self.samples + samples;
117 if self.frames.len() == Self::MAX_FRAMES_PER_PACKET {
118 packets.push(self.build_packet());
119 }
120 Ok(packets)
121 }
122}
123
124pub(crate) struct AacRtpPacketBuilder {
127 max_packet_size: usize,
129 next_sequence: u16,
131 timestamp: u32,
133}
134
135impl AacRtpPacketBuilder {
136 pub fn new(max_packet_size: usize) -> Self {
137 Self { max_packet_size, next_sequence: 1, timestamp: 0 }
138 }
139}
140
141impl RtpPacketBuilder for AacRtpPacketBuilder {
142 fn add_frame(&mut self, mut frame: Vec<u8>, samples: u32) -> Result<Vec<Vec<u8>>, Error> {
143 let mut header = RtpHeader([0; RTP_HEADER_LEN]);
144 header.set_version(RTP_VERSION);
145 header.set_payload_type(RTP_PAYLOAD_DYNAMIC);
146 header.set_timestamp(self.timestamp);
147 let mut left = frame.len();
148 let mut packets = Vec::new();
149 while left > 0 {
150 let mux_element_space = self.max_packet_size - RTP_HEADER_LEN;
151 header.set_sequence_number(self.next_sequence);
152 if left <= mux_element_space {
154 header.set_marker(true);
155 }
156 let header_iter = header.0.iter().cloned();
157 let packet_frame_end = min(mux_element_space, frame.len());
158 let frame_bytes_iter = frame.drain(..packet_frame_end);
159 let packet = header_iter.chain(frame_bytes_iter).collect();
160 packets.push(packet);
161 left = left.saturating_sub(packet_frame_end);
162 self.next_sequence = self.next_sequence.wrapping_add(1);
163 }
164 self.timestamp = self.timestamp.wrapping_add(samples);
165 Ok(packets)
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[test]
174 fn sbc_packet_builder_max_len() {
175 let mut builder = SbcRtpPacketBuilder::new(RTP_HEADER_LEN + 5);
177
178 assert!(builder.add_frame(vec![0xf0], 1).unwrap().is_empty());
179 assert!(builder.add_frame(vec![0x9f], 2).unwrap().is_empty());
180 assert!(builder.add_frame(vec![0x92], 4).unwrap().is_empty());
181 assert!(builder.add_frame(vec![0x96], 8).unwrap().is_empty());
182
183 let mut result = builder.add_frame(vec![0xf0], 16).expect("no error");
184
185 let expected = &[
186 0x80, 0x60, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xf0, 0x9f, 0x92, 0x96, ];
192
193 let result = result.drain(..).next().expect("a packet after 4 frames");
194
195 assert_eq!(expected.len(), result.len());
196 assert_eq!(expected, &result[0..expected.len()]);
197
198 assert!(builder.add_frame(vec![0x9f], 32).unwrap().is_empty());
199 assert!(builder.add_frame(vec![0x92], 64).unwrap().is_empty());
200 assert!(builder.add_frame(vec![0x96], 128).unwrap().is_empty());
201
202 let mut result = builder.add_frame(vec![0x33], 256).expect("no error");
203
204 let expected = &[
205 0x80, 0x60, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x04, 0xf0, 0x9f, 0x92, 0x96, ];
211
212 let result = result.drain(..).next().expect("a packet after 4 more frames");
213
214 assert_eq!(expected.len(), result.len());
215 assert_eq!(expected, &result[0..expected.len()]);
216
217 let result = builder.add_frame(vec![0x01, 0x02, 0x03, 0x04, 0x05], 512);
219 assert!(result.is_err());
220 }
221
222 #[test]
223 fn sbc_packet_builder_max_frames() {
224 let max_tx_size = 200;
225 let mut builder = SbcRtpPacketBuilder::new(max_tx_size);
226
227 assert!(builder.add_frame(vec![0xf0], 1).unwrap().is_empty());
228 assert!(builder.add_frame(vec![0x9f], 2).unwrap().is_empty());
229 assert!(builder.add_frame(vec![0x92], 4).unwrap().is_empty());
230 assert!(builder.add_frame(vec![0x96], 8).unwrap().is_empty());
231 assert!(builder.add_frame(vec![0xf0], 16).unwrap().is_empty());
232 assert!(builder.add_frame(vec![0x9f], 32).unwrap().is_empty());
233 assert!(builder.add_frame(vec![0x92], 64).unwrap().is_empty());
234 assert!(builder.add_frame(vec![0x96], 128).unwrap().is_empty());
235 assert!(builder.add_frame(vec![0xf0], 256).unwrap().is_empty());
236 assert!(builder.add_frame(vec![0x9f], 512).unwrap().is_empty());
237 assert!(builder.add_frame(vec![0x92], 1024).unwrap().is_empty());
238 assert!(builder.add_frame(vec![0x96], 2048).unwrap().is_empty());
239 assert!(builder.add_frame(vec![0x33], 4096).unwrap().is_empty());
240 assert!(builder.add_frame(vec![0x33], 8192).unwrap().is_empty());
241
242 let mut result = builder.add_frame(vec![0x33], 16384).expect("no error");
243
244 let expected = &[
245 0x80, 0x60, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xf0, 0x9f, 0x92, 0x96, 0xf0, 0x9f, 0x92, 0x96, 0xf0, 0x9f, 0x92, 0x96, 0x33, 0x33, 0x33, ];
254
255 let result = result.drain(..).next().expect("should have a packet");
256
257 assert_eq!(expected.len(), result.len());
258 assert_eq!(expected, &result[0..expected.len()]);
259
260 assert!(builder.add_frame(vec![0xf0, 0x9f, 0x92, 0x96], 32768).unwrap().is_empty());
261 let rest_of_packet: Vec<u8> = (4..(max_tx_size - RTP_HEADER_LEN - 1) as u8).collect();
262 assert!(builder.add_frame(rest_of_packet, 65536).unwrap().is_empty());
263
264 let mut result = builder.add_frame(vec![0x33], 131072).expect("no error");
265
266 let expected = &[
267 0x80, 0x60, 0x00, 0x02, 0x00, 0x00, 0x7F, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x02, 0xf0, 0x9f, 0x92, 0x96, ];
273
274 let result = result.drain(..).next().expect("a packet after max bytes exceeded");
275
276 assert!(expected.len() <= result.len());
277 assert_eq!(expected, &result[0..expected.len()]);
278 }
279
280 #[test]
281 fn aac_packet_buikder() {
282 let mut builder = AacRtpPacketBuilder::new(5 + RTP_HEADER_LEN);
283
284 let result = builder
286 .add_frame(vec![0xf0], 1)
287 .unwrap()
288 .drain(..)
289 .next()
290 .expect("should return a frame");
291
292 let expected = &[
293 0x80, 0xE0, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, ];
300
301 assert_eq!(expected.len(), result.len());
302 assert_eq!(expected, &result[0..expected.len()]);
303
304 let result = builder
305 .add_frame(vec![0xf0, 0x9f, 0x92, 0x96], 2)
306 .unwrap()
307 .drain(..)
308 .next()
309 .expect("should return a frame");
310
311 let expected = &[
312 0x80, 0xE0, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x9f, 0x92, 0x96, ];
319
320 assert_eq!(expected.len(), result.len());
321 assert_eq!(expected, &result[0..expected.len()]);
322 }
323
324 #[test]
325 fn aac_packet_builder_fragmentation() {
326 let mut builder = AacRtpPacketBuilder::new(2 + RTP_HEADER_LEN);
327
328 let frames = builder.add_frame(vec![0xf0, 0x9f, 0x92, 0x96], 1).unwrap();
330
331 assert_eq!(2, frames.len());
332
333 let first_expected = &[
334 0x80, 0x60, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x9f, ];
341
342 assert_eq!(first_expected.len(), frames[0].len());
343 assert_eq!(first_expected, &frames[0][0..first_expected.len()]);
344
345 let second_expected = &[
346 0x80, 0xE0, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x96, ];
353
354 assert_eq!(second_expected.len(), frames[1].len());
355 assert_eq!(second_expected, &frames[1][0..second_expected.len()]);
356
357 let frames = builder.add_frame(vec![0xf0, 0x9f], 2).unwrap();
358
359 assert_eq!(1, frames.len());
360
361 let result = frames.first().unwrap();
362
363 let expected = &[
364 0x80, 0xE0, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x9f, ];
371
372 assert_eq!(expected.len(), result.len());
373 assert_eq!(expected, &result[0..expected.len()]);
374 }
375}