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
// Copyright 2017 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.

use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{Error, ErrorKind, Result};
use std::net::UdpSocket;

use net2::UdpBuilder;
use uuid::Uuid;

use packet::{AcnRootLayerProtocol, DataPacketDmpLayer, DataPacketDmpLayerPropertyValues,
             DataPacketFramingLayer, E131RootLayer, E131RootLayerData};

fn universe_to_ip(universe: u16) -> Result<String> {
    if universe == 0 || universe > 63999 {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "universe is limited to the range 1 to 63999",
        ));
    }
    let high_byte = (universe >> 8) & 0xff;
    let low_byte = universe & 0xff;
    Ok(format!("239.255.{}.{}:5568", high_byte, low_byte))
}

/// A DMX over sACN sender.
///
/// DmxSource is used for sending sACN packets over ethernet.
///
/// Each universe will be sent to a dedicated multicast address
/// "239.255.{universe_high_byte}.{universe_low_byte}".
///
/// # Examples
///
/// ```
/// use sacn::DmxSource;
///
/// let mut dmx_source = DmxSource::new("Controller").unwrap();
///
/// dmx_source.send(1, &[100, 100, 100, 100, 100, 100]);
/// dmx_source.terminate_stream(1);
/// ```
#[derive(Debug)]
pub struct DmxSource {
    socket: UdpSocket,
    cid: Uuid,
    name: String,
    preview_data: bool,
    start_code: u8,
    sequences: RefCell<HashMap<u16, u8>>,
}

impl DmxSource {
    /// Constructs a new DmxSource with DMX START code set to 0.
    pub fn new(name: &str) -> Result<DmxSource> {
        let cid = Uuid::new_v4();
        DmxSource::with_cid(name, cid)
    }
    /// Consturcts a new DmxSource with binding to the supplied ip and a DMX START code set to 0.
    pub fn with_ip(name: &str, ip: &str) -> Result<DmxSource> {
        let cid = Uuid::new_v4();
        DmxSource::with_cid_ip(name, cid, ip)
    }

    /// Constructs a new DmxSource with DMX START code set to 0 with specified CID.
    pub fn with_cid(name: &str, cid: Uuid) -> Result<DmxSource> {
        let ip = "0.0.0.0";
        DmxSource::with_cid_ip(name, cid, &ip)
    }
    /// Constructs a new DmxSource with DMX START code set to 0 with specified CID and IP address.
    pub fn with_cid_ip(name: &str, cid: Uuid, ip: &str) -> Result<DmxSource> {
        let ip_port = format!("{}:0", ip);
        let sock_builder = try!(UdpBuilder::new_v4());
        let sock = try!(sock_builder.bind(&ip_port));

        Ok(DmxSource {
            socket: sock,
            cid: cid.clone(),
            name: name.to_string(),
            preview_data: false,
            start_code: 0,
            sequences: RefCell::new(HashMap::new()),
        })
    }

    /// Sends DMX data to specified universe.
    pub fn send(&self, universe: u16, data: &[u8]) -> Result<()> {
        self.send_with_priority(universe, data, 100)
    }

