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 created as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
11

            
12
// Report point: There is no guarantees made by the protocol that different sources will have different names.
13
// As names are used to match universe discovery packets this means that if 2 sources have the same name it won't
14
// be clear which one is sending what universes as they will appear as one source.
15

            
16
// Report point: partially discovered sources are only marked as discovered when a full set of discovery packets has been
17
// received, if a discovery packet is received but there are more pages the source won't be discovered until all the pages are received.
18
// If a page is lost this therefore means the source update / discovery in its entirety will be lost - implementation detail.
19

            
20
/// Socket 2 used for the underlying UDP socket that sACN is sent over.
21
use socket2::{Domain, Protocol, SockAddr, Socket, Type};
22

            
23
/// Mass import as a very large amount of packet is used here (upwards of 20 items) and this is much cleaner.
24
use crate::packet::{
25
    E131RootLayerData::{DataPacket, SynchronizationPacket, UniverseDiscoveryPacket},
26
    *,
27
};
28

            
29
/// Same reasoning as for packet meaning all sacn errors are imported.
30
use crate::error::errors::*;
31

            
32
/// The uuid crate is used for working with/generating UUIDs which sACN uses as part of the cid field in the protocol.
33
/// This is used for uniquely identifying sources when counting sequence numbers.
34
use uuid::Uuid;
35

            
36
use std::cmp::{Ordering, max};
37
use std::collections::HashMap;
38
use std::io::Read;
39
use std::net::{Ipv4Addr, SocketAddr};
40
use std::time::{Duration, Instant};
41
use std::{fmt, io};
42

            
43
/// Extra net imports required for the IPv6 handling on the linux side.
44
#[cfg(not(target_os = "windows"))]
45
use std::net::{IpAddr, Ipv6Addr};
46

            
47
/// Constants required to detect if an IP is IPv4 or IPv6.
48
#[cfg(not(target_os = "windows"))]
49
use libc::{AF_INET, AF_INET6};
50

            
51
/// The libc constants required are not available on many windows environments and therefore are hard-coded.
52
/// Defined as per <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket>
53
#[cfg(target_os = "windows")]
54
const AF_INET: i32 = 2;
55

            
56
/// Defined as per <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket>
57
#[cfg(target_os = "windows")]
58
const AF_INET6: i32 = 23;
59

            
60
#[cfg(target_os = "windows")]
61
use std::net::IpAddr;
62

            
63
/// The default size of the buffer used to receive E1.31 packets.
64
/// 1143 bytes is biggest packet required as per Section 8 of ANSI E1.31-2018, aligned to 64 bit that is 1144 bytes.
65
pub const RCV_BUF_DEFAULT_SIZE: usize = 1144;
66

            
67
/// DMX payload size in bytes (512 bytes of data + 1 byte start code).
68
pub const DMX_PAYLOAD_SIZE: usize = 513;
69

            
70
/// The default value of the `process_preview_data` flag.
71
const PROCESS_PREVIEW_DATA_DEFAULT: bool = false;
72

            
73
/// The default value of the `announce_source_discovery` flag.
74
/// Defaults to false based on the assumption that often receivers won't have any immediate response/checks to do on a source
75
/// announcing itself (every source does this approximately every 10 seconds as per the `E131_DISCOVERY_INTERVAL`).
76
const ANNOUNCE_SOURCE_DISCOVERY_DEFAULT: bool = false;
77

            
78
/// The default value of the `announce_stream_termination` flag.
79
/// Defaults to false based on the assumption that often receivers will want to ignore termination from a source based on there
80
/// being multiple possible sources.
81
const ANNOUNCE_STREAM_TERMINATION_DEFAULT: bool = false;
82

            
83
/// The default value of the `announce_timeout` flag.
84
const ANNOUNCE_TIMEOUT_DEFAULT: bool = false;
85

            
86
/// If a packet for a universe is waiting to be synchronised and then another packet is received with the same universe and synchronisation address
87
/// this situation must be handled. By default the implementation discards the lowest priority packet and if equal priority it discards the oldest
88
/// packet as per ANSI E1.31-2018 Section 6.2.3.
89
///
90
/// This can be changed by providing a new function to handle the situation of the user implementing a custom merge/arbitration algorithm as per
91
/// ANSI E1.31-2018 Section 6.2.3.2.
92
const DEFAULT_MERGE_FUNC: fn(&DMXData, &DMXData) -> Result<DMXData> =
93
    discard_lowest_priority_then_previous;
94

            
95
/// Holds a universes worth of DMX data.
96
#[derive(Debug)]
97
pub struct DMXData {
98
    /// The universe that the data was sent to.
99
    pub universe: u16,
100

            
101
    /// The actual universe data, if less than 512 values in length then implies trailing 0's to pad to a full-universe of data.
102
    pub values: Vec<u8>,
103

            
104
    /// The universe the data is (or was if now acted upon) waiting for a synchronisation packet from.
105
    /// 0 indicates it isn't waiting for a universe synchronisation packet.
106
    pub sync_uni: u16,
107

            
108
    /// The priority of the data, this may be useful for receivers which want to implement their own implementing merge algorithms.
109
    /// Must be less than `packet::E131_MAX_PRIORITY`.
110
    pub priority: u8,
111

            
112
    /// The unique id of the source of the data, this may be useful for receivers which want to implement their own merge algorithms
113
    /// which use the identity of the source to decide behaviour.
114
    /// A value of None indicates that there is no clear source, for example if a merge algorithm has merged data from 2 or more sources together.
115
    pub src_cid: Option<Uuid>,
116

            
117
    /// Indicates if the data is marked as 'preview' data indicating it is for use by visualisers etc. as per ANSI E1.31-2018 Section 6.2.6.
118
    pub preview: bool,
119

            
120
    /// The timestamp that the data was received.
121
    pub recv_timestamp: Instant,
122
}
123

            
124
/// Allows receiving dmx or other (different startcode) data using sacn.
125
///
126
/// # Examples
127
///
128
/// ```
129
/// // Example showing creation of a receiver and receiving some data, as there is no sender this receiver then handles the timeout.
130
/// use sacn::receive::SacnReceiver;
131
/// use sacn::packet::ACN_SDT_MULTICAST_PORT;
132
///
133
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
134
/// use std::time::Duration;
135
///
136
/// const UNIVERSE1: u16 = 1;
137
/// const TIMEOUT: Option<Duration> = Some(Duration::from_secs(1)); // A timeout of None means blocking behaviour, some indicates the actual timeout.
138
///
139
/// let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
140
///
141
/// let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
142
///
143
/// dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
144
///
145
/// match dmx_rcv.recv(TIMEOUT) {
146
///     Err(e) => {
147
///         // Print out the error.
148
///         println!("{:?}", e);
149
///     }
150
///     Ok(p) => {
151
///         // Print out the packet.
152
///         println!("{:?}", p);
153
///     }
154
/// }
155
/// ```
156
pub struct SacnReceiver {
157
    /// The `SacnNetworkReceiver` used for handling communication with UDP / Network / Transport layer.
158
    receiver: SacnNetworkReceiver,
159

            
160
    /// Data that hasn't been passed up yet as it is waiting e.g. due to universe synchronisation.
161
    /// Key is the data universe and the start code (the first property value). A receiver may not have more than one packet
162
    /// waiting per `data_universe` and start code, so that e.g. level data (start code 0x00) and per-address priority data
163
    /// (start code 0xDD) held for the same synchronisation are both released rather than one replacing the other.
164
    /// `Data_universe` used as key as oppose to sync universe because multiple packets might be waiting on the same sync universe
165
    /// and adding data by data universe is at least as common as retrieving data by sync address because in a normal setup
166
    /// 1 or more bits of data wait for 1 sync.
167
    waiting_data: HashMap<(u16, u8), DMXData>,
168

            
169
    /// Universes that this receiver is currently listening for.
170
    universes: Vec<u16>,
171

            
172
    /// Sacn sources that have been discovered by this receiver through universe discovery packets.
173
    discovered_sources: Vec<DiscoveredSacnSource>,
174

            
175
    /// The merge function used by this receiver if `DMXData` for the same universe and synchronisation universe is received while there
176
    /// is already `DMXData` waiting for that universe and synchronisation address.
177
    merge_func: fn(&DMXData, &DMXData) -> Result<DMXData>,
178

            
179
    /// Sacn sources that have been partially discovered by only some of their universes being discovered so far with more pages to go.
180
    partially_discovered_sources: Vec<DiscoveredSacnSource>,
181

            
182
    /// The limit to the number of sources for which to track sequence numbers.
183
    /// A new source after this limit will cause a `SourcesExceededError` as per ANSI E1.31-2018 Section 6.2.3.3.
184
    source_limit: Option<usize>,
185

            
186
    /// The sequence numbers being tracked by this receiver for each packet type, source and universe.
187
    sequences: SequenceNumbering,
188

            
189
    /// Flag that indicates if this receiver should process packets marked as preview data.
190
    /// If true then the receiver will process theses packets.
191
    /// Returned data contains a flag to indicate if it is `preview_data` which can be used by the implementer to use/discard as required.
192
    process_preview_data: bool,
193

            
194
    /// Flag which indicates if a `SourceDiscovered` error should be thrown when receiving data and a source is discovered.
195
    announce_source_discovery: bool,
196

            
197
    /// Flag which indicates if a `StreamTerminated` error should be thrown if a receiver receives a stream terminated packet.
198
    announce_stream_termination: bool,
199

            
200
    /// Flag which indicates if an `UniverseTimeout` error should be thrown if it is detected that a source has timed out.
201
    announce_timeout: bool,
202

            
203
    /// Synchronisation universes that received data packets have named, with the time each was last named.
204
    ///
205
    /// The receiver joins the multicast group of each so that it receives their synchronisation packets, without adding
206
    /// them to `universes`: data sent on a synchronisation universe is only passed up if the user listens to it. Entries
207
    /// that haven't been named for `E131_NETWORK_DATA_LOSS_TIMEOUT` are removed and their group left, unless the user
208
    /// listens to that universe.
209
    sync_universes: HashMap<u16, Instant>,
210

            
211
    /// When the last synchronisation packet was received for each synchronisation address.
212
    /// Used to tell if synchronisation on an address has been lost, as per ANSI E1.31-2016 Section 11.1.2.
213
    last_sync_packets: HashMap<u16, Instant>,
214
}
215

            
216
/// Represents an sACN source/sender on the network that has been discovered by this sACN receiver by receiving universe discovery packets.
217
#[derive(Clone, Debug)]
218
pub struct DiscoveredSacnSource {
219
    /// The name of the source, no protocol guarantee this will be unique but if it isn't then universe discovery may not work correctly.
220
    pub name: String,
221

            
222
    /// The unique CID of the source. This should be unique across all devices on the network.
223
    pub cid: Uuid,
224

            
225
    /// The time at which the discovered source was last updated / a discovery packet was received by the source.
226
    pub last_updated: Instant,
227

            
228
    /// The pages that have been sent so far by this source when enumerating the universes it is currently sending on.
229
    pages: Vec<UniversePage>,
230

            
231
    /// The last page that will be sent by this source.
232
    last_page: u8,
233
}
234

            
235
/// Used for receiving dmx or other data on a particular universe using multicast.
236
#[derive(Debug)]
237
struct SacnNetworkReceiver {
238
    /// The underlying UDP network socket used.
239
    socket: Socket,
240

            
241
    /// The address that this `SacnNetworkReceiver` is bound to.
242
    addr: SocketAddr,
243

            
244
    /// If true then this receiver supports multicast, is false then it does not.
245
    /// This flag is set when the receiver is created as not all environments currently support IP multicast.
246
    /// E.g. IPv6 Windows IP Multicast is currently unsupported.
247
    is_multicast_enabled: bool,
248
}
249

            
250
/// Universe discovery packets are broken down into pages to allow sending a large list of universes, each page contains a list of universes and
251
/// which page it is. The receiver then puts the pages together to get the complete list of universes that the discovered source is sending on.
252
///
253
/// The concept of pages is intentionally hidden from the end-user of the library as they are a way of fragmenting large discovery
254
/// universe lists so that they can work over the network and don't play any part out-side of the protocol.
255
#[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug)]
256
struct UniversePage {
257
    /// The page number of this page.
258
    page: u8,
259

            
260
    /// The universes that the source is transmitting that are on this page, this may or may-not be a complete list of all universes being sent
261
    /// depending on if there are more pages.
262
    universes: Vec<u16>,
263
}
264

            
265
/// Allows debug ({:?}) printing of the `SacnReceiver`, used during debugging.
266
impl fmt::Debug for SacnReceiver {
267
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268
        write!(f, "{:?}", self.receiver)?;
269
        write!(f, "{:?}", self.waiting_data)?;
270
        write!(f, "{:?}", self.universes)?;
271
        write!(f, "{:?}", self.discovered_sources)?;
272
        write!(f, "{:?}", self.partially_discovered_sources)
273
    }
