Smooth section switches and first row moves on weaker TVs
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m16s

Measured every browse transition on the onn, a Fire TV Stick 4K and a TCL
TV with a new framestats harness and atrace breakdowns.

- Stage card artwork and titles a few cards per frame while a section
  enters, so its first frame no longer composes every card at once.
- Give every discovery list the lookahead cache window and nudge it once
  after a section settles, so the first move down composes nothing.
- Activate a focused top tab two frames later, so its highlight responds
  before the section switches; start the page entrance after composition
  settles, using per-draw alpha instead of an offscreen layer.
- Limit Coil to two concurrent decodes, drop the redundant window
  background, size card image requests explicitly, and skip a coroutine
  per card for focus restoration.

Home -> Movies UI stalls drop from 150-200 ms to 70-90 ms and Movies row
moves no longer skip frames. Device scripts can now target any authorized
serial and tolerate the TCL's flaky network ADB link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-24 13:11:45 -07:00
parent 0f926c0435
commit 629546a50c
14 changed files with 282 additions and 30 deletions

View file

@ -4,7 +4,7 @@
- Ask clarifying questions before proceeding when more information is needed. Otherwise make reasonable decisions and complete the authorized work.
- This is a real native Android TV Plex client: Kotlin, Jetpack Compose, Media3/ExoPlayer. Preserve working Plex functionality; do not substitute mock content or prototype playback.
- The authorized test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. Always specify the ADB serial. Do not modify its launcher, accessibility services, other apps, or other devices.
- The primary test device is the onn at **192.168.50.195:5555**, package **tv.kaleido.app**, activity **.MainActivity**. The user also authorized two weaker devices for performance testing: a Fire TV Stick 4K (Fire OS 8, 32-bit) at **192.168.50.146:5555** and a TCL Smart TV Pro (MT5896, slowest GPU) at **192.168.50.200:5555**. Scripts target the onn unless `KALEIDO_DEVICE` names another serial. Always specify the ADB serial. Do not modify any device's launcher, accessibility services (the onn runs two, which add per-frame semantics work), settings, or other apps. The TCL's network ADB link drops intermittently; `device.py` reconnects and retries.
- `.env` contains `PLEX_SERVER_URL` and `PLEX_TOKEN` for local testing. Never print, commit, or embed credentials in source, resources, APKs, or logs. Keep `.env`, signing keys, toolchains, and private evidence ignored.
- Use the existing encrypted session. `scripts/device.py seed` provisions an installed **debug** build only when needed; the app encrypts and deletes its bootstrap file. Never clear app data or sign out just to reset a test.
@ -49,6 +49,8 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan
| `scripts/repro_runtime.py credits` | Visible Skip credits, season/related rows and cancellable countdown; **debug** |
| `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` |
| `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses |
| `scripts/profile_transitions.py <label>` | Skipped frames per D-pad transition (tabs, hero, rows, Movies) from framestats; first cycle is the first pass after launch; profiled **release**; raw frames kept for `resummarize` |
| `scripts/trace_transition.py <label> <setup> <keys>` | atrace one transition and list slow UI frames with their nested work |
| `scripts/profile_home.py <label>` | Hero → Continue Watching frame timing; profiled **release**; `--cold --cycles 1` checks the first transition |
| `scripts/verify_navigation_sounds.py` | Sound toggle and cold-start persistence; leaves sounds On |

View file

@ -15,6 +15,8 @@ import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.*
import androidx.compose.runtime.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@ -41,6 +43,10 @@ import kotlinx.coroutines.delay
@Composable fun TopBar(vm:KaleidoViewModel,navigation:DiscoveryNavigation?=null) {
val initialFocus by remember{derivedStateOf{vm.focusId.isBlank()}}
val scope=rememberCoroutineScope();val pendingTab=remember{arrayOfNulls<Job>(1)}
// Let the focus highlight draw before the new section composes in its long frame,
// so the press responds at once. A quick second move replaces the pending switch.
fun activate(kind:String){pendingTab[0]?.cancel();pendingTab[0]=scope.launch{withFrameNanos{};withFrameNanos{};if(vm.page.kind!=kind)vm.tab(kind)}}
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
// Extend the scrim beyond the controls so it dissolves into the scene without a hard edge.
Box(Modifier.fillMaxWidth().height(62.dp).drawBehind {
@ -53,7 +59,7 @@ import kotlinx.coroutines.delay
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){navigation.enter?.invoke();true}else false
}.focusProperties{if(navigation!=null)down=navigation.entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)->
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={if(vm.page.kind!=kind)vm.tab(kind)}){if(vm.page.kind!=kind)vm.tab(kind)}
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={if(vm.page.kind!=kind)activate(kind)}){pendingTab[0]?.cancel();if(vm.page.kind!=kind)vm.tab(kind)}
}
}
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {

View file

@ -9,6 +9,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.Animatable
import androidx.compose.ui.graphics.graphicsLayer
@ -18,6 +19,7 @@ import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.ChevronRight
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@ -56,11 +58,21 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val hubs=remember(source,destination){editorialHubs(source,destination)}
val restore=remember(hubs){hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=h.items.indexOfFirst{"${h.id}:${it.id}"==vm.focusId};if(column>=0)row to column else null}}
val initialRow=restore?.let{it.first+if(home)1 else 0} ?: 0
// Keep the hero and adjacent rows prepared across the large Home scroll.
// Keep the hero/preview and adjacent rows prepared across vertical moves.
// Without a behind window, every return discards and recomposes those cards.
val list=if(home)rememberLazyListState(initialFirstVisibleItemIndex=initialRow,
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,
cacheWindow=remember{LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=1f)})
else rememberLazyListState(initialFirstVisibleItemIndex=initialRow)
// The window only fills ahead after the list has scrolled, so the first move down after
// a section appeared composed the next rows mid-animation (a ~200 ms stall on the onn).
// Once the screen settles, nudge it so those rows compose in idle frames, then undo it.
LaunchedEffect(list,hubs.isNotEmpty()){
if(hubs.isEmpty()||list.firstVisibleItemIndex!=0||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect
awaitSteadyFrames(4)
if(list.isScrollInProgress||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect
list.scrollBy(1f)
repeat(45){withFrameNanos{}}
if(!list.isScrollInProgress&&list.firstVisibleItemIndex==0&&list.firstVisibleItemScrollOffset==1)list.scrollBy(-1f)
}
val rowStates=remember(hubs){List(hubs.size){row->LazyListState(firstVisibleItemIndex=if(restore?.first==row)restore.second else 0)}}
val requesters=remember(hubs){mutableMapOf<Pair<Int,Int>,FocusRequester>()}
val columns=remember(hubs){mutableMapOf<Int,Int>()}
@ -88,6 +100,8 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(home&&heroActive&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}
}
val heroFocus=remember{FocusRequester()}
val staging=remember{CardStaging()}
LaunchedEffect(staging){delay(1000);staging.entering=false}
val rowOffset=if(home)1 else 0
suspend fun moveToRow(row:Int,column:Int)=coroutineScope {
val state=rowStates.getOrNull(row) ?: return@coroutineScope
@ -165,7 +179,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
LazyRow(state=rowStates[row],contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
val requester=requesters.getOrPut(row to column){FocusRequester()}
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,staging,
Modifier.onPreviewKeyEvent{event->
if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) {
val target=column+if(event.key==Key.DirectionLeft)-1 else 1
@ -247,11 +261,27 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
}
}
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,modifier:Modifier,onHovered:(Title)->Unit) {
/**
* A newly shown section composed every visible card in one 100–200 ms frame. While it is
* entering, each card first lays out at its fixed size and fills in its artwork and titles a
* few cards per frame, under the page's fade-in. Cards composed later fill in at once.
*/
private class CardStaging {
var entering=true
private var count=0
fun frames()=if(entering)count++/3 else -1
}
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,staging:CardStaging,modifier:Modifier,onHovered:(Title)->Unit) {
var focused by remember{mutableStateOf(false)}
val stage=remember{staging.frames()}
var filled by remember{mutableStateOf(stage<0)}
if(!filled)LaunchedEffect(Unit){repeat(stage+1){withFrameNanos{}};filled=true}
val width=if(poster)120.dp else if(wideEpisode)264.dp else 214.dp
val image=if(poster)item.poster.ifBlank{item.thumb}else if(item.type=="episode")item.still.ifBlank{item.thumb}.ifBlank{item.art}else item.art.ifBlank{item.thumb}
LaunchedEffect(Unit){if(vm.focusId==focusKey){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)}}
// Only the card being restored launches an effect; checking inside one per card cost a
// coroutine for every card in a newly shown section.
if(remember{Snapshot.withoutReadObservation{vm.focusId==focusKey}})LaunchedEffect(Unit){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)}
Column(modifier.width(width).then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound().onFocusChanged{
focused=it.isFocused
if(it.isFocused){vm.focusId=focusKey;onHovered(item)}
@ -261,14 +291,20 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
onClick{vm.open(item);true}
}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp))) {
Artwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270,animate=false)
if(item.offset>0&&!poster)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent))
}
WatchBadge(item,vm.watchedPercent)
if(filled) {
Artwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270,animate=false)
if(item.offset>0&&!poster)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent))
}
WatchBadge(item,vm.watchedPercent)
}else Box(Modifier.fillMaxSize().background(Panel))
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Color.White,RoundedCornerShape(4.dp)))
}
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp).height(16.dp))
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(14.dp))
// Placeholder height matches the titles' fixed heights, so card bounds never change.
if(!filled)Spacer(Modifier.height(if(poster)21.dp else 35.dp))
else {
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp).height(16.dp))
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(14.dp))
}
}
}

View file

@ -13,5 +13,8 @@ class KaleidoApplication: Application(), ImageLoaderFactory {
val scope = CoroutineScope(SupervisorJob()+Dispatchers.IO)
val secure by lazy { SecureSession(this) }
val api by lazy { PlexApi(secure.clientId).apply { session=secure.load() } }
override fun newImageLoader() = ImageLoader.Builder(this).okHttpClient(api.http).memoryCache { MemoryCache.Builder(this).maxSizePercent(.12).build() }.diskCache { DiskCache.Builder().directory(cacheDir.resolve("artwork")).maxSizeBytes(250L*1024*1024).build() }.crossfade(250).build()
override fun newImageLoader() = ImageLoader.Builder(this).okHttpClient(api.http).memoryCache { MemoryCache.Builder(this).maxSizePercent(.12).build() }.diskCache { DiskCache.Builder().directory(cacheDir.resolve("artwork")).maxSizeBytes(250L*1024*1024).build() }.crossfade(250)
// Coil defaults to four concurrent decodes, which starves the UI and render threads
// on four-core TV hardware while a newly shown section loads its rows.
.bitmapFactoryMaxParallelism(2).build()
}

View file

@ -35,6 +35,8 @@ class MainActivity: ComponentActivity() {
WindowCompat.setDecorFitsSystemWindows(window,false)
WindowInsetsControllerCompat(window,window.decorView).apply{hide(WindowInsetsCompat.Type.systemBars());systemBarsBehavior=WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE}
setContent { KaleidoApp(model,::installApk) }
// Compose paints Ink over the whole window; the theme background only covers launch.
window.setBackgroundDrawable(null)
debugPlayback(intent)
}
override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent)}

View file

@ -23,6 +23,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@ -34,6 +35,7 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.size.Precision
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.first
@ -43,7 +45,9 @@ import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true) {
val context=LocalContext.current
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(if(animate)180 else 0).build()}}
// The server already scales to width × height. Stating that size lets Coil resolve cache
// hits while composing, instead of each painter waiting for layout to measure it.
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).crossfade(if(animate)180 else 0).build()}}
AsyncImage(model=model,contentDescription=null,contentScale=ContentScale.Crop,modifier=modifier.background(Panel))
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
@ -60,7 +64,11 @@ import java.io.File
val order=listOf("home","movies","tv","search","settings")
direction=if(order.indexOf(vm.page.kind)<order.indexOf(previousDestination))-1f else 1f
previousDestination=vm.page.kind
entrance.snapTo(0f);entrance.animateTo(1f,tween(280))
entrance.snapTo(0f)
// A new section composes its rows in one or two long frames. Start the slide after
// them (bounded) so it doesn't open with a jump.
withTimeoutOrNull(300){awaitSteadyFrames(2)}
entrance.animateTo(1f,tween(280))
}
// A restored Activity after process eviction still needs the cold-start cover.
var startup by remember{mutableStateOf(true)}
@ -80,7 +88,9 @@ import java.io.File
// The app settles into place behind the splash as its aperture opens.
Box(Modifier.fillMaxSize().then(if(startup)Modifier.graphicsLayer{val s=startupArrivalScale(splashExit.value);scaleX=s;scaleY=s}else Modifier)) {
if(vm.servers.isNotEmpty()) ServerPicker(vm) else if(vm.session==null||vm.linkingAccount) SignIn(vm) else {
// Per-draw alpha: an offscreen full-screen layer per frame is costly on weak GPUs.
Column(Modifier.fillMaxSize().graphicsLayer{
compositingStrategy=CompositingStrategy.ModulateAlpha
alpha=.18f+.82f*entrance.value
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) {

View file

@ -128,8 +128,7 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
// the iris never opens through it.
withTimeoutOrNull(700){
snapshotFlow{ready()}.first{it}
var previous=withFrameNanos{it};var steady=0
while(steady<4){val now=withFrameNanos{it};steady=if(now-previous<24_000_000L)steady+1 else 0;previous=now}
awaitSteadyFrames(4)
}
timeline.animateTo(TimelineEnd,tween((TimelineEnd-GatherEnd).toInt(),easing=LinearEasing))
}

View file

@ -33,6 +33,12 @@ import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
val Ink=Color(0xFF090909)
/** Suspends until [count] consecutive frames each arrive within 24 ms of the previous one. */
suspend fun awaitSteadyFrames(count:Int) {
var previous=withFrameNanos{it};var steady=0
while(steady<count){val now=withFrameNanos{it};steady=if(now-previous<24_000_000L)steady+1 else 0;previous=now}
}
val Panel=Color(0xFF1B1B1B)
val Muted=Color(0xFFA5A5A5)
val Accent=Color(0xFFF1F1F1)

View file

@ -22,8 +22,8 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
- Navigation focus changes use Android's native UI tick. Settings > Interface > Navigation sounds toggles it immediately and persists across process restarts; it defaults to On and follows the TV's global sound-effects setting. Initial startup focus and repeated notifications for the same target are silent. The shared focus observer covers navigation, cards, buttons, dialogs, playback options and the timeline without changing key handling.
- Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction.
- A D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid navigation replaces the queued metadata target and cancels superseded artwork prefetches. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop.
- Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV retain their existing list strategy. Card sizes, row targets and the large cinematic Home layout are unchanged.
- Section previews settle for 120 ms (Home artwork for 90 ms), overlapping the navigation animation, and retain previous artwork until replacement data is ready. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Hero recommendation changes crossfade the artwork over 220 ms, including cache hits, and fade the title/summary out for 100 ms and back in over 180 ms. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms. The cold-start sequence lasts 2.9 seconds. The six exact facets begin as a closed, overlapping iris lit from behind; it holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The iris then twists 44° open and locks with a slight overshoot while light leaks through the six gaps, a single sheen crosses the settled mark, and the mark shrinks into a lockup scaled from the header brand as KALEIDO slides out from behind it. Once loading finishes (up to 600 ms extra) the camera flies through the aperture's dark center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background.
- Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV use the same window. The window only fills ahead after the list has scrolled, so once a section settles it is nudged 1 px and back, letting the next rows compose in idle frames instead of during the first move down. Card sizes, row targets and the large cinematic Home layout are unchanged.
- Section previews settle for 120 ms (Home artwork for 90 ms), overlapping the navigation animation, and retain previous artwork until replacement data is ready. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Hero recommendation changes crossfade the artwork over 220 ms, including cache hits, and fade the title/summary out for 100 ms and back in over 180 ms. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms, using per-draw alpha rather than an offscreen layer, and start once the new section's composition frames have passed (at most 300 ms). While a section enters, its cards lay out at their fixed size first and fill in artwork and titles three per frame under the fade, so the section's first frame stays short. Focusing a top tab lets its highlight draw before the section switches. The cold-start sequence lasts 2.9 seconds. The six exact facets begin as a closed, overlapping iris lit from behind; it holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The iris then twists 44° open and locks with a slight overshoot while light leaks through the six gaps, a single sheen crosses the settled mark, and the mark shrinks into a lockup scaled from the header brand as KALEIDO slides out from behind it. Once loading finishes (up to 600 ms extra) the camera flies through the aperture's dark center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background.
- Returning from details restores the library's mode, scroll position, and previously focused title.
## Player

View file

@ -78,3 +78,29 @@ The cold-start splash was prototyped as a dp-accurate canvas page (ignored `evid
Frame statistics from three profiled release cold starts (`dumpsys gfxinfo framestats`, bucketed per 250 ms) first showed 100–125 ms frames about 0.3–0.7 s after launch: startup data arriving and Home composing beneath the splash, with high UI-thread time. Starting the animation a few frames late did not avoid them because they follow the data, not the first frame. Skipping the hidden app's draw until the exit made no measurable difference and was reverted. The final sequence instead runs a 260 ms light-gathering phase on the nearly still closed iris, then holds until `busy` clears and four consecutive frames arrive within 24 ms (capped at 700 ms). On the final build every frame from the iris opening through the start of the exit completed within 25 ms in all three runs, at 15 frames per 250 ms. Frames after the reveal include Home itself and show higher latency without dropping below 15 frames per bucket. These are device samples, not a guarantee.
The hold adds roughly 0.5 s before the iris opens when Plex data takes that long; loading previously overlapped the animation. `Build.ps1 -Release -Test` passed; `repro_runtime.py sections` passed and all six `verify_ui.py browse` checks passed on the final release. A screen recording of the actual cold start (`kaleido-aperture-startup.mp4`, contact sheet `aperture-sheet.png`) was inspected. The optimized release was left on Home.
## Browsing transitions on three devices - 2026-10-24
The user authorized two weaker devices alongside the onn: a Fire TV Stick 4K (AFTKM, Fire OS 8 / Android 11, 32-bit, 1.7 GB) and a TCL Smart TV Pro (MT5896, Android 14, 1080p UI on a 4K panel, slowest GPU). Each was provisioned with `device.py seed` on a debug build, then the optimized release was installed over it with `speed-profile` compilation. `scripts/profile_transitions.py` measures skipped vsyncs and UI-thread time for each D-pad transition from `gfxinfo framestats`; its first cycle is the first pass after launch, and gaps after fast frames or longer than 300 ms count as idle. `scripts/trace_transition.py` breaks a transition's slow UI frames into their nested atrace slices.
Findings:
- Top-tab switches were the worst stall everywhere: about 30 ms disposing the old section, then one 150 ms+ measure pass composing every visible card (Coil painters about 3 ms per card, text layout about 1.4 ms per label), while four Coil decoders and a young GC competed for four cores.
- Home's lookahead cache only fills after the list has scrolled, so the first hero → row move after launch composed the lower rows mid-animation. A screen recording on the onn showed a 204 ms freeze. Movies/TV had no cache window and skipped 1–2 frames on each row move.
- The onn runs two accessibility services (Button Mapper, Luma launcher), adding 1–3 ms of Compose semantics work per frame. Its steady frames are render-bound but drop nothing. These device settings were not changed.
- Converting contrast-baked backdrops to hardware bitmaps removed render-thread uploads but made the TCL's GPU skip 9–14 frames on Home row moves (0 with software bitmaps), so it was reverted. Explicit card image sizes and a staged-card build were also A/B tested.
Changes: staged card fill-in while a section enters, a cache window and one-time 1 px nudge on every discovery list, tab activation two frames after focus, the page entrance starting after composition settles with per-draw alpha, Coil decode parallelism 2, no redundant window background, explicit card image sizes, and no per-card restoration coroutine.
Results (skipped frames per cycle; UI-thread maximum):
| Transition | onn before → after | Fire Stick before → after |
| --- | --- | --- |
| Home → Movies | 11/7/8, 160 ms → 9/3/6/6, 88 ms | 12/5/5, 153 ms → 8/3/2/2, 69 ms |
| Movies → Home | 7/6/5, 104 ms → 3/4/5/3, 67 ms | 4/3/4, 61 ms → 2/2/2/1, 52 ms |
| Movies row → row | 2/2/1 → 0/0/0/0 | 1/1/0 → 0/0/0/0 |
| Home hero/row moves | 0–1 per move, both before and after | 0 per move, both before and after |
On the TCL, Home → Movies measured 196 ms of UI time before and 88 ms in the one completed final sample. Its final full run was skipped at the user's request because its ADB link kept dropping; the partial final run and the A/B runs showed no regressions. Movies row ← row still skips two frames on the onn. Returning from Movies still disposes and composes whole sections. Retaining sections across tabs would remove that cost but needs per-section navigation state.
`Build.ps1 -Release -Test` passed. On the onn, all six `verify_ui.py browse` checks and `repro_runtime.py sections` passed. A recording confirmed the staged cards fill in under the fade without bound changes. The final release was left installed on all three devices. Private evidence: `transitions-*.json`, `transitions-*-frames.txt`, `trace-*.txt` and the `onn-*` recordings in `evidence/private/`.

