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
// Copyright 2018 sacn Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Parsing of sacn network packets.
//!
//! The packets live within the scope of the ACN protocol suite.
//!
//! # Examples
//!
//! ```
//! # extern crate uuid;
//! # extern crate sacn;
//! # use uuid::Uuid;
//! # use sacn::packet::{AcnRootLayerProtocol, E131RootLayer, E131RootLayerData, DataPacketFramingLayer, DataPacketDmpLayer, DataPacketDmpLayerPropertyValues};
//! # fn main() {
//! let packet = AcnRootLayerProtocol {
//!     pdu: E131RootLayer {
//!         cid: Uuid::new_v4(),
//!         data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
//!             source_name: "Source_A",
//!             priority: 100,
//!             synchronization_address: 7962,
//!             sequence_number: 154,
//!             preview_data: false,
//!             stream_terminated: false,
//!             force_synchronization: false,
//!             universe: 1,
//!             data: DataPacketDmpLayer {
//!                 property_values: DataPacketDmpLayerPropertyValues {
//!                     start_code: 0,
//!                     dmx_data: &[1, 2, 3],
//!                 },
//!             },
//!         }),
//!     },
//! };
//!
//! let mut buf = [0; 638];
//! packet.pack(&mut buf).unwrap();
//!
//! assert_eq!(
//!     AcnRootLayerProtocol::parse(&buf).unwrap(),
//!     packet
//! );
//! # }
//! ```

use core::iter::Iterator;
use core::str;
#[cfg(feature = "std")]
use std::vec::Vec;

use byteorder::{ByteOrder, NetworkEndian};
use uuid::Uuid;

use error::{PackError, ParseError};

/// Root layer protocol of the Architecture for Control Networks (ACN) protocol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcnRootLayerProtocol<'a> {
    /// The PDU this packet carries.
    pub pdu: E131RootLayer<'a>,
}

impl<'a> AcnRootLayerProtocol<'a> {
    /// Parse the packet from the given buffer.
    pub fn parse(buf: &'a [u8]) -> Result<AcnRootLayerProtocol<'a>, ParseError> {
        // Preamble Size
        if NetworkEndian::read_u16(&buf[0..2]) != 0x0010 {
            return Err(ParseError::InvalidData("invalid Preamble Size"));
        }

        // Post-amble Size
        if NetworkEndian::read_u16(&buf[2..4]) != 0 {
            return Err(ParseError::InvalidData("invalid Post-amble Size"));
        }

        // ACN Packet Identifier
        if &buf[4..16] != b"ASC-E1.17\x00\x00\x00" {
            return Err(ParseError::InvalidData("invalid ACN packet indentifier"));
        }

        // PDU block
        Ok(AcnRootLayerProtocol {
            pdu: E131RootLayer::parse(&buf[16..])?,
        })
    }

    /// Packs the packet into heap allocated memory.
    #[cfg(feature = "std")]
    pub fn pack_alloc(&self) -> Result<Vec<u8>, PackError> {
        let mut buf = Vec::with_capacity(self.len());
        self.pack_vec(&mut buf)?;
        Ok(buf)
    }

    /// Packs the packet into the given vector.
    ///
    /// Grows the vector `buf` if necessary.
    #[cfg(feature = "std")]
    pub fn pack_vec(&self, buf: &mut Vec<u8>) -> Result<(), PackError> {
        buf.clear();
        buf.reserve_exact(self.len());
        unsafe {
            buf.set_len(self.len());
        }
        self.pack(buf)
    }

    /// Packs the packet into the givven buffer.
    pub fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Preamble Size
        NetworkEndian::write_u16(&mut buf[0..2], 0x0010);

        // Post-amble Size
        zeros(&mut buf[2..4], 2);

        // ACN Packet Identifier
        buf[4..16].copy_from_slice(b"ASC-E1.17\x00\x00\x00");

        // PDU block
        Ok(self.pdu.pack(&mut buf[16..])?)
    }

    /// The length of the packet when packed.
    pub fn len(&self) -> usize {
        // Preamble Size
        2 +

        // Post-amble Size
        2 +

        // ACN Packet Identifier
        12 +

        // PDU block
        self.pdu.len()
    }
}

struct PduInfo {
    length: usize,
    vector: u32,
}

