Skip to main content

rtci_rtcp/transport_feedbacks/pause_resume/
mod.rs

1#[cfg(test)]
2mod pause_resume_test;
3
4use crate::{header::*, packet::*, util::*};
5use shared::{
6    error::{Error, Result},
7    marshal::{Marshal, MarshalSize, Unmarshal},
8};
9
10use bytes::{Buf, BufMut, Bytes};
11use std::any::Any;
12use std::fmt;
13
14/// The octets of an FCI entry before its type-specific field: the target SSRC, then the type,
15/// the reserved bits, the parameter length and the PauseID (RFC 7728 section 7, Figure 6).
16pub const PAUSE_RESUME_ENTRY_HEADER_LENGTH: usize = 8;
17
18/// The pause feedback type of an FCI entry (RFC 7728 section 7, "Type (4 bits)").
19#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
20pub enum PauseResumeType {
21    /// 0: PAUSE request.
22    Pause,
23    /// 1: RESUME request.
24    Resume,
25    /// 2: PAUSED indication.
26    Paused,
27    /// 3: REFUSED notification.
28    Refused,
29    /// 4 to 15: reserved. "FCI fields with these Type values SHALL be ignored on reception by
30    /// receivers and MUST NOT be used by senders implementing this specification": decoded so
31    /// that a packet carrying one still parses, and never written by the engine.
32    Reserved(u8),
33}
34
35impl PauseResumeType {
36    fn value(self) -> u8 {
37        match self {
38            Self::Pause => 0,
39            Self::Resume => 1,
40            Self::Paused => 2,
41            Self::Refused => 3,
42            Self::Reserved(value) => value & 0x0f,
43        }
44    }
45
46    fn from_value(value: u8) -> Self {
47        match value & 0x0f {
48            0 => Self::Pause,
49            1 => Self::Resume,
50            2 => Self::Paused,
51            3 => Self::Refused,
52            other => Self::Reserved(other),
53        }
54    }
55}
56
57/// One FCI entry of a PAUSE-RESUME message (RFC 7728 section 7, Figure 6).
58///
59/// ```text
60///  0                   1                   2                   3
61///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
62/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
63/// |                           Target SSRC                         |
64/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
65/// | Type  |  Res  | Parameter Len |           PauseID             |
66/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
67/// :                         Type Specific                         :
68/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
69/// ```
70#[derive(Debug, PartialEq, Eq, Clone)]
71pub struct PauseResumeEntry {
72    /// The SSRC the request is for, or the one paused (PAUSED), or the target of the refused
73    /// request (REFUSED).
74    pub target_ssrc: u32,
75    /// The pause feedback type.
76    pub typ: PauseResumeType,
77    /// The message sequence identification, scoped by the target SSRC (section 5.2).
78    pub pause_id: u16,
79    /// The type-specific field, a whole number of 32-bit words. PAUSED carries the extended
80    /// sequence number of the last RTP packet sent before the pause in its first word
81    /// (section 8.2; [`PauseResumeEntry::paused_extended_sequence_number`]); the others none.
82    /// Unknown data is kept, so that it can be skipped and ignored ("A receiver ... MUST be
83    /// able to skip and ignore any unknown Type Specific data").
84    pub type_specific: Bytes,
85}
86
87impl PauseResumeEntry {
88    /// A PAUSE request for `target_ssrc`.
89    pub fn pause(target_ssrc: u32, pause_id: u16) -> Self {
90        Self::without_parameters(target_ssrc, PauseResumeType::Pause, pause_id)
91    }
92
93    /// A RESUME request for `target_ssrc`.
94    pub fn resume(target_ssrc: u32, pause_id: u16) -> Self {
95        Self::without_parameters(target_ssrc, PauseResumeType::Resume, pause_id)
96    }
97
98    /// A REFUSED notification for `target_ssrc`.
99    pub fn refused(target_ssrc: u32, pause_id: u16) -> Self {
100        Self::without_parameters(target_ssrc, PauseResumeType::Refused, pause_id)
101    }
102
103    /// A PAUSED indication for `target_ssrc`, with the extended RTP sequence number of the
104    /// last packet sent before the pause (section 8.2: "SHALL contain a fixed-length 32-bit
105    /// parameter at the start of the Type Specific field").
106    pub fn paused(target_ssrc: u32, pause_id: u16, extended_sequence_number: u32) -> Self {
107        Self {
108            target_ssrc,
109            typ: PauseResumeType::Paused,
110            pause_id,
111            type_specific: Bytes::copy_from_slice(&extended_sequence_number.to_be_bytes()),
112        }
113    }
114
115    fn without_parameters(target_ssrc: u32, typ: PauseResumeType, pause_id: u16) -> Self {
116        Self {
117            target_ssrc,
118            typ,
119            pause_id,
120            type_specific: Bytes::new(),
121        }
122    }
123
124    /// The extended sequence number a PAUSED indication carries; `None` for another type or
125    /// a PAUSED without its parameter.
126    pub fn paused_extended_sequence_number(&self) -> Option<u32> {
127        if self.typ != PauseResumeType::Paused || self.type_specific.len() < 4 {
128            return None;
129        }
130        let b = &self.type_specific;
131        Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
132    }
133
134    fn size(&self) -> usize {
135        PAUSE_RESUME_ENTRY_HEADER_LENGTH + self.type_specific.len()
136    }
137}
138
139/// The RTP/AVPF transport-layer PAUSE-RESUME message (RFC 7728 section 7): RTPFB, FMT 9,
140/// one or more PAUSE, RESUME, PAUSED or REFUSED entries. "SSRC of media source: Not used;
141/// SHALL be set to 0. The FCI identifies the SSRC the message is targeted for." Negotiated
142/// with `a=rtcp-fb:<pt> ccm pause` (section 9).
143#[derive(Debug, PartialEq, Eq, Default, Clone)]
144pub struct PauseResume {
145    /// SSRC of the packet sender.
146    pub sender_ssrc: u32,
147    /// The entries, in order.
148    pub entries: Vec<PauseResumeEntry>,
149}
150
151impl fmt::Display for PauseResume {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "PauseResume from {:x}", self.sender_ssrc)?;
154        for entry in &self.entries {
155            write!(
156                f,
157                " {:?} {:x} id {}",
158                entry.typ, entry.target_ssrc, entry.pause_id
159            )?;
160        }
161        Ok(())
162    }
163}
164
165impl Packet for PauseResume {
166    fn header(&self) -> Header {
167        Header {
168            padding: get_padding_size(self.raw_size()) != 0,
169            count: FORMAT_PAUSE_RESUME,
170            packet_type: PacketType::TransportSpecificFeedback,
171            length: ((self.marshal_size() / 4) - 1) as u16,
172        }
173    }
174
175    fn destination_ssrc(&self) -> Vec<u32> {
176        let mut ssrcs: Vec<u32> = vec![];
177        for entry in &self.entries {
178            if !ssrcs.contains(&entry.target_ssrc) {
179                ssrcs.push(entry.target_ssrc);
180            }
181        }
182        ssrcs
183    }
184
185    fn raw_size(&self) -> usize {
186        HEADER_LENGTH
187            + SSRC_LENGTH * 2
188            + self
189                .entries
190                .iter()
191                .map(PauseResumeEntry::size)
192                .sum::<usize>()
193    }
194
195    fn as_any(&self) -> &dyn Any {
196        self
197    }
198
199    fn equal(&self, other: &dyn Packet) -> bool {
200        other.as_any().downcast_ref::<PauseResume>() == Some(self)
201    }
202
203    fn cloned(&self) -> Box<dyn Packet> {
204        Box::new(self.clone())
205    }
206}
207
208impl MarshalSize for PauseResume {
209    fn marshal_size(&self) -> usize {
210        let l = self.raw_size();
211        l + get_padding_size(l)
212    }
213}
214
215impl Marshal for PauseResume {
216    /// Writes the message. An entry whose type-specific field is not a whole number of
217    /// 32-bit words, or longer than 255 words, cannot be described by its Parameter Len and
218    /// is refused; so is a reserved type ("MUST NOT be used by senders").
219    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
220        if buf.remaining_mut() < self.marshal_size() {
221            return Err(Error::BufferTooShort);
222        }
223        for entry in &self.entries {
224            if !entry.type_specific.len().is_multiple_of(4) || entry.type_specific.len() / 4 > 255 {
225                return Err(Error::WrongMarshalSize);
226            }
227            if matches!(entry.typ, PauseResumeType::Reserved(_)) {
228                return Err(Error::WrongType);
229            }
230        }
231        let h = self.header();
232        let n = h.marshal_to(buf)?;
233        buf = &mut buf[n..];
234        buf.put_u32(self.sender_ssrc);
235        // "SSRC of media source: Not used; SHALL be set to 0."
236        buf.put_u32(0);
237        for entry in &self.entries {
238            buf.put_u32(entry.target_ssrc);
239            // "Res: ... MUST be set to 0 by senders".
240            buf.put_u8(entry.typ.value() << 4);
241            buf.put_u8((entry.type_specific.len() / 4) as u8);
242            buf.put_u16(entry.pause_id);
243            buf.put_slice(&entry.type_specific);
244        }
245        Ok(self.marshal_size())
246    }
247}
248
249impl Unmarshal for PauseResume {
250    /// Decodes the message: the media source SSRC is ignored (it is "not used"), the
251    /// reserved bits of each entry too, and each entry's type-specific field is taken by its
252    /// Parameter Len whatever its type. An FCI that ends inside an entry is refused.
253    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
254    where
255        Self: Sized,
256        B: Buf,
257    {
258        let (sender_ssrc, _media_ssrc, mut fci) = read_feedback(
259            raw_packet,
260            PacketType::TransportSpecificFeedback,
261            FORMAT_PAUSE_RESUME,
262        )?;
263        let mut entries = vec![];
264        while fci.has_remaining() {
265            if fci.remaining() < PAUSE_RESUME_ENTRY_HEADER_LENGTH {
266                return Err(Error::PacketTooShort);
267            }
268            let target_ssrc = fci.get_u32();
269            let typ = PauseResumeType::from_value(fci.get_u8() >> 4);
270            let words = usize::from(fci.get_u8());
271            let pause_id = fci.get_u16();
272            if fci.remaining() < words * 4 {
273                return Err(Error::PacketTooShort);
274            }
275            let type_specific = fci.copy_to_bytes(words * 4);
276            entries.push(PauseResumeEntry {
277                target_ssrc,
278                typ,
279                pause_id,
280                type_specific,
281            });
282        }
283        if entries.is_empty() {
284            return Err(Error::PacketTooShort);
285        }
286        Ok(PauseResume {
287            sender_ssrc,
288            entries,
289        })
290    }
291}