diff --git a/Cargo.lock b/Cargo.lock index 30dcfc0..724fb71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/README.md b/README.md index b8f0168..bbf2ab0 100644 --- a/README.md +++ b/README.md @@ -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 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=` (with `TSC_SCREENSHOT_DELAY`), +`TSC_DEMO_STREAM=1` (a local test stream in the viewer, no server needed), +`TSC_OPEN=share|settings[:]|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 diff --git a/crates/tsc-core/Cargo.toml b/crates/tsc-core/Cargo.toml index fa9195b..3271e8c 100644 --- a/crates/tsc-core/Cargo.toml +++ b/crates/tsc-core/Cargo.toml @@ -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" } diff --git a/crates/tsc-core/src/audio.rs b/crates/tsc-core/src/audio.rs index cf97582..ef3dd75 100644 --- a/crates/tsc-core/src/audio.rs +++ b/crates/tsc-core/src/audio.rs @@ -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), /// 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, } @@ -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) { + 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, - errors: mpsc::UnboundedSender, - voice_activation: bool, + events: mpsc::UnboundedSender, + 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, + /// Watched streams whose audio plays through the mixer. + streams: HashMap, + stream_volumes: HashMap, /// Processed microphone audio, for tests. #[cfg(test)] tap: Vec, @@ -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 = 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 { + 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, 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, outgoing: mpsc::UnboundedSender, - errors: mpsc::UnboundedSender, + events: mpsc::UnboundedSender, 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, 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, + 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 = 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); diff --git a/crates/tsc-core/src/lib.rs b/crates/tsc-core/src/lib.rs index 4226b28..74daa13 100644 --- a/crates/tsc-core/src/lib.rs +++ b/crates/tsc-core/src/lib.rs @@ -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), + /// 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, /// Our own channel while voice-connected. pub own_channel: Option, + /// Our own client id while voice-connected. + pub own_client: Option, 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, + 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, events: broadcast::Sender, frames: broadcast::Sender, + 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, ) { let mut sessions: HashMap = HashMap::new(); + let mut settings = AudioSettings::default(); + let mut mic_test: Option = 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) -> 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") + } } } diff --git a/crates/tsc-core/src/media.rs b/crates/tsc-core/src/media.rs new file mode 100644 index 0000000..fd4e8f8 --- /dev/null +++ b/crates/tsc-core/src/media.rs @@ -0,0 +1,1108 @@ +//! Stream media (feature `media`): capture and encoding for our stream, +//! decoding for the streams we watch. +//! +//! - [`Streamer`] captures a screen or window (and optionally system audio), +//! encodes the video with the codec our offer carries ([`stream_codec`], +//! VP8 by default) at the bitrate of the stream setup, and the audio with +//! Opus (48 kHz stereo, 20 ms). It hands the frames to a [`MediaSink`]: +//! the [`StreamSink`] of a live stream, or an [`EncodedSource`] for code +//! that drives `tsc_stream::Streams` itself. Keyframe requests of viewers +//! are honoured. +//! - [`VideoPipeline`] decodes the video of a watched stream on its own +//! thread and hands every picture to a callback. After lost frames or +//! decoder errors it skips to the next keyframe and asks for one. +//! - [`Viewer`] is a [`VideoPipeline`] fed from [`Engine::subscribe_frames`]. +//! The stream's audio needs nothing here: the session plays it +//! ([`Command::SetStreamVolume`]). +//! - [`Latest`] hands the newest picture to a slower consumer such as a UI. +//! - [`LocalPreview`] runs capture → encoder → decoder without a server. +//! +//! [`tsc_media`] is re-exported for sources, codecs and pixel conversion. +//! Codecs are chosen through `tsc_media::Codecs`, so whatever backends the +//! build has are used (libvpx and OpenH264 with feature `media-desktop`, +//! MediaCodec on Android). + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use tracing::{debug, warn}; +use tsc_audio::{VoiceCodec, VoiceEncoder}; +pub use tsc_media; +use tsc_media::capture::synthetic::{SineSource, SyntheticScreen}; +use tsc_media::capture::{ + self, AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, +}; +use tsc_media::{ + AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, VideoEncoder, VideoFrame, +}; +use tsc_stream::{ + EncodedFrame, FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, +}; + +use crate::stream::StreamSink; +use crate::{Command, Engine, SessionId}; + +/// How long media threads wait for input before checking whether to stop. +const POLL: Duration = Duration::from_millis(100); +/// Samples per channel in one 20 ms Opus frame at 48 kHz. +const OPUS_FRAME: usize = 960; +/// Opus bitrate of stream audio (stereo, music). +const OPUS_BITRATE: i32 = 128_000; +/// Video frames the decoder may fall behind before the queue is dropped. +pub const MAX_QUEUED: usize = 30; +/// Keyframe requests while waiting for one are at least this far apart. +const KEYFRAME_RETRY: Duration = Duration::from_millis(500); + +#[derive(Debug, thiserror::Error)] +pub enum MediaError { + #[error(transparent)] + Media(#[from] tsc_media::Error), + #[error("Opus: {0}")] + Opus(#[from] tsc_audio::Error), +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result, MediaError> { + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(f) + .map_err(|e| MediaError::Media(e.into())) +} + +/// The `tsc_media` codec of a negotiated video codec. +pub fn media_codec(codec: VideoCodec) -> Codec { + match codec { + VideoCodec::Vp8 => Codec::Vp8, + VideoCodec::Vp9 => Codec::Vp9, + VideoCodec::H264 => Codec::H264, + VideoCodec::Av1 => Codec::Av1, + } +} + +/// The negotiable video codec of a `tsc_media` codec. +pub fn video_codec(codec: Codec) -> VideoCodec { + match codec { + Codec::Vp8 => VideoCodec::Vp8, + Codec::Vp9 => VideoCodec::Vp9, + Codec::H264 => VideoCodec::H264, + Codec::Av1 => VideoCodec::Av1, + } +} + +/// The codec our stream is encoded with: the first codec of the offer +/// (`config.video_codecs`) that we can encode. +pub fn stream_codec(codecs: &Codecs, config: &PeerConfig) -> Option { + let encodable = codecs.encoder_codecs(); + config.video_codecs.iter().map(|c| media_codec(*c)).find(|c| encodable.contains(c)) +} + +/// `config` adjusted to what `codecs` can do: viewers accept only codecs we +/// decode, and a streamer offers only the codec it encodes (every viewer +/// gets the same frames, and a viewer picks from the offer). +pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig { + config.accept_video_codecs = codecs.decoders().into_iter().map(video_codec).collect(); + if let Some(codec) = stream_codec(codecs, &config) { + config.video_codecs = vec![video_codec(codec)]; + } + config +} + +/// Monitors and windows of this session's capture backend. The portal (on +/// Wayland) lists a single entry: its own dialog picks. +pub fn screen_sources() -> Result, MediaError> { + Ok(capture::default_screen_capture()?.sources()?) +} + +/// The synthetic test pattern as a source. +pub fn test_pattern_source() -> CaptureSource { + let (width, height) = StreamerConfig::default().synthetic_size; + CaptureSource { + id: SourceId::Synthetic, + name: "Test pattern".into(), + width, + height, + primary: false, + } +} + +/// Where a [`Streamer`] puts encoded frames. +pub trait MediaSink: Send + Sync { + /// Send one frame; `false` once nobody takes frames any more. + fn send(&self, frame: EncodedFrame) -> bool; + + /// Whether a keyframe was asked for since the last call. + fn take_keyframe_request(&self) -> bool; +} + +impl MediaSink for StreamSink { + fn send(&self, frame: EncodedFrame) -> bool { + StreamSink::send(self, frame) + } + + fn take_keyframe_request(&self) -> bool { + StreamSink::take_keyframe_request(self) + } +} + +/// Which backend captures monitors and windows. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum CaptureBackend { + /// The one for this desktop session (`capture::default_screen_capture`). + #[default] + Auto, + /// X11, also under Wayland through XWayland (Linux). + X11, +} + +/// What and how to stream. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamerConfig { + pub source: SourceId, + /// For monitors and windows. + pub backend: CaptureBackend, + /// Frames per second (1 to 60). + pub fps: u32, + /// Video bitrate in kbit/s, as in `StreamSetup::bitrate`. + pub bitrate_kbps: u32, + /// The codec of our offer, see [`stream_codec`]. + pub codec: Codec, + /// Capture and send system audio (a sine tone with the test pattern). + pub audio: bool, + pub cursor: bool, + /// Size of the test pattern ([`SourceId::Synthetic`]). + pub synthetic_size: (u32, u32), + /// Portal restore token from an earlier share: the desktop may skip its + /// dialog. The new one is [`Streamer::restore_token`]. + pub restore_token: Option, +} + +impl Default for StreamerConfig { + fn default() -> Self { + Self { + source: SourceId::Monitor(0), + backend: CaptureBackend::Auto, + fps: 30, + bitrate_kbps: 4608, + codec: Codec::Vp8, + audio: true, + cursor: true, + synthetic_size: (1280, 720), + restore_token: None, + } + } +} + +/// What a [`Streamer`] has done so far. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StreamerStats { + /// Frames handed to the sink. + pub video_frames: u64, + pub audio_frames: u64, + /// Size of the last captured frame. + pub width: u32, + pub height: u32, + /// The capture stopped by itself (window closed, sharing ended in the + /// desktop's UI, ...). + pub capture_ended: bool, + /// The last encoder error. + pub error: Option, +} + +#[derive(Default)] +struct Shared { + sink: Mutex>>, + stop: AtomicBool, + video_frames: AtomicU64, + audio_frames: AtomicU64, + /// `width << 32 | height` of the last captured frame. + size: AtomicU64, + capture_ended: AtomicBool, + error: Mutex>, +} + +impl Shared { + fn sink(&self) -> Option> { + lock(&self.sink).clone() + } + + fn stopped(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } +} + +/// Capture and encoding for our stream. Frames are captured from the start +/// (the portal asks the user then), but only encoded once a sink is +/// [attached](Streamer::attach). Stops when dropped. +pub struct Streamer { + shared: Arc, + screen: Option>, + audio: Option>, + threads: Vec>, + backend: &'static str, + restore_token: Option, + audio_error: Option, +} + +impl Streamer { + /// Start capturing. Must run on a Tokio runtime (the portal talks D-Bus + /// on it); may wait for the user in the portal's dialog. + pub async fn start(codecs: &Codecs, config: StreamerConfig) -> Result { + let fps = config.fps.clamp(1, 60); + let encoder = codecs.new_encoder( + config.codec, + EncoderConfig { + fps, + bitrate_bps: config.bitrate_kbps.clamp(100, 10_000) * 1000, + content: ContentHint::Screen, + ..EncoderConfig::default() + }, + )?; + let options = CaptureOptions { fps, cursor: config.cursor, ..CaptureOptions::default() }; + // The portal's token for this choice comes with the capture. + let (screen, frames, restore_token): (Box, _, _) = match &config.source { + SourceId::Synthetic => { + let (w, h) = config.synthetic_size; + let mut screen = SyntheticScreen::new(w, h); + let frames = screen.start(&SourceId::Synthetic, &options).await?; + (Box::new(screen), frames, None) + } + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + SourceId::Portal => { + use tsc_media::capture::portal::PortalCapture; + let mut portal = PortalCapture::with_restore_token(config.restore_token.clone()); + let frames = portal.start(&SourceId::Portal, &options).await?; + let token = portal.restore_token().map(str::to_owned); + (Box::new(portal), frames, token) + } + source => { + let mut screen = match config.backend { + CaptureBackend::Auto => capture::default_screen_capture()?, + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + CaptureBackend::X11 => Box::new(tsc_media::capture::x11::X11Capture::new()), + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + CaptureBackend::X11 => { + return Err(tsc_media::Error::CaptureUnavailable { + backend: "x11", + reason: "X11 capture is only in Linux desktop builds".into(), + } + .into()); + } + }; + let frames = screen.start(source, &options).await?; + (screen, frames, None) + } + }; + let backend = screen.backend(); + + let shared = Arc::new(Shared::default()); + let mut streamer = Self { + shared: shared.clone(), + screen: Some(screen), + audio: None, + threads: Vec::new(), + backend, + restore_token, + audio_error: None, + }; + streamer.threads.push(spawn("tsc-stream-video", { + let shared = shared.clone(); + move || video_loop(&shared, frames, encoder) + })?); + if config.audio { + match start_audio(&config.source) { + Ok((capture, buffers, encoder)) => { + streamer.audio = Some(capture); + streamer.threads.push(spawn("tsc-stream-audio", move || { + audio_loop(&shared, buffers, encoder) + })?); + } + Err(e) => { + warn!("streaming without audio: {e}"); + streamer.audio_error = Some(e.to_string()); + } + } + } + Ok(streamer) + } + + /// Start encoding into `sink` (replacing an earlier one). + pub fn attach(&self, sink: Arc) { + *lock(&self.shared.sink) = Some(sink); + } + + /// Stop encoding; capture goes on. + pub fn detach(&self) { + *lock(&self.shared.sink) = None; + } + + /// The capture backend (`"x11"`, `"portal"`, `"synthetic"`, ...). + pub fn backend(&self) -> &'static str { + self.backend + } + + /// The portal's token for this choice of screen, to store for next time. + pub fn restore_token(&self) -> Option<&str> { + self.restore_token.as_deref() + } + + /// Why system audio is not captured, if it was asked for. + pub fn audio_error(&self) -> Option<&str> { + self.audio_error.as_deref() + } + + /// Whether system audio is captured. + pub fn has_audio(&self) -> bool { + self.audio.is_some() + } + + pub fn stats(&self) -> StreamerStats { + let size = self.shared.size.load(Ordering::Relaxed); + StreamerStats { + video_frames: self.shared.video_frames.load(Ordering::Relaxed), + audio_frames: self.shared.audio_frames.load(Ordering::Relaxed), + width: (size >> 32) as u32, + height: size as u32, + capture_ended: self.shared.capture_ended.load(Ordering::Relaxed), + error: lock(&self.shared.error).clone(), + } + } + + /// Stop capturing and encoding. + pub fn stop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.detach(); + if let Some(mut screen) = self.screen.take() { + screen.stop(); + } + if let Some(mut audio) = self.audio.take() { + audio.stop(); + } + for thread in self.threads.drain(..) { + let _ = thread.join(); + } + } +} + +impl Drop for Streamer { + fn drop(&mut self) { + self.stop(); + } +} + +type AudioStart = (Box, FrameReceiver, VoiceEncoder); + +fn start_audio(source: &SourceId) -> Result { + let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; + encoder.set_bitrate(OPUS_BITRATE)?; + let mut capture: Box = match source { + SourceId::Synthetic => Box::new(SineSource::new(440.0, 0.05)), + _ => capture::default_audio_capture()?, + }; + let buffers = capture.start()?; + Ok((capture, buffers, encoder)) +} + +fn video_loop( + shared: &Shared, + mut frames: FrameReceiver, + mut encoder: Box, +) { + // A requested keyframe the encoder has not produced yet (rate control + // may skip a frame). + let mut keyframe_due = false; + while !shared.stopped() { + let Some(frame) = frames.recv_timeout(POLL) else { + if frames.is_closed() { + debug!("screen capture ended"); + shared.capture_ended.store(true, Ordering::Relaxed); + break; + } + continue; + }; + let size = u64::from(frame.width) << 32 | u64::from(frame.height); + shared.size.store(size, Ordering::Relaxed); + let Some(sink) = shared.sink() else { continue }; + let keyframe = sink.take_keyframe_request() || keyframe_due; + match encoder.encode(&frame, keyframe) { + Ok(encoded) => { + keyframe_due = keyframe && !encoded.iter().any(|f| f.keyframe); + for f in encoded { + let frame = EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(f.pts_90khz), + data: f.data.into(), + }; + if sink.send(frame) { + shared.video_frames.fetch_add(1, Ordering::Relaxed); + } + } + } + Err(e) => { + warn!("video encoding failed: {e}"); + keyframe_due = keyframe; + *lock(&shared.error) = Some(e.to_string()); + } + } + } +} + +/// Interleaved stereo from any channel count (extra channels are dropped). +fn append_stereo(buffer: &AudioBuffer, out: &mut Vec) { + match buffer.channels { + 0 => {} + 1 => out.extend(buffer.samples.iter().flat_map(|s| [*s, *s])), + 2 => out.extend_from_slice(&buffer.samples), + n => { + for frame in buffer.samples.chunks_exact(usize::from(n)) { + out.extend_from_slice(&frame[..2]); + } + } + } +} + +fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut encoder: VoiceEncoder) { + // Interleaved stereo waiting for a whole Opus frame. + let mut pending: Vec = Vec::new(); + // Opus frames since the capture started: the RTP time in 20 ms steps. + let mut frames: u64 = 0; + while !shared.stopped() { + let Some(buffer) = buffers.recv_timeout(POLL) else { + if buffers.is_closed() { + debug!("system audio capture ended"); + break; + } + continue; + }; + // Follow the capture clock across gaps (nothing played, sink not + // attached yet), so audio stays in step with video. + let at = buffer.timestamp.as_micros() as u64 * 48 / 1000; + let position = frames * OPUS_FRAME as u64 + (pending.len() / 2) as u64; + if at > position + 10 * OPUS_FRAME as u64 { + pending.clear(); + frames = at / OPUS_FRAME as u64; + } + let Some(sink) = shared.sink() else { continue }; + append_stereo(&buffer, &mut pending); + while pending.len() >= OPUS_FRAME * 2 { + let data: Option> = match encoder.encode_to_bytes(&pending[..OPUS_FRAME * 2]) + { + Ok(data) => Some(data.into()), + Err(e) => { + warn!("audio encoding failed: {e}"); + None + } + }; + pending.drain(..OPUS_FRAME * 2); + if let Some(data) = data { + let time = MediaTime::new(frames * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); + if sink.send(EncodedFrame { kind: MediaKind::Audio, time, data }) { + shared.audio_frames.fetch_add(1, Ordering::Relaxed); + } + } + frames += 1; + } + } +} + +/// Collects a [`Streamer`]'s frames for [`EncodedSource`]. +struct ChannelSink { + tx: std_mpsc::Sender, + keyframe: AtomicBool, +} + +impl MediaSink for ChannelSink { + fn send(&self, frame: EncodedFrame) -> bool { + self.tx.send(frame).is_ok() + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } +} + +/// A [`Streamer`] as a [`FrameSource`], for code that runs +/// `tsc_stream::Streams` itself (e.g. tsctl). +pub struct EncodedSource { + streamer: Streamer, + frames: std_mpsc::Receiver, + sink: Arc, +} + +impl EncodedSource { + pub fn new(streamer: Streamer) -> Self { + let (tx, frames) = std_mpsc::channel(); + let sink = Arc::new(ChannelSink { tx, keyframe: AtomicBool::new(true) }); + streamer.attach(sink.clone()); + Self { streamer, frames, sink } + } + + pub fn streamer(&self) -> &Streamer { + &self.streamer + } +} + +impl FrameSource for EncodedSource { + fn poll_frames(&mut self, _now: Instant, out: &mut Vec) { + out.extend(self.frames.try_iter()); + } + + fn request_keyframe(&mut self) { + self.sink.keyframe.store(true, Ordering::Relaxed); + } +} + +/// Whether `data` (one depacketized frame) starts a picture that decodes on +/// its own. Unknown formats count as keyframes, so the decoder gets to try. +pub fn is_keyframe(codec: Codec, data: &[u8]) -> bool { + match codec { + // Frame tag: bit 0 is 0 for key frames. + Codec::Vp8 => data.first().is_some_and(|b| b & 1 == 0), + Codec::Vp9 => vp9_is_keyframe(data), + Codec::H264 => h264_nal_types(data).any(|t| t == 5 || t == 7), + Codec::Av1 => av1_has_sequence_header(data).unwrap_or(true), + } +} + +/// VP9 uncompressed header: frame marker, profile, show_existing_frame, +/// frame_type (0 = key frame). +fn vp9_is_keyframe(data: &[u8]) -> bool { + let Some(&b) = data.first() else { return false }; + if b >> 6 != 2 { + return false; + } + let profile = ((b >> 5) & 1) | (((b >> 4) & 1) << 1); + // Profile 3 has a reserved bit after the profile. + let mut bit = if profile == 3 { 3 } else { 4 }; + let read = |bit: u32| (u32::from(b) >> (7 - bit)) & 1; + let show_existing = read(bit); + if show_existing == 1 { + return false; + } + bit += 1; + read(bit) == 0 +} + +/// NAL unit types of an Annex B H.264 frame. +fn h264_nal_types(data: &[u8]) -> impl Iterator + '_ { + data.windows(4).filter_map(|w| (w[..3] == [0, 0, 1]).then_some(w[3] & 0x1f)) +} + +/// Whether an AV1 temporal unit carries a sequence header OBU (sent with +/// key frames); `None` if the OBUs cannot be parsed. +fn av1_has_sequence_header(mut data: &[u8]) -> Option { + while let Some(&header) = data.first() { + let obu_type = (header >> 3) & 0x0f; + if obu_type == 1 { + return Some(true); + } + let extension = header & 0x04 != 0; + let has_size = header & 0x02 != 0; + let mut pos = 1 + usize::from(extension); + if !has_size { + return Some(false); + } + // LEB128 size. + let mut size = 0usize; + for i in 0..8 { + let byte = *data.get(pos)?; + pos += 1; + size |= usize::from(byte & 0x7f) << (7 * i); + if byte & 0x80 == 0 { + break; + } + } + data = data.get(pos + size..)?; + } + Some(false) +} + +/// Decoding statistics of a [`VideoPipeline`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DecodeStats { + /// Pictures handed to the callback. + pub decoded: u64, + /// Frames skipped while waiting for a keyframe. + pub skipped: u64, + pub keyframe_requests: u64, + pub codec: Option, + pub width: u32, + pub height: u32, + /// The last error (no decoder for the codec, decoding failed). + pub error: Option, +} + +#[derive(Default)] +struct QueueState { + frames: VecDeque, + /// Frames were dropped: wait for a keyframe. + lost: bool, + closed: bool, +} + +#[derive(Default)] +struct DecodeQueue { + state: Mutex, + cond: Condvar, + stats: Mutex, +} + +/// Feeds frames into a [`VideoPipeline`]; cheap to clone. +#[derive(Clone)] +pub struct FrameInput { + queue: Arc, +} + +impl FrameInput { + /// Queue a video frame (audio frames are ignored). When the decoder + /// falls more than [`MAX_QUEUED`] frames behind, the queue is dropped + /// and decoding resumes at the next keyframe. + pub fn push(&self, frame: MediaFrame) { + if frame.kind != MediaKind::Video { + return; + } + let mut state = lock(&self.queue.state); + if state.frames.len() >= MAX_QUEUED { + state.frames.clear(); + state.lost = true; + } + state.frames.push_back(frame); + drop(state); + self.queue.cond.notify_one(); + } + + /// Frames were lost before they reached us (e.g. a lagging receiver). + pub fn lost(&self) { + lock(&self.queue.state).lost = true; + } +} + +/// Decodes the video frames of one stream on its own thread. See the +/// [module docs](self). +pub struct VideoPipeline { + input: FrameInput, + thread: Option>, +} + +impl VideoPipeline { + /// `on_frame` gets every decoded picture on the decoding thread; + /// `request_keyframe` is called when the decoder needs one (at most + /// every half second). + pub fn new( + codecs: Arc, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + request_keyframe: impl Fn() + Send + 'static, + ) -> Self { + let queue = Arc::new(DecodeQueue::default()); + let thread = std::thread::Builder::new() + .name("tsc-stream-decode".into()) + .spawn({ + let queue = queue.clone(); + move || decode_loop(&queue, &codecs, on_frame, request_keyframe) + }) + .map_err(|e| warn!("cannot start the video decoder: {e}")) + .ok(); + Self { input: FrameInput { queue }, thread } + } + + /// Where frames go in. + pub fn input(&self) -> FrameInput { + self.input.clone() + } + + pub fn push(&self, frame: MediaFrame) { + self.input.push(frame); + } + + pub fn stats(&self) -> DecodeStats { + lock(&self.input.queue.stats).clone() + } +} + +impl Drop for VideoPipeline { + fn drop(&mut self) { + lock(&self.input.queue.state).closed = true; + self.input.queue.cond.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn decode_loop( + queue: &DecodeQueue, + codecs: &Codecs, + mut on_frame: impl FnMut(VideoFrame), + request_keyframe: impl Fn(), +) { + let mut decoder: Option<(Codec, Box)> = None; + // Start at a keyframe; the streamer sends one when a viewer connects. + let mut waiting = true; + let mut last_request: Option = None; + let mut request = |stats: &Mutex| { + if last_request.is_none_or(|t| t.elapsed() >= KEYFRAME_RETRY) { + last_request = Some(Instant::now()); + lock(stats).keyframe_requests += 1; + request_keyframe(); + } + }; + let set_error = |message: String| lock(&queue.stats).error = Some(message); + loop { + let (frame, lost) = { + let mut state = lock(&queue.state); + loop { + if state.closed { + return; + } + if let Some(frame) = state.frames.pop_front() { + break (frame, std::mem::take(&mut state.lost)); + } + state = + queue.cond.wait_timeout(state, POLL).unwrap_or_else(PoisonError::into_inner).0; + } + }; + let codec = match Codec::try_from(frame.codec) { + Ok(codec) => codec, + Err(e) => { + set_error(e.to_string()); + continue; + } + }; + if decoder.as_ref().is_none_or(|(c, _)| *c != codec) { + match codecs.new_decoder(codec) { + Ok(d) => { + decoder = Some((codec, d)); + waiting = true; + lock(&queue.stats).codec = Some(codec); + } + Err(e) => { + if decoder.is_some() || lock(&queue.stats).error.is_none() { + warn!("no decoder for the stream: {e}"); + } + decoder = None; + set_error(e.to_string()); + continue; + } + } + } + if lost || !frame.contiguous { + waiting = true; + } + if waiting { + if !is_keyframe(codec, &frame.data) { + lock(&queue.stats).skipped += 1; + request(&queue.stats); + continue; + } + waiting = false; + } + let Some((_, dec)) = &mut decoder else { continue }; + match dec.decode(&frame.data) { + Ok(Some(picture)) => { + { + let mut stats = lock(&queue.stats); + stats.decoded += 1; + (stats.width, stats.height) = (picture.width, picture.height); + } + on_frame(picture); + } + Ok(None) => {} + Err(e) => { + debug!("decoding failed: {e}"); + set_error(e.to_string()); + waiting = true; + request(&queue.stats); + } + } + } +} + +/// Decodes a stream watched through the engine: a [`VideoPipeline`] fed from +/// [`Engine::subscribe_frames`], asking the streamer for keyframes through +/// the engine. Stops when dropped. +pub struct Viewer { + pipeline: VideoPipeline, + forward: tokio::task::JoinHandle<()>, +} + +impl Viewer { + pub fn start( + engine: &Engine, + session: SessionId, + stream_id: &str, + codecs: Arc, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + ) -> Self { + let request = { + let engine = engine.clone(); + let stream_id = stream_id.to_owned(); + move || { + let stream_id = stream_id.clone(); + engine.send(Command::RequestStreamKeyframe { session, stream_id }); + } + }; + let pipeline = VideoPipeline::new(codecs, on_frame, request); + let input = pipeline.input(); + let mut frames = engine.subscribe_frames(); + let stream_id = stream_id.to_owned(); + let forward = engine.runtime().spawn(async move { + use tokio::sync::broadcast::error::RecvError; + loop { + match frames.recv().await { + Ok(f) if f.session == session && f.stream_id == stream_id => { + input.push(f.frame) + } + Ok(_) => {} + Err(RecvError::Lagged(_)) => input.lost(), + Err(RecvError::Closed) => break, + } + } + }); + Self { pipeline, forward } + } + + pub fn stats(&self) -> DecodeStats { + self.pipeline.stats() + } +} + +impl Drop for Viewer { + fn drop(&mut self) { + self.forward.abort(); + } +} + +/// Hands the newest item from a producer thread to a consumer that may be +/// slower (e.g. a UI): an item that was not taken yet is replaced. +pub struct Latest { + slot: Mutex>, +} + +impl Default for Latest { + fn default() -> Self { + Self { slot: Mutex::new(None) } + } +} + +impl Latest { + pub fn new() -> Self { + Self::default() + } + + /// Store `item`. Returns `true` if the slot was empty, i.e. the consumer + /// needs a wake-up; otherwise a wake-up is already pending. + pub fn put(&self, item: T) -> bool { + lock(&self.slot).replace(item).is_none() + } + + pub fn take(&self) -> Option { + lock(&self.slot).take() + } +} + +/// Feeds a [`Streamer`]'s video straight into a [`VideoPipeline`]. +struct PipelineSink { + input: FrameInput, + codec: tsc_stream::Codec, + keyframe: Arc, +} + +impl MediaSink for PipelineSink { + fn send(&self, frame: EncodedFrame) -> bool { + self.input.push(MediaFrame { + kind: frame.kind, + codec: self.codec, + time: frame.time, + network_time: Instant::now(), + contiguous: true, + data: frame.data, + }); + true + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } +} + +/// Capture → encoder → decoder without a server, e.g. to preview a share or +/// to develop the viewer (`TSC_DEMO_STREAM` in the desktop app). +pub struct LocalPreview { + // Dropped first: no more frames into the pipeline. + streamer: Streamer, + pipeline: VideoPipeline, +} + +impl LocalPreview { + pub async fn start( + codecs: Arc, + mut config: StreamerConfig, + on_frame: impl FnMut(VideoFrame) + Send + 'static, + ) -> Result { + // The audio would go nowhere. + config.audio = false; + let codec = config.codec; + let streamer = Streamer::start(&codecs, config).await?; + let keyframe = Arc::new(AtomicBool::new(true)); + let pipeline = VideoPipeline::new(codecs, on_frame, { + let keyframe = keyframe.clone(); + move || keyframe.store(true, Ordering::Relaxed) + }); + let input = pipeline.input(); + streamer.attach(Arc::new(PipelineSink { input, codec: codec.into(), keyframe })); + Ok(Self { streamer, pipeline }) + } + + pub fn streamer(&self) -> &Streamer { + &self.streamer + } + + pub fn stats(&self) -> DecodeStats { + self.pipeline.stats() + } +} + +/// The first and last column of the rectangle in the middle row of a +/// decoded test pattern. Checks that pixels further than two columns from +/// its edges (which the codec blurs) have the colour of the rectangle or +/// the background. +#[cfg(all(test, feature = "media-desktop"))] +pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) { + use tsc_media::capture::synthetic::{BACKGROUND, RECT_COLOR}; + + let rgba = tsc_media::convert::to_rgba_vec(picture).unwrap(); + let y = picture.height / 2; + let pixel = |x: u32| { + let i = ((y * picture.width + x) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] + }; + let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24); + let inside: Vec = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect(); + let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row"); + for x in 0..picture.width { + if x + 2 < a || x > b + 2 { + assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x)); + } else if (a + 2..=b.saturating_sub(2)).contains(&x) { + assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x)); + } + } + (a, b) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyframe_detection() { + // VP8: the 1x1 keyframe of tsc-stream's synthetic source. + assert!(is_keyframe(Codec::Vp8, &tsc_stream::source::VP8_KEYFRAME_1X1)); + assert!(!is_keyframe(Codec::Vp8, &[0x31, 0x00])); + // VP9 profile 0: marker 10, profile 00, show_existing 0, frame_type 0/1. + assert!(is_keyframe(Codec::Vp9, &[0b1000_0000])); + assert!(!is_keyframe(Codec::Vp9, &[0b1000_0100])); + assert!(!is_keyframe(Codec::Vp9, &[0b1000_1000]), "show existing frame"); + // H.264: SPS + IDR vs. a non-IDR slice. + assert!(is_keyframe(Codec::H264, &[0, 0, 0, 1, 0x67, 1, 0, 0, 1, 0x65, 2])); + assert!(!is_keyframe(Codec::H264, &[0, 0, 0, 1, 0x41, 1, 2])); + // AV1: temporal delimiter (type 2, size 0) then a sequence header. + assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x0a, 0x01, 0xff])); + assert!(!is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0xff])); + assert!(is_keyframe(Codec::Av1, &[0x12, 0x05]), "truncated: let the decoder try"); + } + + #[test] + fn latest_keeps_the_newest() { + let latest = Latest::new(); + assert!(latest.put(1)); + assert!(!latest.put(2), "a wake-up is pending"); + assert_eq!(latest.take(), Some(2)); + assert_eq!(latest.take(), None); + assert!(latest.put(3)); + } + + #[cfg(feature = "media-desktop")] + #[test] + fn peer_config_follows_codecs() { + let codecs = Codecs::new(); + let config = peer_config(&codecs, PeerConfig::default()); + assert_eq!(config.video_codecs, [VideoCodec::Vp8]); + assert!(config.accept_video_codecs.contains(&VideoCodec::Vp8)); + assert!(!config.accept_video_codecs.contains(&VideoCodec::H264), "no OpenH264 loaded"); + assert_eq!(stream_codec(&codecs, &config), Some(Codec::Vp8)); + let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config }; + assert_eq!(stream_codec(&codecs, &h264_only), None); + } + + /// The test pattern through VP8 and back, without a network: pictures + /// show the moving rectangle. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn local_preview_decodes_the_pattern() { + let codecs = Arc::new(Codecs::new()); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 240), + bitrate_kbps: 1500, + ..StreamerConfig::default() + }; + let (tx, rx) = std_mpsc::channel(); + let preview = LocalPreview::start(codecs, config, move |picture| { + let _ = tx.send(picture); + }) + .await + .unwrap(); + let mut spans = Vec::new(); + while spans.len() < 10 { + let picture = rx.recv_timeout(Duration::from_secs(5)).expect("no picture"); + assert_eq!((picture.width, picture.height), (320, 240)); + spans.push(rectangle_span(&picture)); + } + // 320 / 5 = 64 pixels wide, give or take the codec's blur. + for (a, b) in &spans { + assert!((60..=68).contains(&(b - a + 1)), "{spans:?}"); + } + assert_ne!(spans.first(), spans.last(), "the rectangle moves"); + let stats = preview.stats(); + assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}"); + assert_eq!(stats.codec, Some(Codec::Vp8)); + assert_eq!(preview.streamer().backend(), "synthetic"); + } + + /// Audio of the test pattern: 20 ms Opus frames on a 48 kHz clock. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn streamer_sends_opus() { + let codecs = Codecs::new(); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (64, 48), + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + assert!(streamer.has_audio(), "{:?}", streamer.audio_error()); + let mut source = EncodedSource::new(streamer); + let mut frames = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 { + assert!(Instant::now() < deadline, "no audio"); + tokio::time::sleep(Duration::from_millis(20)).await; + source.poll_frames(Instant::now(), &mut frames); + } + let times: Vec = frames + .iter() + .filter(|f| f.kind == MediaKind::Audio) + .map(|f| f.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer()) + .collect(); + assert!(times.windows(2).all(|w| w[1] - w[0] == OPUS_FRAME as u64), "{times:?}"); + let video = frames.iter().find(|f| f.kind == MediaKind::Video).expect("video too"); + assert!(is_keyframe(Codec::Vp8, &video.data), "the first frame is a keyframe"); + assert!(source.streamer().stats().video_frames > 0); + } +} diff --git a/crates/tsc-core/src/session.rs b/crates/tsc-core/src/session.rs index 93b748a..0702bb9 100644 --- a/crates/tsc-core/src/session.rs +++ b/crates/tsc-core/src/session.rs @@ -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, frames: broadcast::Sender, + 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)>, query_presence: Option, audio: Option, + audio_settings: AudioSettings, /// Streams of the voice connection (TeamSpeak 6 only). streams: Option, stream_peer: PeerConfig, @@ -75,6 +79,7 @@ impl Session { id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, + 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}")); diff --git a/crates/tsc-core/src/stream.rs b/crates/tsc-core/src/stream.rs index 80ed3a2..b820d9e 100644 --- a/crates/tsc-core/src/stream.rs +++ b/crates/tsc-core/src/stream.rs @@ -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, events: broadcast::Sender, frames: broadcast::Sender, + audio: Option, ) -> 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, events: broadcast::Sender, frames: broadcast::Sender, + /// Where the audio of watched streams plays, if the session has audio. + audio: Option, /// For the sinks handed out. tx: mpsc::UnboundedSender, /// 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>; + + /// 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, + ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { + 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, + ) -> 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 = audio_rx.try_iter().collect(); + let times: Vec = 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); + } } diff --git a/crates/tsc-core/tests/media_live.rs b/crates/tsc-core/tests/media_live.rs new file mode 100644 index 0000000..585fd13 --- /dev/null +++ b/crates/tsc-core/tests/media_live.rs @@ -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( + rx: &mut Receiver, + what: &str, + mut f: impl FnMut(&Event) -> Option, +) -> 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, + 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; +} diff --git a/crates/tsc-ui/Cargo.toml b/crates/tsc-ui/Cargo.toml index bbfd97f..1932522 100644 --- a/crates/tsc-ui/Cargo.toml +++ b/crates/tsc-ui/Cargo.toml @@ -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" diff --git a/crates/tsc-ui/src/app.rs b/crates/tsc-ui/src/app.rs index 95033df..fc460e4 100644 --- a/crates/tsc-ui/src/app.rs +++ b/crates/tsc-ui/src/app.rs @@ -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, +pub(crate) struct SessionView { + pub state: SessionState, + pub capabilities: Capabilities, + pub presence: Arc, collapsed: HashSet, talking: HashSet, tabs: Vec, 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, + /// Clients whose stored volume was sent for this voice connection. + applied_playback: HashSet, } 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, +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, store: Store, secrets: Box, - engine: Engine, + pub engine: Engine, identity: tsclientlib::Identity, bookmarks: Vec, - current: Option, - sessions: HashMap, + pub current: Option, + pub sessions: HashMap, 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)>, + mic_test: bool, + ptt: GlobalPtt, + pub video: Video, + /// Our stream. + pub share: Option, + /// The capture for a share is being started. + pub share_busy: bool, + pub share_error: String, + /// The stream in the viewer. + pub watch: Option, + /// 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> = const { RefCell::new(None) }; } -fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { +pub(crate) fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { 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= 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= 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[:]|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::().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(items: Vec) -> ModelRc { +pub(crate) fn model(items: Vec) -> ModelRc { 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) { + pub fn set_status(&mut self, text: impl Into) { self.status = text.into(); if let Some(ui) = self.ui.upgrade() { ui.global::().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.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::(); 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::().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::().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::(); - 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>, 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::>() + }; + 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::(); + 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.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::().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::(); + 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.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::().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 = notices::text().lines().map(SharedString::from).collect(); + ui.global::().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::().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 }); + } + } + } } diff --git a/crates/tsc-ui/src/hotkey.rs b/crates/tsc-ui/src/hotkey.rs new file mode 100644 index 0000000..c888cb1 --- /dev/null +++ b/crates/tsc-ui/src/hotkey.rs @@ -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>, +} + +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) { + let _ = self.tx.send(key); + } +} + +#[cfg(target_os = "android")] +async fn run( + mut rx: mpsc::UnboundedReceiver>, + 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>, + status: impl Fn(String), + transmit: impl Fn(bool), +) { + use tsc_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager}; + + async fn next(events: &mut Option) -> Option { + match events { + Some(events) => events.recv().await, + None => std::future::pending().await, + } + } + + let mut manager: Option = None; + let mut events: Option = 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()); + } + }, + } + } +} diff --git a/crates/tsc-ui/src/lib.rs b/crates/tsc-ui/src/lib.rs index 30d05ec..b9ad8f5 100644 --- a/crates/tsc-ui/src/lib.rs +++ b/crates/tsc-ui/src/lib.rs @@ -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}; diff --git a/crates/tsc-ui/src/main.rs b/crates/tsc-ui/src/main.rs index ededc93..19a9ac3 100644 --- a/crates/tsc-ui/src/main.rs +++ b/crates/tsc-ui/src/main.rs @@ -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; diff --git a/crates/tsc-ui/src/settings.rs b/crates/tsc-ui/src/settings.rs new file mode 100644 index 0000000..d2b3473 --- /dev/null +++ b/crates/tsc-ui/src/settings.rs @@ -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, + 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; + +/// Audio devices as listed in the settings: the system default first. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DeviceChoices { + pub names: Vec, + /// Device ids by index; `None` for the system default. + pub ids: Vec>, +} + +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 { + 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); + } +} diff --git a/crates/tsc-ui/src/streams.rs b/crates/tsc-ui/src/streams.rs new file mode 100644 index 0000000..7ab31e1 --- /dev/null +++ b/crates/tsc-ui/src/streams.rs @@ -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, + /// 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, + 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, +} + +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::(); + let view = self.view(); + let current = self.current; + let mut items: Vec = 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 = 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::(); + 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::>() + .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 = sources + .into_iter() + .map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() }) + .collect(); + ui.global::().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::().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, + ) { + 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.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::().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::(); + if bridge.get_viewer_fullscreen() == full { + return; + } + bridge.set_viewer_fullscreen(full); + ui.window().set_fullscreen(full); + } +} diff --git a/crates/tsc-ui/src/video.rs b/crates/tsc-ui/src/video.rs new file mode 100644 index 0000000..021d7c5 --- /dev/null +++ b/crates/tsc-ui/src/video.rs @@ -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; + +/// 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); +#[cfg(target_os = "android")] +pub(crate) struct H264Download; + +pub(crate) struct Video { + codecs: Arc, + #[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, 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) + 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) + 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>, + 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, +} + +/// 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 { + self.streamer.audio_error().map(str::to_owned) + } + + /// The portal's token for this choice, to keep. + pub fn restore_token(&self) -> Option { + 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>, +} + +impl Decoder { + /// The newest picture since the last call. + pub fn take_picture(&self) -> Option { + 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 { + let stats = self.stats(); + stats.error.filter(|_| stats.decoded == 0) + } +} diff --git a/crates/tsc-ui/ui/app.slint b/crates/tsc-ui/ui/app.slint index 6069f1d..2c958e8 100644 --- a/crates/tsc-ui/ui/app.slint +++ b/crates/tsc-ui/ui/app.slint @@ -1,4 +1,4 @@ -import { Button, LineEdit, ListView, ComboBox, AboutSlint, VerticalBox, HorizontalBox, ScrollView } from "std-widgets.slint"; +import { Button, LineEdit, ListView, ComboBox, CheckBox, Slider, AboutSlint, VerticalBox, HorizontalBox, ScrollView, TabWidget } from "std-widgets.slint"; export struct ServerItem { id: int, @@ -21,6 +21,12 @@ export struct TreeItem { streaming: bool, locked: bool, collapsed: bool, + // Local playback of this client: muted, or its volume in percent + // (100 = unchanged). + local-muted: bool, + local-volume: int, + // Our own client. + myself: bool, } export struct ChatTab { @@ -51,6 +57,73 @@ export struct BookmarkForm { query-password: string, } +// A stream in our channel. An empty id: a client that streams, but the +// server did not announce the stream to us (it started before we joined). +export struct StreamItem { + id: string, + name: string, + streamer: string, + audio: bool, + // Shown in the viewer. + watching: bool, + // Our own stream. + own: bool, +} + +// A viewer of our stream. state: "requested", "connecting" or "connected". +export struct ViewerItem { + client: int, + name: string, + state: string, + message: string, +} + +// A capture source for the share dialog. +export struct SourceItem { + name: string, + detail: string, +} + +export struct ShareForm { + source: int, + name: string, + // Index into the frame rate choices (15, 30, 60). + fps-index: int, + // Index into the bitrate choices (2.5, 4.6, 8, 10 Mbit/s). + bitrate-index: int, + audio: bool, + auto-accept: bool, +} + +export struct AudioForm { + // 0 = system default, then the devices. + input-index: int, + output-index: int, + // 0 = push-to-talk, 1 = voice activation, 2 = continuous. + transmit: int, + // dBFS. + vad-threshold: float, + echo-cancellation: bool, + noise-suppression: bool, + // 0 = low ... 3 = very high. + noise-level: int, + auto-gain: bool, + // dB. + input-gain: float, + // Percent. + output-volume: float, + // Milliseconds. + playback-buffer: float, +} + +// Local playback settings of one client. volume in percent. +export struct ClientAudio { + id: int, + name: string, + volume: float, + muted: bool, +} + export global Bridge { in property <[ServerItem]> servers; in-out property current-server: -1; @@ -59,7 +132,7 @@ export global Bridge { in-out property current-tab: 0; in property <[ChatLine]> messages; in property status-text; - in property server-title: "No server selected"; + in property server-title: @tr("No server selected"); in property voice-connected; in property voice-connecting; in property observing; @@ -69,6 +142,55 @@ export global Bridge { in property transmitting; in property presence-source; + // Streams (TeamSpeak 6 while connected with voice). + in property streams-available; + in property <[StreamItem]> streams; + // Our stream: "", "starting", "live" or "ended". + in property share-state; + in property share-status; + in property <[ViewerItem]> share-viewers; + in property share-requests; + in property <[SourceItem]> share-sources; + in property share-error; + in property share-busy; + // Whether capture and encoding are built in. + in property can-share: true; + + // The stream shown in the viewer. + in property viewer-open; + in property viewer-frame; + in property viewer-has-frame; + in property viewer-title; + // Shown instead of (or over) the picture: waiting, ended, errors. + in property viewer-status; + in property viewer-info; + in property viewer-ended; + in-out property viewer-volume: 100; + in property viewer-fullscreen; + + // Settings. + in property <[string]> input-devices; + in property <[string]> output-devices; + in-out property audio; + // Microphone level in dBFS and whether voice is sent. + in property input-level: -100; + in property input-sending; + in property mic-test; + in-out property global-ptt; + in-out property ptt-key; + in property ptt-status; + in-out property h264-enabled; + in property h264-loaded; + in property h264-busy; + in property h264-status; + in property h264-attribution; + in-out property client-audio; + // Opt-in local crash reports, and a notice about reports on disk. + in-out property crash-reports; + in property crash-notice; + // Third-party notices, one entry per line, for the About page. + in property <[string]> notices; + callback select-server(int); callback connect-voice(); callback disconnect-voice(); @@ -85,6 +207,33 @@ export global Bridge { callback edit-bookmark(int) -> BookmarkForm; callback save-bookmark(BookmarkForm); callback delete-bookmark(int); + + callback open-share() -> ShareForm; + callback start-share(ShareForm); + callback stop-share(); + callback respond-viewer(int, bool); + callback kick-viewer(int); + callback watch-stream(string); + callback show-viewer(); + callback hide-viewer(); + callback leave-stream(); + callback set-stream-volume(float); + callback toggle-fullscreen(); + + callback open-settings(); + callback close-settings(); + callback audio-changed(AudioForm); + callback toggle-mic-test(); + callback apply-ptt(bool, string); + callback set-h264(bool); + callback download-h264(); + callback open-client(int) -> bool; + callback client-audio-changed(ClientAudio); + callback set-crash-reports(bool); + callback open-crash-folder(); + callback delete-crash-reports(); + callback dismiss-crash-notice(); + callback open-about(); } component StatusDot inherits Rectangle { @@ -110,76 +259,112 @@ component Field inherits HorizontalLayout { text <=> value; placeholder-text: placeholder; input-type: input-type; + accessible-label: label; } } -component BookmarkEditor inherits Rectangle { - in-out property form; - callback done(); +// A label beside a control, for settings rows. +component Row inherits HorizontalLayout { + in property label; + spacing: 8px; + Text { + text: label; + width: 170px; + vertical-alignment: center; + wrap: word-wrap; + } + @children +} + +// Small text tag in a list row. +component Tag inherits Text { + font-size: 10px; + vertical-alignment: center; +} + +// A dimmed full-window backdrop with a centered card. +component Dialog inherits Rectangle { + in property card-width: 520px; + in property card-height: 520px; + callback dismissed(); background: #000000a0; - TouchArea { } + TouchArea { + clicked => { dismissed(); } + } Rectangle { - width: min(parent.width - 32px, 520px); - height: min(parent.height - 32px, 520px); + width: min(parent.width - 32px, card-width); + height: min(parent.height - 32px, card-height); background: #1f2328; border-radius: 8px; - VerticalBox { - Text { - text: form.id < 0 ? "Add server" : "Edit server"; - font-size: 18px; - font-weight: 700; - } - ScrollView { - VerticalLayout { - spacing: 6px; - Field { label: "Name"; value <=> form.name; placeholder: "My server"; } - Field { label: "Address"; value <=> form.address; placeholder: "ts.example.org:9987"; } - Field { label: "Nickname"; value <=> form.nickname; } - Field { label: "Server password"; value <=> form.server-password; input-type: InputType.password; } + border-width: 1px; + border-color: #30363d; + // Clicks inside the card do not dismiss it. + TouchArea { } + @children + } +} + +component BookmarkEditor inherits Dialog { + in-out property form; + callback done(); + dismissed => { done(); } + VerticalBox { + Text { + text: form.id < 0 ? @tr("Add server") : @tr("Edit server"); + font-size: 18px; + font-weight: 700; + } + ScrollView { + VerticalLayout { + spacing: 6px; + Field { label: @tr("Name"); value <=> form.name; placeholder: @tr("My server"); } + Field { label: @tr("Address"); value <=> form.address; placeholder: "ts.example.org:9987"; } + Field { label: @tr("Nickname"); value <=> form.nickname; } + Field { label: @tr("Server password"); value <=> form.server-password; input-type: InputType.password; } + Text { + text: @tr("Invisible presence and chat without joining (optional)"); + font-weight: 600; + } + Field { label: @tr("Gateway URL"); value <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; } + HorizontalLayout { + spacing: 8px; Text { - text: "Invisible presence and chat without joining (optional)"; - font-weight: 600; + text: @tr("Query transport"); + width: 130px; + vertical-alignment: center; } - Field { label: "Gateway URL"; value <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; } - HorizontalLayout { - spacing: 8px; - Text { - text: "Query transport"; - width: 130px; - vertical-alignment: center; - } - ComboBox { - model: ["none", "ssh", "raw", "http"]; - current-value <=> form.query-transport; - } + ComboBox { + model: ["none", "ssh", "raw", "http"]; + current-value <=> form.query-transport; + accessible-label: @tr("Query transport"); } - Field { label: "Query address"; value <=> form.query-addr; placeholder: "ts.example.org:10022"; } - Field { label: "Query login"; value <=> form.query-user; } - Field { label: "Query password"; value <=> form.query-password; input-type: InputType.password; } + } + Field { label: @tr("Query address"); value <=> form.query-addr; placeholder: "ts.example.org:10022"; } + Field { label: @tr("Query login"); value <=> form.query-user; } + Field { label: @tr("Query password"); value <=> form.query-password; input-type: InputType.password; } + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + if form.id >= 0: Button { + text: @tr("Delete"); + clicked => { + Bridge.delete-bookmark(form.id); + done(); } } - HorizontalLayout { - alignment: end; - spacing: 8px; - if form.id >= 0: Button { - text: "Delete"; - clicked => { - Bridge.delete-bookmark(form.id); - done(); - } - } - Button { - text: "Cancel"; - clicked => { done(); } - } - Button { - text: "Save"; - primary: true; - enabled: form.address != "" && form.nickname != ""; - clicked => { - Bridge.save-bookmark(form); - done(); - } + Button { + text: @tr("Cancel"); + clicked => { done(); } + } + Button { + text: @tr("Save"); + primary: true; + enabled: form.address != "" && form.nickname != ""; + clicked => { + Bridge.save-bookmark(form); + done(); } } } @@ -190,16 +375,19 @@ component ServerList inherits Rectangle { callback add(); callback edit(int); background: #161b22; + accessible-role: list; + accessible-label: @tr("Servers"); VerticalBox { HorizontalLayout { Text { - text: "Servers"; + text: @tr("Servers"); font-weight: 700; vertical-alignment: center; } Button { text: "+"; width: 32px; + accessible-label: @tr("Add server"); clicked => { add(); } } } @@ -208,6 +396,12 @@ component ServerList inherits Rectangle { height: 48px; border-radius: 6px; background: Bridge.current-server == server.id ? #30363d : area.has-hover ? #21262d : transparent; + accessible-role: list-item; + accessible-label: server.name; + accessible-description: server.address; + accessible-item-selectable: true; + accessible-item-selected: Bridge.current-server == server.id; + accessible-action-default => { Bridge.select-server(server.id); } area := TouchArea { clicked => { Bridge.select-server(server.id); } double-clicked => { edit(server.id); } @@ -239,11 +433,25 @@ component ServerList inherits Rectangle { } component ChannelTree inherits Rectangle { + // A client row was clicked: its local volume and mute. + callback client-clicked(int); background: #0d1117; + accessible-role: list; + accessible-label: @tr("Channels and clients"); ListView { for row in Bridge.tree: Rectangle { height: 26px; background: row-area.has-hover ? #161b22 : transparent; + accessible-role: list-item; + accessible-label: row.is-channel ? @tr("Channel {}", row.name) : row.name; + accessible-description: (row.talking ? @tr("talking") + " " : "") + (row.streaming ? @tr("streaming") + " " : "") + (row.muted ? @tr("microphone off") + " " : "") + (row.local-muted ? @tr("muted for you") : ""); + accessible-action-default => { + if (row.is-channel) { + Bridge.open-channel-chat(row.id); + } else { + client-clicked(row.id); + } + } row-area := TouchArea { double-clicked => { if (row.is-channel) { @@ -253,6 +461,8 @@ component ChannelTree inherits Rectangle { clicked => { if (row.is-channel) { Bridge.open-channel-chat(row.id); + } else if (!row.myself) { + client-clicked(row.id); } } } @@ -263,6 +473,9 @@ component ChannelTree inherits Rectangle { if row.is-channel: Text { text: row.collapsed ? "▸" : "▾"; vertical-alignment: center; + accessible-role: button; + accessible-label: row.collapsed ? @tr("Expand") : @tr("Collapse"); + accessible-action-default => { Bridge.toggle-collapse(row.id); } TouchArea { clicked => { Bridge.toggle-collapse(row.id); } } @@ -283,11 +496,110 @@ component ChannelTree inherits Rectangle { color: row.away ? #8b949e : row.own ? #58a6ff : #e6edf3; overflow: elide; } - if row.locked: Text { text: "password"; font-size: 10px; color: #d29922; vertical-alignment: center; } - if row.muted: Text { text: "mic off"; font-size: 10px; color: #f85149; vertical-alignment: center; } - if row.sound-off: Text { text: "sound off"; font-size: 10px; color: #f85149; vertical-alignment: center; } - if row.streaming: Text { text: "LIVE"; font-size: 10px; color: #a371f7; vertical-alignment: center; } - if row.away: Text { text: "away"; font-size: 10px; color: #8b949e; vertical-alignment: center; } + if row.locked: Tag { text: @tr("password"); color: #d29922; } + if row.muted: Tag { text: @tr("mic off"); color: #f85149; } + if row.sound-off: Tag { text: @tr("sound off"); color: #f85149; } + if row.local-muted: Tag { text: @tr("muted for you"); color: #f0883e; } + if !row.local-muted && row.local-volume != 100 && !row.is-channel: Tag { + text: @tr("{}%", row.local-volume); + color: #8b949e; + } + if row.streaming: Tag { text: @tr("LIVE"); color: #a371f7; font-weight: 700; } + if row.away: Tag { text: @tr("away"); color: #8b949e; } + } + } + } +} + +// Streams in our channel, requests to watch ours. +component StreamsPanel inherits Rectangle { + callback manage-share(); + background: #0d1117; + border-width: 1px; + border-color: #21262d; + accessible-role: groupbox; + accessible-label: @tr("Streams"); + VerticalLayout { + padding: 8px; + spacing: 6px; + HorizontalLayout { + spacing: 6px; + Text { + text: @tr("Streams"); + font-weight: 700; + vertical-alignment: center; + } + if Bridge.share-state == "live": Text { + text: @tr("● You are live"); + color: #f85149; + font-size: 11px; + vertical-alignment: center; + } + Rectangle { } + if Bridge.share-state == "live" || Bridge.share-state == "starting": Button { + text: Bridge.share-requests > 0 ? @tr("Viewers ({})", Bridge.share-requests) : @tr("Manage"); + clicked => { manage-share(); } + } + } + if Bridge.streams.length == 0: Text { + text: @tr("No streams in your channel."); + color: #8b949e; + font-size: 12px; + } + for stream in Bridge.streams: HorizontalLayout { + spacing: 6px; + Rectangle { + width: 6px; + height: 6px; + y: (parent.height - self.height) / 2; + border-radius: 3px; + background: #a371f7; + } + VerticalLayout { + horizontal-stretch: 1; + Text { + text: stream.id == "" ? @tr("{} is streaming", stream.streamer) : stream.name == "" ? @tr("Untitled stream") : stream.name; + font-weight: 600; + overflow: elide; + } + Text { + text: stream.id == "" ? @tr("Started before you joined; the server did not announce it.") : stream.own ? @tr("your stream") : stream.audio ? @tr("by {} · with sound", stream.streamer) : @tr("by {}", stream.streamer); + font-size: 11px; + color: #8b949e; + overflow: elide; + } + } + if stream.id != "" && !stream.own && !stream.watching: Button { + text: @tr("Watch"); + accessible-label: @tr("Watch {}", stream.name); + clicked => { Bridge.watch-stream(stream.id); } + } + if stream.watching && !Bridge.viewer-open: Button { + text: @tr("Show"); + clicked => { Bridge.show-viewer(); } + } + if stream.watching: Button { + text: @tr("Leave"); + clicked => { Bridge.leave-stream(); } + } + } + for viewer in Bridge.share-viewers: HorizontalLayout { + spacing: 6px; + if viewer.state == "requested": Text { + text: @tr("{} wants to watch", viewer.name); + horizontal-stretch: 1; + vertical-alignment: center; + overflow: elide; + color: #d29922; + } + if viewer.state == "requested": Button { + text: @tr("Accept"); + primary: true; + clicked => { Bridge.respond-viewer(viewer.client, true); } + } + if viewer.state == "requested": Button { + text: @tr("Deny"); + clicked => { Bridge.respond-viewer(viewer.client, false); } } } } @@ -299,9 +611,17 @@ component ChatPanel inherits Rectangle { HorizontalLayout { height: 34px; spacing: 2px; + accessible-role: tab-list; + accessible-label: @tr("Chats"); for tab[i] in Bridge.tabs: Rectangle { width: tab-text.preferred-width + 28px; background: Bridge.current-tab == i ? #30363d : tab-area.has-hover ? #21262d : #161b22; + accessible-role: AccessibleRole.tab; + accessible-label: tab.title; + accessible-description: tab.unread > 0 ? @tr("{} unread", tab.unread) : ""; + accessible-item-selectable: true; + accessible-item-selected: Bridge.current-tab == i; + accessible-action-default => { Bridge.select-tab(i); } tab-area := TouchArea { clicked => { Bridge.select-tab(i); } } @@ -317,6 +637,9 @@ component ChatPanel inherits Rectangle { if tab.kind == 1: Text { text: "×"; vertical-alignment: center; + accessible-role: button; + accessible-label: @tr("Close {}", tab.title); + accessible-action-default => { Bridge.close-tab(i); } TouchArea { clicked => { Bridge.close-tab(i); } } @@ -326,6 +649,7 @@ component ChatPanel inherits Rectangle { Rectangle { } } ListView { + accessible-label: @tr("Messages"); for line in Bridge.messages: VerticalLayout { padding: 6px; HorizontalLayout { @@ -336,7 +660,7 @@ component ChatPanel inherits Rectangle { color: line.relayed ? #58a6ff : #e6edf3; } Text { - text: line.time + (line.relayed ? " via relay" : ""); + text: line.time + (line.relayed ? " " + @tr("via relay") : ""); font-size: 11px; color: #8b949e; vertical-alignment: center; @@ -352,7 +676,8 @@ component ChatPanel inherits Rectangle { padding: 6px; spacing: 6px; input := LineEdit { - placeholder-text: "Message"; + placeholder-text: @tr("Message"); + accessible-label: @tr("Message"); accepted(text) => { if (text != "") { Bridge.send-message(text); @@ -361,7 +686,7 @@ component ChatPanel inherits Rectangle { } } Button { - text: "Send"; + text: @tr("Send"); clicked => { if (input.text != "") { Bridge.send-message(input.text); @@ -373,8 +698,757 @@ component ChatPanel inherits Rectangle { } } +// The stream we watch: title, picture, and player controls below it. +component StreamViewer inherits Rectangle { + background: #010409; + accessible-role: groupbox; + accessible-label: @tr("Stream viewer"); + VerticalLayout { + Rectangle { + height: 42px; + background: #161b22; + VerticalLayout { + padding-left: 10px; + padding-right: 10px; + alignment: center; + Text { + text: Bridge.viewer-title; + font-weight: 700; + overflow: elide; + } + Text { + text: Bridge.viewer-info; + font-size: 11px; + color: #8b949e; + overflow: elide; + } + } + } + Rectangle { + vertical-stretch: 1; + Image { + width: parent.width; + height: parent.height; + source: Bridge.viewer-frame; + image-fit: contain; + visible: Bridge.viewer-has-frame; + accessible-role: image; + accessible-label: @tr("Stream picture"); + } + if Bridge.viewer-status != "": Rectangle { + width: min(parent.width - 32px, status-text.preferred-width + 32px); + height: status-text.preferred-height + 20px; + border-radius: 6px; + background: #161b22e0; + status-text := Text { + width: min(root.width - 64px, self.preferred-width); + text: Bridge.viewer-status; + horizontal-alignment: center; + wrap: word-wrap; + accessible-live-region: polite; + } + } + } + Rectangle { + height: 44px; + background: #161b22; + HorizontalLayout { + padding: 6px; + padding-left: 10px; + spacing: 8px; + Text { + text: @tr("Volume"); + vertical-alignment: center; + color: #8b949e; + } + Slider { + width: 140px; + minimum: 0; + maximum: 200; + value <=> Bridge.viewer-volume; + enabled: !Bridge.viewer-ended; + accessible-label: @tr("Stream volume"); + changed(v) => { Bridge.set-stream-volume(v); } + } + Text { + text: @tr("{}%", round(Bridge.viewer-volume)); + width: 40px; + vertical-alignment: center; + color: #8b949e; + } + Rectangle { } + Button { + text: Bridge.viewer-fullscreen ? @tr("Exit full screen") : @tr("Full screen"); + clicked => { Bridge.toggle-fullscreen(); } + } + if !Bridge.viewer-fullscreen: Button { + text: @tr("Chat"); + accessible-label: @tr("Back to the chat"); + clicked => { Bridge.hide-viewer(); } + } + Button { + text: Bridge.viewer-ended ? @tr("Close") : @tr("Leave"); + clicked => { Bridge.leave-stream(); } + } + } + } + } +} + +component ShareDialog inherits Dialog { + in-out property form; + callback done(); + card-width: 560px; + card-height: 560px; + dismissed => { done(); } + VerticalBox { + Text { + text: Bridge.share-state == "live" ? @tr("You are sharing your screen") : Bridge.share-state == "starting" ? @tr("Starting…") : @tr("Share screen"); + font-size: 18px; + font-weight: 700; + } + if Bridge.share-state == "live" || Bridge.share-state == "starting": VerticalLayout { + spacing: 8px; + vertical-stretch: 1; + Text { + text: Bridge.share-status; + color: #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Viewers"); + font-weight: 600; + } + if Bridge.share-viewers.length == 0: Text { + text: @tr("Nobody is watching yet. Viewers in your channel can join from their streams list."); + color: #8b949e; + wrap: word-wrap; + } + ListView { + vertical-stretch: 1; + accessible-label: @tr("Viewers"); + for viewer in Bridge.share-viewers: HorizontalLayout { + padding-top: 4px; + padding-bottom: 4px; + spacing: 8px; + VerticalLayout { + horizontal-stretch: 1; + alignment: center; + Text { + text: viewer.name; + font-weight: 600; + overflow: elide; + } + Text { + text: viewer.state == "requested" ? (viewer.message == "" ? @tr("asks to watch") : @tr("asks to watch: {}", viewer.message)) : viewer.state == "connecting" ? @tr("connecting") : @tr("watching"); + font-size: 11px; + color: viewer.state == "requested" ? #d29922 : viewer.state == "connected" ? #3fb950 : #8b949e; + overflow: elide; + } + } + if viewer.state == "requested": Button { + text: @tr("Accept"); + primary: true; + clicked => { Bridge.respond-viewer(viewer.client, true); } + } + if viewer.state == "requested": Button { + text: @tr("Deny"); + clicked => { Bridge.respond-viewer(viewer.client, false); } + } + if viewer.state != "requested": Button { + text: @tr("Remove"); + accessible-label: @tr("Remove {}", viewer.name); + clicked => { Bridge.kick-viewer(viewer.client); } + } + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Close"); + clicked => { done(); } + } + Button { + text: @tr("Stop sharing"); + primary: true; + clicked => { Bridge.stop-share(); } + } + } + } + if Bridge.share-state != "live" && Bridge.share-state != "starting": VerticalLayout { + spacing: 8px; + vertical-stretch: 1; + Text { + text: @tr("What to share"); + font-weight: 600; + } + ListView { + vertical-stretch: 1; + min-height: 120px; + accessible-label: @tr("What to share"); + for source[i] in Bridge.share-sources: Rectangle { + height: 40px; + border-radius: 6px; + background: form.source == i ? #1f6feb40 : source-area.has-hover ? #21262d : transparent; + border-width: form.source == i ? 1px : 0px; + border-color: #1f6feb; + accessible-role: list-item; + accessible-label: source.name; + accessible-description: source.detail; + accessible-item-selectable: true; + accessible-item-selected: form.source == i; + accessible-action-default => { form.source = i; } + source-area := TouchArea { + clicked => { form.source = i; } + } + HorizontalLayout { + padding-left: 10px; + padding-right: 10px; + spacing: 8px; + Text { + text: source.name; + vertical-alignment: center; + horizontal-stretch: 1; + overflow: elide; + } + Text { + text: source.detail; + vertical-alignment: center; + font-size: 11px; + color: #8b949e; + } + } + } + } + Field { label: @tr("Stream name"); value <=> form.name; } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Frame rate"); + width: 130px; + vertical-alignment: center; + } + ComboBox { + model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps")]; + current-index <=> form.fps-index; + accessible-label: @tr("Frame rate"); + } + } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Quality"); + width: 130px; + vertical-alignment: center; + } + ComboBox { + model: [@tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("Best (10 Mbit/s)")]; + current-index <=> form.bitrate-index; + accessible-label: @tr("Quality"); + } + } + CheckBox { + text: @tr("Share system audio"); + checked <=> form.audio; + } + CheckBox { + text: @tr("Let everyone in the channel watch without asking"); + checked <=> form.auto-accept; + } + if Bridge.share-error != "": Text { + text: Bridge.share-error; + color: #f85149; + wrap: word-wrap; + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Cancel"); + clicked => { done(); } + } + Button { + text: Bridge.share-busy ? @tr("Starting…") : @tr("Start sharing"); + primary: true; + enabled: !Bridge.share-busy && Bridge.streams-available && Bridge.share-sources.length > 0; + clicked => { Bridge.start-share(form); } + } + } + } + } +} + +// Microphone level with the voice activation threshold. +component LevelMeter inherits Rectangle { + in property level: -100; + in property threshold: -40; + in property show-threshold: true; + // dBFS shown at the left edge. + property floor: -70; + height: 12px; + border-radius: 3px; + background: #0d1117; + border-width: 1px; + border-color: #30363d; + accessible-role: progress-indicator; + accessible-label: @tr("Microphone level"); + accessible-value: @tr("{} dB", round(level)); + accessible-value-minimum: floor; + accessible-value-maximum: 0; + Rectangle { + x: 0; + width: parent.width * clamp((level - floor) / (0 - floor), 0, 1); + border-radius: 3px; + background: level >= threshold ? #3fb950 : #58a6ff; + } + if show-threshold: Rectangle { + x: parent.width * clamp((threshold - floor) / (0 - floor), 0, 1) - 1px; + width: 2px; + background: #e6edf3; + } +} + +component SettingsDialog inherits Dialog { + in-out property tab; + callback done(); + card-width: 640px; + card-height: 660px; + dismissed => { done(); } + VerticalBox { + Text { + text: @tr("Settings"); + font-size: 18px; + font-weight: 700; + } + TabWidget { + vertical-stretch: 1; + current-index <=> tab; + Tab { + title: @tr("Audio"); + ScrollView { + VerticalLayout { + padding: 8px; + spacing: 8px; + Row { + label: @tr("Microphone"); + ComboBox { + model: Bridge.input-devices; + current-index: Bridge.audio.input-index; + accessible-label: @tr("Microphone"); + selected => { + Bridge.audio.input-index = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Speakers"); + ComboBox { + model: Bridge.output-devices; + current-index: Bridge.audio.output-index; + accessible-label: @tr("Speakers"); + selected => { + Bridge.audio.output-index = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Transmit"); + ComboBox { + model: [@tr("Push-to-talk"), @tr("Voice activation"), @tr("Continuously")]; + current-index: Bridge.audio.transmit; + accessible-label: @tr("Transmit"); + selected => { + Bridge.audio.transmit = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Voice activation level"); + Slider { + minimum: -70; + maximum: -10; + value: Bridge.audio.vad-threshold; + enabled: Bridge.audio.transmit == 1; + accessible-label: @tr("Voice activation level"); + changed(v) => { + Bridge.audio.vad-threshold = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} dB", round(Bridge.audio.vad-threshold)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Row { + label: @tr("Microphone level"); + VerticalLayout { + alignment: center; + LevelMeter { + level: Bridge.input-level; + threshold: Bridge.audio.vad-threshold; + show-threshold: Bridge.audio.transmit == 1; + } + } + Button { + text: Bridge.mic-test ? @tr("Stop test") : @tr("Test"); + enabled: !Bridge.voice-connected; + accessible-label: Bridge.mic-test ? @tr("Stop the microphone test") : @tr("Test the microphone"); + clicked => { Bridge.toggle-mic-test(); } + } + } + Text { + text: Bridge.voice-connected ? (Bridge.input-sending ? @tr("Sending voice") : @tr("Not sending")) : @tr("The meter shows the microphone while connected or during a test."); + font-size: 11px; + color: Bridge.input-sending ? #3fb950 : #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Processing"); + font-weight: 600; + } + CheckBox { + text: @tr("Echo cancellation"); + checked: Bridge.audio.echo-cancellation; + toggled => { + Bridge.audio.echo-cancellation = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + HorizontalLayout { + spacing: 8px; + CheckBox { + text: @tr("Noise suppression"); + checked: Bridge.audio.noise-suppression; + toggled => { + Bridge.audio.noise-suppression = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + ComboBox { + model: [@tr("Low"), @tr("Moderate"), @tr("High"), @tr("Very high")]; + current-index: Bridge.audio.noise-level; + enabled: Bridge.audio.noise-suppression; + accessible-label: @tr("Noise suppression level"); + selected => { + Bridge.audio.noise-level = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + CheckBox { + text: @tr("Automatic gain control"); + checked: Bridge.audio.auto-gain; + toggled => { + Bridge.audio.auto-gain = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + Row { + label: @tr("Microphone gain"); + Slider { + minimum: -30; + maximum: 30; + value: Bridge.audio.input-gain; + accessible-label: @tr("Microphone gain"); + changed(v) => { + Bridge.audio.input-gain = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} dB", round(Bridge.audio.input-gain)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Text { + text: @tr("Playback"); + font-weight: 600; + } + Row { + label: @tr("Volume"); + Slider { + minimum: 0; + maximum: 200; + value: Bridge.audio.output-volume; + accessible-label: @tr("Playback volume"); + changed(v) => { + Bridge.audio.output-volume = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{}%", round(Bridge.audio.output-volume)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Row { + label: @tr("Playback buffer"); + Slider { + minimum: 20; + maximum: 180; + value: Bridge.audio.playback-buffer; + accessible-label: @tr("Playback buffer"); + changed(v) => { + Bridge.audio.playback-buffer = round(v / 10) * 10; + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} ms", round(Bridge.audio.playback-buffer)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + } + } + } + Tab { + title: @tr("Push-to-talk"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Global push-to-talk key (works while other windows have focus)"); + checked <=> Bridge.global-ptt; + toggled => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + Row { + label: @tr("Key"); + key-edit := LineEdit { + text <=> Bridge.ptt-key; + placeholder-text: "Ctrl+Shift+T"; + enabled: Bridge.global-ptt; + accessible-label: @tr("Push-to-talk key"); + accepted => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + Button { + text: @tr("Apply"); + enabled: Bridge.global-ptt; + clicked => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + } + Text { + text: Bridge.ptt-status; + color: #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Keys are written like Ctrl+Shift+T, Alt+F1, CapsLock or MouseBack. On Wayland the desktop asks to confirm the key and may let you pick another one. The \"Hold to talk\" button in the window always works."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + Tab { + title: @tr("Streaming"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Enable H.264 (downloads OpenH264 from Cisco)"); + checked <=> Bridge.h264-enabled; + toggled => { Bridge.set-h264(Bridge.h264-enabled); } + } + Text { + text: Bridge.h264-attribution; + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + if Bridge.h264-enabled: HorizontalLayout { + spacing: 8px; + Text { + text: Bridge.h264-status; + vertical-alignment: center; + horizontal-stretch: 1; + wrap: word-wrap; + } + if !Bridge.h264-loaded: Button { + text: Bridge.h264-busy ? @tr("Downloading…") : @tr("Download OpenH264"); + enabled: !Bridge.h264-busy; + clicked => { Bridge.download-h264(); } + } + } + Text { + text: @tr("VP8 and VP9 work without it. H.264 lets you watch streams that other clients send as H.264. The library is downloaded from Cisco only when you click Download, and Cisco's license covers its patent royalties."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + Tab { + title: @tr("Privacy"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Save crash reports on this device (never uploaded)"); + checked <=> Bridge.crash-reports; + toggled => { Bridge.set-crash-reports(Bridge.crash-reports); } + } + Text { + text: @tr("A report is a text file with the error and where it happened. It may contain a server address from the error message. You can attach it to a bug report yourself; the app never sends it anywhere."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + } + HorizontalLayout { + alignment: end; + Button { + text: @tr("Close"); + clicked => { done(); } + } + } + } +} + +// Local volume and mute of one client. +component ClientAudioDialog inherits Dialog { + callback done(); + card-width: 380px; + card-height: content.preferred-height; + dismissed => { done(); } + content := VerticalBox { + alignment: start; + Text { + text: Bridge.client-audio.name; + font-size: 16px; + font-weight: 700; + overflow: elide; + } + Text { + text: @tr("Only changes what you hear."); + color: #8b949e; + font-size: 11px; + } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Volume"); + vertical-alignment: center; + } + Slider { + minimum: 0; + maximum: 400; + value: Bridge.client-audio.volume; + enabled: !Bridge.client-audio.muted; + accessible-label: @tr("Volume of {}", Bridge.client-audio.name); + changed(v) => { + Bridge.client-audio.volume = round(v / 5) * 5; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + Text { + text: @tr("{}%", round(Bridge.client-audio.volume)); + width: 48px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + CheckBox { + text: @tr("Mute for me"); + checked: Bridge.client-audio.muted; + toggled => { + Bridge.client-audio.muted = self.checked; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Reset"); + clicked => { + Bridge.client-audio.volume = 100; + Bridge.client-audio.muted = false; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + Button { + text: @tr("Close"); + primary: true; + clicked => { done(); } + } + } + } +} + +component AboutDialog inherits Dialog { + callback done(); + card-width: 720px; + card-height: 680px; + dismissed => { done(); } + VerticalBox { + Text { + text: @tr("About"); + font-size: 18px; + font-weight: 700; + } + Text { + text: @tr("Unofficial TeamSpeak 3/6 compatible client. Not affiliated with TeamSpeak Systems GmbH."); + wrap: word-wrap; + } + AboutSlint { + max-height: 150px; + } + if Bridge.h264-enabled: Text { + text: Bridge.h264-attribution; + wrap: word-wrap; + } + Text { + text: @tr("Third-party notices"); + font-weight: 600; + } + Rectangle { + vertical-stretch: 1; + background: #0d1117; + border-radius: 4px; + border-width: 1px; + border-color: #30363d; + ListView { + accessible-label: @tr("Third-party notices"); + for line in Bridge.notices: Text { + x: 8px; + width: parent.width - 16px; + text: line; + font-size: 11px; + color: #c9d1d9; + wrap: word-wrap; + } + } + } + HorizontalLayout { + alignment: end; + Button { + text: @tr("Close"); + clicked => { done(); } + } + } + } +} + export component MainWindow inherits Window { - title: "TS Client"; + title: @tr("TS Client"); preferred-width: 1200px; preferred-height: 760px; min-width: 360px; @@ -383,8 +1457,13 @@ export component MainWindow inherits Window { default-font-size: 13px; property editing: false; - property show-about: false; + in-out property show-about: false; + in-out property settings-tab: 0; + in-out property sharing-dialog: false; + in-out property settings-open: false; + in-out property client-open: false; property form; + property share-form; // Phones and narrow windows show one pane at a time. Set from a change // handler: a binding on `width` would loop through the layout. property narrow: false; @@ -398,6 +1477,14 @@ export component MainWindow inherits Window { keyboard-inset = self.virtual-keyboard-size.height > 0 ? self.height - self.virtual-keyboard-position.y : 0; } + // The viewer takes the whole window in full screen. + property chrome: !(Bridge.viewer-open && Bridge.viewer-fullscreen); + + public function open-share-dialog() { + share-form = Bridge.open-share(); + sharing-dialog = true; + } + VerticalLayout { // Android draws the window under the status and navigation bars. padding-top: root.safe-area-insets.top; @@ -405,14 +1492,16 @@ export component MainWindow inherits Window { padding-right: root.safe-area-insets.right; padding-bottom: max(root.safe-area-insets.bottom, root.keyboard-inset); // Toolbar - Rectangle { + if chrome: Rectangle { height: 48px; background: #161b22; + accessible-role: banner; HorizontalLayout { padding: 6px; spacing: 6px; if narrow: Button { - text: pane == 0 ? "Tree" : pane == 1 ? "Chat" : "Servers"; + text: pane == 0 ? @tr("Tree") : pane == 1 ? (Bridge.viewer-open ? @tr("Stream") : @tr("Chat")) : @tr("Servers"); + accessible-label: @tr("Switch pane"); clicked => { pane = mod(pane + 1, 3); } } Text { @@ -424,7 +1513,7 @@ export component MainWindow inherits Window { } Rectangle { } Button { - text: Bridge.voice-connected ? "Disconnect" : Bridge.voice-connecting ? "Connecting…" : "Connect"; + text: Bridge.voice-connected ? @tr("Disconnect") : Bridge.voice-connecting ? @tr("Connecting…") : @tr("Connect"); enabled: Bridge.current-server >= 0 && !Bridge.voice-connecting; primary: !Bridge.voice-connected; clicked => { @@ -436,17 +1525,17 @@ export component MainWindow inherits Window { } } Button { - text: Bridge.observing ? "Stop observing" : "Observe (invisible)"; + text: Bridge.observing ? @tr("Stop observing") : @tr("Observe (invisible)"); enabled: Bridge.can-observe; clicked => { Bridge.toggle-observe(); } } Button { - text: Bridge.input-muted ? "Mic: off" : "Mic: on"; + text: Bridge.input-muted ? @tr("Mic: off") : @tr("Mic: on"); enabled: Bridge.voice-connected; clicked => { Bridge.set-input-muted(!Bridge.input-muted); } } Button { - text: Bridge.output-muted ? "Sound: off" : "Sound: on"; + text: Bridge.output-muted ? @tr("Sound: off") : @tr("Sound: on"); enabled: Bridge.voice-connected; clicked => { Bridge.set-output-muted(!Bridge.output-muted); } } @@ -455,8 +1544,14 @@ export component MainWindow inherits Window { border-radius: 4px; background: Bridge.transmitting ? #238636 : ptt-area.has-hover ? #30363d : #21262d; opacity: Bridge.voice-connected ? 1.0 : 0.4; + accessible-role: button; + accessible-label: @tr("Hold to talk"); + accessible-enabled: Bridge.voice-connected; + accessible-checkable: true; + accessible-checked: Bridge.transmitting; + accessible-action-default => { Bridge.push-to-talk(!Bridge.transmitting); } Text { - text: Bridge.transmitting ? "Talking…" : "Hold to talk"; + text: Bridge.transmitting ? @tr("Talking…") : @tr("Hold to talk"); } ptt-area := TouchArea { enabled: Bridge.voice-connected; @@ -469,14 +1564,58 @@ export component MainWindow inherits Window { } } } + if Bridge.streams-available && Bridge.can-share: Button { + text: Bridge.share-state == "live" ? @tr("Sharing") : @tr("Share screen"); + primary: Bridge.share-state == "live"; + clicked => { open-share-dialog(); } + } Button { - text: "About"; - clicked => { show-about = true; } + text: @tr("Settings"); + clicked => { + Bridge.open-settings(); + settings-open = true; + } + } + Button { + text: @tr("About"); + clicked => { + Bridge.open-about(); + show-about = true; + } + } + } + } + if chrome && Bridge.crash-notice != "": Rectangle { + background: #3d2a0a; + accessible-role: groupbox; + accessible-label: @tr("Crash reports"); + HorizontalLayout { + padding: 6px; + padding-left: 10px; + spacing: 8px; + Text { + text: Bridge.crash-notice; + vertical-alignment: center; + horizontal-stretch: 1; + overflow: elide; + } + Button { + text: @tr("Open folder"); + clicked => { Bridge.open-crash-folder(); } + } + Button { + text: @tr("Delete"); + clicked => { Bridge.delete-crash-reports(); } + } + Button { + text: "×"; + accessible-label: @tr("Dismiss"); + clicked => { Bridge.dismiss-crash-notice(); } } } } HorizontalLayout { - if !narrow || pane == 2: ServerList { + if chrome && (!narrow || pane == 2): ServerList { // Fixed width beside the other panes, all the space alone. min-width: narrow ? 0px : 230px; max-width: narrow ? 100000px : 230px; @@ -490,17 +1629,31 @@ export component MainWindow inherits Window { editing = true; } } - if !narrow || pane == 0: ChannelTree { + if chrome && (!narrow || pane == 0): VerticalLayout { min-width: narrow ? 0px : 360px; max-width: narrow ? 100000px : 360px; horizontal-stretch: narrow ? 1 : 0; + ChannelTree { + vertical-stretch: 1; + client-clicked(id) => { + if (Bridge.open-client(id)) { + client-open = true; + } + } + } + if Bridge.streams-available: StreamsPanel { + vertical-stretch: 0; + manage-share => { open-share-dialog(); } + } } - if !narrow || pane == 1: ChatPanel { } + if (!narrow || pane == 1) && Bridge.viewer-open: StreamViewer { } + if chrome && (!narrow || pane == 1) && !Bridge.viewer-open: ChatPanel { } } // Status bar - Rectangle { + if chrome: Rectangle { height: 26px; background: #161b22; + accessible-role: content-info; HorizontalLayout { padding-left: 8px; padding-right: 8px; @@ -525,24 +1678,24 @@ export component MainWindow inherits Window { done => { editing = false; } } - if show-about: Rectangle { - background: #000000c0; - TouchArea { - clicked => { show-about = false; } - } - VerticalBox { - alignment: center; - Text { - text: "Unofficial TeamSpeak 3/6 compatible client. Not affiliated with TeamSpeak Systems GmbH."; - horizontal-alignment: center; - wrap: word-wrap; - } - AboutSlint { } - Text { - text: "Third-party licenses: see THIRD_PARTY_NOTICES. Click to close."; - horizontal-alignment: center; - color: #8b949e; - } + if sharing-dialog: ShareDialog { + form <=> share-form; + done => { sharing-dialog = false; } + } + + if settings-open: SettingsDialog { + tab <=> settings-tab; + done => { + settings-open = false; + Bridge.close-settings(); } } + + if client-open: ClientAudioDialog { + done => { client-open = false; } + } + + if show-about: AboutDialog { + done => { show-about = false; } + } } diff --git a/docs/architecture.md b/docs/architecture.md index b8038b3..e94d147 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 diff --git a/docs/audio.md b/docs/audio.md index b66c796..af035c3 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -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`); diff --git a/docs/media.md b/docs/media.md index 0792e0c..a4f1045 100644 --- a/docs/media.md +++ b/docs/media.md @@ -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) | diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 55c11c2..fe4b56a 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -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 ` 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 ` 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=`). -- [ ] 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). diff --git a/docs/screenshots/desktop-audio-settings.png b/docs/screenshots/desktop-audio-settings.png new file mode 100644 index 0000000..b6edd10 Binary files /dev/null and b/docs/screenshots/desktop-audio-settings.png differ diff --git a/docs/screenshots/desktop-share-dialog.png b/docs/screenshots/desktop-share-dialog.png new file mode 100644 index 0000000..9e020d8 Binary files /dev/null and b/docs/screenshots/desktop-share-dialog.png differ diff --git a/docs/screenshots/desktop-share-live.png b/docs/screenshots/desktop-share-live.png new file mode 100644 index 0000000..75a915c Binary files /dev/null and b/docs/screenshots/desktop-share-live.png differ diff --git a/docs/screenshots/desktop-stream-viewer.png b/docs/screenshots/desktop-stream-viewer.png new file mode 100644 index 0000000..d1a8cd8 Binary files /dev/null and b/docs/screenshots/desktop-stream-viewer.png differ diff --git a/tools/tsctl/Cargo.toml b/tools/tsctl/Cargo.toml index b4f6701..aa44919 100644 --- a/tools/tsctl/Cargo.toml +++ b/tools/tsctl/Cargo.toml @@ -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" diff --git a/tools/tsctl/src/stream.rs b/tools/tsctl/src/stream.rs index 7dfae58..797f6f1 100644 --- a/tools/tsctl/src/stream.rs +++ b/tools/tsctl/src/stream.rs @@ -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 `, `deny `, `kick `, `stop`. + /// Stream in our channel: the screen (VP8) and system audio (Opus). + /// Without `--auto-accept`, answer join requests on stdin: `accept + /// `, `deny `, `kick `, `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[:]`, `screen[:]` (this session's backend), + /// `window:` 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, - /// 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, - /// Exit successfully once this many video frames arrived. + /// Exit successfully once this many video frames were decoded. #[arg(long)] expect_frames: Option, /// Give up after this many seconds; fails if `--expect-frames` was not reached. #[arg(long)] timeout: Option, + /// Save the last decoded picture as PNG. + #[arg(long)] + save_frame: Option, }, } @@ -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> { - if !synthetic { - bail!("only synthetic frames are available yet: pass --synthetic"); - } - Ok(Box::new(SyntheticSource::new(fps, frame_size, audio))) +/// `synthetic`, `x11[:]`, `screen[:]`, `window:`, `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 { + 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:, portal"), + }) +} + +/// `x`. +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, + mut source: EncodedSource, length: Option, ) -> 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, target: &Target, expect: Option, timeout: Option, + save: Option<&Path>, ) -> Result<()> { let deadline = timeout.map(|t| Instant::now() + t); let mut watching: Option = 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 = 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| -> 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())), }; } _ => {}