vendor: import ReSpeak/tsclientlib@ee3bc6f
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:
119 files changed
+24322
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user