Skip to main content

rtci_rtcp/transport_feedbacks/transport_layer_cc/
mod.rs

1//! Transport-wide congestion control feedback.
2//!
3//! Reports the arrival status and time of packets by their *transport-wide* sequence number — the
4//! one the `TransportCcExtension` RTP header extension stamps on every packet
5//! regardless of stream, which is why one report can cover audio and video together.
6//!
7//! Status is run-length or bit-vector encoded ([`StatusChunkTypeTcc`](crate::transport_feedbacks::transport_layer_cc::StatusChunkTypeTcc)) so a report covering
8//! hundreds of packets stays small.
9#[cfg(test)]
10mod chunk_limits_test;
11#[cfg(test)]
12mod delta_bounds_test;
13#[cfg(test)]
14mod reference_time_test;
15#[cfg(test)]
16mod transport_layer_cc_test;
17
18use crate::{header::*, packet::*, util::*};
19use shared::{
20    error::{Error, Result},
21    marshal::{Marshal, MarshalSize, Unmarshal},
22};
23
24use bytes::{Buf, BufMut};
25use std::any::Any;
26use std::fmt;
27
28/// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5>
29/// 0                   1                   2                   3
30/// 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
31/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32/// |V=2|P|  FMT=15 |    PT=205     |           length              |
33/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34/// |                     SSRC of packet sender                     |
35/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36/// |                      SSRC of media source                     |
37/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
38/// |      base sequence number     |      packet status count      |
39/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
40/// |                 reference time                | fb pkt. count |
41/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42/// |          packet chunk         |         packet chunk          |
43/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44/// .                                                               .
45/// .                                                               .
46/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
47/// |         packet chunk          |  recv delta   |  recv delta   |
48/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
49/// .                                                               .
50/// .                                                               .
51/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52/// |           recv delta          |  recv delta   | zero padding  |
53/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
54// for packet status chunk
55/// type of packet status chunk
56///
57/// ## Specifications
58///
59/// * [draft-holmer-rmcat-transport-wide-cc-extensions-01, page 5]
60///
61/// [draft-holmer-rmcat-transport-wide-cc-extensions-01, page 5]: https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5
62#[derive(Default, PartialEq, Eq, Debug, Clone)]
63#[repr(u16)]
64pub enum StatusChunkTypeTcc {
65    #[default]
66    /// A run-length chunk: one status repeated for a stated number of packets.
67    RunLengthChunk = 0,
68    /// A status-vector chunk: explicit per-packet status for a small group.
69    StatusVectorChunk = 1,
70}
71
72/// type of packet status symbol and recv delta
73#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
74#[repr(u16)]
75pub enum SymbolTypeTcc {
76    /// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1>
77    #[default]
78    PacketNotReceived = 0,
79    /// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1>
80    PacketReceivedSmallDelta = 1,
81    /// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1>
82    PacketReceivedLargeDelta = 2,
83    /// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-7>
84    /// see Example 2: "packet received, w/o recv delta"
85    PacketReceivedWithoutDelta = 3,
86}
87
88/// for status vector chunk
89#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
90#[repr(u16)]
91pub enum SymbolSizeTypeTcc {
92    /// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.4>
93    #[default]
94    OneBit = 0,
95    /// Two-bit symbols, which can also express "received, large delta".
96    TwoBit = 1,
97}
98
99impl From<u16> for SymbolSizeTypeTcc {
100    fn from(val: u16) -> Self {
101        match val {
102            0 => SymbolSizeTypeTcc::OneBit,
103            _ => SymbolSizeTypeTcc::TwoBit,
104        }
105    }
106}
107
108impl From<u16> for StatusChunkTypeTcc {
109    fn from(val: u16) -> Self {
110        match val {
111            0 => StatusChunkTypeTcc::RunLengthChunk,
112            _ => StatusChunkTypeTcc::StatusVectorChunk,
113        }
114    }
115}
116
117impl From<u16> for SymbolTypeTcc {
118    fn from(val: u16) -> Self {
119        match val {
120            0 => SymbolTypeTcc::PacketNotReceived,
121            1 => SymbolTypeTcc::PacketReceivedSmallDelta,
122            2 => SymbolTypeTcc::PacketReceivedLargeDelta,
123            _ => SymbolTypeTcc::PacketReceivedWithoutDelta,
124        }
125    }
126}
127
128/// PacketStatusChunk has two kinds:
129/// RunLengthChunk and StatusVectorChunk
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum PacketStatusChunk {
132    /// A run-length encoded chunk.
133    RunLengthChunk(RunLengthChunk),
134    /// A status-vector chunk.
135    StatusVectorChunk(StatusVectorChunk),
136}
137
138impl MarshalSize for PacketStatusChunk {
139    fn marshal_size(&self) -> usize {
140        match self {
141            PacketStatusChunk::RunLengthChunk(c) => c.marshal_size(),
142            PacketStatusChunk::StatusVectorChunk(c) => c.marshal_size(),
143        }
144    }
145}
146
147impl Marshal for PacketStatusChunk {
148    /// Marshal ..
149    fn marshal_to(&self, buf: &mut [u8]) -> Result<usize> {
150        match self {
151            PacketStatusChunk::RunLengthChunk(c) => c.marshal_to(buf),
152            PacketStatusChunk::StatusVectorChunk(c) => c.marshal_to(buf),
153        }
154    }
155}
156
157/// RunLengthChunk T=TypeTCCRunLengthChunk
158/// 0                   1
159/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
160/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
161/// |T| S |       Run Length        |
162/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
163#[derive(Debug, Clone, PartialEq, Eq, Default)]
164pub struct RunLengthChunk {
165    /// T = TypeTCCRunLengthChunk
166    pub type_tcc: StatusChunkTypeTcc,
167    /// S: type of packet status
168    /// kind: TypeTCCPacketNotReceived or...
169    pub packet_status_symbol: SymbolTypeTcc,
170    /// run_length: count of S
171    pub run_length: u16,
172}
173
174impl MarshalSize for RunLengthChunk {
175    fn marshal_size(&self) -> usize {
176        PACKET_STATUS_CHUNK_LENGTH
177    }
178}
179
180impl Marshal for RunLengthChunk {
181    /// Marshal ..
182    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
183        // The run length is 13 bits (draft-holmer-rmcat-transport-wide-cc-extensions-01 section
184        // 3.1.3): a longer run is refused, not written as its low 13 bits.
185        if self.run_length > MAX_RUN_LENGTH {
186            return Err(Error::InvalidSizeOrStartIndex);
187        }
188
189        // append 1 bit '0'
190        let mut dst = set_nbits_of_uint16(0, 1, 0, 0)?;
191
192        // append 2 bit packet_status_symbol
193        dst = set_nbits_of_uint16(dst, 2, 1, self.packet_status_symbol as u16)?;
194
195        // append 13 bit run_length
196        dst = set_nbits_of_uint16(dst, 13, 3, self.run_length)?;
197
198        buf.put_u16(dst);
199
200        Ok(PACKET_STATUS_CHUNK_LENGTH)
201    }
202}
203
204impl Unmarshal for RunLengthChunk {
205    /// Unmarshal ..
206    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
207    where
208        Self: Sized,
209        B: Buf,
210    {
211        let raw_packet_len = raw_packet.remaining();
212        if raw_packet_len < PACKET_STATUS_CHUNK_LENGTH {
213            return Err(Error::PacketStatusChunkLength);
214        }
215
216        // record type
217        let type_tcc = StatusChunkTypeTcc::RunLengthChunk;
218
219        let b0 = raw_packet.get_u8();
220        let b1 = raw_packet.get_u8();
221
222        // get PacketStatusSymbol
223        let packet_status_symbol = get_nbits_from_byte(b0, 1, 2).into();
224
225        // get RunLength
226        let run_length = ((get_nbits_from_byte(b0, 3, 5) as usize) << 8) as u16 + (b1 as u16);
227
228        Ok(RunLengthChunk {
229            type_tcc,
230            packet_status_symbol,
231            run_length,
232        })
233    }
234}
235
236/// StatusVectorChunk T=typeStatusVectorChunk
237/// 0                   1
238/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
239/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
240/// |T|S|       symbol list         |
241/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
242#[derive(Debug, Clone, PartialEq, Eq, Default)]
243pub struct StatusVectorChunk {
244    /// T = TypeTCCRunLengthChunk
245    pub type_tcc: StatusChunkTypeTcc,
246
247    /// TypeTCCSymbolSizeOneBit or TypeTCCSymbolSizeTwoBit
248    pub symbol_size: SymbolSizeTypeTcc,
249
250    /// when symbol_size = TypeTCCSymbolSizeOneBit, symbol_list is 14*1bit:
251    /// TypeTCCSymbolListPacketReceived or TypeTCCSymbolListPacketNotReceived
252    /// when symbol_size = TypeTCCSymbolSizeTwoBit, symbol_list is 7*2bit:
253    /// TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta TypeTCCPacketReceivedLargeDelta or typePacketReserved
254    pub symbol_list: Vec<SymbolTypeTcc>,
255}
256
257impl MarshalSize for StatusVectorChunk {
258    fn marshal_size(&self) -> usize {
259        PACKET_STATUS_CHUNK_LENGTH
260    }
261}
262
263impl Marshal for StatusVectorChunk {
264    /// Marshal ..
265    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
266        // A one-bit symbol is "not received" or "received, small delta" (section 3.1.4): a
267        // large delta (or the reserved symbol) is refused, not written as its low bit.
268        if self.symbol_size == SymbolSizeTypeTcc::OneBit
269            && self.symbol_list.iter().any(|symbol| {
270                !matches!(
271                    symbol,
272                    SymbolTypeTcc::PacketNotReceived | SymbolTypeTcc::PacketReceivedSmallDelta
273                )
274            })
275        {
276            return Err(Error::InvalidSizeOrStartIndex);
277        }
278
279        // set first bit '1'
280        let mut dst = set_nbits_of_uint16(0, 1, 0, 1)?;
281
282        // set second bit symbol_size
283        dst = set_nbits_of_uint16(dst, 1, 1, self.symbol_size as u16)?;
284
285        let num_of_bits = NUM_OF_BITS_OF_SYMBOL_SIZE[self.symbol_size as usize];
286        // append 14 bit symbol_list
287        for (i, s) in self.symbol_list.iter().enumerate() {
288            let index = num_of_bits * (i as u16) + 2;
289            dst = set_nbits_of_uint16(dst, num_of_bits, index, *s as u16)?;
290        }
291
292        buf.put_u16(dst);
293
294        Ok(PACKET_STATUS_CHUNK_LENGTH)
295    }
296}
297
298impl Unmarshal for StatusVectorChunk {
299    /// Unmarshal ..
300    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
301    where
302        Self: Sized,
303        B: Buf,
304    {
305        let raw_packet_len = raw_packet.remaining();
306        if raw_packet_len < PACKET_STATUS_CHUNK_LENGTH {
307            return Err(Error::PacketBeforeCname);
308        }
309
310        let type_tcc = StatusChunkTypeTcc::StatusVectorChunk;
311
312        let b0 = raw_packet.get_u8();
313        let b1 = raw_packet.get_u8();
314
315        let symbol_size = get_nbits_from_byte(b0, 1, 1).into();
316
317        let mut symbol_list: Vec<SymbolTypeTcc> = vec![];
318        match symbol_size {
319            SymbolSizeTypeTcc::OneBit => {
320                for i in 0..6u16 {
321                    symbol_list.push(get_nbits_from_byte(b0, 2 + i, 1).into());
322                }
323
324                for i in 0..8u16 {
325                    symbol_list.push(get_nbits_from_byte(b1, i, 1).into())
326                }
327            }
328
329            SymbolSizeTypeTcc::TwoBit => {
330                for i in 0..3u16 {
331                    symbol_list.push(get_nbits_from_byte(b0, 2 + i * 2, 2).into());
332                }
333
334                for i in 0..4u16 {
335                    symbol_list.push(get_nbits_from_byte(b1, i * 2, 2).into());
336                }
337            }
338        }
339
340        Ok(StatusVectorChunk {
341            type_tcc,
342            symbol_size,
343            symbol_list,
344        })
345    }
346}
347
348/// RecvDelta are represented as multiples of 250us
349/// small delta is 1 byte: [0,63.75]ms = [0, 63750]us = [0, 255]*250us
350/// big delta is 2 bytes: [-8192.0, 8191.75]ms = [-8192000, 8191750]us = [-32768, 32767]*250us
351/// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5>
352#[derive(Debug, Clone, PartialEq, Eq, Default)]
353pub struct RecvDelta {
354    /// Which symbol size this chunk uses.
355    pub type_tcc_packet: SymbolTypeTcc,
356    /// us
357    pub delta: i64,
358}
359
360impl MarshalSize for RecvDelta {
361    fn marshal_size(&self) -> usize {
362        let delta = self.delta / TYPE_TCC_DELTA_SCALE_FACTOR;
363
364        // small delta
365        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta
366            && delta >= 0
367            && delta <= u8::MAX as i64
368        {
369            return 1;
370        }
371
372        // big delta
373        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta
374            && delta >= i16::MIN as i64
375            && delta <= i16::MAX as i64
376        {
377            return 2;
378        }
379
380        0
381    }
382}
383
384impl Marshal for RecvDelta {
385    /// Marshal ..
386    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
387        let delta = self.delta / TYPE_TCC_DELTA_SCALE_FACTOR;
388
389        // small delta
390        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta
391            && delta >= 0
392            && delta <= u8::MAX as i64
393            && buf.remaining_mut() >= 1
394        {
395            buf.put_u8(delta as u8);
396            return Ok(1);
397        }
398
399        // big delta
400        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta
401            && delta >= i16::MIN as i64
402            && delta <= i16::MAX as i64
403            && buf.remaining_mut() >= 2
404        {
405            buf.put_i16(delta as i16);
406            return Ok(2);
407        }
408
409        // overflow
410        Err(Error::DeltaExceedLimit)
411    }
412}
413
414impl Unmarshal for RecvDelta {
415    /// Unmarshal ..
416    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
417    where
418        Self: Sized,
419        B: Buf,
420    {
421        let chunk_len = raw_packet.remaining();
422
423        // must be 1 or 2 bytes
424        if chunk_len != 1 && chunk_len != 2 {
425            return Err(Error::DeltaExceedLimit);
426        }
427
428        let (type_tcc_packet, delta) = if chunk_len == 1 {
429            (
430                SymbolTypeTcc::PacketReceivedSmallDelta,
431                TYPE_TCC_DELTA_SCALE_FACTOR * raw_packet.get_u8() as i64,
432            )
433        } else {
434            (
435                SymbolTypeTcc::PacketReceivedLargeDelta,
436                TYPE_TCC_DELTA_SCALE_FACTOR * raw_packet.get_i16() as i64,
437            )
438        };
439
440        Ok(RecvDelta {
441            type_tcc_packet,
442            delta,
443        })
444    }
445}
446
447/// The offset after header
448const BASE_SEQUENCE_NUMBER_OFFSET: usize = 8;
449/// The offset after header
450const PACKET_STATUS_COUNT_OFFSET: usize = 10;
451/// The offset after header
452const REFERENCE_TIME_OFFSET: usize = 12;
453/// The offset after header
454const FB_PKT_COUNT_OFFSET: usize = 15;
455/// The offset after header
456const PACKET_CHUNK_OFFSET: usize = 16;
457/// len of packet status chunk
458const TYPE_TCC_STATUS_VECTOR_CHUNK: usize = 1;
459
460/// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5>
461pub const TYPE_TCC_DELTA_SCALE_FACTOR: i64 = 250;
462
463// Notice: RFC is wrong: "packet received" (0) and "packet not received" (1)
464// if S == TYPE_TCCSYMBOL_SIZE_ONE_BIT, symbol list will be: TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta
465// if S == TYPE_TCCSYMBOL_SIZE_TWO_BIT, symbol list will be same as above:
466
467static NUM_OF_BITS_OF_SYMBOL_SIZE: [u16; 2] = [1, 2];
468
469/// len of packet status chunk
470const PACKET_STATUS_CHUNK_LENGTH: usize = 2;
471
472/// The longest run a run length chunk holds: 13 bits.
473const MAX_RUN_LENGTH: u16 = 0x1FFF;
474
475/// TransportLayerCC for sender-BWE
476/// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5>
477#[derive(Debug, Default, PartialEq, Eq, Clone)]
478pub struct TransportLayerCc {
479    /// SSRC of sender
480    pub sender_ssrc: u32,
481    /// SSRC of the media source
482    pub media_ssrc: u32,
483    /// Transport wide sequence of rtp extension
484    pub base_sequence_number: u16,
485    /// packet_status_count
486    pub packet_status_count: u16,
487    /// reference_time
488    pub reference_time: u32,
489    /// fb_pkt_count
490    pub fb_pkt_count: u8,
491    /// packet_chunks
492    pub packet_chunks: Vec<PacketStatusChunk>,
493    /// recv_deltas
494    pub recv_deltas: Vec<RecvDelta>,
495}
496
497/// The reference time counts 64 ms ticks.
498pub const TYPE_TCC_REFERENCE_TIME_TICK_MILLIS: i64 = 64;
499
500/// The reference time field is 24 bits wide.
501const REFERENCE_TIME_BITS: u32 = 24;
502const REFERENCE_TIME_MASK: u32 = (1 << REFERENCE_TIME_BITS) - 1;
503
504impl TransportLayerCc {
505    /// The reference time as the draft defines it: a 24-bit signed count of 64 ms ticks.
506    ///
507    /// `reference_time` holds the 24 bits as they are on the wire; this sign-extends them, so
508    /// `0xFFFFFF` reads as -1. The origin is the receiver's own, so only differences between
509    /// feedback packets mean anything: use [`ReferenceTimeUnwrapper`] to follow them.
510    pub fn reference_time_signed(&self) -> i32 {
511        ((self.reference_time << (32 - REFERENCE_TIME_BITS)) as i32) >> (32 - REFERENCE_TIME_BITS)
512    }
513}
514
515/// Follows the 24-bit reference time of successive transport-wide feedback packets across its
516/// wrap, which comes every 2^24 ticks of 64 ms: about 12.4 days.
517///
518/// Feed it the `reference_time` of each feedback packet of one sender, in the order received.
519/// It returns a 64-bit tick count that moves by the shortest signed distance from the last
520/// one, so a step from `0xFFFFFF` to `0` is one tick forward (64 ms) and not 2^24 ticks back,
521/// and a feedback packet that arrives out of order steps back by the little it is behind.
522#[derive(Debug, Default, Clone, PartialEq, Eq)]
523pub struct ReferenceTimeUnwrapper {
524    last: Option<i64>,
525}
526
527impl ReferenceTimeUnwrapper {
528    /// A fresh unwrapper. The first value it sees is taken as is, sign-extended.
529    pub fn new() -> Self {
530        Self::default()
531    }
532
533    /// The unwrapped tick count for `reference_time`, the 24 bits a feedback packet carries.
534    pub fn unwrap(&mut self, reference_time: u32) -> i64 {
535        const SHIFT: u32 = 32 - REFERENCE_TIME_BITS;
536        let reference_time = reference_time & REFERENCE_TIME_MASK;
537        let unwrapped = match self.last {
538            None => (((reference_time << SHIFT) as i32) >> SHIFT) as i64,
539            Some(last) => {
540                // The distance from the last value, modulo 2^24, read as signed.
541                let step = reference_time.wrapping_sub(last as u32) & REFERENCE_TIME_MASK;
542                last + (((step << SHIFT) as i32) >> SHIFT) as i64
543            }
544        };
545        self.last = Some(unwrapped);
546        unwrapped
547    }
548
549    /// The unwrapped reference time of `reference_time` in milliseconds.
550    pub fn unwrap_millis(&mut self, reference_time: u32) -> i64 {
551        self.unwrap(reference_time) * TYPE_TCC_REFERENCE_TIME_TICK_MILLIS
552    }
553}
554
555impl fmt::Display for TransportLayerCc {
556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557        let mut out = String::new();
558        out += format!("TransportLayerCC:\n\tSender Ssrc {}\n", self.sender_ssrc).as_str();
559        out += format!("\tMedia Ssrc {}\n", self.media_ssrc).as_str();
560        out += format!("\tBase Sequence Number {}\n", self.base_sequence_number).as_str();
561        out += format!("\tStatus Count {}\n", self.packet_status_count).as_str();
562        out += format!("\tReference Time {}\n", self.reference_time).as_str();
563        out += format!("\tFeedback Packet Count {}\n", self.fb_pkt_count).as_str();
564        out += "\tpacket_chunks ";
565        out += "\n\trecv_deltas ";
566        for delta in &self.recv_deltas {
567            out += format!("{delta:?} ").as_str();
568        }
569        out += "\n";
570
571        write!(f, "{out}")
572    }
573}
574
575impl Packet for TransportLayerCc {
576    fn header(&self) -> Header {
577        Header {
578            padding: get_padding_size(self.raw_size()) != 0,
579            count: FORMAT_TCC,
580            packet_type: PacketType::TransportSpecificFeedback,
581            length: ((self.marshal_size() / 4) - 1) as u16,
582        }
583    }
584
585    /// destination_ssrc returns an array of SSRC values that this packet refers to.
586    fn destination_ssrc(&self) -> Vec<u32> {
587        vec![self.media_ssrc]
588    }
589
590    fn raw_size(&self) -> usize {
591        let mut n = HEADER_LENGTH + PACKET_CHUNK_OFFSET + self.packet_chunks.len() * 2;
592        for d in &self.recv_deltas {
593            // small delta
594            if d.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta {
595                n += 1;
596            } else {
597                n += 2
598            }
599        }
600        n
601    }
602
603    fn as_any(&self) -> &dyn Any {
604        self
605    }
606
607    fn equal(&self, other: &dyn Packet) -> bool {
608        other.as_any().downcast_ref::<TransportLayerCc>() == Some(self)
609    }
610
611    fn cloned(&self) -> Box<dyn Packet> {
612        Box::new(self.clone())
613    }
614}
615
616impl MarshalSize for TransportLayerCc {
617    fn marshal_size(&self) -> usize {
618        let l = self.raw_size();
619        // align to 32-bit boundary
620        l + get_padding_size(l)
621    }
622}
623
624impl Marshal for TransportLayerCc {
625    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
626        if buf.remaining_mut() < self.marshal_size() {
627            return Err(Error::BufferTooShort);
628        }
629
630        let h = self.header();
631        let n = h.marshal_to(buf)?;
632        buf = &mut buf[n..];
633
634        buf.put_u32(self.sender_ssrc);
635        buf.put_u32(self.media_ssrc);
636        buf.put_u16(self.base_sequence_number);
637        buf.put_u16(self.packet_status_count);
638
639        let reference_time_and_fb_pkt_count = append_nbits_to_uint32(0, 24, self.reference_time);
640        let reference_time_and_fb_pkt_count =
641            append_nbits_to_uint32(reference_time_and_fb_pkt_count, 8, self.fb_pkt_count as u32);
642
643        buf.put_u32(reference_time_and_fb_pkt_count);
644
645        for chunk in &self.packet_chunks {
646            let n = chunk.marshal_to(buf)?;
647            buf = &mut buf[n..];
648        }
649
650        for delta in &self.recv_deltas {
651            let n = delta.marshal_to(buf)?;
652            buf = &mut buf[n..];
653        }
654
655        if h.padding {
656            put_padding(buf, self.raw_size());
657        }
658
659        Ok(self.marshal_size())
660    }
661}
662
663impl Unmarshal for TransportLayerCc {
664    /// Unmarshal ..
665    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
666    where
667        Self: Sized,
668        B: Buf,
669    {
670        // The P bit is honoured here: the padding octets are counted in `length` but are not
671        // control information, so the chunks and the deltas end before them.
672        let (h, mut body) = read_packet(raw_packet)?;
673        if h.packet_type != PacketType::TransportSpecificFeedback || h.count != FORMAT_TCC {
674            return Err(Error::WrongType);
675        }
676
677        // https://tools.ietf.org/html/rfc4585#page-33
678        // header's length + payload's length
679        let total_length = HEADER_LENGTH + body.len();
680        if total_length < HEADER_LENGTH + PACKET_CHUNK_OFFSET {
681            return Err(Error::PacketTooShort);
682        }
683        let raw_packet = &mut body;
684
685        let sender_ssrc = raw_packet.get_u32();
686        let media_ssrc = raw_packet.get_u32();
687        let base_sequence_number = raw_packet.get_u16();
688        let packet_status_count = raw_packet.get_u16();
689
690        let mut buf = vec![0u8; 3];
691        buf[0] = raw_packet.get_u8();
692        buf[1] = raw_packet.get_u8();
693        buf[2] = raw_packet.get_u8();
694        let reference_time = get_24bits_from_bytes(&buf);
695        let fb_pkt_count = raw_packet.get_u8();
696        let mut packet_chunks = vec![];
697        let mut recv_deltas = vec![];
698
699        let mut packet_status_pos = HEADER_LENGTH + PACKET_CHUNK_OFFSET;
700        let mut processed_packet_num = 0u16;
701        // The receive-delta bytes the chunks read so far call for: one per small delta, two per
702        // large one. Checked against the packet before any delta is queued, so a few chunk bytes
703        // cannot claim tens of thousands of deltas the packet does not carry.
704        let mut delta_bytes_needed = 0usize;
705        while processed_packet_num < packet_status_count {
706            // A chunk may be the last thing in the packet: a report of packets that were not
707            // received has no delta after its chunks.
708            if packet_status_pos + PACKET_STATUS_CHUNK_LENGTH > total_length {
709                return Err(Error::PacketTooShort);
710            }
711
712            let mut chunk_reader = raw_packet.copy_to_bytes(PACKET_STATUS_CHUNK_LENGTH);
713            let b0 = chunk_reader[0];
714
715            let typ = get_nbits_from_byte(b0, 0, 1);
716            let initial_packet_status: PacketStatusChunk;
717            match typ.into() {
718                StatusChunkTypeTcc::RunLengthChunk => {
719                    let packet_status = RunLengthChunk::unmarshal(&mut chunk_reader)?;
720                    let packet_number_to_process =
721                        (packet_status_count - processed_packet_num).min(packet_status.run_length);
722
723                    if packet_status.packet_status_symbol == SymbolTypeTcc::PacketReceivedSmallDelta
724                        || packet_status.packet_status_symbol
725                            == SymbolTypeTcc::PacketReceivedLargeDelta
726                    {
727                        let delta_size = if packet_status.packet_status_symbol
728                            == SymbolTypeTcc::PacketReceivedLargeDelta
729                        {
730                            2
731                        } else {
732                            1
733                        };
734                        delta_bytes_needed += packet_number_to_process as usize * delta_size;
735                        if packet_status_pos + PACKET_STATUS_CHUNK_LENGTH + delta_bytes_needed
736                            > total_length
737                        {
738                            return Err(Error::PacketTooShort);
739                        }
740
741                        let mut j = 0u16;
742
743                        while j < packet_number_to_process {
744                            recv_deltas.push(RecvDelta {
745                                type_tcc_packet: packet_status.packet_status_symbol,
746                                ..Default::default()
747                            });
748
749                            j += 1;
750                        }
751                    }
752
753                    initial_packet_status = PacketStatusChunk::RunLengthChunk(packet_status);
754
755                    processed_packet_num =
756                        processed_packet_num.saturating_add(packet_number_to_process);
757                }
758
759                StatusChunkTypeTcc::StatusVectorChunk => {
760                    let packet_status = StatusVectorChunk::unmarshal(&mut chunk_reader)?;
761
762                    // The status count ends the list: the symbols of the last chunk beyond it
763                    // describe no packet and own no delta.
764                    let remaining = (packet_status_count - processed_packet_num) as usize;
765                    let reported = &packet_status.symbol_list
766                        [..packet_status.symbol_list.len().min(remaining)];
767
768                    delta_bytes_needed += reported
769                        .iter()
770                        .map(|sym| match sym {
771                            SymbolTypeTcc::PacketReceivedLargeDelta
772                                if packet_status.symbol_size == SymbolSizeTypeTcc::TwoBit =>
773                            {
774                                2
775                            }
776                            SymbolTypeTcc::PacketReceivedSmallDelta => 1,
777                            _ => 0,
778                        })
779                        .sum::<usize>();
780                    if packet_status_pos + PACKET_STATUS_CHUNK_LENGTH + delta_bytes_needed
781                        > total_length
782                    {
783                        return Err(Error::PacketTooShort);
784                    }
785
786                    match packet_status.symbol_size {
787                        SymbolSizeTypeTcc::OneBit => {
788                            for sym in reported {
789                                if *sym == SymbolTypeTcc::PacketReceivedSmallDelta {
790                                    recv_deltas.push(RecvDelta {
791                                        type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
792                                        ..Default::default()
793                                    })
794                                }
795                            }
796                        }
797
798                        SymbolSizeTypeTcc::TwoBit => {
799                            for sym in reported {
800                                if *sym == SymbolTypeTcc::PacketReceivedSmallDelta
801                                    || *sym == SymbolTypeTcc::PacketReceivedLargeDelta
802                                {
803                                    recv_deltas.push(RecvDelta {
804                                        type_tcc_packet: *sym,
805                                        ..Default::default()
806                                    })
807                                }
808                            }
809                        }
810                    }
811
812                    processed_packet_num =
813                        processed_packet_num.saturating_add(packet_status.symbol_list.len() as u16);
814                    initial_packet_status = PacketStatusChunk::StatusVectorChunk(packet_status);
815                }
816            }
817
818            packet_status_pos += PACKET_STATUS_CHUNK_LENGTH;
819            packet_chunks.push(initial_packet_status);
820        }
821
822        let mut recv_deltas_pos = packet_status_pos;
823
824        for delta in &mut recv_deltas {
825            if recv_deltas_pos >= total_length {
826                return Err(Error::PacketTooShort);
827            }
828
829            if delta.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta {
830                let mut delta_reader = raw_packet.take(1);
831                *delta = RecvDelta::unmarshal(&mut delta_reader)?;
832                recv_deltas_pos += 1;
833            }
834
835            if delta.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta {
836                let mut delta_reader = raw_packet.take(2);
837                *delta = RecvDelta::unmarshal(&mut delta_reader)?;
838                recv_deltas_pos += 2;
839            }
840        }
841
842        Ok(TransportLayerCc {
843            sender_ssrc,
844            media_ssrc,
845            base_sequence_number,
846            packet_status_count,
847            reference_time,
848            fb_pkt_count,
849            packet_chunks,
850            recv_deltas,
851        })
852    }
853}