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 301a543c5e
commit 90e05723da
20 files changed
+2379 -35

No files matched your search

+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)
}