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: screendiff.py, before/after screenshots compared pixel by pixel, private details blurred
sim7de6947befc9
diff --git a/AGENTS.md b/AGENTS.mdindex c7da4f679..48ff99573 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -72,7 +72,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`), `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. |+| `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`), `screendiff.py` (guide: `tools/screendiff.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 1c318c310..bcd4280dc 100644--- a/README.md+++ b/README.md@@ -384,6 +384,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`tools/bench.py`](tools/bench.py) | Measures the launcher that answers HOME: key latency, how far the focus moved, janky frames, cold start, return to Home, and the idle CPU and PSS it costs. Changes nothing on the TV and writes the raw per-key numbers to JSON; no extra install. || [`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/screendiff.py`](tools/screendiff.py) | Compares a before and an after screenshot pixel by pixel, leaving out the clock or anything you mask, and writes the pair with your Wi-Fi name blurred. Optional, like the trace tools. [Guide](tools/screendiff.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 471 KB), installs it, switches Home, and rolls back if Home does not land on it. |diff --git a/docs/workflows/perf-ab.md b/docs/workflows/perf-ab.mdindex 903ac0155..bab51c9fa 100644--- a/docs/workflows/perf-ab.md+++ b/docs/workflows/perf-ab.md@@ -3,8 +3,9 @@**When to use this:** you changed the launcher to make it faster or lighter, and the pull request has toshow by how much, and where the time went. This is the method #666 used.-Tools: [`tools/trace.py` and `tools/trace_report.py`](../../tools/trace.md), then-[`tools/flamechart.py`](../../tools/flamechart.md). Install them once:+Tools: [`tools/trace.py` and `tools/trace_report.py`](../../tools/trace.md),+[`tools/flamechart.py`](../../tools/flamechart.md) and [`tools/screendiff.py`](../../tools/screendiff.md).+Install them once:```bashtools/venv/bin/pip install -r tools/requirements-perf.txt@@ -18,8 +19,9 @@ Copy this checklist into your notes and tick it off:- [ ] 3. Trace your build, 5 runs- [ ] 4. Report; if the change isn't there, go back to your code- [ ] 5. Draw the flame charts-- [ ] 6. Check the behaviour your change could break-- [ ] 7. Write it up+- [ ] 6. Screenshots identical, or the visual change described+- [ ] 7. Check the behaviour your change could break+- [ ] 8. Write it up```## 1. Decide before you measure@@ -65,7 +67,19 @@ tools/venv/bin/python tools/flamechart.py traces/before traces/after \--window start:1500 --threads RenderThread --highlight '^DrawFrame' --out frames.png```-## 6. Behaviour+## 6. Screenshots++Take the same screenshot on both builds, then compare:++```bash+tools/venv/bin/python -I tools/tv.py --screenshot shots/before.png HOME DPAD_RIGHT # each build+tools/venv/bin/python tools/screendiff.py shots/before.png shots/after.png \+ --mask <clock box> --blur <network name box> --out shots/before-after.png+```++`identical` backs "no visible change". If it says `different`, find out why before posting.++## 7. BehaviourOn the TV, check what your change could break, and note what you saw. For the return to Home, forexample:@@ -73,10 +87,11 @@ example:- focus comes back to the tile you left from;- Home on Home goes to the first tile.-## 7. The pull request+## 8. The pull request- **Tested on:** the TV, Android version and firmware.- **The tables:** `trace_report.py --markdown` before, after and the change, with outliers named.- **The charts:** each with its `--highlight` stated.+- **The screenshots:** the pair from `screendiff.py` and its result.- **The behaviour checks:** what you checked and what you saw.-- **Leave out** `traces/`: the files are large and hold your TV's process list.+- **Leave out** `traces/` and raw screenshots: they're large and hold your TV's details.diff --git a/tests/test_screendiff.py b/tests/test_screendiff.pynew file mode 100644index 000000000..2249b19f2--- /dev/null+++ b/tests/test_screendiff.py@@ -0,0 +1,103 @@+"""tools/screendiff.py: "no visible change" has to mean no pixel changed outside the masked regions.++A performance PR claims Home looks the same before and after. The comparison must leave out only+what the person masked (the clock moves on), count every other pixel that changed, and say where;+the picture it writes must hide what the person blurred (the Wi-Fi name) in both screenshots. Box+arguments are checked before anything is read. The image tests need Pillow, which CI does not+install (it is optional, in tools/requirements-perf.txt), so they skip without it.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import argparse+import contextlib+import importlib.util+import io+import os+from pathlib import Path+import tempfile+import unittest++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("cyt_screendiff", ROOT / "tools" / "screendiff.py")+screendiff = importlib.util.module_from_spec(spec)+spec.loader.exec_module(screendiff)+HAVE_PIL = importlib.util.find_spec("PIL") is not None+++class BoxTest(unittest.TestCase):+ def test_a_box_is_four_ordered_numbers(self):+ self.assertEqual(screendiff.box("90,40,900,220"), (90, 40, 900, 220))+ for bad in ("1,2,3", "a,b,c,d", "10,10,5,20", "10,10,20,10"):+ with self.subTest(bad=bad), self.assertRaises(argparse.ArgumentTypeError):+ screendiff.box(bad)++ def test_bad_options_are_usage_errors(self):+ for argv in (["a", "b", "--scale", "2"], ["a", "b", "--labels", "one"], ["a", "b", "--threshold", "300"]):+ with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()), \+ self.assertRaises(SystemExit) as caught:+ screendiff.parse(argv)+ self.assertEqual(caught.exception.code, 2)++[email protected](HAVE_PIL, "needs Pillow (tools/requirements-perf.txt)")+class CompareTest(unittest.TestCase):+ def setUp(self):+ from PIL import Image, ImageDraw+ self.Image, self.ImageDraw = Image, ImageDraw+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)++ def shot(self, name, clock="12:00", tile=(30, 30, 30), noise=0):+ """A 200x100 'Home': a clock at the top left, a tile at the bottom right."""+ im = self.Image.new("RGB", (200, 100), (10 + noise, 10, 10))+ draw = self.ImageDraw.Draw(im)+ draw.text((5, 5), clock, fill="white")+ draw.rectangle([150, 60, 190, 90], fill=tile)+ path = os.path.join(self.tmp.name, name)+ im.save(path)+ return path++ def run_tool(self, argv):+ with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:+ code = screendiff.main(argv)+ return code, out.getvalue() + err.getvalue()++ def test_a_masked_clock_is_left_out(self):+ a, b = self.shot("a.png", "12:00"), self.shot("b.png", "12:01")+ self.assertEqual(self.run_tool([a, b])[0], 1)+ code, text = self.run_tool([a, b, "--mask", "0,0,60,20"])+ self.assertEqual(code, 0)+ self.assertIn("identical (1 region masked)", text)++ def test_a_change_outside_the_mask_is_found_and_located(self):+ a, b = self.shot("a.png"), self.shot("b.png", tile=(200, 30, 30))+ code, text = self.run_tool([a, b, "--mask", "0,0,60,20"])+ self.assertEqual(code, 1)+ self.assertIn("inside 150,60,191,91", text)++ def test_compression_noise_under_the_threshold_is_ignored(self):+ a, b = self.shot("a.png"), self.shot("b.png", noise=3)+ self.assertEqual(self.run_tool([a, b])[0], 0)+ self.assertEqual(self.run_tool([a, b, "--threshold", "1"])[0], 1)++ def test_size_mismatch_and_boxes_outside_the_picture_are_errors(self):+ a = self.shot("a.png")+ small = os.path.join(self.tmp.name, "small.png")+ self.Image.new("RGB", (100, 50)).save(small)+ self.assertEqual(self.run_tool([a, small])[0], 2)+ self.assertEqual(self.run_tool([a, a, "--blur", "0,0,300,10"])[0], 2)++ def test_the_pair_blurs_the_same_region_in_both(self):+ a, b = self.shot("a.png", "SECRET"), self.shot("b.png", "SECRET")+ out = os.path.join(self.tmp.name, "pair.png")+ self.run_tool([a, b, "--blur", "0,0,60,20", "--out", out, "--scale", "1"])+ pair = self.Image.open(out).convert("RGB")+ self.assertEqual(pair.size, (430, 160))+ original = self.Image.open(a).convert("RGB").crop((0, 0, 60, 20))+ for left in (0, 230):+ blurred = pair.crop((left, 60, left + 60, 80))+ self.assertNotEqual(list(blurred.getdata()), list(original.getdata()))+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/requirements-perf.txt b/tools/requirements-perf.txtindex 1fbf21aa9..dbea5e0c3 100644--- a/tools/requirements-perf.txt+++ b/tools/requirements-perf.txt@@ -1,4 +1,4 @@-# 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.+# Optional: only for the performance tools (tools/trace_report.py, tools/flamechart.py, tools/screendiff.py). Not needed to clean a TV.+# tools/venv/bin/pip install -r tools/requirements-perf.txt See tools/trace.md.perfetto==0.58.2pillow==11.3.0diff --git a/tools/screendiff.md b/tools/screendiff.mdnew file mode 100644index 000000000..931652021--- /dev/null+++ b/tools/screendiff.md@@ -0,0 +1,46 @@+# tools/screendiff.py++Check that a before and an after screenshot are identical outside the regions you mask, and write the pair+side by side with private details blurred. Every performance PR claims "no visible change"; this proves it.++```bash+tools/venv/bin/pip install -r tools/requirements-perf.txt # Pillow+tools/venv/bin/python tools/screendiff.py shots/before.png shots/after.png \+ --mask 90,40,900,220 --blur 1265,125,1525,197 --out shots/before-after.png+```++| Exit status | Printed | Meaning |+|---|---|---|+| 0 | `identical (1 region masked): ...` | No pixel outside the masks differs by more than 8 |+| 1 | `different: N pixels differ ..., inside x0,y0,x1,y1` | Find out why before posting |+| 2 | an error | Different sizes, a box outside the picture, an unreadable file |++| Option | Notes |+|---|---|+| `--mask x0,y0,x1,y1` | Left out of the comparison. Repeatable. Only for what changes by itself: clock, greeting, stats line, wallpaper caption. |+| `--blur x0,y0,x1,y1` | Pixelated in both screenshots of the pair. Repeatable. For the Wi-Fi name, account pictures. It doesn't affect the comparison. |+| `--out PNG` | The labelled pair, at `--scale` (default 0.5). |+| `--diff PNG` | The differing pixels, white on black. |+| `--threshold N` | Channel difference to ignore (default 8, compression noise). |++## Boxes++Boxes are `x0,y0,x1,y1` in the screenshot's pixels. On a 1080p TV with the default layout:+- **Greeting, clock and date:** `90,40,900,220`.+- **Network name:** about `1265,125,1525,197`.++The top bar moves with config, and the Hebrew layout mirrors it. Read the Wi-Fi pill's bounds on your TV:++```bash+tools/venv/bin/python -I tools/tv.py 'uiautomator dump /data/local/tmp/ui.xml >/dev/null; grep -o "id/btnWifi\"[^>]*bounds=\"[^\"]*\"" /data/local/tmp/ui.xml; rm /data/local/tmp/ui.xml'+```++## Rules++- **Take both screenshots the same way.** Same key presses, same wait, same theme and wallpaper:+ `tools/tv.py --screenshot shots/before.png HOME DPAD_RIGHT`.+- **Never mask a region your change touches.**+- **Don't raise `--threshold` to make a difference go away.** If something did change, say what in the PR.+- **Compare Home, not Live TV, HDMI or Netflix.** Those capture as empty on most TVs.++The whole before/after method for a pull request is in [`docs/workflows/perf-ab.md`](../docs/workflows/perf-ab.md).diff --git a/tools/screendiff.py b/tools/screendiff.pynew file mode 100644index 000000000..060a324dc--- /dev/null+++ b/tools/screendiff.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""Compare a before and an after screenshot, and draw the pair for a pull request.++A performance change should look exactly the same. This says whether it does: it compares the two+screenshots pixel by pixel, leaving out the regions you --mask (the clock moves on), and reports how+many pixels differ and where. It also writes the pair side by side, with the regions you --blur+pixelated (your Wi-Fi name, an account picture), ready to attach.++ tools/screendiff.py shots/before.png shots/after.png --mask 90,40,900,220 \\+ --blur 1265,125,1525,197 --out shots/before-after.png++Boxes are x0,y0,x1,y1 in the screenshots' pixels. Exit status: 0 identical, 1 different, 2 an error.+Needs Pillow (tools/requirements-perf.txt). Read tools/screendiff.md first.+"""+import argparse+import re+import sys++BOX = re.compile(r"^\d+,\d+,\d+,\d+$")+++def box(text):+ """'x0,y0,x1,y1' as a tuple, x0 < x1 and y0 < y1."""+ if not BOX.match(text):+ raise argparse.ArgumentTypeError(f"a box is x0,y0,x1,y1 in pixels, not {text!r}")+ x0, y0, x1, y1 = map(int, text.split(","))+ if x0 >= x1 or y0 >= y1:+ raise argparse.ArgumentTypeError(f"a box needs x0 < x1 and y0 < y1: {text!r}")+ return x0, y0, x1, y1+++def compare(a, b, masks, threshold):+ """(pixels that differ by more than threshold in any channel, their bounding box or None, the largest difference)."""+ from PIL import ImageChops, ImageDraw+ a, b = a.convert("RGB").copy(), b.convert("RGB").copy()+ for im in (a, b):+ draw = ImageDraw.Draw(im)+ for m in masks:+ draw.rectangle([m[0], m[1], m[2] - 1, m[3] - 1], fill="black")+ diff = ImageChops.difference(a, b)+ # The largest channel difference per pixel, then a 0/255 mask of pixels over the threshold.+ r, g, bl = diff.split()+ worst = ImageChops.lighter(ImageChops.lighter(r, g), bl)+ over = worst.point(lambda v: 255 if v > threshold else 0)+ count = over.histogram()[255]+ return count, over.getbbox(), max(worst.getdata())+++def redact(im, region):+ """Pixelate then blur a region, so text in it can't be read back."""+ from PIL import Image, ImageFilter+ part = im.crop(region)+ small = part.resize((max(1, part.size[0] // 14), max(1, part.size[1] // 14)), Image.BILINEAR)+ im.paste(small.resize(part.size, Image.NEAREST).filter(ImageFilter.GaussianBlur(4)), region)+ return im+++def pair(a, b, blurs, labels, scale):+ """The two screenshots side by side, blurred where asked, scaled, with a label over each."""+ from PIL import Image, ImageDraw, ImageFont+ a, b = a.convert("RGB").copy(), b.convert("RGB").copy()+ for region in blurs:+ redact(a, region)+ redact(b, region)+ w, h = int(a.size[0] * scale), int(a.size[1] * scale)+ a, b = a.resize((w, h), Image.LANCZOS), b.resize((w, h), Image.LANCZOS)+ out = Image.new("RGB", (2 * w + 30, h + 60), "white")+ out.paste(a, (0, 60))+ out.paste(b, (w + 30, 60))+ draw, font = ImageDraw.Draw(out), ImageFont.load_default(size=30)+ draw.text((10, 14), labels[0], fill="black", font=font)+ draw.text((w + 40, 14), labels[1], fill="black", font=font)+ return out+++def parse(argv):+ p = argparse.ArgumentParser(description="Compare two screenshots and draw the pair. See tools/screendiff.md.")+ p.add_argument("before")+ p.add_argument("after")+ p.add_argument("--mask", type=box, action="append", default=[], metavar="BOX",+ help="leave a region out of the comparison (repeatable), e.g. the clock")+ p.add_argument("--blur", type=box, action="append", default=[], metavar="BOX",+ help="pixelate a region in the picture (repeatable), e.g. the Wi-Fi name")+ p.add_argument("--out", help="write the side-by-side pair here")+ p.add_argument("--diff", metavar="PNG", help="write the differing pixels here, white on black")+ p.add_argument("--labels", default="Before,After", help="labels over the pair, comma-separated")+ p.add_argument("--scale", type=float, default=0.5, help="size of each screenshot in the pair (default 0.5)")+ p.add_argument("--threshold", type=int, default=8,+ help="ignore channel differences up to this (0-255, default 8: compression noise)")+ args = p.parse_args(argv)+ if not 0 < args.scale <= 1:+ p.error("--scale is between 0 and 1")+ if not 0 <= args.threshold <= 255:+ p.error("--threshold is between 0 and 255")+ labels = [l.strip() for l in args.labels.split(",")]+ if len(labels) != 2:+ p.error("--labels takes two labels")+ args.label_pair = labels+ return args+++def main(argv=None):+ args = parse(sys.argv[1:] if argv is None else argv)+ try:+ from PIL import Image+ except ImportError:+ print("screendiff.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt", file=sys.stderr)+ return 2+ try:+ a, b = Image.open(args.before), Image.open(args.after)+ except OSError as e:+ print(f"cannot read a screenshot: {e}", file=sys.stderr)+ return 2+ if a.size != b.size:+ print(f"the screenshots differ in size: {a.size[0]}x{a.size[1]} and {b.size[0]}x{b.size[1]}", file=sys.stderr)+ return 2+ outside = [r for r in args.mask + args.blur if r[2] > a.size[0] or r[3] > a.size[1]]+ if outside:+ print(f"a box is outside the {a.size[0]}x{a.size[1]} screenshot: {outside[0]}", file=sys.stderr)+ return 2+ count, bbox, worst = compare(a, b, args.mask, args.threshold)+ if args.out:+ pair(a, b, args.blur, args.label_pair, args.scale).save(args.out)+ print(f"{args.out}: written")+ if args.diff:+ from PIL import ImageChops+ ImageChops.difference(a.convert("RGB"), b.convert("RGB")).point(lambda v: 255 if v > args.threshold else 0).save(args.diff)+ masked = f" ({len(args.mask)} region{'s' if len(args.mask) != 1 else ''} masked)" if args.mask else ""+ if count == 0:+ print(f"identical{masked}: no pixel differs by more than {args.threshold}")+ return 0+ print(f"different{masked}: {count} pixels differ by more than {args.threshold}, inside "+ f"{bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]} (largest difference {worst})")+ return 1+++if __name__ == "__main__":+ sys.exit(main())