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