Skip to main content

rtflow_multicast/
lib.rs

1//! Multicast RTP transport (RFC 3550 ยง2).
2//!
3//! Provides multicast group management for RTP delivery to multiple receivers
4//! without per-subscriber unicast streams. Uses IGMP join/leave on the
5//! underlying UDP socket.
6
7use rtflow_core::error::{Error, Result};
8use std::net::{IpAddr, Ipv4Addr, SocketAddr};
9use tokio::net::UdpSocket;
10
11/// Receive buffer for the group socket, matching the unicast RTP default.
12///
13/// The kernel default (~208 KiB) holds roughly 80 ms at 20 Mbit/s, so an IDR
14/// burst on a busy group overruns it and the losses surface as decoder
15/// artifacts. `SO_RCVBUF` is silently clamped to `net.core.rmem_max`.
16const RECEIVE_BUFFER_SIZE: usize = 4 * 1024 * 1024;
17/// Send buffer for a multicast sender.
18const SEND_BUFFER_SIZE: usize = 1024 * 1024;
19
20/// Multicast group configuration.
21///
22/// Parsed from SDP `c=IN IP4 <group>/<ttl>` lines or constructed directly
23/// for server-side multicast publishing.
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct MulticastConfig {
26    /// Multicast group address (e.g. 239.1.1.1).
27    pub group: IpAddr,
28    /// RTP port number.
29    pub port: u16,
30    /// Multicast TTL (time-to-live). Default 1 = link-local.
31    pub ttl: u8,
32    /// Optional local interface address to bind to.
33    pub interface: Option<IpAddr>,
34}
35
36impl MulticastConfig {
37    /// Create a new multicast configuration.
38    pub fn new(group: IpAddr, port: u16) -> Self {
39        Self {
40            group,
41            port,
42            ttl: 1,
43            interface: None,
44        }
45    }
46
47    /// Set the multicast TTL.
48    pub fn with_ttl(mut self, ttl: u8) -> Self {
49        self.ttl = ttl;
50        self
51    }
52
53    /// Set the local interface.
54    pub fn with_interface(mut self, interface: IpAddr) -> Self {
55        self.interface = Some(interface);
56        self
57    }
58
59    /// Create a multicast UDP socket, bind it, and join the group.
60    ///
61    /// The socket is bound to `0.0.0.0:<port>` (required for multicast receive)
62    /// and joined to the multicast group on the specified or default interface.
63    pub async fn bind(&self) -> Result<UdpSocket> {
64        let bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), self.port);
65        let domain = socket2::Domain::IPV4;
66        let raw = socket2::Socket::new(domain, socket2::Type::DGRAM, Some(socket2::Protocol::UDP))
67            .map_err(Error::Io)?;
68        // Multiple receivers on one host must be able to join the same
69        // group/port (standard multicast deployment).
70        raw.set_reuse_address(true).map_err(Error::Io)?;
71        raw.set_nonblocking(true).map_err(Error::Io)?;
72        // Best effort: a host with a lower `rmem_max` keeps the smaller
73        // buffer instead of failing the join.
74        let _ = raw.set_recv_buffer_size(RECEIVE_BUFFER_SIZE);
75        let _ = raw.set_send_buffer_size(SEND_BUFFER_SIZE);
76        raw.bind(&bind_addr.into()).map_err(Error::Io)?;
77        let socket = UdpSocket::from_std(raw.into()).map_err(Error::Io)?;
78
79        if let IpAddr::V4(group_v4) = self.group {
80            let interface_v4 = match self.interface {
81                Some(IpAddr::V4(iface)) => iface,
82                _ => Ipv4Addr::UNSPECIFIED,
83            };
84            socket.join_multicast_v4(group_v4, interface_v4)?;
85            socket.set_multicast_ttl_v4(u32::from(self.ttl))?;
86        } else {
87            return Err(Error::Unsupported(
88                "IPv6 multicast not yet supported".into(),
89            ));
90        }
91
92        Ok(socket)
93    }
94
95    /// Check if an address is a multicast address.
96    pub fn is_multicast(addr: &IpAddr) -> bool {
97        match addr {
98            IpAddr::V4(v4) => v4.is_multicast(),
99            IpAddr::V6(v6) => v6.is_multicast(),
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn is_multicast_detects_ranges() {
110        assert!(MulticastConfig::is_multicast(&"239.1.1.1".parse().unwrap()));
111        assert!(MulticastConfig::is_multicast(&"224.0.0.1".parse().unwrap()));
112        assert!(!MulticastConfig::is_multicast(
113            &"192.168.1.1".parse().unwrap()
114        ));
115        assert!(!MulticastConfig::is_multicast(&"10.0.0.1".parse().unwrap()));
116        assert!(MulticastConfig::is_multicast(&"ff02::1".parse().unwrap()));
117    }
118
119    #[test]
120    fn config_builder() {
121        let cfg = MulticastConfig::new("239.1.1.1".parse().unwrap(), 5004)
122            .with_ttl(16)
123            .with_interface("192.168.1.100".parse().unwrap());
124        assert_eq!(cfg.ttl, 16);
125        assert_eq!(cfg.interface, Some("192.168.1.100".parse().unwrap()));
126    }
127}