Recover camera session failures once with low-resolution native YUV
This commit is contained in:
+3
-1
@@ -19,6 +19,7 @@ def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull ==
|
||||
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
|
||||
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
|
||||
def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true'
|
||||
def cameraCompatibilityFix = providers.gradleProperty('cameraCompatibilityFix').orNull == 'true'
|
||||
def faceDiagnosticsFix = providers.gradleProperty('faceDiagnosticsFix').orNull == 'true'
|
||||
def presenceCandidate = providers.gradleProperty('presenceCandidate').orNull == 'true'
|
||||
def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true'
|
||||
@@ -40,6 +41,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?
|
||||
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
|
||||
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
|
||||
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
|
||||
if (cameraCompatibilityFix && (!faceDiagnosticsFix || actionVersionCode < 25)) throw new GradleException('Camera compatibility requires face diagnostics and fresh code >=25')
|
||||
if (faceDiagnosticsFix && (!presenceCandidate || actionVersionCode < 24)) throw new GradleException('Face diagnostics fix requires presence and fresh code >=24')
|
||||
if (presenceCandidate && (!avatarStartupFix || actionVersionCode < 23)) throw new GradleException('Presence candidate requires startup fix and fresh code >=23')
|
||||
if (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22')
|
||||
@@ -95,7 +97,7 @@ android {
|
||||
targetSdk 34
|
||||
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
||||
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
|
||||
versionName = faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
|
||||
versionName = cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -116,7 +116,10 @@ object DiagnosticReportUpload {
|
||||
.put("stage_elapsed_ms",(android.os.SystemClock.elapsedRealtime()-info.cameraAnalysis.stageSinceMs).coerceAtLeast(0))
|
||||
.put("last_frame_age_ms",info.cameraAnalysis.lastFrameMs.takeIf { it>=0 }?.let { (android.os.SystemClock.elapsedRealtime()-it).coerceAtLeast(0) } ?: -1)
|
||||
.put("last_result_age_ms",info.cameraAnalysis.lastResultMs.takeIf { it>=0 }?.let { (android.os.SystemClock.elapsedRealtime()-it).coerceAtLeast(0) } ?: -1)
|
||||
.put("recoveries",info.cameraAnalysis.recoveries))
|
||||
.put("recoveries",info.cameraAnalysis.recoveries)
|
||||
.put("profile",info.cameraAnalysis.profile.name.lowercase())
|
||||
.put("session_failure",info.cameraAnalysis.sessionFailure.name.lowercase())
|
||||
.put("frame_width",info.cameraAnalysis.frameWidth).put("frame_height",info.cameraAnalysis.frameHeight))
|
||||
.put("presence", JSONObject().put("enabled",info.presence.enabled).put("camera_active",info.presence.cameraActive)
|
||||
.put("supported",info.presence.supported).put("observation",info.presence.observation.name.lowercase())
|
||||
.put("sample_age_ms",info.presence.sampleAgeMs).put("absent_elapsed_ms",info.presence.absentElapsedMs)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
data class CameraPixelPlane(val bytes: ByteBuffer,val rowStride: Int,val pixelStride: Int)
|
||||
|
||||
/** Local transient pixels only. CameraX YUV planes may have padded/shared chroma rows. */
|
||||
object CameraPixelConverter {
|
||||
fun argb(planes: List<CameraPixelPlane>,yuv: Boolean,left: Int,top: Int,width: Int,height: Int): IntArray {
|
||||
require(left>=0 && top>=0 && width in 1..4096 && height in 1..4096 && width.toLong()*height<=4_000_000)
|
||||
require(planes.size==if(yuv) 3 else 1)
|
||||
require(planes.all { it.rowStride>0 && it.pixelStride>0 })
|
||||
if(!yuv) require(planes[0].pixelStride>=4)
|
||||
fun sample(p: CameraPixelPlane,x: Int,y: Int,channel: Int=0): Int {
|
||||
val offset=p.bytes.position().toLong()+y.toLong()*p.rowStride+x.toLong()*p.pixelStride+channel
|
||||
require(offset in p.bytes.position().toLong() until p.bytes.limit().toLong())
|
||||
return p.bytes.get(offset.toInt()).toInt() and 255
|
||||
}
|
||||
return IntArray(width*height) { index ->
|
||||
val x=left+index%width;val y=top+index/width
|
||||
if(yuv) {
|
||||
val yy=(sample(planes[0],x,y)-16).coerceAtLeast(0)
|
||||
val u=sample(planes[1],x/2,y/2)-128;val v=sample(planes[2],x/2,y/2)-128
|
||||
val r=((298*yy+409*v+128) shr 8).coerceIn(0,255)
|
||||
val g=((298*yy-100*u-208*v+128) shr 8).coerceIn(0,255)
|
||||
val b=((298*yy+516*u+128) shr 8).coerceIn(0,255)
|
||||
(255 shl 24) or (r shl 16) or (g shl 8) or b
|
||||
} else {
|
||||
val p=planes[0]
|
||||
(sample(p,x,y,3) shl 24) or (sample(p,x,y) shl 16) or (sample(p,x,y,1) shl 8) or sample(p,x,y,2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.gorios.lanvoice.expression
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.ImageFormat
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Matrix
|
||||
import android.os.Handler
|
||||
@@ -11,7 +12,12 @@ import android.os.SystemClock
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import com.gorios.lanvoice.net.DebugLogUpload
|
||||
import androidx.camera.core.CameraState
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.resolutionselector.ResolutionSelector
|
||||
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
@@ -43,6 +49,8 @@ class ExpressionController(
|
||||
var analysis: ImageAnalysis? = null // Accessed only on main.
|
||||
var provider: ProcessCameraProvider? = null // Accessed only on main.
|
||||
var firstReady=false
|
||||
var states: LiveData<CameraState>?=null
|
||||
var stateObserver: Observer<CameraState>?=null
|
||||
val callbacks=CameraCallbackFence()
|
||||
var lastSampleMs = Long.MIN_VALUE
|
||||
var lastPublished: List<ExpressionCue>? = null
|
||||
@@ -62,23 +70,8 @@ class ExpressionController(
|
||||
val snapshot=run.diagnostics.snapshot()
|
||||
val failure=cameraTimeout(snapshot,now)
|
||||
if(failure!=CameraFailure.NONE) {
|
||||
if(canRecoverFirstFrame(snapshot,failure)) {
|
||||
run.diagnostics.recovering()
|
||||
DebugLogUpload.log("audio","camera recovery=first_frame_retry")
|
||||
// Same model/run, at most one rebind; invalidate queued old analyzer/provider callbacks.
|
||||
run.callbacks.invalidate()
|
||||
try {
|
||||
run.analysis?.clearAnalyzer()
|
||||
run.analysis?.let { run.provider?.unbind(it) }
|
||||
} catch (_: Exception) {
|
||||
fail(run,"摄像头恢复失败,请重新开启。","camera_bind");return
|
||||
}
|
||||
run.analysis=null
|
||||
bind(run)
|
||||
} else {
|
||||
fail(run,"摄像头未持续输出可用结果,请重新开启;语音功能不受影响。",failure.name.lowercase())
|
||||
return
|
||||
}
|
||||
recoverOrFail(run,failure)
|
||||
if(!isCurrent(run)) return
|
||||
}
|
||||
run.diagnostics.summary(now)?.let { DebugLogUpload.log("audio", it) }
|
||||
main.postDelayed(this, 1_000)
|
||||
@@ -99,6 +92,7 @@ class ExpressionController(
|
||||
current = run
|
||||
lastDiagnostics = run.diagnostics
|
||||
run.diagnostics.stage(CameraStage.MODEL_LOADING,SystemClock.elapsedRealtime())
|
||||
cameraEvent(run,"model_loading")
|
||||
main.post(diagnosticTick)
|
||||
onState(ExpressionUiState(ExpressionStatus.STARTING))
|
||||
// Model loading and all synchronous VIDEO inference stay off the UI/audio threads.
|
||||
@@ -119,7 +113,7 @@ class ExpressionController(
|
||||
val modelStart=android.os.SystemClock.elapsedRealtime()
|
||||
run.landmarker = FaceLandmarker.createFromOptions(appContext, options)
|
||||
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_MODEL,modelStart)
|
||||
main.post { if (isCurrent(run)) bind(run) }
|
||||
main.post { if (isCurrent(run)) { cameraEvent(run,"model_ready");bind(run) } }
|
||||
} catch (_: Exception) {
|
||||
fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。", "model_load")
|
||||
} catch (_: LinkageError) {
|
||||
@@ -166,29 +160,60 @@ class ExpressionController(
|
||||
fail(run, "未找到前置摄像头,语音功能仍可使用。", "no_front_camera")
|
||||
return@addListener
|
||||
}
|
||||
val analysis = ImageAnalysis.Builder()
|
||||
.setTargetResolution(Size(640, 480))
|
||||
.setTargetRotation((appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
|
||||
.defaultDisplay.rotation)
|
||||
val profile=run.diagnostics.snapshot().profile
|
||||
val builder=ImageAnalysis.Builder()
|
||||
.setTargetRotation((appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
if(profile==CameraProfile.RGBA_640) builder.setTargetResolution(Size(640,480))
|
||||
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
|
||||
.build()
|
||||
else builder.setResolutionSelector(ResolutionSelector.Builder().setResolutionStrategy(
|
||||
ResolutionStrategy(Size(320,240),ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)).build())
|
||||
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
|
||||
val analysis=builder.build()
|
||||
run.provider = provider
|
||||
run.analysis = analysis
|
||||
analysis.setAnalyzer(run.executor) { image -> analyze(run, image,binding) }
|
||||
// ImageAnalysis only: no Preview, capture, video recording or image persistence.
|
||||
val bindStart=android.os.SystemClock.elapsedRealtime()
|
||||
run.diagnostics.stage(CameraStage.WAITING_FRAME,bindStart)
|
||||
provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
|
||||
val camera=provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
|
||||
cameraEvent(run,"bound")
|
||||
val states=camera.cameraInfo.cameraState
|
||||
var firstState=true
|
||||
val observer=Observer<CameraState> { state ->
|
||||
val initial=firstState;firstState=false
|
||||
if(isCurrent(run) && run.callbacks.accepts(binding)) {
|
||||
val code=state.error?.code
|
||||
if(code!=null) {
|
||||
val reason=when(code) {
|
||||
CameraState.ERROR_STREAM_CONFIG -> CameraSessionFailure.STREAM_CONFIG
|
||||
CameraState.ERROR_CAMERA_IN_USE -> CameraSessionFailure.IN_USE
|
||||
CameraState.ERROR_MAX_CAMERAS_IN_USE -> CameraSessionFailure.LIMIT
|
||||
CameraState.ERROR_CAMERA_DISABLED -> CameraSessionFailure.DISABLED
|
||||
CameraState.ERROR_CAMERA_FATAL_ERROR -> CameraSessionFailure.FATAL
|
||||
else -> CameraSessionFailure.OTHER
|
||||
}
|
||||
if(run.diagnostics.snapshot().sessionFailure!=reason) {
|
||||
run.diagnostics.sessionFailure(reason);cameraEvent(run,"session_error")
|
||||
}
|
||||
// LiveData may still hold the old session's error during compatibility rebind.
|
||||
// Its first value alone cannot fail the new attempt; the frame deadline remains.
|
||||
if(reason==CameraSessionFailure.STREAM_CONFIG && !(initial && profile==CameraProfile.YUV_320)) main.post {
|
||||
if(isCurrent(run) && run.callbacks.accepts(binding)) recoverOrFail(run,CameraFailure.STREAM_CONFIG)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
run.states=states;run.stateObserver=observer;states.observe(lifecycleOwner,observer)
|
||||
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart)
|
||||
// Binding is not readiness. ACTIVE is published only after an actual inference result.
|
||||
onState(ExpressionUiState(ExpressionStatus.STARTING))
|
||||
} catch (_: Exception) {
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
|
||||
recoverOrFail(run,CameraFailure.CAMERA_BIND)
|
||||
}
|
||||
}, { action -> main.post(action) })
|
||||
} catch (_: Exception) {
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
|
||||
recoverOrFail(run,CameraFailure.CAMERA_BIND)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,11 +222,11 @@ class ExpressionController(
|
||||
try {
|
||||
if (!run.active || !run.callbacks.accepts(binding)) return
|
||||
run.diagnostics.received(SystemClock.elapsedRealtime())
|
||||
if(!run.firstReady) { run.firstReady=true;com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) }
|
||||
if(!run.firstReady) { run.firstReady=true;run.diagnostics.frameShape(image.width,image.height);cameraEvent(run,"first_frame");com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) }
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return
|
||||
run.lastSampleMs = now
|
||||
bitmap = rgbaBitmap(image)
|
||||
bitmap = cameraBitmap(image)
|
||||
if (!run.active) return
|
||||
val mpImage = BitmapImageBuilder(bitmap).build()
|
||||
val result = try {
|
||||
@@ -230,7 +255,9 @@ class ExpressionController(
|
||||
(landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) *
|
||||
(landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f
|
||||
val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now)
|
||||
val firstResult=run.diagnostics.snapshot().processed==0
|
||||
run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - now,SystemClock.elapsedRealtime())
|
||||
if(firstResult) cameraEvent(run,"first_result")
|
||||
main.post { if (isCurrent(run) && run.callbacks.accepts(binding)) onFaceCue(faceCue) }
|
||||
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
|
||||
val presence = if (result.faceLandmarks().isEmpty()) FacePresence.ABSENT else FacePresence.PRESENT
|
||||
@@ -254,9 +281,47 @@ class ExpressionController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun cameraEvent(run: Run,event: String) {
|
||||
val s=run.diagnostics.snapshot()
|
||||
val text="camera event=$event profile=${s.profile.name.lowercase()} stage=${s.stage.name.lowercase()} session_failure=${s.sessionFailure.name.lowercase()} received=${s.received} processed=${s.processed} recoveries=${s.recoveries} width=${s.frameWidth} height=${s.frameHeight}"
|
||||
android.util.Log.i("LanVoiceCamera",text)
|
||||
DebugLogUpload.log("audio",text)
|
||||
}
|
||||
|
||||
private fun unbind(run: Run) {
|
||||
run.stateObserver?.let { run.states?.removeObserver(it) }
|
||||
run.stateObserver=null;run.states=null
|
||||
run.analysis?.clearAnalyzer()
|
||||
run.analysis?.let { run.provider?.unbind(it) }
|
||||
run.analysis=null
|
||||
}
|
||||
|
||||
/** One compatibility attempt, not repeated rebinding of the failed configuration. */
|
||||
private fun recoverOrFail(run: Run,reason: CameraFailure) {
|
||||
if(!isCurrent(run)) return
|
||||
if(appContext.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
|
||||
permissionDenied();return
|
||||
}
|
||||
if(!canRecoverFirstFrame(run.diagnostics.snapshot(),reason)) {
|
||||
fail(run,"摄像头未输出可用结果,请重新开启;语音功能不受影响。",reason.name.lowercase());return
|
||||
}
|
||||
run.diagnostics.recovering();run.callbacks.invalidate()
|
||||
cameraEvent(run,"compat_retry")
|
||||
try { unbind(run) } catch(_: Exception) {
|
||||
fail(run,"摄像头恢复失败,请重新开启。","camera_bind");return
|
||||
}
|
||||
val token=run.callbacks.nextBinding()
|
||||
run.diagnostics.stage(CameraStage.PROVIDER_WAIT,SystemClock.elapsedRealtime())
|
||||
onPresence(null,SystemClock.elapsedRealtime())
|
||||
onState(ExpressionUiState(ExpressionStatus.STARTING))
|
||||
// Only recovery waits a small bounded settle; normal startup has no extra delay.
|
||||
main.postDelayed({ if(isCurrent(run) && run.callbacks.accepts(token)) bind(run) },250)
|
||||
}
|
||||
|
||||
private fun fail(run: Run, guidance: String, reason: String) {
|
||||
run.diagnostics.failed(CameraFailure.entries.firstOrNull { it.name.lowercase() == reason } ?: CameraFailure.ANALYSIS)
|
||||
// Prevent another scheduled frame from running before main unbinds the camera.
|
||||
cameraEvent(run,"failed")
|
||||
run.active = false
|
||||
main.post {
|
||||
if (!released && current === run) {
|
||||
@@ -275,12 +340,7 @@ class ExpressionController(
|
||||
main.removeCallbacks(diagnosticTick)
|
||||
run.active = false
|
||||
run.callbacks.close()
|
||||
try {
|
||||
run.analysis?.clearAnalyzer()
|
||||
} catch (_: Exception) { }
|
||||
try {
|
||||
run.analysis?.let { run.provider?.unbind(it) } // Unbind only this feature's use case.
|
||||
} catch (_: Exception) { }
|
||||
try { unbind(run) } catch (_: Exception) { }
|
||||
run.analysis = null
|
||||
run.provider = null
|
||||
// An in-flight CPU inference may finish; its result is discarded. Close on its executor
|
||||
@@ -309,25 +369,13 @@ class ExpressionController(
|
||||
companion object { private const val SAMPLE_INTERVAL_MS = 100L }
|
||||
}
|
||||
|
||||
/** Convert CameraX RGBA using pixel/row strides, crop and sensor rotation; no selfie mirror. */
|
||||
private fun rgbaBitmap(image: ImageProxy): Bitmap {
|
||||
val plane = image.planes.first()
|
||||
val bytes = plane.buffer.duplicate()
|
||||
val base = bytes.position()
|
||||
/** Convert CameraX RGBA/native YUV using pixel/row strides, crop and sensor rotation; no selfie mirror. */
|
||||
private fun cameraBitmap(image: ImageProxy): Bitmap {
|
||||
val crop=image.cropRect
|
||||
val width = crop.width()
|
||||
val height = crop.height()
|
||||
val pixels = IntArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
val offset = base + (y + crop.top) * plane.rowStride + (x + crop.left) * plane.pixelStride
|
||||
val red = bytes.get(offset).toInt() and 0xff
|
||||
val green = bytes.get(offset + 1).toInt() and 0xff
|
||||
val blue = bytes.get(offset + 2).toInt() and 0xff
|
||||
val alpha = bytes.get(offset + 3).toInt() and 0xff
|
||||
pixels[y * width + x] = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
|
||||
}
|
||||
}
|
||||
val width=crop.width();val height=crop.height()
|
||||
val planes=image.planes.map { CameraPixelPlane(it.buffer.duplicate(),it.rowStride,it.pixelStride) }
|
||||
val pixels=CameraPixelConverter.argb(planes,image.format==ImageFormat.YUV_420_888,
|
||||
crop.left,crop.top,width,height)
|
||||
val raw = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
|
||||
val rotation = image.imageInfo.rotationDegrees
|
||||
if (rotation == 0) return raw
|
||||
|
||||
@@ -94,6 +94,7 @@ fun FaceDebugPanel(camera: ()->CameraAnalysisSnapshot,presence: ()->PresenceDiag
|
||||
CameraStage.WAITING_FRAME->"等待首帧";CameraStage.WAITING_RESULT->"等待首个分析结果"
|
||||
CameraStage.READY->"结果就绪";CameraStage.FAILED->"失败"
|
||||
}} · ${c.failure.name.lowercase()}",fontSize=12.sp)
|
||||
Text("配置 ${c.profile.name.lowercase()} · 最近会话 ${c.sessionFailure.name.lowercase()} · 帧尺寸 ${c.frameWidth}×${c.frameHeight}",fontSize=12.sp)
|
||||
Text("帧 ${c.received} · 分析 ${c.processed} · 人脸 ${c.faceCount} · 耗时 ${c.lastProcessMs}ms · 恢复 ${c.recoveries}",fontSize=12.sp)
|
||||
Text("主动发言:${p.observation.name.lowercase()} · 门禁 ${p.block.name.lowercase()} · 采样年龄 ${p.sampleAgeMs}ms",fontSize=12.sp)
|
||||
Text("缺人 ${p.absentElapsedMs/1000.0}/20s · 有人 ${p.presentElapsedMs/1000.0}/1s · 冷却 ${p.cooldownMs/1000}s",fontSize=12.sp)
|
||||
|
||||
@@ -2,7 +2,9 @@ package com.gorios.lanvoice.expression
|
||||
|
||||
/** Fixed fields only. No image, coefficient, pose, free text, or user speech. */
|
||||
enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT,
|
||||
MODEL_TIMEOUT, PROVIDER_TIMEOUT, FRAME_TIMEOUT, RESULT_TIMEOUT }
|
||||
MODEL_TIMEOUT, PROVIDER_TIMEOUT, FRAME_TIMEOUT, RESULT_TIMEOUT, STREAM_CONFIG }
|
||||
enum class CameraProfile { RGBA_640, YUV_320 }
|
||||
enum class CameraSessionFailure { NONE, STREAM_CONFIG, IN_USE, LIMIT, DISABLED, FATAL, OTHER }
|
||||
enum class CameraStage { OFF, MODEL_LOADING, PROVIDER_WAIT, WAITING_FRAME, WAITING_RESULT, READY, FAILED }
|
||||
data class CameraAnalysisSnapshot(
|
||||
val received: Int = 0, val processed: Int = 0, val failures: Int = 0,
|
||||
@@ -10,6 +12,8 @@ data class CameraAnalysisSnapshot(
|
||||
val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE,
|
||||
val lastProcessMs: Long = 0,
|
||||
val stage: CameraStage = CameraStage.OFF, val stageSinceMs: Long = 0,
|
||||
val profile: CameraProfile = CameraProfile.RGBA_640, val sessionFailure: CameraSessionFailure = CameraSessionFailure.NONE,
|
||||
val frameWidth: Int = 0,val frameHeight: Int = 0,
|
||||
val lastFrameMs: Long = -1, val lastResultMs: Long = -1, val recoveries: Int = 0,
|
||||
)
|
||||
|
||||
@@ -27,7 +31,8 @@ fun cameraTimeout(s: CameraAnalysisSnapshot,now: Long): CameraFailure = when(s.s
|
||||
else -> CameraFailure.NONE
|
||||
}
|
||||
fun canRecoverFirstFrame(s: CameraAnalysisSnapshot,f: CameraFailure) =
|
||||
f==CameraFailure.FRAME_TIMEOUT && s.received==0 && s.recoveries==0
|
||||
f in setOf(CameraFailure.FRAME_TIMEOUT,CameraFailure.STREAM_CONFIG,CameraFailure.CAMERA_BIND) &&
|
||||
s.stage !in setOf(CameraStage.OFF,CameraStage.FAILED) && s.received==0 && s.recoveries==0
|
||||
|
||||
/** Shared by actual provider/analyzer/result callbacks; a rebind or stop retires old callbacks. */
|
||||
class CameraCallbackFence {
|
||||
@@ -43,7 +48,9 @@ class CameraAnalysisDiagnostics {
|
||||
private var state = CameraAnalysisSnapshot()
|
||||
private var lastLogMs: Long? = null
|
||||
@Synchronized fun stage(stage: CameraStage,now: Long) { state=state.copy(stage=stage,stageSinceMs=now) }
|
||||
@Synchronized fun recovering() { state=state.copy(recoveries=state.recoveries+1) }
|
||||
@Synchronized fun recovering() { state=state.copy(recoveries=state.recoveries+1,profile=CameraProfile.YUV_320) }
|
||||
@Synchronized fun sessionFailure(reason: CameraSessionFailure) { state=state.copy(sessionFailure=reason) }
|
||||
@Synchronized fun frameShape(width: Int,height: Int) { state=state.copy(frameWidth=width.coerceIn(0,8192),frameHeight=height.coerceIn(0,8192)) }
|
||||
@Synchronized fun received(now: Long=0) { state = state.copy(received = (state.received + 1).coerceAtMost(1_000_000),
|
||||
lastFrameMs=now,stage=if(state.stage==CameraStage.WAITING_FRAME) CameraStage.WAITING_RESULT else state.stage,
|
||||
stageSinceMs=if(state.stage==CameraStage.WAITING_FRAME) now else state.stageSinceMs) }
|
||||
@@ -61,7 +68,7 @@ class CameraAnalysisDiagnostics {
|
||||
val last = lastLogMs
|
||||
if (!force && last != null && nowMs - last < 10_000) return null
|
||||
lastLogMs = nowMs
|
||||
return "camera analysis stage=${state.stage.name.lowercase()} received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs} recoveries=${state.recoveries}"
|
||||
return "camera analysis stage=${state.stage.name.lowercase()} received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs} recoveries=${state.recoveries} profile=${state.profile.name.lowercase()} session_failure=${state.sessionFailure.name.lowercase()} width=${state.frameWidth} height=${state.frameHeight}"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# 相机捕获会话兼容候选 0.7.7
|
||||
|
||||
## 已有证据与修复边界
|
||||
|
||||
用户提供日志:CameraX 于09:26:36、09:26:42绑定,捕获会话报 `Failed to create capture session; configuration failed`。这支持捕获会话/出帧故障,不能仅凭缺 ExpressionCameraManager/FaceLandmarker/Presence TAG 断言相关类没执行。当前实际入口是 `ExpressionController`:先在后台创建 FaceLandmarker,随后只绑定一个 ImageAnalysis(无Preview/录像/图片捕获)。先前5s首帧恢复重新用了同一640×480 RGBA配置;不会修正不兼容配置,也没有订阅原生CameraState的会话错误。
|
||||
|
||||
这次修正了可确定的恢复逻辑缺口,交付**待真机验证的兼容候选**,不宣称已经证明MTK HAL/硬件/相机占用问题被修好。
|
||||
|
||||
## 变更
|
||||
|
||||
1. 正常首次配置仍为640×480 RGBA、KEEP_ONLY_LATEST、前置相机、单ImageAnalysis。订阅CameraX CameraState,仅输出固定STREAM_CONFIG/IN_USE/LIMIT/DISABLED/FATAL/OTHER枚举,不记录异常正文。
|
||||
2. 首帧前 `ERROR_STREAM_CONFIG`、同步bind失败、5s无首帧触发最多一次兼容尝试:解绑自身usecase/清理旧observer及analyzer,退休旧callback generation,250ms有限恢复settle后用320×240原生YUV重绑。ResolutionSelector按closest-lower-then-higher选择设备实际支持尺寸,320×240是请求值,真实尺寸以首帧记录为准。无额外正常启动延时,无同配置无限retry。
|
||||
3. 兼容重绑的LiveData首值可能仍是前次会话错误;该首值单独不能杀掉新尝试,后续新错误或5s首帧期限仍严格生效。失败明确UNAVAILABLE,模型/语音不重启;只解除本feature usecase,不关闭其他应用相机。
|
||||
4. 原生YUV三平面→ARGB本地转换,处理独立rowStride/pixelStride/plane position、共享chroma、crop及sensor rotation;保留RGBA通道顺序。所有像素仅瞬时本地CPU内存,Bitmap/proxy在成功、旧callback、throttle和异常路径释放,不保存/上传。
|
||||
5. `LanVoiceCamera` TAG记录 model_loading/model_ready/bound/session_error/compat_retry/first_frame/first_result/failed。诊断及设置内新增profile、最近session_failure、真实frame_width/height;原received/processed/阶段/恢复次数/10s摘要继续。没有帧级原图、脸坐标、系数、录音或聊天日志。
|
||||
6. 相机停用/后台/权限撤销会退休observer、旧帧和待执行fallback;不会复活相机。FaceLandmarker模型、.5检测阈值、100ms采样、presence20s/1s/冷却与TTS忙时门禁均未更改。
|
||||
|
||||
## 回归与交付
|
||||
|
||||
- 10 JVM/UI入口:原9入口和新增生产ExpressionController回调回放。21项相机控制器断言覆盖native会话配置失败、一次YUV尝试、旧会话首error缓存、旧frame/observer、真实analyzer回调到首result/ACTIVE、连续失败有界、后台settle取消、同步bind失败、权限撤销、in-use原因与日志隐私。CameraX/MediaPipe为doubles,不能称真机相机会话已通过。
|
||||
- 生产pixel converter测试RGBA及native YUV、padding/stride/crop/shared UV/buffer position、BT601颜色、clamp、非法输入/内存边界。原1410presence断言/播放PTS757+native103/双尺寸各1288媒体回调/两尺寸full graph cache gates继续通过。
|
||||
- 42包装回归;gateway portable source测试110 passed+1既有Silero归档排除skip。gateway源码/部署/时间/provider/TTS/VAD均无变更、无重启/额外推理或素材生成。
|
||||
- 720×1280支持已独立提交 `ddd75fc`,合同见 `GLES_720_SUPPORT.md`;本候选仍只携带冻结白衣480×848资产,旧pin `987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`、3222runtime文件不变。旧五包200 GLES及720 procedural30像素检查通过,不是手机GPU认证。
|
||||
- APK0.7.7/code25、com.gorios.lanvoice、arm64、min26/target34、同debug证书 `b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`。旧code24及所有已发布包保留。Gradle及instrumentation Kotlin编译、APK签名/badging/包内引用hash/HTTPbytes核验;instrumentation运行、USB安装、MTK出帧与检测灵敏度均待测。
|
||||
|
||||
下载:`http://192.168.31.124:8080/lan-voice-v077-camera-compat-code25-arm64-debug.apk`
|
||||
|
||||
SHA256:`7cbf372add69cae19600ae6e0dad08b45f6ec3b433b7daa8a3b01fc87482ac2e`。`.apk.sha256`同URL后缀。首个导出名误沿用v076前缀,保留为相同构建的字节相同副本;上述v077是规范交付名,APK内部版本始终0.7.7/code25,没有覆写已发布APK或同code换hash。全部3819 assets与code24逐字节相同。实际APK生产loader/renderer回调及启动cold/receipt回放均通过,main_asset_reads=0(宿主doubles,不是真机)。新角色素材未导入,此阶段费用0。
|
||||
|
||||
## 一次有界真机验证
|
||||
|
||||
正常启动后使用现有相机权限/开关(可能本地采样;离线播放检查不采集)。只需观察设置“人脸检测调试”是否从waiting_frame到READY,received/processed是否增长、真实尺寸及profile。若首次失败应至多一次yuv_320恢复;再失败显示stage=failed和session_failure,发送现有诊断报告即可区分会话错误/零帧/有帧无结果。不用清数据、无线ADB、换时间/TTS或反复生成素材。
|
||||
|
||||
可采安全TAG:`adb logcat -s LanVoiceCamera:I LanVoiceStartup:I`,只留上述enum/单调计时及计数;本文不授权另行录制用户摄像头、音频或原聊天。本轮未连接/控制真机。
|
||||
@@ -5,6 +5,7 @@ cd "$(dirname "$0")/.."
|
||||
mkdir -p logs/avatar-safe-061
|
||||
python3 scripts/check-reply-regressions.py > logs/avatar-safe-061/client-tests.txt 2>&1
|
||||
./scripts/check-expression-rules.sh > logs/avatar-safe-061/expression-tests.txt 2>&1
|
||||
python3 scripts/check-camera-controller.py > logs/avatar-safe-061/camera-controller-tests.txt 2>&1
|
||||
python3 scripts/check-avatar-ui.py > logs/avatar-safe-061/ui-contract-tests.txt 2>&1
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
@@ -12,9 +13,9 @@ import hashlib,json
|
||||
root=Path.cwd()
|
||||
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'app/src/androidTest').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
|
||||
paths += list((root/'tests/avatar-pixels').glob('*.c'))
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/check-avatar-shader.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py','scripts/package-avatar-mouth.py')]
|
||||
result={'status':'passed','jvm_entry_points':9,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/check-camera-controller.py','scripts/check-avatar-shader.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py','scripts/package-avatar-mouth.py')]
|
||||
result={'status':'passed','jvm_entry_points':10,'camera_callback_replay':True,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
'hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(paths)}}
|
||||
(root/'logs/avatar-safe-061/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('PASS: nine JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
|
||||
print('PASS: ten JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
|
||||
PY
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Production ExpressionController callback replay; no camera/device or network."""
|
||||
from pathlib import Path
|
||||
import ast,subprocess,tempfile
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
script=ROOT/'scripts/check-reply-regressions.py'
|
||||
nodes=[]
|
||||
for node in ast.parse(script.read_text()).body:
|
||||
if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='parser' for t in node.targets): break
|
||||
nodes.append(node)
|
||||
ns={'__file__':str(script)};exec(compile(ast.Module(body=nodes,type_ignores=[]),str(script),'exec'),ns)
|
||||
real=[ROOT/'app/src/main/java/com/gorios/lanvoice/expression'/name for name in
|
||||
('ExpressionController.kt','ExpressionState.kt','ExpressionRules.kt','FaceCueRules.kt','FaceDiagnostics.kt','CameraPixelConverter.kt')]
|
||||
with tempfile.TemporaryDirectory(prefix='camera-controller-check-') as folder:
|
||||
subprocess.run([ns['JAVA'],'-cp',ns['compiler'],'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
|
||||
'-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'],'-d',folder,
|
||||
*map(str,list((ROOT/'tests/camera').glob('*.kt'))+real)],check=True,cwd=ROOT)
|
||||
subprocess.run([ns['JAVA'],'-cp',folder+':'+ns['cp'],'CameraControllerCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
@@ -30,6 +30,8 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/CameraPixelConverter.kt',
|
||||
'tests/expression/CameraPixelsCheck.kt',
|
||||
'tests/expression/ExpressionRulesCheck.kt',
|
||||
'tests/expression/FaceCueRulesCheck.kt',
|
||||
'tests/expression/CameraPermissionCheck.kt',
|
||||
|
||||
@@ -269,7 +269,7 @@ def reviewed_actions(index,pin,registry):
|
||||
|
||||
def tested_source(full=False):
|
||||
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
|
||||
require(client['status']=='passed' and client['jvm_entry_points'] in (9,10),'client regression evidence')
|
||||
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
|
||||
if full:
|
||||
evidence=read_json(ROOT/'logs/action-emotion/full-release/checks.json')
|
||||
@@ -304,14 +304,19 @@ def verify_runtime_fix_assets(built,pin,startup_fix=False):
|
||||
return len([p for p in paths(new) if p.startswith('assets/'+ASSET_ROOT)])
|
||||
|
||||
|
||||
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False,face_diagnostics_fix=False):
|
||||
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False,face_diagnostics_fix=False,camera_compatibility_fix=False):
|
||||
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
|
||||
'live emotion release needs bridge-own TALK runtimes')
|
||||
tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
||||
tested_source(full);packaging_tests_current();
|
||||
if camera_compatibility_fix:
|
||||
require(read_json(ROOT/'logs/avatar-safe-061/client-tests.json').get('camera_callback_replay') is True,
|
||||
'camera compatibility needs production controller callback replay')
|
||||
require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
||||
version=next_version((ROOT/'artifacts').glob('*.apk'))
|
||||
if requested is not None:
|
||||
require(requested>=version,'version code occupied');version=requested
|
||||
require(not full or version>=18,'full candidate needs code >=18')
|
||||
require(not camera_compatibility_fix or face_diagnostics_fix and version>=25,'camera compatibility needs diagnostics and fresh code >=25')
|
||||
require(not face_diagnostics_fix or presence_candidate and version>=24,'face diagnostics needs presence and fresh code >=24')
|
||||
require(not presence_candidate or startup_fix and version>=23,'presence candidate needs startup and fresh code >=23')
|
||||
require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape')
|
||||
@@ -322,9 +327,9 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
require(not runtime_fix or full and version>=19 and report['manifest_sha256']==RUNTIME_FIX_PIN,'runtime fix release shape')
|
||||
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
|
||||
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower(),'-PfaceDiagnosticsFix='+str(face_diagnostics_fix).lower()],check=True,cwd=ROOT)
|
||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower(),'-PfaceDiagnosticsFix='+str(face_diagnostics_fix).lower(),'-PcameraCompatibilityFix='+str(camera_compatibility_fix).lower()],check=True,cwd=ROOT)
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
|
||||
version_name='0.7.6' if face_diagnostics_fix else '0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
|
||||
version_name='0.7.7' if camera_compatibility_fix else '0.7.6' if face_diagnostics_fix else '0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
|
||||
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
require(text in badge,'APK metadata: '+text)
|
||||
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
||||
@@ -344,8 +349,8 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
if startup_fix: require('AVATAR_STARTUP_FIX = true' in config.read_text(),'compiled startup flag mismatch')
|
||||
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
|
||||
if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'],startup_fix)==len(report['files']),'runtime fix file count')
|
||||
stem='face-diagnostics' if face_diagnostics_fix else 'presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
|
||||
release='v076' if face_diagnostics_fix else 'v075' if presence_candidate else 'v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070'
|
||||
stem='camera-compat' if camera_compatibility_fix else 'face-diagnostics' if face_diagnostics_fix else 'presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
|
||||
release='v'+version_name.split('-')[0].replace('.','')
|
||||
artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk'
|
||||
with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
|
||||
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
|
||||
@@ -359,7 +364,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'],
|
||||
'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,
|
||||
'gateway_deployed':bool(full and read_json(ROOT/'logs/action-emotion/full-release/checks.json').get('gateway_deployed',False)),
|
||||
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'face_diagnostics_fix':face_diagnostics_fix,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
|
||||
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'face_diagnostics_fix':face_diagnostics_fix,'camera_compatibility_fix':camera_compatibility_fix,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
|
||||
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
|
||||
return delivery
|
||||
|
||||
@@ -381,8 +386,9 @@ def main():
|
||||
parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap')
|
||||
parser.add_argument('--presence-candidate',action='store_true',help='0.7.5 presence-triggered assistant turns, frozen runtime and startup assets')
|
||||
parser.add_argument('--face-diagnostics-fix',action='store_true',help='0.7.6 local camera readiness/recovery and presence diagnostics; frozen assets')
|
||||
parser.add_argument('--camera-compatibility-fix',action='store_true',help='0.7.7 bounded low-resolution native YUV camera session recovery; frozen assets')
|
||||
args=parser.parse_args();
|
||||
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate,args.face_diagnostics_fix))<=1,'choose one build purpose')
|
||||
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate,args.face_diagnostics_fix,args.camera_compatibility_fix))<=1,'choose one build purpose')
|
||||
manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
||||
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
||||
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
|
||||
@@ -399,7 +405,7 @@ def main():
|
||||
require(not args.previous_pin and not args.backup,'previous import report required')
|
||||
import_files(manifest.parent,report['files'],target)
|
||||
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
|
||||
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate or args.face_diagnostics_fix,args.presence_candidate or args.face_diagnostics_fix,args.face_diagnostics_fix) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix,args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix,args.face_diagnostics_fix or args.camera_compatibility_fix,args.camera_compatibility_fix) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||
print(json.dumps(result,indent=2))
|
||||
|
||||
|
||||
|
||||
@@ -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()}}
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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"}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
package com.gorios.lanvoice.net
|
||||
object DebugLogUpload {fun log(tag: String,msg: String) {}}
|
||||
@@ -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()}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.google.mediapipe.framework.image
|
||||
class MPImage {fun close() {}}
|
||||
class BitmapImageBuilder(b: android.graphics.Bitmap) {fun build()=MPImage()}
|
||||
@@ -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)}}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
package android
|
||||
object Manifest {object permission {const val CAMERA="camera"}}
|
||||
@@ -0,0 +1,2 @@
|
||||
package android.content.pm
|
||||
object PackageManager {const val PERMISSION_GRANTED=0}
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -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)}}
|
||||
@@ -0,0 +1,2 @@
|
||||
package com.google.mediapipe.tasks.vision.core
|
||||
enum class RunningMode {VIDEO}
|
||||
@@ -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) {}}
|
||||
@@ -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}}
|
||||
@@ -0,0 +1,3 @@
|
||||
package android.view
|
||||
class WindowManager {val defaultDisplay=Display()}
|
||||
class Display {val rotation=0}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user