Skip to main content

rtci_rtp/codec/opaque/
mod.rs

1//! A format-agnostic payload: arbitrary bytes split into RTP payloads without being parsed,
2//! for frames whose content the RTP layer cannot read, such as SFrame ciphertexts (RFC 9605
3//! sections 4.2 and 6.2: a whole-frame ciphertext spans packets; the codec payloaders all
4//! parse what they are given, an encrypted frame cannot be).
5//!
6//! Each payload starts with one byte of flags, so that the start and the end of a unit are
7//! explicit in the payload rather than only in the RTP marker bit (several units, one per
8//! layer, can share an RTP timestamp, and only the last carries the marker):
9//!
10//! ```text
11//!  0 1 2 3 4 5 6 7
12//! +-+-+-+-+-+-+-+-+
13//! |S|E|  reserved |
14//! +-+-+-+-+-+-+-+-+
15//! ```
16//!
17//! `S` is set on the first payload of a unit, `E` on its last; reserved bits are sent as zero
18//! and ignored. This is the engine's own framing, not the SFrame RTP payload format of
19//! draft-ietf-avtcore-rtp-sframe, whose layout and negotiation are still to be adopted.
20
21#[cfg(test)]
22mod opaque_test;
23
24use crate::packetizer::{Depacketizer, Payloader};
25use bytes::{BufMut, Bytes, BytesMut};
26use shared::error::{Error, Result};
27
28/// Size of the payload header.
29pub const OPAQUE_HEADER_SIZE: usize = 1;
30/// The start-of-unit flag.
31pub const OPAQUE_START: u8 = 0x80;
32/// The end-of-unit flag.
33pub const OPAQUE_END: u8 = 0x40;
34
35/// Splits a unit of arbitrary bytes into payloads of at most `mtu`, each behind the flags
36/// byte. An empty unit is one payload with both flags.
37#[derive(Default, Debug, Copy, Clone)]
38pub struct OpaquePayloader;
39
40impl Payloader for OpaquePayloader {
41    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
42        let chunk = mtu
43            .checked_sub(OPAQUE_HEADER_SIZE)
44            .filter(|&chunk| chunk > 0)
45            .ok_or(Error::ErrShortBuffer)?;
46        let mut out = Vec::with_capacity(payload.len() / chunk + 1);
47        let mut rest = payload.as_ref();
48        let mut first = true;
49        loop {
50            let take = rest.len().min(chunk);
51            let last = take == rest.len();
52            let mut flags = 0;
53            if first {
54                flags |= OPAQUE_START;
55            }
56            if last {
57                flags |= OPAQUE_END;
58            }
59            let mut buf = BytesMut::with_capacity(OPAQUE_HEADER_SIZE + take);
60            buf.put_u8(flags);
61            buf.put_slice(&rest[..take]);
62            out.push(buf.freeze());
63            rest = &rest[take..];
64            first = false;
65            if last {
66                return Ok(out);
67            }
68        }
69    }
70
71    fn clone_to(&self) -> Box<dyn Payloader> {
72        Box::new(*self)
73    }
74}
75
76/// Reassembles the units [`OpaquePayloader`] split. A unit is returned when its `E` payload
77/// arrives; a payload that continues a unit whose start was not seen (a lost packet) drops
78/// the unit whole: the bytes of a ciphertext are useless without all of them.
79#[derive(Default, Debug, Clone)]
80pub struct OpaqueDepacketizer {
81    unit: Option<BytesMut>,
82}
83
84impl Depacketizer for OpaqueDepacketizer {
85    /// Returns the reassembled unit on its last payload, and an empty `Bytes` before then (or
86    /// for a payload of a unit whose start was lost).
87    fn depacketize(&mut self, payload: &Bytes) -> Result<Bytes> {
88        let Some((&flags, data)) = payload.split_first() else {
89            return Err(Error::ErrShortPacket);
90        };
91        if flags & OPAQUE_START != 0 {
92            self.unit = Some(BytesMut::new());
93        }
94        let Some(unit) = self.unit.as_mut() else {
95            return Ok(Bytes::new());
96        };
97        unit.put_slice(data);
98        if flags & OPAQUE_END != 0 {
99            return Ok(self.unit.take().map(BytesMut::freeze).unwrap_or_default());
100        }
101        Ok(Bytes::new())
102    }
103
104    fn is_partition_head(&self, payload: &Bytes) -> bool {
105        payload
106            .first()
107            .is_some_and(|flags| flags & OPAQUE_START != 0)
108    }
109
110    fn is_partition_tail(&self, _marker: bool, payload: &Bytes) -> bool {
111        payload.first().is_some_and(|flags| flags & OPAQUE_END != 0)
112    }
113}