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, how.** A packet of a local stream sent in RED, whose payload type is the primary
23//!   of the negotiated RED format, leaves as a RED packet: the RED payload type in the header,
24//!   the copies of the last [`RedAudioBuilder::with_redundancy`] primaries (one by default, as
25//!   Chromium sends) before the new primary, the header otherwise the primary's (RFC 2198
26//!   section 3). A primary too large to be wrapped, or of another payload type (comfort noise,
27//!   DTMF), leaves as it is: the receiver negotiated it too.
28//! - **Receive.** A RED packet of a remote stream is taken apart into the packets of its
29//!   blocks (RFC 2198 section 4): the primary with the RED packet's sequence number, marker
30//!   and CSRCs, and the earlier primaries a lost packet carried, recovered from the redundant
31//!   blocks with the sequence numbers they had (one packet per block, as the encoder above and
32//!   Chromium send them), no marker ("the marker bit ... is lost") and the RED packet's CSRCs.
33//!   Nothing is delivered twice (`RedDecoder`). What arrives after this interceptor (the NACK
34//!   generator, the jitter buffer, the application) sees the primary encoding only. Received
35//!   RED is taken apart whatever the [`AudioRedundancy`] setting: the setting is about what
36//!   this side sends, and RFC 8854 section 7 has an endpoint "receive and make use of" the FEC
37//!   formats it indicated.
38//!
39//! # Where it belongs
40//!
41//! [`Slot::Redundancy`](crate::Slot::Redundancy) (10_450). On the write leg it is
42//! application-ward of the NACK responder (4_000) and the FEC encoder (5_000): what is
43//! buffered for retransmission and protected is the RED packet on the wire. On the read leg it
44//! is application-ward of the receiver report (10_000) and the FEC decoder (10_300), which
45//! count and repair the RED packets that arrived, and wire-ward of the NACK generator
46//! (10_600), which then does not ask for a packet RED recovered.
47
48use crate::stream_info::StreamInfo;
49use crate::{Interceptor, Packet, TaggedPacket};
50use rtp::codec::red::{RedDecoder, RedEncoder, RedPacket, parse_red_fmtp};
51use sansio::Protocol;
52use shared::error::Error;
53use std::collections::{HashMap, VecDeque};
54use std::time::Instant;
55
56/// How many earlier primaries a RED packet carries by default: one, as Chromium sends Opus
57/// RED.
58pub const RED_AUDIO_DEFAULT_REDUNDANCY: usize = 1;
59
60/// The largest RED payload the sender builds by default: redundant blocks that would make
61/// the payload larger are left out (an Opus packet is far smaller), so that a RED packet
62/// stays within the path MTU the application sized the primary for, with the header, its
63/// extensions and the SRTP tag.
64pub const RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;
65
66/// When a local audio stream whose section negotiated RED (RFC 2198) is sent in RED. Received
67/// RED is taken apart in every case.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum AudioRedundancy {
70    /// In RED when the remote description lists the RED format ahead of the stream's primary
71    /// encoding, the remote side's preference (RFC 3264 sections 5.1 and 6.1; libwebrtc's
72    /// rule too). Chromium and WebKit list it after Opus, so a call with them carries plain
73    /// Opus. The default.
74    #[default]
75    WhenPreferred,
76    /// In RED whenever RED is negotiated, whatever its place on the m= line: the application's
77    /// request for redundancy (RFC 8854 section 8). Each packet then carries a copy of the
78    /// one before, about doubling the audio bitrate.
79    Always,
80    /// Never in RED, even when the remote side prefers it (RFC 3264's "SHOULD" set aside).
81    Never,
82}
83
84/// Builder for [`RedAudioInterceptor`].
85#[derive(Debug, Clone)]
86pub struct RedAudioBuilder {
87    redundancy: usize,
88    max_payload_size: usize,
89    audio_redundancy: AudioRedundancy,
90}
91
92impl Default for RedAudioBuilder {
93    fn default() -> Self {
94        Self {
95            redundancy: RED_AUDIO_DEFAULT_REDUNDANCY,
96            max_payload_size: RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE,
97            audio_redundancy: AudioRedundancy::default(),
98        }
99    }
100}
101
102impl RedAudioBuilder {
103    /// One earlier primary per packet, payloads of at most
104    /// [`RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE`] octets, sent in RED when the remote side prefers
105    /// it ([`AudioRedundancy::WhenPreferred`]).
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    /// When a local stream that negotiated RED is sent in RED; see [`AudioRedundancy`].
111    pub fn with_audio_redundancy(mut self, audio_redundancy: AudioRedundancy) -> Self {
112        self.audio_redundancy = audio_redundancy;
113        self
114    }
115
116    /// How many earlier primaries each RED packet carries (0 sends RED packets with the
117    /// primary alone).
118    pub fn with_redundancy(mut self, redundancy: usize) -> Self {
119        self.redundancy = redundancy;
120        self
121    }
122
123    /// The largest RED payload built; redundant blocks that would exceed it are left out.
124    pub fn with_max_payload_size(mut self, max_payload_size: usize) -> Self {
125        self.max_payload_size = max_payload_size;
126        self
127    }
128
129    /// The interceptor.
130    pub fn build(self) -> RedAudioInterceptor {
131        RedAudioInterceptor {
132            config: self,
133            senders: HashMap::new(),
134            receivers: HashMap::new(),
135            read_queue: VecDeque::new(),
136            write_queue: VecDeque::new(),
137        }
138    }
139}
140
141struct SendStream {
142    red_payload_type: u8,
143    primary_payload_type: u8,
144    encoder: RedEncoder,
145    /// The sequence number of the last primary wrapped.
146    last_sequence_number: Option<u16>,
147}
148
149struct ReceiveStream {
150    red_payload_type: u8,
151    decoder: RedDecoder,
152}
153
154/// RFC 2198 audio redundancy for the streams that negotiated it; see the module
155/// documentation.
156pub struct RedAudioInterceptor {
157    config: RedAudioBuilder,
158    senders: HashMap<u32, SendStream>,
159    receivers: HashMap<u32, ReceiveStream>,
160    read_queue: VecDeque<TaggedPacket>,
161    write_queue: VecDeque<TaggedPacket>,
162}
163
164impl Default for RedAudioInterceptor {
165    fn default() -> Self {
166        RedAudioBuilder::new().build()
167    }
168}
169
170/// The RED format of an audio stream's m= section and its primary encoding: a format named
171/// `red` (RFC 2198 section 5) whose fmtp lists only `primary`, the stream's payload type, as
172/// the primary and every redundant encoding (the copy-of-the-primary form this interceptor
173/// sends and Chromium and WebKit offer). `None` for a video stream or a section without one.
174fn negotiated_red(info: &StreamInfo, primary: u8) -> Option<u8> {
175    if !info.mime_type.to_ascii_lowercase().starts_with("audio/") {
176        return None;
177    }
178    info.section_mime_types
179        .iter()
180        .filter(|(_, mime_type)| mime_type.to_ascii_lowercase().ends_with("/red"))
181        .find_map(|(payload_type, _)| {
182            let fmtp = info
183                .section_fmtp_lines
184                .iter()
185                .find(|(pt, _)| pt == payload_type)
186                .map(|(_, fmtp)| fmtp.trim())?;
187            let encodings = parse_red_fmtp(fmtp).ok()?;
188            encodings
189                .iter()
190                .all(|pt| *pt == primary)
191                .then_some(*payload_type)
192        })
193}
194
195/// Whether the stream's section lists the RED format `red` ahead of the stream's own payload
196/// type: the remote side prefers redundancy (RFC 3264 sections 5.1 and 6.1). The section's
197/// formats are in the order of the m= line of the description whose numbering the stream
198/// uses, the remote one for a local stream.
199fn red_is_preferred(info: &StreamInfo, red: u8) -> bool {
200    let position = |payload_type: u8| {
201        info.section_mime_types
202            .iter()
203            .position(|(pt, _)| *pt == payload_type)
204    };
205    matches!(
206        (position(red), position(info.payload_type)),
207        (Some(red), Some(primary)) if red < primary
208    )
209}
210
211impl RedAudioInterceptor {
212    /// The RED payload type a local stream is sent with under the builder's
213    /// [`AudioRedundancy`], or `None` to send it as it is.
214    fn red_to_send(&self, info: &StreamInfo) -> Option<u8> {
215        let red = negotiated_red(info, info.payload_type)?;
216        match self.config.audio_redundancy {
217            AudioRedundancy::Always => Some(red),
218            AudioRedundancy::WhenPreferred => red_is_preferred(info, red).then_some(red),
219            AudioRedundancy::Never => None,
220        }
221    }
222
223    /// The RTP packets of the blocks of the RED packet `packet` (RFC 2198 section 4), each
224    /// not yet delivered, the recovered ones first.
225    fn take_apart(stream: &mut ReceiveStream, packet: &rtp::Packet) -> Vec<rtp::Packet> {
226        // The timestamps of the redundant blocks in header order, oldest first: block `i` of
227        // `n` was the primary of the packet `n - i` before this one.
228        let redundant: Vec<u32> = match RedPacket::parse(&packet.payload) {
229            Ok(red) => red
230                .redundant()
231                .iter()
232                .map(|block| block.timestamp(packet.header.timestamp))
233                .collect(),
234            Err(_) => return vec![],
235        };
236        let Ok(blocks) = stream.decoder.decode_rtp(packet) else {
237            return vec![];
238        };
239        blocks
240            .into_iter()
241            .map(|recovered| {
242                let mut header = packet.header.clone();
243                header.payload_type = recovered.block.payload_type;
244                header.timestamp = recovered.block.timestamp;
245                header.marker = recovered.marker;
246                header.csrc = recovered.csrc;
247                if !recovered.block.primary {
248                    let back = redundant
249                        .iter()
250                        .position(|ts| *ts == recovered.block.timestamp)
251                        .map_or(1, |i| redundant.len() - i);
252                    header.sequence_number = header.sequence_number.wrapping_sub(back as u16);
253                    // The extensions and padding were the RED packet's.
254                    header.extension = false;
255                    header.extensions.clear();
256                    header.extension_profile = 0;
257                }
258                header.padding = false;
259                rtp::Packet {
260                    header,
261                    payload: recovered.block.data,
262                }
263            })
264            .collect()
265    }
266}
267
268impl Protocol<TaggedPacket, TaggedPacket, ()> for RedAudioInterceptor {
269    type Rout = TaggedPacket;
270    type Wout = TaggedPacket;
271    type Eout = ();
272    type Error = Error;
273    type Time = Instant;
274
275    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
276        let red = match &msg.message.packet {
277            Packet::Rtp(packet) => self
278                .receivers
279                .get(&packet.header.ssrc)
280                .is_some_and(|stream| packet.header.payload_type == stream.red_payload_type),
281            Packet::Rtcp(_) => false,
282        };
283        if !red {
284            self.read_queue.push_back(msg);
285            return Ok(());
286        }
287        let Packet::Rtp(packet) = &msg.message.packet else {
288            return Ok(());
289        };
290        let Some(stream) = self.receivers.get_mut(&packet.header.ssrc) else {
291            return Ok(());
292        };
293        // A malformed RED payload, or one whose every block was delivered: nothing goes on.
294        for media in Self::take_apart(stream, packet) {
295            self.read_queue.push_back(TaggedPacket {
296                now: msg.now,
297                transport: msg.transport,
298                message: crate::AttributedPacket {
299                    attributes: msg.message.attributes.clone(),
300                    packet: Packet::Rtp(media),
301                },
302            });
303        }
304        Ok(())
305    }
306
307    fn poll_read(&mut self) -> Option<Self::Rout> {
308        self.read_queue.pop_front()
309    }
310
311    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
312        if let Packet::Rtp(packet) = &mut msg.message.packet
313            && !packet.payload.is_empty()
314            && let Some(stream) = self.senders.get_mut(&packet.header.ssrc)
315            && packet.header.payload_type == stream.primary_payload_type
316        {
317            // The receiver numbers a recovered block one packet back per block (RFC 2198
318            // section 4 leaves the sequence number of redundant data to it): a copy goes only
319            // into the packet right after the one it was the primary of.
320            if stream
321                .last_sequence_number
322                .is_some_and(|last| last.wrapping_add(1) != packet.header.sequence_number)
323            {
324                stream.encoder.reset();
325            }
326            stream.last_sequence_number = Some(packet.header.sequence_number);
327            // A primary that does not fit a RED payload goes as it is.
328            if let Ok(red) = stream.encoder.encode_rtp(stream.red_payload_type, packet) {
329                *packet = red;
330            }
331        }
332        self.write_queue.push_back(msg);
333        Ok(())
334    }
335
336    fn poll_write(&mut self) -> Option<Self::Wout> {
337        self.write_queue.pop_front()
338    }
339
340    fn handle_timeout(&mut self, _now: Self::Time) -> Result<(), Self::Error> {
341        Ok(())
342    }
343
344    fn poll_timeout(&mut self) -> Option<Self::Time> {
345        None
346    }
347}
348
349impl Interceptor for RedAudioInterceptor {
350    fn bind_local_stream(&mut self, info: &StreamInfo) {
351        match self.red_to_send(info) {
352            Some(red_payload_type) => {
353                let stream = self.senders.entry(info.ssrc).or_insert(SendStream {
354                    red_payload_type,
355                    primary_payload_type: info.payload_type,
356                    encoder: RedEncoder::new(self.config.redundancy, self.config.max_payload_size),
357                    last_sequence_number: None,
358                });
359                if (stream.red_payload_type, stream.primary_payload_type)
360                    != (red_payload_type, info.payload_type)
361                {
362                    stream.red_payload_type = red_payload_type;
363                    stream.primary_payload_type = info.payload_type;
364                    stream.encoder.reset();
365                }
366            }
367            None => {
368                self.senders.remove(&info.ssrc);
369            }
370        }
371    }
372
373    fn unbind_local_stream(&mut self, info: &StreamInfo) {
374        self.senders.remove(&info.ssrc);
375    }
376
377    fn bind_remote_stream(&mut self, info: &StreamInfo) {
378        match negotiated_red(info, info.payload_type) {
379            Some(red_payload_type) => {
380                self.receivers
381                    .entry(info.ssrc)
382                    .or_insert(ReceiveStream {
383                        red_payload_type,
384                        decoder: RedDecoder::default(),
385                    })
386                    .red_payload_type = red_payload_type;
387            }
388            None => {
389                self.receivers.remove(&info.ssrc);
390            }
391        }
392    }
393
394    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
395        self.receivers.remove(&info.ssrc);
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use crate::{AttributedPacket, TaggedPacket};
403    use bytes::Bytes;
404    use shared::TransportContext;
405
406    const OPUS: u8 = 111;
407    const RED: u8 = 63;
408
409    /// A stream whose section lists Opus, then RED (Chromium's and WebKit's order).
410    fn info(ssrc: u32, red_fmtp: &str) -> StreamInfo {
411        StreamInfo {
412            ssrc,
413            payload_type: OPUS,
414            mime_type: "audio/opus".to_owned(),
415            clock_rate: 48_000,
416            channels: 2,
417            section_mime_types: vec![
418                (OPUS, "audio/opus".to_owned()),
419                (RED, "audio/red".to_owned()),
420            ],
421            section_fmtp_lines: vec![
422                (OPUS, "minptime=10;useinbandfec=1".to_owned()),
423                (RED, red_fmtp.to_owned()),
424            ],
425            ..Default::default()
426        }
427    }
428
429    /// [`info`] with RED listed ahead of Opus: the remote side prefers redundancy.
430    fn info_red_first(ssrc: u32, red_fmtp: &str) -> StreamInfo {
431        let mut info = info(ssrc, red_fmtp);
432        info.section_mime_types.reverse();
433        info.section_fmtp_lines.reverse();
434        info
435    }
436
437    /// The payload type the first packet of a fresh stream leaves `sender` with.
438    fn sent_payload_type(sender: &mut RedAudioInterceptor, ssrc: u32) -> u8 {
439        sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
440        rtp(sender.poll_write().unwrap()).header.payload_type
441    }
442
443    fn opus(ssrc: u32, sequence_number: u16, payload: &'static [u8]) -> TaggedPacket {
444        TaggedPacket {
445            now: Instant::now(),
446            transport: TransportContext::default(),
447            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
448                header: rtp::header::Header {
449                    version: 2,
450                    ssrc,
451                    payload_type: OPUS,
452                    sequence_number,
453                    timestamp: u32::from(sequence_number) * 960,
454                    marker: sequence_number == 1,
455                    ..Default::default()
456                },
457                payload: Bytes::from_static(payload),
458            })),
459        }
460    }
461
462    fn rtp(msg: TaggedPacket) -> rtp::Packet {
463        match msg.message.packet {
464            Packet::Rtp(packet) => packet,
465            Packet::Rtcp(_) => panic!("RTP expected"),
466        }
467    }
468
469    /// RFC 2198 sections 3 and 4 through one sender and one receiver: the sender, whose remote
470    /// side lists RED first, wraps each Opus packet with a copy of the one before; the receiver
471    /// gives back each primary, and, for the packet lost on the way, the copy the next packet
472    /// carried, with its sequence number and timestamp and no marker.
473    #[test]
474    fn red_packets_carry_the_previous_primary_and_recover_a_loss() {
475        let mut sender = RedAudioBuilder::new().build();
476        let mut receiver = RedAudioBuilder::new().build();
477        sender.bind_local_stream(&info_red_first(1, "111/111"));
478        receiver.bind_remote_stream(&info(1, "111/111"));
479
480        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
481        let mut wire = vec![];
482        for (i, payload) in payloads.iter().enumerate() {
483            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
484            let red = rtp(sender.poll_write().unwrap());
485            assert_eq!(red.header.payload_type, RED);
486            assert_eq!(red.header.sequence_number, i as u16 + 1);
487            let blocks = RedPacket::parse(&red.payload).unwrap();
488            assert_eq!(blocks.primary().data.as_ref(), *payload);
489            assert_eq!(blocks.redundant().len(), usize::from(i > 0));
490            wire.push(red);
491        }
492        // The third packet is lost.
493        let mut delivered = vec![];
494        for (i, red) in wire.into_iter().enumerate() {
495            if i == 2 {
496                continue;
497            }
498            receiver
499                .handle_read(TaggedPacket {
500                    now: Instant::now(),
501                    transport: TransportContext::default(),
502                    message: AttributedPacket::new(Packet::Rtp(red)),
503                })
504                .unwrap();
505            while let Some(out) = receiver.poll_read() {
506                delivered.push(rtp(out));
507            }
508        }
509        let got: Vec<(u16, u32, u8, bool, &[u8])> = delivered
510            .iter()
511            .map(|p| {
512                (
513                    p.header.sequence_number,
514                    p.header.timestamp,
515                    p.header.payload_type,
516                    p.header.marker,
517                    p.payload.as_ref(),
518                )
519            })
520            .collect();
521        assert_eq!(
522            got,
523            vec![
524                (1, 960, OPUS, true, b"one".as_ref()),
525                (2, 1920, OPUS, false, b"two".as_ref()),
526                (3, 2880, OPUS, false, b"three".as_ref()),
527                (4, 3840, OPUS, false, b"four".as_ref()),
528            ]
529        );
530    }
531
532    /// Only a stream whose section negotiated a RED format of its own encoding is touched: a
533    /// stream without one, and a packet of another payload type, pass as they are.
534    #[test]
535    fn without_a_negotiated_red_format_packets_pass_unchanged() {
536        let mut sender = RedAudioBuilder::new()
537            .with_audio_redundancy(AudioRedundancy::Always)
538            .build();
539        sender.bind_local_stream(&StreamInfo {
540            section_mime_types: vec![(OPUS, "audio/opus".to_owned())],
541            section_fmtp_lines: vec![(OPUS, String::new())],
542            ..info(1, "")
543        });
544        sender.bind_local_stream(&info(2, "0/0"));
545        sender.bind_local_stream(&info(3, "111/111"));
546        for ssrc in [1, 2] {
547            sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
548            assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, OPUS);
549        }
550        let mut dtmf = opus(3, 1, b"x");
551        if let Packet::Rtp(p) = &mut dtmf.message.packet {
552            p.header.payload_type = 126;
553        }
554        sender.handle_write(dtmf).unwrap();
555        assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, 126);
556    }
557
558    /// RFC 3264 sections 5.1 and 6.1: the formats of an m= line are in order of preference and
559    /// the sender "SHOULD use the format with the highest preference". By default
560    /// ([`AudioRedundancy::WhenPreferred`]) a stream goes in RED only when its section lists
561    /// RED ahead of Opus; `Always` sends RED in either order, `Never` in neither.
562    #[test]
563    fn red_is_sent_by_the_remote_order_unless_the_application_decides() {
564        let cases = [
565            (AudioRedundancy::WhenPreferred, false, OPUS),
566            (AudioRedundancy::WhenPreferred, true, RED),
567            (AudioRedundancy::Always, false, RED),
568            (AudioRedundancy::Always, true, RED),
569            (AudioRedundancy::Never, false, OPUS),
570            (AudioRedundancy::Never, true, OPUS),
571        ];
572        for (policy, red_first, expected) in cases {
573            let mut sender = RedAudioBuilder::new().with_audio_redundancy(policy).build();
574            sender.bind_local_stream(&if red_first {
575                info_red_first(1, "111/111")
576            } else {
577                info(1, "111/111")
578            });
579            assert_eq!(
580                sent_payload_type(&mut sender, 1),
581                expected,
582                "{policy:?}, RED first: {red_first}"
583            );
584        }
585        assert_eq!(
586            RedAudioBuilder::new().audio_redundancy,
587            AudioRedundancy::WhenPreferred
588        );
589    }
590
591    /// The setting is about sending: a receiver takes RED apart and recovers a loss from the
592    /// next packet's copy whatever its own [`AudioRedundancy`] (RFC 8854 section 7: an endpoint
593    /// "MUST be able to receive and make use of" the FEC formats it indicated).
594    #[test]
595    fn received_red_is_taken_apart_in_every_mode() {
596        for policy in [
597            AudioRedundancy::WhenPreferred,
598            AudioRedundancy::Always,
599            AudioRedundancy::Never,
600        ] {
601            let mut sender = RedAudioBuilder::new()
602                .with_audio_redundancy(AudioRedundancy::Always)
603                .build();
604            let mut receiver = RedAudioBuilder::new().with_audio_redundancy(policy).build();
605            sender.bind_local_stream(&info(1, "111/111"));
606            // The receiver's section in its own order: Opus first.
607            receiver.bind_remote_stream(&info(1, "111/111"));
608            let mut delivered = vec![];
609            for (seq, payload) in [(1u16, b"one" as &'static [u8]), (2, b"two"), (3, b"three")] {
610                sender.handle_write(opus(1, seq, payload)).unwrap();
611                let red = rtp(sender.poll_write().unwrap());
612                assert_eq!(red.header.payload_type, RED, "{policy:?}");
613                if seq == 2 {
614                    continue;
615                }
616                receiver
617                    .handle_read(TaggedPacket {
618                        now: Instant::now(),
619                        transport: TransportContext::default(),
620                        message: AttributedPacket::new(Packet::Rtp(red)),
621                    })
622                    .unwrap();
623                while let Some(out) = receiver.poll_read() {
624                    let p = rtp(out);
625                    delivered.push((p.header.sequence_number, p.header.payload_type, p.payload));
626                }
627            }
628            assert_eq!(
629                delivered,
630                vec![
631                    (1, OPUS, Bytes::from_static(b"one")),
632                    (2, OPUS, Bytes::from_static(b"two")),
633                    (3, OPUS, Bytes::from_static(b"three")),
634                ],
635                "{policy:?}"
636            );
637        }
638    }
639}