use std::time::Duration;
use serde::{Deserialize, Serialize};
pub const CHANNELS: u16 = 2;
pub const MAX_SAMPLES: usize = 1920;
pub const MAX_WRITE_BYTES: usize = MAX_SAMPLES * size_of::<i16>();
pub const MAX_QUEUED_FRAMES: u32 = 7680;
pub const DEADLINE: Duration = Duration::from_secs(3);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
Open {},
Write {
generation: u64,
sequence: u64,
bytes: u32,
},
Pause {
generation: u64,
paused: bool,
},
Volume {
generation: u64,
percent: u8,
},
Flush {
generation: u64,
},
Status {
generation: u64,
},
Close {
generation: u64,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub generation: u64,
pub accepted_sequence: u64,
pub rendered_frames: u64,
pub queued_frames: u32,
pub paused: bool,
pub ready: bool,
pub closed: bool,
}
impl Snapshot {
#[must_use]
pub fn valid(&self) -> bool {
self.generation > 0
&& self.queued_frames <= MAX_QUEUED_FRAMES
&& !(self.closed && self.ready)
}
}
impl Request {
#[must_use]
pub fn valid(&self) -> bool {
match self {
Self::Open {} => true,
Self::Write {
generation,
sequence,
bytes,
} => {
*generation > 0
&& *sequence > 0
&& usize::try_from(*bytes).is_ok_and(|bytes| {
bytes > 0
&& bytes <= MAX_WRITE_BYTES
&& bytes.is_multiple_of(usize::from(CHANNELS))
})
}
Self::Volume {
generation,
percent,
} => *generation > 0 && *percent <= 100,
Self::Pause { generation, .. }
| Self::Flush { generation }
| Self::Status { generation }
| Self::Close { generation } => *generation > 0,
}
}
#[must_use]
pub fn body_len(&self) -> usize {
match self {
Self::Write { bytes, .. } if self.valid() => usize::try_from(*bytes).unwrap_or(0),
_ => 0,
}
}
pub fn samples_of(&self, body: &[u8]) -> Result<Vec<i16>, &'static str> {
match self {
Self::Write { bytes, .. } => {
let bytes = usize::try_from(*bytes).map_err(|_| "invalid audio output write")?;
if body.len() != bytes || !bytes.is_multiple_of(usize::from(CHANNELS)) {
return Err("invalid audio output write body");
}
let mut samples = Vec::with_capacity(bytes / 2);
let mut rest = body;
while let [low, high, tail @ ..] = rest {
samples.push(i16::from_le_bytes([*low, *high]));
rest = tail;
}
Ok(samples)
}
_ => Ok(Vec::new()),
}
}
}
#[must_use]
pub fn body_of(samples: &[i16]) -> Vec<u8> {
samples
.iter()
.flat_map(|sample| sample.to_le_bytes())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_output_request_names_no_capture_identity_path_or_unbounded_pcm() {
for bytes in [
br#"{"op":"capture"}"#.as_slice(),
br#"{"op":"open","app_id":"so.tilo.settings"}"#,
br#"{"op":"open","path":"/run/user/1000/pipewire-0"}"#,
] {
assert!(serde_json::from_slice::<Request>(bytes).is_err());
}
let write = Request::Write {
generation: 1,
sequence: 1,
bytes: 3840,
};
assert!(write.valid());
assert_eq!(write.body_len(), 3840);
assert!(
!Request::Write {
generation: 1,
sequence: 0,
bytes: 2,
}
.valid()
);
let samples: Vec<i16> = (0..MAX_SAMPLES)
.map(|at| i16::try_from(at).expect("a bounded sample") - 500)
.collect();
assert_eq!(
write
.samples_of(&body_of(&samples))
.expect("a bounded write"),
samples
);
assert!(
Request::Write {
generation: 1,
sequence: 1,
bytes: 3,
}
.samples_of(&[1, 2, 3])
.is_err(),
"half a sample is no packet"
);
}
}