rvoip-rtc 0.5.2

Attributed rvoip fork of the sans-I/O rtc 0.21.1 stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use crate::peer_connection::configuration::UNSPECIFIED_STR;
use crate::peer_connection::configuration::media_engine::*;
use crate::rtp_transceiver::rtp_sender::rtcp_parameters::RTCPFeedback;
use crate::rtp_transceiver::rtp_sender::rtp_codec_parameters::RTCRtpCodecParameters;
use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
use crate::rtp_transceiver::{PayloadType, fmtp};
use serde::{Deserialize, Serialize};
use shared::error::{Error, Result};
use std::fmt;

/// Codec kind identifying the media type.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum RtpCodecKind {
    /// Unspecified or unknown codec type
    #[default]
    Unspecified = 0,

    /// Audio codec
    #[serde(rename = "audio")]
    Audio = 1,

    /// Video codec
    #[serde(rename = "video")]
    Video = 2,

    /// Non-audio/video RTP-carried application data
    #[serde(rename = "application")]
    Application = 3,
}

impl From<&str> for RtpCodecKind {
    fn from(raw: &str) -> Self {
        match raw {
            "audio" => RtpCodecKind::Audio,
            "video" => RtpCodecKind::Video,
            "application" => RtpCodecKind::Application,
            _ => RtpCodecKind::Unspecified,
        }
    }
}

impl From<u8> for RtpCodecKind {
    fn from(v: u8) -> Self {
        match v {
            1 => RtpCodecKind::Audio,
            2 => RtpCodecKind::Video,
            3 => RtpCodecKind::Application,
            _ => RtpCodecKind::Unspecified,
        }
    }
}

impl fmt::Display for RtpCodecKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match *self {
            RtpCodecKind::Audio => "audio",
            RtpCodecKind::Video => "video",
            RtpCodecKind::Application => "application",
            RtpCodecKind::Unspecified => UNSPECIFIED_STR,
        };
        write!(f, "{s}")
    }
}

/// RTP codec capability providing information about supported codecs.
///
/// ## Specifications
///
/// * [W3C](https://www.w3.org/TR/webrtc/#dictionary-rtcrtpcodec-members)
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct RTCRtpCodec {
    /// MIME type of the codec (e.g., "video/VP8", "audio/opus")
    pub mime_type: String,
    /// Codec clock rate in Hz
    pub clock_rate: u32,
    /// Number of audio channels (0 for video codecs)
    pub channels: u16,
    /// Format-specific parameters as SDP fmtp line
    pub sdp_fmtp_line: String,
    /// RTCP feedback mechanisms supported by this codec (deprecated, will be removed)
    pub rtcp_feedback: Vec<RTCPFeedback>, //TODO: to be removed
}

impl RTCRtpCodec {
    /// Creates an RTP payloader for this codec.
    ///
    /// Returns a boxed trait object implementing the Payloader interface
    /// for packetizing media frames into RTP packets.
    ///
    /// # Errors
    ///
    /// Returns `Error::ErrNoPayloaderForCodec` if the codec is not supported.
    pub fn payloader(&self) -> Result<Box<dyn rtp::packetizer::Payloader>> {
        let mime_type = self.mime_type.to_lowercase();
        if mime_type == MIME_TYPE_H264.to_lowercase() {
            Ok(Box::<rtp::codec::h264::H264Payloader>::default())
        } else if mime_type == MIME_TYPE_HEVC.to_lowercase() {
            Ok(Box::<rtp::codec::h265::HevcPayloader>::default())
        } else if mime_type == MIME_TYPE_VP8.to_lowercase() {
            let mut vp8_payloader = rtp::codec::vp8::Vp8Payloader::default();
            vp8_payloader.enable_picture_id = true;
            Ok(Box::new(vp8_payloader))
        } else if mime_type == MIME_TYPE_VP9.to_lowercase() {
            Ok(Box::<rtp::codec::vp9::Vp9Payloader>::default())
        } else if mime_type == MIME_TYPE_OPUS.to_lowercase() {
            Ok(Box::<rtp::codec::opus::OpusPayloader>::default())
        } else if mime_type == MIME_TYPE_G722.to_lowercase()
            || mime_type == MIME_TYPE_PCMU.to_lowercase()
            || mime_type == MIME_TYPE_PCMA.to_lowercase()
            || mime_type == MIME_TYPE_TELEPHONE_EVENT.to_lowercase()
        {
            Ok(Box::<rtp::codec::g7xx::G7xxPayloader>::default())
        } else if mime_type == MIME_TYPE_AV1.to_lowercase() {
            Ok(Box::<rtp::codec::av1::Av1Payloader>::default())
        } else if mime_type == MIME_TYPE_SMPTE336M.to_lowercase() {
            Ok(Box::<rtp::codec::smpte336m::Smpte336mPayloader>::default())
        } else {
            Err(Error::ErrNoPayloaderForCodec)
        }
    }
}

