Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: trace.py and trace_report.py, Perfetto traces of the launcher and the numbers from them
simeec8a918c3c0
diff --git a/.gitignore b/.gitignoreindex f68fbca65..c065914d1 100644--- a/.gitignore+++ b/.gitignore@@ -10,6 +10,8 @@ backup/# session screenshots and working notes (may show the Wi-Fi name or account avatar) stay localshots/work/+# Perfetto traces from tools/trace.py: large, and they hold the TV's process list+traces/.DS_Store# Generated install bundles and JVM crash reports stay out of contributions.diff --git a/AGENTS.md b/AGENTS.mdindex 2a805894c..afb56b46b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -66,7 +66,7 @@ share their TV's list afterwards, follow [Add a TV list](#add-a-tv-list) below.| `launcher/` | The reference launcher, package `com.gathin.tvhome`: plain Java, AndroidX RecyclerView and DynamicAnimation, `minSdk` 26, no `INTERNET` permission. || `themes/` | One folder per theme: `config.json`, a required `screenshot.jpg`, optional wallpapers. Keys are documented in `themes/README.md`. || `addons/` | Optional module-card apps, each its own Gradle project, never built into the launcher. |-| `tools/` | The ADB client and the scripts: `tv.py`, `b64push.py`, `relay.py` (guide: `tools/relay.md`), `disable.sh`, `restore.sh`, `recovery.py`, `check.py`, `privacy.py`, `theme.sh`, `adb-closed.py`, `bench.py`, `race_calendar.py`. Shell scripts have PowerShell twins (`disable.ps1` and the like). `readme_stats.py`, `readme_featured.py` and `readme_card.py` draw the README card. Each script's usage is in its first lines: read it before running it. |+| `tools/` | The ADB client and the scripts: `tv.py`, `b64push.py`, `relay.py` (guide: `tools/relay.md`), `disable.sh`, `restore.sh`, `recovery.py`, `check.py`, `privacy.py`, `theme.sh`, `adb-closed.py`, `bench.py`, `trace.py` and `trace_report.py` (guide: `tools/trace.md`, optional `tools/requirements-perf.txt`), `race_calendar.py`. Shell scripts have PowerShell twins (`disable.ps1` and the like). `readme_stats.py`, `readme_featured.py` and `readme_card.py` draw the README card. Each script's usage is in its first lines: read it before running it. || `tests/` | Python `unittest` suite: list format, README tables, press counts, themes, add-ons, the Home guard and the tools against fake TVs. || `.github/workflows/` | `ci.yml` (tests, launcher build, APK size gate), `addons.yml`, `maintainer-bot.yml`. || `.github/maintainer/MAINTAINER.md` | The review policy the maintainer and the PR bot apply. |diff --git a/README.md b/README.mdindex c2693f330..a277bcd67 100644--- a/README.md+++ b/README.md@@ -358,6 +358,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`tools/check.py`](tools/check.py) | Compares the TV with the list that was applied, for what a firmware update undid; `--fix` puts it back. || [`tools/privacy.py`](tools/privacy.py) | Audits the TV for voice, ACR and telemetry candidates and prints the evidence for each; `--write` turns the findings into a list `disable.sh` and `restore.sh` already understand. || [`tools/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. |+| [`tools/trace.py`](tools/trace.py), [`trace_report.py`](tools/trace_report.py) | Records Perfetto traces of the launcher (return to Home, cold start, D-pad) and reports where its time goes, per run and before against after. Optional: needs [`requirements-perf.txt`](tools/requirements-perf.txt). [Guide](tools/trace.md). || [`tools/race_calendar.py`](tools/race_calendar.py) | Writes this season's F1 calendar into a theme for race-weekend mode, from the free Jolpica API. || [`launcher/build-and-install.sh`](launcher/build-and-install.sh) | Builds a shrunk release (about 445 KB), installs it, switches Home, and rolls back if Home does not land on it. |diff --git a/tests/test_trace.py b/tests/test_trace.pynew file mode 100644index 000000000..406f81efd--- /dev/null+++ b/tests/test_trace.py@@ -0,0 +1,166 @@+"""tools/trace.py: the scenarios it records, the Perfetto config it sends, and the order it works in.++A trace is only comparable with another if both were recorded the same way: the setup outside the+recording (so opening the other app is not in it), the same steps, a recording long enough for them,+and the trace pulled back with nothing left on the TV. A force-stop can take the launcher's+accessibility helpers off the list, so they are put back after the last run, never before (that+would warm a cold start; see tests/test_bench_accessibility.py).++The TV is faked, so these run without one and without adb_shell.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import contextlib+import importlib.util+import io+import os+from pathlib import Path+import sys+import tempfile+import unittest+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("cyt_trace", ROOT / "tools" / "trace.py")+trace = importlib.util.module_from_spec(spec)+spec.loader.exec_module(trace)++LAUNCHER = "com.gathin.tvhome/.MainActivity"+OTHER = "com.android.tv.settings/.MainSettings"+++class FakeDevice:+ """Answers the shell commands trace.py sends and records them; pull writes a stand-in trace."""++ def __init__(self, perfetto_says="1234\n"):+ self.perfetto_says = perfetto_says+ self.calls = []++ def shell(self, command, read_timeout_s=None):+ self.calls.append(("shell", command))+ if "perfetto --txt" in command:+ return self.perfetto_says+ return ""++ def pull(self, remote, local, transport_timeout_s=None, read_timeout_s=None):+ self.calls.append(("pull", remote, local))+ Path(local).write_bytes(b"trace")+++class ScenarioTest(unittest.TestCase):+ def test_setup_stays_out_of_the_recording(self):+ setup, steps = trace.scenario("home", LAUNCHER, OTHER)+ self.assertIn(f"am start -n {OTHER}", setup)+ self.assertEqual(steps, ["input keyevent KEYCODE_HOME", "sleep 4"])++ def test_cold_stops_the_launcher_before_recording_and_starts_it_inside(self):+ setup, steps = trace.scenario("cold", LAUNCHER, OTHER)+ self.assertIn("am force-stop com.gathin.tvhome", setup)+ self.assertEqual(steps[0], f"am start -W -n {LAUNCHER}")++ def test_coldsys_leaves_the_restart_to_android(self):+ setup, steps = trace.scenario("coldsys", LAUNCHER, None)+ self.assertEqual(steps[0], "am force-stop com.gathin.tvhome")+ self.assertFalse(any("am start" in s for s in setup + steps))++ def test_nav_is_24_moves(self):+ _, steps = trace.scenario("nav", LAUNCHER, None)+ self.assertEqual(sum(s.startswith("input keyevent KEYCODE_DPAD_") for s in steps), 24)++ def test_custom_uses_the_given_commands(self):+ self.assertEqual(trace.scenario("custom", LAUNCHER, None, ["a"], ["b", "sleep 1"]), (["a"], ["b", "sleep 1"]))++ def test_recording_covers_the_sleeps_plus_margins(self):+ self.assertEqual(trace.recording_ms(["input keyevent KEYCODE_HOME", "sleep 4"]),+ (trace.START_MARGIN_S + 4 + trace.END_MARGIN_S) * 1000)++ def test_config_traces_the_launcher_for_that_long(self):+ config = trace.perfetto_config("com.gathin.tvhome", 9000)+ self.assertIn('atrace_apps: "com.gathin.tvhome"', config)+ self.assertIn("duration_ms: 9000", config)+ self.assertIn("android.surfaceflinger.frametimeline", config)+++class ArgumentTest(unittest.TestCase):+ def parse_error(self, argv):+ with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as caught:+ trace.parse(argv)+ self.assertEqual(caught.exception.code, 2)+ return err.getvalue()++ def test_bad_package_and_component_are_refused_before_connecting(self):+ self.assertIn("not a package name", self.parse_error(["home", "--package", "x; reboot"]))+ self.assertIn("--app needs", self.parse_error(["home", "--app", "com.example"]))++ def test_custom_needs_a_step_and_others_take_none(self):+ self.assertIn("at least one --step", self.parse_error(["custom"]))+ self.assertIn("custom scenario", self.parse_error(["home", "--step", "x"]))++ def test_defaults(self):+ args = trace.parse(["nav"])+ self.assertEqual((args.runs, args.out, args.package), (5, "traces", "com.gathin.tvhome"))+++class RecordTest(unittest.TestCase):+ def record(self, device, setup, steps):+ with tempfile.TemporaryDirectory() as tmp, mock.patch.object(trace.time, "sleep") as sleep:+ path = os.path.join(tmp, "home-1.pftrace")+ size = trace.record_one(device, setup, steps, "com.gathin.tvhome", path)+ return size, sleep++ def test_setup_then_perfetto_then_steps_then_pull_and_cleanup(self):+ device = FakeDevice()+ size, _ = self.record(device, ["input keyevent KEYCODE_HOME"], ["input keyevent KEYCODE_DPAD_RIGHT"])+ commands = [c[1] for c in device.calls]+ start = next(i for i, c in enumerate(commands) if "perfetto --txt" in c)+ self.assertEqual(commands[0], "input keyevent KEYCODE_HOME")+ self.assertGreater(commands.index("input keyevent KEYCODE_DPAD_RIGHT"), start)+ self.assertEqual(device.calls[-2][0], "pull")+ self.assertEqual(commands[-1], f"rm -f {trace.REMOTE}")+ self.assertEqual(size, len(b"trace"))++ def test_sleeps_wait_here_not_on_the_tv(self):+ device = FakeDevice()+ _, sleep = self.record(device, ["sleep 2"], ["sleep 1.5"])+ self.assertFalse(any(c[1].startswith("sleep") for c in device.calls if c[0] == "shell"))+ self.assertIn(mock.call(2.0), sleep.call_args_list)+ self.assertIn(mock.call(1.5), sleep.call_args_list)++ def test_waits_on_the_pid_perfetto_reports(self):+ device = FakeDevice("1234\n")+ self.record(device, [], ["sleep 1"])+ self.assertIn(("shell", "[ -d /proc/1234 ] && echo running"), device.calls)++ def test_an_empty_trace_is_an_error_not_a_file(self):+ device = FakeDevice()+ device.pull = lambda remote, local, **kw: Path(local).write_bytes(b"")+ with tempfile.TemporaryDirectory() as tmp, mock.patch.object(trace.time, "sleep"):+ with self.assertRaises(RuntimeError) as caught:+ trace.record_one(device, [], ["sleep 1"], "com.gathin.tvhome", os.path.join(tmp, "x.pftrace"))+ self.assertEqual(os.listdir(tmp), [], "no 0-byte trace is left behind")+ self.assertIn("empty trace", str(caught.exception))+++ def test_a_tv_without_perfetto_says_so(self):+ with self.assertRaises(RuntimeError) as caught:+ self.record(FakeDevice("/system/bin/sh: perfetto: not found\n"), [], ["sleep 1"])+ self.assertIn("Android 9 and later", str(caught.exception))+++class OtherAppTest(unittest.TestCase):+ def shell(self, answers):+ return lambda cmd: next((v for k, v in answers.items() if k in cmd), "")++ def test_settings_first(self):+ shell = self.shell({"android.settings.SETTINGS": "priority=0\ncom.android.tv.settings/.MainSettings\n",+ "LEANBACK_LAUNCHER": "org.videolan.vlc/.StartActivity\n"})+ self.assertEqual(trace.other_app(shell, "com.gathin.tvhome"), "com.android.tv.settings/.MainSettings")++ def test_never_the_chooser_or_the_launcher(self):+ shell = self.shell({"android.settings.SETTINGS": "android/com.android.internal.app.ResolverActivity\n",+ "LEANBACK_LAUNCHER": "com.gathin.tvhome/.MainActivity\norg.videolan.vlc/.StartActivity\n"})+ self.assertEqual(trace.other_app(shell, "com.gathin.tvhome"), "org.videolan.vlc/.StartActivity")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_trace_report.py b/tests/test_trace_report.pynew file mode 100644index 000000000..8b2f3da79--- /dev/null+++ b/tests/test_trace_report.py@@ -0,0 +1,161 @@+"""tools/trace_report.py: the numbers it takes from a trace, and how it reports runs and changes.++The report reads traces with Perfetto's query engine, which CI never downloads. Its SQL is plain+SQLite, though, so these tests run the same queries against a small in-memory database laid out+like a trace (process, thread, thread_track, slice, actual_frame_timeline_slice) and check the+numbers by hand. A test that needs the real engine runs only when the optional perfetto package is+installed and CLEANYOURTV_TRACE names a trace recorded with tools/trace.py.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import contextlib+import importlib.util+import io+import os+from pathlib import Path+import sqlite3+import sys+import tempfile+import unittest+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("cyt_trace_report", ROOT / "tools" / "trace_report.py")+report = importlib.util.module_from_spec(spec)+spec.loader.exec_module(report)++PKG = "com.gathin.tvhome"+MS = 1_000_000+++def fake_trace(cold=False, frames=(), draws=(), missed=1, gpu=()):+ """A database shaped like a trace of the launcher coming to the front at t = 1000 ms."""+ db = sqlite3.connect(":memory:")+ db.row_factory = sqlite3.Row+ db.executescript("""+ create table process (upid integer, pid integer, name text);+ create table thread (utid integer, upid integer, tid integer, name text);+ create table thread_track (id integer, utid integer);+ create table slice (id integer primary key, ts integer, dur integer, name text, track_id integer);+ create table actual_frame_timeline_slice (ts integer, dur integer, upid integer, jank_type text);+ insert into process values (1, 90, 'com.gathin.tvhome'), (2, 100, 'com.gathin.tvhome'), (3, 200, 'other');+ insert into thread values (1, 2, 100, 'com.gathin.tvhome'), (2, 2, 101, 'RenderThread'),+ (3, 1, 90, 'com.gathin.tvhome');+ insert into thread_track values (10, 1), (20, 2), (30, 3);+ """)+ main = [("performStart:com.gathin.tvhome.MainActivity", 1000, 5), ("activityResume", 1005, 30),+ ("traversal", 1040, 20), ("traversal", 1200, 5)]+ if cold:+ main = [("bindApplication", 900, 40), ("activityStart", 945, 50)] + main+ for name, ts, dur in main:+ db.execute("insert into slice (ts, dur, name, track_id) values (?, ?, ?, 10)", (ts * MS, dur * MS, name))+ db.execute("insert into slice (ts, dur, name, track_id) values (?, ?, 'performStart:old', 30)", (100 * MS, MS))+ for ts, dur in [(1055, 10)] + list(draws):+ db.execute("insert into slice (ts, dur, name, track_id) values (?, ?, 'DrawFrames 1', 20)", (ts * MS, dur * MS))+ for ts, dur in gpu:+ db.execute("insert into slice (ts, dur, name, track_id) values (?, ?, 'waiting for GPU completion 5', 20)",+ (ts * MS, dur * MS))+ for i, dur in enumerate(frames):+ jank = "App Deadline Missed" if i < missed else "Buffer Stuffing"+ db.execute("insert into actual_frame_timeline_slice values (?, ?, 2, ?)", ((1060 + 20 * i) * MS, dur * MS, jank))+ return lambda sql: [dict(r) for r in db.execute(sql)]+++class StartMetricsTest(unittest.TestCase):+ def test_warm_return_from_performstart_to_the_first_frame_drawn(self):+ m = report.start_metrics(fake_trace(frames=[16, 16, 16]), PKG)+ self.assertEqual(m["first frame"], 65) # DrawFrame ends at 1065, after the traversal's 1060+ self.assertEqual(m["onResume"], 30)+ self.assertEqual(m["first traversal"], 20)+ self.assertEqual(m["frames"], 1)+ self.assertEqual(m["missed"], 1) # buffer stuffing is not a missed deadline+ self.assertNotIn("bindApplication", m)++ def test_cold_start_counts_from_bindapplication(self):+ m = report.start_metrics(fake_trace(cold=True), PKG)+ self.assertEqual(m["first frame"], 165)+ self.assertEqual((m["bindApplication"], m["activityStart"]), (40, 50))++ def test_frames_outside_the_window_are_not_counted(self):+ m = report.start_metrics(fake_trace(draws=[(1500, 8), (2600, 8)]), PKG)+ self.assertEqual(m["frames"], 2)++ def test_newest_launcher_process_is_used(self):+ self.assertEqual(report.threads(fake_trace(), PKG), (2, 1, 2))++ def test_a_trace_without_the_launcher_gives_nothing(self):+ self.assertEqual(report.start_metrics(fake_trace(), "com.example.other"), {})+++class NavMetricsTest(unittest.TestCase):+ def test_frame_times_draws_gpu_and_missed_deadlines(self):+ q = fake_trace(frames=[10, 12, 14, 16, 40], missed=2, draws=[(1100, 6), (1120, 8)], gpu=[(1101, 2), (1121, 4)])+ m = report.nav_metrics(q, PKG)+ self.assertEqual(m["frames"], 5)+ self.assertEqual(m["frame median"], 14)+ self.assertEqual(m["frame p90"], 40)+ self.assertEqual(m["draw median"], 8)+ self.assertEqual(m["gpu median"], 3)+ self.assertEqual(m["missed"], 2)+++class ReportTest(unittest.TestCase):+ RUNS = [("home-1", {"first frame": 90, "onResume": 40}), ("home-2", {"first frame": 300, "onResume": 290}),+ ("home-3", {"first frame": 80, "onResume": 35})]+ AFTER = [("home-1", {"first frame": 50, "onResume": 2}), ("home-2", {"first frame": 45, "onResume": 3})]++ def test_runs_with_median_range_and_a_starred_outlier(self):+ text = report.report(self.RUNS, None, False, nav=False)+ row = next(l for l in text.splitlines() if l.startswith("start to first frame"))+ self.assertIn("300*", row)+ self.assertIn("90", row.split()[-2]) # median+ self.assertIn("80–300", row)+ self.assertIn("more than twice the median", text)++ def test_comparison_shows_the_change_in_the_median(self):+ text = report.report(self.RUNS, self.AFTER, True, nav=False)+ self.assertIn("| start to first frame drawn (ms) | 90 | 48 | -47% |", text)+ self.assertIn("|---|---|---|---|", text)++ def test_metrics_no_run_has_are_left_out(self):+ text = report.report(self.RUNS, None, False, nav=False)+ self.assertNotIn("bindApplication", text)+++class FilesTest(unittest.TestCase):+ def test_folders_expand_in_run_order(self):+ with tempfile.TemporaryDirectory() as tmp:+ for n in (1, 2, 10):+ Path(tmp, f"home-{n}.pftrace").write_bytes(b"")+ self.assertEqual([os.path.basename(p) for p in report.expand([tmp])],+ ["home-1.pftrace", "home-2.pftrace", "home-10.pftrace"])++ def test_scenario_comes_from_the_sidecar_then_the_name(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp, "run-1.pftrace")+ path.with_suffix(".json").write_text('{"scenario": "nav"}')+ self.assertEqual(report.scenario_of(str(path)), "nav")+ self.assertEqual(report.scenario_of(str(Path(tmp, "cold-3.pftrace"))), "cold")++ def test_missing_perfetto_says_what_to_install(self):+ with mock.patch.dict(sys.modules, {"perfetto": None, "perfetto.trace_processor": None}), \+ contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught:+ report.opener()+ self.assertIn("requirements-perf.txt", str(caught.exception.code))++[email protected](os.environ.get("CLEANYOURTV_TRACE") and importlib.util.find_spec("perfetto"),+ "needs the optional perfetto package and CLEANYOURTV_TRACE=<a trace from tools/trace.py>")+class RealTraceTest(unittest.TestCase):+ def test_the_real_engine_runs_the_same_queries(self):+ path = os.environ["CLEANYOURTV_TRACE"]+ q, close = report.opener()(path)+ try:+ metrics = report.nav_metrics(q, PKG) if report.scenario_of(path) == "nav" else report.start_metrics(q, PKG)+ finally:+ close()+ self.assertIn("frames", metrics)+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/requirements-perf.txt b/tools/requirements-perf.txtnew file mode 100644index 000000000..60056538b--- /dev/null+++ b/tools/requirements-perf.txt@@ -0,0 +1,3 @@+# Optional: only for the performance tools (tools/trace_report.py). Not needed to clean a TV.+# tools/venv/bin/pip install -r tools/requirements-perf.txt See tools/trace.md.+perfetto==0.58.2diff --git a/tools/trace.md b/tools/trace.mdnew file mode 100644index 000000000..8720735b9--- /dev/null+++ b/tools/trace.md@@ -0,0 +1,60 @@+# tools/trace.py and tools/trace_report.py++Record Perfetto traces of the launcher on the TV, then report where its time goes. For headline numbers+only (key latency, jank, cold start, PSS), use `tools/bench.py` instead: it needs no extra install.++## Setup++```bash+tools/venv/bin/pip install -r tools/requirements-perf.txt+```++Recording needs only `tools/requirements.txt` and a TV on Android 9 or later. The report's first run+downloads Perfetto's query engine (about 13 MB, SHA-256 checked) to `~/.local/share/perfetto`. To avoid+that, download `trace_processor_shell` yourself and pass `--engine PATH`.++## Record++```bash+TV_HOST=<tv ip> tools/venv/bin/python -I tools/trace.py home --runs 5 --out traces/before+```++| Scenario | Recorded | Use for |+|---|---|---|+| `home` | HOME pressed while another app is in front | Most Home changes |+| `cold` | `am start -W` after a force-stop, another app in front | Start-up work (`onCreate`, config, fonts) |+| `coldsys` | `am force-stop` with Home in front; Android restarts it | The restart after Home was killed for memory |+| `nav` | 24 D-pad moves, 0.35 s apart | Focus, scrolling, drawing |+| `custom` | `--step CMD` (repeatable) after `--setup CMD` | Anything else; `sleep N` steps set the length |++- **Output:** each run writes `<scenario>-<n>.pftrace` (10–20 MB) and a `.json` with the commands and the+ TV's model and build. `traces/` is gitignored.+- **The other app:** `--app package/activity`, or by default the TV's Settings.++## Report++```bash+tools/venv/bin/python tools/trace_report.py traces/before --vs traces/after --markdown+```++| Scenario | Numbers |+|---|---|+| Starts (`home`, `cold`, `coldsys`, `custom`) | Start to first frame drawn; the steps inside it (`bindApplication`, `onCreate`, `onStart`, `onResume`, first layout and draw); then the frames drawn and missed deadlines in the next 1.5 s |+| `nav` | Frame time (median, 90th percentile); RenderThread draw; GPU wait; missed deadlines |++With `--vs`, a third table shows the change in each median. A run over twice the median is starred.++## Rules++- **Repeat runs.** Record 5 runs per build, on the same TV with the same config, theme and wallpaper.+ Compare medians.+- **Keep starred runs.** They're usually memory pressure on a 1 GB TV. Report them; don't drop them.+- **Don't run `am start` after a force-stop with Home in front.** Android has already restarted Home, so+ `onResume` appears twice. Use `cold` or `coldsys`.+- **Check the remote afterwards.** A force-stop switches off the accessibility helpers. `trace.py` puts the+ list back after the last run, but on some TCL sets a helper still won't bind (`docs/TROUBLESHOOTING.md`).+- **Look in the right place for GPU savings.** Less overdraw shows as GPU wait in `nav`, not as main-thread+ time.+- **Expect no latency gain from off-main-thread work.** It removes work, but doesn't shorten the time to+ the first frame.+- **Never commit the `.pftrace` files.** They hold the TV's process list.diff --git a/tools/trace.py b/tools/trace.pynew file mode 100644index 000000000..aa6a373b5--- /dev/null+++ b/tools/trace.py@@ -0,0 +1,222 @@+#!/usr/bin/env python3+"""Record Perfetto traces on the TV around a launcher scenario, to see where its time goes.++tools/bench.py gives the headline numbers (key latency, jank, cold start, return to Home, PSS) with no+extra installs. This records the full timeline instead: every thread's slices, the launcher's own+lifecycle (onCreate, onResume, layout, draw) and the frame timeline, so a change can be traced to the+work it removes. tools/trace_report.py turns a folder of these traces into the numbers. Read+tools/trace.md first: it says which scenario to use and what can mislead.++Recording needs nothing beyond tools/requirements.txt; the perfetto client already ships on Android 9+and later. Set TV_HOST to the TV's IP (and TV_PORT if it is not 5555). Usage:++ tools/trace.py home --runs 5 --out traces/before+ tools/trace.py cold|coldsys|home|nav --runs N --out DIR [--package PKG] [--app COMPONENT]+ tools/trace.py custom --setup 'input keyevent KEYCODE_HOME' --setup 'sleep 2' \\+ --step 'input keyevent KEYCODE_DPAD_RIGHT' --step 'sleep 1' --out DIR++Scenarios (setup runs before the recording starts, so it stays out of the trace):+ cold another app in front, the launcher force-stopped, then started with `am start -W`+ coldsys Home in front, the launcher force-stopped: Android starts it again by itself+ home another app in front, then the HOME key: the everyday return to Home+ nav Home in front, then 24 D-pad moves 0.35 s apart+ custom your own --setup and --step shell commands; `sleep N` steps set the length+"""+import argparse+import base64+import json+import os+import re+import sys+import time++PACKAGE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$")+COMPONENT = re.compile(r"^[A-Za-z][A-Za-z0-9_.]*/[A-Za-z0-9_.$]+$")+REMOTE = "/data/misc/perfetto-traces/cleanyourtv.pftrace" # the folder perfetto may write to on Android 9 and 10+NAV_KEYS = ("RIGHT RIGHT RIGHT LEFT LEFT LEFT DOWN RIGHT DOWN LEFT DOWN UP "+ "UP RIGHT UP LEFT DOWN DOWN RIGHT RIGHT UP UP UP LEFT").split()+START_MARGIN_S = 3 # recording starts in the background; give it time before the first step+END_MARGIN_S = 2++CONFIG = """buffers {{ size_kb: 65536 fill_policy: RING_BUFFER }}+buffers {{ size_kb: 4096 fill_policy: RING_BUFFER }}+data_sources {{ config {{ name: "linux.ftrace" target_buffer: 0 ftrace_config {{+ ftrace_events: "sched/sched_switch" ftrace_events: "sched/sched_wakeup" ftrace_events: "sched/sched_waking"+ ftrace_events: "power/cpu_frequency" ftrace_events: "power/cpu_idle"+ ftrace_events: "task/task_newtask" ftrace_events: "task/task_rename" ftrace_events: "sched/sched_process_exit"+ atrace_categories: "am" atrace_categories: "wm" atrace_categories: "view" atrace_categories: "gfx"+ atrace_categories: "input" atrace_categories: "dalvik" atrace_categories: "res" atrace_categories: "binder_driver"+ atrace_apps: "{package}"+ buffer_size_kb: 16384 drain_period_ms: 250 }} }} }}+data_sources {{ config {{ name: "linux.process_stats" target_buffer: 1 process_stats_config {{ scan_all_processes_on_start: true }} }} }}+data_sources {{ config {{ name: "android.surfaceflinger.frametimeline" }} }}+data_sources {{ config {{ name: "android.packages_list" }} }}+duration_ms: {duration_ms}+"""+++def perfetto_config(package, duration_ms):+ """The text config: scheduling, the app's lifecycle and drawing slices, and the frame timeline."""+ return CONFIG.format(package=package, duration_ms=int(duration_ms))+++def recording_ms(steps):+ """How long to record: the steps' sleeps plus a margin either side."""+ slept = sum(float(s.split()[1]) for s in steps if re.fullmatch(r"sleep \d+(\.\d+)?", s.strip()))+ return int((START_MARGIN_S + slept + END_MARGIN_S) * 1000)+++def scenario(name, launcher_component, other_component, setup=(), steps=()):+ """(setup, steps) shell commands for a scenario. Setup runs before the recording starts."""+ package = launcher_component.split("/")[0]+ other = f"am start -n {other_component}" if other_component else None+ if name == "cold":+ return [other, "sleep 2", f"am force-stop {package}", "sleep 2"], \+ [f"am start -W -n {launcher_component}", "sleep 4"]+ if name == "coldsys":+ return ["input keyevent KEYCODE_HOME", "sleep 2"], [f"am force-stop {package}", "sleep 5"]+ if name == "home":+ return ["input keyevent KEYCODE_HOME", "sleep 2", other, "sleep 4"], ["input keyevent KEYCODE_HOME", "sleep 4"]+ if name == "nav":+ moves = []+ for key in NAV_KEYS:+ moves += [f"input keyevent KEYCODE_DPAD_{key}", "sleep 0.35"]+ return ["input keyevent KEYCODE_HOME", "sleep 2"], moves + ["sleep 1"]+ return list(setup), list(steps)+++def parse(argv):+ p = argparse.ArgumentParser(description="Record Perfetto traces on the TV around a launcher scenario. "+ "See tools/trace.md.")+ p.add_argument("scenario", choices=["cold", "coldsys", "home", "nav", "custom"])+ p.add_argument("--runs", type=int, default=5, help="how many traces to record (default 5)")+ p.add_argument("--out", default="traces", help="folder for the traces (default traces/)")+ p.add_argument("--package", default="com.gathin.tvhome", help="the launcher's package (default com.gathin.tvhome)")+ p.add_argument("--app", metavar="COMPONENT",+ help="the other app for cold and home, as package/activity (default: found on the TV)")+ p.add_argument("--setup", action="append", default=[], metavar="CMD", help="custom: a setup command")+ p.add_argument("--step", action="append", default=[], metavar="CMD", help="custom: a recorded step")+ args = p.parse_args(argv)+ if not PACKAGE.match(args.package):+ p.error(f"not a package name: {args.package!r}")+ if args.app and not COMPONENT.match(args.app):+ p.error(f"--app needs package/activity, not {args.app!r}")+ if not 1 <= args.runs <= 50:+ p.error("--runs must be between 1 and 50")+ if args.scenario == "custom" and not args.step:+ p.error("custom needs at least one --step")+ if args.scenario != "custom" and (args.setup or args.step):+ p.error("--setup and --step are for the custom scenario")+ return args+++def record_one(dev, setup, steps, package, out_path, run_shell=None):+ """Run the setup, record while the steps run, then pull the trace to out_path."""+ run_shell = run_shell or (lambda cmd: dev.shell(cmd, read_timeout_s=120.0))+ for cmd in setup:+ _run(run_shell, cmd)+ config = base64.b64encode(perfetto_config(package, recording_ms(steps)).encode()).decode()+ said = run_shell(f"rm -f {REMOTE}; echo {config} | base64 -d | perfetto --txt -c - -o {REMOTE} --background 2>&1")+ if re.search(r"not found|inaccessible|[Ee]rror", said):+ raise RuntimeError("perfetto did not start on the TV (it ships with Android 9 and later): " + said.strip())+ # --background prints the PID it continues as. Watch /proc for it: SELinux refuses `kill -0` on perfetto's+ # process from the shell (TCL C755), which would look like a finished recording and pull an empty file.+ pid = next((w for w in said.split() if w.isdigit()), None)+ alive = f"[ -d /proc/{pid} ] && echo running" if pid else "pidof perfetto >/dev/null && echo running"+ time.sleep(START_MARGIN_S)+ for cmd in steps:+ _run(run_shell, cmd)+ time.sleep(END_MARGIN_S)+ for _ in range(60): # the config's duration ends the recording; wait for the file to be written+ if run_shell(alive).strip() != "running":+ break+ time.sleep(1)+ dev.pull(REMOTE, out_path, transport_timeout_s=300.0, read_timeout_s=300.0)+ run_shell(f"rm -f {REMOTE}")+ size = os.path.getsize(out_path)+ if size == 0:+ os.remove(out_path)+ raise RuntimeError("perfetto wrote an empty trace; run with --runs 1 and see tools/trace.md")+ return size+++def other_app(shell, package):+ """An app to leave Home for: the TV's Settings, else the first leanback app that isn't the launcher.++ Never the chooser: on a TCL C755 a plain LAUNCHER lookup resolves to android's ResolverActivity, a dialog.+ """+ candidates = shell("cmd package resolve-activity --brief -a android.settings.SETTINGS").splitlines()+ candidates += shell("cmd package query-activities --brief -a android.intent.action.MAIN "+ "-c android.intent.category.LEANBACK_LAUNCHER").splitlines()+ for line in candidates:+ line = line.strip()+ if COMPONENT.match(line) and not line.startswith(("android/", package + "/")) and "Resolver" not in line:+ return line+ return None+++def _run(run_shell, cmd):+ """A step: `sleep N` waits here (an adb shell sleep would block the connection), anything else runs on the TV."""+ m = re.fullmatch(r"sleep (\d+(?:\.\d+)?)", cmd.strip())+ if m:+ time.sleep(float(m.group(1)))+ else:+ run_shell(cmd)+++def main(argv=None):+ args = parse(sys.argv[1:] if argv is None else argv)+ # Imported only now, so --help and argument errors work without TV_HOST set.+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import bench # noqa: E402 the accessibility helpers bench.py already tested+ import tv # noqa: E402++ try:+ dev = tv.connect()+ except OSError as e:+ sys.exit(f"cannot reach the TV at {tv.HOST}:{tv.PORT} ({e}). Is it on and awake, with network debugging on?")+ shell = lambda cmd: dev.shell(cmd, read_timeout_s=120.0)+ try:+ home = shell("cmd package resolve-activity --brief -a android.intent.action.MAIN "+ f"-c android.intent.category.HOME {args.package}").strip().splitlines()+ launcher = home[-1].strip() if home and "/" in home[-1] else f"{args.package}/.MainActivity"+ other = args.app+ if args.scenario in ("cold", "home") and not other:+ other = other_app(shell, args.package)+ if not other:+ sys.exit("could not find another app to switch to; pass --app package/activity")+ setup, steps = scenario(args.scenario, launcher, other, args.setup, args.step)+ stops = any("force-stop" in c for c in setup + steps)+ # A force-stop can take the launcher's accessibility helpers off the list (tools/bench.py): read them+ # before the first one and put them back after the last run, never before (it would warm a cold start).+ helpers = bench.accessibility_services(_Shell(shell), args.package) if stops else []+ about = {"model": shell("getprop ro.product.model").strip(),+ "android": shell("getprop ro.build.version.release").strip(),+ "build": shell("getprop ro.build.display.id").strip()}+ os.makedirs(args.out, exist_ok=True)+ try:+ for run in range(1, args.runs + 1):+ path = os.path.join(args.out, f"{args.scenario}-{run}.pftrace")+ size = record_one(dev, setup, steps, args.package, path, shell)+ with open(path[:-len(".pftrace")] + ".json", "w") as f:+ json.dump({"scenario": args.scenario, "run": run, "package": args.package,+ "launcher": launcher, "other_app": other, "setup": setup, "steps": steps,+ "tv": about, "recorded": time.strftime("%Y-%m-%dT%H:%M:%S")}, f, indent=1)+ print(f"{path}: {size} bytes")+ finally:+ if helpers:+ bench.restore_accessibility(_Shell(shell), args.package, helpers)+ finally:+ dev.close()+ print(f"next: tools/trace_report.py {args.out} (see tools/trace.md)")+++class _Shell:+ """What bench.py's accessibility helpers expect of a TV: a shell()."""++ def __init__(self, run):+ self.shell = lambda cmd, read_timeout_s=None: run(cmd)+++if __name__ == "__main__":+ main()diff --git a/tools/trace_report.py b/tools/trace_report.pynew file mode 100644index 000000000..b0a2c1f47--- /dev/null+++ b/tools/trace_report.py@@ -0,0 +1,281 @@+#!/usr/bin/env python3+"""The standard launcher numbers from traces recorded with tools/trace.py: per run, median and range.++ tools/trace_report.py traces/before one set of runs+ tools/trace_report.py traces/before --vs traces/after before against after, with the change+ tools/trace_report.py ... --markdown tables to paste into a pull request++TRACES are .pftrace files or folders of them. Needs the optional `perfetto` package+(tools/venv/bin/pip install -r tools/requirements-perf.txt). Its first run downloads Perfetto's query+engine; --engine PATH uses a trace_processor_shell you downloaded yourself. Read tools/trace.md first.++For a start (cold, coldsys, home and custom traces) it reports the time from the launcher starting+(bindApplication in a new process, else performStart) to its first frame drawn, the lifecycle steps+inside that, and the frames drawn and deadlines missed in the 1.5 s after. For nav traces it reports+frame times and missed deadlines over the whole recording.+"""+import argparse+import glob+import json+import os+import re+import statistics+import sys++PACKAGE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$")+WINDOW_NS = 1_500_000_000+MS = 1e6++START_METRICS = [("first frame", "start to first frame drawn (ms)"), ("bindApplication", "bindApplication (ms)"),+ ("activityStart", "onCreate (activityStart, ms)"), ("onStart", "onStart (performStart, ms)"),+ ("onResume", "onResume (activityResume, ms)"), ("first traversal", "first layout and draw (ms)"),+ ("frames", "frames drawn in 1.5 s"), ("missed", "frames that missed their deadline in 1.5 s")]+NAV_METRICS = [("frames", "frames drawn"), ("frame median", "frame time, median (ms)"),+ ("frame p90", "frame time, 90th percentile (ms)"), ("draw median", "RenderThread draw, median (ms)"),+ ("gpu median", "waiting for the GPU, median (ms)"), ("missed", "frames that missed their deadline")]+++def one(q, sql, default=None):+ rows = q(sql)+ if not rows:+ return default+ value = next(iter(rows[0].values()))+ return default if value is None else value+++def threads(q, package):+ """(upid, main thread utid, RenderThread utid) of the newest process named after the package."""+ upid = one(q, f"select upid from process where name = '{package}' order by upid desc limit 1")+ if upid is None:+ return None, None, None+ main = one(q, f"select utid from thread join process using(upid) where thread.upid = {upid} and thread.tid = process.pid")+ render = one(q, f"select utid from thread where upid = {upid} and name = 'RenderThread' order by utid limit 1")+ return upid, main, render+++def slices(utid, where, columns="s.ts, s.dur"):+ return (f"select {columns} from slice s join thread_track tt on s.track_id = tt.id "+ f"where tt.utid = {utid} and {where} order by s.ts")+++def start_metrics(q, package):+ """The numbers for a launcher start: cold, coldsys, home or a custom trace that brings Home up."""+ upid, main, render = threads(q, package)+ if main is None:+ return {}+ bind = q(slices(main, "s.name = 'bindApplication'"))+ start = q(slices(main, "s.name like 'performStart%'"))+ anchor = bind[0]["ts"] if bind else (start[0]["ts"] if start else None)+ if anchor is None:+ return {}+ resume = q(slices(main, f"s.name = 'activityResume' and s.ts >= {anchor}"))+ out = {}+ if bind:+ out["bindApplication"] = bind[0]["dur"] / MS+ created = q(slices(main, f"s.name = 'activityStart' and s.ts >= {anchor}"))+ if created:+ out["activityStart"] = created[0]["dur"] / MS+ if start:+ first_start = [s for s in start if s["ts"] >= anchor] or start+ out["onStart"] = first_start[0]["dur"] / MS+ if resume:+ out["onResume"] = resume[0]["dur"] / MS+ resumed = resume[0]["ts"] + resume[0]["dur"]+ traversal = q(slices(main, f"s.name = 'traversal' and s.ts >= {resumed}"))+ if traversal:+ t = traversal[0]+ out["first traversal"] = t["dur"] / MS+ end = t["ts"] + t["dur"]+ if render is not None:+ drawn = q(slices(render, f"s.name like 'DrawFrame%' and s.ts >= {t['ts']}"))+ if drawn:+ end = max(end, drawn[0]["ts"] + drawn[0]["dur"])+ out["first frame"] = (end - anchor) / MS+ if render is not None:+ out["frames"] = one(q, f"select count(*) from slice s join thread_track tt on s.track_id = tt.id "+ f"where tt.utid = {render} and s.name like 'DrawFrame%' "+ f"and s.ts >= {anchor} and s.ts < {anchor + WINDOW_NS}", 0)+ out["missed"] = one(q, f"select count(*) from actual_frame_timeline_slice where upid = {upid} "+ f"and jank_type like '%App Deadline Missed%' "+ f"and ts >= {anchor} and ts < {anchor + WINDOW_NS}", 0)+ return out+++def nav_metrics(q, package):+ """Frame numbers over a whole nav recording."""+ upid, main, render = threads(q, package)+ if upid is None:+ return {}+ frames = sorted(r["dur"] / MS for r in q(f"select dur from actual_frame_timeline_slice where upid = {upid}"))+ out = {"frames": len(frames)}+ if frames:+ out["frame median"] = statistics.median(frames)+ out["frame p90"] = frames[min(len(frames) - 1, int(0.9 * len(frames)))]+ if render is not None:+ draws = [r["dur"] / MS for r in q(slices(render, "s.name like 'DrawFrame%'", "s.dur"))]+ if draws:+ out["draw median"] = statistics.median(draws)+ waits = [r["dur"] / MS for r in q(f"select s.dur from slice s join thread_track tt on s.track_id = tt.id "+ f"join thread t using(utid) where t.upid = {upid} "+ f"and s.name like 'waiting for GPU completion%'")]+ if waits:+ out["gpu median"] = statistics.median(waits)+ out["missed"] = one(q, f"select count(*) from actual_frame_timeline_slice where upid = {upid} "+ f"and jank_type like '%App Deadline Missed%'", 0)+ return out+++def scenario_of(path):+ """The scenario trace.py wrote next to the trace, or the start of its file name."""+ sidecar = path[:-len(".pftrace")] + ".json" if path.endswith(".pftrace") else None+ if sidecar and os.path.exists(sidecar):+ try:+ with open(sidecar) as f:+ return json.load(f).get("scenario", "")+ except (OSError, ValueError):+ pass+ return os.path.basename(path).split("-")[0]+++def expand(items):+ paths = []+ for item in items:+ if os.path.isdir(item):+ paths += sorted(glob.glob(os.path.join(item, "*.pftrace")), key=_run_order)+ else:+ paths.append(item)+ return paths+++def _run_order(path):+ m = re.search(r"-(\d+)\.pftrace$", path)+ return (re.sub(r"-\d+\.pftrace$", "", path), int(m.group(1)) if m else 0)+++def opener(engine=None):+ """open(path) -> q(sql) returning rows as dicts, plus close(), using Perfetto's query engine."""+ try:+ from perfetto.trace_processor import TraceProcessor, TraceProcessorConfig+ except ImportError:+ sys.exit("trace_report.py needs the optional perfetto package: "+ "tools/venv/bin/pip install -r tools/requirements-perf.txt (see tools/trace.md)")++ def open_trace(path):+ tp = TraceProcessor(trace=path, config=TraceProcessorConfig(bin_path=engine))++ def q(sql):+ result = tp.query(sql)+ names = result.column_names+ return [dict(zip(names, (getattr(row, n) for n in names))) for row in result]+ return q, tp.close+ return open_trace+++def measure(paths, package, open_trace):+ """[(name, metrics)] for each trace, in run order."""+ out = []+ for path in paths:+ q, close = open_trace(path)+ try:+ metrics = nav_metrics(q, package) if scenario_of(path) == "nav" else start_metrics(q, package)+ finally:+ close()+ out.append((os.path.basename(path)[:-len(".pftrace")], metrics))+ return out+++def summary(values):+ values = [v for v in values if v is not None]+ if not values:+ return None, None, None+ return statistics.median(values), min(values), max(values)+++def fmt(value):+ if value is None:+ return "–"+ return f"{value:.0f}" if abs(value) >= 20 or float(value).is_integer() else f"{value:.1f}"+++def table(runs, names, markdown):+ """Metric rows, one column per run, then the median and range. A run more than twice the median is starred."""+ head = ["", *[r[0] for r in runs], "median", "range"]+ rows = []+ for key, label in names:+ values = [r[1].get(key) for r in runs]+ if all(v is None for v in values):+ continue+ med, lo, hi = summary(values)+ cells = [fmt(v) + ("*" if v is not None and med and key == "first frame" and v > 2 * med else "") for v in values]+ rows.append([label, *cells, fmt(med), f"{fmt(lo)}–{fmt(hi)}"])+ return render(head, rows, markdown)+++def compare(before, after, names, markdown):+ rows = []+ for key, label in names:+ b = summary([r[1].get(key) for r in before])[0]+ a = summary([r[1].get(key) for r in after])[0]+ if b is None and a is None:+ continue+ change = f"{100 * (a - b) / b:+.0f}%" if a is not None and b else "–"+ rows.append([label, fmt(b), fmt(a), change])+ return render(["", "before (median)", "after (median)", "change"], rows, markdown)+++def render(head, rows, markdown):+ if markdown:+ lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]+ return "\n".join(lines + ["| " + " | ".join(r) + " |" for r in rows])+ widths = [max(len(str(r[i])) for r in [head] + rows) for i in range(len(head))]+ return "\n".join(" ".join(str(c).ljust(w) for c, w in zip(r, widths)).rstrip() for r in [head] + rows)+++def report(before, after, markdown, nav):+ """The tables for one set of runs, or for two with the change in the medians."""+ names = NAV_METRICS if nav else START_METRICS+ parts = [("Before" if after else "Runs") + f" ({len(before)}):", table(before, names, markdown)]+ if after:+ parts += ["", f"After ({len(after)}):", table(after, names, markdown), "",+ "Change in the median:", compare(before, after, names, markdown)]+ if _has_outlier(before) or (after and _has_outlier(after)):+ parts += ["", "* more than twice the median: often memory pressure on the TV (tools/trace.md). "+ "Report it rather than dropping it."]+ return "\n".join(parts)+++def _has_outlier(runs):+ med = summary([m.get("first frame") for _, m in runs])[0]+ return bool(med) and any((m.get("first frame") or 0) > 2 * med for _, m in runs)+++def parse(argv):+ p = argparse.ArgumentParser(description="Launcher numbers from tools/trace.py traces. See tools/trace.md.")+ p.add_argument("traces", nargs="+", help=".pftrace files or folders of them")+ p.add_argument("--vs", nargs="+", metavar="TRACES", help="the traces to compare against the first set")+ p.add_argument("--package", default="com.gathin.tvhome", help="the launcher's package (default com.gathin.tvhome)")+ p.add_argument("--engine", metavar="PATH", help="a trace_processor_shell to use instead of downloading one")+ p.add_argument("--markdown", action="store_true", help="print Markdown tables")+ args = p.parse_args(argv)+ if not PACKAGE.match(args.package):+ p.error(f"not a package name: {args.package!r}")+ return args+++def main(argv=None):+ args = parse(sys.argv[1:] if argv is None else argv)+ sets = [expand(args.traces)] + ([expand(args.vs)] if args.vs else [])+ for paths in sets:+ if not paths:+ sys.exit("no .pftrace files found; record some with tools/trace.py")+ missing = [p for p in paths if not os.path.isfile(p)]+ if missing:+ sys.exit("not a file: " + ", ".join(missing))+ open_trace = opener(args.engine)+ measured = [measure(paths, args.package, open_trace) for paths in sets]+ nav = all(scenario_of(p) == "nav" for p in sets[0])+ print(report(measured[0], measured[1] if len(measured) > 1 else None, args.markdown, nav))+++if __name__ == "__main__":+ main()