Fix action playback source clock using controlled video decode

This commit is contained in:
zenord
2026-10-13 12:32:37 +08:00
parent 9cebf4f3d3
commit 9ec71c7e20
15 changed files with 335 additions and 91 deletions
+1
View File
@@ -6,6 +6,7 @@ import android.media.MediaPlayer
import android.view.TextureView
fun main() {
reportedActionClockCheck()
playbackDiagnosticCheck()
boundedRuntimeDiagnosticCheck()
dynamicBodyCheck()
+9 -6
View File
@@ -11,23 +11,26 @@ object CodecFixture {
var rendered=mutableListOf<Long>(); var onRender: ((Long) -> Unit)? = null
var emitNativeSurface=false
val timelines=mutableMapOf<String,List<Long>>()
val audioPaths=mutableSetOf<String>()
fun reset() {
frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false
seeks.clear(); releases=0; flushes=0; rendered.clear(); onRender=null
emitNativeSurface=false;timelines.clear()
emitNativeSurface=false;timelines.clear();audioPaths.clear()
}
}
class MediaFormat {
class MediaFormat(private val mime: String="video/avc") {
companion object { const val KEY_MIME="mime"; const val KEY_WIDTH="width"; const val KEY_HEIGHT="height" }
fun getString(key: String): String? = "video/avc"
fun getString(key: String): String? = mime
fun getInteger(key: String): Int = if (key == KEY_WIDTH) 480 else 848
}
class MediaExtractor {
val trackCount=1; private var frame=0
private var av=false
val trackCount get()=if(av) 2 else 1
private var frame=0
private var timeline: List<Long>?=null
val sampleTime: Long get() = timeline?.getOrNull(frame) ?: if(frame >= (timeline?.size ?: CodecFixture.frames)) -1L else CodecFixture.firstPtsUs+frame*1_000_000L/CodecFixture.fps
fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) { timeline=CodecFixture.timelines[android.content.AssetFixture.paths[fd]] }
fun getTrackFormat(index: Int) = MediaFormat()
fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) { val path=android.content.AssetFixture.paths[fd];timeline=CodecFixture.timelines[path];av=path in CodecFixture.audioPaths }
fun getTrackFormat(index: Int) = MediaFormat(if(av && index==1) "audio/mp4a-latm" else "video/avc")
fun selectTrack(index: Int) {}
fun seekTo(time: Long,mode: Int) { CodecFixture.seeks += time; frame=(time*CodecFixture.fps/1_000_000).toInt()/CodecFixture.gop*CodecFixture.gop }
fun readSampleData(buffer: ByteBuffer,offset: Int): Int = if (frame >= (timeline?.size ?: CodecFixture.frames)) -1 else 1
+2 -1
View File
@@ -11,7 +11,8 @@ class MediaPlayer {
var isLooping = false; val looping get() = isLooping
var volume = 1f; var released = false; var started = false
val videoWidth = 480; val videoHeight = 848
fun setSurface(surface: Surface) {}
var videoSurface: Surface? = null
fun setSurface(surface: Surface?) { videoSurface=surface }
fun setVolume(left: Float,right: Float) { volume = left }
fun setDataSource(fd: java.io.FileDescriptor, offset: Long,length: Long) {}
fun setOnPreparedListener(callback: (MediaPlayer)->Unit) { prepared = callback }
+6 -5
View File
@@ -37,6 +37,7 @@ fun actualMediaViewCheck() {
fun rig(index: EmotionActionIndex=mediaFixtureIndex()): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<VideoPresentation>> {
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.filterNot { it.nativeLoop }.forEach { CodecFixture.timelines[(it.mouthRuntime?.root ?: index.root)+(it.mouthRuntime?.body?.path ?: it.clip.path)]=it.clip.ptsUs }
index.actionPack?.assets?.mapNotNull { it.media }?.forEach { CodecFixture.timelines[it.root+it.path]=it.ptsUs;CodecFixture.audioPaths.add(it.root+it.path) }
val binding=AvatarMediaBinding();binding.beginTurn(7)
val reports=mutableListOf<VideoPresentation>()
val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,reports::add)
@@ -113,11 +114,11 @@ fun actualMediaViewCheck() {
stopped!!(true);val movie=MediaPlayer.created.single()
check(!movie.started);movie.prepared!!(movie)
TestScheduler.until { movie.started }
check(trace.last().clipId.startsWith("f96_") && trace.last().actual=="action");cases++
check(trace.any { it.clipId.startsWith("f96_") && it.actual=="action" } && trace.last().actual=="action_first_frame");cases++
val textures=actionView.children.filterIsInstance<TextureView>()
fun latch(pts: Long) { val texture=checkNotNull(textures[3].surfaceTexture);texture.timestamp=pts*1000
textures[3].surfaceTextureListener!!.onSurfaceTextureUpdated(texture) }
check(textures[3].alpha==0f);latch(0);check(textures[3].alpha==1f);cases++
check(textures[3].alpha==1f);latch(0);check(textures[3].alpha==1f);cases++
when(mode) {
"complete","late_final_frame" -> {
index.actionPack!!.assets.first().media!!.ptsUs.drop(1).dropLast(if(mode=="late_final_frame") 1 else 0).forEach(::latch)
@@ -145,7 +146,7 @@ fun actualMediaViewCheck() {
val base=mediaFixtureIndex()
val original=base.actionPack!!.assets.first()
val media=original.media!!.copy(ptsUs=List(241) { it*1_000_000L/24 },durationUs=10_041_667,
sourceFrame=0,returnFrame=96)
sourceFrame=0,returnFrame=96,audioEndUs=10_000_000)
val asset=original.copy(durationMs=10_042,media=media)
val index=base.copy(actionPack=base.actionPack.copy(assets=listOf(asset,asset.copy(id="asset_02"))))
val (v,b,trace)=rig(index)
@@ -158,8 +159,8 @@ fun actualMediaViewCheck() {
val textures=v.children.filterIsInstance<TextureView>()
fun latch(pts: Long) { val t=textures[3].surfaceTexture!!;t.timestamp=pts*1000;textures[3].surfaceTextureListener!!.onSurfaceTextureUpdated(t) }
val owner=driverField.get(v) as ConversationMediaDriver
// Delayed first frame leaves the last valid body visible, with ACTION owning it.
TestScheduler.advanceBy(80);check(owner.layerOwner==ConversationMediaDriver.LayerOwner.ACTION && textures[3].alpha==0f);cases++
// First source frame was decoded+latched and held before native audio could start.
TestScheduler.advanceBy(80);check(owner.layerOwner==ConversationMediaDriver.LayerOwner.ACTION && textures[3].alpha==1f);cases++
latch(0);TestScheduler.advanceBy(21)
check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f } && player.started);cases++
prepared(player) // Duplicated ready cannot start/reclaim again.
+39 -17
View File
@@ -8,30 +8,51 @@ import android.graphics.SurfaceTexture
fun playbackDiagnosticCheck() {
var assertions=0
val asset=mediaFixtureIndex().actionPack!!.assets.first()
for(reason in listOf("first_frame_not_zero","timestamp_not_indexed","timestamp_regressed","native_error","native_ended_missing_final","duration_early")) {
TestScheduler.reset();MediaPlayer.created.clear()
// Exact device report: compositor output clock jumped from0 to47,741,893,941us.
// Reproduce the old failure independently, then pass that same output sequence
// through the production adapter while source codec frames remain exact.
val reported=listOf(0L,47_741_893_941_000L,47_742_026_182_000L)
check(reported.drop(1).none { ts->asset.media!!.ptsUs.any { kotlin.math.abs(it-ts/1000)<=2 } });assertions++
for(mode in listOf("report_clock","early_audio_end","native_error","wrong_codec_pts","missing_audio_end","cancel")) {
TestScheduler.reset();android.media.CodecFixture.reset();MediaPlayer.created.clear()
val media=asset.media!!
android.media.CodecFixture.emitNativeSurface=true
android.media.CodecFixture.timelines[media.root+media.path]=media.ptsUs
android.media.CodecFixture.audioPaths.add(media.root+media.path)
if(mode=="wrong_codec_pts") android.media.CodecFixture.timestampOffsetUs=10_000
val view=TextureView(android.content.Context());val messages=mutableListOf<String>()
val port=AndroidMusicPort(android.content.Context(),view,messages::add)
var ready=false;var first=0;var ended=0;var failures=0
port.prepare(asset.media!!,{ready=true},{first++},{ended++},{failures++})
val native=MediaPlayer.created.last();native.prepared!!(native);check(ready);assertions++
port.start();native.info!!(native,MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
check(first==0 && ended==0);assertions++ // Info does not claim surface presentation.
when(reason) {
"first_frame_not_zero"->port.latched(asset.media.ptsUs[1]*1000)
"timestamp_not_indexed"->port.latched(123456789)
"timestamp_regressed"->{port.latched(0);port.latched(asset.media.ptsUs[1]*1000);port.latched(0)}
"native_error"->native.error!!(native,1,2)
"native_ended_missing_final"->{port.latched(0);native.completion!!(native);TestScheduler.advanceBy(2001)}
"duration_early"->{port.latched(0);port.latched(asset.media.ptsUs.last()*1000);native.completion!!(native)}
port.prepare(media,{ready=true},{first++},{ended++},{failures++})
val native=MediaPlayer.created.last();native.prepared!!(native)
TestScheduler.until { ready || failures>0 }
if(mode=="wrong_codec_pts") {
check(!ready && failures==1 && messages.any { "event=video_decoder_or_gl " in it });assertions++
} else {
check(ready && first==0 && native.videoSurface==null);assertions++
native.info!!(native,MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0);check(first==0);assertions++
port.start();check(first==1 && native.started);assertions++
reported.forEach(port::latched)
check(failures==0 && ended==0);assertions++
when(mode) {
"report_clock","early_audio_end" -> {
if(mode=="early_audio_end") {
native.completion!!(native);check(failures==1 && ended==0);assertions++
} else {
TestScheduler.advanceBy(1200);check(ended==0);assertions++
native.completion!!(native)
check(ended==1 && failures==0 && messages.any { "event=final_codec_frame " in it });assertions++
}
}
"native_error" -> { native.error!!(native,1,2);check(failures==1 && ended==0);assertions++ }
"missing_audio_end" -> { TestScheduler.advanceBy(3300);check(failures==1 && ended==0);assertions++ }
}
}
check(failures==1 && ended==0 && messages.any { "event=$reason " in it });assertions++
port.latched(123456789);port.latched(asset.media.ptsUs.last()*1000);TestScheduler.advanceBy(1001);native.completion!!(native)
check(failures==1 && ended==0);assertions++ // No error flood.
var release=0;port.close { release++ };TestScheduler.advanceBy(1)
check(native.released && release==1 && messages.last().contains("event=released"));assertions++
native.prepared!!(native);native.info!!(native,3,0);native.completion!!(native);native.error!!(native,1,2)
check(failures==1 && ended==0);assertions++ // Old native callbacks fenced.
val prior=ended;reported.forEach(port::latched);TestScheduler.advanceBy(100)
check(ended==prior && release==1);assertions++
}
class Player: ActionPlayer {
lateinit var end: (ActionEnd)->Unit;lateinit var failure: ()->Unit;lateinit var release: ()->Unit
@@ -61,6 +82,7 @@ fun playbackDiagnosticCheck() {
val index=mediaFixtureIndex()
index.packages.values.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.mapNotNull { it.mouthRuntime }.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.actionPack?.assets?.mapNotNull { it.media }?.forEach { android.media.CodecFixture.timelines[it.root+it.path]=it.ptsUs;android.media.CodecFixture.audioPaths.add(it.root+it.path) }
val binding=AvatarMediaBinding();val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding) {}
view.render(true);TestScheduler.advanceBy(1)
val local=OfflineDancePreview(index.actionPack,binding,{TestScheduler.now})
+67
View File
@@ -0,0 +1,67 @@
import com.gorios.lanvoice.avatar.*
import android.os.TestScheduler
import android.media.CodecFixture
import android.media.MediaPlayer
import android.view.TextureView
/** Fixed numeric metadata from code20 offline report, no user media or conversation. */
fun reportedActionClockCheck() {
var checks=0
val base=mediaFixtureIndex().actionPack!!.assets.first().media!!
val media=base.copy(ptsUs=List(241) { it*1_000_000L/24 },durationUs=10_041_667,audioEndUs=10_000_000)
for(mode in listOf("report_first_zero","report_first_epoch","rounding_1us","invalid_codec_timebase","missing_source_zero","missing_source_final","cancel_late_callbacks")) {
TestScheduler.reset();CodecFixture.reset();MediaPlayer.created.clear();CodecFixture.emitNativeSurface=true
CodecFixture.audioPaths.add(media.root+media.path)
CodecFixture.timelines[media.root+media.path]=when(mode) {
"missing_source_zero"->media.ptsUs.drop(1)
"missing_source_final"->media.ptsUs.dropLast(1)
else->media.ptsUs
}
CodecFixture.timestampOffsetUs=when(mode) { "rounding_1us"->1;"invalid_codec_timebase"->47_741_893_941;else->0 }
val output=TextureView(android.content.Context());val messages=mutableListOf<String>()
val port=AndroidMusicPort(android.content.Context(),output,messages::add)
var ready=false;var first=0;var end=0;var failures=0
port.prepare(media,{ready=true},{first++},{end++},{failures++})
val audio=MediaPlayer.created.single();audio.prepared!!(audio)
port.latched(0);audio.info!!(audio,MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
check(first==0 && end==0);checks++ // Neither output timestamp nor info grants source entry.
TestScheduler.until { ready || failures>0 }
if(mode in setOf("invalid_codec_timebase","missing_source_zero")) {
check(!ready && failures==1 && end==0);checks++
} else {
check(ready && audio.videoSurface==null && first==0) { "mode=$mode ready=$ready failures=$failures" };checks++
port.start();check(first==1);checks++
if(mode=="cancel_late_callbacks") {
val stale=audio.completion!!;var releases=0
TestScheduler.advanceBy(249);port.latched(47_741_893_941_000)
port.close { releases++ };TestScheduler.advanceBy(1)
stale(audio);audio.error!!(audio,1,2);TestScheduler.advanceBy(11_000)
check(releases==1 && end==0 && failures==0 && audio.released);checks++
} else {
repeat(241) { i->
// An EGL output update can skip, use0, an epoch clock, ns, or a repeated value.
// None may be relabelled as a source frame or satisfy completion.
TestScheduler.advanceBy(42)
port.latched(when {
mode=="report_first_zero" && i==0->0
i==0->47_742_026_182_000
i%17==0->0
i%13==0->41_666_000
else->47_741_893_941_000+i*41_666_000L
})
if(mode!="missing_source_final") { check(failures==0 && end==0);checks++ }
}
if(mode=="missing_source_final") { check(failures==1 && end==0);checks++ }
else {
audio.currentPosition=10_042;audio.completion!!(audio)
TestScheduler.until { end==1 || failures>0 }
check(end==1 && failures==0 && messages.any { "event=final_codec_frame " in it && "frame=240 " in it && "pts_us=${10_000_000L+CodecFixture.timestampOffsetUs} " in it });checks++
audio.completion!!(audio);check(end==1);checks++
}
}
}
var released=false;port.close { released=true };TestScheduler.advanceBy(1)
check(released && audio.released);checks++
}
println("PASS: $checks production code20 report-clock replay/full241-source-frame/zero-epoch-output/1us-rounding/invalid-codec-timebase/missing-source-endpoint/native-end/cancel-release assertions; native Android/GPU not_run")
}
+11
View File
@@ -245,6 +245,17 @@ class PackageTests(unittest.TestCase):
self.assertIn('-PavatarPlaybackDiagnostic=true',command)
self.assertIn('-PactionVersionCode=20',command)
def test_clock_fix_requires_full_frozen_pin_and_fresh_version(self):
with patch.object(pack,'tested_source'),patch.object(pack,'packaging_tests_current'),patch.object(pack,'read_json',return_value={'edges':[{'nativeLoop':True}]}),patch.object(pack,'next_version',return_value=21),patch.object(pack.subprocess,'run',side_effect=RuntimeError('build_sentinel')) as build:
for full,pin,code in ((False,pack.RUNTIME_FIX_PIN,21),(True,'0'*64,21),(True,pack.RUNTIME_FIX_PIN,20)):
with self.subTest(full=full,pin=pin,code=code),self.assertRaises(ValueError):
pack.publish({'manifest_sha256':pin},self.base,code,full,False,False,True)
build.assert_not_called()
with self.assertRaisesRegex(RuntimeError,'build_sentinel'):
pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},self.base,21,True,False,False,True)
self.assertIn('-PavatarPlaybackClockFix=true',build.call_args.args[0])
self.assertIn('-PactionVersionCode=21',build.call_args.args[0])
def test_cli_no_pin_no_import_no_output(self):
self.manifest.write_text(json.dumps(self.index));out=self.base/'no-pin-output'
result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'),