[go: up one dir, main page]

rtp 0.6.4

A pure Rust implementation of RTP
Documentation
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
use crate::error::{Error, Result};
use crate::packetizer::Depacketizer;
use bytes::Bytes;

#[cfg(test)]
mod h265_test;

///
/// Network Abstraction Unit Header implementation
///

const H265NALU_HEADER_SIZE: usize = 2;
/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
const H265NALU_AGGREGATION_PACKET_TYPE: u8 = 48;
/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3
const H265NALU_FRAGMENTATION_UNIT_TYPE: u8 = 49;
/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4
const H265NALU_PACI_PACKET_TYPE: u8 = 50;

/// H265NALUHeader is a H265 NAL Unit Header
/// https://datatracker.ietf.org/doc/html/rfc7798#section-1.1.4
/// +---------------+---------------+
///  |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|
///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///  |F|   Type    |  layer_id  | tid |
///  +-------------+-----------------+
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct H265NALUHeader(pub u16);

impl H265NALUHeader {
    fn new(high_byte: u8, low_byte: u8) -> Self {
        H265NALUHeader(((high_byte as u16) << 8) | low_byte as u16)
    }

    /// f is the forbidden bit, should always be 0.
    pub fn f(&self) -> bool {
        (self.0 >> 15) != 0
    }

    /// nalu_type of NAL Unit.
    pub fn nalu_type(&self) -> u8 {
        // 01111110 00000000
        const MASK: u16 = 0b01111110 << 8;
        ((self.0 & MASK) >> (8 + 1)) as u8
    }

    /// is_type_vcl_unit returns whether or not the NAL Unit type is a VCL NAL unit.
    pub fn is_type_vcl_unit(&self) -> bool {
        // Type is coded on 6 bits
        const MSB_MASK: u8 = 0b00100000;
        (self.nalu_type() & MSB_MASK) == 0
    }

    /// layer_id should always be 0 in non-3D HEVC context.
    pub fn layer_id(&self) -> u8 {
        // 00000001 11111000
        const MASK: u16 = (0b00000001 << 8) | 0b11111000;
        ((self.0 & MASK) >> 3) as u8
    }

    /// tid is the temporal identifier of the NAL unit +1.
    pub fn tid(&self) -> u8 {
        const MASK: u16 = 0b00000111;
        (self.0 & MASK) as u8
    }

    /// is_aggregation_packet returns whether or not the packet is an Aggregation packet.
    pub fn is_aggregation_packet(&self) -> bool {
        self.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE
    }

    /// is_fragmentation_unit returns whether or not the packet is a Fragmentation Unit packet.
    pub fn is_fragmentation_unit(&self) -> bool {
        self.nalu_type() == H265NALU_FRAGMENTATION_UNIT_TYPE
    }

    /// is_paci_packet returns whether or not the packet is a PACI packet.
    pub fn is_paci_packet(&self) -> bool {
        self.nalu_type() == H265NALU_PACI_PACKET_TYPE
    }
}

///
/// Single NAL Unit Packet implementation
///
/// H265SingleNALUnitPacket represents a NALU packet, containing exactly one NAL unit.
///     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
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |           PayloadHdr          |      DONL (conditional)       |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                                                               |
///   |                  NAL unit payload data                        |
///   |                                                               |
///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                               :...OPTIONAL RTP padding        |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.1
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265SingleNALUnitPacket {
    /// payload_header is the header of the H265 packet.
    payload_header: H265NALUHeader,
    /// donl is a 16-bit field, that may or may not be present.
    donl: Option<u16>,
    /// payload of the fragmentation unit.
    payload: Bytes,

    might_need_donl: bool,
}

impl H265SingleNALUnitPacket {
    /// with_donl can be called to specify whether or not DONL might be parsed.
    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
    pub fn with_donl(&mut self, value: bool) {
        self.might_need_donl = value;
    }

    /// depacketize parses the passed byte slice and stores the result in the H265SingleNALUnitPacket this method is called upon.
    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
        if payload.len() <= H265NALU_HEADER_SIZE {
            return Err(Error::ErrShortPacket);
        }

        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
        if payload_header.f() {
            return Err(Error::ErrH265CorruptedPacket);
        }
        if payload_header.is_fragmentation_unit()
            || payload_header.is_paci_packet()
            || payload_header.is_aggregation_packet()
        {
            return Err(Error::ErrInvalidH265PacketType);
        }

        let mut payload = payload.slice(2..);