274
}
275

            
276
impl SacnReceiver {
277
    /// Creates a new `SacnReceiver`.
278
    ///
279
    /// `SacnReceiverInternal` is used for actually receiving the sACN data but is wrapped in `SacnReceiver` to allow the update thread to handle
280
    /// timeout etc.
281
    ///
282
    /// By default for an IPv6 address this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
283
    /// A receiver with an IPv4 address will only receive IPv4 data.
284
    ///
285
    /// IPv6 multicast is unsupported on Windows in Rust. This is due to the underlying library (Socket2) not providing support.
286
    /// Since `UniverseDiscovery` is primarily based around multicast to receive the `UniverseDiscovery` packets this mechanism is expected
287
    /// to have limited usage when running in an Ipv6 Windows environment. The `is_multicast_enabled` method can be used to see if multicast
288
    /// is enabled or not.
289
    ///
290
    /// Arguments:
291
    ///     ip: The address of the interface for this receiver to join, by default this address should use the `ACN_SDT_MULTICAST_PORT` as defined in
292
    ///         ANSI E1.31-2018 Appendix A: Defined Parameters (Normative) however another address might be used in some situations.
293
    ///     `source_limit`: The limit to the number of sources, past this limit a new source will cause a `SourcesExceededError` as per ANSI E1.31-2018 Section 6.2.3.3.
294
    ///                     A source limit of None means no limit to the number of sources.
295
    ///
296
    /// # Errors
297
    /// Will return an `InvalidInput` error if the `source_limit` has a value of Some(0) which would indicate this receiver can never receive from any source.
298
    ///
299
    /// Will return an error if the `SacnReceiver` fails to bind to a socket with the given ip.
300
    /// For more details see `socket2::Socket::new()`.
301
    ///
302
    /// Will return an error if the created `SacnReceiver` fails to listen to the `E1.31_DISCOVERY_UNIVERSE`.
303
    /// For more details see `SacnReceiver::listen_universes()`.
304
620
    pub fn with_ip(ip: SocketAddr, source_limit: Option<usize>) -> Result<SacnReceiver> {
305
620
        if let Some(x) = source_limit
306
4
            && x == 0
307
        {
308
1
            return Err(SacnError::SourceLimitZero());
309
619
        };
310
        let mut sri = SacnReceiver {
311
619
            receiver: SacnNetworkReceiver::new(ip)?,
312
619
            waiting_data: HashMap::new(),
313
619
            universes: Vec::new(),
314
619
            discovered_sources: Vec::new(),
315
619
            merge_func: DEFAULT_MERGE_FUNC,
316
619
            partially_discovered_sources: Vec::new(),
317
619
            process_preview_data: PROCESS_PREVIEW_DATA_DEFAULT,
318
619
            source_limit,
319
619
            sequences: SequenceNumbering::new(),
320
619
            announce_source_discovery: ANNOUNCE_SOURCE_DISCOVERY_DEFAULT,
321
619
            announce_stream_termination: ANNOUNCE_STREAM_TERMINATION_DEFAULT,
322
619
            announce_timeout: ANNOUNCE_TIMEOUT_DEFAULT,
323
619
            sync_universes: HashMap::new(),
324
619
            last_sync_packets: HashMap::new(),
325
        };
326

            
327
619
        sri.listen_universes(&[E131_DISCOVERY_UNIVERSE])?;
328

            
329
619
        Ok(sri)
330
620
    }
331

            
332
    /// Sets the value of the `is_multicast_enabled` flag to the given value.
333
    ///
334
    /// If set to false then the receiver won't attempt to join any more multicast groups.
335
    ///
336
    /// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
337
    ///
338
    /// # Arguments
339
    /// val: The new value for the `is_multicast_enabled` flag.
340
    ///
341
    /// # Errors
342
    /// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
343
    /// isn't supported i.e. Ipv6 on Windows.
344
2
    pub fn set_is_multicast_enabled(&mut self, val: bool) -> Result<()> {
345
2
        self.receiver.set_is_multicast_enabled(val)
346
2
    }
347

            
348
    /// Returns true if multicast is enabled on this receiver and false if not.
349
    /// This flag is set when the receiver is created as not all environments currently support IP multicast.
350
    /// E.g. IPv6 Windows IP Multicast is currently unsupported.
351
1281
    pub fn is_multicast_enabled(&self) -> bool {
352
1281
        self.receiver.is_multicast_enabled()
353
1281
    }
354

            
355
    /// Wipes the record of discovered and sequence number tracked sources.
356
    /// This is one way to handle a sources exceeded condition.
357
    ///
358
    /// If you want to wipe data awaiting synchronisation then see [`clear_all_waiting_data`](Self::clear_all_waiting_data).
359
2
    pub fn reset_sources(&mut self) {
360
2
        self.sequences.clear();
361
2
        self.partially_discovered_sources.clear();
362
2
        self.discovered_sources.clear();
363
2
    }
364

            
365
    /// Deletes all data currently waiting to be passed up - e.g. waiting for a synchronisation packet.
366
    ///
367
    /// This allows clearing all data awaiting synchronisation but without forgetting sequence numbers. To wipe sequence numbers
368
    /// and discovered sources see [`reset_sources`](Self::reset_sources).
369
    ///
370
    /// To clear only a specific universe of waiting data see [`clear_waiting_data`](Self::clear_waiting_data).
371
1
    pub fn clear_all_waiting_data(&mut self) {
372
1
        self.waiting_data.clear();
373
1
    }
374

            
375
    /// Clears data (if any) waiting to be passed up for the specific universe, whatever its start code.
376
    ///
377
    /// Returns true if data was removed and false if there wasn't any data to remove for this universe.
378
    ///
379
    /// # Arguments
380
    /// universe: The universe that the data that is waiting was sent to.
381
1147
    pub fn clear_waiting_data(&mut self, universe: u16) -> bool {
382
1147
        let len = self.waiting_data.len();
383
1147
        self.waiting_data.retain(|(uni, _), _| *uni != universe);
384
1147
        self.waiting_data.len() != len
385
1147
    }
386

            
387
    /// Sets the merge function to be used by this receiver.
388
    ///
389
    /// This merge function is called if data is waiting for a universe e.g. for synchronisation and then further data for that universe with the same
390
    /// synchronisation address arrives.
391
    ///
392
    /// This merge function MUST return a `DmxMergeError` if there is a problem merging. This error can optionally encapsulate further errors using the Error-chain system
393
    ///     to provide a more informative backtrace.
394
    ///
395
    /// Arguments:
396
    /// func: The merge function to use. Should take 2 `DMXData` references as arguments and return a `Result<DMXData>`.
397
2
    pub fn set_merge_fn(&mut self, func: fn(&DMXData, &DMXData) -> Result<DMXData>) -> Result<()> {
398
2
        self.merge_func = func;
399
2
        Ok(())
400
2
    }
401

            
402
    /// Allow only receiving on Ipv6.
403
    pub fn set_ipv6_only(&mut self, val: bool) -> Result<()> {
404
        self.receiver.set_only_v6(val)
405
    }
406

            
407
    /// Allows receiving from the given universe and starts listening to the multicast addresses which corresponds to the given universe.
408
    ///
409
    /// Note that if the `is_multicast_enabled` flag is set to false then this method will only register the universe to listen to and won't
410
    /// attempt to join any multicast groups.
411
    ///
412
    /// If 1 or more universes in the list are already being listened to this method will have no effect for those universes only.
413
    ///
414
    /// # Errors
415
    /// Returns an `SacnError::IllegalUniverse` error if the given universe is outwith the allowed range of universes,
416
    /// see [`is_universe_in_range`].
417
    ///
418
    ///
419
1240
    pub fn listen_universes(&mut self, universes: &[u16]) -> Result<()> {
420
1240
        for u in universes {
421
1268
            is_universe_in_range(*u)?;
422
        }
423

            
424
1240
        for u in universes {
425
1268
            if let Err(i) = self.universes.binary_search(u) {
426
                // Value not found, i is the position it should be inserted
427
1268
                self.universes.insert(i, *u);
428

            
429
                // The group may already have been joined to receive synchronisation packets for this universe.
430
1268
                if self.is_multicast_enabled() && !self.sync_universes.contains_key(u) {
431
1266
                    self.receiver.listen_multicast_universe(*u)?;
432
2
                }
433
            } else {
434
                // If value found then don't insert to avoid duplicates.
435
            }
436
        }
437

            
438
1240
        Ok(())
439
1240
    }
440

            
441
    /// Stops listening to the given universe.
442
    ///
443
    /// # Errors
444
    /// Returns an `SacnError::IllegalUniverse` error if the given universe is outwith the allowed range of universes,
445
    /// see [`is_universe_in_range`].
446
    ///
447
    /// Returns `UniverseNotFound` if the given universe wasn't already being listened to.
448
1268
    pub fn mute_universe(&mut self, universe: u16) -> Result<()> {
449
1268
        is_universe_in_range(universe)?;
450

            
451
1268
        match self.universes.binary_search(&universe) {
452
            Err(_) => {
453
                // Universe isn't found.
454
                Err(SacnError::UniverseNotFound(universe))
455
            }
456
            Ok(i) => {
457
1268
                self.universes.remove(i);
458
1268
                if self.sync_universes.contains_key(&universe) {
459
                    // Still needed for synchronisation packets; the group is left once it is no longer used for that.
460
1
                    Ok(())
461
                } else {
462
1267
                    self.receiver.mute_multicast_universe(universe)
463
                }
464
            }
465
        }
466
1268
    }
467

            
468
    /// Set the `process_preview_data` flag to the given value.
469
    ///
470
    /// This flag indicates if this receiver should process packets marked as `preview_data` or should ignore them.
471
    ///
472
    /// Argument:
473
    /// val: The new value of `process_preview_data` flag.
474
3
    pub fn set_process_preview_data(&mut self, val: bool) {
475
3
        self.process_preview_data = val;
476
3
    }
477

            
478
    /// Checks if this receiver is currently listening to the given universe.
479
    ///
480
    /// A receiver is 'listening' to a universe if it allows that universe to be received without filtering it out.
481
    /// This does not mean that the multicast address for that universe is or isn't being listened to.
482
    ///
483
    /// Arguments:
484
    /// universe: The sACN universe to check
485
    ///
486
    /// Returns:
487
    /// True if the universe is being listened to by this receiver, false if not.
488
3685
    pub fn is_listening(&self, universe: &u16) -> bool {
489
3685
        self.universes.contains(universe)
490
3685
    }
491

            
492
    /// Attempt to receive data from any of the registered universes.
493
    /// This is the main method for receiving data.
494
    /// Any data returned will be ready to act on immediately i.e. waiting e.g. for universe synchronisation
495
    /// is already handled.
496
    ///
497
    /// # Errors
498
    /// This method will return a `WouldBlock` (unix) or `TimedOut` (windows) error if there is no data ready within the given timeout.
499
    /// A timeout of duration 0 will do timeout checks but otherwise will return a WouldBlock/TimedOut error without checking for data.
500
    ///
501
    /// Will return `SacnError::SourceDiscovered` error if the `announce_source_discovery` flag is set and a universe discovery
502
    /// packet is received and a source fully discovered. This happens once when the source is first discovered, and again
503
    /// only if its name or universe list changes, not for every periodic advert.
504
    ///
505
    /// Will return a `UniverseNotRegistered` error if this method is called with an infinite timeout, no
506
    /// registered data universes and the `announce_discovered_sources` flag set to off. This is to protect the user from
507
    /// making this mistake leading to the method never being able to return.
508
    ///
509
    /// The method may also return an error if there is an issue setting a timeout on the receiver. See
510
    /// `SacnNetworkReceiver::set_timeout` for details.
511
    ///
512
    /// The method may also return an error if there is an issue handling the data as either a Data, Synchronisation or Discovery packet.
513
    /// See the `SacnReceiver::handle_data_packet`, `SacnReceiver::handle_sync_packet` and `SacnReceiver::handle_universe_discovery_packet` methods
514
    /// for details.
515
    ///
516
    /// If the `announce_timeout` flag is set then the recv will return a `UniverseTimeout` error if a source fails to send on a universe within the timeout
517
    /// specified by `E131_NETWORK_DATA_LOSS_TIMEOUT` (ANSI E1.31-2018 Appendix A).  This may not be detected immediately unless data is received for the timed-out
518
    /// universe from the source. If it isn't detected immediately it will be detected within an interval of `E131_NETWORK_DATA_LOSS_TIMEOUT` (assuming code
519
    /// executes in zero time).
520
1742
    pub fn recv(&mut self, timeout: Option<Duration>) -> Result<Vec<DMXData>> {
521
1742
        if self.universes.len() == 1
522
820
            && self.universes[0] == E131_DISCOVERY_UNIVERSE
523
820
            && timeout.is_none()
524
2
            && !self.announce_source_discovery
525
        {
526
            // This indicates that the only universe that can be received is the discovery universe.
527
            // This means that having no timeout may lead to no data ever being received and so this method blocking forever
528
            // to prevent this likely unintended behaviour throw a universe not registered error.
529
            return Err(SacnError::NoDataUniversesRegistered());
530
1742
        }
531

            
532
        // if timeout is 0, then it's time to return
533
1742
        if timeout == Some(Duration::from_secs(0)) {
534
            // always check timeouts
535
1
            self.sequences.check_timeouts(self.announce_timeout)?;
536
1
            self.check_waiting_data_timeouts();
537
1
            self.expire_sync_universes();
538
1
            return Err(io::Error::new(
539
                // Use the right expected error for the operating system.
540
1
                if cfg!(target_os = "windows") {
541
                    io::ErrorKind::TimedOut
542
                } else {
543
1
                    io::ErrorKind::WouldBlock
544
                },
545
1
                "No data available in given timeout",
546
            )
547
            .into());
548
1741
        }
549

            
550
        // Fixed instant that should return the whole recv call
551
1741
        let deadline = timeout.and_then(|t| Instant::now().checked_add(t));
552

            
553
        // shared buf through loop iterations
554
1741
        let mut buf: [u8; RCV_BUF_DEFAULT_SIZE] = [0; RCV_BUF_DEFAULT_SIZE];
555

            
556
        loop {
557
3712
            self.sequences.check_timeouts(self.announce_timeout)?;
558
3710
            self.check_waiting_data_timeouts();
559
3710
            self.expire_sync_universes();
560

            
561
            // In the case of `timeout` being longer than `E131_NETWORK_DATA_LOSS_TIMEOUT`:
562
            // Forces the actual timeout used for receiving from the underlying network to never exceed E131_NETWORK_DATA_LOSS_TIMEOUT.
563
            // This means that the timeouts for the sequence numbers will be checked at least every E131_NETWORK_DATA_LOSS_TIMEOUT even if
564
            // recv is called with a longer timeout.
565
3710
            let remaining = match deadline {
566
1997
                None => None, // set to data loss timeout below so timeouts are checked again.
567
                Some(dl) => {
568
1713
                    let now = Instant::now();
569
1713
                    if now >= dl {
570
                        // timeout expired
571
819
                        return Err(io::Error::new(
572
819
                            if cfg!(target_os = "windows") {
573
                                io::ErrorKind::TimedOut
574
                            } else {
575
819
                                io::ErrorKind::WouldBlock
576
                            },
577
819
                            "No data available in given timeout",
578
                        )
579
                        .into());
580
894
                    }
581
894
                    Some(dl - now)
582
                }
583
            };
584

            
585
2891
            let actual_timeout = if let Some(rem) = remaining {
586
894
                rem.min(E131_NETWORK_DATA_LOSS_TIMEOUT)
587
            } else {
588
1997
                E131_NETWORK_DATA_LOSS_TIMEOUT
589
            };
590

            
591
2891
            self.receiver.set_timeout(Some(actual_timeout))?; // "Failed to set a timeout value for the receiver"
592

            
593
            // Zero out the buffer before receiving. This may be redundant since recv should pack the whole buffer.
594
2891
            buf.fill(0);
595

            
596
2891
            match self.receiver.recv(&mut buf) {
597
                Ok(pkt) => {
598
2059
                    let pdu = pkt.pdu;
599
2059
                    let data = pdu.data;
600
2059
                    match &data {
601
1473
                        DataPacket(d) => log_trace!(
602
                            "Received sACN data packet from {}: universe {}, sequence {}, priority {}, sync address {}, {} bytes",
603
                            pdu.cid,
604
                            d.universe,
605
                            d.sequence_number,
606
                            d.priority,
607
                            d.synchronization_address,
608
                            d.data.property_values.len()
609
                        ),
610
568
                        SynchronizationPacket(s) => log_trace!(
611
                            "Received sACN sync packet from {}: sync address {}, sequence {}",
612
                            pdu.cid,
613
                            s.synchronization_address,
614
                            s.sequence_number
615
                        ),
616
18
                        UniverseDiscoveryPacket(u) => log_trace!(
617
                            "Received sACN universe discovery page {} of {} from {}",
618
                            u.data.page,
619
                            u.data.last_page,
620
                            pdu.cid
621
                        ),
622
                    }
623
2059
                    let res = match data {
624
1473
                        DataPacket(d) => self.handle_data_packet(pdu.cid, d)?,
625
568
                        SynchronizationPacket(s) => self.handle_sync_packet(pdu.cid, s)?,
626
                        UniverseDiscoveryPacket(u) => {
627
                            let discovered_src: Option<String> =
628
18
                                self.handle_universe_discovery_packet(pdu.cid, u);
629
18
                            if let Some(src) = discovered_src
630
10
                                && self.announce_source_discovery
631
                            {
632
4
                                return Err(SacnError::SourceDiscovered(src));
633
14
                            }
634
14
                            None
635
                        }
636
                    };
637

            
638
                    // return the data, otherwise continue if no data is ready
639
2051
                    if let Some(r) = res {
640
912
                        return Ok(r);
641
1139
                    }
642

            
643
                    // end of loop
644
                }
645

            
646
                Err(err) =>
647
                // This could be the socket-level timeout error or other socket recv error.
648
                {
649
832
                    match err {
650
                        // Windows and Unix use different error types (WouldBlock/TimedOut) for the same error.
651
                        SacnError::Io(ref s)
652
832
                            if matches!(
653
832
                                s.kind(),
654
                                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
655
                            ) =>
656
832
                        {
657
832
                            // socket read timedout.
658
832
                            // start new loop to compute new remaining which will return if deadline has passed
659
832
                        }
660
                        _ => {
661
                            // Not a timeout/wouldblock error meaning the recv should stop with the given error.
662
                            return Err(err);
663
                        }
664
                    }
665
                }
666
            }
667
        }
668
1742
    }
669

            
670
    /// Returns the current value of the `announce_source_discovery` flag.
671
    /// See [`set_announce_source_discovery`](Self::set_announce_source_discovery) for an explanation of the flag.
672
1
    pub fn get_announce_source_discovery(&self) -> bool {
673
1
        self.announce_source_discovery
674
1
    }
675

            
676
    /// Gets all discovered sources without checking if any are timed out.
677
    /// As the sources may be timed out `get_discovered_sources` is the preferred method but this is included
678
    /// to allow receivers to disable universe discovery source timeouts which may be useful in very high latency networks.
679
    pub fn get_discovered_sources_no_check(&mut self) -> Vec<DiscoveredSacnSource> {
680
        self.discovered_sources.clone()
681
    }
682

            
683
    /// Returns a list of the sources that have been discovered on the network by this receiver through the E1.31 universe discovery mechanism.
684
823
    pub fn get_discovered_sources(&mut self) -> Vec<DiscoveredSacnSource> {
685
823
        self.remove_expired_sources();
686
823
        self.discovered_sources.clone()
687
823
    }
688

            
689
    /// Sets the value of the `announce_source_discovery` flag to the given value.
690
    ///
691
    /// By default this flag is false which indicates that when receiving data discovered sources through universe discovery
692
    ///  won't be announced by the recv method and the receivers list of discovered universes will be updated silently.
693
    /// If set to true then it means that a `SourceDiscovered` error will be thrown whenever a source is discovered through a
694
    ///  complete universe discovery packet. A source that keeps advertising the same universes is announced once, and again
695
    ///  only if its name or universe list changes.
696
    ///
697
    /// # Arguments:
698
    /// `new_val`: The new value for the `announce_source_discovery` flag.
699
7
    pub fn set_announce_source_discovery(&mut self, new_val: bool) {
700
7
        self.announce_source_discovery = new_val;
701
7
    }
702

            
703
    /// Returns the current value of the `announce_timeout` flag.
704
    /// See [`set_announce_timeout`](Self::set_announce_timeout) for an explanation of the flag.
705
1
    pub fn get_announce_timeout(&self) -> bool {
706
1
        self.announce_timeout
707
1
    }
708

            
709
    /// Sets the value of the `announce_timeout` flag to the given value.
710
    ///
711
    /// By default this flag is false which means that if a universe for a source times out due to data not being sent then
712
    /// this will be updated on the receiver silently.
713
    /// If set to true then a `UniverseTimeout` error will be thrown when attempting to receive if it is detected that a source universe has
714
    /// timed out as per ANSI E1.31-2018 Section 6.7.1.
715
    ///
716
    /// # Arguments:
717
    /// `new_val`: The new value for the `announce_timeout` flag.
718
3
    pub fn set_announce_timeout(&mut self, new_val: bool) {
719
3
        self.announce_timeout = new_val;
720
3
    }
721

            
722
    /// Returns the current value of the `announce_stream_termination` flag.
723
    /// See [`set_announce_stream_termination`](Self::set_announce_stream_termination) for an explanation of the flag.
724
1
    pub fn get_announce_stream_termination(&self) -> bool {
725
1
        self.announce_stream_termination
726
1
    }
727

            
728
    /// Sets the value of the `announce_stream_termination` flag to the given value.
729
    ///
730
    /// By default this flag is false. This indicates that if a source sends a stream termination packet it will be handled silently by the receiver.
731
    /// If set to true then a `UniverseTermination` error will be thrown when attempting to receive if a termination packet is received as per
732
    /// ANSI E1.31-2018 Section 6.2.6.
733
4
    pub fn set_announce_stream_termination(&mut self, new_val: bool) {
734
4
        self.announce_stream_termination = new_val;
735
4
    }
736

            
737
    /// Handles the given data packet for this DMX receiver.
738
    ///
739
    /// Returns the universe data if successful.
740
    /// If the returned value is None it indicates that the data was received successfully but isn't ready to act on.
741
    ///
742
    /// Synchronised data packets handled as per ANSI E1.31-2018 Section 6.2.4.1.
743
    ///
744
    /// Arguments:
745
    /// `data_pkt`: The sACN data packet to handle.
746
    ///
747
    /// # Errors
748
    /// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
749
    /// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
750
    ///
751
    /// Returns a `UniversesTerminated` error if a packet is received with the `stream_terminated` flag set indicating that the source is no longer
752
    /// sending on that universe and the `announce_stream_termination_flag` is set to true.
753
    ///
754
    /// Will return an `DmxMergeError` if there is an issue merging or replacing new and existing waiting data.
755
2278
    fn handle_data_packet(
756
2278
        &mut self,
757
2278
        cid: Uuid,
758
2278
        data_pkt: DataPacketFramingLayer<'_>,
759
2278
    ) -> Result<Option<Vec<DMXData>>> {
760
        // Termination is handled before the preview filter: as per ANSI E1.31-2016 Section 6.2.6 a packet with Stream_Terminated set
761
        // ends the stream whatever its other options are, so a terminating source that also marks its data as preview still terminates.
762
2278
        if data_pkt.stream_terminated {
763
16
            log_debug!(
764
                "sACN source {cid} terminated universe {}",
765
                data_pkt.universe
766
            );
767
16
            self.terminate_stream(cid, data_pkt.universe);
768
16
            if self.announce_stream_termination {
769
4
                return Err(SacnError::UniverseTerminated(cid, data_pkt.universe));
770
12
            }
771
12
            return Ok(None);
772
2262
        }
773

            
774
2262
        if data_pkt.preview_data && !self.process_preview_data {
775
            // Don't process preview data unless receiver has process_preview_data flag set.
776
2
            log_debug!(
777
                "Ignoring sACN preview data from {cid} on universe {} because preview data processing is off",
778
                data_pkt.universe
779
            );
780
2
            return Ok(None);
781
2260
        }
782

            
783
2260
        if !self.is_listening(&data_pkt.universe) {
784
            // If not listening for this universe then ignore the packet.
785
5
            log_debug!(
786
                "Ignoring sACN data from {cid} on universe {}, which this receiver isn't listening to",
787
                data_pkt.universe
788
            );
789
5
            return Ok(None);
790
2255
        }
791

            
792
        // Preview data and stream terminated both get precedence over checking the sequence number.
793
        // This is as per ANSI E1.31-2018 Section 6.2.6, Stream_Terminated: Bit 6, 'Any property values
794
        // in an E1.31 Data Packet containing this bit shall be ignored'
795

            
796
        // Only Null START Code data keeps a source alive. Sources must send Null START Code keep-alives at least every second
797
        // (ANSI E1.31-2016 Section 6.6.2) while alternate START Codes such as 0xDD per-address priority carry no levels, so a
798
        // source that only sends alternate START Code data has lost its data and times out.
799
2255
        let null_start_code = data_pkt.data.property_values.first() == Some(&E131_NULL_START_CODE);
800

            
801
2255
        self.sequences.check_data_seq_number(
802
2255
            self.source_limit,
803
2255
            cid,
804
2255
            data_pkt.sequence_number,
805
2255
            data_pkt.universe,
806
2255
            self.announce_timeout,
807
2255
            null_start_code,
808
2255
        )?;
809

            
810
        // As per ANSI E1.31-2016 Section 11.1.1 a receiver begins synchronising on receipt of the first synchronisation packet,
811
        // so until one has been received on this packet's synchronisation address the data is processed immediately.
812
        // Once synchronisation has started and is then lost, Section 6.2.6 and 11.1.2 apply: with the Force_Synchronization
813
        // option set the data doesn't have to wait for a synchronisation packet, and without it the data is held until
814
        // synchronisation resumes.
815
2234
        let process_unsynchronized = data_pkt.synchronization_address != E131_NO_SYNC_ADDR
816
1105
            && (!self.sync_started(data_pkt.synchronization_address)
817
1090
                || (data_pkt.force_synchronization
818
2
                    && !self.is_synchronized(data_pkt.synchronization_address)));
819

            
820
2234
        if process_unsynchronized {
821
            // Keep listening on the synchronisation address so synchronisation can resume.
822
16
            self.track_sync_universe(data_pkt.synchronization_address)?;
823
2218
        }
824

            
825
2234
        if data_pkt.synchronization_address == E131_NO_SYNC_ADDR || process_unsynchronized {
826
1145
            self.clear_waiting_data(data_pkt.universe);
827

            
828
1145
            let vals: Vec<u8> = data_pkt.data.property_values.into_owned();
829
1145
            let dmx_data: DMXData = DMXData {
830
1145
                universe: data_pkt.universe,
831
1145
                values: vals.clone(),
832
1145
                sync_uni: data_pkt.synchronization_address,
833
1145
                priority: data_pkt.priority,
834
1145
                src_cid: Some(cid),
835
1145
                preview: data_pkt.preview_data,
836
1145
                recv_timestamp: Instant::now(),
837
1145
            };
838

            
839
1145
            Ok(Some(vec![dmx_data]))
840
        } else {
841
            // As per ANSI E1.31-2018 Appendix B.2 the receiver should listen at the synchronisation address when a data packet is received with a non-zero
842
            // synchronisation address.
843
1089
            self.track_sync_universe(data_pkt.synchronization_address)?;
844

            
845
1089
            let vals: Vec<u8> = data_pkt.data.property_values.into_owned();
846
1089
            let dmx_data: DMXData = DMXData {
847
1089
                universe: data_pkt.universe,
848
1089
                values: vals.clone(),
849
1089
                sync_uni: data_pkt.synchronization_address,
850
1089
                priority: data_pkt.priority,
851
1089
                src_cid: Some(cid),
852
1089
                preview: data_pkt.preview_data,
853
1089
                recv_timestamp: Instant::now(),
854
1089
            };
855

            
856
1089
            self.store_waiting_data(dmx_data)?;
857
1089
            Ok(None)
858
        }
859
2278
    }
860

            
861
    /// Removes the given universe from the discovered sACN source with the given name, also stops tracking
862
    /// sequence numbers for that universe / sender combination.
863
    ///
864
    /// Note this is just a record keeping operation, it doesn't actually effect the real sACN sender it
865
    /// just updates the record of what universes are expected on this receiver.
866
    ///
867
    /// If the `src_cid/source_name/universe` isn't currently registered then this method has no effect.
868
    /// This is intentional as it allows calling this function multiple times without worrying about failure because
869
    /// it comes to the same result.
870
    ///     E.g. when a source terminates it sends 3 termination packets but a receiver should only terminate once.
871
    ///
872
    /// # Arguments:
873
    ///
874
    /// `src_cid`: The CID of the source which is terminating a universe.
875
    ///
876
    /// universe:    The sACN universe to remove.
877
16
    fn terminate_stream(&mut self, src_cid: Uuid, universe: u16) {
878
        // Will only return an error if the source/universe wasn't found which is acceptable because as it
879
        // comes to the same result.
880
16
        let _ = self.sequences.remove_seq_numbers(src_cid, universe);
881

            
882
        // As with sequence numbers the source might not be found which is acceptable.
883
16
        if let Some(index) = find_discovered_src(&self.discovered_sources, &src_cid) {
884
2
            self.discovered_sources[index].terminate_universe(universe);
885
14
        }
886
16
    }
887

            
888
    /// Takes the given data and tries to add it to the waiting data.
889
    ///
890
    /// Note that a receiver will only store a single packet of data per `data_universe` and start code at once.
891
    ///
892
    /// If there is waiting data for the same universe and start code as the data then it will be merged as per the
893
    /// `merge_func` which by default keeps the highest priority data, if the data has the same priority
894
    /// then the newest data is kept.
895
    ///
896
    /// # Errors
897
    /// Will return an `DmxMergeError` if there is an issue merging or replacing new and existing waiting data.
898
1101
    fn store_waiting_data(&mut self, data: DMXData) -> Result<()> {
899
1101
        let key = (data.universe, data.values.first().copied().unwrap_or(0));
900
1101
        match self.waiting_data.remove(&key) {
901
            Some(existing) => {
902
5
                self.waiting_data
903
5
                    .insert(key, ((self.merge_func)(&existing, &data))?);
904
            }
905
            None => {
906
1096
                self.waiting_data.insert(key, data);
907
            }
908
        }
909
1101
        Ok(())
910
1101
    }
911

            
912
    /// Handles the given synchronisation packet for this DMX receiver.
913
    ///
914
    /// Synchronisation packets handled as described by ANSI E1.31-2018 Section 6.2.4.1.
915
    ///
916
    /// Returns the released / previously blocked data if successful.
917
    /// If the returned Vec is empty it indicates that no data was waiting.
918
    ///
919
    /// E1.31 Synchronization Packets occur on specific universes. Upon receipt, they indicate that any data advertising that universe as its Synchronization Address must be acted upon.
920
    /// In an E1.31 Data Packet, a value of 0 in the Synchronization Address indicates that the universe data is not synchronized. If a receiver is presented with an E1.31 Data Packet
921
    /// containing a Synchronization Address of 0, it shall discard any data waiting to be processed and immediately act on that Data Packet.
922
    ///
923
    /// If the Synchronization Address field is not 0, and the receiver is receiving an active synchronization stream for that Synchronization Address,
924
    /// it shall hold that E1.31 Data Packet until the arrival of the appropriate E1.31 Synchronization Packet before acting on it.
925
    ///
926
    /// Arguments:
927
    /// `sync_pkt`: The E1.31 synchronisation part of the synchronisation packet to handle.
928
    ///
929
    /// # Errors
930
    /// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
931
    /// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
932
1355
    fn handle_sync_packet(
933
1355
        &mut self,
934
1355
        cid: Uuid,
935
1355
        sync_pkt: SynchronizationPacketFramingLayer,
936
1355
    ) -> Result<Option<Vec<DMXData>>> {
937
1355
        if !self.is_listening(&sync_pkt.synchronization_address)
938
16
            && !self
939
16
                .sync_universes
940
16
                .contains_key(&sync_pkt.synchronization_address)
941
        {
942
            // If not listening for this universe then ignore the packet.
943
2
            log_debug!(
944
                "Ignoring sACN sync packet from {cid} on sync address {}, which this receiver isn't tracking",
945
                sync_pkt.synchronization_address
946
            );
947
2
            return Ok(None);
948
1353
        }
949

            
950
1353
        self.sequences.check_sync_seq_number(
951
1353
            self.source_limit,
952
1353
            cid,
953
1353
            sync_pkt.sequence_number,
954
1353
            sync_pkt.synchronization_address,
955
1353
            self.announce_timeout,
956
1353
        )?;
957

            
958
1333
        self.last_sync_packets
959
1333
            .insert(sync_pkt.synchronization_address, Instant::now());
960

            
961
1333
        let res = self.rtrv_waiting_data(sync_pkt.synchronization_address);
962
1333
        if res.is_empty() {
963
786
            Ok(None)
964
        } else {
965
547
            Ok(Some(res))
966
        }
967
1355
    }
968

            
969
    /// Retrieves and removes the DMX data of all waiting data with a synchronisation address matching the one provided.
970
    /// Returns an empty Vec if there is no data waiting.
971
    ///
972
    /// Arguments:
973
    /// `sync_uni`: The synchronisation universe of the data that should be retrieved.
974
1342
    fn rtrv_waiting_data(&mut self, sync_uni: u16) -> Vec<DMXData> {
975
        // Get the universes (used as keys) to remove and then move the corresponding data out of the waiting data and into the result.
976
        // This prevents having to copy DMXData.
977
        // Cannot do both actions at once as cannot modify a data structure while iterating over it.
978
1342
        let mut keys: Vec<(u16, u8)> = Vec::new();
979
1342
        for (key, data) in self.waiting_data.iter() {
980
1093
            if data.sync_uni == sync_uni {
981
1089
                keys.push(*key);
982
4
            }
983
        }
984
        // Release the data in a stable order: by universe, then start code.
985
1342
        keys.sort_unstable();
986

            
987
1342
        let mut res: Vec<DMXData> = Vec::new();
988
1342
        for k in keys {
989
1089
            let data = self.waiting_data.remove(&k).unwrap();
990
1089
            if data.recv_timestamp.elapsed() < E131_NETWORK_DATA_LOSS_TIMEOUT {
991
1089
                res.push(data);
992
            }
993
        }
994

            
995
1342
        res
996
1342
    }
997

            
998
    /// Takes the given `DiscoveredSacnSource` and updates the record of discovered sacn sources.
999
    ///
    /// This adds the new source, replacing any previous record of a source with the same CID.
    ///
    /// Returns true if the source is new, or if its name or universe list differs from the previous record. Sources
    /// re-advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`, so an unchanged advert returns false.
    ///
    /// Arguments:
    /// src: The `DiscoveredSacnSource` to update the record of discovered sacn sources with.
32
    fn update_discovered_srcs(&mut self, src: DiscoveredSacnSource) -> bool {
32
        let changed = match find_discovered_src(&self.discovered_sources, &src.cid) {
            Some(index) => {
13
                let old = self.discovered_sources.remove(index);
                // An expired record that hasn't been pruned yet counts as a new discovery.
13
                old.last_updated.elapsed() >= UNIVERSE_DISCOVERY_SOURCE_TIMEOUT
12
                    || old.name != src.name
11
                    || old.get_all_universes() != src.get_all_universes()
            }
19
            None => true,
        };
32
        self.discovered_sources.push(src);
32
        changed
32
    }
    /// Handles the given universe discovery packet.
    ///
    /// This universe discovery packet might be the whole thing or may be just one page of a discovery packet.
    /// This method puts the pages to produce the `DiscoveredSacnSource` which is stored in the receiver.
    ///
    /// Returns the source name if a source was fully discovered and is either new or has changed its name or universe list
    /// since its last advert. Returns None if the source was only partially discovered, or if the advert repeats what is
    /// already known about it.
    ///
    /// Arguments:
    ///
    /// cid: the source CID.
    ///
    /// `discovery_pkt`: The universe discovery part of the universe discovery packet to handle.
42
    fn handle_universe_discovery_packet(
42
        &mut self,
42
        cid: Uuid,
42
        discovery_pkt: UniverseDiscoveryPacketFramingLayer<'_>,
42
    ) -> Option<String> {
42
        let data = discovery_pkt.data;
42
        let page: u8 = data.page;
42
        let last_page: u8 = data.last_page;
42
        let universes = data.universes;
42
        let uni_page: UniversePage = UniversePage {
42
            page,
42
            universes: universes.into(),
42
        };
        // See if some pages that belong to the source that this page belongs to have already been received.
42
        if let Some(index) = find_discovered_src(&self.partially_discovered_sources, &cid) {
            // Some pages have already been received from this source.
10
            let partial = &mut self.partially_discovered_sources[index];
10
            if partial.last_page != last_page {
                // The source's universe list has changed size since the earlier pages were sent, so they are stale.
1
                log_debug!(
                    "Discarding {} sACN universe discovery pages from {cid}: its page count changed from {} to {last_page}",
                    partial.pages.len(),
                    partial.last_page + 1,
                    last_page = last_page + 1
                );
1
                partial.last_page = last_page;
1
                partial.pages.clear();
9
            }
            // A page can arrive again in the next discovery interval, for example if another page was lost.
            // Replace the earlier copy rather than storing it twice, which would stop has_all_pages() ever succeeding.
10
            partial.pages.retain(|p| p.page != page);
10
            partial.pages.push(uni_page);
10
            partial.name = discovery_pkt.source_name.to_string();
10
            partial.last_updated = Instant::now();
10
            if self.partially_discovered_sources[index].has_all_pages() {
                let discovered_src: DiscoveredSacnSource =
8
                    self.partially_discovered_sources.remove(index);
8
                if self.update_discovered_srcs(discovered_src) {
7
                    return Some(discovery_pkt.source_name.to_string());
1
                }
2
            }
        } else {
            // This is the first page received from this source.
32
            let discovered_src: DiscoveredSacnSource = DiscoveredSacnSource {
32
                name: discovery_pkt.source_name.to_string(),
32
                cid,
32
                last_page,
32
                pages: vec![uni_page],
32
                last_updated: Instant::now(),
32
            };
32
            if page == 0 && page == last_page {
                // Indicates that this is a single page universe discovery packet.
24
                if self.update_discovered_srcs(discovered_src) {
16
                    return Some(discovery_pkt.source_name.to_string());
8
                }
            } else {
                // Indicates that this is a page in a set of pages as part of a sources universe discovery.
8
                self.partially_discovered_sources.push(discovered_src);
            }
        }
19
        None // No source fully discovered.
42
    }
    /// Records that a received data packet named `sync_uni` as its synchronisation address, joining that universe's
    /// multicast group if it isn't joined already so that the synchronisation packets are received.
    ///
    /// # Errors
    /// Returns an error if the multicast group cannot be joined. The universe isn't recorded in that case, so joining is
    /// tried again with the next data packet that names it.
1105
    fn track_sync_universe(&mut self, sync_uni: u16) -> Result<()> {
1105
        if !self.sync_universes.contains_key(&sync_uni)
33
            && !self.is_listening(&sync_uni)
9
            && self.is_multicast_enabled()
        {
9
            self.receiver.listen_multicast_universe(sync_uni)?;
1096
        }
1105
        self.sync_universes.insert(sync_uni, Instant::now());
1105
        Ok(())
1105
    }
    /// Stops tracking synchronisation universes that no data packet has named for `E131_NETWORK_DATA_LOSS_TIMEOUT`,
    /// leaving their multicast groups unless the user listens to that universe.
3713
    fn expire_sync_universes(&mut self) {
3713
        let expired: Vec<u16> = self
3713
            .sync_universes
3713
            .iter()
1639
            .filter(|(_, last)| last.elapsed() >= E131_NETWORK_DATA_LOSS_TIMEOUT)
3
            .map(|(u, _)| *u)
            .collect();
3713
        for u in expired {
3
            self.sync_universes.remove(&u);
3
            log_debug!("No sACN data has named sync address {u} recently; no longer tracking it");
3
            if !self.is_listening(&u)
2
                && self.is_multicast_enabled()
2
                && let Err(e) = self.receiver.mute_multicast_universe(u)
            {
                // Nothing more can be done if leaving fails; the membership ends when the socket closes.
                log_warn!("Failed to leave the sACN multicast group of sync address {u}: {e:?}");
3
            }
        }
3713
    }
    /// Returns true if a synchronisation packet has ever been received on the given synchronisation address, meaning
    /// synchronisation on that address has started as per ANSI E1.31-2016 Section 11.1.1.
1105
    fn sync_started(&self, sync_addr: u16) -> bool {
1105
        self.last_sync_packets.contains_key(&sync_addr)
1105
    }
    /// Returns true if a synchronisation packet has been received on the given synchronisation address within
    /// `E131_NETWORK_DATA_LOSS_TIMEOUT`, meaning synchronisation on that address is active as per ANSI E1.31-2016 Section 11.1.
2
    fn is_synchronized(&self, sync_addr: u16) -> bool {
2
        self.last_sync_packets
2
            .get(&sync_addr)
2
            .is_some_and(|t| t.elapsed() < E131_NETWORK_DATA_LOSS_TIMEOUT)
2
    }
    /// Goes through all the waiting data and removes any which has timed out as a sync-packet for it hasn't been received within the `E131_NETWORK_DATA_LOSS_TIMEOUT`
    /// period as specified by ANSI E1.31-2018 Section 11.1.2.
3711
    fn check_waiting_data_timeouts(&mut self) {
3711
        self.waiting_data.retain(|(uni, start_code), data| {
1629
            let keep = data.recv_timestamp.elapsed() < E131_NETWORK_DATA_LOSS_TIMEOUT;
1629
            if !keep {
1
                log_debug!(
                    "Discarding sACN data held for universe {uni} (start code {start_code:#04x}): no sync packet arrived on sync address {}",
                    data.sync_uni
                );
1628
            }
1629
            keep
1629
        });
3711
    }
    /// Goes through all discovered sources and removes any that have timed out
823
    fn remove_expired_sources(&mut self) {
823
        self.partially_discovered_sources
            .retain(|s| s.last_updated.elapsed() < UNIVERSE_DISCOVERY_SOURCE_TIMEOUT);
823
        self.discovered_sources.retain(|s| {
406
            let keep = s.last_updated.elapsed() < UNIVERSE_DISCOVERY_SOURCE_TIMEOUT;
406
            if !keep {
2
                log_debug!("Discovered sACN source {} ({}) timed out", s.name, s.cid);
404
            }
406
            keep
406
        });
823
    }
}
/// By implementing the Drop trait for `SacnNetworkReceiver` it means that the user doesn't have to explicitly clean up the receiver
/// and if it goes out of reference it will clean itself up.
impl Drop for SacnReceiver {
619
    fn drop(&mut self) {
619
        let universes = self.universes.clone();
        // Leave the groups joined only for synchronisation first; mute_universe would otherwise skip them.
619
        let sync_only: Vec<u16> = self
619
            .sync_universes
619
            .keys()
30
            .filter(|u| !self.is_listening(u))
            .copied()
            .collect();
619
        self.sync_universes.clear();
619
        for u in sync_only {
7
            if let Err(e) = self.receiver.mute_multicast_universe(u) {
                log_warn!(
                    "sACN receiver failed to leave the multicast group of sync address {u} while being dropped: {e:?}"
                );
7
            }
        }
619
        for u in universes {
            // Cannot return an error or pass it onto the user because drop might be called during a panic.
            // Therefore if there is an error cleaning up the only options are ignore, notify or panic.
            // Notify using stdout might pollute the application using the library so would require a flag to enable/disable but the function of this
            // is unclear and the problem isn't solved if the flag is disabled.
            // A panic might be unnecessary or pollute another in-progress panic hiding the true problem. It would also prevent muting the other
            // universes.
            // The error is therefore ignored as it can't be fixed eitherway as the SacnReceiver has gone out of scope and won't lead to memory un-safety.
1267
            if let Err(e) = self.mute_universe(u) {
1
                log_warn!(
                    "sACN receiver failed to leave the multicast group of universe {u} while being dropped: {e:?}"
                );
1266
            }
        }
619
    }
}
/// Searches for the discovered source with the given name in the given vector of discovered sources and
/// returns the index of the src in the Vec or None if not found.
///
/// Arguments:
///
/// srcs: The Vec of `DiscoveredSacnSources` to search.
///
/// cid: The CID (uuid) of the source to find.
/// Parses the `n` bytes of a received datagram held at the start of `buf`.
///
/// Only the bytes actually received are parsed, so a truncated datagram is rejected by the length checks
/// in the parser rather than being padded out with whatever is left in the rest of the buffer.
///
/// # Errors
/// `TooManyBytesRead`: Returned if `n` is larger than the buffer.
///
/// Otherwise returns any error from `AcnRootLayerProtocol::parse`.
2062
fn parse_datagram(buf: &[u8], n: usize) -> Result<AcnRootLayerProtocol<'_>> {
2062
    if n > buf.len() {
1
        return Err(SacnError::TooManyBytesRead(n, buf.len()));
2061
    }
