feat: add neutral avatar video call MVP in Android 0.6.0
This commit is contained in:
@@ -9,36 +9,9 @@ import android.security.NetworkSecurityPolicy
|
||||
import androidx.activity.ComponentActivity
|
||||
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.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
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
|
||||
@@ -49,10 +22,11 @@ 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
|
||||
import com.gorios.lanvoice.expression.ExpressionUiState
|
||||
import kotlinx.coroutines.delay
|
||||
import com.gorios.lanvoice.avatar.AvatarPack
|
||||
import com.gorios.lanvoice.avatar.CallIntent
|
||||
import com.gorios.lanvoice.avatar.CallScreen
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private var state by mutableStateOf(VoiceUiState())
|
||||
@@ -63,7 +37,10 @@ class MainActivity : ComponentActivity() {
|
||||
private lateinit var session: VoiceSession
|
||||
private lateinit var audioOutput: AudioOutputGate
|
||||
private var shareFace by mutableStateOf(false)
|
||||
private var pendingStart = false
|
||||
private val callIntent = CallIntent()
|
||||
private var dialing by mutableStateOf(false)
|
||||
private var callFailure by mutableStateOf(false)
|
||||
private var avatarPack: AvatarPack? = null
|
||||
private var expressionState by mutableStateOf(ExpressionUiState())
|
||||
private lateinit var expressions: ExpressionController
|
||||
private val cameraGate = CameraPermissionGate()
|
||||
@@ -74,9 +51,11 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground")
|
||||
if (granted) startPendingVoice()
|
||||
else {
|
||||
pendingStart = false
|
||||
val wanted = callIntent.pending
|
||||
callIntent.permissionResult(granted)
|
||||
if (granted && wanted) { session.dial(); startPendingVoice() }
|
||||
else if (!granted && wanted) {
|
||||
dialing = false
|
||||
session.permissionDenied()
|
||||
}
|
||||
}
|
||||
@@ -90,9 +69,19 @@ class MainActivity : ComponentActivity() {
|
||||
appVersion,
|
||||
NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"),
|
||||
)
|
||||
avatarPack = AvatarPack.load(this)
|
||||
session = VoiceSession(
|
||||
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
|
||||
onState = { state = it; startPendingVoice() },
|
||||
onState = {
|
||||
val ended = state.voiceActive && !it.voiceActive
|
||||
state = it
|
||||
if (ended && inForeground && it.connection != ConnectionStatus.CONNECTED) callFailure = true
|
||||
if (dialing && !callIntent.permissionPending && it.connection in setOf(ConnectionStatus.DISCONNECTED, ConnectionStatus.BUSY)) {
|
||||
callIntent.cancel(); dialing = false; callFailure = true
|
||||
}
|
||||
if (ended && !cameraGate.permissionPending && ::expressions.isInitialized) closeCamera()
|
||||
startPendingVoice()
|
||||
},
|
||||
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) },
|
||||
onPreparePlayback = audioOutput::prepare,
|
||||
onVoiceStopped = audioOutput::release,
|
||||
@@ -103,10 +92,11 @@ class MainActivity : ComponentActivity() {
|
||||
expressionState = it
|
||||
}, onFaceCue = session::observeFace)
|
||||
setContent {
|
||||
Home(
|
||||
state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions,
|
||||
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult,
|
||||
shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
|
||||
CallScreen(
|
||||
state, dialing, callFailure, avatarPack, ::dialCall, ::hangUp,
|
||||
{ session.setMicrophoneMuted(!state.microphoneMuted) }, ::toggleExpressions,
|
||||
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
|
||||
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -147,6 +137,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun toggleExpressions() {
|
||||
if (!state.voiceActive) return
|
||||
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}")
|
||||
@@ -160,7 +151,7 @@ class MainActivity : ComponentActivity() {
|
||||
cameraPermission.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
CameraPermissionGate.Action.START -> {
|
||||
if (inForeground) {
|
||||
if (inForeground && state.voiceActive) {
|
||||
DebugLogUpload.log("audio", "camera start_attempt")
|
||||
expressions.start()
|
||||
}
|
||||
@@ -174,24 +165,35 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun toggleVoice() {
|
||||
DebugLogUpload.log("audio", "voice button active=${state.voiceActive}")
|
||||
if (state.voiceActive) {
|
||||
pendingStart = false
|
||||
session.stopVoice()
|
||||
} else if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
session.startVoice()
|
||||
} else if (!pendingStart) {
|
||||
pendingStart = true
|
||||
DebugLogUpload.log("audio", "microphone permission requested")
|
||||
microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
private fun dialCall() {
|
||||
val granted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
if (!callIntent.dial(state.voiceActive, granted)) return
|
||||
dialing = true
|
||||
callFailure = false
|
||||
if (granted) { session.dial(); startPendingVoice() }
|
||||
else microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
|
||||
private fun closeCamera() {
|
||||
cameraGate.cancel()
|
||||
expressions.stop()
|
||||
shareFace = false
|
||||
session.setFaceSharing(false)
|
||||
}
|
||||
|
||||
private fun hangUp() {
|
||||
callIntent.cancel()
|
||||
dialing = false
|
||||
callFailure = false
|
||||
closeCamera()
|
||||
session.hangUp()
|
||||
}
|
||||
|
||||
private fun startPendingVoice() {
|
||||
if (pendingStart && inForeground && state.connection == ConnectionStatus.CONNECTED &&
|
||||
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
pendingStart = false
|
||||
if (!::session.isInitialized) return
|
||||
val granted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
if (callIntent.consumeStart(inForeground, state.connection == ConnectionStatus.CONNECTED, granted)) {
|
||||
dialing = false
|
||||
session.startVoice()
|
||||
}
|
||||
}
|
||||
@@ -207,12 +209,16 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onStop() {
|
||||
inForeground = false
|
||||
val permissionInFlight = pendingStart || cameraGate.permissionPending
|
||||
val permissionInFlight = callIntent.permissionPending || cameraGate.permissionPending
|
||||
if (cameraGate.permissionPending) callIntent.resumeAfterCameraPermission(state.voiceActive)
|
||||
callIntent.background(preserveForPermission = permissionInFlight)
|
||||
dialing = callIntent.pending
|
||||
DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations")
|
||||
cameraGate.onBackground()
|
||||
shareFace = false
|
||||
session.setFaceSharing(false)
|
||||
DebugLogUpload.log("audio", "camera stop reason=background")
|
||||
expressions.stop()
|
||||
if (!permissionInFlight) pendingStart = false
|
||||
session.background(
|
||||
keepConnectionForPermission = permissionInFlight,
|
||||
showDisconnectReason = !permissionInFlight,
|
||||
@@ -229,100 +235,3 @@ class MainActivity : ComponentActivity() {
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun Home(
|
||||
state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit,
|
||||
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)
|
||||
val connected = state.connection == ConnectionStatus.CONNECTED
|
||||
val logScroll = rememberScrollState()
|
||||
LaunchedEffect(connectionLogs, logScroll.maxValue) { logScroll.scrollTo(logScroll.maxValue) }
|
||||
val uploadResult by produceState(initialValue = DebugLogUpload.lastResult) {
|
||||
while (true) {
|
||||
value = DebugLogUpload.lastResult
|
||||
delay(1_000L)
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp).verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = when (state.connection) {
|
||||
ConnectionStatus.CONNECTING -> "连接中"
|
||||
ConnectionStatus.DISCONNECTED -> "已断开"
|
||||
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
|
||||
ConnectionStatus.CONNECTED -> when (state.phase) {
|
||||
VoicePhase.IDLE -> "已连接"
|
||||
VoicePhase.LISTENING -> "听取中"
|
||||
VoicePhase.RECOGNIZING -> "识别中"
|
||||
VoicePhase.THINKING -> "思考中"
|
||||
VoicePhase.ANSWERING -> "回答中"
|
||||
}
|
||||
},
|
||||
color = if (connected) gold else muted,
|
||||
fontSize = 14.sp,
|
||||
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
|
||||
.padding(horizontal = 20.dp, vertical = 10.dp)
|
||||
)
|
||||
Text("调试日志已开启 · $uploadResult", color = muted, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))
|
||||
if (connectionLogs.isNotEmpty()) {
|
||||
Text(
|
||||
text = connectionLogs.takeLast(10).joinToString("\n"),
|
||||
color = muted, fontSize = 12.sp, textAlign = TextAlign.Center,
|
||||
lineHeight = 18.sp, softWrap = false, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(top = 6.dp).heightIn(max = 54.dp).verticalScroll(logScroll),
|
||||
)
|
||||
}
|
||||
ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace)
|
||||
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),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
state.guidance?.let {
|
||||
Text(it, color = gold, fontSize = 14.sp, textAlign = TextAlign.Center)
|
||||
}
|
||||
Button(
|
||||
onClick = onToggleVoice,
|
||||
enabled = connected,
|
||||
shape = CircleShape,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = gold, contentColor = Color(0xFF121220)),
|
||||
modifier = Modifier.size(140.dp),
|
||||
) {
|
||||
Text(if (state.voiceActive) "停止" else "开始\n语音对话", fontSize = 20.sp, textAlign = TextAlign.Center)
|
||||
}
|
||||
Button(onClick = onInterrupt, enabled = connected && state.voiceActive) {
|
||||
Text("打断")
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onSendReport, enabled = !reportSending) {
|
||||
Text(if (reportSending) "发送中…" else "发送诊断报告", color = muted, fontSize = 12.sp)
|
||||
}
|
||||
reportResult?.let { Text(it, color = muted, fontSize = 12.sp) }
|
||||
}
|
||||
Text(
|
||||
"AEC:" + when (state.aec) {
|
||||
AecAvailability.AVAILABLE -> "可用"
|
||||
AecAvailability.UNAVAILABLE -> "不可用"
|
||||
AecAvailability.UNKNOWN -> "未知"
|
||||
} + " · 实际消回声效果需真机验证",
|
||||
color = muted, fontSize = 12.sp, textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ 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 onActivity: (PlaybackActivity) -> Unit = {},
|
||||
) {
|
||||
private val lock = Object()
|
||||
private val queue = ArrayDeque<ByteArray>()
|
||||
@@ -29,6 +30,9 @@ class AudioPlayback(
|
||||
private var lastReportMs = 0L
|
||||
private var track: AudioTrack? = null
|
||||
private var released = false
|
||||
private val headCounter = PlaybackHead()
|
||||
private val activity = PcmActivityTimeline()
|
||||
private var audible = false
|
||||
|
||||
init {
|
||||
Thread(::play, "lan-voice-playback").apply { isDaemon = true; start() }
|
||||
@@ -41,7 +45,7 @@ class AudioPlayback(
|
||||
fun enqueue(frame: DownlinkFrame): Boolean = synchronized(lock) {
|
||||
if (released) return false
|
||||
if (turnId != frame.turnId) resetLocked(frame.turnId)
|
||||
if (ended || drained || queuedBytes + frame.pcm16.size > MAX_QUEUED_BYTES) return false
|
||||
if (ended || drained || frame.pcm16.size % 2 != 0 || queuedBytes + frame.pcm16.size > MAX_QUEUED_BYTES) return false
|
||||
receivedFrames++
|
||||
receivedBytes += frame.pcm16.size
|
||||
queue.addLast(frame.pcm16)
|
||||
@@ -86,6 +90,9 @@ class AudioPlayback(
|
||||
lastHead = 0
|
||||
lastAdvanceMs = 0
|
||||
lastReportMs = 0
|
||||
headCounter.reset()
|
||||
activity.reset()
|
||||
audible = false
|
||||
track?.let {
|
||||
try { it.pause(); it.flush() } catch (_: IllegalStateException) { }
|
||||
}
|
||||
@@ -132,9 +139,14 @@ 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
|
||||
val head = headCounter.read(device.playbackHeadPosition)
|
||||
if (lastAdvanceMs == 0L || head != lastHead || writtenSamples <= head) lastAdvanceMs = now
|
||||
lastHead = head
|
||||
val active = activity.sample(head, writtenSamples, now)
|
||||
if (active != audible) {
|
||||
audible = active
|
||||
onActivity(PlaybackActivity(id, epoch, active, head, writtenSamples))
|
||||
}
|
||||
check(writtenSamples <= head || now - lastAdvanceMs < 10_000) { "AudioTrack playback head stalled" }
|
||||
if (force || now - lastReportMs >= 1_000 || lastReportMs == 0L) {
|
||||
lastReportMs = now
|
||||
@@ -151,7 +163,19 @@ class AudioPlayback(
|
||||
val chunk: ByteArray?
|
||||
synchronized(lock) {
|
||||
while (!released && (turnId == null || (queue.isEmpty() && (!ended || drained)))) {
|
||||
lock.wait()
|
||||
if (turnId != null && !drained && track != null && writtenSamples > 0) {
|
||||
lock.wait(10)
|
||||
if (!released && turnId != null && !drained) {
|
||||
try { track?.let { progressLocked(checkNotNull(turnId), generation, it) } }
|
||||
catch (error: Exception) {
|
||||
val epochNow = generation
|
||||
track?.release(); track = null
|
||||
queue.clear(); queuedBytes = 0; writtenSamples = 0
|
||||
activity.reset(); audible = false
|
||||
onError(epochNow, error)
|
||||
}
|
||||
}
|
||||
} else lock.wait()
|
||||
}
|
||||
if (released) return
|
||||
epoch = generation
|
||||
@@ -162,6 +186,8 @@ class AudioPlayback(
|
||||
try {
|
||||
if (chunk != null) {
|
||||
val device = acquireTrack(epoch) ?: continue
|
||||
// Serialized metadata reset; work stays on the audio worker, never main.
|
||||
synchronized(lock) { if (generation == epoch) activity.append(chunk) }
|
||||
var offset = 0
|
||||
var lastWriteMs = SystemClock.elapsedRealtime()
|
||||
while (offset < chunk.size) {
|
||||
@@ -195,14 +221,20 @@ class AudioPlayback(
|
||||
val padding = ByteArray((device.bufferSizeInFrames - writtenSamples.toInt()) * 2)
|
||||
val written = device.write(padding, 0, padding.size, AudioTrack.WRITE_NON_BLOCKING)
|
||||
check(written >= 0) { "AudioTrack tail write failed: $written" }
|
||||
check(written % 2 == 0) { "Invalid AudioTrack tail count" }
|
||||
activity.append(padding, 0, written)
|
||||
writtenSamples += written / 2
|
||||
}
|
||||
if (device != null) progressLocked(id, epoch, device)
|
||||
val played = device?.playbackHeadPosition?.toLong()?.and(0xffff_ffffL) ?: 0L
|
||||
val played = lastHead
|
||||
val primed = device == null || writtenSamples == 0L || writtenSamples >= device.bufferSizeInFrames
|
||||
if (primed && played >= writtenSamples) {
|
||||
if (device != null) progressLocked(id, epoch, device, force = true)
|
||||
device?.pause()
|
||||
if (audible) {
|
||||
audible = false
|
||||
onActivity(PlaybackActivity(id, epoch, false, played, writtenSamples))
|
||||
}
|
||||
drained = true
|
||||
true
|
||||
} else false
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.gorios.lanvoice.audio
|
||||
|
||||
import java.util.ArrayDeque
|
||||
import kotlin.math.abs
|
||||
|
||||
data class PlaybackActivity(val turnId: Long, val generation: Long, val audible: Boolean,
|
||||
val playedSamples: Long, val writtenSamples: Long)
|
||||
|
||||
/** Unsigned native frame counter; reset only together with AudioTrack pause/flush. */
|
||||
class PlaybackHead {
|
||||
private var previous = 0L
|
||||
private var wraps = 0L
|
||||
fun read(raw: Int): Long {
|
||||
val value = raw.toLong() and 0xffff_ffffL
|
||||
if (value < previous && previous - value > 0x8000_0000L) wraps++
|
||||
previous = value
|
||||
return value + (wraps shl 32)
|
||||
}
|
||||
fun reset() { previous = 0; wraps = 0 }
|
||||
}
|
||||
|
||||
/** 20ms RMS/peak metadata, never PCM retained. Consumed only by actual playback head.
|
||||
* A bounded 120ms release bridges syllables and also closes on native underrun. */
|
||||
class PcmActivityTimeline(private val releaseMs: Long = 120, private val maxWindows: Int = 1600) {
|
||||
init { require(releaseMs in 80..150 && maxWindows > 0) }
|
||||
private data class Window(val start: Long, val end: Long, val active: Boolean)
|
||||
private val windows = ArrayDeque<Window>()
|
||||
private var analyzed = 0L
|
||||
private var count = 0
|
||||
private var squares = 0L
|
||||
private var peak = 0
|
||||
private var previousHead = 0L
|
||||
private var lastVoiceMs: Long? = null
|
||||
private fun active() = count > 0 && squares / count >= 180L * 180L && peak >= 600
|
||||
val retainedWindows: Int get() = windows.size
|
||||
|
||||
fun append(pcm: ByteArray, offset: Int = 0, size: Int = pcm.size - offset) {
|
||||
require(offset >= 0 && size >= 0 && offset + size <= pcm.size && size % 2 == 0)
|
||||
for (i in offset until offset + size step 2) {
|
||||
val value = ((pcm[i].toInt() and 255) or (pcm[i + 1].toInt() shl 8)).toShort().toInt()
|
||||
squares += value.toLong() * value; peak = maxOf(peak, abs(value)); count++; analyzed++
|
||||
if (count == 960) {
|
||||
check(windows.size < maxWindows) { "PCM activity metadata limit" }
|
||||
windows.addLast(Window(analyzed - count, analyzed, active()))
|
||||
count = 0; squares = 0; peak = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun sample(played: Long, written: Long, nowMs: Long): Boolean {
|
||||
val head = minOf(played, written)
|
||||
require(head >= previousHead)
|
||||
var voicedEnd: Long? = null
|
||||
for (w in windows) {
|
||||
if (w.start >= head) break
|
||||
if (w.active && w.end > previousHead) voicedEnd = minOf(w.end, head)
|
||||
}
|
||||
if (count > 0 && analyzed - count < head && analyzed > previousHead && active()) {
|
||||
voicedEnd = minOf(analyzed, head)
|
||||
}
|
||||
voicedEnd?.let { lastVoiceMs = nowMs - (head - it) * 1000 / 48_000 }
|
||||
previousHead = head
|
||||
while (windows.peekFirst()?.end?.let { it <= head } == true) windows.removeFirst()
|
||||
return lastVoiceMs?.let { nowMs - it < releaseMs } == true
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
windows.clear(); analyzed = 0; count = 0; squares = 0; peak = 0
|
||||
previousHead = 0; lastVoiceMs = null
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ data class VoiceUiState(
|
||||
val guidance: String? = null,
|
||||
val replyEmotion: ReplyEmotion = ReplyEmotion(),
|
||||
val previousReplyEmotion: ReplyEmotion? = null,
|
||||
val playbackActivity: PlaybackActivity? = null,
|
||||
val microphoneMuted: Boolean = false,
|
||||
) {
|
||||
val roleLabel: String get() = when {
|
||||
phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label
|
||||
@@ -95,6 +97,14 @@ class VoiceSession(
|
||||
if (isActive() && playbackIsCurrent(epoch)) failAudio("无法播放音频,请重新开始语音对话", error)
|
||||
}
|
||||
},
|
||||
onActivity = { activity ->
|
||||
main.post {
|
||||
if (isActive() && playbackIsCurrent(activity.turnId, activity.generation) &&
|
||||
currentTurn == activity.turnId && blockedTurn != activity.turnId && emotionEndedTurn != activity.turnId) {
|
||||
update(state.copy(playbackActivity = activity))
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
private val dialogue: DialogueClient = DialogueClient(
|
||||
host, port,
|
||||
@@ -163,7 +173,7 @@ class VoiceSession(
|
||||
DebugLogUpload.log("audio", "start_voice state=${state.connection.name.lowercase()} foreground=$foreground active=${state.voiceActive}")
|
||||
if (released || !foreground || state.connection != ConnectionStatus.CONNECTED || state.voiceActive) return
|
||||
if (!dialogue.listen(true)) return
|
||||
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null))
|
||||
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null, microphoneMuted = false))
|
||||
startCapture()
|
||||
}
|
||||
|
||||
@@ -177,13 +187,32 @@ class VoiceSession(
|
||||
clearFaceContext()
|
||||
onVoiceStopped()
|
||||
blockedTurn = currentTurn
|
||||
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion()))
|
||||
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion(), microphoneMuted = false))
|
||||
if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) {
|
||||
dialogue.listen(false)
|
||||
dialogue.abort(currentTurn)
|
||||
}
|
||||
}
|
||||
|
||||
fun dial() {
|
||||
checkMainThread()
|
||||
if (!released && foreground && !dialogue.hasActiveConnection()) dialogue.connect()
|
||||
}
|
||||
|
||||
fun hangUp() {
|
||||
checkMainThread()
|
||||
stopVoice()
|
||||
dialogue.disconnect("call_hangup")
|
||||
}
|
||||
|
||||
fun setMicrophoneMuted(muted: Boolean) {
|
||||
checkMainThread()
|
||||
if (!isActive() || state.microphoneMuted == muted) return
|
||||
update(state.copy(microphoneMuted = muted))
|
||||
if (muted) stopCapture()
|
||||
else if (state.phase == VoicePhase.LISTENING) startCapture()
|
||||
}
|
||||
|
||||
fun interrupt() {
|
||||
checkMainThread()
|
||||
if (!isActive()) return
|
||||
@@ -280,7 +309,7 @@ class VoiceSession(
|
||||
retiredTurns.clear()
|
||||
blockedTurn = null
|
||||
sequence = 1
|
||||
update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion()))
|
||||
update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion(), microphoneMuted = false))
|
||||
} else update(state.copy(
|
||||
connection = connection,
|
||||
// onStop runs while the screen is hidden. Keep the reason visible on
|
||||
@@ -292,7 +321,7 @@ class VoiceSession(
|
||||
private fun startCapture() {
|
||||
val active = isActive()
|
||||
diagnostic("startCapture active=$active capturing=$capturing")
|
||||
if (!active || capturing) return
|
||||
if (!active || capturing || state.microphoneMuted) return
|
||||
capturing = true
|
||||
val epoch = ++captureEpoch
|
||||
val captureTurn = currentTurn
|
||||
@@ -483,7 +512,7 @@ class VoiceSession(
|
||||
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(),
|
||||
update(state.copy(replyEmotion = ReplyEmotion(), playbackActivity = null,
|
||||
previousReplyEmotion = if (played) expression else state.previousReplyEmotion))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
import com.gorios.lanvoice.audio.PlaybackActivity
|
||||
import com.gorios.lanvoice.dialogue.ReplyEmotion
|
||||
import com.gorios.lanvoice.dialogue.RoleEmotion
|
||||
|
||||
enum class AvatarMode { WAITING, IDLE, TALK }
|
||||
data class AssetEmotion(val emotion: RoleEmotion = RoleEmotion.NEUTRAL, val intensity: Int = 0)
|
||||
data class AvatarSelection(val mode: AvatarMode, val requestedEmotion: ReplyEmotion,
|
||||
val resolvedAssetEmotion: AssetEmotion = AssetEmotion()) {
|
||||
val emotionFallback: Boolean get() = requestedEmotion.turnId != null &&
|
||||
(requestedEmotion.emotion != resolvedAssetEmotion.emotion || requestedEmotion.intensity != resolvedAssetEmotion.intensity)
|
||||
}
|
||||
|
||||
/** No timers, socket events or camera cues can turn on talking here. */
|
||||
class AvatarController {
|
||||
fun select(inCall: Boolean, requested: ReplyEmotion, activity: PlaybackActivity?): AvatarSelection =
|
||||
AvatarSelection(if (!inCall) AvatarMode.WAITING else if (activity?.audible == true &&
|
||||
(requested.turnId == null || requested.turnId == activity.turnId)) AvatarMode.TALK else AvatarMode.IDLE, requested)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Local APK paths only. Corrupt/missing pack never affects voice. Imported bytes are pinned. */
|
||||
data class AvatarPack(val idle: String, val talk: String, val fallback: String, val waiting: String) {
|
||||
companion object {
|
||||
private const val ROOT = "avatar/a01-v1/"
|
||||
fun load(context: Context): AvatarPack? = try {
|
||||
val raw = context.assets.open(ROOT + "manifest.json").use { it.readBytes() }
|
||||
check(sha(raw) == "ca817f1e538a5933beac4f3f4cda6367bf87a2d428b3307622c98842ae8679d1")
|
||||
val manifest = JSONObject(String(raw, Charsets.UTF_8))
|
||||
check(manifest.getInt("schemaVersion") == 1 && manifest.getString("identityId") == "a01")
|
||||
fun checked(row: JSONObject): String {
|
||||
val path = row.getString("path")
|
||||
check(path.matches(Regex("(?:videos|frames)/[a-zA-Z0-9_.-]+\\.(?:mp4|png)")))
|
||||
val bytes = context.assets.open(ROOT + path).use { it.readBytes() }
|
||||
check(bytes.size <= 8_000_000 && sha(bytes) == row.getString("sha256"))
|
||||
return ROOT + path
|
||||
}
|
||||
val rows = manifest.getJSONArray("assets")
|
||||
val paths = mutableMapOf<String, String>()
|
||||
for (i in 0 until rows.length()) {
|
||||
val row = rows.getJSONObject(i)
|
||||
check(row.getString("emotion") == "neutral" && row.getInt("intensity") == 0 &&
|
||||
row.getBoolean("loop") && !row.getBoolean("hasAudio"))
|
||||
val mode = row.getString("mode")
|
||||
check(mode in setOf("idle", "talk") && !paths.containsKey(mode))
|
||||
paths[mode] = checked(row)
|
||||
}
|
||||
val fallback = checked(manifest.getJSONObject("staticFallback"))
|
||||
val waiting = try {
|
||||
val extra = context.assets.open(ROOT + "call-avatar-manifest.json").use { it.readBytes() }
|
||||
check(sha(extra) == "3b6918cdc955f6d51e8910cf7a0067f4dedb19d28accbb5525f15876e6ad4d8c")
|
||||
val supplement = JSONObject(String(extra, Charsets.UTF_8))
|
||||
check(supplement.getString("identityId") == "a01" && supplement.getString("basePackId") == manifest.getString("packId"))
|
||||
checked(supplement.getJSONObject("waiting"))
|
||||
} catch (_: Exception) { fallback }
|
||||
AvatarPack(checkNotNull(paths["idle"]), checkNotNull(paths["talk"]), fallback, waiting)
|
||||
} catch (_: Exception) { null }
|
||||
private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes)
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.MediaPlayer
|
||||
import android.os.SystemClock
|
||||
import android.view.Surface
|
||||
import android.view.TextureView
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||
|
||||
/** Two independent muted loops. First-frame callbacks reveal only the current desired mode.
|
||||
* No seeks or player allocation on syllables; lifecycle release invalidates all callbacks. */
|
||||
class AvatarVideoView(context: Context, private val pack: AvatarPack?) : FrameLayout(context) {
|
||||
private data class Clip(val mode: AvatarMode, val path: String, val view: TextureView,
|
||||
var player: MediaPlayer? = null, var surface: Surface? = null, var ready: Boolean = false)
|
||||
private val still = ImageView(context).apply { scaleType = ImageView.ScaleType.FIT_CENTER }
|
||||
private val clips = mutableListOf<Clip>()
|
||||
private var desired = AvatarMode.WAITING
|
||||
private var active = false
|
||||
private var epoch = 0L
|
||||
private var failed = false
|
||||
private var lastLog = -10_000L
|
||||
private var displayedStill: String? = null
|
||||
private var idleFirstMs: Long? = null
|
||||
private var talkFirstMs: Long? = null
|
||||
init {
|
||||
addView(still, LayoutParams(-1, -1))
|
||||
pack?.let {
|
||||
for ((mode, path) in listOf(AvatarMode.IDLE to it.idle, AvatarMode.TALK to it.talk)) {
|
||||
val view = TextureView(context).apply { alpha = 0f; isOpaque = false }
|
||||
val clip = Clip(mode, path, view); clips.add(clip)
|
||||
addView(view, LayoutParams(-1, -1))
|
||||
view.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
|
||||
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, w: Int, h: Int) { clips.forEach { prepare(it) }; fit(clip) }
|
||||
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, w: Int, h: Int) { fit(clip) }
|
||||
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) {}
|
||||
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean { releasePlayers(); return true }
|
||||
}
|
||||
}
|
||||
}
|
||||
reveal()
|
||||
}
|
||||
|
||||
fun render(mode: AvatarMode, foreground: Boolean) {
|
||||
desired = mode
|
||||
val run = foreground && mode != AvatarMode.WAITING
|
||||
if (active && !run) { active = false; releasePlayers() }
|
||||
if (!active && run) {
|
||||
active = true; failed = false
|
||||
clips.forEach { prepare(it) }
|
||||
}
|
||||
reveal()
|
||||
}
|
||||
|
||||
private fun prepare(clip: Clip) {
|
||||
if (!active || failed || clip.player != null || !clip.view.isAvailable) return
|
||||
val fence = epoch
|
||||
val started = SystemClock.elapsedRealtime()
|
||||
try {
|
||||
val player = MediaPlayer(); clip.player = player
|
||||
val surface = Surface(checkNotNull(clip.view.surfaceTexture)); clip.surface = surface
|
||||
player.setSurface(surface); player.setVolume(0f, 0f); player.isLooping = true
|
||||
context.assets.openFd(clip.path).use { player.setDataSource(it.fileDescriptor, it.startOffset, it.length) }
|
||||
player.setOnPreparedListener {
|
||||
if (valid(clip, player, fence)) { fit(clip); player.start() }
|
||||
}
|
||||
player.setOnInfoListener { _, what, _ ->
|
||||
if (valid(clip, player, fence) && what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
|
||||
clip.ready = true
|
||||
val elapsed = (SystemClock.elapsedRealtime()-started).coerceIn(0,60000)
|
||||
if (clip.mode == AvatarMode.IDLE) idleFirstMs = elapsed else talkFirstMs = elapsed
|
||||
if (clips.all { it.ready }) diagnostic("decoder=ready idle_first_ms=$idleFirstMs talk_first_ms=$talkFirstMs")
|
||||
reveal()
|
||||
}
|
||||
true
|
||||
}
|
||||
player.setOnErrorListener { _, _, _ -> if (valid(clip, player, fence)) decoderFailed(); true }
|
||||
player.prepareAsync()
|
||||
} catch (_: Exception) { decoderFailed() }
|
||||
}
|
||||
|
||||
private fun valid(clip: Clip, player: MediaPlayer, fence: Long) = active && !failed && epoch == fence && clip.player === player
|
||||
private fun fit(clip: Clip) {
|
||||
val w = clip.view.width.toFloat(); val h = clip.view.height.toFloat()
|
||||
if (w <= 0 || h <= 0) return
|
||||
val vw = clip.player?.videoWidth?.takeIf { it > 0 }?.toFloat() ?: 480f
|
||||
val vh = clip.player?.videoHeight?.takeIf { it > 0 }?.toFloat() ?: 848f
|
||||
val scale = minOf(w / vw, h / vh)
|
||||
clip.view.setTransform(Matrix().apply { setScale(vw * scale / w, vh * scale / h, w / 2, h / 2) })
|
||||
}
|
||||
|
||||
private fun reveal() {
|
||||
val ready = active && !failed && clips.size == 2 && clips.all { it.ready }
|
||||
clips.forEach { it.view.alpha = if (ready && it.mode == desired) 1f else 0f }
|
||||
still.alpha = if (ready) 0f else 1f
|
||||
val path = if (desired == AvatarMode.WAITING) pack?.waiting else pack?.fallback
|
||||
if (path != displayedStill) {
|
||||
displayedStill = path
|
||||
try { still.setImageBitmap(path?.let { context.assets.open(it).use(BitmapFactory::decodeStream) }) }
|
||||
catch (_: Exception) { still.setImageDrawable(null) }
|
||||
}
|
||||
}
|
||||
private fun decoderFailed() { failed = true; releasePlayers(); diagnostic("decoder=failed fallback=static"); reveal() }
|
||||
private fun diagnostic(message: String) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - lastLog < 1_000) return
|
||||
lastLog = now; DiagnosticLog.record("avatar", message)
|
||||
}
|
||||
private fun releasePlayers() {
|
||||
epoch++
|
||||
clips.forEach {
|
||||
it.ready = false
|
||||
try { it.player?.release() } catch (_: Exception) { }
|
||||
it.player = null; it.surface?.release(); it.surface = null; it.view.alpha = 0f
|
||||
}
|
||||
}
|
||||
fun dispose() { active = false; releasePlayers() }
|
||||
override fun onDetachedFromWindow() { dispose(); super.onDetachedFromWindow() }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
/** Explicit dial intent survives only its own permission continuation. */
|
||||
class CallIntent {
|
||||
var pending = false
|
||||
private set
|
||||
var permissionPending = false
|
||||
private set
|
||||
fun dial(inCall: Boolean, microphoneGranted: Boolean): Boolean {
|
||||
if (inCall || pending || permissionPending) return false
|
||||
pending = true; permissionPending = !microphoneGranted
|
||||
return true
|
||||
}
|
||||
fun permissionResult(granted: Boolean) {
|
||||
permissionPending = false
|
||||
if (!granted) pending = false
|
||||
}
|
||||
fun consumeStart(foreground: Boolean, connected: Boolean, microphoneGranted: Boolean): Boolean {
|
||||
if (!pending || !foreground || !connected || !microphoneGranted || permissionPending) return false
|
||||
pending = false; return true
|
||||
}
|
||||
fun cancel() { pending = false }
|
||||
fun resumeAfterCameraPermission(inCall: Boolean) { if (inCall) pending = true }
|
||||
fun background(preserveForPermission: Boolean = false) { if (!permissionPending && !preserveForPermission) pending = false }
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||
import kotlinx.coroutines.delay
|
||||
import com.gorios.lanvoice.audio.VoicePhase
|
||||
import com.gorios.lanvoice.audio.VoiceUiState
|
||||
import com.gorios.lanvoice.expression.ExpressionControls
|
||||
import com.gorios.lanvoice.expression.ExpressionStatus
|
||||
import com.gorios.lanvoice.expression.ExpressionUiState
|
||||
|
||||
@Composable
|
||||
fun CallScreen(state: VoiceUiState, dialing: Boolean, failure: Boolean, pack: AvatarPack?,
|
||||
onDial: () -> Unit, onHangUp: () -> Unit, onMute: () -> Unit, onCamera: () -> Unit,
|
||||
expression: ExpressionUiState, shareFace: Boolean, onShare: (Boolean) -> Unit,
|
||||
logs: List<String>, onReport: () -> Unit, reportSending: Boolean, reportResult: String?, onInterrupt: () -> Unit,
|
||||
) {
|
||||
val muted = Color(0xFFB5B7C6)
|
||||
val gold = Color(0xFFE8C884)
|
||||
val context = LocalContext.current
|
||||
val avatar = remember { AvatarController() }.select(state.voiceActive, state.replyEmotion, state.playbackActivity)
|
||||
val latestAvatar by rememberUpdatedState(avatar)
|
||||
LaunchedEffect(state.voiceActive) {
|
||||
if (state.voiceActive) while (true) {
|
||||
val selected = latestAvatar
|
||||
DiagnosticLog.record("avatar", "mode=${selected.mode.name.lowercase()} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} selected=${selected.resolvedAssetEmotion.emotion.wire}/${selected.resolvedAssetEmotion.intensity} fallback=${selected.emotionFallback}")
|
||||
delay(1_000)
|
||||
}
|
||||
}
|
||||
var details by remember { mutableStateOf(false) }
|
||||
val waiting = remember(pack) { try {
|
||||
pack?.let { context.assets.open(it.waiting).use { stream -> BitmapFactory.decodeStream(stream)?.asImageBitmap() } }
|
||||
} catch (_: Exception) { null } }
|
||||
Column(Modifier.fillMaxSize().background(Color(0xFF121220)).windowInsetsPadding(WindowInsets.safeDrawing)
|
||||
.padding(horizontal = 20.dp, vertical = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(if (state.voiceActive) "通话中 · " + when (state.phase) {
|
||||
VoicePhase.LISTENING -> if (state.microphoneMuted) "麦克风已静音" else "听取中"
|
||||
VoicePhase.RECOGNIZING -> "识别中"
|
||||
VoicePhase.THINKING -> "思考中"
|
||||
VoicePhase.ANSWERING -> "回答中"
|
||||
else -> "已连接"
|
||||
} else if (dialing) "正在连接…" else if (failure) "连接失败" else "声伴", color = gold, fontSize = 15.sp)
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
if (state.voiceActive) {
|
||||
val width = minOf(maxWidth, maxHeight * (480f / 848f))
|
||||
AvatarPortrait(pack, avatar.mode, Modifier.width(width).aspectRatio(480f / 848f))
|
||||
} else {
|
||||
val size = minOf(maxWidth, maxHeight * .65f, 320.dp)
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (waiting != null) Image(waiting, "待接听角色头像", Modifier.size(size).clip(CircleShape))
|
||||
else Box(Modifier.size(size).clip(CircleShape).background(Color(0xFF292A3C)), contentAlignment = Alignment.Center) {
|
||||
Text("声伴", color = gold, fontSize = 30.sp)
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text("声伴", color = Color.White, fontSize = 28.sp)
|
||||
Text("视频角色 · 候选素材", color = muted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
state.guidance?.let { Text(it, color = gold, fontSize = 12.sp, textAlign = TextAlign.Center) }
|
||||
if (state.voiceActive) {
|
||||
Row(Modifier.widthIn(max = 520.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CallButton(if (state.microphoneMuted) "取消静音" else "麦克风静音", onMute, Modifier.weight(1f), Color(0xFF343648))
|
||||
CallButton(if (expression.status in setOf(ExpressionStatus.ACTIVE, ExpressionStatus.STARTING)) "关闭相机" else "开启相机", onCamera, Modifier.weight(1f), Color(0xFF343648))
|
||||
CallButton("挂断", onHangUp, Modifier.weight(1f), Color(0xFFB83B50))
|
||||
}
|
||||
} else {
|
||||
CallButton(if (dialing) "取消连接" else "拨通", if (dialing) onHangUp else onDial,
|
||||
Modifier.widthIn(max = 360.dp).fillMaxWidth(), if (dialing) Color(0xFF343648) else Color(0xFF267E63))
|
||||
}
|
||||
TextButton(onClick = { details = !details }) { Text(if (details) "收起详情" else "通话详情", color = muted, fontSize = 12.sp) }
|
||||
if (details) Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("角色:${state.roleLabel}", color = gold, fontSize = 12.sp)
|
||||
Text("请求表达:" + if (state.replyEmotion.turnId == null) "尚未收到" else
|
||||
"${state.replyEmotion.label} (${state.replyEmotion.emotion.wire}/${state.replyEmotion.intensity})", color = muted, fontSize = 12.sp)
|
||||
state.previousReplyEmotion?.let { Text("上一轮:${it.label}", color = muted, fontSize = 12.sp) }
|
||||
Text("素材:中立 · ${avatar.mode.name.lowercase()}" + if (avatar.emotionFallback) "(当前表达缺素材,降级中立)" else "", color = muted, fontSize = 12.sp)
|
||||
Text(if (pack == null) "素材包缺失或校验失败 · 语音仍可用" else "素材审核 / 设备验收待完成", color = muted, fontSize = 11.sp)
|
||||
ExpressionControls(expression, onCamera, shareFace, onShare, controlsEnabled = state.voiceActive)
|
||||
Text("AEC:${state.aec.name} · 效果待真机验证", color = muted, fontSize = 11.sp)
|
||||
Row {
|
||||
TextButton(onClick = onInterrupt, enabled = state.voiceActive) { Text("打断") }
|
||||
TextButton(onClick = onReport, enabled = !reportSending) { Text(if (reportSending) "发送中…" else "发送诊断报告") }
|
||||
}
|
||||
reportResult?.let { Text(it, color = muted, fontSize = 11.sp) }
|
||||
Text(logs.takeLast(10).joinToString("\n"), color = muted, fontSize = 10.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CallButton(label: String, onClick: () -> Unit, modifier: Modifier, color: Color) {
|
||||
Button(onClick, modifier.heightIn(min = 52.dp), colors = ButtonDefaults.buttonColors(containerColor = color), contentPadding = PaddingValues(8.dp)) {
|
||||
Text(label, fontSize = 13.sp, textAlign = TextAlign.Center)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, modifier: Modifier) {
|
||||
val activity = LocalContext.current as ComponentActivity
|
||||
val view = remember(pack) { AvatarVideoView(activity, pack) }
|
||||
val currentMode by rememberUpdatedState(mode)
|
||||
SideEffect { view.render(mode, activity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(view) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_STOP) view.render(AvatarMode.WAITING, false)
|
||||
if (event == Lifecycle.Event.ON_START) view.render(currentMode, true)
|
||||
}
|
||||
activity.lifecycle.addObserver(observer)
|
||||
onDispose { activity.lifecycle.removeObserver(observer); view.dispose() }
|
||||
}
|
||||
AndroidView(factory = { view }, modifier = modifier)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ class CameraPermissionGate {
|
||||
return consumeStart()
|
||||
}
|
||||
fun release() { released = true; requested = false; approved = false; permissionPending = false }
|
||||
fun cancel() { requested = false; approved = false }
|
||||
private fun consumeStart(): Action {
|
||||
if (!released && foreground && requested && approved) {
|
||||
requested = false; approved = false
|
||||
|
||||
@@ -44,6 +44,7 @@ class ExpressionController(
|
||||
var lastSampleMs = Long.MIN_VALUE
|
||||
var lastPublished: List<ExpressionCue>? = null
|
||||
var lastStableCue = FaceCue.UNKNOWN
|
||||
var lastPresence = FacePresence.UNKNOWN
|
||||
}
|
||||
|
||||
private val appContext = context.applicationContext
|
||||
@@ -196,11 +197,13 @@ class ExpressionController(
|
||||
run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - 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.lastStableCue != faceCue.cue) {
|
||||
val presence = if (result.faceLandmarks().isEmpty()) FacePresence.ABSENT else FacePresence.PRESENT
|
||||
if (run.lastPublished != visible || run.lastStableCue != faceCue.cue || run.lastPresence != presence) {
|
||||
run.lastPresence = presence
|
||||
run.lastStableCue = faceCue.cue
|
||||
run.lastPublished = visible
|
||||
main.post {
|
||||
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue))
|
||||
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue, facePresence = presence))
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
enum class ExpressionStatus { OFF, STARTING, ACTIVE, UNAVAILABLE }
|
||||
enum class FacePresence { UNKNOWN, PRESENT, ABSENT }
|
||||
|
||||
data class ExpressionUiState(
|
||||
val status: ExpressionStatus = ExpressionStatus.OFF,
|
||||
val cues: List<ExpressionCue> = emptyList(),
|
||||
val guidance: String? = null,
|
||||
val stableCue: FaceCue = FaceCue.UNKNOWN,
|
||||
val facePresence: FacePresence = FacePresence.UNKNOWN,
|
||||
)
|
||||
|
||||
@@ -21,21 +21,23 @@ import androidx.compose.ui.unit.sp
|
||||
fun ExpressionControls(
|
||||
state: ExpressionUiState, onToggle: () -> Unit,
|
||||
shareFace: Boolean = false, onShareFace: (Boolean) -> Unit = {},
|
||||
controlsEnabled: Boolean = true,
|
||||
) {
|
||||
val enabled = state.status == ExpressionStatus.STARTING || state.status == ExpressionStatus.ACTIVE
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"你:" + when {
|
||||
!enabled -> "摄像头已关闭"
|
||||
state.status == ExpressionStatus.STARTING -> "检测中"
|
||||
"相机:" + when {
|
||||
state.status == ExpressionStatus.UNAVAILABLE -> "不可用 / 失败"
|
||||
!enabled -> "已关闭"
|
||||
state.status == ExpressionStatus.STARTING -> "启动中"
|
||||
ExpressionCue.FACE_LOST in state.cues -> "无脸"
|
||||
state.stableCue == FaceCue.SMILING -> "明显微笑"
|
||||
state.stableCue == FaceCue.BROW_FURROWED -> "明显皱眉"
|
||||
else -> "未见明显线索"
|
||||
state.facePresence == FacePresence.PRESENT -> "有人脸"
|
||||
state.facePresence == FacePresence.ABSENT -> "尚无结果"
|
||||
else -> "尚无结果"
|
||||
}, fontSize = 12.sp, color = Color(0xFFE8C884),
|
||||
)
|
||||
TextButton(onClick = onToggle) {
|
||||
TextButton(onClick = onToggle, enabled = controlsEnabled) {
|
||||
Text(when {
|
||||
state.status == ExpressionStatus.STARTING -> "取消开启"
|
||||
enabled -> "关闭摄像头"
|
||||
@@ -43,6 +45,11 @@ fun ExpressionControls(
|
||||
}, fontSize = 12.sp, color = Color(0xFFE8C884))
|
||||
}
|
||||
}
|
||||
Text("表情线索:" + when (state.stableCue) {
|
||||
FaceCue.SMILING -> "明显微笑"
|
||||
FaceCue.BROW_FURROWED -> "明显皱眉"
|
||||
else -> "未见明显线索"
|
||||
}, fontSize = 12.sp, color = Color(0xFF9CA3AF))
|
||||
if (state.status == ExpressionStatus.STARTING) {
|
||||
Text("正在开启摄像头…", color = Color(0xFF9CA3AF), fontSize = 12.sp)
|
||||
}
|
||||
@@ -55,7 +62,7 @@ fun ExpressionControls(
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("将表情线索用于对话", color = Color(0xFF9CA3AF), fontSize = 12.sp)
|
||||
Switch(checked = shareFace, onCheckedChange = onShareFace)
|
||||
Switch(checked = shareFace, onCheckedChange = onShareFace, enabled = controlsEnabled)
|
||||
}
|
||||
if (shareFace && state.status != ExpressionStatus.ACTIVE) {
|
||||
Text("摄像头关闭时不发送线索", color = Color(0xFF9CA3AF), fontSize = 11.sp)
|
||||
|
||||
Reference in New Issue
Block a user