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
use std::{
    fmt::{self, Display, Formatter},
    {collections::BTreeMap, convert::TryFrom, time::Duration},
};

use bitflags::bitflags;
use bytes::{Buf, BufMut};
use log::warn;

use crate::{options::SrtVersion, packet::PacketParseError};

/// The SRT-specific control packets
/// These are `Packet::Custom` types
#[derive(Clone, Eq, PartialEq)]
pub enum SrtControlPacket {
    /// SRT handshake reject
    /// ID = 0
    Reject,

    /// SRT handshake request
    /// ID = 1
    HandshakeRequest(SrtHandshake),

    /// SRT handshake response
    /// ID = 2
    HandshakeResponse(SrtHandshake),

    /// Key manager request
    /// ID = 3
    KeyRefreshRequest(KeyingMaterialMessage),

    /// Key manager response
    /// ID = 4
    KeyRefreshResponse(KeyingMaterialMessage),

    /// Stream identifier
    /// ID = 5
    StreamId(String),

    /// Congestion control type. Often "live" or "file"
    /// ID = 6
    Congestion(String),

    /// ID = 7
    /// Filter seems to be a string of
    /// comma-separted key-value pairs like:
    /// a:b,c:d
    Filter(FilterSpec),

    // ID = 8
    Group {
        ty: GroupType,
        flags: GroupFlags,
        weight: u16,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterSpec(pub BTreeMap<String, String>);

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum GroupType {
    Undefined,
    Broadcast,
    MainBackup,
    Balancing,
    Multicast,
    Unrecognized(u8),
}

bitflags! {
    pub struct GroupFlags: u8 {
        const MSG_SYNC = 1 << 6;
    }
}

/// from https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/haicrypt/hcrypt_msg.h#L76-L96
/// or https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-00#section-3.2.2
///
/// HaiCrypt KMmsg (Keying Material Message):
///
/// ```ignore,
///        0                   1                   2                   3
///        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// +0x00 |0|Vers |   PT  |             Sign              |    resv   |KF |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// +0x04 |                              KEKI                             |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// +0x08 |    Cipher     |      Auth     |      SE       |     Resv1     |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// +0x0C |             Resv2             |     Slen/4    |     Klen/4    |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// +0x10 |                              Salt                             |
///       |                              ...                              |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
///       |                              Wrap                             |
///       |                              ...                              |
///       +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// ```
///
#[derive(Clone, Eq, PartialEq)]
pub struct KeyingMaterialMessage {
    pub pt: PacketType, // TODO: i think this is always KeyingMaterial....
    pub key_flags: KeyFlags,
    pub keki: u32,
    pub cipher: CipherType,
    pub auth: Auth,
    pub salt: Vec<u8>,
    pub wrapped_keys: Vec<u8>,
}

impl From<GroupType> for u8 {
    fn from(from: GroupType) -> u8 {
        match from {
            GroupType::Undefined => 0,
            GroupType::Broadcast => 1,
            GroupType::MainBackup => 2,
            GroupType::Balancing => 3,
            GroupType::Multicast => 4,
            GroupType::Unrecognized(u) => u,
        }
    }
}

impl From<u8> for GroupType {
    fn from(from: u8) -> GroupType {
        match from {
            0 => GroupType::Undefined,
            1 => GroupType::Broadcast,
            2 => GroupType::MainBackup,
            3 => GroupType::Balancing,
            4 => GroupType::Multicast,
            u => GroupType::Unrecognized(u),
        }
    }
}

impl fmt::Debug for KeyingMaterialMessage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeyingMaterialMessage")
            .field("pt", &self.pt)
            .field("key_flags", &self.key_flags)
            .field("keki", &self.keki)
            .field("cipher", &self.cipher)
            .field("auth", &self.auth)
            .finish()
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Auth {
    None = 0,
}

impl TryFrom<u8> for Auth {
    type Error = PacketParseError;
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Auth::None),
            e => Err(PacketParseError::BadAuth(e)),
        }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum StreamEncapsulation {
    Udp = 1,
    Srt = 2,
}

impl TryFrom<u8> for StreamEncapsulation {
    type Error = PacketParseError;
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        Ok(match value {
            1 => StreamEncapsulation::Udp,
            2 => StreamEncapsulation::Srt,
            e => return Err(PacketParseError::BadStreamEncapsulation(e)),
        })
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
// see htcryp_msg.h:43...
// 7: Reserved to discriminate MPEG-TS packet (0x47=sync byte).
pub enum PacketType {
    MediaStream = 1,    // Media Stream Message (MSmsg)
    KeyingMaterial = 2, // Keying Material Message (KMmsg)
}

bitflags! {
    pub struct KeyFlags : u8 {
        const EVEN = 0b01;
        const ODD = 0b10;
    }
}

impl TryFrom<u8> for PacketType {
    type Error = PacketParseError;
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(PacketType::MediaStream),
            2 => Ok(PacketType::KeyingMaterial),
            err => Err(PacketParseError::BadKeyPacketType(err)),
        }
    }
}