        if self.might_need_donl {
            // sizeof(uint16)
            if payload.len() <= 2 {
                return Err(Error::ErrShortPacket);
            }

            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
            self.donl = Some(donl);
            payload = payload.slice(2..);
        }

        self.payload_header = payload_header;
        self.payload = payload;

        Ok(())
    }

    /// payload_header returns the NALU header of the packet.
    pub fn payload_header(&self) -> H265NALUHeader {
        self.payload_header
    }

    /// donl returns the DONL of the packet.
    pub fn donl(&self) -> Option<u16> {
        self.donl
    }

    /// payload returns the Fragmentation Unit packet payload.
    pub fn payload(&self) -> Bytes {
        self.payload.clone()
    }
}

///
/// Aggregation Packets implementation
///
/// H265AggregationUnitFirst represent the First Aggregation Unit in an AP.
///
///    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
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///                   :       DONL (conditional)      |   NALU size   |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |   NALU size   |                                               |
///   +-+-+-+-+-+-+-+-+         NAL unit                              |
///   |                                                               |
///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                               :
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265AggregationUnitFirst {
    donl: Option<u16>,
    nal_unit_size: u16,
    nal_unit: Bytes,
}

impl H265AggregationUnitFirst {
    /// donl field, when present, specifies the value of the 16 least
    /// significant bits of the decoding order number of the aggregated NAL
    /// unit.
    pub fn donl(&self) -> Option<u16> {
        self.donl
    }

    /// nalu_size represents the size, in bytes, of the nal_unit.
    pub fn nalu_size(&self) -> u16 {
        self.nal_unit_size
    }

    /// nal_unit payload.
    pub fn nal_unit(&self) -> Bytes {
        self.nal_unit.clone()
    }
}

/// H265AggregationUnit represent the an Aggregation Unit in an AP, which is not the first one.
///
///    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
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///                   : DOND (cond)   |          NALU size            |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                                                               |
///   |                       NAL unit                                |
///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                               :
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265AggregationUnit {
    dond: Option<u8>,
    nal_unit_size: u16,
    nal_unit: Bytes,
}

impl H265AggregationUnit {
    /// dond field plus 1 specifies the difference between
    /// the decoding order number values of the current aggregated NAL unit
    /// and the preceding aggregated NAL unit in the same AP.
    pub fn dond(&self) -> Option<u8> {
        self.dond
    }

    /// nalu_size represents the size, in bytes, of the nal_unit.
    pub fn nalu_size(&self) -> u16 {
        self.nal_unit_size
    }

    /// nal_unit payload.
    pub fn nal_unit(&self) -> Bytes {
        self.nal_unit.clone()
    }
}

/// H265AggregationPacket represents an Aggregation packet.
///   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
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |    PayloadHdr (Type=48)       |                               |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
///   |                                                               |
///   |             two or more aggregation units                     |
///   |                                                               |
///   |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///   |                               :...OPTIONAL RTP padding        |
///   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265AggregationPacket {
    first_unit: Option<H265AggregationUnitFirst>,
    other_units: Vec<H265AggregationUnit>,

    might_need_donl: bool,
}

impl H265AggregationPacket {
    /// with_donl can be called to specify whether or not DONL might be parsed.
    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
    pub fn with_donl(&mut self, value: bool) {
        self.might_need_donl = value;
    }

    /// depacketize parses the passed byte slice and stores the result in the H265AggregationPacket this method is called upon.
    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
        if payload.len() <= H265NALU_HEADER_SIZE {
            return Err(Error::ErrShortPacket);
        }

        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
        if payload_header.f() {
            return Err(Error::ErrH265CorruptedPacket);
        }
        if !payload_header.is_aggregation_packet() {
            return Err(Error::ErrInvalidH265PacketType);
        }

        // First parse the first aggregation unit
        let mut payload = payload.slice(2..);
        let mut first_unit = H265AggregationUnitFirst::default();

        if self.might_need_donl {
            if payload.len() < 2 {
                return Err(Error::ErrShortPacket);
            }

            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
            first_unit.donl = Some(donl);

            payload = payload.slice(2..);
        }
        if payload.len() < 2 {
            return Err(Error::ErrShortPacket);
        }
        first_unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
        payload = payload.slice(2..);

        if payload.len() < first_unit.nal_unit_size as usize {
            return Err(Error::ErrShortPacket);
        }

        first_unit.nal_unit = payload.slice(..first_unit.nal_unit_size as usize);
        payload = payload.slice(first_unit.nal_unit_size as usize..);