/// Codec match quality result from fuzzy search.
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub(crate) enum CodecMatch {
    /// No match found
    #[default]
    None = 0,
    /// Partial match (MIME type matches)
    Partial = 1,
    /// Exact match (MIME type and format parameters match)
    Exact = 2,
}

fn codec_identity_matches(needle: &RTCRtpCodec, candidate: &RTCRtpCodec) -> bool {
    needle.mime_type.eq_ignore_ascii_case(&candidate.mime_type)
        // A zero value is retained as an unspecified/wildcard value for
        // callers constructed from SDP forms that omit an optional field.
        && (needle.clock_rate == 0
            || candidate.clock_rate == 0
            || needle.clock_rate == candidate.clock_rate)
        && (needle.channels == 0
            || candidate.channels == 0
            || needle.channels == candidate.channels)
}

/// Performs fuzzy search for a codec in a list of available codecs.
///
/// First attempts an exact match on codec identity (MIME type, clock rate,
/// and channel count) plus format parameters, then falls back to codec
/// identity without requiring matching format parameters. A zero clock rate
/// or channel count is treated as unspecified for compatibility with SDP
/// forms that omit the optional value.
///
/// # Parameters
///
/// * `needle_rtp_codec` - The codec to search for
/// * `haystack` - List of available codecs to search in
///
/// # Returns
///
/// A tuple of (matched codec parameters, match quality)
pub(crate) fn codec_parameters_fuzzy_search(
    needle_rtp_codec: &RTCRtpCodec,
    haystack: &[RTCRtpCodecParameters],
) -> (RTCRtpCodecParameters, CodecMatch) {
    let needle_fmtp = fmtp::parse(&needle_rtp_codec.mime_type, &needle_rtp_codec.sdp_fmtp_line);

    //TODO: add unicode case-folding equal support

    // First attempt to match codec identity + sdpfmtp_line.
    for c in haystack {
        if !codec_identity_matches(needle_rtp_codec, &c.rtp_codec) {
            continue;
        }
        let cfmpt = fmtp::parse(&c.rtp_codec.mime_type, &c.rtp_codec.sdp_fmtp_line);
        if needle_fmtp.match_fmtp(&*cfmpt) {
            return (c.clone(), CodecMatch::Exact);
        }
    }

    // Fallback keeps the codec identity constraints but permits an fmtp
    // mismatch. In particular, it must not collapse separate RTP clock rates
    // for codecs such as telephone-event into the first registered payload.
    for c in haystack {
        if codec_identity_matches(needle_rtp_codec, &c.rtp_codec) {
            return (c.clone(), CodecMatch::Partial);
        }
    }

    (RTCRtpCodecParameters::default(), CodecMatch::None)
}

/// Searches for a matching encoding in available codecs.
///
/// Iterates through encodings looking for the best codec match, preferring exact matches.
///
/// # Parameters
///
/// * `encodings` - List of encoding parameters to search through
/// * `haystack` - List of available codec parameters
///
/// # Returns
///
/// A tuple of (matched encoding, match quality)
pub(crate) fn encoding_parameters_fuzzy_search(
    encodings: &[RTCRtpEncodingParameters],
    haystack: &[RTCRtpCodecParameters],
) -> (RTCRtpEncodingParameters, CodecMatch) {
    let mut result = None;
    for encoding in encodings {
        let (_, codec_match_type) = codec_parameters_fuzzy_search(&encoding.codec, haystack);
        if codec_match_type == CodecMatch::Exact {
            return (encoding.clone(), codec_match_type);
        } else if result.is_none() {
            result = Some((encoding.clone(), CodecMatch::Partial));
        }
    }

    if let Some((encoding, code_match_type)) = result {
        (encoding, code_match_type)
    } else {
        (RTCRtpEncodingParameters::default(), CodecMatch::None)
    }
}

