multimux 0.9.0

Multi-input (RTSP/RTP/TS-UDP/TS-HTTP/SRT/HLS-pull/DASH-pull/Smooth-pull/RTMP), multi-output (LL-HLS/DASH/LL-DASH) just-in-time repackaging HTTP origin (library: tokio + axum), with shared output auth and an external scheme plugin registry.
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
//! The `Output` abstraction: one implementation per delivery protocol
//! (LL-HLS, DASH, LL-DASH, classic TS-HLS) layered over the protocol-neutral
//! [`crate::route::RouteHandle`] (step 5b's replacement for the deleted
//! `hls_runtime::server::MediaStore` — see that module's own docs).
//!
//! Each `Output` renders only its own **manifest** (m3u8 / MPD) — the
//! init/segment/part byte serving is mounted **once per stream** by the
//! origin itself (`crate::origin::resource`), not per-output; see that
//! module's docs for why (the "multi-output nest collision" this split fixes
//! — issue #663 P4). LL-HLS and DASH share that one shared resource route
//! because they are both fMP4/CMAF over the same produced bytes;
//! [`ts_hls::TsHlsOutput`] (issue #887) shares the exact same route, but the
//! bytes it references are classic whole-segment `.ts` instead — the
//! resource route itself is container-agnostic (resolved through the route's
//! `hls_runtime::server::HlsOrigin`, which already dispatches on its own
//! configured `Container`), so no separate resource route is needed for it.
//! [`OutputKind::TsHls`] is mutually exclusive with
//! [`OutputKind::LlHls`]/[`OutputKind::Dash`]/[`OutputKind::LlDash`] on one
//! route (`crate::config::Route::validate_standalone`) — see that check's own
//! doc for why.

pub mod catchup;
pub mod dash;
pub mod ll_dash;
pub mod llhls;
pub mod smooth;
pub mod ts_hls;
// WHEP egress (issue #743): a raw listen-socket output (HTTP POST + SDP +
// ICE/DTLS-SRTP, mirroring `crate::source::whip`'s ingest side) rather than
// an axum-manifest `Output` — see `OutputKind::Whep`/`OutputKind::is_whep`
// below and `whep`'s own module doc. Only compiled behind this crate's
// `whep` Cargo feature (needs rustc >= 1.88 — see `Cargo.toml`'s `whep`
// feature doc).
#[cfg(feature = "whep")]
pub mod whep;

use std::sync::Arc;

use axum::Router;

use crate::route::RouteHandle;

