rtci_interceptor/twcc/receiver.rs
1//! TWCC Receiver Interceptor - tracks incoming packets and generates feedback.
2
3use super::recorder::Recorder;
4use super::{flow_ssrcs, stream_supports_twcc};
5use crate::Interceptor;
6use crate::cc::feedback::{CongestionFeedbackFormat, negotiated_congestion_feedback};
7use crate::cc::feedback_cadence::{CongestionFeedbackCadence, FeedbackCadence};
8use crate::stream_info::StreamInfo;
9use crate::{AttributedPacket, Packet, TaggedPacket};
10use sansio::Protocol;
11use shared::TransportContext;
12use shared::error::Error;
13use shared::marshal::Unmarshal;
14use std::collections::{HashMap, HashSet, VecDeque};
15use std::time::{Duration, Instant};
16
17/// Default interval for sending TWCC feedback.
18const DEFAULT_INTERVAL: Duration = Duration::from_millis(100);
19
20/// Builder for the TwccReceiverInterceptor.
21///
22/// # Example
23///
24/// ```
25/// use rtci_interceptor::{Slot, Registry, TwccReceiverBuilder};
26/// use std::time::Duration;
27///
28/// let chain = Registry::new()
29/// .with(Slot::TwccReceiver, TwccReceiverBuilder::new()
30/// .with_interval(Duration::from_millis(100))
31/// .build())
32/// .build();
33/// ```
34pub struct TwccReceiverBuilder {
35 /// Interval between feedback reports.
36 interval: Duration,
37 /// Whether the interval follows [`Self::with_cadence`] (or is fixed).
38 adaptive_interval: bool,
39 /// See [`Self::with_cadence`].
40 cadence: CongestionFeedbackCadence,
41 /// Whether packets already reported received are reported again (libwebrtc).
42 rereport_received: bool,
43 /// See [`Self::with_feedback_share`].
44 feedback_share: f64,
45 /// See [`Self::with_max_adaptive_interval`].
46 max_adaptive_interval: Duration,
47 /// Whether the header extension alone, without `transport-cc` feedback, makes a stream
48 /// reported.
49 extension_alone: bool,
50 /// See [`Self::with_stability_stretch`].
51 stability_stretch: bool,
52}
53
54impl Default for TwccReceiverBuilder {
55 fn default() -> Self {
56 Self {
57 interval: DEFAULT_INTERVAL,
58 adaptive_interval: true,
59 cadence: CongestionFeedbackCadence::default(),
60 feedback_share: crate::cc::feedback_cadence::FEEDBACK_SHARE,
61 max_adaptive_interval: crate::cc::feedback_cadence::MAX_ADAPTIVE_INTERVAL,
62 rereport_received: false,
63 extension_alone: false,
64 stability_stretch: false,
65 }
66 }
67}
68
69impl TwccReceiverBuilder {
70 /// Create a new builder with default settings.
71 pub fn new() -> Self {
72 Self::default()
73 }
74
75 /// Set the interval between feedback reports.
76 pub fn with_interval(mut self, interval: Duration) -> Self {
77 self.interval = interval;
78 self
79 }
80
81 /// Whether the interval follows the cadence ([`Self::with_cadence`]: by default 50 to
82 /// 250 ms, sized to 5% of the media received) or stays fixed at [`Self::with_interval`]
83 /// (`false`). On by default.
84 pub fn with_adaptive_interval(mut self, adaptive_interval: bool) -> Self {
85 self.adaptive_interval = adaptive_interval;
86 self
87 }
88
89 /// When feedback is built while the interval is not fixed: see
90 /// [`CongestionFeedbackCadence`]. Default [`CongestionFeedbackCadence::ReceivedMedia`],
91 /// the engine's own form, which no specification has. The drafts' form is
92 /// [`CongestionFeedbackCadence::PerFrame`]
93 /// (draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3, "It is recommended that
94 /// a feedback message is sent for every frame received, but in cases of low uplink
95 /// bandwidth it is acceptable to send them less frequently", with
96 /// draft-ietf-rmcat-gcc-02 section 3's intervals: 30 ms, up to 100 ms): measured worse as
97 /// the default, it is the `StrictRfc` behaviour profile's.
98 pub fn with_cadence(mut self, cadence: CongestionFeedbackCadence) -> Self {
99 self.cadence = cadence;
100 self
101 }
102
103 /// The share of the rate it is sized to that the feedback may take with
104 /// [`CongestionFeedbackCadence::SendEstimate`] (of the send estimate) and
105 /// [`CongestionFeedbackCadence::ReceivedMedia`] (of the media received): the interval is
106 /// the time in which this share holds one feedback packet. Default 0.05 (libwebrtc: "Let
107 /// TWCC reports occupy 5% of total bandwidth"); the `Performance` behaviour profile
108 /// takes 0.025. [`CongestionFeedbackCadence::PerFrame`] does not use it.
109 pub fn with_feedback_share(mut self, share: f64) -> Self {
110 self.feedback_share = share;
111 self
112 }
113
114 /// The longest interval of [`CongestionFeedbackCadence::SendEstimate`] and
115 /// [`CongestionFeedbackCadence::ReceivedMedia`] while media flows. Default 250 ms
116 /// (libwebrtc's `kMaxInterval`); the `Performance` behaviour profile takes 500 ms.
117 /// [`CongestionFeedbackCadence::PerFrame`] has the draft's own ceiling, 100 ms.
118 pub fn with_max_adaptive_interval(mut self, max_interval: Duration) -> Self {
119 self.max_adaptive_interval = max_interval;
120 self
121 }
122
123 /// Whether a packet an earlier feedback message reported as received is reported as
124 /// received again when a late packet moves the base sequence number back over it, as
125 /// libwebrtc does. Off by default: draft-holmer-rmcat-transport-wide-cc-extensions-01
126 /// section 3.1.1 has such packets marked "Packet not received", with no delta. A
127 /// libwebrtc sender drops a packet from its history once it is reported received, so it
128 /// ignores the later "not received" either way.
129 pub fn with_rereport_received(mut self, rereport_received: bool) -> Self {
130 self.rereport_received = rereport_received;
131 self
132 }
133
134 /// Whether a remote stream whose packets carry the transport-wide sequence number header
135 /// extension is reported on although `a=rtcp-fb:<pt> transport-cc` was not negotiated for
136 /// it. Off by default: the feedback is an RTCP feedback message, sent only where the
137 /// session negotiated it (RFC 4585 section 4.2: "MUST NOT" use feedback other than the
138 /// listed types), and libwebrtc too reports only when the feedback is negotiated beside
139 /// the extension. On is the fork's earlier behaviour, for a peer that signals the
140 /// extension alone.
141 pub fn with_feedback_on_extension_alone(mut self, extension_alone: bool) -> Self {
142 self.extension_alone = extension_alone;
143 self
144 }
145
146 /// RFC 8836 section 2, requirement 8c ("In areas of stability, backchannel data may be
147 /// sent more infrequently ... When the channel is unstable ... more frequent"): while the
148 /// path reads stable (no packet missing and the interarrival jitter of every reported
149 /// stream under [`STABLE_JITTER`](crate::STABLE_FEEDBACK_JITTER) for
150 /// [`STABLE_REPORTS`](crate::STABLE_FEEDBACK_REPORTS) reports in a row), the adaptive
151 /// interval is twice what the cadence gives, up to 500 ms; a loss or the jitter rising
152 /// brings it back at once. Off by default: no cadence change becomes the default without a
153 /// capacity-instrument measurement (`DefaultInterceptorOptions::congestion_feedback_stretch_when_stable`).
154 pub fn with_stability_stretch(mut self, stretch: bool) -> Self {
155 self.stability_stretch = stretch;
156 self
157 }
158
159 /// Build the interceptor.
160 pub fn build(self) -> TwccReceiverInterceptor {
161 let mut interceptor = TwccReceiverInterceptor::new(self.interval, self.adaptive_interval);
162 interceptor.cadence = FeedbackCadence::new(self.interval, self.adaptive_interval)
163 .with_form(self.cadence)
164 .with_limits(self.feedback_share, self.max_adaptive_interval)
165 .with_stability_stretch(self.stability_stretch);
166 interceptor.rereport_received = self.rereport_received;
167 interceptor.extension_alone = self.extension_alone;
168 interceptor
169 }
170}
171
172/// Per-stream state for the receiver.
173struct RemoteStream {
174 /// Header extension ID for transport-wide CC.
175 hdr_ext_id: u8,
176}
177
178/// Interceptor that tracks incoming RTP packets and generates TWCC feedback.
179///
180/// This interceptor examines incoming RTP packets for transport-wide CC sequence
181/// numbers and periodically generates TransportLayerCC feedback packets.
182pub struct TwccReceiverInterceptor {
183 /// When feedback is built ([`TwccReceiverBuilder::with_cadence`]).
184 cadence: FeedbackCadence,
185
186 /// Start time for calculating arrival times.
187 start_time: Option<Instant>,
188
189 /// TWCC recorder for building feedback.
190 recorder: Option<Recorder>,
191
192 /// Remote stream state per SSRC.
193 streams: HashMap<u32, RemoteStream>,
194
195 /// SSRCs of streams whose feedback is RFC 8888: never reported here, even when their
196 /// packets carry a transport-wide sequence number (RFC 8888 section 6).
197 rfc8888_ssrcs: HashSet<u32>,
198
199 /// Transport-wide CC header extension ID negotiated on this transport.
200 ///
201 /// Transport-wide congestion control is per *transport*, not per SSRC: the feedback
202 /// must account for every packet that carried the transport-cc sequence extension,
203 /// whatever SSRC it rode on. Packets can legitimately arrive on SSRCs that have no
204 /// stream binding - RTX/probe padding and RID simulcast layers before they are bound -
205 /// and omitting them makes the remote congestion controller read them as lost. This ID
206 /// is used as the fallback for those unbound SSRCs.
207 transport_hdr_ext_id: Option<u8>,
208
209 /// Queue for feedback packets.
210 write_queue: VecDeque<TaggedPacket>,
211
212 /// Next timeout for sending feedback.
213 next_timeout: Option<Instant>,
214 /// Inbound packets ready for the next interceptor.
215 read_queue: VecDeque<TaggedPacket>,
216 /// See [`TwccReceiverBuilder::with_rereport_received`].
217 rereport_received: bool,
218 /// See [`TwccReceiverBuilder::with_feedback_on_extension_alone`].
219 extension_alone: bool,
220}
221
222impl TwccReceiverInterceptor {
223 fn new(interval: Duration, adaptive_interval: bool) -> Self {
224 Self {
225 read_queue: VecDeque::new(),
226 cadence: FeedbackCadence::new(interval, adaptive_interval),
227 start_time: None,
228 recorder: None,
229 streams: HashMap::new(),
230 rfc8888_ssrcs: HashSet::new(),
231 transport_hdr_ext_id: None,
232 write_queue: VecDeque::new(),
233 rereport_received: false,
234 extension_alone: false,
235 next_timeout: None,
236 }
237 }
238
239 fn generate_feedback(&mut self, now: Instant) {
240 self.cadence.reported(now);
241 let Some(recorder) = self.recorder.as_mut() else {
242 return;
243 };
244
245 let packets = recorder.build_feedback_packet();
246 for pkt in packets {
247 self.cadence.on_feedback(pkt.marshal_size());
248 self.write_queue.push_back(TaggedPacket {
249 now,
250 transport: TransportContext::default(),
251 message: AttributedPacket::new(Packet::Rtcp(vec![pkt])),
252 });
253 }
254 }
255}
256
257impl Protocol<TaggedPacket, TaggedPacket, ()> for TwccReceiverInterceptor {
258 type Rout = TaggedPacket;
259 type Wout = TaggedPacket;
260 type Eout = ();
261 type Error = Error;
262 type Time = Instant;
263
264 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
265 // Whether this packet ends a frame the cadence reports at once (per-frame feedback).
266 let frame_ended = self.cadence.on_packet(&msg);
267 // A report scheduled with a stretched interval is due sooner once the path stops
268 // reading stable (RFC 8836 section 2, requirement 8c).
269 if let (Some(due), Some(next)) =
270 (self.cadence.stretched_deadline(msg.now), self.next_timeout)
271 && due < next
272 {
273 self.next_timeout = Some(due.max(msg.now));
274 }
275 // Process incoming RTP packets with TWCC extension
276 if let Packet::Rtp(ref rtp_packet) = msg.message.packet
277 && !self.rfc8888_ssrcs.contains(&rtp_packet.header.ssrc)
278 {
279 // Prefer the ID bound for this SSRC, and fall back to the transport-wide one so
280 // that padding and not-yet-bound streams still make it into the feedback.
281 let hdr_ext_id = self
282 .streams
283 .get(&rtp_packet.header.ssrc)
284 .map(|stream| stream.hdr_ext_id)
285 .or(self.transport_hdr_ext_id);
286
287 // Extract transport CC sequence number
288 if let Some(hdr_ext_id) = hdr_ext_id
289 && let Some(ext_data) = rtp_packet.header.get_extension(hdr_ext_id)
290 && let Ok(tcc) =
291 rtp::extension::transport_cc_extension::TransportCcExtension::unmarshal(
292 &mut ext_data.as_ref(),
293 )
294 {
295 // Initialize recorder on the first packet carrying transport-wide CC
296 if self.recorder.is_none() {
297 // Use a random sender SSRC for feedback
298 self.recorder = Some(
299 Recorder::new(rand::random())
300 .with_rereport_received(self.rereport_received),
301 );
302 self.start_time = Some(msg.now);
303 self.next_timeout = Some(msg.now + self.cadence.interval(msg.now));
304 }
305
306 // Calculate arrival time in microseconds since start
307 let arrival_time = self
308 .start_time
309 .map(|start| msg.now.duration_since(start).as_micros() as i64)
310 .unwrap_or(0);
311
312 if let Some(recorder) = self.recorder.as_mut() {
313 recorder.record(rtp_packet.header.ssrc, tcc.transport_sequence, arrival_time);
314 }
315 if frame_ended {
316 self.generate_feedback(msg.now);
317 self.next_timeout = Some(msg.now + self.cadence.interval(msg.now));
318 }
319 }
320 }
321
322 self.read_queue.push_back(msg);
323
324 Ok(())
325 }
326
327 fn poll_read(&mut self) -> Option<Self::Rout> {
328 self.read_queue.pop_front()
329 }
330
331 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
332 // The media this endpoint sends is part of the session bandwidth, and what the RTCP
333 // session is told about its bandwidth passes here on its way to it.
334 self.cadence.on_write(&msg);
335 self.write_queue.push_back(msg);
336 Ok(())
337 }
338
339 fn poll_write(&mut self) -> Option<TaggedPacket> {
340 // First drain feedback packets
341 if let Some(pkt) = self.write_queue.pop_front() {
342 return Some(pkt);
343 }
344 None
345 }
346
347 fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
348 // Check if we need to send feedback
349 if let Some(timeout) = self.next_timeout
350 && now >= timeout
351 {
352 self.generate_feedback(now);
353 self.next_timeout = Some(now + self.cadence.interval(now));
354 }
355 Ok(())
356 }
357
358 fn poll_timeout(&mut self) -> Option<Instant> {
359 self.next_timeout
360 }
361}
362
363impl Interceptor for TwccReceiverInterceptor {
364 fn bind_remote_stream(&mut self, info: &StreamInfo) {
365 // One feedback mechanism per stream: a stream that negotiated RFC 8888 is reported by
366 // the RFC 8888 recorder and not here as well.
367 if negotiated_congestion_feedback(info) == Some(CongestionFeedbackFormat::Rfc8888) {
368 self.rfc8888_ssrcs.extend(flow_ssrcs(info));
369 self.streams.remove(&info.ssrc);
370 self.cadence.unbind_remote(info);
371 return;
372 }
373 for ssrc in flow_ssrcs(info) {
374 self.rfc8888_ssrcs.remove(&ssrc);
375 }
376 // draft-holmer-rmcat-transport-wide-cc-extensions-01 section 2.3 / RFC 4585 section
377 // 4.2: the feedback is sent where `transport-cc` was negotiated, not on the header
378 // extension alone.
379 let feedback_negotiated = self.extension_alone
380 || info
381 .rtcp_feedback
382 .iter()
383 .any(|fb| fb.typ == "transport-cc" && fb.parameter.is_empty());
384 if feedback_negotiated && let Some(hdr_ext_id) = stream_supports_twcc(info) {
385 // Don't track if ID is 0 (invalid)
386 if hdr_ext_id != 0 {
387 self.streams.insert(info.ssrc, RemoteStream { hdr_ext_id });
388 self.cadence.bind_remote(info);
389 // An extension ID maps to exactly one URI within an RTP session, and BUNDLE
390 // makes the bundled m-lines one session, so every binding here carries the
391 // same transport-cc ID: taking the newest is taking the only one. A genuinely
392 // different ID means renegotiation, where the newest is also what we want.
393 self.transport_hdr_ext_id = Some(hdr_ext_id);
394 }
395 }
396 }
397
398 fn unbind_remote_stream(&mut self, info: &StreamInfo) {
399 for ssrc in flow_ssrcs(info) {
400 self.rfc8888_ssrcs.remove(&ssrc);
401 }
402 self.streams.remove(&info.ssrc);
403 self.cadence.unbind_remote(info);
404 // Any binding that remains carries the same ID (see `bind_remote_stream`), so only the
405 // loss of the last one leaves no negotiated ID to fall back on. Dropping it then keeps
406 // a stale ID from outliving the negotiation and being misread as transport-cc.
407 if self.streams.is_empty() {
408 self.transport_hdr_ext_id = None;
409 }
410 }
411
412 fn bind_local_stream(&mut self, _info: &StreamInfo) {}
413
414 fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
415}