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