/// Which delivery protocol an [`Output`] implements — used for config
/// (`crate::config::Route::outputs`) and diagnostics; never for dispatch
/// (the manifest routes an `Output` mounts are the actual behaviour).
///
/// [`OutputKind::Custom`] (issue #663 external scheme plugin registry) names
/// an external delivery protocol by an opaque `type_tag`, resolved at
/// `crate::origin::serve_with_registry` time via
/// [`crate::registry::SchemeRegistry::output`] — the escape hatch that lets a
/// third-party crate add a new output without editing this crate. Its
/// `params` is a `serde_json::Value`, which is `Clone` but not `Copy`, so this
/// enum can no longer derive `Copy`/`Hash` (a breaking change from the
/// pre-registry `OutputKind`); `PartialEq` (via `serde_json::Value`'s own) is
/// still derived — the runtime admin API's reload diffing
/// (`crate::origin::admin`, issue #749) compares a whole `crate::config::Route`
/// (which embeds `Vec<OutputKind>`) for equality to decide whether a route's
/// config actually changed.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum OutputKind {
    /// Low-Latency HLS (`master.m3u8` + `media.m3u8`).
    #[serde(rename = "llhls")]
    LlHls,
    /// MPEG-DASH (`manifest.mpd`).
    #[serde(rename = "dash")]
    Dash,
    /// Low-latency DASH (`manifest-ll.mpd`) — issue #663 P4.2 / #721. True
    /// chunked-transfer LL-DASH: see [`ll_dash`]'s module docs for how a
    /// whole-segment `SegmentTemplate` is served over HTTP chunked
    /// transfer-encoding while the segment is still being produced.
    #[serde(rename = "ll_dash")]
    LlDash,
    /// Microsoft Smooth Streaming (MS-SSTR) — `Manifest` plus fragment
    /// responses from the shared `Trunk`'s segment ring (the same fMP4
    /// bytes every other output shares). Issue #742.
    #[serde(rename = "smooth")]
    Smooth,
    /// Classic MPEG-TS HLS (`master.m3u8` + `media.m3u8` referencing `.ts`
    /// media segments instead of fMP4) — issue #887. Container is a
    /// per-*route* property (`crate::route::RouteHandle::with_container`),
    /// not per-output, so this kind is mutually exclusive with
    /// [`OutputKind::LlHls`]/[`OutputKind::Dash`]/[`OutputKind::LlDash`] on
    /// the same route — see `crate::config::Route::validate_standalone` for
    /// why (one `Trunk` segment ring per program, fMP4 *or* TS, never both).
    #[serde(rename = "ts_hls")]
    TsHls,
    /// Catch-up / time-shift / VOD-from-live serving over the route's DVR
    /// durable archive (issue #900) — `GET /catchup.m3u8`, `GET
    /// /vod/p{N}.m3u8`, `GET /catchup/seg-{seq}.{ext}` (see
    /// [`catchup::CatchupOutput`]). Requires `crate::config::Route::dvr` to
    /// be `enabled` — `crate::config::Route::validate_standalone` rejects
    /// this kind otherwise, since there would be no archive to serve.
    #[serde(rename = "catchup")]
    Catchup,
    /// Push to a remote SRT Listener (Caller mode). Issue #744.
    #[serde(rename = "srt_push")]
    SrtPush {
        url: String,
        #[serde(default)]
        format: Option<crate::config::PushFormat>,
        #[serde(default)]
        reconnect: Option<crate::config::ReconnectPolicy>,
    },
    /// Push to a remote RTMP server (client publish). Issue #744.
    #[serde(rename = "rtmp_push")]
    RtmpPush {
        url: String,
        #[serde(default)]
        format: Option<crate::config::PushFormat>,
        #[serde(default)]
        reconnect: Option<crate::config::ReconnectPolicy>,
    },
    /// Push to a remote RTSP server (ANNOUNCE/RECORD). Issue #744.
    #[serde(rename = "rtsp_push")]
    RtspPush {
        url: String,
        #[serde(default)]
        format: Option<crate::config::PushFormat>,
        #[serde(default)]
        reconnect: Option<crate::config::ReconnectPolicy>,
    },
    /// External output scheme resolved at runtime via
    /// [`crate::registry::SchemeRegistry`]. `type_tag` selects the registered
    /// factory; `params` is passed opaquely to it. JSON (this variant is not
    /// internally tagged like [`crate::config::InputSpec`], since the other
    /// three variants are plain strings): `{ "custom": { "type_tag": "webrtc",
    /// "params": { ... } } }`.
    #[serde(rename = "custom")]
    Custom {
        /// Selects the registered factory in
        /// [`crate::registry::SchemeRegistry`] that builds this output.
        type_tag: String,
        /// Opaque config passed to the registered factory verbatim.
        #[serde(default)]
        params: serde_json::Value,
    },
    /// WHEP (draft-ietf-wish-whep) egress (issue #743): accepts an inbound
    /// viewer's HTTP `POST`ed SDP offer, answers over ICE + DTLS-SRTP, and
    /// pushes this route's `Trunk` samples out as SRTP RTP — see
    /// [`crate::output::whep`]. **Video (H.264) only** in this cut, the same
    /// constraint [`crate::config::InputSpec::Whip`] documents in reverse:
    /// this workspace has no RTP/Opus *packetiser* either. Only compiled in
    /// behind this crate's own `whep` Cargo feature, which (unlike this
    /// crate's default build) needs rustc >= 1.88 — see `Cargo.toml`'s
    /// `whep` feature doc.
    #[cfg(feature = "whep")]
    #[serde(rename = "whep")]
    Whep {
        /// `host:port` to bind the WHEP viewer HTTP endpoint to (e.g.
        /// `"0.0.0.0:8081"`). Any request path is accepted — this is a
        /// single-route listener, not a multi-tenant path router.
        listen: String,
    },
}

