1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#[cfg(test)]
mod transport_layer_cc_test;

use std::any::Any;
use std::fmt;

use bytes::{Buf, BufMut};
use util::marshal::{Marshal, MarshalSize, Unmarshal};

use crate::error::Error;
use crate::header::*;
use crate::packet::*;
use crate::util::*;

type Result<T> = std::result::Result<T, util::Error>;

/// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5
/// 0                   1                   2                   3
/// 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
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |V=2|P|  FMT=15 |    PT=205     |           length              |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                     SSRC of packet sender                     |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                      SSRC of media source                     |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |      base sequence number     |      packet status count      |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                 reference time                | fb pkt. count |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |          packet chunk         |         packet chunk          |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// .                                                               .
/// .                                                               .
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |         packet chunk          |  recv delta   |  recv delta   |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// .                                                               .
/// .                                                               .
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |           recv delta          |  recv delta   | zero padding  |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

// for packet status chunk
/// type of packet status chunk
#[derive(Default, PartialEq, Eq, Debug, Clone)]
#[repr(u16)]
pub enum StatusChunkTypeTcc {
    #[default]
    RunLengthChunk = 0,
    StatusVectorChunk = 1,
}

/// type of packet status symbol and recv delta
#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
#[repr(u16)]
pub enum SymbolTypeTcc {
    /// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1
    #[default]
    PacketNotReceived = 0,
    /// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1
    PacketReceivedSmallDelta = 1,
    /// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1
    PacketReceivedLargeDelta = 2,
    /// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-7
    /// see Example 2: "packet received, w/o recv delta"
    PacketReceivedWithoutDelta = 3,
}

/// for status vector chunk
#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
#[repr(u16)]
pub enum SymbolSizeTypeTcc {
    /// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.4
    #[default]
    OneBit = 0,
    TwoBit = 1,
}

impl From<u16> for SymbolSizeTypeTcc {
    fn from(val: u16) -> Self {
        match val {
            0 => SymbolSizeTypeTcc::OneBit,
            _ => SymbolSizeTypeTcc::TwoBit,
        }
    }
}

impl From<u16> for StatusChunkTypeTcc {
    fn from(val: u16) -> Self {
        match val {
            0 => StatusChunkTypeTcc::RunLengthChunk,
            _ => StatusChunkTypeTcc::StatusVectorChunk,
        }
    }
}

impl From<u16> for SymbolTypeTcc {
    fn from(val: u16) -> Self {
        match val {
            0 => SymbolTypeTcc::PacketNotReceived,
            1 => SymbolTypeTcc::PacketReceivedSmallDelta,
            2 => SymbolTypeTcc::PacketReceivedLargeDelta,
            _ => SymbolTypeTcc::PacketReceivedWithoutDelta,
        }
    }
}

/// PacketStatusChunk has two kinds:
/// RunLengthChunk and StatusVectorChunk
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PacketStatusChunk {
    RunLengthChunk(RunLengthChunk),
    StatusVectorChunk(StatusVectorChunk),
}

impl MarshalSize for PacketStatusChunk {
    fn marshal_size(&self) -> usize {
        match self {
            PacketStatusChunk::RunLengthChunk(c) => c.marshal_size(),
            PacketStatusChunk::StatusVectorChunk(c) => c.marshal_size(),
        }
    }
}

impl Marshal for PacketStatusChunk {
    /// Marshal ..
    fn marshal_to(&self, buf: &mut [u8]) -> Result<usize> {
        match self {
            PacketStatusChunk::RunLengthChunk(c) => c.marshal_to(buf),
            PacketStatusChunk::StatusVectorChunk(c) => c.marshal_to(buf),
        }
    }
}

/// RunLengthChunk T=TypeTCCRunLengthChunk
/// 0                   1
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |T| S |       Run Length        |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RunLengthChunk {
    /// T = TypeTCCRunLengthChunk
    pub type_tcc: StatusChunkTypeTcc,
    /// S: type of packet status
    /// kind: TypeTCCPacketNotReceived or...
    pub packet_status_symbol: SymbolTypeTcc,
    /// run_length: count of S
    pub run_length: u16,
}

impl MarshalSize for RunLengthChunk {
    fn marshal_size(&self) -> usize {
        PACKET_STATUS_CHUNK_LENGTH
    }
}

impl Marshal for RunLengthChunk {
    /// Marshal ..
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        // append 1 bit '0'
        let mut dst = set_nbits_of_uint16(0, 1, 0, 0)?;

