From c69c3caf6b5ea194d426e0ba5348a2814dc2c783 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 22:00:01 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20one=20client?= =?UTF-8?q?=20media=20owner,=20datagram=20v2=20and=20typed=20calls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voice, shares and the mic test live in one client Media owner guarded by the link epoch, so a stale join never installs after a reconnect and a blip keeps the capture source. Datagrams become a Packet enum with fixed little endian headers, derived fragment layout and bounds checked decode; the server peeks three bytes to route video. Calls start moving to typed Call structs whose reply type and gate come from the type, beginning with the user domain. Share throughput unchanged at 59.4 fps. --- crates/client/Cargo.toml | 1 + crates/client/src/gui.rs | 10 +- crates/client/src/gui/camera_view.rs | 7 +- crates/client/src/gui/chat.rs | 27 +- crates/client/src/gui/settings_page.rs | 2 +- crates/client/src/gui/share_view.rs | 23 +- crates/client/src/gui/voice_settings.rs | 6 +- crates/client/src/net/datagram.rs | 31 +- crates/client/src/net/events.rs | 10 +- crates/client/src/net/link.rs | 120 ++-- crates/client/src/net/media.rs | 778 ++++++++++++++++++++++++ crates/client/src/net/mod.rs | 352 +++++------ crates/client/src/net/share.rs | 338 ---------- crates/client/src/net/voice.rs | 87 --- crates/client/src/share/reassembly.rs | 71 ++- crates/client/src/share/session.rs | 124 ++-- crates/client/src/voice/engine.rs | 30 +- crates/client/src/voice/mod.rs | 14 +- crates/common/Cargo.toml | 2 + crates/common/src/call.rs | 109 ++++ crates/common/src/constant.rs | 1 + crates/common/src/datagram.rs | 440 ++++++++------ crates/common/src/lib.rs | 1 + crates/common/src/open.rs | 2 +- crates/common/src/request.rs | 32 +- crates/common/src/share.rs | 12 - crates/common/src/transport.rs | 2 +- crates/server/src/attachment.rs | 4 +- crates/server/src/call/mod.rs | 123 ++++ crates/server/src/call/user.rs | 147 +++++ crates/server/src/lib.rs | 1 + crates/server/src/network.rs | 23 +- crates/server/src/request.rs | 352 ++++------- crates/server/src/rooms.rs | 81 ++- 34 files changed, 1985 insertions(+), 1378 deletions(-) create mode 100644 crates/client/src/net/media.rs delete mode 100644 crates/client/src/net/share.rs delete mode 100644 crates/client/src/net/voice.rs create mode 100644 crates/common/src/call.rs create mode 100644 crates/server/src/call/mod.rs create mode 100644 crates/server/src/call/user.rs diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 3b61f4f..eb3df60 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -25,6 +25,7 @@ ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d9 ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ureq = "3.5.2" bytes = "1.12.2" +uuid = "1.29.3" tracing = "0.1.44" tracing-subscriber = "0.3.23" jiff = "1.0.2" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index b18d539..5bffcd5 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -602,9 +602,6 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) -> Self { - network.set_voice_settings(settings.voice.clone()); - network.set_share_settings(settings.share.clone()); - cx.spawn(async move |this, cx| { while let Some(event) = network_event_receiver.recv().await { let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else { @@ -1141,12 +1138,13 @@ impl Yumush { self.load_server_settings(window, cx); if self.user.is_some() { self.reload(window, cx); - self.rejoin_voice(window, cx); } else if let Some(active) = self.accounts.active.clone() { self.switch_account(active, window, cx); } } NetworkEvent::Disconnected(error) => self.connection.lost(&error), + NetworkEvent::VoiceRejoined => self.refresh_voice(cx), + NetworkEvent::VoiceEnded => self.chat.set_voice_off(), NetworkEvent::SessionLost => { if let Some(user) = &self.user { self.accounts.forget(&user.id); @@ -1208,7 +1206,7 @@ impl Yumush { match event { Event::MessageCreated(message) => { if self.should_notify(message, active) { - self.network.play_notification(); + self.network.play_notification(&self.settings.voice); } self.count_message(message, active, cx); if message.call == Some(CallLog::Declined) @@ -1240,6 +1238,8 @@ impl Yumush { self.deferred.push(NetworkEvent::Connected); } NetworkEvent::Disconnected(error) => self.connection.lost(&error), + NetworkEvent::VoiceRejoined => self.refresh_voice(cx), + NetworkEvent::VoiceEnded => self.chat.set_voice_off(), NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost), NetworkEvent::Pushed(event) => match *event { Event::MemberLeft { .. } diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index 8cdcab8..fda324d 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -59,9 +59,11 @@ impl Yumush { ); let network = self.network.clone(); let user_id = user_id.clone(); + let volume = self.settings.share.volume; + let choice = self.settings.voice.choice.clone(); spawn_warn(cx, "camera watch", async move { network - .watch_share(&user_id, Kind::Camera, CAMERA_TILE) + .watch_share(&user_id, Kind::Camera, CAMERA_TILE, volume, choice) .await }); changed = true; @@ -116,11 +118,12 @@ impl Yumush { pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); let on = network.camera_on(); + let settings = self.settings.share.clone(); cx.spawn_in(window, async move |this, cx| { if on { let _ = network.stop_camera().await; - } else if let Err(error) = network.start_camera().await { + } else if let Err(error) = network.start_camera(&settings).await { notify_error(&this, cx, error); } let _ = this.update(cx, |_, cx| cx.notify()); diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 6ebc724..b1e0c73 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1598,7 +1598,7 @@ impl Yumush { self.chat.focus(window, cx); self.load_members(window, cx); self.load_pins(window, cx); - self.load_voice(window, cx); + self.load_voice(community_id.clone(), cx); self.load_shares(community_id, cx); self.load_messages(None, window, cx); cx.notify(); @@ -1626,7 +1626,7 @@ impl Yumush { self.load_members(window, cx); self.chat.messages.clear(); self.load_messages(None, window, cx); - self.load_voice(window, cx); + self.load_voice(community_id.clone(), cx); self.load_shares(community_id, cx); } } @@ -1937,16 +1937,11 @@ impl Yumush { .detach(); } - fn load_voice(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { - return; - }; + fn load_voice(&self, community_id: String, cx: &mut Context) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - let Some(participants) = - ok_or_notify(network.voice_participants(&community_id).await, &this, cx) - else { + cx.spawn(async move |this, cx| { + let Ok(participants) = network.voice_participants(&community_id).await else { return; }; @@ -1986,13 +1981,14 @@ impl Yumush { cx: &mut Context, ) { let network = self.network.clone(); + let voice_settings = self.settings.voice.clone(); cx.spawn_in(window, async move |this, cx| { if was_in { let _ = network.leave_voice().await; } - match network.join_voice(&community_id).await { + match network.join_voice(&community_id, &voice_settings).await { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { @@ -2035,13 +2031,12 @@ impl Yumush { .detach(); } - pub(super) fn rejoin_voice(&mut self, window: &mut Window, cx: &mut Context) { + pub(super) fn refresh_voice(&mut self, cx: &mut Context) { let Some(community_id) = self.chat.voice_community().map(str::to_string) else { return; }; - let flags = self.chat.voice_flags().unwrap_or((false, false)); - self.chat.set_voice_off(); - self.join_voice(community_id, flags, false, window, cx); + self.load_voice(community_id.clone(), cx); + self.load_shares(community_id, cx); } pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context) { @@ -2400,7 +2395,7 @@ impl Yumush { let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { Some((community_id, _)) => { if yumush.ring_allowed(&community_id) { - yumush.network.play_ring(); + yumush.network.play_ring(&yumush.settings.voice); } true } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 2fb53f2..81117fc 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -254,7 +254,7 @@ impl Yumush { pub(super) fn commit_settings(&mut self, cx: &mut Context) { settings::save(&self.settings); - self.network.set_voice_settings(self.settings.voice.clone()); + self.network.set_voice_settings(&self.settings.voice); cx.notify(); } } diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 0cb72f4..ebf4217 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -106,11 +106,12 @@ impl Yumush { pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); let sharing = network.sharing(); + let settings = self.settings.share.clone(); cx.spawn_in(window, async move |this, cx| { if sharing { let _ = network.stop_share().await; - } else if let Err(error) = network.start_share().await { + } else if let Err(error) = network.start_share(&settings).await { notify_error(&this, cx, error); } let _ = this.update(cx, |_, cx| cx.notify()); @@ -119,15 +120,16 @@ impl Yumush { } fn update_share(&mut self, cx: &mut Context, change: impl FnOnce(&mut ShareSettings)) { + let before = self.settings.share.clone(); change(&mut self.settings.share); settings::save(&self.settings); - if self.network.set_share_settings(self.settings.share.clone()) { + self.network.set_share_settings(&self.settings.share); + if self.network.sharing() && before.encoding_differs(&self.settings.share) { let network = self.network.clone(); - spawn_warn( - cx, - "share update", - async move { network.update_share().await }, - ); + let settings = self.settings.share.clone(); + spawn_warn(cx, "share update", async move { + network.update_share(&settings).await + }); } cx.notify(); } @@ -259,11 +261,16 @@ impl Yumush { let network = self.network.clone(); let watch = self.settings.share.watch; + let volume = self.settings.share.volume; + let choice = self.settings.voice.choice.clone(); if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) { network.set_watch_quality(&user_id, kind, watch); } else { cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.watch_share(&user_id, kind, watch).await { + if let Err(error) = network + .watch_share(&user_id, kind, watch, volume, choice) + .await + { let _ = this.update(cx, |yumush, cx| { if yumush.is_watching(&user_id, kind) { yumush.close_viewer(cx); diff --git a/crates/client/src/gui/voice_settings.rs b/crates/client/src/gui/voice_settings.rs index f3b0243..dc8b9e3 100644 --- a/crates/client/src/gui/voice_settings.rs +++ b/crates/client/src/gui/voice_settings.rs @@ -289,7 +289,9 @@ impl Yumush { ) .child( test_button("speaker_test_button", palette, false, move |_, cx| { - speaker.update(cx, |yumush, _| yumush.network.play_chime()); + speaker.update(cx, |yumush, _| { + yumush.network.play_chime(&yumush.settings.voice) + }); }) .child(Icon::new(IconName::Volume2).w(px(14.)).h(px(14.))) .child("Play sound"), @@ -455,7 +457,7 @@ impl Yumush { match self.voice.mic_test { MicTest::On => self.stop_mic_test(), MicTest::Off => { - self.network.start_mic_test(); + self.network.start_mic_test(&self.settings.voice); self.voice.mic_test = MicTest::On; self.start_level_poll(cx); } diff --git a/crates/client/src/net/datagram.rs b/crates/client/src/net/datagram.rs index da22553..54adcc9 100644 --- a/crates/client/src/net/datagram.rs +++ b/crates/client/src/net/datagram.rs @@ -1,34 +1,23 @@ -use common::{ - datagram::{Datagram, decode_relay}, - share::Kind, -}; +use common::datagram::{Packet, split}; use super::*; -pub(super) async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) { +pub(super) async fn datagram_receive_loop(connection: quinn::Connection, media: Arc) { let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") .ok() .and_then(|value| value.parse().ok()) .unwrap_or(0); let mut received: u64 = 0; while let Ok(datagram) = connection.read_datagram().await { - if let Some(voice) = shared.voice.lock().unwrap().as_ref() { - voice.receive(&datagram); - } - if let Some((user_id, packet)) = decode_relay(&datagram) { - if let Datagram::Video(_) = packet { - received += 1; - if received * 37 % 100 < loss { - continue; - } - } - let kind = match &packet { - Datagram::Video(fragment) => fragment.kind, - _ => Kind::Screen, - }; - if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) { - watching.receive(packet); + let Some((from, packet)) = split(&datagram) else { + continue; + }; + if matches!(packet, Packet::Video { .. }) { + received += 1; + if received * 37 % 100 < loss { + continue; } } + media.receive(&datagram, from, packet); } } diff --git a/crates/client/src/net/events.rs b/crates/client/src/net/events.rs index a8cd4b6..ef2c6ec 100644 --- a/crates/client/src/net/events.rs +++ b/crates/client/src/net/events.rs @@ -9,7 +9,7 @@ use super::*; pub(super) async fn event_receive_loop( connection: quinn::Connection, event_sender: mpsc::Sender, - share: SharedShare, + media: Arc, ) { let Ok(mut receive_stream) = connection.accept_uni().await else { return; @@ -18,7 +18,7 @@ pub(super) async fn event_receive_loop( while let Ok(down) = frame::read::(&mut receive_stream, DOWN_MAX).await { match down { Down::Event(event) => { - share.lock().unwrap().event(&event); + media.pushed(&event); if event_sender .send(NetworkEvent::Pushed(event)) .await @@ -27,7 +27,11 @@ pub(super) async fn event_receive_loop( return; } } - Down::Media(media) => share.lock().unwrap().media(&media), + Down::Media(down) => { + if media.down(&down) && event_sender.send(NetworkEvent::VoiceEnded).await.is_err() { + return; + } + } } } } diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index 207789e..440ced0 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -1,12 +1,13 @@ use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration}; use common::{ + call::{Call, Legacy}, constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::Error, frame::{self, DOWN_MAX, Sending, UP_MAX}, model::{Attachment, User}, open::{Blob, Open, Upload}, - request::Request, + request::LegacyRequest, response::Response, session::{Hello, Welcome}, transport::{Close, alpn, transport}, @@ -27,40 +28,31 @@ use rustls_platform_verifier as _; use tokio::sync::{mpsc, oneshot}; use tracing::{info, warn}; -use crate::{ - ClientConfig, - voice::{self}, -}; +use crate::ClientConfig; -use super::{ - datagram::datagram_receive_loop, - events::event_receive_loop, - share::{start_share, update_share}, - *, -}; +use super::{datagram::datagram_receive_loop, events::event_receive_loop, *}; const CHANNEL_SIZE: usize = 32; const BACKOFF_BASE_MILLIS: u64 = 250; const BACKOFF_CAP_MILLIS: u64 = 8_000; -const SHARE_TICK: Duration = Duration::from_secs(1); - pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver) { let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); - let shared = Shared::default(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("network runtime"); + let shared = Shared { + media: Media::new(runtime.handle().clone()), + fetches: Arc::default(), + }; std::thread::Builder::new() .name("network".to_string()) .spawn({ let shared = shared.clone(); - move || { - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("network runtime") - .block_on(actor(client_config, command_receiver, event_sender, shared)); - } + move || runtime.block_on(actor(client_config, command_receiver, event_sender, shared)) }) .expect("network thread"); @@ -261,16 +253,23 @@ fn config() -> Result { Ok(client_config) } -pub(super) async fn send( +pub(super) async fn call( connection: &quinn::Connection, - request: &Request, -) -> Result { + call: C, +) -> Result { let (send_stream, mut receive_stream) = connection.open_bi().await?; let mut send_stream = Sending::new(send_stream); - frame::write(&mut send_stream, &Open::Call(request.clone()), UP_MAX).await?; + frame::write(&mut send_stream, &Open::Call(call.into_request()), UP_MAX).await?; send_stream.finish()?; - Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) + Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) +} + +pub(super) async fn send( + connection: &quinn::Connection, + request: &LegacyRequest, +) -> Result { + call(connection, Legacy(request.clone())).await } async fn hello(connection: &quinn::Connection, token: Option) -> Result { @@ -286,7 +285,10 @@ async fn hello(connection: &quinn::Connection, token: Option) -> Result< Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) } -pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> { +pub(super) async fn done( + connection: &quinn::Connection, + request: LegacyRequest, +) -> Result<(), Fail> { match send(connection, &request).await? { Response::Done => Ok(()), _ => Err(Fail::Protocol), @@ -471,6 +473,7 @@ async fn actor( let _ = reply.send(Err(Fail::Server(error))); } None => { + shared.media.reset(); if event_sender.send(NetworkEvent::SessionLost).await.is_err() { return; } @@ -496,6 +499,7 @@ async fn actor( attempt = 0; info!("connected"); + shared.media.ready(connection.clone(), event_sender.clone()); if event_sender.send(NetworkEvent::Connected).await.is_err() { return; } @@ -506,60 +510,24 @@ async fn actor( tokio::spawn(event_receive_loop( connection.clone(), event_sender.clone(), - shared.share.clone(), + shared.media.clone(), + )); + tokio::spawn(datagram_receive_loop( + connection.clone(), + shared.media.clone(), )); - tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone())); - let mut ticker = tokio::time::interval(SHARE_TICK); loop { tokio::select! { command = command_receiver.recv() => match command { - Some(Command::Request { request, reply }) => match &request { - Request::JoinVoice { .. } => { - let shared = shared.clone(); - let settings = shared.voice_settings.lock().unwrap().clone(); - let connection = connection.clone(); - - answer(reply, async move { - let response = send(&connection, &request).await; - if let Ok(Response::Voice(_)) = &response { - shared.mic_test.lock().unwrap().take(); - *shared.voice.lock().unwrap() = - Some(voice::start(Some(connection), &settings)); - } - response - }); - } - Request::LeaveVoice => { - hang_up(&shared); - - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } - _ => { - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } - }, + Some(Command::Call(run)) => run(connection.clone()), Some(Command::SignIn { token: next, reply }) => { token = next; pending = Some(reply); - hang_up(&shared); + shared.media.reset(); connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); break; } - Some(Command::StartShare { kind, settings, reply }) => { - let connection = connection.clone(); - let share = shared.share.clone(); - - answer(reply, async move { start_share(&connection, &share, kind, &settings).await }); - } - Some(Command::UpdateShare { settings, reply }) => { - let connection = connection.clone(); - let share = shared.share.clone(); - - answer(reply, async move { update_share(&connection, &share, &settings).await }); - } Some(Command::Upload { community_id, path, maximum, reply }) => { let connection = connection.clone(); @@ -583,19 +551,9 @@ async fn actor( None => break 'session, }, - _ = ticker.tick() => { - let requests = shared.share.lock().unwrap().ticks(); - for request in requests { - let connection = connection.clone(); - tokio::spawn(async move { - let _ = send(&connection, &request).await; - }); - } - } - error = connection.closed() => { warn!("disconnected: {error}"); - hang_up(&shared); + shared.media.lost(); let event = LinkError::from(error); let banned = event == LinkError::Closed(Close::Banned); diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs new file mode 100644 index 0000000..d2552fd --- /dev/null +++ b/crates/client/src/net/media.rs @@ -0,0 +1,778 @@ +use std::{ + collections::HashMap, + sync::{Arc, Mutex, MutexGuard}, + time::Duration, +}; + +use bytes::Bytes; +use common::{ + datagram::{Packet, RELAY_PREFIX}, + event::{Event, Media as Down}, + request::LegacyRequest, + response::Response, + share::{Fps, Kind, Quality, Resolution, Source}, +}; +use quinn::Connection; +use tokio::{runtime::Handle, sync::mpsc}; +use tracing::warn; +use uuid::Uuid; + +use crate::{ + settings::{ShareSettings, VoiceSettings}, + share::{ + audio::AudioApp, + audio_capture, + encode::capabilities, + session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, + }, + voice::{self, Voice, VoiceSample, audio::Choice}, +}; + +use super::{ + link::{done, send}, + *, +}; + +const TICK: Duration = Duration::from_secs(1); +const WAIT_STEP: Duration = Duration::from_millis(100); +const WAIT_STEPS: u32 = 50; + +const CAMERA_TOP: Quality = Quality { + resolution: Resolution::P2160, + fps: Fps::F60, +}; + +#[derive(Clone)] +struct Want { + community_id: String, + settings: VoiceSettings, + muted: bool, + deafened: bool, +} + +struct Inner { + epoch: u64, + connection: Option, + want_voice: Option, + voice: Option, + joining: u32, + mic_test: Option, + sharing: HashMap, + watching: HashMap<(String, Kind), Watching>, +} + +impl Inner { + fn current(&self, epoch: u64) -> bool { + self.connection.is_some() && self.epoch == epoch + } + + fn drop_calls(&mut self) { + self.voice = None; + self.sharing.clear(); + } + + fn install_voice(&mut self, mut voice: Voice, want: Want) { + voice.apply(&want.settings); + voice.set_muted(want.muted); + voice.set_deafened(want.deafened); + self.mic_test = None; + self.voice = Some(voice); + self.want_voice = Some(want); + } +} + +pub(super) struct Media { + handle: Handle, + inner: Mutex, +} + +impl Media { + pub(super) fn new(handle: Handle) -> Arc { + let media = Arc::new(Media { + handle: handle.clone(), + inner: Mutex::new(Inner { + epoch: 0, + connection: None, + want_voice: None, + voice: None, + joining: 0, + mic_test: None, + sharing: HashMap::new(), + watching: HashMap::new(), + }), + }); + handle.spawn(tick_loop(media.clone())); + + media + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner.lock().unwrap() + } + + fn current(&self) -> Result<(Connection, u64), Fail> { + let inner = self.lock(); + let connection = inner.connection.clone().ok_or(Fail::Offline)?; + + Ok((connection, inner.epoch)) + } + + async fn current_wait(&self) -> Result<(Connection, u64), Fail> { + for _ in 0..WAIT_STEPS { + if let Ok(current) = self.current() { + return Ok(current); + } + tokio::time::sleep(WAIT_STEP).await; + } + + self.current() + } + + async fn run( + &self, + work: impl Future> + Send + 'static, + ) -> Result { + self.handle.spawn(work).await.map_err(|_| Fail::Offline)? + } + + pub(super) fn ready( + self: &Arc, + connection: Connection, + events: mpsc::Sender, + ) { + let (epoch, want) = { + let mut inner = self.lock(); + inner.epoch += 1; + inner.connection = Some(connection.clone()); + (inner.epoch, inner.want_voice.clone()) + }; + if let Some(want) = want { + tokio::spawn(self.clone().rejoin(connection, epoch, want, events)); + } + } + + pub(super) fn lost(&self) { + let mut inner = self.lock(); + inner.connection = None; + inner.drop_calls(); + } + + pub(super) fn reset(&self) { + let mut inner = self.lock(); + inner.connection = None; + inner.drop_calls(); + inner.want_voice = None; + inner.watching.clear(); + } + + async fn rejoin( + self: Arc, + connection: Connection, + epoch: u64, + want: Want, + events: mpsc::Sender, + ) { + let joined = join(&connection, &want.community_id).await; + let next = { + let mut inner = self.lock(); + if !inner.current(epoch) { + return; + } + let ours = inner + .want_voice + .as_ref() + .is_some_and(|wanted| wanted.community_id == want.community_id) + && inner.voice.is_none(); + match joined { + Ok(_) if ours => Rejoin::Install, + Ok(_) => { + if inner.want_voice.is_none() && inner.joining == 0 { + tokio::spawn(send_quietly(connection.clone(), LegacyRequest::LeaveVoice)); + } + Rejoin::Skip + } + Err(error) if ours => { + warn!("voice rejoin failed: {error}"); + inner.want_voice = None; + inner.watching.clear(); + Rejoin::Ended + } + Err(_) => Rejoin::Skip, + } + }; + + let watches = match next { + Rejoin::Skip => return, + Rejoin::Ended => None, + Rejoin::Install => { + let voice = voice::start(Some(connection.clone()), &want.settings); + let mut inner = self.lock(); + let wanted = inner.want_voice.clone(); + match wanted { + Some(wanted) + if inner.current(epoch) + && wanted.community_id == want.community_id + && inner.voice.is_none() => + { + inner.install_voice(voice, wanted); + Some(inner.watch_requests()) + } + _ => return, + } + } + }; + + let event = match watches { + Some(requests) => { + for (key, request) in requests { + let media = self.clone(); + let connection = connection.clone(); + tokio::spawn(async move { + if send(&connection, &request).await.is_err() { + media.lock().watching.remove(&key); + } + }); + } + NetworkEvent::VoiceRejoined + } + None => NetworkEvent::VoiceEnded, + }; + let _ = events.send(event).await; + } + + pub(super) fn pushed(&self, event: &Event) { + if let Event::ShareStopped { user_id, kind, .. } = event { + self.lock().watching.remove(&(user_id.clone(), *kind)); + } + } + + pub(super) fn down(&self, media: &Down) -> bool { + let mut inner = self.lock(); + match media { + Down::Layers { kind, layers } => { + if let Some(sharing) = inner.sharing.get_mut(kind) { + sharing.set_layers(layers); + } + } + Down::Keyframe { kind, layer } => { + if let Some(sharing) = inner.sharing.get(kind) { + sharing.keyframe(*layer); + } + } + Down::VoiceEnded => { + inner.drop_calls(); + inner.want_voice = None; + inner.watching.clear(); + return true; + } + } + + false + } + + pub(super) fn receive(&self, datagram: &Bytes, from: &[u8; RELAY_PREFIX], packet: Packet<'_>) { + let inner = self.lock(); + let kind = match packet { + Packet::Voice { seq, opus } => { + if let Some(voice) = &inner.voice { + voice.receive(from, seq, opus); + } + return; + } + Packet::ScreenAudio { .. } => Kind::Screen, + Packet::Video { kind, .. } => kind, + }; + let key = (Uuid::from_bytes(*from).to_string(), kind); + if let Some(watching) = inner.watching.get(&key) { + watching.receive(datagram, &packet); + } + } + + async fn join_voice( + &self, + community_id: String, + settings: VoiceSettings, + ) -> Result, Fail> { + self.lock().joining += 1; + let result = self.join_voice_inner(community_id, settings).await; + self.lock().joining -= 1; + + result + } + + async fn join_voice_inner( + &self, + community_id: String, + settings: VoiceSettings, + ) -> Result, Fail> { + let (connection, epoch) = self.current_wait().await?; + let participants = join(&connection, &community_id).await?; + let voice = voice::start(Some(connection), &settings); + let mut inner = self.lock(); + if !inner.current(epoch) { + return Err(Fail::Offline); + } + let want = Want { + community_id, + settings, + muted: false, + deafened: false, + }; + inner.install_voice(voice, want); + + Ok(participants) + } + + async fn leave_voice(&self) -> Result<(), Fail> { + let connection = { + let mut inner = self.lock(); + inner.drop_calls(); + inner.want_voice = None; + inner.watching.clear(); + inner.connection.clone().ok_or(Fail::Offline)? + }; + + done(&connection, LegacyRequest::LeaveVoice).await + } + + async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> { + let (connection, epoch) = self.current_wait().await?; + let top = match kind { + Kind::Screen => settings.top, + Kind::Camera => CAMERA_TOP, + }; + let sharing = Sharing::start( + connection.clone(), + kind, + top, + settings.encode(), + settings.audio_mode(), + ) + .await + .map_err(Fail::Io)?; + let source = sharing.source(); + { + let mut inner = self.lock(); + if !inner.current(epoch) { + return Err(Fail::Offline); + } + inner.sharing.insert(kind, sharing); + } + + let result = done(&connection, LegacyRequest::StartShare { kind, source }).await; + if result.is_err() { + self.lock().sharing.remove(&kind); + } + + result + } + + async fn update_share(&self, settings: ShareSettings) -> Result<(), Fail> { + let (connection, _) = self.current_wait().await?; + let source = { + let mut inner = self.lock(); + let Some(sharing) = inner.sharing.get_mut(&Kind::Screen) else { + return Ok(()); + }; + sharing + .update( + &connection, + settings.top, + settings.encode(), + settings.audio_mode(), + ) + .map_err(Fail::Io)? + }; + + done( + &connection, + LegacyRequest::StartShare { + kind: Kind::Screen, + source, + }, + ) + .await + } + + async fn stop_share(&self, kind: Kind) -> Result<(), Fail> { + self.lock().sharing.remove(&kind); + let (connection, _) = self.current_wait().await?; + + done(&connection, LegacyRequest::StopShare { kind }).await + } +} + +impl Inner { + fn watch_requests(&self) -> Vec<((String, Kind), LegacyRequest)> { + self.watching + .iter() + .map(|((user_id, kind), watching)| { + let request = LegacyRequest::WatchShare { + user_id: user_id.clone(), + kind: *kind, + quality: watching.wanted(), + decode: capabilities().decode.clone(), + }; + ((user_id.clone(), *kind), request) + }) + .collect() + } +} + +enum Rejoin { + Install, + Ended, + Skip, +} + +async fn join(connection: &Connection, community_id: &str) -> Result, Fail> { + let request = LegacyRequest::JoinVoice { + community_id: community_id.to_string(), + }; + match send(connection, &request).await? { + Response::Voice(participants) => Ok(participants), + _ => Err(Fail::Protocol), + } +} + +async fn send_quietly(connection: Connection, request: LegacyRequest) { + if let Err(error) = send(&connection, &request).await { + warn!("media request failed: {error}"); + } +} + +async fn tick_loop(media: Arc) { + let mut ticker = tokio::time::interval(TICK); + loop { + ticker.tick().await; + let (connection, requests) = { + let mut inner = media.lock(); + (inner.connection.clone(), watch_ticks(&mut inner.watching)) + }; + let Some(connection) = connection else { + continue; + }; + for request in requests { + tokio::spawn(send_quietly(connection.clone(), request)); + } + } +} + +fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec { + watching + .iter_mut() + .flat_map(|((user_id, kind), watching)| { + let (user_id, kind) = (user_id.clone(), *kind); + watching + .tick() + .into_iter() + .map(|tick| match tick { + Tick::Quality(quality) => LegacyRequest::WatchShare { + user_id: user_id.clone(), + kind, + quality, + decode: capabilities().decode.clone(), + }, + Tick::Keyframe => LegacyRequest::RequestKeyframe { + user_id: user_id.clone(), + kind, + }, + }) + .collect::>() + }) + .collect() +} + +impl NetworkHandle { + fn media(&self) -> &Arc { + &self.shared.media + } + + pub async fn join_voice( + &self, + community_id: &str, + settings: &VoiceSettings, + ) -> Result, Fail> { + let media = self.media().clone(); + let community_id = community_id.to_string(); + let settings = settings.clone(); + + self.media() + .run(async move { media.join_voice(community_id, settings).await }) + .await + } + + pub async fn leave_voice(&self) -> Result<(), Fail> { + let media = self.media().clone(); + + self.media() + .run(async move { media.leave_voice().await }) + .await + } + + pub fn set_voice_settings(&self, settings: &VoiceSettings) { + let mut inner = self.media().lock(); + if let Some(want) = inner.want_voice.as_mut() { + want.settings = settings.clone(); + } + if let Some(voice) = inner.voice.as_mut() { + voice.apply(settings); + } + if let Some(voice) = inner.mic_test.as_mut() { + voice.apply(settings); + } + } + + pub fn start_mic_test(&self, settings: &VoiceSettings) { + if self.media().lock().voice.is_some() { + return; + } + let voice = voice::start(None, settings); + let mut inner = self.media().lock(); + if inner.voice.is_none() { + inner.mic_test = Some(voice); + } + } + + pub fn stop_mic_test(&self) { + self.media().lock().mic_test = None; + } + + pub fn play_chime(&self, settings: &VoiceSettings) { + voice::play_chime(settings); + } + + pub fn play_notification(&self, settings: &VoiceSettings) { + voice::play_yumush(settings); + } + + pub fn play_ring(&self, settings: &VoiceSettings) { + voice::play_ring(settings); + } + + pub fn voice_level_db(&self) -> Option { + let inner = self.media().lock(); + + inner + .voice + .as_ref() + .or(inner.mic_test.as_ref()) + .map(Voice::level_db) + } + + pub fn voice_sample(&self) -> Option { + self.media().lock().voice.as_ref().map(Voice::sample) + } + + pub fn set_talking(&self, talking: bool) { + if let Some(voice) = &self.media().lock().voice { + voice.set_talking(talking); + } + } + + pub fn set_muted(&self, muted: bool) { + let mut inner = self.media().lock(); + if let Some(want) = inner.want_voice.as_mut() { + want.muted = muted; + } + if let Some(voice) = &inner.voice { + voice.set_muted(muted); + } + } + + pub fn set_deafened(&self, deafened: bool) { + let mut inner = self.media().lock(); + if let Some(want) = inner.want_voice.as_mut() { + want.deafened = deafened; + } + if let Some(voice) = &inner.voice { + voice.set_deafened(deafened); + } + } + + pub fn levels(&self) -> Levels { + let inner = self.media().lock(); + Levels { + voice: inner.voice.as_ref().map(Voice::levels).unwrap_or_default(), + watching: inner + .watching + .iter() + .filter(|((_, kind), _)| *kind == Kind::Screen) + .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) + .collect(), + sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level), + } + } + + pub async fn start_share(&self, settings: &ShareSettings) -> Result<(), Fail> { + self.start(Kind::Screen, settings).await + } + + pub async fn start_camera(&self, settings: &ShareSettings) -> Result<(), Fail> { + self.start(Kind::Camera, settings).await + } + + async fn start(&self, kind: Kind, settings: &ShareSettings) -> Result<(), Fail> { + let media = self.media().clone(); + let settings = settings.clone(); + + self.media() + .run(async move { media.start_share(kind, settings).await }) + .await + } + + pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> { + let media = self.media().clone(); + let settings = settings.clone(); + + self.media() + .run(async move { media.update_share(settings).await }) + .await + } + + pub async fn stop_share(&self) -> Result<(), Fail> { + self.stop(Kind::Screen).await + } + + pub async fn stop_camera(&self) -> Result<(), Fail> { + self.stop(Kind::Camera).await + } + + async fn stop(&self, kind: Kind) -> Result<(), Fail> { + let media = self.media().clone(); + + self.media() + .run(async move { media.stop_share(kind).await }) + .await + } + + pub fn sharing(&self) -> bool { + self.media().lock().sharing.contains_key(&Kind::Screen) + } + + pub fn camera_on(&self) -> bool { + self.media().lock().sharing.contains_key(&Kind::Camera) + } + + pub fn share_source(&self) -> Option { + self.media() + .lock() + .sharing + .get(&Kind::Screen) + .map(Sharing::source) + } + + pub async fn shares(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(LegacyRequest::Shares { + community_id: community_id.to_string(), + }) + .await?, + Response::Shares + ) + } + + pub async fn watch_share( + &self, + user_id: &str, + kind: Kind, + watch: WatchQuality, + volume: f32, + choice: Choice, + ) -> Result<(), Fail> { + let media = self.media().clone(); + let key = (user_id.to_string(), kind); + let watching = Watching::new(kind, watch, volume, choice); + let quality = watching.wanted(); + + self.media() + .run(async move { + let (connection, epoch) = media.current_wait().await?; + { + let mut inner = media.lock(); + if !inner.current(epoch) { + return Err(Fail::Offline); + } + inner.watching.insert(key.clone(), watching); + } + let result = done( + &connection, + LegacyRequest::WatchShare { + user_id: key.0.clone(), + kind, + quality, + decode: capabilities().decode.clone(), + }, + ) + .await; + if result.is_err() { + media.lock().watching.remove(&key); + } + + result + }) + .await + } + + pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> { + self.media() + .lock() + .watching + .remove(&(user_id.to_string(), kind)); + + self.done(LegacyRequest::UnwatchShare { + user_id: user_id.to_string(), + kind, + }) + .await + } + + pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { + if let Some(watching) = self + .media() + .lock() + .watching + .get_mut(&(user_id.to_string(), kind)) + { + watching.set_quality(quality); + } + } + + pub fn set_share_settings(&self, settings: &ShareSettings) { + for ((_, kind), watching) in self.media().lock().watching.iter_mut() { + if *kind == Kind::Screen { + watching.set_volume(settings.volume); + watching.set_quality(settings.watch); + } + } + } + + pub fn share_sample(&self) -> ShareSample { + let mut inner = self.media().lock(); + ShareSample { + sending: inner + .sharing + .get(&Kind::Screen) + .map(Sharing::stats) + .unwrap_or_default(), + watching: inner + .watching + .iter_mut() + .filter(|((_, kind), _)| *kind == Kind::Screen) + .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) + .collect(), + } + } + + pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { + self.media() + .lock() + .watching + .get(&(user_id.to_string(), kind))? + .frame() + } + + pub fn audio_apps(&self) -> Vec { + audio_capture::apps() + } +} diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index 6776e5b..17e4e0b 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -1,9 +1,10 @@ -use std::{ - path::PathBuf, - sync::{Arc, Mutex}, -}; +use std::{path::PathBuf, sync::Arc}; use common::{ + call::{ + Call, GetAvatar, GetSettings, GetUser, Legacy, ListPresences, ListSessions, RemoveAvatar, + RevokeSession, UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser, + }, constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, event::Event, model::{ @@ -13,9 +14,8 @@ use common::{ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, open::Blob, - request::Request, + request::LegacyRequest, response::Response, - share::Kind, validate::{ validate_avatar_size, validate_community_name, validate_forward, validate_new_message, validate_password, validate_poll, validate_reason, validate_server_settings, @@ -24,11 +24,6 @@ use common::{ }; use tokio::sync::{mpsc, oneshot}; -use crate::{ - settings::{ShareSettings, VoiceSettings}, - voice::Voice, -}; - macro_rules! expect { ($response:expr, $variant:path) => { match $response { @@ -43,12 +38,11 @@ mod events; mod fail; mod fetch; mod link; -mod share; -mod voice; +mod media; pub use fail::{Fail, LinkError}; pub use link::start; -use share::Share; +use media::Media; fn device_name() -> String { let host = gethostname::gethostname() @@ -64,26 +58,12 @@ fn device_name() -> String { format!("{host} {}", std::env::consts::OS) } -type SharedVoice = Arc>>; -type SharedSettings = Arc>; -type SharedShare = Arc>; -type SharedShareSettings = Arc>; - -#[derive(Clone, Default)] +#[derive(Clone)] struct Shared { - voice: SharedVoice, - mic_test: SharedVoice, - voice_settings: SharedSettings, - share: SharedShare, - share_settings: SharedShareSettings, + media: Arc, fetches: Arc, } -fn hang_up(shared: &Shared) { - shared.voice.lock().unwrap().take(); - *shared.share.lock().unwrap() = Share::default(); -} - #[derive(Default)] pub struct Levels { pub voice: Vec<(String, Vec)>, @@ -94,17 +74,15 @@ pub struct Levels { #[derive(Debug)] pub enum NetworkEvent { Connected, + VoiceRejoined, + VoiceEnded, Disconnected(LinkError), SessionLost, Pushed(Box), } -#[derive(Debug)] enum Command { - Request { - request: Request, - reply: oneshot::Sender>, - }, + Call(Box), SignIn { token: Option, reply: oneshot::Sender, Fail>>, @@ -124,15 +102,6 @@ enum Command { path: PathBuf, reply: oneshot::Sender>, }, - StartShare { - kind: Kind, - settings: ShareSettings, - reply: oneshot::Sender>, - }, - UpdateShare { - settings: ShareSettings, - reply: oneshot::Sender>, - }, } #[derive(Clone)] @@ -156,19 +125,24 @@ impl NetworkHandle { response.await.map_err(|_| Fail::Offline)? } - fn with_voice(&self, f: impl FnOnce(&Voice) -> T) -> Option { - self.shared.voice.lock().unwrap().as_ref().map(f) + async fn call(&self, call: C) -> Result { + self.ask(|reply| { + Command::Call(Box::new(move |connection| { + link::answer(reply, async move { link::call(&connection, call).await }); + })) + }) + .await } - async fn request(&self, request: Request) -> Result { - self.ask(|reply| Command::Request { request, reply }).await + async fn request(&self, request: LegacyRequest) -> Result { + self.call(Legacy(request)).await } async fn switch(&self, token: Option) -> Result, Fail> { self.ask(|reply| Command::SignIn { token, reply }).await } - async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> { + async fn sign_in(&self, request: LegacyRequest) -> Result<(User, String), Fail> { let (user, token) = match self.request(request).await? { Response::Session { user, token } => (user, token), _ => return Err(Fail::Protocol), @@ -179,17 +153,14 @@ impl NetworkHandle { } pub async fn sessions(&self, user_id: &str) -> Result, Fail> { - expect!( - self.request(Request::Sessions { - user_id: user_id.to_string(), - }) - .await?, - Response::Sessions - ) + self.call(ListSessions { + user_id: user_id.to_string(), + }) + .await } pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> { - self.done(Request::RevokeSession { + self.call(RevokeSession { user_id: user_id.to_string(), session_id: session_id.to_string(), }) @@ -200,7 +171,7 @@ impl NetworkHandle { validate_username(username)?; expect!( - self.request(Request::RenameUser { + self.request(LegacyRequest::RenameUser { user_id: user_id.to_string(), username: username.to_string(), }) @@ -231,7 +202,7 @@ impl NetworkHandle { validate_username(username)?; validate_password(password)?; - self.sign_in(Request::Register { + self.sign_in(LegacyRequest::Register { username: username.to_string(), password: password.to_string(), invite: invite.map(str::to_string), @@ -242,7 +213,7 @@ impl NetworkHandle { pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { validate_password(password)?; - self.sign_in(Request::Login { + self.sign_in(LegacyRequest::Login { username: username.to_string(), password: password.to_string(), }) @@ -250,7 +221,7 @@ impl NetworkHandle { } pub async fn logout(&self) -> Result<(), Fail> { - let result = self.done(Request::Logout).await; + let result = self.done(LegacyRequest::Logout).await; self.detach().await?; result } @@ -258,18 +229,15 @@ impl NetworkHandle { pub async fn update_user(&self, username: &str) -> Result { validate_username(username)?; - expect!( - self.request(Request::UpdateUser { - username: username.to_string(), - }) - .await?, - Response::User - ) + self.call(UpdateUser { + username: username.to_string(), + }) + .await } pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> { expect!( - self.request(Request::DeleteUser { + self.request(LegacyRequest::DeleteUser { user_id: user_id.to_string(), }) .await?, @@ -279,11 +247,11 @@ impl NetworkHandle { } pub async fn users(&self) -> Result, Fail> { - expect!(self.request(Request::Users).await?, Response::Users) + expect!(self.request(LegacyRequest::Users).await?, Response::Users) } pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> { - self.done(Request::SuspendUser { + self.done(LegacyRequest::SuspendUser { user_id: user_id.to_string(), suspended, }) @@ -291,7 +259,7 @@ impl NetworkHandle { } pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> { - self.done(Request::TimeoutUser { + self.done(LegacyRequest::TimeoutUser { user_id: user_id.to_string(), minutes, }) @@ -306,7 +274,7 @@ impl NetworkHandle { ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(Request::BanUser { + self.done(LegacyRequest::BanUser { user_id: user_id.to_string(), reason: reason.map(str::to_string), scope, @@ -316,13 +284,13 @@ impl NetworkHandle { pub async fn server_bans(&self) -> Result, Fail> { expect!( - self.request(Request::ServerBans).await?, + self.request(LegacyRequest::ServerBans).await?, Response::ServerBans ) } pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> { - self.done(Request::RemoveServerBan { id: id.to_string() }) + self.done(LegacyRequest::RemoveServerBan { id: id.to_string() }) .await } @@ -332,7 +300,7 @@ impl NetworkHandle { hours: Option, ) -> Result { expect!( - self.request(Request::CreateInviteCode { uses, hours }) + self.request(LegacyRequest::CreateInviteCode { uses, hours }) .await?, Response::InviteCode ) @@ -340,20 +308,20 @@ impl NetworkHandle { pub async fn invite_codes(&self) -> Result, Fail> { expect!( - self.request(Request::InviteCodes).await?, + self.request(LegacyRequest::InviteCodes).await?, Response::InviteCodes ) } pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> { - self.done(Request::DeleteInviteCode { + self.done(LegacyRequest::DeleteInviteCode { code: code.to_string(), }) .await } pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::RevokeSessions { + self.done(LegacyRequest::RevokeSessions { user_id: user_id.to_string(), }) .await @@ -362,7 +330,7 @@ impl NetworkHandle { pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> { validate_password(password)?; - self.done(Request::ResetPassword { + self.done(LegacyRequest::ResetPassword { user_id: user_id.to_string(), password: password.to_string(), }) @@ -371,7 +339,7 @@ impl NetworkHandle { pub async fn clear_profile(&self, user_id: &str) -> Result { expect!( - self.request(Request::ClearProfile { + self.request(LegacyRequest::ClearProfile { user_id: user_id.to_string(), }) .await?, @@ -381,7 +349,7 @@ impl NetworkHandle { pub async fn set_role(&self, user_id: &str, role: Role) -> Result { expect!( - self.request(Request::SetRole { + self.request(LegacyRequest::SetRole { user_id: user_id.to_string(), role, }) @@ -398,7 +366,7 @@ impl NetworkHandle { after_ms: Option, before_ms: Option, ) -> Result, Fail> { - let request = Request::AdminLogs { + let request = LegacyRequest::AdminLogs { actor_id, target_id, action, @@ -410,16 +378,13 @@ impl NetworkHandle { pub async fn daily_stats(&self, days: u32) -> Result, Fail> { expect!( - self.request(Request::DailyStats { days }).await?, + self.request(LegacyRequest::DailyStats { days }).await?, Response::DailyStats ) } pub async fn server_settings(&self) -> Result { - expect!( - self.request(Request::ServerSettings).await?, - Response::ServerSettings - ) + self.call(GetSettings).await } pub async fn update_server_settings( @@ -429,7 +394,7 @@ impl NetworkHandle { validate_server_settings(&settings)?; expect!( - self.request(Request::UpdateServerSettings { settings }) + self.request(LegacyRequest::UpdateServerSettings { settings }) .await?, Response::ServerSettings ) @@ -440,7 +405,7 @@ impl NetworkHandle { validate_password(password)?; expect!( - self.request(Request::CreateUser { + self.request(LegacyRequest::CreateUser { username: username.to_string(), password: password.to_string(), }) @@ -450,18 +415,21 @@ impl NetworkHandle { } pub async fn overview(&self) -> Result { - expect!(self.request(Request::Overview).await?, Response::Overview) + expect!( + self.request(LegacyRequest::Overview).await?, + Response::Overview + ) } pub async fn all_communities(&self) -> Result, Fail> { expect!( - self.request(Request::AllCommunities).await?, + self.request(LegacyRequest::AllCommunities).await?, Response::AllCommunities ) } pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(Request::TransferOwnership { + self.done(LegacyRequest::TransferOwnership { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -469,20 +437,17 @@ impl NetworkHandle { } pub async fn read_user(&self, user_id: &str) -> Result { - expect!( - self.request(Request::ReadUser { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) + self.call(GetUser { + user_id: user_id.to_string(), + }) + .await } pub async fn create_community(&self, name: &str) -> Result { validate_community_name(name)?; expect!( - self.request(Request::CreateCommunity { + self.request(LegacyRequest::CreateCommunity { name: name.to_string(), }) .await?, @@ -498,7 +463,7 @@ impl NetworkHandle { validate_community_name(name)?; expect!( - self.request(Request::UpdateCommunity { + self.request(LegacyRequest::UpdateCommunity { community_id: community_id.to_string(), name: name.to_string(), }) @@ -509,7 +474,7 @@ impl NetworkHandle { pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> { expect!( - self.request(Request::DeleteCommunity { + self.request(LegacyRequest::DeleteCommunity { community_id: community_id.to_string(), }) .await?, @@ -519,7 +484,7 @@ impl NetworkHandle { } pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> { - self.done(Request::LeaveCommunity { + self.done(LegacyRequest::LeaveCommunity { community_id: community_id.to_string(), }) .await @@ -527,14 +492,14 @@ impl NetworkHandle { pub async fn communities(&self) -> Result, Fail> { expect!( - self.request(Request::Communities).await?, + self.request(LegacyRequest::Communities).await?, Response::Communities ) } pub async fn members(&self, community_id: &str) -> Result, Fail> { expect!( - self.request(Request::Members { + self.request(LegacyRequest::Members { community_id: community_id.to_string(), }) .await?, @@ -549,7 +514,7 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(Request::Kick { + self.done(LegacyRequest::Kick { community_id: community_id.to_string(), user_id: user_id.to_string(), reason: reason.map(str::to_string), @@ -564,7 +529,7 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(Request::Ban { + self.done(LegacyRequest::Ban { community_id: community_id.to_string(), user_id: user_id.to_string(), reason: reason.map(str::to_string), @@ -573,7 +538,7 @@ impl NetworkHandle { } pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(Request::Unban { + self.done(LegacyRequest::Unban { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -582,7 +547,7 @@ impl NetworkHandle { pub async fn bans(&self, community_id: &str) -> Result, Fail> { expect!( - self.request(Request::Bans { + self.request(LegacyRequest::Bans { community_id: community_id.to_string(), }) .await?, @@ -592,7 +557,7 @@ impl NetworkHandle { pub async fn logs(&self, community_id: &str) -> Result, Fail> { expect!( - self.request(Request::Logs { + self.request(LegacyRequest::Logs { community_id: community_id.to_string(), }) .await?, @@ -606,7 +571,7 @@ impl NetworkHandle { user_id: &str, rank: Rank, ) -> Result<(), Fail> { - self.done(Request::SetRank { + self.done(LegacyRequest::SetRank { community_id: community_id.to_string(), user_id: user_id.to_string(), rank, @@ -616,7 +581,7 @@ impl NetworkHandle { pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> { expect!( - self.request(Request::DeleteMessage { + self.request(LegacyRequest::DeleteMessage { message_id: message_id.to_string(), }) .await?, @@ -635,7 +600,7 @@ impl NetworkHandle { validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; expect!( - self.request(Request::CreateMessage { + self.request(LegacyRequest::CreateMessage { community_id: community_id.to_string(), body: body.to_string(), attachments, @@ -650,7 +615,7 @@ impl NetworkHandle { validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; expect!( - self.request(Request::UpdateMessage { + self.request(LegacyRequest::UpdateMessage { message_id: message_id.to_string(), body: body.to_string(), }) @@ -668,7 +633,7 @@ impl NetworkHandle { validate_forward(message_ids.len())?; expect!( - self.request(Request::ForwardMessages { + self.request(LegacyRequest::ForwardMessages { message_ids, community_id: community_id.to_string(), snippet, @@ -680,7 +645,7 @@ impl NetworkHandle { pub async fn find_user(&self, username: &str) -> Result { expect!( - self.request(Request::FindUser { + self.request(LegacyRequest::FindUser { username: username.to_string(), }) .await?, @@ -689,12 +654,15 @@ impl NetworkHandle { } pub async fn open_notes(&self) -> Result { - expect!(self.request(Request::OpenNotes).await?, Response::Community) + expect!( + self.request(LegacyRequest::OpenNotes).await?, + Response::Community + ) } pub async fn open_direct(&self, user_id: &str) -> Result { expect!( - self.request(Request::OpenDirect { + self.request(LegacyRequest::OpenDirect { user_id: user_id.to_string(), }) .await?, @@ -703,43 +671,43 @@ impl NetworkHandle { } pub async fn friends(&self) -> Result { - expect!(self.request(Request::Friends).await?, Response::Friends) + expect!( + self.request(LegacyRequest::Friends).await?, + Response::Friends + ) } pub async fn read_presences(&self) -> Result, Fail> { - expect!( - self.request(Request::ReadPresences).await?, - Response::Presences - ) + self.call(ListPresences).await } pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> { - self.done(Request::UpdatePresence { presence }).await + self.call(UpdatePresence { presence }).await } pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::AddFriend { + self.done(LegacyRequest::AddFriend { user_id: user_id.to_string(), }) .await } pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::AcceptFriend { + self.done(LegacyRequest::AcceptFriend { user_id: user_id.to_string(), }) .await } pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::RemoveFriend { + self.done(LegacyRequest::RemoveFriend { user_id: user_id.to_string(), }) .await } pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(Request::Invite { + self.done(LegacyRequest::Invite { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -748,14 +716,14 @@ impl NetworkHandle { pub async fn invitations(&self) -> Result, Fail> { expect!( - self.request(Request::Invitations).await?, + self.request(LegacyRequest::Invitations).await?, Response::Invitations ) } pub async fn accept_invitation(&self, community_id: &str) -> Result { expect!( - self.request(Request::AcceptInvitation { + self.request(LegacyRequest::AcceptInvitation { community_id: community_id.to_string(), }) .await?, @@ -764,21 +732,21 @@ impl NetworkHandle { } pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> { - self.done(Request::DeclineInvitation { + self.done(LegacyRequest::DeclineInvitation { community_id: community_id.to_string(), }) .await } pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> { - self.done(Request::DeclineCall { + self.done(LegacyRequest::DeclineCall { community_id: community_id.to_string(), }) .await } pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> { - self.done(Request::React { + self.done(LegacyRequest::React { message_id: message_id.to_string(), emoji: emoji.to_string(), }) @@ -786,7 +754,7 @@ impl NetworkHandle { } pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> { - self.done(Request::Pin { + self.done(LegacyRequest::Pin { message_id: message_id.to_string(), pinned, }) @@ -795,7 +763,7 @@ impl NetworkHandle { pub async fn pins(&self, community_id: &str) -> Result, Fail> { expect!( - self.request(Request::Pins { + self.request(LegacyRequest::Pins { community_id: community_id.to_string(), }) .await?, @@ -813,7 +781,7 @@ impl NetworkHandle { validate_poll(question, &options)?; expect!( - self.request(Request::CreatePoll { + self.request(LegacyRequest::CreatePoll { community_id: community_id.to_string(), question: question.to_string(), options, @@ -825,7 +793,7 @@ impl NetworkHandle { } pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Fail> { - self.done(Request::Vote { + self.done(LegacyRequest::Vote { message_id: message_id.to_string(), positions, }) @@ -833,7 +801,7 @@ impl NetworkHandle { } pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> { - self.done(Request::ClosePoll { + self.done(LegacyRequest::ClosePoll { message_id: message_id.to_string(), }) .await @@ -842,7 +810,7 @@ impl NetworkHandle { pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> { validate_reason(Some(reason))?; - self.done(Request::ReportMessage { + self.done(LegacyRequest::ReportMessage { message_id: message_id.to_string(), reason: reason.to_string(), }) @@ -852,7 +820,7 @@ impl NetworkHandle { pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> { validate_reason(Some(reason))?; - self.done(Request::ReportUser { + self.done(LegacyRequest::ReportUser { user_id: user_id.to_string(), reason: reason.to_string(), }) @@ -861,13 +829,13 @@ impl NetworkHandle { pub async fn reports(&self, status: Option) -> Result, Fail> { expect!( - self.request(Request::Reports { status }).await?, + self.request(LegacyRequest::Reports { status }).await?, Response::Reports ) } pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> { - self.done(Request::HandleReport { + self.done(LegacyRequest::HandleReport { report_id: report_id.to_string(), status, }) @@ -883,7 +851,7 @@ impl NetworkHandle { before_ms: Option, ) -> Result, Fail> { expect!( - self.request(Request::SearchMessages { + self.request(LegacyRequest::SearchMessages { text, user_id, community_id, @@ -901,29 +869,35 @@ impl NetworkHandle { text: String, ) -> Result, Fail> { expect!( - self.request(Request::SearchCommunity { community_id, text }) + self.request(LegacyRequest::SearchCommunity { community_id, text }) .await?, Response::MessageHits ) } pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { - match self.request(Request::StorageUsage).await? { + match self.request(LegacyRequest::StorageUsage).await? { Response::StorageUsage { users, communities } => Ok((users, communities)), _ => Err(Fail::Protocol), } } pub async fn create_backup(&self) -> Result { - expect!(self.request(Request::CreateBackup).await?, Response::Backup) + expect!( + self.request(LegacyRequest::CreateBackup).await?, + Response::Backup + ) } pub async fn backups(&self) -> Result, Fail> { - expect!(self.request(Request::Backups).await?, Response::Backups) + expect!( + self.request(LegacyRequest::Backups).await?, + Response::Backups + ) } pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> { - self.done(Request::DeleteBackup { + self.done(LegacyRequest::DeleteBackup { name: name.to_string(), }) .await @@ -935,7 +909,7 @@ impl NetworkHandle { community_id: Option, ) -> Result, Fail> { expect!( - self.request(Request::AllAttachments { + self.request(LegacyRequest::AllAttachments { user_id, community_id, }) @@ -945,20 +919,20 @@ impl NetworkHandle { } pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> { - self.done(Request::DeleteAttachment { + self.done(LegacyRequest::DeleteAttachment { attachment_id: attachment_id.to_string(), }) .await } pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::PurgeUser { + self.done(LegacyRequest::PurgeUser { user_id: user_id.to_string(), }) .await } - async fn done(&self, request: Request) -> Result<(), Fail> { + async fn done(&self, request: LegacyRequest) -> Result<(), Fail> { match self.request(request).await? { Response::Done => Ok(()), _ => Err(Fail::Protocol), @@ -1004,7 +978,7 @@ impl NetworkHandle { } pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> { - self.done(Request::WatchCommunity { + self.done(LegacyRequest::WatchCommunity { community_id: community_id.map(str::to_string), }) .await @@ -1016,7 +990,7 @@ impl NetworkHandle { before: Option<&str>, ) -> Result, Fail> { expect!( - self.request(Request::ReadMessages { + self.request(LegacyRequest::ReadMessages { community_id: community_id.to_string(), before: before.map(str::to_string), }) @@ -1026,11 +1000,14 @@ impl NetworkHandle { } pub async fn unreads(&self) -> Result, Fail> { - expect!(self.request(Request::Unreads).await?, Response::Unreads) + expect!( + self.request(LegacyRequest::Unreads).await?, + Response::Unreads + ) } pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> { - self.done(Request::MarkRead { + self.done(LegacyRequest::MarkRead { community_id: community_id.to_string(), message_id: message_id.to_string(), }) @@ -1040,22 +1017,16 @@ impl NetworkHandle { pub async fn update_status(&self, status: &str) -> Result { validate_status(status)?; - expect!( - self.request(Request::UpdateStatus { - status: status.to_string(), - }) - .await?, - Response::User - ) + self.call(UpdateStatus { + status: status.to_string(), + }) + .await } pub async fn update_avatar(&self, bytes: Vec) -> Result { validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; - expect!( - self.request(Request::UpdateAvatar { image: bytes }).await?, - Response::User - ) + self.call(UpdateAvatar { image: bytes }).await } pub async fn update_community_avatar( @@ -1068,7 +1039,7 @@ impl NetworkHandle { } expect!( - self.request(Request::UpdateCommunityAvatar { + self.request(LegacyRequest::UpdateCommunityAvatar { community_id: community_id.to_string(), image, }) @@ -1078,43 +1049,26 @@ impl NetworkHandle { } pub async fn remove_avatar(&self) -> Result { - expect!(self.request(Request::RemoveAvatar).await?, Response::User) + self.call(RemoveAvatar).await } pub async fn read_avatar(&self, avatar_id: &str) -> Result, Fail> { - expect!( - self.request(Request::ReadAvatar { - avatar_id: avatar_id.to_string(), - }) - .await?, - Response::Avatar - ) - } - - pub async fn join_voice(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(Request::JoinVoice { - community_id: community_id.to_string(), - }) - .await?, - Response::Voice - ) + self.call(GetAvatar { + avatar_id: avatar_id.to_string(), + }) + .await } pub async fn typing(&self, community_id: &str) -> Result<(), Fail> { - self.done(Request::Typing { + self.done(LegacyRequest::Typing { community_id: community_id.to_string(), }) .await } - pub async fn leave_voice(&self) -> Result<(), Fail> { - self.done(Request::LeaveVoice).await - } - pub async fn read_community(&self, community_id: &str) -> Result { expect!( - self.request(Request::ReadCommunity { + self.request(LegacyRequest::ReadCommunity { community_id: community_id.to_string(), }) .await?, @@ -1124,7 +1078,7 @@ impl NetworkHandle { pub async fn voice_participants(&self, community_id: &str) -> Result, Fail> { expect!( - self.request(Request::VoiceParticipants { + self.request(LegacyRequest::VoiceParticipants { community_id: community_id.to_string(), }) .await?, @@ -1134,24 +1088,24 @@ impl NetworkHandle { pub async fn voice_rooms(&self) -> Result, Fail> { expect!( - self.request(Request::VoiceRooms).await?, + self.request(LegacyRequest::VoiceRooms).await?, Response::VoiceRooms ) } pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> { - self.done(Request::SetGhost { enabled }).await + self.done(LegacyRequest::SetGhost { enabled }).await } pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> { - self.done(Request::KickFromVoice { + self.done(LegacyRequest::KickFromVoice { user_id: user_id.to_string(), }) .await } pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> { - self.done(Request::ServerMute { + self.done(LegacyRequest::ServerMute { user_id: user_id.to_string(), muted, }) @@ -1164,7 +1118,7 @@ impl NetworkHandle { enabled: bool, ) -> Result { expect!( - self.request(Request::SetCommunityVoice { + self.request(LegacyRequest::SetCommunityVoice { community_id: community_id.to_string(), enabled, }) diff --git a/crates/client/src/net/share.rs b/crates/client/src/net/share.rs deleted file mode 100644 index ef28d1b..0000000 --- a/crates/client/src/net/share.rs +++ /dev/null @@ -1,338 +0,0 @@ -use std::collections::HashMap; - -use common::{ - event::{Event, Media}, - request::Request, - response::Response, - share::{Fps, Kind, Quality, Resolution, Source}, -}; - -use crate::{ - settings::ShareSettings, - share::{ - audio::AudioApp, - audio_capture, - encode::capabilities, - session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, - }, -}; - -use super::{link::done, *}; - -#[derive(Default)] -pub(super) struct Share { - pub(super) sharing: HashMap, - pub(super) sources: HashMap, - pub(super) watching: HashMap<(String, Kind), Watching>, -} - -impl Share { - pub(super) fn event(&mut self, event: &Event) { - if let Event::ShareStopped { user_id, kind, .. } = event { - self.watching.remove(&(user_id.clone(), *kind)); - } - } - - pub(super) fn media(&mut self, media: &Media) { - match media { - Media::Layers { kind, layers } => { - if let Some(sharing) = self.sharing.get_mut(kind) { - sharing.set_layers(layers); - } - } - Media::Keyframe { kind, layer } => { - if let Some(sharing) = self.sharing.get(kind) { - sharing.keyframe(*layer); - } - } - Media::VoiceEnded => {} - } - } - - pub(super) fn ticks(&mut self) -> Vec { - self.watching - .iter_mut() - .flat_map(|((user_id, kind), watching)| { - let (user_id, kind) = (user_id.clone(), *kind); - watching - .tick() - .into_iter() - .map(|tick| match tick { - Tick::Quality(quality) => Request::WatchShare { - user_id: user_id.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }, - Tick::Keyframe => Request::RequestKeyframe { - user_id: user_id.clone(), - kind, - }, - }) - .collect::>() - }) - .collect() - } -} - -const CAMERA_TOP: Quality = Quality { - resolution: Resolution::P2160, - fps: Fps::F60, -}; - -impl NetworkHandle { - pub async fn start_share(&self) -> Result<(), Fail> { - self.start(Kind::Screen).await - } - - pub async fn start_camera(&self) -> Result<(), Fail> { - self.start(Kind::Camera).await - } - - async fn start(&self, kind: Kind) -> Result<(), Fail> { - let settings = self.shared.share_settings.lock().unwrap().clone(); - self.ask(|reply| Command::StartShare { - kind, - settings, - reply, - }) - .await - } - - pub async fn update_share(&self) -> Result<(), Fail> { - let settings = self.shared.share_settings.lock().unwrap().clone(); - self.ask(|reply| Command::UpdateShare { settings, reply }) - .await - } - - pub async fn stop_share(&self) -> Result<(), Fail> { - self.stop(Kind::Screen).await - } - - pub async fn stop_camera(&self) -> Result<(), Fail> { - self.stop(Kind::Camera).await - } - - async fn stop(&self, kind: Kind) -> Result<(), Fail> { - let result = self.done(Request::StopShare { kind }).await; - let mut share = self.shared.share.lock().unwrap(); - share.sharing.remove(&kind); - share.sources.remove(&kind); - result - } - - pub fn sharing(&self) -> bool { - self.shared - .share - .lock() - .unwrap() - .sharing - .contains_key(&Kind::Screen) - } - - pub fn camera_on(&self) -> bool { - self.shared - .share - .lock() - .unwrap() - .sharing - .contains_key(&Kind::Camera) - } - - pub fn share_source(&self) -> Option { - self.shared - .share - .lock() - .unwrap() - .sources - .get(&Kind::Screen) - .cloned() - } - - pub async fn shares(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(Request::Shares { - community_id: community_id.to_string(), - }) - .await?, - Response::Shares - ) - } - - pub async fn watch_share( - &self, - user_id: &str, - kind: Kind, - watch: WatchQuality, - ) -> Result<(), Fail> { - let volume = self.shared.share_settings.lock().unwrap().volume; - let choice = self.shared.voice_settings.lock().unwrap().choice.clone(); - let key = (user_id.to_string(), kind); - let watching = Watching::new(kind, watch, volume, choice); - let quality = watching.wanted(); - self.shared - .share - .lock() - .unwrap() - .watching - .insert(key.clone(), watching); - - let result = self - .done(Request::WatchShare { - user_id: key.0.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }) - .await; - if result.is_err() { - self.shared.share.lock().unwrap().watching.remove(&key); - } - result - } - - pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> { - self.shared - .share - .lock() - .unwrap() - .watching - .remove(&(user_id.to_string(), kind)); - self.done(Request::UnwatchShare { - user_id: user_id.to_string(), - kind, - }) - .await - } - - pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { - if let Some(watching) = self - .shared - .share - .lock() - .unwrap() - .watching - .get_mut(&(user_id.to_string(), kind)) - { - watching.set_quality(quality); - } - } - - pub fn share_sample(&self) -> ShareSample { - let mut share = self.shared.share.lock().unwrap(); - ShareSample { - sending: share - .sharing - .get(&Kind::Screen) - .map(Sharing::stats) - .unwrap_or_default(), - watching: share - .watching - .iter_mut() - .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) - .collect(), - } - } - - pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { - self.shared - .share - .lock() - .unwrap() - .watching - .get(&(user_id.to_string(), kind))? - .frame() - } - - pub fn set_share_settings(&self, settings: ShareSettings) -> bool { - let changed = self.sharing() - && self - .shared - .share_settings - .lock() - .unwrap() - .encoding_differs(&settings); - *self.shared.share_settings.lock().unwrap() = settings.clone(); - for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() { - if *kind == Kind::Screen { - watching.set_volume(settings.volume); - watching.set_quality(settings.watch); - } - } - changed - } - - pub fn audio_apps(&self) -> Vec { - audio_capture::apps() - } -} - -pub(super) async fn start_share( - connection: &quinn::Connection, - share: &SharedShare, - kind: Kind, - settings: &ShareSettings, -) -> Result<(), Fail> { - let top = match kind { - Kind::Screen => settings.top, - Kind::Camera => CAMERA_TOP, - }; - let (sharing, source) = Sharing::start( - connection.clone(), - kind, - top, - settings.encode(), - settings.audio_mode(), - ) - .await - .map_err(Fail::Io)?; - { - let mut share = share.lock().unwrap(); - share.sharing.insert(kind, sharing); - share.sources.insert(kind, source.clone()); - } - - let result = done(connection, Request::StartShare { kind, source }).await; - if result.is_err() { - let mut share = share.lock().unwrap(); - share.sharing.remove(&kind); - share.sources.remove(&kind); - } - result -} - -pub(super) async fn update_share( - connection: &quinn::Connection, - share: &SharedShare, - settings: &ShareSettings, -) -> Result<(), Fail> { - let source = { - let mut share = share.lock().unwrap(); - let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else { - return Ok(()); - }; - sharing - .update( - connection, - settings.top, - settings.encode(), - settings.audio_mode(), - ) - .map_err(Fail::Io)? - }; - share - .lock() - .unwrap() - .sources - .insert(Kind::Screen, source.clone()); - - done( - connection, - Request::StartShare { - kind: Kind::Screen, - source, - }, - ) - .await -} diff --git a/crates/client/src/net/voice.rs b/crates/client/src/net/voice.rs deleted file mode 100644 index f3baa08..0000000 --- a/crates/client/src/net/voice.rs +++ /dev/null @@ -1,87 +0,0 @@ -use common::share::Kind; - -use crate::{ - settings::VoiceSettings, - share::session::Sharing, - voice::{self, Voice, VoiceSample}, -}; - -use super::*; - -impl NetworkHandle { - pub fn set_voice_settings(&self, settings: VoiceSettings) { - *self.shared.voice_settings.lock().unwrap() = settings.clone(); - - if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() { - voice.apply(&settings); - } - if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() { - voice.apply(&settings); - } - } - - pub fn start_mic_test(&self) { - if self.shared.voice.lock().unwrap().is_some() { - return; - } - let settings = self.shared.voice_settings.lock().unwrap().clone(); - *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); - } - - pub fn play_chime(&self) { - voice::play_chime(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn play_notification(&self) { - voice::play_yumush(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn play_ring(&self) { - voice::play_ring(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn stop_mic_test(&self) { - self.shared.mic_test.lock().unwrap().take(); - } - - pub fn voice_level_db(&self) -> Option { - self.with_voice(Voice::level_db).or_else(|| { - self.shared - .mic_test - .lock() - .unwrap() - .as_ref() - .map(Voice::level_db) - }) - } - - pub fn voice_sample(&self) -> Option { - self.with_voice(Voice::sample) - } - - pub fn set_talking(&self, talking: bool) { - self.with_voice(|voice| voice.set_talking(talking)); - } - - pub fn set_muted(&self, muted: bool) { - self.with_voice(|voice| voice.set_muted(muted)); - } - - pub fn set_deafened(&self, deafened: bool) { - self.with_voice(|voice| voice.set_deafened(deafened)); - } - - pub fn levels(&self) -> Levels { - let share = self.shared.share.lock().unwrap(); - Levels { - voice: self.with_voice(Voice::levels).unwrap_or_default(), - watching: share - .watching - .iter() - .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) - .collect(), - sharing: share.sharing.get(&Kind::Screen).map(Sharing::level), - } - } -} diff --git a/crates/client/src/share/reassembly.rs b/crates/client/src/share/reassembly.rs index 990c371..5da22e0 100644 --- a/crates/client/src/share/reassembly.rs +++ b/crates/client/src/share/reassembly.rs @@ -1,6 +1,9 @@ use std::collections::HashMap; -use common::{datagram::Fragment, share::Layer}; +use common::{ + datagram::{Packet, layout, seq_newer}, + share::Layer, +}; const PENDING_LIMIT: usize = 8; @@ -29,23 +32,24 @@ struct Pending { } impl Pending { - fn new(fragment: Fragment<'_>) -> Pending { + fn new(layer: Layer, keyframe: bool, timestamp_ms: u32, length: u32) -> Pending { + let layout = layout(length); Pending { - layer: fragment.layer, - keyframe: fragment.keyframe, - timestamp_ms: fragment.timestamp_ms, - data: usize::from(fragment.data), - length: fragment.length as usize, + layer, + keyframe, + timestamp_ms, + data: layout.data, + length: length as usize, present: 0, - shards: vec![None; usize::from(fragment.count)], + shards: vec![None; layout.count()], } } - fn insert(&mut self, fragment: Fragment<'_>) { - if let Some(shard) = self.shards.get_mut(usize::from(fragment.index)) - && shard.is_none() + fn insert(&mut self, index: u16, shard: &[u8]) { + if let Some(slot) = self.shards.get_mut(usize::from(index)) + && slot.is_none() { - *shard = Some(fragment.payload.to_vec()); + *slot = Some(shard.to_vec()); self.present += 1; } } @@ -78,11 +82,6 @@ impl Pending { } } -fn is_newer(frame: u32, than: u32) -> bool { - let distance = frame.wrapping_sub(than); - distance != 0 && distance < u32::MAX / 2 -} - pub struct Reassembler { layer: Option, pending: HashMap, @@ -110,33 +109,43 @@ impl Reassembler { } } - pub fn push(&mut self, fragment: Fragment<'_>) -> Option { - if self.layer != Some(fragment.layer) { - self.layer = Some(fragment.layer); + pub fn push(&mut self, packet: &Packet<'_>) -> Option { + let &Packet::Video { + layer, + keyframe, + frame, + index, + length, + ts_ms, + shard, + .. + } = packet + else { + return None; + }; + if self.layer != Some(layer) { + self.layer = Some(layer); self.pending.clear(); self.last = None; self.phase = Phase::WaitingKeyframe; } - if self - .last - .is_some_and(|last| !is_newer(fragment.frame, last)) - { + if self.last.is_some_and(|last| !seq_newer(frame, last)) { return None; } - if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT { + if !self.pending.contains_key(&frame) && self.pending.len() >= PENDING_LIMIT { self.pending.clear(); self.phase = Phase::WaitingKeyframe; } let pending = self .pending - .entry(fragment.frame) - .or_insert_with(|| Pending::new(fragment)); - pending.insert(fragment); + .entry(frame) + .or_insert_with(|| Pending::new(layer, keyframe, ts_ms, length)); + pending.insert(index, shard); if !pending.is_complete() { return None; } - let complete = self.pending.remove(&fragment.frame)?; - self.deliver(fragment.frame, complete) + let complete = self.pending.remove(&frame)?; + self.deliver(frame, complete) } fn deliver(&mut self, frame: u32, complete: Pending) -> Option { @@ -150,7 +159,7 @@ impl Reassembler { if skipped > 0 || data.is_none() { self.lost_frames += skipped + u32::from(data.is_none()); self.phase = Phase::WaitingKeyframe; - self.pending.retain(|&older, _| is_newer(older, frame)); + self.pending.retain(|&older, _| seq_newer(older, frame)); } let data = data?; self.received_frames += 1; diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index b13cac9..795fa06 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -15,7 +15,7 @@ use common::{ SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, }, - datagram::{Datagram, fragments}, + datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, }; use ec_opus::{Application, Decoder, Encoder}; @@ -208,11 +208,12 @@ impl Sharing { top: Quality, encode: Vec, audio: Option, - ) -> Result<(Sharing, Source), String> { + ) -> Result { if encode.is_empty() { return Err("codec unavailable".into()); } let audio = audio.filter(|_| kind == Kind::Screen); + warn_if_small(&connection); let mut input = match kind { Kind::Screen => Input::Screen(capture::open().await?), Kind::Camera => Input::Camera( @@ -261,24 +262,25 @@ impl Sharing { }) }; - Ok(( - Sharing { - encoders, - _feed: feed, - _input: input, - refresh, - source: source.clone(), - started, - audio, - _audio: audio_capture, - _audio_encode: audio_encode, - meter, - _sender: sender, - _congestion: congestion, - sent, - }, + Ok(Sharing { + encoders, + _feed: feed, + _input: input, + refresh, source, - )) + started, + audio, + _audio: audio_capture, + _audio_encode: audio_encode, + meter, + _sender: sender, + _congestion: congestion, + sent, + }) + } + + pub fn source(&self) -> Source { + self.source.clone() } pub fn update( @@ -376,16 +378,15 @@ fn send( let counter = counters.entry(item.layer).or_default(); let number = *counter; *counter = counter.wrapping_add(1); - for packet in fragments( + fragments( kind, item.layer, number, item.keyframe, item.timestamp_ms, &item.data, - ) { - let _ = connection.send_datagram(Bytes::from(packet)); - } + |packet| datagram::send(&connection, Bytes::copy_from_slice(packet)), + ); } } @@ -404,6 +405,7 @@ fn encode_audio( encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32); let mut pcm = vec![0.0; CHUNK_SAMPLES]; let mut payload = [0u8; VOICE_MAX_PAYLOAD]; + let mut packet = Vec::new(); let mut sequence = 0u32; while !stop.load(Ordering::Relaxed) { if samples.slots() < CHUNK_SAMPLES { @@ -417,13 +419,14 @@ fn encode_audio( let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else { continue; }; - let packet = Datagram::ShareAudio { - sequence, - timestamp_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS), - payload: &payload[..length], + packet.clear(); + Packet::ScreenAudio { + seq: sequence, + ts_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS), + opus: &payload[..length], } - .encode(); - let _ = connection.send_datagram(Bytes::from(packet)); + .encode(&mut packet); + datagram::send(&connection, Bytes::copy_from_slice(&packet)); sequence = sequence.wrapping_add(1); } } @@ -470,8 +473,8 @@ pub struct Watching { video: Arc>, health: Arc>, volume: Arc, - video_tx: Sender>, - audio_tx: Option>>, + video_tx: Sender, + audio_tx: Option>, meter: Meter, received: AtomicU64, since: Instant, @@ -553,18 +556,17 @@ impl Watching { } } - pub fn receive(&self, datagram: Datagram<'_>) { - let (timestamp_ms, tx) = match datagram { - Datagram::Video(fragment) => (fragment.timestamp_ms, Some(&self.video_tx)), - Datagram::ShareAudio { timestamp_ms, .. } => (timestamp_ms, self.audio_tx.as_ref()), - Datagram::Voice { .. } => return, + pub fn receive(&self, datagram: &Bytes, packet: &Packet<'_>) { + let (ts_ms, tx) = match packet { + Packet::Video { ts_ms, .. } => (*ts_ms, Some(&self.video_tx)), + Packet::ScreenAudio { ts_ms, .. } => (*ts_ms, self.audio_tx.as_ref()), + Packet::Voice { .. } => return, }; - self.clock.observe(timestamp_ms); - let bytes = datagram.encode(); + self.clock.observe(ts_ms); self.received - .fetch_add(bytes.len() as u64, Ordering::Relaxed); + .fetch_add((datagram.len() - RELAY_PREFIX) as u64, Ordering::Relaxed); if let Some(tx) = tx { - let _ = tx.send(bytes); + let _ = tx.send(datagram.clone()); } } @@ -685,7 +687,7 @@ fn rungs() -> &'static [Quality] { } fn watch_video( - rx: Receiver>, + rx: Receiver, clock: &Clock, video: &Mutex