M2: tsc-audio, tsc-store and tsctl voice

- tsc-audio: Opus voice/music encoder producing TeamSpeak voice packets,
  framer, rubato resampling, WAV I/O, tone/Goertzel helpers, cpal
  capture/playback over lock-free ring buffers; the vendored
  AudioHandler is the jitter buffer/mixer.
- tsc-store: SQLite (bundled, WAL, 0600) with migrations for identities,
  bookmarks, settings and paged chat history; Secrets trait with memory
  and OS keyring backends.
- tsctl voice send (WAV or tone, real time) / record (mix to WAV,
  --expect-tone check). The smoke test now includes a voice round-trip:
  1 kHz tone ratio ~0.95 on TS3 and TS6.
- Dev profile: no debug info for dependencies (target/ 16 GB -> 2.4 GB).

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 13:56:01 +00:00
1 parent 339fa32f1b
commit 908e5566c4
20 files changed
+2379 -35

No files matched your search

Generated
+974 -25
View File
File diff suppressed because it is too large. Load diff
+13
View File
@@ -8,7 +8,9 @@ members = [
"crates/proto/tsproto",
"crates/proto/ts-bookkeeping",
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-model",
"crates/tsc-store",
"tools/tsctl",
]
default-members = [
@@ -18,7 +20,9 @@ default-members = [
"crates/proto/tsproto",
"crates/proto/ts-bookkeeping",
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-model",
"crates/tsc-store",
"tools/tsctl",
]
@@ -39,3 +43,12 @@ all = { level = "warn", priority = -1 }
# The Init1 puzzle does a large modular exponentiation on connect; unoptimized
# it takes seconds.
opt-level = 3
[profile.dev]
# Line tables (for backtraces) for workspace crates, no debug info for
# dependencies: keeps target/ several times smaller. Override locally for
# debugging with CARGO_PROFILE_DEV_DEBUG=true.
debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
+15 -7
View File
@@ -23,14 +23,20 @@ See [docs/architecture.md](docs/architecture.md) for the design and milestones.
## Status
Milestone **M0 (foundation)**:
Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)):
- `crates/proto/`: vendored tsclientlib (see [UPSTREAM.md](crates/proto/UPSTREAM.md) for the patch log)
- `tools/tsctl`: headless CLI that connects, prints the channel tree, sends and receives chat
- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers for local testing
- CI: build and test on Linux and Windows, `cargo-deny`, smoke test against both servers
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
- `crates/tsc-model`: server flavor detection (TS3 / TS6) and capabilities
- `crates/tsc-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events
- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh`
checks tree, server chat, channel chat and a voice tone round-trip on both
- `fuzz/`: cargo-fuzz targets for packets, commands and the license chain
No GUI, voice or screen sharing yet.
No GUI and no screen sharing yet.
## Try it
@@ -41,8 +47,10 @@ docker compose -f dev/docker-compose.yml up -d
cargo run -p tsctl -- connect 127.0.0.1:9987 tree # TeamSpeak 3
cargo run -p tsctl -- connect 127.0.0.1:9988 tree # TeamSpeak 6
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav
scripts/it-smoke.sh # tree + server/channel chat round-trips on both servers
scripts/it-smoke.sh # tree, chat and voice round-trips on both servers
```
Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect <addr> listen|chat|raw`.
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "tsc-audio"
version = "0.1.0"
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["device"]
# Audio device I/O through cpal (needs ALSA headers on Linux).
device = ["dep:cpal", "dep:rtrb"]
[dependencies]
cpal = { version = "0.18", optional = true }
hound = "3.5.1"
opus2 = "0.4"
rtrb = { version = "0.4.0", optional = true }
rubato = "5.0.0"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[lints]
workspace = true
+134
View File
@@ -0,0 +1,134 @@
//! Audio capture and playback through cpal.
//!
//! The device callbacks only move samples through lock-free ring buffers; all
//! processing happens on the caller's side.
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use rtrb::{Consumer, Producer, RingBuffer};
use tracing::warn;
use crate::{Error, Result};
/// A device as shown in settings.
#[derive(Clone, Debug)]
pub struct DeviceInfo {
pub name: String,
pub input: bool,
pub output: bool,
}
fn device_error(e: impl std::fmt::Display) -> Error {
Error::Device(e.to_string())
}
/// All devices of the default host.
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
let host = cpal::default_host();
let devices = host.devices().map_err(device_error)?;
Ok(devices
.map(|d| DeviceInfo {
name: d.description().map(|d| d.name().to_string()).unwrap_or_default(),
input: d.supports_input(),
output: d.supports_output(),
})
.collect())
}
/// Running capture stream. Samples are interleaved at the device's rate.
pub struct Capture {
_stream: cpal::Stream,
consumer: Consumer<f32>,
pub channels: usize,
pub rate: u32,
}
impl Capture {
/// Open the default input device, buffering up to `buffer_ms` of audio.
pub fn open_default(buffer_ms: u32) -> Result<Self> {
let device = cpal::default_host()
.default_input_device()
.ok_or_else(|| Error::Device("no input device".into()))?;
let config = device.default_input_config().map_err(device_error)?.config();
let channels = config.channels as usize;
let rate = config.sample_rate;
let (mut producer, consumer) =
RingBuffer::new((rate * buffer_ms / 1000) as usize * channels);
let stream = device
.build_input_stream(
config,
move |data: &[f32], _: &cpal::InputCallbackInfo| {
let n = producer.slots().min(data.len());
if let Ok(chunk) = producer.write_chunk_uninit(n) {
chunk.fill_from_iter(data[..n].iter().copied());
}
},
|error| warn!(%error, "capture stream error"),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, consumer, channels, rate })
}
/// Move everything captured so far into `out`.
pub fn read_available(&mut self, out: &mut Vec<f32>) {
let n = self.consumer.slots();
if let Ok(chunk) = self.consumer.read_chunk(n) {
out.extend(chunk);
}
}
}
/// Running playback stream. Write interleaved samples at the device's rate.
pub struct Playback {
_stream: cpal::Stream,
producer: Producer<f32>,
pub channels: usize,
pub rate: u32,
}
impl Playback {
pub fn open_default(buffer_ms: u32) -> Result<Self> {
let device = cpal::default_host()
.default_output_device()
.ok_or_else(|| Error::Device("no output device".into()))?;
let config = device.default_output_config().map_err(device_error)?.config();
let channels = config.channels as usize;
let rate = config.sample_rate;
let (producer, mut consumer) =
RingBuffer::<f32>::new((rate * buffer_ms / 1000) as usize * channels);
let stream = device
.build_output_stream(
config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
let n = consumer.slots().min(data.len());
if let Ok(chunk) = consumer.read_chunk(n) {
for (dst, src) in data.iter_mut().zip(chunk) {
*dst = src;
}
}
// Underrun: play silence.
data[n..].fill(0.0);
},
|error| warn!(%error, "playback stream error"),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, producer, channels, rate })
}
/// Queue samples; returns how many fit into the buffer.
pub fn write(&mut self, samples: &[f32]) -> usize {
let n = self.producer.slots().min(samples.len());
if let Ok(chunk) = self.producer.write_chunk_uninit(n) {
chunk.fill_from_iter(samples[..n].iter().copied());
}
n
}
/// Samples that can be written without blocking.
pub fn free(&self) -> usize {
self.producer.slots()
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Opus encoding into TeamSpeak voice packets.
use opus2::{Application, Bitrate, Channels, Encoder};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use crate::pcm::{FRAME_SAMPLES, 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.
pub struct VoiceEncoder {
encoder: Encoder,
codec: VoiceCodec,
out: Vec<u8>,
}
impl VoiceEncoder {
pub fn new(codec: VoiceCodec) -> Result<Self> {
let (channels, application) = match codec {
VoiceCodec::Voice => (Channels::Mono, Application::Voip),
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
};
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
// Survive some packet loss: TeamSpeak voice is plain UDP.
encoder.set_inband_fec(true)?;
encoder.set_packet_loss_perc(5)?;
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
}
pub fn codec(&self) -> VoiceCodec {
self.codec
}
/// Target bitrate in bits per second.
pub fn set_bitrate(&mut self, bps: i32) -> Result<()> {
self.encoder.set_bitrate(Bitrate::Bits(bps))?;
Ok(())
}
/// Encode one frame of [`VoiceCodec::frame_len`] interleaved samples.
pub fn encode_to_bytes(&mut self, frame: &[f32]) -> Result<&[u8]> {
if frame.len() != self.codec.frame_len() {
return Err(Error::Invalid(format!(
"frame has {} samples, expected {}",
frame.len(),
self.codec.frame_len()
)));
}
let len = self.encoder.encode_float(frame, &mut self.out)?;
Ok(&self.out[..len])
}
/// Encode one frame 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 }))
}
/// 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: &[] })
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{Direction, InAudioBuf};
use super::*;
use crate::pcm;
/// Encode a tone, feed the packets through the mixer (jitter buffer +
/// decoder), and check the tone comes out.
#[test]
fn roundtrip_through_mixer() {
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut mixer = crate::Mixer::new();
let tone = pcm::sine(1000.0, 1.0, 0.5);
let mut decoded = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let 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 mut out = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut out);
decoded.extend(pcm::to_mono(&out, 2));
}
// Skip the jitter buffer's initial latency and the codec warm-up.
let tail = &decoded[decoded.len() / 2..];
let ratio = pcm::tone_ratio(tail, 1000.0, SAMPLE_RATE);
assert!(ratio > 0.8, "tone ratio {ratio}");
}
#[test]
fn rejects_wrong_frame_size() {
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
assert!(encoder.encode(&[0.0; FRAME_SAMPLES]).is_err());
assert!(encoder.encode(&[0.0; FRAME_SAMPLES * 2]).is_ok());
}
}
+57
View File
@@ -0,0 +1,57 @@
//! Cut a continuous sample stream into fixed-size frames.
/// Buffers samples until a whole frame is available.
#[derive(Debug)]
pub struct Framer {
frame_len: usize,
buf: Vec<f32>,
}
impl Framer {
/// `frame_len` is in samples (all channels, interleaved).
pub fn new(frame_len: usize) -> Self {
assert!(frame_len > 0);
Self { frame_len, buf: Vec::with_capacity(frame_len * 2) }
}
/// Append samples and call `f` for every complete frame.
pub fn push(&mut self, samples: &[f32], mut f: impl FnMut(&[f32])) {
self.buf.extend_from_slice(samples);
let whole = self.buf.len() / self.frame_len * self.frame_len;
for frame in self.buf[..whole].chunks_exact(self.frame_len) {
f(frame);
}
self.buf.drain(..whole);
}
/// Pad the remaining samples with silence into one last frame, if any.
pub fn flush(&mut self, f: impl FnOnce(&[f32])) {
if !self.buf.is_empty() {
self.buf.resize(self.frame_len, 0.0);
f(&self.buf);
self.buf.clear();
}
}
pub fn buffered(&self) -> usize {
self.buf.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_and_flushes() {
let mut framer = Framer::new(4);
let mut frames = Vec::new();
framer.push(&[1.0, 2.0, 3.0], |f| frames.push(f.to_vec()));
assert!(frames.is_empty());
framer.push(&[4.0, 5.0, 6.0, 7.0, 8.0, 9.0], |f| frames.push(f.to_vec()));
assert_eq!(frames, vec![vec![1.0, 2.0, 3.0, 4.0], vec![5.0, 6.0, 7.0, 8.0]]);
assert_eq!(framer.buffered(), 1);
framer.flush(|f| frames.push(f.to_vec()));
assert_eq!(frames[2], vec![9.0, 0.0, 0.0, 0.0]);
}
}
+42
View File
@@ -0,0 +1,42 @@
//! Voice pipeline building blocks.
//!
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
//! - [`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
//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored
//! `tsclientlib::audio::AudioHandler`)
//! - `device` (feature `device`): capture and playback through cpal
pub mod encode;
pub mod framer;
pub mod pcm;
pub mod resample;
pub mod wav;
#[cfg(feature = "device")]
pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use framer::Framer;
pub use tsclientlib::audio::AudioHandler;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
pub type Mixer = AudioHandler<tsclientlib::ClientId>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("opus: {0}")]
Opus(#[from] opus2::Error),
#[error("wav: {0}")]
Wav(#[from] hound::Error),
#[error("resampling failed: {0}")]
Resample(String),
#[error("audio device: {0}")]
Device(String),
#[error("invalid input: {0}")]
Invalid(String),
}
pub type Result<T> = std::result::Result<T, Error>;
+101
View File
@@ -0,0 +1,101 @@
//! PCM constants and helpers.
use std::f32::consts::TAU;
/// The sample rate TeamSpeak's Opus codecs run at.
pub const SAMPLE_RATE: u32 = 48_000;
/// Samples per channel in one 20 ms frame.
pub const FRAME_SAMPLES: usize = SAMPLE_RATE as usize / 50;
/// A sine tone, mono, at [`SAMPLE_RATE`].
pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec<f32> {
let n = (seconds * SAMPLE_RATE as f32) as usize;
(0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect()
}
/// Average interleaved channels into mono.
pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec<f32> {
if channels <= 1 {
return interleaved.to_vec();
}
interleaved.chunks_exact(channels).map(|f| f.iter().sum::<f32>() / channels as f32).collect()
}
/// Duplicate mono samples into `channels` interleaved channels.
pub fn from_mono(mono: &[f32], channels: usize) -> Vec<f32> {
mono.iter().flat_map(|&s| std::iter::repeat_n(s, channels)).collect()
}
/// Power of one frequency in `samples` (Goertzel algorithm), normalised so a
/// full-scale sine at `freq` gives about 0.25 per sample squared.
pub fn goertzel_power(samples: &[f32], freq: f32, rate: u32) -> f32 {
if samples.is_empty() {
return 0.0;
}
let coeff = 2.0 * (TAU * freq / rate as f32).cos();
let (mut s1, mut s2) = (0.0f32, 0.0f32);
for &x in samples {
let s = x + coeff * s1 - s2;
s2 = s1;
s1 = s;
}
let power = s1 * s1 + s2 * s2 - coeff * s1 * s2;
power / (samples.len() as f32 * samples.len() as f32)
}
/// Mean square of the signal.
pub fn energy(samples: &[f32]) -> f32 {
if samples.is_empty() {
return 0.0;
}
samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32
}
/// Fraction of the signal energy at `freq`: close to 1 for a clean tone,
/// close to 0 for silence or noise.
pub fn tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 {
let e = energy(samples);
if e < 1e-9 {
return 0.0;
}
// A sine of amplitude a has energy a²/2 and Goertzel power a²/4.
(2.0 * goertzel_power(samples, freq, rate) / e).min(1.0)
}
/// Like [`tone_ratio`], but only over the 100 ms windows that are not silent,
/// so leading and trailing silence in a recording do not dilute the result.
pub fn voiced_tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 {
let window = rate as usize / 10;
let ratios: Vec<f32> = samples
.chunks_exact(window)
.filter(|w| energy(w) > 1e-4)
.map(|w| tone_ratio(w, freq, rate))
.collect();
if ratios.is_empty() { 0.0 } else { ratios.iter().sum::<f32>() / ratios.len() as f32 }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_tone() {
let tone = sine(1000.0, 0.5, 0.5);
assert!(tone_ratio(&tone, 1000.0, SAMPLE_RATE) > 0.95);
assert!(tone_ratio(&tone, 440.0, SAMPLE_RATE) < 0.05);
assert_eq!(tone_ratio(&[0.0; 100], 1000.0, SAMPLE_RATE), 0.0);
let mut padded = vec![0.0; SAMPLE_RATE as usize];
padded.extend(&tone);
padded.extend(vec![0.0; SAMPLE_RATE as usize]);
assert!(tone_ratio(&padded, 1000.0, SAMPLE_RATE) < 0.5);
assert!(voiced_tone_ratio(&padded, 1000.0, SAMPLE_RATE) > 0.95);
assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0);
}
#[test]
fn channel_conversion() {
assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]);
assert_eq!(from_mono(&[1.0, 2.0], 2), vec![1.0, 1.0, 2.0, 2.0]);
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Sample-rate conversion.
use rubato::audioadapter_buffers::direct::InterleavedSlice;
use rubato::{Fft, FixedSync, Resampler};
use crate::{Error, Result};
/// Resample a whole interleaved clip from `from` Hz to `to` Hz.
pub fn resample_all(samples: &[f32], channels: usize, from: u32, to: u32) -> Result<Vec<f32>> {
if from == to || samples.is_empty() {
return Ok(samples.to_vec());
}
if channels == 0 || !samples.len().is_multiple_of(channels) {
return Err(Error::Invalid(format!("{} samples for {channels} channels", samples.len())));
}
let frames = samples.len() / channels;
let mut resampler =
Fft::<f32>::new(from as usize, to as usize, 1024, channels, FixedSync::Input)
.map_err(|e| Error::Resample(e.to_string()))?;
let input = InterleavedSlice::new(samples, channels, frames)
.map_err(|e| Error::Resample(e.to_string()))?;
let output =
resampler.process_all(&input, frames, None).map_err(|e| Error::Resample(e.to_string()))?;
Ok(output.take_data())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pcm;
#[test]
fn keeps_tone_across_rates() {
// 1 kHz at 44.1 kHz, resampled to 48 kHz.
let n = 44_100;
let tone: Vec<f32> = (0..n)
.map(|i| 0.5 * (std::f32::consts::TAU * 1000.0 * i as f32 / 44_100.0).sin())
.collect();
let out = resample_all(&tone, 1, 44_100, 48_000).unwrap();
assert!((out.len() as i64 - 48_000).abs() < 100, "len {}", out.len());
assert!(pcm::tone_ratio(&out, 1000.0, 48_000) > 0.95);
}
#[test]
fn passthrough_and_errors() {
assert_eq!(resample_all(&[1.0, 2.0], 1, 48_000, 48_000).unwrap(), vec![1.0, 2.0]);
assert!(resample_all(&[1.0, 2.0, 3.0], 2, 44_100, 48_000).is_err());
}
}
+65
View File
@@ -0,0 +1,65 @@
//! WAV file input and output (float samples in memory).
use std::path::Path;
use hound::{SampleFormat, WavReader, WavSpec, WavWriter};
use crate::Result;
/// Interleaved samples plus their format.
#[derive(Clone, Debug, PartialEq)]
pub struct Clip {
pub samples: Vec<f32>,
pub channels: usize,
pub rate: u32,
}
pub fn read(path: &Path) -> Result<Clip> {
let mut reader = WavReader::open(path)?;
let spec = reader.spec();
let samples = match spec.sample_format {
SampleFormat::Float => reader.samples::<f32>().collect::<std::result::Result<_, _>>()?,
SampleFormat::Int => {
let scale = 1.0 / (1u64 << (spec.bits_per_sample - 1)) as f32;
reader
.samples::<i32>()
.map(|s| s.map(|s| s as f32 * scale))
.collect::<std::result::Result<_, _>>()?
}
};
Ok(Clip { samples, channels: spec.channels as usize, rate: spec.sample_rate })
}
/// Write 16-bit PCM.
pub fn write(path: &Path, clip: &Clip) -> Result<()> {
let spec = WavSpec {
channels: clip.channels as u16,
sample_rate: clip.rate,
bits_per_sample: 16,
sample_format: SampleFormat::Int,
};
let mut writer = WavWriter::create(path, spec)?;
for &s in &clip.samples {
writer.write_sample((s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)?;
}
writer.finalize()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip() {
let path = std::env::temp_dir().join(format!("tsc-audio-{}.wav", std::process::id()));
let clip = Clip { samples: vec![0.0, 0.5, -0.5, 0.25], channels: 2, rate: 48_000 };
write(&path, &clip).unwrap();
let back = read(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!((back.channels, back.rate), (2, 48_000));
for (a, b) in clip.samples.iter().zip(&back.samples) {
assert!((a - b).abs() < 1e-3);
}
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "tsc-store"
version = "0.1.0"
description = "Local persistence: identities, bookmarks, settings, chat cache and secrets."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = []
# Store secrets in the OS keyring (Secret Service, Windows Credential Manager, Keychain).
keyring = ["dep:keyring"]
[dependencies]
keyring = { version = "4.2.0", optional = true }
rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
thiserror = "2.0.21"
tsclientlib = { path = "../proto/tsclientlib" }
[lints]
workspace = true
+31
View File
@@ -0,0 +1,31 @@
//! Local persistence for the client.
//!
//! One SQLite database holds identities, bookmarks, settings and a chat
//! cache. Passwords and query credentials never go into the database; they
//! live in a [`Secrets`] store (the OS keyring with the `keyring` feature).
mod secrets;
mod store;
#[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets;
pub use secrets::{MemorySecrets, Secrets};
pub use store::{
Bookmark, ChatTarget, IdentityEntry, QueryConfig, QueryTransport, Store, StoredMessage,
};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("database: {0}")]
Db(#[from] rusqlite::Error),
#[error("serialization: {0}")]
Json(#[from] serde_json::Error),
#[error("{0} {1} not found")]
NotFound(&'static str, i64),
#[error("secret store: {0}")]
Secrets(String),
#[error("io: {0}")]
Io(#[from] std::io::Error),
}
pub type Result<T> = std::result::Result<T, Error>;
+91
View File
@@ -0,0 +1,91 @@
//! Storage for passwords and credentials.
use std::collections::HashMap;
use std::sync::Mutex;
use crate::Result;
/// Key-value secret storage. `key` names what the secret is for, e.g.
/// `bookmark/3/server-password` or `bookmark/3/query-password`.
pub trait Secrets: Send + Sync {
fn get(&self, key: &str) -> Result<Option<String>>;
fn set(&self, key: &str, value: &str) -> Result<()>;
fn delete(&self, key: &str) -> Result<()>;
}
/// In-memory secrets, for tests and platforms without a keyring.
#[derive(Default)]
pub struct MemorySecrets(Mutex<HashMap<String, String>>);
impl Secrets for MemorySecrets {
fn get(&self, key: &str) -> Result<Option<String>> {
Ok(self.0.lock().unwrap().get(key).cloned())
}
fn set(&self, key: &str, value: &str) -> Result<()> {
self.0.lock().unwrap().insert(key.to_string(), value.to_string());
Ok(())
}
fn delete(&self, key: &str) -> Result<()> {
self.0.lock().unwrap().remove(key);
Ok(())
}
}
/// The platform keyring: Secret Service on Linux, Credential Manager on
/// Windows, Keychain on macOS.
#[cfg(feature = "keyring")]
pub struct KeyringSecrets {
service: String,
}
#[cfg(feature = "keyring")]
impl KeyringSecrets {
/// `service` distinguishes this application's entries, e.g. the app id.
pub fn new(service: impl Into<String>) -> Self {
Self { service: service.into() }
}
fn entry(&self, key: &str) -> Result<keyring::Entry> {
keyring::Entry::new(&self.service, key).map_err(|e| crate::Error::Secrets(e.to_string()))
}
}
#[cfg(feature = "keyring")]
impl Secrets for KeyringSecrets {
fn get(&self, key: &str) -> Result<Option<String>> {
match self.entry(key)?.get_password() {
Ok(v) => Ok(Some(v)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(crate::Error::Secrets(e.to_string())),
}
}
fn set(&self, key: &str, value: &str) -> Result<()> {
self.entry(key)?.set_password(value).map_err(|e| crate::Error::Secrets(e.to_string()))
}
fn delete(&self, key: &str) -> Result<()> {
match self.entry(key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(crate::Error::Secrets(e.to_string())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memory_secrets() {
let s = MemorySecrets::default();
assert_eq!(s.get("a").unwrap(), None);
s.set("a", "1").unwrap();
assert_eq!(s.get("a").unwrap().as_deref(), Some("1"));
s.delete("a").unwrap();
s.delete("a").unwrap();
assert_eq!(s.get("a").unwrap(), None);
}
}
+446
View File
@@ -0,0 +1,446 @@
//! The SQLite database.
use std::path::Path;
use rusqlite::{Connection, OptionalExtension, params};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tsclientlib::Identity;
use crate::{Error, Result};
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`.
const MIGRATIONS: &[&str] = &[r#"
CREATE TABLE identities (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
uid TEXT NOT NULL UNIQUE,
data TEXT NOT NULL,
created INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE TABLE bookmarks (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
server_uid TEXT NOT NULL,
target TEXT NOT NULL,
ts INTEGER NOT NULL,
author_uid TEXT,
author_name TEXT NOT NULL,
via_relay INTEGER NOT NULL DEFAULT 0,
text TEXT NOT NULL
);
CREATE INDEX messages_by_target ON messages (server_uid, target, id);
"#];
/// A stored identity, without its private key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityEntry {
pub id: i64,
pub name: String,
pub uid: String,
pub level: u8,
}
/// How to reach a server's ServerQuery for invisible presence and relay chat.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryConfig {
pub transport: QueryTransport,
pub host: String,
pub port: u16,
pub user: String,
/// Virtual server port to `use` (defaults to the voice port).
pub server_port: Option<u16>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum QueryTransport {
/// Raw TCP (TeamSpeak 3 only, port 10011).
Raw,
/// SSH (port 10022).
#[default]
Ssh,
/// HTTP WebQuery with an API key (TeamSpeak 6, port 10080/10443). No events.
Http,
}
/// A saved server.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Bookmark {
/// Assigned by the store.
#[serde(skip)]
pub id: i64,
pub name: String,
/// host, host:port, or a server nickname.
pub address: String,
pub nickname: String,
/// Identity to connect with (`IdentityEntry::id`).
pub identity: Option<i64>,
pub default_channel: Option<String>,
/// `wss://` URL of a companion gateway, for invisible presence and relay chat.
pub gateway_url: Option<String>,
/// Own ServerQuery credentials (the password is kept in [`crate::Secrets`]).
pub query: Option<QueryConfig>,
/// Signed client version to present (`tsctl versions` spec), `None` for the default.
pub client_version: Option<String>,
}
impl Bookmark {
/// Secret key of the server password.
pub fn server_password_key(&self) -> String {
format!("bookmark/{}/server-password", self.id)
}
/// Secret key of the query password or API key.
pub fn query_password_key(&self) -> String {
format!("bookmark/{}/query-password", self.id)
}
}
/// Where a chat message was posted.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ChatTarget {
Server,
Channel(u64),
/// Private chat with the client of this unique id.
Private(String),
}
impl ChatTarget {
fn key(&self) -> String {
match self {
ChatTarget::Server => "server".into(),
ChatTarget::Channel(cid) => format!("channel/{cid}"),
ChatTarget::Private(uid) => format!("private/{uid}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredMessage {
/// Assigned by the store; used for paging.
pub id: i64,
pub server_uid: String,
pub target: ChatTarget,
/// Unix timestamp in seconds.
pub ts: i64,
pub author_uid: Option<String>,
pub author_name: String,
/// Received through a gateway/query relay instead of our own connection.
pub via_relay: bool,
pub text: String,
}
pub struct Store {
db: Connection,
}
impl Store {
/// Open or create the database at `path`.
pub fn open(path: &Path) -> Result<Self> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let db = Connection::open(path)?;
// Identities contain private keys: keep the file private.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
}
db.pragma_update(None, "journal_mode", "WAL")?;
Self::init(db)
}
pub fn open_in_memory() -> Result<Self> {
Self::init(Connection::open_in_memory()?)
}
fn init(db: Connection) -> Result<Self> {
db.pragma_update(None, "foreign_keys", true)?;
let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?;
for (i, migration) in MIGRATIONS.iter().enumerate().skip(version as usize) {
db.execute_batch(migration)?;
db.pragma_update(None, "user_version", i as i64 + 1)?;
}
Ok(Self { db })
}
// Identities
pub fn add_identity(&self, name: &str, identity: &Identity) -> Result<i64> {
let uid = identity.key().to_pub().get_uid();
self.db.execute(
"INSERT INTO identities (name, uid, data) VALUES (?1, ?2, ?3)",
params![name, uid, serde_json::to_string(identity)?],
)?;
Ok(self.db.last_insert_rowid())
}
pub fn identities(&self) -> Result<Vec<IdentityEntry>> {
let mut stmt = self.db.prepare("SELECT id, name, uid, data FROM identities ORDER BY id")?;
let rows = stmt.query_map([], |r| {
Ok((r.get::<_, i64>(0)?, r.get(1)?, r.get(2)?, r.get::<_, String>(3)?))
})?;
rows.map(|row| {
let (id, name, uid, data) = row?;
let identity: Identity = serde_json::from_str(&data)?;
Ok(IdentityEntry { id, name, uid, level: identity.level() })
})
.collect()
}
pub fn identity(&self, id: i64) -> Result<Identity> {
let data: Option<String> = self
.db
.query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0))
.optional()?;
let data = data.ok_or(Error::NotFound("identity", id))?;
Ok(serde_json::from_str(&data)?)
}
/// Store an identity again, e.g. after its security level was improved.
pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> {
let n = self.db.execute(
"UPDATE identities SET data = ?2 WHERE id = ?1",
params![id, serde_json::to_string(identity)?],
)?;
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
}
pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> {
let n =
self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?;
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
}
pub fn delete_identity(&self, id: i64) -> Result<()> {
self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?;
Ok(())
}
// Bookmarks
pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result<i64> {
self.db.execute(
"INSERT INTO bookmarks (data, position)
VALUES (?1, (SELECT COALESCE(MAX(position), -1) + 1 FROM bookmarks))",
[serde_json::to_string(bookmark)?],
)?;
Ok(self.db.last_insert_rowid())
}
pub fn update_bookmark(&self, bookmark: &Bookmark) -> Result<()> {
let n = self.db.execute(
"UPDATE bookmarks SET data = ?2 WHERE id = ?1",
params![bookmark.id, serde_json::to_string(bookmark)?],
)?;
if n == 0 { Err(Error::NotFound("bookmark", bookmark.id)) } else { Ok(()) }
}
pub fn bookmarks(&self) -> Result<Vec<Bookmark>> {
let mut stmt = self.db.prepare("SELECT id, data FROM bookmarks ORDER BY position, id")?;
let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?;
rows.map(|row| {
let (id, data) = row?;
let mut bookmark: Bookmark = serde_json::from_str(&data)?;
bookmark.id = id;
Ok(bookmark)
})
.collect()
}
pub fn delete_bookmark(&self, id: i64) -> Result<()> {
self.db.execute("DELETE FROM bookmarks WHERE id = ?1", [id])?;
Ok(())
}
// Settings
pub fn setting<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
let value: Option<String> = self
.db
.query_row("SELECT value FROM settings WHERE key = ?1", [key], |r| r.get(0))
.optional()?;
value.map(|v| serde_json::from_str(&v).map_err(Error::from)).transpose()
}
pub fn set_setting<T: Serialize>(&self, key: &str, value: &T) -> Result<()> {
self.db.execute(
"INSERT INTO settings (key, value) VALUES (?1, ?2)
ON CONFLICT (key) DO UPDATE SET value = excluded.value",
params![key, serde_json::to_string(value)?],
)?;
Ok(())
}
// Chat cache
pub fn add_message(&self, msg: &StoredMessage) -> Result<i64> {
self.db.execute(
"INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
msg.server_uid,
msg.target.key(),
msg.ts,
msg.author_uid,
msg.author_name,
msg.via_relay,
msg.text
],
)?;
Ok(self.db.last_insert_rowid())
}
/// Up to `limit` messages older than `before` (message id), oldest first.
pub fn history(
&self,
server_uid: &str,
target: &ChatTarget,
before: Option<i64>,
limit: usize,
) -> Result<Vec<StoredMessage>> {
let mut stmt = self.db.prepare(
"SELECT id, ts, author_uid, author_name, via_relay, text FROM messages
WHERE server_uid = ?1 AND target = ?2 AND id < ?3
ORDER BY id DESC LIMIT ?4",
)?;
let rows = stmt.query_map(
params![server_uid, target.key(), before.unwrap_or(i64::MAX), limit as i64],
|r| {
Ok(StoredMessage {
id: r.get(0)?,
server_uid: server_uid.to_string(),
target: target.clone(),
ts: r.get(1)?,
author_uid: r.get(2)?,
author_name: r.get(3)?,
via_relay: r.get(4)?,
text: r.get(5)?,
})
},
)?;
let mut messages = rows.collect::<rusqlite::Result<Vec<_>>>()?;
messages.reverse();
Ok(messages)
}
/// Delete cached messages older than `ts` (Unix seconds).
pub fn prune_messages(&self, ts: i64) -> Result<usize> {
Ok(self.db.execute("DELETE FROM messages WHERE ts < ?1", [ts])?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identities() {
let store = Store::open_in_memory().unwrap();
let identity = Identity::create();
let id = store.add_identity("main", &identity).unwrap();
let list = store.identities().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].name, "main");
assert_eq!(list[0].uid, identity.key().to_pub().get_uid());
assert!(list[0].level >= 8);
let loaded = store.identity(id).unwrap();
assert_eq!(loaded.counter(), identity.counter());
// The same key twice is rejected (uid is unique).
assert!(store.add_identity("dup", &identity).is_err());
store.rename_identity(id, "renamed").unwrap();
assert_eq!(store.identities().unwrap()[0].name, "renamed");
store.delete_identity(id).unwrap();
assert!(matches!(store.identity(id), Err(Error::NotFound(..))));
}
#[test]
fn bookmarks_keep_order_and_fields() {
let store = Store::open_in_memory().unwrap();
let mut b = Bookmark {
name: "Home".into(),
address: "ts.example.org".into(),
nickname: "me".into(),
gateway_url: Some("wss://gw.example.org/v1".into()),
query: Some(QueryConfig {
transport: QueryTransport::Ssh,
host: "ts.example.org".into(),
port: 10022,
user: "me".into(),
server_port: None,
}),
..Default::default()
};
b.id = store.add_bookmark(&b).unwrap();
let second = Bookmark { name: "Other".into(), ..Default::default() };
store.add_bookmark(&second).unwrap();
let list = store.bookmarks().unwrap();
assert_eq!(list.len(), 2);
assert_eq!(list[0], b);
assert_eq!(list[1].name, "Other");
b.nickname = "renamed".into();
store.update_bookmark(&b).unwrap();
assert_eq!(store.bookmarks().unwrap()[0].nickname, "renamed");
assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id));
}
#[test]
fn settings() {
let store = Store::open_in_memory().unwrap();
assert_eq!(store.setting::<u32>("volume").unwrap(), None);
store.set_setting("volume", &80u32).unwrap();
store.set_setting("volume", &90u32).unwrap();
assert_eq!(store.setting::<u32>("volume").unwrap(), Some(90));
}
#[test]
fn chat_history_pages() {
let store = Store::open_in_memory().unwrap();
let target = ChatTarget::Channel(5);
for i in 0..10 {
store
.add_message(&StoredMessage {
id: 0,
server_uid: "srv".into(),
target: target.clone(),
ts: 1000 + i,
author_uid: None,
author_name: "a".into(),
via_relay: i % 2 == 0,
text: format!("m{i}"),
})
.unwrap();
}
let last = store.history("srv", &target, None, 3).unwrap();
let texts: Vec<_> = last.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["m7", "m8", "m9"]);
let older = store.history("srv", &target, Some(last[0].id), 3).unwrap();
assert_eq!(older.iter().map(|m| m.text.as_str()).collect::<Vec<_>>(), ["m4", "m5", "m6"]);
assert!(store.history("srv", &ChatTarget::Server, None, 3).unwrap().is_empty());
assert_eq!(store.prune_messages(1005).unwrap(), 5);
}
#[test]
fn reopen_keeps_data_and_schema() {
let dir = std::env::temp_dir().join(format!("tsc-store-{}", std::process::id()));
let path = dir.join("client.db");
{
let store = Store::open(&path).unwrap();
store.set_setting("k", &"v").unwrap();
}
let store = Store::open(&path).unwrap();
assert_eq!(store.setting::<String>("k").unwrap().as_deref(), Some("v"));
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
}
+17
View File
@@ -6,6 +6,7 @@
# 1. connect + channel tree (channelsubscribeall)
# 2. server chat between two clients
# 3. channel chat between two clients
# 4. voice: a 1 kHz tone sent by one client is recorded by another
#
# Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both)
# Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl)
@@ -77,6 +78,21 @@ chat_roundtrip() {
grep -F "[$kind] sender" "$out"
}
# One client records while another sends a tone; Goertzel checks the result.
voice_roundtrip() {
local addr=$1 out="$STATE_DIR/voice.log"
"$TSCTL" connect "$addr" --nick recorder voice record "$STATE_DIR/voice.wav" \
--seconds 6 --expect-tone 1000 >"$out" 2>&1 &
local recorder=$!
sleep 2
"$TSCTL" connect "$addr" --nick talker voice send --tone 1000 --seconds 2 >/dev/null
if ! wait "$recorder"; then
cat "$out"
fail "voice tone not received"
fi
grep "tone ratio" "$out"
}
for svc in "${SERVERS[@]}"; do
port=${PORTS[$svc]:?unknown server $svc}
addr="127.0.0.1:$port"
@@ -91,6 +107,7 @@ for svc in "${SERVERS[@]}"; do
# Guests may not use the server chat by default, so the sender is the admin.
chat_roundtrip "$addr" server "$admin"
chat_roundtrip "$addr" channel ""
voice_roundtrip "$addr"
done
log "all smoke tests passed"
+1
View File
@@ -21,6 +21,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tsclientlib = { path = "../../crates/proto/tsclientlib" }
tsproto-packets = { path = "../../crates/proto/tsproto-packets" }
tsc-model = { path = "../../crates/tsc-model" }
tsc-audio = { path = "../../crates/tsc-audio", default-features = false }
[lints]
workspace = true
+34
View File
@@ -4,6 +4,7 @@ mod identity;
mod session;
mod tree;
mod versions;
mod voice;
use std::path::PathBuf;
use std::time::Duration;
@@ -116,10 +117,43 @@ pub enum Action {
/// Send a raw, already escaped command (e.g. `serveredit virtualserver_name=Test\\sServer`)
/// and wait for the result. Combine with `--log-commands` to see the answer.
Raw { command: String },
/// Send or record voice in the current channel.
Voice {
#[command(subcommand)]
command: VoiceCommand,
},
/// Interactive session. Type `/help` for commands.
Repl,
}
#[derive(Subcommand, Debug, Clone)]
pub enum VoiceCommand {
/// Talk: send a WAV file or a test tone, in real time.
Send {
/// WAV file to send (any sample rate; resampled to 48 kHz).
file: Option<PathBuf>,
/// Send a sine tone of this frequency instead of a file.
#[arg(long, conflicts_with = "file")]
tone: Option<f32>,
/// Tone length in seconds.
#[arg(long, default_value_t = 3.0)]
seconds: f32,
/// Use the stereo Opus Music codec instead of mono Opus Voice.
#[arg(long)]
music: bool,
},
/// Listen: mix everything said in the channel into a stereo 48 kHz WAV file.
Record {
out: PathBuf,
/// Recording length in seconds.
#[arg(long, default_value_t = 5.0)]
seconds: f32,
/// Fail unless the recording contains this tone frequency (for tests).
#[arg(long)]
expect_tone: Option<f32>,
},
}
#[derive(Subcommand, Debug, Clone)]
pub enum ChatTarget {
/// Send to the server chat (everyone on the server).
+4 -3
View File
@@ -57,6 +57,7 @@ pub async fn run(args: ConnectArgs) -> Result<()> {
let cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, command);
send_and_wait(&mut con, cmd, "command").await.map(|()| println!("ok"))
}
Action::Voice { command } => crate::voice::run(&mut con, command).await,
Action::Repl => repl(&mut con).await,
};
@@ -65,14 +66,14 @@ pub async fn run(args: ConnectArgs) -> Result<()> {
}
/// What to do after handling one stream item.
enum Flow {
pub(crate) enum Flow {
Continue,
Stop,
}
/// How [`pump`] ended.
#[derive(Debug, PartialEq, Eq)]
enum PumpEnd {
pub(crate) enum PumpEnd {
Stopped,
Deadline,
Interrupted,
@@ -80,7 +81,7 @@ enum PumpEnd {
/// Drive the connection, handing every item to `handler` until it returns
/// [`Flow::Stop`], the deadline passes, or Ctrl-C is pressed.
async fn pump(
pub(crate) async fn pump(
con: &mut Connection,
deadline: Option<Instant>,
mut handler: impl FnMut(&mut Connection, StreamItem) -> Result<Flow>,
+112
View File
@@ -0,0 +1,112 @@
//! `tsctl connect ... voice send|record`.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use tokio::time::Instant;
use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder, resample, wav};
use tsclientlib::{ClientId, Connection, StreamItem};
use tsproto_packets::packets::AudioData;
use crate::VoiceCommand;
use crate::session::{Flow, PumpEnd, pump};
const FRAME: Duration = Duration::from_millis(20);
pub async fn run(con: &mut Connection, command: &VoiceCommand) -> Result<()> {
match command {
VoiceCommand::Send { file, tone, seconds, music } => {
let codec = if *music { VoiceCodec::Music } else { VoiceCodec::Voice };
let samples = match (file, tone) {
(Some(path), _) => load(path, codec.channels())?,
(None, Some(freq)) => {
pcm::from_mono(&pcm::sine(*freq, *seconds, 0.5), codec.channels())
}
(None, None) => bail!("pass a WAV file or --tone <hz>"),
};
send(con, codec, &samples).await
}
VoiceCommand::Record { out, seconds, expect_tone } => {
let samples = record(con, Duration::from_secs_f32(*seconds)).await?;
let clip = wav::Clip { samples, channels: 2, rate: SAMPLE_RATE };
wav::write(out, &clip)?;
let mono = pcm::to_mono(&clip.samples, 2);
println!(
"recorded {:.1} s to {} (energy {:.5})",
mono.len() as f32 / SAMPLE_RATE as f32,
out.display(),
pcm::energy(&mono)
);
if let Some(freq) = expect_tone {
let ratio = pcm::voiced_tone_ratio(&mono, *freq, SAMPLE_RATE);
println!("{freq} Hz tone ratio: {ratio:.3}");
if ratio < 0.5 {
bail!("expected a {freq} Hz tone, ratio {ratio:.3} < 0.5");
}
}
Ok(())
}
}
}
/// Read a WAV file and convert it to 48 kHz with the codec's channel count.
fn load(path: &std::path::Path, channels: usize) -> Result<Vec<f32>> {
let clip = wav::read(path).with_context(|| format!("failed to read {}", path.display()))?;
let samples = resample::resample_all(&clip.samples, clip.channels, clip.rate, SAMPLE_RATE)?;
let mono = pcm::to_mono(&samples, clip.channels);
Ok(pcm::from_mono(&mono, channels))
}
/// Send in real time: one frame every 20 ms, driving the connection in between.
async fn send(con: &mut Connection, codec: VoiceCodec, samples: &[f32]) -> Result<()> {
let mut encoder = VoiceEncoder::new(codec)?;
let mut frames = Vec::new();
let mut framer = Framer::new(codec.frame_len());
framer.push(samples, |f| frames.push(f.to_vec()));
framer.flush(|f| frames.push(f.to_vec()));
let mut next = Instant::now();
for frame in &frames {
con.send_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())?;
// 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);
Ok(())
}
/// Collect voice for `length`, mixing all speakers into stereo.
async fn record(con: &mut Connection, length: Duration) -> Result<Vec<f32>> {
let mut mixer = Mixer::new();
let mut out = Vec::new();
let end = Instant::now() + length;
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),
};
// Late or duplicate packets are expected on UDP; the mixer drops them.
let _ = mixer.handle_packet(ClientId(from), packet);
}
Ok(Flow::Continue)
})
.await?;
let mut frame = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut frame);
out.extend_from_slice(&frame);
if end == PumpEnd::Interrupted {
break;
}
next += FRAME;
}
Ok(out)
}