1use 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum VideoSourceSpec {
65 Camera(Option<String>),
67 Display(Option<String>),
73 Window(String),
78 App(String),
80 #[cfg(all(target_os = "linux", feature = "rpicam"))]
85 Rpicam(RpicamMode),
86 Test(TestPattern),
88 File {
90 path: PathBuf,
92 looping: bool,
94 },
95 None,
97}
98
99impl FromStr for VideoSourceSpec {
100 type Err = ParseSpecError;
101
102 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 "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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
157#[non_exhaustive]
158pub enum TestPattern {
159 #[default]
166 Timing,
167 Gradient,
169 Bounce,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum RpicamMode {
178 Encoded,
183 Raw,
188}
189
190#[cfg(all(target_os = "linux", feature = "rpicam"))]
192fn rpicam(mode: RpicamMode) -> Result<VideoSourceSpec, ParseSpecError> {
193 Ok(VideoSourceSpec::Rpicam(mode))
194}
195
196#[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#[derive(Debug, Clone, PartialEq, Eq)]
208#[non_exhaustive]
209pub enum AudioSourceSpec {
210 Microphone(Option<String>),
214 System,
216 Test(TestTone),
218 File {
220 path: PathBuf,
222 looping: bool,
224 },
225 None,
227}
228
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub enum TestTone {
232 #[default]
237 Beeps,
238 Tone,
240}
241
242impl FromStr for AudioSourceSpec {
243 type Err = ParseSpecError;
244
245 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 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 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#[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
337fn 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
345fn 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
354fn 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
363fn 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
374pub const PORTAL: &str = "portal";
378
379const TEST_SIZE: video::Size = video::Size {
381 width: 1280,
382 height: 720,
383};
384
385#[cfg(all(target_os = "linux", feature = "rpicam"))]
387const RPICAM_SIZE: video::Size = video::Size {
388 width: 640,
389 height: 360,
390};
391
392const GENERATED_FPS: u32 = 30;
394
395#[cfg(feature = "pattern")]
399const TEST_TONE_HZ: f32 = 440.0;
400
401#[cfg(feature = "pattern")]
403const TEST_TONE_LAYOUT: audio::Layout = audio::Layout::Stereo;
404
405#[derive(Debug, Clone, PartialEq, Eq)]
427#[non_exhaustive]
428pub struct MediaSpec {
429 pub video: VideoSourceSpec,
431 pub audio: Option<AudioSourceSpec>,
437 pub reencode: bool,
443}
444
445impl MediaSpec {
446 #[must_use]
448 pub fn new(video: VideoSourceSpec) -> Self {
449 Self {
450 video,
451 audio: None,
452 reencode: false,
453 }
454 }
455
456 #[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 #[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 #[cfg(feature = "capture")]
482 #[must_use]
483 pub fn screen() -> Self {
484 Self::new(VideoSourceSpec::Display(None))
485 }
486
487 #[must_use]
489 pub fn with_audio(mut self, audio: AudioSourceSpec) -> Self {
490 self.audio = Some(audio);
491 self
492 }
493
494 #[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#[derive(Debug, Clone, PartialEq, Eq)]
513#[non_exhaustive]
514pub struct VideoOpenOptions {
515 pub width: Option<u32>,
517 pub height: Option<u32>,
519 pub framerate: Option<video::FrameRate>,
523 pub cursor: bool,
525 portal_grants: Option<String>,
527 portal_grants_kept_after_end: bool,
529 #[cfg(feature = "file")]
531 file: Option<HeldFile>,
532}
533
534#[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 #[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 #[must_use]
575 pub fn with_framerate(mut self, rate: video::FrameRate) -> Self {
576 self.framerate = Some(rate);
577 self
578 }
579
580 #[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 #[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 #[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 #[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 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 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 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 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#[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#[derive(Debug, Clone, Copy)]
743enum PortalKind {
744 Screen,
745 Window,
746}
747
748#[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#[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#[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#[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#[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#[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#[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#[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 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#[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}