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 7a8c901a08
commit 67dd8e04d6
11 files changed
+159 -81

No files matched your search

+15 -2
View File
@@ -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 });
}
}
+19 -6
View File
@@ -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<Global<JClass<'static>>> = 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(())
}
+6 -6
View File
@@ -29,8 +29,9 @@ struct State {
/// Answer for the pending `start`.
pending: Option<oneshot::Sender<Result<()>>>,
audio: Option<FrameSender<AudioBuffer>>,
first_frame_ns: Option<i64>,
first_audio_ns: Option<i64>,
/// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC`
/// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync.
origin_ns: Option<i64>,
}
static STATE: Mutex<Option<State>> = 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<AudioBuffer>) -> 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<f32>, 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;
};
+55 -32
View File
@@ -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<SessionId, Session>,
@@ -18,50 +26,53 @@ pub struct Foreground {
struct Session {
name: Option<String>,
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<Option<String>> {
let before = self.notification();
pub fn update(&mut self, event: &Event) -> Option<Option<VoiceNotice>> {
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<SessionId> {
self.sessions
.iter()
.filter(|(_, s)| s.voice != VoiceState::Disconnected)
.map(|(id, _)| *id)
.collect()
fn active(&self) -> impl Iterator<Item = (&SessionId, &Session)> {
self.sessions.iter().filter(|(_, s)| s.voice != VoiceState::Disconnected)
}
/// The notification text, `None` without voice.
pub fn notification(&self) -> Option<String> {
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<SessionId> {
self.active().map(|(id, _)| *id).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() {
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<Option<VoiceNotice>> {
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());
}
}