View file

@ -1,14 +1,24 @@
"""Operate only Kaleido on the authorized onn streamer. Credentials stay on stdin."""
import argparse, json, pathlib, subprocess, sys, time, xml.etree.ElementTree as ET
"""Operate only Kaleido on an authorized streamer. Credentials stay on stdin."""
import argparse, json, os, pathlib, subprocess, sys, time, xml.etree.ElementTree as ET
ROOT=pathlib.Path(__file__).resolve().parents[1]
ADB=pathlib.Path(r'C:\Users\Elijah\Desktop\platform-tools\adb.exe')
DEVICE='192.168.50.195:5555'
# The onn is the default; KALEIDO_DEVICE selects the authorized Fire TV Stick (192.168.50.146:5555).
DEVICE=os.environ.get('KALEIDO_DEVICE','192.168.50.195:5555')
OUT=ROOT/'evidence/private'
OUT.mkdir(parents=True,exist_ok=True)
def adb(*args, data=None):
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode: raise RuntimeError(p.stderr.decode(errors='replace'))
return p.stdout
for attempt in range(4):
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
error=p.stderr.decode(errors='replace')
# The TCL's network ADB link drops intermittently; reconnecting restores it.
if p.returncode and attempt<3 and ('closed' in error or 'offline' in error):
subprocess.run([str(ADB),'disconnect',DEVICE],capture_output=True);time.sleep(2)
subprocess.run([str(ADB),'connect',DEVICE],capture_output=True);time.sleep(2);continue
# It also occasionally fails a shell command silently. Retry, except key input,
# which may already have been delivered.
if p.returncode and attempt<3 and not error.strip() and args[:2]!=('shell','input'):time.sleep(1);continue
if p.returncode: raise RuntimeError(error)
return p.stdout
def screenshot(name):
path=OUT/(name+'.png');path.write_bytes(adb('exec-out','screencap','-p'));print(path)
def hierarchy():

