Skip to main content

rtc_interceptor/
lib.rs

1//! RTC Interceptor - Sans-IO interceptor framework for RTP/RTCP processing.
2//!
3//! This crate provides a composable interceptor framework built on top of the
4//! [`sansio::Protocol`] trait. Interceptors can process, modify, or generate
5//! RTP/RTCP packets as they flow through the pipeline.
6//!
7//! # Available Interceptors
8//!
9//! ## RTCP Reports
10//!
11//! | Interceptor | Description |
12//! |-------------|-------------|
13//! | [`SenderReportInterceptor`] | Generates RTCP Sender Reports (SR) for local streams and filters hop-by-hop RTCP feedback |
14//! | [`ReceiverReportInterceptor`] | Generates RTCP Receiver Reports (RR) based on incoming RTP statistics |
15//!
16//! ## NACK (Negative Acknowledgement)
17//!
18//! | Interceptor | Description |
19//! |-------------|-------------|
20//! | [`NackGeneratorInterceptor`] | Detects missing RTP packets and generates NACK requests (RFC 4585) |
21//! | [`NackResponderInterceptor`] | Buffers sent packets and retransmits on NACK, with optional RTX support (RFC 4588) |
22//!
23//! ## TWCC (Transport Wide Congestion Control)
24//!
25//! | Interceptor | Description |
26//! |-------------|-------------|
27//! | [`TwccSenderInterceptor`] | Adds transport-wide sequence numbers to outgoing RTP packets |
28//! | [`TwccReceiverInterceptor`] | Tracks incoming packets and generates TransportLayerCC feedback |
29//!
30//! ## Utility
31//!
32//! | Interceptor | Description |
33//! |-------------|-------------|
34//! | [`NoopInterceptor`] | Pass-through terminal for interceptor chains |
35//!
36//! # Design
37//!
38//! Each interceptor wraps an inner `Interceptor` and can:
39//! - Process incoming/outgoing RTP/RTCP packets
40//! - Modify packet contents (headers, payloads)
41//! - Generate new packets (e.g., RTCP Sender/Receiver Reports)
42//! - Handle timeouts for periodic tasks (e.g., report generation)
43//! - Track stream statistics and state
44//!
45//! All interceptors work with [`TaggedPacket`] (RTP or RTCP packets with transport metadata).
46//! The innermost interceptor is typically [`NoopInterceptor`], which serves as the terminal.
47//!
48//! # No Direction Concept
49//!
50//! **Important:** Unlike PeerConnection's pipeline where `read` and `write` have
51//! opposite processing direction orders, interceptors have **no direction concept**.
52//!
53//! In PeerConnection's pipeline:
54//! ```text
55//! Read:  Network → HandlerA → HandlerB → HandlerC → Application
56//! Write: Application → HandlerC → HandlerB → HandlerA → Network
57//!        (reversed order)
58//! ```
59//!
60//! In Interceptor chains, all operations flow in the **same direction**:
61//! ```text
62//! handle_read:    Outer → Inner (A.handle_read calls B.handle_read calls C.handle_read)
63//! handle_write:   Outer → Inner (A.handle_write calls B.handle_write calls C.handle_write)
64//! handle_event:   Outer → Inner (A.handle_event calls B.handle_event calls C.handle_event)
65//! handle_timeout: Outer → Inner (A.handle_timeout calls B.handle_timeout calls C.handle_timeout)
66//!
67//! poll_read:    Outer → Inner (A.poll_read calls B.poll_read calls C.poll_read)
68//! poll_write:   Outer → Inner (A.poll_write calls B.poll_write calls C.poll_write)
69//! poll_event:   Outer → Inner (A.poll_event calls B.poll_event calls C.poll_event)
70//! poll_timeout: Outer → Inner (A.poll_timeout calls B.poll_timeout calls C.poll_timeout)
71//! ```
72//!
73//! This means interceptors are symmetric - they process `read`, `write`, and `event`
74//! in the same structural order. The distinction between "inbound" and "outbound"
75//! is semantic (based on message content), not structural (based on call order).
76//!
77//! # Quick Start
78//!
79//! ```
80//! use rtc_interceptor::{
81//!     Registry, SenderReportBuilder, ReceiverReportBuilder,
82//!     NackGeneratorBuilder, NackResponderBuilder,
83//!     TwccSenderBuilder, TwccReceiverBuilder,
84//! };
85//! use std::time::Duration;
86//!
87//! // Build a full-featured interceptor chain
88//! let chain = Registry::new()
89//!     // RTCP reports
90//!     .with(SenderReportBuilder::new()
91//!         .with_interval(Duration::from_secs(1))
92//!         .build())
93//!     .with(ReceiverReportBuilder::new()
94//!         .with_interval(Duration::from_secs(1))
95//!         .build())
96//!     // NACK for packet loss recovery
97//!     .with(NackGeneratorBuilder::new()
98//!         .with_size(512)
99//!         .with_interval(Duration::from_millis(100))
100//!         .build())
101//!     .with(NackResponderBuilder::new()
102//!         .with_size(1024)
103//!         .build())
104//!     // TWCC for congestion control
105//!     .with(TwccSenderBuilder::new().build())
106//!     .with(TwccReceiverBuilder::new()
107//!         .with_interval(Duration::from_millis(100))
108//!         .build())
109//!     .build();
110//! ```
111//!
112//! # Type-Erasing a Chain
113//!
114//! A chain's type spells out its whole composition
115//! (`TwccReceiverInterceptor<SenderReportInterceptor<…>>`), and it propagates into every type
116//! that holds the peer connection built from it. That is fine when the chain is fixed at compile
117//! time, and a problem when it is chosen at runtime or has to live in your own structs.
118//!
119//! [`Interceptor`] is object safe, so [`Registry::boxed`] can erase the chain to
120//! [`BoxedInterceptor`] — one concrete type, whatever it was built from:
121//!
122//! ```
123//! use rtc_interceptor::{BoxedInterceptor, NackGeneratorBuilder, Registry, SenderReportBuilder};
124//!
125//! # let nack_enabled = true; // e.g. from configuration, negotiated SDP, …
126//! // Two different chain types, unified by `.boxed()`.
127//! let chain: BoxedInterceptor = if nack_enabled {
128//!     Registry::new()
129//!         .with(SenderReportBuilder::new().build())
130//!         .with(NackGeneratorBuilder::new().build())
131//!         .boxed()
132//!         .build()
133//! } else {
134//!     Registry::new().with(SenderReportBuilder::new().build()).boxed().build()
135//! };
136//! ```
137//!
138//! The cost is one virtual call per chain entry point (`handle_read`, `poll_write`,
139//! `handle_timeout`, …); the layers inside still call each other through static dispatch and
140//! inline as before. `Box<P>` and `&mut P` both implement [`Interceptor`], so a boxed or borrowed
141//! chain satisfies an `I: Interceptor` bound like any other.
142//!
143//! # Stream Binding
144//!
145//! Before interceptors can process packets for a stream, the stream must be bound:
146//!
147//! ```
148//! use rtc_interceptor::{Interceptor, RTCPFeedback, RTPHeaderExtension, Registry, StreamInfo};
149//!
150//! let mut chain = Registry::new().build();
151//!
152//! // Create stream info with NACK and TWCC support
153//! let stream_info = StreamInfo {
154//!     ssrc: 0x12345678,
155//!     clock_rate: 90000,
156//!     mime_type: "video/VP8".to_string(),
157//!     payload_type: 96,
158//!     rtcp_feedback: vec![RTCPFeedback {
159//!         typ: "nack".to_string(),
160//!         parameter: String::new(),
161//!     }],
162//!     rtp_header_extensions: vec![RTPHeaderExtension {
163//!         uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01".to_string(),
164//!         id: 5,
165//!     }],
166//!     ..Default::default()
167//! };
168//!
169//! // Bind for outgoing streams (sender side)
170//! chain.bind_local_stream(&stream_info);
171//!
172//! // Bind for incoming streams (receiver side)
173//! chain.bind_remote_stream(&stream_info);
174//! ```
175//!
176//! # Creating Custom Interceptors
177//!
178//! Use the derive macros to easily create custom interceptors:
179//!
180//! ```
181//! use rtc_interceptor::{Interceptor, StreamInfo, TaggedPacket, interceptor};
182//! use sansio::Protocol;
183//! use shared::error::Error; // the generated `Protocol` impl names it
184//! use std::collections::VecDeque;
185//!
186//! #[derive(Interceptor)]
187//! pub struct MyInterceptor<P: Interceptor> {
188//!     #[next]
189//!     next: P,  // The next interceptor in the chain (can use any field name)
190//!     buffer: VecDeque<TaggedPacket>,
191//! }
192//!
193//! #[interceptor]
194//! impl<P: Interceptor> MyInterceptor<P> {
195//!     #[overrides]
196//!     fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
197//!         // Custom logic here
198//!         self.next.handle_read(msg)
199//!     }
200//! }
201//! ```
202//!
203//! - `#[derive(Interceptor)]` - Marks a struct as an interceptor, requires `#[next]` field
204//! - `#[interceptor]` - Generates `Protocol` and `Interceptor` trait implementations
205//! - `#[overrides]` - Marks methods with custom implementations (non-marked methods delegate to next)
206//!
207//! See the [`Interceptor`] trait documentation for more details.
208
209#![warn(rust_2018_idioms)]
210#![warn(missing_docs)]
211#![allow(dead_code)]
212
213use shared::TransportMessage;
214use std::time::Instant;
215
216mod noop;
217mod registry;
218
219pub(crate) mod nack;
220pub(crate) mod report;
221pub(crate) mod stream_info;
222pub(crate) mod twcc;
223
224pub use nack::{
225    generator::{NackGeneratorBuilder, NackGeneratorInterceptor},
226    responder::{NackResponderBuilder, NackResponderInterceptor},
227};
228pub use noop::NoopInterceptor;
229pub use registry::Registry;
230pub use report::{
231    receiver::{ReceiverReportBuilder, ReceiverReportInterceptor},
232    sender::{SenderReportBuilder, SenderReportInterceptor},
233};
234pub use stream_info::{RTCPFeedback, RTPHeaderExtension, StreamInfo};
235pub use twcc::{
236    receiver::{TwccReceiverBuilder, TwccReceiverInterceptor},
237    sender::{TwccSenderBuilder, TwccSenderInterceptor},
238};
239
240// Re-export derive macros for creating custom interceptors
241// - `Interceptor` derive macro: marks a struct as an interceptor with #[next] field
242// - `interceptor` attribute macro: generates Protocol and Interceptor trait implementations
243pub use interceptor_derive::{Interceptor, interceptor};
244
245/// RTP/RTCP Packet
246///
247/// An enum representing either an RTP or RTCP packet that can be processed
248/// by interceptors in the chain.
249#[derive(Debug, Clone, PartialEq)]
250#[non_exhaustive]
251pub enum Packet {
252    /// RTP (Real-time Transport Protocol) packet containing media data
253    Rtp(rtp::Packet),
254    /// RTCP (RTP Control Protocol) packets for feedback and statistics
255    Rtcp(Vec<Box<dyn rtcp::Packet>>),
256}
257
258/// Tagged packet with transport metadata.
259///
260/// A [`TransportMessage`] wrapping a [`Packet`], which includes transport-level
261/// context such as source/destination addresses and protocol information.
262/// This is the primary message type passed through interceptor chains.
263pub type TaggedPacket = TransportMessage<Packet>;
264
265/// Trait for RTP/RTCP interceptors with fixed Protocol type parameters.
266///
267/// `Interceptor` is a marker trait that requires implementors to also implement
268/// [`sansio::Protocol`] with specific fixed type parameters for RTP/RTCP processing:
269/// - `Rin`, `Win`, `Rout`, `Wout` = [`TaggedPacket`]
270/// - `Ein`, `Eout` = `()`
271/// - `Time` = [`Instant`]
272/// - `Error` = [`shared::error::Error`]
273///
274/// This trait adds stream binding methods and provides a [`with()`](Interceptor::with)
275/// method for composable chaining of interceptors.
276///
277/// # Creating Custom Interceptors
278///
279/// ## Using Derive Macros (Recommended)
280///
281/// The easiest way to create a custom interceptor is using the derive macros:
282///
283/// ```
284/// use rtc_interceptor::{Interceptor, StreamInfo, TaggedPacket, interceptor};
285/// use sansio::Protocol;
286/// use shared::error::Error; // the generated `Protocol` impl names it
287/// use std::collections::VecDeque;
288///
289/// #[derive(Interceptor)]
290/// pub struct MyInterceptor<P: Interceptor> {
291///     #[next]
292///     next: P,  // The next interceptor in the chain
293///     buffer: VecDeque<TaggedPacket>,
294/// }
295///
296/// #[interceptor]
297/// impl<P: Interceptor> MyInterceptor<P> {
298///     #[overrides]
299///     fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
300///         // Custom logic here
301///         self.next.handle_read(msg)
302///     }
303/// }
304/// ```
305///
306/// The `#[derive(Interceptor)]` macro requires a `#[next]` field that contains the
307/// next interceptor in the chain. The `#[interceptor]` attribute on the impl block
308/// generates the `Protocol` and `Interceptor` trait implementations, delegating
309/// non-overridden methods to the next interceptor.
310///
311/// Use `#[overrides]` to mark methods with custom implementations.
312///
313/// ## Manual Implementation
314///
315/// For more control, you can implement the traits manually. The sketch below omits the
316/// `Protocol` method bodies, so it is not compiled — see [`NoopInterceptor`] for a complete
317/// hand-written implementation:
318///
319/// ```ignore
320/// pub struct MyInterceptor<P> {
321///     inner: P,
322/// }
323///
324/// impl<P: Interceptor> Protocol<TaggedPacket, TaggedPacket, ()> for MyInterceptor<P> {
325///     type Rout = TaggedPacket;
326///     type Wout = TaggedPacket;
327///     type Eout = ();
328///     type Time = Instant;
329///     type Error = shared::error::Error;
330///     // ... implement Protocol methods
331/// }
332///
333/// impl<P: Interceptor> Interceptor for MyInterceptor<P> {
334///     fn bind_local_stream(&mut self, _info: &StreamInfo) {}
335///     fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
336///     fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
337///     fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
338/// }
339/// ```
340///
341/// # Using with Registry
342///
343/// A builder is just a closure from the next layer to the wrapping one, so a custom
344/// interceptor can be added the same way as a built-in:
345///
346/// ```
347/// use rtc_interceptor::{Registry, SenderReportBuilder};
348///
349/// let registry = Registry::new().with(SenderReportBuilder::new().build());
350/// // ...or with a closure: `.with(|inner| MyInterceptor { next: inner, .. })`
351/// ```
352pub trait Interceptor:
353    sansio::Protocol<
354        TaggedPacket,
355        TaggedPacket,
356        (),
357        Rout = TaggedPacket,
358        Wout = TaggedPacket,
359        Eout = (),
360        Time = Instant,
361        Error = shared::error::Error,
362    > + Send
363    + Sync
364{
365    /// Wrap this interceptor with another layer.
366    ///
367    /// The wrapper function receives `self` and returns a new interceptor
368    /// that wraps it.
369    ///
370    /// # Example
371    ///
372    /// ```
373    /// use rtc_interceptor::{Interceptor, NoopInterceptor, SenderReportBuilder};
374    /// use std::time::Duration;
375    ///
376    /// // `Interceptor` must be in scope for `with` to resolve.
377    /// let chain = NoopInterceptor::new()
378    ///     .with(SenderReportBuilder::new().with_interval(Duration::from_secs(1)).build());
379    /// ```
380    fn with<O, F>(self, f: F) -> O
381    where
382        Self: Sized,
383        F: FnOnce(Self) -> O,
384        O: Interceptor,
385    {
386        f(self)
387    }
388
389    /// bind_local_stream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method
390    /// will be called once per rtp packet.
391    fn bind_local_stream(&mut self, info: &StreamInfo);
392
393    /// unbind_local_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
394    fn unbind_local_stream(&mut self, info: &StreamInfo);
395
396    /// bind_remote_stream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method
397    /// will be called once per rtp packet.
398    fn bind_remote_stream(&mut self, info: &StreamInfo);
399
400    /// unbind_remote_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
401    fn unbind_remote_stream(&mut self, info: &StreamInfo);
402}
403
404/// A type-erased interceptor chain.
405///
406/// `Interceptor` is object safe, so a chain built at runtime can be erased into this one
407/// concrete type. That lets an application store a `RTCPeerConnection<BoxedInterceptor>`
408/// (see [`Registry::boxed`]) instead of being generic over the chain's type.
409pub type BoxedInterceptor = Box<dyn Interceptor>;
410
411impl<P: Interceptor + ?Sized> Interceptor for Box<P> {
412    fn bind_local_stream(&mut self, info: &StreamInfo) {
413        (**self).bind_local_stream(info)
414    }
415
416    fn unbind_local_stream(&mut self, info: &StreamInfo) {
417        (**self).unbind_local_stream(info)
418    }
419
420    fn bind_remote_stream(&mut self, info: &StreamInfo) {
421        (**self).bind_remote_stream(info)
422    }
423
424    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
425        (**self).unbind_remote_stream(info)
426    }
427}
428
429/// Blanket implementation for mutable references.
430///
431/// This lets a borrowed chain satisfy an `Interceptor` bound, so a function taking
432/// `I: Interceptor` by value can be called with `&mut chain` and leave ownership with the
433/// caller. It mirrors [`sansio::Protocol`]'s own `&mut P` implementation, and the same idiom
434/// in `std` (`impl Read for &mut R`, `impl Iterator for &mut I`).
435///
436/// This is only expressible because [`Interceptor`] does not require `'static`: `&'a mut P`
437/// outlives only `'a`. See [`Registry::boxed`], which carries that bound locally instead.
438impl<P: Interceptor + ?Sized> Interceptor for &mut P {
439    fn bind_local_stream(&mut self, info: &StreamInfo) {
440        (**self).bind_local_stream(info)
441    }
442
443    fn unbind_local_stream(&mut self, info: &StreamInfo) {
444        (**self).unbind_local_stream(info)
445    }
446
447    fn bind_remote_stream(&mut self, info: &StreamInfo) {
448        (**self).bind_remote_stream(info)
449    }
450
451    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
452        (**self).unbind_remote_stream(info)
453    }
454}
455
456#[cfg(test)]
457mod derive_test {
458    use super::*;
459    #[allow(unused_imports)]
460    use shared::error::Error;
461
462    /// Test interceptor that uses the derive macro.
463    /// It should automatically delegate all Protocol and Interceptor methods to inner.
464    #[derive(Interceptor)]
465    pub struct SimplePassthrough<P: Interceptor> {
466        #[next]
467        inner: P,
468    }
469
470    // Empty impl block - #[interceptor] generates all delegations
471    #[interceptor]
472    impl<P: Interceptor> SimplePassthrough<P> {}
473
474    impl<P: Interceptor> SimplePassthrough<P> {
475        fn new(inner: P) -> Self {
476            Self { inner }
477        }
478    }
479
480    #[test]
481    fn test_derive_interceptor_basic() {
482        // Build a chain with the derived interceptor
483        let mut chain = SimplePassthrough::new(NoopInterceptor::new());
484
485        // Test that delegation works
486        let pkt = TaggedPacket {
487            now: std::time::Instant::now(),
488            transport: Default::default(),
489            message: Packet::Rtp(rtp::Packet::default()),
490        };
491
492        // handle_write should delegate to inner
493        sansio::Protocol::handle_write(&mut chain, pkt).unwrap();
494
495        // poll_write should return the packet from inner
496        let result = sansio::Protocol::poll_write(&mut chain);
497        assert!(result.is_some());
498    }
499
500    #[test]
501    fn test_derive_interceptor_close() {
502        let mut chain = SimplePassthrough::new(NoopInterceptor::new());
503
504        // close should delegate to inner without error
505        sansio::Protocol::close(&mut chain).unwrap();
506    }
507
508    #[test]
509    fn test_derive_interceptor_stream_binding() {
510        let mut chain = SimplePassthrough::new(NoopInterceptor::new());
511
512        let info = StreamInfo {
513            ssrc: 12345,
514            ..Default::default()
515        };
516
517        // These should delegate to inner without panic
518        chain.bind_local_stream(&info);
519        chain.unbind_local_stream(&info);
520        chain.bind_remote_stream(&info);
521        chain.unbind_remote_stream(&info);
522    }
523
524    /// Consumes an interceptor by value, as the `Registry`/`with` builders do.
525    fn takes_by_value<I: Interceptor>(mut interceptor: I, info: &StreamInfo) {
526        interceptor.bind_local_stream(info);
527        interceptor.unbind_local_stream(info);
528    }
529
530    #[test]
531    fn test_borrowed_chain_satisfies_interceptor_bound() {
532        let mut chain = SimplePassthrough::new(NoopInterceptor::new());
533        let info = StreamInfo {
534            ssrc: 12345,
535            ..Default::default()
536        };
537
538        // `&mut chain` satisfies a by-value `I: Interceptor` bound thanks to the blanket impl.
539        takes_by_value(&mut chain, &info);
540
541        // Ownership stayed with us, so the chain is still usable afterwards.
542        takes_by_value(&mut chain, &info);
543        chain.bind_remote_stream(&info);
544
545        // The borrow also still drives the Protocol side.
546        let pkt = TaggedPacket {
547            now: std::time::Instant::now(),
548            transport: Default::default(),
549            message: Packet::Rtp(rtp::Packet::default()),
550        };
551        sansio::Protocol::handle_write(&mut chain, pkt).unwrap();
552        assert!(sansio::Protocol::poll_write(&mut chain).is_some());
553    }
554
555    #[test]
556    fn test_boxed_chain_still_satisfies_interceptor_bound() {
557        // The `Box<P>` impl coexists with the new `&mut P` impl.
558        let chain: BoxedInterceptor = Box::new(SimplePassthrough::new(NoopInterceptor::new()));
559        let info = StreamInfo {
560            ssrc: 999,
561            ..Default::default()
562        };
563        takes_by_value(chain, &info);
564    }
565}