Skip to main content

rtci_rtp/codec/red/
mod.rs

1//! Redundant audio data, RED ([RFC 2198]).
2//!
3//! A RED payload is a list of block headers followed by the data blocks in the same order,
4//! with no padding between them (section 3):
5//!
6//! ```text
7//!  0                   1                   2                   3
8//!  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
9//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
10//! |1|   block PT  |  timestamp offset         |   block length    |   redundant block header
11//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12//! |0|   block PT  |                                                   primary block header
13//! +-+-+-+-+-+-+-+-+
14//! ```
15//!
16//! The RTP header of a RED packet (sequence number, timestamp, marker, CSRCs) belongs to the
17//! primary block; a redundant block's timestamp is the RTP timestamp minus its offset, and it
18//! must use the same clock rate as the primary. Two things are not carried for redundant data
19//! (section 4): the marker bit of a lost primary is lost with it, and the CSRC list of the RED
20//! packet that carried a recovered block is the one to apply to it. `RedDecoder` exposes
21//! neither; the caller takes the CSRCs from the RED packet it fed in.
22//!
23//! * `RedPacket` reads and writes one payload, strictly bounds-checked.
24//! * `RedEncoder` builds each payload from a new primary plus copies of the previous ones
25//!   (section 3: "a copy of the primary MAY be used as the redundancy", the mode Chrome uses
26//!   for Opus).
27//! * `RedDecoder` returns each packet's primary and recovers lost earlier primaries from
28//!   later packets' redundant blocks.
29//! * `parse_red_fmtp` / `format_red_fmtp` handle the `a=fmtp:<pt> 111/111` list
30//!   (section 5).
31//!
32//! An empty primary block is accepted and produced: nothing in RFC 2198 forbids a zero-length
33//! block, and RFC 4103 (T.140 text over RED) sends empty primaries while idle.
34//!
35//! [RFC 2198]: https://datatracker.ietf.org/doc/html/rfc2198
36#[cfg(test)]
37mod red_test;
38
39use crate::packetizer::Depacketizer;
40use bytes::{Buf, BufMut, Bytes};
41use shared::error::{Error, Result};
42use shared::marshal::{Marshal, MarshalSize, Unmarshal};
43use std::collections::VecDeque;
44
45/// The most blocks (redundant ones plus the primary) a [`RedPacket`] may have. RFC 2198 sets
46/// no limit; one or two levels of redundancy are usual, and 32 bounds the parser's work.
47pub const RED_MAX_BLOCKS: usize = 32;
48/// The largest timestamp offset (14 bits).
49pub const RED_MAX_TIMESTAMP_OFFSET: u16 = 0x3FFF;
50/// The largest redundant block length (10 bits).
51pub const RED_MAX_BLOCK_LENGTH: usize = 0x3FF;
52/// The largest RTP payload type (7 bits).
53pub const RED_MAX_PAYLOAD_TYPE: u8 = 0x7F;
54/// Size of a redundant block header.
55pub const RED_REDUNDANT_HEADER_SIZE: usize = 4;
56/// Size of the primary block header.
57pub const RED_PRIMARY_HEADER_SIZE: usize = 1;
58
59/// One block of a RED payload.
60#[derive(PartialEq, Eq, Debug, Default, Clone)]
61pub struct RedBlock {
62    /// RTP payload type of the block's data.
63    pub payload_type: u8,
64    /// How far the block's timestamp is before the RTP timestamp; 0 for the primary.
65    pub timestamp_offset: u16,
66    /// The block's data: a standard RTP payload of `payload_type`.
67    pub data: Bytes,
68    /// Whether this is the primary block.
69    pub primary: bool,
70}
71
72impl RedBlock {
73    /// A redundant block.
74    pub fn redundant(payload_type: u8, timestamp_offset: u16, data: Bytes) -> Self {
75        RedBlock {
76            payload_type,
77            timestamp_offset,
78            data,
79            primary: false,
80        }
81    }
82
83    /// The primary block.
84    pub fn primary(payload_type: u8, data: Bytes) -> Self {
85        RedBlock {
86            payload_type,
87            timestamp_offset: 0,
88            data,
89            primary: true,
90        }
91    }
92
93    /// The block's absolute RTP timestamp, given the RED packet's RTP timestamp.
94    pub fn timestamp(&self, red_timestamp: u32) -> u32 {
95        red_timestamp.wrapping_sub(u32::from(self.timestamp_offset))
96    }
97
98    fn header_size(&self) -> usize {
99        if self.primary {
100            RED_PRIMARY_HEADER_SIZE
101        } else {
102            RED_REDUNDANT_HEADER_SIZE
103        }
104    }
105}
106
107/// One RED payload: redundant blocks in header order, then the primary.
108///
109/// Always valid by construction: at most [`RED_MAX_BLOCKS`] blocks, the last and only the
110/// last one primary, payload types at most 127, redundant offsets at most 0x3FFF and lengths
111/// at most 0x3FF.
112#[derive(PartialEq, Eq, Debug, Clone)]
113pub struct RedPacket {
114    blocks: Vec<RedBlock>,
115}
116
117impl RedPacket {
118    /// A payload of `redundant` blocks (in header order, conventionally oldest first) followed
119    /// by the primary.
120    ///
121    /// # Errors
122    ///
123    /// Fails on a payload type above 127, a redundant offset above 0x3FFF or length above
124    /// 0x3FF, or more than [`RED_MAX_BLOCKS`] blocks in all.
125    pub fn new(
126        primary_payload_type: u8,
127        primary: Bytes,
128        redundant: impl IntoIterator<Item = (u8, u16, Bytes)>,
129    ) -> Result<Self> {
130        let mut blocks: Vec<RedBlock> = redundant
131            .into_iter()
132            .take(RED_MAX_BLOCKS)
133            .map(|(pt, offset, data)| RedBlock::redundant(pt, offset, data))
134            .collect();
135        blocks.push(RedBlock::primary(primary_payload_type, primary));
136        Self::from_blocks(blocks)
137    }
138
139    /// A payload from explicit blocks; the last must be the primary.
140    ///
141    /// # Errors
142    ///
143    /// As [`RedPacket::new`], plus: no block, or a primary block anywhere but last.
144    pub fn from_blocks(blocks: Vec<RedBlock>) -> Result<Self> {
145        if blocks.is_empty() || blocks.len() > RED_MAX_BLOCKS {
146            return Err(Error::Other(format!(
147                "a RED payload has 1 to {RED_MAX_BLOCKS} blocks, not {}",
148                blocks.len()
149            )));
150        }
151        let last = blocks.len() - 1;
152        for (i, block) in blocks.iter().enumerate() {
153            if block.primary != (i == last) {
154                return Err(Error::Other(
155                    "the primary block must be the last and only primary".into(),
156                ));
157            }
158            if block.payload_type > RED_MAX_PAYLOAD_TYPE {
159                return Err(Error::Other(format!(
160                    "RED block payload type {} exceeds 127",
161                    block.payload_type
162                )));
163            }
164            if block.primary {
165                if block.timestamp_offset != 0 {
166                    return Err(Error::Other("the RED primary has no offset".into()));
167                }
168            } else {
169                if block.timestamp_offset > RED_MAX_TIMESTAMP_OFFSET {
170                    return Err(Error::Other(format!(
171                        "RED timestamp offset {} exceeds 0x3FFF",
172                        block.timestamp_offset
173                    )));
174                }
175                if block.data.len() > RED_MAX_BLOCK_LENGTH {
176                    return Err(Error::Other(format!(
177                        "RED block length {} exceeds 0x3FF",
178                        block.data.len()
179                    )));
180                }
181            }
182        }
183        Ok(RedPacket { blocks })
184    }
185
186    /// Parses a RED payload (zero-copy: the blocks' data are slices of `payload`).
187    ///
188    /// # Errors
189    ///
190    /// Fails on an empty payload, a truncated header, no primary header within
191    /// [`RED_MAX_BLOCKS`] headers, or block lengths exceeding the payload.
192    pub fn parse(payload: &Bytes) -> Result<Self> {
193        let mut headers: Vec<(u8, u16, usize)> = Vec::new();
194        let mut pos = 0usize;
195        let primary_pt = loop {
196            let Some(&first) = payload.get(pos) else {
197                return Err(Error::ErrShortPacket);
198            };
199            if first & 0x80 == 0 {
200                pos += RED_PRIMARY_HEADER_SIZE;
201                break first;
202            }
203            if headers.len() + 1 >= RED_MAX_BLOCKS {
204                return Err(Error::Other(format!(
205                    "RED payload has more than {RED_MAX_BLOCKS} blocks"
206                )));
207            }
208            let Some(header) = payload.get(pos..pos + RED_REDUNDANT_HEADER_SIZE) else {
209                return Err(Error::ErrShortPacket);
210            };
211            let rest = u32::from_be_bytes([0, header[1], header[2], header[3]]);
212            headers.push((first & 0x7F, (rest >> 10) as u16, (rest & 0x3FF) as usize));
213            pos += RED_REDUNDANT_HEADER_SIZE;
214        };
215
216        let mut blocks = Vec::with_capacity(headers.len() + 1);
217        for (pt, offset, len) in headers {
218            let end = pos + len;
219            if end > payload.len() {
220                return Err(Error::ErrShortPacket);
221            }
222            blocks.push(RedBlock::redundant(pt, offset, payload.slice(pos..end)));
223            pos = end;
224        }
225        blocks.push(RedBlock::primary(primary_pt, payload.slice(pos..)));
226        Ok(RedPacket { blocks })
227    }
228
229    /// All blocks: redundant ones in header order, the primary last.
230    pub fn blocks(&self) -> &[RedBlock] {
231        &self.blocks
232    }
233
234    /// The redundant blocks, in header order.
235    pub fn redundant(&self) -> &[RedBlock] {
236        &self.blocks[..self.blocks.len() - 1]
237    }
238
239    /// The primary block.
240    pub fn primary(&self) -> &RedBlock {
241        &self.blocks[self.blocks.len() - 1]
242    }
243
244    /// Takes the blocks out.
245    pub fn into_blocks(self) -> Vec<RedBlock> {
246        self.blocks
247    }
248}
249
250impl MarshalSize for RedPacket {
251    fn marshal_size(&self) -> usize {
252        self.blocks
253            .iter()
254            .map(|b| b.header_size() + b.data.len())
255            .sum()
256    }
257}
258
259impl Marshal for RedPacket {
260    /// Writes the headers, F set on all but the primary's, then the data blocks.
261    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
262        let size = self.marshal_size();
263        if buf.remaining_mut() < size {
264            return Err(Error::ErrBufferTooSmall);
265        }
266        for block in &self.blocks {
267            if block.primary {
268                buf.put_u8(block.payload_type);
269            } else {
270                buf.put_u8(0x80 | block.payload_type);
271                let rest = (u32::from(block.timestamp_offset) << 10) | block.data.len() as u32;
272                buf.put_slice(&rest.to_be_bytes()[1..]);
273            }
274        }
275        for block in &self.blocks {
276            buf.put_slice(&block.data);
277        }
278        Ok(size)
279    }
280}
281
282impl Unmarshal for RedPacket {
283    /// Parses all remaining bytes of `buf` as one RED payload (see [`RedPacket::parse`]).
284    fn unmarshal<B>(buf: &mut B) -> Result<Self>
285    where
286        Self: Sized,
287        B: Buf,
288    {
289        let payload = buf.copy_to_bytes(buf.remaining());
290        RedPacket::parse(&payload)
291    }
292}
293
294/// Builds RED payloads whose redundancy is copies of the previous primaries (RFC 2198
295/// section 3), the way Chrome sends Opus RED.
296///
297/// It keeps the last `redundancy` primaries with their timestamps. Each
298/// [`encode`](Self::encode) puts the still-usable ones before the new primary, oldest first,
299/// dropping (oldest first) those whose offset would be 0 or exceed 0x3FFF, whose length exceeds
300/// 0x3FF, or that do not fit `max_payload_size`. Deterministic and bounded.
301#[derive(Debug, Clone)]
302pub struct RedEncoder {
303    redundancy: usize,
304    max_payload_size: usize,
305    history: VecDeque<(u32, u8, Bytes)>,
306}
307
308impl RedEncoder {
309    /// An encoder carrying up to `redundancy` earlier primaries (capped at
310    /// `RED_MAX_BLOCKS - 1`) in payloads of at most `max_payload_size` bytes.
311    pub fn new(redundancy: usize, max_payload_size: usize) -> Self {
312        let redundancy = redundancy.min(RED_MAX_BLOCKS - 1);
313        RedEncoder {
314            redundancy,
315            max_payload_size,
316            history: VecDeque::with_capacity(redundancy),
317        }
318    }
319
320    /// The configured redundancy level.
321    pub fn redundancy(&self) -> usize {
322        self.redundancy
323    }
324
325    /// Forgets the earlier primaries (for a stream restart or timestamp jump).
326    pub fn reset(&mut self) {
327        self.history.clear();
328    }
329
330    /// The RED packet for a new primary at RTP `timestamp`. The caller sends it with the RED
331    /// payload type, this `timestamp` and the primary's marker bit.
332    ///
333    /// # Errors
334    ///
335    /// Fails on a payload type above 127, or a primary that alone does not fit
336    /// `max_payload_size` (nothing is remembered then).
337    pub fn encode_packet(
338        &mut self,
339        payload_type: u8,
340        timestamp: u32,
341        payload: Bytes,
342    ) -> Result<RedPacket> {
343        self.encode_packet_keeping(payload_type, timestamp, payload, None)
344    }
345
346    /// As [`encode_packet`](Self::encode_packet), but the later packets carry `redundant` as
347    /// this primary's redundant copy instead of the primary itself: another encoding of the
348    /// same audio, at the primary's payload type and timestamp, at a lower bitrate (RFC 2198
349    /// section 3: "It is expected that the redundant encoding shall use significantly less
350    /// bandwidth that the primary encoding"; RFC 8854 section 4.1: "redundant encoding with
351    /// reduced-bitrate Opus encodings"). A `redundant` larger than the primary is not kept
352    /// (RFC 2198 section 3: it "MUST NOT be higher bandwidth than the primary"): the primary
353    /// is, as [`encode_packet`](Self::encode_packet) keeps it.
354    ///
355    /// # Errors
356    ///
357    /// As [`encode_packet`](Self::encode_packet).
358    pub fn encode_packet_with_redundant(
359        &mut self,
360        payload_type: u8,
361        timestamp: u32,
362        payload: Bytes,
363        redundant: Bytes,
364    ) -> Result<RedPacket> {
365        self.encode_packet_keeping(payload_type, timestamp, payload, Some(redundant))
366    }
367
368    fn encode_packet_keeping(
369        &mut self,
370        payload_type: u8,
371        timestamp: u32,
372        payload: Bytes,
373        redundant_copy: Option<Bytes>,
374    ) -> Result<RedPacket> {
375        if payload_type > RED_MAX_PAYLOAD_TYPE {
376            return Err(Error::Other(format!(
377                "RED block payload type {payload_type} exceeds 127"
378            )));
379        }
380        let primary_size = RED_PRIMARY_HEADER_SIZE + payload.len();
381        if primary_size > self.max_payload_size {
382            return Err(Error::ErrPacketTooBig);
383        }
384
385        let mut redundant: Vec<(u8, u16, Bytes)> = self
386            .history
387            .iter()
388            .filter_map(|(ts, pt, data)| {
389                let offset = timestamp.wrapping_sub(*ts);
390                (offset >= 1
391                    && offset <= u32::from(RED_MAX_TIMESTAMP_OFFSET)
392                    && data.len() <= RED_MAX_BLOCK_LENGTH)
393                    .then(|| (*pt, offset as u16, data.clone()))
394            })
395            .collect();
396        let mut size = primary_size
397            + redundant
398                .iter()
399                .map(|(_, _, d)| RED_REDUNDANT_HEADER_SIZE + d.len())
400                .sum::<usize>();
401        let mut drop = 0;
402        while size > self.max_payload_size && drop < redundant.len() {
403            size -= RED_REDUNDANT_HEADER_SIZE + redundant[drop].2.len();
404            drop += 1;
405        }
406        redundant.drain(..drop);
407
408        let packet = RedPacket::new(payload_type, payload.clone(), redundant)?;
409        if self.redundancy > 0 {
410            if self.history.len() == self.redundancy {
411                self.history.pop_front();
412            }
413            let copy = redundant_copy
414                .filter(|redundant| redundant.len() <= payload.len())
415                .unwrap_or(payload);
416            self.history.push_back((timestamp, payload_type, copy));
417        }
418        Ok(packet)
419    }
420
421    /// The RED RTP packet for the media packet `primary` (RFC 2198 section 3): "a standard
422    /// RTP header ... where the payload type field indicates the redundant encoding" and the
423    /// other fields (sequence number, timestamp, marker, SSRC, CSRCs, extensions) are those of
424    /// the primary. Its payload is [`encode_packet`](Self::encode_packet) of the primary's.
425    ///
426    /// # Errors
427    ///
428    /// As [`encode_packet`](Self::encode_packet), and for a RED payload type above 127.
429    pub fn encode_rtp(
430        &mut self,
431        red_payload_type: u8,
432        primary: &crate::packet::Packet,
433    ) -> Result<crate::packet::Packet> {
434        self.encode_rtp_keeping(red_payload_type, primary, None)
435    }
436
437    /// As [`encode_rtp`](Self::encode_rtp), the later packets carrying `redundant` as this
438    /// primary's copy ([`encode_packet_with_redundant`](Self::encode_packet_with_redundant)).
439    ///
440    /// # Errors
441    ///
442    /// As [`encode_rtp`](Self::encode_rtp).
443    pub fn encode_rtp_with_redundant(
444        &mut self,
445        red_payload_type: u8,
446        primary: &crate::packet::Packet,
447        redundant: Bytes,
448    ) -> Result<crate::packet::Packet> {
449        self.encode_rtp_keeping(red_payload_type, primary, Some(redundant))
450    }
451
452    fn encode_rtp_keeping(
453        &mut self,
454        red_payload_type: u8,
455        primary: &crate::packet::Packet,
456        redundant: Option<Bytes>,
457    ) -> Result<crate::packet::Packet> {
458        if red_payload_type > RED_MAX_PAYLOAD_TYPE {
459            return Err(Error::Other(format!(
460                "RED payload type {red_payload_type} exceeds 127"
461            )));
462        }
463        let payload = self
464            .encode_packet_keeping(
465                primary.header.payload_type,
466                primary.header.timestamp,
467                primary.payload.clone(),
468                redundant,
469            )?
470            .marshal()?
471            .freeze();
472        let mut header = primary.header.clone();
473        header.payload_type = red_payload_type;
474        Ok(crate::packet::Packet { header, payload })
475    }
476
477    /// As [`encode_packet`](Self::encode_packet), marshalled.
478    ///
479    /// # Errors
480    ///
481    /// As [`encode_packet`](Self::encode_packet).
482    pub fn encode(&mut self, payload_type: u8, timestamp: u32, payload: Bytes) -> Result<Bytes> {
483        Ok(self
484            .encode_packet(payload_type, timestamp, payload)?
485            .marshal()?
486            .freeze())
487    }
488}
489
490/// A payload a [`RedDecoder`] delivers.
491#[derive(PartialEq, Eq, Debug, Clone)]
492pub struct RecoveredBlock {
493    /// RTP timestamp of the data.
494    pub timestamp: u32,
495    /// Payload type of the data.
496    pub payload_type: u8,
497    /// The data: a standard RTP payload of `payload_type`.
498    pub data: Bytes,
499    /// `true` for the primary of the packet fed in, `false` for data recovered from a
500    /// redundant block (whose marker bit is unknown).
501    pub primary: bool,
502}
503
504/// A block [`RedDecoder::decode_rtp`] delivers, with what of the RED packet's header
505/// applies to it (RFC 2198 section 4).
506#[derive(PartialEq, Eq, Debug, Clone)]
507pub struct RecoveredMedia {
508    /// The block.
509    pub block: RecoveredBlock,
510    /// The marker bit: the RED packet's for its primary; `false` for recovered data, whose
511    /// marker "is lost" with its packet.
512    pub marker: bool,
513    /// The CSRC list of the RED packet, which "should be applied to the reconstructed
514    /// redundant data" as to the primary.
515    pub csrc: Vec<u32>,
516}
517
518/// The default number of recent deliveries a [`RedDecoder`] remembers.
519pub const RED_DEFAULT_DUPLICATE_WINDOW: usize = 64;
520/// The largest duplicate window a [`RedDecoder`] accepts.
521pub const RED_MAX_DUPLICATE_WINDOW: usize = 1024;
522
523/// Unpacks RED packets and recovers lost primaries from later packets' redundant blocks
524/// (RFC 2198 section 3), without delivering anything twice.
525///
526/// Each [`decode`](Self::decode) returns, in timestamp order, the redundant blocks whose
527/// timestamp was not delivered yet, then the packet's primary (unless the same sequence
528/// number, or a timestamp already recovered, was delivered). It remembers the last `window`
529/// sequence numbers and timestamps it delivered; older duplicates can come through again.
530///
531/// The decoder exposes nothing of the RTP header for recovered data (section 4): its marker
532/// bit was lost with the primary, and the RED packet's CSRC list, which the caller has, is the
533/// one to apply to it.
534#[derive(Debug, Clone)]
535pub struct RedDecoder {
536    window: usize,
537    sequence_numbers: VecDeque<u16>,
538    /// Delivered timestamps, and whether each was a recovery.
539    timestamps: VecDeque<(u32, bool)>,
540}
541
542impl Default for RedDecoder {
543    fn default() -> Self {
544        Self::new(RED_DEFAULT_DUPLICATE_WINDOW)
545    }
546}
547
548impl RedDecoder {
549    /// A decoder remembering the last `window` deliveries (1 to
550    /// [`RED_MAX_DUPLICATE_WINDOW`]; out-of-range values are clamped).
551    pub fn new(window: usize) -> Self {
552        let window = window.clamp(1, RED_MAX_DUPLICATE_WINDOW);
553        RedDecoder {
554            window,
555            sequence_numbers: VecDeque::with_capacity(window),
556            timestamps: VecDeque::with_capacity(window),
557        }
558    }
559
560    /// Decodes one RED packet with RTP `sequence_number` and `timestamp`.
561    ///
562    /// The primary is matched against earlier primaries by sequence number (several packets
563    /// may share a timestamp) and against recoveries by timestamp; a redundant block is
564    /// matched against everything delivered by timestamp.
565    ///
566    /// # Errors
567    ///
568    /// Fails on a malformed payload (see [`RedPacket::parse`]); state is unchanged then.
569    pub fn decode(
570        &mut self,
571        sequence_number: u16,
572        timestamp: u32,
573        payload: &Bytes,
574    ) -> Result<Vec<RecoveredBlock>> {
575        let packet = RedPacket::parse(payload)?;
576        let mut out = Vec::with_capacity(packet.blocks.len());
577
578        let mut redundant: Vec<&RedBlock> = packet
579            .redundant()
580            .iter()
581            .filter(|b| b.timestamp_offset != 0)
582            .collect();
583        // Oldest first: largest offset first; stable for equal offsets.
584        redundant.sort_by_key(|b| std::cmp::Reverse(b.timestamp_offset));
585        for block in redundant {
586            let ts = block.timestamp(timestamp);
587            if self.timestamps.iter().any(|(t, _)| *t == ts) {
588                continue;
589            }
590            self.remember_timestamp(ts, true);
591            out.push(RecoveredBlock {
592                timestamp: ts,
593                payload_type: block.payload_type,
594                data: block.data.clone(),
595                primary: false,
596            });
597        }
598
599        let primary = packet.primary();
600        let seen_sequence = self.sequence_numbers.contains(&sequence_number);
601        let recovered_before = self.timestamps.iter().any(|(t, r)| *r && *t == timestamp);
602        if !seen_sequence && !recovered_before {
603            if self.sequence_numbers.len() == self.window {
604                self.sequence_numbers.pop_front();
605            }
606            self.sequence_numbers.push_back(sequence_number);
607            self.remember_timestamp(timestamp, false);
608            out.push(RecoveredBlock {
609                timestamp,
610                payload_type: primary.payload_type,
611                data: primary.data.clone(),
612                primary: true,
613            });
614        }
615        Ok(out)
616    }
617
618    /// [`decode`](Self::decode) of a RED RTP packet, each block with the marker bit and the
619    /// CSRC list section 4 gives it.
620    ///
621    /// # Errors
622    ///
623    /// As [`decode`](Self::decode).
624    pub fn decode_rtp(&mut self, packet: &crate::packet::Packet) -> Result<Vec<RecoveredMedia>> {
625        let header = &packet.header;
626        Ok(self
627            .decode(header.sequence_number, header.timestamp, &packet.payload)?
628            .into_iter()
629            .map(|block| RecoveredMedia {
630                marker: block.primary && header.marker,
631                csrc: header.csrc.clone(),
632                block,
633            })
634            .collect())
635    }
636
637    fn remember_timestamp(&mut self, timestamp: u32, recovered: bool) {
638        if self.timestamps.len() == self.window {
639            self.timestamps.pop_front();
640        }
641        self.timestamps.push_back((timestamp, recovered));
642    }
643}
644
645/// Returns a RED payload's primary data, for audio streams whose RED payload type is
646/// depacketized like a codec. Redundant blocks are dropped; use [`RedDecoder`] to recover from
647/// them.
648#[derive(PartialEq, Eq, Debug, Default, Clone)]
649pub struct RedDepacketizer;
650
651impl Depacketizer for RedDepacketizer {
652    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
653        Ok(RedPacket::parse(packet)?.primary().data.clone())
654    }
655
656    fn is_partition_head(&self, _payload: &Bytes) -> bool {
657        true
658    }
659
660    fn is_partition_tail(&self, _marker: bool, _payload: &Bytes) -> bool {
661        true
662    }
663}
664
665/// Parses the RED fmtp list, `a=fmtp:<pt> 111/111` (section 5): the payload types of the
666/// primary and then the redundant encodings, slash-separated.
667///
668/// # Errors
669///
670/// Fails on an empty list or entry, a non-decimal entry, a payload type above 127, or more
671/// than [`RED_MAX_BLOCKS`] entries.
672pub fn parse_red_fmtp(fmtp: &str) -> Result<Vec<u8>> {
673    let mut out = Vec::new();
674    for entry in fmtp.split('/') {
675        if out.len() == RED_MAX_BLOCKS {
676            return Err(Error::Other(format!(
677                "RED fmtp lists more than {RED_MAX_BLOCKS} encodings"
678            )));
679        }
680        if entry.is_empty() || entry.len() > 3 || !entry.bytes().all(|b| b.is_ascii_digit()) {
681            return Err(Error::Other(format!("invalid RED fmtp entry {entry:?}")));
682        }
683        let pt: u8 = entry
684            .parse()
685            .map_err(|_| Error::Other(format!("invalid RED fmtp entry {entry:?}")))?;
686        if pt > RED_MAX_PAYLOAD_TYPE {
687            return Err(Error::Other(format!(
688                "RED fmtp payload type {pt} exceeds 127"
689            )));
690        }
691        out.push(pt);
692    }
693    Ok(out)
694}
695
696/// Formats a RED fmtp list: payload types joined by `/`.
697pub fn format_red_fmtp(payload_types: &[u8]) -> String {
698    payload_types
699        .iter()
700        .map(|pt| pt.to_string())
701        .collect::<Vec<_>>()
702        .join("/")
703}