Wire reviewed emotion bridges and action media playback fences
This commit is contained in:
@@ -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'] }
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}")
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Long>,
|
||||
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<ActionAsset>)
|
||||
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<ActionPlan,String>?=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. */
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
logs: List<String>,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
|
||||
|
||||
@@ -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<EGLConfig>(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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -63,9 +63,9 @@ class ContinuousMouth(private val curves: Map<String,MouthCurve>, 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<Long> = List(frames) { it*1_000_000L/24 }) {
|
||||
init { require(pts.size==frames && frames>0) }
|
||||
private var expected=0
|
||||
private val pts: List<Long> = 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 {
|
||||
|
||||
@@ -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<Slot>()
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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<ContinuousBodyRenderer>(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]<lastPts) { failed?.invoke();return }
|
||||
if(lastPts<0) {
|
||||
if(index!=0) { failed?.invoke();return }
|
||||
firstFrame?.invoke();firstFrame=null
|
||||
}
|
||||
lastPts=timeline[index]
|
||||
finishIfReady()
|
||||
}
|
||||
private fun finishIfReady() {
|
||||
val current=media ?: return
|
||||
if(nativeEnded && lastPts==current.ptsUs.last()) {
|
||||
nativeEnded=false
|
||||
if(SystemClock.elapsedRealtime()-startedMs<(current.durationUs+999)/1000) failed?.invoke()
|
||||
else ended?.invoke()
|
||||
}
|
||||
}
|
||||
override fun close(released: ()->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.
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,17 @@ package com.gorios.lanvoice.avatar
|
||||
import com.gorios.lanvoice.dialogue.RoleEmotion
|
||||
|
||||
data class EmotionActionIndex(val fallbackId: String, val packages: Map<String,ContinuousAvatarPack>,
|
||||
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?, val edges: List<ConversationEdge> = emptyList())
|
||||
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?, val edges: List<ConversationEdge> = emptyList(),val root: String="",
|
||||
val loopIds: Map<String,String> = 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<String,Any?>, actualSha: String, piPinnedSha: String,
|
||||
fun read(root: Map<String,Any?>, 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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user