Fix action playback source clock using controlled video decode
This commit is contained in:
+3
-1
@@ -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 avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true'
|
||||
def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true'
|
||||
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
|
||||
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
|
||||
@@ -36,6 +37,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 (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21')
|
||||
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}/)) {
|
||||
@@ -86,7 +88,7 @@ android {
|
||||
targetSdk 34
|
||||
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
||||
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
|
||||
versionName = avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
|
||||
versionName = avatarPlaybackClockFix ? '0.7.3' : 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 }
|
||||
|
||||
@@ -2,7 +2,8 @@ package com.gorios.lanvoice.avatar
|
||||
|
||||
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)
|
||||
val returnPackage: String,val returnFrame: Int,val audioEndUs: Long,
|
||||
val fpsNumerator: Int=24,val fpsDenominator: Int=1)
|
||||
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)
|
||||
|
||||
@@ -29,7 +29,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
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 automatic: Boolean=true,private val startFrame: Int=0,private val mayLoop: Boolean=true,
|
||||
private val mouthEnabled: Boolean=true,private val sharedMouth: ConversationMouthClock?=null,private val ended: ()->Unit={}) {
|
||||
private val mouthEnabled: Boolean=true,private val videoOnlyFromAv: Boolean=false,private val sharedMouth: ConversationMouthClock?=null,private val ended: ()->Unit={}) {
|
||||
private val alive=AtomicBoolean(true)
|
||||
private val releaseLock=Any()
|
||||
private val releaseCallbacks=mutableListOf<()->Unit>()
|
||||
@@ -141,10 +141,15 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
||||
inputSurface=Surface(checkNotNull(inputTexture))
|
||||
val ex=MediaExtractor();extractor=ex
|
||||
context.assets.openFd(pack.root+pack.body.path).use { ex.setDataSource(it.fileDescriptor,it.startOffset,it.length) }
|
||||
check(ex.trackCount==1)
|
||||
val format=ex.getTrackFormat(0);check(format.getString(MediaFormat.KEY_MIME)=="video/avc")
|
||||
val track=if(videoOnlyFromAv) {
|
||||
check(!mouthEnabled && !mayLoop && ex.trackCount==2)
|
||||
val video=(0 until ex.trackCount).single { ex.getTrackFormat(it).getString(MediaFormat.KEY_MIME)=="video/avc" }
|
||||
check(ex.getTrackFormat(1-video).getString(MediaFormat.KEY_MIME)=="audio/mp4a-latm")
|
||||
video
|
||||
} else { check(ex.trackCount==1);0 }
|
||||
val format=ex.getTrackFormat(track);check(format.getString(MediaFormat.KEY_MIME)=="video/avc")
|
||||
check(format.getInteger(MediaFormat.KEY_WIDTH)==480 && format.getInteger(MediaFormat.KEY_HEIGHT)==848)
|
||||
ex.selectTrack(0);check(ex.sampleTime==0L)
|
||||
ex.selectTrack(track);check(ex.sampleTime==0L)
|
||||
codec=MediaCodec.createDecoderByType("video/avc").also { it.configure(format,checkNotNull(inputSurface),null,0);it.start() }
|
||||
progressMs=SystemClock.elapsedRealtime()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.gorios.lanvoice.avatar
|
||||
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.MediaPlayer
|
||||
import android.os.Handler
|
||||
@@ -92,8 +91,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
||||
}
|
||||
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) })
|
||||
movie?.resize(view.width,view.height)
|
||||
}
|
||||
private fun suspend() {
|
||||
main.removeCallbacks(summary)
|
||||
@@ -104,86 +102,109 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
||||
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. */
|
||||
/** Video uses the existing controlled codec/compositor's decoded+latched source PTS.
|
||||
* MediaPlayer supplies audio only: its TextureView timestamp is a presentation clock,
|
||||
* not a source-frame index. Completion still requires final video, native audio end,
|
||||
* actual resource release and the driver's reviewed return A. */
|
||||
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
|
||||
private var video: ContinuousBodyRenderer?=null
|
||||
private var epoch=0L
|
||||
private var media: ActionMedia?=null
|
||||
private var firstFrame: (()->Unit)?=null
|
||||
private var ready: (()->Unit)?=null
|
||||
private var ended: (()->Unit)?=null
|
||||
private var failed: (()->Unit)?=null
|
||||
private var lastPts=-1L
|
||||
private var lastIndex=-1
|
||||
private var playing=false
|
||||
private var audioReady=false
|
||||
private var readySent=false
|
||||
private var nativeEnded=false
|
||||
private var videoEnded=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}"
|
||||
val message="event=$reason epoch=$epoch playing=$playing ended=$nativeEnded video_ended=$videoEnded elapsed_ms=${SystemClock.elapsedRealtime()-startedMs} position_ms=$position pts_us=$lastPts frame=$lastIndex output_us=${timestampUs ?: -1} layer_alpha=${view.alpha}"
|
||||
diagnostic(message)
|
||||
DiagnosticLog.state("music_native", "$epoch/$reason",message)
|
||||
}
|
||||
private fun fault(reason: String,timestampUs: Long?=null) {
|
||||
private fun fault(reason: String) {
|
||||
if(faulted) return
|
||||
faulted=true;event(reason,timestampUs);failed?.invoke()
|
||||
faulted=true;event(reason);failed?.invoke()
|
||||
}
|
||||
private fun announceReady() {
|
||||
if(!faulted && audioReady && lastIndex==0 && !readySent) { readySent=true;event("prepared");ready?.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;faulted=false;startedMs=SystemClock.elapsedRealtime();event("preparing")
|
||||
check(player==null && video==null);val token=++epoch
|
||||
this.media=media;this.ready=ready;this.firstFrame=firstFrame;this.ended=ended;this.failed=failed
|
||||
lastPts=-1;lastIndex=-1;faulted=false;audioReady=false;readySent=false;videoEnded=false;nativeEnded=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
|
||||
val body=ContinuousBodyAsset(media.path,media.sha256,media.width,media.height,media.ptsUs.size,
|
||||
media.durationUs,media.ptsUs,media.fpsNumerator,media.fpsDenominator)
|
||||
// Genuine body-only action: no registered mouth assets or conversation patch reuse.
|
||||
val pack=ContinuousAvatarPack(body,emptyList(),emptyMap(),media.root,media.sha256)
|
||||
video=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(view.surfaceTexture)),view.width,view.height,
|
||||
{ value,_-> if(token==epoch && !faulted) {
|
||||
val key=value.key
|
||||
if(key.loopOrdinal!=0L || key.index!=lastIndex+1 || (media.ptsUs.getOrNull(key.index)?.let { kotlin.math.abs(it-key.ptsUs)<=2 }!=true) || value.selection.opacity!=0f) fault("video_frame_invalid")
|
||||
else {
|
||||
lastIndex=key.index;lastPts=key.ptsUs
|
||||
if(!playing) announceReady() else { if(key.index==media.ptsUs.lastIndex) event("final_codec_frame");video?.advance() }
|
||||
}
|
||||
} },{ _-> if(token==epoch) fault("video_decoder_or_gl") },automatic=false,mayLoop=false,
|
||||
mouthEnabled=false,videoOnlyFromAv=true,ended={ if(token==epoch && !faulted) {
|
||||
videoEnded=true;event("video_completed");finishIfReady()
|
||||
main.postDelayed({ if(token==epoch && videoEnded && !nativeEnded && playing) fault("audio_end_missing") },2_000)
|
||||
} })
|
||||
val current=MediaPlayer();player=current;current.setSurface(null);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) fault("dimensions_invalid") else { event("prepared");ready() }
|
||||
} }
|
||||
current.setOnCompletionListener { if(token==epoch && playing) {
|
||||
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.setOnPreparedListener { if(token==epoch && !faulted) { audioReady=true;event("audio_prepared");announceReady() } }
|
||||
current.setOnCompletionListener { if(token==epoch && playing && !faulted) {
|
||||
if(SystemClock.elapsedRealtime()-startedMs+50 < media.audioEndUs/1000) fault("audio_duration_early")
|
||||
else { nativeEnded=true;event("native_completed");finishIfReady() }
|
||||
// Missing video progress retains the decoder's bounded watchdog, never fabricates an end.
|
||||
} }
|
||||
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.
|
||||
false // Informational only; audio player owns no visible surface.
|
||||
}
|
||||
current.setOnErrorListener { _,_,_->if(token==epoch) fault("native_error");true }
|
||||
current.prepareAsync()
|
||||
} catch(_: Exception) { fault("prepare_failed") }
|
||||
}
|
||||
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(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) { fault("timestamp_not_indexed",pts);return }
|
||||
if(timeline[index]<lastPts) { fault("timestamp_regressed",pts);return }
|
||||
if(lastPts<0) {
|
||||
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() {
|
||||
override fun start() {
|
||||
if(faulted) return
|
||||
try {
|
||||
check(readySent && lastIndex==0 && !playing)
|
||||
startedMs=SystemClock.elapsedRealtime();playing=true;checkNotNull(player).start();event("started")
|
||||
// Frame0 is already decoded, input-latched, composited and held on this action surface.
|
||||
event("first_codec_frame");firstFrame?.invoke();firstFrame=null;video?.advance()
|
||||
} catch(_: Exception) { fault("start_failed") }
|
||||
}
|
||||
/** EGL output presentation timestamps are diagnostic only. They cannot index source media.
|
||||
* Zero/old/epoch timestamps from SurfaceTexture updates never grant an entry or completion. */
|
||||
fun latched(timestampNs: Long) { if(playing && !faulted) event("output_texture_updated",timestampNs/1000) }
|
||||
fun resize(width: Int,height: Int) { video?.resize(width,height) }
|
||||
private fun finishIfReady() {
|
||||
val current=media ?: return
|
||||
if(nativeEnded && lastPts==current.ptsUs.last()) {
|
||||
nativeEnded=false
|
||||
if(!faulted && playing && nativeEnded && videoEnded && lastIndex==current.ptsUs.lastIndex && kotlin.math.abs(lastPts-current.ptsUs.last())<=2) {
|
||||
if(SystemClock.elapsedRealtime()-startedMs<(current.durationUs+999)/1000) fault("duration_early")
|
||||
else { event("validated_end");ended?.invoke() }
|
||||
else { playing=false;event("validated_end");ended?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun close(released: ()->Unit) {
|
||||
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
|
||||
event("released");main.post { released() }
|
||||
event("closing");epoch++;playing=false;nativeEnded=false;firstFrame=null;ready=null;ended=null
|
||||
val old=player;val oldVideo=video;video=null
|
||||
try {
|
||||
try { old?.stop() } catch(_: Exception) { } // release also stops a prepared/error player.
|
||||
old?.release();player=null;media=null;event("audio_released")
|
||||
val finish={ event("released");released() }
|
||||
oldVideo?.close(finish) ?: main.post(finish)
|
||||
} catch(_: Exception) { event("release_failed");val callback=failed;failed=null;callback?.invoke() } // No false release acknowledgement.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,7 +159,8 @@ object EmotionActionManifest {
|
||||
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"])))
|
||||
pts,duration,480,848,fallback,sourceFrame.toInt(),fallback,returnFrame.toInt(),integer(action["audioEndUs"]),
|
||||
boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)))
|
||||
}
|
||||
ReviewedActionPack(actualSha,assets)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user