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