From 0aa7219a592ea2773ea97eebe6504425b5c6c7fa Mon Sep 17 00:00:00 2001 From: evgeny Date: Wed, 28 Oct 2026 21:20:41 +0100 Subject: [PATCH] Confirm call cleanup before releasing ownership and retry every retained resource independently --- .../java/com/utun/chat/data/CallService.kt | 175 ++++++++++++++---- 1 file changed, 136 insertions(+), 39 deletions(-) diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallService.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallService.kt index 5a7ccfe41..bdf35ebcf 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallService.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallService.kt @@ -238,25 +238,60 @@ class CallService : Service() { } fun startAudio(id: Long): Boolean { - if (id != callId || wakeLock?.isHeld != true) { - LogManager.addLog("ERROR", "CallService", "audio start rejected id=$id owned=$callId lock=${wakeLock?.isHeld}") + checkMain() + if (id == 0L || id != callId || stopping || destroyed) { + LogManager.addLog("ERROR", "CallService", "audio start rejected id=$id owned=$callId stopping=$stopping destroyed=$destroyed") + return false + } + if (audioOwned && audio.isActive() && video != null) return true + var operation = "wake lock" + try { + check(wakeLock?.isHeld == true) { "CPU lock not held" } + operation = "route" + audio.router.setPreferredRoute(ChatApplication.instance.configProvider.getCallAudioRoute()) + operation = "audio" + audioOwned = true + check(audio.start(id)) { "audio engine rejected start" } + operation = "video" + video = CallVideoEngine(this, id) + LogManager.addLog("INFO", "CallService", "audio/video started id=$id") + return true + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "audio start failed operation=$operation id=$id: $e") + shutdown() return false } - audio.router.setPreferredRoute(ChatApplication.instance.configProvider.getCallAudioRoute()) - if (!audio.start(id)) return false - video = CallVideoEngine(this, id) - return true } fun setVideoCapture(enabled: Boolean): Boolean { - return try { cameraForeground = enabled; promote(true); true } - catch (e: Exception) { cameraForeground = false; LogManager.addLog("ERROR", "call", "camera foreground failed: ${e.message}"); false } + checkMain() + if (callId == 0L || stopping || destroyed || !audioOwned || video == null) { + LogManager.addLog("WARN", "CallService", "camera request rejected id=$callId enabled=$enabled stopping=$stopping") + return false + } + val previous = cameraForeground + return try { + cameraForeground = enabled + promote(true) + LogManager.addLog("INFO", "CallService", "camera foreground confirmed id=$callId enabled=$enabled") + true + } catch (e: Exception) { + cameraForeground = previous + LogManager.addLog("ERROR", "CallService", "camera foreground failed id=$callId requested=$enabled lastConfirmed=$previous: $e") + false + } } fun updateNotification() { - requireNotNull(getSystemService(NotificationManager::class.java)) { "notification manager unavailable" } - .notify(NOTIFICATION_ID, notification()) - LogManager.addLog("INFO", "CallService", "notification updated id=$callId phase=${CallController.state.value?.phase}") + checkMain() + if (callId == 0L || stopping || destroyed || !foregroundOwned) return + try { + requireNotNull(getSystemService(NotificationManager::class.java)) { "notification manager unavailable" } + .notify(NOTIFICATION_ID, notification()) + LogManager.addLog("INFO", "CallService", "notification updated id=$callId phase=${CallController.state.value?.phase}") + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "notification update failed id=$callId: $e") + } } private fun notification(): Notification { @@ -264,12 +299,13 @@ class CallService : Service() { val active = st?.phase == CallPhase.ACTIVE val person = Person.Builder().setName(st?.peerName?.takeIf { it.isNotBlank() } ?: "vibechat") .setKey("node:${st?.peerNodeId}").build() - val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) - val end = PendingIntent.getService(this, 0, + val open = openIntent ?: PendingIntent.getActivity(this, 0, + Intent(this, MainActivity::class.java).setData(Uri.parse("utun-call:open:$callId")), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE).also { openIntent = it } + val end = endIntent ?: PendingIntent.getService(this, 0, Intent(this, CallService::class.java).setAction(ACTION_END) .setData(Uri.parse("utun-call:$callId")).putExtra(EXTRA_ID, callId), - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE).also { endIntent = it } val builder = NotificationCompat.Builder(AppLanguage.context(), CHANNEL) .setSmallIcon(android.R.drawable.ic_menu_call) .setContentTitle(person.name) @@ -296,44 +332,105 @@ class CallService : Service() { return builder.build() } - /** Идемпотентное освобождение до остановки сервиса; выполняется в main thread. */ - fun shutdown() { + /** На main независимо очистить владельцев. Deferred завершается только после подтверждения всех операций. + * При отказе сохраняется один process-владелец и отменяемый retry 250мс..30с; main не ждёт Deferred. */ + fun shutdown(): Deferred { + checkMain() + main.removeCallbacks(retryCleanup) + stopping = true releaseResources() - stopForeground(STOP_FOREGROUND_REMOVE) - stopSelf() + if (!audioOwned && video == null) { + if (foregroundOwned) try { + stopForeground(STOP_FOREGROUND_REMOVE) + foregroundOwned = false + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "foreground removal failed id=$callId; retained for retry: $e") + } + if (!stopRequested) try { + if (!destroyed) stopSelf(lastStartId) + stopRequested = true + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "service stop failed id=$callId; retained for retry: $e") + } + } + val pending = audioOwned || video != null || wakeLock != null || powerEventsRegistered || + foregroundOwned || openIntent != null || endIntent != null || !stopRequested + if (pending) { + check(pendingCleanup == null || pendingCleanup === this) { "Two retained call service owners" } + pendingCleanup = this + val delay = retryDelayMs + retryDelayMs = (retryDelayMs * 2).coerceAtMost(30_000L) + if (!main.postDelayed(retryCleanup, delay)) LogManager.addLog("ERROR", "CallService", + "cleanup retry rejected id=$callId audio=$audioOwned video=${video != null} lock=${wakeLock != null} " + + "receiver=$powerEventsRegistered; retained for explicit retry") + else LogManager.addLog("DEBUG", "CallService", "cleanup retry scheduled id=$callId delayMs=$delay") + } else { + val id = callId + callId = 0L; cameraForeground = false; retryDelayMs = 250L + if (pendingCleanup === this) pendingCleanup = null + if (released.complete(Unit)) LogManager.addLog("INFO", "CallService", "resources released id=$id; cleanup confirmed") + } + return released } private fun releaseResources() { val id = callId - video?.stop(); video = null; cameraForeground = false - if (powerEventsRegistered) { - try { unregisterReceiver(powerEvents) } - catch (e: Exception) { LogManager.addLog("WARN", "CallService", "power receiver cleanup failed id=$id: ${e.message}") } - powerEventsRegistered = false - } + audio.onFailure = null audio.router.onChanged = null - try { + video?.let { owned -> try { + owned.stop() + video = null + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "video stop failed id=$id; retained for retry: $e") + } } + if (audioOwned) try { audio.stop() - } finally { - wakeLock?.let { lock -> - try { - if (lock.isHeld) lock.release() - } catch (e: Exception) { - LogManager.addLog("ERROR", "CallService", "wake lock release failed id=$id: ${e.message}") - } + audioOwned = false + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "audio stop failed id=$id; retained for retry: $e") + } + if (powerEventsRegistered) { + try { + unregisterReceiver(powerEvents) + powerEventsRegistered = false + } catch (e: IllegalArgumentException) { + powerEventsRegistered = false + LogManager.addLog("WARN", "CallService", "power receiver already absent id=$id: $e") + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "power receiver cleanup failed id=$id; retained for retry: $e") } + } + wakeLock?.let { lock -> try { + if (lock.isHeld) lock.release() wakeLock = null - callId = 0L - if (id != 0L) LogManager.addLog("INFO", "CallService", "resources released id=$id; CPU lock cleared") + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "wake lock release failed id=$id; retained for retry: $e") + } } + openIntent?.let { token -> try { + token.cancel(); openIntent = null + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "open action cancellation failed id=$id; retained for retry: $e") + } } + endIntent?.let { token -> try { + token.cancel(); endIntent = null + } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "END action cancellation failed id=$id; retained for retry: $e") + } } } } override fun onDestroy() { + checkMain() + if (destroyed) return + destroyed = true val id = callId - releaseResources() - CallController.serviceLost(id, this) - LogManager.addLog("INFO", "CallService", "destroyed id=$id") - super.onDestroy() + try { + shutdown() + try { CallController.serviceLost(id, this) } catch (e: Exception) { + LogManager.addLog("ERROR", "CallService", "service lost callback failed id=$id: $e") + } + LogManager.addLog("INFO", "CallService", "destroyed id=$id cleanupComplete=${released.isCompleted}") + } finally { super.onDestroy() } } override fun onBind(intent: Intent?): IBinder? = null