From 922e62df6519eeb4f2cf21cc8a6032c3f9213f49 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 29 Jul 2026 10:25:29 +0200 Subject: [PATCH] fix(mobile): keep calls active in background --- src-tauri/Cargo.lock | 12 ++++ src-tauri/Cargo.toml | 4 ++ .../moe/sable/client/CallForegroundService.kt | 66 ++++++++++++------- .../java/moe/sable/client/MainActivity.kt | 36 +++++----- src-tauri/ios-project.yml | 3 + src-tauri/src/ios.rs | 22 +++++++ src-tauri/src/lib.rs | 4 ++ src/app/generated/tauri/commands.ts | 18 ++++- src/app/generated/tauri/events.ts | 2 +- src/app/generated/tauri/index.ts | 2 +- src/app/generated/tauri/types.ts | 2 +- src/app/plugins/call/CallEmbed.ts | 54 ++++++++++++--- 12 files changed, 173 insertions(+), 52 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d2ac364e1..67a78b98f 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3881,6 +3881,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-cloud-kit" version = "0.3.2" @@ -5365,6 +5376,7 @@ dependencies = [ "libloading 0.8.9", "log", "objc2", + "objc2-avf-audio", "objc2-foundation", "percent-encoding", "regex", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f7868c710..2a4e5376d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -129,6 +129,10 @@ tauri-plugin-sharekit = { git = "https://github.com/Choochmeque/tauri-plugin-sha objc2 = "0.6" objc2-foundation = { version = "0.3", features = ["NSFileManager", "NSString", "NSURL"] } tauri-plugin-fs = "2" +objc2-avf-audio = { version = "0.3", default-features = false, features = [ + "AVAudioSession", + "AVAudioSessionTypes", +] } [target.'cfg(target_os = "android")'.dependencies] tauri-plugin-android-fs = { version = "=28.4.0", features = ["legacy-storage-permission"] } diff --git a/src-tauri/gen/android/app/src/main/java/moe/sable/client/CallForegroundService.kt b/src-tauri/gen/android/app/src/main/java/moe/sable/client/CallForegroundService.kt index 17aeb4a6d..33a0e974d 100644 --- a/src-tauri/gen/android/app/src/main/java/moe/sable/client/CallForegroundService.kt +++ b/src-tauri/gen/android/app/src/main/java/moe/sable/client/CallForegroundService.kt @@ -1,25 +1,57 @@ package moe.sable.client -import android.app.Notification +import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service -import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo import android.os.Build import android.os.IBinder +import android.util.Log import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat class CallForegroundService : Service() { - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - createNotificationChannel() - startForeground(NOTIFICATION_ID, buildNotification()) + override fun onBind(intent: android.content.Intent?): IBinder? = null + + override fun onStartCommand(intent: android.content.Intent?, flags: Int, startId: Int): Int { + if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + Log.w(TAG, "Microphone permission is not granted; stopping foreground service") + stopSelf(startId) + return START_NOT_STICKY + } + + try { + createNotificationChannel() + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.mipmap.ic_launcher) + .setContentTitle("Call in progress") + .setContentText("Sable is using your microphone") + .setCategory(NotificationCompat.CATEGORY_CALL) + .setOngoing(true) + .setOnlyAlertOnce(true) + .build(), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE + } else { + 0 + } + ) + } catch (error: Exception) { + Log.e(TAG, "Failed to start microphone foreground service", error) + stopSelf(startId) + return START_NOT_STICKY + } + return START_NOT_STICKY } - override fun onBind(intent: Intent?): IBinder? = null - override fun onDestroy() { - stopForeground(true) + stopForeground(STOP_FOREGROUND_REMOVE) super.onDestroy() } @@ -34,19 +66,9 @@ class CallForegroundService : Service() { getSystemService(NotificationManager::class.java).createNotificationChannel(channel) } - private fun buildNotification(): Notification { - return NotificationCompat.Builder(this, CHANNEL_ID) - .setSmallIcon(R.mipmap.ic_notification) - .setContentTitle("Call in progress") - .setContentText("Sable is keeping your call active") - .setCategory(Notification.CATEGORY_CALL) - .setOngoing(true) - .setOnlyAlertOnce(true) - .build() - } - - companion object { - private const val CHANNEL_ID = "call_foreground" - private const val NOTIFICATION_ID = 1395 + private companion object { + const val CHANNEL_ID = "call_foreground" + const val NOTIFICATION_ID = 1395 + const val TAG = "CallForegroundService" } } diff --git a/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt b/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt index b433d7db5..c5b3096f1 100644 --- a/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt +++ b/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt @@ -1,6 +1,8 @@ package moe.sable.client +import android.Manifest import android.content.Intent +import android.content.pm.PackageManager import android.graphics.Color import android.media.AudioAttributes import android.media.MediaPlayer @@ -175,6 +177,22 @@ class MainActivity : TauriActivity() { } } + @JvmStatic + fun startCallForegroundServiceNative() { + val activity = checkNotNull(instance) { "MainActivity is unavailable" } + check( + ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == + PackageManager.PERMISSION_GRANTED + ) { "Microphone permission is not granted" } + ContextCompat.startForegroundService(activity, Intent(activity, CallForegroundService::class.java)) + } + + @JvmStatic + fun stopCallForegroundServiceNative() { + val activity = checkNotNull(instance) { "MainActivity is unavailable" } + activity.stopService(Intent(activity, CallForegroundService::class.java)) + } + private fun isLight(color: Int): Boolean { val luminance = (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255.0 @@ -210,23 +228,5 @@ class MainActivity : TauriActivity() { } } - @JvmStatic - fun startCallForegroundServiceNative() { - val activity = instance ?: return - activity.runOnUiThread { - ContextCompat.startForegroundService( - activity, - Intent(activity, CallForegroundService::class.java) - ) - } - } - - @JvmStatic - fun stopCallForegroundServiceNative() { - val activity = instance ?: return - activity.runOnUiThread { - activity.stopService(Intent(activity, CallForegroundService::class.java)) - } - } } } diff --git a/src-tauri/ios-project.yml b/src-tauri/ios-project.yml index 0209f360d..0c1484928 100644 --- a/src-tauri/ios-project.yml +++ b/src-tauri/ios-project.yml @@ -92,6 +92,9 @@ targets: properties: LSRequiresIPhoneOS: true UILaunchStoryboardName: LaunchScreen + UIBackgroundModes: [audio] + NSMicrophoneUsageDescription: Sable uses your microphone for calls. + NSCameraUsageDescription: Sable uses your camera for video calls. UIRequiredDeviceCapabilities: [arm64, metal] UISupportedInterfaceOrientations: - UIInterfaceOrientationPortrait diff --git a/src-tauri/src/ios.rs b/src-tauri/src/ios.rs index b3160db09..59a449f33 100644 --- a/src-tauri/src/ios.rs +++ b/src-tauri/src/ios.rs @@ -9,6 +9,9 @@ use std::sync::OnceLock; use objc2::rc::{Allocated, Retained}; use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; use objc2::{msg_send, sel}; +use objc2_avf_audio::{ + AVAudioSession, AVAudioSessionCategoryOptions, AVAudioSessionCategoryPlayAndRecord, +}; use tauri::webview::WebviewWindow; extern "C-unwind" fn input_accessory_view_nil(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject { @@ -56,6 +59,25 @@ pub fn haptic_feedback(style: String) { } } +#[tauri::command] +pub fn activate_call_audio_session() -> Result<(), String> { + let session = unsafe { AVAudioSession::sharedInstance() }; + unsafe { + session.setCategory_withOptions_error( + AVAudioSessionCategoryPlayAndRecord.expect("PlayAndRecord category is unavailable"), + AVAudioSessionCategoryOptions::DefaultToSpeaker, + ) + } + .map_err(|error| error.to_string())?; + unsafe { session.setActive_error(true) }.map_err(|error| error.to_string()) +} + +#[tauri::command] +pub fn deactivate_call_audio_session() -> Result<(), String> { + let session = unsafe { AVAudioSession::sharedInstance() }; + unsafe { session.setActive_error(false) }.map_err(|error| error.to_string()) +} + pub fn hide_form_accessory_bar(window: &WebviewWindow) { let _ = window.with_webview(|webview| unsafe { let webview: *mut AnyObject = webview.inner().cast(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 30fec5668..66343198c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -447,6 +447,10 @@ pub fn run() { ios::haptic_feedback, #[cfg(any(target_os = "android", target_os = "ios"))] play_notification_sound, + #[cfg(target_os = "ios")] + ios::activate_call_audio_session, + #[cfg(target_os = "ios")] + ios::deactivate_call_audio_session, #[cfg(desktop)] desktop::download::save_download, #[cfg(desktop)] diff --git a/src/app/generated/tauri/commands.ts b/src/app/generated/tauri/commands.ts index c4e3811cf..f402febf8 100644 --- a/src/app/generated/tauri/commands.ts +++ b/src/app/generated/tauri/commands.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-27T14:52:10.696863893+00:00 + * Generated at: 2026-07-29T09:24:56.411984+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate @@ -18,10 +18,18 @@ export async function abortNativeUpload(params: types.AbortNativeUploadParams): return invoke('abort_native_upload', params); } +export async function activateCallAudioSession(): Promise { + return invoke('activate_call_audio_session'); +} + export async function clearMediaSession(): Promise { return invoke('clear_media_session'); } +export async function deactivateCallAudioSession(): Promise { + return invoke('deactivate_call_audio_session'); +} + export async function exportDiagnostics(params: types.ExportDiagnosticsParams): Promise { return invoke('export_diagnostics', params); } @@ -98,10 +106,18 @@ export async function showSnapOverlay(): Promise { return invoke('show_snap_overlay'); } +export async function startCallForegroundService(): Promise { + return invoke('start_call_foreground_service'); +} + export async function startWindowTrackingWithTarget(params: types.StartWindowTrackingWithTargetParams): Promise { return invoke('start_window_tracking_with_target', params); } +export async function stopCallForegroundService(): Promise { + return invoke('stop_call_foreground_service'); +} + export async function stopWindowTracking(): Promise { return invoke('stop_window_tracking'); } diff --git a/src/app/generated/tauri/events.ts b/src/app/generated/tauri/events.ts index cf2db300a..5d4703b02 100644 --- a/src/app/generated/tauri/events.ts +++ b/src/app/generated/tauri/events.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-26T18:31:24.510042400+00:00 + * Generated at: 2026-07-29T09:24:56.415138+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/generated/tauri/index.ts b/src/app/generated/tauri/index.ts index 0f9a3b033..c15cf28d9 100644 --- a/src/app/generated/tauri/index.ts +++ b/src/app/generated/tauri/index.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-26T18:31:24.510311700+00:00 + * Generated at: 2026-07-29T09:24:56.415651+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/generated/tauri/types.ts b/src/app/generated/tauri/types.ts index f68376749..83aef83d8 100644 --- a/src/app/generated/tauri/types.ts +++ b/src/app/generated/tauri/types.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-26T18:31:24.507322700+00:00 + * Generated at: 2026-07-29T09:24:56.409726+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index fe86a76d0..829b06481 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -11,7 +11,7 @@ import { } from 'matrix-widget-api'; import { CallWidgetDriver } from './CallWidgetDriver'; import { trimTrailingSlash } from '../../utils/common'; -import { getWindowOrigin, isAndroidTauri } from '../../utils/platform'; +import { getWindowOrigin, iosApp, isAndroidTauri } from '../../utils/platform'; import type { ElementCallThemeKind, ElementMediaStateDetail } from './types'; import { color, config } from 'folds'; import { ElementCallIntent, ElementWidgetActions } from './types'; @@ -46,6 +46,10 @@ export class CallEmbed { public joined = false; + private initialMediaStateReceived = false; + + private nativeCallRuntimeActive = false; + public readonly control: CallControl; private readonly container: HTMLElement; @@ -230,7 +234,9 @@ export class CallEmbed { this.call.transport.reply(evt.detail as IWidgetApiRequest, {}); if (initialMediaEvent) { initialMediaEvent = false; + this.initialMediaStateReceived = true; this.control.applyState(); + this.startNativeCallRuntime(); return; } this.control.onMediaState(evt as CustomEvent); @@ -356,7 +362,22 @@ export class CallEmbed { */ public dispose(): void { debugLog.info('call', 'Disposing call widget', { roomId: this.roomId }); - this.invokeForegroundService('stop_call_foreground_service'); + if (this.nativeCallRuntimeActive && isAndroidTauri()) { + void invoke('stop_call_foreground_service').catch((error) => { + debugLog.error('call', 'Failed to stop call foreground service', { + roomId: this.roomId, + error: error instanceof Error ? error.message : String(error), + }); + }); + } else if (this.nativeCallRuntimeActive && iosApp()) { + void invoke('deactivate_call_audio_session').catch((error) => { + debugLog.error('call', 'Failed to deactivate call audio session', { + roomId: this.roomId, + error: error instanceof Error ? error.message : String(error), + }); + }); + } + this.nativeCallRuntimeActive = false; this.disposables.forEach((disposable) => { disposable(); }); @@ -375,16 +396,33 @@ export class CallEmbed { this.call.transport.reply(evt.detail as IWidgetApiRequest, {}); debugLog.info('call', 'Call joined', { roomId: this.roomId }); this.joined = true; - this.invokeForegroundService('start_call_foreground_service'); + this.startNativeCallRuntime(); this.applyStyles(); this.control.startObserving(); } - private invokeForegroundService( - command: 'start_call_foreground_service' | 'stop_call_foreground_service' - ): void { - if (!isAndroidTauri()) return; - void invoke(command).catch(() => {}); + private startNativeCallRuntime(): void { + if (!this.joined || !this.initialMediaStateReceived || this.nativeCallRuntimeActive) return; + + if (isAndroidTauri()) { + this.nativeCallRuntimeActive = true; + void invoke('start_call_foreground_service').catch((error) => { + this.nativeCallRuntimeActive = false; + debugLog.error('call', 'Failed to start call foreground service', { + roomId: this.roomId, + error: error instanceof Error ? error.message : String(error), + }); + }); + } else if (iosApp()) { + this.nativeCallRuntimeActive = true; + void invoke('activate_call_audio_session').catch((error) => { + this.nativeCallRuntimeActive = false; + debugLog.error('call', 'Failed to activate call audio session', { + roomId: this.roomId, + error: error instanceof Error ? error.message : String(error), + }); + }); + } } private applyStyles(): void {