        // append 2 bit packet_status_symbol
        dst = set_nbits_of_uint16(dst, 2, 1, self.packet_status_symbol as u16)?;

        // append 13 bit run_length
        dst = set_nbits_of_uint16(dst, 13, 3, self.run_length)?;

        buf.put_u16(dst);

        Ok(PACKET_STATUS_CHUNK_LENGTH)
    }
}

impl Unmarshal for RunLengthChunk {
    /// Unmarshal ..
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        let raw_packet_len = raw_packet.remaining();
        if raw_packet_len < PACKET_STATUS_CHUNK_LENGTH {
            return Err(Error::PacketStatusChunkLength.into());
        }

        // record type
        let type_tcc = StatusChunkTypeTcc::RunLengthChunk;

        let b0 = raw_packet.get_u8();
        let b1 = raw_packet.get_u8();

        // get PacketStatusSymbol
        let packet_status_symbol = get_nbits_from_byte(b0, 1, 2).into();

        // get RunLength
        let run_length = ((get_nbits_from_byte(b0, 3, 5) as usize) << 8) as u16 + (b1 as u16);

        Ok(RunLengthChunk {
            type_tcc,
            packet_status_symbol,
            run_length,
        })
    }
}

/// StatusVectorChunk T=typeStatusVectorChunk
/// 0                   1
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |T|S|       symbol list         |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StatusVectorChunk {
    /// T = TypeTCCRunLengthChunk
    pub type_tcc: StatusChunkTypeTcc,

    /// TypeTCCSymbolSizeOneBit or TypeTCCSymbolSizeTwoBit
    pub symbol_size: SymbolSizeTypeTcc,

    /// when symbol_size = TypeTCCSymbolSizeOneBit, symbol_list is 14*1bit:
    /// TypeTCCSymbolListPacketReceived or TypeTCCSymbolListPacketNotReceived
    /// when symbol_size = TypeTCCSymbolSizeTwoBit, symbol_list is 7*2bit:
    /// TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta TypeTCCPacketReceivedLargeDelta or typePacketReserved
    pub symbol_list: Vec<SymbolTypeTcc>,
}

impl MarshalSize for StatusVectorChunk {
    fn marshal_size(&self) -> usize {
        PACKET_STATUS_CHUNK_LENGTH
    }
}

impl Marshal for StatusVectorChunk {
    /// Marshal ..
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        // set first bit '1'
        let mut dst = set_nbits_of_uint16(0, 1, 0, 1)?;

        // set second bit symbol_size
        dst = set_nbits_of_uint16(dst, 1, 1, self.symbol_size as u16)?;

        let num_of_bits = NUM_OF_BITS_OF_SYMBOL_SIZE[self.symbol_size as usize];
        // append 14 bit symbol_list
        for (i, s) in self.symbol_list.iter().enumerate() {
            let index = num_of_bits * (i as u16) + 2;
            dst = set_nbits_of_uint16(dst, num_of_bits, index, *s as u16)?;
        }

        buf.put_u16(dst);

        Ok(PACKET_STATUS_CHUNK_LENGTH)
    }
}

impl Unmarshal for StatusVectorChunk {
    /// Unmarshal ..
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        let raw_packet_len = raw_packet.remaining();
        if raw_packet_len < PACKET_STATUS_CHUNK_LENGTH {
            return Err(Error::PacketBeforeCname.into());
        }

        let type_tcc = StatusChunkTypeTcc::StatusVectorChunk;

        let b0 = raw_packet.get_u8();
        let b1 = raw_packet.get_u8();

        let symbol_size = get_nbits_from_byte(b0, 1, 1).into();

        let mut symbol_list: Vec<SymbolTypeTcc> = vec![];
        match symbol_size {
            SymbolSizeTypeTcc::OneBit => {
                for i in 0..6u16 {
                    symbol_list.push(get_nbits_from_byte(b0, 2 + i, 1).into());
                }

                for i in 0..8u16 {
                    symbol_list.push(get_nbits_from_byte(b1, i, 1).into())
                }
            }

            SymbolSizeTypeTcc::TwoBit => {
                for i in 0..3u16 {
                    symbol_list.push(get_nbits_from_byte(b0, 2 + i * 2, 2).into());
                }

                for i in 0..4u16 {
                    symbol_list.push(get_nbits_from_byte(b1, i * 2, 2).into());
                }
            }
        }

