fix: preserve camera permission intent and distinguish unknown reply expression
This commit is contained in:
+2
-2
@@ -45,8 +45,8 @@ android {
|
||||
applicationId 'com.gorios.lanvoice'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 8
|
||||
versionName '0.5.0'
|
||||
versionCode 9
|
||||
versionName '0.5.1'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -47,6 +47,7 @@ import com.gorios.lanvoice.diag.DiagnosticReportInfo
|
||||
import com.gorios.lanvoice.diag.DiagnosticReportUpload
|
||||
import com.gorios.lanvoice.net.ConnectionStatus
|
||||
import com.gorios.lanvoice.net.DebugLogUpload
|
||||
import com.gorios.lanvoice.expression.CameraPermissionGate
|
||||
import com.gorios.lanvoice.expression.ExpressionController
|
||||
import com.gorios.lanvoice.expression.ExpressionControls
|
||||
import com.gorios.lanvoice.expression.ExpressionStatus
|
||||
@@ -65,13 +66,11 @@ class MainActivity : ComponentActivity() {
|
||||
private var pendingStart = false
|
||||
private var expressionState by mutableStateOf(ExpressionUiState())
|
||||
private lateinit var expressions: ExpressionController
|
||||
private var pendingCamera = false
|
||||
private val cameraGate = CameraPermissionGate()
|
||||
private var inForeground = false
|
||||
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
val shouldStart = pendingCamera && inForeground
|
||||
pendingCamera = false
|
||||
if (granted && shouldStart) expressions.start()
|
||||
else if (!granted) expressions.permissionDenied()
|
||||
DebugLogUpload.log("audio", "camera permission_result granted=$granted foreground=$inForeground")
|
||||
cameraAction(cameraGate.permissionResult(granted))
|
||||
}
|
||||
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground")
|
||||
@@ -99,7 +98,10 @@ class MainActivity : ComponentActivity() {
|
||||
onVoiceStopped = audioOutput::release,
|
||||
)
|
||||
expressions = ExpressionController(this, this,
|
||||
onState = { expressionState = it }, onFaceCue = session::observeFace)
|
||||
onState = {
|
||||
if (expressionState.status != it.status) DebugLogUpload.log("audio", "camera state=${it.status.name.lowercase()}")
|
||||
expressionState = it
|
||||
}, onFaceCue = session::observeFace)
|
||||
setContent {
|
||||
Home(
|
||||
state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions,
|
||||
@@ -117,6 +119,14 @@ class MainActivity : ComponentActivity() {
|
||||
DiagnosticReportUpload.send(
|
||||
DiagnosticReportInfo(
|
||||
appVersion = appVersion,
|
||||
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode,
|
||||
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
|
||||
cameraStatus = expressionState.status,
|
||||
cameraPermissionPending = cameraGate.permissionPending,
|
||||
faceSharing = shareFace,
|
||||
rolePlaying = state.phase == VoicePhase.ANSWERING,
|
||||
role = state.replyEmotion.takeIf { it.turnId != null },
|
||||
previousRole = state.previousReplyEmotion,
|
||||
device = "${Build.MANUFACTURER} ${Build.MODEL}",
|
||||
androidApi = Build.VERSION.SDK_INT,
|
||||
connection = state.connection.name,
|
||||
@@ -135,15 +145,30 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun toggleExpressions() {
|
||||
if (!inForeground) return
|
||||
if (expressionState.status == ExpressionStatus.STARTING || expressionState.status == ExpressionStatus.ACTIVE) {
|
||||
pendingCamera = false
|
||||
expressions.stop()
|
||||
} else if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||||
expressions.start()
|
||||
} else if (!pendingCamera) {
|
||||
pendingCamera = true
|
||||
cameraPermission.launch(Manifest.permission.CAMERA)
|
||||
val granted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
|
||||
val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE)
|
||||
DebugLogUpload.log("audio", "camera click foreground=$inForeground granted=$granted running=$running pending=${cameraGate.permissionPending}")
|
||||
cameraAction(cameraGate.click(running, granted))
|
||||
}
|
||||
|
||||
private fun cameraAction(action: CameraPermissionGate.Action) {
|
||||
when (action) {
|
||||
CameraPermissionGate.Action.REQUEST_PERMISSION -> {
|
||||
DebugLogUpload.log("audio", "camera permission_request")
|
||||
cameraPermission.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
CameraPermissionGate.Action.START -> {
|
||||
if (inForeground) {
|
||||
DebugLogUpload.log("audio", "camera start_attempt")
|
||||
expressions.start()
|
||||
}
|
||||
}
|
||||
CameraPermissionGate.Action.STOP -> {
|
||||
DebugLogUpload.log("audio", "camera stop reason=user")
|
||||
expressions.stop()
|
||||
}
|
||||
CameraPermissionGate.Action.DENIED -> expressions.permissionDenied()
|
||||
CameraPermissionGate.Action.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,14 +199,16 @@ class MainActivity : ComponentActivity() {
|
||||
inForeground = true
|
||||
DebugLogUpload.log("connect", "activity onStart")
|
||||
session.foreground()
|
||||
cameraAction(cameraGate.onForeground())
|
||||
startPendingVoice()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
inForeground = false
|
||||
val permissionInFlight = pendingStart || pendingCamera
|
||||
val permissionInFlight = pendingStart || cameraGate.permissionPending
|
||||
DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations")
|
||||
pendingCamera = false
|
||||
cameraGate.onBackground()
|
||||
DebugLogUpload.log("audio", "camera stop reason=background")
|
||||
expressions.stop()
|
||||
if (!permissionInFlight) pendingStart = false
|
||||
session.background(
|
||||
@@ -192,6 +219,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
cameraGate.release()
|
||||
DebugLogUpload.log("audio", "camera stop reason=release")
|
||||
expressions.release()
|
||||
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
|
||||
session.release()
|
||||
@@ -255,7 +284,8 @@ fun Home(
|
||||
)
|
||||
}
|
||||
ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace)
|
||||
Text("角色:${state.replyEmotion.label}(角色表达)", color = gold, fontSize = 13.sp)
|
||||
Text("角色:${state.roleLabel}(角色表达)", color = gold, fontSize = 13.sp)
|
||||
state.previousReplyEmotion?.let { Text("上一轮:${it.label}", color = muted, fontSize = 12.sp) }
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.padding(top = 24.dp, bottom = 12.dp),
|
||||
|
||||
@@ -24,7 +24,14 @@ data class VoiceUiState(
|
||||
val aec: AecAvailability = AecAvailability.UNKNOWN,
|
||||
val guidance: String? = null,
|
||||
val replyEmotion: ReplyEmotion = ReplyEmotion(),
|
||||
)
|
||||
val previousReplyEmotion: ReplyEmotion? = null,
|
||||
) {
|
||||
val roleLabel: String get() = when {
|
||||
phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label
|
||||
voiceActive && phase in setOf(VoicePhase.RECOGNIZING, VoicePhase.THINKING, VoicePhase.ANSWERING) -> "等待回复"
|
||||
else -> "当前未播放"
|
||||
}
|
||||
}
|
||||
|
||||
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
|
||||
class VoiceSession(
|
||||
@@ -71,6 +78,7 @@ class VoiceSession(
|
||||
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
|
||||
diagnostic("playback drained turn=$turn")
|
||||
if (dialogue.playbackDrained(turn)) {
|
||||
resetReply("drained")
|
||||
emotionEndedTurn = turn
|
||||
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
|
||||
startCapture()
|
||||
@@ -162,6 +170,7 @@ class VoiceSession(
|
||||
|
||||
fun stopVoice(sendControls: Boolean = true) {
|
||||
checkMainThread()
|
||||
resetReply("stop")
|
||||
val wasActive = state.voiceActive
|
||||
stopCapture()
|
||||
playback.interrupt()
|
||||
@@ -179,6 +188,7 @@ class VoiceSession(
|
||||
fun interrupt() {
|
||||
checkMainThread()
|
||||
if (!isActive()) return
|
||||
resetReply("interrupt")
|
||||
blockedTurn = currentTurn
|
||||
playback.interrupt() // Silence locally before waiting for the server's abort event.
|
||||
if (dialogue.abort(currentTurn)) {
|
||||
@@ -225,6 +235,7 @@ class VoiceSession(
|
||||
private fun onConnection(connection: ConnectionStatus, reason: String) {
|
||||
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
|
||||
if (connection != ConnectionStatus.CONNECTED) {
|
||||
resetReply("disconnect")
|
||||
faceSupported = false
|
||||
faceSent = false
|
||||
faceCue = FaceCueObservation()
|
||||
@@ -291,6 +302,7 @@ class VoiceSession(
|
||||
private fun onEvent(event: ServerEvent) {
|
||||
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
|
||||
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
|
||||
if (event.kind == EventKind.REPLY_EMOTION) { receiveReply(event, turn); return }
|
||||
if (released || state.connection != ConnectionStatus.CONNECTED) {
|
||||
diagnostic("event ignored: connection=${state.connection.name} released=$released")
|
||||
return
|
||||
@@ -302,7 +314,6 @@ class VoiceSession(
|
||||
// An ABORT can announce the replacement turn. Remember the interrupted
|
||||
// turn before acceptTurn updates currentTurn and retires the old one.
|
||||
// An expression cannot announce/switch a turn. Other protocol events establish it first.
|
||||
if (event.kind == EventKind.REPLY_EMOTION && (!hasTurn || turn != currentTurn)) return
|
||||
val oldTurn = if (hasTurn) currentTurn else null
|
||||
if (turn != null && !acceptTurn(turn)) return
|
||||
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
|
||||
@@ -338,11 +349,6 @@ class VoiceSession(
|
||||
EventKind.LLM -> if (isActive() && state.phase != VoicePhase.ANSWERING) {
|
||||
update(state.copy(phase = VoicePhase.THINKING))
|
||||
}
|
||||
EventKind.REPLY_EMOTION -> if (isActive() && blockedTurn != currentTurn && emotionEndedTurn != currentTurn) {
|
||||
val emotion = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"),
|
||||
event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source")) ?: return
|
||||
if (emotion.sequence > state.replyEmotion.sequence) update(state.copy(replyEmotion = emotion))
|
||||
}
|
||||
EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) {
|
||||
// The gateway sends start BEFORE LLM generation and also tts.metrics.
|
||||
// Only received PCM means there is an answer to play.
|
||||
@@ -355,6 +361,7 @@ class VoiceSession(
|
||||
}
|
||||
}
|
||||
EventKind.ABORT -> {
|
||||
resetReply("abort")
|
||||
// listen_start aborts the previous reply while announcing the NEW turn.
|
||||
// The server's following LISTEN start and TTS belong to that new turn.
|
||||
val reason = event.payload.optString("reason")
|
||||
@@ -399,6 +406,7 @@ class VoiceSession(
|
||||
}
|
||||
// IDs identify turns; do not assume the server allocates them in numeric order.
|
||||
if (!hasTurn || id != currentTurn) {
|
||||
resetReply("new_turn")
|
||||
val resumeCapture = capturing
|
||||
if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq.
|
||||
if (hasTurn) retiredTurns.add(currentTurn)
|
||||
@@ -416,6 +424,38 @@ class VoiceSession(
|
||||
return true
|
||||
}
|
||||
|
||||
private fun receiveReply(event: ServerEvent, turn: Long?) {
|
||||
val reason = when {
|
||||
released -> "released"
|
||||
state.connection != ConnectionStatus.CONNECTED -> "disconnected"
|
||||
!hasTurn -> "no_turn"
|
||||
turn in retiredTurns -> "old_turn"
|
||||
turn != currentTurn -> "unannounced_turn"
|
||||
!isActive() -> "inactive"
|
||||
blockedTurn == currentTurn -> "blocked_turn"
|
||||
emotionEndedTurn == currentTurn -> "drained"
|
||||
else -> null
|
||||
}
|
||||
if (reason != null) { diagnostic("role ignore reason=$reason turn=$turn"); return }
|
||||
val expression = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"),
|
||||
event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source"),
|
||||
event.payload.opt("reason"), event.payload.opt("parse_branch"), event.payload.opt("finish_reason"))
|
||||
if (expression == null) { diagnostic("role ignore reason=invalid_identity turn=$turn"); return }
|
||||
if (expression.sequence <= state.replyEmotion.sequence) {
|
||||
diagnostic("role ignore reason=old_seq turn=$turn seq=${expression.sequence}"); return
|
||||
}
|
||||
update(state.copy(replyEmotion = expression))
|
||||
diagnostic("role apply turn=$turn seq=${expression.sequence} emotion=${expression.emotion.wire} intensity=${expression.intensity} source=${expression.source.name.lowercase()} reason=${expression.reason.wire} branch=${expression.parseBranch.wire} finish=${expression.finishReason.wire}")
|
||||
}
|
||||
|
||||
private fun resetReply(reason: String) {
|
||||
val expression = state.replyEmotion
|
||||
val played = preparedPlaybackTurn == currentTurn && expression.turnId == currentTurn
|
||||
if (expression.turnId != null) diagnostic("role reset reason=$reason turn=${expression.turnId} played=$played")
|
||||
update(state.copy(replyEmotion = ReplyEmotion(),
|
||||
previousReplyEmotion = if (played) expression else state.previousReplyEmotion))
|
||||
}
|
||||
|
||||
private fun failAudio(message: String, error: Exception) {
|
||||
diagnostic("audio failed: ${error.javaClass.simpleName} connection=${state.connection.name}", "error")
|
||||
Log.w(TAG, message, error)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.gorios.lanvoice.diag
|
||||
|
||||
import com.gorios.lanvoice.dialogue.ReplyEmotion
|
||||
import com.gorios.lanvoice.expression.ExpressionStatus
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.ConnectionPool
|
||||
@@ -25,6 +27,14 @@ data class DiagnosticReportInfo(
|
||||
val voiceActive: Boolean,
|
||||
val phase: String,
|
||||
val aec: String,
|
||||
val versionCode: Int = 0,
|
||||
val cameraGranted: Boolean = false,
|
||||
val cameraStatus: ExpressionStatus = ExpressionStatus.OFF,
|
||||
val cameraPermissionPending: Boolean = false,
|
||||
val faceSharing: Boolean = false,
|
||||
val rolePlaying: Boolean = false,
|
||||
val role: ReplyEmotion? = null,
|
||||
val previousRole: ReplyEmotion? = null,
|
||||
)
|
||||
|
||||
/** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */
|
||||
@@ -48,6 +58,12 @@ object DiagnosticReportUpload {
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun roleMetadata(role: ReplyEmotion?): Any = role?.let {
|
||||
JSONObject().put("turn_id", it.turnId).put("seq", it.sequence).put("emotion", it.emotion.wire)
|
||||
.put("intensity", it.intensity).put("source", it.source.name.lowercase()).put("reason", it.reason.wire)
|
||||
.put("parse_branch", it.parseBranch.wire).put("finish_reason", it.finishReason.wire)
|
||||
} ?: JSONObject.NULL
|
||||
|
||||
/** Result arrives on an OkHttp worker (or immediately if setup fails). */
|
||||
fun send(info: DiagnosticReportInfo, onResult: (Boolean) -> Unit) {
|
||||
if (!sending.compareAndSet(false, true)) {
|
||||
@@ -72,6 +88,12 @@ object DiagnosticReportUpload {
|
||||
.put("voice_active", info.voiceActive)
|
||||
.put("phase", info.phase)
|
||||
.put("aec", info.aec)
|
||||
.put("version_code", info.versionCode)
|
||||
.put("camera", JSONObject().put("granted", info.cameraGranted).put("status", info.cameraStatus.name.lowercase())
|
||||
.put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing))
|
||||
.put("role_playing", info.rolePlaying)
|
||||
.put("role_active", roleMetadata(info.role))
|
||||
.put("role_previous", roleMetadata(info.previousRole))
|
||||
.put("logs", logs)
|
||||
.toString().toRequestBody(json)
|
||||
client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback {
|
||||
|
||||
@@ -5,16 +5,32 @@ enum class RoleEmotion(val wire: String, val label: String) {
|
||||
NEUTRAL("neutral", "中立"), HAPPY("happy", "高兴"), ANGRY("angry", "生气"), SAD("sad", "难过")
|
||||
}
|
||||
enum class EmotionSource { MODEL, FALLBACK }
|
||||
enum class EmotionReason(val wire: String) {
|
||||
NONE("none"), MISSING_FIELDS("missing_fields"), UNEXPECTED_FIELDS("unexpected_fields"),
|
||||
INVALID_EMOTION("invalid_emotion"), INVALID_INTENSITY("invalid_intensity"), INVALID_REPLY("invalid_reply"),
|
||||
NON_JSON("non_json"), INVALID_JSON("invalid_json"), TRUNCATED("truncated"), INPUT_LIMIT("input_limit"), UNKNOWN("unknown")
|
||||
}
|
||||
enum class ParseBranch(val wire: String) {
|
||||
STRICT_JSON("strict_json"), FENCED_JSON("fenced_json"), JSON_REPLY("json_reply"), ALTERNATE_FIELD("alternate_field"),
|
||||
QUOTED_REPLY("quoted_reply"), REPAIRED_STRING("repaired_string"), PLAIN_TEXT("plain_text"), SAFE_REPLY("safe_reply"), UNKNOWN("unknown")
|
||||
}
|
||||
enum class FinishReason(val wire: String) {
|
||||
STOP("stop"), LENGTH("length"), CONTENT_FILTER("content_filter"), TOOL_CALLS("tool_calls"), FUNCTION_CALL("function_call"),
|
||||
NOT_PROVIDED("not_provided"), UNKNOWN("unknown")
|
||||
}
|
||||
data class ReplyEmotion(
|
||||
val emotion: RoleEmotion = RoleEmotion.NEUTRAL,
|
||||
val intensity: Int = 0,
|
||||
val source: EmotionSource = EmotionSource.FALLBACK,
|
||||
val turnId: Long? = null,
|
||||
val sequence: Long = -1,
|
||||
val reason: EmotionReason = EmotionReason.UNKNOWN,
|
||||
val parseBranch: ParseBranch = ParseBranch.UNKNOWN,
|
||||
val finishReason: FinishReason = FinishReason.NOT_PROVIDED,
|
||||
) {
|
||||
val label: String get() = emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" }
|
||||
val label: String get() = if (source == EmotionSource.FALLBACK) "表达未判定(格式回退)" else emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" }
|
||||
companion object {
|
||||
fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?): ReplyEmotion? {
|
||||
fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?, reason: Any? = null, branch: Any? = null, finish: Any? = null): ReplyEmotion? {
|
||||
fun integer(value: Any?): Long? = when (value) { is Int -> value.toLong(); is Long -> value; else -> null }
|
||||
val id = integer(turn)?.takeIf { it in 0..0xffff_ffffL } ?: return null
|
||||
val sequence = integer(seq)?.takeIf { it >= 0 } ?: return null
|
||||
@@ -26,7 +42,10 @@ data class ReplyEmotion(
|
||||
origin == EmotionSource.FALLBACK && kind != RoleEmotion.NEUTRAL) {
|
||||
return ReplyEmotion(turnId = id, sequence = sequence)
|
||||
}
|
||||
return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence)
|
||||
return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence,
|
||||
EmotionReason.entries.firstOrNull { it.wire == reason } ?: if (origin == EmotionSource.MODEL) EmotionReason.NONE else EmotionReason.UNKNOWN,
|
||||
ParseBranch.entries.firstOrNull { it.wire == branch } ?: ParseBranch.UNKNOWN,
|
||||
FinishReason.entries.firstOrNull { it.wire == finish } ?: FinishReason.NOT_PROVIDED)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
/** Explicit, one-shot camera intent. A permission result may arrive before or after onStart. */
|
||||
class CameraPermissionGate {
|
||||
enum class Action { NONE, REQUEST_PERMISSION, START, STOP, DENIED }
|
||||
var permissionPending = false
|
||||
private set
|
||||
private var foreground = false
|
||||
private var requested = false
|
||||
private var approved = false
|
||||
private var released = false
|
||||
|
||||
fun onForeground(): Action { foreground = true; return consumeStart() }
|
||||
fun onBackground() {
|
||||
foreground = false
|
||||
// Retain only a user-requested authorization continuation, never an active camera.
|
||||
if (!permissionPending && !approved) requested = false
|
||||
}
|
||||
fun click(running: Boolean, granted: Boolean): Action {
|
||||
if (released || !foreground) return Action.NONE
|
||||
if (running || requested) {
|
||||
requested = false; approved = false
|
||||
return Action.STOP
|
||||
}
|
||||
if (permissionPending) return Action.NONE
|
||||
requested = true
|
||||
if (granted) { approved = true; return consumeStart() }
|
||||
permissionPending = true
|
||||
return Action.REQUEST_PERMISSION
|
||||
}
|
||||
fun permissionResult(granted: Boolean): Action {
|
||||
if (released || !permissionPending) return Action.NONE
|
||||
permissionPending = false
|
||||
if (!granted) { requested = false; approved = false; return Action.DENIED }
|
||||
if (requested) approved = true
|
||||
return consumeStart()
|
||||
}
|
||||
fun release() { released = true; requested = false; approved = false; permissionPending = false }
|
||||
private fun consumeStart(): Action {
|
||||
if (!released && foreground && requested && approved) {
|
||||
requested = false; approved = false
|
||||
return Action.START
|
||||
}
|
||||
return Action.NONE
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import com.gorios.lanvoice.net.DebugLogUpload
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
@@ -78,9 +79,9 @@ class ExpressionController(
|
||||
run.landmarker = FaceLandmarker.createFromOptions(appContext, options)
|
||||
main.post { if (isCurrent(run)) bind(run) }
|
||||
} catch (_: Exception) {
|
||||
fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。")
|
||||
fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。", "model_load")
|
||||
} catch (_: LinkageError) {
|
||||
fail(run, "设备暂不支持表情分析,语音功能仍可使用。")
|
||||
fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +95,7 @@ class ExpressionController(
|
||||
|
||||
fun permissionDenied() {
|
||||
checkMainThread()
|
||||
DebugLogUpload.log("audio", "camera denied")
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
if (!released) onState(ExpressionUiState(guidance =
|
||||
@@ -117,7 +119,7 @@ class ExpressionController(
|
||||
try {
|
||||
val provider = future.get()
|
||||
if (!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {
|
||||
fail(run, "未找到前置摄像头,语音功能仍可使用。")
|
||||
fail(run, "未找到前置摄像头,语音功能仍可使用。", "no_front_camera")
|
||||
return@addListener
|
||||
}
|
||||
val analysis = ImageAnalysis.Builder()
|
||||
@@ -134,11 +136,11 @@ class ExpressionController(
|
||||
provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
|
||||
onState(ExpressionUiState(ExpressionStatus.ACTIVE))
|
||||
} catch (_: Exception) {
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。")
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
|
||||
}
|
||||
}, { action -> main.post(action) })
|
||||
} catch (_: Exception) {
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。")
|
||||
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,20 +187,21 @@ class ExpressionController(
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Never log exceptions from inference, frames, coefficients or head pose.
|
||||
fail(run, "表情分析已停止,请重新开启;语音功能不受影响。")
|
||||
fail(run, "表情分析已停止,请重新开启;语音功能不受影响。", "analysis")
|
||||
} catch (_: LinkageError) {
|
||||
fail(run, "设备暂不支持表情分析,语音功能仍可使用。")
|
||||
fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support")
|
||||
} finally {
|
||||
bitmap?.recycle()
|
||||
image.close() // Includes throttle/stop/error paths, so CameraX never retains the proxy.
|
||||
}
|
||||
}
|
||||
|
||||
private fun fail(run: Run, guidance: String) {
|
||||
private fun fail(run: Run, guidance: String, reason: String) {
|
||||
// Prevent another scheduled frame from running before main unbinds the camera.
|
||||
run.active = false
|
||||
main.post {
|
||||
if (!released && current === run) {
|
||||
DebugLogUpload.log("error", "camera failure=$reason")
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
onState(ExpressionUiState(ExpressionStatus.UNAVAILABLE, guidance = guidance))
|
||||
|
||||
Reference in New Issue
Block a user