    /// Sends DMX data to specified universe with specified priority.
    pub fn send_with_priority(&self, universe: u16, data: &[u8], priority: u8) -> Result<()> {
        if priority > 200 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "priority must be <= 200",
            ));
        }
        let ip = try!(universe_to_ip(universe));
        let mut sequence = match self.sequences.borrow().get(&universe) {
            Some(s) => s.clone(),
            None => 0,
        };

        let packet = AcnRootLayerProtocol {
            pdu: E131RootLayer {
                cid: self.cid,
                data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
                    source_name: &self.name,
                    priority: priority,
                    synchronization_address: 0,
                    sequence_number: sequence,
                    preview_data: self.preview_data,
                    stream_terminated: false,
                    force_synchronization: false,
                    universe: universe,
                    data: DataPacketDmpLayer {
                        property_values: DataPacketDmpLayerPropertyValues {
                            start_code: self.start_code,
                            dmx_data: data,
                        },
                    },
                }),
            },
        };
        try!(self.socket.send_to(&packet.pack_alloc().unwrap(), &*ip));

        if sequence == 255 {
            sequence = 0;
        } else {
            sequence += 1;
        }
        self.sequences.borrow_mut().insert(universe, sequence);
        Ok(())
    }

    /// Terminates a universe stream.
    ///
    /// Terminates a stream to a specified universe by sending three packages with
    /// Stream_Terminated flag set to 1.
    pub fn terminate_stream(&self, universe: u16) -> Result<()> {
        let ip = try!(universe_to_ip(universe));
        let mut sequence = match self.sequences.borrow_mut().remove(&universe) {
            Some(s) => s,
            None => 0,
        };

        for _ in 0..3 {
            let packet = AcnRootLayerProtocol {
                pdu: E131RootLayer {
                    cid: self.cid,
                    data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
                        source_name: &self.name,
                        priority: 100,
                        synchronization_address: 0,
                        sequence_number: sequence,
                        preview_data: self.preview_data,
                        stream_terminated: true,
                        force_synchronization: false,
                        universe: universe,
                        data: DataPacketDmpLayer {
                            property_values: DataPacketDmpLayerPropertyValues {
                                start_code: self.start_code,
                                dmx_data: &[],
                            },
                        },
                    }),
                },
            };
            try!(self.socket.send_to(&packet.pack_alloc().unwrap(), &*ip));

            if sequence == 255 {
                sequence = 0;
            } else {
                sequence += 1;
            }
        }
        Ok(())
    }

    /// Returns the ACN CID device identifier of the DmxSource.
    pub fn cid(&self) -> &Uuid {
        &self.cid
    }

    /// Sets the ACN CID device identifier.
    pub fn set_cid(&mut self, cid: Uuid) {
        self.cid = cid;
    }

    /// Returns the ACN source name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Sets ACN source name.
    pub fn set_name(&mut self, name: &str) {
        self.name = name.to_string();
    }

    /// Returns if DmxSource is in preview mode.
    pub fn preview_mode(&self) -> bool {
        self.preview_data
    }

    /// Sets the DmxSource to preview mode.
    ///
    /// All packets will be sent with Preview_Data flag set to 1.
    pub fn set_preview_mode(&mut self, preview_mode: bool) {
        self.preview_data = preview_mode;
    }

    /// Returns the current DMX START code.
    pub fn start_code(&self) -> u8 {
        self.start_code
    }

    /// Sets the DMX START code.
    pub fn set_start_code(&mut self, start_code: u8) {
        self.start_code = start_code;
    }

    /// Sets the multicast time to live.
    pub fn set_multicast_ttl(&self, multicast_ttl: u32) -> Result<()> {
        self.socket.set_multicast_ttl_v4(multicast_ttl)
    }

    /// Returns the multicast time to live of the socket.
    pub fn multicast_ttl(&self) -> Result<u32> {
        self.socket.multicast_ttl_v4()
    }

    /// Sets if multicast loop is enabled.
    pub fn set_multicast_loop(&self, multicast_loop: bool) -> Result<()> {
        self.socket.set_multicast_loop_v4(multicast_loop)
    }

    /// Returns if multicast loop of the socket is enabled.
    pub fn multicast_loop(&self) -> Result<bool> {
        self.socket.multicast_loop_v4()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::iter;
    use std::net::Ipv4Addr;
    use net2::UdpBuilder;

    #[test]
    #[cfg_attr(rustfmt, rustfmt_skip)]
    fn test_dmx_source() {
        let cid = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        let universe = 1;
        let source_name = "SourceName";
        let priority = 150;
        let sequence = 0;
        let preview_data = false;
        let start_code = 0;
        let mut dmx_data: Vec<u8> = Vec::new();
        dmx_data.extend(iter::repeat(100).take(255));

        // Root Layer
        let mut packet = Vec::new();
        // Preamble Size
        packet.extend("\x00\x10".bytes());
        // Post-amble Size
        packet.extend("\x00\x00".bytes());
        // ACN Packet Identifier
        packet.extend("\x41\x53\x43\x2d\x45\x31\x2e\x31\x37\x00\x00\x00".bytes());
        // Flags and Length (22 + 343)
        packet.push(0b01110001);
        packet.push(0b01101101);
        // Vector
        packet.extend("\x00\x00\x00\x04".bytes());
        // CID
        packet.extend(&cid);

        // E1.31 Framing Layer
        // Flags and Length (77 + 266)
        packet.push(0b01110001);
        packet.push(0b01010111);
        // Vector
        packet.extend("\x00\x00\x00\x02".bytes());
        // Source Name
        let source_name = source_name.to_string() +
                          "\0\0\0\0\0\0\0\0\0\0" +
                          "\0\0\0\0\0\0\0\0\0\0" +
                          "\0\0\0\0\0\0\0\0\0\0" +
                          "\0\0\0\0\0\0\0\0\0\0" +
                          "\0\0\0\0\0\0\0\0\0\0" +
                          "\0\0\0\0";
        assert_eq!(source_name.len(), 64);
        packet.extend(source_name.bytes());
        // Priority
        packet.push(priority);
        // Reserved
        packet.extend("\x00\x00".bytes());
        // Sequence Number
        packet.push(sequence);
        // Options
        packet.push(0);
        // Universe
        packet.push(0);
        packet.push(1);

        // DMP Layer
        // Flags and Length (266)
        packet.push(0b01110001);
        packet.push(0b00001010);
        // Vector
        packet.push(0x02);
        // Address Type & Data Type
        packet.push(0xa1);
        // First Property Address
        packet.extend("\x00\x00".bytes());
        // Address Increment
        packet.extend("\x00\x01".bytes());
        // Property value count
        packet.push(0b1);
        packet.push(0b00000000);
        // Property values
        packet.push(start_code);
        packet.extend(&dmx_data);

        let mut source = DmxSource::with_cid(&source_name, Uuid::from_bytes(&cid).unwrap()).unwrap();
        source.set_preview_mode(preview_data);
        source.set_start_code(start_code);
        source.set_multicast_loop(true).unwrap();

        let recv_socket = UdpBuilder::new_v4().unwrap().bind("0.0.0.0:5568").unwrap();
        recv_socket.join_multicast_v4(&Ipv4Addr::new(239, 255, 0, 1), &Ipv4Addr::new(0, 0, 0, 0))
                   .unwrap();

        let mut recv_buf = [0; 1024];

        source.send_with_priority(universe, &dmx_data, priority).unwrap();
        let (amt, _) = recv_socket.recv_from(&mut recv_buf).unwrap();

        assert_eq!(&packet[..], &recv_buf[0..amt]);
    }

    #[test]
    fn test_terminate_stream() {
        let source = DmxSource::new("Source").unwrap();
        source.set_multicast_loop(true).unwrap();

        let recv_socket = UdpBuilder::new_v4().unwrap().bind("0.0.0.0:5568").unwrap();
        recv_socket
            .join_multicast_v4(&Ipv4Addr::new(239, 255, 0, 1), &Ipv4Addr::new(0, 0, 0, 0))
            .unwrap();

        let mut recv_buf = [0; 1024];

        source.terminate_stream(1).unwrap();
        for _ in 0..2 {
            recv_socket.recv_from(&mut recv_buf).unwrap();
            assert_eq!(
                match AcnRootLayerProtocol::parse(&recv_buf).unwrap().pdu.data {
                    E131RootLayerData::DataPacket(data) => data.stream_terminated,
                    _ => panic!(),
                },
                true
            )
        }
    }
}