Skip to main content

moq_ext_sources/
source.rs

1//! Opened video and audio sources.
2//!
3//! A source is already open when the application gets it. Opening is async
4//! and fails if the device does not open, so a missing camera is an error
5//! where the application asked for it. Each device lives on its own thread,
6//! because platform capture objects are often not `Send`. Only frames cross
7//! threads.
8
9#[cfg(feature = "file")]
10use std::path::Path;
11use std::sync::Arc;
12
13use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
14#[cfg(feature = "capture")]
15use tracing::info;
16use tracing::{debug, warn};
17
18#[cfg(feature = "file")]
19pub use self::media_file::{AudioInfo, MediaFile, MediaInfo, VideoFileConfig, VideoInfo};
20#[cfg(all(target_os = "linux", feature = "rpicam"))]
21pub use self::rpicam::RpicamConfig;
22pub use self::{
23    sender::{Demand, DemandGuard, FrameSender, PcmFanout, WeakPcmFanout},
24    switch::VideoSwitch,
25};
26use crate::{
27    Error, audio,
28    frames::{FrameReader, FrameSlot, VideoFrames},
29    video,
30};
31
32#[cfg(feature = "capture")]
33mod capture;
34#[cfg(feature = "file")]
35mod file;
36#[cfg(feature = "pattern")]
37mod generator;
38#[cfg(feature = "file")]
39mod media_file;
40#[cfg(all(target_os = "linux", feature = "rpicam"))]
41mod rpicam;
42mod scaled;
43mod sender;
44mod switch;
45
46/// How many PCM frames a broadcast may lag before it loses the oldest.
47///
48/// Sources deliver 10 to 60 ms per frame, so this is one to six seconds of
49/// audio.
50const PCM_BUFFER: usize = 100;
51
52/// The size and cadence of a raw video source.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct VideoFormat {
55    /// The picture size.
56    pub size: video::Size,
57    /// The frame rate.
58    pub rate: video::FrameRate,
59}
60
61/// The sample rate and speaker layout of a raw audio source.
62///
63/// Samples are interleaved 32-bit floats in `-1.0..=1.0`.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AudioFormat {
66    /// Samples per second per channel.
67    pub sample_rate: u32,
68    /// The channels and their order.
69    pub layout: audio::Layout,
70}
71
72/// What keeps a source's producer running, dropped with the last handle.
73#[derive(Debug)]
74enum Driver {
75    /// A thread that watches the stop token.
76    Thread,
77    /// A task on a thread of its own, for capture objects that cannot move.
78    #[cfg(any(feature = "capture", all(target_os = "linux", feature = "rpicam")))]
79    Local(crate::local_task::LocalTask),
80    /// A camera's capture thread, which the next camera open waits for once dropped.
81    #[cfg(feature = "capture")]
82    Camera(capture::Camera),
83    /// Nothing: the application pushes.
84    Pushed,
85    /// A task that derives frames from another source, which it keeps running.
86    Derived {
87        input: VideoSource,
88        _task: n0_future::task::AbortOnDropHandle<()>,
89    },
90}
91
92/// The shared half of a [`VideoSource`].
93#[derive(Debug)]
94struct VideoInner {
95    label: String,
96    format: VideoFormat,
97    frames: FrameReader,
98    demand: Demand,
99    stop: CancellationToken,
100    driver: Driver,
101}
102
103impl Drop for VideoInner {
104    fn drop(&mut self) {
105        self.stop.cancel();
106    }
107}
108
109/// A raw video source running on its own thread.
110///
111/// Capture runs while any clone exists, including the clone a broadcast holds.
112/// Any number of broadcasts and previews can read it at once. Encoding runs
113/// only while something wants the frames. Cheap to clone.
114#[derive(Debug, Clone)]
115pub struct VideoSource {
116    inner: Arc<VideoInner>,
117}
118
119/// Returns the capture source of the main screen, as [`VideoSource::screen`] opens it.
120///
121/// In a Wayland session on Linux with the `pipewire` feature, this is the
122/// desktop portal's screen picker. Elsewhere it is the main display, which
123/// [`VideoSource::capture`] still tries through the portal first on an X11
124/// session with that feature. Use it to set a size or a rate on the capture
125/// config of a screen. The portal's selection keeps no grant across runs;
126/// use a `PortalGrant`'s selection for that.
127#[cfg(feature = "capture")]
128#[must_use]
129pub fn screen_source() -> video::capture::Source {
130    #[cfg(all(target_os = "linux", feature = "pipewire"))]
131    if std::env::var_os("WAYLAND_DISPLAY").is_some() {
132        use video::capture::portal::{Kind, Selection};
133        return video::capture::Source::Portal(Selection::new(Kind::Screen));
134    }
135    video::capture::Source::Display(video::capture::DisplaySelection::default())
136}
137
138impl VideoSource {
139    fn new(
140        label: impl Into<String>,
141        format: VideoFormat,
142        frames: FrameReader,
143        stop: CancellationToken,
144        driver: Driver,
145    ) -> Self {
146        Self::with_demand(label, format, frames, stop, driver, Demand::default())
147    }
148
149    /// As [`new`](Self::new), with a demand its driver already watches.
150    fn with_demand(
151        label: impl Into<String>,
152        format: VideoFormat,
153        frames: FrameReader,
154        stop: CancellationToken,
155        driver: Driver,
156        demand: Demand,
157    ) -> Self {
158        Self {
159            inner: Arc::new(VideoInner {
160                label: label.into(),
161                format,
162                frames,
163                demand,
164                stop,
165                driver,
166            }),
167        }
168    }
169
170    /// Opens the camera, display or window that `config.source` names.
171    ///
172    /// Returns once the device has produced a frame. An opened camera that
173    /// produces none within 10 seconds fails, any other device within 30
174    /// seconds. A permission dialog the platform shows while the device opens
175    /// does not count against that time.
176    ///
177    /// A camera first waits, for at most 3 seconds, until every camera source
178    /// dropped before this call has closed its device, so a switch back to the
179    /// same camera does not fail as busy. Drop the old source before opening
180    /// its replacement. A capture that does not let go in time is stuck in a
181    /// read: the open proceeds without it, and that thread may hold its device
182    /// until the read returns. A V4L2 read gives up after a second, but a Media
183    /// Foundation read on Windows has no timeout.
184    ///
185    /// With the `pipewire` feature on Linux, the defaults go through PipeWire
186    /// first. The default camera is PipeWire's, which shares the device with
187    /// other applications, and the default V4L2 device opens if it does not.
188    /// The default display is the one the user picks in the desktop portal's
189    /// screen-sharing dialog. On an X11 session the main X11 display opens if
190    /// the portal is unavailable. On Wayland there is no fallback, because X11
191    /// capture there sees only XWayland's windows.
192    ///
193    /// A window or display that settles at a new size, or a device that
194    /// changes its format, is reopened behind the same source, so its frames
195    /// go on at the new size while [`format`](Self::format) keeps the size it
196    /// opened at. The source fails if the reopen does not succeed after a few
197    /// attempts, and ends when the user stops sharing, the window closes or
198    /// the device goes away.
199    ///
200    /// Cancellation safe: dropping the future stops the thread and releases
201    /// the device.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`Error::Device`] if the device does not open or produces no
206    /// frame.
207    #[cfg(feature = "capture")]
208    pub async fn capture(config: video::capture::Config) -> Result<Self, Error> {
209        if matches!(config.source, video::capture::Source::Camera(_)) {
210            capture::settle().await;
211        }
212        #[cfg(all(target_os = "linux", feature = "pipewire"))]
213        let mut config = config;
214        #[cfg(all(target_os = "linux", feature = "pipewire"))]
215        if let Some(preferred) = capture::pipewire_default(&config.source) {
216            let mut pipewire = config.clone();
217            pipewire.source = preferred;
218            match Self::capture_device(pipewire).await {
219                Ok(source) => return Ok(source),
220                Err(err) if !capture::falls_back(&config.source, &err) => return Err(err),
221                Err(err) => info!(
222                    error = format_args!("{err:#}"),
223                    source = ?config.source,
224                    "PipeWire did not open the default source, trying the fallback"
225                ),
226            }
227            config.source = capture::fallback(config.source);
228        }
229        Self::capture_device(config).await
230    }
231
232    /// Opens camera `id` at its default mode, or the default camera for `None`.
233    ///
234    /// The ids are the ones `moq_video::capture::cameras` reports. For a size
235    /// or a rate, build a `capture::Config` and call
236    /// [`capture`](Self::capture).
237    ///
238    /// # Errors
239    ///
240    /// As [`capture`](Self::capture).
241    #[cfg(feature = "capture")]
242    pub async fn camera(id: Option<String>) -> Result<Self, Error> {
243        let mut config = video::capture::Config::default();
244        config.source = video::capture::Source::Camera(id);
245        Self::capture(config).await
246    }
247
248    /// Opens the main screen at its own size.
249    ///
250    /// Opens [`screen_source`]: on Wayland in a build with the `pipewire`
251    /// feature, the user picks the screen in the desktop portal's dialog,
252    /// since Wayland refuses a direct display capture. The portal asks on
253    /// each call; see
254    /// [`VideoOpenOptions::with_portal_grants`](crate::spec::VideoOpenOptions::with_portal_grants)
255    /// to keep the grant.
256    ///
257    /// # Errors
258    ///
259    /// As [`capture`](Self::capture), and fails on Wayland without the
260    /// `pipewire` feature.
261    #[cfg(feature = "capture")]
262    pub async fn screen() -> Result<Self, Error> {
263        let mut config = video::capture::Config::default();
264        config.source = screen_source();
265        Self::capture(config).await
266    }
267
268    /// Opens exactly the device `config` names.
269    #[cfg(feature = "capture")]
270    async fn capture_device(config: video::capture::Config) -> Result<Self, Error> {
271        let slot = FrameSlot::new();
272        let reader = slot.reader();
273        let stop = CancellationToken::new();
274        let (format, driver) = capture::open(config, slot, stop.clone()).await?;
275        Ok(Self::new("capture", format, reader, stop, driver))
276    }
277
278    /// Returns a generated test pattern at `size` and `rate`.
279    ///
280    /// The pattern shows a sweeping bar, a frame counter and a clock. A marker
281    /// flashes in step with the beep of [`AudioSource::test_pattern`].
282    ///
283    /// # Errors
284    ///
285    /// Fails if the thread that draws the pattern cannot be started.
286    #[cfg(feature = "pattern")]
287    pub fn test_pattern(size: video::Size, rate: video::FrameRate) -> Result<Self, Error> {
288        Self::spawn_generator(
289            "test-pattern",
290            VideoFormat { size, rate },
291            move |slot, stop| {
292                generator::run_pattern(size, rate, slot, stop);
293            },
294        )
295    }
296
297    /// Returns a diagonal gradient at `size` and `rate` that shifts every frame.
298    ///
299    /// Cheap to draw, and different in every frame, so a stalled pipeline does
300    /// not look like a working one. Unlike [`test_pattern`](Self::test_pattern),
301    /// it carries no clock or counter.
302    ///
303    /// # Errors
304    ///
305    /// Fails if the thread that draws the gradient cannot be started.
306    #[cfg(feature = "pattern")]
307    pub fn test_gradient(size: video::Size, rate: video::FrameRate) -> Result<Self, Error> {
308        Self::spawn_generator(
309            "test-gradient",
310            VideoFormat { size, rate },
311            move |slot, stop| {
312                generator::run_gradient(size, rate, slot, stop);
313            },
314        )
315    }
316
317    /// Returns a bouncing square on a drifting hue at `size` and `rate`.
318    ///
319    /// Draws [`BouncePattern`](crate::BouncePattern) at each frame's media time.
320    ///
321    /// # Errors
322    ///
323    /// Fails with [`Error::InvalidConfig`] if a dimension of `size` is zero or
324    /// odd, and if the thread that draws the pattern cannot be started.
325    #[cfg(feature = "pattern")]
326    pub fn test_bounce(size: video::Size, rate: video::FrameRate) -> Result<Self, Error> {
327        let pattern = crate::BouncePattern::new(size)?;
328        Self::spawn_generator(
329            "test-bounce",
330            VideoFormat { size, rate },
331            move |slot, stop| {
332                generator::run_bounce(&pattern, rate, slot, stop);
333            },
334        )
335    }
336
337    /// Returns a source whose pictures `run` draws into a slot on a thread named `name`.
338    ///
339    /// `run` returns once its token is cancelled.
340    ///
341    /// # Errors
342    ///
343    /// Fails if the thread cannot be started.
344    #[cfg(feature = "pattern")]
345    fn spawn_generator(
346        name: &'static str,
347        format: VideoFormat,
348        run: impl FnOnce(FrameSlot, CancellationToken) + Send + 'static,
349    ) -> Result<Self, Error> {
350        let slot = FrameSlot::new();
351        let reader = slot.reader();
352        let stop = CancellationToken::new();
353        let token = stop.clone();
354        std::thread::Builder::new()
355            .name(name.into())
356            .spawn(move || run(slot, token))?;
357        Ok(Self::new(name, format, reader, stop, Driver::Thread))
358    }
359
360    /// Returns a source fed by the returned sender.
361    ///
362    /// The source ends when every sender is dropped. `format` describes what
363    /// the sender will push, and a broadcast advertises its size. A frame of
364    /// another size is scaled to the rendition's.
365    ///
366    /// An application may switch devices while it pushes. Timestamps only have
367    /// to rise within one device's run: a broadcast re-anchors a timeline that
368    /// goes back or jumps far ahead, and starts a new group there.
369    #[must_use]
370    pub fn push(format: VideoFormat) -> (FrameSender<video::Frame>, Self) {
371        let slot = FrameSlot::new();
372        let reader = slot.reader();
373        let stop = CancellationToken::new();
374        let source = Self::new("push", format, reader, stop.clone(), Driver::Pushed);
375        let sender = FrameSender::new(Arc::new(slot), stop, source.inner.demand.clone());
376        (sender, source)
377    }
378
379    /// Runs `run` on a dedicated thread that feeds the source.
380    ///
381    /// Use it for thread-bound platform objects. The thread has a
382    /// current-thread Tokio runtime entered, so `run` can drive async code
383    /// with `tokio::runtime::Handle::current().block_on`. The source ends once
384    /// `run` returns and every clone of its sender is dropped. If `run` fails,
385    /// the source fails with its error. `run` should return once
386    /// [`FrameSender::push`] reports [`SourceClosed`](crate::SourceClosed).
387    ///
388    /// # Errors
389    ///
390    /// Fails if the thread or its runtime cannot be started.
391    pub fn spawn<F>(name: &str, format: VideoFormat, run: F) -> Result<Self, Error>
392    where
393        F: FnOnce(FrameSender<video::Frame>) -> Result<(), Error> + Send + 'static,
394    {
395        let slot = FrameSlot::new();
396        let stop = CancellationToken::new();
397        let source = Self::new(name, format, slot.reader(), stop.clone(), Driver::Thread);
398        let sender = FrameSender::new(Arc::new(slot.clone()), stop, source.inner.demand.clone());
399        let runtime = tokio::runtime::Builder::new_current_thread()
400            .enable_all()
401            .build()?;
402        let thread_name = name.to_string();
403        std::thread::Builder::new()
404            .name(thread_name.clone())
405            .spawn(move || {
406                let _entered = runtime.enter();
407                match run(sender) {
408                    Ok(()) => debug!(source = %thread_name, "video source ended"),
409                    Err(err) => {
410                        warn!(source = %thread_name, error = format_args!("{err:#}"), "video source failed");
411                        slot.fail(Arc::new(err));
412                    }
413                }
414            })?;
415        Ok(source)
416    }
417
418    /// Starts the Raspberry Pi camera through `rpicam-vid`, for raw pictures.
419    ///
420    /// The width is rounded up to one libcamera writes without row padding, so
421    /// [`format`](Self::format) may be a few columns wider than asked for. For
422    /// the camera's hardware H.264, use [`rpicam_h264`].
423    ///
424    /// Cancellation safe: dropping the future kills the subprocess.
425    ///
426    /// # Errors
427    ///
428    /// Fails if `rpicam-vid` is not installed or cannot open the camera.
429    #[cfg(all(target_os = "linux", feature = "rpicam"))]
430    pub async fn rpicam(config: RpicamConfig) -> Result<Self, Error> {
431        let slot = FrameSlot::new();
432        let reader = slot.reader();
433        let stop = CancellationToken::new();
434        let (format, task) = rpicam::open_raw(config, slot, stop.clone()).await?;
435        Ok(Self::new(
436            "rpicam",
437            format,
438            reader,
439            stop,
440            Driver::Local(task),
441        ))
442    }
443
444    /// Returns the source's frames, for a local preview or a QR scanner.
445    ///
446    /// Every call returns a handle onto the same stream. The handle counts as
447    /// demand, which [`FrameSender::demand`] reports, until it and its clones
448    /// are dropped, so a source that idles until wanted produces frames for
449    /// it. Reading it does not encode.
450    #[must_use]
451    pub fn frames(&self) -> VideoFrames {
452        self.observe().wanting(self.want())
453    }
454
455    /// Returns the source's frames without counting as demand.
456    ///
457    /// For a reader that wants the frames only some of the time, and holds a
458    /// [`want`](Self::want) guard while it does. A publisher's encoder reads
459    /// the source this way, and wants it only while somebody watches. A
460    /// source that idles until wanted produces nothing for this handle alone.
461    #[must_use]
462    pub fn observe(&self) -> VideoFrames {
463        self.inner.frames.frames()
464    }
465
466    /// Returns the format the source opened at.
467    ///
468    /// It may differ from what the config asked for. Frames can come at
469    /// another size later, such as from a captured window that was resized,
470    /// so a consumer that cares takes the size from each frame.
471    #[must_use]
472    pub fn format(&self) -> VideoFormat {
473        self.inner.format
474    }
475
476    /// Registers a consumer that wants frames, for [`FrameSender::demand`].
477    ///
478    /// The demand lasts until the guard is dropped. A handle from
479    /// [`frames`](Self::frames) already holds one, so this is only for a
480    /// reader from [`observe`](Self::observe).
481    #[doc(hidden)]
482    pub fn want(&self) -> DemandGuard {
483        self.inner.demand.acquire()
484    }
485
486    /// Returns why the source stopped, if it failed.
487    #[must_use]
488    pub fn failure(&self) -> Option<Arc<Error>> {
489        self.inner.frames.failure()
490    }
491
492    /// Returns a short name of the source, for logs.
493    #[must_use]
494    pub fn label(&self) -> &str {
495        &self.inner.label
496    }
497
498    /// Returns a future that resolves once the source has closed its device.
499    ///
500    /// The device closes on the capture thread after the last handle is
501    /// dropped. Bound the wait: a thread stuck in a read lets go only once the
502    /// read returns, which takes up to a second on V4L2 and has no limit for
503    /// Media Foundation on Windows. Resolves at once for a source without a
504    /// device. [`capture`](Self::capture) already waits for dropped cameras,
505    /// so this is for a device something other than this crate opens next.
506    pub fn released(&self) -> WaitForCancellationFutureOwned {
507        match &self.inner.driver {
508            #[cfg(any(feature = "capture", all(target_os = "linux", feature = "rpicam")))]
509            Driver::Local(task) => task.released().cancelled_owned(),
510            #[cfg(feature = "capture")]
511            Driver::Camera(camera) => camera.released().cancelled_owned(),
512            Driver::Derived { input, .. } => input.released(),
513            Driver::Thread | Driver::Pushed => {
514                let released = CancellationToken::new();
515                released.cancel();
516                released.cancelled_owned()
517            }
518        }
519    }
520}
521
522/// Starts the Raspberry Pi camera's hardware H.264 through `rpicam-vid`.
523///
524/// This is the cheapest thing a Pi Zero can publish: no raw pipe and no second
525/// encode. The returned Annex-B stream goes to
526/// `LocalBroadcast::set_encoded_video`, and dropping it kills the subprocess.
527///
528/// # Errors
529///
530/// Fails if `rpicam-vid` is not installed or cannot be started.
531#[cfg(all(target_os = "linux", feature = "rpicam"))]
532pub fn rpicam_h264(config: RpicamConfig) -> Result<crate::EncodedVideo, Error> {
533    rpicam::open_encoded(config).map(crate::EncodedVideo::AnnexB)
534}
535
536/// What a file source does when it reaches the end of the file.
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
538pub enum FileEnd {
539    /// Ends the source.
540    Stop,
541    /// Starts the file again from the beginning.
542    Restart,
543}
544
545impl FileEnd {
546    /// Returns [`Restart`](Self::Restart) for a file that loops, and [`Stop`](Self::Stop) otherwise.
547    #[must_use]
548    pub fn looping(looping: bool) -> Self {
549        if looping { Self::Restart } else { Self::Stop }
550    }
551}
552
553/// What an audio source produces.
554#[derive(Debug)]
555pub enum AudioKind {
556    /// A microphone, opened by the publication that encodes it.
557    #[cfg(feature = "capture")]
558    Microphone(audio::capture::Config),
559    /// PCM, fanned out to every broadcast that reads it.
560    ///
561    /// The fan-out is weak, so the source ends when its producer drops the
562    /// sender.
563    Pcm {
564        /// The sample rate and layout of every frame.
565        format: AudioFormat,
566        /// The fan-out a broadcast subscribes to, held weakly.
567        fanout: WeakPcmFanout,
568    },
569}
570
571/// The shared half of an [`AudioSource`].
572#[derive(Debug)]
573struct AudioInner {
574    label: &'static str,
575    kind: AudioKind,
576    demand: Demand,
577    stop: CancellationToken,
578    _driver: Driver,
579}
580
581impl Drop for AudioInner {
582    fn drop(&mut self) {
583        self.stop.cancel();
584    }
585}
586
587/// A raw audio source.
588///
589/// Runs while any clone exists, until its input ends: a file that does not
590/// loop, or a push source whose senders are gone. Cheap to clone. Every
591/// broadcast it feeds reads all of its samples.
592#[derive(Debug, Clone)]
593pub struct AudioSource {
594    inner: Arc<AudioInner>,
595}
596
597impl AudioSource {
598    fn new(label: &'static str, kind: AudioKind, stop: CancellationToken, driver: Driver) -> Self {
599        Self {
600            inner: Arc::new(AudioInner {
601                label,
602                kind,
603                demand: Demand::default(),
604                stop,
605                _driver: driver,
606            }),
607        }
608    }
609
610    /// Registers a broadcast that publishes this source.
611    // Shared with moq-ext-publisher, not public API.
612    #[doc(hidden)]
613    pub fn want(&self) -> DemandGuard {
614        self.inner.demand.acquire()
615    }
616
617    /// Creates a microphone source.
618    ///
619    /// The device opens only when `LocalBroadcast::set_audio` publishes the
620    /// source. A failure then shows in that broadcast's status, and the audio
621    /// slot stays failed until the next `set_audio`: a failed microphone is
622    /// not opened again. The same source set on two broadcasts opens the
623    /// device twice.
624    ///
625    /// For echo cancellation, set `config.aec` to the canceller of the
626    /// speaker's engine, from `playback::Engine::canceller`. Only one open
627    /// microphone attaches to it at a time, and a publication that replaces
628    /// this one attaches once this one has closed.
629    ///
630    /// Cancellation safe: dropping the future only abandons the device query.
631    ///
632    /// # Errors
633    ///
634    /// Returns [`Error::Device`] if no microphone matches the config.
635    #[cfg(feature = "capture")]
636    pub async fn microphone(config: audio::capture::Config) -> Result<Self, Error> {
637        if let audio::capture::Source::Microphone(wanted) = &config.source {
638            let devices = audio::capture::devices().await.map_err(Error::device)?;
639            let found = match wanted {
640                Some(id) => devices.iter().any(|device| &device.id == id),
641                None => !devices.is_empty(),
642            };
643            if !found {
644                return Err(Error::device_msg(match wanted {
645                    Some(id) => format!("no microphone with the id {id}"),
646                    None => "this machine has no microphone".to_string(),
647                }));
648            }
649        }
650        #[cfg(feature = "aec")]
651        let echo_cancellation = config.aec.is_some();
652        #[cfg(not(feature = "aec"))]
653        let echo_cancellation = false;
654        info!(source = ?config.source, echo_cancellation, "microphone ready");
655        Ok(Self::microphone_unchecked(config))
656    }
657
658    /// Wraps a microphone config without looking for the device.
659    ///
660    /// A missing device then shows only when a broadcast publishes the source.
661    #[cfg(feature = "capture")]
662    #[must_use]
663    pub fn microphone_unchecked(config: audio::capture::Config) -> Self {
664        Self::new(
665            "microphone",
666            AudioKind::Microphone(config),
667            CancellationToken::new(),
668            Driver::Pushed,
669        )
670    }
671
672    /// Decodes an audio file in real time.
673    ///
674    /// `at_end` says whether the source ends with the file or starts it again.
675    /// Reads WAV, MP3, and the AAC of an MP4 file, which goes through
676    /// [`MediaFile::audio`]. The file is probed before this returns, and
677    /// decoding starts on its own thread.
678    ///
679    /// Cancellation safe: dropping the future stops the decode thread.
680    ///
681    /// # Errors
682    ///
683    /// Fails if the file cannot be read, holds no audio track, or uses a codec
684    /// this build cannot decode.
685    #[cfg(feature = "file")]
686    pub async fn file(path: impl AsRef<Path>, at_end: FileEnd) -> Result<Self, Error> {
687        let path = path.as_ref().to_path_buf();
688        if media_file::is_mp4(&path).await {
689            return MediaFile::open(&path).await?.with_end(at_end).audio();
690        }
691        let probed = path.clone();
692        let format = tokio::task::spawn_blocking(move || file::probe(&probed))
693            .await
694            .map_err(|err| Error::device_msg(format!("the file reader failed: {err}")))??;
695        Self::spawn("audio-file", format, move |sender| {
696            file::decode_loop(&path, at_end, &sender)
697        })
698    }
699
700    /// Returns a steady sine tone at `hz`, at 48 kHz in `layout`.
701    ///
702    /// # Errors
703    ///
704    /// Fails if the thread that generates the tone cannot be started.
705    #[cfg(feature = "pattern")]
706    pub fn tone(hz: f32, layout: audio::Layout) -> Result<Self, Error> {
707        Self::generated("tone", f64::from(hz), layout, generator::Gate::Continuous)
708    }
709
710    /// Returns the beeping tone that goes with [`VideoSource::test_pattern`].
711    ///
712    /// It beeps for a tenth of a second every second, on the timeline the
713    /// pattern's marker flashes on, so a viewer can check lip sync.
714    ///
715    /// # Errors
716    ///
717    /// Fails if the thread that generates the tone cannot be started.
718    #[cfg(feature = "pattern")]
719    pub fn test_pattern(layout: audio::Layout) -> Result<Self, Error> {
720        Self::generated("test-pattern", generator::BEEP_HZ, layout, generator::BEEP)
721    }
722
723    /// Returns a tone at `hz`, gated by `gate`, on a thread named `name`.
724    #[cfg(feature = "pattern")]
725    fn generated(
726        name: &'static str,
727        hz: f64,
728        layout: audio::Layout,
729        gate: generator::Gate,
730    ) -> Result<Self, Error> {
731        let format = AudioFormat {
732            sample_rate: generator::TONE_RATE,
733            layout,
734        };
735        Self::spawn(name, format, move |sender| {
736            generator::run_tone(hz, format, gate, &sender);
737            Ok(())
738        })
739    }
740
741    /// Returns a source fed by the returned sender.
742    ///
743    /// The source ends when every sender is dropped. A broadcast that falls
744    /// more than a few seconds behind loses the oldest frames and counts them
745    /// in its stats. The sender's demand is true while a broadcast publishes
746    /// the source.
747    #[must_use]
748    pub fn push(format: AudioFormat) -> (FrameSender<audio::Frame>, Self) {
749        Self::pcm("push", format, Driver::Pushed)
750    }
751
752    /// Runs `run` on a dedicated thread named `name` that feeds the source.
753    ///
754    /// As [`VideoSource::spawn`], for PCM in `format`. The source ends once
755    /// `run` returns and every clone of its sender is dropped. An error of
756    /// `run` is logged. `run` should return once [`FrameSender::push`]
757    /// reports [`SourceClosed`](crate::SourceClosed).
758    ///
759    /// # Errors
760    ///
761    /// Fails if the thread cannot be started.
762    pub fn spawn<F>(name: &'static str, format: AudioFormat, run: F) -> Result<Self, Error>
763    where
764        F: FnOnce(FrameSender<audio::Frame>) -> Result<(), Error> + Send + 'static,
765    {
766        let (sender, source) = Self::pcm(name, format, Driver::Thread);
767        std::thread::Builder::new()
768            .name(name.into())
769            .spawn(move || match run(sender) {
770                Ok(()) => debug!(source = name, "audio source ended"),
771                Err(err) => {
772                    warn!(
773                        source = name,
774                        error = format_args!("{err:#}"),
775                        "audio source failed"
776                    );
777                }
778            })?;
779        Ok(source)
780    }
781
782    /// Returns a PCM source in `format` and the sender that feeds it.
783    fn pcm(
784        label: &'static str,
785        format: AudioFormat,
786        driver: Driver,
787    ) -> (FrameSender<audio::Frame>, Self) {
788        let (fanout, _) = tokio::sync::broadcast::channel(PCM_BUFFER);
789        let stop = CancellationToken::new();
790        let kind = AudioKind::Pcm {
791            format,
792            fanout: fanout.downgrade(),
793        };
794        let source = Self::new(label, kind, stop.clone(), driver);
795        let sender = FrameSender::new(Arc::new(fanout), stop, source.inner.demand.clone());
796        (sender, source)
797    }
798
799    /// Returns what the source produces.
800    // Shared with moq-ext-publisher, not public API.
801    #[doc(hidden)]
802    #[must_use]
803    pub fn kind(&self) -> &AudioKind {
804        &self.inner.kind
805    }
806
807    /// Returns the format of the samples, or `None` for a microphone.
808    ///
809    /// A microphone's format is known only once the publication opens it.
810    #[must_use]
811    pub fn format(&self) -> Option<AudioFormat> {
812        match &self.inner.kind {
813            AudioKind::Pcm { format, .. } => Some(*format),
814            #[cfg(feature = "capture")]
815            AudioKind::Microphone(_) => None,
816        }
817    }
818
819    /// Returns a short name of the source, for logs.
820    #[must_use]
821    pub fn label(&self) -> &str {
822        self.inner.label
823    }
824}
825
826#[cfg(all(test, any(feature = "pattern", feature = "file")))]
827impl AudioSource {
828    /// Returns a receiver of the PCM the source produces, while its producer runs.
829    pub(crate) fn subscribe_pcm(&self) -> Option<tokio::sync::broadcast::Receiver<audio::Frame>> {
830        match &self.inner.kind {
831            AudioKind::Pcm { fanout, .. } => fanout.upgrade().map(|fanout| fanout.subscribe()),
832            #[cfg(feature = "capture")]
833            AudioKind::Microphone(_) => None,
834        }
835    }
836}
837
838/// Sleeps until `due`, or returns `false` once `closed` reports the source gone.
839///
840/// Wakes every 50 ms to ask, so a dropped source does not hold its thread for
841/// a slow frame interval or a still picture that lasts seconds.
842#[cfg(any(feature = "pattern", feature = "file"))]
843fn sleep_until(due: std::time::Instant, closed: impl Fn() -> bool) -> bool {
844    loop {
845        if closed() {
846            return false;
847        }
848        let left = due.saturating_duration_since(std::time::Instant::now());
849        if left.is_zero() {
850            return true;
851        }
852        std::thread::sleep(left.min(std::time::Duration::from_millis(50)));
853    }
854}
855
856/// How long an opened capture device may take over its first frame.
857#[cfg(any(feature = "capture", all(target_os = "linux", feature = "rpicam")))]
858pub(crate) const FIRST_FRAME_PATIENCE: std::time::Duration = std::time::Duration::from_secs(30);
859
860#[cfg(test)]
861mod tests {
862    #[cfg(feature = "pattern")]
863    use std::time::Duration;
864
865    use super::*;
866
867    fn rate(fps: u32) -> video::FrameRate {
868        video::FrameRate::new(fps, 1).expect("a valid rate")
869    }
870
871    #[cfg(feature = "pattern")]
872    #[tokio::test]
873    async fn a_test_pattern_produces_frames_and_stops_with_its_source() {
874        let source = VideoSource::test_pattern(video::Size::new(64, 48), rate(30))
875            .expect("the pattern thread starts");
876        let mut frames = source.frames();
877        let first = tokio::time::timeout(Duration::from_secs(5), frames.next())
878            .await
879            .expect("the pattern draws")
880            .expect("the pattern runs");
881        assert_eq!(first.size(), video::Size::new(64, 48));
882        drop(source);
883        let ended = tokio::time::timeout(Duration::from_secs(5), async {
884            while frames.next().await.is_some() {}
885        })
886        .await;
887        assert!(ended.is_ok(), "the pattern kept running without its source");
888    }
889
890    #[tokio::test]
891    async fn a_pushed_source_ends_when_its_senders_go() {
892        let format = VideoFormat {
893            size: video::Size::new(2, 2),
894            rate: rate(30),
895        };
896        let (sender, source) = VideoSource::push(format);
897        let mut frames = source.frames();
898        let surface = video::Surface::rgba(&[0; 16], format.size).expect("2x2");
899        sender
900            .push(video::Frame::new(
901                moq_net::Timestamp::from_micros(0).expect("0"),
902                surface,
903            ))
904            .expect("open");
905        assert!(frames.next().await.is_some());
906        drop(sender);
907        assert!(frames.next().await.is_none());
908    }
909
910    #[tokio::test]
911    async fn a_source_without_a_device_is_released_at_once() {
912        let (_sender, source) = VideoSource::push(VideoFormat {
913            size: video::Size::new(2, 2),
914            rate: rate(30),
915        });
916        // A pushed source holds no device, so nothing waits on it.
917        source.released().await;
918    }
919
920    #[tokio::test]
921    async fn a_pushed_source_reports_demand_while_something_wants_it() {
922        let format = VideoFormat {
923            size: video::Size::new(2, 2),
924            rate: rate(30),
925        };
926        let (sender, source) = VideoSource::push(format);
927        let demand = sender.demand();
928        assert!(!*demand.borrow());
929        let wanted = source.want();
930        assert!(*demand.borrow());
931        drop(wanted);
932        assert!(!*demand.borrow());
933
934        let _observed = source.observe();
935        assert!(!*demand.borrow(), "an observer is not demand");
936        let frames = source.frames();
937        let clone = frames.clone();
938        assert!(*demand.borrow(), "a frames reader is demand");
939        drop(frames);
940        assert!(*demand.borrow(), "the clone still wants frames");
941        drop(clone);
942        assert!(!*demand.borrow());
943        drop(source);
944        assert!(sender.is_closed());
945    }
946
947    /// A source that pushes only while wanted feeds a plain frames reader.
948    #[tokio::test]
949    async fn a_frames_reader_gets_frames_from_a_source_that_waits_for_demand() {
950        let format = VideoFormat {
951            size: video::Size::new(2, 2),
952            rate: rate(30),
953        };
954        let (sender, source) = VideoSource::push(format);
955        let producer = tokio::spawn(async move {
956            sender
957                .demand()
958                .wait_for(|wanted| *wanted)
959                .await
960                .expect("the source is open");
961            let surface = video::Surface::rgba(&[0; 16], format.size).expect("2x2");
962            let timestamp = moq_net::Timestamp::from_micros(7).expect("in range");
963            sender.push(video::Frame::new(timestamp, surface))
964        });
965        let mut frames = source.frames();
966        let frame = tokio::time::timeout(std::time::Duration::from_secs(5), frames.next())
967            .await
968            .expect("the source produced for the reader")
969            .expect("the source is open");
970        assert_eq!(frame.timestamp.as_micros(), Ok(7));
971        producer.await.expect("joined").expect("pushed");
972    }
973
974    #[tokio::test]
975    async fn a_spawned_source_that_fails_reports_why() {
976        let format = VideoFormat {
977            size: video::Size::new(2, 2),
978            rate: rate(30),
979        };
980        let source = VideoSource::spawn("failing", format, |_sender| {
981            Err(Error::device_msg("the camera caught fire"))
982        })
983        .expect("the thread starts");
984        let mut frames = source.frames();
985        assert!(frames.next().await.is_none());
986        let failure = source.failure().expect("the failure is kept");
987        assert!(matches!(*failure, Error::Device { .. }));
988    }
989
990    /// Reads one frame of the PCM `source` generates, and checks that it stops once dropped.
991    #[cfg(feature = "pattern")]
992    async fn generates_pcm(source: AudioSource, layout: audio::Layout) {
993        let (format, fanout) = match source.kind() {
994            AudioKind::Pcm { format, fanout } => (*format, fanout.clone()),
995            #[cfg(feature = "capture")]
996            AudioKind::Microphone(_) => panic!("a generated source is PCM"),
997        };
998        assert_eq!(format.sample_rate, 48_000);
999        assert_eq!(format.layout, layout);
1000        let mut frames = fanout.upgrade().expect("the generator runs").subscribe();
1001        let frame = tokio::time::timeout(Duration::from_secs(5), frames.recv())
1002            .await
1003            .expect("the generator sends")
1004            .expect("the generator runs");
1005        let sample_bytes = layout.channels() as usize * 4;
1006        assert!(!frame.data.is_empty());
1007        assert_eq!(frame.data.len() % sample_bytes, 0, "whole samples");
1008
1009        drop(source);
1010        let stopped = tokio::time::timeout(Duration::from_secs(5), async {
1011            while fanout.upgrade().is_some() {
1012                tokio::time::sleep(Duration::from_millis(10)).await;
1013            }
1014        })
1015        .await;
1016        assert!(
1017            stopped.is_ok(),
1018            "the generator kept running without its source"
1019        );
1020    }
1021
1022    #[cfg(feature = "pattern")]
1023    #[tokio::test]
1024    async fn a_tone_generates_pcm_in_its_layout_and_stops_with_its_source() {
1025        let source = AudioSource::tone(440.0, audio::Layout::Stereo).expect("the thread starts");
1026        assert_eq!(source.label(), "tone");
1027        generates_pcm(source, audio::Layout::Stereo).await;
1028    }
1029
1030    #[cfg(feature = "pattern")]
1031    #[tokio::test]
1032    async fn the_audio_test_pattern_generates_pcm_and_stops_with_its_source() {
1033        let source = AudioSource::test_pattern(audio::Layout::Mono).expect("the thread starts");
1034        assert_eq!(source.label(), "test-pattern");
1035        generates_pcm(source, audio::Layout::Mono).await;
1036    }
1037}