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::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 stretches to what the RTCP bandwidth allows.
38 adaptive_interval: bool,
39 /// Whether packets already reported received are reported again (libwebrtc).
40 rereport_received: bool,
41 /// See [`Self::with_feedback_share`].
42 feedback_share: f64,
43 /// See [`Self::with_max_adaptive_interval`].
44 max_adaptive_interval: Duration,
45 /// Whether the header extension alone, without `transport-cc` feedback, makes a stream
46 /// reported.
47 extension_alone: bool,
48}
49
50impl Default for TwccReceiverBuilder {
51 fn default() -> Self {
52 Self {
53 interval: DEFAULT_INTERVAL,
54 adaptive_interval: true,
55 feedback_share: crate::cc::feedback_cadence::FEEDBACK_SHARE,
56 max_adaptive_interval: crate::cc::feedback_cadence::MAX_ADAPTIVE_INTERVAL,
57 rereport_received: false,
58 extension_alone: false,
59 }
60 }
61}
62
63impl TwccReceiverBuilder {
64 /// Create a new builder with default settings.
65 pub fn new() -> Self {
66 Self::default()
67 }
68
69 /// Set the interval between feedback reports.
70 pub fn with_interval(mut self, interval: Duration) -> Self {
71 self.interval = interval;
72 self
73 }
74
75 /// Whether the interval stretches to what the RTCP bandwidth holds one feedback packet
76 /// in. On by default.
77 ///
78 /// All RTCP of an endpoint shares 5% of the session bandwidth (RFC 3550 section 6.2,
79 /// unless `b=RS` / `b=RR` say otherwise), and the RTCP session sends no more than that.
80 /// At low media rates a tenth of a second of it does not hold a feedback packet, so
81 /// feedback built every 100 ms queues in the session and reaches the sender late or not
82 /// at all. With this on, the interval is the configured one where the bandwidth allows
83 /// it and longer where it does not, up to half a second ("with low uplink bandwidth
84 /// feedback may be sent less often", section 3 of the draft): one feedback packet for
85 /// every RTCP packet the session may send, each covering everything since the last.
86 /// `false` keeps the interval fixed.
87 pub fn with_adaptive_interval(mut self, adaptive_interval: bool) -> Self {
88 self.adaptive_interval = adaptive_interval;
89 self
90 }
91
92 /// The share of the media received that the feedback may take while the interval is
93 /// adaptive: the interval is the time in which this share holds one feedback packet (with
94 /// its lower layers, and the minimal compound packet around it without reduced-size
95 /// RTCP). Default 0.05, RFC 3550 section 6.2's 5% for all of RTCP. A smaller share leaves
96 /// room in the 5% for the regular reports (the `Performance` behaviour profile: 0.025).
97 pub fn with_feedback_share(mut self, share: f64) -> Self {
98 self.feedback_share = share;
99 self
100 }
101
102 /// The longest the adaptive interval stretches to while media flows. Default 250 ms.
103 /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3: "in cases of low uplink
104 /// bandwidth it is acceptable to send them less frequently, e.g., for instance once per
105 /// RTT"; RFC 8888 section 4 leaves the interval to the application ("Applications need to
106 /// negotiate an appropriate congestion control feedback interval ... based on ... the
107 /// acceptable feedback overhead"). The `Performance` behaviour profile takes 500 ms.
108 pub fn with_max_adaptive_interval(mut self, max_interval: Duration) -> Self {
109 self.max_adaptive_interval = max_interval;
110 self
111 }
112
113 /// Whether a packet an earlier feedback message reported as received is reported as
114 /// received again when a late packet moves the base sequence number back over it, as
115 /// libwebrtc does. Off by default: draft-holmer-rmcat-transport-wide-cc-extensions-01
116 /// section 3.1.1 has such packets marked "Packet not received", with no delta. A
117 /// libwebrtc sender drops a packet from its history once it is reported received, so it
118 /// ignores the later "not received" either way.
119 pub fn with_rereport_received(mut self, rereport_received: bool) -> Self {
120 self.rereport_received = rereport_received;
121 self
122 }
123
124 /// Whether a remote stream whose packets carry the transport-wide sequence number header
125 /// extension is reported on although `a=rtcp-fb:<pt> transport-cc` was not negotiated for
126 /// it. Off by default: the feedback is an RTCP feedback message, sent only where the
127 /// session negotiated it (RFC 4585 section 4.2: "MUST NOT" use feedback other than the
128 /// listed types), and libwebrtc too reports only when the feedback is negotiated beside
129 /// the extension. On is the fork's earlier behaviour, for a peer that signals the
130 /// extension alone.
131 pub fn with_feedback_on_extension_alone(mut self, extension_alone: bool) -> Self {
132 self.extension_alone = extension_alone;
133 self
134 }
135
136 /// Build the interceptor.
137 pub fn build(self) -> TwccReceiverInterceptor {
138 let mut interceptor = TwccReceiverInterceptor::new(self.interval, self.adaptive_interval);
139 interceptor.cadence = FeedbackCadence::new(self.interval, self.adaptive_interval)
140 .with_limits(self.feedback_share, self.max_adaptive_interval);
141 interceptor.rereport_received = self.rereport_received;
142 interceptor.extension_alone = self.extension_alone;
143 interceptor
144 }
145}
146
147/// Per-stream state for the receiver.
148struct RemoteStream {
149 /// Header extension ID for transport-wide CC.
150 hdr_ext_id: u8,
151}
152
153/// Interceptor that tracks incoming RTP packets and generates TWCC feedback.
154///
155/// This interceptor examines incoming RTP packets for transport-wide CC sequence
156/// numbers and periodically generates TransportLayerCC feedback packets.
157pub struct TwccReceiverInterceptor {
158 /// When feedback is built: the configured interval, stretched to the RTCP bandwidth.
159 cadence: FeedbackCadence,
160
161 /// Start time for calculating arrival times.
162 start_time: Option<Instant>,
163
164 /// TWCC recorder for building feedback.
165 recorder: Option<Recorder>,
166
167 /// Remote stream state per SSRC.
168 streams: HashMap<u32, RemoteStream>,
169
170 /// SSRCs of streams whose feedback is RFC 8888: never reported here, even when their
171 /// packets carry a transport-wide sequence number (RFC 8888 section 6).
172 rfc8888_ssrcs: HashSet<u32>,
173
174 /// Transport-wide CC header extension ID negotiated on this transport.
175 ///
176 /// Transport-wide congestion control is per *transport*, not per SSRC: the feedback
177 /// must account for every packet that carried the transport-cc sequence extension,
178 /// whatever SSRC it rode on. Packets can legitimately arrive on SSRCs that have no
179 /// stream binding - RTX/probe padding and RID simulcast layers before they are bound -
180 /// and omitting them makes the remote congestion controller read them as lost. This ID
181 /// is used as the fallback for those unbound SSRCs.
182 transport_hdr_ext_id: Option<u8>,
183
184 /// Queue for feedback packets.
185 write_queue: VecDeque<TaggedPacket>,
186
187 /// Next timeout for sending feedback.
188 next_timeout: Option<Instant>,
189 /// Inbound packets ready for the next interceptor.
190 read_queue: VecDeque<TaggedPacket>,
191 /// See [`TwccReceiverBuilder::with_rereport_received`].
192 rereport_received: bool,
193 /// See [`TwccReceiverBuilder::with_feedback_on_extension_alone`].
194 extension_alone: bool,
195}
196
197impl TwccReceiverInterceptor {
198 fn new(interval: Duration, adaptive_interval: bool) -> Self {
199 Self {
200 read_queue: VecDeque::new(),
201 cadence: FeedbackCadence::new(interval, adaptive_interval),
202 start_time: None,
203 recorder: None,
204 streams: HashMap::new(),
205 rfc8888_ssrcs: HashSet::new(),
206 transport_hdr_ext_id: None,
207 write_queue: VecDeque::new(),
208 rereport_received: false,
209 extension_alone: false,
210 next_timeout: None,
211 }
212 }
213
214 fn generate_feedback(&mut self, now: Instant) {
215 let Some(recorder) = self.recorder.as_mut() else {
216 return;
217 };
218
219 let packets = recorder.build_feedback_packet();
220 for pkt in packets {
221 self.cadence.on_feedback(pkt.marshal_size());
222 self.write_queue.push_back(TaggedPacket {
223 now,
224 transport: TransportContext::default(),
225 message: AttributedPacket::new(Packet::Rtcp(vec![pkt])),
226 });
227 }
228 }
229}
230
231impl Protocol<TaggedPacket, TaggedPacket, ()> for TwccReceiverInterceptor {
232 type Rout = TaggedPacket;
233 type Wout = TaggedPacket;
234 type Eout = ();
235 type Error = Error;
236 type Time = Instant;
237
238 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
239 self.cadence.on_packet(&msg);
240 // Process incoming RTP packets with TWCC extension
241 if let Packet::Rtp(ref rtp_packet) = msg.message.packet
242 && !self.rfc8888_ssrcs.contains(&rtp_packet.header.ssrc)
243 {
244 // Prefer the ID bound for this SSRC, and fall back to the transport-wide one so
245 // that padding and not-yet-bound streams still make it into the feedback.
246 let hdr_ext_id = self
247 .streams
248 .get(&rtp_packet.header.ssrc)
249 .map(|stream| stream.hdr_ext_id)
250 .or(self.transport_hdr_ext_id);
251
252 // Extract transport CC sequence number
253 if let Some(hdr_ext_id) = hdr_ext_id
254 && let Some(ext_data) = rtp_packet.header.get_extension(hdr_ext_id)
255 && let Ok(tcc) =
256 rtp::extension::transport_cc_extension::TransportCcExtension::unmarshal(
257 &mut ext_data.as_ref(),
258 )
259 {
260 // Initialize recorder on the first packet carrying transport-wide CC
261 if self.recorder.is_none() {
262 // Use a random sender SSRC for feedback
263 self.recorder = Some(
264 Recorder::new(rand::random())
265 .with_rereport_received(self.rereport_received),
266 );
267 self.start_time = Some(msg.now);
268 self.next_timeout = Some(msg.now + self.cadence.interval(msg.now));
269 }
270
271 // Calculate arrival time in microseconds since start
272 let arrival_time = self
273 .start_time
274 .map(|start| msg.now.duration_since(start).as_micros() as i64)
275 .unwrap_or(0);
276
277 if let Some(recorder) = self.recorder.as_mut() {
278 recorder.record(rtp_packet.header.ssrc, tcc.transport_sequence, arrival_time);
279 }
280 }
281 }
282
283 self.read_queue.push_back(msg);
284
285 Ok(())
286 }
287
288 fn poll_read(&mut self) -> Option<Self::Rout> {
289 self.read_queue.pop_front()
290 }
291
292 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
293 // The media this endpoint sends is part of the session bandwidth, and what the RTCP
294 // session is told about its bandwidth passes here on its way to it.
295 self.cadence.on_write(&msg);
296 self.write_queue.push_back(msg);
297 Ok(())
298 }
299
300 fn poll_write(&mut self) -> Option<TaggedPacket> {
301 // First drain feedback packets
302 if let Some(pkt) = self.write_queue.pop_front() {
303 return Some(pkt);
304 }
305 None
306 }
307
308 fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
309 // Check if we need to send feedback
310 if let Some(timeout) = self.next_timeout
311 && now >= timeout
312 {
313 self.generate_feedback(now);
314 self.next_timeout = Some(now + self.cadence.interval(now));
315 }
316 Ok(())
317 }
318
319 fn poll_timeout(&mut self) -> Option<Instant> {
320 self.next_timeout
321 }
322}
323
324impl Interceptor for TwccReceiverInterceptor {
325 fn bind_remote_stream(&mut self, info: &StreamInfo) {
326 // One feedback mechanism per stream: a stream that negotiated RFC 8888 is reported by
327 // the RFC 8888 recorder and not here as well.
328 if negotiated_congestion_feedback(info) == Some(CongestionFeedbackFormat::Rfc8888) {
329 self.rfc8888_ssrcs.extend(flow_ssrcs(info));
330 self.streams.remove(&info.ssrc);
331 return;
332 }
333 for ssrc in flow_ssrcs(info) {
334 self.rfc8888_ssrcs.remove(&ssrc);
335 }
336 // draft-holmer-rmcat-transport-wide-cc-extensions-01 section 2.3 / RFC 4585 section
337 // 4.2: the feedback is sent where `transport-cc` was negotiated, not on the header
338 // extension alone.
339 let feedback_negotiated = self.extension_alone
340 || info
341 .rtcp_feedback
342 .iter()
343 .any(|fb| fb.typ == "transport-cc" && fb.parameter.is_empty());
344 if feedback_negotiated && let Some(hdr_ext_id) = stream_supports_twcc(info) {
345 // Don't track if ID is 0 (invalid)
346 if hdr_ext_id != 0 {
347 self.streams.insert(info.ssrc, RemoteStream { hdr_ext_id });
348 // An extension ID maps to exactly one URI within an RTP session, and BUNDLE
349 // makes the bundled m-lines one session, so every binding here carries the
350 // same transport-cc ID: taking the newest is taking the only one. A genuinely
351 // different ID means renegotiation, where the newest is also what we want.
352 self.transport_hdr_ext_id = Some(hdr_ext_id);
353 }
354 }
355 }
356
357 fn unbind_remote_stream(&mut self, info: &StreamInfo) {
358 for ssrc in flow_ssrcs(info) {
359 self.rfc8888_ssrcs.remove(&ssrc);
360 }
361 self.streams.remove(&info.ssrc);
362 // Any binding that remains carries the same ID (see `bind_remote_stream`), so only the
363 // loss of the last one leaves no negotiated ID to fall back on. Dropping it then keeps
364 // a stale ID from outliving the negotiation and being misread as transport-cc.
365 if self.streams.is_empty() {
366 self.transport_hdr_ext_id = None;
367 }
368 }
369
370 fn bind_local_stream(&mut self, _info: &StreamInfo) {}
371
372 fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
373}