- Kotlin 83.8%
- Python 15.5%
- Shell 0.7%
- A launcher start (ACTION_MAIN, fresh MainActivity) while the Sendspin player plays opens Now playing on top of settings; paused, or started any other way, it stays on settings. - Back on settings finishes the activity: Android 12+ would only move the task to the back, and the next launcher open would skip onCreate. - Now playing opens with REORDER_TO_FRONT, so a task the notification rooted at Now playing doesn't get a second one stacked on top. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|---|---|---|
| app | ||
| core | ||
| gradle | ||
| host-test | ||
| .gitignore | ||
| build.gradle.kts | ||
| build.sh | ||
| gradle.properties | ||
| gradlew | ||
| gradlew.bat | ||
| LICENSE | ||
| README.md | ||
| settings.gradle.kts | ||
TV Bridge
A lightweight, open reimplementation of the Android TV Remote Service v2
protocol (the one used by Google's com.google.android.tv.remote.service).
It lets the official Android TV remote apps (and any client implementing the
androidtvremote2 protocol, such as the
androidtvremote2 Python client)
discover and control a device without Google's proprietary service.
It can also make the device a Music Assistant player: a Sendspin client that plays in sync with Music Assistant's other speakers (see Music Assistant player).
How it works
The first toggle in MainActivity, Enable remote service, starts
RemoteServerService, a foreground service that:
- Advertises itself over mDNS as
_androidtvremote2._tcp. - Listens for TLS connections on port 6467 (polo pairing server).
- Listens for TLS connections on port 6466 (remote v2 server, speaking
the
RemoteMessageprotobuf protocol).
Clients first pair over 6467 (the user confirms a PIN on the device via
PairingDialogActivity), then connect to 6466 to send key events, text, and
app-launch requests.
Protocol notes
- Pairing uses the polo handshake: the client sends a client cert
(RSA modulus + exponent), the server replies with its own, and both sides
derive a shared secret hashed with SHA-256. The pairing secret is stored
via
KeyStoreManagerand presented for later reconnections. - Transport: plain TLS sockets; messages are protobufs prefixed with a
varint length (
Pbprovides minimal protobuf wire primitives,Dera minimal DER encoder for the self-signed certificate machinery inSelfSignedCert). - Remote messages (
RemoteMsg) cover key presses/releases, text input (IME batches), app links, ping/pong keepalives, and configuration.
Key handling
A non-system app cannot inject key events into other apps: INJECT_EVENTS
is privileged. Each key therefore takes an unprivileged route with the same effect:
| Keys | Route |
|---|---|
| VOLUME_UP / DOWN / MUTE | AudioManager.adjustStreamVolume. On HDMI "full volume" output (SHIELD) the stream stays at max and the framework forwards the change to the TV/AVR as HDMI-CEC volume keys. |
| MEDIA_* (play/pause, stop, next, ...) | AudioManager.dispatchMediaKeyEvent to the active media session |
| HOME, BACK, DPAD_*, ENTER, APP_SWITCH | RemoteAccessibilityService global actions (DPAD needs API 33+); the system injects real key events |
| POWER / SLEEP / WAKEUP | screen off via GLOBAL_ACTION_LOCK_SCREEN, on via WakeActivity (setTurnScreenOn) |
| Text (IME batch edit), letters/digits, DEL | ACTION_SET_TEXT on the focused text field |
App links (market://launch?id=, deep links) |
startActivity; allowed from the background because a bound accessibility service exempts the app from Android 14's background-activity-launch block |
The accessibility service also tracks the foreground app, which is pushed to
clients as remote_ime_key_inject.app_info.app_package (androidtvremote2's
current_app, the app Home Assistant shows). Screen on/off and volume are
pushed as remote_start / remote_set_volume_level.
Setup
Enable the accessibility service once, either from the app's main screen (opens Accessibility settings) or over adb. Append to the existing list rather than replacing it:
adb shell settings get secure enabled_accessibility_services
adb shell settings put secure enabled_accessibility_services \
"<existing entries>:com.hydrogen.tvbridge/.RemoteAccessibilityService"
adb shell settings put secure accessibility_enabled 1
Without it only volume and media keys work, and current_app stays empty.
Music Assistant player (Sendspin)
The second toggle, Music Assistant player (Sendspin), starts
SendspinService, which makes the device a Sendspin player: Music Assistant's
open protocol for synchronized multi-room audio. It speaks Sendspin 1.0
(1.0.0-rc1), which Music Assistant uses from 2.10.7 (2.11.0b4 on the beta
channel).
- Discovery: advertises
_sendspin._tcpon port 8928 with TXTpath=/sendspinandname=<device name>(Settings > Device name). Music Assistant finds it and dialsws://<tv>:8928/sendspin(server-initiated, the direction the spec recommends). - Security: each connection runs the spec's Noise
KKpsk2_25519_AESGCM_SHA256handshake (pure-Java X25519, platform AES-GCM). The player keeps no pairing records and offers unpaired (guest) access, which Music Assistant approves on its own: the player shows up ready to play. Its static key, which is its identity (client_id), is kept in the app's files. - Roles:
player@v1(FLAC through MediaCodec where the device has a decoder, PCM otherwise; 48 kHz, 16-bit, stereo, which the server resamples to),metadata@v1andcontroller@v1. - Several servers: one connection is admitted at a time, by the spec's rules: playback beats an idle connection, and between idle ones the server that last played wins. A server pushed off this way dials back when you play to the player from it.
The protocol code lives in the Android-free core.sendspin package
(SendspinServer, SendspinSession, Noise, TimeFilter, ...); the Android
side is SendspinService, SendspinAudio (playback) and FlacDecoder.
Sync
Audio chunks carry the server-clock time of their first sample; the spec's
two-state Kalman filter over bursts of client/time exchanges maps that to the
local clock. SendspinAudio writes 10 ms blocks to a fast AudioTrack and
places each block by the time it will leave the device: where it is off, it
snaps (silence until the audio is due, or drops what is late) on stream start,
seeks and underruns, and otherwise drops or repeats single frames (at most 0.42%
speed, which is inaudible).
The time a block leaves the device comes from AudioTrack.getTimestamp() where
the HAL reports clean timestamps. The SHIELD's HDMI output does not (frame 0
forever for normal tracks, jumps of tens of milliseconds for fast ones), so
there it comes from the playback head of a fast track plus the HDMI latency the
timestamps show on average, about 47 ms. The app remembers both findings, so
later streams start on the playback head right away. Every 10 s the engine logs
how far off it was:
adb logcat -s TVBridge | grep "Sendspin sync"
Delay after the HDMI port (TV or AVR processing) is what Music Assistant's
per-player Static playback delay setting is for (Sendspin output_delay_ms).
Volume
By default Music Assistant's volume slider scales only this stream, with the
spec's loudness curve ((volume / 100) ^ 1.5). With Music Assistant volume
controls TV volume on, it sets the device's music volume (STREAM_MUSIC)
instead, and volume changes from the remote are reported back to Music
Assistant. When HDMI is in full-volume mode (the TV or AVR does volume over
HDMI-CEC), only relative changes are possible: the difference goes out as
HDMI-CEC volume steps, one per 100 / max percent, and the slider becomes a
relative control.
Now playing and remote control
The metadata and controller roles feed a MediaSession (title, artist, album,
artwork from Music Assistant's artwork URL, progress) and a media notification.
Its transport controls send controller commands, so play/pause, next and
previous from the remote, and media keys from TV Bridge remote clients (which
go to the active media session), control the Music Assistant group. A launcher
that consumes media keys itself (FLauncher does) keeps them from any media
session while it is in front. Now playing on the main screen, or the
notification, opens a full-screen view with artwork, progress and buttons.
Opening TV Bridge from the launcher while the player is playing goes straight
to it; Back leads to the main screen.
Limitations
- Music Assistant 2.10.7 links a Sendspin player to the device's other players (Chromecast, ...) only by MAC address, and Android 11+ hides that from apps, so the player shows up as its own entry next to them. Rename one in Music Assistant.
- Pairing (pairing PSK or codes) is not implemented; the player relies on unpaired access.
- With the SHIELD asleep (screen off) the connection stayed up and Music Assistant could still play to it; whether that holds through hours of deep sleep is untested.
Code layout
Everything is Kotlin, in three Gradle modules:
-
:core: the Android-free protocol code (polo pairing, the remote v2 server, and the Sendspin player core: Noise, X25519, the time filter, FLAC framing, the WebSocket layer). It targets JVM 1.8 APIs so it runs unchanged on Android 7 and on the host test JVM. Its JUnit tests pin the wire format byte for byte. -
:app: the Android side. Services, the accessibility service and the boot receiver use plain threads, like the protocol code. The UI is Jetpack Compose with TV Material 3 (androidx.tv.material3):- Main screen: the toggles and live status.
- Now playing: artwork, progress and transport buttons.
- Pairing dialog: follows the pairing connection and closes when it ends, or when the remote service stops (which also closes the connection).
The services publish their state through
SendspinStateandPairingState(StateFlows), which the screens collect. AcheckTvImportstask (part ofcheck) fails onandroidx.compose.material3widgets and raw click modifiers, which have no D-pad focus styling. -
:host-test: JVM programs the Python test scripts drive (see below).
Building
Requirements:
- JDK 21.
- The Android SDK with build-tools 36.1.0 and the
android-37.0platform. - For the tests: Python 3 and
pip install -r host-test/requirements.txt(tested with androidtvremote2 0.3.2 and aiosendspin 10.2.0). - For the device test:
adb.
Gradle comes from the wrapper (9.7.1). Point it at the SDK with ANDROID_HOME
or a local.properties holding sdk.dir=....
./build.sh builds dist/TVBridge.apk: the release build (minified), signed
with ~/.android/debug.keystore (override it with KEYSTORE). Because the key
and the application id stay the same, adb install -r updates in place and
keeps existing pairings and the accessibility grant. Extra arguments go to
Gradle, e.g. ./build.sh --offline. For a full check:
./gradlew :core:test :app:assembleRelease :app:lintRelease check
targetSdk stays at 34 on purpose. From 35 on, Android 15 no longer allows a
mediaPlayback foreground service to start from BOOT_COMPLETED, and that is how
the Music Assistant player comes back after a reboot.
The app was formerly com.joeri.atvremotemimic (ATV Remote Mimic). The
package ID changed, so upgrading from it is a fresh install: uninstall the old
app first (it holds ports 6466/6467), enable the accessibility service again
and re-pair every client.
Host tests
The :core module (protocol, sessions, the multi-client RemoteServer) is
deliberately Android-free so the harness runs exactly the shipped code on a
plain JVM. The :host-test module holds the JVM programs the Python scripts
drive; the scripts build it with Gradle.
run_remote_tests.sh starts HostServerTest (the pairing and remote servers on
127.0.0.1:16467/16466) and runs remote_protocol_test.py (handshake, pings,
concurrent clients, state pushes) and full_pair_test.py (polo pairing with
PIN) against it with the real androidtvremote2 client:
cd host-test
PYTHON=<venv>/bin/python3 ./run_remote_tests.sh
host-test/client_test.py is an older partial script kept for reference.
full_pair_test.py fails now and then (about 1 run in 10) with "Connection
has been lost" after the server has already logged "paired". The androidtvremote2
client races the server closing the socket after secret_ack. It happens with
the old Java core too; rerun it.
For the Sendspin player, run_sendspin_tests.sh first runs the core's JUnit
tests (./gradlew :core:test). They cover:
- RFC 7748 vectors, the Sentinel PSK id and the time filter.
- FLAC frame splitting on a committed
tone.flac. - The WebSocket layer.
- Byte-exact protocol goldens.
The script then runs sendspin_server_harness.py, which plays the Music
Assistant side with the real aiosendspin server (10.2.0, the version Music
Assistant 2.10.7 uses). It plays against SendspinHostTest, the shipped core on
a plain JVM, once with PCM and once with FLAC.
cd host-test
PYTHON=<venv>/bin/python3 ./run_sendspin_tests.sh
Device test
host-test/device_e2e_test.py drives a real TV with androidtvremote2 and
checks each result against adb ground truth: focused window and view, HDMI-CEC
history, stream volume, wakefulness and logcat. It needs adb access to the TV
and the service running. The full run switches apps, presses volume down and
up again, and leaves the TV on the home screen.
adb connect <tv-ip>:5555
cd host-test
python3 device_e2e_test.py --host <tv-ip> pair # once; reads the code off the screen
python3 device_e2e_test.py --host <tv-ip> full # --power also turns the screen off and on
The client certificate is kept in host-test/e2e-certs/ (git-ignored). The
home app is detected; the plain-LAUNCHER launch test uses the first
third-party app unless --launch-app <package> is given.
The Sendspin harness also runs against the device. It dials the player directly
(no mDNS), streams a test tone, round-trips volume, mute and output delay
(--no-commands skips them, and with them the volume change), and with
--expect-controller pause waits for you to press pause on the remote. Music
Assistant, if connected, gives way to its playback activation and dials back
the next time you play to the player:
python3 sendspin_server_harness.py --url ws://<tv-ip>:8928/sendspin \
--approve preapproved --reason playback --metadata --expect-controller pause
Verification status
Host: remote_protocol_test.py and full_pair_test.py pass against the real
androidtvremote2 0.3.2 client: one configure each way (no configure echo),
pings every 5s, several concurrent clients, current_app and volume_info
pushes.
On device (SHIELD Android TV, LineageOS 21 / Android 14), checked against adb
ground truth with device_e2e_test.py: HOME, BACK, DPAD up/down/center
(focused view moves), volume (HDMI-CEC <User Control Pressed> to the TV),
app links for LAUNCHER and LEANBACK_LAUNCHER-only apps, current_app
following the foreground app, volume_info, pings, concurrent clients. Not
yet verified on device: text entry, POWER off/on, and the effect of media keys
(they are dispatched, but no session state change was checked).
Music Assistant player, on the host: run_sendspin_tests.sh passes, with the
aiosendspin harness passing all 26 checks in --strict mode for PCM and FLAC
and the audio timestamps contiguous. On the SHIELD with Music Assistant
2.10.7: discovery and guest approval, FLAC streaming, volume and mute in both
volume modes (in TV mode the music volume follows the slider, and remote volume
changes reach Music Assistant), metadata and artwork in the media session and
the now-playing screen, pause and play from media keys (dispatched through the
media session service) changing Music Assistant's queue state, and Music
Assistant dialing back after another server took over. The harness against the
device passes all 20 checks (PCM, --no-commands). In steady state the
measured sync error is about 100 us (p50) and 150 to 200 us (p95), as measured
against the playback head, not acoustically. Media keys sent by a remote
protocol client (androidtvremote2) reach the Sendspin media session too:
MEDIA_PLAY_PAUSE paused Music Assistant and the next one resumed it. Not
verified: HDMI-CEC volume steps in full-volume mode (HDMI was in
variable-volume mode during the tests) and the hardware remote's media buttons.
device_e2e_test.py full needs the TV awake. While the SHIELD is dreaming
(screensaver), its setup step monkey -p <pkg> -c <category> 1 doesn't bring
apps to the front. The test's adb calls block its client while it retries, and
the server's 16 s read timeout drops the connection, so the checks after it fail
too. On 2026-11-08 an earlier run had 9 such failures; with the TV awake, the
same SHIELD passed all 23 checks.
Kotlin and Compose rewrite (2026-11-08)
The app was rewritten from Java and XML views to Kotlin and Compose. Each step was checked against the Java build:
- Host:
- The core's JUnit tests (the expected bytes came from the Java core before
it was translated) and
run_remote_tests.shpass. run_sendspin_tests.shpasses 26 of 26 strict checks for PCM and FLAC, withgaps=0.- The host programs print the same lines as their Java versions.
- The core's JUnit tests (the expected bytes came from the Java core before
it was translated) and
- On the SHIELD, installed over the Java build with
adb install -r:- Existing pairings (the e2e client and Home Assistant) and the accessibility grant kept working, and Music Assistant reconnected on its own.
device_e2e_test.py fullpassed all 23 checks, the same as the Java APK in an A/B run.pairread the code off the Compose dialog. The dialog and its notification closed after pairing, and when a client cancelled.- The Sendspin harness passed 19 of 19 checks for PCM and FLAC
(
--no-commands). The sync log showedp50<=100us p95<=150us.
License
Apache License 2.0, see LICENSE.