        Ok(StatusVectorChunk {
            type_tcc,
            symbol_size,
            symbol_list,
        })
    }
}

/// RecvDelta are represented as multiples of 250us
/// small delta is 1 byte: [0,63.75]ms = [0, 63750]us = [0, 255]*250us
/// big delta is 2 bytes: [-8192.0, 8191.75]ms = [-8192000, 8191750]us = [-32768, 32767]*250us
/// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RecvDelta {
    pub type_tcc_packet: SymbolTypeTcc,
    /// us
    pub delta: i64,
}

impl MarshalSize for RecvDelta {
    fn marshal_size(&self) -> usize {
        let delta = self.delta / TYPE_TCC_DELTA_SCALE_FACTOR;

        // small delta
        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta
            && delta >= 0
            && delta <= std::u8::MAX as i64
        {
            return 1;
        }

        // big delta
        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta
            && delta >= std::i16::MIN as i64
            && delta <= std::u16::MAX as i64
        {
            return 2;
        }

        0
    }
}

impl Marshal for RecvDelta {
    /// Marshal ..
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        let delta = self.delta / TYPE_TCC_DELTA_SCALE_FACTOR;

        // small delta
        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta
            && delta >= 0
            && delta <= std::u8::MAX as i64
            && buf.remaining_mut() >= 1
        {
            buf.put_u8(delta as u8);
            return Ok(1);
        }

        // big delta
        if self.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta
            && delta >= std::i16::MIN as i64
            && delta <= std::u16::MAX as i64
            && buf.remaining_mut() >= 2
        {
            buf.put_u16(delta as u16);
            return Ok(2);
        }

        // overflow
        Err(Error::DeltaExceedLimit.into())
    }
}

impl Unmarshal for RecvDelta {
    /// Unmarshal ..
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        let chunk_len = raw_packet.remaining();

        // must be 1 or 2 bytes
        if chunk_len != 1 && chunk_len != 2 {
            return Err(Error::DeltaExceedLimit.into());
        }

        let (type_tcc_packet, delta) = if chunk_len == 1 {
            (
                SymbolTypeTcc::PacketReceivedSmallDelta,
                TYPE_TCC_DELTA_SCALE_FACTOR * raw_packet.get_u8() as i64,
            )
        } else {
            (
                SymbolTypeTcc::PacketReceivedLargeDelta,
                TYPE_TCC_DELTA_SCALE_FACTOR * raw_packet.get_i16() as i64,
            )
        };

        Ok(RecvDelta {
            type_tcc_packet,
            delta,
        })
    }
}

/// The offset after header
const BASE_SEQUENCE_NUMBER_OFFSET: usize = 8;
/// The offset after header
const PACKET_STATUS_COUNT_OFFSET: usize = 10;
/// The offset after header
const REFERENCE_TIME_OFFSET: usize = 12;
/// The offset after header
const FB_PKT_COUNT_OFFSET: usize = 15;
/// The offset after header
const PACKET_CHUNK_OFFSET: usize = 16;
/// len of packet status chunk
const TYPE_TCC_STATUS_VECTOR_CHUNK: usize = 1;

/// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5
pub const TYPE_TCC_DELTA_SCALE_FACTOR: i64 = 250;

// Notice: RFC is wrong: "packet received" (0) and "packet not received" (1)
// if S == TYPE_TCCSYMBOL_SIZE_ONE_BIT, symbol list will be: TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta
// if S == TYPE_TCCSYMBOL_SIZE_TWO_BIT, symbol list will be same as above:

static NUM_OF_BITS_OF_SYMBOL_SIZE: [u16; 2] = [1, 2];

/// len of packet status chunk
const PACKET_STATUS_CHUNK_LENGTH: usize = 2;

/// TransportLayerCC for sender-BWE
/// https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct TransportLayerCc {
    /// SSRC of sender
    pub sender_ssrc: u32,
    /// SSRC of the media source
    pub media_ssrc: u32,
    /// Transport wide sequence of rtp extension
    pub base_sequence_number: u16,
    /// packet_status_count
    pub packet_status_count: u16,
    /// reference_time
    pub reference_time: u32,
    /// fb_pkt_count
    pub fb_pkt_count: u8,
    /// packet_chunks
    pub packet_chunks: Vec<PacketStatusChunk>,
    /// recv_deltas
    pub recv_deltas: Vec<RecvDelta>,
}

