1
#![warn(missing_docs)]
2

            
3
// Copyright 2020 sacn Developers
4
//
5
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
6
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
7
// http://opensource.org/licenses/MIT>, at your option. This file may not be
8
// copied, modified, or distributed except according to those terms.
9
//
10
// This file was modified as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
11
//
12
// Documentation of private or crate local items that effects public items, such as errors from private functions which get passed up to a
13
// public function, should be copied into the documentation of the public item so that the public facing documentation is a complete documentation
14
// of each public item without relying on referring to private items.
15
//
16

            
17
use crate::error::errors::*;
18
use crate::packet::*;
19

            
20
use std::cell::RefCell;
21
use std::cmp;
22
use std::collections::HashMap;
23
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
24
use std::sync::{Arc, Mutex, MutexGuard};
25
use std::thread;
26
use std::thread::JoinHandle;
27
use std::time::{Duration, Instant};
28

            
29
/// Socket2 used to create the underlying UDP socket that sACN is sent on.
30
use socket2::{Domain, Socket, Type};
31

            
32
/// UUID library used to handle the UUID's used in the CID fields.
33
use uuid::Uuid;
34

            
35
/// The name of the thread which runs periodically to perform various actions such as universe discovery adverts for the source.
36
const SND_UPDATE_THREAD_NAME: &str = "rust_sacn_snd_update_thread";
37

            
38
/// The default startcode used to send stream termination packets when the `SacnSource` is closed.
39
const DEFAULT_TERMINATE_START_CODE: u8 = 0;
40

            
41
/// The poll rate of the update thread.
42
/// Discovery updates are sent every `E131_UNIVERSE_DISCOVERY_INTERVAL` so the poll rate must be lower than or equal to this.
43
// const DEFAULT_POLL_PERIOD: Duration = E131_UNIVERSE_DISCOVERY_INTERVAL;
44
const DEFAULT_POLL_PERIOD: Duration = Duration::from_secs(1);
45

            
46
/// A DMX over sACN sender.
47
///
48
/// `SacnSource` is used for sending sACN packets over an IP network.
49
///
50
/// # Examples
51
///
52
/// ```no_run
53
/// // Example showing creation of a source and then sending some data.
54
/// use sacn::source::SacnSource;
55
/// use sacn::packet::ACN_SDT_MULTICAST_PORT;
56
/// use std::net::{IpAddr, SocketAddr};
57
///
58
/// let local_addr: SocketAddr = SocketAddr::new(IpAddr::V4("0.0.0.0".parse().unwrap()), ACN_SDT_MULTICAST_PORT + 1);
59
///
60
/// let mut src = SacnSource::with_ip("Source", local_addr).unwrap();
61
///
62
/// let universe: u16 = 1;                        // Universe the data is to be sent on.
63
/// let sync_uni: Option<u16> = None;             // Don't want the packet to be delayed on the receiver awaiting synchronisation.
64
/// let priority: u8 = 100;                       // The priority for the sending data, must be 1-200 inclusive,  None means use default.
65
/// let dst_ip: Option<SocketAddr> = None;        // Sending the data using IP multicast so don't have a destination IP.
66
///
67
/// src.register_universe(universe).unwrap(); // Register with the source that will be sending on the given universe.
68
///
69
/// let mut data: Vec<u8> = vec![0, 0, 0, 0, 255, 255, 128, 128]; // Some arbitrary data, must have length <= 513 (including start-code).
70
///
71
/// src.send(&[universe], &data, Some(priority), dst_ip, sync_uni).unwrap(); // Actually send the data
72
/// ```
73
///
74
/// An ANSI E1.31-2018 sACN source.
75
///
76
/// Allows sending DMX data over an IPv4 or IPv6 network using sACN.
77
#[derive(Debug)]
78
pub struct SacnSource {
79
    /// The DMX source used for actually sending the sACN packets.
80
    /// Protected by a Mutex lock to allow concurrent access between user threads and the update thread below.
81
    internal: Arc<Mutex<SacnSourceInternal>>,
82

            
83
    /// Update thread which performs actions every `DEFAULT_POLL_PERIOD` such as checking if a universe
84
    /// discovery packet should be sent.
85
    update_thread: Option<JoinHandle<()>>,
86
}
87

            
88
/// Internal sACN sender, this does most of the work however is encapsulated within `SacnSource`
89
/// to allow access by the `update_thread` which is used to manage sending periodic universe discovery packets.
90
#[derive(Debug)]
91
struct SacnSourceInternal {
92
    /// Underlying UDP socket used for sending sACN packets on the network.
93
    socket: Socket,
94

            
95
    /// The address of this `SacnSourceInternal` on the network.
96
    addr: SocketAddr,
97

            
98
    /// The unique ID of this `SacnSourceInternal`.
99
    /// It is the job of the user of the library to ensure that the cid is given on creation of the `SacnSourceInternal` is unique.
100
    cid: Uuid,
101

            
102
    /// The human readable name of this source.
103
    name: String,
104

            
105
    /// Flag which is included in sACN packets to indicate that the data shouldn't be used for live output
106
    /// (ie. on actual lighting fixtures). A receiver may or may not be compliant with this so it should not be relied
107
    /// upon in an untested environment.
108
    preview_data: bool,
109

            
110
    /// Flag which is included in sACN data packets that have a synchronisation address. It tells receivers what to do if
111
    /// synchronisation is lost, as per ANSI E1.31-2016 Section 6.2.6 (`Force_Synchronization`). If false receivers hold the
112
    /// data until synchronisation resumes, if true they may process the data without waiting for a synchronisation packet.
113
    force_synchronization: bool,
114

            
115
    /// The sequence numbers used for data packets, keeps a reference of the next sequence number to use for each universe.
116
    /// Sequence numbers are always in the range [0, 255].
117
    data_sequences: RefCell<HashMap<u16, u8>>,
118

            
119
    /// The sequence numbers used for sync packets, keeps a reference of the next sequence number to use for each universe.
120
    /// Sequence numbers are always in the range [0, 255].
121
    sync_sequences: RefCell<HashMap<u16, u8>>,
122

            
123
    /// A list of the universes registered to send by this source, used for universe discovery.
124
    /// Always sorted with lowest universe first to allow quicker usage.
125
    /// This may never contain duplicate universe values.
126
    universes: Vec<u16>,
127

            
128
    /// Flag that indicates if the `SacnSourceInternal` is running (the update thread should be triggering periodic discovery packets).
129
    running: bool,
130

            
131
    /// The time that the last universe discovery advert was send.
132
    last_discovery_advert_timestamp: Instant,
133

            
134
    /// Flag that is set to True to indicate that the source is sending periodic universe discovery packets.
135
    is_sending_discovery: bool,
136
}
137

            
138
impl SacnSource {
139
    /// Constructs a new `SacnSource` with the given name, binding to an IPv4 address on an ephemeral port.
140
    /// This generates a new CID automatically using random values.
141
    ///
142
    /// # Errors
143
    /// See [`with_cid_ip`](Self::with_cid_ip)
144
21
    pub fn new_v4(name: &str) -> Result<SacnSource> {
145
21
        let cid = Uuid::new_v4();
146
21
        SacnSource::with_cid_v4(name, cid)
147
21
    }
148

            
149
    /// Constructs a new `SacnSource` with the given name and specified CID binding to an IPv4 address.
150
    ///
151
    /// # Errors
152
    /// See [`with_cid_ip`](Self::with_cid_ip)
153
22
    pub fn with_cid_v4(name: &str, cid: Uuid) -> Result<SacnSource> {
154
22
        let ip = SocketAddr::new(
155
22
            IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
156
22
            // Use an ephemeral port. Binding the ACN port would put this socket in the receivers' `SO_REUSEPORT` group,
157
22
            // and Linux would then hand some of the unicast sACN addressed to this host to this socket, where it is never read.
158
22
            0,
159
22
        );
160
22
        SacnSource::with_cid_ip(name, cid, ip)
161
22
    }
162

            
163
    /// Constructs a new `SacnSource` with the given name, binding to an IPv6 address on an ephemeral port.
164
    /// By default this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
165
    ///
166
    /// # Errors
167
    /// See [`with_cid_ip`](Self::with_cid_ip)
168
2
    pub fn new_v6(name: &str) -> Result<SacnSource> {
169
2
        let cid = Uuid::new_v4();
170
2
        SacnSource::with_cid_v6(name, cid)
171
2
    }
172

            
173
    /// Constructs a new `SacnSource` with the given name and specified CID binding to an IPv6 address.
174
    ///
175
    /// # Errors
176
    /// See [`with_cid_ip`](Self::with_cid_ip)
177
3
    pub fn with_cid_v6(name: &str, cid: Uuid) -> Result<SacnSource> {
178
3
        let ip = SocketAddr::new(
179
3
            IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
180
3
            // Use an ephemeral port. Binding the ACN port would put this socket in the receivers' `SO_REUSEPORT` group,
181
3
            // and Linux would then hand some of the unicast sACN addressed to this host to this socket, where it is never read.
182
3
            0,
183
3
        );
184
3
        SacnSource::with_cid_ip(name, cid, ip)
185
3
    }
186

            
187
    /// Constructs a new `SacnSource` with the given name and binding to the supplied ip.
188
    ///
189
    /// Avoid binding to `ACN_SDT_MULTICAST_PORT` if a `SacnReceiver` may run on the same host. The socket would share the
190
    /// port with the receiver, and on Linux some unicast sACN sent to this host would be delivered to the source's socket
191
    /// and lost. Port 0 (an ephemeral port) is a good choice.
192
    ///
193
    /// # Errors
194
    /// See [`with_cid_ip`](Self::with_cid_ip)
195
74
    pub fn with_ip(name: &str, ip: SocketAddr) -> Result<SacnSource> {
196
74
        SacnSource::with_cid_ip(name, Uuid::new_v4(), ip)
197
74
    }
198

            
199
    /// Constructs a new `SacnSource` with the given name, cid and binding to the supplied ip.
200
    ///
201
    /// # Errors
202
    /// Io: Returned if the underlying UDP socket cannot be created and bound or if the thread used for sending periodic
203
    ///     discovery adverts fails to be created. Causes can be distinguished by looking at the error chain.
204
    ///
205
    /// `UnsupportedIpVersion`: Returned if the `SocketAddr` is not IPv4 or IPv6.
206
    ///
207
    /// `MalformedSourceName`: Returned if the given source name is longer than the maximum allowed size of `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
208
125
    pub fn with_cid_ip(name: &str, cid: Uuid, ip: SocketAddr) -> Result<SacnSource> {
209
125
        if name.len() > E131_SOURCE_NAME_MAX_LENGTH {
210
8
            return Err(SacnError::MalformedSourceName(
211
8
                "Source name provided is longer than maximum allowed".to_string(),
212
8
            ));
213
117
        }
214

            
215
117
        let trd_builder = thread::Builder::new().name(SND_UPDATE_THREAD_NAME.into());
216

            
217
117
        let internal_src = Arc::new(Mutex::new(SacnSourceInternal::with_cid_ip(name, cid, ip)?));
218

            
219
117
        let mut trd_src = internal_src.clone();
220

            
221
        let src = SacnSource {
222
117
            internal: internal_src,
223
117
            update_thread: Some(trd_builder.spawn(move || {
224
                // Stop if the source has been dropped or the mutex was poisoned by a panic elsewhere.
225
421
                while matches!(trd_src.lock().map(|s| s.running), Ok(true)) {
226
304
                    thread::sleep(DEFAULT_POLL_PERIOD);
227
                    // On error the source keeps running and tries again on the next period. With the `logging` feature the
228
                    // error is reported through the `log` crate, so the application decides whether and where it is shown.
229
304
                    if let Err(e) = perform_periodic_update(&mut trd_src) {
230
                        log_warn!("sACN source periodic update failed: {e:?}");
231
304
                    }
232
                }
233
117
            })?),
234
        };
235

            
236
117
        Ok(src)
237
125
    }
238

            
239
    /// Registers the given universes on this source in addition to already registered universes.
240
    ///
241
    /// This allows sending data to those universes or using them as synchronisation addresses as well as adding them to
242
    /// the list of universes that appear in universe discovery packets that are sent (depending on the
243
    /// `set_is_sending_discovery` flag) periodically.
244
    ///
245
    /// This is more efficient than repeated calls to `register_universe` as it means only 1 mutex unlock is required.
246
    ///
247
    /// # Arguments
248
    /// universes: The sACN universes to register for usage as data universes and/or synchronisation addresses. Note that sACN
249
    ///     universes start at 1 not 0.
250
    ///
251
    /// # Errors
252
    /// `IllegalUniverse`: Returned if a universe is outwith the range permitted by ANSI E1.31-2018.
253
    ///
254
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
255
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
256
48
    pub fn register_universes(&mut self, universes: &[u16]) -> Result<()> {
257
48
        unlock_internal_mut(&mut self.internal)?.register_universes(universes)
258
48
    }
259

            
260
    /// Registers a single universe on this source in addition to already registered universes.
261
    ///
262
    /// This allows sending data to those universes or using them as synchronisation addresses as well as adding them to
263
    /// the list of universes that appear in universe discovery packets that are sent (depending on the
264
    /// `set_is_sending_discovery` flag) periodically.
265
    ///
266
    /// If registering multiple universes see [`register_universes`](Self::register_universes).
267
    ///
268
    /// # Arguments
269
    /// universe: The sACN universe to register for usage as a data universe and/or synchronisation address. Note that sACN
270
    ///     universes start at 1 not 0.
271
    ///
272
    /// # Errors
273
    /// `IllegalUniverse`: Returned if the universe is outwith the range permitted by ANSI E1.31-2018.
274
    ///
275
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
276
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
277
61
    pub fn register_universe(&mut self, universe: u16) -> Result<()> {
278
61
        unlock_internal_mut(&mut self.internal)?.register_universe(universe)
279
61
    }
280

            
281
    /// Sends the given data to the given universes with the given priority, synchronisation address (universe) and destination ip.
282
    ///
283
    /// # Arguments
284
    ///
285
    /// universe:     The sACN universes that the data should be set on, the data will be split over these universes with each `UNIVERSE_CHANNEL_CAPACITY`
286
    ///                 sized chunk sent to the next universe.
287
    ///
288
    /// data:         The data that should be sent, must have a length greater than 0.
289
    ///
290
    /// priority:     The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`),
291
    ///                 if a value of None is provided then the default of `E131_DEFAULT_PRIORITY` (`const.E131_DEFAULT_PRIORITY.packet`) is used.
292
    ///
293
    /// `dst_ip`:       The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
294
    ///
295
    /// `sync_address`: The address to use for synchronisation, must be a valid universe, None indicates no synchronisation. If synchronisation is required a
296
    ///                 reasonable default address to use is the first universe that this data is being sent to.
297
    ///                 It doesn't need to be registered, so a universe used only for synchronisation isn't advertised in
298
    ///                 universe discovery.
299
    ///
300
    /// As per ANSI E1.31-2018 Section 6.6.1 this method shouldn't be called at a higher refresher rate than specified in ANSI E1.11 \[DMX\] unless
301
    ///     configured by the user to do so in an environment which doesn't contain any E1.31 to DMX512-A converters.
302
    ///
303
    /// Note as per ANSI-E1.31-2018 Appendix B.1 it is recommended to have a small delay before sending the follow up sync packet.
304
    ///
305
    /// # Errors
306
    /// `SenderAlreadyTerminated`: Returned if this method is called on an `SacnReceiverInternal` that has already terminated.
307
    ///
308
    /// `InvalidInput`: Returned if the data array has length 0 or if an insufficient number of universes for the given data are provided (each universe takes 513 bytes of data).
309
    ///
310
    /// `InvalidPriority`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
311
    ///
312
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range as specified by ANSI E1.31-2018 Section 6.2.7.
313
    ///
314
    /// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
315
    ///
316
    /// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe (`packet::UNIVERSE_CHANNEL_CAPACITY`).
317
    ///
318
    /// Io: Returned if the data fails to be sent on the socket, see `send_to(fn.send_to.Socket)`.
319
    ///
320
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
321
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
322
3311
    pub fn send(
323
3311
        &mut self,
324
3311
        universes: &[u16],
325
3311
        data: &[u8],
326
3311
        priority: Option<u8>,
327
3311
        dst_ip: Option<SocketAddr>,
328
3311
        synchronisation_addr: Option<u16>,
329
3311
    ) -> Result<()> {
330
3311
        unlock_internal_mut(&mut self.internal)?.send(
331
3311
            universes,
332
3311
            data,
333
3311
            priority,
334
3311
            dst_ip,
335
3311
            synchronisation_addr,
336
        )
337
3311
    }
338

            
339
    /// Sends a synchronisation packet to trigger the sending of packets waiting to be sent together.
340
    ///
341
    /// A common pattern would be to use the send method to send data to all the universes that should be synchronised using a
342
    /// chosen synchronisation universe then wait for a small time as per the recommendation in ANSI-E1.31-2018 Appendix B.1 and
343
    /// then send a synchronisation packet with the address of the synchronisation universe chosen to trigger the packets.
344
    ///
345
    /// # Arguments
346
    /// universe: The universe of this synchronisation packet.
347
    /// `dst_ip`:   The destination IP address for this packet or None if it should be sent using multicast.
348
    ///
349
    /// The universe doesn't need to be registered: a synchronisation universe carries no data, so it is left out of universe discovery.
350
    ///
351
    /// # Errors
352
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
353
    ///
354
    /// Io: Returned if the packet fails to be sent using the underlying network socket.
355
    ///
356
    /// `SacnParsePackError`: Returned if the sync packet fails to be packed.
357
    ///
358
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
359
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
360
3021
    pub fn send_sync_packet(&mut self, universe: u16, dst_ip: Option<SocketAddr>) -> Result<()> {
361
3021
        unlock_internal_mut(&mut self.internal)?.send_sync_packet(universe, dst_ip)
362
3021
    }
363

            
364
    /// Terminates sending on the given universe.
365
    ///
366
    /// # Errors:
367
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
368
    ///
369
    /// `UniverseNotRegistered`: Returned if the universe is not registered on this source.
370
    ///
371
    /// Io: Returned if the termination packets fail to be sent on the socket.
372
    ///
373
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
374
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
375
5
    pub fn terminate_stream(&mut self, universe: u16, start_code: u8) -> Result<()> {
376
5
        unlock_internal_mut(&mut self.internal)?.terminate_stream(universe, start_code)
377
5
    }
378

            
379
    /// Terminates sending on the given universe, sending the termination packets to the given unicast destinations.
380
    ///
381
    /// `terminate_stream` sends the termination packets only to the universe's multicast group, so a receiver that was
382
    /// sent the universe's data by unicast and hasn't joined that group never sees them. It then only notices the
383
    /// source has gone after the network data loss timeout. Pass the same destinations that were given to `send` here
384
    /// so those receivers are told straight away.
385
    ///
386
    /// The `E131_TERMINATE_STREAM_PACKET_COUNT` termination packets are sent to each destination in turn, then the
387
    /// universe is deregistered. If `dst_ips` is empty this behaves exactly like `terminate_stream` (multicast).
388
    ///
389
    /// # Arguments
390
    /// universe: The universe that is being terminated.
391
    ///
392
    /// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
393
    ///
394
    /// `dst_ips`: The unicast destinations to send the termination packets to.
395
    ///
396
    /// # Errors:
397
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
398
    ///
399
    /// `UniverseNotRegistered`: Returned if the universe is not registered on this source.
400
    ///
401
    /// Io: Returned if the termination packets fail to be sent on the socket. The packets are still sent to the
402
    /// remaining destinations and the universe is still deregistered; the first error is returned.
403
    ///
404
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
405
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
406
1
    pub fn terminate_stream_to(
407
1
        &mut self,
408
1
        universe: u16,
409
1
        start_code: u8,
410
1
        dst_ips: &[SocketAddr],
411
1
    ) -> Result<()> {
412
1
        unlock_internal_mut(&mut self.internal)?.terminate_stream_to(universe, start_code, dst_ips)
413
1
    }
414

            
415
    /// Returns the ACN CID device identifier of the `SacnSourceInternal`.
416
    ///
417
    /// # Errors
418
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
419
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
420
3
    pub fn cid(&self) -> Result<Uuid> {
421
3
        Ok(*unlock_internal(&self.internal)?.cid())
422
3
    }
423

            
424
    /// Sets the ACN CID device identifier.
425
    ///
426
    /// # Arguments
427
    /// cid: The new CID identifier for this source. It is left to the user to ensure that this is always unique within the network the source is in.
428
    ///
429
    /// # Errors
430
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
431
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
432
1
    pub fn set_cid(&mut self, cid: Uuid) -> Result<()> {
433
1
        unlock_internal_mut(&mut self.internal)?.set_cid(cid);
434
1
        Ok(())
435
1
    }
436

            
437
    /// Returns the ACN source name.
438
    ///
439
    /// # Errors
440
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
441
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
442
4
    pub fn name(&self) -> Result<String> {
443
4
        Ok(unlock_internal(&self.internal)?.name().into())
444
4
    }
445

            
446
    /// Sets ACN source name.
447
    ///
448
    /// # Argument
449
    /// name: The new name for the source, it is left to the user to ensure this is unique within the sACN network.
450
    ///
451
    /// # Errors
452
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
453
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
454
    ///
455
    /// `MalformedSourceName`: Returned to indicate that the given source name is longer than the maximum allowed as per `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
456
3
    pub fn set_name(&mut self, name: &str) -> Result<()> {
457
3
        unlock_internal_mut(&mut self.internal)?.set_name(name)
458
3
    }
459

            
460
    /// Returns true if `SacnSourceInternal` is in preview mode, false if not.
461
    ///
462
    /// For details of `preview_mode` see [`set_preview_mode`](Self::set_preview_mode).
463
    ///
464
    /// # Errors
465
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
466
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
467
2
    pub fn preview_mode(&self) -> Result<bool> {
468
2
        Ok(unlock_internal(&self.internal)?.preview_mode())
469
2
    }
470

            
471
    /// Sets the value of the `Preview_Data` flag in packets from this `SacnSource`.
472
    ///
473
    /// # Arguments
474
    /// `preview_mode`: If true then all data packets from this `SacnSource` will have the `Preview_Data` flag set to true indicating that the data is not
475
    ///     for live output. If false then the flag will be set to false.
476
    ///
477
    /// # Errors
478
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
479
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
480
5
    pub fn set_preview_mode(&mut self, preview_mode: bool) -> Result<()> {
481
5
        unlock_internal_mut(&mut self.internal)?.set_preview_mode(preview_mode);
482
5
        Ok(())
483
5
    }
484

            
485
    /// Returns the value of the `Force_Synchronization` option set on data packets sent by this `SacnSource`.
486
    ///
487
    /// For details see [`set_force_synchronization`](Self::set_force_synchronization).
488
    ///
489
    /// # Errors
490
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
491
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
492
3
    pub fn force_synchronization(&self) -> Result<bool> {
493
3
        Ok(unlock_internal(&self.internal)?.force_synchronization)
494
3
    }
495

            
496
    /// Sets the `Force_Synchronization` option on data packets sent by this `SacnSource`, as per ANSI E1.31-2016 Section 6.2.6.
497
    ///
498
    /// The option tells receivers what to do with synchronised data (data sent with a synchronisation address) if synchronisation is lost,
499
    /// meaning no synchronisation packet has been received on that address within `E131_NETWORK_DATA_LOSS_TIMEOUT`:
500
    /// - false (the default): receivers hold the data until synchronisation resumes.
501
    /// - true: receivers may process the data straight away without waiting for a synchronisation packet.
502
    ///
503
    /// # Errors
504
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
505
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
506
2
    pub fn set_force_synchronization(&mut self, force_synchronization: bool) -> Result<()> {
507
2
        unlock_internal_mut(&mut self.internal)?.force_synchronization = force_synchronization;
508
2
        Ok(())
509
2
    }
510

            
511
    /// Sets the `is_sending_discovery` flag to the given value.
512
    ///
513
    /// # Arguments
514
    /// val: The new value for the `is_sending_discovery` flag, if true then source will send periodic universe discovery packets
515
    /// and if false it won't.
516
8
    pub fn set_is_sending_discovery(&mut self, val: bool) {
517
8
        self.internal.lock().unwrap().set_is_sending_discovery(val);
518
8
    }
519

            
520
    /// Returns the multicast time to live of the socket (the multicast hop limit for an IPv6 source).
521
4
    pub fn multicast_ttl(&self) -> Result<u32> {
522
4
        unlock_internal(&self.internal)?.multicast_ttl()
523
4
    }
524

            
525
    /// Sets the multicast time to live (the multicast hop limit for an IPv6 source).
526
    ///
527
    /// # Arguments
528
    /// `multicast_ttl`: The new time to live value for network packets sent using multicast.
529
    ///
530
    /// # Errors
531
    /// Io: Returned if the multicast TTL fails to be set on the underlying socket.
532
    ///
533
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
534
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
535
4
    pub fn set_multicast_ttl(&mut self, multicast_ttl: u32) -> Result<()> {
536
4
        unlock_internal_mut(&mut self.internal)?.set_multicast_ttl(multicast_ttl)
537
4
    }
538

            
539
    /// Returns the current Time To Live for unicast packets send by this source (the unicast hop limit for an IPv6 source).
540
    ///
541
    /// # Errors
542
    /// Io: Returned if the TTL cannot be retrieved from the underlying socket.
543
    ///
544
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
545
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
546
4
    pub fn ttl(&self) -> Result<u32> {
547
4
        unlock_internal(&self.internal)?.ttl()
548
4
    }
549

            
550
    /// Sets the Time To Live for packets sent by this source (the unicast hop limit for an IPv6 source).
551
    ///
552
    /// # Arguments
553
    /// ttl: The new time to live value for new packets.
554
    ///
555
    /// # Errors
556
    /// Io: Returned if the TTL value cannot be changed.
557
    ///
558
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
559
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
560
4
    pub fn set_ttl(&mut self, ttl: u32) -> Result<()> {
561
4
        unlock_internal_mut(&mut self.internal)?.set_ttl(ttl)
562
4
    }
563

            
564
    /// Sets if multicast loop is enabled for an IPv4 source. Returns an error on an IPv6 source; use `set_multicast_loop` instead.
565
    ///
566
    /// # Arguments:
567
    /// `multicast_loop`: If true then multicast loop is enabled, if false it is not.
568
    ///
569
    /// # Errors
570
    /// Io: Returned if the `set_multicast_loop` option fails to be set on the socket.
571
    ///
572
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
573
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
574
10
    pub fn set_multicast_loop_v4(&mut self, multicast_loop: bool) -> Result<()> {
575
10
        unlock_internal_mut(&mut self.internal)?.set_multicast_loop_v4(multicast_loop)
576
10
    }
577

            
578
    /// Sets if multicast loop is enabled, for either an IPv4 or an IPv6 source.
579
    ///
580
    /// Unlike `set_multicast_loop_v4`, this works on IPv6 sources too.
581
    ///
582
    /// # Arguments:
583
    /// `multicast_loop`: If true then multicast loop is enabled, if false it is not.
584
    ///
585
    /// # Errors
586
    /// Io: Returned if the multicast loop option fails to be set on the socket.
587
    ///
588
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
589
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
590
6
    pub fn set_multicast_loop(&mut self, multicast_loop: bool) -> Result<()> {
591
6
        unlock_internal_mut(&mut self.internal)?.set_multicast_loop(multicast_loop)
592
6
    }
593

            
594
    /// Returns true if multicast loop is enabled, false if not.
595
    ///
596
    /// # Errors
597
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
598
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
599
8
    pub fn multicast_loop(&self) -> Result<bool> {
600
8
        unlock_internal(&self.internal)?.multicast_loop()
601
8
    }
602

            
603
    /// Returns the universes currently registered on this source.
604
    ///
605
    /// # Errors
606
    /// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
607
    /// a panic while accessing causing the source to be left in a potentially inconsistent state.
608
4
    pub fn universes(&self) -> Result<Vec<u16>> {
609
4
        Ok(unlock_internal(&self.internal)?.universes())
610
4
    }
611
}
612

            
613
/// By implementing the Drop trait for `SacnSource` it means that the user doesn't have to explicitly clean up the source
614
/// and if it goes out of reference it will clean itself up and send the required termination packets etc.
615
impl Drop for SacnSource {
616
117
    fn drop(&mut self) {
617
        // The guard is dropped at the end of this statement so the update thread can see `running` change.
618
117
        if let Ok(mut i) = unlock_internal_mut(&mut self.internal) {
619
117
            i.running = false;
620
        } else {
621
            // As drop isn't always explicitly called and cannot return an error the error can't be returned. Memory safety is
622
            // maintained and this prevents causing a panic!.
623
            log_warn!(
624
                "sACN source dropped with a poisoned mutex; termination packets were not sent"
625
            );
626
            return;
627
        }
628

            
629
117
        if let Some(thread) = self.update_thread.take() {
630
            // Internal is accessed twice separately, this allows the discovery thread to interleave between running being set to false speeding up termination.
631
117
            if let Ok(mut i) = unlock_internal_mut(&mut self.internal) {
632
                // For same reasons as above a potential error can't be returned and a 'best attempt' is used to clean up.
633
117
                if let Err(e) = i.terminate(DEFAULT_TERMINATE_START_CODE) {
634
                    log_warn!(
635
                        "sACN source failed to send termination packets while being dropped: {e:?}"
636
                    );
637
117
                }
638
            } else {
639
                log_warn!(
640
                    "sACN source dropped with a poisoned mutex; termination packets were not sent"
641
                );
642
                // As drop isn't always explicitly called and cannot return an error the error is ignored. Memory safety is maintain and this prevents causing a panic!.
643
            };
644

            
645
            // The update thread only panics if the mutex was poisoned. Panicking here as well would abort the
646
            // process if the source is being dropped while unwinding, so the result is ignored.
647
117
            if thread.join().is_err() {
648
                log_warn!("sACN source update thread panicked");
649
117
            }
650
        }
651
117
    }
652
}
653

            
654
impl SacnSourceInternal {
655
    /// Constructs a new `SacnSourceInternal` with DMX START code set to 0 with specified CID and binding IP address.
656
    ///
657
    /// By default for an IPv6 address this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
658
    /// By default the TTL for ipv4 packets is 1 to keep them within the local network.
659
    ///
660
    /// # Arguments:
661
    /// name: The human readable name for this sacn source.
662
    /// cid:  The UUID for this source.
663
    /// ip:   The address that this source should bind to.
664
    ///
665
    /// # Errors
666
    /// Io: Returned if the underlying socket cannot be created or the IP cannot be bound to the underlying socket. See (`UdpBuilder::new_v4`)[`fn.new_v4.UdpBuilder`], (`UdpBuilder::new_v6`)[`fn.new_v6.UdpBuilder`] and (`Socket::bind`)[fn.bind.Socket2].
667
    ///
668
    /// `UnsupportedIpVersion`: Returned if the `SockAddr` is not IPv4 or IPv6.
669
118
    fn with_cid_ip(name: &str, cid: Uuid, ip: SocketAddr) -> Result<SacnSourceInternal> {
670
118
        let socket = if ip.is_ipv4() {
671
95
            Socket::new(Domain::IPV4, Type::DGRAM, None)?
672
23
        } else if ip.is_ipv6() {
673
23
            Socket::new(Domain::IPV6, Type::DGRAM, None)?
674
        } else {
675
            return Err(SacnError::UnsupportedIpVersion(
676
                "Address to create SacnSource is not IPv4 or IPv6".to_string(),
677
            ));
678
        };
679

            
680
        // Multiple different processes might want to send to the sACN stream so therefore need to allow re-using the ACN port.
681
        // Set reuse port is only supported on linux.
682
        #[cfg(target_os = "linux")]
683
118
        socket.set_reuse_port(true)?;
684

            
685
        // Set reuse address supported on linux and windows.
686
118
        socket.set_reuse_address(true)?;
687
118
        socket.bind(&ip.into())?;
688

            
689
118
        let ds = SacnSourceInternal {
690
118
            socket,
691
118
            addr: ip,
692
118
            cid,
693
118
            name: name.to_string(),
694
118
            preview_data: false,
695
118
            force_synchronization: false,
696
118
            data_sequences: RefCell::new(HashMap::new()),
697
118
            sync_sequences: RefCell::new(HashMap::new()),
698
118
            universes: Vec::new(),
699
118
            running: true,
700
118
            last_discovery_advert_timestamp: Instant::now(),
701
118
            is_sending_discovery: true,
702
118
        };
703

            
704
118
        Ok(ds)
705
118
    }
706

            
707
    /// Sets the `is_sending_discovery` flag to the given value.
708
    ///
709
    /// If `is_sending_discovery` is set to false then no discovery adverts for this source
710
    /// will be sent otherwise (and by default) they will be sent every `UNIVERSE_DISCOVERY_INTERVAL`.
711
    ///
712
    /// # Arguments:
713
    /// val: The new value of the `is_sending_discovery` flag.
714
8
    fn set_is_sending_discovery(&mut self, val: bool) {
715
8
        self.is_sending_discovery = val;
716
8
    }
717

            
718
    /// Registers the given array of universes with this source.
719
    ///
720
    /// Any universes already registered won't be re-registered and will have no effect.
721
    ///
722
    /// # Arguments:
723
    /// universes: The sACN universe to register. Note that sACN universes start at 1 not 0.
724
    ///
725
    /// # Errors
726
    /// See `register_universe(fn.register_universe.source)` for more details.
727
49
    fn register_universes(&mut self, universes: &[u16]) -> Result<()> {
728
49
        for u in universes {
729
1288
            self.register_universe(*u)?;
730
        }
731
46
        Ok(())
732
49
    }
733

            
734
    /// Registers the given universe for sending with this source.
735
    ///
736
    /// If a universe is already registered then this method has no effect.
737
    ///
738
    /// # Errors
739
    /// `IllegalUniverse`: Returned if the universe can't carry data, see (`is_data_universe_in_range`)[`fn.is_data_universe_in_range.packet`].
740
1349
    fn register_universe(&mut self, universe: u16) -> Result<()> {
741
1349
        is_data_universe_in_range(universe)?;
742

            
743
1346
        if self.universes.is_empty() {
744
93
            self.universes.push(universe);
745
1253
        } else if let Err(i) = self.universes.binary_search(&universe) {
746
            // Value not found, i is the position it should be inserted
747
1249
            self.universes.insert(i, universe);
748
4
        } else {
749
4
            // If value found then don't insert to avoid duplicates.
750
4
        }
751

            
752
1346
        Ok(())
753
1349
    }
754

            
755
    /// De-registers the given universe for sending with this source.
756
    ///
757
    /// # Errors
758
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range, see [`is_universe_in_range`](crate::packet::is_universe_in_range).
759
    ///
760
    /// `UniverseNotFound`: Returned if the given universe was never registered originally.
761
1342
    fn deregister_universe(&mut self, universe: u16) -> Result<()> {
762
1342
        is_universe_in_range(universe)?;
763

            
764
1342
        match self.universes.binary_search(&universe) {
765
            Err(_i) => {
766
                // Value not found
767
                Err(SacnError::UniverseNotFound(universe))
768
            }
769
            Ok(i) => {
770
                // Value found, i is index.
771
1342
                self.universes.remove(i);
772
1342
                Ok(())
773
            }
774
        }
775
1342
    }
776

            
777
    /// Checks if the given universe is a valid universe to send on (within allowed range) and that it is registered with this `SacnSourceInternal`.
778
    ///
779
    /// # Errors
780
    /// `IllegalUniverse`: Returned if the universe can't carry data, see (`is_data_universe_in_range`)[`fn.is_data_universe_in_range.packet`].
781
    ///
782
    /// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
783
7342
    fn universe_allowed(&self, u: &u16) -> Result<()> {
784
7342
        is_data_universe_in_range(*u)?;
785

            
786
7341
        if !self.universes.contains(u) {
787
2
            return Err(SacnError::UniverseNotRegistered(*u));
788
7339
        }
789

            
790
7339
        Ok(())
791
7342
    }
792

            
793
    /// Sends the given data to the given universes with the given priority, synchronisation address (universe) and destination ip.
794
    ///
795
    /// # Arguments
796
    ///
797
    /// universe:     The sACN universes that the data should be set on, the data will be split over these universes with each `UNIVERSE_CHANNEL_CAPACITY`
798
    ///                 sized chunk sent to the next universe.
799
    ///
800
    /// data:         The data that should be sent, must have a length greater than 0.
801
    ///
802
    /// priority:     The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`),
803
    ///                 if a value of None is provided then the default of `E131_DEFAULT_PRIORITY` (`const.E131_DEFAULT_PRIORITY.packet`) is used.
804
    ///
805
    /// `dst_ip`:       The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
806
    ///
807
    /// `sync_address`: The address to use for synchronisation, must be a valid universe, None indicates no synchronisation. If synchronisation is required a
808
    ///                 reasonable default address to use is the first universe that this data is being sent to.
809
    ///                 It doesn't need to be registered, so a universe used only for synchronisation isn't advertised in
810
    ///                 universe discovery.
811
    ///
812
    /// As per ANSI E1.31-2018 Section 6.6.1 this method shouldn't be called at a higher refresher rate than specified in ANSI E1.11 \[DMX\] unless
813
    ///     configured by the user to do so in an environment which doesn't contain any E1.31 to DMX512-A converters.
814
    ///
815
    /// Note as per ANSI-E1.31-2018 Appendix B.1 it is recommended to have a small delay before sending the follow up sync packet.
816
    ///
817
    /// # Errors
818
    /// `SenderAlreadyTerminated`: Returned if this method is called on an `SacnReceiverInternal` that has already terminated.
819
    ///
820
    /// `InvalidInput`: Returned if the data array has length 0 or if an insufficient number of universes for the given data are provided (each universe takes 513 bytes of data).
821
    ///
822
    /// `InvalidPriority`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
823
    ///
824
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range as specified by ANSI E1.31-2018 Section 6.2.7.
825
    ///
826
    /// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
827
    ///
828
    /// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe (`packet::UNIVERSE_CHANNEL_CAPACITY`).
829
    ///
830
    /// Io: Returned if the data fails to be sent on the socket, see `send_to(fn.send_to.Socket)`.
831
3311
    fn send(
832
3311
        &self,
833
3311
        universes: &[u16],
834
3311
        data: &[u8],
835
3311
        priority: Option<u8>,
836
3311
        dst_ip: Option<SocketAddr>,
837
3311
        synchronisation_addr: Option<u16>,
838
3311
    ) -> Result<()> {
839
3311
        if !self.running {
840
            // Indicates that this sender has been terminated.
841
            return Err(SacnError::SenderAlreadyTerminated(
842
                "Attempted to send".to_string(),
843
            ));
844
3311
        }
845

            
846
3311
        if data.is_empty() {
847
1
            return Err(SacnError::DataArrayEmpty());
848
3310
        }
849

            
850
        // Check all the given universes are valid before doing any action.
851
        // This prevents leaving the source in an inconsistent state if later a universe is found to be invalid.
852
3310
        for u in universes {
853
3320
            self.universe_allowed(u)?;
854
        }
855

            
856
        // Check that the synchronisation universe is a valid universe. It doesn't need to be registered: a synchronisation
857
        // universe carries no data, so it isn't advertised in universe discovery.
858
3308
        if let Some(sync_addr) = synchronisation_addr {
859
1486
            is_data_universe_in_range(sync_addr)
860
2
                .map_err(|_e| SacnError::IllegalSyncUniverse(sync_addr))?;
861
1822
        }
862

            
863
        // + 1 as there must be at least 1 universe required as the data isn't empty then additional universes for any more.
864
        let required_universes =
865
3306
            (data.len() as f64 / UNIVERSE_CHANNEL_CAPACITY as f64).ceil() as usize;
866

            
867
3306
        if universes.len() < required_universes {
868
            return Err(SacnError::UniverseListEmpty());
869
3306
        }
870

            
871
3306
        for (i, &universe) in universes.iter().enumerate().take(required_universes) {
872
3316
            let start_index = i * UNIVERSE_CHANNEL_CAPACITY;
873
            // Safety check to make sure that the end index doesn't exceed the data length
874
3316
            let end_index = cmp::min((i + 1) * UNIVERSE_CHANNEL_CAPACITY, data.len());
875

            
876
3316
            self.send_universe(
877
3316
                universe,
878
3316
                &data[start_index..end_index],
879
3316
                priority.unwrap_or(E131_DEFAULT_PRIORITY),
880
3316
                &dst_ip,
881
3316
                synchronisation_addr.unwrap_or(NO_SYNC_UNIVERSE),
882
3316
            )?;
883
        }
884

            
885
3305
        Ok(())
886
3311
    }
887

            
888
    /// Sends the given data to the given universe with the given priority, synchronisation address (universe) and destination ip.
889
    ///
890
    /// # Arguments
891
    /// universe:     The sACN universe that the data should be set on.
892
    ///
893
    /// data:         The data that should be sent, must be less than or equal in length to `UNIVERSE_CHANNEL_CAPACITY(const.UNIVERSE_CHANNEL_CAPACITY.packet)`.
894
    ///
895
    /// priority:     The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`), default `E131_DEFAULT_PRIORITY`.
896
    ///
897
    /// `dst_ip`:       The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
898
    ///
899
    /// `sync_address`: The address to use for synchronisation, must be a valid universe, 0 indicates no synchronisation.
900
    ///
901
    /// # Errors
902
    /// `InvalidInput`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
903
    ///
904
    /// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe.
905
    ///
906
    /// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
907
    ///                     see (`universe_to_ipv4_multicast_addr`)[`fn.universe_to_ipv4_multicast_addr.packet`] and (`universe_to_ipv6_multicast_addr`)[`fn.universe_to_ipv6_multicast_addr.packet`].
908
    ///
909
    /// Io: Returned if the data fails to be sent on the socket, see `send_to(fn.send_to.Socket)`.
910
3316
    fn send_universe(
911
3316
        &self,
912
3316
        universe: u16,
913
3316
        data: &[u8],
914
3316
        priority: u8,
915
3316
        dst_ip: &Option<SocketAddr>,
916
3316
        sync_address: u16,
917
3316
    ) -> Result<()> {
918
3316
        if priority > E131_MAX_PRIORITY {
919
1
            return Err(SacnError::InvalidPriority(priority));
920
3315
        }
921

            
922
3315
        if data.len() > UNIVERSE_CHANNEL_CAPACITY {
923
            return Err(SacnError::ExceedUniverseCapacity(data.len()));
924
3315
        }
925

            
926
3315
        let mut sequence = match self.data_sequences.borrow().get(&universe) {
927
3223
            Some(s) => *s,
928
92
            None => STARTING_SEQUENCE_NUMBER,
929
        };
930

            
931
3315
        let packet = AcnRootLayerProtocol {
932
3315
            pdu: E131RootLayer {
933
3315
                cid: self.cid,
934
3315
                data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
935
3315
                    source_name: self.name.as_str().into(),
936
3315
                    priority,
937
3315
                    synchronization_address: sync_address,
938
3315
                    sequence_number: sequence,
939
3315
                    preview_data: self.preview_data,
940
3315
                    stream_terminated: false,
941
3315
                    force_synchronization: self.force_synchronization,
942
3315
                    universe,
943
3315
                    data: DataPacketDmpLayer {
944
3315
                        property_values: {
945
3315
                            let mut property_values = Vec::with_capacity(data.len());
946
3315
                            property_values.extend(data);
947
3315
                            property_values.into()
948
3315
                        },
949
3315
                    },
950
3315
                }),
951
3315
            },
952
3315
        };