impl OutputKind {
    /// The spec/field-enum label (workspace #204 convention): a stable,
    /// lowercase token per kind, suitable for logs/config.
    /// [`OutputKind::Custom`] labels itself by its own `type_tag` rather than
    /// a fixed token, which is why this borrows from `self` (`&str`) instead
    /// of returning `&'static str` like most `name()` methods in this
    /// workspace.
    pub fn name(&self) -> &str {
        match self {
            OutputKind::LlHls => "llhls",
            OutputKind::Dash => "dash",
            OutputKind::LlDash => "ll_dash",
            OutputKind::Smooth => "smooth",
            OutputKind::TsHls => "ts_hls",
            OutputKind::Catchup => "catchup",
            OutputKind::SrtPush { .. } => "srt_push",
            OutputKind::RtmpPush { .. } => "rtmp_push",
            OutputKind::RtspPush { .. } => "rtsp_push",
            OutputKind::Custom { type_tag, .. } => type_tag,
            #[cfg(feature = "whep")]
            OutputKind::Whep { .. } => "whep",
        }
    }

    /// Whether this output is a push output (SRT/RTMP/RTSP push) rather than
    /// an HTTP-served output — push outputs are driven by
    /// [`crate::push::drive_push`], not built into an [`Output`] trait object.
    pub fn is_push(&self) -> bool {
        matches!(
            self,
            OutputKind::SrtPush { .. } | OutputKind::RtmpPush { .. } | OutputKind::RtspPush { .. }
        )
    }

    /// Whether this is [`OutputKind::Whep`] — a raw listen-socket output
    /// (like [`Self::is_push`]'s outputs, no [`Output`] trait object, no
    /// axum manifest routes) but, unlike a push output, one that *accepts*
    /// inbound viewer connections rather than dialing out to a fixed URL —
    /// see `crate::origin::serve_with_registry_impl`'s output-spawning
    /// split. Defined unconditionally (returning `false` when the `whep`
    /// feature is off) so call sites never need their own `#[cfg]`.
    pub fn is_whep(&self) -> bool {
        #[cfg(feature = "whep")]
        {
            matches!(self, OutputKind::Whep { .. })
        }
        #[cfg(not(feature = "whep"))]
        {
            false
        }
    }

    /// Build the [`Output`] this kind names, using
    /// [`llhls::DEFAULT_PLAYLIST_NAME`] for LL-HLS's media playlist filename.
    /// Use [`Self::build_with_playlist_name`] to serve it under a
    /// configured name instead (`crate::config::Config::playlist_name`).
    ///
    /// # Panics
    ///
    /// Panics if `self` is [`OutputKind::Custom`] — a custom output cannot be
    /// built without a [`crate::registry::SchemeRegistry`]; use
    /// `crate::origin::serve_with_registry`, which resolves it via
    /// `registry.output(type_tag)` instead of calling this method.
    pub fn build(&self) -> Arc<dyn Output> {
        self.build_with_playlist_name(llhls::DEFAULT_PLAYLIST_NAME)
    }

