rtci_interceptor/flexfec/draft03/sender.rs
1//! Send-side FlexFEC draft-03: protects outgoing media with repair packets.
2
3use super::encoder::FlexFec03Encoder;
4use crate::Interceptor;
5use crate::cc::fec_rate::FecRate;
6use crate::stream_info::StreamInfo;
7use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
8use crate::{AttributedPacket, Packet, TaggedPacket};
9use sansio::Protocol;
10use shared::error::Error;
11use shared::marshal::MarshalSize;
12use std::collections::{HashMap, VecDeque};
13use std::time::Instant;
14
15/// Media packets gathered before a repair block is produced.
16pub const DEFAULT_NUM_MEDIA_PACKETS: u32 = 5;
17
18/// Repair packets produced per block.
19pub const DEFAULT_NUM_FEC_PACKETS: u32 = 2;
20
21/// Builder for [`FlexFec03SendInterceptor`].
22///
23/// # Example
24///
25/// ```
26/// use rtci_interceptor::{Slot, FlexFec03SendBuilder, Registry};
27///
28/// let mut fec = FlexFec03SendBuilder::new().with_num_fec_packets(1).build();
29/// // The encoder protects the packets as they leave: see `wire_tap`.
30/// let tap = fec.wire_tap();
31/// let chain = Registry::new()
32/// .with(Slot::FecEncoder, fec)
33/// .with(Slot::FecWireImage, tap)
34/// .build();
35/// ```
36pub struct FlexFec03SendBuilder {
37 num_media_packets: u32,
38 num_fec_packets: u32,
39 adaptive_rate: bool,
40 initial_sequence_number: Option<u16>,
41 initial_timestamp: Option<u32>,
42 latency_budget: Option<std::time::Duration>,
43 base_layer_only: bool,
44}
45
46impl Default for FlexFec03SendBuilder {
47 fn default() -> Self {
48 Self {
49 num_media_packets: DEFAULT_NUM_MEDIA_PACKETS,
50 num_fec_packets: DEFAULT_NUM_FEC_PACKETS,
51 adaptive_rate: true,
52 initial_sequence_number: None,
53 initial_timestamp: None,
54 latency_budget: Some(crate::FEC_DEFAULT_LATENCY_BUDGET),
55 base_layer_only: true,
56 }
57 }
58}
59
60impl FlexFec03SendBuilder {
61 /// Create a builder with the default block shape.
62 pub fn new() -> Self {
63 Self::default()
64 }
65
66 /// How many media packets one repair block protects.
67 ///
68 /// Larger blocks cost less bandwidth per protected packet and recover later, since the block
69 /// is only sent once it is full.
70 pub fn with_num_media_packets(mut self, num_media_packets: u32) -> Self {
71 self.num_media_packets = num_media_packets;
72 self
73 }
74
75 /// How many repair packets each block produces.
76 ///
77 /// This is what the block can survive: *n* repair packets recover up to *n* losses, spread
78 /// across the block by the interleaving.
79 pub fn with_num_fec_packets(mut self, num_fec_packets: u32) -> Self {
80 self.num_fec_packets = num_fec_packets;
81 self
82 }
83
84 /// The sequence number each repair stream starts at.
85 ///
86 /// Unset, every repair stream starts at a random one (draft-03 section 4.2, RFC 3550 section
87 /// 5.1). A test pins it to assert on the numbers.
88 pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
89 self.initial_sequence_number = Some(sequence_number);
90 self
91 }
92
93 /// The RTP timestamp each repair stream carries at the instant of its first packet.
94 ///
95 /// Unset, it is random (RFC 3550 section 5.1). From there the timestamp follows the send
96 /// clock: the `now` each media packet is written with, at the stream's clock rate.
97 pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
98 self.initial_timestamp = Some(timestamp);
99 self
100 }
101
102 /// Whether the amount of FEC follows the loss the receiver reports (the default), or
103 /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
104 /// for twice the loss above it, at most half the block; the FEC sent is taken out of the
105 /// target the application encodes at.
106 pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
107 self.adaptive_rate = adaptive;
108 self
109 }
110
111 /// The application's latency budget (RFC 8854 section 8): while the round trip measured to
112 /// the receiver is within it, a stream that can be repaired by RTX (`nack` and an RTX stream
113 /// negotiated) gets no FEC.
114 /// [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by default; `None`
115 /// sends FEC by the loss whatever the round trip (proactive FEC).
116 pub fn with_latency_budget(mut self, latency_budget: Option<std::time::Duration>) -> Self {
117 self.latency_budget = latency_budget;
118 self
119 }
120
121 /// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
122 /// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
123 /// left out, and ends the block gathered so far, which is protected as it is.
124 pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
125 self.base_layer_only = base_layer_only;
126 self
127 }
128
129 /// Build the interceptor.
130 pub fn build(self) -> FlexFec03SendInterceptor {
131 let mut interceptor =
132 FlexFec03SendInterceptor::new(self.num_media_packets, self.num_fec_packets);
133 interceptor.rate = FecRate::new(
134 self.num_media_packets,
135 self.num_fec_packets,
136 self.adaptive_rate,
137 )
138 .with_latency_budget(self.latency_budget);
139 interceptor.base_layer_only = self.base_layer_only;
140 interceptor.initial_sequence_number = self.initial_sequence_number;
141 interceptor.initial_timestamp = self.initial_timestamp;
142 interceptor
143 }
144}
145
146/// One protected media stream.
147struct ProtectedStream {
148 encoder: FlexFec03Encoder,
149 /// Media packets awaiting a full block.
150 block: Vec<rtp::Packet>,
151 /// When the block's first packet left, and the transport it left on.
152 block_started: Option<(Instant, shared::TransportContext)>,
153 /// The negotiated `repair-window` (draft section 5.1, "the time that spans the source
154 /// packets and the corresponding repair packets"): a block is closed and protected no
155 /// later than this after its first packet left.
156 repair_window: Option<std::time::Duration>,
157 /// The repair stream's send clock: its rate, and the timestamp it carries at `epoch`.
158 clock: RepairClock,
159 /// Whether the stream can be repaired by RTX (`nack` and an RTX stream negotiated).
160 retransmission: bool,
161 /// The temporal layer of its packets.
162 layers: crate::fec_layer::LayerReader,
163}
164
165/// The repair stream's RTP clock, driven by the instants packets are written with.
166///
167/// A repair packet's timestamp is its transmission time (draft-03 section 4.2), so it comes from
168/// the send clock and not from the media it protects. The engine is sans-I/O: the only clock is
169/// the `now` each packet carries.
170struct RepairClock {
171 clock_rate: u32,
172 initial_timestamp: u32,
173 /// The instant of the first repair packet, which carries `initial_timestamp`.
174 epoch: Option<Instant>,
175}
176
177impl RepairClock {
178 fn timestamp_at(&mut self, now: Instant) -> u32 {
179 let epoch = *self.epoch.get_or_insert(now);
180 let elapsed = now.saturating_duration_since(epoch);
181 let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
182 // The RTP timestamp is modulo 2^32.
183 self.initial_timestamp.wrapping_add(ticks as u32)
184 }
185}
186
187/// Produces FlexFEC draft-03 repair packets for outgoing media.
188///
189/// Binds only when the stream carries both a FEC SSRC and a FEC payload type: a repair stream
190/// needs its own SSRC to send on and its own payload type to be recognised by, and half an
191/// association is not usable. Those come from the negotiated `a=ssrc-group:FEC-FR`.
192pub struct FlexFec03SendInterceptor {
193 num_media_packets: u32,
194 num_fec_packets: u32,
195 /// The loss-driven amount of FEC.
196 rate: FecRate,
197 /// Only base-layer frames are protected.
198 base_layer_only: bool,
199 /// Keyed by the **media** SSRC being protected.
200 streams: HashMap<u32, ProtectedStream>,
201 /// Pinned by the builder; random per repair stream when unset.
202 initial_sequence_number: Option<u16>,
203 initial_timestamp: Option<u32>,
204 /// Where the media packets are read from once [`wire_tap`](Self::wire_tap) was called: as
205 /// they left, below everything that edits them.
206 wire: Option<WireImages>,
207 /// Repair packets the encoder produced, waiting to join the belt.
208 /// Inbound packets ready for the next interceptor.
209 read_queue: VecDeque<TaggedPacket>,
210 /// Outbound packets ready for the next interceptor: what passed through, plus
211 /// anything this one generated.
212 write_queue: VecDeque<TaggedPacket>,
213}
214
215impl FlexFec03SendInterceptor {
216 fn new(num_media_packets: u32, num_fec_packets: u32) -> Self {
217 Self {
218 read_queue: VecDeque::new(),
219 write_queue: VecDeque::new(),
220 num_media_packets: num_media_packets.max(1),
221 num_fec_packets,
222 rate: FecRate::new(num_media_packets, num_fec_packets, true),
223 base_layer_only: true,
224 streams: HashMap::new(),
225 initial_sequence_number: None,
226 initial_timestamp: None,
227 wire: None,
228 }
229 }
230
231 /// The tap this encoder reads the media packets from, to register at
232 /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
233 ///
234 /// FEC covers the source packets as they are on the wire (draft-03 section 4.1). This
235 /// interceptor generates packets, so it sits above the pacer, where a media packet is not
236 /// final: the TWCC sender below writes the transport-wide sequence number into it, adding
237 /// the header extension when the packet has none. Encoding there protects an image the
238 /// receiver never sees, and what it recovers from it is corrupt. With the tap registered the
239 /// encoder protects the packet that left, and the repair packets still enter the chain
240 /// here, so they are paced, numbered and recorded.
241 ///
242 /// Without a tap (this method never called) the encoder reads the packets as they pass this
243 /// slot, which is the wire image only when nothing below edits them: no TWCC sender in the
244 /// chain.
245 pub fn wire_tap(&mut self) -> WireImageTap {
246 let (tap, images) = wire_image_tap();
247 for ssrc in self.streams.keys() {
248 images.watch(*ssrc);
249 }
250 self.wire = Some(images);
251 tap
252 }
253
254 /// Add one media packet to its stream's block and queue the repair packets a full block
255 /// yields.
256 fn protect(
257 &mut self,
258 now: Instant,
259 transport: shared::TransportContext,
260 rtp_packet: &rtp::Packet,
261 ) {
262 let ssrc = rtp_packet.header.ssrc;
263 // A block whose window ended before this packet left is protected first.
264 self.close_expired_block(ssrc, now);
265 let Some(stream) = self.streams.get_mut(&ssrc) else {
266 return;
267 };
268
269 // RFC 8854 section 8: with a layered codec only base-layer frames are protected. A
270 // packet of a higher temporal layer is left out; a block is a run of consecutive
271 // packets, so it ends the block, which is protected with what it has.
272 if self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload) {
273 if !stream.block.is_empty() {
274 self.complete_block(ssrc, now, transport);
275 }
276 return;
277 }
278
279 stream.block.push(rtp_packet.clone());
280 stream.block_started.get_or_insert((now, transport));
281 if (stream.block.len() as u32) < self.num_media_packets {
282 return;
283 }
284 self.complete_block(ssrc, now, transport);
285 }
286
287 /// Protects the block of `ssrc` now if its repair window ran out by `now`.
288 fn close_expired_block(&mut self, ssrc: u32, now: Instant) {
289 let Some(stream) = self.streams.get(&ssrc) else {
290 return;
291 };
292 if let (Some(window), Some((started, transport))) =
293 (stream.repair_window, stream.block_started)
294 && !stream.block.is_empty()
295 && now.saturating_duration_since(started) >= window
296 {
297 self.complete_block(ssrc, (started + window).min(now), transport);
298 }
299 }
300
301 /// Encodes the block of `ssrc` gathered so far and queues its repair packets.
302 fn complete_block(&mut self, ssrc: u32, now: Instant, transport: shared::TransportContext) {
303 let Some(stream) = self.streams.get_mut(&ssrc) else {
304 return;
305 };
306 stream.block_started = None;
307 // The repair packets carry the send clock at `now`: the instant the block's last packet
308 // was written with (from the wire tap, the instant the pacer released it).
309 let timestamp = stream.clock.timestamp_at(now);
310 // None while retransmission is preferred (RFC 8854 section 8).
311 self.num_fec_packets = self.rate.fec_packets_with(stream.retransmission);
312 let repair_packets = if self.num_fec_packets == 0 {
313 Vec::new()
314 } else {
315 stream
316 .encoder
317 .encode(&stream.block, self.num_fec_packets, timestamp)
318 };
319 // Cleared either way: a block the encoder refused — a gap, or one longer than the
320 // masks describe — must not be retried packet by packet as more arrive.
321 stream.block.clear();
322
323 for packet in repair_packets {
324 self.rate.on_repair_sent(now, packet.marshal_size());
325 // Queued for `poll_write`, which puts them back on the belt: a repair packet is a real
326 // outgoing RTP packet and still needs every interceptor ahead — a transport-wide sequence
327 // number, the pacer, and a place in the send history congestion control reads.
328 let fec_bytes = packet.payload.len();
329 self.write_queue.push_back(TaggedPacket {
330 now,
331 transport,
332 message: AttributedPacket::new(Packet::Rtp(packet))
333 .with(crate::FecSent::one(ssrc, fec_bytes)),
334 });
335 }
336 }
337
338 /// Protect the media packets that left since the last call.
339 fn protect_wire_images(&mut self) {
340 let Some(images) = self.wire.as_ref().map(WireImages::take) else {
341 return;
342 };
343 for image in images {
344 if let Packet::Rtp(rtp_packet) = &image.message.packet {
345 // `image.now` is the instant the pacer released the packet.
346 self.protect(image.now, image.transport, rtp_packet);
347 }
348 }
349 }
350
351 /// The media SSRCs currently being protected.
352 pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
353 self.streams.keys().copied()
354 }
355}
356
357impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFec03SendInterceptor {
358 type Rout = TaggedPacket;
359 type Wout = TaggedPacket;
360 type Eout = ();
361 type Error = Error;
362 type Time = Instant;
363
364 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
365 let streams = &self.streams;
366 self.rate
367 .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
368 self.read_queue.push_back(msg);
369 Ok(())
370 }
371
372 fn poll_read(&mut self) -> Option<Self::Rout> {
373 self.read_queue.pop_front()
374 }
375
376 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
377 if self.wire.is_some() {
378 // The packets are protected as they leave, from the tap: here they only pass.
379 self.protect_wire_images();
380 self.write_queue.push_back(msg);
381 return Ok(());
382 }
383
384 let Packet::Rtp(rtp_packet) = &msg.message.packet else {
385 self.write_queue.push_back(msg);
386 return Ok(());
387 };
388 let rtp_packet = rtp_packet.clone();
389 let now = msg.now;
390 let transport = msg.transport;
391
392 // The media packet goes out first; the repair packets protect what has already left.
393 self.write_queue.push_back(msg);
394 self.protect(now, transport, &rtp_packet);
395 Ok(())
396 }
397
398 fn poll_write(&mut self) -> Option<TaggedPacket> {
399 self.protect_wire_images();
400 self.write_queue.pop_front()
401 }
402
403 /// A block whose repair window ends is protected then, with what it has: its repair
404 /// packets must not leave later than the window after its first packet.
405 fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
406 let ssrcs: Vec<u32> = self.streams.keys().copied().collect();
407 for ssrc in ssrcs {
408 self.close_expired_block(ssrc, now);
409 }
410 Ok(())
411 }
412
413 fn poll_timeout(&mut self) -> Option<Self::Time> {
414 self.streams
415 .values()
416 .filter(|stream| !stream.block.is_empty())
417 .filter_map(|stream| Some(stream.block_started?.0 + stream.repair_window?))
418 .min()
419 }
420}
421
422impl Interceptor for FlexFec03SendInterceptor {
423 fn bind_local_stream(&mut self, info: &StreamInfo) {
424 // The gate FEC-PRE-01 exists to open. Both halves or neither: an SSRC with no payload
425 // type has nothing to mark its packets with, and a payload type with no SSRC has nowhere
426 // to send them.
427 //
428 // And only for this format: RFC 8627 `flexfec` is another wire format with its own
429 // interceptor.
430 if let (Some(ssrc_fec), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
431 && info.fec_is_flexfec03()
432 {
433 self.streams.insert(
434 info.ssrc,
435 ProtectedStream {
436 encoder: FlexFec03Encoder::new(payload_type_fec, ssrc_fec)
437 .with_base_sequence_number(
438 self.initial_sequence_number.unwrap_or_else(rand::random),
439 ),
440 block: Vec::new(),
441 block_started: None,
442 repair_window: crate::FlexFecParameters::parse(&info.sdp_fmtp_line_fec)
443 .repair_window
444 .filter(|window| !window.is_zero()),
445 clock: RepairClock {
446 // The FlexFEC rate is negotiated equal to the media's (section 5.1);
447 // 90 kHz is the video clock when a stream names none.
448 clock_rate: if info.clock_rate == 0 {
449 90_000
450 } else {
451 info.clock_rate
452 },
453 initial_timestamp: self.initial_timestamp.unwrap_or_else(rand::random),
454 epoch: None,
455 },
456 retransmission: crate::nack::stream_supports_rtx_repair(info),
457 layers: crate::fec_layer::LayerReader::for_mime_type(&info.mime_type),
458 },
459 );
460 if let Some(images) = &self.wire {
461 images.watch(info.ssrc);
462 }
463 }
464 }
465
466 fn unbind_local_stream(&mut self, info: &StreamInfo) {
467 // Any partly-filled block goes with it: those packets have already been sent unprotected,
468 // and a repair packet for a stream that has stopped has nothing left to repair.
469 self.streams.remove(&info.ssrc);
470 if let Some(images) = &self.wire {
471 images.unwatch(info.ssrc);
472 }
473 }
474
475 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
476
477 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
478}