Skip to main content

moq_ext_sources/
spec.rs

1//! Text specifiers that name a video or an audio source, and open it.
2//!
3//! A specifier is a kind and an optional id, such as `cam:2`, `screen`,
4//! `test:gradient` or `file:clip.mp4:loop`. The ids are the ones the device
5//! listings report, such as `moq_video::capture::cameras`. There is no
6//! backend segment: the platform picks the backend for a device.
7//!
8//! Both specifiers implement [`FromStr`] and [`Display`](fmt::Display), so a
9//! `--video` or `--audio` flag parses straight into one, and a specifier
10//! written out reads back the same. With the `serde` feature they also
11//! deserialize from, and serialize to, the same string.
12//! [`VideoSourceSpec::open`] and [`AudioSourceSpec::open`] open the source a
13//! specifier names.
14//! [`MediaSpec`] pairs a video with the audio that goes with it, which
15//! `LocalBroadcast::set_spec` in `moq-ext-publisher` opens and publishes.
16//!
17//! # Examples
18//!
19//! ```no_run
20//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
21//! use moq_ext_sources::spec::{VideoOpenOptions, VideoSourceSpec};
22//!
23//! let spec: VideoSourceSpec = "test:gradient".parse()?;
24//! let source = spec.open(&VideoOpenOptions::default()).await?;
25//! # drop(source);
26//! # Ok(())
27//! # }
28//! ```
29
30use std::{
31    fmt,
32    path::{Path, PathBuf},
33    str::FromStr,
34};
35
36#[cfg(any(feature = "capture", feature = "pattern"))]
37use crate::audio;
38use crate::{AudioSource, Error, VideoSource, video};
39
40/// An error from parsing a source specifier.
41///
42/// The message names the forms the specifier accepts.
43#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
44#[display("{_0}")]
45pub struct ParseSpecError(String);
46
47impl std::error::Error for ParseSpecError {}
48
49impl From<String> for ParseSpecError {
50    fn from(message: String) -> Self {
51        Self(message)
52    }
53}
54
55impl From<&str> for ParseSpecError {
56    fn from(message: &str) -> Self {
57        Self(message.to_string())
58    }
59}
60
61/// A parsed video source specifier.
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum VideoSourceSpec {
65    /// A camera, by the id the camera listing reports. `None` opens the default.
66    Camera(Option<String>),
67    /// A whole display. `None` opens the main one.
68    ///
69    /// On Linux, `None` and `portal` let the user pick a screen in the desktop
70    /// portal's dialog. An `x11:` id opens that X11 display, which on Wayland
71    /// shows only XWayland's windows.
72    Display(Option<String>),
73    /// A single window, by id. Supported on macOS, Windows and X11.
74    ///
75    /// On Linux, `portal` lets the user pick a window in the desktop portal's
76    /// dialog.
77    Window(String),
78    /// Every window of one application, by bundle id. macOS only.
79    App(String),
80    /// The Raspberry Pi camera, driven through `rpicam-vid`.
81    ///
82    /// A kind of its own because a Pi's `/dev/video0` is the Unicam node. It
83    /// delivers raw Bayer that only libcamera can drive.
84    #[cfg(all(target_os = "linux", feature = "rpicam"))]
85    Rpicam(RpicamMode),
86    /// A generated picture, for publishing without a camera.
87    Test(TestPattern),
88    /// An MP4 file, decoded by [`open`](Self::open) or passed through by `MediaFile`.
89    File {
90        /// Path to the file.
91        path: PathBuf,
92        /// Restart at the beginning on end of file.
93        looping: bool,
94    },
95    /// Publish no video.
96    None,
97}
98
99impl FromStr for VideoSourceSpec {
100    type Err = ParseSpecError;
101
102    /// Parses a video source specifier.
103    ///
104    /// Fails with a message naming the accepted forms if `spec` is not one of
105    /// them, or if a form that needs an identifier was given without one.
106    fn from_str(spec: &str) -> Result<Self, ParseSpecError> {
107        let (kind, rest) = split_once(spec);
108        match kind.to_lowercase().as_str() {
109            "cam" | "camera" => Ok(Self::Camera(rest.map(str::to_string))),
110            "screen" | "display" => Ok(Self::Display(rest.map(str::to_string))),
111            "window" => rest
112                .map(|id| Self::Window(id.to_string()))
113                .ok_or_else(|| "window: needs an id (e.g. window:1042)".into()),
114            "app" => rest
115                .map(|id| Self::App(id.to_string()))
116                .ok_or_else(|| "app: needs a bundle id (e.g. app:com.apple.Safari)".into()),
117            // No id, because `rpicam-vid` picks the camera.
118            "rpicam" | "picam" => match rest.map(str::to_lowercase).as_deref() {
119                None => rpicam(RpicamMode::Encoded),
120                Some("raw") => rpicam(RpicamMode::Raw),
121                Some(other) => Err(format!(
122                    "rpicam: takes no camera id, and the only suffix is \
123                     ':raw' for uncompressed pictures; got '{other}'"
124                )
125                .into()),
126            },
127            "test" => match rest.map(str::to_lowercase).as_deref() {
128                None | Some("timing") => Ok(Self::Test(TestPattern::Timing)),
129                Some("gradient") => Ok(Self::Test(TestPattern::Gradient)),
130                Some("bounce") => Ok(Self::Test(TestPattern::Bounce)),
131                Some(other) => Err(format!(
132                    "test: the patterns are 'timing' (the default), \
133                     'gradient' and 'bounce'; got '{other}'"
134                )
135                .into()),
136            },
137            "file" => {
138                let rest = rest.ok_or("file: needs a path (e.g. file:clip.mp4)")?;
139                let (path, looping) = split_loop(rest);
140                Ok(Self::File {
141                    path: PathBuf::from(path),
142                    looping,
143                })
144            }
145            "none" => Ok(Self::None),
146            other => Err(format!(
147                "unknown video source '{other}': expected cam, screen, window, app, \
148                 rpicam, rpicam:raw, file, test, or none"
149            )
150            .into()),
151        }
152    }
153}
154
155/// The generated picture `test` and `test:<name>` publish.
156#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
157#[non_exhaustive]
158pub enum TestPattern {
159    /// A sweeping bar, a frame counter, a clock, and a flashing marker.
160    ///
161    /// The marker flashes with the test tone's beep.
162    ///
163    /// Shows smoothness, dropped frames, latency, and A/V sync. See
164    /// [`VideoSource::test_pattern`].
165    #[default]
166    Timing,
167    /// A moving gradient. Cheap, and different in every frame.
168    Gradient,
169    /// A white square bouncing left and right on a background that drifts through the hues.
170    ///
171    /// See [`BouncePattern`](crate::BouncePattern).
172    Bounce,
173}
174
175/// What `rpicam-vid` hands over: `rpicam` or `rpicam:raw`.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum RpicamMode {
178    /// H.264 from the Pi's hardware encoder, published unchanged.
179    ///
180    /// The cheapest option, and the right one for a Pi Zero. There is no
181    /// preview, no choice of encoder, and no ladder.
182    Encoded,
183    /// Raw pictures, which we encode ourselves.
184    ///
185    /// Costs about 10 MB/s of pipe at 640x360, plus an encode. Allows a
186    /// preview, a choice of encoder and codec, and a ladder.
187    Raw,
188}
189
190/// Returns the `rpicam` source.
191#[cfg(all(target_os = "linux", feature = "rpicam"))]
192fn rpicam(mode: RpicamMode) -> Result<VideoSourceSpec, ParseSpecError> {
193    Ok(VideoSourceSpec::Rpicam(mode))
194}
195
196/// Fails with a message that names the missing feature.
197#[cfg(not(all(target_os = "linux", feature = "rpicam")))]
198fn rpicam(_mode: RpicamMode) -> Result<VideoSourceSpec, ParseSpecError> {
199    Err(
200        "rpicam: this build has no Raspberry Pi camera source; it needs Linux \
201         and the 'rpicam' feature"
202            .into(),
203    )
204}
205
206/// A parsed audio source specifier.
207#[derive(Debug, Clone, PartialEq, Eq)]
208#[non_exhaustive]
209pub enum AudioSourceSpec {
210    /// An input device, by the id the microphone listing reports.
211    ///
212    /// `None` opens the default microphone.
213    Microphone(Option<String>),
214    /// Everything the machine is playing. macOS only.
215    System,
216    /// A generated tone, for publishing without a microphone.
217    Test(TestTone),
218    /// An audio file, decoded and encoded like any other PCM source.
219    File {
220        /// Path to the file.
221        path: PathBuf,
222        /// Restart at the beginning on end of file.
223        looping: bool,
224    },
225    /// Publish no audio.
226    None,
227}
228
229/// The generated tone `test` and `test:<name>` publish.
230#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub enum TestTone {
232    /// A beep every second, silent in between.
233    ///
234    /// Each beep sounds while the test pattern's marker is lit, to check A/V
235    /// sync.
236    #[default]
237    Beeps,
238    /// A continuous sine tone. Dropouts are easy to hear.
239    Tone,
240}
241
242impl FromStr for AudioSourceSpec {
243    type Err = ParseSpecError;
244
245    /// Parses an audio source specifier.
246    ///
247    /// An unknown kind is a device name, such as `hw:0,1`. Fails for `file:`
248    /// without a path and for an unknown test tone.
249    fn from_str(spec: &str) -> Result<Self, ParseSpecError> {
250        let (kind, rest) = split_once(spec);
251        match kind.to_lowercase().as_str() {
252            "mic" | "microphone" | "default" => Ok(Self::Microphone(rest.map(str::to_string))),
253            "system" | "system-audio" => Ok(Self::System),
254            "test" => match rest.map(str::to_lowercase).as_deref() {
255                None | Some("beeps") => Ok(Self::Test(TestTone::Beeps)),
256                Some("tone") => Ok(Self::Test(TestTone::Tone)),
257                Some(other) => Err(format!(
258                    "test: the tones are 'beeps' (the default) and 'tone'; \
259                     got '{other}'"
260                )
261                .into()),
262            },
263            "none" => Ok(Self::None),
264            "file" => {
265                let rest = rest.ok_or("file: needs a path (e.g. file:music.mp3)")?;
266                let (path, looping) = split_loop(rest);
267                Ok(Self::File {
268                    path: PathBuf::from(path),
269                    looping,
270                })
271            }
272            _ => Ok(Self::Microphone(Some(spec.to_string()))),
273        }
274    }
275}
276
277impl fmt::Display for VideoSourceSpec {
278    /// Writes the specifier in the form [`FromStr`] reads.
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        match self {
281            Self::Camera(id) => with_id(f, "cam", id.as_deref()),
282            Self::Display(id) => with_id(f, "screen", id.as_deref()),
283            Self::Window(id) => with_id(f, "window", Some(id)),
284            Self::App(id) => with_id(f, "app", Some(id)),
285            #[cfg(all(target_os = "linux", feature = "rpicam"))]
286            Self::Rpicam(RpicamMode::Encoded) => f.write_str("rpicam"),
287            #[cfg(all(target_os = "linux", feature = "rpicam"))]
288            Self::Rpicam(RpicamMode::Raw) => f.write_str("rpicam:raw"),
289            Self::Test(TestPattern::Timing) => f.write_str("test"),
290            Self::Test(TestPattern::Gradient) => f.write_str("test:gradient"),
291            Self::Test(TestPattern::Bounce) => f.write_str("test:bounce"),
292            Self::File { path, looping } => file(f, path, *looping),
293            Self::None => f.write_str("none"),
294        }
295    }
296}
297
298impl fmt::Display for AudioSourceSpec {
299    /// Writes the specifier in the form [`FromStr`] reads.
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        match self {
302            Self::Microphone(id) => with_id(f, "mic", id.as_deref()),
303            Self::System => f.write_str("system"),
304            Self::Test(TestTone::Beeps) => f.write_str("test"),
305            Self::Test(TestTone::Tone) => f.write_str("test:tone"),
306            Self::File { path, looping } => file(f, path, *looping),
307            Self::None => f.write_str("none"),
308        }
309    }
310}
311
312/// Implements serde for a specifier as the string it parses from and displays as.
313#[cfg(feature = "serde")]
314macro_rules! serde_as_string {
315    ($spec:ty) => {
316        impl<'de> serde::Deserialize<'de> for $spec {
317            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
318                String::deserialize(deserializer)?
319                    .parse()
320                    .map_err(serde::de::Error::custom)
321            }
322        }
323
324        impl serde::Serialize for $spec {
325            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
326                serializer.collect_str(self)
327            }
328        }
329    };
330}
331
332#[cfg(feature = "serde")]
333serde_as_string!(VideoSourceSpec);
334#[cfg(feature = "serde")]
335serde_as_string!(AudioSourceSpec);
336
337/// Writes `kind`, then `:id` if there is an id.
338fn with_id(f: &mut fmt::Formatter<'_>, kind: &str, id: Option<&str>) -> fmt::Result {
339    match id {
340        Some(id) => write!(f, "{kind}:{id}"),
341        None => f.write_str(kind),
342    }
343}
344
345/// Writes a `file:` specifier, with the `:loop` suffix if it loops.
346fn file(f: &mut fmt::Formatter<'_>, path: &Path, looping: bool) -> fmt::Result {
347    write!(f, "file:{}", path.display())?;
348    if looping {
349        f.write_str(":loop")?;
350    }
351    Ok(())
352}
353
354/// Splits the `:loop` suffix off a file path, if it carries one.
355fn split_loop(rest: &str) -> (&str, bool) {
356    if rest.to_lowercase().ends_with(":loop") {
357        (&rest[..rest.len() - ":loop".len()], true)
358    } else {
359        (rest, false)
360    }
361}
362
363/// Splits a specifier into its kind and the identifier that follows.
364///
365/// Only the first colon separates, because ids and paths such as `hw:0,1` and
366/// `C:\clips\demo.mp4` contain their own.
367fn split_once(spec: &str) -> (&str, Option<&str>) {
368    match spec.split_once(':') {
369        Some((kind, rest)) => (kind, Some(rest)),
370        None => (spec, None),
371    }
372}
373
374/// The id of `screen:portal` and `window:portal`.
375///
376/// Either lets the user pick in the desktop portal's screen-sharing dialog.
377pub const PORTAL: &str = "portal";
378
379/// The size of a test pattern without [`VideoOpenOptions::with_size`].
380const TEST_SIZE: video::Size = video::Size {
381    width: 1280,
382    height: 720,
383};
384
385/// The capture size of the Raspberry Pi camera without [`VideoOpenOptions::with_size`].
386#[cfg(all(target_os = "linux", feature = "rpicam"))]
387const RPICAM_SIZE: video::Size = video::Size {
388    width: 640,
389    height: 360,
390};
391
392/// The frame rate of a generated source without [`VideoOpenOptions::framerate`].
393const GENERATED_FPS: u32 = 30;
394
395/// The frequency of the continuous test tone, in hertz.
396///
397/// Concert A, low enough that no resampler can alias it.
398#[cfg(feature = "pattern")]
399const TEST_TONE_HZ: f32 = 440.0;
400
401/// The channel layout of the test tones.
402#[cfg(feature = "pattern")]
403const TEST_TONE_LAYOUT: audio::Layout = audio::Layout::Stereo;
404
405/// A video source and the audio that goes with it, which a broadcast publishes together.
406///
407/// `LocalBroadcast::set_spec` in `moq-ext-publisher` opens and publishes
408/// one. A `file:` video brings its own audio unless [`audio`](Self::audio)
409/// names another source, and goes out as it is stored unless
410/// [`reencode`](Self::reencode) is set.
411///
412/// # Examples
413///
414/// ```
415/// use moq_ext_sources::spec::{AudioSourceSpec, MediaSpec, TestTone};
416///
417/// # fn main() -> Result<(), moq_ext_sources::spec::ParseSpecError> {
418/// let spec =
419///     MediaSpec::new("test:bounce".parse()?).with_audio(AudioSourceSpec::Test(TestTone::Beeps));
420/// let file = MediaSpec::new("file:clip.mp4:loop".parse()?);
421/// assert!(file.audio.is_none());
422/// # drop(spec);
423/// # Ok(())
424/// # }
425/// ```
426#[derive(Debug, Clone, PartialEq, Eq)]
427#[non_exhaustive]
428pub struct MediaSpec {
429    /// The video source. [`VideoSourceSpec::None`] stops the video.
430    pub video: VideoSourceSpec,
431    /// The audio source, or `None` to leave the audio to the video.
432    ///
433    /// With `None`, a `file:` video publishes the file's own audio, or none
434    /// if the file has none, and any other video leaves the current audio
435    /// alone. [`AudioSourceSpec::None`] stops the audio.
436    pub audio: Option<AudioSourceSpec>,
437    /// Whether a `file:` video and its own audio are decoded and encoded again.
438    ///
439    /// Off by default: the file's H.264 and AAC go out as they are stored,
440    /// at no CPU cost but in one rendition at the file's size, bitrate and
441    /// keyframe interval.
442    pub reencode: bool,
443}
444
445impl MediaSpec {
446    /// Creates a spec of `video`, leaving the audio to the video.
447    #[must_use]
448    pub fn new(video: VideoSourceSpec) -> Self {
449        Self {
450            video,
451            audio: None,
452            reencode: false,
453        }
454    }
455
456    /// Returns the timing test pattern with the beeps that mark it, which needs no device.
457    ///
458    /// The same as `test` for the video and the audio specifier.
459    #[cfg(feature = "pattern")]
460    #[must_use]
461    pub fn test() -> Self {
462        Self::new(VideoSourceSpec::Test(TestPattern::Timing))
463            .with_audio(AudioSourceSpec::Test(TestTone::Beeps))
464    }
465
466    /// Returns the default camera with the default microphone.
467    ///
468    /// The same as `cam` for the video and `mic` for the audio specifier.
469    #[cfg(feature = "capture")]
470    #[must_use]
471    pub fn camera() -> Self {
472        Self::new(VideoSourceSpec::Camera(None)).with_audio(AudioSourceSpec::Microphone(None))
473    }
474
475    /// Returns the main display, and leaves the audio as it is.
476    ///
477    /// The same as `screen` for the video specifier. It opens what
478    /// [`screen_source`](crate::screen_source) names: in a Wayland session
479    /// with the `pipewire` feature, the desktop portal's dialog, where the
480    /// user picks a screen.
481    #[cfg(feature = "capture")]
482    #[must_use]
483    pub fn screen() -> Self {
484        Self::new(VideoSourceSpec::Display(None))
485    }
486
487    /// Returns this spec with `audio` as the audio source.
488    #[must_use]
489    pub fn with_audio(mut self, audio: AudioSourceSpec) -> Self {
490        self.audio = Some(audio);
491        self
492    }
493
494    /// Returns this spec with `reencode` as whether a `file:` video and its own audio are decoded and encoded again.
495    #[must_use]
496    pub fn with_reencode(mut self, reencode: bool) -> Self {
497        self.reencode = reencode;
498        self
499    }
500}
501
502impl From<VideoSourceSpec> for MediaSpec {
503    fn from(video: VideoSourceSpec) -> Self {
504        Self::new(video)
505    }
506}
507
508/// How [`VideoSourceSpec::open`] opens a source.
509///
510/// Every field is a hint. A device that cannot honor one picks the closest
511/// mode it has.
512#[derive(Debug, Clone, PartialEq, Eq)]
513#[non_exhaustive]
514pub struct VideoOpenOptions {
515    /// The picture width to ask a device or a generator for.
516    pub width: Option<u32>,
517    /// The picture height to ask a device or a generator for.
518    pub height: Option<u32>,
519    /// The frame rate to ask for.
520    ///
521    /// A device picks its own without it, and a generator runs at 30 fps.
522    pub framerate: Option<video::FrameRate>,
523    /// Whether a screen or window capture draws the mouse cursor, `true` by default.
524    pub cursor: bool,
525    /// The app whose config directory keeps the desktop portal's grants.
526    portal_grants: Option<String>,
527    /// Whether the grants stay stored when the stream ends.
528    portal_grants_kept_after_end: bool,
529    /// An open file that a `file:` source of its path plays instead of opening it again.
530    #[cfg(feature = "file")]
531    file: Option<HeldFile>,
532}
533
534/// The file [`VideoOpenOptions::with_file`] holds, equal to the clones of the same open file.
535#[cfg(feature = "file")]
536#[derive(Debug, Clone)]
537struct HeldFile(crate::MediaFile);
538
539#[cfg(feature = "file")]
540impl PartialEq for HeldFile {
541    fn eq(&self, other: &Self) -> bool {
542        self.0.is_clone_of(&other.0)
543    }
544}
545
546#[cfg(feature = "file")]
547impl Eq for HeldFile {}
548
549impl Default for VideoOpenOptions {
550    fn default() -> Self {
551        Self {
552            width: None,
553            height: None,
554            framerate: None,
555            cursor: true,
556            portal_grants: None,
557            portal_grants_kept_after_end: false,
558            #[cfg(feature = "file")]
559            file: None,
560        }
561    }
562}
563
564impl VideoOpenOptions {
565    /// Asks for pictures of `size`.
566    #[must_use]
567    pub fn with_size(mut self, size: video::Size) -> Self {
568        self.width = Some(size.width);
569        self.height = Some(size.height);
570        self
571    }
572
573    /// Asks for `rate` frames per second.
574    #[must_use]
575    pub fn with_framerate(mut self, rate: video::FrameRate) -> Self {
576        self.framerate = Some(rate);
577        self
578    }
579
580    /// Keeps the desktop portal's grants in `app`'s config directory.
581    ///
582    /// Sources opened through the portal (`screen:portal`, `window:portal`,
583    /// or the default display on Wayland) reuse and store their grant as
584    /// `PortalGrant::in_config_dir` does, so a later run can skip the picker.
585    /// Has no effect without a portal, or when `app` is not a single file
586    /// name.
587    #[must_use]
588    pub fn with_portal_grants(mut self, app: impl Into<String>) -> Self {
589        self.portal_grants = Some(app.into());
590        self
591    }
592
593    /// Keeps the grants [`with_portal_grants`](Self::with_portal_grants)
594    /// stores when the stream ends, as `PortalGrant::keep_after_end` does.
595    #[must_use]
596    pub fn keep_portal_grants_after_end(mut self) -> Self {
597        self.portal_grants_kept_after_end = true;
598        self
599    }
600
601    /// Plays `file` for a `file:` source of its path, instead of opening the path again.
602    ///
603    /// Applies to audio sources too: `LocalBroadcast::set_spec` opens a
604    /// `file:` audio source through these options. Clones of a
605    /// [`MediaFile`](crate::MediaFile) share its clock, so a video that opens
606    /// again, or an audio source of the same file, plays in sync with the
607    /// streams the file already feeds.
608    #[cfg(feature = "file")]
609    #[must_use]
610    pub fn with_file(mut self, file: crate::MediaFile) -> Self {
611        self.file = Some(HeldFile(file));
612        self
613    }
614
615    /// Returns the file at `path` with `end`: the one [`with_file`](Self::with_file) holds, or newly opened.
616    ///
617    /// # Errors
618    ///
619    /// Fails with [`Error::Device`] if the file is not the one the options
620    /// hold and does not open, as [`MediaFile::open`](crate::MediaFile::open)
621    /// does.
622    // Shared with moq-ext-publisher, not public API.
623    #[doc(hidden)]
624    #[cfg(feature = "file")]
625    pub async fn open_file(
626        &self,
627        path: &Path,
628        end: crate::FileEnd,
629    ) -> Result<crate::MediaFile, Error> {
630        let file = match &self.file {
631            Some(HeldFile(file)) if file.path() == path => file.clone(),
632            _ => crate::MediaFile::open(path).await?,
633        };
634        Ok(file.with_end(end))
635    }
636
637    /// Returns the size these options ask for, filling in from `default`.
638    fn size_or(&self, default: video::Size) -> video::Size {
639        video::Size::new(
640            self.width.unwrap_or(default.width),
641            self.height.unwrap_or(default.height),
642        )
643    }
644
645    /// Returns the rate of a generated source.
646    fn generated_rate(&self) -> video::FrameRate {
647        self.framerate.unwrap_or_else(|| {
648            video::FrameRate::new(GENERATED_FPS, 1).expect("30 fps is a valid rate")
649        })
650    }
651}
652
653impl VideoSourceSpec {
654    /// Opens the source this specifier names, or returns `None` for [`None`](Self::None).
655    ///
656    /// A camera, display, window or app opens through
657    /// [`VideoSource::capture`], so the default camera follows its rules. The
658    /// default display is [`screen_source`](crate::screen_source), the
659    /// desktop portal on Wayland with the `pipewire` feature. The portal asks
660    /// on each open unless [`VideoOpenOptions::with_portal_grants`] keeps its
661    /// grants. A test pattern defaults to 1280x720 at 30 fps.
662    ///
663    /// Cancellation safe, as [`VideoSource::capture`] is.
664    ///
665    /// # Errors
666    ///
667    /// Fails with [`Error::InvalidConfig`] for a source this build cannot
668    /// open, such as a camera without the `capture` feature or the portal off
669    /// Linux, or a file without the `file` feature. Also fails for
670    /// [`RpicamMode::Encoded`], which carries encoded video and has no raw
671    /// source: read `rpicam_h264` instead. Fails with [`Error::Device`] if the
672    /// device or the file does not open.
673    ///
674    /// A file decodes through [`MediaFile::video`](crate::MediaFile::video),
675    /// at its own size and rate, which the options do not change. It plays
676    /// the file [`VideoOpenOptions::with_file`] holds if the paths match.
677    pub async fn open(&self, options: &VideoOpenOptions) -> Result<Option<VideoSource>, Error> {
678        let source = match self {
679            Self::None => return Ok(None),
680            Self::Test(pattern) => test_pattern(*pattern, options)?,
681            #[cfg(feature = "file")]
682            Self::File { path, looping } => {
683                let file = options.open_file(path, crate::FileEnd::looping(*looping));
684                return file.await?.video(Default::default()).await.map(Some);
685            }
686            #[cfg(not(feature = "file"))]
687            Self::File { path, .. } => {
688                return Err(Error::invalid(format!(
689                    "this build cannot decode {}; it needs the `file` feature",
690                    path.display()
691                )));
692            }
693            #[cfg(all(target_os = "linux", feature = "rpicam"))]
694            Self::Rpicam(RpicamMode::Raw) => {
695                let rate = options.generated_rate().rounded().max(1);
696                let config = crate::RpicamConfig::new(options.size_or(RPICAM_SIZE), rate);
697                VideoSource::rpicam(config).await?
698            }
699            #[cfg(all(target_os = "linux", feature = "rpicam"))]
700            Self::Rpicam(RpicamMode::Encoded) => {
701                return Err(Error::invalid(
702                    "rpicam delivers H.264 that rpicam-vid encoded; read it with \
703                     rpicam_h264, or use rpicam:raw for raw pictures",
704                ));
705            }
706            Self::Camera(_) | Self::Display(_) | Self::Window(_) | Self::App(_) => {
707                return capture(self.capture_source()?, options).await.map(Some);
708            }
709        };
710        Ok(Some(source))
711    }
712
713    /// Returns the capture source of a camera, display, window or app specifier.
714    fn capture_source(&self) -> Result<CaptureSource, Error> {
715        Ok(match self {
716            Self::Camera(id) => CaptureSource::Camera(id.clone()),
717            Self::Display(Some(id)) if id == PORTAL => CaptureSource::Portal(PortalKind::Screen),
718            Self::Display(id) => CaptureSource::Display(id.clone()),
719            Self::Window(id) if id == PORTAL => CaptureSource::Portal(PortalKind::Window),
720            Self::Window(id) => CaptureSource::Window(id.clone()),
721            Self::App(id) => CaptureSource::App(id.clone()),
722            other => return Err(Error::invalid(format!("{other} is no capture device"))),
723        })
724    }
725}
726
727/// A capture device a specifier names, before the build's capture types.
728#[derive(Debug)]
729#[cfg_attr(
730    not(feature = "capture"),
731    expect(dead_code, reason = "only read by the capture build")
732)]
733enum CaptureSource {
734    Camera(Option<String>),
735    Display(Option<String>),
736    Window(String),
737    App(String),
738    Portal(PortalKind),
739}
740
741/// What the desktop portal's picker offers.
742#[derive(Debug, Clone, Copy)]
743enum PortalKind {
744    Screen,
745    Window,
746}
747
748/// Opens `source` through [`VideoSource::capture`] with the hints in `options`.
749#[cfg(feature = "capture")]
750async fn capture(source: CaptureSource, options: &VideoOpenOptions) -> Result<VideoSource, Error> {
751    use video::capture::{DisplaySelection, Source};
752    let source = match source {
753        CaptureSource::Camera(id) => Source::Camera(id),
754        CaptureSource::Display(None) => screen(options),
755        CaptureSource::Display(Some(id)) => Source::Display(DisplaySelection::new(id)),
756        CaptureSource::Window(id) => Source::Window(id),
757        CaptureSource::App(id) => Source::App(id),
758        CaptureSource::Portal(kind) => portal(kind, options)?,
759    };
760    let mut config = video::capture::Config::default();
761    config.source = source;
762    config.width = options.width;
763    config.height = options.height;
764    config.framerate = options.framerate;
765    config.cursor = if options.cursor {
766        video::capture::Cursor::Drawn
767    } else {
768        video::capture::Cursor::Hidden
769    };
770    VideoSource::capture(config).await
771}
772
773/// Fails, since this build has no capture.
774#[cfg(not(feature = "capture"))]
775#[expect(clippy::unused_async, reason = "the capture build awaits")]
776async fn capture(source: CaptureSource, _options: &VideoOpenOptions) -> Result<VideoSource, Error> {
777    Err(Error::invalid(format!(
778        "opening {source:?} needs a build with the `capture` feature"
779    )))
780}
781
782/// Returns the capture source of the default display, keeping its portal grant as `options` ask.
783#[cfg(feature = "capture")]
784fn screen(options: &VideoOpenOptions) -> video::capture::Source {
785    let source = crate::screen_source();
786    #[cfg(all(target_os = "linux", feature = "pipewire"))]
787    if matches!(source, video::capture::Source::Portal(_)) {
788        return portal_selection(PortalKind::Screen, options);
789    }
790    #[cfg(not(all(target_os = "linux", feature = "pipewire")))]
791    let _ = options;
792    source
793}
794
795/// Returns the portal source for `kind`, a selection the user picks in the dialog.
796#[cfg(all(feature = "capture", target_os = "linux", feature = "pipewire"))]
797#[expect(
798    clippy::unnecessary_wraps,
799    reason = "the build without a portal fails here"
800)]
801fn portal(kind: PortalKind, options: &VideoOpenOptions) -> Result<video::capture::Source, Error> {
802    Ok(portal_selection(kind, options))
803}
804
805/// Returns a portal selection for `kind`, seeded from the grant `options` keep.
806#[cfg(all(feature = "capture", target_os = "linux", feature = "pipewire"))]
807fn portal_selection(kind: PortalKind, options: &VideoOpenOptions) -> video::capture::Source {
808    use video::capture::portal::{Kind, Selection};
809    let kind = match kind {
810        PortalKind::Screen => Kind::Screen,
811        PortalKind::Window => Kind::Window,
812    };
813    let grant = options
814        .portal_grants
815        .as_deref()
816        .and_then(|app| crate::PortalGrant::in_config_dir(kind, app))
817        .map(|grant| {
818            if options.portal_grants_kept_after_end {
819                grant.keep_after_end()
820            } else {
821                grant
822            }
823        });
824    let selection = match grant {
825        Some(grant) => grant.selection(),
826        None => Selection::new(kind),
827    };
828    video::capture::Source::Portal(selection)
829}
830
831/// Fails, since only Linux with the `pipewire` feature has the portal.
832#[cfg(all(
833    feature = "capture",
834    not(all(target_os = "linux", feature = "pipewire"))
835))]
836fn portal(kind: PortalKind, _options: &VideoOpenOptions) -> Result<video::capture::Source, Error> {
837    Err(Error::invalid(format!(
838        "the desktop portal's {kind:?} picker needs a Linux build with the `pipewire` feature"
839    )))
840}
841
842/// Starts the test pattern `pattern` names, at the size and rate in `options`.
843#[cfg(feature = "pattern")]
844fn test_pattern(pattern: TestPattern, options: &VideoOpenOptions) -> Result<VideoSource, Error> {
845    let size = options.size_or(TEST_SIZE);
846    let rate = options.generated_rate();
847    match pattern {
848        TestPattern::Timing => VideoSource::test_pattern(size, rate),
849        TestPattern::Gradient => VideoSource::test_gradient(size, rate),
850        TestPattern::Bounce => VideoSource::test_bounce(size, rate),
851    }
852}
853
854/// Fails, since this build has no generated pictures.
855#[cfg(not(feature = "pattern"))]
856fn test_pattern(_pattern: TestPattern, options: &VideoOpenOptions) -> Result<VideoSource, Error> {
857    let _ = (options.size_or(TEST_SIZE), options.generated_rate());
858    Err(Error::invalid(
859        "a test pattern needs a build with the `pattern` feature",
860    ))
861}
862
863impl AudioSourceSpec {
864    /// Opens the source this specifier names, or returns `None` for [`None`](Self::None).
865    ///
866    /// A microphone opens with the default capture config and no echo
867    /// cancellation. Build the config yourself and call
868    /// [`AudioSource::microphone`] to attach a canceller. The test tones are
869    /// stereo.
870    ///
871    /// Cancellation safe.
872    ///
873    /// # Errors
874    ///
875    /// Fails with [`Error::InvalidConfig`] for a source this build cannot
876    /// open, such as a microphone without the `capture` feature or a file
877    /// without the `file` feature, and with [`Error::Device`] if the device
878    /// or the file does not open.
879    pub async fn open(&self) -> Result<Option<AudioSource>, Error> {
880        match self {
881            Self::None => Ok(None),
882            spec => open_audio(spec).await.map(Some),
883        }
884    }
885}
886
887/// Opens the audio source `spec` names, which is not [`AudioSourceSpec::None`].
888#[cfg_attr(
889    not(any(feature = "capture", feature = "file")),
890    expect(clippy::unused_async, reason = "only devices and files await")
891)]
892async fn open_audio(spec: &AudioSourceSpec) -> Result<AudioSource, Error> {
893    match spec {
894        #[cfg(feature = "capture")]
895        AudioSourceSpec::Microphone(id) => {
896            let mut config = audio::capture::Config::default();
897            if let Some(id) = id {
898                config.source = audio::capture::Source::Microphone(Some(id.clone()));
899            }
900            AudioSource::microphone(config).await
901        }
902        #[cfg(feature = "capture")]
903        AudioSourceSpec::System => {
904            let mut config = audio::capture::Config::default();
905            config.source = audio::capture::Source::System;
906            AudioSource::microphone(config).await
907        }
908        #[cfg(feature = "pattern")]
909        AudioSourceSpec::Test(TestTone::Beeps) => AudioSource::test_pattern(TEST_TONE_LAYOUT),
910        #[cfg(feature = "pattern")]
911        AudioSourceSpec::Test(TestTone::Tone) => AudioSource::tone(TEST_TONE_HZ, TEST_TONE_LAYOUT),
912        #[cfg(feature = "file")]
913        AudioSourceSpec::File { path, looping } => {
914            AudioSource::file(path, crate::FileEnd::looping(*looping)).await
915        }
916        #[allow(
917            unreachable_patterns,
918            reason = "reached only in a build without one of the features"
919        )]
920        other => Err(Error::invalid(format!(
921            "this build cannot open the audio source {other}; it needs the \
922             `capture`, `pattern` or `file` feature"
923        ))),
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930
931    /// A test pattern opens at the default size, or at the size the options ask for.
932    #[cfg(feature = "pattern")]
933    #[tokio::test]
934    async fn a_test_pattern_opens_at_the_size_asked_for() {
935        let spec: VideoSourceSpec = "test:gradient".parse().unwrap();
936        let source = spec
937            .open(&VideoOpenOptions::default())
938            .await
939            .unwrap()
940            .expect("a source");
941        assert_eq!(source.format().size, TEST_SIZE);
942        let options = VideoOpenOptions {
943            width: Some(320),
944            height: Some(240),
945            ..Default::default()
946        };
947        let source = spec.open(&options).await.unwrap().expect("a source");
948        assert_eq!(source.format().size, video::Size::new(320, 240));
949    }
950
951    /// `test:bounce` runs as a clocked source of I420 pictures at the size asked for.
952    #[cfg(feature = "pattern")]
953    #[tokio::test]
954    async fn the_bounce_pattern_runs_as_a_source() {
955        let spec: VideoSourceSpec = "test:bounce".parse().unwrap();
956        let options = VideoOpenOptions {
957            width: Some(320),
958            height: Some(180),
959            ..Default::default()
960        };
961        let source = spec.open(&options).await.unwrap().expect("a source");
962        let frame = source.frames().next().await.expect("a frame");
963        let video::Surface::I420(image) = &frame.surface else {
964            panic!("not I420");
965        };
966        assert_eq!(image.size(), video::Size::new(320, 180));
967    }
968
969    /// `none` opens nothing.
970    #[tokio::test]
971    async fn none_opens_nothing() {
972        let options = VideoOpenOptions::default();
973        assert!(
974            VideoSourceSpec::None
975                .open(&options)
976                .await
977                .unwrap()
978                .is_none()
979        );
980        assert!(AudioSourceSpec::None.open().await.unwrap().is_none());
981    }
982
983    /// A `file:` video decodes at the file's size.
984    #[cfg(feature = "file")]
985    #[tokio::test]
986    async fn a_file_video_decodes() {
987        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/source/test_data/clip.mp4");
988        let spec: VideoSourceSpec = format!("file:{path}").parse().unwrap();
989        let source = spec.open(&Default::default()).await.unwrap().unwrap();
990        assert_eq!(source.format().size, video::Size::new(64, 48));
991    }
992
993    /// The test tones open in every build with generated sources.
994    #[cfg(feature = "pattern")]
995    #[tokio::test]
996    async fn the_test_tones_open() {
997        for spec in ["test", "test:tone"] {
998            let spec: AudioSourceSpec = spec.parse().unwrap();
999            assert!(spec.open().await.unwrap().is_some(), "{spec}");
1000        }
1001    }
1002
1003    /// The test preset is `test` for both the video and the audio.
1004    #[cfg(feature = "pattern")]
1005    #[test]
1006    fn the_test_preset_is_the_test_specifiers() {
1007        let spec = MediaSpec::test();
1008        assert_eq!(spec.video, "test".parse().unwrap());
1009        assert_eq!(spec.audio, Some("test".parse().unwrap()));
1010        assert!(!spec.reencode);
1011    }
1012
1013    /// The camera preset adds the microphone, and the screen preset keeps the audio.
1014    #[cfg(feature = "capture")]
1015    #[test]
1016    fn the_device_presets_are_their_specifiers() {
1017        let camera = MediaSpec::camera();
1018        assert_eq!(camera.video, "cam".parse().unwrap());
1019        assert_eq!(camera.audio, Some("mic".parse().unwrap()));
1020        let screen = MediaSpec::screen();
1021        assert_eq!(screen.video, "screen".parse().unwrap());
1022        assert_eq!(screen.audio, None);
1023    }
1024
1025    #[test]
1026    fn video_specifiers_parse_to_their_kinds() {
1027        assert_eq!(
1028            "cam".parse::<VideoSourceSpec>().unwrap(),
1029            VideoSourceSpec::Camera(None)
1030        );
1031        assert_eq!(
1032            "screen".parse::<VideoSourceSpec>().unwrap(),
1033            VideoSourceSpec::Display(None)
1034        );
1035        assert_eq!(
1036            "test".parse::<VideoSourceSpec>().unwrap(),
1037            VideoSourceSpec::Test(TestPattern::Timing)
1038        );
1039        assert_eq!(
1040            "none".parse::<VideoSourceSpec>().unwrap(),
1041            VideoSourceSpec::None
1042        );
1043    }
1044
1045    /// The bare specifier is the timing pattern, and the gradient has a name.
1046    #[test]
1047    fn test_patterns_by_name() {
1048        assert_eq!(
1049            "test:timing".parse::<VideoSourceSpec>().unwrap(),
1050            VideoSourceSpec::Test(TestPattern::Timing)
1051        );
1052        assert_eq!(
1053            "test:GRADIENT".parse::<VideoSourceSpec>().unwrap(),
1054            VideoSourceSpec::Test(TestPattern::Gradient)
1055        );
1056        assert_eq!(
1057            "test:bounce".parse::<VideoSourceSpec>().unwrap(),
1058            VideoSourceSpec::Test(TestPattern::Bounce)
1059        );
1060        let err = "test:bars".parse::<VideoSourceSpec>().unwrap_err();
1061        assert!(err.to_string().contains("timing"), "{err}");
1062    }
1063
1064    #[test]
1065    fn test_tones_by_name() {
1066        assert_eq!(
1067            "test:beeps".parse::<AudioSourceSpec>().unwrap(),
1068            AudioSourceSpec::Test(TestTone::Beeps)
1069        );
1070        assert_eq!(
1071            "test:tone".parse::<AudioSourceSpec>().unwrap(),
1072            AudioSourceSpec::Test(TestTone::Tone)
1073        );
1074        let err = "test:sine".parse::<AudioSourceSpec>().unwrap_err();
1075        assert!(err.to_string().contains("beeps"), "{err}");
1076    }
1077
1078    #[test]
1079    fn video_device_ids_survive_colons() {
1080        assert_eq!(
1081            "cam:/dev/video2".parse::<VideoSourceSpec>().unwrap(),
1082            VideoSourceSpec::Camera(Some("/dev/video2".into()))
1083        );
1084        assert_eq!(
1085            "file:C:/clips/demo.mp4".parse::<VideoSourceSpec>().unwrap(),
1086            VideoSourceSpec::File {
1087                path: "C:/clips/demo.mp4".into(),
1088                looping: false,
1089            }
1090        );
1091    }
1092
1093    #[test]
1094    #[cfg(all(target_os = "linux", feature = "rpicam"))]
1095    fn rpicam_specifiers_parse_with_and_without_raw() {
1096        assert_eq!(
1097            "rpicam".parse::<VideoSourceSpec>().unwrap(),
1098            VideoSourceSpec::Rpicam(RpicamMode::Encoded)
1099        );
1100        assert_eq!(
1101            "picam".parse::<VideoSourceSpec>().unwrap(),
1102            VideoSourceSpec::Rpicam(RpicamMode::Encoded)
1103        );
1104        assert!("rpicam:0".parse::<VideoSourceSpec>().is_err());
1105    }
1106
1107    /// `:raw` asks for pictures instead of the hardware encoder's H.264.
1108    #[test]
1109    #[cfg(all(target_os = "linux", feature = "rpicam"))]
1110    fn rpicam_raw_is_a_mode_of_rpicam() {
1111        assert_eq!(
1112            "rpicam:raw".parse::<VideoSourceSpec>().unwrap(),
1113            VideoSourceSpec::Rpicam(RpicamMode::Raw)
1114        );
1115        assert_eq!(
1116            "picam:RAW".parse::<VideoSourceSpec>().unwrap(),
1117            VideoSourceSpec::Rpicam(RpicamMode::Raw)
1118        );
1119        let err = "rpicam:yuv".parse::<VideoSourceSpec>().unwrap_err();
1120        assert!(err.to_string().contains(":raw"), "{err}");
1121    }
1122
1123    /// A build without the source names the missing feature.
1124    #[test]
1125    #[cfg(not(all(target_os = "linux", feature = "rpicam")))]
1126    fn rpicam_is_refused_without_the_feature() {
1127        let err = "rpicam".parse::<VideoSourceSpec>().unwrap_err();
1128        assert!(err.to_string().contains("'rpicam' feature"), "{err}");
1129    }
1130
1131    #[test]
1132    fn forms_that_need_an_id_are_refused_without_one() {
1133        assert!("window".parse::<VideoSourceSpec>().is_err());
1134        assert!("app".parse::<VideoSourceSpec>().is_err());
1135        assert!("file".parse::<VideoSourceSpec>().is_err());
1136        assert!("webcam".parse::<VideoSourceSpec>().is_err());
1137    }
1138
1139    #[test]
1140    fn a_video_file_takes_a_loop_suffix() {
1141        assert_eq!(
1142            "file:/tmp/clip.mp4:loop"
1143                .parse::<VideoSourceSpec>()
1144                .unwrap(),
1145            VideoSourceSpec::File {
1146                path: "/tmp/clip.mp4".into(),
1147                looping: true,
1148            }
1149        );
1150    }
1151
1152    #[test]
1153    fn specifiers_display_in_the_form_they_parse_from() {
1154        for spec in [
1155            "cam",
1156            "cam:/dev/video2",
1157            "screen:1",
1158            "screen:portal",
1159            "screen:x11:0",
1160            "window:1042",
1161            "window:portal",
1162            "app:com.apple.Safari",
1163            "test",
1164            "test:gradient",
1165            "test:bounce",
1166            "file:C:/clips/demo.mp4:loop",
1167            "none",
1168        ] {
1169            let parsed: VideoSourceSpec = spec.parse().expect(spec);
1170            assert_eq!(parsed.to_string(), spec);
1171            assert_eq!(parsed.to_string().parse(), Ok(parsed));
1172        }
1173        for spec in [
1174            "mic",
1175            "mic:hw:0,1",
1176            "system",
1177            "test",
1178            "test:tone",
1179            "file:a.mp3",
1180            "none",
1181        ] {
1182            let parsed: AudioSourceSpec = spec.parse().expect(spec);
1183            assert_eq!(parsed.to_string(), spec);
1184        }
1185        let device: AudioSourceSpec = "hw:0,1".parse().expect("a device name");
1186        assert_eq!(device.to_string().parse(), Ok(device));
1187    }
1188
1189    #[test]
1190    fn audio_specifiers_parse_to_their_kinds() {
1191        assert_eq!(
1192            "mic".parse::<AudioSourceSpec>().unwrap(),
1193            AudioSourceSpec::Microphone(None)
1194        );
1195        assert_eq!(
1196            "test".parse::<AudioSourceSpec>().unwrap(),
1197            AudioSourceSpec::Test(TestTone::Beeps)
1198        );
1199        assert_eq!(
1200            "none".parse::<AudioSourceSpec>().unwrap(),
1201            AudioSourceSpec::None
1202        );
1203        assert_eq!(
1204            "system".parse::<AudioSourceSpec>().unwrap(),
1205            AudioSourceSpec::System
1206        );
1207    }
1208
1209    #[test]
1210    fn an_unknown_audio_specifier_is_a_device_name() {
1211        assert_eq!(
1212            "hw:0,1".parse::<AudioSourceSpec>().unwrap(),
1213            AudioSourceSpec::Microphone(Some("hw:0,1".into()))
1214        );
1215    }
1216
1217    #[test]
1218    fn an_audio_file_takes_a_loop_suffix() {
1219        assert_eq!(
1220            "file:/tmp/song.flac:loop"
1221                .parse::<AudioSourceSpec>()
1222                .unwrap(),
1223            AudioSourceSpec::File {
1224                path: "/tmp/song.flac".into(),
1225                looping: true,
1226            }
1227        );
1228        assert_eq!(
1229            "file:music.mp3".parse::<AudioSourceSpec>().unwrap(),
1230            AudioSourceSpec::File {
1231                path: "music.mp3".into(),
1232                looping: false,
1233            }
1234        );
1235    }
1236
1237    /// The options play the file they hold for its path, and open any other path anew.
1238    #[cfg(feature = "file")]
1239    #[tokio::test]
1240    async fn options_play_the_file_they_hold() {
1241        let data = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/source/test_data");
1242        let clip = data.join("clip.mp4");
1243        let held = crate::MediaFile::open(&clip).await.expect("the clip opens");
1244        let options = VideoOpenOptions::default().with_file(held.clone());
1245        let again = options
1246            .open_file(&clip, crate::FileEnd::Restart)
1247            .await
1248            .expect("the held file");
1249        assert!(
1250            again.is_clone_of(&held.with_end(crate::FileEnd::Restart)),
1251            "the held file was opened again"
1252        );
1253        let other = options
1254            .open_file(&data.join("fragmented.mp4"), crate::FileEnd::Stop)
1255            .await
1256            .expect("the fragmented clip opens");
1257        assert_ne!(other.path(), clip);
1258    }
1259}