2061
    AcnRootLayerProtocol::parse(&buf[..n])
2062
}
90
fn find_discovered_src(srcs: &[DiscoveredSacnSource], cid: &Uuid) -> Option<usize> {
90
    (0..srcs.len()).find(|&i| srcs[i].cid == *cid)
90
}
/// In general the lower level transport layer is handled by `SacnNetworkReceiver` (which itself wraps a Socket).
/// Windows and linux handle multicast sockets differently.
/// This is built for / tested with Windows 10 1909.
#[cfg(target_os = "windows")]
impl SacnNetworkReceiver {
    /// Creates a new DMX receiver on the interface specified by the given address.
    ///
    /// If the given address is an IPv4 address then communication will only work between IPv4 devices, if the given address is IPv6 then communication
    /// will only work between IPv6 devices by default but IPv4 receiving can be enabled using `set_ipv6_only(false)`.
    ///
    /// # Errors
    /// Will return an error if the `SacnReceiver` fails to bind to a socket with the given ip.
    /// For more details see `socket2::Socket::new()`.
    fn new(ip: SocketAddr) -> Result<SacnNetworkReceiver> {
        Ok(SacnNetworkReceiver {
            socket: create_win_socket(ip)?,
            addr: ip,
            is_multicast_enabled: !(ip.is_ipv6()), // IPv6 Windows IP Multicast is currently unsupported.
        })
    }
    /// Connects this `SacnNetworkReceiver` to the multicast address which corresponds to the given universe to allow receiving packets for that universe.
    ///
    /// # Errors
    /// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
    /// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
    ///
    /// Will return an Io error if cannot join the universes corresponding multicast group address.
    fn listen_multicast_universe(&self, universe: u16) -> Result<()> {
        let multicast_addr = if self.addr.is_ipv4() {
            universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
        } else {
            universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
        };
        join_win_multicast(&self.socket, multicast_addr, self.addr.ip())
    }
    /// Removes this `SacnNetworkReceiver` from the multicast group which corresponds to the given universe.
    ///
    /// # Errors
    /// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
    /// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
    fn mute_multicast_universe(&mut self, universe: u16) -> Result<()> {
        let multicast_addr = if self.addr.is_ipv4() {
            universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
        } else {
            universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
        };
        leave_win_multicast(&self.socket, multicast_addr)
    }
    /// Sets the value of the `is_multicast_enabled` flag to the given value.
    ///
    /// If set to false then the receiver won't attempt to join any more multicast groups.
    ///
    /// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
    ///
    /// # Arguments
    /// val: The new value for the `is_multicast_enabled` flag.
    ///
    /// # Errors
    /// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
    /// isn't supported i.e. Ipv6 on Windows.
    fn set_is_multicast_enabled(&mut self, val: bool) -> Result<()> {
        if val && self.is_ipv6() {
            return Err(SacnError::OsOperationUnsupported(
                "IPv6 multicast is currently unsupported on Windows".to_string(),
            ));
        }
        self.is_multicast_enabled = val;
        Ok(())
    }
    /// Returns true if multicast is enabled on this receiver and false if not.
    /// This flag is set when the receiver is created as not all environments currently support IP multicast.
    /// E.g. IPv6 Windows IP Multicast is currently unsupported.
    fn is_multicast_enabled(&self) -> bool {
        self.is_multicast_enabled
    }
    /// If set to true then only receive over IPv6. If false then receiving will be over both IPv4 and IPv6.
    /// This will return an error if the `SacnReceiver` wasn't created using an IPv6 address to bind to.
    fn set_only_v6(&mut self, val: bool) -> Result<()> {
        if self.addr.is_ipv4() {
            Err(SacnError::IpVersionError())
        } else {
            Ok(self.socket.set_only_v6(val)?)
        }
    }
    /// Returns a packet if there is one available.
    ///
    /// The packet may not be ready to transmit if it is awaiting synchronisation.
    /// Will only block if `set_timeout` was called with a timeout of None so otherwise (and by default) it won't
    /// block so may return a WouldBlock/TimedOut error to indicate that there was no data ready.
    ///
    /// IMPORTANT NOTE:
    /// An explicit lifetime is given to the `AcnRootLayerProtocol` which comes from the lifetime of the given buffer.
    /// The compiler will prevent usage of the returned `AcnRootLayerProtocol` after the buffer is dropped normally but may not in the case
    /// of unsafe code .
    ///
    /// Arguments:
    /// buf: The buffer to use for storing the received data into. This buffer shouldn't be accessed or used directly as the data
    /// is returned formatted properly in the `AcnRootLayerProtocol`. This buffer is used as memory space for the returned `AcnRootLayerProtocol`.
    ///
    /// # Errors
    /// May return an error if there is an issue receiving data from the underlying socket, see (recv)[fn.recv.Socket].
    ///
    /// May return an error if there is an issue parsing the data from the underlying socket, see (parse)[`fn.AcnRootLayerProtocol::parse.packet`].
    fn recv<'a>(
        &mut self,
        buf: &'a mut [u8; RCV_BUF_DEFAULT_SIZE],
    ) -> Result<AcnRootLayerProtocol<'a>> {
        // use read() for the windows impl, since windows does not like using read_exact()
        let n = self.socket.read(buf)?;
        parse_datagram(buf, n)
    }
    /// Set the timeout for the recv operation.
    ///
    /// Arguments:
    /// timeout: The new timeout for the receive operation, a value of None means the recv operation will become blocking.
    ///
    /// Errors:
    /// A timeout with Duration 0 will cause an error. See (`set_read_timeout`)[`fn.set_read_timeout.Socket`].
    fn set_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
        Ok(self.socket.set_read_timeout(timeout)?)
    }
    /// Returns true if this `SacnNetworkReceiver` is bound to an Ipv6 address.
    fn is_ipv6(&self) -> bool {
        self.addr.is_ipv6()
    }
}
/// Windows and linux handle multicast sockets differently.
/// This is built for / tested with Fedora 30/31.
#[cfg(not(target_os = "windows"))]
impl SacnNetworkReceiver {
    /// Creates a new DMX receiver on the interface specified by the given address.
    ///
    /// If the given address is an IPv4 address then communication will only work between IPv4 devices, if the given address is IPv6 then communication
    /// will only work between IPv6 devices by default but IPv4 receiving can be enabled using `set_ipv6_only(false)`.
    ///
    /// # Errors
    /// Will return an Io error if the `SacnReceiver` fails to bind to a socket with the given ip.
    /// For more details see `socket2::Socket::new()`.
619
    fn new(ip: SocketAddr) -> Result<SacnNetworkReceiver> {
        Ok(SacnNetworkReceiver {
619
            socket: create_unix_socket(ip)?,
619
            addr: ip,
619
            is_multicast_enabled: true, // Linux IP Multicast is supported for Ipv4 and Ipv6.
        })
619
    }
    /// Connects this `SacnNetworkReceiver` to the multicast address which corresponds to the given universe to allow receiving packets for that universe.
    ///
    /// # Errors
    /// Will return an Error if the given universe cannot be converted to an IPv4 or IPv6 `multicast_addr` depending on if the Receiver is bound to an
    /// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
    ///
    /// Will return an Io error if cannot join the universes corresponding multicast group address.
1275
    fn listen_multicast_universe(&self, universe: u16) -> Result<()> {
1275
        let multicast_addr = if self.addr.is_ipv4() {
1221
            universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
        } else {
54
            universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
        };
1275
        join_unix_multicast(&self.socket, multicast_addr, self.addr.ip())
1275
    }
    /// Removes this `SacnNetworkReceiver` from the multicast group which corresponds to the given universe.
    ///
    /// # Errors
    /// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
    /// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
1277
    fn mute_multicast_universe(&mut self, universe: u16) -> Result<()> {
1277
        let multicast_addr = if self.addr.is_ipv4() {
1223
            universe_to_ipv4_multicast_addr(universe)?
        } else {
54
            universe_to_ipv6_multicast_addr(universe)?
        };
1277
        leave_unix_multicast(&self.socket, multicast_addr, self.addr.ip())
1277
    }
    /// Sets the value of the `is_multicast_enabled` flag to the given value.
    ///
    /// If set to false then the receiver won't attempt to join any more multicast groups.
    ///
    /// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
    ///
    /// # Arguments
    /// val: The new value for the `is_multicast_enabled` flag.
    ///
    /// # Errors
    /// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
    /// isn't supported i.e. Ipv6 on Windows. Note that this is the UNIX implementation
2
    fn set_is_multicast_enabled(&mut self, val: bool) -> Result<()> {
2
        self.is_multicast_enabled = val;
2
        Ok(())
2
    }
    /// Returns true if multicast is enabled on this receiver and false if not.
    /// This flag is set when the receiver is created as not all environments currently support IP multicast.
    /// E.g. IPv6 Windows IP Multicast is currently unsupported.
1281
    fn is_multicast_enabled(&self) -> bool {
1281
        self.is_multicast_enabled
1281
    }
    /// If set to true then only receive over IPv6. If false then receiving will be over both IPv4 and IPv6.
    /// This will return an error if the `SacnReceiver` wasn't created using an IPv6 address to bind to.
    fn set_only_v6(&mut self, val: bool) -> Result<()> {
        if self.addr.is_ipv4() {
            Err(SacnError::IpVersionError())
        } else {
            Ok(self.socket.set_only_v6(val)?)
        }
    }
    /// Returns a packet if there is one available.
    ///
    /// The packet may not be ready to transmit if it is awaiting synchronisation.
    /// Will only block if `set_timeout` was called with a timeout of None so otherwise (and by default) it won't
    /// block so may return a WouldBlock/TimedOut error to indicate that there was no data ready.
    ///
    /// IMPORTANT NOTE:
    /// An explicit lifetime is given to the `AcnRootLayerProtocol` which comes from the lifetime of the given buffer.
    /// The compiler will prevent usage of the returned `AcnRootLayerProtocol` after the buffer is dropped.
    ///
    /// Arguments:
    /// buf: The buffer to use for storing the received data into. This buffer shouldn't be accessed or used directly as the data
    /// is returned formatted properly in the `AcnRootLayerProtocol`. This buffer is used as memory space for the returned `AcnRootLayerProtocol`.
    ///
    /// # Errors
    /// May return an error if there is an issue receiving data from the underlying socket, see (recv)[fn.recv.Socket].
    ///
    /// May return an error if there is an issue parsing the data from the underlying socket, see (parse)[`fn.AcnRootLayerProtocol::parse.packet`].
2891
    fn recv<'a>(
2891
        &mut self,
2891
        buf: &'a mut [u8; RCV_BUF_DEFAULT_SIZE],
2891
    ) -> Result<AcnRootLayerProtocol<'a>> {
        // use read() since read_exact() was not passing the tests.
