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

Generated
-2
View File
@@ -9474,8 +9474,6 @@ dependencies = [
"sonora-simd",
"thiserror 2.0.21",
"tracing",
"tsclientlib",
"tsproto-packets",
]
[[package]]
+1 -3
View File
@@ -1,7 +1,7 @@
[package]
name = "voelin-audio"
version = "0.1.0"
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
sonora-simd = "0.2"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
serde_json = "1"
+43 -55
View File
@@ -1,45 +1,15 @@
//! Opus encoding into TeamSpeak voice packets.
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
use opus2::{Application, Bitrate, Channels, Encoder};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
use crate::packet::{EncodedVoice, VoiceCodec};
use crate::pcm::SAMPLE_RATE;
use crate::{Error, Result};
/// Largest possible Opus packet.
const MAX_PACKET: usize = 1275;
/// The two Opus codecs TeamSpeak channels use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VoiceCodec {
/// Mono, tuned for speech (`CodecType::OpusVoice`).
Voice,
/// Stereo, tuned for music (`CodecType::OpusMusic`).
Music,
}
impl VoiceCodec {
pub fn channels(self) -> usize {
match self {
VoiceCodec::Voice => 1,
VoiceCodec::Music => 2,
}
}
pub fn codec_type(self) -> CodecType {
match self {
VoiceCodec::Voice => CodecType::OpusVoice,
VoiceCodec::Music => CodecType::OpusMusic,
}
}
/// Samples (all channels) in one 20 ms frame.
pub fn frame_len(self) -> usize {
FRAME_SAMPLES * self.channels()
}
}
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
pub struct VoiceEncoder {
encoder: Encoder,
codec: VoiceCodec,
@@ -53,7 +23,7 @@ impl VoiceEncoder {
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
};
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
// Survive some packet loss: TeamSpeak voice is plain UDP.
// 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] })
@@ -82,26 +52,25 @@ impl VoiceEncoder {
Ok(&self.out[..len])
}
/// Encode one frame into a packet ready for `Connection::send_audio`.
/// The connection assigns the packet id.
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
let codec = self.codec.codec_type();
let data = self.encode_to_bytes(frame)?;
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
/// 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) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
pub fn end_of_stream(&self) -> EncodedVoice {
EncodedVoice { codec: self.codec, payload: Vec::new() }
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{Direction, InAudioBuf};
use super::*;
use crate::pcm;
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.
@@ -112,15 +81,16 @@ mod tests {
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 data = encoder.encode_to_bytes(frame).unwrap().to_vec();
let packet = OutAudio::new(&AudioData::S2C {
id: i as u16,
codec: CodecType::OpusVoice,
from: 7,
data: &data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
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));
@@ -131,6 +101,24 @@ mod tests {
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();
+878
View File
@@ -0,0 +1,878 @@
//! Handle receiving audio.
//!
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
//! transport: it reads [`VoicePacket`]s, whatever carried them.
//!
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
//! talker. It decodes the audio, handles out-of-order packets and missing
//! packets. It automatically adjusts the queue length based on the jitter of
//! incoming packets.
use std::cmp::Reverse;
use std::collections::{HashMap, VecDeque};
use std::convert::TryInto;
use opus2::{Channels, Decoder, packet};
use thiserror::Error;
use tracing::{Span, debug, info_span, trace, warn};
use crate::packet::{TalkerId, VoicePacket};
const SAMPLE_RATE: u32 = 48_000;
const CHANNELS: Channels = Channels::Stereo;
const CHANNEL_NUM: usize = 2;
/// If this amount of packets is lost consecutively, we assume the stream stopped.
const MAX_PACKET_LOSSES: usize = 3;
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
/// Maximum number of packets in the queue.
const MAX_BUFFER_PACKETS: usize = 50;
/// Buffer for maximal 0.5 s without playing anything.
const MAX_BUFFER_TIME: usize = 48_000 / 2;
/// Duplicate or remove every `step` sample when speeding-up.
const SPEED_CHANGE_STEPS: usize = 100;
/// The usual amount of samples in a frame.
///
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
/// This means 1920 samples and 7.5 kiB.
const USUAL_FRAME_SIZE: usize = 48000 / 50;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create opus decoder: {0}")]
CreateDecoder(#[source] opus2::Error),
#[error("Opus decode failed: {error} (packet: {packet:?})")]
Decode {
#[source]
error: opus2::Error,
packet: Option<Vec<u8>>,
},
#[error("Get duplicate packet id {0}")]
Duplicate(u16),
#[error("Failed to get packet samples: {0}")]
GetPacketSample(#[source] opus2::Error),
#[error("Audio queue is full, dropping")]
QueueFull,
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
TooLate { wanted: u16, got: u16 },
#[error("Packet has too many samples")]
TooManySamples,
}
#[derive(Clone, Debug)]
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
/// How long a value stays in the sliding window.
size: u8,
/// This is a sliding window minimum, it contains
/// `(insertion time, value)`.
///
/// When we insert a value, we can remove all bigger sample counts,
/// thus the queue always stays sorted with the minimum at the front
/// and the maximum at the back (latest entry).
///
/// Provides amortized O(1) minimum.
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
queue: VecDeque<(u8, T)>,
/// The current insertion time.
cur_time: u8,
}
#[derive(Debug)]
struct QueuePacket {
packet: VoicePacket,
samples: usize,
id: u16,
}
/// A queue for audio packets for one audio stream.
pub struct AudioQueue {
span: Span,
decoder: Decoder,
pub volume: f32,
/// The id of the next packet that should be decoded.
///
/// Used to check for packet loss.
next_id: u16,
/// If the last packet was a whisper packet.
whispering: bool,
packet_buffer: VecDeque<QueuePacket>,
/// Amount of samples in the `packet_buffer`.
packet_buffer_samples: usize,
/// Temporary buffer that contains the samples of one decoded packet.
decoded_buffer: Vec<f32>,
/// The number of samples in `decoded_buffer` that have been returned.
decoded_pos: usize,
/// The number of samples in the last packet.
last_packet_samples: usize,
/// The last `packet_loss_num` packet decodes were a loss.
packet_loss_num: usize,
/// The amount of samples to buffer until this queue is ready to play.
buffering_samples: usize,
/// The amount of packets in the buffer when a packet was decoded.
///
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
/// Used to expand or reduce the buffer.
last_buffer_size_min: SlidingWindowMinimum<u8>,
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
/// Buffered for this duration.
buffered_for_samples: usize,
}
/// Handles incoming audio, has one [`AudioQueue`] per talker.
#[derive(Default)]
pub struct AudioHandler {
queues: HashMap<TalkerId, AudioQueue>,
/// Buffer this amount of samples for new queues before starting to play.
///
/// Updated when a new queue gets added.
avg_buffer_samples: usize,
}
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
fn new(size: u8) -> Self {
Self { size, queue: Default::default(), cur_time: 0 }
}
fn push(&mut self, value: T) {
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
self.queue.pop_back();
}
let i = self.cur_time;
self.queue.push_back((i, value));
while self
.queue
.front()
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
.unwrap_or_default()
{
self.queue.pop_front();
}
self.cur_time = self.cur_time.wrapping_add(1);
}
fn get_min(&self) -> T {
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
}
}
impl AudioQueue {
fn new(packet: VoicePacket) -> Result<Self> {
let last_packet_samples =
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
if last_packet_samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
let whispering = packet.whisper;
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
let mut res = Self {
span: Span::current(),
decoder,
volume: 1.0,
next_id: packet.seq,
whispering,
packet_buffer: Default::default(),
packet_buffer_samples: 0,
decoded_buffer: Default::default(),
decoded_pos: 0,
last_packet_samples,
packet_loss_num: 0,
buffering_samples: 0,
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
buffered_for_samples: 0,
};
res.add_buffer_size(0);
res.add_packet(packet)?;
Ok(res)
}
pub fn get_decoder(&self) -> &Decoder {
&self.decoder
}
pub fn is_whispering(&self) -> bool {
self.whispering
}
/// Size is in samples.
fn add_buffer_size(&mut self, size: usize) {
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
self.last_buffer_size_min.push(size);
self.last_buffer_size_max.push(Reverse(size));
} else {
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
}
}
/// The approximate deviation of the buffer size.
fn get_deviation(&self) -> u8 {
let min = self.last_buffer_size_min.get_min();
let max = self.last_buffer_size_max.get_min();
max.0 - min
}
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
let _span = self.span.enter();
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
return Err(Error::QueueFull);
}
let samples;
if packet.is_end() {
// End of stream
samples = 0;
} else {
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
.map_err(Error::GetPacketSample)?;
if samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
}
let id = packet.seq;
let packet = QueuePacket { packet, samples, id };
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
return Err(Error::TooLate { wanted: self.next_id, got: id });
}
// Put into first spot where the id is smaller
let i = self.packet_buffer.len()
- self
.packet_buffer
.iter()
.enumerate()
.rev()
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
.count();
// Check for duplicate packet
if let Some(p) = self.packet_buffer.get(i)
&& p.id == packet.id
{
return Err(Error::Duplicate(p.id));
}
trace!("Insert packet {} at {}", id, i);
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
if last_id <= id {
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
// Reduce buffering counter by lost packets if there are some
self.buffering_samples = self
.buffering_samples
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.insert(i, packet);
Ok(())
}
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
let _span = self.span.clone().entered();
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
let packet_data;
let len;
if let Some(p) = packet {
packet_data = &p.packet.payload[..];
len = p.samples;
self.whispering = p.packet.whisper;
} else {
// An empty slice signals packet loss to the decoder
packet_data = &[];
len = self.last_packet_samples;
}
self.packet_loss_num += 1;
let orig_buffer_len = self.decoded_buffer.len();
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
let len = self
.decoder
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
.map_err(|e| Error::Decode {
error: e,
packet: packet.map(|p| p.packet.payload.clone()),
})?;
self.last_packet_samples = len;
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
// Update packet_loss_num
if packet.is_some() && !fec {
self.packet_loss_num = 0;
}
// Update last_buffer_size
let mut count = self.packet_buffer_samples;
if let Some(last) = self.packet_buffer.back() {
// Lost packets
trace!(
last.id,
next_id = self.next_id,
first_id = self.packet_buffer.front().unwrap().id,
buffer_len = self.packet_buffer.len(),
"Ids"
);
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
- self.packet_buffer.len())
* self.last_packet_samples;
}
self.add_buffer_size(count);
Ok(())
}
/// Decode data and return the requested length of buffered data.
///
/// Returns `true` in the second return value when the stream ended,
/// `false` when it continues normally.
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
let _span = self.span.clone().entered();
if self.buffering_samples > 0 {
if self.buffered_for_samples >= MAX_BUFFER_TIME {
self.buffering_samples = 0;
self.buffered_for_samples = 0;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffered for too long"
);
} else {
self.buffered_for_samples += len;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffering"
);
return Ok((&[], false));
}
}
// Need to refill buffer
self.decoded_buffer.drain(..self.decoded_pos);
while self.decoded_buffer.len() < len {
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
// Decode a packet
if let Some(packet) = self.packet_buffer.pop_front() {
if packet.packet.is_end() {
// End of stream
return Ok((&self.decoded_buffer, true));
}
self.packet_buffer_samples -= packet.samples;
let cur_id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
if packet.id != cur_id {
debug_assert!(
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
"Invalid packet queue state: {} < {}",
packet.id,
cur_id
);
// Packet loss
debug!(need = cur_id, have = packet.id, "Audio packet loss");
if packet.id == self.next_id {
// Can use forward-error-correction
self.decode_packet(Some(&packet), true)?;
} else {
self.decode_packet(None, false)?;
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.push_front(packet);
} else {
self.decode_packet(Some(&packet), false)?;
}
} else {
debug!("No packets in queue");
// Packet loss or end of stream
self.decode_packet(None, false)?;
}
if self.last_packet_samples == 0 {
break;
}
// Check if we should speed-up playback
let min = self.last_buffer_size_min.get_min();
let dev = self.get_deviation();
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
debug!(min, "Truncating buffer");
// Throw out all but min samples
let mut keep_samples = 0;
let keep = self
.packet_buffer
.iter()
.rev()
.take_while(|p| {
keep_samples += p.samples;
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
})
.count();
let len = self.packet_buffer.len() - keep;
self.packet_buffer.drain(..len);
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
if let Some(p) = self.packet_buffer.front() {
self.next_id = p.id;
}
} else if min > dev {
// Speed-up
debug!(
min,
cur_packet_count = self.packet_buffer.len(),
last_packet_samples = self.last_packet_samples,
dev,
"Speed-up buffer"
);
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
}
}
}
self.decoded_pos = len;
Ok((&self.decoded_buffer[..len], false))
}
}
impl AudioHandler {
pub fn new() -> Self {
Default::default()
}
/// Delete all queues
pub fn reset(&mut self) {
self.queues.clear();
}
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
&self.queues
}
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
&mut self.queues
}
/// `buf` is not cleared before filling it.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
self.fill_buffer_with_proc(buf, |_, _| {})
}
/// `buf` is not cleared before filling it.
///
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
/// function is called. The queue volume is applied after calling the preprocessor.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
&mut self,
buf: &mut [f32],
mut handle: F,
) -> Vec<TalkerId> {
trace!(len = buf.len(), "Filling audio buffer");
let mut to_remove = Vec::new();
for (id, queue) in self.queues.iter_mut() {
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
to_remove.push(*id);
continue;
}
let vol = queue.volume;
match queue.get_next_data(buf.len()) {
Err(error) => {
warn!(%error, "Failed to decode audio packet");
}
Ok((r, is_end)) => {
handle(id, r);
for i in 0..r.len() {
buf[i] += r[i] * vol;
}
if is_end {
to_remove.push(*id);
}
}
}
}
for id in &to_remove {
self.queues.remove(id);
}
to_remove
}
/// Add a packet to the queue of its talker.
///
/// If a new talker started talking, returns its id.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
let id = packet.talker;
let empty = packet.is_end();
if let Some(queue) = self.queues.get_mut(&id) {
queue.add_packet(packet)?;
Ok(None)
} else {
if empty {
return Ok(None);
}
let _span = info_span!("audio queue", client = ?id);
trace!("Adding talker");
let mut queue = AudioQueue::new(packet)?;
if !self.queues.is_empty() {
// Update avg_buffer_samples
let total: usize = self
.queues
.values()
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
.sum();
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
}
queue.buffering_samples = self.avg_buffer_samples;
self.queues.insert(id, queue);
Ok(Some(id))
}
}
}
#[cfg(test)]
mod test {
use opus2::Encoder;
use super::*;
use crate::packet::VoiceCodec;
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
const ID: TalkerId = TalkerId(0);
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Music,
whisper: false,
payload: payload.to_vec(),
}
}
enum SimulateAction {
CreateEncoder,
/// Create packet with id.
///
/// The `bool` is `false` if packet handling should fail.
ReceivePacket(u16, bool),
ReceiveRaw(u16, Vec<u8>),
/// Fetch audio of this sample count and expect a certain packet id.
FillBuffer(usize, Option<u16>),
/// Custom check
Check(Box<dyn FnOnce(&AudioHandler)>),
}
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
let mut encoder = None;
let mut opus_output = [0; 1275]; // Max size for an opus packet
let mut handler = AudioHandler::new();
for a in actions {
println!("\nCurrent state");
for q in &handler.queues {
print!("Queue {:?}:", q.0);
for p in &q.1.packet_buffer {
print!(" {:?},", p);
}
println!();
}
match a {
SimulateAction::CreateEncoder => {
encoder = Some(Encoder::new(
48_000,
opus2::Channels::Mono,
opus2::Application::Voip,
)?);
}
SimulateAction::ReceivePacket(i, success) => {
let e = encoder.as_mut().unwrap();
let data = vec![i as f32; USUAL_FRAME_SIZE];
let len = e.encode_float(&data, &mut opus_output[..])?;
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
return Err(format!(
"handle_packet returned {:?} but expected {:?}",
!success, success
)
.into());
}
}
SimulateAction::ReceiveRaw(i, data) => {
let _ = handler.handle_packet(packet(i, &data));
}
SimulateAction::FillBuffer(size, expect) => {
let mut buf = vec![0.0; size * 2]; // Stereo
let cur_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
handler.fill_buffer(&mut buf);
let next_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
if expect.is_some() {
assert_eq!(expect, cur_packet_id);
assert_ne!(cur_packet_id, next_packet_id);
}
}
SimulateAction::Check(f) => {
f(&handler);
}
}
}
Ok(())
}
#[test]
fn sliding_window_minimum() {
let data = &[
(5, 5),
(6, 5),
(3, 3),
(4, 3),
(6, 3),
(5, 3),
(6, 3),
(6, 4),
(6, 5),
(6, 5),
(6, 6),
(7, 6),
(5, 5),
];
let mut window = SlidingWindowMinimum::new(5);
assert_eq!(window.get_min(), 0);
for (i, (val, min)) in data.iter().enumerate() {
println!("{:?}", window);
window.push(*val);
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
}
}
#[test]
fn sliding_window_minimum_full() {
let mut window = SlidingWindowMinimum::new(255);
window.push(1);
assert_eq!(window.get_min(), 1);
for _ in 0..254 {
window.push(2);
}
assert_eq!(window.get_min(), 1);
window.push(2);
assert_eq!(window.get_min(), 2);
}
#[test]
fn packets_wrapping() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
for i in 0..100 {
let seq = 65_500u16.wrapping_add(i);
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
if i > 5 {
handler.fill_buffer(&mut buf);
}
}
}
/// Short and malformed packets of any content are errors, never panics.
#[test]
fn short_packet_fuzz() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for _ in 0..500 {
let len = (next() % 12) as usize;
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
let _ = handler.handle_packet(packet(30, &payload));
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
}
}
#[test]
fn packets_wrapping2() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..100 {
let i = 65_500u16.wrapping_add(i);
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn silence() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for _ in 0..100 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
simulate(a)
}
#[test]
fn reversed() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..5 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceivePacket(4, false));
a.push(SimulateAction::ReceivePacket(3, false));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn duplicate() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(0, true));
a.push(SimulateAction::ReceivePacket(0, false));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
simulate(a)
}
#[test]
fn big_whole() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 27120..27124 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
for _ in 0..10 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
for i in 27339..27349 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn end_packet() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..10 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(10, vec![]));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(50, true));
a.push(SimulateAction::ReceivePacket(53, true));
for _ in 0..8 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_wrapping_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(65534, true));
a.push(SimulateAction::ReceivePacket(0, true));
for _ in 0..7 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
/// The talker is the key of the queues, and a new one is reported once.
#[test]
fn talkers_have_their_own_queues() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let from = |talker: u16, seq: u16| VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
assert_eq!(handler.handle_packet(from(7, 101))?, None);
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
talkers.sort_unstable();
assert_eq!(talkers, [7, 9]);
// A talker that only says goodbye never gets a queue.
let end = VoicePacket { payload: vec![], ..from(11, 0) };
assert_eq!(handler.handle_packet(end)?, None);
assert_eq!(handler.get_queues().len(), 2);
Ok(())
}
/// A queue knows whether the last packet it played was a whisper.
#[test]
fn whisper_flag_follows_the_packets() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let packet = |seq: u16, whisper: bool| VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Voice,
whisper,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
handler.handle_packet(packet(0, true))?;
assert!(handler.get_queues()[&ID].is_whispering());
handler.handle_packet(packet(1, false))?;
// One packet is played per call.
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
assert!(!handler.get_queues()[&ID].is_whispering());
Ok(())
}
}
+11 -5
View File
@@ -1,14 +1,17 @@
//! Voice pipeline building blocks.
//!
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
//! - [`packet`]: the voice packet types the pipeline takes and produces
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
//! - [`framer`]: slice an arbitrary sample stream into codec frames
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
//! - [`wav`]: WAV file input/output
//! - [`process`]: echo cancellation, noise suppression and gain control
//! - [`vad`]: voice activity detection
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
//! vendored `tsclientlib::audio::AudioHandler`)
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
//! buffer, mixing to stereo
//! - [`settings`]: all user audio settings in one serde struct
//! - [`tap`]: the processed microphone for other consumers (the stream
//! mixer), free while nobody listens
@@ -17,7 +20,9 @@
pub mod encode;
pub mod framer;
pub mod jitter;
pub mod mixer;
pub mod packet;
pub mod pcm;
pub mod process;
pub mod resample;
@@ -29,12 +34,13 @@ pub mod wav;
#[cfg(feature = "device")]
pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use encode::VoiceEncoder;
pub use framer::Framer;
pub use jitter::AudioHandler;
pub use mixer::Mixer;
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
pub use process::{ProcessingSettings, Processor};
pub use settings::AudioSettings;
pub use tsclientlib::audio::AudioHandler;
pub use vad::{Vad, VadSettings};
#[derive(Debug, thiserror::Error)]
+60 -65
View File
@@ -1,8 +1,8 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client, and everyone else dimmed while a priority
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
//! volume and mute per talker, and everyone else dimmed while a priority
//! speaker talks.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! The jitter buffer is [`AudioHandler`]. Per
//! sender it keeps a queue of Opus packets and adapts its length:
//!
//! - a new talker starts after a pre-buffer derived from the queue lengths of
@@ -21,13 +21,11 @@
use std::collections::{HashMap, HashSet};
use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
use crate::jitter::{AudioHandler, Error as QueueError};
use crate::packet::{TalkerId, VoicePacket};
use crate::pcm::FRAME_SAMPLES;
/// Loudest per-client volume: +12 dB.
/// Loudest per-talker volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Most a priority speaker dims the others (dB).
const MAX_DIMM_DB: f32 = -60.0;
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
/// samples (5 frames, 100 ms) instead of jumping.
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
/// Output is interleaved stereo at 48 kHz.
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
handler: AudioHandler,
volumes: HashMap<TalkerId, f32>,
muted: HashSet<TalkerId>,
/// While one of them talks, everyone else is dimmed.
priority: HashSet<ClientId>,
priority: HashSet<TalkerId>,
/// Linear gain of the others while a priority speaker talks (1: none).
dimm: f32,
/// How far the dimming has faded in (0..=1).
@@ -70,21 +68,17 @@ impl Mixer {
Self::default()
}
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
/// just started talking. Late, duplicate and malformed packets are
/// errors; on UDP they are expected and can be ignored.
pub fn handle_packet(
&mut self,
id: ClientId,
packet: InAudioBuf,
) -> Result<Option<ClientId>, QueueError> {
self.handler.handle_packet(id, packet)
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
/// talker just started talking. Late, duplicate and malformed packets are
/// errors; on datagrams they are expected and can be ignored.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
self.handler.handle_packet(packet)
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume, and dimmed while a
/// priority speaker talks. Returns the clients that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
/// priority speaker talks. Returns the talkers that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
let queues = self.handler.get_mut_queues();
// A priority speaker with a queue (talking or buffering) dims all
// other queues, streams too, unless we muted it.
@@ -141,9 +135,9 @@ impl Mixer {
stopped
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the client stops and starts talking again.
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the talker stops and starts talking again.
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
if volume == 1.0 {
self.volumes.remove(&id);
@@ -153,15 +147,15 @@ impl Mixer {
}
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
self.set_volume(id, 10f32.powf(db / 20.0));
}
pub fn volume(&self, id: ClientId) -> f32 {
pub fn volume(&self, id: TalkerId) -> f32 {
self.volumes.get(&id).copied().unwrap_or(1.0)
}
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
if muted {
self.muted.insert(id);
} else {
@@ -169,30 +163,30 @@ impl Mixer {
}
}
pub fn is_muted(&self, id: ClientId) -> bool {
pub fn is_muted(&self, id: TalkerId) -> bool {
self.muted.contains(&id)
}
/// The priority speakers, and how much everyone else is dimmed while
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
/// the caller sends a new set when the clients change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
/// the caller sends a new set when the talkers change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
self.priority = clients.into_iter().collect();
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
self.dimm = 10f32.powf(db / 20.0);
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
/// Forget volume and mute of a talker (e.g. it left the server; ids may
/// be reused).
pub fn forget(&mut self, id: TalkerId) {
self.volumes.remove(&id);
self.muted.remove(&id);
self.handler.get_mut_queues().remove(&id);
}
/// Clients with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
/// Talkers with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
self.handler.get_queues().keys().copied()
}
@@ -202,7 +196,7 @@ impl Mixer {
}
/// The underlying jitter buffer.
pub fn handler(&self) -> &AudioHandler<ClientId> {
pub fn handler(&self) -> &AudioHandler {
&self.handler
}
}
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
use super::*;
use crate::VoiceEncoder;
use crate::encode::VoiceCodec;
use crate::packet::VoiceCodec;
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
}
}
/// Two clients send tones at the same level; after setting volumes the
/// mix carries each at its own gain, and a muted one not at all.
#[test]
fn volume_per_client() {
let (a, b) = (ClientId(3), ClientId(4));
let (a, b) = (TalkerId(3), TalkerId(4));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 2.0, 0.2);
@@ -251,11 +248,11 @@ mod tests {
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
for (i, (fa, fb)) in frames.enumerate() {
let id = i as u16;
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
if i == 0 {
assert_eq!(started.unwrap(), Some(a));
}
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -274,8 +271,8 @@ mod tests {
let id = 100 + i;
let fa = &tone_a[..FRAME_SAMPLES];
let fb = &tone_b[..FRAME_SAMPLES];
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -289,7 +286,7 @@ mod tests {
/// in and out, but not itself, and not while we muted it.
#[test]
fn priority_speaker_dims_others() {
let (a, p) = (ClientId(3), ClientId(5));
let (a, p) = (TalkerId(3), TalkerId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 4.0, 0.2);
@@ -308,14 +305,12 @@ mod tests {
let mut out = Vec::new();
for _ in 0..frames {
let fa = frame(&tone_a, id_a);
mixer
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
.unwrap();
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
id_a += 1;
if with_p {
let fp = frame(&tone_p, id_p);
let data = enc_p.encode_to_bytes(&fp).unwrap();
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
mixer.handle_packet(packet(5, id_p, data)).unwrap();
id_p += 1;
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
@@ -359,7 +354,7 @@ mod tests {
/// frame: the other talker's level (per period of its tone) never jumps.
#[test]
fn priority_dimming_ramps_per_sample() {
let (a, p) = (ClientId(3), ClientId(5));
let p = TalkerId(5);
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = pcm::sine(500.0, 2.0, 0.2);
@@ -371,10 +366,10 @@ mod tests {
// p talks from frame 30 to 59.
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let id = i as u16;
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
let data = enc_p.encode_to_bytes(frame).unwrap();
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
@@ -400,17 +395,17 @@ mod tests {
fn priority_dimm_bounds() {
let mut mixer = Mixer::new();
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], -18.0);
mixer.set_priority([TalkerId(1)], -18.0);
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
mixer.set_priority([ClientId(1)], 6.0);
mixer.set_priority([TalkerId(1)], 6.0);
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
assert!((mixer.dimm - 0.001).abs() < 1e-6);
mixer.set_priority([ClientId(1)], f32::NAN);
mixer.set_priority([TalkerId(1)], f32::NAN);
assert_eq!(mixer.dimm, 1.0);
// Forgetting a client keeps the set: the caller replaces it.
mixer.forget(ClientId(1));
assert!(mixer.priority.contains(&ClientId(1)));
mixer.forget(TalkerId(1));
assert!(mixer.priority.contains(&TalkerId(1)));
mixer.set_priority([], -18.0);
assert!(mixer.priority.is_empty());
}
@@ -418,7 +413,7 @@ mod tests {
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
let id = ClientId(9);
let id = TalkerId(9);
mixer.set_volume(id, 100.0);
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
mixer.set_volume(id, -1.0);
+101
View File
@@ -0,0 +1,101 @@
//! 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<u8>,
}
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<u8>,
}
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());
}
}
+10 -12
View File
@@ -7,10 +7,8 @@
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let mut rng = Rng(ppm.to_bits());
let mut mixer = Mixer::new();
let client = ClientId(5);
let talker = TalkerId(5);
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
// Sender frame n is made at n * 20 ms of the sender's clock.
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
for (_, n) in in_flight.drain(..arrived) {
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
let packet = OutAudio::new(&AudioData::S2C {
id: n as u16,
codec: CodecType::OpusVoice,
from: 5,
data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
let packet = VoicePacket {
talker,
seq: n as u16,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.clone(),
};
// Late packets are dropped by the jitter buffer, as on a real network.
let _ = mixer.handle_packet(client, packet);
let _ = mixer.handle_packet(packet);
}
out.fill(0.0);
+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::*;
+1 -1
View File
@@ -70,7 +70,7 @@ fuzz/ cargo-fuzz targets
| `voelin-observer` | Presence tracker + chat relay pool over `voelin-query` | done |
| `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done |
| `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done |
| `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) |
| `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk; the voice packet types (`TalkerId`, `VoicePacket`, `EncodedVoice`), so it depends on no voice transport | v0 (no AEC yet) |
| `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport |
| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder) | done |
| `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) |
+27 -7
View File
@@ -2,10 +2,10 @@
```
microphone ─ cpal ─ resample 48 kHz mono ─ Processor (AEC3, NS, AGC2) ─ 20 ms frames
─ Vad / push-to-talk / continuous ─ Opus ─ voice connection
─ Vad / push-to-talk / continuous ─ Opus ─ EncodedVoice ─ voice connection
voice connection ─ Mixer (jitter buffer, Opus decode, per-client volume/mute,
priority speaker dimming)
voice connection ─ VoicePacket ─ Mixer (jitter buffer, Opus decode, per-talker
volume/mute, priority speaker dimming)
─ output volume ─┬─ resample to device ─ cpal ─ speakers
└─ Processor::render (echo canceller reference)
```
@@ -13,6 +13,25 @@ voice connection ─ Mixer (jitter buffer, Opus decode, per-client volume/mute,
The audio thread lives in `voelin-core/src/audio.rs`; the building blocks are in
`voelin-audio`. All user settings are one serde struct, `voelin_audio::AudioSettings`.
## Voice packets
`voelin-audio` knows no voice transport (it depends on no TeamSpeak crate). What
crosses its boundary are the plain types of `voelin_audio::packet`:
| Type | Meaning |
|---|---|
| `TalkerId(u16)` | who is talking; the key of the mixer's queues, volumes and mutes (TeamSpeak's client id is used as is, watched streams get made-up ids) |
| `VoiceCodec` | `Voice` (mono Opus, speech) or `Music` (stereo Opus) |
| `VoicePacket { talker, seq, codec, whisper, payload }` | one received Opus packet; `seq` counts up per talker and wraps, an empty `payload` (or a single byte) ends the talk |
| `EncodedVoice { codec, payload }` | one frame from `VoiceEncoder`, an empty `payload` ends the transmission |
The transport adapter converts between these and its wire format; for the
TeamSpeak connection that is `out_audio` and `voice_packet` in
`voelin-core/src/voice.rs`, the only place that builds TeamSpeak audio packets
from `EncodedVoice` or reads them into `VoicePacket`s (codecs other than Opus
are dropped there, as the jitter buffer never played them). The audio thread,
the session and the mixer see only the types above.
## Echo cancellation, noise suppression, gain control
[sonora](https://crates.io/crates/sonora) 0.2 (BSD-3-Clause), a pure Rust port of
@@ -51,9 +70,10 @@ two 20 ms frames before the gate opened are sent too, so onsets are not cut.
## Jitter buffer and clock drift
`Mixer` wraps the vendored `tsclientlib::audio::AudioHandler` (one queue per
talker) and adds per-client volume and mute, and priority speaker dimming. The
handler absorbs sender clock drift: an underrun plays Opus loss concealment for
`Mixer` wraps `voelin_audio::jitter::AudioHandler` (one queue per talker; it
started as `tsclientlib::audio::AudioHandler` and now reads `VoicePacket`s) and
adds per-talker volume and mute, and priority speaker dimming. The handler
absorbs sender clock drift: an underrun plays Opus loss concealment for
the missing frame (one inserted frame, and the talker is dropped after three in a
row), and when the smallest queue length over the last 255 packets exceeds its
spread, it drops every 100th sample (1 % faster) until the surplus is gone;
@@ -86,7 +106,7 @@ settings page shows as a meter with the threshold. Without a voice connection,
Per-client volume and mute are local (`SetClientVolume`, `SetClientMuted`); the
app keeps them by unique id and sends them again when the client shows up. Client
ids are reused, so the session forgets the settings of clients that left.
Watched streams play through the same mixer under made-up client ids (counting
Watched streams play through the same mixer under made-up talker ids (counting
down from 65535) with their own volume (`SetStreamVolume`).
While a priority speaker has a queue (talking, or buffering before it plays)
+1 -1
View File
@@ -294,7 +294,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
its layers live is seen with its next offer.
- The audio of watched streams does not go through this module: the session
hands the Opus frames to its audio thread, which plays them through the
jitter buffer and mixer under a made-up client id, with its own volume.
jitter buffer and mixer under a made-up talker id, with its own volume.
Playback is mono like the rest of the audio path.
## Stream audio
+36 -11
View File
@@ -4,16 +4,43 @@ use std::time::Duration;
use anyhow::{Context, Result, bail};
use tokio::time::Instant;
use tsclientlib::{ClientId, Connection, StreamItem};
use tsproto_packets::packets::AudioData;
use tsclientlib::{Connection, StreamItem};
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutPacket};
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use voelin_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder, resample, wav};
use voelin_audio::{
EncodedVoice, Framer, Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket, resample, wav,
};
use crate::VoiceCommand;
use crate::session::{Flow, PumpEnd, pump};
const FRAME: Duration = Duration::from_millis(20);
/// A voice frame as a TeamSpeak audio packet; the connection numbers it.
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 mixer; `None` for anything but
/// Opus voice.
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,
_ => return None,
};
Some(VoicePacket { talker: TalkerId(from), seq, codec, whisper, payload: data.to_vec() })
}
pub async fn run(con: &mut Connection, command: &VoiceCommand) -> Result<()> {
match command {
VoiceCommand::Send { file, tone, seconds, music } => {
@@ -68,13 +95,13 @@ async fn send(con: &mut Connection, codec: VoiceCodec, samples: &[f32]) -> Resul
let mut next = Instant::now();
for frame in &frames {
con.send_audio(encoder.encode(frame)?)?;
con.send_audio(out_audio(&encoder.encode(frame)?))?;
next += FRAME;
if pump(con, Some(next), |_, _| Ok(Flow::Continue)).await? == PumpEnd::Interrupted {
break;
}
}
con.send_audio(encoder.end_of_stream())?;
con.send_audio(out_audio(&encoder.end_of_stream()))?;
// Let the last packets go out.
pump(con, Some(Instant::now() + Duration::from_millis(200)), |_, _| Ok(Flow::Continue)).await?;
println!("sent {} frames ({:.1} s)", frames.len(), frames.len() as f32 * 0.02);
@@ -89,13 +116,11 @@ async fn record(con: &mut Connection, length: Duration) -> Result<Vec<f32>> {
let mut next = Instant::now() + FRAME;
while next <= end {
let end = pump(con, Some(next), |_, item| {
if let StreamItem::Audio(packet) = item {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => return Ok(Flow::Continue),
};
if let StreamItem::Audio(packet) = item
&& let Some(packet) = voice_packet(&packet)
{
// Late or duplicate packets are expected on UDP; the mixer drops them.
let _ = mixer.handle_packet(ClientId(from), packet);
let _ = mixer.handle_packet(packet);
}
Ok(Flow::Continue)
})