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: send Perfetto binary configs on Android 9 and later
SlivenRedc2896c125ea7
diff --git a/tests/test_trace.py b/tests/test_trace.pyindex 406f81efd..557a0d2fd 100644--- a/tests/test_trace.py+++ b/tests/test_trace.py@@ -10,11 +10,13 @@ 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 base64import contextlibimport importlib.utilimport ioimport osfrom pathlib import Path+import reimport sysimport tempfileimport unittest@@ -28,6 +30,29 @@ spec.loader.exec_module(trace)LAUNCHER = "com.gathin.tvhome/.MainActivity"OTHER = "com.android.tv.settings/.MainSettings"+# Encoded by protoc 3.13.0 from the original text config, using the official+# android-9.0.0_r1 schema (protos/perfetto/config/trace_config.proto). These independent+# fixtures cover every buffer/data source, plus multi-byte lengths and duration varints.+CONFIG_9000 = base64.b64decode(+ "CgYIgIAEIAEKBQiAICABEocCCoQCCgxsaW51eC5mdHJhY2UQAKIG8AEKEnNjaGVkL3NjaGVkX3N3aXRj"+ "aAoSc2NoZWQvc2NoZWRfd2FrZXVwChJzY2hlZC9zY2hlZF93YWtpbmcKE3Bvd2VyL2NwdV9mcmVxdWVu"+ "Y3kKDnBvd2VyL2NwdV9pZGxlChF0YXNrL3Rhc2tfbmV3dGFzawoQdGFzay90YXNrX3JlbmFtZQoYc2No"+ "ZWQvc2NoZWRfcHJvY2Vzc19leGl0EgJhbRICd20SBHZpZXcSA2dmeBIFaW5wdXQSBmRhbHZpaxIDcmVzEg1i"+ "aW5kZXJfZHJpdmVyGhFjb20uZ2F0aGluLnR2aG9tZVCAgAFY+gESHgocChNsaW51eC5wcm9jZXNzX3N0"+ "YXRzEAG6BgIQARIoCiYKJGFuZHJvaWQuc3VyZmFjZWZsaW5nZXIuZnJhbWV0aW1lbGluZRIZChcKFWFu"+ "ZHJvaWQucGFja2FnZXNfbGlzdBioRg==")+LONG_PACKAGE = "com.example." + "launcher" * 20+CONFIG_LONG = base64.b64decode(+ "CgYIgIAEIAEKBQiAICABEqMDCqADCgxsaW51eC5mdHJhY2UQAKIGjAMKEnNjaGVkL3NjaGVkX3N3aXRj"+ "aAoSc2NoZWQvc2NoZWRfd2FrZXVwChJzY2hlZC9zY2hlZF93YWtpbmcKE3Bvd2VyL2NwdV9mcmVxdWVu"+ "Y3kKDnBvd2VyL2NwdV9pZGxlChF0YXNrL3Rhc2tfbmV3dGFzawoQdGFzay90YXNrX3JlbmFtZQoYc2No"+ "ZWQvc2NoZWRfcHJvY2Vzc19leGl0EgJhbRICd20SBHZpZXcSA2dmeBIFaW5wdXQSBmRhbHZpaxIDcmVzEg1i"+ "aW5kZXJfZHJpdmVyGqwBY29tLmV4YW1wbGUubGF1bmNoZXJsYXVuY2hlcmxhdW5jaGVybGF1bmNoZXJs"+ "YXVuY2hlcmxhdW5jaGVybGF1bmNoZXJsYXVuY2hlcmxhdW5jaGVybGF1bmNoZXJsYXVuY2hlcmxhdW5j"+ "aGVybGF1bmNoZXJsYXVuY2hlcmxhdW5jaGVybGF1bmNoZXJsYXVuY2hlcmxhdW5jaGVybGF1bmNoZXJs"+ "YXVuY2hlclCAgAFY+gESHgocChNsaW51eC5wcm9jZXNzX3N0YXRzEAG6BgIQARIoCiYKJGFuZHJvaWQu"+ "c3VyZmFjZWZsaW5nZXIuZnJhbWV0aW1lbGluZRIZChcKFWFuZHJvaWQucGFja2FnZXNfbGlzdBiAgAE=")+class FakeDevice:"""Answers the shell commands trace.py sends and records them; pull writes a stand-in trace."""@@ -38,7 +63,7 @@ class FakeDevice:def shell(self, command, read_timeout_s=None):self.calls.append(("shell", command))- if "perfetto --txt" in command:+ if "| perfetto " in command:return self.perfetto_saysreturn ""@@ -75,10 +100,10 @@ class ScenarioTest(unittest.TestCase):(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)+ self.assertEqual(trace.perfetto_config("com.gathin.tvhome", 9000), CONFIG_9000)++ def test_config_supports_a_different_package_and_multibyte_lengths(self):+ self.assertEqual(trace.perfetto_config(LONG_PACKAGE, 16384), CONFIG_LONG)class ArgumentTest(unittest.TestCase):@@ -112,13 +137,38 @@ class RecordTest(unittest.TestCase):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)+ start = next(i for i, c in enumerate(commands) if "| perfetto " 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_android_9_accepts_the_binary_config_without_txt(self):+ class AndroidPDevice(FakeDevice):+ started = False++ def shell(self, command, read_timeout_s=None):+ self.calls.append(("shell", command))+ if "| perfetto " in command:+ if "--txt" in command:+ return "perfetto: unrecognized option '--txt'\nUsage: perfetto\n"+ match = re.search(r"echo (\S+) \| base64 -d \| perfetto -c - -o ", command)+ if match and base64.b64decode(match.group(1), validate=True) == CONFIG_9000:+ self.started = True+ # Android P's --background does not print a PID.+ return ""++ def pull(self, *args, **kwargs):+ if not self.started:+ raise RuntimeError("Android P never started recording")+ super().pull(*args, **kwargs)++ device = AndroidPDevice()+ size, _ = self.record(device, [], ["sleep 4"])+ self.assertEqual(size, len(b"trace"))+ self.assertIn(("shell", "pidof perfetto >/dev/null && echo running"), device.calls)+def test_sleeps_wait_here_not_on_the_tv(self):device = FakeDevice()_, sleep = self.record(device, ["sleep 2"], ["sleep 1.5"])diff --git a/tools/trace.md b/tools/trace.mdindex 8720735b9..642f12f8e 100644--- a/tools/trace.md+++ b/tools/trace.md@@ -13,6 +13,11 @@ Recording needs only `tools/requirements.txt` and a TV on Android 9 or later. Thdownloads Perfetto's query engine (about 13 MB, SHA-256 checked) to `~/.local/share/perfetto`. To avoidthat, download `trace_processor_shell` yourself and pass `--engine PATH`.+On Android 9 and 10, the TV's tracing services must be enabled first; they are enabled by default only+from Android 11. See Perfetto's [tracing-service setup](https://perfetto.dev/docs/quickstart/android-tracing#starting-the-tracing-services)+for the `persist.traced.enable` prerequisite on non-Pixel devices. This tool does not change that setting.+It sends a binary trace config, which Android 9 accepts without the `--txt` option added in Android 10.+## Record```bashdiff --git a/tools/trace.py b/tools/trace.pyindex aa6a373b5..35c9b22e3 100644--- a/tools/trace.py+++ b/tools/trace.py@@ -38,26 +38,49 @@ NAV_KEYS = ("RIGHT RIGHT RIGHT LEFT LEFT LEFT DOWN RIGHT DOWN LEFT DOWN UP "START_MARGIN_S = 3 # recording starts in the background; give it time before the first stepEND_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 _varint(value):+ """Unsigned protobuf integer; the config only uses non-negative values."""+ out = bytearray()+ while value > 127:+ out.append((value & 127) | 128)+ value >>= 7+ out.append(value)+ return bytes(out)+++def _field(number, value):+ """The config's two wire types: unsigned integers and length-delimited strings/messages."""+ if isinstance(value, str):+ value = value.encode("utf-8")+ if isinstance(value, bytes):+ return _varint((number << 3) | 2) + _varint(len(value)) + value+ return _varint(number << 3) + _varint(value)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))+ """Binary TraceConfig: Android P has no --txt parser; later versions accept binary too.++ Field numbers come from the Android P schema, including FtraceConfig and ProcessStatsConfig:+ https://android.googlesource.com/platform/external/perfetto/+/android-9.0.0_r1/protos/perfetto/config/+ """+ ftrace = b"".join(_field(1, event) for event in (+ "sched/sched_switch", "sched/sched_wakeup", "sched/sched_waking",+ "power/cpu_frequency", "power/cpu_idle", "task/task_newtask", "task/task_rename",+ "sched/sched_process_exit"))+ ftrace += b"".join(_field(2, category) for category in (+ "am", "wm", "view", "gfx", "input", "dalvik", "res", "binder_driver"))+ # FtraceConfig.atrace_apps=3, buffer_size_kb=10, drain_period_ms=11.+ ftrace += _field(3, package) + _field(10, 16384) + _field(11, 250)+ sources = (+ _field(1, "linux.ftrace") + _field(2, 0) + _field(100, ftrace),+ _field(1, "linux.process_stats") + _field(2, 1) + _field(103, _field(2, 1)), # scan_all_processes_on_start+ _field(1, "android.surfaceflinger.frametimeline"),+ _field(1, "android.packages_list"),+ )+ # TraceConfig.buffers=1, data_sources=2, duration_ms=3. Each DataSource.config=1.+ # BufferConfig.size_kb=1 and fill_policy=4 (RING_BUFFER=1).+ buffers = b"".join(_field(1, _field(1, size) + _field(4, 1)) for size in (65536, 4096))+ return buffers + b"".join(_field(2, _field(1, source)) for source in sources) + _field(3, int(duration_ms))def recording_ms(steps):@@ -115,11 +138,11 @@ def record_one(dev, setup, steps, package, out_path, run_shell=None):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")+ config = base64.b64encode(perfetto_config(package, recording_ms(steps))).decode()+ said = run_shell(f"rm -f {REMOTE}; echo {config} | base64 -d | perfetto -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+ # Newer --background clients print their PID. 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"