2891
        let n = self.socket.read(buf)?;
2059
        parse_datagram(buf, n)
2891
    }
    /// Set the timeout for the recv operation.
    ///
    /// Arguments:
    /// timeout: The new timeout for the receive operation, a value of None means the recv operation will become blocking.
    ///
    /// Errors:
    /// A timeout with Duration 0 will cause an error. See (`set_read_timeout`)[`fn.set_read_timeout.Socket`].
2891
    fn set_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
2891
        Ok(self.socket.set_read_timeout(timeout)?)
2891
    }
}
impl Clone for DMXData {
320
    fn clone(&self) -> DMXData {
320
        let new_vals = self.values.clone(); // https://stackoverflow.com/questions/21369876/what-is-the-idiomatic-rust-way-to-copy-clone-a-vector-in-a-parameterized-functio (26/12/2019)
320
        DMXData {
320
            universe: self.universe,
320
            values: new_vals,
320
            sync_uni: self.sync_uni,
320
            priority: self.priority,
320
            src_cid: self.src_cid,
320
            preview: self.preview,
320
            recv_timestamp: self.recv_timestamp,
320
        }
320
    }
}
/// `DMXData` has a total ordering based on the universe, then sync-universe and finally values.
impl Ord for DMXData {
37
    fn cmp(&self, other: &Self) -> Ordering {
37
        self.universe
37
            .cmp(&other.universe)
37
            .then(self.sync_uni.cmp(&other.sync_uni))
37
            .then(self.values.cmp(&other.values))
37
    }
}
/// See Ord trait implementation for `DMXData`.
impl PartialOrd for DMXData {
37
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
37
        Some(self.cmp(other))
37
    }
}
/// `DMXData` is taken to be equivalent iff:
///     - The universes are the same
///     - The synchronisation universes are the same
///     - The values are all the same
impl PartialEq for DMXData {
1
    fn eq(&self, other: &Self) -> bool {
1
        self.universe == other.universe
1
            && self.sync_uni == other.sync_uni
1
            && self.values == other.values
1
    }
}
/// See `PartialEq` trait implementation for `DMXData`.
impl Eq for DMXData {}
impl DiscoveredSacnSource {
    /// Returns true if all the pages sent by this `DiscoveredSacnSource` have been received.
    ///
    /// This is based on each page containing a last-page value which indicates the number of the last page expected.
10
    pub fn has_all_pages(&mut self) -> bool {
        // https://rust-lang-nursery.github.io/rust-cookbook/algorithms/sorting.html (31/12/2019)
16
        self.pages.sort_by_key(|a| a.page);
10
        for i in 0..=self.last_page {
20
            if self.pages.get(i as usize).is_none_or(|p| p.page != i) {
2
                return false;
18
            }
        }
8
        true
10
    }
    /// Returns all the universes being send by this `SacnSource` as discovered through the universe discovery mechanism.
    ///
    /// Intentionally abstracts over the underlying concept of pages as this is purely an E1.31 Universe Discovery concept and is otherwise transparent.
32
    pub fn get_all_universes(&self) -> Vec<u16> {
32
        let mut uni: Vec<u16> = Vec::new();
32
        for p in &self.pages {
40
            uni.extend_from_slice(&p.universes);
        }
32
        uni
32
    }
    /// Removes the given universe from the list of universes being sent by this discovered source.
2
    pub fn terminate_universe(&mut self, universe: u16) {
2
        for p in &mut self.pages {
6
            p.universes.retain(|x| *x != universe);
        }
2
    }
}
/// Creates a new Socket2 socket bound to the given address.
///
/// Returns the created socket.
///
/// Arguments:
/// addr: The address that the newly created socket should bind to.
///
/// # Errors
/// Will return an error if the socket cannot be created, see (`Socket::new`)[fn.new.Socket].
///
/// Will return an error if the socket cannot be bound to the given address, see (bind)[fn.bind.Socket2].
#[cfg(not(target_os = "windows"))]
619
fn create_unix_socket(addr: SocketAddr) -> Result<Socket> {
619
    if addr.is_ipv4() {
599
        let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
        // Multiple different processes might want to listen to the sACN stream so therefore need to allow re-using the ACN port.
        // If the OS doesn't support SO_REUSEPORT then ignore the error and continue.
        // FreeRTOS on ESP32 doesn't support SO_REUSEPORT and so this allows the library to be used on the platform without issue.
599
        if let Err(e) = socket.set_reuse_port(true) {
            if e.raw_os_error() != Some(libc::ENOPROTOOPT) {
                return Err(e.into());
            }
            log_debug!(
                "SO_REUSEPORT isn't supported on this platform; the sACN receiver is continuing without it"
            );
599
        }
599
        socket.set_reuse_address(true)?;
        let socket_addr =
599
            SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), ACN_SDT_MULTICAST_PORT);
599
        socket.bind(&socket_addr.into())?;
599
        Ok(socket)
    } else {
20
        let socket = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?;
        // Multiple different processes might want to listen to the sACN stream so therefore need to allow re-using the ACN port.
20
        if let Err(e) = socket.set_reuse_port(true) {
            if e.raw_os_error() != Some(libc::ENOPROTOOPT) {
                return Err(e.into());
            }
            log_debug!(
                "SO_REUSEPORT isn't supported on this platform; the sACN receiver is continuing without it"
            );
20
        }
20
        socket.set_reuse_address(true)?;
        let socket_addr =
20
            SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), ACN_SDT_MULTICAST_PORT);
20
        socket.bind(&socket_addr.into())?;
20
        Ok(socket)
    }
619
}
/// Joins the multicast group with the given address using the given socket.
///
/// Arguments:
/// socket: The socket to join to the multicast group.
/// addr:   The address of the multicast group to join.
///
/// # Errors
/// Will return an error if the given socket cannot be joined to the given multicast group address.
///     See `join_multicast_v4`[`fn.join_multicast_v4.Socket`] and `join_multicast_v6`[`fn.join_multicast_v6.Socket`]
///
/// Will return an `IpVersionError` if addr and `interface_addr` are not the same IP version.
#[cfg(not(target_os = "windows"))]
1275
fn join_unix_multicast(socket: &Socket, addr: SockAddr, interface_addr: IpAddr) -> Result<()> {
1275
    match addr.family() as i32 {
        // Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
1221
        AF_INET => match addr.as_socket_ipv4() {
1221
            Some(a) => match interface_addr {
                IpAddr::V4(ref interface_v4) => {
1221
                    socket
1221
                        .join_multicast_v4(a.ip(), interface_v4)
                        .map_err(|e| {
                            SacnError::Io(std::io::Error::new(
                                e.kind(),
                                "Failed to join IPv4 multicast",
                            ))
                        })?;
                }
                IpAddr::V6(ref _interface_v6) => {
                    return Err(SacnError::IpVersionError());
                }
            },
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
            }
        },
54
        AF_INET6 => match addr.as_socket_ipv6() {
            Some(a) => {
54
                socket.join_multicast_v6(a.ip(), 0).map_err(|e| {
                    SacnError::Io(std::io::Error::new(
                        e.kind(),
                        "Failed to join IPv6 multicast",
                    ))
                })?;
            }
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
            }
        },
        x => {
            return Err(SacnError::UnsupportedIpVersion(format!("IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {}", x).to_string()));
        }
    };
1275
    Ok(())
1275
}
/// Leaves the multicast group with the given address using the given socket.
///
/// Arguments:
/// socket: The socket to leave the multicast group.
/// addr:   The address of the multicast group to leave.
///
/// # Errors
/// Will return an error if the given socket cannot leave the given multicast group address.
///     See `leave_multicast_v4`[`fn.leave_multicast_v4.Socket`] and `leave_multicast_v6`[`fn.leave_multicast_v6.Socket`]
///
/// Will return an `IpVersionError` if addr and `interface_addr` are not the same IP version.
#[cfg(not(target_os = "windows"))]
1277
fn leave_unix_multicast(socket: &Socket, addr: SockAddr, interface_addr: IpAddr) -> Result<()> {
1277
    match addr.family() as i32 {
        // Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
1223
        AF_INET => match addr.as_socket_ipv4() {
1223
            Some(a) => match interface_addr {
                IpAddr::V4(ref interface_v4) => {
1223
                    socket
1223
                        .leave_multicast_v4(a.ip(), interface_v4)
2
                        .map_err(|e| {
2
                            SacnError::Io(std::io::Error::new(
2
                                e.kind(),
2
                                "Failed to leave IPv4 multicast",
2
                            ))
2
                        })?;
                }
                IpAddr::V6(ref _interface_v6) => {
                    return Err(SacnError::IpVersionError());
                }
            },
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
            }
        },
54
        AF_INET6 => match addr.as_socket_ipv6() {
            Some(a) => {
54
                socket.leave_multicast_v6(a.ip(), 0).map_err(|e| {
                    SacnError::Io(std::io::Error::new(
                        e.kind(),
                        "Failed to leave IPv6 multicast",
                    ))
                })?;
            }
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
            }
        },
        x => {
            return Err(SacnError::UnsupportedIpVersion(format!("IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {}", x).to_string()));
        }
    };
1275
    Ok(())