View file

@ -0,0 +1,99 @@
"""Time individual D-pad focus transitions on Home and Movies with gfxinfo framestats.
Select the device with KALEIDO_DEVICE (default: the onn). Use an optimized release
with the baseline profile installed and speed-profile compilation, and never run
another device test alongside it. Results stay in ignored evidence/private/.
For each transition this reports the frames drawn in the following window, the
vsyncs skipped between them (visible stutter), and frame latency percentiles.
"""
import argparse,json,time
from device import adb,OUT,DEVICE
from verify_ui import launch,key,wait,focus,focused,snapshot
HERO=('Play','Resume')
LABEL='run'
def card(r):return focus(r) not in ('','Home','Movies','TV Shows','Discover','Library')+HERO
def changed(previous):return lambda r:card(r) and focus(r)!=previous
def frames(raw):
rows=[]
for block in raw.split('---PROFILEDATA---')[1::2]:
lines=[line.strip() for line in block.splitlines() if line.strip()]
if not lines:continue
names=lines[0].rstrip(',').split(',')
for line in lines[1:]:
values=line.rstrip(',').split(',')
if len(values)!=len(names):continue
row=dict(zip(names,map(int,values)))
if row['Flags']==0 and row['FrameCompleted']>row['IntendedVsync']:rows.append(row)
return sorted(rows,key=lambda r:r['IntendedVsync'])
def summarize(rows,period):
if not rows:return {'frames':0,'skipped':0}
latency=sorted((r['FrameCompleted']-r['IntendedVsync'])/1e6 for r in rows)
ui=sorted((r['SyncQueued']-r['IntendedVsync'])/1e6 for r in rows)
# A gap after a slow frame is a stall; a gap after a fast frame, or one longer than
# 300 ms, is idle time (on weak GPUs every frame's latency exceeds one interval).
skipped=sum(max(0,round((b['IntendedVsync']-a['IntendedVsync'])/period)-1) for a,b in zip(rows,rows[1:])
if a['FrameCompleted']-a['IntendedVsync']>period and b['IntendedVsync']-a['IntendedVsync']<3e8)
pick=lambda v,p:v[min(len(v)-1,int((len(v)-1)*p))]
return {'frames':len(rows),'skipped':skipped,'median':round(pick(latency,.5),1),'p95':round(pick(latency,.95),1),
'max':round(latency[-1],1),'uiMax':round(ui[-1],1)}
def measure(name,code,expect,window,results):
time.sleep(.8)
adb('shell','dumpsys','gfxinfo','tv.kaleido.app','reset')
adb('shell','input','keyevent',str(code));time.sleep(window)
raw=adb('shell','dumpsys','gfxinfo','tv.kaleido.app','framestats').decode(errors='replace')
rows=frames(raw)
with open(OUT/f'transitions-{LABEL}-frames.txt','a') as log:log.write(f'### {name}\n'+raw.split('---PROFILEDATA---')[1]+'\n')
# The display's frame interval is the shortest step between measured frames.
steps=[b['IntendedVsync']-a['IntendedVsync'] for a,b in zip(rows,rows[1:]) if b['IntendedVsync']>a['IntendedVsync']]
results.setdefault(name,[]).append(summarize(rows,min(steps) if steps else 1e9/60))
print(name,json.dumps(results[name][-1]),flush=True)
return wait(expect,name+' destination')
def resummarize(label):
"""Recompute a saved run's per-transition stalls from its raw framestats."""
text=(OUT/f'transitions-{label}-frames.txt').read_text();totals={}
for chunk in text.split('### ')[1:]:
name,raw=chunk.split('\n',1);rows=frames('---PROFILEDATA---\n'+raw+'---PROFILEDATA---')
steps=[b['IntendedVsync']-a['IntendedVsync'] for a,b in zip(rows,rows[1:]) if b['IntendedVsync']>a['IntendedVsync']]
totals.setdefault(name,[]).append(summarize(rows,min(steps) if steps else 1e9/60))
return totals
def main():
parser=argparse.ArgumentParser();parser.add_argument('label');parser.add_argument('--cycles',type=int,default=3)
parser.add_argument('--window',type=float,default=1.2);parser.add_argument('--skip-movies',action='store_true');args=parser.parse_args()
global LABEL;LABEL=args.label;(OUT/f'transitions-{LABEL}-frames.txt').unlink(missing_ok=True)
results={}
launch()
for _ in range(args.cycles):
measure('home: tab -> hero',20,lambda r:focus(r) in HERO,args.window,results)
root=measure('home: hero -> row',20,card,args.window,results)
first=focus(root)
root=measure('home: row -> row',20,changed(first),args.window,results)
measure('home: row <- row',19,lambda r:focus(r)==first,args.window,results)
measure('home: hero <- row',19,lambda r:focus(r) in HERO,args.window,results)
measure('home: tab <- hero',19,lambda r:focus(r)=='Home',args.window,results)
if not args.skip_movies:
for _ in range(args.cycles):
measure('tabs: home -> movies',22,lambda r:focus(r)=='Movies' and 'Recently released' in [n.get('text') for n in r.iter('node')],args.window*2,results)
measure('movies: tab -> discover',20,lambda r:focus(r)=='Discover',args.window,results)
root=measure('movies: discover -> row',20,card,args.window,results)
first=focus(root)
measure('movies: row -> row',20,changed(first),args.window,results)
measure('movies: row <- row',19,lambda r:focus(r)==first,args.window,results)
measure('movies: discover <- row',19,lambda r:focus(r)=='Discover',args.window,results)
measure('movies: tab <- discover',19,lambda r:focus(r)=='Movies',args.window,results)
measure('tabs: home <- movies',21,lambda r:focus(r)=='Home',args.window*2,results)
summary={}
for name,runs in results.items():
summary[name]={'skipped':[r['skipped'] for r in runs],'p95':max(r.get('p95',0) for r in runs),'max':max(r.get('max',0) for r in runs),'uiMax':max(r.get('uiMax',0) for r in runs)}
report={'device':DEVICE,'transitions':summary,'runs':results}
(OUT/f'transitions-{args.label}.json').write_text(json.dumps(report,indent=2)+'\n')
print('\nSUMMARY',args.label,DEVICE)
for name,s in summary.items():print(f" {name:28} skipped={s['skipped']} p95={s['p95']} max={s['max']} uiMax={s['uiMax']}")
if __name__=='__main__':main()

