arcly-stream 0.8.2

An open-extensible live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, a pluggable multi-protocol ingestion layer (RTMP, RTSP, SRT, WHIP/WHEP shipped), and a feature-gated pure-Rust media plane (MPEG-TS/HLS/fMP4) — runtime, config, and metrics free.
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
//! WebRTC SDP offer parsing and answer generation (RFC 8866 + JSEP).
//!
//! Just enough of the offer is parsed to emit a compatible single-video answer:
//! the media line, the chosen H.264 payload type, and the bundle/mid grouping.
//! The crypto-bearing lines in the answer (`a=fingerprint`, `a=ice-ufrag`,
//! `a=ice-pwd`) come from the host's [`DtlsSrtpTransport`](super::DtlsSrtpTransport).

/// A parsed WHIP/WHEP SDP offer (only the fields the answer needs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SdpOffer {
    /// The video media `mid` (defaults to `"0"` when absent).
    pub mid: String,
    /// The negotiated H.264 dynamic payload type (e.g. 96).
    pub payload_type: u8,
    /// The negotiated Opus audio payload type, when the offer carries an audio
    /// `m=` line (e.g. 111). `None` for a video-only offer.
    pub audio_payload_type: Option<u8>,
    /// Whether the offer requested `a=sendonly`/`sendrecv` (a publisher).
    pub send: bool,
    /// The RTP header-extension id negotiated for the RID
    /// (`urn:ietf:params:rtp-hdrext:sdes:rid`), if the offer carries one. Needed
    /// to read [`simulcast_rids`](Self::simulcast_rids) layers off the RTP stream.
    pub rid_ext_id: Option<u8>,
    /// The simulcast send layers the publisher offers, in declared order (the
    /// rid identifiers from `a=simulcast:send` / `a=rid:… send`). Empty when the
    /// offer is not simulcast.
    pub simulcast_rids: Vec<String>,
    /// The `m=application` data-channel `mid`, when the offer negotiates an SCTP
    /// (`webrtc-datachannel`) data channel. `None` if there is no data channel.
    pub data_mid: Option<String>,
}

impl SdpOffer {
    /// Whether the offer negotiates an SCTP data channel.
    pub fn has_data_channel(&self) -> bool {
        self.data_mid.is_some()
    }

    /// Whether the offer carries more than one simulcast layer.
    pub fn is_simulcast(&self) -> bool {
        self.simulcast_rids.len() > 1
    }

