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
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! Parser data formatted according to
//! [SCTE-35](http://www.scte.org/SCTEDocs/Standards/SCTE%2035%202016.pdf).
//!
//! Intended to be used in conjunction with the
//! [mpeg2ts-reader](https://crates.io/crates/mpeg2ts-reader) crate's facilities for processing
//! the Transport Stream structures within which SCTE-35 data is usually embedded.
//!
//! ## Example
//!
//! ```
//! # use hex_literal::*;
//! # use scte35_reader::Scte35SectionProcessor;
//! # use mpeg2ts_reader::psi::WholeCompactSyntaxPayloadParser;
//! # use mpeg2ts_reader::{ psi, demultiplex };
//! # mpeg2ts_reader::demux_context!(
//! #        NullDemuxContext,
//! #        demultiplex::NullPacketFilter<NullDemuxContext>
//! #    );
//! # impl NullDemuxContext {
//! #    fn do_construct(
//! #        &mut self,
//! #        _req: demultiplex::FilterRequest<'_, '_>,
//! #    ) -> demultiplex::NullPacketFilter<NullDemuxContext> {
//! #        unimplemented!();
//! #    }
//! # }
//! pub struct DumpSpliceInfoProcessor;
//! impl scte35_reader::SpliceInfoProcessor for DumpSpliceInfoProcessor {
//!     fn process(
//!         &self,
//!         header: scte35_reader::SpliceInfoHeader<'_>,
//!         command: scte35_reader::SpliceCommand,
//!         descriptors: scte35_reader::SpliceDescriptors<'_>,
//!     ) {
//!         println!("{:?} {:#?}", header, command);
//!         for d in &descriptors {
//!             println!(" - {:?}", d);
//!         }
//!     }
//! }
//!
//! let data = hex!(
//!             "fc302500000000000000fff01405000000017feffe2d142b00fe0123d3080001010100007f157a49"
//!         );
//! let mut parser = Scte35SectionProcessor::new(DumpSpliceInfoProcessor);
//! let header = psi::SectionCommonHeader::new(&data[..psi::SectionCommonHeader::SIZE]);
//! let mut ctx = NullDemuxContext::new();
//! parser.section(&mut ctx, &header, &data[..]);
//! ```
//!
//! Output:
//!
//! ```plain
//! SpliceInfoHeader { protocol_version: 0, encrypted_packet: false, encryption_algorithm: None, pts_adjustment: 0, cw_index: 0, tier: 4095 } SpliceInsert {
//!     splice_event_id: 1,
//!     reserved: 127,
//!     splice_detail: Insert {
//!         network_indicator: Out,
//!         splice_mode: Program(
//!             Timed(
//!                 Some(
//!                     756296448
//!                 )
//!             )
//!         ),
//!         duration: Some(
//!             SpliceDuration {
//!                 return_mode: Automatic,
//!                 duration: 19125000
//!             }
//!         ),
//!         unique_program_id: 1,
//!         avail_num: 1,
//!         avails_expected: 1
//!     }
//! }
//! ```

#![forbid(unsafe_code)]
#![deny(rust_2018_idioms, future_incompatible)]

pub mod upid;

use bitreader::BitReaderError;
use mpeg2ts_reader::demultiplex;
use mpeg2ts_reader::psi;
use serde::ser::{SerializeSeq, SerializeStruct};
use serdebug::*;
use smptera_format_identifiers_rust::FormatIdentifier;
use std::convert::TryInto;
use std::marker;
use log::error;

/// The StreamType which might be used for `SCTE-35` data
pub const SCTE35_STREAM_TYPE: mpeg2ts_reader::StreamType = mpeg2ts_reader::StreamType::Private(0x86);

/// Utility function to search the PTM section for a `CUEI` registration descriptor per
/// _SCTE-35, section 8.1_, which indicates that streams with `stream_type` equal to the private
/// value `0x86` within this PMT section are formatted according to SCTE-35.
///
/// Returns `true` if the descriptor is attached to the given PMT section and `false` otherwise.
pub fn is_scte35(pmt: &mpeg2ts_reader::psi::pmt::PmtSection<'_>) -> bool {
    for d in pmt.descriptors() {
        if let Ok(mpeg2ts_reader::descriptor::CoreDescriptors::Registration(reg)) = d {
            if reg.is_format(FormatIdentifier::CUEI) {
                return true;
            }
        }
    }
    false
}
#[derive(Debug, PartialEq, serde_derive::Serialize)]
pub enum EncryptionAlgorithm {
    None,
    DesEcb,
    DesCbc,
    TripleDesEde3Ecb,
    Reserved(u8),
    Private(u8),
}
impl EncryptionAlgorithm {
    pub fn from_id(id: u8) -> EncryptionAlgorithm {
        match id {
            0 => EncryptionAlgorithm::None,
            1 => EncryptionAlgorithm::DesEcb,
            2 => EncryptionAlgorithm::DesCbc,
            3 => EncryptionAlgorithm::TripleDesEde3Ecb,
            _ => {
                if id < 32 {
                    EncryptionAlgorithm::Reserved(id)
                } else {
                    EncryptionAlgorithm::Private(id)
                }
            }
        }
    }
}

#[derive(Debug, PartialEq, serde_derive::Serialize)]
pub enum SpliceCommandType {
    SpliceNull,
    Reserved(u8),
    SpliceSchedule,
    SpliceInsert,
    TimeSignal,
    BandwidthReservation,
    PrivateCommand,
}
impl SpliceCommandType {
    pub fn from_id(id: u8) -> SpliceCommandType {
        match id {
            0x00 => SpliceCommandType::SpliceNull,
            0x04 => SpliceCommandType::SpliceSchedule,
            0x05 => SpliceCommandType::SpliceInsert,
            0x06 => SpliceCommandType::TimeSignal,
            0x07 => SpliceCommandType::BandwidthReservation,
            0xff => SpliceCommandType::PrivateCommand,
            _ => SpliceCommandType::Reserved(id),
        }
    }
}

/// Header element within a SCTE-43 _splice_info_section_ containing metadata generic across all kinds of _splice-command_.
///
/// This is a wrapper around a byte-slice that will extract requested fields on demand, as its
/// methods are called.
#[derive(SerDebug)]
pub struct SpliceInfoHeader<'a> {
    buf: &'a [u8],
}
impl<'a> SpliceInfoHeader<'a> {
    const HEADER_LENGTH: usize = 11;

    /// Splits the given buffer into a `SpliceInfoHeader` element, and a remainder which will
    /// include the _splice-command_ itself, plus any _descriptor_loop_.
    pub fn new(buf: &'a [u8]) -> (SpliceInfoHeader<'a>, &'a [u8]) {
        if buf.len() < 11 {
            panic!("buffer too short: {} (expected 11)", buf.len());
        }
        let (head, tail) = buf.split_at(11);
        (SpliceInfoHeader { buf: head }, tail)
        // TODO: change this to return Err if the protocol_version or encrypted_packet values are
        //       unsupported
    }

    /// The version of the SCTE-35 data structures carried in this _splice_info_section_ (only
    /// version `0` is supported by this library).
    pub fn protocol_version(&self) -> u8 {
        self.buf[0]
    }

