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/bench.py: one ADB connection for the whole run, and only the log lines it needs
simbfea95401d61
diff --git a/tests/test_bench_connection.py b/tests/test_bench_connection.pynew file mode 100644index 000000000..f99623d36--- /dev/null+++ b/tests/test_bench_connection.py@@ -0,0 +1,144 @@+"""tools/bench.py keeps one ADB connection for the whole run, and asks the TV only for what it needs.++It used to start tools/tv.py for every shell command: a new Python, a new TCP connection and a new+ADB handshake, several times per key, plus the whole main log pulled back for every key (about+100 MB on a TCL C755, 41 s a read). Through a+relay one full run took over 45 minutes. Now the TV class connects once with tools/tv.py's client+and reuses it, reopening it once if it drops; only the log's newest lines are read, filtered on the+TV, and not at all once the first keys show the TV doesn't log them; and the key loop looks up Home once. --host also has to reach the client: the old subprocesses only read TV_HOST.++The TV and tools/tv.py are faked, so these run without either.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import sys+import types+import unittest+from unittest import mock++from tools import bench+++class FakeDevice:+ def __init__(self, answers=None, fail_first=False):+ self.answers = answers or {}+ self.fail_first = fail_first+ self.commands = []+ self.closed = False++ def shell(self, command, read_timeout_s=None, decode=True):+ if self.fail_first:+ self.fail_first = False+ raise ConnectionResetError("TV went to standby")+ self.commands.append(command)+ return next((v for k, v in self.answers.items() if k in command), b"")++ def close(self):+ self.closed = True+++def fake_client(devices):+ """A stand-in for tools/tv.py: connect() hands out the given devices in turn."""+ module = types.ModuleType("tv")+ module.HOST, module.PORT = None, None+ module.connects = 0++ def connect():+ module.connects += 1+ return devices[module.connects - 1]+ module.connect = connect+ return module+++class OneConnectionTest(unittest.TestCase):+ def tv_with(self, *devices):+ client = fake_client(list(devices))+ patcher = mock.patch.dict(sys.modules, {"tv": client})+ patcher.start()+ self.addCleanup(patcher.stop)+ return bench.TV("192.0.2.7", 15555), client++ def test_many_commands_share_one_connection(self):+ tv, client = self.tv_with(FakeDevice())+ for _ in range(10):+ tv.shell("input keyevent 22")+ self.assertEqual(client.connects, 1)++ def test_host_and_port_from_the_command_line_reach_the_client(self):+ tv, client = self.tv_with(FakeDevice())+ tv.shell("true")+ self.assertEqual((client.HOST, client.PORT), ("192.0.2.7", 15555))++ def test_a_dropped_connection_is_reopened_once(self):+ first, second = FakeDevice(fail_first=True), FakeDevice({"echo": b"ok"})+ tv, client = self.tv_with(first, second)+ self.assertEqual(tv.shell("echo ok"), "ok")+ self.assertEqual(client.connects, 2)+ self.assertTrue(first.closed)++ def test_output_that_is_not_utf8_does_not_stop_the_run(self):+ tv, _ = self.tv_with(FakeDevice({"dumpsys": b"Uptime: 5 \xff\xfe"}))+ self.assertEqual(tv.shell("dumpsys gfxinfo"), "Uptime: 5 ��")++ def test_close_closes_the_connection(self):+ device = FakeDevice()+ tv, _ = self.tv_with(device)+ tv.shell("true")+ tv.close()+ self.assertTrue(device.closed)+++class FakeTV:+ """Records commands; answers the two dumpsys calls and the filtered log."""++ def __init__(self, log=""):+ self.log = log+ self.commands = []++ def shell(self, command):+ self.commands.append(command)+ if "framestats" in command:+ return "Uptime: 2000\n"+ if "gfxinfo" in command:+ return "Uptime: 1000\n"+ if command.startswith("logcat"):+ return self.log+ return ""++ def package_of(self, component):+ return component.split("/", 1)[0]++ def home_component(self):+ self.commands.append("HOME LOOKUP")+ return "com.gathin.tvhome/.MainActivity"+++class KeyTest(unittest.TestCase):+ def test_the_log_is_filtered_on_the_tv(self):+ line = "10-22 I Input: injectKeyEvent: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_DPAD_RIGHT, eventTime=1500 }"+ tv = FakeTV(line)+ self.assertEqual(bench.key_event_time(tv, 22), 1500)+ self.assertEqual(tv.commands, ["logcat -d -b main -t 2000 | grep injectKeyEvent"])++ def test_a_tv_that_never_logs_keys_stops_being_asked(self):+ tv = FakeTV("")+ for _ in range(10):+ self.assertIsNone(bench.key_event_time(tv, 22))+ self.assertEqual(len(tv.commands), bench.KEY_LOG_PROBES)++ def test_a_tv_that_logs_keys_keeps_being_asked(self):+ tv = FakeTV("injectKeyEvent action=ACTION_DOWN KEYCODE_DPAD_RIGHT eventTime=7")+ for _ in range(10):+ bench.key_event_time(tv, 22)+ self.assertEqual(len(tv.commands), 10)++ def test_the_key_loop_does_not_look_up_home_for_every_key(self):+ tv = FakeTV()+ with mock.patch.object(bench.time, "sleep"):+ bench.measure_key(tv, 22, package="com.gathin.tvhome")+ self.assertNotIn("HOME LOOKUP", tv.commands)+ self.assertIn("dumpsys gfxinfo com.gathin.tvhome reset", tv.commands)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_bench_framestats.py b/tests/test_bench_framestats.pyindex 6494c6f8a..9297e2f6e 100644--- a/tests/test_bench_framestats.py+++ b/tests/test_bench_framestats.py@@ -64,7 +64,7 @@ class FrameStatsTest(unittest.TestCase):"dumpsys gfxinfo com.gathin.tvhome reset": "Uptime: 1000 Realtime: 1000\n","input keyevent 22": "","dumpsys gfxinfo com.gathin.tvhome framestats": stats,- "logcat -d -b main":+ "logcat -d -b main -t 2000 | grep injectKeyEvent":"injectKeyEvent action=ACTION_DOWN KEYCODE_DPAD_RIGHT eventTime=1000",}tv = mock.Mock()diff --git a/tests/test_bench_target.py b/tests/test_bench_target.pyindex dcedb3687..8bcea8028 100644--- a/tests/test_bench_target.py+++ b/tests/test_bench_target.py@@ -1,4 +1,4 @@-"""bench.py passes its selected host and port to the tv.py subprocess.+"""bench.py passes its selected host and port to tools/tv.py's client.A local tv.py records its environment and returns no Home component, so the CLI stopsbefore measuring anything. No TV, network connection or ADB key is needed.@@ -26,12 +26,21 @@ class BenchTargetTest(unittest.TestCase):with tempfile.TemporaryDirectory() as tmp:folder = Path(tmp)shutil.copyfile(ROOT / "tools" / "bench.py", folder / "bench.py")+ # bench.py imports tv.py and calls connect(); this one records the target and answers nothing.(folder / "tv.py").write_text("import json, os\n""from pathlib import Path\n"- "target = {key: os.environ.get(key) for key in "+ "HOST = PORT = None\n"+ "class Device:\n"+ " def shell(self, command, read_timeout_s=None, decode=True):\n"+ " return b''\n"+ " def close(self):\n"+ " pass\n"+ "def connect():\n"+ " target = {key: os.environ.get(key) for key in ""('TV_HOST', 'TV_PORT', 'BENCH_TARGET_TEST')}\n"- "Path(__file__).with_name('target.json').write_text(json.dumps(target))\n",+ " Path(__file__).with_name('target.json').write_text(json.dumps(target))\n"+ " return Device()\n",encoding="utf-8")result = subprocess.run([sys.executable, str(folder / "bench.py"), *args],cwd=tmp, env=env, capture_output=True, text=True, timeout=10)diff --git a/tools/bench.py b/tools/bench.pyindex 3ed248b10..628c00545 100644--- a/tools/bench.py+++ b/tools/bench.py@@ -28,12 +28,13 @@ from the vsync BEFORE the key and only finishes after it. Matching on the intendmost of those keys and leaves a sample too small to say anything."""import argparse+import atexit+import importlib.utilimport jsonimport osfrom pathlib import Pathimport reimport statistics-import subprocessimport sysimport time@@ -47,7 +48,7 @@ KEYCODE_NAMES = {19: "KEYCODE_DPAD_UP", 20: "KEYCODE_DPAD_DOWN", 21: "KEYCODE_DPclass TV:- """The TV, reached through tools/tv.py.+ """The TV, reached with tools/tv.py's client over one ADB connection.tools/tv.py is the client this project already ships: it speaks ADB over TCP with theadb_shell library, so no adb binary is needed. That matters on macOS, where the platform@@ -62,44 +63,50 @@ class TV:self.client = Noneself._other_app = None- def _tv_py(self):- """The path of tools/tv.py, next to this file."""- return str(Path(__file__).resolve().parent / "tv.py")+ def _connect(self):+ """tools/tv.py's ADB connection, opened on first use and kept for the whole run.- def _python(self):- """The interpreter that has the adb_shell library.-- tools/tv.py needs adb_shell, which lives in this project's venv (tools/venv). When the- venv is there, it is used; otherwise the interpreter running this script is, and- tv.py's own error says what to install.+ Starting tools/tv.py per command paid a Python start and a fresh ADB handshake each time,+ several per key; through a relay a full run took over 45 minutes."""- here = Path(__file__).resolve().parent- for candidate in (here / "venv" / "bin" / "python",- here / "venv" / "Scripts" / "python.exe"):- if candidate.exists():- return str(candidate)- return sys.executable-- def _run(self, *args, capture=True):- """Run tools/tv.py with the given arguments."""- cmd = [self._python(), "-I", self._tv_py(), *args]- # tv.py reads its target from the environment, including CLI overrides here.- env = os.environ.copy()- env.update(TV_HOST=self.host, TV_PORT=str(self.port))- result = subprocess.run(cmd, capture_output=capture, text=True,- errors="replace" if capture else None, env=env)- if result and result.returncode != 0 and not result.stdout.strip():- raise SystemExit(f"tools/tv.py failed: {result.stderr.strip()}")- return result+ if self.client is None:+ here = str(Path(__file__).resolve().parent)+ if here not in sys.path:+ sys.path.insert(0, here)+ # tv.py reads its target from the environment when imported, including CLI overrides here.+ os.environ["TV_HOST"], os.environ["TV_PORT"] = self.host, str(self.port)+ try:+ import tv as tv_client # noqa: E402+ except ModuleNotFoundError as e:+ raise SystemExit(f"bench.py needs {e.name}: python3 -m venv tools/venv && "+ "tools/venv/bin/pip install -r tools/requirements.txt") from e+ tv_client.HOST, tv_client.PORT = self.host, int(self.port)+ self.client = tv_client.connect()+ return self.clientdef shell(self, command):- """Run one shell command on the TV and return its output.+ """Run one shell command on the TV and return its output; bytes that aren't UTF-8 become U+FFFD.- tools/tv.py joins the arguments with a space and runs them in the TV's shell, so the- command is passed as it is, without a "shell" subcommand of our own.+ A dropped connection (the TV went to standby for a moment) is reopened once."""- result = self._run(command)- return result.stdout if result else ""+ for attempt in (1, 2):+ try:+ out = self._connect().shell(command, read_timeout_s=120.0, decode=False)+ return out.decode("utf-8", "replace") if isinstance(out, bytes) else (out or "")+ except SystemExit:+ raise+ except Exception:+ self.close()+ if attempt == 2:+ raise++ def close(self):+ if self.client is not None:+ try:+ self.client.close()+ except Exception:+ pass+ self.client = Nonedef shell_ok(self, command):return self.shell(command).strip() == ""@@ -147,19 +154,41 @@ class TV:return self.shell(f"dumpsys {what}")+# Keys to read the input log for before deciding this TV doesn't log injected keys.+KEY_LOG_PROBES = 3+++def venv_python():+ """tools/venv's interpreter, which has adb_shell, or None."""+ here = Path(__file__).resolve().parent+ for candidate in (here / "venv" / "bin" / "python", here / "venv" / "Scripts" / "python.exe"):+ if candidate.exists():+ return str(candidate)+ return None++def key_event_time(tv, keycode, binary=None):"""The uptime (ms) at which the key went down, read from the input log.The log line is matched by the key's own name: the buffer holds the keys injected before it,and the first line of the buffer is not necessarily the key of this measurement."""- out = tv.shell("logcat -d -b main")+ # Some TVs never log injected keys (a TCL C755 on Google TV 14 doesn't), and reading the log costs+ # seconds there: its main buffer holds about 100 MB. After KEY_LOG_PROBES keys without a line, stop+ # reading it; measure_key then times the key from just before it was sent, as it always did when+ # the line was missing. Only the newest lines are read, filtered on the TV.+ state = vars(tv).setdefault("_key_log", {"seen": False, "misses": 0})+ if not state["seen"] and state["misses"] >= KEY_LOG_PROBES:+ return None+ out = tv.shell("logcat -d -b main -t 2000 | grep injectKeyEvent")name = KEYCODE_NAMES.get(keycode, f"keyCode={keycode}")for line in reversed(out.splitlines()):if "injectKeyEvent" in line and "action=ACTION_DOWN" in line and name in line:match = re.search(r"eventTime=(\d+)", line)if match:+ state["seen"] = Truereturn int(match.group(1))+ state["misses"] += 1return Nonedef android_uptime(tv, package=None, binary=None):@@ -174,9 +203,9 @@ def android_uptime(tv, package=None, binary=None):return int(match.group(1)) if match else None-def measure_key(tv, keycode, binary=None):+def measure_key(tv, keycode, binary=None, package=None):"""Inject one key and return (response_ms, movement_ms, frames, janky) or None."""- package = tv.package_of(tv.home_component())+ package = package or tv.package_of(tv.home_component())# The reset zeroes the gfxinfo counters. Without it, the previous key's frame would still be# in the window and the "first frame after the key" would be the previous key's.reset_out = tv.shell(f"dumpsys gfxinfo {package} reset")@@ -374,7 +403,7 @@ def return_to_home(tv, component, repeats):clear_log(tv)tv.shell("input keyevent 3")time.sleep(3)- out = tv.shell("logcat -d -b main -b events -v epoch")+ out = tv.shell("logcat -d -b main -b events -v epoch | grep -e injectKeyEvent -e am_on_resume_called")key_at = resume_at = Nonefor line in out.splitlines():# The log indents its lines, so the timestamp is not at the start of the line.@@ -478,8 +507,14 @@ def main():args = parser.parse_args()if not args.host:raise SystemExit("pass --host or set TV_HOST")+ venv = venv_python()+ if importlib.util.find_spec("adb_shell") is None and venv \+ and os.path.realpath(venv) != os.path.realpath(sys.executable):+ # Started with a Python that lacks adb_shell: run again with the project's venv, which has it.+ os.execv(venv, [venv, os.path.abspath(__file__), *sys.argv[1:]])tv = TV(args.host, args.port)+ atexit.register(tv.close)component = tv.home_component()if not component:raise SystemExit("no component answers HOME on this TV")@@ -505,7 +540,7 @@ def main():return 1for index in range(args.keys):keycode = DEFAULT_SEQUENCE[index % len(DEFAULT_SEQUENCE)]- measured = measure_key(tv, keycode)+ measured = measure_key(tv, keycode, package=package)if measured is None:samples.append({"series": series, "key": keycode, "measured": False})continue