    /// Parse the offer, returning `None` if it has no video `m=` line.
    ///
    /// Audio is parsed opportunistically: a publisher (WHIP) offering both video
    /// and Opus audio yields [`audio_payload_type`](Self::audio_payload_type) so
    /// the ingest pump can route audio RTP onto the bus. Video remains required
    /// (audio-only offers return `None`). Simulcast (`a=simulcast`/`a=rid`) and a
    /// data-channel `m=application` line are captured when present.
    pub fn parse(sdp: &str) -> Option<SdpOffer> {
        #[derive(PartialEq)]
        enum Section {
            None,
            Video,
            Audio,
            Application,
        }
        let mut section = Section::None;
        let mut payload_type = None;
        let mut mid = "0".to_string();
        let mut send = false;
        let mut h264_pt = None;
        let mut opus_pt = None;
        let mut audio_default_pt = None;
        let mut rid_ext_id = None;
        let mut rid_send: Vec<String> = Vec::new();
        let mut simulcast: Vec<String> = Vec::new();
        let mut data_mid = None;
        let mut app_mid = "data".to_string();

        for line in sdp.lines() {
            let line = line.trim_end();
            if let Some(rest) = line.strip_prefix("m=") {
                if rest.starts_with("video") {
                    section = Section::Video;
                    // First payload type on the m= line is the default.
                    payload_type = rest.split(' ').nth(3).and_then(|p| p.parse().ok());
                } else if rest.starts_with("audio") {
                    section = Section::Audio;
                    audio_default_pt = rest.split(' ').nth(3).and_then(|p| p.parse().ok());
                } else if rest.starts_with("application") {
                    section = Section::Application;
                    data_mid = Some(app_mid.clone());
                } else {
                    section = Section::None;
                }
            } else if section == Section::Video {
                if let Some(rtpmap) = line.strip_prefix("a=rtpmap:") {
                    // Keep the *first* H.264 payload type. Browsers list several
                    // (different profiles/packetization modes); the first is the
                    // baseline `42001f`, packetization-mode=1 profile that a
                    // sender (and str0m's answer) reliably keeps. Picking the last
                    // can land on a high profile the answerer drops, leaving the
                    // egress PT un-negotiated and the RTP silently undeliverable.
                    if rtpmap.contains("H264") && h264_pt.is_none() {
                        h264_pt = rtpmap.split(' ').next().and_then(|p| p.parse().ok());
                    }
                } else if let Some(m) = line.strip_prefix("a=mid:") {
                    mid = m.to_string();
                } else if let Some(ext) = line.strip_prefix("a=extmap:") {
                    // `a=extmap:<id>[/dir] <uri>` — capture the RID extension id.
                    if ext.contains("sdes:rid") && !ext.contains("repaired") {
                        rid_ext_id = ext.split(['/', ' ']).next().and_then(|id| id.parse().ok());
                    }
                } else if let Some(rid) = line.strip_prefix("a=rid:") {
                    // `a=rid:<id> send` — a simulcast layer the publisher sends.
                    let mut it = rid.split_whitespace();
                    if let (Some(id), Some(dir)) = (it.next(), it.next()) {
                        if dir == "send" {
                            rid_send.push(id.to_string());
                        }
                    }
                } else if let Some(sc) = line.strip_prefix("a=simulcast:") {
                    // `a=simulcast:send <alt>;<alt>;…` — take the primary rid of
                    // each `;`-separated layer (ignoring `,`-separated alternatives).
                    if let Some(send_list) = sc.strip_prefix("send ") {
                        simulcast = send_list
                            .split(';')
                            .filter_map(|alt| alt.split(',').next())
                            .map(|r| r.trim_start_matches('~').to_string())
                            .filter(|r| !r.is_empty())
                            .collect();
                    }
                } else if line == "a=sendonly" || line == "a=sendrecv" {
                    send = true;
                }
            } else if section == Section::Audio {
                if let Some(rtpmap) = line.strip_prefix("a=rtpmap:") {
                    if rtpmap.to_ascii_lowercase().contains("opus") && opus_pt.is_none() {
                        opus_pt = rtpmap.split(' ').next().and_then(|p| p.parse().ok());
                    }
                } else if line == "a=sendonly" || line == "a=sendrecv" {
                    send = true;
                }
            } else if section == Section::Application {
                if let Some(m) = line.strip_prefix("a=mid:") {
                    app_mid = m.to_string();
                    data_mid = Some(app_mid.clone());
                }
            }
        }

        let payload_type = h264_pt.or(payload_type)?;
        // Prefer the explicit `a=simulcast` order; fall back to the rid lines.
        let simulcast_rids = if !simulcast.is_empty() {
            simulcast
        } else {
            rid_send
        };
        Some(SdpOffer {
            mid,
            payload_type,
            audio_payload_type: opus_pt.or(audio_default_pt),
            send,
            rid_ext_id,
            simulcast_rids,
            data_mid,
        })
    }
}

/// The crypto/ICE parameters the host injects into the answer.
#[derive(Debug, Clone)]
pub struct SdpAnswerParams {
    /// `a=fingerprint` value (`sha-256 AA:BB:…`).
    pub fingerprint: String,
    /// `a=ice-ufrag` value.
    pub ice_ufrag: String,
    /// `a=ice-pwd` value.
    pub ice_pwd: String,
}

/// The direction the server's media line takes in the answer: `recvonly` for
/// WHIP ingest (the server receives), `sendonly` for WHEP egress (it sends).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaDirection {
    /// Server receives media (WHIP).
    RecvOnly,
    /// Server sends media (WHEP).
    SendOnly,
}