953

            
954
3315
        log_trace!(
955
            "Sending sACN data packet: universe {universe}, sequence {sequence}, priority {priority}, sync address {sync_address}, {} bytes, destination {}",
956
            data.len(),
957
            dst_ip.map_or_else(|| "multicast".to_string(), |ip| ip.to_string())
958
        );
959

            
960
3315
        if dst_ip.is_some() {
961
16
            self.socket
962
16
                .send_to(&packet.pack_alloc().unwrap(), &dst_ip.unwrap().into())
963
                .map_err(|e| {
964
                    std::io::Error::new(e.kind(), "Failed to send data unicast on socket")
965
                })?;
966
        } else {
967
3299
            let dst = if self.addr.is_ipv6() {
968
751
                universe_to_ipv6_multicast_addr(universe)?
969
            } else {
970
2548
                universe_to_ipv4_multicast_addr(universe)?
971
            };
972

            
973
3299
            self.socket
974
3299
                .send_to(&packet.pack_alloc().unwrap(), &dst)
975
                .map_err(|e| {
976
                    std::io::Error::new(e.kind(), "Failed to send data multicast on socket")
977
                })?;
978
        }
979

            
980
3315
        if sequence == 255 {
981
10
            sequence = 0;
982
        } else {
983
3305
            sequence += 1;
984
        }