    /// Indicates that portions of this _splice_info_section_ are encrypted (only un-encrypted
    /// data is supported by this library).
    pub fn encrypted_packet(&self) -> bool {
        self.buf[1] & 0b1000_0000 != 0
    }
    /// The algorithm by which portions of this _splice_info_section_ are encrypted (only
    /// un-encrypted data is supported by this library).
    pub fn encryption_algorithm(&self) -> EncryptionAlgorithm {
        EncryptionAlgorithm::from_id((self.buf[1] & 0b0111_1110) >> 1)
    }
    /// A 33-bit adjustment value to be applied to any PTS value in a _splice-command_ within this
    /// _splice_info_section_.
    pub fn pts_adjustment(&self) -> u64 {
        u64::from(self.buf[1] & 1) << 32
            | u64::from(self.buf[2]) << 24
            | u64::from(self.buf[3]) << 16
            | u64::from(self.buf[4]) << 8
            | u64::from(self.buf[5])
    }
    /// Identifier for the 'control word' (key) used to encrypt the message, if `encrypted_packet`
    /// is true.
    pub fn cw_index(&self) -> u8 {
        self.buf[6]
    }
    /// 12-bit authorization tier.
    pub fn tier(&self) -> u16 {
        u16::from(self.buf[7]) << 4 | u16::from(self.buf[8]) >> 4
    }
    /// Length in bytes of the _splice-command_ data within this message.
    pub fn splice_command_length(&self) -> u16 {
        u16::from(self.buf[8] & 0b0000_1111) << 8 | u16::from(self.buf[9])
    }
    /// Type of _splice-command_ within this message.
    pub fn splice_command_type(&self) -> SpliceCommandType {
        SpliceCommandType::from_id(self.buf[10])
    }
}
impl<'a> serde::Serialize for SpliceInfoHeader<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut s = serializer.serialize_struct("SpliceInfoHeader", 6)?;
        s.serialize_field("protocol_version", &self.protocol_version())?;
        s.serialize_field("encrypted_packet", &self.encrypted_packet())?;
        s.serialize_field("encryption_algorithm", &self.encryption_algorithm())?;
        s.serialize_field("pts_adjustment", &self.pts_adjustment())?;
        s.serialize_field("cw_index", &self.cw_index())?;
        s.serialize_field("tier", &self.tier())?;
        s.end()
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceCommand {
    SpliceNull {},
    SpliceInsert {
        splice_event_id: u32,
        reserved: u8,
        splice_detail: SpliceInsert,
    },
    TimeSignal {
        splice_time: SpliceTime,
    },
    BandwidthReservation {},
}