View file

@ -0,0 +1,49 @@
"""Trace one D-pad transition and summarize Kaleido's slow UI-thread frames.
Usage: trace_transition.py <label> <setup keys> <measured keys>
Keys are comma-separated keycodes (19 up, 20 down, 21 left, 22 right); setup runs
after launch and is not measured. Select the device with KALEIDO_DEVICE. Raw atrace
output and the summary stay in ignored evidence/private/.
"""
import collections,re,sys,time
from device import adb,OUT
from verify_ui import launch
SLICE=re.compile(r'^\s*(.+?)-(\d+)\s+\(\s*(\d+)\)\s+\[\d+\]\s+\S+\s+([\d.]+): tracing_mark_write: ([BE])\|(\d+)(?:\|(.*))?$')
def slices(text,pid):
stacks=collections.defaultdict(list);done=[]
for line in text.splitlines():
m=SLICE.match(line)
if not m or m.group(3)!=pid:continue
tid=int(m.group(2));at=float(m.group(4))*1000
if m.group(5)=='B':stacks[tid].append((m.group(7) or '',at))
elif stacks[tid]:
name,start=stacks[tid].pop();done.append((tid,len(stacks[tid]),name,start,at-start))
return done
def main():
label,setup,measured=sys.argv[1],sys.argv[2],sys.argv[3]
launch()
for code in filter(None,setup.split(',')):adb('shell','input','keyevent',code);time.sleep(1.2)
pid=adb('shell','pidof','tv.kaleido.app').decode().split()[0]
time.sleep(1)
adb('shell','atrace','--async_start','-b','16384','-a','tv.kaleido.app','gfx','view','sched','dalvik')
for code in measured.split(','):adb('shell','input','keyevent',code);time.sleep(1.5)
raw=adb('shell','atrace','--async_stop','-a','tv.kaleido.app','gfx','view','sched','dalvik').decode(errors='replace')
(OUT/f'trace-{label}.txt').write_text(raw)
found=slices(raw,pid);main_tid=int(pid)
frames=[s for s in found if s[0]==main_tid and s[2].startswith('Choreographer#doFrame')]
lines=[f'{len(frames)} UI frames; slow (>12 ms) frames with their longest nested work:']
for tid,depth,name,start,length in frames:
if length<12:continue
inner=[s for s in found if s[0]==main_tid and s[3]>=start and s[3]+s[4]<=start+length and s[1]>depth]
top=sorted(inner,key=lambda s:-s[4])[:8]
lines.append(f' {name} {length:.1f} ms')
lines+=[f' {" "*(s[1]-depth-1)}{s[2][:90]} {s[4]:.1f}' for s in sorted(top,key=lambda s:(s[3],s[1]))]
render=[s for s in found if s[2]=='DrawFrame' or s[2].startswith('DrawFrames')]
if render:lines.append(f'RenderThread DrawFrame max {max(s[4] for s in render):.1f} ms over {len(render)} frames')
(OUT/f'trace-{label}-summary.txt').write_text('\n'.join(lines)+'\n')
print('\n'.join(lines))
if __name__=='__main__':main()

View file

@ -16,9 +16,11 @@ def focus(root):
if n is None:return ''
return n.get('content-desc','') or ' '.join(labels(n))
def wait(check,description,timeout=25):
deadline=time.monotonic()+timeout
deadline=time.monotonic()+timeout;root=ET.fromstring('<hierarchy/>')
while time.monotonic()<deadline:
root=snapshot()
# uiautomator can't dump while an animation keeps the window busy; try again.
try:root=snapshot()
except RuntimeError:time.sleep(.5);continue
if check(root):return root
time.sleep(.2)
raise AssertionError(description+'; last focus='+focus(root)+'; labels='+str(labels(root)[:10]))
@ -27,6 +29,8 @@ def focused(value):return wait(lambda root:value in focus(root),'Expected focus
def passed(name):results.append(name);print('PASS '+name,flush=True)
def capture(name):time.sleep(.4);screenshot('final-'+name)
def launch():
# Idle test devices may be in their screensaver; WAKEUP only wakes, it never navigates.
adb('shell','input','keyevent','KEYCODE_WAKEUP');time.sleep(1)
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
text('Continue Watching')