/// from https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/haicrypt/hcrypt_msg.h#L121-L124
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum CipherType {
    None = 0,
    Ecb = 1,
    Ctr = 2,
    Cbc = 3,
}

/// The SRT handshake object
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct SrtHandshake {
    /// The SRT version
    /// Serialized just as the u32 that SrtVersion serialized to
    pub version: SrtVersion,

    /// SRT connection init flags
    pub flags: SrtShakeFlags,

    /// The peer's TSBPD latency (latency to send at)
    /// This is serialized as the upper 16 bits of the third 32-bit word
    /// source: https://github.com/Haivision/srt/blob/4f7f2beb2e1e306111b9b11402049a90cb6d3787/srtcore/core.cpp#L1341-L1353
    pub send_latency: Duration,

    /// The TSBPD latency (latency to recv at)
    /// This is serialized as the lower 16 bits of the third 32-bit word
    /// see csrtcc.cpp:132 in the reference implementation
    pub recv_latency: Duration,
}

bitflags! {
    pub struct SrtShakeFlags: u32 {
        /// Timestamp-based Packet delivery real-time data sender
        const TSBPDSND = 0x1;

        /// Timestamp-based Packet delivery real-time data receiver
        const TSBPDRCV = 0x2;

        /// HaiCrypt AES-128/192/256-CTR
        /// also represents if it supports the encryption flags in the data packet
        const HAICRYPT = 0x4;

        /// Drop real-time data packets too late to be processed in time
        const TLPKTDROP = 0x8;

        /// Periodic NAK report
        const NAKREPORT = 0x10;

        /// One bit in payload packet msgno is "retransmitted" flag
        const REXMITFLG = 0x20;

        /// This entity supports stream ID packets
        const STREAM = 0x40;

        /// Again not sure... TODO:
        const PACKET_FILTER = 0x80;

        // currently implemented flags
        const SUPPORTED = Self::TSBPDSND.bits | Self::TSBPDRCV.bits | Self::HAICRYPT.bits | Self::REXMITFLG.bits;
    }
}

fn le_bytes_to_string(le_bytes: &mut impl Buf) -> Result<String, PacketParseError> {
    if le_bytes.remaining() % 4 != 0 {
        return Err(PacketParseError::NotEnoughData);
    }

    let mut str_bytes = Vec::with_capacity(le_bytes.remaining());

    while le_bytes.remaining() > 4 {
        str_bytes.extend(le_bytes.get_u32_le().to_be_bytes());
    }

    // make sure to skip padding bytes if any for the last word
    match le_bytes.get_u32_le().to_be_bytes() {
        [a, 0, 0, 0] => str_bytes.push(a),
        [a, b, 0, 0] => str_bytes.extend([a, b]),
        [a, b, c, 0] => str_bytes.extend([a, b, c]),
        [a, b, c, d] => str_bytes.extend([a, b, c, d]),
    }

    String::from_utf8(str_bytes).map_err(|e| PacketParseError::StreamTypeNotUtf8(e.utf8_error()))
}

