Milestone 4 desktop research: adb automation, video, audio, webcam, input
- Date: 2026-11-15
- Scope: desktop side of the enhanced tier (ADR-0007), implementation reference for M4.
- Machine used for local checks: Linux Mint 22.2, kernel 6.17.0-1032-oem, X11 Cinnamon,
NVIDIA RTX 4050 (driver 580, no iGPU visible in
lspci), PipeWire 1.0.5, GStreamer 1.24.2, GTK 4.14.5, libadwaita 1.5.0, Secure Boot disabled. - Nothing was installed and no device was contacted. Only
adb version,adb mdns check,adb host-features(server-only queries),apt-cache,dpkg -S,gst-inspect-1.0were run.
Confidence markers used below:
- [verified-local] checked on this machine.
- [verified-src] read in AOSP / Debian / crates.io / scrcpy sources or docs during this research (link given).
- [unverified] from memory or community reports; spike before relying on it.
Summary of recommendations
| Topic | Choice |
|---|---|
| Pairing UX | QR flow primary (WIFI:T:ADB;S:studio-<10>;P:<12>;;), 6-digit code as fallback; both discover the pairing port through Avahi |
| Connect-port discovery | Our own Avahi browse of _adb-tls-connect._tcp, then adb connect ip:port. Never rely on adb’s built-in mDNS |
| adb server and key | Private adb server (own socket/port, own key dir via HOME, ADB_USB=0, ADB_MDNS=0) for wireless; user’s default server only for the USB fallback. Config switch for “shared” |
| adb integration | Shell out to the adb binary; speak the host protocol directly only for host:track-devices |
| Helper transport | adb reverse localabstract:tether_<id> to a daemon listener, separate sockets for control/video/audio, token kept. Direct LAN TLS is a later optimisation |
| Minimum adb | 34.0.0 (parse adb version); never trust adb pair/adb connect exit codes, parse stdout |
| Video | GStreamer via gstreamer-rs 0.23 + gst-plugin-gtk4 0.13 linked statically; appsrc ! h264parse ! <dec> ! glsinkbin(gtk4paintablesink) |
| Audio | GStreamer in the daemon: `appsrc ! opusdec ! audioconvert ! audioresample ! pulsesink |
| Webcam | v4l2loopback + v4l2sink first (only path every call app sees); PipeWire Video/Source node as a no-root second output |
| Input | GestureClick + EventControllerMotion + EventControllerScroll + EventControllerKey with GtkIMMulticontext; EventControllerLegacy for touch sequences; scrcpy’s default bindings |
A. adb automation from a daemon
A.1 Wireless debugging pairing flows (Android 11+)
Source of truth: AOSP packages/modules/adb/docs/dev/adb_wifi.md [verified-src].
Facts:
- The phone runs the Pairing Server; the desktop’s adb is the pairing client. A host is
“paired” once its public key is in the phone’s
/data/misc/adb/adb_keys. - mDNS service types published by the phone:
_adb._tcp: legacyadb tcpiplistener._adb-tls-pairing._tcp: only while a pairing dialog is open on the phone._adb-tls-connect._tcp: while “Wireless debugging” is on (TLS server, random port).
- Instance names:
- connect service:
adb-<ro.serialno>-<random>(e.g.adb-14141FDF600081-TnSdi9); the value ispersist.adb.wifi.guidand is the “guid” adb prints after pairing. - pairing service, code flow:
adb-<guid>. - pairing service, QR flow: exactly the name the QR asked for,
studio-<RANDOM-10>.
- connect service:
- Shared secret: 6-digit number (code flow) or a host-generated password (QR flow). The doc
says “10-digit number” in one place but its own example password is 12 printable
characters:
WIFI:T:ADB;S:studio-g@<xeYnap/;P:(Aq+v9>Cx>!/;;.
Pairing-code flow
- Phone: Developer options, Wireless debugging, “Pair device with pairing code”. The dialog
shows a 6-digit code and
ip:port. - Desktop:
adb pair <ip>:<port> <code>(code may also be given on stdin after theEnter pairing code:prompt). - Success output:
Successfully paired to <ip>:<port> [guid=adb-<serial>-<suffix>]; failure:Failed: Wrong password or connection was dropped.(strings fromclient/adb_wifi.cpp, platform-tools 35.0.2 [verified-src]). adb then writes the guid toadb_known_hosts.pband tries to connect by service name. - We do not need the user to read the ip:port: browse
_adb-tls-pairing._tcpwith Avahi and take the address and port from the resolved record; the user types six digits only.
QR flow (what Android Studio does)
- Desktop generates a service name and password and shows the QR
WIFI:T:ADB;S:<name>;P:<password>;;(format piggybacks on the WPA3 Wi-Fi QR syntax). - Phone: Wireless debugging, “Pair device with QR code”, scan. Seeing
T:ADB, the phone starts a Pairing Server and advertises_adb-tls-pairing._tcpwith instance name<name>. - Desktop sees that instance (which also tells it which phone scanned), resolves it and
runs
adb pair <ip>:<port> <password>.
Implementation notes for our generator:
- Name:
studio-+ 10 random characters. Community tools pair with arbitrary names (a widely used gist usesdebug), so the prefix is probably not enforced [unverified]; keepstudio-because that is what AOSP documents and Studio emits. - Password: 12 random characters. Use
[A-Za-z0-9]only for both fields, so nothing needs the Wi-Fi QR escaping rules (\ ; , : ") and nothing needs shell quoting. - Pass the password as an argv element (no shell). It is single-use and short-lived.
- The QR must be scanned from inside Settings (Wireless debugging), not a general camera app, on most builds [unverified for One UI].
- The
qrcodecrate is already in the workspace and the GTK app already renders pairing QRs. - Platform-tools 37.0.3 added
adb pair --qr(terminal QR) [verified-src]; too new to depend on, but it confirms the flow is the supported one.
Recommendation. Offer the QR flow as the primary path and the 6-digit code as the
fallback in the same wizard page. QR needs no typing and identifies the phone
unambiguously when several devices are in pairing mode. The fallback covers camera
problems. Both use one Avahi browser for _adb-tls-pairing._tcp (reuse
desktop/crates/tether-core/src/discovery/avahi.rs), and both end in the same
adb pair call. The CLI (tether enhance) uses the code flow, or a terminal QR.
This changes the roadmap text (“user types the 6-digit code”) from the only path to the
fallback path.
Sources:
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/dev/adb_wifi.md
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/tags/platform-tools-35.0.2/client/adb_wifi.cpp
- https://developer.android.com/tools/adb (user-facing steps)
- https://gist.github.com/benigumocom/a6a87fc1cb690c3c4e3a7642ebf2be6f (community QR script, arbitrary name)
- https://developer.android.com/tools/releases/platform-tools (37.0.3
adb pair --qr)
A.2 Discovering the connect port
The TLS connect port is random and changes every time Wireless debugging is toggled (and therefore after every reboot). It has to be discovered each time.
State of adb’s own mDNS, from the platform-tools release notes [verified-src]:
| Version | mDNS backend |
|---|---|
| 30.0.0 | wireless pairing added; mDNS needs a Bonjour daemon (mdnsResponder) |
| 30.0.2 | mDNS auto-connect off by default (ADB_MDNS_AUTO_CONNECT) |
| 31.0.2 | embedded openscreen backend added, off by default (ADB_MDNS_OPENSCREEN=1) |
| 35.0.2 | openscreen default on all platforms |
| 37.0.0 | new default backend libadbmdns, openscreen deprecated |
| 37.0.1 | openscreen deleted; ADB_MDNS_OPENSCREEN has no effect |
What the distributions ship:
- Debian 13 (trixie):
adb1:34.0.5-12 (bookworm 29.0.6, bookworm-backports 34.0.5, experimental 35.0.2). Debian’s build stubs mDNS out completely:debian/system/adb.mkgenerates a file with emptyinit_mdns_transport_discovery(),mdns_check()returning"", andmdns_get_connect_service_info()returningnullopt; the openscreen and mdnsresponder sources are commented out inlibadb.mk[verified-src]. Soadb mdns servicesreturns nothing and there is no auto-connect. - Ubuntu 24.04 / Mint 22:
adb1:34.0.4-1build3 (universe) [verified-local]. Same packaging lineage, so mDNS is almost certainly stubbed as well [unverified, not inspected]. - This machine:
/usr/bin/adbis Google’s binary 35.0.0-11411520 fromgoogle-android-platform-tools-installer(multiverse,Provides: adb). It contains openscreen (host-featureslistsopenscreen_mdns) but 35.0.0 still defaults to Bonjour, andadb mdns checkanswersERROR: mdns daemon unavailable[verified-local]. A second adb, 37.0.1, sits in~/Android/Sdk/platform-tools.
So a user can have an adb with no mDNS, with a non-working Bonjour default, with openscreen, or with libadbmdns. Only our own browse is predictable.
Recommendation.
- Browse
_adb-tls-connect._tcp(and_adb-tls-pairing._tcpduring the wizard) with the existing Avahi D-Bus code. Resolve, prefer IPv4 (adb’s own listing is IPv4-only). - Remember the guid printed by
adb pairper paired phone. When a connect instance whose name equals that guid appears:adb connect <ip>:<port>. When it disappears, treat the transport as gone (and confirm via track-devices). - Start our adb server with
ADB_MDNS=0(honoured inclient/main.cpp[verified-src]) so behaviour is the same on every adb build and adb never auto-connects behind our back. - Because
adb paironly auto-connects through adb’s mDNS, always follow a successful pair with our ownadb connect. - Serial to use afterwards:
<ip>:<port>(whatadb connectregisters). Pass it with-son every command. - Optional later: the Tether Android app can report the port over the normal-tier
connection (
NsdManagerdiscovery of its own service) for networks where multicast is filtered [unverified].
Sources:
- https://developer.android.com/tools/releases/platform-tools
- https://sources.debian.org/src/android-platform-tools/34.0.5-12/debian/system/adb.mk
- https://sources.debian.org/src/android-platform-tools/34.0.5-12/debian/system/libadb.mk
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/tags/platform-tools-35.0.2/client/main.cpp
A.3 Key storage and server: shared or private
How adb decides [verified-src] (adb_utils.cpp, client/auth.cpp, client/adb_wifi.cpp,
client/main.cpp, 35.0.2):
- Key:
$HOME/.android/adbkey(+.pub), generated on first server start. OnlyHOMEis consulted on Linux. ADB_VENDOR_KEYS: colon-separated extra private keys (files or directories) offered in addition to the user key.- Wireless known hosts:
$HOME/.android/adb_known_hosts.pb(guids of paired devices). - Server address:
-L <socket>/ADB_SERVER_SOCKET, or-P <port>/ANDROID_ADB_SERVER_PORT; defaulttcp:localhost:5037. ADB_USB=0skips USB initialisation;ADB_MDNS=0skips mDNS;ADB_REJECT_KILL_SERVER=1makes the server ignorekill-server.- A client kills a running server only when the internal protocol version differs. Both
35.0.0 and 37.0.1 here report
1.0.41, so the two installed adbs do not kill each other’s server [verified-local]. The server keeps the feature set of whichever binary started it.
Options:
| Shared (user’s key, server on 5037) | Private (own key dir, own socket) | |
|---|---|---|
Phone appears in the developer’s adb devices, Android Studio, flutter devices | Yes, permanently, as soon as it is on Wi-Fi. A second device then makes every un-targeted adb command fail with “more than one device” | No |
adb kill-server by the user or an IDE | Kills our helper session (we recover, but mirroring drops) | No effect |
| Server started by another binary (Studio’s 37.x, distro 34.x) | We inherit its behaviour (mDNS auto-connect, USB backend) | We control the binary and environment |
| Existing USB authorisation reused | Yes | No, needs its own pairing (we drive pairing anyway) |
| USB | One server owns the USB interface, no contention | Would compete with the user’s server for the USB interface unless ADB_USB=0 |
| Revocation | Mixed with the developer’s own authorisation | Separate key; “Revoke” still removes both on the phone |
| Local attack surface | tcp:localhost:5037 is reachable by every local user | Can listen on a unix socket inside $XDG_RUNTIME_DIR |
Recommendation. Private server by default, shared as a config option
([adb] server = "private" | "shared").
- Environment for every adb invocation in private mode:
HOME=$XDG_DATA_HOME/tether/adb(key ends up in.../tether/adb/.android/adbkey, mode 0600 as adb creates it),ADB_MDNS=0,ADB_USB=0, and eitherADB_SERVER_SOCKET=localfilesystem:$XDG_RUNTIME_DIR/tether/adb.sockwithadb -L <same> start-server, orANDROID_ADB_SERVER_PORT=<fixed non-5037 port>. The unix-socket form is supported by adb’s socket specs but is [unverified] with distro 34.x; fall back to a TCP port ifstart-serverfails. - Start the server explicitly (
adb start-server) from the daemon and stop it withkill-serveron daemon exit; do not leave it to implicit start. - USB fallback: use the user’s default server (plain
adb, no overrides). The phone shows the usual “Allow USB debugging?” dialog for the user’s own key. This keeps a single USB owner on the machine and still gives “cable always works”. - Wrap this in one
AdbEnv { binary, envs, serial }type so shared/private/USB are data, not code paths. - Never copy or read
~/.android/adbkeyourselves.
Sources:
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/tags/platform-tools-35.0.2/adb_utils.cpp
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/tags/platform-tools-35.0.2/client/auth.cpp
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/tags/platform-tools-35.0.2/client/main.cpp
A.4 Detecting state
Event-driven device list. host:track-devices [verified-src] (docs/dev/services.md):
open a connection to the adb server, send <4 hex length>host:track-devices (i.e.
0012host:track-devices), read OKAY, then read forever: <4 hex length> followed by that
many bytes of serial\tstate\n lines, one full list per change. Variants
host:track-devices-proto-binary / -proto-text exist on newer servers (feature
devicetracker_proto_format, present in 35.0.0 here); do not depend on them. 31.0.2 fixed
late updates for wireless devices and 33.0.3 fixed duplicate entries, both below our
minimum. A zero-length list (0000) means no devices. This is about 40 lines of tokio code
and works over TCP or a unix socket.
States (from adb devices / tracker; strings confirmed in the 35.0.0 binary
[verified-local]): device (usable), unauthorized (key not accepted or dialog
pending), authorizing, connecting, offline, no permissions (USB udev rules),
host, recovery, sideload, bootloader.
Decision table for the daemon
| Observation | Meaning | Action |
|---|---|---|
Tether normal-tier link up, no _adb-tls-connect._tcp instance with our guid | Wireless debugging is off (reboot, Wi-Fi network changed, user toggled) | Notify “Turn Wireless debugging back on”; offer USB |
Instance present, adb connect prints connected to / already connected to and tracker shows device | Ready | Launch helper |
adb connect prints failed to connect to ...: Connection refused or times out | Stale port or client isolation on the AP | Re-resolve; after N tries, guide |
adb connect prints failed to authenticate to <ip:port> or tracker shows unauthorized on a TLS transport | Our key was revoked (“Revoke USB debugging authorisations”, factory reset) | Forget guid, run pairing wizard again |
Tracker offline | Transport stalled (Wi-Fi sleep) | adb disconnect <serial>, reconnect; adb reconnect offline |
USB: unauthorized | RSA dialog waiting on the phone | Prompt the user to accept |
USB: no permissions | udev rules missing | Point at android-sdk-platform-tools-common / plugdev |
| USB: phone connected (normal tier knows) but nothing appears on the default server | USB debugging off or blocked (Auto Blocker) | Guide |
Helper process (adb shell ... app_process) exits while tracker still says device | Helper crashed or was killed | Restart with backoff; report ShellHello missing |
Notes:
adb connectand (before 34.0.5)adb pairreturn exit code 0 on failure; 34.0.5 fixedpaironly [verified-src, release notes]. Ubuntu ships 34.0.4. Always parse stdout. The exactadb connectstrings above are [unverified] against 34.x; capture them in the first spike and match loosely (connected to,failed to).- Wireless debugging resets. The toggle does not survive a reboot, and it switches off when the phone leaves the Wi-Fi network it was enabled on. ADR-0007 attributes this to Samsung; it is believed to be AOSP behaviour [unverified]. Either way the detection above is the same.
- Possible self-heal [unverified, worth a spike]: during the first enhanced session the
helper can
pm grant org.tether.android android.permission.WRITE_SECURE_SETTINGS; the normal app could then writeSettings.Global "adb_wifi_enabled" = 1after boot when the desktop asks, removing the manual step. Known from community tools on stock Android; behaviour on One UI 6/7 and Android 15/16 is unknown, and it must stay opt-in because it widens what the normal app may do (ADR-0007 security boundary). - Samsung Auto Blocker. Community and Samsung-forum reports: with Auto Blocker on, the
USB debugging toggle is greyed out / forced off (“Block commands by USB cable”). Whether
it also blocks Wireless debugging on One UI 7 is [unverified]. Desktop-visible
symptoms: no USB device at all, no pairing or connect service advertised. The phone app
cannot be assumed to read the Auto Blocker state; the wizard should show the Samsung
step whenever
Build.MANUFACTURER == samsung(the phone reports that inHello). - Add a “Wireless debugging” Quick Settings tile hint (Developer options, “Quick settings developer tiles”) to the guidance; it turns the post-reboot fix into one tap.
Recommendation. One AdbMonitor task per adb server: a persistent
host:track-devices connection (reconnect with backoff, starting the server if needed)
merged with Avahi browse events and the normal-tier link state into a small state machine
(Unpaired, WirelessOff, Connecting, Unauthorized, Ready, HelperRunning) exported over
D-Bus for the wizard and the tray.
Sources:
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/dev/services.md
- https://developer.android.com/tools/releases/platform-tools
- https://forum.developer.samsung.com/t/s24-ultra-developer-option-usb-debugging-greyed-out/29526
- https://techwiser.com/fix-usb-debugging-greyed-out-on-samsung-galaxy-phone/
A.5 Shell out to adb or speak the protocol from Rust
Crates checked on crates.io [verified-src]:
| Crate | Version (date) | Licence | Notes |
|---|---|---|---|
adb_client | 3.2.3 (2026-08) | MIT | Most active. Server-proxy mode and direct USB/TCP mode, optional mdns, usb. Depends on rustls/rcgen/rsa. Its pair (src/server/commands/pair.rs) forwards to a running adb server; no native pairing was found. Blocking API |
mozdevice | 0.5.5 (2026-06) | MPL-2.0 | Talks to an adb server only |
forensic-adb | 0.8.1 (2025-03) | MPL-2.0 | Tokio fork of mozdevice, server only |
adbear | 0.1.1 (2024) | n/a | Pairing CLI, self-described as fragile |
MIT and MPL-2.0 are both compatible with GPL-3.0-or-later, so licence is not the deciding factor.
Why not native:
- Pairing is TLS, then SPAKE2 as implemented in BoringSSL (not the RustCrypto
spake2wire format [unverified]), keyed with TLS exported keying material, then AES-128-GCM framedPeerInfoexchange. No maintained Rust implementation was found. Android 17 is reported to rework ADB Wi-Fi again [unverified]. - The connect path needs the A_STLS upgrade, client-certificate auth with the adb RSA key,
the adb stream multiplexer, shell v2,
reverse:and sync. scrcpy, Android Studio’s fallback and every comparable project lean on the stock binary for this. adbis already a package dependency (ADR-0007), and USB works for free.
Recommendation. Shell out to adb with tokio::process::Command (argv, never a shell
string; kill_on_drop(true); timeouts on every call) for start-server, pair, connect,
disconnect, reverse, push/install and the long-running
adb -s <serial> shell CLASSPATH=... app_process ... child whose lifetime is the helper’s
lifetime. Speak the host protocol ourselves only for host:track-devices (A.4). Do not add
an adb crate.
Sources:
- https://docs.rs/crate/adb_client/latest and https://github.com/cocool97/adb_client
- https://docs.rs/crate/adb_client/3.2.1/source/src/server/commands/pair.rs
- https://crates.io/crates/mozdevice , https://crates.io/crates/forensic-adb
A.6 Transport for the helper’s connection back to the daemon
What scrcpy does [verified-src] (doc/develop.md, doc/tunnels.md):
- Default is
adb reverse: the client listens first, then starts the server, which connects tolocalabstract:scrcpy_<SCID>on the device (SCID is a random 31-bit id so several instances coexist). Reason given: no race and no polling, because the listener exists before the server starts. - Fallback is
adb forward(--force-adb-forward, or automatically when reverse fails): the device listens and the client connects. Because a forward “connect” succeeds even with nobody listening, the server sends one dummy byte on the first socket so the client can detect a real connection. - Up to three separate sockets, opened in order: video, audio, control.
- Frames are sent with a 12-byte header (flags for config/key frame, PTS, size); the client decodes and shows frames immediately with no buffering.
adb reverseover a TCP/IP adb transport is unreliable on old Android versions, which is why the fallback exists [unverified, from scrcpy FAQ memory]; not a concern for our Android 14+ floor.
Options for Tether:
adb reverse | adb forward | Helper dials daemon over LAN TLS | |
|---|---|---|---|
| Works over USB and Wi-Fi alike | Yes | Yes | Wi-Fi only |
| Startup race | None | Needs retry or dummy byte | None |
| Path | helper, adbd, TLS, adb server, daemon (two extra hops, one multiplexed TCP connection) | same | one hop, separate TCP connections |
| Head-of-line blocking between video/audio/control | Yes, all adb streams share one TCP connection | Yes | No |
| Extra crypto and auth in the helper | None (adb TLS already protects it) | None | TLS + pinning + token |
| Firewall | Nothing new | Nothing new | Needs the daemon port reachable (ufw profile exists for 7360) |
| Fits ADR-0014 secondary streams | Framing reused, transport differs | same | Yes, directly |
Latency: scrcpy’s 35 to 70 ms figures are achieved through the adb tunnel, over USB and Wi-Fi, so the tunnel is not the limiting factor on a good LAN. The risk is Wi-Fi loss: a retransmit stalls every stream at once.
Recommendation.
- M4 baseline:
adb reverse localabstract:tether_<8 hex> <host spec>where the host side is a daemon listener:localfilesystem:$XDG_RUNTIME_DIR/tether/shell-<id>.sock[unverified with distro adb], elsetcp:<ephemeral port bound on 127.0.0.1>. Set it up before launching the helper and remove it (adb reverse --remove) at stop. Reverse entries vanish when the transport drops; re-create on every launch. - Open one connection per purpose (control, video per mirror, audio), each starting with
the existing
StreamOpenenvelope plus the launch token, so the code path matches ADR-0014 streams and the transport can be swapped. - Keep the one-time token even with reverse: other processes on the phone may be able to reach an abstract socket, and with the TCP fallback any local desktop user can reach the port.
- Pass the token on the helper’s stdin, not argv (argv is visible in
psto other shell-uid processes). - Add direct LAN TLS later only if measurements on Wi-Fi show stalls; the helper (shell uid) may open network sockets, and the protocol will not need to change.
Sources:
- https://github.com/Genymobile/scrcpy/blob/master/doc/develop.md
- https://github.com/Genymobile/scrcpy/blob/master/doc/tunnels.md
- https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/dev/services.md (
reverse:)
A.7 Minimum adb version and detection
Relevant history [verified-src, release notes]: 30.0.0 wireless pairing; 31.0.2
track-devices fix for wireless; 33.0.3 duplicate entry fix, rejects unexpected reverse
requests; 34.0.5 adb pair returns non-zero on failure and wait-for-disconnect works
for wireless; 35.0.2 openscreen default.
Available: Ubuntu 24.04 / Mint 22 adb 34.0.4; Debian 13 34.0.5; Debian 12 29.0.6 (too
old; backports has 34.0.5); Google installer package 35.0.0; SDK 37.x.
Detection: run adb version; the second line is Version <major>.<minor>.<patch>-<build>
(Version 35.0.0-11411520 here [verified-local]; Debian builds print a -debian
suffix [unverified]). Parse with ^Version (\d+)\.(\d+)\.(\d+). The first line
(Android Debug Bridge version 1.0.41) is the protocol version and is useless for this.
Binary lookup order: config adb.path, then adb on PATH, then
$ANDROID_HOME/platform-tools/adb, $ANDROID_SDK_ROOT/platform-tools/adb,
~/Android/Sdk/platform-tools/adb. Use the first that meets the minimum; log the path and
version; expose both over D-Bus for the wizard.
Recommendation. Require >= 34.0.0 (as the roadmap says). Treat 34.0.x pair/connect
exit codes as unreliable and parse output. Keep adb in Depends (the Google installer
package satisfies it through Provides: adb). If adb is missing or too old the enhanced
tier reports “unavailable” with the reason; the normal tier is unaffected.
Sources:
- https://developer.android.com/tools/releases/platform-tools
- https://packages.debian.org/search?keywords=adb&searchon=names&exact=1
B. Video in the GTK4 app
B.1 Decoding and display options
Assumed plumbing: the daemon owns adb and the helper sockets. The GTK app gets the video stream as a unix socket file descriptor passed over D-Bus (zbus supports fd passing), with the same framing as the helper stream (header with PTS, flags, length, then one Annex-B access unit). The app does not talk to adb.
Option 1: GStreamer + gtk4paintablesink (recommended)
Availability of the sink [verified-src / verified-local]:
| Distro | Package | Version |
|---|---|---|
| Ubuntu 24.04 / Mint 22 | none. Only librust-gst-plugin-gtk4-dev 0.12.3 (Rust source, universe). gst-inspect-1.0 gtk4paintablesink fails here | n/a |
| Debian 13 | gstreamer1.0-gtk4 | 0.13.5-1 |
| Ubuntu 26.04 | gstreamer1.0-gtk4 | 0.14.4 (component not checked, probably universe) |
So on our oldest targets the plugin does not exist as a package and we must link it
statically. Versions that fit the workspace (gtk4 0.9, rust-version 1.85)
[verified-src, crates.io]:
gst-plugin-gtk40.13.x (0.13.7): depends ongtk4 ^0.9,gstreamer ^0.23, MSRV 1.71, licence MPL-2.0 (compatible with GPL-3.0-or-later).- 0.14.x needs
gtk4 0.10/gstreamer 0.24; 0.15.x needsgtk4 0.11/gstreamer 0.25and Rust 1.92. Moving up means bumping gtk4-rs for the whole app. - 0.13 features:
wayland(=waylandegl),x11egl,x11glx,dmabuf(pullsgtk_v4_14andgst-video/v1_24),gtk_v4_10/12/14/16.
# desktop/crates/tether-gtk/Cargo.toml
gst = { package = "gstreamer", version = "0.23" }
gst-app = { package = "gstreamer-app", version = "0.23" }
gst-video = { package = "gstreamer-video", version = "0.23" }
gst-plugin-gtk4 = { version = "0.13", features = ["wayland", "x11egl", "x11glx", "dmabuf", "gtk_v4_14"] }
#![allow(unused)]
fn main() {
gst::init()?;
gstgtk4::plugin_register_static()?; // registers gtk4paintablesink in-process
let sink = gst::ElementFactory::make("gtk4paintablesink").build()?;
let paintable = sink.property::<gdk::Paintable>("paintable");
// If the paintable has a GL context, wrap the sink so upload and colour conversion run in GL.
let video_sink = if paintable.property::<Option<gdk::GLContext>>("gl-context").is_some() {
gst::ElementFactory::make("glsinkbin").property("sink", &sink).build()?
} else {
sink.upcast() // put `videoconvert` in front in this case
};
picture.set_paintable(Some(&paintable)); // gtk::Picture, content-fit = Contain
}
The crate name in code is gstgtk4. This registration pattern is the documented way
applications embed the plugin, but the README fetched for this research did not show it,
so treat the snippet as [unverified] until it compiles. glsinkbin lives in
gstreamer1.0-gl [verified-local].
GL and dmabuf paths:
- X11 (Cinnamon, the primary dev setup):
x11eglandx11glxlet hardware or GL-uploaded frames reach GTK asGdkGLTexturewith no CPU copy. Enable both; GTK picks EGL or GLX depending on the driver. - Wayland (GNOME):
waylandfor GL textures, anddmabuf(GTK >= 4.14, GStreamer >= 1.24, both exactly what Ubuntu 24.04 has) letsvah264decoutputvideo/x-raw(memory:DMABuf)straight into aGdkDmabufTexture. Wrapping the picture inGtkGraphicsOffload(GTK 4.14) can hand it to the compositor as a subsurface. - No GL context (software renderer, remote X): the sink accepts system-memory frames; slower but works.
Decoders [verified-local unless marked]:
| Element | Package (Ubuntu 24.04) | Hardware | State on this machine |
|---|---|---|---|
vah264dec | gstreamer1.0-plugins-bad (universe), libgstva.so | Intel / AMD through VA-API | Plugin file installed, element not registered (NVIDIA-only GPU, no usable VA driver) |
nvh264dec | gstreamer1.0-plugins-bad, libgstnvcodec.so | NVIDIA proprietary driver | Present, rank primary+1, outputs CUDAMemory, GLMemory or system NV12 |
vaapih264dec | gstreamer1.0-vaapi (universe) | legacy VA plugin, deprecated upstream | Package installed, element not registered |
v4l2h264dec / v4l2slh264dec | gstreamer1.0-plugins-good | ARM SBCs, some laptops | Not present |
avdec_h264 | gstreamer1.0-libav (universe) | software (FFmpeg) | Present |
openh264dec | gstreamer1.0-plugins-bad | software | Present |
h264parse | gstreamer1.0-plugins-bad (libgstvideoparsersbad.so) | n/a | Present |
Selection: build the pipeline with an explicit candidate list and take the first factory
that exists and reaches PAUSED with the stream’s caps: vah264dec, nvh264dec,
v4l2slh264dec, avdec_h264, openh264dec. On error at runtime fall back to the next and
request a key frame. Expose a “software decoding” switch in preferences and an env override
(TETHER_VIDEO_DECODER).
Option 2: FFmpeg (ffmpeg-next 9.1.0, WTFPL; ac-ffmpeg 0.19, MIT) + our own texture upload
- This is what scrcpy does in C. We would decode to
AVFrame, convert (swscale) and buildGdkMemoryTextures per frame, or wire VA-API/NVDEC hwaccel and dmabuf export ourselves for zero copy. - Packaging blocker: libavcodec’s soname differs between targets (FFmpeg 6.1 in Ubuntu
24.04, 7.1 in Debian 13), so one
.debcannot link dynamically against both. We would need per-distro builds or a statically bundled FFmpeg. GStreamer 1.x keeps one ABI, so a binary built on Ubuntu 24.04 runs on Debian 13. - More code for less: hardware paths, colour handling and GL upload are all ours.
Option 3: VA-API directly. Needs our own H.264 bitstream parsing and DPB management (or
the cros-codecs crate), covers Intel/AMD only, and still needs a software fallback.
Rejected.
Recommendation. GStreamer through gstreamer-rs 0.23 with gst-plugin-gtk4 0.13 linked
statically, features wayland,x11egl,x11glx,dmabuf,gtk_v4_14; pipeline
appsrc ! h264parse ! <decoder> ! glsinkbin sink=gtk4paintablesink; explicit decoder
fallback list. Put it behind a cargo feature (mirror, default on) so --mock UI work
does not need GStreamer headers. The VA path cannot be tested on this machine; it needs an
Intel or AMD box (or CI smoke tests on software decode only).
Sources:
- https://packages.debian.org/search?keywords=gstreamer1.0-gtk4 , https://packages.ubuntu.com/search?keywords=gstreamer1.0-gtk4
- https://crates.io/crates/gst-plugin-gtk4 (versions, features, dependencies)
- https://github.com/GStreamer/gst-plugins-rs/blob/main/video/gtk4/README.md
- https://crates.io/crates/ffmpeg-next , https://crates.io/crates/ac-ffmpeg
B.2 Low-latency pipeline settings
Properties below exist in GStreamer 1.24.2 here [verified-local via gst-inspect]; the latency effects are from GStreamer/scrcpy practice and should be measured [unverified].
- appsrc:
is-live=true,format=time,stream-type=stream,do-timestamp=true(arrival-time stamping; we render unsynchronised anyway),block=false,max-buffers=4,leaky-type=none. Do not let appsrc drop encoded frames: dropping a P-frame corrupts everything until the next key frame. If the queue ever exceeds the bound, flush and ask the helper for a key frame instead. - caps on appsrc:
video/x-h264,stream-format=byte-stream,alignment=au. Declaring access-unit alignment letsh264parseforward each buffer immediately instead of waiting for the start of the next AU (one frame of latency saved). Requires the helper to send exactly one AU per message, with SPS/PPS prepended to the first key frame (scrcpy merges the config packet into the next frame for the same reason). - h264parse: defaults; it also gives decoders the framerate/resolution caps they need.
- Decoders:
avdec_h264:max-threads=1orthread-type=slice. Frame threading (the default with auto threads) adds one frame of delay per thread. FFmpeg may also hold frames for reordering if the SPS lacksbitstream_restriction; scrcpy setsAV_CODEC_FLAG_LOW_DELAY, whichavdec_h264does not expose as a property. Measure; if output lags by frames, preferopenh264decor fix on the encoder side (baseline / no B-frames,KEY_LATENCY=0/KEY_LOW_LATENCY=1,KEY_MAX_B_FRAMES=0).nvh264dec:max-display-delay=0.vah264dec: no property needed; the base class uses low-latency bumping for live pipelines, which is another reason foris-live=true[unverified for 1.24].
- After the decoder:
queue max-size-buffers=1 max-size-bytes=0 max-size-time=0 leaky=downstream. Decoded frames are safe to drop; this keeps only the newest frame when the UI thread is slow. - Sink:
sync=falseon the sink (glsinkbinproxies it),qos=false. No clock synchronisation; show frames as they arrive, like scrcpy. Pipelinelatencystays default. - Session changes: on rotation or flex-resize the helper starts a new stream with new
SPS/PPS;
h264parserenegotiates caps. Verify that every decoder in the list survives a mid-stream resolution change; otherwise rebuild the pipeline on the session packet. - Static screens: the Android encoder emits frames only when the surface changes. Set
KEY_REPEAT_PREVIOUS_FRAME_AFTER(scrcpy uses 100 ms) in the helper so the first frame arrives and quality recovers after motion. - Stats for the “<= 100 ms” verification: timestamp at socket read and in a pad probe on the sink; expose frames dropped, decode ms and decoder name in a debug overlay.
Sources:
- https://github.com/Genymobile/scrcpy/blob/master/doc/develop.md
gst-inspect-1.0 appsrc | avdec_h264 | nvh264dec | h264parseon this machine
B.3 Build and packaging impact
Build dependencies (Ubuntu 24.04 names; none of the -dev packages is installed on this
machine yet, pkg-config --modversion gstreamer-1.0 fails [verified-local]):
libgstreamer1.0-dev(1.24.2)libgstreamer-plugins-base1.0-dev(app, video, gl, allocators.pcfiles; pulls GL/EGL headers)- existing:
libgtk-4-dev,libadwaita-1-dev libgstreamer-plugins-bad1.0-devis not needed.
CI (ubuntu-24.04 runner): add libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev to
both apt steps in the workflow; for pipeline smoke tests also
gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav gstreamer1.0-gl and run under xvfb-run with software GL. Build on
24.04 (oldest GStreamer/GTK/glibc) so the binary runs on Debian 13 (GStreamer 1.26.2, GTK
4.18.6, libadwaita 1.7.6, PipeWire 1.4.2).
Runtime metadata for [package.metadata.deb] in desktop/crates/tetherd/Cargo.toml:
$autowill addlibgstreamer1.0-0,libgstreamer-plugins-base1.0-0,libgstreamer-gl1.0-0.- Add to
depends:gstreamer1.0-plugins-base(app, opus, audioconvert, videoconvert),gstreamer1.0-plugins-good(v4l2sink, pulse),gstreamer1.0-gl(glsinkbin). - Add to
recommends:gstreamer1.0-plugins-bad(h264parse and all hardware decoders; effectively required for mirroring),gstreamer1.0-libav(software H.264/H.265),gstreamer1.0-pipewire. Both-badand-libavare in universe on Ubuntu and main on Debian. If we want mirroring to work on a default install, promotegstreamer1.0-plugins-badandgstreamer1.0-libavtodepends; Mint enables universe by default and already ships both. - Add to
suggests:v4l2loopback-dkms. - No
gstreamer1.0-gtk4dependency (static). - At startup, check for
h264parseand at least one decoder; show a precise “install gstreamer1.0-plugins-bad / gstreamer1.0-libav” message instead of a pipeline error.
Size: release binaries today are tether 6.6 MB and tetherd 12.1 MB (stripped, thin
LTO). Expect a few MB more for tether from gstreamer-rs bindings and the static sink
[unverified estimate]; GStreamer itself stays dynamic. Build time grows noticeably
(gstreamer-gl and friends).
Sources: local apt-cache policy/show, dpkg -S; https://sources.debian.org (trixie versions).
B.4 H.265 and AV1 later
| Codec | Hardware elements | Software elements | Here (Ubuntu 24.04 base) |
|---|---|---|---|
| H.265 | vah265dec, nvh265dec, vulkanh265dec | avdec_h265 (libav), libde265dec (bad) | nvh265dec, avdec_h265, libde265dec, vulkanh265dec present; vah265dec not registered |
| AV1 | vaav1dec, nvav1dec | av1dec (libaom, slow), dav1ddec (not in 24.04’s packages) | nvav1dec, av1dec present; dav1ddec, vaav1dec absent |
Parsers h265parse and av1parse are in gstreamer1.0-plugins-bad. Whether Debian 13’s
GStreamer 1.26 ships dav1ddec was not checked [unverified].
Recommendation. H.264 only in M4. Design MirrorStart.codec negotiation now: the
desktop probes factories at startup and sends the list it can decode (hardware first); the
helper intersects with its encoders. Add H.265 next (wide hardware support on both ends,
real bitrate saving on Wi-Fi). AV1 only when a hardware decoder is present; software AV1 at
phone resolution is not viable with av1dec.
C. Audio and webcam
C.1 Opus to PipeWire playback
Ownership: the daemon should own phone audio (and the webcam), so both work with the
GTK window closed, like call audio does today. The daemon already shells out to
wpctl/pw-link/pipewire and depends on pipewire-bin.
Options:
| Option | Pros | Cons |
|---|---|---|
GStreamer in tetherd: appsrc ! opusdec ! audioconvert ! audioresample ! sink | One media stack shared with webcam; opusdec has PLC and in-band FEC (plc, use-inband-fec); sinks handle device changes and clock drift; all elements installed by default here | tetherd links GStreamer (glib main context not needed for appsrc pipelines, but a bus watch thread is) |
opus crate 0.4 (MIT/Apache, libopus) + pw-cat --playback --raw - | Tiny; no new library in the daemon beyond libopus | Pipe buffering (default pipe is 64 KiB, about 340 ms of 48 kHz stereo s16) must be shrunk; no drift compensation; underrun handling is ours; one more subprocess to supervise |
opus + pipewire crate 0.10 (MIT) | Lowest latency, real graph node | Needs libpipewire-0.3-dev + clang/bindgen at build, own PipeWire main-loop thread, compatibility with PipeWire 1.0.5 not checked [unverified] |
opus + cpal 0.18 (Apache-2.0) | Portable | Goes through ALSA to pipewire-alsa: extra buffering, poor device naming |
audiopus (ISC) has had no release since 2021; prefer opus if a pure-crate decoder is
ever needed.
Sink choice [verified-local for presence]: pulsesink (talks to pipewire-pulse, the
best-tested path on PipeWire 1.0.x), pipewiresink (gstreamer1.0-pipewire, main; fine
for video, historically rougher for audio on 1.0.x [unverified]), autoaudiosink. Try
pulsesink, then pipewiresink, then autoaudiosink.
Latency settings:
- Helper: Opus 48 kHz stereo, 10 or 20 ms frames, one packet per message with PTS.
- appsrc:
is-live=true format=time do-timestamp=true, capsaudio/x-opus,channel-mapping-family=0,channels=2,rate=48000. - pulsesink:
buffer-time=40000 latency-time=10000(40 ms target, 10 ms periods),stream-properties="props,media.role=Music,application.name=Tether,node.name=tether_phone_audio". - Keep
sync=trueon the audio sink with arrival timestamps so the sink’s clock slaving absorbs phone/PC drift; cap backlog by flushing when appsrc holds more than about 150 ms. scrcpy targets a 50 ms audio buffer and compensates drift by resampling. - There is no lip-sync between audio (daemon) and video (GTK app, unsynchronised). With both under about 100 ms this matches scrcpy’s behaviour and is acceptable for M4.
- When phone audio is captured with
REMOTE_SUBMIXthe phone goes silent;PLAYBACK_DUPkeeps it audible (Android 13+ in scrcpy terms). That is a helper decision, noted here because the desktop toggle needs both labels. - Calls: do not start phone audio while an HFP call is active, or mute it (interaction with the M3 call-audio graph).
Recommendation. GStreamer in tetherd behind a cargo feature media (default on):
appsrc ! opusdec plc=true ! audioconvert ! audioresample ! pulsesink with the fallback
order above. The same feature hosts the webcam pipeline (C.2), so the dependency is paid
once. The roadmap’s opusdec ! pipewiresink becomes the second choice of sink, not the
first.
Sources: local gst-inspect-1.0 opusdec | pipewiresink; crates.io (opus, audiopus,
pipewire, cpal); https://github.com/Genymobile/scrcpy/blob/master/doc/develop.md
C.2 Phone as webcam
v4l2loopback
| Distro | Package | Version | Component |
|---|---|---|---|
| Ubuntu 24.04 / Mint 22 | v4l2loopback-dkms, v4l2loopback-utils | 0.12.7-2ubuntu5.2 | universe |
| Debian 13 | v4l2loopback-dkms | 0.15.0-2 | main |
On this machine [verified-local]: v4l2loopback-dkms 0.12.7-2ubuntu5.1 is installed
and DKMS has built it for 6.17.0-1032-oem and 6.17.0-35-generic (older OEM kernels show
DKMS warnings), modinfo v4l2loopback resolves, the module is not loaded, Secure Boot
is disabled, /dev/video0-1 are the integrated camera. So Ubuntu’s patched 0.12.7 does
build on an OEM 6.17 kernel, but every kernel update re-runs DKMS and can break it.
Constraints:
- Out-of-tree module: needs
dkms, kernel headers and a compiler on the user’s machine. - Secure Boot: the module must be signed with an enrolled MOK. Ubuntu’s DKMS signs with
the machine owner key and prompts for enrolment (reboot + MOK manager) the first time; on
Debian the user must
mokutil --importthe DKMS key manually. Until enrolled,modprobefails with “Key was rejected by service”. We cannot automate this. - Creating the device needs root:
modprobe v4l2loopback devices=1 video_nr=<N> card_label="Tether Phone Camera" exclusive_caps=1, or persistently/etc/modprobe.d/*.conf+/etc/modules-load.d/*.conf.exclusive_caps=1is needed for Chromium-based apps to list the device.v4l2loopback-ctl add(dynamic devices through/dev/v4l2loopback) also needs root and its availability in 0.12.7 is [unverified]. - If another tool already loaded the module (OBS), reuse an existing free loopback device instead of reloading.
- Once the node exists the daemon can write to it as the session user (udev
uaccess/videogroup).
Feeding: appsrc ! h264parse ! <decoder> ! videoconvert ! videoscale ! video/x-raw,format=YUY2,width=W,height=H,framerate=F/1 ! v4l2sink device=/dev/videoN sync=false. Keep format and size fixed for the lifetime of the device (letterbox on
rotation); consumers do not cope with format changes. v4l2sink is in
gstreamer1.0-plugins-good. v4l2sink against loopback 0.12.7 with GStreamer 1.24 needs a
quick spike (there have been negotiation regressions between specific versions)
[unverified].
Detection for guidance: /sys/module/v4l2loopback (loaded), modinfo v4l2loopback
(installed), /sys/devices/virtual/video4linux/video*/name (find our label),
mokutil --sb-state, and the modprobe error text.
PipeWire virtual camera (no kernel module)
... ! videoconvert ! pipewiresink mode=provide stream-properties="props,media.class=Video/Source,media.role=Camera,node.description=Tether Phone Camera"creates a camera node in the session; no root, no DKMS, no Secure Boot issue. (pipewiresinkhasmodeandstream-propertieshere [verified-local]; the exact property string is from published examples and is [unverified] on 1.0.5.)- Who sees it (2026) [mostly unverified, moving target]:
- Firefox: PipeWire camera backend exists (
media.webrtc.camera.allow-pipewire), default on in Fedora since 41, apparently still off by default upstream; a December 2025 Ubuntu bug shows users setting the pref by hand and the snap unable to reach PipeWire cameras. - Chromium/Chrome: PipeWire camera landed in M127 behind a flag, official builds fixed around M132; default state today not confirmed.
- OBS Studio: PipeWire camera source (beta) since 30.2; GNOME Snapshot uses PipeWire natively.
- Zoom, Teams, Discord, Slack desktop clients and most Electron apps: V4L2 only.
- Access goes through the xdg-desktop-portal Camera portal (1.20 here and in Debian 13).
- Firefox: PipeWire camera backend exists (
- Conclusion: on Mint 22 / Ubuntu 24.04 with default browsers the PipeWire node will not show up in a typical video call without the user flipping a browser pref. It does not satisfy the M4 verification line “webcam appears in a video call app” by itself.
Recommendation.
- M4: v4l2loopback path.
Suggests: v4l2loopback-dkms; a “Set up webcam” page that detects state (not installed / installed not loaded / Secure Boot key rejected / ready) and runs onepkexec modprobe ...on request, plus an optional “load at boot” step that writes the two config files through the same polkit prompt. Never load the module implicitly. - Build the webcam pipeline with a
teeso a PipeWireVideo/Sourceoutput can be added as a second, zero-setup sink; ship it in M4 only if the spike on PipeWire 1.0.5 is clean, labelled “works in apps with PipeWire camera support”. - Revisit the default once Firefox and Chromium enable PipeWire cameras by default on the target distros.
Sources:
- local
apt-cache policy v4l2loopback-dkms,dkms status,modinfo,mokutil --sb-state - https://sources.debian.org/src/v4l2loopback/ (trixie 0.15.0-2)
- https://www.phoronix.com/news/Fedora-41-Firefox-PipeWire-Cam
- https://www.phoronix.com/news/Chrome-127-PipeWire-Capture
- https://lists.ubuntu.com/archives/ubuntu-mozillateam-bugs/2025-December/182153.html
- https://ideasonboard.com/news/pipewire-is-the-new-v4l2loopback (could not be fetched, 403; cited from search summary)
D. Input mapping for the remote-control window
D.1 Event controllers
Attach to the widget that shows the video (a gtk::Picture inside a focusable container,
focusable=true, can-target=true, grab focus on click):
| Input | Controller | Notes |
|---|---|---|
| Mouse buttons | GestureClick with button=0 (all buttons) | pressed/released give widget coordinates; current_button() gives 1..9; current_event_state() gives modifiers |
| Pointer motion / hover | EventControllerMotion | Send move events while a button is held (drag); send hover moves only when no button is held and throttle to the frame rate |
| Wheel / touchpad scroll | EventControllerScroll with BOTH_AXES (not DISCRETE) | scroll(dx, dy); check unit() (GTK 4.8+): wheel units vs surface pixels. Accumulate and send floats |
| Keys | EventControllerKey | key-pressed(keyval, keycode, state) / key-released; attach the IM context with set_im_context |
| Text | GtkIMMulticontext | commit(str) gives composed text (dead keys, compose, IBus/Fcitx) |
| Touchscreen | EventControllerLegacy | Raw GdkEvent: TouchBegin/Update/End/Cancel, event_sequence() maps to pointer_id; gives true multi-touch |
| Touchpad pinch | GestureZoom | Translate to a two-pointer gesture around the pointer position |
| Focus loss | EventControllerFocus | On leave: release every pressed key and pointer (send UP/CANCEL) to avoid stuck input |
| File drop | DropTarget (gdk::FileList) | Later: push file / install APK, as scrcpy does |
Mouse-emulated touch uses one fixed pointer id (scrcpy reserves special ids for mouse and for the virtual second finger), real touch sequences get ids from a small allocator.
D.2 Coordinate mapping with letterboxing
With gtk::Picture content-fit=Contain, widget size (w, h) in logical pixels and
current video size (vw, vh):
s = min(w / vw, h / vh)
ox = (w - vw * s) / 2 oy = (h - vh * s) / 2
x' = (x - ox) / s y' = (y - oy) / s
- Ignore presses that start in the bars; clamp moves and releases of an ongoing drag to
[0, vw-1] x [0, vh-1]. - Scale factor (HiDPI) cancels out because only ratios are used.
- Send the frame size the coordinates refer to with every event (scrcpy sends position
plus screen size) so the helper can rescale or drop events that raced with a rotation or
a flex-resize. This suggests adding
frame_w/frame_htoInputEvent.touchandInputEvent.scrollin the protocol. (vw, vh)comes from the stream’s session packet / negotiated caps, never from the widget.- For window resize driving a display resize (NEW_DISPLAY / flex): debounce to about 200 ms, round to multiples of 8, keep letterboxing active in between.
D.3 Keys: keycodes or committed text
scrcpy’s SDK keyboard [verified-src, doc/keyboard.md]: letters and control keys go as
key events (so games get real key down/up), other printable characters go as text events;
--prefer-text sends letters as text too; --raw-key-events sends everything as key
events. Text injection in this mode is limited to ASCII plus a few characters; scrcpy’s
answer for everything else is a simulated HID keyboard (UHID), which needs the phone’s
layout to match.
Proposed rule for Tether:
- In
key-pressed, if Ctrl, Alt or Super is held, or the keyval is non-printing (navigation, editing, function, modifier, media keys): sendInputEvent.keywith an Android keycode and metastate, on press and on release. - Otherwise let the IM context filter the event; on
commit(str)sendInputEvent.text{utf8}. - Helper side: inject ASCII through
KeyCharacterMapevents; for anything else set the clipboard and inject paste, or (later) a UHID keyboard. This is the same limitation scrcpy has and should be stated in the UI docs. - A “game mode / raw keys” toggle sends every key as a key event (WASD).
- Key repeat: forward repeats with a repeat count; allow disabling.
Keyval to Android keycode (values are android.view.KeyEvent constants, from memory,
check against the SDK when writing the table):
| GDK keyval | Android | GDK keyval | Android | |
|---|---|---|---|---|
Return, KP_Enter | ENTER 66 | Up/Down/Left/Right | DPAD 19/20/21/22 | |
BackSpace | DEL 67 | Home / End | MOVE_HOME 122 / MOVE_END 123 | |
Delete | FORWARD_DEL 112 | Page_Up / Page_Down | 92 / 93 | |
Tab | TAB 61 | Insert | 124 | |
Escape | ESCAPE 111 | F1..F12 | 131..142 | |
space | SPACE 62 | a..z | A..Z 29..54 | |
0..9 | 7..16 | Shift_L/R | 59 / 60 | |
Control_L/R | 113 / 114 | Alt_L/R | 57 / 58 | |
Super_L/R | META 117 / 118 | Menu | MENU 82 | |
Caps_Lock | 115 | XF86AudioRaiseVolume/LowerVolume/Mute | 24 / 25 / 164 | |
XF86AudioPlay | MEDIA_PLAY_PAUSE 85 | (navigation) | BACK 4, HOME 3, APP_SWITCH 187, POWER 26 |
Metastate: SHIFT 0x1, ALT 0x2, CTRL 0x1000, META 0x10000 (plus the left/right bits if
needed). Use the keyval lowered with gdk::Key::to_lower() for letters so Shift state
travels in the metastate, not in the keycode choice.
D.4 Mouse buttons and shortcuts (scrcpy defaults)
Mouse [verified-src, doc/mouse.md]; scrcpy’s default is --mouse-bind=bhsn:++++:
| Button | Default | With Shift |
|---|---|---|
| Left | touch / click | n/a |
| Right | BACK (wakes the screen if it is off) | forwarded as a real secondary click |
| Middle | HOME | forwarded |
| 4th | APP_SWITCH | forwarded |
| 5th | expand notification panel | forwarded |
Hover is forwarded by default. Ctrl + drag simulates pinch-to-zoom/rotate around the centre, Shift + drag a vertical two-finger tilt, Ctrl + Shift + drag a horizontal one. Double-click on the black bars removes them (resize window to content).
Shortcuts [verified-src, doc/shortcuts.md]: scrcpy uses MOD = left Alt or left Super; MOD+h HOME, MOD+b / MOD+Backspace BACK, MOD+s APP_SWITCH, MOD+m MENU, MOD+Up/Down volume, MOD+p POWER, MOD+o screen off (keep mirroring), MOD+Shift+o screen on, MOD+r rotate, MOD+n / MOD+Shift+n notification panel, MOD+f fullscreen, MOD+g 1:1, MOD+w fit window, MOD+c / MOD+x copy / cut, MOD+v sync clipboard and paste, MOD+Shift+v inject clipboard as typed text. All plain Ctrl+key combinations are forwarded to the device.
Adjustments for a GTK app on GNOME and Cinnamon:
- Super combinations are taken by the shell, and Alt+drag moves windows on Cinnamon. Use left Alt as MOD by default, configurable, and give every action a header-bar button or menu entry (Back, Home, Recents, Power, Volume, Screen off, Rotate, Fit, Fullscreen) so no shortcut is required.
- Forward Ctrl+key to the phone (Ctrl+C/X/V/A/Z work in Android text fields). On Ctrl+V, first push the desktop clipboard to the phone, then forward the key, which gives the expected paste. Ctrl+Shift+V types the clipboard as text.
- F11 toggles fullscreen locally; Escape is forwarded (Android treats it as Back).
- Optional:
gdk::Toplevel::inhibit_system_shortcutswhile the pointer is inside and a “capture keyboard” toggle is on, so Alt+Tab reaches the phone. - Scroll: one wheel notch = 1.0 scroll unit; for smooth scrolling divide pixel deltas by a fixed step (about 50 px) and send fractional values; natural-scroll direction follows the desktop setting automatically because GDK already applies it.
Recommendation. Use the controller set in D.1, the letterbox mapping in D.2 with the
frame size carried in each event, the hybrid key/text rule in D.3, and scrcpy’s
bhsn:++++ mouse defaults with left Alt as the shortcut modifier plus visible buttons for
every navigation action. Add frame_w/frame_h (and a mouse buttons mask if hover and
real secondary clicks are wanted) to the InputEvent messages before the protocol is
frozen.
Sources:
- https://github.com/Genymobile/scrcpy/blob/master/doc/mouse.md
- https://github.com/Genymobile/scrcpy/blob/master/doc/keyboard.md
- https://github.com/Genymobile/scrcpy/blob/master/doc/shortcuts.md
- https://github.com/Genymobile/scrcpy/blob/master/doc/develop.md
Open items to spike first
adb -L localfilesystem:...server socket andadb reverse ... localfilesystem:...with distro adb 34.0.4 / 34.0.5; exactadb connect/adb pairoutput strings on 34.x.- Whether Ubuntu’s adb 34.0.4 has mDNS stubbed like Debian’s (expected yes; irrelevant if
we set
ADB_MDNS=0and use Avahi). - QR pairing on One UI: is the
studio-prefix required, and does the Settings scanner accept our payload. gstgtk4::plugin_register_static()build with gtk4 0.9 / gstreamer 0.23 on Ubuntu 24.04;nvh264decto GL texture on X11 with the NVIDIA driver; frame delay ofavdec_h264with a MediaCodec stream.- A VA-API test machine (Intel/AMD) for
vah264decand the dmabuf path on Wayland. v4l2sinkinto v4l2loopback 0.12.7 with GStreamer 1.24;pipewiresink mode=providecamera node on PipeWire 1.0.5 and which apps list it.- Re-enabling Wireless debugging from the app with
WRITE_SECURE_SETTINGSon One UI. - Auto Blocker’s effect on Wireless debugging (as opposed to USB) on One UI 7.