wip: Mute action in the voice notification, shared capture clock

This commit is contained in:
Claude committed 2026-09-26 15:20:20 +00:00
1 parent 14d0d81fdf
commit 1eff869d39
11 files changed
+159 -81

No files matched your search

@@ -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 @JvmStatic
fun setVoiceNotification(text: String?) { fun setVoiceNotification(text: String?, muted: Boolean) {
if (text == null) VoiceService.stop(app) else VoiceService.start(app, text) 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. */ /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */
@@ -38,4 +38,8 @@ object Native {
/** "Disconnect" in the voice notification. */ /** "Disconnect" in the voice notification. */
@JvmStatic @JvmStatic
external fun onDisconnectVoice() external fun onDisconnectVoice()
/** "Mute" / "Unmute" in the voice notification. */
@JvmStatic
external fun onToggleMute()
} }
@@ -38,19 +38,24 @@ object Notifications {
PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_IMMUTABLE,
) )
/** An ongoing notification with `actions` (title, intent). */
fun ongoing( fun ongoing(
context: Context, context: Context,
channel: String, channel: String,
text: String, text: String,
actionTitle: String, vararg actions: Pair<String, PendingIntent>,
action: PendingIntent, ): Notification {
): Notification = Notification.Builder(context, channel) val builder = Notification.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification) .setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name)) .setContentTitle(context.getString(R.string.app_name))
.setContentText(text) .setContentText(text)
.setContentIntent(openApp(context)) .setContentIntent(openApp(context))
.setOngoing(true) .setOngoing(true)
.setCategory(Notification.CATEGORY_CALL) .setOnlyAlertOnce(true)
.addAction(Notification.Action.Builder(null, actionTitle, action).build()) .setCategory(Notification.CATEGORY_CALL)
.build() for ((title, intent) in actions) {
builder.addAction(Notification.Action.Builder(null, title, intent).build())
}
return builder.build()
}
} }
@@ -65,8 +65,7 @@ class ScreenCaptureService : Service() {
this, this,
Notifications.CHANNEL_SCREEN, Notifications.CHANNEL_SCREEN,
getString(R.string.screen_sharing), getString(R.string.screen_sharing),
getString(R.string.stop_sharing), getString(R.string.stop_sharing) to stop,
stop,
) )
try { try {
// Must be in the foreground before getMediaProjection (Android 14). // Must be in the foreground before getMediaProjection (Android 14).
@@ -20,16 +20,23 @@ class VoiceService : Service() {
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_DISCONNECT) { when (intent?.action) {
Native.onDisconnectVoice() ACTION_DISCONNECT -> {
return START_NOT_STICKY 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 text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected)
val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false
try { try {
if (Build.VERSION.SDK_INT >= 30) { 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 { } else {
startForeground(ID, notification(this, text)) startForeground(ID, notification(this, text, muted))
} }
running = this running = this
} catch (e: RuntimeException) { } catch (e: RuntimeException) {
@@ -50,38 +57,44 @@ class VoiceService : Service() {
private const val TAG = "VoiceService" private const val TAG = "VoiceService"
private const val ID = 1 private const val ID = 1
private const val EXTRA_TEXT = "text" 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_DISCONNECT = "io.github.faumaray.tsc.DISCONNECT"
private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.tsc.TOGGLE_MUTE"
@Volatile @Volatile
private var running: VoiceService? = null private var running: VoiceService? = null
private fun notification(context: Context, text: String): Notification { private fun action(context: Context, action: String, request: Int): PendingIntent =
val disconnect = PendingIntent.getService( PendingIntent.getService(
context, context,
0, request,
Intent(context, VoiceService::class.java).setAction(ACTION_DISCONNECT), Intent(context, VoiceService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_IMMUTABLE,
) )
return Notifications.ongoing(
private fun notification(context: Context, text: String, muted: Boolean): Notification =
Notifications.ongoing(
context, context,
Notifications.CHANNEL_VOICE, Notifications.CHANNEL_VOICE,
text, text,
context.getString(R.string.disconnect), context.getString(if (muted) R.string.unmute else R.string.mute) to
disconnect, 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. */ /** 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 val service = running
if (service != null) { if (service != null) {
service.getSystemService(NotificationManager::class.java) service.getSystemService(NotificationManager::class.java)
.notify(ID, notification(service, text)) .notify(ID, notification(service, text, muted))
return return
} }
try { try {
context.startForegroundService( 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) { } catch (e: RuntimeException) {
// Not allowed from the background (Android 12+). Voice is // Not allowed from the background (Android 12+). Voice is
@@ -6,6 +6,8 @@
<string name="channel_screen">Screen sharing</string> <string name="channel_screen">Screen sharing</string>
<string name="voice_connected">Connected to voice</string> <string name="voice_connected">Connected to voice</string>
<string name="disconnect">Disconnect</string> <string name="disconnect">Disconnect</string>
<string name="mute">Mute</string>
<string name="unmute">Unmute</string>
<string name="screen_sharing">Sharing your screen</string> <string name="screen_sharing">Sharing your screen</string>
<string name="stop_sharing">Stop sharing</string> <string name="stop_sharing">Stop sharing</string>
</resources> </resources>
+15 -2
View File
@@ -111,8 +111,8 @@ fn watch_voice(host: &'static EngineHost) {
loop { loop {
match events.recv().await { match events.recv().await {
Ok(event) => { Ok(event) => {
if let Some(text) = with_foreground(|f| f.update(&event)) if let Some(notice) = with_foreground(|f| f.update(&event))
&& let Err(e) = bridge::set_voice_notification(text.as_deref()) && let Err(e) = bridge::set_voice_notification(notice.as_ref())
{ {
warn!("voice service: {e}"); warn!("voice service: {e}");
} }
@@ -133,3 +133,16 @@ pub fn disconnect_voice() {
host.engine().send(Command::DisconnectVoice { session }); 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 });
}
}
+19 -6
View File
@@ -15,6 +15,8 @@ use jni::refs::{Global, Reference as _};
use jni::sys::{jboolean, jint, jlong}; use jni::sys::{jboolean, jint, jlong};
use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; use jni::{Env, JavaVM, jni_sig, jni_str, native_method};
use crate::foreground::VoiceNotice;
static BRIDGE: OnceLock<Global<JClass<'static>>> = OnceLock::new(); static BRIDGE: OnceLock<Global<JClass<'static>>> = OnceLock::new();
/// Look up `Bridge` (on the `android_main` thread). /// 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. /// 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| { with_bridge(|env, class| {
let text = match text { let (text, muted) = match notice {
Some(text) => JObject::from(env.new_string(text)?), Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted),
None => JObject::null(), None => (JObject::null(), false),
}; };
env.call_static_method( env.call_static_method(
class, class,
jni_str!("setVoiceNotification"), jni_str!("setVoiceNotification"),
jni_sig!((text: java.lang.String) -> void), jni_sig!((text: java.lang.String, muted: jboolean) -> void),
&[JValue::Object(&text)], &[JValue::Object(&text), JValue::Bool(muted)],
)?; )?;
Ok(()) Ok(())
}) })
@@ -258,3 +260,14 @@ fn on_disconnect_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -
crate::app::disconnect_voice(); crate::app::disconnect_voice();
Ok(()) 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(())
}
+6 -6
View File
@@ -29,8 +29,9 @@ struct State {
/// Answer for the pending `start`. /// Answer for the pending `start`.
pending: Option<oneshot::Sender<Result<()>>>, pending: Option<oneshot::Sender<Result<()>>>,
audio: Option<FrameSender<AudioBuffer>>, audio: Option<FrameSender<AudioBuffer>>,
first_frame_ns: Option<i64>, /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC`
first_audio_ns: Option<i64>, /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync.
origin_ns: Option<i64>,
} }
static STATE: Mutex<Option<State>> = Mutex::new(None); static STATE: Mutex<Option<State>> = Mutex::new(None);
@@ -82,7 +83,7 @@ impl ScreenProvider for Projection {
let _ = previous.send(Err(Error::Cancelled)); let _ = previous.send(Err(Error::Cancelled));
} }
s.frames = Some(frames); 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) { if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) {
with_state(|s| { with_state(|s| {
@@ -113,7 +114,6 @@ impl AudioProvider for PlaybackAudio {
fn start(&self, buffers: FrameSender<AudioBuffer>) -> Result<()> { fn start(&self, buffers: FrameSender<AudioBuffer>) -> Result<()> {
with_state(|s| { with_state(|s| {
s.audio = Some(buffers); s.audio = Some(buffers);
s.first_audio_ns = None;
}); });
let started = bridge::start_system_audio(); let started = bridge::start_system_audio();
match started { match started {
@@ -167,7 +167,7 @@ pub fn on_frame(
timestamp_ns: i64, timestamp_ns: i64,
) -> bool { ) -> bool {
with_state(|s| { 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 { let Some(frames) = &s.frames else {
return false; return false;
}; };
@@ -203,7 +203,7 @@ pub fn wants_audio() -> bool {
/// Captured playback audio. Returns `false` once nobody wants it. /// Captured playback audio. Returns `false` once nobody wants it.
pub fn on_audio(samples: Vec<f32>, channels: u16, timestamp_ns: i64) -> bool { pub fn on_audio(samples: Vec<f32>, channels: u16, timestamp_ns: i64) -> bool {
with_state(|s| { 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 { let Some(audio) = &s.audio else {
return false; return false;
}; };
+55 -32
View File
@@ -3,12 +3,20 @@
//! Android keeps the microphone and the process of a backgrounded app only //! Android keeps the microphone and the process of a backgrounded app only
//! while a foreground service with a visible notification runs. The service //! while a foreground service with a visible notification runs. The service
//! runs while any session has a voice connection (connecting or connected); //! 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 std::collections::BTreeMap;
use tsc_core::{Event, SessionId, VoiceState}; 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)] #[derive(Default)]
pub struct Foreground { pub struct Foreground {
sessions: BTreeMap<SessionId, Session>, sessions: BTreeMap<SessionId, Session>,
@@ -18,50 +26,53 @@ pub struct Foreground {
struct Session { struct Session {
name: Option<String>, name: Option<String>,
voice: VoiceState, voice: VoiceState,
muted: bool,
} }
impl Foreground { 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. /// `Some(None)` means the service should stop.
pub fn update(&mut self, event: &Event) -> Option<Option<String>> { pub fn update(&mut self, event: &Event) -> Option<Option<VoiceNotice>> {
let before = self.notification(); let before = self.notice();
match event { match event {
Event::State { session, state } => { 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, .. } => { Event::ServerInfo { session, name, .. } => {
self.sessions.entry(*session).or_default().name = Some(name.clone()); self.sessions.entry(*session).or_default().name = Some(name.clone());
} }
_ => return None, _ => return None,
} }
let after = self.notification(); let after = self.notice();
(after != before).then_some(after) (after != before).then_some(after)
} }
/// Sessions with a voice connection (for "Disconnect"). fn active(&self) -> impl Iterator<Item = (&SessionId, &Session)> {
pub fn voice_sessions(&self) -> Vec<SessionId> { self.sessions.iter().filter(|(_, s)| s.voice != VoiceState::Disconnected)
self.sessions
.iter()
.filter(|(_, s)| s.voice != VoiceState::Disconnected)
.map(|(id, _)| *id)
.collect()
} }
/// The notification text, `None` without voice. /// Sessions with a voice connection (for the notification's actions).
pub fn notification(&self) -> Option<String> { pub fn voice_sessions(&self) -> Vec<SessionId> {
let active: Vec<&Session> = self.active().map(|(id, _)| *id).collect()
self.sessions.values().filter(|s| s.voice != VoiceState::Disconnected).collect(); }
/// The notification, `None` without voice.
pub fn notice(&self) -> Option<VoiceNotice> {
let active: Vec<&Session> = self.active().map(|(_, s)| s).collect();
if active.is_empty() { if active.is_empty() {
return None; return None;
} }
let names: Vec<&str> = let names: Vec<&str> =
active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect();
let names = names.join(", "); 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}") format!("Connecting to {names}")
} else { } else {
format!("In voice on {names}") format!("In voice on {names}")
}) };
Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) })
} }
} }
@@ -72,17 +83,24 @@ mod tests {
use super::*; use super::*;
fn voice(session: SessionId, voice: VoiceState) -> Event { fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event {
Event::State { session, state: SessionState { voice, ..SessionState::default() } } Event::State {
session,
state: SessionState { voice, input_muted, ..SessionState::default() },
}
}
fn notice(text: &str, muted: bool) -> Option<Option<VoiceNotice>> {
Some(Some(VoiceNotice { text: text.into(), muted }))
} }
#[test] #[test]
fn service_follows_voice_connections() { fn service_follows_voice_connections() {
let mut fg = Foreground::default(); 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!( assert_eq!(
fg.update(&voice(1, VoiceState::Connecting)), fg.update(&voice(1, VoiceState::Connecting, false)),
Some(Some("Connecting to a server".into())) notice("Connecting to a server", false)
); );
let info = Event::ServerInfo { let info = Event::ServerInfo {
session: 1, session: 1,
@@ -90,20 +108,25 @@ mod tests {
flavor: ServerFlavor::Unknown(String::new()), flavor: ServerFlavor::Unknown(String::new()),
capabilities: Capabilities::default(), 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!( assert_eq!(
fg.update(&voice(1, VoiceState::Connected)), fg.update(&voice(1, VoiceState::Connected, false)),
Some(Some("In voice on Home".into())) 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!( assert_eq!(
fg.update(&voice(2, VoiceState::Connecting)), fg.update(&voice(1, VoiceState::Connected, true)),
Some(Some("In voice on Home, a server".into())) 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.voice_sessions(), [1, 2]);
assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None);
fg.update(&voice(2, VoiceState::Disconnected)); fg.update(&voice(2, VoiceState::Disconnected, false));
assert_eq!(fg.update(&voice(1, VoiceState::Disconnected)), Some(None)); assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None));
assert!(fg.voice_sessions().is_empty()); assert!(fg.voice_sessions().is_empty());
} }
} }
+6 -3
View File
@@ -80,9 +80,9 @@ capture, NDK MediaCodec format queries); targetSdk and compileSdk 36.
do not recreate it. do not recreate it.
- **Voice in the background**: while any session has a voice connection, - **Voice in the background**: while any session has a voice connection,
`VoiceService` runs as a foreground service of type `microphone` with a `VoiceService` runs as a foreground service of type `microphone` with a
notification ("In voice on …", Disconnect). Rust drives it from engine notification ("In voice on …", Mute or Unmute, Disconnect). Rust drives it
events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio itself is from engine events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio
cpal on AAudio, as on desktop. itself is cpal on AAudio, as on desktop.
- **Sharing the screen**: `tsc_media::capture::default_screen_capture()` - **Sharing the screen**: `tsc_media::capture::default_screen_capture()`
returns the MediaProjection provider (`capture.rs`) registered at start. returns the MediaProjection provider (`capture.rs`) registered at start.
Starting shows the system consent dialog; on consent `ScreenCaptureService` 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 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. 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. - 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.