Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.0 were 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

TopicChoice
Pairing UXQR flow primary (WIFI:T:ADB;S:studio-<10>;P:<12>;;), 6-digit code as fallback; both discover the pairing port through Avahi
Connect-port discoveryOur own Avahi browse of _adb-tls-connect._tcp, then adb connect ip:port. Never rely on adb’s built-in mDNS
adb server and keyPrivate 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 integrationShell out to the adb binary; speak the host protocol directly only for host:track-devices
Helper transportadb reverse localabstract:tether_<id> to a daemon listener, separate sockets for control/video/audio, token kept. Direct LAN TLS is a later optimisation
Minimum adb34.0.0 (parse adb version); never trust adb pair/adb connect exit codes, parse stdout
VideoGStreamer via gstreamer-rs 0.23 + gst-plugin-gtk4 0.13 linked statically; appsrc ! h264parse ! <dec> ! glsinkbin(gtk4paintablesink)
AudioGStreamer in the daemon: `appsrc ! opusdec ! audioconvert ! audioresample ! pulsesink
Webcamv4l2loopback + v4l2sink first (only path every call app sees); PipeWire Video/Source node as a no-root second output
InputGestureClick + 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: legacy adb tcpip listener.
    • _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 is persist.adb.wifi.guid and 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>.
  • 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

  1. Phone: Developer options, Wireless debugging, “Pair device with pairing code”. The dialog shows a 6-digit code and ip:port.
  2. Desktop: adb pair <ip>:<port> <code> (code may also be given on stdin after the Enter pairing code: prompt).
  3. Success output: Successfully paired to <ip>:<port> [guid=adb-<serial>-<suffix>]; failure: Failed: Wrong password or connection was dropped. (strings from client/adb_wifi.cpp, platform-tools 35.0.2 [verified-src]). adb then writes the guid to adb_known_hosts.pb and tries to connect by service name.
  4. We do not need the user to read the ip:port: browse _adb-tls-pairing._tcp with Avahi and take the address and port from the resolved record; the user types six digits only.

QR flow (what Android Studio does)

  1. 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).
  2. Phone: Wireless debugging, “Pair device with QR code”, scan. Seeing T:ADB, the phone starts a Pairing Server and advertises _adb-tls-pairing._tcp with instance name <name>.
  3. 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 uses debug), so the prefix is probably not enforced [unverified]; keep studio- 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 qrcode crate 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]:

VersionmDNS backend
30.0.0wireless pairing added; mDNS needs a Bonjour daemon (mdnsResponder)
30.0.2mDNS auto-connect off by default (ADB_MDNS_AUTO_CONNECT)
31.0.2embedded openscreen backend added, off by default (ADB_MDNS_OPENSCREEN=1)
35.0.2openscreen default on all platforms
37.0.0new default backend libadbmdns, openscreen deprecated
37.0.1openscreen deleted; ADB_MDNS_OPENSCREEN has no effect

What the distributions ship:

  • Debian 13 (trixie): adb 1: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.mk generates a file with empty init_mdns_transport_discovery(), mdns_check() returning "", and mdns_get_connect_service_info() returning nullopt; the openscreen and mdnsresponder sources are commented out in libadb.mk [verified-src]. So adb mdns services returns nothing and there is no auto-connect.
  • Ubuntu 24.04 / Mint 22: adb 1: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/adb is Google’s binary 35.0.0-11411520 from google-android-platform-tools-installer (multiverse, Provides: adb). It contains openscreen (host-features lists openscreen_mdns) but 35.0.0 still defaults to Bonjour, and adb mdns check answers ERROR: 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.

  1. Browse _adb-tls-connect._tcp (and _adb-tls-pairing._tcp during the wizard) with the existing Avahi D-Bus code. Resolve, prefer IPv4 (adb’s own listing is IPv4-only).
  2. Remember the guid printed by adb pair per 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).
  3. Start our adb server with ADB_MDNS=0 (honoured in client/main.cpp [verified-src]) so behaviour is the same on every adb build and adb never auto-connects behind our back.
  4. Because adb pair only auto-connects through adb’s mDNS, always follow a successful pair with our own adb connect.
  5. Serial to use afterwards: <ip>:<port> (what adb connect registers). Pass it with -s on every command.
  6. Optional later: the Tether Android app can report the port over the normal-tier connection (NsdManager discovery 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. Only HOME is 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; default tcp:localhost:5037.
  • ADB_USB=0 skips USB initialisation; ADB_MDNS=0 skips mDNS; ADB_REJECT_KILL_SERVER=1 makes the server ignore kill-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 devicesYes, 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 IDEKills 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 reusedYesNo, needs its own pairing (we drive pairing anyway)
USBOne server owns the USB interface, no contentionWould compete with the user’s server for the USB interface unless ADB_USB=0
RevocationMixed with the developer’s own authorisationSeparate key; “Revoke” still removes both on the phone
Local attack surfacetcp:localhost:5037 is reachable by every local userCan 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 either ADB_SERVER_SOCKET=localfilesystem:$XDG_RUNTIME_DIR/tether/adb.sock with adb -L <same> start-server, or ANDROID_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 if start-server fails.
  • Start the server explicitly (adb start-server) from the daemon and stop it with kill-server on 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/adbkey ourselves.

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

ObservationMeaningAction
Tether normal-tier link up, no _adb-tls-connect._tcp instance with our guidWireless 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 deviceReadyLaunch helper
adb connect prints failed to connect to ...: Connection refused or times outStale port or client isolation on the APRe-resolve; after N tries, guide
adb connect prints failed to authenticate to <ip:port> or tracker shows unauthorized on a TLS transportOur key was revoked (“Revoke USB debugging authorisations”, factory reset)Forget guid, run pairing wizard again
Tracker offlineTransport stalled (Wi-Fi sleep)adb disconnect <serial>, reconnect; adb reconnect offline
USB: unauthorizedRSA dialog waiting on the phonePrompt the user to accept
USB: no permissionsudev rules missingPoint at android-sdk-platform-tools-common / plugdev
USB: phone connected (normal tier knows) but nothing appears on the default serverUSB debugging off or blocked (Auto Blocker)Guide
Helper process (adb shell ... app_process) exits while tracker still says deviceHelper crashed or was killedRestart with backoff; report ShellHello missing

Notes:

  • adb connect and (before 34.0.5) adb pair return exit code 0 on failure; 34.0.5 fixed pair only [verified-src, release notes]. Ubuntu ships 34.0.4. Always parse stdout. The exact adb connect strings 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 write Settings.Global "adb_wifi_enabled" = 1 after 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 in Hello).
  • 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]:

CrateVersion (date)LicenceNotes
adb_client3.2.3 (2026-08)MITMost 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
mozdevice0.5.5 (2026-06)MPL-2.0Talks to an adb server only
forensic-adb0.8.1 (2025-03)MPL-2.0Tokio fork of mozdevice, server only
adbear0.1.1 (2024)n/aPairing 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 spake2 wire format [unverified]), keyed with TLS exported keying material, then AES-128-GCM framed PeerInfo exchange. 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.
  • adb is 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 to localabstract: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 reverse over 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 reverseadb forwardHelper dials daemon over LAN TLS
Works over USB and Wi-Fi alikeYesYesWi-Fi only
Startup raceNoneNeeds retry or dummy byteNone
Pathhelper, adbd, TLS, adb server, daemon (two extra hops, one multiplexed TCP connection)sameone hop, separate TCP connections
Head-of-line blocking between video/audio/controlYes, all adb streams share one TCP connectionYesNo
Extra crypto and auth in the helperNone (adb TLS already protects it)NoneTLS + pinning + token
FirewallNothing newNothing newNeeds the daemon port reachable (ufw profile exists for 7360)
Fits ADR-0014 secondary streamsFraming reused, transport differssameYes, 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.

  1. 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], else tcp:<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.
  2. Open one connection per purpose (control, video per mirror, audio), each starting with the existing StreamOpen envelope plus the launch token, so the code path matches ADR-0014 streams and the transport can be swapped.
  3. 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.
  4. Pass the token on the helper’s stdin, not argv (argv is visible in ps to other shell-uid processes).
  5. 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]:

DistroPackageVersion
Ubuntu 24.04 / Mint 22none. Only librust-gst-plugin-gtk4-dev 0.12.3 (Rust source, universe). gst-inspect-1.0 gtk4paintablesink fails heren/a
Debian 13gstreamer1.0-gtk40.13.5-1
Ubuntu 26.04gstreamer1.0-gtk40.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-gtk4 0.13.x (0.13.7): depends on gtk4 ^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 needs gtk4 0.11 / gstreamer 0.25 and Rust 1.92. Moving up means bumping gtk4-rs for the whole app.
  • 0.13 features: wayland (= waylandegl), x11egl, x11glx, dmabuf (pulls gtk_v4_14 and gst-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): x11egl and x11glx let hardware or GL-uploaded frames reach GTK as GdkGLTexture with no CPU copy. Enable both; GTK picks EGL or GLX depending on the driver.
  • Wayland (GNOME): wayland for GL textures, and dmabuf (GTK >= 4.14, GStreamer >= 1.24, both exactly what Ubuntu 24.04 has) lets vah264dec output video/x-raw(memory:DMABuf) straight into a GdkDmabufTexture. Wrapping the picture in GtkGraphicsOffload (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]:

ElementPackage (Ubuntu 24.04)HardwareState on this machine
vah264decgstreamer1.0-plugins-bad (universe), libgstva.soIntel / AMD through VA-APIPlugin file installed, element not registered (NVIDIA-only GPU, no usable VA driver)
nvh264decgstreamer1.0-plugins-bad, libgstnvcodec.soNVIDIA proprietary driverPresent, rank primary+1, outputs CUDAMemory, GLMemory or system NV12
vaapih264decgstreamer1.0-vaapi (universe)legacy VA plugin, deprecated upstreamPackage installed, element not registered
v4l2h264dec / v4l2slh264decgstreamer1.0-plugins-goodARM SBCs, some laptopsNot present
avdec_h264gstreamer1.0-libav (universe)software (FFmpeg)Present
openh264decgstreamer1.0-plugins-badsoftwarePresent
h264parsegstreamer1.0-plugins-bad (libgstvideoparsersbad.so)n/aPresent

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 build GdkMemoryTextures 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 .deb cannot 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 lets h264parse forward 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=1 or thread-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 lacks bitstream_restriction; scrcpy sets AV_CODEC_FLAG_LOW_DELAY, which avdec_h264 does not expose as a property. Measure; if output lags by frames, prefer openh264dec or 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 for is-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=false on the sink (glsinkbin proxies it), qos=false. No clock synchronisation; show frames as they arrive, like scrcpy. Pipeline latency stays default.
  • Session changes: on rotation or flex-resize the helper starts a new stream with new SPS/PPS; h264parse renegotiates 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 | h264parse on 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 .pc files; pulls GL/EGL headers)
  • existing: libgtk-4-dev, libadwaita-1-dev
  • libgstreamer-plugins-bad1.0-dev is 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:

  • $auto will add libgstreamer1.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 -bad and -libav are in universe on Ubuntu and main on Debian. If we want mirroring to work on a default install, promote gstreamer1.0-plugins-bad and gstreamer1.0-libav to depends; Mint enables universe by default and already ships both.
  • Add to suggests: v4l2loopback-dkms.
  • No gstreamer1.0-gtk4 dependency (static).
  • At startup, check for h264parse and 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

CodecHardware elementsSoftware elementsHere (Ubuntu 24.04 base)
H.265vah265dec, nvh265dec, vulkanh265decavdec_h265 (libav), libde265dec (bad)nvh265dec, avdec_h265, libde265dec, vulkanh265dec present; vah265dec not registered
AV1vaav1dec, nvav1decav1dec (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:

OptionProsCons
GStreamer in tetherd: appsrc ! opusdec ! audioconvert ! audioresample ! sinkOne 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 heretetherd 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 libopusPipe 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 nodeNeeds 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)PortableGoes 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, caps audio/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=true on 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_SUBMIX the phone goes silent; PLAYBACK_DUP keeps 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

DistroPackageVersionComponent
Ubuntu 24.04 / Mint 22v4l2loopback-dkms, v4l2loopback-utils0.12.7-2ubuntu5.2universe
Debian 13v4l2loopback-dkms0.15.0-2main

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 --import the DKMS key manually. Until enrolled, modprobe fails 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=1 is 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 / video group).

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. (pipewiresink has mode and stream-properties here [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).
  • 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.

  1. 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 one pkexec 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.
  2. Build the webcam pipeline with a tee so a PipeWire Video/Source output 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”.
  3. 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):

InputControllerNotes
Mouse buttonsGestureClick with button=0 (all buttons)pressed/released give widget coordinates; current_button() gives 1..9; current_event_state() gives modifiers
Pointer motion / hoverEventControllerMotionSend 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 scrollEventControllerScroll with BOTH_AXES (not DISCRETE)scroll(dx, dy); check unit() (GTK 4.8+): wheel units vs surface pixels. Accumulate and send floats
KeysEventControllerKeykey-pressed(keyval, keycode, state) / key-released; attach the IM context with set_im_context
TextGtkIMMulticontextcommit(str) gives composed text (dead keys, compose, IBus/Fcitx)
TouchscreenEventControllerLegacyRaw GdkEvent: TouchBegin/Update/End/Cancel, event_sequence() maps to pointer_id; gives true multi-touch
Touchpad pinchGestureZoomTranslate to a two-pointer gesture around the pointer position
Focus lossEventControllerFocusOn leave: release every pressed key and pointer (send UP/CANCEL) to avoid stuck input
File dropDropTarget (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_h to InputEvent.touch and InputEvent.scroll in 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:

  1. In key-pressed, if Ctrl, Alt or Super is held, or the keyval is non-printing (navigation, editing, function, modifier, media keys): send InputEvent.key with an Android keycode and metastate, on press and on release.
  2. Otherwise let the IM context filter the event; on commit(str) send InputEvent.text{utf8}.
  3. Helper side: inject ASCII through KeyCharacterMap events; 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.
  4. A “game mode / raw keys” toggle sends every key as a key event (WASD).
  5. 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 keyvalAndroidGDK keyvalAndroid
Return, KP_EnterENTER 66Up/Down/Left/RightDPAD 19/20/21/22
BackSpaceDEL 67Home / EndMOVE_HOME 122 / MOVE_END 123
DeleteFORWARD_DEL 112Page_Up / Page_Down92 / 93
TabTAB 61Insert124
EscapeESCAPE 111F1..F12131..142
spaceSPACE 62a..zA..Z 29..54
0..97..16Shift_L/R59 / 60
Control_L/R113 / 114Alt_L/R57 / 58
Super_L/RMETA 117 / 118MenuMENU 82
Caps_Lock115XF86AudioRaiseVolume/LowerVolume/Mute24 / 25 / 164
XF86AudioPlayMEDIA_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:++++:

ButtonDefaultWith Shift
Lefttouch / clickn/a
RightBACK (wakes the screen if it is off)forwarded as a real secondary click
MiddleHOMEforwarded
4thAPP_SWITCHforwarded
5thexpand notification panelforwarded

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_shortcuts while 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

  1. adb -L localfilesystem:... server socket and adb reverse ... localfilesystem:... with distro adb 34.0.4 / 34.0.5; exact adb connect / adb pair output strings on 34.x.
  2. Whether Ubuntu’s adb 34.0.4 has mDNS stubbed like Debian’s (expected yes; irrelevant if we set ADB_MDNS=0 and use Avahi).
  3. QR pairing on One UI: is the studio- prefix required, and does the Settings scanner accept our payload.
  4. gstgtk4::plugin_register_static() build with gtk4 0.9 / gstreamer 0.23 on Ubuntu 24.04; nvh264dec to GL texture on X11 with the NVIDIA driver; frame delay of avdec_h264 with a MediaCodec stream.
  5. A VA-API test machine (Intel/AMD) for vah264dec and the dmabuf path on Wayland.
  6. v4l2sink into v4l2loopback 0.12.7 with GStreamer 1.24; pipewiresink mode=provide camera node on PipeWire 1.0.5 and which apps list it.
  7. Re-enabling Wireless debugging from the app with WRITE_SECURE_SETTINGS on One UI.
  8. Auto Blocker’s effect on Wireless debugging (as opposed to USB) on One UI 7.