diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallVideoPlayer.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallVideoPlayer.kt index 3f6769d01..0eaa8e8e3 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallVideoPlayer.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CallVideoPlayer.kt @@ -1,18 +1,36 @@ package com.utun.chat.data import android.media.MediaCodec +import android.os.Handler +import android.os.Looper import android.view.Surface import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import java.util.concurrent.ConcurrentLinkedQueue import java.util.ArrayDeque +import java.util.concurrent.ConcurrentHashMap -/** Один RX worker, общий абсолютный таймер показа. Новое поколение ждёт drain старого. */ +/** Один RX worker, общий абсолютный таймер показа. Новое поколение ждёт drain старого. + * surface передаёт player владение callback освобождения до его успешного возврата. + * stop ждёт worker до 250 мс и подтверждает decoder/playout/Surface cleanup; отказ допускает повтор. + * Освобождение Surface ждёт decoder. После join cleanup может выполнять caller/main retry; + * callback release должен допускать повтор после исключения. Поздние Surface также получают cleanup. + * Неподтверждённые ресурсы удерживаются process-ссылкой с повтором через 250 мс..30 с. */ internal class CallVideoPlayer(private val id: Long, private val failure: (String) -> Unit) { + companion object { private val retained = ConcurrentHashMap.newKeySet() } private val createdAt = System.nanoTime() @Volatile private var running = true - private data class Output(val surface: Surface?, val release: () -> Unit, val detach: Surface? = null) + private class Output(val surface: Surface?, val release: () -> Unit, val detach: Surface? = null) private val outputs = ConcurrentLinkedQueue() + private val ownedOutputs = ConcurrentLinkedQueue() + private var output: Output? = null // RX worker; после join — под монитором player. + private var decoder: MediaCodec? = null + private var playout = 0L + private val cleanupHandler = Handler(Looper.getMainLooper()) + private var cleanupDelay = 250L + private val cleanupRetry = Runnable { + try { stop() } catch (e: Exception) { LogManager.addLog("WARN", "call", "video RX cleanup retry pending call=$id: $e") } + } private data class Presentation(val surface: Surface, val pts: Long, val at: Long = 0) private val presentations = ConcurrentLinkedQueue() @Volatile private var awaiting: Presentation? = null @@ -27,21 +45,94 @@ internal class CallVideoPlayer(private val id: Long, private val failure: (Strin @Volatile private var verified = emptyMap() private val worker = Thread(::loop, "call-video-rx").apply { start() } @Synchronized fun surface(surface: Surface?, release: () -> Unit = {}) { - if (running) outputs.add(Output(surface, release)) else release() + val owner = Output(surface, release) + ownedOutputs.add(owner) + if (running) outputs.add(owner) else { + LogManager.addLog("WARN", "call", "video surface received after RX stop call=$id; retained for cleanup") + scheduleCleanup() + } } @Synchronized fun detach(surface: Surface) { if (running) outputs.add(Output(null, {}, surface)) } fun decoders(value: Map) { verified = value } - fun stop() { synchronized(this) { running = false }; worker.join() } + /** Caller вне RX: ошибка join/release сохраняет владельцев и блокирует native port close. */ + fun stop() { + check(Thread.currentThread() !== worker) { + LogManager.addLog("ERROR", "call", "video RX stop from its own worker call=$id") + "Video RX cannot join itself" + } + synchronized(this) { running = false } + try { worker.join(250) } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + LogManager.addLog("ERROR", "call", "video RX join interrupted call=$id: $e") + synchronized(this) { scheduleCleanup() } + throw e + } + synchronized(this) { + if (!worker.isAlive) releaseResources() + scheduleCleanup() + check(!worker.isAlive && decoder == null && playout == 0L && ownedOutputs.isEmpty()) { + val detail = "video RX cleanup pending call=$id worker=${worker.state} decoder=${decoder != null} " + + "playout=$playout surfaces=${ownedOutputs.size}" + LogManager.addLog("ERROR", "call", detail) + detail + } + } + } + + private fun releaseDecoder(): Boolean { + val owned = decoder ?: return true + try { owned.stop() } catch (e: Exception) { LogManager.addLog("WARN", "call", "video decoder stop call=$id: $e") } + return try { owned.release(); decoder = null; true } catch (e: Exception) { + LogManager.addLog("ERROR", "call", "video decoder release failed call=$id; retained for retry: $e") + false + } + } + + private fun releaseOutput(owner: Output): Boolean = try { + owner.release(); ownedOutputs.remove(owner); true + } catch (e: Exception) { + LogManager.addLog("ERROR", "call", "video surface release failed call=$id surface=${System.identityHashCode(owner.surface)}; retained: $e") + false + } + + /** Только finally RX либо после join: независимые владельцы очищаются даже при ошибке соседнего. */ + private fun releaseResources() { + releaseDecoder() + for (owner in ownedOutputs.toList()) { + if (decoder != null && owner === output) continue + if (releaseOutput(owner) && owner === output) output = null + } + if (decoder == null && output !in ownedOutputs) output = null + if (playout != 0L) try { + CallVideoNative.playoutDestroy(playout); playout = 0 + } catch (e: Exception) { LogManager.addLog("ERROR", "call", "video playout destroy failed call=$id; retained: $e") } + } + + private fun scheduleCleanup() { + cleanupHandler.removeCallbacks(cleanupRetry) + if (!worker.isAlive && decoder == null && playout == 0L && ownedOutputs.isEmpty()) { + if (retained.remove(this)) LogManager.addLog("INFO", "call", "video RX cleanup confirmed call=$id") + cleanupDelay = 250 + return + } + retained.add(this) + val delay = cleanupDelay; cleanupDelay = (cleanupDelay * 2).coerceAtMost(30_000) + if (!cleanupHandler.postDelayed(cleanupRetry, delay)) + LogManager.addLog("ERROR", "call", "video RX cleanup retry rejected call=$id; owner retained delayMs=$delay") + } + + private fun reportFailure(detail: String) { + LogManager.addLog("ERROR", "call", "video receive call=$id: $detail") + try { failure(detail) } catch (e: Exception) { LogManager.addLog("ERROR", "call", "video RX failure callback failed call=$id: $e") } + } private fun loop() { data class Timing(val pts: Long, val received: Long, val interval: Int) data class Picture(val index: Int, val timing: Timing) - val playout = CallVideoNative.playoutCreate(id) - if (playout == 0L) { failure("Video playout allocation failed"); return } - var decoder: MediaCodec? = null; var surface: Surface? = null; var format: CallVideoFormat? = null - var output: Output? = null; var lastRendered = 0L + var surface: Surface? = null; var format: CallVideoFormat? = null + var lastRendered = 0L var awaitingPts = -1L var pending: ByteArray? = null; val meta = LongArray(13) val pictures = ArrayDeque(); val inputs = ArrayDeque() @@ -53,20 +144,23 @@ internal class CallVideoPlayer(private val id: Long, private val failure: (Strin var firstInput = true; var firstDecoded = true; var firstPresented = true val clock = LongArray(8); val info = MediaCodec.BufferInfo() fun close() { - try { decoder?.stop() } catch (e: Exception) { LogManager.addLog("WARN", "call", "video decoder stop: ${e.message}") } - try { decoder?.release() } catch (e: Exception) { LogManager.addLog("WARN", "call", "video decoder release: ${e.message}") } - decoder = null; format = null; pictures.clear(); inputs.clear() + check(releaseDecoder()) { running = false; "Video decoder cleanup pending" } + format = null; pictures.clear(); inputs.clear() awaitingPts = -1; awaiting = null; presentations.clear() draining = false; endSeen = false; lastOutput = -1 } try { + playout = CallVideoNative.playoutCreate(id) + check(playout != 0L) { "Video playout allocation failed" } while (running) { var worked = false; var wakeUs = System.nanoTime() / 1000 + 5000 try { while (true) { - val next = outputs.poll() ?: break - if (next.detach != null && output?.surface !== next.detach) continue - close(); output?.release?.invoke(); output = next; surface = next.surface + val next = outputs.peek() ?: break + if (next.detach != null && output?.surface !== next.detach) { outputs.poll(); continue } + close() + output?.let { check(releaseOutput(it)) { running = false; "Video surface cleanup pending" } } + output = next; surface = next.surface; outputs.poll() CallVideoNative.playoutReset(playout) pending = null; displayed.value = null; CallVideoNative.requestKey(id) LogManager.addLog("INFO", "call", "video output attached=${surface != null} call=$id elapsedMs=${(System.nanoTime() - createdAt) / 1_000_000}") @@ -203,18 +297,24 @@ internal class CallVideoPlayer(private val id: Long, private val failure: (Strin acknowledged = 0; ackMaxUs = 0 } } catch (e: Exception) { - LogManager.addLog("ERROR", "call", "video receive call=$id: ${e.message}") + LogManager.addLog("ERROR", "call", "video receive call=$id: $e") val generation = if (pending != null) meta[0] else format?.generation ?: 0 if (generation != 0L) { CallVideoNative.decoded(id, generation, false); rejectedGeneration = generation } close(); CallVideoNative.playoutReset(playout) - pending = null; displayed.value = null; failure(e.message ?: "Video decoder failed") + pending = null; displayed.value = null; reportFailure(e.message ?: "Video decoder failed") } val waitUs = wakeUs - System.nanoTime() / 1000 if (!worked && waitUs > 0) Thread.sleep(waitUs / 1000, (waitUs % 1000 * 1000).toInt()) } + } catch (e: Exception) { + reportFailure("Video RX stopped: $e") } finally { - close(); CallVideoNative.playoutDestroy(playout); displayed.value = null; output?.release?.invoke() - while (true) { val next = outputs.poll() ?: break; next.release() } + synchronized(this) { + running = false; displayed.value = null; awaiting = null; presentations.clear(); outputs.clear() + releaseResources() + scheduleCleanup() + LogManager.addLog("INFO", "call", "video RX worker exited call=$id decoder=${decoder != null} playout=$playout surfaces=${ownedOutputs.size}") + } } } }