1277
}
/// Creates a new Socket2 socket bound to the given address.
///
/// Returns the created socket.
///
/// Arguments:
/// addr: The address that the newly created socket should bind to.
///
/// # Errors
/// Will return an error if the socket cannot be created, see (`Socket::new`)[fn.new.Socket].
///
/// Will return an error if the socket cannot be bound to the given address, see (bind)[fn.bind.Socket].
#[cfg(target_os = "windows")]
fn create_win_socket(addr: SocketAddr) -> Result<Socket> {
    if addr.is_ipv4() {
        let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
        socket.set_reuse_address(true)?;
        socket.bind(&SockAddr::from(addr))?;
        Ok(socket)
    } else {
        let socket = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?;
        socket.set_reuse_address(true)?;
        socket.bind(&SockAddr::from(addr))?;
        Ok(socket)
    }
}
/// Joins the multicast group with the given address using the given socket on the windows operating system.
///
/// Note that Ipv6 is currently unsupported.
///
/// Arguments:
/// socket: The socket to join to the multicast group.
/// addr:   The address of the multicast group to join.
///
/// # Errors
/// Will return an error if the given socket cannot be joined to the given multicast group address.
///     See `join_multicast_v4`[`fn.join_multicast_v4.Socket`] and `join_multicast_v6`[`fn.join_multicast_v6.Socket`]
///
/// Will return `OsOperationUnsupported` error if attempt to leave an Ipv6 multicast group as all Ipv6 multicast operations are currently unsupported in Rust on Windows.
#[cfg(target_os = "windows")]
fn join_win_multicast(socket: &Socket, addr: SockAddr, interface_addr: IpAddr) -> Result<()> {
    match addr.family() as i32 {
        // Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
        AF_INET => match addr.as_socket_ipv4() {
            Some(a) => match interface_addr {
                IpAddr::V4(ref interface_v4) => {
                    socket
                        .join_multicast_v4(a.ip(), interface_v4)
                        .map_err(|e| {
                            SacnError::Io(std::io::Error::new(
                                e.kind(),
                                "Failed to join IPv4 multicast",
                            ))
                        })?;
                }
                IpAddr::V6(ref _interface_v6) => {
                    return Err(SacnError::IpVersionError());
                }
            },
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
            }
        },
        AF_INET6 => match addr.as_socket_ipv6() {
            Some(a) => {
                socket.join_multicast_v6(a.ip(), 0).map_err(|e| {
                    SacnError::Io(std::io::Error::new(
                        e.kind(),
                        "Failed to join IPv6 multicast",
                    ))
                })?;
            }
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
            }
        },
        x => {
            return Err(SacnError::UnsupportedIpVersion(format!(
                "IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {x}"
            )));
        }
    };
    Ok(())
}
/// Leaves the multicast group with the given address using the given socket.
///
/// Note that Ipv6 is currently unsupported.
///
/// Arguments:
/// socket: The socket to leave the multicast group.
/// addr:   The address of the multicast group to leave.
///
/// # Errors
/// Will return an error if the given socket cannot leave the given multicast group address.
///     See `leave_multicast_v4`[`fn.leave_multicast_v4.Socket`] and `leave_multicast_v6`[`fn.leave_multicast_v6.Socket`]
///
/// Will return `OsOperationUnsupported` error if attempt to leave an Ipv6 multicast group as all Ipv6 multicast operations are currently unsupported in Rust on Windows.
#[cfg(target_os = "windows")]
fn leave_win_multicast(socket: &Socket, addr: SockAddr) -> Result<()> {
    match addr.family() as i32 {
        // Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
        AF_INET => match addr.as_socket_ipv4() {
            Some(a) => {
                socket
                    .leave_multicast_v4(a.ip(), &Ipv4Addr::new(0, 0, 0, 0))
                    .map_err(|e| {
                        SacnError::Io(std::io::Error::new(
                            e.kind(),
                            "Failed to leave IPv4 multicast",
                        ))
                    })?;
            }
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
            }
        },
        AF_INET6 => match addr.as_socket_ipv6() {
            Some(_) => {
                return Err(SacnError::OsOperationUnsupported(
                    "IPv6 multicast is currently unsupported on Windows".to_string(),
                ));
            }
            None => {
                return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
            }
        },
        x => {
            return Err(SacnError::UnsupportedIpVersion(format!(
                "IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {x}"
            )));
        }
    };
    Ok(())
}
/// Stores a sequence number and a timestamp.
///
/// Used internally within `SequenceNumbering` for tracking the last received timestamps of each packet-type, source, universe combination.
///
/// This is then used to workout timeouts to trigger network data loss as per ANSI E1.31-2018 Section 6.7.1.
#[derive(Copy, Clone)]
struct TimedStampedSeqNo {
    sequence_number: u8,
    last_recv: Instant,
}
impl TimedStampedSeqNo {
4289
    fn new(sequence_number: u8, last_recv: Instant) -> TimedStampedSeqNo {
4289
        TimedStampedSeqNo {
4289
            sequence_number,
4289
            last_recv,
4289
        }
4289
    }
}
/// Stores information about the current expected sequence numbers for each source, universe and packet type.
///
/// Also handles timeouts of sources.
///
/// Abstracts over the internal data-structures/mechanisms used allowing them be changed.
struct SequenceNumbering {
    /// The sequence numbers used for data packets, keeps a reference of the last sequence number received for each universe.
    /// Sequence numbers are always in the range [0, 255] inclusive.
    /// Each type of packet is tracked differently with respect to sequence numbers as per ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
    /// The uuid refers to the source that is sending the data.
    data_sequences: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>>,
    /// The sequence numbers used for synchronisation packets, keeps a reference of the last sequence number received for each universe.
    /// Sequence numbers are always in the range [0, 255] inclusive.
    /// Each type of packet is tracked differently with respect to sequence numbers as per ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
    /// The uuid refers to the source that is sending the data.
    sync_sequences: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>>,
}
impl SequenceNumbering {
    /// Creates a new `SequenceNumbering` for tracking sequence numbers for the various types of packets.
    ///
    /// This implementation uses `HashMaps` internally to allow O(1) checking and updating of sequence numbers.
619
    fn new() -> SequenceNumbering {
619
        SequenceNumbering {
619
            data_sequences: HashMap::new(),
619
            sync_sequences: HashMap::new(),
619
        }
619
    }
    /// Clears the sequence number records completely removing all sources/universes for all types of packet.
2
    fn clear(&mut self) {
2
        self.data_sequences.clear();
2
        self.sync_sequences.clear();
2
    }
    /// Checks the timeouts for all packet types, sources and universes with sequence numbers registed.
    /// Removes any universes for which the `last_recv` time was at least the given timeout amount of time ago.
    /// Any sources which have no universes after this operation are also removed.
    ///
    /// #Arguments
    ///
    /// `announce_timeout`: A flag, if true it indicates than a `UniverseTimeout` error should be thrown if a universe times out on a source.
3714
    fn check_timeouts(&mut self, announce_timeout: bool) -> Result<()> {
3714
        check_timeouts(
3714
            &mut self.data_sequences,
3714
            E131_NETWORK_DATA_LOSS_TIMEOUT,
3714
            announce_timeout,
3714
        )?;
3711
        check_timeouts(
3711
            &mut self.sync_sequences,
3711
            E131_NETWORK_DATA_LOSS_TIMEOUT,
3711
            announce_timeout,
3711
        )
3714
    }
    /// Checks the sequence number is correct for a data packet with the given `sequence_number` and universe from the given source with given cid.
    /// Uses the given `source_limit` to check that it isn't exceeded.
    ///
    /// Returns Ok(()) if the packet is detected in-order.
    ///
    /// # Arguments
    /// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
    ///
    /// cid:    The Uuid of the source that send the packet.
    ///
    /// `sequence_number`: The sequence number of the packet to check.
    ///
    /// universe: The data universe of the packet.
    ///
    /// # Errors
    /// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
    /// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
    ///
    /// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
2255
    fn check_data_seq_number(
2255
        &mut self,
2255
        source_limit: Option<usize>,
2255
        cid: Uuid,
2255
        sequence_number: u8,
2255
        universe: u16,
2255
        announce_timeout: bool,
2255
        null_start_code: bool,
2255
    ) -> Result<()> {
2255
        check_seq_number(
2255
            &mut self.data_sequences,
2255
            source_limit,
2255
            cid,
2255
            sequence_number,
2255
            universe,
2255
            announce_timeout,
2255
            null_start_code,
2255
        )
2255
    }
    /// Checks the sequence number is correct for a sync packet with the given `sequence_number` and universe from the given source with given cid.
    /// Uses the given `source_limit` to check that it isn't exceeded.
    ///
    /// Returns Ok(()) if the packet is detected in-order.
    ///
    /// # Arguments
    /// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
    ///
    /// cid:    The Uuid of the source that send the packet.
    ///
    /// `sequence_number`: The sequence number of the packet to check.
    ///
    /// universe: The sync universe of the packet
    ///
    /// # Errors
    /// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
    /// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
    ///
    /// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
1353
    fn check_sync_seq_number(
1353
        &mut self,
1353
        source_limit: Option<usize>,
1353
        cid: Uuid,
1353
        sequence_number: u8,
1353
        sync_uni: u16,
1353
        announce_timeout: bool,
1353
    ) -> Result<()> {
1353
        check_seq_number(
1353
            &mut self.sync_sequences,
1353
            source_limit,
1353
            cid,
1353
            sequence_number,
1353
            sync_uni,
1353
            announce_timeout,
1353
            true,
1353
        )
1353
    }
    /// Removes the sequence number tracking for the given source / universe combination.
    /// This applies to both data and sync packets.
    ///
    /// # Arguments:
    ///
    /// `src_cid`: The CID of the source to remove the sequence numbers of.
    ///
    /// universe: The universe being sent by the source from which to remove the sequence numbers.
16
    fn remove_seq_numbers(&mut self, src_cid: Uuid, universe: u16) -> Result<()> {
16
        remove_source_universe_seq(&mut self.data_sequences, src_cid, universe)?;
5
        remove_source_universe_seq(&mut self.sync_sequences, src_cid, universe)
16
    }
}
/// Checks the given sequence number for the given universe against the given expected sequence numbers.
///
/// Returns Ok(()) if the packet is detected in-order.
///
/// # Arguments
/// `src_sequences`: A mutable hashmap which relates sources identified by Uuid to another hashmap which itself relates universes to sequence numbers. The given hashmap of
///                 sequences should be for the specific packet-type being checked as different packet-types have their own sequence numbers even from the same source.
/// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
/// cid:    The Uuid of the source that send the packet.
/// `sequence_number`: The sequence number of the packet to check.
/// universe: The universe of the packet (this is the data universe for data packets and the sync universe for synchronisation packets).
/// `refresh_timeout`: True if the packet keeps the source / universe alive (Null START Code data and synchronisation packets). Otherwise
///                 (alternate START Code data) the sequence number is still checked and updated, but the data loss timer of a live
///                 source / universe isn't reset. A new or timed out source / universe is tracked as usual, so a source sending only
///                 alternate START Code data times out `E131_NETWORK_DATA_LOSS_TIMEOUT` after it starts.
///
/// # Errors
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
///
/// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
3616
fn check_seq_number(
3616
    src_sequences: &mut HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>>,
3616
    source_limit: Option<usize>,
3616
    cid: Uuid,
3616
    sequence_number: u8,
3616
    universe: u16,
3616
    announce_timeout: bool,
3616
    refresh_timeout: bool,
3616
) -> Result<()> {
    // Remove timed out sources/universes before checking this packet.
    // This is done for all sources/universes rather than just the source that sent the packet because a completely dead (no packets being sent) universe
    // would not be removed otherwise and would continue to take up space. This comes at the cost of increased processing time complexity as each
    // source is checked every time.
    //
    // When timeouts are announced they are reported by `SacnReceiver::recv` before each read instead. Reporting them from here would return an error
    // in place of this (valid) packet, so the packet would be lost because a different source had timed out.
3616
    if !announce_timeout {
3603
        check_timeouts(src_sequences, E131_NETWORK_DATA_LOSS_TIMEOUT, false)?;
13
    }
3616
    if src_sequences.get(&cid).is_none() {
        // New source not previously received from.
673
        if source_limit.is_none() || src_sequences.len() < source_limit.unwrap() {
671
            src_sequences.insert(cid, HashMap::new());
        } else {
2
            return Err(SacnError::SourcesExceededError(src_sequences.len()));
        }
2943
    };
3614
    let expected_seq = match src_sequences.get(&cid) {
        Some(src) => {
3614
            if let Some(s) = src
3614
                .get(&universe)
2923
                .filter(|s| s.last_recv.elapsed() < E131_NETWORK_DATA_LOSS_TIMEOUT)
            {
                // Get the sequence number within the source for the specific universe.
                // Indicates that the source / universe combination is known and hasn't timed out.
2921
                *s
            } else {
                // Indicates that this is the first time (or the first time since it timed out) the universe has been received from this source.
                // A timed out entry that hasn't been removed yet (because timeouts are being announced) is treated the same way.
693
                let initial_seq_num = sequence_number.wrapping_sub(1);
693
                TimedStampedSeqNo::new(initial_seq_num, Instant::now())
            }
        }
        None => {
            // Previously checked that cid is present (and added if not), if None is returned now it indicates that between that check and this
            // function the cid key value has been removed. This can only happen if there is a memory corruption/thread-interleaving or similar external
            // event which the receiver cannot be expected to handle / doesn't support.
            // The rust typing system forces this possibility to be acknowledged when in some languages this possibility would still exist but it would be hidden
            // within the code.
            // While a panic!() call here isn't ideal it shows the strength in the explictness of the rust system and points to an area of
            // potential later improvement within the code by not hiding the problem. As normal if the panic must be caught then rust allows this later on by utilising
            // a mechanism such as catch unwind https://doc.rust-lang.org/std/panic/fn.catch_unwind.html.
            // Another possibility here could be to retry the method but this could end with an infinite loop.
            // Returning an error could also be done but that could confuse error handling as this should not occur and the receiver would be in an inconsistent
            // state.
            panic!();
        }
    };
3614
    let seq_diff = sequence_number.wrapping_sub(expected_seq.sequence_number) as i8;
3614
    if seq_diff as isize <= E131_SEQ_DIFF_DISCARD_UPPER_BOUND
260
        && seq_diff as isize > E131_SEQ_DIFF_DISCARD_LOWER_BOUND
    {
        // Reject the out of order packet as per ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
41
        return Err(SacnError::OutOfSequence(
41
            sequence_number,
41
            expected_seq.sequence_number,
41
            seq_diff as isize,
41
        ));
3573
    }
3573
    match src_sequences.get_mut(&cid) {
        Some(src) => {
            // Replace the old sequence number with the new and reset the timeout, unless this packet doesn't keep the
            // universe alive in which case a live universe keeps its timer (a new or timed out universe starts one).
3573
            let last_recv = if refresh_timeout {
3512
                Instant::now()
            } else {
61
                expected_seq.last_recv
            };
3573
            src.insert(universe, TimedStampedSeqNo::new(sequence_number, last_recv));
        }
        None => {
            // See previous node regarding panic previously in this method.
            panic!();
        }
    };
3573
    Ok(())
3616
}
/// Checks the timeouts for all sources and universes for the given sequences.
/// Removes any universes for which the `last_recv` time was at least the given timeout amount of time ago.
/// Any sources which have no universes after this operation are also removed.
///
/// #Arguments
///
/// `src_sequences`: The source sequence numbers to check the timeout of.
///
/// timeout: The exclusive length of time permitted since a source last sent on a universe.
///     If the time elapsed since the last received data that is equal to or great than the timeout then the source is said to have timed out.
11030
fn check_timeouts(
11030
    src_sequences: &mut HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>>,
11030
    timeout: Duration,
11030
    announce_timeout: bool,
11030
) -> Result<()> {
11030
    if announce_timeout {
21
        let mut timedout_src_id: Option<Uuid> = None;
21
        let mut timedout_uni: Option<u16> = None;
21
        for (src_id, universes) in src_sequences.iter_mut() {
41
            for (uni, seq_num) in universes.iter() {
45
                if seq_num.last_recv.elapsed() >= timeout {
4
                    timedout_src_id = Some(*src_id);
4
                    timedout_uni = Some(*uni);
4
                    break;
41
                }
            }
41
            if timedout_uni.is_some() {
4
                break;
37
            }
        }
21
        if let Some(uni_to_remove) = timedout_uni {
            // If None then it indicates nothing timed out.
4
            let src_universes = src_sequences.get_mut(&timedout_src_id.unwrap());
4
            if let Some(universes) = src_universes {
4
                universes.remove(&uni_to_remove);
4
                if universes.is_empty() {
                    // Remove source if all its universes have timed out
3
                    src_sequences.remove(&timedout_src_id.unwrap());
1
                }
4
                return Err(SacnError::UniverseTimeout(
4
                    timedout_src_id.unwrap(),
4
                    uni_to_remove,
4
                ));
            }
17
        }
17
        Ok(())
    } else {
11009
        for (src_id, universes) in src_sequences.iter_mut() {
9638
            universes.retain(|uni, seq_num| {
9638
                let keep = seq_num.last_recv.elapsed() < timeout;
9638
                if !keep {
3
                    log_debug!("sACN source {src_id} timed out on universe {uni}");
9635
                }
9638
                keep
9638
            });
        }
        // Remove all empty sources.
11009
        src_sequences.retain(|_src_id, universes| !universes.is_empty());
11009
        Ok(())
    }
11030
}
/// Removes the sequence number entry from the given sequences for the given source cid and universe.
///
/// This removes the source entirely if there are no universes left.
///
/// # Arguments
/// `src_sequences`: The sequence numbers for each source and universe.
///
/// `src_cid`:       The CID for the source to remove the universe from.
///
/// universe:      The universe to remove from the source.
///
/// # Errors
/// Returns a `SourceNotFound` error if the given `src_cid` isn't in the given collection of sources/sequence-numbers.
///
/// Returns a `UniverseNotFound` error if the given universe isn't registered to the given source and so cannot be removed.
21
fn remove_source_universe_seq(
21
    src_sequences: &mut HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>>,
21
    src_cid: Uuid,
21
    universe: u16,
21
) -> Result<()> {
21
    match src_sequences.get_mut(&src_cid) {
        Some(x) => {
7
            match x.remove(&universe) {
                Some(_) => {
5
                    if x.is_empty() {
                        // Remove the source if there are no universes registered to it.
3
                        match src_sequences.remove(&src_cid) {
3
                            Some(_x) => Ok(()),
                            None => Err(SacnError::SourceNotFound(src_cid)),
                        }
                    } else {
2
                        Ok(())
                    }
                }
2
                None => Err(SacnError::UniverseNotFound(universe)),
            }
        }
14
        None => Err(SacnError::SourceNotFound(src_cid)),
    }
21
}
/// The default merge action for the receiver.
///
/// This discarding of the old data is the default action for compliance as specified in ANSI E1.31-2018, Section 11.2.1.
///
/// This can be changed if required as part of the mechanism described in ANSI E1.31-2018, Section 6.2.3.4 Requirements for Merging and Arbitrating.
///
/// The first argument (i) is the existing data, n is the new data.
/// This function is only valid if both inputs have the same universe, sync addr, `start_code` and the data contains at least the first value (the start code).
/// If this doesn't hold an error will be returned.
/// Other merge functions may allow merging different start codes or not check for them.
4
pub fn discard_lowest_priority_then_previous(i: &DMXData, n: &DMXData) -> Result<DMXData> {
4
    if i.priority > n.priority {
2
        return Ok(i.clone());
2
    }
2
    Ok(n.clone())
4
}
/// Performs a highest takes priority (HTP) (per byte) DMX merge of data.
///
/// Note this merge is done within the explicit priority, if i or n has an explicitly higher priority it will always take precedence before this HTP merge is attempted.
/// If either data has the preview flag set then the result will have the preview flag set.
///
/// Given as an example of a possible merge algorithm.
///
/// The first argument (i) is the existing data, n is the new data.
///
/// This function is only valid if both inputs have the same universe, sync addr, `start_code` and the data contains at least the first value (the start code).
/// If this doesn't hold an error will be returned.
/// Other merge functions may allow merging different start codes or not check for them.
2
pub fn htp_dmx_merge(i: &DMXData, n: &DMXData) -> Result<DMXData> {
2
    if i.values.is_empty()
2
        || n.values.is_empty()
2
        || i.universe != n.universe
2
        || i.values[0] != n.values[0]
2
        || i.sync_uni != n.sync_uni
    {
        return Err(SacnError::DmxMergeError());
2
    }
2
    if i.priority > n.priority {
        return Ok(i.clone());
2
    } else if n.priority > i.priority {
        return Ok(n.clone());
2
    }
    // Must have same priority.
    let mut r: DMXData = DMXData {
2
        universe: i.universe,
2
        values: Vec::new(),
2
        sync_uni: i.sync_uni,
2
        priority: i.priority,
2
        src_cid: None,
2
        preview: i.preview || n.preview, // If either data is preview then mark the result as preview.
2
        recv_timestamp: i.recv_timestamp,
    };
2
    let mut i_iter = i.values.iter();
2
    let mut n_iter = n.values.iter();
2
    let mut i_val = i_iter.next();
2
    let mut n_val = n_iter.next();
1028
    while (i_val.is_some()) || (n_val.is_some()) {
1026
        if let (Some(&i), Some(&n)) = (i_val, n_val) {
626
            r.values.push(max(i, n));
400
        } else if let Some(&i) = i_val
400
            && n_val.is_none()
        {
400
            r.values.push(i);
        } else if let Some(&n) = n_val
            && i_val.is_none()
        {
            r.values.push(n);
        }
1026
        i_val = i_iter.next();
1026
        n_val = n_iter.next();
    }
2
    Ok(r)
2
}
#[cfg(test)]
mod test {
    use super::*;
    /// A valid data packet whose DMX data was cut short in transit must be rejected rather than parsed with
    /// zeros filling in for the missing bytes.
    #[test]
1
    fn test_parse_datagram_rejects_truncated_packet() {
1
        let packet = AcnRootLayerProtocol {
1
            pdu: E131RootLayer {
1
                cid: Uuid::new_v4(),
1
                data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
1
                    source_name: "Source".into(),
1
                    priority: E131_DEFAULT_PRIORITY,
1
                    synchronization_address: 0,
1
                    sequence_number: 0,
1
                    preview_data: false,
1
                    stream_terminated: false,
1
                    force_synchronization: false,
1
                    universe: 1,
1
                    data: DataPacketDmpLayer {
1
                        property_values: vec![0u8; 513].into(),
1
                    },
1
                }),
1
            },
1
        };
1
        let packed = packet.pack_alloc().unwrap();
        // The receiver always reads into a zero-filled buffer of the maximum packet size.
1
        let mut buf = [0u8; RCV_BUF_DEFAULT_SIZE];
1
        buf[..packed.len()].copy_from_slice(&packed);
1
        assert_eq!(parse_datagram(&buf, packed.len()).unwrap(), packet);
        // The last 100 DMX slots never arrived.
1
        assert!(parse_datagram(&buf, packed.len() - 100).is_err());
1
    }
    #[test]
1
    fn test_parse_datagram_rejects_length_larger_than_buffer() {
1
        let buf = [0u8; RCV_BUF_DEFAULT_SIZE];
1
        match parse_datagram(&buf, RCV_BUF_DEFAULT_SIZE + 1) {
1
            Err(SacnError::TooManyBytesRead(_, _)) => {}
            other => panic!("Expected TooManyBytesRead, got {other:?}"),
        }
1
    }
    use std::borrow::Cow;
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
    use std::time::Instant;
    use uuid::Uuid;
    #[test]
1
    fn test_handle_single_page_discovery_packet() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let name = "Test Src 1";
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let page: u8 = 0;
1
        let last_page: u8 = 0;
1
        let universes: Vec<u16> = vec![0, 1, 2, 3, 4, 5];
        let discovery_pkt: UniverseDiscoveryPacketFramingLayer<'_> =
1
            UniverseDiscoveryPacketFramingLayer {
1
                source_name: name.into(),
1

            
1
                // Universe discovery layer.
1
                data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
1
                    page,
1

            
1
                    // The number of the final page.
1
                    last_page,
1

            
1
                    // List of universes.
1
                    universes: universes.clone().into(),
1
                },
