oximedia-net 0.1.8

Network streaming for OxiMedia
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! Minimal SDP parser sufficient for RTSP DESCRIBE responses (RFC 8866, formerly 4566).
//!
//! SDP is a line-oriented format where each line is `<type>=<value>`. We only
//! parse the subset that an RTSP client genuinely needs to act on:
//! - session-level connection (`c=`) and media-level connection
//! - media descriptions (`m=`) — payload types and transport
//! - `a=rtpmap`, `a=fmtp`, `a=control`, `a=range`
//!
//! Unknown lines are preserved as raw attributes and not treated as errors —
//! real-world cameras send a lot of vendor extensions.

use crate::error::NetError;

/// A complete SDP session description.
#[derive(Debug, Clone, Default)]
pub struct SessionDescription {
    /// Protocol version (`v=`). Always 0 in practice.
    pub version: u8,
    /// Originator (`o=`) raw value.
    pub origin: Option<String>,
    /// Session name (`s=`).
    pub session_name: Option<String>,
    /// Session-level connection (`c=`).
    pub connection: Option<ConnectionInfo>,
    /// Session-level `a=control` aggregate-control URI.
    pub control: Option<String>,
    /// Session-level range, e.g. `npt=0-`.
    pub range: Option<String>,
    /// One entry per `m=` media line.
    pub media: Vec<MediaDescription>,
    /// All session-level attributes (`a=` lines) preserved verbatim.
    pub attributes: Vec<(String, Option<String>)>,
}

/// `c=` line — network type, address type, connection address.
#[derive(Debug, Clone)]
pub struct ConnectionInfo {
    /// Network type. Almost always `IN` (Internet).
    pub network_type: String,
    /// Address type, e.g. `IP4`/`IP6`.
    pub address_type: String,
    /// Connection address, possibly with TTL or multicast count suffix.
    pub address: String,
}

/// A single media stream described by `m=` and its attributes.
#[derive(Debug, Clone)]
pub struct MediaDescription {
    /// Media type: `video`, `audio`, `application`, etc.
    pub media: String,
    /// Transport port; the RFC allows a range but we keep the first value.
    pub port: u16,
    /// Transport protocol, e.g. `RTP/AVP` or `RTP/AVP/TCP`.
    pub protocol: String,
    /// Listed RTP payload types (the trailing tokens of `m=`).
    pub formats: Vec<u8>,
    /// Per-stream connection override, if present.
    pub connection: Option<ConnectionInfo>,
    /// `a=control:` — the URL to SETUP this specific stream.
    pub control: Option<String>,
    /// Decoded `a=rtpmap:` entries keyed by payload type.
    pub rtpmaps: Vec<RtpMap>,
    /// `a=fmtp:` lines keyed by payload type.
    pub fmtps: Vec<Fmtp>,
    /// Any other attribute, preserved as `(name, value)`.
    pub attributes: Vec<(String, Option<String>)>,
}

/// `a=rtpmap:<pt> <encoding>/<clock-rate>[/<channels>]`.
#[derive(Debug, Clone)]
pub struct RtpMap {
    /// Payload type number (0–127).
    pub payload_type: u8,
    /// Codec name, e.g. `H264`, `MP4A-LATM`, `PCMU`.
    pub encoding: String,
    /// Clock rate (Hz). Video is typically 90000.
    pub clock_rate: u32,
    /// Channel count for audio, `None` for video.
    pub channels: Option<u8>,
}

/// `a=fmtp:<pt> <params>`.
#[derive(Debug, Clone)]
pub struct Fmtp {
    /// Payload type number.
    pub payload_type: u8,
    /// Everything after the payload type, unparsed (the syntax is per-codec).
    pub params: String,
}

