//! Voice packets as the audio pipeline sees them, whatever transport carries //! them (the TeamSpeak connection today, a Voelin server later). //! //! The transport adapter turns what it receives into a [`VoicePacket`] and //! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`]) //! into its own wire format; nothing in this crate knows either format. use crate::pcm::FRAME_SAMPLES; /// Who is talking: a sender id, unique among the talkers of one voice /// connection. A transport maps its own client ids onto it (TeamSpeak's /// 16-bit client id is used as is). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TalkerId(pub u16); /// The two Opus flavours voice is sent in. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum VoiceCodec { /// Mono, tuned for speech. Voice, /// Stereo, tuned for music. Music, } impl VoiceCodec { pub fn channels(self) -> usize { match self { VoiceCodec::Voice => 1, VoiceCodec::Music => 2, } } /// Samples (all channels) in one 20 ms frame. pub fn frame_len(self) -> usize { FRAME_SAMPLES * self.channels() } } /// A voice packet received from a talker. #[derive(Clone, Debug, PartialEq, Eq)] pub struct VoicePacket { pub talker: TalkerId, /// Packet number of this talker, counting up by one per 20 ms frame and /// wrapping at 65536; the jitter buffer orders by it and finds gaps. pub seq: u16, pub codec: VoiceCodec, /// Sent to us as a whisper instead of to the whole channel. pub whisper: bool, /// One Opus packet. An empty one ends the talk (a single byte counts as /// empty too: some servers send one). pub payload: Vec, } impl VoicePacket { /// Whether this packet only ends the talk and carries no audio. pub fn is_end(&self) -> bool { self.payload.len() <= 1 } } /// One encoded frame to send. The transport assigns the packet number. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodedVoice { pub codec: VoiceCodec, /// One Opus packet; empty: the transmission ended. pub payload: Vec, } impl EncodedVoice { /// Whether this only tells listeners the transmission ended. pub fn is_end(&self) -> bool { self.payload.is_empty() } } #[cfg(test)] mod tests { use super::*; #[test] fn codec_frames() { assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES); assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2); } #[test] fn end_of_talk() { let voice = |payload: &[u8]| VoicePacket { talker: TalkerId(1), seq: 0, codec: VoiceCodec::Voice, whisper: false, payload: payload.to_vec(), }; assert!(voice(&[]).is_end()); assert!(voice(&[2]).is_end()); assert!(!voice(&[2, 3]).is_end()); assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end()); assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end()); } }