#[derive(Debug, serde_derive::Serialize)]
pub enum NetworkIndicator {
    Out,
    In,
}
impl NetworkIndicator {
    /// panics if `id` is something other than `0` or `1`
    pub fn from_flag(id: u8) -> NetworkIndicator {
        match id {
            0 => NetworkIndicator::In,
            1 => NetworkIndicator::Out,
            _ => panic!(
                "Invalid out_of_network_indicator value: {} (expected 0 or 1)",
                id
            ),
        }
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceInsert {
    Cancel,
    Insert {
        network_indicator: NetworkIndicator,
        splice_mode: SpliceMode,
        duration: Option<SpliceDuration>,
        unique_program_id: u16,
        avail_num: u8,
        avails_expected: u8,
    },
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceTime {
    Immediate,
    Timed(Option<u64>),
}

#[derive(Debug, serde_derive::Serialize)]
pub struct ComponentSplice {
    component_tag: u8,
    splice_time: SpliceTime,
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceMode {
    Program(SpliceTime),
    Components(Vec<ComponentSplice>),
}

#[derive(Debug, serde_derive::Serialize)]
pub enum ReturnMode {
    Automatic,
    Manual,
}
impl ReturnMode {
    pub fn from_flag(flag: u8) -> ReturnMode {
        match flag {
            0 => ReturnMode::Manual,
            1 => ReturnMode::Automatic,
            _ => panic!("Invalid auto_return value: {} (expected 0 or 1)", flag),
        }
    }
}

#[derive(Debug, PartialEq, serde_derive::Serialize, Copy, Clone)]
pub enum SegmentationUpidType {
    NotUsed,
    UserDefinedDeprecated,
    /// _Industry Standard Commercial Identifier_
    ISCIDeprecated,
    /// Defined by the _Advertising Digital Identification_ group
    AdID,
    UMID,
    ISANDeprecated,
    ISAN,
    TID,
    TI,
    ADI,
    EIDR,
    ATSC,
    MPU,
    MID,
    ADS,
    URI,
    Reserved(u8),
}
impl SegmentationUpidType {
    pub fn from_type(id: u8) -> SegmentationUpidType {
        match id {
            0 => SegmentationUpidType::NotUsed,
            1 => SegmentationUpidType::UserDefinedDeprecated,
            2 => SegmentationUpidType::ISCIDeprecated,
            3 => SegmentationUpidType::AdID,
            4 => SegmentationUpidType::UMID,
            5 => SegmentationUpidType::ISANDeprecated,
            6 => SegmentationUpidType::ISAN,
            7 => SegmentationUpidType::TID,
            8 => SegmentationUpidType::TI,
            9 => SegmentationUpidType::ADI,
            10 => SegmentationUpidType::EIDR,
            11 => SegmentationUpidType::ATSC,
            12 => SegmentationUpidType::MPU,
            13 => SegmentationUpidType::MID,
            14 => SegmentationUpidType::ADS,
            15 => SegmentationUpidType::URI,
            _ => SegmentationUpidType::Reserved(id),
        }
    }
}

#[derive(Debug, PartialEq, serde_derive::Serialize)]
pub enum SegmentationTypeId {
    NotIndicated,
    ContentIdentification,
    ProgramStart,
    ProgramEnd,
    ProgramEarlyTermination,
    ProgramBreakaway,
    ProgramResumption,
    ProgramRunoverPlanned,
    ProgramRunoverUnplanned,
    ProgramOverlapStart,
    ProgramBlackoutOverride,
    ProgramStartInProgress,
    ChapterStart,
    ChapterEnd,
    BreakStart,
    BreakEnd,
    ProviderAdvertisementStart,
    ProviderAdvertisementEnd,
    DistributorAdvertisementStart,
    DistributorAdvertisementEnd,
    ProviderPlacementOpportunityStart,
    ProviderPlacementOpportunityEnd,
    DistributorPlacementOpportunityStart,
    DistributorPlacementOpportunityEnd,
    UnscheduledEventStart,
    UnscheduledEventEnd,
    NetworkStart,
    NetworkEnd,
    Reserved(u8),
}
impl SegmentationTypeId {
    pub fn from_id(id: u8) -> SegmentationTypeId {
        match id {
            0 => SegmentationTypeId::NotIndicated,
            1 => SegmentationTypeId::ContentIdentification,
            16 => SegmentationTypeId::ProgramStart,
            17 => SegmentationTypeId::ProgramEnd,
            18 => SegmentationTypeId::ProgramEarlyTermination,
            19 => SegmentationTypeId::ProgramBreakaway,
            20 => SegmentationTypeId::ProgramResumption,
            21 => SegmentationTypeId::ProgramRunoverPlanned,
            22 => SegmentationTypeId::ProgramRunoverUnplanned,
            23 => SegmentationTypeId::ProgramOverlapStart,
            24 => SegmentationTypeId::ProgramBlackoutOverride,
            25 => SegmentationTypeId::ProgramStartInProgress,
            32 => SegmentationTypeId::ChapterStart,
            33 => SegmentationTypeId::ChapterEnd,
            34 => SegmentationTypeId::BreakStart,
            35 => SegmentationTypeId::BreakEnd,
            48 => SegmentationTypeId::ProviderAdvertisementStart,
            49 => SegmentationTypeId::ProviderAdvertisementEnd,
            50 => SegmentationTypeId::DistributorAdvertisementStart,
            51 => SegmentationTypeId::DistributorAdvertisementEnd,
            52 => SegmentationTypeId::ProviderPlacementOpportunityStart,
            53 => SegmentationTypeId::ProviderPlacementOpportunityEnd,
            54 => SegmentationTypeId::DistributorPlacementOpportunityStart,
            55 => SegmentationTypeId::DistributorPlacementOpportunityEnd,
            64 => SegmentationTypeId::UnscheduledEventStart,
            65 => SegmentationTypeId::UnscheduledEventEnd,
            80 => SegmentationTypeId::NetworkStart,
            81 => SegmentationTypeId::NetworkEnd,
            _ => SegmentationTypeId::Reserved(id),
        }
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SegmentationUpid {
    None,
    UserDefined(upid::UserDefinedDeprecated),
    Isci(upid::IsciDeprecated),
    AdID(upid::AdID),
    IsanDeprecated(upid::IsanDeprecated),
    Umid(upid::Umid),
    TID(upid::TID),
    TI(upid::TI),
    ADI(upid::ADI),
    EIDR(upid::EIDR),
    ATSC(upid::ATSC),
    MPU(upid::MPU),
    MID(Vec<SegmentationUpid>),
    ADS(upid::ADSInformation),
    URI(upid::Url),
    Reserved(SegmentationUpidType, Vec<u8>),
}
impl SegmentationUpid {
    fn parse(
        r: &mut bitreader::BitReader<'_>,
        segmentation_upid_type: SegmentationUpidType,
        segmentation_upid_length: u8,
    ) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        if segmentation_upid_length > 0 {
            let upid_result: Result<Vec<u8>, bitreader::BitReaderError> = (0
                ..segmentation_upid_length)
                .map(|_| r.read_u8(8))
                .collect();
            let upid = upid_result.named("segmentation_descriptor.segmentation_upid")?;
            SegmentationUpid::parse_payload(segmentation_upid_type, upid)
        } else {
            Ok(SegmentationUpid::None)
        }
    }

    // TODO: rework 'upid' param from Vec<u8> into &[u8]
    fn parse_payload(
        segmentation_upid_type: SegmentationUpidType,
        upid: Vec<u8>,
    ) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        match segmentation_upid_type {
            SegmentationUpidType::NotUsed => Err(
                SpliceDescriptorErr::SegmentationUpidLengthTypeMismatch(segmentation_upid_type),
            ),
            SegmentationUpidType::UserDefinedDeprecated => Self::parse_user_defined(upid),
            SegmentationUpidType::ISCIDeprecated => Self::parse_isci(upid),
            SegmentationUpidType::AdID => Self::parse_adid(upid),
            SegmentationUpidType::UMID => Self::parse_umid(upid),
            SegmentationUpidType::ISANDeprecated => Self::parse_isan_deprecated(upid),
            SegmentationUpidType::ISAN => Self::parse_isan(upid),
            SegmentationUpidType::TID => Self::parse_tid(upid),
            SegmentationUpidType::TI => Self::parse_ti(upid),
            SegmentationUpidType::ADI => Self::parse_adi(upid),
            SegmentationUpidType::EIDR => Self::parse_eidr(upid),
            SegmentationUpidType::ATSC => Self::parse_atsc(upid),
            SegmentationUpidType::MPU => Self::parse_mpu(upid),
            SegmentationUpidType::MID => Self::parse_mid(upid),
            SegmentationUpidType::ADS => Self::parse_ads(upid),
            SegmentationUpidType::URI => Self::parse_url(upid),
            SegmentationUpidType::Reserved(_) => Self::parse_reserved(segmentation_upid_type, upid),
        }
    }

    pub fn segmentation_upid_length(&self) -> usize {
        match self {
            SegmentationUpid::None => 0,
            SegmentationUpid::UserDefined(v) => v.0.len(),
            SegmentationUpid::Isci(_) => 8,
            SegmentationUpid::AdID(_) => 12,
            SegmentationUpid::IsanDeprecated(_) => 8,
            SegmentationUpid::Umid(_) => 32,
            SegmentationUpid::TID(_) => 12,
            SegmentationUpid::TI(_) => 8,
            SegmentationUpid::ADI(adi) => adi.0.len(),
            SegmentationUpid::EIDR(_) => 12,
            SegmentationUpid::ATSC(atsc) => atsc.0.len(),
            SegmentationUpid::MPU(m) => m.0.len(),
            SegmentationUpid::MID(v) => {
                v.len() * 2
                    + v.iter()
                        .map(|upid| upid.segmentation_upid_length())
                        .sum::<usize>()
            }
            SegmentationUpid::ADS(a) => a.0.len(),
            SegmentationUpid::URI(u) => u.0.as_str().len(),
            SegmentationUpid::Reserved(_, r) => r.len(),
        }
    }

    pub fn segmentation_upid_type(&self) -> SegmentationUpidType {
        match self {
            SegmentationUpid::None => SegmentationUpidType::NotUsed,
            SegmentationUpid::UserDefined(_) => SegmentationUpidType::UserDefinedDeprecated,
            SegmentationUpid::Isci(_) => SegmentationUpidType::ISCIDeprecated,
            SegmentationUpid::AdID(_) => SegmentationUpidType::AdID,
            SegmentationUpid::IsanDeprecated(_) => SegmentationUpidType::ISAN,
            SegmentationUpid::Umid(_) => SegmentationUpidType::UMID,
            SegmentationUpid::TID(_) => SegmentationUpidType::TID,
            SegmentationUpid::TI(_) => SegmentationUpidType::TI,
            SegmentationUpid::ADI(_) => SegmentationUpidType::ADI,
            SegmentationUpid::EIDR(_) => SegmentationUpidType::EIDR,
            SegmentationUpid::ATSC(_) => SegmentationUpidType::ATSC,
            SegmentationUpid::MPU(_) => SegmentationUpidType::MPU,
            SegmentationUpid::MID(_) => SegmentationUpidType::MID,
            SegmentationUpid::ADS(_) => SegmentationUpidType::ADS,
            SegmentationUpid::URI(_) => SegmentationUpidType::URI,
            SegmentationUpid::Reserved(t, _) => *t,
        }
    }

    fn parse_user_defined(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        Ok(SegmentationUpid::UserDefined(upid::UserDefinedDeprecated(
            upid,
        )))
    }
    fn parse_isci(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 8, SegmentationUpidType::ISCIDeprecated)?;
        upid_from_utf8(upid, SegmentationUpidType::ISCIDeprecated)
            .map(|s| SegmentationUpid::Isci(upid::IsciDeprecated(s)))
    }
    fn parse_adid(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 12, SegmentationUpidType::AdID)?;
        upid_from_utf8(upid, SegmentationUpidType::AdID)
            .map(|s| SegmentationUpid::AdID(upid::AdID(s)))
    }
    fn parse_umid(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 32, SegmentationUpidType::UMID)?;
        Ok(SegmentationUpid::Umid(upid::Umid(upid)))
    }
    fn parse_isan_deprecated(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 8, SegmentationUpidType::ISANDeprecated)?;
        Ok(SegmentationUpid::IsanDeprecated(upid::IsanDeprecated(upid)))
    }
    fn parse_isan(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 12, SegmentationUpidType::ISAN)?;
        Ok(SegmentationUpid::IsanDeprecated(upid::IsanDeprecated(upid)))
    }
    fn parse_tid(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 12, SegmentationUpidType::TID)?;
        upid_from_utf8(upid, SegmentationUpidType::TID).map(|s| SegmentationUpid::TID(upid::TID(s)))
    }
    fn parse_ti(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 8, SegmentationUpidType::TI)?;
        Ok(SegmentationUpid::TI(upid::TI(upid)))
    }
    fn parse_adi(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        upid_from_utf8(upid, SegmentationUpidType::ADI).map(|s| SegmentationUpid::ADI(upid::ADI(s)))
    }
    fn parse_eidr(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        chk_upid(&upid, 12, SegmentationUpidType::EIDR)?;
        Ok(SegmentationUpid::EIDR(upid::EIDR(
            upid.as_slice().try_into().unwrap(),
        )))
    }
    fn parse_atsc(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        Ok(SegmentationUpid::ATSC(upid::ATSC(upid)))
    }
    fn parse_mpu(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        Ok(SegmentationUpid::MPU(upid::MPU(upid)))
    }
    fn parse_mid(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        let mut data = &upid[..];
        let mut result = vec![];
        while !data.is_empty() {
            if data.len() < 2 {
                return Err(SpliceDescriptorErr::not_enough_data("MID.length", 1, 0));
            }
            let segmentation_upid_type = SegmentationUpidType::from_type(data[0]);
            let length = data[1] as usize;
            let payload_end = 2 + length;
            if data.len() < payload_end {
                return Err(SpliceDescriptorErr::not_enough_data(
                    "MID.segmentation_upid",
                    length,
                    data.len() - 2,
                ));
            }
            let payload = &data[2..payload_end];
            result.push(Self::parse_payload(
                segmentation_upid_type,
                payload.to_vec(),
            )?);
            data = &data[payload_end..];
        }
        Ok(SegmentationUpid::MID(result))
    }
    fn parse_ads(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        Ok(SegmentationUpid::ADS(upid::ADSInformation(upid)))
    }
    fn parse_url(upid: Vec<u8>) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        upid_from_utf8(upid, SegmentationUpidType::URI)
            .and_then(|s| {
                url::Url::parse(&s).map_err(|_| SpliceDescriptorErr::InvalidUpidContent {
                    upid_type: SegmentationUpidType::URI,
                    bytes: s.into_bytes(),
                })
            })
            .map(|u| SegmentationUpid::URI(upid::Url(u)))
    }
    fn parse_reserved(
        segmentation_upid_type: SegmentationUpidType,
        upid: Vec<u8>,
    ) -> Result<SegmentationUpid, SpliceDescriptorErr> {
        Ok(SegmentationUpid::Reserved(segmentation_upid_type, upid))
    }
}

