Skip to main content

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
129#[derive(Clone)]
130pub(crate) struct PacketizerImpl {
131    pub(crate) mtu: usize,
132    pub(crate) payload_type: u8,
133    pub(crate) ssrc: u32,
134    pub(crate) payloader: Box<dyn Payloader>,
135    pub(crate) sequencer: Box<dyn Sequencer>,
136    pub(crate) timestamp: u32,
137    pub(crate) clock_rate: u32,
138    pub(crate) abs_send_time_ext_id: u8, //http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
139    pub(crate) time_baseline: SystemInstant,
140    /// A silence was skipped since the last packet: the next one starts a talkspurt.
141    pub(crate) talkspurt_start: bool,
142}
143
144impl fmt::Debug for PacketizerImpl {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.debug_struct("PacketizerImpl")
147            .field("mtu", &self.mtu)
148            .field("payload_type", &self.payload_type)
149            .field("ssrc", &self.ssrc)
150            .field("timestamp", &self.timestamp)
151            .field("clock_rate", &self.clock_rate)
152            .field("abs_send_time_ext_id", &self.abs_send_time_ext_id)
153            .finish()
154    }
155}
156
157/// Builds a packetizer for one outbound stream.
158///
159/// Ties together the codec's payloader, a sequencer, and the SSRC, payload type, MTU and clock
160/// rate the stream was negotiated with.
161pub fn new_packetizer(
162    now: Instant,
163    mtu: usize,
164    payload_type: u8,
165    ssrc: u32,
166    payloader: Box<dyn Payloader>,
167    sequencer: Box<dyn Sequencer>,
168    clock_rate: u32,
169) -> impl Packetizer {
170    PacketizerImpl {
171        mtu,
172        payload_type,
173        ssrc,
174        payloader,
175        sequencer,
176        timestamp: rand::random::<u32>(),
177        clock_rate,
178        abs_send_time_ext_id: 0,
179        time_baseline: SystemInstant::now(now),
180        talkspurt_start: false,
181    }
182}
183
184impl Packetizer for PacketizerImpl {
185    fn enable_abs_send_time(&mut self, id: u8) {
186        self.abs_send_time_ext_id = id
187    }
188
189    fn packetize(&mut self, now: Instant, payload: &Bytes, samples: u32) -> Result<Vec<Packet>> {
190        // What the MTU leaves once the fixed header is written. An MTU that leaves nothing
191        // cannot carry media.
192        let payload_mtu = self
193            .mtu
194            .checked_sub(RTP_FIXED_HEADER_SIZE)
195            .filter(|&payload_mtu| payload_mtu > 0)
196            .ok_or_else(|| {
197                Error::Other(format!(
198                    "an RTP MTU of {} bytes leaves no room for a payload after the \
199                     {RTP_FIXED_HEADER_SIZE}-byte header",
200                    self.mtu
201                ))
202            })?;
203        let payloads = self.payloader.payload(payload_mtu, payload)?;
204        let payloads_len = payloads.len();
205        let marker_rule = self.payloader.marker_rule();
206        let mut packets = Vec::with_capacity(payloads_len);
207        // A sample-based payload split over several packets: each packet's timestamp is that
208        // of its first sample (RFC 3551 section 4.3).
209        let mut timestamp = self.timestamp;
210        for (i, payload) in payloads.into_iter().enumerate() {
211            let marker = match marker_rule {
212                MarkerRule::LastPacketOfFrame => i == payloads_len - 1,
213                MarkerRule::FirstPacketOfTalkspurt => std::mem::take(&mut self.talkspurt_start),
214                MarkerRule::Never => false,
215            };
216            let duration = self.payloader.payload_duration(&payload);
217            packets.push(Packet {
218                header: Header {
219                    version: 2,
220                    padding: false,
221                    extension: false,
222                    marker,
223                    payload_type: self.payload_type,
224                    sequence_number: self.sequencer.next_sequence_number(),
225                    timestamp,
226                    ssrc: self.ssrc,
227                    ..Default::default()
228                },
229                payload,
230            });
231            if let Some(duration) = duration {
232                timestamp = timestamp.wrapping_add(duration);
233            }
234        }
235
236        self.timestamp = self.timestamp.wrapping_add(samples);
237
238        if payloads_len != 0 && self.abs_send_time_ext_id != 0 {
239            let send_time = AbsSendTimeExtension::new(self.time_baseline.ntp(now));
240            //apply http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
241            let mut raw = BytesMut::with_capacity(send_time.marshal_size());
242            raw.resize(send_time.marshal_size(), 0);
243            let _ = send_time.marshal_to(&mut raw)?;
244            packets[payloads_len - 1]
245                .header
246                .set_extension(self.abs_send_time_ext_id, raw.freeze())?;
247        }
248
249        Ok(packets)
250    }
251
252    /// skip_samples causes a gap in sample count between Packetize requests so the
253    /// RTP payloads produced have a gap in timestamps
254    fn skip_samples(&mut self, skipped_samples: u32) {
255        self.timestamp = self.timestamp.wrapping_add(skipped_samples);
256        self.talkspurt_start = true;
257    }
258
259    fn set_next_frame_info(&mut self, info: &dyn std::any::Any) {
260        self.payloader.set_next_frame_info(info);
261    }
262
263    fn clone_to(&self) -> Box<dyn Packetizer> {
264        Box::new(self.clone())
265    }
266}