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
+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")!!