/// helper wrapping String::from_utf8() and producing a useful error type
fn upid_from_utf8(
    upid: Vec<u8>,
    upid_type: SegmentationUpidType,
) -> Result<String, SpliceDescriptorErr> {
    String::from_utf8(upid).map_err(|e| SpliceDescriptorErr::InvalidUpidContent {
        upid_type,
        bytes: e.into_bytes(),
    })
}

fn chk_upid(
    upid: &[u8],
    expected: usize,
    upid_type: SegmentationUpidType,
) -> Result<(), SpliceDescriptorErr> {
    if upid.len() == expected {
        Ok(())
    } else {
        Err(SpliceDescriptorErr::InvalidUpidLength {
            upid_type,
            expected,
            actual: upid.len(),
        })
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum DeviceRestrictions {
    RestrictGroup0,
    RestrictGroup1,
    RestrictGroup2,
    None,
}
impl DeviceRestrictions {
    /// panics if `id` is something other than `0`, `1`, `2` or `3`
    pub fn from_bits(restriction: u8) -> DeviceRestrictions {
        match restriction {
            0 => DeviceRestrictions::RestrictGroup0,
            1 => DeviceRestrictions::RestrictGroup1,
            2 => DeviceRestrictions::RestrictGroup2,
            3 => DeviceRestrictions::None,
            _ => panic!(
                "Invalid device_restrictions value: {} (expected 0, 1, 2, 3)",
                restriction
            ),
        }
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum DeliveryRestrictionFlags {
    None,
    DeliveryRestrictions {
        web_delivery_allowed_flag: bool,
        no_regional_blackout_flag: bool,
        archive_allowed_flag: bool,
        device_restrictions: DeviceRestrictions,
    },
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SegmentationMode {
    Program,
    Component {
        components: Vec<SegmentationModeComponent>,
    },
}

#[derive(Debug, serde_derive::Serialize)]
pub struct SegmentationModeComponent {
    component_tag: u8,
    pts_offset: u64,
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SegmentationDescriptor {
    Cancel,
    Insert {
        program_segmentation_flag: bool,
        segmentation_duration_flag: bool,
        delivery_not_restricted_flag: bool,
        delivery_restrictions: DeliveryRestrictionFlags,
        segmentation_mode: SegmentationMode,
        segmentation_duration: Option<u64>,
        segmentation_upid: SegmentationUpid,
        segmentation_type_id: SegmentationTypeId,
        segment_num: u8,
        segments_expected: u8,
        sub_segments: Option<SubSegments>,
    },
}

#[derive(Debug, serde_derive::Serialize)]
pub struct SubSegments {
    sub_segment_num: u8,
    sub_segments_expected: u8,
}

#[derive(Debug, serde_derive::Serialize)]
pub struct SpliceDuration {
    return_mode: ReturnMode,
    duration: u64,
}

pub trait SpliceInfoProcessor {
    fn process(
        &self,
        header: SpliceInfoHeader<'_>,
        command: SpliceCommand,
        descriptors: SpliceDescriptors<'_>,
    );
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceDescriptor {
    AvailDescriptor {
        provider_avail_id: u32,
    },
    DTMFDescriptor {
        preroll: u8,
        dtmf_chars: Vec<u8>,
    },
    SegmentationDescriptor {
        segmentation_event_id: u32,
        descriptor_detail: SegmentationDescriptor,
    },
    TimeDescriptor {
        tai_seconds: u64,
        tai_nanoseconds: u32,
        utc_offset: u16,
    },
    Reserved {
        tag: u8,
        identifier: [u8; 4],
        private_bytes: Vec<u8>,
    },
}
impl SpliceDescriptor {
    fn parse_segmentation_descriptor_details(
        r: &mut bitreader::BitReader<'_>,
        cancelled: bool,
    ) -> Result<SegmentationDescriptor, SpliceDescriptorErr> {
        if cancelled {
            Ok(SegmentationDescriptor::Cancel)
        } else {
            let program_segmentation_flag = r
                .read_bool()
                .named("segmentation_descriptor.program_segmentation_flag")?;
            let segmentation_duration_flag = r
                .read_bool()
                .named("segmentation_descriptor.segmentation_duration_flag")?;
            let delivery_not_restricted_flag = r
                .read_bool()
                .named("segmentation_descriptor.delivery_not_restricted_flag")?;
            let delivery_restrictions;
            if !delivery_not_restricted_flag {
                delivery_restrictions = DeliveryRestrictionFlags::DeliveryRestrictions {
                    web_delivery_allowed_flag: r
                        .read_bool()
                        .named("segmentation_descriptor.web_delivery_allowed_flag")?,
                    no_regional_blackout_flag: r
                        .read_bool()
                        .named("segmentation_descriptor.no_regional_blackout_flag")?,
                    archive_allowed_flag: r
                        .read_bool()
                        .named("segmentation_descriptor.archive_allowed_flag")?,
                    device_restrictions: DeviceRestrictions::from_bits(
                        r.read_u8(2)
                            .named("segmentation_descriptor.device_restrictions")?,
                    ),
                }
            } else {
                delivery_restrictions = DeliveryRestrictionFlags::None;
                r.skip(5).named("segmentation_descriptor.reserved")?;
            }
            let segmentation_mode = if !program_segmentation_flag {
                let component_count = r
                    .read_u8(8)
                    .named("segmentation_descriptor.component_count")?;
                let mut components = Vec::with_capacity(component_count as usize);

                for _ in 0..component_count {
                    let component_tag = r
                        .read_u8(8)
                        .named("segmentation_descriptor.component.component_tag")?;
                    r.skip(7)
                        .named("segmentation_descriptor.component.reserved")?;
                    let pts_offset = r
                        .read_u64(33)
                        .named("segmentation_descriptor.component.pts_offset")?;
                    components.push(SegmentationModeComponent {
                        component_tag,
                        pts_offset,
                    })
                }

                SegmentationMode::Component { components }
            } else {
                SegmentationMode::Program
            };

            let segmentation_duration = if segmentation_duration_flag {
                Some(
                    r.read_u64(40)
                        .named("segmentation_descriptor.segmentation_duration")?,
                )
            } else {
                None
            };

            let segmentation_upid_type = SegmentationUpidType::from_type(
                r.read_u8(8)
                    .named("segmentation_descriptor.segmentation_upid_type")?,
            );
            let segmentation_upid_length = r
                .read_u8(8)
                .named("segmentation_descriptor.segmentation_upid_length")?;
            let segmentation_upid =
                SegmentationUpid::parse(r, segmentation_upid_type, segmentation_upid_length)?;

            let segmentation_type_id =
                SegmentationTypeId::from_id(r.read_u8(8).named("segmentation_type_id")?);
            let segment_num = r.read_u8(8).named("segment_num")?;
            let segments_expected = r.read_u8(8).named("segments_expected")?;

            // The spec notes: "sub_segment_num and sub_segments_expected can form an optional
            // appendix to the segmentation descriptor. The presence or absence of this optional
            // data block is determined by the descriptor loop's descriptor_length."
            let sub_segments = if r.relative_reader().skip(1).is_ok() {
                Some(SubSegments {
                    sub_segment_num: r.read_u8(8).named("sub_segment_num")?,
                    sub_segments_expected: r.read_u8(8).named("sub_segments_expected")?,
                })
            } else {
                None
            };

            Ok(SegmentationDescriptor::Insert {
                program_segmentation_flag,
                segmentation_duration_flag,
                delivery_not_restricted_flag,
                delivery_restrictions,
                segmentation_mode,
                segmentation_duration,
                segmentation_upid,
                segmentation_type_id,
                segment_num,
                segments_expected,
                sub_segments,
            })
        }
    }

    fn parse_segmentation_descriptor(buf: &[u8]) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        let mut r = bitreader::BitReader::new(buf);
        let id = r.read_u32(32).named("segmentation_descriptor.id")?;
        let cancel = r.read_bool().named("segmentation_descriptor.cancel")?;
        r.skip(7).named("segmentation_descriptor.reserved")?;

        let result = SpliceDescriptor::SegmentationDescriptor {
            segmentation_event_id: id,
            descriptor_detail: Self::parse_segmentation_descriptor_details(&mut r, cancel)?,
        };

        // if we end up without reading to the end of a byte, this must indicate a bug in the
        // parsing routine,
        assert!(r.is_aligned(1));

        if buf.len() > (r.position() / 8) as usize {
            error!(
                "only {} bytes consumed data in segmentation_descriptor of {} bytes",
                r.position() / 8,
                buf.len()
            );
        }
        Ok(result)
    }

    fn parse_dtmf_descriptor(buf: &[u8]) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        let mut r = bitreader::BitReader::new(buf);
        let preroll = r.read_u8(8).named("dtmf_descriptor.preroll")?;
        let dtmf_count = r.read_u8(3).named("dtmf_descriptor.dtmf_count")?;
        r.skip(5).named("dtmf_descriptor.reserved")?;
        let dtmf_chars_result: Result<Vec<u8>, BitReaderError> =
            (0..dtmf_count).map(|_| r.read_u8(8)).collect();
        let dtmf_chars = dtmf_chars_result.named("dtmf_descriptor")?;

        // if we end up without reading to the end of a byte, this must indicate a bug in the
        // parsing routine,
        assert!(r.is_aligned(1));

        if buf.len() > (r.position() / 8) as usize {
            error!(
                "only {} bytes consumed data in segmentation_descriptor of {} bytes",
                r.position() / 8,
                buf.len()
            );
        }

        Ok(SpliceDescriptor::DTMFDescriptor {
            preroll,
            dtmf_chars,
        })
    }
    fn parse(buf: &[u8]) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        if buf.len() < 6 {
            return Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "splice_descriptor",
                actual: buf.len(),
                expected: 6,
            });
        }
        let splice_descriptor_tag = buf[0];
        let splice_descriptor_len = buf[1] as usize;
        if splice_descriptor_len < 4 {
            // descriptor must at least be big enough to hold the 4-byte id value
            return Err(SpliceDescriptorErr::InvalidDescriptorLength(
                splice_descriptor_len,
            ));
        }
        let splice_descriptor_end = splice_descriptor_len + 2;
        if splice_descriptor_end > buf.len() {
            return Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "splice_descriptor.private_byte",
                actual: buf.len(),
                expected: splice_descriptor_end,
            });
        }
        let id = &buf[2..6];
        let payload = &buf[6..splice_descriptor_end];
        if id == b"CUEI" {
            match splice_descriptor_tag {
                0x00 => Self::parse_avail_descriptor(payload),
                0x01 => Self::parse_dtmf_descriptor(payload),
                0x02 => Self::parse_segmentation_descriptor(payload),
                0x03 => Self::parse_time_descriptor(payload),
                _ => Self::parse_reserved(payload, splice_descriptor_tag, id),
            }
        } else {
            Self::parse_reserved(payload, splice_descriptor_tag, id)
        }
    }

    fn parse_reserved(
        buf: &[u8],
        splice_descriptor_tag: u8,
        id: &[u8],
    ) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        Ok(SpliceDescriptor::Reserved {
            tag: splice_descriptor_tag,
            identifier: [id[0], id[1], id[2], id[3]],
            private_bytes: buf.to_owned(),
        })
    }

    fn parse_avail_descriptor(buf: &[u8]) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        if buf.len() < 4 {
            return Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "avail_descriptor",
                expected: 4,
                actual: buf.len(),
            });
        }
        Ok(SpliceDescriptor::AvailDescriptor {
            provider_avail_id: u32::from(buf[0]) << 24
                | u32::from(buf[1]) << 16
                | u32::from(buf[2]) << 8
                | u32::from(buf[3]),
        })
    }

    fn parse_time_descriptor(buf: &[u8]) -> Result<SpliceDescriptor, SpliceDescriptorErr> {
        if buf.len() < 12 {
            return Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "time_descriptor",
                expected: 12,
                actual: buf.len(),
            });
        }
        Ok(SpliceDescriptor::TimeDescriptor {
            tai_seconds: u64::from(buf[0]) << 40
                | u64::from(buf[1]) << 32
                | u64::from(buf[2]) << 24
                | u64::from(buf[3]) << 16
                | u64::from(buf[4]) << 8
                | u64::from(buf[5]),
            tai_nanoseconds: u32::from(buf[6]) << 24
                | u32::from(buf[7]) << 16
                | u32::from(buf[8]) << 8
                | u32::from(buf[9]),
            utc_offset: u16::from(buf[10]) << 8 | u16::from(buf[11]),
        })
    }
}