impl fmt::Display for TransportLayerCc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = String::new();
        out += format!("TransportLayerCC:\n\tSender Ssrc {}\n", self.sender_ssrc).as_str();
        out += format!("\tMedia Ssrc {}\n", self.media_ssrc).as_str();
        out += format!("\tBase Sequence Number {}\n", self.base_sequence_number).as_str();
        out += format!("\tStatus Count {}\n", self.packet_status_count).as_str();
        out += format!("\tReference Time {}\n", self.reference_time).as_str();
        out += format!("\tFeedback Packet Count {}\n", self.fb_pkt_count).as_str();
        out += "\tpacket_chunks ";
        out += "\n\trecv_deltas ";
        for delta in &self.recv_deltas {
            out += format!("{delta:?} ").as_str();
        }
        out += "\n";

        write!(f, "{out}")
    }
}

impl Packet for TransportLayerCc {
    fn header(&self) -> Header {
        Header {
            padding: get_padding_size(self.raw_size()) != 0,
            count: FORMAT_TCC,
            packet_type: PacketType::TransportSpecificFeedback,
            length: ((self.marshal_size() / 4) - 1) as u16,
        }
    }

    /// destination_ssrc returns an array of SSRC values that this packet refers to.
    fn destination_ssrc(&self) -> Vec<u32> {
        vec![self.media_ssrc]
    }

    fn raw_size(&self) -> usize {
        let mut n = HEADER_LENGTH + PACKET_CHUNK_OFFSET + self.packet_chunks.len() * 2;
        for d in &self.recv_deltas {
            // small delta
            if d.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta {
                n += 1;
            } else {
                n += 2
            }
        }
        n
    }

    fn as_any(&self) -> &(dyn Any + Send + Sync) {
        self
    }

    fn equal(&self, other: &(dyn Packet + Send + Sync)) -> bool {
        other
            .as_any()
            .downcast_ref::<TransportLayerCc>()
            .map_or(false, |a| self == a)
    }

    fn cloned(&self) -> Box<dyn Packet + Send + Sync> {
        Box::new(self.clone())
    }
}

impl MarshalSize for TransportLayerCc {
    fn marshal_size(&self) -> usize {
        let l = self.raw_size();
        // align to 32-bit boundary
        l + get_padding_size(l)
    }
}

impl Marshal for TransportLayerCc {
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        if buf.remaining_mut() < self.marshal_size() {
            return Err(Error::BufferTooShort.into());
        }

        let h = self.header();
        let n = h.marshal_to(buf)?;
        buf = &mut buf[n..];

        buf.put_u32(self.sender_ssrc);
        buf.put_u32(self.media_ssrc);
        buf.put_u16(self.base_sequence_number);
        buf.put_u16(self.packet_status_count);

        let reference_time_and_fb_pkt_count = append_nbits_to_uint32(0, 24, self.reference_time);
        let reference_time_and_fb_pkt_count =
            append_nbits_to_uint32(reference_time_and_fb_pkt_count, 8, self.fb_pkt_count as u32);

        buf.put_u32(reference_time_and_fb_pkt_count);

        for chunk in &self.packet_chunks {
            let n = chunk.marshal_to(buf)?;
            buf = &mut buf[n..];
        }

        for delta in &self.recv_deltas {
            let n = delta.marshal_to(buf)?;
            buf = &mut buf[n..];
        }

        if h.padding {
            put_padding(buf, self.raw_size());
        }

        Ok(self.marshal_size())
    }
}

impl Unmarshal for TransportLayerCc {
    /// Unmarshal ..
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        let raw_packet_len = raw_packet.remaining();
        if raw_packet_len < (HEADER_LENGTH + SSRC_LENGTH) {
            return Err(Error::PacketTooShort.into());
        }

        let h = Header::unmarshal(raw_packet)?;

        // https://tools.ietf.org/html/rfc4585#page-33
        // header's length + payload's length
        let total_length = 4 * (h.length + 1) as usize;

        if total_length < HEADER_LENGTH + PACKET_CHUNK_OFFSET {
            return Err(Error::PacketTooShort.into());
        }

        if raw_packet_len < total_length {
            return Err(Error::PacketTooShort.into());
        }

        if h.packet_type != PacketType::TransportSpecificFeedback || h.count != FORMAT_TCC {
            return Err(Error::WrongType.into());
        }

        let sender_ssrc = raw_packet.get_u32();
        let media_ssrc = raw_packet.get_u32();
        let base_sequence_number = raw_packet.get_u16();
        let packet_status_count = raw_packet.get_u16();