impl SessionDescription {
    /// Parse a complete SDP document.
    ///
    /// # Errors
    ///
    /// Returns [`NetError::Parse`] if a line is missing the `=` separator,
    /// or if a known line type (`v=`, `m=`, `c=`, `a=rtpmap`, `a=fmtp`)
    /// has an unparseable value.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    ///
    /// let sdp = "v=0\r\n\
    ///            m=video 0 RTP/AVP 96\r\n\
    ///            a=rtpmap:96 H264/90000\r\n\
    ///            a=control:trackID=1\r\n";
    /// let parsed = SessionDescription::parse(sdp).unwrap();
    /// let video = parsed.video().expect("video track present");
    /// assert_eq!(video.primary_rtpmap().unwrap().encoding, "H264");
    /// ```
    pub fn parse(input: &str) -> Result<Self, NetError> {
        let mut session = Self::default();
        let mut current_media: Option<MediaDescription> = None;

        for (lineno, raw) in input.lines().enumerate() {
            let line = raw.trim_end_matches('\r');
            if line.is_empty() {
                continue;
            }
            let (kind, value) = line.split_once('=').ok_or_else(|| NetError::Parse {
                offset: lineno as u64,
                message: format!("SDP line missing '=': {line:?}"),
            })?;

            match kind {
                "v" => {
                    session.version = value.trim().parse::<u8>().map_err(|e| NetError::Parse {
                        offset: lineno as u64,
                        message: format!("bad version: {e}"),
                    })?;
                }
                "o" => session.origin = Some(value.to_string()),
                "s" => session.session_name = Some(value.to_string()),
                "c" => {
                    let conn = parse_connection(value, lineno)?;
                    if let Some(m) = current_media.as_mut() {
                        m.connection = Some(conn);
                    } else {
                        session.connection = Some(conn);
                    }
                }
                "m" => {
                    if let Some(m) = current_media.take() {
                        session.media.push(m);
                    }
                    current_media = Some(parse_media(value, lineno)?);
                }
                "a" => {
                    let (attr_name, attr_value) = split_attribute(value);
                    handle_attribute(
                        &mut session,
                        current_media.as_mut(),
                        attr_name,
                        attr_value,
                        lineno,
                    )?;
                }
                _ => {
                    // Lines we don't care about (t=, i=, u=, e=, p=, b=, k=, r=, z=)
                    // are intentionally ignored — RTSP playback doesn't need them.
                }
            }
        }
        if let Some(m) = current_media.take() {
            session.media.push(m);
        }
        Ok(session)
    }

    /// Find the first video media block, if any.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    ///
    /// let sdp = "v=0\r\nm=video 0 RTP/AVP 96\r\na=rtpmap:96 H264/90000\r\n";
    /// let parsed = SessionDescription::parse(sdp).unwrap();
    /// assert!(parsed.video().is_some());
    /// assert!(parsed.audio().is_none());
    /// ```
    #[must_use]
    pub fn video(&self) -> Option<&MediaDescription> {
        self.media.iter().find(|m| m.media == "video")
    }

    /// Find the first audio media block, if any.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    ///
    /// let sdp = "v=0\r\nm=audio 0 RTP/AVP 97\r\na=rtpmap:97 MPEG4-GENERIC/48000/2\r\n";
    /// let parsed = SessionDescription::parse(sdp).unwrap();
    /// let audio = parsed.audio().unwrap();
    /// assert_eq!(audio.primary_rtpmap().unwrap().channels, Some(2));
    /// ```
    #[must_use]
    pub fn audio(&self) -> Option<&MediaDescription> {
        self.media.iter().find(|m| m.media == "audio")
    }
}

impl SessionDescription {
    /// Build a minimal SDP for advertising a video (optionally + audio) track pair over RTSP.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    /// let sdp = SessionDescription::for_rtsp_stream(
    ///     "127.0.0.1",
    ///     96, "H264", 90000,
    ///     Some(97), Some("MPEG4-GENERIC"), Some(44100), Some(2),
    /// );
    /// assert!(sdp.video().is_some());
    /// assert!(sdp.audio().is_some());
    /// ```
    #[must_use]
    pub fn for_rtsp_stream(
        addr: &str,
        video_payload_type: u8,
        video_codec: &str,
        video_clock_rate: u32,
        audio_payload_type: Option<u8>,
        audio_codec: Option<&str>,
        audio_clock_rate: Option<u32>,
        audio_channels: Option<u8>,
    ) -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        let connection = Some(ConnectionInfo {
            network_type: "IN".into(),
            address_type: "IP4".into(),
            address: addr.to_string(),
        });