#[derive(Debug, serde_derive::Serialize)]
pub enum SpliceDescriptorErr {
    InvalidDescriptorLength(usize),
    NotEnoughData {
        field_name: &'static str,
        expected: usize,
        actual: usize,
    },
    /// The segmentation_upid_length field value was `0`, but the segmentation_upid_type value was
    /// non-`0` (as indicated by the given `SegmentationUpidType` enum variant)
    SegmentationUpidLengthTypeMismatch(SegmentationUpidType),
    /// The UPID field contained byte values that are invalid for the given UPID type
    InvalidUpidContent {
        upid_type: SegmentationUpidType,
        bytes: Vec<u8>,
    },
    /// The UPID field had a length invalid for its type
    InvalidUpidLength {
        upid_type: SegmentationUpidType,
        expected: usize,
        actual: usize,
    },
}
impl SpliceDescriptorErr {
    fn not_enough_data(
        field_name: &'static str,
        expected: usize,
        actual: usize,
    ) -> SpliceDescriptorErr {
        SpliceDescriptorErr::NotEnoughData {
            field_name,
            expected,
            actual,
        }
    }
}

trait ErrorFieldNamed<T> {
    fn named(self, field_name: &'static str) -> Result<T, SpliceDescriptorErr>;
}
impl<T> ErrorFieldNamed<T> for Result<T, bitreader::BitReaderError> {
    fn named(self, field_name: &'static str) -> Result<T, SpliceDescriptorErr> {
        match self {
            Err(bitreader::BitReaderError::NotEnoughData {
                position,
                length,
                requested,
            }) => {
                // TODO: round numbers up to nearest byte,
                Err(SpliceDescriptorErr::NotEnoughData {
                    field_name,
                    expected: (requested / 8) as usize,
                    actual: ((length - position) / 8) as usize,
                })
            }
            Err(e) => {
                panic!("scte35-reader bug: {:?}", e)
            }
            Ok(v) => Ok(v),
        }
    }
}

pub struct SpliceDescriptors<'buf> {
    buf: &'buf [u8],
}
impl<'buf> IntoIterator for &SpliceDescriptors<'buf> {
    type Item = Result<SpliceDescriptor, SpliceDescriptorErr>;
    type IntoIter = SpliceDescriptorIter<'buf>;