        // Parse remaining Aggregation Units
        let mut units = vec![]; //H265AggregationUnit
        loop {
            let mut unit = H265AggregationUnit::default();

            if self.might_need_donl {
                if payload.is_empty() {
                    break;
                }

                let dond = payload[0];
                unit.dond = Some(dond);

                payload = payload.slice(1..);
            }

            if payload.len() < 2 {
                break;
            }
            unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16);
            payload = payload.slice(2..);

            if payload.len() < unit.nal_unit_size as usize {
                break;
            }

            unit.nal_unit = payload.slice(..unit.nal_unit_size as usize);
            payload = payload.slice(unit.nal_unit_size as usize..);

            units.push(unit);
        }

        // There need to be **at least** two Aggregation Units (first + another one)
        if units.is_empty() {
            return Err(Error::ErrShortPacket);
        }

        self.first_unit = Some(first_unit);
        self.other_units = units;

        Ok(())
    }

    /// first_unit returns the first Aggregated Unit of the packet.
    pub fn first_unit(&self) -> Option<&H265AggregationUnitFirst> {
        self.first_unit.as_ref()
    }

    /// other_units returns the all the other Aggregated Unit of the packet (excluding the first one).
    pub fn other_units(&self) -> &[H265AggregationUnit] {
        self.other_units.as_slice()
    }
}

///
/// Fragmentation Unit implementation
///

const H265FRAGMENTATION_UNIT_HEADER_SIZE: usize = 1;

/// H265FragmentationUnitHeader is a H265 FU Header
/// +---------------+
/// |0|1|2|3|4|5|6|7|
/// +-+-+-+-+-+-+-+-+
/// |S|E|  fu_type   |
/// +---------------+
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct H265FragmentationUnitHeader(pub u8);

impl H265FragmentationUnitHeader {
    /// s represents the start of a fragmented NAL unit.
    pub fn s(&self) -> bool {
        const MASK: u8 = 0b10000000;
        ((self.0 & MASK) >> 7) != 0
    }

    /// e represents the end of a fragmented NAL unit.
    pub fn e(&self) -> bool {
        const MASK: u8 = 0b01000000;
        ((self.0 & MASK) >> 6) != 0
    }

    /// fu_type MUST be equal to the field Type of the fragmented NAL unit.
    pub fn fu_type(&self) -> u8 {
        const MASK: u8 = 0b00111111;
        self.0 & MASK
    }
}

/// H265FragmentationUnitPacket represents a single Fragmentation Unit packet.
///
///  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
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |    PayloadHdr (Type=49)       |   FU header   | DONL (cond)   |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
/// | DONL (cond)   |                                               |
/// |-+-+-+-+-+-+-+-+                                               |
/// |                         FU payload                            |
/// |                                                               |
/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                               :...OPTIONAL RTP padding        |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265FragmentationUnitPacket {
    /// payload_header is the header of the H265 packet.
    payload_header: H265NALUHeader,
    /// fu_header is the header of the fragmentation unit
    fu_header: H265FragmentationUnitHeader,
    /// donl is a 16-bit field, that may or may not be present.
    donl: Option<u16>,
    /// payload of the fragmentation unit.
    payload: Bytes,

    might_need_donl: bool,
}

impl H265FragmentationUnitPacket {
    /// with_donl can be called to specify whether or not DONL might be parsed.
    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
    pub fn with_donl(&mut self, value: bool) {
        self.might_need_donl = value;
    }

    /// depacketize parses the passed byte slice and stores the result in the H265FragmentationUnitPacket this method is called upon.
    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE;
        if payload.len() <= TOTAL_HEADER_SIZE {
            return Err(Error::ErrShortPacket);
        }

        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
        if payload_header.f() {
            return Err(Error::ErrH265CorruptedPacket);
        }
        if !payload_header.is_fragmentation_unit() {
            return Err(Error::ErrInvalidH265PacketType);
        }

        let fu_header = H265FragmentationUnitHeader(payload[2]);
        let mut payload = payload.slice(3..);

        if fu_header.s() && self.might_need_donl {
            if payload.len() <= 2 {
                return Err(Error::ErrShortPacket);
            }

            let donl = ((payload[0] as u16) << 8) | (payload[1] as u16);
            self.donl = Some(donl);
            payload = payload.slice(2..);
        }

        self.payload_header = payload_header;
        self.fu_header = fu_header;
        self.payload = payload;

