Move voice packet types into voelin-audio

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>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-14 13:06:46 +03:00
1 parent 1bee9c94e8
commit df7be67d4c
15 files changed
+1352 -227

No files matched your search

+46 -49
View File
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
use voelin_audio::pcm::{self, FRAME_SAMPLES};
use voelin_audio::settings::TransmitMode;
use voelin_audio::tap;
use voelin_audio::vad::SILENCE_DB;
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use voelin_audio::{
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
VoicePacket,
};
pub(crate) enum AudioIn {
Packet(InAudioBuf),
/// Voice of a talker, from the voice connection.
Packet(VoicePacket),
Transmit(bool),
InputMuted(bool),
OutputMuted(bool),
@@ -33,19 +35,19 @@ pub(crate) enum AudioIn {
Settings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
ClientVolume {
client: ClientId,
client: TalkerId,
volume: f32,
},
ClientMuted {
client: ClientId,
client: TalkerId,
muted: bool,
},
/// The client left; client ids are reused, so forget its volume.
ClientLeft(ClientId),
ClientLeft(TalkerId),
/// The priority speakers: while one talks, everyone else (streams too)
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
PrioritySpeakers {
clients: Vec<ClientId>,
clients: Vec<TalkerId>,
dimm_db: f32,
},
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
@@ -111,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
const OPUS_FRAME: u64 = 960;
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
/// no device) and the microphone level are reported through `events`.
pub(crate) fn spawn(
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) -> AudioHandle {
@@ -126,9 +128,9 @@ pub(crate) fn spawn(
AudioHandle { tx }
}
/// Audio of a watched stream in the mixer, under a made-up client id.
/// Audio of a watched stream in the mixer, under a made-up talker id.
struct StreamAudio {
client: ClientId,
client: TalkerId,
/// RTP time and packet id of the last packet.
last: Option<(u64, u64)>,
}
@@ -190,11 +192,7 @@ impl Pipeline {
fn handle(&mut self, msg: AudioIn) {
match msg {
AudioIn::Packet(packet) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => return,
};
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped voice packet");
}
}
@@ -241,8 +239,8 @@ impl Pipeline {
let client = match self.streams.get(&stream) {
Some(s) => s.client,
None => {
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
else {
return;
};
@@ -263,19 +261,15 @@ impl Pipeline {
}
};
entry.last = Some((time, id));
let packet = OutAudio::new(&AudioData::S2C {
id: id as u16,
codec: CodecType::OpusMusic,
from: client.0,
data,
});
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
Ok(packet) => {
if let Err(error) = self.mixer.handle_packet(client, packet) {
debug!(%error, "dropped stream audio packet");
}
}
Err(error) => debug!(?error, "stream audio packet"),
let packet = VoicePacket {
talker: client,
seq: id as u16,
codec: VoiceCodec::Music,
whisper: false,
payload: data.to_vec(),
};
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped stream audio packet");
}
}
@@ -286,7 +280,7 @@ impl Pipeline {
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
self.processor.set_delay_ms(delay_ms);
self.processed.clear();
self.processor.capture(samples, &mut self.processed);
@@ -308,7 +302,7 @@ impl Pipeline {
}
}
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
// Always analysed, so the detector's state is current when needed.
let voice = self.vad.process(&frame);
let level = self.vad.level_db().max(SILENCE_DB);
@@ -369,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) {
@@ -445,11 +439,10 @@ fn run(
#[cfg(feature = "audio-device")]
mod devices {
use tracing::debug;
use tsproto_packets::packets::OutPacket;
use voelin_audio::AudioSettings;
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use voelin_audio::resample::Linear;
use voelin_audio::{AudioSettings, EncodedVoice};
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
@@ -509,7 +502,7 @@ mod devices {
pub fn step(
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
send: &mut impl FnMut(EncodedVoice),
error: &impl Fn(String),
) -> bool {
if let Some(event) = self.playback.poll() {
@@ -575,16 +568,20 @@ mod tests {
/// end-of-stream packets).
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
let (mut voice, mut end) = (0, 0);
p.capture(samples, 0, &mut |packet: OutPacket| {
// Header of 3 bytes (id + codec) for C2S audio.
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
p.capture(samples, 0, &mut |packet: EncodedVoice| {
if packet.is_end() { end += 1 } else { voice += 1 }
});
(voice, end)
}
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
AudioIn::Packet(VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
})
}
#[test]
@@ -667,14 +664,14 @@ mod tests {
energy(&out[out.len() / 2..])
};
let full = play(&mut p, 1);
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
let half = play(&mut p, 2);
let ratio_db = 10.0 * (half / full).log10();
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
assert!(play(&mut p, 3) < 1e-8);
p.handle(AudioIn::ClientLeft(ClientId(3)));
assert!(!p.mixer.is_muted(ClientId(3)));
p.handle(AudioIn::ClientLeft(TalkerId(3)));
assert!(!p.mixer.is_muted(TalkerId(3)));
}
/// While a priority speaker talks, another talker and a watched stream
@@ -682,7 +679,7 @@ mod tests {
#[test]
fn priority_speaker() {
let mut p = pipeline(TransmitMode::PushToTalk);
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();