wip: tsc-ui streams panel, viewer, share dialog, settings, hotkeys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 14:54:26 +00:00
1 parent 38363ca447
commit 222edcf775
12 files changed
+3324 -160

No files matched your search

Generated
+4
View File
@@ -8767,13 +8767,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",
+2
View File
@@ -209,6 +209,8 @@ pub struct SessionState {
pub presence_source: Option<Source>,
/// Our own channel while voice-connected.
pub own_channel: Option<ChannelId>,
/// Our own client id while voice-connected.
pub own_client: Option<u16>,
pub input_muted: bool,
pub output_muted: bool,
pub transmitting: bool,
+2
View File
@@ -433,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
@@ -501,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}"));
+13 -1
View File
@@ -16,21 +16,33 @@ path = "src/lib.rs"
name = "tsc-desktop"
path = "src/main.rs"
[features]
default = ["media"]
# Sharing the screen and decoding watched streams (tsc-core's media
# pipeline: libvpx, X11 / PipeWire capture). Stream audio works without it.
media = ["tsc-core/media"]
[dependencies]
anyhow = "1.0.104"
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
dirs = "6"
png = "0.18"
serde = { version = "1", features = ["derive"] }
slint = { version = "1.18", features = ["renderer-software"] }
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" }
tsc-platform = { path = "../tsc-platform" }
tsc-query = { path = "../tsc-query" }
tsc-store = { path = "../tsc-store", features = ["keyring"] }
tsclientlib = { path = "../proto/tsclientlib" }
[dev-dependencies]
serde_json = "1"
[build-dependencies]
slint-build = "1.18"
+583 -58
View File
@@ -1,20 +1,36 @@
//! Application state on the UI thread, wired to the engine.
//!
//! Streams (the streams panel, sharing, the viewer) are in `streams.rs`,
//! the settings page's data in `settings.rs`.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use tokio::runtime::Runtime;
use tracing::warn;
use tsc_core::stream::StreamInfo;
use tsc_core::{
Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, VoiceState,
AudioSettings, Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions,
VoiceState,
};
use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows};
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows};
use tsc_platform::{crash, notices};
use tsc_store::{Bookmark, MemorySecrets, QueryConfig, QueryTransport, Secrets, Store};
use crate::hotkey::GlobalPtt;
use crate::settings::{
self, AUDIO_KEY, CLIENT_PLAYBACK_KEY, ClientPlayback, ClientPlaybackMap, DeviceChoices, UI_KEY,
UiSettings,
};
use crate::streams::{Share, Watch};
use crate::video::Video;
slint::include_modules!();
/// Secrets in the OS keyring, or in memory when there is none (headless
@@ -54,21 +70,27 @@ struct Tab {
}
/// What we know about one server session.
struct SessionView {
state: SessionState,
presence: Arc<Presence>,
pub(crate) struct SessionView {
pub state: SessionState,
pub capabilities: Capabilities,
pub presence: Arc<Presence>,
collapsed: HashSet<ChannelId>,
talking: HashSet<u16>,
tabs: Vec<Tab>,
current_tab: usize,
/// The own channel's tab was focused for this voice connection.
focused_own_channel: bool,
/// The streams in our channel (TeamSpeak 6).
pub streams: Vec<StreamInfo>,
/// Clients whose stored volume was sent for this voice connection.
applied_playback: HashSet<u16>,
}
impl Default for SessionView {
fn default() -> Self {
Self {
state: SessionState::default(),
capabilities: Capabilities::default(),
presence: Arc::default(),
collapsed: HashSet::new(),
talking: HashSet::new(),
@@ -80,30 +102,79 @@ impl Default for SessionView {
}],
current_tab: 0,
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
}
}
}
struct App {
ui: slint::Weak<MainWindow>,
impl SessionView {
/// Streams can be watched and shared: TeamSpeak 6, connected with voice.
pub fn streams_available(&self) -> bool {
self.capabilities.streams && self.state.voice == VoiceState::Connected
}
/// A client's nickname, or its id.
pub fn nickname(&self, client: u16) -> String {
self.presence
.clients
.get(&client)
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
}
}
pub(crate) struct App {
pub ui: slint::Weak<MainWindow>,
store: Store,
secrets: Box<dyn Secrets>,
engine: Engine,
pub engine: Engine,
identity: tsclientlib::Identity,
bookmarks: Vec<Bookmark>,
current: Option<i64>,
sessions: HashMap<i64, SessionView>,
pub current: Option<i64>,
pub sessions: HashMap<i64, SessionView>,
status: String,
pub settings: UiSettings,
audio: AudioSettings,
/// Audio settings changed since they were last stored.
audio_dirty: bool,
inputs: DeviceChoices,
outputs: DeviceChoices,
playback: ClientPlaybackMap,
/// The client in the volume dialog: session, client id, unique id.
playback_dialog: Option<(i64, u16, Option<String>)>,
mic_test: bool,
ptt: GlobalPtt,
pub video: Video,
/// Our stream.
pub share: Option<Share>,
/// The capture for a share is being started.
pub share_busy: bool,
pub share_error: String,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// Stream volume in percent, kept between streams.
pub stream_volume: f32,
/// `TSC_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
/// The notices are in the About page's model.
notices_loaded: bool,
}
thread_local! {
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
}
fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
pub(crate) fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
APP.with(|app| app.borrow_mut().as_mut().map(f))
}
/// Run `f` on the app from another thread, on the UI thread.
pub(crate) fn later(f: impl FnOnce(&mut App) + Send + 'static) {
let _ = slint::invoke_from_event_loop(move || {
with_app(f);
});
}
/// Start options for [`run`].
#[derive(Clone, Debug, Default)]
pub struct RunOptions {
@@ -115,13 +186,19 @@ pub struct RunOptions {
/// 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 runtime = Runtime::new()?;
let engine = runtime.block_on(async { Engine::start() });
// Development switches: TSC_DATA_DIR isolates the database,
// TSC_AUTOCONNECT=voice|observe connects the first bookmark on start,
// TSC_SCREENSHOT=<png> saves the window after TSC_SCREENSHOT_DELAY seconds and exits.
let dir = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) {
// TSC_SCREENSHOT=<png> saves the window after TSC_SCREENSHOT_DELAY seconds and exits,
// TSC_DEMO_STREAM=1 shows a local test stream in the viewer,
// TSC_OPEN=share|settings opens that dialog on start, TSC_AUTOWATCH=1 watches the
// first stream that shows up.
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"),
@@ -137,9 +214,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,
@@ -153,26 +252,51 @@ 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,
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.
let mut events = engine.subscribe();
runtime.spawn(async move {
loop {
match events.recv().await {
Ok(event) => {
let _ = slint::invoke_from_event_loop(move || {
with_app(|app| app.handle_event(event));
});
}
Ok(event) => later(move |app| app.handle_event(event)),
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
});
// 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") => {
@@ -183,29 +307,46 @@ pub fn run(options: RunOptions) -> Result<()> {
}
_ => {}
}
match std::env::var("TSC_OPEN").as_deref() {
Ok("share") => ui.invoke_open_share_dialog(),
Ok("settings") => {
with_app(|app| app.open_settings());
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()?;
// Leave servers properly, so no ghost client stays behind until it times out.
let open = with_app(|app| {
app.save_audio();
app.watch = None;
app.share = None;
for id in app.sessions.keys() {
app.engine.send(Command::CloseSession { session: *id as u64 });
}
!app.sessions.is_empty()
});
APP.with(|a| a.borrow_mut().take());
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(())
}
@@ -282,6 +423,112 @@ fn wire_callbacks(ui: &MainWindow) {
bridge.on_delete_bookmark(|id| {
with_app(|app| app.delete_bookmark(id as i64));
});
// Streams.
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default());
bridge.on_start_share(|form| {
with_app(|app| app.start_share(form));
});
bridge.on_stop_share(|| {
with_app(|app| app.stop_share());
});
bridge.on_respond_viewer(|viewer, accept| {
with_app(|app| app.respond_viewer(viewer as u16, accept));
});
bridge.on_kick_viewer(|viewer| {
with_app(|app| app.kick_viewer(viewer as u16));
});
bridge.on_watch_stream(|id| {
with_app(|app| app.watch_stream(id.to_string()));
});
bridge.on_show_viewer(|| {
with_app(|app| app.show_viewer(true));
});
bridge.on_hide_viewer(|| {
with_app(|app| app.show_viewer(false));
});
bridge.on_leave_stream(|| {
with_app(|app| app.leave_stream());
});
bridge.on_set_stream_volume(|volume| {
with_app(|app| app.set_stream_volume(volume));
});
bridge.on_toggle_fullscreen(|| {
with_app(|app| app.toggle_fullscreen());
});
// Settings.
bridge.on_open_settings(|| {
with_app(|app| app.open_settings());
});
bridge.on_close_settings(|| {
with_app(|app| app.close_settings());
});
bridge.on_audio_changed(|form| {
with_app(|app| app.audio_changed(&form));
});
bridge.on_toggle_mic_test(|| {
with_app(|app| app.set_mic_test(!app.mic_test));
});
bridge.on_apply_ptt(|enabled, key| {
with_app(|app| app.apply_ptt(enabled, key.to_string()));
});
bridge.on_set_h264(|enabled| {
with_app(|app| app.set_h264(enabled));
});
bridge.on_download_h264(|| {
with_app(|app| app.download_h264());
});
bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false));
bridge.on_client_audio_changed(|form| {
with_app(|app| app.client_playback_changed(&form));
});
// Crash reports and notices.
bridge.on_set_crash_reports(|enabled| {
with_app(|app| app.set_crash_reports(enabled));
});
bridge.on_open_crash_folder(|| {
with_app(|app| {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) = result.and_then(|dir| open_path(&dir).map_err(|e| e.to_string())) {
app.set_status(format!("Cannot open the crash report folder: {e}"));
}
});
});
bridge.on_delete_crash_reports(|| {
with_app(|app| {
match crash::clear() {
Ok(n) => app.set_status(format!("Deleted {n} crash reports")),
Err(e) => app.set_status(format!("Cannot delete the crash reports: {e}")),
}
app.refresh_crash_notice();
});
});
bridge.on_dismiss_crash_notice(|| {
with_app(|app| {
if let Some(ui) = app.ui.upgrade() {
ui.global::<Bridge>().set_crash_notice(SharedString::new());
}
});
});
bridge.on_open_about(|| {
with_app(|app| app.load_notices());
});
}
/// Open a file or folder with the desktop's default application.
fn open_path(path: &Path) -> std::io::Result<()> {
#[cfg(windows)]
let mut command = std::process::Command::new("explorer");
#[cfg(target_os = "macos")]
let mut command = std::process::Command::new("open");
#[cfg(not(any(windows, target_os = "macos")))]
let mut command = std::process::Command::new("xdg-open");
let mut child = command.arg(path).spawn()?;
// Reap it without blocking the UI.
std::thread::spawn(move || child.wait());
Ok(())
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
@@ -300,7 +547,7 @@ fn time_of(ts_ms: i64) -> String {
.unwrap_or_default()
}
fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
ModelRc::from(Rc::new(VecModel::from(items)))
}
@@ -310,23 +557,33 @@ impl App {
Some(self.sessions.entry(id).or_default())
}
fn bookmark(&self, id: i64) -> Option<&Bookmark> {
pub fn view(&self) -> Option<&SessionView> {
self.current.and_then(|id| self.sessions.get(&id))
}
pub fn bookmark(&self, id: i64) -> Option<&Bookmark> {
self.bookmarks.iter().find(|b| b.id == id)
}
fn command(&self, f: impl FnOnce(u64) -> Command) {
pub fn command(&self, f: impl FnOnce(u64) -> Command) {
if let Some(id) = self.current {
self.engine.send(f(id as u64));
}
}
fn set_status(&mut self, text: impl Into<String>) {
pub fn set_status(&mut self, text: impl Into<String>) {
self.status = text.into();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_status_text(self.status.clone().into());
}
}
pub fn store_settings(&self) {
if let Err(e) = self.store.set_setting(UI_KEY, &self.settings) {
warn!(%e, "could not store settings");
}
}
fn connect_voice(&mut self) {
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
let mut options = VoiceOptions::new(&b.address, &b.nickname);
@@ -334,6 +591,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));
@@ -556,6 +814,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");
@@ -570,8 +832,10 @@ impl App {
}
self.refresh_servers();
self.refresh_toolbar();
self.refresh_streams();
}
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}"),
@@ -580,12 +844,15 @@ impl App {
};
self.set_status(format!("Connected to {name} ({kind})"));
}
self.refresh_streams();
}
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();
}
}
Event::Talking { session, client, talking } => {
@@ -599,10 +866,23 @@ impl App {
self.refresh_tree();
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => self.current == Some(s as i64),
None => self.mic_test,
};
if shown && let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
}
Event::MicrophoneTestError { message } => {
self.set_status(format!("Microphone test: {message}"))
}
Event::Chat { session, message } => self.add_message(session as i64, message),
Event::Error { message, .. } => self.set_status(message),
// Stream events: the streams panel is not wired yet.
_ => {}
event => self.stream_event(event),
}
}
@@ -648,11 +928,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) {
@@ -685,11 +974,7 @@ impl App {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.current.and_then(|id| self.bookmark(id));
let state = self
.current
.and_then(|id| self.sessions.get(&id))
.map(|v| v.state.clone())
.unwrap_or_default();
let state = self.view().map(|v| v.state.clone()).unwrap_or_default();
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
@@ -712,11 +997,15 @@ impl App {
.into(),
);
bridge.set_status_text(self.status.clone().into());
if state.voice != VoiceState::Connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
fn refresh_tree(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
let Some(view) = self.view() else {
ui.global::<Bridge>().set_tree(model(Vec::new()));
return;
};
@@ -732,21 +1021,33 @@ impl App {
own: own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: view.collapsed.contains(&channel.id),
local_volume: 100,
..Default::default()
},
TreeRow::Client { depth, client } => TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
own: false,
talking: view.talking.contains(&client.id) || client.talking == Some(true),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
..Default::default()
},
TreeRow::Client { depth, client } => {
let playback = client
.uid
.as_ref()
.and_then(|uid| self.playback.get(uid))
.copied()
.unwrap_or_default();
TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
own: false,
talking: view.talking.contains(&client.id) || client.talking == Some(true),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
local_muted: playback.muted,
local_volume: (playback.volume * 100.0).round() as i32,
myself: view.state.own_client == Some(client.id),
..Default::default()
}
}
})
.collect();
ui.global::<Bridge>().set_tree(model(rows));
@@ -755,7 +1056,7 @@ impl App {
fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
let Some(view) = self.view() else {
bridge.set_tabs(model(vec![ChatTab { title: "Server".into(), ..Default::default() }]));
bridge.set_messages(model(Vec::new()));
return;
@@ -777,4 +1078,228 @@ impl App {
bridge.set_current_tab(view.current_tab as i32);
bridge.set_messages(model(view.tabs[view.current_tab].lines.clone()));
}
// Settings page.
fn open_settings(&mut self) {
let list = |devices: tsc_audio::Result<Vec<tsc_audio::device::DeviceInfo>>, input: bool| {
let devices = devices.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
});
devices
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect::<Vec<_>>()
};
let inputs = list(tsc_audio::device::input_devices(), true);
let outputs = list(tsc_audio::device::output_devices(), false);
self.inputs = DeviceChoices::new(&inputs, self.audio.input_device.as_deref());
self.outputs = DeviceChoices::new(&outputs, self.audio.output_device.as_deref());
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect());
bridge.set_input_devices(names(&self.inputs));
bridge.set_output_devices(names(&self.outputs));
bridge.set_audio(settings::audio_form(&self.audio, &self.inputs, &self.outputs));
bridge.set_global_ptt(self.settings.global_ptt);
bridge.set_ptt_key(self.settings.ptt_key.clone().into());
bridge.set_h264_enabled(self.settings.openh264);
self.refresh_h264();
}
fn close_settings(&mut self) {
self.set_mic_test(false);
self.save_audio();
}
fn audio_changed(&mut self, form: &AudioForm) {
let audio = settings::apply_audio_form(form, &self.audio, &self.inputs, &self.outputs);
if audio == self.audio {
return;
}
self.audio = audio;
self.audio_dirty = true;
self.engine.send(Command::SetAudioSettings(Box::new(self.audio.clone())));
}
fn save_audio(&mut self) {
if !self.audio_dirty {
return;
}
self.audio_dirty = false;
if let Err(e) = self.store.set_setting(AUDIO_KEY, &self.audio) {
warn!(%e, "could not store audio settings");
}
}
fn set_mic_test(&mut self, on: bool) {
if self.mic_test == on {
return;
}
self.mic_test = on;
self.engine.send(Command::TestMicrophone { on });
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(on);
if !on {
bridge.set_input_level(-100.0);
}
}
}
fn apply_ptt(&mut self, enabled: bool, key: String) {
let key = key.trim().to_owned();
self.settings.global_ptt = enabled;
if !key.is_empty() {
self.settings.ptt_key = key.clone();
}
self.store_settings();
self.ptt.set((enabled && !key.is_empty()).then_some(key));
}
fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
fn set_h264(&mut self, enabled: bool) {
self.settings.openh264 = enabled;
self.store_settings();
self.video.set_h264(enabled);
self.refresh_h264();
}
fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
bridge.set_h264_loaded(loaded);
bridge.set_h264_busy(status.starts_with("Downloading"));
bridge.set_h264_status(status.into());
}
/// Switches the About page and the settings show.
fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.settings.crash_reports);
}
fn set_crash_reports(&mut self, enabled: bool) {
self.settings.crash_reports = enabled;
self.store_settings();
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk.
fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let text = match crash::pending_reports() {
Ok(reports) if !reports.is_empty() => {
let newest = &reports[reports.len() - 1];
let saved = match reports.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({}). {saved} on this device.", newest.summary)
}
_ => String::new(),
};
ui.global::<Bridge>().set_crash_notice(text.into());
}
/// The third-party notices, one model entry per line.
fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session.
fn open_client(&mut self, client: u16) -> bool {
let Some(id) = self.current else { return false };
let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else {
return false;
};
let playback =
info.uid.as_ref().and_then(|uid| self.playback.get(uid)).copied().unwrap_or_default();
self.playback_dialog = Some((id, client, info.uid.clone()));
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(ClientAudio {
id: client as i32,
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
});
}
true
}
fn client_playback_changed(&mut self, form: &ClientAudio) {
let Some((session, client, uid)) = self.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume });
self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted });
// Kept by unique id; clients without one only for this connection.
if let Some(uid) = uid {
if playback.is_default() {
self.playback.remove(&uid);
} else {
self.playback.insert(uid, playback);
}
if let Err(e) = self.store.set_setting(CLIENT_PLAYBACK_KEY, &self.playback) {
warn!(%e, "could not store client volumes");
}
}
self.refresh_tree();
}
/// Send the stored volumes of clients that appeared in a voice session.
fn apply_client_playback(&mut self, session: i64) {
let Some(view) = self.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| self.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
self.engine.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume });
if playback.muted {
self.engine.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
}
+123
View File
@@ -0,0 +1,123 @@
//! Global push-to-talk: a task owns the `tsc_platform::HotkeyManager`
//! (portal on Wayland, XInput2 on X11, a hook on Windows) and reports
//! presses and releases.
use tokio::runtime::Runtime;
use tokio::sync::mpsc;
/// Id of the push-to-talk registration (the portal remembers it).
#[cfg(not(target_os = "android"))]
const PTT_ID: &str = "push-to-talk";
/// Handle to the hotkey task.
pub(crate) struct GlobalPtt {
tx: mpsc::UnboundedSender<Option<String>>,
}
impl GlobalPtt {
/// Start the task. `status` gets a line for the settings page,
/// `transmit` the key's state; both are called on the runtime.
pub fn start(
runtime: &Runtime,
status: impl Fn(String) + Send + 'static,
transmit: impl Fn(bool) + Send + 'static,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
runtime.spawn(run(rx, status, transmit));
Self { tx }
}
/// Register `key` (e.g. `Ctrl+Shift+T`) instead of the current one, or
/// nothing.
pub fn set(&self, key: Option<String>) {
let _ = self.tx.send(key);
}
}
#[cfg(target_os = "android")]
async fn run(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
_transmit: impl Fn(bool),
) {
while let Some(key) = rx.recv().await {
if key.is_some() {
status("Global hotkeys are not available on this platform.".into());
}
}
}
#[cfg(not(target_os = "android"))]
async fn run(
mut rx: mpsc::UnboundedReceiver<Option<String>>,
status: impl Fn(String),
transmit: impl Fn(bool),
) {
use tsc_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager};
async fn next(events: &mut Option<HotkeyEvents>) -> Option<HotkeyEvent> {
match events {
Some(events) => events.recv().await,
None => std::future::pending().await,
}
}
let mut manager: Option<HotkeyManager> = None;
let mut events: Option<HotkeyEvents> = None;
loop {
tokio::select! {
key = rx.recv() => {
let Some(key) = key else { break };
events = None;
// Released: whatever was held no longer counts.
transmit(false);
if let Some(m) = &mut manager {
let _ = m.unregister(PTT_ID).await;
}
let Some(key) = key else {
status("Off.".into());
continue;
};
let hotkey: Hotkey = match key.parse() {
Ok(h) => h,
Err(e) => {
status(format!("{e}"));
continue;
}
};
if manager.is_none() {
match HotkeyManager::new().await {
Ok(m) => manager = Some(m),
Err(e) => {
status(format!("Global hotkeys are not available: {e}"));
continue;
}
}
}
let Some(m) = &mut manager else { continue };
match m.register(PTT_ID, "Push to talk", hotkey).await {
Ok(registered) => {
events = Some(registered);
status(match m.backend() {
BackendKind::Portal => format!(
"Registered with the desktop: {}",
m.trigger_description(PTT_ID).unwrap_or(key)
),
BackendKind::X11 => format!("Active: {hotkey} (X11)"),
BackendKind::WindowsHook => format!("Active: {hotkey}"),
});
}
Err(e) => status(format!("Could not register {key}: {e}")),
}
}
event = next(&mut events) => match event {
Some(HotkeyEvent::Pressed) => transmit(true),
Some(HotkeyEvent::Released) => transmit(false),
None => {
events = None;
status("The hotkey was removed by the desktop.".into());
}
},
}
}
}
+4
View File
@@ -1,5 +1,9 @@
//! Slint user interface shared by the desktop binary and the mobile apps.
mod app;
mod hotkey;
mod settings;
mod streams;
mod video;
pub use app::{RunOptions, run};
+4
View File
@@ -1,5 +1,9 @@
//! Desktop client.
// Release builds on Windows are GUI programs (no console window); debug
// builds keep the console for logs.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use anyhow::Result;
use tracing_subscriber::EnvFilter;
+262
View File
@@ -0,0 +1,262 @@
//! Settings kept in the store (besides bookmarks and identities), and their
//! conversion to and from the forms of the settings page.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use tsc_audio::process::NoiseLevel;
use tsc_core::{AudioSettings, TransmitMode};
use crate::app::AudioForm;
/// Store keys.
pub const AUDIO_KEY: &str = "audio";
pub const UI_KEY: &str = "ui";
pub const CLIENT_PLAYBACK_KEY: &str = "client_playback";
/// Frame rates and bitrates (kbit/s) of the share dialog.
pub const FPS_CHOICES: [u32; 3] = [15, 30, 60];
pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiSettings {
/// Global push-to-talk hotkey (besides the button in the window).
pub global_ptt: bool,
/// E.g. `Ctrl+Shift+T` (`tsc_platform::Hotkey` syntax).
pub ptt_key: String,
/// H.264 through Cisco's OpenH264, downloaded on request.
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
}
impl Default for UiSettings {
fn default() -> Self {
Self {
global_ptt: true,
ptt_key: "Ctrl+Shift+T".into(),
openh264: false,
portal_restore_token: None,
share: ShareDefaults::default(),
crash_reports: false,
}
}
}
/// The last choices in the share dialog.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
pub fps_index: usize,
pub bitrate_index: usize,
pub audio: bool,
pub auto_accept: bool,
}
impl Default for ShareDefaults {
fn default() -> Self {
Self { fps_index: 1, bitrate_index: 1, audio: true, auto_accept: false }
}
}
/// Local playback of one client, kept by its unique id.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
pub muted: bool,
}
impl Default for ClientPlayback {
fn default() -> Self {
Self { volume: 1.0, muted: false }
}
}
impl ClientPlayback {
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
}
impl DeviceChoices {
/// `devices` as `(id, name, is_default)`. A selected device that is not
/// connected stays in the list, so the choice survives.
pub fn new(devices: &[(String, String, bool)], selected: Option<&str>) -> Self {
let default_name = devices.iter().find(|d| d.2).map(|d| d.1.as_str());
let mut choices = Self {
names: vec![match default_name {
Some(name) => format!("System default ({name})"),
None => "System default".into(),
}],
ids: vec![None],
};
for (id, name, _) in devices {
choices.names.push(name.clone());
choices.ids.push(Some(id.clone()));
}
if let Some(id) = selected
&& !choices.ids.iter().any(|i| i.as_deref() == Some(id))
{
choices.names.push(format!("{id} (not connected)"));
choices.ids.push(Some(id.to_owned()));
}
choices
}
pub fn index_of(&self, id: Option<&str>) -> usize {
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
}
pub fn id_at(&self, index: i32) -> Option<String> {
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
}
}
fn noise_index(level: NoiseLevel) -> i32 {
match level {
NoiseLevel::Low => 0,
NoiseLevel::Moderate => 1,
NoiseLevel::High => 2,
NoiseLevel::VeryHigh => 3,
}
}
fn noise_level(index: i32) -> NoiseLevel {
match index {
0 => NoiseLevel::Low,
2 => NoiseLevel::High,
3 => NoiseLevel::VeryHigh,
_ => NoiseLevel::Moderate,
}
}
/// The settings page's form for `settings`.
pub fn audio_form(
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioForm {
let p = &settings.processing;
AudioForm {
input_index: inputs.index_of(settings.input_device.as_deref()) as i32,
output_index: outputs.index_of(settings.output_device.as_deref()) as i32,
transmit: match settings.transmit {
TransmitMode::PushToTalk => 0,
TransmitMode::VoiceActivation => 1,
TransmitMode::Continuous => 2,
},
vad_threshold: settings.vad.threshold_db,
echo_cancellation: p.echo_cancellation,
noise_suppression: p.noise_suppression,
noise_level: noise_index(p.noise_level),
auto_gain: p.auto_gain,
input_gain: p.input_gain_db,
output_volume: settings.output_volume * 100.0,
playback_buffer: settings.playback_buffer_ms as f32,
}
}
/// `settings` changed as the form says; what the form does not show stays.
pub fn apply_audio_form(
form: &AudioForm,
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioSettings {
let mut s = settings.clone();
s.input_device = inputs.id_at(form.input_index);
s.output_device = outputs.id_at(form.output_index);
s.transmit = match form.transmit {
1 => TransmitMode::VoiceActivation,
2 => TransmitMode::Continuous,
_ => TransmitMode::PushToTalk,
};
s.vad.threshold_db = form.vad_threshold;
s.processing.echo_cancellation = form.echo_cancellation;
s.processing.noise_suppression = form.noise_suppression;
s.processing.noise_level = noise_level(form.noise_level);
s.processing.auto_gain = form.auto_gain;
s.processing.input_gain_db = form.input_gain;
s.output_volume = (form.output_volume / 100.0).clamp(0.0, 4.0);
s.playback_buffer_ms = form.playback_buffer.round().clamp(20.0, 180.0) as u32;
s
}
#[cfg(test)]
mod tests {
use super::*;
fn devices() -> Vec<(String, String, bool)> {
vec![
("alsa:hw:0,0".into(), "Built-in".into(), true),
("alsa:hw:1,0".into(), "Headset".into(), false),
]
}
#[test]
fn device_choices() {
let choices = DeviceChoices::new(&devices(), None);
assert_eq!(choices.names, ["System default (Built-in)", "Built-in", "Headset"]);
assert_eq!(choices.index_of(Some("alsa:hw:1,0")), 2);
assert_eq!(choices.id_at(0), None);
assert_eq!(choices.id_at(2).as_deref(), Some("alsa:hw:1,0"));
assert_eq!(choices.id_at(9), None);
// An unplugged device stays selectable.
let choices = DeviceChoices::new(&devices(), Some("usb:mic"));
assert_eq!(choices.names.last().unwrap(), "usb:mic (not connected)");
assert_eq!(choices.index_of(Some("usb:mic")), 3);
}
#[test]
fn audio_form_roundtrip() {
let inputs = DeviceChoices::new(&devices(), None);
let outputs = DeviceChoices::new(&devices(), None);
let mut settings = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
output_volume: 0.5,
playback_buffer_ms: 80,
..Default::default()
};
settings.vad.threshold_db = -35.0;
settings.processing.noise_level = NoiseLevel::High;
settings.processing.input_gain_db = 6.0;
let form = audio_form(&settings, &inputs, &outputs);
assert_eq!((form.input_index, form.output_index, form.transmit), (2, 0, 1));
assert_eq!(form.output_volume, 50.0);
assert_eq!(apply_audio_form(&form, &settings, &inputs, &outputs), settings);
let form = AudioForm { transmit: 2, echo_cancellation: false, playback_buffer: 500.0, ..form };
let changed = apply_audio_form(&form, &settings, &inputs, &outputs);
assert_eq!(changed.transmit, TransmitMode::Continuous);
assert!(!changed.processing.echo_cancellation);
assert_eq!(changed.playback_buffer_ms, 180);
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
assert!(parsed.openh264);
assert!(!parsed.crash_reports, "crash reports are opt-in");
assert_eq!(parsed.ptt_key, "Ctrl+Shift+T");
assert_eq!(parsed.share, ShareDefaults::default());
let map: ClientPlaybackMap =
serde_json::from_str(r#"{"uid=":{"volume":0.5,"muted":false}}"#).unwrap();
assert_eq!(map["uid="].volume, 0.5);
}
}
+582
View File
@@ -0,0 +1,582 @@
//! 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;
use tsc_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState};
use tsc_core::{Command, Event, StreamState, WatchState};
use crate::app::{
App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model,
};
use crate::settings::{BITRATE_CHOICES, FPS_CHOICES, ShareDefaults};
use crate::video::{self, Capture, CaptureRequest, Decoder};
/// Our stream.
pub(crate) struct Share {
pub session: i64,
/// Stops capturing when dropped.
capture: Capture,
/// The server confirmed the stream.
live: bool,
viewers: Vec<ViewerInfo>,
/// The capture ended by itself and the stream is being stopped.
stopping: bool,
}
/// The stream in the viewer.
pub(crate) struct Watch {
/// `None` for the local demo stream.
session: Option<i64>,
stream_id: String,
title: String,
streamer: String,
/// Shown over the picture; empty while it plays.
status: String,
connected: bool,
ended: bool,
has_frame: bool,
/// Shown instead of the chat.
shown: bool,
decoder: Option<Decoder>,
}
fn end_text(reason: &EndReason, streamer: &str) -> String {
match reason {
EndReason::Local => "You left the stream.".into(),
EndReason::Denied => format!("{streamer} did not let you watch."),
EndReason::Stopped => "The stream has ended.".into(),
EndReason::Removed(Some(LeaveReason::Kicked | LeaveReason::Banned)) => {
format!("{streamer} removed you from the stream.")
}
EndReason::Removed(_) => "You were removed from the stream.".into(),
EndReason::Failed(e) => format!("The stream failed: {e}"),
}
}
fn share_end_text(reason: &EndReason) -> String {
match reason {
EndReason::Failed(e) => format!("Sharing failed: {e}"),
_ => "Sharing ended.".into(),
}
}
impl App {
pub(crate) fn stream_event(&mut self, event: Event) {
match event {
Event::StreamsChanged { session, streams } => {
let view = self.sessions.entry(session as i64).or_default();
// Development switch: watch the first stream that shows up.
let autowatch = std::env::var("TSC_AUTOWATCH").is_ok_and(|v| v == "1")
&& self.watch.is_none()
&& self.current == Some(session as i64);
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer.0))
.map(|s| s.id.clone());
view.streams = streams;
self.refresh_streams();
if autowatch && let Some(id) = first {
self.watch_stream(id);
}
}
Event::StreamState { session, state } => self.share_state(session as i64, state),
Event::StreamViewerRequest { session, viewer, .. } => {
let name = self.sessions.entry(session as i64).or_default().nickname(viewer);
self.set_status(format!("{name} wants to watch your stream"));
}
Event::StreamViewers { session, viewers } => {
if let Some(share) = self.share.as_mut().filter(|s| s.session == session as i64) {
share.viewers = viewers;
self.refresh_streams();
}
}
Event::WatchState { session, stream_id, state } => {
self.watch_state(session as i64, &stream_id, state);
}
// Also flagged on the sink, which the encoder reads.
Event::StreamKeyframeRequest { .. } => {}
_ => {}
}
}
fn share_state(&mut self, session: i64, state: StreamState) {
let Some(share) = self.share.as_mut().filter(|s| s.session == session) else { return };
match state {
StreamState::Starting => {}
StreamState::Live { sink, .. } => {
share.live = true;
share.capture.attach(sink);
self.set_status("You are sharing your screen");
}
StreamState::Ended(reason) => {
let local = reason == EndReason::Local || share.stopping;
self.share = None;
self.share_error = if local { String::new() } else { share_end_text(&reason) };
self.set_status(if local { "You stopped sharing".into() } else { share_end_text(&reason) });
}
}
self.refresh_streams();
}
fn watch_state(&mut self, session: i64, stream_id: &str, state: WatchState) {
let Some(watch) = self
.watch
.as_mut()
.filter(|w| w.session == Some(session) && w.stream_id == stream_id && !w.ended)
else {
return;
};
match state {
WatchState::Requested => {
watch.status = format!("Waiting for {} to let you watch…", watch.streamer);
}
WatchState::Connecting => {
watch.status = format!("Connecting to {}…", watch.streamer);
}
WatchState::Connected => {
watch.connected = true;
if !watch.has_frame {
watch.status = "Waiting for the picture…".into();
}
}
WatchState::Ended(reason) => {
watch.ended = true;
watch.decoder = None;
watch.status = end_text(&reason, &watch.streamer);
}
}
self.refresh_viewer();
self.refresh_streams();
}
/// The streams panel, the share dialog's live part and the toolbar.
pub(crate) fn refresh_streams(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let view = self.view();
let current = self.current;
let mut items: Vec<StreamItem> = Vec::new();
if let Some(view) = view.filter(|v| v.streams_available()) {
for s in &view.streams {
let watching = self.watch.as_ref().is_some_and(|w| {
w.session == current && w.stream_id == s.id && !w.ended
});
items.push(StreamItem {
id: s.id.clone().into(),
name: s.name.clone().into(),
streamer: view.nickname(s.streamer.0).into(),
audio: s.audio,
watching,
own: view.state.own_client == Some(s.streamer.0),
});
}
// Streams that started before we joined are only known by the
// streaming flag: the server does not tell their ids.
let channel = view.state.own_channel;
for c in view.presence.clients.values() {
let announced = view.streams.iter().any(|s| s.streamer.0 == c.id);
if c.streaming == Some(true)
&& Some(c.channel) == channel
&& !announced
&& view.state.own_client != Some(c.id)
{
items.push(StreamItem {
name: c.nickname.clone().into(),
streamer: c.nickname.clone().into(),
..StreamItem::default()
});
}
}
}
if self.demo {
items.push(StreamItem {
id: "demo".into(),
name: "Test pattern".into(),
streamer: "local preview".into(),
audio: false,
watching: self.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended),
own: false,
});
}
bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available()));
bridge.set_streams(model(items));
bridge.set_can_share(video::AVAILABLE);
let share = self.share.as_ref().filter(|s| Some(s.session) == current);
let state = match share {
Some(s) if s.live => "live",
Some(_) => "starting",
None if self.share_busy => "starting",
None => "",
};
bridge.set_share_state(state.into());
bridge.set_share_busy(self.share_busy);
bridge.set_share_error(self.share_error.clone().into());
let viewers: Vec<ViewerItem> = share
.map(|s| {
s.viewers
.iter()
.map(|v| ViewerItem {
client: i32::from(v.client.0),
name: view.map_or_else(String::new, |view| view.nickname(v.client.0)).into(),
state: match v.state {
ViewerState::Requested => "requested",
ViewerState::Connecting => "connecting",
ViewerState::Connected => "connected",
}
.into(),
message: v.message.clone().into(),
})
.collect()
})
.unwrap_or_default();
let requests = viewers.iter().filter(|v| v.state == "requested").count();
bridge.set_share_requests(requests as i32);
bridge.set_share_viewers(model(viewers));
let status = match share {
Some(s) if s.live => s.capture.status(),
Some(s) => format!("Starting the stream of {}…", s.capture.source_name()),
None if self.share_busy => "Starting the capture…".into(),
None => String::new(),
};
bridge.set_share_status(status.into());
}
fn refresh_viewer(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(watch) = &self.watch else {
bridge.set_viewer_open(false);
bridge.set_viewer_has_frame(false);
bridge.set_viewer_frame(slint::Image::default());
return;
};
bridge.set_viewer_open(watch.shown && (watch.session.is_none() || watch.session == self.current));
bridge.set_viewer_title(watch.title.clone().into());
bridge.set_viewer_status(watch.status.clone().into());
bridge.set_viewer_ended(watch.ended);
bridge.set_viewer_has_frame(watch.has_frame);
bridge.set_viewer_volume(self.stream_volume);
let info = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let info = [format!("by {}", watch.streamer), info]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" · ");
bridge.set_viewer_info(info.into());
}
/// Once a second: statistics, a capture that ended, decoder problems.
pub(crate) fn tick_streams(&mut self) {
if let Some(share) = &mut self.share
&& share.live
&& !share.stopping
&& share.capture.ended()
{
share.stopping = true;
self.engine.send(Command::StopStream { session: share.session as u64 });
}
if let Some(watch) = &mut self.watch
&& watch.connected
&& !watch.has_frame
&& let Some(error) = watch.decoder.as_ref().and_then(Decoder::error)
{
watch.status = if error.contains("H264") || error.contains("OpenH264") {
format!("{error}. Enable H.264 in Settings → Streaming to watch this stream.")
} else {
format!("Cannot show the picture: {error}")
};
}
if self.share.is_some() {
self.refresh_streams();
}
if self.watch.is_some() {
self.refresh_viewer();
}
}
// Sharing.
/// Fill the share dialog: sources and the last choices.
pub(crate) fn open_share(&mut self) -> ShareForm {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("TSC_TEST_PATTERN").is_ok_and(|v| v == "1");
let sources = match self.video.sources(test_pattern) {
Ok(sources) => {
if self.share.is_none() {
self.share_error.clear();
}
sources
}
Err(e) => {
self.share_error = e;
Vec::new()
}
};
if let Some(ui) = self.ui.upgrade() {
let items: Vec<SourceItem> = sources
.into_iter()
.map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() })
.collect();
ui.global::<Bridge>().set_share_sources(model(items));
}
self.refresh_streams();
let defaults = &self.settings.share;
let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone());
ShareForm {
source: 0,
name: match nickname {
Some(nick) if !nick.is_empty() => format!("{nick}'s screen").into(),
_ => "Screen".into(),
},
fps_index: defaults.fps_index.min(FPS_CHOICES.len() - 1) as i32,
bitrate_index: defaults.bitrate_index.min(BITRATE_CHOICES.len() - 1) as i32,
audio: defaults.audio,
auto_accept: defaults.auto_accept,
}
}
pub(crate) fn start_share(&mut self, form: ShareForm) {
let Some(session) = self.current else { return };
if self.share_busy || self.share.is_some() {
return;
}
let index = |i: i32, len: usize| usize::try_from(i).unwrap_or(0).min(len - 1);
let defaults = ShareDefaults {
fps_index: index(form.fps_index, FPS_CHOICES.len()),
bitrate_index: index(form.bitrate_index, BITRATE_CHOICES.len()),
audio: form.audio,
auto_accept: form.auto_accept,
};
let request = CaptureRequest {
fps: FPS_CHOICES[defaults.fps_index],
bitrate_kbps: BITRATE_CHOICES[defaults.bitrate_index],
audio: form.audio,
restore_token: self.settings.portal_restore_token.clone(),
};
let bitrate = request.bitrate_kbps;
self.settings.share = defaults;
self.store_settings();
self.share_busy = true;
self.share_error.clear();
self.refresh_streams();
let setup = StreamSetup {
name: form.name.trim().to_owned(),
bitrate,
audio: form.audio,
..StreamSetup::default()
};
let auto_accept = form.auto_accept;
let runtime = self.engine.runtime().clone();
let source = usize::try_from(form.source).unwrap_or(0);
self.video.start_capture(&runtime, source, request, move |result| {
later(move |app| app.capture_ready(session, setup, auto_accept, result));
});
}
/// The capture started (or not): go live.
fn capture_ready(
&mut self,
session: i64,
mut setup: StreamSetup,
auto_accept: bool,
result: Result<Capture, String>,
) {
self.share_busy = false;
match result {
Err(e) => {
self.share_error = format!("Could not start the capture: {e}");
}
Ok(capture) => {
if let Some(token) = capture.restore_token()
&& self.settings.portal_restore_token.as_ref() != Some(&token)
{
self.settings.portal_restore_token = Some(token);
self.store_settings();
}
if setup.audio && !capture.has_audio() {
setup.audio = false;
let reason = capture.audio_error().unwrap_or_default();
self.set_status(format!("Sharing without sound: {reason}"));
}
self.engine.send(Command::StartStream { session: session as u64, setup, auto_accept });
self.share = Some(Share {
session,
capture,
live: false,
viewers: Vec::new(),
stopping: false,
});
}
}
self.refresh_streams();
}
pub(crate) fn stop_share(&mut self) {
if let Some(share) = &mut self.share {
share.stopping = true;
self.engine.send(Command::StopStream { session: share.session as u64 });
}
}
pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) {
if let Some(share) = &self.share {
let session = share.session as u64;
self.engine.send(Command::AcceptViewer { session, viewer, accept });
}
}
pub(crate) fn kick_viewer(&mut self, viewer: u16) {
if let Some(share) = &self.share {
self.engine.send(Command::KickViewer { session: share.session as u64, viewer });
}
}
// Watching.
pub(crate) fn watch_stream(&mut self, stream_id: String) {
if stream_id == "demo" && self.demo {
self.start_demo();
return;
}
let Some(session) = self.current else { return };
let Some(view) = self.sessions.get(&session) else { return };
let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return };
let streamer = view.nickname(info.streamer.0);
let title = if info.name.is_empty() { format!("{streamer}'s stream") } else { info.name.clone() };
self.leave_stream();
self.engine.send(Command::WatchStream { session: session as u64, stream_id: stream_id.clone() });
if self.stream_volume != 100.0 {
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: stream_id.clone(),
volume: self.stream_volume / 100.0,
});
}
let wake = || later(|app| app.show_picture());
let decoder = self.video.watch(&self.engine, session as u64, &stream_id, wake);
self.watch = Some(Watch {
session: Some(session),
stream_id,
title,
status: format!("Asking {streamer} to let you watch…"),
streamer,
connected: false,
ended: false,
has_frame: false,
shown: true,
decoder: Some(decoder),
});
self.refresh_viewer();
self.refresh_streams();
}
/// The local test stream in the viewer (`TSC_DEMO_STREAM`).
pub(crate) fn start_demo(&mut self) {
self.leave_stream();
self.watch = Some(Watch {
session: None,
stream_id: "demo".into(),
title: "Test pattern".into(),
streamer: "local preview".into(),
status: "Starting the local preview…".into(),
connected: true,
ended: false,
has_frame: false,
shown: true,
decoder: None,
});
let runtime = self.engine.runtime().clone();
let wake = || later(|app| app.show_picture());
self.video.demo(&runtime, wake, |result| {
later(move |app| {
let Some(watch) = app.watch.as_mut().filter(|w| w.session.is_none()) else {
return;
};
match result {
Ok(decoder) => watch.decoder = Some(decoder),
Err(e) => watch.status = format!("The preview failed: {e}"),
}
app.refresh_viewer();
});
});
self.refresh_viewer();
self.refresh_streams();
}
/// A decoded picture is waiting.
fn show_picture(&mut self) {
let Some(watch) = &mut self.watch else { return };
let Some(image) = watch.decoder.as_ref().and_then(Decoder::take_picture) else { return };
let first = !watch.has_frame;
watch.has_frame = true;
if first {
watch.status.clear();
}
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_viewer_frame(image);
if first {
self.refresh_viewer();
}
}
}
pub(crate) fn show_viewer(&mut self, shown: bool) {
if let Some(watch) = &mut self.watch {
watch.shown = shown;
}
if !shown {
self.set_fullscreen(false);
}
self.refresh_viewer();
self.refresh_streams();
}
/// Stop watching and close the viewer.
pub(crate) fn leave_stream(&mut self) {
if let Some(watch) = self.watch.take()
&& let Some(session) = watch.session
&& !watch.ended
{
self.engine.send(Command::LeaveStream {
session: session as u64,
stream_id: watch.stream_id,
});
}
self.set_fullscreen(false);
self.refresh_viewer();
self.refresh_streams();
}
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
self.stream_volume = percent.round().clamp(0.0, 200.0);
if let Some(watch) = &self.watch
&& let Some(session) = watch.session
{
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: watch.stream_id.clone(),
volume: self.stream_volume / 100.0,
});
}
}
pub(crate) fn toggle_fullscreen(&mut self) {
let Some(ui) = self.ui.upgrade() else { return };
let full = !ui.global::<Bridge>().get_viewer_fullscreen();
self.set_fullscreen(full);
}
fn set_fullscreen(&self, full: bool) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
if bridge.get_viewer_fullscreen() == full {
return;
}
bridge.set_viewer_fullscreen(full);
ui.window().set_fullscreen(full);
}
}
+497
View File
@@ -0,0 +1,497 @@
//! Video of streams for the UI: capture and encoding when we share, decoding
//! into Slint images when we watch, and the optional OpenH264 library.
//!
//! Needs the `media` feature (tsc-core's media pipeline). Without it the
//! same API exists and reports that video is not available; stream audio
//! still plays (the engine does that).
pub(crate) use imp::*;
/// Human-readable text for a capture source size.
fn size_text(width: u32, height: u32) -> String {
if width == 0 || height == 0 { String::new() } else { format!("{width}×{height}") }
}
#[cfg(feature = "media")]
mod imp {
use std::path::{Path, PathBuf};
use std::sync::Arc;
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
use tokio::runtime::Handle;
use tsc_core::media::tsc_media::capture::SourceId;
use tsc_core::media::tsc_media::codec::h264::{self, OpenH264};
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};
use tracing::warn;
use super::size_text;
/// Whether this build can share and decode video.
pub const AVAILABLE: bool = true;
type Picture = SharedPixelBuffer<Rgba8Pixel>;
/// OpenH264 state.
enum H264 {
Off,
/// Enabled, but not downloaded yet (or the file is not a known build).
Missing(String),
Downloading,
Loaded(PathBuf),
}
pub(crate) struct Video {
codecs: Arc<Codecs>,
openh264_dir: PathBuf,
h264: H264,
/// Sources of the share dialog, by index.
sources: Vec<(SourceId, String)>,
}
impl Video {
pub fn new(data_dir: &Path, openh264: bool) -> Self {
let mut video = Self {
codecs: Arc::new(Codecs::new()),
openh264_dir: data_dir.join("openh264"),
h264: H264::Off,
sources: Vec::new(),
};
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) {
match &self.h264 {
H264::Off => (false, String::new()),
H264::Missing(reason) => (false, reason.clone()),
H264::Downloading => (false, "Downloading OpenH264 from Cisco…".into()),
H264::Loaded(path) => {
(true, format!("OpenH264 {} is loaded ({}).", h264::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) {
if !enabled {
self.h264 = H264::Off;
self.codecs = Arc::new(Codecs::new());
return;
}
if matches!(self.h264, H264::Loaded(_) | H264::Downloading) {
return;
}
match OpenH264::find_in(&self.openh264_dir) {
Ok(library) => self.loaded(library),
Err(_) => {
self.h264 = H264::Missing("OpenH264 is not downloaded yet.".into());
}
}
}
fn loaded(&mut self, library: OpenH264) {
self.h264 = H264::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,
) {
if matches!(self.h264, H264::Downloading | H264::Loaded(_)) {
return;
}
self.h264 = H264::Downloading;
let dir = self.openh264_dir.clone();
runtime.spawn(async move {
let result = h264::download_openh264(&dir).await.map_err(|e| e.to_string());
done(H264Download(result));
});
}
pub fn downloaded(&mut self, download: H264Download, enabled: bool) {
match download.0 {
Ok(library) if enabled => self.loaded(library),
Ok(_) => self.h264 = H264::Off,
Err(e) => {
warn!("OpenH264 download failed: {e}");
self.h264 = H264::Missing(format!("Download failed: {e}"));
}
}
}
/// Screens and windows to share, as (name, detail); the test pattern
/// too when asked for.
pub fn sources(&mut self, test_pattern: bool) -> Result<Vec<(String, String)>, String> {
let mut error = None;
let mut sources = match media::screen_sources() {
Ok(list) => list,
Err(e) => {
error = Some(e.to_string());
Vec::new()
}
};
if test_pattern {
sources.push(media::test_pattern_source());
}
if sources.is_empty() {
return Err(error.unwrap_or_else(|| "Nothing to share was found.".into()));
}
self.sources = sources.iter().map(|s| (s.id.clone(), s.name.clone())).collect();
Ok(sources
.iter()
.map(|s| {
let name = match s.id {
SourceId::Portal => "Choose via system dialog".to_owned(),
_ => s.name.clone(),
};
let detail = match (&s.id, s.primary) {
(SourceId::Monitor(_), true) => {
format!("{} · primary", size_text(s.width, s.height))
}
(SourceId::Window(_), _) => {
format!("window {}", size_text(s.width, s.height)).trim().to_owned()
}
_ => size_text(s.width, s.height),
};
(name, detail)
})
.collect())
}
/// Start capturing source `index` of [`Video::sources`]; `done` runs
/// on the runtime (the portal may wait for the user first).
pub fn start_capture(
&self,
runtime: &Handle,
index: usize,
options: CaptureRequest,
done: impl FnOnce(Result<Capture, String>) + Send + 'static,
) {
let Some((source, name)) = self.sources.get(index).cloned() else {
done(Err("Pick something to share.".into()));
return;
};
let peer = self.peer_config(PeerConfig::default());
let Some(codec) = stream_codec(&self.codecs, &peer) else {
done(Err("No video encoder is available.".into()));
return;
};
let codecs = self.codecs.clone();
let config = StreamerConfig {
source,
fps: options.fps,
bitrate_kbps: options.bitrate_kbps,
codec,
audio: options.audio,
restore_token: options.restore_token,
..StreamerConfig::default()
};
runtime.spawn(async move {
let result = Streamer::start(&codecs, config).await;
done(result.map(|streamer| Capture { streamer, name }).map_err(|e| e.to_string()));
});
}
/// Decode stream `stream_id` of `session`; `wake` is called (on the
/// decoder thread) when a picture is ready and none is waiting.
pub fn watch(
&self,
engine: &Engine,
session: u64,
stream_id: &str,
wake: impl Fn() + Send + Sync + 'static,
) -> Decoder {
let pictures = Arc::new(Latest::new());
let on_frame = deliver(pictures.clone(), wake);
let viewer = Viewer::start(engine, session, stream_id, self.codecs.clone(), on_frame);
Decoder { source: Source::Viewer(viewer), pictures }
}
/// The test pattern through the encoder and decoder, without a
/// server (`TSC_DEMO_STREAM`).
pub fn demo(
&self,
runtime: &Handle,
wake: impl Fn() + Send + Sync + 'static,
done: impl FnOnce(Result<Decoder, String>) + Send + 'static,
) {
let pictures = Arc::new(Latest::new());
let on_frame = deliver(pictures.clone(), wake);
let codecs = self.codecs.clone();
let config = StreamerConfig { source: SourceId::Synthetic, ..StreamerConfig::default() };
runtime.spawn(async move {
let result = LocalPreview::start(codecs, config, on_frame).await;
done(
result
.map(|preview| Decoder { source: Source::Preview(preview), pictures })
.map_err(|e| e.to_string()),
);
});
}
}
/// Converts decoded frames into Slint pixel buffers, keeping the newest.
fn deliver(
pictures: Arc<Latest<Picture>>,
wake: impl Fn() + Send + Sync + 'static,
) -> impl FnMut(VideoFrame) + Send + 'static {
move |frame: VideoFrame| {
let mut buffer = Picture::new(frame.width, frame.height);
let stride = frame.width as usize * 4;
if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) {
warn!("cannot show a picture: {e}");
return;
}
if pictures.put(buffer) {
wake();
}
}
}
/// The result of [`Video::download_h264`].
pub(crate) struct H264Download(Result<OpenH264, String>);
/// Share settings from the dialog.
pub(crate) struct CaptureRequest {
pub fps: u32,
pub bitrate_kbps: u32,
pub audio: bool,
pub restore_token: Option<String>,
}
/// A running capture for our stream. Stops when dropped.
pub(crate) struct Capture {
streamer: Streamer,
name: String,
}
impl Capture {
/// Encode into the live stream.
pub fn attach(&self, sink: StreamSink) {
self.streamer.attach(Arc::new(sink));
}
pub fn source_name(&self) -> &str {
&self.name
}
pub fn has_audio(&self) -> bool {
self.streamer.has_audio()
}
pub fn audio_error(&self) -> Option<String> {
self.streamer.audio_error().map(str::to_owned)
}
/// The portal's token for this choice, to keep.
pub fn restore_token(&self) -> Option<String> {
self.streamer.restore_token().map(str::to_owned)
}
/// The capture stopped by itself (e.g. sharing ended in the desktop).
pub fn ended(&self) -> bool {
self.streamer.stats().capture_ended
}
/// One line about what is sent.
pub fn status(&self) -> String {
let stats = self.streamer.stats();
let mut text = format!("{} · {}", self.name, size_text(stats.width, stats.height));
text.push_str(&format!(" · {} frames sent", stats.video_frames));
if self.streamer.has_audio() {
text.push_str(" · with sound");
}
if let Some(e) = stats.error {
text.push_str(&format!(" · encoder: {e}"));
}
text
}
}
enum Source {
Viewer(Viewer),
Preview(LocalPreview),
}
/// Decodes a watched stream into pictures. Stops when dropped.
pub(crate) struct Decoder {
source: Source,
pictures: Arc<Latest<Picture>>,
}
impl Decoder {
/// The newest picture since the last call.
pub fn take_picture(&self) -> Option<Image> {
self.pictures.take().map(Image::from_rgba8)
}
/// One line about the video: codec, size, problems.
pub fn info(&self) -> String {
let stats = match &self.source {
Source::Viewer(v) => v.stats(),
Source::Preview(p) => p.stats(),
};
let mut parts = Vec::new();
if let Some(codec) = stats.codec {
parts.push(codec.to_string());
}
if stats.width > 0 {
parts.push(size_text(stats.width, stats.height));
}
if let Some(e) = stats.error {
parts.push(e);
}
parts.join(" · ")
}
/// Whether pictures could never come (no decoder for the codec).
pub fn error(&self) -> Option<String> {
let stats = match &self.source {
Source::Viewer(v) => v.stats(),
Source::Preview(p) => p.stats(),
};
stats.error.filter(|_| stats.decoded == 0)
}
}
}
#[cfg(not(feature = "media"))]
mod imp {
use std::path::Path;
use slint::Image;
use tokio::runtime::Handle;
use tsc_core::stream::PeerConfig;
use tsc_core::{Engine, StreamSink};
pub const AVAILABLE: bool = false;
const UNAVAILABLE: &str = "Video is not available in this build.";
pub(crate) struct Video;
impl Video {
pub fn new(_data_dir: &Path, _openh264: bool) -> Self {
Self
}
pub fn peer_config(&self, base: PeerConfig) -> PeerConfig {
base
}
pub fn h264_status(&self) -> (bool, String) {
(false, UNAVAILABLE.into())
}
pub fn set_h264(&mut self, _enabled: bool) {}
pub fn download_h264(&mut self, _runtime: &Handle, _done: impl FnOnce(H264Download)) {}
pub fn downloaded(&mut self, _download: H264Download, _enabled: bool) {}
pub fn sources(&mut self, _test_pattern: bool) -> Result<Vec<(String, String)>, String> {
Err(UNAVAILABLE.into())
}
pub fn start_capture(
&self,
_runtime: &Handle,
_index: usize,
_options: CaptureRequest,
done: impl FnOnce(Result<Capture, String>),
) {
done(Err(UNAVAILABLE.into()));
}
pub fn watch(
&self,
_engine: &Engine,
_session: u64,
_stream_id: &str,
_wake: impl Fn() + Send + Sync + 'static,
) -> Decoder {
Decoder
}
pub fn demo(
&self,
_runtime: &Handle,
_wake: impl Fn() + Send + Sync + 'static,
done: impl FnOnce(Result<Decoder, String>),
) {
done(Err(UNAVAILABLE.into()));
}
}
pub(crate) struct H264Download;
pub(crate) struct CaptureRequest {
pub fps: u32,
pub bitrate_kbps: u32,
pub audio: bool,
pub restore_token: Option<String>,
}
pub(crate) enum Capture {}
impl Capture {
pub fn attach(&self, _sink: StreamSink) {
match *self {}
}
pub fn source_name(&self) -> &str {
match *self {}
}
pub fn has_audio(&self) -> bool {
match *self {}
}
pub fn audio_error(&self) -> Option<String> {
match *self {}
}
pub fn restore_token(&self) -> Option<String> {
match *self {}
}
pub fn ended(&self) -> bool {
match *self {}
}
pub fn status(&self) -> String {
match *self {}
}
}
pub(crate) struct Decoder;
impl Decoder {
pub fn take_picture(&self) -> Option<Image> {
None
}
pub fn info(&self) -> String {
String::new()
}
pub fn error(&self) -> Option<String> {
Some(UNAVAILABLE.into())
}
}
}
+1248 -101
View File
File diff suppressed because it is too large. Load diff