        Ok(())
    }

    /// payload_header returns the NALU header of the packet.
    pub fn payload_header(&self) -> H265NALUHeader {
        self.payload_header
    }

    /// fu_header returns the Fragmentation Unit Header of the packet.
    pub fn fu_header(&self) -> H265FragmentationUnitHeader {
        self.fu_header
    }

    /// donl returns the DONL of the packet.
    pub fn donl(&self) -> Option<u16> {
        self.donl
    }

    /// payload returns the Fragmentation Unit packet payload.
    pub fn payload(&self) -> Bytes {
        self.payload.clone()
    }
}

///
/// PACI implementation
///

/// H265PACIPacket represents a single H265 PACI packet.
///
///  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
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |    PayloadHdr (Type=50)       |A|   cType   | phssize |F0..2|Y|
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |        payload Header Extension Structure (phes)              |
/// |=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=|
/// |                                                               |
/// |                  PACI payload: NAL unit                       |
/// |                   . . .                                       |
/// |                                                               |
/// |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                               :...OPTIONAL RTP padding        |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265PACIPacket {
    /// payload_header is the header of the H265 packet.
    payload_header: H265NALUHeader,

    /// Field which holds value for `A`, `cType`, `phssize`, `F0`, `F1`, `F2` and `Y` fields.
    paci_header_fields: u16,

    /// phes is a header extension, of byte length `phssize`
    phes: Bytes,

    /// payload contains NAL units & optional padding
    payload: Bytes,
}

impl H265PACIPacket {
    /// payload_header returns the NAL Unit Header.
    pub fn payload_header(&self) -> H265NALUHeader {
        self.payload_header
    }

    /// a copies the F bit of the PACI payload NALU.
    pub fn a(&self) -> bool {
        const MASK: u16 = 0b10000000 << 8;
        (self.paci_header_fields & MASK) != 0
    }

    /// ctype copies the Type field of the PACI payload NALU.
    pub fn ctype(&self) -> u8 {
        const MASK: u16 = 0b01111110 << 8;
        ((self.paci_header_fields & MASK) >> (8 + 1)) as u8
    }

    /// phs_size indicates the size of the phes field.
    pub fn phs_size(&self) -> u8 {
        const MASK: u16 = (0b00000001 << 8) | 0b11110000;
        ((self.paci_header_fields & MASK) >> 4) as u8
    }

    /// f0 indicates the presence of a Temporal Scalability support extension in the phes.
    pub fn f0(&self) -> bool {
        const MASK: u16 = 0b00001000;
        (self.paci_header_fields & MASK) != 0
    }

    /// f1 must be zero, reserved for future extensions.
    pub fn f1(&self) -> bool {
        const MASK: u16 = 0b00000100;
        (self.paci_header_fields & MASK) != 0
    }

    /// f2 must be zero, reserved for future extensions.
    pub fn f2(&self) -> bool {
        const MASK: u16 = 0b00000010;
        (self.paci_header_fields & MASK) != 0
    }

    /// y must be zero, reserved for future extensions.
    pub fn y(&self) -> bool {
        const MASK: u16 = 0b00000001;
        (self.paci_header_fields & MASK) != 0
    }

    /// phes contains header extensions. Its size is indicated by phssize.
    pub fn phes(&self) -> Bytes {
        self.phes.clone()
    }

    /// payload is a single NALU or NALU-like struct, not including the first two octets (header).
    pub fn payload(&self) -> Bytes {
        self.payload.clone()
    }

    /// tsci returns the Temporal Scalability Control Information extension, if present.
    pub fn tsci(&self) -> Option<H265TSCI> {
        if !self.f0() || self.phs_size() < 3 {
            return None;
        }

        Some(H265TSCI(
            ((self.phes[0] as u32) << 16) | ((self.phes[1] as u32) << 8) | self.phes[0] as u32,
        ))
    }

    /// depacketize parses the passed byte slice and stores the result in the H265PACIPacket this method is called upon.
    fn depacketize(&mut self, payload: &Bytes) -> Result<()> {
        const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + 2;
        if payload.len() <= TOTAL_HEADER_SIZE {
            return Err(Error::ErrShortPacket);
        }

        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
        if payload_header.f() {
            return Err(Error::ErrH265CorruptedPacket);
        }
        if !payload_header.is_paci_packet() {
            return Err(Error::ErrInvalidH265PacketType);
        }

        let paci_header_fields = ((payload[2] as u16) << 8) | (payload[3] as u16);
        let mut payload = payload.slice(4..);

        self.paci_header_fields = paci_header_fields;
        let header_extension_size = self.phs_size();

        if payload.len() < header_extension_size as usize + 1 {
            self.paci_header_fields = 0;
            return Err(Error::ErrShortPacket);
        }

        self.payload_header = payload_header;

        if header_extension_size > 0 {
            self.phes = payload.slice(..header_extension_size as usize);
        }

        payload = payload.slice(header_extension_size as usize..);
        self.payload = payload;

        Ok(())
    }
}

