srt/
packet.rs

1// Packet structures
2// see https://tools.ietf.org/html/draft-gg-udt-03#page-5
3
4use std::fmt::{self, Debug, Formatter};
5
6use bytes::{Buf, BufMut};
7
8mod codec;
9mod control;
10mod data;
11mod error;
12
13pub use self::codec::PacketCodec;
14pub use self::control::{
15    AckControlInfo, CipherType, ControlPacket, ControlTypes, HandshakeControlInfo, HandshakeVSInfo,
16    ShakeType, SocketType, SrtControlPacket, SrtHandshake, SrtKeyMessage, SrtShakeFlags,
17};
18pub use self::data::{DataPacket, PacketLocation};
19pub use error::PacketParseError;
20
21use crate::protocol::TimeStamp;
22use crate::SocketID;
23
24/// Represents A UDT/SRT packet
25#[allow(clippy::large_enum_variant)]
26#[derive(Clone, PartialEq, Eq)]
27pub enum Packet {
28    Data(DataPacket),
29    Control(ControlPacket),
30}
31impl Packet {
32    pub fn timestamp(&self) -> TimeStamp {
33        match *self {
34            Packet::Data(DataPacket { timestamp, .. })
35            | Packet::Control(ControlPacket { timestamp, .. }) => timestamp,
36        }
37    }
38
39    pub fn dest_sockid(&self) -> SocketID {
40        match *self {
41            Packet::Data(DataPacket { dest_sockid, .. })
42            | Packet::Control(ControlPacket { dest_sockid, .. }) => dest_sockid,
43        }
44    }
45
46    pub fn parse<T: Buf>(buf: &mut T) -> Result<Packet, PacketParseError> {
47        // Buffer must be at least 16 bytes,
48        // the length of a header packet
49        if buf.remaining() < 16 {
50            return Err(PacketParseError::NotEnoughData);
51        }
52
53        // peek at the first byte to check if it's data or control
54        let first = buf.bytes()[0];
55
56        // Check if the first bit is one or zero;
57        // if it's one it's a cotnrol packet,
58        // if zero it's a data packet
59        Ok(if (first & 0x80) == 0 {
60            Packet::Data(DataPacket::parse(buf)?)
61        } else {
62            Packet::Control(ControlPacket::parse(buf)?)
63        })
64    }
65
66    pub fn serialize<T: BufMut>(&self, into: &mut T) {
67        match *self {
68            Packet::Control(ref control) => {
69                control.serialize(into);
70            }
71            Packet::Data(ref data) => {
72                data.serialize(into);
73            }
74        }
75    }
76}
77impl Debug for Packet {
78    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
79        match self {
80            Packet::Data(dp) => write!(f, "{:?}", dp),
81            Packet::Control(cp) => write!(f, "{:?}", cp),
82        }
83    }
84}