Skip to main content

djs_voice/
input.rs

1//! What a track plays (D-317, D-323, D-338, D-354): Ogg/Opus from a file or any
2//! [`AsyncRead`], raw PCM, and anything FFmpeg reads.
3//!
4//! A track's reader task reads its input ahead into raw frames, Opus packets or 20 ms blocks
5//! of PCM, which the call's task turns into packets when they are due (C-126). The inputs
6//! that can be opened again, a file and FFmpeg, loop and seek (D-358–D-360).
7
8use core::fmt;
9use std::{
10    ffi::{OsStr, OsString},
11    io,
12    path::{Path, PathBuf},
13    process::Stdio,
14};
15
16use tokio::{
17    io::{AsyncRead, AsyncReadExt},
18    process::Command,
19    sync::mpsc,
20};
21
22use crate::{InputError, codec::FRAME_BYTES, ogg::OggOpus, opus};
23
24/// How many bytes of an Ogg input are read at a time.
25const CHUNK: usize = 16 * 1024;
26/// How much of FFmpeg's standard error is kept for [`InputError::Ffmpeg`].
27const STDERR_TAIL: usize = 4 * 1024;
28/// The lines of FFmpeg's standard error an [`InputError::Ffmpeg`] shows.
29const STDERR_LINES: usize = 4;
30/// The program `Input::ffmpeg` runs, from `PATH`.
31const FFMPEG: &str = "ffmpeg";
32/// How much of an input's audio before the place a new decoder starts at (a seek's, or where
33/// re-encoding starts) it decodes first, so that it has settled there: 400 ms. RFC 7845
34/// (section 4.2) asks for at least 80 ms; the SILK, hybrid and CELT packets measured here
35/// needed up to 240 ms before their level was right (C-127).
36const PREROLL: u64 = 19_200;
37
38/// What a track plays, given to [`Call::play`](crate::Call::play) or
39/// [`Call::enqueue`](crate::Call::enqueue).
40///
41/// - **Ogg/Opus** (`.opus` and `.ogg` files with Opus inside, as `ffmpeg -c:a libopus` or
42///   `opusenc` make them), from a file ([`ogg_file`](Self::ogg_file)) or from any
43///   [`AsyncRead`] ([`ogg`](Self::ogg)): a pipe, a socket, an HTTP body, memory. At volume
44///   1.0 its packets are sent as they are, without decoding: Discord wants 48 kHz Opus,
45///   which Ogg/Opus always is.
46/// - **Raw PCM** ([`pcm`](Self::pcm)): 16-bit little-endian, 48 kHz, interleaved stereo,
47///   encoded to Opus by the call.
48/// - **Anything FFmpeg reads** ([`ffmpeg`](Self::ffmpeg)): MP3, FLAC, WAV, AAC, video files,
49///   HTTP(S) URLs, … FFmpeg must be installed; it decodes, djs-voice encodes.
50///
51/// The input is read ahead of playback, at most about a second, so a slow source makes the
52/// track skip rather than the call stall. A track from a file or FFmpeg can loop
53/// ([`TrackHandle::set_loop`](crate::TrackHandle::set_loop)) and seek
54/// ([`TrackHandle::seek`](crate::TrackHandle::seek)), as they can be opened again; a track
55/// from a reader cannot (D-360).
56///
57/// discord.js counterpart: `createAudioResource` of `@discordjs/voice`; songbird: `Input`.
58///
59/// # Examples
60///
61/// ```no_run
62/// # async fn run(call: djs_voice::Call) -> Result<(), djs_voice::InputError> {
63/// use djs_voice::Input;
64///
65/// call.play(Input::ogg_file("music/intro.opus").await?);
66/// call.enqueue(Input::ffmpeg("music/song.mp3"));
67/// # Ok(()) }
68/// ```
69pub struct Input {
70    source: Source,
71    again: Option<Again>,
72}
73
74/// What an input reads.
75pub(crate) enum Source {
76    Ogg {
77        reader: Box<dyn AsyncRead + Send + Unpin>,
78        ogg: Box<OggOpus>,
79        /// The first audio packet, read while checking the input.
80        first: Option<Vec<u8>>,
81    },
82    OggFile(PathBuf),
83    Pcm(Box<dyn AsyncRead + Send + Unpin>),
84    Ffmpeg {
85        program: OsString,
86        source: OsString,
87    },
88}
89
90/// How to open an input again, for loops and seeking.
91#[derive(Clone)]
92pub(crate) enum Again {
93    OggFile(PathBuf),
94    Ffmpeg { program: OsString, source: OsString },
95}
96
97impl Again {
98    pub(crate) fn source(&self) -> Source {
99        match self {
100            Self::OggFile(path) => Source::OggFile(path.clone()),
101            Self::Ffmpeg { program, source } => Source::Ffmpeg {
102                program: program.clone(),
103                source: source.clone(),
104            },
105        }
106    }
107}
108
109impl fmt::Debug for Input {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        // No path or URL: a URL may carry a signature.
112        f.write_str(match (&self.source, &self.again) {
113            (Source::Ogg { .. } | Source::OggFile(_), Some(_)) => "Input::OggFile",
114            (Source::Ogg { .. } | Source::OggFile(_), None) => "Input::Ogg",
115            (Source::Pcm(_), _) => "Input::Pcm",
116            (Source::Ffmpeg { .. }, _) => "Input::Ffmpeg",
117        })
118    }
119}
120
121/// An audio frame read ahead.
122#[derive(Debug)]
123pub(crate) enum Frame {
124    /// An Opus packet, and how long it lasts (samples per channel at 48 kHz).
125    Opus { data: Vec<u8>, samples: u32 },
126    /// 20 ms of s16le stereo PCM ([`FRAME_BYTES`]).
127    Pcm(Vec<u8>),
128}
129
130impl Frame {
131    /// How long the frame lasts: samples per channel at 48 kHz.
132    pub(crate) fn samples(&self) -> u32 {
133        match self {
134            Self::Opus { samples, .. } => *samples,
135            Self::Pcm(_) => 960,
136        }
137    }
138}
139
140/// The last 400 ms of an input's Opus packets ([`PREROLL`]): a new decoder decodes them
141/// first, so that it starts where the listeners' decoders are (C-127).
142#[derive(Debug, Default)]
143pub(crate) struct History {
144    packets: std::collections::VecDeque<(Vec<u8>, u32)>,
145    samples: u64,
146}
147
148impl History {
149    /// Adds the next packet, of `samples` per channel, and drops the oldest ones no longer
150    /// needed.
151    pub(crate) fn push(&mut self, data: Vec<u8>, samples: u32) {
152        self.samples += u64::from(samples);
153        self.packets.push_back((data, samples));
154        while let Some((_, oldest)) = self.packets.front()
155            && self.samples - u64::from(*oldest) >= PREROLL
156        {
157            self.samples -= u64::from(*oldest);
158            self.packets.pop_front();
159        }
160    }
161
162    pub(crate) fn clear(&mut self) {
163        self.packets.clear();
164        self.samples = 0;
165    }
166
167    pub(crate) fn is_empty(&self) -> bool {
168        self.packets.is_empty()
169    }
170
171    #[cfg(test)]
172    pub(crate) fn len(&self) -> usize {
173        self.packets.len()
174    }
175
176    /// The packets, oldest first.
177    pub(crate) fn packets(&self) -> impl Iterator<Item = &[u8]> {
178        self.packets.iter().map(|(data, _)| &data[..])
179    }
180}
181
182/// What a reader sends the player.
183#[derive(Debug)]
184pub(crate) enum Chunk {
185    /// The Opus packets just before a seek's position: to decode, not to play.
186    Preroll(History),
187    /// Where the audio that follows starts, for a read that started past the beginning: the
188    /// position (samples per channel) asked for, or the start of the frame holding it.
189    Start(u64),
190    Frame(Frame),
191}
192
193/// Where a reader sends its chunks; an error is the last thing it sends.
194pub(crate) type Chunks = mpsc::Sender<Result<Chunk, InputError>>;
195
196impl Input {
197    /// Ogg/Opus audio read from `reader`.
198    ///
199    /// Nothing is read until the track plays; an input that turns out not to be Ogg/Opus
200    /// (or fails to read) ends its track then. [`ogg_file`](Self::ogg_file) checks a file at
201    /// once. The track cannot loop or seek (D-360).
202    ///
203    /// discord.js counterpart: `createAudioResource(stream, { inputType: StreamType.OggOpus })`.
204    ///
205    /// # Examples
206    ///
207    /// ```no_run
208    /// # async fn download() -> Vec<u8> { Vec::new() }
209    /// # async fn run(call: djs_voice::Call) {
210    /// use djs_voice::Input;
211    ///
212    /// // Any `AsyncRead`: here bytes already in memory.
213    /// let bytes: Vec<u8> = download().await;
214    /// call.play(Input::ogg(std::io::Cursor::new(bytes)));
215    /// # }
216    /// ```
217    #[must_use]
218    pub fn ogg(reader: impl AsyncRead + Send + Unpin + 'static) -> Self {
219        Self {
220            source: Source::Ogg {
221                reader: Box::new(reader),
222                ogg: Box::new(OggOpus::new()),
223                first: None,
224            },
225            again: None,
226        }
227    }
228
229    /// Ogg/Opus audio from the file at `path`, opened and checked now: the result is an
230    /// error if it cannot be read or does not start like Ogg/Opus. The track can loop and
231    /// seek: the file is opened again for them.
232    ///
233    /// discord.js counterpart: `createAudioResource(createReadStream(path), { inputType:
234    /// StreamType.OggOpus })`.
235    ///
236    /// # Errors
237    ///
238    /// [`InputError::Io`] when the file cannot be opened or read, [`InputError::NotOgg`] or
239    /// [`InputError::NotOpus`] when it is not Ogg/Opus.
240    ///
241    /// # Examples
242    ///
243    /// ```no_run
244    /// # async fn run(call: djs_voice::Call) -> Result<(), djs_voice::InputError> {
245    /// let track = call.play(djs_voice::Input::ogg_file("intro.opus").await?);
246    /// # Ok(()) }
247    /// ```
248    pub async fn ogg_file(path: impl AsRef<Path>) -> Result<Self, InputError> {
249        let path = path.as_ref();
250        let mut reader = tokio::fs::File::open(path).await?;
251        let mut ogg = Box::new(OggOpus::new());
252        let mut chunk = vec![0; CHUNK];
253        let first = loop {
254            if let Some(packet) = ogg.packet()? {
255                break Some(packet.to_vec());
256            }
257            let read = reader.read(&mut chunk).await?;
258            if read == 0 {
259                // An empty stream is still checked: `finish` makes the reader say whether
260                // it saw Ogg/Opus at all.
261                ogg.finish();
262                break ogg.packet()?.map(<[u8]>::to_vec);
263            }
264            ogg.push(&chunk[..read]);
265        };
266        Ok(Self {
267            source: Source::Ogg {
268                reader: Box::new(reader),
269                ogg,
270                first,
271            },
272            again: Some(Again::OggFile(path.to_path_buf())),
273        })
274    }
275
276    /// Raw PCM read from `reader`: 16-bit signed little-endian samples, 48 kHz, two
277    /// interleaved channels (left, right), as `ffmpeg -f s16le -ar 48000 -ac 2` writes it.
278    /// The call encodes it to Opus; a last frame shorter than 20 ms is completed with
279    /// silence. The track cannot loop or seek (D-360).
280    ///
281    /// discord.js counterpart: `createAudioResource(stream, { inputType: StreamType.Raw })`.
282    ///
283    /// # Examples
284    ///
285    /// ```no_run
286    /// # async fn run(call: djs_voice::Call) {
287    /// // One second of silence: 48 000 samples × 2 channels × 2 bytes.
288    /// let silence = vec![0_u8; 192_000];
289    /// call.play(djs_voice::Input::pcm(std::io::Cursor::new(silence)));
290    /// # }
291    /// ```
292    #[must_use]
293    pub fn pcm(reader: impl AsyncRead + Send + Unpin + 'static) -> Self {
294        Self {
295            source: Source::Pcm(Box::new(reader)),
296            again: None,
297        }
298    }
299
300    /// Anything FFmpeg can read: a file path or a URL (`https://…`, with reconnection on
301    /// errors), in any format it decodes; video files play their audio.
302    ///
303    /// `ffmpeg` is run from `PATH` when the track starts to play (not now, so a queue of
304    /// tracks does not run a program for each), and killed when the track ends. Its errors
305    /// end the track ([`TrackEnd::Failed`](crate::TrackEnd::Failed)): no program
306    /// ([`InputError::FfmpegMissing`]), or a source it cannot read
307    /// ([`InputError::Ffmpeg`]). The track can loop and seek: FFmpeg is run again for them.
308    ///
309    /// discord.js counterpart: `createAudioResource(path)` (`StreamType.Arbitrary`, through
310    /// prism-media's FFmpeg); songbird: `File` and `HttpRequest` inputs.
311    ///
312    /// # Examples
313    ///
314    /// ```no_run
315    /// # fn run(call: djs_voice::Call) {
316    /// use djs_voice::Input;
317    ///
318    /// call.enqueue(Input::ffmpeg("music/song.mp3"));
319    /// call.enqueue(Input::ffmpeg("https://example.com/radio.aac"));
320    /// # }
321    /// ```
322    #[must_use]
323    pub fn ffmpeg(source: impl AsRef<OsStr>) -> Self {
324        let program = OsString::from(FFMPEG);
325        let source = source.as_ref().to_os_string();
326        Self {
327            source: Source::Ffmpeg {
328                program: program.clone(),
329                source: source.clone(),
330            },
331            again: Some(Again::Ffmpeg { program, source }),
332        }
333    }
334
335    /// What the input reads first, and how to open it again (`None` for a reader).
336    pub(crate) fn into_parts(self) -> (Source, Option<Again>) {
337        (self.source, self.again)
338    }
339
340    /// Whether the input can be opened again: its track loops and seeks.
341    pub(crate) fn seekable(&self) -> bool {
342        self.again.is_some()
343    }
344
345    /// An FFmpeg input running `program` instead of `ffmpeg`.
346    #[cfg(test)]
347    pub(crate) fn ffmpeg_with(program: &str, source: impl AsRef<OsStr>) -> Self {
348        let program = OsString::from(program);
349        let source = source.as_ref().to_os_string();
350        Self {
351            source: Source::Ffmpeg {
352                program: program.clone(),
353                source: source.clone(),
354            },
355            again: Some(Again::Ffmpeg { program, source }),
356        }
357    }
358}
359
360/// Reads `source` from `start` (samples per channel) into `chunks`, until its end, an error
361/// (sent last), or the receiver is dropped.
362pub(crate) async fn read(source: Source, start: u64, chunks: Chunks) {
363    let result = match source {
364        Source::Ogg { reader, ogg, first } => read_ogg(reader, ogg, first, start, &chunks).await,
365        Source::OggFile(path) => match tokio::fs::File::open(path).await {
366            Ok(file) => read_ogg(Box::new(file), Box::default(), None, start, &chunks).await,
367            Err(error) => Err(error.into()),
368        },
369        Source::Pcm(reader) => read_pcm(reader, None, &chunks).await.map(drop),
370        Source::Ffmpeg { program, source } => ffmpeg(&program, &source, start, &chunks).await,
371    };
372    if let Err(error) = result {
373        let _ = chunks.send(Err(error)).await;
374    }
375}
376
377/// Where an Ogg read is, before `start`: packets are skipped (without decoding) until the one
378/// holding it, keeping the last 400 ms of them for the decoder ([`Chunk::Preroll`]).
379struct Skip {
380    start: u64,
381    at: u64,
382    preroll: History,
383}
384
385impl Skip {
386    const fn new(start: u64) -> Self {
387        Self {
388            start,
389            at: 0,
390            preroll: History {
391                packets: std::collections::VecDeque::new(),
392                samples: 0,
393            },
394        }
395    }
396
397    /// Whether the packet `data` of `samples` that comes next is played: the first one
398    /// that is played after a skip sends [`Chunk::Preroll`] and [`Chunk::Start`] first.
399    async fn keep(&mut self, data: &[u8], samples: u32, chunks: &Chunks) -> Option<bool> {
400        if self.start == 0 {
401            return Some(true);
402        }
403        if self.at + u64::from(samples) <= self.start {
404            self.at += u64::from(samples);
405            self.preroll.push(data.to_vec(), samples);
406            return Some(false);
407        }
408        let at = self.at;
409        self.start = 0;
410        let preroll = core::mem::take(&mut self.preroll);
411        if !preroll.is_empty() {
412            chunks.send(Ok(Chunk::Preroll(preroll))).await.ok()?;
413        }
414        chunks.send(Ok(Chunk::Start(at))).await.ok()?;
415        Some(true)
416    }
417}
418
419async fn read_ogg(
420    mut reader: Box<dyn AsyncRead + Send + Unpin>,
421    mut ogg: Box<OggOpus>,
422    first: Option<Vec<u8>>,
423    start: u64,
424    chunks: &Chunks,
425) -> Result<(), InputError> {
426    let mut skip = Skip::new(start);
427    if let Some(data) = first
428        && !forward(data, &mut skip, chunks).await
429    {
430        return Ok(());
431    }
432    let mut chunk = vec![0; CHUNK];
433    let mut ended = false;
434    loop {
435        while let Some(data) = ogg.packet()? {
436            let data = data.to_vec();
437            if !forward(data, &mut skip, chunks).await {
438                return Ok(());
439            }
440        }
441        if ended {
442            return Ok(());
443        }
444        let read = reader.read(&mut chunk).await?;
445        if read == 0 {
446            ogg.finish();
447            ended = true;
448        } else {
449            ogg.push(&chunk[..read]);
450        }
451    }
452}
453
454/// Sends an Opus packet to the player; `false` once the player no longer wants any.
455async fn forward(data: Vec<u8>, skip: &mut Skip, chunks: &Chunks) -> bool {
456    let Some(samples) = opus::packet_samples(&data) else {
457        tracing::debug!(len = data.len(), "skipping a packet that is not Opus");
458        return true;
459    };
460    match skip.keep(&data, samples, chunks).await {
461        Some(true) => chunks
462            .send(Ok(Chunk::Frame(Frame::Opus { data, samples })))
463            .await
464            .is_ok(),
465        Some(false) => true,
466        None => false,
467    }
468}
469
470/// Reads PCM in 20 ms frames, the last one completed with silence; sends
471/// [`Chunk::Start`]`(start)` before the first. Returns `false` once the player no longer
472/// wants any.
473async fn read_pcm(
474    mut reader: impl AsyncRead + Unpin,
475    mut start: Option<u64>,
476    chunks: &Chunks,
477) -> Result<bool, InputError> {
478    let mut frame = vec![0; FRAME_BYTES];
479    let mut filled = 0;
480    loop {
481        let read = reader.read(&mut frame[filled..]).await?;
482        filled += read;
483        if read != 0 && filled < FRAME_BYTES {
484            continue;
485        }
486        if filled == 0 {
487            return Ok(true);
488        }
489        // A short last frame: the rest is silence (zeros).
490        frame[filled..].fill(0);
491        if let Some(start) = start.take()
492            && chunks.send(Ok(Chunk::Start(start))).await.is_err()
493        {
494            return Ok(false);
495        }
496        let full = core::mem::replace(&mut frame, vec![0; FRAME_BYTES]);
497        if chunks
498            .send(Ok(Chunk::Frame(Frame::Pcm(full))))
499            .await
500            .is_err()
501        {
502            return Ok(false);
503        }
504        if read == 0 {
505            return Ok(true);
506        }
507        filled = 0;
508    }
509}
510
511/// Runs FFmpeg on `source` from `start` and reads its PCM (C-126).
512async fn ffmpeg(
513    program: &OsStr,
514    source: &OsStr,
515    start: u64,
516    chunks: &Chunks,
517) -> Result<(), InputError> {
518    let mut command = Command::new(program);
519    command.args(["-nostdin", "-hide_banner", "-loglevel", "error"]);
520    if start > 0 {
521        command.arg("-ss").arg(seconds(start));
522    }
523    if is_http(source) {
524        command.args([
525            "-reconnect",
526            "1",
527            "-reconnect_streamed",
528            "1",
529            "-reconnect_delay_max",
530            "5",
531        ]);
532    }
533    command
534        .arg("-i")
535        .arg(source)
536        .args(["-vn", "-f", "s16le", "-ar", "48000", "-ac", "2", "pipe:1"])
537        .stdin(Stdio::null())
538        .stdout(Stdio::piped())
539        .stderr(Stdio::piped())
540        .kill_on_drop(true);
541    let mut child = command.spawn().map_err(|error| match error.kind() {
542        io::ErrorKind::NotFound => InputError::FfmpegMissing,
543        _ => InputError::Io(error),
544    })?;
545    let stdout = child
546        .stdout
547        .take()
548        .ok_or_else(|| io::Error::other("FFmpeg's standard output is not piped"))?;
549    let stderr = child.stderr.take().map(|stderr| tokio::spawn(tail(stderr)));
550    if !read_pcm(stdout, (start > 0).then_some(start), chunks).await? {
551        // The track ended: dropping the child kills FFmpeg.
552        return Ok(());
553    }
554    let status = child.wait().await?;
555    if status.success() {
556        return Ok(());
557    }
558    let message = match stderr {
559        Some(task) => task.await.unwrap_or_default(),
560        None => String::new(),
561    };
562    Err(InputError::Ffmpeg {
563        code: status.code(),
564        message,
565    })
566}
567
568/// The last lines FFmpeg wrote to its standard error.
569async fn tail(mut stderr: impl AsyncRead + Unpin) -> String {
570    let mut kept = Vec::new();
571    let mut chunk = [0; 1024];
572    while let Ok(read @ 1..) = stderr.read(&mut chunk).await {
573        kept.extend_from_slice(&chunk[..read]);
574        if kept.len() > STDERR_TAIL {
575            kept.drain(..kept.len() - STDERR_TAIL);
576        }
577    }
578    let text = String::from_utf8_lossy(&kept);
579    let lines: Vec<&str> = text
580        .lines()
581        .map(str::trim)
582        .filter(|line| !line.is_empty())
583        .collect();
584    lines[lines.len().saturating_sub(STDERR_LINES)..].join("\n")
585}
586
587/// `samples` at 48 kHz as FFmpeg's seconds, to the microsecond.
588fn seconds(samples: u64) -> String {
589    format!(
590        "{}.{:06}",
591        samples / 48_000,
592        samples % 48_000 * 1_000_000 / 48_000
593    )
594}
595
596fn is_http(source: &OsStr) -> bool {
597    source.to_str().is_some_and(|source| {
598        let source = source.trim_start().to_ascii_lowercase();
599        source.starts_with("http://") || source.starts_with("https://")
600    })
601}
602
603#[cfg(test)]
604mod tests {
605    use std::path::PathBuf;
606
607    use tokio::sync::mpsc;
608
609    use super::{Chunk, Frame, Input, Source, is_http, read, seconds};
610    use crate::{InputError, codec::FRAME_BYTES};
611
612    const SINE: &[u8] = include_bytes!("../tests/data/sine.opus");
613
614    /// What reading `input` from `start` sends.
615    async fn chunks(input: Input, start: u64) -> Vec<Result<Chunk, InputError>> {
616        let (tx, mut rx) = mpsc::channel(4);
617        let (source, _) = input.into_parts();
618        let reader = tokio::spawn(read(source, start, tx));
619        let mut chunks = Vec::new();
620        while let Some(chunk) = rx.recv().await {
621            chunks.push(chunk);
622        }
623        reader.await.unwrap();
624        chunks
625    }
626
627    fn frames(chunks: &[Result<Chunk, InputError>]) -> Vec<&Frame> {
628        chunks
629            .iter()
630            .filter_map(|chunk| match chunk {
631                Ok(Chunk::Frame(frame)) => Some(frame),
632                _ => None,
633            })
634            .collect()
635    }
636
637    /// A directory of its own for a test's files.
638    fn dir(name: &str) -> PathBuf {
639        let dir = std::env::temp_dir().join(format!("djs-voice-{name}-{}", std::process::id()));
640        std::fs::create_dir_all(&dir).unwrap();
641        dir
642    }
643
644    #[tokio::test]
645    async fn reads_every_packet_of_a_stream() {
646        let chunks = chunks(Input::ogg(SINE), 0).await;
647        let frames = frames(&chunks);
648        assert_eq!(frames.len(), 51);
649        assert_eq!(chunks.len(), 51, "no start, no error");
650        assert!(frames.iter().all(|frame| frame.samples() == 960));
651        assert!(!Input::ogg(SINE).seekable());
652    }
653
654    #[tokio::test]
655    async fn files_are_checked_when_opened_and_read_again_from_a_place() {
656        let dir = dir("input");
657        let good = dir.join("sine.opus");
658        std::fs::write(&good, SINE).unwrap();
659        let input = Input::ogg_file(&good).await.unwrap();
660        assert!(input.seekable());
661        assert_eq!(format!("{input:?}"), "Input::OggFile");
662        let read = chunks(input, 0).await;
663        assert_eq!(
664            frames(&read).len(),
665            51,
666            "the packet read while checking is kept"
667        );
668        // From 0.5 s: 25 packets of 20 ms skipped. 24 010 is inside the 26th packet.
669        let (_, again) = Input::ogg_file(&good).await.unwrap().into_parts();
670        for (start, at, left) in [(24_000, 24_000, 26), (24_010, 24_000, 26), (60_000, 0, 0)] {
671            let read = chunks(
672                Input {
673                    source: again.as_ref().unwrap().source(),
674                    again: None,
675                },
676                start,
677            )
678            .await;
679            if left == 0 {
680                assert!(read.is_empty(), "past the end");
681                continue;
682            }
683            // 400 ms before the place to decode first: twenty packets of 20 ms.
684            assert!(matches!(&read[0], Ok(Chunk::Preroll(packets)) if packets.len() == 20));
685            assert!(matches!(read[1], Ok(Chunk::Start(position)) if position == at));
686            assert_eq!(frames(&read).len(), left);
687        }
688        let text = dir.join("text.opus");
689        std::fs::write(&text, b"not audio at all").unwrap();
690        assert!(matches!(
691            Input::ogg_file(&text).await,
692            Err(InputError::NotOgg)
693        ));
694        assert!(matches!(
695            Input::ogg_file(dir.join("missing.opus")).await,
696            Err(InputError::Io(_))
697        ));
698        let read = chunks(
699            Input {
700                source: Source::OggFile(dir.join("missing.opus")),
701                again: None,
702            },
703            0,
704        )
705        .await;
706        assert!(matches!(read[..], [Err(InputError::Io(_))]));
707        std::fs::remove_dir_all(&dir).unwrap();
708    }
709
710    #[tokio::test]
711    async fn readers_report_inputs_that_are_not_ogg_opus() {
712        let chunks = chunks(Input::ogg(&b"plain text"[..]), 0).await;
713        assert!(matches!(chunks[..], [Err(InputError::NotOgg)]));
714    }
715
716    #[tokio::test]
717    async fn reading_stops_when_the_player_does() {
718        let (tx, mut rx) = mpsc::channel(1);
719        let (source, _) = Input::ogg(SINE).into_parts();
720        let reader = tokio::spawn(read(source, 0, tx));
721        rx.recv().await.unwrap().unwrap();
722        drop(rx);
723        reader.await.unwrap();
724    }
725
726    #[tokio::test]
727    async fn pcm_comes_in_frames_of_20_ms() {
728        // Two and a half frames, from a reader that gives a few bytes at a time.
729        let bytes: Vec<u8> = (0..FRAME_BYTES * 5 / 2)
730            .map(|i| u8::try_from(i % 251).unwrap())
731            .collect();
732        let (client, mut server) = tokio::io::duplex(64);
733        let writer = {
734            let bytes = bytes.clone();
735            tokio::spawn(async move {
736                use tokio::io::AsyncWriteExt;
737                for piece in bytes.chunks(1000) {
738                    server.write_all(piece).await.unwrap();
739                }
740            })
741        };
742        let read = chunks(Input::pcm(client), 0).await;
743        writer.await.unwrap();
744        let frames = frames(&read);
745        assert_eq!(frames.len(), 3);
746        let Frame::Pcm(last) = frames[2] else {
747            panic!("{:?}", frames[2])
748        };
749        assert_eq!(last.len(), FRAME_BYTES);
750        assert_eq!(last[..FRAME_BYTES / 2], bytes[FRAME_BYTES * 2..]);
751        assert!(last[FRAME_BYTES / 2..].iter().all(|&byte| byte == 0));
752        assert!(chunks(Input::pcm(&b""[..]), 0).await.is_empty());
753        assert!(!Input::pcm(&b""[..]).seekable());
754    }
755
756    #[test]
757    fn ffmpeg_arguments_are_formatted() {
758        assert_eq!(seconds(0), "0.000000");
759        assert_eq!(seconds(72_000), "1.500000");
760        assert_eq!(seconds(48_001), "1.000020");
761        assert!(is_http("https://example.com/a.mp3".as_ref()));
762        assert!(is_http(" HTTP://example.com".as_ref()));
763        assert!(!is_http("music/https.mp3".as_ref()));
764    }
765
766    #[tokio::test]
767    async fn a_missing_ffmpeg_is_reported() {
768        let input = Input::ffmpeg_with("djs-voice-no-such-program", "song.mp3");
769        assert!(input.seekable());
770        let read = chunks(input, 0).await;
771        assert!(matches!(read[..], [Err(InputError::FfmpegMissing)]));
772    }
773
774    /// Whether `ffmpeg` runs here; the tests that need it pass without it.
775    fn have_ffmpeg() -> bool {
776        let found = std::process::Command::new("ffmpeg")
777            .arg("-version")
778            .output()
779            .is_ok_and(|output| output.status.success());
780        if !found {
781            eprintln!("ffmpeg is not installed: skipped");
782        }
783        found
784    }
785
786    /// A WAV file of `seconds` of a 44.1 kHz mono tone: FFmpeg resamples it.
787    fn wav(path: &std::path::Path, seconds: u32) {
788        let samples = 44_100 * seconds;
789        let mut file = Vec::new();
790        file.extend_from_slice(b"RIFF");
791        file.extend_from_slice(&(36 + samples * 2).to_le_bytes());
792        file.extend_from_slice(b"WAVEfmt ");
793        file.extend_from_slice(&16_u32.to_le_bytes());
794        file.extend_from_slice(&1_u16.to_le_bytes()); // PCM
795        file.extend_from_slice(&1_u16.to_le_bytes()); // mono
796        file.extend_from_slice(&44_100_u32.to_le_bytes());
797        file.extend_from_slice(&88_200_u32.to_le_bytes());
798        file.extend_from_slice(&2_u16.to_le_bytes());
799        file.extend_from_slice(&16_u16.to_le_bytes());
800        file.extend_from_slice(b"data");
801        file.extend_from_slice(&(samples * 2).to_le_bytes());
802        for i in 0..samples {
803            let value = (f64::from(i) * 440.0 * core::f64::consts::TAU / 44_100.0).sin() * 8000.0;
804            #[expect(clippy::cast_possible_truncation, reason = "within ±8000")]
805            file.extend_from_slice(&(value as i16).to_le_bytes());
806        }
807        std::fs::write(path, file).unwrap();
808    }
809
810    #[tokio::test]
811    async fn ffmpeg_decodes_and_seeks() {
812        if !have_ffmpeg() {
813            return;
814        }
815        let dir = dir("ffmpeg");
816        let path = dir.join("tone.wav");
817        wav(&path, 1);
818        // One second: 50 frames of 20 ms.
819        let read = chunks(Input::ffmpeg(&path), 0).await;
820        assert_eq!(frames(&read).len(), 50, "{read:?}");
821        assert!(read.iter().all(Result::is_ok));
822        // From 0.5 s: 25 frames.
823        let read = chunks(Input::ffmpeg(&path), 24_000).await;
824        assert!(matches!(read[0], Ok(Chunk::Start(24_000))));
825        assert_eq!(frames(&read).len(), 25);
826        // A file that does not exist: FFmpeg says why.
827        let read = chunks(Input::ffmpeg(dir.join("missing.mp3")), 0).await;
828        match &read[..] {
829            [Err(InputError::Ffmpeg { code, message })] => {
830                assert_ne!(*code, Some(0));
831                assert!(message.contains("missing.mp3"), "{message}");
832            }
833            other => panic!("{other:?}"),
834        }
835        std::fs::remove_dir_all(&dir).unwrap();
836    }
837
838    /// Step 4's measurement of the readers through `Input` (C-129, C-118): `cargo test
839    /// --release -p djs-voice --lib input::tests::throughput -- --ignored --nocapture`.
840    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
841    #[ignore = "a measurement; run it in release"]
842    async fn throughput() {
843        use std::time::Instant;
844
845        use crate::ogg::tests::{audio, opus, stream};
846
847        // An hour of 64 kbit/s Ogg/Opus in a file: 20 ms CELT packets of 160 bytes.
848        let packets: u32 = 3600 * 50;
849        let audio: Vec<Vec<u8>> = (0..packets)
850            .map(|number| {
851                let mut packet = vec![0xFC];
852                packet.extend(audio(u8::try_from(number % 256).unwrap(), 159));
853                packet
854            })
855            .collect();
856        let file = stream(1, 0, &opus(&audio), 50);
857        let dir = std::env::temp_dir().join(format!("djs-voice-read-{}", std::process::id()));
858        std::fs::create_dir_all(&dir).unwrap();
859        let path = dir.join("hour.opus");
860        std::fs::write(&path, &file).unwrap();
861        let drain = |input: Input| async move {
862            let (source, _) = input.into_parts();
863            // As a track's reader: 50 chunks ahead.
864            let (tx, mut rx) = mpsc::channel(50);
865            tokio::spawn(read(source, 0, tx));
866            let mut frames = 0_u32;
867            while let Some(chunk) = rx.recv().await {
868                if let Ok(Chunk::Frame(_)) = chunk {
869                    frames += 1;
870                }
871            }
872            frames
873        };
874        let mut best = f64::MAX;
875        for _ in 0..3 {
876            let started = Instant::now();
877            let frames = drain(Input::ogg_file(&path).await.unwrap()).await;
878            best = best.min(started.elapsed().as_secs_f64());
879            assert_eq!(frames, packets);
880        }
881        println!(
882            "an hour of Ogg/Opus from a file: {:.0} ms, {:.2} M packets/s, {:.0}x real time",
883            best * 1e3,
884            f64::from(packets) / best / 1e6,
885            3600.0 / best
886        );
887        std::fs::remove_dir_all(&dir).unwrap();
888        // Ten minutes of PCM from memory, in 20 ms frames.
889        let minutes = 10;
890        let pcm = vec![0_u8; minutes * 60 * 48_000 * 4];
891        let frames = u32::try_from(minutes * 60 * 50).unwrap();
892        let mut best = f64::MAX;
893        for _ in 0..3 {
894            let started = Instant::now();
895            let read = drain(Input::pcm(std::io::Cursor::new(pcm.clone()))).await;
896            best = best.min(started.elapsed().as_secs_f64());
897            assert_eq!(read, frames);
898        }
899        println!(
900            "ten minutes of PCM from memory: {:.0} ms, {:.2} M frames/s, {:.0}x real time",
901            best * 1e3,
902            f64::from(frames) / best / 1e6,
903            600.0 / best
904        );
905    }
906}