1
            };
1
        let res: Option<String> = dmx_rcv.handle_universe_discovery_packet(src_cid, discovery_pkt);
1
        assert!(res.is_some());
1
        assert_eq!(res.unwrap(), name);
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 1);
1
        assert_eq!(dmx_rcv.discovered_sources[0].name, name);
1
        assert_eq!(dmx_rcv.discovered_sources[0].cid, src_cid);
1
        assert_eq!(dmx_rcv.discovered_sources[0].last_page, last_page);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages.len(), 1);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages[0].page, page);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages[0].universes, universes);
1
    }
    /// With `announce_timeout` set, a universe that has timed out must be reported whichever source it belongs to, not only if
    /// it belongs to the first source in the map.
    #[test]
1
    fn test_check_timeouts_announce_finds_any_source() {
1
        let mut src_sequences: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        for _ in 0..16 {
16
            let mut universes = HashMap::new();
16
            universes.insert(1, TimedStampedSeqNo::new(0, Instant::now()));
16
            src_sequences.insert(Uuid::new_v4(), universes);
        }
1
        let timed_out_cid = Uuid::new_v4();
1
        let stale = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(100);
1
        let mut universes = HashMap::new();
1
        universes.insert(7, TimedStampedSeqNo::new(0, stale));
1
        src_sequences.insert(timed_out_cid, universes);
1
        match check_timeouts(&mut src_sequences, E131_NETWORK_DATA_LOSS_TIMEOUT, true) {
            Err(SacnError::UniverseTimeout(cid, universe)) => {
1
                assert_eq!(cid, timed_out_cid);
1
                assert_eq!(universe, 7);
            }
            other => panic!("Expected UniverseTimeout, got {other:?}"),
        }
        // The timed out source is removed and nothing else times out.
1
        assert!(!src_sequences.contains_key(&timed_out_cid));
1
        assert_eq!(src_sequences.len(), 16);
1
        assert!(check_timeouts(&mut src_sequences, E131_NETWORK_DATA_LOSS_TIMEOUT, true).is_ok());
1
    }
    /// Sources only advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`, so a discovered source must not expire before its next advert.
    #[test]
1
    fn test_discovered_source_kept_between_adverts() {
1
        assert!(UNIVERSE_DISCOVERY_SOURCE_TIMEOUT > E131_UNIVERSE_DISCOVERY_INTERVAL);
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let discovery_pkt = UniverseDiscoveryPacketFramingLayer {
1
            source_name: "Test Src".into(),
1
            data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
1
                page: 0,
1
                last_page: 0,
1
                universes: vec![1u16, 2].into(),
1
            },
1
        };
1
        dmx_rcv.handle_universe_discovery_packet(Uuid::new_v4(), discovery_pkt);
        // Pretend the advert arrived just before the next one is due.
1
        let advert_age = E131_UNIVERSE_DISCOVERY_INTERVAL - Duration::from_millis(100);
1
        dmx_rcv.discovered_sources[0].last_updated = Instant::now() - advert_age;
1
        assert_eq!(dmx_rcv.get_discovered_sources().len(), 1);
        // Once the source has missed adverts for longer than the timeout it is removed.
1
        dmx_rcv.discovered_sources[0].last_updated =
1
            Instant::now() - UNIVERSE_DISCOVERY_SOURCE_TIMEOUT - Duration::from_millis(100);
1
        assert!(dmx_rcv.get_discovered_sources().is_empty());
1
    }
20
    fn discovery_page(
20
        page: u8,
20
        last_page: u8,
20
        universes: &[u16],
20
    ) -> UniverseDiscoveryPacketFramingLayer<'static> {
20
        UniverseDiscoveryPacketFramingLayer {
20
            source_name: "Test Src".into(),
20
            data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
20
                page,
20
                last_page,
20
                universes: universes.to_vec().into(),
20
            },
20
        }
20
    }
    /// If a page is lost, the next discovery interval resends the pages already received. Those repeats must not stop the
    /// source from being discovered once the missing page arrives.
    #[test]
1
    fn test_multi_page_discovery_with_repeated_page() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let cid = Uuid::new_v4();
        // First interval: page 0 arrives, page 1 is lost.
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
        // Second interval: both pages arrive.
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
1
        assert_eq!(
1
            dmx_rcv.handle_universe_discovery_packet(cid, discovery_page(1, 1, &[3, 4])),
1
            Some("Test Src".to_string())
        );
1
        assert!(dmx_rcv.partially_discovered_sources.is_empty());
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 1);
1
        assert_eq!(
1
            dmx_rcv.discovered_sources[0].get_all_universes(),
1
            vec![1, 2, 3, 4]
        );
1
    }
    /// If the number of pages changes between intervals, pages from the older set are discarded.
    #[test]
1
    fn test_multi_page_discovery_page_count_changes() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let cid = Uuid::new_v4();
        // Page 1 of a 3 page set arrives, then the source drops to 2 pages.
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(1, 2, &[9]))
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(1, 1, &[3, 4]))
1
                .is_some()
        );
1
        assert_eq!(dmx_rcv.discovered_sources[0].last_page, 1);
1
        assert_eq!(
1
            dmx_rcv.discovered_sources[0].get_all_universes(),
1
            vec![1, 2, 3, 4]
        );
1
    }
    /// Sources re-advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`. Only the first advert, and adverts that change the
    /// source's universe list or name, should be reported as a discovery.
    #[test]
1
    fn test_repeated_discovery_advert_not_reported() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let cid = Uuid::new_v4();
        // Single page source.
1
        assert_eq!(
1
            dmx_rcv.handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1, 2])),
1
            Some("Test Src".to_string())
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1, 2]))
1
                .is_none()
        );
        // The repeat still refreshes the record so the source doesn't time out.
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 1);
        // A changed universe list is reported again.
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1, 2, 3]))
1
                .is_some()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1, 2, 3]))
1
                .is_none()
        );
        // A changed name is reported again.
1
        let mut renamed = discovery_page(0, 0, &[1, 2, 3]);
1
        renamed.source_name = "Renamed Src".into();
1
        assert_eq!(
1
            dmx_rcv.handle_universe_discovery_packet(cid, renamed),
1
            Some("Renamed Src".to_string())
        );
        // Multi page source: the second full set of identical pages isn't reported.
1
        let cid2 = Uuid::new_v4();
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(1, 1, &[3, 4]))
1
                .is_some()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(1, 1, &[3, 4]))
1
                .is_none()
        );
1
        assert!(dmx_rcv.partially_discovered_sources.is_empty());
        // Changing a page's universes is reported once the set is complete.
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(0, 1, &[1, 2]))
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid2, discovery_page(1, 1, &[3, 5]))
1
                .is_some()
        );
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 2);
1
    }
    /// A source that times out and comes back is reported as discovered again.
    #[test]
1
    fn test_rediscovered_source_reported_after_timeout() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let cid = Uuid::new_v4();
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1]))
1
                .is_some()
        );
1
        dmx_rcv.discovered_sources[0].last_updated =
1
            Instant::now() - UNIVERSE_DISCOVERY_SOURCE_TIMEOUT - Duration::from_millis(100);
1
        assert!(dmx_rcv.get_discovered_sources().is_empty());
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1]))
1
                .is_some()
        );
        // Also when the expired record hasn't been pruned by get_discovered_sources() yet.
1
        dmx_rcv.discovered_sources[0].last_updated =
1
            Instant::now() - UNIVERSE_DISCOVERY_SOURCE_TIMEOUT - Duration::from_millis(100);
1
        assert!(
1
            dmx_rcv
1
                .handle_universe_discovery_packet(cid, discovery_page(0, 0, &[1]))
1
                .is_some()
        );
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 1);
1
    }
9
    fn synchronized_data_packet<'a>(
9
        universe: u16,
9
        sync_address: u16,
9
        sequence_number: u8,
9
        force_synchronization: bool,
9
    ) -> DataPacketFramingLayer<'a> {
9
        DataPacketFramingLayer {
9
            synchronization_address: sync_address,
9
            force_synchronization,
9
            ..generate_data_packet_framing_layer_seq_num(universe, sequence_number)
9
        }
9
    }
    /// With `Force_Synchronization` set and no synchronisation packet ever received on the address, data isn't held.
    #[test]
1
    fn test_force_synchronization_before_sync_starts() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        let cid = Uuid::new_v4();
1
        let res = dmx_rcv
1
            .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 0, true))
1
            .unwrap()
1
            .expect("data with Force_Synchronization should be passed up when not synchronised");
1
        assert_eq!(res[0].universe, UNIVERSE);
1
        assert!(dmx_rcv.waiting_data.is_empty());
        // The receiver still listens on the synchronisation address so synchronisation can start, without passing up data
        // sent on it.
1
        assert!(dmx_rcv.sync_universes.contains_key(&SYNC_UNI));
1
        assert!(!dmx_rcv.is_listening(&SYNC_UNI));
1
    }
    /// While synchronisation is active, data is held until the synchronisation packet even with `Force_Synchronization` set.
    #[test]
1
    fn test_force_synchronization_while_synchronized() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE, SYNC_UNI]).unwrap();
1
        let cid = Uuid::new_v4();
        // Synchronisation starts with the first synchronisation packet.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
                .unwrap()
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 0, true))
1
                .unwrap()
1
                .is_none()
        );
1
        let res = dmx_rcv
1
            .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 1))
1
            .unwrap()
1
            .expect("held data should be released by the synchronisation packet");
1
        assert_eq!(res[0].universe, UNIVERSE);
1
    }
    /// Once synchronisation is lost, `Force_Synchronization` set means data is processed without waiting, and unset means the
    /// data is held until synchronisation resumes.
    #[test]
1
    fn test_force_synchronization_after_sync_lost() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE, SYNC_UNI]).unwrap();
1
        let cid = Uuid::new_v4();
1
        dmx_rcv
1
            .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
            .unwrap();
        // No synchronisation packet for longer than the network data loss timeout.
1
        dmx_rcv.last_sync_packets.insert(
1
            SYNC_UNI,
1
            Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(100),
1
        );
        // Force_Synchronization unset: hold the data.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 0, false))
1
                .unwrap()
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .waiting_data
1
                .contains_key(&(UNIVERSE, E131_NULL_START_CODE))
        );
        // Force_Synchronization set: process the data now, replacing the held data.
1
        let res = dmx_rcv
1
            .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 1, true))
1
            .unwrap()
1
            .expect(
1
                "data with Force_Synchronization should be passed up once synchronisation is lost",
1
            );
1
        assert_eq!(res[0].universe, UNIVERSE);
1
        assert!(dmx_rcv.waiting_data.is_empty());
1
    }
    /// Level data (start code 0x00) and per-address priority data (start code 0xDD) for the same universe held for the
    /// same synchronisation are both released by the synchronisation packet, rather than one replacing the other, and
    /// a merge function that requires matching start codes doesn't fail.
    #[test]
1
    fn test_sync_holds_levels_and_per_address_priority_separately() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE, SYNC_UNI]).unwrap();
1
        dmx_rcv.set_merge_fn(htp_dmx_merge).unwrap();
1
        let cid = Uuid::new_v4();
1
        dmx_rcv
1
            .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
            .unwrap();
1
        let levels: Vec<u8> = vec![0x00, 10, 20, 30];
1
        let priorities: Vec<u8> = vec![0xDD, 100, 0, 200];
1
        let levels_pkt = DataPacketFramingLayer {
1
            data: DataPacketDmpLayer {
1
                property_values: Cow::from(levels.clone()),
1
            },
1
            ..synchronized_data_packet(UNIVERSE, SYNC_UNI, 0, false)
1
        };
1
        let priorities_pkt = DataPacketFramingLayer {
1
            data: DataPacketDmpLayer {
1
                property_values: Cow::from(priorities.clone()),
1
            },
1
            ..synchronized_data_packet(UNIVERSE, SYNC_UNI, 1, false)
1
        };
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(cid, levels_pkt)
1
                .unwrap()
1
                .is_none()
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(cid, priorities_pkt)
1
                .unwrap()
1
                .is_none()
        );
1
        let res = dmx_rcv
1
            .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 1))
1
            .unwrap()
1
            .expect("held data should be released by the synchronisation packet");
1
        assert_eq!(res.len(), 2);
1
        assert_eq!(res[0].universe, UNIVERSE);
1
        assert_eq!(res[0].values, levels);
1
        assert_eq!(res[1].universe, UNIVERSE);
1
        assert_eq!(res[1].values, priorities);
1
        assert!(dmx_rcv.waiting_data.is_empty());
1
    }
    /// Clearing a universe's waiting data clears it for every start code.
    #[test]
1
    fn test_clear_waiting_data_all_start_codes() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        for start_code in [0x00, 0xDD] {
2
            dmx_rcv
2
                .store_waiting_data(DMXData {
2
                    universe: UNIVERSE,
2
                    values: vec![start_code, 1, 2, 3],
2
                    sync_uni: SYNC_UNI,
2
                    priority: 100,
2
                    src_cid: None,
2
                    preview: false,
2
                    recv_timestamp: Instant::now(),
2
                })
2
                .unwrap();
        }
1
        assert_eq!(dmx_rcv.waiting_data.len(), 2);
1
        assert!(dmx_rcv.clear_waiting_data(UNIVERSE));
1
        assert!(dmx_rcv.waiting_data.is_empty());
1
        assert!(!dmx_rcv.clear_waiting_data(UNIVERSE));
1
    }
    /// As per ANSI E1.31-2016 Section 11.1.1, synchronisation begins with the first synchronisation packet. Until then data
    /// naming a synchronisation address is passed up straight away, whatever its `Force_Synchronization` option.
    #[test]
1
    fn test_data_passed_up_before_first_sync_packet() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        let cid = Uuid::new_v4();
1
        let res = dmx_rcv
1
            .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 0, false))
1
            .unwrap()
1
            .expect("data should be passed up before synchronisation has started");
1
        assert_eq!(res.len(), 1);
1
        assert_eq!(res[0].universe, UNIVERSE);
1
        assert_eq!(res[0].sync_uni, SYNC_UNI);
1
        assert!(dmx_rcv.waiting_data.is_empty());
        // The synchronisation address is joined so that the first synchronisation packet is received.
1
        assert!(dmx_rcv.sync_universes.contains_key(&SYNC_UNI));
        // The first synchronisation packet starts synchronisation; there is nothing waiting for it to release.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
                .unwrap()
1
                .is_none()
        );
        // From then on the data waits for the synchronisation packet.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(cid, synchronized_data_packet(UNIVERSE, SYNC_UNI, 1, false))
1
                .unwrap()
1
                .is_none()
        );
1
        let res = dmx_rcv
1
            .handle_sync_packet(cid, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 1))
1
            .unwrap()
1
            .expect("held data should be released by the synchronisation packet");
1
        assert_eq!(res[0].universe, UNIVERSE);
1
    }
    /// Synchronisation started on one address doesn't hold data naming a different address that has never had a
    /// synchronisation packet.
    #[test]
1
    fn test_sync_started_is_per_sync_address() {
        const UNIVERSE: u16 = 1;
        const SYNC_UNI_A: u16 = 2;
        const SYNC_UNI_B: u16 = 3;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE, SYNC_UNI_A]).unwrap();
1
        let cid = Uuid::new_v4();
1
        dmx_rcv
1
            .handle_sync_packet(
1
                cid,
1
                generate_sync_packet_framing_layer_seq_num(SYNC_UNI_A, 0),
1
            )
1
            .unwrap();
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(
1
                    cid,
1
                    synchronized_data_packet(UNIVERSE, SYNC_UNI_B, 0, false)
1
                )
1
                .unwrap()
1
                .is_some()
        );
1
    }
    #[test]
1
    fn test_handle_multi_page_discovery_packet() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let name = "Test Src 1";
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let last_page: u8 = 1;
1
        let mut universes_page_1: Vec<u16> = Vec::new();
1
        let mut universes_page_2: Vec<u16> = Vec::new();
1
        for i in 1..513 {
512
            universes_page_1.push(i);
        }
1
        for i in 513..1024 {
511
            universes_page_2.push(i);
        }
        let discovery_pkt_1: UniverseDiscoveryPacketFramingLayer<'_> =
1
            UniverseDiscoveryPacketFramingLayer {
1
                source_name: name.into(),
1

            
1
                // Universe discovery layer.
1
                data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
1
                    page: 0,
1

            
1
                    // The number of the final page.
1
                    last_page,
1

            
1
                    // List of universes.
1
                    universes: universes_page_1.clone().into(),
1
                },
1
            };
        let discovery_pkt_2: UniverseDiscoveryPacketFramingLayer<'_> =
1
            UniverseDiscoveryPacketFramingLayer {
1
                source_name: name.into(),
1

            
1
                // Universe discovery layer.
1
                data: UniverseDiscoveryPacketUniverseDiscoveryLayer {
1
                    page: 1,
1

            
1
                    // The number of the final page.
1
                    last_page,
1

            
1
                    // List of universes.
1
                    universes: universes_page_2.clone().into(),
1
                },
1
            };
        let res: Option<String> =
1
            dmx_rcv.handle_universe_discovery_packet(src_cid, discovery_pkt_1);
1
        assert!(res.is_none()); // Should be none because first packet isn't complete as its only the first page.
        let res2: Option<String> =
1
            dmx_rcv.handle_universe_discovery_packet(src_cid, discovery_pkt_2);
1
        assert!(res2.is_some()); // Source should be discovered because the second and last page is now received.
1
        assert_eq!(res2.unwrap(), name);
1
        assert_eq!(dmx_rcv.discovered_sources.len(), 1);
1
        assert_eq!(dmx_rcv.discovered_sources[0].name, name);
1
        assert_eq!(dmx_rcv.discovered_sources[0].cid, src_cid);
1
        assert_eq!(dmx_rcv.discovered_sources[0].last_page, last_page);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages.len(), 2);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages[0].page, 0);
1
        assert_eq!(dmx_rcv.discovered_sources[0].pages[1].page, 1);
1
        assert_eq!(
1
            dmx_rcv.discovered_sources[0].pages[0].universes,
1
            universes_page_1
        );
1
        assert_eq!(
1
            dmx_rcv.discovered_sources[0].pages[1].universes,
1
            universes_page_2
        );
1
    }
    #[test]
1
    fn test_store_retrieve_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let sync_uni: u16 = 1;
1
        let universe: u16 = 1;
1
        let vals: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1
        let dmx_data = DMXData {
1
            universe,
1
            values: vals.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(dmx_data).unwrap();
1
        let res: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni);
1
        assert_eq!(res.len(), 1);
1
        assert_eq!(res[0].universe, universe);
1
        assert_eq!(res[0].sync_uni, sync_uni);
1
        assert_eq!(res[0].values, vals);
1
    }
    #[test]
1
    fn test_store_2_retrieve_1_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let sync_uni: u16 = 1;
1
        let universe: u16 = 1;
1
        let vals: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1
        let dmx_data = DMXData {
1
            universe,
1
            values: vals.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        let dmx_data2 = DMXData {
1
            universe: universe + 1,
1
            values: vals.clone(),
1
            sync_uni: sync_uni + 1,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(dmx_data).unwrap();
1
        dmx_rcv.store_waiting_data(dmx_data2).unwrap();
1
        let res: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni);
1
        assert_eq!(res.len(), 1);
1
        assert_eq!(res[0].universe, universe);
1
        assert_eq!(res[0].sync_uni, sync_uni);
1
        assert_eq!(res[0].values, vals);
1
    }
    #[test]
1
    fn test_store_2_retrieve_2_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let sync_uni: u16 = 1;
1
        let universe: u16 = 1;
1
        let vals: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1
        let dmx_data = DMXData {
1
            universe,
1
            values: vals.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        let vals2: Vec<u8> = vec![0, 9, 7, 3, 2, 4, 5, 6, 5, 1, 2, 3];
1
        let dmx_data2 = DMXData {
1
            universe: universe + 1,
1
            values: vals2.clone(),
1
            sync_uni: sync_uni + 1,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(dmx_data).unwrap();
1
        dmx_rcv.store_waiting_data(dmx_data2).unwrap();
1
        let res: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni);
1
        assert_eq!(res.len(), 1);
1
        assert_eq!(res[0].universe, universe);
1
        assert_eq!(res[0].sync_uni, sync_uni);
1
        assert_eq!(res[0].values, vals);
1
        let res2: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni + 1);
1
        assert_eq!(res2.len(), 1);
