freeswitch-types 1.5.0-beta.1

FreeSWITCH ESL protocol types: channel state, events, headers, commands, and variables
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! SDP media types and codec descriptors.

use std::fmt;
use std::str::FromStr;

/// SDP media type from an `m=` line.
///
/// Unrecognized types are represented as [`Other`](SdpMediaType::Other) rather
/// than hard-failing the parse — FreeSWITCH ignores media sections it does not
/// recognize (BFCP, MSRP, datachannel, etc.), and a converter must not drop
/// the whole session over an unknown `m=` line.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SdpMediaType {
    /// `m=audio`
    Audio,
    /// `m=video`
    Video,
    /// `m=application` — used for BFCP, MSRP, datachannel, etc.
    Application,
    /// `m=text` — used for MSRP text streams.
    Text,
    /// `m=message` — used for MSRP message streams.
    Message,
    /// Any other `m=` media type not recognized above.
    Other(String),
}

impl fmt::Display for SdpMediaType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Audio => f.write_str("audio"),
            Self::Video => f.write_str("video"),
            Self::Application => f.write_str("application"),
            Self::Text => f.write_str("text"),
            Self::Message => f.write_str("message"),
            Self::Other(s) => f.write_str(s),
        }
    }
}

impl FromStr for SdpMediaType {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "audio" => Self::Audio,
            "video" => Self::Video,
            "application" => Self::Application,
            "text" => Self::Text,
            "message" => Self::Message,
            other => Self::Other(other.to_string()),
        })
    }
}

/// SDP direction attribute from an `a=` line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SdpDirection {
    /// `a=sendrecv` — bidirectional (the default when no direction attribute is present).
    SendRecv,
    /// `a=sendonly` — the sender transmits but does not receive.
    SendOnly,
    /// `a=recvonly` — the sender receives but does not transmit.
    RecvOnly,
    /// `a=inactive` — neither side transmits.
    Inactive,
}

impl fmt::Display for SdpDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SendRecv => f.write_str("sendrecv"),
            Self::SendOnly => f.write_str("sendonly"),
            Self::RecvOnly => f.write_str("recvonly"),
            Self::Inactive => f.write_str("inactive"),
        }
    }
}

/// Errors returned when an unrecognized direction attribute is encountered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseSdpDirectionError(String);

impl fmt::Display for ParseSdpDirectionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "unrecognized SDP direction attribute: {:?}", self.0)
    }
}

impl std::error::Error for ParseSdpDirectionError {}

impl FromStr for SdpDirection {
    type Err = ParseSdpDirectionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "sendrecv" => Ok(Self::SendRecv),
            "sendonly" => Ok(Self::SendOnly),
            "recvonly" => Ok(Self::RecvOnly),
            "inactive" => Ok(Self::Inactive),
            other => Err(ParseSdpDirectionError(other.to_string())),
        }
    }
}

/// A codec derived from an SDP `m=` section.
///
/// Fields are private; use the accessor methods. Mutable accessors (`_mut()`)
/// are provided for fields a caller may need to adjust before emitting a codec
/// string (e.g. after deserializing a config and tweaking ptime).
#[derive(Debug, Clone)]
pub struct SdpCodec {
    media: SdpMediaType,
    /// Session-local payload type from the `m=` format list.
    /// Never emitted into a codec string — it is only meaningful within
    /// this session and must not be carried across calls.
    payload_type: u8,
    name: String,
    clock_rate: u32,
    channels: Option<u8>,
    fmtp: Option<String>,
    ptime: Option<u32>,
    maxptime: Option<u32>,
    bitrate: Option<u32>,
    direction: SdpDirection,
    has_rtpmap: bool,
}

