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: flamechart.py, a before/after flame chart from tools/trace.py traces
sim21282c6f96de
diff --git a/AGENTS.md b/AGENTS.mdindex 9dfcba96c..f8edbadbf 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`, `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. |+| `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`), `flamechart.py` (guide: `tools/flamechart.md`), `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 8981a502e..76ddb2e34 100644--- a/README.md+++ b/README.md@@ -376,6 +376,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`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/flamechart.py`](tools/flamechart.py) | Draws a before/after flame chart from those traces, for a pull request: one lane per thread on a shared time scale, the work a change targets in magenta with its total. Optional, like the trace tools. [Guide](tools/flamechart.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 470 KB), installs it, switches Home, and rolls back if Home does not land on it. |diff --git a/tests/test_flamechart.py b/tests/test_flamechart.pynew file mode 100644index 000000000..eb6e92a5a--- /dev/null+++ b/tests/test_flamechart.py@@ -0,0 +1,129 @@+"""tools/flamechart.py: what it highlights, which run it draws, and the window it draws.++A flame chart in a pull request is only honest if the magenta total counts each piece of work once+(a highlighted slice's children are inside it, not extra), if a folder of runs is drawn by its+median run rather than its best, and if both panels share one time scale. The trace queries run+against an in-memory SQLite table laid out like a trace, as in test_trace_report.py, so these need+neither Perfetto's query engine nor a TV. Drawing needs Pillow, so that test skips without it.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import importlib.util+import os+from pathlib import Path+import re+import sqlite3+import sys+import tempfile+import unittest+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "tools"))+spec = importlib.util.spec_from_file_location("cyt_flamechart", ROOT / "tools" / "flamechart.py")+flamechart = importlib.util.module_from_spec(spec)+spec.loader.exec_module(flamechart)++PKG = "com.gathin.tvhome"+MS = 1_000_000+++def fake_trace():+ """The launcher brought to the front at 1000 ms: performStart, onResume with nested work, a traversal, a frame."""+ 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, depth integer, name text,+ track_id integer, parent_id integer);+ create table actual_frame_timeline_slice (ts integer, dur integer, upid integer, jank_type text);+ insert into process values (2, 100, 'com.gathin.tvhome');+ insert into thread values (1, 2, 100, 'com.gathin.tvhome'), (2, 2, 101, 'RenderThread');+ insert into thread_track values (10, 1), (20, 2);+ """)+ rows = [(1, 1000, 5, 0, "performStart:x", 10, None), (2, 1005, 30, 0, "activityResume", 10, None),+ (3, 1010, 10, 1, "inflate", 10, 2), (4, 1040, 20, 0, "traversal", 10, None),+ (5, 1050, 4, 1, "RV OnBindView", 10, 4), (6, 1055, 10, 0, "DrawFrames 1", 20, None)]+ db.executemany("insert into slice values (?, ?, ?, ?, ?, ?, ?)",+ [(i, ts * MS, dur * MS, depth, name, track, parent) for i, ts, dur, depth, name, track, parent in rows])+ return lambda sql: [dict(r) for r in db.execute(sql)]+++class HighlightTest(unittest.TestCase):+ def test_nested_work_is_counted_once_and_drawn_magenta(self):+ q = fake_trace()+ rows = flamechart.lanes(q, PKG, ["main"], 0, 2000 * MS)[0][1]+ total, hit = flamechart.highlighted(rows, re.compile("^(activityResume|RV OnBindView)$"), 0, 2000 * MS)+ self.assertEqual(total, 34) # onResume 30 + binding 4; inflate inside onResume adds nothing+ self.assertEqual(hit, {2, 3, 5})++ def test_only_the_part_inside_the_window_counts(self):+ rows = flamechart.lanes(fake_trace(), PKG, ["main"], 0, 2000 * MS)[0][1]+ total, _ = flamechart.highlighted(rows, re.compile("^activityResume$"), 1020 * MS, 2000 * MS)+ self.assertEqual(total, 15)+++class WindowTest(unittest.TestCase):+ def test_first_frame_window_spans_start_to_frame_drawn(self):+ t0, t1 = flamechart.window(fake_trace(), PKG, "first-frame", nav=False)+ self.assertEqual((t0, t1), (1000 * MS - 500_000, 1065 * MS + 500_000))++ def test_start_window_has_a_fixed_length(self):+ t0, t1 = flamechart.window(fake_trace(), PKG, "start:1500", nav=False)+ self.assertEqual(t1 - (t0 + 500_000), 1500 * MS)++ def test_all_and_nav_take_the_whole_process(self):+ self.assertEqual(flamechart.window(fake_trace(), PKG, "all", nav=False), (1000 * MS, 1065 * MS))+ self.assertEqual(flamechart.window(fake_trace(), PKG, "first-frame", nav=True), (1000 * MS, 1065 * MS))++ def test_a_trace_without_the_launcher_is_refused(self):+ with self.assertRaises(ValueError):+ flamechart.window(fake_trace(), "com.example.other", "first-frame", nav=False)++ def test_lanes_by_name_and_a_missing_thread_stays_empty(self):+ names = [label for label, _ in flamechart.lanes(fake_trace(), PKG, ["main", "RenderThread", "nope"], 0, 2000 * MS)]+ self.assertEqual(names, ["main thread", "RenderThread", "nope"])+++class MedianRunTest(unittest.TestCase):+ def test_the_median_run_is_drawn_not_the_best(self):+ scores = {"a": 90, "b": 300, "c": 80, "d": 95, "e": 85}+ measure = lambda paths, package, open_trace: [(p, {"first frame": scores[p]}) for p in paths]+ original = flamechart.trace_report.measure+ flamechart.trace_report.measure = measure+ try:+ self.assertEqual(flamechart.median_run(list("abcde"), PKG, None), "a")+ self.assertEqual(flamechart.median_run(list("abce"), PKG, None), "e") # 80 85 90 300: the lower middle+ finally:+ flamechart.trace_report.measure = original+++class ArgumentTest(unittest.TestCase):+ def test_bad_window_regex_and_threads_are_refused(self):+ for argv in (["a", "--out", "x.png", "--window", "soon"], ["a", "--out", "x.png", "--highlight", "("],+ ["a", "--out", "x.png", "--threads", "main;rm"]):+ with self.subTest(argv=argv), self.assertRaises(SystemExit):+ with open(os.devnull, "w") as null, mock.patch("sys.stderr", null):+ flamechart.parse(argv)++[email protected](importlib.util.find_spec("PIL"), "drawing needs Pillow (tools/requirements-perf.txt)")+class DrawTest(unittest.TestCase):+ def test_draws_both_panels_on_one_scale_with_magenta(self):+ q = fake_trace()+ panel = lambda label, t1: {"label": label, "note": "", "t0": 1000 * MS, "t1": t1,+ "lanes": flamechart.lanes(q, PKG, ["main", "RenderThread"], 1000 * MS, t1)}+ with tempfile.TemporaryDirectory() as tmp:+ out = os.path.join(tmp, "chart.png")+ size = flamechart.draw([panel("Before", 1065 * MS), panel("After", 1030 * MS)],+ re.compile("^activityResume$"), "t", "s", out, width=1000)+ from PIL import Image+ im = Image.open(out).convert("RGB")+ self.assertEqual(im.size, size)+ self.assertIn(flamechart.MAGENTA, set(im.getdata()))+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/flamechart.md b/tools/flamechart.mdnew file mode 100644index 000000000..b550c7ce4--- /dev/null+++ b/tools/flamechart.md@@ -0,0 +1,33 @@+# tools/flamechart.py++Draw a before/after flame chart PNG from `tools/trace.py` traces: one lane per thread, both panels on one+time scale, the work your change targets in magenta with its total. Use it to show *where* a difference+from `tools/trace_report.py` comes from; attach the report's table next to it.++```bash+tools/venv/bin/pip install -r tools/requirements-perf.txt # adds Pillow+tools/venv/bin/python tools/flamechart.py traces/before traces/after \+ --highlight '^(activityResume|RV OnBindView)$' \+ --title 'Back to Home: Home press to first frame' \+ --subtitle 'TCL C755, Google TV 14 · magenta: onResume and tile binding' \+ --out chart.png+```++| Option | Default | Notes |+|---|---|---|+| `TRACE ...` | | Before, then after (up to 4). A folder draws its median run (by time to first frame, or median frame time for `nav`), named in the panel. |+| `--highlight REGEX` | `^(activityResume\|RV OnBindView)$` | Slice names to draw magenta and total. Children of a match count once. |+| `--window` | `first-frame` | `first-frame`: launcher start to first frame drawn. `start:MS`: a fixed span from the start. `all`: the whole recording (always for `nav`). |+| `--threads` | `main,RenderThread` | Lanes, by thread name in the launcher's process. |++A Home change usually needs two charts:+- **The start:** the defaults, with `--highlight` set to the slices you removed.+- **The frames after it:** `--window start:1500 --threads RenderThread --highlight '^DrawFrame'`.++## Rules++- **Choose `--highlight` before you look.** Name the slices your change should remove, then draw. A regex+ fitted to whatever shrank proves nothing.+- **Pass folders, not single runs.** The tool picks the median run. If you pass single traces, say why.+- **Magenta is main and render thread time only.** Work moved to another thread or to the GPU isn't gone:+ add that thread as a lane, or use the `nav` GPU numbers.diff --git a/tools/flamechart.py b/tools/flamechart.pynew file mode 100644index 000000000..281a0feca--- /dev/null+++ b/tools/flamechart.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""A before/after flame chart, as a PNG for a pull request, from traces recorded with tools/trace.py.++One panel per trace, one lane per thread, every slice drawn on the same time scale, so the faster run is+visibly shorter. Slices whose name matches --highlight are drawn in magenta, and their time is summed+(nested slices once), with the change against the first panel.++ tools/flamechart.py traces/before traces/after --highlight '^(activityResume|RV OnBindView)$' \\+ --title 'Back to Home: Home press to first frame' --out chart.png++BEFORE and AFTER are .pftrace files or folders; for a folder the median run is drawn (by the time to the+first frame, or for nav traces by the median frame time). Needs the optional packages in+tools/requirements-perf.txt. Read tools/flamechart.md first.+"""+import argparse+import colorsys+import hashlib+import os+import re+import statistics+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import trace_report # noqa: E402 the same trace queries the report uses++MAGENTA = (214, 51, 132)+ROW = 16+LEFT = 150+MS = 1e6+++def window(q, package, spec, nav):+ """(t0, t1) in ns: first-frame (launcher start to first frame drawn), start:MS, or all."""+ upid, main, _ = trace_report.threads(q, package)+ if main is None:+ raise ValueError(f"no {package} process in the trace")+ if spec == "all" or nav:+ row = q(f"select min(s.ts) as t0, max(s.ts + s.dur) as t1 from slice s join thread_track tt on s.track_id = tt.id "+ f"join thread t using(utid) where t.upid = {upid}")[0]+ return row["t0"], row["t1"]+ anchor, end = trace_report.start_window(q, package)+ if anchor is None:+ raise ValueError("no launcher start in the trace (bindApplication or performStart); try --window all")+ if spec.startswith("start:"):+ return anchor - 500_000, anchor + int(float(spec[6:]) * MS)+ if end is None:+ raise ValueError("no first frame after the start; try --window start:1500")+ return anchor - 500_000, end + 500_000+++def lanes(q, package, names, t0, t1):+ """[(label, slices)] for each lane: main, RenderThread, or any thread name in the launcher's process."""+ upid, main, render = trace_report.threads(q, package)+ out = []+ for name in names:+ if name == "main":+ utid = main+ elif name == "RenderThread":+ utid = render+ else:+ rows = q(f"select utid from thread where upid = {upid} and name = '{name}' order by utid limit 1")+ utid = rows[0]["utid"] if rows else None+ if utid is None:+ out.append((name, []))+ continue+ rows = q(f"select s.id, s.ts, s.dur, s.depth, s.name, s.parent_id from slice s join thread_track tt "+ f"on s.track_id = tt.id where tt.utid = {utid} and s.ts < {t1} and s.ts + s.dur > {t0} "+ f"and s.dur > 0 order by s.ts")+ out.append(("main thread" if name == "main" else name, rows))+ return out+++def highlighted(rows, rx, t0, t1):+ """(ms, ids): time inside the window of slices matching rx, a match's children counted once; and the ids drawn magenta."""+ hit, total = set(), 0+ for s in sorted(rows, key=lambda r: (r["depth"], r["ts"])):+ if s["parent_id"] in hit:+ hit.add(s["id"])+ elif rx.search(s["name"]):+ hit.add(s["id"])+ total += min(s["ts"] + s["dur"], t1) - max(s["ts"], t0)+ return total / MS, hit+++def median_run(paths, package, open_trace):+ """The run whose time to the first frame (or nav frame time) is the median of the set."""+ if len(paths) == 1:+ return paths[0]+ scored = []+ for path, metrics in zip(paths, (m for _, m in trace_report.measure(paths, package, open_trace))):+ score = metrics.get("first frame", metrics.get("frame median"))+ if score is not None:+ scored.append((score, path))+ if not scored:+ return paths[0]+ scored.sort()+ return scored[(len(scored) - 1) // 2][1]+++def colour(name):+ """A warm, muted colour per slice name, numbers ignored, so the same work looks the same in both panels."""+ h = int(hashlib.md5(re.sub(r"\d+", "", name).encode()).hexdigest()[:6], 16) / 0xFFFFFF+ r, g, b = colorsys.hls_to_rgb(0.08 + 0.12 * h, 0.72, 0.55)+ return int(r * 255), int(g * 255), int(b * 255)+++def lane_height(rows):+ return (max((r["depth"] for r in rows), default=0) + 1) * ROW+++def tick_step(span_ms):+ """Axis ticks every 10 ms on a short chart, up to every second on a long one."""+ for limit, step in ((120, 10), (300, 25), (700, 50), (1600, 100), (4000, 250)):+ if span_ms <= limit:+ return step+ return 1000+++def draw(panels, rx, title, subtitle, out, width=1600):+ """panels: [{label, note, t0, t1, lanes}]. Writes the PNG and returns its size."""+ from PIL import Image, ImageDraw, ImageFont++ def font(size):+ return ImageFont.load_default(size=size)+ small, normal, bold, big = font(11), font(13), font(15), font(19)+ span = max((p["t1"] - p["t0"]) / MS for p in panels)+ plot = width - LEFT - 95+ heights = [52 + sum(lane_height(rows) + 26 for _, rows in p["lanes"]) + 10 for p in panels]+ im = Image.new("RGB", (width, 90 + sum(heights) + 30), "white")+ d = ImageDraw.Draw(im)+ d.text((20, 14), title, fill="black", font=big)+ d.text((20, 42), subtitle, fill="#555", font=normal)+ d.rectangle([width - 430, 18, width - 416, 32], fill=MAGENTA)+ d.text((width - 410, 18), "highlighted: " + rx.pattern[:52], fill="#333", font=small)+ totals = [sum(highlighted(rows, rx, p["t0"], p["t1"])[0] for _, rows in p["lanes"]) for p in panels]+ y = 80+ for i, p in enumerate(panels):+ dur = (p["t1"] - p["t0"]) / MS+ d.text((20, y), p["label"], fill="black", font=bold)+ info = f"{dur:.1f} ms shown · highlighted {totals[i]:.1f} ms" + (f" · {p['note']}" if p.get("note") else "")+ d.text((20 + d.textlength(p["label"], font=bold) + 14, y + 1), info, fill="#444", font=normal)+ if i and totals[0] > 0:+ change = f"highlighted {totals[i] - totals[0]:+.1f} ms ({100 * (totals[i] - totals[0]) / totals[0]:+.0f}%) " \+ f"vs {panels[0]['label'].lower()}"+ d.text((width - 20 - d.textlength(change, font=bold), y), change, fill=MAGENTA, font=bold)+ y += 26+ x_end = LEFT + plot * dur / span+ d.line([LEFT, y + 6, x_end, y + 6], fill="#999")+ step, t = tick_step(span), 0+ while t <= dur + 1e-6:+ x = LEFT + plot * t / span+ d.line([x, y + 2, x, y + 10], fill="#999")+ d.text((x + 2, y - 8), f"{t:g}", fill="#777", font=small)+ t += step+ d.text((x_end + 6, y), f"{dur:.0f} ms", fill="#222", font=bold)+ y += 18+ for label, rows in p["lanes"]:+ h = lane_height(rows)+ d.text((20, y + 2), label, fill="#222", font=normal)+ d.rectangle([LEFT, y, x_end, y + h], fill="#f6f6f6")+ _, hit = highlighted(rows, rx, p["t0"], p["t1"])+ for s in rows:+ a, b = max(s["ts"], p["t0"]), min(s["ts"] + s["dur"], p["t1"])+ x0 = LEFT + plot * (a - p["t0"]) / MS / span+ x1 = LEFT + plot * (b - p["t0"]) / MS / span+ if x1 - x0 < 0.6:+ continue+ yy = y + s["depth"] * ROW+ d.rectangle([x0, yy, max(x0 + 1, x1 - 1), yy + ROW - 2], fill=MAGENTA if s["id"] in hit else colour(s["name"]))+ if x1 - x0 > 46:+ text = s["name"]+ while text and d.textlength(text, font=small) > x1 - x0 - 6:+ text = text[:-2]+ d.text((x0 + 3, yy + 1), text, fill="white" if s["id"] in hit else "#222", font=small)+ y += h + 26+ y += 10+ im.save(out)+ return im.size+++def parse(argv):+ p = argparse.ArgumentParser(description="Before/after flame chart PNG from tools/trace.py traces. See tools/flamechart.md.")+ p.add_argument("traces", nargs="+", metavar="TRACE", help="before, then after: .pftrace files or folders (median run)")+ p.add_argument("--out", required=True, help="the PNG to write")+ p.add_argument("--highlight", default="^(activityResume|RV OnBindView)$",+ help="regex of slice names to draw in magenta and total (default: onResume and tile binding)")+ p.add_argument("--window", default="first-frame",+ help="first-frame (start to first frame drawn, default), start:MS, or all")+ p.add_argument("--threads", default="main,RenderThread", help="lanes, comma-separated (default main,RenderThread)")+ p.add_argument("--labels", default="Before,After", help="panel labels, comma-separated")+ p.add_argument("--title", default="Launcher: start to first frame", help="the chart's title")+ p.add_argument("--subtitle", default="", help="a line under the title: the TV, the build, what magenta means")+ p.add_argument("--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("--width", type=int, default=1600)+ args = p.parse_args(argv)+ if len(args.traces) > 4:+ p.error("at most four traces (panels)")+ if not re.fullmatch(r"first-frame|all|start:\d+(\.\d+)?", args.window):+ p.error("--window is first-frame, all or start:MS")+ if not trace_report.PACKAGE.match(args.package):+ p.error(f"not a package name: {args.package!r}")+ try:+ args.rx = re.compile(args.highlight)+ except re.error as e:+ p.error(f"--highlight is not a regex: {e}")+ names = [n.strip() for n in args.threads.split(",") if n.strip()]+ if not names or not all(re.fullmatch(r"[A-Za-z0-9 _.:#-]+", n) for n in names):+ p.error("--threads takes thread names such as main,RenderThread")+ args.thread_names = names+ return args+++def main(argv=None):+ args = parse(sys.argv[1:] if argv is None else argv)+ try:+ import PIL # noqa: F401+ except ImportError:+ sys.exit("flamechart.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")+ open_trace = trace_report.opener(args.engine)+ labels = [l.strip() for l in args.labels.split(",")]+ panels = []+ for i, item in enumerate(args.traces):+ paths = trace_report.expand([item])+ if not paths:+ sys.exit(f"no .pftrace files in {item}")+ path = median_run(paths, args.package, open_trace)+ nav = trace_report.scenario_of(path) == "nav"+ q, close = open_trace(path)+ try:+ t0, t1 = window(q, args.package, args.window, nav)+ data = lanes(q, args.package, args.thread_names, t0, t1)+ except ValueError as e:+ sys.exit(f"{path}: {e}")+ finally:+ close()+ note = f"median of {len(paths)} runs ({os.path.basename(path)})" if len(paths) > 1 else os.path.basename(path)+ panels.append({"label": labels[i] if i < len(labels) else f"Run {i + 1}", "note": note,+ "t0": t0, "t1": t1, "lanes": data})+ size = draw(panels, args.rx, args.title, args.subtitle, args.out, args.width)+ print(f"{args.out}: {size[0]}x{size[1]}")+++if __name__ == "__main__":+ main()diff --git a/tools/requirements-perf.txt b/tools/requirements-perf.txtindex 60056538b..1fbf21aa9 100644--- a/tools/requirements-perf.txt+++ b/tools/requirements-perf.txt@@ -1,3 +1,4 @@-# 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.+# Optional: only for the performance tools (tools/trace_report.py, tools/flamechart.py). Not needed to clean a TV.+# tools/venv/bin/pip install -r tools/requirements-perf.txt See tools/trace.md and tools/flamechart.md.perfetto==0.58.2+pillow==11.3.0diff --git a/tools/trace.md b/tools/trace.mdindex 8720735b9..e84788c92 100644--- a/tools/trace.md+++ b/tools/trace.md@@ -1,7 +1,8 @@# tools/trace.py and tools/trace_report.pyRecord 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.+only (key latency, jank, cold start, PSS), use `tools/bench.py` instead: it needs no extra install. To draw the+result for a pull request, use `tools/flamechart.py` ([guide](flamechart.md)).## Setupdiff --git a/tools/trace_report.py b/tools/trace_report.pyindex b0a2c1f47..0b1d1c31f 100644--- a/tools/trace_report.py+++ b/tools/trace_report.py@@ -60,14 +60,25 @@ def slices(utid, where, columns="s.ts, s.dur"):def start_metrics(q, package):"""The numbers for a launcher start: cold, coldsys, home or a custom trace that brings Home up."""+ return _start(q, package)[0]+++def start_window(q, package):+ """(start, first frame drawn) in ns for a launcher start; either is None when the trace lacks it."""+ return _start(q, package)[1:]+++def _start(q, package):+ """(metrics, start ns, first frame drawn ns) for a launcher start."""upid, main, render = threads(q, package)if main is None:- return {}+ return {}, None, Nonebind = 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 {}+ return {}, None, None+ end = Noneresume = q(slices(main, f"s.name = 'activityResume' and s.ts >= {anchor}"))out = {}if bind:@@ -98,7 +109,7 @@ def start_metrics(q, package):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+ return out, anchor, enddef nav_metrics(q, package):