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