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        if payload_type > RED_MAX_PAYLOAD_TYPE {
344            return Err(Error::Other(format!(
345                "RED block payload type {payload_type} exceeds 127"
346            )));
347        }
348        let primary_size = RED_PRIMARY_HEADER_SIZE + payload.len();
349        if primary_size > self.max_payload_size {
350            return Err(Error::ErrPacketTooBig);
351        }
352
353        let mut redundant: Vec<(u8, u16, Bytes)> = self
354            .history
355            .iter()
356            .filter_map(|(ts, pt, data)| {
357                let offset = timestamp.wrapping_sub(*ts);
358                (offset >= 1
359                    && offset <= u32::from(RED_MAX_TIMESTAMP_OFFSET)
360                    && data.len() <= RED_MAX_BLOCK_LENGTH)
361                    .then(|| (*pt, offset as u16, data.clone()))
362            })
363            .collect();
364        let mut size = primary_size
365            + redundant
366                .iter()
367                .map(|(_, _, d)| RED_REDUNDANT_HEADER_SIZE + d.len())
368                .sum::<usize>();
369        let mut drop = 0;
370        while size > self.max_payload_size && drop < redundant.len() {
371            size -= RED_REDUNDANT_HEADER_SIZE + redundant[drop].2.len();
372            drop += 1;
373        }
374        redundant.drain(..drop);
375
376        let packet = RedPacket::new(payload_type, payload.clone(), redundant)?;
377        if self.redundancy > 0 {
378            if self.history.len() == self.redundancy {
379                self.history.pop_front();
380            }
381            self.history.push_back((timestamp, payload_type, payload));
382        }
383        Ok(packet)
384    }
385
386    /// The RED RTP packet for the media packet `primary` (RFC 2198 section 3): "a standard
387    /// RTP header ... where the payload type field indicates the redundant encoding" and the
388    /// other fields (sequence number, timestamp, marker, SSRC, CSRCs, extensions) are those of
389    /// the primary. Its payload is [`encode_packet`](Self::encode_packet) of the primary's.
390    ///
391    /// # Errors
392    ///
393    /// As [`encode_packet`](Self::encode_packet), and for a RED payload type above 127.
394    pub fn encode_rtp(
395        &mut self,
396        red_payload_type: u8,
397        primary: &crate::packet::Packet,
398    ) -> Result<crate::packet::Packet> {
399        if red_payload_type > RED_MAX_PAYLOAD_TYPE {
400            return Err(Error::Other(format!(
401                "RED payload type {red_payload_type} exceeds 127"
402            )));
403        }
404        let payload = self
405            .encode_packet(
406                primary.header.payload_type,
407                primary.header.timestamp,
408                primary.payload.clone(),
409            )?
410            .marshal()?
411            .freeze();
412        let mut header = primary.header.clone();
413        header.payload_type = red_payload_type;
414        Ok(crate::packet::Packet { header, payload })
415    }
416
417    /// As [`encode_packet`](Self::encode_packet), marshalled.
418    ///
419    /// # Errors
420    ///
421    /// As [`encode_packet`](Self::encode_packet).
422    pub fn encode(&mut self, payload_type: u8, timestamp: u32, payload: Bytes) -> Result<Bytes> {
423        Ok(self
424            .encode_packet(payload_type, timestamp, payload)?
425            .marshal()?
426            .freeze())
427    }
428}
429
430/// A payload a [`RedDecoder`] delivers.
431#[derive(PartialEq, Eq, Debug, Clone)]
432pub struct RecoveredBlock {
433    /// RTP timestamp of the data.
434    pub timestamp: u32,
435    /// Payload type of the data.
436    pub payload_type: u8,
437    /// The data: a standard RTP payload of `payload_type`.
438    pub data: Bytes,
439    /// `true` for the primary of the packet fed in, `false` for data recovered from a
440    /// redundant block (whose marker bit is unknown).
441    pub primary: bool,
442}
443
444/// A block [`RedDecoder::decode_rtp`] delivers, with what of the RED packet's header
445/// applies to it (RFC 2198 section 4).
446#[derive(PartialEq, Eq, Debug, Clone)]
447pub struct RecoveredMedia {
448    /// The block.
449    pub block: RecoveredBlock,
450    /// The marker bit: the RED packet's for its primary; `false` for recovered data, whose
451    /// marker "is lost" with its packet.
452    pub marker: bool,
453    /// The CSRC list of the RED packet, which "should be applied to the reconstructed
454    /// redundant data" as to the primary.
455    pub csrc: Vec<u32>,
456}
457
458/// The default number of recent deliveries a [`RedDecoder`] remembers.
459pub const RED_DEFAULT_DUPLICATE_WINDOW: usize = 64;
460/// The largest duplicate window a [`RedDecoder`] accepts.
461pub const RED_MAX_DUPLICATE_WINDOW: usize = 1024;
462
463/// Unpacks RED packets and recovers lost primaries from later packets' redundant blocks
464/// (RFC 2198 section 3), without delivering anything twice.
465///
466/// Each [`decode`](Self::decode) returns, in timestamp order, the redundant blocks whose
467/// timestamp was not delivered yet, then the packet's primary (unless the same sequence
468/// number, or a timestamp already recovered, was delivered). It remembers the last `window`
469/// sequence numbers and timestamps it delivered; older duplicates can come through again.
470///
471/// The decoder exposes nothing of the RTP header for recovered data (section 4): its marker
472/// bit was lost with the primary, and the RED packet's CSRC list, which the caller has, is the
473/// one to apply to it.
474#[derive(Debug, Clone)]
475pub struct RedDecoder {
476    window: usize,
477    sequence_numbers: VecDeque<u16>,
478    /// Delivered timestamps, and whether each was a recovery.
479    timestamps: VecDeque<(u32, bool)>,
480}
481
482impl Default for RedDecoder {
483    fn default() -> Self {
484        Self::new(RED_DEFAULT_DUPLICATE_WINDOW)
485    }
486}
487
488impl RedDecoder {
489    /// A decoder remembering the last `window` deliveries (1 to
490    /// [`RED_MAX_DUPLICATE_WINDOW`]; out-of-range values are clamped).
491    pub fn new(window: usize) -> Self {
492        let window = window.clamp(1, RED_MAX_DUPLICATE_WINDOW);
493        RedDecoder {
494            window,
495            sequence_numbers: VecDeque::with_capacity(window),
496            timestamps: VecDeque::with_capacity(window),
497        }
498    }
499
500    /// Decodes one RED packet with RTP `sequence_number` and `timestamp`.
501    ///
502    /// The primary is matched against earlier primaries by sequence number (several packets
503    /// may share a timestamp) and against recoveries by timestamp; a redundant block is
504    /// matched against everything delivered by timestamp.
505    ///
506    /// # Errors
507    ///
508    /// Fails on a malformed payload (see [`RedPacket::parse`]); state is unchanged then.
509    pub fn decode(
510        &mut self,
511        sequence_number: u16,
512        timestamp: u32,
513        payload: &Bytes,
514    ) -> Result<Vec<RecoveredBlock>> {
515        let packet = RedPacket::parse(payload)?;
516        let mut out = Vec::with_capacity(packet.blocks.len());
517
518        let mut redundant: Vec<&RedBlock> = packet
519            .redundant()
520            .iter()
521            .filter(|b| b.timestamp_offset != 0)
522            .collect();
523        // Oldest first: largest offset first; stable for equal offsets.
524        redundant.sort_by_key(|b| std::cmp::Reverse(b.timestamp_offset));
525        for block in redundant {
526            let ts = block.timestamp(timestamp);
527            if self.timestamps.iter().any(|(t, _)| *t == ts) {
528                continue;
529            }
530            self.remember_timestamp(ts, true);
531            out.push(RecoveredBlock {
532                timestamp: ts,
533                payload_type: block.payload_type,
534                data: block.data.clone(),
535                primary: false,
536            });
537        }
538
539        let primary = packet.primary();
540        let seen_sequence = self.sequence_numbers.contains(&sequence_number);
541        let recovered_before = self.timestamps.iter().any(|(t, r)| *r && *t == timestamp);
542        if !seen_sequence && !recovered_before {
543            if self.sequence_numbers.len() == self.window {
544                self.sequence_numbers.pop_front();
545            }
546            self.sequence_numbers.push_back(sequence_number);
547            self.remember_timestamp(timestamp, false);
548            out.push(RecoveredBlock {
549                timestamp,
550                payload_type: primary.payload_type,
551                data: primary.data.clone(),
552                primary: true,
553            });
554        }
555        Ok(out)
556    }
557
558    /// [`decode`](Self::decode) of a RED RTP packet, each block with the marker bit and the
559    /// CSRC list section 4 gives it.
560    ///
561    /// # Errors
562    ///
563    /// As [`decode`](Self::decode).
564    pub fn decode_rtp(&mut self, packet: &crate::packet::Packet) -> Result<Vec<RecoveredMedia>> {
565        let header = &packet.header;
566        Ok(self
567            .decode(header.sequence_number, header.timestamp, &packet.payload)?
568            .into_iter()
569            .map(|block| RecoveredMedia {
570                marker: block.primary && header.marker,
571                csrc: header.csrc.clone(),
572                block,
573            })
574            .collect())
575    }
576
577    fn remember_timestamp(&mut self, timestamp: u32, recovered: bool) {
578        if self.timestamps.len() == self.window {
579            self.timestamps.pop_front();
580        }
581        self.timestamps.push_back((timestamp, recovered));
582    }
583}
584
585/// Returns a RED payload's primary data, for audio streams whose RED payload type is
586/// depacketized like a codec. Redundant blocks are dropped; use [`RedDecoder`] to recover from
587/// them.
588#[derive(PartialEq, Eq, Debug, Default, Clone)]
589pub struct RedDepacketizer;
590
591impl Depacketizer for RedDepacketizer {
592    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
593        Ok(RedPacket::parse(packet)?.primary().data.clone())
594    }
595
596    fn is_partition_head(&self, _payload: &Bytes) -> bool {
597        true
598    }
599
600    fn is_partition_tail(&self, _marker: bool, _payload: &Bytes) -> bool {
601        true
602    }
603}
604
605/// Parses the RED fmtp list, `a=fmtp:<pt> 111/111` (section 5): the payload types of the
606/// primary and then the redundant encodings, slash-separated.
607///
608/// # Errors
609///
610/// Fails on an empty list or entry, a non-decimal entry, a payload type above 127, or more
611/// than [`RED_MAX_BLOCKS`] entries.
612pub fn parse_red_fmtp(fmtp: &str) -> Result<Vec<u8>> {
613    let mut out = Vec::new();
614    for entry in fmtp.split('/') {
615        if out.len() == RED_MAX_BLOCKS {
616            return Err(Error::Other(format!(
617                "RED fmtp lists more than {RED_MAX_BLOCKS} encodings"
618            )));
619        }
620        if entry.is_empty() || entry.len() > 3 || !entry.bytes().all(|b| b.is_ascii_digit()) {
621            return Err(Error::Other(format!("invalid RED fmtp entry {entry:?}")));
622        }
623        let pt: u8 = entry
624            .parse()
625            .map_err(|_| Error::Other(format!("invalid RED fmtp entry {entry:?}")))?;
626        if pt > RED_MAX_PAYLOAD_TYPE {
627            return Err(Error::Other(format!(
628                "RED fmtp payload type {pt} exceeds 127"
629            )));
630        }
631        out.push(pt);
632    }
633    Ok(out)
634}
635
636/// Formats a RED fmtp list: payload types joined by `/`.
637pub fn format_red_fmtp(payload_types: &[u8]) -> String {
638    payload_types
639        .iter()
640        .map(|pt| pt.to_string())
641        .collect::<Vec<_>>()
642        .join("/")
643}