    fn into_iter(self) -> <Self as IntoIterator>::IntoIter {
        SpliceDescriptorIter::new(self.buf)
    }
}
impl<'a> serde::Serialize for SpliceDescriptors<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut s = serializer.serialize_seq(None)?;
        for e in self {
            if let Ok(elem) = e {
                s.serialize_element(&elem)?;
            }
        }
        s.end()
    }
}

pub struct SpliceDescriptorIter<'buf> {
    buf: &'buf [u8],
}
impl<'buf> SpliceDescriptorIter<'buf> {
    fn new(buf: &'buf [u8]) -> SpliceDescriptorIter<'_> {
        SpliceDescriptorIter { buf }
    }
}
impl<'buf> Iterator for SpliceDescriptorIter<'buf> {
    type Item = Result<SpliceDescriptor, SpliceDescriptorErr>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.buf.is_empty() {
            return None;
        }
        if self.buf.len() < 6 {
            self.buf = &self.buf[0..0];
            return Some(Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "splice_descriptor",
                expected: 2,
                actual: self.buf.len(),
            }));
        }
        let descriptor_length = self.buf[1] as usize;
        if self.buf.len() < descriptor_length + 2 {
            self.buf = &self.buf[0..0];
            return Some(Err(SpliceDescriptorErr::NotEnoughData {
                field_name: "splice_descriptor",
                expected: descriptor_length + 2,
                actual: self.buf.len(),
            }));
        }
        if descriptor_length > 254 {
            self.buf = &self.buf[0..0];
            return Some(Err(SpliceDescriptorErr::InvalidDescriptorLength(
                descriptor_length,
            )));
        }
        let (desc, rest) = self.buf.split_at(2 + descriptor_length);
        let result = SpliceDescriptor::parse(desc);
        self.buf = rest;
        Some(result)
    }
}

pub struct Scte35SectionProcessor<P, Ctx: demultiplex::DemuxContext>
where
    P: SpliceInfoProcessor,
{
    processor: P,
    phantom: marker::PhantomData<Ctx>,
}
impl<P, Ctx: demultiplex::DemuxContext> psi::WholeCompactSyntaxPayloadParser
    for Scte35SectionProcessor<P, Ctx>
