Merge wip/stream-ui: media pipeline, streams UI, audio settings, push-to-talk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 15:51:03 +00:00
commit 66936325f2
28 files changed
+5385 -264

No files matched your search

Generated
+7
View File
@@ -8720,6 +8720,7 @@ dependencies = [
"tracing",
"tsc-audio",
"tsc-gateway-proto",
"tsc-media",
"tsc-model",
"tsc-observer",
"tsc-query",
@@ -8880,13 +8881,17 @@ dependencies = [
"chrono",
"dirs",
"png",
"serde",
"serde_json",
"slint",
"slint-build",
"tokio",
"tracing",
"tracing-subscriber",
"tsc-audio",
"tsc-core",
"tsc-model",
"tsc-platform",
"tsc-query",
"tsc-store",
"tsclientlib",
@@ -8936,12 +8941,14 @@ dependencies = [
"dirs",
"futures",
"futures-util",
"png",
"serde_json",
"tokio",
"tokio-tungstenite 0.30.0",
"tracing",
"tracing-subscriber",
"tsc-audio",
"tsc-core",
"tsc-gateway-proto",
"tsc-model",
"tsc-observer",
+18 -4
View File
@@ -36,9 +36,12 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/tsc-gateway` (`tsgw`) + `tsc-gateway-proto`: companion gateway for server admins. Users log in
with their TeamSpeak identity and get presence, channel chat and history without joining voice,
limited by their server permissions ([admin guide](docs/gateway-admin.md))
- `crates/tsc-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio
- `crates/tsc-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio;
the media pipeline for streams (capture → VP8 + Opus → stream, stream → decoder)
- `crates/tsc-ui` (`tsc-desktop`): Slint desktop app: servers, channel tree with talking indicators,
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
TeamSpeak 6 streams: watch in a viewer, share the screen with sound
- `crates/tsc-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
clients through a TS6 server
@@ -52,12 +55,14 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
voice in a foreground service, screen sharing through MediaProjection, MediaCodec, Keystore
passwords). It builds; it has not run on a device yet ([docs/android.md](docs/android.md))
Screen sharing has its protocol and transport layer (`tsc-stream`); capture, codecs and the UI
for it are in progress.
Screen sharing works between our clients through a TeamSpeak 6 server (VP8 video, Opus audio);
interop with the official TeamSpeak 6 client is not verified yet.
| Connected with voice | Observing invisibly through the gateway |
|---|---|
| ![voice](docs/screenshots/desktop-voice.png) | ![observe](docs/screenshots/desktop-observe.png) |
| **Watching a stream** | **Sharing the screen** |
| ![viewer](docs/screenshots/desktop-stream-viewer.png) | ![share](docs/screenshots/desktop-share-dialog.png) |
## Try it
@@ -74,6 +79,10 @@ cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav
# Streams (TeamSpeak 6): share the test pattern (or --source x11), watch and decode it
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick eye stream watch --save-frame shot.png &
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me stream start --synthetic --auto-accept
# ServerQuery (dev password tsc-dev-admin): invisible presence and relay chat
cargo run -p tsctl -- observe ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted
cargo run -p tsctl -- relay ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted --channel 1
@@ -88,9 +97,14 @@ scripts/it-smoke.sh # all of the above, on both servers
Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect <addr> listen|chat|raw`.
`tsctl --help` lists all options.
Development switches of the desktop app (environment variables): `TSC_DATA_DIR` (database),
`TSC_AUTOCONNECT=voice|observe`, `TSC_SCREENSHOT=<png>` (with `TSC_SCREENSHOT_DELAY`),
`TSC_DEMO_STREAM=1` (a local test stream in the viewer, no server needed),
`TSC_OPEN=share|settings[:<tab>]|about|client`, `TSC_AUTOWATCH=1`, `TSC_AUTOSHARE=test-pattern`.
Building on Linux needs the ALSA headers (`libasound2-dev`), fontconfig and xkbcommon
headers for the UI (`libfontconfig1-dev libxkbcommon-dev`), plus CMake and a C compiler for
the bundled libopus.
the bundled libopus; for streams also libvpx and PipeWire (see [docs/media.md](docs/media.md#build-requirements)).
## License
+9
View File
@@ -12,6 +12,14 @@ publish.workspace = true
default = ["audio-device"]
# Capture and play audio through the system's devices.
audio-device = ["tsc-audio/device"]
# The `media` module: capture and video codecs for streams, with whatever
# tsc-media backends are enabled (e.g. MediaCodec and a registered capture
# source on Android).
media = ["dep:tsc-media"]
# `media` with tsc-media's desktop backends: libvpx, OpenH264 loaded at
# runtime, X11 and PipeWire on Linux. Not for Android (libvpx does not
# cross-compile there).
media-desktop = ["media", "tsc-media/default"]
[dependencies]
anyhow = "1"
@@ -23,6 +31,7 @@ tokio-tungstenite = "0.30"
tracing = "0.1"
tsc-audio = { path = "../tsc-audio", default-features = false }
tsc-gateway-proto = { path = "../tsc-gateway-proto" }
tsc-media = { path = "../tsc-media", default-features = false, features = ["str0m"], optional = true }
tsc-model = { path = "../tsc-model" }
tsc-observer = { path = "../tsc-observer" }
tsc-query = { path = "../tsc-query" }
+192 -24
View File
@@ -8,7 +8,8 @@
//! 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::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::thread;
use std::time::{Duration, Instant};
@@ -17,9 +18,10 @@ use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsc_audio::pcm::{self, FRAME_SAMPLES};
use tsc_audio::settings::TransmitMode;
use tsc_audio::vad::SILENCE_DB;
use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
pub(crate) enum AudioIn {
Packet(InAudioBuf),
@@ -27,24 +29,46 @@ pub(crate) enum AudioIn {
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),
/// 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 {
tx: std_mpsc::Sender<AudioIn>,
}
@@ -53,6 +77,13 @@ impl AudioHandle {
pub fn send(&self, msg: AudioIn) {
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
@@ -68,25 +99,33 @@ const PLAYBACK_CAPACITY_MS: u32 = 200;
const DEVICE_LATENCY_MS: u32 = 20;
/// How long the loop sleeps between rounds.
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.
/// no device) are reported through `errors`.
/// no device) and the microphone level are reported through `events`.
pub(crate) fn spawn(
outgoing: mpsc::UnboundedSender<OutPacket>,
errors: mpsc::UnboundedSender<String>,
voice_activation: bool,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) -> 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, settings))
.spawn(move || run(rx, outgoing, events, settings))
.expect("spawn audio thread");
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.
struct Pipeline {
settings: AudioSettings,
@@ -101,6 +140,11 @@ struct Pipeline {
input_muted: bool,
output_muted: 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.
#[cfg(test)]
tap: Vec<f32>,
@@ -121,6 +165,9 @@ impl Pipeline {
input_muted: false,
output_muted: false,
was_sending: false,
level_peak: None,
streams: HashMap::new(),
stream_volumes: HashMap::new(),
settings,
#[cfg(test)]
tap: Vec::new(),
@@ -154,9 +201,73 @@ impl Pipeline {
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),
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.
/// `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)) {
@@ -175,6 +286,8 @@ impl Pipeline {
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 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 {
TransmitMode::PushToTalk => self.ptt,
TransmitMode::VoiceActivation => voice,
@@ -232,18 +345,21 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
errors: mpsc::UnboundedSender<String>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) {
let error = |message: String| {
let _ = events.send(AudioEvent::Error(message));
};
#[cfg(feature = "audio-device")]
let mut devices = devices::Devices::new(&settings);
#[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) {
Ok(p) => p,
Err(e) => {
let _ = errors.send(e.to_string());
error(e.to_string());
return;
}
};
@@ -253,6 +369,7 @@ fn run(
// 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();
let mut level_clock = Instant::now();
loop {
// Control messages and incoming voice.
@@ -271,7 +388,7 @@ fn run(
}
#[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"))]
let playing = {
// 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);
}
}
#[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};
@@ -324,7 +447,7 @@ mod devices {
&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 {
DeviceEvent::Opened { name, fallback: false } => {
debug!(%name, "{what} opened");
@@ -336,7 +459,7 @@ mod devices {
DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"),
DeviceEvent::Unavailable(e) => format!("no {what}: {e}"),
};
let _ = errors.send(message);
error(message);
}
impl Devices {
@@ -362,13 +485,13 @@ mod devices {
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
errors: &mpsc::UnboundedSender<String>,
error: &impl Fn(String),
) -> bool {
if let Some(event) = self.playback.poll() {
report(errors, "speakers", event);
report(error, "speakers", event);
}
if let Some(event) = self.capture.poll() {
report(errors, "microphone", event);
report(error, "microphone", event);
}
// Mixer → speakers, keeping the configured amount queued.
@@ -410,7 +533,6 @@ mod devices {
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::*;
@@ -529,6 +651,52 @@ mod tests {
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]
fn settings_are_sanitized() {
let mut p = pipeline(TransmitMode::PushToTalk);
+111 -5
View File
@@ -13,10 +13,15 @@
//!
//! 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.
//! [`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 gateway;
#[cfg(feature = "media")]
pub mod media;
mod query;
mod route;
mod session;
@@ -27,8 +32,11 @@ use std::collections::HashMap;
use std::sync::Arc;
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 crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use route::{ChatRoute, Dedup, route_chat};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
@@ -86,11 +94,33 @@ pub enum Command {
session: SessionId,
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 {
session: SessionId,
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
/// [`Event::StreamState`]; frames go in through the sink of
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
@@ -134,6 +164,13 @@ pub enum Command {
session: SessionId,
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.
CloseSession {
session: SessionId,
@@ -172,6 +209,8 @@ pub struct SessionState {
pub presence_source: Option<Source>,
/// Our own channel while voice-connected.
pub own_channel: Option<ChannelId>,
/// Our own client id while voice-connected.
pub own_client: Option<u16>,
pub input_muted: bool,
pub output_muted: bool,
pub transmitting: bool,
@@ -205,6 +244,20 @@ pub enum Event {
client: u16,
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 {
session: SessionId,
message: String,
@@ -248,6 +301,7 @@ pub struct Engine {
commands: mpsc::UnboundedSender<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
runtime: tokio::runtime::Handle,
}
impl Engine {
@@ -258,7 +312,13 @@ impl Engine {
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
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) {
@@ -281,8 +341,26 @@ async fn run(
frames: broadcast::Sender<StreamFrame>,
) {
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 {
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 let Some(s) = sessions.remove(&id) {
s.send(command);
@@ -291,11 +369,33 @@ async fn run(
}
sessions
.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);
}
}
/// 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 {
match command {
Command::ConnectVoice { session, .. }
@@ -318,6 +418,12 @@ fn command_session(command: &Command) -> SessionId {
| Command::WatchStream { session, .. }
| Command::LeaveStream { session, .. }
| Command::RequestStreamKeyframe { session, .. }
| Command::SetStreamVolume { session, .. }
| Command::SetClientVolume { session, .. }
| Command::SetClientMuted { 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
+52 -8
View File
@@ -5,9 +5,11 @@ use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsc_audio::AudioSettings;
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::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
@@ -24,9 +26,10 @@ impl SessionHandle {
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
) -> Self {
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 }
}
@@ -42,7 +45,7 @@ enum SourceEvent {
Gateway(u64, GatewayEvent),
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
AudioError(String),
Audio(u64, AudioEvent),
}
struct Session {
@@ -58,6 +61,7 @@ struct Session {
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
audio_settings: AudioSettings,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
@@ -75,6 +79,7 @@ impl Session {
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
@@ -90,6 +95,7 @@ impl Session {
query: None,
query_presence: None,
audio: None,
audio_settings,
streams: None,
stream_peer: PeerConfig::default(),
frames,
@@ -160,12 +166,13 @@ impl Session {
self.stream_peer = options.stream_peer.clone();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
self.audio = None;
if options.audio {
let (out_tx, out_rx) = mpsc::unbounded_channel();
let (err_tx, err_rx) = mpsc::unbounded_channel();
self.audio = Some(audio::spawn(out_tx, err_tx, false));
let (audio_tx, audio_rx) = mpsc::unbounded_channel();
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(err_rx, SourceEvent::AudioError);
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
tokio::spawn(voice::run(*options, cmd_rx, ev_tx));
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
@@ -264,6 +271,29 @@ impl Session {
}
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, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
}
@@ -287,7 +317,7 @@ impl Session {
Command::RequestStreamKeyframe { 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));
}
}
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"),
}
}
@@ -398,6 +433,7 @@ impl Session {
match e {
VoiceEvent::Connected { name, flavor, own_client } => {
self.state.voice = VoiceState::Connected;
self.state.own_client = Some(own_client);
self.emit_state();
let capabilities = flavor.capabilities();
if capabilities.streams
@@ -410,12 +446,19 @@ impl Session {
voice.clone(),
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
));
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
}
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 {
let clients: BTreeMap<_, _> =
p.clients.values().map(|c| (c.id, c.streaming)).collect();
@@ -459,6 +502,7 @@ impl Session {
self.audio = None;
self.state.voice = VoiceState::Disconnected;
self.state.own_channel = None;
self.state.own_client = None;
self.emit_state();
if let Some(reason) = reason {
self.error(format!("voice: {reason}"));
+138 -9
View File
@@ -22,6 +22,7 @@ use tsc_stream::{
};
use tsclientlib::ClientId;
use crate::audio::{AudioHandle, AudioIn};
use crate::voice::VoiceCmd;
use crate::{Event, SessionId};
@@ -138,6 +139,7 @@ impl StreamHandle {
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio: Option<AudioHandle>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let task = StreamTask {
@@ -146,6 +148,7 @@ impl StreamHandle {
voice,
events,
frames,
audio,
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
@@ -165,6 +168,8 @@ struct StreamTask {
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
/// Where the audio of watched streams plays, if the session has audio.
audio: Option<AudioHandle>,
/// For the sinks handed out.
tx: mpsc::UnboundedSender<StreamInput>,
/// The sink of our live stream.
@@ -299,8 +304,20 @@ impl StreamTask {
let state = match event {
WatchEvent::Accepted => WatchState::Connecting,
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) => {
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 });
return;
}
@@ -322,6 +339,9 @@ impl StreamTask {
}
for watched in self.streams.watching() {
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()) });
}
if self.streams.directory().iter().next().is_some() {
@@ -416,13 +436,18 @@ mod tests {
.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);
type Handles = Arc<Vec<StreamHandle>>;
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake
/// server; `audio` is the viewer's audio thread.
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 handles = Vec::new();
let mut audio = audio;
for (i, clid) in CLIENTS.into_iter().enumerate() {
let (voice, voice_rx) = mpsc::unbounded_channel();
let config = PeerConfig::loopback();
@@ -434,6 +459,7 @@ mod tests {
voice,
events.clone(),
frames.clone(),
if session == 2 { audio.take() } else { None },
));
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() };
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| {
wait(rx, |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
sink = Some(s);
@@ -468,13 +502,21 @@ mod tests {
(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 {
wait(rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
})
.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.
let feeder = tokio::spawn({
@@ -518,6 +560,20 @@ mod tests {
assert!(!sink.is_live());
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.
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
@@ -527,4 +583,77 @@ mod tests {
.await;
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-desktop")]
#[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);
}
}
+175
View File
@@ -0,0 +1,175 @@
//! The media pipeline through the engine and the TeamSpeak 6 development
//! server (dev/docker-compose.yml): one session streams the test pattern
//! (VP8 + Opus), another decodes it. Runs only with `TSC_LIVE=1`.
#![cfg(feature = "media-desktop")]
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
use tokio::time::timeout;
use tsc_core::media::tsc_media::capture::SourceId;
use tsc_core::media::tsc_media::capture::synthetic::RECT_COLOR;
use tsc_core::media::tsc_media::{Codec, Codecs, convert};
use tsc_core::media::{Streamer, StreamerConfig, Viewer, peer_config, stream_codec};
use tsc_core::stream::{PeerConfig, StreamSetup};
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}"))
}
async fn connect(
engine: &Engine,
events: &mut Receiver<Event>,
session: u64,
nick: &str,
peer: PeerConfig,
) {
let mut options = VoiceOptions::new("127.0.0.1:9988", nick);
options.stream_peer = peer;
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_test_pattern_decoded() {
if !live() {
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let codecs = Arc::new(Codecs::new());
let peer = peer_config(&codecs, PeerConfig::loopback());
let codec = stream_codec(&codecs, &peer).expect("an encoder");
assert_eq!(codec, Codec::Vp8);
let tag = std::process::id() % 10_000;
connect(&engine, &mut events, 1, &format!("m-streamer-{tag}"), peer.clone()).await;
connect(&engine, &mut events, 2, &format!("m-viewer-{tag}"), peer).await;
// Capture first (as the app does: the portal may ask), then go live.
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (640, 360),
bitrate_kbps: 2000,
codec,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let setup = StreamSetup { name: format!("media {tag}"), ..Default::default() };
engine.send(Command::StartStream { session: 1, setup, auto_accept: true });
// The viewer's list may update before the streamer goes live.
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;
streamer.attach(Arc::new(sink));
let (tx, pictures) = std_mpsc::channel();
let viewer = Viewer::start(&engine, 2, &id, codecs, move |picture| {
let _ = tx.send(picture);
});
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
wait_for(&mut events, "watching", |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,
})
.await;
// 60 decoded pictures (two seconds), each with the rectangle in the
// middle row, about a fifth of the width.
let widths = tokio::task::spawn_blocking(move || {
let mut widths = Vec::new();
while widths.len() < 60 {
let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture");
assert_eq!((picture.width, picture.height), (640, 360));
let rgba = convert::to_rgba_vec(&picture).unwrap();
let row = &rgba[(picture.height / 2 * picture.width * 4) as usize..]
[..(picture.width * 4) as usize];
let rect = row
.chunks_exact(4)
.filter(|p| p.iter().zip(RECT_COLOR).all(|(a, b)| a.abs_diff(b) <= 24))
.count();
widths.push(rect);
}
widths
})
.await
.unwrap();
assert!(widths.iter().all(|w| (120..=136).contains(w)), "{widths:?}");
let stats = viewer.stats();
assert!(stats.error.is_none(), "{stats:?}");
eprintln!("decoded {stats:?}, sent {:?}", streamer.stats());
engine.send(Command::StopStream { session: 1 });
wait_for(&mut events, "stream ended", |e| match e {
Event::StreamState { session: 1, state: StreamState::Ended(_) } => Some(()),
_ => None,
})
.await;
drop(viewer);
drop(streamer);
engine.send(Command::CloseSession { session: 1 });
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
+16 -3
View File
@@ -21,23 +21,36 @@ anyhow = "1.0.104"
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
dirs = "6"
png = "0.18"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tsc-core = { path = "../tsc-core" }
tsc-audio = { path = "../tsc-audio" }
tsc-core = { path = "../tsc-core", default-features = false, features = ["audio-device"] }
tsc-model = { path = "../tsc-model" }
# Crash reports and notices everywhere; hotkey backends on desktop (below).
tsc-platform = { path = "../tsc-platform", default-features = false }
tsc-query = { path = "../tsc-query" }
tsc-store = { path = "../tsc-store" }
tsclientlib = { path = "../proto/tsclientlib" }
# Android (tsc-android): no keyring backend (the app passes Keystore-backed
# secrets) and no winit/femtovg (the app picks Slint's Android backend).
# Desktop: the keyring for passwords, stream media with libvpx, OpenH264, X11
# and PipeWire, global hotkeys through the portal and X11.
[target.'cfg(not(target_os = "android"))'.dependencies]
slint = { version = "1.18", features = ["renderer-software"] }
tsc-core = { path = "../tsc-core", default-features = false, features = ["media-desktop"] }
tsc-platform = { path = "../tsc-platform" }
tsc-store = { path = "../tsc-store", features = ["keyring"] }
# Android (tsc-android): no keyring backend (the app passes Keystore-backed
# secrets), no winit/femtovg (the app picks Slint's Android backend), stream
# media through MediaCodec and the app's capture source.
[target.'cfg(target_os = "android")'.dependencies]
slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "renderer-software"] }
tsc-core = { path = "../tsc-core", default-features = false, features = ["media"] }
[dev-dependencies]
serde_json = "1"
[build-dependencies]
slint-build = "1.18"
+626 -53
View File
@@ -1,20 +1,36 @@
//! Application state on the UI thread, wired to the engine.
//!
//! Streams (the streams panel, sharing, the viewer) are in `streams.rs`,
//! the settings page's data in `settings.rs`.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use tokio::runtime::Runtime;
use tracing::warn;
use tsc_core::stream::StreamInfo;
use tsc_core::{
Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, VoiceState,
AudioSettings, Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions,
VoiceState,
};
use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows};
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows};
use tsc_platform::{crash, notices};
use tsc_store::{Bookmark, MemorySecrets, QueryConfig, QueryTransport, Secrets, Store};
use crate::hotkey::GlobalPtt;
use crate::settings::{
self, AUDIO_KEY, CLIENT_PLAYBACK_KEY, ClientPlayback, ClientPlaybackMap, DeviceChoices, UI_KEY,
UiSettings,
};
use crate::streams::{Share, Watch};
use crate::video::Video;
slint::include_modules!();
/// Secrets in the OS keyring, or in memory when there is none (headless
@@ -68,21 +84,27 @@ struct Tab {
}
/// What we know about one server session.
struct SessionView {
state: SessionState,
presence: Arc<Presence>,
pub(crate) struct SessionView {
pub state: SessionState,
pub capabilities: Capabilities,
pub presence: Arc<Presence>,
collapsed: HashSet<ChannelId>,
talking: HashSet<u16>,
tabs: Vec<Tab>,
current_tab: usize,
/// The own channel's tab was focused for this voice connection.
focused_own_channel: bool,
/// The streams in our channel (TeamSpeak 6).
pub streams: Vec<StreamInfo>,
/// Clients whose stored volume was sent for this voice connection.
applied_playback: HashSet<u16>,
}
impl Default for SessionView {
fn default() -> Self {
Self {
state: SessionState::default(),
capabilities: Capabilities::default(),
presence: Arc::default(),
collapsed: HashSet::new(),
talking: HashSet::new(),
@@ -94,30 +116,83 @@ impl Default for SessionView {
}],
current_tab: 0,
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
}
}
}
struct App {
ui: slint::Weak<MainWindow>,
impl SessionView {
/// Streams can be watched and shared: TeamSpeak 6, connected with voice.
pub fn streams_available(&self) -> bool {
self.capabilities.streams && self.state.voice == VoiceState::Connected
}
/// A client's nickname, or its id.
pub fn nickname(&self, client: u16) -> String {
self.presence
.clients
.get(&client)
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
}
}
pub(crate) struct App {
pub ui: slint::Weak<MainWindow>,
store: Store,
secrets: Box<dyn Secrets>,
engine: Engine,
pub engine: Engine,
identity: tsclientlib::Identity,
bookmarks: Vec<Bookmark>,
current: Option<i64>,
sessions: HashMap<i64, SessionView>,
pub current: Option<i64>,
pub sessions: HashMap<i64, SessionView>,
status: String,
pub settings: UiSettings,
audio: AudioSettings,
/// Audio settings changed since they were last stored.
audio_dirty: bool,
inputs: DeviceChoices,
outputs: DeviceChoices,
playback: ClientPlaybackMap,
/// The client in the volume dialog: session, client id, unique id.
playback_dialog: Option<(i64, u16, Option<String>)>,
mic_test: bool,
ptt: GlobalPtt,
pub video: Video,
/// Our stream.
pub share: Option<Share>,
/// The capture for a share is being started.
pub share_busy: bool,
pub share_error: String,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// Stream volume in percent, kept between streams.
pub stream_volume: f32,
/// `TSC_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
/// `TSC_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
/// `TSC_OPEN=client`: open the volume dialog of the first other client.
open_client_pending: bool,
/// The notices are in the About page's model.
notices_loaded: bool,
}
thread_local! {
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
}
fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
pub(crate) fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
APP.with(|app| app.borrow_mut().as_mut().map(f))
}
/// Run `f` on the app from another thread, on the UI thread.
pub(crate) fn later(f: impl FnOnce(&mut App) + Send + 'static) {
let _ = slint::invoke_from_event_loop(move || {
with_app(f);
});
}
/// Start options for [`run`].
#[derive(Default)]
pub struct RunOptions {
@@ -180,6 +255,9 @@ impl HostedEngine {
/// Run the app on the current thread until the window closes. The Slint
/// platform must be set up before (the default backend on desktop).
pub fn run(options: RunOptions) -> Result<()> {
// Crash reports: the hook first, recording once the setting is known.
crash::set_app_version(env!("CARGO_PKG_VERSION"));
crash::install(crash::default_dir(), false);
let (own_runtime, hosted) = match options.engine {
Some(hosted) => (None, hosted),
None => {
@@ -192,8 +270,13 @@ pub fn run(options: RunOptions) -> Result<()> {
// Development switches: TSC_DATA_DIR isolates the database,
// TSC_AUTOCONNECT=voice|observe connects the first bookmark on start,
// TSC_SCREENSHOT=<png> saves the window after TSC_SCREENSHOT_DELAY seconds and exits.
let dir = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) {
// TSC_SCREENSHOT=<png> saves the window after TSC_SCREENSHOT_DELAY seconds and exits,
// TSC_DEMO_STREAM=1 shows a local test stream in the viewer,
// TSC_OPEN=share|settings[:<tab>]|about|client opens that on start (client: the
// volume dialog of the first other client once connected), TSC_AUTOWATCH=1
// watches the first stream that shows up, TSC_AUTOSHARE=test-pattern shares
// the test pattern (accepting everyone) once connected to a TeamSpeak 6 server.
let dir: PathBuf = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) {
(Some(dir), _) => dir,
(None, Some(dir)) => dir.into(),
(None, None) => dirs::data_dir().unwrap_or_else(|| ".".into()).join("tsc"),
@@ -209,9 +292,31 @@ pub fn run(options: RunOptions) -> Result<()> {
identity
}
};
let settings: UiSettings = store.setting(UI_KEY).ok().flatten().unwrap_or_default();
crash::set_enabled(settings.crash_reports);
crash::test_crash_if_requested();
let audio: AudioSettings = store.setting(AUDIO_KEY).ok().flatten().unwrap_or_default();
let playback: ClientPlaybackMap =
store.setting(CLIENT_PLAYBACK_KEY).ok().flatten().unwrap_or_default();
engine.send(Command::SetAudioSettings(Box::new(audio.clone())));
let ui = MainWindow::new()?;
// Wayland and X11 find the desktop file (and icon) by this id.
#[cfg(not(target_os = "android"))]
if let Err(e) = slint::set_xdg_app_id(tsc_platform::APP_ID) {
warn!("cannot set the app id: {e}");
}
let bookmarks = store.bookmarks()?;
let ptt = GlobalPtt::start(
&runtime,
|status| later(move |app| app.set_ptt_status(status)),
|on| later(move |app| app.command(|session| Command::SetTransmitting { session, on })),
);
if settings.global_ptt {
ptt.set(Some(settings.ptt_key.clone()));
}
let video = Video::new(&dir, settings.openh264);
let demo = std::env::var("TSC_DEMO_STREAM").is_ok_and(|v| v == "1");
let app = App {
ui: ui.as_weak(),
store,
@@ -222,10 +327,36 @@ pub fn run(options: RunOptions) -> Result<()> {
bookmarks,
sessions: HashMap::new(),
status: "Ready".into(),
settings,
audio,
audio_dirty: false,
inputs: DeviceChoices::default(),
outputs: DeviceChoices::default(),
playback,
playback_dialog: None,
mic_test: false,
ptt,
video,
share: None,
share_busy: false,
share_error: String::new(),
watch: None,
stream_volume: 100.0,
demo,
autoshare: std::env::var("TSC_AUTOSHARE").is_ok_and(|v| v == "test-pattern"),
open_client_pending: std::env::var("TSC_OPEN").is_ok_and(|v| v == "client"),
notices_loaded: false,
};
APP.with(|a| *a.borrow_mut() = Some(app));
wire_callbacks(&ui);
with_app(|app| app.refresh_all());
with_app(|app| {
app.refresh_all();
app.refresh_settings_flags();
app.refresh_crash_notice();
if app.demo {
app.start_demo();
}
});
// Engine events -> UI thread, until the event loop is gone.
runtime.spawn(async move {
@@ -238,6 +369,11 @@ pub fn run(options: RunOptions) -> Result<()> {
}
}
});
// Once a second: stream statistics, stored settings.
let ticker = slint::Timer::default();
ticker.start(slint::TimerMode::Repeated, Duration::from_secs(1), || {
with_app(|app| app.tick());
});
match std::env::var("TSC_AUTOCONNECT").as_deref() {
Ok("voice") => {
@@ -248,30 +384,57 @@ pub fn run(options: RunOptions) -> Result<()> {
}
_ => {}
}
match std::env::var("TSC_OPEN").as_deref() {
Ok("share") => ui.invoke_open_share_dialog(),
Ok("about") => {
with_app(|app| app.load_notices());
ui.set_show_about(true);
}
Ok(open) if open.starts_with("settings") => {
with_app(|app| app.open_settings());
let tab = open.strip_prefix("settings:").and_then(|t| t.parse().ok());
ui.set_settings_tab(tab.unwrap_or(0));
ui.set_settings_open(true);
}
_ => {}
}
let _screenshot_timer = std::env::var_os("TSC_SCREENSHOT").map(|path| {
let delay =
std::env::var("TSC_SCREENSHOT_DELAY").ok().and_then(|d| d.parse().ok()).unwrap_or(4);
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
std::time::Duration::from_secs(delay),
move || {
if let Some(ui) = weak.upgrade() {
if let Err(e) = save_screenshot(&ui, std::path::Path::new(&path)) {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
timer.start(slint::TimerMode::SingleShot, Duration::from_secs(delay), move || {
if let Some(ui) = weak.upgrade() {
if let Err(e) = save_screenshot(&ui, std::path::Path::new(&path)) {
eprintln!("screenshot failed: {e}");
}
},
);
let _ = ui.hide();
}
});
timer
});
ui.run()?;
// With our own engine, leave servers properly, so no ghost client stays
// behind until it times out. A hosted engine keeps its sessions.
let own = own_runtime.is_some();
let open = with_app(|app| {
app.save_audio();
app.watch = None;
app.share = None;
if own {
for id in app.sessions.keys() {
app.engine.send(Command::CloseSession { session: *id as u64 });
}
}
own && !app.sessions.is_empty()
});
APP.with(|a| a.borrow_mut().take());
if let Some(runtime) = own_runtime {
runtime.shutdown_timeout(std::time::Duration::from_secs(2));
if open == Some(true) {
runtime.block_on(async { tokio::time::sleep(Duration::from_millis(500)).await });
}
runtime.shutdown_timeout(Duration::from_secs(2));
}
Ok(())
}
@@ -349,6 +512,112 @@ fn wire_callbacks(ui: &MainWindow) {
bridge.on_delete_bookmark(|id| {
with_app(|app| app.delete_bookmark(id as i64));
});
// Streams.
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default());
bridge.on_start_share(|form| {
with_app(|app| app.start_share(form));
});
bridge.on_stop_share(|| {
with_app(|app| app.stop_share());
});
bridge.on_respond_viewer(|viewer, accept| {
with_app(|app| app.respond_viewer(viewer as u16, accept));
});
bridge.on_kick_viewer(|viewer| {
with_app(|app| app.kick_viewer(viewer as u16));
});
bridge.on_watch_stream(|id| {
with_app(|app| app.watch_stream(id.to_string()));
});
bridge.on_show_viewer(|| {
with_app(|app| app.show_viewer(true));
});
bridge.on_hide_viewer(|| {
with_app(|app| app.show_viewer(false));
});
bridge.on_leave_stream(|| {
with_app(|app| app.leave_stream());
});
bridge.on_set_stream_volume(|volume| {
with_app(|app| app.set_stream_volume(volume));
});
bridge.on_toggle_fullscreen(|| {
with_app(|app| app.toggle_fullscreen());
});
// Settings.
bridge.on_open_settings(|| {
with_app(|app| app.open_settings());
});
bridge.on_close_settings(|| {
with_app(|app| app.close_settings());
});
bridge.on_audio_changed(|form| {
with_app(|app| app.audio_changed(&form));
});
bridge.on_toggle_mic_test(|| {
with_app(|app| app.set_mic_test(!app.mic_test));
});
bridge.on_apply_ptt(|enabled, key| {
with_app(|app| app.apply_ptt(enabled, key.to_string()));
});
bridge.on_set_h264(|enabled| {
with_app(|app| app.set_h264(enabled));
});
bridge.on_download_h264(|| {
with_app(|app| app.download_h264());
});
bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false));
bridge.on_client_audio_changed(|form| {
with_app(|app| app.client_playback_changed(&form));
});
// Crash reports and notices.
bridge.on_set_crash_reports(|enabled| {
with_app(|app| app.set_crash_reports(enabled));
});
bridge.on_open_crash_folder(|| {
with_app(|app| {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) = result.and_then(|dir| open_path(&dir).map_err(|e| e.to_string())) {
app.set_status(format!("Cannot open the crash report folder: {e}"));
}
});
});
bridge.on_delete_crash_reports(|| {
with_app(|app| {
match crash::clear() {
Ok(n) => app.set_status(format!("Deleted {n} crash reports")),
Err(e) => app.set_status(format!("Cannot delete the crash reports: {e}")),
}
app.refresh_crash_notice();
});
});
bridge.on_dismiss_crash_notice(|| {
with_app(|app| {
if let Some(ui) = app.ui.upgrade() {
ui.global::<Bridge>().set_crash_notice(SharedString::new());
}
});
});
bridge.on_open_about(|| {
with_app(|app| app.load_notices());
});
}
/// Open a file or folder with the desktop's default application.
fn open_path(path: &Path) -> std::io::Result<()> {
#[cfg(windows)]
let mut command = std::process::Command::new("explorer");
#[cfg(target_os = "macos")]
let mut command = std::process::Command::new("open");
#[cfg(not(any(windows, target_os = "macos")))]
let mut command = std::process::Command::new("xdg-open");
let mut child = command.arg(path).spawn()?;
// Reap it without blocking the UI.
std::thread::spawn(move || child.wait());
Ok(())
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
@@ -367,7 +636,7 @@ fn time_of(ts_ms: i64) -> String {
.unwrap_or_default()
}
fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
ModelRc::from(Rc::new(VecModel::from(items)))
}
@@ -377,23 +646,33 @@ impl App {
Some(self.sessions.entry(id).or_default())
}
fn bookmark(&self, id: i64) -> Option<&Bookmark> {
pub fn view(&self) -> Option<&SessionView> {
self.current.and_then(|id| self.sessions.get(&id))
}
pub fn bookmark(&self, id: i64) -> Option<&Bookmark> {
self.bookmarks.iter().find(|b| b.id == id)
}
fn command(&self, f: impl FnOnce(u64) -> Command) {
pub fn command(&self, f: impl FnOnce(u64) -> Command) {
if let Some(id) = self.current {
self.engine.send(f(id as u64));
}
}
fn set_status(&mut self, text: impl Into<String>) {
pub fn set_status(&mut self, text: impl Into<String>) {
self.status = text.into();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_status_text(self.status.clone().into());
}
}
pub fn store_settings(&self) {
if let Err(e) = self.store.set_setting(UI_KEY, &self.settings) {
warn!(%e, "could not store settings");
}
}
fn connect_voice(&mut self) {
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
let mut options = VoiceOptions::new(&b.address, &b.nickname);
@@ -401,6 +680,7 @@ impl App {
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = b.default_channel.clone();
options.audio = true;
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
@@ -623,6 +903,10 @@ impl App {
if state.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
@@ -637,8 +921,11 @@ impl App {
}
self.refresh_servers();
self.refresh_toolbar();
self.refresh_streams();
self.autoshare();
}
Event::ServerInfo { session, name, flavor, .. } => {
Event::ServerInfo { session, name, flavor, capabilities } => {
self.sessions.entry(session as i64).or_default().capabilities = capabilities;
if self.current == Some(session as i64) {
let kind = match flavor {
tsc_model::ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"),
@@ -647,12 +934,19 @@ impl App {
};
self.set_status(format!("Connected to {name} ({kind})"));
}
self.refresh_streams();
self.autoshare();
}
Event::Presence { session, presence } => {
self.sessions.entry(session as i64).or_default().presence = presence;
self.apply_client_playback(session as i64);
if self.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
self.refresh_streams();
if self.open_client_pending {
self.open_first_client();
}
}
}
Event::Talking { session, client, talking } => {
@@ -666,10 +960,23 @@ impl App {
self.refresh_tree();
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => self.current == Some(s as i64),
None => self.mic_test,
};
if shown && let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
}
Event::MicrophoneTestError { message } => {
self.set_status(format!("Microphone test: {message}"))
}
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.
_ => {}
event => self.stream_event(event),
}
}
@@ -715,11 +1022,20 @@ impl App {
}
}
/// Once a second.
fn tick(&mut self) {
self.tick_streams();
if self.audio_dirty {
self.save_audio();
}
}
fn refresh_all(&mut self) {
self.refresh_servers();
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
self.refresh_streams();
}
fn refresh_servers(&self) {
@@ -752,11 +1068,7 @@ impl App {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.current.and_then(|id| self.bookmark(id));
let state = self
.current
.and_then(|id| self.sessions.get(&id))
.map(|v| v.state.clone())
.unwrap_or_default();
let state = self.view().map(|v| v.state.clone()).unwrap_or_default();
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
@@ -779,11 +1091,15 @@ impl App {
.into(),
);
bridge.set_status_text(self.status.clone().into());
if state.voice != VoiceState::Connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
fn refresh_tree(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
let Some(view) = self.view() else {
ui.global::<Bridge>().set_tree(model(Vec::new()));
return;
};
@@ -799,21 +1115,33 @@ impl App {
own: own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: view.collapsed.contains(&channel.id),
local_volume: 100,
..Default::default()
},
TreeRow::Client { depth, client } => TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
own: false,
talking: view.talking.contains(&client.id) || client.talking == Some(true),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
..Default::default()
},
TreeRow::Client { depth, client } => {
let playback = client
.uid
.as_ref()
.and_then(|uid| self.playback.get(uid))
.copied()
.unwrap_or_default();
TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
own: false,
talking: view.talking.contains(&client.id) || client.talking == Some(true),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
local_muted: playback.muted,
local_volume: (playback.volume * 100.0).round() as i32,
myself: view.state.own_client == Some(client.id),
..Default::default()
}
}
})
.collect();
ui.global::<Bridge>().set_tree(model(rows));
@@ -822,7 +1150,7 @@ impl App {
fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
let Some(view) = self.view() else {
bridge.set_tabs(model(vec![ChatTab { title: "Server".into(), ..Default::default() }]));
bridge.set_messages(model(Vec::new()));
return;
@@ -844,4 +1172,249 @@ impl App {
bridge.set_current_tab(view.current_tab as i32);
bridge.set_messages(model(view.tabs[view.current_tab].lines.clone()));
}
// Settings page.
fn open_settings(&mut self) {
let list = |devices: tsc_audio::Result<Vec<tsc_audio::device::DeviceInfo>>, input: bool| {
let devices = devices.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
});
devices
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect::<Vec<_>>()
};
let inputs = list(tsc_audio::device::input_devices(), true);
let outputs = list(tsc_audio::device::output_devices(), false);
self.inputs = DeviceChoices::new(&inputs, self.audio.input_device.as_deref());
self.outputs = DeviceChoices::new(&outputs, self.audio.output_device.as_deref());
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect());
bridge.set_input_devices(names(&self.inputs));
bridge.set_output_devices(names(&self.outputs));
bridge.set_audio(settings::audio_form(&self.audio, &self.inputs, &self.outputs));
bridge.set_global_ptt(self.settings.global_ptt);
bridge.set_ptt_key(self.settings.ptt_key.clone().into());
bridge.set_h264_enabled(self.settings.openh264);
self.refresh_h264();
}
fn close_settings(&mut self) {
self.set_mic_test(false);
self.save_audio();
}
fn audio_changed(&mut self, form: &AudioForm) {
let audio = settings::apply_audio_form(form, &self.audio, &self.inputs, &self.outputs);
if audio == self.audio {
return;
}
self.audio = audio;
self.audio_dirty = true;
self.engine.send(Command::SetAudioSettings(Box::new(self.audio.clone())));
}
fn save_audio(&mut self) {
if !self.audio_dirty {
return;
}
self.audio_dirty = false;
if let Err(e) = self.store.set_setting(AUDIO_KEY, &self.audio) {
warn!(%e, "could not store audio settings");
}
}
fn set_mic_test(&mut self, on: bool) {
if self.mic_test == on {
return;
}
self.mic_test = on;
self.engine.send(Command::TestMicrophone { on });
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(on);
if !on {
bridge.set_input_level(-100.0);
}
}
}
fn apply_ptt(&mut self, enabled: bool, key: String) {
let key = key.trim().to_owned();
self.settings.global_ptt = enabled;
if !key.is_empty() {
self.settings.ptt_key = key.clone();
}
self.store_settings();
self.ptt.set((enabled && !key.is_empty()).then_some(key));
}
fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
fn set_h264(&mut self, enabled: bool) {
self.settings.openh264 = enabled;
self.store_settings();
self.video.set_h264(enabled);
self.refresh_h264();
}
fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
bridge.set_h264_loaded(loaded);
bridge.set_h264_busy(status.starts_with("Downloading"));
bridge.set_h264_status(status.into());
}
/// Switches the About page and the settings show.
fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.settings.crash_reports);
}
fn set_crash_reports(&mut self, enabled: bool) {
self.settings.crash_reports = enabled;
self.store_settings();
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk.
fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let text = match crash::pending_reports() {
Ok(reports) if !reports.is_empty() => {
let newest = &reports[reports.len() - 1];
let saved = match reports.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({}). {saved} on this device.", newest.summary)
}
_ => String::new(),
};
ui.global::<Bridge>().set_crash_notice(text.into());
}
/// The third-party notices, one model entry per line.
fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session.
fn open_client(&mut self, client: u16) -> bool {
let Some(id) = self.current else { return false };
let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else {
return false;
};
let playback =
info.uid.as_ref().and_then(|uid| self.playback.get(uid)).copied().unwrap_or_default();
self.playback_dialog = Some((id, client, info.uid.clone()));
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(ClientAudio {
id: client as i32,
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
});
}
true
}
fn client_playback_changed(&mut self, form: &ClientAudio) {
let Some((session, client, uid)) = self.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume });
self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted });
// Kept by unique id; clients without one only for this connection.
if let Some(uid) = uid {
if playback.is_default() {
self.playback.remove(&uid);
} else {
self.playback.insert(uid, playback);
}
if let Err(e) = self.store.set_setting(CLIENT_PLAYBACK_KEY, &self.playback) {
warn!(%e, "could not store client volumes");
}
}
self.refresh_tree();
}
/// `TSC_OPEN=client`: the volume dialog of the first client that is not us.
fn open_first_client(&mut self) {
let Some(view) = self.view().filter(|v| v.state.own_client.is_some()) else { return };
let own = view.state.own_client;
let mut others: Vec<_> =
view.presence.clients.values().filter(|c| Some(c.id) != own && !c.is_query).collect();
others.sort_by_key(|c| c.id);
let Some(id) = others.first().map(|c| c.id) else { return };
self.open_client_pending = false;
if self.open_client(id)
&& let Some(ui) = self.ui.upgrade()
{
ui.set_client_open(true);
}
}
/// Send the stored volumes of clients that appeared in a voice session.
fn apply_client_playback(&mut self, session: i64) {
let Some(view) = self.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| self.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
self.engine.send(Command::SetClientVolume {
session: s,
client: c,
volume: playback.volume,
});
if playback.muted {
self.engine.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
}
+123
View File
@@ -0,0 +1,123 @@
//! Global push-to-talk: a task owns the `tsc_platform::HotkeyManager`
//! (portal on Wayland, XInput2 on X11, a hook on Windows) and reports
//! presses and releases.
use tokio::runtime::Handle;
use tokio::sync::mpsc;
/// Id of the push-to-talk registration (the portal remembers it).
#[cfg(not(target_os = "android"))]
const PTT_ID: &str = "push-to-talk";
/// Handle to the hotkey task.
pub(crate) struct GlobalPtt {
tx: mpsc::UnboundedSender<Option<String>>,
}
impl GlobalPtt {
/// Start the task. `status` gets a line for the settings page,
/// `transmit` the key's state; both are called on the runtime.
pub fn start(
runtime: &Handle,
status: impl Fn(String) + Send + 'static,
transmit: impl Fn(bool) + Send + 'static,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
runtime.spawn(run(rx, status, transmit));
Self { tx }
}
/// Register `key` (e.g. `Ctrl+Shift+T`) instead of the current one, or
/// nothing.
pub fn set(&self, key: Option<String>) {
let _ = self.tx.send(key);
}
}
#[cfg(target_os = "android")]
async fn run(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
_transmit: impl Fn(bool),
) {
while let Some(key) = rx.recv().await {
if key.is_some() {
status("Global hotkeys are not available on this platform.".into());
}
}
}
#[cfg(not(target_os = "android"))]
async fn run(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
use tsc_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
async fn next(events: &mut Option<HotkeyEvents>) -> Option<HotkeyEvent> {
match events {
Some(events) => events.recv().await,
None => std::future::pending().await,
}
}
let mut manager: Option<HotkeyManager> = None;
let mut events: Option<HotkeyEvents> = None;
loop {
tokio::select! {
key = rx.recv() => {
let Some(key) = key else { break };
events = None;
// Released: whatever was held no longer counts.
transmit(false);
if let Some(m) = &mut manager {
let _ = m.unregister(PTT_ID).await;
}
let Some(key) = key else {
status("Off.".into());
continue;
};
let hotkey: Hotkey = match key.parse() {
Ok(h) => h,
Err(e) => {
status(format!("{e}"));
continue;
}
};
if manager.is_none() {
match HotkeyManager::new().await {
Ok(m) => manager = Some(m),
Err(e) => {
status(format!("Global hotkeys are not available: {e}"));
continue;
}
}
}
let Some(m) = &mut manager else { continue };
match m.register(PTT_ID, "Push to talk", hotkey).await {
Ok(registered) => {
events = Some(registered);
status(match m.backend() {
BackendKind::Portal => format!(
"Registered with the desktop: {}",
m.trigger_description(PTT_ID).unwrap_or(key)
),
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
BackendKind::WindowsHook => format!("Active: {hotkey}"),
});
}
Err(e) => status(format!("Could not register {key}: {e}")),
}
}
event = next(&mut events) => match event {
Some(HotkeyEvent::Pressed) => transmit(true),
Some(HotkeyEvent::Released) => transmit(false),
None => {
events = None;
status("The hotkey was removed by the desktop.".into());
}
},
}
}
}
+4
View File
@@ -1,5 +1,9 @@
//! Slint user interface shared by the desktop binary and the mobile apps.
mod app;
mod hotkey;
mod settings;
mod streams;
mod video;
pub use app::{HostedEngine, RunOptions, run};
+4
View File
@@ -1,5 +1,9 @@
//! Desktop client.
// Release builds on Windows are GUI programs (no console window); debug
// builds keep the console for logs.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use anyhow::Result;
use tracing_subscriber::EnvFilter;
+263
View File
@@ -0,0 +1,263 @@
//! Settings kept in the store (besides bookmarks and identities), and their
//! conversion to and from the forms of the settings page.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use tsc_audio::process::NoiseLevel;
use tsc_core::{AudioSettings, TransmitMode};
use crate::app::AudioForm;
/// Store keys.
pub const AUDIO_KEY: &str = "audio";
pub const UI_KEY: &str = "ui";
pub const CLIENT_PLAYBACK_KEY: &str = "client_playback";
/// Frame rates and bitrates (kbit/s) of the share dialog.
pub const FPS_CHOICES: [u32; 3] = [15, 30, 60];
pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiSettings {
/// Global push-to-talk hotkey (besides the button in the window).
pub global_ptt: bool,
/// E.g. `Ctrl+Shift+T` (`tsc_platform::Hotkey` syntax).
pub ptt_key: String,
/// H.264 through Cisco's OpenH264, downloaded on request.
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
}
impl Default for UiSettings {
fn default() -> Self {
Self {
global_ptt: true,
ptt_key: "Ctrl+Shift+T".into(),
openh264: false,
portal_restore_token: None,
share: ShareDefaults::default(),
crash_reports: false,
}
}
}
/// The last choices in the share dialog.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
pub fps_index: usize,
pub bitrate_index: usize,
pub audio: bool,
pub auto_accept: bool,
}
impl Default for ShareDefaults {
fn default() -> Self {
Self { fps_index: 1, bitrate_index: 1, audio: true, auto_accept: false }
}
}
/// Local playback of one client, kept by its unique id.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
pub muted: bool,
}
impl Default for ClientPlayback {
fn default() -> Self {
Self { volume: 1.0, muted: false }
}
}
impl ClientPlayback {
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
}
impl DeviceChoices {
/// `devices` as `(id, name, is_default)`. A selected device that is not
/// connected stays in the list, so the choice survives.
pub fn new(devices: &[(String, String, bool)], selected: Option<&str>) -> Self {
let default_name = devices.iter().find(|d| d.2).map(|d| d.1.as_str());
let mut choices = Self {
names: vec![match default_name {
Some(name) => format!("System default ({name})"),
None => "System default".into(),
}],
ids: vec![None],
};
for (id, name, _) in devices {
choices.names.push(name.clone());
choices.ids.push(Some(id.clone()));
}
if let Some(id) = selected
&& !choices.ids.iter().any(|i| i.as_deref() == Some(id))
{
choices.names.push(format!("{id} (not connected)"));
choices.ids.push(Some(id.to_owned()));
}
choices
}
pub fn index_of(&self, id: Option<&str>) -> usize {
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
}
pub fn id_at(&self, index: i32) -> Option<String> {
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
}
}
fn noise_index(level: NoiseLevel) -> i32 {
match level {
NoiseLevel::Low => 0,
NoiseLevel::Moderate => 1,
NoiseLevel::High => 2,
NoiseLevel::VeryHigh => 3,
}
}
fn noise_level(index: i32) -> NoiseLevel {
match index {
0 => NoiseLevel::Low,
2 => NoiseLevel::High,
3 => NoiseLevel::VeryHigh,
_ => NoiseLevel::Moderate,
}
}
/// The settings page's form for `settings`.
pub fn audio_form(
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioForm {
let p = &settings.processing;
AudioForm {
input_index: inputs.index_of(settings.input_device.as_deref()) as i32,
output_index: outputs.index_of(settings.output_device.as_deref()) as i32,
transmit: match settings.transmit {
TransmitMode::PushToTalk => 0,
TransmitMode::VoiceActivation => 1,
TransmitMode::Continuous => 2,
},
vad_threshold: settings.vad.threshold_db,
echo_cancellation: p.echo_cancellation,
noise_suppression: p.noise_suppression,
noise_level: noise_index(p.noise_level),
auto_gain: p.auto_gain,
input_gain: p.input_gain_db,
output_volume: settings.output_volume * 100.0,
playback_buffer: settings.playback_buffer_ms as f32,
}
}
/// `settings` changed as the form says; what the form does not show stays.
pub fn apply_audio_form(
form: &AudioForm,
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioSettings {
let mut s = settings.clone();
s.input_device = inputs.id_at(form.input_index);
s.output_device = outputs.id_at(form.output_index);
s.transmit = match form.transmit {
1 => TransmitMode::VoiceActivation,
2 => TransmitMode::Continuous,
_ => TransmitMode::PushToTalk,
};
s.vad.threshold_db = form.vad_threshold;
s.processing.echo_cancellation = form.echo_cancellation;
s.processing.noise_suppression = form.noise_suppression;
s.processing.noise_level = noise_level(form.noise_level);
s.processing.auto_gain = form.auto_gain;
s.processing.input_gain_db = form.input_gain;
s.output_volume = (form.output_volume / 100.0).clamp(0.0, 4.0);
s.playback_buffer_ms = form.playback_buffer.round().clamp(20.0, 180.0) as u32;
s
}
#[cfg(test)]
mod tests {
use super::*;
fn devices() -> Vec<(String, String, bool)> {
vec![
("alsa:hw:0,0".into(), "Built-in".into(), true),
("alsa:hw:1,0".into(), "Headset".into(), false),
]
}
#[test]
fn device_choices() {
let choices = DeviceChoices::new(&devices(), None);
assert_eq!(choices.names, ["System default (Built-in)", "Built-in", "Headset"]);
assert_eq!(choices.index_of(Some("alsa:hw:1,0")), 2);
assert_eq!(choices.id_at(0), None);
assert_eq!(choices.id_at(2).as_deref(), Some("alsa:hw:1,0"));
assert_eq!(choices.id_at(9), None);
// An unplugged device stays selectable.
let choices = DeviceChoices::new(&devices(), Some("usb:mic"));
assert_eq!(choices.names.last().unwrap(), "usb:mic (not connected)");
assert_eq!(choices.index_of(Some("usb:mic")), 3);
}
#[test]
fn audio_form_roundtrip() {
let inputs = DeviceChoices::new(&devices(), None);
let outputs = DeviceChoices::new(&devices(), None);
let mut settings = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
output_volume: 0.5,
playback_buffer_ms: 80,
..Default::default()
};
settings.vad.threshold_db = -35.0;
settings.processing.noise_level = NoiseLevel::High;
settings.processing.input_gain_db = 6.0;
let form = audio_form(&settings, &inputs, &outputs);
assert_eq!((form.input_index, form.output_index, form.transmit), (2, 0, 1));
assert_eq!(form.output_volume, 50.0);
assert_eq!(apply_audio_form(&form, &settings, &inputs, &outputs), settings);
let form =
AudioForm { transmit: 2, echo_cancellation: false, playback_buffer: 500.0, ..form };
let changed = apply_audio_form(&form, &settings, &inputs, &outputs);
assert_eq!(changed.transmit, TransmitMode::Continuous);
assert!(!changed.processing.echo_cancellation);
assert_eq!(changed.playback_buffer_ms, 180);
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
assert!(parsed.openh264);
assert!(!parsed.crash_reports, "crash reports are opt-in");
assert_eq!(parsed.ptt_key, "Ctrl+Shift+T");
assert_eq!(parsed.share, ShareDefaults::default());
let map: ClientPlaybackMap =
serde_json::from_str(r#"{"uid=":{"volume":0.5,"muted":false}}"#).unwrap();
assert_eq!(map["uid="].volume, 0.5);
}
}
+609
View File
@@ -0,0 +1,609 @@
//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the
//! viewer. The engine runs the stream sessions; `video.rs` captures,
//! encodes and decodes.
use slint::{ComponentHandle, Model};
use tsc_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState};
use tsc_core::{Command, Event, StreamState, WatchState};
use crate::app::{App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model};
use crate::settings::{BITRATE_CHOICES, FPS_CHOICES, ShareDefaults};
use crate::video::{self, Capture, CaptureRequest, Decoder};
/// Our stream.
pub(crate) struct Share {
pub session: i64,
/// Stops capturing when dropped.
capture: Capture,
/// The server confirmed the stream.
live: bool,
viewers: Vec<ViewerInfo>,
/// The capture ended by itself and the stream is being stopped.
stopping: bool,
}
/// The stream in the viewer.
pub(crate) struct Watch {
/// `None` for the local demo stream.
session: Option<i64>,
stream_id: String,
title: String,
streamer: String,
/// Shown over the picture; empty while it plays.
status: String,
connected: bool,
ended: bool,
has_frame: bool,
/// Shown instead of the chat.
shown: bool,
decoder: Option<Decoder>,
}
fn end_text(reason: &EndReason, streamer: &str) -> String {
match reason {
EndReason::Local => "You left the stream.".into(),
EndReason::Denied => format!("{streamer} did not let you watch."),
EndReason::Stopped => "The stream has ended.".into(),
EndReason::Removed(Some(LeaveReason::Kicked | LeaveReason::Banned)) => {
format!("{streamer} removed you from the stream.")
}
EndReason::Removed(_) => "You were removed from the stream.".into(),
EndReason::Failed(e) => format!("The stream failed: {e}"),
}
}
fn share_end_text(reason: &EndReason) -> String {
match reason {
EndReason::Failed(e) => format!("Sharing failed: {e}"),
_ => "Sharing ended.".into(),
}
}
impl App {
pub(crate) fn stream_event(&mut self, event: Event) {
match event {
Event::StreamsChanged { session, streams } => {
let view = self.sessions.entry(session as i64).or_default();
// Development switch: watch the first stream that shows up.
let autowatch = std::env::var("TSC_AUTOWATCH").is_ok_and(|v| v == "1")
&& self.watch.is_none()
&& self.current == Some(session as i64);
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer.0))
.map(|s| s.id.clone());
view.streams = streams;
self.refresh_streams();
if autowatch && let Some(id) = first {
self.watch_stream(id);
}
}
Event::StreamState { session, state } => self.share_state(session as i64, state),
Event::StreamViewerRequest { session, viewer, .. } => {
let name = self.sessions.entry(session as i64).or_default().nickname(viewer);
self.set_status(format!("{name} wants to watch your stream"));
}
Event::StreamViewers { session, viewers } => {
if let Some(share) = self.share.as_mut().filter(|s| s.session == session as i64) {
share.viewers = viewers;
self.refresh_streams();
}
}
Event::WatchState { session, stream_id, state } => {
self.watch_state(session as i64, &stream_id, state);
}
// Also flagged on the sink, which the encoder reads.
Event::StreamKeyframeRequest { .. } => {}
_ => {}
}
}
fn share_state(&mut self, session: i64, state: StreamState) {
let Some(share) = self.share.as_mut().filter(|s| s.session == session) else { return };
match state {
StreamState::Starting => {}
StreamState::Live { sink, .. } => {
share.live = true;
share.capture.attach(sink);
self.set_status("You are sharing your screen");
}
StreamState::Ended(reason) => {
let local = reason == EndReason::Local || share.stopping;
self.share = None;
self.share_error = if local { String::new() } else { share_end_text(&reason) };
self.set_status(if local {
"You stopped sharing".into()
} else {
share_end_text(&reason)
});
}
}
self.refresh_streams();
}
fn watch_state(&mut self, session: i64, stream_id: &str, state: WatchState) {
let Some(watch) = self
.watch
.as_mut()
.filter(|w| w.session == Some(session) && w.stream_id == stream_id && !w.ended)
else {
return;
};
match state {
WatchState::Requested => {
watch.status = format!("Waiting for {} to let you watch…", watch.streamer);
}
WatchState::Connecting => {
watch.status = format!("Connecting to {}…", watch.streamer);
}
WatchState::Connected => {
watch.connected = true;
if !watch.has_frame {
watch.status = "Waiting for the picture…".into();
}
}
WatchState::Ended(reason) => {
watch.ended = true;
watch.decoder = None;
watch.status = end_text(&reason, &watch.streamer);
}
}
self.refresh_viewer();
self.refresh_streams();
}
/// The streams panel, the share dialog's live part and the toolbar.
pub(crate) fn refresh_streams(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let view = self.view();
let current = self.current;
let mut items: Vec<StreamItem> = Vec::new();
if let Some(view) = view.filter(|v| v.streams_available()) {
for s in &view.streams {
let watching = self
.watch
.as_ref()
.is_some_and(|w| w.session == current && w.stream_id == s.id && !w.ended);
items.push(StreamItem {
id: s.id.clone().into(),
name: s.name.clone().into(),
streamer: view.nickname(s.streamer.0).into(),
audio: s.audio,
watching,
own: view.state.own_client == Some(s.streamer.0),
});
}
// Streams that started before we joined are only known by the
// streaming flag: the server does not tell their ids.
let channel = view.state.own_channel;
for c in view.presence.clients.values() {
let announced = view.streams.iter().any(|s| s.streamer.0 == c.id);
if c.streaming == Some(true)
&& Some(c.channel) == channel
&& !announced && view.state.own_client != Some(c.id)
{
items.push(StreamItem {
name: c.nickname.clone().into(),
streamer: c.nickname.clone().into(),
..StreamItem::default()
});
}
}
}
if self.demo {
items.push(StreamItem {
id: "demo".into(),
name: "Test pattern".into(),
streamer: "local preview".into(),
audio: false,
watching: self.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended),
own: false,
});
}
bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available()));
bridge.set_streams(model(items));
bridge.set_can_share(video::AVAILABLE);
let share = self.share.as_ref().filter(|s| Some(s.session) == current);
let state = match share {
Some(s) if s.live => "live",
Some(_) => "starting",
None if self.share_busy => "starting",
None => "",
};
bridge.set_share_state(state.into());
bridge.set_share_busy(self.share_busy);
bridge.set_share_error(self.share_error.clone().into());
let viewers: Vec<ViewerItem> = share
.map(|s| {
s.viewers
.iter()
.map(|v| ViewerItem {
client: i32::from(v.client.0),
name: view
.map_or_else(String::new, |view| view.nickname(v.client.0))
.into(),
state: match v.state {
ViewerState::Requested => "requested",
ViewerState::Connecting => "connecting",
ViewerState::Connected => "connected",
}
.into(),
message: v.message.clone().into(),
})
.collect()
})
.unwrap_or_default();
let requests = viewers.iter().filter(|v| v.state == "requested").count();
bridge.set_share_requests(requests as i32);
bridge.set_share_viewers(model(viewers));
let status = match share {
Some(s) if s.live => s.capture.status(),
Some(s) => format!("Starting the stream of {}…", s.capture.source_name()),
None if self.share_busy => "Starting the capture…".into(),
None => String::new(),
};
bridge.set_share_status(status.into());
}
fn refresh_viewer(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(watch) = &self.watch else {
bridge.set_viewer_open(false);
bridge.set_viewer_has_frame(false);
bridge.set_viewer_frame(slint::Image::default());
return;
};
bridge.set_viewer_open(
watch.shown && (watch.session.is_none() || watch.session == self.current),
);
bridge.set_viewer_title(watch.title.clone().into());
bridge.set_viewer_status(watch.status.clone().into());
bridge.set_viewer_ended(watch.ended);
bridge.set_viewer_has_frame(watch.has_frame);
bridge.set_viewer_volume(self.stream_volume);
let info = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let info = [format!("by {}", watch.streamer), info]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" · ");
bridge.set_viewer_info(info.into());
}
/// Once a second: statistics, a capture that ended, decoder problems.
pub(crate) fn tick_streams(&mut self) {
if let Some(share) = &mut self.share
&& share.live
&& !share.stopping
&& share.capture.ended()
{
share.stopping = true;
self.engine.send(Command::StopStream { session: share.session as u64 });
}
if let Some(watch) = &mut self.watch
&& watch.connected
&& !watch.has_frame
&& let Some(error) = watch.decoder.as_ref().and_then(Decoder::error)
{
watch.status = if error.contains("H264") || error.contains("OpenH264") {
format!("{error}. Enable H.264 in Settings → Streaming to watch this stream.")
} else {
format!("Cannot show the picture: {error}")
};
}
if self.share.is_some() {
self.refresh_streams();
}
if self.watch.is_some() {
self.refresh_viewer();
}
}
// Sharing.
/// Fill the share dialog: sources and the last choices.
pub(crate) fn open_share(&mut self) -> ShareForm {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("TSC_TEST_PATTERN").is_ok_and(|v| v == "1");
let sources = match self.video.sources(test_pattern) {
Ok(sources) => {
if self.share.is_none() {
self.share_error.clear();
}
sources
}
Err(e) => {
self.share_error = e;
Vec::new()
}
};
if let Some(ui) = self.ui.upgrade() {
let items: Vec<SourceItem> = sources
.into_iter()
.map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() })
.collect();
ui.global::<Bridge>().set_share_sources(model(items));
}
self.refresh_streams();
let defaults = &self.settings.share;
let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone());
ShareForm {
source: 0,
name: match nickname {
Some(nick) if !nick.is_empty() => format!("{nick}'s screen").into(),
_ => "Screen".into(),
},
fps_index: defaults.fps_index.min(FPS_CHOICES.len() - 1) as i32,
bitrate_index: defaults.bitrate_index.min(BITRATE_CHOICES.len() - 1) as i32,
audio: defaults.audio,
auto_accept: defaults.auto_accept,
}
}
/// Development switch `TSC_AUTOSHARE`: share the test pattern once.
pub(crate) fn autoshare(&mut self) {
if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) {
return;
}
self.autoshare = false;
let mut form = self.open_share();
let Some(ui) = self.ui.upgrade() else { return };
let sources = ui.global::<Bridge>().get_share_sources();
let pattern = (0..sources.row_count())
.find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"));
let Some(index) = pattern else { return };
form.source = index as i32;
form.auto_accept = true;
self.start_share(form);
}
pub(crate) fn start_share(&mut self, form: ShareForm) {
let Some(session) = self.current else { return };
if self.share_busy || self.share.is_some() {
return;
}
let index = |i: i32, len: usize| usize::try_from(i).unwrap_or(0).min(len - 1);
let defaults = ShareDefaults {
fps_index: index(form.fps_index, FPS_CHOICES.len()),
bitrate_index: index(form.bitrate_index, BITRATE_CHOICES.len()),
audio: form.audio,
auto_accept: form.auto_accept,
};
let request = CaptureRequest {
fps: FPS_CHOICES[defaults.fps_index],
bitrate_kbps: BITRATE_CHOICES[defaults.bitrate_index],
audio: form.audio,
restore_token: self.settings.portal_restore_token.clone(),
};
let bitrate = request.bitrate_kbps;
self.settings.share = defaults;
self.store_settings();
self.share_busy = true;
self.share_error.clear();
self.refresh_streams();
let setup = StreamSetup {
name: form.name.trim().to_owned(),
bitrate,
audio: form.audio,
..StreamSetup::default()
};
let auto_accept = form.auto_accept;
let runtime = self.engine.runtime().clone();
let source = usize::try_from(form.source).unwrap_or(0);
self.video.start_capture(&runtime, source, request, move |result| {
later(move |app| app.capture_ready(session, setup, auto_accept, result));
});
}
/// The capture started (or not): go live.
fn capture_ready(
&mut self,
session: i64,
mut setup: StreamSetup,
auto_accept: bool,
result: Result<Capture, String>,
) {
self.share_busy = false;
match result {
Err(e) => {
self.share_error = format!("Could not start the capture: {e}");
}
Ok(capture) => {
if let Some(token) = capture.restore_token()
&& self.settings.portal_restore_token.as_ref() != Some(&token)
{
self.settings.portal_restore_token = Some(token);
self.store_settings();
}
if setup.audio && !capture.has_audio() {
setup.audio = false;
let reason = capture.audio_error().unwrap_or_default();
self.set_status(format!("Sharing without sound: {reason}"));
}
self.engine.send(Command::StartStream {
session: session as u64,
setup,
auto_accept,
});
self.share = Some(Share {
session,
capture,
live: false,
viewers: Vec::new(),
stopping: false,
});
}
}
self.refresh_streams();
}
pub(crate) fn stop_share(&mut self) {
if let Some(share) = &mut self.share {
share.stopping = true;
self.engine.send(Command::StopStream { session: share.session as u64 });
}
}
pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) {
if let Some(share) = &self.share {
let session = share.session as u64;
self.engine.send(Command::AcceptViewer { session, viewer, accept });
}
}
pub(crate) fn kick_viewer(&mut self, viewer: u16) {
if let Some(share) = &self.share {
self.engine.send(Command::KickViewer { session: share.session as u64, viewer });
}
}
// Watching.
pub(crate) fn watch_stream(&mut self, stream_id: String) {
if stream_id == "demo" && self.demo {
self.start_demo();
return;
}
let Some(session) = self.current else { return };
let Some(view) = self.sessions.get(&session) else { return };
let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return };
let streamer = view.nickname(info.streamer.0);
let title =
if info.name.is_empty() { format!("{streamer}'s stream") } else { info.name.clone() };
self.leave_stream();
self.engine
.send(Command::WatchStream { session: session as u64, stream_id: stream_id.clone() });
if self.stream_volume != 100.0 {
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: stream_id.clone(),
volume: self.stream_volume / 100.0,
});
}
let wake = || later(|app| app.show_picture());
let decoder = self.video.watch(&self.engine, session as u64, &stream_id, wake);
self.watch = Some(Watch {
session: Some(session),
stream_id,
title,
status: format!("Asking {streamer} to let you watch…"),
streamer,
connected: false,
ended: false,
has_frame: false,
shown: true,
decoder: Some(decoder),
});
self.refresh_viewer();
self.refresh_streams();
}
/// The local test stream in the viewer (`TSC_DEMO_STREAM`).
pub(crate) fn start_demo(&mut self) {
self.leave_stream();
self.watch = Some(Watch {
session: None,
stream_id: "demo".into(),
title: "Test pattern".into(),
streamer: "local preview".into(),
status: "Starting the local preview…".into(),
connected: true,
ended: false,
has_frame: false,
shown: true,
decoder: None,
});
let runtime = self.engine.runtime().clone();
let wake = || later(|app| app.show_picture());
self.video.demo(&runtime, wake, |result| {
later(move |app| {
let Some(watch) = app.watch.as_mut().filter(|w| w.session.is_none()) else {
return;
};
match result {
Ok(decoder) => watch.decoder = Some(decoder),
Err(e) => watch.status = format!("The preview failed: {e}"),
}
app.refresh_viewer();
});
});
self.refresh_viewer();
self.refresh_streams();
}
/// A decoded picture is waiting.
fn show_picture(&mut self) {
let Some(watch) = &mut self.watch else { return };
let Some(image) = watch.decoder.as_ref().and_then(Decoder::take_picture) else { return };
let first = !watch.has_frame;
watch.has_frame = true;
if first {
watch.status.clear();
}
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_viewer_frame(image);
if first {
self.refresh_viewer();
}
}
}
pub(crate) fn show_viewer(&mut self, shown: bool) {
if let Some(watch) = &mut self.watch {
watch.shown = shown;
}
if !shown {
self.set_fullscreen(false);
}
self.refresh_viewer();
self.refresh_streams();
}
/// Stop watching and close the viewer.
pub(crate) fn leave_stream(&mut self) {
if let Some(watch) = self.watch.take()
&& let Some(session) = watch.session
&& !watch.ended
{
self.engine
.send(Command::LeaveStream { session: session as u64, stream_id: watch.stream_id });
}
self.set_fullscreen(false);
self.refresh_viewer();
self.refresh_streams();
}
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
self.stream_volume = percent.round().clamp(0.0, 200.0);
if let Some(watch) = &self.watch
&& let Some(session) = watch.session
{
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: watch.stream_id.clone(),
volume: self.stream_volume / 100.0,
});
}
}
pub(crate) fn toggle_fullscreen(&mut self) {
let Some(ui) = self.ui.upgrade() else { return };
let full = !ui.global::<Bridge>().get_viewer_fullscreen();
self.set_fullscreen(full);
}
fn set_fullscreen(&self, full: bool) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
if bridge.get_viewer_fullscreen() == full {
return;
}
bridge.set_viewer_fullscreen(full);
ui.window().set_fullscreen(full);
}
}
+400
View File
@@ -0,0 +1,400 @@
//! Video of streams for the UI: capture and encoding when we share, decoding
//! into Slint images when we watch, and the optional OpenH264 library
//! (desktop; Android decodes H.264 with the device's MediaCodec).
use std::path::Path;
#[cfg(not(target_os = "android"))]
use std::path::PathBuf;
use std::sync::Arc;
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
use tokio::runtime::Handle;
use tracing::warn;
use tsc_core::media::tsc_media::capture::SourceId;
use tsc_core::media::tsc_media::{Codecs, VideoFrame, convert};
use tsc_core::media::{
self, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, stream_codec,
};
use tsc_core::stream::PeerConfig;
use tsc_core::{Engine, StreamSink};
/// Whether this build can share and decode video.
pub const AVAILABLE: bool = true;
type Picture = SharedPixelBuffer<Rgba8Pixel>;
/// Human-readable text for a picture size.
fn size_text(width: u32, height: u32) -> String {
if width == 0 || height == 0 { String::new() } else { format!("{width}×{height}") }
}
/// Cisco's OpenH264, downloaded on the user's request.
#[cfg(not(target_os = "android"))]
mod openh264 {
pub use tsc_core::media::tsc_media::codec::h264::{
OPENH264_VERSION, OpenH264, download_openh264,
};
pub enum State {
Off,
/// Enabled, but not downloaded yet (or the file is not a known build).
Missing(String),
Downloading,
Loaded(std::path::PathBuf),
}
}
/// The result of [`Video::download_h264`].
#[cfg(not(target_os = "android"))]
pub(crate) struct H264Download(Result<openh264::OpenH264, String>);
#[cfg(target_os = "android")]
pub(crate) struct H264Download;
pub(crate) struct Video {
codecs: Arc<Codecs>,
#[cfg(not(target_os = "android"))]
openh264_dir: PathBuf,
#[cfg(not(target_os = "android"))]
h264: openh264::State,
/// Sources of the share dialog, by index.
sources: Vec<(SourceId, String)>,
}
impl Video {
pub fn new(data_dir: &Path, openh264: bool) -> Self {
#[cfg(target_os = "android")]
let _ = (data_dir, openh264);
#[allow(unused_mut, reason = "set_h264 does nothing on Android")]
let mut video = Self {
codecs: Arc::new(Codecs::new()),
#[cfg(not(target_os = "android"))]
openh264_dir: data_dir.join("openh264"),
#[cfg(not(target_os = "android"))]
h264: openh264::State::Off,
sources: Vec::new(),
};
#[cfg(not(target_os = "android"))]
video.set_h264(openh264);
video
}
/// `base` with the codecs this machine can encode and decode.
pub fn peer_config(&self, base: PeerConfig) -> PeerConfig {
peer_config(&self.codecs, base)
}
/// Whether H.264 works, and a line for the settings page.
pub fn h264_status(&self) -> (bool, String) {
#[cfg(target_os = "android")]
return (true, "H.264 uses the device's codecs.".into());
#[cfg(not(target_os = "android"))]
match &self.h264 {
openh264::State::Off => (false, String::new()),
openh264::State::Missing(reason) => (false, reason.clone()),
openh264::State::Downloading => (false, "Downloading OpenH264 from Cisco…".into()),
openh264::State::Loaded(path) => (
true,
format!("OpenH264 {} is loaded ({}).", openh264::OPENH264_VERSION, path.display()),
),
}
}
/// Enable or disable H.264; enabling loads a library downloaded earlier.
/// Takes effect for new connections.
pub fn set_h264(&mut self, enabled: bool) {
#[cfg(target_os = "android")]
let _ = enabled;
#[cfg(not(target_os = "android"))]
{
use openh264::State;
if !enabled {
self.h264 = State::Off;
self.codecs = Arc::new(Codecs::new());
return;
}
if matches!(self.h264, State::Loaded(_) | State::Downloading) {
return;
}
match openh264::OpenH264::find_in(&self.openh264_dir) {
Ok(library) => self.loaded(library),
Err(_) => self.h264 = State::Missing("OpenH264 is not downloaded yet.".into()),
}
}
}
#[cfg(not(target_os = "android"))]
fn loaded(&mut self, library: openh264::OpenH264) {
self.h264 = openh264::State::Loaded(library.path().to_owned());
self.codecs = Arc::new(Codecs::new().with_openh264(library));
}
/// Download Cisco's OpenH264 (only on the user's request). `done` runs
/// on the runtime; pass its argument to [`Video::downloaded`].
pub fn download_h264(
&mut self,
runtime: &Handle,
done: impl FnOnce(H264Download) + Send + 'static,
) {
#[cfg(target_os = "android")]
let _ = (runtime, done);
#[cfg(not(target_os = "android"))]
{
use openh264::State;
if matches!(self.h264, State::Downloading | State::Loaded(_)) {
return;
}
self.h264 = State::Downloading;
let dir = self.openh264_dir.clone();
runtime.spawn(async move {
let result = openh264::download_openh264(&dir).await.map_err(|e| e.to_string());
done(H264Download(result));
});
}
}
pub fn downloaded(&mut self, download: H264Download, enabled: bool) {
#[cfg(target_os = "android")]
let _ = (download, enabled);
#[cfg(not(target_os = "android"))]
match download.0 {
Ok(library) if enabled => self.loaded(library),
Ok(_) => self.h264 = openh264::State::Off,
Err(e) => {
warn!("OpenH264 download failed: {e}");
self.h264 = openh264::State::Missing(format!("Download failed: {e}"));
}
}
}
/// Screens and windows to share, as (name, detail); the test pattern too
/// when asked for.
pub fn sources(&mut self, test_pattern: bool) -> Result<Vec<(String, String)>, String> {
let mut error = None;
let mut sources = match media::screen_sources() {
Ok(list) => list,
Err(e) => {
error = Some(e.to_string());
Vec::new()
}
};
if test_pattern {
sources.push(media::test_pattern_source());
}
if sources.is_empty() {
return Err(error.unwrap_or_else(|| "Nothing to share was found.".into()));
}
self.sources = sources.iter().map(|s| (s.id.clone(), s.name.clone())).collect();
Ok(sources
.iter()
.map(|s| {
let name = match s.id {
SourceId::Portal => "Choose via system dialog".to_owned(),
_ => s.name.clone(),
};
let detail = match (&s.id, s.primary) {
(SourceId::Monitor(_), true) => {
format!("{} · primary", size_text(s.width, s.height))
}
(SourceId::Window(_), _) => {
format!("window {}", size_text(s.width, s.height)).trim().to_owned()
}
_ => size_text(s.width, s.height),
};
(name, detail)
})
.collect())
}
/// Start capturing source `index` of [`Video::sources`]; `done` runs on
/// the runtime (the portal may wait for the user first).
pub fn start_capture(
&self,
runtime: &Handle,
index: usize,
options: CaptureRequest,
done: impl FnOnce(Result<Capture, String>) + Send + 'static,
) {
let Some((source, name)) = self.sources.get(index).cloned() else {
done(Err("Pick something to share.".into()));
return;
};
let peer = self.peer_config(PeerConfig::default());
let Some(codec) = stream_codec(&self.codecs, &peer) else {
done(Err("No video encoder is available.".into()));
return;
};
let codecs = self.codecs.clone();
let config = StreamerConfig {
source,
fps: options.fps,
bitrate_kbps: options.bitrate_kbps,
codec,
audio: options.audio,
restore_token: options.restore_token,
..StreamerConfig::default()
};
runtime.spawn(async move {
let result = Streamer::start(&codecs, config).await;
done(result.map(|streamer| Capture { streamer, name }).map_err(|e| e.to_string()));
});
}
/// Decode stream `stream_id` of `session`; `wake` is called (on the
/// decoder thread) when a picture is ready and none is waiting.
pub fn watch(
&self,
engine: &Engine,
session: u64,
stream_id: &str,
wake: impl Fn() + Send + Sync + 'static,
) -> Decoder {
let pictures = Arc::new(Latest::new());
let on_frame = deliver(pictures.clone(), wake);
let viewer = Viewer::start(engine, session, stream_id, self.codecs.clone(), on_frame);
Decoder { source: Source::Viewer(viewer), pictures }
}
/// The test pattern through the encoder and decoder, without a server
/// (`TSC_DEMO_STREAM`).
pub fn demo(
&self,
runtime: &Handle,
wake: impl Fn() + Send + Sync + 'static,
done: impl FnOnce(Result<Decoder, String>) + Send + 'static,
) {
let pictures = Arc::new(Latest::new());
let on_frame = deliver(pictures.clone(), wake);
let codecs = self.codecs.clone();
let config = StreamerConfig { source: SourceId::Synthetic, ..StreamerConfig::default() };
runtime.spawn(async move {
let result = LocalPreview::start(codecs, config, on_frame).await;
done(
result
.map(|preview| Decoder { source: Source::Preview(preview), pictures })
.map_err(|e| e.to_string()),
);
});
}
}
/// Converts decoded frames into Slint pixel buffers, keeping the newest.
fn deliver(
pictures: Arc<Latest<Picture>>,
wake: impl Fn() + Send + Sync + 'static,
) -> impl FnMut(VideoFrame) + Send + 'static {
move |frame: VideoFrame| {
let mut buffer = Picture::new(frame.width, frame.height);
let stride = frame.width as usize * 4;
if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) {
warn!("cannot show a picture: {e}");
return;
}
if pictures.put(buffer) {
wake();
}
}
}
/// Share settings from the dialog.
pub(crate) struct CaptureRequest {
pub fps: u32,
pub bitrate_kbps: u32,
pub audio: bool,
pub restore_token: Option<String>,
}
/// A running capture for our stream. Stops when dropped.
pub(crate) struct Capture {
streamer: Streamer,
name: String,
}
impl Capture {
/// Encode into the live stream.
pub fn attach(&self, sink: StreamSink) {
self.streamer.attach(Arc::new(sink));
}
pub fn source_name(&self) -> &str {
&self.name
}
pub fn has_audio(&self) -> bool {
self.streamer.has_audio()
}
pub fn audio_error(&self) -> Option<String> {
self.streamer.audio_error().map(str::to_owned)
}
/// The portal's token for this choice, to keep.
pub fn restore_token(&self) -> Option<String> {
self.streamer.restore_token().map(str::to_owned)
}
/// The capture stopped by itself (e.g. sharing ended in the desktop).
pub fn ended(&self) -> bool {
self.streamer.stats().capture_ended
}
/// One line about what is sent.
pub fn status(&self) -> String {
let stats = self.streamer.stats();
let mut text = format!("{} · {}", self.name, size_text(stats.width, stats.height));
text.push_str(&format!(" · {} frames sent", stats.video_frames));
if self.streamer.has_audio() {
text.push_str(" · with sound");
}
if let Some(e) = stats.error {
text.push_str(&format!(" · encoder: {e}"));
}
text
}
}
enum Source {
Viewer(Viewer),
Preview(LocalPreview),
}
/// Decodes a watched stream into pictures. Stops when dropped.
pub(crate) struct Decoder {
source: Source,
pictures: Arc<Latest<Picture>>,
}
impl Decoder {
/// The newest picture since the last call.
pub fn take_picture(&self) -> Option<Image> {
self.pictures.take().map(Image::from_rgba8)
}
fn stats(&self) -> media::DecodeStats {
match &self.source {
Source::Viewer(v) => v.stats(),
Source::Preview(p) => p.stats(),
}
}
/// One line about the video: codec, size, problems.
pub fn info(&self) -> String {
let stats = self.stats();
let mut parts = Vec::new();
if let Some(codec) = stats.codec {
parts.push(codec.to_string());
}
if stats.width > 0 {
parts.push(size_text(stats.width, stats.height));
}
if let Some(e) = stats.error {
parts.push(e);
}
parts.join(" · ")
}
/// Whether pictures could never come (no decoder for the codec).
pub fn error(&self) -> Option<String> {
let stats = self.stats();
stats.error.filter(|_| stats.decoded == 0)
}
}
+1255 -102
View File
File diff suppressed because it is too large. Load diff
+18 -7
View File
@@ -67,10 +67,10 @@ fuzz/ cargo-fuzz targets
| `tsc-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) | done |
| `tsc-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) |
| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport |
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, streams on TS6 | done (streams with synthetic frames) |
| `tsc-ui` | Slint UI and the desktop binary | done (no streams yet) |
| `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | planned |
| `tsc-platform` | Global hotkeys, notifications, paths | planned |
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, audio settings and volumes, streams on TS6; `media` module (capture → encoder → stream, stream → decoder) | done |
| `tsc-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) |
| `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders planned; MediaCodec not run on a device yet) |
| `tsc-platform` | Global hotkeys, notifications, paths, crash reports, notices | done |
| `tsc-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture); see [android.md](android.md) | builds, not yet run on a device |
## Merging sources
@@ -95,9 +95,20 @@ channel. Its tests drive two instances through a fake relay server.
In `tsc-core` a stream task per voice connection runs `Streams`; the voice task
forwards `MessageEvent`s and sends the requests. Encoders push frames through
the `StreamSink` of `StreamState::Live`; received frames of watched streams go
to `Engine::subscribe_frames`, not the event bus. `tsc-stream::FrameSource` is
the seam for capture and encoders (`tsc-media`); `SyntheticSource` stands in
for tests and `tsctl stream start --synthetic`.
to `Engine::subscribe_frames`, not the event bus. The audio of watched streams
goes straight to the session's audio thread, which mixes it like a talker
with its own volume (`Command::SetStreamVolume`).
`tsc-core::media` (feature `media`) connects this to `tsc-media`:
`Streamer` captures (screen, window, portal or the test pattern, plus system
audio), encodes with the codec of our offer (VP8 by default; the offer carries
only the codec we encode, since every viewer gets the same frames) and Opus,
and feeds the `StreamSink`, honouring keyframe requests. `Viewer` decodes a
watched stream on its own thread (skipping to the next keyframe after losses
and asking for one) and hands pictures to the UI, which keeps only the newest
(`Latest`). `EncodedSource` wraps a `Streamer` as a `tsc-stream::FrameSource`
for `tsctl stream start`; `SyntheticSource` (fake VP8 bytes) remains for
tsc-stream's own tests.
## Milestones
+24
View File
@@ -67,6 +67,30 @@ measure the end-to-end latency:
| +200 ppm | 73 / 131 ms | 112 ms | 125 ms |
| -200 ppm | 67 / 95 ms | 82 ms | 84 ms |
## Settings, levels and volumes
The engine keeps one `AudioSettings` for all sessions (`Command::SetAudioSettings`;
each new audio thread starts with it) and applies changes live. The desktop app
stores them under the setting `audio` and shows them on its settings page:
devices, transmit mode (push-to-talk, voice activation, continuous), the voice
activation threshold, echo cancellation, noise suppression and its level,
automatic gain, microphone gain, output volume and the playback buffer.
The audio thread reports the loudest 10 ms level since the last report about
ten times a second (`Event::InputLevel`, with whether voice is sent), which the
settings page shows as a meter with the threshold. Without a voice connection,
`Command::TestMicrophone` opens the microphone for the meter alone.
Per-client volume and mute are local (`SetClientVolume`, `SetClientMuted`); the
app keeps them by unique id and sends them again when the client shows up. Client
ids are reused, so the session forgets the settings of clients that left.
Watched streams play through the same mixer under made-up client ids (counting
down from 65535) with their own volume (`SetStreamVolume`).
Push-to-talk works with the button in the window and a global hotkey
(`tsc_platform::HotkeyManager`: the portal on Wayland, XInput2 on X11, a hook on
Windows), configurable as e.g. `Ctrl+Shift+T`.
## Devices
Devices are selected by cpal's stable id (`host:device`, e.g. `alsa:hw:1,0`);
+46
View File
@@ -38,6 +38,46 @@ while let Some(frame) = frames.recv().await {
}
```
## The pipeline in `tsc-core` (`media` module)
Feature `media` of tsc-core builds the module with whatever tsc-media backends
are enabled (on Android: MediaCodec and the app's capture source);
`media-desktop` adds tsc-media's default backends (libvpx, OpenH264, X11,
PipeWire). The desktop app and tsctl use `media-desktop`, the Android app
`media`. Codecs are always chosen through `Codecs`, so each build uses its own.
```
streamer: ScreenCapture ─ VideoEncoder (codec of our offer) ─┐
AudioCapture ─ 20 ms stereo Opus (128 kbit/s) ─────┴─ MediaSink: StreamSink / EncodedSource
viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder ─ picture callback ─ Latest
stream audio ─ session audio thread (mixer, own volume) ─ speakers
```
- `Streamer::start(&codecs, StreamerConfig)` starts capturing right away (the
portal asks the user then), so a cancelled dialog never starts a stream;
frames are encoded only after `attach(sink)`, i.e. once the stream is live.
The encoder runs at the setup's bitrate; a viewer's keyframe request (on
the sink) forces a keyframe, and is kept until the encoder produced one.
Audio follows the capture clock across gaps. With the test pattern
(`SourceId::Synthetic`) the audio is a quiet sine tone. The portal's restore
token is available afterwards (`restore_token()`) to store.
- `peer_config(&codecs, config)` makes a viewer accept only what we decode
and a streamer offer only the codec it encodes (VP8 unless changed): all
viewers get the same frames, and a viewer picks from the offer.
- `VideoPipeline` decodes on its own thread. It starts at a keyframe, and
after a lost frame (`contiguous == false`, a lagging frame bus, a queue
longer than 30 frames) or a decoder error it skips to the next keyframe,
asking for one at most every 500 ms. Keyframes are recognised from the
bitstream (VP8 frame tag, VP9 header, H.264 IDR/SPS NAL units, AV1
sequence header OBU).
- `Viewer` feeds a `VideoPipeline` from the engine and sends
`RequestStreamKeyframe`; `LocalPreview` runs capture → encoder → decoder
without a server (the desktop app's `TSC_DEMO_STREAM`).
- The audio of watched streams does not go through this module: the session
hands the Opus frames to its audio thread, which plays them through the
jitter buffer and mixer under a made-up client id, with its own volume.
Playback is mono like the rest of the audio path.
## Codecs
Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with
@@ -187,6 +227,12 @@ run on Windows yet.
| Portal capture, PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) |
| Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only |
| Hardware encoders | – | stubs |
| Test pattern → VP8 → decoder, rectangle position and colour | `tsc-core` `media::tests::local_preview_decodes_the_pattern` | tested |
| Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `tsc-core` `stream::tests::test_pattern_through_stream_tasks` | tested |
| Stream audio (RTP time → jitter buffer ids, volume, end) | `tsc-core` `audio::tests::stream_audio_with_volume`, stream task test | tested |
| The same through the TeamSpeak 6 server | `tsc-core/tests/media_live.rs` (`TSC_LIVE=1`), `tsctl stream start --synthetic` / `watch --expect-frames` | tested against 6.0.0-beta13.1 |
| X11 monitor capture → VP8 → server → decoder | `tsctl stream start --source x11` under Xvfb | tested manually (debug build: about 8 fps at 1400×900) |
| Desktop app watching and sharing | Xvfb, `TSC_AUTOWATCH` / `TSC_AUTOSHARE` against tsctl, screenshots | tested manually |
| External capture providers (start, refusal, end of capture, default selection) | unit tests | tested |
| MediaCodec buffer layouts (I420, NV12 with padding, `MediaImage2` NV21, crop) | unit tests (`codec::image_layout`) | tested |
| MediaCodec encoders and decoders | – | compiles for `aarch64-linux-android` only (no device or emulator here) |
+12 -7
View File
@@ -173,14 +173,18 @@ cannot discover the ids of unknown streams), `updatestream` (`stream_id`,
`stream_name`, `max_width`, `max_height`, `max_framerate`, `properties`),
`notifystreamupdated`, `notifystreamattendees` (`return_code`, `client_id`).
### Streams that started before we joined (open)
### Streams that started before we joined (confirmed, 6.0.0-beta13.1, 2026-09-26)
`initserver` and `notifycliententerview` carry `client_is_streaming`, but no
stream id. Whether the server sends `notifystreamstarted` for running streams
to a client that connects or enters the channel later is not confirmed yet.
`tsctl stream list` shows such streamers as "id not announced"; `tsctl stream
watch --id <uuid>` can still join when the streamer is known (`--streamer-nick`,
or the only other client streaming). The smoke test starts the viewer first.
stream id, and the server does not send `notifystreamstarted` for running
streams to a client that connects later: a `tsctl stream list` started while
the desktop app streamed printed only "id not announced", while one connected
before the stream started got the id. Entering the channel later was not
probed separately. `tsctl stream list` shows such streamers as "id not
announced"; `tsctl stream watch --id <uuid>` can still join when the streamer
is known (`--streamer-nick`, or the only other client streaming). The desktop
app lists them as streaming but not watchable. The smoke test starts the
viewer first. How the official client learns these ids is open.
### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26)
@@ -213,7 +217,8 @@ libwebrtc, the stack the official client is built on:
- [ ] Which permission gates `setupstream` (error 2568).
- [x] Contents of `notifystreamstarted` (see probe results).
- [ ] Contents of `notifystreaminfo` (`requeststreaminfo id=<uuid>`).
- [ ] Whether a client that joins later is told about running streams (see above).
- [x] Whether a client that connects later is told about running streams: no (see above).
- [ ] How the official client finds running streams after connecting.
- [ ] Interop with the official TS6 client (its offer/answer details, codecs it
actually picks, whether it trickles candidates, mDNS host candidates).
Chromium's WebRTC stack interoperates (see above).
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

+3
View File
@@ -14,6 +14,7 @@ base64 = "0.22"
clap = { version = "4", features = ["derive", "env"] }
dirs = "6"
futures = "0.3"
png = "0.18"
serde_json = "1"
tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "signal", "time"] }
tracing = "0.1"
@@ -24,6 +25,8 @@ tsc-model = { path = "../../crates/tsc-model" }
tsc-query = { path = "../../crates/tsc-query" }
tsc-observer = { path = "../../crates/tsc-observer" }
tsc-audio = { path = "../../crates/tsc-audio", default-features = false }
# The stream media pipeline (capture, VP8, decoding), without audio devices.
tsc-core = { path = "../../crates/tsc-core", default-features = false, features = ["media-desktop"] }
tsc-stream = { path = "../../crates/tsc-stream" }
tokio-tungstenite = "0.30"
futures-util = "0.3.34"
+172 -42
View File
@@ -1,18 +1,26 @@
//! `tsctl connect ... stream start|list|watch`: TeamSpeak 6 streams.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use clap::{Args, Subcommand};
use futures::prelude::*;
use tokio::io::{AsyncBufReadExt, BufReader, Lines, Stdin};
use tokio::time::{Instant, Interval, sleep_until};
use tsc_core::media::tsc_media::capture::SourceId;
use tsc_core::media::tsc_media::{Codecs, VideoFrame, convert};
use tsc_core::media::{
CaptureBackend, EncodedSource, Latest, Streamer, StreamerConfig, VideoPipeline, peer_config,
stream_codec,
};
use tsc_model::ServerFlavor;
use tsc_stream::{
EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, StreamInfo,
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource,
WatchEvent,
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, WatchEvent,
};
use tsclientlib::events::{Event, PropertyId};
use tsclientlib::prelude::*;
@@ -35,28 +43,36 @@ pub struct StreamArgs {
#[derive(Subcommand, Debug, Clone)]
pub enum StreamCommand {
/// Stream in our channel. Without `--auto-accept`, answer join requests on
/// stdin: `accept <clid>`, `deny <clid>`, `kick <clid>`, `stop`.
/// Stream in our channel: the screen (VP8) and system audio (Opus).
/// Without `--auto-accept`, answer join requests on stdin: `accept
/// <clid>`, `deny <clid>`, `kick <clid>`, `stop`.
Start {
/// Stream name.
#[arg(long, default_value = "tsctl")]
name: String,
/// Send synthetic frames (tiny VP8 keyframes and silent Opus); needed
/// until capture and encoders exist.
#[arg(long)]
/// What to capture: `synthetic` (a moving test pattern and a tone),
/// `x11[:<monitor>]`, `screen[:<monitor>]` (this session's backend),
/// `window:<id>` or `portal` (the desktop's dialog).
#[arg(long, default_value = "screen")]
source: String,
/// Same as `--source synthetic`.
#[arg(long, conflicts_with = "source")]
synthetic: bool,
/// Size of the test pattern.
#[arg(long, default_value = "1280x720")]
size: String,
/// Accept every viewer.
#[arg(long)]
auto_accept: bool,
/// Stop after this many seconds [default: until Ctrl-C].
#[arg(long)]
seconds: Option<u64>,
/// Synthetic video frames per second.
/// Video frames per second.
#[arg(long, default_value_t = 30)]
fps: u32,
/// Size of each synthetic video frame in bytes.
#[arg(long, default_value_t = 4000)]
frame_size: usize,
/// Video bitrate in kbit/s (announced in `setupstream` too).
#[arg(long, default_value_t = 4608)]
bitrate: u32,
/// No audio track.
#[arg(long)]
no_audio: bool,
@@ -76,12 +92,15 @@ pub enum StreamCommand {
/// Nickname of the streamer.
#[arg(long)]
streamer_nick: Option<String>,
/// Exit successfully once this many video frames arrived.
/// Exit successfully once this many video frames were decoded.
#[arg(long)]
expect_frames: Option<u64>,
/// Give up after this many seconds; fails if `--expect-frames` was not reached.
#[arg(long)]
timeout: Option<u64>,
/// Save the last decoded picture as PNG.
#[arg(long)]
save_frame: Option<PathBuf>,
},
}
@@ -99,47 +118,90 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
} else if args.no_stun {
config.stun_servers.clear();
}
// Offer the codec we encode, accept what we decode.
let codecs = Arc::new(Codecs::new());
let config = peer_config(&codecs, config);
let codec = stream_codec(&codecs, &config);
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
let result = match &args.command {
StreamCommand::Start {
name,
source,
synthetic,
size,
auto_accept,
seconds,
fps,
frame_size,
bitrate,
no_audio,
} => {
let source = frame_source(*synthetic, *fps, *frame_size, !no_audio)?;
let setup = StreamSetup { name: name.clone(), audio: !no_audio, ..Default::default() };
let source = if *synthetic { "synthetic" } else { source.as_str() };
let (source, backend) = parse_source(source)?;
let Some(codec) = codec else { bail!("no video encoder in this build") };
let config = StreamerConfig {
source,
backend,
fps: *fps,
bitrate_kbps: *bitrate,
codec,
audio: !no_audio,
synthetic_size: parse_size(size)?,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.context("capture")?;
println!("capturing with {} ({codec})", streamer.backend());
if let Some(e) = streamer.audio_error() {
println!("no system audio: {e}");
}
let setup = StreamSetup {
name: name.clone(),
bitrate: *bitrate,
audio: streamer.has_audio(),
..Default::default()
};
let options = StreamerOptions { setup, auto_accept: *auto_accept };
let source = EncodedSource::new(streamer);
start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await
}
StreamCommand::List { settle_ms } => {
list(con, &mut driver, Duration::from_millis(*settle_ms)).await
}
StreamCommand::Watch { id, streamer_nick, expect_frames, timeout } => {
StreamCommand::Watch { id, streamer_nick, expect_frames, timeout, save_frame } => {
let target = Target { id: id.clone(), streamer_nick: streamer_nick.clone() };
let timeout = timeout.map(Duration::from_secs);
watch(con, &mut driver, &target, *expect_frames, timeout).await
let expect = *expect_frames;
let save = save_frame.as_deref();
watch(con, &mut driver, codecs, &target, expect, timeout, save).await
}
};
driver.finish(con).await;
result
}
/// Where a streamer's frames come from. Capture and encoders (`tsc-media`)
/// plug in here.
fn frame_source(
synthetic: bool,
fps: u32,
frame_size: usize,
audio: bool,
) -> Result<Box<dyn FrameSource>> {
if !synthetic {
bail!("only synthetic frames are available yet: pass --synthetic");
}
Ok(Box::new(SyntheticSource::new(fps, frame_size, audio)))
/// `synthetic`, `x11[:<monitor>]`, `screen[:<monitor>]`, `window:<id>`, `portal`.
fn parse_source(spec: &str) -> Result<(SourceId, CaptureBackend)> {
let (kind, arg) = spec.split_once(':').map_or((spec, None), |(k, a)| (k, Some(a)));
let number = |default: u64| -> Result<u64> {
arg.map_or(Ok(default), |a| {
let a = a.trim_start_matches("0x");
let radix = if a.len() < arg.unwrap_or_default().len() { 16 } else { 10 };
u64::from_str_radix(a, radix).with_context(|| format!("bad number in {spec:?}"))
})
};
Ok(match kind {
"synthetic" => (SourceId::Synthetic, CaptureBackend::Auto),
"portal" => (SourceId::Portal, CaptureBackend::Auto),
"x11" => (SourceId::Monitor(number(0)? as u32), CaptureBackend::X11),
"screen" | "monitor" => (SourceId::Monitor(number(0)? as u32), CaptureBackend::Auto),
"window" if arg.is_some() => (SourceId::Window(number(0)?), CaptureBackend::Auto),
_ => bail!("unknown source {spec:?}: synthetic, x11[:N], screen[:N], window:<id>, portal"),
})
}
/// `<width>x<height>`.
fn parse_size(size: &str) -> Result<(u32, u32)> {
let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)));
parsed.with_context(|| format!("bad size {size:?}, expected e.g. 1280x720"))
}
/// What woke the driver.
@@ -290,7 +352,7 @@ async fn start(
con: &mut Connection,
driver: &mut Driver,
options: StreamerOptions,
mut source: Box<dyn FrameSource>,
mut source: EncodedSource,
length: Option<Duration>,
) -> Result<()> {
let auto_accept = options.auto_accept;
@@ -357,6 +419,10 @@ async fn start(
StreamerEvent::KeyframeRequest => source.request_keyframe(),
StreamerEvent::Ended(reason) => {
println!("sent {video} video / {audio} audio frames to connected viewers");
let stats = source.streamer().stats();
if let Some(e) = &stats.error {
println!("last encoder error: {e}");
}
return match reason {
EndReason::Local => Ok(()),
other => bail!("stream ended: {}", end_text(&other)),
@@ -458,19 +524,86 @@ impl Target {
}
}
/// Save a picture as an RGBA PNG.
fn save_png(picture: &VideoFrame, path: &Path) -> Result<()> {
let rgba = convert::to_rgba_vec(picture)?;
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut encoder = png::Encoder::new(file, picture.width, picture.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header()?.write_image_data(&rgba)?;
Ok(())
}
async fn watch(
con: &mut Connection,
driver: &mut Driver,
codecs: Arc<Codecs>,
target: &Target,
expect: Option<u64>,
timeout: Option<Duration>,
save: Option<&Path>,
) -> Result<()> {
let deadline = timeout.map(|t| Instant::now() + t);
let mut watching: Option<String> = None;
let (mut video, mut audio) = (0u64, 0u64);
let mut codec = None;
let mut waiting_told = false;
// Decoding runs on its own thread; the loop checks its progress.
let latest = Arc::new(Latest::new());
let keyframe_wanted = Arc::new(AtomicBool::new(false));
let decoder = VideoPipeline::new(
codecs,
{
let latest = latest.clone();
move |picture| {
latest.put(picture);
}
},
{
let wanted = keyframe_wanted.clone();
move || wanted.store(true, Ordering::Relaxed)
},
);
let mut tick = tokio::time::interval(Duration::from_millis(100));
let mut first_picture = true;
let mut last_picture: Option<VideoFrame> = None;
let summary = |video: u64, audio: u64, decoder: &VideoPipeline| {
let stats = decoder.stats();
println!(
"received {video} video / {audio} audio frames, decoded {} pictures{}",
stats.decoded,
stats.error.map(|e| format!(" (last error: {e})")).unwrap_or_default()
);
};
let save_last = |last: &Option<VideoFrame>| -> Result<()> {
match (save, last) {
(Some(path), Some(picture)) => {
save_png(picture, path)?;
println!("saved {}", path.display());
Ok(())
}
(Some(_), None) => bail!("no picture to save"),
(None, _) => Ok(()),
}
};
loop {
if let Some(picture) = latest.take() {
if first_picture {
println!("first picture decoded ({}x{})", picture.width, picture.height);
first_picture = false;
}
last_picture = Some(picture);
}
if let Some(id) = &watching
&& keyframe_wanted.swap(false, Ordering::Relaxed)
{
driver.streams.request_keyframe(id);
}
if expect.is_some_and(|n| decoder.stats().decoded >= n) {
summary(video, audio, &decoder);
return save_last(&last_picture);
}
if watching.is_none() {
if let Some((id, streamer)) = target.find(con, &driver.streams) {
println!("watching {id} of {} (clid {})", nick(con, streamer), streamer.0);
@@ -497,29 +630,26 @@ async fn watch(
if f.kind == MediaKind::Video && codec.replace(f.codec).is_none() {
println!("first video frame ({:?}, {} bytes)", f.codec, f.data.len());
}
if expect.is_some_and(|n| video >= n) {
println!("received {video} video / {audio} audio frames");
return Ok(());
}
decoder.push(f);
}
WatchEvent::Ended(reason) => {
println!("received {video} video / {audio} audio frames");
summary(video, audio, &decoder);
match expect {
Some(n) => bail!("{} before {n} video frames arrived", end_text(&reason)),
Some(n) => bail!("{} before {n} pictures were decoded", end_text(&reason)),
None => {
println!("{}", end_text(&reason));
return Ok(());
return save_last(&last_picture.or_else(|| latest.take()));
}
}
}
}
}
match driver.next(con, deadline, None, None).await? {
match driver.next(con, deadline, Some(&mut tick), None).await? {
Wake::Deadline | Wake::Interrupted => {
println!("received {video} video / {audio} audio frames");
summary(video, audio, &decoder);
return match expect {
Some(n) => bail!("timed out waiting for {n} video frames"),
None => Ok(()),
Some(n) => bail!("timed out waiting for {n} decoded pictures"),
None => save_last(&last_picture.or_else(|| latest.take())),
};
}
_ => {}