985
3315
        self.data_sequences.borrow_mut().insert(universe, sequence);
986
3315
        Ok(())
987
3316
    }
988

            
989
    /// Sends a synchronisation packet to trigger the sending of packets waiting to be sent together.
990
    ///
991
    /// A common pattern would be to use the send method to send data to all the universes that should be synchronised using a
992
    /// chosen synchronisation universe then wait for a small time as per the recommendation in ANSI-E1.31-2018 Appendix B.1 and
993
    /// then send a synchronisation packet with the address of the synchronisation universe chosen to trigger the packets.
994
    ///
995
    /// # Arguments
996
    /// universe: The universe of this synchronisation packet.
997
    /// `dst_ip`:   The destination IP address for this packet or None if it should be sent using multicast.
998
    ///
999
    /// The universe doesn't need to be registered: a synchronisation universe carries no data, so it is left out of universe discovery.
    ///
    /// # Errors
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
    ///
    /// Io: Returned if the packet fails to be sent using the underlying network socket.
    ///
    /// `SacnParsePackError`: Returned if the sync packet fails to be packed.
3021
    fn send_sync_packet(&self, universe: u16, dst_ip: Option<SocketAddr>) -> Result<()> {
3021
        is_data_universe_in_range(universe)?;
3019
        let ip = if let Some(dst) = dst_ip {
5
            dst.into()
3014
        } else if self.addr.is_ipv6() {
374
            universe_to_ipv6_multicast_addr(universe)?
        } else {
2640
            universe_to_ipv4_multicast_addr(universe)?
        };
3019
        let mut sequence = match self.sync_sequences.borrow().get(&universe) {
2984
            Some(s) => *s,
35
            None => STARTING_SEQUENCE_NUMBER,
        };
3019
        let packet = AcnRootLayerProtocol {
3019
            pdu: E131RootLayer {
3019
                cid: self.cid,
3019
                data: E131RootLayerData::SynchronizationPacket(SynchronizationPacketFramingLayer {
3019
                    sequence_number: sequence,
3019
                    synchronization_address: universe,
3019
                }),
3019
            },
3019
        };
3019
        log_trace!("Sending sACN sync packet: sync address {universe}, sequence {sequence}");
3019
        self.socket
3019
            .send_to(&packet.pack_alloc()?, &ip)
            .map_err(|e| std::io::Error::new(e.kind(), "Failed to send sync packet on socket"))?;
3019
        if sequence == 255 {
7
            sequence = 0;
        } else {
3012
            sequence += 1;
        }
3019
        self.sync_sequences.borrow_mut().insert(universe, sequence);
3019
        Ok(())
3021
    }
    /// Sends a stream termination packet for the given universe.
    ///
    /// In normal usage this method would be called three times to send three packets for termination as per
    ///     ANSI E1.31-2018 Section 6.2.6, `Stream_Terminated`: Bit 6.
    ///
    /// # Arguments
    /// universe: The universe of this synchronisation packet.
    /// `dst_ip`:   The destination IP address for this packet or None if it should be sent using multicast.
    ///
    /// # Errors
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
    ///
    /// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
    ///
    /// Io: Returned if the termination packets fail to be sent on the underlying socket.
