Skip to main content

rtci_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
10//!
11//! | Interceptor | Description |
12//! |-------------|-------------|
13//! | [`RtcpSessionInterceptor`] | The endpoint's RTCP session: one CNAME and reporting identity, SR / RR / SDES / BYE, the timing of RFC 3550 6.3 and RFC 4585 3.5, every outbound RTCP packet in a compound packet (RFC 8108, RFC 5506) |
14//! | [`SenderReportInterceptor`] | Sender Reports (SR) for local streams on a fixed timer, for a chain built without the session |
15//! | [`ReceiverReportInterceptor`] | Receiver Reports (RR) on a fixed timer, for a chain built without the session |
16//! | [`KeyFrameRequestInterceptor`] | Delivers inbound PLI and FIR (each FIR command once) to the application |
17//!
18//! ## NACK (Negative Acknowledgement)
19//!
20//! | Interceptor | Description |
21//! |-------------|-------------|
22//! | [`NackGeneratorInterceptor`] | Detects missing RTP packets and generates NACK requests (RFC 4585) |
23//! | [`NackResponderInterceptor`] | Buffers sent packets and retransmits on NACK, with optional RTX support (RFC 4588) |
24//!
25//! ## TWCC (Transport Wide Congestion Control)
26//!
27//! | Interceptor | Description |
28//! |-------------|-------------|
29//! | [`TwccSenderInterceptor`] | Adds transport-wide sequence numbers to outgoing RTP packets |
30//! | [`TwccReceiverInterceptor`] | Tracks incoming packets and generates TransportLayerCC feedback |
31//!
32//! ## Congestion control
33//!
34//! | Interceptor | Description |
35//! |-------------|-------------|
36//! | [`PacerInterceptor`] | Releases outgoing packets at a target rate rather than in bursts |
37//! | [`Rfc8888Interceptor`] | Reports per-packet arrival times back to the sender (RFC 8888) |
38//!
39//! ## Utility
40//!
41//! | Interceptor | Description |
42//! |-------------|-------------|
43//! | [`NoopInterceptor`] | Ends the inbound RTCP path; the last interceptor in a chain |
44//!
45//! # Design
46//!
47//! A chain is a flat list of interceptors driven over a shared belt. Each one can:
48//! - transform a packet passing through, or swallow it to drop or delay it
49//! - emit packets it generated or was holding, which rejoin the belt and carry on
50//! - act on timeouts, for periodic work like report generation
51//! - track stream statistics and state
52//!
53//! All interceptors work with [`TaggedPacket`] — an RTP or RTCP packet with transport metadata,
54//! carrying [`Attribute`]s that say what happened to it on the way. No interceptor holds a
55//! reference to another; [`Registry`] assembles the list and walks it. [`Registry::build`] appends
56//! [`NoopInterceptor`] last, so inbound RTCP stops before the application — control traffic the
57//! interceptors act on is not media the caller asked for. An interceptor that wants a particular
58//! packet delivered anyway attaches [`Attribute::DeliverToApplication`] to it.
59//!
60//! # Direction
61//!
62//! A chain is a flat list ordered by **distance from the wire**: the first interceptor is closest to the
63//! network, the last closest to the application. Direction is a property of the walk, not of the
64//! structure:
65//!
66//! ```text
67//! read   (network → application)   forward:  first → … → last
68//! write  (application → network)   reverse:  last  → … → first
69//! ```
70//!
71//! Each interceptor is fed from a shared belt and its output is collected back onto it, so **what a
72//! interceptor emits is seen by every interceptor still ahead of it in the walk**. A retransmission emitted
73//! mid-chain still gets paced, numbered and recorded, because there is no way out of the chain
74//! except through the interceptors that follow.
75//!
76//! One list serves both directions, so "closest to the wire" means one thing rather than opposite
77//! things per direction — which is why the send history and the FEC decoder sit next to each
78//! other, one being the last thing on the way out and the other the first on the way in.
79//!
80//! # Quick Start
81//!
82//! ```
83//! use rtci_interceptor::{
84//!     NackGeneratorBuilder, NackResponderBuilder, ReceiverReportBuilder,
85//!     Registry, SenderReportBuilder, Slot, TwccReceiverBuilder, TwccSenderBuilder,
86//! };
87//! use std::time::Duration;
88//!
89//! // The slot decides the position, not the order of these calls; they are listed
90//! // wire-to-application here only because that reads the way the chain runs — forwards on the
91//! // read path, and in reverse on the write path.
92//! let chain = Registry::new()
93//!     .with(Slot::TwccSender, TwccSenderBuilder::new().build())
94//!     .with(Slot::NackResponder, NackResponderBuilder::new().build())
95//!     .with(Slot::NackGenerator, NackGeneratorBuilder::new().build())
96//!     .with(Slot::TwccReceiver, TwccReceiverBuilder::new().build())
97//!     .with(Slot::ReceiverReport, ReceiverReportBuilder::new().build())
98//!     .with(Slot::SenderReport, SenderReportBuilder::new().with_interval(Duration::from_secs(1)).build())
99//!     .build();
100//!
101//! // `build` appends [`NoopInterceptor`] last, so inbound RTCP — control traffic the interceptors
102//! // above act on — stops there rather than arriving mixed in with the application's media. To
103//! // receive some of it, add an interceptor that marks those packets `DeliverToApplication`.
104//! # let _ = chain;
105//! ```
106//!
107//! # One chain type
108//!
109//! [`Registry::build`] returns a single concrete type whatever it was built from, so a struct can
110//! hold one without a type parameter and two connections with different chains share a collection:
111//!
112//! ```
113//! use rtci_interceptor::{Slot, NackGeneratorBuilder, Registry, SenderReportBuilder};
114//!
115//! # let nack_enabled = true; // e.g. from configuration, negotiated SDP, …
116//! let chain = if nack_enabled {
117//!     Registry::new().with(Slot::NackGenerator, NackGeneratorBuilder::new().build()).build()
118//! } else {
119//!     Registry::new().with(Slot::SenderReport, SenderReportBuilder::new().build()).build()
120//! };
121//! ```
122//!
123//! The cost is one virtual call per interceptor per packet, which is nothing beside SRTP.
124//!
125//! # Stream Binding
126//!
127//! Before interceptors can process packets for a stream, the stream must be bound:
128//!
129//! ```
130//! use rtci_interceptor::{Slot, Interceptor, RTCPFeedback, RTPHeaderExtension, Registry, StreamInfo};
131//!
132//! let mut chain = Registry::new().build();
133//!
134//! // Create stream info with NACK and TWCC support
135//! let stream_info = StreamInfo {
136//!     ssrc: 0x12345678,
137//!     clock_rate: 90000,
138//!     mime_type: "video/VP8".to_string(),
139//!     payload_type: 96,
140//!     rtcp_feedback: vec![RTCPFeedback {
141//!         typ: "nack".to_string(),
142//!         parameter: String::new(),
143//!     }],
144//!     rtp_header_extensions: vec![RTPHeaderExtension {
145//!         uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01".to_string(),
146//!         id: 5,
147//!     }],
148//!     ..Default::default()
149//! };
150//!
151//! // Bind for outgoing streams (sender side)
152//! chain.bind_local_stream(&stream_info);
153//!
154//! // Bind for incoming streams (receiver side)
155//! chain.bind_remote_stream(&stream_info);
156//! ```
157//!
158//! # Writing your own
159//!
160//! Implement [`sansio::Protocol`] and [`Interceptor`], then add it wherever it belongs in the
161//! list. What `handle_*` takes in, `poll_*` gives back — so even a pass-through needs a queue,
162//! because the queue is what the next interceptor is fed from:
163//!
164//! ```
165//! use rtci_interceptor::{Slot, Interceptor, Registry, StreamInfo, TaggedPacket};
166//! use sansio::Protocol;
167//! use std::collections::VecDeque;
168//! use std::time::Instant;
169//!
170//! /// Counts packets on their way out.
171//! #[derive(Default)]
172//! struct Counter {
173//!     sent: u64,
174//!     read_queue: VecDeque<TaggedPacket>,
175//!     write_queue: VecDeque<TaggedPacket>,
176//! }
177//!
178//! impl Protocol<TaggedPacket, TaggedPacket, ()> for Counter {
179//!     type Rout = TaggedPacket;
180//!     type Wout = TaggedPacket;
181//!     type Eout = ();
182//!     type Error = shared::error::Error;
183//!     type Time = Instant;
184//!
185//!     fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
186//!         self.read_queue.push_back(msg);
187//!         Ok(())
188//!     }
189//!
190//!     fn poll_read(&mut self) -> Option<Self::Rout> {
191//!         self.read_queue.pop_front()
192//!     }
193//!
194//!     fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
195//!         self.sent += 1;
196//!         self.write_queue.push_back(msg); // queueing nothing would swallow it
197//!         Ok(())
198//!     }
199//!
200//!     fn poll_write(&mut self) -> Option<Self::Wout> {
201//!         self.write_queue.pop_front()
202//!     }
203//! }
204//!
205//! impl Interceptor for Counter {
206//!     fn bind_local_stream(&mut self, _info: &StreamInfo) {}
207//!     fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
208//!     fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
209//!     fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
210//! }
211//!
212//! let chain = Registry::new().with(Slot::NackGenerator, Counter::default()).build();
213//! # let _ = chain;
214//! ```
215//!
216//! Queue nothing to drop or delay a packet, and queue delayed or generated ones whenever they are
217//! ready — from [`handle_timeout`](sansio::Protocol::handle_timeout), say. They leave through
218//! `poll_*` and continue through every interceptor ahead.
219
220#![warn(rust_2018_idioms)]
221#![warn(missing_docs)]
222#![allow(dead_code)]
223
224use std::time::Instant;
225
226pub(crate) mod chain;
227pub(crate) mod noop;
228pub(crate) mod pass_through;
229pub(crate) mod registry;
230
231pub(crate) mod adaptive_jitter_buffer;
232pub(crate) mod audio_red;
233pub(crate) mod cc;
234pub(crate) mod circuit_breaker;
235pub(crate) mod flexfec;
236pub(crate) mod gcc;
237pub(crate) mod intervalpli;
238pub(crate) mod jitterbuffer;
239pub(crate) mod keyframe;
240pub(crate) mod nack;
241pub(crate) mod never_sent;
242pub(crate) mod ntp_timestamp;
243pub(crate) mod pacing;
244pub(crate) mod packet;
245pub(crate) mod pause_resume;
246pub(crate) mod report;
247pub(crate) mod rfc8888;
248pub(crate) mod rtcp_session;
249pub(crate) mod rtp_session;
250pub(crate) mod rtpfb;
251pub(crate) mod stream_info;
252pub(crate) mod tst;
253pub(crate) mod twcc;
254pub(crate) mod ulpfec;
255pub(crate) mod wire_image;
256pub(crate) mod xr;
257
258// Fork additions kept over upstream (see FORK.md): the TWCC-driven GCC interceptor with its
259// shared bitrate handle, and the adaptive (RFC 3550 jitter + playout-delay extension) jitter buffer.
260pub use adaptive_jitter_buffer::{
261    JitterBufferBuilder as AdaptiveJitterBufferBuilder, JitterBufferControl,
262    JitterBufferInterceptor as AdaptiveJitterBufferInterceptor,
263};
264pub use audio_red::{
265    AudioRedundancy, RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE, RED_AUDIO_DEFAULT_REDUNDANCY,
266    RedAudioBuilder, RedAudioInterceptor,
267};
268pub use cc::estimator::{BandwidthEstimator, ConstantBitrate, EstimatorStats};
269pub use cc::fec_rate::{FecRate, MIN_LOSS as FEC_MIN_LOSS};
270pub use cc::feedback::{CongestionFeedbackFormat, negotiated_congestion_feedback};
271pub use cc::interceptor::{
272    CongestionControlBuilder, CongestionControlHandle, CongestionControlInterceptor,
273    DEFAULT_PRUNE_HORIZON as CONGESTION_CONTROL_DEFAULT_PRUNE_HORIZON, REMB_TIMEOUT,
274};
275pub use cc::probe::{
276    PROBE_AFTER_DROP_TIMEOUT, PROBE_APPLICATION_LIMITED_INTERVAL, PROBE_MAX_OCTETS,
277    PROBE_MIN_DURATION, PROBE_MIN_PACKETS, PROBE_RESULT_TIMEOUT, ProbeController, ProbePacket,
278    ProbeRequest, probe_estimate,
279};
280pub use cc::tmmbr::{TMMBR_OWNER_TIMEOUT, TmmbEntry};
281pub use cc::tmmbr_request::{TMMBR_REPEAT_INTERVAL, TmmbrControl};
282pub use circuit_breaker::{
283    CircuitBreakerBuilder, CircuitBreakerHandle, CircuitBreakerInterceptor, CircuitBreakerReason,
284    CircuitBreakerState,
285    DEFAULT_NON_REPORTING_THRESHOLD as CIRCUIT_BREAKER_NON_REPORTING_THRESHOLD,
286    DEFAULT_RTCP_INTERVAL as CIRCUIT_BREAKER_RTCP_INTERVAL, MediaUsability,
287    PacketSize as CircuitBreakerPacketSize,
288};
289pub use flexfec::bit_array::BitArray;
290pub use flexfec::coverage::{MAX_FEC_PACKETS, MAX_MEDIA_PACKETS, ProtectionCoverage};
291pub use flexfec::draft03::decoder::{FlexFec03Decoder, ParseError as FlexFecParseError};
292pub use flexfec::draft03::encoder::DRAFT03_MAX_MEDIA_PACKETS as FLEXFEC03_MAX_MEDIA_PACKETS;
293pub use flexfec::draft03::encoder::FlexFec03Encoder;
294pub use flexfec::draft03::receiver::{FlexFec03ReceiveBuilder, FlexFec03ReceiveInterceptor};
295pub use flexfec::draft03::sender::{
296    DEFAULT_NUM_FEC_PACKETS, DEFAULT_NUM_MEDIA_PACKETS, FlexFec03SendBuilder,
297    FlexFec03SendInterceptor,
298};
299pub use flexfec::rfc8627::decoder::{
300    FLEXFEC_DEFAULT_REPAIR_WINDOW, FlexFecDecoder, FlexFecDecoderConfig, FlexFecDecoderStats,
301};
302pub use flexfec::rfc8627::encoder::{
303    FlexFecEncodeError, FlexFecEncoder, FlexFecLayout, FlexFecProtection,
304};
305pub use flexfec::rfc8627::header::{
306    FLEXFEC_MAX_MASK_BITS, FLEXFEC_MAX_PROTECTED_SSRCS, FLEXFEC_RECOVERY_SIZE, FlexFecBlock,
307    FlexFecHeader, FlexFecHeaderError, FlexFecProtected,
308};
309pub use flexfec::rfc8627::params::FlexFecParameters;
310pub use flexfec::rfc8627::receiver::{
311    FLEXFEC_MAX_REPAIR_WINDOW, FlexFecReceiveBuilder, FlexFecReceiveInterceptor,
312};
313pub use flexfec::rfc8627::sender::{
314    FLEXFEC_DEFAULT_PROTECTION, FlexFecSendBuilder, FlexFecSendInterceptor,
315};
316pub use gcc::arrival_group::{
317    ArrivalGroup, ArrivalGroupAccumulator, DEFAULT_BURST_INTERVAL as GCC_DEFAULT_BURST_INTERVAL,
318    InterGroupDelay,
319};
320pub use gcc::estimator::{
321    DEFAULT_INITIAL_BITRATE as GCC_INITIAL_BITRATE, DEFAULT_MAX_BITRATE as GCC_MAX_BITRATE,
322    DEFAULT_MIN_BITRATE as GCC_MIN_BITRATE, Gcc,
323};
324pub use gcc::kalman::Kalman;
325pub use gcc::loss::{
326    DEFAULT_HIGH_LOSS as GCC_HIGH_LOSS, DEFAULT_LOSS_INTERVAL as GCC_LOSS_INTERVAL,
327    DEFAULT_LOW_LOSS as GCC_LOW_LOSS, LossController,
328};
329pub use gcc::overuse::{DEFAULT_OVERUSE_TIME as GCC_DEFAULT_OVERUSE_TIME, OveruseDetector, Usage};
330pub use gcc::queue_limit::{
331    QUEUE_AT_LIMIT_MIN_DELAY, QUEUE_AT_LIMIT_SHARE, QUEUE_BASE_WINDOW, QUEUE_HIGH_WINDOW,
332    QueueLimitDetector,
333};
334pub use gcc::rate_calc::{DEFAULT_WINDOW as GCC_RATE_WINDOW, RateCalculator};
335pub use gcc::rate_control::{
336    DEFAULT_DECREASE_FACTOR as GCC_DECREASE_FACTOR, DEFAULT_INCREASE_FACTOR as GCC_INCREASE_FACTOR,
337    DEFAULT_RATE_CONTROL_INTERVAL as GCC_RATE_CONTROL_INTERVAL, RateController, ReceivedRateBound,
338};
339pub use gcc::remb::{
340    ABS_SEND_TIME_SLOT, ABS_SEND_TIME_URI, AbsSendTimeInterceptor, GOOG_REMB,
341    REMB_DECREASE_TRIGGER, REMB_GENERATOR_SLOT, REMB_INITIALIZATION_TIME, REMB_MAX_INTERVAL,
342    REMB_UPDATE_INTERVAL, RembGeneratorBuilder, RembGeneratorInterceptor,
343};
344pub use gcc::slope::{DelayTrend, SlopeEstimator};
345pub use gcc::state::RateControlState;
346pub use gcc::threshold::{
347    AdaptiveThreshold, DEFAULT_INITIAL_MS as GCC_THRESHOLD_INITIAL_MS, ThresholdTimeBase,
348};
349pub use gcc::twcc_gcc::{GccHandle, GccInterceptor, GccInterceptorBuilder, GccShared};
350/// Derive macros for nested (`#[next]`-field) interceptors.
351pub use interceptor_derive::{Interceptor, interceptor};
352pub use intervalpli::generator::{
353    DEFAULT_INTERVAL as INTERVAL_PLI_DEFAULT_INTERVAL, IntervalPliInterceptor,
354};
355pub use jitterbuffer::buffer::{
356    JitterBuffer, JitterBufferStats, Rejected, State as JitterBufferState,
357};
358pub use jitterbuffer::receiver::{
359    DEFAULT_CAPACITY as JITTER_BUFFER_DEFAULT_CAPACITY,
360    DEFAULT_DEPTH as JITTER_BUFFER_DEFAULT_DEPTH, JitterBufferBuilder, JitterBufferInterceptor,
361};
362pub use keyframe::{FirCommands, KeyFrameRequestInterceptor};
363pub use nack::NackControl;
364pub use nack::generator::{
365    NackGeneratorBuilder, NackGeneratorInterceptor,
366    SUGGESTED_MAX_NACKS_PER_PACKET as NACK_SUGGESTED_MAX_NACKS_PER_PACKET,
367    SUGGESTED_MAX_PACKET_AGE as NACK_SUGGESTED_MAX_PACKET_AGE,
368};
369pub use nack::responder::{
370    MAX_RETRANSMISSION_RESERVE, MinimumTarget, NackResponderBuilder, NackResponderInterceptor,
371    PENDING_REQUEST_LIFETIME, PROBE_PADDING_OCTETS, RETRANSMISSION_RATE_WINDOW,
372    RetransmissionRateLimit, RetransmissionReserve,
373};
374pub use noop::NoopInterceptor;
375pub use ntp_timestamp::{
376    NTP_TIMESTAMP_INITIAL_WINDOW, NTP_TIMESTAMP_INTERVAL, NTP_TIMESTAMP_SLOT, NtpTimestampBuilder,
377    NtpTimestampInterceptor,
378};
379pub use pacing::pacer::{
380    BURST_TIME as PACER_BURST_TIME, MIN_BURST_BITS as PACER_MIN_BURST_BITS, Pacer,
381};
382pub use pacing::sender::{
383    DEFAULT_BITRATE as PACER_DEFAULT_BITRATE, DEFAULT_QUEUE_LIMIT as PACER_DEFAULT_QUEUE_LIMIT,
384    DEFAULT_QUEUE_TIME_LIMIT as PACER_DEFAULT_QUEUE_TIME_LIMIT, PacerBuilder, PacerDiscard,
385    PacerInterceptor, PacerPause, QueueOverflow as PacerQueueOverflow, RetransmissionsLeft,
386};
387pub use packet::{Attribute, AttributedPacket, Packet, TaggedPacket};
388pub use pass_through::PassThroughInterceptor;
389pub use pause_resume::{
390    PAUSE_DEFAULT_REPORT_INTERVAL, PAUSE_DEFAULT_ROUND_TRIP_TIME, PAUSED_REPETITIONS,
391    PauseCapability, PauseResumeBuilder, PauseResumeControl, PauseResumeHandle,
392    PauseResumeInterceptor, PauseState, RTCP_FB_CCM_PAUSE, RemotePauseState, pause_config_answer,
393};
394pub use registry::{Registry, Slot};
395pub use report::receiver::{RTCP_FB_RRTR, ReceiverReportBuilder, ReceiverReportInterceptor};
396pub use report::sender::{SenderReportBuilder, SenderReportInterceptor};
397pub use rfc8888::ecn::{
398    CONFIRMATIONS as ECN_CONFIRMATIONS, DEFAULT_RETRY_AFTER as ECN_DEFAULT_RETRY_AFTER, EcnFailure,
399    EcnInitiation, EcnMarking, EcnState, EcnValidation, EctPreference,
400    PROBE_INTERVAL as ECN_PROBE_INTERVAL, PROBE_SPACING as ECN_PROBE_SPACING,
401};
402pub use rfc8888::recorder::CcFeedbackRecorder;
403pub use rfc8888::sender::{
404    DEFAULT_INTERVAL as RFC8888_DEFAULT_INTERVAL,
405    DEFAULT_MAX_REPORT_SIZE as RFC8888_DEFAULT_MAX_REPORT_SIZE, Rfc8888Builder, Rfc8888Interceptor,
406};
407pub use rtcp_session::identity::{RtcpRandom, generate_rtcp_cname};
408pub use rtcp_session::{
409    RTCP_SESSION_DEFAULT_MTU, RTCP_SESSION_DEFAULT_T_RR_INTERVAL, RTCP_SESSION_MIN_BANDWIDTH,
410    RTCP_SESSION_NOMINAL_AUDIO_BANDWIDTH, RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH,
411    RepeatInRegularReports, RtcpBandwidth, RtcpProfile, RtcpSessionBuilder, RtcpSessionControl,
412    RtcpSessionEvent, RtcpSessionInterceptor,
413};
414pub use rtp_session::{PathChanged, PerRtpSession, RtpSession, RtpSessionAssignment};
415pub use rtpfb::acknowledgement::{Acknowledgement, PacketReport, Report};
416pub use rtpfb::convert::{FeedbackTimeline, convert_ccfb, convert_twcc};
417pub use rtpfb::history::History;
418pub use stream_info::{RTCPFeedback, RTPHeaderExtension, StreamInfo};
419pub use tst::{TstnResponderBuilder, TstnResponderInterceptor, TstrCommands, VbcmCommands};
420pub use twcc::receiver::{TwccReceiverBuilder, TwccReceiverInterceptor};
421pub use twcc::sender::{TwccSenderBuilder, TwccSenderInterceptor};
422pub use ulpfec::decoder::{ULPFEC_MAX_HELD_FEC, ULPFEC_MEDIA_WINDOW};
423pub use ulpfec::sender::{ULPFEC_DEFAULT_NUM_FEC_PACKETS, ULPFEC_DEFAULT_NUM_MEDIA_PACKETS};
424pub use ulpfec::{
425    FEC_HEADER_LENGTH as ULPFEC_HEADER_LENGTH, LONG_MASK_BITS as ULPFEC_LONG_MASK_BITS,
426    MAX_LEVELS as ULPFEC_MAX_LEVELS, ProtectionLevel as UlpfecProtectionLevel, RedFecPayload,
427    RedPlacement, SHORT_MASK_BITS as ULPFEC_SHORT_MASK_BITS, UlpfecDecoder, UlpfecDecoderStats,
428    UlpfecEncoder, UlpfecError, UlpfecLevel, UlpfecPacket, UlpfecReceiveBuilder,
429    UlpfecReceiveInterceptor, UlpfecRepair, UlpfecSendBuilder, UlpfecSendInterceptor,
430    UlpfecStreamPacketizer, depacketize_red as depacketize_red_for_ulpfec,
431    one_level_only_from_fmtp as ulpfec_one_level_only_from_fmtp,
432    validate_scheme as validate_ulpfec_scheme,
433};
434pub use wire_image::{MAX_HELD_WIRE_IMAGES, WireImageTap, WireImages, wire_image_tap};
435pub use xr::{
436    DEFAULT_GMIN as XR_DEFAULT_GMIN, DEFAULT_INTERVAL as XR_DEFAULT_INTERVAL, JitterBufferMetrics,
437    RTCP_FB_NACK_ECN, RTCP_FB_XR, RTCP_XR_ECN_SUMMARY, XrReportBuilder, XrReportInterceptor,
438};
439
440/// One interceptor of packet processing.
441///
442/// An interceptor is a [`sansio::Protocol`] like everything else in this stack: packets arrive
443/// through `handle_read`/`handle_write` and leave through `poll_read`/`poll_write`. What is
444/// different is that nothing is wired to anything — an interceptor does not know what is on either
445/// side of it. [`Registry`] builds a flat list and the chain it returns moves packets along it.
446///
447/// # The contract
448///
449/// **What `handle_*` takes in, `poll_*` gives back.** The chain hands you a packet, then asks what
450/// you have ready; whatever you return is what the next interceptor receives. So an interceptor
451/// that passes packets through still needs a queue — take the packet in `handle_read`, hand it
452/// back from `poll_read`.
453///
454/// | To | Do |
455/// |---|---|
456/// | pass a packet through | queue it in `handle_*`, return it from `poll_*` |
457/// | transform it | queue the modified packet |
458/// | drop or delay it | queue nothing; a delayed one is queued later, from `handle_timeout` |
459/// | generate one | queue it whenever you like; it joins the walk from `poll_*` |
460/// | act on a timer | `handle_timeout`, and report the deadline from `poll_timeout` |
461///
462/// # What you emit continues
463///
464/// A packet returned from `poll_write` is handed to the next interceptor in the walk and passes
465/// through every one still ahead of it. Nothing can bypass an interceptor by being generated past
466/// it — which is the class of bug the previous, nested design allowed, and why a retransmission
467/// used to escape the pacer, the transport-wide numbering and the send history.
468///
469/// The same is true in reverse: it also means **nothing reaches the wire or the application except
470/// by passing through the interceptors that follow it**. An interceptor that keeps a packet to
471/// itself keeps it from everything downstream, deliberately.
472///
473/// # Direction
474///
475/// Read walks the list forwards, write walks it in reverse, so one ordering serves both: the first
476/// interceptor is closest to the network in both directions.
477///
478pub trait Interceptor:
479    sansio::Protocol<
480        TaggedPacket,
481        TaggedPacket,
482        (),
483        Rout = TaggedPacket,
484        Wout = TaggedPacket,
485        Eout = (),
486        Time = Instant,
487        Error = shared::error::Error,
488    > + Send
489    + Sync
490{
491    /// Wraps this interceptor in an outer one built by `f`, for nested (`#[next]`-field)
492    /// interceptors written with the [`Interceptor`](derive@Interceptor) derive. The result is an
493    /// ordinary interceptor and can be placed in a [`Registry`] slot.
494    ///
495    /// Kept by the Brainwires fork: upstream removed it with the list-based chain.
496    fn with<O, F>(self, f: F) -> O
497    where
498        Self: Sized,
499        F: FnOnce(Self) -> O,
500        O: Interceptor,
501    {
502        f(self)
503    }
504
505    /// bind_local_stream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method
506    /// will be called once per rtp packet.
507    fn bind_local_stream(&mut self, info: &StreamInfo);
508
509    /// unbind_local_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
510    fn unbind_local_stream(&mut self, info: &StreamInfo);
511
512    /// The local stream `info` moves to another RTP session (its m= section moved to another
513    /// transport, as a bundling answer does): it leaves this one without ending, so nothing
514    /// says it left (no RTCP BYE, RFC 3550 section 6.6). Unbinds it by default.
515    fn move_local_stream_out(&mut self, info: &StreamInfo) {
516        self.unbind_local_stream(info);
517    }
518
519    /// bind_remote_stream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method
520    /// will be called once per rtp packet.
521    fn bind_remote_stream(&mut self, info: &StreamInfo);
522
523    /// unbind_remote_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
524    fn unbind_remote_stream(&mut self, info: &StreamInfo);
525}
526
527/// An interceptor whose concrete type has been erased.
528///
529/// `Interceptor` is object safe, which is what lets a chain be a flat list of these rather than a
530/// tower of nested types.
531pub type BoxedInterceptor = Box<dyn Interceptor>;
532
533impl<P: Interceptor + ?Sized> Interceptor for Box<P> {
534    fn bind_local_stream(&mut self, info: &StreamInfo) {
535        (**self).bind_local_stream(info)
536    }
537
538    fn unbind_local_stream(&mut self, info: &StreamInfo) {
539        (**self).unbind_local_stream(info)
540    }
541
542    fn bind_remote_stream(&mut self, info: &StreamInfo) {
543        (**self).bind_remote_stream(info)
544    }
545
546    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
547        (**self).unbind_remote_stream(info)
548    }
549}
550
551/// Blanket implementation for mutable references.
552///
553/// This lets a borrowed chain satisfy an `Interceptor` bound, so a function taking
554/// `I: Interceptor` by value can be called with `&mut chain` and leave ownership with the
555/// caller. It mirrors [`sansio::Protocol`]'s own `&mut P` implementation, and the same idiom
556/// in `std` (`impl Read for &mut R`, `impl Iterator for &mut I`).
557///
558/// This is only expressible because [`Interceptor`] does not require `'static`: `&'a mut P`
559/// outlives only `'a`. [`Registry::with`] is where the `'static` bound is asked for instead —
560/// locally, by the one method that has to box what it is given.
561impl<P: Interceptor + ?Sized> Interceptor for &mut P {
562    fn bind_local_stream(&mut self, info: &StreamInfo) {
563        (**self).bind_local_stream(info)
564    }
565
566    fn unbind_local_stream(&mut self, info: &StreamInfo) {
567        (**self).unbind_local_stream(info)
568    }
569
570    fn bind_remote_stream(&mut self, info: &StreamInfo) {
571        (**self).bind_remote_stream(info)
572    }
573
574    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
575        (**self).unbind_remote_stream(info)
576    }
577}