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 fec_layer;
236pub(crate) mod fec_sent;
237pub(crate) mod fec_session;
238pub(crate) mod first_transmission;
239pub(crate) mod flexfec;
240pub(crate) mod gcc;
241pub(crate) mod intervalpli;
242pub(crate) mod jitterbuffer;
243pub(crate) mod keyframe;
244pub(crate) mod nack;
245pub(crate) mod never_sent;
246pub(crate) mod ntp_timestamp;
247pub(crate) mod pacing;
248pub(crate) mod packet;
249pub(crate) mod pause_resume;
250pub(crate) mod report;
251pub(crate) mod rfc8888;
252pub(crate) mod rtcp_session;
253pub(crate) mod rtp_session;
254pub(crate) mod rtpfb;
255pub(crate) mod stream_info;
256pub(crate) mod tst;
257pub(crate) mod twcc;
258pub(crate) mod ulpfec;
259pub(crate) mod wire_image;
260pub(crate) mod xr;
261
262// Fork additions kept over upstream (see FORK.md): the TWCC-driven GCC interceptor with its
263// shared bitrate handle, and the adaptive (RFC 3550 jitter + playout-delay extension) jitter buffer.
264pub use adaptive_jitter_buffer::{
265    JitterBufferBuilder as AdaptiveJitterBufferBuilder, JitterBufferControl,
266    JitterBufferInterceptor as AdaptiveJitterBufferInterceptor,
267};
268pub use audio_red::{
269    AudioRedundancy, RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE, RED_AUDIO_DEFAULT_REDUNDANCY,
270    RED_AUDIO_LOSS_ON, RedAudioBuilder, RedAudioInterceptor, RedundantEncoding,
271};
272pub use cc::estimator::{BandwidthEstimator, ConstantBitrate, EstimatorStats};
273pub use cc::fec_rate::{
274    FEC_DEFAULT_LATENCY_BUDGET, FecRate, LossPattern as FecLossPattern, MIN_LOSS as FEC_MIN_LOSS,
275};
276pub use cc::feedback::{CongestionFeedbackFormat, negotiated_congestion_feedback};
277pub use cc::feedback_cadence::{
278    CongestionFeedbackCadence, PER_FRAME_INTERVAL, PER_FRAME_MAX_INTERVAL,
279};
280pub use cc::interceptor::{
281    CongestionControlBuilder, CongestionControlHandle, CongestionControlInterceptor,
282    DEFAULT_PRUNE_HORIZON as CONGESTION_CONTROL_DEFAULT_PRUNE_HORIZON, REMB_TIMEOUT, SendEstimate,
283};
284pub use cc::probe::{
285    AfterDropProbe, PROBE_AFTER_DROP_TIMEOUT, PROBE_APPLICATION_LIMITED_INTERVAL,
286    PROBE_DROP_MEMORY, PROBE_MAX_OCTETS, PROBE_MIN_DURATION, PROBE_MIN_PACKETS,
287    PROBE_RECOVERY_INTERVAL, PROBE_RESULT_TIMEOUT, ProbeController, ProbeFill, ProbePacket,
288    ProbeRequest, burst_estimate, probe_estimate,
289};
290pub use cc::tmmbr::{TMMBR_OWNER_TIMEOUT, TmmbEntry};
291pub use cc::tmmbr_request::{TMMBR_REPEAT_INTERVAL, TmmbrControl};
292pub use circuit_breaker::{
293    CircuitBreakerBuilder, CircuitBreakerHandle, CircuitBreakerInterceptor, CircuitBreakerNotice,
294    CircuitBreakerReason, CircuitBreakerState,
295    DEFAULT_NON_REPORTING_THRESHOLD as CIRCUIT_BREAKER_NON_REPORTING_THRESHOLD,
296    DEFAULT_RTCP_INTERVAL as CIRCUIT_BREAKER_RTCP_INTERVAL, MediaUsability,
297    PacketSize as CircuitBreakerPacketSize,
298};
299pub use fec_sent::FecSent;
300pub use fec_session::FecSessionSsrcMap;
301pub use flexfec::bit_array::BitArray;
302pub use flexfec::coverage::{MAX_FEC_PACKETS, MAX_MEDIA_PACKETS, ProtectionCoverage};
303pub use flexfec::draft03::decoder::{FlexFec03Decoder, ParseError as FlexFecParseError};
304pub use flexfec::draft03::encoder::FlexFec03Encoder;
305pub use flexfec::draft03::encoder::{
306    DRAFT03_MAX_MEDIA_PACKETS as FLEXFEC03_MAX_MEDIA_PACKETS,
307    DRAFT03_MAX_REPAIR_PACKET_SIZE as FLEXFEC03_MAX_REPAIR_PACKET_SIZE,
308};
309pub use flexfec::draft03::receiver::{FlexFec03ReceiveBuilder, FlexFec03ReceiveInterceptor};
310pub use flexfec::draft03::sender::{
311    DEFAULT_NUM_FEC_PACKETS, DEFAULT_NUM_MEDIA_PACKETS, FlexFec03SendBuilder,
312    FlexFec03SendInterceptor,
313};
314pub use flexfec::rfc8627::decoder::{
315    FLEXFEC_DEFAULT_REPAIR_WINDOW, FlexFecDecoder, FlexFecDecoderConfig, FlexFecDecoderStats,
316};
317pub use flexfec::rfc8627::encoder::{
318    FlexFecEncodeError, FlexFecEncoder, FlexFecLayout, FlexFecProtection,
319};
320pub use flexfec::rfc8627::header::{
321    FLEXFEC_MAX_MASK_BITS, FLEXFEC_MAX_PROTECTED_SSRCS, FLEXFEC_RECOVERY_SIZE, FlexFecBlock,
322    FlexFecHeader, FlexFecHeaderError, FlexFecProtected,
323};
324pub use flexfec::rfc8627::params::FlexFecParameters;
325pub use flexfec::rfc8627::receiver::{
326    FLEXFEC_MAX_REPAIR_WINDOW, FlexFecReceiveBuilder, FlexFecReceiveInterceptor,
327};
328pub use flexfec::rfc8627::sender::{
329    FLEXFEC_DEFAULT_PROTECTION, FlexFecSendBuilder, FlexFecSendInterceptor,
330};
331pub use gcc::arrival_group::{
332    ArrivalGroup, ArrivalGroupAccumulator, DEFAULT_BURST_INTERVAL as GCC_DEFAULT_BURST_INTERVAL,
333    InterGroupDelay,
334};
335pub use gcc::estimator::{
336    DEFAULT_INITIAL_BITRATE as GCC_INITIAL_BITRATE, DEFAULT_MAX_BITRATE as GCC_MAX_BITRATE,
337    DEFAULT_MIN_BITRATE as GCC_MIN_BITRATE, Gcc,
338};
339pub use gcc::kalman::Kalman;
340pub use gcc::loss::{
341    DEFAULT_HIGH_LOSS as GCC_HIGH_LOSS, DEFAULT_LOSS_INTERVAL as GCC_LOSS_INTERVAL,
342    DEFAULT_LOW_LOSS as GCC_LOW_LOSS, LossController,
343};
344pub use gcc::overuse::{DEFAULT_OVERUSE_TIME as GCC_DEFAULT_OVERUSE_TIME, OveruseDetector, Usage};
345pub use gcc::queue_limit::{
346    QUEUE_AT_LIMIT_MIN_DELAY, QUEUE_AT_LIMIT_SHARE, QUEUE_BASE_WINDOW, QUEUE_HIGH_WINDOW,
347    QueueLimitDetector,
348};
349pub use gcc::rate_calc::{DEFAULT_WINDOW as GCC_RATE_WINDOW, RateCalculator};
350pub use gcc::rate_control::{
351    DEFAULT_DECREASE_FACTOR as GCC_DECREASE_FACTOR, DEFAULT_INCREASE_FACTOR as GCC_INCREASE_FACTOR,
352    DEFAULT_RATE_CONTROL_INTERVAL as GCC_RATE_CONTROL_INTERVAL, RateController, ReceivedRateBound,
353};
354pub use gcc::remb::{
355    ABS_SEND_TIME_SLOT, ABS_SEND_TIME_URI, AbsSendTimeInterceptor, GOOG_REMB,
356    REMB_DECREASE_TRIGGER, REMB_GENERATOR_SLOT, REMB_INITIALIZATION_TIME, REMB_MAX_INTERVAL,
357    REMB_UPDATE_INTERVAL, RembGeneratorBuilder, RembGeneratorInterceptor,
358};
359pub use gcc::slope::{DelayTrend, SlopeEstimator};
360pub use gcc::state::RateControlState;
361pub use gcc::threshold::{
362    AdaptiveThreshold, DEFAULT_INITIAL_MS as GCC_THRESHOLD_INITIAL_MS, ThresholdTimeBase,
363};
364pub use gcc::twcc_gcc::{GccHandle, GccInterceptor, GccInterceptorBuilder, GccShared};
365/// Derive macros for nested (`#[next]`-field) interceptors.
366pub use interceptor_derive::{Interceptor, interceptor};
367pub use intervalpli::generator::{
368    DEFAULT_INTERVAL as INTERVAL_PLI_DEFAULT_INTERVAL, IntervalPliInterceptor,
369};
370pub use jitterbuffer::buffer::{
371    JitterBuffer, JitterBufferStats, Rejected, State as JitterBufferState,
372};
373pub use jitterbuffer::receiver::{
374    DEFAULT_CAPACITY as JITTER_BUFFER_DEFAULT_CAPACITY,
375    DEFAULT_DEPTH as JITTER_BUFFER_DEFAULT_DEPTH, JitterBufferBuilder, JitterBufferInterceptor,
376};
377pub use keyframe::{FirCommands, KeyFrameRequestInterceptor, LocalKeyFrameRequest};
378pub use nack::NackControl;
379pub use nack::generator::{
380    NackGeneratorBuilder, NackGeneratorInterceptor,
381    SUGGESTED_MAX_NACKS_PER_PACKET as NACK_SUGGESTED_MAX_NACKS_PER_PACKET,
382    SUGGESTED_MAX_PACKET_AGE as NACK_SUGGESTED_MAX_PACKET_AGE,
383};
384pub use nack::responder::{
385    MAX_REPAIR_AGE as NACK_MAX_REPAIR_AGE, MAX_RETRANSMISSION_RESERVE, MinimumTarget,
386    NackResponderBuilder, NackResponderInterceptor, PENDING_REQUEST_LIFETIME, PROBE_PADDING_OCTETS,
387    REPAIR_BACKLOG_BOUND as NACK_REPAIR_BACKLOG_BOUND, RETRANSMISSION_RATE_WINDOW,
388    RetransmissionRateLimit, RetransmissionReserve,
389};
390pub use noop::NoopInterceptor;
391pub use ntp_timestamp::{
392    NTP_TIMESTAMP_INITIAL_WINDOW, NTP_TIMESTAMP_INTERVAL, NTP_TIMESTAMP_SLOT, NtpTimestampBuilder,
393    NtpTimestampInterceptor,
394};
395pub use pacing::pacer::{
396    BURST_TIME as PACER_BURST_TIME, MIN_BURST_BITS as PACER_MIN_BURST_BITS, Pacer,
397};
398pub use pacing::sender::{
399    Backlog as PacerBacklog, DEFAULT_BITRATE as PACER_DEFAULT_BITRATE,
400    DEFAULT_QUEUE_LIMIT as PACER_DEFAULT_QUEUE_LIMIT,
401    DEFAULT_QUEUE_TIME_LIMIT as PACER_DEFAULT_QUEUE_TIME_LIMIT, PacerBuilder, PacerDiscard,
402    PacerFlush, PacerInterceptor, PacerPause, PacerPriorities, QueueOverflow as PacerQueueOverflow,
403    RetransmissionsLeft, StreamsNotSending,
404};
405pub use packet::{Attribute, AttributedPacket, Packet, TaggedPacket};
406pub use pass_through::PassThroughInterceptor;
407pub use pause_resume::{
408    PAUSE_DEFAULT_REPORT_INTERVAL, PAUSE_DEFAULT_ROUND_TRIP_TIME, PAUSE_MEDIA_BOUNDARY_MAX_WAIT,
409    PAUSED_REPETITIONS, PauseCapability, PauseResumeBuilder, PauseResumeControl, PauseResumeHandle,
410    PauseResumeInterceptor, PauseState, RTCP_FB_CCM_PAUSE, RemotePauseState, pause_config_answer,
411};
412pub use registry::{Registry, Slot};
413pub use report::receiver::{RTCP_FB_RRTR, ReceiverReportBuilder, ReceiverReportInterceptor};
414pub use report::sender::{SenderReportBuilder, SenderReportInterceptor};
415pub use rfc8888::ecn::{
416    CONFIRMATIONS as ECN_CONFIRMATIONS, DEFAULT_RETRY_AFTER as ECN_DEFAULT_RETRY_AFTER, EcnFailure,
417    EcnInitiation, EcnMarking, EcnState, EcnValidation, EctPreference,
418    PROBE_INTERVAL as ECN_PROBE_INTERVAL, PROBE_SPACING as ECN_PROBE_SPACING,
419};
420pub use rfc8888::recorder::CcFeedbackRecorder;
421pub use rfc8888::sender::{
422    DEFAULT_INTERVAL as RFC8888_DEFAULT_INTERVAL,
423    DEFAULT_MAX_REPORT_SIZE as RFC8888_DEFAULT_MAX_REPORT_SIZE, Rfc8888Builder, Rfc8888Interceptor,
424};
425pub use rtcp_session::identity::{RtcpRandom, generate_rtcp_cname};
426pub use rtcp_session::{
427    RTCP_SESSION_DEFAULT_MTU, RTCP_SESSION_DEFAULT_T_RR_INTERVAL, RTCP_SESSION_MIN_BANDWIDTH,
428    RTCP_SESSION_NOMINAL_AUDIO_BANDWIDTH, RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH,
429    RepeatInRegularReports, RtcpBandwidth, RtcpBandwidthShare, RtcpProfile, RtcpReportingInterval,
430    RtcpSessionBuilder, RtcpSessionControl, RtcpSessionEvent, RtcpSessionInterceptor,
431};
432pub use rtp_session::{PathChanged, PerRtpSession, RtpSession, RtpSessionAssignment};
433pub use rtpfb::acknowledgement::{Acknowledgement, PacketReport, Report};
434pub use rtpfb::convert::{FeedbackTimeline, convert_ccfb, convert_twcc};
435pub use rtpfb::history::History;
436pub use stream_info::{FecSessionStream, RTCPFeedback, RTPHeaderExtension, StreamInfo};
437pub use tst::{TstnResponderBuilder, TstnResponderInterceptor, TstrCommands, VbcmCommands};
438pub use twcc::receiver::{TwccReceiverBuilder, TwccReceiverInterceptor};
439pub use twcc::sender::{
440    RETRANSMISSION_REPORT_HORIZON, ReportedRetransmission, RetransmissionsReported,
441    TwccSenderBuilder, TwccSenderInterceptor,
442};
443pub use ulpfec::decoder::{ULPFEC_MAX_HELD_FEC, ULPFEC_MEDIA_WINDOW};
444pub use ulpfec::sender::{
445    ULPFEC_DEFAULT_NUM_FEC_PACKETS, ULPFEC_DEFAULT_NUM_MEDIA_PACKETS, ULPFEC_MAX_HELD_FEC_PACKETS,
446};
447pub use ulpfec::{
448    FEC_HEADER_LENGTH as ULPFEC_HEADER_LENGTH, FecSessionPacket,
449    LONG_MASK_BITS as ULPFEC_LONG_MASK_BITS, MAX_LEVELS as ULPFEC_MAX_LEVELS,
450    ProtectionLevel as UlpfecProtectionLevel, RedFecPayload, RedPlacement,
451    SHORT_MASK_BITS as ULPFEC_SHORT_MASK_BITS, UlpfecDecoder, UlpfecDecoderStats, UlpfecEncoder,
452    UlpfecError, UlpfecLevel, UlpfecPacket, UlpfecReceiveBuilder, UlpfecReceiveInterceptor,
453    UlpfecReceiveStats, UlpfecRepair, UlpfecSendBuilder, UlpfecSendInterceptor,
454    UlpfecStreamPacketizer, depacketize_red as depacketize_red_for_ulpfec,
455    one_level_only_from_fmtp as ulpfec_one_level_only_from_fmtp,
456    validate_scheme as validate_ulpfec_scheme,
457};
458pub use wire_image::{MAX_HELD_WIRE_IMAGES, WireImageTap, WireImages, wire_image_tap};
459pub use xr::{
460    CallQuality, DEFAULT_GMIN as XR_DEFAULT_GMIN, DEFAULT_INTERVAL as XR_DEFAULT_INTERVAL,
461    DEFAULT_MAX_BLOCK_SIZE as XR_DEFAULT_MAX_BLOCK_SIZE, JitterBufferMetrics, RTCP_FB_NACK_ECN,
462    RTCP_FB_XR, RTCP_XR_ECN_SUMMARY, XrReportBuilder, XrReportHandle, XrReportInterceptor,
463};
464
465/// One interceptor of packet processing.
466///
467/// An interceptor is a [`sansio::Protocol`] like everything else in this stack: packets arrive
468/// through `handle_read`/`handle_write` and leave through `poll_read`/`poll_write`. What is
469/// different is that nothing is wired to anything — an interceptor does not know what is on either
470/// side of it. [`Registry`] builds a flat list and the chain it returns moves packets along it.
471///
472/// # The contract
473///
474/// **What `handle_*` takes in, `poll_*` gives back.** The chain hands you a packet, then asks what
475/// you have ready; whatever you return is what the next interceptor receives. So an interceptor
476/// that passes packets through still needs a queue — take the packet in `handle_read`, hand it
477/// back from `poll_read`.
478///
479/// | To | Do |
480/// |---|---|
481/// | pass a packet through | queue it in `handle_*`, return it from `poll_*` |
482/// | transform it | queue the modified packet |
483/// | drop or delay it | queue nothing; a delayed one is queued later, from `handle_timeout` |
484/// | generate one | queue it whenever you like; it joins the walk from `poll_*` |
485/// | act on a timer | `handle_timeout`, and report the deadline from `poll_timeout` |
486///
487/// # What you emit continues
488///
489/// A packet returned from `poll_write` is handed to the next interceptor in the walk and passes
490/// through every one still ahead of it. Nothing can bypass an interceptor by being generated past
491/// it — which is the class of bug the previous, nested design allowed, and why a retransmission
492/// used to escape the pacer, the transport-wide numbering and the send history.
493///
494/// The same is true in reverse: it also means **nothing reaches the wire or the application except
495/// by passing through the interceptors that follow it**. An interceptor that keeps a packet to
496/// itself keeps it from everything downstream, deliberately.
497///
498/// # Direction
499///
500/// Read walks the list forwards, write walks it in reverse, so one ordering serves both: the first
501/// interceptor is closest to the network in both directions.
502///
503pub trait Interceptor:
504    sansio::Protocol<
505        TaggedPacket,
506        TaggedPacket,
507        (),
508        Rout = TaggedPacket,
509        Wout = TaggedPacket,
510        Eout = (),
511        Time = Instant,
512        Error = shared::error::Error,
513    > + Send
514    + Sync
515{
516    /// Wraps this interceptor in an outer one built by `f`, for nested (`#[next]`-field)
517    /// interceptors written with the [`Interceptor`](derive@Interceptor) derive. The result is an
518    /// ordinary interceptor and can be placed in a [`Registry`] slot.
519    ///
520    /// Kept by the Brainwires fork: upstream removed it with the list-based chain.
521    fn with<O, F>(self, f: F) -> O
522    where
523        Self: Sized,
524        F: FnOnce(Self) -> O,
525        O: Interceptor,
526    {
527        f(self)
528    }
529
530    /// bind_local_stream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method
531    /// will be called once per rtp packet.
532    fn bind_local_stream(&mut self, info: &StreamInfo);
533
534    /// unbind_local_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
535    fn unbind_local_stream(&mut self, info: &StreamInfo);
536
537    /// The local stream `info` moves to another RTP session (its m= section moved to another
538    /// transport, as a bundling answer does): it leaves this one without ending, so nothing
539    /// says it left (no RTCP BYE, RFC 3550 section 6.6). Unbinds it by default.
540    fn move_local_stream_out(&mut self, info: &StreamInfo) {
541        self.unbind_local_stream(info);
542    }
543
544    /// bind_remote_stream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method
545    /// will be called once per rtp packet.
546    fn bind_remote_stream(&mut self, info: &StreamInfo);
547
548    /// unbind_remote_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
549    fn unbind_remote_stream(&mut self, info: &StreamInfo);
550}
551
552/// An interceptor whose concrete type has been erased.
553///
554/// `Interceptor` is object safe, which is what lets a chain be a flat list of these rather than a
555/// tower of nested types.
556pub type BoxedInterceptor = Box<dyn Interceptor>;
557
558impl<P: Interceptor + ?Sized> Interceptor for Box<P> {
559    fn bind_local_stream(&mut self, info: &StreamInfo) {
560        (**self).bind_local_stream(info)
561    }
562
563    fn unbind_local_stream(&mut self, info: &StreamInfo) {
564        (**self).unbind_local_stream(info)
565    }
566
567    fn bind_remote_stream(&mut self, info: &StreamInfo) {
568        (**self).bind_remote_stream(info)
569    }
570
571    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
572        (**self).unbind_remote_stream(info)
573    }
574}
575
576/// Blanket implementation for mutable references.
577///
578/// This lets a borrowed chain satisfy an `Interceptor` bound, so a function taking
579/// `I: Interceptor` by value can be called with `&mut chain` and leave ownership with the
580/// caller. It mirrors [`sansio::Protocol`]'s own `&mut P` implementation, and the same idiom
581/// in `std` (`impl Read for &mut R`, `impl Iterator for &mut I`).
582///
583/// This is only expressible because [`Interceptor`] does not require `'static`: `&'a mut P`
584/// outlives only `'a`. [`Registry::with`] is where the `'static` bound is asked for instead —
585/// locally, by the one method that has to box what it is given.
586impl<P: Interceptor + ?Sized> Interceptor for &mut P {
587    fn bind_local_stream(&mut self, info: &StreamInfo) {
588        (**self).bind_local_stream(info)
589    }
590
591    fn unbind_local_stream(&mut self, info: &StreamInfo) {
592        (**self).unbind_local_stream(info)
593    }
594
595    fn bind_remote_stream(&mut self, info: &StreamInfo) {
596        (**self).bind_remote_stream(info)
597    }
598
599    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
600        (**self).unbind_remote_stream(info)
601    }
602}