From 65d7b5e907ffbb594319e13684f7f566c0ad2264 Mon Sep 17 00:00:00 2001 From: Eskil Q Date: Fri, 1 Jan 2021 15:08:05 +0100 Subject: add AudioStream struct --- mumd/src/audio/input.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'mumd/src') diff --git a/mumd/src/audio/input.rs b/mumd/src/audio/input.rs index 914891b..01fd1f3 100644 --- a/mumd/src/audio/input.rs +++ b/mumd/src/audio/input.rs @@ -5,6 +5,10 @@ use std::collections::VecDeque; use std::sync::{Arc, Mutex}; use tokio::sync::{mpsc, watch}; use log::*; +use futures::Stream; +use std::pin::Pin; +use std::task::{Context, Poll}; +use futures_util::task::Waker; pub fn callback( mut opus_encoder: opus::Encoder, @@ -54,3 +58,38 @@ pub fn callback( } } } + +struct AudioStream { + data: Arc, Option)>>, +} + +impl AudioStream { + fn new() -> Self { + Self { + data: Arc::new(Mutex::new((VecDeque::new(), None))) + } + } + + fn insert_sample(&self, sample: T) { + let mut data = self.data.lock().unwrap(); + data.0.push_back(sample); + if let Some(waker) = data.1.take() { + waker.wake(); + } + } +} + +impl Stream for AudioStream { + type Item = T; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let s = self.get_mut(); + let mut data = s.data.lock().unwrap(); + if data.0.len() > 0 { + Poll::Ready(data.0.pop_front()) + } else { + data.1 = Some(cx.waker().clone()); + Poll::Pending + } + } +} \ No newline at end of file -- cgit v1.2.1