    /// Build the [`Output`] this kind names, serving LL-HLS's media playlist
    /// at `playlist_name` (ignored for [`OutputKind::Dash`]/[`OutputKind::LlDash`],
    /// neither of which has an equivalent configurable filename —
    /// `manifest.mpd`/`manifest-ll.mpd` are fixed).
    ///
    /// # Panics
    ///
    /// Panics if `self` is [`OutputKind::Custom`] — see [`Self::build`].
    pub fn build_with_playlist_name(&self, playlist_name: &str) -> Arc<dyn Output> {
        match self {
            OutputKind::LlHls => Arc::new(llhls::LlHlsOutput::new(playlist_name)),
            OutputKind::Dash => Arc::new(dash::DashOutput),
            OutputKind::LlDash => Arc::new(ll_dash::LlDashOutput),
            OutputKind::Smooth => Arc::new(smooth::SmoothOutput),
            OutputKind::TsHls => Arc::new(ts_hls::TsHlsOutput::new(playlist_name)),
            OutputKind::Catchup => Arc::new(catchup::CatchupOutput),
            // Push outputs are not `Arc<dyn Output>` — they are driven by the
            // push driver (`crate::push`) instead of mounting manifest routes.
            OutputKind::SrtPush { .. }
            | OutputKind::RtmpPush { .. }
            | OutputKind::RtspPush { .. } => {
                unreachable!(
                    "OutputKind::SrtPush/RtmpPush/RtspPush produce no Arc<dyn Output> — \
                     push outputs are driven by crate::push::drive_push"
                )
            }
            OutputKind::Custom { .. } => unreachable!(
                "OutputKind::Custom cannot be built without a SchemeRegistry — \
                 crate::origin::serve_with_registry resolves it via \
                 `registry.output(type_tag)` instead of this method"
            ),
            #[cfg(feature = "whep")]
            OutputKind::Whep { .. } => unreachable!(
                "OutputKind::Whep produces no Arc<dyn Output> — WHEP egress is driven by \
                 crate::output::whep::run_whep, a raw listen socket, exactly like WHIP \
                 ingest on the source side"
            ),
        }
    }
}

broadcast_common::impl_spec_display!(OutputKind);

