use std::fmt;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AudioFrame<'a> {
Pcm(&'a [u8]),
Encoded {
codec: Codec,
data: &'a [u8],
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Codec {
Pcm,
Flac,
Opus,
Other(String),
}
impl Codec {
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Pcm => "pcm",
Self::Flac => "flac",
Self::Opus => "opus",
Self::Other(name) => name,
}
}
}
impl fmt::Display for Codec {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl From<&str> for Codec {
fn from(value: &str) -> Self {
match value {
"pcm" => Self::Pcm,
"flac" => Self::Flac,
"opus" => Self::Opus,
other => Self::Other(other.to_owned()),
}
}
}
impl From<String> for Codec {
fn from(value: String) -> Self {
match value.as_str() {
"pcm" => Self::Pcm,
"flac" => Self::Flac,
"opus" => Self::Opus,
_ => Self::Other(value),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioFormat {
pub codec: Codec,
pub sample_rate: u32,
pub channels: u8,
pub bit_depth: u8,
pub codec_header: Option<Vec<u8>>,
}
pub trait Sink: Send + 'static {
fn open(&mut self, format: AudioFormat) -> anyhow::Result<()>;
fn write(&mut self, frame: AudioFrame<'_>, due: std::time::Instant) -> anyhow::Result<()>;
fn flush(&mut self) -> anyhow::Result<()>;
fn latency(&self) -> Option<Duration> {
None
}
fn underruns(&self) -> u64 {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codec_names_roundtrip_through_the_wire_identifier() {
for (name, codec) in [
("pcm", Codec::Pcm),
("flac", Codec::Flac),
("opus", Codec::Opus),
("future", Codec::Other("future".to_owned())),
] {
assert_eq!(Codec::from(name), codec);
assert_eq!(codec.as_str(), name);
assert_eq!(codec.to_string(), name);
assert_eq!(Codec::from(name.to_owned()), codec);
}
}
}