feat: add neutral avatar video call MVP in Android 0.6.0

This commit is contained in:
zenord
2026-10-12 15:12:57 +08:00
parent 4d305ad0df
commit fdd91234b5
39 changed files with 1325 additions and 184 deletions
+2
View File
@@ -9,3 +9,5 @@ artifacts/
__pycache__/
*.py[cod]
.runtime/
app/src/main/assets/avatar/
+3 -3
View File
@@ -45,14 +45,14 @@ android {
applicationId 'com.gorios.lanvoice'
minSdk 26
targetSdk 34
versionCode 10
versionName '0.5.2'
versionCode 11
versionName '0.6.0'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = '17' }
buildFeatures { compose true }
androidResources { noCompress += ['task'] }
androidResources { noCompress += ['task', 'mp4'] }
sourceSets.main.res.srcDir(networkSecurityResources)
}
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig) }
@@ -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)
+65
View File
@@ -0,0 +1,65 @@
# Android 0.6.0 / code11 — neutral avatar candidate MVP
This release replaces the debug home with a video-call style single page. Before dialing it displays the a01 waiting portrait, title “声伴” and Dial; no listen/start or microphone capture occurs until the user explicitly dials and grants microphone permission. WS/health preparation alone is not a call. Connecting has a cancel action, duplicate dialing is fenced, denial shows guidance. These labels describe an app conversation, not a real person's ringing/answering. The existing hello has no character display field consumed by this client, so no private persona name is embedded.
During a call the 480×848 portrait fits the available width/height without stretching. Bottom controls hang up, mute the microphone, or explicitly enable the camera. Status is short; actual requested role expression, previous reply, selected neutral asset/fallback, camera presence/cue, interruption and diagnostic upload live in the expandable details. Insets are respected; details have bounded scrolling and portrait shrinks for small/landscape screens. Physical small-screen/tablet rendering remains pending.
Mute stops AudioCapture and invalidates already queued capture callbacks while keeping listen/session and sequence allocation. Unmute restarts capture only in LISTENING; subsequent LISTEN/drained resumes respect mute. Mute does not stop the character's answer. Because no silence is sent while muted, a server speech endpoint already underway may remain waiting until unmute; this is not a new server mute protocol. Hangup cancels dial intent, stops capture, aborts/flushes local playback, closes WS, closes camera, cancels pending camera intent and clears face/share context. A new WS generation and existing turn/seq fences reject late old events. It preserves history/diagnostics. Camera/share default off. Normal background closes the call/audio/camera and releases video players. A one-shot system permission continuation may resume an explicitly requested call; it does not restart a background camera. Existing orientation configChanges and camera thresholds/10Hz/TTL/model are unchanged.
## PCM activity and video
`PlaybackActivity.kt` analyzes 48k mono PCM16 into 20ms windows (960 samples), carrying RMS/peak across network chunks. Default activity requires RMS≥180 and peak≥600 on the signed16 scale. It has a configurable80–150ms release, default120ms. These are approximate speech activity thresholds, not phoneme recognition. Metadata is consumed only when AudioTrack.playbackHeadPosition actually advances through accepted samples, capped to written samples. Partial writes, final partial windows, unsigned32 wrap and pause/flush resets are handled. Consumed windows are pruned, pending metadata is capped at1600; the pre-existing PCM queue stays capped at30s. Empty software queue still polls hardware every10ms so native buffered sound, sustained silence, underrun and resumed sound update the renderer. Native draining polls retain existing5ms behavior. TTS stop does not force idle while voiced PCM remains buffered; explicit drained, abort/error/disconnect/background/old turn reset does. No extra fixed200ms startup buffer/wait was added; native short-utterance silence tail remains.
Activity reaches the main coordinator through current turn/generation/block/drained guards. TTS start, network arrival, successful write and phase ANSWERING never directly select talk. requestedEmotion remains the original seven-state reply value. resolvedAssetEmotion is neutral0 for all seven inputs in this pack, displayed visibly as fallback for nonneutral requests. The previous label never resurrects a previous talk loop. The user camera cue cannot select avatar expression.
Platform MediaPlayer avoids new dependencies or compileSDK upgrades. Each call preloads two volume0 loops into separate TextureViews; both first-render callbacks are required before revealing video. They run continuously with one visible layer; switches change visibility without seeking, waiting for clip end, creating a player per syllable or delaying audio. There is no crossfade. Texture scaling preserves aspect ratio. Call/lifecycle release increments a renderer epoch; old prepared/info/error callbacks cannot reveal retired video. Any prepare/decoder failure releases both players and shows static neutral for that run, without affecting audio. No pack shows a generic waiting placeholder plus a details explanation while voice remains usable. Supplement failure falls back to base neutralPNG. Unsupported simultaneous decoders, dropped frames, black flashes and resource/thermal behavior require real-device testing. Both loops running continuously trades additional decoder usage for prompt visibility switches; not claimed universally supported.
First-frame times for both clips and bounded mode/requested/selected/decoder enums are recorded locally, at most once per second per summary source; no PCM, image, speech, video, raw decoder errors or camera coefficients are recorded. They are included only through the existing explicit diagnostic report path. Existing0.5.2 camera/transmission numeric summaries and failure enums remain. Face presence is now independently UNKNOWN/PRESENT/ABSENT from actual successful face results; only stable FACE_LOST displays “无脸”. No result is never fabricated as a face, and no stable cue reads “未见明显线索”. This is a display improvement, not evidence the algorithm has recovered. Face acceptance remains a separate user task.
## Offline pack and rights
Original authorized candidate directory: `.runtime/avatar-imports/a01-v1/` (directory0700/files0600). It is never overwritten or transcoded. Import with:
```bash
python3 scripts/import-avatar-pack.py /path/to/authorized/a01-v1
./scripts/check-avatar-regressions.sh
./scripts/build.sh
```
The importer validates pinned manifests, local relative paths, individual SHA256 and bounded file sizes before copying into ignored `app/src/main/assets/avatar/a01-v1/` with0700/0600. APK includes two MP4s, fallbackPNG, waitingPNG and both manifests. MP4 is uncompressed for asset file descriptors. Runtime checks hashes again. Missing pack may build but renders the generic placeholder; release packaging refuses missing or mismatched candidates. Binary portraits/videos, `.runtime`, APKs and real test evidence remain ignored. Git stores only code, documentation and exact text manifests in `docs/avatar/`. Cloning source alone does not provide the private portrait pack; obtain the authorized pack out of band and import before reproducing this APK.
| File | SHA256 |
|---|---|
| manifest.json | ca817f1e538a5933beac4f3f4cda6367bf87a2d428b3307622c98842ae8679d1 |
| call-avatar-manifest.json | 3b6918cdc955f6d51e8910cf7a0067f4dedb19d28accbb5525f15876e6ad4d8c |
| videos/neutral-idle-loop.mp4 | 5d6aa20392b2f6c33cc0af366bac0ac81d0a0dce60a9ed95703c8c6067046a00 |
| videos/neutral-talk-loop.mp4 | 8e410bb769b4fe5290b8e2de0df0236d4bc65d4212c9ea53f71be0ab40231208 |
| frames/neutral.png | af3cf393601548483ab60696d35e832679231845d498627ec4ffcdc2ec8d94b9 |
| frames/waiting-avatar.png | 778a1047ccd5cea2ddcda81b3856e6fcd0e17f1dec42fba57dada2e4c95d71e3 |
The waiting portrait is a768×768 crop/resize of the941×1672 original; no paid generation or new AI generation. Pack identitya01, all rightsStatus=unverified, review/device=pending. A user-provided source is not a verified portrait/copyright/commercial license. No old expressionPNG is mixed in; other emotions and one-shots are future extensions, not implemented in this neutral-only selector. Manifests are preserved byte-for-byte, including original untested metadata; new verification evidence is separate, not a false promotion to qualified assets.
## Verification and limitations
Original MP4s were decoded end-to-end using local FFmpeg7.0.2 with `-xerror -map 0:v:0 -f null -`; idle145 frames/6041.667ms, talk193 frames/8041.667ms. ffprobe8.0.1 and trace_headers verified H264avc1 HighL4.1,480×848/24fps, yuv420p/8-bit, SPS chroma_format_idc1 and both bit_depth_minus8=0, BT709 limited. Both containers have an MJPEG attached cover plus main H264, and no playable audio stream; possible orphan mdat audio payload is not erased. One sync sample per clip is retained. Initial/last-frame contact sheets and first14 talk mouth crops were inspected: mouth opening is visible by frame5≈208ms and visibly open by frame6≈250ms, a qualitative observation without a measured detection threshold. Thus this source cannot justify a200ms visual mouth response claim even before decoding/scheduling. Paused hidden loops resume visibility at their continuously running phase, not necessarily closed-mouth anchors. Initial/last stills look similar; temporal seam motion was not accepted by this still inspection. Safe closed-mouth cuts remain unknown and no seek points are invented.
Nine JVM entry points pass: existing session/playback/capture/protocol and four expression suites, plus avatar. New production-code tests cover RMS/peak/cross-chunk/partial writes/tail/no head activity/silence/underrun/resume/u32 wrap/reset/bounds; software queue empty with real playback worker doubles; downlink-stop vs drained; generation/turn/abort/hangup/late frames; dial/denial/cancel/permission/background; mute queued-frame discard/seq continuity; actual AvatarVideoView preparation/first-frame visibility/two muted loops/switch reuse/stale callbacks/static failure/missing pack/lifecycle. Synthetic audio is a public fixed tone/zero fixture; no user recordings/text were used. These are deterministic Android/media doubles, not measurements of speaker audibility or hardware decoding.
All74 gateway regression tests passed in an isolated temporary source tree using the existing server interpreter and checksum-verified read-only Silero artifact, including model state check. No backend source/provider/prompt/voice/VAD/ASR/environment changes, deployments, restarts or extra live inference were performed. The first attempt with local generic Python lacked dependencies; the complete existing server environment resolved that test-environment failure.
`scripts/package-avatar-release.sh` checks tested-source hashes, manifest/asset hashes, builds0.6.0/code11/arm64/min26/target34, verifies badging and apksigner certificate equality with retained0.5.1/0.5.2, exact APK asset bytes/uncompressedMP4, and HTTP APK plus checksum bytes. It refuses overwriting0.6.0 and preserves old APKs. Numeric release/test/decode evidence stays under ignored `logs/avatar-060/`.
Target alps p30_6771/API31 hardware decode, dual-decoder capability, real switching/loop-seam/first mouth motion, UI layouts/rotation, temperature/power, phone audibility and end-to-end timing are still pending. No claimed exact lip sync or≤200ms guarantee. No automatic recording/camera permission, ADB USB/wireless/USBIP/SSH setup, data clearing or app launching occurs. For an already authorized Windows USB device, the coordinator can run `scripts/install-avatar-windows.ps1 -Adb <existing-adb> -Serial <device> -Sha256 <release-sha>`; it verifies bytes, installs with`-r`, checks version, and leaves the app for manual launch. This script being available does not mean installation was executed.
## Manual acceptance
1. Install the candidate, open manually: waiting portrait + 声伴 + 拨通; verify no microphone/camera indicator before dialing. Cancel a connection and deny microphone once; return to waiting with clear guidance. Dial twice quickly and verify one connection/start.
2. Dial with permission: inspect portrait aspect ratio and actual idle motion in waiting/listening/thinking. During TTS, verify talk only follows sound consumption; let sustained pause/underrun close to idle and resumption return to talk. No camera is enabled automatically.
3. Mute during listening: indicator clears, no new uplink frames; unmute resumes. Mute while answering: reply continues. Downlink completion with buffered speech should remain animated until consumed. Drained returns idle/listening. Interrupt/hangup promptly stop speech and retired video state; hangup returns waiting portrait and closes camera/share. Redial cannot resurrect the old answer.
4. Expand details on public happy/sad/angry reply cases: actual requested label/intensity stays unchanged, selected asset says neutral fallback; previous reply remains a separate label. No claim that nonneutral visual clips exist.
5. Explicitly enable camera during a call only for the separate later face acceptance: off/start/presence unknown or present/no face/failure distinct from “未见明显线索” and role expression. Share remains opt-in. Hangup/background clears camera/share. Verify both permission callback orders; a canceled intent must not reopen camera.
6. Background/foreground, rotate, and exercise small portrait/landscape/tablet layouts. Verify no silent auto-call on return, no clipping of hangup, no black/ghost faces or retired callback switching. Explicitly send diagnostics for decoder first-frame enums/times; failure/static path must preserve voice.
## Candidate release artifact
APK: `artifacts/lan-voice-v060-arm64-debug.apk` (36105893bytes),0.6.0/code11. URL: http://192.168.31.124:8080/lan-voice-v060-arm64-debug.apk . SHA256 `37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e`. Matching `.apk.sha256` HTTP bytes and signatures verified; retained0.5.1/0.5.2 unchanged. Installation/device acceptance pending.
@@ -0,0 +1,48 @@
{
"schemaVersion": 1,
"supplementId": "a01-v1-call-avatar-01",
"identityId": "a01",
"basePackId": "a01-v1",
"baseManifestPath": "manifest.json",
"callAvatarPath": "frames/waiting-avatar.png",
"waiting": {
"id": "a01_neutral_0_waiting_01_v1",
"path": "frames/waiting-avatar.png",
"mode": "static_waiting",
"emotion": "neutral",
"intensity": 0,
"width": 768,
"height": 768,
"format": "png",
"bytes": 703317,
"sha256": "778a1047ccd5cea2ddcda81b3856e6fcd0e17f1dec42fba57dada2e4c95d71e3",
"rightsStatus": "unverified",
"reviewStatus": "pending",
"deviceTestStatus": "pending",
"provenance": {
"operation": "crop_and_resize",
"sourcePath": "frames/neutral.png",
"sourceSha256": "af3cf393601548483ab60696d35e832679231845d498627ec4ffcdc2ec8d94b9",
"sourceWidth": 941,
"sourceHeight": 1672,
"cropBoxPixels": [
0,
40,
941,
981
],
"cropBoxConvention": "left,top,right,bottom; right/bottom exclusive",
"resizeFilter": "Pillow LANCZOS",
"newImageGeneration": false,
"generationCost": 0
}
},
"usage": {
"state": "not_connected",
"closedMouthNeutral": true,
"simulatesRealPersonAnswering": false,
"branding": "App-owned video-call layout; no Apple branding",
"audio": "No avatar audio; no mandatory simulated ringing or added TTS startup delay"
},
"rightsNote": "User-supplied source does not establish portrait or commercial-use authorization."
}
+186
View File
@@ -0,0 +1,186 @@
{
"schemaVersion": 1,
"packId": "a01-v1",
"identityId": "a01",
"rightsStatus": "unverified",
"reviewStatus": "pending",
"deviceTestStatus": "pending",
"staticFallbackPath": "frames/neutral.png",
"staticFallback": {
"path": "frames/neutral.png",
"width": 941,
"height": 1672,
"sha256": "af3cf393601548483ab60696d35e832679231845d498627ec4ffcdc2ec8d94b9",
"rightsStatus": "unverified"
},
"emotionContract": {
"requestedEmotion": "Original reply emotion/intensity; never rewritten by fallback",
"resolvedAssetEmotion": "Selected asset emotion/intensity only"
},
"availableAssetEmotions": [
{
"emotion": "neutral",
"intensity": 0
}
],
"fallbackRules": [
{
"requestedEmotion": {
"emotion": "neutral",
"intensity": 0
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "happy",
"intensity": 1
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "happy",
"intensity": 2
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "sad",
"intensity": 1
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "sad",
"intensity": 2
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "angry",
"intensity": 1
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
},
{
"requestedEmotion": {
"emotion": "angry",
"intensity": 2
},
"resolvedAssetEmotion": {
"emotion": "neutral",
"intensity": 0
}
}
],
"unknownEmotionFallback": {
"emotion": "neutral",
"intensity": 0
},
"playbackContract": {
"mouthActivitySource": "actual_pcm_playback_head",
"extraStartupDelayMs": 0,
"visualResponseTargetMs": 200,
"visualResponseTargetStatus": "pending_measurement",
"videoVolume": 0,
"abortPreemptsAll": true,
"phonemeSync": false
},
"assets": [
{
"id": "a01_neutral_0_idle_01_v1",
"path": "videos/neutral-idle-loop.mp4",
"emotion": "neutral",
"intensity": 0,
"mode": "idle",
"loop": true,
"durationMs": 6042,
"width": 480,
"height": 848,
"fps": 24,
"codec": "h264",
"codecTag": "avc1",
"profile": "High",
"level": "4.1",
"hasAudio": false,
"sha256": "5d6aa20392b2f6c33cc0af366bac0ac81d0a0dce60a9ed95703c8c6067046a00",
"bytes": 881745,
"startAnchor": "neutral",
"endAnchor": "neutral",
"firstMouthActivityMs": null,
"safeClosedMouthCutsMs": null,
"pixelFormat": null,
"reviewStatus": "pending",
"deviceTestStatus": "pending",
"rightsStatus": "unverified",
"verification": {
"containerMetadata": "checked",
"fullDecode": "not_tested",
"spsBitDepthAndChroma": "not_tested",
"loopSeam": "not_tested",
"mouthTiming": "not_tested",
"syncSampleCount": 1,
"colorMetadata": "BT.709 limited range"
}
},
{
"id": "a01_neutral_0_talk_01_v1",
"path": "videos/neutral-talk-loop.mp4",
"emotion": "neutral",
"intensity": 0,
"mode": "talk",
"loop": true,
"durationMs": 8042,
"width": 480,
"height": 848,
"fps": 24,
"codec": "h264",
"codecTag": "avc1",
"profile": "High",
"level": "4.1",
"hasAudio": false,
"sha256": "8e410bb769b4fe5290b8e2de0df0236d4bc65d4212c9ea53f71be0ab40231208",
"bytes": 1060214,
"startAnchor": "neutral",
"endAnchor": "neutral",
"firstMouthActivityMs": null,
"safeClosedMouthCutsMs": null,
"pixelFormat": null,
"reviewStatus": "pending",
"deviceTestStatus": "pending",
"rightsStatus": "unverified",
"verification": {
"containerMetadata": "checked",
"fullDecode": "not_tested",
"spsBitDepthAndChroma": "not_tested",
"loopSeam": "not_tested",
"mouthTiming": "not_tested",
"syncSampleCount": 1,
"colorMetadata": "BT.709 limited range"
}
}
],
"documentationPath": "docs/MVP_ASSET_INTERFACE.md"
}
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Production Kotlin with local deterministic media/transport doubles, no real capture.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p logs/avatar-060
python3 scripts/check-reply-regressions.py > logs/avatar-060/client-tests.txt 2>&1
./scripts/check-expression-rules.sh > logs/avatar-060/expression-tests.txt 2>&1
python3 - <<'PY'
from pathlib import Path
import hashlib,json
root=Path.cwd()
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
paths += [root/'scripts/check-reply-regressions.py',root/'scripts/check-expression-rules.sh',root/'scripts/check-avatar-regressions.sh']
result={'status':'passed','jvm_entry_points':9,'real_device':'pending',
'hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(paths)}}
(root/'logs/avatar-060/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: nine JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
PY
+3 -2
View File
@@ -23,8 +23,9 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
suites = [
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']),
('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']),
('avatar','AvatarCheckKt', [source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
]
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Import the pinned, authorized local candidate pack; never generate or modify originals."""
from pathlib import Path, PurePosixPath
import argparse
import hashlib
import json
import shutil
ROOT = Path(__file__).resolve().parents[1]
BASE_SHA = 'ca817f1e538a5933beac4f3f4cda6367bf87a2d428b3307622c98842ae8679d1'
CALL_SHA = '3b6918cdc955f6d51e8910cf7a0067f4dedb19d28accbb5525f15876e6ad4d8c'
def digest(data):
return hashlib.sha256(data).hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('source', type=Path)
args = parser.parse_args()
source = args.source.resolve(strict=True)
base = (source/'manifest.json').read_bytes()
call = (source/'call-avatar-manifest.json').read_bytes()
assert digest(base) == BASE_SHA and digest(call) == CALL_SHA, 'Manifest hash mismatch'
manifest, supplement = json.loads(base), json.loads(call)
assert manifest['schemaVersion'] == 1 and manifest['identityId'] == supplement['identityId'] == 'a01'
assert manifest['rightsStatus'] == 'unverified' and manifest['deviceTestStatus'] == 'pending'
assert {a['mode'] for a in manifest['assets']} == {'idle','talk'}
rows = manifest['assets'] + [manifest['staticFallback'], supplement['waiting']]
verified = {'manifest.json': base, 'call-avatar-manifest.json': call}
for row in rows:
path = PurePosixPath(row['path'])
assert len(path.parts) == 2 and path.parts[0] in ('videos','frames') and '..' not in path.parts
src = (source/str(path)).resolve(strict=True)
assert src.is_relative_to(source) and src.is_file()
data = src.read_bytes()
assert len(data) <= 8_000_000 and digest(data) == row['sha256'], str(path)
if row.get('mode') in ('idle','talk'):
assert row['emotion'] == 'neutral' and row['intensity'] == 0 and row['loop'] and not row['hasAudio']
verified[str(path)] = data
target = ROOT/'app/src/main/assets/avatar/a01-v1'
# Refuse overwriting an unknown imported file; safe idempotent reimport is supported.
for name, data in verified.items():
dest = target/name
assert not dest.exists() or digest(dest.read_bytes()) == digest(data), f'Unknown existing asset: {dest}'
target.mkdir(parents=True, exist_ok=True, mode=0o700)
for name, data in verified.items():
dest = target/name
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
dest.write_bytes(data); dest.chmod(0o600)
print(json.dumps({'pack':'a01-v1','files':{name:digest(data) for name,data in verified.items()},
'rightsStatus':'unverified','deviceTestStatus':'pending'}, indent=2))
if __name__ == '__main__':
main()
+26
View File
@@ -0,0 +1,26 @@
# Run with an existing authorized Windows USB adb. Does not configure ADB/network or start app.
param(
[string]$Adb = 'adb',
[string]$Serial = '',
[Parameter(Mandatory = $true)][string]$Sha256,
[string]$Url = 'http://192.168.31.124:8080/lan-voice-v060-arm64-debug.apk'
)
$ErrorActionPreference = 'Stop'
if ($Sha256 -notmatch '^[0-9a-fA-F]{64}$') { throw 'Supply the release SHA256 from the handoff.' }
$artifact = Join-Path $PSScriptRoot '..\artifacts\lan-voice-v060-arm64-debug.apk'
New-Item -ItemType Directory -Force (Split-Path $artifact) | Out-Null
if (!(Test-Path $artifact)) { Invoke-WebRequest -Uri $Url -OutFile $artifact -UseBasicParsing }
if ((Get-FileHash -Algorithm SHA256 $artifact).Hash -ne $Sha256) { throw 'APK hash mismatch; existing file preserved.' }
$devices = @(& $Adb devices | Select-String '^([^\s]+)\s+device$' | ForEach-Object { $_.Matches[0].Groups[1].Value })
if ($LASTEXITCODE -ne 0) { throw 'Existing adb unavailable.' }
if (!$Serial) {
if ($devices.Count -ne 1) { throw 'Select an already authorized USB device using -Serial.' }
$Serial = $devices[0]
}
if ($Serial -notin $devices) { throw 'Device is not already authorized.' }
& $Adb -s $Serial install -r $artifact
if ($LASTEXITCODE -ne 0) { throw 'Installation failed; no uninstall or data clearing performed.' }
$version = & $Adb -s $Serial shell dumpsys package com.gorios.lanvoice | Select-String 'versionCode=|versionName='
if ($LASTEXITCODE -ne 0 -or !($version -match 'versionCode=11') -or !($version -match 'versionName=0.6.0')) { throw 'Installed version did not verify.' }
$version
Write-Output 'Installed 0.6.0/code11. Open manually; recording and camera require explicit user actions.'
+73
View File
@@ -0,0 +1,73 @@
#!/bin/bash
# Pinned offline pack + tested code, retained certificate, new artifact only, HTTP bytes.
set -euo pipefail
cd "$(dirname "$0")/.."
python3 - <<'PY'
from pathlib import Path
import hashlib,json
root=Path.cwd()
assert not (root/'artifacts/lan-voice-v060-arm64-debug.apk').exists(), 'Refuse overwriting release'
assert (root/'artifacts/lan-voice-v052-arm64-debug.apk').is_file()
tests=json.loads((root/'logs/avatar-060/client-tests.json').read_text())
assert tests['status']=='passed' and tests['jvm_entry_points']==9
for path,digest in tests['hashes'].items(): assert hashlib.sha256((root/path).read_bytes()).hexdigest()==digest,path
for name in ('a01-v1.manifest.json','a01-v1.call-avatar-manifest.json'):
original=(root/'docs/avatar'/name).read_bytes()
target='manifest.json' if name=='a01-v1.manifest.json' else 'call-avatar-manifest.json'
assert original==(root/'app/src/main/assets/avatar/a01-v1'/target).read_bytes()
base=json.loads((root/'docs/avatar/a01-v1.manifest.json').read_text())
call=json.loads((root/'docs/avatar/a01-v1.call-avatar-manifest.json').read_text())
for row in base['assets']+[base['staticFallback'],call['waiting']]:
assert hashlib.sha256((root/'app/src/main/assets/avatar/a01-v1'/row['path']).read_bytes()).hexdigest()==row['sha256']
print('Verified tested source and all offline candidate hashes')
PY
./scripts/build.sh
source /home/ubuntu/android-build/env.sh
TOOLS=/home/ubuntu/android-build/sdk/build-tools/34.0.0
APK=app/build/outputs/apk/debug/app-debug.apk
"$TOOLS/aapt" dump badging "$APK" > logs/avatar-060/badging.txt
"$TOOLS/apksigner" verify --verbose --print-certs "$APK" > logs/avatar-060/signature.txt
python3 - <<'PY'
from pathlib import Path
import hashlib,json,re,shutil,subprocess,urllib.request,zipfile
root=Path.cwd();logs=root/'logs/avatar-060'
badge=(logs/'badging.txt').read_text()
for value in ("name='com.gorios.lanvoice'","versionCode='11'","versionName='0.6.0'","sdkVersion:'26'","targetSdkVersion:'34'"):assert value in badge,value
assert re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'"
sig=(logs/'signature.txt').read_text();pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
for version in ('051','052'):
old=root/f'artifacts/lan-voice-v{version}-arm64-debug.apk'
output=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(old)],text=True)
assert re.search(pattern,output)[1]==re.search(pattern,sig)[1], 'Signing certificate mismatch'
source=root/'app/build/outputs/apk/debug/app-debug.apk'
with zipfile.ZipFile(source) as archive:
for file in (root/'app/src/main/assets/avatar/a01-v1').rglob('*'):
if file.is_file():
name='assets/'+str(file.relative_to(root/'app/src/main/assets'))
assert archive.read(name)==file.read_bytes(),name
if file.suffix=='.mp4':assert archive.getinfo(name).compress_type==zipfile.ZIP_STORED
artifact=root/'artifacts/lan-voice-v060-arm64-debug.apk'
assert not artifact.exists()
shutil.copy2(source,artifact)
digest=hashlib.sha256(artifact.read_bytes()).hexdigest()
sidecar=artifact.with_suffix('.apk.sha256');sidecar.write_text(f'{digest} {artifact.name}\n')
base='http://192.168.31.124:8080/'
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
url=None
for prefix in ('','artifacts/'):
try:
candidate=base+prefix+artifact.name
with opener.open(candidate,timeout=15) as response:
assert response.status==200;data=response.read()
assert len(data)==artifact.stat().st_size and hashlib.sha256(data).hexdigest()==digest
with opener.open(candidate+'.sha256',timeout=15) as response:
assert response.status==200 and response.read()==sidecar.read_bytes()
url=candidate;break
except Exception:pass
assert url, 'New APK exists; matching HTTP delivery unavailable. Preserve artifact and inspect before continuing.'
result={'version':'0.6.0','versionCode':11,'apk':str(artifact.relative_to(root)),
'bytes':artifact.stat().st_size,'sha256':digest,'url':url,'httpBytesVerified':True,
'signature':'apksigner_verified','sameCertificateAs':['0.5.1','0.5.2'],'deviceTestStatus':'pending'}
(logs/'release.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
PY
+64
View File
@@ -0,0 +1,64 @@
import com.gorios.lanvoice.avatar.*
import com.gorios.lanvoice.audio.PlaybackActivity
import com.gorios.lanvoice.dialogue.*
import android.content.Context
import android.media.MediaPlayer
import android.view.TextureView
fun main() {
val controller = AvatarController()
for (emotion in RoleEmotion.entries) for (intensity in if (emotion == RoleEmotion.NEUTRAL) listOf(0) else listOf(1,2)) {
val request = ReplyEmotion(emotion, intensity, EmotionSource.MODEL,7L,2)
val selected = controller.select(true,request,PlaybackActivity(7,3,true,960,1920))
check(selected.mode == AvatarMode.TALK && selected.requestedEmotion == request)
check(selected.resolvedAssetEmotion == AssetEmotion())
check(selected.emotionFallback == (emotion != RoleEmotion.NEUTRAL))
check(controller.select(false,request,PlaybackActivity(7,3,true,960,1920)).mode == AvatarMode.WAITING)
check(controller.select(true,request,PlaybackActivity(6,2,true,960,1920)).mode == AvatarMode.IDLE)
check(controller.select(true,request,null).mode == AvatarMode.IDLE)
}
val call = CallIntent()
check(!call.consumeStart(true,true,true))
check(call.dial(false,false) && !call.dial(false,false))
check(!call.consumeStart(true,true,false))
call.background(); check(call.pending)
call.cancel(); call.permissionResult(true)
check(!call.consumeStart(true,true,true)) // canceled permission cannot resurrect a call
check(call.dial(false,false)); call.permissionResult(false); check(!call.pending)
check(call.dial(false,true)); check(!call.consumeStart(true,false,true))
check(!call.consumeStart(false,true,true)); check(call.consumeStart(true,true,true))
check(!call.consumeStart(true,true,true))
call.resumeAfterCameraPermission(true); call.background(true)
check(call.consumeStart(true,true,true))
check(call.dial(false,true)); call.background(); check(!call.pending)
val view = AvatarVideoView(Context(),AvatarPack("idle.mp4","talk.mp4","static.png","waiting.png"))
view.render(AvatarMode.IDLE,true)
check(MediaPlayer.created.size == 2)
val players = MediaPlayer.created.toList()
check(players.all { it.looping && it.volume == 0f })
val textures = view.children.filterIsInstance<TextureView>()
players.forEach { it.prepared?.invoke(it) }
players[0].info?.invoke(players[0],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
view.render(AvatarMode.TALK,true)
check(textures.all { it.alpha == 0f }) // first-frame gate, static stays visible
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
check(textures[1].alpha == 1f && textures[0].alpha == 0f)
repeat(10) { view.render(if (it%2==0) AvatarMode.IDLE else AvatarMode.TALK,true) }
check(MediaPlayer.created.size == 2) // switches don't recreate or seek players
view.render(AvatarMode.WAITING,true)
check(players.all { it.released } && textures.all { it.alpha == 0f })
view.render(AvatarMode.IDLE,true)
check(MediaPlayer.created.size == 4)
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
check(textures.all { it.alpha == 0f }) // stale callbacks can't show old talk
val latest = MediaPlayer.created.takeLast(2)
latest[0].error?.invoke(latest[0],1,0)
check(latest.all { it.released } && textures.all { it.alpha == 0f })
view.render(AvatarMode.TALK,true); check(MediaPlayer.created.size == 4) // fail to static for the current run
view.render(AvatarMode.IDLE,false); view.render(AvatarMode.IDLE,true)
check(MediaPlayer.created.size == 6)
view.dispose(); check(MediaPlayer.created.all { it.released })
AvatarVideoView(Context(),null).render(AvatarMode.TALK,true)
println("PASS: seven requested labels preserved/neutral resolved fallback, old-turn fence; explicit dial/permission/cancel/background; actual video view two muted loops/first-frame gate/switch reuse/stale callback/failure/static/missing pack/lifecycle")
}
+2
View File
@@ -0,0 +1,2 @@
package android.os
object SystemClock { fun elapsedRealtime() = System.nanoTime()/1000000 }
+10
View File
@@ -0,0 +1,10 @@
package android.content
class Context { val assets = Assets() }
class Assets {
fun open(path: String) = java.io.ByteArrayInputStream(byteArrayOf())
fun openFd(path: String) = Descriptor()
}
class Descriptor : java.io.Closeable {
val fileDescriptor = java.io.FileDescriptor(); val startOffset = 0L; val length = 20L
override fun close() {}
}
+2
View File
@@ -0,0 +1,2 @@
package com.gorios.lanvoice.diag
object DiagnosticLog { fun record(tag: String,msg: String) {} }
+4
View File
@@ -0,0 +1,4 @@
package android.graphics
class Matrix { fun setScale(x: Float,y: Float,px: Float,py: Float) {} }
class SurfaceTexture
object BitmapFactory { fun decodeStream(input: java.io.InputStream): Any? = Any() }
+21
View File
@@ -0,0 +1,21 @@
package android.media
import android.view.Surface
class MediaPlayer {
companion object { const val MEDIA_INFO_VIDEO_RENDERING_START = 3; val created = mutableListOf<MediaPlayer>() }
init { created.add(this) }
var prepared: ((MediaPlayer)->Unit)? = null
var info: ((MediaPlayer,Int,Int)->Boolean)? = null
var error: ((MediaPlayer,Int,Int)->Boolean)? = null
var isLooping = false; val looping get() = isLooping
var volume = 1f; var released = false; var started = false
val videoWidth = 480; val videoHeight = 848
fun setSurface(surface: Surface) {}
fun setVolume(left: Float,right: Float) { volume = left }
fun setDataSource(fd: java.io.FileDescriptor, offset: Long,length: Long) {}
fun setOnPreparedListener(callback: (MediaPlayer)->Unit) { prepared = callback }
fun setOnInfoListener(callback: (MediaPlayer,Int,Int)->Boolean) { info = callback }
fun setOnErrorListener(callback: (MediaPlayer,Int,Int)->Boolean) { error = callback }
fun prepareAsync() {}
fun start() { started = true }
fun release() { released = true }
}
+3
View File
@@ -0,0 +1,3 @@
package com.gorios.lanvoice.avatar
// File loading is separately verified against imported APK bytes; no Android assets here.
data class AvatarPack(val idle: String,val talk: String,val fallback: String,val waiting: String)
+18
View File
@@ -0,0 +1,18 @@
package android.view
import android.content.Context
import android.graphics.SurfaceTexture
import android.graphics.Matrix
class Surface(texture: SurfaceTexture) { fun release() {} }
class TextureView(context: Context) {
var alpha = 1f; var isOpaque = true
val isAvailable = true; val surfaceTexture = SurfaceTexture()
val width = 480; val height = 848
var surfaceTextureListener: SurfaceTextureListener? = null
fun setTransform(matrix: Matrix) {}
interface SurfaceTextureListener {
fun onSurfaceTextureAvailable(texture: SurfaceTexture,w: Int,h: Int)
fun onSurfaceTextureSizeChanged(texture: SurfaceTexture,w: Int,h: Int)
fun onSurfaceTextureUpdated(texture: SurfaceTexture)
fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean
}
}
+14
View File
@@ -0,0 +1,14 @@
package android.widget
import android.content.Context
open class FrameLayout(val context: Context) {
class LayoutParams(w: Int,h: Int)
val children = mutableListOf<Any>()
fun addView(view: Any, params: LayoutParams) { children.add(view) }
open fun onDetachedFromWindow() {}
}
class ImageView(context: Context) {
enum class ScaleType { FIT_CENTER }
var scaleType = ScaleType.FIT_CENTER; var alpha = 1f
fun setImageBitmap(bitmap: Any?) {}
fun setImageDrawable(drawable: Any?) {}
}
@@ -24,6 +24,8 @@ fun main() {
check(cancel.click(false,false)==Action.STOP);check(cancel.permissionResult(true)==Action.NONE)
val released=gate();released.click(false,false);released.release()
check(released.permissionResult(true)==Action.NONE);check(released.onForeground()==Action.NONE)
val hungUp=gate();hungUp.click(false,false);hungUp.cancel()
check(hungUp.permissionResult(true)==Action.NONE);check(hungUp.onForeground()==Action.NONE)
val granted=gate();check(granted.click(false,true)==Action.START)
check(granted.click(true,true)==Action.STOP)
check(granted.permissionResult(true)==Action.NONE) // duplicate/stale result
+36
View File
@@ -0,0 +1,36 @@
import com.gorios.lanvoice.audio.PcmActivityTimeline
import com.gorios.lanvoice.audio.PlaybackHead
fun publicTone(samples: Int, value: Int = 2000) = ByteArray(samples * 2).also {
for (i in 0 until samples) { it[i*2] = value.toByte(); it[i*2+1] = (value shr 8).toByte() }
}
fun checkActivityTimeline() {
val head = PlaybackHead()
check(head.read(0xfffffff0.toInt()) == 0xfffffff0L)
check(head.read(32) == 0x1_0000_0020L)
head.reset(); check(head.read(0) == 0L)
val activity = PcmActivityTimeline()
activity.append(publicTone(300)); activity.append(publicTone(660)) // a cross-chunk 20ms window
check(!activity.sample(0,960,0)) // writing and queueing do not open mouth
check(!activity.sample(480,0,5)) // beyond accepted partial write never consumes activity
check(activity.sample(480,480,10))
check(activity.sample(960,960,20))
check(activity.sample(960,960,139))
check(!activity.sample(960,960,140)) // actual native underrun, TTS need not be ended
activity.append(ByteArray(48_000/5*2))
check(!activity.sample(10_560,10_560,240)) // 200ms silence closes
activity.append(publicTone(960))
check(activity.sample(11_520,11_520,260))
activity.reset(); check(!activity.sample(0,0,270))
activity.append(publicTone(100)) // final partial analysis window is playable immediately
check(activity.sample(100,100,280))
activity.reset(); activity.append(publicTone(960,100))
check(!activity.sample(960,960,300)) // low noise under RMS and peak thresholds
activity.reset()
repeat(2000) { activity.append(publicTone(960)); check(activity.sample((it+1)*960L,(it+1)*960L,400+it*20L)) }
check(activity.retainedWindows == 0) // continuous long playback prunes consumed metadata
val bounded = PcmActivityTimeline(maxWindows=2)
bounded.append(publicTone(1920))
check(runCatching { bounded.append(publicTone(960)) }.isFailure)
println("PASS: production PCM RMS/peak cross-block/partial/tail, no activity until playback head, silence/120ms underrun/resume/reset, u32 wrap and bounded/pruned metadata")
}
+2 -1
View File
@@ -14,6 +14,7 @@ class AudioTrack {
@Volatile var latest: AudioTrack? = null
@Volatile var advanceHead = true
@Volatile var rejectWrites = false
@Volatile var manualHead: Int? = null
fun getMinBufferSize(a: Int, b: Int, c: Int) = 320
}
class Builder {
@@ -29,7 +30,7 @@ class AudioTrack {
@Volatile var released = false
@Volatile var attempts = 0
val underrunCount get() = attempts / 4
val playbackHeadPosition get() = if (advanceHead && samples >= bufferSizeInFrames) samples else 0
val playbackHeadPosition get() = manualHead ?: if (advanceHead && samples >= bufferSizeInFrames) samples else 0
fun play() { playState = PLAYSTATE_PLAYING }
fun pause() { playState = 0 }
fun flush() { samples = 0; flushes++ }
+37
View File
@@ -9,6 +9,7 @@ fun awaitCheck(test: () -> Boolean) {
while (!test()) { check(System.nanoTime() < deadline) { "playback test timed out" }; Thread.sleep(2) }
}
fun main() {
checkActivityTimeline()
val drains = CopyOnWriteArrayList<Long>()
val failures = CopyOnWriteArrayList<Exception>()
val progress = CopyOnWriteArrayList<String>()
@@ -52,4 +53,40 @@ fun main() {
check(5L !in drains)
println("PASS: real AudioPlayback partial/zero writes, explicit end + native head drain, short tail, interruption fence, write failure, stalled head watchdog; device doubles, no real speaker")
} finally { player.release() }
checkActualActivityPlayback()
}
fun checkActualActivityPlayback() {
SystemClock.extra = 0
AudioTrack.rejectWrites = false; AudioTrack.manualHead = 0
val activities = CopyOnWriteArrayList<com.gorios.lanvoice.audio.PlaybackActivity>()
val drains = CopyOnWriteArrayList<Long>()
val errors = CopyOnWriteArrayList<Exception>()
val player = AudioPlayback({ turn, _ -> drains.add(turn) }, { _, error -> errors.add(error) }, onActivity = activities::add)
try {
player.beginTurn(70); player.enqueue(DownlinkFrame(70,1,publicTone(960)))
awaitCheck { AudioTrack.latest?.samples == 960 }
check(activities.isEmpty())
AudioTrack.manualHead = 960
awaitCheck { activities.lastOrNull()?.audible == true }
awaitCheck { activities.lastOrNull()?.audible == false } // software queue empty but TTS remains open
check(drains.isEmpty())
player.enqueue(DownlinkFrame(70,2,ByteArray(1920)))
awaitCheck { AudioTrack.latest?.samples == 1920 }
AudioTrack.manualHead = 1920
Thread.sleep(30); check(!activities.last().audible)
player.enqueue(DownlinkFrame(70,3,publicTone(960)))
awaitCheck { AudioTrack.latest?.samples == 2880 }
player.endTurn(70) // downlink stop still leaves native buffered speech
check(drains.isEmpty())
AudioTrack.manualHead = 2400
awaitCheck { activities.lastOrNull()?.audible == true }
AudioTrack.manualHead = 2880
awaitCheck { drains == listOf(70L) }
check(!activities.last().audible && errors.isEmpty())
val count = activities.size
player.interrupt(); Thread.sleep(30)
check(activities.size == count)
println("PASS: actual AudioPlayback head sampling continues during empty queue; queued PCM held silent, underrun idle, resumed speech talk, downlink end preserves buffered activity, drained/interrupt fences")
} finally { player.release(); AudioTrack.manualHead = null }
}
+8 -6
View File
@@ -5,19 +5,21 @@ import com.gorios.lanvoice.net.DownlinkFrame
enum class AecAvailability { AVAILABLE, UNAVAILABLE, UNKNOWN }
// No audio devices in callback propagation tests.
class AudioCapture {
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null }
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null; var starts = 0 }
fun aecAvailability() = AecAvailability.UNKNOWN
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit, onDiagnostic: (String) -> Unit = {}) { lastFrame = onFrame; lastError = onError; onDiagnostic("AudioRecord initialization ok") }
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit, onDiagnostic: (String) -> Unit = {}) { starts++; lastFrame = onFrame; lastError = onError; onDiagnostic("AudioRecord initialization ok") }
fun stop() {}
fun release() {}
}
class AudioPlayback(onDrained: (Long, Long) -> Unit, onError: (Long, Exception) -> Unit, onProgress: (Long, Long, String) -> Unit = { _, _, _ -> }) {
companion object { var interrupts = 0; var enqueued = 0; var lastDrained: ((Long, Long) -> Unit)? = null }
init { lastDrained = onDrained }
class AudioPlayback(onDrained: (Long, Long) -> Unit, onError: (Long, Exception) -> Unit, onProgress: (Long, Long, String) -> Unit = { _, _, _ -> }, onActivity: (PlaybackActivity) -> Unit = {}) {
companion object { var interrupts = 0; var enqueued = 0; var lastDrained: ((Long, Long) -> Unit)? = null
var lastActivity: ((PlaybackActivity) -> Unit)? = null
var activityFence: ((Long,Long)->Boolean)? = null }
init { lastDrained = onDrained; lastActivity = onActivity }
fun beginTurn(turn: Long) {}
fun endTurn(turn: Long) {}
fun enqueue(frame: DownlinkFrame): Boolean { enqueued++; return true }
fun isCurrent(turn: Long, epoch: Long) = true
fun isCurrent(turn: Long, epoch: Long) = activityFence?.invoke(turn,epoch) ?: true
fun isCurrent(epoch: Long) = true
fun interrupt() { interrupts++ }
fun release() {}
+49
View File
@@ -0,0 +1,49 @@
import android.os.Handler
import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.net.*
fun checkCallControls() {
val states = mutableListOf<VoiceUiState>()
val session = VoiceSession("localhost",5011,states::add)
fun set(name: String,value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
val dialogue = session.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(session) as DialogueClient
val socket = FakeSocket(); dialogue.setField("socket",socket); dialogue.setField("ready",true)
set("foreground",true); set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
val eventMethod = session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true }
fun event(kind: EventKind,turn: Long,state: String="") = eventMethod.invoke(session,ServerEvent(kind.name.lowercase(),kind,Payload(turn=turn,state=state)))
session.dial(); check(socket.sent.isEmpty()) // prepare WS never listens or records
val starts = AudioCapture.starts
session.startVoice(); session.startVoice(); check(AudioCapture.starts == starts+1)
event(EventKind.LISTEN,10,"start")
val prior = checkNotNull(AudioCapture.lastFrame)
prior(ByteArray(640)) // queued frame before mute must be discarded
val before = DialogueProtocol.uplinks.size
session.setMicrophoneMuted(true); Handler.drain()
check(DialogueProtocol.uplinks.size == before && states.last().microphoneMuted)
session.setMicrophoneMuted(false); checkNotNull(AudioCapture.lastFrame)(ByteArray(640)); Handler.drain()
check(DialogueProtocol.uplinks.last() == Triple(10L,1L,640))
session.setMicrophoneMuted(true); session.setMicrophoneMuted(false)
checkNotNull(AudioCapture.lastFrame)(ByteArray(640)); Handler.drain()
check(DialogueProtocol.uplinks.last() == Triple(10L,2L,640)) // mute never resets seq
event(EventKind.LISTEN,10,"stop")
val pausedStarts = AudioCapture.starts
session.setMicrophoneMuted(true); session.setMicrophoneMuted(false)
check(AudioCapture.starts == pausedStarts) // no mic takeover while recognizing/answering
val activity = checkNotNull(AudioPlayback.lastActivity)
AudioPlayback.activityFence = { _,generation -> generation == 7L }
activity(PlaybackActivity(10,6,true,960,1920)); Handler.drain(); check(states.last().playbackActivity == null)
activity(PlaybackActivity(10,7,true,960,1920)); Handler.drain(); check(states.last().playbackActivity?.audible == true)
activity(PlaybackActivity(10,7,false,1920,1920)); Handler.drain(); check(states.last().playbackActivity?.audible == false)
activity(PlaybackActivity(10,7,true,1920,2880)); session.interrupt(); Handler.drain()
check(states.last().playbackActivity == null)
event(EventKind.LISTEN,11,"start")
activity(PlaybackActivity(10,7,true,1920,2880)); Handler.drain(); check(states.last().playbackActivity == null)
val enqueued = AudioPlayback.enqueued
session.hangUp()
check(!states.last().voiceActive && states.last().connection == ConnectionStatus.DISCONNECTED && states.last().playbackActivity == null)
val frame = session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
frame.invoke(session,DownlinkFrame(11)); activity(PlaybackActivity(11,7,true,960,1920)); Handler.drain()
check(AudioPlayback.enqueued == enqueued && states.last().playbackActivity == null)
session.release(); AudioPlayback.activityFence = null
println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences")
}
+1
View File
@@ -481,6 +481,7 @@ fun runChecks() {
}
fun main() {
checkCallControls()
checkFaceTransmission()
run {
val normal = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "model")!!