fix: fence voice turns and playback; add opt-in face context
This commit is contained in:
+2
-2
@@ -45,8 +45,8 @@ android {
|
||||
applicationId 'com.gorios.lanvoice'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 6
|
||||
versionName '0.3.3'
|
||||
versionCode 7
|
||||
versionName '0.4.0'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.gorios.lanvoice
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.media.AudioManager
|
||||
import android.os.Bundle
|
||||
import android.security.NetworkSecurityPolicy
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -10,7 +11,6 @@ import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.gorios.lanvoice.audio.AecAvailability
|
||||
import com.gorios.lanvoice.audio.AudioOutputGate
|
||||
import com.gorios.lanvoice.audio.VoicePhase
|
||||
import com.gorios.lanvoice.audio.VoiceSession
|
||||
import com.gorios.lanvoice.audio.VoiceUiState
|
||||
@@ -59,6 +60,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var reportResult by mutableStateOf<String?>(null)
|
||||
private var appVersion = "unknown"
|
||||
private lateinit var session: VoiceSession
|
||||
private lateinit var audioOutput: AudioOutputGate
|
||||
private var shareFace by mutableStateOf(false)
|
||||
private var pendingStart = false
|
||||
private var expressionState by mutableStateOf(ExpressionUiState())
|
||||
private lateinit var expressions: ExpressionController
|
||||
@@ -82,6 +85,8 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown"
|
||||
volumeControlStream = AudioManager.STREAM_MUSIC
|
||||
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
|
||||
DebugLogUpload.appLaunch(
|
||||
appVersion,
|
||||
NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"),
|
||||
@@ -90,12 +95,16 @@ class MainActivity : ComponentActivity() {
|
||||
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
|
||||
onState = { state = it; startPendingVoice() },
|
||||
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) },
|
||||
onPreparePlayback = audioOutput::prepare,
|
||||
onVoiceStopped = audioOutput::release,
|
||||
)
|
||||
expressions = ExpressionController(this, this) { expressionState = it }
|
||||
expressions = ExpressionController(this, this,
|
||||
onState = { expressionState = it }, onFaceCue = session::observeFace)
|
||||
setContent {
|
||||
Home(
|
||||
state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions,
|
||||
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult,
|
||||
shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +205,7 @@ fun Home(
|
||||
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
|
||||
connectionLogs: List<String> = emptyList(),
|
||||
onSendReport: () -> Unit = {}, reportSending: Boolean = false, reportResult: String? = null,
|
||||
shareFace: Boolean = false, onShareFace: (Boolean) -> Unit = {},
|
||||
) {
|
||||
val gold = Color(0xFFE8C884)
|
||||
val muted = Color(0xFF9CA3AF)
|
||||
@@ -208,9 +218,13 @@ fun Home(
|
||||
delay(1_000L)
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp).verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp),
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
@@ -240,17 +254,10 @@ fun Home(
|
||||
modifier = Modifier.padding(top = 6.dp).heightIn(max = 54.dp).verticalScroll(logScroll),
|
||||
)
|
||||
}
|
||||
ExpressionControls(expressionState, onToggleExpressions)
|
||||
ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace)
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.Center).padding(bottom = 180.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text("声伴", color = gold, fontSize = 44.sp)
|
||||
Text("角色与音色由服务端决定", color = muted, modifier = Modifier.padding(top = 16.dp))
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 24.dp),
|
||||
modifier = Modifier.padding(top = 24.dp, bottom = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
|
||||
@@ -15,6 +15,11 @@ class AudioCapture {
|
||||
var recorder: AudioRecord? = null
|
||||
}
|
||||
|
||||
// A replacement run must not initialize a second microphone before the old
|
||||
// worker releases its AudioRecord/AEC (turn boundaries can arrive back-to-back).
|
||||
private val worker = java.util.concurrent.Executors.newSingleThreadExecutor { task ->
|
||||
Thread(task, "lan-voice-capture").apply { isDaemon = true }
|
||||
}
|
||||
private val lock = Any()
|
||||
private var current: Run? = null
|
||||
|
||||
@@ -32,10 +37,7 @@ class AudioCapture {
|
||||
stop()
|
||||
val run = Run()
|
||||
synchronized(lock) { current = run }
|
||||
Thread({ record(run, onFrame, onError, onDiagnostic) }, "lan-voice-capture").apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) }
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
@@ -48,6 +50,11 @@ class AudioCapture {
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stop()
|
||||
worker.shutdown()
|
||||
}
|
||||
|
||||
private fun record(
|
||||
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
|
||||
onDiagnostic: (String) -> Unit,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.gorios.lanvoice.audio
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
|
||||
/** Respect system routing/volume; never silently raise volume or force a speaker during a call. */
|
||||
class AudioOutputGate(context: Context, onFocusLost: () -> Unit) {
|
||||
private val manager = context.getSystemService(AudioManager::class.java)
|
||||
private var held = false
|
||||
private val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
|
||||
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
|
||||
.setAcceptsDelayedFocusGain(false)
|
||||
.setOnAudioFocusChangeListener({ change ->
|
||||
if (held && change in setOf(AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
|
||||
onFocusLost()
|
||||
}
|
||||
}, Handler(Looper.getMainLooper()))
|
||||
.build()
|
||||
|
||||
fun prepare(): String? {
|
||||
if (manager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0 || manager.isStreamMute(AudioManager.STREAM_MUSIC)) {
|
||||
return "媒体音量为零,请调高手机媒体音量后重新开始"
|
||||
}
|
||||
if (!held) held = manager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
||||
return if (held) null else "系统暂未允许播放,请结束其他音频占用后重试"
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (held) { held = false; manager.abandonAudioFocusRequest(request) }
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioTrack
|
||||
import android.os.Process
|
||||
import android.os.SystemClock
|
||||
import com.gorios.lanvoice.net.DownlinkFrame
|
||||
import java.util.ArrayDeque
|
||||
|
||||
@@ -11,6 +12,7 @@ import java.util.ArrayDeque
|
||||
class AudioPlayback(
|
||||
private val onDrained: (turnId: Long, generation: Long) -> Unit,
|
||||
private val onError: (generation: Long, error: Exception) -> Unit,
|
||||
private val onProgress: (turnId: Long, generation: Long, message: String) -> Unit = { _, _, _ -> },
|
||||
) {
|
||||
private val lock = Object()
|
||||
private val queue = ArrayDeque<ByteArray>()
|
||||
@@ -20,6 +22,11 @@ class AudioPlayback(
|
||||
private var ended = false
|
||||
private var drained = false
|
||||
private var writtenSamples = 0L
|
||||
private var receivedFrames = 0L
|
||||
private var receivedBytes = 0L
|
||||
private var lastHead = 0L
|
||||
private var lastAdvanceMs = 0L
|
||||
private var lastReportMs = 0L
|
||||
private var track: AudioTrack? = null
|
||||
private var released = false
|
||||
|
||||
@@ -35,6 +42,8 @@ class AudioPlayback(
|
||||
if (released) return false
|
||||
if (turnId != frame.turnId) resetLocked(frame.turnId)
|
||||
if (ended || drained || queuedBytes + frame.pcm16.size > MAX_QUEUED_BYTES) return false
|
||||
receivedFrames++
|
||||
receivedBytes += frame.pcm16.size
|
||||
queue.addLast(frame.pcm16)
|
||||
queuedBytes += frame.pcm16.size
|
||||
lock.notifyAll()
|
||||
@@ -72,6 +81,11 @@ class AudioPlayback(
|
||||
queue.clear()
|
||||
queuedBytes = 0
|
||||
writtenSamples = 0
|
||||
receivedFrames = 0
|
||||
receivedBytes = 0
|
||||
lastHead = 0
|
||||
lastAdvanceMs = 0
|
||||
lastReportMs = 0
|
||||
track?.let {
|
||||
try { it.pause(); it.flush() } catch (_: IllegalStateException) { }
|
||||
}
|
||||
@@ -115,6 +129,19 @@ class AudioPlayback(
|
||||
}
|
||||
}
|
||||
|
||||
/** At most one numeric summary/second; a stalled native sink must not hang forever. */
|
||||
private fun progressLocked(id: Long, epoch: Long, device: AudioTrack, force: Boolean = false) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val head = device.playbackHeadPosition.toLong() and 0xffff_ffffL
|
||||
if (lastAdvanceMs == 0L || head != lastHead || writtenSamples <= head) lastAdvanceMs = now
|
||||
lastHead = head
|
||||
check(writtenSamples <= head || now - lastAdvanceMs < 10_000) { "AudioTrack playback head stalled" }
|
||||
if (force || now - lastReportMs >= 1_000 || lastReportMs == 0L) {
|
||||
lastReportMs = now
|
||||
onProgress(id, epoch, "frames=$receivedFrames bytes=$receivedBytes written=$writtenSamples head=$head queued=$queuedBytes underruns=${device.underrunCount} ended=$ended")
|
||||
}
|
||||
}
|
||||
|
||||
private fun play() {
|
||||
try {
|
||||
try { Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO) } catch (_: SecurityException) { }
|
||||
@@ -136,15 +163,24 @@ class AudioPlayback(
|
||||
if (chunk != null) {
|
||||
val device = acquireTrack(epoch) ?: continue
|
||||
var offset = 0
|
||||
var lastWriteMs = SystemClock.elapsedRealtime()
|
||||
while (offset < chunk.size) {
|
||||
val written = synchronized(lock) {
|
||||
if (released || generation != epoch) null else
|
||||
device.write(chunk, offset, chunk.size - offset, AudioTrack.WRITE_NON_BLOCKING)
|
||||
.also { if (it > 0) writtenSamples += it / 2 }
|
||||
.also {
|
||||
check(it <= chunk.size - offset && it % 2 == 0) { "Invalid AudioTrack write count" }
|
||||
if (it > 0) writtenSamples += it / 2
|
||||
progressLocked(id, epoch, device)
|
||||
}
|
||||
} ?: break
|
||||
check(written >= 0) { "AudioTrack write failed: $written" }
|
||||
offset += written
|
||||
if (written == 0) Thread.sleep(4)
|
||||
if (written > 0) lastWriteMs = SystemClock.elapsedRealtime()
|
||||
else {
|
||||
check(SystemClock.elapsedRealtime() - lastWriteMs < 10_000) { "AudioTrack write stalled" }
|
||||
Thread.sleep(4)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val finished = synchronized(lock) {
|
||||
@@ -161,9 +197,11 @@ class AudioPlayback(
|
||||
check(written >= 0) { "AudioTrack tail write failed: $written" }
|
||||
writtenSamples += written / 2
|
||||
}
|
||||
if (device != null) progressLocked(id, epoch, device)
|
||||
val played = device?.playbackHeadPosition?.toLong()?.and(0xffff_ffffL) ?: 0L
|
||||
val primed = device == null || writtenSamples == 0L || writtenSamples >= device.bufferSizeInFrames
|
||||
if (primed && played >= writtenSamples) {
|
||||
if (device != null) progressLocked(id, epoch, device, force = true)
|
||||
device?.pause()
|
||||
drained = true
|
||||
true
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.gorios.lanvoice.audio
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import com.gorios.lanvoice.net.ConnectionStatus
|
||||
import com.gorios.lanvoice.net.DialogueClient
|
||||
@@ -9,6 +10,8 @@ import com.gorios.lanvoice.net.DebugLogUpload
|
||||
import com.gorios.lanvoice.net.DownlinkFrame
|
||||
import com.gorios.lanvoice.net.EventKind
|
||||
import com.gorios.lanvoice.net.ServerEvent
|
||||
import com.gorios.lanvoice.expression.FaceCue
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
|
||||
|
||||
@@ -24,6 +27,8 @@ data class VoiceUiState(
|
||||
class VoiceSession(
|
||||
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
|
||||
private val onConnectionLog: (String) -> Unit = {},
|
||||
private val onPreparePlayback: () -> String? = { null },
|
||||
private val onVoiceStopped: () -> Unit = {},
|
||||
) {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var state = VoiceUiState()
|
||||
@@ -37,11 +42,29 @@ class VoiceSession(
|
||||
private val retiredTurns = mutableSetOf<Long>()
|
||||
private var blockedTurn: Long? = null
|
||||
private var sequence = 1L
|
||||
private var preparedPlaybackTurn: Long? = null
|
||||
private var faceSharing = false
|
||||
private var faceSupported = false
|
||||
private var faceCue = FaceCueObservation()
|
||||
private var faceSent = false
|
||||
private val faceTick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!faceSharing || released) return
|
||||
if (isActive() && faceSupported && hasTurn) {
|
||||
val age = SystemClock.elapsedRealtime() - faceCue.observedAtMs
|
||||
if (dialogue.sendFaceCue(currentTurn, faceCue, age)) {
|
||||
faceSent = faceCue.cue != FaceCue.UNKNOWN && age in 0..3_000
|
||||
}
|
||||
}
|
||||
main.postDelayed(this, 1_000L)
|
||||
}
|
||||
}
|
||||
private val capture = AudioCapture()
|
||||
private val playback: AudioPlayback = AudioPlayback(
|
||||
onDrained = { turn, epoch ->
|
||||
main.post {
|
||||
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
|
||||
diagnostic("playback drained turn=$turn")
|
||||
if (dialogue.playbackDrained(turn)) {
|
||||
update(state.copy(phase = VoicePhase.LISTENING))
|
||||
startCapture()
|
||||
@@ -49,6 +72,11 @@ class VoiceSession(
|
||||
}
|
||||
}
|
||||
},
|
||||
onProgress = { turn, epoch, message ->
|
||||
main.post {
|
||||
if (playbackIsCurrent(turn, epoch)) diagnostic("playback turn=$turn $message")
|
||||
}
|
||||
},
|
||||
onError = { epoch, error ->
|
||||
main.post {
|
||||
if (isActive() && playbackIsCurrent(epoch)) failAudio("无法播放音频,请重新开始语音对话", error)
|
||||
@@ -83,6 +111,7 @@ class VoiceSession(
|
||||
|
||||
fun background(keepConnectionForPermission: Boolean = false, showDisconnectReason: Boolean = false) {
|
||||
checkMainThread()
|
||||
clearFaceContext()
|
||||
foreground = false
|
||||
stopVoice(sendControls = false)
|
||||
backgroundTimeout?.let { main.removeCallbacks(it) }
|
||||
@@ -109,6 +138,8 @@ class VoiceSession(
|
||||
if (released) return
|
||||
background()
|
||||
released = true
|
||||
main.removeCallbacks(faceTick)
|
||||
capture.release()
|
||||
playback.release()
|
||||
dialogue.release()
|
||||
}
|
||||
@@ -128,6 +159,9 @@ class VoiceSession(
|
||||
val wasActive = state.voiceActive
|
||||
stopCapture()
|
||||
playback.interrupt()
|
||||
preparedPlaybackTurn = null
|
||||
clearFaceContext()
|
||||
onVoiceStopped()
|
||||
blockedTurn = currentTurn
|
||||
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE))
|
||||
if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) {
|
||||
@@ -152,9 +186,44 @@ class VoiceSession(
|
||||
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
|
||||
}
|
||||
|
||||
fun outputUnavailable(message: String) {
|
||||
checkMainThread()
|
||||
if (state.voiceActive) {
|
||||
stopVoice()
|
||||
update(state.copy(guidance = message))
|
||||
}
|
||||
}
|
||||
|
||||
fun setFaceSharing(enabled: Boolean) {
|
||||
checkMainThread()
|
||||
main.removeCallbacks(faceTick)
|
||||
if (!enabled) clearFaceContext()
|
||||
faceSharing = enabled
|
||||
if (enabled && !released) main.post(faceTick)
|
||||
}
|
||||
|
||||
fun observeFace(observation: FaceCueObservation) {
|
||||
checkMainThread()
|
||||
if (observation.cue == FaceCue.UNKNOWN) clearFaceContext()
|
||||
faceCue = observation
|
||||
}
|
||||
|
||||
private fun clearFaceContext() {
|
||||
if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) {
|
||||
dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0)
|
||||
}
|
||||
faceSent = false
|
||||
faceCue = FaceCueObservation()
|
||||
}
|
||||
|
||||
private fun onConnection(connection: ConnectionStatus, reason: String) {
|
||||
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
|
||||
if (connection != ConnectionStatus.CONNECTED) {
|
||||
faceSupported = false
|
||||
faceSent = false
|
||||
faceCue = FaceCueObservation()
|
||||
preparedPlaybackTurn = null
|
||||
onVoiceStopped()
|
||||
stopCapture()
|
||||
playback.interrupt()
|
||||
currentTurn = 0
|
||||
@@ -177,13 +246,14 @@ class VoiceSession(
|
||||
if (!active || capturing) return
|
||||
capturing = true
|
||||
val epoch = ++captureEpoch
|
||||
val captureTurn = currentTurn
|
||||
diagnostic("capture start epoch=$epoch")
|
||||
try {
|
||||
capture.start(
|
||||
onFrame = { pcm ->
|
||||
main.post {
|
||||
if (epoch == captureEpoch && capturing && isActive()) {
|
||||
if (dialogue.sendAudio(pcm, currentTurn, sequence)) {
|
||||
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive()) {
|
||||
if (dialogue.sendAudio(pcm, captureTurn, sequence)) {
|
||||
sequence = (sequence + 1) and UINT32_MASK
|
||||
}
|
||||
}
|
||||
@@ -228,6 +298,7 @@ class VoiceSession(
|
||||
if (turn != null && !acceptTurn(turn)) return
|
||||
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
|
||||
when (event.kind) {
|
||||
EventKind.HELLO -> faceSupported = event.payload.optInt("context_face_cue_version", 0) == 1
|
||||
EventKind.LISTEN -> {
|
||||
val active = isActive()
|
||||
diagnostic("LISTEN action=${if (action in setOf("start", "stop")) action else "other"} active=$active blockedTurn=$blockedTurn")
|
||||
@@ -241,6 +312,10 @@ class VoiceSession(
|
||||
stopCapture()
|
||||
update(state.copy(phase = VoicePhase.RECOGNIZING))
|
||||
}
|
||||
"resumed" -> {
|
||||
update(state.copy(phase = VoicePhase.LISTENING))
|
||||
startCapture()
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind.VAD -> if (isActive()) {
|
||||
@@ -255,15 +330,23 @@ class VoiceSession(
|
||||
update(state.copy(phase = VoicePhase.THINKING))
|
||||
}
|
||||
EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) {
|
||||
playback.beginTurn(currentTurn)
|
||||
update(state.copy(phase = VoicePhase.ANSWERING))
|
||||
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
|
||||
// The gateway sends start BEFORE LLM generation and also tts.metrics.
|
||||
// Only received PCM means there is an answer to play.
|
||||
when (action) {
|
||||
"start" -> playback.beginTurn(currentTurn)
|
||||
"stop", "done", "end" -> {
|
||||
if (preparedPlaybackTurn == currentTurn) playback.endTurn(currentTurn)
|
||||
else failAudio("本轮未收到可播放音频,请重新开始", IllegalStateException("TTS ended without accepted PCM"))
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind.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 listenReset = event.payload.optString("reason") == "listen_start"
|
||||
blockedTurn = if (listenReset) null else oldTurn
|
||||
val reason = event.payload.optString("reason")
|
||||
val listenReset = reason == "listen_start"
|
||||
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort")
|
||||
blockedTurn = if (announcesNewTurn) null else oldTurn
|
||||
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
|
||||
playback.interrupt()
|
||||
if (isActive()) {
|
||||
@@ -283,6 +366,11 @@ class VoiceSession(
|
||||
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
|
||||
if (!isActive() || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
|
||||
blockedTurn == frame.turnId) return
|
||||
if (preparedPlaybackTurn != frame.turnId) {
|
||||
val failure = onPreparePlayback()
|
||||
if (failure != null) { outputUnavailable(failure); return }
|
||||
preparedPlaybackTurn = frame.turnId
|
||||
}
|
||||
update(state.copy(phase = VoicePhase.ANSWERING))
|
||||
if (!playback.enqueue(frame)) {
|
||||
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
|
||||
@@ -297,12 +385,16 @@ class VoiceSession(
|
||||
}
|
||||
// IDs identify turns; do not assume the server allocates them in numeric order.
|
||||
if (!hasTurn || id != currentTurn) {
|
||||
val resumeCapture = capturing
|
||||
if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq.
|
||||
if (hasTurn) retiredTurns.add(currentTurn)
|
||||
playback.interrupt()
|
||||
preparedPlaybackTurn = null
|
||||
currentTurn = id
|
||||
hasTurn = true
|
||||
sequence = 1
|
||||
if (blockedTurn != id) blockedTurn = null
|
||||
if (resumeCapture) startCapture()
|
||||
}
|
||||
if (logDecision) diagnostic("acceptTurn $before accepted=true nextTurn=$currentTurn nextBlocked=$blockedTurn retiredNow=${retiredTurns.size}")
|
||||
return true
|
||||
|
||||
@@ -22,11 +22,12 @@ import com.google.mediapipe.tasks.vision.facelandmarker.FaceLandmarker
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Independent local feature. It never references net/audio, writes user data or opens a network. */
|
||||
/** Local analyzer. Only enum observations leave this feature; images/coefficients never do. */
|
||||
class ExpressionController(
|
||||
context: Context,
|
||||
private val lifecycleOwner: LifecycleOwner,
|
||||
private val onState: (ExpressionUiState) -> Unit,
|
||||
private val onFaceCue: (FaceCueObservation) -> Unit = {},
|
||||
) {
|
||||
private class Run {
|
||||
@Volatile var active = true
|
||||
@@ -34,6 +35,7 @@ class ExpressionController(
|
||||
Thread(task, "lan-voice-expression").apply { isDaemon = true }
|
||||
}
|
||||
val rules = ExpressionRules()
|
||||
val faceRules = FaceCueRules()
|
||||
var landmarker: FaceLandmarker? = null // Accessed only on this run's executor.
|
||||
var analysis: ImageAnalysis? = null // Accessed only on main.
|
||||
var provider: ProcessCameraProvider? = null // Accessed only on main.
|
||||
@@ -65,7 +67,7 @@ class ExpressionController(
|
||||
val options = FaceLandmarker.FaceLandmarkerOptions.builder()
|
||||
.setBaseOptions(base) // Default delegate is CPU; no GPU/context requirements.
|
||||
.setRunningMode(RunningMode.VIDEO)
|
||||
.setNumFaces(1)
|
||||
.setNumFaces(2) // Multiple faces must produce unknown for dialogue context.
|
||||
.setMinFaceDetectionConfidence(.5f)
|
||||
.setMinFacePresenceConfidence(.5f)
|
||||
.setMinTrackingConfidence(.5f)
|
||||
@@ -85,12 +87,14 @@ class ExpressionController(
|
||||
fun stop() {
|
||||
checkMainThread()
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
if (!released) onState(ExpressionUiState())
|
||||
}
|
||||
|
||||
fun permissionDenied() {
|
||||
checkMainThread()
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
if (!released) onState(ExpressionUiState(guidance =
|
||||
"摄像头权限未授予。可在系统应用权限中开启,语音功能仍可使用。"))
|
||||
}
|
||||
@@ -98,6 +102,7 @@ class ExpressionController(
|
||||
fun release() {
|
||||
checkMainThread()
|
||||
if (released) return
|
||||
onFaceCue(FaceCueObservation())
|
||||
released = true
|
||||
stopCurrent()
|
||||
}
|
||||
@@ -159,6 +164,16 @@ class ExpressionController(
|
||||
FaceObservation(blendshapes, transform?.let(HeadPose::fromMatrix))
|
||||
}
|
||||
val visible = ExpressionRules.visible(run.rules.evaluate(observation, now))
|
||||
val landmarks = result.faceLandmarks().singleOrNull()
|
||||
val pose = observation?.pose
|
||||
// Conservative framing/pose checks, not a calibrated quality/confidence score.
|
||||
val quality = landmarks != null && landmarks.isNotEmpty() && pose != null &&
|
||||
kotlin.math.abs(pose.yaw) <= 30 && kotlin.math.abs(pose.pitch) <= 25 && kotlin.math.abs(pose.roll) <= 25 &&
|
||||
landmarks.all { it.x().isFinite() && it.y().isFinite() && it.x() in 0f..1f && it.y() in 0f..1f } &&
|
||||
(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)
|
||||
main.post { if (isCurrent(run)) onFaceCue(faceCue) }
|
||||
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
|
||||
if (run.lastPublished != visible) {
|
||||
run.lastPublished = visible
|
||||
@@ -183,6 +198,7 @@ class ExpressionController(
|
||||
main.post {
|
||||
if (!released && current === run) {
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
onState(ExpressionUiState(ExpressionStatus.UNAVAILABLE, guidance = guidance))
|
||||
}
|
||||
}
|
||||
@@ -209,6 +225,7 @@ class ExpressionController(
|
||||
} finally {
|
||||
run.landmarker = null
|
||||
run.rules.reset()
|
||||
run.faceRules.reset()
|
||||
run.lastPublished = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -17,7 +18,10 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@Composable
|
||||
fun ExpressionControls(state: ExpressionUiState, onToggle: () -> Unit) {
|
||||
fun ExpressionControls(
|
||||
state: ExpressionUiState, onToggle: () -> Unit,
|
||||
shareFace: Boolean = false, onShareFace: (Boolean) -> Unit = {},
|
||||
) {
|
||||
val enabled = state.status == ExpressionStatus.STARTING || state.status == ExpressionStatus.ACTIVE
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -46,5 +50,12 @@ fun ExpressionControls(state: ExpressionUiState, onToggle: () -> Unit) {
|
||||
"表情线索仅供参考,不代表真实情绪",
|
||||
fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("将表情线索用于对话", color = Color(0xFF9CA3AF), fontSize = 12.sp)
|
||||
Switch(checked = shareFace, onCheckedChange = onShareFace)
|
||||
}
|
||||
if (shareFace && state.status != ExpressionStatus.ACTIVE) {
|
||||
Text("摄像头关闭时不发送线索", color = Color(0xFF9CA3AF), fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
enum class FaceCue(val wire: String) { UNKNOWN("unknown"), SMILING("smiling"), BROW_FURROWED("brow_furrowed") }
|
||||
|
||||
/** Rule intensity is an uncalibrated coefficient, never a probability or emotional state. */
|
||||
data class FaceCueObservation(
|
||||
val cue: FaceCue = FaceCue.UNKNOWN,
|
||||
val intensity: Float = 0f,
|
||||
val durationMs: Long = 0,
|
||||
val observedAtMs: Long = 0,
|
||||
)
|
||||
|
||||
class FaceCueRules {
|
||||
private var previous: Long? = null
|
||||
private var candidate = FaceCue.UNKNOWN
|
||||
private var since = 0L
|
||||
private var active = false
|
||||
|
||||
fun reset() { previous = null; candidate = FaceCue.UNKNOWN; active = false; since = 0 }
|
||||
|
||||
fun evaluate(observation: FaceObservation?, faceCount: Int, quality: Boolean, nowMs: Long): FaceCueObservation {
|
||||
val last = previous
|
||||
if (last != null && (nowMs <= last || nowMs - last > 500)) reset()
|
||||
previous = nowMs
|
||||
fun unknown(): FaceCueObservation {
|
||||
candidate = FaceCue.UNKNOWN; active = false; since = nowMs
|
||||
return FaceCueObservation(observedAtMs = nowMs)
|
||||
}
|
||||
if (faceCount != 1 || !quality || observation == null) return unknown()
|
||||
val names = listOf("mouthSmileLeft", "mouthSmileRight", "browDownLeft", "browDownRight")
|
||||
val scores = names.map { observation.blendshapes[it] ?: return unknown() }
|
||||
if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown()
|
||||
val smile = minOf(scores[0], scores[1])
|
||||
val brow = minOf(scores[2], scores[3])
|
||||
val smiling = smile >= if (active && candidate == FaceCue.SMILING) .60f else .75f
|
||||
val furrowed = brow >= if (active && candidate == FaceCue.BROW_FURROWED) .50f else .65f
|
||||
if (smiling == furrowed) return unknown() // Conflict or no clear cue.
|
||||
val next = if (smiling) FaceCue.SMILING else FaceCue.BROW_FURROWED
|
||||
if (candidate != next) { candidate = next; since = nowMs; active = false }
|
||||
val duration = (nowMs - since).coerceIn(0, 10_000)
|
||||
if (duration < 800) return FaceCueObservation(observedAtMs = nowMs)
|
||||
active = true
|
||||
return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import java.security.cert.CertificateException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.net.ssl.SSLException
|
||||
import javax.net.ssl.SSLPeerUnverifiedException
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
enum class ConnectionStatus { CONNECTING, CONNECTED, DISCONNECTED, BUSY }
|
||||
|
||||
@@ -215,6 +216,15 @@ class DialogueClient(
|
||||
|
||||
fun playbackDrained(turnId: Long): Boolean = send(DialogueProtocol.playbackDrained(turnId))
|
||||
|
||||
/** Optional context is best effort and never tears down the audio connection. */
|
||||
fun sendFaceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): Boolean {
|
||||
checkMainThread()
|
||||
val current = socket ?: return false
|
||||
if (!ready || released || current.queueSize() > 64 * 1024) return false
|
||||
return try { current.send(DialogueProtocol.faceCue(turnId, observation, ageMs)) }
|
||||
catch (_: Exception) { false }
|
||||
}
|
||||
|
||||
fun sendAudio(pcm16: ByteArray, turnId: Long, sequence: Long): Boolean {
|
||||
checkMainThread()
|
||||
val current = socket ?: return false
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.gorios.lanvoice.net
|
||||
import org.json.JSONObject
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import com.gorios.lanvoice.expression.FaceCue
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
/** Wire payloads stay intact: event-specific fields are consumed by later milestones. */
|
||||
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
|
||||
@@ -49,6 +51,17 @@ object DialogueProtocol {
|
||||
fun playbackDrained(turnId: Long): String = JSONObject()
|
||||
.put("type", "playback.drained").put("turn_id", turnId).toString()
|
||||
|
||||
fun faceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): String {
|
||||
require(turnId in 0..0xffff_ffffL)
|
||||
val valid = observation.cue != FaceCue.UNKNOWN && ageMs in 0..3_000 &&
|
||||
observation.intensity.isFinite() && observation.intensity in .5f..1f && observation.durationMs in 800..10_000
|
||||
return JSONObject().put("type", "context.face_cue").put("version", 1).put("turn_id", turnId)
|
||||
.put("valid", valid).put("cue", if (valid) observation.cue.wire else "unknown")
|
||||
.put("intensity", if (valid) observation.intensity.toDouble() else 0.0)
|
||||
.put("duration_ms", if (valid) observation.durationMs else 0)
|
||||
.put("age_ms", if (valid) ageMs else 0).toString()
|
||||
}
|
||||
|
||||
fun uplink(pcm16: ByteArray, turnId: Long, sequence: Long): ByteArray {
|
||||
require(pcm16.size == UPLINK_PCM_BYTES) { "Expected 20 ms of PCM16@16k" }
|
||||
require(turnId in 0..0xffff_ffffL && sequence in 0..0xffff_ffffL) {
|
||||
|
||||
Reference in New Issue
Block a user