tsc-core: audio settings, client and stream volumes, media pipeline
Audio: sessions start their audio thread with the engine's AudioSettings (SetAudioSettings, engine-wide), SetClientVolume / SetClientMuted reach the mixer, clients that leave are forgotten, and the audio thread reports the microphone level (InputLevel, also from TestMicrophone without a session). Audio of watched streams plays through the mixer under a made-up client id with its own volume (SetStreamVolume). Media (feature `media`, default): Streamer captures a screen and system audio, encodes VP8 (the offered codec) at the setup's bitrate and Opus, honours keyframe requests and feeds a StreamSink or, as EncodedSource, a FrameSource. VideoPipeline / Viewer decode watched streams on their own thread, skip to keyframes after losses and ask for them. A test streams the test pattern through two stream tasks and loopback peers and checks the rectangle in the decoded pictures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
0c83716fa1
commit
af5b202347
7 files changed
+1573
-47
No files matched your search
Generated
+1
@@ -8607,6 +8607,7 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"tsc-audio",
|
"tsc-audio",
|
||||||
"tsc-gateway-proto",
|
"tsc-gateway-proto",
|
||||||
|
"tsc-media",
|
||||||
"tsc-model",
|
"tsc-model",
|
||||||
"tsc-observer",
|
"tsc-observer",
|
||||||
"tsc-query",
|
"tsc-query",
|
||||||
|
|||||||
@@ -9,9 +9,13 @@ repository.workspace = true
|
|||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["audio-device"]
|
default = ["audio-device", "media"]
|
||||||
# Capture and play audio through the system's devices.
|
# Capture and play audio through the system's devices.
|
||||||
audio-device = ["tsc-audio/device"]
|
audio-device = ["tsc-audio/device"]
|
||||||
|
# Screen / system-audio capture and video codecs for streams (`media`
|
||||||
|
# module; tsc-media with its default backends: libvpx, OpenH264 loaded at
|
||||||
|
# runtime, X11 and PipeWire on Linux). Off for mobile builds.
|
||||||
|
media = ["dep:tsc-media"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
@@ -23,6 +27,7 @@ tokio-tungstenite = "0.30"
|
|||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tsc-audio = { path = "../tsc-audio", default-features = false }
|
tsc-audio = { path = "../tsc-audio", default-features = false }
|
||||||
tsc-gateway-proto = { path = "../tsc-gateway-proto" }
|
tsc-gateway-proto = { path = "../tsc-gateway-proto" }
|
||||||
|
tsc-media = { path = "../tsc-media", features = ["str0m"], optional = true }
|
||||||
tsc-model = { path = "../tsc-model" }
|
tsc-model = { path = "../tsc-model" }
|
||||||
tsc-observer = { path = "../tsc-observer" }
|
tsc-observer = { path = "../tsc-observer" }
|
||||||
tsc-query = { path = "../tsc-query" }
|
tsc-query = { path = "../tsc-query" }
|
||||||
|
|||||||
+192
-24
@@ -8,7 +8,8 @@
|
|||||||
//! independent part is [`Pipeline`]; the thread loop only moves samples
|
//! independent part is [`Pipeline`]; the thread loop only moves samples
|
||||||
//! between it and the devices, reopening devices that go away.
|
//! between it and the devices, reopening devices that go away.
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::sync::Arc;
|
||||||
use std::sync::mpsc as std_mpsc;
|
use std::sync::mpsc as std_mpsc;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
@@ -17,9 +18,10 @@ use tokio::sync::mpsc;
|
|||||||
use tracing::{debug, warn};
|
use tracing::{debug, warn};
|
||||||
use tsc_audio::pcm::{self, FRAME_SAMPLES};
|
use tsc_audio::pcm::{self, FRAME_SAMPLES};
|
||||||
use tsc_audio::settings::TransmitMode;
|
use tsc_audio::settings::TransmitMode;
|
||||||
|
use tsc_audio::vad::SILENCE_DB;
|
||||||
use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
||||||
use tsclientlib::ClientId;
|
use tsclientlib::ClientId;
|
||||||
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
|
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
|
||||||
|
|
||||||
pub(crate) enum AudioIn {
|
pub(crate) enum AudioIn {
|
||||||
Packet(InAudioBuf),
|
Packet(InAudioBuf),
|
||||||
@@ -27,24 +29,46 @@ pub(crate) enum AudioIn {
|
|||||||
InputMuted(bool),
|
InputMuted(bool),
|
||||||
OutputMuted(bool),
|
OutputMuted(bool),
|
||||||
/// Devices, processing, voice activation and transmit mode.
|
/// Devices, processing, voice activation and transmit mode.
|
||||||
#[allow(dead_code, reason = "sent once the session exposes audio settings")]
|
|
||||||
Settings(Box<AudioSettings>),
|
Settings(Box<AudioSettings>),
|
||||||
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||||
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
|
|
||||||
ClientVolume {
|
ClientVolume {
|
||||||
client: ClientId,
|
client: ClientId,
|
||||||
volume: f32,
|
volume: f32,
|
||||||
},
|
},
|
||||||
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
|
|
||||||
ClientMuted {
|
ClientMuted {
|
||||||
client: ClientId,
|
client: ClientId,
|
||||||
muted: bool,
|
muted: bool,
|
||||||
},
|
},
|
||||||
/// The client left; client ids are reused, so forget its volume.
|
/// The client left; client ids are reused, so forget its volume.
|
||||||
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
|
|
||||||
ClientLeft(ClientId),
|
ClientLeft(ClientId),
|
||||||
|
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||||
|
/// on the 48 kHz clock.
|
||||||
|
StreamAudio {
|
||||||
|
stream: String,
|
||||||
|
time: u64,
|
||||||
|
data: Arc<[u8]>,
|
||||||
|
},
|
||||||
|
/// Playback volume of a watched stream, linear like client volumes.
|
||||||
|
StreamVolume {
|
||||||
|
stream: String,
|
||||||
|
volume: f32,
|
||||||
|
},
|
||||||
|
/// We stopped watching the stream: forget its queue and volume.
|
||||||
|
StreamEnded(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the audio thread reports.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub(crate) enum AudioEvent {
|
||||||
|
/// A problem, e.g. a missing device.
|
||||||
|
Error(String),
|
||||||
|
/// Loudest microphone level (dBFS, after processing) since the last
|
||||||
|
/// report, and whether voice is being sent. About every
|
||||||
|
/// [`LEVEL_INTERVAL`] while the microphone delivers audio.
|
||||||
|
Level { db: f32, sending: bool },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub(crate) struct AudioHandle {
|
pub(crate) struct AudioHandle {
|
||||||
tx: std_mpsc::Sender<AudioIn>,
|
tx: std_mpsc::Sender<AudioIn>,
|
||||||
}
|
}
|
||||||
@@ -53,6 +77,13 @@ impl AudioHandle {
|
|||||||
pub fn send(&self, msg: AudioIn) {
|
pub fn send(&self, msg: AudioIn) {
|
||||||
let _ = self.tx.send(msg);
|
let _ = self.tx.send(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A handle without a thread, to see what would reach it.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn channel() -> (Self, std_mpsc::Receiver<AudioIn>) {
|
||||||
|
let (tx, rx) = std_mpsc::channel();
|
||||||
|
(Self { tx }, rx)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// With voice activation, also send this many 20 ms frames from before the
|
/// With voice activation, also send this many 20 ms frames from before the
|
||||||
@@ -68,25 +99,33 @@ const PLAYBACK_CAPACITY_MS: u32 = 200;
|
|||||||
const DEVICE_LATENCY_MS: u32 = 20;
|
const DEVICE_LATENCY_MS: u32 = 20;
|
||||||
/// How long the loop sleeps between rounds.
|
/// How long the loop sleeps between rounds.
|
||||||
const TICK: Duration = Duration::from_millis(5);
|
const TICK: Duration = Duration::from_millis(5);
|
||||||
|
/// How often the microphone level is reported (for a meter).
|
||||||
|
pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
|
||||||
|
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
|
||||||
|
const OPUS_FRAME: u64 = 960;
|
||||||
|
|
||||||
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
|
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
|
||||||
/// no device) are reported through `errors`.
|
/// no device) and the microphone level are reported through `events`.
|
||||||
pub(crate) fn spawn(
|
pub(crate) fn spawn(
|
||||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||||
errors: mpsc::UnboundedSender<String>,
|
events: mpsc::UnboundedSender<AudioEvent>,
|
||||||
voice_activation: bool,
|
settings: AudioSettings,
|
||||||
) -> AudioHandle {
|
) -> AudioHandle {
|
||||||
let transmit =
|
|
||||||
if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk };
|
|
||||||
let settings = AudioSettings { transmit, ..Default::default() };
|
|
||||||
let (tx, rx) = std_mpsc::channel();
|
let (tx, rx) = std_mpsc::channel();
|
||||||
thread::Builder::new()
|
thread::Builder::new()
|
||||||
.name("tsc-audio".into())
|
.name("tsc-audio".into())
|
||||||
.spawn(move || run(rx, outgoing, errors, settings))
|
.spawn(move || run(rx, outgoing, events, settings))
|
||||||
.expect("spawn audio thread");
|
.expect("spawn audio thread");
|
||||||
AudioHandle { tx }
|
AudioHandle { tx }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Audio of a watched stream in the mixer, under a made-up client id.
|
||||||
|
struct StreamAudio {
|
||||||
|
client: ClientId,
|
||||||
|
/// RTP time and packet id of the last packet.
|
||||||
|
last: Option<(u64, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Everything between the devices and the connection.
|
/// Everything between the devices and the connection.
|
||||||
struct Pipeline {
|
struct Pipeline {
|
||||||
settings: AudioSettings,
|
settings: AudioSettings,
|
||||||
@@ -101,6 +140,11 @@ struct Pipeline {
|
|||||||
input_muted: bool,
|
input_muted: bool,
|
||||||
output_muted: bool,
|
output_muted: bool,
|
||||||
was_sending: bool,
|
was_sending: bool,
|
||||||
|
/// Loudest level since the last report; `None` without microphone audio.
|
||||||
|
level_peak: Option<f32>,
|
||||||
|
/// Watched streams whose audio plays through the mixer.
|
||||||
|
streams: HashMap<String, StreamAudio>,
|
||||||
|
stream_volumes: HashMap<String, f32>,
|
||||||
/// Processed microphone audio, for tests.
|
/// Processed microphone audio, for tests.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
tap: Vec<f32>,
|
tap: Vec<f32>,
|
||||||
@@ -121,6 +165,9 @@ impl Pipeline {
|
|||||||
input_muted: false,
|
input_muted: false,
|
||||||
output_muted: false,
|
output_muted: false,
|
||||||
was_sending: false,
|
was_sending: false,
|
||||||
|
level_peak: None,
|
||||||
|
streams: HashMap::new(),
|
||||||
|
stream_volumes: HashMap::new(),
|
||||||
settings,
|
settings,
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
tap: Vec::new(),
|
tap: Vec::new(),
|
||||||
@@ -154,9 +201,73 @@ impl Pipeline {
|
|||||||
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
|
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
|
||||||
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
|
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
|
||||||
AudioIn::ClientLeft(client) => self.mixer.forget(client),
|
AudioIn::ClientLeft(client) => self.mixer.forget(client),
|
||||||
|
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
|
||||||
|
AudioIn::StreamVolume { stream, volume } => {
|
||||||
|
if let Some(s) = self.streams.get(&stream) {
|
||||||
|
self.mixer.set_volume(s.client, volume);
|
||||||
|
}
|
||||||
|
self.stream_volumes.insert(stream, volume);
|
||||||
|
}
|
||||||
|
AudioIn::StreamEnded(stream) => {
|
||||||
|
if let Some(s) = self.streams.remove(&stream) {
|
||||||
|
self.mixer.forget(s.client);
|
||||||
|
}
|
||||||
|
self.stream_volumes.remove(&stream);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Queue an Opus frame of a stream in the mixer, as if a client with a
|
||||||
|
/// made-up id (counting down from `u16::MAX`, where real ids are rare)
|
||||||
|
/// talked. The jitter buffer orders packets by id: one id per 20 ms of
|
||||||
|
/// RTP time, at least one per packet (shorter frames).
|
||||||
|
fn stream_packet(&mut self, stream: String, time: u64, data: &[u8]) {
|
||||||
|
let client = match self.streams.get(&stream) {
|
||||||
|
Some(s) => s.client,
|
||||||
|
None => {
|
||||||
|
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
|
||||||
|
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.mixer.forget(client);
|
||||||
|
let volume = self.stream_volumes.get(&stream).copied().unwrap_or(1.0);
|
||||||
|
self.mixer.set_volume(client, volume);
|
||||||
|
self.streams.insert(stream.clone(), StreamAudio { client, last: None });
|
||||||
|
client
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let entry = self.streams.get_mut(&stream).expect("inserted above");
|
||||||
|
let id = match entry.last {
|
||||||
|
None => time / OPUS_FRAME,
|
||||||
|
// Duplicate or reordered: the depacketizer delivers in order.
|
||||||
|
Some((last_time, _)) if time <= last_time => return,
|
||||||
|
Some((last_time, last_id)) => {
|
||||||
|
last_id + ((time - last_time + OPUS_FRAME / 2) / OPUS_FRAME).max(1)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
entry.last = Some((time, id));
|
||||||
|
let packet = OutAudio::new(&AudioData::S2C {
|
||||||
|
id: id as u16,
|
||||||
|
codec: CodecType::OpusMusic,
|
||||||
|
from: client.0,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
|
||||||
|
Ok(packet) => {
|
||||||
|
if let Err(error) = self.mixer.handle_packet(client, packet) {
|
||||||
|
debug!(%error, "dropped stream audio packet");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => debug!(?error, "stream audio packet"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The loudest microphone level since the last call, if any audio came in.
|
||||||
|
fn take_level(&mut self) -> Option<f32> {
|
||||||
|
self.level_peak.take()
|
||||||
|
}
|
||||||
|
|
||||||
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
|
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
|
||||||
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
|
/// `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)) {
|
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
|
||||||
@@ -175,6 +286,8 @@ impl Pipeline {
|
|||||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
||||||
// Always analysed, so the detector's state is current when needed.
|
// Always analysed, so the detector's state is current when needed.
|
||||||
let voice = self.vad.process(&frame);
|
let voice = self.vad.process(&frame);
|
||||||
|
let level = self.vad.level_db().max(SILENCE_DB);
|
||||||
|
self.level_peak = Some(self.level_peak.map_or(level, |peak| peak.max(level)));
|
||||||
let wanted = match self.settings.transmit {
|
let wanted = match self.settings.transmit {
|
||||||
TransmitMode::PushToTalk => self.ptt,
|
TransmitMode::PushToTalk => self.ptt,
|
||||||
TransmitMode::VoiceActivation => voice,
|
TransmitMode::VoiceActivation => voice,
|
||||||
@@ -232,18 +345,21 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
|
|||||||
fn run(
|
fn run(
|
||||||
rx: std_mpsc::Receiver<AudioIn>,
|
rx: std_mpsc::Receiver<AudioIn>,
|
||||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||||
errors: mpsc::UnboundedSender<String>,
|
events: mpsc::UnboundedSender<AudioEvent>,
|
||||||
settings: AudioSettings,
|
settings: AudioSettings,
|
||||||
) {
|
) {
|
||||||
|
let error = |message: String| {
|
||||||
|
let _ = events.send(AudioEvent::Error(message));
|
||||||
|
};
|
||||||
#[cfg(feature = "audio-device")]
|
#[cfg(feature = "audio-device")]
|
||||||
let mut devices = devices::Devices::new(&settings);
|
let mut devices = devices::Devices::new(&settings);
|
||||||
#[cfg(not(feature = "audio-device"))]
|
#[cfg(not(feature = "audio-device"))]
|
||||||
let _ = errors.send("built without audio device support".to_string());
|
error("built without audio device support".to_string());
|
||||||
|
|
||||||
let mut pipeline = match Pipeline::new(settings) {
|
let mut pipeline = match Pipeline::new(settings) {
|
||||||
Ok(p) => p,
|
Ok(p) => p,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = errors.send(e.to_string());
|
error(e.to_string());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -253,6 +369,7 @@ fn run(
|
|||||||
// Without speakers the mixer is drained at real time, so queues do not
|
// Without speakers the mixer is drained at real time, so queues do not
|
||||||
// fill up and talkers still end.
|
// fill up and talkers still end.
|
||||||
let mut idle_clock = Instant::now();
|
let mut idle_clock = Instant::now();
|
||||||
|
let mut level_clock = Instant::now();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
// Control messages and incoming voice.
|
// Control messages and incoming voice.
|
||||||
@@ -271,7 +388,7 @@ fn run(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "audio-device")]
|
#[cfg(feature = "audio-device")]
|
||||||
let playing = devices.step(&mut pipeline, &mut send, &errors);
|
let playing = devices.step(&mut pipeline, &mut send, &error);
|
||||||
#[cfg(not(feature = "audio-device"))]
|
#[cfg(not(feature = "audio-device"))]
|
||||||
let playing = {
|
let playing = {
|
||||||
// No microphone: nothing to process, but keep the path alive.
|
// No microphone: nothing to process, but keep the path alive.
|
||||||
@@ -289,13 +406,19 @@ fn run(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if level_clock.elapsed() >= LEVEL_INTERVAL {
|
||||||
|
level_clock = Instant::now();
|
||||||
|
if let Some(db) = pipeline.take_level() {
|
||||||
|
let _ = events.send(AudioEvent::Level { db, sending: pipeline.was_sending });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
thread::sleep(TICK);
|
thread::sleep(TICK);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "audio-device")]
|
#[cfg(feature = "audio-device")]
|
||||||
mod devices {
|
mod devices {
|
||||||
use tokio::sync::mpsc;
|
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
use tsc_audio::AudioSettings;
|
use tsc_audio::AudioSettings;
|
||||||
use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback};
|
use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback};
|
||||||
@@ -324,7 +447,7 @@ mod devices {
|
|||||||
&mut slot.as_mut().expect("just set").1
|
&mut slot.as_mut().expect("just set").1
|
||||||
}
|
}
|
||||||
|
|
||||||
fn report(errors: &mpsc::UnboundedSender<String>, what: &str, event: DeviceEvent) {
|
fn report(error: &impl Fn(String), what: &str, event: DeviceEvent) {
|
||||||
let message = match event {
|
let message = match event {
|
||||||
DeviceEvent::Opened { name, fallback: false } => {
|
DeviceEvent::Opened { name, fallback: false } => {
|
||||||
debug!(%name, "{what} opened");
|
debug!(%name, "{what} opened");
|
||||||
@@ -336,7 +459,7 @@ mod devices {
|
|||||||
DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"),
|
DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"),
|
||||||
DeviceEvent::Unavailable(e) => format!("no {what}: {e}"),
|
DeviceEvent::Unavailable(e) => format!("no {what}: {e}"),
|
||||||
};
|
};
|
||||||
let _ = errors.send(message);
|
error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Devices {
|
impl Devices {
|
||||||
@@ -362,13 +485,13 @@ mod devices {
|
|||||||
&mut self,
|
&mut self,
|
||||||
pipeline: &mut Pipeline,
|
pipeline: &mut Pipeline,
|
||||||
send: &mut impl FnMut(OutPacket),
|
send: &mut impl FnMut(OutPacket),
|
||||||
errors: &mpsc::UnboundedSender<String>,
|
error: &impl Fn(String),
|
||||||
) -> bool {
|
) -> bool {
|
||||||
if let Some(event) = self.playback.poll() {
|
if let Some(event) = self.playback.poll() {
|
||||||
report(errors, "speakers", event);
|
report(error, "speakers", event);
|
||||||
}
|
}
|
||||||
if let Some(event) = self.capture.poll() {
|
if let Some(event) = self.capture.poll() {
|
||||||
report(errors, "microphone", event);
|
report(error, "microphone", event);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mixer → speakers, keeping the configured amount queued.
|
// Mixer → speakers, keeping the configured amount queued.
|
||||||
@@ -410,7 +533,6 @@ mod devices {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
|
use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
|
||||||
use tsc_audio::{ProcessingSettings, VadSettings};
|
use tsc_audio::{ProcessingSettings, VadSettings};
|
||||||
use tsproto_packets::packets::{CodecType, Direction, OutAudio};
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@@ -529,6 +651,52 @@ mod tests {
|
|||||||
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
|
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Stream audio (stereo Opus with RTP times) plays through the mixer at
|
||||||
|
/// its own volume and is forgotten when the stream ends.
|
||||||
|
#[test]
|
||||||
|
fn stream_audio_with_volume() {
|
||||||
|
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||||
|
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||||
|
let tone = pcm::from_mono(&sine(600.0, 1.0, 0.4), 2);
|
||||||
|
// A random RTP start, as WebRTC senders use.
|
||||||
|
let start = 7_777_000u64;
|
||||||
|
let mut play = |p: &mut Pipeline, stream: &str| -> f32 {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES * 2).enumerate() {
|
||||||
|
let data: Arc<[u8]> = encoder.encode_to_bytes(frame).unwrap().into();
|
||||||
|
let time = start + i as u64 * OPUS_FRAME;
|
||||||
|
p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data: data.clone() });
|
||||||
|
// A duplicate is ignored.
|
||||||
|
p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data });
|
||||||
|
out.extend(p.playback_frame());
|
||||||
|
}
|
||||||
|
energy(&out[out.len() / 2..])
|
||||||
|
};
|
||||||
|
let full = play(&mut p, "a");
|
||||||
|
assert!(full > 1e-3, "stream audio must be audible");
|
||||||
|
p.handle(AudioIn::StreamVolume { stream: "b".into(), volume: 0.5 });
|
||||||
|
let half = play(&mut p, "b");
|
||||||
|
let ratio_db = 10.0 * (half / full).log10();
|
||||||
|
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
|
||||||
|
let mut clients: Vec<u16> = p.streams.values().map(|s| s.client.0).collect();
|
||||||
|
clients.sort_unstable();
|
||||||
|
assert_eq!(clients, [u16::MAX - 1, u16::MAX]);
|
||||||
|
p.handle(AudioIn::StreamEnded("b".into()));
|
||||||
|
assert_eq!(p.streams.len(), 1);
|
||||||
|
assert!(!p.stream_volumes.contains_key("b"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn level_is_reported() {
|
||||||
|
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||||
|
assert_eq!(p.take_level(), None, "no microphone audio yet");
|
||||||
|
// A sine of amplitude 0.3 has an RMS level of about -13.5 dBFS.
|
||||||
|
capture(&mut p, &sine(440.0, 0.1, 0.3));
|
||||||
|
let level = p.take_level().unwrap();
|
||||||
|
assert!((level + 13.5).abs() < 1.0, "{level}");
|
||||||
|
assert_eq!(p.take_level(), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn settings_are_sanitized() {
|
fn settings_are_sanitized() {
|
||||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||||
|
|||||||
+109
-5
@@ -13,10 +13,15 @@
|
|||||||
//!
|
//!
|
||||||
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
|
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
|
||||||
//! sharing): see the `*Stream*` commands and events, and
|
//! sharing): see the `*Stream*` commands and events, and
|
||||||
//! [`Engine::subscribe_frames`] for the frames of watched streams.
|
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
|
||||||
|
//! of watched streams plays through the session's speakers by itself
|
||||||
|
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
|
||||||
|
//! are in [`media`] (feature `media`).
|
||||||
|
|
||||||
mod audio;
|
mod audio;
|
||||||
mod gateway;
|
mod gateway;
|
||||||
|
#[cfg(feature = "media")]
|
||||||
|
pub mod media;
|
||||||
mod query;
|
mod query;
|
||||||
mod route;
|
mod route;
|
||||||
mod session;
|
mod session;
|
||||||
@@ -27,8 +32,11 @@ use std::collections::HashMap;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use tokio::sync::{broadcast, mpsc};
|
use tokio::sync::{broadcast, mpsc};
|
||||||
|
pub use tsc_audio::settings::TransmitMode;
|
||||||
|
pub use tsc_audio::{AudioSettings, ProcessingSettings, VadSettings};
|
||||||
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||||
|
|
||||||
|
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
|
||||||
pub use route::{ChatRoute, Dedup, route_chat};
|
pub use route::{ChatRoute, Dedup, route_chat};
|
||||||
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||||
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
|
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
|
||||||
@@ -86,11 +94,33 @@ pub enum Command {
|
|||||||
session: SessionId,
|
session: SessionId,
|
||||||
muted: bool,
|
muted: bool,
|
||||||
},
|
},
|
||||||
/// Push-to-talk state (or "always transmit" when voice activation is off).
|
/// Push-to-talk key or button held (only counts with
|
||||||
|
/// [`TransmitMode::PushToTalk`]).
|
||||||
SetTransmitting {
|
SetTransmitting {
|
||||||
session: SessionId,
|
session: SessionId,
|
||||||
on: bool,
|
on: bool,
|
||||||
},
|
},
|
||||||
|
/// Audio settings of all sessions (devices, processing, transmit mode),
|
||||||
|
/// also used by sessions started later.
|
||||||
|
SetAudioSettings(Box<AudioSettings>),
|
||||||
|
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||||
|
/// Local only; forgotten when the client leaves.
|
||||||
|
SetClientVolume {
|
||||||
|
session: SessionId,
|
||||||
|
client: u16,
|
||||||
|
volume: f32,
|
||||||
|
},
|
||||||
|
/// Do not play one client (local only).
|
||||||
|
SetClientMuted {
|
||||||
|
session: SessionId,
|
||||||
|
client: u16,
|
||||||
|
muted: bool,
|
||||||
|
},
|
||||||
|
/// Open the microphone without a session to show its level
|
||||||
|
/// ([`Event::InputLevel`] with `session: None`), e.g. in the settings.
|
||||||
|
TestMicrophone {
|
||||||
|
on: bool,
|
||||||
|
},
|
||||||
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
|
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
|
||||||
/// [`Event::StreamState`]; frames go in through the sink of
|
/// [`Event::StreamState`]; frames go in through the sink of
|
||||||
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
|
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
|
||||||
@@ -134,6 +164,13 @@ pub enum Command {
|
|||||||
session: SessionId,
|
session: SessionId,
|
||||||
stream_id: String,
|
stream_id: String,
|
||||||
},
|
},
|
||||||
|
/// Playback volume of a watched stream's audio, linear (1 = unchanged,
|
||||||
|
/// up to 4).
|
||||||
|
SetStreamVolume {
|
||||||
|
session: SessionId,
|
||||||
|
stream_id: String,
|
||||||
|
volume: f32,
|
||||||
|
},
|
||||||
/// Close everything of a session.
|
/// Close everything of a session.
|
||||||
CloseSession {
|
CloseSession {
|
||||||
session: SessionId,
|
session: SessionId,
|
||||||
@@ -205,6 +242,20 @@ pub enum Event {
|
|||||||
client: u16,
|
client: u16,
|
||||||
talking: bool,
|
talking: bool,
|
||||||
},
|
},
|
||||||
|
/// Microphone level for a meter, about ten times a second while the
|
||||||
|
/// microphone is open: of a voice session, or of
|
||||||
|
/// [`Command::TestMicrophone`] (`session: None`). `level_db` is the
|
||||||
|
/// loudest 10 ms (dBFS, after processing) since the last report;
|
||||||
|
/// `sending` whether voice is transmitted.
|
||||||
|
InputLevel {
|
||||||
|
session: Option<SessionId>,
|
||||||
|
level_db: f32,
|
||||||
|
sending: bool,
|
||||||
|
},
|
||||||
|
/// A problem with the microphone test (e.g. no device).
|
||||||
|
MicrophoneTestError {
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
Error {
|
Error {
|
||||||
session: SessionId,
|
session: SessionId,
|
||||||
message: String,
|
message: String,
|
||||||
@@ -248,6 +299,7 @@ pub struct Engine {
|
|||||||
commands: mpsc::UnboundedSender<Command>,
|
commands: mpsc::UnboundedSender<Command>,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
runtime: tokio::runtime::Handle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Engine {
|
impl Engine {
|
||||||
@@ -258,7 +310,13 @@ impl Engine {
|
|||||||
// About a minute of one watched stream.
|
// About a minute of one watched stream.
|
||||||
let (frames, _) = broadcast::channel(4096);
|
let (frames, _) = broadcast::channel(4096);
|
||||||
tokio::spawn(run(rx, events.clone(), frames.clone()));
|
tokio::spawn(run(rx, events.clone(), frames.clone()));
|
||||||
Self { commands, events, frames }
|
Self { commands, events, frames, runtime: tokio::runtime::Handle::current() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The runtime the engine runs on, for helpers started from other
|
||||||
|
/// threads (e.g. `media::Viewer` from a UI thread).
|
||||||
|
pub fn runtime(&self) -> &tokio::runtime::Handle {
|
||||||
|
&self.runtime
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send(&self, command: Command) {
|
pub fn send(&self, command: Command) {
|
||||||
@@ -281,8 +339,26 @@ async fn run(
|
|||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
) {
|
) {
|
||||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||||
|
let mut settings = AudioSettings::default();
|
||||||
|
let mut mic_test: Option<AudioHandle> = None;
|
||||||
while let Some(command) = commands.recv().await {
|
while let Some(command) = commands.recv().await {
|
||||||
let id = command_session(&command);
|
let id = match command {
|
||||||
|
Command::SetAudioSettings(new) => {
|
||||||
|
settings = (*new).clone();
|
||||||
|
for s in sessions.values() {
|
||||||
|
s.send(Command::SetAudioSettings(new.clone()));
|
||||||
|
}
|
||||||
|
if let Some(test) = &mic_test {
|
||||||
|
test.send(AudioIn::Settings(new));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Command::TestMicrophone { on } => {
|
||||||
|
mic_test = on.then(|| test_microphone(&settings, &events));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ref command => command_session(command),
|
||||||
|
};
|
||||||
if matches!(command, Command::CloseSession { .. }) {
|
if matches!(command, Command::CloseSession { .. }) {
|
||||||
if let Some(s) = sessions.remove(&id) {
|
if let Some(s) = sessions.remove(&id) {
|
||||||
s.send(command);
|
s.send(command);
|
||||||
@@ -291,11 +367,33 @@ async fn run(
|
|||||||
}
|
}
|
||||||
sessions
|
sessions
|
||||||
.entry(id)
|
.entry(id)
|
||||||
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone()))
|
.or_insert_with(|| {
|
||||||
|
session::SessionHandle::spawn(id, events.clone(), frames.clone(), settings.clone())
|
||||||
|
})
|
||||||
.send(command);
|
.send(command);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An audio thread whose packets go nowhere, for its level.
|
||||||
|
fn test_microphone(settings: &AudioSettings, events: &broadcast::Sender<Event>) -> AudioHandle {
|
||||||
|
let (packets, _) = mpsc::unbounded_channel();
|
||||||
|
let (audio_tx, mut audio_rx) = mpsc::unbounded_channel();
|
||||||
|
let handle = audio::spawn(packets, audio_tx, settings.clone());
|
||||||
|
let events = events.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(event) = audio_rx.recv().await {
|
||||||
|
let _ = events.send(match event {
|
||||||
|
AudioEvent::Level { db, sending } => {
|
||||||
|
Event::InputLevel { session: None, level_db: db, sending }
|
||||||
|
}
|
||||||
|
AudioEvent::Error(message) => Event::MicrophoneTestError { message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
handle
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session a command is for (engine-wide commands are handled before).
|
||||||
fn command_session(command: &Command) -> SessionId {
|
fn command_session(command: &Command) -> SessionId {
|
||||||
match command {
|
match command {
|
||||||
Command::ConnectVoice { session, .. }
|
Command::ConnectVoice { session, .. }
|
||||||
@@ -318,6 +416,12 @@ fn command_session(command: &Command) -> SessionId {
|
|||||||
| Command::WatchStream { session, .. }
|
| Command::WatchStream { session, .. }
|
||||||
| Command::LeaveStream { session, .. }
|
| Command::LeaveStream { session, .. }
|
||||||
| Command::RequestStreamKeyframe { session, .. }
|
| Command::RequestStreamKeyframe { session, .. }
|
||||||
|
| Command::SetStreamVolume { session, .. }
|
||||||
|
| Command::SetClientVolume { session, .. }
|
||||||
|
| Command::SetClientMuted { session, .. }
|
||||||
| Command::CloseSession { session } => *session,
|
| Command::CloseSession { session } => *session,
|
||||||
|
Command::SetAudioSettings(_) | Command::TestMicrophone { .. } => {
|
||||||
|
unreachable!("engine-wide commands have no session")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -5,9 +5,11 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use tokio::sync::{broadcast, mpsc};
|
use tokio::sync::{broadcast, mpsc};
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
|
use tsc_audio::AudioSettings;
|
||||||
use tsc_model::{ChatMessage, ChatTarget, Presence};
|
use tsc_model::{ChatMessage, ChatTarget, Presence};
|
||||||
|
use tsclientlib::ClientId;
|
||||||
|
|
||||||
use crate::audio::{self, AudioHandle, AudioIn};
|
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
|
||||||
use crate::gateway::{self, GatewayCmd, GatewayEvent};
|
use crate::gateway::{self, GatewayCmd, GatewayEvent};
|
||||||
use crate::query::{self, QueryCmd, QueryEvent};
|
use crate::query::{self, QueryCmd, QueryEvent};
|
||||||
use crate::route::{ChatRoute, Dedup, route_chat};
|
use crate::route::{ChatRoute, Dedup, route_chat};
|
||||||
@@ -24,9 +26,10 @@ impl SessionHandle {
|
|||||||
id: SessionId,
|
id: SessionId,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
audio_settings: AudioSettings,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let (tx, rx) = mpsc::unbounded_channel();
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
tokio::spawn(Session::new(id, events, frames).run(rx));
|
tokio::spawn(Session::new(id, events, frames, audio_settings).run(rx));
|
||||||
Self { tx }
|
Self { tx }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +45,7 @@ enum SourceEvent {
|
|||||||
Gateway(u64, GatewayEvent),
|
Gateway(u64, GatewayEvent),
|
||||||
Query(u64, QueryEvent),
|
Query(u64, QueryEvent),
|
||||||
AudioOut(u64, tsproto_packets::packets::OutPacket),
|
AudioOut(u64, tsproto_packets::packets::OutPacket),
|
||||||
AudioError(String),
|
Audio(u64, AudioEvent),
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Session {
|
struct Session {
|
||||||
@@ -58,6 +61,7 @@ struct Session {
|
|||||||
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
|
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
|
||||||
query_presence: Option<Presence>,
|
query_presence: Option<Presence>,
|
||||||
audio: Option<AudioHandle>,
|
audio: Option<AudioHandle>,
|
||||||
|
audio_settings: AudioSettings,
|
||||||
/// Streams of the voice connection (TeamSpeak 6 only).
|
/// Streams of the voice connection (TeamSpeak 6 only).
|
||||||
streams: Option<StreamHandle>,
|
streams: Option<StreamHandle>,
|
||||||
stream_peer: PeerConfig,
|
stream_peer: PeerConfig,
|
||||||
@@ -75,6 +79,7 @@ impl Session {
|
|||||||
id: SessionId,
|
id: SessionId,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
audio_settings: AudioSettings,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
||||||
Self {
|
Self {
|
||||||
@@ -90,6 +95,7 @@ impl Session {
|
|||||||
query: None,
|
query: None,
|
||||||
query_presence: None,
|
query_presence: None,
|
||||||
audio: None,
|
audio: None,
|
||||||
|
audio_settings,
|
||||||
streams: None,
|
streams: None,
|
||||||
stream_peer: PeerConfig::default(),
|
stream_peer: PeerConfig::default(),
|
||||||
frames,
|
frames,
|
||||||
@@ -160,12 +166,13 @@ impl Session {
|
|||||||
self.stream_peer = options.stream_peer.clone();
|
self.stream_peer = options.stream_peer.clone();
|
||||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||||
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
|
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
|
||||||
|
self.audio = None;
|
||||||
if options.audio {
|
if options.audio {
|
||||||
let (out_tx, out_rx) = mpsc::unbounded_channel();
|
let (out_tx, out_rx) = mpsc::unbounded_channel();
|
||||||
let (err_tx, err_rx) = mpsc::unbounded_channel();
|
let (audio_tx, audio_rx) = mpsc::unbounded_channel();
|
||||||
self.audio = Some(audio::spawn(out_tx, err_tx, false));
|
self.audio = Some(audio::spawn(out_tx, audio_tx, self.audio_settings.clone()));
|
||||||
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
|
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
|
||||||
self.forward(err_rx, SourceEvent::AudioError);
|
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
|
||||||
}
|
}
|
||||||
tokio::spawn(voice::run(*options, cmd_rx, ev_tx));
|
tokio::spawn(voice::run(*options, cmd_rx, ev_tx));
|
||||||
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
|
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
|
||||||
@@ -264,6 +271,29 @@ impl Session {
|
|||||||
}
|
}
|
||||||
self.emit_state();
|
self.emit_state();
|
||||||
}
|
}
|
||||||
|
Command::SetAudioSettings(settings) => {
|
||||||
|
self.audio_settings = (*settings).clone();
|
||||||
|
if let Some(a) = &self.audio {
|
||||||
|
a.send(AudioIn::Settings(settings));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Without audio there is nothing to adjust; the UI sends volumes
|
||||||
|
// again after connecting.
|
||||||
|
Command::SetClientVolume { client, volume, .. } => {
|
||||||
|
if let Some(a) = &self.audio {
|
||||||
|
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::SetClientMuted { client, muted, .. } => {
|
||||||
|
if let Some(a) = &self.audio {
|
||||||
|
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::SetStreamVolume { stream_id, volume, .. } => {
|
||||||
|
if let Some(a) = &self.audio {
|
||||||
|
a.send(AudioIn::StreamVolume { stream: stream_id, volume });
|
||||||
|
}
|
||||||
|
}
|
||||||
Command::StartStream { setup, auto_accept, .. } => {
|
Command::StartStream { setup, auto_accept, .. } => {
|
||||||
self.stream_input(StreamInput::Start { setup, auto_accept });
|
self.stream_input(StreamInput::Start { setup, auto_accept });
|
||||||
}
|
}
|
||||||
@@ -287,7 +317,7 @@ impl Session {
|
|||||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||||
}
|
}
|
||||||
Command::CloseSession { .. } => {}
|
Command::CloseSession { .. } | Command::TestMicrophone { .. } => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,7 +419,12 @@ impl Session {
|
|||||||
let _ = tx.send(VoiceCmd::Audio(packet));
|
let _ = tx.send(VoiceCmd::Audio(packet));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SourceEvent::AudioError(message) => self.error(message),
|
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
|
||||||
|
AudioEvent::Error(message) => self.error(message),
|
||||||
|
AudioEvent::Level { db, sending } => {
|
||||||
|
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => debug!("event from a replaced source ignored"),
|
_ => debug!("event from a replaced source ignored"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -410,12 +445,19 @@ impl Session {
|
|||||||
voice.clone(),
|
voice.clone(),
|
||||||
self.events.clone(),
|
self.events.clone(),
|
||||||
self.frames.clone(),
|
self.frames.clone(),
|
||||||
|
self.audio.clone(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
||||||
self.reopen_relayed_chats();
|
self.reopen_relayed_chats();
|
||||||
}
|
}
|
||||||
VoiceEvent::Presence(p) => {
|
VoiceEvent::Presence(p) => {
|
||||||
|
// Client ids are reused: forget the volumes of those who left.
|
||||||
|
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
|
||||||
|
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
|
||||||
|
a.send(AudioIn::ClientLeft(ClientId(*id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
if let Some(s) = &self.streams {
|
if let Some(s) = &self.streams {
|
||||||
let clients: BTreeMap<_, _> =
|
let clients: BTreeMap<_, _> =
|
||||||
p.clients.values().map(|c| (c.id, c.streaming)).collect();
|
p.clients.values().map(|c| (c.id, c.streaming)).collect();
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ use tsc_stream::{
|
|||||||
};
|
};
|
||||||
use tsclientlib::ClientId;
|
use tsclientlib::ClientId;
|
||||||
|
|
||||||
|
use crate::audio::{AudioHandle, AudioIn};
|
||||||
use crate::voice::VoiceCmd;
|
use crate::voice::VoiceCmd;
|
||||||
use crate::{Event, SessionId};
|
use crate::{Event, SessionId};
|
||||||
|
|
||||||
@@ -138,6 +139,7 @@ impl StreamHandle {
|
|||||||
voice: mpsc::UnboundedSender<VoiceCmd>,
|
voice: mpsc::UnboundedSender<VoiceCmd>,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
audio: Option<AudioHandle>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let (tx, rx) = mpsc::unbounded_channel();
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
let task = StreamTask {
|
let task = StreamTask {
|
||||||
@@ -146,6 +148,7 @@ impl StreamHandle {
|
|||||||
voice,
|
voice,
|
||||||
events,
|
events,
|
||||||
frames,
|
frames,
|
||||||
|
audio,
|
||||||
tx: tx.clone(),
|
tx: tx.clone(),
|
||||||
sink: None,
|
sink: None,
|
||||||
clients: BTreeMap::new(),
|
clients: BTreeMap::new(),
|
||||||
@@ -165,6 +168,8 @@ struct StreamTask {
|
|||||||
voice: mpsc::UnboundedSender<VoiceCmd>,
|
voice: mpsc::UnboundedSender<VoiceCmd>,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
frames: broadcast::Sender<StreamFrame>,
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
/// Where the audio of watched streams plays, if the session has audio.
|
||||||
|
audio: Option<AudioHandle>,
|
||||||
/// For the sinks handed out.
|
/// For the sinks handed out.
|
||||||
tx: mpsc::UnboundedSender<StreamInput>,
|
tx: mpsc::UnboundedSender<StreamInput>,
|
||||||
/// The sink of our live stream.
|
/// The sink of our live stream.
|
||||||
@@ -299,8 +304,20 @@ impl StreamTask {
|
|||||||
let state = match event {
|
let state = match event {
|
||||||
WatchEvent::Accepted => WatchState::Connecting,
|
WatchEvent::Accepted => WatchState::Connecting,
|
||||||
WatchEvent::Connected => WatchState::Connected,
|
WatchEvent::Connected => WatchState::Connected,
|
||||||
WatchEvent::Ended(reason) => WatchState::Ended(reason),
|
WatchEvent::Ended(reason) => {
|
||||||
|
if let Some(audio) = &self.audio {
|
||||||
|
audio.send(AudioIn::StreamEnded(id.clone()));
|
||||||
|
}
|
||||||
|
WatchState::Ended(reason)
|
||||||
|
}
|
||||||
WatchEvent::Frame(frame) => {
|
WatchEvent::Frame(frame) => {
|
||||||
|
if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) {
|
||||||
|
audio.send(AudioIn::StreamAudio {
|
||||||
|
stream: id.clone(),
|
||||||
|
time: frame.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer(),
|
||||||
|
data: frame.data.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
|
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -322,6 +339,9 @@ impl StreamTask {
|
|||||||
}
|
}
|
||||||
for watched in self.streams.watching() {
|
for watched in self.streams.watching() {
|
||||||
let stream_id = watched.id().to_owned();
|
let stream_id = watched.id().to_owned();
|
||||||
|
if let Some(audio) = &self.audio {
|
||||||
|
audio.send(AudioIn::StreamEnded(stream_id.clone()));
|
||||||
|
}
|
||||||
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
|
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
|
||||||
}
|
}
|
||||||
if self.streams.directory().iter().next().is_some() {
|
if self.streams.directory().iter().next().is_some() {
|
||||||
@@ -416,13 +436,18 @@ mod tests {
|
|||||||
.expect("timed out")
|
.expect("timed out")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake server.
|
type Handles = Arc<Vec<StreamHandle>>;
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
|
||||||
async fn stream_tasks_through_fake_server() {
|
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake
|
||||||
let (events, mut rx) = broadcast::channel(4096);
|
/// server; `audio` is the viewer's audio thread.
|
||||||
let (frames, mut frames_rx) = broadcast::channel(4096);
|
fn pair(
|
||||||
|
audio: Option<AudioHandle>,
|
||||||
|
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
|
||||||
|
let (events, rx) = broadcast::channel(4096);
|
||||||
|
let (frames, frames_rx) = broadcast::channel(4096);
|
||||||
let mut voices = Vec::new();
|
let mut voices = Vec::new();
|
||||||
let mut handles = Vec::new();
|
let mut handles = Vec::new();
|
||||||
|
let mut audio = audio;
|
||||||
for (i, clid) in CLIENTS.into_iter().enumerate() {
|
for (i, clid) in CLIENTS.into_iter().enumerate() {
|
||||||
let (voice, voice_rx) = mpsc::unbounded_channel();
|
let (voice, voice_rx) = mpsc::unbounded_channel();
|
||||||
let config = PeerConfig::loopback();
|
let config = PeerConfig::loopback();
|
||||||
@@ -434,6 +459,7 @@ mod tests {
|
|||||||
voice,
|
voice,
|
||||||
events.clone(),
|
events.clone(),
|
||||||
frames.clone(),
|
frames.clone(),
|
||||||
|
if session == 2 { audio.take() } else { None },
|
||||||
));
|
));
|
||||||
voices.push(voice_rx);
|
voices.push(voice_rx);
|
||||||
}
|
}
|
||||||
@@ -452,12 +478,20 @@ mod tests {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
(handles, rx, frames_rx)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Session 1 streams (auto-accepting), session 2 watches; returns the sink
|
||||||
|
/// once the viewer is connected.
|
||||||
|
async fn live_and_watching(
|
||||||
|
handles: &Handles,
|
||||||
|
rx: &mut broadcast::Receiver<Event>,
|
||||||
|
) -> StreamSink {
|
||||||
let setup = StreamSetup { name: "t".into(), ..Default::default() };
|
let setup = StreamSetup { name: "t".into(), ..Default::default() };
|
||||||
handles[0].send(StreamInput::Start { setup, auto_accept: true });
|
handles[0].send(StreamInput::Start { setup, auto_accept: true });
|
||||||
// Live for the streamer and listed for the viewer, in either order.
|
// Live for the streamer and listed for the viewer, in either order.
|
||||||
let (mut sink, mut listed) = (None, false);
|
let (mut sink, mut listed) = (None, false);
|
||||||
wait(&mut rx, |e| {
|
wait(rx, |e| {
|
||||||
match e {
|
match e {
|
||||||
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
|
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
|
||||||
sink = Some(s);
|
sink = Some(s);
|
||||||
@@ -468,13 +502,21 @@ mod tests {
|
|||||||
(sink.is_some() && listed).then_some(())
|
(sink.is_some() && listed).then_some(())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
let sink = sink.unwrap();
|
|
||||||
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
|
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
|
||||||
wait(&mut rx, |e| match e {
|
wait(rx, |e| match e {
|
||||||
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
sink.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn stream_tasks_through_fake_server() {
|
||||||
|
// The viewer's audio thread.
|
||||||
|
let (audio, audio_rx) = AudioHandle::channel();
|
||||||
|
let (handles, mut rx, mut frames_rx) = pair(Some(audio));
|
||||||
|
let sink = live_and_watching(&handles, &mut rx).await;
|
||||||
|
|
||||||
// Frames from the sink reach the viewer's frame bus.
|
// Frames from the sink reach the viewer's frame bus.
|
||||||
let feeder = tokio::spawn({
|
let feeder = tokio::spawn({
|
||||||
@@ -518,6 +560,20 @@ mod tests {
|
|||||||
assert!(!sink.is_live());
|
assert!(!sink.is_live());
|
||||||
feeder.await.unwrap();
|
feeder.await.unwrap();
|
||||||
|
|
||||||
|
// Stream audio went to the viewer's audio thread, in 20 ms steps,
|
||||||
|
// and the ended stream was forgotten there.
|
||||||
|
let received: Vec<AudioIn> = audio_rx.try_iter().collect();
|
||||||
|
let times: Vec<u64> = received
|
||||||
|
.iter()
|
||||||
|
.filter_map(|m| match m {
|
||||||
|
AudioIn::StreamAudio { stream, time, .. } if stream == "s-1" => Some(*time),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert!(times.len() >= 10, "{} audio frames", times.len());
|
||||||
|
assert!(times.windows(2).all(|w| w[1] > w[0] && (w[1] - w[0]) % 960 == 0), "{times:?}");
|
||||||
|
assert!(matches!(received.last(), Some(AudioIn::StreamEnded(id)) if id == "s-1"));
|
||||||
|
|
||||||
// Errors surface as events.
|
// Errors surface as events.
|
||||||
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
|
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
|
||||||
wait(&mut rx, |e| match e {
|
wait(&mut rx, |e| match e {
|
||||||
@@ -527,4 +583,77 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
handles[1].send(StreamInput::Shutdown("bye".into()));
|
handles[1].send(StreamInput::Shutdown("bye".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The whole path: test pattern → VP8 → stream task → str0m peers on
|
||||||
|
/// loopback → the viewer's frame bus → decoder. The pictures show the
|
||||||
|
/// moving rectangle.
|
||||||
|
#[cfg(feature = "media")]
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn test_pattern_through_stream_tasks() {
|
||||||
|
use std::sync::mpsc as std_mpsc;
|
||||||
|
|
||||||
|
use tsc_media::capture::SourceId;
|
||||||
|
use tsc_media::{Codec, Codecs};
|
||||||
|
|
||||||
|
use crate::media::{Streamer, StreamerConfig, VideoPipeline, rectangle_span};
|
||||||
|
|
||||||
|
let (handles, mut rx, mut frames_rx) = pair(None);
|
||||||
|
let sink = live_and_watching(&handles, &mut rx).await;
|
||||||
|
let codecs = Arc::new(Codecs::new());
|
||||||
|
let config = StreamerConfig {
|
||||||
|
source: SourceId::Synthetic,
|
||||||
|
synthetic_size: (320, 240),
|
||||||
|
bitrate_kbps: 1500,
|
||||||
|
..StreamerConfig::default()
|
||||||
|
};
|
||||||
|
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||||
|
streamer.attach(Arc::new(sink.clone()));
|
||||||
|
|
||||||
|
let (tx, pictures) = std_mpsc::channel();
|
||||||
|
let pipeline = VideoPipeline::new(
|
||||||
|
codecs,
|
||||||
|
move |picture| {
|
||||||
|
let _ = tx.send(picture);
|
||||||
|
},
|
||||||
|
{
|
||||||
|
let handles = handles.clone();
|
||||||
|
move || handles[1].send(StreamInput::RequestKeyframe { stream_id: "s-1".into() })
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let input = pipeline.input();
|
||||||
|
let forward = tokio::spawn(async move {
|
||||||
|
while let Ok(f) = frames_rx.recv().await {
|
||||||
|
input.push(f.frame);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let spans = tokio::task::spawn_blocking(move || {
|
||||||
|
let mut spans = Vec::new();
|
||||||
|
while spans.len() < 15 {
|
||||||
|
let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture");
|
||||||
|
assert_eq!((picture.width, picture.height), (320, 240));
|
||||||
|
spans.push(rectangle_span(&picture));
|
||||||
|
}
|
||||||
|
spans
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
for (a, b) in &spans {
|
||||||
|
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
|
||||||
|
}
|
||||||
|
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
|
||||||
|
let stats = pipeline.stats();
|
||||||
|
assert_eq!(stats.codec, Some(Codec::Vp8));
|
||||||
|
assert!(stats.error.is_none(), "{stats:?}");
|
||||||
|
let sent = streamer.stats();
|
||||||
|
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
|
||||||
|
|
||||||
|
handles[0].send(StreamInput::Stop);
|
||||||
|
wait(&mut rx, |e| match e {
|
||||||
|
Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
forward.abort();
|
||||||
|
drop(streamer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user