diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt b/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt index 835aed5..20a8dc3 100644 --- a/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt @@ -28,10 +28,13 @@ object Bridge { } } - /** Run the voice service with this notification text; null stops it. */ + /** + * Run the voice service with this notification text (`muted`: the action + * offers Unmute); null stops it. + */ @JvmStatic - fun setVoiceNotification(text: String?) { - if (text == null) VoiceService.stop(app) else VoiceService.start(app, text) + fun setVoiceNotification(text: String?, muted: Boolean) { + if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted) } /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */ diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Native.kt b/android/app/src/main/java/io/github/faumaray/tsc/Native.kt index cb57838..55e08f3 100644 --- a/android/app/src/main/java/io/github/faumaray/tsc/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/tsc/Native.kt @@ -38,4 +38,8 @@ object Native { /** "Disconnect" in the voice notification. */ @JvmStatic external fun onDisconnectVoice() + + /** "Mute" / "Unmute" in the voice notification. */ + @JvmStatic + external fun onToggleMute() } diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt b/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt index dca1560..502e069 100644 --- a/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt +++ b/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt @@ -38,19 +38,24 @@ object Notifications { PendingIntent.FLAG_IMMUTABLE, ) + /** An ongoing notification with `actions` (title, intent). */ fun ongoing( context: Context, channel: String, text: String, - actionTitle: String, - action: PendingIntent, - ): Notification = Notification.Builder(context, channel) - .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(context.getString(R.string.app_name)) - .setContentText(text) - .setContentIntent(openApp(context)) - .setOngoing(true) - .setCategory(Notification.CATEGORY_CALL) - .addAction(Notification.Action.Builder(null, actionTitle, action).build()) - .build() + vararg actions: Pair, + ): Notification { + val builder = Notification.Builder(context, channel) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(text) + .setContentIntent(openApp(context)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setCategory(Notification.CATEGORY_CALL) + for ((title, intent) in actions) { + builder.addAction(Notification.Action.Builder(null, title, intent).build()) + } + return builder.build() + } } diff --git a/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt index 0e69bf5..3cd2084 100644 --- a/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt @@ -65,8 +65,7 @@ class ScreenCaptureService : Service() { this, Notifications.CHANNEL_SCREEN, getString(R.string.screen_sharing), - getString(R.string.stop_sharing), - stop, + getString(R.string.stop_sharing) to stop, ) try { // Must be in the foreground before getMediaProjection (Android 14). diff --git a/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt b/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt index 62c338b..d56357b 100644 --- a/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt +++ b/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt @@ -20,16 +20,23 @@ class VoiceService : Service() { override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - if (intent?.action == ACTION_DISCONNECT) { - Native.onDisconnectVoice() - return START_NOT_STICKY + when (intent?.action) { + ACTION_DISCONNECT -> { + Native.onDisconnectVoice() + return START_NOT_STICKY + } + ACTION_TOGGLE_MUTE -> { + Native.onToggleMute() + return START_NOT_STICKY + } } val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) + val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false try { if (Build.VERSION.SDK_INT >= 30) { - startForeground(ID, notification(this, text), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) } else { - startForeground(ID, notification(this, text)) + startForeground(ID, notification(this, text, muted)) } running = this } catch (e: RuntimeException) { @@ -50,38 +57,44 @@ class VoiceService : Service() { private const val TAG = "VoiceService" private const val ID = 1 private const val EXTRA_TEXT = "text" + private const val EXTRA_MUTED = "muted" private const val ACTION_DISCONNECT = "io.github.faumaray.tsc.DISCONNECT" + private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.tsc.TOGGLE_MUTE" @Volatile private var running: VoiceService? = null - private fun notification(context: Context, text: String): Notification { - val disconnect = PendingIntent.getService( + private fun action(context: Context, action: String, request: Int): PendingIntent = + PendingIntent.getService( context, - 0, - Intent(context, VoiceService::class.java).setAction(ACTION_DISCONNECT), + request, + Intent(context, VoiceService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE, ) - return Notifications.ongoing( + + private fun notification(context: Context, text: String, muted: Boolean): Notification = + Notifications.ongoing( context, Notifications.CHANNEL_VOICE, text, - context.getString(R.string.disconnect), - disconnect, + context.getString(if (muted) R.string.unmute else R.string.mute) to + action(context, ACTION_TOGGLE_MUTE, 1), + context.getString(R.string.disconnect) to action(context, ACTION_DISCONNECT, 0), ) - } /** Start the service, or update its notification when it runs. */ - fun start(context: Context, text: String) { + fun start(context: Context, text: String, muted: Boolean) { val service = running if (service != null) { service.getSystemService(NotificationManager::class.java) - .notify(ID, notification(service, text)) + .notify(ID, notification(service, text, muted)) return } try { context.startForegroundService( - Intent(context, VoiceService::class.java).putExtra(EXTRA_TEXT, text), + Intent(context, VoiceService::class.java) + .putExtra(EXTRA_TEXT, text) + .putExtra(EXTRA_MUTED, muted), ) } catch (e: RuntimeException) { // Not allowed from the background (Android 12+). Voice is diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index f5c94cb..f1e2b43 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -6,6 +6,8 @@ Screen sharing Connected to voice Disconnect + Mute + Unmute Sharing your screen Stop sharing diff --git a/crates/tsc-android/src/app.rs b/crates/tsc-android/src/app.rs index 9ab9fd8..3961f9d 100644 --- a/crates/tsc-android/src/app.rs +++ b/crates/tsc-android/src/app.rs @@ -111,8 +111,8 @@ fn watch_voice(host: &'static EngineHost) { loop { match events.recv().await { Ok(event) => { - if let Some(text) = with_foreground(|f| f.update(&event)) - && let Err(e) = bridge::set_voice_notification(text.as_deref()) + if let Some(notice) = with_foreground(|f| f.update(&event)) + && let Err(e) = bridge::set_voice_notification(notice.as_ref()) { warn!("voice service: {e}"); } @@ -133,3 +133,16 @@ pub fn disconnect_voice() { host.engine().send(Command::DisconnectVoice { session }); } } + +/// "Mute" / "Unmute" in the voice notification: mute every voice session, +/// or unmute them all when all are muted. +pub fn toggle_mute() { + let Some(host) = HOST.get() else { + return; + }; + let (sessions, muted) = + with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.muted))); + for session in sessions { + host.engine().send(Command::SetInputMuted { session, muted: !muted }); + } +} diff --git a/crates/tsc-android/src/bridge.rs b/crates/tsc-android/src/bridge.rs index 53ce2b3..56e92d1 100644 --- a/crates/tsc-android/src/bridge.rs +++ b/crates/tsc-android/src/bridge.rs @@ -15,6 +15,8 @@ use jni::refs::{Global, Reference as _}; use jni::sys::{jboolean, jint, jlong}; use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; +use crate::foreground::VoiceNotice; + static BRIDGE: OnceLock>> = OnceLock::new(); /// Look up `Bridge` (on the `android_main` thread). @@ -57,17 +59,17 @@ pub fn request_permissions() -> Result<()> { } /// Show or update the voice service's notification; `None` stops the service. -pub fn set_voice_notification(text: Option<&str>) -> Result<()> { +pub fn set_voice_notification(notice: Option<&VoiceNotice>) -> Result<()> { with_bridge(|env, class| { - let text = match text { - Some(text) => JObject::from(env.new_string(text)?), - None => JObject::null(), + let (text, muted) = match notice { + Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted), + None => (JObject::null(), false), }; env.call_static_method( class, jni_str!("setVoiceNotification"), - jni_sig!((text: java.lang.String) -> void), - &[JValue::Object(&text)], + jni_sig!((text: java.lang.String, muted: jboolean) -> void), + &[JValue::Object(&text), JValue::Bool(muted)], )?; Ok(()) }) @@ -258,3 +260,14 @@ fn on_disconnect_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) - crate::app::disconnect_voice(); Ok(()) } + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_toggle_mute(), +}; + +/// "Mute" / "Unmute" in the voice notification. +fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::toggle_mute(); + Ok(()) +} diff --git a/crates/tsc-android/src/capture.rs b/crates/tsc-android/src/capture.rs index 08275c6..a73caa3 100644 --- a/crates/tsc-android/src/capture.rs +++ b/crates/tsc-android/src/capture.rs @@ -29,8 +29,9 @@ struct State { /// Answer for the pending `start`. pending: Option>>, audio: Option>, - first_frame_ns: Option, - first_audio_ns: Option, + /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC` + /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync. + origin_ns: Option, } static STATE: Mutex> = Mutex::new(None); @@ -82,7 +83,7 @@ impl ScreenProvider for Projection { let _ = previous.send(Err(Error::Cancelled)); } s.frames = Some(frames); - s.first_frame_ns = None; + s.origin_ns = None; }); if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) { with_state(|s| { @@ -113,7 +114,6 @@ impl AudioProvider for PlaybackAudio { fn start(&self, buffers: FrameSender) -> Result<()> { with_state(|s| { s.audio = Some(buffers); - s.first_audio_ns = None; }); let started = bridge::start_system_audio(); match started { @@ -167,7 +167,7 @@ pub fn on_frame( timestamp_ns: i64, ) -> bool { with_state(|s| { - let timestamp = since(&mut s.first_frame_ns, timestamp_ns); + let timestamp = since(&mut s.origin_ns, timestamp_ns); let Some(frames) = &s.frames else { return false; }; @@ -203,7 +203,7 @@ pub fn wants_audio() -> bool { /// Captured playback audio. Returns `false` once nobody wants it. pub fn on_audio(samples: Vec, channels: u16, timestamp_ns: i64) -> bool { with_state(|s| { - let timestamp = since(&mut s.first_audio_ns, timestamp_ns); + let timestamp = since(&mut s.origin_ns, timestamp_ns); let Some(audio) = &s.audio else { return false; }; diff --git a/crates/tsc-android/src/foreground.rs b/crates/tsc-android/src/foreground.rs index 0dee48d..a1c376c 100644 --- a/crates/tsc-android/src/foreground.rs +++ b/crates/tsc-android/src/foreground.rs @@ -3,12 +3,20 @@ //! Android keeps the microphone and the process of a backgrounded app only //! while a foreground service with a visible notification runs. The service //! runs while any session has a voice connection (connecting or connected); -//! its notification names the servers and offers "Disconnect". +//! its notification names the servers and offers Mute and Disconnect. use std::collections::BTreeMap; use tsc_core::{Event, SessionId, VoiceState}; +/// What the voice notification shows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VoiceNotice { + pub text: String, + /// The microphone is muted in every voice session (the action unmutes). + pub muted: bool, +} + #[derive(Default)] pub struct Foreground { sessions: BTreeMap, @@ -18,50 +26,53 @@ pub struct Foreground { struct Session { name: Option, voice: VoiceState, + muted: bool, } impl Foreground { - /// Apply `event`. Returns the new notification text when it changed: + /// Apply `event`. Returns the new notification when it changed: /// `Some(None)` means the service should stop. - pub fn update(&mut self, event: &Event) -> Option> { - let before = self.notification(); + pub fn update(&mut self, event: &Event) -> Option> { + let before = self.notice(); match event { Event::State { session, state } => { - self.sessions.entry(*session).or_default().voice = state.voice; + let s = self.sessions.entry(*session).or_default(); + s.voice = state.voice; + s.muted = state.input_muted; } Event::ServerInfo { session, name, .. } => { self.sessions.entry(*session).or_default().name = Some(name.clone()); } _ => return None, } - let after = self.notification(); + let after = self.notice(); (after != before).then_some(after) } - /// Sessions with a voice connection (for "Disconnect"). - pub fn voice_sessions(&self) -> Vec { - self.sessions - .iter() - .filter(|(_, s)| s.voice != VoiceState::Disconnected) - .map(|(id, _)| *id) - .collect() + fn active(&self) -> impl Iterator { + self.sessions.iter().filter(|(_, s)| s.voice != VoiceState::Disconnected) } - /// The notification text, `None` without voice. - pub fn notification(&self) -> Option { - let active: Vec<&Session> = - self.sessions.values().filter(|s| s.voice != VoiceState::Disconnected).collect(); + /// Sessions with a voice connection (for the notification's actions). + pub fn voice_sessions(&self) -> Vec { + self.active().map(|(id, _)| *id).collect() + } + + /// The notification, `None` without voice. + pub fn notice(&self) -> Option { + let active: Vec<&Session> = self.active().map(|(_, s)| s).collect(); if active.is_empty() { return None; } let names: Vec<&str> = active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); let names = names.join(", "); - Some(if active.iter().all(|s| s.voice == VoiceState::Connecting) { + let text = if active.iter().all(|s| s.voice == VoiceState::Connecting) { format!("Connecting to {names}") } else { format!("In voice on {names}") - }) + }; + Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) }) } } @@ -72,17 +83,24 @@ mod tests { use super::*; - fn voice(session: SessionId, voice: VoiceState) -> Event { - Event::State { session, state: SessionState { voice, ..SessionState::default() } } + fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event { + Event::State { + session, + state: SessionState { voice, input_muted, ..SessionState::default() }, + } + } + + fn notice(text: &str, muted: bool) -> Option> { + Some(Some(VoiceNotice { text: text.into(), muted })) } #[test] fn service_follows_voice_connections() { let mut fg = Foreground::default(); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected)), None); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None); assert_eq!( - fg.update(&voice(1, VoiceState::Connecting)), - Some(Some("Connecting to a server".into())) + fg.update(&voice(1, VoiceState::Connecting, false)), + notice("Connecting to a server", false) ); let info = Event::ServerInfo { session: 1, @@ -90,20 +108,25 @@ mod tests { flavor: ServerFlavor::Unknown(String::new()), capabilities: Capabilities::default(), }; - assert_eq!(fg.update(&info), Some(Some("Connecting to Home".into()))); + assert_eq!(fg.update(&info), notice("Connecting to Home", false)); assert_eq!( - fg.update(&voice(1, VoiceState::Connected)), - Some(Some("In voice on Home".into())) + fg.update(&voice(1, VoiceState::Connected, false)), + notice("In voice on Home", false) ); - assert_eq!(fg.update(&voice(1, VoiceState::Connected)), None, "no change"); + assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change"); assert_eq!( - fg.update(&voice(2, VoiceState::Connecting)), - Some(Some("In voice on Home, a server".into())) + fg.update(&voice(1, VoiceState::Connected, true)), + notice("In voice on Home", true) + ); + // A second session that is not muted: the action mutes both. + assert_eq!( + fg.update(&voice(2, VoiceState::Connecting, false)), + notice("In voice on Home, a server", false) ); assert_eq!(fg.voice_sessions(), [1, 2]); assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); - fg.update(&voice(2, VoiceState::Disconnected)); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected)), Some(None)); + fg.update(&voice(2, VoiceState::Disconnected, false)); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None)); assert!(fg.voice_sessions().is_empty()); } } diff --git a/docs/android.md b/docs/android.md index 2809925..4e04426 100644 --- a/docs/android.md +++ b/docs/android.md @@ -80,9 +80,9 @@ capture, NDK MediaCodec format queries); targetSdk and compileSdk 36. do not recreate it. - **Voice in the background**: while any session has a voice connection, `VoiceService` runs as a foreground service of type `microphone` with a - notification ("In voice on …", Disconnect). Rust drives it from engine - events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio itself is - cpal on AAudio, as on desktop. + notification ("In voice on …", Mute or Unmute, Disconnect). Rust drives it + from engine events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio + itself is cpal on AAudio, as on desktop. - **Sharing the screen**: `tsc_media::capture::default_screen_capture()` returns the MediaProjection provider (`capture.rs`) registered at start. Starting shows the system consent dialog; on consent `ScreenCaptureService` @@ -130,3 +130,6 @@ Known gaps: - The safe area (status and navigation bars) and the on-screen keyboard pad the main window; dialogs drawn over it do not account for them yet. - Only `arm64-v8a` and `x86_64` are built; 32-bit devices are not supported. +- No audio focus handling yet: a phone call does not pause our audio + (matrix row AN4). After a network change (Wi-Fi to mobile data) only + tsclientlib's own reconnect applies; untested on a phone.