4021
    fn send_terminate_stream_pkt(
4021
        &self,
4021
        universe: u16,
4021
        dst_ip: Option<SocketAddr>,
4021
        start_code: u8,
4021
    ) -> Result<()> {
4021
        self.universe_allowed(&universe)?;
4020
        let ip = match dst_ip {
3
            Some(x) => x.into(),
            None => {
4017
                if self.addr.is_ipv6() {
1905
                    universe_to_ipv6_multicast_addr(universe)?
                } else {
2112
                    universe_to_ipv4_multicast_addr(universe)?
                }
            }
        };
4020
        let mut sequence = match self.data_sequences.borrow_mut().remove(&universe) {
2770
            Some(s) => s,
1250
            None => STARTING_SEQUENCE_NUMBER,
        };
4020
        let packet = AcnRootLayerProtocol {
4020
            pdu: E131RootLayer {
4020
                cid: self.cid,
4020
                data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
4020
                    source_name: self.name.as_str().into(),
4020
                    priority: 100,
4020
                    synchronization_address: 0,
4020
                    sequence_number: sequence,
4020
                    preview_data: self.preview_data,
4020
                    stream_terminated: true,
4020
                    force_synchronization: false,
4020
                    universe,
4020
                    data: DataPacketDmpLayer {
4020
                        property_values: vec![start_code].into(),
4020
                    },
4020
                }),
4020
            },