impl MediaDirection {
    fn attr(self) -> &'static str {
        match self {
            MediaDirection::RecvOnly => "recvonly",
            MediaDirection::SendOnly => "sendonly",
        }
    }
}

/// Build a WHIP (recvonly) SDP answer for `offer`. See [`build_answer_directed`].
pub fn build_answer(offer: &SdpOffer, params: &SdpAnswerParams) -> String {
    build_answer_directed(offer, params, MediaDirection::RecvOnly)
}

/// Build an SDP answer for `offer` with an explicit media `direction`.
///
/// The answer is a minimal single-video description echoing the offer's payload
/// type and mid, advertising the server's DTLS fingerprint and ICE credentials.
/// A real connection's ICE candidates are trickled separately by the transport.
pub fn build_answer_directed(
    offer: &SdpOffer,
    params: &SdpAnswerParams,
    direction: MediaDirection,
) -> String {
    let pt = offer.payload_type;
    // BUNDLE every accepted m-line (video, and the data channel when offered).
    let bundle = match &offer.data_mid {
        Some(d) => format!("{} {}", offer.mid, d),
        None => offer.mid.clone(),
    };
    let mut sdp = format!(
        "v=0\r\n\
o=- 0 0 IN IP4 0.0.0.0\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE {bundle}\r\n\
m=video 9 UDP/TLS/RTP/SAVPF {pt}\r\n\
c=IN IP4 0.0.0.0\r\n\
a=rtcp-mux\r\n\
a=mid:{mid}\r\n\
a={dir}\r\n\
a=ice-ufrag:{ufrag}\r\n\
a=ice-pwd:{pwd}\r\n\
a=fingerprint:{fp}\r\n\
a=setup:passive\r\n\
a=rtpmap:{pt} H264/90000\r\n\
a=rtcp-fb:{pt} nack pli\r\n\
a=rtcp-fb:{pt} ccm fir\r\n",
        bundle = bundle,
        mid = offer.mid,
        pt = pt,
        dir = direction.attr(),
        ufrag = params.ice_ufrag,
        pwd = params.ice_pwd,
        fp = params.fingerprint,
    );

    // Simulcast: accept the publisher's layers as `recv` (the server is the SFU
    // receiving every layer). Echo the RID extension and each rid.
    if direction == MediaDirection::RecvOnly && offer.is_simulcast() {
        if let Some(id) = offer.rid_ext_id {
            sdp.push_str(&format!(
                "a=extmap:{id} urn:ietf:params:rtp-hdrext:sdes:rid\r\n"
            ));
        }
        for rid in &offer.simulcast_rids {
            sdp.push_str(&format!("a=rid:{rid} recv\r\n"));
        }
        sdp.push_str(&format!(
            "a=simulcast:recv {}\r\n",
            offer.simulcast_rids.join(";")
        ));
    }

    // Data channel: accept the SCTP association on its own m-line.
    if let Some(data_mid) = &offer.data_mid {
        sdp.push_str(&format!(
            "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:{data_mid}\r\n\
a=ice-ufrag:{ufrag}\r\n\
a=ice-pwd:{pwd}\r\n\
a=fingerprint:{fp}\r\n\
a=setup:passive\r\n\
a=sctp-port:5000\r\n",
            data_mid = data_mid,
            ufrag = params.ice_ufrag,
            pwd = params.ice_pwd,
            fp = params.fingerprint,
        ));
    }

    sdp
}

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

    const OFFER: &str = "v=0\r\n\
o=- 0 0 IN IP4 0.0.0.0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n\
a=mid:vid\r\n\
a=sendonly\r\n\
a=rtpmap:96 H264/90000\r\n";

    #[test]
    fn parses_video_offer() {
        let o = SdpOffer::parse(OFFER).unwrap();
        assert_eq!(o.payload_type, 96);
        assert_eq!(o.mid, "vid");
        assert!(o.send);
    }

    #[test]
    fn audio_only_offer_is_rejected() {
        assert!(SdpOffer::parse("m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n").is_none());
    }

    #[test]
    fn parses_opus_audio_payload_alongside_video() {
        let offer = "v=0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
a=mid:vid\r\n\
a=sendonly\r\n\
a=rtpmap:96 H264/90000\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\
a=mid:aud\r\n\
a=sendonly\r\n\
a=rtpmap:111 opus/48000/2\r\n";
        let o = SdpOffer::parse(offer).unwrap();
        assert_eq!(o.payload_type, 96);
        assert_eq!(o.audio_payload_type, Some(111));
        // Video-only offer carries no audio PT.
        assert_eq!(SdpOffer::parse(OFFER).unwrap().audio_payload_type, None);
    }

    #[test]
    fn answer_echoes_mid_and_payload_and_injects_crypto() {
        let o = SdpOffer::parse(OFFER).unwrap();
        let a = build_answer(
            &o,
            &SdpAnswerParams {
                fingerprint: "sha-256 11:22".into(),
                ice_ufrag: "uf".into(),
                ice_pwd: "pw".into(),
            },
        );
        assert!(a.contains("a=mid:vid"));
        assert!(a.contains("m=video 9 UDP/TLS/RTP/SAVPF 96"));
        assert!(a.contains("a=recvonly"));
        assert!(a.contains("a=ice-ufrag:uf"));
        assert!(a.contains("a=fingerprint:sha-256 11:22"));
        assert!(a.contains("a=rtcp-fb:96 nack pli"));
    }

    const SIMULCAST_OFFER: &str = "v=0\r\n\
o=- 0 0 IN IP4 0.0.0.0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
a=mid:0\r\n\
a=sendonly\r\n\
a=rtpmap:96 H264/90000\r\n\
a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:rid\r\n\
a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\
a=rid:q send\r\n\
a=rid:h send\r\n\
a=rid:f send\r\n\
a=simulcast:send q;h;f\r\n";

    #[test]
    fn parses_simulcast_layers_and_rid_extension() {
        let o = SdpOffer::parse(SIMULCAST_OFFER).unwrap();
        assert!(o.is_simulcast());
        assert_eq!(o.rid_ext_id, Some(4)); // not the "repaired" extmap id 5
        assert_eq!(o.simulcast_rids, vec!["q", "h", "f"]);
    }

    #[test]
    fn answer_echoes_simulcast_as_recv() {
        let o = SdpOffer::parse(SIMULCAST_OFFER).unwrap();
        let a = build_answer(
            &o,
            &SdpAnswerParams {
                fingerprint: "sha-256 11:22".into(),
                ice_ufrag: "uf".into(),
                ice_pwd: "pw".into(),
            },
        );
        assert!(a.contains("a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:rid"));
        assert!(a.contains("a=rid:q recv"));
        assert!(a.contains("a=rid:f recv"));
        assert!(a.contains("a=simulcast:recv q;h;f"));
    }

    #[test]
    fn parses_and_answers_data_channel() {
        let offer = "v=0\r\n\
o=- 0 0 IN IP4 0.0.0.0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
a=mid:0\r\n\
a=sendonly\r\n\
a=rtpmap:96 H264/90000\r\n\
m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
a=mid:dc\r\n\
a=sctp-port:5000\r\n";
        let o = SdpOffer::parse(offer).unwrap();
        assert!(o.has_data_channel());
        assert_eq!(o.data_mid.as_deref(), Some("dc"));

        let a = build_answer(
            &o,
            &SdpAnswerParams {
                fingerprint: "sha-256 11:22".into(),
                ice_ufrag: "uf".into(),
                ice_pwd: "pw".into(),
            },
        );
        assert!(a.contains("a=group:BUNDLE 0 dc"));
        assert!(a.contains("m=application 9 UDP/DTLS/SCTP webrtc-datachannel"));
        assert!(a.contains("a=mid:dc"));
        assert!(a.contains("a=sctp-port:5000"));
    }
}