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    /// The ids of the stream's audio level extensions (RFC 6464 `ssrc-audio-level`, RFC 6465
153    /// `csrc-audio-level`): what a packet rebuilt from a redundant block takes from the RED
154    /// packet that carried it, as an approximation (RFC 8854 section 4.1).
155    level_extensions: Vec<u8>,
156}
157
158/// The ids `info` negotiated the audio level extensions under.
159fn level_extension_ids(info: &StreamInfo) -> Vec<u8> {
160    info.rtp_header_extensions
161        .iter()
162        .filter(|extension| {
163            extension.uri == rtp::extension::AUDIO_LEVEL_URI
164                || extension.uri == rtp::extension::CSRC_AUDIO_LEVEL_URI
165        })
166        .filter_map(|extension| u8::try_from(extension.id).ok())
167        .collect()
168}
169
170/// RFC 2198 audio redundancy for the streams that negotiated it; see the module
171/// documentation.
172pub struct RedAudioInterceptor {
173    config: RedAudioBuilder,
174    senders: HashMap<u32, SendStream>,
175    receivers: HashMap<u32, ReceiveStream>,
176    read_queue: VecDeque<TaggedPacket>,
177    write_queue: VecDeque<TaggedPacket>,
178}
179
180impl Default for RedAudioInterceptor {
181    fn default() -> Self {
182        RedAudioBuilder::new().build()
183    }
184}
185
186/// The RED format of an audio stream's m= section and its primary encoding: a format named
187/// `red` (RFC 2198 section 5) whose fmtp lists only `primary`, the stream's payload type, as
188/// the primary and every redundant encoding (the copy-of-the-primary form this interceptor
189/// sends and Chromium and WebKit offer). `None` for a video stream or a section without one.
190fn negotiated_red(info: &StreamInfo, primary: u8) -> Option<u8> {
191    if !info.mime_type.to_ascii_lowercase().starts_with("audio/") {
192        return None;
193    }
194    info.section_mime_types
195        .iter()
196        .filter(|(_, mime_type)| mime_type.to_ascii_lowercase().ends_with("/red"))
197        .find_map(|(payload_type, _)| {
198            let fmtp = info
199                .section_fmtp_lines
200                .iter()
201                .find(|(pt, _)| pt == payload_type)
202                .map(|(_, fmtp)| fmtp.trim())?;
203            let encodings = parse_red_fmtp(fmtp).ok()?;
204            encodings
205                .iter()
206                .all(|pt| *pt == primary)
207                .then_some(*payload_type)
208        })
209}
210
211/// Whether the stream's section lists the RED format `red` ahead of the stream's own payload
212/// type: the remote side prefers redundancy (RFC 3264 sections 5.1 and 6.1). The section's
213/// formats are in the order of the m= line of the description whose numbering the stream
214/// uses, the remote one for a local stream.
215fn red_is_preferred(info: &StreamInfo, red: u8) -> bool {
216    let position = |payload_type: u8| {
217        info.section_mime_types
218            .iter()
219            .position(|(pt, _)| *pt == payload_type)
220    };
221    matches!(
222        (position(red), position(info.payload_type)),
223        (Some(red), Some(primary)) if red < primary
224    )
225}
226
227impl RedAudioInterceptor {
228    /// The RED payload type a local stream is sent with under the builder's
229    /// [`AudioRedundancy`], or `None` to send it as it is.
230    fn red_to_send(&self, info: &StreamInfo) -> Option<u8> {
231        let red = negotiated_red(info, info.payload_type)?;
232        match self.config.audio_redundancy {
233            AudioRedundancy::Always => Some(red),
234            AudioRedundancy::WhenPreferred => red_is_preferred(info, red).then_some(red),
235            AudioRedundancy::Never => None,
236        }
237    }
238
239    /// The RTP packets of the blocks of the RED packet `packet` (RFC 2198 section 4), each
240    /// not yet delivered, the recovered ones first.
241    fn take_apart(stream: &mut ReceiveStream, packet: &rtp::Packet) -> Vec<rtp::Packet> {
242        // The timestamps of the redundant blocks in header order, oldest first: block `i` of
243        // `n` was the primary of the packet `n - i` before this one.
244        let redundant: Vec<u32> = match RedPacket::parse(&packet.payload) {
245            Ok(red) => red
246                .redundant()
247                .iter()
248                .map(|block| block.timestamp(packet.header.timestamp))
249                .collect(),
250            Err(_) => return vec![],
251        };
252        let Ok(blocks) = stream.decoder.decode_rtp(packet) else {
253            return vec![];
254        };
255        blocks
256            .into_iter()
257            .map(|recovered| {
258                let mut header = packet.header.clone();
259                header.payload_type = recovered.block.payload_type;
260                header.timestamp = recovered.block.timestamp;
261                header.marker = recovered.marker;
262                header.csrc = recovered.csrc;
263                if !recovered.block.primary {
264                    let back = redundant
265                        .iter()
266                        .position(|ts| *ts == recovered.block.timestamp)
267                        .map_or(1, |i| redundant.len() - i);
268                    header.sequence_number = header.sequence_number.wrapping_sub(back as u16);
269                    // The extensions and padding were the RED packet's. RFC 8854 section 4.1:
270                    // the header parts RED cannot recover, "RTP header extensions like those
271                    // specified in [RFC6464] and [RFC6465]", are approximated "using an
272                    // approach similar to those described in [RFC2198], Section 4": as RFC
273                    // 2198 applies the RED packet's CSRCs to the rebuilt data, the rebuilt
274                    // packet takes the RED packet's audio levels (one packet later in time,
275                    // the nearest measure there is). Every other extension is left out.
276                    let levels: Vec<(u8, bytes::Bytes)> = stream
277                        .level_extensions
278                        .iter()
279                        .filter_map(|id| packet.header.get_extension(*id).map(|v| (*id, v)))
280                        .collect();
281                    header.extension = false;
282                    header.extensions.clear();
283                    header.extension_profile = 0;
284                    header.extensions_padding = 0;
285                    for (id, value) in levels {
286                        // The RED packet carried it in this form, so it fits.
287                        let _ = header.set_extension(id, value);
288                    }
289                }
290                header.padding = false;
291                rtp::Packet {
292                    header,
293                    payload: recovered.block.data,
294                }
295            })
296            .collect()
297    }
298}
299
300impl Protocol<TaggedPacket, TaggedPacket, ()> for RedAudioInterceptor {
301    type Rout = TaggedPacket;
302    type Wout = TaggedPacket;
303    type Eout = ();
304    type Error = Error;
305    type Time = Instant;
306
307    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
308        let red = match &msg.message.packet {
309            Packet::Rtp(packet) => self
310                .receivers
311                .get(&packet.header.ssrc)
312                .is_some_and(|stream| packet.header.payload_type == stream.red_payload_type),
313            Packet::Rtcp(_) => false,
314        };
315        if !red {
316            self.read_queue.push_back(msg);
317            return Ok(());
318        }
319        let Packet::Rtp(packet) = &msg.message.packet else {
320            return Ok(());
321        };
322        let Some(stream) = self.receivers.get_mut(&packet.header.ssrc) else {
323            return Ok(());
324        };
325        // A malformed RED payload, or one whose every block was delivered: nothing goes on.
326        for media in Self::take_apart(stream, packet) {
327            self.read_queue.push_back(TaggedPacket {
328                now: msg.now,
329                transport: msg.transport,
330                message: crate::AttributedPacket {
331                    attributes: msg.message.attributes.clone(),
332                    packet: Packet::Rtp(media),
333                },
334            });
335        }
336        Ok(())
337    }
338
339    fn poll_read(&mut self) -> Option<Self::Rout> {
340        self.read_queue.pop_front()
341    }
342
343    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
344        if let Packet::Rtp(packet) = &mut msg.message.packet
345            && !packet.payload.is_empty()
346            && let Some(stream) = self.senders.get_mut(&packet.header.ssrc)
347            && packet.header.payload_type == stream.primary_payload_type
348        {
349            // The receiver numbers a recovered block one packet back per block (RFC 2198
350            // section 4 leaves the sequence number of redundant data to it): a copy goes only
351            // into the packet right after the one it was the primary of.
352            if stream
353                .last_sequence_number
354                .is_some_and(|last| last.wrapping_add(1) != packet.header.sequence_number)
355            {
356                stream.encoder.reset();
357            }
358            stream.last_sequence_number = Some(packet.header.sequence_number);
359            // A primary that does not fit a RED payload goes as it is.
360            if let Ok(red) = stream.encoder.encode_rtp(stream.red_payload_type, packet) {
361                *packet = red;
362            }
363        }
364        self.write_queue.push_back(msg);
365        Ok(())
366    }
367
368    fn poll_write(&mut self) -> Option<Self::Wout> {
369        self.write_queue.pop_front()
370    }
371
372    fn handle_timeout(&mut self, _now: Self::Time) -> Result<(), Self::Error> {
373        Ok(())
374    }
375
376    fn poll_timeout(&mut self) -> Option<Self::Time> {
377        None
378    }
379}
380
381impl Interceptor for RedAudioInterceptor {
382    fn bind_local_stream(&mut self, info: &StreamInfo) {
383        match self.red_to_send(info) {
384            Some(red_payload_type) => {
385                let stream = self.senders.entry(info.ssrc).or_insert(SendStream {
386                    red_payload_type,
387                    primary_payload_type: info.payload_type,
388                    encoder: RedEncoder::new(self.config.redundancy, self.config.max_payload_size),
389                    last_sequence_number: None,
390                });
391                if (stream.red_payload_type, stream.primary_payload_type)
392                    != (red_payload_type, info.payload_type)
393                {
394                    stream.red_payload_type = red_payload_type;
395                    stream.primary_payload_type = info.payload_type;
396                    stream.encoder.reset();
397                }
398            }
399            None => {
400                self.senders.remove(&info.ssrc);
401            }
402        }
403    }
404
405    fn unbind_local_stream(&mut self, info: &StreamInfo) {
406        self.senders.remove(&info.ssrc);
407    }
408
409    fn bind_remote_stream(&mut self, info: &StreamInfo) {
410        match negotiated_red(info, info.payload_type) {
411            Some(red_payload_type) => {
412                let stream = self.receivers.entry(info.ssrc).or_insert(ReceiveStream {
413                    red_payload_type,
414                    decoder: RedDecoder::default(),
415                    level_extensions: vec![],
416                });
417                stream.red_payload_type = red_payload_type;
418                stream.level_extensions = level_extension_ids(info);
419            }
420            None => {
421                self.receivers.remove(&info.ssrc);
422            }
423        }
424    }
425
426    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
427        self.receivers.remove(&info.ssrc);
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::{AttributedPacket, TaggedPacket};
435    use bytes::Bytes;
436    use shared::TransportContext;
437
438    const OPUS: u8 = 111;
439    const RED: u8 = 63;
440
441    /// A stream whose section lists Opus, then RED (Chromium's and WebKit's order).
442    fn info(ssrc: u32, red_fmtp: &str) -> StreamInfo {
443        StreamInfo {
444            ssrc,
445            payload_type: OPUS,
446            mime_type: "audio/opus".to_owned(),
447            clock_rate: 48_000,
448            channels: 2,
449            section_mime_types: vec![
450                (OPUS, "audio/opus".to_owned()),
451                (RED, "audio/red".to_owned()),
452            ],
453            section_fmtp_lines: vec![
454                (OPUS, "minptime=10;useinbandfec=1".to_owned()),
455                (RED, red_fmtp.to_owned()),
456            ],
457            ..Default::default()
458        }
459    }
460
461    /// [`info`] with RED listed ahead of Opus: the remote side prefers redundancy.
462    fn info_red_first(ssrc: u32, red_fmtp: &str) -> StreamInfo {
463        let mut info = info(ssrc, red_fmtp);
464        info.section_mime_types.reverse();
465        info.section_fmtp_lines.reverse();
466        info
467    }
468
469    /// The payload type the first packet of a fresh stream leaves `sender` with.
470    fn sent_payload_type(sender: &mut RedAudioInterceptor, ssrc: u32) -> u8 {
471        sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
472        rtp(sender.poll_write().unwrap()).header.payload_type
473    }
474
475    fn opus(ssrc: u32, sequence_number: u16, payload: &'static [u8]) -> TaggedPacket {
476        TaggedPacket {
477            now: Instant::now(),
478            transport: TransportContext::default(),
479            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
480                header: rtp::header::Header {
481                    version: 2,
482                    ssrc,
483                    payload_type: OPUS,
484                    sequence_number,
485                    timestamp: u32::from(sequence_number) * 960,
486                    marker: sequence_number == 1,
487                    ..Default::default()
488                },
489                payload: Bytes::from_static(payload),
490            })),
491        }
492    }
493
494    fn rtp(msg: TaggedPacket) -> rtp::Packet {
495        match msg.message.packet {
496            Packet::Rtp(packet) => packet,
497            Packet::Rtcp(_) => panic!("RTP expected"),
498        }
499    }
500
501    /// RFC 2198 sections 3 and 4 through one sender and one receiver: the sender, whose remote
502    /// side lists RED first, wraps each Opus packet with a copy of the one before; the receiver
503    /// gives back each primary, and, for the packet lost on the way, the copy the next packet
504    /// carried, with its sequence number and timestamp and no marker.
505    #[test]
506    fn red_packets_carry_the_previous_primary_and_recover_a_loss() {
507        let mut sender = RedAudioBuilder::new().build();
508        let mut receiver = RedAudioBuilder::new().build();
509        sender.bind_local_stream(&info_red_first(1, "111/111"));
510        receiver.bind_remote_stream(&info(1, "111/111"));
511
512        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
513        let mut wire = vec![];
514        for (i, payload) in payloads.iter().enumerate() {
515            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
516            let red = rtp(sender.poll_write().unwrap());
517            assert_eq!(red.header.payload_type, RED);
518            assert_eq!(red.header.sequence_number, i as u16 + 1);
519            let blocks = RedPacket::parse(&red.payload).unwrap();
520            assert_eq!(blocks.primary().data.as_ref(), *payload);
521            assert_eq!(blocks.redundant().len(), usize::from(i > 0));
522            wire.push(red);
523        }
524        // The third packet is lost.
525        let mut delivered = vec![];
526        for (i, red) in wire.into_iter().enumerate() {
527            if i == 2 {
528                continue;
529            }
530            receiver
531                .handle_read(TaggedPacket {
532                    now: Instant::now(),
533                    transport: TransportContext::default(),
534                    message: AttributedPacket::new(Packet::Rtp(red)),
535                })
536                .unwrap();
537            while let Some(out) = receiver.poll_read() {
538                delivered.push(rtp(out));
539            }
540        }
541        let got: Vec<(u16, u32, u8, bool, &[u8])> = delivered
542            .iter()
543            .map(|p| {
544                (
545                    p.header.sequence_number,
546                    p.header.timestamp,
547                    p.header.payload_type,
548                    p.header.marker,
549                    p.payload.as_ref(),
550                )
551            })
552            .collect();
553        assert_eq!(
554            got,
555            vec![
556                (1, 960, OPUS, true, b"one".as_ref()),
557                (2, 1920, OPUS, false, b"two".as_ref()),
558                (3, 2880, OPUS, false, b"three".as_ref()),
559                (4, 3840, OPUS, false, b"four".as_ref()),
560            ]
561        );
562    }
563
564    /// Sends `payloads` through `sender`, each RED packet given header extensions by `extend`,
565    /// loses the packets at `lost` (indices) and returns what `receiver` delivered.
566    fn through(
567        sender: &mut RedAudioInterceptor,
568        receiver: &mut RedAudioInterceptor,
569        payloads: &[&'static [u8]],
570        lost: &[usize],
571        extend: impl Fn(usize, &mut rtp::header::Header),
572    ) -> Vec<rtp::Packet> {
573        let mut delivered = vec![];
574        for (i, payload) in payloads.iter().enumerate() {
575            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
576            let mut red = rtp(sender.poll_write().unwrap());
577            extend(i, &mut red.header);
578            if lost.contains(&i) {
579                continue;
580            }
581            receiver
582                .handle_read(TaggedPacket {
583                    now: Instant::now(),
584                    transport: TransportContext::default(),
585                    message: AttributedPacket::new(Packet::Rtp(red)),
586                })
587                .unwrap();
588            while let Some(out) = receiver.poll_read() {
589                delivered.push(rtp(out));
590            }
591        }
592        delivered
593    }
594
595    /// RFC 8854 section 4.1: "the recommended mechanisms do not allow recovery of parts of the
596    /// RTP header that may be important in certain audio applications, e.g., CSRCs and RTP
597    /// header extensions like those specified in [RFC6464] and [RFC6465]. Implementations
598    /// SHOULD account for this and attempt to approximate this information, using an approach
599    /// similar to those described in [RFC2198], Section 4". A packet rebuilt from a redundant
600    /// block takes the audio levels of the RED packet that carried it (as RFC 2198 section 4
601    /// applies that packet's CSRCs), and no other extension of it.
602    #[test]
603    fn a_rebuilt_packet_takes_the_audio_levels_of_the_red_packet_that_carried_it() {
604        const LEVEL: u8 = 1;
605        const CSRC_LEVELS: u8 = 2;
606        const OTHER: u8 = 3;
607        let mut sender = RedAudioBuilder::new().build();
608        let mut receiver = RedAudioBuilder::new().build();
609        sender.bind_local_stream(&info_red_first(1, "111/111"));
610        let mut remote = info(1, "111/111");
611        for (uri, id) in [
612            (rtp::extension::AUDIO_LEVEL_URI, LEVEL),
613            (rtp::extension::CSRC_AUDIO_LEVEL_URI, CSRC_LEVELS),
614            (
615                "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
616                OTHER,
617            ),
618        ] {
619            remote
620                .rtp_header_extensions
621                .push(crate::RTPHeaderExtension {
622                    uri: uri.to_owned(),
623                    id: u16::from(id),
624                });
625        }
626        receiver.bind_remote_stream(&remote);
627
628        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
629        let delivered = through(&mut sender, &mut receiver, &payloads, &[2], |i, header| {
630            header.csrc = vec![77];
631            let level = 0x80 | (10 + i as u8);
632            header
633                .set_extension(LEVEL, Bytes::from(vec![level]))
634                .unwrap();
635            header
636                .set_extension(CSRC_LEVELS, Bytes::from(vec![20 + i as u8]))
637                .unwrap();
638            header
639                .set_extension(OTHER, Bytes::from(vec![1, 2, 3]))
640                .unwrap();
641        });
642        let rebuilt = delivered
643            .iter()
644            .find(|p| p.header.sequence_number == 3)
645            .expect("the lost packet is rebuilt");
646        assert_eq!(rebuilt.payload.as_ref(), b"three");
647        assert_eq!(
648            rebuilt.header.get_extension(LEVEL).as_deref(),
649            Some([0x80 | 13].as_ref()),
650            "the audio level of the packet that carried it"
651        );
652        assert_eq!(
653            rebuilt.header.get_extension(CSRC_LEVELS).as_deref(),
654            Some([23].as_ref())
655        );
656        assert_eq!(rebuilt.header.csrc, vec![77]);
657        assert_eq!(rebuilt.header.get_extension(OTHER), None, "nothing else");
658        // The primaries keep their own extensions.
659        let primary = delivered
660            .iter()
661            .find(|p| p.header.sequence_number == 4)
662            .unwrap();
663        assert_eq!(
664            primary.header.get_extension(LEVEL).as_deref(),
665            Some([0x80 | 13].as_ref())
666        );
667        assert!(primary.header.get_extension(OTHER).is_some());
668    }
669
670    /// RFC 8854 section 4.1: "if multi-packet protection is needed, the aforementioned
671    /// redundant encoding ... SHOULD be used instead". With two redundant blocks per packet
672    /// (`with_redundancy(2)`) two consecutive losses are both rebuilt from the packet after
673    /// them; with one, only the second of them.
674    #[test]
675    fn two_redundant_blocks_rebuild_two_consecutive_losses() {
676        let payloads: [&'static [u8]; 5] = [b"one", b"two", b"three", b"four", b"five"];
677        for (redundancy, rebuilt) in [(2usize, vec![2u16, 3]), (1, vec![3])] {
678            let mut sender = RedAudioBuilder::new().with_redundancy(redundancy).build();
679            let mut receiver = RedAudioBuilder::new().build();
680            sender.bind_local_stream(&info_red_first(1, "111/111/111"));
681            receiver.bind_remote_stream(&info(1, "111/111/111"));
682            let delivered = through(&mut sender, &mut receiver, &payloads, &[1, 2], |_, _| {});
683            let got: Vec<u16> = delivered
684                .iter()
685                .map(|p| p.header.sequence_number)
686                .filter(|seq| [2, 3].contains(seq))
687                .collect();
688            assert_eq!(got, rebuilt, "redundancy {redundancy}");
689            for packet in &delivered {
690                assert_eq!(
691                    packet.payload.as_ref(),
692                    payloads[usize::from(packet.header.sequence_number) - 1]
693                );
694            }
695        }
696    }
697
698    /// RFC 8854 section 4.1: "When using constant-bitrate codecs, e.g., PCMU [RFC5391],
699    /// redundant encoding MAY be used". A PCMU stream whose section negotiated `red/8000`
700    /// naming PCMU (an application's registration: the default codecs offer RED for Opus
701    /// only, the clause warning that it "will result in a potentially significant bitrate
702    /// increase") is sent in RED and a lost packet comes back from the next one.
703    #[test]
704    fn a_constant_bitrate_codec_gets_redundancy_when_its_section_negotiated_red() {
705        const PCMU: u8 = 0;
706        const RED_8K: u8 = 98;
707        let pcmu = |red_first: bool| {
708            let mut formats = vec![
709                (PCMU, "audio/PCMU".to_owned()),
710                (RED_8K, "audio/red".to_owned()),
711            ];
712            if red_first {
713                formats.reverse();
714            }
715            StreamInfo {
716                ssrc: 1,
717                payload_type: PCMU,
718                mime_type: "audio/PCMU".to_owned(),
719                clock_rate: 8_000,
720                channels: 1,
721                section_mime_types: formats,
722                section_fmtp_lines: vec![(RED_8K, "0/0".to_owned())],
723                ..Default::default()
724            }
725        };
726        let mut sender = RedAudioBuilder::new().build();
727        let mut receiver = RedAudioBuilder::new().build();
728        sender.bind_local_stream(&pcmu(true));
729        receiver.bind_remote_stream(&pcmu(false));
730        let mut delivered = vec![];
731        for (i, payload) in [b"aaaa", b"bbbb", b"cccc", b"dddd"].iter().enumerate() {
732            let mut packet = opus(1, i as u16 + 1, payload.as_slice());
733            if let Packet::Rtp(rtp) = &mut packet.message.packet {
734                rtp.header.payload_type = PCMU;
735                rtp.header.timestamp = u32::from(rtp.header.sequence_number) * 160;
736            }
737            sender.handle_write(packet).unwrap();
738            let red = rtp(sender.poll_write().unwrap());
739            assert_eq!(red.header.payload_type, RED_8K);
740            if i == 1 {
741                continue;
742            }
743            receiver
744                .handle_read(TaggedPacket {
745                    now: Instant::now(),
746                    transport: TransportContext::default(),
747                    message: AttributedPacket::new(Packet::Rtp(red)),
748                })
749                .unwrap();
750            while let Some(out) = receiver.poll_read() {
751                delivered.push(rtp(out));
752            }
753        }
754        let got: Vec<(u16, u8, &[u8])> = delivered
755            .iter()
756            .map(|p| {
757                (
758                    p.header.sequence_number,
759                    p.header.payload_type,
760                    p.payload.as_ref(),
761                )
762            })
763            .collect();
764        assert_eq!(
765            got,
766            vec![
767                (1, PCMU, b"aaaa".as_ref()),
768                (2, PCMU, b"bbbb".as_ref()),
769                (3, PCMU, b"cccc".as_ref()),
770                (4, PCMU, b"dddd".as_ref()),
771            ]
772        );
773    }
774
775    /// Only a stream whose section negotiated a RED format of its own encoding is touched: a
776    /// stream without one, and a packet of another payload type, pass as they are.
777    #[test]
778    fn without_a_negotiated_red_format_packets_pass_unchanged() {
779        let mut sender = RedAudioBuilder::new()
780            .with_audio_redundancy(AudioRedundancy::Always)
781            .build();
782        sender.bind_local_stream(&StreamInfo {
783            section_mime_types: vec![(OPUS, "audio/opus".to_owned())],
784            section_fmtp_lines: vec![(OPUS, String::new())],
785            ..info(1, "")
786        });
787        sender.bind_local_stream(&info(2, "0/0"));
788        sender.bind_local_stream(&info(3, "111/111"));
789        for ssrc in [1, 2] {
790            sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
791            assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, OPUS);
792        }
793        let mut dtmf = opus(3, 1, b"x");
794        if let Packet::Rtp(p) = &mut dtmf.message.packet {
795            p.header.payload_type = 126;
796        }
797        sender.handle_write(dtmf).unwrap();
798        assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, 126);
799    }
800
801    /// RFC 3264 sections 5.1 and 6.1: the formats of an m= line are in order of preference and
802    /// the sender "SHOULD use the format with the highest preference". By default
803    /// ([`AudioRedundancy::WhenPreferred`]) a stream goes in RED only when its section lists
804    /// RED ahead of Opus; `Always` sends RED in either order, `Never` in neither.
805    #[test]
806    fn red_is_sent_by_the_remote_order_unless_the_application_decides() {
807        let cases = [
808            (AudioRedundancy::WhenPreferred, false, OPUS),
809            (AudioRedundancy::WhenPreferred, true, RED),
810            (AudioRedundancy::Always, false, RED),
811            (AudioRedundancy::Always, true, RED),
812            (AudioRedundancy::Never, false, OPUS),
813            (AudioRedundancy::Never, true, OPUS),
814        ];
815        for (policy, red_first, expected) in cases {
816            let mut sender = RedAudioBuilder::new().with_audio_redundancy(policy).build();
817            sender.bind_local_stream(&if red_first {
818                info_red_first(1, "111/111")
819            } else {
820                info(1, "111/111")
821            });
822            assert_eq!(
823                sent_payload_type(&mut sender, 1),
824                expected,
825                "{policy:?}, RED first: {red_first}"
826            );
827        }
828        assert_eq!(
829            RedAudioBuilder::new().audio_redundancy,
830            AudioRedundancy::WhenPreferred
831        );
832    }
833
834    /// The setting is about sending: a receiver takes RED apart and recovers a loss from the
835    /// next packet's copy whatever its own [`AudioRedundancy`] (RFC 8854 section 7: an endpoint
836    /// "MUST be able to receive and make use of" the FEC formats it indicated).
837    #[test]
838    fn received_red_is_taken_apart_in_every_mode() {
839        for policy in [
840            AudioRedundancy::WhenPreferred,
841            AudioRedundancy::Always,
842            AudioRedundancy::Never,
843        ] {
844            let mut sender = RedAudioBuilder::new()
845                .with_audio_redundancy(AudioRedundancy::Always)
846                .build();
847            let mut receiver = RedAudioBuilder::new().with_audio_redundancy(policy).build();
848            sender.bind_local_stream(&info(1, "111/111"));
849            // The receiver's section in its own order: Opus first.
850            receiver.bind_remote_stream(&info(1, "111/111"));
851            let mut delivered = vec![];
852            for (seq, payload) in [(1u16, b"one" as &'static [u8]), (2, b"two"), (3, b"three")] {
853                sender.handle_write(opus(1, seq, payload)).unwrap();
854                let red = rtp(sender.poll_write().unwrap());
855                assert_eq!(red.header.payload_type, RED, "{policy:?}");
856                if seq == 2 {
857                    continue;
858                }
859                receiver
860                    .handle_read(TaggedPacket {
861                        now: Instant::now(),
862                        transport: TransportContext::default(),
863                        message: AttributedPacket::new(Packet::Rtp(red)),
864                    })
865                    .unwrap();
866                while let Some(out) = receiver.poll_read() {
867                    let p = rtp(out);
868                    delivered.push((p.header.sequence_number, p.header.payload_type, p.payload));
869                }
870            }
871            assert_eq!(
872                delivered,
873                vec![
874                    (1, OPUS, Bytes::from_static(b"one")),
875                    (2, OPUS, Bytes::from_static(b"two")),
876                    (3, OPUS, Bytes::from_static(b"three")),
877                ],
878                "{policy:?}"
879            );
880        }
881    }
882}