From 0db3ceea8132bc39c602d52f06745eebe9983e21 Mon Sep 17 00:00:00 2001 From: evgeny Date: Wed, 28 Oct 2026 00:28:42 +0100 Subject: [PATCH] Recover Android media audio sessions with explicit resource ownership Retry monitor and capture setup after invalidating failed attempts. Bind output leases and callbacks to registration identity, cancel confirmation timers, and keep hardware cleanup independent from device enumeration during call handoff. Commit profiles only after successful storage writes, acquire mode ownership before Android side effects, and reject blocking operations on main or the control worker. Keep the app singleton backed by an isolated MediaAudioSession with a single executor. Validation: 30 media session scenarios, 420 JVM tests, assembleDebug, core build, and full check.sh (225 tests plus proxy/burst/load) passed. --- .../utun/chat/data/MediaAudioController.kt | 256 ++++++++--- .../router-tests/build.gradle.kts | 2 + .../main/kotlin/android/media/HostAudio.kt | 2 + .../main/kotlin/android/media/HostTracks.kt | 47 ++ .../kotlin/com/utun/chat/RouterHostApp.kt | 1 + .../utun/chat/data/IncomingHostEnvironment.kt | 2 + .../com/utun/chat/data/MediaHostCapture.kt | 38 ++ .../utun/chat/data/RouterHostEnvironment.kt | 18 + .../utun/chat/data/MediaAudioSessionTest.kt | 428 ++++++++++++++++++ 9 files changed, 727 insertions(+), 67 deletions(-) create mode 100644 tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostTracks.kt create mode 100644 tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/MediaHostCapture.kt create mode 100644 tools/chatgui-android/router-tests/src/test/kotlin/com/utun/chat/data/MediaAudioSessionTest.kt diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/MediaAudioController.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/MediaAudioController.kt index 772d9b357..9649d9ee8 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/MediaAudioController.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/MediaAudioController.kt @@ -13,6 +13,9 @@ import com.utun.chat.R import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import java.util.concurrent.Executors +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit enum class MediaAudioProfile { AUTO, PHONE, WIRED, BLUETOOTH } @@ -23,14 +26,24 @@ data class MediaAudioState( val inputName: String? = null, val outputName: String? = null, val switching: Boolean = false, val notice: Int? = null ) -/** Общий владелец аудио рации и трансляций. Маршрутизация — тот же CallAudioRouter, что у звонка. - * UI только выбирает профиль. Аппаратный reader и регистрация AudioTrack принадлежат io. - * Постоянные stereo-подписки сохраняют PTT, mute и PTS при смене устройства; видео не затрагивается. */ -object MediaAudioController { +/** Единственная app-scoped сессия общего аудио рации и трансляций; живёт до завершения процесса. */ +internal object MediaAudioController : MediaAudioSession() + +/** + * Владелец общего аудио: router, аппаратный reader, AudioTrack leases и один таймер подтверждения. + * Все изменения оборудования выполняет единственный io worker; подписки PCM защищены inputLock. + * refresh/select асинхронны. attachOutput/close lease/awaitIdle/close блокируют вызывающего worker, + * поэтому main и io для них запрещены. Track регистрируется до play и отсоединяется до release. + * Ошибки инвалидируют поколение; следующий refresh повторяет попытку, сохраняя действующие PCM-подписки. + * Настройка становится committed только после успешной записи. close требует отсутствия потребителей. + */ +internal open class MediaAudioSession(private val io: ScheduledExecutorService = + Executors.newSingleThreadScheduledExecutor { Thread(it, "media-audio-control").apply { isDaemon = true } }) : AutoCloseable { private val app get() = ChatApplication.instance private val am = app.getSystemService(Context.AUDIO_SERVICE) as AudioManager private val main = Handler(Looper.getMainLooper()) - private val io = Executors.newSingleThreadScheduledExecutor { Thread(it, "media-audio-control").apply { isDaemon = true } } + @Volatile private var controlThread: Thread? = null + @Volatile private var closed = false private val router = CallAudioRouter() private val mutable = MutableStateFlow(MediaAudioState()) val state: StateFlow = mutable @@ -45,10 +58,17 @@ object MediaAudioController { private var systemRoute: Pair? = null private var preferred = MediaAudioProfile.AUTO private var committed = preferred + private var preferencesLoaded = false private var forcedPhone = false private var savePending = false private var modeOwned = false - private val outputs = linkedMapOf() + private class OutputRegistration { + lateinit var listener: AudioRouting.OnRoutingChangedListener + var reported = false + var deviceId: Int? = null + } + private val outputs = linkedMapOf() + private var confirmationTimeout: ScheduledFuture<*>? = null private var wantedOutput: AudioDeviceInfo? = null private var wantedInputName: String? = null private var routeAvailable = false @@ -58,41 +78,39 @@ object MediaAudioController { // Наблюдение не занимает микрофон и не меняет глобальный маршрут без потребителей. router.fallbackRoute = AudioRoute.SPEAKER router.setGlobalRouting(false) - router.onChanged = { _, _ -> refresh() } - router.onInputDevicesChanged = { _, _ -> refresh() } - router.onInputDevice = { refresh() } - router.onOutputDevice = { refresh() } - io.execute { - try { - preferred = kotlinx.coroutines.runBlocking { app.configProvider.getMediaAudioProfile() }; committed = preferred - router.start() - reconcile() - } catch (e: Exception) { recover(e) } + // Собственный apply учитывается текущей транзакцией; внешние события возвращаются на io. + val routeChanged = { if (Thread.currentThread() !== controlThread) refresh() } + router.onChanged = { _, _ -> routeChanged() } + router.onInputDevicesChanged = { _, _ -> routeChanged() } + router.onInputDevice = { routeChanged() } + router.onOutputDevice = { routeChanged() } + enqueue { + controlThread = Thread.currentThread() + reconcile() } } fun refresh() { - io.execute { - try { reconcile() } - catch (e: Exception) { recover(e) } - } + enqueue { reconcile() } } fun select(profile: MediaAudioProfile) { - io.execute { + enqueue { if (CallController.blocksMedia()) { - LogManager.addLog("WARN", "media_audio", "selection blocked by call profile=$profile"); return@execute + LogManager.addLog("WARN", "media_audio", "selection blocked by call profile=$profile"); return@enqueue } + loadPreferences() preferred = profile; forcedPhone = false; savePending = true mutable.value = mutable.value.copy(notice = null) LogManager.addLog("INFO", "media_audio", "profile requested=$profile") - try { router.reapply(); reconcile(force = true) } - catch (e: Exception) { recover(e) } + router.reapply() + reconcile(force = true) } } /** Не открывает микрофон из UI. Вызывается реальным владельцем захвата с RECORD_AUDIO. */ fun subscribe(name: String): MicrophoneCapture.Subscription = synchronized(inputLock) { + check(!closed) { "Media audio session closed" } check(!CallController.blocksMedia()) { "Media capture blocked by call" } if (shared?.closed != false) { val device = InputBridge() @@ -105,37 +123,53 @@ object MediaAudioController { /** Регистрация завершается до play, удаление — до release. Не вызывается из main или io. */ fun attachOutput(track: AudioTrack): AutoCloseable { - io.submit { + checkBlockingCaller() + check(!closed) { "Media audio session closed" } + val registration = io.submit { + check(!closed) { "Media audio session closed" } check(!CallController.blocksMedia()) { "Media output blocked by call" } - val listener = AudioRouting.OnRoutingChangedListener { - val actual = track.routedDevice - LogManager.addLog("INFO", "media_audio", "output routed session=${track.audioSessionId} " + - "device=${actual?.id}/${actual?.type} mode=${am.mode} sco=${am.isBluetoothScoOn}") - refresh() - } check(track !in outputs) { "AudioTrack already registered" } - outputs[track] = listener + val owner = OutputRegistration() + owner.listener = AudioRouting.OnRoutingChangedListener { + enqueue { + if (outputs[track] !== owner) return@enqueue + val actual = track.routedDevice + if (owner.reported && owner.deviceId == actual?.id) return@enqueue + owner.reported = true; owner.deviceId = actual?.id + LogManager.addLog("INFO", "media_audio", "output routed session=${track.audioSessionId} " + + "device=${actual?.id}/${actual?.type} mode=${am.mode} sco=${am.isBluetoothScoOn}") + reconcile() + } + } + outputs[track] = owner try { - track.addOnRoutingChangedListener(listener, main) + track.addOnRoutingChangedListener(owner.listener, main) reconcile() check(track.setPreferredDevice(wantedOutput)) { "Output selection rejected session=${track.audioSessionId}" } mutable.value = mutable.value.copy(switching = true) + ensureTimeout() confirm() - val epoch = generation - io.schedule({ if (generation == epoch && track in outputs && !outputsReady(listOf(track))) - recover(IllegalStateException("Output confirmation timeout session=${track.audioSessionId} " + - "wanted=${wantedOutput?.id} actual=${track.routedDevice?.id}")) }, 30, TimeUnit.SECONDS) } catch (e: Exception) { - outputs.remove(track); track.removeOnRoutingChangedListener(listener) + outputs.remove(track) + try { track.removeOnRoutingChangedListener(owner.listener) } catch (cleanup: Exception) { + LogManager.addLog("WARN", "media_audio", "output listener cleanup failed session=${track.audioSessionId}: $cleanup") + } LogManager.addLog("ERROR", "media_audio", "output registration failed session=${track.audioSessionId}: $e") recover(e) throw e } LogManager.addLog("INFO", "media_audio", "output attached session=${track.audioSessionId} count=${outputs.size}") + owner }.get() return AutoCloseable { + if (closed) return@AutoCloseable + checkBlockingCaller() io.submit { - outputs.remove(track)?.let { track.removeOnRoutingChangedListener(it) } + if (outputs[track] !== registration) return@submit + outputs.remove(track) + try { track.removeOnRoutingChangedListener(registration.listener) } catch (e: Exception) { + LogManager.addLog("WARN", "media_audio", "output listener removal failed session=${track.audioSessionId}: $e") + } try { reconcile() } catch (e: Exception) { recover(e) } LogManager.addLog("INFO", "media_audio", "output detached session=${track.audioSessionId} count=${outputs.size}") @@ -145,13 +179,46 @@ object MediaAudioController { /** Барьер cleanup после остановки всех движков, перед передачей ресурсов Telecom. */ fun awaitIdle() { + checkBlockingCaller() io.submit { check(outputs.isEmpty() && synchronized(inputLock) { shared?.closed != false }) { "Media audio still owned" } - reconcile() + invalidateAttempt() + releaseHardware() + mutable.value = mutable.value.copy(switching = false, inputName = null, outputName = null) LogManager.addLog("INFO", "media_audio", "all media audio resources released for call") }.get() } + override fun close() { + if (closed) return + checkBlockingCaller() + try { + io.submit { + synchronized(inputLock) { + check(outputs.isEmpty() && shared?.closed != false) { "Media audio still owned" } + closed = true + } + invalidateAttempt() + try { releaseHardware() } finally { router.stop() } + LogManager.addLog("INFO", "media_audio", "session closed") + }.get() + } finally { if (closed) io.shutdown() } + } + + private fun checkBlockingCaller() = check(Looper.myLooper() != Looper.getMainLooper() && Thread.currentThread() !== controlThread) { + LogManager.addLog("ERROR", "media_audio", "blocking audio operation requires a consumer worker") + "Media audio operation cannot block main/control thread" + } + + private fun enqueue(action: () -> Unit) { + if (closed) return + try { + io.execute { if (!closed) try { action() } catch (e: Exception) { recover(e) } } + } catch (e: RejectedExecutionException) { + if (!closed) LogManager.addLog("ERROR", "media_audio", "control task rejected: $e") + } + } + private fun isWired(type: Int) = type == AudioDeviceInfo.TYPE_WIRED_HEADSET || type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || type == AudioDeviceInfo.TYPE_USB_HEADSET || type == AudioDeviceInfo.TYPE_USB_DEVICE || type == AudioDeviceInfo.TYPE_USB_ACCESSORY @@ -161,11 +228,13 @@ object MediaAudioController { private fun isBluetooth(type: Int) = type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || isBluetoothMedia(type) private fun reconcile(force: Boolean = false) { + loadPreferences() + router.start() val devices = am.getDevices(AudioManager.GET_DEVICES_ALL).toList() val wired = devices.any { isWired(it.type) } val bluetooth = router.btInputAvailable || devices.any { isBluetooth(it.type) } val available = wired to bluetooth - if (availability?.let { (!it.first && wired) || (!it.second && bluetooth) } == true) forcedPhone = false + if (availability == null || availability?.let { (!it.first && wired) || (!it.second && bluetooth) } == true) forcedPhone = false availability = available val resolved = when (preferred) { MediaAudioProfile.AUTO -> if (wired) MediaAudioProfile.WIRED else if (bluetooth) MediaAudioProfile.BLUETOOTH else MediaAudioProfile.PHONE @@ -196,14 +265,14 @@ object MediaAudioController { val route = active to (voice && owned) if (systemRoute != route) { // Смена глобального тракта принадлежит только этому владельцу, до открытия нового reader. - record?.close(); record = null - router.setGlobalRouting(false) - if (modeOwned) { am.mode = AudioManager.MODE_NORMAL; modeOwned = false } + invalidateAttempt() + releaseHardware() router.setAutoHeadset(false) router.setRoute(if (active == MediaAudioProfile.PHONE) AudioRoute.SPEAKER else AudioRoute.HEADSET, preferWired = active == MediaAudioProfile.WIRED) if (voice && owned) { - am.mode = AudioManager.MODE_IN_COMMUNICATION; modeOwned = true + modeOwned = true + am.mode = AudioManager.MODE_IN_COMMUNICATION router.setGlobalRouting(true) } systemRoute = route @@ -220,16 +289,16 @@ object MediaAudioController { notice = if (preferred != MediaAudioProfile.AUTO && preferred != resolved) R.string.media_audio_fallback else mutable.value.notice?.takeUnless { it == R.string.media_audio_fallback }) if (!force && key == routeKey) { confirm(); return } - routeKey = key - val epoch = ++generation + invalidateAttempt() + val epoch = generation inputReady = capture == null - targetBridge?.reset(epoch) record?.close(); record = null mutable.value = mutable.value.copy(switching = owned) if (!owned) { wantedOutput = null mutable.value = mutable.value.copy(switching = false, inputName = null, outputName = null) saveSelection() + routeKey = key return } LogManager.addLog("INFO", "media_audio", "apply generation=$epoch preferred=$preferred active=$active " + @@ -238,18 +307,14 @@ object MediaAudioController { wantedInputName = if (capture != null) input?.productName?.toString() else null routeAvailable = output != null && (active != MediaAudioProfile.BLUETOOTH || isBluetooth(output.type)) for (track in outputs.keys) check(track.setPreferredDevice(output)) { "Output rejected session=${track.audioSessionId} device=${output?.id}" } - val expectedOutputs = outputs.keys.toList() - io.schedule({ - if (generation == epoch && (!inputReady || !routeAvailable || !outputsReady(expectedOutputs))) - recover(IllegalStateException("Audio route confirmation timeout generation=$epoch inputReady=$inputReady " + - "wantedOutput=${wantedOutput?.id} actualOutputs=${outputs.keys.map { it.routedDevice?.id }} state=${mutable.value}")) - }, if (active == MediaAudioProfile.BLUETOOTH) 30 else 6, TimeUnit.SECONDS) if (capture != null && input != null) { record = AndroidMicrophoneCapture.open(input, voice, stereo, micSource, epoch, accept = { frame -> targetBridge?.offer(frame) == true }, - failed = { error -> io.execute { if (generation == epoch) recover(error) } }, - confirmed = { io.execute { if (generation == epoch) { inputReady = true; confirm() } } }) + failed = { error -> enqueue { if (generation == epoch) recover(error) } }, + confirmed = { enqueue { if (generation == epoch) { inputReady = true; confirm() } } }) } else if (capture != null && active != MediaAudioProfile.BLUETOOTH) error("Selected microphone unavailable profile=$active") + routeKey = key + ensureTimeout() confirm() } @@ -259,6 +324,7 @@ object MediaAudioController { mutable.value = mutable.value.copy(switching = false, inputName = wantedInputName, outputName = wantedOutput?.productName?.toString()) saveSelection() + confirmationTimeout?.cancel(false); confirmationTimeout = null LogManager.addLog("INFO", "media_audio", "route confirmed generation=$generation mode=${am.mode} sco=${am.isBluetoothScoOn} state=${mutable.value}") } @@ -269,23 +335,79 @@ object MediaAudioController { private fun saveSelection() { if (!savePending) return - savePending = false; committed = preferred kotlinx.coroutines.runBlocking { app.configProvider.setMediaAudioProfile(preferred) } + savePending = false; committed = preferred + LogManager.addLog("INFO", "media_audio", "profile saved=$committed") + } + + private fun loadPreferences() { + if (preferencesLoaded) return + preferred = kotlinx.coroutines.runBlocking { app.configProvider.getMediaAudioProfile() } + committed = preferred; preferencesLoaded = true + LogManager.addLog("INFO", "media_audio", "profile loaded=$preferred") + } + + private fun invalidateAttempt() { + confirmationTimeout?.cancel(false); confirmationTimeout = null + ++generation + routeKey = null; inputReady = false; routeAvailable = false + synchronized(inputLock) { bridge }?.reset(generation) + } + + private fun ensureTimeout() { + if (confirmationTimeout != null || !mutable.value.switching) return + val epoch = generation + lateinit var task: ScheduledFuture<*> + task = io.schedule({ + if (closed || generation != epoch || confirmationTimeout !== task) return@schedule + confirmationTimeout = null + try { + check(inputReady && routeAvailable && outputsReady(outputs.keys)) { + "Audio route confirmation timeout generation=$epoch inputReady=$inputReady " + + "wantedOutput=${wantedOutput?.id} state=${mutable.value}" + } + confirm() + } catch (e: Exception) { recover(e) } + }, if (mutable.value.active == MediaAudioProfile.BLUETOOTH) 30 else 6, TimeUnit.SECONDS) + confirmationTimeout = task + } + + private fun releaseHardware() { + var failure: Exception? = null + try { record?.close(); record = null } catch (e: Exception) { + LogManager.addLog("ERROR", "media_audio", "capture release failed generation=$generation: $e") + failure = e + } + try { router.setGlobalRouting(false) } catch (e: Exception) { + LogManager.addLog("ERROR", "media_audio", "global route release failed: $e") + if (failure == null) failure = e + } + if (modeOwned) try { am.mode = AudioManager.MODE_NORMAL; modeOwned = false } catch (e: Exception) { + LogManager.addLog("ERROR", "media_audio", "audio mode release failed: $e") + if (failure == null) failure = e + } + systemRoute = null + failure?.let { throw it } } private fun recover(error: Exception) { LogManager.addLog("ERROR", "media_audio", "route failed generation=$generation preferred=$preferred: $error") if (savePending) { preferred = committed; savePending = false } - mutable.value = mutable.value.copy(notice = R.string.media_audio_failed, switching = false) - if (!forcedPhone) { - forcedPhone = true - try { reconcile(force = true) } - catch (e: Exception) { recover(e) } - } else { - ++generation - synchronized(inputLock) { bridge }?.reset(generation) - record?.close(); record = null; inputReady = false - mutable.value = mutable.value.copy(switching = false) + val fallback = !forcedPhone + forcedPhone = true + mutable.value = mutable.value.copy(preferred = preferred, notice = R.string.media_audio_failed, + switching = false, inputName = null, outputName = null) + invalidateAttempt() + try { + releaseHardware() + if (fallback) reconcile(force = true) + } catch (e: Exception) { + LogManager.addLog("ERROR", "media_audio", "fallback failed generation=$generation: $e") + invalidateAttempt() + try { releaseHardware() } catch (cleanup: Exception) { + LogManager.addLog("ERROR", "media_audio", "fallback cleanup failed: $cleanup") + } + mutable.value = mutable.value.copy(switching = false, inputName = null, outputName = null) } } diff --git a/tools/chatgui-android/router-tests/build.gradle.kts b/tools/chatgui-android/router-tests/build.gradle.kts index 1e564cc62..76c159631 100644 --- a/tools/chatgui-android/router-tests/build.gradle.kts +++ b/tools/chatgui-android/router-tests/build.gradle.kts @@ -10,6 +10,8 @@ kotlin { kotlin.include("android/**", "androidx/**", "com/utun/chat/RouterHostApp.kt", "com/utun/chat/data/RouterHostEnvironment.kt", "com/utun/chat/data/IncomingHostEnvironment.kt", "com/utun/chat/data/IncomingCallManager.kt", "com/utun/chat/data/IncomingCallActionReceiver.kt", + "com/utun/chat/data/MediaAudioController.kt", "com/utun/chat/data/MicrophoneCapture.kt", + "com/utun/chat/data/MediaCaptureTimeline.kt", "com/utun/chat/data/MediaHostCapture.kt", "com/utun/chat/data/CallAudioRouter.kt", "com/utun/chat/data/CoreActivity.kt", "com/utun/chat/data/ProximityManager.kt", "com/utun/chat/data/PhoneStateMonitor.kt", "com/utun/chat/data/NetworkActivityMonitor.kt", "com/utun/chat/data/NetworkChangeMonitor.kt", diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostAudio.kt b/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostAudio.kt index 9f12ac5b4..a4ff236c2 100644 --- a/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostAudio.kt +++ b/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostAudio.kt @@ -23,6 +23,7 @@ class AudioManager { const val AUDIO_SESSION_ID_GENERATE = 0 const val RINGER_MODE_SILENT = 0; const val RINGER_MODE_VIBRATE = 1; const val RINGER_MODE_NORMAL = 2 const val STREAM_RING = 2 + const val MODE_NORMAL = 0; const val MODE_IN_COMMUNICATION = 3 const val AUDIOFOCUS_GAIN_TRANSIENT = 2; const val AUDIOFOCUS_GAIN = 1 const val AUDIOFOCUS_LOSS = -1; const val AUDIOFOCUS_LOSS_TRANSIENT = -2; const val AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK = -3 const val AUDIOFOCUS_REQUEST_GRANTED = 1; const val AUDIOFOCUS_REQUEST_FAILED = 0 @@ -58,6 +59,7 @@ class AudioManager { var isSpeakerphoneOn = false set(value) { operation("speaker=$value"); field = value } var mode = 0 + set(value) { operation("mode=$value"); field = value; operation("mode after=$value") } val callbacks = mutableSetOf() val callbackHistory = mutableListOf() var devices = arrayOf(AudioDeviceInfo(1, 2, true, false, "speaker"), AudioDeviceInfo(2, 15, false, true, "mic")) diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostTracks.kt b/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostTracks.kt new file mode 100644 index 000000000..65a2e4042 --- /dev/null +++ b/tools/chatgui-android/router-tests/src/main/kotlin/android/media/HostTracks.kt @@ -0,0 +1,47 @@ +package android.media + +import android.os.Handler + +interface AudioRouting { + fun interface OnRoutingChangedListener { fun onRoutingChanged(router: AudioRouting) } +} + +/** Только JVM: descriptor может подтвердиться позже, callback сохраняется после удаления для проверки lease identity. */ +class AudioTrack(val id: Int) : AudioRouting { + var failures = emptySet() + var acceptPreference = true + var autoRoute = true + var emitOnPreference = false + var released = false + var accessAfterRelease = 0 + var actual: AudioDeviceInfo? = null + var preferred: AudioDeviceInfo? = null + var selectionAttempts = 0 + val history = mutableListOf() + val listeners = mutableMapOf() + private fun access(operation: String) { + if (released) accessAfterRelease++ + check(!released) { "track released: $operation" } + check(operation !in failures) { "track failed: $operation" } + } + val audioSessionId: Int get() { access("session"); return id } + val routedDevice: AudioDeviceInfo? get() { access("routed"); return actual } + fun addOnRoutingChangedListener(listener: AudioRouting.OnRoutingChangedListener, handler: Handler) { + access("add listener") + history.add(listener); listeners[listener] = handler + access("add listener after") + } + fun removeOnRoutingChangedListener(listener: AudioRouting.OnRoutingChangedListener) { + access("remove listener") + listeners.remove(listener) + } + fun setPreferredDevice(device: AudioDeviceInfo?): Boolean { + access("prefer"); selectionAttempts++ + if (!acceptPreference) return false + preferred = device + if (autoRoute) actual = device + if (emitOnPreference) listeners.toList().forEach { (listener, handler) -> handler.post { listener.onRoutingChanged(this) } } + return true + } + fun deliver(index: Int) { history[index].onRoutingChanged(this) } +} diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/RouterHostApp.kt b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/RouterHostApp.kt index 38eeed655..8011137c5 100644 --- a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/RouterHostApp.kt +++ b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/RouterHostApp.kt @@ -15,5 +15,6 @@ object R { object string { const val incoming_calls = 101; const val incoming_call_notification = 102; const val radio_call_incoming = 103 const val incoming_call = 104; const val decline = 105; const val hang_up = 106; const val accept = 107 + const val media_audio_fallback = 108; const val media_audio_failed = 109 } } diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/IncomingHostEnvironment.kt b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/IncomingHostEnvironment.kt index 2e608e1db..2507362d4 100644 --- a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/IncomingHostEnvironment.kt +++ b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/IncomingHostEnvironment.kt @@ -14,6 +14,8 @@ object AppLanguage { object CallController { var media = false + var blocked = false + fun blocksMedia() = blocked val endings = mutableListOf>() fun hasMedia() = media fun mediaWarning(incoming: Boolean): Int { check(incoming); return 999 } diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/MediaHostCapture.kt b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/MediaHostCapture.kt new file mode 100644 index 000000000..2fca9cf4a --- /dev/null +++ b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/MediaHostCapture.kt @@ -0,0 +1,38 @@ +package com.utun.chat.data + +import android.media.AudioDeviceInfo + +/** Hardware-only JVM seam: MediaAudioSession, общие подписки и временная шкала компилируются из приложения. */ +internal class AndroidMicrophoneCapture private constructor( + val input: AudioDeviceInfo, val voice: Boolean, val stereo: Boolean, val micSource: Int, val generation: Long, + val accept: (MicrophoneCapture.Frame) -> Boolean, val failed: (Exception) -> Unit, val confirmed: () -> Unit +) : AutoCloseable { + companion object { + val opened = mutableListOf() + var failOpen = false + var failClose = false + var autoConfirm = true + var attempts = 0 + fun reset() { opened.clear(); failOpen = false; failClose = false; autoConfirm = true; attempts = 0 } + fun open(input: AudioDeviceInfo, voice: Boolean, stereo: Boolean, micSource: Int, generation: Long, + accept: (MicrophoneCapture.Frame) -> Boolean, failed: (Exception) -> Unit, + confirmed: () -> Unit): AndroidMicrophoneCapture { + attempts++ + check(!failOpen) { "hardware capture open failed" } + check(opened.none { !it.closed }) { "overlapping hardware readers" } + return AndroidMicrophoneCapture(input, voice, stereo, micSource, generation, accept, failed, confirmed).also { + opened.add(it) + if (autoConfirm) confirmed() + } + } + } + var closed = false + private set + var closeAttempts = 0 + private set + override fun close() { + closeAttempts++ + check(!failClose) { "hardware capture close failed" } + closed = true + } +} diff --git a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/RouterHostEnvironment.kt b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/RouterHostEnvironment.kt index 803c78e04..2aff133a4 100644 --- a/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/RouterHostEnvironment.kt +++ b/tools/chatgui-android/router-tests/src/main/kotlin/com/utun/chat/data/RouterHostEnvironment.kt @@ -62,6 +62,24 @@ object NativeLib { /** Управляемая подготовка конфига: тест удерживает реальный worker, считает перекрытия и затем дожидается его завершения. */ class HostConfigProvider { + var mediaProfile = MediaAudioProfile.AUTO + var failMediaRead = false + var failMediaWrite = false + var mediaLoads = 0 + val mediaSaves = mutableListOf() + var stereo = false + var micSource = 0 + fun getMediaAudioProfile(): MediaAudioProfile { + mediaLoads++ + check(!failMediaRead) { "media storage read failed" } + return mediaProfile + } + fun setMediaAudioProfile(value: MediaAudioProfile) { + check(!failMediaWrite) { "media storage write failed" } + mediaProfile = value; mediaSaves.add(value) + } + fun getRadioCaptureStereo() = stereo + fun getRadioMicSource() = micSource val incomingCallOptions = MutableStateFlow(List(5) { false }) val builds = AtomicInteger() val inBuild = AtomicInteger() diff --git a/tools/chatgui-android/router-tests/src/test/kotlin/com/utun/chat/data/MediaAudioSessionTest.kt b/tools/chatgui-android/router-tests/src/test/kotlin/com/utun/chat/data/MediaAudioSessionTest.kt new file mode 100644 index 000000000..6853d0f8e --- /dev/null +++ b/tools/chatgui-android/router-tests/src/test/kotlin/com/utun/chat/data/MediaAudioSessionTest.kt @@ -0,0 +1,428 @@ +package com.utun.chat.data + +import android.bluetooth.BluetoothAdapter +import android.content.Context +import android.media.AudioDeviceInfo +import android.media.AudioManager +import android.media.AudioTrack +import android.os.Looper +import com.utun.chat.ChatApplication +import com.utun.chat.R +import java.util.concurrent.Callable +import java.util.concurrent.Delayed +import java.util.concurrent.ExecutionException +import java.util.concurrent.FutureTask +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.ScheduledThreadPoolExecutor +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +/** Настоящие session/router/PCM subscriptions; аппаратный reader и AudioTrack управляются host fixtures. */ +class MediaAudioSessionTest { + private lateinit var context: Context + private lateinit var audio: AudioManager + private lateinit var clock: ClockExecutor + private var session: MediaAudioSession? = null + private val subscriptions = mutableListOf() + private val leases = mutableListOf() + private val tracks = mutableListOf() + private val speaker = AudioDeviceInfo(1, 2, true, false, "speaker") + private val mic = AudioDeviceInfo(2, 15, false, true, "microphone") + private val wired = AudioDeviceInfo(3, 22, true, false, "USB output") + private val wiredMic = AudioDeviceInfo(4, 22, false, true, "USB input") + private val owner get() = requireNotNull(session) + + @Before fun prepare() { + assertSame(Looper.getMainLooper(), Looper.myLooper()) + context = Context().also { ChatApplication.instance = it } + audio = AudioManager().also { AudioManager.shared = it; it.devices = arrayOf(speaker, mic) } + BluetoothAdapter.current = null; CallController.blocked = false + AndroidMicrophoneCapture.reset() + clock = ClockExecutor() + LogManager.entries.clear(); LogManager.console = true + } + + @After fun release() { + audio.failures = emptySet(); context.configProvider.failMediaWrite = false; context.configProvider.failMediaRead = false + AndroidMicrophoneCapture.failClose = false; AndroidMicrophoneCapture.failOpen = false + tracks.forEach { it.failures = emptySet() } + subscriptions.forEach { it.close() } + leases.forEach { background { it.close() } } + session?.let { background { it.close() } } + Looper.getMainLooper().dispatchAll() + clock.shutdownNow(); assertTrue(clock.awaitTermination(5, TimeUnit.SECONDS)) + assertTrue(audio.callbacks.isEmpty()) + assertTrue(AndroidMicrophoneCapture.opened.all { it.closed }) + CallController.blocked = false + } + + private fun start() { session = MediaAudioSession(clock); drain() } + private fun drain() { repeat(4) { clock.submit {}.get(5, TimeUnit.SECONDS) } } + private fun subscribe(name: String = "radio"): MicrophoneCapture.Subscription = owner.subscribe(name).also { subscriptions.add(it); drain() } + private fun track(id: Int = tracks.size + 1) = AudioTrack(id).also { tracks.add(it) } + private fun attach(track: AudioTrack): AutoCloseable = background { owner.attachOutput(track) }.also { leases.add(it); drain() } + private fun diagnostic(fragment: String) = assertTrue("Missing diagnostic: $fragment", + LogManager.entries.any { it.message.contains(fragment) && it.level in listOf("ERROR", "WARN") }) + private fun event() { audio.callbacks.single().onAudioDevicesAdded(emptyArray()); drain() } + private fun select(profile: MediaAudioProfile) { owner.select(profile); drain() } + + @Test fun idleMonitoringDoesNotOpenHardwareOrTakeAudioMode() { + start() + assertEquals(1, audio.callbacks.size) + assertTrue(AndroidMicrophoneCapture.opened.isEmpty()) + assertEquals(AudioManager.MODE_NORMAL, audio.mode) + assertTrue(audio.operations.none { it == "clear" || it.startsWith("select=") || it.startsWith("mode=") }) + assertEquals(0, clock.activeTimers) + } + + @Test fun startupFailureIsBoundedAndExplicitRefreshRestartsMonitor() { + audio.failures = setOf("register") + start() + assertEquals(2, audio.callbackHistory.size) + assertTrue(audio.callbacks.isEmpty()) + diagnostic("fallback failed") + audio.failures = emptySet(); owner.refresh(); drain() + assertEquals(1, audio.callbacks.size) + assertEquals(3, audio.callbackHistory.size) + } + + @Test fun storageReadFailureCanRecoverSavedPreference() { + context.configProvider.mediaProfile = MediaAudioProfile.WIRED + context.configProvider.failMediaRead = true + start() + assertEquals(2, context.configProvider.mediaLoads) + context.configProvider.failMediaRead = false + owner.refresh(); drain() + assertEquals(MediaAudioProfile.WIRED, owner.state.value.preferred) + assertEquals(3, context.configProvider.mediaLoads) + } + + @Test fun recoveredStartupUsesFirstKnownDevicesInsteadOfLatchingPhoneFallback() { + audio.devices += arrayOf(wired, wiredMic) + audio.failures = setOf("register") + start() + audio.failures = emptySet(); owner.refresh(); drain() + assertEquals(MediaAudioProfile.WIRED, owner.state.value.active) + } + + @Test fun subscriptionOnControlWorkerStillRequestsCaptureReconciliation() { + start() + val sub = clock.submit { owner.subscribe("radio") }.get(5, TimeUnit.SECONDS) + subscriptions.add(sub); drain() + assertEquals(1, AndroidMicrophoneCapture.opened.size) + } + + @Test fun terminalInputOpenFailureCanRetrySameRouteWithoutOverlappingReaders() { + AndroidMicrophoneCapture.failOpen = true + start(); subscribe() + val attempts = AndroidMicrophoneCapture.attempts + assertTrue(attempts in 1..2) + AndroidMicrophoneCapture.failOpen = false; owner.refresh(); drain() + assertEquals(attempts + 1, AndroidMicrophoneCapture.attempts) + assertEquals(1, AndroidMicrophoneCapture.opened.count { !it.closed }) + assertFalse(owner.state.value.switching) + } + + @Test fun radioAndStreamKeepSubscriptionsAcrossCaptureReplacement() { + start() + val radio = subscribe() + val first = AndroidMicrophoneCapture.opened.last() + val stream = subscribe("stream") + val second = AndroidMicrophoneCapture.opened.last() + assertNotSame(first, second); assertTrue(first.closed) + assertTrue(second.stereo); assertEquals(3, second.micSource) + stream.close(); drain() + assertSame(second, AndroidMicrophoneCapture.opened.last()) + assertTrue(radio.ptt(true)); assertTrue(radio.ptt(false)) + assertFalse(second.closed) + radio.close(); drain() + assertTrue(second.closed) + assertEquals(AudioManager.MODE_NORMAL, audio.mode) + } + + @Test fun oldCaptureCallbacksAndFramesCannotAffectReplacement() { + start(); subscribe() + val old = AndroidMicrophoneCapture.opened.last() + select(MediaAudioProfile.PHONE) + val current = AndroidMicrophoneCapture.opened.last() + assertNotSame(old, current) + val count = AndroidMicrophoneCapture.attempts + old.failed(IllegalStateException("stale hardware failure")); old.confirmed() + assertFalse(old.accept(MicrophoneCapture.Frame(ShortArray(1920), System.nanoTime(), 0, generation = old.generation))) + drain() + assertEquals(count, AndroidMicrophoneCapture.attempts) + assertFalse(current.closed) + assertTrue(LogManager.entries.none { it.message.contains("stale hardware failure") }) + } + + @Test fun outputLeaseIsIdempotentAcrossReattachOfSameTrack() { + start() + val output = track() + val old = attach(output) + background { old.close() } + val current = attach(output) + background { old.close() } + assertEquals(1, output.listeners.size) + output.deliver(0); drain() + assertEquals(1, output.listeners.size) + background { current.close() } + assertTrue(output.listeners.isEmpty()) + } + + @Test fun lateRoutingCallbackDoesNotReadReleasedTrack() { + start() + val output = track() + val lease = attach(output) + background { lease.close() } + output.released = true + output.deliver(0); drain() + assertEquals(0, output.accessAfterRelease) + } + + @Test fun duplicateTrackRegistrationDoesNotRemoveOriginalListener() { + start() + val output = track() + attach(output) + assertThrows(IllegalStateException::class.java) { background { owner.attachOutput(output) } } + assertEquals(1, output.listeners.size) + } + + @Test fun partialRegistrationAndListenerCleanupFailureKeepOriginalErrorAndReleaseMode() { + start() + val output = track().apply { failures = setOf("add listener after", "remove listener") } + val error = assertThrows(IllegalStateException::class.java) { background { owner.attachOutput(output) } } + assertTrue(error.message!!.contains("add listener after")) + diagnostic("output listener cleanup failed"); diagnostic("output registration failed") + output.failures = emptySet() + output.history.forEach { output.removeOnRoutingChangedListener(it) } + background { owner.awaitIdle() } + } + + @Test fun detachFailureDoesNotSkipHardwareReleaseOrAffectOtherOutput() { + start(); val one = track(); val two = track() + val first = attach(one); attach(two) + one.failures = setOf("remove listener") + background { first.close() } + assertEquals(1, two.listeners.size) + one.failures = emptySet(); one.history.forEach { one.removeOnRoutingChangedListener(it) } + diagnostic("output listener removal failed") + } + + @Test fun preferenceWriteFailureDoesNotCommitUnsavedSelection() { + start() + select(MediaAudioProfile.PHONE) + assertEquals(listOf(MediaAudioProfile.PHONE), context.configProvider.mediaSaves) + context.configProvider.failMediaWrite = true + select(MediaAudioProfile.WIRED) + assertEquals(MediaAudioProfile.PHONE, owner.state.value.preferred) + assertEquals(MediaAudioProfile.PHONE, context.configProvider.mediaProfile) + context.configProvider.failMediaWrite = false + select(MediaAudioProfile.WIRED) + assertEquals(listOf(MediaAudioProfile.PHONE, MediaAudioProfile.WIRED), context.configProvider.mediaSaves) + diagnostic("media storage write failed") + } + + @Test fun selectionIsPersistedOnlyAfterPhysicalOutputConfirmation() { + start() + val output = track().apply { autoRoute = false } + attach(output) + select(MediaAudioProfile.PHONE) + assertTrue(owner.state.value.switching) + assertTrue(context.configProvider.mediaSaves.isEmpty()) + output.actual = speaker; output.deliver(0); drain() + assertFalse(owner.state.value.switching) + assertEquals(listOf(MediaAudioProfile.PHONE), context.configProvider.mediaSaves) + assertEquals(0, clock.activeTimers) + } + + @Test fun confirmationTimeoutIsUniqueCancelledOnSuccessAndOldTimerCannotAffectNewLease() { + start() + val output = track().apply { autoRoute = false } + val first = attach(output) + assertEquals(1, clock.activeTimers) + val old = clock.timers.last() + background { first.close() }; drain() + attach(output) + val now = clock.timers.last() + assertNotSame(old, now) + clock.replay(old); drain() + assertTrue(owner.state.value.switching) + output.actual = speaker; output.deliver(1); drain() + assertFalse(owner.state.value.switching) + assertEquals(0, clock.activeTimers) + } + + @Test fun outputTimeoutRecoversWithoutLosingLeaseAndNextRefreshCanConfirm() { + start() + val output = track().apply { autoRoute = false } + attach(output) + assertEquals(6L, clock.timers.last().seconds) + clock.fire(); drain() + diagnostic("Audio route confirmation timeout") + assertEquals(1, output.listeners.size) + clock.fire(); drain() // Повторный отказ уже PHONE fallback инвалидирует и закешированный ключ. + output.autoRoute = true + owner.refresh(); drain() + assertFalse(owner.state.value.switching) + assertEquals(0, clock.activeTimers) + } + + @Test fun bluetoothOutputUsesLongConfirmationDeadline() { + val bt = AudioDeviceInfo(5, AudioDeviceInfo.TYPE_BLUETOOTH_A2DP, true, false, "BT output") + audio.devices += bt + start() + attach(track().apply { autoRoute = false }) + assertEquals(30L, clock.timers.last().seconds) + assertEquals(MediaAudioProfile.BLUETOOTH, owner.state.value.active) + } + + @Test fun exceptionFromCaptureConfirmationIsLoggedAndRecovered() { + AndroidMicrophoneCapture.autoConfirm = false + start(); val output = track(); attach(output); subscribe() + val capture = AndroidMicrophoneCapture.opened.last() + output.failures = setOf("routed") + capture.confirmed(); drain() + diagnostic("track failed: routed") + output.failures = emptySet(); owner.refresh(); drain() + AndroidMicrophoneCapture.opened.last().confirmed(); drain() + assertFalse(owner.state.value.switching) + } + + @Test fun exceptionInsideTimerIsLoggedRatherThanLostInFuture() { + start(); val output = track().apply { autoRoute = false }; attach(output) + output.failures = setOf("routed") + clock.fire(); drain() + diagnostic("track failed: routed") + } + + @Test fun hardwareCloseFailurePreventsOverlappingReopenAndCanRecover() { + start(); subscribe() + val first = AndroidMicrophoneCapture.opened.last() + AndroidMicrophoneCapture.failClose = true + select(MediaAudioProfile.PHONE) + assertEquals(1, AndroidMicrophoneCapture.opened.size) + assertFalse(first.closed) + diagnostic("capture release failed") + AndroidMicrophoneCapture.failClose = false; owner.refresh(); drain() + assertTrue(first.closed) + assertEquals(1, AndroidMicrophoneCapture.opened.count { !it.closed }) + } + + @Test fun failedModeAcquisitionAfterSideEffectStillReleasesOwnedMode() { + start() + audio.failures = setOf("mode after=3") + subscribe() + assertEquals(AudioManager.MODE_NORMAL, audio.mode) + assertTrue(AndroidMicrophoneCapture.opened.isEmpty()) + diagnostic("mode after=3") + audio.failures = emptySet(); owner.refresh(); drain() + assertEquals(1, AndroidMicrophoneCapture.opened.count { !it.closed }) + } + + @Test fun idleHandoffDoesNotRequireDeviceQueryAndDoesNotResetTelecomModeLater() { + start(); val subscription = subscribe() + subscription.close(); drain() + audio.failures = setOf("devices") + background { owner.awaitIdle() } + assertEquals(AudioManager.MODE_NORMAL, audio.mode) + audio.mode = AudioManager.MODE_IN_COMMUNICATION // Telecom теперь владеет режимом. + audio.failures = emptySet(); owner.refresh(); drain() + assertEquals(AudioManager.MODE_IN_COMMUNICATION, audio.mode) + } + + @Test fun idleBarrierRejectsLiveInputOrOutput() { + start(); val sub = subscribe() + assertThrows(IllegalStateException::class.java) { background { owner.awaitIdle() } } + sub.close(); drain() + val lease = attach(track()) + assertThrows(IllegalStateException::class.java) { background { owner.awaitIdle() } } + background { lease.close() }; background { owner.awaitIdle() } + } + + @Test fun closeRejectsLiveLeaseAndClosedSessionIgnoresLateEvents() { + start(); val output = track(); val lease = attach(output) + assertThrows(IllegalStateException::class.java) { background { owner.close() } } + background { lease.close() }; background { owner.close() } + output.released = true; output.deliver(0) + owner.refresh(); owner.select(MediaAudioProfile.WIRED) + assertThrows(IllegalStateException::class.java) { owner.subscribe("radio") } + assertEquals(0, output.accessAfterRelease) + } + + @Test fun blockingCallsRejectMainAndControlWorkerBeforeSubmitting() { + start() + assertThrows(IllegalStateException::class.java) { owner.attachOutput(track()) } + assertThrows(IllegalStateException::class.java) { owner.awaitIdle() } + assertThrows(IllegalStateException::class.java) { owner.close() } + clock.submit { assertThrows(IllegalStateException::class.java) { owner.awaitIdle() } }.get(5, TimeUnit.SECONDS) + assertTrue(tracks.all { it.listeners.isEmpty() }) + } + + @Test fun callReservationBlocksSelectionCaptureAndOutput() { + start(); CallController.blocked = true + select(MediaAudioProfile.WIRED) + assertTrue(context.configProvider.mediaSaves.isEmpty()) + assertThrows(IllegalStateException::class.java) { owner.subscribe("radio") } + assertThrows(IllegalStateException::class.java) { background { owner.attachOutput(track()) } } + } + + @Test fun ownRoutingEventsCannotCreatePersistentFailureLoop() { + start(); val output = track().apply { emitOnPreference = true }; attach(output) + AndroidMicrophoneCapture.failOpen = true + subscribe() + repeat(4) { Looper.getMainLooper().dispatchAll(); drain() } + val attempts = AndroidMicrophoneCapture.attempts + repeat(4) { Looper.getMainLooper().dispatchAll(); drain() } + assertEquals(attempts, AndroidMicrophoneCapture.attempts) + assertTrue(attempts <= 3) + } + + @Test fun usbMicOnlyKeepsSpeakerPlaybackAndSelectsMicSource() { + audio.devices += wiredMic + start(); subscribe() + val capture = AndroidMicrophoneCapture.opened.last() + assertEquals(wiredMic, capture.input) + assertEquals(1, capture.micSource) + assertEquals("speaker", owner.state.value.outputName) + } + + @Test fun unplugReopensOneReaderWhileKeepingSubscriptionAlive() { + audio.devices += arrayOf(wired, wiredMic) + start(); val sub = subscribe() + val first = AndroidMicrophoneCapture.opened.last() + audio.devices = arrayOf(speaker, mic); event() + assertTrue(first.closed) + assertEquals(mic, AndroidMicrophoneCapture.opened.last().input) + assertTrue(sub.ptt(true)) + assertEquals(1, AndroidMicrophoneCapture.opened.count { !it.closed }) + } + + private fun background(action: () -> T): T { + val future = FutureTask(Callable { action() }) + Thread(future, "media-test-consumer").apply { isDaemon = true; start() } + try { return future.get(5, TimeUnit.SECONDS) } catch (e: ExecutionException) { + var cause: Throwable = e.cause ?: e + while (cause is ExecutionException && cause.cause != null) cause = requireNotNull(cause.cause) + throw cause + } + } + + /** Реальный single worker; только положительные задержки исполняются вручную, без sleep и ожидания 30 секунд. */ + private class ClockExecutor : ScheduledThreadPoolExecutor(1, { task -> Thread(task, "media-test-control").apply { isDaemon = true } }) { + class Timer(val action: Runnable, val seconds: Long) : FutureTask(action, Unit), ScheduledFuture { + override fun getDelay(unit: TimeUnit) = unit.convert(seconds, TimeUnit.SECONDS) + override fun compareTo(other: Delayed) = getDelay(TimeUnit.NANOSECONDS).compareTo(other.getDelay(TimeUnit.NANOSECONDS)) + } + val timers = java.util.Collections.synchronizedList(mutableListOf()) + val activeTimers: Int get() = synchronized(timers) { timers.count { !it.isCancelled && !it.isDone } } + override fun schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture<*> { + if (delay == 0L) return super.schedule(command, delay, unit) + return Timer(command, unit.toSeconds(delay)).also { timers.add(it) } + } + fun fire() { synchronized(timers) { timers.filter { !it.isCancelled && !it.isDone } }.forEach { execute(it) } } + fun replay(timer: Timer) { execute(timer.action) } + } +}