rtci_interceptor/flexfec/rfc8627/decoder.rs
1//! RFC 8627 source packet reconstruction (section 6.3).
2
3use super::header::{FLEXFEC_RECOVERY_SIZE, FlexFecHeader, RTP_FIXED_HEADER_SIZE};
4use super::params::FlexFecParameters;
5use bytes::Bytes;
6use shared::marshal::{Marshal, MarshalSize, Unmarshal};
7use std::collections::{BTreeMap, HashMap, VecDeque};
8use std::time::{Duration, Instant};
9
10/// The repair window a decoder assumes when none is signalled: 10 s, the value libwebrtc
11/// writes for FlexFEC.
12pub const FLEXFEC_DEFAULT_REPAIR_WINDOW: Duration = Duration::from_secs(10);
13
14/// Bounds on what a [`FlexFecDecoder`] keeps, all of them derived from the repair window the
15/// session agreed to (RFC 8627 sections 1.1.2 and 9).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct FlexFecDecoderConfig {
18 /// How long a source or repair packet is kept after it arrived: the `repair-window`
19 /// parameter. A repair packet and the sources it protects are at most this far apart.
20 pub repair_window: Duration,
21 /// The most source packets kept per source stream, whatever the window. Also the largest
22 /// span of sequence numbers a repair packet may cover: one whose L and D (or mask) reach
23 /// further cannot be within the repair window and is ignored (section 4.2.2.2).
24 pub max_source_packets: usize,
25 /// The most repair packets kept while they wait for sources. The source packets they name
26 /// are bounded too, at 16 times `max_source_packets` over all of them: the oldest repair
27 /// packets go first.
28 pub max_repair_packets: usize,
29}
30
31impl FlexFecDecoderConfig {
32 /// Packets per second the packet-count bounds assume when turning the repair window into a
33 /// buffer size.
34 pub const ASSUMED_PACKET_RATE: u32 = 1000;
35 /// The floor and the ceiling of [`max_source_packets`](Self::max_source_packets) as derived
36 /// from a repair window: a short window still holds one full mask, and no window makes a
37 /// peer's parameters allocate without bound (section 9).
38 pub const MIN_SOURCE_PACKETS: usize = 128;
39 /// See [`MIN_SOURCE_PACKETS`](Self::MIN_SOURCE_PACKETS).
40 pub const MAX_SOURCE_PACKETS: usize = 4096;
41
42 /// The bounds for a session whose repair window is `repair_window`.
43 pub fn for_repair_window(repair_window: Duration) -> Self {
44 let packets = (repair_window.as_millis() * u128::from(Self::ASSUMED_PACKET_RATE) / 1000)
45 .clamp(
46 Self::MIN_SOURCE_PACKETS as u128,
47 Self::MAX_SOURCE_PACKETS as u128,
48 ) as usize;
49 Self {
50 repair_window,
51 max_source_packets: packets,
52 max_repair_packets: packets,
53 }
54 }
55
56 /// The bounds for a session described by `parameters` (its `a=fmtp` line).
57 pub fn for_parameters(parameters: &FlexFecParameters) -> Self {
58 Self::for_repair_window(
59 parameters
60 .repair_window
61 .unwrap_or(FLEXFEC_DEFAULT_REPAIR_WINDOW),
62 )
63 }
64}
65
66impl Default for FlexFecDecoderConfig {
67 fn default() -> Self {
68 Self::for_repair_window(FLEXFEC_DEFAULT_REPAIR_WINDOW)
69 }
70}
71
72/// One source packet held: when it arrived and its octets as they were on the wire.
73#[derive(Debug, Clone)]
74struct Held {
75 at: Instant,
76 wire: Bytes,
77}
78
79/// The packets of one source stream, by extended sequence number.
80#[derive(Debug, Default)]
81struct SourceBuffer {
82 packets: BTreeMap<i64, Held>,
83 /// The highest extended sequence number placed so far: the anchor 16-bit numbers are
84 /// unwrapped against.
85 highest: Option<i64>,
86 /// The sequence number of the last source packet refused as too far behind `highest`. A
87 /// second one right after it means the stream itself moved (a restart), not a stray.
88 stray: Option<u16>,
89}
90
91impl SourceBuffer {
92 /// Keep at most `max` packets, none further behind the newest than `max` sequence numbers.
93 fn trim(&mut self, max: usize) {
94 let Some(highest) = self.highest else {
95 return;
96 };
97 let floor = highest - max as i64;
98 while let Some((&oldest, _)) = self.packets.first_key_value() {
99 if oldest > floor && self.packets.len() <= max {
100 break;
101 }
102 self.packets.remove(&oldest);
103 }
104 }
105
106 /// The extended sequence number `sequence_number` stands for: the one nearest the highest
107 /// seen. The first number of a stream is placed one cycle up, so that packets a little
108 /// behind it do not go negative.
109 fn extend(&self, sequence_number: u16) -> i64 {
110 match self.highest {
111 None => 0x1_0000 + i64::from(sequence_number),
112 Some(highest) => {
113 let delta = sequence_number.wrapping_sub(highest as u16) as i16;
114 highest + i64::from(delta)
115 }
116 }
117 }
118}
119
120/// A repair packet waiting for the source packets it protects.
121#[derive(Debug)]
122struct PendingRepair {
123 at: Instant,
124 recovery: [u8; FLEXFEC_RECOVERY_SIZE],
125 /// The repair payload: what follows the FEC header.
126 payload: Bytes,
127 /// Every source packet protected: stream and extended sequence number.
128 protected: Vec<(u32, i64)>,
129}
130
131/// Counters a [`FlexFecDecoder`] keeps about itself.
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
133#[non_exhaustive]
134pub struct FlexFecDecoderStats {
135 /// Source packets rebuilt from parity.
136 pub recovered: u64,
137 /// Source packets delivered by a retransmission (R=1) that were not already held.
138 pub retransmitted: u64,
139 /// Repair packets ignored: a reserved or malformed header, L=0, a stream this decoder does
140 /// not protect, a span beyond the repair window.
141 pub ignored_repair_packets: u64,
142 /// Repair packets dropped because what they rebuilt was not an RTP packet, or their length
143 /// recovery pointed beyond their own payload.
144 pub failed_recoveries: u64,
145}
146
147/// Recovers lost source packets from RFC 8627 FlexFEC repair packets (`flexfec`, not
148/// `flexfec-03`): flexible masks, fixed L/D rows and columns (1-D and 2-D, decoded
149/// iteratively), retransmissions, and repair packets that protect several source streams.
150///
151/// Every packet of the protected source streams goes to
152/// [`push_source`](Self::push_source), every packet of the repair stream to
153/// [`push_repair`](Self::push_repair); both return the source packets that became available.
154///
155/// # Bounds
156///
157/// Only streams registered with [`add_source_stream`](Self::add_source_stream) are buffered: a
158/// repair packet naming any other SSRC is ignored, so a peer cannot make the decoder open
159/// buffers by inventing CSRCs. Per stream at most
160/// [`max_source_packets`](FlexFecDecoderConfig::max_source_packets) are kept, for at most the
161/// repair window; a repair packet whose L and D reach beyond that is ignored. Length recovery
162/// can never ask for more than the repair packet itself holds.
163#[derive(Debug)]
164pub struct FlexFecDecoder {
165 config: FlexFecDecoderConfig,
166 sources: HashMap<u32, SourceBuffer>,
167 repairs: VecDeque<PendingRepair>,
168 /// Source packets named by the pending repair packets, summed.
169 protected_entries: usize,
170 stats: FlexFecDecoderStats,
171}
172
173impl FlexFecDecoder {
174 /// A decoder with no source stream registered.
175 pub fn new(config: FlexFecDecoderConfig) -> Self {
176 Self {
177 config,
178 sources: HashMap::new(),
179 repairs: VecDeque::new(),
180 protected_entries: 0,
181 stats: FlexFecDecoderStats::default(),
182 }
183 }
184
185 /// The bounds this decoder runs with.
186 pub fn config(&self) -> &FlexFecDecoderConfig {
187 &self.config
188 }
189
190 /// Raise each bound to at least `config`'s: another stream joined with a longer repair
191 /// window. Bounds are never lowered while packets are held against them.
192 pub fn widen(&mut self, config: FlexFecDecoderConfig) {
193 self.config.repair_window = self.config.repair_window.max(config.repair_window);
194 self.config.max_source_packets = self
195 .config
196 .max_source_packets
197 .max(config.max_source_packets);
198 self.config.max_repair_packets = self
199 .config
200 .max_repair_packets
201 .max(config.max_repair_packets);
202 }
203
204 /// Counters.
205 pub fn stats(&self) -> FlexFecDecoderStats {
206 self.stats
207 }
208
209 /// Protect the source stream `ssrc`: buffer its packets and accept repair packets for it.
210 pub fn add_source_stream(&mut self, ssrc: u32) {
211 self.sources.entry(ssrc).or_default();
212 }
213
214 /// Stop protecting `ssrc`, dropping what was held for it.
215 pub fn remove_source_stream(&mut self, ssrc: u32) {
216 self.sources.remove(&ssrc);
217 self.drop_repairs_for(ssrc);
218 }
219
220 /// Drop the pending repair packets that protect `ssrc`.
221 fn drop_repairs_for(&mut self, ssrc: u32) {
222 self.repairs
223 .retain(|repair| repair.protected.iter().all(|(stream, _)| *stream != ssrc));
224 self.protected_entries = self.repairs.iter().map(|r| r.protected.len()).sum();
225 }
226
227 fn pop_oldest_repair(&mut self) {
228 if let Some(repair) = self.repairs.pop_front() {
229 self.protected_entries -= repair.protected.len();
230 }
231 }
232
233 fn take_repair(&mut self, index: usize) -> Option<PendingRepair> {
234 let repair = self.repairs.remove(index)?;
235 self.protected_entries -= repair.protected.len();
236 Some(repair)
237 }
238
239 /// Whether `ssrc` is a protected source stream.
240 pub fn protects(&self, ssrc: u32) -> bool {
241 self.sources.contains_key(&ssrc)
242 }
243
244 /// The protected source streams.
245 pub fn source_streams(&self) -> impl Iterator<Item = u32> + '_ {
246 self.sources.keys().copied()
247 }
248
249 /// Source packets held, over all streams.
250 pub fn held_source_packets(&self) -> usize {
251 self.sources
252 .values()
253 .map(|buffer| buffer.packets.len())
254 .sum()
255 }
256
257 /// Repair packets held while they wait for sources.
258 pub fn pending_repair_packets(&self) -> usize {
259 self.repairs.len()
260 }
261
262 /// Offer a packet of a protected source stream that arrived at `now`. Returns the source
263 /// packets it made recoverable.
264 pub fn push_source(&mut self, now: Instant, packet: &rtp::Packet) -> Vec<rtp::Packet> {
265 self.expire(now);
266 if !self.sources.contains_key(&packet.header.ssrc) {
267 return Vec::new();
268 }
269 let mut wire = vec![0u8; packet.marshal_size()];
270 if packet.marshal_to(&mut wire).is_err() || wire.len() < RTP_FIXED_HEADER_SIZE {
271 return Vec::new();
272 }
273 if !self.hold(
274 now,
275 packet.header.ssrc,
276 packet.header.sequence_number,
277 wire.into(),
278 ) {
279 return Vec::new();
280 }
281 self.recover_all(now)
282 }
283
284 /// Offer a packet of the repair stream that arrived at `now`. Returns the source packets
285 /// it made available: rebuilt from parity, or carried whole by a retransmission and not
286 /// held before.
287 pub fn push_repair(&mut self, now: Instant, packet: &rtp::Packet) -> Vec<rtp::Packet> {
288 self.expire(now);
289 // The marker bit of a repair packet is ignored (section 4.2.1), as are its own padding
290 // and header extensions: only the CSRC list and the payload are read.
291 match FlexFecHeader::parse(&packet.header.csrc, &packet.payload) {
292 Err(_) => {
293 self.stats.ignored_repair_packets += 1;
294 Vec::new()
295 }
296 Ok(FlexFecHeader::Retransmission) => self.push_retransmission(now, &packet.payload),
297 Ok(FlexFecHeader::Repair {
298 recovery,
299 blocks,
300 payload_offset,
301 }) => {
302 let mut protected = Vec::new();
303 for block in &blocks {
304 let Some(buffer) = self.sources.get_mut(&block.ssrc) else {
305 // A stream this decoder does not protect: its packets are never held,
306 // so nothing this repair packet covers can be rebuilt.
307 self.stats.ignored_repair_packets += 1;
308 return Vec::new();
309 };
310 // L and D (or a mask) reaching beyond what the repair window holds: MUST be
311 // ignored (section 4.2.2.2).
312 if block.span() as usize > self.config.max_source_packets {
313 self.stats.ignored_repair_packets += 1;
314 return Vec::new();
315 }
316 let base = buffer.extend(block.sn_base);
317 // A block that lies wholly outside what this stream's buffer can hold (too
318 // far behind the newest packet, or too far ahead of it) repairs nothing the
319 // decoder still has or is about to get: it is not kept, and nothing is
320 // rebuilt out there.
321 if let Some(highest) = buffer.highest {
322 let window = self.config.max_source_packets as i64;
323 let end = base + i64::from(block.span());
324 if end <= highest - window || base > highest + window {
325 self.stats.ignored_repair_packets += 1;
326 return Vec::new();
327 }
328 }
329 // A repair packet ahead of every source packet of its stream anchors the
330 // numbering, so the sources that follow are placed against it.
331 buffer.highest.get_or_insert(base);
332 protected.extend(
333 block
334 .offsets()
335 .into_iter()
336 .map(|offset| (block.ssrc, base + i64::from(offset))),
337 );
338 }
339
340 self.protected_entries += protected.len();
341 self.repairs.push_back(PendingRepair {
342 at: now,
343 recovery,
344 payload: packet.payload.slice(payload_offset..),
345 protected,
346 });
347 while self.repairs.len() > self.config.max_repair_packets
348 || self.protected_entries > 16 * self.config.max_source_packets
349 {
350 self.pop_oldest_repair();
351 }
352 self.recover_all(now)
353 }
354 }
355 }
356
357 /// A retransmission (section 4.2.2.3): the payload is the source packet, its version bits
358 /// reading R=1 F=0, which is version 2.
359 fn push_retransmission(&mut self, now: Instant, payload: &Bytes) -> Vec<rtp::Packet> {
360 let Ok(packet) = rtp::Packet::unmarshal(&mut payload.clone()) else {
361 self.stats.ignored_repair_packets += 1;
362 return Vec::new();
363 };
364 let ssrc = packet.header.ssrc;
365 let Some(buffer) = self.sources.get(&ssrc) else {
366 self.stats.ignored_repair_packets += 1;
367 return Vec::new();
368 };
369 // Within the repair window only: a packet further behind than the buffer reaches is
370 // one this decoder no longer knows whether it delivered.
371 if let Some(highest) = buffer.highest
372 && highest - buffer.extend(packet.header.sequence_number)
373 >= self.config.max_source_packets as i64
374 {
375 self.stats.ignored_repair_packets += 1;
376 return Vec::new();
377 }
378 if !self.hold(now, ssrc, packet.header.sequence_number, payload.clone()) {
379 // Already held: the original arrived after all, or this is a second copy.
380 return Vec::new();
381 }
382 self.stats.retransmitted += 1;
383 let mut available = vec![packet];
384 available.extend(self.recover_all(now));
385 available
386 }
387
388 /// Keep a source packet. Returns false when it was already held or is too old to keep.
389 fn hold(&mut self, now: Instant, ssrc: u32, sequence_number: u16, wire: Bytes) -> bool {
390 let max = self.config.max_source_packets;
391 let Some(buffer) = self.sources.get_mut(&ssrc) else {
392 return false;
393 };
394 let mut extended = buffer.extend(sequence_number);
395 if let Some(highest) = buffer.highest
396 && highest - extended >= max as i64
397 {
398 // Too far behind to keep. One such packet is a stray; a second one that follows it
399 // is the stream itself, restarted at another number: start over from there.
400 let restarted = buffer.stray == Some(sequence_number.wrapping_sub(1));
401 buffer.stray = Some(sequence_number);
402 if !restarted {
403 return false;
404 }
405 *buffer = SourceBuffer::default();
406 extended = buffer.extend(sequence_number);
407 self.drop_repairs_for(ssrc);
408 let Some(restarted) = self.sources.get_mut(&ssrc) else {
409 return false;
410 };
411 return {
412 restarted.packets.insert(extended, Held { at: now, wire });
413 restarted.highest = Some(extended);
414 true
415 };
416 }
417 buffer.stray = None;
418 if buffer.packets.contains_key(&extended) {
419 return false;
420 }
421 buffer.packets.insert(extended, Held { at: now, wire });
422 let highest = buffer
423 .highest
424 .map_or(extended, |highest| highest.max(extended));
425 buffer.highest = Some(highest);
426 buffer.trim(max);
427 true
428 }
429
430 /// Drop what arrived longer ago than the repair window.
431 fn expire(&mut self, now: Instant) {
432 let Some(cutoff) = now.checked_sub(self.config.repair_window) else {
433 return;
434 };
435 for buffer in self.sources.values_mut() {
436 buffer.packets.retain(|_, held| held.at >= cutoff);
437 }
438 while self
439 .repairs
440 .front()
441 .is_some_and(|repair| repair.at < cutoff)
442 {
443 self.pop_oldest_repair();
444 }
445 }
446
447 /// The iterative decoding of section 6.3.4: use every repair packet that misses exactly one
448 /// source packet, feed what it rebuilt back, and go round again until a pass rebuilds
449 /// nothing. Rows and columns are not told apart: the end result is the same in any order.
450 fn recover_all(&mut self, now: Instant) -> Vec<rtp::Packet> {
451 let mut recovered = Vec::new();
452 loop {
453 let mut progress = false;
454 let mut index = 0;
455 while index < self.repairs.len() {
456 let missing: Vec<(u32, i64)> = self.repairs[index]
457 .protected
458 .iter()
459 .filter(|(ssrc, extended)| !self.holds(*ssrc, *extended))
460 .copied()
461 .collect();
462 match missing.as_slice() {
463 // Everything it protects is here: it has nothing left to give.
464 [] => {
465 self.take_repair(index);
466 }
467 [(ssrc, extended)] => {
468 // Taken out before it is used, so the loop is bounded by the number of
469 // repair packets whatever the rebuilt packet turns out to be.
470 let Some(repair) = self.take_repair(index) else {
471 break;
472 };
473 match self.rebuild(&repair, *ssrc, *extended) {
474 Some((packet, wire)) => {
475 self.stats.recovered += 1;
476 // Held like a packet that arrived, and within the same
477 // bounds: one rebuilt from below the window is handed out and
478 // not kept.
479 let max = self.config.max_source_packets;
480 if let Some(buffer) = self.sources.get_mut(ssrc) {
481 buffer.packets.insert(*extended, Held { at: now, wire });
482 buffer.trim(max);
483 }
484 recovered.push(packet);
485 progress = true;
486 }
487 None => self.stats.failed_recoveries += 1,
488 }
489 }
490 _ => index += 1,
491 }
492 }
493 if !progress {
494 return recovered;
495 }
496 }
497 }
498
499 fn holds(&self, ssrc: u32, extended: i64) -> bool {
500 self.sources
501 .get(&ssrc)
502 .is_some_and(|buffer| buffer.packets.contains_key(&extended))
503 }
504
505 /// Sections 6.3.2 and 6.3.3: XOR the repair packet with every source packet it protects
506 /// but the missing one, and read the missing packet out of what is left.
507 fn rebuild(
508 &self,
509 repair: &PendingRepair,
510 missing_ssrc: u32,
511 missing: i64,
512 ) -> Option<(rtp::Packet, Bytes)> {
513 let mut bits = repair.recovery;
514 for (ssrc, extended) in &repair.protected {
515 if (*ssrc, *extended) == (missing_ssrc, missing) {
516 continue;
517 }
518 let wire = &self.sources.get(ssrc)?.packets.get(extended)?.wire;
519 let length = (wire.len() - RTP_FIXED_HEADER_SIZE) as u16;
520 bits[0] ^= wire[0];
521 bits[1] ^= wire[1];
522 bits[2] ^= (length >> 8) as u8;
523 bits[3] ^= length as u8;
524 for (target, &octet) in bits[4..8].iter_mut().zip(&wire[4..8]) {
525 *target ^= octet;
526 }
527 }
528
529 // Y: the length of the missing packet minus its fixed header. It comes off the wire, so
530 // it is trusted no further than the repair payload reaches: a sender pads every source
531 // to the longest, so an honest Y never exceeds it.
532 let length = usize::from(u16::from_be_bytes([bits[2], bits[3]]));
533 if length > repair.payload.len() {
534 return None;
535 }
536
537 let mut wire = Vec::with_capacity(RTP_FIXED_HEADER_SIZE + length);
538 // Version 2; P, X and CC from the recovered bit string, then M and PT.
539 wire.push(0x80 | (bits[0] & 0x3F));
540 wire.push(bits[1]);
541 wire.extend_from_slice(&(missing as u16).to_be_bytes());
542 wire.extend_from_slice(&bits[4..8]);
543 wire.extend_from_slice(&missing_ssrc.to_be_bytes());
544 wire.extend_from_slice(&repair.payload[..length]);
545 for (ssrc, extended) in &repair.protected {
546 if (*ssrc, *extended) == (missing_ssrc, missing) {
547 continue;
548 }
549 let source = &self.sources.get(ssrc)?.packets.get(extended)?.wire;
550 for (target, &octet) in wire[RTP_FIXED_HEADER_SIZE..]
551 .iter_mut()
552 .zip(&source[RTP_FIXED_HEADER_SIZE..])
553 {
554 *target ^= octet;
555 }
556 }
557
558 // What comes out has to be an RTP packet: CC, the extension length and the padding
559 // count were all recovered from the peer's bits.
560 let wire = Bytes::from(wire);
561 let packet = rtp::Packet::unmarshal(&mut wire.clone()).ok()?;
562 Some((packet, wire))
563 }
564}