        let video_track = MediaDescription {
            media: "video".into(),
            port: 0,
            protocol: "RTP/AVP".into(),
            formats: vec![video_payload_type],
            connection: None,
            control: Some("trackID=1".into()),
            rtpmaps: vec![RtpMap {
                payload_type: video_payload_type,
                encoding: video_codec.to_string(),
                clock_rate: video_clock_rate,
                channels: None,
            }],
            fmtps: Vec::new(),
            attributes: Vec::new(),
        };

        let mut media = vec![video_track];

        if let (Some(apt), Some(acodec), Some(arate)) =
            (audio_payload_type, audio_codec, audio_clock_rate)
        {
            let audio_track = MediaDescription {
                media: "audio".into(),
                port: 0,
                protocol: "RTP/AVP".into(),
                formats: vec![apt],
                connection: None,
                control: Some("trackID=2".into()),
                rtpmaps: vec![RtpMap {
                    payload_type: apt,
                    encoding: acodec.to_string(),
                    clock_rate: arate,
                    channels: audio_channels,
                }],
                fmtps: Vec::new(),
                attributes: Vec::new(),
            };
            media.push(audio_track);
        }

        Self {
            version: 0,
            origin: Some(format!("- {ts} {ts} IN IP4 {addr}")),
            session_name: Some("RTSP Stream".into()),
            connection,
            control: Some("*".into()),
            range: None,
            media,
            attributes: Vec::new(),
        }
    }
}

impl std::fmt::Display for SessionDescription {
    /// Serialize this session description to SDP wire format (RFC 8866).
    ///
    /// Each line is CRLF-terminated as required by the RFC.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    /// let sdp = SessionDescription::for_rtsp_stream(
    ///     "127.0.0.1", 96, "H264", 90000, None, None, None, None,
    /// );
    /// let text = sdp.to_string();
    /// assert!(text.starts_with("v=0\r\n"));
    /// assert!(text.contains("m=video"));
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Helper macro to write a CRLF-terminated line.
        macro_rules! line {
            ($f:expr, $($arg:tt)*) => {
                write!($f, "{}\r\n", format_args!($($arg)*))?
            };
        }

        // v= line
        line!(f, "v={}", self.version);

        // o= line
        if let Some(origin) = &self.origin {
            line!(f, "o={origin}");
        } else {
            line!(f, "o=- 0 0 IN IP4 0.0.0.0");
        }

        // s= line
        if let Some(name) = &self.session_name {
            line!(f, "s={name}");
        } else {
            line!(f, "s= ");
        }

        // c= line (session-level)
        if let Some(conn) = &self.connection {
            line!(
                f,
                "c={} {} {}",
                conn.network_type,
                conn.address_type,
                conn.address
            );
        }

        // t= line (mandatory)
        line!(f, "t=0 0");

        // Session-level a= lines
        for (name, value) in &self.attributes {
            if let Some(v) = value {
                line!(f, "a={name}:{v}");
            } else {
                line!(f, "a={name}");
            }
        }

        // Session-level a=control
        if let Some(ctrl) = &self.control {
            line!(f, "a=control:{ctrl}");
        }

