From 2d22f845e9a7d4e78e6a8db7357aa274b6f075fb Mon Sep 17 00:00:00 2001 From: evgeny Date: Thu, 29 Oct 2026 09:50:27 +0100 Subject: [PATCH] Test camera writer completion, failed close, binding cleanup and cache transfer --- .../utun/chat/data/CameraCaptureResources.kt | 13 ++- .../chat/data/CameraCaptureResourcesTest.kt | 88 +++++++++++++++++++ 2 files changed, 97 insertions(+), 4 deletions(-) create mode 100644 tools/chatgui-android/video-tests/src/test/kotlin/com/utun/chat/data/CameraCaptureResourcesTest.kt diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureResources.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureResources.kt index e0525fa2a..857deef87 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureResources.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureResources.kt @@ -20,7 +20,9 @@ internal class CameraCaptureResources : AutoCloseable { } private data class Binding(val provider: ProcessCameraProvider, val cases: Array) private val files = mutableMapOf() + private val completedWriters = mutableSetOf() private var binding: Binding? = null + private var bindingRetiring = false private var closed = false private val main = Handler(Looper.getMainLooper()) private var scheduled = false @@ -34,6 +36,7 @@ internal class CameraCaptureResources : AutoCloseable { } fun recording(file: File, recording: AutoCloseable) { + if (file in completedWriters) return val capture = checkNotNull(files[file]) { "Recording has no file owner" } if (!capture.pending) return // Синхронный Finalize уже подтвердил закрытый Recording. capture.recording = recording @@ -43,6 +46,7 @@ internal class CameraCaptureResources : AutoCloseable { /** Подтверждение writer; false означает discard/close и запрещает показывать либо отправлять результат. */ fun completed(file: File): Boolean { val capture = files[file] ?: return false + completedWriters.add(file) capture.pending = false; capture.recording = null val usable = !closed && !capture.discarded LogManager.addLog("INFO", "Capture", "Writer finished path=$file usable=$usable") @@ -73,8 +77,9 @@ internal class CameraCaptureResources : AutoCloseable { fun unbind(): Boolean { val current = binding ?: return true + bindingRetiring = true try { - current.provider.unbind(*current.cases); binding = null + current.provider.unbind(*current.cases); binding = null; bindingRetiring = false LogManager.addLog("INFO", "Capture", "Own camera use cases unbound count=${current.cases.size}") } catch (e: Exception) { LogManager.addLog("ERROR", "Capture", "Camera unbind failed; owner retained: $e") @@ -90,7 +95,7 @@ internal class CameraCaptureResources : AutoCloseable { } private fun cleanup() { - if (closed) unbind() + if (closed || bindingRetiring) unbind() for (capture in files.values.toList()) { if (!capture.discarded) continue capture.recording?.let { record -> @@ -107,14 +112,14 @@ internal class CameraCaptureResources : AutoCloseable { } private fun schedule() { - val pending = (closed && binding != null) || files.values.any { it.discarded } + val pending = (bindingRetiring && binding != null) || files.values.any { it.discarded } if (!pending) { main.removeCallbacks(retry); scheduled = false; delayMs = 250; retained.remove(this) return } retained.add(this) // Ожидание callback не опрашиваем: owner удерживается до подтверждения writer. - val retryable = binding != null || files.values.any { it.discarded && (!it.pending || it.recording != null) } + val retryable = bindingRetiring || files.values.any { it.discarded && (!it.pending || it.recording != null) } if (!scheduled && retryable) { scheduled = main.postDelayed(retry, delayMs) if (scheduled) delayMs = (delayMs * 2).coerceAtMost(30_000) diff --git a/tools/chatgui-android/video-tests/src/test/kotlin/com/utun/chat/data/CameraCaptureResourcesTest.kt b/tools/chatgui-android/video-tests/src/test/kotlin/com/utun/chat/data/CameraCaptureResourcesTest.kt new file mode 100644 index 000000000..385646182 --- /dev/null +++ b/tools/chatgui-android/video-tests/src/test/kotlin/com/utun/chat/data/CameraCaptureResourcesTest.kt @@ -0,0 +1,88 @@ +package com.utun.chat.data + +import android.os.Handler +import android.os.Looper +import androidx.camera.core.Preview +import androidx.camera.lifecycle.ProcessCameraProvider +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import java.io.File +import java.nio.file.Files + +class CameraCaptureResourcesTest { + private val root = Files.createTempDirectory("utun-camera-owner").toFile() + private val owner = CameraCaptureResources() + @Before fun prepare() { Handler.rejectDelayed = false } + @After fun release() { Handler.rejectDelayed = false; owner.close(); root.deleteRecursively(); Looper.getMainLooper().advanceBy(30_000) } + private fun file(name: String = "capture.mp4") = File(root, name).also { it.writeText("camera data") } + private class Recording : AutoCloseable { + var fail = false; var closes = 0 + override fun close() { closes++; check(!fail) { "Recording close rejected" } } + } + + @Test fun discardedVideoWaitsForFinalizeAfterSuccessfulClose() { + val file = file(); val record = Recording() + owner.own(file); owner.recording(file, record); owner.discard(file) + assertEquals(1, record.closes); assertTrue(file.exists()) + owner.close(); assertTrue(file.exists()); assertFalse(owner.completed(file)); assertFalse(file.exists()) + } + @Test fun discardedPhotoIsNotDeletedUnderTheImageWriter() { + val file = file("photo.jpg") + owner.own(file); owner.close(); assertTrue(file.exists()) + file.appendText("late writer output") + assertFalse(owner.completed(file)); assertFalse(file.exists()) + } + @Test fun closeFailureKeepsRecordingAndRetriesIndependentlyOfFileCompletion() { + val file = file(); val record = Recording().also { it.fail = true } + owner.own(file); owner.recording(file, record); owner.close() + assertTrue(file.exists()); assertEquals(1, record.closes) + record.fail = false; Looper.getMainLooper().advanceBy(250) + assertEquals(2, record.closes); assertTrue(file.exists()) + owner.completed(file); assertFalse(file.exists()) + } + @Test fun lateRecordingAdoptionAfterCloseStillClosesAndWaitsForFinalize() { + val file = file(); val record = Recording() + owner.own(file); owner.close(); owner.recording(file, record) + assertEquals(1, record.closes); assertTrue(file.exists()) + owner.completed(file); assertFalse(file.exists()) + } + @Test fun synchronousFinalizeBeforeHandleAdoptionDoesNotResurrectTheWriter() { + val file = file(); val record = Recording() + owner.own(file); owner.close(); owner.completed(file); owner.recording(file, record) + assertFalse(file.exists()); assertEquals(0, record.closes) + } + @Test fun cacheTransferredToSenderSurvivesUiCloseAndCannotBeDiscardedTwice() { + val file = file(); owner.own(file); assertTrue(owner.completed(file)); owner.transferred(file) + owner.close(); owner.discard(file); assertTrue(file.exists()) + } + @Test fun unbindFailureRetainsOnlyOwnUseCasesUntilRetryAcknowledgesCleanup() { + val provider = ProcessCameraProvider(); val own = Preview.Builder().build(); val other = Preview.Builder().build() + provider.bound.addAll(listOf(own, other)); owner.binding(provider, own) + provider.failures = setOf("unbind"); owner.close() + assertTrue(own in provider.bound); assertTrue(other in provider.bound) + provider.failures = emptySet(); Looper.getMainLooper().advanceBy(250) + assertFalse(own in provider.bound); assertTrue(other in provider.bound) + } + @Test fun failedRebindCleanupAlsoRetriesBeforeTheUiOwnerIsClosed() { + val provider = ProcessCameraProvider(); val useCase = Preview.Builder().build() + provider.bound.add(useCase); owner.binding(provider, useCase); provider.failures = setOf("unbind") + assertFalse(owner.unbind()); provider.failures = emptySet(); Looper.getMainLooper().advanceBy(250) + assertFalse(useCase in provider.bound); assertTrue(owner.unbind()) + } + @Test fun rejectedRetryDoesNotLoseTheRecordingOrPreventExplicitClose() { + val file = file(); val record = Recording().also { it.fail = true } + owner.own(file); owner.recording(file, record); Handler.rejectDelayed = true; owner.close() + record.fail = false; owner.close(); assertEquals(2, record.closes); assertTrue(file.exists()) + owner.completed(file); assertFalse(file.exists()) + } + @Test fun failedDeletionDoesNotPreventAnotherCacheFromBeingReleased() { + val directory = File(root, "cannot-delete-yet").also { it.mkdir() } + val child = File(directory, "busy").also { it.writeText("data") } + val second = file("second.jpg") + owner.own(directory); owner.completed(directory); owner.own(second); owner.completed(second); owner.close() + assertTrue(directory.exists()); assertFalse(second.exists()) + child.delete(); Looper.getMainLooper().advanceBy(250); assertFalse(directory.exists()) + } +}