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

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