fn string_to_le_bytes(str: &str, into: &mut impl BufMut) {
    let mut chunks = str.as_bytes().chunks_exact(4);

    while let Some(&[a, b, c, d]) = chunks.next() {
        into.put(&[d, c, b, a][..]);
    }

    // add padding bytes for the final word if needed
    match *chunks.remainder() {
        [a, b, c] => into.put(&[0, c, b, a][..]),
        [a, b] => into.put(&[0, 0, b, a][..]),
        [a] => into.put(&[0, 0, 0, a][..]),
        [] => {} // exact multiple of 4
        _ => unreachable!(),
    }
}

impl Display for FilterSpec {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        for (i, (k, v)) in self.0.iter().enumerate() {
            write!(f, "{k}:{v}")?;
            if i != self.0.len() - 1 {
                write!(f, ",")?;
            }
        }
        Ok(())
    }
}

impl SrtControlPacket {
    pub fn parse<T: Buf>(
        packet_type: u16,
        buf: &mut T,
    ) -> Result<SrtControlPacket, PacketParseError> {
        use self::SrtControlPacket::*;

        match packet_type {
            0 => Ok(Reject),
            1 => Ok(HandshakeRequest(SrtHandshake::parse(buf)?)),
            2 => Ok(HandshakeResponse(SrtHandshake::parse(buf)?)),
            3 => Ok(KeyRefreshRequest(KeyingMaterialMessage::parse(buf)?)),
            4 => Ok(KeyRefreshResponse(KeyingMaterialMessage::parse(buf)?)),
            5 => {
                // the stream id string is stored as 32-bit little endian words
                // https://tools.ietf.org/html/draft-sharabayko-mops-srt-01#section-3.2.1.3
                le_bytes_to_string(buf).map(StreamId)
            }
            6 => le_bytes_to_string(buf).map(Congestion),
            // Filter
            7 => {
                let filter_str = le_bytes_to_string(buf)?;
                Ok(Filter(FilterSpec(
                    filter_str
                        .split(',')
                        .map(|kv| {
                            let mut colon_split_iter = kv.split(':');
                            let k = colon_split_iter
                                .next()
                                .ok_or_else(|| PacketParseError::BadFilter(filter_str.clone()))?;
                            let v = colon_split_iter
                                .next()
                                .ok_or_else(|| PacketParseError::BadFilter(filter_str.clone()))?;
                            // only one colon
                            if colon_split_iter.next().is_some() {
                                return Err(PacketParseError::BadFilter(filter_str.clone()));
                            }
                            Ok((k.to_string(), v.to_string()))
                        })
                        .collect::<Result<_, _>>()?,
                )))
            }
            8 => {
                let ty = buf.get_u8().into();
                let flags = GroupFlags::from_bits_truncate(buf.get_u8());
                let weight = buf.get_u16_le();
                Ok(Group { ty, flags, weight })
            }
            _ => Err(PacketParseError::UnsupportedSrtExtensionType(packet_type)),
        }
    }