/// One delivery protocol's axum **manifest** routes for a single stream,
/// mounted by the origin under `/{stream}/` alongside every other configured
/// output's manifest routes and the one shared resource route (see this
/// module's docs).
pub trait Output: Send + Sync + 'static {
    /// This output's kind — for diagnostics/config round-tripping only.
    fn kind(&self) -> OutputKind;

    /// Build the axum routes this output serves for one stream's manifest,
    /// sharing the one `route`. The origin merges the returned router with
    /// every other configured output's manifest routes and the shared
    /// resource route, then mounts the whole thing under `/{stream}/`, so
    /// routes here are relative (e.g. `/media.m3u8`, not `/:stream/media.m3u8`)
    /// and must never collide with another enabled output's manifest
    /// filename or with the shared `/:file` catch-all (a bare numeric/opaque
    /// filename would; `master.m3u8`/`media.m3u8`/`manifest.mpd`/
    /// `manifest-ll.mpd` don't).
    ///
    /// # At most one output may set a fallback
    ///
    /// The origin `merge`s these routers, and **axum panics when two merged
    /// routers both set a fallback**. `smooth` sets one, because Smooth's
    /// parenthesised `QualityLevels(…)/Fragments(…)` segments cannot be
    /// expressed as literal axum routes. It is therefore currently the only
    /// output that may — and because the collision panics at *startup* rather
    /// than failing to compile, a second one would take the server down on
    /// every route that enables both, not fail in CI.
    ///
    /// A new output needing multi-segment paths must either extend `smooth`'s
    /// fallback to dispatch on prefix, or the merge must move to a dispatching
    /// parent router. `every_output_kind_merges_without_panicking` pins this.
    fn manifest_routes(&self, route: Arc<RouteHandle>) -> Router;
}

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

    #[test]
    fn output_kind_name_and_display_agree() {
        for (kind, label) in [
            (OutputKind::LlHls, "llhls"),
            (OutputKind::Dash, "dash"),
            (OutputKind::LlDash, "ll_dash"),
            (OutputKind::Smooth, "smooth"),
            (OutputKind::TsHls, "ts_hls"),
            (OutputKind::Catchup, "catchup"),
        ] {
            assert_eq!(kind.name(), label);
            assert_eq!(kind.to_string(), label);
        }
    }

    /// Merging every output's manifest routes must not panic.
    ///
    /// `Router::merge` panics at runtime when both routers set a fallback, and
    /// `smooth` sets one — its parenthesised `QualityLevels(…)/Fragments(…)`
    /// segments cannot be literal axum routes. A second fallback-setting
    /// output would take down every route enabling both, and it would do so at
    /// **startup**, where nothing in CI exercises it. This is the check that
    /// turns that into a test failure instead.
    #[test]
    fn every_output_kind_merges_without_panicking() {
        let route = Arc::new(RouteHandle::new(1.0, 250, 8));

        // The maximal set a route may actually configure. `ts_hls` is excluded
        // deliberately: it is mutually exclusive with the fMP4 outputs (it
        // serves `/media.m3u8` too, so merging it with `llhls` panics with
        // "Overlapping method route"), and `Config::validate` rejects that
        // combination before a router is ever built.
        let mut merged = Router::new();
        for kind in [
            OutputKind::LlHls,
            OutputKind::Dash,
            OutputKind::LlDash,
            OutputKind::Smooth,
            OutputKind::Catchup,
        ] {
            merged = merged.merge(kind.build().manifest_routes(route.clone()));
        }
        // Consuming the merged router is the assertion: `merge` panics on a
        // duplicate fallback, so reaching here is the pass condition.
        let _: Router = merged;

        // `ts_hls` alone, the other permitted shape.
        let _: Router = Router::new().merge(OutputKind::TsHls.build().manifest_routes(route));
    }

    #[test]
    fn output_kind_serde_round_trips() {
        // `OutputKind` no longer derives `PartialEq` (its `Custom` variant
        // carries a `serde_json::Value`, so instances are compared by
        // `name()` instead of `==` — see the type's doc comment).
        for kind in [
            OutputKind::LlHls,
            OutputKind::Dash,
            OutputKind::LlDash,
            OutputKind::Smooth,
            OutputKind::TsHls,
            OutputKind::Catchup,
        ] {
            let json = serde_json::to_string(&kind).unwrap();
            let back: OutputKind = serde_json::from_str(&json).unwrap();
            assert_eq!(back.name(), kind.name());
        }
        assert_eq!(
            serde_json::to_string(&OutputKind::LlHls).unwrap(),
            "\"llhls\""
        );
        assert_eq!(
            serde_json::to_string(&OutputKind::TsHls).unwrap(),
            "\"ts_hls\""
        );
    }

    #[test]
    fn output_kind_build_matches_kind() {
        assert!(matches!(
            OutputKind::LlHls.build().kind(),
            OutputKind::LlHls
        ));
        assert!(matches!(OutputKind::Dash.build().kind(), OutputKind::Dash));
        assert!(matches!(
            OutputKind::LlDash.build().kind(),
            OutputKind::LlDash
        ));
        assert!(matches!(
            OutputKind::TsHls.build().kind(),
            OutputKind::TsHls
        ));
        assert!(matches!(
            OutputKind::Catchup.build().kind(),
            OutputKind::Catchup
        ));
    }

    // --- issue #663 external scheme plugin registry: `OutputKind::Custom` ---

    /// `OutputKind::Custom` deserializes with the right `type_tag`/`params`.
    #[test]
    fn output_kind_custom_deserializes_with_type_tag_and_params() {
        let json = r#"{ "custom": { "type_tag": "webrtc", "params": { "k": "v" } } }"#;
        let kind: OutputKind = serde_json::from_str(json).unwrap();
        match &kind {
            OutputKind::Custom { type_tag, params } => {
                assert_eq!(type_tag, "webrtc");
                assert_eq!(params.get("k").and_then(|v| v.as_str()), Some("v"));
            }
            other => panic!("expected OutputKind::Custom, got {other:?}"),
        }
        assert_eq!(kind.name(), "webrtc");
    }

    /// `#[should_panic]`: [`OutputKind::build_with_playlist_name`] cannot
    /// build a [`OutputKind::Custom`] without a
    /// `crate::registry::SchemeRegistry` — documented via this test so a
    /// future refactor that silently returns a bogus `Output` instead of
    /// panicking is caught.
    #[test]
    #[should_panic(expected = "SchemeRegistry")]
    fn output_kind_custom_build_panics() {
        let kind = OutputKind::Custom {
            type_tag: "webrtc".into(),
            params: serde_json::Value::Null,
        };
        let _ = kind.build();
    }
}