Skip to main content

oxideav_core/registry/
source.rs

1//! Generic source registry.
2//!
3//! `SourceRegistry` maps URI schemes (`file`, `http`, `rtmp`, `generate`,
4//! …) to opener functions and dispatches `open(uri)` to the right driver.
5//! A driver opens a URI as one of four shapes:
6//!
7//! * [`BytesSource`] — a `Read + Seek` byte stream that downstream code
8//!   then passes to a container demuxer (the historical shape, used by
9//!   `file://` and `http(s)://`).
10//! * [`PacketSource`] — a producer of already-demuxed [`Packet`]s. Used
11//!   by transport-layer protocols that do their own demux (RTMP, future
12//!   SRT / WebRTC). Skips the container layer entirely.
13//! * [`FrameSource`] — a producer of already-decoded [`Frame`]s. Used by
14//!   synthetic generators that emit frames natively, skipping both the
15//!   container and decoder stages.
16//! * [`MultiTitleSource`] — a source that emits N discrete byte streams
17//!   (titles), one per logical "segment" the source carries
18//!   (BD-ROM chapters or unique titles, DVD VTS entries, multi-title
19//!   MKV editions, …). The CLI's `oxideav remux` substitutes a
20//!   per-title token into a `%s.<ext>`-style output-path template, so
21//!   each title lands in its own output file.
22//!
23//! The driver picks the variant when it registers; [`SourceRegistry::open`]
24//! returns the corresponding [`SourceOutput`] enum so the pipeline
25//! executor can branch on the source shape.
26
27use std::collections::HashMap;
28use std::io::{Read, Seek};
29
30use crate::{CodecParameters, Error, Frame, Packet, Result, StreamInfo};
31
32// ───────────────────────── traits ─────────────────────────
33
34/// A seekable byte stream (`Read + Seek + Send`). Replaces the historical
35/// `Box<dyn ReadSeek>` opener-return type with a name that mirrors the
36/// other source-shape traits in this module. Blanket-implemented for
37/// every type that satisfies the bounds, so existing readers (files,
38/// `Cursor<Vec<u8>>`, HTTP-over-Range adapters) work unchanged.
39pub trait BytesSource: Read + Seek + Send {}
40impl<T: Read + Seek + Send> BytesSource for T {}
41
42/// A producer of already-demuxed [`Packet`]s.
43///
44/// Used by transport-layer protocols that perform demux themselves
45/// (RTMP, RTSP, …). The pipeline executor consumes packets directly,
46/// skipping the container-demux stage that bytes-shape sources go
47/// through.
48pub trait PacketSource: Send {
49    /// Streams advertised by this source. Stable across the lifetime of
50    /// the source.
51    fn streams(&self) -> &[StreamInfo];
52
53    /// Read the next packet from any stream. Returns [`Error::Eof`] at
54    /// end of stream.
55    fn next_packet(&mut self) -> Result<Packet>;
56
57    /// Source-level metadata as ordered (key, value) pairs. Default is
58    /// empty.
59    fn metadata(&self) -> &[(String, String)] {
60        &[]
61    }
62
63    /// Source-level duration in microseconds, if known. Default is
64    /// `None`. Live sources (RTMP push, etc.) typically return `None`.
65    fn duration_micros(&self) -> Option<i64> {
66        None
67    }
68}
69
70/// A source that emits N discrete byte streams ("titles") rather
71/// than a single contiguous one.
72///
73/// The motivating shape is BD-ROM: a disc contains many *titles*
74/// (whole movies, behind-the-scenes featurettes, trailers) and each
75/// title can be sliced further into *chapters*. The Blu-ray source
76/// driver expresses both shapes through this trait — a URI like
77/// `bluray:///path?title=1&chapters=2-5` opens a [`MultiTitleSource`]
78/// whose four titles are chapters 2, 3, 4, 5 of disc-title 1; a URI
79/// without `?chapters=` opens a [`MultiTitleSource`] with a single
80/// title (the autoplay title). DVD-Video, multi-edition MKV, and
81/// any other format with explicit segment structure plug in the
82/// same way.
83///
84/// Downstream callers fan out: each title is opened as its own
85/// [`BytesSource`], demuxed independently, and written to its own
86/// output path. The CLI's `oxideav remux` substitutes
87/// [`Self::title_label`] into a `%s` token in the output-path
88/// template so each title lands in a separate file. Other front-ends
89/// (`oxideplay bluray://`, a future GUI title-picker, …) can iterate
90/// titles the same way.
91///
92/// Sources that don't have multi-title structure should keep
93/// returning a [`BytesSource`] — there's no benefit to wrapping a
94/// single-title file in this trait.
95pub trait MultiTitleSource: Send {
96    /// Number of titles this source emits. Stable for the lifetime
97    /// of the source — title discovery happens at `open` time, not
98    /// while streaming.
99    fn title_count(&self) -> usize;
100
101    /// Open the title at `index` (0-based) as a single-stream
102    /// [`BytesSource`] the existing container registry can demux.
103    /// `index` must satisfy `index < self.title_count()`. Calling
104    /// `open_title` more than once on the same index is allowed —
105    /// the returned source is a fresh handle each time.
106    fn open_title(&mut self, index: usize) -> Result<Box<dyn BytesSource>>;
107
108    /// Stable per-title identifier substituted into a `%s` token of
109    /// a templated output path. Examples: `"3"` for chapter 3,
110    /// `"t01"` for title 1, `"introduction"` for a named edition.
111    /// Returned values must be filename-safe: ASCII letters / digits
112    /// / `-` / `_`, no path separators, no whitespace, no leading
113    /// dot. Calling code is free to additionally sanitise; an empty
114    /// string is rejected.
115    fn title_label(&self, index: usize) -> String;
116
117    /// Human-readable display name for the title (e.g.
118    /// `"Kite Uncut — Director's Cut"`) — used by interactive
119    /// front-ends to render menus. `None` when the source carries
120    /// no name. The default returns `None`.
121    fn title_display_name(&self, index: usize) -> Option<String> {
122        let _ = index;
123        None
124    }
125
126    /// Container-format hint for the title's byte stream
127    /// (`"mpegts"`, `"matroska"`, `"mp4"`, …). When `Some`, callers
128    /// can skip the format-detector pass and hand the bytes straight
129    /// to that demuxer. `None` means "sniff it" — preserves the
130    /// existing detection path. The default returns `None`.
131    fn title_container_hint(&self, index: usize) -> Option<&'static str> {
132        let _ = index;
133        None
134    }
135
136    /// Source-level metadata as ordered (key, value) pairs (disc
137    /// label, BDMT `<di:name>`, region code, …). Default is empty.
138    fn metadata(&self) -> &[(String, String)] {
139        &[]
140    }
141}
142
143/// A producer of already-decoded [`Frame`]s.
144///
145/// Used by synthetic generators (testsrc, sine sweep, gradient image,
146/// …) that emit decoded frames natively. The pipeline executor consumes
147/// frames directly, skipping both the container-demux and decode stages.
148pub trait FrameSource: Send {
149    /// Codec parameters describing the frames this source emits. Stable
150    /// across the lifetime of the source. Even though the frames are
151    /// already decoded, downstream filters and encoders need the
152    /// parameter shape (sample rate / pixel format / channel layout /
153    /// frame rate / …) to configure themselves.
154    fn params(&self) -> &CodecParameters;
155
156    /// Produce the next frame. Returns [`Error::Eof`] at end of stream.
157    fn next_frame(&mut self) -> Result<Frame>;
158
159    /// Source-level metadata as ordered (key, value) pairs. Default is
160    /// empty.
161    fn metadata(&self) -> &[(String, String)] {
162        &[]
163    }
164
165    /// Source-level duration in microseconds, if known. Default is
166    /// `None`.
167    fn duration_micros(&self) -> Option<i64> {
168        None
169    }
170}
171
172/// What a [`SourceRegistry::open`] call returns. The variant is decided
173/// at driver-registration time, so callers can match on the shape and
174/// branch the pipeline accordingly.
175///
176/// **Marked `#[non_exhaustive]`** so a new source kind (e.g. a future
177/// `LiveStream` variant) can be added without semver-breaking
178/// downstream consumers. Match arms must include a wildcard.
179#[non_exhaustive]
180pub enum SourceOutput {
181    /// A raw byte stream — feed it to container probing / a demuxer.
182    Bytes(Box<dyn BytesSource>),
183    /// Already-demuxed compressed packets — feed them to decoders.
184    Packets(Box<dyn PacketSource>),
185    /// Already-decoded frames (e.g. a capture device) — feed them to
186    /// filters / encoders directly.
187    Frames(Box<dyn FrameSource>),
188    /// A multi-title source (BD-ROM, DVD-Video, multi-edition MKV).
189    /// Callers fan out: each title is opened independently via
190    /// [`MultiTitleSource::open_title`], demuxed, and routed to its
191    /// own output sink.
192    MultiTitle(Box<dyn MultiTitleSource>),
193}
194
195// ───────────────────────── opener function aliases ─────────────────────────
196
197/// Opener for a [`BytesSource`] driver.
198pub type OpenBytesFn = fn(uri: &str) -> Result<Box<dyn BytesSource>>;
199
200/// Opener for a [`PacketSource`] driver.
201pub type OpenPacketsFn = fn(uri: &str) -> Result<Box<dyn PacketSource>>;
202
203/// Opener for a [`FrameSource`] driver.
204pub type OpenFramesFn = fn(uri: &str) -> Result<Box<dyn FrameSource>>;
205
206/// Opener for a [`MultiTitleSource`] driver.
207pub type OpenMultiTitleFn = fn(uri: &str) -> Result<Box<dyn MultiTitleSource>>;
208
209/// Internal per-scheme entry: which opener kind is registered for this
210/// scheme. Stored in a single map so [`SourceRegistry::open`] can
211/// dispatch with a single lookup, then match the variant to wrap in the
212/// returned [`SourceOutput`].
213enum OpenerEntry {
214    Bytes(OpenBytesFn),
215    Packets(OpenPacketsFn),
216    Frames(OpenFramesFn),
217    MultiTitle(OpenMultiTitleFn),
218}
219
220// ───────────────────────── SourceRegistry ─────────────────────────
221
222/// Registry mapping URI schemes to opener functions. Each scheme picks
223/// one of three opener kinds (bytes / packets / frames) at registration
224/// time; callers see the choice via the [`SourceOutput`] variant
225/// returned from [`open`](Self::open).
226#[derive(Default)]
227pub struct SourceRegistry {
228    schemes: HashMap<String, OpenerEntry>,
229}
230
231impl SourceRegistry {
232    /// Empty registry. Callers must register at least one driver before
233    /// calling [`open`](Self::open). The conventional minimum is the
234    /// `file` driver (provided by the `oxideav-source` crate).
235    pub fn new() -> Self {
236        Self::default()
237    }
238
239    /// Register a [`BytesSource`] opener for a scheme. Schemes are
240    /// normalised to ASCII lowercase. Replaces any prior registration
241    /// (including registrations of other opener kinds).
242    pub fn register_bytes(&mut self, scheme: &str, opener: OpenBytesFn) {
243        self.schemes
244            .insert(scheme.to_ascii_lowercase(), OpenerEntry::Bytes(opener));
245    }
246
247    /// Register a [`PacketSource`] opener for a scheme. Schemes are
248    /// normalised to ASCII lowercase. Replaces any prior registration
249    /// (including registrations of other opener kinds).
250    pub fn register_packets(&mut self, scheme: &str, opener: OpenPacketsFn) {
251        self.schemes
252            .insert(scheme.to_ascii_lowercase(), OpenerEntry::Packets(opener));
253    }
254
255    /// Register a [`FrameSource`] opener for a scheme. Schemes are
256    /// normalised to ASCII lowercase. Replaces any prior registration
257    /// (including registrations of other opener kinds).
258    pub fn register_frames(&mut self, scheme: &str, opener: OpenFramesFn) {
259        self.schemes
260            .insert(scheme.to_ascii_lowercase(), OpenerEntry::Frames(opener));
261    }
262
263    /// Register a [`MultiTitleSource`] opener for a scheme. Schemes
264    /// are normalised to ASCII lowercase. Replaces any prior
265    /// registration (including registrations of other opener kinds).
266    pub fn register_multi_title(&mut self, scheme: &str, opener: OpenMultiTitleFn) {
267        self.schemes
268            .insert(scheme.to_ascii_lowercase(), OpenerEntry::MultiTitle(opener));
269    }
270
271    /// Open a URI. The URI's scheme determines which opener runs; bare
272    /// paths (no scheme) and unrecognised schemes both fall back to the
273    /// `file` driver if it is registered.
274    ///
275    /// Returns a [`SourceOutput`] whose variant matches the registered
276    /// opener kind: bytes-shape drivers return `SourceOutput::Bytes`,
277    /// packet-shape drivers return `SourceOutput::Packets`, and so on.
278    pub fn open(&self, uri_str: &str) -> Result<SourceOutput> {
279        let (scheme, _) = split_scheme(uri_str);
280        let scheme = scheme.to_ascii_lowercase();
281        if let Some(entry) = self.schemes.get(&scheme) {
282            return dispatch(entry, uri_str);
283        }
284        // Fall back to file driver for unknown schemes.
285        if let Some(entry) = self.schemes.get("file") {
286            return dispatch(entry, uri_str);
287        }
288        Err(Error::Unsupported(format!(
289            "no source driver for scheme '{scheme}' (URI: {uri_str})"
290        )))
291    }
292
293    /// Iterate the registered schemes (for diagnostics).
294    pub fn schemes(&self) -> impl Iterator<Item = &str> {
295        self.schemes.keys().map(|s| s.as_str())
296    }
297}
298
299fn dispatch(entry: &OpenerEntry, uri_str: &str) -> Result<SourceOutput> {
300    match entry {
301        OpenerEntry::Bytes(open) => open(uri_str).map(SourceOutput::Bytes),
302        OpenerEntry::Packets(open) => open(uri_str).map(SourceOutput::Packets),
303        OpenerEntry::Frames(open) => open(uri_str).map(SourceOutput::Frames),
304        OpenerEntry::MultiTitle(open) => open(uri_str).map(SourceOutput::MultiTitle),
305    }
306}
307
308/// Split a URI into `(scheme, rest)`. Bare paths (no scheme) report scheme
309/// `"file"` and `rest = uri`. Path-like inputs that happen to start with
310/// `c:` on Windows are treated as bare paths.
311pub(crate) fn split_scheme(uri: &str) -> (&str, &str) {
312    if let Some(idx) = uri.find(':') {
313        let (scheme, rest) = uri.split_at(idx);
314        let rest = &rest[1..]; // skip ':'
315
316        // Reject single-letter scheme that looks like a Windows drive letter.
317        if scheme.len() == 1 && scheme.chars().next().unwrap().is_ascii_alphabetic() {
318            return ("file", uri);
319        }
320
321        // Scheme must be ASCII alphanumeric / `+` / `-` / `.`, starting with a letter.
322        let valid = !scheme.is_empty()
323            && scheme.chars().next().unwrap().is_ascii_alphabetic()
324            && scheme
325                .chars()
326                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
327
328        if !valid {
329            return ("file", uri);
330        }
331
332        // Strip leading `//` from rest if present.
333        let rest = rest.strip_prefix("//").unwrap_or(rest);
334        return (scheme, rest);
335    }
336    ("file", uri)
337}
338
339// ───────────────────────── tests ─────────────────────────
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344    use crate::frame::{AudioFrame, Frame};
345    use crate::packet::Packet;
346    use crate::stream::{CodecId, CodecParameters, StreamInfo};
347    use crate::time::TimeBase;
348    use std::io::{Cursor, Read};
349
350    // ---- mock BytesSource ----
351    fn open_bytes_mock(_uri: &str) -> Result<Box<dyn BytesSource>> {
352        Ok(Box::new(Cursor::new(b"hello world".to_vec())))
353    }
354
355    #[test]
356    fn register_bytes_and_open_returns_bytes_variant() {
357        let mut reg = SourceRegistry::new();
358        reg.register_bytes("mockb", open_bytes_mock);
359        let out = reg.open("mockb://anything").expect("open");
360        match out {
361            SourceOutput::Bytes(mut r) => {
362                let mut buf = String::new();
363                r.read_to_string(&mut buf).unwrap();
364                assert_eq!(buf, "hello world");
365            }
366            _ => panic!("expected SourceOutput::Bytes"),
367        }
368    }
369
370    // ---- mock PacketSource ----
371    struct MockPacketSource {
372        streams: Vec<StreamInfo>,
373        emitted: bool,
374    }
375
376    impl MockPacketSource {
377        fn new() -> Self {
378            let params = CodecParameters::audio(CodecId::new("pcm_s16le"));
379            let s = StreamInfo {
380                index: 0,
381                time_base: TimeBase::new(1, 1000),
382                duration: None,
383                start_time: None,
384                params,
385            };
386            Self {
387                streams: vec![s],
388                emitted: false,
389            }
390        }
391    }
392
393    impl PacketSource for MockPacketSource {
394        fn streams(&self) -> &[StreamInfo] {
395            &self.streams
396        }
397        fn next_packet(&mut self) -> Result<Packet> {
398            if self.emitted {
399                return Err(Error::Eof);
400            }
401            self.emitted = true;
402            Ok(Packet::new(0, TimeBase::new(1, 1000), vec![1, 2, 3, 4]))
403        }
404    }
405
406    fn open_packets_mock(_uri: &str) -> Result<Box<dyn PacketSource>> {
407        Ok(Box::new(MockPacketSource::new()))
408    }
409
410    #[test]
411    fn register_packets_and_open_returns_packets_variant() {
412        let mut reg = SourceRegistry::new();
413        reg.register_packets("mockp", open_packets_mock);
414        let out = reg.open("mockp://anything").expect("open");
415        match out {
416            SourceOutput::Packets(mut p) => {
417                assert_eq!(p.streams().len(), 1);
418                let pkt = p.next_packet().expect("first packet");
419                assert_eq!(pkt.data, vec![1, 2, 3, 4]);
420                assert!(matches!(p.next_packet(), Err(Error::Eof)));
421            }
422            _ => panic!("expected SourceOutput::Packets"),
423        }
424    }
425
426    // ---- mock FrameSource ----
427    struct MockFrameSource {
428        params: CodecParameters,
429        emitted: bool,
430    }
431
432    impl MockFrameSource {
433        fn new() -> Self {
434            Self {
435                params: CodecParameters::audio(CodecId::new("pcm_s16le")),
436                emitted: false,
437            }
438        }
439    }
440
441    impl FrameSource for MockFrameSource {
442        fn params(&self) -> &CodecParameters {
443            &self.params
444        }
445        fn next_frame(&mut self) -> Result<Frame> {
446            if self.emitted {
447                return Err(Error::Eof);
448            }
449            self.emitted = true;
450            Ok(Frame::Audio(AudioFrame {
451                samples: 1,
452                pts: Some(0),
453                data: vec![vec![0u8, 0u8]],
454            }))
455        }
456    }
457
458    fn open_frames_mock(_uri: &str) -> Result<Box<dyn FrameSource>> {
459        Ok(Box::new(MockFrameSource::new()))
460    }
461
462    #[test]
463    fn register_frames_and_open_returns_frames_variant() {
464        let mut reg = SourceRegistry::new();
465        reg.register_frames("mockf", open_frames_mock);
466        let out = reg.open("mockf://anything").expect("open");
467        match out {
468            SourceOutput::Frames(mut f) => {
469                assert_eq!(f.params().codec_id.as_str(), "pcm_s16le");
470                let frame = f.next_frame().expect("first frame");
471                match frame {
472                    Frame::Audio(a) => assert_eq!(a.samples, 1),
473                    _ => panic!("expected audio frame"),
474                }
475                assert!(matches!(f.next_frame(), Err(Error::Eof)));
476            }
477            _ => panic!("expected SourceOutput::Frames"),
478        }
479    }
480
481    #[test]
482    fn unknown_scheme_falls_back_to_file_when_registered() {
483        let mut reg = SourceRegistry::new();
484        reg.register_bytes("file", open_bytes_mock);
485        // No `foo` driver — falls through to the `file` driver.
486        let out = reg.open("foo://x").expect("fallback open");
487        assert!(matches!(out, SourceOutput::Bytes(_)));
488    }
489
490    #[test]
491    fn unknown_scheme_with_no_file_driver_errors() {
492        let reg = SourceRegistry::new();
493        let r = reg.open("nope://x");
494        assert!(matches!(r, Err(Error::Unsupported(_))));
495    }
496
497    // ---- mock MultiTitleSource ----
498    struct MockMultiTitleSource {
499        labels: Vec<String>,
500    }
501
502    impl MultiTitleSource for MockMultiTitleSource {
503        fn title_count(&self) -> usize {
504            self.labels.len()
505        }
506        fn open_title(&mut self, index: usize) -> Result<Box<dyn BytesSource>> {
507            if index >= self.labels.len() {
508                return Err(Error::Unsupported(format!(
509                    "no title {index} (have {})",
510                    self.labels.len()
511                )));
512            }
513            // Each title is just its label repeated 4×.
514            let payload = self.labels[index].as_bytes().repeat(4);
515            Ok(Box::new(Cursor::new(payload)))
516        }
517        fn title_label(&self, index: usize) -> String {
518            self.labels[index].clone()
519        }
520        fn title_display_name(&self, index: usize) -> Option<String> {
521            Some(format!("Title {}", self.labels[index]))
522        }
523        fn title_container_hint(&self, _index: usize) -> Option<&'static str> {
524            Some("mpegts")
525        }
526    }
527
528    fn open_multi_title_mock(_uri: &str) -> Result<Box<dyn MultiTitleSource>> {
529        Ok(Box::new(MockMultiTitleSource {
530            labels: vec!["1".to_string(), "2".to_string(), "3".to_string()],
531        }))
532    }
533
534    #[test]
535    fn register_multi_title_and_open_returns_multi_title_variant() {
536        let mut reg = SourceRegistry::new();
537        reg.register_multi_title("mockmt", open_multi_title_mock);
538        let out = reg.open("mockmt://anything").expect("open");
539        match out {
540            SourceOutput::MultiTitle(mut mt) => {
541                assert_eq!(mt.title_count(), 3);
542                assert_eq!(mt.title_label(0), "1");
543                assert_eq!(mt.title_display_name(2).as_deref(), Some("Title 3"));
544                assert_eq!(mt.title_container_hint(0), Some("mpegts"));
545                let mut buf = String::new();
546                mt.open_title(1)
547                    .expect("title 1")
548                    .read_to_string(&mut buf)
549                    .unwrap();
550                assert_eq!(buf, "2222");
551            }
552            _ => panic!("expected SourceOutput::MultiTitle"),
553        }
554    }
555
556    #[test]
557    fn register_overrides_prior_kind() {
558        // Registering `mock` first as bytes then as frames should leave
559        // only the frames opener active (last write wins).
560        let mut reg = SourceRegistry::new();
561        reg.register_bytes("mock", open_bytes_mock);
562        reg.register_frames("mock", open_frames_mock);
563        let out = reg.open("mock://x").expect("open");
564        assert!(matches!(out, SourceOutput::Frames(_)));
565    }
566
567    #[test]
568    fn schemes_iterator_lists_registered() {
569        let mut reg = SourceRegistry::new();
570        reg.register_bytes("mockb", open_bytes_mock);
571        reg.register_packets("mockp", open_packets_mock);
572        reg.register_frames("mockf", open_frames_mock);
573        let mut names: Vec<&str> = reg.schemes().collect();
574        names.sort();
575        assert_eq!(names, vec!["mockb", "mockf", "mockp"]);
576    }
577}