Skip to main content

rtci_rtcp/payload_feedbacks/
temporal_spatial_tradeoff.rs

1//! Temporal-Spatial Trade-off Request and Notification ([RFC 5104] §4.3.2, §4.3.3).
2//!
3//! A receiver tells an encoder which way to lean between frame rate and picture quality with a
4//! TSTR; the encoder answers with a TSTN that echoes the request and states the index it uses.
5//! Both carry the same FCI entry.
6//!
7//! [RFC 5104]: https://datatracker.ietf.org/doc/html/rfc5104#section-4.3.2
8use crate::{header::*, packet::*, util::*};
9use shared::{
10    error::{Error, Result},
11    marshal::{Marshal, MarshalSize, Unmarshal},
12};
13
14use bytes::{Buf, BufMut};
15use std::fmt;
16
17const TST_ENTRY_LENGTH: usize = 8;
18const TST_INDEX_MAX: u8 = (1 << 5) - 1;
19
20/// One FCI entry of a TSTR or a TSTN.
21///
22/// ```text
23///  0                   1                   2                   3
24///  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
25/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
26/// |                              SSRC                             |
27/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
28/// |  Seq nr.      |  Reserved                           | Index   |
29/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30/// ```
31#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
32pub struct TstEntry {
33    /// In a TSTR, the media sender asked. In a TSTN, the source whose request is answered.
34    pub ssrc: u32,
35    /// The request's sequence number: it goes up with each new request, a repetition keeps it,
36    /// and a notification echoes it.
37    pub sequence_number: u8,
38    /// The trade-off, 5 bits: 0 is the highest picture quality, 31 the highest frame rate.
39    pub index: u8,
40}
41
42fn marshal_tst(
43    buf: &mut [u8],
44    format: u8,
45    size: usize,
46    sender_ssrc: u32,
47    entries: &[TstEntry],
48) -> Result<usize> {
49    // RFC 5104 4.3.2.1 / 4.3.3.1: the FCI "SHALL contain one or more" entries.
50    if entries.is_empty() {
51        return Err(Error::PacketTooShort);
52    }
53    if entries.iter().any(|e| e.index > TST_INDEX_MAX) {
54        return Err(Error::InvalidHeader);
55    }
56    // RFC 5104 4.3.2.2 / 4.3.3.2: the "SSRC of media source" is not used and SHALL be 0.
57    let mut buf = put_feedback_start(
58        buf,
59        PacketType::PayloadSpecificFeedback,
60        format,
61        size,
62        sender_ssrc,
63        0,
64    )?;
65    for entry in entries {
66        buf.put_u32(entry.ssrc);
67        // The 19 reserved bits are sent as zero.
68        buf.put_u32(((entry.sequence_number as u32) << 24) | entry.index as u32);
69    }
70    Ok(size)
71}
72
73fn unmarshal_tst<B: Buf>(raw_packet: &mut B, format: u8) -> Result<(u32, Vec<TstEntry>)> {
74    let (sender_ssrc, _media_ssrc, mut fci) =
75        read_feedback(raw_packet, PacketType::PayloadSpecificFeedback, format)?;
76    if fci.is_empty() {
77        return Err(Error::PacketTooShort);
78    }
79    // The length is 2 + 2 * N.
80    if !fci.len().is_multiple_of(TST_ENTRY_LENGTH) {
81        return Err(Error::InvalidHeader);
82    }
83    let mut entries = Vec::with_capacity(fci.len() / TST_ENTRY_LENGTH);
84    while fci.has_remaining() {
85        let ssrc = fci.get_u32();
86        let word = fci.get_u32();
87        entries.push(TstEntry {
88            ssrc,
89            sequence_number: (word >> 24) as u8,
90            // The reserved bits are ignored.
91            index: (word as u8) & TST_INDEX_MAX,
92        });
93    }
94    Ok((sender_ssrc, entries))
95}
96
97fn fmt_tst(
98    f: &mut fmt::Formatter<'_>,
99    name: &str,
100    sender_ssrc: u32,
101    entries: &[TstEntry],
102) -> fmt::Result {
103    write!(f, "{name} {sender_ssrc:x}")?;
104    for e in entries {
105        write!(f, " ({:x} {} {})", e.ssrc, e.sequence_number, e.index)?;
106    }
107    Ok(())
108}
109
110macro_rules! tst_packet {
111    ($(#[$doc:meta])* $name:ident, $format:expr, $label:literal) => {
112        $(#[$doc])*
113        #[derive(Debug, PartialEq, Eq, Default, Clone)]
114        pub struct $name {
115            /// The source that sends this message.
116            pub sender_ssrc: u32,
117            /// At least one entry.
118            pub entries: Vec<TstEntry>,
119        }
120
121        impl fmt::Display for $name {
122            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123                fmt_tst(f, $label, self.sender_ssrc, &self.entries)
124            }
125        }
126
127        impl Packet for $name {
128            fn header(&self) -> Header {
129                Header {
130                    padding: false,
131                    count: $format,
132                    packet_type: PacketType::PayloadSpecificFeedback,
133                    length: ((self.marshal_size() / 4) - 1) as u16,
134                }
135            }
136
137            fn destination_ssrc(&self) -> Vec<u32> {
138                self.entries.iter().map(|e| e.ssrc).collect()
139            }
140
141            fn raw_size(&self) -> usize {
142                HEADER_LENGTH + FEEDBACK_SSRCS_LENGTH + self.entries.len() * TST_ENTRY_LENGTH
143            }
144
145            packet_any!($name);
146        }
147
148        impl MarshalSize for $name {
149            fn marshal_size(&self) -> usize {
150                self.raw_size()
151            }
152        }
153
154        impl Marshal for $name {
155            fn marshal_to(&self, buf: &mut [u8]) -> Result<usize> {
156                marshal_tst(buf, $format, self.raw_size(), self.sender_ssrc, &self.entries)
157            }
158        }
159
160        impl Unmarshal for $name {
161            fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
162            where
163                Self: Sized,
164                B: Buf,
165            {
166                let (sender_ssrc, entries) = unmarshal_tst(raw_packet, $format)?;
167                Ok($name {
168                    sender_ssrc,
169                    entries,
170                })
171            }
172        }
173    };
174}
175
176tst_packet!(
177    /// Temporal-Spatial Trade-off Request (TSTR, PSFB FMT=5, RFC 5104 §4.3.2).
178    TemporalSpatialTradeoffRequest,
179    FORMAT_TSTR,
180    "TSTR"
181);
182tst_packet!(
183    /// Temporal-Spatial Trade-off Notification (TSTN, PSFB FMT=6, RFC 5104 §4.3.3).
184    TemporalSpatialTradeoffNotification,
185    FORMAT_TSTN,
186    "TSTN"
187);
188
189#[cfg(test)]
190mod test {
191    use super::*;
192    use bytes::Bytes;
193
194    #[test]
195    fn tstr_round_trips_with_the_wire_layout_of_rfc5104() {
196        let tstr = TemporalSpatialTradeoffRequest {
197            sender_ssrc: 0x01020304,
198            entries: vec![
199                TstEntry {
200                    ssrc: 0x0a0b0c0d,
201                    sequence_number: 9,
202                    index: 31,
203                },
204                TstEntry {
205                    ssrc: 0x0a0b0c0e,
206                    sequence_number: 255,
207                    index: 0,
208                },
209            ],
210        };
211        let raw = tstr.marshal().unwrap();
212        assert_eq!(
213            &[
214                0x85, 0xce, 0x00, 0x06, // v=2, FMT=5, PSFB, len = 2 + 2 * 2
215                0x01, 0x02, 0x03, 0x04, // sender
216                0x00, 0x00, 0x00, 0x00, // media source: not used, zero
217                0x0a, 0x0b, 0x0c, 0x0d, 0x09, 0x00, 0x00, 0x1f, //
218                0x0a, 0x0b, 0x0c, 0x0e, 0xff, 0x00, 0x00, 0x00,
219            ][..],
220            &raw[..]
221        );
222        assert_eq!(
223            tstr,
224            TemporalSpatialTradeoffRequest::unmarshal(&mut raw.freeze()).unwrap()
225        );
226        assert_eq!(vec![0x0a0b0c0d, 0x0a0b0c0e], tstr.destination_ssrc());
227    }
228
229    /// RFC 5104 4.3.3: a TSTN is PSFB (206) FMT=6, "SSRC of media source" not used and 0
230    /// (4.3.3.2), and one or more FCI entries (4.3.3.1) of SSRC, Seq nr., 19 reserved bits sent
231    /// as 0, and the 5-bit Index; the length is 2 + 2 * N words. The bytes are written out.
232    /// Received, the reserved bits and the media source are ignored.
233    #[test]
234    fn tstn_round_trips_and_is_not_a_tstr() {
235        let tstn = TemporalSpatialTradeoffNotification {
236            sender_ssrc: 0x01020304,
237            entries: vec![
238                TstEntry {
239                    ssrc: 0x0a0b0c0d,
240                    sequence_number: 3,
241                    index: 4,
242                },
243                TstEntry {
244                    ssrc: 0x0a0b0c0e,
245                    sequence_number: 0xfe,
246                    index: 31,
247                },
248            ],
249        };
250        let raw = tstn.marshal().unwrap().freeze();
251        assert_eq!(
252            &[
253                0x86, 0xce, 0x00, 0x06, // v=2, FMT=6, PSFB, len = 2 + 2 * 2
254                0x01, 0x02, 0x03, 0x04, // sender
255                0x00, 0x00, 0x00, 0x00, // media source: not used, zero
256                0x0a, 0x0b, 0x0c, 0x0d, 0x03, 0x00, 0x00, 0x04, //
257                0x0a, 0x0b, 0x0c, 0x0e, 0xfe, 0x00, 0x00, 0x1f,
258            ][..],
259            &raw[..]
260        );
261        assert_eq!(
262            tstn,
263            TemporalSpatialTradeoffNotification::unmarshal(&mut raw.clone()).unwrap()
264        );
265        // The reserved bits set and a media source given: the same notification.
266        let mut noisy = raw.to_vec();
267        noisy[8..12].copy_from_slice(&[0xff; 4]);
268        noisy[17] = 0xff;
269        noisy[18] = 0xff;
270        noisy[19] |= 0xe0;
271        assert_eq!(
272            tstn,
273            TemporalSpatialTradeoffNotification::unmarshal(&mut Bytes::from(noisy)).unwrap()
274        );
275        assert_eq!(
276            Err(Error::WrongType),
277            TemporalSpatialTradeoffRequest::unmarshal(&mut raw.clone())
278        );
279    }
280
281    // RFC 5104 4.3.2.1: reserved bits are ignored on reception.
282    #[test]
283    fn reserved_bits_are_ignored() {
284        let mut raw = Bytes::from_static(&[
285            0x85, 0xce, 0x00, 0x04, 0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 2, 0x07, 0xff,
286            0xff, 0xe5,
287        ]);
288        let tstr = TemporalSpatialTradeoffRequest::unmarshal(&mut raw).unwrap();
289        assert_eq!(
290            vec![TstEntry {
291                ssrc: 2,
292                sequence_number: 7,
293                index: 5
294            }],
295            tstr.entries
296        );
297    }
298
299    #[test]
300    fn an_entry_is_required_and_must_be_whole() {
301        assert_eq!(
302            Err(Error::PacketTooShort),
303            TemporalSpatialTradeoffRequest::default().marshal()
304        );
305        let over = TemporalSpatialTradeoffNotification {
306            sender_ssrc: 1,
307            entries: vec![TstEntry {
308                index: 32,
309                ..Default::default()
310            }],
311        };
312        assert_eq!(Err(Error::InvalidHeader), over.marshal());
313
314        let mut none = Bytes::from_static(&[0x85, 0xce, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]);
315        assert_eq!(
316            Err(Error::PacketTooShort),
317            TemporalSpatialTradeoffRequest::unmarshal(&mut none)
318        );
319        let mut half = Bytes::from_static(&[0x86, 0xce, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2]);
320        assert_eq!(
321            Err(Error::InvalidHeader),
322            TemporalSpatialTradeoffNotification::unmarshal(&mut half)
323        );
324    }
325}