        // Media descriptions
        for m in &self.media {
            // m= line: e.g. "m=video 0 RTP/AVP 96 97"
            let fmts: Vec<String> = m.formats.iter().map(|pt| pt.to_string()).collect();
            line!(
                f,
                "m={} {} {} {}",
                m.media,
                m.port,
                m.protocol,
                fmts.join(" ")
            );

            // Media-level c= override
            if let Some(conn) = &m.connection {
                line!(
                    f,
                    "c={} {} {}",
                    conn.network_type,
                    conn.address_type,
                    conn.address
                );
            }

            // a=rtpmap lines
            for rtpmap in &m.rtpmaps {
                if let Some(ch) = rtpmap.channels {
                    line!(
                        f,
                        "a=rtpmap:{} {}/{}/{}",
                        rtpmap.payload_type,
                        rtpmap.encoding,
                        rtpmap.clock_rate,
                        ch
                    );
                } else {
                    line!(
                        f,
                        "a=rtpmap:{} {}/{}",
                        rtpmap.payload_type,
                        rtpmap.encoding,
                        rtpmap.clock_rate
                    );
                }
            }

            // a=fmtp lines
            for fmtp in &m.fmtps {
                line!(f, "a=fmtp:{} {}", fmtp.payload_type, fmtp.params);
            }

            // a=control
            if let Some(ctrl) = &m.control {
                line!(f, "a=control:{ctrl}");
            }

            // Other attributes
            for (name, value) in &m.attributes {
                if let Some(v) = value {
                    line!(f, "a={name}:{v}");
                } else {
                    line!(f, "a={name}");
                }
            }
        }

        Ok(())
    }
}

impl MediaDescription {
    /// Lookup the `a=rtpmap` for the first listed payload type.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    ///
    /// let sdp = "v=0\r\nm=video 0 RTP/AVP 96\r\na=rtpmap:96 H264/90000\r\n";
    /// let parsed = SessionDescription::parse(sdp).unwrap();
    /// let r = parsed.video().unwrap().primary_rtpmap().unwrap();
    /// assert_eq!(r.encoding, "H264");
    /// assert_eq!(r.clock_rate, 90_000);
    /// ```
    #[must_use]
    pub fn primary_rtpmap(&self) -> Option<&RtpMap> {
        let pt = *self.formats.first()?;
        self.rtpmaps.iter().find(|r| r.payload_type == pt)
    }

    /// Lookup `a=fmtp` for the first listed payload type.
    ///
    /// # Example
    ///
    /// ```
    /// use oximedia_net::rtsp::SessionDescription;
    ///
    /// let sdp = "v=0\r\n\
    ///            m=video 0 RTP/AVP 96\r\n\
    ///            a=rtpmap:96 H264/90000\r\n\
    ///            a=fmtp:96 profile-level-id=42E01F\r\n";
    /// let parsed = SessionDescription::parse(sdp).unwrap();
    /// let f = parsed.video().unwrap().primary_fmtp().unwrap();
    /// assert!(f.params.contains("profile-level-id=42E01F"));
    /// ```
    #[must_use]
    pub fn primary_fmtp(&self) -> Option<&Fmtp> {
        let pt = *self.formats.first()?;
        self.fmtps.iter().find(|f| f.payload_type == pt)
    }
}

fn parse_connection(value: &str, lineno: usize) -> Result<ConnectionInfo, NetError> {
    let mut parts = value.split_ascii_whitespace();
    let network_type = parts.next().ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "c= missing network type".into(),
    })?;
    let address_type = parts.next().ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "c= missing address type".into(),
    })?;
    let address = parts.next().ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "c= missing address".into(),
    })?;
    Ok(ConnectionInfo {
        network_type: network_type.to_string(),
        address_type: address_type.to_string(),
        address: address.to_string(),
    })
}

fn parse_media(value: &str, lineno: usize) -> Result<MediaDescription, NetError> {
    let mut parts = value.split_ascii_whitespace();
    let media = parts.next().ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "m= missing media type".into(),
    })?;
    let port_field = parts.next().ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "m= missing port".into(),
    })?;
    // `port[/count]` — keep the leading number, drop any "/count".
    let port_str = port_field.split('/').next().unwrap_or(port_field);
    let port = port_str.parse::<u16>().map_err(|e| NetError::Parse {
        offset: lineno as u64,
        message: format!("bad m= port {port_str:?}: {e}"),
    })?;
    let protocol = parts
        .next()
        .ok_or_else(|| NetError::Parse {
            offset: lineno as u64,
            message: "m= missing protocol".into(),
        })?
        .to_string();
    let mut formats = Vec::new();
    for fmt in parts {
        if let Ok(pt) = fmt.parse::<u8>() {
            formats.push(pt);
        }
        // Non-numeric format tokens appear for non-RTP protocols; we skip them
        // rather than error so we can still parse such SDPs for inspection.
    }
    Ok(MediaDescription {
        media: media.to_string(),
        port,
        protocol,
        formats,
        connection: None,
        control: None,
        rtpmaps: Vec::new(),
        fmtps: Vec::new(),
        attributes: Vec::new(),
    })
}

