rtci_rtp/packetizer/mod.rs
1#[cfg(test)]
2mod packetizer_rules_test;
3#[cfg(test)]
4mod packetizer_test;
5
6use crate::{extension::abs_send_time_extension::*, header::*, packet::*, sequence::*};
7use shared::{
8 error::{Error, Result},
9 marshal::{Marshal, MarshalSize},
10 time::SystemInstant,
11};
12
13use bytes::{Bytes, BytesMut};
14use std::fmt;
15use std::time::Instant;
16
17/// Bytes of fixed RTP header a packetizer leaves room for in the MTU (RFC 3550 section 5.1).
18pub const RTP_FIXED_HEADER_SIZE: usize = 12;
19
20/// Which packets of a payload format carry the RTP marker bit. The bit's meaning is the
21/// profile's and the payload format's (RFC 3550 section 5.1), so the payloader says.
22#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
23#[non_exhaustive]
24pub enum MarkerRule {
25 /// Video: the last packet of the frame, which is the last payload of a
26 /// [`Packetizer::packetize`] call (RFC 6184 section 5.1, RFC 7798 section 4.1, RFC 7741
27 /// section 4.1).
28 #[default]
29 LastPacketOfFrame,
30 /// Audio: the first packet of a talkspurt, that is the first packet after a silence the
31 /// caller reported with [`Packetizer::skip_samples`], and no other (RFC 3551 section 4.1,
32 /// RFC 7587 section 4.1). A stream without silence suppression never sets it.
33 FirstPacketOfTalkspurt,
34 /// Never set: comfort noise (RFC 3389 section 4).
35 Never,
36}
37
38/// Payloader payloads a byte array for use as rtp.Packet payloads
39pub trait Payloader: Send + Sync + fmt::Debug {
40 /// Splits one encoded frame into payloads no larger than `mtu`.
41 ///
42 /// # Errors
43 ///
44 /// Fails if the frame is malformed for this codec, or `mtu` is too small to make progress.
45 fn payload(&mut self, mtu: usize, b: &Bytes) -> Result<Vec<Bytes>>;
46 /// Which packets carry the marker bit. Video unless the payloader says otherwise.
47 fn marker_rule(&self) -> MarkerRule {
48 MarkerRule::LastPacketOfFrame
49 }
50 /// For a sample-based format, the RTP timestamp units one payload of
51 /// [`payload`](Payloader::payload) covers, so that a frame split over several packets gets
52 /// a timestamp per packet (RFC 3551 section 4.3: the timestamp is the sampling instant of
53 /// the packet's first sample). `None`, the default, is a frame-based format: every packet
54 /// of the frame carries the frame's timestamp.
55 fn payload_duration(&self, _payload: &Bytes) -> Option<u32> {
56 None
57 }
58 /// What the encoder says about the next frame [`payload`](Payloader::payload) is given,
59 /// for a format whose payload describes more than the frame's bytes (VP9's layer indices,
60 /// [`Vp9FrameInfo`](crate::codec::vp9::Vp9FrameInfo)); a type the payloader does not use
61 /// is ignored, as is the call by a payloader that uses none (the default).
62 fn set_next_frame_info(&mut self, _info: &dyn std::any::Any) {}
63 /// Clones this payloader behind a trait object.
64 fn clone_to(&self) -> Box<dyn Payloader>;
65}
66
67impl Clone for Box<dyn Payloader> {
68 fn clone(&self) -> Box<dyn Payloader> {
69 self.clone_to()
70 }
71}
72
73/// Packetizer packetizes a payload
74pub trait Packetizer: Send + Sync + fmt::Debug {
75 /// Attaches the absolute-send-time header extension under id `value`.
76 fn enable_abs_send_time(&mut self, value: u8);
77 /// Packetizes one frame, advancing the timestamp by `samples`.
78 ///
79 /// Assigns sequence numbers, sets the marker bit as the payload format has it (see
80 /// [`MarkerRule`]: the final packet of a video frame, the first packet of an audio
81 /// talkspurt) and applies any enabled header extensions. `now` is the instant the frame is being sent at; it is what
82 /// the absolute-send-time extension is derived from, so the caller supplies it rather than
83 /// the packetizer sampling a clock of its own.
84 ///
85 /// # Errors
86 ///
87 /// Propagates payloader failures, and fails when the MTU leaves no room for a payload
88 /// after the 12-byte RTP header.
89 fn packetize(&mut self, now: Instant, payload: &Bytes, samples: u32) -> Result<Vec<Packet>>;
90 /// Advances the timestamp without sending anything, for dropped or silent frames. For an
91 /// audio format this is a silence period: the next packet starts a talkspurt and carries
92 /// the marker bit (RFC 3551 section 4.1; Opus DTX, RFC 7587 section 3.1.3).
93 fn skip_samples(&mut self, skipped_samples: u32);
94 /// Describes the next frame [`packetize`](Packetizer::packetize) is given to the
95 /// payloader ([`Payloader::set_next_frame_info`]): for VP9 a
96 /// [`Vp9FrameInfo`](crate::codec::vp9::Vp9FrameInfo), so that the frames of a picture
97 /// with spatial layers carry their layer indices and only the picture's last packet the
98 /// marker (RFC 9628 section 4.1). The default ignores it.
99 fn set_next_frame_info(&mut self, _info: &dyn std::any::Any) {}
100 /// Clones this packetizer behind a trait object.
101 fn clone_to(&self) -> Box<dyn Packetizer>;
102}
103
104impl Clone for Box<dyn Packetizer> {
105 fn clone(&self) -> Box<dyn Packetizer> {
106 self.clone_to()
107 }
108}
109
110/// Depacketizer depacketizes a RTP payload, removing any RTP specific data from the payload
111pub trait Depacketizer {
112 /// Reassembles a frame from one RTP payload, buffering fragments as needed.
113 ///
114 /// # Errors
115 ///
116 /// Fails if the payload is malformed for this codec.
117 fn depacketize(&mut self, b: &Bytes) -> Result<Bytes>;
118
119 /// Checks if the packet is at the beginning of a partition. This
120 /// should return false if the result could not be determined, in
121 /// which case the caller will detect timestamp discontinuities.
122 fn is_partition_head(&self, payload: &Bytes) -> bool;
123
124 /// Checks if the packet is at the end of a partition. This should
125 /// return false if the result could not be determined.
126 fn is_partition_tail(&self, marker: bool, payload: &Bytes) -> bool;
127
128 /// Whether frames of this format are predicted from earlier frames, so that a receiver
129 /// that lost one cannot use what follows until a key frame (a decoder refresh point, RFC
130 /// 5104 section 2.2) arrives: the video formats. `false`, the default, is a format whose
131 /// frames stand alone (audio) or one this depacketizer cannot speak for.
132 fn has_key_frames(&self) -> bool {
133 false
134 }
135
136 /// Whether the payload is the first packet of a key frame: a frame that is decoded without
137 /// reference to any earlier one, so that nothing sent before it is needed once it is
138 /// complete. `false`, the default, when the payload format does not say or the result
139 /// could not be determined; a format that can tell also returns `true` from
140 /// [`has_key_frames`](Depacketizer::has_key_frames).
141 fn is_key_frame_start(&self, _payload: &Bytes) -> bool {
142 false
143 }
144}
145
146#[derive(Clone)]
147pub(crate) struct PacketizerImpl {
148 pub(crate) mtu: usize,
149 pub(crate) payload_type: u8,
150 pub(crate) ssrc: u32,
151 pub(crate) payloader: Box<dyn Payloader>,
152 pub(crate) sequencer: Box<dyn Sequencer>,
153 pub(crate) timestamp: u32,
154 pub(crate) clock_rate: u32,
155 pub(crate) abs_send_time_ext_id: u8, //http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
156 pub(crate) time_baseline: SystemInstant,
157 /// A silence was skipped since the last packet: the next one starts a talkspurt.
158 pub(crate) talkspurt_start: bool,
159}
160
161impl fmt::Debug for PacketizerImpl {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 f.debug_struct("PacketizerImpl")
164 .field("mtu", &self.mtu)
165 .field("payload_type", &self.payload_type)
166 .field("ssrc", &self.ssrc)
167 .field("timestamp", &self.timestamp)
168 .field("clock_rate", &self.clock_rate)
169 .field("abs_send_time_ext_id", &self.abs_send_time_ext_id)
170 .finish()
171 }
172}
173
174/// Builds a packetizer for one outbound stream.
175///
176/// Ties together the codec's payloader, a sequencer, and the SSRC, payload type, MTU and clock
177/// rate the stream was negotiated with.
178pub fn new_packetizer(
179 now: Instant,
180 mtu: usize,
181 payload_type: u8,
182 ssrc: u32,
183 payloader: Box<dyn Payloader>,
184 sequencer: Box<dyn Sequencer>,
185 clock_rate: u32,
186) -> impl Packetizer {
187 PacketizerImpl {
188 mtu,
189 payload_type,
190 ssrc,
191 payloader,
192 sequencer,
193 timestamp: rand::random::<u32>(),
194 clock_rate,
195 abs_send_time_ext_id: 0,
196 time_baseline: SystemInstant::now(now),
197 talkspurt_start: false,
198 }
199}
200
201impl Packetizer for PacketizerImpl {
202 fn enable_abs_send_time(&mut self, id: u8) {
203 self.abs_send_time_ext_id = id
204 }
205
206 fn packetize(&mut self, now: Instant, payload: &Bytes, samples: u32) -> Result<Vec<Packet>> {
207 // What the MTU leaves once the fixed header is written. An MTU that leaves nothing
208 // cannot carry media.
209 let payload_mtu = self
210 .mtu
211 .checked_sub(RTP_FIXED_HEADER_SIZE)
212 .filter(|&payload_mtu| payload_mtu > 0)
213 .ok_or_else(|| {
214 Error::Other(format!(
215 "an RTP MTU of {} bytes leaves no room for a payload after the \
216 {RTP_FIXED_HEADER_SIZE}-byte header",
217 self.mtu
218 ))
219 })?;
220 let payloads = self.payloader.payload(payload_mtu, payload)?;
221 let payloads_len = payloads.len();
222 let marker_rule = self.payloader.marker_rule();
223 let mut packets = Vec::with_capacity(payloads_len);
224 // A sample-based payload split over several packets: each packet's timestamp is that
225 // of its first sample (RFC 3551 section 4.3).
226 let mut timestamp = self.timestamp;
227 for (i, payload) in payloads.into_iter().enumerate() {
228 let marker = match marker_rule {
229 MarkerRule::LastPacketOfFrame => i == payloads_len - 1,
230 MarkerRule::FirstPacketOfTalkspurt => std::mem::take(&mut self.talkspurt_start),
231 MarkerRule::Never => false,
232 };
233 let duration = self.payloader.payload_duration(&payload);
234 packets.push(Packet {
235 header: Header {
236 version: 2,
237 padding: false,
238 extension: false,
239 marker,
240 payload_type: self.payload_type,
241 sequence_number: self.sequencer.next_sequence_number(),
242 timestamp,
243 ssrc: self.ssrc,
244 ..Default::default()
245 },
246 payload,
247 });
248 if let Some(duration) = duration {
249 timestamp = timestamp.wrapping_add(duration);
250 }
251 }
252
253 self.timestamp = self.timestamp.wrapping_add(samples);
254
255 if payloads_len != 0 && self.abs_send_time_ext_id != 0 {
256 let send_time = AbsSendTimeExtension::new(self.time_baseline.ntp(now));
257 //apply http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
258 let mut raw = BytesMut::with_capacity(send_time.marshal_size());
259 raw.resize(send_time.marshal_size(), 0);
260 let _ = send_time.marshal_to(&mut raw)?;
261 packets[payloads_len - 1]
262 .header
263 .set_extension(self.abs_send_time_ext_id, raw.freeze())?;
264 }
265
266 Ok(packets)
267 }
268
269 /// skip_samples causes a gap in sample count between Packetize requests so the
270 /// RTP payloads produced have a gap in timestamps
271 fn skip_samples(&mut self, skipped_samples: u32) {
272 self.timestamp = self.timestamp.wrapping_add(skipped_samples);
273 self.talkspurt_start = true;
274 }
275
276 fn set_next_frame_info(&mut self, info: &dyn std::any::Any) {
277 self.payloader.set_next_frame_info(info);
278 }
279
280 fn clone_to(&self) -> Box<dyn Packetizer> {
281 Box::new(self.clone())
282 }
283}