fix: pair front camera analysis with a local drained preview surface

This commit is contained in:
zenord
2026-10-13 18:54:59 +08:00
parent 4010675f8c
commit 688bb7d6b3
20 changed files with 453 additions and 24 deletions
+2 -1
View File
@@ -10,7 +10,8 @@ class CameraState(val error: StateError?=null,val type: Type=Type.CLOSED) {
}
class Camera(val cameraInfo: CameraInfo=CameraInfo())
class CameraInfo {val cameraState=LiveData(CameraState())}
class ImageAnalysis(val size: Size,val format: Int,val fallback: Int=0) {
open class UseCase
class ImageAnalysis(val size: Size,val format: Int,val fallback: Int=0) : UseCase() {
var callback: ((ImageProxy)->Unit)?=null;var executor: Executor?=null
fun setAnalyzer(e: Executor,c: (ImageProxy)->Unit) {executor=e;callback=c}
fun clearAnalyzer() {callback=null}
+11 -1
View File
@@ -5,6 +5,7 @@ import androidx.camera.core.resolutionselector.ResolutionStrategy
import androidx.camera.lifecycle.ProcessCameraProvider
fun main() {
cameraPreviewSurfaceCheck()
var cases=0
fun verify(value: Boolean) { check(value);cases++ }
fun rig(beforeStart: (ProcessCameraProvider)->Unit={}): Triple<ExpressionController,MutableList<ExpressionUiState>,MutableList<Boolean?>> {
@@ -18,6 +19,8 @@ fun main() {
val a=ProcessCameraProvider.instance.bindings.single()
verify(a.size.width==640 && a.size.height==480 && a.format==ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
verify(a.fallback==ResolutionStrategy.FALLBACK_RULE_NONE && c.diagnosticsSnapshot().recoveries==0)
val preview=ProcessCameraProvider.instance.previews.single()
verify(preview.size.width==640 && preview.size.height==480 && preview.fallback==ResolutionStrategy.FALLBACK_RULE_NONE)
return Triple(c,states,presence)
}
// Device report: bound + zero images + failure. No automatic second session.
@@ -43,6 +46,11 @@ fun main() {
// Initial LiveData can retain an earlier lifecycle error. Real frames can still arrive.
val (ready,readyStates,presence)=rig { it.camera.cameraInfo.cameraState.current=CameraState(CameraState.StateError(CameraState.ERROR_STREAM_CONFIG)) }
val p3=ProcessCameraProvider.instance;val actual=p3.bindings.single();val previousAnalyzer=actual.callback!!
val request=p3.previews.single().request();CameraClock.advance()
verify(request.provided==1 && ready.diagnosticsSnapshot().previewProvided)
request.surface!!.texture.frame();CameraClock.advance()
verify(ready.diagnosticsSnapshot().previewFirstFrameMs==0L && readyStates.last().status==ExpressionStatus.STARTING)
verify(ready.diagnosticsSnapshot().processed==0 && presence.isEmpty()) // Preview frame is not an analysis/ABSENT result.
CameraClock.advance(200)
p3.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.OPEN))
val frame=ImageProxy();actual.frame(frame);CameraClock.await {frame.closed && ready.diagnosticsSnapshot().processed==1}
@@ -53,6 +61,8 @@ fun main() {
repeat(100) {p3.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.OPEN))}
verify(android.util.Log.lines.size==logsBefore)
ready.stop();CameraClock.advance();val count=presence.size
verify(p3.unboundPreviews.size==1 && !request.surface!!.released)
request.complete();CameraClock.advance();verify(ready.diagnosticsSnapshot().previewReleased && request.surface!!.released)
val retired=ImageProxy();previousAnalyzer(retired)
CameraClock.advance(30000);verify(retired.closed && p3.bindings.size==1 && presence.size==count && p3.camera.cameraInfo.cameraState.observers.isEmpty())
@@ -79,5 +89,5 @@ fun main() {
val log=android.util.Log.lines.joinToString("\n")
verify("event=bind_requested" in log && "event=first_frame t_ms=200 bind_elapsed_ms=200" in log && "native_state=open" in log)
verify(listOf("compat_retry","synthetic_bind_error","landmark","image=","prompt=","reply=").none {it in log})
println("PASS: $cases actual ExpressionController single-front-YUV640/no-rebind/native-state/zero-frame/retained-error/first-result/permission/stop/stale-callback assertions; CameraX/MediaPipe doubles, MTK device not_run")
println("PASS: $cases actual ExpressionController front-preview-plus-YUV640/no-rebind/native-state/zero-frame/retained-error/first-result/permission/stop/stale-callback assertions; CameraX/MediaPipe doubles, MTK device not_run")
}
+6
View File
@@ -4,6 +4,12 @@ class Looper { companion object {
fun getMainLooper()=main
fun myLooper()=if(Thread.currentThread()===owner) main else other
} }
class HandlerThread(val name: String) {
val looper=Looper();var quit=false
fun start() { threads+=this }
fun quitSafely(): Boolean {quit=true;return true}
companion object {val threads=mutableListOf<HandlerThread>()}
}
object SystemClock { fun elapsedRealtime()=CameraClock.now }
class Handler(val looper: Looper=Looper.getMainLooper()) {
fun post(r: Runnable): Boolean=postDelayed(r,0)
+12
View File
@@ -1,4 +1,16 @@
package android.graphics
class SurfaceTexture(val texture: Int) {
fun interface OnFrameAvailableListener {fun onFrameAvailable(surface: SurfaceTexture)}
var released=false;var updates=0;var throwUpdate=false
var width=0;var height=0
private var listener: OnFrameAvailableListener?=null;private var handler: android.os.Handler?=null
init {check(texture in android.opengl.GLES20.liveTextures)}
fun setDefaultBufferSize(w: Int,h: Int) {width=w;height=h}
fun setOnFrameAvailableListener(l: OnFrameAvailableListener?,h: android.os.Handler?=null) {listener=l;handler=h}
fun frame() {val cb=listener ?: return;handler!!.post {cb.onFrameAvailable(this)}}
fun updateTexImage() {check(!released);if(throwUpdate) error("synthetic_update_failure");updates++}
fun release() {check(!released);released=true}
}
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}
+27
View File
@@ -0,0 +1,27 @@
package androidx.camera.core
import android.util.Size
import android.view.Surface
import java.util.concurrent.Executor
class Preview(val size: Size,val fallback: Int) : UseCase() {
interface SurfaceProvider {fun onSurfaceRequested(request: SurfaceRequest)}
var provider: SurfaceProvider?=null
fun setSurfaceProvider(p: SurfaceProvider) {provider=p}
fun request(r: SurfaceRequest=SurfaceRequest(size)): SurfaceRequest {provider!!.onSurfaceRequested(r);return r}
class Builder {
var size=Size(640,480);var fallback=0
fun setTargetRotation(r: Int)=this
fun setResolutionSelector(r: androidx.camera.core.resolutionselector.ResolutionSelector)=apply {size=r.strategy.size;fallback=r.strategy.fallback}
fun build()=Preview(size,fallback)
}
}
class SurfaceRequest(val resolution: Size) {
var rejected=0;var surface: Surface?=null;var provided=0;var throwProvide=false
private var executor: Executor?=null;private var result: ((Result)->Unit)?=null
class Result
fun willNotProvideSurface(): Boolean {rejected++;return surface==null}
fun provideSurface(s: Surface,e: Executor,r: (Result)->Unit) {
if(throwProvide) error("synthetic_surface_failure")
check(provided==0);surface=s;provided++;executor=e;result=r
}
fun complete() {executor?.execute {result!!(Result())}}
}
+74
View File
@@ -0,0 +1,74 @@
import com.gorios.lanvoice.expression.*
import android.os.CameraClock
import android.os.HandlerThread
import android.opengl.EGL14
import android.opengl.GLES20
import androidx.camera.core.SurfaceRequest
fun cameraPreviewSurfaceCheck(): Int {
var cases=0
fun verify(value: Boolean) {check(value);cases++}
fun request()=SurfaceRequest(android.util.Size(640,480))
CameraClock.reset()
val events=mutableListOf<CameraPreviewEvent>();var errors=0
val sink=CameraPreviewSurface({e,_,_->events+=e},{errors++})
val r=request();sink.onSurfaceRequested(r);CameraClock.advance()
val surface=checkNotNull(r.surface);val thread=HandlerThread.threads.last()
verify(r.provided==1 && events==listOf(CameraPreviewEvent.REQUESTED,CameraPreviewEvent.PROVIDED))
verify(surface.texture.width==640 && surface.texture.height==480 && !thread.quit)
repeat(3) {surface.texture.frame()};CameraClock.advance()
verify(surface.texture.updates==3 && events.count {it==CameraPreviewEvent.FIRST_FRAME}==1)
sink.close();sink.close();CameraClock.advance()
verify(!surface.released && !surface.texture.released && !thread.quit) // Camera still owns producer.
surface.texture.frame();CameraClock.advance()
verify(surface.texture.updates==4 && errors==0) // Drain while CameraX asynchronously closes.
val rejected=request();sink.onSurfaceRequested(rejected);CameraClock.advance()
verify(rejected.rejected==1 && rejected.provided==0)
r.complete();r.complete();CameraClock.advance()
verify(surface.released && surface.texture.released && thread.quit)
verify(events.count {it==CameraPreviewEvent.RELEASED}==1 && GLES20.liveTextures.isEmpty())
verify(EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
// Late frame queued behind release must not update a released texture or report readiness.
val lateEvents=mutableListOf<CameraPreviewEvent>()
val late=CameraPreviewSurface({e,_,_->lateEvents+=e},{errors++});val lr=request()
late.onSurfaceRequested(lr);CameraClock.advance();val ls=checkNotNull(lr.surface)
lr.complete();ls.texture.frame();late.close();CameraClock.advance()
verify(ls.released && ls.texture.updates==0 && CameraPreviewEvent.FIRST_FRAME !in lateEvents)
// Stop before queued request executes never allocates/returns a Surface.
val stopped=CameraPreviewSurface({_,_,_->},{errors++});val sr=request()
stopped.onSurfaceRequested(sr);stopped.close();CameraClock.advance()
verify(sr.rejected==1 && sr.provided==0 && HandlerThread.threads.last().quit)
// Actual worker initialization failure is one enum-only failure, not fallback/retry.
EGL14.failInitialize=true
val failing=CameraPreviewSurface({_,_,_->},{errors++});val fr=request()
failing.onSurfaceRequested(fr);CameraClock.advance();EGL14.failInitialize=false
verify(fr.rejected==1 && errors==1 && HandlerThread.threads.last().quit)
// Surface rejected before transfer releases locally, with no leaked GPU/camera ownership.
val broken=CameraPreviewSurface({_,_,_->},{errors++});val br=request().apply {throwProvide=true}
broken.onSurfaceRequested(br);CameraClock.advance()
verify(br.provided==0 && br.rejected==1 && errors==2 && HandlerThread.threads.last().quit)
verify(GLES20.liveTextures.isEmpty() && EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
// Runtime latch failure requests teardown, but must wait for the camera's release callback.
val update=CameraPreviewSurface({_,_,_->},{errors++});val ur=request()
update.onSurfaceRequested(ur);CameraClock.advance();val us=checkNotNull(ur.surface)
us.texture.throwUpdate=true;us.texture.frame();us.texture.frame();CameraClock.advance()
verify(errors==3 && !us.released && !HandlerThread.threads.last().quit)
ur.complete();CameraClock.advance()
verify(us.released && HandlerThread.threads.last().quit && GLES20.liveTextures.isEmpty())
// CameraX can replace a request; at most two in-flight surfaces, all release once.
val bounded=CameraPreviewSurface({_,_,_->},{errors++})
val one=request();val two=request();val three=request()
bounded.onSurfaceRequested(one);bounded.onSurfaceRequested(two);bounded.onSurfaceRequested(three);CameraClock.advance()
verify(one.provided==1 && two.provided==1 && three.rejected==1 && errors==4)
one.complete();CameraClock.advance();verify(!HandlerThread.threads.last().quit)
two.complete();CameraClock.advance()
verify(HandlerThread.threads.last().quit && GLES20.liveTextures.isEmpty() && EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
println("PASS: $cases production camera Preview consumer lifetime/frame-drain/stop-before-provide/stale-frame/once-release/GL-failure/bounded-surfaces assertions; EGL/SurfaceTexture doubles, device not_run")
return cases
}
+34
View File
@@ -0,0 +1,34 @@
package android.opengl
class EGLDisplay
class EGLContext
class EGLSurface
class EGLConfig
object EGL14 {
val EGL_NO_DISPLAY=EGLDisplay();val EGL_NO_CONTEXT=EGLContext();val EGL_NO_SURFACE=EGLSurface()
const val EGL_DEFAULT_DISPLAY=0;const val EGL_RENDERABLE_TYPE=1;const val EGL_OPENGL_ES2_BIT=2
const val EGL_SURFACE_TYPE=3;const val EGL_PBUFFER_BIT=4;const val EGL_RED_SIZE=5;const val EGL_GREEN_SIZE=6
const val EGL_BLUE_SIZE=7;const val EGL_ALPHA_SIZE=8;const val EGL_NONE=9;const val EGL_CONTEXT_CLIENT_VERSION=10
const val EGL_WIDTH=11;const val EGL_HEIGHT=12
var failInitialize=false;var destroyedContexts=0;var destroyedSurfaces=0;var releasedThreads=0
val liveContexts=mutableSetOf<EGLContext>();val liveSurfaces=mutableSetOf<EGLSurface>()
fun eglGetDisplay(id: Int)=EGLDisplay()
fun eglInitialize(d: EGLDisplay,a: IntArray,ai: Int,b: IntArray,bi: Int)=!failInitialize
fun eglChooseConfig(d: EGLDisplay,a: IntArray,offset: Int,c: Array<EGLConfig?>,co: Int,n: Int,num: IntArray,no: Int): Boolean {c[0]=EGLConfig();num[0]=1;return true}
fun eglCreateContext(d: EGLDisplay,c: EGLConfig?,s: EGLContext,a: IntArray,o: Int)=EGLContext().also {liveContexts+=it}
fun eglCreatePbufferSurface(d: EGLDisplay,c: EGLConfig?,a: IntArray,o: Int)=EGLSurface().also {liveSurfaces+=it}
fun eglMakeCurrent(d: EGLDisplay,a: EGLSurface,b: EGLSurface,c: EGLContext)=true
fun eglDestroySurface(d: EGLDisplay,s: EGLSurface): Boolean {check(liveSurfaces.remove(s));destroyedSurfaces++;return true}
fun eglDestroyContext(d: EGLDisplay,c: EGLContext): Boolean {check(liveContexts.remove(c));destroyedContexts++;return true}
fun eglReleaseThread(): Boolean {releasedThreads++;return true}
fun eglTerminate(d: EGLDisplay): Boolean {error("must_not_terminate_role_display")}
}
object GLES11Ext {const val GL_TEXTURE_EXTERNAL_OES=36197}
object GLES20 {
const val GL_TEXTURE_MIN_FILTER=1;const val GL_TEXTURE_MAG_FILTER=2;const val GL_LINEAR=3
const val GL_TEXTURE_WRAP_S=4;const val GL_TEXTURE_WRAP_T=5;const val GL_CLAMP_TO_EDGE=6
var nextId=1;val liveTextures=mutableSetOf<Int>()
fun glGenTextures(n: Int,ids: IntArray,o: Int) {repeat(n) {ids[o+it]=nextId++;liveTextures+=ids[o+it]}}
fun glBindTexture(t: Int,id: Int) {check(id in liveTextures)}
fun glTexParameteri(t: Int,p: Int,v: Int) {}
fun glDeleteTextures(n: Int,ids: IntArray,o: Int) {repeat(n) {check(liveTextures.remove(ids[o+it]))}}
}
+5
View File
@@ -0,0 +1,5 @@
package android.view
class Surface(val texture: android.graphics.SurfaceTexture) {
var released=false
fun release() {check(!released);released=true}
}
+6 -3
View File
@@ -2,12 +2,15 @@ package androidx.camera.lifecycle
import androidx.camera.core.*
class ProcessCameraProvider {
val camera=Camera();val bindings=mutableListOf<ImageAnalysis>();val unbound=mutableListOf<ImageAnalysis>()
val previews=mutableListOf<Preview>();val unboundPreviews=mutableListOf<Preview>()
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 bindToLifecycle(l: androidx.lifecycle.LifecycleOwner,s: CameraSelector,vararg cases: UseCase): Camera {
if(throwBind) {throwBind=false;error("synthetic_bind_error")}
check(cases.size==2 && cases[0] is Preview && cases[1] is ImageAnalysis)
bindings+=cases.filterIsInstance<ImageAnalysis>();previews+=cases.filterIsInstance<Preview>();return camera
}
fun unbind(a: ImageAnalysis) {unbound+=a}
fun unbind(vararg cases: UseCase) {unbound+=cases.filterIsInstance<ImageAnalysis>();unboundPreviews+=cases.filterIsInstance<Preview>()}
class Future(val provider: ProcessCameraProvider) {
fun get()=provider
fun addListener(r: Runnable,e: java.util.concurrent.Executor) {e.execute(r)}