fn split_attribute(value: &str) -> (&str, Option<&str>) {
    match value.split_once(':') {
        Some((name, rest)) => (name, Some(rest)),
        None => (value, None),
    }
}

fn handle_attribute(
    session: &mut SessionDescription,
    media: Option<&mut MediaDescription>,
    name: &str,
    value: Option<&str>,
    lineno: usize,
) -> Result<(), NetError> {
    match name {
        "control" => {
            let v = value.unwrap_or("").to_string();
            if let Some(m) = media {
                m.control = Some(v);
            } else {
                session.control = Some(v);
            }
        }
        "range" => {
            let v = value.unwrap_or("").to_string();
            if media.is_none() {
                session.range = Some(v);
            } else if let Some(m) = media {
                m.attributes.push(("range".into(), Some(v)));
            }
        }
        "rtpmap" => {
            let v = value.ok_or_else(|| NetError::Parse {
                offset: lineno as u64,
                message: "a=rtpmap missing value".into(),
            })?;
            let rtpmap = parse_rtpmap(v, lineno)?;
            if let Some(m) = media {
                m.rtpmaps.push(rtpmap);
            }
        }
        "fmtp" => {
            let v = value.ok_or_else(|| NetError::Parse {
                offset: lineno as u64,
                message: "a=fmtp missing value".into(),
            })?;
            let fmtp = parse_fmtp(v, lineno)?;
            if let Some(m) = media {
                m.fmtps.push(fmtp);
            }
        }
        other => {
            let v = value.map(str::to_string);
            if let Some(m) = media {
                m.attributes.push((other.to_string(), v));
            } else {
                session.attributes.push((other.to_string(), v));
            }
        }
    }
    Ok(())
}

fn parse_rtpmap(value: &str, lineno: usize) -> Result<RtpMap, NetError> {
    let (pt_str, rest) = value.split_once(' ').ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "a=rtpmap missing space".into(),
    })?;
    let payload_type = pt_str.parse::<u8>().map_err(|e| NetError::Parse {
        offset: lineno as u64,
        message: format!("bad rtpmap PT: {e}"),
    })?;
    // `encoding/clock-rate[/channels]`
    let mut parts = rest.split('/');
    let encoding = parts
        .next()
        .ok_or_else(|| NetError::Parse {
            offset: lineno as u64,
            message: "a=rtpmap missing encoding".into(),
        })?
        .to_string();
    let clock_rate = parts
        .next()
        .ok_or_else(|| NetError::Parse {
            offset: lineno as u64,
            message: "a=rtpmap missing clock-rate".into(),
        })?
        .parse::<u32>()
        .map_err(|e| NetError::Parse {
            offset: lineno as u64,
            message: format!("bad rtpmap clock-rate: {e}"),
        })?;
    let channels = parts.next().and_then(|s| s.parse::<u8>().ok());
    Ok(RtpMap {
        payload_type,
        encoding,
        clock_rate,
        channels,
    })
}