where
    P: SpliceInfoProcessor,
{
    type Context = Ctx;

    fn section<'a>(
        &mut self,
        _ctx: &mut Self::Context,
        header: &psi::SectionCommonHeader,
        data: &'a [u8],
    ) {
        if header.table_id == 0xfc {
            // no CRC while fuzz-testing, to make it more likely to find parser bugs,
            if !cfg!(fuzzing) {
                let crc = mpeg2ts_reader::mpegts_crc::sum32(data);
                if crc != 0 {
                    error!("section CRC check failed {:#08x}", crc);
                    return;
                }
            }
            let section_data = &data[psi::SectionCommonHeader::SIZE..];
            if section_data.len() < SpliceInfoHeader::HEADER_LENGTH + 4 {
                error!(
                    "section data too short: {} (must be at least {})",
                    section_data.len(),
                    SpliceInfoHeader::HEADER_LENGTH + 4
                );
                return;
            }
            // trim off the 32-bit CRC
            let section_data = &section_data[..section_data.len() - 4];
            let (splice_header, rest) = SpliceInfoHeader::new(section_data);
            if splice_header.encrypted_packet() {
                error!("encrypted SCTE-35 data not supoprted");
                return;
            }
            let command_len = splice_header.splice_command_length() as usize;
            if command_len > rest.len() {
                error!("splice_command_length of {} bytes is too long to fit in remaining {} bytes of section data", command_len, rest.len());
                return;
            }
            let (payload, rest) = rest.split_at(command_len);
            if rest.len() < 2 {
                error!("end of section data while trying to read descriptor_loop_length");
                return;
            }
            let descriptor_loop_length = (u16::from(rest[0]) << 8 | u16::from(rest[1])) as usize;
            if descriptor_loop_length + 2 > rest.len() {
                error!("descriptor_loop_length of {} bytes is too long to fit in remaining {} bytes of section data", descriptor_loop_length, rest.len());
                return;
            }
            let descriptors = &rest[2..2 + descriptor_loop_length];
            let splice_command = match splice_header.splice_command_type() {
                SpliceCommandType::SpliceNull => Some(Self::splice_null(payload)),
                SpliceCommandType::SpliceInsert => Some(Self::splice_insert(payload)),
                SpliceCommandType::TimeSignal => Some(Self::time_signal(payload)),
                SpliceCommandType::BandwidthReservation => {
                    Some(Self::bandwidth_reservation(payload))
                }
                _ => None,
            };
            match splice_command {
                Some(Ok(splice_command)) => {
                    self.processor.process(
                        splice_header,
                        splice_command,
                        SpliceDescriptors { buf: descriptors },
                    );
                }
                Some(Err(e)) => {
                    error!("parse error: {:?}", e);
                }
                None => {
                    error!(
                        "unhandled command {:?}",
                        splice_header.splice_command_type()
                    );
                }
            }
        } else {
            error!(
                "bad table_id for scte35: {:#x} (expected 0xfc)",
                header.table_id
            );
        }
    }
}
impl<P, Ctx: demultiplex::DemuxContext> Scte35SectionProcessor<P, Ctx>
where
    P: SpliceInfoProcessor,
{
    pub fn new(processor: P) -> Scte35SectionProcessor<P, Ctx> {
        Scte35SectionProcessor {
            processor,
            phantom: marker::PhantomData,
        }
    }
    fn splice_null(payload: &[u8]) -> Result<SpliceCommand, SpliceDescriptorErr> {
        if payload.is_empty() {
            Ok(SpliceCommand::SpliceNull {})
        } else {
            Err(SpliceDescriptorErr::InvalidDescriptorLength(payload.len()))
        }
    }

    fn splice_insert(payload: &[u8]) -> Result<SpliceCommand, SpliceDescriptorErr> {
        let mut r = bitreader::BitReader::new(payload);

        let splice_event_id = r.read_u32(32).named("splice_insert.splice_event_id")?;
        let splice_event_cancel_indicator = r
            .read_bool()
            .named("splice_insert.splice_event_cancel_indicator")?;
        let reserved = r.read_u8(7).named("splice_insert.reserved")?;
        let result = SpliceCommand::SpliceInsert {
            splice_event_id,
            reserved,
            splice_detail: Self::read_splice_detail(&mut r, splice_event_cancel_indicator)?,
        };

        // if we end up without reading to the end of a byte, this must indicate a bug in the
        // parsing routine,
        assert!(r.is_aligned(1));

        if payload.len() > (r.position() / 8) as usize {
            error!(
                "only {} bytes consumed data in splice_insert of {} bytes",
                r.position() / 8,
                payload.len()
            );
        }
        Ok(result)
    }

    fn time_signal(payload: &[u8]) -> Result<SpliceCommand, SpliceDescriptorErr> {
        let mut r = bitreader::BitReader::new(payload);

        let result = SpliceCommand::TimeSignal {
            splice_time: SpliceTime::Timed(Self::read_splice_time(&mut r)?),
        };

        // if we end up without reading to the end of a byte, this must indicate a bug in the
        // parsing routine,
        assert!(r.is_aligned(1));

        if payload.len() > (r.position() / 8) as usize {
            error!(
                "only {} bytes consumed data in time_signal of {} bytes",
                r.position() / 8,
                payload.len()
            );
        }
        Ok(result)
    }

    fn bandwidth_reservation(payload: &[u8]) -> Result<SpliceCommand, SpliceDescriptorErr> {
        if payload.is_empty() {
            Ok(SpliceCommand::BandwidthReservation {})
        } else {
            Err(SpliceDescriptorErr::InvalidDescriptorLength(payload.len()))
        }
    }

    fn read_splice_detail(
        r: &mut bitreader::BitReader<'_>,
        splice_event_cancel_indicator: bool,
    ) -> Result<SpliceInsert, SpliceDescriptorErr> {
        if splice_event_cancel_indicator {
            Ok(SpliceInsert::Cancel)
        } else {
            r.relative_reader().skip(1).named("splice_insert.flags")?;
            let network_indicator =
                NetworkIndicator::from_flag(r.read_u8(1).named("splice_insert.network_indicator")?);
            let program_splice_flag = r.read_bool().named("splice_insert.program_splice_flag")?;
            let duration_flag = r.read_bool().named("splice_insert.duration_flag")?;
            let splice_immediate_flag =
                r.read_bool().named("splice_insert.splice_immediate_flag")?;
            r.skip(4).named("splice_insert.reserved")?;

            Ok(SpliceInsert::Insert {
                network_indicator,
                splice_mode: Self::read_splice_mode(r, program_splice_flag, splice_immediate_flag)?,
                duration: if duration_flag {
                    Some(Self::read_duration(r)?)
                } else {
                    None
                },
                unique_program_id: r.read_u16(16).named("unique_program_id")?,
                avail_num: r.read_u8(8).named("avail_num")?,
                avails_expected: r.read_u8(8).named("avails_expected")?,
            })
        }
    }

    fn read_splice_mode(
        r: &mut bitreader::BitReader<'_>,
        program_splice_flag: bool,
        splice_immediate_flag: bool,
    ) -> Result<SpliceMode, SpliceDescriptorErr> {
        if program_splice_flag {
            let time = if splice_immediate_flag {
                SpliceTime::Immediate
            } else {
                SpliceTime::Timed(Self::read_splice_time(r)?)
            };
            Ok(SpliceMode::Program(time))
        } else {
            let component_count = r.read_u8(8).named("component_count")? as usize;
            let mut components = Vec::with_capacity(component_count);
            for _ in 0..component_count {
                let component_tag = r.read_u8(8).named("component_tag")?;
                let splice_time = if splice_immediate_flag {
                    SpliceTime::Immediate
                } else {
                    SpliceTime::Timed(Self::read_splice_time(r)?)
                };
                components.push(ComponentSplice {
                    component_tag,
                    splice_time,
                });
            }
            Ok(SpliceMode::Components(components))
        }
    }

    fn read_splice_time(
        r: &mut bitreader::BitReader<'_>,
    ) -> Result<Option<u64>, SpliceDescriptorErr> {
        Ok(if r.read_bool().named("splice_time.time_specified_flag")? {
            r.skip(6).named("splice_time.reserved")?; // reserved
            Some(r.read_u64(33).named("splice_time.pts_time")?)
        } else {
            r.skip(7).named("splice_time.reserved")?; // reserved
            None
        })
    }

    fn read_duration(
        r: &mut bitreader::BitReader<'_>,
    ) -> Result<SpliceDuration, SpliceDescriptorErr> {
        let return_mode = ReturnMode::from_flag(r.read_u8(1).named("break_duration.auto_return")?);
        r.skip(6).named("break_duration.reserved")?;
        Ok(SpliceDuration {
            return_mode,
            duration: r.read_u64(33).named("break_duration.duration")?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hex_literal::*;
    use matches::*;
    use mpeg2ts_reader::demultiplex;
    use mpeg2ts_reader::psi;
    use mpeg2ts_reader::psi::WholeCompactSyntaxPayloadParser;

    mpeg2ts_reader::demux_context!(
        NullDemuxContext,
        demultiplex::NullPacketFilter<NullDemuxContext>
    );
    impl NullDemuxContext {
        fn do_construct(
            &mut self,
            _req: demultiplex::FilterRequest<'_, '_>,
        ) -> demultiplex::NullPacketFilter<NullDemuxContext> {
            unimplemented!();
        }
    }

    struct MockSpliceInsertProcessor;
    impl SpliceInfoProcessor for MockSpliceInsertProcessor {
        fn process(
            &self,
            header: SpliceInfoHeader<'_>,
            command: SpliceCommand,
            descriptors: SpliceDescriptors<'_>,
        ) {
            assert_eq!(header.encryption_algorithm(), EncryptionAlgorithm::None);
            assert_matches!(command, SpliceCommand::SpliceInsert { .. });
            for d in &descriptors {
                d.unwrap();
            }
        }
    }

    #[test]
    fn it_works() {
        let data = hex!(
            "fc302500000000000000fff01405000000017feffe2d142b00fe0123d3080001010100007f157a49"
        );
        let mut parser = Scte35SectionProcessor::new(MockSpliceInsertProcessor);
        let header = psi::SectionCommonHeader::new(&data[..psi::SectionCommonHeader::SIZE]);
        let mut ctx = NullDemuxContext::new();
        parser.section(&mut ctx, &header, &data[..]);
    }

    struct MockTimeSignalProcessor;
    impl SpliceInfoProcessor for MockTimeSignalProcessor {
        fn process(
            &self,
            header: SpliceInfoHeader<'_>,
            command: SpliceCommand,
            descriptors: SpliceDescriptors<'_>,
        ) {
            assert_eq!(header.encryption_algorithm(), EncryptionAlgorithm::None);
            assert_matches!(command, SpliceCommand::TimeSignal { .. });
            for d in &descriptors {
                d.unwrap();
            }
        }
    }

    #[test]
    fn it_understands_time_signal() {
        let data = hex!(
            "fc302700000000000000fff00506ff592d03c00011020f43554549000000017fbf000010010112ce0e6b"
        );
        let mut parser = Scte35SectionProcessor::new(MockTimeSignalProcessor);
        let header = psi::SectionCommonHeader::new(&data[..psi::SectionCommonHeader::SIZE]);
        let mut ctx = NullDemuxContext::new();
        parser.section(&mut ctx, &header, &data[..]);
    }

    #[test]
    fn splice_descriptor() {
        let data = [];
        assert_matches!(
            SpliceDescriptor::parse(&data[..]),
            Err(SpliceDescriptorErr::NotEnoughData { .. })
        );
        let data = hex!("01084D5949440000"); // descriptor payload too short
        assert_matches!(
            SpliceDescriptor::parse(&data[..]),
            Err(SpliceDescriptorErr::NotEnoughData { .. })
        );
        let data = hex!("01034D59494400000003");
        assert_matches!(
            SpliceDescriptor::parse(&data[..]),
            Err(SpliceDescriptorErr::InvalidDescriptorLength { .. })
        );
        let data = hex!("01084D59494400000003");
        assert_matches!(
            SpliceDescriptor::parse(&data[..]),
            Ok(SpliceDescriptor::Reserved {
                tag: 01,
                identifier: [0x4D, 0x59, 0x49, 0x44],
                private_bytes: _,
            })
        );

        let data = hex!("020f43554549000000017fbf0000100101");
        assert_matches!(
            SpliceDescriptor::parse(&data[..]),
            Ok(SpliceDescriptor::SegmentationDescriptor {
                segmentation_event_id: 1,
                descriptor_detail: SegmentationDescriptor::Insert {
                    program_segmentation_flag: true,
                    segmentation_duration_flag: false,
                    delivery_not_restricted_flag: true,
                    delivery_restrictions: DeliveryRestrictionFlags::None,
                    segmentation_mode: SegmentationMode::Program,
                    segmentation_duration: None,
                    segmentation_upid: SegmentationUpid::None,
                    segmentation_type_id: SegmentationTypeId::ProgramStart,
                    segment_num: 1,
                    segments_expected: 1,
                    sub_segments: None,
                }
            })
        );
    }

    #[test]
    fn segmentation_descriptor() {
        let data = hex!("480000ad7f9f0808000000002cb2d79d350200");
        let desc = SpliceDescriptor::parse_segmentation_descriptor(&data[..]).unwrap();
        match desc {
            SpliceDescriptor::SegmentationDescriptor {
                descriptor_detail:
                    SegmentationDescriptor::Insert {
                        segmentation_upid: SegmentationUpid::TI(ti),
                        ..
                    },
                ..
            } => {
                // TODO: assert_eq!(upid.len(), 8);
                assert_eq!(ti, upid::TI(hex!("000000002cb2d79d").to_vec()));
            }
            _ => panic!("unexpected {:?}", desc),
        };
    }

    #[test]
    fn no_sub_segment_num() {
        // This segmentation_descriptor() does not include sub_segment_num or
        // sub_segments_expected fields.  Their absence should not cause parsing problems.
        let data = hex!("480000bf7fcf0000f8fa630d110e054c413330390808000000002e538481340000");
        SpliceDescriptor::parse_segmentation_descriptor(&data[..]).unwrap();
    }

    #[test]
    fn too_large_segment_descriptor() {
        // there are more bytes than expected; this should not panic
        let data = hex!("480000ad7f9f0808000000002cb2d79d350200000000");
        SpliceDescriptor::parse_segmentation_descriptor(&data[..]).unwrap();
    }
}