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();
+10 -10
View File
@@ -17,7 +17,7 @@ use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
use voelin_stream::ClientState;
@@ -108,7 +108,7 @@ enum SourceEvent {
Voice(u64, VoiceEvent),
Gateway(u64, GatewayEvent),
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
AudioOut(u64, EncodedVoice),
Audio(u64, AudioEvent),
/// Our own stream (from the stream task of that voice connection).
OwnStream(u64, OwnStreamEvent),
@@ -692,12 +692,12 @@ impl Session {
// again after connecting.
Command::SetClientVolume { client, volume, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
}
}
Command::SetClientMuted { client, muted, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
}
}
Command::SetStreamVolume { stream_id, volume, .. } => {
@@ -1436,15 +1436,15 @@ impl Session {
if let Some(a) = &self.audio {
for (client, (volume, muted)) in &wanted {
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
}
}
// No contact setting any more: back to normal.
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
if p.clients.contains_key(client) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
}
}
self.contact_audio = wanted;
@@ -1464,7 +1464,7 @@ impl Session {
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
let wanted = (clients, p.server.priority_speaker_dimm_db);
if wanted != self.priority_audio {
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
self.priority_audio = wanted;
}
@@ -1972,7 +1972,7 @@ impl Session {
// Client ids are reused: forget the volumes of those who left.
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
a.send(AudioIn::ClientLeft(ClientId(*id)));
a.send(AudioIn::ClientLeft(TalkerId(*id)));
}
}
if let Some(s) = &self.streams {
+127 -6
View File
@@ -24,7 +24,8 @@ use tsclientlib::{
Connection, DisconnectOptions, FiletransferHandle, Identity, InMessage, MessageHandle,
MessageTarget, StreamItem, TsError, Version,
};
use tsproto_packets::packets::{AudioData, InAudioBuf, OutCommand, OutPacket};
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutCommand, OutPacket};
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_stream::{PeerConfig, Request, StreamNotification};
@@ -119,8 +120,8 @@ pub(crate) enum VoiceCmd {
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice packet from the audio thread.
Audio(OutPacket),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`].
Stream(Request),
Poke {
@@ -214,7 +215,7 @@ pub(crate) enum VoiceEvent {
message: String,
},
/// Incoming voice for the audio thread, and who is talking.
Audio(InAudioBuf),
Audio(VoicePacket),
Talking {
client: u16,
talking: bool,
@@ -665,7 +666,9 @@ impl Voice {
if self.talking.insert(from, Instant::now()).is_none() {
let _ = self.events.send(VoiceEvent::Talking { client: from, talking: true });
}
let _ = self.events.send(VoiceEvent::Audio(packet));
if let Some(packet) = voice_packet(&packet) {
let _ = self.events.send(VoiceEvent::Audio(packet));
}
}
StreamItem::MessageEvent(msg) => self.message_event(&msg),
StreamItem::MessageResult(handle, result) => {
@@ -1107,7 +1110,7 @@ impl Voice {
let update = self.con.get_state()?.client_update().set_output_muted(muted);
update.send(&mut self.con)?;
}
VoiceCmd::Audio(packet) => self.con.send_audio(packet)?,
VoiceCmd::Audio(voice) => self.con.send_audio(out_audio(&voice))?,
VoiceCmd::Stream(request) => {
let cmd = request.to_command();
self.send(cmd, Pending::Stream(request))?;
@@ -1357,6 +1360,124 @@ fn transfer_error(error: &tsclientlib::Error) -> String {
}
}
/// Our voice frame as a TeamSpeak audio packet; the connection assigns its
/// packet id. This and [`voice_packet`] are the only places that convert
/// between the audio pipeline's packets and TeamSpeak's.
fn out_audio(voice: &EncodedVoice) -> OutPacket {
let codec = match voice.codec {
VoiceCodec::Voice => CodecType::OpusVoice,
VoiceCodec::Music => CodecType::OpusMusic,
};
OutAudio::new(&AudioData::C2S { id: 0, codec, data: &voice.payload })
}
/// A received TeamSpeak audio packet for the audio thread. `None` for
/// anything but Opus voice: the jitter buffer cannot play the other codecs
/// (Speex, CELT), and only server-to-client packets are received.
fn voice_packet(packet: &InAudioBuf) -> Option<VoicePacket> {
let (seq, from, codec, data, whisper) = match packet.data().data() {
AudioData::S2C { id, from, codec, data } => (*id, *from, *codec, *data, false),
AudioData::S2CWhisper { id, from, codec, data } => (*id, *from, *codec, *data, true),
_ => return None,
};
let codec = match codec {
CodecType::OpusVoice => VoiceCodec::Voice,
CodecType::OpusMusic => VoiceCodec::Music,
other => {
debug!(codec = ?other, "dropped voice packet: only Opus is supported");
return None;
}
};
Some(VoicePacket { talker: TalkerId(from), seq, codec, whisper, payload: data.to_vec() })
}
#[cfg(test)]
mod audio_packet_tests {
use tsproto_packets::packets::Direction;
use super::*;
fn received(data: AudioData) -> InAudioBuf {
InAudioBuf::try_new(Direction::S2C, OutAudio::new(&data).into_vec()).unwrap()
}
#[test]
fn received_voice_reaches_the_audio_thread_as_a_voice_packet() {
let packet = received(AudioData::S2C {
id: 513,
from: 7,
codec: CodecType::OpusVoice,
data: &[1, 2, 3],
});
assert_eq!(
voice_packet(&packet),
Some(VoicePacket {
talker: TalkerId(7),
seq: 513,
codec: VoiceCodec::Voice,
whisper: false,
payload: vec![1, 2, 3],
})
);
}
#[test]
fn whispers_and_music_are_marked() {
let packet = received(AudioData::S2CWhisper {
id: 65_535,
from: 300,
codec: CodecType::OpusMusic,
data: &[9],
});
let voice = voice_packet(&packet).unwrap();
assert_eq!((voice.talker, voice.seq), (TalkerId(300), 65_535));
assert_eq!(voice.codec, VoiceCodec::Music);
assert!(voice.whisper);
}
#[test]
fn the_end_of_a_talk_arrives_empty() {
let packet =
received(AudioData::S2C { id: 4, from: 7, codec: CodecType::OpusVoice, data: &[] });
let voice = voice_packet(&packet).unwrap();
assert!(voice.payload.is_empty() && voice.is_end());
}
#[test]
fn codecs_other_than_opus_are_dropped() {
for codec in [CodecType::SpeexWideband, CodecType::CeltMono] {
let packet = received(AudioData::S2C { id: 1, from: 7, codec, data: &[1, 2, 3] });
assert_eq!(voice_packet(&packet), None);
}
}
#[test]
fn sent_voice_is_a_client_audio_packet() {
for (codec, wire) in
[(VoiceCodec::Voice, CodecType::OpusVoice), (VoiceCodec::Music, CodecType::OpusMusic)]
{
let voice = EncodedVoice { codec, payload: vec![5, 6, 7] };
let packet = InAudioBuf::try_new(Direction::C2S, out_audio(&voice).into_vec()).unwrap();
match packet.data().data() {
AudioData::C2S { id, codec, data } => {
// The connection numbers the packets.
assert_eq!((*id, *codec, *data), (0, wire, &[5u8, 6, 7][..]));
}
other => panic!("not a client audio packet: {other:?}"),
}
}
}
#[test]
fn the_end_of_our_transmission_is_an_empty_packet() {
let end = EncodedVoice { codec: VoiceCodec::Voice, payload: Vec::new() };
// Two bytes of packet id and one of codec, no audio.
assert_eq!(out_audio(&end).content().len(), 3);
let voice = EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] };
assert_eq!(out_audio(&voice).content().len(), 4);
}
}
#[cfg(test)]
mod join_tests {
use super::*;