forge
Explore
Log in

Don't you dare go Hollow

Apply share settings live and fix share stats and settings

Browse files at this commit

6cc4c4cb5523666883e1e9cadea52c7140d940aeAhmet Kaan GümüşParent: f550e1a
  • fix
    • apply share settings live and fix share stats and settings
Show full message
🐛 fix: apply share settings live and fix share stats and settings

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.tomlmodified+0 -3
@@ -32,6 +32,3 @@ quinn = { version = "0.11.12", default-features = false, features = [
3232 "runtime-tokio",
3333 ] }
3434 rustls = "0.23.45"
35-
36-[patch."https://github.com/chromeos/cros-libva"]
37-cros-libva = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
crates/client/Cargo.tomlmodified+16 -16
@@ -9,20 +9,20 @@ tokio.workspace = true
99 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
1010
1111 gpui-kit = { version = "0.11.0", features = ["syntect"] }
12-ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
13-ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
14-ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
15-ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
16-ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
17-ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
18-ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
19-ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
20-ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
21-ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
22-ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
23-ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
24-ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
25-ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
12+ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
13+ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
14+ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
15+ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
16+ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
17+ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
18+ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
19+ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
20+ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
21+ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
22+ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
23+ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
24+ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
25+ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
2626 ureq = "3.5.2"
2727 bytes = "1.12.2"
2828 tracing = "0.1.44"
@@ -37,8 +37,8 @@ rtrb = "0.4.1"
3737 pipewire = { version = "0.10.1", features = ["v0_3_49"] }
3838 ksni = "0.3.7"
3939 ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] }
40-ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
41-ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
40+ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
41+ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "24666c0482f23b366ea752d2eb988c41ea07657f" }
4242
4343 [target.'cfg(target_os = "windows")'.dependencies]
4444 wasapi = "0.27.0"
crates/client/src/gui/share_view.rsmodified+36 -16
@@ -1,6 +1,6 @@
11 use std::{sync::Arc, time::Duration};
22
3-use common::share::{Codec, Fps, Quality, Resolution};
3+use common::share::{Codec, Fps, Quality, Resolution, Source, options};
44 use gpui_kit::{
55 Anchor, AnyElement, AppContext, Context, Div, Entity, FontWeight, InteractiveElement,
66 IntoElement, MouseButton, ObjectFit, ParentElement, RenderImage, Styled, StyledImage,
@@ -122,7 +122,15 @@ impl Yumush {
122122 fn update_share(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut ShareSettings)) {
123123 change(&mut self.settings.share);
124124 settings::save(&self.settings);
125- self.network.set_share_settings(self.settings.share.clone());
125+ if self.network.set_share_settings(self.settings.share.clone()) {
126+ let network = self.network.clone();
127+ cx.spawn(async move |_, _| {
128+ if let Err(error) = network.update_share().await {
129+ tracing::warn!("share update failed: {error}");
130+ }
131+ })
132+ .detach();
133+ }
126134 cx.notify();
127135 }
128136
@@ -543,6 +551,7 @@ pub(super) fn share_badge(
543551
544552 fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Div {
545553 let settings = &yumush.settings.share;
554+ let (resolutions, fps) = share_limits(yumush.network.share_source());
546555
547556 div()
548557 .w(px(320.))
@@ -558,7 +567,9 @@ fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) ->
558567 .child(field(
559568 "Resolution",
560569 segmented(
561- RESOLUTIONS,
570+ RESOLUTIONS
571+ .into_iter()
572+ .filter(|(resolution, _)| resolutions.contains(resolution)),
562573 settings.top.resolution,
563574 entity,
564575 palette,
@@ -569,7 +580,7 @@ fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) ->
569580 .child(field(
570581 "FPS",
571582 segmented(
572- FPS,
583+ FPS.into_iter().filter(|(value, _)| fps.contains(value)),
573584 settings.top.fps,
574585 entity,
575586 palette,
@@ -605,24 +616,33 @@ fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) ->
605616 .children(audio_list(entity, yumush, palette))
606617 }
607618
619+fn share_limits(source: Option<Source>) -> (Vec<Resolution>, Vec<Fps>) {
620+ options(
621+ source.map_or(u32::MAX, |source| source.height),
622+ u32::MAX,
623+ capabilities().max_height,
624+ )
625+}
626+
608627 fn audio_list(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Option<AnyElement> {
609628 let settings = &yumush.settings.share;
610629
611630 match &settings.audio {
612631 ShareAudio::Off => None,
613632 ShareAudio::Everything => {
614- let rows = div()
615- .flex()
616- .flex_col()
617- .gap(px(2.))
618- .children(
619- yumush
620- .share_apps
621- .iter()
622- .filter(|app| app.kind == AudioKind::App)
623- .map(|app| exclude_row(entity, settings, app)),
624- );
625- Some(field("Exclude", app_list(rows), palette).into_any_element())
633+ let apps: Vec<&AudioApp> = yumush
634+ .share_apps
635+ .iter()
636+ .filter(|app| app.kind == AudioKind::App)
637+ .collect();
638+ (!apps.is_empty()).then(|| {
639+ let rows = div()
640+ .flex()
641+ .flex_col()
642+ .gap(px(2.))
643+ .children(apps.into_iter().map(|app| exclude_row(entity, settings, app)));
644+ field("Exclude", app_list(rows), palette).into_any_element()
645+ })
626646 }
627647 ShareAudio::Source(selected) => Some(
628648 app_list(pick_list(
crates/client/src/gui/sidebar.rsmodified+3 -1
@@ -173,10 +173,12 @@ impl Yumush {
173173 .flex_col()
174174 .child(
175175 div()
176+ .min_w_0()
177+ .truncate()
176178 .text_size(text(12.))
177179 .font_weight(FontWeight::SEMIBOLD)
178180 .text_color(palette.ok)
179- .child("Voice connected"),
181+ .child("Connected"),
180182 )
181183 .child(
182184 div()
crates/client/src/gui/voice_stats.rsmodified+28 -20
@@ -176,13 +176,7 @@ fn voice_body(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div {
176176 ];
177177
178178 column()
179- .child(
180- div()
181- .flex()
182- .flex_wrap()
183- .gap(px(6.))
184- .children(tiles.map(|(label, value)| tile(label, value, palette))),
185- )
179+ .child(tile_grid(tiles, palette))
186180 .child(graph(
187181 "Ping",
188182 samples
@@ -220,11 +214,10 @@ fn voice_body(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div {
220214 fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div {
221215 let upload: u32 = layers.iter().map(|layer| layer.kbps).sum();
222216 column()
223- .child(div().flex().flex_wrap().gap(px(6.)).child(tile(
224- "Upload",
225- format!("{upload} kbps"),
217+ .child(tile_grid(
218+ [("Upload", format!("{upload} kbps"))],
226219 palette,
227- )))
220+ ))
228221 .children(layers.iter().map(|stat| {
229222 row_line(
230223 describe(Some(stat.layer), Some(stat.engine)),
@@ -236,7 +229,7 @@ fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div {
236229
237230 fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div {
238231 column().children(watching.iter().map(|(user_id, stats)| {
239- let name = chat.users.get(user_id).map_or_else(
232+ let name = chat.author(user_id).map_or_else(
240233 || user_id.chars().take(8).collect(),
241234 |user| user.username.clone(),
242235 );
@@ -249,13 +242,7 @@ fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palett
249242 ];
250243 column()
251244 .child(row_line(name, describe(stats.layer, stats.engine), palette))
252- .child(
253- div()
254- .flex()
255- .flex_wrap()
256- .gap(px(6.))
257- .children(tiles.map(|(label, value)| tile(label, value, palette))),
258- )
245+ .child(tile_grid(tiles, palette))
259246 .child(graph(
260247 "Loss",
261248 chat.share_loss
@@ -323,9 +310,30 @@ fn row_line(left: String, right: String, palette: Palette) -> Div {
323310 )
324311 }
325312
313+fn tile_grid<const N: usize>(tiles: [(&'static str, String); N], palette: Palette) -> Div {
314+ let mut tiles: Vec<Div> = tiles
315+ .into_iter()
316+ .map(|(label, value)| tile(label, value, palette).flex_1())
317+ .collect();
318+ let mut grid = div().flex().flex_col().gap(px(6.));
319+ while !tiles.is_empty() {
320+ let rest = tiles.split_off(tiles.len().min(3));
321+ let filler = 3 - tiles.len();
322+ grid = grid.child(
323+ div()
324+ .flex()
325+ .gap(px(6.))
326+ .children(tiles)
327+ .children((0..filler).map(|_| div().flex_1())),
328+ );
329+ tiles = rest;
330+ }
331+ grid
332+}
333+
326334 fn tile(label: &'static str, value: String, palette: Palette) -> Div {
327335 div()
328- .w(px(80.))
336+ .min_w_0()
329337 .px(px(8.))
330338 .py(px(6.))
331339 .flex()
crates/client/src/network.rsmodified+71 -4
@@ -25,6 +25,7 @@ use common::{
2525 },
2626 request::{DownloadRequest, Request, UploadHeader},
2727 response::Response,
28+ share::Source,
2829 validate::{
2930 validate_attachment_name, validate_attachment_size, validate_avatar_size,
3031 validate_community_name, validate_forward, validate_message_body, validate_new_message,
@@ -85,6 +86,7 @@ type SharedShareSettings = Arc<Mutex<ShareSettings>>;
8586 #[derive(Default)]
8687 struct Share {
8788 sharing: Option<Sharing>,
89+ source: Option<Source>,
8890 watching: HashMap<String, Watching>,
8991 }
9092
@@ -169,6 +171,10 @@ enum Command {
169171 settings: ShareSettings,
170172 reply: oneshot::Sender<Result<(), Error>>,
171173 },
174+ UpdateShare {
175+ settings: ShareSettings,
176+ reply: oneshot::Sender<Result<(), Error>>,
177+ },
172178 }
173179
174180 #[derive(Clone)]
@@ -1372,9 +1378,17 @@ impl NetworkHandle {
13721378 .await
13731379 }
13741380
1381+ pub async fn update_share(&self) -> Result<(), Error> {
1382+ let settings = self.share_settings.lock().unwrap().clone();
1383+ self.ask(|reply| Command::UpdateShare { settings, reply })
1384+ .await
1385+ }
1386+
13751387 pub async fn stop_share(&self) -> Result<(), Error> {
13761388 let result = self.done(Request::StopShare).await;
1377- self.share.lock().unwrap().sharing.take();
1389+ let mut share = self.share.lock().unwrap();
1390+ share.sharing.take();
1391+ share.source.take();
13781392 result
13791393 }
13801394
@@ -1382,6 +1396,10 @@ impl NetworkHandle {
13821396 self.share.lock().unwrap().sharing.is_some()
13831397 }
13841398
1399+ pub fn share_source(&self) -> Option<Source> {
1400+ self.share.lock().unwrap().source.clone()
1401+ }
1402+
13851403 pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Error> {
13861404 match self
13871405 .request(Request::Shares {
@@ -1449,12 +1467,19 @@ impl NetworkHandle {
14491467 self.share.lock().unwrap().watching.get(user_id)?.frame()
14501468 }
14511469
1452- pub fn set_share_settings(&self, settings: ShareSettings) {
1470+ pub fn set_share_settings(&self, settings: ShareSettings) -> bool {
1471+ let changed = self.sharing()
1472+ && self
1473+ .share_settings
1474+ .lock()
1475+ .unwrap()
1476+ .encoding_differs(&settings);
14531477 *self.share_settings.lock().unwrap() = settings.clone();
14541478 for watching in self.share.lock().unwrap().watching.values_mut() {
14551479 watching.set_volume(settings.volume);
14561480 watching.set_quality(settings.watch);
14571481 }
1482+ changed
14581483 }
14591484
14601485 pub fn audio_apps(&self) -> Vec<AudioApp> {
@@ -1858,6 +1883,14 @@ async fn actor(
18581883 let _ = reply.send(start_share(&connection, &share, &settings).await);
18591884 });
18601885 }
1886+ Some(Command::UpdateShare { settings, reply }) => {
1887+ let connection = connection.clone();
1888+ let share = share.clone();
1889+
1890+ tokio::spawn(async move {
1891+ let _ = reply.send(update_share(&connection, &share, &settings).await);
1892+ });
1893+ }
18611894 Some(Command::Upload { community_id, path, maximum, reply }) => {
18621895 let connection = connection.clone();
18631896
@@ -1926,7 +1959,11 @@ async fn start_share(
19261959 )
19271960 .await
19281961 .map_err(Error::Network)?;
1929- share.lock().unwrap().sharing = Some(sharing);
1962+ {
1963+ let mut share = share.lock().unwrap();
1964+ share.sharing = Some(sharing);
1965+ share.source = Some(source.clone());
1966+ }
19301967
19311968 let result = match send(connection, &Request::StartShare { source }).await {
19321969 Ok(Response::Done) => Ok(()),
@@ -1934,11 +1971,41 @@ async fn start_share(
19341971 Err(error) => Err(error),
19351972 };
19361973 if result.is_err() {
1937- share.lock().unwrap().sharing.take();
1974+ let mut share = share.lock().unwrap();
1975+ share.sharing.take();
1976+ share.source.take();
19381977 }
19391978 result
19401979 }
19411980
1981+async fn update_share(
1982+ connection: &quinn::Connection,
1983+ share: &SharedShare,
1984+ settings: &ShareSettings,
1985+) -> Result<(), Error> {
1986+ let source = {
1987+ let mut share = share.lock().unwrap();
1988+ let Some(sharing) = share.sharing.as_mut() else {
1989+ return Ok(());
1990+ };
1991+ sharing
1992+ .update(
1993+ connection,
1994+ settings.top,
1995+ settings.encode(),
1996+ settings.audio_mode(),
1997+ )
1998+ .map_err(Error::Network)?
1999+ };
2000+ share.lock().unwrap().source = Some(source.clone());
2001+
2002+ match send(connection, &Request::StartShare { source }).await {
2003+ Ok(Response::Done) => Ok(()),
2004+ Ok(_) => Err(Error::Server),
2005+ Err(error) => Err(error),
2006+ }
2007+}
2008+
19422009 async fn event_receive_loop(
19432010 connection: quinn::Connection,
19442011 event_sender: mpsc::Sender<NetworkEvent>,
crates/client/src/settings.rsmodified+7 -0
@@ -160,6 +160,13 @@ impl Default for ShareSettings {
160160 }
161161
162162 impl ShareSettings {
163+ pub fn encoding_differs(&self, other: &Self) -> bool {
164+ self.top != other.top
165+ || self.codec != other.codec
166+ || self.audio != other.audio
167+ || self.excluded != other.excluded
168+ }
169+
163170 pub fn encode(&self) -> Vec<Codec> {
164171 let capable = &capabilities().encode;
165172 match self.codec {
crates/client/src/share/audio.rsmodified+1 -0
@@ -1,3 +1,4 @@
1+#[derive(Debug, Clone, PartialEq, Eq)]
12 pub enum AudioMode {
23 Everything { excluded: Vec<String> },
34 Source(String),
crates/client/src/share/encode.rsmodified+2 -7
@@ -116,7 +116,8 @@ impl Backend {
116116 &planes.u,
117117 &planes.v,
118118 );
119- report(encoder.encode(&picture)).map(|picture| (picture.au, picture.key_frame))
119+ report(encoder.encode_with(&picture, force))
120+ .map(|picture| (picture.au, picture.key_frame))
120121 }
121122 }
122123 }
@@ -247,12 +248,6 @@ fn run(
247248 }
248249 last = Some(frame.timestamp_ms);
249250 let force = request.swap(false, Ordering::Relaxed);
250- if force
251- && matches!(backend, Backend::H264(_))
252- && let Some(fresh) = Backend::software(&settings)
253- {
254- backend = fresh;
255- }
256251 let planes = convert::bgra_to_i420(&frame, settings.width, settings.height);
257252 let Some((data, keyframe)) = backend.encode(planes, frame.timestamp_ms, force) else {
258253 continue;
crates/client/src/share/session.rsmodified+81 -34
@@ -150,6 +150,10 @@ pub struct Sharing {
150150 encoders: Arc<Mutex<Encoders>>,
151151 _feed: Worker,
152152 _capture: Capture,
153+ refresh: u32,
154+ source: Source,
155+ started: Instant,
156+ audio: Option<AudioMode>,
153157 _audio: Option<AudioCapture>,
154158 _audio_encode: Option<Worker>,
155159 _sender: Worker,
@@ -167,6 +171,16 @@ impl Sharing {
167171 Err("screen share needs linux".into())
168172 }
169173
174+ pub fn update(
175+ &mut self,
176+ _: &Connection,
177+ _: Quality,
178+ _: Vec<Codec>,
179+ _: Option<AudioMode>,
180+ ) -> Result<Source, String> {
181+ Err("screen share needs linux".into())
182+ }
183+
170184 pub fn set_layers(&mut self, _: &[Layer]) {}
171185
172186 pub fn keyframe(&self, _: Layer) {}
@@ -178,22 +192,10 @@ impl Sharing {
178192
179193 #[cfg(any(target_os = "linux", target_os = "windows"))]
180194 impl Sharing {
181- pub async fn start(
182- connection: Connection,
183- top: Quality,
184- encode: Vec<Codec>,
185- audio: Option<AudioMode>,
186- ) -> Result<(Sharing, Source), String> {
187- if encode.is_empty() {
188- return Err("codec unavailable".into());
189- }
190- let mut capture = capture::open().await?;
191- let (resolutions, frame_rates) = options(
192- capture.height,
193- capture.refresh,
194- encode::capabilities().max_height,
195- );
196- let clamped = Quality {
195+ fn clamp(top: Quality, height: u32, refresh: u32) -> Result<Quality, String> {
196+ let (resolutions, frame_rates) =
197+ options(height, refresh, encode::capabilities().max_height);
198+ Ok(Quality {
197199 resolution: resolutions
198200 .into_iter()
199201 .filter(|resolution| *resolution <= top.resolution)
@@ -204,11 +206,24 @@ impl Sharing {
204206 .filter(|fps| *fps <= top.fps)
205207 .max()
206208 .ok_or("no share fps")?,
207- };
209+ })
210+ }
211+
212+ pub async fn start(
213+ connection: Connection,
214+ top: Quality,
215+ encode: Vec<Codec>,
216+ audio: Option<AudioMode>,
217+ ) -> Result<(Sharing, Source), String> {
218+ if encode.is_empty() {
219+ return Err("codec unavailable".into());
220+ }
221+ let mut capture = capture::open().await?;
222+ let refresh = capture.refresh;
208223 let source = Source {
209224 width: capture.width,
210225 height: capture.height,
211- top: clamped,
226+ top: Self::clamp(top, capture.height, refresh)?,
212227 encode,
213228 };
214229
@@ -227,17 +242,7 @@ impl Sharing {
227242 })
228243 };
229244
230- let (audio_capture, audio_encode) = match audio {
231- Some(mode) => {
232- let (producer, consumer) = RingBuffer::new(AUDIO_RING);
233- let audio_connection = connection.clone();
234- let encode = Worker::spawn("share-audio-encode", move |stop| {
235- encode_audio(consumer, audio_connection, started, stop)
236- });
237- (Some(audio_capture::start(mode, producer)), Some(encode))
238- }
239- None => (None, None),
240- };
245+ let (audio_capture, audio_encode) = start_audio(&connection, started, audio.clone());
241246
242247 let sent = Arc::new(Mutex::new(Sent {
243248 since: Instant::now(),
@@ -255,6 +260,10 @@ impl Sharing {
255260 encoders,
256261 _feed: feed,
257262 _capture: capture,
263+ refresh,
264+ source: source.clone(),
265+ started,
266+ audio,
258267 _audio: audio_capture,
259268 _audio_encode: audio_encode,
260269 _sender: sender,
@@ -264,6 +273,26 @@ impl Sharing {
264273 ))
265274 }
266275
276+ pub fn update(
277+ &mut self,
278+ connection: &Connection,
279+ top: Quality,
280+ encode: Vec<Codec>,
281+ audio: Option<AudioMode>,
282+ ) -> Result<Source, String> {
283+ if encode.is_empty() {
284+ return Err("codec unavailable".into());
285+ }
286+ self.source.top = Self::clamp(top, self.source.height, self.refresh)?;
287+ self.source.encode = encode;
288+ if self.audio != audio {
289+ self.audio = audio.clone();
290+ (self._audio, self._audio_encode) = start_audio(connection, self.started, audio);
291+ }
292+
293+ Ok(self.source.clone())
294+ }
295+
267296 pub fn set_layers(&mut self, layers: &[Layer]) {
268297 lock(&self.encoders).set_layers(layers);
269298 }
@@ -277,6 +306,22 @@ impl Sharing {
277306 }
278307 }
279308
309+fn start_audio(
310+ connection: &Connection,
311+ started: Instant,
312+ mode: Option<AudioMode>,
313+) -> (Option<AudioCapture>, Option<Worker>) {
314+ let Some(mode) = mode else {
315+ return (None, None);
316+ };
317+ let (producer, consumer) = RingBuffer::new(AUDIO_RING);
318+ let audio_connection = connection.clone();
319+ let encode = Worker::spawn("share-audio-encode", move |stop| {
320+ encode_audio(consumer, audio_connection, started, stop)
321+ });
322+ (Some(audio_capture::start(mode, producer)), Some(encode))
323+}
324+
280325 fn feed(
281326 frames: Receiver<Frame>,
282327 encoders: Arc<Mutex<Encoders>>,
@@ -379,6 +424,7 @@ struct Health {
379424 loss: f32,
380425 lost: bool,
381426 served: Option<Layer>,
427+ keyframes: u32,
382428 }
383429
384430 pub struct Watching {
@@ -389,7 +435,6 @@ pub struct Watching {
389435 video_tx: Sender<Vec<u8>>,
390436 audio_tx: Sender<Vec<u8>>,
391437 received: AtomicU64,
392- keyframes: u32,
393438 since: Instant,
394439 _video: Worker,
395440 _audio: Worker,
@@ -436,7 +481,6 @@ impl Watching {
436481 video_tx,
437482 audio_tx,
438483 received: AtomicU64::new(0),
439- keyframes: 0,
440484 since: Instant::now(),
441485 _video: video_worker,
442486 _audio: audio_worker,
@@ -485,7 +529,7 @@ impl Watching {
485529 kbps: (bytes as f32 * 8. / 1000. / seconds) as u32,
486530 fps: decoded as f32 / seconds,
487531 loss: health.loss,
488- keyframes: self.keyframes,
532+ keyframes: health.keyframes,
489533 buffer_ms,
490534 }
491535 }
@@ -522,7 +566,6 @@ impl Watching {
522566 };
523567 let mut ticks = Vec::new();
524568 if lost {
525- self.keyframes += 1;
526569 ticks.push(Tick::Keyframe);
527570 }
528571 let wanted = match self.quality {
@@ -588,7 +631,11 @@ fn watch_video(
588631 if let Some(Datagram::Video(fragment)) = Datagram::decode(&bytes)
589632 && let Some(assembled) = reassembler.push(fragment)
590633 {
591- lock(health).served = Some(assembled.layer);
634+ {
635+ let mut health = lock(health);
636+ health.served = Some(assembled.layer);
637+ health.keyframes += u32::from(assembled.keyframe);
638+ }
592639 decode_video(&mut decoder, &assembled, clock, video);
593640 }
594641 }
crates/server/src/request.rsmodified+5 -4
@@ -988,16 +988,17 @@ async fn dispatch(
988988 return Err(CommonError::Server.into());
989989 };
990990 let members = user_community::members(&community_id, &conn).await?;
991- share.start(&community_id, &me.id, connection.clone(), source.clone());
992991 let event = Event::ShareStarted {
993- community_id,
992+ community_id: community_id.clone(),
994993 share: Share {
995994 user_id: me.id.clone(),
996- source,
995+ source: source.clone(),
997996 },
998997 };
998+ let mut broadcasts = vec![broadcast(event, &members)];
999+ broadcasts.extend(share.start(&community_id, &me.id, connection.clone(), source));
9991000
1000- (Response::Done, vec![broadcast(event, &members)])
1001+ (Response::Done, broadcasts)
10011002 }
10021003 Request::StopShare => {
10031004 let me = authenticated(state, &conn).await?;
crates/server/src/share.rsmodified+53 -2
@@ -63,6 +63,8 @@ impl Forward {
6363 struct Viewer {
6464 user_id: String,
6565 connection: Connection,
66+ quality: Quality,
67+ decode: Vec<Codec>,
6668 forward: Forward,
6769 }
6870
@@ -103,6 +105,36 @@ fn layers_changed(
103105 (after != before).then(|| to(sharer_id, Event::ShareLayers(after.into_iter().collect())))
104106 }
105107
108+fn reroute(sharer_id: &str, sharing: &mut Sharing) -> Vec<Broadcast> {
109+ let before = sharing.layers();
110+ let Sharing {
111+ source, viewers, ..
112+ } = sharing;
113+ let mut used: Vec<Layer> = Vec::new();
114+ let mut keyframes = Vec::new();
115+ viewers.retain_mut(|viewer| {
116+ let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else {
117+ return false;
118+ };
119+ if !used.contains(&layer) {
120+ used.push(layer);
121+ }
122+ if viewer.forward.target() != layer {
123+ keyframes.push(to(sharer_id, Event::KeyframeWanted(layer)));
124+ }
125+ viewer.forward = viewer.forward.retarget(layer);
126+
127+ true
128+ });
129+
130+ let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_id, sharing, before)
131+ .into_iter()
132+ .collect();
133+ broadcasts.extend(keyframes);
134+
135+ broadcasts
136+}
137+
106138 fn remove_viewer(sharer_id: &str, sharing: &mut Sharing, viewer_id: &str) -> Option<Broadcast> {
107139 let before = sharing.layers();
108140 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
114146 pub struct Shares(Arc<Mutex<BTreeMap<String, Sharing>>>);
115147
116148 impl Shares {
117- pub fn start(&self, community_id: &str, user_id: &str, connection: Connection, source: Source) {
118- self.0.lock().unwrap().insert(
149+ pub fn start(
150+ &self,
151+ community_id: &str,
152+ user_id: &str,
153+ connection: Connection,
154+ source: Source,
155+ ) -> Vec<Broadcast> {
156+ let mut sharings = self.0.lock().unwrap();
157+ if let Some(sharing) = sharings
158+ .get_mut(user_id)
159+ .filter(|sharing| sharing.community_id == community_id)
160+ {
161+ sharing.connection = connection;
162+ sharing.source = source;
163+ return reroute(user_id, sharing);
164+ }
165+ sharings.insert(
119166 user_id.to_string(),
120167 Sharing {
121168 community_id: community_id.to_string(),
@@ -124,6 +171,8 @@ impl Shares {
124171 viewers: Vec::new(),
125172 },
126173 );
174+
175+ Vec::new()
127176 }
128177
129178 pub fn stop(&self, user_id: &str) -> Option<String> {
@@ -169,6 +218,8 @@ impl Shares {
169218 sharing.viewers.push(Viewer {
170219 user_id: viewer_id.to_string(),
171220 connection,
221+ quality,
222+ decode: decode.to_vec(),
172223 forward,
173224 });
174225 let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_id, sharing, before)
harness/audio.shadded+33 -0
@@ -0,0 +1,33 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
4+source "$STATE/env"
5+out="$STATE/audio"
6+mkdir -p "$out"
7+python3 - "$out/tone.wav" "${1:-8}" <<'PY'
8+import sys, wave, struct, math
9+w = wave.open(sys.argv[1], "wb"); w.setnchannels(2); w.setsampwidth(2); w.setframerate(48000)
10+v = [int(12000 * math.sin(2 * math.pi * 440 * i / 48000)) for i in range(48000 * int(sys.argv[2]))]
11+w.writeframes(b"".join(struct.pack("<hh", a, a) for a in v))
12+PY
13+pw-play --target harness-app "$out/tone.wav" &
14+player=$!
15+sleep 2
16+timeout 4 pw-record --target harness-speaker -P '{ stream.capture.sink = true }' "$out/speaker.wav" || true
17+wait "$player" || true
18+python3 - "$out/speaker.wav" <<'PY'
19+import sys, wave, struct, math
20+w = wave.open(sys.argv[1])
21+n = w.getnframes(); ch = w.getnchannels(); width = w.getsampwidth()
22+raw = w.readframes(n)
23+fmt = {2: "h", 4: "i"}[width]
24+s = struct.unpack("<" + fmt * (len(raw) // width), raw)[::ch]
25+scale = float(1 << (8 * width - 1))
26+x = [v / scale for v in s[: 48000 * 2]]
27+def power(f):
28+ re = sum(v * math.cos(2 * math.pi * f * i / 48000) for i, v in enumerate(x))
29+ im = sum(v * math.sin(2 * math.pi * f * i / 48000) for i, v in enumerate(x))
30+ return math.hypot(re, im) / max(len(x), 1)
31+rms = math.sqrt(sum(v * v for v in x) / max(len(x), 1))
32+print(f"rms {rms:.4f} 440Hz {power(440):.4f} 1000Hz {power(1000):.4f}")
33+PY
harness/client.shmodified+1 -1
@@ -4,7 +4,7 @@ HERE="$(cd "$(dirname "$0")" && pwd)"
44 ROOT="$(dirname "$HERE")"
55 STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
66 NAME="$1"
7-source "$STATE/env"
7+source "${ENV_FILE:-$STATE/env}"
88 mkdir -p "$STATE/clients/$NAME"
99 XDG_CONFIG_HOME="$STATE/clients/$NAME" RUST_LOG="${RUST_LOG:-info}" "$ROOT/target/${PROFILE:-harness}/client" >"$STATE/$NAME.log" 2>&1 &
1010 echo "$NAME $!" >> "$STATE/pids"
harness/down.shmodified+1 -1
@@ -2,4 +2,4 @@
22 STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
33 [ -f "$STATE/pids" ] || exit 0
44 tac "$STATE/pids" | while read -r name pid; do kill "$pid" 2>/dev/null && echo "stopped $name $pid"; done
5-rm -f "$STATE/pids" "$STATE/env"
5+rm -f "$STATE/pids" "$STATE/env" "$STATE/env2"
harness/niri.kdlmodified+3 -0
@@ -18,3 +18,6 @@ gestures {
1818 off
1919 }
2020 }
21+input {
22+ focus-follows-mouse
23+}
harness/pipewire/pipewire.conf.d/harness.confadded+8 -0
@@ -0,0 +1,8 @@
1+context.objects = [
2+ { factory = adapter
3+ args = { factory.name = support.null-audio-sink node.name = harness-speaker media.class = Audio/Sink audio.position = [ FL FR ] monitor.channel-volumes = true } }
4+ { factory = adapter
5+ args = { factory.name = support.null-audio-sink node.name = harness-app media.class = Audio/Sink audio.position = [ FL FR ] } }
6+ { factory = adapter
7+ args = { factory.name = support.null-audio-sink node.name = harness-mic media.class = Audio/Source/Virtual audio.position = [ FL FR ] } }
8+]
harness/pipewire/wireplumber.conf.d/harness.confadded+10 -0
@@ -0,0 +1,10 @@
1+wireplumber.profiles = {
2+ main = {
3+ monitor.alsa = disabled
4+ monitor.alsa-midi = disabled
5+ monitor.bluez = disabled
6+ monitor.bluez-midi = disabled
7+ monitor.v4l2 = disabled
8+ monitor.libcamera = disabled
9+ }
10+}
harness/session.shmodified+34 -18
@@ -2,22 +2,38 @@
22 set -euo pipefail
33 HERE="$(cd "$(dirname "$0")" && pwd)"
44 STATE="$1"
5-before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)"
6-niri --headless -c "$HERE/niri.kdl" >"$STATE/niri.log" 2>&1 &
7-echo "niri $!" >> "$STATE/pids"
8-socket=""
9-for _ in $(seq 100); do
10- socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)"
11- [ -n "$socket" ] && break
12- sleep 0.1
13-done
14-export WAYLAND_DISPLAY="$socket" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland
15-export NIRI_SOCKET="$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)"
16-dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE NIRI_SOCKET XDG_CONFIG_HOME="$STATE/xdg"
17-{
18- echo "export WAYLAND_DISPLAY=$WAYLAND_DISPLAY"
19- echo "export NIRI_SOCKET=$NIRI_SOCKET"
20- echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS"
21- echo "export XDG_CURRENT_DESKTOP=niri"
22-} > "$STATE/env"
5+mkdir -p "$STATE/pw" "$STATE/xdg/pipewire" "$STATE/xdg/wireplumber" "$STATE/wpstate"
6+cp -r "$HERE/pipewire/pipewire.conf.d" "$STATE/xdg/pipewire/"
7+cp -r "$HERE/pipewire/wireplumber.conf.d" "$STATE/xdg/wireplumber/"
8+export PIPEWIRE_RUNTIME_DIR="$STATE/pw"
9+XDG_CONFIG_HOME="$STATE/xdg" pipewire >"$STATE/pipewire.log" 2>&1 &
10+echo "pipewire $!" >> "$STATE/pids"
11+sleep 0.5
12+XDG_CONFIG_HOME="$STATE/xdg" XDG_STATE_HOME="$STATE/wpstate" wireplumber >"$STATE/wireplumber.log" 2>&1 &
13+echo "wireplumber $!" >> "$STATE/pids"
14+sleep 0.5
15+dbus-update-activation-environment PIPEWIRE_RUNTIME_DIR="$PIPEWIRE_RUNTIME_DIR" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland XDG_CONFIG_HOME="$STATE/xdg"
16+compositor() {
17+ local before socket=""
18+ before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)"
19+ niri --headless -c "$HERE/niri.kdl" >"$STATE/$1.log" 2>&1 &
20+ echo "$1 $!" >> "$STATE/pids"
21+ for _ in $(seq 100); do
22+ socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)"
23+ [ -n "$socket" ] && break
24+ sleep 0.1
25+ done
26+ {
27+ echo "export WAYLAND_DISPLAY=$socket"
28+ echo "export NIRI_SOCKET=$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)"
29+ echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS"
30+ echo "export XDG_CURRENT_DESKTOP=niri"
31+ echo "export PIPEWIRE_RUNTIME_DIR=$PIPEWIRE_RUNTIME_DIR"
32+ } > "$STATE/$2.tmp"
33+ mv "$STATE/$2.tmp" "$STATE/$2"
34+}
35+compositor niri2 env2
36+compositor niri env
37+source "$STATE/env"
38+dbus-update-activation-environment WAYLAND_DISPLAY NIRI_SOCKET
2339 wait
harness/shot.shmodified+1 -1
@@ -1,5 +1,5 @@
11 #!/usr/bin/env bash
22 STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
3-source "$STATE/env"
3+source "${ENV_FILE:-$STATE/env}"
44 out="$STATE/shots/${1:-shot}.png"
55 grim "$out" && echo "$out"
harness/ui.shmodified+1 -1
@@ -1,7 +1,7 @@
11 #!/usr/bin/env bash
22 set -euo pipefail
33 STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
4-source "$STATE/env"
4+source "${ENV_FILE:-$STATE/env}"
55 to() { wlrctl pointer move -4000 -4000; wlrctl pointer move "$1" "$2"; sleep 0.1; }
66 case "$1" in
77 click) to "$2" "$3"; wlrctl pointer click "${4:-left}";;