Skip to main content

zaun_client/voice/
player.rs

1//! Playing audio into voice sessions, in the shape of discord.js's `@discordjs/voice`: an
2//! [`AudioPlayer`] plays [`AudioResource`]s, and every [`VoiceSession`] subscribed to it sends
3//! what it plays. One player can feed sessions in several communities at once.
4//!
5//! ```no_run
6//! # use zaun_client::{AudioPlayer, AudioPlayerEvent, AudioResource, Community};
7//! # fn demo(community: &Community) -> zaun_client::Result<()> {
8//! let voice = community.channel_by_name("music").expect("a voice channel").join()?;
9//! let player = AudioPlayer::new()?;
10//! voice.subscribe(&player);
11//! player.play(AudioResource::ogg_file("intro.opus")?);           // Ogg Opus: no transcoding
12//! player.enqueue(AudioResource::ffmpeg_file("song.flac", Default::default())?); // anything ffmpeg reads
13//! for event in player.events() {
14//!     if let AudioPlayerEvent::TrackEnd { .. } = event {
15//!         // pick the next song
16//!     }
17//! }
18//! # Ok(()) }
19//! ```
20//!
21//! Packets are sent on absolute 20 ms (or whatever each packet holds) deadlines, so the
22//! stream keeps real time; after a stall of more than [`LATE`] the schedule restarts instead
23//! of bursting. A player with nobody able to send (no subscriber, or every one muted) pauses
24//! itself instead of playing into nothing, and resumes when someone can hear it again.
25//!
26//! [`VoiceSession`]: super::VoiceSession
27
28use std::collections::VecDeque;
29use std::ffi::OsString;
30use std::fmt;
31use std::io::{self, Read};
32use std::path::{Path, PathBuf};
33use std::process::{Child, ChildStdout, Command, Stdio};
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
36use std::thread::JoinHandle;
37use std::time::{Duration, Instant};
38
39use crossbeam_channel::{Receiver, Sender, unbounded};
40use zaun_community_protocol::ids::VoiceSessionId;
41
42use super::media::Input;
43use super::ogg::{OggOpus, packet_samples};
44use crate::error::{Error, Result};
45
46/// The largest Opus packet sent: str0m would split a larger one over several RTP packets,
47/// which no receiver can decode. 1000 bytes is 400 kbit/s at 20 ms, far above any bitrate
48/// [`FfmpegOptions`] allows.
49pub const OPUS_PACKET_MAX: usize = 1_000;
50/// How far behind schedule the player may fall before it restarts the schedule.
51pub const LATE: Duration = Duration::from_millis(100);
52/// Opus silence (RFC 6716 §3.1 TOC `0xf8`, 20 ms): sent a few times when playback stops, so
53/// receivers' decoders do not interpolate the last sound.
54const SILENCE: [u8; 3] = [0xf8, 0xff, 0xfe];
55const SILENCE_FRAMES: u8 = 5;
56/// Samples per second (Opus in WebRTC is always 48 kHz).
57const RATE: u64 = 48_000;
58
59#[allow(
60    clippy::disallowed_methods,
61    reason = "playback keeps real time; the player thread owns its schedule"
62)]
63fn now() -> Instant {
64    Instant::now()
65}
66
67/// A voice session's way in, held by a player. It does not keep the session alive: once the
68/// session ends, sending fails and the player drops it.
69#[derive(Clone)]
70pub(crate) struct Sink {
71    pub(crate) session: VoiceSessionId,
72    pub(crate) input: Sender<Input>,
73    pub(crate) can_send: Arc<AtomicBool>,
74}
75
76/// What a player is doing.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum AudioPlayerStatus {
79    /// Nothing to play.
80    Idle,
81    /// Sending a resource.
82    Playing,
83    /// Paused with [`AudioPlayer::pause`].
84    Paused,
85    /// Paused because no subscribed session can send (none subscribed, or all muted or
86    /// without `SPEAK`); resumes by itself.
87    AutoPaused,
88}
89
90/// What a player tells the application.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum AudioPlayerEvent {
93    /// The status changed.
94    StateChange {
95        /// Before.
96        from: AudioPlayerStatus,
97        /// Now.
98        to: AudioPlayerStatus,
99    },
100    /// A resource started playing.
101    TrackStart {
102        /// Its title, if it was given one.
103        title: Option<String>,
104    },
105    /// A resource ended: played out, skipped, stopped or failed.
106    TrackEnd {
107        /// Its title, if it was given one.
108        title: Option<String>,
109    },
110    /// A resource could not be read (the track ends), or a packet was skipped.
111    Error {
112        /// Its title, if it was given one.
113        title: Option<String>,
114        /// What happened; names no path or URL.
115        error: String,
116    },
117}
118
119/// How [`AudioResource::ffmpeg_file`] and its siblings transcode.
120#[derive(Debug, Clone)]
121pub struct FfmpegOptions {
122    /// Opus bitrate in kbit/s, 8 to 256 (default 128).
123    pub bitrate_kbps: u32,
124    /// Gain, 0.0 to 4.0 (`None` leaves the volume alone).
125    pub volume: Option<f32>,
126    /// Start this far in.
127    pub seek: Option<Duration>,
128    /// The ffmpeg program (default `ffmpeg`, found on `PATH`).
129    pub program: PathBuf,
130}
131
132impl Default for FfmpegOptions {
133    fn default() -> Self {
134        Self {
135            bitrate_kbps: 128,
136            volume: None,
137            seek: None,
138            program: PathBuf::from("ffmpeg"),
139        }
140    }
141}
142
143/// Where ffmpeg reads from.
144enum FfmpegInput<'a> {
145    File(&'a Path),
146    Url(&'a str),
147    Pipe,
148    /// Raw PCM on stdin: signed 16-bit little-endian, 48 kHz, stereo.
149    Pcm,
150}
151
152/// ffmpeg's arguments: one input, restricted to its kind's protocols, out as Ogg Opus at
153/// 48 kHz in 20 ms packets, one per page, on stdout.
154fn ffmpeg_args(input: &FfmpegInput<'_>, o: &FfmpegOptions) -> Result<Vec<OsString>> {
155    if !(8..=256).contains(&o.bitrate_kbps) {
156        return Err(Error::Audio("bitrate_kbps must be 8 to 256".into()));
157    }
158    let mut a: Vec<OsString> = ["-hide_banner", "-loglevel", "error"]
159        .iter()
160        .map(Into::into)
161        .collect();
162    if !matches!(input, FfmpegInput::Pipe | FfmpegInput::Pcm) {
163        a.push("-nostdin".into());
164    }
165    if let Some(seek) = o.seek {
166        a.push("-ss".into());
167        a.push(format!("{:.3}", seek.as_secs_f64()).into());
168    }
169    let (protocols, source): (&str, OsString) = match input {
170        // `file:` keeps a name that starts with `-` from being read as an option.
171        FfmpegInput::File(p) => {
172            let mut s = OsString::from("file:");
173            s.push(p.as_os_str());
174            ("file", s)
175        }
176        FfmpegInput::Url(u) => ("http,https,tls,tcp", (*u).into()),
177        FfmpegInput::Pipe => ("pipe", "pipe:0".into()),
178        FfmpegInput::Pcm => {
179            for s in ["-f", "s16le", "-ar", "48000", "-ac", "2"] {
180                a.push(s.into());
181            }
182            ("pipe", "pipe:0".into())
183        }
184    };
185    a.extend([
186        "-protocol_whitelist".into(),
187        protocols.into(),
188        "-i".into(),
189        source,
190    ]);
191    for s in [
192        "-vn",
193        "-map",
194        "0:a:0",
195        "-ac",
196        "2",
197        "-ar",
198        "48000",
199        "-c:a",
200        "libopus",
201        "-application",
202        "audio",
203        "-frame_duration",
204        "20",
205        "-b:a",
206    ] {
207        a.push(s.into());
208    }
209    a.push(format!("{}k", o.bitrate_kbps).into());
210    if let Some(v) = o.volume {
211        if !(0.0..=4.0).contains(&v) {
212            return Err(Error::Audio("volume must be 0.0 to 4.0".into()));
213        }
214        a.push("-af".into());
215        a.push(format!("volume={v:.3}").into());
216    }
217    for s in [
218        "-f",
219        "ogg",
220        "-page_duration",
221        "20000",
222        "-flush_packets",
223        "1",
224        "pipe:1",
225    ] {
226        a.push(s.into());
227    }
228    Ok(a)
229}
230
231/// Whether the file begins as an Ogg Opus stream: an Ogg page whose first packet is `OpusHead`.
232fn is_ogg_opus(path: &Path) -> bool {
233    let mut head = [0u8; 64];
234    let Ok(mut f) = std::fs::File::open(path) else {
235        return false;
236    };
237    if f.read_exact(&mut head).is_err() || &head[..4] != b"OggS" || head[5] & 0x02 == 0 {
238        return false;
239    }
240    let body = 27 + usize::from(head[26]);
241    head.get(body..body + 8) == Some(&b"OpusHead"[..])
242}
243
244enum Source {
245    Ogg(OggOpus<Box<dyn Read + Send>>),
246    Packets(Box<dyn Iterator<Item = Vec<u8>> + Send>),
247    Ffmpeg {
248        child: Child,
249        ogg: OggOpus<ChildStdout>,
250        feeder: Option<JoinHandle<()>>,
251    },
252}
253
254/// Something to play: Opus packets, from an Ogg Opus file or stream, from ffmpeg (any format
255/// it reads), or from the application.
256pub struct AudioResource {
257    title: Option<String>,
258    source: Source,
259}
260
261impl fmt::Debug for AudioResource {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        let kind = match self.source {
264            Source::Ogg(_) => "ogg",
265            Source::Packets(_) => "packets",
266            Source::Ffmpeg { .. } => "ffmpeg",
267        };
268        f.debug_struct("AudioResource")
269            .field("title", &self.title)
270            .field("source", &kind)
271            .finish()
272    }
273}
274
275impl AudioResource {
276    /// An Ogg Opus stream (`.opus`, or `.ogg` holding Opus), sent as it is.
277    pub fn ogg(reader: impl Read + Send + 'static) -> Self {
278        Self {
279            title: None,
280            source: Source::Ogg(OggOpus::new(Box::new(reader))),
281        }
282    }
283
284    /// An Ogg Opus file, sent as it is; titled with its file name.
285    ///
286    /// # Errors
287    /// [`Error::Audio`] when the file cannot be opened.
288    pub fn ogg_file(path: impl AsRef<Path>) -> Result<Self> {
289        let path = path.as_ref();
290        let file = std::fs::File::open(path)
291            .map_err(|e| Error::Audio(format!("cannot open the file: {}", e.kind())))?;
292        Ok(Self::ogg(io::BufReader::new(file)).titled_from(path))
293    }
294
295    /// Opus packets the application made (each one 2.5 to 120 ms, as its TOC byte says).
296    pub fn opus_packets(
297        packets: impl IntoIterator<Item = Vec<u8>, IntoIter: Send + 'static>,
298    ) -> Self {
299        Self {
300            title: None,
301            source: Source::Packets(Box::new(packets.into_iter())),
302        }
303    }
304
305    /// Any audio file ffmpeg reads (mp3, flac, wav, m4a, a video's sound…), transcoded to Opus.
306    ///
307    /// # Errors
308    /// [`Error::Audio`] when the file is missing, an option is out of range, or ffmpeg is not
309    /// installed.
310    pub fn ffmpeg_file(path: impl AsRef<Path>, options: FfmpegOptions) -> Result<Self> {
311        let path = path.as_ref();
312        if !path.is_file() {
313            return Err(Error::Audio("no such file".into()));
314        }
315        let path = std::path::absolute(path)
316            .map_err(|e| Error::Audio(format!("cannot resolve the path: {}", e.kind())))?;
317        Ok(Self::spawn(&FfmpegInput::File(&path), &options, None)?.titled_from(&path))
318    }
319
320    /// An `http://` or `https://` stream or file, fetched and transcoded by ffmpeg.
321    ///
322    /// # Errors
323    /// [`Error::Audio`] for another scheme, an option out of range, or no ffmpeg.
324    pub fn ffmpeg_url(url: &str, options: FfmpegOptions) -> Result<Self> {
325        if !(url.starts_with("https://") || url.starts_with("http://")) {
326            return Err(Error::Audio(
327                "only http:// and https:// URLs are played".into(),
328            ));
329        }
330        Self::spawn(&FfmpegInput::Url(url), &options, None)
331    }
332
333    /// Audio the application streams (another program's output, a download), transcoded by
334    /// ffmpeg as it arrives.
335    ///
336    /// # Errors
337    /// [`Error::Audio`] for an option out of range, or no ffmpeg.
338    pub fn ffmpeg_reader(
339        reader: impl Read + Send + 'static,
340        options: FfmpegOptions,
341    ) -> Result<Self> {
342        Self::spawn(&FfmpegInput::Pipe, &options, Some(Box::new(reader)))
343    }
344
345    /// Raw PCM the application makes (text to speech, a synthesiser): signed 16-bit
346    /// little-endian samples, 48 kHz, two channels interleaved. Encoded to Opus by ffmpeg.
347    ///
348    /// # Errors
349    /// [`Error::Audio`] for an option out of range, or no ffmpeg.
350    pub fn pcm(reader: impl Read + Send + 'static, options: FfmpegOptions) -> Result<Self> {
351        Self::spawn(&FfmpegInput::Pcm, &options, Some(Box::new(reader)))
352    }
353
354    /// Any audio file: an Ogg Opus file is sent as it is (no ffmpeg, no quality lost, like
355    /// discord.js's `demuxProbe`), anything else goes through ffmpeg. `options` apply only
356    /// when ffmpeg runs; a volume or seek asks for it even for Ogg Opus.
357    ///
358    /// # Errors
359    /// As [`ogg_file`](Self::ogg_file) and [`ffmpeg_file`](Self::ffmpeg_file).
360    pub fn file(path: impl AsRef<Path>, options: FfmpegOptions) -> Result<Self> {
361        let path = path.as_ref();
362        if options.volume.is_none() && options.seek.is_none() && is_ogg_opus(path) {
363            Self::ogg_file(path)
364        } else {
365            Self::ffmpeg_file(path, options)
366        }
367    }
368
369    fn spawn(
370        input: &FfmpegInput<'_>,
371        options: &FfmpegOptions,
372        feed: Option<Box<dyn Read + Send>>,
373    ) -> Result<Self> {
374        let args = ffmpeg_args(input, options)?;
375        let mut child = Command::new(&options.program)
376            .args(&args)
377            .stdin(if feed.is_some() {
378                Stdio::piped()
379            } else {
380                Stdio::null()
381            })
382            .stdout(Stdio::piped())
383            // Never read, so never full: a piped stderr could stall ffmpeg.
384            .stderr(Stdio::null())
385            .spawn()
386            .map_err(|e| match e.kind() {
387                io::ErrorKind::NotFound => {
388                    Error::Audio("ffmpeg is not installed (or not on PATH)".into())
389                }
390                k => Error::Audio(format!("ffmpeg did not start: {k}")),
391            })?;
392        let stdout = child
393            .stdout
394            .take()
395            .ok_or_else(|| Error::Audio("ffmpeg: no stdout".into()))?;
396        let feeder = match (feed, child.stdin.take()) {
397            (Some(mut from), Some(mut to)) => Some(
398                std::thread::Builder::new()
399                    .name("zaun-audio-feed".into())
400                    .spawn(move || {
401                        // Ends when the input ends or ffmpeg is gone.
402                        let _ = io::copy(&mut from, &mut to);
403                    })
404                    .map_err(|e| Error::Audio(format!("thread: {e}")))?,
405            ),
406            _ => None,
407        };
408        Ok(Self {
409            title: None,
410            source: Source::Ffmpeg {
411                child,
412                ogg: OggOpus::new(stdout),
413                feeder,
414            },
415        })
416    }
417
418    /// Names the resource (the events carry it).
419    #[must_use]
420    pub fn with_title(mut self, title: impl Into<String>) -> Self {
421        self.title = Some(title.into());
422        self
423    }
424
425    fn titled_from(mut self, path: &Path) -> Self {
426        self.title = path.file_name().map(|n| n.to_string_lossy().into_owned());
427        self
428    }
429
430    /// The title, if any.
431    #[must_use]
432    pub fn title(&self) -> Option<&str> {
433        self.title.as_deref()
434    }
435
436    /// The next packet, `None` at the end.
437    fn next_packet(&mut self) -> io::Result<Option<Vec<u8>>> {
438        match &mut self.source {
439            Source::Ogg(o) => o.next_packet(),
440            Source::Packets(p) => Ok(p.next()),
441            Source::Ffmpeg { ogg, .. } => ogg.next_packet(),
442        }
443    }
444}
445
446impl Drop for AudioResource {
447    fn drop(&mut self) {
448        if let Source::Ffmpeg { child, feeder, .. } = &mut self.source {
449            let _ = child.kill();
450            let _ = child.wait();
451            if let Some(f) = feeder.take() {
452                // The feeder's writes fail once ffmpeg is gone; a reader blocked on its input
453                // keeps the thread, not the player.
454                if f.is_finished() {
455                    let _ = f.join();
456                }
457            }
458        }
459    }
460}
461
462/// What the application asked for, picked up by the player thread.
463struct State {
464    status: AudioPlayerStatus,
465    paused: bool,
466    /// Replaces the current resource.
467    play: Option<AudioResource>,
468    queue: VecDeque<AudioResource>,
469    /// Ends the current resource.
470    end_current: bool,
471    subs: Vec<Sink>,
472    quit: bool,
473}
474
475struct Shared {
476    state: Mutex<State>,
477    wake: Condvar,
478    events: Sender<AudioPlayerEvent>,
479}
480
481impl Shared {
482    fn lock(&self) -> MutexGuard<'_, State> {
483        self.state.lock().unwrap_or_else(PoisonError::into_inner)
484    }
485}
486
487/// Plays [`AudioResource`]s, one at a time, into every subscribed voice session.
488pub struct AudioPlayer {
489    shared: Arc<Shared>,
490    events: Receiver<AudioPlayerEvent>,
491    thread: Option<JoinHandle<()>>,
492}
493
494impl fmt::Debug for AudioPlayer {
495    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496        f.debug_struct("AudioPlayer")
497            .field("status", &self.status())
498            .finish_non_exhaustive()
499    }
500}
501
502impl AudioPlayer {
503    /// A player, idle, with its own thread.
504    ///
505    /// # Errors
506    /// [`Error::Audio`] when the thread cannot start.
507    pub fn new() -> Result<Self> {
508        let (tx, events) = unbounded();
509        let shared = Arc::new(Shared {
510            state: Mutex::new(State {
511                status: AudioPlayerStatus::Idle,
512                paused: false,
513                play: None,
514                queue: VecDeque::new(),
515                end_current: false,
516                subs: Vec::new(),
517                quit: false,
518            }),
519            wake: Condvar::new(),
520            events: tx,
521        });
522        let run = Arc::clone(&shared);
523        let thread = std::thread::Builder::new()
524            .name("zaun-audio-player".into())
525            .spawn(move || Playback::new(run).run())
526            .map_err(|e| Error::Audio(format!("thread: {e}")))?;
527        Ok(Self {
528            shared,
529            events,
530            thread: Some(thread),
531        })
532    }
533
534    fn with(&self, f: impl FnOnce(&mut State)) {
535        f(&mut self.shared.lock());
536        self.shared.wake.notify_all();
537    }
538
539    /// Plays `resource` now, ending the current one; the queue stays.
540    pub fn play(&self, resource: AudioResource) {
541        self.with(|s| {
542            s.play = Some(resource);
543            s.paused = false;
544        });
545    }
546
547    /// Plays `resource` after the current one and those queued before it.
548    pub fn enqueue(&self, resource: AudioResource) {
549        self.with(|s| s.queue.push_back(resource));
550    }
551
552    /// Ends the current resource; the next queued one plays.
553    pub fn skip(&self) {
554        self.with(|s| s.end_current = true);
555    }
556
557    /// Ends the current resource and empties the queue: the player goes idle.
558    pub fn stop(&self) {
559        self.with(|s| {
560            s.end_current = true;
561            s.play = None;
562            s.queue.clear();
563            s.paused = false;
564        });
565    }
566
567    /// Pauses; `false` when there was nothing playing.
568    pub fn pause(&self) -> bool {
569        let mut was = false;
570        self.with(|s| {
571            was = matches!(
572                s.status,
573                AudioPlayerStatus::Playing | AudioPlayerStatus::AutoPaused
574            );
575            s.paused = was || s.paused;
576        });
577        was
578    }
579
580    /// Resumes after [`pause`](Self::pause); `false` when it was not paused.
581    pub fn unpause(&self) -> bool {
582        let mut was = false;
583        self.with(|s| {
584            was = s.paused;
585            s.paused = false;
586        });
587        was
588    }
589
590    /// What the player is doing.
591    #[must_use]
592    pub fn status(&self) -> AudioPlayerStatus {
593        self.shared.lock().status
594    }
595
596    /// Resources waiting after the current one.
597    #[must_use]
598    pub fn queue_len(&self) -> usize {
599        self.shared.lock().queue.len()
600    }
601
602    /// The next event, or `None` when none arrives within `timeout`.
603    #[must_use]
604    pub fn next_event(&self, timeout: Duration) -> Option<AudioPlayerEvent> {
605        self.events.recv_timeout(timeout).ok()
606    }
607
608    /// The events, blocking; ends when the player is dropped.
609    pub fn events(&self) -> impl Iterator<Item = AudioPlayerEvent> + Send + 'static {
610        self.events.clone().into_iter()
611    }
612
613    pub(crate) fn subscribe(&self, sink: Sink) {
614        self.with(|s| {
615            s.subs.retain(|x| x.session != sink.session);
616            s.subs.push(sink);
617        });
618    }
619
620    pub(crate) fn unsubscribe(&self, session: VoiceSessionId) {
621        self.with(|s| s.subs.retain(|x| x.session != session));
622    }
623}
624
625impl Drop for AudioPlayer {
626    fn drop(&mut self) {
627        self.with(|s| s.quit = true);
628        if let Some(t) = self.thread.take() {
629            let _ = t.join();
630        }
631    }
632}
633
634/// The player thread's own state.
635struct Playback {
636    shared: Arc<Shared>,
637    current: Option<AudioResource>,
638    next_at: Instant,
639    silence: u8,
640    warned_large: bool,
641}
642
643impl Playback {
644    fn new(shared: Arc<Shared>) -> Self {
645        Self {
646            shared,
647            current: None,
648            next_at: now(),
649            silence: 0,
650            warned_large: false,
651        }
652    }
653
654    fn emit(&self, e: AudioPlayerEvent) {
655        let _ = self.shared.events.send(e);
656    }
657
658    fn set_status(&self, s: &mut State, to: AudioPlayerStatus) {
659        if s.status != to {
660            let from = std::mem::replace(&mut s.status, to);
661            self.emit(AudioPlayerEvent::StateChange { from, to });
662        }
663    }
664
665    fn end_track(&mut self) {
666        if let Some(r) = self.current.take() {
667            self.silence = SILENCE_FRAMES;
668            let title = r.title.clone();
669            drop(r);
670            self.emit(AudioPlayerEvent::TrackEnd { title });
671        }
672    }
673
674    fn start_track(&mut self, r: AudioResource) {
675        self.end_track();
676        self.warned_large = false;
677        self.emit(AudioPlayerEvent::TrackStart {
678            title: r.title.clone(),
679        });
680        self.current = Some(r);
681        self.next_at = now();
682    }
683
684    fn run(mut self) {
685        loop {
686            let subs = {
687                let shared = Arc::clone(&self.shared);
688                let mut s = shared.lock();
689                if s.quit {
690                    break;
691                }
692                if std::mem::take(&mut s.end_current) {
693                    self.end_track();
694                }
695                if let Some(r) = s.play.take() {
696                    self.start_track(r);
697                }
698                if self.current.is_none()
699                    && self.silence == 0
700                    && let Some(r) = s.queue.pop_front()
701                {
702                    self.start_track(r);
703                }
704                let audible = s.subs.iter().any(|x| x.can_send.load(Ordering::Relaxed));
705                let status = match (&self.current, s.paused, audible) {
706                    (None, ..) => AudioPlayerStatus::Idle,
707                    (Some(_), true, _) => AudioPlayerStatus::Paused,
708                    (Some(_), false, false) => AudioPlayerStatus::AutoPaused,
709                    (Some(_), false, true) => AudioPlayerStatus::Playing,
710                };
711                if s.status == AudioPlayerStatus::Playing && status != AudioPlayerStatus::Playing {
712                    self.silence = self.silence.max(SILENCE_FRAMES);
713                }
714                self.set_status(&mut s, status);
715                // Wait for the next deadline, or for something to do.
716                let t = now();
717                let busy = status == AudioPlayerStatus::Playing || self.silence > 0;
718                if !busy || t < self.next_at {
719                    let wait = if busy {
720                        self.next_at - t
721                    } else {
722                        Duration::from_millis(250)
723                    };
724                    drop(shared.wake.wait_timeout(s, wait));
725                    continue;
726                }
727                if t > self.next_at + LATE {
728                    self.next_at = t;
729                }
730                s.subs.clone()
731            };
732            let packet = if self.silence > 0 {
733                self.silence -= 1;
734                Some(SILENCE.to_vec())
735            } else {
736                self.read()
737            };
738            let Some(packet) = packet else {
739                continue;
740            };
741            let samples = packet_samples(&packet).unwrap_or(960);
742            let mut gone = Vec::new();
743            for sub in &subs {
744                if sub.can_send.load(Ordering::Relaxed)
745                    && sub
746                        .input
747                        .send(Input::Audio {
748                            frame: packet.clone(),
749                            samples,
750                        })
751                        .is_err()
752                {
753                    gone.push(sub.session);
754                }
755            }
756            if !gone.is_empty() {
757                self.shared
758                    .lock()
759                    .subs
760                    .retain(|x| !gone.contains(&x.session));
761            }
762            self.next_at += Duration::from_micros(u64::from(samples) * 1_000_000 / RATE);
763        }
764        self.current = None;
765    }
766
767    /// The current resource's next packet to send, or `None` (ended, failed, or skipped).
768    fn read(&mut self) -> Option<Vec<u8>> {
769        let r = self.current.as_mut()?;
770        match r.next_packet() {
771            Ok(Some(p)) if packet_samples(&p).is_none() => {
772                let title = r.title.clone();
773                self.skipped(title, "a packet that is not Opus was skipped");
774                None
775            }
776            Ok(Some(p)) if p.len() > OPUS_PACKET_MAX => {
777                let title = r.title.clone();
778                self.skipped(title, "an Opus packet too large to send was skipped");
779                None
780            }
781            Ok(Some(p)) => Some(p),
782            Ok(None) => {
783                self.end_track();
784                None
785            }
786            Err(e) => {
787                let title = r.title.clone();
788                self.emit(AudioPlayerEvent::Error {
789                    title,
790                    error: e.to_string(),
791                });
792                self.end_track();
793                None
794            }
795        }
796    }
797
798    fn skipped(&mut self, title: Option<String>, why: &str) {
799        if !std::mem::replace(&mut self.warned_large, true) {
800            self.emit(AudioPlayerEvent::Error {
801                title,
802                error: why.into(),
803            });
804        }
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use super::*;
811
812    fn sink(n: u8) -> (Sink, Receiver<Input>, Arc<AtomicBool>) {
813        let (tx, rx) = unbounded();
814        let can = Arc::new(AtomicBool::new(true));
815        let s = Sink {
816            session: VoiceSessionId::from_bytes([n; 16]),
817            input: tx,
818            can_send: Arc::clone(&can),
819        };
820        (s, rx, can)
821    }
822
823    fn frames(rx: &Receiver<Input>, within: Duration) -> Vec<(Vec<u8>, Instant)> {
824        let end = now() + within;
825        let mut out = Vec::new();
826        while let Ok(i) = rx.recv_timeout(end.saturating_duration_since(now())) {
827            if let Input::Audio { frame, .. } = i {
828                out.push((frame, now()));
829            }
830        }
831        out
832    }
833
834    fn numbered(n: u16) -> AudioResource {
835        AudioResource::opus_packets((0..n).map(|i| {
836            let [a, b] = i.to_be_bytes();
837            vec![0xfc, a, b]
838        }))
839    }
840
841    fn until(p: &AudioPlayer, want: impl Fn(&AudioPlayerEvent) -> bool) -> bool {
842        while let Some(e) = p.next_event(Duration::from_secs(3)) {
843            if want(&e) {
844                return true;
845            }
846        }
847        false
848    }
849
850    #[test]
851    fn packets_go_out_in_order_in_real_time_then_silence_and_idle() {
852        let player = AudioPlayer::new().unwrap();
853        let (s, rx, _) = sink(1);
854        player.subscribe(s);
855        player.play(numbered(25).with_title("tone"));
856        let got = frames(&rx, Duration::from_millis(900));
857        let sound: Vec<_> = got.iter().filter(|(f, _)| f[0] == 0xfc).collect();
858        assert_eq!(sound.len(), 25);
859        for (i, (f, _)) in sound.iter().enumerate() {
860            assert_eq!(u16::from_be_bytes([f[1], f[2]]), u16::try_from(i).unwrap());
861        }
862        // 24 intervals of 20 ms: about 480 ms, not a burst.
863        let span = sound[24].1 - sound[0].1;
864        assert!(
865            span >= Duration::from_millis(440) && span <= Duration::from_millis(700),
866            "{span:?}"
867        );
868        assert_eq!(got.iter().filter(|(f, _)| f[..] == SILENCE).count(), 5);
869        assert!(until(
870            &player,
871            |e| matches!(e, AudioPlayerEvent::TrackEnd { title } if title.as_deref() == Some("tone"))
872        ));
873        assert!(until(&player, |e| *e
874            == AudioPlayerEvent::StateChange {
875                from: AudioPlayerStatus::Playing,
876                to: AudioPlayerStatus::Idle
877            }));
878    }
879
880    #[test]
881    fn pause_and_muted_subscribers_hold_the_track_and_the_queue_plays_in_order() {
882        let player = AudioPlayer::new().unwrap();
883        let (s, rx, can) = sink(1);
884        // Nobody can hear: auto-paused, nothing consumed.
885        can.store(false, Ordering::Relaxed);
886        player.subscribe(s);
887        player.play(numbered(10).with_title("one"));
888        player.enqueue(numbered(3).with_title("two"));
889        assert!(until(&player, |e| matches!(
890            e,
891            AudioPlayerEvent::StateChange {
892                to: AudioPlayerStatus::AutoPaused,
893                ..
894            }
895        )));
896        assert!(frames(&rx, Duration::from_millis(150)).is_empty());
897        can.store(true, Ordering::Relaxed);
898        assert!(player.pause());
899        assert!(until(&player, |e| matches!(
900            e,
901            AudioPlayerEvent::StateChange {
902                to: AudioPlayerStatus::Paused,
903                ..
904            }
905        )));
906        assert!(frames(&rx, Duration::from_millis(150)).is_empty());
907        assert!(player.unpause());
908        let got = frames(&rx, Duration::from_millis(800));
909        let sound: Vec<u16> = got
910            .iter()
911            .filter(|(f, _)| f[0] == 0xfc)
912            .map(|(f, _)| u16::from_be_bytes([f[1], f[2]]))
913            .collect();
914        assert_eq!(sound, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
915        assert_eq!(player.queue_len(), 0);
916    }
917
918    #[test]
919    fn stop_skip_and_a_gone_session_are_handled() {
920        let player = AudioPlayer::new().unwrap();
921        let (s, rx, _) = sink(1);
922        player.subscribe(s);
923        player.play(numbered(1_000));
924        player.enqueue(numbered(1_000));
925        assert!(!frames(&rx, Duration::from_millis(100)).is_empty());
926        player.skip();
927        assert!(until(&player, |e| matches!(
928            e,
929            AudioPlayerEvent::TrackStart { .. }
930        )));
931        player.stop();
932        assert!(until(&player, |e| matches!(
933            e,
934            AudioPlayerEvent::StateChange {
935                to: AudioPlayerStatus::Idle,
936                ..
937            }
938        )));
939        assert_eq!(player.queue_len(), 0);
940        // The session ended: the player forgets it.
941        drop(rx);
942        player.play(numbered(5));
943        std::thread::sleep(Duration::from_millis(200));
944        assert!(player.shared.lock().subs.is_empty());
945        // Oversized and non-Opus packets are skipped, with one error.
946        let (s, rx, _) = sink(2);
947        player.subscribe(s);
948        player.play(AudioResource::opus_packets(vec![
949            vec![0xfc; OPUS_PACKET_MAX + 1],
950            vec![],
951            vec![0xfc, 0, 7],
952        ]));
953        assert!(until(&player, |e| matches!(
954            e,
955            AudioPlayerEvent::Error { .. }
956        )));
957        let got = frames(&rx, Duration::from_millis(300));
958        assert!(got.iter().any(|(f, _)| f[..] == [0xfc, 0, 7]));
959        assert!(got.iter().all(|(f, _)| f.len() <= OPUS_PACKET_MAX));
960    }
961
962    #[test]
963    fn ffmpeg_gets_a_fixed_argument_list_and_inputs_cannot_become_options() {
964        let o = FfmpegOptions {
965            volume: Some(0.5),
966            seek: Some(Duration::from_millis(1_500)),
967            ..FfmpegOptions::default()
968        };
969        let a = ffmpeg_args(&FfmpegInput::File(Path::new("-y")), &o).unwrap();
970        let a: Vec<String> = a.iter().map(|s| s.to_string_lossy().into_owned()).collect();
971        let at = a.iter().position(|s| s == "-i").unwrap();
972        assert_eq!(a[at + 1], "file:-y");
973        assert_eq!(a[at - 1], "file");
974        assert!(a.contains(&"-nostdin".to_owned()) && a.contains(&"volume=0.500".to_owned()));
975        assert!(a.contains(&"1.500".to_owned()) && a.contains(&"128k".to_owned()));
976        assert_eq!(a.last().map(String::as_str), Some("pipe:1"));
977        let u = ffmpeg_args(
978            &FfmpegInput::Url("https://example.org/a.mp3"),
979            &FfmpegOptions::default(),
980        )
981        .unwrap();
982        assert!(u.iter().any(|s| s == "http,https,tls,tcp"));
983        let p = ffmpeg_args(&FfmpegInput::Pipe, &FfmpegOptions::default()).unwrap();
984        assert!(!p.iter().any(|s| s == "-nostdin") && p.iter().any(|s| s == "pipe:0"));
985        for bad in [
986            FfmpegOptions {
987                bitrate_kbps: 0,
988                ..FfmpegOptions::default()
989            },
990            FfmpegOptions {
991                bitrate_kbps: 512,
992                ..FfmpegOptions::default()
993            },
994            FfmpegOptions {
995                volume: Some(9.0),
996                ..FfmpegOptions::default()
997            },
998            FfmpegOptions {
999                volume: Some(f32::NAN),
1000                ..FfmpegOptions::default()
1001            },
1002        ] {
1003            assert!(ffmpeg_args(&FfmpegInput::Pipe, &bad).is_err());
1004        }
1005        let pcm = ffmpeg_args(&FfmpegInput::Pcm, &FfmpegOptions::default()).unwrap();
1006        let pcm: Vec<String> = pcm
1007            .iter()
1008            .map(|s| s.to_string_lossy().into_owned())
1009            .collect();
1010        let at = pcm.iter().position(|s| s == "-i").unwrap();
1011        assert_eq!(
1012            pcm[at - 8..at - 2],
1013            ["-f", "s16le", "-ar", "48000", "-ac", "2"]
1014        );
1015        assert!(AudioResource::ffmpeg_url("file:///etc/passwd", FfmpegOptions::default()).is_err());
1016        assert!(AudioResource::ffmpeg_file("/no/such/file.mp3", FfmpegOptions::default()).is_err());
1017        let missing = FfmpegOptions {
1018            program: PathBuf::from("/no/such/ffmpeg"),
1019            ..FfmpegOptions::default()
1020        };
1021        match AudioResource::ffmpeg_reader(io::empty(), missing) {
1022            Err(Error::Audio(t)) => assert!(t.contains("not installed"), "{t}"),
1023            other => panic!("{other:?}"),
1024        }
1025    }
1026
1027    #[test]
1028    fn a_file_is_probed_for_ogg_opus() {
1029        let dir = tempfile::tempdir().unwrap();
1030        let opus = dir.path().join("a.opus");
1031        std::fs::write(&opus, super::super::ogg::tests::stream(1, 40)).unwrap();
1032        let wav = dir.path().join("b.wav");
1033        std::fs::write(&wav, [b"RIFF".as_slice(), &[0; 60]].concat()).unwrap();
1034        assert!(is_ogg_opus(&opus));
1035        assert!(!is_ogg_opus(&wav));
1036        assert!(!is_ogg_opus(&dir.path().join("missing")));
1037        let r = AudioResource::file(&opus, FfmpegOptions::default()).unwrap();
1038        assert!(matches!(r.source, Source::Ogg(_)) && r.title() == Some("a.opus"));
1039    }
1040
1041    #[test]
1042    fn an_ogg_resource_plays_its_packets() {
1043        let player = AudioPlayer::new().unwrap();
1044        let (s, rx, _) = sink(1);
1045        player.subscribe(s);
1046        player.play(AudioResource::ogg(io::Cursor::new(
1047            super::super::ogg::tests::stream(3, 4),
1048        )));
1049        let got = frames(&rx, Duration::from_millis(400));
1050        let sound: Vec<_> = got
1051            .iter()
1052            .filter(|(f, _)| f[0] == 0xfc)
1053            .map(|(f, _)| f[1])
1054            .collect();
1055        assert_eq!(sound, [0, 1, 2, 3]);
1056    }
1057}