/// Finds the RTX payload type associated with a given payload type.
///
/// Searches for an RTX codec with the matching APT (Associated Payload Type) parameter.
///
/// # Parameters
///
/// * `needle` - The primary payload type to find RTX for
/// * `haystack` - List of codec parameters to search
///
/// # Returns
///
/// The RTX payload type if found, None otherwise
pub(crate) fn find_rtx_payload_type(
    needle: PayloadType,
    haystack: &[RTCRtpCodecParameters],
) -> Option<PayloadType> {
    for c in haystack {
        // Match on the parsed `apt` value rather than the whole fmtp line, so an
        // RTX codec carrying extra parameters (e.g. `apt=96;rtx-time=3000`, RFC
        // 4588 §8.1) is still associated with its primary.
        if parse_rtx_apt(&c.rtp_codec.sdp_fmtp_line) == Some(needle) {
            return Some(c.payload_type);
        }
    }

    None
}

/// Parses the associated payload type (`apt`) from an RTX codec's fmtp line.
///
/// RFC 4588 §8.1 defines the `apt` parameter, which maps a retransmission
/// payload type to the payload type of the stream it repairs. The fmtp line may
/// carry additional parameters (e.g. `apt=96;rtx-time=3000`), so the value is
/// extracted from the `apt=` token rather than compared against the whole line.
///
/// # Parameters
///
/// * `sdp_fmtp_line` - The RTX codec's fmtp line, e.g. `"apt=96"`
///
/// # Returns
///
/// The associated (primary) payload type if an `apt=` token is present, else None.
pub(crate) fn parse_rtx_apt(sdp_fmtp_line: &str) -> Option<PayloadType> {
    sdp_fmtp_line
        .split(';')
        .filter_map(|param| param.trim().strip_prefix("apt="))
        .find_map(|value| value.trim().parse::<PayloadType>().ok())
}

/// Whether `codec` repairs another stream rather than carrying media of its own.
///
/// Covers retransmission (RTX, RFC 4588) and forward error correction (FlexFEC, ULPFEC, RED).
/// These are not alternative media formats a peer chooses between — they accompany whichever
/// primary codec was chosen — which is why codec preferences leave them in place. See
/// [setCodecPreferences](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences):
///
/// > Codecs of type RTX, RED and FEC are always supported […] and are not affected by this method.
pub(crate) fn is_repair_codec(codec: &RTCRtpCodec) -> bool {
    let mime_type = codec.mime_type.to_lowercase();
    let subtype = mime_type
        .split_once('/')
        .map_or(mime_type.as_str(), |(_, subtype)| subtype);

    matches!(subtype, "rtx" | "ulpfec" | "red") || subtype.starts_with("flexfec")
}

// For now, only FlexFEC is supported.
pub(crate) fn find_fec_payload_type(haystack: &[RTCRtpCodecParameters]) -> Option<PayloadType> {
    for c in haystack {
        if c.rtp_codec
            .mime_type
            .to_lowercase()
            .contains(MIME_TYPE_FLEX_FEC)
        {
            return Some(c.payload_type);
        }
    }

    None
}

/// Computes the intersection of two RTCP feedback lists.
///
/// Returns feedback mechanisms that are supported by both lists,
/// matching on both type and parameter fields.
///
/// # Parameters
///
/// * `a` - First feedback list
/// * `b` - Second feedback list
///
/// # Returns
///
/// Vector of common feedback mechanisms
pub(crate) fn rtcp_feedback_intersection(
    a: &[RTCPFeedback],
    b: &[RTCPFeedback],
) -> Vec<RTCPFeedback> {
    let mut out = vec![];
    for a_feedback in a {
        for b_feeback in b {
            if a_feedback.typ == b_feeback.typ && a_feedback.parameter == b_feeback.parameter {
                out.push(a_feedback.clone());
                break;
            }
        }
    }

    out
}

#[cfg(test)]
mod rtx_apt_test {
    use super::{RTCRtpCodec, RTCRtpCodecParameters, find_rtx_payload_type, parse_rtx_apt};

