Unmodified copy of the tsclientlib workspace crates (MIT OR Apache-2.0)
with the tsdeclarations submodule (83cb8a9) flattened into plain files.
See crates/proto/UPSTREAM.md for the path mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 12:46:11 +00:00
commit 7b6959c4cc
119 files changed
+24322

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
[package]
name = "tsclientlib"
version = "0.2.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "A library to create TeamSpeak clients and bots."
repository = "https://github.com/ReSpeak/tsclientlib"
readme = "README.md"
keywords = ["teamspeak3", "ts3", "voip"]
categories = ["multimedia"]
license = "MIT OR Apache-2.0"
edition = "2018"
include = [
"/Cargo.toml",
"/README.md",
"**/*.rs",
]
[package.metadata.docs.rs]
features = ["unstable"]
[features]
default = ["audio", "default-tls"]
# Enable the unstable api
unstable = []
audio = ["audiopus"]
# Enable default reqwest features.
# Use default-features=false on tsclientlib to configure reqwest differently.
default-tls = ["reqwest/charset", "reqwest/default-tls", "reqwest/http2"]
# Use API of audiopus fork at https://github.com/Flakebi/audiopus for more features
audiopus-unstable = []
[dependencies]
audiopus = { version = "0.3.0-rc.0", optional = true }
base64 = "0.22"
futures = "0.3"
git-testament = "0.2"
itertools = "0.14"
num-traits = "0.2"
pin-utils = "0.1"
rand = "0.10"
reqwest = { version = "0.13", default-features = false }
thiserror = "2"
time = "0.3"
tokio = { version = "1", features = ["time"] }
tokio-stream = "0.1"
tracing = "0.1"
hickory-net = "0.26"
hickory-resolver = "0.26"
ts-bookkeeping = { path = "../utils/ts-bookkeeping", version = "0.1" }
tsproto = { path = "../tsproto", version = "0.2" }
tsproto-packets = { path = "../utils/tsproto-packets", version = "0.1" }
tsproto-types = { path = "../utils/tsproto-types", version = "0.1" }
url = "2"
[dev-dependencies]
anyhow = "1"
audiopus = "0.3.0-rc.0"
cpal = "0.18"
once_cell = "1"
quickcheck = "1"
quickcheck_macros = "1"
clap = { version = "4", features = ["derive"] }
tokio = { version = "1", features = ["io-util", "net", "rt-multi-thread", "rt", "signal"] }
tracing-subscriber = "0.3"
+21
View File
@@ -0,0 +1,21 @@
# TsClientlib [![docs.rs](https://docs.rs/tsclientlib/badge.svg)](https://docs.rs/tsclientlib)
tsclientlib is a library which makes it simple to create TeamSpeak clients
and bots.
For a full client application, you might want to have a look at [Qint].
If more power over the internals of a connection is needed, the `unstable` feature can be
enabled. Beware that functionality behind this feature may change on any minor release.
The base class of this library is the [`Connection`]. One instance of this
struct manages a single connection to a server.
[Qint]: https://github.com/ReSpeak/Qint
## License
Licensed under either of
* [Apache License, Version 2.0](../LICENSE-APACHE)
* [MIT license](../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# TsClientlib [![docs.rs](https://docs.rs/tsclientlib/badge.svg)](https://docs.rs/tsclientlib)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../LICENSE-APACHE)
* [MIT license](../LICENSE-MIT)
at your option.
@@ -0,0 +1,66 @@
use anyhow::Result;
use clap::Parser;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tracing::{debug, info};
use tsclientlib::ClientId;
use tsproto_packets::packets::{Direction, InAudioBuf};
mod audio_utils;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ConnectionId(u64);
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The volume for the capturing
#[arg(default_value_t = 1.0)]
volume: f32,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_id = ConnectionId(0);
let local_set = LocalSet::new();
let audiodata = audio_utils::start(&local_set)?;
let (send, mut recv) = mpsc::channel(1);
{
let mut a2t = audiodata.a2ts.lock().unwrap();
a2t.set_listener(send);
a2t.set_volume(args.volume);
a2t.set_playing(true);
}
let t2a = audiodata.ts2a.clone();
loop {
// Wait for ctrl + c
tokio::select! {
send_audio = recv.recv() => {
if let Some(packet) = send_audio {
let from = ClientId(0);
let mut t2a = t2a.lock().unwrap();
let in_audio = InAudioBuf::try_new(Direction::C2S, packet.into_vec()).unwrap();
if let Err(error) = t2a.play_packet((con_id, from), in_audio) {
debug!(%error, "Failed to play packet");
}
} else {
info!("Audio sending stream was canceled");
break;
}
}
_ = tokio::signal::ctrl_c() => { break; }
};
}
Ok(())
}
+127
View File
@@ -0,0 +1,127 @@
//! This example connects to a teamspeak instance and joins a channel.
//! The connected bot-identity will listen on your microphone and send everything to the current
//! channel. In parallel, the program will play back all other clients in the channel via its own
//! audio output.
//! Microphone -> Channel
//! Channel -> PC Speakers
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tracing::{debug, info};
use tsclientlib::{ClientId, Connection, DisconnectOptions, Identity, StreamItem};
use tsproto_packets::packets::AudioData;
mod audio_utils;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ConnectionId(u64);
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// The volume for the capturing
#[arg(default_value_t = 1.0)]
volume: f32,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_id = ConnectionId(0);
let local_set = LocalSet::new();
let audiodata = audio_utils::start(&local_set)?;
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
let (send, mut recv) = mpsc::channel(5);
{
let mut a2t = audiodata.a2ts.lock().unwrap();
a2t.set_listener(send);
a2t.set_volume(args.volume);
a2t.set_playing(true);
}
loop {
let t2a = audiodata.ts2a.clone();
let events = con.events().try_for_each(|e| async {
if let StreamItem::Audio(packet) = e {
let from = ClientId(match packet.data().data() {
AudioData::S2C { from, .. } => *from,
AudioData::S2CWhisper { from, .. } => *from,
_ => panic!("Can only handle S2C packets but got a C2S packet"),
});
let mut t2a = t2a.lock().unwrap();
if let Err(error) = t2a.play_packet((con_id, from), packet) {
debug!(%error, "Failed to play packet");
}
}
Ok(())
});
// Wait for ctrl + c
tokio::select! {
send_audio = recv.recv() => {
if let Some(packet) = send_audio {
con.send_audio(packet)?;
} else {
info!("Audio sending stream was canceled");
break;
}
}
_ = tokio::signal::ctrl_c() => { break; }
r = events => {
r?;
bail!("Disconnected");
}
};
}
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
@@ -0,0 +1,184 @@
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use anyhow::{Result, format_err};
use audiopus::coder::Encoder;
use cpal::traits::{DeviceTrait, StreamTrait};
use cpal::{Device, Stream, StreamConfig};
use futures::prelude::*;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tokio::time::{self, Duration};
use tokio_stream::wrappers::IntervalStream;
use tracing::{debug, error, instrument, warn};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use super::*;
pub struct AudioToTs {
device: Device,
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
stream: Option<Stream>,
is_playing: bool,
/// Storing an f32
volume: Arc<AtomicU32>,
}
struct Callback {
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
encoder: Encoder,
/// Storing an f32
volume: Arc<AtomicU32>,
tmp_buffer: [f32; USUAL_FRAME_SIZE * 2],
opus_output: [u8; MAX_OPUS_FRAME_SIZE],
}
impl AudioToTs {
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
let listener = Arc::new(Mutex::new(Default::default()));
let volume = Arc::new(AtomicU32::new(1.0_f32.to_bits()));
let res = Arc::new(Mutex::new(Self {
device,
listener,
stream: None,
is_playing: false,
volume,
}));
Self::start(res.clone(), local_set);
Ok(res)
}
#[instrument(skip(self))]
fn open_capture(&self) -> Result<Stream> {
let config = StreamConfig {
channels: 1,
sample_rate: 48000,
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
};
let encoder = Encoder::new(
audiopus::SampleRate::Hz48000,
audiopus::Channels::Mono,
audiopus::Application::Voip,
)
.expect("Could not create encoder");
let mut callback = Callback {
listener: self.listener.clone(),
encoder,
volume: self.volume.clone(),
tmp_buffer: [0.0; _],
opus_output: [0; _],
};
self.device
.build_input_stream(
config,
move |audio_data, _| callback.callback(audio_data),
|error| error!(%error, "Error during audio capture"),
Some(Duration::from_secs(5)),
)
.map_err(|e| format_err!("cpal error: {}", e))
}
pub fn set_listener(&self, sender: mpsc::Sender<OutPacket>) {
let mut listener = self.listener.lock().unwrap();
*listener = Some(sender);
}
pub fn set_volume(&mut self, volume: f32) {
self.volume.store(volume.to_bits(), Ordering::Relaxed);
}
pub fn set_playing(&mut self, playing: bool) {
if let Some(stream) = &self.stream {
if playing {
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
self.stream = None;
} else {
self.is_playing = true;
}
} else {
if let Err(error) = stream.pause() {
error!(%error, "Failed to pause stream");
self.stream = None;
}
self.is_playing = false;
}
}
}
#[instrument(skip(a2t, local_set))]
fn start(a2t: Arc<Mutex<Self>>, local_set: &LocalSet) {
local_set.spawn_local(
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
let mut a2t = a2t.lock().unwrap();
if a2t.stream.is_none() {
// Try to reconnect to audio
match a2t.open_capture() {
Ok(s) => {
a2t.stream = Some(s);
debug!("Reconnected to capture device");
if a2t.is_playing {
a2t.set_playing(true);
}
}
Err(error) => {
error!(%error, "Failed to open capture device");
}
};
}
future::ready(())
}),
);
}
}
impl Callback {
#[instrument(skip(self, buffer))]
fn callback<'a>(&'a mut self, mut buffer: &'a [f32]) {
// Handle volume
let volume = f32::from_bits(self.volume.load(Ordering::Relaxed));
if volume != 1.0 {
if self.tmp_buffer.len() < buffer.len() {
warn!("tmp buffer len smaller than received capture buffer, dropping data");
}
for (dst, src) in self.tmp_buffer.iter_mut().zip(buffer.iter()) {
*dst = *src * volume;
}
buffer = &self.tmp_buffer[..buffer.len()];
}
match self.encoder.encode_float(buffer, &mut self.opus_output[..]) {
Err(error) => {
error!(%error, "Failed to encode opus");
}
Ok(len) => {
// Create packet
let packet = OutAudio::new(&AudioData::C2S {
id: 0,
codec: CodecType::OpusVoice,
data: &self.opus_output[..len],
});
// Write into packet sink
let mut listener = self.listener.lock().unwrap();
if let Some(lis) = &mut *listener {
match lis.try_send(packet) {
Err(mpsc::error::TrySendError::Closed(_)) => *listener = None,
_ => {}
}
}
}
}
}
}
@@ -0,0 +1,37 @@
use std::sync::{Arc, Mutex};
use anyhow::Result;
use cpal::traits::HostTrait;
use tokio::task::LocalSet;
use audio_to_ts::AudioToTs;
use ts_to_audio::TsToAudio;
pub mod audio_to_ts;
pub mod ts_to_audio;
/// The usual frame size.
///
/// 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;
/// The maximum size of an opus frame is 1275 as from RFC6716.
const MAX_OPUS_FRAME_SIZE: usize = 1275;
#[derive(Clone)]
pub struct AudioData {
pub a2ts: Arc<Mutex<AudioToTs>>,
pub ts2a: Arc<Mutex<TsToAudio>>,
}
pub(crate) fn start(local_set: &LocalSet) -> Result<AudioData> {
let host = cpal::default_host();
let output_device = host.default_output_device().unwrap();
let input_device = host.default_input_device().unwrap();
let ts2a = TsToAudio::new(output_device, local_set)?;
let a2ts = AudioToTs::new(input_device, local_set)?;
Ok(AudioData { a2ts, ts2a })
}
@@ -0,0 +1,138 @@
use std::sync::{Arc, Mutex};
use anyhow::{Result, format_err};
use cpal::traits::{DeviceTrait, StreamTrait};
use cpal::{Device, Stream, StreamConfig};
use futures::prelude::*;
use tokio::task::LocalSet;
use tokio::time::{self, Duration};
use tokio_stream::wrappers::IntervalStream;
use tracing::{debug, error, instrument};
use tsclientlib::ClientId;
use tsproto_packets::packets::InAudioBuf;
use super::*;
use crate::ConnectionId;
type Id = (ConnectionId, ClientId);
type AudioHandler = tsclientlib::audio::AudioHandler<Id>;
pub struct TsToAudio {
device: Device,
stream: Option<Stream>,
is_playing: bool,
data: Arc<Mutex<AudioHandler>>,
}
struct Callback {
data: Arc<Mutex<AudioHandler>>,
}
impl TsToAudio {
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
let data = Arc::new(Mutex::new(AudioHandler::new()));
let res = Arc::new(Mutex::new(Self { device, stream: None, is_playing: false, data }));
Self::start(res.clone(), local_set);
Ok(res)
}
#[instrument(skip(self))]
fn open_playback(&self) -> Result<Stream> {
let config = StreamConfig {
channels: 2,
sample_rate: 48000,
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
};
let mut callback = Callback { data: self.data.clone() };
self.device
.build_output_stream(
config,
move |audio_data, _| callback.callback(audio_data),
|error| error!(%error, "Error during audio playback"),
Some(Duration::from_secs(5)),
)
.map_err(|e| format_err!("cpal error: {}", e))
}
#[instrument(skip(t2a, local_set))]
fn start(t2a: Arc<Mutex<Self>>, local_set: &LocalSet) {
local_set.spawn_local(
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
let mut t2a = t2a.lock().unwrap();
if t2a.stream.is_none() {
// Try to reconnect to audio
match t2a.open_playback() {
Ok(s) => {
t2a.stream = Some(s);
t2a.is_playing = false;
debug!("Reconnected to playback device");
}
Err(error) => {
error!(%error, "Failed to open playback device");
}
};
}
if let Some(stream) = &t2a.stream {
let data_empty = t2a.data.lock().unwrap().get_queues().is_empty();
if !t2a.is_playing && !data_empty {
debug!("Resuming playback");
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
t2a.stream = None;
} else {
t2a.is_playing = true;
}
} else if t2a.is_playing && data_empty {
debug!("Pausing playback");
if let Err(error) = stream.pause() {
error!(%error, "Failed to pause stream");
t2a.stream = None;
}
t2a.is_playing = false;
}
}
future::ready(())
}),
);
}
#[instrument(skip(self, id, packet))]
pub(crate) fn play_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<()> {
{
let mut data = self.data.lock().unwrap();
data.handle_packet(id, packet)?;
}
if !self.is_playing {
if let Some(stream) = &self.stream {
debug!("Resuming playback");
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
self.stream = None;
} else {
self.is_playing = true;
}
}
}
Ok(())
}
}
impl Callback {
fn callback(&mut self, buffer: &mut [f32]) {
// Clear buffer
for d in &mut *buffer {
*d = 0.0;
}
let mut data = self.data.lock().unwrap();
data.fill_buffer(buffer);
}
}
@@ -0,0 +1,129 @@
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::data::{self, Channel, Client};
use tsclientlib::prelude::*;
use tsclientlib::{ChannelId, Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
/// `channels` have to be ordered.
fn print_channels(clients: &[&Client], channels: &[&Channel], parent: ChannelId, depth: usize) {
let indention = " ".repeat(depth);
for channel in channels {
if channel.parent == parent {
println!("{}- {}", indention, channel.name);
// Print all clients in this channel
for client in clients {
if client.channel == channel.id {
println!("{} {}", indention, client.name);
}
}
print_channels(clients, channels, channel.id, depth + 1);
}
}
}
fn print_channel_tree(con: &data::Connection) {
let mut channels: Vec<_> = con.channels.values().collect();
let mut clients: Vec<_> = con.clients.values().collect();
// This is not the real sorting order, the order is the ChannelId of the
// channel on top of this one, but we don't care for this example.
channels.sort_by_key(|ch| ch.order.0);
clients.sort_by_key(|c| c.talk_power);
println!("{}", con.server.name);
print_channels(&clients, &channels, ChannelId(0), 0);
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
con.get_state().unwrap().server.set_subscribed(true).send(&mut con)?;
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(1)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Print channel tree
print_channel_tree(con.get_state().unwrap());
// Change name
{
let state = con.get_state().unwrap();
let name = state.clients[&state.own_client].name.clone();
state
.client_update()
.set_input_muted(true)
.set_name(&format!("{}1", name))
.send(&mut con)?;
}
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(3)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
+86
View File
@@ -0,0 +1,86 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tracing::error;
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
/// How many connections
#[arg()]
count: usize,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address.as_str())
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
stream::iter(0..args.count)
.for_each_concurrent(None, |_| {
let con_config = con_config.clone();
tokio::spawn(async move {
// Connect
let mut con = con_config.connect().unwrap();
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(Err(error)) = r {
error!(%error, "Connection failed");
return;
}
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(15)) => {}
_ = events.next() => {
error!("Disconnected unexpectedly");
return;
}
};
drop(events);
// Disconnect
let _ = con.disconnect(DisconnectOptions::new());
con.events().for_each(|_| future::ready(())).await;
})
.map(|_| ())
})
.await;
Ok(())
}
@@ -0,0 +1,78 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::sync::SyncConnection;
use tsclientlib::{Connection, DisconnectOptions, Identity};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let con: SyncConnection = con_config.connect()?.into();
let mut handle = con.get_handle();
// Do event handling in another thread
tokio::spawn(con.for_each(|_| future::ready(())));
handle.wait_until_connected().await?;
let welcome_message = handle
.with_connection(|con| Result::<_>::Ok(con.get_state()?.server.welcome_message.clone()))
.await??;
println!("Server welcome message: {}", sanitize(&welcome_message));
// Wait some time
time::sleep(Duration::from_secs(1)).await;
// Disconnect
handle.disconnect(DisconnectOptions::new()).await?;
Ok(())
}
/// Only retain a certain set of characters.
fn sanitize(s: &str) -> String {
s.chars()
.filter(|c| {
c.is_alphanumeric()
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
.contains(c)
})
.collect()
}
@@ -0,0 +1,85 @@
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
println!("Server welcome message: {}", sanitize(&con.get_state()?.server.welcome_message));
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(1)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
/// Only retain a certain set of characters.
fn sanitize(s: &str) -> String {
s.chars()
.filter(|c| {
c.is_alphanumeric()
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
.contains(c)
})
.collect()
}
+77
View File
@@ -0,0 +1,77 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::prelude::*;
use tsclientlib::sync::SyncConnection;
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
let sync_con: SyncConnection = con.into();
let mut con = sync_con.get_handle();
tokio::spawn(sync_con.for_each(|_| future::ready(())));
con.with_connection(move |mut con| {
let state = con.get_state()?;
state.server.send_textmessage("Hello there").send(&mut con)?;
Result::<_>::Ok(())
})
.await??;
// Wait some time
time::sleep(Duration::from_secs(1)).await;
// Disconnect
con.disconnect(DisconnectOptions::new()).await?;
Ok(())
}
+876
View File
@@ -0,0 +1,876 @@
//! Handle receiving audio.
//!
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
//! client. 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 std::fmt::Debug;
use std::hash::Hash;
use audiopus::coder::Decoder;
#[cfg(feature = "audiopus-unstable")]
use audiopus::coder::GenericCtl;
use audiopus::{Channels, SampleRate, packet};
use thiserror::Error;
use tracing::{Span, debug, info_span, trace, warn};
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf};
use crate::ClientId;
const SAMPLE_RATE: SampleRate = SampleRate::Hz48000;
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] audiopus::Error),
#[error("Opus decode failed: {error} (packet: {packet:?})")]
Decode {
#[source]
error: audiopus::Error,
packet: Option<Vec<u8>>,
},
#[error("Get duplicate packet id {0}")]
Duplicate(u16),
#[error("Failed to get packet samples: {0}")]
GetPacketSample(#[source] audiopus::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,
#[error("Only opus audio is supported, ignoring {0:?}")]
UnsupportedCodec(CodecType),
}
#[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: InAudioBuf,
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 sending client.
pub struct AudioHandler<Id: Clone + Debug + Eq + Hash + PartialEq = ClientId> {
queues: HashMap<Id, 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: InAudioBuf) -> Result<Self> {
let data = packet.data().data();
let opus_packet = data.data().try_into().map_err(Error::GetPacketSample)?;
let last_packet_samples =
packet::nb_samples(opus_packet, 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 = matches!(data, AudioData::S2CWhisper { .. });
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
// Enable DRED and NoLACE, ignore errors e.g. if unsupported
#[cfg(feature = "audiopus-unstable")]
let decoder = {
let mut decoder = decoder;
if let Err(error) = decoder.set_complexity(7) {
debug!(%error, "Failed setting opus decoder complexity, ignoring");
}
decoder
};
let mut res = Self {
span: Span::current(),
decoder,
volume: 1.0,
next_id: data.id(),
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: InAudioBuf) -> Result<()> {
let _span = self.span.enter();
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
return Err(Error::QueueFull);
}
let samples;
if packet.data().data().data().len() <= 1 {
// End of stream
samples = 0;
} else {
let opus_packet =
packet.data().data().data().try_into().map_err(Error::GetPacketSample)?;
samples =
packet::nb_samples(opus_packet, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
if samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
}
let id = packet.data().data().id();
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) {
if 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 =
Some(p.packet.data().data().data().try_into().map_err(Error::GetPacketSample)?);
len = p.samples;
self.whispering = matches!(p.packet.data().data(), AudioData::S2CWhisper { .. });
} else {
packet_data = None;
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..])
.try_into()
.map_err(Error::GetPacketSample)?,
fec,
)
.map_err(|e| Error::Decode {
error: e,
packet: packet.map(|p| p.packet.raw_data().to_vec()),
})?;
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.data().data().data().len() <= 1 {
// 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<Id: Clone + Debug + Eq + Hash + PartialEq> Default for AudioHandler<Id> {
fn default() -> Self { Self { queues: Default::default(), avg_buffer_samples: 0 } }
}
impl<Id: Clone + Debug + Eq + Hash + PartialEq> AudioHandler<Id> {
pub fn new() -> Self { Default::default() }
/// Delete all queues
pub fn reset(&mut self) { self.queues.clear(); }
pub fn get_queues(&self) -> &HashMap<Id, AudioQueue> { &self.queues }
pub fn get_mut_queues(&mut self) -> &mut HashMap<Id, 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<Id> {
self.fill_buffer_with_proc(buf, |_, _| {})
}
/// `buf` is not cleared before filling it.
///
/// Same as [`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(&Id, &[f32])>(
&mut self, buf: &mut [f32], mut handle: F,
) -> Vec<Id> {
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.clone());
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.clone());
}
}
}
}
for id in &to_remove {
self.queues.remove(id);
}
to_remove
}
/// Add a packet to the audio queue.
///
/// If a new client started talking, returns the id of this client.
pub fn handle_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<Option<Id>> {
let empty = packet.data().data().data().len() <= 1;
let codec = packet.data().data().codec();
if codec != CodecType::OpusMusic && codec != CodecType::OpusVoice {
return Err(Error::UnsupportedCodec(codec));
}
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
self.avg_buffer_samples = USUAL_FRAME_SIZE
+ self
.queues
.values()
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
.sum::<usize>() / self.queues.len();
}
queue.buffering_samples = self.avg_buffer_samples;
self.queues.insert(id.clone(), queue);
Ok(Some(id))
}
}
}
#[cfg(test)]
mod test {
use anyhow::{Result, bail};
use audiopus::coder::Encoder;
use tsproto_packets::packets::{Direction, OutAudio};
use super::*;
use crate::tests::create_logger;
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<ClientId>)>),
}
/// Helper function to check an audio packet.
#[allow(dead_code)]
fn check_packet(data: &[u8]) -> Result<()> {
create_logger();
let mut handler = AudioHandler::<ClientId>::new();
let id = ClientId(0);
let mut buf = vec![0.0; 48_000 / 100 * 2];
// Sometimes, TS sends short, non-opus packets
let packet =
OutAudio::new(&AudioData::S2C { id: 30, codec: CodecType::OpusMusic, from: 0, data });
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
handler.handle_packet(id, input)?;
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
Ok(())
}
fn simulate(actions: Vec<SimulateAction>) -> Result<()> {
let mut encoder = None;
let mut opus_output = [0; 1275]; // Max size for an opus packet
let id = ClientId(0);
create_logger();
let mut handler = AudioHandler::<ClientId>::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(
audiopus::SampleRate::Hz48000,
audiopus::Channels::Mono,
audiopus::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[..])?;
let packet = OutAudio::new(&AudioData::S2C {
id: i,
codec: CodecType::OpusMusic,
from: 0,
data: &opus_output[..len],
});
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
if handler.handle_packet(id, input).is_ok() != success {
bail!("handle_packet returned {:?} but expected {:?}", !success, success);
}
}
SimulateAction::ReceiveRaw(i, data) => {
let packet = OutAudio::new(&AudioData::S2C {
id: i,
codec: CodecType::OpusMusic,
from: 0,
data: &data,
});
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
let _ = handler.handle_packet(id, input);
}
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);
}
/*if let Some(e) = expect {
let e = *e as f32;
for b in &buf {
if (*b - e).abs() > 0.01 {
bail!("Buffer contains wrong value, \
expected {}: {:?}", e, buf);
}
}
}*/
}
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() {
create_logger();
let mut handler = AudioHandler::<ClientId>::new();
let id = ClientId(0);
let mut buf = vec![0.0; 48_000 / 100 * 2];
for i in 0..100 {
let packet = OutAudio::new(&AudioData::S2C {
id: 65_500u16.wrapping_add(i),
codec: CodecType::OpusMusic,
from: 0,
data: &[0, 0, 0, 0, 0, 0, 0],
});
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
handler.handle_packet(id, input).unwrap();
if i > 5 {
handler.fill_buffer(&mut buf);
}
}
}
#[quickcheck_macros::quickcheck]
fn short_packet_quickcheck(data: Vec<Vec<u8>>) {
create_logger();
let mut handler = AudioHandler::<ClientId>::new();
let id = ClientId(0);
let mut buf = vec![0.0; 48_000 / 100 * 2];
for p in data {
// Sometimes, TS sends short, non-opus packets
let packet = OutAudio::new(&AudioData::S2C {
id: 30,
codec: CodecType::OpusMusic,
from: 0,
data: &p,
});
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
let _ = handler.handle_packet(id, input);
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
}
}
#[test]
fn packets_wrapping2() -> Result<()> {
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() -> Result<()> {
let mut a = vec![SimulateAction::CreateEncoder];
for _ in 0..100 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
simulate(a)
}
#[test]
fn reversed() -> Result<()> {
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() -> Result<()> {
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() -> Result<()> {
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() -> Result<()> {
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() -> Result<()> {
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() -> Result<()> {
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)
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
pub use ts_bookkeeping::data::exts::*;
pub use ts_bookkeeping::messages::OutMessageTrait;
pub use crate::OutCommandExt as _;
+514
View File
@@ -0,0 +1,514 @@
//! Resolve TeamSpeak server addresses of any kind.
// Changes with TeamSpeak client 3.1:
// https://support.teamspeakusa.com/index.php?/Knowledgebase/Article/View/332
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::str;
use futures::prelude::*;
use hickory_net::proto::rr::RData;
use hickory_resolver::TokioResolver;
use hickory_resolver::config::{CLOUDFLARE, ResolverConfig, ResolverOpts};
use hickory_resolver::net::runtime::TokioRuntimeProvider;
use itertools::Itertools;
use rand::RngExt;
use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{self, TcpStream};
use tokio::time::Duration;
use tracing::{debug, instrument, warn};
const DEFAULT_PORT: u16 = 9987;
const DNS_PREFIX_TCP: &str = "_tsdns._tcp.";
const DNS_PREFIX_UDP: &str = "_ts3._udp.";
const NICKNAME_LOOKUP_ADDRESS: &str = "https://named.myteamspeak.com/lookup";
/// Wait this amount of seconds before giving up.
const TIMEOUT_SECONDS: u64 = 10;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create resolver: {0}")]
CreateResolver(#[source] hickory_net::NetError),
#[error("Invalid IPv4 address")]
InvalidIp4Address,
#[error("Invalid IPv6 address")]
InvalidIp6Address,
#[error("Invalid IP address")]
InvalidIpAddress,
#[error("Not a valid nickname")]
InvalidNickname,
#[error("Failed to parse port: {0}")]
InvalidPort(#[source] std::num::ParseIntError),
#[error("Failed to contact {0} server: {1}")]
Io(&'static str, #[source] std::io::Error),
#[error("Failed to parse url: {0}")]
NicknameParseUrl(#[source] url::ParseError),
#[error("Failed to resolve nickname: {0}")]
NicknameResolve(#[source] reqwest::Error),
#[error("Failed to resolve hostname: {0}")]
ResolveHost(#[source] tokio::io::Error),
#[error("Failed to get SRV record")]
SrvLookup(#[source] hickory_net::NetError),
#[error("tsdns did not return an ip address but {0:?}")]
TsdnsAddressInvalidResponse(String),
#[error("tsdns server does not know the address")]
TsdnsAddressNotFound,
#[error("Failed to parse tsdns response: {0}")]
TsdnsParseResponse(#[source] std::str::Utf8Error),
}
#[derive(Debug, PartialEq, Eq)]
enum ParseIpResult<'a> {
Addr(SocketAddr),
Other(&'a str, Option<u16>),
}
/// Beware that this may be slow because it tries all available methods.
///
/// The following methods are tried:
/// 1. If the address is an ip, the ip is returned
/// 1. Server nicknames are resolved by a http request to TeamSpeak
/// 1. The SRV record at `_ts3._udp.<address>`
/// 1. The SRV record at `_tsdns._tcp.address.tld` to get the address of a tsdns
/// server, e.g. when the address is `ts3.subdomain.from.com`, the SRV record
/// at `_tsdns._tcp.from.com` is requested
/// 1. Directly resolve the address to an ip address
///
/// If a port is given with `:port`, it overwrites the automatically determined
/// port. IPv6 addresses are put in square brackets when a port is present:
/// `[::1]:9987`
#[instrument]
pub fn resolve(address: String) -> impl Stream<Item = Result<SocketAddr>> {
debug!("Starting resolve");
let addr;
let port;
match parse_ip(&address) {
Ok(ParseIpResult::Addr(res)) => {
return stream::once(future::ok(res)).left_stream();
}
Ok(ParseIpResult::Other(a, p)) => {
addr = a.to_string();
port = p;
if let Some(port) = port {
debug!(port, "Found port");
}
}
Err(res) => return stream::once(future::err(res)).left_stream(),
}
// Resolve as nickname
let res = if !address.contains('.') && addr != "localhost" {
debug!("Resolving nickname");
// Could be a server nickname
resolve_nickname(address.clone())
.map_ok(move |mut addr| {
if let Some(port) = port {
addr.set_port(port);
}
addr
})
.left_stream()
} else {
stream::once(future::err(Error::InvalidNickname)).right_stream()
};
// The system config does not yet work on android:
// https://github.com/bluejekyll/trust-dns/issues/652
let addr2 = addr.clone();
// TODO Move current span into stream
let res = res.chain(
stream::once(async move {
let resolver = create_resolver()?;
// Try to get the address by an SRV record
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_UDP}{addr2}.")))
})
.try_flatten(),
);
// Try to get the address of a tsdns server by an SRV record
let addr2 = addr.clone();
// TODO Move current span into stream
let res = res.chain(
stream::once(async move {
let resolver = create_resolver()?;
// Trim address to two components
let name = if let Some(i) = addr2.rfind('.').and_then(|i| addr2[..i].rfind('.')) {
&addr2[i + 1..]
} else {
&addr2
};
// Pick the first srv record of the first server that answers
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_TCP}{name}.")).and_then(
move |srv| {
let address = address.clone();
async move {
// Got tsdns server
let mut addr = resolve_tsdns(srv, &address).await?;
if let Some(port) = port {
// Overwrite port if it was specified
addr.set_port(port);
}
Ok(addr)
}
},
))
})
.try_flatten(),
);
// Interpret as normal address and resolve with system resolver
let res = res.chain(
stream::once(async move {
let res = net::lookup_host((addr.as_str(), port.unwrap_or(DEFAULT_PORT)))
.await
.map_err(Error::ResolveHost)?
.map(Ok)
.collect::<Vec<_>>();
Result::<_>::Ok(stream::iter(res))
})
.try_flatten(),
);
// TODO Move current span into stream
tokio_stream::StreamExt::timeout(res, Duration::from_secs(TIMEOUT_SECONDS))
.filter_map(move |r: std::result::Result<Result<SocketAddr>, _>| {
future::ready(match r {
// Timeout
Err(_) => None,
// Error
Ok(Err(error)) => {
debug!(%error, "Resolver failed in one step");
None
}
// Success
Ok(Ok(r)) => Some(Ok(r)),
})
})
.right_stream()
}
// Windows for some reason automatically adds a link-local address to the dns
// resolver. These addresses are usually not reachable and should be filtered out.
// See: https://superuser.com/questions/638566/strange-value-in-dns-shown-in-ipconfig
const FILTERED_IPS: &[IpAddr] = &[
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 1)),
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 2)),
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 3)),
];
fn create_resolver() -> Result<TokioResolver> {
let (config, options) = match hickory_resolver::system_conf::read_system_conf() {
Ok((mut config, options)) => {
config.name_servers.retain(|ns| !FILTERED_IPS.contains(&ns.ip));
(config, options)
}
Err(error) => {
warn!(%error, "Failed to use system dns resolver config");
// Fallback
(ResolverConfig::udp_and_tcp(&CLOUDFLARE), ResolverOpts::default())
}
};
let mut builder = TokioResolver::builder_with_config(config, TokioRuntimeProvider::default());
*builder.options_mut() = options;
builder.build().map_err(Error::CreateResolver)
}
fn parse_ip(address: &str) -> Result<ParseIpResult<'_>> {
let mut addr = address;
let mut port = None;
if let Some(pos) = address.rfind(':') {
// Either with port or IPv6 address
if address.find(':').unwrap() == pos {
// Port is appended
addr = &address[..pos];
port = Some(&address[pos + 1..]);
if addr.chars().all(|c| c.is_ascii_digit() || c == '.') {
// IPv4 address
return Ok(ParseIpResult::Addr(
std::net::ToSocketAddrs::to_socket_addrs(address)
.map_err(|_| Error::InvalidIp4Address)?
.next()
.ok_or(Error::InvalidIp4Address)?,
));
}
} else if let Some(pos_bracket) = address.rfind(']') {
if pos_bracket < pos {
// IPv6 address and port
return Ok(ParseIpResult::Addr(
std::net::ToSocketAddrs::to_socket_addrs(address)
.map_err(|_| Error::InvalidIp6Address)?
.next()
.ok_or(Error::InvalidIp6Address)?,
));
} else if pos_bracket == address.len() - 1 && address.starts_with('[') {
// IPv6 address
return Ok(ParseIpResult::Addr(
std::net::ToSocketAddrs::to_socket_addrs(&(
&address[1..pos_bracket],
DEFAULT_PORT,
))
.map_err(|_| Error::InvalidIp6Address)?
.next()
.ok_or(Error::InvalidIp6Address)?,
));
} else {
return Err(Error::InvalidIpAddress);
}
} else {
// IPv6 address
return Ok(ParseIpResult::Addr(
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
.map_err(|_| Error::InvalidIp6Address)?
.next()
.ok_or(Error::InvalidIp6Address)?,
));
}
} else if address.chars().all(|c| c.is_ascii_digit() || c == '.') {
// IPv4 address
return Ok(ParseIpResult::Addr(
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
.map_err(|_| Error::InvalidIp4Address)?
.next()
.ok_or(Error::InvalidIp4Address)?,
));
}
let port = if let Some(port) = port.map(|p| p.parse().map_err(Error::InvalidPort)) {
Some(port?)
} else {
None
};
Ok(ParseIpResult::Other(addr, port))
}
pub fn resolve_nickname(nickname: String) -> impl Stream<Item = Result<SocketAddr>> {
stream::once(async {
let nickname = nickname;
let url =
reqwest::Url::parse_with_params(NICKNAME_LOOKUP_ADDRESS, Some(("name", &nickname)))
.map_err(Error::NicknameParseUrl)?;
let body = reqwest::get(url)
.await
.map_err(Error::NicknameResolve)?
.error_for_status()
.map_err(Error::NicknameResolve)?
.text()
.await
.map_err(Error::NicknameResolve)?;
let addrs = body
.split(&['\r', '\n'][..])
.filter(|s| !s.is_empty())
.map(|s| Result::<_>::Ok(s.to_string()))
.collect::<Vec<_>>();
Result::<_>::Ok(
stream::iter(addrs)
.and_then(|addr| async move {
match parse_ip(&addr)? {
ParseIpResult::Addr(a) => Ok(stream::once(future::ok(a)).left_stream()),
ParseIpResult::Other(a, p) => {
let addrs = net::lookup_host((a, p.unwrap_or(DEFAULT_PORT)))
.await
.map_err(Error::ResolveHost)?
.collect::<Vec<_>>();
Ok(stream::iter(addrs).map(Result::<_>::Ok).right_stream())
}
}
})
.try_flatten(),
)
})
.try_flatten()
}
pub async fn resolve_tsdns<A: net::ToSocketAddrs>(server: A, addr: &str) -> Result<SocketAddr> {
let mut stream = TcpStream::connect(server).await.map_err(|e| Error::Io("tsdns", e))?;
stream.write_all(addr.as_bytes()).await.map_err(|e| Error::Io("tsdns", e))?;
let mut data = Vec::new();
stream.read_to_end(&mut data).await.map_err(|e| Error::Io("tsdns", e))?;
let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?;
if addr.starts_with("404") {
return Err(Error::TsdnsAddressNotFound);
}
match parse_ip(addr)? {
ParseIpResult::Addr(a) => Ok(a),
_ => Err(Error::TsdnsAddressInvalidResponse(addr.to_string())),
}
}
fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream<Item = Result<SocketAddr>> {
stream::once(async {
let lookup = resolver.srv_lookup(addr).await.map_err(Error::SrvLookup)?;
let srvs = lookup
.answers()
.iter()
.map(|r| {
let RData::SRV(srv) = &r.data else { panic!("Unexpected answer") };
srv.clone()
})
.collect::<Vec<_>>();
let prios = srvs.iter().chunk_by(|srv| srv.priority);
let entries = prios.into_iter().sorted_by_key(|(p, _)| *p);
// Select by weight
let mut sorted_entries = Vec::new();
for (_, es) in entries {
let mut zero_entries = Vec::new();
// All non-zero entries
let mut entries = es
.filter_map(|e| {
if e.weight == 0 {
zero_entries.push(e);
None
} else {
Some(e)
}
})
.collect::<Vec<_>>();
while !entries.is_empty() {
let weight: u32 = entries.iter().map(|e| e.weight as u32).sum();
let mut w = rand::rng().random_range(0..=weight);
if w == 0 {
// Pick the first entry with weight 0
if let Some(i) = entries.iter().position(|e| e.weight == 0) {
sorted_entries.push(entries.remove(i));
}
}
for i in 0..entries.len() {
let weight = entries[i].weight as u32;
if w <= weight {
sorted_entries.push(entries.remove(i));
break;
}
w -= weight;
}
}
}
let res = sorted_entries
.into_iter()
.map(|e| Ok((e.target.to_ascii(), e.port)))
.collect::<Vec<Result<(String, u16)>>>();
drop(resolver);
Ok(stream::iter(res)
.and_then(|(e, port)| async move {
let res = net::lookup_host((e.as_str(), port))
.await
.map_err(Error::ResolveHost)?
.map(Ok)
.collect::<Vec<_>>();
Ok(stream::iter(res))
})
.try_flatten())
})
.try_flatten()
}
#[cfg(test)]
mod test {
use super::*;
use crate::tests::create_logger;
#[test]
fn parse_ip_without_port() {
let res = parse_ip("127.0.0.1");
assert_eq!(
res.unwrap(),
ParseIpResult::Addr(format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap())
);
}
#[test]
fn parse_ip_with_port() {
let res = parse_ip("127.0.0.1:1");
assert_eq!(res.unwrap(), ParseIpResult::Addr("127.0.0.1:1".parse().unwrap()));
}
#[test]
fn parse_ip6_without_port() {
let res = parse_ip("::");
assert_eq!(
res.unwrap(),
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
);
}
#[test]
fn parse_ip6_without_port2() {
let res = parse_ip("[::]");
assert_eq!(
res.unwrap(),
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
);
}
#[test]
fn parse_ip6_with_port() {
let res = parse_ip("[::]:1");
assert_eq!(res.unwrap(), ParseIpResult::Addr("[::]:1".parse().unwrap()));
}
#[test]
fn parse_ip_address_without_port() {
assert_eq!(parse_ip("localhost").unwrap(), ParseIpResult::Other("localhost", None));
}
#[test]
fn parse_ip_address_with_port() {
assert_eq!(parse_ip("localhost:1").unwrap(), ParseIpResult::Other("localhost", Some(1)));
}
#[test]
fn parse_ip_with_large_port() {
assert!(parse_ip("127.0.0.1:65536").is_err());
}
#[tokio::test]
async fn resolve_localhost() {
create_logger();
let res: Vec<_> = resolve("127.0.0.1".into()).map(|r| r.unwrap()).collect().await;
let addr = format!("127.0.0.1:{}", DEFAULT_PORT).parse::<SocketAddr>().unwrap();
assert_eq!(res.as_slice(), &[addr]);
}
#[tokio::test]
async fn resolve_localhost2() {
create_logger();
let res: Vec<_> = resolve("localhost".into()).map(|r| r.unwrap()).collect().await;
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
}
#[tokio::test]
async fn resolve_example() {
create_logger();
let res: Vec<_> = resolve("example.com".into()).map(|r| r.unwrap()).collect().await;
assert!(!res.is_empty());
}
#[tokio::test]
async fn resolve_splamy_de() {
create_logger();
let res: Vec<_> = tokio::time::timeout(
Duration::from_secs(5),
resolve("splamy.de".into()).map(|r| r.unwrap()).collect(),
)
.await
.expect("Resolve takes unacceptable long");
assert!(res.contains(&format!("37.120.179.68:{}", DEFAULT_PORT).parse().unwrap()));
}
#[tokio::test]
async fn resolve_loc() {
create_logger();
let res: Vec<_> = resolve("loc".into()).map(|r| r.unwrap()).collect().await;
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
}
}
+470
View File
@@ -0,0 +1,470 @@
//! The `sync` module contains an easier to use interface for a connection.
//!
//! It makes it easier to use a connection from multiple threads and use
//! `async`/`await` syntax for the cost of a little bit performance.
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::prelude::*;
use tokio::sync::{mpsc, oneshot};
use tracing::{error, info};
use ts_bookkeeping::ChannelId;
#[cfg(feature = "audio")]
use tsproto_packets::packets::InAudioBuf;
#[cfg(feature = "unstable")]
use tsproto_packets::packets::OutCommand;
use crate::{
events, AudioEvent, DisconnectOptions, Error, InMessage, Result, StreamItem,
TemporaryDisconnectReason,
};
enum SyncConMessage {
RunFn(Box<dyn FnOnce(&mut SyncConnection) + Send>),
#[cfg(feature = "unstable")]
SendCommand(OutCommand, oneshot::Sender<Result<()>>),
WaitConnected(oneshot::Sender<Result<()>>),
Disconnect(DisconnectOptions, oneshot::Sender<Result<()>>),
DownloadFile {
channel_id: ChannelId,
path: String,
channel_password: Option<String>,
seek_position: Option<u64>,
send: oneshot::Sender<Result<super::FileDownloadResult>>,
},
UploadFile {
channel_id: ChannelId,
path: String,
channel_password: Option<String>,
size: u64,
overwrite: bool,
resume: bool,
send: oneshot::Sender<Result<super::FileUploadResult>>,
},
}
/// This is a subset of [`StreamItem`](crate::StreamItem).
pub enum SyncStreamItem {
/// All the incoming book events.
///
/// If a connection to the server was established this will contain an added event of a server.
BookEvents(Vec<events::Event>),
/// All incoming messages that are not related to the book.
///
/// This contains messages like `ChannelListFinished` or `ClientChatComposing`.
/// All events related to channels or clients are returned as events in the `BookEvents`
/// variant. Other messages handled by tsclientlib, e.g. for filetransfer are also not included
/// in these events.
MessageEvent(InMessage),
/// Received an audio packet.
///
/// Audio packets can be handled by the [`AudioHandler`](crate::audio::AudioHandler), which
/// builds a queue per client and handles packet loss and jitter.
#[cfg(feature = "audio")]
Audio(InAudioBuf),
/// The needed level.
IdentityLevelIncreasing(u8),
/// This event may occur without an `IdentityLevelIncreasing` event before
/// if a new identity is created because no identity was supplied.
IdentityLevelIncreased,
/// The connection timed out or the server shut down. The connection will be
/// rebuilt automatically.
DisconnectedTemporarily(TemporaryDisconnectReason),
/// The network statistics were updated.
///
/// This means e.g. the packet loss got a new value. Clients with audio probably want to update
/// the packet loss option of opus.
NetworkStatsUpdated,
/// A change related to audio.
AudioChange(AudioEvent),
}
/// A handle for a [`SyncConnection`] which can be sent across threads.
///
/// All actions like sending messages, downloading and uploading happens through
/// a handle.
#[derive(Clone)]
pub struct SyncConnectionHandle {
send: mpsc::Sender<SyncConMessage>,
}
pub struct SyncConnection {
con: super::Connection,
recv: mpsc::Receiver<SyncConMessage>,
send: mpsc::Sender<SyncConMessage>,
commands: HashMap<super::MessageHandle, oneshot::Sender<Result<()>>>,
connects: Vec<oneshot::Sender<Result<()>>>,
disconnects: Vec<oneshot::Sender<Result<()>>>,
downloads:
HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileDownloadResult>>>,
uploads: HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileUploadResult>>>,
}
impl From<super::Connection> for SyncConnection {
fn from(con: super::Connection) -> Self {
let (send, recv) = mpsc::channel(1);
Self {
con,
recv,
send,
commands: Default::default(),
connects: Default::default(),
disconnects: Default::default(),
downloads: Default::default(),
uploads: Default::default(),
}
}
}
impl Deref for SyncConnection {
type Target = super::Connection;
#[inline]
fn deref(&self) -> &Self::Target { &self.con }
}
impl DerefMut for SyncConnection {
#[inline]
fn deref_mut(&mut self) -> &mut <Self as Deref>::Target { &mut self.con }
}
impl Stream for SyncConnection {
type Item = Result<SyncStreamItem>;
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
let _span = self.con.span.clone().entered();
loop {
if let Poll::Ready(msg) = self.recv.poll_recv(ctx) {
if let Some(msg) = msg {
match msg {
SyncConMessage::RunFn(f) => f(&mut self),
#[cfg(feature = "unstable")]
SyncConMessage::SendCommand(arg, send) => {
let handle = match self.con.send_command_with_result(arg) {
Ok(r) => r,
Err(e) => {
let _ = send.send(Err(e));
continue;
}
};
self.commands.insert(handle, send);
}
SyncConMessage::WaitConnected(send) => {
if self.con.get_state().is_ok() {
let _ = send.send(Ok(()));
} else {
self.connects.push(send);
}
}
SyncConMessage::Disconnect(arg, send) => {
match self.con.disconnect(arg) {
Ok(r) => r,
Err(e) => {
let _ = send.send(Err(e));
continue;
}
}
self.disconnects.push(send);
}
SyncConMessage::DownloadFile {
channel_id,
path,
channel_password,
seek_position,
send,
} => {
let handle = match self.con.download_file(
channel_id,
&path,
channel_password.as_deref(),
seek_position,
) {
Ok(r) => r,
Err(e) => {
let _ = send.send(Err(e));
continue;
}
};
self.downloads.insert(handle, send);
}
SyncConMessage::UploadFile {
channel_id,
path,
channel_password,
size,
overwrite,
resume,
send,
} => {
let handle = match self.con.upload_file(
channel_id,
&path,
channel_password.as_deref(),
size,
overwrite,
resume,
) {
Ok(r) => r,
Err(e) => {
let _ = send.send(Err(e));
continue;
}
};
self.uploads.insert(handle, send);
}
}
continue;
} else {
error!("Message stream ended unexpectedly");
}
}
break;
}
loop {
break if let Poll::Ready(item) = self.con.poll_next(ctx) {
Poll::Ready(match item {
Some(Ok(item)) => Some(Ok(match item {
StreamItem::BookEvents(i) => {
self.connects.drain(..).for_each(|send| {
let _ = send.send(Ok(()));
});
SyncStreamItem::BookEvents(i)
}
StreamItem::MessageEvent(i) => SyncStreamItem::MessageEvent(i),
#[cfg(feature = "audio")]
StreamItem::Audio(i) => SyncStreamItem::Audio(i),
StreamItem::IdentityLevelIncreasing(i) => {
SyncStreamItem::IdentityLevelIncreasing(i)
}
StreamItem::IdentityLevelIncreased => {
SyncStreamItem::IdentityLevelIncreased
}
StreamItem::DisconnectedTemporarily(reason) => {
SyncStreamItem::DisconnectedTemporarily(reason)
}
StreamItem::MessageResult(handle, res) => {
if let Some(send) = self.commands.remove(&handle) {
let _ = send.send(res.map_err(|e| e.into()));
} else {
info!("Got untracked message result");
}
continue;
}
StreamItem::FileDownload(handle, res) => {
if let Some(send) = self.downloads.remove(&handle) {
let _ = send.send(Ok(res));
} else {
info!("Got untracked download");
}
continue;
}
StreamItem::FileUpload(handle, res) => {
if let Some(send) = self.uploads.remove(&handle) {
let _ = send.send(Ok(res));
} else {
info!("Got untracked upload");
}
continue;
}
StreamItem::FiletransferFailed(handle, res) => {
if let Some(send) = self.downloads.remove(&handle) {
let _ = send.send(Err(res));
} else if let Some(send) = self.uploads.remove(&handle) {
let _ = send.send(Err(res));
} else {
info!("Got untracked file transfer");
}
continue;
}
StreamItem::NetworkStatsUpdated => SyncStreamItem::NetworkStatsUpdated,
StreamItem::AudioChange(change) => SyncStreamItem::AudioChange(change),
})),
Some(Err(e)) => Some(Err(e)),
None => {
self.disconnects.drain(..).for_each(|send| {
let _ = send.send(Ok(()));
});
None
}
})
} else {
Poll::Pending
};
}
}
}
impl SyncConnection {
/// Get a handle to the connection that can be sent across threads.
#[inline]
pub fn get_handle(&self) -> SyncConnectionHandle {
SyncConnectionHandle { send: self.send.clone() }
}
}
impl SyncConnectionHandle {
/// Run a function on the connection.
pub async fn with_connection<
T: Send + 'static,
F: FnOnce(&mut SyncConnection) -> T + Send + 'static,
>(
&mut self, f: F,
) -> Result<T> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::RunFn(Box::new(move |con| {
let _ = send.send(f(con));
})))
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)
}
/// Adds a `return_code` to the command and returns if the corresponding
/// answer is received. If an error occurs, the future will return an error.
#[cfg(feature = "unstable")]
pub async fn send_command(&mut self, arg: OutCommand) -> Result<()> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::SendCommand(arg, send))
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)?
}
/// This future resolves once the connection is connected to the server.
pub async fn wait_until_connected(&mut self) -> Result<()> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::WaitConnected(send))
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)?
}
/// Disconnect from the server.
///
/// # Arguments
/// - `options`: Either `None` or `DisconnectOptions`.
///
/// # Examples
///
/// Use default options:
///
/// ```no_run
/// # use futures::prelude::*;
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, StreamItem};
/// # use tsclientlib::sync::SyncConnection;
///
/// # #[tokio::main]
/// # async fn main() {
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
/// let mut handle = con.get_handle();
/// tokio::spawn(con.for_each(|_| future::ready(())));
/// // Wait until connected
/// handle.wait_until_connected().await.unwrap();
///
/// // Disconnect
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
/// # }
/// ```
///
/// Specify a reason and a quit message:
///
/// ```no_run
/// # use futures::prelude::*;
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, Reason, StreamItem};
/// # use tsclientlib::sync::SyncConnection;
///
/// # #[tokio::main]
/// # async fn main() {
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
/// let mut handle = con.get_handle();
/// tokio::spawn(con.for_each(|_| future::ready(())));
/// // Wait until connected
/// handle.wait_until_connected().await.unwrap();
///
/// // Disconnect
/// let options = DisconnectOptions::new()
/// .reason(Reason::Clientdisconnect)
/// .message("Away for a while");
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
/// # }
/// ```
pub async fn disconnect(&mut self, arg: DisconnectOptions) -> Result<()> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::Disconnect(arg, send))
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)?
}
/// Download a file from a channel of the connected TeamSpeak server.
///
/// Returns the size of the file and a tcp stream of the requested file.
///
/// # Example
/// Download an icon.
///
/// ```no_run
/// # use tsclientlib::ChannelId;
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
/// # let id = 0;
/// let download = handle.download_file(ChannelId(0), format!("/icon_{}", id), None, None);
/// ```
pub async fn download_file(
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
seek_position: Option<u64>,
) -> Result<super::FileDownloadResult> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::DownloadFile {
channel_id,
path,
channel_password,
seek_position,
send,
})
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)?
}
/// Upload a file to a channel of the connected TeamSpeak server.
///
/// Returns the size of the part which is already uploaded (when resume is
/// specified) and a tcp stream where the requested file should be uploaded.
///
/// # Example
/// Upload an avatar.
///
/// ```no_run
/// # use tsclientlib::ChannelId;
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
/// # let size = 0;
/// let upload = handle.upload_file(ChannelId(0), "/avatar".to_string(), None, size, true, false);
/// ```
pub async fn upload_file(
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
size: u64, overwrite: bool, resume: bool,
) -> Result<super::FileUploadResult> {
let (send, recv) = oneshot::channel();
self.send
.send(SyncConMessage::UploadFile {
channel_id,
path,
channel_password,
size,
overwrite,
resume,
send,
})
.await
.map_err(|_| Error::ConnectionGone)?;
recv.await.map_err(|_| Error::ConnectionGone)?
}
}
+37
View File
@@ -0,0 +1,37 @@
use once_cell::sync::Lazy;
use ts_bookkeeping::messages::s2c::InMessage;
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
pub(crate) fn create_logger() { Lazy::force(&TRACING); }
fn parse_msg(msg: &str) -> InMessage {
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
InMessage::new(&header.header(), msg.as_bytes()).unwrap()
}
fn test_iconid(input: &str, expected: u32) {
create_logger();
let msg = parse_msg(&format!(
r#"initserver virtualserver_name=TeamSpeak\s]I[\sServer virtualserver_welcomemessage=Welcome\sto\sTeamSpeak,\scheck\s[URL]www.teamspeak.com[\/URL]\sfor\slatest\sinformation virtualserver_platform=Linux virtualserver_version=3.11.0\s[Build:\s1578903157] virtualserver_maxclients=32 virtualserver_created=1571572631 virtualserver_codec_encryption_mode=2 virtualserver_hostmessage virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 virtualserver_default_channel_group=8 virtualserver_hostbanner_url virtualserver_hostbanner_gfx_url virtualserver_hostbanner_gfx_interval=0 virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 virtualserver_hostbutton_tooltip virtualserver_hostbutton_url virtualserver_hostbutton_gfx_url virtualserver_name_phonetic virtualserver_ip=0.0.0.0,\s:: virtualserver_ask_for_privilegekey=0 virtualserver_hostbanner_mode=0 virtualserver_channel_temp_delete_delay_default=0 virtualserver_nickname client_nickname=TeamSpeakUser client_version=3.?.?\s[Build:\s5680278000] client_platform=Windows client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 client_output_hardware=1 client_default_channel client_default_channel_password client_server_password client_meta_data client_version_sign=DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg== client_security_hash client_key_offset=354 client_away=0 client_away_message client_nickname_phonetic client_default_token client_badges client_myteamspeak_id client_integrations client_active_integrations_info client_myteamspeak_avatar client_signed_badges acn=TeamSpeakUser aclid=2 pv=7 client_talk_power=75 client_needed_serverquery_view_power=75 virtualserver_icon_id={}"#,
input
));
if let InMessage::InitServer(list) = msg {
let cmd = list.iter().next().unwrap();
assert_eq!(cmd.icon, ts_bookkeeping::IconId(expected));
} else {
panic!("Failed to parse as initserver");
}
}
#[test]
fn normal_iconid() { test_iconid("96136942", 96136942); }
#[test]
fn negative_iconid() { test_iconid("-96136942", 4198830354); }
#[test]
fn big_iconid() { test_iconid("18446744073225738240", 3811153920); }