fn parse_fmtp(value: &str, lineno: usize) -> Result<Fmtp, NetError> {
    let (pt_str, params) = value.split_once(' ').ok_or_else(|| NetError::Parse {
        offset: lineno as u64,
        message: "a=fmtp missing space".into(),
    })?;
    let payload_type = pt_str.parse::<u8>().map_err(|e| NetError::Parse {
        offset: lineno as u64,
        message: format!("bad fmtp PT: {e}"),
    })?;
    Ok(Fmtp {
        payload_type,
        params: params.to_string(),
    })
}

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

    /// Minimal SDP that real IP cameras produce.
    const CAMERA_SDP: &str = "v=0\r\n\
o=- 1234 1234 IN IP4 192.168.1.10\r\n\
s=Camera Stream\r\n\
c=IN IP4 0.0.0.0\r\n\
t=0 0\r\n\
a=control:*\r\n\
m=video 0 RTP/AVP 96\r\n\
a=rtpmap:96 H264/90000\r\n\
a=fmtp:96 packetization-mode=1; profile-level-id=42E01F; sprop-parameter-sets=Z0LAH9oBQBboQAAAAwBAAAAPI8WLkgA=,aM48gA==\r\n\
a=control:trackID=1\r\n\
m=audio 0 RTP/AVP 0\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=control:trackID=2\r\n";

    #[test]
    fn parses_camera_sdp() {
        let sdp = SessionDescription::parse(CAMERA_SDP).unwrap();
        assert_eq!(sdp.version, 0);
        assert_eq!(sdp.session_name.as_deref(), Some("Camera Stream"));
        assert_eq!(sdp.control.as_deref(), Some("*"));
        assert_eq!(sdp.media.len(), 2);

        let video = sdp.video().expect("video track");
        assert_eq!(video.media, "video");
        assert_eq!(video.protocol, "RTP/AVP");
        assert_eq!(video.formats, vec![96]);
        assert_eq!(video.control.as_deref(), Some("trackID=1"));
        let rtpmap = video.primary_rtpmap().expect("rtpmap");
        assert_eq!(rtpmap.encoding, "H264");
        assert_eq!(rtpmap.clock_rate, 90000);
        assert!(rtpmap.channels.is_none());
        let fmtp = video.primary_fmtp().expect("fmtp");
        assert!(fmtp.params.contains("profile-level-id=42E01F"));

        let audio = sdp.audio().expect("audio track");
        assert_eq!(audio.formats, vec![0]);
        let rtpmap = audio.primary_rtpmap().expect("audio rtpmap");
        assert_eq!(rtpmap.encoding, "PCMU");
        assert_eq!(rtpmap.clock_rate, 8000);
    }

    #[test]
    fn ignores_unknown_attributes() {
        let sdp =
            "v=0\r\nm=video 0 RTP/AVP 96\r\na=rtpmap:96 H264/90000\r\na=x-vendor-flag:true\r\n";
        let parsed = SessionDescription::parse(sdp).unwrap();
        let video = &parsed.media[0];
        assert!(video.attributes.iter().any(|(k, _)| k == "x-vendor-flag"));
    }

    #[test]
    fn rejects_missing_equals() {
        let bad = "v=0\r\nbadline\r\n";
        assert!(SessionDescription::parse(bad).is_err());
    }

    #[test]
    fn audio_channels_parsed() {
        let sdp = "v=0\r\nm=audio 0 RTP/AVP 97\r\na=rtpmap:97 MPEG4-GENERIC/48000/2\r\n";
        let parsed = SessionDescription::parse(sdp).unwrap();
        let m = &parsed.media[0];
        let r = m.primary_rtpmap().unwrap();
        assert_eq!(r.encoding, "MPEG4-GENERIC");
        assert_eq!(r.clock_rate, 48000);
        assert_eq!(r.channels, Some(2));
    }

    #[test]
    fn media_level_connection_overrides_session() {
        let sdp = "v=0\r\nc=IN IP4 0.0.0.0\r\nm=video 0 RTP/AVP 96\r\nc=IN IP4 239.0.0.1/127\r\na=rtpmap:96 H264/90000\r\n";
        let parsed = SessionDescription::parse(sdp).unwrap();
        let v = &parsed.media[0];
        assert!(v.connection.is_some());
        assert_eq!(v.connection.as_ref().unwrap().address, "239.0.0.1/127");
    }
}