Skip to main content

rtci_interceptor/
packet.rs

1use shared::TransportMessage;
2use std::any::Any;
3use std::sync::Arc;
4
5/// RTP/RTCP Packet
6///
7/// An enum representing either an RTP or RTCP packet that can be processed
8/// by interceptors in the chain.
9#[derive(Debug, Clone, PartialEq)]
10#[non_exhaustive]
11pub enum Packet {
12    /// RTP (Real-time Transport Protocol) packet containing media data
13    Rtp(rtp::Packet),
14    /// RTCP (RTP Control Protocol) packets for feedback and statistics.
15    ///
16    /// # An empty vector is reserved
17    ///
18    /// `Packet::Rtcp(vec![])` means **attribute carrier** and nothing else: a packet that exists
19    /// only to carry [`Attribute`]s when no real packet is going the same way. `rtci`'s handler
20    /// reads the attributes off it and then drops it, so it never reaches the wire or the
21    /// application.
22    ///
23    /// An interceptor must therefore never emit an empty compound packet meaning anything else —
24    /// it would be discarded with no error and no trace. Generators that build from a
25    /// variable-length list return early when that list is empty rather than emitting nothing-shaped
26    /// output; `rtci-interceptor/tests/empty_rtcp_is_reserved.rs` holds them to it.
27    Rtcp(Vec<Box<dyn rtcp::Packet>>),
28}
29
30/// A fact about a packet, attached by one interceptor and readable by the rest.
31///
32/// # Why it rides with the packet
33///
34/// Because it has to survive the journey. An interceptor that queues a packet and emits it later
35/// puts it back on the belt *behind* itself, where every interceptor ahead sees it again — so what
36/// was learned about that packet has to travel with it or be worked out twice. A side channel
37/// cannot manage that: it has no way to say *which* packet it refers to once the packet has been
38/// held, reordered or duplicated.
39///
40/// With `Ein`/`Eout` left as `()`, this is the only way information crosses interceptors.
41///
42/// # When there is no packet to ride
43///
44/// A connection-level fact — a bandwidth estimate, a keyframe request from the application — often
45/// needs to travel when no media is going that way. The carrier for those is an RTCP packet with an
46/// empty payload, [`Packet::Rtcp(vec![])`](Packet::Rtcp), which is inert to every interceptor that
47/// does not look for attributes and is dropped at the crate boundary once its attributes are read.
48/// That makes an empty compound RTCP packet **reserved**: see [`Packet::Rtcp`].
49///
50/// # Cost
51///
52/// [`AttributedPacket`] holds a `Vec`, which does not allocate while empty — and most packets carry
53/// nothing. Lookup is a linear scan of a handful of words, cheaper than hashing.
54#[derive(Clone)]
55#[non_exhaustive]
56pub enum Attribute {
57    /// Rebuilt by FEC rather than received: these bytes never arrived on the wire.
58    ///
59    /// Not needed by the NACK generator, despite the obvious guess. The FEC decoder is wire-ward of
60    /// it, so a rebuilt packet reaches the generator on the read walk like any other arrival and
61    /// fills the gap in its receive log — there is nothing left to ask for, by ordering rather than
62    /// by inspection. `tests/flexfec_receive.rs` pins that.
63    ///
64    /// It matters to anything that must distinguish *arrived* from *present*: an arrival recorder
65    /// telling the remote a packet turned up, when in fact it was lost and rebuilt here, overstates
66    /// what the path delivered.
67    RecoveredByFec,
68
69    /// A retransmission answering a NACK, not a first transmission.
70    ///
71    /// Still new bytes on the wire, which is why a send history has to count it — counting it as
72    /// an original tells a bandwidth estimator the path is carrying less than it is.
73    Retransmission,
74
75    /// An inbound packet that arrived as an RTX retransmission (RFC 4588) and was rewritten
76    /// into the original before the chain: `ssrc` and `sequence_number` are the RTX
77    /// stream's, the ones it had on the wire.
78    ///
79    /// The chain sees the original packet, so a NACK generator stops asking for it and a
80    /// jitter buffer slots it in. What the *network* delivered is another matter: reception
81    /// statistics count this arrival on the RTX stream, not on the stream it repairs, which
82    /// keeps a receiver report's loss figures those of the path (RFC 4588 section 3).
83    Retransmitted {
84        /// The SSRC of the retransmission stream the packet arrived on.
85        ssrc: u32,
86        /// Its sequence number in that stream.
87        sequence_number: u16,
88    },
89
90    /// Inbound RTCP an interceptor has decided the application should see.
91    ///
92    /// [`NoopInterceptor`](crate::NoopInterceptor) ends the inbound RTCP path unless the packet
93    /// carries this, which makes forwarding a per-packet judgement by whichever interceptor is
94    /// qualified to make it, rather than a chain-wide setting. An SFU relaying keyframe requests
95    /// marks those and leaves the receiver reports its own chain is acting on alone; a chain-wide
96    /// switch could only offer all of it or none.
97    ///
98    /// Usually attached by an interceptor the application supplies, since the application is what
99    /// knows which packets it can act on. Attaching it is the only way past the terminus:
100    /// re-emitting a copy does not work, because what an interceptor emits from `poll_read` rejoins
101    /// the belt *behind* itself, where the terminus is still ahead of it.
102    DeliverToApplication,
103
104    /// The congestion controller's estimate, in bits per second.
105    ///
106    /// Rides outbound so the pacer reads it on the way past. A bitrate is connection state rather
107    /// than a property of the packet carrying it — it travels this way because with no event
108    /// channel there is nowhere else for it to go.
109    ///
110    /// **Zero means pause**: produce nothing until the next target. The pacer hands zero
111    /// application-ward while its queue would take half its queue time bound or more to drain
112    /// (`PacerPause` carries the controller's own target for the interceptors that need it);
113    /// an encoder skips the frames captured meanwhile and resumes with the next target, without
114    /// a key frame (nothing it encoded was lost). See "Pausing the source" on `PacerInterceptor`.
115    ///
116    /// What the application writes has to keep to this target. One that does not hear it
117    /// otherwise hears it from the pacer: media that waited the pacer's queue time bound is
118    /// discarded whole frames at a time, announced as [`PacerDiscard`](crate::PacerDiscard)
119    /// on the read leg (`RTCPeerConnectionEvent::OnPacerDiscard` in the peer connection) with a
120    /// key-frame request for the stream: **your source is above the target**.
121    TargetBitrateChanged {
122        /// The new target, in bits per second.
123        bits_per_second: f64,
124    },
125
126    /// Anything an application defines, so this enum is never a bottleneck on it.
127    ///
128    /// `Arc` rather than `Box` so an attributed packet stays cheap to clone — the NACK responder
129    /// clones into its send buffer and the FEC encoder into its block, and neither should deep-copy
130    /// an application's payload. Reached by type: [`AttributedPacket::custom`].
131    Custom(Arc<dyn Any + Send + Sync>),
132}
133
134impl std::fmt::Debug for Attribute {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        match self {
137            Self::RecoveredByFec => f.write_str("RecoveredByFec"),
138            Self::Retransmission => f.write_str("Retransmission"),
139            Self::Retransmitted {
140                ssrc,
141                sequence_number,
142            } => f
143                .debug_struct("Retransmitted")
144                .field("ssrc", ssrc)
145                .field("sequence_number", sequence_number)
146                .finish(),
147            Self::DeliverToApplication => f.write_str("DeliverToApplication"),
148            Self::TargetBitrateChanged { bits_per_second } => f
149                .debug_struct("TargetBitrateChanged")
150                .field("bits_per_second", bits_per_second)
151                .finish(),
152            // The payload is `dyn Any`, which is not `Debug`.
153            Self::Custom(_) => f.write_str("Custom(..)"),
154        }
155    }
156}
157
158/// A packet together with what the interceptors have learned about it.
159#[derive(Clone, Debug)]
160pub struct AttributedPacket {
161    /// What the interceptors have attached on the way, in the order they attached it.
162    pub attributes: Vec<Attribute>,
163    /// The packet itself.
164    pub packet: Packet,
165}
166
167impl AttributedPacket {
168    /// A packet with nothing attached.
169    pub fn new(packet: Packet) -> Self {
170        Self {
171            attributes: Vec::new(),
172            packet,
173        }
174    }
175    /// Attach `attribute`, taking ownership — for building a packet in one expression.
176    pub fn with(mut self, attribute: Attribute) -> Self {
177        self.attributes.push(attribute);
178        self
179    }
180    /// Attach `attribute`.
181    ///
182    /// Attaching the same one twice is allowed and means nothing extra; [`has`](Self::has) answers
183    /// the only question anyone asks of it.
184    pub fn add(&mut self, attribute: Attribute) -> &mut Self {
185        self.attributes.push(attribute);
186        self
187    }
188
189    /// Whether this packet carries `attribute`.
190    ///
191    /// Compares by variant, not by value, so `has(&Attribute::TargetBitrateChanged { .. })` finds
192    /// one whatever the rate is, and [`Attribute::Custom`] never satisfies a query for a built-in.
193    pub fn has(&self, attribute: &Attribute) -> bool {
194        let wanted = std::mem::discriminant(attribute);
195        self.attributes
196            .iter()
197            .any(|held| std::mem::discriminant(held) == wanted)
198    }
199
200    /// The first attribute matching `attribute`'s variant, for reading a value out of it.
201    pub fn get(&self, attribute: &Attribute) -> Option<&Attribute> {
202        let wanted = std::mem::discriminant(attribute);
203        self.attributes
204            .iter()
205            .find(|held| std::mem::discriminant(*held) == wanted)
206    }
207
208    /// The first [`Attribute::Custom`] payload of type `T`, if this packet carries one.
209    pub fn custom<T: Any + Send + Sync>(&self) -> Option<&T> {
210        self.attributes
211            .iter()
212            .find_map(|attribute| match attribute {
213                Attribute::Custom(value) => value.downcast_ref::<T>(),
214                _ => None,
215            })
216    }
217}
218
219impl From<Packet> for AttributedPacket {
220    fn from(packet: Packet) -> Self {
221        Self::new(packet)
222    }
223}
224
225/// Tagged packet with transport metadata.
226///
227/// A [`TransportMessage`] wrapping a [`Packet`], which includes transport-level
228/// context such as source/destination addresses and protocol information.
229/// This is the primary message type passed through interceptor chains.
230pub type TaggedPacket = TransportMessage<AttributedPacket>;