4020
        };
4020
        let res = &packet.pack_alloc().unwrap();
4020
        log_trace!(
            "Sending sACN stream termination packet: universe {universe}, sequence {sequence}"
        );
4020
        self.socket.send_to(res, &ip)?;
4017
        if sequence == 255 {
            sequence = 0;
        } else {
4017
            sequence += 1;
        }
4017
        self.data_sequences.borrow_mut().insert(universe, sequence);
4017
        Ok(())
4021
    }
    /// Terminates a universe stream.
    ///
    /// Terminates a stream to the specified universe by sending packets with the `Stream_Terminated` flag set to 1.
    /// Number of packets sent as per section 6.2.6 , `Stream_Terminated`: Bit 6 of ANSI E1.31-2018.
    ///
    /// Arguments:
    /// universe: The universe that is being terminated.
    /// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
    ///
    /// # Errors:
    /// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
    ///
    /// `UniverseNotRegistered`: Returned if the universe is not registered on this source.
    ///
    /// Io: Returned if the termination packets fail to be sent on the socket.
1342
    fn terminate_stream(&mut self, universe: u16, start_code: u8) -> Result<()> {
1342
        for _ in 0..E131_TERMINATE_STREAM_PACKET_COUNT {
4018
            self.send_terminate_stream_pkt(universe, None, start_code)?;
        }
1338
        self.deregister_universe(universe)?;
1338
        Ok(())
1342
    }
    /// Terminates a universe stream, sending the termination packets to each of the given unicast destinations.
    ///
    /// See (`SacnSource::terminate_stream_to`)[`SacnSource::terminate_stream_to`].