        let mut buf = vec![0u8; 3];
        buf[0] = raw_packet.get_u8();
        buf[1] = raw_packet.get_u8();
        buf[2] = raw_packet.get_u8();
        let reference_time = get_24bits_from_bytes(&buf);
        let fb_pkt_count = raw_packet.get_u8();
        let mut packet_chunks = vec![];
        let mut recv_deltas = vec![];

        let mut packet_status_pos = HEADER_LENGTH + PACKET_CHUNK_OFFSET;
        let mut processed_packet_num = 0u16;
        while processed_packet_num < packet_status_count {
            if packet_status_pos + PACKET_STATUS_CHUNK_LENGTH >= total_length {
                return Err(Error::PacketTooShort.into());
            }

            let mut chunk_reader = raw_packet.copy_to_bytes(PACKET_STATUS_CHUNK_LENGTH);
            let b0 = chunk_reader[0];

            let typ = get_nbits_from_byte(b0, 0, 1);
            let initial_packet_status: PacketStatusChunk;
            match typ.into() {
                StatusChunkTypeTcc::RunLengthChunk => {
                    let packet_status = RunLengthChunk::unmarshal(&mut chunk_reader)?;

                    let packet_number_to_process =
                        (packet_status_count - processed_packet_num).min(packet_status.run_length);

                    if packet_status.packet_status_symbol == SymbolTypeTcc::PacketReceivedSmallDelta
                        || packet_status.packet_status_symbol
                            == SymbolTypeTcc::PacketReceivedLargeDelta
                    {
                        let mut j = 0u16;

                        while j < packet_number_to_process {
                            recv_deltas.push(RecvDelta {
                                type_tcc_packet: packet_status.packet_status_symbol,
                                ..Default::default()
                            });

                            j += 1;
                        }
                    }

                    initial_packet_status = PacketStatusChunk::RunLengthChunk(packet_status);
                    processed_packet_num += packet_number_to_process;
                }

                StatusChunkTypeTcc::StatusVectorChunk => {
                    let packet_status = StatusVectorChunk::unmarshal(&mut chunk_reader)?;

                    match packet_status.symbol_size {
                        SymbolSizeTypeTcc::OneBit => {
                            for sym in &packet_status.symbol_list {
                                if *sym == SymbolTypeTcc::PacketReceivedSmallDelta {
                                    recv_deltas.push(RecvDelta {
                                        type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
                                        ..Default::default()
                                    })
                                }
                            }
                        }

                        SymbolSizeTypeTcc::TwoBit => {
                            for sym in &packet_status.symbol_list {
                                if *sym == SymbolTypeTcc::PacketReceivedSmallDelta
                                    || *sym == SymbolTypeTcc::PacketReceivedLargeDelta
                                {
                                    recv_deltas.push(RecvDelta {
                                        type_tcc_packet: *sym,
                                        ..Default::default()
                                    })
                                }
                            }
                        }
                    }

                    processed_packet_num += packet_status.symbol_list.len() as u16;
                    initial_packet_status = PacketStatusChunk::StatusVectorChunk(packet_status);
                }
            }

            packet_status_pos += PACKET_STATUS_CHUNK_LENGTH;
            packet_chunks.push(initial_packet_status);
        }

        let mut recv_deltas_pos = packet_status_pos;

        for delta in &mut recv_deltas {
            if recv_deltas_pos >= total_length {
                return Err(Error::PacketTooShort.into());
            }

            if delta.type_tcc_packet == SymbolTypeTcc::PacketReceivedSmallDelta {
                let mut delta_reader = raw_packet.take(1);
                *delta = RecvDelta::unmarshal(&mut delta_reader)?;
                recv_deltas_pos += 1;
            }

            if delta.type_tcc_packet == SymbolTypeTcc::PacketReceivedLargeDelta {
                let mut delta_reader = raw_packet.take(2);
                *delta = RecvDelta::unmarshal(&mut delta_reader)?;
                recv_deltas_pos += 2;
            }
        }

        if
        /*h.padding &&*/
        raw_packet.has_remaining() {
            raw_packet.advance(raw_packet.remaining());
        }

        Ok(TransportLayerCc {
            sender_ssrc,
            media_ssrc,
            base_sequence_number,
            packet_status_count,
            reference_time,
            fb_pkt_count,
            packet_chunks,
            recv_deltas,
        })
    }
}