    /// Get the value to fill the reserved area with
    pub fn type_id(&self) -> u16 {
        use self::SrtControlPacket::*;

        match self {
            Reject => 0,
            HandshakeRequest(_) => 1,
            HandshakeResponse(_) => 2,
            KeyRefreshRequest(_) => 3,
            KeyRefreshResponse(_) => 4,
            StreamId(_) => 5,
            Congestion(_) => 6,
            Filter(_) => 7,
            Group { .. } => 8,
        }
    }
    pub fn serialize<T: BufMut>(&self, into: &mut T) {
        use self::SrtControlPacket::*;

        match self {
            HandshakeRequest(s) | HandshakeResponse(s) => {
                s.serialize(into);
            }
            KeyRefreshRequest(k) | KeyRefreshResponse(k) => {
                k.serialize(into);
            }
            Filter(filter) => {
                string_to_le_bytes(&format!("{filter}"), into);
            }
            Group { ty, flags, weight } => {
                into.put_u8((*ty).into());
                into.put_u8(flags.bits());
                into.put_u16_le(*weight);
            }
            Reject => {}
            StreamId(str) | Congestion(str) => {
                // the stream id string and congestion string is stored as 32-bit little endian words
                // https://tools.ietf.org/html/draft-sharabayko-mops-srt-01#section-3.2.1.3
                string_to_le_bytes(str, into);
            }
        }
    }
    // size in 32-bit words
    pub fn size_words(&self) -> u16 {
        use self::SrtControlPacket::*;

        match self {
            // 3 32-bit words, version, flags, latency
            HandshakeRequest(_) | HandshakeResponse(_) => 3,
            // 4 32-bit words + salt + key + wrap [2]
            KeyRefreshRequest(ref k) | KeyRefreshResponse(ref k) => {
                4 + k.salt.len() as u16 / 4 + k.wrapped_keys.len() as u16 / 4
            }
            Congestion(str) | StreamId(str) => ((str.len() + 3) / 4) as u16, // round up to nearest multiple of 4
            // 1 32-bit word packed with type, flags, and weight
            Group { .. } => 1,
            Filter(filter) => ((format!("{filter}").len() + 3) / 4) as u16, // TODO: not optimial performace, but probably okay
            _ => unimplemented!("{:?}", self),
        }
    }
}

impl SrtHandshake {
    pub fn parse<T: Buf>(buf: &mut T) -> Result<SrtHandshake, PacketParseError> {
        if buf.remaining() < 12 {
            return Err(PacketParseError::NotEnoughData);
        }

        let version = SrtVersion::parse(buf.get_u32());

        let shake_flags = buf.get_u32();
        let flags = match SrtShakeFlags::from_bits(shake_flags) {
            Some(i) => i,
            None => {
                warn!("Unrecognized SRT flags: 0b{:b}", shake_flags);
                SrtShakeFlags::from_bits_truncate(shake_flags)
            }
        };
        let peer_latency = buf.get_u16();
        let latency = buf.get_u16();

        Ok(SrtHandshake {
            version,
            flags,
            send_latency: Duration::from_millis(u64::from(peer_latency)),
            recv_latency: Duration::from_millis(u64::from(latency)),
        })
    }

    pub fn serialize<T: BufMut>(&self, into: &mut T) {
        into.put_u32(self.version.to_u32());
        into.put_u32(self.flags.bits());
        // upper 16 bits are peer latency
        into.put_u16(self.send_latency.as_millis() as u16); // TODO: handle overflow

        // lower 16 is latency
        into.put_u16(self.recv_latency.as_millis() as u16); // TODO: handle overflow
    }
}

impl KeyingMaterialMessage {
    // from hcrypt_msg.h:39
    // also const traits aren't a thing yet, so u16::from can't be used
    const SIGN: u16 =
        ((b'H' - b'@') as u16) << 10 | ((b'A' - b'@') as u16) << 5 | (b'I' - b'@') as u16;

