1use 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
24const CHUNK: usize = 16 * 1024;
26const STDERR_TAIL: usize = 4 * 1024;
28const STDERR_LINES: usize = 4;
30const FFMPEG: &str = "ffmpeg";
32const PREROLL: u64 = 19_200;
37
38pub struct Input {
70 source: Source,
71 again: Option<Again>,
72}
73
74pub(crate) enum Source {
76 Ogg {
77 reader: Box<dyn AsyncRead + Send + Unpin>,
78 ogg: Box<OggOpus>,
79 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#[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 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#[derive(Debug)]
123pub(crate) enum Frame {
124 Opus { data: Vec<u8>, samples: u32 },
126 Pcm(Vec<u8>),
128}
129
130impl Frame {
131 pub(crate) fn samples(&self) -> u32 {
133 match self {
134 Self::Opus { samples, .. } => *samples,
135 Self::Pcm(_) => 960,
136 }
137 }
138}
139
140#[derive(Debug, Default)]
143pub(crate) struct History {
144 packets: std::collections::VecDeque<(Vec<u8>, u32)>,
145 samples: u64,
146}
147
148impl History {
149 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 pub(crate) fn packets(&self) -> impl Iterator<Item = &[u8]> {
178 self.packets.iter().map(|(data, _)| &data[..])
179 }
180}
181
182#[derive(Debug)]
184pub(crate) enum Chunk {
185 Preroll(History),
187 Start(u64),
190 Frame(Frame),
191}
192
193pub(crate) type Chunks = mpsc::Sender<Result<Chunk, InputError>>;
195
196impl Input {
197 #[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 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 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 #[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 #[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 pub(crate) fn into_parts(self) -> (Source, Option<Again>) {
337 (self.source, self.again)
338 }
339
340 pub(crate) fn seekable(&self) -> bool {
342 self.again.is_some()
343 }
344
345 #[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
360pub(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
377struct 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 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
454async 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
470async 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 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
511async 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 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
568async 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
587fn 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 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 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 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 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 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 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 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()); file.extend_from_slice(&1_u16.to_le_bytes()); 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 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 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 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 #[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 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 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 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}