1
        assert_eq!(res2[0].universe, universe + 1);
1
        assert_eq!(res2[0].sync_uni, sync_uni + 1);
1
        assert_eq!(res2[0].values, vals2);
1
    }
    #[test]
1
    fn test_store_2_same_universe_same_priority_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let sync_uni: u16 = 1;
1
        let universe: u16 = 1;
1
        let vals: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1
        let dmx_data = DMXData {
1
            universe,
1
            values: vals.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        let vals2: Vec<u8> = vec![0, 9, 7, 3, 2, 4, 5, 6, 5, 1, 2, 3];
1
        let dmx_data2 = DMXData {
1
            universe,
1
            values: vals2.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(dmx_data).unwrap();
1
        dmx_rcv.store_waiting_data(dmx_data2).unwrap();
1
        let res2: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni);
1
        assert_eq!(res2.len(), 1);
1
        assert_eq!(res2[0].universe, universe);
1
        assert_eq!(res2[0].sync_uni, sync_uni);
1
        assert_eq!(res2[0].values, vals2);
1
        assert_eq!(dmx_rcv.rtrv_waiting_data(sync_uni).len(), 0);
1
    }
    #[test]
1
    fn test_store_2_same_universe_diff_priority_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let sync_uni: u16 = 1;
1
        let universe: u16 = 1;
1
        let vals: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1
        let dmx_data = DMXData {
1
            universe,
1
            values: vals.clone(),
1
            sync_uni,
1
            priority: 120,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        let vals2: Vec<u8> = vec![0, 9, 7, 3, 2, 4, 5, 6, 5, 1, 2, 3];
1
        let dmx_data2 = DMXData {
1
            universe,
1
            values: vals2.clone(),
1
            sync_uni,
1
            priority: 100,
1
            src_cid: None,
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(dmx_data).unwrap();
1
        dmx_rcv.store_waiting_data(dmx_data2).unwrap(); // Won't be added as lower priority than already waiting data.
1
        let res: Vec<DMXData> = dmx_rcv.rtrv_waiting_data(sync_uni);
1
        assert_eq!(res.len(), 1);
1
        assert_eq!(res[0].universe, universe);
1
        assert_eq!(res[0].sync_uni, sync_uni);
1
        assert_eq!(res[0].values, vals);
1
        assert_eq!(dmx_rcv.rtrv_waiting_data(sync_uni).len(), 0);
1
    }
    /// Generates a data packet framing layer with arbitrary values except for the sequence number which is set to the given value.
    /// This is used for tests targeted at checking sequence number behaviour that don't care about other fields.
    /// The generated data packet framing layer has structure
    /// `DataPacketFramingLayer` {
    ///     `source_name`: "`Source_A".into()`,
    ///     priority: 100,
    ///     `synchronization_address`: <given sequence number>,
    ///     `sequence_number`: `sequence_number`,
    ///     `preview_data`: false,
    ///     `stream_terminated`: false,
    ///     `force_synchronization`: false,
    ///     universe: <given universe>,
    ///     data: `DataPacketDmpLayer` {
    ///         `property_values`: `Cow::from(&TEST_DATA_SINGLE_UNIVERSE`[0..]),
    ///     },
    /// }
805
    fn generate_data_packet_framing_layer_seq_num<'a>(
805
        universe: u16,
805
        sequence_number: u8,
805
    ) -> DataPacketFramingLayer<'a> {
805
        DataPacketFramingLayer {
805
            source_name: "Source_A".into(),
805
            priority: 100,
805
            synchronization_address: 0,
805
            sequence_number,
805
            preview_data: false,
805
            stream_terminated: false,
805
            force_synchronization: false,
805
            universe,
805
            data: DataPacketDmpLayer {
805
                property_values: Cow::from(&TEST_NULL_START_CODE_DATA[0..]),
805
            },
805
        }
805
    }
    /// Test data with a Null START Code, so that it keeps its source alive like ordinary DMX levels.
    const TEST_NULL_START_CODE_DATA: [u8; 4] = [E131_NULL_START_CODE, 1, 2, 3];
    /// Generates a sync packet framing layer with arbitrary values except for the sequence number which is set to the given value.
    /// This is used for tests targeted at checking sequence number behaviour that don't care about other fields.
    /// The generated Generates a sync packet framing layer has structure:
    /// `SynchronizationPacketFramingLayer` {
    ///     `sequence_number`: <given sequence number>,
    ///     `synchronization_address`: <given synchronisation address>
    /// }
786
    fn generate_sync_packet_framing_layer_seq_num(
786
        sync_address: u16,
786
        sequence_number: u8,
786
    ) -> SynchronizationPacketFramingLayer {
786
        SynchronizationPacketFramingLayer {
786
            sequence_number,
786
            synchronization_address: sync_address,
786
        }
786
    }
    /// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively.
    /// The receiver is then given a data packet with sequence number 0 which is the lower than the expected value of 2 so should be rejected.
    ///
    /// This shows that sequence numbers are correctly evaluated and packets rejected if the sequence number is too low for data packets.
    #[test]
1
    fn test_data_packet_sequence_number_below_expected() {
        const UNIVERSE1: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let data_packet = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0);
1
        let data_packet2 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 1);
1
        let data_packet3 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0); // This data packet has a sequence number lower than the expected value of 2 so should be rejected.
        // Not interested in specific return values from this test, just assert the data is processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected first data packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet2)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected second data packet"
        );
        // Check that the third data packet with the low sequence number is rejected correctly with the expected OutOfSequence error.
1
        match dmx_rcv.handle_data_packet(src_cid, data_packet3) {
            Err(SacnError::OutOfSequence(..)) => {
1
                {};
            }
            Ok(_) => {
                panic!("Receiver incorrectly accepted third data packet");
            }
            Err(e) => {
                panic!(
                    "Receiver correctly rejected third data packet but with unexpected error: {}",
                    e
                );
            }
        }
1
    }
    /// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively meaning the next expected sequence number should be 2.
    /// The receiver is then given a data packet with sequence number x.
    /// This is repeated for all x in [0, 255].
    ///
    /// This exhaustively checks that only sequence numbers outwith the reject range as specified by ANSI E1.31-2018 Section 6.7.2 are accepted for
    /// data packets specifically.
    #[test]
1
    fn test_data_packet_sequence_number_exhaustive() {
        const UNIVERSE1: u16 = 1;
        // The inclusive lower limit used for the sequence numbers tried. Chosen as the minimum value that can fit in an unsigned byte.
        const SEQ_NUM_LOWER_BOUND: u8 = 0;
        // The inclusive upper limit used for the sequence numbers tried. Chosen as the maximum value that can fit in an unsigned byte.
        const SEQ_NUM_UPPER_BOUND: u8 = 255;
        // The last sequence number received before the exhaustive checking.
        const LAST_SEQ_NUM: u8 = 1;
        // Reject range set as per ANSI E1.31-2018 Section 6.7.2 "Having first received a packet with sequence number A, a second packet with sequence number B
        // arrives. If, using signed 8-bit binary arithmetic, B - A is less than or equal to 0, but greater than -20, then
        // the packet containing sequence number B shall be deemed out of sequence and discarded."
        // The inclusive upper bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
        const REJECT_RANGE_UPPER_BOUND: i16 = 0;
        // The exclusive lower bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
        const REJECT_RANGE_LOWER_BOUND: i16 = -20;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        for i in SEQ_NUM_LOWER_BOUND..SEQ_NUM_UPPER_BOUND {
            // Create the receiver.
255
            let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
255
            dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
            // Generate the packets used to put the receiver in a known start state.
            let data_packet =
255
                generate_data_packet_framing_layer_seq_num(UNIVERSE1, LAST_SEQ_NUM - 1);
255
            let data_packet2 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, LAST_SEQ_NUM);
            // Not interested in specific return values from this test, just assert the data is processed successfully.
255
            assert!(
255
                dmx_rcv
255
                    .handle_data_packet(src_cid, data_packet)
255
                    .unwrap()
255
                    .is_some(),
                "Receiver incorrectly rejected first data packet"
            );
255
            assert!(
255
                dmx_rcv
255
                    .handle_data_packet(src_cid, data_packet2)
255
                    .unwrap()
255
                    .is_some(),
                "Receiver incorrectly rejected second data packet"
            );
            // The receiver is now setup correctly ready for the test with a known start state that expects the next data packet sequence number
            // to be 2.
255
            let res = dmx_rcv.handle_data_packet(
255
                src_cid,
255
                generate_data_packet_framing_layer_seq_num(UNIVERSE1, i),
255
            );
            // Cannot do straight 8 bit arithmetic that relies on underflows/overflows as this is undefined behaviour in rust forbidden by the compiler.
            // use same logic as check seq number fn and the e1.31 spec
255
            let diff: i16 = (i.wrapping_sub(LAST_SEQ_NUM) as i8) as i16;
255
            match res {
                Err(SacnError::OutOfSequence(..)) => {
                    // Data packet was rejected due to sequence number.
19
                    if (diff <= REJECT_RANGE_UPPER_BOUND) && (diff > REJECT_RANGE_LOWER_BOUND) {
19
                        {};
                    } else {
                        panic!(
                            "Data packet with sequence number: {} was rejected incorrectly",
                            i
                        );
                    }
                }
                Ok(_p) => {
                    // Data packet and therefore sequence number was accepted.
236
                    if (diff <= REJECT_RANGE_UPPER_BOUND) && (diff > REJECT_RANGE_LOWER_BOUND) {
                        panic!(
                            "Data packet with sequence number: {} was accepted incorrectly",
                            1
                        );
                    } else {
236
                        {};
                    }
                }
                Err(e) => {
                    // This is never expected and always means test failure.
                    panic!("Receiver produced unexpected error: {}", e);
                }
            }
        }
1
    }
    /// Exactly the same as `test_data_packet_sequence_number_exhaustive` but using synchronisation packets.
    ///
    /// This exhaustively checks that only sequence numbers outwith the reject range as specified by ANSI E1.31-2018 Section 6.7.2 are accepted for
    /// synchronisation packets specifically.
    ///
    /// As shown by `test_sequence_number_packet_type_independence` sequence numbers are treated independently for data and synchronisation packets so
    /// therefore appropriate to test separately. Could have been combined with the data packet variant of this test but by keeping them separate
    /// it more clearly shows that data and sync packet sequence numbers should be treated independently and it report errors independently.
    #[test]
1
    fn test_sync_packet_sequence_number_exhaustive() {
        const SYNC_ADDR: u16 = 1;
        // The inclusive lower limit used for the sequence numbers tried. Chosen as the minimum value that can fit in an unsigned byte.
        const SEQ_NUM_LOWER_BOUND: u8 = 0;
        // The inclusive upper limit used for the sequence numbers tried. Chosen as the maximum value that can fit in an unsigned byte.
        const SEQ_NUM_UPPER_BOUND: u8 = 255;
        // The last sequence number received before the exhaustive checking.
        const LAST_SEQ_NUM: u8 = 1;
        // Reject range set as per ANSI E1.31-2018 Section 6.7.2 "Having first received a packet with sequence number A, a second packet with sequence number B
        // arrives. If, using signed 8-bit binary arithmetic, B - A is less than or equal to 0, but greater than -20, then
        // the packet containing sequence number B shall be deemed out of sequence and discarded."
        // The inclusive upper bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
        const REJECT_RANGE_UPPER_BOUND: i16 = 0;
        // The exclusive lower bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
        const REJECT_RANGE_LOWER_BOUND: i16 = -20;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        for i in SEQ_NUM_LOWER_BOUND..SEQ_NUM_UPPER_BOUND {
            // Create the receiver.
255
            let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
255
            dmx_rcv.listen_universes(&[SYNC_ADDR]).unwrap();
            // Generate the packets used to put the receiver in a known start state.
            let sync_packet =
255
                generate_sync_packet_framing_layer_seq_num(SYNC_ADDR, LAST_SEQ_NUM - 1);
255
            let sync_packet2 = generate_sync_packet_framing_layer_seq_num(SYNC_ADDR, LAST_SEQ_NUM);
            // Not interested in specific return values from this test, just assert the sync packet is processed successfully.
255
            assert!(
255
                dmx_rcv
255
                    .handle_sync_packet(src_cid, sync_packet)
255
                    .unwrap()
255
                    .is_none(),
                "Receiver incorrectly rejected first sync packet"
            );
255
            assert!(
255
                dmx_rcv
255
                    .handle_sync_packet(src_cid, sync_packet2)
255
                    .unwrap()
255
                    .is_none(),
                "Receiver incorrectly rejected second sync packet"
            );
            // The receiver is now setup correctly ready for the test with a known start state that expects the next sync packet sequence number
            // to be 2.
255
            let res = dmx_rcv.handle_sync_packet(
255
                src_cid,
255
                generate_sync_packet_framing_layer_seq_num(SYNC_ADDR, i),
255
            );
            // Cannot do straight 8 bit arithmetic that relies on underflows/overflows as this is undefined behaviour in rust forbidden by the compiler.
            // use same logic as check seq number fn and the e1.31 spec
255
            let diff: i16 = (i.wrapping_sub(LAST_SEQ_NUM) as i8) as i16;
255
            match res {
                Err(SacnError::OutOfSequence(..)) => {
                    // Sync packet was rejected due to sequence number.
19
                    if (diff <= REJECT_RANGE_UPPER_BOUND) && (diff > REJECT_RANGE_LOWER_BOUND) {
19
                        {};
                    } else {
                        panic!(
                            "Sync packet with sequence number: {} was rejected incorrectly",
                            i
                        );
                    }
                }
                Ok(_p) => {
                    // Sync packet and therefore sequence number was accepted.
236
                    if (diff <= REJECT_RANGE_UPPER_BOUND) && (diff > REJECT_RANGE_LOWER_BOUND) {
                        panic!(
                            "Sync packet with sequence number: {} was accepted incorrectly",
                            i
                        );
                    } else {
236
                        {};
                    }
                }
                Err(e) => {
                    // This is never expected and always means test failure.
                    panic!("Receiver produced unexpected error: {}", e);
                }
            }
        }
1
    }
    /// Creates a receiver and then makes it handle 2 sync packets with sequence numbers 0 and 1 respectively.
    /// The receiver is then given a sync packet with sequence number 0 which is the lower than the expected value of 2 so should be rejected.
    ///
    /// This shows that sequence numbers are correctly evaluated and packets rejected if the sequence number is too low for synchronisation packets.
    #[test]
1
    fn test_sync_packet_sequence_number_below_expected() {
        const UNIVERSE1: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let sync_packet = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0);
1
        let sync_packet2 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 1);
1
        let sync_packet3 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0); // This sync packet has a sequence number lower than the expected value of 2 so should be rejected.
        // Not interested in specific return values from this test, just assert the packets are processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected first sync packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet2)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected second sync packet"
        );
        // Check that the third sync packet with the low sequence number is rejected correctly with the expected OutOfSequence error.
1
        match dmx_rcv.handle_sync_packet(src_cid, sync_packet3) {
            Err(SacnError::OutOfSequence(..)) => {
1
                {};
            }
            Ok(_) => {
                panic!("Receiver incorrectly accepted third sync packet");
            }
            Err(e) => {
                panic!(
                    "Receiver correctly rejected third sync packet but with unexpected error: {}",
                    e
                );
            }
        }
1
    }
    /// Creates a receiver and then makes it handle 2 sync packets with sequence numbers 0 and 1 respectively.
    /// The receiver then resets the sequence number counters and then handles a sync packet with sequence number 0. This would normally be rejected
    /// as per `test_sync_packet_sequence_number_below_expected` but because of the reset it shouldn't be.
    ///
    /// This checks that the sync packet sequence numbers are reset correctly.
    #[test]
1
    fn test_sync_packet_sequence_number_reset() {
        const UNIVERSE1: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let sync_packet = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0);
1
        let sync_packet2 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 1);
1
        let sync_packet3 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0); // This sync packet has a sequence number lower than the expected value of 2 so should be rejected.
        // Not interested in specific return values from this test, just assert the packets are processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected first sync packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet2)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected second sync packet"
        );
1
        dmx_rcv.reset_sources();
        // Packet shouldn't be rejected.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet3)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected third sync packet"
        );
1
    }
    /// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively.
    /// The receiver then resets the sequence number counters and then handles a data packet with sequence number 0. This would normally be rejected
    /// as per `test_data_packet_sequence_number_below_expected` but because of the reset it shouldn't be.
    ///
    /// This checks that the data packet sequence numbers are reset correctly.
    #[test]
1
    fn test_data_packet_sequence_number_reset() {
        const UNIVERSE1: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE1]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let data_packet = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0);
1
        let data_packet2 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 1);
1
        let data_packet3 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0); // This data packet has a sequence number lower than the expected value of 2 so should be rejected.
        // Not interested in specific return values from this test, just assert the data is processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected first data packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet2)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected second data packet"
        );
1
        dmx_rcv.reset_sources();
        // Packet shouldn't be rejected.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet3)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected third data packet"
        );
1
    }
    /// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1.
    /// This then means the receiver will reject another data packet with sequence number 0.
    /// The receiver is then passed a sync packet with sequence number 0 which shouldn't be rejected as it is a different packet type.
    ///
    /// Shows sequence numbers are evaluated separately for each packet type as per ANSI E1.31-2018 Section 6.7.2.
    #[test]
1
    fn test_sequence_number_packet_type_independence() {
        const UNIVERSE: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let data_packet = generate_data_packet_framing_layer_seq_num(UNIVERSE, 0);
1
        let data_packet2 = generate_data_packet_framing_layer_seq_num(UNIVERSE, 1);
1
        let sync_packet = generate_sync_packet_framing_layer_seq_num(UNIVERSE, 0);
        // Not interested in specific return values from this test, just assert the data is processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected first data packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet2)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected second data packet"
        );
        // At this point the receiver should be expecting data_packet sequence number 2.
        // Pass the receiver a sync packet with sequence number 0.
        // If this isn't rejected it shows that the receiver correctly treats different packet types individually.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected synchronisation packet"
        );
1
    }
    /// Creates a receiver and then makes it handle 2 data packets for the same universe with sequence numbers 0 and 1.
    /// This then means the receiver will reject another data packet for that universe with sequence number 0.
    /// The receiver is then passed a data packet with sequence number 0 for a different universe which shouldn't be rejected as it is for a different universe.
    ///
    /// Shows sequence numbers are evaluated separately for each universe as per ANSI E1.31-2018 Section 6.7.2.
    #[test]
1
    fn test_data_packet_sequence_number_universe_independence() {
        const UNIVERSE1: u16 = 1;
        const UNIVERSE2: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.listen_universes(&[UNIVERSE1, UNIVERSE2]).unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let data_packet = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0);
1
        let data_packet2 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 1);
1
        let data_packet3 = generate_data_packet_framing_layer_seq_num(UNIVERSE2, 0);
        // Not interested in specific return values from this test, just assert the data is processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected first data packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet2)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected second data packet"
        );
        // At this point the receiver will (as shown by test_data_packet_sequence_number_below_expected) reject a data packet to UNIVERSE1 with sequence number 0
        // however this data packet is for UNIVERSE2 and so therefore should be accepted.
1
        assert!(
1
            dmx_rcv
1
                .handle_data_packet(src_cid, data_packet3)
1
                .unwrap()
1
                .is_some(),
            "Receiver incorrectly rejected third data packet"
        );
1
    }
    /// Creates a receiver and then makes it handle 2 sync packets for the same synchronisation address with sequence numbers 0 and 1.
    /// This then means the receiver will reject another sync packet for that universe with sequence number 0.
    /// The receiver is then passed a sync packet with sequence number 0 for a different synchronisation address which shouldn't be rejected as it is for
    /// a different synchronisation address.
    ///
    /// Shows sequence numbers are evaluated separately for each synchronisation address individually as per ANSI E1.31-2018 Section 6.7.2.
    #[test]
1
    fn test_sync_packet_sequence_number_universe_independence() {
        const SYNC_ADDR_1: u16 = 1;
        const SYNC_ADDR_2: u16 = 2;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv
1
            .listen_universes(&[SYNC_ADDR_1, SYNC_ADDR_2])
1
            .unwrap();
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let sync_packet = generate_sync_packet_framing_layer_seq_num(SYNC_ADDR_1, 0);
1
        let sync_packet2 = generate_sync_packet_framing_layer_seq_num(SYNC_ADDR_1, 1);
1
        let sync_packet3 = generate_sync_packet_framing_layer_seq_num(SYNC_ADDR_2, 0);
        // Not interested in specific return values from this test, just assert the data is processed successfully.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected first sync packet"
        );
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet2)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected second sync packet"
        );
        // At this point the receiver will (as shown by test_sync_packet_sequence_number_below_expected) reject a sync packet for SYNC_ADDR_1 with sequence number 0
        // however this sync packet is for SYNC_ADDR_2 and so therefore should be accepted.
