Merge branch 'claude/gifted-lovelace-1crlx2' into wip/android

This commit is contained in:
Claude committed 2026-09-26 10:05:43 +00:00
commit d0e43684ca
56 files changed
+8873 -237

No files matched your search

+7
View File
@@ -19,10 +19,17 @@ hound = "3.5.1"
opus2 = "0.4"
rtrb = { version = "0.4.0", optional = true }
rubato = "5.0.0"
serde = { version = "1.0.228", features = ["derive"] }
sonora = "0.2"
sonora-agc2 = "0.2"
sonora-simd = "0.2"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
+456 -20
View File
@@ -2,42 +2,140 @@
//!
//! The device callbacks only move samples through lock-free ring buffers; all
//! processing happens on the caller's side.
//!
//! Devices are identified by cpal's stable device id (`host:device`, e.g.
//! `alsa:hw:1,0`), which survives restarts and replugging. A stream notices
//! when its device goes away through cpal's error callback
//! ([`Capture::is_lost`]); [`Managed`] reopens it, on the default device when
//! the selected one is gone, and moves back when it returns.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{ErrorKind, SampleFormat};
use rtrb::{Consumer, Producer, RingBuffer};
use tracing::warn;
use tracing::{debug, warn};
use crate::{Error, Result};
/// A device as shown in settings.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviceInfo {
/// Stable id to store in settings (`AudioSettings::input_device`).
pub id: String,
/// Human-readable name.
pub name: String,
pub input: bool,
pub output: bool,
/// The system's default input device.
pub default_input: bool,
/// The system's default output device.
pub default_output: bool,
}
fn device_error(e: impl std::fmt::Display) -> Error {
Error::Device(e.to_string())
}
fn device_name(device: &cpal::Device) -> String {
device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| device.to_string())
}
fn device_id(device: &cpal::Device) -> Option<String> {
device.id().ok().map(|id| id.to_string())
}
/// All devices of the default host.
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
let host = cpal::default_host();
let default_input = host.default_input_device().and_then(|d| device_id(&d));
let default_output = host.default_output_device().and_then(|d| device_id(&d));
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(),
.filter_map(|d| {
let id = device_id(&d)?;
Some(DeviceInfo {
name: device_name(&d),
input: d.supports_input(),
output: d.supports_output(),
default_input: default_input.as_deref() == Some(id.as_str()),
default_output: default_output.as_deref() == Some(id.as_str()),
id,
})
})
.collect())
}
/// Devices that can record.
pub fn input_devices() -> Result<Vec<DeviceInfo>> {
Ok(list_devices()?.into_iter().filter(|d| d.input).collect())
}
/// Devices that can play.
pub fn output_devices() -> Result<Vec<DeviceInfo>> {
Ok(list_devices()?.into_iter().filter(|d| d.output).collect())
}
/// The device with this id, or the default one for `None`.
fn find_device(id: Option<&str>, input: bool) -> Result<cpal::Device> {
let host = cpal::default_host();
let kind = if input { "input" } else { "output" };
let Some(id) = id else {
let device = if input { host.default_input_device() } else { host.default_output_device() };
return device.ok_or_else(|| Error::Device(format!("no {kind} device")));
};
let parsed = id.parse().map_err(device_error)?;
host.device_by_id(&parsed).ok_or_else(|| Error::Device(format!("{kind} device {id} not found")))
}
/// Whether a device with this id is present.
pub fn device_exists(id: &str) -> bool {
id.parse().ok().and_then(|id| cpal::default_host().device_by_id(&id)).is_some()
}
/// Errors after which a stream will not recover by itself.
fn is_fatal(kind: ErrorKind) -> bool {
!matches!(kind, ErrorKind::DeviceChanged | ErrorKind::Xrun | ErrorKind::RealtimeDenied)
}
/// The error callback: log, and flag the stream lost on fatal errors.
fn error_callback(what: &'static str, lost: Arc<AtomicBool>) -> impl FnMut(cpal::Error) + Send {
move |error| {
if is_fatal(error.kind()) {
warn!(%error, "{what} stream lost");
lost.store(true, Ordering::Relaxed);
} else {
debug!(%error, "{what} stream");
}
}
}
/// The default config, but with f32 samples if the device offers them at the
/// same rate (streams here are f32 only).
fn f32_config(
default: cpal::SupportedStreamConfig,
supported: impl Iterator<Item = cpal::SupportedStreamConfigRange>,
) -> cpal::StreamConfig {
if default.sample_format() == SampleFormat::F32 {
return default.config();
}
let rate = default.sample_rate();
supported
.filter(|r| r.sample_format() == SampleFormat::F32)
.find_map(|r| r.try_with_sample_rate(rate))
.map(|c| c.config())
.unwrap_or_else(|| default.config())
}
/// Running capture stream. Samples are interleaved at the device's rate.
pub struct Capture {
_stream: cpal::Stream,
consumer: Consumer<f32>,
lost: Arc<AtomicBool>,
id: Option<String>,
name: String,
pub channels: usize,
pub rate: u32,
}
@@ -45,14 +143,21 @@ pub struct Capture {
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();
Self::open(None, buffer_ms)
}
/// Open the input device with this id (see [`DeviceInfo::id`]), or the
/// default one for `None`.
pub fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
let device = find_device(id, true)?;
let default = device.default_input_config().map_err(device_error)?;
let supported = device.supported_input_configs().map_err(device_error)?;
let config = f32_config(default, supported);
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 lost = Arc::new(AtomicBool::new(false));
let stream = device
.build_input_stream(
config,
@@ -62,12 +167,20 @@ impl Capture {
chunk.fill_from_iter(data[..n].iter().copied());
}
},
|error| warn!(%error, "capture stream error"),
error_callback("capture", lost.clone()),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, consumer, channels, rate })
Ok(Self {
_stream: stream,
consumer,
lost,
id: device_id(&device),
name: device_name(&device),
channels,
rate,
})
}
/// Move everything captured so far into `out`.
@@ -77,26 +190,45 @@ impl Capture {
out.extend(chunk);
}
}
/// The device went away or the stream broke; reopen it.
pub fn is_lost(&self) -> bool {
self.lost.load(Ordering::Relaxed)
}
pub fn name(&self) -> &str {
&self.name
}
}
/// Running playback stream. Write interleaved samples at the device's rate.
pub struct Playback {
_stream: cpal::Stream,
producer: Producer<f32>,
lost: Arc<AtomicBool>,
id: Option<String>,
name: String,
capacity: usize,
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();
Self::open(None, buffer_ms)
}
/// Open the output device with this id, or the default one for `None`.
pub fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
let device = find_device(id, false)?;
let default = device.default_output_config().map_err(device_error)?;
let supported = device.supported_output_configs().map_err(device_error)?;
let config = f32_config(default, supported);
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 capacity = (rate * buffer_ms / 1000) as usize * channels;
let (producer, mut consumer) = RingBuffer::<f32>::new(capacity);
let lost = Arc::new(AtomicBool::new(false));
let stream = device
.build_output_stream(
config,
@@ -110,12 +242,21 @@ impl Playback {
// Underrun: play silence.
data[n..].fill(0.0);
},
|error| warn!(%error, "playback stream error"),
error_callback("playback", lost.clone()),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, producer, channels, rate })
Ok(Self {
_stream: stream,
producer,
lost,
id: device_id(&device),
name: device_name(&device),
capacity,
channels,
rate,
})
}
/// Queue samples; returns how many fit into the buffer.
@@ -131,4 +272,299 @@ impl Playback {
pub fn free(&self) -> usize {
self.producer.slots()
}
/// Samples (all channels) queued and not yet handed to the device.
pub fn queued(&self) -> usize {
self.capacity - self.producer.slots()
}
/// Queued audio in milliseconds.
pub fn queued_ms(&self) -> u32 {
(self.queued() / self.channels.max(1)) as u32 * 1000 / self.rate.max(1)
}
/// The device went away or the stream broke; reopen it.
pub fn is_lost(&self) -> bool {
self.lost.load(Ordering::Relaxed)
}
pub fn name(&self) -> &str {
&self.name
}
}
/// What [`Managed`] needs from a stream; implemented by [`Capture`] and
/// [`Playback`].
pub trait DeviceStream: Sized {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self>;
fn is_lost(&self) -> bool;
/// Id of the device actually opened.
fn device_id(&self) -> Option<&str>;
fn name(&self) -> &str;
fn device_exists(id: &str) -> bool;
}
impl DeviceStream for Capture {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
Capture::open(id, buffer_ms)
}
fn is_lost(&self) -> bool {
Capture::is_lost(self)
}
fn device_id(&self) -> Option<&str> {
self.id.as_deref()
}
fn name(&self) -> &str {
&self.name
}
fn device_exists(id: &str) -> bool {
device_exists(id)
}
}
impl DeviceStream for Playback {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
Playback::open(id, buffer_ms)
}
fn is_lost(&self) -> bool {
Playback::is_lost(self)
}
fn device_id(&self) -> Option<&str> {
self.id.as_deref()
}
fn name(&self) -> &str {
&self.name
}
fn device_exists(id: &str) -> bool {
device_exists(id)
}
}
/// What happened to a [`Managed`] stream, for the user.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviceEvent {
/// Opened a device. `fallback` is set when it is the default device
/// because the selected one is missing.
Opened { name: String, fallback: bool },
/// The open device went away.
Lost { name: String },
/// No device could be opened; retrying in the background. Reported once
/// until a device opens again.
Unavailable(String),
}
/// Retry opening a device this often while none is open.
pub const RETRY_INTERVAL: Duration = Duration::from_secs(2);
/// While on the default device instead of the selected one, look for the
/// selected one this often.
pub const RETURN_INTERVAL: Duration = Duration::from_secs(5);
/// Keeps a stream open across device loss and selection changes. Call
/// [`poll`](Self::poll) regularly from the audio loop.
pub struct Managed<S> {
stream: Option<S>,
wanted: Option<String>,
buffer_ms: u32,
retry_at: Instant,
return_at: Instant,
failing: bool,
}
impl<S: DeviceStream> Managed<S> {
/// Nothing is opened until the first [`poll`](Self::poll).
pub fn new(wanted: Option<String>, buffer_ms: u32) -> Self {
let now = Instant::now();
Self { stream: None, wanted, buffer_ms, retry_at: now, return_at: now, failing: false }
}
/// Select another device (`None`: the default); reopens on the next poll.
pub fn select(&mut self, wanted: Option<String>) {
if wanted != self.wanted {
self.wanted = wanted;
self.stream = None;
self.retry_at = Instant::now();
}
}
pub fn wanted(&self) -> Option<&str> {
self.wanted.as_deref()
}
pub fn stream(&mut self) -> Option<&mut S> {
self.stream.as_mut()
}
/// Whether the stream was replaced since the caller last saw it matters
/// for resamplers; callers compare [`DeviceEvent::Opened`].
pub fn poll(&mut self) -> Option<DeviceEvent> {
self.poll_at(Instant::now())
}
fn poll_at(&mut self, now: Instant) -> Option<DeviceEvent> {
if let Some(stream) = &self.stream {
if stream.is_lost() {
let name = stream.name().to_string();
self.stream = None;
self.retry_at = now;
return Some(DeviceEvent::Lost { name });
}
// On the default device although another one is selected: move
// back once it is present again.
let on_fallback = self.wanted.is_some() && stream.device_id() != self.wanted.as_deref();
if !on_fallback || now < self.return_at {
return None;
}
self.return_at = now + RETURN_INTERVAL;
match self.wanted.as_deref() {
Some(id) if S::device_exists(id) => self.stream = None,
_ => return None,
}
}
if now < self.retry_at {
return None;
}
let wanted = self.wanted.clone();
let opened = match S::open(wanted.as_deref(), self.buffer_ms) {
Ok(s) => Ok((s, false)),
Err(e) if wanted.is_some() => {
S::open(None, self.buffer_ms).map(|s| (s, true)).map_err(|default_error| {
Error::Device(format!("{e}; default device: {default_error}"))
})
}
Err(e) => Err(e),
};
match opened {
Ok((stream, fallback)) => {
let name = stream.name().to_string();
self.stream = Some(stream);
self.failing = false;
self.return_at = now + RETURN_INTERVAL;
Some(DeviceEvent::Opened { name, fallback })
}
Err(e) => {
self.retry_at = now + RETRY_INTERVAL;
let first = !self.failing;
self.failing = true;
first.then(|| DeviceEvent::Unavailable(e.to_string()))
}
}
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::collections::HashSet;
use super::*;
thread_local! {
/// Plugged-in fake devices; "default" is the system default.
static PLUGGED: RefCell<HashSet<String>> = RefCell::new(HashSet::new());
}
fn plug(id: &str, on: bool) {
PLUGGED.with(|p| {
let mut p = p.borrow_mut();
if on { p.insert(id.into()) } else { p.remove(id) }
});
}
fn plugged(id: &str) -> bool {
PLUGGED.with(|p| p.borrow().contains(id))
}
struct Fake {
id: String,
}
impl DeviceStream for Fake {
fn open(id: Option<&str>, _: u32) -> Result<Self> {
let id = id.unwrap_or("default");
if plugged(id) {
Ok(Fake { id: id.into() })
} else {
Err(Error::Device(format!("{id} not found")))
}
}
fn is_lost(&self) -> bool {
!plugged(&self.id)
}
fn device_id(&self) -> Option<&str> {
Some(&self.id)
}
fn name(&self) -> &str {
&self.id
}
fn device_exists(id: &str) -> bool {
plugged(id)
}
}
fn opened(name: &str, fallback: bool) -> Option<DeviceEvent> {
Some(DeviceEvent::Opened { name: name.into(), fallback })
}
#[test]
fn fatal_errors() {
assert!(is_fatal(ErrorKind::DeviceNotAvailable));
assert!(is_fatal(ErrorKind::StreamInvalidated));
assert!(!is_fatal(ErrorKind::Xrun));
assert!(!is_fatal(ErrorKind::DeviceChanged));
}
/// Headset selected, unplugged mid-call, plugged back in.
#[test]
fn reopens_and_falls_back() {
plug("default", true);
plug("headset", true);
let mut m = Managed::<Fake>::new(Some("headset".into()), 100);
let t0 = Instant::now();
assert_eq!(m.poll_at(t0), opened("headset", false));
assert_eq!(m.poll_at(t0), None);
plug("headset", false);
assert_eq!(m.poll_at(t0), Some(DeviceEvent::Lost { name: "headset".into() }));
assert_eq!(m.poll_at(t0), opened("default", true));
assert_eq!(m.stream().unwrap().id, "default");
// Back only after the return interval.
plug("headset", true);
assert_eq!(m.poll_at(t0 + Duration::from_secs(1)), None);
assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("headset", false));
// Selecting the default device switches right away.
m.select(None);
assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("default", false));
}
/// Nothing plugged in: one report, retries every interval, recovers.
#[test]
fn retries_when_unavailable() {
plug("default", false);
let mut m = Managed::<Fake>::new(None, 100);
let t0 = Instant::now();
assert!(matches!(m.poll_at(t0), Some(DeviceEvent::Unavailable(_))));
assert!(m.stream().is_none());
plug("default", true);
// Not before the retry interval, and no repeated report.
assert_eq!(m.poll_at(t0 + Duration::from_millis(500)), None);
assert_eq!(m.poll_at(t0 + RETRY_INTERVAL), opened("default", false));
plug("default", false);
assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Lost { .. })));
assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Unavailable(_))));
assert_eq!(m.poll_at(t0 + RETRY_INTERVAL * 2), None);
}
/// Opening real devices needs hardware; just make sure enumeration does
/// not fail or panic without any.
#[test]
fn enumeration_without_hardware() {
if let Ok(devices) = list_devices() {
for d in devices {
assert!(!d.id.is_empty());
}
}
assert!(!device_exists("no-such-host:nothing"));
}
}
+15 -6
View File
@@ -5,14 +5,22 @@
//! - [`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
//! - [`process`]: echo cancellation, noise suppression and gain control
//! - [`vad`]: voice activity detection
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
//! vendored `tsclientlib::audio::AudioHandler`)
//! - [`settings`]: all user audio settings in one serde struct
//! - `device` (feature `device`): capture and playback through cpal, device
//! lists and loss detection
pub mod encode;
pub mod framer;
pub mod mixer;
pub mod pcm;
pub mod process;
pub mod resample;
pub mod settings;
pub mod vad;
pub mod wav;
#[cfg(feature = "device")]
@@ -20,10 +28,11 @@ pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use framer::Framer;
pub use mixer::Mixer;
pub use process::{ProcessingSettings, Processor};
pub use settings::AudioSettings;
pub use tsclientlib::audio::AudioHandler;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
pub type Mixer = AudioHandler<tsclientlib::ClientId>;
pub use vad::{Vad, VadSettings};
#[derive(Debug, thiserror::Error)]
pub enum Error {
+219
View File
@@ -0,0 +1,219 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
//!
//! - a new talker starts after a pre-buffer derived from the queue lengths of
//! the other talkers (none for the first one);
//! - a queue that underruns plays Opus packet-loss concealment for the
//! missing packet (one inserted frame) and drops the talker after three
//! frames in a row without data, so a slow sender never lets latency grow;
//! - when the smallest queue length over the last 255 decoded packets exceeds
//! its spread (a fast sender, or a jitter spike that passed), every 100th
//! sample of the decoded frame is dropped (1 % faster playback) until the
//! surplus is gone; above 0.5 s the queue is truncated outright.
//!
//! So sender clock drift is absorbed by occasional 1 % speed-ups (fast
//! sender) or concealment frames (slow sender) and latency stays bounded; the
//! `drift` integration test simulates an hour at ±200 ppm to check that.
use std::collections::{HashMap, HashSet};
use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
/// Loudest per-client volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Output is interleaved stereo at 48 kHz.
#[derive(Default)]
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
}
impl Mixer {
pub fn new() -> Self {
Self::default()
}
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
/// just started talking. Late, duplicate and malformed packets are
/// errors; on UDP they are expected and can be ignored.
pub fn handle_packet(
&mut self,
id: ClientId,
packet: InAudioBuf,
) -> Result<Option<ClientId>, QueueError> {
self.handler.handle_packet(id, packet)
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume. Returns the clients
/// that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
for (id, queue) in self.handler.get_mut_queues() {
queue.volume = if self.muted.contains(id) {
0.0
} else {
self.volumes.get(id).copied().unwrap_or(1.0)
};
}
// Muted talkers are still decoded so their queues stay in sync.
self.handler.fill_buffer(buf)
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the client stops and starts talking again.
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
if volume == 1.0 {
self.volumes.remove(&id);
} else {
self.volumes.insert(id, volume);
}
}
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
self.set_volume(id, 10f32.powf(db / 20.0));
}
pub fn volume(&self, id: ClientId) -> f32 {
self.volumes.get(&id).copied().unwrap_or(1.0)
}
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
if muted {
self.muted.insert(id);
} else {
self.muted.remove(&id);
}
}
pub fn is_muted(&self, id: ClientId) -> bool {
self.muted.contains(&id)
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
self.volumes.remove(&id);
self.muted.remove(&id);
self.handler.get_mut_queues().remove(&id);
}
/// Clients with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
self.handler.get_queues().keys().copied()
}
/// Drop all queues; volumes and mutes are kept.
pub fn reset(&mut self) {
self.handler.reset();
}
/// The underlying jitter buffer.
pub fn handler(&self) -> &AudioHandler<ClientId> {
&self.handler
}
}
impl std::fmt::Debug for Mixer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Mixer")
.field("talkers", &self.handler.get_queues().len())
.field("volumes", &self.volumes)
.field("muted", &self.muted)
.finish()
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
use super::*;
use crate::VoiceEncoder;
use crate::encode::VoiceCodec;
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
}
/// Two clients send tones at the same level; after setting volumes the
/// mix carries each at its own gain, and a muted one not at all.
#[test]
fn volume_per_client() {
let (a, b) = (ClientId(3), ClientId(4));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 2.0, 0.2);
let tone_b = pcm::sine(1300.0, 2.0, 0.2);
let mut mixer = Mixer::new();
mixer.set_volume(a, 0.25);
mixer.set_volume_db(b, 6.0);
assert!((mixer.volume(b) - 1.995).abs() < 0.01);
let mut out = Vec::new();
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
for (i, (fa, fb)) in frames.enumerate() {
let id = i as u16;
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
if i == 0 {
assert_eq!(started.unwrap(), Some(a));
}
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
assert_eq!(mixer.talkers().count(), 2);
let tail = &out[out.len() / 2..];
let power = |f| pcm::goertzel_power(tail, f, SAMPLE_RATE);
// Amplitude ratio 0.25 / 2 = 1/8, power ratio 1/64 (-18 dB).
let ratio_db = 10.0 * (power(500.0) / power(1300.0)).log10();
assert!((ratio_db + 18.0).abs() < 1.5, "ratio {ratio_db} dB");
// Mute b: only a remains.
mixer.set_muted(b, true);
let mut out = Vec::new();
for i in 0..20u16 {
let id = 100 + i;
let fa = &tone_a[..FRAME_SAMPLES];
let fb = &tone_b[..FRAME_SAMPLES];
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
let tail = &out[out.len() / 2..];
assert!(pcm::goertzel_power(tail, 1300.0, SAMPLE_RATE) < 1e-6);
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
}
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
let id = ClientId(9);
mixer.set_volume(id, 100.0);
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
mixer.set_volume(id, -1.0);
assert_eq!(mixer.volume(id), 0.0);
mixer.set_volume(id, f32::NAN);
assert_eq!(mixer.volume(id), 1.0);
mixer.set_volume(id, 0.5);
mixer.set_muted(id, true);
assert!(mixer.is_muted(id));
mixer.forget(id);
assert!(!mixer.is_muted(id));
assert_eq!(mixer.volume(id), 1.0);
}
}
+25
View File
@@ -13,6 +13,20 @@ pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec<f32> {
(0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect()
}
/// Deterministic white noise, uniform in `[-amplitude, amplitude]`, for tests
/// and calibration.
pub fn white_noise(n: usize, amplitude: f32, seed: u64) -> Vec<f32> {
// PCG-style LCG; the top 24 bits are uniform enough.
let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(0..n)
.map(|_| {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let x = (state >> 40) as f32 / (1u64 << 24) as f32;
amplitude * (2.0 * x - 1.0)
})
.collect()
}
/// Average interleaved channels into mono.
pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec<f32> {
if channels <= 1 {
@@ -93,6 +107,17 @@ mod tests {
assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0);
}
#[test]
fn noise_is_white_and_deterministic() {
let n = white_noise(48_000, 0.5, 1);
assert_eq!(n, white_noise(48_000, 0.5, 1));
assert_ne!(n, white_noise(48_000, 0.5, 2));
assert!(n.iter().all(|s| s.abs() <= 0.5));
// Uniform in ±a has energy a²/3.
assert!((energy(&n) - 0.25 / 3.0).abs() < 0.005);
assert!(tone_ratio(&n, 1000.0, SAMPLE_RATE) < 0.01);
}
#[test]
fn channel_conversion() {
assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]);
+363
View File
@@ -0,0 +1,363 @@
//! Microphone processing: echo cancellation, noise suppression and automatic
//! gain control.
//!
//! Backed by [sonora](https://crates.io/crates/sonora) (BSD-3-Clause), a pure
//! Rust port of the WebRTC audio processing module (AEC3, NS, AGC2): no C++
//! toolchain or system library needed, so it builds the same on Linux,
//! Windows and Android.
//!
//! The [`Processor`] runs on 10 ms mono frames at 48 kHz. The far end, i.e.
//! exactly what goes to the speakers (the mixer output after per-client volume
//! and output mute), is fed through [`Processor::render`]; the microphone
//! through [`Processor::capture`]. Both accept any length and frame internally.
use serde::{Deserialize, Serialize};
use sonora::config::{
AdaptiveDigital, CaptureLevelAdjustment, EchoCanceller, GainController2, HighPassFilter,
MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline,
};
use sonora::{AudioProcessing, Config, StreamConfig};
use crate::Framer;
use crate::pcm::SAMPLE_RATE;
/// Samples in one 10 ms processing frame (mono, 48 kHz).
pub const PROCESS_FRAME: usize = SAMPLE_RATE as usize / 100;
/// How hard noise suppression works.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoiseLevel {
/// About 6 dB.
Low,
/// About 12 dB.
#[default]
Moderate,
/// About 18 dB.
High,
/// About 21 dB.
VeryHigh,
}
impl From<NoiseLevel> for NoiseSuppressionLevel {
fn from(level: NoiseLevel) -> Self {
match level {
NoiseLevel::Low => Self::Low,
NoiseLevel::Moderate => Self::Moderate,
NoiseLevel::High => Self::High,
NoiseLevel::VeryHigh => Self::VeryHigh,
}
}
}
/// User settings for microphone processing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProcessingSettings {
/// Remove what the speakers play from the microphone signal.
pub echo_cancellation: bool,
/// Remove steady background noise (fans, hum, hiss).
pub noise_suppression: bool,
pub noise_level: NoiseLevel,
/// Bring speech to a steady level (adaptive digital gain and limiter).
pub auto_gain: bool,
/// Manual microphone gain in dB, applied before everything else.
/// Clamped to ±[`MAX_INPUT_GAIN_DB`].
pub input_gain_db: f32,
/// Remove rumble below ~80 Hz. Always on while echo cancellation is.
pub high_pass: bool,
}
/// Limit of [`ProcessingSettings::input_gain_db`].
pub const MAX_INPUT_GAIN_DB: f32 = 30.0;
impl Default for ProcessingSettings {
fn default() -> Self {
Self {
echo_cancellation: true,
noise_suppression: true,
noise_level: NoiseLevel::Moderate,
auto_gain: true,
input_gain_db: 0.0,
high_pass: true,
}
}
}
impl ProcessingSettings {
/// Everything off: the processor passes audio through untouched.
pub fn off() -> Self {
Self {
echo_cancellation: false,
noise_suppression: false,
noise_level: NoiseLevel::Moderate,
auto_gain: false,
input_gain_db: 0.0,
high_pass: false,
}
}
fn input_gain(&self) -> f32 {
let db = if self.input_gain_db.is_finite() { self.input_gain_db } else { 0.0 };
10f32.powf(db.clamp(-MAX_INPUT_GAIN_DB, MAX_INPUT_GAIN_DB) / 20.0)
}
fn is_passthrough(&self) -> bool {
!self.echo_cancellation
&& !self.noise_suppression
&& !self.auto_gain
&& !self.high_pass
&& self.input_gain() == 1.0
}
fn to_config(&self) -> Config {
let gain = self.input_gain();
Config {
pipeline: Pipeline {
// Full band: voice is Opus at 48 kHz.
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
..Default::default()
},
capture_level_adjustment: (gain != 1.0)
.then(|| CaptureLevelAdjustment { pre_gain_factor: gain, ..Default::default() }),
high_pass_filter: self.high_pass.then(HighPassFilter::default),
echo_canceller: self.echo_cancellation.then(EchoCanceller::default),
noise_suppression: self
.noise_suppression
.then(|| NoiseSuppression { level: self.noise_level.into(), ..Default::default() }),
gain_controller2: self.auto_gain.then(|| GainController2 {
adaptive_digital: Some(AdaptiveDigital::default()),
..Default::default()
}),
..Default::default()
}
}
}
/// Echo canceller statistics, for diagnostics.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ProcessingStats {
/// Echo return loss enhancement in dB: how much echo the canceller removes.
pub erle_db: Option<f64>,
/// Render-to-capture delay the canceller estimated.
pub delay_ms: Option<i32>,
}
/// Microphone processing pipeline stage. See the [module docs](self).
pub struct Processor {
apm: AudioProcessing,
settings: ProcessingSettings,
passthrough: bool,
delay_ms: u32,
render_framer: Framer,
capture_framer: Framer,
frame: Vec<f32>,
}
impl Processor {
pub fn new(settings: &ProcessingSettings) -> Self {
let stream = StreamConfig::new(SAMPLE_RATE, 1);
let apm = AudioProcessing::builder()
.config(settings.to_config())
.capture_config(stream)
.render_config(stream)
.build();
Self {
apm,
settings: settings.clone(),
passthrough: settings.is_passthrough(),
delay_ms: 0,
render_framer: Framer::new(PROCESS_FRAME),
capture_framer: Framer::new(PROCESS_FRAME),
frame: vec![0.0; PROCESS_FRAME],
}
}
pub fn settings(&self) -> &ProcessingSettings {
&self.settings
}
/// Change settings. Only reconfigures when something changed, since that
/// resets the adaptive filters.
pub fn apply(&mut self, settings: &ProcessingSettings) {
if *settings == self.settings {
return;
}
self.apm.apply_config(settings.to_config());
self.settings = settings.clone();
self.passthrough = settings.is_passthrough();
}
/// Hint for the echo canceller: time from handing a frame to
/// [`render`](Self::render) until it is heard, plus time from the
/// microphone picking a sample up until it reaches
/// [`capture`](Self::capture). The canceller estimates the rest itself.
pub fn set_delay_ms(&mut self, delay_ms: u32) {
if delay_ms != self.delay_ms {
self.delay_ms = delay_ms;
// Values above 500 ms are clamped, which is fine for a hint.
let _ = self.apm.set_stream_delay_ms(delay_ms.min(500) as i32);
}
}
/// Feed far-end audio: mono 48 kHz, exactly as played.
pub fn render(&mut self, samples: &[f32]) {
if !self.settings.echo_cancellation {
return;
}
let Self { apm, render_framer, frame, .. } = self;
render_framer.push(samples, |f| {
// Render output is not used: no render-side processing is enabled.
let _ = apm.process_render_f32(&[f], &mut [frame.as_mut_slice()]);
});
}
/// Process microphone audio (mono 48 kHz), appending the result to `out`.
/// Output comes in whole 10 ms frames, so up to 10 ms stay buffered.
pub fn capture(&mut self, samples: &[f32], out: &mut Vec<f32>) {
if self.passthrough && self.capture_framer.buffered() == 0 {
out.extend_from_slice(samples);
return;
}
let Self { apm, capture_framer, frame, passthrough, .. } = self;
capture_framer.push(samples, |f| {
if *passthrough {
out.extend_from_slice(f);
} else if apm.process_capture_f32(&[f], &mut [frame.as_mut_slice()]).is_ok() {
out.extend_from_slice(frame);
} else {
out.extend_from_slice(f);
}
});
}
pub fn stats(&self) -> ProcessingStats {
let stats = self.apm.statistics();
ProcessingStats { erle_db: stats.echo_return_loss_enhancement, delay_ms: stats.delay_ms }
}
}
impl std::fmt::Debug for Processor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Processor").field("settings", &self.settings).finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use std::f32::consts::TAU;
use super::*;
use crate::pcm::{self, energy, white_noise as noise};
fn db(ratio: f32) -> f32 {
10.0 * ratio.max(1e-20).log10()
}
#[test]
fn passthrough_when_off() {
let mut p = Processor::new(&ProcessingSettings::off());
let input = pcm::sine(440.0, 0.05, 0.3);
let mut out = Vec::new();
p.capture(&input[..100], &mut out);
p.capture(&input[100..], &mut out);
assert_eq!(out, input);
}
#[test]
fn input_gain_is_clamped() {
let s = ProcessingSettings { input_gain_db: 1000.0, ..ProcessingSettings::off() };
assert!((s.input_gain() - 10f32.powf(1.5)).abs() < 1e-3);
let s = ProcessingSettings { input_gain_db: f32::NAN, ..ProcessingSettings::off() };
assert_eq!(s.input_gain(), 1.0);
let s = ProcessingSettings { input_gain_db: 6.0, ..ProcessingSettings::off() };
assert!(!s.is_passthrough());
}
#[test]
fn settings_serde_defaults() {
let s: ProcessingSettings = serde_json::from_str(r#"{"noise_level":"very_high"}"#).unwrap();
assert_eq!(s.noise_level, NoiseLevel::VeryHigh);
assert!(s.echo_cancellation);
}
/// The far end leaks into the microphone 40 ms later at -6 dB; after the
/// canceller converged the echo must be at least 10 dB quieter.
#[test]
fn cancels_synthetic_echo() {
let settings = ProcessingSettings {
echo_cancellation: true,
high_pass: true,
..ProcessingSettings::off()
};
let mut p = Processor::new(&settings);
p.set_delay_ms(40);
let seconds = 6;
let delay = 40 * PROCESS_FRAME / 10;
// Speech-like far end: noise with a syllable-rate envelope.
let far: Vec<f32> = noise(SAMPLE_RATE as usize * seconds, 0.4, 1)
.into_iter()
.enumerate()
.map(|(i, s)| s * (0.6 + 0.4 * (i as f32 * 4.0 / SAMPLE_RATE as f32 * TAU).sin()))
.collect();
let mut near = vec![0.0; delay];
near.extend(far.iter().map(|s| s * 0.5));
near.truncate(far.len());
let mut out = Vec::new();
for (f, n) in far.chunks(PROCESS_FRAME).zip(near.chunks(PROCESS_FRAME)) {
p.render(f);
p.capture(n, &mut out);
}
assert_eq!(out.len(), near.len());
let tail = SAMPLE_RATE as usize * 2;
let before = energy(&near[near.len() - tail..]);
let after = energy(&out[out.len() - tail..]);
let attenuation = db(before / after);
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
}
/// White noise gets quieter while a tone on top of it survives. The tone
/// comes in 200 ms bursts like syllables: a steady tone is stationary and
/// a noise suppressor rightly learns it as noise.
#[test]
fn suppresses_noise_keeps_tone() {
let settings = ProcessingSettings {
noise_suppression: true,
noise_level: NoiseLevel::High,
..ProcessingSettings::off()
};
let seconds = 4;
let n = SAMPLE_RATE as usize * seconds;
let hiss = noise(n, 0.05, 7);
let mut p = Processor::new(&settings);
let mut out = Vec::new();
p.capture(&hiss, &mut out);
let tail = SAMPLE_RATE as usize;
let reduction = db(energy(&hiss[n - tail..]) / energy(&out[n - tail..]));
assert!(reduction >= 10.0, "noise reduced by {reduction:.1} dB");
let ms = |ms: usize| ms * SAMPLE_RATE as usize / 1000;
let tone: Vec<f32> = pcm::sine(600.0, seconds as f32, 0.3)
.into_iter()
.enumerate()
.map(|(i, s)| if i % ms(400) < ms(200) { s } else { 0.0 })
.collect();
let mixed: Vec<f32> = tone.iter().zip(&hiss).map(|(a, b)| a + b).collect();
let mut p = Processor::new(&settings);
let mut out = Vec::new();
p.capture(&mixed, &mut out);
// The last two seconds, away from the burst edges.
for start in (n - ms(2000)..n).step_by(ms(400)) {
let on = start + ms(40)..start + ms(160);
let tone_in = pcm::goertzel_power(&tone[on.clone()], 600.0, SAMPLE_RATE);
let tone_out = pcm::goertzel_power(&out[on], 600.0, SAMPLE_RATE);
let loss = db(tone_in / tone_out);
assert!(loss.abs() < 3.0, "tone changed by {loss:.1} dB");
let off = start + ms(240)..start + ms(360);
let reduction = db(energy(&hiss[off.clone()]) / energy(&out[off]));
assert!(reduction >= 6.0, "noise between bursts reduced by {reduction:.1} dB");
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! All user audio settings in one serde struct, e.g. for
//! `tsc_store::Store::set_setting("audio", &settings)`. Missing fields take
//! their defaults, so stored settings survive new options.
use serde::{Deserialize, Serialize};
use crate::process::ProcessingSettings;
use crate::vad::VadSettings;
/// When the microphone is sent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransmitMode {
/// While the push-to-talk key or button is held.
#[default]
PushToTalk,
/// While the voice activity detector hears speech.
VoiceActivation,
/// Always (unless muted).
Continuous,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AudioSettings {
pub transmit: TransmitMode,
pub processing: ProcessingSettings,
pub vad: VadSettings,
/// Microphone by device id (`device::DeviceInfo::id`); `None` follows
/// the system default.
pub input_device: Option<String>,
/// Speakers by device id; `None` follows the system default.
pub output_device: Option<String>,
/// Output volume for everyone, linear (1 = unchanged), applied before
/// the echo canceller sees the signal.
pub output_volume: f32,
/// Audio kept queued for the speakers. Lower is snappier, higher
/// survives scheduling hiccups.
pub playback_buffer_ms: u32,
}
impl Default for AudioSettings {
fn default() -> Self {
Self {
transmit: TransmitMode::PushToTalk,
processing: ProcessingSettings::default(),
vad: VadSettings::default(),
input_device: None,
output_device: None,
output_volume: 1.0,
playback_buffer_ms: 60,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_roundtrip_and_defaults() {
let mut s = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
..Default::default()
};
s.processing.echo_cancellation = false;
s.vad.threshold_db = -35.0;
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<AudioSettings>(&json).unwrap(), s);
// Older or partial settings fill in defaults.
let partial: AudioSettings =
serde_json::from_str(r#"{"transmit":"continuous","vad":{"hangover_ms":100}}"#).unwrap();
assert_eq!(partial.transmit, TransmitMode::Continuous);
assert_eq!(partial.vad.hangover_ms, 100);
assert_eq!(partial.vad.threshold_db, VadSettings::default().threshold_db);
assert_eq!(partial.processing, ProcessingSettings::default());
}
}
+250
View File
@@ -0,0 +1,250 @@
//! Voice activity detection for voice-activated transmission.
//!
//! A level gate with hangover, optionally combined with the RNN speech
//! detector of WebRTC's AGC2 (through sonora), which ignores noise such as
//! typing, fans or breathing that is loud enough to pass the level gate.
//! Works on 10 ms mono frames at 48 kHz, after [`Processor`](crate::process::Processor).
use serde::{Deserialize, Serialize};
use sonora_agc2::vad_wrapper::VoiceActivityDetectorWrapper;
use crate::pcm::SAMPLE_RATE;
use crate::process::PROCESS_FRAME;
/// What opens the gate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VadMode {
/// The level is above the threshold.
#[default]
Level,
/// The level is above the threshold and the frame sounds like speech.
Speech,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct VadSettings {
pub mode: VadMode,
/// Level in dBFS (RMS of a 10 ms frame; a full-scale sine is -3 dBFS)
/// that opens the gate.
pub threshold_db: f32,
/// Keep transmitting this long after the last active frame, so word
/// endings and short pauses are not cut.
pub hangover_ms: u32,
/// Speech probability (0 to 1) needed in [`VadMode::Speech`].
pub speech_probability: f32,
}
impl Default for VadSettings {
fn default() -> Self {
// Speech after automatic gain control sits around -20 dBFS and the
// controller keeps noise below -50 dBFS.
Self {
mode: VadMode::Level,
threshold_db: -40.0,
hangover_ms: 300,
speech_probability: 0.6,
}
}
}
/// Level of silence, so the meter has a floor.
pub const SILENCE_DB: f32 = -100.0;
/// RMS level in dBFS.
pub fn level_db(samples: &[f32]) -> f32 {
let e = crate::pcm::energy(samples);
if e > 0.0 { (10.0 * e.log10()).max(SILENCE_DB) } else { SILENCE_DB }
}
/// Voice activity detector. See the [module docs](self).
pub struct Vad {
settings: VadSettings,
rnn: Option<VoiceActivityDetectorWrapper>,
scaled: Vec<f32>,
hang_remaining_ms: u32,
level_db: f32,
probability: f32,
}
impl Vad {
pub fn new(settings: &VadSettings) -> Self {
let mut vad = Self {
settings: settings.clone(),
rnn: None,
scaled: vec![0.0; PROCESS_FRAME],
hang_remaining_ms: 0,
level_db: SILENCE_DB,
probability: 0.0,
};
vad.apply(settings);
vad
}
pub fn settings(&self) -> &VadSettings {
&self.settings
}
pub fn apply(&mut self, settings: &VadSettings) {
if settings.mode == VadMode::Speech && self.rnn.is_none() {
self.rnn = Some(VoiceActivityDetectorWrapper::new(
sonora_simd::detect_backend(),
SAMPLE_RATE as i32,
));
} else if settings.mode != VadMode::Speech {
self.rnn = None;
self.probability = 0.0;
}
self.settings = settings.clone();
}
/// Analyse mono 48 kHz audio, a whole number of 10 ms frames (a
/// trailing partial frame is ignored). Returns whether to transmit.
pub fn process(&mut self, samples: &[f32]) -> bool {
for frame in samples.chunks_exact(PROCESS_FRAME) {
self.level_db = level_db(frame);
let mut active = self.level_db >= self.settings.threshold_db;
if let Some(rnn) = &mut self.rnn {
// The detector works on 16-bit scale floats.
for (dst, src) in self.scaled.iter_mut().zip(frame) {
*dst = src * 32768.0;
}
self.probability = rnn.analyze(&self.scaled);
active &= self.probability >= self.settings.speech_probability;
}
if active {
// Plus this frame itself.
self.hang_remaining_ms = self.settings.hangover_ms + 10;
} else {
self.hang_remaining_ms = self.hang_remaining_ms.saturating_sub(10);
}
}
self.is_active()
}
/// Whether the gate is open after the last frame.
pub fn is_active(&self) -> bool {
self.hang_remaining_ms > 0
}
/// Level of the last frame in dBFS, for a microphone meter.
pub fn level_db(&self) -> f32 {
self.level_db
}
/// Speech probability of the last frame, 0 unless in [`VadMode::Speech`].
pub fn speech_probability(&self) -> f32 {
self.probability
}
/// Close the gate immediately (e.g. when switching to push-to-talk).
pub fn reset(&mut self) {
self.hang_remaining_ms = 0;
}
}
impl std::fmt::Debug for Vad {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vad")
.field("settings", &self.settings)
.field("level_db", &self.level_db)
.field("active", &self.is_active())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pcm::{self, white_noise as noise};
/// A voiced sound: a 120 Hz pulse train through three vowel formants,
/// scaled to `amplitude` peak.
pub(crate) fn vowel(seconds: f32, amplitude: f32) -> Vec<f32> {
let n = (seconds * SAMPLE_RATE as f32) as usize;
let pulses: Vec<f32> =
(0..n).map(|i| if i % (SAMPLE_RATE as usize / 120) == 0 { 1.0 } else { 0.0 }).collect();
let resonate = |freq: f32, bandwidth: f32| -> Vec<f32> {
let r = (-std::f32::consts::PI * bandwidth / SAMPLE_RATE as f32).exp();
let c = 2.0 * r * (std::f32::consts::TAU * freq / SAMPLE_RATE as f32).cos();
let (mut y1, mut y2) = (0.0f32, 0.0f32);
pulses
.iter()
.map(|&x| {
let y = x * (1.0 - r) + c * y1 - r * r * y2;
(y2, y1) = (y1, y);
y
})
.collect()
};
let (f1, f2, f3) = (resonate(700.0, 80.0), resonate(1200.0, 90.0), resonate(2600.0, 120.0));
let mix: Vec<f32> = (0..n).map(|i| f1[i] + 0.6 * f2[i] + 0.3 * f3[i]).collect();
let peak = mix.iter().fold(0.0f32, |m, s| m.max(s.abs()));
mix.iter().map(|s| s / peak * amplitude).collect()
}
fn active_fraction(vad: &mut Vad, signal: &[f32]) -> f32 {
let frames: Vec<bool> =
signal.chunks_exact(PROCESS_FRAME).map(|f| vad.process(f)).collect();
frames.iter().filter(|&&a| a).count() as f32 / frames.len() as f32
}
#[test]
fn level() {
assert_eq!(level_db(&[0.0; 480]), SILENCE_DB);
assert!((level_db(&pcm::sine(1000.0, 0.01, 1.0)) + 3.01).abs() < 0.1);
assert!((level_db(&[0.1; 480]) + 20.0).abs() < 0.01);
}
#[test]
fn gate_and_hangover() {
let settings = VadSettings { hangover_ms: 50, ..Default::default() };
let mut vad = Vad::new(&settings);
let loud = pcm::sine(300.0, 0.01, 0.1);
let quiet = vec![0.001; PROCESS_FRAME];
assert!(!vad.process(&quiet));
assert!(vad.process(&loud));
// 50 ms of hangover after the last loud frame, then closed.
for _ in 0..5 {
assert!(vad.process(&quiet));
}
assert!(!vad.process(&quiet));
// A 20 ms frame is analysed as two 10 ms frames.
assert!(vad.process(&[loud.clone(), loud].concat()));
vad.reset();
assert!(!vad.is_active());
}
#[test]
fn threshold_is_respected() {
let mut vad =
Vad::new(&VadSettings { threshold_db: -30.0, hangover_ms: 0, ..Default::default() });
// -33 dBFS stays closed, -23 dBFS opens.
assert!(!vad.process(&pcm::sine(300.0, 0.01, 0.0316)));
assert!(vad.process(&pcm::sine(300.0, 0.01, 0.1)));
}
/// In speech mode, noise loud enough for the level gate stays out, a
/// voiced sound gets through.
#[test]
fn speech_mode_rejects_noise() {
let settings = VadSettings { mode: VadMode::Speech, hangover_ms: 0, ..Default::default() };
let hiss = noise(SAMPLE_RATE as usize * 2, 0.05, 3);
assert!(level_db(&hiss) > settings.threshold_db);
let mut level_only = Vad::new(&VadSettings { mode: VadMode::Level, ..settings.clone() });
assert!(active_fraction(&mut level_only, &hiss) > 0.99);
let mut vad = Vad::new(&settings);
let noise_active = active_fraction(&mut vad, &hiss);
assert!(noise_active < 0.1, "noise active {noise_active}");
let mut vad = Vad::new(&settings);
let voice_active = active_fraction(&mut vad, &vowel(2.0, 0.3));
assert!(voice_active > 0.8, "voice active {voice_active}");
assert!(vad.speech_probability() > 0.5);
// Switching back to level mode drops the detector.
vad.apply(&VadSettings::default());
assert_eq!(vad.speech_probability(), 0.0);
}
}
+129
View File
@@ -0,0 +1,129 @@
//! A one-hour call with a sender whose clock runs ±200 ppm off ours: the
//! jitter buffer must keep the latency bounded instead of drifting by the
//! 720 ms the clocks disagree over an hour.
//!
//! The sender transmits continuously (the worst case: talk spurts would reset
//! the queue) over a network with 20–60 ms of jitter, reordering and 0.5 %
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsc_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use tsc_audio::{Mixer, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
const MARKER_EVERY: u64 = 1500;
struct Rng(u64);
impl Rng {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 11) as f64 / (1u64 << 53) as f64
}
}
/// Returns the latency of each marker in ms, in order.
fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
// A quiet frame (-65 dBFS noise) and a loud marker, encoded once.
let quiet = white_noise(FRAME_SAMPLES, 0.001, 1);
for _ in 0..5 {
encoder.encode_to_bytes(&quiet).unwrap();
}
let quiet = encoder.encode_to_bytes(&quiet).unwrap().to_vec();
let marker = encoder.encode_to_bytes(&sine(1000.0, 0.02, 0.5)).unwrap().to_vec();
let mut rng = Rng(ppm.to_bits());
let mut mixer = Mixer::new();
let client = ClientId(5);
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
// Sender frame n is made at n * 20 ms of the sender's clock.
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
// (arrival time, packet id), kept sorted by arrival.
let mut in_flight: Vec<(f64, u64)> = Vec::new();
let mut next_frame = 0u64;
let mut markers_sent = Vec::new();
let mut latencies = Vec::new();
let mut out = vec![0.0f32; PULL * 2];
let mut now = 0u64;
while now < total {
// Everything the sender produced up to now goes on the wire.
while frame_time(next_frame) <= now as f64 {
let is_marker = next_frame % MARKER_EVERY == MARKER_EVERY / 2;
if is_marker {
markers_sent.push(frame_time(next_frame));
}
// Markers are never lost, so each one can be matched.
if is_marker || rng.next() >= 0.005 {
let jitter = (0.02 + 0.04 * rng.next()) * SAMPLE_RATE as f64;
in_flight.push((frame_time(next_frame) + jitter, next_frame));
}
next_frame += 1;
}
in_flight.sort_by(|a, b| a.0.total_cmp(&b.0));
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
for (_, n) in in_flight.drain(..arrived) {
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
let packet = OutAudio::new(&AudioData::S2C {
id: n as u16,
codec: CodecType::OpusVoice,
from: 5,
data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
// Late packets are dropped by the jitter buffer, as on a real network.
let _ = mixer.handle_packet(client, packet);
}
out.fill(0.0);
mixer.fill_buffer(&mut out);
let left: Vec<f32> = out.iter().step_by(2).copied().collect();
if energy(&left) > 1e-3 {
// The latest marker made before now; they are 30 s apart.
let sent = markers_sent.iter().rev().find(|&&t| t <= now as f64).copied();
if let Some(sent) = sent {
let latency = (now as f64 - sent) * 1000.0 / SAMPLE_RATE as f64;
// One detection per marker (it spans two 10 ms pulls).
if latencies.len() < markers_sent.len() && latency < 5000.0 {
let index = markers_sent.iter().position(|&t| t == sent).unwrap();
if index == latencies.len() {
latencies.push(latency);
}
}
}
}
now += PULL as u64;
}
assert_eq!(latencies.len(), markers_sent.len(), "every marker must come out (ppm {ppm})");
latencies
}
fn check(ppm: f64) {
let latencies = simulate(ppm, 1.0);
assert_eq!(latencies.len(), 120);
let max = latencies.iter().copied().fold(0.0, f64::max);
let min = latencies.iter().copied().fold(f64::MAX, f64::min);
let first: f64 = latencies[..20].iter().sum::<f64>() / 20.0;
let last: f64 = latencies[latencies.len() - 20..].iter().sum::<f64>() / 20.0;
println!(
"{ppm:+} ppm: latency min {min:.0} ms, max {max:.0} ms, first 10 min avg {first:.0} ms, last 10 min avg {last:.0} ms"
);
// The network alone adds 20-60 ms; unchecked drift would add 720 ms.
assert!(min >= 20.0, "latency {min} ms is below the network delay");
assert!(max < 250.0, "latency grew to {max} ms");
assert!((last - first).abs() < 60.0, "latency drifted from {first} ms to {last} ms");
}
#[test]
fn fast_sender_one_hour() {
check(200.0);
}
#[test]
fn slow_sender_one_hour() {
check(-200.0);
}
+1
View File
@@ -26,6 +26,7 @@ tsc-gateway-proto = { path = "../tsc-gateway-proto" }
tsc-model = { path = "../tsc-model" }
tsc-observer = { path = "../tsc-observer" }
tsc-query = { path = "../tsc-query" }
tsc-stream = { path = "../tsc-stream" }
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
+457 -117
View File
@@ -1,18 +1,23 @@
//! Audio thread: capture → encode → voice connection, and incoming voice →
//! jitter buffer/mixer → playback.
//! Audio thread: capture → processing (echo cancellation, noise suppression,
//! gain) → voice activity / push-to-talk → encode → voice connection, and
//! incoming voice → jitter buffer/mixer (per-client volume) → playback, with
//! what is played fed back to the echo canceller as its reference.
//!
//! Devices live on their own OS thread (cpal streams are not `Send` on every
//! platform); the connection task talks to it through channels.
//! platform); the connection task talks to it through channels. The device
//! independent part is [`Pipeline`]; the thread loop only moves samples
//! between it and the devices, reopening devices that go away.
use std::collections::VecDeque;
use std::sync::mpsc as std_mpsc;
use std::thread;
use std::time::Duration;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use tsc_audio::resample::Linear;
use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder};
use tsc_audio::pcm::{self, FRAME_SAMPLES};
use tsc_audio::settings::TransmitMode;
use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
@@ -21,6 +26,23 @@ pub(crate) enum AudioIn {
Transmit(bool),
InputMuted(bool),
OutputMuted(bool),
/// Devices, processing, voice activation and transmit mode.
#[allow(dead_code, reason = "sent once the session exposes audio settings")]
Settings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientVolume {
client: ClientId,
volume: f32,
},
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientMuted {
client: ClientId,
muted: bool,
},
/// The client left; client ids are reused, so forget its volume.
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientLeft(ClientId),
}
pub(crate) struct AudioHandle {
@@ -33,24 +55,19 @@ impl AudioHandle {
}
}
/// Voice activity: transmit while the level is above the threshold, with a
/// short hang time so word endings are not cut.
struct Vad {
threshold: f32,
hang_frames: u32,
remaining: u32,
}
impl Vad {
fn active(&mut self, frame: &[f32]) -> bool {
if pcm::energy(frame) > self.threshold {
self.remaining = self.hang_frames;
} else if self.remaining > 0 {
self.remaining -= 1;
}
self.remaining > 0
}
}
/// With voice activation, also send this many 20 ms frames from before the
/// detector opened, so word onsets are not cut.
const PRE_ROLL_FRAMES: usize = 2;
/// Capacity of the speaker queue; [`AudioSettings::playback_buffer_ms`] is
/// clamped below it.
#[cfg(feature = "audio-device")]
const PLAYBACK_CAPACITY_MS: u32 = 200;
/// Latency of the devices beyond our queues, as a hint for the echo
/// canceller (it estimates the actual delay itself).
#[cfg(feature = "audio-device")]
const DEVICE_LATENCY_MS: u32 = 20;
/// How long the loop sleeps between rounds.
const TICK: Duration = Duration::from_millis(5);
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
/// no device) are reported through `errors`.
@@ -59,141 +76,464 @@ pub(crate) fn spawn(
errors: mpsc::UnboundedSender<String>,
voice_activation: bool,
) -> AudioHandle {
let transmit =
if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk };
let settings = AudioSettings { transmit, ..Default::default() };
let (tx, rx) = std_mpsc::channel();
thread::Builder::new()
.name("tsc-audio".into())
.spawn(move || run(rx, outgoing, errors, voice_activation))
.spawn(move || run(rx, outgoing, errors, settings))
.expect("spawn audio thread");
AudioHandle { tx }
}
/// Everything between the devices and the connection.
struct Pipeline {
settings: AudioSettings,
encoder: VoiceEncoder,
mixer: Mixer,
processor: Processor,
vad: Vad,
framer: Framer,
processed: Vec<f32>,
pre_roll: VecDeque<Vec<f32>>,
ptt: bool,
input_muted: bool,
output_muted: bool,
was_sending: bool,
/// Processed microphone audio, for tests.
#[cfg(test)]
tap: Vec<f32>,
}
impl Pipeline {
fn new(settings: AudioSettings) -> tsc_audio::Result<Self> {
let settings = sanitize(settings);
Ok(Self {
encoder: VoiceEncoder::new(VoiceCodec::Voice)?,
mixer: Mixer::new(),
processor: Processor::new(&settings.processing),
vad: Vad::new(&settings.vad),
framer: Framer::new(FRAME_SAMPLES),
processed: Vec::new(),
pre_roll: VecDeque::new(),
ptt: false,
input_muted: false,
output_muted: false,
was_sending: false,
settings,
#[cfg(test)]
tap: Vec::new(),
})
}
fn handle(&mut self, msg: AudioIn) {
match msg {
AudioIn::Packet(packet) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => return,
};
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
debug!(%error, "dropped voice packet");
}
}
AudioIn::Transmit(on) => self.ptt = on,
AudioIn::InputMuted(m) => self.input_muted = m,
AudioIn::OutputMuted(m) => self.output_muted = m,
AudioIn::Settings(settings) => {
let settings = sanitize(*settings);
self.processor.apply(&settings.processing);
self.vad.apply(&settings.vad);
if settings.transmit != TransmitMode::VoiceActivation {
self.vad.reset();
self.pre_roll.clear();
}
self.settings = settings;
}
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
AudioIn::ClientLeft(client) => self.mixer.forget(client),
}
}
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
self.processor.set_delay_ms(delay_ms);
self.processed.clear();
self.processor.capture(samples, &mut self.processed);
#[cfg(test)]
self.tap.extend_from_slice(&self.processed);
let mut frames = Vec::new();
self.framer.push(&self.processed, |f| frames.push(f.to_vec()));
for frame in frames {
self.transmit(frame, send);
}
}
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
// Always analysed, so the detector's state is current when needed.
let voice = self.vad.process(&frame);
let wanted = match self.settings.transmit {
TransmitMode::PushToTalk => self.ptt,
TransmitMode::VoiceActivation => voice,
TransmitMode::Continuous => true,
};
let sending = wanted && !self.input_muted;
if sending {
let pre_roll: Vec<_> = self.pre_roll.drain(..).collect();
for f in pre_roll.iter().chain([&frame]) {
match self.encoder.encode(f) {
Ok(packet) => send(packet),
Err(e) => warn!(%e, "encoding failed"),
}
}
} else {
if self.was_sending {
send(self.encoder.end_of_stream());
}
if self.settings.transmit == TransmitMode::VoiceActivation {
self.pre_roll.push_back(frame);
if self.pre_roll.len() > PRE_ROLL_FRAMES {
self.pre_roll.pop_front();
}
}
}
self.was_sending = sending;
}
/// The next 20 ms for the speakers (mono, 48 kHz), which also becomes
/// the echo canceller's reference.
fn playback_frame(&mut self) -> Vec<f32> {
let mut stereo = vec![0.0; FRAME_SAMPLES * 2];
self.mixer.fill_buffer(&mut stereo);
let gain = if self.output_muted { 0.0 } else { self.settings.output_volume };
let mut mono = pcm::to_mono(&stereo, 2);
for s in &mut mono {
*s = (*s * gain).clamp(-1.0, 1.0);
}
self.processor.render(&mono);
mono
}
}
fn sanitize(mut settings: AudioSettings) -> AudioSettings {
let volume = settings.output_volume;
settings.output_volume = if volume.is_finite() { volume.clamp(0.0, 4.0) } else { 1.0 };
#[cfg(feature = "audio-device")]
{
settings.playback_buffer_ms =
settings.playback_buffer_ms.clamp(20, PLAYBACK_CAPACITY_MS - 20);
}
settings
}
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
errors: mpsc::UnboundedSender<String>,
voice_activation: bool,
settings: AudioSettings,
) {
#[cfg(feature = "audio-device")]
let mut capture = match tsc_audio::device::Capture::open_default(500) {
Ok(c) => Some(c),
Err(e) => {
let _ = errors.send(format!("no microphone: {e}"));
None
}
};
#[cfg(feature = "audio-device")]
let mut playback = match tsc_audio::device::Playback::open_default(200) {
Ok(p) => Some(p),
Err(e) => {
let _ = errors.send(format!("no speakers: {e}"));
None
}
};
let mut devices = devices::Devices::new(&settings);
#[cfg(not(feature = "audio-device"))]
let _ = errors.send("built without audio device support".to_string());
let mut encoder = match VoiceEncoder::new(VoiceCodec::Voice) {
Ok(e) => e,
let mut pipeline = match Pipeline::new(settings) {
Ok(p) => p,
Err(e) => {
let _ = errors.send(e.to_string());
return;
}
};
let mut mixer = Mixer::new();
let mut framer = Framer::new(FRAME_SAMPLES);
let mut vad = Vad { threshold: 1e-4, hang_frames: 15, remaining: 0 };
let (mut ptt, mut input_muted, mut output_muted) = (false, false, false);
let mut was_sending = false;
#[cfg(feature = "audio-device")]
let mut capture_resampler = capture.as_ref().map(|c| Linear::new(c.rate, SAMPLE_RATE));
#[cfg(feature = "audio-device")]
let mut playback_resampler = playback.as_ref().map(|p| Linear::new(SAMPLE_RATE, p.rate));
let mut captured = Vec::new();
let mut resampled = Vec::new();
let mut send = |packet| {
let _ = outgoing.send(packet);
};
// Without speakers the mixer is drained at real time, so queues do not
// fill up and talkers still end.
let mut idle_clock = Instant::now();
loop {
// Control messages and incoming voice.
loop {
match rx.try_recv() {
Ok(AudioIn::Packet(packet)) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => continue,
};
if let Err(error) = mixer.handle_packet(ClientId(from), packet) {
debug!(%error, "dropped voice packet");
Ok(msg) => {
#[cfg(feature = "audio-device")]
if let AudioIn::Settings(s) = &msg {
devices.select(s);
}
pipeline.handle(msg);
}
Ok(AudioIn::Transmit(on)) => ptt = on,
Ok(AudioIn::InputMuted(m)) => input_muted = m,
Ok(AudioIn::OutputMuted(m)) => output_muted = m,
Err(std_mpsc::TryRecvError::Empty) => break,
Err(std_mpsc::TryRecvError::Disconnected) => return,
}
}
// Capture → 48 kHz mono → 20 ms frames → Opus.
captured.clear();
resampled.clear();
#[cfg(feature = "audio-device")]
if let (Some(c), Some(r)) = (&mut capture, &mut capture_resampler) {
c.read_available(&mut captured);
let mono = pcm::to_mono(&captured, c.channels);
r.process(&mono, &mut resampled);
}
let mut frames = Vec::new();
framer.push(&resampled, |f| frames.push(f.to_vec()));
for frame in frames {
let send = !input_muted && if voice_activation { vad.active(&frame) } else { ptt };
if send {
match encoder.encode(&frame) {
Ok(packet) => {
let _ = outgoing.send(packet);
}
Err(e) => warn!(%e, "encoding failed"),
}
} else if was_sending {
let _ = outgoing.send(encoder.end_of_stream());
}
was_sending = send;
}
// Mixer → device rate/channels → playback.
#[cfg(feature = "audio-device")]
if let (Some(p), Some(r)) = (&mut playback, &mut playback_resampler) {
let needed_48k = (p.free() / p.channels) as u64 * SAMPLE_RATE as u64 / p.rate as u64;
if needed_48k as usize >= FRAME_SAMPLES {
let mut stereo = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut stereo);
if output_muted {
stereo.fill(0.0);
}
let mono = pcm::to_mono(&stereo, 2);
let mut out = Vec::with_capacity(mono.len());
r.process(&mono, &mut out);
p.write(&pcm::from_mono(&out, p.channels));
}
}
let playing = devices.step(&mut pipeline, &mut send, &errors);
#[cfg(not(feature = "audio-device"))]
let _ = (output_muted, &mut mixer);
let playing = {
// No microphone: nothing to process, but keep the path alive.
pipeline.capture(&[], 0, &mut send);
false
};
thread::sleep(Duration::from_millis(5));
if playing {
idle_clock = Instant::now();
} else {
let frame = Duration::from_millis(20);
while idle_clock + frame <= Instant::now() {
pipeline.playback_frame();
idle_clock += frame;
}
}
thread::sleep(TICK);
}
}
#[cfg(feature = "audio-device")]
mod devices {
use tokio::sync::mpsc;
use tracing::debug;
use tsc_audio::AudioSettings;
use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback};
use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use tsc_audio::resample::Linear;
use tsproto_packets::packets::OutPacket;
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
/// The microphone and speakers, reopened when they go away.
pub(super) struct Devices {
capture: Managed<Capture>,
playback: Managed<Playback>,
capture_resampler: Option<(u32, Linear)>,
playback_resampler: Option<(u32, Linear)>,
captured: Vec<f32>,
resampled: Vec<f32>,
}
/// A resampler for this device rate, recreated when the rate changes
/// (another device was opened).
fn resampler(slot: &mut Option<(u32, Linear)>, from: u32, to: u32, rate: u32) -> &mut Linear {
if slot.as_ref().is_none_or(|(r, _)| *r != rate) {
*slot = Some((rate, Linear::new(from, to)));
}
&mut slot.as_mut().expect("just set").1
}
fn report(errors: &mpsc::UnboundedSender<String>, what: &str, event: DeviceEvent) {
let message = match event {
DeviceEvent::Opened { name, fallback: false } => {
debug!(%name, "{what} opened");
return;
}
DeviceEvent::Opened { name, fallback: true } => {
format!("selected {what} not found, using {name}")
}
DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"),
DeviceEvent::Unavailable(e) => format!("no {what}: {e}"),
};
let _ = errors.send(message);
}
impl Devices {
pub fn new(settings: &AudioSettings) -> Self {
Self {
capture: Managed::new(settings.input_device.clone(), 500),
playback: Managed::new(settings.output_device.clone(), PLAYBACK_CAPACITY_MS),
capture_resampler: None,
playback_resampler: None,
captured: Vec::new(),
resampled: Vec::new(),
}
}
pub fn select(&mut self, settings: &AudioSettings) {
self.capture.select(settings.input_device.clone());
self.playback.select(settings.output_device.clone());
}
/// One round: top up the speakers, then process what the microphone
/// recorded. Returns whether speakers are open.
pub fn step(
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
errors: &mpsc::UnboundedSender<String>,
) -> bool {
if let Some(event) = self.playback.poll() {
report(errors, "speakers", event);
}
if let Some(event) = self.capture.poll() {
report(errors, "microphone", event);
}
// Mixer → speakers, keeping the configured amount queued.
let mut delay_ms = DEVICE_LATENCY_MS;
let playing = if let Some(p) = self.playback.stream() {
let r = resampler(&mut self.playback_resampler, SAMPLE_RATE, p.rate, p.rate);
let frame_len =
(FRAME_SAMPLES * p.rate as usize).div_ceil(SAMPLE_RATE as usize) + 1;
while p.queued_ms() < pipeline.settings.playback_buffer_ms
&& p.free() >= frame_len * p.channels
{
let mono = pipeline.playback_frame();
let mut out = Vec::with_capacity(frame_len);
r.process(&mono, &mut out);
p.write(&pcm::from_mono(&out, p.channels));
}
delay_ms += p.queued_ms();
true
} else {
false
};
// Microphone → 48 kHz mono → pipeline.
if let Some(c) = self.capture.stream() {
self.captured.clear();
self.resampled.clear();
c.read_available(&mut self.captured);
let mono = pcm::to_mono(&self.captured, c.channels);
let r = resampler(&mut self.capture_resampler, c.rate, SAMPLE_RATE, c.rate);
r.process(&mono, &mut self.resampled);
pipeline.capture(&self.resampled, delay_ms, send);
}
playing
}
}
}
#[cfg(test)]
mod tests {
use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
use tsc_audio::{ProcessingSettings, VadSettings};
use tsproto_packets::packets::{CodecType, Direction, OutAudio};
use super::*;
fn pipeline(transmit: TransmitMode) -> Pipeline {
Pipeline::new(AudioSettings {
transmit,
processing: ProcessingSettings::off(),
vad: VadSettings { hangover_ms: 40, ..Default::default() },
..Default::default()
})
.unwrap()
}
/// Run `samples` through the capture side; returns (voice packets,
/// end-of-stream packets).
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
let (mut voice, mut end) = (0, 0);
p.capture(samples, 0, &mut |packet: OutPacket| {
// Header of 3 bytes (id + codec) for C2S audio.
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
});
(voice, end)
}
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
}
#[test]
fn vad_hangs_after_speech() {
let mut vad = Vad { threshold: 1e-3, hang_frames: 2, remaining: 0 };
let loud = vec![0.5; 960];
let quiet = vec![0.0; 960];
assert!(!vad.active(&quiet));
assert!(vad.active(&loud));
assert!(vad.active(&quiet));
assert!(!vad.active(&quiet));
fn push_to_talk_and_mute() {
let mut p = pipeline(TransmitMode::PushToTalk);
let tone = sine(440.0, 0.2, 0.3);
assert_eq!(capture(&mut p, &tone), (0, 0));
p.handle(AudioIn::Transmit(true));
assert_eq!(capture(&mut p, &tone), (10, 0));
p.handle(AudioIn::InputMuted(true));
assert_eq!(capture(&mut p, &tone), (0, 1));
p.handle(AudioIn::InputMuted(false));
p.handle(AudioIn::Transmit(false));
assert_eq!(capture(&mut p, &tone), (0, 0));
}
#[test]
fn voice_activation_with_pre_roll() {
let mut p = pipeline(TransmitMode::VoiceActivation);
let quiet = vec![0.0; FRAME_SAMPLES * 5];
assert_eq!(capture(&mut p, &quiet), (0, 0));
// Speech opens the gate: the frame itself plus the pre-roll.
assert_eq!(capture(&mut p, &sine(440.0, 0.02, 0.3)), (1 + PRE_ROLL_FRAMES, 0));
// 40 ms of hangover, then the stream ends.
assert_eq!(capture(&mut p, &quiet), (2, 1));
// Switching modes through settings.
let settings = AudioSettings { transmit: TransmitMode::Continuous, ..p.settings.clone() };
p.handle(AudioIn::Settings(Box::new(settings)));
assert_eq!(capture(&mut p, &quiet), (5, 0));
}
/// Two talkers; one turned down, one muted, then forgotten.
#[test]
fn client_volume() {
let mut p = pipeline(TransmitMode::PushToTalk);
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = sine(700.0, 1.0, 0.4);
let mut play = |p: &mut Pipeline, from: u16| -> f32 {
let mut out = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
p.handle(incoming(from, i as u16, encoder.encode_to_bytes(frame).unwrap()));
out.extend(p.playback_frame());
}
energy(&out[out.len() / 2..])
};
let full = play(&mut p, 1);
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
let half = play(&mut p, 2);
let ratio_db = 10.0 * (half / full).log10();
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
assert!(play(&mut p, 3) < 1e-8);
p.handle(AudioIn::ClientLeft(ClientId(3)));
assert!(!p.mixer.is_muted(ClientId(3)));
}
/// End to end: a remote talker is played, the speakers leak into the
/// microphone 30 ms later, and the echo canceller (fed with what was
/// played) removes it from what we would send.
#[test]
fn echo_of_playback_is_cancelled() {
let mut p = Pipeline::new(AudioSettings {
transmit: TransmitMode::Continuous,
processing: ProcessingSettings { echo_cancellation: true, ..ProcessingSettings::off() },
..Default::default()
})
.unwrap();
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let far = white_noise(SAMPLE_RATE as usize * 6, 0.3, 11);
let delay = SAMPLE_RATE as usize * 30 / 1000;
let mut played = vec![0.0; delay];
let mut echo = Vec::new();
for (i, frame) in far.chunks_exact(FRAME_SAMPLES).enumerate() {
p.handle(incoming(9, i as u16, encoder.encode_to_bytes(frame).unwrap()));
played.extend(p.playback_frame());
let mic: Vec<f32> = played[played.len() - delay - FRAME_SAMPLES..played.len() - delay]
.iter()
.map(|s| s * 0.5)
.collect();
p.capture(&mic, 30, &mut |_| {});
echo.extend(mic);
}
let tail = SAMPLE_RATE as usize * 2;
let before = energy(&echo[echo.len() - tail..]);
let after = energy(&p.tap[p.tap.len() - tail..]);
let attenuation = 10.0 * (before / after).log10();
assert!(before > 1e-3, "the echo must be audible");
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
}
#[test]
fn settings_are_sanitized() {
let mut p = pipeline(TransmitMode::PushToTalk);
let settings = AudioSettings { output_volume: f32::INFINITY, ..Default::default() };
p.handle(AudioIn::Settings(Box::new(settings)));
assert_eq!(p.settings.output_volume, 1.0);
}
}
+105 -4
View File
@@ -10,12 +10,17 @@
//! Presence comes from the most authoritative connected source
//! (voice > gateway > query). Channel chat goes through the voice connection
//! when the user is in that channel, otherwise through a relay.
//!
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
//! sharing): see the `*Stream*` commands and events, and
//! [`Engine::subscribe_frames`] for the frames of watched streams.
mod audio;
mod gateway;
mod query;
mod route;
mod session;
pub mod stream;
mod voice;
use std::collections::HashMap;
@@ -25,6 +30,8 @@ use tokio::sync::{broadcast, mpsc};
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
pub use route::{ChatRoute, Dedup, route_chat};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
pub use voice::VoiceOptions;
pub type SessionId = u64;
@@ -84,6 +91,49 @@ pub enum Command {
session: SessionId,
on: bool,
},
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
/// [`Event::StreamState`]; frames go in through the sink of
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
StartStream {
session: SessionId,
setup: StreamSetup,
/// Accept every viewer instead of asking with [`Event::StreamViewerRequest`].
auto_accept: bool,
},
StopStream {
session: SessionId,
},
/// Answer an [`Event::StreamViewerRequest`].
AcceptViewer {
session: SessionId,
viewer: u16,
accept: bool,
},
/// Remove a viewer from our stream.
KickViewer {
session: SessionId,
viewer: u16,
},
/// An encoded frame for our stream.
SendStreamFrame {
session: SessionId,
frame: EncodedFrame,
},
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
/// [`Engine::subscribe_frames`].
WatchStream {
session: SessionId,
stream_id: String,
},
LeaveStream {
session: SessionId,
stream_id: String,
},
/// Ask the streamer of a watched stream for a keyframe.
RequestStreamKeyframe {
session: SessionId,
stream_id: String,
},
/// Close everything of a session.
CloseSession {
session: SessionId,
@@ -159,6 +209,37 @@ pub enum Event {
session: SessionId,
message: String,
},
/// The streams in our channel (TeamSpeak 6), full list.
StreamsChanged {
session: SessionId,
streams: Vec<StreamInfo>,
},
/// Our own stream.
StreamState {
session: SessionId,
state: StreamState,
},
/// Someone asks to watch our stream; answer with [`Command::AcceptViewer`].
StreamViewerRequest {
session: SessionId,
viewer: u16,
message: String,
},
/// The viewers of our stream and their state, full list.
StreamViewers {
session: SessionId,
viewers: Vec<ViewerInfo>,
},
/// A viewer needs a keyframe (also flagged on the [`StreamSink`]).
StreamKeyframeRequest {
session: SessionId,
},
/// A stream we watch.
WatchState {
session: SessionId,
stream_id: String,
state: WatchState,
},
}
/// Handle to the engine. Cheap to clone; all methods are non-blocking.
@@ -166,6 +247,7 @@ pub enum Event {
pub struct Engine {
commands: mpsc::UnboundedSender<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
}
impl Engine {
@@ -173,8 +255,10 @@ impl Engine {
pub fn start() -> Self {
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone()));
Self { commands, events }
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone(), frames.clone()));
Self { commands, events, frames }
}
pub fn send(&self, command: Command) {
@@ -184,9 +268,18 @@ impl Engine {
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.events.subscribe()
}
/// Encoded frames of the streams we watch (kept off the event bus).
pub fn subscribe_frames(&self) -> broadcast::Receiver<StreamFrame> {
self.frames.subscribe()
}
}
async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::Sender<Event>) {
async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
while let Some(command) = commands.recv().await {
let id = command_session(&command);
@@ -198,7 +291,7 @@ async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::
}
sessions
.entry(id)
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone()))
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone()))
.send(command);
}
}
@@ -217,6 +310,14 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetInputMuted { session, .. }
| Command::SetOutputMuted { session, .. }
| Command::SetTransmitting { session, .. }
| Command::StartStream { session, .. }
| Command::StopStream { session }
| Command::AcceptViewer { session, .. }
| Command::KickViewer { session, .. }
| Command::SendStreamFrame { session, .. }
| Command::WatchStream { session, .. }
| Command::LeaveStream { session, .. }
| Command::RequestStreamKeyframe { session, .. }
| Command::CloseSession { session } => *session,
}
}
+98 -5
View File
@@ -1,6 +1,6 @@
//! One server session: merges its sources and routes commands.
use std::collections::HashSet;
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
@@ -11,6 +11,7 @@ use crate::audio::{self, AudioHandle, AudioIn};
use crate::gateway::{self, GatewayCmd, GatewayEvent};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::stream::{PeerConfig, StreamFrame, StreamHandle, StreamInput};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
@@ -19,9 +20,13 @@ pub(crate) struct SessionHandle {
}
impl SessionHandle {
pub fn spawn(id: SessionId, events: broadcast::Sender<Event>) -> Self {
pub fn spawn(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events).run(rx));
tokio::spawn(Session::new(id, events, frames).run(rx));
Self { tx }
}
@@ -53,6 +58,12 @@ struct Session {
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
frames: broadcast::Sender<StreamFrame>,
/// `client_is_streaming` of the voice presence, as last told to the streams.
streaming_clients: BTreeMap<u16, Option<bool>>,
open_chats: HashSet<ChatTarget>,
dedup: Dedup,
sources_tx: mpsc::UnboundedSender<SourceEvent>,
@@ -60,7 +71,11 @@ struct Session {
}
impl Session {
fn new(id: SessionId, events: broadcast::Sender<Event>) -> Self {
fn new(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
id,
@@ -75,6 +90,10 @@ impl Session {
query: None,
query_presence: None,
audio: None,
streams: None,
stream_peer: PeerConfig::default(),
frames,
streaming_clients: BTreeMap::new(),
open_chats: HashSet::new(),
dedup: Dedup::default(),
sources_tx,
@@ -135,8 +154,10 @@ impl Session {
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
self.stop_streams("voice reconnecting");
let generation = self.next_generation();
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
if options.audio {
@@ -243,10 +264,50 @@ impl Session {
}
self.emit_state();
}
Command::StartStream { setup, auto_accept, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
}
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
Command::AcceptViewer { viewer, accept, .. } => {
self.stream_input(StreamInput::Respond { viewer, accept });
}
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
Command::SendStreamFrame { frame, .. } => {
// Frames without a stream are dropped silently.
if let Some(s) = &self.streams {
s.send(StreamInput::Frame(frame));
}
}
Command::WatchStream { stream_id, .. } => {
self.stream_input(StreamInput::Watch { stream_id });
}
Command::LeaveStream { stream_id, .. } => {
self.stream_input(StreamInput::Leave { stream_id });
}
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
}
Command::CloseSession { .. } => {}
}
}
fn stream_input(&self, input: StreamInput) {
match &self.streams {
Some(s) => s.send(input),
None if self.state.voice == VoiceState::Connected => {
self.error("streams need a TeamSpeak 6 server");
}
None => self.error("not connected with voice"),
}
}
fn stop_streams(&mut self, reason: &str) {
if let Some(s) = self.streams.take() {
s.send(StreamInput::Shutdown(reason.into()));
}
self.streaming_clients.clear();
}
fn voice_cmd(&self, cmd: VoiceCmd) {
match &self.voice {
Some((_, tx)) => {
@@ -299,6 +360,7 @@ impl Session {
}
fn stop_all(&mut self) {
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
@@ -334,17 +396,47 @@ impl Session {
fn voice_event(&mut self, e: VoiceEvent) {
match e {
VoiceEvent::Connected { name, flavor } => {
VoiceEvent::Connected { name, flavor, own_client } => {
self.state.voice = VoiceState::Connected;
self.emit_state();
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((_, voice)) = &self.voice
{
self.streams = Some(StreamHandle::spawn(
self.id,
own_client,
self.stream_peer.clone(),
voice.clone(),
self.events.clone(),
self.frames.clone(),
));
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
}
VoiceEvent::Presence(p) => {
if let Some(s) = &self.streams {
let clients: BTreeMap<_, _> =
p.clients.values().map(|c| (c.id, c.streaming)).collect();
if clients != self.streaming_clients {
self.streaming_clients = clients.clone();
s.send(StreamInput::Clients(clients));
}
}
self.voice_presence = Some(p);
self.publish_presence();
}
VoiceEvent::Stream(n) => {
if let Some(s) = &self.streams {
s.send(StreamInput::Notification(n));
}
}
VoiceEvent::StreamRequestFailed(request, error) => {
if let Some(s) = &self.streams {
s.send(StreamInput::RequestFailed(request, error));
}
}
VoiceEvent::OwnChannel(cid) => {
if self.state.own_channel != Some(cid) {
self.state.own_channel = Some(cid);
@@ -361,6 +453,7 @@ impl Session {
self.emit(Event::Talking { session: self.id, client, talking });
}
VoiceEvent::Disconnected(reason) => {
self.stop_streams("voice disconnected");
self.voice = None;
self.voice_presence = None;
self.audio = None;
+530
View File
@@ -0,0 +1,530 @@
//! TeamSpeak 6 streams of a session: a task that runs the stream sessions
//! ([`tsc_stream::Streams`]) of the voice connection.
//!
//! The voice task forwards stream notifications here and sends the resulting
//! commands. Only started for TeamSpeak 6 servers.
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
pub use tsc_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind,
MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec,
ViewerInfo, ViewerState,
};
use tsc_stream::{
Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams,
WatchEvent,
};
use tsclientlib::ClientId;
use crate::voice::VoiceCmd;
use crate::{Event, SessionId};
/// Our own stream.
#[derive(Clone, Debug, PartialEq)]
pub enum StreamState {
/// `setupstream` sent.
Starting,
/// Live: frames given to `sink` (or [`crate::Command::SendStreamFrame`])
/// reach every connected viewer.
Live {
id: String,
sink: StreamSink,
},
Ended(EndReason),
}
/// A stream we watch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WatchState {
/// Join request sent; waiting for the streamer.
Requested,
/// Accepted; connecting to the streamer.
Connecting,
/// Frames arrive through [`crate::Engine::subscribe_frames`].
Connected,
Ended(EndReason),
}
/// A received frame of a watched stream.
#[derive(Clone, Debug)]
pub struct StreamFrame {
pub session: SessionId,
pub stream_id: String,
pub frame: MediaFrame,
}
/// Hands encoded frames of our stream to the engine, e.g. from an encoder thread.
#[derive(Clone)]
pub struct StreamSink {
tx: mpsc::UnboundedSender<StreamInput>,
live: Arc<AtomicBool>,
keyframe: Arc<AtomicBool>,
}
impl StreamSink {
/// Send one frame; `false` once the stream has ended.
pub fn send(&self, frame: EncodedFrame) -> bool {
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
}
/// Whether a viewer asked for a keyframe since the last call.
pub fn take_keyframe_request(&self) -> bool {
self.keyframe.swap(false, Ordering::Relaxed)
}
pub fn is_live(&self) -> bool {
self.live.load(Ordering::Relaxed)
}
}
impl fmt::Debug for StreamSink {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StreamSink").field("live", &self.is_live()).finish()
}
}
impl PartialEq for StreamSink {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.live, &other.live)
}
}
pub(crate) enum StreamInput {
Start {
setup: StreamSetup,
auto_accept: bool,
},
Stop,
Respond {
viewer: u16,
accept: bool,
},
Kick {
viewer: u16,
},
Watch {
stream_id: String,
},
Leave {
stream_id: String,
},
RequestKeyframe {
stream_id: String,
},
Frame(EncodedFrame),
Notification(StreamNotification),
RequestFailed(Request, String),
/// Clients on the server with their `client_is_streaming`.
Clients(BTreeMap<u16, Option<bool>>),
/// The voice connection is gone.
Shutdown(String),
}
pub(crate) struct StreamHandle {
tx: mpsc::UnboundedSender<StreamInput>,
}
impl StreamHandle {
pub fn spawn(
session: SessionId,
own_client: u16,
config: PeerConfig,
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let task = StreamTask {
session,
streams: Streams::new(ClientId(own_client), config),
voice,
events,
frames,
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
};
tokio::spawn(task.run(rx));
Self { tx }
}
pub fn send(&self, input: StreamInput) {
let _ = self.tx.send(input);
}
}
struct StreamTask {
session: SessionId,
streams: Streams,
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
/// For the sinks handed out.
tx: mpsc::UnboundedSender<StreamInput>,
/// The sink of our live stream.
sink: Option<StreamSink>,
/// Clients on the server and their `client_is_streaming`.
clients: BTreeMap<u16, Option<bool>>,
}
impl StreamTask {
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<StreamInput>) {
loop {
tokio::select! {
input = rx.recv() => match input {
None => break,
Some(StreamInput::Shutdown(reason)) => {
self.shutdown(reason);
break;
}
Some(input) => self.input(input).await,
},
() = self.streams.wait_peers() => {}
}
self.flush();
}
debug!(session = self.session, "stream task ended");
}
fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
async fn input(&mut self, input: StreamInput) {
let session = self.session;
let result = match input {
StreamInput::Start { setup, auto_accept } => {
self.streams.start(StreamerOptions { setup, auto_accept }).map(|()| {
self.emit(Event::StreamState { session, state: StreamState::Starting });
})
}
StreamInput::Stop => self.streams.stop(),
StreamInput::Respond { viewer, accept } => {
self.streams.respond(ClientId(viewer), accept).await
}
StreamInput::Kick { viewer } => self.streams.kick(ClientId(viewer)),
StreamInput::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| {
self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested });
}),
StreamInput::Leave { stream_id } => self.streams.leave(&stream_id),
StreamInput::RequestKeyframe { stream_id } => {
self.streams.request_keyframe(&stream_id);
Ok(())
}
StreamInput::Frame(frame) => {
self.streams.write_frame(&frame);
Ok(())
}
StreamInput::Notification(n) => {
self.streams.handle_notification(n).await;
Ok(())
}
StreamInput::RequestFailed(request, error) => {
self.streams.request_failed(&request, &error);
Ok(())
}
StreamInput::Clients(clients) => {
// Streams of clients that left or stopped streaming are gone.
// Only changes count: a snapshot may predate the streaming flag
// of a stream that was just announced.
for (client, streaming) in &clients {
let was = self.clients.get(client).copied().flatten();
if let (Some(was), Some(now)) = (was, *streaming)
&& was != now
{
self.streams.set_client_streaming(ClientId(*client), now);
}
}
self.streams.retain_streamers(|c| clients.contains_key(&c.0));
self.clients = clients;
Ok(())
}
StreamInput::Shutdown(_) => Ok(()),
};
if let Err(e) = result {
self.emit(Event::Error { session, message: format!("stream: {e}") });
}
}
/// Send the requests on the connection and report the events.
fn flush(&mut self) {
while let Some(output) = self.streams.poll_output() {
match output {
Output::Request(request) => {
let _ = self.voice.send(VoiceCmd::Stream(request));
}
Output::Event(event) => self.event(event),
}
}
}
fn event(&mut self, event: StreamEvent) {
let session = self.session;
match event {
StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }),
StreamEvent::Streamer(StreamerEvent::Live { id }) => {
let sink = StreamSink {
tx: self.tx.clone(),
live: Arc::new(AtomicBool::new(true)),
keyframe: Arc::new(AtomicBool::new(true)),
};
self.sink = Some(sink.clone());
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
}
StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => {
self.emit(Event::StreamViewerRequest { session, viewer: viewer.0, message });
}
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
self.emit(Event::StreamViewers { session, viewers });
}
StreamEvent::Streamer(StreamerEvent::KeyframeRequest) => {
if let Some(sink) = &self.sink {
sink.keyframe.store(true, Ordering::Relaxed);
}
self.emit(Event::StreamKeyframeRequest { session });
}
StreamEvent::Streamer(StreamerEvent::Ended(reason)) => {
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
self.emit(Event::StreamState { session, state: StreamState::Ended(reason) });
}
StreamEvent::Watch { id, event } => {
let state = match event {
WatchEvent::Accepted => WatchState::Connecting,
WatchEvent::Connected => WatchState::Connected,
WatchEvent::Ended(reason) => WatchState::Ended(reason),
WatchEvent::Frame(frame) => {
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
return;
}
};
self.emit(Event::WatchState { session, stream_id: id, state });
}
}
}
/// The connection is gone: report our stream and watched streams as ended.
fn shutdown(&mut self, reason: String) {
let session = self.session;
let ended = || EndReason::Failed(reason.clone());
if self.streams.streamer().is_some() {
self.emit(Event::StreamState { session, state: StreamState::Ended(ended()) });
}
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
for watched in self.streams.watching() {
let stream_id = watched.id().to_owned();
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
}
if self.streams.directory().iter().next().is_some() {
self.emit(Event::StreamsChanged { session, streams: Vec::new() });
}
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tsc_stream::{FrameSource, SyntheticSource};
use super::*;
const CLIENTS: [u16; 2] = [5, 6];
/// The notifications the server sends for `request` from `from`, per receiver.
fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> {
let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec();
match request {
Request::Setup(setup) => CLIENTS
.map(|c| {
let info = StreamInfo {
id: "s-1".into(),
streamer: ClientId(from),
name: setup.name.clone(),
kind: setup.kind,
bitrate: setup.bitrate,
viewer_limit: setup.viewer_limit,
audio: setup.audio,
};
let return_code = (c == from).then(|| "1".to_owned());
(c, StreamNotification::Started { info, return_code })
})
.to_vec(),
Request::Stop { id } => {
both(StreamNotification::Stopped { id, streamer: None, reason: None })
}
Request::Join { id, streamer, message } => vec![(
streamer.0,
StreamNotification::JoinRequest {
id,
viewer: ClientId(from),
message,
remove: false,
},
)],
Request::Leave { id, streamer } => vec![(
streamer.0,
StreamNotification::JoinRequest {
id,
viewer: ClientId(from),
message: String::new(),
remove: true,
},
)],
Request::Respond { id, viewer, offer, accept } => vec![(
viewer.0,
StreamNotification::JoinResponse {
id,
streamer: Some(ClientId(from)),
accepted: accept,
offer,
message: String::new(),
},
)],
Request::Signal { id, peer, signal } => vec![(
peer.0,
StreamNotification::Signaling { id, peer: ClientId(from), json: signal.to_json() },
)],
Request::RemoveViewer { id, viewer, reason } => {
both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) })
}
}
}
async fn wait<T>(
rx: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> T {
timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(rx.recv().await.unwrap()) {
return t;
}
}
})
.await
.expect("timed out")
}
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake server.
#[tokio::test(flavor = "multi_thread")]
async fn stream_tasks_through_fake_server() {
let (events, mut rx) = broadcast::channel(4096);
let (frames, mut frames_rx) = broadcast::channel(4096);
let mut voices = Vec::new();
let mut handles = Vec::new();
for (i, clid) in CLIENTS.into_iter().enumerate() {
let (voice, voice_rx) = mpsc::unbounded_channel();
let config = PeerConfig::loopback();
let session = i as u64 + 1;
handles.push(StreamHandle::spawn(
session,
clid,
config,
voice,
events.clone(),
frames.clone(),
));
voices.push(voice_rx);
}
let handles = Arc::new(handles);
// The server: relays requests from one task as notifications to the others.
for (i, mut voice_rx) in voices.into_iter().enumerate() {
let handles = handles.clone();
tokio::spawn(async move {
while let Some(cmd) = voice_rx.recv().await {
if let VoiceCmd::Stream(request) = cmd {
for (to, n) in relay(CLIENTS[i], request) {
let index = CLIENTS.iter().position(|c| *c == to).unwrap();
handles[index].send(StreamInput::Notification(n));
}
}
}
});
}
let setup = StreamSetup { name: "t".into(), ..Default::default() };
handles[0].send(StreamInput::Start { setup, auto_accept: true });
// Live for the streamer and listed for the viewer, in either order.
let (mut sink, mut listed) = (None, false);
wait(&mut rx, |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
sink = Some(s);
}
Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1,
_ => {}
}
(sink.is_some() && listed).then_some(())
})
.await;
let sink = sink.unwrap();
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
})
.await;
// Frames from the sink reach the viewer's frame bus.
let feeder = tokio::spawn({
let sink = sink.clone();
async move {
let mut source = SyntheticSource::new(30, 2000, true);
let mut out = Vec::new();
while sink.is_live() {
source.poll_frames(Instant::now(), &mut out);
for f in out.drain(..) {
sink.send(f);
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
});
let (mut video, mut audio) = (0, 0);
timeout(Duration::from_secs(10), async {
while video < 10 || audio < 10 {
let f = frames_rx.recv().await.unwrap();
assert_eq!((f.session, f.stream_id.as_str()), (2, "s-1"));
match f.frame.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
}
}
})
.await
.expect("no frames");
assert!(sink.take_keyframe_request());
// Stopping ends the sink and tells the viewer.
handles[0].send(StreamInput::Stop);
wait(&mut rx, |e| match e {
Event::WatchState {
session: 2, state: WatchState::Ended(EndReason::Stopped), ..
} => Some(()),
_ => None,
})
.await;
assert!(!sink.is_live());
feeder.await.unwrap();
// Errors surface as events.
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::Error { session: 2, message } if message.contains("not watching") => Some(()),
_ => None,
})
.await;
handles[1].send(StreamInput::Shutdown("bye".into()));
}
}
+37 -3
View File
@@ -1,5 +1,6 @@
//! The voice source: a normal client connection.
use std::collections::HashMap;
use std::time::Duration;
use futures::prelude::*;
@@ -9,12 +10,13 @@ use tracing::{info, warn};
use tsc_model::{
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
};
use tsc_stream::{PeerConfig, Request, StreamNotification};
use tsclientlib::data;
use tsclientlib::events::Event as BookEvent;
use tsclientlib::prelude::*;
use tsclientlib::{
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageTarget, StreamItem,
Version,
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle, MessageTarget,
StreamItem, Version,
};
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
@@ -30,6 +32,8 @@ pub struct VoiceOptions {
pub channel: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
@@ -42,6 +46,7 @@ impl VoiceOptions {
server_password: None,
channel: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
@@ -53,6 +58,8 @@ pub(crate) enum VoiceCmd {
SetOutputMuted(bool),
/// An encoded voice packet from the audio thread.
Audio(OutPacket),
/// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`].
Stream(Request),
Disconnect,
}
@@ -60,6 +67,7 @@ pub(crate) enum VoiceEvent {
Connected {
name: String,
flavor: ServerFlavor,
own_client: u16,
},
Presence(Presence),
OwnChannel(ChannelId),
@@ -70,6 +78,8 @@ pub(crate) enum VoiceEvent {
client: u16,
talking: bool,
},
Stream(StreamNotification),
StreamRequestFailed(Request, String),
Disconnected(Option<String>),
}
@@ -192,7 +202,11 @@ async fn run_inner(
let state = con.get_state()?;
let flavor = ServerFlavor::from_version_string(&state.server.version);
info!(server = %state.server.name, ?flavor, "voice connected");
let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor });
let _ = events.send(VoiceEvent::Connected {
name: state.server.name.clone(),
flavor,
own_client: state.own_client.0,
});
}
// Subscribe to all channels to see everyone.
let cmd = con.get_state()?.server.set_subscribed(true);
@@ -202,6 +216,8 @@ async fn run_inner(
// Who is talking: last voice packet per client.
let mut talking: std::collections::HashMap<u16, Instant> = Default::default();
let mut tick = tokio::time::interval(Duration::from_millis(250));
// Stream commands waiting for the server's answer.
let mut stream_requests: HashMap<MessageHandle, Request> = HashMap::new();
loop {
let input = {
@@ -258,12 +274,27 @@ async fn run_inner(
}
let _ = events.send(VoiceEvent::Audio(packet));
}
StreamItem::MessageEvent(msg) => {
for n in StreamNotification::from_message(&msg) {
let _ = events.send(VoiceEvent::Stream(n));
}
}
StreamItem::MessageResult(handle, result) => {
if let (Some(request), Err(e)) = (stream_requests.remove(&handle), result) {
let _ =
events.send(VoiceEvent::StreamRequestFailed(request, e.to_string()));
}
}
StreamItem::DisconnectedTemporarily(reason) => {
warn!(?reason, "voice connection interrupted, reconnecting");
}
_ => {}
},
Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break,
Input::Cmd(Some(VoiceCmd::Stream(request))) => {
let handle = request.to_command().send_with_result(&mut con)?;
stream_requests.insert(handle, request);
}
Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?,
Input::Tick => {
talking.retain(|client, last| {
@@ -336,6 +367,9 @@ fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> {
VoiceCmd::Audio(packet) => {
con.send_audio(packet)?;
}
VoiceCmd::Stream(request) => {
request.to_command().send(con)?;
}
VoiceCmd::Disconnect => {}
}
Ok(())
+257
View File
@@ -0,0 +1,257 @@
//! Streams through the engine against the development servers
//! (dev/docker-compose.yml): one session streams synthetic frames, another
//! watches. Runs only with `TSC_LIVE=1`.
use std::time::{Duration, Instant};
use tokio::sync::broadcast::Receiver;
use tokio::time::timeout;
use tsc_core::stream::{
EndReason, FrameSource, LeaveReason, MediaKind, PeerConfig, StreamSetup, SyntheticSource,
ViewerState,
};
use tsc_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
fn live() -> bool {
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
}
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for<T>(
rx: &mut Receiver<Event>,
what: &str,
mut f: impl FnMut(&Event) -> Option<T>,
) -> T {
timeout(Duration::from_secs(20), async {
loop {
match rx.recv().await {
Ok(e) => {
if let Some(t) = f(&e) {
return t;
}
if let Event::Error { session, message } = e {
eprintln!("engine error (session {session}): {message}");
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("event bus closed: {e}"),
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
}
/// Wait until both `f` and `g` matched an event, in either order. Events of
/// the two sessions race, so waiting for them one after the other can drop one.
async fn wait_both<A, B>(
rx: &mut Receiver<Event>,
what: &str,
mut f: impl FnMut(&Event) -> Option<A>,
mut g: impl FnMut(&Event) -> Option<B>,
) -> (A, B) {
let (mut a, mut b) = (None, None);
wait_for(rx, what, |e| {
if a.is_none() {
a = f(e);
}
if b.is_none() {
b = g(e);
}
(a.is_some() && b.is_some()).then_some(())
})
.await;
(a.unwrap(), b.unwrap())
}
async fn connect(
engine: &Engine,
events: &mut Receiver<Event>,
session: u64,
addr: &str,
nick: &str,
) {
let mut options = VoiceOptions::new(addr, nick);
options.stream_peer = PeerConfig::loopback();
engine.send(Command::ConnectVoice { session, options: Box::new(options) });
wait_for(events, "voice connected", |e| match e {
Event::State { session: s, state }
if *s == session
&& state.voice == VoiceState::Connected
&& state.own_channel.is_some() =>
{
Some(())
}
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_stream_between_sessions() {
if !live() {
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let mut frames = engine.subscribe_frames();
let tag = std::process::id() % 10_000;
connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-streamer-{tag}")).await;
connect(&engine, &mut events, 2, "127.0.0.1:9988", &format!("e-viewer-{tag}")).await;
// Stream, asking for each viewer.
let setup = StreamSetup { name: format!("engine {tag}"), ..Default::default() };
engine.send(Command::StartStream { session: 1, setup, auto_accept: false });
// The viewer's list often updates before the streamer goes live, so wait
// for both at once and remember the latest list.
let mut live = None;
let mut listed = Vec::new();
let (id, sink) = wait_for(&mut events, "stream live and in the viewer's list", |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => {
live = Some((id.clone(), sink.clone()));
}
Event::StreamState { session: 1, state: StreamState::Ended(reason) } => {
panic!("stream ended: {reason:?}")
}
Event::StreamsChanged { session: 2, streams } => {
listed = streams.iter().map(|s| s.id.clone()).collect();
}
_ => {}
}
live.clone().filter(|(id, _)| listed.contains(id))
})
.await;
// Synthetic frames through the sink, as an encoder would send them.
let feeder = tokio::spawn({
let sink = sink.clone();
async move {
let mut source = SyntheticSource::new(30, 3000, true);
let mut out = Vec::new();
while sink.is_live() {
source.poll_frames(Instant::now(), &mut out);
for frame in out.drain(..) {
sink.send(frame);
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
});
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
let viewer = wait_for(&mut events, "viewer request", |e| match e {
Event::StreamViewerRequest { session: 1, viewer, .. } => Some(*viewer),
_ => None,
})
.await;
engine.send(Command::AcceptViewer { session: 1, viewer, accept: true });
wait_both(
&mut events,
"watching and viewer connected",
|e| match e {
Event::WatchState { session: 2, stream_id, state: WatchState::Connected }
if *stream_id == id =>
{
Some(())
}
Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => {
panic!("watching ended: {reason:?}")
}
_ => None,
},
|e| match e {
Event::StreamViewers { session: 1, viewers }
if viewers
.iter()
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
{
Some(())
}
_ => None,
},
)
.await;
assert!(sink.take_keyframe_request(), "a new viewer asks for a keyframe");
let (mut video, mut audio) = (0, 0);
let _ = timeout(Duration::from_secs(10), async {
while video < 60 || audio < 60 {
match frames.recv().await {
Ok(f) if f.session == 2 && f.stream_id == id => match f.frame.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
},
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(_) => break,
}
}
})
.await;
assert!(video >= 60 && audio >= 60, "viewer got {video} video / {audio} audio frames");
// The streamer removes the viewer, then ends the stream.
engine.send(Command::KickViewer { session: 1, viewer });
wait_for(&mut events, "kicked", |e| match e {
Event::WatchState {
session: 2,
state: WatchState::Ended(EndReason::Removed(Some(LeaveReason::Kicked))),
..
} => Some(()),
_ => None,
})
.await;
engine.send(Command::StopStream { session: 1 });
wait_both(
&mut events,
"stream ended and gone from the viewer's list",
|e| match e {
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) } => {
Some(())
}
_ => None,
},
|e| match e {
Event::StreamsChanged { session: 2, streams } if streams.iter().all(|s| s.id != id) => {
Some(())
}
_ => None,
},
)
.await;
assert!(!sink.send(tsc_core::stream::EncodedFrame {
kind: MediaKind::Audio,
time: tsc_core::stream::MediaTime::from_90khz(0),
data: vec![0].into(),
}));
feeder.await.unwrap();
engine.send(Command::CloseSession { session: 1 });
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_has_no_streams() {
if !live() {
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let nick = format!("e-nostream-{}", std::process::id() % 10_000);
connect(&engine, &mut events, 1, "127.0.0.1:9987", &nick).await;
engine.send(Command::StartStream {
session: 1,
setup: StreamSetup::default(),
auto_accept: true,
});
let message = wait_for(&mut events, "error", |e| match e {
Event::Error { session: 1, message } => Some(message.clone()),
_ => None,
})
.await;
assert!(message.contains("TeamSpeak 6"), "{message}");
engine.send(Command::CloseSession { session: 1 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
+49
View File
@@ -0,0 +1,49 @@
[package]
name = "tsc-platform"
version = "0.1.0"
description = "Desktop integration: global push-to-talk hotkeys, notifications and app directories."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["portal", "x11"]
# Wayland global shortcuts through xdg-desktop-portal (Linux).
portal = ["dep:ashpd", "dep:futures-util"]
# X11 global hotkeys through XInput2 raw events (Linux).
x11 = ["dep:x11rb"]
[dependencies]
dirs = "6"
serde = { version = "1.0.228", features = ["derive"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
[target.'cfg(windows)'.dependencies]
notify-rust = { version = "4.18", default-features = false }
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_System_LibraryLoader",
"Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
[lints]
workspace = true
+456
View File
@@ -0,0 +1,456 @@
//! Keys and key combinations, with their X11 keysyms, Windows virtual-key
//! codes and xdg "shortcuts" names.
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::Error;
macro_rules! named_keys {
($($variant:ident $name:literal $keysym:literal $vk:literal $xdg:literal;)*) => {
/// Keys that are not letters, digits, function or keypad digit keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NamedKey {
$($variant,)*
}
impl NamedKey {
pub const ALL: &[NamedKey] = &[$(NamedKey::$variant,)*];
pub fn name(self) -> &'static str {
match self {
$(NamedKey::$variant => $name,)*
}
}
fn keysym(self) -> u32 {
match self {
$(NamedKey::$variant => $keysym,)*
}
}
fn vk(self) -> u16 {
match self {
$(NamedKey::$variant => $vk,)*
}
}
fn xdg(self) -> &'static str {
match self {
$(NamedKey::$variant => $xdg,)*
}
}
}
};
}
// Mouse buttons have no keysym (0) and no xdg name (""); their codes are
// handled by the backends.
named_keys! {
Space "Space" 0x0020 0x20 "space";
Tab "Tab" 0xff09 0x09 "Tab";
CapsLock "CapsLock" 0xffe5 0x14 "Caps_Lock";
Backquote "Backquote" 0x0060 0xc0 "grave";
Minus "Minus" 0x002d 0xbd "minus";
Equal "Equal" 0x003d 0xbb "equal";
BracketLeft "BracketLeft" 0x005b 0xdb "bracketleft";
BracketRight "BracketRight" 0x005d 0xdd "bracketright";
Backslash "Backslash" 0x005c 0xdc "backslash";
Semicolon "Semicolon" 0x003b 0xba "semicolon";
Quote "Quote" 0x0027 0xde "apostrophe";
Comma "Comma" 0x002c 0xbc "comma";
Period "Period" 0x002e 0xbe "period";
Slash "Slash" 0x002f 0xbf "slash";
Enter "Enter" 0xff0d 0x0d "Return";
Escape "Escape" 0xff1b 0x1b "Escape";
Backspace "Backspace" 0xff08 0x08 "BackSpace";
Insert "Insert" 0xff63 0x2d "Insert";
Delete "Delete" 0xffff 0x2e "Delete";
Home "Home" 0xff50 0x24 "Home";
End "End" 0xff57 0x23 "End";
PageUp "PageUp" 0xff55 0x21 "Prior";
PageDown "PageDown" 0xff56 0x22 "Next";
Left "Left" 0xff51 0x25 "Left";
Up "Up" 0xff52 0x26 "Up";
Right "Right" 0xff53 0x27 "Right";
Down "Down" 0xff54 0x28 "Down";
Pause "Pause" 0xff13 0x13 "Pause";
ScrollLock "ScrollLock" 0xff14 0x91 "Scroll_Lock";
PrintScreen "PrintScreen" 0xff61 0x2c "Print";
NumLock "NumLock" 0xff7f 0x90 "Num_Lock";
NumpadAdd "NumpadAdd" 0xffab 0x6b "KP_Add";
NumpadSubtract "NumpadSubtract" 0xffad 0x6d "KP_Subtract";
NumpadMultiply "NumpadMultiply" 0xffaa 0x6a "KP_Multiply";
NumpadDivide "NumpadDivide" 0xffaf 0x6f "KP_Divide";
NumpadDecimal "NumpadDecimal" 0xffae 0x6e "KP_Decimal";
// Windows reports it as Enter with the extended flag.
NumpadEnter "NumpadEnter" 0xff8d 0x0d "KP_Enter";
Menu "Menu" 0xff67 0x5d "Menu";
LeftCtrl "LeftCtrl" 0xffe3 0xa2 "Control_L";
RightCtrl "RightCtrl" 0xffe4 0xa3 "Control_R";
LeftShift "LeftShift" 0xffe1 0xa0 "Shift_L";
RightShift "RightShift" 0xffe2 0xa1 "Shift_R";
LeftAlt "LeftAlt" 0xffe9 0xa4 "Alt_L";
RightAlt "RightAlt" 0xffea 0xa5 "Alt_R";
LeftSuper "LeftSuper" 0xffeb 0x5b "Super_L";
RightSuper "RightSuper" 0xffec 0x5c "Super_R";
MouseMiddle "MouseMiddle" 0 0x04 "";
MouseBack "MouseBack" 0 0x05 "";
MouseForward "MouseForward" 0 0x06 "";
}
/// X11 keysym of AltGr on most layouts, sitting on the right Alt key.
const XK_ISO_LEVEL3_SHIFT: u32 = 0xfe03;
/// A physical key (or mouse side button) as a hotkey trigger.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
/// `'A'..='Z'`.
Letter(char),
/// 0 to 9 on the main keyboard.
Digit(u8),
/// F1 to F24.
F(u8),
/// 0 to 9 on the keypad.
Numpad(u8),
Named(NamedKey),
}
/// Which modifier a key is, if it is one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModifierKind {
Ctrl,
Shift,
Alt,
Super,
}
impl Key {
fn validate(self) -> Result<Self, Error> {
let ok = match self {
Key::Letter(c) => c.is_ascii_uppercase(),
Key::Digit(d) | Key::Numpad(d) => d <= 9,
Key::F(n) => (1..=24).contains(&n),
Key::Named(_) => true,
};
if ok { Ok(self) } else { Err(Error::InvalidHotkey(format!("{self:?}"))) }
}
pub fn is_mouse(self) -> bool {
matches!(
self,
Key::Named(NamedKey::MouseMiddle | NamedKey::MouseBack | NamedKey::MouseForward)
)
}
#[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))]
pub(crate) fn modifier(self) -> Option<ModifierKind> {
match self {
Key::Named(NamedKey::LeftCtrl | NamedKey::RightCtrl) => Some(ModifierKind::Ctrl),
Key::Named(NamedKey::LeftShift | NamedKey::RightShift) => Some(ModifierKind::Shift),
Key::Named(NamedKey::LeftAlt | NamedKey::RightAlt) => Some(ModifierKind::Alt),
Key::Named(NamedKey::LeftSuper | NamedKey::RightSuper) => Some(ModifierKind::Super),
_ => None,
}
}
/// X11 keysym (for letters the lowercase one). 0 for mouse buttons.
pub fn x11_keysym(self) -> u32 {
match self {
Key::Letter(c) => c.to_ascii_lowercase() as u32,
Key::Digit(d) => 0x30 + d as u32,
Key::F(n) => 0xffbe + n as u32 - 1,
Key::Numpad(d) => 0xffb0 + d as u32,
Key::Named(k) => k.keysym(),
}
}
/// The key an X11 keysym belongs to (any shift level).
pub fn from_x11_keysym(keysym: u32) -> Option<Key> {
match keysym {
0x61..=0x7a => Some(Key::Letter((keysym as u8 - 0x20) as char)),
0x41..=0x5a => Some(Key::Letter(keysym as u8 as char)),
0x30..=0x39 => Some(Key::Digit((keysym - 0x30) as u8)),
0xffbe..=0xffd5 => Some(Key::F((keysym - 0xffbe + 1) as u8)),
0xffb0..=0xffb9 => Some(Key::Numpad((keysym - 0xffb0) as u8)),
XK_ISO_LEVEL3_SHIFT => Some(Key::Named(NamedKey::RightAlt)),
0 => None,
_ => NamedKey::ALL.iter().find(|k| k.keysym() == keysym).map(|&k| Key::Named(k)),
}
}
/// Windows virtual-key code. Mouse buttons use VK_MBUTTON/VK_XBUTTON1/2.
pub fn windows_vk(self) -> u16 {
match self {
Key::Letter(c) => c as u16,
Key::Digit(d) => 0x30 + d as u16,
Key::F(n) => 0x70 + n as u16 - 1,
Key::Numpad(d) => 0x60 + d as u16,
Key::Named(k) => k.vk(),
}
}
/// The key for a Windows virtual-key code; `extended` is the
/// low-level hook's extended-key flag (tells keypad Enter apart).
pub fn from_windows_vk(vk: u16, extended: bool) -> Option<Key> {
match vk {
0x0d if extended => Some(Key::Named(NamedKey::NumpadEnter)),
0x41..=0x5a => Some(Key::Letter(vk as u8 as char)),
0x30..=0x39 => Some(Key::Digit((vk - 0x30) as u8)),
0x70..=0x87 => Some(Key::F((vk - 0x70 + 1) as u8)),
0x60..=0x69 => Some(Key::Numpad((vk - 0x60) as u8)),
// Generic Ctrl/Shift/Alt (never sent to low-level hooks, but cheap).
0x10 => Some(Key::Named(NamedKey::LeftShift)),
0x11 => Some(Key::Named(NamedKey::LeftCtrl)),
0x12 => Some(Key::Named(NamedKey::LeftAlt)),
_ => NamedKey::ALL
.iter()
.find(|k| k.vk() == vk && **k != NamedKey::NumpadEnter)
.map(|&k| Key::Named(k)),
}
}
/// Keysym name as used by the xdg "shortcuts" specification (portal
/// preferred triggers). `None` for mouse buttons.
pub fn xdg_name(self) -> Option<String> {
let name = match self {
Key::Letter(c) => c.to_ascii_lowercase().to_string(),
Key::Digit(d) => d.to_string(),
Key::F(n) => format!("F{n}"),
Key::Numpad(d) => format!("KP_{d}"),
Key::Named(k) => k.xdg().to_string(),
};
(!name.is_empty()).then_some(name)
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::Letter(c) => write!(f, "{c}"),
Key::Digit(d) => write!(f, "{d}"),
Key::F(n) => write!(f, "F{n}"),
Key::Numpad(d) => write!(f, "Numpad{d}"),
Key::Named(k) => f.write_str(k.name()),
}
}
}
impl FromStr for Key {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidHotkey(s.to_string());
let key = if s.len() == 1 {
let c = s.chars().next().ok_or_else(invalid)?;
match c {
'a'..='z' | 'A'..='Z' => Key::Letter(c.to_ascii_uppercase()),
'0'..='9' => Key::Digit(c as u8 - b'0'),
_ => return Err(invalid()),
}
} else if let Some(d) = s.strip_prefix("Numpad").and_then(|d| d.parse().ok()) {
Key::Numpad(d)
} else if let Some(n) = s.strip_prefix(['F', 'f']).and_then(|n| n.parse().ok()) {
Key::F(n)
} else {
let named = NamedKey::ALL.iter().find(|k| k.name().eq_ignore_ascii_case(s));
Key::Named(*named.ok_or_else(invalid)?)
};
key.validate().map_err(|_| invalid())
}
}
/// Modifiers that must be held with a hotkey's key. Either side counts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Modifiers {
pub ctrl: bool,
pub shift: bool,
pub alt: bool,
/// The Windows / Command / "logo" key.
pub logo: bool,
}
impl Modifiers {
pub const NONE: Modifiers = Modifiers { ctrl: false, shift: false, alt: false, logo: false };
/// Every modifier in `self` is also in `held`.
pub fn is_subset_of(self, held: Modifiers) -> bool {
(!self.ctrl || held.ctrl)
&& (!self.shift || held.shift)
&& (!self.alt || held.alt)
&& (!self.logo || held.logo)
}
pub(crate) fn add(&mut self, kind: ModifierKind) {
match kind {
ModifierKind::Ctrl => self.ctrl = true,
ModifierKind::Shift => self.shift = true,
ModifierKind::Alt => self.alt = true,
ModifierKind::Super => self.logo = true,
}
}
fn names(self) -> impl Iterator<Item = (&'static str, &'static str)> {
[
(self.ctrl, "Ctrl", "CTRL"),
(self.shift, "Shift", "SHIFT"),
(self.alt, "Alt", "ALT"),
(self.logo, "Super", "LOGO"),
]
.into_iter()
.filter(|(on, ..)| *on)
.map(|(_, name, xdg)| (name, xdg))
}
}
/// A key plus required modifiers, e.g. `Ctrl+Shift+T`, `F13`, `RightCtrl`
/// or `MouseBack`.
///
/// Fires when the key goes down while at least these modifiers are held
/// (extra modifiers do not prevent it, so push-to-talk keeps working while
/// typing with Shift), and releases when the key goes up. Serialized as
/// that string.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Hotkey {
pub modifiers: Modifiers,
pub key: Key,
}
impl Hotkey {
pub fn new(key: Key) -> Self {
Self { modifiers: Modifiers::NONE, key }
}
pub fn with(mut self, modifiers: Modifiers) -> Self {
self.modifiers = modifiers;
self
}
/// Trigger in the xdg "shortcuts" format (`CTRL+SHIFT+t`), as the
/// portal's preferred trigger. `None` for mouse buttons.
pub fn xdg_trigger(&self) -> Option<String> {
let key = self.key.xdg_name()?;
let mut parts: Vec<String> = self.modifiers.names().map(|(_, x)| x.to_string()).collect();
parts.push(key);
Some(parts.join("+"))
}
}
impl fmt::Display for Hotkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (name, _) in self.modifiers.names() {
write!(f, "{name}+")?;
}
write!(f, "{}", self.key)
}
}
impl FromStr for Hotkey {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let mut parts: Vec<&str> = s.split('+').map(str::trim).collect();
// "Ctrl++" is not supported; Plus is not a key here.
let key = parts.pop().filter(|k| !k.is_empty());
let key: Key = key.ok_or_else(|| Error::InvalidHotkey(s.to_string()))?.parse()?;
let mut modifiers = Modifiers::NONE;
for part in parts {
let kind = match part.to_ascii_lowercase().as_str() {
"ctrl" | "control" => ModifierKind::Ctrl,
"shift" => ModifierKind::Shift,
"alt" => ModifierKind::Alt,
"super" | "logo" | "win" | "meta" => ModifierKind::Super,
_ => return Err(Error::InvalidHotkey(s.to_string())),
};
modifiers.add(kind);
}
Ok(Hotkey { modifiers, key })
}
}
impl TryFrom<String> for Hotkey {
type Error = Error;
fn try_from(s: String) -> Result<Self, Error> {
s.parse()
}
}
impl From<Hotkey> for String {
fn from(h: Hotkey) -> String {
h.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_and_display() {
for s in
["Ctrl+Shift+T", "F13", "RightCtrl", "MouseBack", "Alt+Numpad5", "Super+Space", "7"]
{
let h: Hotkey = s.parse().unwrap();
assert_eq!(h.to_string(), s);
}
let h: Hotkey = "control + shift + t".parse().unwrap();
assert_eq!(h.to_string(), "Ctrl+Shift+T");
assert_eq!("win+f1".parse::<Hotkey>().unwrap().to_string(), "Super+F1");
for bad in ["", "Ctrl+", "Hyper+A", "F25", "F0", "Numpad10", "NoSuchKey", "Ctrl+Shift"] {
assert!(bad.parse::<Hotkey>().is_err(), "{bad} should not parse");
}
}
#[test]
fn serde_as_string() {
let h: Hotkey = "Ctrl+F13".parse().unwrap();
let json = serde_json::to_string(&h).unwrap();
assert_eq!(json, r#""Ctrl+F13""#);
assert_eq!(serde_json::from_str::<Hotkey>(&json).unwrap(), h);
assert!(serde_json::from_str::<Hotkey>(r#""Ctrl+Nope""#).is_err());
}
#[test]
fn platform_codes_roundtrip() {
let mut keys: Vec<Key> = NamedKey::ALL.iter().map(|&k| Key::Named(k)).collect();
keys.extend(('A'..='Z').map(Key::Letter));
keys.extend((0..=9).map(Key::Digit));
keys.extend((0..=9).map(Key::Numpad));
keys.extend((1..=24).map(Key::F));
for key in keys {
let extended = key == Key::Named(NamedKey::NumpadEnter);
assert_eq!(Key::from_windows_vk(key.windows_vk(), extended), Some(key), "{key}");
if !key.is_mouse() {
assert_eq!(Key::from_x11_keysym(key.x11_keysym()), Some(key), "{key}");
assert!(key.xdg_name().is_some());
}
assert_eq!(key.to_string().parse::<Key>().unwrap(), key);
}
// Shifted letters and AltGr.
assert_eq!(Key::from_x11_keysym(0x41), Some(Key::Letter('A')));
assert_eq!(Key::from_x11_keysym(0xfe03), Some(Key::Named(NamedKey::RightAlt)));
assert_eq!(Key::from_x11_keysym(0x1234), None);
}
#[test]
fn xdg_triggers() {
let h: Hotkey = "Ctrl+Shift+T".parse().unwrap();
assert_eq!(h.xdg_trigger().as_deref(), Some("CTRL+SHIFT+t"));
let h: Hotkey = "Super+PageUp".parse().unwrap();
assert_eq!(h.xdg_trigger().as_deref(), Some("LOGO+Prior"));
assert_eq!("MouseBack".parse::<Hotkey>().unwrap().xdg_trigger(), None);
}
#[test]
fn modifier_subsets() {
let ctrl = Modifiers { ctrl: true, ..Modifiers::NONE };
let ctrl_shift = Modifiers { shift: true, ..ctrl };
assert!(Modifiers::NONE.is_subset_of(ctrl));
assert!(ctrl.is_subset_of(ctrl_shift));
assert!(!ctrl_shift.is_subset_of(ctrl));
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Global hotkeys with press and release events, for push-to-talk.
//!
//! Backends, picked by [`HotkeyManager::new`]:
//!
//! - **Portal** (Wayland): the xdg-desktop-portal `GlobalShortcuts`
//! interface. The compositor owns the binding: our [`Hotkey`] is only the
//! preferred trigger, the user confirms or changes it in a system dialog,
//! and the portal reports `Activated` / `Deactivated`. Needs KDE Plasma
//! 5.27+, GNOME 48+ or another desktop implementing it.
//! - **X11**: XInput2 raw key and button events on the root window. They are
//! delivered whatever window has focus and nothing is grabbed, so the key
//! still reaches the focused application. Under Wayland this only sees keys
//! while an X11 (XWayland) window has focus.
//! - **Windows**: a low-level keyboard and mouse hook (`WH_KEYBOARD_LL`,
//! `WH_MOUSE_LL`) on its own thread. `RegisterHotKey` would only report
//! presses and swallow the key.
// Builds without a backend (other platforms, or Linux without both
// features) compile, but have nothing to register with.
#![cfg_attr(
not(any(
windows,
all(unix, not(target_os = "macos"), any(feature = "portal", feature = "x11"))
)),
allow(unused_variables, unreachable_code)
)]
mod key;
#[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))]
mod tracker;
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
mod portal;
#[cfg(windows)]
mod windows;
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
mod x11;
pub use key::{Hotkey, Key, Modifiers, NamedKey};
use tokio::sync::mpsc;
use crate::{Error, Result};
/// A registered hotkey went down or up.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HotkeyEvent {
Pressed,
Released,
}
/// Events of one registration; dropping it unregisters the hotkey on the
/// next key event (X11, Windows) or on [`HotkeyManager::unregister`].
pub type HotkeyEvents = mpsc::UnboundedReceiver<HotkeyEvent>;
/// How hotkeys are captured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackendKind {
Portal,
X11,
WindowsHook,
}
enum Backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Portal(portal::PortalBackend),
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
X11(x11::X11Backend),
#[cfg(windows)]
Windows(windows::HookBackend),
/// Keeps matches exhaustive on platforms without any backend.
#[allow(dead_code)]
None(std::convert::Infallible),
}
/// Registers global hotkeys. See the [module docs](self) for the backends.
pub struct HotkeyManager {
backend: Backend,
}
impl HotkeyManager {
/// The best backend for this desktop session: the portal on Wayland
/// (falling back to X11 when the desktop does not offer it), X11 on X11,
/// the hook on Windows. Must be called within a Tokio runtime (the portal
/// listens for its signals on a task).
pub async fn new() -> Result<Self> {
let mut errors = Vec::new();
for kind in preferred_backends() {
match Self::with_backend(kind).await {
Ok(manager) => return Ok(manager),
Err(e) => {
tracing::debug!(?kind, %e, "hotkey backend unavailable");
errors.push(format!("{kind:?}: {e}"));
}
}
}
Err(Error::Unsupported(if errors.is_empty() {
"no hotkey backend for this platform".into()
} else {
errors.join("; ")
}))
}
/// Use a specific backend.
pub async fn with_backend(kind: BackendKind) -> Result<Self> {
let backend = match kind {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
BackendKind::Portal => Backend::Portal(portal::PortalBackend::new().await?),
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
BackendKind::X11 => Backend::X11(x11::X11Backend::connect(None)?),
#[cfg(windows)]
BackendKind::WindowsHook => Backend::Windows(windows::HookBackend::start()?),
#[allow(unreachable_patterns)]
_ => return Err(Error::Unsupported(format!("{kind:?} is not available in this build"))),
};
Ok(Self { backend })
}
/// X11 on a specific display (e.g. `":1"`), mainly for tests.
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
pub fn x11(display: &str) -> Result<Self> {
Ok(Self { backend: Backend::X11(x11::X11Backend::connect(Some(display))?) })
}
pub fn backend(&self) -> BackendKind {
match &self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(_) => BackendKind::Portal,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(_) => BackendKind::X11,
#[cfg(windows)]
Backend::Windows(_) => BackendKind::WindowsHook,
Backend::None(never) => match *never {},
}
}
/// Register `hotkey` under a stable `id` (the portal remembers the
/// user's choice by it); `description` is shown in the portal's dialog.
/// Registering an id again replaces it.
///
/// With the portal this may show a dialog and waits for the user.
pub async fn register(
&mut self,
id: &str,
description: &str,
hotkey: Hotkey,
) -> Result<HotkeyEvents> {
let _ = description;
match &mut self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.register(id, description, hotkey).await,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(x) => Ok(x.register(id, hotkey)),
#[cfg(windows)]
Backend::Windows(w) => Ok(w.register(id, hotkey)),
Backend::None(never) => match *never {},
}
}
pub async fn unregister(&mut self, id: &str) -> Result<()> {
match &mut self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.unregister(id).await,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(x) => {
x.unregister(id);
Ok(())
}
#[cfg(windows)]
Backend::Windows(w) => {
w.unregister(id);
Ok(())
}
Backend::None(never) => match *never {},
}
}
/// What actually triggers `id`, as the desktop describes it (portal
/// only: the user may have picked another key). Other backends return
/// `None`; the registered [`Hotkey`] is the trigger.
pub fn trigger_description(&self, id: &str) -> Option<String> {
match &self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.trigger_description(id),
#[allow(unreachable_patterns)]
_ => {
let _ = id;
None
}
}
}
}
/// Backends to try, best first.
fn preferred_backends() -> Vec<BackendKind> {
if cfg!(windows) {
return vec![BackendKind::WindowsHook];
}
if !cfg!(all(unix, not(target_os = "macos"))) {
return Vec::new();
}
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland");
let x11 = std::env::var_os("DISPLAY").is_some();
let mut kinds = Vec::new();
if wayland {
kinds.push(BackendKind::Portal);
}
if x11 {
kinds.push(BackendKind::X11);
}
if !wayland {
// E.g. a portal without a Wayland session, or no display variables.
kinds.push(BackendKind::Portal);
}
kinds
}
+162
View File
@@ -0,0 +1,162 @@
//! Wayland backend: xdg-desktop-portal `GlobalShortcuts`.
//!
//! The portal binds all shortcuts of a session at once, so every change
//! closes the session and binds the full list in a new one. Shortcuts the
//! user already confirmed are remembered by id and do not ask again.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use ashpd::desktop::global_shortcuts::{
Activated, BindShortcutsOptions, Deactivated, GlobalShortcuts, NewShortcut,
};
use ashpd::desktop::{CreateSessionOptions, Session};
use futures_util::{Stream, StreamExt};
use tokio::sync::mpsc;
use tracing::debug;
use super::{Hotkey, HotkeyEvent, HotkeyEvents};
use crate::{APP_ID, Error, Result};
type Senders = Arc<Mutex<HashMap<String, mpsc::UnboundedSender<HotkeyEvent>>>>;
fn portal_error(e: ashpd::Error) -> Error {
Error::Backend(format!("portal: {e}"))
}
struct Shortcut {
id: String,
description: String,
hotkey: Hotkey,
}
pub(crate) struct PortalBackend {
portal: GlobalShortcuts,
session: Option<Session<GlobalShortcuts>>,
shortcuts: Vec<Shortcut>,
senders: Senders,
triggers: HashMap<String, String>,
listener: tokio::task::JoinHandle<()>,
}
impl PortalBackend {
pub async fn new() -> Result<Self> {
// Outside a sandbox the portal learns our app id this way (newer
// portals need it for global shortcuts); older ones lack the call.
if let Ok(app_id) = APP_ID.parse()
&& let Err(e) = ashpd::register_host_app(app_id).await
{
debug!(%e, "portal host app registration");
}
let portal = GlobalShortcuts::new().await.map_err(portal_error)?;
let activated = portal.receive_activated().await.map_err(portal_error)?;
let deactivated = portal.receive_deactivated().await.map_err(portal_error)?;
let senders = Senders::default();
let listener = tokio::spawn(listen(activated, deactivated, senders.clone()));
Ok(Self {
portal,
session: None,
shortcuts: Vec::new(),
senders,
triggers: HashMap::new(),
listener,
})
}
fn senders(
&self,
) -> std::sync::MutexGuard<'_, HashMap<String, mpsc::UnboundedSender<HotkeyEvent>>> {
self.senders.lock().unwrap_or_else(PoisonError::into_inner)
}
pub async fn register(
&mut self,
id: &str,
description: &str,
hotkey: Hotkey,
) -> Result<HotkeyEvents> {
if hotkey.key.is_mouse() {
return Err(Error::Unsupported("the portal does not bind mouse buttons".into()));
}
self.shortcuts.retain(|s| s.id != id);
self.shortcuts.push(Shortcut { id: id.into(), description: description.into(), hotkey });
if let Err(e) = self.rebind().await {
self.shortcuts.retain(|s| s.id != id);
return Err(e);
}
let (tx, rx) = mpsc::unbounded_channel();
self.senders().insert(id.into(), tx);
Ok(rx)
}
pub async fn unregister(&mut self, id: &str) -> Result<()> {
self.senders().remove(id);
self.shortcuts.retain(|s| s.id != id);
self.rebind().await
}
pub fn trigger_description(&self, id: &str) -> Option<String> {
self.triggers.get(id).cloned()
}
async fn rebind(&mut self) -> Result<()> {
if let Some(old) = self.session.take() {
let _ = old.close().await;
}
self.triggers.clear();
if self.shortcuts.is_empty() {
return Ok(());
}
let session = self
.portal
.create_session(CreateSessionOptions::default())
.await
.map_err(portal_error)?;
let new: Vec<NewShortcut> = self
.shortcuts
.iter()
.map(|s| {
let trigger = s.hotkey.xdg_trigger();
NewShortcut::new(&s.id, &s.description).preferred_trigger(trigger.as_deref())
})
.collect();
let request = self
.portal
.bind_shortcuts(&session, &new, None, BindShortcutsOptions::default())
.await
.map_err(portal_error)?;
let bound = request.response().map_err(portal_error)?;
self.triggers = bound
.shortcuts()
.iter()
.map(|s| (s.id().to_string(), s.trigger_description().to_string()))
.collect();
self.session = Some(session);
Ok(())
}
}
impl Drop for PortalBackend {
fn drop(&mut self) {
// Closing the session needs an await; the portal closes it when our
// D-Bus connection goes away.
self.listener.abort();
}
}
/// Forward `Activated` / `Deactivated` to the registration with that id.
async fn listen(
activated: impl Stream<Item = Activated>,
deactivated: impl Stream<Item = Deactivated>,
senders: Senders,
) {
let activated = activated.map(|a| (a.shortcut_id().to_string(), HotkeyEvent::Pressed));
let deactivated = deactivated.map(|d| (d.shortcut_id().to_string(), HotkeyEvent::Released));
let mut events = std::pin::pin!(futures_util::stream::select(activated, deactivated));
while let Some((id, event)) = events.next().await {
let senders = senders.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(tx) = senders.get(&id) {
let _ = tx.send(event);
}
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Turns raw key presses and releases into hotkey events. Used by the
//! backends that see every key (X11 raw events, the Windows keyboard hook);
//! the portal does its own matching.
use std::collections::HashSet;
use tokio::sync::mpsc;
use super::{Hotkey, HotkeyEvent, HotkeyEvents, Key, Modifiers};
struct Registration {
id: String,
hotkey: Hotkey,
events: mpsc::UnboundedSender<HotkeyEvent>,
active: bool,
}
#[derive(Default)]
pub(crate) struct Tracker {
registrations: Vec<Registration>,
held: HashSet<Key>,
}
impl Tracker {
/// Register (or replace) `id`.
pub fn add(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.remove(id);
let (tx, rx) = mpsc::unbounded_channel();
self.registrations.push(Registration { id: id.into(), hotkey, events: tx, active: false });
rx
}
pub fn remove(&mut self, id: &str) -> bool {
let before = self.registrations.len();
self.registrations.retain(|r| r.id != id);
self.registrations.len() != before
}
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.registrations.is_empty()
}
fn held_modifiers(&self) -> Modifiers {
let mut m = Modifiers::NONE;
for kind in self.held.iter().filter_map(|k| k.modifier()) {
m.add(kind);
}
m
}
/// A key went down (`pressed`) or up. Auto-repeat presses are ignored.
pub fn key(&mut self, key: Key, pressed: bool) {
if pressed {
self.held.insert(key);
let held = self.held_modifiers();
for r in &mut self.registrations {
if !r.active && r.hotkey.key == key && r.hotkey.modifiers.is_subset_of(held) {
r.active = true;
let _ = r.events.send(HotkeyEvent::Pressed);
}
}
} else {
self.held.remove(&key);
for r in &mut self.registrations {
if r.active && r.hotkey.key == key {
r.active = false;
let _ = r.events.send(HotkeyEvent::Released);
}
}
}
// Receivers that were dropped unregister themselves.
self.registrations.retain(|r| !r.events.is_closed());
}
/// Release everything (e.g. the keyboard state was lost).
pub fn release_all(&mut self) {
self.held.clear();
for r in &mut self.registrations {
if r.active {
r.active = false;
let _ = r.events.send(HotkeyEvent::Released);
}
}
}
}
#[cfg(test)]
mod tests {
use super::super::NamedKey;
use super::*;
fn drain(rx: &mut HotkeyEvents) -> Vec<HotkeyEvent> {
std::iter::from_fn(|| rx.try_recv().ok()).collect()
}
#[test]
fn press_release_with_modifiers() {
use HotkeyEvent::*;
let mut t = Tracker::default();
let mut ptt = t.add("ptt", "Ctrl+F13".parse().unwrap());
let mut plain = t.add("mute", "M".parse().unwrap());
let ctrl = Key::Named(NamedKey::RightCtrl);
// Without Ctrl nothing happens for Ctrl+F13.
t.key(Key::F(13), true);
t.key(Key::F(13), false);
assert!(drain(&mut ptt).is_empty());
t.key(ctrl, true);
t.key(Key::F(13), true);
t.key(Key::F(13), true); // auto-repeat
// Letting go of Ctrl first keeps it pressed until F13 is released.
t.key(ctrl, false);
assert_eq!(drain(&mut ptt), vec![Pressed]);
t.key(Key::F(13), false);
assert_eq!(drain(&mut ptt), vec![Released]);
// Extra modifiers do not block a plain hotkey.
t.key(Key::Named(NamedKey::LeftShift), true);
t.key(Key::Letter('M'), true);
t.key(Key::Letter('M'), false);
assert_eq!(drain(&mut plain), vec![Pressed, Released]);
}
#[test]
fn modifier_alone_and_unregister() {
use HotkeyEvent::*;
let mut t = Tracker::default();
let mut rx = t.add("ptt", "RightCtrl".parse().unwrap());
let key = Key::Named(NamedKey::RightCtrl);
t.key(key, true);
t.release_all();
assert_eq!(drain(&mut rx), vec![Pressed, Released]);
assert!(t.remove("ptt"));
assert!(!t.remove("ptt"));
t.key(key, true);
assert!(rx.try_recv().is_err());
// A dropped receiver unregisters on the next key.
let rx = t.add("x", "A".parse().unwrap());
drop(rx);
t.key(Key::Letter('B'), true);
assert!(t.is_empty());
}
}
+179
View File
@@ -0,0 +1,179 @@
//! Windows backend: low-level keyboard and mouse hooks.
//!
//! `RegisterHotKey` only reports presses and takes the key away from other
//! applications, so push-to-talk uses `WH_KEYBOARD_LL` / `WH_MOUSE_LL`
//! instead. The hooks run on a dedicated thread with a message loop (Windows
//! calls low-level hooks on the installing thread) and always pass events
//! on. Hook procedures get no user data, so the thread's tracker lives in a
//! thread local.
//!
//! This is the crate's only unsafe code: the Win32 calls and reading the
//! hook structs Windows hands to the callbacks.
#![allow(unsafe_code)]
use std::cell::RefCell;
use std::sync::{Arc, Mutex, PoisonError, mpsc as std_mpsc};
use std::thread;
use windows::Win32::Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Threading::GetCurrentThreadId;
use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, DispatchMessageW, GetMessageW, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT,
LLKHF_EXTENDED, MSG, MSLLHOOKSTRUCT, PostThreadMessageW, SetWindowsHookExW, TranslateMessage,
UnhookWindowsHookEx, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP, WM_MBUTTONDOWN,
WM_MBUTTONUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP,
};
use windows::core::PCWSTR;
use super::tracker::Tracker;
use super::{Hotkey, HotkeyEvents, Key, NamedKey};
use crate::{Error, Result};
thread_local! {
/// The tracker of the hook thread this runs on.
static TRACKER: RefCell<Option<Arc<Mutex<Tracker>>>> = const { RefCell::new(None) };
}
fn with_tracker(f: impl FnOnce(&mut Tracker)) {
TRACKER.with(|t| {
if let Some(tracker) = &*t.borrow() {
f(&mut tracker.lock().unwrap_or_else(PoisonError::into_inner));
}
});
}
/// Keyboard hook procedure.
unsafe extern "system" fn keyboard_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
// SAFETY: for WH_KEYBOARD_LL with HC_ACTION, lparam points to a
// KBDLLHOOKSTRUCT that is valid for the duration of this call.
let info = unsafe { &*(lparam.0 as *const KBDLLHOOKSTRUCT) };
let pressed = match wparam.0 as u32 {
WM_KEYDOWN | WM_SYSKEYDOWN => Some(true),
WM_KEYUP | WM_SYSKEYUP => Some(false),
_ => None,
};
let extended = info.flags.contains(LLKHF_EXTENDED);
if let (Some(pressed), Some(key)) =
(pressed, Key::from_windows_vk(info.vkCode as u16, extended))
{
with_tracker(|t| t.key(key, pressed));
}
}
// SAFETY: passing the unchanged arguments on to the next hook.
unsafe { CallNextHookEx(None, code, wparam, lparam) }
}
/// Mouse hook procedure: middle and side buttons.
unsafe extern "system" fn mouse_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
// SAFETY: for WH_MOUSE_LL with HC_ACTION, lparam points to a
// MSLLHOOKSTRUCT that is valid for the duration of this call.
let info = unsafe { &*(lparam.0 as *const MSLLHOOKSTRUCT) };
let side = |pressed| {
// The high word of mouseData: 1 = XBUTTON1 (back), 2 = forward.
let key = match info.mouseData >> 16 {
1 => NamedKey::MouseBack,
2 => NamedKey::MouseForward,
_ => return None,
};
Some((Key::Named(key), pressed))
};
let event = match wparam.0 as u32 {
WM_MBUTTONDOWN => Some((Key::Named(NamedKey::MouseMiddle), true)),
WM_MBUTTONUP => Some((Key::Named(NamedKey::MouseMiddle), false)),
WM_XBUTTONDOWN => side(true),
WM_XBUTTONUP => side(false),
_ => None,
};
if let Some((key, pressed)) = event {
with_tracker(|t| t.key(key, pressed));
}
}
// SAFETY: passing the unchanged arguments on to the next hook.
unsafe { CallNextHookEx(None, code, wparam, lparam) }
}
/// Install both hooks on this thread.
fn install() -> windows::core::Result<(HHOOK, HHOOK)> {
// SAFETY: plain Win32 calls with valid arguments; the hook procedures
// have the HOOKPROC signature and live for the whole program.
unsafe {
let module = HINSTANCE::from(GetModuleHandleW(PCWSTR::null())?);
let keyboard = SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_proc), Some(module), 0)?;
match SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_proc), Some(module), 0) {
Ok(mouse) => Ok((keyboard, mouse)),
Err(e) => {
let _ = UnhookWindowsHookEx(keyboard);
Err(e)
}
}
}
}
fn hook_thread(tracker: Arc<Mutex<Tracker>>, ready: std_mpsc::Sender<Result<u32>>) {
TRACKER.with(|t| *t.borrow_mut() = Some(tracker.clone()));
let hooks = match install() {
Ok(hooks) => hooks,
Err(e) => {
let _ = ready.send(Err(Error::Backend(format!("keyboard hook: {e}"))));
return;
}
};
// SAFETY: returns the id of the calling thread.
let _ = ready.send(Ok(unsafe { GetCurrentThreadId() }));
let mut msg = MSG::default();
// SAFETY: standard message loop on this thread's queue; `msg` is valid.
// GetMessageW returns 0 for WM_QUIT and -1 on errors.
unsafe {
while GetMessageW(&mut msg, None, 0, 0).0 > 0 {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
let _ = UnhookWindowsHookEx(hooks.0);
let _ = UnhookWindowsHookEx(hooks.1);
}
tracker.lock().unwrap_or_else(PoisonError::into_inner).release_all();
}
pub(crate) struct HookBackend {
tracker: Arc<Mutex<Tracker>>,
thread_id: u32,
}
impl HookBackend {
pub fn start() -> Result<Self> {
let tracker = Arc::new(Mutex::new(Tracker::default()));
let (ready_tx, ready_rx) = std_mpsc::channel();
{
let tracker = tracker.clone();
thread::Builder::new()
.name("tsc-hotkeys-hook".into())
.spawn(move || hook_thread(tracker, ready_tx))
.map_err(|e| Error::Backend(format!("keyboard hook: {e}")))?;
}
let thread_id =
ready_rx.recv().map_err(|_| Error::Backend("keyboard hook thread ended".into()))??;
Ok(Self { tracker, thread_id })
}
fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> {
self.tracker.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.tracker().add(id, hotkey)
}
pub fn unregister(&mut self, id: &str) {
self.tracker().remove(id);
}
}
impl Drop for HookBackend {
fn drop(&mut self) {
// SAFETY: posting WM_QUIT to our hook thread's queue ends its loop.
let _ = unsafe { PostThreadMessageW(self.thread_id, WM_QUIT, WPARAM(0), LPARAM(0)) };
}
}
+193
View File
@@ -0,0 +1,193 @@
//! X11 backend: XInput2 raw key and button events on the root window.
//!
//! Raw events reach us whichever window has focus, and nothing is grabbed,
//! so the key also reaches the focused application. A thread blocks on the
//! connection; dropping the backend wakes it with a client message to a
//! private input-only window.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread;
use tracing::{debug, warn};
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::xinput::{self, ConnectionExt as _, XIEventMask};
use x11rb::protocol::xproto::{
AtomEnum, ClientMessageEvent, ConnectionExt as _, CreateWindowAux, EventMask, Window,
WindowClass,
};
use x11rb::rust_connection::RustConnection;
use super::tracker::Tracker;
use super::{Hotkey, HotkeyEvents, Key, NamedKey};
use crate::{Error, Result};
fn x11_error(e: impl std::fmt::Display) -> Error {
Error::Backend(format!("X11: {e}"))
}
/// Keycode to keysyms, from the server's keyboard mapping.
struct Keymap {
min_keycode: u8,
per_keycode: usize,
keysyms: Vec<u32>,
}
impl Keymap {
fn load(conn: &RustConnection) -> Result<Self> {
let setup = conn.setup();
let (min, max) = (setup.min_keycode, setup.max_keycode);
let reply = conn
.get_keyboard_mapping(min, max - min + 1)
.map_err(x11_error)?
.reply()
.map_err(x11_error)?;
Ok(Self {
min_keycode: min,
per_keycode: reply.keysyms_per_keycode as usize,
keysyms: reply.keysyms,
})
}
/// The key on this keycode, by the first of its keysyms we know.
fn key(&self, keycode: u32) -> Option<Key> {
let index = (keycode.checked_sub(self.min_keycode as u32)? as usize) * self.per_keycode;
let syms = self.keysyms.get(index..index + self.per_keycode)?;
syms.iter().find_map(|&s| Key::from_x11_keysym(s))
}
}
/// Raw (physical) button numbers: 2 middle, 8 back, 9 forward.
fn button_key(button: u32) -> Option<Key> {
match button {
2 => Some(Key::Named(NamedKey::MouseMiddle)),
8 => Some(Key::Named(NamedKey::MouseBack)),
9 => Some(Key::Named(NamedKey::MouseForward)),
_ => None,
}
}
pub(crate) struct X11Backend {
conn: Arc<RustConnection>,
wake_window: Window,
tracker: Arc<Mutex<Tracker>>,
stop: Arc<AtomicBool>,
}
impl X11Backend {
/// Connect to `display`, or `$DISPLAY` for `None`.
pub fn connect(display: Option<&str>) -> Result<Self> {
let (conn, screen) = x11rb::connect(display).map_err(x11_error)?;
let root = conn.setup().roots[screen].root;
let version =
conn.xinput_xi_query_version(2, 0).map_err(x11_error)?.reply().map_err(x11_error)?;
if version.major_version < 2 {
return Err(Error::Backend("X11: XInput 2 is not available".into()));
}
let mask = XIEventMask::RAW_KEY_PRESS
| XIEventMask::RAW_KEY_RELEASE
| XIEventMask::RAW_BUTTON_PRESS
| XIEventMask::RAW_BUTTON_RELEASE;
let masks =
[xinput::EventMask { deviceid: xinput::Device::ALL_MASTER.into(), mask: vec![mask] }];
conn.xinput_xi_select_events(root, &masks)
.map_err(x11_error)?
.check()
.map_err(x11_error)?;
let wake_window = conn.generate_id().map_err(x11_error)?;
conn.create_window(
0,
wake_window,
root,
0,
0,
1,
1,
0,
WindowClass::INPUT_ONLY,
0,
&CreateWindowAux::new(),
)
.map_err(x11_error)?
.check()
.map_err(x11_error)?;
let keymap = Keymap::load(&conn)?;
let conn = Arc::new(conn);
let tracker = Arc::new(Mutex::new(Tracker::default()));
let stop = Arc::new(AtomicBool::new(false));
{
let (conn, tracker, stop) = (conn.clone(), tracker.clone(), stop.clone());
thread::Builder::new()
.name("tsc-hotkeys-x11".into())
.spawn(move || event_loop(&conn, keymap, &tracker, &stop))
.map_err(|e| Error::Backend(format!("X11: {e}")))?;
}
Ok(Self { conn, wake_window, tracker, stop })
}
fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> {
self.tracker.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.tracker().add(id, hotkey)
}
pub fn unregister(&mut self, id: &str) {
self.tracker().remove(id);
}
}
impl Drop for X11Backend {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
// With an empty event mask the event goes to the window's creator: us.
let wake = ClientMessageEvent::new(32, self.wake_window, AtomEnum::NONE, [0u32; 5]);
let _ = self.conn.send_event(false, self.wake_window, EventMask::NO_EVENT, wake);
let _ = self.conn.flush();
}
}
fn event_loop(
conn: &RustConnection,
mut keymap: Keymap,
tracker: &Mutex<Tracker>,
stop: &AtomicBool,
) {
let lock = || tracker.lock().unwrap_or_else(PoisonError::into_inner);
loop {
let event = match conn.wait_for_event() {
Ok(event) => event,
Err(error) => {
warn!(%error, "X11 hotkey connection lost");
lock().release_all();
return;
}
};
if stop.load(Ordering::Relaxed) {
lock().release_all();
return;
}
let (key, pressed) = match event {
Event::XinputRawKeyPress(e) => (keymap.key(e.detail), true),
Event::XinputRawKeyRelease(e) => (keymap.key(e.detail), false),
Event::XinputRawButtonPress(e) => (button_key(e.detail), true),
Event::XinputRawButtonRelease(e) => (button_key(e.detail), false),
Event::MappingNotify(_) => {
match Keymap::load(conn) {
Ok(k) => keymap = k,
Err(error) => debug!(%error, "keeping the old keymap"),
}
continue;
}
_ => continue,
};
if let Some(key) = key {
lock().key(key, pressed);
}
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Desktop integration.
//!
//! - [`hotkey`]: global push-to-talk hotkeys with press and release events
//! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on
//! Windows)
//! - [`notify`]: desktop notifications
//! - [`paths`]: data, config, cache and state directories
pub mod hotkey;
pub mod notify;
pub mod paths;
pub use hotkey::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager, Key, Modifiers};
pub use notify::{Notification, notify};
/// Application id: desktop file, icon, portal registrations. A placeholder
/// until the product has a name.
pub const APP_ID: &str = "io.github.faumaray.TsClient";
/// Name shown in notifications. A placeholder until the product has a name.
pub const APP_NAME: &str = "TS Client";
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid hotkey: {0}")]
InvalidHotkey(String),
#[error("not supported: {0}")]
Unsupported(String),
#[error("{0}")]
Backend(String),
#[error("notification: {0}")]
Notification(String),
}
pub type Result<T> = std::result::Result<T, Error>;
+75
View File
@@ -0,0 +1,75 @@
//! Desktop notifications through notify-rust: the freedesktop notification
//! service over D-Bus on Linux (works from Flatpak too), toasts on Windows.
use std::time::Duration;
use crate::{APP_NAME, Error, Result};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Notification {
pub title: String,
pub body: String,
/// How long it stays; `None` for the desktop's default.
pub timeout: Option<Duration>,
/// Urgent (a poke, a private message): kept until dismissed where the
/// desktop supports that.
pub urgent: bool,
}
impl Notification {
pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
Self { title: title.into(), body: body.into(), ..Default::default() }
}
}
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn native(n: &Notification) -> notify_rust::Notification {
let mut native = notify_rust::Notification::new();
native.summary(&n.title).body(&n.body).appname(APP_NAME);
if let Some(timeout) = n.timeout {
native.timeout(notify_rust::Timeout::Milliseconds(timeout.as_millis() as u32));
}
#[cfg(all(unix, not(target_os = "macos")))]
{
// The desktop file and icon are installed under the app id.
native.icon(crate::APP_ID).hint(notify_rust::Hint::DesktopEntry(crate::APP_ID.into()));
if n.urgent {
native.urgency(notify_rust::Urgency::Critical);
}
}
native
}
/// Show a notification. Fails when there is no notification service (e.g. no
/// D-Bus session); callers usually just log that.
pub async fn notify(n: &Notification) -> Result<()> {
#[cfg(all(unix, not(target_os = "macos")))]
{
native(n).show_async().await.map_err(|e| Error::Notification(e.to_string()))?;
Ok(())
}
#[cfg(windows)]
{
native(n).show().map_err(|e| Error::Notification(e.to_string()))?;
Ok(())
}
#[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
{
let _ = (n, APP_NAME);
Err(Error::Unsupported("notifications".into()))
}
}
// On Windows a toast would really show, so Linux only.
#[cfg(all(test, unix, not(target_os = "macos")))]
mod tests {
use super::*;
/// Without a notification service this must fail, not hang or panic.
#[tokio::test]
async fn notify_returns() {
let n = Notification { urgent: true, ..Notification::new("Poke", "from a test") };
let result = tokio::time::timeout(Duration::from_secs(10), notify(&n)).await;
assert!(result.is_ok(), "notify hung");
}
}
+106
View File
@@ -0,0 +1,106 @@
//! Where the app keeps its files.
//!
//! `<base>/tsc` for the platform's data, config, cache and state bases (XDG
//! on Linux, where Flatpak points them into `~/.var/app/<app id>/`; Known
//! Folders on Windows: `%APPDATA%` for data and config, `%LOCALAPPDATA%` for
//! cache and state). Each can be overridden with an environment variable,
//! e.g. for portable installs or tests.
use std::path::{Path, PathBuf};
/// Directory name under each base; the desktop app's store already lives in
/// `<data>/tsc`.
pub const APP_DIR: &str = "tsc";
fn resolve(var: &str, base: Option<PathBuf>) -> PathBuf {
match std::env::var_os(var).filter(|v| !v.is_empty()) {
Some(dir) => dir.into(),
None => base.unwrap_or_else(|| PathBuf::from(".")).join(APP_DIR),
}
}
/// Identities, bookmarks, chat history. `TSC_DATA_DIR` overrides.
pub fn data_dir() -> PathBuf {
resolve("TSC_DATA_DIR", dirs::data_dir())
}
/// Settings files. `TSC_CONFIG_DIR` overrides.
pub fn config_dir() -> PathBuf {
resolve("TSC_CONFIG_DIR", dirs::config_dir())
}
/// Disposable files (avatars, downloaded codecs). `TSC_CACHE_DIR` overrides.
pub fn cache_dir() -> PathBuf {
resolve("TSC_CACHE_DIR", dirs::cache_dir())
}
/// Logs and crash reports. `TSC_STATE_DIR` overrides.
pub fn state_dir() -> PathBuf {
resolve("TSC_STATE_DIR", dirs::state_dir().or_else(dirs::data_local_dir))
}
/// Create `dir` and its parents if needed.
pub fn ensure(dir: &Path) -> std::io::Result<&Path> {
std::fs::create_dir_all(dir)?;
Ok(dir)
}
/// Running inside a Flatpak sandbox.
pub fn is_flatpak() -> bool {
cfg!(target_os = "linux") && Path::new("/.flatpak-info").exists()
}
/// The display server of this session, as far as the environment tells.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisplayServer {
Wayland,
X11,
Windows,
MacOs,
Unknown,
}
pub fn display_server() -> DisplayServer {
if cfg!(windows) {
DisplayServer::Windows
} else if cfg!(target_os = "macos") {
DisplayServer::MacOs
} else if std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland")
{
DisplayServer::Wayland
} else if std::env::var_os("DISPLAY").is_some() {
DisplayServer::X11
} else {
DisplayServer::Unknown
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dirs_end_in_app_dir_or_override() {
for dir in [data_dir(), config_dir(), cache_dir(), state_dir()] {
assert!(dir.is_absolute() || dir.starts_with("."), "{}", dir.display());
}
assert_eq!(
resolve("TSC_TEST_UNSET_VARIABLE", Some("/base".into())),
Path::new("/base/tsc")
);
assert_eq!(resolve("TSC_TEST_UNSET_VARIABLE", None), Path::new("./tsc"));
// PATH is always set: stands in for an override.
let path = std::env::var_os("PATH").unwrap();
assert_eq!(resolve("PATH", Some("/base".into())), PathBuf::from(path));
}
#[test]
fn ensure_creates() {
let dir =
std::env::temp_dir().join(format!("tsc-platform-{}", std::process::id())).join("a");
assert_eq!(ensure(&dir).unwrap(), dir);
assert!(dir.is_dir());
std::fs::remove_dir_all(dir.parent().unwrap()).unwrap();
}
}
+115
View File
@@ -0,0 +1,115 @@
//! Global hotkeys against a real X server, typing through XTEST.
//!
//! Needs `TSC_X11_TEST_DISPLAY` naming a display to use (e.g. an Xvfb
//! started for the test, as CI does); skipped otherwise.
#![cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
use std::time::Duration;
use tokio::time::timeout;
use tsc_platform::{HotkeyEvent, HotkeyEvents, HotkeyManager};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{
BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, KEY_PRESS_EVENT,
KEY_RELEASE_EVENT,
};
use x11rb::protocol::xtest::ConnectionExt as _;
use x11rb::rust_connection::RustConnection;
use x11rb::wrapper::ConnectionExt as _;
struct Typist {
conn: RustConnection,
root: u32,
}
impl Typist {
fn new(display: &str) -> Self {
let (conn, screen) = x11rb::connect(Some(display)).unwrap();
let root = conn.setup().roots[screen].root;
Self { conn, root }
}
fn keycode(&self, keysym: u32) -> u8 {
let setup = self.conn.setup();
let (min, max) = (setup.min_keycode, setup.max_keycode);
let map = self.conn.get_keyboard_mapping(min, max - min + 1).unwrap().reply().unwrap();
let per = map.keysyms_per_keycode as usize;
let index = map.keysyms.iter().position(|&s| s == keysym).expect("keysym in keymap");
min + (index / per) as u8
}
fn fake(&self, kind: u8, detail: u8) {
self.conn.xtest_fake_input(kind, detail, 0, self.root, 0, 0, 0).unwrap();
self.conn.sync().unwrap();
}
fn key(&self, keysym: u32, down: bool) {
let kind = if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT };
self.fake(kind, self.keycode(keysym));
}
fn button(&self, button: u8, down: bool) {
self.fake(if down { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, button);
}
}
async fn next(events: &mut HotkeyEvents) -> Option<HotkeyEvent> {
timeout(Duration::from_secs(2), events.recv()).await.ok().flatten()
}
async fn nothing(events: &mut HotkeyEvents) -> bool {
timeout(Duration::from_millis(300), events.recv()).await.is_err()
}
const XK_CONTROL_L: u32 = 0xffe3;
const XK_F9: u32 = 0xffc6;
const XK_A: u32 = 0x61;
#[tokio::test]
async fn xinput2_press_and_release() {
let Ok(display) = std::env::var("TSC_X11_TEST_DISPLAY") else {
eprintln!("TSC_X11_TEST_DISPLAY not set, skipping");
return;
};
let mut manager = HotkeyManager::x11(&display).unwrap();
let mut ptt =
manager.register("ptt", "Push to talk", "Ctrl+F9".parse().unwrap()).await.unwrap();
let mut plain = manager.register("a", "Plain key", "A".parse().unwrap()).await.unwrap();
let mut back = manager.register("back", "Mouse", "MouseBack".parse().unwrap()).await.unwrap();
let typist = Typist::new(&display);
// F9 alone does not trigger Ctrl+F9.
typist.key(XK_F9, true);
typist.key(XK_F9, false);
assert!(nothing(&mut ptt).await);
typist.key(XK_CONTROL_L, true);
typist.key(XK_F9, true);
assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Pressed));
// Still held while Ctrl goes up first.
typist.key(XK_CONTROL_L, false);
assert!(nothing(&mut ptt).await);
typist.key(XK_F9, false);
assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Released));
typist.key(XK_A, true);
typist.key(XK_A, false);
assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Pressed));
assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Released));
typist.button(8, true);
typist.button(8, false);
assert_eq!(next(&mut back).await, Some(HotkeyEvent::Pressed));
assert_eq!(next(&mut back).await, Some(HotkeyEvent::Released));
manager.unregister("a").await.unwrap();
typist.key(XK_A, true);
typist.key(XK_A, false);
// The sender is gone: the channel ends.
assert_eq!(next(&mut plain).await, None);
// Dropping the manager stops its thread and closes the channels.
drop(manager);
assert_eq!(next(&mut ptt).await, None);
}
+1 -1
View File
@@ -21,7 +21,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
anyhow = "1"
futures = "0.3"
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[lints]
+11
View File
@@ -4,14 +4,25 @@
//! Only TeamSpeak 6 servers support streams. Media flows peer to peer; the
//! server only forwards `respondjoinstreamrequest` (the streamer's offer) and
//! `streamsignaling` (answer and ICE candidates).
//!
//! [`Streams`] (module [`session`]) ties it together for one connection: the
//! streams in our channel, our own stream with a peer per viewer, and the
//! streams we watch. [`FrameSource`] is where a streamer's encoded frames come from.
pub mod peer;
pub mod proto;
pub mod session;
pub mod signal;
pub mod source;
pub mod stun;
pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
pub use session::{
EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent,
StreamerOptions, Streams, ViewerInfo, ViewerState, WatchEvent, WatchState,
};
pub use signal::{Signal, SignalError};
pub use source::{EncodedFrame, FrameSource, SyntheticSource};
pub use str0m::format::Codec;
pub use str0m::media::{Frequency, MediaKind, MediaTime};
+145 -22
View File
@@ -9,6 +9,7 @@ use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer};
@@ -32,6 +33,8 @@ pub enum VideoCodec {
}
impl VideoCodec {
pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1];
pub fn from_codec(c: Codec) -> Option<Self> {
match c {
Codec::Vp8 => Some(Self::Vp8),
@@ -41,6 +44,20 @@ impl VideoCodec {
_ => None,
}
}
/// From an SDP encoding name (`a=rtpmap:<pt> VP8/90000`).
pub fn from_sdp_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.sdp_name().eq_ignore_ascii_case(name))
}
pub fn sdp_name(self) -> &'static str {
match self {
Self::Vp8 => "VP8",
Self::Vp9 => "VP9",
Self::H264 => "H264",
Self::Av1 => "AV1",
}
}
}
#[derive(Clone, Debug)]
@@ -49,8 +66,12 @@ pub struct PeerConfig {
pub hosts: Vec<IpAddr>,
/// STUN servers (`host:port`) for a server-reflexive candidate.
pub stun_servers: Vec<String>,
/// Video codecs, used for the streamer's offer; a viewer accepts all it knows.
/// Video codecs a streamer offers, in order of preference. Frames are sent
/// with the codec the viewer picks, so offer only what the encoder produces.
pub video_codecs: Vec<VideoCodec>,
/// Video codecs a viewer accepts (what it can decode). The answer keeps
/// the order of the streamer's offer, so the streamer's preference wins.
pub accept_video_codecs: Vec<VideoCodec>,
pub video: bool,
pub audio: bool,
}
@@ -60,7 +81,8 @@ impl Default for PeerConfig {
Self {
hosts: Vec::new(),
stun_servers: stun::TEAMSPEAK_STUN.iter().map(|s| (*s).to_owned()).collect(),
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264],
video_codecs: vec![VideoCodec::Vp8],
accept_video_codecs: VideoCodec::ALL.to_vec(),
video: true,
audio: true,
}
@@ -100,8 +122,9 @@ pub enum PeerEvent {
/// ICE and DTLS are up; media can flow.
Connected,
/// A candidate found after the SDP was sent (server reflexive), as an SDP
/// `candidate:` line for [`crate::Signal::IceCandidate`].
LocalCandidate(String),
/// `candidate:` line for [`crate::Signal::IceCandidate`], with the mid of
/// the first (bundled) media line.
LocalCandidate { candidate: String, mid: Option<String> },
/// A received frame (depacketized).
Media(MediaFrame),
/// The viewer asks for a keyframe.
@@ -140,7 +163,7 @@ impl Peer {
/// Streamer side: create a connection that sends our media; returns the SDP
/// offer for `respondjoinstreamrequest`.
pub async fn offer(config: &PeerConfig, stream_id: &str) -> Result<(Self, String), PeerError> {
let mut rtc = build_rtc(config, true);
let mut rtc = build_rtc(config, &config.video_codecs);
let net = Net::bind(config, &mut rtc).await?;
let mut api = rtc.sdp_api();
let msid = Some(stream_id.to_owned());
@@ -161,8 +184,18 @@ impl Peer {
/// Viewer side: accept the streamer's offer; returns our SDP answer.
pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> {
// Our codecs in the order of the offer, then the rest.
let mut codecs: Vec<_> = offered_video_codecs(offer)
.into_iter()
.filter(|c| config.accept_video_codecs.contains(c))
.collect();
for c in &config.accept_video_codecs {
if !codecs.contains(c) {
codecs.push(*c);
}
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let mut rtc = build_rtc(config, false);
let mut rtc = build_rtc(config, &codecs);
let net = Net::bind(config, &mut rtc).await?;
let answer = rtc.sdp_api().accept_offer(offer)?;
Ok((Self::spawn(rtc, net, config, None, Vec::new()), answer.to_sdp_string()))
@@ -225,6 +258,11 @@ impl Peer {
pub fn try_next_event(&mut self) -> Option<PeerEvent> {
self.events.try_recv().ok()
}
/// Poll for the next event, for driving many peers from one task.
pub fn poll_event(&mut self, cx: &mut Context<'_>) -> Poll<Option<PeerEvent>> {
self.events.poll_recv(cx)
}
}
impl Drop for Peer {
@@ -233,24 +271,66 @@ impl Drop for Peer {
}
}
fn build_rtc(config: &PeerConfig, offering: bool) -> Rtc {
let mut rtc_config =
RtcConfig::new().set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags()));
if offering {
// Offer only the codecs we can encode, in our order of preference.
rtc_config = rtc_config.clear_codecs().enable_opus(config.audio);
for codec in &config.video_codecs {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => rtc_config.enable_h264(true),
VideoCodec::Av1 => rtc_config.enable_av1(true),
};
}
/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the
/// TeamSpeak client decodes; str0m's defaults lack it.
const H264_CONSTRAINED_HIGH: u32 = 0x640c1f;
/// An RTC with Opus and `video` codecs, in this order of preference.
fn build_rtc(config: &PeerConfig, video: &[VideoCodec]) -> Rtc {
let mut rtc_config = RtcConfig::new()
.set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags()))
.clear_codecs()
.enable_opus(config.audio);
for codec in video {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => {
let mut c = rtc_config.enable_h264(true);
c.codec_config().add_h264(
112.into(),
Some(113.into()),
true,
H264_CONSTRAINED_HIGH,
);
c
}
VideoCodec::Av1 => rtc_config.enable_av1(true),
};
}
rtc_config.build(Instant::now())
}
/// The video codecs of the first video media line of `sdp`, in offered order.
fn offered_video_codecs(sdp: &str) -> Vec<VideoCodec> {
let mut pts: Vec<&str> = Vec::new();
let mut names: Vec<(&str, VideoCodec)> = Vec::new();
let mut in_video = false;
for line in sdp.lines().map(str::trim) {
if let Some(media) = line.strip_prefix("m=") {
in_video = pts.is_empty() && media.starts_with("video ");
if in_video {
pts = media.split_whitespace().skip(3).collect();
}
} else if in_video
&& let Some((pt, encoding)) =
line.strip_prefix("a=rtpmap:").and_then(|r| r.split_once(' '))
&& let Some(codec) = encoding.split('/').next().and_then(VideoCodec::from_sdp_name)
{
names.push((pt, codec));
}
}
let mut codecs = Vec::new();
for pt in pts {
if let Some((_, codec)) = names.iter().find(|(p, _)| *p == pt)
&& !codecs.contains(codec)
{
codecs.push(*codec);
}
}
codecs
}
/// The primary local IPv4 address (the one used for the default route).
fn primary_ipv4() -> Option<IpAddr> {
let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
@@ -420,9 +500,10 @@ impl Task {
}
match Candidate::server_reflexive(mapped, pending.base, "udp") {
Ok(c) => {
let line = c.to_sdp_string();
let candidate = c.to_sdp_string();
let mid = self.mids.first().map(|(mid, _)| mid.to_string());
if self.rtc.add_local_candidate(c).is_some() {
let _ = self.events.send(PeerEvent::LocalCandidate(line));
let _ = self.events.send(PeerEvent::LocalCandidate { candidate, mid });
}
}
Err(e) => debug!("bad reflexive candidate {mapped}: {e}"),
@@ -583,3 +664,45 @@ impl Task {
Some((mid, pt))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offered_codec_order() {
let sdp = "v=0\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\
a=rtpmap:111 opus/48000/2\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45 102\r\n\
a=rtpmap:96 VP8/90000\r\n\
a=rtpmap:97 rtx/90000\r\n\
a=rtpmap:98 VP9/90000\r\n\
a=rtpmap:99 rtx/90000\r\n\
a=rtpmap:45 AV1/90000\r\n\
a=rtpmap:102 H264/90000\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
a=rtpmap:96 H264/90000\r\n";
assert_eq!(
offered_video_codecs(sdp),
[VideoCodec::Vp9, VideoCodec::Vp8, VideoCodec::Av1, VideoCodec::H264]
);
assert!(offered_video_codecs("v=0\r\n").is_empty());
}
#[tokio::test]
async fn answer_follows_offer_order() {
let streamer = PeerConfig {
video_codecs: vec![VideoCodec::H264, VideoCodec::Vp8],
..PeerConfig::loopback()
};
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
let vp8_only =
PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() };
let (_peer, answer) = Peer::answer(&vp8_only, &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
}
}
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
//! Where a streamer's encoded frames come from.
//!
//! [`FrameSource`] is the seam between capture/encoding (`tsc-media`) and the
//! stream sessions. [`SyntheticSource`] produces decodable placeholder media
//! without any encoder, for tests and `tsctl stream start --synthetic`.
use std::sync::Arc;
use std::time::{Duration, Instant};
use str0m::media::{Frequency, MediaKind, MediaTime};
/// One encoded video or audio frame.
#[derive(Clone, Debug)]
pub struct EncodedFrame {
pub kind: MediaKind,
/// RTP time: 90 kHz for video, 48 kHz for Opus.
pub time: MediaTime,
pub data: Arc<[u8]>,
}
/// Produces encoded frames in real time.
pub trait FrameSource: Send {
/// Append the frames that are due at `now`.
fn poll_frames(&mut self, now: Instant, out: &mut Vec<EncodedFrame>);
/// A viewer needs a keyframe soon.
fn request_keyframe(&mut self) {}
/// How often `poll_frames` should be called.
fn interval(&self) -> Duration {
Duration::from_millis(10)
}
}
/// A complete 1x1 VP8 keyframe (the image of the smallest lossy WebP).
/// Decoders accept it, so browsers count decoded frames.
pub const VP8_KEYFRAME_1X1: [u8; 22] = [
0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x01, 0x00, 0x01, 0x00, 0x0e, 0xc0, 0xfe, 0x25, 0xa4, 0x00,
0x03, 0x70, 0x00, 0x00, 0x00, 0x00,
];
/// A 20 ms Opus frame of silence (CELT, fullband, mono).
pub const OPUS_SILENCE: [u8; 3] = [0xf8, 0xff, 0xfe];
/// Opus frame length at 48 kHz (20 ms).
const OPUS_FRAME: u64 = 960;
/// Synthetic media: every video frame is [`VP8_KEYFRAME_1X1`] padded to a
/// chosen size (large frames span several RTP packets), audio is
/// [`OPUS_SILENCE`] every 20 ms. Byte `VP8_KEYFRAME_1X1.len()` of each video
/// frame holds the low byte of its sequence number.
pub struct SyntheticSource {
start: Instant,
fps: u32,
video_size: usize,
audio: bool,
video_frames: u64,
audio_frames: u64,
}
impl SyntheticSource {
/// `fps` video frames of `video_size` bytes per second, plus audio if `audio`.
pub fn new(fps: u32, video_size: usize, audio: bool) -> Self {
Self {
start: Instant::now(),
fps: fps.max(1),
video_size: video_size.max(VP8_KEYFRAME_1X1.len() + 1),
audio,
video_frames: 0,
audio_frames: 0,
}
}
pub fn video_frame(seq: u64, size: usize) -> Vec<u8> {
let mut frame = VP8_KEYFRAME_1X1.to_vec();
frame.push(seq as u8);
frame.extend((frame.len()..size).map(|i| (i as u8).wrapping_mul(31) ^ seq as u8));
frame
}
}
impl FrameSource for SyntheticSource {
fn poll_frames(&mut self, now: Instant, out: &mut Vec<EncodedFrame>) {
let elapsed = now.saturating_duration_since(self.start);
let due_video = elapsed.as_micros() as u64 * u64::from(self.fps) / 1_000_000 + 1;
while self.video_frames < due_video {
let n = self.video_frames;
out.push(EncodedFrame {
kind: MediaKind::Video,
time: MediaTime::from_90khz(n * 90_000 / u64::from(self.fps)),
data: Self::video_frame(n, self.video_size).into(),
});
self.video_frames += 1;
}
if self.audio {
let due_audio = elapsed.as_millis() as u64 / 20 + 1;
while self.audio_frames < due_audio {
let time =
MediaTime::new(self.audio_frames * OPUS_FRAME, Frequency::FORTY_EIGHT_KHZ);
let data = Arc::from(&OPUS_SILENCE[..]);
out.push(EncodedFrame { kind: MediaKind::Audio, time, data });
self.audio_frames += 1;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paced_frames() {
let mut source = SyntheticSource::new(30, 3000, true);
let start = source.start;
let mut out = Vec::new();
source.poll_frames(start, &mut out);
assert_eq!(out.len(), 2, "one video and one audio frame at the start");
out.clear();
source.poll_frames(start + Duration::from_millis(1000), &mut out);
let video: Vec<_> = out.iter().filter(|f| f.kind == MediaKind::Video).collect();
let audio = out.len() - video.len();
assert_eq!((video.len(), audio), (30, 50));
assert_eq!(video[29].time, MediaTime::from_90khz(90_000));
assert_eq!(video[0].data.len(), 3000);
assert_eq!(video[0].data[..22], VP8_KEYFRAME_1X1);
assert_eq!(video[0].data[22], 1);
}
}
+320
View File
@@ -0,0 +1,320 @@
//! Interop with a browser WebRTC stack: headless Chromium (Playwright) is the
//! other peer, driven by `tests/interop/browser-peer.cjs` over stdin/stdout.
//! No TeamSpeak server is involved; SDP goes straight between the peers.
//!
//! Runs only with `TSC_INTEROP=1` (see `tests/interop/README.md`).
use std::path::PathBuf;
use std::process::Stdio;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::time::timeout;
use tsc_stream::{
Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SyntheticSource,
};
fn enabled() -> bool {
std::env::var("TSC_INTEROP").is_ok_and(|v| v == "1")
}
/// The Node.js side (headless Chromium).
struct Browser {
_child: Child,
stdin: ChildStdin,
stdout: Lines<BufReader<ChildStdout>>,
}
impl Browser {
async fn start() -> Self {
let script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/interop/browser-peer.cjs")
.canonicalize()
.expect("tests/interop/browser-peer.cjs");
let node = std::env::var("TSC_NODE").unwrap_or_else(|_| "node".into());
let mut command = Command::new(node);
command
.arg(script)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
// Playwright is usually installed globally.
if std::env::var_os("NODE_PATH").is_none()
&& let Ok(out) = std::process::Command::new("npm").args(["root", "-g"]).output()
{
command.env("NODE_PATH", String::from_utf8_lossy(&out.stdout).trim());
}
let mut child = command.spawn().expect("cannot start node (set TSC_NODE)");
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap()).lines();
let mut browser = Self { _child: child, stdin, stdout };
let ready = browser.read().await;
eprintln!("browser: {}", ready["userAgent"]);
browser
}
async fn read(&mut self) -> Value {
let line = timeout(Duration::from_secs(60), self.stdout.next_line())
.await
.expect("browser did not answer")
.unwrap()
.expect("browser exited");
let value: Value = serde_json::from_str(&line).unwrap();
if let Some(error) = value.get("error") {
panic!("browser: {error}");
}
value
}
async fn call(&mut self, command: Value) -> Value {
let mut line = command.to_string();
line.push('\n');
self.stdin.write_all(line.as_bytes()).await.unwrap();
self.read().await
}
async fn quit(mut self) {
let _ = self.call(json!({ "op": "quit" })).await;
}
}
async fn wait_connected(peer: &mut Peer) {
timeout(Duration::from_secs(15), async {
loop {
match peer.next_event().await {
Some(PeerEvent::Connected) => return,
Some(PeerEvent::Closed) | None => panic!("closed before connecting"),
_ => {}
}
}
})
.await
.expect("no connection with the browser");
}
/// Our streamer peer (as in a TeamSpeak stream) sends VP8 + Opus to Chromium.
#[tokio::test(flavor = "multi_thread")]
async fn rust_streams_to_browser() {
if !enabled() {
eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let mut browser = Browser::start().await;
let config = PeerConfig::loopback();
let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap();
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
let answer = answer["sdp"].as_str().unwrap();
eprintln!("browser answer:\n{answer}");
peer.accept_answer(answer).await.unwrap();
wait_connected(&mut peer).await;
// Three seconds of synthetic media.
let mut source = SyntheticSource::new(30, 3000, true);
let mut frames = Vec::new();
let mut keyframe_requests = 0;
let end = Instant::now() + Duration::from_secs(3);
while Instant::now() < end {
source.poll_frames(Instant::now(), &mut frames);
for f in frames.drain(..) {
peer.write(f.kind, f.time, f.data);
}
while let Some(event) = peer.try_next_event() {
if let PeerEvent::KeyframeRequest = event {
keyframe_requests += 1;
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stats = browser.call(json!({ "op": "stats" })).await;
eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}");
assert_eq!(stats["connectionState"], "connected");
let video = &stats["inbound"]["video"];
let audio = &stats["inbound"]["audio"];
assert_eq!(video["codec"], "video/VP8");
assert!(video["packetsReceived"].as_u64().unwrap() > 100, "video packets: {video}");
assert!(video["bytesReceived"].as_u64().unwrap() > 100_000, "video bytes: {video}");
assert_eq!(audio["codec"], "audio/opus");
assert!(audio["packetsReceived"].as_u64().unwrap() > 50, "audio packets: {audio}");
// The synthetic frames are real (tiny) VP8 keyframes.
assert!(video["framesDecoded"].as_u64().unwrap() > 30, "decoded: {video}");
browser.quit().await;
}
/// Answer STUN binding requests with a made-up public address, so a peer
/// reports a server-reflexive candidate without internet access.
async fn fake_stun_server() -> std::net::SocketAddr {
let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let addr = socket.local_addr().unwrap();
tokio::spawn(async move {
let mut buf = [0; 1500];
while let Ok((n, from)) = socket.recv_from(&mut buf).await {
if n < 20 || buf[..2] != [0, 1] {
continue;
}
// Binding success with XOR-MAPPED-ADDRESS 203.0.113.9:40000.
let mut resp = vec![0x01, 0x01, 0, 12];
resp.extend_from_slice(&buf[4..20]);
resp.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
resp.extend_from_slice(&(40000u16 ^ 0x2112).to_be_bytes());
let ip = u32::from(std::net::Ipv4Addr::new(203, 0, 113, 9)) ^ 0x2112_A442;
resp.extend_from_slice(&ip.to_be_bytes());
let _ = socket.send_to(&resp, from).await;
}
});
addr
}
/// A trickled candidate as our sessions send it (`iceCandidate` signal with
/// the peer's mid) must be accepted by the browser.
#[tokio::test(flavor = "multi_thread")]
async fn trickled_candidates_reach_browser() {
if !enabled() {
eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let mut browser = Browser::start().await;
// Primary address (STUN is not sent from loopback) and the fake STUN server.
let stun = fake_stun_server().await;
let config = PeerConfig {
hosts: Vec::new(),
stun_servers: vec![stun.to_string()],
..PeerConfig::loopback()
};
let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap();
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
peer.accept_answer(answer["sdp"].as_str().unwrap()).await.unwrap();
let (candidate, mid) = timeout(Duration::from_secs(10), async {
loop {
match peer.next_event().await {
Some(PeerEvent::LocalCandidate { candidate, mid }) => return (candidate, mid),
Some(PeerEvent::Closed) | None => panic!("closed"),
_ => {}
}
}
})
.await
.expect("no server-reflexive candidate");
assert!(candidate.contains("203.0.113.9 40000 typ srflx"), "{candidate}");
let first_mid = offer.lines().find_map(|l| l.strip_prefix("a=mid:")).unwrap().trim();
assert_eq!(mid.as_deref(), Some(first_mid));
// Through the signal JSON, as the server relays it.
let json = Signal::IceCandidate { candidate, mid, mline_index: Some(0) }.to_json();
let Signal::IceCandidate { candidate, mid, mline_index } = Signal::parse(&json).unwrap() else {
unreachable!()
};
let add = json!({
"op": "candidate", "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index
});
browser.call(add).await;
wait_connected(&mut peer).await;
browser.quit().await;
}
/// Frames per codec.
#[derive(Debug, Default)]
struct Counts(Vec<(Codec, usize)>);
impl Counts {
fn add(&mut self, codec: Codec) {
match self.0.iter_mut().find(|(c, _)| *c == codec) {
Some((_, n)) => *n += 1,
None => self.0.push((codec, 1)),
}
}
fn get(&self, codec: Codec) -> usize {
self.0.iter().find(|(c, _)| *c == codec).map_or(0, |(_, n)| *n)
}
fn total(&self) -> usize {
self.0.iter().map(|(_, n)| n).sum()
}
}
struct Received {
video: Counts,
audio: Counts,
/// VP8 keyframes (frame tag bit 0 clear).
vp8_keyframes: usize,
}
/// Collect frames from `peer` for up to `limit` or until `enough`.
async fn receive(peer: &mut Peer, limit: Duration, enough: usize) -> Received {
let mut r = Received { video: Counts::default(), audio: Counts::default(), vp8_keyframes: 0 };
let _ = timeout(limit, async {
while let Some(event) = peer.next_event().await {
if let PeerEvent::Media(frame) = event {
let map = match frame.kind {
MediaKind::Video => &mut r.video,
MediaKind::Audio => &mut r.audio,
};
map.add(frame.codec);
if frame.codec == Codec::Vp8 && frame.data.first().is_some_and(|b| b & 1 == 0) {
r.vp8_keyframes += 1;
}
if r.video.total() >= enough && r.audio.total() >= enough {
return;
}
}
}
})
.await;
r
}
/// Chromium sends a canvas stream and an oscillator; our viewer peer answers.
#[tokio::test(flavor = "multi_thread")]
async fn browser_streams_to_rust() {
if !enabled() {
eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let mut browser = Browser::start().await;
let config = PeerConfig::loopback();
let mut tested = Vec::new();
for (name, codec) in
[("VP8", Codec::Vp8), ("VP9", Codec::Vp9), ("H264", Codec::H264), ("AV1", Codec::Av1)]
{
// VP8 with trickled browser candidates, the others with candidates in the SDP.
let trickle = codec == Codec::Vp8;
let offer = browser.call(json!({ "op": "offer", "codec": name, "trickle": trickle })).await;
if offer.get("unsupported").is_some() {
eprintln!("{name}: the browser cannot send it, skipped");
continue;
}
let offer = offer["sdp"].as_str().unwrap();
let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap();
browser.call(json!({ "op": "accept", "sdp": answer })).await;
if trickle {
let candidates = browser.call(json!({ "op": "candidates" })).await;
let candidates = candidates["candidates"].as_array().unwrap();
assert!(!candidates.is_empty(), "no browser candidates");
for c in candidates {
peer.add_remote_candidate(c["candidate"].as_str().unwrap());
}
}
wait_connected(&mut peer).await;
let received = receive(&mut peer, Duration::from_secs(8), 60).await;
eprintln!(
"{name}: video {:?}, audio {:?}, VP8 keyframes {}",
received.video, received.audio, received.vp8_keyframes
);
assert!(received.video.get(codec) >= 30, "{name} video frames");
assert!(received.audio.get(Codec::Opus) >= 30, "{name} Opus frames");
if codec == Codec::Vp8 {
// A keyframe request (PLI) makes the browser's encoder send one.
let before = received.vp8_keyframes;
peer.request_keyframe();
let after = receive(&mut peer, Duration::from_secs(3), 90).await;
assert!(after.vp8_keyframes > 0, "no keyframe after PLI (had {before} before)");
}
tested.push(name);
}
assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}");
browser.quit().await;
}
+280
View File
@@ -0,0 +1,280 @@
//! Two stream session managers talking through a fake server that relays the
//! commands like the TeamSpeak 6 server does (see
//! `docs/protocol-notes/ts6-streaming.md`), with real peers on loopback.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tsc_stream::{
EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, StreamEvent,
StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, StreamerOptions,
Streams, SyntheticSource, ViewerState, WatchEvent,
};
use tsclientlib::ClientId;
const STREAMER: usize = 0;
const VIEWER: usize = 1;
const IDS: [ClientId; 2] = [ClientId(5), ClientId(6)];
/// Relays requests to notifications, as observed on a TS6 server.
#[derive(Default)]
struct FakeServer {
streams: HashMap<String, ClientId>,
next: u32,
}
impl FakeServer {
fn relay(&mut self, from: ClientId, request: Request) -> Vec<(usize, StreamNotification)> {
let everyone = |n: StreamNotification| (0..2).map(move |i| (i, n.clone()));
let to = |client: ClientId| IDS.iter().position(|c| *c == client).unwrap();
match request {
Request::Setup(setup) => {
self.next += 1;
let id = format!("stream-{}", self.next);
self.streams.insert(id.clone(), from);
let info = StreamInfo {
id,
streamer: from,
name: setup.name,
kind: setup.kind,
bitrate: setup.bitrate,
viewer_limit: setup.viewer_limit,
audio: setup.audio,
};
(0..2)
.map(|i| {
let own = IDS[i] == from;
let return_code = own.then(|| "1".to_owned());
(i, StreamNotification::Started { info: info.clone(), return_code })
})
.collect()
}
Request::Stop { id } => {
self.streams.remove(&id);
everyone(StreamNotification::Stopped { id, streamer: Some(from), reason: None })
.collect()
}
Request::Join { id, streamer, message } => vec![(
to(streamer),
StreamNotification::JoinRequest { id, viewer: from, message, remove: false },
)],
Request::Leave { id, streamer } => vec![(
to(streamer),
StreamNotification::JoinRequest {
id,
viewer: from,
message: String::new(),
remove: true,
},
)],
Request::Respond { id, viewer, offer, accept } => vec![(
to(viewer),
StreamNotification::JoinResponse {
id,
streamer: Some(from),
accepted: accept,
offer,
message: String::new(),
},
)],
Request::Signal { id, peer, signal } => vec![(
to(peer),
StreamNotification::Signaling { id, peer: from, json: signal.to_json() },
)],
Request::RemoveViewer { id, viewer, reason } => {
everyone(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) })
.collect()
}
}
}
}
struct Net {
server: FakeServer,
clients: [Streams; 2],
/// Events not looked at yet, with the client index.
events: Vec<(usize, StreamEvent)>,
source: Option<SyntheticSource>,
video: usize,
audio: usize,
}
impl Net {
fn new() -> Self {
let config = PeerConfig::loopback();
Self {
server: FakeServer::default(),
clients: IDS.map(|id| Streams::new(id, config.clone())),
events: Vec::new(),
source: None,
video: 0,
audio: 0,
}
}
/// Deliver queued requests until nothing is left.
async fn flush(&mut self) {
loop {
let mut notes = Vec::new();
for (i, client) in self.clients.iter_mut().enumerate() {
while let Some(output) = client.poll_output() {
match output {
Output::Request(r) => notes.extend(self.server.relay(IDS[i], r)),
Output::Event(StreamEvent::Watch {
event: WatchEvent::Frame(f), ..
}) => match f.kind {
MediaKind::Video => self.video += 1,
MediaKind::Audio => self.audio += 1,
},
Output::Event(e) => self.events.push((i, e)),
}
}
}
if notes.is_empty() {
return;
}
for (to, n) in notes {
self.clients[to].handle_notification(n).await;
}
}
}
/// Handle queued requests, then wait for peer events or the next frame tick.
async fn step(&mut self) {
self.flush().await;
let [a, b] = &mut self.clients;
tokio::select! {
() = a.wait_peers() => {}
() = b.wait_peers() => {}
() = tokio::time::sleep(Duration::from_millis(10)) => {}
}
if let Some(source) = &mut self.source {
let mut frames = Vec::new();
source.poll_frames(Instant::now(), &mut frames);
for frame in &frames {
self.clients[STREAMER].write_frame(frame);
}
}
}
/// Run the network until `f` accepts an event; earlier events are dropped.
async fn until(&mut self, what: &str, mut f: impl FnMut(usize, &StreamEvent) -> bool) {
timeout(Duration::from_secs(10), async {
loop {
self.flush().await;
if let Some(pos) = self.events.iter().position(|(i, e)| f(*i, e)) {
self.events.drain(..=pos);
return;
}
self.step().await;
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}; events: {:?}", self.events));
}
/// Run until the viewer received `n` more video and audio frames.
async fn frames(&mut self, n: usize) {
let (video, audio) = (self.video + n, self.audio + n);
let deadline = Instant::now() + Duration::from_secs(10);
while self.video < video || self.audio < audio {
assert!(
Instant::now() < deadline,
"got {} video / {} audio frames",
self.video,
self.audio
);
self.step().await;
}
}
}
fn watch_event(event: &StreamEvent, f: impl Fn(&WatchEvent) -> bool) -> bool {
matches!(event, StreamEvent::Watch { event, .. } if f(event))
}
#[tokio::test(flavor = "multi_thread")]
async fn stream_between_sessions() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let mut net = Net::new();
let setup = StreamSetup { name: "fake".into(), kind: StreamKind::Screen, ..Default::default() };
net.clients[STREAMER].start(StreamerOptions { setup, auto_accept: false }).unwrap();
net.until("live", |i, e| {
i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Live { .. }))
})
.await;
net.until("stream in the viewer's list", |i, e| {
i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1)
})
.await;
let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone();
// Join, accepted by the streamer.
net.clients[VIEWER].watch(&id, "let me see").unwrap();
net.until("join request", |i, e| {
i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. }))
})
.await;
net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap();
net.until("viewer connected", |i, e| {
i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected))
})
.await;
net.until("streamer sees the viewer", |i, e| {
i == STREAMER
&& matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v))
if v.len() == 1 && v[0].state == ViewerState::Connected)
})
.await;
// Media.
net.source = Some(SyntheticSource::new(30, 4000, true));
net.frames(20).await;
// The viewer reconnects: new offer, new answer, media again.
net.clients[VIEWER].reconnect(&id).unwrap();
net.until("reconnected", |i, e| {
i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected))
})
.await;
net.frames(20).await;
// The streamer kicks the viewer.
net.clients[STREAMER].kick(IDS[VIEWER]).unwrap();
net.until("kicked", |i, e| {
i == VIEWER
&& watch_event(e, |e| {
matches!(e, WatchEvent::Ended(EndReason::Removed(Some(LeaveReason::Kicked))))
})
})
.await;
assert_eq!(net.clients[VIEWER].watching().count(), 0);
// Watch again, then the viewer leaves by itself.
net.clients[VIEWER].watch(&id, "").unwrap();
net.until("second join request", |i, e| {
i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. }))
})
.await;
net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap();
net.until("viewer connected again", |i, e| {
i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected))
})
.await;
net.frames(5).await;
net.clients[VIEWER].leave(&id).unwrap();
net.until("viewer gone", |i, e| {
i == STREAMER
&& matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v)) if v.is_empty())
})
.await;
// The streamer stops; the viewer's list empties.
net.clients[STREAMER].stop().unwrap();
net.until("stream gone", |i, e| {
i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.is_empty())
})
.await;
assert!(net.clients[STREAMER].streamer().is_none());
}
+2
View File
@@ -601,6 +601,8 @@ impl App {
}
Event::Chat { session, message } => self.add_message(session as i64, message),
Event::Error { message, .. } => self.set_status(message),
// Stream events: the streams panel is not wired yet.
_ => {}
}
}