Recover camera session failures once with low-resolution native YUV

This commit is contained in:
zenord
2026-10-13 17:50:57 +08:00
parent ddd75fc571
commit e5a7e87f25
32 changed files with 519 additions and 73 deletions
+2
View File
@@ -0,0 +1,2 @@
package com.google.mediapipe.tasks.core
class BaseOptions {companion object {fun builder()=Builder()};class Builder {fun setModelAssetPath(s: String)=this;fun build()=BaseOptions()}}
+37
View File
@@ -0,0 +1,37 @@
package androidx.camera.core
import androidx.lifecycle.LiveData
import android.util.Size
import java.util.concurrent.Executor
class CameraSelector {companion object {val DEFAULT_FRONT_CAMERA=CameraSelector()}}
class CameraState(val error: StateError?=null) {
class StateError(val code: Int)
companion object {const val ERROR_STREAM_CONFIG=4;const val ERROR_CAMERA_IN_USE=2;const val ERROR_MAX_CAMERAS_IN_USE=1;const val ERROR_CAMERA_DISABLED=5;const val ERROR_CAMERA_FATAL_ERROR=6}
}
class Camera(val cameraInfo: CameraInfo=CameraInfo())
class CameraInfo {val cameraState=LiveData(CameraState())}
class ImageAnalysis(val size: Size,val format: Int) {
var callback: ((ImageProxy)->Unit)?=null;var executor: Executor?=null
fun setAnalyzer(e: Executor,c: (ImageProxy)->Unit) {executor=e;callback=c}
fun clearAnalyzer() {callback=null}
fun frame(i: ImageProxy) {val c=callback;executor!!.execute {c!!(i)}}
class Builder {
var size=Size(640,480);var format=2
fun setTargetResolution(s: Size)=apply {size=s}
fun setTargetRotation(r: Int)=this
fun setBackpressureStrategy(s: Int)=this
fun setOutputImageFormat(f: Int)=apply {format=f}
fun setResolutionSelector(r: androidx.camera.core.resolutionselector.ResolutionSelector)=apply {size=r.strategy.size}
fun build()=ImageAnalysis(size,format)
}
companion object {const val STRATEGY_KEEP_ONLY_LATEST=0;const val OUTPUT_IMAGE_FORMAT_RGBA_8888=2;const val OUTPUT_IMAGE_FORMAT_YUV_420_888=1}
}
class ImageProxy(val format: Int=35,val width: Int=2,val height: Int=2) {
class Plane(val buffer: java.nio.ByteBuffer,val rowStride: Int,val pixelStride: Int)
val planes=if(format==35) arrayOf(Plane(java.nio.ByteBuffer.wrap(ByteArray(4) {100}),2,1),
Plane(java.nio.ByteBuffer.wrap(byteArrayOf(128.toByte())),1,1),Plane(java.nio.ByteBuffer.wrap(byteArrayOf(128.toByte())),1,1))
else arrayOf(Plane(java.nio.ByteBuffer.wrap(ByteArray(16) {100}),8,4))
val cropRect=android.graphics.Rect(0,0,2,2)
class ImageInfo {val rotationDegrees=0};val imageInfo=ImageInfo()
@Volatile var closed=false
fun close() {closed=true}
}
+67
View File
@@ -0,0 +1,67 @@
import com.gorios.lanvoice.expression.*
import android.os.CameraClock
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
fun main() {
var cases=0
fun rig(): Triple<ExpressionController,MutableList<ExpressionUiState>,MutableList<Boolean?>> {
CameraClock.reset();ProcessCameraProvider.instance=ProcessCameraProvider()
val states=mutableListOf<ExpressionUiState>();val presence=mutableListOf<Boolean?>()
val c=ExpressionController(android.content.Context(),object: androidx.lifecycle.LifecycleOwner {},states::add,
onPresence={value,_->presence+=value})
c.start();CameraClock.await {ProcessCameraProvider.instance.bindings.size==1}
check(states.last().status==ExpressionStatus.STARTING);cases++
return Triple(c,states,presence)
}
// Exact failure branch: native stream configuration error before a single frame.
val (c,states,presence)=rig();val provider=ProcessCameraProvider.instance
val old=provider.bindings.single();val oldAnalyzer=old.callback!!;val oldObserver=provider.camera.cameraInfo.cameraState.observers.single()
provider.camera.cameraInfo.cameraState.emit(CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)))
CameraClock.advance();check(provider.bindings.size==1 && c.diagnosticsSnapshot().recoveries==1);cases++
CameraClock.advance(249);check(provider.bindings.size==1);cases++
CameraClock.advance(1);val compat=provider.bindings.last()
check(provider.bindings.size==2 && compat.size.width==320 && compat.size.height==240 && compat.format==ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);cases++
check(provider.unbound==listOf(old) && c.diagnosticsSnapshot().stage==CameraStage.WAITING_FRAME);cases++
// LiveData's retained error from the old session must not immediately kill the new one.
check(states.last().status==ExpressionStatus.STARTING);cases++
oldObserver.onChanged(CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)))
val late=ImageProxy();oldAnalyzer(late);check(late.closed && c.diagnosticsSnapshot().received==0);cases++
val frame=ImageProxy();compat.frame(frame);CameraClock.await {frame.closed && c.diagnosticsSnapshot().processed==1}
check(states.last().status==ExpressionStatus.ACTIVE && presence.last()==false && c.diagnosticsSnapshot().profile==CameraProfile.YUV_320);cases++
c.stop();CameraClock.advance();val count=presence.size
oldObserver.onChanged(CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)));CameraClock.advance(6000)
check(provider.bindings.size==2 && presence.size==count && provider.camera.cameraInfo.cameraState.observers.isEmpty());cases++
// At most one retry, no repeating failed binds every five seconds.
val (failed,failedStates,_)=rig();val p=ProcessCameraProvider.instance
CameraClock.advance(5000);CameraClock.advance(250);check(p.bindings.size==2);cases++
p.camera.cameraInfo.cameraState.emit(CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)))
CameraClock.advance();check(failedStates.last().status==ExpressionStatus.UNAVAILABLE && failed.diagnosticsSnapshot().failure==CameraFailure.STREAM_CONFIG);cases++
CameraClock.advance(30000);check(p.bindings.size==2 && failed.diagnosticsSnapshot().recoveries==1);cases++
// Background during settle invalidates the scheduled fallback and old callbacks.
val (stopped,_,_)=rig();val p2=ProcessCameraProvider.instance
CameraClock.advance(5000);stopped.stop();CameraClock.advance(1000)
check(p2.bindings.size==1 && stopped.diagnosticsSnapshot().stage==CameraStage.OFF);cases++
// In-use is recorded distinctly; it is not mislabeled as a detection/model failure.
val (occupied,_,_)=rig();val p3=ProcessCameraProvider.instance
p3.camera.cameraInfo.cameraState.emit(CameraState(CameraState.StateError(CameraState.ERROR_CAMERA_IN_USE)))
CameraClock.advance();check(occupied.diagnosticsSnapshot().sessionFailure==CameraSessionFailure.IN_USE && occupied.diagnosticsSnapshot().recoveries==0);cases++
occupied.stop()
// Synchronous bind rejection also switches profile once; revoked permission never retries.
CameraClock.reset();ProcessCameraProvider.instance=ProcessCameraProvider().apply {throwBind=true}
val deniedContext=android.content.Context()
val sync=ExpressionController(deniedContext,object: androidx.lifecycle.LifecycleOwner {},{})
sync.start();CameraClock.await {sync.diagnosticsSnapshot().recoveries==1}
CameraClock.advance(250);check(ProcessCameraProvider.instance.bindings.single().format==ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888);cases++
sync.stop()
CameraClock.reset();ProcessCameraProvider.instance=ProcessCameraProvider()
val revoked=android.content.Context();val revokedController=ExpressionController(revoked,object: androidx.lifecycle.LifecycleOwner {},{})
revokedController.start();CameraClock.await {ProcessCameraProvider.instance.bindings.size==1}
revoked.permission=false
ProcessCameraProvider.instance.camera.cameraInfo.cameraState.emit(CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)))
CameraClock.advance(1000);check(ProcessCameraProvider.instance.bindings.size==1 && revokedController.diagnosticsSnapshot().stage==CameraStage.OFF);cases++
val log=android.util.Log.lines.joinToString("\n")
check("LanVoiceCamera|camera event=model_ready" in log && "event=first_frame" in log && "event=first_result" in log && "session_failure=stream_config" in log);cases++
check(listOf("synthetic_bind_error","landmark","image=","prompt=","reply=").none {it in log});cases++
println("PASS: $cases actual ExpressionController provider/native-error/analyzer/result/observer/one-YUV-retry/deadline/stop/stale-callback assertions; CameraX/MediaPipe doubles, MTK device not_run")
}
+33
View File
@@ -0,0 +1,33 @@
package android.os
class Looper { companion object {
val owner=Thread.currentThread();private val main=Looper();private val other=Looper()
fun getMainLooper()=main
fun myLooper()=if(Thread.currentThread()===owner) main else other
} }
object SystemClock { fun elapsedRealtime()=CameraClock.now }
class Handler(val looper: Looper=Looper.getMainLooper()) {
fun post(r: Runnable): Boolean=postDelayed(r,0)
fun postDelayed(r: Runnable,ms: Long): Boolean {CameraClock.add(this,r,ms);return true}
fun removeCallbacks(r: Runnable) {CameraClock.remove(this,r)}
}
object CameraClock {
@Volatile var now=0L
private data class Task(val h: Handler,val r: Runnable,val due: Long,val order: Long)
private val tasks=java.util.PriorityQueue<Task>(compareBy<Task> {it.due}.thenBy {it.order})
private var serial=0L
@Synchronized fun add(h: Handler,r: Runnable,ms: Long) {tasks.add(Task(h,r,now+ms,serial++))}
@Synchronized fun remove(h: Handler,r: Runnable) {tasks.removeIf {it.h===h && it.r===r}}
@Synchronized fun reset() {tasks.clear();now=0;serial=0}
fun advance(ms: Long=0) {
val end=now+ms
while(true) {
val task=synchronized(this) {if(tasks.peek()?.due?.let {it<=end}==true) tasks.poll() else null} ?: break
now=task.due;task.r.run()
};now=end
}
fun await(condition: ()->Boolean) {
val deadline=System.nanoTime()+3_000_000_000
while(!condition()) {advance();check(System.nanoTime()<deadline);Thread.sleep(1)}
advance()
}
}
+8
View File
@@ -0,0 +1,8 @@
package android.content
class Context {
var permission=true
val applicationContext get()=this
fun checkSelfPermission(name: String)=if(permission) 0 else -1
fun getSystemService(name: String)=android.view.WindowManager()
companion object {const val WINDOW_SERVICE="window"}
}
+2
View File
@@ -0,0 +1,2 @@
package com.gorios.lanvoice.net
object DebugLogUpload {fun log(tag: String,msg: String) {}}
+27
View File
@@ -0,0 +1,27 @@
package com.google.mediapipe.tasks.vision.facelandmarker
class Landmark {fun x()=.5f;fun y()=.5f}
class Category {fun categoryName()="none";fun score()=0f}
class Result {
fun faceLandmarks(): List<List<Landmark>> = emptyList()
fun faceBlendshapes(): java.util.Optional<List<List<Category>>> = java.util.Optional.empty()
fun facialTransformationMatrixes(): java.util.Optional<List<FloatArray>> = java.util.Optional.empty()
}
class FaceLandmarker {
fun detectForVideo(image: com.google.mediapipe.framework.image.MPImage,now: Long)=Result()
fun close() {}
class FaceLandmarkerOptions {
companion object {fun builder()=Builder()}
class Builder {
fun setBaseOptions(b: com.google.mediapipe.tasks.core.BaseOptions)=this
fun setRunningMode(r: com.google.mediapipe.tasks.vision.core.RunningMode)=this
fun setNumFaces(n: Int)=this
fun setMinFaceDetectionConfidence(f: Float)=this
fun setMinFacePresenceConfidence(f: Float)=this
fun setMinTrackingConfidence(f: Float)=this
fun setOutputFaceBlendshapes(b: Boolean)=this
fun setOutputFacialTransformationMatrixes(b: Boolean)=this
fun build()=FaceLandmarkerOptions()
}
}
companion object {fun createFromOptions(c: android.content.Context,o: FaceLandmarkerOptions)=FaceLandmarker()}
}
+12
View File
@@ -0,0 +1,12 @@
package android.graphics
object ImageFormat {const val YUV_420_888=35}
class Matrix {fun postRotate(f: Float) {}}
class Rect(val left: Int,val top: Int,val right: Int,val bottom: Int) {fun width()=right-left;fun height()=bottom-top}
class Bitmap(val width: Int,val height: Int) {
enum class Config {ARGB_8888}
fun recycle() {}
companion object {
fun createBitmap(p: IntArray,w: Int,h: Int,c: Config)=Bitmap(w,h)
fun createBitmap(b: Bitmap,x: Int,y: Int,w: Int,h: Int,m: Matrix,f: Boolean)=Bitmap(w,h)
}
}
+3
View File
@@ -0,0 +1,3 @@
package com.google.mediapipe.framework.image
class MPImage {fun close() {}}
class BitmapImageBuilder(b: android.graphics.Bitmap) {fun build()=MPImage()}
+9
View File
@@ -0,0 +1,9 @@
package androidx.lifecycle
interface LifecycleOwner
fun interface Observer<T> {fun onChanged(value: T)}
class LiveData<T>(var current: T) {
val observers=mutableListOf<Observer<T>>()
fun observe(owner: LifecycleOwner,o: Observer<T>) {observers+=o;o.onChanged(current)}
fun removeObserver(o: Observer<T>) {observers.remove(o)}
fun emit(value: T) {current=value;observers.toList().forEach {it.onChanged(value)}}
}
+2
View File
@@ -0,0 +1,2 @@
package android
object Manifest {object permission {const val CAMERA="camera"}}
+2
View File
@@ -0,0 +1,2 @@
package android.content.pm
object PackageManager {const val PERMISSION_GRANTED=0}
+16
View File
@@ -0,0 +1,16 @@
package androidx.camera.lifecycle
import androidx.camera.core.*
class ProcessCameraProvider {
val camera=Camera();val bindings=mutableListOf<ImageAnalysis>();val unbound=mutableListOf<ImageAnalysis>()
var throwBind=false
fun hasCamera(s: CameraSelector)=true
fun bindToLifecycle(l: androidx.lifecycle.LifecycleOwner,s: CameraSelector,a: ImageAnalysis): Camera {
if(throwBind) {throwBind=false;error("synthetic_bind_error")};bindings+=a;return camera
}
fun unbind(a: ImageAnalysis) {unbound+=a}
class Future(val provider: ProcessCameraProvider) {
fun get()=provider
fun addListener(r: Runnable,e: java.util.concurrent.Executor) {e.execute(r)}
}
companion object {var instance=ProcessCameraProvider();fun getInstance(c: android.content.Context)=Future(instance)}
}
+3
View File
@@ -0,0 +1,3 @@
package androidx.camera.core.resolutionselector
class ResolutionStrategy(val size: android.util.Size,val fallback: Int) {companion object {const val FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER=3}}
class ResolutionSelector(val strategy: ResolutionStrategy) {class Builder {lateinit var s: ResolutionStrategy;fun setResolutionStrategy(s: ResolutionStrategy)=apply {this.s=s};fun build()=ResolutionSelector(s)}}
+2
View File
@@ -0,0 +1,2 @@
package com.google.mediapipe.tasks.vision.core
enum class RunningMode {VIDEO}
+2
View File
@@ -0,0 +1,2 @@
package com.gorios.lanvoice.diag
object StartupTrace {enum class Phase {CAMERA_MODEL,CAMERA_BIND,CAMERA_READY};fun mark(p: Phase,start: Long?=null) {}}
+3
View File
@@ -0,0 +1,3 @@
package android.util
class Size(val width: Int,val height: Int)
object Log {val lines=java.util.Collections.synchronizedList(mutableListOf<String>());fun i(tag: String,msg: String): Int {lines+="$tag|$msg";return 0}}
+3
View File
@@ -0,0 +1,3 @@
package android.view
class WindowManager {val defaultDisplay=Display()}
class Display {val rotation=0}
+31
View File
@@ -0,0 +1,31 @@
import com.gorios.lanvoice.expression.*
import java.nio.ByteBuffer
fun cameraPixelsCheck() {
fun plane(bytes: IntArray,row: Int,pixel: Int,offset: Int=0)=CameraPixelPlane(
ByteBuffer.wrap(bytes.map { it.toByte() }.toByteArray()).apply { position(offset) },row,pixel)
val rgba=plane(intArrayOf(99,10,20,30,255,40,50,60,128,99,99,70,80,90,255,100,110,120,255,99,99),10,4,1)
check(CameraPixelConverter.argb(listOf(rgba),false,0,0,2,2).toList()==
listOf(0xff0a141e.toInt(),0x8028323c.toInt(),0xff46505a.toInt(),0xff646e78.toInt()))
check(CameraPixelConverter.argb(listOf(rgba),false,1,1,1,1).single()==0xff646e78.toInt())
check(rgba.bytes.position()==1)
val luma=plane(intArrayOf(16,235,99,99,81,145,99,99),4,1)
val chroma=plane(intArrayOf(128,99,128,99),4,2)
val pixels=CameraPixelConverter.argb(listOf(luma,chroma,chroma),true,0,0,2,2)
check(pixels[0]==0xff000000.toInt() && pixels[1]==0xffffffff.toInt())
check((pixels[2] and 0xffffff)==0x4c4c4c && (pixels[3] and 0xffffff)==0x969696)
// Shared interleaved chroma buffers, each view starts at its own channel.
val uv=ByteBuffer.wrap(byteArrayOf(90,240.toByte(),99,99))
val u=CameraPixelPlane(uv.duplicate(),4,2);val v=CameraPixelPlane(uv.duplicate().apply { position(1) },4,2)
val red=CameraPixelConverter.argb(listOf(plane(IntArray(4) {81},2,1),u,v),true,1,1,1,1).single()
check((red ushr 16 and 255)==255 && (red ushr 8 and 255)==0 && (red and 255)==0)
check(uv.position()==0 && v.bytes.position()==1)
for(block in listOf<()->Unit>(
{CameraPixelConverter.argb(listOf(rgba),true,0,0,2,2)},
{CameraPixelConverter.argb(listOf(rgba),false,0,0,4000,4000)},
{CameraPixelConverter.argb(listOf(rgba),false,-1,0,1,1)},
{CameraPixelConverter.argb(listOf(rgba),false,0,0,2,3)},
{CameraPixelConverter.argb(listOf(plane(intArrayOf(1),1,1)),false,0,0,1,1)}
)) check(runCatching(block).isFailure)
println("PASS: production RGBA/native YUV local conversion, row/pixel strides/crop/plane offsets/shared chroma/BT601/clamp, buffer positions and malformed/bounded allocation rejection; no real camera")
}
+5 -1
View File
@@ -1,6 +1,7 @@
import com.gorios.lanvoice.expression.*
fun main() {
cameraPixelsCheck()
val fence=CameraCallbackFence()
val initial=fence.nextBinding()
check(fence.accepts(initial))
@@ -18,7 +19,10 @@ fun main() {
boot.stage(CameraStage.WAITING_FRAME,30000)
check(cameraTimeout(boot.snapshot(),34999)==CameraFailure.NONE)
check(canRecoverFirstFrame(boot.snapshot(),cameraTimeout(boot.snapshot(),35000)))
boot.recovering();boot.stage(CameraStage.WAITING_FRAME,35000)
check(canRecoverFirstFrame(boot.snapshot(),CameraFailure.STREAM_CONFIG))
boot.recovering();check(boot.snapshot().profile==CameraProfile.YUV_320)
check(!canRecoverFirstFrame(boot.snapshot(),CameraFailure.STREAM_CONFIG))
boot.stage(CameraStage.WAITING_FRAME,35000)
check(!canRecoverFirstFrame(boot.snapshot(),cameraTimeout(boot.snapshot(),40000)))
boot.received(39000)
check(boot.snapshot().stage==CameraStage.WAITING_RESULT)
+22
View File
@@ -1,6 +1,7 @@
import importlib.util
from pathlib import Path
import unittest
import tempfile,sys
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
spec=importlib.util.spec_from_file_location('presence_package',ROOT/'scripts/package-avatar-emotion.py')
@@ -18,6 +19,27 @@ class PresencePackageTests(unittest.TestCase):
with patch.object(pack,'tested_source'),patch.object(pack,'packaging_tests_current'),patch.object(pack,'read_json',return_value={'edges':[{'nativeLoop':True}]}),patch.object(pack,'next_version',return_value=24),patch.object(pack.subprocess,'run',side_effect=stop_build):
with self.assertRaises(ValueError):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,24,full=True,startup_fix=True,face_diagnostics_fix=True)
with self.assertRaisesRegex(RuntimeError,'build_sentinel'):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,24,full=True,startup_fix=True,presence_candidate=True,face_diagnostics_fix=True)
def test_camera_compatibility_release_requires_diagnostics_replay_and_fresh_code(self):
def stop_build(command,**kwargs):
if command[0]=='python3': return
for flag in ('-PcameraCompatibilityFix=true','-PfaceDiagnosticsFix=true',
'-PpresenceCandidate=true','-PavatarStartupFix=true','-PactionVersionCode=25'):
self.assertIn(flag,command)
raise RuntimeError('build_sentinel')
with patch.object(pack,'tested_source'),patch.object(pack,'packaging_tests_current'),patch.object(pack,'read_json',
return_value={'edges':[{'nativeLoop':True}],'camera_callback_replay':True}),patch.object(pack,'next_version',return_value=25), patch.object(pack.subprocess,'run',side_effect=stop_build):
with self.assertRaises(ValueError): pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,25,
full=True,startup_fix=True,presence_candidate=True,camera_compatibility_fix=True)
with self.assertRaisesRegex(RuntimeError,'build_sentinel'): pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,25,
full=True,startup_fix=True,presence_candidate=True,face_diagnostics_fix=True,camera_compatibility_fix=True)
def test_camera_cli_is_one_purpose_not_two_inherited_flags(self):
with tempfile.TemporaryDirectory() as folder:
args=['package-avatar-emotion.py','--manifest',str(ROOT/'app/src/main/assets'/pack.ASSET_ROOT/'manifest.json'),
'--sha256',pack.RUNTIME_FIX_PIN,'--output',str(Path(folder)/'evidence'),'--camera-compatibility-fix']
with patch.object(sys,'argv',args),patch.object(pack,'check_bundle',side_effect=RuntimeError('gate_sentinel')):
with self.assertRaisesRegex(RuntimeError,'gate_sentinel'): pack.main()
with patch.object(sys,'argv',args+['--face-diagnostics-fix']):
with self.assertRaisesRegex(ValueError,'choose one build purpose'): pack.main()
def test_fresh_presence_version_requires_startup_and_frozen_pack(self):
report={'manifest_sha256':pack.RUNTIME_FIX_PIN}
def stop_build(command,**kwargs):