fn pdu_info(buf: &[u8], vector_length: usize) -> Result<PduInfo, ParseError> {
    if buf.len() < 2 {
        return Err(ParseError::NotEnoughData);
    }

    // Flags
    let flags = buf[0] & 0xf0;
    if flags != 0x70 {
        return Err(ParseError::PduInvalidFlags(flags));
    }
    // Length
    let length = (NetworkEndian::read_u16(&buf[0..2]) & 0x0fff) as usize;
    if buf.len() < length {
        return Err(ParseError::NotEnoughData);
    }

    // Vector
    let vector = NetworkEndian::read_uint(&buf[2..], vector_length) as u32;

    Ok(PduInfo {
        length: length,
        vector: vector,
    })
}

#[inline]
fn parse_source_name(buf: &[u8]) -> Result<&str, ParseError> {
    let mut source_name_len = buf.len();
    for i in 0..buf.len() {
        if buf[i] == 0 {
            source_name_len = i;
            break;
        }
    }
    Ok(str::from_utf8(&buf[..source_name_len])?)
}

#[inline]
fn zeros(buf: &mut [u8], n: usize) {
    for i in 0..n {
        buf[i] = 0;
    }
}

trait Pdu<'a>: Sized {
    fn parse(buf: &'a [u8]) -> Result<Self, ParseError>;

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError>;

    fn len(&self) -> usize;
}

const VECTOR_ROOT_E131_DATA: u32 = 0x00000004;
const VECTOR_ROOT_E131_EXTENDED: u32 = 0x00000008;

/// Root layer protocol data unit (PDU).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct E131RootLayer<'a> {
    /// Sender UUID.
    pub cid: Uuid,

    /// Data carried by the Root Layer PDU.
    pub data: E131RootLayerData<'a>,
}

