diff --git a/AGENTS.md b/AGENTS.md
index c21bbbf..0cd7d46 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,7 +35,7 @@ Install `app/build/outputs/apk/release/app-release.apk` instead for performance/
## Testing suite
-Use `& $KaleidoPython` before the Python commands below. Run only checks relevant to the change; **never run competing device/UI tests in parallel**. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home.
+Use `& $KaleidoPython` before the Python commands below. Run only checks relevant to the change; **never run competing device/UI tests in parallel**. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home. After a functional debug batch, restore the signed release and its ART profile before returning the device to normal use; never judge performance from an unoptimized debug build.
| Command | Purpose / required build |
| --- | --- |
@@ -75,7 +75,7 @@ These require the private test session. Playback test intents (`testTitleId`, `t
- Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread.
- Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**.
- Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences.
-- Playback has one quality preference (`StreamQuality`): **Original quality** (the default) direct-streams the source video, falling back to a 1080p conversion if the TV can't play it; 4K/1080p/720p/480p ask Plex to convert. Earlier mode/quality preferences migrate on first read. Debug test intents (`testMode`) still force a delivery mode. Augment Plex's existing HEVC target; competing transcode targets previously forced unnecessary H.264 conversion. A server decision to copy video does not itself prove successful rendering.
+- Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats.
- **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test.
- Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b26c3e8..6d2b131 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Kaleido releases
+## 0.1.10
+
+- Play the original media file first at Original quality, preserving supported 4K video, Dolby Vision/HDR metadata and multichannel audio instead of unnecessarily converting to 1080p/stereo.
+- Automatically fall back to Plex when the native player cannot render the source video, including files that previously produced audio without a picture. Movie controls identify server conversions of video or audio.
+- Use Android's standard mono PCM output mask when a source specifies a center-only mono layout, fixing the tested 24-bit/96 kHz WAV without changing its sample rate. Preserve multichannel layouts and compressed-audio passthrough.
+- Honor Plex's selected audio and subtitle tracks during native playback, including Subtitles Off, and serialize stream changes to keep seeks and quality changes from competing.
+
## 0.1.9
- Move Seasons up on TV show pages so the artwork and season labels fit together on the first screen.
diff --git a/app/src/androidTest/java/tv/kaleido/app/PlaybackCompatibilityTest.kt b/app/src/androidTest/java/tv/kaleido/app/PlaybackCompatibilityTest.kt
new file mode 100644
index 0000000..6e13e8a
--- /dev/null
+++ b/app/src/androidTest/java/tv/kaleido/app/PlaybackCompatibilityTest.kt
@@ -0,0 +1,28 @@
+package tv.kaleido.app
+
+import android.media.AudioFormat
+import android.media.AudioTrack
+import androidx.media3.common.C
+import androidx.media3.common.Format
+import androidx.media3.common.MimeTypes
+import org.junit.Assert.*
+import org.junit.Test
+
+@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
+class PlaybackCompatibilityTest {
+ @Test fun monoPcmHasAPlayableMaskWithoutChangingSamples() {
+ val source=Format.Builder().setSampleMimeType(MimeTypes.AUDIO_RAW).setChannelCount(1)
+ .setChannelMask(AudioFormat.CHANNEL_OUT_FRONT_CENTER).setSampleRate(96000).setPcmEncoding(C.ENCODING_PCM_24BIT).build()
+ val output=compatiblePcmFormat(source)
+ assertEquals(96000,output.sampleRate);assertEquals(source.pcmEncoding,output.pcmEncoding)
+ assertEquals(1,output.channelCount);assertEquals(AudioFormat.CHANNEL_OUT_MONO,output.channelMask)
+ // The default sink converts integer PCM to 16 bit before opening AudioTrack.
+ assertTrue(AudioTrack.getMinBufferSize(output.sampleRate,output.channelMask,C.ENCODING_PCM_16BIT)>0)
+ }
+ @Test fun multichannelPcmAndBitstreamsKeepTheirLayout() {
+ val pcm=Format.Builder().setSampleMimeType(MimeTypes.AUDIO_RAW).setChannelCount(6)
+ .setChannelMask(AudioFormat.CHANNEL_OUT_5POINT1).setSampleRate(48000).setPcmEncoding(C.ENCODING_PCM_16BIT).build()
+ val eac3=pcm.buildUpon().setSampleMimeType(MimeTypes.AUDIO_E_AC3).build()
+ assertSame(pcm,compatiblePcmFormat(pcm));assertSame(eac3,compatiblePcmFormat(eac3))
+ }
+}
diff --git a/app/src/androidTest/java/tv/kaleido/app/PlaybackValidationSetupTest.kt b/app/src/androidTest/java/tv/kaleido/app/PlaybackValidationSetupTest.kt
new file mode 100644
index 0000000..5df0d6e
--- /dev/null
+++ b/app/src/androidTest/java/tv/kaleido/app/PlaybackValidationSetupTest.kt
@@ -0,0 +1,46 @@
+package tv.kaleido.app
+
+import android.content.Context
+import android.hardware.display.DisplayManager
+import android.media.AudioManager
+import android.media.MediaCodecList
+import android.os.Build
+import androidx.test.platform.app.InstrumentationRegistry
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/** Explicit opt-in capability inventory. No session credentials are exported. */
+class PlaybackValidationSetupTest {
+ @Test fun privateValidationContext() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("validationSetup")=="true")
+ val app=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication
+ val codecs=JSONArray()
+ MediaCodecList(MediaCodecList.ALL_CODECS).codecInfos.filterNot{it.isEncoder}.forEach { codec->
+ codec.supportedTypes.forEach { type->
+ runCatching {
+ val caps=codec.getCapabilitiesForType(type)
+ codecs.put(JSONObject().put("name",codec.name).put("mime",type)
+ .put("hardware",if(Build.VERSION.SDK_INT>=29)codec.isHardwareAccelerated else JSONObject.NULL)
+ .put("profiles",JSONArray(caps.profileLevels.map{JSONObject().put("profile",it.profile).put("level",it.level)})))
+ }
+ }
+ }
+ val displays=app.getSystemService(DisplayManager::class.java).displays.map { display->
+ JSONObject().put("id",display.displayId).put("name",display.name)
+ .put("hdrTypes",JSONArray(display.hdrCapabilities.supportedHdrTypes.toList()))
+ .put("mode",display.mode.toString())
+ }
+ val audio=app.getSystemService(AudioManager::class.java)
+ val outputs=audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS).map { device->
+ JSONObject().put("id",device.id).put("type",device.type).put("name",device.productName)
+ .put("encodings",JSONArray(device.encodings.toList())).put("channels",JSONArray(device.channelCounts.toList()))
+ }
+ val report=JSONObject().put("model",Build.MODEL).put("sdk",Build.VERSION.SDK_INT)
+ .put("codecs",codecs).put("displays",JSONArray(displays)).put("audioOutputs",JSONArray(outputs))
+ .put("mediaVolume",audio.getStreamVolume(AudioManager.STREAM_MUSIC))
+ .put("mediaMuted",audio.isStreamMute(AudioManager.STREAM_MUSIC))
+ app.openFileOutput("validation-capabilities.json",Context.MODE_PRIVATE).use{it.write(report.toString(2).toByteArray())}
+ }
+}
diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml
new file mode 100644
index 0000000..bc90a87
--- /dev/null
+++ b/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/app/src/debug/java/tv/kaleido/app/HdmiValidationActivity.kt b/app/src/debug/java/tv/kaleido/app/HdmiValidationActivity.kt
new file mode 100644
index 0000000..a038132
--- /dev/null
+++ b/app/src/debug/java/tv/kaleido/app/HdmiValidationActivity.kt
@@ -0,0 +1,54 @@
+package tv.kaleido.app
+
+import android.app.Activity
+import android.media.tv.TvContract
+import android.media.tv.TvView
+import android.os.Bundle
+import android.view.Gravity
+import android.widget.FrameLayout
+import android.widget.TextView
+import org.json.JSONObject
+
+/** Temporary, public-TIF HDMI observer. No capture permissions or device settings changes. */
+class HdmiValidationActivity:Activity() {
+ private lateinit var tv:TvView
+ private lateinit var label:TextView
+ private fun extras(bundle:Bundle?)=bundle?.let{b->b.keySet().joinToString{key->"$key=${b.get(key)}"}}.orEmpty()
+ private fun record(event:String,data:String="") {
+ val line=JSONObject().put("event",event).put("detail",data).put("elapsedMs",android.os.SystemClock.elapsedRealtime()).toString()
+ openFileOutput("hdmi-validation.jsonl",MODE_APPEND).use{it.write((line+"\n").toByteArray())}
+ label.text="HDMI validation · $event"
+ }
+ override fun onCreate(state:Bundle?) {
+ super.onCreate(state)
+ window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ setTurnScreenOn(true)
+ window.decorView.systemUiVisibility=android.view.View.SYSTEM_UI_FLAG_FULLSCREEN or android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ val input=intent.getStringExtra("inputId") ?: return finish()
+ tv=TvView(this)
+ label=TextView(this).apply{setTextColor(android.graphics.Color.WHITE);setBackgroundColor(0x99000000.toInt());setPadding(18,10,18,10)}
+ val root=FrameLayout(this).apply {
+ addView(tv,FrameLayout.LayoutParams(-1,-1))
+ addView(label,FrameLayout.LayoutParams(-2,-2,Gravity.BOTTOM or Gravity.START))
+ }
+ setContentView(root)
+ openFileOutput("hdmi-validation.jsonl",MODE_PRIVATE).close()
+ tv.setCallback(object:TvView.TvInputCallback() {
+ override fun onVideoAvailable(inputId:String){record("videoAvailable")}
+ override fun onVideoUnavailable(inputId:String,reason:Int){record("videoUnavailable",reason.toString())}
+ override fun onConnectionFailed(inputId:String){record("connectionFailed")}
+ override fun onDisconnected(inputId:String){record("disconnected")}
+ override fun onVideoSizeChanged(inputId:String,width:Int,height:Int){record("size","${width}x$height")}
+ override fun onTracksChanged(inputId:String,tracks:MutableList?) {
+ record("tracks",tracks?.joinToString { t->
+ if(t.type==android.media.tv.TvTrackInfo.TYPE_VIDEO)"video ${t.videoWidth}x${t.videoHeight} ${t.videoFrameRate} ${extras(t.extra)}"
+ else "type=${t.type} ${t.extra}"
+ }.orEmpty())
+ }
+ override fun onTvMessage(inputId:String,type:Int,args:Bundle){record("message:$type",args.toString())}
+ })
+ record("tuning",input)
+ runCatching{tv.tune(input,TvContract.buildChannelUriForPassthroughInput(input))}.onFailure{record("tuneFailed",it.javaClass.simpleName)}
+ }
+ override fun onDestroy(){if(::tv.isInitialized)tv.reset();super.onDestroy()}
+}
diff --git a/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt
new file mode 100644
index 0000000..51a537a
--- /dev/null
+++ b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt
@@ -0,0 +1,27 @@
+package tv.kaleido.app
+
+import android.media.AudioFormat
+import androidx.media3.common.Format
+import androidx.media3.common.MimeTypes
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.exoplayer.audio.AudioSink
+import androidx.media3.exoplayer.audio.ForwardingAudioSink
+
+/** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */
+@androidx.annotation.OptIn(UnstableApi::class)
+internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) {
+ @Suppress("DEPRECATION")
+ override fun configure(config:AudioSink.AudioSinkConfig) {
+ val format=compatiblePcmFormat(config.format)
+ super.configure(if(format===config.format)config else AudioSink.AudioSinkConfig.Builder(format)
+ .setPreferredBufferSizeOverride(config.preferredBufferSizeOverride)
+ .setOutputChannelMapping(config.outputChannelMapping)
+ .setTimeline(config.timeline).setMediaPeriodId(config.mediaPeriodId).build())
+ }
+}
+
+@androidx.annotation.OptIn(UnstableApi::class)
+internal fun compatiblePcmFormat(format:Format):Format =
+ if(format.sampleMimeType==MimeTypes.AUDIO_RAW&&format.channelCount==1&&format.channelMask!=AudioFormat.CHANNEL_OUT_MONO)
+ format.buildUpon().setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build()
+ else format
diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt
index 228987e..9bcca8a 100644
--- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt
+++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt
@@ -69,6 +69,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var streamQuality by mutableStateOf(savedStreamQuality()); private set
/** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */
var debugMode by mutableStateOf(null); private set
+ var debugValidation=false; private set
+ var debugValidationFile:File?=null; private set
var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set
var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set
var episodeQueue by mutableStateOf(emptyList());private set
@@ -277,6 +279,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
sectionCache.clear()
}
fun play(item: Title,fromStart: Boolean=false)=launchLoad {
+ debugMode=null;debugValidation=false;debugValidationFile=null
val playable=if(item.type=="show" || item.type=="season") {
val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.")
} else item
@@ -335,5 +338,17 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun clearDownload(){downloadedApk=null}
/** Back from the system installer without updating: the verified APK can be installed again. */
fun installerReturned(){if(readyApk!=null&&!downloading)updateStatus="Update downloaded. Select Install ${update?.version.orEmpty()} to finish."}
- fun debugPlay(id: String,offset: Long,mode: Int){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);debugMode=mode;playing=api.details(id).copy(offset=offset);startFromZero=false}}
+ fun debugPlay(id: String,offset: Long,mode: Int,validation:Boolean=false){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);debugValidationFile=null;debugMode=mode.takeIf{it>=0};debugValidation=validation;playing=api.details(id).copy(offset=offset);startFromZero=false}}
+ /** Private, opt-in test media uses the same controller and SurfaceView as Plex playback. */
+ fun debugPlayFixture(name:String){
+ if(!BuildConfig.DEBUG||!name.matches(Regex("[a-z0-9-]+")))return
+ launchLoad {
+ val folder=File(application.filesDir,"validation").canonicalFile
+ val fixture=Title.parse(JSONObject(File(folder,"$name.json").readText()))
+ val file=File(folder,fixture.media.first().parts.first().key).canonicalFile
+ require(file.parentFile==folder&&file.isFile)
+ playing=null;delay(150);debugMode=0;debugValidation=true;debugValidationFile=file
+ playing=fixture;startFromZero=true
+ }
+ }
}
diff --git a/app/src/main/java/tv/kaleido/app/MainActivity.kt b/app/src/main/java/tv/kaleido/app/MainActivity.kt
index 9edc338..8f81828 100644
--- a/app/src/main/java/tv/kaleido/app/MainActivity.kt
+++ b/app/src/main/java/tv/kaleido/app/MainActivity.kt
@@ -42,6 +42,9 @@ class MainActivity: ComponentActivity() {
debugPlayback(intent)
}
override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent)}
- private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG)intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0))}}
+ private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){
+ intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return}
+ intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0),intent.getBooleanExtra("testValidation",false))}
+ }}
override fun onStart() { super.onStart(); model.checkUpdate(false) }
}
diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt
index 7b59468..3cdce91 100644
--- a/app/src/main/java/tv/kaleido/app/Playback.kt
+++ b/app/src/main/java/tv/kaleido/app/Playback.kt
@@ -40,6 +40,8 @@ import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.util.UUID
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
data class TimelineReport(val position: Long,val state: String,val duration: Long,val final: Boolean=false)
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@@ -49,15 +51,31 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate)
val selector=DefaultTrackSelector(app)
private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"})))
- val player=ExoPlayer.Builder(app,DefaultRenderersFactory(app).setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
+ private val renderers=object:DefaultRenderersFactory(app) {
+ override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink =
+ CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
+ .setEnableFloatOutput(enableFloatOutput)
+ .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
+ .build())
+ }.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()
+ val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)
setHandleAudioBecomingNoisy(true)
}
val mediaSession=MediaSession.Builder(app,player).setId("kaleido-${UUID.randomUUID()}").build()
- // Original quality direct-streams the source video (remuxed, never re-encoded) and falls back
- // to conversion if the TV can't play it; a resolution always asks Plex to convert.
- var mode by mutableIntStateOf(vm.debugMode ?: if(vm.streamQuality==StreamQuality.Original)1 else 2);private set
- val qualityLabel get()=if(mode<2)StreamQuality.Original.label else "Converting · "+vm.streamQuality.conversion.label
+ private val validation=BuildConfig.DEBUG&&vm.debugValidation
+ private val localValidationFile=if(validation)vm.debugValidationFile else null
+ private val audit=if(validation)PlaybackValidationLog(app,item,player)else null
+ // Preserve the actual file first; Plex's generic HLS profile can convert even with directStream=1.
+ var mode by mutableIntStateOf(vm.debugMode ?: if(vm.streamQuality==StreamQuality.Original)0 else 2);private set
+ private var serverConverting by mutableStateOf(false)
+ private var serverAudioConverting by mutableStateOf(false)
+ val qualityLabel get()=when {
+ mode==2->"Converting · "+vm.streamQuality.conversion.label
+ serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video"
+ serverAudioConverting->"Original video · Converted audio"
+ else->StreamQuality.Original.label
+ }
var loading by mutableStateOf(true);private set
var error by mutableStateOf(null);private set
var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set
@@ -75,17 +93,23 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private var streamStart=0L
private var preparing=false
private var closed=false
+ private val prepareMutex=Mutex()
+ private var fallbackPending=false
+ private var nativeSelectionApplied=false
private val reports=Channel(Channel.UNLIMITED)
private val reportJob=app.scope.launch {
val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
for(r in reports) {
- runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
- runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
- .onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
+ if(!validation) {
+ runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
+ runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
+ .onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
+ }
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession)};break}
}
}
init {
+ audit?.let{player.addAnalyticsListener(it)}
player.addListener(object: Player.Listener {
override fun onPlaybackStateChanged(state: Int) {
loading=state==Player.STATE_BUFFERING;ended=state==Player.STATE_ENDED
@@ -93,45 +117,91 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
if(ended) {position=duration;report("stopped");Log.i("KaleidoPlayback","ENDED")}
}
override fun onIsPlayingChanged(value: Boolean){isPlaying=value;if(!preparing&&!closed)report(if(value)"playing"else "paused")}
- override fun onTracksChanged(value: Tracks){tracks=value;Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")}
+ override fun onTracksChanged(value: Tracks){
+ tracks=value
+ Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")
+ // Some extractors expose only audio for an unsupported video codec (e.g. VC-1).
+ if(value.groups.isNotEmpty()&&item.media.first().videoCodec.isNotBlank()&&
+ value.groups.none{it.type==C.TRACK_TYPE_VIDEO&&it.isSupported(true)}) {
+ fallback("unsupportedVideo");return
+ }
+ if(mode==0&&!nativeSelectionApplied&&value.groups.isNotEmpty()) {
+ nativeSelectionApplied=true
+ applyNativeSelection(C.TRACK_TYPE_AUDIO,activeAudio)
+ applyNativeSelection(C.TRACK_TYPE_TEXT,activeSubtitle)
+ }
+ }
override fun onPlayerError(e: PlaybackException) {
Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode")
- if(mode<2){scope.launch{prepare(mode+1,position)}}else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}
+ if(mode<2&&localValidationFile==null)fallback(e.errorCodeName)else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}
}
})
scope.launch {prepare(mode,position)}
+ if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}}
scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=player.bufferedPosition.coerceIn(0,duration);val d=player.duration;if(d>0)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}}
}
private fun currentPosition() = player.currentPosition.coerceIn(0,duration.coerceAtLeast(0))
private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))}
- suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) {
+ private fun fallback(reason:String) {
+ if(closed||mode>=2||localValidationFile!=null||fallbackPending)return
+ fallbackPending=true
+ val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady
+ scope.launch {
+ try {prepareMutex.withLock {
+ if(!closed&&session==streamSession) {
+ audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset))
+ prepareInternal(mode+1,offset,resume)
+ }
+ }}finally{fallbackPending=false}
+ }
+ }
+ suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) = prepareMutex.withLock{prepareInternal(newMode,offset,resume)}
+ private suspend fun prepareInternal(newMode: Int,offset: Long,resume:Boolean) {
if(closed)return
- preparing=true;loading=true;error=null;ended=false;player.stop()
+ preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false
+ serverConverting=false;serverAudioConverting=false
+ // Empty track events from stop must not be mistaken for a missing video track.
+ player.stop()
try {
if(mode>0)runCatching{api.stopTranscode(streamSession)}
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=if(mode>0)offset else 0L
+ audit?.event("prepare",org.json.JSONObject().put("mode",mode).put("offset",offset))
val media=item.media.first();val part=media.parts.first()
val builder=MediaItem.Builder().setMediaId(item.id).setMediaMetadata(MediaMetadata.Builder().setTitle(item.title).setArtist(item.grandparentTitle).build())
if(mode==0) {
- builder.setUri(api.url(part.key))
+ builder.setUri(if(localValidationFile!=null)android.net.Uri.fromFile(localValidationFile).toString()else api.url(part.key))
builder.setSubtitleConfigurations(part.streams.filter{it.type==3&&it.key.isNotBlank()&&it.codec in listOf("srt","webvtt","vtt","ass","ssa")}.map {s ->
MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==activeSubtitle)C.SELECTION_FLAG_DEFAULT else 0).build()
})
} else {
val p=api.transcodeParams(item,streamSession,mode,offset,vm.streamQuality.conversion)
val decision=api.container("/video/:/transcode/universal/decision",p)
+ val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}
+ .flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
+ serverConverting=streams.any{it.optInt("streamType")==1&&it.optString("decision")=="transcode"}
+ serverAudioConverting=streams.any{it.optInt("streamType")==2&&it.optString("decision")=="transcode"}
+ audit?.event("decision",org.json.JSONObject().apply{
+ listOf("generalDecisionCode","generalDecisionText","directPlayDecisionCode","directPlayDecisionText","transcodeDecisionCode","transcodeDecisionText").forEach{k->if(decision.has(k))put(k,decision.get(k))}
+ }
+ .put("streams",org.json.JSONArray(decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}
+ .flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}.map{s->
+ org.json.JSONObject().apply{listOf("streamType","codec","decision","profile","bitDepth","colorTrc","DOVIProfile").forEach{k->if(s.has(k))put(k,s.get(k))}}
+ })))
if(decision.optInt("generalDecisionCode")>=2000)throw PlexException(decision.optString("generalDecisionText","Server cannot convert this media."))
builder.setUri(api.url("/video/:/transcode/universal/start.m3u8",p)).setMimeType(MimeTypes.APPLICATION_M3U8)
}
// Plex HLS exposes the original absolute timeline, including a seek-start offset.
player.setMediaItem(builder.build(),offset);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate)
Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset")
- }catch(e:CancellationException){throw e}catch(e:Exception){if(newMode<2)prepare(newMode+1,offset)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."}}
+ }catch(e:CancellationException){throw e}catch(e:Exception){
+ audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status))
+ if(newMode<2&&localValidationFile==null)prepareInternal(newMode+1,offset,resume)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."}
+ }
}
fun seekTo(target:Long){val clamped=target.coerceIn(0,duration);if(mode>0&&clamped? {
+ val candidates=tracks.groups.withIndex().filter{it.value.type==type}.flatMap{g->(0 until g.value.length).map{g.index to it}}
+ if(stream.key.isNotBlank())return candidates.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id}
+ val ordinal=item.media.first().parts.first().streams.filter{it.type==stream.type&&it.key.isBlank()}.indexOfFirst{it.id==stream.id}
+ return candidates.filter{(g,t)->tracks.groups[g].getTrackFormat(t).id !in item.media.first().parts.first().streams.filter{it.key.isNotBlank()}.map{it.id}}.getOrNull(ordinal)
+ }
+ private fun applyNativeSelection(type:Int,id:String) {
+ if(type==C.TRACK_TYPE_TEXT&&id=="0") {
+ selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return
+ }
+ val stream=item.media.first().parts.first().streams.firstOrNull{it.id==id} ?: return
+ val match=nativeTrack(type,stream) ?: return
+ if(tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
+ else fallback("unsupportedSelectedTrack")
+ }
fun selectServerStream(stream:Stream?,type:Int) {
scope.launch {
try {
@@ -147,18 +232,13 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
if(type==C.TRACK_TYPE_TEXT){activeSubtitle=stream?.id ?: "0";api.selectStreams(part,subtitle=activeSubtitle)}else{activeAudio=stream?.id.orEmpty();api.selectStreams(part,audio=activeAudio)}
if(mode>0){prepare(mode,position,player.playWhenReady);return@launch}
if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch}
- val groups=tracks.groups.withIndex().filter{it.value.type==type}
- val matching=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id}
- val matchingExternal=if(type==C.TRACK_TYPE_TEXT&&stream.key.isNotBlank())matching else null
- val streamIndex=part.streams.filter{it.type==(if(type==C.TRACK_TYPE_AUDIO)2 else 3)&&it.key.isBlank()}.indexOfFirst{it.id==stream.id}
- val candidates=groups.flatMap{g->(0 until g.value.length).map{g.index to it}}
- val match=matchingExternal ?: matching ?: candidates.getOrNull(streamIndex)
- if(match!=null)select(type,match.first,match.second)
+ val match=nativeTrack(type,stream)
+ if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex.
}catch(e:Exception){error=e.message ?: "Could not change the selected track."}
}
}
- fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();report("stopped",true);reports.close();mediaSession.release();player.release()}
+ fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
}
/** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */
enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) {
diff --git a/app/src/main/java/tv/kaleido/app/PlaybackValidationLog.kt b/app/src/main/java/tv/kaleido/app/PlaybackValidationLog.kt
new file mode 100644
index 0000000..1a67a27
--- /dev/null
+++ b/app/src/main/java/tv/kaleido/app/PlaybackValidationLog.kt
@@ -0,0 +1,71 @@
+package tv.kaleido.app
+
+import android.content.Context
+import android.util.Base64
+import androidx.media3.common.*
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.exoplayer.*
+import androidx.media3.exoplayer.analytics.AnalyticsListener
+import androidx.media3.exoplayer.audio.AudioSink
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.launch
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** Opt-in debug evidence only: never serialize media URLs, headers, or session credentials. */
+@androidx.annotation.OptIn(UnstableApi::class)
+internal class PlaybackValidationLog(app:KaleidoApplication,item:Title,private val player:ExoPlayer):AnalyticsListener {
+ private val lines=Channel(Channel.UNLIMITED)
+ init {
+ app.scope.launch(Dispatchers.IO) {
+ app.openFileOutput("playback-validation.jsonl",Context.MODE_PRIVATE).bufferedWriter().use { out->
+ for(line in lines){out.write(line);out.newLine();out.flush()}
+ }
+ }
+ event("source",JSONObject().put("id",item.id).put("title",item.title).put("type",item.type)
+ .put("media",JSONArray(item.media.map{JSONObject().put("videoCodec",it.videoCodec).put("audioCodec",it.audioCodec)
+ .put("width",it.width).put("height",it.height).put("container",it.container).put("bitrate",it.bitrate)})))
+ }
+ fun event(name:String,data:JSONObject=JSONObject()) {
+ data.put("event",name).put("elapsedMs",android.os.SystemClock.elapsedRealtime())
+ lines.trySend(data.toString())
+ }
+ private fun format(f:Format):JSONObject=JSONObject().put("mime",f.sampleMimeType).put("codecs",f.codecs)
+ .put("width",f.width).put("height",f.height).put("fps",f.frameRate).put("channels",f.channelCount).put("channelMask",f.channelMask).put("sampleRate",f.sampleRate).put("pcmEncoding",f.pcmEncoding)
+ .apply { f.colorInfo?.let { c->
+ put("colorSpace",c.colorSpace).put("colorRange",c.colorRange).put("colorTransfer",c.colorTransfer)
+ put("hdrStaticInfo",c.hdrStaticInfo?.let{Base64.encodeToString(it,Base64.NO_WRAP)} ?: JSONObject.NULL)
+ }}
+ fun sample(mode:Int) {
+ event("sample",JSONObject().put("mode",mode).put("state",player.playbackState).put("playing",player.isPlaying)
+ .put("position",player.currentPosition).put("buffered",player.bufferedPosition).put("duration",player.duration)
+ .put("video",player.videoFormat?.let(::format)).put("audio",player.audioFormat?.let(::format))
+ .put("videoCounters",player.videoDecoderCounters?.let(::counters)).put("audioCounters",player.audioDecoderCounters?.let(::counters)))
+ }
+ private fun counters(c:DecoderCounters):JSONObject {
+ c.ensureUpdated()
+ return JSONObject().put("queued",c.queuedInputBufferCount).put("rendered",c.renderedOutputBufferCount)
+ .put("dropped",c.droppedBufferCount).put("skipped",c.skippedOutputBufferCount)
+ .put("maxConsecutiveDropped",c.maxConsecutiveDroppedBufferCount)
+ }
+ override fun onVideoDecoderInitialized(t:AnalyticsListener.EventTime,name:String,a:Long,b:Long){event("videoDecoder",JSONObject().put("name",name))}
+ override fun onAudioDecoderInitialized(t:AnalyticsListener.EventTime,name:String,a:Long,b:Long){event("audioDecoder",JSONObject().put("name",name))}
+ override fun onVideoInputFormatChanged(t:AnalyticsListener.EventTime,f:Format,reuse:DecoderReuseEvaluation?){event("videoFormat",format(f))}
+ override fun onAudioInputFormatChanged(t:AnalyticsListener.EventTime,f:Format,reuse:DecoderReuseEvaluation?){event("audioFormat",format(f))}
+ override fun onRenderedFirstFrame(t:AnalyticsListener.EventTime,output:Any,renderTimeMs:Long){event("firstFrame")}
+ override fun onAudioPositionAdvancing(t:AnalyticsListener.EventTime,startTimeMs:Long){event("audioAdvancing")}
+ override fun onAudioTrackInitialized(t:AnalyticsListener.EventTime,c:AudioSink.AudioTrackConfig){
+ event("audioTrack",JSONObject().put("encoding",c.encoding).put("sampleRate",c.sampleRate)
+ .put("channelMask",c.channelConfig).put("offload",c.offload).put("tunneling",c.tunneling))
+ }
+ override fun onAudioUnderrun(t:AnalyticsListener.EventTime,size:Int,duration:Long,elapsed:Long){event("audioUnderrun",JSONObject().put("elapsedMsSinceFeed",elapsed))}
+ override fun onPlayerError(t:AnalyticsListener.EventTime,e:PlaybackException){
+ val http=generateSequence(e){it.cause}.filterIsInstance().firstOrNull()
+ event("error",JSONObject().put("code",e.errorCodeName).put("httpStatus",http?.responseCode)
+ .put("causes",JSONArray(generateSequence(e){it.cause}.map{cause->
+ JSONObject().put("type",cause.javaClass.simpleName).put("frames",JSONArray(cause.stackTrace.take(4).map{"${it.className}.${it.methodName}:${it.lineNumber}"}))
+ }.toList())))
+ }
+ fun finish(mode:Int){sample(mode);event("closed");lines.close()}
+}
diff --git a/distribution/Kaleido.apk b/distribution/Kaleido.apk
index befc2d9..233ebbc 100644
Binary files a/distribution/Kaleido.apk and b/distribution/Kaleido.apk differ
diff --git a/distribution/Kaleido.apk.sha256 b/distribution/Kaleido.apk.sha256
index ea7a489..a0389a5 100644
--- a/distribution/Kaleido.apk.sha256
+++ b/distribution/Kaleido.apk.sha256
@@ -1 +1 @@
-ddc9b089bd02aaa0e636e27786159d86419dba8eba8e9995a569a3a9902b576b Kaleido.apk
+f93e377fd6746d0bb64689de3102a6da2615a790e46b023c78c885760bfe41e7 Kaleido.apk
diff --git a/distribution/latest.json b/distribution/latest.json
index 69ded63..fd40d6b 100644
--- a/distribution/latest.json
+++ b/distribution/latest.json
@@ -1,7 +1,7 @@
{
- "version": "0.1.9",
- "versionCode": 10,
- "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.9/distribution/Kaleido.apk",
- "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.9/distribution/Kaleido.apk.sha256",
- "notes": "- Move Seasons up on TV show pages so the artwork and season labels fit together on the first screen.\n- Constrain show descriptions to the movie-detail text width, with full text in an artwork-led Synopsis panel styled to match title details. Fade artwork to near-black behind lower rows and as details scroll.\n- Combine newly added seasons from the same Plex show into one card. Multiple seasons open the show's full season list; a single season still opens directly.\n- Make Movies and TV navigation enter Discover immediately, without waiting for catalog scrolling. Preserve a quick Down press while switching tabs and focus visible cards before scrolling.\n- Align horizontal focus and scrolling with the next frame, retain each requested D-pad step, and prepare nearby cards ahead of navigation. Prevent unnecessary focus searches above the top navigation."
+ "version": "0.1.10",
+ "versionCode": 11,
+ "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.10/distribution/Kaleido.apk",
+ "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.10/distribution/Kaleido.apk.sha256",
+ "notes": "- Play the original media file first at Original quality, preserving supported 4K video, Dolby Vision/HDR metadata and multichannel audio instead of unnecessarily converting to 1080p/stereo.\n- Automatically fall back to Plex when the native player cannot render the source video, including files that previously produced audio without a picture. Movie controls identify server conversions of video or audio.\n- Use Android's standard mono PCM output mask when a source specifies a center-only mono layout, fixing the tested 24-bit/96 kHz WAV without changing its sample rate. Preserve multichannel layouts and compressed-audio passthrough.\n- Honor Plex's selected audio and subtitle tracks during native playback, including Subtitles Off, and serialize stream changes to keep seeks and quality changes from competing."
}
diff --git a/docs/playback-validation-2026-10-26.md b/docs/playback-validation-2026-10-26.md
new file mode 100644
index 0000000..a8c461f
--- /dev/null
+++ b/docs/playback-validation-2026-10-26.md
@@ -0,0 +1,67 @@
+# Dedicated playback validation — 2026-10-26
+
+This records the 0.1.9 baseline investigation. The subsequent 0.1.10 fixes and release checks are recorded in [runtime verification](runtime-verification.md).
+
+Tested the onn 4K Plus (`192.168.50.195:5555`) connected to the TCL TV over HDMI, using 0.1.9 source plus opt-in debug instrumentation. These results describe this device chain and these fixtures. They are not a certification of every file, display, receiver, or Dolby profile.
+
+## Main finding
+
+The native file path can render 4K video and output multichannel audio, but the production **Original quality** path requests Plex HLS and unnecessarily converts the tested 4K sources. A 3840×2160 HEVC/AAC 5.1 source reached the player as 1920×1080 HEVC/AAC stereo. A 3840×1608 Dolby Vision profile 8/EAC3 7.1 source reached it as 1920×804 HEVC PQ/AAC stereo, losing Dolby Vision signaling. The latter was repeated with HDR formats fully enabled. Both files retained their source resolution/audio on forced native playback.
+
+This is a fidelity failure even though converted playback starts and renders. The previous live HEVC remux integration test covers a different, 1080p episode; its passing result does not cover these 4K cases. No production playback negotiation fix or new release was published during this validation.
+
+## HDR and Dolby Vision
+
+Verification combines Media3 input format, the selected decoder, rendered-frame counters, the SurfaceView's compositor state, and the ONN HDMI transmitter/HWC status. Output signaling is stronger evidence than the server's decision or advertised capabilities. It still cannot establish panel calibration, correct tone mapping, or perceptual image accuracy remotely.
+
+| Source | Observed native playback / HDMI output | Result |
+| --- | --- | --- |
+| Dolby Vision profile 5, HEVC MP4, 1080p | `dvhe.05.03`, Dolby Vision HEVC decoder, rendered test pattern; `DolbyVision-Std` | Rendering and signaling pass; local fixture, Plex delivery untested |
+| Dolby Vision profile 8, HEVC MKV, 4K | `dvhe.08.06`, Dolby Vision HEVC decoder; `DolbyVision-Std` | Rendering and signaling pass |
+| Dolby Vision profile 10, AV1 MKV, 4K | `dav1.10.08`, Dolby Vision AV1 decoder; `DolbyVision-Std` | Rendering and signaling pass |
+| HDR10, HEVC MP4, 4K | BT.2020/PQ input, HEVC hardware decoder; `HDR10-GAMMA_ST2084` | Rendering and signaling pass with Dolby Vision temporarily excluded |
+| HDR10, AV1 MKV, 4K | BT.2020/PQ input with mastering metadata, AV1 hardware decoder; `HDR10-GAMMA_ST2084` | Rendering and signaling pass with Dolby Vision temporarily excluded |
+| HLG, HEVC MKV, 4K | HLG input, HEVC hardware decoder; `HDR10-GAMMA_HLG` | Rendering and signaling pass under the original HLG-priority policy |
+| Dolby Vision profile 7 candidate | Frames rendered, but source advertises contradictory BT.709/SDR metadata | Inconclusive; not a valid reference for profile 7 enhancement-layer fidelity |
+| HDR10+ dynamic metadata | No independently identified reference tested | Not covered |
+
+The initial ONN configuration manually disabled Dolby Vision and HDR10. Clearing Android's disabled-format list, and even selecting Automatic, did **not** update its vendor `HLG priority` policy. That policy produced SDR for tested Dolby Vision inputs and HLG for a PQ source. Toggling Dolby Vision off/on through the normal manual-format UI updated the vendor policy to `DV_HDR10_HLG priority`, after which profile 5/8/10 output was confirmed as Dolby Vision. Excluding Dolby Vision while leaving HDR10 enabled selected `HDR10_HLG priority` and allowed isolated HDR10 checks. With System-preferred conversion, a HDR10 source can otherwise leave the device as Dolby Vision; that is device conversion and must be distinguished from the input format.
+
+The profile 5 fixture is Dolby's unencrypted [official color pattern](https://ott.dolby.com/OnDelKits/DolbyVision_OSS_Media_Kit/clear/color_pattern_24_dvhe_05_1920x1080.mp4), verified locally as profile 5 with compatibility ID 0. It was copied into Kaleido's private debug fixture directory and exercised through the same controller and SurfaceView. It was not uploaded to the Plex library. The HDMI status strings also correspond to the [Amlogic transmitter implementation](https://nest-open-source.googlesource.com/manifest_repos/kernel/+/1650886512330522da41d487bb2ce75fd5da5ec8/drivers/amlogic/media/vout/hdmitx/hdmi_tx_20/hdmi_tx_main.c).
+
+## Other video and audio
+
+Native rendering passed for AVC 8-bit and a 10-bit AVC candidate, HEVC 8/10-bit SDR, AV1 HDR, VP9, and MPEG-4 Part 2. MP4, MKV, and AVI were exercised. Source resolutions ranged from SD to 4K. The VC-1 MKV sample advanced audio without producing a video format or rendered frame during a 55-second observation. **Normal Plex playback of that same sample converted it to 1080p HEVC/AAC and rendered successfully.** It is not counted as native VC-1 support.
+
+| Audio source | Observed player output | Result / limit |
+| --- | --- | --- |
+| AAC, including 5.1 | PCM 16-bit, including six-channel output | Played |
+| AC3 | AC3 bitstream, stereo / 5.1 fixtures | Played; output position advanced |
+| EAC3, including 7.1 and an Atmos-tagged fixture | EAC3 bitstream, six/eight channels | Played; receiver Atmos/object decoding not verified |
+| DTS | DTS bitstream, 5.1 | Played; output position advanced |
+| DTS-HD Master Audio | DTS-HD input selected, **DTS core** output | Compatible playback; full DTS-HD passthrough not demonstrated |
+| TrueHD, Atmos-tagged 7.1 | TrueHD bitstream accepted by AudioTrack | Played; receiver sound and Atmos/object decoding not verified |
+| FLAC stereo, Vorbis 5.1, Opus 7.1 | PCM output with corresponding channel counts | Played; no bit-perfect claim |
+| MP2 / MP3 | PCM stereo | Played |
+| Generated 16-bit / 48 kHz stereo WAV | PCM 16-bit / 48 kHz stereo | Played; local fixture |
+| Generated 24-bit / 96 kHz mono WAV | Failed before AudioTrack initialization | Reproduced `ERROR_CODE_FAILED_RUNTIME_CHECK`; `getAudioTrackMinBufferSize` check failed during output configuration. Other high-resolution PCM combinations remain untested |
+
+One 4K AV1/TrueHD run sustained 61.8 seconds after playback began, rendering 1,475 frames with one dropped frame and no subsequent buffering samples. Most other matrix cases observed approximately 10–12 seconds of steady playback. This is a compatibility sweep, not a feature-length soak or perceptual lip-sync test. Initial native-file probes encountered HTTP-status fallbacks; later repeated native probes succeeded. The initial HTTP status was not captured, so transport reliability is not certified by the later passes.
+
+Pause, three backward 10-second seeks, resume and exit passed for native Dolby Vision and the Plex HLS path. The HLS test crossed the original start offset and reached the correct absolute position without doubling the resume offset. No tested Plex item's watched count, last-viewed timestamp, or resume position changed.
+
+## TCL HDMI observation
+
+A debug-only `TvView` activity tuned the verified HDMI 1 hardware input through Android's public TV Input Framework. TCL reported `videoAvailable` and a 3840×2160/60 input. Its standard ADB screenshot attempts while HDMI was active produced no usable image, including a failed file-based capture. The vendor track extras did not provide a dependable changing HDR indication. Thus **ADB via this TCL is not a reliable capture of the actual HDMI picture**. No capture-protection bypass was attempted. The confirmed HDR output results above use ONN transmitter/HWC diagnostics; they do not replace a physical screen/receiver check.
+
+## Reproduction and evidence
+
+`scripts/inventory_playback.py` inventories actual Plex metadata. `scripts/validate_playback.py` cold-launches one case at a time, records delivered formats/decoder counters/audio output, optionally seeks, closes the player, and verifies unchanged Plex progress. `--mode 0` forces a native file, `--mode -1` follows the saved production preference, and `--observe-hdmi` reads an already tuned TCL observer. Local `--fixture` files require matching Title-style JSON metadata and explicitly bypass Plex delivery. A fixture failure does not request a Plex conversion for that synthetic ID.
+
+Validation is debug-only and opt-in. It suppresses timeline/scrobble writes while retaining normal playback otherwise. The capability inventory exports no credentials. Telemetry excludes URLs, headers, tokens, and exception messages; raw source metadata and captures stay under ignored `evidence/private/playback-validation/`. A missing video track on a movie is a failure, not an audio-only pass. A blank ADB HEVC capture alone is not a failure when decoder counters demonstrate rendering.
+
+`assembleDebug testDebugUnitTest lintDebug` passed (five unit tests), as did Python compilation and `git diff --check`. Playback failures and limitations above are recorded test outcomes, not passing checks. The signed 0.1.9 release remains the published update; validation instrumentation is local work.
+
+The original HDR state was restored through the manual-format UI and verified: `user_disabled_hdr_formats=1,2`, `are_user_disabled_hdr_formats_allowed=0`, `hdr_conversion_mode=2`, `hdr_force_conversion_type=-1`. The vendor policy returned to `HLG priority`; a final HLG run rendered and reported `HDR10-GAMMA_HLG`. Dolby Vision and HDR10 are therefore disabled again, matching the user's original setup.
+
+The temporary on-device fixtures and telemetry were removed. Both ONN and TCL were reinstalled in place with the original published, non-debuggable 0.1.9 APK (version code 10; SHA-256 `ddc9b089bd02aaa0e636e27786159d86419dba8eba8e9995a569a3a9902b576b`). Both confirmed ART `speed-profile` compilation. Sessions and app data were retained.
diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md
index bbd7009..7d8a727 100644
--- a/docs/runtime-verification.md
+++ b/docs/runtime-verification.md
@@ -1,5 +1,7 @@
# Device regression review - 2026-10-23
+For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback findings, see [Dedicated playback validation](playback-validation-2026-10-26.md). It includes confirmed Dolby Vision/HDR10/HLG signaling, audio output limits, the TCL HDMI capture limitation, and the restored HDR settings.
+
Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`.
## Browsing
@@ -144,3 +146,18 @@ Performance was measured with the signed release and confirmed ART `speed-profil
The macOS checkout was reattached to the existing repository history without replacing its source files. Builds reused an existing JDK 17 with Gradle 8.13 and an isolated SDK 36, and used the original private signing key. `assembleRelease testDebugUnitTest lintDebug` passed (five unit tests); the signed debug build passed all 21 Android integration tests against the existing encrypted session. An outdated integration-test transcode argument was updated to `StreamQuality.Original`. Scripts accept `KALEIDO_ADB` for the local ADB executable and retain the authorized serial selection. Private keys, toolchains and raw device evidence remain ignored.
On the TCL (`192.168.50.200:5555`), 0.1.9 installed in place and ART confirmed `speed-profile` after a lost compilation reply. Rapid tab/Down, scrolled catalog re-entry and the horizontal round-trip passed. A longer transition run lost its ADB transport; `device.py` now reconnects when the serial disappears as well as on closed/offline errors. A shorter, complete Movies sample (`profile_transitions.py --skip-home`) measured tab → Discover p95 22.7 ms, Discover → row 23.2 ms and row → row 46.1 ms (baseline 74.8 ms). Entering Movies measured p95 94.2 ms / maximum 106.4 ms, versus baseline 106.8 / 150.1 ms. These are individual samples; the weaker TV still misses frames on section composition, and the interrupted run is not counted as a complete pass. Both comparisons retained the existing session and settings.
+
+
+## Native playback and release performance — 2026-10-26 (0.1.10)
+
+Original quality now opens the actual file first. On the ONN, the default path retained 3840×2160 HEVC/AAC 5.1 and 3840×1608 Dolby Vision/EAC3 7.1 instead of the baseline's 1080p/stereo conversion. Plex-selected audio is applied to native tracks, Subtitles Off disables native text tracks, and unsupported selected tracks retain server fallback. A nonempty audio-only track list for a declared video now triggers fallback: the VC-1 sample automatically reached rendered 1080p HEVC through Plex. Stream preparation is serialized, and fallback checks its session generation before replacing a newer stream. Movie controls identify server conversions.
+
+The failing mono WAV contained a center-only PCM speaker mask. The audio sink normalizes one-channel PCM to Android's standard mono output, preserving rate, channel count, timeline and channel mapping. The 24-bit/96 kHz source played at 96 kHz through the existing 16-bit PCM sink; standard 16-bit/48 kHz stereo also passed. Multichannel PCM and encoded bitstreams retain their layout. This is a playback compatibility fix, not a new claim of bit-perfect 24-bit output.
+
+Debug functional checks passed native Dolby Vision profiles 5/8/10, EAC3 7.1, AV1/TrueHD 7.1, Opus 7.1, DTS-HD input with DTS-core output, FLAC, selected AC3, and backward seeking. The AV1/TrueHD steady run covered 61.8 seconds with 1,483 rendered frames, one dropped frame and no later buffering samples. All seven remote player checks passed, including switching a conversion to Original quality. The Android runner reported OK for 24 tests (the capability inventory is opt-in); five host unit tests and release/debug builds plus lint passed. Native next-episode validation was not completed after the testing interruption and is not counted as a pass.
+
+The user reported severe lag while the devices still had temporary debug APKs installed. Both were confirmed `DEBUGGABLE`, version code 11, with ART `run-from-apk`. They were restored to the exact published 0.1.9 release, without clearing data, and profile compiled. A subsequent controlled ONN comparison used only non-debuggable production-signed APKs with ART `speed-profile`. Three cold starts measured activity startup median 431 ms for 0.1.9 versus 423 ms for 0.1.10. Home readiness, including UI-dump polling overhead, was 6.720 versus 6.773 seconds. A full Home/Movies transition cycle recorded 26 versus 23 skipped vsyncs overall; Movies entry p95 was 79.7 versus 75.6 ms, with 11 skipped vsyncs in each. Individual transitions varied by a few milliseconds. The release comparison showed no material navigation/startup regression; it does not promise zero stutter. The TCL repeat was skipped at the user's request.
+
+The signed 0.1.10 APK uses the existing production certificate, version code 11. APK checks found neither private session data nor debug playback intent strings. Raw comparison records remain in ignored `evidence/private/release-comparison/`. The new benchmark scripts reject debuggable APKs and require `speed-profile`, so functional debug results cannot be mistaken for release performance evidence. The user explicitly authorized leaving Dolby Vision/HDR10 enabled; cleanup must not restore the earlier disabled list.
+
+The actual non-debuggable release was also opened through Search and title details and played the 4K HEVC fixture from the beginning. Playback reached PLAYING/READY in 2.565 seconds; the recorded 30-second steady sample had zero BUFFERING transitions and one READY event. A preceding one-minute session also completed without a second READY event, but its harness incorrectly expected Home instead of the originating details page, so it is not counted as a fully completed benchmark. The corrected run returned normally and restored the exact previous resume point with the watched count unchanged. This checks real release playback, rather than ignored debug test intents.
diff --git a/scripts/benchmark_release.py b/scripts/benchmark_release.py
new file mode 100644
index 0000000..d5063c8
--- /dev/null
+++ b/scripts/benchmark_release.py
@@ -0,0 +1,28 @@
+"""Compare optimized release builds on one authorized device at a time."""
+import argparse,json,pathlib,re,statistics,subprocess,sys,time
+from device import adb,DEVICE,OUT
+from verify_ui import wait,labels,focus
+
+def main():
+ p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('--cycles',type=int,default=3);p.add_argument('--nav-cycles',type=int,default=1)
+ args=p.parse_args();folder=OUT/'release-comparison';folder.mkdir(exist_ok=True)
+ package=adb('shell','dumpsys','package','tv.kaleido.app').decode()
+ assert 'DEBUGGABLE' not in re.search(r'pkgFlags=\[(.*?)\]',package)[1],'Performance tests require a release APK'
+ assert 'status=speed-profile' in package,'Apply the matching ART profile before comparison'
+ result={'device':DEVICE,'version':re.search(r'versionName=(\S+)',package)[1],'startup':[]}
+ adb('shell','input','keyevent','KEYCODE_WAKEUP')
+ for i in range(args.cycles):
+ adb('shell','am','force-stop','tv.kaleido.app');start=time.monotonic()
+ raw=adb('shell','am','start','-W','-n','tv.kaleido.app/.MainActivity').decode()
+ wait(lambda r:'Continue Watching' in labels(r) and focus(r)=='Home' and
+ all(n.get('content-desc')!='Kaleido starting' for n in r.iter('node')),'Cold Home ready',timeout=45)
+ row={'homeReadySeconds':round(time.monotonic()-start,3)}
+ row.update({k:int(v) for k,v in re.findall(r'(ThisTime|TotalTime|WaitTime): (\d+)',raw)})
+ result['startup'].append(row);print('STARTUP',args.label,i+1,row,flush=True)
+ result['medianHomeReadySeconds']=statistics.median(r['homeReadySeconds'] for r in result['startup'])
+ result['medianActivityMs']=statistics.median(r['TotalTime'] for r in result['startup'])
+ (folder/(args.label+'.json')).write_text(json.dumps(result,indent=2))
+ nav=subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('profile_transitions.py')),args.label,'--cycles',str(args.nav_cycles)])
+ if nav.returncode:raise SystemExit(nav.returncode)
+ print('COMPLETE',args.label,'activity median',result['medianActivityMs'],'Home median',result['medianHomeReadySeconds'],flush=True)
+if __name__=='__main__':main()
diff --git a/scripts/benchmark_release_playback.py b/scripts/benchmark_release_playback.py
new file mode 100644
index 0000000..9cc746b
--- /dev/null
+++ b/scripts/benchmark_release_playback.py
@@ -0,0 +1,76 @@
+"""Exercise the actual release UI, measure startup/rebuffering, restore resume time."""
+import argparse,json,os,pathlib,re,shlex,time,urllib.parse,urllib.request
+if pathlib.Path('/etc/ssl/cert.pem').exists():os.environ.setdefault('SSL_CERT_FILE','/etc/ssl/cert.pem')
+from device import adb,OUT,DEVICE
+from verify_ui import launch,key,focused,wait,labels,focus,snapshot
+from inspect_server import get,base,token
+
+def session():
+ raw=adb('shell','dumpsys','media_session').decode(errors='replace')
+ m=re.search(r'package=tv\.kaleido\.app.*?PlaybackState \{state=(\w+)\(\d+\), position=(\d+).*?speed=([\d.]+), updated=(\d+)',raw,re.S)
+ return {'state':m[1],'position':int(m[2]),'speed':float(m[3]),'updated':int(m[4])} if m else {}
+
+def main():
+ p=argparse.ArgumentParser();p.add_argument('label');p.add_argument('id');p.add_argument('--seconds',type=int,default=60);args=p.parse_args()
+ folder=OUT/'release-comparison';folder.mkdir(exist_ok=True)
+ pkg=adb('shell','dumpsys','package','tv.kaleido.app').decode()
+ assert 'DEBUGGABLE' not in re.search(r'pkgFlags=\[(.*?)\]',pkg)[1]
+ assert 'status=speed-profile' in pkg
+ before=get('/library/metadata/'+args.id)['Metadata'][0];title=before['title']
+ (folder/(args.label+'-before.json')).write_text(json.dumps(before,indent=2))
+ # A previous ADB tap can leave Android in touch mode across app restarts.
+ adb('shell','input','keyevent','19')
+ launch()
+ for target in ['Movies','TV Shows','Search']:key(22);focused(target)
+ key(23);wait(lambda r:'Movies, shows, episodes' in labels(r),'Search field')
+ adb('shell','input','text',shlex.quote(title.replace(' ','%s')))
+ wait(lambda r:title in labels(r),'Matching search result')
+ ime=adb('shell','dumpsys','input_method').decode(errors='replace')
+ if re.search(r'mInputShown=true|isInputViewShown=true',ime):key(4)
+ # EditText has the same text as the result; Tab exits editing without entering
+ # Android touch mode, and the focused poster is verified before activation.
+ key(61)
+ wait(lambda r:any(n.get('focused')=='true' and n.get('class')!='android.widget.EditText' and title in labels(n) for n in r.iter('node')),'Movie result focus')
+ key(23)
+ root=wait(lambda r:any(s=='Play' or s.startswith('Resume') for s in labels(r)),'Movie actions')
+ wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Playback action focus')
+ if 'Start over' in labels(root):key(22);focused('Start over')
+ print('PLAYBACK_START',args.label,flush=True)
+ adb('logcat','-c');start=time.monotonic();key(23)
+ ready=None;samples=[];ready_logs=''
+ while time.monotonic()-start<70:
+ s=session();s['elapsed']=round(time.monotonic()-start,3);samples.append(s)
+ ready_logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
+ if s.get('state')=='PLAYING' and 'READY item='+args.id in ready_logs:ready=s['elapsed'];break
+ time.sleep(.7)
+ assert ready is not None,'Release playback did not become ready'
+ print('PLAYBACK_READY',args.label,ready,flush=True)
+ steady_start=time.monotonic();last='PLAYING';rebuffers=0
+ while time.monotonic()-steady_start=int(data.get('totalSize',start)):break
+ print('Inventoried',section['type'],start,'items',flush=True)
+ (OUT/'inventory.json').write_text(json.dumps(items))
+ for label,field in [('Video','videoCodec'),('Audio','audioCodec'),('Containers','container')]:
+ counts=collections.Counter(media.get(field,'none') for item in items for media in item.get('Media',[]))
+ print(label,dict(counts),flush=True)
+if __name__=='__main__':main()
diff --git a/scripts/repro_runtime.py b/scripts/repro_runtime.py
index 13b7998..6162561 100644
--- a/scripts/repro_runtime.py
+++ b/scripts/repro_runtime.py
@@ -26,7 +26,7 @@ def ready(item,timeout=45):
def controls():
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
- adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1')
+ adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1','--ez','testValidation','true')
ready(7599);key(127);focused('Play')
screenshot('direct-stream-episode')
key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus')
@@ -67,7 +67,7 @@ def episode():
item=titles[0];expected=str(titles[1]['ratingKey'])
adb('shell','am','force-stop','tv.kaleido.app')
adb('logcat','-c')
- adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2')
+ adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
time.sleep(9);key(127);focused('Play')
for _ in range(6):
if 'Next episode' in focus(snapshot()):break
@@ -82,12 +82,12 @@ def episode():
assert 'item='+expected in logs,'Next episode did not become the active player'
print('PASS next episode replaced player with expected title')
-def postplay():
+def postplay(mode=2):
from inspect_server import get
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
- adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(item['duration']-12000),'--ei','testMode','2')
- deadline=time.monotonic()+45
+ adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(item['duration']-12000),'--ei','testMode',str(mode),'--ez','testValidation','true')
+ deadline=time.monotonic()+(90 if mode<=0 else 45)
while time.monotonic() postplay, episode/related rows, cancellable autoplay')
-globals()[sys.argv[1]]()
+if __name__=='__main__':globals()[sys.argv[1]]()
diff --git a/scripts/validate_playback.py b/scripts/validate_playback.py
new file mode 100644
index 0000000..e6a1b59
--- /dev/null
+++ b/scripts/validate_playback.py
@@ -0,0 +1,126 @@
+"""Exercise real Plex playback through Kaleido's opt-in debug validation mode.
+
+One device at a time. No timeline/scrobble writes in validation mode. Raw reports
+and screenshots remain private; source media and track preferences are untouched.
+"""
+import argparse,json,os,pathlib,subprocess,time
+if pathlib.Path('/etc/ssl/cert.pem').exists():os.environ.setdefault('SSL_CERT_FILE','/etc/ssl/cert.pem')
+from device import adb,DEVICE,OUT
+from inspect_server import get
+
+def audit():
+ try:raw=adb('exec-out','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
+ except RuntimeError:return b'',[]
+ records=[]
+ for line in raw.splitlines():
+ try:records.append(json.loads(line))
+ except json.JSONDecodeError:pass # The writer can be appending its last line.
+ return raw,records
+
+def snapshot_signal():
+ command='for p in /sys/class/amhdmitx/amhdmitx0/attr /sys/class/amhdmitx/amhdmitx0/hdmi_hdr_status /sys/class/amhdmitx/amhdmitx0/hdr_status /sys/class/video/frame_format /sys/module/amdolby_vision/parameters/dolby_vision_status /sys/module/amdolby_vision/parameters/dolby_vision_mode; do if [ -r "$p" ]; then printf "%s=" "$p"; cat "$p"; fi; done'
+ return adb('shell',command)
+
+def watched(item):return {k:item.get(k) for k in ('viewOffset','viewCount','lastViewedAt')}
+
+def main():
+ parser=argparse.ArgumentParser()
+ parser.add_argument('id');parser.add_argument('label');parser.add_argument('--mode',type=int,default=-1)
+ parser.add_argument('--seconds',type=float,default=12);parser.add_argument('--offset',type=int,default=90000)
+ parser.add_argument('--seek',action='store_true');parser.add_argument('--screenshot',action='store_true')
+ parser.add_argument('--observe-hdmi',action='store_true',help='Read the already tuned TCL debug HDMI observer during ONN playback')
+ parser.add_argument('--fixture',type=pathlib.Path,help='Private local test media with a matching .json metadata file; bypasses Plex transport')
+ parser.add_argument('--expect-mode',type=int,choices=(0,1,2))
+ parser.add_argument('--expect-width',type=int)
+ parser.add_argument('--expect-channels',type=int)
+ parser.add_argument('--expect-audio-encoding',type=int)
+ args=parser.parse_args()
+ folder=OUT/'playback-validation'/('onn' if DEVICE=='192.168.50.195:5555' else 'tcl')/args.label
+ folder.mkdir(parents=True,exist_ok=True)
+ before=json.loads(args.fixture.with_suffix('.json').read_text()) if args.fixture else get('/library/metadata/'+args.id)['Metadata'][0]
+ expects_video=any(m.get('videoCodec') for m in before.get('Media',[]))
+ (folder/'source.json').write_text(json.dumps(before,indent=2))
+ adb('shell','input','keyevent','KEYCODE_WAKEUP')
+ adb('shell','am','force-stop','tv.kaleido.app')
+ adb('shell','run-as','tv.kaleido.app','rm','-f','files/playback-validation.jsonl')
+ if args.fixture:
+ name=args.fixture.stem
+ if not name.replace('-','').isalnum() or name.lower()!=name:raise SystemExit('Use a lowercase alphanumeric fixture name')
+ adb('shell','run-as','tv.kaleido.app','mkdir','-p','files/validation')
+ for path in (args.fixture,args.fixture.with_suffix('.json')):
+ tmp='/data/local/tmp/kaleido-validation-'+path.name
+ adb('push',str(path),tmp)
+ adb('shell','run-as','tv.kaleido.app','cp',tmp,'files/validation/'+path.name)
+ adb('shell','rm','-f',tmp)
+ start=time.monotonic()
+ if args.fixture:adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testFixture',args.fixture.stem)
+ else:adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',args.id,'--el','testOffset',str(args.offset),'--ei','testMode',str(args.mode),'--ez','testValidation','true')
+ ready=None;records=[]
+ while time.monotonic()-start<55:
+ _,records=audit()
+ if args.fixture and any(r['event'] in ('error','prepareFailure') for r in records):break
+ samples=[r for r in records if r['event']=='sample']
+ if samples:
+ last=samples[-1]
+ video=last.get('videoCounters',{})
+ if last.get('playing') and (video.get('rendered',0)>5 or not expects_video and any(r['event']=='audioAdvancing' for r in records)):
+ ready=round(time.monotonic()-start,2);break
+ time.sleep(.8)
+ if ready is not None:time.sleep(args.seconds)
+ raw,records=audit();(folder/'audit-steady.jsonl').write_bytes(raw)
+ (folder/'signal-steady.txt').write_bytes(snapshot_signal())
+ (folder/'surface-steady.txt').write_bytes(adb('shell','dumpsys','SurfaceFlinger'))
+ if args.observe_hdmi:
+ import device
+ original=device.DEVICE
+ try:
+ device.DEVICE='192.168.50.200:5555'
+ (folder/'tcl-hdmi.jsonl').write_bytes(adb('exec-out','run-as','tv.kaleido.app','cat','files/hdmi-validation.jsonl'))
+ (folder/'tcl-picture.png').write_bytes(adb('exec-out','screencap','-p'))
+ finally:device.DEVICE=original
+ if args.screenshot:(folder/'onn-picture.png').write_bytes(adb('exec-out','screencap','-p'))
+ seek_result=None
+ if args.seek and ready is not None:
+ adb('shell','input','keyevent','127');time.sleep(1.5)
+ _,paused=audit();old=[r for r in paused if r['event']=='sample'][-1]['position']
+ for _ in range(3):
+ _,current=audit();position=[r for r in current if r['event']=='sample'][-1]['position']
+ adb('shell','input','keyevent','89')
+ deadline=time.monotonic()+25
+ while time.monotonic()5 for r in samples),
+ 'closed':any(r['event']=='closed' for r in records),'before':watched(before),'after':watched(after),
+ 'transport':'private-local-fixture' if args.fixture else 'Plex','progressUnchanged':None if args.fixture else watched(before)==watched(after)}
+ (folder/'result.json').write_text(json.dumps(result,indent=2))
+ print(json.dumps({k:result[k] for k in ('label','readySeconds','firstFrame','audioAdvancing','videoDecoders','errors','progressUnchanged')}),flush=True)
+ print('Output:',last.get('video'),last.get('audio'),'mode:',last.get('mode'),'seek:',seek_result,flush=True)
+ if ready is None:raise SystemExit('Playback did not become ready; see private evidence')
+ if not result['closed']:raise SystemExit('Player did not close cleanly')
+ if result['progressUnchanged'] is False:raise SystemExit('Unexpected progress change; see before/after evidence')
+ if args.seek and not seek_result['correct']:raise SystemExit('Seek did not reach the expected absolute position')
+ if args.expect_mode is not None and last.get('mode')!=args.expect_mode:raise SystemExit('Unexpected delivery mode')
+ if args.expect_width is not None and last.get('video',{}).get('width')!=args.expect_width:raise SystemExit('Unexpected delivered video width')
+ if args.expect_channels is not None and last.get('audio',{}).get('channels')!=args.expect_channels:raise SystemExit('Unexpected delivered audio channel count')
+ if args.expect_audio_encoding is not None and (not result['audioTracks'] or result['audioTracks'][-1]['encoding']!=args.expect_audio_encoding):raise SystemExit('Unexpected audio output encoding')
+if __name__=='__main__':main()
diff --git a/scripts/verify_ui.py b/scripts/verify_ui.py
index 651a229..9b64a2f 100644
--- a/scripts/verify_ui.py
+++ b/scripts/verify_ui.py
@@ -72,7 +72,7 @@ def position():
def player():
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
- adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2')
+ adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
# A pause sent while the player is still preparing is overridden when playback starts.
deadline=time.monotonic()+45
while 'READY item=9776' not in adb('logcat','-d','-s','KaleidoPlayback:I').decode(errors='replace'):
diff --git a/version.properties b/version.properties
index 970e81e..f64821d 100644
--- a/version.properties
+++ b/version.properties
@@ -1,2 +1,2 @@
-versionName=0.1.9
-versionCode=10
+versionName=0.1.10
+versionCode=11