    fn rtx(payload_type: u8, fmtp: &str) -> RTCRtpCodecParameters {
        RTCRtpCodecParameters {
            rtp_codec: RTCRtpCodec {
                mime_type: "video/rtx".to_owned(),
                clock_rate: 90000,
                channels: 0,
                sdp_fmtp_line: fmtp.to_owned(),
                rtcp_feedback: vec![],
            },
            payload_type,
        }
    }

    #[test]
    fn find_rtx_payload_type_tolerates_extra_apt_params() {
        // A remote may append rtx-time to the apt fmtp (RFC 4588 §8.1); the
        // association must still succeed rather than dropping RTX from the answer.
        let haystack = vec![rtx(97, "apt=96;rtx-time=3000"), rtx(99, "apt=98")];
        assert_eq!(find_rtx_payload_type(96, &haystack), Some(97));
        assert_eq!(find_rtx_payload_type(98, &haystack), Some(99));
        assert_eq!(find_rtx_payload_type(100, &haystack), None);
    }

    #[test]
    fn parses_plain_apt() {
        assert_eq!(parse_rtx_apt("apt=96"), Some(96));
        assert_eq!(parse_rtx_apt("apt=127"), Some(127));
        assert_eq!(parse_rtx_apt("apt=0"), Some(0));
    }

    #[test]
    fn parses_apt_with_extra_params() {
        // RFC 4588 §8.1 allows an optional rtx-time parameter alongside apt.
        assert_eq!(parse_rtx_apt("apt=96;rtx-time=3000"), Some(96));
        assert_eq!(parse_rtx_apt("rtx-time=3000;apt=102"), Some(102));
        assert_eq!(parse_rtx_apt("apt=98 ; rtx-time=1000"), Some(98));
    }

    #[test]
    fn returns_none_without_apt() {
        assert_eq!(parse_rtx_apt(""), None);
        assert_eq!(parse_rtx_apt("profile-id=0"), None);
        assert_eq!(parse_rtx_apt("apt="), None);
        assert_eq!(parse_rtx_apt("apt=notanumber"), None);
        // Out of the u8 payload-type range.
        assert_eq!(parse_rtx_apt("apt=300"), None);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn codec(
        payload_type: PayloadType,
        mime_type: &str,
        clock_rate: u32,
        channels: u16,
        fmtp: &str,
    ) -> RTCRtpCodecParameters {
        RTCRtpCodecParameters {
            rtp_codec: RTCRtpCodec {
                mime_type: mime_type.to_owned(),
                clock_rate,
                channels,
                sdp_fmtp_line: fmtp.to_owned(),
                rtcp_feedback: vec![],
            },
            payload_type,
        }
    }

    #[test]
    fn telephone_event_match_respects_clock_rate() {
        let haystack = [
            codec(101, MIME_TYPE_TELEPHONE_EVENT, 8_000, 1, "0-15"),
            codec(110, MIME_TYPE_TELEPHONE_EVENT, 48_000, 1, "0-15"),
        ];
        let needle = codec(0, MIME_TYPE_TELEPHONE_EVENT, 48_000, 1, "0-15");

        let (matched, quality) = codec_parameters_fuzzy_search(&needle.rtp_codec, &haystack);

        assert_eq!(quality, CodecMatch::Exact);
        assert_eq!(matched.payload_type, 110);
    }

    #[test]
    fn partial_match_still_rejects_a_different_clock_rate() {
        let haystack = [codec(101, MIME_TYPE_TELEPHONE_EVENT, 8_000, 1, "0-16")];
        let needle = codec(0, MIME_TYPE_TELEPHONE_EVENT, 48_000, 1, "0-15");

        let (_, quality) = codec_parameters_fuzzy_search(&needle.rtp_codec, &haystack);

        assert_eq!(quality, CodecMatch::None);
    }

    #[test]
    fn codec_match_respects_audio_channel_count() {
        let haystack = [
            codec(109, MIME_TYPE_OPUS, 48_000, 1, "minptime=10"),
            codec(111, MIME_TYPE_OPUS, 48_000, 2, "minptime=10"),
        ];
        let needle = codec(0, MIME_TYPE_OPUS, 48_000, 2, "minptime=10");

        let (matched, quality) = codec_parameters_fuzzy_search(&needle.rtp_codec, &haystack);

        assert_eq!(quality, CodecMatch::Exact);
        assert_eq!(matched.payload_type, 111);
    }
}