impl SdpCodec {
    /// Create a new [`SdpCodec`].
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        media: SdpMediaType,
        payload_type: u8,
        name: impl Into<String>,
        clock_rate: u32,
        channels: Option<u8>,
        fmtp: Option<String>,
        ptime: Option<u32>,
        maxptime: Option<u32>,
        bitrate: Option<u32>,
        direction: SdpDirection,
        has_rtpmap: bool,
    ) -> Self {
        Self {
            media,
            payload_type,
            name: name.into(),
            clock_rate,
            channels,
            fmtp,
            ptime,
            maxptime,
            bitrate,
            direction,
            has_rtpmap,
        }
    }

    /// The SDP media type this codec belongs to.
    pub fn media(&self) -> &SdpMediaType {
        &self.media
    }

    /// The session-local RTP payload type.
    ///
    /// This value is assigned by the offerer for the duration of this session
    /// only. It is **never** emitted into a FreeSWITCH codec string — codec
    /// strings identify codecs by name, not by payload type number.
    pub fn payload_type(&self) -> u8 {
        self.payload_type
    }

    /// The codec encoding name (e.g. `"opus"`, `"PCMU"`, `"AMR-WB"`).
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The RTP clock rate in Hz.
    pub fn clock_rate(&self) -> u32 {
        self.clock_rate
    }

    /// The channel count, or `None` when not applicable (video) or stream-defined.
    pub fn channels(&self) -> Option<u8> {
        self.channels
    }

    /// The format parameters from `a=fmtp`, if any.
    pub fn fmtp(&self) -> Option<&str> {
        self.fmtp
            .as_deref()
    }

    /// The packetization time in milliseconds, or `None` if not specified.
    pub fn ptime(&self) -> Option<u32> {
        self.ptime
    }

    /// The maximum packetization time in milliseconds, or `None` if not specified.
    pub fn maxptime(&self) -> Option<u32> {
        self.maxptime
    }

    /// The bitrate in bits per second, or `None` if not known.
    pub fn bitrate(&self) -> Option<u32> {
        self.bitrate
    }

    /// The media direction for this codec's stream.
    pub fn direction(&self) -> SdpDirection {
        self.direction
    }

    /// Whether the encoding name and clock rate came from an `a=rtpmap` line.
    ///
    /// `false` means they were filled in from the RFC 3551 static table.
    pub fn has_rtpmap(&self) -> bool {
        self.has_rtpmap
    }

    // --- mutable accessors ---

    /// Mutable access to the format parameters.
    pub fn fmtp_mut(&mut self) -> &mut Option<String> {
        &mut self.fmtp
    }

    /// Mutable access to ptime.
    pub fn ptime_mut(&mut self) -> &mut Option<u32> {
        &mut self.ptime
    }

    /// Mutable access to maxptime.
    pub fn maxptime_mut(&mut self) -> &mut Option<u32> {
        &mut self.maxptime
    }

    /// Mutable access to bitrate.
    pub fn bitrate_mut(&mut self) -> &mut Option<u32> {
        &mut self.bitrate
    }

    /// Mutable access to the channel count.
    pub fn channels_mut(&mut self) -> &mut Option<u8> {
        &mut self.channels
    }
}

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

    // --- SdpMediaType ---

    #[test]
    fn sdp_media_type_display() {
        assert_eq!(SdpMediaType::Audio.to_string(), "audio");
        assert_eq!(SdpMediaType::Video.to_string(), "video");
        assert_eq!(SdpMediaType::Application.to_string(), "application");
        assert_eq!(SdpMediaType::Text.to_string(), "text");
        assert_eq!(SdpMediaType::Message.to_string(), "message");
        assert_eq!(
            SdpMediaType::Other("image".to_string()).to_string(),
            "image"
        );
    }

    #[test]
    fn sdp_media_type_from_str_known() {
        assert_eq!(
            "audio"
                .parse::<SdpMediaType>()
                .unwrap(),
            SdpMediaType::Audio
        );
        assert_eq!(
            "video"
                .parse::<SdpMediaType>()
                .unwrap(),
            SdpMediaType::Video
        );
        assert_eq!(
            "application"
                .parse::<SdpMediaType>()
                .unwrap(),
            SdpMediaType::Application
        );
        assert_eq!(
            "text"
                .parse::<SdpMediaType>()
                .unwrap(),
            SdpMediaType::Text
        );
        assert_eq!(
            "message"
                .parse::<SdpMediaType>()
                .unwrap(),
            SdpMediaType::Message
        );
    }

    #[test]
    fn sdp_media_type_from_str_unknown_becomes_other() {
        // Unknown types become Other instead of erroring — FreeSWITCH ignores
        // media sections it does not recognize.
        let t = "image"
            .parse::<SdpMediaType>()
            .unwrap();
        assert_eq!(t, SdpMediaType::Other("image".to_string()));
    }

    #[test]
    fn sdp_media_type_round_trip() {
        for s in &[
            "audio",
            "video",
            "application",
            "text",
            "message",
            "datachannel",
        ] {
            let parsed: SdpMediaType = s
                .parse()
                .unwrap();
            assert_eq!(&parsed.to_string(), s);
        }
    }

    // --- SdpDirection ---

    #[test]
    fn sdp_direction_display() {
        assert_eq!(SdpDirection::SendRecv.to_string(), "sendrecv");
        assert_eq!(SdpDirection::SendOnly.to_string(), "sendonly");
        assert_eq!(SdpDirection::RecvOnly.to_string(), "recvonly");
        assert_eq!(SdpDirection::Inactive.to_string(), "inactive");
    }

    #[test]
    fn sdp_direction_from_str() {
        assert_eq!(
            "sendrecv"
                .parse::<SdpDirection>()
                .unwrap(),
            SdpDirection::SendRecv
        );
        assert_eq!(
            "sendonly"
                .parse::<SdpDirection>()
                .unwrap(),
            SdpDirection::SendOnly
        );
        assert_eq!(
            "recvonly"
                .parse::<SdpDirection>()
                .unwrap(),
            SdpDirection::RecvOnly
        );
        assert_eq!(
            "inactive"
                .parse::<SdpDirection>()
                .unwrap(),
            SdpDirection::Inactive
        );
    }

    #[test]
    fn sdp_direction_from_str_error() {
        let err = "halfduplex"
            .parse::<SdpDirection>()
            .unwrap_err();
        assert!(err
            .to_string()
            .contains("halfduplex"));
    }

    #[test]
    fn sdp_direction_round_trip() {
        for dir in &[
            SdpDirection::SendRecv,
            SdpDirection::SendOnly,
            SdpDirection::RecvOnly,
            SdpDirection::Inactive,
        ] {
            let parsed: SdpDirection = dir
                .to_string()
                .parse()
                .unwrap();
            assert_eq!(&parsed, dir);
        }
    }

    // --- SdpCodec ---

    fn make_audio_codec() -> SdpCodec {
        SdpCodec::new(
            SdpMediaType::Audio,
            0,
            "PCMU",
            8000,
            Some(1),
            None,
            Some(20),
            None,
            Some(64000),
            SdpDirection::SendRecv,
            false,
        )
    }

    #[test]
    fn sdp_codec_accessors() {
        let c = make_audio_codec();
        assert_eq!(c.media(), &SdpMediaType::Audio);
        assert_eq!(c.payload_type(), 0);
        assert_eq!(c.name(), "PCMU");
        assert_eq!(c.clock_rate(), 8000);
        assert_eq!(c.channels(), Some(1));
        assert_eq!(c.fmtp(), None);
        assert_eq!(c.ptime(), Some(20));
        assert_eq!(c.maxptime(), None);
        assert_eq!(c.bitrate(), Some(64000));
        assert_eq!(c.direction(), SdpDirection::SendRecv);
        assert!(!c.has_rtpmap());
    }

    #[test]
    fn sdp_codec_with_rtpmap() {
        let c = SdpCodec::new(
            SdpMediaType::Audio,
            111,
            "opus",
            48000,
            Some(2),
            Some("minptime=10;useinbandfec=1".into()),
            Some(20),
            None,
            None,
            SdpDirection::SendRecv,
            true,
        );
        assert_eq!(c.name(), "opus");
        assert_eq!(c.clock_rate(), 48000);
        assert_eq!(c.channels(), Some(2));
        assert_eq!(c.fmtp(), Some("minptime=10;useinbandfec=1"));
        assert!(c.has_rtpmap());
    }

    #[test]
    fn sdp_codec_video_no_channels() {
        let c = SdpCodec::new(
            SdpMediaType::Video,
            99,
            "H264",
            90000,
            None,
            None,
            None,
            None,
            None,
            SdpDirection::SendRecv,
            true,
        );
        assert_eq!(c.media(), &SdpMediaType::Video);
        assert!(c
            .channels()
            .is_none());
    }

    #[test]
    fn sdp_codec_mutable_accessors() {
        let mut c = make_audio_codec();
        *c.ptime_mut() = Some(30);
        assert_eq!(c.ptime(), Some(30));

        *c.fmtp_mut() = Some("mode=20".into());
        assert_eq!(c.fmtp(), Some("mode=20"));

        *c.bitrate_mut() = None;
        assert!(c
            .bitrate()
            .is_none());

        *c.maxptime_mut() = Some(40);
        assert_eq!(c.maxptime(), Some(40));

        *c.channels_mut() = Some(2);
        assert_eq!(c.channels(), Some(2));
    }
}