Enable reviewed Liam dances and add playback-driven voice status
This commit is contained in:
@@ -39,6 +39,25 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
|
||||
val renderer=checkNotNull(currentRenderer())
|
||||
await { gear()!=null }
|
||||
assertClean()
|
||||
runOnMainSync {
|
||||
val indicator=VoiceStatusView(activity)
|
||||
indicator.animate=false
|
||||
val size=(36*activity.resources.displayMetrics.density).toInt()
|
||||
indicator.measure(View.MeasureSpec.makeMeasureSpec(size,View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(size,View.MeasureSpec.EXACTLY))
|
||||
indicator.layout(0,0,size,size)
|
||||
val bitmap=android.graphics.Bitmap.createBitmap(size,size,android.graphics.Bitmap.Config.ARGB_8888)
|
||||
val canvas=android.graphics.Canvas(bitmap)
|
||||
check(indicator.visibility==View.GONE)
|
||||
for(state in listOf(VoiceStatusView.State.LISTENING,VoiceStatusView.State.SPEAKING)) {
|
||||
indicator.state=state;indicator.speechLevel=.5f
|
||||
bitmap.eraseColor(android.graphics.Color.TRANSPARENT);indicator.draw(canvas)
|
||||
val pixels=IntArray(size*size);bitmap.getPixels(pixels,0,size,0,0,size,size)
|
||||
check(pixels.any { android.graphics.Color.alpha(it)>0 })
|
||||
check(indicator.visibility==View.VISIBLE && !indicator.contentDescription.isNullOrBlank())
|
||||
}
|
||||
indicator.state=VoiceStatusView.State.IDLE;check(indicator.visibility==View.GONE)
|
||||
bitmap.recycle()
|
||||
}
|
||||
val gear=checkNotNull(gear()); val bounds=android.graphics.Rect();gear.getBoundsInScreen(bounds)
|
||||
val minimum=(48*targetContext.resources.displayMetrics.density).toInt()-1
|
||||
check(bounds.width()>=minimum && bounds.height()>=minimum) { "Gear touch target below 48dp" }
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.sin
|
||||
|
||||
/** Overlay at TOP|END. No microphone permission or network access required. */
|
||||
class VoiceStatusView @JvmOverloads constructor(
|
||||
context: Context, attrs: AttributeSet? = null
|
||||
) : View(context, attrs) {
|
||||
enum class State { IDLE, LISTENING, SPEAKING }
|
||||
var state: State = State.IDLE
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
field = value
|
||||
contentDescription = when (value) {
|
||||
State.IDLE -> ""
|
||||
State.LISTENING -> "数字角色聆听中"
|
||||
State.SPEAKING -> "数字角色正在说话"
|
||||
}
|
||||
visibility = if (value == State.IDLE) GONE else VISIBLE
|
||||
epoch = android.os.SystemClock.uptimeMillis()
|
||||
invalidate()
|
||||
}
|
||||
/** Supply normalized TTS playback amplitude [0..1] for synchronized speech bars. */
|
||||
var speechLevel: Float? = null
|
||||
set(value) { field = value?.takeIf { it.isFinite() }?.coerceIn(0f, 1f); invalidate() }
|
||||
var animate: Boolean = true
|
||||
set(value) { field = value; invalidate() }
|
||||
private val d = resources.displayMetrics.density
|
||||
private val p = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private var epoch = android.os.SystemClock.uptimeMillis()
|
||||
private val cyan = Color.rgb(130, 237, 224)
|
||||
private val violet = Color.rgb(203, 187, 255)
|
||||
init { visibility = GONE; importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES }
|
||||
override fun onMeasure(w: Int, h: Int) {
|
||||
setMeasuredDimension(resolveSize((36*d).toInt(), w), resolveSize((36*d).toInt(), h))
|
||||
}
|
||||
override fun onDraw(c: Canvas) {
|
||||
super.onDraw(c)
|
||||
if (state == State.IDLE) return
|
||||
val save = c.save()
|
||||
c.scale(width / 36f, height / 36f)
|
||||
val t = if (animate) (android.os.SystemClock.uptimeMillis()-epoch)/1000f else 0f
|
||||
val accent = if (state == State.LISTENING) cyan else violet
|
||||
p.style = Paint.Style.STROKE
|
||||
p.color = accent; p.strokeWidth = 1.7f; p.strokeCap = Paint.Cap.ROUND
|
||||
if (state == State.LISTENING) {
|
||||
// Recognizable microphone; two gentle rings convey attentive listening.
|
||||
c.drawRoundRect(RectF(15f,9f,21f,20f),3f,3f,p)
|
||||
c.drawArc(RectF(12f,12f,24f,25f),0f,180f,false,p)
|
||||
c.drawLine(18f,25f,18f,28f,p); c.drawLine(15f,28f,21f,28f,p)
|
||||
for (i in 0..1) {
|
||||
val phase = (t/1.8f+i*.5f)%1f
|
||||
p.color = Color.argb(((1-phase)*65).toInt(),130,237,224)
|
||||
c.drawCircle(18f,18f,11f+phase*5f,p)
|
||||
}
|
||||
} else {
|
||||
p.style = Paint.Style.FILL; p.color = accent
|
||||
for (i in 0..4) {
|
||||
val wave = (.5f+.5f*sin(t*2*PI*1.2+i*1.35)).toFloat()
|
||||
val level = speechLevel
|
||||
val bar = if (level != null) 4f+18f*level*(.45f+.55f*wave) else 5f+17f*wave
|
||||
val x = 7.4f+i*4.6f
|
||||
c.drawRoundRect(RectF(x,18f-bar/2,x+2.8f,18f+bar/2),1.4f,1.4f,p)
|
||||
}
|
||||
}
|
||||
c.restoreToCount(save)
|
||||
if (animate && isAttachedToWindow && isShown && windowVisibility == VISIBLE) postInvalidateOnAnimation()
|
||||
}
|
||||
override fun onWindowVisibilityChanged(visibility: Int) {
|
||||
super.onWindowVisibilityChanged(visibility)
|
||||
if (visibility == VISIBLE) invalidate()
|
||||
}
|
||||
override fun onVisibilityChanged(changedView: View, visibility: Int) {
|
||||
super.onVisibilityChanged(changedView, visibility)
|
||||
if (visibility == VISIBLE) invalidate()
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ class AudioPlayback(
|
||||
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 onPlaying: (turnId: Long, generation: Long, playing: Boolean) -> Unit = { _, _, _ -> },
|
||||
) {
|
||||
private val lock = Object()
|
||||
private val queue = ArrayDeque<ByteArray>()
|
||||
@@ -33,6 +34,7 @@ class AudioPlayback(
|
||||
private val headCounter = PlaybackHead()
|
||||
private val activity = PcmActivityTimeline()
|
||||
private var audible = false
|
||||
private var playing = false
|
||||
|
||||
init {
|
||||
Thread(::play, "lan-voice-playback").apply { isDaemon = true; start() }
|
||||
@@ -93,6 +95,7 @@ class AudioPlayback(
|
||||
headCounter.reset()
|
||||
activity.reset()
|
||||
audible = false
|
||||
playing = false
|
||||
track?.let {
|
||||
try { it.pause(); it.flush() } catch (_: IllegalStateException) { }
|
||||
}
|
||||
@@ -142,6 +145,10 @@ class AudioPlayback(
|
||||
val head = headCounter.read(device.playbackHeadPosition)
|
||||
if (lastAdvanceMs == 0L || head != lastHead || writtenSamples <= head) lastAdvanceMs = now
|
||||
lastHead = head
|
||||
if(!playing && head > 0) {
|
||||
playing = true
|
||||
onPlaying(id,epoch,true)
|
||||
}
|
||||
val active = activity.sample(head, writtenSamples, now)
|
||||
if (active != audible) {
|
||||
audible = active
|
||||
@@ -235,6 +242,7 @@ class AudioPlayback(
|
||||
audible = false
|
||||
onActivity(PlaybackActivity(id, epoch, false, played, writtenSamples))
|
||||
}
|
||||
if(playing) { playing = false; onPlaying(id,epoch,false) }
|
||||
drained = true
|
||||
true
|
||||
} else false
|
||||
|
||||
@@ -25,6 +25,7 @@ import com.gorios.lanvoice.expression.PresenceOutcome
|
||||
import com.gorios.lanvoice.expression.PresenceServerReason
|
||||
|
||||
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
|
||||
enum class VoiceIndicatorState { IDLE, LISTENING, SPEAKING }
|
||||
|
||||
data class VoiceUiState(
|
||||
val connection: ConnectionStatus = ConnectionStatus.DISCONNECTED,
|
||||
@@ -38,7 +39,15 @@ data class VoiceUiState(
|
||||
val microphoneMuted: Boolean = false,
|
||||
val actionActive: Boolean = false,
|
||||
val turnId: Long? = null,
|
||||
val captureActive: Boolean = false,
|
||||
val playbackRunning: Boolean = false,
|
||||
) {
|
||||
val voiceIndicator: VoiceIndicatorState get() = when {
|
||||
!voiceActive || connection != ConnectionStatus.CONNECTED || actionActive -> VoiceIndicatorState.IDLE
|
||||
phase == VoicePhase.ANSWERING && playbackRunning -> VoiceIndicatorState.SPEAKING
|
||||
phase == VoicePhase.LISTENING && captureActive && !microphoneMuted -> VoiceIndicatorState.LISTENING
|
||||
else -> VoiceIndicatorState.IDLE
|
||||
}
|
||||
val roleLabel: String get() = when {
|
||||
phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label
|
||||
voiceActive && phase in setOf(VoicePhase.RECOGNIZING, VoicePhase.THINKING, VoicePhase.ANSWERING) -> "等待回复"
|
||||
@@ -106,6 +115,7 @@ class VoiceSession(
|
||||
private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime,
|
||||
stopCapture = { confirmed ->
|
||||
captureEpoch++; capturing = false
|
||||
if(state.captureActive) update(state.copy(captureActive = false))
|
||||
diagnostic("action_capture state=stop_pending turn=$currentTurn epoch=$captureEpoch")
|
||||
capture.stopAndConfirm { stopped -> main.post {
|
||||
diagnostic("action_capture state=${if(stopped) "stop_confirmed" else "stop_failed"} turn=$currentTurn epoch=$captureEpoch")
|
||||
@@ -163,6 +173,14 @@ class VoiceSession(
|
||||
if(reason=="accepted") update(state.copy(playbackActivity = activity))
|
||||
}
|
||||
},
|
||||
onPlaying = { turn, epoch, playing ->
|
||||
main.post {
|
||||
if(isActive() && !actions.active && playbackIsCurrent(turn,epoch) &&
|
||||
currentTurn==turn && blockedTurn!=turn && emotionEndedTurn!=turn) {
|
||||
update(state.copy(playbackRunning = playing))
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
private val dialogue: DialogueClient = DialogueClient(
|
||||
host, port,
|
||||
@@ -516,6 +534,8 @@ class VoiceSession(
|
||||
onFrame = { pcm ->
|
||||
main.post {
|
||||
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive()) {
|
||||
// First real recorder frame, rather than a listen command or permission.
|
||||
if(!state.captureActive) update(state.copy(captureActive = true))
|
||||
if (dialogue.sendAudio(pcm, captureTurn, sequence)) {
|
||||
sequence = (sequence + 1) and UINT32_MASK
|
||||
}
|
||||
@@ -541,6 +561,7 @@ class VoiceSession(
|
||||
private fun stopCapture() {
|
||||
captureEpoch++
|
||||
capturing = false
|
||||
if(state.captureActive) update(state.copy(captureActive = false))
|
||||
capture.stop()
|
||||
}
|
||||
|
||||
@@ -769,7 +790,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(), playbackActivity = null,
|
||||
update(state.copy(replyEmotion = ReplyEmotion(), playbackActivity = null, playbackRunning = false,
|
||||
previousReplyEmotion = if (played) expression else state.previousReplyEmotion))
|
||||
}
|
||||
|
||||
|
||||
@@ -43,10 +43,14 @@ private val NoUiAction: ()->Unit = {}
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composable ()->Unit,
|
||||
startupStage: String="ready",connecting: Boolean=false) {
|
||||
startupStage: String="ready",connecting: Boolean=false,
|
||||
voiceStatus: com.gorios.lanvoice.VoiceStatusView.State=com.gorios.lanvoice.VoiceStatusView.State.IDLE) {
|
||||
var settingsOpen by rememberSaveable { mutableStateOf(false) }
|
||||
Box(Modifier.fillMaxSize().background(Color.White).testTag("avatar_home")) {
|
||||
avatar()
|
||||
AndroidView(factory={com.gorios.lanvoice.VoiceStatusView(it)},update={it.state=voiceStatus},
|
||||
modifier=Modifier.align(Alignment.TopEnd).windowInsetsPadding(WindowInsets.safeDrawing)
|
||||
.padding(12.dp).size(36.dp).testTag("voice_status"))
|
||||
StartupStatus(startupStage,connecting,Modifier.align(Alignment.BottomStart)
|
||||
.windowInsetsPadding(WindowInsets.safeDrawing).padding(start=16.dp,end=88.dp,bottom=16.dp))
|
||||
IconButton(onClick={settingsOpen=true},modifier=Modifier.align(Alignment.BottomEnd)
|
||||
@@ -201,7 +205,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
TextButton(onClick=onOfflinePreview) { Text("离线播放检查(停止当前会话)") }
|
||||
reportResult?.let { Text(it,fontSize=12.sp) }
|
||||
Text(logs.takeLast(10).joinToString("\n"),fontSize=11.sp)
|
||||
},startupStage=startupStage,connecting=BuildConfig.AVATAR_STARTUP_FIX && entry==EntryPhase.CONNECTING)
|
||||
},startupStage=startupStage,connecting=BuildConfig.AVATAR_STARTUP_FIX && entry==EntryPhase.CONNECTING,
|
||||
voiceStatus=com.gorios.lanvoice.VoiceStatusView.State.valueOf(state.voiceIndicator.name))
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
Reference in New Issue
Block a user