From 6cc4c4cb5523666883e1e9cadea52c7140d940ae 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 08:18:01 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20apply=20share=20settings?= =?UTF-8?q?=20live=20and=20fix=20share=20stats=20and=20settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changing resolution, fps, codec or audio while sharing now updates the running share in place: the server keeps the viewers and re-picks their layers, and the client keeps its capture. Before, a change did nothing until the share was restarted. Also fixed: - the watching tab names the sharer; - keyframes are counted; - stats tiles fill the card; - the voice label stays on one line; - share settings only offer sizes the source supports; - the empty exclude heading is hidden; - software H.264 forces keyframes instead of rebuilding the encoder. The harness now runs on a private PipeWire with null devices, gets a second compositor for a third client, and has an audio round-trip check. edith_codecs now carries the cros-libva fix itself. --- Cargo.toml | 3 - crates/client/Cargo.toml | 32 ++--- crates/client/src/gui/share_view.rs | 52 +++++--- crates/client/src/gui/sidebar.rs | 4 +- crates/client/src/gui/voice_stats.rs | 48 +++++--- crates/client/src/network.rs | 75 +++++++++++- crates/client/src/settings.rs | 7 ++ crates/client/src/share/audio.rs | 1 + crates/client/src/share/encode.rs | 9 +- crates/client/src/share/session.rs | 115 ++++++++++++------ crates/server/src/request.rs | 9 +- crates/server/src/share.rs | 55 ++++++++- harness/audio.sh | 33 +++++ harness/client.sh | 2 +- harness/down.sh | 2 +- harness/niri.kdl | 3 + harness/pipewire/pipewire.conf.d/harness.conf | 8 ++ .../pipewire/wireplumber.conf.d/harness.conf | 10 ++ harness/session.sh | 52 +++++--- harness/shot.sh | 2 +- harness/ui.sh | 2 +- 21 files changed, 395 insertions(+), 129 deletions(-) create mode 100755 harness/audio.sh create mode 100644 harness/pipewire/pipewire.conf.d/harness.conf create mode 100644 harness/pipewire/wireplumber.conf.d/harness.conf diff --git a/Cargo.toml b/Cargo.toml index aed1d73..27ab7de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,3 @@ quinn = { version = "0.11.12", default-features = false, features = [ "runtime-tokio", ] } rustls = "0.23.45" - -[patch."https://github.com/chromeos/cros-libva"] -cros-libva = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 5b829e6..3089039 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,20 +9,20 @@ tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } gpui-kit = { version = "0.11.0", features = ["syntect"] } -ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } ureq = "3.5.2" bytes = "1.12.2" tracing = "0.1.44" @@ -37,8 +37,8 @@ rtrb = "0.4.1" pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } -ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } -ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } +ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" } [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 180ec7c..477d746 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -1,6 +1,6 @@ use std::{sync::Arc, time::Duration}; -use common::share::{Codec, Fps, Quality, Resolution}; +use common::share::{Codec, Fps, Quality, Resolution, Source, options}; use gpui_kit::{ Anchor, AnyElement, AppContext, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton, ObjectFit, ParentElement, RenderImage, Styled, StyledImage, @@ -122,7 +122,15 @@ impl Yumush { fn update_share(&mut self, cx: &mut Context, change: impl FnOnce(&mut ShareSettings)) { change(&mut self.settings.share); settings::save(&self.settings); - self.network.set_share_settings(self.settings.share.clone()); + if self.network.set_share_settings(self.settings.share.clone()) { + let network = self.network.clone(); + cx.spawn(async move |_, _| { + if let Err(error) = network.update_share().await { + tracing::warn!("share update failed: {error}"); + } + }) + .detach(); + } cx.notify(); } @@ -543,6 +551,7 @@ pub(super) fn share_badge( fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> Div { let settings = &yumush.settings.share; + let (resolutions, fps) = share_limits(yumush.network.share_source()); div() .w(px(320.)) @@ -558,7 +567,9 @@ fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> .child(field( "Resolution", segmented( - RESOLUTIONS, + RESOLUTIONS + .into_iter() + .filter(|(resolution, _)| resolutions.contains(resolution)), settings.top.resolution, entity, palette, @@ -569,7 +580,7 @@ fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> .child(field( "FPS", segmented( - FPS, + FPS.into_iter().filter(|(value, _)| fps.contains(value)), settings.top.fps, entity, palette, @@ -605,24 +616,33 @@ fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> .children(audio_list(entity, yumush, palette)) } +fn share_limits(source: Option) -> (Vec, Vec) { + options( + source.map_or(u32::MAX, |source| source.height), + u32::MAX, + capabilities().max_height, + ) +} + fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Option { let settings = &yumush.settings.share; match &settings.audio { ShareAudio::Off => None, ShareAudio::Everything => { - let rows = div() - .flex() - .flex_col() - .gap(px(2.)) - .children( - yumush - .share_apps - .iter() - .filter(|app| app.kind == AudioKind::App) - .map(|app| exclude_row(entity, settings, app)), - ); - Some(field("Exclude", app_list(rows), palette).into_any_element()) + let apps: Vec<&AudioApp> = yumush + .share_apps + .iter() + .filter(|app| app.kind == AudioKind::App) + .collect(); + (!apps.is_empty()).then(|| { + let rows = div() + .flex() + .flex_col() + .gap(px(2.)) + .children(apps.into_iter().map(|app| exclude_row(entity, settings, app))); + field("Exclude", app_list(rows), palette).into_any_element() + }) } ShareAudio::Source(selected) => Some( app_list(pick_list( diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 49ecc14..3adac1e 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -173,10 +173,12 @@ impl Yumush { .flex_col() .child( div() + .min_w_0() + .truncate() .text_size(text(12.)) .font_weight(FontWeight::SEMIBOLD) .text_color(palette.ok) - .child("Voice connected"), + .child("Connected"), ) .child( div() diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index 1d0bc12..16bbb24 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -176,13 +176,7 @@ fn voice_body(samples: &VecDeque, palette: Palette) -> Div { ]; column() - .child( - div() - .flex() - .flex_wrap() - .gap(px(6.)) - .children(tiles.map(|(label, value)| tile(label, value, palette))), - ) + .child(tile_grid(tiles, palette)) .child(graph( "Ping", samples @@ -220,11 +214,10 @@ fn voice_body(samples: &VecDeque, palette: Palette) -> Div { fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { let upload: u32 = layers.iter().map(|layer| layer.kbps).sum(); column() - .child(div().flex().flex_wrap().gap(px(6.)).child(tile( - "Upload", - format!("{upload} kbps"), + .child(tile_grid( + [("Upload", format!("{upload} kbps"))], palette, - ))) + )) .children(layers.iter().map(|stat| { row_line( describe(Some(stat.layer), Some(stat.engine)), @@ -236,7 +229,7 @@ fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div { column().children(watching.iter().map(|(user_id, stats)| { - let name = chat.users.get(user_id).map_or_else( + let name = chat.author(user_id).map_or_else( || user_id.chars().take(8).collect(), |user| user.username.clone(), ); @@ -249,13 +242,7 @@ fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palett ]; column() .child(row_line(name, describe(stats.layer, stats.engine), palette)) - .child( - div() - .flex() - .flex_wrap() - .gap(px(6.)) - .children(tiles.map(|(label, value)| tile(label, value, palette))), - ) + .child(tile_grid(tiles, palette)) .child(graph( "Loss", chat.share_loss @@ -323,9 +310,30 @@ fn row_line(left: String, right: String, palette: Palette) -> Div { ) } +fn tile_grid(tiles: [(&'static str, String); N], palette: Palette) -> Div { + let mut tiles: Vec
= tiles + .into_iter() + .map(|(label, value)| tile(label, value, palette).flex_1()) + .collect(); + let mut grid = div().flex().flex_col().gap(px(6.)); + while !tiles.is_empty() { + let rest = tiles.split_off(tiles.len().min(3)); + let filler = 3 - tiles.len(); + grid = grid.child( + div() + .flex() + .gap(px(6.)) + .children(tiles) + .children((0..filler).map(|_| div().flex_1())), + ); + tiles = rest; + } + grid +} + fn tile(label: &'static str, value: String, palette: Palette) -> Div { div() - .w(px(80.)) + .min_w_0() .px(px(8.)) .py(px(6.)) .flex() diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 526cdfe..a651b5f 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -25,6 +25,7 @@ use common::{ }, request::{DownloadRequest, Request, UploadHeader}, response::Response, + share::Source, validate::{ validate_attachment_name, validate_attachment_size, validate_avatar_size, validate_community_name, validate_forward, validate_message_body, validate_new_message, @@ -85,6 +86,7 @@ type SharedShareSettings = Arc>; #[derive(Default)] struct Share { sharing: Option, + source: Option, watching: HashMap, } @@ -169,6 +171,10 @@ enum Command { settings: ShareSettings, reply: oneshot::Sender>, }, + UpdateShare { + settings: ShareSettings, + reply: oneshot::Sender>, + }, } #[derive(Clone)] @@ -1372,9 +1378,17 @@ impl NetworkHandle { .await } + pub async fn update_share(&self) -> Result<(), Error> { + let settings = self.share_settings.lock().unwrap().clone(); + self.ask(|reply| Command::UpdateShare { settings, reply }) + .await + } + pub async fn stop_share(&self) -> Result<(), Error> { let result = self.done(Request::StopShare).await; - self.share.lock().unwrap().sharing.take(); + let mut share = self.share.lock().unwrap(); + share.sharing.take(); + share.source.take(); result } @@ -1382,6 +1396,10 @@ impl NetworkHandle { self.share.lock().unwrap().sharing.is_some() } + pub fn share_source(&self) -> Option { + self.share.lock().unwrap().source.clone() + } + pub async fn shares(&self, community_id: &str) -> Result, Error> { match self .request(Request::Shares { @@ -1449,12 +1467,19 @@ impl NetworkHandle { self.share.lock().unwrap().watching.get(user_id)?.frame() } - pub fn set_share_settings(&self, settings: ShareSettings) { + pub fn set_share_settings(&self, settings: ShareSettings) -> bool { + let changed = self.sharing() + && self + .share_settings + .lock() + .unwrap() + .encoding_differs(&settings); *self.share_settings.lock().unwrap() = settings.clone(); for watching in self.share.lock().unwrap().watching.values_mut() { watching.set_volume(settings.volume); watching.set_quality(settings.watch); } + changed } pub fn audio_apps(&self) -> Vec { @@ -1858,6 +1883,14 @@ async fn actor( let _ = reply.send(start_share(&connection, &share, &settings).await); }); } + Some(Command::UpdateShare { settings, reply }) => { + let connection = connection.clone(); + let share = share.clone(); + + tokio::spawn(async move { + let _ = reply.send(update_share(&connection, &share, &settings).await); + }); + } Some(Command::Upload { community_id, path, maximum, reply }) => { let connection = connection.clone(); @@ -1926,7 +1959,11 @@ async fn start_share( ) .await .map_err(Error::Network)?; - share.lock().unwrap().sharing = Some(sharing); + { + let mut share = share.lock().unwrap(); + share.sharing = Some(sharing); + share.source = Some(source.clone()); + } let result = match send(connection, &Request::StartShare { source }).await { Ok(Response::Done) => Ok(()), @@ -1934,11 +1971,41 @@ async fn start_share( Err(error) => Err(error), }; if result.is_err() { - share.lock().unwrap().sharing.take(); + let mut share = share.lock().unwrap(); + share.sharing.take(); + share.source.take(); } result } +async fn update_share( + connection: &quinn::Connection, + share: &SharedShare, + settings: &ShareSettings, +) -> Result<(), Error> { + let source = { + let mut share = share.lock().unwrap(); + let Some(sharing) = share.sharing.as_mut() else { + return Ok(()); + }; + sharing + .update( + connection, + settings.top, + settings.encode(), + settings.audio_mode(), + ) + .map_err(Error::Network)? + }; + share.lock().unwrap().source = Some(source.clone()); + + match send(connection, &Request::StartShare { source }).await { + Ok(Response::Done) => Ok(()), + Ok(_) => Err(Error::Server), + Err(error) => Err(error), + } +} + async fn event_receive_loop( connection: quinn::Connection, event_sender: mpsc::Sender, diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index ea15898..b985e7d 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -160,6 +160,13 @@ impl Default for ShareSettings { } impl ShareSettings { + pub fn encoding_differs(&self, other: &Self) -> bool { + self.top != other.top + || self.codec != other.codec + || self.audio != other.audio + || self.excluded != other.excluded + } + pub fn encode(&self) -> Vec { let capable = &capabilities().encode; match self.codec { diff --git a/crates/client/src/share/audio.rs b/crates/client/src/share/audio.rs index 36e6d67..e9e049e 100644 --- a/crates/client/src/share/audio.rs +++ b/crates/client/src/share/audio.rs @@ -1,3 +1,4 @@ +#[derive(Debug, Clone, PartialEq, Eq)] pub enum AudioMode { Everything { excluded: Vec }, Source(String), diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index 2dc192b..c0259c5 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -116,7 +116,8 @@ impl Backend { &planes.u, &planes.v, ); - report(encoder.encode(&picture)).map(|picture| (picture.au, picture.key_frame)) + report(encoder.encode_with(&picture, force)) + .map(|picture| (picture.au, picture.key_frame)) } } } @@ -247,12 +248,6 @@ fn run( } last = Some(frame.timestamp_ms); let force = request.swap(false, Ordering::Relaxed); - if force - && matches!(backend, Backend::H264(_)) - && let Some(fresh) = Backend::software(&settings) - { - backend = fresh; - } let planes = convert::bgra_to_i420(&frame, settings.width, settings.height); let Some((data, keyframe)) = backend.encode(planes, frame.timestamp_ms, force) else { continue; diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index dde4567..ca6df78 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -150,6 +150,10 @@ pub struct Sharing { encoders: Arc>, _feed: Worker, _capture: Capture, + refresh: u32, + source: Source, + started: Instant, + audio: Option, _audio: Option, _audio_encode: Option, _sender: Worker, @@ -167,6 +171,16 @@ impl Sharing { Err("screen share needs linux".into()) } + pub fn update( + &mut self, + _: &Connection, + _: Quality, + _: Vec, + _: Option, + ) -> Result { + Err("screen share needs linux".into()) + } + pub fn set_layers(&mut self, _: &[Layer]) {} pub fn keyframe(&self, _: Layer) {} @@ -178,22 +192,10 @@ impl Sharing { #[cfg(any(target_os = "linux", target_os = "windows"))] impl Sharing { - pub async fn start( - connection: Connection, - top: Quality, - encode: Vec, - audio: Option, - ) -> Result<(Sharing, Source), String> { - if encode.is_empty() { - return Err("codec unavailable".into()); - } - let mut capture = capture::open().await?; - let (resolutions, frame_rates) = options( - capture.height, - capture.refresh, - encode::capabilities().max_height, - ); - let clamped = Quality { + fn clamp(top: Quality, height: u32, refresh: u32) -> Result { + let (resolutions, frame_rates) = + options(height, refresh, encode::capabilities().max_height); + Ok(Quality { resolution: resolutions .into_iter() .filter(|resolution| *resolution <= top.resolution) @@ -204,11 +206,24 @@ impl Sharing { .filter(|fps| *fps <= top.fps) .max() .ok_or("no share fps")?, - }; + }) + } + + pub async fn start( + connection: Connection, + top: Quality, + encode: Vec, + audio: Option, + ) -> Result<(Sharing, Source), String> { + if encode.is_empty() { + return Err("codec unavailable".into()); + } + let mut capture = capture::open().await?; + let refresh = capture.refresh; let source = Source { width: capture.width, height: capture.height, - top: clamped, + top: Self::clamp(top, capture.height, refresh)?, encode, }; @@ -227,17 +242,7 @@ impl Sharing { }) }; - let (audio_capture, audio_encode) = match audio { - Some(mode) => { - let (producer, consumer) = RingBuffer::new(AUDIO_RING); - let audio_connection = connection.clone(); - let encode = Worker::spawn("share-audio-encode", move |stop| { - encode_audio(consumer, audio_connection, started, stop) - }); - (Some(audio_capture::start(mode, producer)), Some(encode)) - } - None => (None, None), - }; + let (audio_capture, audio_encode) = start_audio(&connection, started, audio.clone()); let sent = Arc::new(Mutex::new(Sent { since: Instant::now(), @@ -255,6 +260,10 @@ impl Sharing { encoders, _feed: feed, _capture: capture, + refresh, + source: source.clone(), + started, + audio, _audio: audio_capture, _audio_encode: audio_encode, _sender: sender, @@ -264,6 +273,26 @@ impl Sharing { )) } + pub fn update( + &mut self, + connection: &Connection, + top: Quality, + encode: Vec, + audio: Option, + ) -> Result { + if encode.is_empty() { + return Err("codec unavailable".into()); + } + self.source.top = Self::clamp(top, self.source.height, self.refresh)?; + self.source.encode = encode; + if self.audio != audio { + self.audio = audio.clone(); + (self._audio, self._audio_encode) = start_audio(connection, self.started, audio); + } + + Ok(self.source.clone()) + } + pub fn set_layers(&mut self, layers: &[Layer]) { lock(&self.encoders).set_layers(layers); } @@ -277,6 +306,22 @@ impl Sharing { } } +fn start_audio( + connection: &Connection, + started: Instant, + mode: Option, +) -> (Option, Option) { + let Some(mode) = mode else { + return (None, None); + }; + let (producer, consumer) = RingBuffer::new(AUDIO_RING); + let audio_connection = connection.clone(); + let encode = Worker::spawn("share-audio-encode", move |stop| { + encode_audio(consumer, audio_connection, started, stop) + }); + (Some(audio_capture::start(mode, producer)), Some(encode)) +} + fn feed( frames: Receiver, encoders: Arc>, @@ -379,6 +424,7 @@ struct Health { loss: f32, lost: bool, served: Option, + keyframes: u32, } pub struct Watching { @@ -389,7 +435,6 @@ pub struct Watching { video_tx: Sender>, audio_tx: Sender>, received: AtomicU64, - keyframes: u32, since: Instant, _video: Worker, _audio: Worker, @@ -436,7 +481,6 @@ impl Watching { video_tx, audio_tx, received: AtomicU64::new(0), - keyframes: 0, since: Instant::now(), _video: video_worker, _audio: audio_worker, @@ -485,7 +529,7 @@ impl Watching { kbps: (bytes as f32 * 8. / 1000. / seconds) as u32, fps: decoded as f32 / seconds, loss: health.loss, - keyframes: self.keyframes, + keyframes: health.keyframes, buffer_ms, } } @@ -522,7 +566,6 @@ impl Watching { }; let mut ticks = Vec::new(); if lost { - self.keyframes += 1; ticks.push(Tick::Keyframe); } let wanted = match self.quality { @@ -588,7 +631,11 @@ fn watch_video( if let Some(Datagram::Video(fragment)) = Datagram::decode(&bytes) && let Some(assembled) = reassembler.push(fragment) { - lock(health).served = Some(assembled.layer); + { + let mut health = lock(health); + health.served = Some(assembled.layer); + health.keyframes += u32::from(assembled.keyframe); + } decode_video(&mut decoder, &assembled, clock, video); } } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 35ddb11..b31185c 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -988,16 +988,17 @@ async fn dispatch( return Err(CommonError::Server.into()); }; let members = user_community::members(&community_id, &conn).await?; - share.start(&community_id, &me.id, connection.clone(), source.clone()); let event = Event::ShareStarted { - community_id, + community_id: community_id.clone(), share: Share { user_id: me.id.clone(), - source, + source: source.clone(), }, }; + let mut broadcasts = vec![broadcast(event, &members)]; + broadcasts.extend(share.start(&community_id, &me.id, connection.clone(), source)); - (Response::Done, vec![broadcast(event, &members)]) + (Response::Done, broadcasts) } Request::StopShare => { let me = authenticated(state, &conn).await?; diff --git a/crates/server/src/share.rs b/crates/server/src/share.rs index 0b6b708..2a1ddb6 100644 --- a/crates/server/src/share.rs +++ b/crates/server/src/share.rs @@ -63,6 +63,8 @@ impl Forward { struct Viewer { user_id: String, connection: Connection, + quality: Quality, + decode: Vec, forward: Forward, } @@ -103,6 +105,36 @@ fn layers_changed( (after != before).then(|| to(sharer_id, Event::ShareLayers(after.into_iter().collect()))) } +fn reroute(sharer_id: &str, sharing: &mut Sharing) -> Vec { + let before = sharing.layers(); + let Sharing { + source, viewers, .. + } = sharing; + let mut used: Vec = Vec::new(); + let mut keyframes = Vec::new(); + viewers.retain_mut(|viewer| { + let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { + return false; + }; + if !used.contains(&layer) { + used.push(layer); + } + if viewer.forward.target() != layer { + keyframes.push(to(sharer_id, Event::KeyframeWanted(layer))); + } + viewer.forward = viewer.forward.retarget(layer); + + true + }); + + let mut broadcasts: Vec = layers_changed(sharer_id, sharing, before) + .into_iter() + .collect(); + broadcasts.extend(keyframes); + + broadcasts +} + fn remove_viewer(sharer_id: &str, sharing: &mut Sharing, viewer_id: &str) -> Option { let before = sharing.layers(); sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); @@ -114,8 +146,23 @@ fn remove_viewer(sharer_id: &str, sharing: &mut Sharing, viewer_id: &str) -> Opt pub struct Shares(Arc>>); impl Shares { - pub fn start(&self, community_id: &str, user_id: &str, connection: Connection, source: Source) { - self.0.lock().unwrap().insert( + pub fn start( + &self, + community_id: &str, + user_id: &str, + connection: Connection, + source: Source, + ) -> Vec { + let mut sharings = self.0.lock().unwrap(); + if let Some(sharing) = sharings + .get_mut(user_id) + .filter(|sharing| sharing.community_id == community_id) + { + sharing.connection = connection; + sharing.source = source; + return reroute(user_id, sharing); + } + sharings.insert( user_id.to_string(), Sharing { community_id: community_id.to_string(), @@ -124,6 +171,8 @@ impl Shares { viewers: Vec::new(), }, ); + + Vec::new() } pub fn stop(&self, user_id: &str) -> Option { @@ -169,6 +218,8 @@ impl Shares { sharing.viewers.push(Viewer { user_id: viewer_id.to_string(), connection, + quality, + decode: decode.to_vec(), forward, }); let mut broadcasts: Vec = layers_changed(sharer_id, sharing, before) diff --git a/harness/audio.sh b/harness/audio.sh new file mode 100755 index 0000000..1204e9a --- /dev/null +++ b/harness/audio.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$STATE/env" +out="$STATE/audio" +mkdir -p "$out" +python3 - "$out/tone.wav" "${1:-8}" <<'PY' +import sys, wave, struct, math +w = wave.open(sys.argv[1], "wb"); w.setnchannels(2); w.setsampwidth(2); w.setframerate(48000) +v = [int(12000 * math.sin(2 * math.pi * 440 * i / 48000)) for i in range(48000 * int(sys.argv[2]))] +w.writeframes(b"".join(struct.pack(""$STATE/$NAME.log" 2>&1 & echo "$NAME $!" >> "$STATE/pids" diff --git a/harness/down.sh b/harness/down.sh index 6fcc7d0..dc65686 100755 --- a/harness/down.sh +++ b/harness/down.sh @@ -2,4 +2,4 @@ STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" [ -f "$STATE/pids" ] || exit 0 tac "$STATE/pids" | while read -r name pid; do kill "$pid" 2>/dev/null && echo "stopped $name $pid"; done -rm -f "$STATE/pids" "$STATE/env" +rm -f "$STATE/pids" "$STATE/env" "$STATE/env2" diff --git a/harness/niri.kdl b/harness/niri.kdl index 8bf3362..e16d43e 100644 --- a/harness/niri.kdl +++ b/harness/niri.kdl @@ -18,3 +18,6 @@ gestures { off } } +input { + focus-follows-mouse +} diff --git a/harness/pipewire/pipewire.conf.d/harness.conf b/harness/pipewire/pipewire.conf.d/harness.conf new file mode 100644 index 0000000..c29f52e --- /dev/null +++ b/harness/pipewire/pipewire.conf.d/harness.conf @@ -0,0 +1,8 @@ +context.objects = [ + { factory = adapter + args = { factory.name = support.null-audio-sink node.name = harness-speaker media.class = Audio/Sink audio.position = [ FL FR ] monitor.channel-volumes = true } } + { factory = adapter + args = { factory.name = support.null-audio-sink node.name = harness-app media.class = Audio/Sink audio.position = [ FL FR ] } } + { factory = adapter + args = { factory.name = support.null-audio-sink node.name = harness-mic media.class = Audio/Source/Virtual audio.position = [ FL FR ] } } +] diff --git a/harness/pipewire/wireplumber.conf.d/harness.conf b/harness/pipewire/wireplumber.conf.d/harness.conf new file mode 100644 index 0000000..84a2a85 --- /dev/null +++ b/harness/pipewire/wireplumber.conf.d/harness.conf @@ -0,0 +1,10 @@ +wireplumber.profiles = { + main = { + monitor.alsa = disabled + monitor.alsa-midi = disabled + monitor.bluez = disabled + monitor.bluez-midi = disabled + monitor.v4l2 = disabled + monitor.libcamera = disabled + } +} diff --git a/harness/session.sh b/harness/session.sh index c82e1f4..3bca4d7 100755 --- a/harness/session.sh +++ b/harness/session.sh @@ -2,22 +2,38 @@ set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" STATE="$1" -before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)" -niri --headless -c "$HERE/niri.kdl" >"$STATE/niri.log" 2>&1 & -echo "niri $!" >> "$STATE/pids" -socket="" -for _ in $(seq 100); do - socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)" - [ -n "$socket" ] && break - sleep 0.1 -done -export WAYLAND_DISPLAY="$socket" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland -export NIRI_SOCKET="$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)" -dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE NIRI_SOCKET XDG_CONFIG_HOME="$STATE/xdg" -{ - echo "export WAYLAND_DISPLAY=$WAYLAND_DISPLAY" - echo "export NIRI_SOCKET=$NIRI_SOCKET" - echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS" - echo "export XDG_CURRENT_DESKTOP=niri" -} > "$STATE/env" +mkdir -p "$STATE/pw" "$STATE/xdg/pipewire" "$STATE/xdg/wireplumber" "$STATE/wpstate" +cp -r "$HERE/pipewire/pipewire.conf.d" "$STATE/xdg/pipewire/" +cp -r "$HERE/pipewire/wireplumber.conf.d" "$STATE/xdg/wireplumber/" +export PIPEWIRE_RUNTIME_DIR="$STATE/pw" +XDG_CONFIG_HOME="$STATE/xdg" pipewire >"$STATE/pipewire.log" 2>&1 & +echo "pipewire $!" >> "$STATE/pids" +sleep 0.5 +XDG_CONFIG_HOME="$STATE/xdg" XDG_STATE_HOME="$STATE/wpstate" wireplumber >"$STATE/wireplumber.log" 2>&1 & +echo "wireplumber $!" >> "$STATE/pids" +sleep 0.5 +dbus-update-activation-environment PIPEWIRE_RUNTIME_DIR="$PIPEWIRE_RUNTIME_DIR" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland XDG_CONFIG_HOME="$STATE/xdg" +compositor() { + local before socket="" + before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)" + niri --headless -c "$HERE/niri.kdl" >"$STATE/$1.log" 2>&1 & + echo "$1 $!" >> "$STATE/pids" + for _ in $(seq 100); do + socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)" + [ -n "$socket" ] && break + sleep 0.1 + done + { + echo "export WAYLAND_DISPLAY=$socket" + echo "export NIRI_SOCKET=$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)" + echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS" + echo "export XDG_CURRENT_DESKTOP=niri" + echo "export PIPEWIRE_RUNTIME_DIR=$PIPEWIRE_RUNTIME_DIR" + } > "$STATE/$2.tmp" + mv "$STATE/$2.tmp" "$STATE/$2" +} +compositor niri2 env2 +compositor niri env +source "$STATE/env" +dbus-update-activation-environment WAYLAND_DISPLAY NIRI_SOCKET wait diff --git a/harness/shot.sh b/harness/shot.sh index 458bef8..d7fe011 100755 --- a/harness/shot.sh +++ b/harness/shot.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" -source "$STATE/env" +source "${ENV_FILE:-$STATE/env}" out="$STATE/shots/${1:-shot}.png" grim "$out" && echo "$out" diff --git a/harness/ui.sh b/harness/ui.sh index 9f5ed37..919147b 100755 --- a/harness/ui.sh +++ b/harness/ui.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" -source "$STATE/env" +source "${ENV_FILE:-$STATE/env}" to() { wlrctl pointer move -4000 -4000; wlrctl pointer move "$1" "$2"; sleep 0.1; } case "$1" in click) to "$2" "$3"; wlrctl pointer click "${4:-left}";;