diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index cea305b..0bf1398 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -630,6 +630,8 @@ pub struct Yumush { backups: Vec, pending_backup_delete: Option, share_apps: Vec, + share_apps_seen: std::cell::Cell, + share_apps_task: Option>, share_tab: common::share::Kind, camera_modes: Vec, fullscreen: bool, @@ -694,6 +696,8 @@ impl Yumush { backups: Vec::new(), pending_backup_delete: None, share_apps: Vec::new(), + share_apps_seen: std::cell::Cell::new(Instant::now()), + share_apps_task: None, share_tab: common::share::Kind::Screen, camera_modes: Vec::new(), fullscreen: false, diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index 14ef6a1..88c7d7b 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -510,6 +510,8 @@ pub(super) fn tile_label(yumush: &Yumush, palette: Palette, (user_id, kind): (Id .px(px(8.)) .rounded(px(12.)) .bg(gpui_kit::black().opacity(0.72)) + .border_1() + .border_color(palette.tinted(user_id).opacity(0.7)) .flex() .items_center() .gap(px(6.)) @@ -522,8 +524,8 @@ pub(super) fn tile_label(yumush: &Yumush, palette: Palette, (user_id, kind): (Id })) .child( div() - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tinted(user_id)) + .font_weight(FontWeight::MEDIUM) + .text_color(gpui_kit::white().opacity(0.95)) .child(name.to_string()), ) .children(wave.map(|history| mini_wave(history, 10., palette.ok))) diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index d480f9d..b0a9468 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -42,13 +42,15 @@ use super::{ use crate::{ settings::{self, ShareAudio, ShareCodec, ShareSettings}, share::{ - audio::{AudioApp, AudioKind}, + audio::{AudioApp, AudioKind, is_excluded, is_picked}, encode::capabilities, session::WatchQuality, }, }; const BAR_TTL: Duration = Duration::from_millis(2500); +const APPS_REFRESH: Duration = Duration::from_secs(2); +const APPS_IDLE: Duration = Duration::from_secs(5); const RESOLUTIONS: [(Resolution, &str); 6] = [ (Resolution::P360, "360"), @@ -85,11 +87,31 @@ impl AudioMode { match audio { ShareAudio::Off => Self::Off, ShareAudio::Everything => Self::Everything, - ShareAudio::Source(_) => Self::App, + ShareAudio::App { .. } | ShareAudio::Device(_) => Self::App, } } } +fn pick(app: &AudioApp) -> ShareAudio { + match app.kind { + AudioKind::App => ShareAudio::App { + name: app.name.clone(), + pid: app.pid, + }, + AudioKind::Output | AudioKind::Input => ShareAudio::Device(app.node.clone()), + } +} + +fn chosen(audio: &ShareAudio, app: &AudioApp) -> bool { + match audio { + ShareAudio::App { name, pid } => { + app.kind == AudioKind::App && is_picked((name, *pid), &app.name, app.pid) + } + ShareAudio::Device(node) => app.kind != AudioKind::App && *node == app.node, + _ => false, + } +} + pub(super) struct Viewer { user_id: Id, kind: Kind, @@ -166,20 +188,33 @@ impl Yumush { cx.notify(); } - pub(super) fn refresh_share_apps(&self, cx: &mut Context) { + pub(super) fn refresh_share_apps(&mut self, cx: &mut Context) { + self.share_apps_seen.set(Instant::now()); + if self.share_apps_task.is_some() { + return; + } let network = self.network.clone(); - - cx.spawn(async move |this, cx| { - let apps = cx - .background_executor() - .spawn(async move { network.audio_apps() }) - .await; - let _ = this.update(cx, |yumush, cx| { - yumush.share_apps = apps; - cx.notify(); - }); - }) - .detach(); + self.share_apps_task = Some(cx.spawn(async move |this, cx| { + loop { + let network = network.clone(); + let apps = cx + .background_executor() + .spawn(async move { network.audio_apps() }) + .await; + let shown = this + .update(cx, |yumush, cx| { + yumush.share_apps = apps; + cx.notify(); + yumush.share_apps_seen.get().elapsed() < APPS_IDLE + }) + .unwrap_or(false); + if !shown { + let _ = this.update(cx, |yumush, _| yumush.share_apps_task = None); + return; + } + cx.background_executor().timer(APPS_REFRESH).await; + } + })); } fn refresh_camera_modes(&self, cx: &mut Context) { @@ -224,26 +259,46 @@ impl Yumush { let audio = match (mode, self.share_apps.first()) { (AudioMode::Off, _) => ShareAudio::Off, (AudioMode::Everything, _) => ShareAudio::Everything, - (AudioMode::App, Some(app)) => ShareAudio::Source(app.node.clone()), + (AudioMode::App, Some(app)) => pick(app), (AudioMode::App, None) => return, }; self.update_share(cx, |settings| settings.audio = audio); } - pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context) { - self.update_share(cx, |settings| settings.audio = ShareAudio::Source(node)); + pub(super) fn set_share_source(&mut self, app: &AudioApp, cx: &mut Context) { + let audio = pick(app); + self.update_share(cx, |settings| settings.audio = audio); } - pub(super) fn set_share_excluded( + pub(super) fn set_share_included( &mut self, - name: String, - excluded: bool, + app: &AudioApp, + included: bool, cx: &mut Context, ) { + let siblings: Vec = self + .share_apps + .iter() + .filter(|other| other.kind == AudioKind::App && other.name == app.name) + .map(AudioApp::key) + .collect(); + let name = app.name.clone(); + let key = app.key(); self.update_share(cx, |settings| { - settings.excluded.retain(|app| *app != name); - if excluded { - settings.excluded.push(name); + let excluded = &mut settings.excluded; + let app_off = excluded.contains(&name); + excluded.retain(|entry| *entry != name && *entry != key); + match (included, siblings.len() > 1) { + (false, false) => excluded.push(name), + (false, true) => excluded.push(key), + (true, true) if app_off => { + let others: Vec = siblings + .into_iter() + .filter(|sibling| *sibling != key && !excluded.contains(sibling)) + .collect(); + excluded.extend(others); + } + (true, _) => {} } }); } @@ -747,10 +802,12 @@ fn share_modes(yumush: &Yumush, kind: Kind) -> Vec { } fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Option { + yumush.share_apps_seen.set(Instant::now()); let settings = &yumush.settings.share; match &settings.audio { ShareAudio::Off => None, + ShareAudio::Everything if cfg!(target_os = "windows") => None, ShareAudio::Everything => { let apps: Vec<&AudioApp> = yumush .share_apps @@ -760,20 +817,14 @@ fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Opt (!apps.is_empty()).then(|| { let rows = div().flex().flex_col().gap(px(2.)).children( apps.into_iter() - .map(|app| exclude_row(entity, settings, app)), + .map(|app| include_row(entity, settings, app, palette)), ); field("Include", app_list(rows), palette).into_any_element() }) } - ShareAudio::Source(selected) => Some( - app_list(pick_list( - entity, - selected.as_str(), - &yumush.share_apps, - palette, - )) - .into_any_element(), - ), + audio => { + Some(app_list(pick_list(entity, audio, &yumush.share_apps, palette)).into_any_element()) + } } } @@ -785,7 +836,12 @@ fn app_list(rows: impl IntoElement) -> impl IntoElement { .child(rows) } -fn pick_list(entity: &Entity, selected: &str, apps: &[AudioApp], palette: Palette) -> Div { +fn pick_list( + entity: &Entity, + audio: &ShareAudio, + apps: &[AudioApp], + palette: Palette, +) -> Div { let groups = [ (AudioKind::App, "Apps"), (AudioKind::Output, "Outputs"), @@ -800,7 +856,7 @@ fn pick_list(entity: &Entity, selected: &str, apps: &[AudioApp], palette let rows: Vec<_> = apps .iter() .filter(|app| app.kind == kind) - .map(|app| pick_row(entity, selected == app.node, app, palette)) + .map(|app| pick_row(entity, chosen(audio, app), app, palette)) .collect(); (!rows.is_empty()).then(|| group(label, rows, palette)) })) @@ -844,28 +900,42 @@ fn row_style(item: E) -> E { .rounded(px(6.)) } -fn name_cell(name: String) -> Div { - div().flex_1().min_w_0().truncate().child(name) +fn name_cell(app: &AudioApp, palette: Palette) -> Div { + div() + .flex_1() + .min_w_0() + .flex() + .items_baseline() + .gap(px(6.)) + .child(div().flex_none().child(app.name.clone())) + .child( + div() + .min_w_0() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(app.detail.clone()), + ) } -fn exclude_row( +fn include_row( entity: &Entity, settings: &ShareSettings, app: &AudioApp, + palette: Palette, ) -> impl IntoElement { let entity = entity.clone(); - let name = app.name.clone(); - let included = !settings.excluded.contains(&app.name); + let included = !is_excluded(&settings.excluded, &app.name, app.pid); + let target = app.clone(); - row_style(div()).child(name_cell(app.name.clone())).child( + row_style(div()).child(name_cell(app, palette)).child( div().flex_shrink_0().child( - Switch::new(format!("share_app_{}", app.node)) + Switch::new(format!("share_app_{}", app.key())) .checked(included) .on_change(move |checked, _, cx| { - let name = name.clone(); let included = *checked; entity.update(cx, |yumush, cx| { - yumush.set_share_excluded(name, !included, cx) + yumush.set_share_included(&target, included, cx) }); }), ), @@ -879,17 +949,16 @@ fn pick_row( palette: Palette, ) -> impl IntoElement { let entity = entity.clone(); - let node = app.node.clone(); + let target = app.clone(); row_style(clickable( - format!("share_app_{}", app.node), + format!("share_app_{}", app.key()), palette, move |_, cx| { - let node = node.clone(); - entity.update(cx, |yumush, cx| yumush.set_share_source(node, cx)); + entity.update(cx, |yumush, cx| yumush.set_share_source(&target, cx)); }, )) - .child(name_cell(app.name.clone())) + .child(name_cell(app, palette)) .children(chosen.then(|| { Icon::new(IconName::Check) .w(px(14.)) diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 174c82e..96b6785 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -135,7 +135,8 @@ impl Default for VoiceSettings { pub enum ShareAudio { Off, Everything, - Source(String), + App { name: String, pid: Option }, + Device(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -197,7 +198,11 @@ impl ShareSettings { ShareAudio::Everything => Some(AudioMode::Everything { excluded: self.excluded.clone(), }), - ShareAudio::Source(name) => Some(AudioMode::Source(name.clone())), + ShareAudio::App { name, pid } => Some(AudioMode::App { + name: name.clone(), + pid: *pid, + }), + ShareAudio::Device(node) => Some(AudioMode::Device(node.clone())), } } } @@ -301,8 +306,11 @@ pub fn load() -> Settings { .map_or(ShareCodec::Auto, ShareCodec::Only), audio: match text("share.audio").as_deref() { Some("off") => ShareAudio::Off, + Some("app") => text("share.audio_source").map_or(ShareAudio::Everything, |name| { + ShareAudio::App { name, pid: None } + }), Some("source") => { - text("share.audio_source").map_or(ShareAudio::Everything, ShareAudio::Source) + text("share.audio_source").map_or(ShareAudio::Everything, ShareAudio::Device) } _ => ShareAudio::Everything, }, @@ -336,7 +344,8 @@ pub fn save(settings: &Settings) { let (audio, source) = match &share.audio { ShareAudio::Off => ("off", ""), ShareAudio::Everything => ("everything", ""), - ShareAudio::Source(name) => ("source", name.as_str()), + ShareAudio::App { name, .. } => ("app", name.as_str()), + ShareAudio::Device(node) => ("source", node.as_str()), }; let content = [ line("theme", settings.theme.as_str()), @@ -376,7 +385,16 @@ pub fn save(settings: &Settings) { ), line("share.audio", audio), line("share.audio_source", source), - line("share.excluded", share.excluded.join("\t")), + line( + "share.excluded", + share + .excluded + .iter() + .filter(|entry| !entry.contains('#')) + .cloned() + .collect::>() + .join("\t"), + ), line("share.volume", share.volume), ] .concat(); diff --git a/crates/client/src/share/audio.rs b/crates/client/src/share/audio.rs index e9e049e..1d3fde6 100644 --- a/crates/client/src/share/audio.rs +++ b/crates/client/src/share/audio.rs @@ -1,7 +1,8 @@ #[derive(Debug, Clone, PartialEq, Eq)] pub enum AudioMode { Everything { excluded: Vec }, - Source(String), + App { name: String, pid: Option }, + Device(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -14,6 +15,30 @@ pub enum AudioKind { #[derive(Debug, Clone)] pub struct AudioApp { pub name: String, + pub detail: String, pub node: String, + pub pid: Option, pub kind: AudioKind, } + +impl AudioApp { + pub fn key(&self) -> String { + instance_key(&self.name, self.pid) + } +} + +pub fn instance_key(name: &str, pid: Option) -> String { + match pid { + Some(pid) => format!("{name}#{pid}"), + None => name.to_string(), + } +} + +pub fn is_excluded(excluded: &[String], name: &str, pid: Option) -> bool { + excluded.iter().any(|entry| *entry == name) + || pid.is_some_and(|pid| excluded.contains(&instance_key(name, Some(pid)))) +} + +pub fn is_picked(picked: (&str, Option), name: &str, pid: Option) -> bool { + picked.0 == name && picked.1.is_none_or(|picked| Some(picked) == pid) +} diff --git a/crates/client/src/share/audio_capture.rs b/crates/client/src/share/audio_capture.rs index 042ccec..352c479 100644 --- a/crates/client/src/share/audio_capture.rs +++ b/crates/client/src/share/audio_capture.rs @@ -1,6 +1,6 @@ use std::{ cell::{Cell, RefCell}, - collections::{HashMap, HashSet}, + collections::{BTreeMap, HashMap, HashSet}, error::Error, process, rc::Rc, @@ -23,7 +23,7 @@ use pw::{ use spa::{pod::Pod, utils::dict::DictRef}; use tracing::warn; -use super::audio::{AudioApp, AudioKind, AudioMode}; +use super::audio::{AudioApp, AudioKind, AudioMode, is_excluded, is_picked}; use crate::voice::audio::{Worker, supervise}; const STOP_CHECK: Duration = Duration::from_millis(100); @@ -52,6 +52,13 @@ struct Node { role: String, process: String, app: String, + media: String, +} + +impl Node { + fn pid(&self) -> Option { + self.process.parse().ok() + } } struct Port { @@ -69,20 +76,43 @@ struct Routing { } pub fn apps() -> Vec { - let mut apps: Vec = nodes() - .unwrap_or_default() + let nodes = nodes().unwrap_or_default(); + let own = process::id().to_string(); + let mut instances: BTreeMap<(String, Option), Vec> = BTreeMap::new(); + let mut devices = Vec::new(); + for node in nodes .into_iter() - .filter(|node| !node.name.starts_with(OWN_PREFIX)) - .filter_map(|node| { - Some(AudioApp { - kind: AudioKind::of(&node.class)?, + .filter(|node| !node.name.starts_with(OWN_PREFIX) && node.process != own) + { + match AudioKind::of(&node.class) { + Some(AudioKind::App) => { + let media = instances.entry((node.app.clone(), node.pid())).or_default(); + if !node.media.is_empty() && !media.contains(&node.media) { + media.push(node.media); + } + } + Some(kind) => devices.push(AudioApp { name: node.app, + detail: String::new(), node: node.name, - }) + pid: None, + kind, + }), + None => {} + } + } + let mut apps: Vec = instances + .into_iter() + .map(|((name, pid), media)| AudioApp { + detail: media.join(", "), + node: name.clone(), + name, + pid, + kind: AudioKind::App, }) .collect(); - apps.sort_by(|a, b| (a.kind as u8, &a.name).cmp(&(b.kind as u8, &b.name))); - apps.dedup_by(|a, b| a.kind == AudioKind::App && a.kind == b.kind && a.name == b.name); + devices.sort_by(|a, b| (a.kind as u8, &a.name).cmp(&(b.kind as u8, &b.name))); + apps.extend(devices); apps } @@ -90,11 +120,11 @@ pub fn start(mode: AudioMode, output: rtrb::Producer) -> AudioCapture { Worker::spawn("share-audio", move |stop| { let output = Rc::new(RefCell::new(output)); let is_sink = match &mode { - AudioMode::Everything { .. } => false, - AudioMode::Source(name) => nodes() + AudioMode::Device(name) => nodes() .unwrap_or_default() .iter() .any(|node| &node.name == name && node.class == "Audio/Sink"), + _ => false, }; supervise("share audio", stop, || run(&mode, &output, is_sink, stop)); }) @@ -185,6 +215,10 @@ fn node_of(global: &GlobalObject<&DictRef>) -> Option { .get(*pw::keys::APP_NAME) .unwrap_or(description) .to_string(), + media: props + .get(*pw::keys::MEDIA_NAME) + .unwrap_or_default() + .to_string(), }) } @@ -215,7 +249,7 @@ impl Routing { self.ports.remove(&id); } - fn sync(&mut self, own: u32, excluded: &[String], core: &CoreRc) { + fn sync(&mut self, own: u32, mode: &AudioMode, core: &CoreRc) { self.links.retain(|(output, input), _| { self.ports.contains_key(output) && self.ports.contains_key(input) }); @@ -225,7 +259,7 @@ impl Routing { let eligible = self .streams .get(&output.node) - .is_some_and(|node| eligible(node, excluded)); + .is_some_and(|node| eligible(node, mode)); if !eligible { continue; } @@ -258,13 +292,18 @@ impl Routing { } } -fn eligible(node: &Node, excluded: &[String]) -> bool { +fn eligible(node: &Node, mode: &AudioMode) -> bool { let own_process = process::id().to_string(); - !(SKIPPED_ROLES.contains(&node.role.as_str()) + let foreign = !(SKIPPED_ROLES.contains(&node.role.as_str()) || node.process == own_process || node.name.starts_with(OWN_PREFIX) - || node.name.contains("echo-cancel") - || excluded.contains(&node.app)) + || node.name.contains("echo-cancel")); + foreign + && match mode { + AudioMode::Everything { excluded } => !is_excluded(excluded, &node.app, node.pid()), + AudioMode::App { name, pid } => is_picked((name, *pid), &node.app, node.pid()), + AudioMode::Device(_) => false, + } } fn matches_channel(output: &Port, input: &Port) -> bool { @@ -354,8 +393,8 @@ fn run( .register(); let target = match mode { - AudioMode::Everything { .. } => None, - AudioMode::Source(name) => Some(name.as_str()), + AudioMode::Device(name) => Some(name.as_str()), + _ => None, }; let mut props = properties! { @@ -411,8 +450,8 @@ fn run( if failed.get() { return Err("pipewire connection lost".into()); } - if let AudioMode::Everything { excluded } = mode { - routing.borrow_mut().sync(stream.node_id(), excluded, &core); + if target.is_none() { + routing.borrow_mut().sync(stream.node_id(), mode, &core); } mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK)); } diff --git a/crates/client/src/share/audio_capture_windows.rs b/crates/client/src/share/audio_capture_windows.rs index a78e63d..a76ca8d 100644 --- a/crates/client/src/share/audio_capture_windows.rs +++ b/crates/client/src/share/audio_capture_windows.rs @@ -14,7 +14,7 @@ use wasapi::{ StreamMode, WaveFormat, deinitialize, initialize_mta, }; -use super::audio::{AudioApp, AudioKind, AudioMode}; +use super::audio::{AudioApp, AudioKind, AudioMode, is_picked}; use crate::voice::audio::{Worker, supervise}; const STOP_CHECK: Duration = Duration::from_millis(100); @@ -64,7 +64,7 @@ fn sessions() -> Result, Box> { } let name = session.get_display_name().unwrap_or_default(); let name = if name.is_empty() { - format!("pid {pid}") + process_name(pid).unwrap_or_else(|| format!("pid {pid}")) } else { name }; @@ -74,14 +74,28 @@ fn sessions() -> Result, Box> { .into_iter() .map(|(pid, name)| AudioApp { name, + detail: format!("pid {pid}"), node: pid.to_string(), + pid: Some(pid), kind: AudioKind::App, }) .collect(); - apps.sort_by(|a, b| a.name.cmp(&b.name)); + apps.sort_by(|a, b| (&a.name, a.pid).cmp(&(&b.name, b.pid))); Ok(apps) } +fn process_name(pid: u32) -> Option { + let pid = sysinfo::Pid::from_u32(pid); + let mut system = sysinfo::System::new().ok()?; + system.refresh_processes_specifics( + sysinfo::ProcessesToUpdate::Some(&[pid]), + false, + sysinfo::ProcessRefreshKind::nothing(), + ); + let name = system.process(pid)?.name().to_string_lossy().into_owned(); + Some(name.trim_end_matches(".exe").to_string()) +} + pub fn start(mode: AudioMode, output: Producer) -> AudioCapture { Worker::spawn("share-audio", move |stop| { with_com(|| { @@ -111,12 +125,15 @@ fn run( AudioMode::Everything { .. } => { AudioClient::new_application_loopback_client(process::id(), false)? } - AudioMode::Source(node) => { - if !sessions()?.iter().any(|app| &app.node == node) { - return Err("share audio app is not running".into()); - } - AudioClient::new_application_loopback_client(node.parse()?, true)? + AudioMode::App { name, pid } => { + let target = sessions()? + .into_iter() + .find(|app| is_picked((name, *pid), &app.name, app.pid)) + .and_then(|app| app.pid) + .ok_or("share audio app is not running")?; + AudioClient::new_application_loopback_client(target, true)? } + AudioMode::Device(_) => return Err("share audio device capture is not supported".into()), }; client.initialize_client( &wave_format(),