    pub fn parse(buf: &mut impl Buf) -> Result<KeyingMaterialMessage, PacketParseError> {
        // first 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |0|Vers |   PT  |             Sign              |    resv   |KF |

        // make sure there is enough data left in the buffer to at least get to the key flags and length, which tells us how long the packet will be
        // that's 4x32bit words
        if buf.remaining() < 4 * 4 {
            return Err(PacketParseError::NotEnoughData);
        }

        let vers_pt = buf.get_u8();

        // make sure the first bit is zero
        if (vers_pt & 0b1000_0000) != 0 {
            return Err(PacketParseError::BadSrtExtensionMessage);
        }

        // upper 4 bits are version
        let version = vers_pt >> 4;

        if version != 1 {
            return Err(PacketParseError::BadSrtExtensionMessage);
        }

        // lower 4 bits are pt
        let pt = PacketType::try_from(vers_pt & 0b0000_1111)?;

        // next 16 bis are sign
        let sign = buf.get_u16();

        if sign != Self::SIGN {
            return Err(PacketParseError::BadKeySign(sign));
        }

        // next 6 bits is reserved, then two bits of KF
        let key_flags = KeyFlags::from_bits_truncate(buf.get_u8() & 0b0000_0011);

        // second 32-bit word: keki
        let keki = buf.get_u32();

        // third 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |    Cipher     |      Auth     |      SE       |     Resv1     |

        let cipher = CipherType::try_from(buf.get_u8())?;
        let auth = Auth::try_from(buf.get_u8())?;
        let se = StreamEncapsulation::try_from(buf.get_u8())?;
        if se != StreamEncapsulation::Srt {
            return Err(PacketParseError::StreamEncapsulationNotSrt);
        }

        let _resv1 = buf.get_u8();

        // fourth 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |             Resv2             |     Slen/4    |     Klen/4    |

        let _resv2 = buf.get_u16();
        let salt_len = usize::from(buf.get_u8()) * 4;
        let key_len = usize::from(buf.get_u8()) * 4;

        // acceptable key lengths are 16, 24, and 32
        match key_len {
            // OK
            16 | 24 | 32 => {}
            // not
            e => return Err(PacketParseError::BadCryptoLength(e as u32)),
        }

        // get the size of the packet to make sure that there is enough space

        // salt + keys (there's a 1 for each in key flags, it's already been anded with 0b11 so max is 2), wrap data is 8 long
        if buf.remaining() < salt_len + key_len * (key_flags.bits.count_ones() as usize) + 8 {
            return Err(PacketParseError::NotEnoughData);
        }

        // the reference implmentation converts the whole thing to network order (bit endian) (in 32-bit words)
        // so we need to make sure to do the same. Source:
        // https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/srtcore/crypto.cpp#L115

        // after this, is the salt
        let mut salt = vec![];
        for _ in 0..salt_len / 4 {
            salt.extend_from_slice(&buf.get_u32().to_be_bytes()[..]);
        }

        // then key[s]
        let mut wrapped_keys = vec![];

        for _ in 0..(key_len * key_flags.bits.count_ones() as usize + 8) / 4 {
            wrapped_keys.extend_from_slice(&buf.get_u32().to_be_bytes()[..]);
        }

        Ok(KeyingMaterialMessage {
            pt,
            key_flags,
            keki,
            cipher,
            auth,
            salt,
            wrapped_keys,
        })
    }

    fn serialize<T: BufMut>(&self, into: &mut T) {
        // first 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |0|Vers |   PT  |             Sign              |    resv   |KF |

        // version is 1
        into.put_u8(1 << 4 | self.pt as u8);

        into.put_u16(Self::SIGN);

        // rightmost bit of KF is even, other is odd
        into.put_u8(self.key_flags.bits);

        // second 32-bit word: keki
        into.put_u32(self.keki);

        // third 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |    Cipher     |      Auth     |      SE       |     Resv1     |
        into.put_u8(self.cipher as u8);
        into.put_u8(self.auth as u8);
        into.put_u8(StreamEncapsulation::Srt as u8);
        into.put_u8(0); // resv1

        // fourth 32-bit word:
        //
        //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        // +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
        // |             Resv2             |     Slen/4    |     Klen/4    |
        into.put_u16(0); // resv2
        into.put_u8((self.salt.len() / 4) as u8);

        // this unwrap is okay because we already panic above if both are None
        let key_len = (self.wrapped_keys.len() - 8) / self.key_flags.bits.count_ones() as usize;
        into.put_u8((key_len / 4) as u8);

        // put the salt then key[s]
        into.put(&self.salt[..]);

        // the reference implmentation converts the whole thing to network order (big endian) (in 32-bit words)
        // so we need to make sure to do the same. Source:
        // https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/srtcore/crypto.cpp#L115

        for num in self.wrapped_keys[..].chunks(4) {
            into.put_u32(u32::from_be_bytes([num[0], num[1], num[2], num[3]]));
        }
    }
}

