use wincode::{ SchemaRead, SchemaWrite };
use crate::
{
consts as chat_consts,
network::voice::consts,
};
const MAGIC: &[u8; 8] = b"WHY2VOX\x01";
#[derive(SchemaRead, SchemaWrite)]
pub struct Clip {
pub channels: u8, pub frames: Vec<Vec<u8>>, }
impl Clip
{
pub fn encode(&self) -> Vec<u8> {
let mut bytes = MAGIC.to_vec();
bytes.extend(wincode::config::serialize(self, chat_consts::PACKET_CONFIG).expect("Encoding voice message failed"));
bytes
}
pub fn decode(bytes: &[u8]) -> Option<Self> {
let clip = wincode::config::deserialize::<Self, _>(bytes.strip_prefix(MAGIC)?, chat_consts::PACKET_CONFIG).ok()?;
let valid = matches!(clip.channels, 1 | 2)
&& !clip.frames.is_empty()
&& clip.frames.len() <= consts::MESSAGE_MAX_FRAMES
&& clip.frames.iter().all(|frame| !frame.is_empty() && frame.len() <= consts::MESSAGE_MAX_PACKET);
valid.then_some(clip)
}
pub fn duration(&self) -> u32 {
self.frames.len() as u32 * consts::FRAME_MS
}
}
pub fn is_clip(header: &[u8]) -> bool {
header.starts_with(MAGIC)
}