Skip to main content

rtflow_rtsp/transport/
mod.rs

1//! Transport-independent RTP delivery primitives shared by client and server.
2use bytes::{Buf, Bytes, BytesMut};
3use rtflow_core::error::{Error, Result};
4use socket2::{Domain, Protocol, Socket, Type};
5use std::{
6    net::{IpAddr, SocketAddr},
7    ops::RangeInclusive,
8    str::FromStr,
9    sync::Arc,
10};
11use tokio::net::UdpSocket;
12
13/// RTSP `Transport: mode=` parameter.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum TransportMode {
16    Play,
17    Record,
18}
19
20impl TransportMode {
21    fn parse(value: &str) -> Result<Self> {
22        if value.eq_ignore_ascii_case("play") {
23            Ok(Self::Play)
24        } else if value.eq_ignore_ascii_case("record") {
25            Ok(Self::Record)
26        } else {
27            Err(Error::Rtsp("unsupported Transport mode".into()))
28        }
29    }
30
31    fn as_str(self) -> &'static str {
32        match self {
33            Self::Play => "play",
34            Self::Record => "record",
35        }
36    }
37}
38
39#[derive(Clone, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub enum TransportSpec {
42    Udp {
43        client_rtp: u16,
44        client_rtcp: u16,
45        server_rtp: Option<u16>,
46        server_rtcp: Option<u16>,
47        /// RTCP is multiplexed on the RTP port (`rtcp-mux`, RFC 7826 ยง4.1).
48        rtcp_mux: bool,
49        /// SRTP (`RTP/SAVP`) is required for this transport.
50        secure: bool,
51        /// Optional multicast/unicast destination hint.
52        destination: Option<IpAddr>,
53        /// Optional source-address hint.
54        source: Option<IpAddr>,
55        /// Optional `mode=play|record`.
56        mode: Option<TransportMode>,
57    },
58    TcpInterleaved {
59        rtp_channel: u8,
60        rtcp_channel: u8,
61        /// RTCP is multiplexed on the RTP interleaved channel.
62        rtcp_mux: bool,
63        /// SRTP (`RTP/SAVP`) is required for this transport.
64        secure: bool,
65        /// Optional `mode=play|record`.
66        mode: Option<TransportMode>,
67    },
68    /// Server-published multicast group (`RTP/AVP;multicast`).
69    Multicast {
70        destination: Option<IpAddr>,
71        port: Option<u16>,
72        ttl: Option<u8>,
73        source: Option<IpAddr>,
74        mode: Option<TransportMode>,
75        /// SRTP (`RTP/SAVP;multicast`) is required for this group.
76        secure: bool,
77    },
78}
79impl TransportSpec {
80    pub fn parse(value: &str) -> Result<Self> {
81        let mut alternatives = Self::parse_all(value)?;
82        if alternatives.len() != 1 {
83            return Err(Error::Rtsp(
84                "expected exactly one Transport alternative".into(),
85            ));
86        }
87        Ok(alternatives.remove(0))
88    }
89
90    pub fn parse_all(value: &str) -> Result<Vec<Self>> {
91        let alternatives = value
92            .split(',')
93            .map(str::trim)
94            .map(Self::parse_one)
95            .collect::<Result<Vec<_>>>()?;
96        if alternatives.is_empty() {
97            return Err(Error::Rtsp("empty Transport".into()));
98        }
99        Ok(alternatives)
100    }
101
102    fn parse_one(value: &str) -> Result<Self> {
103        let mut parts = value.split(';').map(str::trim);
104        let profile = parts
105            .next()
106            .filter(|value| !value.is_empty())
107            .ok_or_else(|| Error::Rtsp("empty Transport".into()))?;
108        let mut parameters = std::collections::BTreeMap::new();
109        let mut unicast = false;
110        let mut multicast = false;
111        let mut rtcp_mux = false;
112        let mut destination: Option<IpAddr> = None;
113        let mut source: Option<IpAddr> = None;
114        let mut mode: Option<TransportMode> = None;
115        for part in parts {
116            if part.eq_ignore_ascii_case("rtcp-mux") {
117                if rtcp_mux {
118                    return Err(Error::Rtsp("duplicate rtcp-mux Transport parameter".into()));
119                }
120                rtcp_mux = true;
121                continue;
122            }
123            if part.eq_ignore_ascii_case("unicast") {
124                if unicast {
125                    return Err(Error::Rtsp("duplicate unicast Transport parameter".into()));
126                }
127                unicast = true;
128                continue;
129            }
130            if part.eq_ignore_ascii_case("multicast") {
131                if multicast {
132                    return Err(Error::Rtsp(
133                        "duplicate multicast Transport parameter".into(),
134                    ));
135                }
136                multicast = true;
137                continue;
138            }
139            let (name, value) = part
140                .split_once('=')
141                .ok_or_else(|| Error::Rtsp("malformed Transport parameter".into()))?;
142            let name = name.trim().to_ascii_lowercase();
143            let value = value.trim();
144            if name.is_empty() || value.is_empty() || parameters.insert(name, value).is_some() {
145                return Err(Error::Rtsp(
146                    "duplicate or malformed Transport parameter".into(),
147                ));
148            }
149        }
150        if multicast {
151            let secure = profile.eq_ignore_ascii_case("RTP/SAVP");
152            if !secure && !profile.eq_ignore_ascii_case("RTP/AVP") {
153                return Err(Error::Rtsp(
154                    "unsupported multicast Transport profile".into(),
155                ));
156            }
157            if unicast {
158                return Err(Error::Rtsp(
159                    "Transport cannot be both unicast and multicast".into(),
160                ));
161            }
162            let destination = parameters
163                .get("destination")
164                .map(|value| {
165                    value
166                        .parse::<IpAddr>()
167                        .map_err(|_| Error::Rtsp("invalid multicast destination".into()))
168                })
169                .transpose()?;
170            let port = parameters
171                .get("port")
172                .map(|value| {
173                    value
174                        .parse::<u16>()
175                        .map_err(|_| Error::Rtsp("invalid multicast port".into()))
176                })
177                .transpose()?;
178            let ttl = parameters
179                .get("ttl")
180                .map(|value| {
181                    value
182                        .parse::<u8>()
183                        .map_err(|_| Error::Rtsp("invalid multicast TTL".into()))
184                })
185                .transpose()?;
186            let source = parameters
187                .get("source")
188                .map(|value| {
189                    value
190                        .parse::<IpAddr>()
191                        .map_err(|_| Error::Rtsp("invalid multicast source".into()))
192                })
193                .transpose()?;
194            let mode = parameters
195                .get("mode")
196                .map(|value| TransportMode::parse(value))
197                .transpose()?;
198            return Ok(Self::Multicast {
199                destination,
200                port,
201                ttl,
202                source,
203                mode,
204                secure,
205            });
206        }
207        // RFC 2326 lists unicast/multicast as parameters; several real
208        // clients omit the token for unicast, so treat "neither" as unicast
209        // instead of rejecting the SETUP.
210        let _ = unicast;
211        if let Some(value) = parameters.get("destination") {
212            destination = Some(
213                value
214                    .parse()
215                    .map_err(|_| Error::Rtsp("invalid Transport destination".into()))?,
216            );
217        }
218        if let Some(value) = parameters.get("source") {
219            source = Some(
220                value
221                    .parse()
222                    .map_err(|_| Error::Rtsp("invalid Transport source".into()))?,
223            );
224        }
225        if let Some(value) = parameters.get("mode") {
226            mode = Some(TransportMode::parse(value)?);
227        }
228
229        let secure = profile.eq_ignore_ascii_case("RTP/SAVP/TCP");
230        if profile.eq_ignore_ascii_case("RTP/AVP/TCP") || secure {
231            let channels = parameters
232                .get("interleaved")
233                .ok_or_else(|| Error::Rtsp("TCP Transport has no interleaved channels".into()))?;
234            let (rtp, rtcp) = port_or_pair(channels, rtcp_mux)?;
235            return Ok(Self::TcpInterleaved {
236                rtp_channel: u8::try_from(rtp)
237                    .map_err(|_| Error::Rtsp("RTP interleaved channel exceeds 255".into()))?,
238                rtcp_channel: u8::try_from(rtcp)
239                    .map_err(|_| Error::Rtsp("RTCP interleaved channel exceeds 255".into()))?,
240                rtcp_mux,
241                secure,
242                mode,
243            });
244        }
245        let secure = profile.eq_ignore_ascii_case("RTP/SAVP")
246            || profile.eq_ignore_ascii_case("RTP/SAVP/UDP");
247        if !secure
248            && !profile.eq_ignore_ascii_case("RTP/AVP")
249            && !profile.eq_ignore_ascii_case("RTP/AVP/UDP")
250        {
251            return Err(Error::Rtsp("unsupported RTP transport profile".into()));
252        }
253        let client = parameters
254            .get("client_port")
255            .ok_or_else(|| Error::Rtsp("UDP Transport has no client_port".into()))?;
256        let (client_rtp, client_rtcp) = port_or_pair(client, rtcp_mux)?;
257        if client_rtp == 0 {
258            return Err(Error::Rtsp("UDP client_port must be non-zero".into()));
259        }
260        let (server_rtp, server_rtcp) = parameters
261            .get("server_port")
262            .map(|value| port_or_pair(value, rtcp_mux))
263            .transpose()?
264            .map_or((None, None), |(a, b)| (Some(a), Some(b)));
265        Ok(Self::Udp {
266            client_rtp,
267            client_rtcp,
268            server_rtp,
269            server_rtcp,
270            rtcp_mux,
271            secure,
272            destination,
273            source,
274            mode,
275        })
276    }
277
278    pub fn render(&self) -> String {
279        match self {
280            Self::Udp {
281                client_rtp,
282                client_rtcp,
283                server_rtp,
284                server_rtcp,
285                rtcp_mux,
286                secure,
287                destination,
288                source,
289                mode,
290            } => {
291                let profile = if *secure { "RTP/SAVP" } else { "RTP/AVP" };
292                let mut s = if *rtcp_mux {
293                    format!("{profile};unicast;client_port={client_rtp};rtcp-mux")
294                } else {
295                    format!("{profile};unicast;client_port={client_rtp}-{client_rtcp}")
296                };
297                if let (Some(a), Some(b)) = (server_rtp, server_rtcp) {
298                    if *rtcp_mux {
299                        s.push_str(&format!(";server_port={a}"))
300                    } else {
301                        s.push_str(&format!(";server_port={a}-{b}"))
302                    }
303                }
304                if let Some(destination) = destination {
305                    s.push_str(&format!(";destination={destination}"));
306                }
307                if let Some(source) = source {
308                    s.push_str(&format!(";source={source}"));
309                }
310                if let Some(mode) = mode {
311                    s.push_str(&format!(";mode={}", mode.as_str()));
312                }
313                s
314            }
315            Self::TcpInterleaved {
316                rtp_channel,
317                rtcp_channel,
318                rtcp_mux,
319                secure,
320                mode,
321            } => {
322                let profile = if *secure {
323                    "RTP/SAVP/TCP"
324                } else {
325                    "RTP/AVP/TCP"
326                };
327                let mut rendered = if *rtcp_mux {
328                    format!("{profile};unicast;interleaved={rtp_channel};rtcp-mux")
329                } else {
330                    format!("{profile};unicast;interleaved={rtp_channel}-{rtcp_channel}")
331                };
332                if let Some(mode) = mode {
333                    rendered.push_str(&format!(";mode={}", mode.as_str()));
334                }
335                rendered
336            }
337            Self::Multicast {
338                destination,
339                port,
340                ttl,
341                source,
342                mode,
343                secure,
344            } => {
345                let mut rendered = if *secure {
346                    String::from("RTP/SAVP;multicast")
347                } else {
348                    String::from("RTP/AVP;multicast")
349                };
350                if let Some(destination) = destination {
351                    rendered.push_str(&format!(";destination={destination}"));
352                }
353                if let Some(port) = port {
354                    rendered.push_str(&format!(";port={port}"));
355                }
356                if let Some(ttl) = ttl {
357                    rendered.push_str(&format!(";ttl={ttl}"));
358                }
359                if let Some(source) = source {
360                    rendered.push_str(&format!(";source={source}"));
361                }
362                if let Some(mode) = mode {
363                    rendered.push_str(&format!(";mode={}", mode.as_str()));
364                }
365                rendered
366            }
367        }
368    }
369}
370fn port_or_pair(s: &str, allow_single: bool) -> Result<(u16, u16)> {
371    if let Some((a, b)) = s.split_once('-') {
372        let a = u16::from_str(a.trim()).map_err(|_| Error::Rtsp("invalid RTP port".into()))?;
373        let b = u16::from_str(b.trim()).map_err(|_| Error::Rtsp("invalid RTCP port".into()))?;
374        if b != a.checked_add(1).unwrap_or_default() {
375            return Err(Error::Rtsp(
376                "RTP/RTCP values must be an adjacent pair".into(),
377            ));
378        }
379        return Ok((a, b));
380    }
381    if allow_single {
382        let value = u16::from_str(s.trim()).map_err(|_| Error::Rtsp("invalid RTP port".into()))?;
383        return Ok((value, value));
384    }
385    Err(Error::Rtsp("port pair must use '-'".into()))
386}
387#[derive(Clone, Debug)]
388pub struct InterleavedFrame {
389    pub channel: u8,
390    pub payload: Bytes,
391}
392impl InterleavedFrame {
393    pub fn try_encode(&self) -> Result<Bytes> {
394        let length =
395            u16::try_from(self.payload.len()).map_err(|_| Error::Limit("interleaved RTP frame"))?;
396        let mut out = BytesMut::with_capacity(4 + self.payload.len());
397        out.extend_from_slice(&[b'$', self.channel]);
398        out.extend_from_slice(&length.to_be_bytes());
399        out.extend_from_slice(&self.payload);
400        Ok(out.freeze())
401    }
402
403    /// Encode without panicking; prefer [`Self::try_encode`] directly.
404    pub fn encode(&self) -> Result<Bytes> {
405        self.try_encode()
406    }
407    pub fn parse(buf: &mut BytesMut, max: usize) -> Result<Option<Self>> {
408        if buf.first() != Some(&b'$') {
409            return Ok(None);
410        }
411        if buf.len() < 4 {
412            return Ok(None);
413        }
414        let len = u16::from_be_bytes([buf[2], buf[3]]) as usize;
415        if len > max {
416            return Err(Error::Limit("interleaved RTP frame"));
417        }
418        if buf.len() < len + 4 {
419            return Ok(None);
420        }
421        let channel = buf[1];
422        buf.advance(4);
423        let payload = buf.split_to(len).freeze();
424        Ok(Some(Self { channel, payload }))
425    }
426}
427#[derive(Clone, Debug)]
428pub struct UdpPair {
429    pub rtp: Arc<UdpSocket>,
430    pub rtcp: Arc<UdpSocket>,
431}
432const UDP_RECEIVE_BUFFER_SIZE: usize = 4 * 1024 * 1024;
433/// Send-side buffer for RTP packets. IDR bursts otherwise overflow the
434/// kernel default (usually ~200 KiB) and show up as receiver loss.
435const UDP_SEND_BUFFER_SIZE: usize = 1024 * 1024;
436
437fn bind_udp(addr: SocketAddr, recv_buffer: usize) -> Result<UdpSocket> {
438    let domain = match addr {
439        SocketAddr::V4(_) => Domain::IPV4,
440        SocketAddr::V6(_) => Domain::IPV6,
441    };
442    let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP)).map_err(Error::Io)?;
443    socket.set_nonblocking(true).map_err(Error::Io)?;
444    socket
445        .set_recv_buffer_size(recv_buffer)
446        .map_err(Error::Io)?;
447    socket
448        .set_send_buffer_size(UDP_SEND_BUFFER_SIZE)
449        .map_err(Error::Io)?;
450    socket.bind(&addr.into()).map_err(Error::Io)?;
451    UdpSocket::from_std(socket.into()).map_err(Error::Io)
452}
453
454impl UdpPair {
455    pub async fn bind(ip: IpAddr, range: Option<RangeInclusive<u16>>) -> Result<Self> {
456        Self::bind_with_recv_buffer(ip, range, UDP_RECEIVE_BUFFER_SIZE).await
457    }
458
459    /// Like [`Self::bind`] with an explicit socket receive-buffer size.
460    /// Memory-constrained clients can trade burst tolerance for a smaller
461    /// footprint (the default is 4MiB per socket).
462    pub async fn bind_with_recv_buffer(
463        ip: IpAddr,
464        range: Option<RangeInclusive<u16>>,
465        recv_buffer: usize,
466    ) -> Result<Self> {
467        if let Some(range) = range {
468            for rtp_port in range.clone() {
469                let Some(rtcp_port) = rtp_port.checked_add(1) else {
470                    continue;
471                };
472                if !range.contains(&rtcp_port) {
473                    continue;
474                }
475                if let Ok(rtp) = bind_udp(SocketAddr::new(ip, rtp_port), recv_buffer)
476                    && let Ok(rtcp) = bind_udp(SocketAddr::new(ip, rtcp_port), recv_buffer)
477                {
478                    return Ok(Self {
479                        rtp: Arc::new(rtp),
480                        rtcp: Arc::new(rtcp),
481                    });
482                }
483            }
484            return Err(Error::Io(std::io::Error::new(
485                std::io::ErrorKind::AddrNotAvailable,
486                "no free RTP/RTCP port pair",
487            )));
488        }
489        for _ in 0..64 {
490            let rtp = bind_udp(SocketAddr::new(ip, 0), recv_buffer)?;
491            let port = rtp.local_addr()?.port();
492            let Some(rtcp_port) = port.checked_add(1) else {
493                continue;
494            };
495            if let Ok(rtcp) = bind_udp(SocketAddr::new(ip, rtcp_port), recv_buffer) {
496                return Ok(Self {
497                    rtp: Arc::new(rtp),
498                    rtcp: Arc::new(rtcp),
499                });
500            }
501        }
502        Err(Error::Io(std::io::Error::new(
503            std::io::ErrorKind::AddrNotAvailable,
504            "unable to allocate adjacent RTP/RTCP ports",
505        )))
506    }
507    /// Bind a single UDP socket shared by RTP and RTCP (`rtcp-mux`).
508    pub async fn bind_mux(
509        ip: IpAddr,
510        range: Option<RangeInclusive<u16>>,
511        recv_buffer: usize,
512    ) -> Result<Self> {
513        let socket = if let Some(range) = range {
514            range
515                .into_iter()
516                .find_map(|port| bind_udp(SocketAddr::new(ip, port), recv_buffer).ok())
517                .ok_or_else(|| {
518                    Error::Io(std::io::Error::new(
519                        std::io::ErrorKind::AddrNotAvailable,
520                        "no free RTP port",
521                    ))
522                })?
523        } else {
524            bind_udp(SocketAddr::new(ip, 0), recv_buffer)?
525        };
526        let socket = Arc::new(socket);
527        Ok(Self {
528            rtp: socket.clone(),
529            rtcp: socket,
530        })
531    }
532    /// Set the IPv4 multicast TTL on both sockets (sender side).
533    #[cfg(feature = "multicast")]
534    pub fn set_multicast_ttl(&self, ttl: u8) -> Result<()> {
535        let ttl = u32::from(ttl);
536        socket2::SockRef::from(&*self.rtp)
537            .set_multicast_ttl_v4(ttl)
538            .map_err(Error::Io)?;
539        socket2::SockRef::from(&*self.rtcp)
540            .set_multicast_ttl_v4(ttl)
541            .map_err(Error::Io)?;
542        Ok(())
543    }
544    /// Build a pair from already-bound sockets (multicast joins).
545    pub fn from_sockets(rtp: UdpSocket, rtcp: UdpSocket) -> Self {
546        Self {
547            rtp: Arc::new(rtp),
548            rtcp: Arc::new(rtcp),
549        }
550    }
551    pub fn rtp_port(&self) -> Result<u16> {
552        Ok(self.rtp.local_addr()?.port())
553    }
554    pub fn rtcp_port(&self) -> Result<u16> {
555        Ok(self.rtcp.local_addr()?.port())
556    }
557}
558
559#[derive(Clone, Debug)]
560pub enum PeerTransport {
561    Udp(SocketAddr),
562    Interleaved { rtp_channel: u8, rtcp_channel: u8 },
563}
564
565/// Upstream transport selection for proxy and client connections.
566#[derive(Clone, Copy, Debug, Eq, PartialEq)]
567pub enum UpstreamTransport {
568    /// Attempt UDP first, then reconnect and use TCP interleaving if SETUP fails.
569    Auto,
570    Udp,
571    TcpInterleaved,
572}
573
574#[cfg(test)]
575mod tests;