voelin-audio no longer depends on tsclientlib or tsproto-packets. Its boundary is now plain types in packet.rs: TalkerId, VoiceCodec, VoicePacket (talker, seq, codec, whisper, payload) and EncodedVoice (codec, payload; an empty payload ends the transmission). The jitter buffer moves from tsclientlib::audio into jitter.rs and reads VoicePacket fields; the encoder returns EncodedVoice and the mixer is keyed by TalkerId. In voelin-core, voice.rs is the only place that wraps EncodedVoice into a TeamSpeak audio packet and reads one into a VoicePacket (codecs other than Opus are dropped there, where the jitter buffer rejected them before); audio.rs and session.rs work on the new types. voelinctl converts at its own edge. Behaviour is unchanged: the one-hour drift simulation gives the same latencies as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
129 lines
4.0 KiB
Rust
129 lines
4.0 KiB
Rust
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
|
|
|
|
use opus2::{Application, Bitrate, Channels, Encoder};
|
|
|
|
use crate::packet::{EncodedVoice, VoiceCodec};
|
|
use crate::pcm::SAMPLE_RATE;
|
|
use crate::{Error, Result};
|
|
|
|
/// Largest possible Opus packet.
|
|
const MAX_PACKET: usize = 1275;
|
|
|
|
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
|
|
pub struct VoiceEncoder {
|
|
encoder: Encoder,
|
|
codec: VoiceCodec,
|
|
out: Vec<u8>,
|
|
}
|
|
|
|
impl VoiceEncoder {
|
|
pub fn new(codec: VoiceCodec) -> Result<Self> {
|
|
let (channels, application) = match codec {
|
|
VoiceCodec::Voice => (Channels::Mono, Application::Voip),
|
|
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
|
};
|
|
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
|
// Survive some packet loss: voice travels over unreliable datagrams.
|
|
encoder.set_inband_fec(true)?;
|
|
encoder.set_packet_loss_perc(5)?;
|
|
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
|
}
|
|
|
|
pub fn codec(&self) -> VoiceCodec {
|
|
self.codec
|
|
}
|
|
|
|
/// Target bitrate in bits per second.
|
|
pub fn set_bitrate(&mut self, bps: i32) -> Result<()> {
|
|
self.encoder.set_bitrate(Bitrate::Bits(bps))?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Encode one frame of [`VoiceCodec::frame_len`] interleaved samples.
|
|
pub fn encode_to_bytes(&mut self, frame: &[f32]) -> Result<&[u8]> {
|
|
if frame.len() != self.codec.frame_len() {
|
|
return Err(Error::Invalid(format!(
|
|
"frame has {} samples, expected {}",
|
|
frame.len(),
|
|
self.codec.frame_len()
|
|
)));
|
|
}
|
|
let len = self.encoder.encode_float(frame, &mut self.out)?;
|
|
Ok(&self.out[..len])
|
|
}
|
|
|
|
/// Encode one frame for the transport to send. The transport assigns the
|
|
/// packet number.
|
|
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
|
|
let codec = self.codec;
|
|
let payload = self.encode_to_bytes(frame)?.to_vec();
|
|
Ok(EncodedVoice { codec, payload })
|
|
}
|
|
|
|
/// The empty packet that tells listeners the transmission ended.
|
|
pub fn end_of_stream(&self) -> EncodedVoice {
|
|
EncodedVoice { codec: self.codec, payload: Vec::new() }
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::packet::{TalkerId, VoicePacket};
|
|
use crate::pcm::{self, FRAME_SAMPLES};
|
|
|
|
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
|
/// decoder), and check the tone comes out.
|
|
#[test]
|
|
fn roundtrip_through_mixer() {
|
|
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
|
let mut mixer = crate::Mixer::new();
|
|
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
|
let mut decoded = Vec::new();
|
|
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
|
let sent = encoder.encode(frame).unwrap();
|
|
assert_eq!(sent.codec, VoiceCodec::Voice);
|
|
let packet = VoicePacket {
|
|
talker: TalkerId(7),
|
|
seq: i as u16,
|
|
codec: sent.codec,
|
|
whisper: false,
|
|
payload: sent.payload,
|
|
};
|
|
mixer.handle_packet(packet).unwrap();
|
|
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
|
mixer.fill_buffer(&mut out);
|
|
decoded.extend(pcm::to_mono(&out, 2));
|
|
}
|
|
// Skip the jitter buffer's initial latency and the codec warm-up.
|
|
let tail = &decoded[decoded.len() / 2..];
|
|
let ratio = pcm::tone_ratio(tail, 1000.0, SAMPLE_RATE);
|
|
assert!(ratio > 0.8, "tone ratio {ratio}");
|
|
}
|
|
|
|
#[test]
|
|
fn end_of_stream_has_no_payload() {
|
|
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
|
let end = encoder.end_of_stream();
|
|
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
|
|
assert!(end.is_end());
|
|
}
|
|
|
|
#[test]
|
|
fn encoded_frames_carry_codec_and_audio() {
|
|
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
|
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
|
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
|
|
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
|
|
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
|
|
assert!(!a.is_end() && !b.is_end());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_wrong_frame_size() {
|
|
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
|
assert!(encoder.encode(&[0.0; FRAME_SAMPLES]).is_err());
|
|
assert!(encoder.encode(&[0.0; FRAME_SAMPLES * 2]).is_ok());
|
|
}
|
|
}
|