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

@ -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)