1
        assert!(
1
            dmx_rcv
1
                .handle_sync_packet(src_cid, sync_packet3)
1
                .unwrap()
1
                .is_none(),
            "Receiver incorrectly rejected third sync packet"
        );
1
    }
    #[test]
1
    fn test_source_limit_0() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let source_limit: Option<usize> = Some(0);
1
        match SacnReceiver::with_ip(addr, source_limit) {
1
            Err(e) => match e {
                SacnError::SourceLimitZero() => {
1
                    {};
                }
                _ => {
                    panic!("Unexpected error type returned");
                }
            },
            _ => {
                panic!("SacnReceiver accepted 0 source limit when it shouldn't");
            }
        }
1
    }
    #[test]
1
    fn test_is_multicast_enabled() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        assert!(
1
            dmx_rcv.is_multicast_enabled(),
            "Multicast not enabled by default"
        );
1
    }
    #[test]
1
    fn test_set_is_multicast_enabled() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        dmx_rcv.set_is_multicast_enabled(false).unwrap();
1
        assert!(
1
            !dmx_rcv.is_multicast_enabled(),
            "Multicast not disabled correctly"
        );
1
    }
    #[test]
1
    fn test_clear_waiting_data() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
        const SYNC_ADDR: u16 = 1;
1
        let data: DMXData = DMXData {
1
            universe: 0,
1
            values: vec![1, 2, 3],
1
            sync_uni: SYNC_ADDR,
1
            priority: 100,
1
            src_cid: Some(Uuid::new_v4()),
1
            preview: false,
1
            recv_timestamp: Instant::now(),
1
        };
1
        dmx_rcv.store_waiting_data(data).unwrap();
1
        dmx_rcv.clear_all_waiting_data();
1
        assert_eq!(
1
            dmx_rcv.rtrv_waiting_data(SYNC_ADDR),
1
            Vec::new(),
            "Data was not reset as expected"
        );
1
    }
    #[test]
1
    fn test_get_announce_source_discovery() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        assert!(
1
            !dmx_rcv.get_announce_source_discovery(),
            "Announce source discovery is true by default when should be false"
        );
1
    }
    #[test]
1
    fn test_get_announce_timeout() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        assert!(
1
            !dmx_rcv.get_announce_timeout(),
            "Announce timeout flag is true by default when should be false"
        );
1
    }
    #[test]
1
    fn test_get_announce_stream_termination() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        assert!(
1
            !dmx_rcv.get_announce_stream_termination(),
            "Announce termination flag is true by default when should be false"
        );
1
    }
    /// Tests handling a sync packet for a synchronisation address which isn't currently being listened to.
    #[test]
1
    fn test_handle_sync_packet_not_listening_to_sync_addr() {
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut dmx_rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        let res = dmx_rcv
1
            .handle_sync_packet(
1
                Uuid::new_v4(),
1
                SynchronizationPacketFramingLayer {
1
                    sequence_number: 0,
1
                    synchronization_address: 1,
1
                },
1
            )
1
            .unwrap(); // Checks that no error is produced.
1
        assert_eq!(
1
            res, None,
            "Sync packet produced output when should have been ignored as for an address that isn't being listened to"
        );
1
    }
    /// Tests the equivalence of 2 `DMXDatas` which are only similar in the aspects used for checking equivalence.
    #[test]
1
    fn test_dmx_data_eq() {
        const UNIVERSE: u16 = 1;
1
        let values: Vec<u8> = vec![1, 2, 3];
        const SYNC_ADDR: u16 = 1;
        const PRIORITY: u8 = 100;
        const PREVIEW: bool = false;
1
        let data1 = DMXData {
1
            universe: UNIVERSE,
1
            values: values.clone(),
1
            sync_uni: SYNC_ADDR,
1

            
1
            // The below values can be different for 2 DMXData to be taken as equivalent.
1
            priority: PRIORITY,
1
            src_cid: Some(Uuid::new_v4()),
1
            preview: PREVIEW,
1
            recv_timestamp: Instant::now(),
1
        };
1
        let data2 = DMXData {
1
            universe: UNIVERSE,
1
            values,
1
            sync_uni: SYNC_ADDR,
1

            
1
            // The below values can be different for 2 DMXData to be taken as equivalent.
1
            priority: PRIORITY + 50,
1
            src_cid: None,
1
            preview: !PREVIEW,
1
            recv_timestamp: Instant::now(),
1
        };
1
        assert_eq!(
1
            data1, data2,
            "DMX data not seen as equivalent when should be"
        );
1
    }
    #[test]
1
    fn test_data_sequence_number_wraparound_255_to_0() {
        // This test is intended to validate ANSI E1.31-2018 sequence handling
        // using signed 8-bit arithmetic (wraparound at 255->0).
        //
        // Expected behavior:
        // - First packet from a source/universe should establish the baseline
        //   (regardless of its value; the standard does not require starting at 0).
        // - After receiving 250..255, receiving 0 should be accepted as a wrap.
        const UNIVERSE: u16 = 1;
1
        let src_cid: Uuid = Uuid::from_bytes([
1
            0xef, 0x07, 0xc8, 0xdd, 0x00, 0x64, 0x44, 0x01, 0xa3, 0xa2, 0x45, 0x9e, 0xf8, 0xe6,
1
            0x14, 0x3e,
1
        ]);
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[UNIVERSE]).unwrap();
        // Initial sequence number of new universe is 255 so send a valid new sequnce number to start.
1
        let pkt = generate_data_packet_framing_layer_seq_num(UNIVERSE, 21u8);
1
        let _ = rcv.handle_data_packet(src_cid, pkt);
        // Send a run up to wrap.
1
        for seq in 250u8..=255u8 {
6
            let pkt = generate_data_packet_framing_layer_seq_num(UNIVERSE, seq);
6
            let res = rcv.handle_data_packet(src_cid, pkt);
6
            assert!(
6
                res.is_ok(),
                "sequence {} should be accepted (got {:?})",
                seq,
                res
            );
        }
        // Now wrap to 0. This should be accepted as the next in-sequence packet.
1
        let pkt0 = generate_data_packet_framing_layer_seq_num(UNIVERSE, 0);
1
        let res0 = rcv.handle_data_packet(src_cid, pkt0);
1
        assert!(
1
            res0.is_ok(),
            "sequence wrap 255->0 should be accepted (got {:?})",
            res0
        );
        // And 1 should also be accepted.
1
        let pkt1 = generate_data_packet_framing_layer_seq_num(UNIVERSE, 1);
1
        let res1 = rcv.handle_data_packet(src_cid, pkt1);
1
        assert!(
1
            res1.is_ok(),
            "sequence 1 after wrap should be accepted (got {:?})",
            res1
        );
1
    }
    /// A packet from one source must not be discarded because a different source has timed out
    /// while `announce_timeout` is set.
    #[test]
1
    fn test_seq_check_keeps_packet_when_other_source_timed_out() {
1
        let mut seqs: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        let live = Uuid::new_v4();
1
        let dead = Uuid::new_v4();
1
        let expired = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(100);
1
        seqs.insert(
1
            live,
1
            HashMap::from([(1, TimedStampedSeqNo::new(10, Instant::now()))]),
1
        );
1
        seqs.insert(
1
            dead,
1
            HashMap::from([(1, TimedStampedSeqNo::new(10, expired))]),
1
        );
1
        let res = check_seq_number(&mut seqs, None, live, 11, 1, true, true);
1
        assert!(res.is_ok(), "in-sequence packet was rejected: {res:?}");
1
        assert_eq!(seqs[&live][&1].sequence_number, 11);
        // The timed out source is left in place so that the timeout check `recv` runs can still report it.
1
        assert!(seqs.contains_key(&dead));
1
    }
    /// A source that comes back after timing out starts a new sequence, even if the timed out entry
    /// hasn't been removed yet.
    #[test]
1
    fn test_seq_check_treats_timed_out_universe_as_new() {
1
        let mut seqs: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        let src = Uuid::new_v4();
1
        let expired = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(100);
1
        seqs.insert(
1
            src,
1
            HashMap::from([(1, TimedStampedSeqNo::new(10, expired))]),
1
        );
        // Sequence 5 is within the discard window relative to 10, but the old entry has timed out.
1
        let res = check_seq_number(&mut seqs, None, src, 5, 1, true, true);
1
        assert!(res.is_ok(), "packet after timeout was rejected: {res:?}");
1
        assert_eq!(seqs[&src][&1].sequence_number, 5);
1
    }
    /// Builds a data packet for `universe` that waits for a synchronisation packet on `sync_uni`.
5
    fn sync_data_packet<'a>(universe: u16, sync_uni: u16, seq: u8) -> DataPacketFramingLayer<'a> {
5
        let mut pkt = generate_data_packet_framing_layer_seq_num(universe, seq);
5
        pkt.synchronization_address = sync_uni;
5
        pkt
5
    }
    /// A synchronisation address named by a data packet is joined for its sync packets, but data sent on that universe
    /// isn't passed up unless the user listens to it.
    #[test]
1
    fn test_sync_universe_not_added_to_data_universes() {
        const DATA_UNI: u16 = 1;
        const SYNC_UNI: u16 = 7;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[DATA_UNI]).unwrap();
1
        let src = Uuid::new_v4();
        // Synchronisation hasn't started yet, so the data is passed up straight away.
1
        assert!(
1
            rcv.handle_data_packet(src, sync_data_packet(DATA_UNI, SYNC_UNI, 0))
1
                .unwrap()
1
                .is_some()
        );
1
        assert!(!rcv.is_listening(&SYNC_UNI));
1
        assert!(rcv.sync_universes.contains_key(&SYNC_UNI));
        // Data on the synchronisation universe is ignored: the user never listened to it.
1
        let on_sync_uni = generate_data_packet_framing_layer_seq_num(SYNC_UNI, 0);
1
        assert!(rcv.handle_data_packet(src, on_sync_uni).unwrap().is_none());
        // The sync packet is still received, starting synchronisation.
1
        assert!(
1
            rcv.handle_sync_packet(src, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
                .unwrap()
1
                .is_none()
        );
1
        assert!(
1
            rcv.handle_data_packet(src, sync_data_packet(DATA_UNI, SYNC_UNI, 1))
1
                .unwrap()
1
                .is_none()
        );
        // The next sync packet releases the waiting data.
1
        let released = rcv
1
            .handle_sync_packet(src, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 1))
1
            .unwrap()
1
            .expect("sync packet should release the waiting data");
1
        assert_eq!(released.len(), 1);
1
        assert_eq!(released[0].universe, DATA_UNI);
1
    }
    /// A synchronisation universe nobody has named for the data loss timeout is forgotten, so its sync packets are
    /// ignored and its multicast group can be left.
    #[test]
1
    fn test_sync_universe_expires() {
        const DATA_UNI: u16 = 1;
        const SYNC_UNI: u16 = 7;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[DATA_UNI]).unwrap();
1
        let src = Uuid::new_v4();
1
        rcv.handle_data_packet(src, sync_data_packet(DATA_UNI, SYNC_UNI, 0))
1
            .unwrap();
1
        let expired = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(1);
1
        rcv.sync_universes.insert(SYNC_UNI, expired);
1
        rcv.expire_sync_universes();
1
        assert!(!rcv.sync_universes.contains_key(&SYNC_UNI));
1
        let res = rcv
1
            .handle_sync_packet(src, generate_sync_packet_framing_layer_seq_num(SYNC_UNI, 0))
1
            .unwrap();
1
        assert!(
1
            res.is_none(),
            "sync packet on a forgotten universe was acted on"
        );
        // Naming it again joins it again without error.
1
        rcv.handle_data_packet(src, sync_data_packet(DATA_UNI, SYNC_UNI, 1))
1
            .unwrap();
1
        assert!(rcv.sync_universes.contains_key(&SYNC_UNI));
1
    }
    /// Listening to, then muting, a universe that is also in use for synchronisation must not join its group twice or
    /// leave it while it is still needed for sync packets.
    #[test]
1
    fn test_listen_and_mute_universe_also_used_for_sync() {
        const DATA_UNI: u16 = 1;
        const SYNC_UNI: u16 = 7;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[DATA_UNI]).unwrap();
1
        let src = Uuid::new_v4();
1
        rcv.handle_data_packet(src, sync_data_packet(DATA_UNI, SYNC_UNI, 0))
1
            .unwrap();
        // Joining the same group twice fails on Linux (EADDRINUSE), so this would error if it re-joined.
1
        rcv.listen_universes(&[SYNC_UNI]).unwrap();
1
        assert!(rcv.is_listening(&SYNC_UNI));
1
        rcv.mute_universe(SYNC_UNI).unwrap();
1
        assert!(!rcv.is_listening(&SYNC_UNI));
1
        assert!(rcv.sync_universes.contains_key(&SYNC_UNI));
        // Still joined: the group can be left once, when the sync universe expires. Leaving a group that isn't joined
        // errors, so a second leave here would fail.
1
        rcv.sync_universes.insert(
1
            SYNC_UNI,
1
            Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(1),
1
        );
1
        rcv.expire_sync_universes();
        #[cfg(not(target_os = "windows"))]
1
        assert!(rcv.receiver.mute_multicast_universe(SYNC_UNI).is_err());
1
    }
    /// A data packet like `generate_data_packet_framing_layer_seq_num` but with the given START code.
2
    fn start_code_data_packet<'a>(
2
        universe: u16,
2
        seq: u8,
2
        start_code: u8,
2
    ) -> DataPacketFramingLayer<'a> {
2
        let mut pkt = generate_data_packet_framing_layer_seq_num(universe, seq);
2
        let mut vals = TEST_NULL_START_CODE_DATA.to_vec();
2
        vals[0] = start_code;
2
        pkt.data.property_values = Cow::from(vals);
2
        pkt
2
    }
    /// A termination packet that is also marked as preview data still terminates the stream when preview data is ignored.
    #[test]
1
    fn test_preview_termination_packet_terminates_when_ignoring_preview() {
        const UNIVERSE: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        rcv.set_process_preview_data(false);
1
        rcv.set_announce_stream_termination(true);
1
        let src = Uuid::new_v4();
1
        rcv.handle_data_packet(src, generate_data_packet_framing_layer_seq_num(UNIVERSE, 0))
1
            .unwrap();
1
        assert!(rcv.sequences.data_sequences[&src].contains_key(&UNIVERSE));
1
        let mut term = generate_data_packet_framing_layer_seq_num(UNIVERSE, 1);
1
        term.preview_data = true;
1
        term.stream_terminated = true;
1
        match rcv.handle_data_packet(src, term) {
            Err(SacnError::UniverseTerminated(cid, uni)) => {
1
                assert_eq!(cid, src);
1
                assert_eq!(uni, UNIVERSE);
            }
            other => panic!("expected UniverseTerminated, got {other:?}"),
        }
1
        assert!(
1
            rcv.sequences
1
                .data_sequences
1
                .get(&src)
                .is_none_or(|unis| !unis.contains_key(&UNIVERSE)),
            "terminated universe is still tracked"
        );
1
    }
    /// Ordinary preview data is still ignored when the receiver doesn't process preview data.
    #[test]
1
    fn test_preview_data_ignored_when_not_processing_preview() {
        const UNIVERSE: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        rcv.set_process_preview_data(false);
1
        let src = Uuid::new_v4();
1
        let mut pkt = generate_data_packet_framing_layer_seq_num(UNIVERSE, 0);
1
        pkt.preview_data = true;
1
        assert!(rcv.handle_data_packet(src, pkt).unwrap().is_none());
1
        assert!(!rcv.sequences.data_sequences.contains_key(&src));
1
    }
    /// Alternate START Code data updates the sequence number of a live stream but doesn't reset its data loss timer.
    #[test]
1
    fn test_alternate_start_code_does_not_refresh_timeout() {
1
        let mut seqs: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        let src = Uuid::new_v4();
1
        let last_null = Instant::now() - Duration::from_secs(2);
1
        seqs.insert(
1
            src,
1
            HashMap::from([(1, TimedStampedSeqNo::new(10, last_null))]),
1
        );
1
        let res = check_seq_number(&mut seqs, None, src, 11, 1, false, false);
1
        assert!(res.is_ok(), "in-sequence 0xDD packet was rejected: {res:?}");
1
        assert_eq!(seqs[&src][&1].sequence_number, 11);
1
        assert_eq!(
1
            seqs[&src][&1].last_recv, last_null,
            "0xDD packet reset the data loss timer"
        );
        // The sequence check still applies to alternate START Code packets on a live stream.
1
        assert!(matches!(
1
            check_seq_number(&mut seqs, None, src, 9, 1, false, false),
            Err(SacnError::OutOfSequence(..))
        ));
        // Null START Code data resets the timer.
1
        check_seq_number(&mut seqs, None, src, 12, 1, false, true).unwrap();
1
        assert!(seqs[&src][&1].last_recv > last_null);
1
    }
    /// Alternate START Code data from a new or timed out source starts a data loss timer, so that it can time out.
    #[test]
1
    fn test_alternate_start_code_new_source_starts_timer() {
1
        let mut seqs: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        let new_src = Uuid::new_v4();
1
        let before = Instant::now();
1
        assert!(check_seq_number(&mut seqs, None, new_src, 0, 1, true, false).is_ok());
1
        assert!(seqs[&new_src][&1].last_recv >= before);
1
        let dead = Uuid::new_v4();
1
        let expired = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT - Duration::from_millis(100);
1
        seqs.insert(
1
            dead,
1
            HashMap::from([(1, TimedStampedSeqNo::new(10, expired))]),
1
        );
1
        assert!(check_seq_number(&mut seqs, None, dead, 5, 1, true, false).is_ok());
1
        assert_eq!(seqs[&dead][&1].sequence_number, 5);
1
        assert!(seqs[&dead][&1].last_recv > expired);
1
    }
    /// The source limit still applies to alternate START Code data from a new source.
    #[test]
1
    fn test_alternate_start_code_respects_source_limit() {
1
        let mut seqs: HashMap<Uuid, HashMap<u16, TimedStampedSeqNo>> = HashMap::new();
1
        seqs.insert(
1
            Uuid::new_v4(),
1
            HashMap::from([(1, TimedStampedSeqNo::new(0, Instant::now()))]),
1
        );
1
        assert!(matches!(
1
            check_seq_number(&mut seqs, Some(1), Uuid::new_v4(), 0, 1, true, false),
            Err(SacnError::SourcesExceededError(1))
        ));
1
    }
    /// A source sending only 0xDD per-address priority data times out even though its packets keep arriving.
    #[test]
1
    fn test_receiver_alternate_start_code_only_source_times_out() {
        const UNIVERSE: u16 = 1;
1
        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), ACN_SDT_MULTICAST_PORT);
1
        let mut rcv = SacnReceiver::with_ip(addr, None).unwrap();
1
        rcv.listen_universes(&[UNIVERSE]).unwrap();
1
        rcv.set_announce_timeout(true);
1
        let src = Uuid::new_v4();
1
        rcv.handle_data_packet(
1
            src,
1
            start_code_data_packet(UNIVERSE, 0, E131_NULL_START_CODE),
1
        )
1
        .unwrap();
        // Age the Null START Code stream to just short of the data loss timeout.
1
        let expired = Instant::now() - E131_NETWORK_DATA_LOSS_TIMEOUT + Duration::from_millis(50);
1
        rcv.sequences
1
            .data_sequences
1
            .get_mut(&src)
1
            .unwrap()
1
            .get_mut(&UNIVERSE)
1
            .unwrap()
1
            .last_recv = expired;
        // 0xDD data is still delivered, but doesn't keep the source alive.
1
        let data = rcv
1
            .handle_data_packet(src, start_code_data_packet(UNIVERSE, 1, 0xDD))
1
            .unwrap()
1
            .unwrap();
1
        assert_eq!(data[0].values[0], 0xDD);
1
        std::thread::sleep(Duration::from_millis(100));
1
        assert!(matches!(
1
            rcv.sequences.check_timeouts(true),
1
            Err(SacnError::UniverseTimeout(cid, UNIVERSE)) if cid == src
        ));
1
    }
}