// This file was modified as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
// Documentation of private or crate local items that effects public items, such as errors from private functions which get passed up to a
// public function, should be copied into the documentation of the public item so that the public facing documentation is a complete documentation
/// The name of the thread which runs periodically to perform various actions such as universe discovery adverts for the source.
/// The default startcode used to send stream termination packets when the `SacnSource` is closed.
/// Discovery updates are sent every `E131_UNIVERSE_DISCOVERY_INTERVAL` so the poll rate must be lower than or equal to this.
/// let local_addr: SocketAddr = SocketAddr::new(IpAddr::V4("0.0.0.0".parse().unwrap()), ACN_SDT_MULTICAST_PORT + 1);
/// let sync_uni: Option<u16> = None; // Don't want the packet to be delayed on the receiver awaiting synchronisation.
/// let priority: u8 = 100; // The priority for the sending data, must be 1-200 inclusive, None means use default.
/// let dst_ip: Option<SocketAddr> = None; // Sending the data using IP multicast so don't have a destination IP.
/// src.register_universe(universe).unwrap(); // Register with the source that will be sending on the given universe.
/// let mut data: Vec<u8> = vec![0, 0, 0, 0, 255, 255, 128, 128]; // Some arbitrary data, must have length <= 513 (including start-code).
/// src.send(&[universe], &data, Some(priority), dst_ip, sync_uni).unwrap(); // Actually send the data
/// Protected by a Mutex lock to allow concurrent access between user threads and the update thread below.
/// Update thread which performs actions every `DEFAULT_POLL_PERIOD` such as checking if a universe
/// to allow access by the `update_thread` which is used to manage sending periodic universe discovery packets.
/// It is the job of the user of the library to ensure that the cid is given on creation of the `SacnSourceInternal` is unique.
/// Flag which is included in sACN packets to indicate that the data shouldn't be used for live output
/// (ie. on actual lighting fixtures). A receiver may or may not be compliant with this so it should not be relied
/// Flag which is included in sACN data packets that have a synchronisation address. It tells receivers what to do if
/// synchronisation is lost, as per ANSI E1.31-2016 Section 6.2.6 (`Force_Synchronization`). If false receivers hold the
/// data until synchronisation resumes, if true they may process the data without waiting for a synchronisation packet.
/// The sequence numbers used for data packets, keeps a reference of the next sequence number to use for each universe.
/// The sequence numbers used for sync packets, keeps a reference of the next sequence number to use for each universe.
/// Flag that indicates if the `SacnSourceInternal` is running (the update thread should be triggering periodic discovery packets).
/// Flag that is set to True to indicate that the source is sending periodic universe discovery packets.
/// Constructs a new `SacnSource` with the given name, binding to an IPv4 address on an ephemeral port.
/// Constructs a new `SacnSource` with the given name and specified CID binding to an IPv4 address.
// Use an ephemeral port. Binding the ACN port would put this socket in the receivers' `SO_REUSEPORT` group,
// and Linux would then hand some of the unicast sACN addressed to this host to this socket, where it is never read.
/// Constructs a new `SacnSource` with the given name, binding to an IPv6 address on an ephemeral port.
/// By default this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
/// Constructs a new `SacnSource` with the given name and specified CID binding to an IPv6 address.
// Use an ephemeral port. Binding the ACN port would put this socket in the receivers' `SO_REUSEPORT` group,
// and Linux would then hand some of the unicast sACN addressed to this host to this socket, where it is never read.
/// Avoid binding to `ACN_SDT_MULTICAST_PORT` if a `SacnReceiver` may run on the same host. The socket would share the
/// port with the receiver, and on Linux some unicast sACN sent to this host would be delivered to the source's socket
/// Io: Returned if the underlying UDP socket cannot be created and bound or if the thread used for sending periodic
/// discovery adverts fails to be created. Causes can be distinguished by looking at the error chain.
/// `MalformedSourceName`: Returned if the given source name is longer than the maximum allowed size of `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
// On error the source keeps running and tries again on the next period. With the `logging` feature the
// error is reported through the `log` crate, so the application decides whether and where it is shown.
/// This allows sending data to those universes or using them as synchronisation addresses as well as adding them to
/// the list of universes that appear in universe discovery packets that are sent (depending on the
/// This is more efficient than repeated calls to `register_universe` as it means only 1 mutex unlock is required.
/// universes: The sACN universes to register for usage as data universes and/or synchronisation addresses. Note that sACN
/// `IllegalUniverse`: Returned if a universe is outwith the range permitted by ANSI E1.31-2018.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// This allows sending data to those universes or using them as synchronisation addresses as well as adding them to
/// the list of universes that appear in universe discovery packets that are sent (depending on the
/// universe: The sACN universe to register for usage as a data universe and/or synchronisation address. Note that sACN
/// `IllegalUniverse`: Returned if the universe is outwith the range permitted by ANSI E1.31-2018.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Sends the given data to the given universes with the given priority, synchronisation address (universe) and destination ip.
/// universe: The sACN universes that the data should be set on, the data will be split over these universes with each `UNIVERSE_CHANNEL_CAPACITY`
/// priority: The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`),
/// if a value of None is provided then the default of `E131_DEFAULT_PRIORITY` (`const.E131_DEFAULT_PRIORITY.packet`) is used.
/// `dst_ip`: The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
/// `sync_address`: The address to use for synchronisation, must be a valid universe, None indicates no synchronisation. If synchronisation is required a
/// It doesn't need to be registered, so a universe used only for synchronisation isn't advertised in
/// As per ANSI E1.31-2018 Section 6.6.1 this method shouldn't be called at a higher refresher rate than specified in ANSI E1.11 \[DMX\] unless
/// configured by the user to do so in an environment which doesn't contain any E1.31 to DMX512-A converters.
/// Note as per ANSI-E1.31-2018 Appendix B.1 it is recommended to have a small delay before sending the follow up sync packet.
/// `SenderAlreadyTerminated`: Returned if this method is called on an `SacnReceiverInternal` that has already terminated.
/// `InvalidInput`: Returned if the data array has length 0 or if an insufficient number of universes for the given data are provided (each universe takes 513 bytes of data).
/// `InvalidPriority`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range as specified by ANSI E1.31-2018 Section 6.2.7.
/// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
/// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe (`packet::UNIVERSE_CHANNEL_CAPACITY`).
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Sends a synchronisation packet to trigger the sending of packets waiting to be sent together.
/// A common pattern would be to use the send method to send data to all the universes that should be synchronised using a
/// chosen synchronisation universe then wait for a small time as per the recommendation in ANSI-E1.31-2018 Appendix B.1 and
/// then send a synchronisation packet with the address of the synchronisation universe chosen to trigger the packets.
/// `dst_ip`: The destination IP address for this packet or None if it should be sent using multicast.
/// The universe doesn't need to be registered: a synchronisation universe carries no data, so it is left out of universe discovery.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
pub fn send_sync_packet(&mut self, universe: u16, dst_ip: Option<SocketAddr>) -> Result<()> {
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Terminates sending on the given universe, sending the termination packets to the given unicast destinations.
/// `terminate_stream` sends the termination packets only to the universe's multicast group, so a receiver that was
/// sent the universe's data by unicast and hasn't joined that group never sees them. It then only notices the
/// source has gone after the network data loss timeout. Pass the same destinations that were given to `send` here
/// The `E131_TERMINATE_STREAM_PACKET_COUNT` termination packets are sent to each destination in turn, then the
/// universe is deregistered. If `dst_ips` is empty this behaves exactly like `terminate_stream` (multicast).
/// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// Io: Returned if the termination packets fail to be sent on the socket. The packets are still sent to the
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// cid: The new CID identifier for this source. It is left to the user to ensure that this is always unique within the network the source is in.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// name: The new name for the source, it is left to the user to ensure this is unique within the sACN network.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `MalformedSourceName`: Returned to indicate that the given source name is longer than the maximum allowed as per `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `preview_mode`: If true then all data packets from this `SacnSource` will have the `Preview_Data` flag set to true indicating that the data is not
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Returns the value of the `Force_Synchronization` option set on data packets sent by this `SacnSource`.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Sets the `Force_Synchronization` option on data packets sent by this `SacnSource`, as per ANSI E1.31-2016 Section 6.2.6.
/// The option tells receivers what to do with synchronised data (data sent with a synchronisation address) if synchronisation is lost,
/// meaning no synchronisation packet has been received on that address within `E131_NETWORK_DATA_LOSS_TIMEOUT`:
/// - true: receivers may process the data straight away without waiting for a synchronisation packet.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// val: The new value for the `is_sending_discovery` flag, if true then source will send periodic universe discovery packets
/// Returns the multicast time to live of the socket (the multicast hop limit for an IPv6 source).
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Returns the current Time To Live for unicast packets send by this source (the unicast hop limit for an IPv6 source).
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Sets the Time To Live for packets sent by this source (the unicast hop limit for an IPv6 source).
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// Sets if multicast loop is enabled for an IPv4 source. Returns an error on an IPv6 source; use `set_multicast_loop` instead.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
/// By implementing the Drop trait for `SacnSource` it means that the user doesn't have to explicitly clean up the source
/// and if it goes out of reference it will clean itself up and send the required termination packets etc.
// The guard is dropped at the end of this statement so the update thread can see `running` change.
// As drop isn't always explicitly called and cannot return an error the error can't be returned. Memory safety is
// Internal is accessed twice separately, this allows the discovery thread to interleave between running being set to false speeding up termination.
// For same reasons as above a potential error can't be returned and a 'best attempt' is used to clean up.
// As drop isn't always explicitly called and cannot return an error the error is ignored. Memory safety is maintain and this prevents causing a panic!.
// The update thread only panics if the mutex was poisoned. Panicking here as well would abort the
/// Constructs a new `SacnSourceInternal` with DMX START code set to 0 with specified CID and binding IP address.
/// By default for an IPv6 address this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
/// Io: Returned if the underlying socket cannot be created or the IP cannot be bound to the underlying socket. See (`UdpBuilder::new_v4`)[`fn.new_v4.UdpBuilder`], (`UdpBuilder::new_v6`)[`fn.new_v6.UdpBuilder`] and (`Socket::bind`)[fn.bind.Socket2].
// Multiple different processes might want to send to the sACN stream so therefore need to allow re-using the ACN port.
/// will be sent otherwise (and by default) they will be sent every `UNIVERSE_DISCOVERY_INTERVAL`.
/// `IllegalUniverse`: Returned if the universe can't carry data, see (`is_data_universe_in_range`)[`fn.is_data_universe_in_range.packet`].
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range, see [`is_universe_in_range`](crate::packet::is_universe_in_range).
/// Checks if the given universe is a valid universe to send on (within allowed range) and that it is registered with this `SacnSourceInternal`.
/// `IllegalUniverse`: Returned if the universe can't carry data, see (`is_data_universe_in_range`)[`fn.is_data_universe_in_range.packet`].
/// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
/// Sends the given data to the given universes with the given priority, synchronisation address (universe) and destination ip.
/// universe: The sACN universes that the data should be set on, the data will be split over these universes with each `UNIVERSE_CHANNEL_CAPACITY`
/// priority: The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`),
/// if a value of None is provided then the default of `E131_DEFAULT_PRIORITY` (`const.E131_DEFAULT_PRIORITY.packet`) is used.
/// `dst_ip`: The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
/// `sync_address`: The address to use for synchronisation, must be a valid universe, None indicates no synchronisation. If synchronisation is required a
/// It doesn't need to be registered, so a universe used only for synchronisation isn't advertised in
/// As per ANSI E1.31-2018 Section 6.6.1 this method shouldn't be called at a higher refresher rate than specified in ANSI E1.11 \[DMX\] unless
/// configured by the user to do so in an environment which doesn't contain any E1.31 to DMX512-A converters.
/// Note as per ANSI-E1.31-2018 Appendix B.1 it is recommended to have a small delay before sending the follow up sync packet.
/// `SenderAlreadyTerminated`: Returned if this method is called on an `SacnReceiverInternal` that has already terminated.
/// `InvalidInput`: Returned if the data array has length 0 or if an insufficient number of universes for the given data are provided (each universe takes 513 bytes of data).
/// `InvalidPriority`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range as specified by ANSI E1.31-2018 Section 6.2.7.
/// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
/// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe (`packet::UNIVERSE_CHANNEL_CAPACITY`).
// This prevents leaving the source in an inconsistent state if later a universe is found to be invalid.
// Check that the synchronisation universe is a valid universe. It doesn't need to be registered: a synchronisation
// + 1 as there must be at least 1 universe required as the data isn't empty then additional universes for any more.
/// Sends the given data to the given universe with the given priority, synchronisation address (universe) and destination ip.
/// data: The data that should be sent, must be less than or equal in length to `UNIVERSE_CHANNEL_CAPACITY(const.UNIVERSE_CHANNEL_CAPACITY.packet)`.
/// priority: The E131 priority that the data should be sent with, must be less than `E131_MAX_PRIORITY` (`const.E131_MAX_PRIORITY.packet`), default `E131_DEFAULT_PRIORITY`.
/// `dst_ip`: The destination IP, can be Ipv4 or Ipv6, None if should be sent using ip multicast.
/// `sync_address`: The address to use for synchronisation, must be a valid universe, 0 indicates no synchronisation.
/// `InvalidInput`: Returned if the priority is greater than the allowed maximum priority of `E131_MAX_PRIORITY`.
/// `ExceedUniverseCapacity`: Returned if the data has a length greater than the maximum allowed within a universe.
/// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
/// see (`universe_to_ipv4_multicast_addr`)[`fn.universe_to_ipv4_multicast_addr.packet`] and (`universe_to_ipv6_multicast_addr`)[`fn.universe_to_ipv6_multicast_addr.packet`].
"Sending sACN data packet: universe {universe}, sequence {sequence}, priority {priority}, sync address {sync_address}, {} bytes, destination {}",
/// Sends a synchronisation packet to trigger the sending of packets waiting to be sent together.
/// A common pattern would be to use the send method to send data to all the universes that should be synchronised using a
/// chosen synchronisation universe then wait for a small time as per the recommendation in ANSI-E1.31-2018 Appendix B.1 and
/// then send a synchronisation packet with the address of the synchronisation universe chosen to trigger the packets.
/// `dst_ip`: The destination IP address for this packet or None if it should be sent using multicast.
/// The universe doesn't need to be registered: a synchronisation universe carries no data, so it is left out of universe discovery.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// In normal usage this method would be called three times to send three packets for termination as per
/// `dst_ip`: The destination IP address for this packet or None if it should be sent using multicast.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// `UniverseNotRegistered`: Returned if the universe is not registered on the given `SacnSourceInternal`.
/// Terminates a stream to the specified universe by sending packets with the `Stream_Terminated` flag set to 1.
/// Number of packets sent as per section 6.2.6 , `Stream_Terminated`: Bit 6 of ANSI E1.31-2018.
/// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of sACN universes as defined in ANSI E1.31-2018 Section 6.2.7.
/// Terminates a universe stream, sending the termination packets to each of the given unicast destinations.
// Keep going after a failed send so one unreachable destination doesn't stop the others being told.
/// `start_code`: used for the first byte of the otherwise empty data payload to indicate the `start_code` of the data.
let universes = self.universes.clone(); // About to start manipulating self.universes as universes are removed so clone original list.
// Attempt every universe even if one fails, so a single send error doesn't leave the remaining universes
// terminate_stream only deregisters after its packets were sent; the source is shutting down so
/// Sends a universe discovery packet advertising the universes that this source is registered to send.
/// This packet may be broken down into multiple pages internally resulting in multiple UDP packets.
/// There may be 1 or more pages for each full universe discovery packet with each page sent separately.
/// cid: The new CID identifier for this source. It is left to the user to ensure that this is always unique within the network the source is in.
/// name: The new name for the source, it is left to the user to ensure this is unique within the sACN network.
/// `MalformedSourceName`: Returned to indicate that the given source name is longer than the maximum allowed as per `E131_SOURCE_NAME_MAX_LENGTH` (63 bytes, leaving room for the null terminator).
/// `preview_mode`: If true then all data packets from this `SacnSourceInternal` will have the `Preview_Data` flag set to true indicating that the data is not
/// This centralises the locking of the source to a single point within the code allowing any changes to the mechanism to be made in one place.
/// `SourceCorrupt`: Returned if the Mutex used to control access to the internal sender is poisoned by a thread encountering
// The PoisonError returned doesn't contain further information and just allows access to the internal potentially inconsistent sender which
// Cannot directly return the PoisonError due to PoisonError using a different error system to other std modules which doesn't work with
/// This centralises the locking of the source to a single point within the code allowing any changes to the mechanism to be made in one place.
/// Returns an `SourceCorrupt` error if the Mutex used to control access to the internal sender is poisoned by a thread encountering
// The PoisonError returned doesn't contain further information and just allows access to the internal potentially inconsistent sender which
// Cannot directly return the PoisonError due to PoisonError using a different error system to other std modules which doesn't work with
/// src: A reference to the `SacnSourceInternal` for which to send the universe discovery packet with/from.
/// Returns a `SourceCorrupt` error if the internal source mutex has been corrupted, see [`unlock_internal`].
/// Returns an error if a discovery packet cannot be sent, see (`send_universe_discovery`)[`fn.send_universe_discovery.source`].
/// Returns one `(page, last_page, universes)` entry per page, each holding at most `DISCOVERY_UNI_PER_PAGE` universes.
/// A list of n universes gives ceil(n / 512) pages with a last page of `(n - 1) / 512`, so a source with no universes
/// sends no discovery packet at all and an exact multiple of 512 does not produce a trailing empty page.
// A u16 universe field and no duplicates give at most 65536 / 512 = 128 pages, so the page numbers fit in a u8.
/// A send failure on one universe must not stop the remaining universes from being terminated.