Skip to main content

rtci_interceptor/
noop.rs

1//! Where the inbound RTCP path ends.
2
3use crate::Interceptor;
4use crate::{Attribute, Packet, RtpSession, StreamInfo, TaggedPacket};
5use sansio::Protocol;
6use shared::error::Error;
7use std::collections::VecDeque;
8use std::time::Instant;
9
10/// Decides what becomes of inbound RTCP once the interceptors have had it, and passes everything
11/// else through.
12///
13/// # Why this exists
14///
15/// Inbound RTCP is **for the interceptors**: a receiver report feeds the sender-side statistics, a
16/// NACK is answered by the responder, transport-wide feedback drives the bandwidth estimate.
17/// Handing it onward by default would give an application a stream of control traffic it did not
18/// ask for and cannot act on, mixed in with its media — so by default it stops here.
19///
20/// An application that *does* read RTCP puts an interceptor of its own in the chain and has it
21/// attach [`Attribute::DeliverToApplication`] to the packets it wants. That makes delivery a
22/// per-packet judgement, made by the one component that knows which packets matter: an SFU
23/// forwarding PLIs wants those and not the receiver reports its own chain is already acting on. A
24/// chain-wide switch could only offer "all of it or none of it", and every application that wanted
25/// one kind of packet had to take the lot and filter afterwards.
26///
27/// # Where this belongs in the chain
28///
29/// **Last**, so every interceptor that reads RTCP has already seen it by the time it is dropped.
30/// Anywhere else it would starve the ones beyond it — a NACK responder placed after this would
31/// never see a NACK. [`Registry::build`](crate::Registry::build) appends it for that reason,
32/// rather than leaving the position to each caller.
33///
34/// # Why marking is the mechanism, and not re-emitting a copy
35///
36/// Under the nested chain an application could add an interceptor that kept a copy of each RTCP
37/// packet and returned it from its own `poll_read` ahead of delegating inward. That worked because
38/// a local `poll_read` queue was *terminal*: the copy bypassed everything below and escaped this
39/// one.
40///
41/// On the belt it does not. What an interceptor emits from `poll_read` rejoins the belt **behind
42/// itself**, so it arrives here like any other packet and is dropped like any other packet — the
43/// original *and* the copy, twice over. Since this is always the last interceptor, no position
44/// exists from which to forward past it. Marking the packet works precisely because it does not try
45/// to get around this one: the packet travels the whole chain as normal, and this reads the mark
46/// when it arrives.
47///
48/// # Naming
49///
50/// It was a no-op in the nested chain, where its job was to terminate the recursion and hand
51/// packets back. The belt needs no terminator, so all that is left is the one decision it always
52/// quietly made.
53#[derive(Default)]
54pub struct NoopInterceptor {
55    read_queue: VecDeque<TaggedPacket>,
56    write_queue: VecDeque<TaggedPacket>,
57}
58
59impl NoopInterceptor {
60    /// A terminus
61    pub fn new() -> Self {
62        Self::default()
63    }
64}
65
66impl Protocol<TaggedPacket, TaggedPacket, ()> for NoopInterceptor {
67    type Rout = TaggedPacket;
68    type Wout = TaggedPacket;
69    type Eout = ();
70    type Error = Error;
71    type Time = Instant;
72
73    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
74        // RTP is media the application asked for; it always passes.
75        if matches!(msg.message.packet, Packet::Rtp(_)) {
76            self.read_queue.push_back(msg);
77            return Ok(());
78        }
79
80        // Inbound RTCP is for the interceptors. Two ways past this point:
81        //
82        // 1. an interceptor judged this particular packet worth forwarding, by attaching
83        //    `Attribute::DeliverToApplication` — the per-packet judgement, made by whichever
84        //    interceptor is qualified to make it;
85        // 2. it carries attributes an interceptor attached for something beyond the chain. The
86        //    *payload* still stops here — nothing asked for this packet, and handing it over
87        //    because an interceptor annotated it would be a surprise — but the packet carries on
88        //    as an empty-RTCP carrier so the attributes reach the crate boundary.
89        //
90        // Anything else ends here. The tag naming the RTP session a packet travels in
91        // ([`RtpSession`], put on by every per-session wrapper) is routing, not something for
92        // beyond the chain: a report that carries only that ends here too.
93        if msg.message.has(&Attribute::DeliverToApplication) {
94            self.read_queue.push_back(msg);
95        } else if msg
96            .message
97            .attributes
98            .iter()
99            .any(|attribute| !is_session_tag(attribute))
100        {
101            msg.message.packet = Packet::Rtcp(Vec::new());
102            self.read_queue.push_back(msg);
103        }
104        Ok(())
105    }
106
107    fn poll_read(&mut self) -> Option<Self::Rout> {
108        self.read_queue.pop_front()
109    }
110
111    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
112        self.write_queue.push_back(msg);
113        Ok(())
114    }
115
116    fn poll_write(&mut self) -> Option<Self::Wout> {
117        self.write_queue.pop_front()
118    }
119}
120
121/// Whether `attribute` is the [`RtpSession`] tag.
122fn is_session_tag(attribute: &Attribute) -> bool {
123    matches!(attribute, Attribute::Custom(value) if value.downcast_ref::<RtpSession>().is_some())
124}
125
126impl Interceptor for NoopInterceptor {
127    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
128    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
129    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
130    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::{AttributedPacket, Registry, Slot, StreamInfo};
137    use sansio::Protocol;
138    use shared::TransportContext;
139    use shared::error::Error;
140    use std::collections::VecDeque;
141    use std::time::Instant;
142
143    fn packet(message: Packet) -> TaggedPacket {
144        TaggedPacket {
145            now: Instant::now(),
146            transport: TransportContext::default(),
147            message: AttributedPacket::new(message),
148        }
149    }
150
151    #[test]
152    fn inbound_rtcp_does_not_reach_the_application() {
153        let mut chain = Registry::new().build();
154
155        chain.handle_read(packet(Packet::Rtcp(vec![]))).unwrap();
156        assert!(chain.poll_read().is_none());
157    }
158
159    #[test]
160    fn inbound_rtp_passes_through() {
161        let mut chain = Registry::new().build();
162
163        chain
164            .handle_read(packet(Packet::Rtp(rtp::Packet::default())))
165            .unwrap();
166        assert!(chain.poll_read().is_some());
167    }
168
169    /// Outbound RTCP is untouched: this ends the *inbound* path only.
170    #[test]
171    fn outbound_rtcp_is_not_affected() {
172        let mut chain = Registry::new().build();
173
174        chain.handle_write(packet(Packet::Rtcp(vec![]))).unwrap();
175        assert!(chain.poll_write().is_some());
176    }
177
178    /// An interceptor wire-ward of the terminus still sees inbound RTCP — that is the whole point of it
179    /// being application-most.
180    #[test]
181    fn stages_before_it_still_see_inbound_rtcp() {
182        #[derive(Default)]
183        struct Counter {
184            seen: std::sync::Arc<std::sync::atomic::AtomicUsize>,
185            read_queue: VecDeque<TaggedPacket>,
186            write_queue: VecDeque<TaggedPacket>,
187        }
188        impl Protocol<TaggedPacket, TaggedPacket, ()> for Counter {
189            type Rout = TaggedPacket;
190            type Wout = TaggedPacket;
191            type Eout = ();
192            type Error = Error;
193            type Time = Instant;
194
195            fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
196                if matches!(msg.message.packet, Packet::Rtcp(_)) {
197                    self.seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
198                }
199                self.read_queue.push_back(msg);
200                Ok(())
201            }
202
203            fn poll_read(&mut self) -> Option<Self::Rout> {
204                self.read_queue.pop_front()
205            }
206
207            fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
208                self.write_queue.push_back(msg);
209                Ok(())
210            }
211
212            fn poll_write(&mut self) -> Option<Self::Wout> {
213                self.write_queue.pop_front()
214            }
215
216            fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
217                Ok(())
218            }
219
220            fn poll_timeout(&mut self) -> Option<Self::Time> {
221                None
222            }
223        }
224        impl Interceptor for Counter {
225            fn bind_local_stream(&mut self, _info: &StreamInfo) {}
226            fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
227            fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
228            fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
229        }
230        let counter = Counter::default();
231        let seen = counter.seen.clone();
232        let mut chain = Registry::new().with(Slot::NackGenerator, counter).build();
233
234        chain.handle_read(packet(Packet::Rtcp(vec![]))).unwrap();
235
236        assert_eq!(1, seen.load(std::sync::atomic::Ordering::Relaxed));
237        assert!(chain.poll_read().is_none(), "but it stops at the terminus");
238    }
239}
240
241#[cfg(test)]
242mod carrier_tests {
243    use super::*;
244    use crate::{Attribute, AttributedPacket, Registry};
245    use sansio::Protocol;
246    use shared::TransportContext;
247    use std::time::Instant;
248
249    fn annotated(attribute: Option<Attribute>) -> TaggedPacket {
250        let mut message = AttributedPacket::new(Packet::Rtcp(vec![Box::new(
251            rtcp::receiver_report::ReceiverReport::default(),
252        )]));
253        if let Some(attribute) = attribute {
254            message.add(attribute);
255        }
256        TaggedPacket {
257            now: Instant::now(),
258            transport: TransportContext::default(),
259            message,
260        }
261    }
262
263    /// An annotated report is stripped, not dropped: the payload stops here — the application did
264    /// not ask for RTCP — but the attributes carry on to the crate boundary, which is the only way
265    /// a bandwidth estimate reaches the application.
266    #[test]
267    fn an_annotated_report_passes_on_as_an_empty_carrier() {
268        let mut chain = Registry::new().build();
269        chain
270            .handle_read(annotated(Some(Attribute::TargetBitrateChanged {
271                bits_per_second: 750_000.0,
272            })))
273            .unwrap();
274
275        let carrier = chain.poll_read().expect("the attributes must get through");
276        assert!(
277            matches!(&carrier.message.packet, Packet::Rtcp(packets) if packets.is_empty()),
278            "the payload must be stripped: the application did not ask for RTCP"
279        );
280        assert!(
281            carrier.message.has(&Attribute::TargetBitrateChanged {
282                bits_per_second: 0.0
283            }),
284            "but the attribute must survive"
285        );
286    }
287
288    /// A report nobody annotated is still dropped, exactly as before.
289    #[test]
290    fn an_unannotated_report_still_stops_here() {
291        let mut chain = Registry::new().build();
292        chain.handle_read(annotated(None)).unwrap();
293        assert!(chain.poll_read().is_none());
294    }
295
296    /// The tag a per-RTP-session wrapper puts on what it hands on names the transport; it is
297    /// not an annotation for beyond the chain. A report carrying only that still stops here,
298    /// while one with a real annotation besides keeps its tag on the carrier.
299    #[test]
300    fn a_report_tagged_only_with_its_rtp_session_still_stops_here() {
301        let mut chain = Registry::new().build();
302        chain
303            .handle_read(annotated(Some(RtpSession(1).attribute())))
304            .unwrap();
305        assert!(chain.poll_read().is_none());
306
307        let mut annotated_too = annotated(Some(RtpSession(1).attribute()));
308        annotated_too.message.add(Attribute::TargetBitrateChanged {
309            bits_per_second: 1.0,
310        });
311        chain.handle_read(annotated_too).unwrap();
312        let carrier = chain.poll_read().expect("the annotation gets through");
313        assert_eq!(RtpSession::of(&carrier.message), Some(1));
314    }
315
316    /// `DeliverToApplication` is the per-packet judgement its documentation always described:
317    /// this one packet goes on **with its payload**, without turning RTCP on chain-wide.
318    #[test]
319    fn deliver_to_application_keeps_the_payload() {
320        let mut chain = Registry::new().build();
321        chain
322            .handle_read(annotated(Some(Attribute::DeliverToApplication)))
323            .unwrap();
324
325        let delivered = chain.poll_read().expect("forwarded");
326        assert!(
327            matches!(&delivered.message.packet, Packet::Rtcp(packets) if !packets.is_empty()),
328            "this packet was judged worth delivering, payload and all"
329        );
330    }
331}