1
    fn terminate_stream_to(
1
        &mut self,
1
        universe: u16,
1
        start_code: u8,
1
        dst_ips: &[SocketAddr],
1
    ) -> Result<()> {
1
        if dst_ips.is_empty() {
            return self.terminate_stream(universe, start_code);
1
        }
        // Check before sending anything so that an unregistered universe sends nothing.
1
        self.universe_allowed(&universe)?;
        // Keep going after a failed send so one unreachable destination doesn't stop the others being told.
1
        let mut first_err: Option<SacnError> = None;
1
        for dst in dst_ips {
1
            for _ in 0..E131_TERMINATE_STREAM_PACKET_COUNT {
3
                if let Err(e) = self.send_terminate_stream_pkt(universe, Some(*dst), start_code) {
                    first_err.get_or_insert(e);
                    break;
3
                }
            }
        }
1
        self.deregister_universe(universe)?;
1
        match first_err {
            Some(e) => Err(e),
1
            None => Ok(()),
        }
1
    }
    /// Terminates the DMX source.
    ///
    /// This includes terminating each registered universe with the `start_code` given.
    ///
    /// Arguments:
    /// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
    ///
    /// # Errors:
    /// Io: Returned if the termination packets fail to be sent on the underlying socket.
118
    fn terminate(&mut self, start_code: u8) -> Result<()> {
118
        self.running = false;
118
        let universes = self.universes.clone(); // About to start manipulating self.universes as universes are removed so clone original list.
        // Attempt every universe even if one fails, so a single send error doesn't leave the remaining universes
        // unterminated. The first error is returned once all universes have been attempted.
118
        let mut first_err: Option<SacnError> = None;
118
        for u in universes {
1337
            if let Err(e) = self.terminate_stream(u, start_code) {
                // terminate_stream only deregisters after its packets were sent; the source is shutting down so
                // deregister regardless.
3
                let _ = self.deregister_universe(u);
3
                first_err.get_or_insert(e);
1334
            }
        }
118
        match first_err {
1
            Some(e) => Err(e),
117
            None => Ok(()),
        }
118
    }
    /// Sends a universe discovery packet advertising the universes that this source is registered to send.
    ///
    /// This packet may be broken down into multiple pages internally resulting in multiple UDP packets.
    ///
    /// # Errors
    /// See (`send_universe_discovery_detailed`)[`fn.send_universe_discovery_detailed.source`].