///
/// Temporal Scalability Control Information
///

/// H265TSCI is a Temporal Scalability Control Information header extension.
/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.5
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct H265TSCI(pub u32);

impl H265TSCI {
    /// tl0picidx see RFC7798 for more details.
    pub fn tl0picidx(&self) -> u8 {
        const M1: u32 = 0xFFFF0000;
        const M2: u32 = 0xFF00;
        ((((self.0 & M1) >> 16) & M2) >> 8) as u8
    }

    /// irap_pic_id see RFC7798 for more details.
    pub fn irap_pic_id(&self) -> u8 {
        const M1: u32 = 0xFFFF0000;
        const M2: u32 = 0x00FF;
        (((self.0 & M1) >> 16) & M2) as u8
    }

    /// s see RFC7798 for more details.
    pub fn s(&self) -> bool {
        const M1: u32 = 0xFF00;
        const M2: u32 = 0b10000000;
        (((self.0 & M1) >> 8) & M2) != 0
    }

    /// e see RFC7798 for more details.
    pub fn e(&self) -> bool {
        const M1: u32 = 0xFF00;
        const M2: u32 = 0b01000000;
        (((self.0 & M1) >> 8) & M2) != 0
    }

    /// res see RFC7798 for more details.
    pub fn res(&self) -> u8 {
        const M1: u32 = 0xFF00;
        const M2: u32 = 0b00111111;
        (((self.0 & M1) >> 8) & M2) as u8
    }
}

///
/// H265 Payload Enum
///
#[derive(Debug, Clone, PartialEq)]
pub enum H265Payload {
    H265SingleNALUnitPacket(H265SingleNALUnitPacket),
    H265FragmentationUnitPacket(H265FragmentationUnitPacket),
    H265AggregationPacket(H265AggregationPacket),
    H265PACIPacket(H265PACIPacket),
}

impl Default for H265Payload {
    fn default() -> Self {
        H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default())
    }
}

///
/// Packet implementation
///

/// H265Packet represents a H265 packet, stored in the payload of an RTP packet.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct H265Packet {
    payload: H265Payload,
    might_need_donl: bool,
}

impl H265Packet {
    /// with_donl can be called to specify whether or not DONL might be parsed.
    /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream.
    pub fn with_donl(&mut self, value: bool) {
        self.might_need_donl = value;
    }

    /// payload returns the populated payload.
    /// Must be casted to one of:
    /// - H265SingleNALUnitPacket
    /// - H265FragmentationUnitPacket
    /// - H265AggregationPacket
    /// - H265PACIPacket
    pub fn payload(&self) -> &H265Payload {
        &self.payload
    }
}

impl Depacketizer for H265Packet {
    /// depacketize parses the passed byte slice and stores the result in the H265Packet this method is called upon
    fn depacketize(&mut self, payload: &Bytes) -> Result<Bytes> {
        if payload.len() <= H265NALU_HEADER_SIZE {
            return Err(Error::ErrShortPacket);
        }

        let payload_header = H265NALUHeader::new(payload[0], payload[1]);
        if payload_header.f() {
            return Err(Error::ErrH265CorruptedPacket);
        }

        if payload_header.is_paci_packet() {
            let mut decoded = H265PACIPacket::default();
            decoded.depacketize(payload)?;

            self.payload = H265Payload::H265PACIPacket(decoded);
        } else if payload_header.is_fragmentation_unit() {
            let mut decoded = H265FragmentationUnitPacket::default();
            decoded.with_donl(self.might_need_donl);

            decoded.depacketize(payload)?;

            self.payload = H265Payload::H265FragmentationUnitPacket(decoded);
        } else if payload_header.is_aggregation_packet() {
            let mut decoded = H265AggregationPacket::default();
            decoded.with_donl(self.might_need_donl);

            decoded.depacketize(payload)?;

            self.payload = H265Payload::H265AggregationPacket(decoded);
        } else {
            let mut decoded = H265SingleNALUnitPacket::default();
            decoded.with_donl(self.might_need_donl);

            decoded.depacketize(payload)?;

            self.payload = H265Payload::H265SingleNALUnitPacket(decoded);
        }

        Ok(payload.clone())
    }

    /// is_partition_head checks if this is the head of a packetized nalu stream.
    fn is_partition_head(&self, _payload: &Bytes) -> bool {
        //TODO:
        true
    }

    fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
        marker
    }
}