From 515d106da748cf4e7450d8b53d0077689dfe2d1c Mon Sep 17 00:00:00 2001 From: zenord Date: Tue, 13 Oct 2026 02:09:38 +0800 Subject: [PATCH] Wire reviewed emotion bridges and action media playback fences --- app/build.gradle | 4 + .../java/com/gorios/lanvoice/MainActivity.kt | 8 + .../com/gorios/lanvoice/audio/VoiceSession.kt | 14 +- .../lanvoice/avatar/ActionController.kt | 29 ++- .../lanvoice/avatar/AvatarMediaBinding.kt | 34 +++ .../com/gorios/lanvoice/avatar/AvatarPack.kt | 37 ++- .../com/gorios/lanvoice/avatar/CallScreen.kt | 21 +- .../lanvoice/avatar/ContinuousBodyRenderer.kt | 77 ++++++- .../avatar/ContinuousFramePresenter.kt | 19 +- .../gorios/lanvoice/avatar/ContinuousMouth.kt | 6 +- .../avatar/ConversationMediaDriver.kt | 218 ++++++++++++++++++ .../avatar/EmotionActionAvatarView.kt | 148 ++++++++++++ .../lanvoice/avatar/EmotionActionManifest.kt | 26 ++- docs/ACTION_EMOTION_STAGE_070.md | 71 +++++- docs/AVATAR_PACK_V2_CONTRACT.md | 39 +++- scripts/check-avatar-ui.py | 5 + scripts/check-reply-regressions.py | 2 +- tests/avatar/ActionCheck.kt | 14 +- tests/avatar/AvatarCheck.kt | 2 + tests/avatar/CodecMedia.kt | 17 +- tests/avatar/Context.kt | 6 +- tests/avatar/EmotionActionCheck.kt | 2 + tests/avatar/Media.kt | 3 + tests/avatar/MediaBoundaryCheck.kt | 76 ++++++ tests/avatar/MediaWiringCheck.kt | 133 +++++++++++ tests/avatar/Pack.kt | 3 +- tests/avatar/View.kt | 2 +- tests/session/ActionSessionCheck.kt | 10 +- 28 files changed, 961 insertions(+), 65 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt create mode 100644 tests/avatar/MediaBoundaryCheck.kt create mode 100644 tests/avatar/MediaWiringCheck.kt diff --git a/app/build.gradle b/app/build.gradle index 44baf9a..9380ba4 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -29,6 +29,8 @@ if (avatarUiCandidate && !avatarNatural) { throw new GradleException('UI candidate requires the pinned natural debug runtime') } def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?: '' +def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: '' +if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA') if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) { throw new GradleException('Natural debug candidate requires exact runtime manifest SHA') } @@ -93,12 +95,14 @@ android { buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false' buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', avatarMouthCandidate ? 'true' : 'false' buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '"' + (avatarNatural ? naturalManifestSha : '') + '"' + buildConfigField 'String', 'EMOTION_MANIFEST_SHA', '"' + emotionManifestSha + '"' } release { buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false' buildConfigField 'boolean', 'AVATAR_NATURAL', 'false' buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', 'false' buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '""' + buildConfigField 'String', 'EMOTION_MANIFEST_SHA', '""' } } androidResources { noCompress += ['task', 'mp4'] } diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index 6e006db..b02144a 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -55,6 +55,7 @@ class MainActivity : ComponentActivity() { private val pump = Runnable { advanceEntry() } private val retryTimer = Runnable { advanceEntry() } private var avatarPack: AvatarPack? = null + private val avatarMedia=com.gorios.lanvoice.avatar.AvatarMediaBinding() private var expressionState by mutableStateOf(ExpressionUiState()) private lateinit var expressions: ExpressionController private var inForeground = false @@ -170,6 +171,9 @@ class MainActivity : ComponentActivity() { onState = { val lostConnection = state.connection == ConnectionStatus.CONNECTED && it.connection != ConnectionStatus.CONNECTED state = it + avatarMedia.beginTurn(it.turnId) + avatarMedia.intent(it.replyEmotion.takeIf { role->role.turnId!=null }, + it.playbackActivity?.audible==true && !it.actionActive) if (lostConnection && ::expressions.isInitialized) closeCamera() entry.connection(it.connection == ConnectionStatus.CONNECTED, it.connection == ConnectionStatus.CONNECTING, android.os.SystemClock.elapsedRealtime(), it.connection == ConnectionStatus.BUSY) @@ -178,6 +182,9 @@ class MainActivity : ComponentActivity() { onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) }, onPreparePlayback = audioOutput::prepare, onVoiceStopped = audioOutput::release, + reviewedActionPack = avatarPack?.emotionAction?.actionPack, + actionPlayer = avatarMedia, + onPrepareExpression = avatarMedia::prepare, ) expressions = ExpressionController(this, this, onState = { @@ -194,6 +201,7 @@ class MainActivity : ComponentActivity() { connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt, micGranted,cameraGranted,permissionPending,::authorizeCamera, onCancelAction = session::cancelAction, + mediaBinding = avatarMedia, ) } } diff --git a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt index 5ab12bc..1fff8af 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -32,6 +32,7 @@ data class VoiceUiState( val playbackActivity: PlaybackActivity? = null, val microphoneMuted: Boolean = false, val actionActive: Boolean = false, + val turnId: Long? = null, ) { val roleLabel: String get() = when { phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label @@ -65,6 +66,7 @@ class VoiceSession( private var blockedTurn: Long? = null private var sequence = 1L private var preparedPlaybackTurn: Long? = null + private var drainedTurn: Long? = null private var emotionEndedTurn: Long? = null private var faceSharing = false private var faceSupported = false @@ -96,6 +98,7 @@ class VoiceSession( if (isActive() && !actions.active && playbackIsCurrent(turn, epoch) && blockedTurn != turn) { diagnostic("playback drained turn=$turn") if (dialogue.playbackDrained(turn)) { + drainedTurn=turn resetReply("drained") emotionEndedTurn = turn update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) @@ -339,7 +342,8 @@ class VoiceSession( retiredTurns.clear() blockedTurn = null sequence = 1 - update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion(), microphoneMuted = false)) + drainedTurn=null + update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion(), microphoneMuted = false,turnId=null)) } else update(state.copy( connection = connection, // onStop runs while the screen is hidden. Keep the reason visible on @@ -406,7 +410,7 @@ class VoiceSession( else if (event.type == "action.plan") { val id = event.payload.optString("action_id") val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L - if (!actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl))) + if (drainedTurn!=currentTurn || !actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl))) dialogue.actionStatus(ActionStatus(id,currentTurn,"failed")) else if(actions.active) { actionTimeout?.let { main.removeCallbacks(it) } @@ -502,6 +506,7 @@ class VoiceSession( if (!isActive() || actions.active || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) || blockedTurn == frame.turnId) return if (preparedPlaybackTurn != frame.turnId) { + drainedTurn=null val failure = onPreparePlayback() if (failure != null) { outputUnavailable(failure); return } preparedPlaybackTurn = frame.turnId @@ -528,9 +533,10 @@ class VoiceSession( if (hasTurn) retiredTurns.add(currentTurn) playback.interrupt() preparedPlaybackTurn = null + drainedTurn=null currentTurn = id emotionEndedTurn = null - update(state.copy(replyEmotion = ReplyEmotion())) + update(state.copy(replyEmotion = ReplyEmotion(),turnId=id)) hasTurn = true sequence = 1 if (blockedTurn != id) blockedTurn = null @@ -554,7 +560,6 @@ class VoiceSession( else -> null } if (reason != null) { diagnostic("role ignore reason=$reason turn=$turn"); return } - onPrepareExpression(null) val expression = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"), event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source"), event.payload.opt("reason"), event.payload.opt("parse_branch"), event.payload.opt("finish_reason")) @@ -563,6 +568,7 @@ class VoiceSession( diagnostic("role ignore reason=old_seq turn=$turn seq=${expression.sequence}"); return } update(state.copy(replyEmotion = expression)) + onPrepareExpression(null) diagnostic("role apply turn=$turn seq=${expression.sequence} emotion=${expression.emotion.wire} intensity=${expression.intensity} source=${expression.source.name.lowercase()} reason=${expression.reason.wire} branch=${expression.parseBranch.wire} finish=${expression.finishReason.wire}") } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt index 117f50e..e37bfcf 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt @@ -1,6 +1,9 @@ package com.gorios.lanvoice.avatar -data class ActionAsset(val id: String, val durationMs: Long) +data class ActionMedia(val path: String,val sha256: String,val root: String,val ptsUs: List, + val durationUs: Long,val width: Int,val height: Int,val sourcePackage: String,val sourceFrame: Int, + val returnPackage: String,val returnFrame: Int,val audioEndUs: Long) +data class ActionAsset(val id: String, val durationMs: Long,val media: ActionMedia?=null) data class ReviewedActionPack(val manifestSha: String, val assets: List) data class ActionPlan(val id: String, val turn: Long, val packSha: String, val ttlMs: Long) data class ActionStatus(val id: String, val turn: Long, val status: String, val asset: String? = null, @@ -27,6 +30,10 @@ class ActionController( private var plan: ActionPlan? = null private var previous: String? = null private var stopping = false + private var capturePending=false + private var captureSafe=true + private var mediaReleased=false + private var cancellation: Pair?=null val active get() = plan != null || stopping private var deadline = 0L private var started = 0L @@ -43,7 +50,13 @@ class ActionController( val asset = candidates[choose(candidates.size)] val fence = ++generation plan = next; deadline = clock()+next.ttlMs; changed(true) + capturePending=true;captureSafe=false + var acknowledged=false stopCapture { confirmed -> + if(acknowledged || (plan!=next && cancellation?.first!=next)) return@stopCapture + acknowledged=true + capturePending=false;captureSafe=confirmed + if(stopping) { finishCancellation();return@stopCapture } if (fence != generation || plan != next) return@stopCapture if (!confirmed || clock() >= deadline) { cancel("failed"); return@stopCapture } started = clock(); previous = asset.id @@ -66,12 +79,20 @@ class ActionController( fun cancel(reason: String = "cancelled") { val old = plan ?: return generation++; plan = null; stopping = true + cancellation=old to if(reason=="failed") "failed" else "cancelled" + mediaReleased=false player.stop { - stopping = false - status(ActionStatus(old.id,old.turn,if (reason == "failed") "failed" else "cancelled")) - changed(false) + mediaReleased=true;finishCancellation() } } + private fun finishCancellation() { + if(!stopping || !mediaReleased || capturePending) return + val (old,reason)=cancellation ?: return + cancellation=null + status(ActionStatus(old.id,old.turn,if(captureSafe) reason else "failed")) + // Unknown/failed recording stop never enables another recording session. + if(captureSafe) { stopping=false;changed(false) } + } } /** Production default while no independently approved dance pack exists. */ diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt new file mode 100644 index 0000000..14e35c5 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt @@ -0,0 +1,34 @@ +package com.gorios.lanvoice.avatar + +import com.gorios.lanvoice.dialogue.ReplyEmotion + +/** One Activity-owned binding shared by VoiceSession and its persistent avatar view. */ +class AvatarMediaBinding : ActionPlayer { + private var driver: ConversationMediaDriver?=null + private var prepared: ReplyEmotion?=null + private var reply: ReplyEmotion?=null + private var talking=false + private var turn: Long?=null + private var onReleased: ()->Unit={} + fun attach(value: ConversationMediaDriver,onReleased: (()->Unit)?=null) { + check(driver==null || driver===value);driver=value + if(onReleased!=null) this.onReleased=onReleased + value.beginTurn(turn);value.intent(reply,talking);value.prepareExpression(prepared) + } + fun detach(value: ConversationMediaDriver) { if(driver===value) driver=null } + fun prepare(value: ReplyEmotion?) { prepared=value;driver?.prepareExpression(value) } + fun beginTurn(id: Long?) { + if(id!=turn) { prepared=null;reply=null;talking=false } + turn=id;driver?.beginTurn(id) + } + fun intent(value: ReplyEmotion?,talk: Boolean) { + reply=value;talking=talk;driver?.intent(value,talk) + } + override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { + driver?.play(asset,finished,failed) ?: failed() + } + override fun stop(released: ()->Unit) { + val current=driver + current?.stop { released();if(driver===current) onReleased() } ?: released() + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt index 8f8db0b..82f3974 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt @@ -9,7 +9,7 @@ import com.gorios.lanvoice.BuildConfig /** Static identity approval and motion approval are independent. No metadata self-approval. */ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback: String, val waiting: String = fallback, val safeGraph: SafeAvatarGraph? = null, val pathRoot: String = "", val motionStatus: String = "anchor_review_pending", - val continuous: ContinuousAvatarPack? = null) { + val continuous: ContinuousAvatarPack? = null,val emotionAction: EmotionActionIndex?=null) { companion object { const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2" private const val STATIC_ROOT = "avatar/a01-standing-arms-reference/" @@ -21,6 +21,32 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) } catch (_: Exception) { return null } val static = AvatarPack(fallback=fallback) + if(BuildConfig.DEBUG && BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) { + val admitted=try { + val root="avatar/a01-expression-action-v1/" + val raw=read(context,root+"manifest.json",2_000_000) + val index=checkNotNull(EmotionActionManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw), + BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash -> + val runtimeRoot=root+path.substringBeforeLast('/')+"/" + val bytes=read(context,root+path,2_000_000) + check(sha(bytes)==hash) + val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot)) + verifyRuntime(context,runtime);runtime + }) + var total=0L + for(clip in index.edges.map { it.clip }) { + val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size + check(total<=512_000_000) + } + for(asset in index.actionPack?.assets.orEmpty()) { + val media=checkNotNull(asset.media);val data=read(context,media.root+media.path,128_000_000) + check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000) + } + static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph") + } catch(_: Exception) { null } + if(admitted!=null) return admitted + // Continue into independently pinned neutral admission as a whole pack. + } if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try { val root=MOTION_ROOT+(if(BuildConfig.AVATAR_MOUTH_CANDIDATE) "runtime-04/" else "runtime-03/") val raw=read(context,root+"manifest.json",512_000) @@ -82,6 +108,15 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback safeGraph=graph,pathRoot=MOTION_ROOT,motionStatus="approved") } catch (_: Exception) { static.copy(motionStatus="pack_unavailable") } } + private fun verifyRuntime(context: Context,runtime: ContinuousAvatarPack) { + check(sha(read(context,runtime.root+runtime.body.path,64_000_000))==runtime.body.sha256) + runtime.textureImages.forEachIndexed { i,image -> + val bytes=read(context,runtime.root+image.path,256_000);check(sha(bytes)==image.sha256) + val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true } + android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options) + val patch=runtime.patches[i/5];check(options.outWidth==patch.width && options.outHeight==patch.height) + } + } private fun read(context: Context,path: String,maximum: Int): ByteArray = context.assets.open(path).use { val data = it.readBytesBounded(maximum); data } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt index ae668ff..14f4c5b 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt @@ -78,6 +78,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, logs: List,onReport: ()->Unit,reportSending: Boolean,reportResult: String?,onInterrupt: ()->Unit, micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit, onCancelAction: ()->Unit, + mediaBinding: AvatarMediaBinding?=null, ) { val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive }) val latestAvatar by rememberUpdatedState(avatar) @@ -91,7 +92,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, } } CleanAvatarScaffold(avatar={ - AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize()) { video=it } + AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding) { video=it } },settings={ val status=when(entry) { EntryPhase.CONNECTING -> "正在连接" @@ -206,7 +207,23 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted } @Composable -private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, turn: Long?, audioEpoch: Long?, modifier: Modifier, onPresentation: (VideoPresentation) -> Unit) { +private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, turn: Long?, audioEpoch: Long?, modifier: Modifier, + mediaBinding: AvatarMediaBinding?=null,onPresentation: (VideoPresentation) -> Unit) { + if(pack?.emotionAction!=null && mediaBinding!=null) { + val activity=LocalContext.current as ComponentActivity + val latest by rememberUpdatedState(onPresentation) + val view=remember(pack,mediaBinding) { EmotionActionAvatarView(activity,pack,mediaBinding) { latest(it) } } + SideEffect { view.render(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) } + DisposableEffect(view) { + val observer=LifecycleEventObserver { _,event-> + if(event==Lifecycle.Event.ON_PAUSE) view.render(false) + if(event==Lifecycle.Event.ON_RESUME) view.render(true) + } + activity.lifecycle.addObserver(observer) + onDispose { activity.lifecycle.removeObserver(observer);view.dispose() } + } + AndroidView(factory={view},modifier=modifier);return + } if (BuildConfig.AVATAR_NATURAL) { ContinuousPortrait(pack,mode,turn,audioEpoch,modifier,onPresentation) return diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt index e59c6a6..d281557 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt @@ -27,12 +27,17 @@ import java.util.concurrent.atomic.AtomicBoolean * Only small patch bitmaps are cached at startup. Audio never waits on this worker. */ class ContinuousBodyRenderer(private val context: Context,private val pack: ContinuousAvatarPack, private val output: Surface,private var width: Int,private var height: Int, - private val presented: (ComposedBodyFrame,Long)->Unit,private val failure: (String)->Unit) { + private val presented: (ComposedBodyFrame,Long)->Unit,private val failure: (String)->Unit, + private val automatic: Boolean=true,private val startFrame: Int=0,private val mayLoop: Boolean=true, + private val mouthEnabled: Boolean=true,private val ended: ()->Unit={}) { private val alive=AtomicBoolean(true) + private val releaseLock=Any() + private val releaseCallbacks=mutableListOf<()->Unit>() + private var releaseComplete=false private val thread=HandlerThread("avatar-body-gl").apply { start() } private val worker=Handler(thread.looper) private val main=Handler(Looper.getMainLooper()) - private val gate=ContinuousFramePresenter(pack) + private val gate=ContinuousFramePresenter(pack,mouthEnabled=mouthEnabled,startFrame=startFrame) private var display: EGLDisplay=EGL14.EGL_NO_DISPLAY private var eglContext: EGLContext=EGL14.EGL_NO_CONTEXT private var window: EGLSurface=EGL14.EGL_NO_SURFACE @@ -45,9 +50,11 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont private var lastIndex=-1 private var lastPresentedMs=0L private var first=true + private var held=false + private var preroll=true private var program=0 private var bodyTexture=0 - private val patchTextures=IntArray(pack.textureImages.size) + private val patchTextures=IntArray(if(mouthEnabled) pack.textureImages.size else 1) private val textureMatrix=FloatArray(16) private val positions=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer() private val uv=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply { @@ -58,12 +65,29 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont private var startedMs=SystemClock.elapsedRealtime() private var progressMs=startedMs private val timeout=Runnable { fail("frame_timeout") } + private val heldTick=object: Runnable { + override fun run() { guarded { + if(!held || !mouthEnabled) return@guarded + val value=gate.recompose(SystemClock.elapsedRealtime()) { draw(it) } ?: return@guarded + val elapsed=SystemClock.elapsedRealtime()-startedMs + main.post { if(alive.get()) presented(value,elapsed) } + worker.postDelayed(this,20) + } } + } init { worker.post { guarded { initialize(); pump() } } } fun intent(talk: Boolean,generation: Long,revision: Long) { worker.post { if(alive.get()) gate.intent(talk,generation,revision,SystemClock.elapsedRealtime()) } } fun resize(w: Int,h: Int) { worker.post { if(alive.get()) { width=w; height=h } } } + fun advance() { worker.post { guarded { if(held) { + held=false;worker.removeCallbacks(heldTick) + // Hidden entry may be held for an entire source loop. Decode watchdog and + // next display interval begin at this explicit reveal/advance, not preload. + progressMs=SystemClock.elapsedRealtime();lastPresentedMs=progressMs + continueBody() + } } } } private fun initialize() { - check(pack.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES && pack.patches.size==pack.body.frameCount) + check(pack.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES && (!mouthEnabled || pack.patches.size==pack.body.frameCount)) + check(startFrame in pack.body.ptsUs.indices) display=EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);check(display!=EGL14.EGL_NO_DISPLAY) val version=IntArray(2);check(EGL14.eglInitialize(display,version,0,version,1)) val configs=arrayOfNulls(1);val count=IntArray(1) @@ -84,7 +108,11 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture) configureTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES) GLES20.glGenTextures(patchTextures.size,patchTextures,0) - pack.textureImages.forEachIndexed { index,image -> + if(!mouthEnabled) { + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[0]);configureTexture(GLES20.GL_TEXTURE_2D) + GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D,0,GLES20.GL_RGBA,1,1,0,GLES20.GL_RGBA,GLES20.GL_UNSIGNED_BYTE,ByteBuffer.allocateDirect(4)) + } + (if(mouthEnabled) pack.textureImages else emptyList()).forEachIndexed { index,image -> val p=pack.patches[index/(if(pack.apertureMode) 5 else 1)] val bitmap=context.assets.open(pack.root+image.path).use { BitmapFactory.decodeStream(it) } ?: error("patch_decode") try { @@ -148,6 +176,10 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont val info=MediaCodec.BufferInfo();val outputIndex=decoder.dequeueOutputBuffer(info,0) if(outputIndex>=0) { check(!(info.size==0 && info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM!=0)) { "early_eos" } + if(preroll && info.presentationTimeUs < pack.body.ptsUs[startFrame]-2) { + decoder.releaseOutputBuffer(outputIndex,false);worker.post { pump() };return@guarded + } + preroll=false val key=gate.decoded(info.presentationTimeUs) waiting=true;lastIndex=key.index val pts=pack.body.ptsUs @@ -166,8 +198,17 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont val now=SystemClock.elapsedRealtime() val result=checkNotNull(gate.present(texture.timestamp,now) { draw(it) }) worker.removeCallbacks(timeout);waiting=false;first=false;lastPresentedMs=SystemClock.elapsedRealtime();progressMs=lastPresentedMs - main.post { if(alive.get()) presented(result,(lastPresentedMs-startedMs).coerceAtLeast(0)) } + val elapsed=(lastPresentedMs-startedMs).coerceAtLeast(0) + main.post { if(alive.get()) presented(result,elapsed) } + if(automatic) continueBody() else { held=true;if(mouthEnabled) worker.postDelayed(heldTick,20) } + } + private fun continueBody() { if(lastIndex==pack.body.frameCount-1) { + if(!mayLoop) { + worker.postDelayed({ if(alive.get()) main.post { if(alive.get()) ended() } }, + (pack.body.durationUs-pack.body.ptsUs.last()+999)/1000) + return + } gate.wrap();checkNotNull(codec).flush();checkNotNull(extractor).seekTo(0,MediaExtractor.SEEK_TO_PREVIOUS_SYNC) inputEnded=false } @@ -185,7 +226,8 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont GLES20.glVertexAttribPointer(aUv,2,GLES20.GL_FLOAT,false,0,uv);GLES20.glEnableVertexAttribArray(aUv) GLES20.glUniformMatrix4fv(uTextureMatrix,1,false,textureMatrix,0) GLES20.glActiveTexture(GLES20.GL_TEXTURE0);GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture);GLES20.glUniform1i(uBody,0) - GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[frame.selection.textureSlot]);GLES20.glUniform1i(uPatch,1) + GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, + if(mouthEnabled) patchTextures[frame.selection.textureSlot] else patchTextures[0]);GLES20.glUniform1i(uPatch,1) val p=frame.patch;GLES20.glUniform4f(uRect,p.x,p.y,p.width.toFloat(),p.height.toFloat());GLES20.glUniform1f(uOpacity,frame.selection.opacity) GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4) check(GLES20.glGetError()==GLES20.GL_NO_ERROR && EGL14.eglSwapBuffers(display,window)) @@ -199,15 +241,20 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont main.post { failure("natural_$reason") } close() } - fun close() { + fun close(released: ()->Unit={}) { + synchronized(releaseLock) { + if(releaseComplete) { main.post { released() };return } + releaseCallbacks.add(released) + } if(!alive.compareAndSet(true,false)) return worker.removeCallbacksAndMessages(null) worker.post { gate.close() try { codec?.stop() } catch(_: Exception) { } - try { codec?.release() } catch(_: Exception) { } - try { extractor?.release() } catch(_: Exception) { } - try { inputSurface?.release();inputTexture?.release() } catch(_: Exception) { } + var success=true + try { codec?.release() } catch(_: Exception) { success=false } + try { extractor?.release() } catch(_: Exception) { success=false } + try { inputSurface?.release();inputTexture?.release() } catch(_: Exception) { success=false } if(display!=EGL14.EGL_NO_DISPLAY) { try { GLES20.glDeleteTextures(patchTextures.size,patchTextures,0);GLES20.glDeleteTextures(1,intArrayOf(bodyTexture),0);GLES20.glDeleteProgram(program) } catch(_: Exception) { } EGL14.eglMakeCurrent(display,EGL14.EGL_NO_SURFACE,EGL14.EGL_NO_SURFACE,EGL14.EGL_NO_CONTEXT) @@ -215,7 +262,13 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont if(eglContext!=EGL14.EGL_NO_CONTEXT) EGL14.eglDestroyContext(display,eglContext) EGL14.eglTerminate(display);EGL14.eglReleaseThread() } - output.release();thread.quitSafely() + try { output.release() } catch(_: Exception) { success=false } + if(success) synchronized(releaseLock) { + releaseComplete=true + val callbacks=releaseCallbacks.toList();releaseCallbacks.clear() + main.post { callbacks.forEach { it() } } + } else main.post { failure("natural_release_failed") } + thread.quitSafely() } } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt index c3d36d6..95ede39 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt @@ -12,17 +12,28 @@ data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPat val selection: MouthPatchSelection) /** The real EGL renderer uses this gate immediately around updateTexImage + draw/swap. * No other thread can choose a patch or change body phase. close() fences stale output. */ -class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) { - private val clock=ContinuousFrameClock(pack.body.frameCount,pack.body.ptsUs) +class ContinuousFramePresenter(private val pack: ContinuousAvatarPack, + private val mouthEnabled: Boolean=true,startFrame: Int=0,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) { + private val clock=ContinuousFrameClock(pack.body.frameCount,pack.body.ptsUs,startFrame) private val mouth=ContinuousMouth(pack.curves,choose) private var active=true - fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && mouth.request(talk,generation,revision,nowMs) + private var heldKey: BodyFrameKey?=null + fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && mouth.request(talk && mouthEnabled,generation,revision,nowMs) fun decoded(ptsUs: Long): BodyFrameKey { check(active); return clock.decoded(ptsUs) } fun present(timestampNs: Long,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? { if(!active) return null val key=clock.latched(timestampNs) + heldKey=key + return compose(key,nowMs,drawAndSwap) + } + fun recompose(nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? { + if(!active) return null + return compose(heldKey ?: return null,nowMs,drawAndSwap) + } + private fun compose(key: BodyFrameKey,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame { val sample=mouth.sample(nowMs) - val frame=ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha)) + val frame=if(mouthEnabled) ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha)) + else ComposedBodyFrame(key,RegisteredMouthPatch(key.index,key.ptsUs,"","",0f,0f,1,1),sample,MouthPatchSelection(-1,0,0f)) drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented. return frame } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt index 08bbae6..b61b458 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt @@ -63,9 +63,9 @@ class ContinuousMouth(private val curves: Map, private val ch data class BodyFrameKey(val index: Int, val loopOrdinal: Long, val ptsUs: Long) /** Decoder order and SurfaceTexture consumption are separately checked. */ class ContinuousFrameClock(private val frames: Int=97, - private val pts: List = List(frames) { it*1_000_000L/24 }) { - init { require(pts.size==frames && frames>0) } - private var expected=0 + private val pts: List = List(frames) { it*1_000_000L/24 },startFrame: Int=0) { + init { require(pts.size==frames && startFrame in 0 until frames) } + private var expected=startFrame private var loop=0L private var pending: BodyFrameKey?=null fun decoded(ptsUs: Long): BodyFrameKey { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt new file mode 100644 index 0000000..8690611 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt @@ -0,0 +1,218 @@ +package com.gorios.lanvoice.avatar + +import com.gorios.lanvoice.dialogue.ReplyEmotion + +/** Frames here mean composed/latching evidence, never codec submission. */ +interface CompositeMediaPort { + fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean, + frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) + fun advance() + fun mouth(talk: Boolean,generation: Long,revision: Long) + fun close(released: ()->Unit) +} +interface MusicMediaPort { + fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit) + fun start() + fun close(released: ()->Unit) +} + +/** Three bounded slots: visible body/bridge and hidden bridge/target entrance. + * Each hidden target stays held; no phase-changing reveal without its reviewed edge. + * New intent during a bridge finishes that edge and then routes the latest target. */ +class ConversationMediaDriver(private val index: EmotionActionIndex, + private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort, + private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> }) : ActionPlayer { + private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack, + val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false) + private val slots=mutableListOf() + private var visible: Slot?=null + private var target: Slot?=null + private var bridge: Slot?=null + private var edge: ConversationEdge?=null + private var selectedId=index.fallbackId + var selection: RoleVisualSelection?=null;private set + private var turn: Long?=null + private var seq=-1L + private var generation=0L + private var revision=0L + private var talk=false + private var active=false + private var inBridge=false + private var action: ActionAsset?=null + private var actionStarted=false + private var musicReady=false + private var returning=false + private var actionFinished: ((ActionEnd)->Unit)?=null + private var actionFailed: (()->Unit)?=null + private var musicEpoch=0L + private var closing=0 + private val releaseWaiters=mutableListOf<()->Unit>() + fun beginTurn(id: Long?) { + if(id==turn) return + turn=id;seq=-1;generation++;revision=0;talk=false + selectedId=visible?.packageId ?: index.fallbackId + if(!inBridge) discardRoute() + applyMouth() + } + fun start() { + if(active || closing!=0) return + active=true;generation++;revision=0 + val slot=prepare(index.fallbackId,0);visible=slot + // Ports must deliver callbacks asynchronously, like both Android ports. + } + fun prepareExpression(reply: ReplyEmotion?) { + if(!active || action!=null || inBridge || slots.size>=3) return + if(reply==null) { if(edge==null) discardTarget();return } + if(reply.turnId!=turn) return + val id=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId).packageId + if(id!=visible?.packageId && target?.packageId!=id && edge==null) { + discardTarget();target=prepare(id,0) + } + } + fun intent(reply: ReplyEmotion?,talking: Boolean) { + if(reply?.turnId!=null && reply.turnId!=turn) return + if(reply?.turnId!=null && (reply.turnId!=turn || reply.sequence>seq)) { + if(reply.turnId!=turn) { turn=reply.turnId;seq=-1;generation++;revision=0 } + seq=reply.sequence + selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId) + selectedId=checkNotNull(selection).packageId + } + talk=talking && reply?.turnId==turn + applyMouth() + if(active && !inBridge && !actionStarted) plan() + } + private fun applyMouth() { + visible?.port?.mouth(talk && action==null && !inBridge && edge==null && visible?.packageId==selectedId,generation,++revision) + } + private fun loopEdge(id: String)=index.edges.first { it.from==id && it.to==id && (index.loopIds[id]==null || it.id==index.loopIds[id]) } + private fun prepare(id: String,frame: Int): Slot = prepare(index.packages.getValue(id),frame,true,loopEdge(id).nativeLoop,id) + private fun prepare(pack: ContinuousAvatarPack,entry: Int,mouth: Boolean,loop: Boolean,id: String?): Slot { + check(slots.size<3) + val number=(0..2).first { n->slots.none { it.number==n } } + val slot=Slot(number,create(number),pack,entry,id);slots.add(slot) + slot.port.prepare(pack,entry,mouth,loop,{ key,closedMouth -> + if(active && slot.live && slot in slots) { + val previous=slot.key + val sequential=previous==null || key==previous || + (key.loopOrdinal==previous.loopOrdinal && key.index==previous.index+1) || + (loop && previous.index==pack.body.frameCount-1 && key.index==0 && key.loopOrdinal==previous.loopOrdinal+1) + if(key.index !in pack.body.ptsUs.indices || kotlin.math.abs(key.ptsUs-pack.body.ptsUs[key.index])>2 || + !sequential || previous==null && (key.index!=entry || key.loopOrdinal!=0L)) { fail();return@prepare } + slot.key=key;slot.closedMouth=closedMouth + if(slot===visible) { + reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key) + if(!inBridge) { applyMouth();plan() } + if(slot===visible && !actionStarted && !holdExit(slot)) slot.port.advance() + } else if(returning) restoreAction(slot) else plan() + } + },{ + if(active && visible===slot && inBridge) finishBridge() + },{ if(active && slot.live && slot in slots) fail() }) + return slot + } + private fun holdExit(slot: Slot): Boolean = !inBridge && ( + slot.key?.index==edge?.fromFrame && edge!=null || + action?.media?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true) + private fun plan() { + val source=visible ?: return + val key=source.key ?: return + if(inBridge || !active || returning || actionStarted) return + val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else selectedId + var reviewedLoop: ConversationEdge?=null + if(source.packageId==wanted) { + if(edge!=null && edge?.from!=edge?.to) { discardRoute();return } + if(action!=null && musicReady && source.closedMouth && key.index==action?.media?.sourceFrame) { + actionStarted=true;talk=false;applyMouth();report("action",key) + music.start() + return + } + reviewedLoop=loopEdge(wanted) + if(reviewedLoop.nativeLoop) return + } + if(edge==null) { + val next=reviewedLoop ?: index.edges.firstOrNull { it.from==source.packageId && it.to==wanted && it.from!=it.to } + ?: index.edges.firstOrNull { it.from==source.packageId && it.to==index.fallbackId && it.from!=it.to } + ?: run { + report("whole_package_path_unavailable",key);selectedId=index.fallbackId + selection=selection?.copy(visualEmotion=com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL, + visualIntensity=0,packageId=index.fallbackId,degraded=true,reason="whole_package_path_unavailable") + return + } + if(target!=null && (target?.packageId!=next.to || target?.entry!=next.toFrame)) { discardTarget();return } + if(slots.size+(if(target==null) 2 else 1)>3) return + edge=next + if(target==null) target=prepare(next.to,next.toFrame) + bridge=prepare(ContinuousAvatarPack(next.clip,emptyList(),emptyMap(),index.root,"",false),0,false,false,null) + applyMouth() + } + val current=edge ?: return + if(source.closedMouth && key.index==current.fromFrame && target?.key?.index==current.toFrame && bridge?.key?.index==0) { + val destination=checkNotNull(bridge) + inBridge=true;visible=destination;closeSlot(source);reveal(destination.number) + report("bridge",destination.key);destination.port.advance() + } + } + private fun finishBridge() { + val old=visible ?: return + val destination=target ?: return fail() + val current=edge ?: return fail() + if(destination.key?.index!=current.toFrame) return fail() + visible=destination;target=null;bridge=null;edge=null;inBridge=false + closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key) + applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance() + } + private fun discardTarget() { target?.let(::closeSlot);target=null } + private fun discardRoute() { bridge?.let(::closeSlot);bridge=null;edge=null;discardTarget() } + private fun closeSlot(slot: Slot) { + if(!slot.live || slot !in slots) return + slot.live=false;closing++ + slot.port.close { slots.remove(slot);closing--;releasedIfDone();if(active) plan() } + } + override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { + val media=asset.media + if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return } + action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;applyMouth() + val epoch=++musicEpoch + music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } }, + { if(active && epoch==musicEpoch && actionStarted) reveal(3) },{ + if(active && epoch==musicEpoch && action==asset && actionStarted) { + returning=true;closing++ + // onCompletion alone is not audio-release evidence. + music.close { + closing--;releasedIfDone() + if(active && epoch==musicEpoch && action==asset) { + visible?.let(::closeSlot);visible=null;discardRoute() + target=prepare(media.returnPackage,media.returnFrame) + // Target's first composed frame is the restored idle evidence. + } + } + } + },{ if(active && epoch==musicEpoch) fail() }) + } + private fun restoreAction(slot: Slot) { + val media=action?.media ?: return + if(!returning || slot!==target || slot.key?.index!=media.returnFrame) return + visible=slot;target=null;returning=false;actionStarted=false;action=null + reveal(slot.number);report("body_${slot.packageId}",slot.key) + val completed=actionFinished;actionFinished=null;actionFailed=null + selectedId=slot.packageId ?: index.fallbackId;applyMouth();slot.port.advance() + completed?.invoke(ActionEnd(true,true,true)) + } + override fun stop(released: ()->Unit) { + musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false + actionFinished=null;actionFailed=null;talk=false;generation++;revision=0 + reveal(null);releaseWaiters.add(released) + active=false;visible=null;target=null;bridge=null;edge=null;inBridge=false + closing++ // Music barrier exists before any synchronous port release callback. + slots.toList().forEach(::closeSlot) + music.close { closing--;releasedIfDone() } + } + private fun releasedIfDone() { + if(closing==0) { val callbacks=releaseWaiters.toList();releaseWaiters.clear();callbacks.forEach { it() } } + } + private fun fail() { + report("media_failed",null) + val failed=actionFailed;actionFailed=null + stop {};failed?.invoke() + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt new file mode 100644 index 0000000..7142d61 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt @@ -0,0 +1,148 @@ +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.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.Surface +import android.view.TextureView +import android.widget.FrameLayout +import android.widget.ImageView + +/** All views remain in one stable settings-independent composition slot. */ +class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, + private val binding: AvatarMediaBinding,private val report: (VideoPresentation)->Unit): FrameLayout(context) { + private val main=Handler(Looper.getMainLooper()) + private val textures=List(4) { TextureView(context).apply { isOpaque=false;alpha=0f } } + private val still=ImageView(context).apply { scaleType=ImageView.ScaleType.FIT_CENTER } + private var driver: ConversationMediaDriver?=null + private var active=false + private var released=false + private var movie: AndroidMusicPort?=null + private val renderers=arrayOfNulls(3) + init { + addView(still,LayoutParams(-1,-1)) + try { still.setImageBitmap(context.assets.open(pack.fallback).use(BitmapFactory::decodeStream)) } catch(_: Exception) { } + textures.forEachIndexed { i,view -> + addView(view,LayoutParams(-1,-1)) + view.surfaceTextureListener=object: TextureView.SurfaceTextureListener { + override fun onSurfaceTextureAvailable(s: SurfaceTexture,w: Int,h: Int) { start() } + override fun onSurfaceTextureSizeChanged(s: SurfaceTexture,w: Int,h: Int) { + if(i==3) fitMovie() else renderers[i]?.resize(w,h) + } + override fun onSurfaceTextureUpdated(s: SurfaceTexture) { if(i==3) movie?.latched(s.timestamp) } + override fun onSurfaceTextureDestroyed(s: SurfaceTexture): Boolean { suspend();return true } + } + } + } + fun render(foreground: Boolean) { active=foreground;if(active) start() else suspend() } + private fun start() { + if(!active || released || driver!=null || textures.any { !it.isAvailable }) return + val index=checkNotNull(pack.emotionAction) + val music=AndroidMusicPort(context,textures[3]);movie=music + val current=ConversationMediaDriver(index,{ slot -> + object: CompositeMediaPort { + private var renderer: ContinuousBodyRenderer?=null + override fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean, + frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) { + renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(textures[slot].surfaceTexture)), + textures[slot].width,textures[slot].height,{ value,_-> + frame(value.key,value.mouth.phase=="idle" && value.selection.opacity==0f) + },{ reason->report(VideoPresentation(reason=reason));failed() },automatic=false,startFrame=entryFrame,mayLoop=loop,mouthEnabled=mouth,ended=ended) + renderers[slot]=renderer + } + override fun advance() { renderer?.advance() } + override fun mouth(talk: Boolean,generation: Long,revision: Long) { renderer?.intent(talk,generation,revision) } + override fun close(released: ()->Unit) { val old=renderer;renderer=null + if(renderers[slot]===old) renderers[slot]=null + old?.close(released) ?: released() + } + } + },music,{ slot -> + textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f + },{ phase,key -> report(VideoPresentation(actual=phase,reason="reviewed_media_path", + clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) }) + driver=current;current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie() + } + private fun fitMovie() { + val view=textures[3];if(view.width<=0 || view.height<=0) return + val fit=fitVideo(view.width,view.height,480,848) + view.setTransform(Matrix().apply { setScale(fit.scaleX,fit.scaleY,view.width/2f,view.height/2f) }) + } + private fun suspend() { + val old=driver ?: return + old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() } + } + fun dispose() { active=false;released=true;suspend() } + override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() } +} + +/** Android's completion is combined with actual final TextureView PTS and release. + * No timer substitutes for MediaPlayer.stop/release or idle presentation. */ +internal class AndroidMusicPort(private val context: Context,private val view: TextureView): MusicMediaPort { + private val main=Handler(Looper.getMainLooper()) + private var player: MediaPlayer?=null + private var surface: Surface?=null + private var epoch=0L + private var media: ActionMedia?=null + private var firstFrame: (()->Unit)?=null + private var ended: (()->Unit)?=null + private var failed: (()->Unit)?=null + private var lastPts=-1L + private var playing=false + private var nativeEnded=false + private var startedMs=0L + override fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit) { + check(player==null);val token=++epoch + this.media=media;this.firstFrame=firstFrame;this.ended=ended;this.failed=failed;lastPts=-1 + try { + val s=Surface(checkNotNull(view.surfaceTexture));surface=s + val current=MediaPlayer();player=current;current.setSurface(s);current.isLooping=false + context.assets.openFd(media.root+media.path).use { current.setDataSource(it.fileDescriptor,it.startOffset,it.length) } + current.setOnPreparedListener { if(token==epoch) { + if(current.videoWidth!=media.width || current.videoHeight!=media.height) failed() else ready() + } } + current.setOnCompletionListener { if(token==epoch && playing) { + playing=false;nativeEnded=true;finishIfReady() + main.postDelayed({ if(token==epoch && nativeEnded) failed() },2_000) // Missing final-frame watchdog, no fabricated completion. + } } + current.setOnErrorListener { _,_,_->if(token==epoch) failed();true } + current.prepareAsync() + } catch(_: Exception) { failed() } + } + override fun start() { try { startedMs=SystemClock.elapsedRealtime();nativeEnded=false;playing=true;checkNotNull(player).start() } catch(_: Exception) { failed?.invoke() } } + fun latched(timestampNs: Long) { + if(!playing && !nativeEnded) return + val pts=timestampNs/1000;val timeline=media?.ptsUs ?: return + val found=timeline.binarySearch(pts) + val candidate=if(found>=0) found else (-found-1).coerceAtMost(timeline.lastIndex) + val index=listOf(candidate,(candidate-1).coerceAtLeast(0)).firstOrNull { kotlin.math.abs(timeline[it]-pts)<=2 } + if(index==null || timeline[index]Unit) { + epoch++;playing=false;nativeEnded=false;firstFrame=null;ended=null + val old=player + try { try { old?.stop() } catch(_: Exception) { } // release also stops a prepared/error player. + old?.release();player=null;surface?.release();surface=null;media=null + main.post { released() } + } catch(_: Exception) { val callback=failed;failed=null;callback?.invoke() } // No false release acknowledgement. + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt index 5d9a006..1467c49 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt @@ -3,16 +3,17 @@ package com.gorios.lanvoice.avatar import com.gorios.lanvoice.dialogue.RoleEmotion data class EmotionActionIndex(val fallbackId: String, val packages: Map, - val visuals: List, val actionPack: ReviewedActionPack?, val edges: List = emptyList()) + val visuals: List, val actionPack: ReviewedActionPack?, val edges: List = emptyList(),val root: String="", + val loopIds: Map = emptyMap()) data class ConversationEdge(val id: String,val from: String,val to: String,val fromFrame: Int,val toFrame: Int, - val clip: ContinuousBodyAsset) + val clip: ContinuousBodyAsset,val nativeLoop: Boolean=false) /** Exact external manifest pin admits the whole graph. Self-approval fields have no effect. * loadRuntime must hash-check exact bytes and all body/patch files before returning a pack. * An admitted index is data; playback still needs reviewed bridge execution by its driver. */ object EmotionActionManifest { @Suppress("UNCHECKED_CAST") - fun read(root: Map, actualSha: String, piPinnedSha: String, + fun read(root: Map, actualSha: String, piPinnedSha: String,pathRoot: String="", loadRuntime: (String,String)->ContinuousAvatarPack?): EmotionActionIndex? = try { require(piPinnedSha.matches(Regex("[0-9a-f]{64}")) && actualSha==piPinnedSha) require(root["schemaVersion"]==2L || root["schemaVersion"]==2) @@ -64,10 +65,15 @@ object EmotionActionManifest { require(integer(edge["fromFrame"]) in (source["legalExitFrames"] as List<*>).map(::integer)) require(integer(edge["fromPtsUs"])==from.body.ptsUs[integer(edge["fromFrame"]).toInt()]) require(integer(edge["toPtsUs"])==to.body.ptsUs[integer(edge["toFrame"]).toInt()]) + require(edge["nativeLoop"]==null || edge["nativeLoop"] is Boolean) + val nativeLoop=edge["nativeLoop"]==true + if(nativeLoop) require(edge["from"]==edge["to"] && integer(edge["fromFrame"])==from.body.frameCount-1L && + integer(edge["toFrame"])==0L && hash(clip["sha256"])==from.body.sha256 && pts==from.body.ptsUs && + integer(clip["durationUs"])==from.body.durationUs) ConversationEdge(edge["id"] as String,edge["from"] as String,edge["to"] as String, integer(edge["fromFrame"]).toInt(),integer(edge["toFrame"]).toInt(), ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size, - integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000))) + integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop) } val admitted=visuals.map { visual -> val row=rows.single { it["id"]==visual.id } @@ -97,10 +103,18 @@ object EmotionActionManifest { require(BodyTimeline.valid(pts,count,duration, boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000),5400,90_000_000)) require(duration in 1_000_000..90_000_000) - ActionAsset(action["id"] as String,(duration+999)/1000) + require(action["sourcePackageId"]==fallback && action["returnPackageId"]==fallback) + val runtime=packages.getValue(fallback) + val sourceFrame=integer(action["sourceFrame"]);val returnFrame=integer(action["returnFrame"]) + require(sourceFrame in 0 until runtime.body.frameCount.toLong() && returnFrame in 0 until runtime.body.frameCount.toLong()) + require(sourceFrame in (rows.single { it["id"]==fallback }["legalExitFrames"] as List<*>).map(::integer)) + require(integer(action["sourcePtsUs"])==runtime.body.ptsUs[sourceFrame.toInt()] && + integer(action["returnPtsUs"])==runtime.body.ptsUs[returnFrame.toInt()]) + ActionAsset(action["id"] as String,(duration+999)/1000,ActionMedia(path(clip["path"]),hash(clip["sha256"]),pathRoot, + pts,duration,480,848,fallback,sourceFrame.toInt(),fallback,returnFrame.toInt(),integer(action["audioEndUs"]))) } ReviewedActionPack(actualSha,assets) } - EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges) + EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges,pathRoot,rows.associate { it["id"] as String to it["loopEdge"] as String }) } catch(_: Exception) { null } } diff --git a/docs/ACTION_EMOTION_STAGE_070.md b/docs/ACTION_EMOTION_STAGE_070.md index 30fea17..eed8c5a 100644 --- a/docs/ACTION_EMOTION_STAGE_070.md +++ b/docs/ACTION_EMOTION_STAGE_070.md @@ -28,7 +28,7 @@ See [asset contract](AVATAR_PACK_V2_CONTRACT.md). Pending: happy/sad TALK packages and their own mouths/bridges, Pi exact manifest review, idle variants, two real music dances, -asset file/decode import gate and actual v2 bridge/media renderer integration. +approved asset import and publication (v2 bridge/media source wiring is now implemented below). No new asset is admitted in this APK; default action capability remains absent. Existing neutral runtime04 bytes are preserved. No naturalness approval is inferred from hashes, tests or fixtures. Real device/GPU/music tail/≤1s perception: **not_run**. @@ -84,10 +84,10 @@ Asset-owner update: P1 free amplitude previews completed in its own `.runtime/avatar-imports/a01-expression-action-v1/p1-amplitude-01/`; Pi selected1.1 source pixels for candidate production based on fixed comparisons. Dynamic visual review remains pending. Nearest-level/opacity1/zero-bypass rendering stays intact. -Latest coordinator ledger snapshot: **6 submitted**, known video fee **$0.96**, -image fee unknown (supersedes earlier4/$0.68 and5/$0.86 snapshots, not an all-time total). -sad001 idle rejected for visible opening/strong expression; sad0022s inspection -continues in `p4a-sad-revision-02`. Happy own mouth uses1.1 sourcepx and actual97 +Latest coordinator batch ledger snapshot: **8 submitted**, known video fee **$1.14**, +3 image fees unknown (supersedes earlier snapshots, not an all-time total). +sad001 idle rejected for visible opening/strong expression; sad00249-frame revision +also rejected for opening around1–1.7s. Targeted sad003 is in its own frame gate. Happy own mouth uses1.1 sourcepx and actual97 source PTS; dynamic12s review pending. First real frame0-to-frame0 entry bridge is in `bridge-review/neutral-happy-enter-001`; its gate determines later bridges. Bodies/own-mouth/bridges are not admitted; @@ -99,10 +99,9 @@ four outputs. They cannot guarantee all future finals. `reply.emotion.prepare` i **preload-only**, turn/seq scoped; it must not select visible expression or start speech. The final `reply.emotion` event is authoritative. Duplicate/mismatched/ truncated/extra-field finals cancel preparation; after_action emotion is excluded -from prefix preparation and is displayed only in its later speech turn. Current -MainActivity has no approved multi-pack preload implementation wired to this hook; -the protocol hook and deterministic planner are tested separately, not claimed as -actual new expression pixels on code16. The code16 APK remains unchanged/rollback. +from prefix preparation and is displayed only in its later speech turn. The code16 rollback APK has no multi-pack rendering. The current source wires this +hook to hidden preload and final-authoritative real media playback, still requiring +a Pi-pinned complete index before activation. The code16 APK remains unchanged/rollback. Post-code16 source milestone starts from clean/pushed `4358fc9cae27bcad01b0098690c4a77fa4767d13`. New schema2 per-body parser, frame @@ -116,7 +115,8 @@ New multi-package planner keeps prepare separate from final selection and actual visible package. Sad→neutral→happy executes only reviewed source frames/bridges; serial/turn fences reject stale/repeated presentation, and missing own mouth falls back as a whole package. Index retains bridge clip metadata for its future -driver. It remains unwired to MainActivity until asset/bridge admission is complete. +driver. That planner milestone was not wired to MainActivity; the next source milestone +below implements the actual playback driver and view. Followup validation: 2,361 dynamic frame/level/rejection checks, 15 invalid graph/ cache cases; all nine JVM entries + UI checks; 40 offline real EGL/GLES goldens; @@ -135,5 +135,54 @@ owner files/previews were not changed. Evidence: `logs/avatar-safe-061/`; gateway98-test and compile summaries are in the same dynamic-n evidence directory. No new live probes, paid calls, deployments, service restarts or code16 replacement in this milestone. Whole visual/action -release remains pending approved own-mouth/bridges/index and media integration; +release remains pending approved own-mouth/bridges/index and publication; device/AudioRecord/GPU/perceptual≤1s remain not_run. + + +Media-wiring source milestone (development baseline +`4ead34a944bbe27ba2acca602c9651ff8a16ef0b`): +MainActivity/VoiceSession now share an Activity-owned AvatarMediaBinding and real +EmotionActionAvatarView: three bounded held GLES composite slots and one music +TextureView. Prepare only warms a hidden package; final emotion selects its own +body/mouth, with intensity2 retained and slight visual intensity1. Body changes +wait for exact reviewed source frame, closed mouth, prepared bridge0 and target +entry. Renderer prerolls to actual entry PTS, handles variable N/fps and loop +ordinals, and fences retired frame/turn callbacks. Non-native loop edges play their +actual bridge. Missing package/own-mouth/path degrades the whole package; an +invalid external v2 import can fall back to independently pinned neutral runtime. +Settings keep the same view/driver; the home remains character plus gear only. + +Action plan admission now independently requires accepted local playback drain. +Actual AudioRecord-stop acknowledgement precedes music start; unknown/failed stop +keeps capture blocked. Cancellation while acknowledgement is pending waits both +capture and native release. Music starts only at the declared source frame with +mouth disabled, reveals on actual first texture PTS, joins native completion and +final PTS (either callback order), then waits native stop/release and actual restored +idle entry before completed. Native errors, settings/background/disconnect/new turn +and stale callbacks cancel; no additional LLM/provider/TTS change. Hardware texture +timestamps, physical microphone/music-tail behavior and naturalness remain not_run. + +Happy schema2 candidate read-only Gate1 passed exact manifest +`8d4e56e356d0da3ab9260c448c986fcdb2ef42b66a0dfba11f7bd5dbfeb81b2e`: +97 decoded frames/PTS,4.041667s,485 own PNGs,486 files,1,617,000 RGBA cache bytes, +full decode and real Kotlin admission. The first combined gate failed due to fixture +player records leaking into an older static-admission assertion; fixture isolation +was corrected and the complete gate rerun passed. No owner asset writes or relabeling. +Empty legalExitFrames is deliberately not approved; full index is still absent. + +No APK assembled/published in this milestone, no gateway deploy/restart or live probe; +code16 URL/SHA above remains rollback. Live deployment remains gateway0.8.0/Qwen +json_schema/Asia-Shanghai as last verified. Code-owner paid calls:0. Next handoff is +**MEDIA_WIRING_READY_FOR_PARTIAL_PI_PIN**: neutral+happy, each complete own runtime, +reviewed loops and both actual bridges, index SHA and Pi approval; `actions:[]` is +valid and advertises no dance. Sad and the two complete music dances can follow. +Exact fields/paths are in AVATAR_PACK_V2_CONTRACT.md; capability is not silently +claimed complete. Ignored evidence is in `logs/action-emotion/media-wiring/`. + +Media-wiring validation: **9 JVM entry points + UI source contracts passed**, including +43 actual production view/binding/renderer/MediaPlayer callback fixture cases and +15 held-port driver boundary cases (58 new cases total). Existing2,361 dynamic +N×5 checks and15 invalid graph/cache cases also pass. Local gateway98 tests: +97 passed/1 existing Silero artifact skip.40 offline EGL/GLES goldens passed. +Application and Android instrumentation Kotlin compilation passed; instrumentation +execution and real device capture/GPU/perception were not run. diff --git a/docs/AVATAR_PACK_V2_CONTRACT.md b/docs/AVATAR_PACK_V2_CONTRACT.md index f8983fc..439a562 100644 --- a/docs/AVATAR_PACK_V2_CONTRACT.md +++ b/docs/AVATAR_PACK_V2_CONTRACT.md @@ -31,12 +31,13 @@ Frame indices/PTS are actual decoded values. Every changed body phase requires a reviewed edge, no arbitrary alpha cut. Supply dense seam frames, real-speed loops and full-scale/close previews, not just matching endpoints. -Actions: exactly `asset_01`, `asset_02`, `kind:dance`, `mouthAllowed:false`, +Actions may be `[]` for a partial conversation-only index. Dance requires exactly +`asset_01`, `asset_02`, `kind:dance`, `mouthAllowed:false`, `disallowTALK:true`, `entryAnchor:A`, `returnAnchor:A`, `clip` with file SHA/dimensions/frameCount/PTS/ duration/audio track metadata, `audioEndUs`, `reviewEvidence`. -Use a single complete video including entry, music dance and return A, or list -explicitly hashed sequential segments with reviewed edges. Music must actually +Current player accepts a **single complete video including entry, music dance and +return A**. Separately hashed sequential segments are not yet supported. Music must actually exist, end naturally, and actor must not talk/sing. Source/music provenance and job/fee ledger stay in owner storage; Git stores metadata only. @@ -101,4 +102,34 @@ Deliver corrected runtime paths/hashes plus complete index hash, reviewed loop/ enter/return clip paths/hashes, timed seam previews and Pi's external exact pin. Conversation planning retains clip metadata and assigns each bridge execution a unique serial; stale completion cannot authorize a later bridge with the same id. -Playback driver integration and capability activation remain separate work. +MainActivity now uses the real multi-pack/bridge/music driver; capability activation +still requires the external exact index pin and file admission. + + +Next pin / asset handoff (media-wiring stage, no activation): +- A partial neutral+happy index is sufficient; sad can follow in a later pinned index. + Each included package needs its own schema2 runtime04 and actual N×5 data; + an independently hash-validated legacy neutral runtime04 is also supported. +- happy v2 exact SHA `8d4e56e356d0da3ab9260c448c986fcdb2ef42b66a0dfba11f7bd5dbfeb81b2e` + passed read-only decode/hash/production-parser checks:97 actual PTS,485 PNGs, + 1,617,000 RGBA bytes, body SHA + `232943dc11698c47d4d38c281b08ea87cfcbbd11263b107da59f154a84f4230f`. + Its empty legalExitFrames is not changed or treated as a reviewed exit. +- Index rows declare reviewed legalExitFrames (actual frame indices), loopEdge, + A entry/exit anchors and exact runtimeManifest path/hash. Index paths resolve + under `avatar/a01-expression-action-v1/`; runtime file paths under each runtime. +- Every package requires a loop edge. `nativeLoop:true` is only for a reviewed + same-body last→0 loop: clip has that body's exact SHA/PTS/duration. Otherwise + deliver an actual silent loop bridge; runtime plays that bridge rather than wraps. +- neutral→happy and happy→neutral require actual silent bridge clip metadata, + fromFrame/fromPtsUs and toFrame/toPtsUs bound to each own body. Frame0 exits + are allowed only with reviewed index legalExitFrames; target entry is preroll- + decoded and composed before the bridge reveals, regardless of different N/fps. +- For each later dance, supply sourcePackageId/returnPackageId equal to fallback, + sourceFrame/sourcePtsUs and returnFrame/returnPtsUs exact bindings. SourceFrame + must be a declared legal exit. The complete clip includes the reviewed departure + from that source and return to that target A frame, with actual PTS/duration, + hasAudio:true, measured audioEndUs, no TALK/singing and seam/music evidence. +- Supply full index bytes SHA, all referenced files plus SHA/bytes, preview paths + and Pi's independent exact index approval. A runtime-only SHA is not the index pin. + Do not fabricate bridges, exits, audio, naturalness or dance capability to fill gaps. diff --git a/scripts/check-avatar-ui.py b/scripts/check-avatar-ui.py index 8e8bb9c..d30838f 100644 --- a/scripts/check-avatar-ui.py +++ b/scripts/check-avatar-ui.py @@ -67,6 +67,11 @@ for method,next_method in (('authorizeMicrophone','authorizeCamera'),('authorize assert 'ConnectionStatus.CONNECTED' not in body,'Manual consent must not depend on HELLO' assert 'granted(Manifest.permission.' in body and 'openSettings()' in body assert 'entry.permissionPending!=permission' in activity +assert 'actionPlayer = avatarMedia' in activity and 'onPrepareExpression = avatarMedia::prepare' in activity +assert 'avatarMedia.beginTurn(it.turnId)' in activity and 'mediaBinding = avatarMedia' in activity +assert 'pack?.emotionAction!=null && mediaBinding!=null' in source +assert 'remember(pack,mediaBinding) { EmotionActionAvatarView' in source +assert 'EMOTION_MANIFEST_SHA' in (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text() permissions=text(block('fun PermissionSettings')) for label in ('已授权','未授权','申请麦克风权限','申请摄像头权限','系统权限设置'): assert label in permissions diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index 21f6a24..bcaca6b 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -27,7 +27,7 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice' suites = [ ('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.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/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), + ('avatar','AvatarCheckKt', [source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', 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/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ] diff --git a/tests/avatar/ActionCheck.kt b/tests/avatar/ActionCheck.kt index eec956d..47c6b0d 100644 --- a/tests/avatar/ActionCheck.kt +++ b/tests/avatar/ActionCheck.kt @@ -29,10 +29,20 @@ fun actionCheck() { check(statuses.last().status=="started") release!!();check(!controller.active && statuses.last().status=="cancelled") stale(ActionEnd(true,true,true));check(statuses.last().status=="cancelled") - check(controller.offer(plan(3)));confirm!!(false);release!!() - check(statuses.last().status=="failed" && picked.size==2) + check(controller.offer(plan(6))) + val pendingStop=confirm!! + controller.cancel();release!!() + check(controller.active && statuses.last().status=="cancelled") + pendingStop(true);check(!controller.active && statuses.last().turn==6L && statuses.last().status=="cancelled") + check(controller.offer(plan(7))) + pendingStop(false) // Duplicate retired callback must not poison current capture gate. + check(controller.active && !playing) + confirm!!(true);check(playing) + controller.cancel();release!!();check(!controller.active) check(controller.offer(plan(4)));confirm!!(true) now+=10001;controller.tick();release!!();check(statuses.last().status=="failed") + check(controller.offer(plan(3)));confirm!!(false);release!!() + check(statuses.last().status=="failed" && controller.active && picked.size==4) val missing=ActionController(null,player,{now},{confirm=it},{statuses.add(it)}) check(missing.capability==null && !missing.offer(plan(5))) diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index a80a3ac..fa128d0 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -10,6 +10,8 @@ fun main() { actionCheck() emotionActionCheck() conversationPackageCheck() + actualMediaViewCheck() + mediaBoundaryCheck() checkContinuous() checkEngineering() checkSafeDriver() diff --git a/tests/avatar/CodecMedia.kt b/tests/avatar/CodecMedia.kt index a886c33..4331981 100644 --- a/tests/avatar/CodecMedia.kt +++ b/tests/avatar/CodecMedia.kt @@ -9,9 +9,12 @@ object CodecFixture { var timestampOffsetUs=0L; var outputEnabled=true; var configureFails=false var seeks=mutableListOf(); var releases=0; var flushes=0 var rendered=mutableListOf(); var onRender: ((Long) -> Unit)? = null + var emitNativeSurface=false + val timelines=mutableMapOf>() fun reset() { frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false seeks.clear(); releases=0; flushes=0; rendered.clear(); onRender=null + emitNativeSurface=false;timelines.clear() } } class MediaFormat { @@ -21,12 +24,13 @@ class MediaFormat { } class MediaExtractor { val trackCount=1; private var frame=0 - val sampleTime: Long get() = if (frame >= CodecFixture.frames) -1L else CodecFixture.firstPtsUs+frame*1_000_000L/CodecFixture.fps - fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) {} + private var timeline: List?=null + val sampleTime: Long get() = timeline?.getOrNull(frame) ?: if(frame >= (timeline?.size ?: CodecFixture.frames)) -1L else CodecFixture.firstPtsUs+frame*1_000_000L/CodecFixture.fps + fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) { timeline=CodecFixture.timelines[android.content.AssetFixture.paths[fd]] } fun getTrackFormat(index: Int) = MediaFormat() fun selectTrack(index: Int) {} fun seekTo(time: Long,mode: Int) { CodecFixture.seeks += time; frame=(time*CodecFixture.fps/1_000_000).toInt()/CodecFixture.gop*CodecFixture.gop } - fun readSampleData(buffer: ByteBuffer,offset: Int): Int = if (frame >= CodecFixture.frames) -1 else 1 + fun readSampleData(buffer: ByteBuffer,offset: Int): Int = if (frame >= (timeline?.size ?: CodecFixture.frames)) -1 else 1 fun advance() { frame++ } fun release() {} companion object { const val SEEK_TO_PREVIOUS_SYNC=0 } @@ -35,11 +39,12 @@ class MediaCodec { class BufferInfo { var presentationTimeUs=0L; var flags=0; var size=0 } private data class Output(val pts: Long,val flags: Int,val size: Int) private val queue=java.util.ArrayDeque(); private var current: Output? = null + private var target: Surface?=null companion object { const val BUFFER_FLAG_END_OF_STREAM=4 fun createDecoderByType(mime: String) = MediaCodec() } - fun configure(format: MediaFormat,surface: Surface,crypto: Any?,flags: Int) { check(!CodecFixture.configureFails) } + fun configure(format: MediaFormat,surface: Surface,crypto: Any?,flags: Int) { check(!CodecFixture.configureFails);target=surface } fun start() {} fun dequeueInputBuffer(timeout: Long) = 0 fun getInputBuffer(index: Int): ByteBuffer = ByteBuffer.allocate(32) @@ -51,7 +56,9 @@ class MediaCodec { return 0 } fun releaseOutputBuffer(index: Int,render: Boolean) { - if (render) { val pts=checkNotNull(current).pts; CodecFixture.rendered += pts; CodecFixture.onRender?.invoke(pts) } + if (render) { val pts=checkNotNull(current).pts; CodecFixture.rendered += pts; CodecFixture.onRender?.invoke(pts) + if(CodecFixture.emitNativeSurface) target?.texture?.emit(pts*1000) + } } fun flush() { queue.clear(); CodecFixture.flushes++ } fun stop() {} diff --git a/tests/avatar/Context.kt b/tests/avatar/Context.kt index d3b02b6..8f71ef6 100644 --- a/tests/avatar/Context.kt +++ b/tests/avatar/Context.kt @@ -2,9 +2,11 @@ package android.content class Context { val assets = Assets() } class Assets { fun open(path: String) = java.io.ByteArrayInputStream(byteArrayOf()) - fun openFd(path: String) = Descriptor() + fun openFd(path: String) = Descriptor(path) } -class Descriptor : java.io.Closeable { +object AssetFixture { val paths=mutableMapOf() } +class Descriptor(path: String="") : java.io.Closeable { val fileDescriptor = java.io.FileDescriptor(); val startOffset = 0L; val length = 20L + init { AssetFixture.paths[fileDescriptor]=path } override fun close() {} } diff --git a/tests/avatar/EmotionActionCheck.kt b/tests/avatar/EmotionActionCheck.kt index c613eb7..99f4b86 100644 --- a/tests/avatar/EmotionActionCheck.kt +++ b/tests/avatar/EmotionActionCheck.kt @@ -17,6 +17,8 @@ fun emotionActionCheck() { edge("in","neutral","happy"),edge("out","happy","neutral")) val actions=listOf("asset_01","asset_02").map { mapOf("id" to it,"kind" to "dance", "mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A", + "sourcePackageId" to "neutral","sourceFrame" to 96,"sourcePtsUs" to 4_000_000L, + "returnPackageId" to "neutral","returnFrame" to 0,"returnPtsUs" to 0L, "clip" to clip(true),"audioEndUs" to 1_900_000L) } val root=mapOf("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1", "fallbackPackageId" to "neutral","conversationPackages" to listOf(conversation("neutral"),conversation("happy")), diff --git a/tests/avatar/Media.kt b/tests/avatar/Media.kt index 4bc5bb7..d46ecbf 100644 --- a/tests/avatar/Media.kt +++ b/tests/avatar/Media.kt @@ -6,6 +6,7 @@ class MediaPlayer { var prepared: ((MediaPlayer)->Unit)? = null var info: ((MediaPlayer,Int,Int)->Boolean)? = null var error: ((MediaPlayer,Int,Int)->Boolean)? = null + var completion: ((MediaPlayer)->Unit)? = null var isLooping = false; val looping get() = isLooping var volume = 1f; var released = false; var started = false val videoWidth = 480; val videoHeight = 848 @@ -15,7 +16,9 @@ class MediaPlayer { 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 setOnCompletionListener(callback: (MediaPlayer)->Unit) { completion=callback } fun prepareAsync() {} fun start() { started = true } + fun stop() { started = false } fun release() { released = true } } diff --git a/tests/avatar/MediaBoundaryCheck.kt b/tests/avatar/MediaBoundaryCheck.kt new file mode 100644 index 0000000..f5e775c --- /dev/null +++ b/tests/avatar/MediaBoundaryCheck.kt @@ -0,0 +1,76 @@ +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.dialogue.RoleEmotion + +/** Callback-controlled ports test held exits and release fences, not physical playback. */ +fun mediaBoundaryCheck() { + var cases=0 + class Port: CompositeMediaPort { + lateinit var pack: ContinuousAvatarPack + lateinit var frame: (BodyFrameKey,Boolean)->Unit + lateinit var ended: ()->Unit + var advances=0;var loop=false + var release: (()->Unit)?=null + override fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean, + frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) { + this.pack=pack;this.frame=frame;this.ended=ended;this.loop=loop + } + override fun advance() { advances++ } + override fun mouth(talk: Boolean,generation: Long,revision: Long) {} + override fun close(released: ()->Unit) { release=released } + fun emit(i: Int,ordinal: Long=0) { frame(BodyFrameKey(i,ordinal,pack.body.ptsUs[i]),true) } + } + val music=object: MusicMediaPort { + override fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit) { error("No action in this fixture") } + override fun start() { error("No action in this fixture") } + override fun close(released: ()->Unit) = released() + } + val original=mediaFixtureIndex() + val clip=original.edges.first { it.id=="neutral-happy" }.clip + for(loopBridge in listOf(false,true)) { + val edges=original.edges.map { + when { + loopBridge && it.id=="neutral-loop" -> it.copy(clip=clip,nativeLoop=false) + !loopBridge && it.id=="neutral-happy" -> it.copy(fromFrame=0) + else -> it + } + } + val ports=mutableListOf();val reports=mutableListOf() + val driver=ConversationMediaDriver(original.copy(edges=edges),{ Port().also(ports::add) },music,{}, { phase,_-> reports.add(phase) }) + driver.beginTurn(7);driver.start();val source=ports.single() + if(!loopBridge) driver.intent(mediaReply(RoleEmotion.HAPPY),true) + source.emit(0) + if(loopBridge) (1..96).forEach { source.emit(it) } + check(ports.size==3 && reports.last()=="body_neutral");cases++ + val held=source.advances + val target=ports[1];val bridge=ports[2] + check(!bridge.loop && (!loopBridge || !source.loop));cases++ + bridge.emit(0) + check(source.advances==held && reports.last()=="body_neutral");cases++ + target.emit(0) + check(reports.last()=="bridge" && source.release!=null);cases++ + bridge.emit(1);bridge.emit(2);bridge.ended() + check(reports.contains(if(loopBridge) "body_neutral" else "body_happy") && bridge.release!=null);cases++ + driver.stop {} + val before=reports.size + source.emit(0);bridge.ended();target.emit(0) + check(reports.size==before);cases++ + ports.forEach { it.release?.invoke() } + } + for(bad in listOf("index","ordinal")) { + val ports=mutableListOf();val reports=mutableListOf() + val driver=ConversationMediaDriver(original,{ Port().also(ports::add) },music,{}, { phase,_->reports.add(phase) }) + driver.beginTurn(7);driver.start();val source=ports.single();source.emit(0) + if(bad=="index") source.emit(2) else source.emit(1,1) + check(reports.last()=="media_failed" && source.release!=null);cases++ + source.release?.invoke() + } + val noOwn=original.copy(visuals=original.visuals.map { if(it.id=="happy") it.copy(mouthBodySha=null) else it }) + val ports=mutableListOf() + val driver=ConversationMediaDriver(noOwn,{ Port().also(ports::add) },music,{}) + driver.beginTurn(7);driver.start();ports.single().emit(0) + driver.prepareExpression(mediaReply(RoleEmotion.HAPPY,seq=1)) + driver.intent(mediaReply(RoleEmotion.HAPPY,intensity=2),true) + check(ports.size==1 && driver.selection?.let { it.packageId=="neutral" && it.selectedEmotion==RoleEmotion.HAPPY && it.selectedIntensity==2 }==true);cases++ + driver.stop {};ports.forEach { it.release?.invoke() } + println("PASS: $cases production media driver boundary cases: frame0 exit held until target+bridge ready, actual non-native loop bridge, own-mouth whole fallback, exact frame/ordinal guards and retired callbacks; fixture only") +} diff --git a/tests/avatar/MediaWiringCheck.kt b/tests/avatar/MediaWiringCheck.kt new file mode 100644 index 0000000..9696db9 --- /dev/null +++ b/tests/avatar/MediaWiringCheck.kt @@ -0,0 +1,133 @@ +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.dialogue.* +import android.os.TestScheduler +import android.media.CodecFixture +import android.media.MediaPlayer +import android.graphics.BitmapFactory +import android.opengl.GLFixture +import android.view.TextureView + +fun mediaFixtureIndex(): EmotionActionIndex { + val packs=linkedMapOf("neutral" to dynamicPack(97,24,"c".repeat(64)).copy(root="neutral/"), + "happy" to dynamicPack(49,24,"d".repeat(64)).copy(root="happy/"), + "sad" to dynamicPack(121,30,"e".repeat(64)).copy(root="sad/")) + val visuals=packs.map { (id,p)->TalkPackage(id,RoleEmotion.entries.single { it.wire==id },p.body.sha256,p.body.sha256,p.body.ptsUs,p.body.ptsUs,true) } + val bridges=packs.map { (id,p)->ConversationEdge("$id-loop",id,id,p.body.frameCount-1,0,p.body,true) }+ + listOf("happy","sad").flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)-> + ConversationEdge("$from-$to",from,to,packs.getValue(from).body.frameCount-1,0, + ContinuousBodyAsset("clips/$from-$to.mp4","f".repeat(64),480,848,3,125000,List(3) { it*1_000_000L/24 })) + } } + val musicPts=List(24) { it*1_000_000L/24 } + val actions=ReviewedActionPack("a".repeat(64),listOf("asset_01","asset_02").map { + ActionAsset(it,1000,ActionMedia("clips/$it.mp4","a".repeat(64),"",musicPts,1_000_000,480,848,"neutral",96,"neutral",0,950_000)) + }) + return EmotionActionIndex("neutral",packs,visuals,actions,bridges) +} + +fun mediaReply(emotion: RoleEmotion,turn: Long=7,seq: Long=2,intensity: Int=if(emotion==RoleEmotion.NEUTRAL) 0 else 1)= + ReplyEmotion(emotion,intensity,EmotionSource.MODEL,turn,seq) + +fun actualMediaViewCheck() { + var cases=0 + fun reset() { + TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false;MediaPlayer.created.clear() + CodecFixture.emitNativeSurface=true + } + fun rig(index: EmotionActionIndex=mediaFixtureIndex()): Triple> { + index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } + index.edges.filterNot { it.nativeLoop }.forEach { CodecFixture.timelines[index.root+it.clip.path]=it.clip.ptsUs } + val binding=AvatarMediaBinding();binding.beginTurn(7) + val reports=mutableListOf() + val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,reports::add) + view.render(true);TestScheduler.advanceBy(1) + return Triple(view,binding,reports) + } + reset();val (view,binding,reports)=rig() + check(reports.last().actual=="body_neutral");cases++ + val driverField=view.javaClass.getDeclaredField("driver").apply { isAccessible=true } + val driver=driverField.get(view) + binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(200) + check(reports.none { it.actual=="body_happy" });cases++ // Header preloads hidden, never shows. + binding.intent(mediaReply(RoleEmotion.HAPPY,intensity=2),true) + TestScheduler.until { reports.any { it.actual=="body_happy" } || reports.any { it.actual=="media_failed" } } + check(reports.none { it.actual=="media_failed" }) { reports.takeLast(6).toString() } + val selected=(driver as ConversationMediaDriver).selection + check(selected?.selectedIntensity==2 && selected.visualIntensity==1 && selected.selectedEmotion==RoleEmotion.HAPPY);cases++ + check(reports.any { it.actual=="bridge" } && reports.none { it.actual=="media_failed" });cases++ + TestScheduler.advanceBy(3000) + check(reports.any { it.actual=="body_happy" && it.clipId.contains("loop1") });cases++ + view.render(true);TestScheduler.advanceBy(100) + check(driverField.get(view)===driver);cases++ // Actual persistent view, same settings/foreground path. + binding.intent(mediaReply(RoleEmotion.SAD,seq=3),false) + TestScheduler.until { reports.last().actual=="bridge" } + binding.beginTurn(8);binding.intent(mediaReply(RoleEmotion.SAD,turn=8),true) + binding.intent(mediaReply(RoleEmotion.HAPPY,turn=7,seq=99),true) // Retired reply ignored. + TestScheduler.until { reports.last().actual=="body_sad" } + check((driverField.get(view) as ConversationMediaDriver).selection?.selectedEmotion==RoleEmotion.SAD);cases++ + TestScheduler.advanceBy(4500) + check(reports.any { it.actual=="body_sad" && it.clipId.contains("loop1") } && reports.none { it.actual=="media_failed" });cases++ + val count=reports.size;view.render(false);TestScheduler.advanceBy(1000) + check(reports.size==count && driverField.get(view)==null && CodecFixture.releases>=5);cases++ + view.dispose() + + reset();val (mismatchView,mismatchBinding,mismatchTrace)=rig() + mismatchBinding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(100) + mismatchBinding.intent(mediaReply(RoleEmotion.SAD,seq=2),true) + mismatchBinding.prepare(null) + TestScheduler.until { mismatchTrace.any { it.actual=="body_sad" } } + check(mismatchTrace.none { it.actual=="body_happy" || it.actual=="media_failed" });cases++ + mismatchView.dispose();TestScheduler.advanceBy(100) + + for(confirmed in listOf(true,false)) { + reset();val (cancelView,cancelBinding,_)=rig() + var stop: ((Boolean)->Unit)?=null;var resumed=0 + val statuses=mutableListOf() + val controller=ActionController(mediaFixtureIndex().actionPack,cancelBinding,{TestScheduler.now},{stop=it},statuses::add, + { active->if(!active) resumed++ }) + check(controller.offer(ActionPlan("p".repeat(24),7,"a".repeat(64),15000))) + controller.cancel();TestScheduler.advanceBy(100) + check(statuses.isEmpty() && controller.active && MediaPlayer.created.isEmpty());cases++ + stop!!(confirmed);TestScheduler.advanceBy(100) + check(statuses.single().status==if(confirmed) "cancelled" else "failed");cases++ + check(MediaPlayer.created.isEmpty() && resumed==(if(confirmed) 1 else 0) && controller.active!=confirmed);cases++ + cancelView.dispose();TestScheduler.advanceBy(100) + } + + for(mode in listOf("complete","cancel","failed","background","late_final_frame")) { + reset();val index=mediaFixtureIndex();val (actionView,actionBinding,trace)=rig(index) + var stopped: ((Boolean)->Unit)?=null + val statuses=mutableListOf() + val controller=ActionController(index.actionPack,actionBinding,{TestScheduler.now},{stopped=it},statuses::add) + check(controller.offer(ActionPlan("x".repeat(24),7,"a".repeat(64),15000))) + TestScheduler.advanceBy(100);check(MediaPlayer.created.isEmpty());cases++ + stopped!!(true);val movie=MediaPlayer.created.single() + check(!movie.started);movie.prepared!!(movie) + TestScheduler.until { movie.started } + check(trace.last().clipId.startsWith("f96_") && trace.last().actual=="action");cases++ + val textures=actionView.children.filterIsInstance() + fun latch(pts: Long) { val texture=checkNotNull(textures[3].surfaceTexture);texture.timestamp=pts*1000 + textures[3].surfaceTextureListener!!.onSurfaceTextureUpdated(texture) } + check(textures[3].alpha==0f);latch(0);check(textures[3].alpha==1f);cases++ + when(mode) { + "complete","late_final_frame" -> { + index.actionPack!!.assets.first().media!!.ptsUs.drop(1).dropLast(if(mode=="late_final_frame") 1 else 0).forEach(::latch) + TestScheduler.advanceBy(1000);movie.completion!!(movie) + if(mode=="late_final_frame") { check(statuses.last().status=="started");latch(index.actionPack.assets.first().media!!.ptsUs.last()) } + TestScheduler.until { statuses.last().status=="completed" } + check(movie.released && trace.last().actual=="body_neutral" && trace.last().clipId.startsWith("f0_"));cases++ + movie.completion!!(movie);check(statuses.count { it.status=="completed" }==1);cases++ + } + "cancel" -> { controller.cancel();TestScheduler.until { statuses.last().status=="cancelled" } + check(movie.released && !movie.started && !controller.active);cases++ } + "failed" -> { movie.error!!(movie,1,2);TestScheduler.until { statuses.last().status=="failed" } + check(movie.released && !controller.active);cases++ } + "background" -> { controller.cancel();actionView.render(false);TestScheduler.until { !controller.active } + check(movie.released && driverField.get(actionView)==null);cases++ } + } + val before=statuses.size;movie.completion!!(movie);TestScheduler.advanceBy(10) + check(statuses.size==before);cases++ + actionView.dispose();TestScheduler.advanceBy(100) + } + CodecFixture.reset();MediaPlayer.created.clear() + println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback cases: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run") +} diff --git a/tests/avatar/Pack.kt b/tests/avatar/Pack.kt index 1665119..93cc073 100644 --- a/tests/avatar/Pack.kt +++ b/tests/avatar/Pack.kt @@ -1,4 +1,5 @@ package com.gorios.lanvoice.avatar // Loader has independent byte/hash verification; no real portrait bytes in JVM fixtures. data class AvatarPack(val idle: String = "",val talk: String = "",val fallback: String,val waiting: String = fallback, - val safeGraph: SafeAvatarGraph? = null,val pathRoot: String = "",val motionStatus: String = "anchor_review_pending") + val safeGraph: SafeAvatarGraph? = null,val pathRoot: String = "",val motionStatus: String = "anchor_review_pending", + val continuous: ContinuousAvatarPack?=null,val emotionAction: EmotionActionIndex?=null) diff --git a/tests/avatar/View.kt b/tests/avatar/View.kt index a64b02f..5a60f95 100644 --- a/tests/avatar/View.kt +++ b/tests/avatar/View.kt @@ -2,7 +2,7 @@ package android.view import android.content.Context import android.graphics.SurfaceTexture import android.graphics.Matrix -class Surface(texture: SurfaceTexture) { fun release() {} } +class Surface(val texture: SurfaceTexture) { fun release() {} } class TextureView(context: Context) { var alpha = 1f; var isOpaque = true val isAvailable = true; val surfaceTexture = SurfaceTexture() diff --git a/tests/session/ActionSessionCheck.kt b/tests/session/ActionSessionCheck.kt index 9b062e8..58dd66b 100644 --- a/tests/session/ActionSessionCheck.kt +++ b/tests/session/ActionSessionCheck.kt @@ -30,7 +30,13 @@ fun checkActionSession() { check(prepared.last()?.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY) AudioCapture.confirmStopsAutomatically=false val oldFrame=checkNotNull(AudioCapture.lastFrame) - event("action.plan",EventKind.ACTION,7,mapOf("action_id" to "x".repeat(24),"pack_sha256" to sha,"ttl_ms" to 10000L)) + val fields=mapOf("action_id" to "x".repeat(24),"pack_sha256" to sha,"ttl_ms" to 10000L) + event("action.plan",EventKind.ACTION,7,fields) + check(!states.last().actionActive && plays==0) // A server plan cannot fabricate local TTS drain. + val frameMethod=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true } + frameMethod.invoke(session,DownlinkFrame(7)) + checkNotNull(AudioPlayback.lastDrained)(7,0);Handler.drain() + event("action.plan",EventKind.ACTION,7,fields) check(states.last().actionActive && plays==0) val before=DialogueProtocol.uplinks.size oldFrame(ByteArray(640));Handler.drain();check(DialogueProtocol.uplinks.size==before) @@ -39,7 +45,7 @@ fun checkActionSession() { session.setMicrophoneMuted(true);session.setMicrophoneMuted(false);session.interrupt() check(AudioCapture.starts==starts) val enqueued=AudioPlayback.enqueued - session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }.invoke(session,DownlinkFrame(7)) + frameMethod.invoke(session,DownlinkFrame(7)) check(enqueued==AudioPlayback.enqueued) val stale=checkNotNull(ended) session.background();Handler.drain()