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
use core::{convert::TryFrom, time::Duration};
use std::{
    error::Error,
    io::{Cursor, ErrorKind, Read, Write},
    net::{SocketAddr, UdpSocket},
    time::{Instant, SystemTime},
};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

use crate::{
    protocol::{LookupInfo, ScanInfo, MAGIC},
    rtp::Header,
};

pub mod mac;
pub mod protocol;
mod rtp;

enum Command {
    Scan,
    ScanReply,
    StartRtp,
}

impl Command {
    pub fn as_u16(&self) -> u16 {
        match self {
            Command::Scan => 0x1004,
            Command::ScanReply => 0x100e,
            Command::StartRtp => 0x1007,
        }
    }

    pub fn encode(&self, cid: &[u8], args: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
        let mut cid = cid;
        if cid.len() > 15 {
            cid = &cid[..15]
        }

        let mut buf = Cursor::new(Vec::new());

        buf.write_u16::<BigEndian>(MAGIC)?;
        buf.write_u16::<BigEndian>(self.as_u16())?;
        buf.write_all(cid)?;
        buf.write_all(&b"000000000000000"[..15usize.saturating_sub(cid.len())])?;
        buf.write_all(&[0x0])?;
        buf.write_all(args)?;

        Ok(buf.into_inner())
    }
}

pub fn lookup() -> Result<LookupInfo, Box<dyn Error>> {
    let sock = UdpSocket::bind("0.0.0.0:0")?;
    sock.set_broadcast(true)?;
    sock.set_read_timeout(Some(Duration::new(1, 0)))?;

    let comm = Command::Scan.encode(b"", b"00000000000000000000000000000000000000")?;
    sock.send_to(&comm, "192.168.1.71:10008")?;

    let mut buf = [0; 4096];

    loop {
        let (size, addr) = match sock.recv_from(&mut buf[..]) {
            Ok((size, addr)) => (size, addr),
            Err(ref err) if err.kind() == ErrorKind::WouldBlock => {
                return Err("timed out".into());
            }
            Err(err) => return Err(err.into()),
        };

        let mut buf = Cursor::new(&buf[..size]);

        let magic = buf.read_u16::<BigEndian>()?;

        if magic != MAGIC {
            return Err("invalid magic header".into());
        }

        let comm = buf.read_u16::<BigEndian>()?;

        if comm != Command::ScanReply.as_u16() {
            continue;
        }

        let mut cid = [0; 16];
        buf.read_exact(&mut cid[..])?;

        let idx = buf.position() as usize;
        let info = ScanInfo::try_from(&buf.into_inner()[idx..])?;
        let info = LookupInfo::new(addr, cid, info);

        return Ok(info);
    }
}

pub fn stream<F>(cid: &[u8], src: SocketAddr, f: F) -> Result<(), Box<dyn Error>>
where
    F: Fn(&[u8]) -> Result<(), Box<dyn Error>>,
{
    let sock = UdpSocket::bind("0.0.0.0:0")?;
    sock.set_read_timeout(Some(Duration::new(10, 0)))?;

    let local_addr = sock.local_addr()?;

    let mut args = Cursor::new(Vec::new());
    args.write_all(b"00000000000000000000000000000000000000")?;
    args.write_fmt(format_args!("{}:{}\0", local_addr.port(), local_addr.port()))?;

    let comm = Command::StartRtp.encode(cid, &args.into_inner())?;
    sock.send_to(&comm, src)?;

    let mut timestamp = Instant::now();
    let mut buf = [0; 4096];
    loop {
        let (size, addr) = sock.recv_from(&mut buf[..])?;

        if timestamp.elapsed() >= Duration::from_secs(1) {
            timestamp = Instant::now();
            send_rtcp(&sock, &addr)?;
        }

        if buf[..size].len() < 16 {
            continue;
        }

        let hdr = Header::from_slice(&buf[4..])?;

        if hdr.version() != 2 {
            continue;
        }

        // Skip non-video frames.
        if buf[2] != 1 {
            continue;
        }

        if hdr.ssrc() != 16 {
            continue;
        }

        f(&buf[4..size])?;
    }
}

fn send_rtcp(sock: &UdpSocket, camera: &SocketAddr) -> Result<(), Box<dyn Error>> {
    let mut buf = Cursor::new(Vec::new());

    buf.write_all(&[
        0x00, 0x00, 0x01, 0x00, // Header.
        0x80, // RTP v2
        0xc8, // RTCP sender report packet type
        0x00, 0x06,
    ])?;
    buf.write_u32::<BigEndian>(0x00000002)?;

    let msecs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_nanos() / 1e6 as u128 + 2208988800000;
    let seconds = (msecs / 1000) as u32;
    let fraction = (0x100000000 * (msecs % 1000) / 1000) as u32;

    buf.write_u32::<BigEndian>(seconds)?;
    buf.write_u32::<BigEndian>(fraction)?;
    buf.write_u32::<BigEndian>(0)?;
    buf.write_u32::<BigEndian>(0)?;
    buf.write_u32::<BigEndian>(0)?;

    sock.send_to(&buf.into_inner(), camera)?;

    Ok(())
}