20
    fn send_universe_discovery(&self) -> Result<()> {
20
        for (page, last_page, universes) in discovery_pages(&self.universes) {
21
            self.send_universe_discovery_detailed(page, last_page, universes)?;
        }
20
        Ok(())
20
    }
    /// Sends a page of a universe discovery packet.
    ///
    /// There may be 1 or more pages for each full universe discovery packet with each page sent separately.
    ///
    /// # Arguments
    ///
    /// page: The page number of this universe discovery page.
    ///
    /// `last_page`: The last page that is expected as part of this universe discovery packet.
    ///
    /// universes: The universes to include on the page.
    ///
    /// # Errors
    /// Io: Returned if the discovery packet fails to be sent on the socket.
    ///
    /// `SacnParsePackError`: Returned if the discovery packet cannot be packed to send.
21
    fn send_universe_discovery_detailed(
21
        &self,
21
        page: u8,
21
        last_page: u8,
21
        universes: &[u16],
21
    ) -> Result<()> {
21
        let packet = AcnRootLayerProtocol {
21
            pdu: E131RootLayer {
21
                cid: self.cid,
21
                data: E131RootLayerData::UniverseDiscoveryPacket(
21
                    UniverseDiscoveryPacketFramingLayer {
21
                        source_name: self.name.as_str().into(),
21
                        data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
21
                            page,
21
                            last_page,
21
                            universes: universes.into(),
21
                        },
21
                    },
21
                ),
21
            },
21
        };
21
        let ip = if self.addr.is_ipv6() {
8
            universe_to_ipv6_multicast_addr(E131_DISCOVERY_UNIVERSE)?
        } else {
13
            universe_to_ipv4_multicast_addr(E131_DISCOVERY_UNIVERSE)?
        };
21
        log_trace!(
            "Sending sACN universe discovery page {page} of {last_page} with {} universes",
            universes.len()
        );
21
        self.socket.send_to(&packet.pack_alloc()?, &ip)?;
21
        Ok(())
21
    }
    /// Returns the ACN CID device identifier of the `SacnSourceInternal`.
3
    fn cid(&self) -> &Uuid {
3
        &self.cid
3
    }
    /// Sets the ACN CID device identifier.
    ///
    /// # Arguments
    /// cid: The new CID identifier for this source. It is left to the user to ensure that this is always unique within the network the source is in.
1
    fn set_cid(&mut self, cid: Uuid) {
1
        self.cid = cid;
1
    }
    /// Returns the ACN source name.
4
    fn name(&self) -> &str {
4
        &self.name
4
    }
    /// Sets ACN source name.
    ///
    /// # Argument
    /// name: The new name for the source, it is left to the user to ensure this is unique within the sACN network.
    ///
    /// # Errors
    /// `MalformedSourceName`: Returned to indicate that the given source name is longer than the maximum allowed as per `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
3
    fn set_name(&mut self, name: &str) -> Result<()> {
3
        if name.len() > E131_SOURCE_NAME_MAX_LENGTH {
2
            return Err(SacnError::MalformedSourceName(
2
                "Source name provided is longer than maximum allowed".to_string(),
2
            ));
1
        }
1
        self.name = name.to_string();
1
        Ok(())
3
    }
    /// Returns if `SacnSourceInternal` is in preview mode.
2
    fn preview_mode(&self) -> bool {
2
        self.preview_data
2
    }
    /// Sets the value of the `Preview_Data` flag in packets from this `SacnSourceInternal`.
    ///
    /// # Arguments
    /// `preview_mode`: If true then all data packets from this `SacnSourceInternal` will have the `Preview_Data` flag set to true indicating that the data is not
    ///     for live output. If false then the flag will be set to false.
5
    fn set_preview_mode(&mut self, preview_mode: bool) {
5
        self.preview_data = preview_mode;
5
    }
    /// Sets the multicast time to live.
    ///
    /// # Arguments
    /// `multicast_ttl`: The new time to live value for network packets sent using multicast.
    ///
    /// # Errors
    /// Io: Returned if the multicast TTL fails to be set on the underlying socket.
4
    fn set_multicast_ttl(&self, multicast_ttl: u32) -> Result<()> {
4
        if self.addr.is_ipv6() {
2
            Ok(self.socket.set_multicast_hops_v6(multicast_ttl)?)
        } else {
2
            Ok(self.socket.set_multicast_ttl_v4(multicast_ttl)?)
        }
4
    }
    /// Returns the current Time To Live for unicast packets send by this source.
    ///
    /// # Errors
    /// Io: Returned if the TTL cannot be retrieved from the underlying socket.
4
    fn ttl(&self) -> Result<u32> {
4
        if self.addr.is_ipv6() {
2
            Ok(self.socket.unicast_hops_v6()?)
        } else {
2
            Ok(self.socket.ttl_v4()?)
        }
4
    }
    /// Sets the Time To Live for unicast packets sent by this source.
    ///
    /// # Arguments
    /// ttl: The new time to live value for network packets sent by the source.
    ///
    /// # Errors
    /// Io: Returned if the TTL fails to be set on the underlying socket.
4
    fn set_ttl(&mut self, ttl: u32) -> Result<()> {
4
        if self.addr.is_ipv6() {
2
            Ok(self.socket.set_unicast_hops_v6(ttl)?)
        } else {
2
            Ok(self.socket.set_ttl_v4(ttl)?)
        }
4
    }
    /// Returns the multicast time to live of the socket.
4
    fn multicast_ttl(&self) -> Result<u32> {
4
        if self.addr.is_ipv6() {
2
            Ok(self.socket.multicast_hops_v6()?)
        } else {
2
            Ok(self.socket.multicast_ttl_v4()?)
        }
4
    }
    /// Sets if multicast loop is enabled.
    ///
    /// # Arguments:
    /// `multicast_loop`: If true then multicast loop is enabled, if false it is not.
    ///
    /// # Errors
    /// Io: Returned if the `set_multicast_loop` option fails to be set on the socket.
10
    fn set_multicast_loop_v4(&self, multicast_loop: bool) -> Result<()> {
10
        Ok(self.socket.set_multicast_loop_v4(multicast_loop)?)
10
    }
    /// Sets if multicast loop is enabled, using the option for this source's IP version.
