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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Send-side FlexFEC draft-03: protects outgoing media with repair packets.
use super::encoder::FlexFec03Encoder;
use crate::Interceptor;
use crate::cc::fec_rate::FecRate;
use crate::cc::probe::{
FEC_PROBE_FILLER_ANNOUNCE_INTERVAL, FEC_PROBE_MAX_REPAIR_PACKETS, FEC_PROBE_SOURCE_PACKETS,
};
use crate::stream_info::StreamInfo;
use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
use sansio::Protocol;
use shared::error::Error;
use shared::marshal::MarshalSize;
use std::collections::{HashMap, VecDeque};
use std::time::Instant;
/// Media packets gathered before a repair block is produced.
pub const DEFAULT_NUM_MEDIA_PACKETS: u32 = 5;
/// Repair packets produced per block.
pub const DEFAULT_NUM_FEC_PACKETS: u32 = 2;
/// Builder for [`FlexFec03SendInterceptor`].
///
/// # Example
///
/// ```
/// use rtci_interceptor::{Slot, FlexFec03SendBuilder, Registry};
///
/// let mut fec = FlexFec03SendBuilder::new().with_num_fec_packets(1).build();
/// // The encoder protects the packets as they leave: see `wire_tap`.
/// let tap = fec.wire_tap();
/// let chain = Registry::new()
/// .with(Slot::FecEncoder, fec)
/// .with(Slot::FecWireImage, tap)
/// .build();
/// ```
pub struct FlexFec03SendBuilder {
num_media_packets: u32,
num_fec_packets: u32,
adaptive_rate: bool,
initial_sequence_number: Option<u16>,
initial_timestamp: Option<u32>,
latency_budget: Option<std::time::Duration>,
base_layer_only: bool,
source_rate_first: bool,
probe_fill: bool,
}
impl Default for FlexFec03SendBuilder {
fn default() -> Self {
Self {
num_media_packets: DEFAULT_NUM_MEDIA_PACKETS,
num_fec_packets: DEFAULT_NUM_FEC_PACKETS,
adaptive_rate: true,
initial_sequence_number: None,
initial_timestamp: None,
latency_budget: Some(crate::FEC_DEFAULT_LATENCY_BUDGET),
base_layer_only: true,
source_rate_first: true,
probe_fill: true,
}
}
}
impl FlexFec03SendBuilder {
/// Create a builder with the default block shape.
pub fn new() -> Self {
Self::default()
}
/// How many media packets one repair block protects.
///
/// Larger blocks cost less bandwidth per protected packet and recover later, since the block
/// is only sent once it is full.
pub fn with_num_media_packets(mut self, num_media_packets: u32) -> Self {
self.num_media_packets = num_media_packets;
self
}
/// How many repair packets each block produces.
///
/// This is what the block can survive: *n* repair packets recover up to *n* losses, spread
/// across the block by the interleaving.
pub fn with_num_fec_packets(mut self, num_fec_packets: u32) -> Self {
self.num_fec_packets = num_fec_packets;
self
}
/// The sequence number each repair stream starts at.
///
/// Unset, every repair stream starts at a random one (draft-03 section 4.2, RFC 3550 section
/// 5.1). A test pins it to assert on the numbers.
pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
self.initial_sequence_number = Some(sequence_number);
self
}
/// The RTP timestamp each repair stream carries at the instant of its first packet.
///
/// Unset, it is random (RFC 3550 section 5.1). From there the timestamp follows the send
/// clock: the `now` each media packet is written with, at the stream's clock rate.
pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
self.initial_timestamp = Some(timestamp);
self
}
/// Whether the amount of FEC follows the loss the receiver reports (the default), or
/// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
/// for twice the loss above it, at most half the block; the FEC sent is taken out of the
/// target the application encodes at.
pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
self.adaptive_rate = adaptive;
self
}
/// The application's latency budget (RFC 8854 section 8): while the round trip measured to
/// the receiver is within it, a stream that can be repaired by RTX (`nack` and an RTX stream
/// negotiated) gets no FEC.
/// [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by default; `None`
/// sends FEC by the loss whatever the round trip (proactive FEC).
pub fn with_latency_budget(mut self, latency_budget: Option<std::time::Duration>) -> Self {
self.latency_budget = latency_budget;
self
}
/// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
/// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
/// left out, and ends the block gathered so far, which is protected as it is.
pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
self.base_layer_only = base_layer_only;
self
}
/// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8:
/// "stronger FEC protection MAY be applied only after the source rate has been reduced";
/// the default). Once a congestion controller's target went by, the amount of FEC rises
/// only when the source sent in the last second plus the FEC the higher amount adds fit
/// within the target, and the target for the application is lowered by the FEC asked for
/// so the source makes the room. See [`FecRate::with_source_rate_first`](crate::FecRate::with_source_rate_first).
pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
self.source_rate_first = source_rate_first;
self
}
/// Whether bandwidth probe clusters are filled with repair packets (RFC 8854 section 8:
/// "when probing bandwidth, i.e., speculatively sending extra data to determine if
/// additional link capacity exists, FEC data SHOULD be used as the additional data"; the
/// default). When a cluster is asked for (the pacer's [`ProbeFill`](crate::ProbeFill) says
/// how much the media it holds leaves to fill; without a pacer, the whole cluster), the
/// encoder sends up to that much in repair packets over the newest run of consecutive
/// base-layer packets that left (at most 16, within the repair window; one repair packet
/// each at most) of the stream that sent last, on its repair stream, and the NACK responder
/// pads only what they leave unfilled (a stream without RTX: the encoder fills it all).
/// These repair packets are not taken out of the target the application encodes at. Off,
/// the NACK responder fills clusters with padding on the RTX stream.
pub fn with_probe_fill(mut self, probe_fill: bool) -> Self {
self.probe_fill = probe_fill;
self
}
/// Build the interceptor.
pub fn build(self) -> FlexFec03SendInterceptor {
let mut interceptor =
FlexFec03SendInterceptor::new(self.num_media_packets, self.num_fec_packets);
interceptor.rate = FecRate::new(
self.num_media_packets,
self.num_fec_packets,
self.adaptive_rate,
)
.with_latency_budget(self.latency_budget)
.with_source_rate_first(self.source_rate_first);
interceptor.base_layer_only = self.base_layer_only;
interceptor.probe_fill = self.probe_fill;
interceptor.initial_sequence_number = self.initial_sequence_number;
interceptor.initial_timestamp = self.initial_timestamp;
interceptor
}
}
/// One protected media stream.
struct ProtectedStream {
encoder: FlexFec03Encoder,
/// Media packets awaiting a full block.
block: Vec<rtp::Packet>,
/// When the block's first packet left, and the transport it left on.
block_started: Option<(Instant, shared::TransportContext)>,
/// The negotiated `repair-window` (draft section 5.1, "the time that spans the source
/// packets and the corresponding repair packets"): a block is closed and protected no
/// later than this after its first packet left.
repair_window: Option<std::time::Duration>,
/// The repair stream's send clock: its rate, and the timestamp it carries at `epoch`.
clock: RepairClock,
/// Whether the stream can be repaired by RTX (`nack` and an RTX stream negotiated).
retransmission: bool,
/// The temporal layer of its packets.
layers: crate::fec_layer::LayerReader,
/// The newest run of consecutive base-layer media packets that left and when each did, for
/// the repair packets of a probe cluster.
recent: VecDeque<(Instant, rtp::Packet)>,
/// When the NACK responder was last told this encoder fills the stream's probe clusters.
announced: Option<Instant>,
}
/// The repair stream's RTP clock, driven by the instants packets are written with.
///
/// A repair packet's timestamp is its transmission time (draft-03 section 4.2), so it comes from
/// the send clock and not from the media it protects. The engine is sans-I/O: the only clock is
/// the `now` each packet carries.
struct RepairClock {
clock_rate: u32,
initial_timestamp: u32,
/// The instant of the first repair packet, which carries `initial_timestamp`.
epoch: Option<Instant>,
}
impl RepairClock {
fn timestamp_at(&mut self, now: Instant) -> u32 {
let epoch = *self.epoch.get_or_insert(now);
let elapsed = now.saturating_duration_since(epoch);
let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
// The RTP timestamp is modulo 2^32.
self.initial_timestamp.wrapping_add(ticks as u32)
}
}
/// Produces FlexFEC draft-03 repair packets for outgoing media.
///
/// Binds only when the stream carries both a FEC SSRC and a FEC payload type: a repair stream
/// needs its own SSRC to send on and its own payload type to be recognised by, and half an
/// association is not usable. Those come from the negotiated `a=ssrc-group:FEC-FR`.
pub struct FlexFec03SendInterceptor {
num_media_packets: u32,
num_fec_packets: u32,
/// The loss-driven amount of FEC.
rate: FecRate,
/// Only base-layer frames are protected.
base_layer_only: bool,
/// Probe clusters are filled with repair packets ([`FlexFec03SendBuilder::with_probe_fill`]).
probe_fill: bool,
/// Keyed by the **media** SSRC being protected.
streams: HashMap<u32, ProtectedStream>,
/// Pinned by the builder; random per repair stream when unset.
initial_sequence_number: Option<u16>,
initial_timestamp: Option<u32>,
/// Where the media packets are read from once [`wire_tap`](Self::wire_tap) was called: as
/// they left, below everything that edits them.
wire: Option<WireImages>,
/// Repair packets the encoder produced, waiting to join the belt.
/// Inbound packets ready for the next interceptor.
read_queue: VecDeque<TaggedPacket>,
/// Outbound packets ready for the next interceptor: what passed through, plus
/// anything this one generated.
write_queue: VecDeque<TaggedPacket>,
}
impl FlexFec03SendInterceptor {
fn new(num_media_packets: u32, num_fec_packets: u32) -> Self {
Self {
read_queue: VecDeque::new(),
write_queue: VecDeque::new(),
num_media_packets: num_media_packets.max(1),
num_fec_packets,
rate: FecRate::new(num_media_packets, num_fec_packets, true),
base_layer_only: true,
probe_fill: true,
streams: HashMap::new(),
initial_sequence_number: None,
initial_timestamp: None,
wire: None,
}
}
/// The tap this encoder reads the media packets from, to register at
/// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
///
/// FEC covers the source packets as they are on the wire (draft-03 section 4.1). This
/// interceptor generates packets, so it sits above the pacer, where a media packet is not
/// final: the TWCC sender below writes the transport-wide sequence number into it, adding
/// the header extension when the packet has none. Encoding there protects an image the
/// receiver never sees, and what it recovers from it is corrupt. With the tap registered the
/// encoder protects the packet that left, and the repair packets still enter the chain
/// here, so they are paced, numbered and recorded.
///
/// Without a tap (this method never called) the encoder reads the packets as they pass this
/// slot, which is the wire image only when nothing below edits them: no TWCC sender in the
/// chain.
pub fn wire_tap(&mut self) -> WireImageTap {
let (tap, images) = wire_image_tap();
for ssrc in self.streams.keys() {
images.watch(*ssrc);
}
self.wire = Some(images);
tap
}
/// Add one media packet to its stream's block and queue the repair packets a full block
/// yields.
fn protect(
&mut self,
now: Instant,
transport: shared::TransportContext,
rtp_packet: &rtp::Packet,
) {
let ssrc = rtp_packet.header.ssrc;
// A block whose window ended before this packet left is protected first.
self.close_expired_block(ssrc, now);
let Some(stream) = self.streams.get_mut(&ssrc) else {
return;
};
// RFC 8854 section 8: with a layered codec only base-layer frames are protected. A
// packet of a higher temporal layer is left out; a block is a run of consecutive
// packets, so it ends the block, which is protected with what it has.
if self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload) {
if !stream.block.is_empty() {
self.complete_block(ssrc, now, transport);
}
return;
}
// The newest run of consecutive base-layer packets, for a probe cluster's repair
// packets: the next base-layer packet after an enhancement-layer one starts a new run.
if self.probe_fill {
if stream.recent.back().is_some_and(|(_, last)| {
rtp_packet.header.sequence_number != last.header.sequence_number.wrapping_add(1)
}) {
stream.recent.clear();
}
if stream.recent.len() == FEC_PROBE_SOURCE_PACKETS {
stream.recent.pop_front();
}
stream.recent.push_back((now, rtp_packet.clone()));
}
stream.block.push(rtp_packet.clone());
stream.block_started.get_or_insert((now, transport));
if (stream.block.len() as u32) < self.num_media_packets {
return;
}
self.complete_block(ssrc, now, transport);
}
/// Protects the block of `ssrc` now if its repair window ran out by `now`.
fn close_expired_block(&mut self, ssrc: u32, now: Instant) {
let Some(stream) = self.streams.get(&ssrc) else {
return;
};
if let (Some(window), Some((started, transport))) =
(stream.repair_window, stream.block_started)
&& !stream.block.is_empty()
&& now.saturating_duration_since(started) >= window
{
self.complete_block(ssrc, (started + window).min(now), transport);
}
}
/// Encodes the block of `ssrc` gathered so far and queues its repair packets.
fn complete_block(&mut self, ssrc: u32, now: Instant, transport: shared::TransportContext) {
let Some(stream) = self.streams.get_mut(&ssrc) else {
return;
};
stream.block_started = None;
// The repair packets carry the send clock at `now`: the instant the block's last packet
// was written with (from the wire tap, the instant the pacer released it).
let timestamp = stream.clock.timestamp_at(now);
// None while retransmission is preferred (RFC 8854 section 8).
self.num_fec_packets = self.rate.fec_packets_with(stream.retransmission);
let repair_packets = if self.num_fec_packets == 0 {
Vec::new()
} else {
stream
.encoder
.encode(&stream.block, self.num_fec_packets, timestamp)
};
// Cleared either way: a block the encoder refused — a gap, or one longer than the
// masks describe — must not be retried packet by packet as more arrive.
stream.block.clear();
for packet in repair_packets {
self.rate.on_repair_sent(now, packet.marshal_size());
// Queued for `poll_write`, which puts them back on the belt: a repair packet is a real
// outgoing RTP packet and still needs every interceptor ahead — a transport-wide sequence
// number, the pacer, and a place in the send history congestion control reads.
let fec_bytes = packet.payload.len();
self.write_queue.push_back(TaggedPacket {
now,
transport,
message: AttributedPacket::new(Packet::Rtp(packet))
.with(crate::FecSent::one(ssrc, fec_bytes)),
});
}
}
/// Protect the media packets that left since the last call.
fn protect_wire_images(&mut self) {
let Some(images) = self.wire.as_ref().map(WireImages::take) else {
return;
};
for image in images {
if let Packet::Rtp(rtp_packet) = &image.message.packet {
// `image.now` is the instant the pacer released the packet.
self.protect(image.now, image.transport, rtp_packet);
}
}
}
/// The media SSRCs currently being protected.
pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
self.streams.keys().copied()
}
/// Fills a probe cluster with `octets` of repair packets (RFC 8854 section 8) over the
/// newest run of base-layer packets of the stream that sent last, as many as the octets ask
/// for (at most one per media packet), within the repair window when one was negotiated.
/// Not counted in the FEC bit rate taken out of the media target. Returns the octets made;
/// the NACK responder pads the rest on the stream's RTX stream, and a stream without one
/// is filled whole here (further repair packets over the same run, at most
/// [`FEC_PROBE_MAX_REPAIR_PACKETS`]). `mark`: the cluster, when no pacer sends it.
fn fill_probe(
&mut self,
now: Instant,
transport: shared::TransportContext,
octets: usize,
mark: Option<u32>,
) -> usize {
let Some((&ssrc, stream)) = self
.streams
.iter_mut()
.filter(|(_, stream)| !stream.recent.is_empty())
.max_by_key(|(_, stream)| stream.recent.back().map(|(at, _)| *at))
else {
return 0;
};
if let Some(window) = stream.repair_window {
while stream
.recent
.front()
.is_some_and(|(at, _)| now.saturating_duration_since(*at) > window)
{
stream.recent.pop_front();
}
}
if stream.recent.is_empty() || octets == 0 {
return 0;
}
let sources: Vec<rtp::Packet> = stream
.recent
.iter()
.map(|(_, packet)| packet.clone())
.collect();
// A repair packet is about as large as the largest packet it protects, with the
// draft-03 header (at most 24 octets) in front.
let repair_size = sources
.iter()
.map(|packet| packet.marshal_size())
.max()
.unwrap_or(0)
+ 24;
let rtx = stream.retransmission;
let timestamp = stream.clock.timestamp_at(now);
let (mut filled, mut made) = (0usize, 0usize);
loop {
let wanted = octets.saturating_sub(filled).div_ceil(repair_size.max(1));
let count = wanted
.clamp(1, sources.len())
.min(FEC_PROBE_MAX_REPAIR_PACKETS - made);
let packets = stream.encoder.encode(&sources, count as u32, timestamp);
if packets.is_empty() {
break;
}
for packet in packets {
filled += packet.marshal_size();
made += 1;
let fec_bytes = packet.payload.len();
let mut message = AttributedPacket::new(Packet::Rtp(packet))
.with(crate::FecSent::one(ssrc, fec_bytes));
if let Some(cluster) = mark {
message.add(Attribute::Custom(std::sync::Arc::new(crate::ProbePacket {
cluster,
})));
}
self.write_queue.push_back(TaggedPacket {
now,
transport,
message,
});
}
// With an RTX stream the responder pads the rest; without, the encoder goes on.
if rtx || filled >= octets || made >= FEC_PROBE_MAX_REPAIR_PACKETS {
break;
}
}
filled
}
}
impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFec03SendInterceptor {
type Rout = TaggedPacket;
type Wout = TaggedPacket;
type Eout = ();
type Error = Error;
type Time = Instant;
fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
let streams = &self.streams;
self.rate
.on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
// A probe cluster (RFC 8854 section 8): what its media leaves to fill (the pacer's
// `ProbeFill`; without a pacer, the whole cluster) is filled with repair packets, and
// what they cannot fill the NACK responder pads.
if self.probe_fill
&& !self.streams.is_empty()
&& let Some(request) = msg.message.custom::<crate::ProbeRequest>().copied()
{
let paced = msg
.message
.custom::<crate::ProbeFill>()
.filter(|fill| fill.cluster == request.cluster)
.map(|fill| fill.octets.min(request.octets));
let fill = paced.unwrap_or(request.octets);
let mark = paced.is_none().then_some(request.cluster);
self.protect_wire_images();
let filled = self.fill_probe(msg.now, msg.transport, fill, mark);
// After the repair packets, wire-ward: the NACK responder pads what they left.
self.write_queue.push_back(
crate::cc::probe::FecProbeFilled {
cluster: request.cluster,
octets: filled,
}
.into_packet(msg.now, msg.transport),
);
}
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, mut msg: TaggedPacket) -> Result<(), Self::Error> {
// The source's rate, which stronger FEC waits on (RFC 8627 section 8).
let streams = &self.streams;
self.rate.on_write(&msg, |ssrc| streams.contains_key(&ssrc));
// The NACK responder learns that this encoder fills the stream's probe clusters.
if self.probe_fill
&& let Packet::Rtp(rtp_packet) = &msg.message.packet
&& let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
&& stream.announced.is_none_or(|at| {
msg.now.saturating_duration_since(at) >= FEC_PROBE_FILLER_ANNOUNCE_INTERVAL
})
{
stream.announced = Some(msg.now);
let ssrc = rtp_packet.header.ssrc;
msg.message.add(Attribute::Custom(std::sync::Arc::new(
crate::cc::probe::FecProbeFiller { ssrc },
)));
}
if self.wire.is_some() {
// The packets are protected as they leave, from the tap: here they only pass.
self.protect_wire_images();
self.write_queue.push_back(msg);
return Ok(());
}
let Packet::Rtp(rtp_packet) = &msg.message.packet else {
self.write_queue.push_back(msg);
return Ok(());
};
let rtp_packet = rtp_packet.clone();
let now = msg.now;
let transport = msg.transport;
// The media packet goes out first; the repair packets protect what has already left.
self.write_queue.push_back(msg);
self.protect(now, transport, &rtp_packet);
Ok(())
}
fn poll_write(&mut self) -> Option<TaggedPacket> {
self.protect_wire_images();
self.write_queue.pop_front()
}
/// A block whose repair window ends is protected then, with what it has: its repair
/// packets must not leave later than the window after its first packet.
fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
let ssrcs: Vec<u32> = self.streams.keys().copied().collect();
for ssrc in ssrcs {
self.close_expired_block(ssrc, now);
}
Ok(())
}
fn poll_timeout(&mut self) -> Option<Self::Time> {
self.streams
.values()
.filter(|stream| !stream.block.is_empty())
.filter_map(|stream| Some(stream.block_started?.0 + stream.repair_window?))
.min()
}
}
impl Interceptor for FlexFec03SendInterceptor {
fn bind_local_stream(&mut self, info: &StreamInfo) {
// The gate FEC-PRE-01 exists to open. Both halves or neither: an SSRC with no payload
// type has nothing to mark its packets with, and a payload type with no SSRC has nowhere
// to send them.
//
// And only for this format: RFC 8627 `flexfec` is another wire format with its own
// interceptor.
if let (Some(ssrc_fec), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
&& info.fec_is_flexfec03()
{
self.streams.insert(
info.ssrc,
ProtectedStream {
encoder: FlexFec03Encoder::new(payload_type_fec, ssrc_fec)
.with_base_sequence_number(
self.initial_sequence_number.unwrap_or_else(rand::random),
),
block: Vec::new(),
block_started: None,
repair_window: crate::FlexFecParameters::parse(&info.sdp_fmtp_line_fec)
.repair_window
.filter(|window| !window.is_zero()),
clock: RepairClock {
// The FlexFEC rate is negotiated equal to the media's (section 5.1);
// 90 kHz is the video clock when a stream names none.
clock_rate: if info.clock_rate == 0 {
90_000
} else {
info.clock_rate
},
initial_timestamp: self.initial_timestamp.unwrap_or_else(rand::random),
epoch: None,
},
retransmission: crate::nack::stream_supports_rtx_repair(info),
layers: crate::fec_layer::LayerReader::for_mime_type(&info.mime_type),
recent: VecDeque::new(),
announced: None,
},
);
if let Some(images) = &self.wire {
images.watch(info.ssrc);
}
}
}
fn unbind_local_stream(&mut self, info: &StreamInfo) {
// Any partly-filled block goes with it: those packets have already been sent unprotected,
// and a repair packet for a stream that has stopped has nothing left to repair.
self.streams.remove(&info.ssrc);
if let Some(images) = &self.wire {
images.unwatch(info.ssrc);
}
}
fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
}