rtci_interceptor/registry.rs
1//! Building a chain.
2
3use crate::chain::Chain;
4use crate::noop::NoopInterceptor;
5use crate::{BoxedInterceptor, Interceptor};
6use log::warn;
7use std::collections::BTreeMap;
8
9/// Where an interceptor belongs in the chain, measured by **distance from the wire**.
10///
11/// This is the chain contract's ordering table expressed as data, so that one place decides it and
12/// a test can check a builder against it. The doc comments carry that table's indices; the gaps are
13/// slots nothing fills yet.
14///
15/// Read walks the list forwards and write walks it in reverse, so a smaller slot is closer to the
16/// network in both directions.
17#[derive(Copy, Clone, Debug)]
18#[non_exhaustive]
19#[repr(usize)]
20pub enum Slot {
21 /// The RTCP session ([`RtcpSessionInterceptor`](crate::RtcpSessionInterceptor)): the
22 /// last thing every outbound RTCP packet passes and the first to see what arrives, so it
23 /// counts what really left and arrived and no RTCP leaves except in its compound packets.
24 RtcpSession = 500,
25 /// `CongestionControlInterceptor` — the send history, and the ingest of returning feedback.
26 ///
27 /// **Both legs.** *Read:* ingests inbound TWCC or CCFB and hands the reports to the estimator.
28 /// *Write:* records every departing RTP packet in the send history.
29 ///
30 /// **Why here — wire-most.** The write walk runs from the application down to the wire, so the
31 /// lowest slot is the *last* thing a departing packet meets. Two facts depend on that. The
32 /// departure instant it records is the moment the packet actually left, after the pacer held
33 /// it; recording at enqueue instead would charge the pacer's own queueing delay to the network
34 /// and drive the estimate down for a delay this endpoint created. And the transport-wide
35 /// sequence number the history keys on has already been assigned at 2_000, so a report naming
36 /// that number can be matched to the packet that carried it.
37 CongestionControl = 1_000,
38 /// `WireImageTap` — copies departing media packets, as they leave, for an FEC encoder.
39 ///
40 /// **Outbound only**, and it changes nothing: every packet passes through untouched.
41 ///
42 /// **Why here — below the last thing that edits a packet.** FEC protects the source packets
43 /// as they are on the wire: the receiver XORs what arrived. [`Slot::TwccSender`] at 2_000
44 /// writes the transport-wide sequence number into each departing packet, adding the header
45 /// extension when the packet had none, so an encoder that read the packet above it protects
46 /// an image the receiver never sees, and what it recovers is corrupt. The encoder itself
47 /// cannot move down here: it generates packets, and a generator has to stay above the pacer
48 /// and the TWCC sender so its repair packets are metered and numbered. So the encoder stays
49 /// at [`Slot::FecEncoder`] and reads the wire image from this tap.
50 FecWireImage = 1_500,
51 /// `TwccSenderInterceptor` — stamps each departing RTP packet with the transport-wide sequence
52 /// number the remote will report against.
53 ///
54 /// **Outbound only.** Inbound packets pass through untouched.
55 ///
56 /// **Why here — below every generator, above the history.** The write walk must reach it
57 /// *before* [`Slot::CongestionControl`], or the history would key on a number that does not
58 /// exist yet. It must sit below everything that produces a packet — the NACK responder at
59 /// 4_000, the FEC encoder at 5_000, every RTCP generator above them — because a packet that
60 /// never passes this slot is never numbered, and the remote cannot report on what it cannot
61 /// name. A retransmission is exactly that case.
62 TwccSender = 2_000,
63 /// `CircuitBreakerInterceptor` — the RTP circuit breaker of RFC 8083: stops a flow whose
64 /// receiver has gone, whose media is not arriving, or that persistently takes ten times what
65 /// TCP would.
66 ///
67 /// **Both legs.** *Write:* counts every departing RTP packet, and drops the packets of a
68 /// flow that has ceased transmission. *Read:* reads the report blocks of inbound SR and RR.
69 ///
70 /// **Why here — below the pacer, above the numbering.** Below the pacer it counts what is
71 /// actually released, retransmissions and repair packets included. Above the TWCC sender
72 /// and the send history, a packet it drops is never numbered and never recorded as sent: a
73 /// ceased flow does not read as loss to the congestion controller.
74 CircuitBreaker = 2_500,
75 /// `PacerInterceptor` — gates departures, releasing at the estimated rate.
76 ///
77 /// **Outbound, with one inbound read.** *Write:* queues RTP and releases it on a timer; RTCP
78 /// passes straight through, because feedback is only useful while it is fresh. *Read:* observes
79 /// [`Attribute::TargetBitrateChanged`](crate::Attribute) going past.
80 ///
81 /// **Why here — the meter every generated byte must cross.** Everything that produces a packet
82 /// sits application-ward of this slot, so retransmissions, FEC repair and generated RTCP are all
83 /// metered rather than bursting past the estimate. It is above the TWCC sender so that numbering
84 /// happens at release rather than at enqueue, which keeps the numbers in the order the packets
85 /// actually reach the wire.
86 ///
87 /// The estimate reaches it on the *read* leg because that is the only leg it can: the
88 /// controller is wire-ward of here, so on the write leg it sees packets after this interceptor
89 /// — too late to inform it.
90 Pacer = 3_000,
91 /// `NackResponderInterceptor` — answers a NACK by resending from its own buffer.
92 ///
93 /// **Both legs.** *Write:* buffers each departing RTP packet against a later request.
94 /// *Read:* watches for inbound NACK and queues the retransmissions it asks for.
95 ///
96 /// **Why here — the lowest of the generators.** A retransmission it emits re-enters the belt at
97 /// this slot and continues down, so it is still paced (3_000), numbered (2_000) and recorded
98 /// (1_000). It has to be: a retransmission is new bytes on the wire, and an estimator that does
99 /// not see them believes the path is carrying less than it is — then raises the rate during
100 /// loss, which is the worst moment to do it.
101 NackResponder = 4_000,
102 /// The FEC send interceptor (`FlexFec03SendInterceptor`) — generates repair packets for the
103 /// media it sees leaving.
104 ///
105 /// **Outbound only.**
106 ///
107 /// **Why here — a generator, so above the pacer.** Its repair packets are real bytes and are
108 /// metered, numbered and recorded like any other. Being above the NACK responder also means
109 /// the media it protects has already been buffered for retransmission, so the two recovery
110 /// mechanisms cover the same packets rather than racing to protect different ones.
111 ///
112 /// What it protects is the packet as sent, and at this slot the packet is not final yet: see
113 /// [`Slot::FecWireImage`], where the encoder reads it from.
114 FecEncoder = 5_000,
115 /// `TwccReceiverInterceptor` — reports arrival times to the **remote** sender's congestion
116 /// controller.
117 ///
118 /// **Both legs.** *Read:* records when each inbound packet arrived. *Write:* emits
119 /// `TransportLayerCC` on a timer.
120 ///
121 /// **Why here — the write leg is what pins it.** It reads as a receive-side interceptor, and
122 /// moving it wire-ward looks harmless because nothing it does affects what this endpoint sends.
123 /// It does not work: it *generates*, and below the pacer its feedback would leave unpaced and
124 /// unrecorded by the send history. It is also an arrival recorder, so it must precede the
125 /// jitter buffer — see [`Slot::JitterBuffer`].
126 TwccReceiver = 8_000,
127 /// `Rfc8888Interceptor` — the same job as [`Slot::TwccReceiver`] in a different format.
128 ///
129 /// **Both legs**, and pinned by the same two constraints: a generator above the pacer, an
130 /// arrival recorder before the jitter buffer. It sits next to the TWCC receiver because the two
131 /// are alternatives — registering both reports every packet to the remote twice, and its
132 /// estimator cannot tell the two formats apart, so it reads the path as carrying double.
133 Rfc8888 = 9_000,
134 /// `ReceiverReportInterceptor` — RFC 3550 reception quality, not congestion-control feedback.
135 ///
136 /// **Both legs.** *Read:* accumulates loss, jitter and the extended sequence number from
137 /// inbound RTP. *Write:* emits RR on a timer.
138 ///
139 /// **Why here — the same pair of constraints as the arrival recorders above.** Above the pacer
140 /// because it generates; before the jitter buffer because the jitter it measures must be the
141 /// path's, not this endpoint's buffering.
142 ReceiverReport = 10_000,
143 /// The FEC receive interceptor (`FlexFec03ReceiveInterceptor`) — rebuilds packets the path
144 /// dropped.
145 ///
146 /// **Inbound only.** Nothing on the write leg.
147 ///
148 /// **Why here — after the arrival recorders, before anything reads a sequence number.** The
149 /// read walk runs wire to application. The arrival recorders ([`Slot::TwccReceiver`],
150 /// [`Slot::Rfc8888`], [`Slot::ReceiverReport`]) come first: they report what the path
151 /// delivered, so they have to see the repair packets this interceptor consumes, and they must
152 /// not see the packets it rebuilds. A repair packet swallowed before them is reported to the
153 /// sender as lost, and a rebuilt packet counted by them hides a loss from the sender's
154 /// congestion controller and from `fraction lost`. The NACK generator comes after
155 /// ([`Slot::NackGenerator`]): this endpoint must not ask the remote to retransmit a packet it
156 /// is about to rebuild locally.
157 FecDecoder = 10_300,
158 /// `NackGeneratorInterceptor` — asks the remote for what did not arrive.
159 ///
160 /// **Both legs.** *Read:* detects gaps in the inbound sequence space. *Write:* emits NACK on a
161 /// timer.
162 ///
163 /// **Why here — after recovery, before re-timing.** After the FEC decoder (10_300), so a
164 /// rebuilt packet counts as present and is not requested again. Before the jitter buffer
165 /// (13_000), so it judges loss from arrival order rather than from playout order. And, being
166 /// a generator, application-ward of the pacer so its NACKs are metered.
167 NackGenerator = 10_600,
168 /// `SenderReportInterceptor` — emits SR on a timer, describing what this endpoint has sent.
169 ///
170 /// **Outbound only.**
171 ///
172 /// **Why here — generator, and nothing else constrains it.** Above the pacer so its reports are
173 /// metered. Nothing inbound informs it, so it has no read-side ordering requirement and its
174 /// exact position among the generators does not matter.
175 SenderReport = 11_000,
176 /// `IntervalPliInterceptor` — asks the remote for a keyframe on a timer.
177 ///
178 /// **Outbound only.**
179 ///
180 /// **Why here — generator, and nothing else constrains it**, exactly as for
181 /// [`Slot::SenderReport`].
182 IntervalPli = 12_000,
183 /// `JitterBufferInterceptor` — holds inbound packets to smooth arrival jitter, then releases
184 /// them in order on a timer.
185 ///
186 /// **Inbound only.**
187 ///
188 /// **Why here — application-most, because it re-times what passes through it.** Every arrival
189 /// recorder must precede it. One placed after would read a packet's *playout* instant and
190 /// report it to the remote as its arrival time; the remote's congestion controller would then
191 /// see this endpoint's own buffering depth as network delay variation — a delay signal
192 /// manufactured locally and indistinguishable, at the far end, from a congested path.
193 JitterBuffer = 13_000,
194 /// Anywhere else, for an interceptor this crate knows nothing about.
195 ///
196 /// The named slots are spaced so one of your own fits between any two of them
197 /// without renumbering anything: `Slot::from(10_450)` sits after the FEC decoder and before the
198 /// NACK generator. Reach it through [`From<usize>`](#impl-From<usize>-for-Slot) rather than by
199 /// naming the variant, so the spelling survives this gaining a richer representation.
200 ///
201 /// **Choosing a number.** Work out which legs your interceptor uses, then apply the same rules
202 /// the named slots obey:
203 ///
204 /// * *It produces packets* — retransmissions, repair, RTCP, anything the wire has not seen yet.
205 /// Put it **above [`Slot::Pacer`]** (> 3_000), or its output leaves unpaced and the send
206 /// history never counts the bytes. This is the constraint people miss, because an interceptor
207 /// that only *reports* on what it received still produces packets to report with.
208 /// * *It reads inbound sequence numbers or arrival times* — loss detection, arrival recording,
209 /// reception statistics. Put it **below [`Slot::JitterBuffer`]** (< 13_000), so it sees the
210 /// order and timing the path produced rather than the order this endpoint replays.
211 /// * *It repairs or recovers inbound packets.* Put it **below anything that would otherwise ask
212 /// for them again** — below [`Slot::NackGenerator`] (< 10_600), as the FEC decoder is.
213 /// * *It only observes, and emits nothing.* Nothing pins it; pick a slot that reads well next to
214 /// its neighbours.
215 ///
216 /// Both legs walk this one list — read from low to high, write from high to low — so a slot is
217 /// a position in *both* directions at once. An interceptor that acts on each leg is subject to
218 /// the constraints of each, and those can pull in opposite directions:
219 /// [`Slot::TwccReceiver`] is the worked example.
220 Custom(usize),
221 /// `KeyFrameRequestInterceptor` — marks inbound PLI and FIR for delivery to the application,
222 /// which is the encoder that has to answer them.
223 ///
224 /// **Inbound only, and it only marks.**
225 ///
226 /// **Why here — application-most.** It neither holds, drops nor generates a packet, so it
227 /// constrains nothing; past every other interceptor, each of them has seen the request before
228 /// it leaves the chain. (Fork addition; see FORK.md. Declared after
229 /// [`Slot::Custom`] so that variant keeps its discriminant.)
230 KeyFrameRequests = 14_000,
231 /// `XrReportInterceptor` — RFC 3611 report blocks about received streams (Loss RLE,
232 /// Duplicate RLE, Packet Receipt Times, Statistics Summary, VoIP Metrics).
233 ///
234 /// **Both legs.** *Read:* records each remote packet's arrival. *Write:* emits XR on a
235 /// timer.
236 ///
237 /// **Why here — an arrival recorder next to the receiver report.** It reports what the
238 /// path delivered, so it reads before the FEC decoder rebuilds packets and before the
239 /// jitter buffer holds them, and it generates, so it sits above the pacer. (Declared after
240 /// [`Slot::Custom`] so that variant keeps its discriminant.)
241 ExtendedReports = 10_100,
242 /// `TstnResponderInterceptor` — answers each temporal-spatial trade-off request a local
243 /// media sender receives with a notification (RFC 5104 section 4.3.3).
244 ///
245 /// **Both legs.** *Read:* sees the requests, which go on to the application. *Write:*
246 /// emits the notifications.
247 ///
248 /// **Why here — application-most, next to the key-frame requests.** It only generates
249 /// RTCP, so it sits above the pacer; nothing it does depends on arrival order. (Declared
250 /// after [`Slot::Custom`] so that variant keeps its discriminant.)
251 TradeoffNotifications = 14_100,
252 /// [`PauseResumeInterceptor`](crate::PauseResumeInterceptor) (RFC 7728): closest to the
253 /// application, so that what it holds back while a stream is paused, and the sequence
254 /// numbers it closes up afterwards, are all any other interceptor sees.
255 PauseResume = 14_200,
256 /// [`RedAudioInterceptor`](crate::RedAudioInterceptor) (RFC 2198): wraps a local audio
257 /// stream's packets in RED and takes received RED packets apart.
258 ///
259 /// **Both legs.** *Write:* application-ward of the NACK responder and the FEC encoder, so
260 /// the RED packet is what they buffer and protect. *Read:* after the receiver report and
261 /// the FEC decoder, which count and repair the RED packets that arrived, and before the
262 /// NACK generator, which then does not ask for a packet RED recovered. (Declared after
263 /// [`Slot::Custom`] so that variant keeps its discriminant.)
264 Redundancy = 10_450,
265}
266
267impl Slot {
268 /// Where this sits, as a distance from the wire.
269 ///
270 /// The named slots are the thousands; a custom one is whatever it was built from.
271 pub const fn slot(self) -> usize {
272 match self {
273 Self::RtcpSession => 500,
274 Self::CongestionControl => 1_000,
275 Self::FecWireImage => 1_500,
276 Self::TwccSender => 2_000,
277 Self::CircuitBreaker => 2_500,
278 Self::Pacer => 3_000,
279 Self::NackResponder => 4_000,
280 Self::FecEncoder => 5_000,
281 Self::TwccReceiver => 8_000,
282 Self::Rfc8888 => 9_000,
283 Self::ReceiverReport => 10_000,
284 Self::FecDecoder => 10_300,
285 Self::NackGenerator => 10_600,
286 Self::SenderReport => 11_000,
287 Self::IntervalPli => 12_000,
288 Self::JitterBuffer => 13_000,
289 Self::KeyFrameRequests => 14_000,
290 Self::ExtendedReports => 10_100,
291 Self::TradeoffNotifications => 14_100,
292 Self::PauseResume => 14_200,
293 Self::Redundancy => 10_450,
294 Self::Custom(position) => position,
295 }
296 }
297}
298
299/// A position of your own. See [`Slot::Custom`].
300impl From<usize> for Slot {
301 fn from(position: usize) -> Self {
302 Self::Custom(position)
303 }
304}
305
306impl From<Slot> for usize {
307 fn from(slot: Slot) -> Self {
308 slot.slot()
309 }
310}
311
312// Equality and ordering are both by position, and they are written out rather than derived because
313// deriving them would disagree with each other. A derived `PartialEq` compares variants, so
314// `Slot::from(2_000) != Slot::TwccSender` even though both name the same distance from the wire; a
315// derived `Ord` compares *declaration* order, so `Slot::Custom(1_500)` would sort after
316// `JitterBuffer` rather than between `CongestionControl` and `TwccSender` — which is the whole
317// point of allowing a custom one. Two values that compare `Equal` must also be `==`, and a sort by
318// slot must put a custom position where its number says, so both come from [`Slot::slot`].
319impl PartialEq for Slot {
320 fn eq(&self, other: &Self) -> bool {
321 self.slot() == other.slot()
322 }
323}
324
325impl Eq for Slot {}
326
327impl PartialOrd for Slot {
328 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
329 Some(self.cmp(other))
330 }
331}
332
333impl Ord for Slot {
334 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
335 self.slot().cmp(&other.slot())
336 }
337}
338
339impl std::hash::Hash for Slot {
340 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
341 self.slot().hash(state);
342 }
343}
344
345/// Collects interceptors and assembles them into a chain.
346///
347/// # Order
348///
349/// Every interceptor is added at a [`Slot`], and [`build`](Self::build) sorts by it. A slot is a
350/// **distance from the wire**: the smallest is closest to the network, the largest closest to the
351/// application. Read walks that order, write walks it in reverse, so one list serves both
352/// directions and "closest to the wire" means one thing rather than opposite things per direction.
353///
354/// ```text
355/// Registry::new()
356/// .with(Slot::TwccSender, a) // 2_000: closest to the wire
357/// .with(Slot::NackGenerator, b) // 10_600
358/// .with(Slot::JitterBuffer, c) // 13_000: closest to the application
359/// .build()
360///
361/// read: a → b → c → application
362/// write: application → c → b → a → wire
363/// ```
364///
365/// Declaring the position rather than relying on call order is what makes the helpers in
366/// `rtci` composable: `configure_twcc` places interceptors at 2_000 and 8_000, `configure_nack` at
367/// 4_000 and 10_600, and the two interleave correctly however the caller sequences them. With order taken
368/// from insertion, calling them in either sequence produced a chain that was wrong in a different
369/// way each time, and nothing caught it — the nested registry that preceded this added *innermost*
370/// first, so `register_default_interceptors` assembled TWCC receiver → RTCP reports → NACK
371/// generator, the reverse of what the chain contract documented.
372///
373/// A slot holds one interceptor. Two of your own go at two custom positions — the named slots are
374/// spaced a thousand apart so there is room between any two of them.
375///
376/// # Example
377///
378/// ```
379/// use rtci_interceptor::{NackGeneratorBuilder, Registry, Slot, TwccSenderBuilder};
380///
381/// let chain = Registry::new()
382/// .with(Slot::TwccSender, TwccSenderBuilder::new().build()) // closest to the wire
383/// .with(Slot::NackGenerator, NackGeneratorBuilder::new().build()) // sees arrivals after it
384/// .build(); // terminus appended here
385/// # let _ = chain;
386/// ```
387#[derive(Default)]
388pub struct Registry {
389 interceptors: BTreeMap<Slot, BoxedInterceptor>,
390 /// What each interceptor is called, keyed the same way as `interceptors`.
391 ///
392 /// Kept beside the chain rather than asked of it: `Interceptor` is a trait object by the time
393 /// it is stored, and a trait object cannot say what it used to be. Recording the name at the
394 /// one moment the concrete type is still in hand is the only way to have it later, which is
395 /// also why [`with`](Self::with) takes a concrete interceptor rather than a boxed one.
396 names: BTreeMap<Slot, String>,
397}
398
399/// A type's name without its module paths — `TwccSenderInterceptor`, not
400/// `rtci_interceptor::twcc::sender::TwccSenderInterceptor`.
401///
402/// Every path is shortened, not just the outermost one, so a congestion controller reads as
403/// `CongestionControlInterceptor<Gcc>`. Splitting the whole string on its last `::` would be
404/// simpler and wrong: on a generic type that separator sits inside the *argument*, and
405/// `CongestionControlInterceptor<rtci_interceptor::cc::estimator::ConstantBitrate>` comes back as
406/// `ConstantBitrate>` — the interceptor's own name gone, and a stray bracket left behind.
407///
408/// The generic argument is kept because it is often the only thing telling two interceptors apart:
409/// which estimator a congestion controller carries is the interesting half of its name.
410fn short_type_name<T: ?Sized>() -> String {
411 let full = std::any::type_name::<T>();
412 let mut out = String::with_capacity(full.len());
413 let mut segment = String::new();
414
415 let flush = |segment: &mut String, out: &mut String| {
416 out.push_str(segment.rsplit("::").next().unwrap_or(segment));
417 segment.clear();
418 };
419
420 for ch in full.chars() {
421 // A path segment runs until punctuation that cannot appear in one: `<`, `>`, `,`, a space.
422 if ch.is_alphanumeric() || ch == '_' || ch == ':' {
423 segment.push(ch);
424 } else {
425 flush(&mut segment, &mut out);
426 out.push(ch);
427 }
428 }
429 flush(&mut segment, &mut out);
430
431 out
432}
433
434impl Registry {
435 /// An empty registry.
436 pub fn new() -> Self {
437 Self::default()
438 }
439
440 /// Add an interceptor at `slot`.
441 ///
442 /// Call order does not matter: the slot decides the position. A slot holds one interceptor, so
443 /// adding a second at the same position replaces the first and says so in the log.
444 pub fn with<T: Interceptor + 'static>(mut self, slot: Slot, interceptor: T) -> Self {
445 let name = short_type_name::<T>();
446
447 // One interceptor per slot: the map key is the position. Replacing rather than stacking is
448 // what a map gives, and it is announced rather than done quietly — an interceptor that
449 // vanished because something else claimed its slot is the kind of fault that shows up much
450 // later as "the chain does not do what I configured".
451 if let Some(displaced) = self.names.insert(slot, name.clone()) {
452 warn!("{slot:?} already held {displaced}; {name} replaced it");
453 }
454 self.interceptors.insert(slot, Box::new(interceptor));
455 self
456 }
457
458 /// Add an interceptor that keeps one instance per RTP session ([`PerRtpSession`]) at
459 /// `slot`. [`slots`](Self::slots) names it by the interceptor it holds.
460 ///
461 /// [`PerRtpSession`]: crate::PerRtpSession
462 pub fn with_per_rtp_session<T: Interceptor + 'static>(
463 mut self,
464 slot: Slot,
465 interceptor: crate::PerRtpSession<T>,
466 ) -> Self {
467 let name = short_type_name::<T>();
468 if let Some(displaced) = self.names.insert(slot, name.clone()) {
469 warn!("{slot:?} already held {displaced}; {name} replaced it");
470 }
471 self.interceptors.insert(slot, Box::new(interceptor));
472 self
473 }
474
475 /// What this registry holds, wire-to-application: each interceptor's slot and its type name,
476 /// in the order [`build`](Self::build) will compose them.
477 ///
478 /// Present so a caller assembling a chain from several helpers can assert what it got. Each
479 /// helper places interceptors at its own landmarks and none of them sees the whole, so the
480 /// composition is precisely the thing no single helper can check.
481 pub fn slots(&self) -> Vec<(Slot, String)> {
482 // Already wire-to-application: a `BTreeMap` iterates in key order, and `Slot` orders by
483 // position. This is the order `build` will compose them in, for the same reason.
484 self.names
485 .iter()
486 .map(|(slot, name)| (*slot, name.clone()))
487 .collect()
488 }
489
490 /// Whether an interceptor sits at `slot`.
491 pub fn holds(&self, slot: Slot) -> bool {
492 self.names.contains_key(&slot)
493 }
494
495 /// Assemble the interceptor chain.
496 ///
497 /// [`NoopInterceptor`] is appended last, so every chain ends the inbound RTCP path. That is a
498 /// property of a chain rather than something a caller opts into: left out, an application would
499 /// get a stream of control traffic it never asked for, and the omission would look like working
500 /// code.
501 ///
502 /// What gets past it is decided per packet, by an interceptor attaching
503 /// [`Attribute::DeliverToApplication`](crate::Attribute::DeliverToApplication) to the ones it
504 /// vouches for — the component that knows which packets an application can act on is the one
505 /// that makes the call, rather than a switch here that could only say "all of it or none".
506 pub fn build(self) -> impl Interceptor {
507 // No sort: a `BTreeMap` is already in key order, and `Slot` orders by distance from the
508 // wire, which is the order the chain runs in.
509 let mut interceptors: Vec<BoxedInterceptor> = self.interceptors.into_values().collect();
510
511 interceptors.push(Box::new(NoopInterceptor::new()));
512
513 Chain::new(interceptors)
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520 use crate::StreamInfo;
521 use crate::{AttributedPacket, Packet, TaggedPacket};
522 use sansio::Protocol;
523 use shared::TransportContext;
524 use shared::error::Error;
525 use std::collections::VecDeque;
526 use std::sync::{Arc, Mutex};
527 use std::time::Instant;
528
529 #[derive(Clone, Default)]
530 struct Log(Arc<Mutex<Vec<&'static str>>>);
531
532 struct Marker {
533 name: &'static str,
534 log: Log,
535 read_queue: VecDeque<TaggedPacket>,
536 write_queue: VecDeque<TaggedPacket>,
537 }
538
539 impl Marker {
540 fn new(name: &'static str, log: Log) -> Self {
541 Self {
542 name,
543 log,
544 read_queue: VecDeque::new(),
545 write_queue: VecDeque::new(),
546 }
547 }
548 }
549
550 impl Protocol<TaggedPacket, TaggedPacket, ()> for Marker {
551 type Rout = TaggedPacket;
552 type Wout = TaggedPacket;
553 type Eout = ();
554 type Error = Error;
555 type Time = Instant;
556
557 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
558 self.log.0.lock().unwrap().push(self.name);
559 self.read_queue.push_back(msg);
560 Ok(())
561 }
562
563 fn poll_read(&mut self) -> Option<Self::Rout> {
564 self.read_queue.pop_front()
565 }
566
567 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
568 self.log.0.lock().unwrap().push(self.name);
569 self.write_queue.push_back(msg);
570 Ok(())
571 }
572
573 fn poll_write(&mut self) -> Option<Self::Wout> {
574 self.write_queue.pop_front()
575 }
576
577 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
578 Ok(())
579 }
580
581 fn poll_timeout(&mut self) -> Option<Self::Time> {
582 None
583 }
584 }
585
586 impl Interceptor for Marker {
587 fn bind_local_stream(&mut self, _info: &StreamInfo) {}
588 fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
589 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
590 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
591 }
592
593 fn packet() -> TaggedPacket {
594 TaggedPacket {
595 now: Instant::now(),
596 transport: TransportContext::default(),
597 message: AttributedPacket::new(Packet::Rtp(rtp::Packet::default())),
598 }
599 }
600
601 fn chain(log: &Log) -> impl Interceptor {
602 Registry::new()
603 .with(Slot::TwccSender, Marker::new("wire", log.clone()))
604 .with(Slot::NackGenerator, Marker::new("middle", log.clone()))
605 .with(Slot::JitterBuffer, Marker::new("app", log.clone()))
606 .build()
607 }
608
609 /// Slots decide the order, not the sequence of calls. Adding application-most first must
610 /// compose the same chain as adding wire-most first — the property the helpers in `rtci` rely
611 /// on to be callable in any sequence.
612 #[test]
613 fn call_order_does_not_decide_chain_order() {
614 let log = Log::default();
615 let mut chain = Registry::new()
616 .with(Slot::JitterBuffer, Marker::new("app", log.clone()))
617 .with(Slot::TwccSender, Marker::new("wire", log.clone()))
618 .with(Slot::NackGenerator, Marker::new("middle", log.clone()))
619 .build();
620
621 chain.handle_read(packet()).unwrap();
622 while chain.poll_read().is_some() {}
623
624 assert_eq!(vec!["wire", "middle", "app"], *log.0.lock().unwrap());
625 }
626
627 /// A slot holds one interceptor: adding a second at the same position replaces the first
628 /// rather than stacking with it. Two of your own go at two custom positions, which is what the
629 /// thousand-apart spacing leaves room for.
630 #[test]
631 fn a_slot_holds_one_interceptor() {
632 let log = Log::default();
633 let mut chain = Registry::new()
634 .with(Slot::NackGenerator, Marker::new("first", log.clone()))
635 .with(Slot::NackGenerator, Marker::new("second", log.clone()))
636 .build();
637
638 chain.handle_read(packet()).unwrap();
639 while chain.poll_read().is_some() {}
640
641 assert_eq!(
642 vec!["second"],
643 *log.0.lock().unwrap(),
644 "the later one claimed the slot; the earlier one is not in the chain"
645 );
646 }
647
648 /// Read runs the list forwards: the first interceptor added is closest to the wire.
649 #[test]
650 fn read_runs_in_the_order_stages_were_added() {
651 let log = Log::default();
652 let mut chain = chain(&log);
653
654 chain.handle_read(packet()).unwrap();
655 while chain.poll_read().is_some() {}
656
657 assert_eq!(vec!["wire", "middle", "app"], *log.0.lock().unwrap());
658 }
659
660 /// Write runs it backwards, so the same list describes both directions.
661 #[test]
662 fn write_runs_in_reverse() {
663 let log = Log::default();
664 let mut chain = chain(&log);
665
666 chain.handle_write(packet()).unwrap();
667 while chain.poll_write().is_some() {}
668
669 assert_eq!(vec!["app", "middle", "wire"], *log.0.lock().unwrap());
670 }
671
672 /// Ending the inbound RTCP path is a property of every chain, not something a caller adds.
673 #[test]
674 fn a_registry_with_nothing_added_still_has_the_terminus() {
675 let mut chain = Registry::new().build();
676
677 chain
678 .handle_read(TaggedPacket {
679 now: Instant::now(),
680 transport: TransportContext::default(),
681 message: AttributedPacket::new(Packet::Rtcp(vec![])),
682 })
683 .unwrap();
684 assert!(
685 chain.poll_read().is_none(),
686 "inbound RTCP stops before the application"
687 );
688 }
689
690 /// The terminus goes last, so every interceptor sees inbound RTCP before it is dropped.
691 #[test]
692 fn the_terminus_is_application_most() {
693 let log = Log::default();
694 let mut chain = Registry::new()
695 .with(Slot::TwccSender, Marker::new("wire", log.clone()))
696 .build();
697
698 chain
699 .handle_read(TaggedPacket {
700 now: Instant::now(),
701 transport: TransportContext::default(),
702 message: AttributedPacket::new(Packet::Rtcp(vec![])),
703 })
704 .unwrap();
705
706 assert_eq!(
707 vec!["wire"],
708 *log.0.lock().unwrap(),
709 "the stage saw the RTCP packet; the terminus dropped it afterwards"
710 );
711 assert!(chain.poll_read().is_none());
712 }
713
714 /// An application's own interceptor goes between two named slots, which is what the spacing is
715 /// for: nothing has to be renumbered to make room.
716 #[test]
717 fn a_custom_slot_sits_where_its_number_says() {
718 let log = Log::default();
719 let mut chain = Registry::new()
720 .with(Slot::FecDecoder, Marker::new("fec", log.clone()))
721 .with(Slot::NackGenerator, Marker::new("nack", log.clone()))
722 .with(Slot::from(10_450), Marker::new("mine", log.clone()))
723 .build();
724
725 chain.handle_read(packet()).unwrap();
726 while chain.poll_read().is_some() {}
727
728 assert_eq!(
729 vec!["fec", "mine", "nack"],
730 *log.0.lock().unwrap(),
731 "10_450 belongs after the FEC decoder at 10_300 and before the NACK generator at 10_600"
732 );
733 }
734
735 /// A custom slot naming a named slot's position *is* that slot. Equality and ordering both come
736 /// from the position, and they have to agree: a pair that compares `Equal` must also be `==`,
737 /// or a sort or a `BTreeMap` keyed on this behaves differently depending on which spelling the
738 /// caller reached for.
739 #[test]
740 fn equality_and_ordering_both_follow_the_position() {
741 assert_eq!(Slot::TwccSender, Slot::from(2_000));
742 assert_eq!(
743 std::cmp::Ordering::Equal,
744 Slot::TwccSender.cmp(&Slot::from(2_000))
745 );
746 assert!(Slot::from(1_500) > Slot::CongestionControl);
747 assert!(Slot::from(1_500) < Slot::TwccSender);
748 assert!(
749 Slot::from(20_000) > Slot::JitterBuffer,
750 "a position past every named slot sorts past them, not by declaration order"
751 );
752 }
753
754 /// The named slots keep room between them, so `Slot::from` has somewhere to aim, and they are
755 /// in the order the chain contract gives.
756 #[test]
757 fn the_named_slots_are_in_contract_order_with_room_between() {
758 let named = [
759 Slot::CongestionControl,
760 Slot::FecWireImage,
761 Slot::TwccSender,
762 Slot::CircuitBreaker,
763 Slot::Pacer,
764 Slot::NackResponder,
765 Slot::FecEncoder,
766 Slot::TwccReceiver,
767 Slot::Rfc8888,
768 Slot::ReceiverReport,
769 Slot::FecDecoder,
770 Slot::NackGenerator,
771 Slot::SenderReport,
772 Slot::IntervalPli,
773 Slot::JitterBuffer,
774 Slot::KeyFrameRequests,
775 ];
776
777 for pair in named.windows(2) {
778 assert!(
779 pair[1].slot() >= pair[0].slot() + 300,
780 "{:?} and {:?} must stay in order with room for a custom slot between",
781 pair[0],
782 pair[1]
783 );
784 }
785 }
786
787 /// A registry records what each interceptor is called, which a chain of trait objects could not
788 /// tell you afterwards. It is what makes a composed chain inspectable — several helpers each
789 /// place interceptors at their own landmarks, and this is the only view of the result.
790 #[test]
791 fn slots_carry_the_interceptor_names() {
792 let log = Log::default();
793 let registry = Registry::new()
794 .with(Slot::JitterBuffer, Marker::new("app", log.clone()))
795 .with(Slot::TwccSender, crate::TwccSenderBuilder::new().build());
796
797 assert_eq!(
798 vec![
799 (Slot::TwccSender, "TwccSenderInterceptor".to_owned()),
800 (Slot::JitterBuffer, "Marker".to_owned()),
801 ],
802 registry.slots(),
803 "names come back with their slots, sorted wire-to-application"
804 );
805 }
806
807 /// The module path is dropped: a name is for reading, and the full path is mostly the crate's
808 /// own directory layout.
809 #[test]
810 fn names_are_stripped_of_their_module_path() {
811 let registry = Registry::new().with(
812 Slot::CongestionControl,
813 crate::CongestionControlBuilder::new(crate::ConstantBitrate::new(1_000_000.0)).build(),
814 );
815
816 let (_, name) = ®istry.slots()[0];
817 assert!(
818 !name.contains("::"),
819 "a module path leaked into the name: {name}"
820 );
821 assert_eq!(
822 "CongestionControlInterceptor<ConstantBitrate>", name,
823 "the generic argument is shortened too, and kept — it is what tells two \
824 congestion controllers apart"
825 );
826 }
827}