6
    fn set_multicast_loop(&self, multicast_loop: bool) -> Result<()> {
6
        if self.addr.is_ipv6() {
4
            Ok(self.socket.set_multicast_loop_v6(multicast_loop)?)
        } else {
2
            Ok(self.socket.set_multicast_loop_v4(multicast_loop)?)
        }
6
    }
    /// Returns true if multicast loop is enabled, false if not.
8
    fn multicast_loop(&self) -> Result<bool> {
8
        if self.addr.is_ipv6() {
4
            Ok(self.socket.multicast_loop_v6()?)
        } else {
4
            Ok(self.socket.multicast_loop_v4()?)
        }
8
    }
    /// Returns the universes currently registered on this source.
4
    pub fn universes(&self) -> Vec<u16> {
4
        self.universes.clone()
4
    }
}
/// Returns the locked internal `SacnSourceInternal` used within the `SacnSource`.
///
/// This centralises the locking of the source to a single point within the code allowing any changes to the mechanism to be made in one place.
///
/// This differs to (`unlock_internal_mut`) as it takes an immutable reference to internal.
///
/// # Arguments
/// internal: The `SacnSourceInternal` to unlock encapsulated within an Arc and Mutex.
///
/// # Errors
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// a panic while accessing causing the source to be left in a potentially inconsistent state.
32
fn unlock_internal(
32
    internal: &Arc<Mutex<SacnSourceInternal>>,
32
) -> Result<MutexGuard<'_, SacnSourceInternal>> {
32
    match internal.lock() {
        Err(_) => {
            // The PoisonError returned doesn't contain further information and just allows access to the internal potentially inconsistent sender which
            // shouldn't be exposed to the user (as its internal and would have no use).
            // Cannot directly return the PoisonError due to PoisonError using a different error system to other std modules which doesn't work with
            // error_chain.
            Err(SacnError::SourceCorrupt("Mutex poisoned".to_string()))
        }
32
        Ok(lock) => Ok(lock),
    }
32
}
/// Returns the locked internal `SacnSourceInternal` used within the `SacnSource`.
///
/// This centralises the locking of the source to a single point within the code allowing any changes to the mechanism to be made in one place.
///
/// This differs to (`unlock_internal`) as it takes an mutable reference to internal.
///
/// # Arguments
/// internal: The `SacnSourceInternal` to unlock encapsulated within an Arc and Mutex.
///
/// # Errors
/// Returns an `SourceCorrupt` error if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// a panic while accessing causing the source to be left in a potentially inconsistent state.
7020
fn unlock_internal_mut(
7020
    internal: &mut Arc<Mutex<SacnSourceInternal>>,
7020
) -> Result<MutexGuard<'_, SacnSourceInternal>> {
7020
    match internal.lock() {
        Err(_) => {
            // The PoisonError returned doesn't contain further information and just allows access to the internal potentially inconsistent sender which
            // shouldn't be exposed to the user (as its internal and would have no use).
            // Cannot directly return the PoisonError due to PoisonError using a different error system to other std modules which doesn't work with
            // error_chain.
            Err(SacnError::SourceCorrupt("Mutex poisoned".to_string()))
        }
7020
        Ok(lock) => Ok(lock),
    }
7020
}
/// Called periodically by the source update thread.
///
/// Is responsible for sending the periodic universe discovery packets.
///
/// # Arguments:
/// src: A reference to the `SacnSourceInternal` for which to send the universe discovery packet with/from.
///
/// # Errors
/// Returns a `SourceCorrupt` error if the internal source mutex has been corrupted, see [`unlock_internal`].
///
/// Returns an error if a discovery packet cannot be sent, see (`send_universe_discovery`)[`fn.send_universe_discovery.source`].
304
fn perform_periodic_update(src: &mut Arc<Mutex<SacnSourceInternal>>) -> Result<()> {
304
    let mut unwrap_src = unlock_internal_mut(src)?;
304
    if unwrap_src.is_sending_discovery
301
        && Instant::now().duration_since(unwrap_src.last_discovery_advert_timestamp)
301
            > E131_UNIVERSE_DISCOVERY_INTERVAL
    {
20
        unwrap_src.send_universe_discovery()?;
20
        unwrap_src.last_discovery_advert_timestamp = Instant::now();
284
    }
304
    Ok(())
304
}
/// Splits the given (sorted) universe list into universe discovery pages.
///
/// Returns one `(page, last_page, universes)` entry per page, each holding at most `DISCOVERY_UNI_PER_PAGE` universes.
/// A list of n universes gives ceil(n / 512) pages with a last page of `(n - 1) / 512`, so a source with no universes
/// sends no discovery packet at all and an exact multiple of 512 does not produce a trailing empty page.
26
fn discovery_pages(universes: &[u16]) -> Vec<(u8, u8, &[u16])> {
26
    let chunks: Vec<&[u16]> = universes.chunks(DISCOVERY_UNI_PER_PAGE).collect();
    // A u16 universe field and no duplicates give at most 65536 / 512 = 128 pages, so the page numbers fit in a u8.
26
    let last_page = chunks.len().saturating_sub(1) as u8;
26
    chunks
26
        .into_iter()
26
        .enumerate()
155
        .map(|(p, c)| (p as u8, last_page, c))
        .collect()
26
}
#[cfg(test)]
mod test {
    use super::*;
    /// A send failure on one universe must not stop the remaining universes from being terminated.
    #[cfg(unix)]
    #[test]
1
    fn test_terminate_attempts_every_universe() {
1
        let ip = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
1
        let mut src = SacnSourceInternal::with_cid_ip("Test", Uuid::new_v4(), ip).unwrap();
1
        src.register_universes(&[1, 2, 3]).unwrap();
        // Swap in a Unix domain socket so every IP multicast send fails.
1
        src.socket = Socket::new(Domain::UNIX, Type::DGRAM, None).unwrap();
1
        assert!(src.terminate(DEFAULT_TERMINATE_START_CODE).is_err());
1
        assert!(
1
            src.universes.is_empty(),
            "universes left registered after terminate: {:?}",
            src.universes
        );
1
        assert!(!src.running);
1
    }
    /// A source with no universes has nothing to advertise and sends no discovery page.
    #[test]
1
    fn test_discovery_pages_empty() {
1
        assert!(discovery_pages(&[]).is_empty());
1
    }
    #[test]
1
    fn test_discovery_pages_single_page() {
1
        let unis: Vec<u16> = (1..=3).collect();
1
        let pages = discovery_pages(&unis);
1
        assert_eq!(pages, vec![(0, 0, &unis[..])]);
1
    }
    /// Exactly 512 universes fill one page; no trailing empty page is sent.
    #[test]
1
    fn test_discovery_pages_exact_multiple() {
1
        let unis: Vec<u16> = (1..=(DISCOVERY_UNI_PER_PAGE as u16)).collect();
1
        let pages = discovery_pages(&unis);
1
        assert_eq!(pages, vec![(0, 0, &unis[..])]);
1
        let unis: Vec<u16> = (1..=(2 * DISCOVERY_UNI_PER_PAGE as u16)).collect();
1
        let pages = discovery_pages(&unis);
1
        assert_eq!(pages.len(), 2);
1
        assert_eq!(pages[0], (0, 1, &unis[..DISCOVERY_UNI_PER_PAGE]));
1
        assert_eq!(pages[1], (1, 1, &unis[DISCOVERY_UNI_PER_PAGE..]));
1
    }
    #[test]
1
    fn test_discovery_pages_partial_last_page() {
1
        let unis: Vec<u16> = (1..=(DISCOVERY_UNI_PER_PAGE as u16 + 1)).collect();
1
        let pages = discovery_pages(&unis);
1
        assert_eq!(pages.len(), 2);
1
        assert_eq!(pages[0], (0, 1, &unis[..DISCOVERY_UNI_PER_PAGE]));
1
        assert_eq!(pages[1], (1, 1, &unis[DISCOVERY_UNI_PER_PAGE..]));
1
    }
    /// The largest possible universe set still fits the 8-bit page fields.
    #[test]
1
    fn test_discovery_pages_max() {
1
        let unis: Vec<u16> = (0..=u16::MAX).collect();
1
        let pages = discovery_pages(&unis);
1
        assert_eq!(pages.len(), 128);
1
        assert_eq!(pages.last().unwrap().0, 127);
1
        assert!(
1
            pages
1
                .iter()
128
                .all(|(_, last, u)| *last == 127 && u.len() == DISCOVERY_UNI_PER_PAGE)
        );
1
    }
}