Add bounded native playback diagnostics and sensor-free dance inspection

This commit is contained in:
zenord
2026-10-13 11:43:38 +08:00
parent 3458a9b03e
commit f9c45a3c4e
16 changed files with 400 additions and 53 deletions
+3 -1
View File
@@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true'
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
@@ -35,6 +36,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
if (avatarPlaybackDiagnostic && (!avatarFullActionCandidate || actionVersionCode < 20 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback diagnostic requires frozen full graph and fresh code >=20')
if (avatarRuntimeFix && (!avatarFullActionCandidate || actionVersionCode < 19)) throw new GradleException('Runtime fix requires full pinned graph and fresh code >=19')
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
@@ -84,7 +86,7 @@ android {
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
versionName = avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -60,6 +60,7 @@ class MainActivity : ComponentActivity() {
private lateinit var expressions: ExpressionController
private var inForeground = false
private var offlineAvatarPreview = false
private var openingOffline = false
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
permissionResult(EntryPermission.CAMERA, granted)
}
@@ -155,7 +156,7 @@ class MainActivity : ComponentActivity() {
entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false),
conversationEnabled=false,automaticPermissions=false)
setContent { EngineeringPreviewScreen(avatarPack,micGranted,cameraGranted,micSettings,cameraSettings,
permissionPending,::authorizeMicrophone,::authorizeCamera) }
permissionPending,::authorizeMicrophone,::authorizeCamera,avatarMedia,::sendDiagnosticReport,reportSending,reportResult) }
return // No VoiceSession/audio focus/camera controller; manual permission consent only.
}
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
@@ -202,6 +203,16 @@ class MainActivity : ComponentActivity() {
micGranted,cameraGranted,permissionPending,::authorizeCamera,
onCancelAction = session::cancelAction,
mediaBinding = avatarMedia,
onOfflinePreview = {
if(!openingOffline) {
openingOffline=true;closeCamera()
session.suspendForLocalPreview { safe ->
openingOffline=false
if(safe && inForeground && !isDestroyed) startActivity(android.content.Intent(this,MainActivity::class.java).putExtra(OfflineAvatarTrace.EXTRA,true))
else reportResult="录音停止未确认,暂不进入离线播放检查"
}
}
},
)
}
}
@@ -224,8 +235,8 @@ class MainActivity : ComponentActivity() {
cameraStatus = expressionState.status,
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
faceSharing = shareFace,
cameraAnalysis = expressions.diagnosticsSnapshot(),
faceTransmission = session.faceDiagnosticsSnapshot(),
cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else expressions.diagnosticsSnapshot(),
faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else session.faceDiagnosticsSnapshot(),
rolePlaying = state.phase == VoicePhase.ANSWERING,
role = state.replyEmotion.takeIf { it.turnId != null },
previousRole = state.previousReplyEmotion,
@@ -126,10 +126,18 @@ class VoiceSession(
},
onActivity = { activity ->
main.post {
if (isActive() && !actions.active && playbackIsCurrent(activity.turnId, activity.generation) &&
currentTurn == activity.turnId && blockedTurn != activity.turnId && emotionEndedTurn != activity.turnId) {
update(state.copy(playbackActivity = activity))
val reason=when {
!isActive()->"inactive"
actions.active->"action_owner"
!playbackIsCurrent(activity.turnId,activity.generation)->"stale_generation"
currentTurn!=activity.turnId->"old_turn"
blockedTurn==activity.turnId->"blocked"
emotionEndedTurn==activity.turnId->"drained"
else->"accepted"
}
com.gorios.lanvoice.diag.DiagnosticLog.state("talk_gate","$reason/${activity.turnId}/${activity.generation}/${activity.audible}",
"reason=$reason turn=${activity.turnId} generation=${activity.generation} audible=${activity.audible} head=${activity.playedSamples} written=${activity.writtenSamples}")
if(reason=="accepted") update(state.copy(playbackActivity = activity))
}
},
)
@@ -164,7 +172,7 @@ class VoiceSession(
checkMainThread()
clearFaceContext()
foreground = false
stopVoice(sendControls = keepConnectionForPermission)
stopVoice(sendControls = keepConnectionForPermission,cancelReason = "background")
backgroundTimeout?.let { main.removeCallbacks(it) }
backgroundTimeout = null
DebugLogUpload.log("connect", "session background permission=$keepConnectionForPermission")
@@ -184,6 +192,21 @@ class VoiceSession(
}
}
/** Explicit local inspection leaves voice first, then waits for real recorder cleanup.
* No microphone-safe flag is invented by the offline player. */
fun suspendForLocalPreview(confirmed: (Boolean)->Unit) {
checkMainThread();background()
val fence=captureEpoch;var acknowledged=false
capture.stopAndConfirm { stopped -> main.post {
if(!acknowledged) {
acknowledged=true
val safe=stopped && captureEpoch==fence && !foreground && !released
diagnostic("offline_capture state=${if(safe) "stop_confirmed" else "stop_unconfirmed"} epoch=$fence")
confirmed(safe)
}
} }
}
fun release() {
checkMainThread()
if (released) return
@@ -205,9 +228,9 @@ class VoiceSession(
startCapture()
}
fun stopVoice(sendControls: Boolean = true) {
fun stopVoice(sendControls: Boolean = true,cancelReason: String = "stop_voice") {
checkMainThread()
actions.cancel()
cancelActionFor(cancelReason)
resetReply("stop")
val wasActive = state.voiceActive
stopCapture()
@@ -261,7 +284,11 @@ class VoiceSession(
}
}
fun cancelAction() { checkMainThread(); actions.cancel() }
private fun cancelActionFor(reason: String) {
if(actions.active) com.gorios.lanvoice.diag.DiagnosticLog.state("action_cancel","$reason/$currentTurn","reason=$reason turn=$currentTurn")
actions.cancel()
}
fun cancelAction() { checkMainThread(); cancelActionFor("settings_cancel") }
fun permissionDenied() {
checkMainThread()
@@ -271,7 +298,7 @@ class VoiceSession(
fun outputUnavailable(message: String) {
checkMainThread()
if (state.voiceActive) {
stopVoice()
stopVoice(cancelReason = "audio_focus_unavailable")
update(state.copy(guidance = message))
}
}
@@ -334,7 +361,7 @@ class VoiceSession(
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
actions.cancel()
cancelActionFor("disconnect")
onPrepareExpression(null)
resetReply("disconnect")
faceSupported = false
@@ -417,7 +444,7 @@ class VoiceSession(
}
if (event.kind == EventKind.ACTION) {
if (!isActive() || !hasTurn || turn != currentTurn) { diagnostic("action_plan state=ignored_turn_or_inactive turn=$turn");return }
if (event.type == "action.cancel") actions.cancel()
if (event.type == "action.cancel") cancelActionFor("server_cancel")
else if (event.type == "action.plan") {
val id = event.payload.optString("action_id")
val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L
@@ -538,7 +565,7 @@ class VoiceSession(
}
// IDs identify turns; do not assume the server allocates them in numeric order.
if (!hasTurn || id != currentTurn) {
actions.cancel()
cancelActionFor("new_turn")
onPrepareExpression(null)
resetReply("new_turn")
val resumeCapture = capturing
@@ -1,13 +1,26 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.dialogue.ReplyEmotion
import com.gorios.lanvoice.diag.DiagnosticLog
/** One Activity-owned binding shared by VoiceSession and its persistent avatar view. */
class AvatarMediaBinding : ActionPlayer {
val currentPackageId: String? get() = driver?.currentPackageId
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
val diagnosticState: String get() = driver?.diagnosticState ?: "owner=stopped renderer=unavailable"
val diagnosticState: String get() = (driver?.diagnosticState ?: "owner=stopped renderer=unavailable")+" $nativeMusic $mouthPresentation"
val selection: RoleVisualSelection? get() = driver?.selection
private var nativeMusic="music=unavailable"
private var visibleSlot: Int?=null
private val presentations=mutableMapOf<Int,String>()
private val mouthPresentation: String get() = visibleSlot?.let { presentations[it] } ?: "mouth=off"
fun visible(slot: Int?) { visibleSlot=slot }
fun musicDiagnostic(value: String) { nativeMusic=value }
fun presented(slot: Int,value: ComposedBodyFrame) {
val sample="slot=$slot mouth_phase=${value.mouth.phase} aperture=${value.mouth.alpha} level=${value.selection.levelIndex ?: -1} opacity=${value.selection.opacity} frame=${value.key.index} loop=${value.key.loopOrdinal} pts_us=${value.key.ptsUs} mouth_generation=${value.mouth.generation}"
// Frame/level changes are sampled, never the ring signature. Swap callback, not GPU visibility proof.
presentations[slot]=sample
if(visibleSlot==slot) DiagnosticLog.state("mouth_presented","$slot/${value.mouth.phase}/${value.mouth.generation}",sample)
}
private var driver: ConversationMediaDriver?=null
private var prepared: ReplyEmotion?=null
private var reply: ReplyEmotion?=null
@@ -34,6 +34,8 @@ import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.ExpressionUiState
import com.gorios.lanvoice.BuildConfig
private val NoUiAction: ()->Unit = {}
/** The avatar always occupies the same composition slot. Opening/closing the sheet
* only changes chrome, never a lifecycle/voice/decoder key or renderer instance. */
@OptIn(ExperimentalMaterial3Api::class)
@@ -79,6 +81,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit,
onCancelAction: ()->Unit,
mediaBinding: AvatarMediaBinding?=null,
onOfflinePreview: ()->Unit=NoUiAction,
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar)
@@ -133,6 +136,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
Text("版本 ${com.gorios.lanvoice.BuildConfig.VERSION_NAME} · code ${com.gorios.lanvoice.BuildConfig.VERSION_CODE} · pin ${com.gorios.lanvoice.BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp)
if(BuildConfig.VERSION_NAME=="0.7.2") Text("播放诊断版:未确认手机根因;可离线检查两段原舞蹈并发送状态报告",fontSize=12.sp)
Text("素材准入:${pack?.emotionAdmission ?: "unavailable"} · ${mediaBinding?.diagnosticState ?: "legacy_neutral"}",fontSize=11.sp)
AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
@@ -140,6 +144,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
TextButton(onClick=onInterrupt,enabled=state.voiceActive && !state.actionActive) { Text("打断回答") }
TextButton(onClick=onReport,enabled=!reportSending) { Text(if(reportSending) "发送中…" else "发送诊断报告") }
}
TextButton(onClick=onOfflinePreview) { Text("离线播放检查(停止当前会话)") }
reportResult?.let { Text(it,fontSize=12.sp) }
Text(logs.takeLast(10).joinToString("\n"),fontSize=11.sp)
})
@@ -174,25 +179,32 @@ private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
/** Sensor-free synthetic intents, same real renderer and same clean home. */
@Composable
fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit) {
permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit,
mediaBinding: AvatarMediaBinding?=null,onReport: ()->Unit=NoUiAction,reportSending: Boolean=false,reportResult: String?=null) {
val activity=LocalContext.current as ComponentActivity
var resumed by remember { mutableStateOf(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }
var trace by remember { mutableStateOf(OfflineAvatarTrace.at(0)) }
var override by remember { mutableStateOf<AvatarMode?>(null) }
var restart by remember { mutableStateOf(0L) }
var video by remember { mutableStateOf(VideoPresentation()) }
val offlineBinding=remember(pack) { AvatarMediaBinding() }
val offlineBinding=mediaBinding ?: remember(pack) { AvatarMediaBinding() }
var danceActive by remember { mutableStateOf(false) }
var danceStatus by remember { mutableStateOf("idle") }
var nativeState by remember { mutableStateOf("renderer_unavailable") }
val dance=remember(pack,offlineBinding) { OfflineDancePreview(pack?.emotionAction?.actionPack,offlineBinding,
{ android.os.SystemClock.elapsedRealtime() }) { active,status -> danceActive=active;danceStatus=status } }
var emotionLabel by remember { mutableStateOf("") }
DisposableEffect(activity) {
val observer=LifecycleEventObserver { _,event ->
if(event==Lifecycle.Event.ON_RESUME) resumed=true
if(event==Lifecycle.Event.ON_PAUSE) resumed=false
if(event==Lifecycle.Event.ON_PAUSE) { resumed=false;dance.cancel("background") }
}
activity.lifecycle.addObserver(observer)
onDispose { activity.lifecycle.removeObserver(observer) }
onDispose { activity.lifecycle.removeObserver(observer);dance.cancel("disposed") }
}
LaunchedEffect(resumed,restart,override) {
if(resumed) {
LaunchedEffect(resumed) { while(resumed) { nativeState=offlineBinding.diagnosticState;delay(500) } }
LaunchedEffect(resumed,restart,override,danceActive) {
if(resumed && !danceActive) {
val start=android.os.SystemClock.elapsedRealtime()
val emotionSequence=OfflineEmotionSequence(1000+restart)
if(pack?.emotionAction!=null) offlineBinding.beginTurn(1000+restart)
@@ -218,11 +230,22 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
Text("版本 ${BuildConfig.VERSION_NAME} · code ${BuildConfig.VERSION_CODE} · pin ${BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp)
Text("离线媒体:$danceStatus · $nativeState",fontSize=11.sp)
AvatarDiagnostics(pack,video)
if(pack?.emotionAction?.actionPack!=null) {
Row {
TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_01")},enabled=resumed && !danceActive) { Text("舞蹈 01") }
TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_02")},enabled=resumed && !danceActive) { Text("舞蹈 02") }
TextButton(onClick={dance.cancel()},enabled=danceActive) { Text("停止舞蹈") }
}
}
TextButton(onClick=onReport,enabled=!reportSending) { Text(if(reportSending) "发送中…" else "发送诊断报告") }
reportResult?.let { Text(it,fontSize=12.sp) }
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") }
TextButton(onClick={override=AvatarMode.TALK}) { Text("Talk") }
TextButton(onClick={override=AvatarMode.IDLE;restart++}) { Text("Abort") }
TextButton(onClick={dance.cancel();override=AvatarMode.IDLE;restart++}) { Text("Abort") }
TextButton(onClick={override=null;restart++}) { Text("Trace") }
}
})
@@ -55,7 +55,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
if(!active || released || driver!=null || textures.any { !it.isAvailable }) return
val index=checkNotNull(pack.emotionAction)
val mouthClock=ConversationMouthClock()
val music=AndroidMusicPort(context,textures[3]);movie=music
val music=AndroidMusicPort(context,textures[3],binding::musicDiagnostic);movie=music
val current=ConversationMediaDriver(index,{ slot ->
object: CompositeMediaPort {
private var renderer: ContinuousBodyRenderer?=null
@@ -63,6 +63,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) {
renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(textures[slot].surfaceTexture)),
textures[slot].width,textures[slot].height,{ value,_->
binding.presented(slot,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,sharedMouth=mouthClock,ended=ended)
renderers[slot]=renderer
@@ -79,7 +80,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
}
},music,{ slot ->
if(visibleLayer!=slot) {
visibleLayer=slot
visibleLayer=slot;binding.visible(slot)
textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f
}
},{ phase,key ->
@@ -105,7 +106,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
/** 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 {
internal class AndroidMusicPort(private val context: Context,private val view: TextureView,private val diagnostic: (String)->Unit={}): MusicMediaPort {
private val main=Handler(Looper.getMainLooper())
private var player: MediaPlayer?=null
private var surface: Surface?=null
@@ -118,53 +119,71 @@ internal class AndroidMusicPort(private val context: Context,private val view: T
private var playing=false
private var nativeEnded=false
private var startedMs=0L
private var faulted=false
private fun event(reason: String, timestampUs: Long?=null) {
val position=try { player?.currentPosition ?: -1 } catch(_: Exception) { -1 }
val message="event=$reason epoch=$epoch playing=$playing ended=$nativeEnded elapsed_ms=${SystemClock.elapsedRealtime()-startedMs} position_ms=$position pts_us=${timestampUs ?: lastPts} layer_alpha=${view.alpha}"
diagnostic(message)
DiagnosticLog.state("music_native", "$epoch/$reason",message)
}
private fun fault(reason: String,timestampUs: Long?=null) {
if(faulted) return
faulted=true;event(reason,timestampUs);failed?.invoke()
}
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
this.media=media;this.firstFrame=firstFrame;this.ended=ended;this.failed=failed;lastPts=-1;faulted=false;startedMs=SystemClock.elapsedRealtime();event("preparing")
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()
if(current.videoWidth!=media.width || current.videoHeight!=media.height) fault("dimensions_invalid") else { event("prepared");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.
playing=false;nativeEnded=true;event("native_completed");finishIfReady()
main.postDelayed({ if(token==epoch && nativeEnded) fault("native_ended_missing_final") },2_000) // Missing final-frame watchdog, no fabricated completion.
} }
current.setOnErrorListener { _,_,_->if(token==epoch) failed();true }
current.setOnInfoListener { _,what,_->
if(token==epoch && what==MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) event("native_rendering_start")
true // Native info is not a latched frame or completion proof.
}
current.setOnErrorListener { _,_,_->if(token==epoch) fault("native_error");true }
current.prepareAsync()
} catch(_: Exception) { failed() }
} catch(_: Exception) { fault("prepare_failed") }
}
override fun start() { try { startedMs=SystemClock.elapsedRealtime();nativeEnded=false;playing=true;checkNotNull(player).start() } catch(_: Exception) { failed?.invoke() } }
override fun start() { if(faulted) return;try { startedMs=SystemClock.elapsedRealtime();nativeEnded=false;playing=true;checkNotNull(player).start();event("started") } catch(_: Exception) { fault("start_failed") } }
fun latched(timestampNs: Long) {
if(!playing && !nativeEnded) return
if(faulted || (!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(index==null) { fault("timestamp_not_indexed",pts);return }
if(timeline[index]<lastPts) { fault("timestamp_regressed",pts);return }
if(lastPts<0) {
if(index!=0) { failed?.invoke();return }
if(index!=0) { fault("first_frame_not_zero",pts);return }
event("first_frame_latched",pts)
firstFrame?.invoke();firstFrame=null
}
lastPts=timeline[index]
finishIfReady()
}
private fun finishIfReady() {
if(faulted) return
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()
if(SystemClock.elapsedRealtime()-startedMs<(current.durationUs+999)/1000) fault("duration_early")
else { event("validated_end");ended?.invoke() }
}
}
override fun close(released: ()->Unit) {
epoch++;playing=false;nativeEnded=false;firstFrame=null;ended=null
event("closing");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.
event("released");main.post { released() }
} catch(_: Exception) { event("release_failed");val callback=failed;failed=null;callback?.invoke() } // No false release acknowledgement.
}
}
@@ -0,0 +1,29 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.diag.DiagnosticLog
/** Explicit local media inspection, not a network action or a fabricated mic confirmation.
* Uses the same production player/return-A release fence. No capture, transport or after-reply. */
class OfflineDancePreview(private val pack: ReviewedActionPack?,private val player: ActionPlayer,
private val clock: ()->Long,private val changed: (Boolean,String)->Unit={_,_->}) {
private var epoch=0L
var active=false;private set
private var stopping=false
private fun state(value: String) { DiagnosticLog.state("offline_dance","$epoch/$value","event=$value epoch=$epoch active=$active");changed(active,value) }
fun play(id: String): Boolean {
if(active || stopping) return false
val asset=pack?.assets?.singleOrNull { it.id==id && it.id in setOf("asset_01","asset_02") && it.media!=null } ?: return false
val token=++epoch;val start=clock();active=true;state("requested_$id")
player.play(asset,{ end->
if(token!=epoch || !active || stopping) return@play
if(!end.videoEnded || !end.audioStopped || !end.idleRestored || clock()-start<asset.durationMs) cancel("invalid_end")
else { active=false;epoch++;state("completed") }
},{ if(token==epoch && active && !stopping) cancel("media_failed") })
return true
}
fun cancel(reason: String="settings_cancel") {
if(!active || stopping) return
epoch++;stopping=true;state(reason)
player.stop { stopping=false;active=false;state("released") }
}
}