/// Payload of the Root Layer PDU.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum E131RootLayerData<'a> {
    /// DMX data packet.
    DataPacket(DataPacketFramingLayer<'a>),

    /// Synchronization packet.
    SynchronizationPacket(SynchronizationPacketFramingLayer),

    /// Universe discovery packet.
    UniverseDiscoveryPacket(UniverseDiscoveryPacketFramingLayer<'a>),
}

impl<'a> Pdu<'a> for E131RootLayer<'a> {
    fn parse(buf: &'a [u8]) -> Result<E131RootLayer<'a>, ParseError> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(&buf, 4)?;
        if vector != VECTOR_ROOT_E131_DATA && vector != VECTOR_ROOT_E131_EXTENDED {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // CID
        let cid = Uuid::from_bytes(&buf[6..22])?;

        // Data
        let data = match vector {
            VECTOR_ROOT_E131_DATA => {
                E131RootLayerData::DataPacket(DataPacketFramingLayer::parse(&buf[22..length])?)
            }
            VECTOR_ROOT_E131_EXTENDED => {
                let data_buf = &buf[22..length];
                let PduInfo {
                    length: _,
                    vector: data_vector,
                } = pdu_info(&data_buf, 4)?;

                match data_vector {
                    VECTOR_E131_EXTENDED_SYNCHRONIZATION => {
                        E131RootLayerData::SynchronizationPacket(
                            SynchronizationPacketFramingLayer::parse(data_buf)?,
                        )
                    }
                    VECTOR_E131_EXTENDED_DISCOVERY => E131RootLayerData::UniverseDiscoveryPacket(
                        UniverseDiscoveryPacketFramingLayer::parse(data_buf)?,
                    ),

                    vector => return Err(ParseError::PduInvalidVector(vector)),
                }
            }
            vector => return Err(ParseError::PduInvalidVector(vector)),
        };

        Ok(E131RootLayer {
            cid: cid,
            data: data,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        match self.data {
            E131RootLayerData::DataPacket(_) => {
                NetworkEndian::write_u32(&mut buf[2..6], VECTOR_ROOT_E131_DATA)
            }
            E131RootLayerData::SynchronizationPacket(_)
            | E131RootLayerData::UniverseDiscoveryPacket(_) => {
                NetworkEndian::write_u32(&mut buf[2..6], VECTOR_ROOT_E131_EXTENDED)
            }
        }

        // CID
        buf[6..22].copy_from_slice(self.cid.as_bytes());

        // Data
        match self.data {
            E131RootLayerData::DataPacket(ref data) => Ok(data.pack(&mut buf[22..])?),
            E131RootLayerData::SynchronizationPacket(ref data) => Ok(data.pack(&mut buf[22..])?),
            E131RootLayerData::UniverseDiscoveryPacket(ref data) => Ok(data.pack(&mut buf[22..])?),
        }
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        4 +

        // CID
        16 +

        // Data
        match self.data {
            E131RootLayerData::DataPacket(ref data) => data.len(),
            E131RootLayerData::SynchronizationPacket(ref data) => data.len(),
            E131RootLayerData::UniverseDiscoveryPacket(ref data) => data.len(),
        }
    }
}

const VECTOR_E131_DATA_PACKET: u32 = 0x00000002;

/// Framing layer PDU for sACN data packets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataPacketFramingLayer<'a> {
    /// The name of the source.
    pub source_name: &'a str,

    /// Priority of this data packet.
    pub priority: u8,

    /// Synchronization adress.
    pub synchronization_address: u16,

    /// The sequence number of this packet.
    pub sequence_number: u8,

    /// If this packets data is preview data.
    pub preview_data: bool,

    /// If transmission on this universe is terminated.
    pub stream_terminated: bool,

    /// Force synchronization if no synchronization packets are received.
    pub force_synchronization: bool,

    /// The universe DMX data is transmitted for.
    pub universe: u16,

    /// DMP layer containing the DMX data.
    pub data: DataPacketDmpLayer<'a>,
}

impl<'a> Pdu<'a> for DataPacketFramingLayer<'a> {
    fn parse(buf: &'a [u8]) -> Result<DataPacketFramingLayer, ParseError> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(&buf, 4)?;
        if vector != VECTOR_E131_DATA_PACKET {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // Source Name
        let source_name = parse_source_name(&buf[6..70])?;

        // Priority
        let priority = buf[70];

        // Synchronization Address
        let synchronization_address = NetworkEndian::read_u16(&buf[71..73]);

        // Sequence Number
        let sequence_number = buf[73];

        // Options
        let preview_data = buf[74] & 0b01000000 != 0;
        let stream_terminated = buf[74] & 0b00100000 != 0;
        let force_synchronization = buf[74] & 0b00010000 != 0;

        // Universe
        let universe = NetworkEndian::read_u16(&buf[75..77]);

        // Data
        let data = DataPacketDmpLayer::parse(&buf[77..length])?;

        Ok(DataPacketFramingLayer {
            source_name: source_name,
            priority: priority,
            synchronization_address: synchronization_address,
            sequence_number: sequence_number,
            preview_data: preview_data,
            stream_terminated: stream_terminated,
            force_synchronization: force_synchronization,
            universe: universe,
            data: data,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        NetworkEndian::write_u32(&mut buf[2..6], VECTOR_E131_DATA_PACKET);

        // Source Name
        zeros(&mut buf[6..70], 64);
        buf[6..6 + self.source_name.len()].copy_from_slice(self.source_name.as_bytes());

        // Priority
        buf[70] = self.priority;

        // Synchronization Address
        NetworkEndian::write_u16(&mut buf[71..73], self.synchronization_address);

        // Sequence Number
        buf[73] = self.sequence_number;

        // Options
        buf[74] = 0;

        // Preview Data
        if self.preview_data {
            buf[74] = 0b01000000
        }

        // Stream Terminated
        if self.stream_terminated {
            buf[74] |= 0b00100000
        }

        // Force Synchronization
        if self.force_synchronization {
            buf[74] |= 0b00010000
        }

        // Universe
        NetworkEndian::write_u16(&mut buf[75..77], self.universe);

        // Data
        Ok(self.data.pack(&mut buf[77..])?)
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        4 +

        // Source Name
        64 +

        // Priority
        1 +

        // Synchronization Address
        2 +

        // Sequence Number
        1 +

        // Options
        1 +

        // Universe
        2 +

        // Data
        self.data.len()
    }
}

const VECTOR_DMP_SET_PROPERTY: u8 = 0x02;

/// Device Management Protocol PDU with SET PROPERTY vector.
///
/// Used for sACN data packets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataPacketDmpLayer<'a> {
    /// DMX data property values.
    pub property_values: DataPacketDmpLayerPropertyValues<'a>,
}

/// Property values carrying the actual DMX data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataPacketDmpLayerPropertyValues<'a> {
    /// DMX start code.
    pub start_code: u8,

    /// The DMX data.
    pub dmx_data: &'a [u8],
}

impl<'a> Pdu<'a> for DataPacketDmpLayer<'a> {
    fn parse(buf: &'a [u8]) -> Result<DataPacketDmpLayer, ParseError> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(&buf, 1)?;
        if vector != VECTOR_DMP_SET_PROPERTY as u32 {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // Address and Data Type
        if buf[3] != 0xa1 {
            return Err(ParseError::InvalidData("invalid Address and Data Type"));
        }

        // First Property Address
        if NetworkEndian::read_u16(&buf[4..6]) != 0 {
            return Err(ParseError::InvalidData("invalid First Property Address"));
        }

        // Address Increment
        if NetworkEndian::read_u16(&buf[6..8]) != 0x0001 {
            return Err(ParseError::InvalidData("invalid Address Increment"));
        }

        // Property value count
        if NetworkEndian::read_u16(&buf[8..10]) as usize + 10 != length {
            return Err(ParseError::InvalidData("invalid Property value count"));
        }

        // Property values
        let property_values_start_code = buf[10];
        let property_values_dmx_data = &buf[11..length];
        if property_values_dmx_data.len() > 512 {
            return Err(ParseError::InvalidData("only 512 universes allowed"));
        }

        let property_values = DataPacketDmpLayerPropertyValues {
            start_code: property_values_start_code,
            dmx_data: property_values_dmx_data,
        };

        Ok(DataPacketDmpLayer {
            property_values: property_values,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if self.property_values.dmx_data.len() > 512 {
            return Err(PackError::InvalidData("only 512 DMX values allowed"));
        }

        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        buf[2] = VECTOR_DMP_SET_PROPERTY;

        // Address and Data Type
        buf[3] = 0xa1;

        // First Property Address
        zeros(&mut buf[4..6], 2);

        // Address Increment
        NetworkEndian::write_u16(&mut buf[6..8], 0x0001);

        // Property value count
        NetworkEndian::write_u16(
            &mut buf[8..10],
            self.property_values.dmx_data.len() as u16 + 1,
        );

        // Property values
        buf[10] = self.property_values.start_code;
        buf[11..11 + self.property_values.dmx_data.len()]
            .copy_from_slice(&self.property_values.dmx_data);

        Ok(())
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        1 +

        // Address and Data Type
        1 +

        // First Property Address
        2 +

        // Address Increment
        2 +

        // Property value count
        2 +

        // Property values
        1 + self.property_values.dmx_data.len()
    }
}

const VECTOR_E131_EXTENDED_SYNCHRONIZATION: u32 = 0x00000001;

/// sACN synchronization packet PDU.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SynchronizationPacketFramingLayer {
    /// The sequence number of the packet.
    pub sequence_number: u8,

    /// The address to synchronize.
    pub synchronization_address: u16,
}

impl<'a> Pdu<'a> for SynchronizationPacketFramingLayer {
    fn parse(buf: &'a [u8]) -> Result<SynchronizationPacketFramingLayer, ParseError> {
        // Length and Vector
        let PduInfo { length: _, vector } = pdu_info(&buf, 4)?;
        if vector != VECTOR_E131_EXTENDED_SYNCHRONIZATION {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // Sequence Number
        let sequence_number = buf[6];

        // Synchronization Address
        let synchronization_address = NetworkEndian::read_u16(&buf[7..9]);

        // Reserved
        if buf[9..11] != [0, 0] {
            return Err(ParseError::InvalidData("invalid Reserved"));
        }

        Ok(SynchronizationPacketFramingLayer {
            sequence_number: sequence_number,
            synchronization_address: synchronization_address,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        NetworkEndian::write_u32(&mut buf[2..6], VECTOR_E131_EXTENDED_SYNCHRONIZATION);

        // Sequence Number
        buf[6] = self.sequence_number;

        // Synchronization Address
        NetworkEndian::write_u16(&mut buf[7..9], self.synchronization_address);

        // Reserved
        zeros(&mut buf[9..11], 2);

        Ok(())
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        4 +

        // Sequence Number
        1 +

        // Synchronization Address
        2 +

        // Reserved
        2
    }
}

const VECTOR_E131_EXTENDED_DISCOVERY: u32 = 0x00000002;

/// Framing layer PDU for sACN universe discovery packets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UniverseDiscoveryPacketFramingLayer<'a> {
    /// Name of the source.
    pub source_name: &'a str,

    /// Universe dicovery layer.
    pub data: UniverseDiscoveryPacketUniverseDiscoveryLayer<'a>,
}

impl<'a> Pdu<'a> for UniverseDiscoveryPacketFramingLayer<'a> {
    fn parse(buf: &'a [u8]) -> Result<UniverseDiscoveryPacketFramingLayer<'a>, ParseError> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(&buf, 4)?;
        if vector != VECTOR_E131_EXTENDED_DISCOVERY {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // Source Name
        let source_name = parse_source_name(&buf[6..70])?;

        // Reserved
        if buf[70..74] != [0, 0, 0, 0] {
            return Err(ParseError::InvalidData("invalid Reserved"));
        }

        // Data
        let data = UniverseDiscoveryPacketUniverseDiscoveryLayer::parse(&buf[74..length])?;

        Ok(UniverseDiscoveryPacketFramingLayer {
            source_name: source_name,
            data: data,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        NetworkEndian::write_u32(&mut buf[2..6], VECTOR_E131_EXTENDED_DISCOVERY);

        // Source Name
        zeros(&mut buf[6..70], 64);
        buf[6..6 + self.source_name.len()].copy_from_slice(self.source_name.as_bytes());

        // Reserved
        zeros(&mut buf[70..74], 4);

        // Data
        Ok(self.data.pack(&mut buf[74..])?)
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        4 +

        // Source Name
        64 +

        // Reserved
        4 +

        // Data
        self.data.len()
    }
}

const VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST: u32 = 0x00000001;

/// List of universes.
///
/// Use `From` trait to create from a list of `u16` integers.
/// The universes must not contain duplicates and must be sorted from
/// low to high.
#[derive(Debug, Clone)]
pub struct Universes<'a> {
    data: UniversesData<'a>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum UniversesData<'a> {
    Packed(&'a [u8]),
    Unpacked(&'a [u16]),
}

impl<'a, B: ?Sized + AsRef<[u16]>> From<&'a B> for Universes<'a> {
    fn from(buf: &'a B) -> Self {
        Universes {
            data: UniversesData::Unpacked(buf.as_ref()),
        }
    }
}

impl<'a> Universes<'a> {
    /// Create an Iterator over the contained universes.
    pub fn iter(&self) -> UniversesIter {
        UniversesIter {
            data: self.data.clone(),
            index: 0,
        }
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if !self.unique() {
            return Err(PackError::InvalidData("Universes are not unique"));
        }

        if !self.sorted() {
            return Err(PackError::InvalidData("Universes are not sorted"));
        }

        match self.data {
            UniversesData::Packed(data) => buf[..self.len() * 2].copy_from_slice(data),
            UniversesData::Unpacked(_) => for (index, universe) in self.iter().enumerate() {
                NetworkEndian::write_u16(&mut buf[index * 2..], universe);
            },
        }

        Ok(())
    }

    fn unique(&self) -> bool {
        let mut last_universe = 0;
        for universe in self.iter() {
            if universe == last_universe {
                return false;
            } else {
                last_universe = universe;
            }
        }
        true
    }

    fn sorted(&self) -> bool {
        let mut current_universe = 0;
        for universe in self.iter() {
            if universe < current_universe {
                return false;
            } else {
                current_universe = universe;
            }
        }
        true
    }

    /// The length of the universe list.
    pub fn len(&self) -> usize {
        match self.data {
            UniversesData::Packed(data) => data.len() / 2,
            UniversesData::Unpacked(data) => data.len(),
        }
    }
}

impl<'a> PartialEq for Universes<'a> {
    fn eq(&self, other: &Universes) -> bool {
        self.iter().eq(other.iter())
    }
}

impl<'a> Eq for Universes<'a> {}

/// Iterator yielding each universe.
///
/// If received form the network, `u16`s are read from an internal `u8` buffer.
pub struct UniversesIter<'a> {
    data: UniversesData<'a>,
    index: usize,
}

impl<'a> Iterator for UniversesIter<'a> {
    type Item = u16;

    fn next(&mut self) -> Option<Self::Item> {
        match self.data {
            UniversesData::Packed(data) => {
                if self.index < data.len() / 2 {
                    let universe = NetworkEndian::read_u16(&data[self.index * 2..]);
                    self.index += 1;
                    Some(universe)
                } else {
                    None
                }
            }
            UniversesData::Unpacked(data) => {
                if self.index < data.len() {
                    let universe = data[self.index];
                    self.index += 1;
                    Some(universe)
                } else {
                    None
                }
            }
        }
    }
}

/// Universe discovery layer PDU.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
    /// Current page of the dicovery packet.
    pub page: u8,

    /// The number of the final page.
    pub last_page: u8,

    /// List of universes.
    pub universes: Universes<'a>,
}

impl<'a> Pdu<'a> for UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
    fn parse(
        buf: &'a [u8],
    ) -> Result<UniverseDiscoveryPacketUniverseDiscoveryLayer<'a>, ParseError> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(&buf, 4)?;
        if vector != VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST {
            return Err(ParseError::PduInvalidVector(vector));
        }

        // Page
        let page = buf[6];

        // Last Page
        let last_page = buf[7];

        // Universes
        let universe_buf = &buf[8..length];
        if universe_buf.len() > 512 * 2 {
            return Err(ParseError::InvalidData("only 512 universes allowed"));
        }
        let universes = Universes {
            data: UniversesData::Packed(universe_buf),
        };

        Ok(UniverseDiscoveryPacketUniverseDiscoveryLayer {
            page: page,
            last_page: last_page,
            universes: universes,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<(), PackError> {
        if self.universes.len() > 512 {
            return Err(PackError::InvalidData("only 512 universes allowed"));
        }

        if buf.len() < self.len() {
            return Err(PackError::BufferNotLargeEnough);
        }

        // Flags and Length
        let flags_and_length = 0x7000 | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..2], flags_and_length);

        // Vector
        NetworkEndian::write_u32(&mut buf[2..6], VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST);

        // Page
        buf[6] = self.page;

        // Last Page
        buf[7] = self.last_page;

        // Universes
        self.universes
            .pack(&mut buf[8..8 + self.universes.len() * 2])?;

        Ok(())
    }

    fn len(&self) -> usize {
        // Length and Flags
        2 +

        // Vector
        4 +

        // Page
        1 +

        // Last Page
        1 +

        // Universes
        self.universes.len() * 2
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[cfg_attr(rustfmt, rustfmt_skip)]
    const TEST_DATA_PACKET: &[u8] = &[
        // Root Layer
        // Preamble Size
        0x00, 0x10,
        // Post-amble Size
        0x00, 0x00,
        // ACN Packet Identifier
        0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00,
        0x00, 0x00,
        // Flags and Length Protocol
        0x72, 0x6e, // 0x7d in E1-31-2016 sample packet (which is wrong)
        // Vector
        0x00, 0x00, 0x00, 0x04,
        // CID
        0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2,
        0x45, 0x9e, 0xf8, 0xe6, 0x14, 0x3e,
        // Data Packet Framing Layer
        // Flags and Length
        0x72, 0x58, // 0x57 in E1-31-2016 sample packet (which is wrong)
        // Vector
        0x00, 0x00, 0x00, 0x02,
        // Source Name
        b'S', b'o', b'u', b'r', b'c', b'e', b'_',  b'A', 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0,
        // Priority
        100,
        // Synchronization Address
        0x1F, 0x1A, // 7962
        // Sequence Number
        154,
        // Options
        0,
        // Universe
        0, 1,
        // DMP Layer
        // Flags and Length
        0x72, 0x0b, // 0x0d in E1-31-2016 sample packet (which is wrong)
        // Vector
        0x02,
        // Address and Data Type
        0xa1,
        // First Property Address
        0x00, 0x00,
        // Address Increment
        0x00, 0x01,
        // Property value count
        0x02, 0x01,
        // Property values
        0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    ];

    #[cfg_attr(rustfmt, rustfmt_skip)]
    const TEST_UNIVERSE_DISCOVERY_PACKET: &[u8] = &[
        // Root Layer
        // Preamble Size
        0x00, 0x10,
        // Post-amble Size
        0x00, 0x00,
        // ACN Packet Identifier
        0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00,
        0x00, 0x00,
        // Flags and Length Protocol
        0x70, 0x6e,
        // Vector
        0x00, 0x00, 0x00, 0x08,
        // CID
        0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2,
        0x45, 0x9e, 0xf8, 0xe6, 0x14, 0x3e,
        // E1.31 Framing Layer
        // Flags and Length
        0x70, 0x58,
        // Vector
        0x00, 0x00, 0x00, 0x02,
        // Source Name
        b'S', b'o', b'u', b'r', b'c', b'e', b'_',  b'A', 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0,
        // Reserved
        0, 0, 0, 0,
        // Universe Discovery Layer
        // Flags and Length
        0x70, 0x0e,
        // Vector
        0x00, 0x00, 0x00, 0x01,
        // Page
        1,
        // Last Page
        2,
        // Universes
        0, 3, 0, 4, 0, 5,
    ];

    #[cfg_attr(rustfmt, rustfmt_skip)]
    const TEST_SYNCHRONIZATION_PACKET: &[u8] = &[
        // Root Layer
        // Preamble Size
        0x00, 0x10,
        // Post-amble Size
        0x00, 0x00,
        // ACN Packet Identifier
        0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00,
        0x00, 0x00,
        // Flags and Length Protocol
        0x70, 0x21, // 0x30 in E1-31-2016 sample packet (which is wrong)
        // Vector
        0x00, 0x00, 0x00, 0x08,
        // CID
        0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2,
        0x45, 0x9e, 0xf8, 0xe6, 0x14, 0x3e,
        // Synchronization Packet Framing Layer
        // Flags and Length
        0x70, 0x0b, // 0x0a in E1-31-2016 sample packet (which is wrong)
        // Vector
        0x00, 0x00, 0x00, 0x01,
        // Sequence Number
        0x65, // 367 % 0xff
        // Synchronization Address
        0x1F, 0x1A, // 7962
        // Reserved
        0, 0,
    ];

    #[test]
    fn test_data_packet() {
        let packet = AcnRootLayerProtocol {
            pdu: E131RootLayer {
                cid: Uuid::from_bytes(&TEST_DATA_PACKET[22..38]).unwrap(),
                data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
                    source_name: "Source_A",
                    priority: 100,
                    synchronization_address: 7962,
                    sequence_number: 154,
                    preview_data: false,
                    stream_terminated: false,
                    force_synchronization: false,
                    universe: 1,
                    data: DataPacketDmpLayer {
                        property_values: DataPacketDmpLayerPropertyValues {
                            start_code: 0,
                            dmx_data: &TEST_DATA_PACKET[126..638],
                        },
                    },
                }),
            },
        };

        assert_eq!(
            AcnRootLayerProtocol::parse(&TEST_DATA_PACKET).unwrap(),
            packet
        );

        let mut buf = [0; 638];
        packet.pack(&mut buf).unwrap();

        assert_eq!(&buf[..packet.len()], TEST_DATA_PACKET);
    }

    #[test]
    fn test_synchronization_packet() {
        let packet = AcnRootLayerProtocol {
            pdu: E131RootLayer {
                cid: Uuid::from_bytes(&TEST_DATA_PACKET[22..38]).unwrap(),
                data: E131RootLayerData::SynchronizationPacket(SynchronizationPacketFramingLayer {
                    sequence_number: 0x65,
                    synchronization_address: 7962,
                }),
            },
        };

        assert_eq!(
            AcnRootLayerProtocol::parse(&TEST_SYNCHRONIZATION_PACKET).unwrap(),
            packet
        );

        let mut buf = [0; 49];
        packet.pack(&mut buf).unwrap();

        assert_eq!(&buf[..packet.len()], TEST_SYNCHRONIZATION_PACKET);
    }

    #[test]
    fn test_universe_discovery_packet() {
        let packet = AcnRootLayerProtocol {
            pdu: E131RootLayer {
                cid: Uuid::from_bytes(&TEST_DATA_PACKET[22..38]).unwrap(),
                data: E131RootLayerData::UniverseDiscoveryPacket(
                    UniverseDiscoveryPacketFramingLayer {
                        source_name: "Source_A",
                        data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
                            page: 1,
                            last_page: 2,
                            universes: Universes::from(&[3, 4, 5]),
                        },
                    },
                ),
            },
        };

        assert_eq!(
            AcnRootLayerProtocol::parse(&TEST_UNIVERSE_DISCOVERY_PACKET).unwrap(),
            packet
        );

        let mut buf = [0; 126];
        packet.pack(&mut buf).unwrap();

        assert_eq!(&buf[..packet.len()], TEST_UNIVERSE_DISCOVERY_PACKET);
    }
}