Skip to main content

rtci_interceptor/
audio_red.rs

1//! Redundant audio data, RED (RFC 2198), for the audio streams whose m= section negotiated a
2//! RED format (`a=rtpmap:<pt> red/48000/2`, `a=fmtp:<pt> 111/111`).
3//!
4//! RFC 8854 section 4.2 has a WebRTC endpoint support RED for audio; Chromium and WebKit
5//! offer it with Opus as both the primary and the redundant encoding (the fmtp lists the Opus
6//! payload type twice), the form RFC 2198 section 3 allows ("a copy of the primary MAY be
7//! used as the redundancy").
8//!
9//! - **Send, when.** Negotiating RED does not by itself make the sender use it
10//!   ([`AudioRedundancy`], [`RedAudioBuilder::with_audio_redundancy`]). By default a local
11//!   stream is sent in RED only when its remote description lists the RED format ahead of the
12//!   stream's primary encoding: RFC 3264 sections 5.1 and 6.1 have the formats of an m= line
13//!   "listed in order of preference", and the sender "SHOULD use the format with the highest
14//!   preference"; RFC 2198 section 5 reads a section that leads with `red` as "the sender will
15//!   send redundancy by default, but also may send" the others. libwebrtc decides the same way
16//!   (`WebRtcVoiceSendChannel::SetSendCodecs`: "RED codec needs to be negotiated before the
17//!   actual codec they reference"), and Chromium and WebKit list RED after Opus, in their
18//!   offers and their answers alike, so neither they nor this engine send it between each
19//!   other by default. RFC 8854 section 4.1 recommends Opus's own in-band FEC over RED for
20//!   Opus, and section 8 has FEC sent only for the loss observed or when the application asks:
21//!   [`AudioRedundancy::Always`] is that request.
22//! - **Send, when the loss asks for it.** With [`RedAudioBuilder::with_redundancy_on_loss`]
23//!   (off by default), a stream that negotiated RED and is not otherwise sent in it (under
24//!   [`AudioRedundancy::WhenPreferred`]) goes in RED while the loss its receiver reports is
25//!   0.5% or more ([`RED_AUDIO_LOSS_ON`], smoothed over reports as `FecRate` smooths it), and
26//!   back to the primary once it falls under half that: RFC 8854 section 5, "FEC should only
27//!   be activated if network conditions warrant it", and section 7, "Use of these formats
28//!   when sending ... is RECOMMENDED". Off by default: RED about doubles the audio rate, and
29//!   section 8 warns that when "the loss is caused by network congestion, the additional
30//!   bandwidth used by the redundant data may actually make the situation worse"; the default
31//!   waits for a measurement under congestion.
32//! - **Send, how.** A packet of a local stream sent in RED, whose payload type is the primary
33//!   of the negotiated RED format, leaves as a RED packet: the RED payload type in the header,
34//!   the copies of the last [`RedAudioBuilder::with_redundancy`] primaries (one by default, as
35//!   Chromium sends) before the new primary, the header otherwise the primary's (RFC 2198
36//!   section 3). A primary too large to be wrapped, or of another payload type (comfort noise,
37//!   DTMF), leaves as it is: the receiver negotiated it too. A packet written with a
38//!   [`RedundantEncoding`] (another, lower-bitrate encoding of its audio, RFC 8854 section 4.1:
39//!   "redundant encoding with reduced-bitrate Opus encodings") is carried as that encoding in
40//!   the packets after it instead of a copy.
41//! - **Receive.** A RED packet of a remote stream is taken apart into the packets of its
42//!   blocks (RFC 2198 section 4): the primary with the RED packet's sequence number, marker
43//!   and CSRCs, and the earlier primaries a lost packet carried, recovered from the redundant
44//!   blocks with the sequence numbers they had (one packet per block, as the encoder above and
45//!   Chromium send them), no marker ("the marker bit ... is lost") and the RED packet's CSRCs.
46//!   Nothing is delivered twice (`RedDecoder`). What arrives after this interceptor (the NACK
47//!   generator, the jitter buffer, the application) sees the primary encoding only. Received
48//!   RED is taken apart whatever the [`AudioRedundancy`] setting: the setting is about what
49//!   this side sends, and RFC 8854 section 7 has an endpoint "receive and make use of" the FEC
50//!   formats it indicated.
51//!
52//! # Where it belongs
53//!
54//! [`Slot::Redundancy`](crate::Slot::Redundancy) (10_450). On the write leg it is
55//! application-ward of the NACK responder (4_000) and the FEC encoder (5_000): what is
56//! buffered for retransmission and protected is the RED packet on the wire. On the read leg it
57//! is application-ward of the receiver report (10_000) and the FEC decoder (10_300), which
58//! count and repair the RED packets that arrived, and wire-ward of the NACK generator
59//! (10_600), which then does not ask for a packet RED recovered.
60
61use crate::stream_info::StreamInfo;
62use crate::{Interceptor, Packet, TaggedPacket};
63use bytes::Bytes;
64use rtp::codec::red::{RedDecoder, RedEncoder, RedPacket, parse_red_fmtp};
65use sansio::Protocol;
66use shared::error::Error;
67use std::collections::{HashMap, VecDeque};
68use std::time::Instant;
69
70/// How many earlier primaries a RED packet carries by default: one, as Chromium sends Opus
71/// RED.
72pub const RED_AUDIO_DEFAULT_REDUNDANCY: usize = 1;
73
74/// The largest RED payload the sender builds by default: redundant blocks that would make
75/// the payload larger are left out (an Opus packet is far smaller), so that a RED packet
76/// stays within the path MTU the application sized the primary for, with the header, its
77/// extensions and the SRTP tag.
78pub const RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;
79
80/// The smoothed loss at which a stream sent in RED on loss
81/// ([`RedAudioBuilder::with_redundancy_on_loss`]) goes in RED: the loss under which the FEC
82/// senders send no repair ([`FEC_MIN_LOSS`](crate::FEC_MIN_LOSS)). It goes back to the primary
83/// under half of it.
84pub const RED_AUDIO_LOSS_ON: f64 = crate::cc::fec_rate::MIN_LOSS;
85
86/// Weight of a new receiver report in the smoothed loss (as `FecRate` smooths it).
87const LOSS_WEIGHT: f64 = 0.3;
88
89/// Another encoding of a packet's audio, for the RED packets after it to carry instead of a
90/// copy of the packet (RFC 8854 section 4.1: when multi-packet protection is needed,
91/// "redundant encoding with reduced-bitrate Opus encodings SHOULD be used"; RFC 2198 section 3:
92/// "the redundant encoding shall use significantly less bandwidth"). The engine does not
93/// encode audio: the application's encoder makes it, at the primary's payload type and
94/// timestamp, and puts it on the packet it writes as [`Attribute::Custom`](crate::Attribute::Custom).
95/// One larger than the primary is not used (RFC 2198: it "MUST NOT be higher bandwidth than
96/// the primary"); a stream not sent in RED ignores it.
97///
98/// ```
99/// use bytes::Bytes;
100/// use rtci_interceptor::{Attribute, AttributedPacket, Packet, RedundantEncoding};
101/// use std::sync::Arc;
102///
103/// # let primary = rtp::Packet::default();
104/// let low_bitrate = Bytes::from_static(&[0x08, 0x01, 0x02]);
105/// let message = AttributedPacket::new(Packet::Rtp(primary))
106///     .with(Attribute::Custom(Arc::new(RedundantEncoding::new(low_bitrate))));
107/// # let _ = message;
108/// ```
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub struct RedundantEncoding {
112    /// The payload of the other encoding.
113    pub payload: Bytes,
114}
115
116impl RedundantEncoding {
117    /// `payload` as the redundant encoding of the packet it rides on.
118    pub fn new(payload: Bytes) -> Self {
119        Self { payload }
120    }
121}
122
123/// When a local audio stream whose section negotiated RED (RFC 2198) is sent in RED. Received
124/// RED is taken apart in every case.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub enum AudioRedundancy {
127    /// In RED when the remote description lists the RED format ahead of the stream's primary
128    /// encoding, the remote side's preference (RFC 3264 sections 5.1 and 6.1; libwebrtc's
129    /// rule too). Chromium and WebKit list it after Opus, so a call with them carries plain
130    /// Opus. The default.
131    #[default]
132    WhenPreferred,
133    /// In RED whenever RED is negotiated, whatever its place on the m= line: the application's
134    /// request for redundancy (RFC 8854 section 8). Each packet then carries a copy of the
135    /// one before, about doubling the audio bitrate.
136    Always,
137    /// Never in RED, even when the remote side prefers it (RFC 3264's "SHOULD" set aside).
138    Never,
139}
140
141/// Builder for [`RedAudioInterceptor`].
142#[derive(Debug, Clone)]
143pub struct RedAudioBuilder {
144    redundancy: usize,
145    max_payload_size: usize,
146    audio_redundancy: AudioRedundancy,
147    redundancy_on_loss: bool,
148}
149
150impl Default for RedAudioBuilder {
151    fn default() -> Self {
152        Self {
153            redundancy: RED_AUDIO_DEFAULT_REDUNDANCY,
154            max_payload_size: RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE,
155            audio_redundancy: AudioRedundancy::default(),
156            redundancy_on_loss: false,
157        }
158    }
159}
160
161impl RedAudioBuilder {
162    /// One earlier primary per packet, payloads of at most
163    /// [`RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE`] octets, sent in RED when the remote side prefers
164    /// it ([`AudioRedundancy::WhenPreferred`]).
165    pub fn new() -> Self {
166        Self::default()
167    }
168
169    /// When a local stream that negotiated RED is sent in RED; see [`AudioRedundancy`].
170    pub fn with_audio_redundancy(mut self, audio_redundancy: AudioRedundancy) -> Self {
171        self.audio_redundancy = audio_redundancy;
172        self
173    }
174
175    /// How many earlier primaries each RED packet carries (0 sends RED packets with the
176    /// primary alone).
177    pub fn with_redundancy(mut self, redundancy: usize) -> Self {
178        self.redundancy = redundancy;
179        self
180    }
181
182    /// The largest RED payload built; redundant blocks that would exceed it are left out.
183    pub fn with_max_payload_size(mut self, max_payload_size: usize) -> Self {
184        self.max_payload_size = max_payload_size;
185        self
186    }
187
188    /// Under [`AudioRedundancy::WhenPreferred`], also send a stream that negotiated RED, and
189    /// whose remote side did not prefer it, in RED while the loss its receiver reports is at
190    /// least [`RED_AUDIO_LOSS_ON`] (smoothed), back to the primary under half of it (RFC 8854
191    /// sections 5, 7 and 8). Off by default: see the module documentation.
192    pub fn with_redundancy_on_loss(mut self, redundancy_on_loss: bool) -> Self {
193        self.redundancy_on_loss = redundancy_on_loss;
194        self
195    }
196
197    /// The interceptor.
198    pub fn build(self) -> RedAudioInterceptor {
199        RedAudioInterceptor {
200            config: self,
201            senders: HashMap::new(),
202            receivers: HashMap::new(),
203            read_queue: VecDeque::new(),
204            write_queue: VecDeque::new(),
205        }
206    }
207}
208
209struct SendStream {
210    red_payload_type: u8,
211    primary_payload_type: u8,
212    encoder: RedEncoder,
213    /// The sequence number of the last primary wrapped.
214    last_sequence_number: Option<u16>,
215    /// Sent in RED only while `lossy` ([`RedAudioBuilder::with_redundancy_on_loss`]).
216    on_loss: bool,
217    /// The loss the receiver reports, smoothed.
218    loss: Option<f64>,
219    /// Whether the loss asks for RED: on at [`RED_AUDIO_LOSS_ON`], off under half of it.
220    lossy: bool,
221}
222
223impl SendStream {
224    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for this stream.
225    fn on_fraction_lost(&mut self, fraction_lost: u8) {
226        let sample = f64::from(fraction_lost) / 256.0;
227        let loss = match self.loss {
228            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
229            None => sample,
230        };
231        self.loss = Some(loss);
232        self.lossy = if self.lossy {
233            loss >= RED_AUDIO_LOSS_ON / 2.0
234        } else {
235            loss >= RED_AUDIO_LOSS_ON
236        };
237    }
238
239    /// Whether the packets written now go in RED.
240    fn sends_red(&self) -> bool {
241        !self.on_loss || self.lossy
242    }
243}
244
245struct ReceiveStream {
246    red_payload_type: u8,
247    decoder: RedDecoder,
248    /// The ids of the stream's audio level extensions (RFC 6464 `ssrc-audio-level`, RFC 6465
249    /// `csrc-audio-level`): what a packet rebuilt from a redundant block takes from the RED
250    /// packet that carried it, as an approximation (RFC 8854 section 4.1).
251    level_extensions: Vec<u8>,
252}
253
254/// The ids `info` negotiated the audio level extensions under.
255fn level_extension_ids(info: &StreamInfo) -> Vec<u8> {
256    info.rtp_header_extensions
257        .iter()
258        .filter(|extension| {
259            extension.uri == rtp::extension::AUDIO_LEVEL_URI
260                || extension.uri == rtp::extension::CSRC_AUDIO_LEVEL_URI
261        })
262        .filter_map(|extension| u8::try_from(extension.id).ok())
263        .collect()
264}
265
266/// RFC 2198 audio redundancy for the streams that negotiated it; see the module
267/// documentation.
268pub struct RedAudioInterceptor {
269    config: RedAudioBuilder,
270    senders: HashMap<u32, SendStream>,
271    receivers: HashMap<u32, ReceiveStream>,
272    read_queue: VecDeque<TaggedPacket>,
273    write_queue: VecDeque<TaggedPacket>,
274}
275
276impl Default for RedAudioInterceptor {
277    fn default() -> Self {
278        RedAudioBuilder::new().build()
279    }
280}
281
282/// The RED format of an audio stream's m= section and its primary encoding: a format named
283/// `red` (RFC 2198 section 5) whose fmtp lists only `primary`, the stream's payload type, as
284/// the primary and every redundant encoding (the copy-of-the-primary form this interceptor
285/// sends and Chromium and WebKit offer). `None` for a video stream or a section without one.
286fn negotiated_red(info: &StreamInfo, primary: u8) -> Option<u8> {
287    if !info.mime_type.to_ascii_lowercase().starts_with("audio/") {
288        return None;
289    }
290    info.section_mime_types
291        .iter()
292        .filter(|(_, mime_type)| mime_type.to_ascii_lowercase().ends_with("/red"))
293        .find_map(|(payload_type, _)| {
294            let fmtp = info
295                .section_fmtp_lines
296                .iter()
297                .find(|(pt, _)| pt == payload_type)
298                .map(|(_, fmtp)| fmtp.trim())?;
299            let encodings = parse_red_fmtp(fmtp).ok()?;
300            encodings
301                .iter()
302                .all(|pt| *pt == primary)
303                .then_some(*payload_type)
304        })
305}
306
307/// Whether the stream's section lists the RED format `red` ahead of the stream's own payload
308/// type: the remote side prefers redundancy (RFC 3264 sections 5.1 and 6.1). The section's
309/// formats are in the order of the m= line of the description whose numbering the stream
310/// uses, the remote one for a local stream.
311fn red_is_preferred(info: &StreamInfo, red: u8) -> bool {
312    let position = |payload_type: u8| {
313        info.section_mime_types
314            .iter()
315            .position(|(pt, _)| *pt == payload_type)
316    };
317    matches!(
318        (position(red), position(info.payload_type)),
319        (Some(red), Some(primary)) if red < primary
320    )
321}
322
323impl RedAudioInterceptor {
324    /// The RED payload type a local stream may be sent with, and whether only while the loss
325    /// asks for it ([`RedAudioBuilder::with_redundancy_on_loss`]); `None` to send it as it is.
326    fn red_mode(&self, info: &StreamInfo) -> Option<(u8, bool)> {
327        if let Some(red) = self.red_to_send(info) {
328            return Some((red, false));
329        }
330        if self.config.redundancy_on_loss
331            && self.config.audio_redundancy == AudioRedundancy::WhenPreferred
332        {
333            return negotiated_red(info, info.payload_type).map(|red| (red, true));
334        }
335        None
336    }
337
338    /// The RED payload type a local stream is sent with under the builder's
339    /// [`AudioRedundancy`], or `None` to send it as it is.
340    fn red_to_send(&self, info: &StreamInfo) -> Option<u8> {
341        let red = negotiated_red(info, info.payload_type)?;
342        match self.config.audio_redundancy {
343            AudioRedundancy::Always => Some(red),
344            AudioRedundancy::WhenPreferred => red_is_preferred(info, red).then_some(red),
345            AudioRedundancy::Never => None,
346        }
347    }
348
349    /// The RTP packets of the blocks of the RED packet `packet` (RFC 2198 section 4), each
350    /// not yet delivered, the recovered ones first.
351    fn take_apart(stream: &mut ReceiveStream, packet: &rtp::Packet) -> Vec<rtp::Packet> {
352        // The timestamps of the redundant blocks in header order, oldest first: block `i` of
353        // `n` was the primary of the packet `n - i` before this one.
354        let redundant: Vec<u32> = match RedPacket::parse(&packet.payload) {
355            Ok(red) => red
356                .redundant()
357                .iter()
358                .map(|block| block.timestamp(packet.header.timestamp))
359                .collect(),
360            Err(_) => return vec![],
361        };
362        let Ok(blocks) = stream.decoder.decode_rtp(packet) else {
363            return vec![];
364        };
365        blocks
366            .into_iter()
367            .map(|recovered| {
368                let mut header = packet.header.clone();
369                header.payload_type = recovered.block.payload_type;
370                header.timestamp = recovered.block.timestamp;
371                header.marker = recovered.marker;
372                header.csrc = recovered.csrc;
373                if !recovered.block.primary {
374                    let back = redundant
375                        .iter()
376                        .position(|ts| *ts == recovered.block.timestamp)
377                        .map_or(1, |i| redundant.len() - i);
378                    header.sequence_number = header.sequence_number.wrapping_sub(back as u16);
379                    // The extensions and padding were the RED packet's. RFC 8854 section 4.1:
380                    // the header parts RED cannot recover, "RTP header extensions like those
381                    // specified in [RFC6464] and [RFC6465]", are approximated "using an
382                    // approach similar to those described in [RFC2198], Section 4": as RFC
383                    // 2198 applies the RED packet's CSRCs to the rebuilt data, the rebuilt
384                    // packet takes the RED packet's audio levels (one packet later in time,
385                    // the nearest measure there is). Every other extension is left out.
386                    let levels: Vec<(u8, bytes::Bytes)> = stream
387                        .level_extensions
388                        .iter()
389                        .filter_map(|id| packet.header.get_extension(*id).map(|v| (*id, v)))
390                        .collect();
391                    header.extension = false;
392                    header.extensions.clear();
393                    header.extension_profile = 0;
394                    header.extensions_padding = 0;
395                    for (id, value) in levels {
396                        // The RED packet carried it in this form, so it fits.
397                        let _ = header.set_extension(id, value);
398                    }
399                }
400                header.padding = false;
401                rtp::Packet {
402                    header,
403                    payload: recovered.block.data,
404                }
405            })
406            .collect()
407    }
408}
409
410impl Protocol<TaggedPacket, TaggedPacket, ()> for RedAudioInterceptor {
411    type Rout = TaggedPacket;
412    type Wout = TaggedPacket;
413    type Eout = ();
414    type Error = Error;
415    type Time = Instant;
416
417    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
418        // The receiver reports of the streams sent in RED on loss.
419        if let Packet::Rtcp(packets) = &msg.message.packet
420            && self.senders.values().any(|stream| stream.on_loss)
421        {
422            for packet in packets {
423                let any = packet.as_any();
424                let reports = if let Some(rr) =
425                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
426                {
427                    &rr.reports
428                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
429                    &sr.reports
430                } else {
431                    continue;
432                };
433                for report in reports {
434                    if let Some(stream) = self.senders.get_mut(&report.ssrc)
435                        && stream.on_loss
436                    {
437                        stream.on_fraction_lost(report.fraction_lost);
438                    }
439                }
440            }
441        }
442        let red = match &msg.message.packet {
443            Packet::Rtp(packet) => self
444                .receivers
445                .get(&packet.header.ssrc)
446                .is_some_and(|stream| packet.header.payload_type == stream.red_payload_type),
447            Packet::Rtcp(_) => false,
448        };
449        if !red {
450            self.read_queue.push_back(msg);
451            return Ok(());
452        }
453        let Packet::Rtp(packet) = &msg.message.packet else {
454            return Ok(());
455        };
456        let Some(stream) = self.receivers.get_mut(&packet.header.ssrc) else {
457            return Ok(());
458        };
459        // A malformed RED payload, or one whose every block was delivered: nothing goes on.
460        for media in Self::take_apart(stream, packet) {
461            self.read_queue.push_back(TaggedPacket {
462                now: msg.now,
463                transport: msg.transport,
464                message: crate::AttributedPacket {
465                    attributes: msg.message.attributes.clone(),
466                    packet: Packet::Rtp(media),
467                },
468            });
469        }
470        Ok(())
471    }
472
473    fn poll_read(&mut self) -> Option<Self::Rout> {
474        self.read_queue.pop_front()
475    }
476
477    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
478        let redundant = msg
479            .message
480            .custom::<RedundantEncoding>()
481            .map(|redundant| redundant.payload.clone());
482        if let Packet::Rtp(packet) = &mut msg.message.packet
483            && !packet.payload.is_empty()
484            && let Some(stream) = self.senders.get_mut(&packet.header.ssrc)
485            && packet.header.payload_type == stream.primary_payload_type
486        {
487            // The receiver numbers a recovered block one packet back per block (RFC 2198
488            // section 4 leaves the sequence number of redundant data to it): a copy goes only
489            // into the packet right after the one it was the primary of.
490            if stream
491                .last_sequence_number
492                .is_some_and(|last| last.wrapping_add(1) != packet.header.sequence_number)
493            {
494                stream.encoder.reset();
495            }
496            stream.last_sequence_number = Some(packet.header.sequence_number);
497            if stream.sends_red() {
498                // A primary that does not fit a RED payload goes as it is.
499                let red = match redundant {
500                    Some(redundant) => stream.encoder.encode_rtp_with_redundant(
501                        stream.red_payload_type,
502                        packet,
503                        redundant,
504                    ),
505                    None => stream.encoder.encode_rtp(stream.red_payload_type, packet),
506                };
507                if let Ok(red) = red {
508                    *packet = red;
509                }
510            } else {
511                // Not in RED while the loss does not ask for it: the first RED packet after
512                // carries no copy of a packet that left as the primary.
513                stream.encoder.reset();
514            }
515        }
516        self.write_queue.push_back(msg);
517        Ok(())
518    }
519
520    fn poll_write(&mut self) -> Option<Self::Wout> {
521        self.write_queue.pop_front()
522    }
523
524    fn handle_timeout(&mut self, _now: Self::Time) -> Result<(), Self::Error> {
525        Ok(())
526    }
527
528    fn poll_timeout(&mut self) -> Option<Self::Time> {
529        None
530    }
531}
532
533impl Interceptor for RedAudioInterceptor {
534    fn bind_local_stream(&mut self, info: &StreamInfo) {
535        match self.red_mode(info) {
536            Some((red_payload_type, on_loss)) => {
537                let stream = self.senders.entry(info.ssrc).or_insert(SendStream {
538                    red_payload_type,
539                    primary_payload_type: info.payload_type,
540                    encoder: RedEncoder::new(self.config.redundancy, self.config.max_payload_size),
541                    last_sequence_number: None,
542                    on_loss,
543                    loss: None,
544                    lossy: false,
545                });
546                stream.on_loss = on_loss;
547                if (stream.red_payload_type, stream.primary_payload_type)
548                    != (red_payload_type, info.payload_type)
549                {
550                    stream.red_payload_type = red_payload_type;
551                    stream.primary_payload_type = info.payload_type;
552                    stream.encoder.reset();
553                }
554            }
555            None => {
556                self.senders.remove(&info.ssrc);
557            }
558        }
559    }
560
561    fn unbind_local_stream(&mut self, info: &StreamInfo) {
562        self.senders.remove(&info.ssrc);
563    }
564
565    fn bind_remote_stream(&mut self, info: &StreamInfo) {
566        match negotiated_red(info, info.payload_type) {
567            Some(red_payload_type) => {
568                let stream = self.receivers.entry(info.ssrc).or_insert(ReceiveStream {
569                    red_payload_type,
570                    decoder: RedDecoder::default(),
571                    level_extensions: vec![],
572                });
573                stream.red_payload_type = red_payload_type;
574                stream.level_extensions = level_extension_ids(info);
575            }
576            None => {
577                self.receivers.remove(&info.ssrc);
578            }
579        }
580    }
581
582    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
583        self.receivers.remove(&info.ssrc);
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use crate::{AttributedPacket, TaggedPacket};
591    use bytes::Bytes;
592    use shared::TransportContext;
593
594    const OPUS: u8 = 111;
595    const RED: u8 = 63;
596
597    /// A stream whose section lists Opus, then RED (Chromium's and WebKit's order).
598    fn info(ssrc: u32, red_fmtp: &str) -> StreamInfo {
599        StreamInfo {
600            ssrc,
601            payload_type: OPUS,
602            mime_type: "audio/opus".to_owned(),
603            clock_rate: 48_000,
604            channels: 2,
605            section_mime_types: vec![
606                (OPUS, "audio/opus".to_owned()),
607                (RED, "audio/red".to_owned()),
608            ],
609            section_fmtp_lines: vec![
610                (OPUS, "minptime=10;useinbandfec=1".to_owned()),
611                (RED, red_fmtp.to_owned()),
612            ],
613            ..Default::default()
614        }
615    }
616
617    /// [`info`] with RED listed ahead of Opus: the remote side prefers redundancy.
618    fn info_red_first(ssrc: u32, red_fmtp: &str) -> StreamInfo {
619        let mut info = info(ssrc, red_fmtp);
620        info.section_mime_types.reverse();
621        info.section_fmtp_lines.reverse();
622        info
623    }
624
625    /// The payload type the first packet of a fresh stream leaves `sender` with.
626    fn sent_payload_type(sender: &mut RedAudioInterceptor, ssrc: u32) -> u8 {
627        sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
628        rtp(sender.poll_write().unwrap()).header.payload_type
629    }
630
631    fn opus(ssrc: u32, sequence_number: u16, payload: &'static [u8]) -> TaggedPacket {
632        TaggedPacket {
633            now: Instant::now(),
634            transport: TransportContext::default(),
635            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
636                header: rtp::header::Header {
637                    version: 2,
638                    ssrc,
639                    payload_type: OPUS,
640                    sequence_number,
641                    timestamp: u32::from(sequence_number) * 960,
642                    marker: sequence_number == 1,
643                    ..Default::default()
644                },
645                payload: Bytes::from_static(payload),
646            })),
647        }
648    }
649
650    fn rtp(msg: TaggedPacket) -> rtp::Packet {
651        match msg.message.packet {
652            Packet::Rtp(packet) => packet,
653            Packet::Rtcp(_) => panic!("RTP expected"),
654        }
655    }
656
657    /// RFC 2198 sections 3 and 4 through one sender and one receiver: the sender, whose remote
658    /// side lists RED first, wraps each Opus packet with a copy of the one before; the receiver
659    /// gives back each primary, and, for the packet lost on the way, the copy the next packet
660    /// carried, with its sequence number and timestamp and no marker.
661    #[test]
662    fn red_packets_carry_the_previous_primary_and_recover_a_loss() {
663        let mut sender = RedAudioBuilder::new().build();
664        let mut receiver = RedAudioBuilder::new().build();
665        sender.bind_local_stream(&info_red_first(1, "111/111"));
666        receiver.bind_remote_stream(&info(1, "111/111"));
667
668        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
669        let mut wire = vec![];
670        for (i, payload) in payloads.iter().enumerate() {
671            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
672            let red = rtp(sender.poll_write().unwrap());
673            assert_eq!(red.header.payload_type, RED);
674            assert_eq!(red.header.sequence_number, i as u16 + 1);
675            let blocks = RedPacket::parse(&red.payload).unwrap();
676            assert_eq!(blocks.primary().data.as_ref(), *payload);
677            assert_eq!(blocks.redundant().len(), usize::from(i > 0));
678            wire.push(red);
679        }
680        // The third packet is lost.
681        let mut delivered = vec![];
682        for (i, red) in wire.into_iter().enumerate() {
683            if i == 2 {
684                continue;
685            }
686            receiver
687                .handle_read(TaggedPacket {
688                    now: Instant::now(),
689                    transport: TransportContext::default(),
690                    message: AttributedPacket::new(Packet::Rtp(red)),
691                })
692                .unwrap();
693            while let Some(out) = receiver.poll_read() {
694                delivered.push(rtp(out));
695            }
696        }
697        let got: Vec<(u16, u32, u8, bool, &[u8])> = delivered
698            .iter()
699            .map(|p| {
700                (
701                    p.header.sequence_number,
702                    p.header.timestamp,
703                    p.header.payload_type,
704                    p.header.marker,
705                    p.payload.as_ref(),
706                )
707            })
708            .collect();
709        assert_eq!(
710            got,
711            vec![
712                (1, 960, OPUS, true, b"one".as_ref()),
713                (2, 1920, OPUS, false, b"two".as_ref()),
714                (3, 2880, OPUS, false, b"three".as_ref()),
715                (4, 3840, OPUS, false, b"four".as_ref()),
716            ]
717        );
718    }
719
720    /// Sends `payloads` through `sender`, each RED packet given header extensions by `extend`,
721    /// loses the packets at `lost` (indices) and returns what `receiver` delivered.
722    fn through(
723        sender: &mut RedAudioInterceptor,
724        receiver: &mut RedAudioInterceptor,
725        payloads: &[&'static [u8]],
726        lost: &[usize],
727        extend: impl Fn(usize, &mut rtp::header::Header),
728    ) -> Vec<rtp::Packet> {
729        let mut delivered = vec![];
730        for (i, payload) in payloads.iter().enumerate() {
731            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
732            let mut red = rtp(sender.poll_write().unwrap());
733            extend(i, &mut red.header);
734            if lost.contains(&i) {
735                continue;
736            }
737            receiver
738                .handle_read(TaggedPacket {
739                    now: Instant::now(),
740                    transport: TransportContext::default(),
741                    message: AttributedPacket::new(Packet::Rtp(red)),
742                })
743                .unwrap();
744            while let Some(out) = receiver.poll_read() {
745                delivered.push(rtp(out));
746            }
747        }
748        delivered
749    }
750
751    /// RFC 8854 section 4.1: "the recommended mechanisms do not allow recovery of parts of the
752    /// RTP header that may be important in certain audio applications, e.g., CSRCs and RTP
753    /// header extensions like those specified in [RFC6464] and [RFC6465]. Implementations
754    /// SHOULD account for this and attempt to approximate this information, using an approach
755    /// similar to those described in [RFC2198], Section 4". A packet rebuilt from a redundant
756    /// block takes the audio levels of the RED packet that carried it (as RFC 2198 section 4
757    /// applies that packet's CSRCs), and no other extension of it.
758    #[test]
759    fn a_rebuilt_packet_takes_the_audio_levels_of_the_red_packet_that_carried_it() {
760        const LEVEL: u8 = 1;
761        const CSRC_LEVELS: u8 = 2;
762        const OTHER: u8 = 3;
763        let mut sender = RedAudioBuilder::new().build();
764        let mut receiver = RedAudioBuilder::new().build();
765        sender.bind_local_stream(&info_red_first(1, "111/111"));
766        let mut remote = info(1, "111/111");
767        for (uri, id) in [
768            (rtp::extension::AUDIO_LEVEL_URI, LEVEL),
769            (rtp::extension::CSRC_AUDIO_LEVEL_URI, CSRC_LEVELS),
770            (
771                "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
772                OTHER,
773            ),
774        ] {
775            remote
776                .rtp_header_extensions
777                .push(crate::RTPHeaderExtension {
778                    uri: uri.to_owned(),
779                    id: u16::from(id),
780                });
781        }
782        receiver.bind_remote_stream(&remote);
783
784        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
785        let delivered = through(&mut sender, &mut receiver, &payloads, &[2], |i, header| {
786            header.csrc = vec![77];
787            let level = 0x80 | (10 + i as u8);
788            header
789                .set_extension(LEVEL, Bytes::from(vec![level]))
790                .unwrap();
791            header
792                .set_extension(CSRC_LEVELS, Bytes::from(vec![20 + i as u8]))
793                .unwrap();
794            header
795                .set_extension(OTHER, Bytes::from(vec![1, 2, 3]))
796                .unwrap();
797        });
798        let rebuilt = delivered
799            .iter()
800            .find(|p| p.header.sequence_number == 3)
801            .expect("the lost packet is rebuilt");
802        assert_eq!(rebuilt.payload.as_ref(), b"three");
803        assert_eq!(
804            rebuilt.header.get_extension(LEVEL).as_deref(),
805            Some([0x80 | 13].as_ref()),
806            "the audio level of the packet that carried it"
807        );
808        assert_eq!(
809            rebuilt.header.get_extension(CSRC_LEVELS).as_deref(),
810            Some([23].as_ref())
811        );
812        assert_eq!(rebuilt.header.csrc, vec![77]);
813        assert_eq!(rebuilt.header.get_extension(OTHER), None, "nothing else");
814        // The primaries keep their own extensions.
815        let primary = delivered
816            .iter()
817            .find(|p| p.header.sequence_number == 4)
818            .unwrap();
819        assert_eq!(
820            primary.header.get_extension(LEVEL).as_deref(),
821            Some([0x80 | 13].as_ref())
822        );
823        assert!(primary.header.get_extension(OTHER).is_some());
824    }
825
826    /// RFC 8854 section 4.1: "if multi-packet protection is needed, the aforementioned
827    /// redundant encoding ... SHOULD be used instead". With two redundant blocks per packet
828    /// (`with_redundancy(2)`) two consecutive losses are both rebuilt from the packet after
829    /// them; with one, only the second of them.
830    #[test]
831    fn two_redundant_blocks_rebuild_two_consecutive_losses() {
832        let payloads: [&'static [u8]; 5] = [b"one", b"two", b"three", b"four", b"five"];
833        for (redundancy, rebuilt) in [(2usize, vec![2u16, 3]), (1, vec![3])] {
834            let mut sender = RedAudioBuilder::new().with_redundancy(redundancy).build();
835            let mut receiver = RedAudioBuilder::new().build();
836            sender.bind_local_stream(&info_red_first(1, "111/111/111"));
837            receiver.bind_remote_stream(&info(1, "111/111/111"));
838            let delivered = through(&mut sender, &mut receiver, &payloads, &[1, 2], |_, _| {});
839            let got: Vec<u16> = delivered
840                .iter()
841                .map(|p| p.header.sequence_number)
842                .filter(|seq| [2, 3].contains(seq))
843                .collect();
844            assert_eq!(got, rebuilt, "redundancy {redundancy}");
845            for packet in &delivered {
846                assert_eq!(
847                    packet.payload.as_ref(),
848                    payloads[usize::from(packet.header.sequence_number) - 1]
849                );
850            }
851        }
852    }
853
854    /// A receiver report on `ssrc` with `fraction_lost` (in 1/256).
855    fn report(fraction_lost: u8, ssrc: u32) -> TaggedPacket {
856        TaggedPacket {
857            now: Instant::now(),
858            transport: TransportContext::default(),
859            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
860                rtcp::receiver_report::ReceiverReport {
861                    ssrc: 0x7777,
862                    reports: vec![rtcp::reception_report::ReceptionReport {
863                        ssrc,
864                        fraction_lost,
865                        ..Default::default()
866                    }],
867                    ..Default::default()
868                },
869            )])),
870        }
871    }
872
873    /// RFC 8854 section 5 ("FEC should only be activated if network conditions warrant it")
874    /// and section 7 ("Use of these formats when sending ... is RECOMMENDED"): with
875    /// `with_redundancy_on_loss`, a stream whose remote side lists RED after Opus goes as Opus
876    /// until its receiver reports loss of 0.5% or more (smoothed), then in RED, and back to
877    /// Opus once the smoothed loss is under half of that. Another stream's report changes
878    /// nothing; without the setting the loss changes nothing.
879    #[test]
880    fn with_redundancy_on_loss_red_follows_the_reported_loss() {
881        let mut sender = RedAudioBuilder::new().with_redundancy_on_loss(true).build();
882        sender.bind_local_stream(&info(1, "111/111"));
883        let mut seq = 0u16;
884        let mut send = |sender: &mut RedAudioInterceptor| {
885            seq += 1;
886            sender.handle_write(opus(1, seq, b"opus")).unwrap();
887            rtp(sender.poll_write().unwrap())
888        };
889        let read = |sender: &mut RedAudioInterceptor, msg: TaggedPacket| {
890            sender.handle_read(msg).unwrap();
891            while sender.poll_read().is_some() {}
892        };
893        assert_eq!(
894            send(&mut sender).header.payload_type,
895            OPUS,
896            "no loss reported"
897        );
898        read(&mut sender, report(0, 1));
899        assert_eq!(send(&mut sender).header.payload_type, OPUS, "no loss");
900        read(&mut sender, report(64, 2));
901        assert_eq!(
902            send(&mut sender).header.payload_type,
903            OPUS,
904            "another stream's loss"
905        );
906        read(&mut sender, report(3, 1)); // 0.3 x 1.2%: 0.35%
907        assert_eq!(send(&mut sender).header.payload_type, OPUS, "under 0.5%");
908        read(&mut sender, report(13, 1)); // 5%: smoothed 1.7%
909        let red = send(&mut sender);
910        assert_eq!(red.header.payload_type, RED, "the loss turned RED on");
911        assert!(
912            RedPacket::parse(&red.payload)
913                .unwrap()
914                .redundant()
915                .is_empty(),
916            "no copy of a packet that left as Opus"
917        );
918        let red = send(&mut sender);
919        assert_eq!(red.header.payload_type, RED);
920        assert_eq!(RedPacket::parse(&red.payload).unwrap().redundant().len(), 1);
921        // Reports of no loss: 1.7% x 0.7^n; over 0.25% until the sixth.
922        for n in 1..=6 {
923            read(&mut sender, report(0, 1));
924            let expected = if n < 6 { RED } else { OPUS };
925            assert_eq!(
926                send(&mut sender).header.payload_type,
927                expected,
928                "report {n}"
929            );
930        }
931
932        // Without the setting, or with another policy, the loss decides nothing.
933        for (builder, expected) in [
934            (RedAudioBuilder::new(), OPUS),
935            (
936                RedAudioBuilder::new()
937                    .with_redundancy_on_loss(true)
938                    .with_audio_redundancy(AudioRedundancy::Never),
939                OPUS,
940            ),
941            (
942                RedAudioBuilder::new()
943                    .with_redundancy_on_loss(true)
944                    .with_audio_redundancy(AudioRedundancy::Always),
945                RED,
946            ),
947        ] {
948            let mut sender = builder.build();
949            sender.bind_local_stream(&info(1, "111/111"));
950            assert_eq!(sent_payload_type(&mut sender, 1), expected);
951            for _ in 0..4 {
952                sender.handle_read(report(128, 1)).unwrap();
953                while sender.poll_read().is_some() {}
954            }
955            sender.handle_write(opus(1, 2, b"x")).unwrap();
956            assert_eq!(
957                rtp(sender.poll_write().unwrap()).header.payload_type,
958                expected
959            );
960        }
961    }
962
963    /// RFC 8854 section 4.1: "redundant encoding with reduced-bitrate Opus encodings": a packet
964    /// written with a `RedundantEncoding` is carried as that encoding in the RED packets after
965    /// it, and a receiver that lost it rebuilds that encoding. One larger than the primary is
966    /// not used (RFC 2198 section 3: "MUST NOT be higher bandwidth than the primary").
967    #[test]
968    fn a_lower_bitrate_encoding_supplied_with_a_packet_is_the_copy_the_next_packet_carries() {
969        let mut sender = RedAudioBuilder::new().with_redundancy(2).build();
970        let mut receiver = RedAudioBuilder::new().build();
971        sender.bind_local_stream(&info_red_first(1, "111/111/111"));
972        receiver.bind_remote_stream(&info(1, "111/111/111"));
973        let with = |mut msg: TaggedPacket, redundant: &'static [u8]| {
974            msg.message
975                .add(crate::Attribute::Custom(std::sync::Arc::new(
976                    RedundantEncoding::new(Bytes::from_static(redundant)),
977                )));
978            msg
979        };
980        let packets = [
981            with(opus(1, 1, b"primary one"), b"low1"),
982            with(opus(1, 2, b"two"), b"larger than two"),
983            opus(1, 3, b"three"),
984        ];
985        let mut wire = vec![];
986        for packet in packets {
987            sender.handle_write(packet).unwrap();
988            wire.push(rtp(sender.poll_write().unwrap()));
989        }
990        let third = RedPacket::parse(&wire[2].payload).unwrap();
991        let copies: Vec<&[u8]> = third
992            .redundant()
993            .iter()
994            .map(|block| block.data.as_ref())
995            .collect();
996        assert_eq!(copies, vec![b"low1".as_ref(), b"two".as_ref()]);
997        // The first two are lost: the third rebuilds the low-bitrate first and the second.
998        receiver
999            .handle_read(TaggedPacket {
1000                now: Instant::now(),
1001                transport: TransportContext::default(),
1002                message: AttributedPacket::new(Packet::Rtp(wire[2].clone())),
1003            })
1004            .unwrap();
1005        let mut delivered = vec![];
1006        while let Some(out) = receiver.poll_read() {
1007            let packet = rtp(out);
1008            delivered.push((packet.header.sequence_number, packet.payload));
1009        }
1010        assert_eq!(
1011            delivered,
1012            vec![
1013                (1, Bytes::from_static(b"low1")),
1014                (2, Bytes::from_static(b"two")),
1015                (3, Bytes::from_static(b"three")),
1016            ]
1017        );
1018    }
1019
1020    /// RFC 8854 section 4.1: "When using constant-bitrate codecs, e.g., PCMU [RFC5391],
1021    /// redundant encoding MAY be used". A PCMU stream whose section negotiated `red/8000`
1022    /// naming PCMU (an application's registration: the default codecs offer RED for Opus
1023    /// only, the clause warning that it "will result in a potentially significant bitrate
1024    /// increase") is sent in RED and a lost packet comes back from the next one.
1025    #[test]
1026    fn a_constant_bitrate_codec_gets_redundancy_when_its_section_negotiated_red() {
1027        const PCMU: u8 = 0;
1028        const RED_8K: u8 = 98;
1029        let pcmu = |red_first: bool| {
1030            let mut formats = vec![
1031                (PCMU, "audio/PCMU".to_owned()),
1032                (RED_8K, "audio/red".to_owned()),
1033            ];
1034            if red_first {
1035                formats.reverse();
1036            }
1037            StreamInfo {
1038                ssrc: 1,
1039                payload_type: PCMU,
1040                mime_type: "audio/PCMU".to_owned(),
1041                clock_rate: 8_000,
1042                channels: 1,
1043                section_mime_types: formats,
1044                section_fmtp_lines: vec![(RED_8K, "0/0".to_owned())],
1045                ..Default::default()
1046            }
1047        };
1048        let mut sender = RedAudioBuilder::new().build();
1049        let mut receiver = RedAudioBuilder::new().build();
1050        sender.bind_local_stream(&pcmu(true));
1051        receiver.bind_remote_stream(&pcmu(false));
1052        let mut delivered = vec![];
1053        for (i, payload) in [b"aaaa", b"bbbb", b"cccc", b"dddd"].iter().enumerate() {
1054            let mut packet = opus(1, i as u16 + 1, payload.as_slice());
1055            if let Packet::Rtp(rtp) = &mut packet.message.packet {
1056                rtp.header.payload_type = PCMU;
1057                rtp.header.timestamp = u32::from(rtp.header.sequence_number) * 160;
1058            }
1059            sender.handle_write(packet).unwrap();
1060            let red = rtp(sender.poll_write().unwrap());
1061            assert_eq!(red.header.payload_type, RED_8K);
1062            if i == 1 {
1063                continue;
1064            }
1065            receiver
1066                .handle_read(TaggedPacket {
1067                    now: Instant::now(),
1068                    transport: TransportContext::default(),
1069                    message: AttributedPacket::new(Packet::Rtp(red)),
1070                })
1071                .unwrap();
1072            while let Some(out) = receiver.poll_read() {
1073                delivered.push(rtp(out));
1074            }
1075        }
1076        let got: Vec<(u16, u8, &[u8])> = delivered
1077            .iter()
1078            .map(|p| {
1079                (
1080                    p.header.sequence_number,
1081                    p.header.payload_type,
1082                    p.payload.as_ref(),
1083                )
1084            })
1085            .collect();
1086        assert_eq!(
1087            got,
1088            vec![
1089                (1, PCMU, b"aaaa".as_ref()),
1090                (2, PCMU, b"bbbb".as_ref()),
1091                (3, PCMU, b"cccc".as_ref()),
1092                (4, PCMU, b"dddd".as_ref()),
1093            ]
1094        );
1095    }
1096
1097    /// Only a stream whose section negotiated a RED format of its own encoding is touched: a
1098    /// stream without one, and a packet of another payload type, pass as they are.
1099    #[test]
1100    fn without_a_negotiated_red_format_packets_pass_unchanged() {
1101        let mut sender = RedAudioBuilder::new()
1102            .with_audio_redundancy(AudioRedundancy::Always)
1103            .build();
1104        sender.bind_local_stream(&StreamInfo {
1105            section_mime_types: vec![(OPUS, "audio/opus".to_owned())],
1106            section_fmtp_lines: vec![(OPUS, String::new())],
1107            ..info(1, "")
1108        });
1109        sender.bind_local_stream(&info(2, "0/0"));
1110        sender.bind_local_stream(&info(3, "111/111"));
1111        for ssrc in [1, 2] {
1112            sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
1113            assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, OPUS);
1114        }
1115        let mut dtmf = opus(3, 1, b"x");
1116        if let Packet::Rtp(p) = &mut dtmf.message.packet {
1117            p.header.payload_type = 126;
1118        }
1119        sender.handle_write(dtmf).unwrap();
1120        assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, 126);
1121    }
1122
1123    /// RFC 3264 sections 5.1 and 6.1: the formats of an m= line are in order of preference and
1124    /// the sender "SHOULD use the format with the highest preference". By default
1125    /// ([`AudioRedundancy::WhenPreferred`]) a stream goes in RED only when its section lists
1126    /// RED ahead of Opus; `Always` sends RED in either order, `Never` in neither.
1127    #[test]
1128    fn red_is_sent_by_the_remote_order_unless_the_application_decides() {
1129        let cases = [
1130            (AudioRedundancy::WhenPreferred, false, OPUS),
1131            (AudioRedundancy::WhenPreferred, true, RED),
1132            (AudioRedundancy::Always, false, RED),
1133            (AudioRedundancy::Always, true, RED),
1134            (AudioRedundancy::Never, false, OPUS),
1135            (AudioRedundancy::Never, true, OPUS),
1136        ];
1137        for (policy, red_first, expected) in cases {
1138            let mut sender = RedAudioBuilder::new().with_audio_redundancy(policy).build();
1139            sender.bind_local_stream(&if red_first {
1140                info_red_first(1, "111/111")
1141            } else {
1142                info(1, "111/111")
1143            });
1144            assert_eq!(
1145                sent_payload_type(&mut sender, 1),
1146                expected,
1147                "{policy:?}, RED first: {red_first}"
1148            );
1149        }
1150        assert_eq!(
1151            RedAudioBuilder::new().audio_redundancy,
1152            AudioRedundancy::WhenPreferred
1153        );
1154    }
1155
1156    /// The setting is about sending: a receiver takes RED apart and recovers a loss from the
1157    /// next packet's copy whatever its own [`AudioRedundancy`] (RFC 8854 section 7: an endpoint
1158    /// "MUST be able to receive and make use of" the FEC formats it indicated).
1159    #[test]
1160    fn received_red_is_taken_apart_in_every_mode() {
1161        for policy in [
1162            AudioRedundancy::WhenPreferred,
1163            AudioRedundancy::Always,
1164            AudioRedundancy::Never,
1165        ] {
1166            let mut sender = RedAudioBuilder::new()
1167                .with_audio_redundancy(AudioRedundancy::Always)
1168                .build();
1169            let mut receiver = RedAudioBuilder::new().with_audio_redundancy(policy).build();
1170            sender.bind_local_stream(&info(1, "111/111"));
1171            // The receiver's section in its own order: Opus first.
1172            receiver.bind_remote_stream(&info(1, "111/111"));
1173            let mut delivered = vec![];
1174            for (seq, payload) in [(1u16, b"one" as &'static [u8]), (2, b"two"), (3, b"three")] {
1175                sender.handle_write(opus(1, seq, payload)).unwrap();
1176                let red = rtp(sender.poll_write().unwrap());
1177                assert_eq!(red.header.payload_type, RED, "{policy:?}");
1178                if seq == 2 {
1179                    continue;
1180                }
1181                receiver
1182                    .handle_read(TaggedPacket {
1183                        now: Instant::now(),
1184                        transport: TransportContext::default(),
1185                        message: AttributedPacket::new(Packet::Rtp(red)),
1186                    })
1187                    .unwrap();
1188                while let Some(out) = receiver.poll_read() {
1189                    let p = rtp(out);
1190                    delivered.push((p.header.sequence_number, p.header.payload_type, p.payload));
1191                }
1192            }
1193            assert_eq!(
1194                delivered,
1195                vec![
1196                    (1, OPUS, Bytes::from_static(b"one")),
1197                    (2, OPUS, Bytes::from_static(b"two")),
1198                    (3, OPUS, Bytes::from_static(b"three")),
1199                ],
1200                "{policy:?}"
1201            );
1202        }
1203    }
1204}