impl fmt::Debug for SrtControlPacket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SrtControlPacket::Reject => write!(f, "reject"),
            SrtControlPacket::HandshakeRequest(req) => write!(f, "hsreq={req:?}"),
            SrtControlPacket::HandshakeResponse(resp) => write!(f, "hsresp={resp:?}"),
            SrtControlPacket::KeyRefreshRequest(req) => write!(f, "kmreq={req:?}"),
            SrtControlPacket::KeyRefreshResponse(resp) => write!(f, "kmresp={resp:?}"),
            SrtControlPacket::StreamId(sid) => write!(f, "streamid={sid}"),
            SrtControlPacket::Congestion(ctype) => write!(f, "congestion={ctype}"),
            SrtControlPacket::Filter(filter) => write!(f, "filter={filter:?}"),
            SrtControlPacket::Group { ty, flags, weight } => {
                write!(f, "group=({ty:?}, {flags:?}, {weight:?})")
            }
        }
    }
}

impl TryFrom<u8> for CipherType {
    type Error = PacketParseError;
    fn try_from(from: u8) -> Result<CipherType, PacketParseError> {
        match from {
            0 => Ok(CipherType::None),
            1 => Ok(CipherType::Ecb),
            2 => Ok(CipherType::Ctr),
            3 => Ok(CipherType::Cbc),
            e => Err(PacketParseError::BadCipherKind(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{KeyingMaterialMessage, SrtControlPacket, SrtHandshake, SrtShakeFlags};

    use crate::{options::*, packet::*};

    use std::{io::Cursor, time::Duration};

    #[test]
    fn deser_ser_shake() {
        let handshake = Packet::Control(ControlPacket {
            timestamp: TimeStamp::from_micros(123_141),
            dest_sockid: SocketId(123),
            control_type: ControlTypes::Srt(SrtControlPacket::HandshakeRequest(SrtHandshake {
                version: SrtVersion::CURRENT,
                flags: SrtShakeFlags::empty(),
                send_latency: Duration::from_millis(4000),
                recv_latency: Duration::from_millis(3000),
            })),
        });

        let mut buf = Vec::new();
        handshake.serialize(&mut buf);

        let deserialized = Packet::parse(&mut Cursor::new(buf), false).unwrap();

        assert_eq!(handshake, deserialized);
    }

    #[test]
    fn ser_deser_sid() {
        let sid = Packet::Control(ControlPacket {
            timestamp: TimeStamp::from_micros(123),
            dest_sockid: SocketId(1234),
            control_type: ControlTypes::Srt(SrtControlPacket::StreamId("Hellohelloheloo".into())),
        });

        let mut buf = Vec::new();
        sid.serialize(&mut buf);

        let deser = Packet::parse(&mut Cursor::new(buf), false).unwrap();

        assert_eq!(sid, deser);
    }

    #[test]
    fn srt_key_message_debug() {
        let salt = b"\x00\x00\x00\x00\x00\x00\x00\x00\x85\x2c\x3c\xcd\x02\x65\x1a\x22";
        let wrapped = b"U\x06\xe9\xfd\xdfd\xf1'nr\xf4\xe9f\x81#(\xb7\xb5D\x19{\x9b\xcdx";

        let km = KeyingMaterialMessage {
            pt: PacketType::KeyingMaterial,
            key_flags: KeyFlags::EVEN,
            keki: 0,
            cipher: CipherType::Ctr,
            auth: Auth::None,
            salt: salt[..].into(),
            wrapped_keys: wrapped[..].into(),
        };

        assert_eq!(format!("{km:?}"), "KeyingMaterialMessage { pt: KeyingMaterial, key_flags: EVEN, keki: 0, cipher: Ctr, auth: None }")
    }
}