diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 52bcf64..8c3445e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,7 +18,7 @@ jobs:
steps:
- name: Install system packages
run: |
- pacman -Syu --noconfirm --needed base-devel clang pkgconf ffmpeg pipewire libva git curl
+ pacman -Syu --noconfirm --needed base-devel clang pkgconf ffmpeg pipewire libva libusb git curl
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
diff --git a/.github/workflows/linux-packages.yml b/.github/workflows/linux-packages.yml
index d2b57b0..bdcce57 100644
--- a/.github/workflows/linux-packages.yml
+++ b/.github/workflows/linux-packages.yml
@@ -18,7 +18,7 @@ jobs:
steps:
- name: Install build tools and runtime libraries
run: |
- pacman -Syu --noconfirm --needed base-devel sudo git clang pkgconf rust ffmpeg pipewire libva \
+ pacman -Syu --noconfirm --needed base-devel sudo git clang pkgconf rust ffmpeg pipewire libva libusb \
android-tools xdg-desktop-portal-kde libkscreen
- uses: actions/checkout@v4
- name: Build the package as a regular user
@@ -66,7 +66,7 @@ jobs:
apt-get install -y --no-install-recommends build-essential clang libclang-dev pkg-config \
ca-certificates git curl dpkg-dev libavcodec-dev libavformat-dev libavfilter-dev \
libavutil-dev libswscale-dev libswresample-dev libpipewire-0.3-dev libva-dev \
- libx11-dev libxkbcommon-dev libwayland-dev
+ libusb-1.0-0-dev libx11-dev libxkbcommon-dev libwayland-dev
- uses: actions/checkout@v4
- run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
- uses: dtolnay/rust-toolchain@stable
@@ -111,7 +111,7 @@ jobs:
apt-get update
apt-get install -y --no-install-recommends build-essential clang libclang-dev pkg-config \
nasm curl ca-certificates git xz-utils unzip file patchelf binutils \
- libva-dev libdrm-dev libpipewire-0.3-dev libvulkan-dev libxkbcommon-dev \
+ libva-dev libdrm-dev libpipewire-0.3-dev libvulkan-dev libusb-1.0-0-dev libxkbcommon-dev \
libwayland-dev libx11-dev glslang-tools glslang-dev spirv-tools
- uses: actions/checkout@v4
- run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
@@ -149,7 +149,7 @@ jobs:
run: |
apt-get update
apt-get install -y --no-install-recommends ca-certificates git jq libva2 libva-drm2 \
- libdrm2 libvulkan1 libpipewire-0.3-0t64
+ libdrm2 libvulkan1 libpipewire-0.3-0t64 libusb-1.0-0
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
diff --git a/Cargo.lock b/Cargo.lock
index d770669..c0e9757 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1748,6 +1748,7 @@ dependencies = [
"quinn",
"rcgen",
"ring",
+ "rusb",
"rustls",
"serde",
"socket2",
@@ -2759,6 +2760,18 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "libusb1-sys"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da050ade7ac4ff1ba5379af847a10a10a8e284181e060105bf8d86960ce9ce0f"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+ "vcpkg",
+]
+
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -4259,6 +4272,16 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "rusb"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab9f9ff05b63a786553a4c02943b74b34a988448671001e9a27e2f0565cc05a4"
+dependencies = [
+ "libc",
+ "libusb1-sys",
+]
+
[[package]]
name = "rust-embed"
version = "8.13.0"
diff --git a/README.md b/README.md
index d1cb791..9689204 100644
--- a/README.md
+++ b/README.md
@@ -64,8 +64,7 @@ Working today, over USB with ADB:
| Tray app with settings and live statistics | ✅ | ✅ |
| Installer / packages | ✅ `.exe` | ✅ AppImage, `.deb`, Arch |
-**Not yet:** Android Open Accessory and native Wi-Fi transports, audio, GNOME and wlroots backends,
-X11.
+**Not yet:** audio, GNOME and wlroots backends, X11.
## How it works
@@ -91,6 +90,23 @@ All channels share one prioritized, multiplexed link (ADB over USB today), so in
updates are never stuck behind a video frame. Details: [docs/architecture.md](docs/architecture.md),
wire format: [docs/protocol.md](docs/protocol.md), input path: [docs/input.md](docs/input.md).
+## USB without developer mode
+
+Besides adb, ezdisplay can talk to the tablet over USB with the Android Open Accessory protocol,
+which does not need developer mode or USB debugging.
+
+- **Linux:** needs the udev rule `packaging/linux/70-ezdisplay-usb.rules`, which the packages install
+ (from source or an AppImage, install it yourself, see
+ [packaging/linux/README.md](packaging/linux/README.md)).
+- **Windows:** needs the optional UsbDk driver. The installer offers it as the unchecked task "USB
+ without developer mode (installs the UsbDk driver)". Without it, USB falls back to adb.
+- The first time, Android asks which app should open the accessory. Pick ezdisplay; choosing "always"
+ avoids the question next time.
+- In auto mode the host tries the accessory first and falls back to adb. Turn it off with
+ `--aoa off` or `aoa = "off"` in `config.toml`.
+- A phone or tablet without the app is switched once and then left alone: it is reset back to normal
+ mode and not tried again while the host runs.
+
## Install
Everything is on the [Releases page](https://github.com/LibreStatic/ezdisplay/releases)
@@ -161,6 +177,9 @@ Build it (see [Building](#building)), then:
sudo udevadm control --reload && sudo udevadm trigger --name-match=uinput
```
+ For USB without developer mode, install `packaging/linux/70-ezdisplay-usb.rules` the same way and
+ run `sudo udevadm trigger --subsystem-match=usb`.
+
2. Install the app and its desktop entry:
```sh
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 45f2a6e..56b0d9a 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -6,6 +6,10 @@
+
+
+
+
+
+
diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt
index 489b164..f4d49a3 100644
--- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt
@@ -1,12 +1,19 @@
package com.librestatic.ezdisplay
+import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Rect
import android.graphics.Typeface
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
import android.content.Intent
+import android.content.IntentFilter
import android.content.res.Configuration
+import android.hardware.usb.UsbAccessory
+import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
@@ -33,6 +40,10 @@ import android.widget.ImageView
import android.widget.TextView
import com.librestatic.ezdisplay.settings.SettingsStore
import com.librestatic.ezdisplay.settings.wifiErrorText
+import com.librestatic.ezdisplay.usb.Route
+import com.librestatic.ezdisplay.usb.chooseRoute
+import com.librestatic.ezdisplay.usb.isOurAccessory
+import com.librestatic.ezdisplay.usb.shouldSwitchToAccessory
import com.librestatic.ezdisplay.wifi.HostDiscovery
import com.librestatic.ezdisplay.wifi.NativeWifiBackend
import com.librestatic.ezdisplay.wifi.WifiChoice
@@ -51,7 +62,9 @@ import java.util.Locale
* touch/pen input to the host and drives the local zoom of the [stage] (surface + cursor).
* Outside of streaming a settings button is shown.
*
- * Connection order: USB first (the adb-reversed loopback port). When that fails and Wi-Fi is enabled in the settings
+ * Connection order: a USB accessory (AOA, no developer mode needed) first, then the adb-reversed loopback port.
+ * An attached accessory always wins and is retried with the normal backoff while it stays attached; the loopback
+ * port and Wi-Fi are only used when none is attached. When the loopback attempt fails and Wi-Fi is enabled in the settings
* with a paired host known, the next attempt goes to that host over Wi-Fi; if the Wi-Fi attempt fails the next one is
* USB again, so plugging the cable in always wins.
*/
@@ -60,6 +73,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
const val TAG = "ezdisplay"
const val HOST = "127.0.0.1"
const val PORT = 27183
+ const val ACTION_USB_PERMISSION = "com.librestatic.ezdisplay.USB_PERMISSION"
const val LAST_WIFI_HOST = "wifi_last_host"
const val BACKOFF_MIN_MS = 1000L
const val BACKOFF_MAX_MS = 5000L
@@ -134,8 +148,34 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
private var tryWifiNext = false // the loopback connection just failed: try the paired host
private var pairingLost: String? = null // the host forgot this device: kept above later retry messages
+ private val usbManager by lazy { getSystemService(Context.USB_SERVICE) as UsbManager }
+ private var accessory: UsbAccessory? = null // our accessory while it is attached
+ private var activeAccessory = false // the current session runs over the accessory
+ private var accessoryPermissionAsked = false // a permission dialog was shown for the attached accessory
+ private var launchIntent: Intent? = null // the intent that started or re-delivered this activity, read once
+ private var usbReceiverRegistered = false
+
+ private val usbReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val acc = usbAccessoryExtra(intent)
+ when (intent.action) {
+ UsbManager.ACTION_USB_ACCESSORY_DETACHED -> {
+ if (acc == null || isOurAccessory(acc.manufacturer, acc.model)) accessoryGone()
+ }
+ ACTION_USB_PERMISSION -> {
+ if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
+ checkAccessory()
+ } else {
+ Log.w(TAG, "USB accessory permission denied")
+ }
+ }
+ }
+ }
+ }
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ launchIntent = intent
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.also {
@@ -270,6 +310,94 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
super.onResume()
applyInputConfig()
updateDiscovery()
+ checkAccessory()
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ launchIntent = intent
+ accessoryPermissionAsked = false
+ checkAccessory()
+ }
+
+ @Suppress("DEPRECATION")
+ private fun usbAccessoryExtra(intent: Intent?): UsbAccessory? =
+ if (Build.VERSION.SDK_INT >= 33) intent?.getParcelableExtra(UsbManager.EXTRA_ACCESSORY, UsbAccessory::class.java)
+ else intent?.getParcelableExtra(UsbManager.EXTRA_ACCESSORY)
+
+ @SuppressLint("InlinedApi")
+ private fun registerUsbReceiver() {
+ if (usbReceiverRegistered) return
+ val filter = IntentFilter().apply {
+ addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED)
+ addAction(ACTION_USB_PERMISSION)
+ }
+ // The flag is a constant, ignored before Android 13; the permission result is sent as this app.
+ registerReceiver(usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
+ usbReceiverRegistered = true
+ }
+
+ private fun unregisterUsbReceiver() {
+ if (!usbReceiverRegistered) return
+ usbReceiverRegistered = false
+ unregisterReceiver(usbReceiver)
+ }
+
+ /**
+ * Finds our accessory (from the attach intent, else the system's list), asks for permission when the app
+ * was not launched by the attach, and switches to it. Cheap and idempotent: called on start, resume,
+ * new intents and permission results.
+ */
+ private fun checkAccessory() {
+ val fromIntent = launchIntent?.takeIf { it.action == UsbManager.ACTION_USB_ACCESSORY_ATTACHED }
+ ?.let { usbAccessoryExtra(it) }
+ launchIntent = null
+ if (!started) {
+ // Keep the intent's accessory for onStart (onNewIntent arrives before onStart when stopped).
+ if (fromIntent != null) launchIntent = intentFor(fromIntent)
+ return
+ }
+ val found = fromIntent?.takeIf { isOurAccessory(it.manufacturer, it.model) }
+ ?: usbManager.accessoryList?.firstOrNull { isOurAccessory(it.manufacturer, it.model) }
+ if (found == null) {
+ if (accessory != null) accessoryGone()
+ return
+ }
+ accessory = found
+ if (!usbManager.hasPermission(found)) {
+ if (!accessoryPermissionAsked) {
+ accessoryPermissionAsked = true
+ val flags = PendingIntent.FLAG_UPDATE_CURRENT or
+ (if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0)
+ val pi = PendingIntent.getBroadcast(
+ this, 0, Intent(ACTION_USB_PERMISSION).setPackage(packageName), flags,
+ )
+ setStatus(getString(R.string.status_usb_permission))
+ usbManager.requestPermission(found, pi)
+ }
+ return
+ }
+ if (shouldSwitchToAccessory(true, sessionActive, activeAccessory)) {
+ if (sessionActive) stopSession()
+ backoffMs = BACKOFF_MIN_MS
+ scheduleConnect(0)
+ }
+ }
+
+ private fun intentFor(acc: UsbAccessory) =
+ Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED).putExtra(UsbManager.EXTRA_ACCESSORY, acc)
+
+ /** The accessory is gone: end its session and go back to the loopback and Wi-Fi loop. */
+ private fun accessoryGone() {
+ accessory = null
+ accessoryPermissionAsked = false
+ if (!activeAccessory) return
+ stopSession()
+ backoffMs = BACKOFF_MIN_MS
+ tryWifiNext = false
+ setStatus(getString(R.string.status_waiting, "$HOST:$PORT"))
+ scheduleConnect(0)
}
private fun wifiEnabled() = InputPrefs.prefs(this).getBoolean(SettingsStore.WIFI_ENABLED, false)
@@ -298,6 +426,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
setStatus(getString(R.string.status_waiting, "$HOST:$PORT"))
Choreographer.getInstance().postFrameCallback(this)
updateDiscovery()
+ registerUsbReceiver()
+ checkAccessory()
scheduleConnect(0)
}
@@ -311,6 +441,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
handler.removeCallbacks(connectRunnable)
Choreographer.getInstance().removeFrameCallback(this)
stopSession()
+ unregisterUsbReceiver()
discovery.stop()
super.onStop()
}
@@ -345,25 +476,32 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
if (!surfaceReady) return // surfaceCreated reschedules
val caps = capsJson ?: Capabilities.toJson(this, chosenMode).also { capsJson = it }
pushKeyboardState()
- val choice = if (tryWifiNext) wifiTarget() else null
+ val acc = accessory?.takeIf { usbManager.hasPermission(it) }
+ val wifiChoice = if (tryWifiNext) wifiTarget() else null
+ val route = chooseRoute(acc != null, tryWifiNext, wifiChoice != null)
tryWifiNext = false
- val err = if (choice != null) {
- NativeBridge.startWifi(
- surfaceView.holder.surface, choice.addr, choice.host.fingerprint,
+ val choice = if (route == Route.WIFI) wifiChoice else null
+ val err = when (route) {
+ Route.ACCESSORY -> startAccessory(acc!!, caps)
+ Route.WIFI -> NativeBridge.startWifi(
+ surfaceView.holder.surface, choice!!.addr, choice.host.fingerprint,
NativeWifiBackend.stateDir(this).absolutePath, caps,
)
- } else {
- NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps)
+ Route.TCP -> NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps)
}
if (err != null) {
Log.w(TAG, "start failed: $err")
- setStatus(getString(R.string.status_bad_caps, err))
+ setStatus(
+ if (route == Route.ACCESSORY) getString(R.string.status_usb_open_failed)
+ else getString(R.string.status_bad_caps, err),
+ )
scheduleConnect(backoffMs)
backoffMs = (backoffMs * 2).coerceAtMost(BACKOFF_MAX_MS)
return
}
sessionActive = true
activeWifi = choice
+ activeAccessory = route == Route.ACCESSORY
applyInputConfig()
wasStreaming = false
lastInputNote = ""
@@ -377,11 +515,26 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
fitSurface()
frameRateSet = 0
setStatus(
- if (choice != null) getString(R.string.status_wifi_connecting, hostLabel(choice))
- else getString(R.string.status_waiting, "$HOST:$PORT"),
+ when (route) {
+ Route.ACCESSORY -> getString(R.string.status_usb_connecting)
+ Route.WIFI -> getString(R.string.status_wifi_connecting, hostLabel(choice!!))
+ Route.TCP -> getString(R.string.status_waiting, "$HOST:$PORT")
+ },
)
}
+ /** Opens [acc] and hands the descriptor to the native layer, which closes it. Null on success, else an error. */
+ private fun startAccessory(acc: UsbAccessory, caps: String): String? {
+ val pfd = try {
+ usbManager.openAccessory(acc)
+ } catch (e: Exception) {
+ return "open accessory: ${e.message}"
+ } ?: return "open accessory failed"
+ // detachFd leaves the descriptor open and ours to close: the native session owns it from here on.
+ val fd = pfd.detachFd()
+ return NativeBridge.startFd(surfaceView.holder.surface, fd, caps)
+ }
+
private fun hostLabel(choice: WifiChoice) = choice.host.name.ifEmpty { choice.host.shortFp }
private fun stopSession() {
@@ -391,6 +544,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
sessionActive = false
}
activeWifi = null
+ activeAccessory = false
cursorVisible = false
cursorView.visibility = View.GONE
cursorSeq = 0
@@ -540,14 +694,22 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
fitSurface()
}
val wifiChoice = activeWifi
+ val usb = activeAccessory
val addr = if (wifiChoice != null) hostLabel(wifiChoice) else "$HOST:$PORT"
when (j.optString("phase")) {
"connecting" -> setStatus(
- if (wifiChoice != null) getString(R.string.status_wifi_connecting, addr)
- else getString(R.string.status_waiting, addr),
+ when {
+ usb -> getString(R.string.status_usb_connecting)
+ wifiChoice != null -> getString(R.string.status_wifi_connecting, addr)
+ else -> getString(R.string.status_waiting, addr)
+ },
)
"handshaking" -> setStatus(
- getString(if (wifiChoice != null) R.string.status_wifi_handshake else R.string.status_handshake, addr),
+ when {
+ usb -> getString(R.string.status_usb_handshake)
+ wifiChoice != null -> getString(R.string.status_wifi_handshake, addr)
+ else -> getString(R.string.status_handshake, addr)
+ },
)
"streaming" -> {
if (!wasStreaming) {
@@ -577,7 +739,11 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
statusView.visibility = View.GONE
}
}
- "ended" -> disconnected(getString(R.string.status_ended, j.optString("detail"), addr), false)
+ "ended" -> disconnected(
+ if (usb) getString(R.string.status_ended_usb, j.optString("detail"))
+ else getString(R.string.status_ended, j.optString("detail"), addr),
+ false,
+ )
"failed" -> {
// A Wi-Fi failure carries a stable code; the detail is English text for the log.
val code = if (j.isNull("code")) null else j.optString("code")
@@ -628,7 +794,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
if (wifiTarget() != null) pairingLost = null
setStatus(message)
// The loopback connection failed (no cable, no adb reverse): try the paired host over Wi-Fi right away.
- if (failed && !wasWifi && wifiTarget() != null) {
+ // While an accessory is attached it is retried with the normal backoff; no fallback.
+ if (failed && !wasWifi && accessory == null && wifiTarget() != null) {
tryWifiNext = true
scheduleConnect(0)
return
diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt
index ec43742..d10a3af 100644
--- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt
+++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt
@@ -16,6 +16,12 @@ object NativeBridge {
/** Starts one connection attempt to [host]:[port]. Returns null on success or an error message. */
@JvmStatic external fun start(surface: Surface?, host: String, port: Int, capsJson: String): String?
+ /**
+ * Starts one connection attempt over the USB accessory file descriptor [fd]. Takes ownership: the caller
+ * detached it from its ParcelFileDescriptor and must not close it. Null on success, else an error.
+ */
+ @JvmStatic external fun startFd(surface: Surface?, fd: Int, capsJson: String): String?
+
/**
* Starts one connection attempt over Wi-Fi to the paired host with certificate [fingerprintHex] at [addr]
* (`ip:port`). [stateDir] holds this device's identity and the paired hosts. Null on success, else an error.
diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/usb/AccessoryModel.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/usb/AccessoryModel.kt
new file mode 100644
index 0000000..4536797
--- /dev/null
+++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/usb/AccessoryModel.kt
@@ -0,0 +1,27 @@
+package com.librestatic.ezdisplay.usb
+
+/** Manufacturer and model the PC announces when it switches the tablet into accessory mode. */
+const val ACCESSORY_MANUFACTURER = "LibreStatic"
+const val ACCESSORY_MODEL = "ezdisplay"
+
+/** True for the USB accessory the ezdisplay PC host presents (see `res/xml/accessory_filter.xml`). */
+fun isOurAccessory(manufacturer: String?, model: String?): Boolean =
+ manufacturer == ACCESSORY_MANUFACTURER && model == ACCESSORY_MODEL
+
+/** How the next connection attempt reaches the host. */
+enum class Route { ACCESSORY, TCP, WIFI }
+
+/**
+ * Connection order: USB accessory, then the adb-reversed loopback port, then Wi-Fi.
+ * An attached accessory always wins (the PC holds its session slot for it). Wi-Fi is only tried right
+ * after a loopback attempt failed ([loopbackFailed]) and a paired host is available ([wifiAvailable]).
+ */
+fun chooseRoute(accessoryReady: Boolean, loopbackFailed: Boolean, wifiAvailable: Boolean): Route = when {
+ accessoryReady -> Route.ACCESSORY
+ loopbackFailed && wifiAvailable -> Route.WIFI
+ else -> Route.TCP
+}
+
+/** What to do with the current session when an accessory shows up. */
+fun shouldSwitchToAccessory(accessoryReady: Boolean, sessionActive: Boolean, sessionIsAccessory: Boolean): Boolean =
+ accessoryReady && !(sessionActive && sessionIsAccessory)
diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml
index c1f8f53..0f40f85 100644
--- a/android/app/src/main/res/values-de/strings.xml
+++ b/android/app/src/main/res/values-de/strings.xml
@@ -97,6 +97,11 @@
Aktion auswählen
Verbinde über WLAN mit %1$s…
Über WLAN mit %1$s verbunden, Verhandlung läuft…
+ Verbinde über USB (Zubehör)…
+ Über USB (Zubehör) verbunden, Verhandlung läuft…
+ Verbindung getrennt (%1$s). Verbinde erneut über USB (Zubehör)…
+ Erlaube den USB-Zugriff, um dich mit dem PC zu verbinden.
+ Das USB-Zubehör konnte nicht geöffnet werden. Neuer Versuch…
WLAN erhöht die Latenz; USB ist am besten zum Zeichnen.
Verbindung
Nur USB
diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml
index bbea076..509bbc3 100644
--- a/android/app/src/main/res/values-es/strings.xml
+++ b/android/app/src/main/res/values-es/strings.xml
@@ -97,6 +97,11 @@
Elegir acción
Conectando por Wi-Fi a %1$s…
Conectado por Wi-Fi a %1$s, negociando…
+ Conectando por USB (accesorio)…
+ Conectado por USB (accesorio), negociando…
+ Desconectado (%1$s). Reconectando por USB (accesorio)…
+ Permití el acceso USB para conectarte a la PC.
+ No se pudo abrir el accesorio USB. Reintentando…
El Wi-Fi agrega latencia; el USB es lo mejor para dibujar.
Conexión
Solo USB
diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml
index 50d6725..8d204b5 100644
--- a/android/app/src/main/res/values-fr/strings.xml
+++ b/android/app/src/main/res/values-fr/strings.xml
@@ -97,6 +97,11 @@
Choisir l\'action
Connexion en Wi-Fi à %1$s…
Connecté en Wi-Fi à %1$s, négociation…
+ Connexion en USB (accessoire)…
+ Connecté en USB (accessoire), négociation…
+ Déconnecté (%1$s). Reconnexion en USB (accessoire)…
+ Autorisez l\'accès USB pour vous connecter au PC.
+ Impossible d\'ouvrir l\'accessoire USB. Nouvelle tentative…
Le Wi-Fi ajoute de la latence ; l\'USB est idéal pour dessiner.
Connexion
USB uniquement
diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml
index ec3cd30..323d90f 100644
--- a/android/app/src/main/res/values-it/strings.xml
+++ b/android/app/src/main/res/values-it/strings.xml
@@ -97,6 +97,11 @@
Scegli azione
Connessione via Wi-Fi a %1$s…
Connesso via Wi-Fi a %1$s, negoziazione…
+ Connessione via USB (accessorio)…
+ Connesso via USB (accessorio), negoziazione…
+ Disconnesso (%1$s). Riconnessione via USB (accessorio)…
+ Consenti l\'accesso USB per collegarti al PC.
+ Impossibile aprire l\'accessorio USB. Nuovo tentativo…
Il Wi-Fi aggiunge latenza; l\'USB è il migliore per disegnare.
Connessione
Solo USB
diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml
index cccc58e..66f39d7 100644
--- a/android/app/src/main/res/values-pt/strings.xml
+++ b/android/app/src/main/res/values-pt/strings.xml
@@ -97,6 +97,11 @@
Escolher ação
Conectando por Wi-Fi a %1$s…
Conectado por Wi-Fi a %1$s, negociando…
+ Conectando por USB (acessório)…
+ Conectado por USB (acessório), negociando…
+ Desconectado (%1$s). Reconectando por USB (acessório)…
+ Permita o acesso USB para conectar ao PC.
+ Não foi possível abrir o acessório USB. Tentando novamente…
O Wi-Fi adiciona latência; o USB é o melhor para desenhar.
Conexão
Somente USB
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index ba03097..6a4fd8c 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -97,6 +97,11 @@
Choose action
Connecting over Wi-Fi to %1$s…
Connected over Wi-Fi to %1$s, negotiating…
+ Connecting over USB (accessory)…
+ Connected over USB (accessory), negotiating…
+ Disconnected (%1$s). Reconnecting over USB (accessory)…
+ Allow USB access to connect to the PC.
+ Could not open the USB accessory. Retrying…
Wi-Fi adds latency; USB is best for drawing.
Connection
USB only
diff --git a/android/app/src/main/res/xml/accessory_filter.xml b/android/app/src/main/res/xml/accessory_filter.xml
new file mode 100644
index 0000000..8f08dbd
--- /dev/null
+++ b/android/app/src/main/res/xml/accessory_filter.xml
@@ -0,0 +1,6 @@
+
+
+
+
diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/usb/AccessoryModelTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/usb/AccessoryModelTest.kt
new file mode 100644
index 0000000..faa74c7
--- /dev/null
+++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/usb/AccessoryModelTest.kt
@@ -0,0 +1,35 @@
+package com.librestatic.ezdisplay.usb
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class AccessoryModelTest {
+ @Test fun matchesOnlyOurManufacturerAndModel() {
+ assertTrue(isOurAccessory("LibreStatic", "ezdisplay"))
+ assertFalse(isOurAccessory("LibreStatic", "other"))
+ assertFalse(isOurAccessory("Other", "ezdisplay"))
+ assertFalse(isOurAccessory(null, "ezdisplay"))
+ assertFalse(isOurAccessory("LibreStatic", null))
+ assertFalse(isOurAccessory("librestatic", "ezdisplay"))
+ }
+
+ @Test fun accessoryBeatsEverything() {
+ assertEquals(Route.ACCESSORY, chooseRoute(accessoryReady = true, loopbackFailed = true, wifiAvailable = true))
+ assertEquals(Route.ACCESSORY, chooseRoute(accessoryReady = true, loopbackFailed = false, wifiAvailable = false))
+ }
+
+ @Test fun loopbackIsTriedBeforeWifi() {
+ assertEquals(Route.TCP, chooseRoute(accessoryReady = false, loopbackFailed = false, wifiAvailable = true))
+ assertEquals(Route.WIFI, chooseRoute(accessoryReady = false, loopbackFailed = true, wifiAvailable = true))
+ assertEquals(Route.TCP, chooseRoute(accessoryReady = false, loopbackFailed = true, wifiAvailable = false))
+ }
+
+ @Test fun switchesToAccessoryUnlessAlreadyOnIt() {
+ assertTrue(shouldSwitchToAccessory(true, sessionActive = false, sessionIsAccessory = false))
+ assertTrue(shouldSwitchToAccessory(true, sessionActive = true, sessionIsAccessory = false))
+ assertFalse(shouldSwitchToAccessory(true, sessionActive = true, sessionIsAccessory = true))
+ assertFalse(shouldSwitchToAccessory(false, sessionActive = true, sessionIsAccessory = false))
+ }
+}
diff --git a/crates/ezd-android/src/bridge.rs b/crates/ezd-android/src/bridge.rs
index e32d642..dc5a139 100644
--- a/crates/ezd-android/src/bridge.rs
+++ b/crates/ezd-android/src/bridge.rs
@@ -6,7 +6,7 @@ use crate::caps::parse_caps;
use crate::decoder::SendWindow;
use crate::input::{mono_to_now_us, unpack_motion};
use crate::keys::keycode_to_hid;
-use crate::session::{Session, Target};
+use crate::session::{AccessoryFd, Session, Target};
use crate::wifi;
use ezd_client_core::now_us;
use ezd_input::{InputConfig, InputEngine, ViewTransform};
@@ -18,6 +18,7 @@ use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JObje
use jni::sys::{jboolean, jint};
use ndk::native_window::NativeWindow;
use std::cell::RefCell;
+use std::os::fd::FromRawFd;
use std::sync::Mutex;
use std::sync::Once;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -206,6 +207,44 @@ pub extern "system" fn startWifi<'local>(
.resolve::()
}
+/// `external fun startFd(surface: Surface?, fd: Int, capsJson: String): String?`
+/// Streams over the USB accessory file descriptor. Takes ownership of `fd` (Kotlin detached it
+/// from its `ParcelFileDescriptor`): it is closed exactly once, when the session ends. Returns
+/// null on success or an error message.
+#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")]
+pub extern "system" fn startFd<'local>(
+ mut env: EnvUnowned<'local>,
+ _class: JClass<'local>,
+ surface: JObject<'local>,
+ fd: jint,
+ caps_json: JString<'local>,
+) -> JString<'local> {
+ init_logging();
+ env.with_env(|env| -> jni::errors::Result> {
+ let caps_json = caps_json.try_to_string(env)?;
+ let mut err = |m: String| env.new_string(m);
+ if fd < 0 {
+ return err(format!("bad accessory fd {fd}"));
+ }
+ // SAFETY: Kotlin detached `fd` and hands over its only owner; nothing else closes it.
+ let fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) };
+ let caps = match parse_caps(&caps_json) {
+ Ok(c) => c,
+ Err(e) => return err(e),
+ };
+ let window = window_from(env, &surface);
+ start_session(
+ window,
+ Target::Accessory {
+ fd: AccessoryFd::new(fd),
+ },
+ caps,
+ );
+ Ok(JString::null())
+ })
+ .resolve::()
+}
+
/// `external fun wifiPair(addr: String, pinOrUri: String, deviceName: String, stateDir: String):
/// String` Blocks (call off the main thread). JSON, see [`wifi::pair_json`].
#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")]
diff --git a/crates/ezd-android/src/session.rs b/crates/ezd-android/src/session.rs
index 3f42d9f..989ea28 100644
--- a/crates/ezd-android/src/session.rs
+++ b/crates/ezd-android/src/session.rs
@@ -9,18 +9,25 @@ use ezd_client_core::{
ClientConfig, ClientEnd, ClientHandle, ClientHandler, CursorSnapshot, Flow, HandlerResult,
run_client,
};
-use ezd_link::Link;
+use ezd_link::{BlockingOptions, Link};
use ezd_proto::pair::Fingerprint;
use ezd_proto::{CursorShape, StreamColor, StreamConfig, VideoFrame};
+use std::fs::File;
+use std::io::{Read, Write};
use std::net::SocketAddr;
+use std::os::fd::{AsRawFd, OwnedFd};
use std::path::PathBuf;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+/// The accessory gadget driver moves 16 KiB per transfer; smaller reads can fail or truncate.
+const ACCESSORY_BUF: usize = 16 * 1024;
/// Wi-Fi sessions retry while the host is busy or not reachable yet, up to this long.
const WIFI_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
+/// How long [`Session::stop`] lets the client say Bye over the accessory before revoking it.
+const ACCESSORY_BYE_GRACE: Duration = Duration::from_millis(500);
/// Where a session connects to.
#[derive(Debug, Clone)]
@@ -41,6 +48,107 @@ pub enum Target {
/// Directory with this device's identity and the paired hosts.
state_dir: PathBuf,
},
+ /// The USB accessory file descriptor (Android Open Accessory). Owned: closed when the session ends.
+ Accessory {
+ /// Descriptor detached from the `ParcelFileDescriptor`.
+ fd: AccessoryFd,
+ },
+}
+
+/// The accessory descriptor, shared by the link's read and write threads without duplicating it.
+///
+/// The gadget driver lets one opener at a time have `/dev/usb_accessory`, and the system opens it
+/// again on every new accessory handshake. A read blocks until the host sends something, even
+/// after the cable is pulled, and keeps the device open while it waits: closing the descriptor
+/// does not end it. [`AccessoryFd::revoke`] releases the device without waiting for that thread.
+#[derive(Debug, Clone)]
+pub struct AccessoryFd(Arc);
+
+#[derive(Debug)]
+struct AccessoryInner {
+ file: File,
+ /// The thread inside `read`, if any.
+ reader: Mutex>,
+}
+
+impl AccessoryFd {
+ pub fn new(fd: OwnedFd) -> Self {
+ AccessoryFd(Arc::new(AccessoryInner {
+ file: File::from(fd),
+ reader: Mutex::new(None),
+ }))
+ }
+
+ /// Points the descriptor at `/dev/null`, then interrupts a read in progress so it lets go of
+ /// the device; restarted, it reads end of file. The number stays allocated (this value holds
+ /// it), so a thread still using it never touches an unrelated descriptor.
+ fn revoke(&self) {
+ let null = match File::open("/dev/null") {
+ Ok(f) => f,
+ Err(e) => {
+ tracing::warn!("cannot release the accessory: /dev/null: {e}");
+ return;
+ }
+ };
+ // SAFETY: both descriptors are open and owned by live `File`s; dup2 replaces the target
+ // atomically, so its number is never free for another open to take.
+ if unsafe { libc::dup2(null.as_raw_fd(), self.0.file.as_raw_fd()) } < 0 {
+ tracing::warn!(
+ "cannot release the accessory: {}",
+ std::io::Error::last_os_error()
+ );
+ return;
+ }
+ let reader = self.0.reader.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(thread) = *reader {
+ install_wake_handler();
+ // SAFETY: the reader clears its entry under this lock before it exits, so `thread`
+ // is a live thread. The handler does nothing; the signal only ends the wait.
+ unsafe { libc::pthread_kill(thread, WAKE_SIGNAL) };
+ }
+ }
+}
+
+/// Interrupts a blocked accessory read. Nothing else in the app uses it, and its default action
+/// (ignore) would not interrupt anything, hence the handler.
+const WAKE_SIGNAL: libc::c_int = libc::SIGURG;
+
+fn install_wake_handler() {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ extern "C" fn wake(_: libc::c_int) {}
+ ONCE.call_once(|| {
+ // SAFETY: a zeroed sigaction is valid; the handler is async-signal-safe (empty).
+ unsafe {
+ let mut sa: libc::sigaction = std::mem::zeroed();
+ sa.sa_sigaction = wake as extern "C" fn(libc::c_int) as libc::sighandler_t;
+ sa.sa_flags = libc::SA_RESTART;
+ libc::sigemptyset(&mut sa.sa_mask);
+ if libc::sigaction(WAKE_SIGNAL, &sa, std::ptr::null_mut()) < 0 {
+ tracing::warn!("cannot install the accessory wake handler");
+ }
+ }
+ });
+}
+
+impl Read for AccessoryFd {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result {
+ let lock = || self.0.reader.lock().unwrap_or_else(|e| e.into_inner());
+ // SAFETY: pthread_self has no preconditions.
+ *lock() = Some(unsafe { libc::pthread_self() });
+ let r = (&self.0.file).read(buf);
+ *lock() = None;
+ r
+ }
+}
+
+impl Write for AccessoryFd {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result {
+ (&self.0.file).write(buf)
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
}
impl Target {
@@ -48,6 +156,7 @@ impl Target {
match self {
Target::Tcp { host, port } => format!("{host}:{port}"),
Target::Wifi { addr, .. } => addr.to_string(),
+ Target::Accessory { .. } => "usb-accessory".to_string(),
}
}
}
@@ -58,6 +167,7 @@ pub struct Session {
shared: Arc,
dec: Arc,
thread: Option>,
+ accessory: Option,
}
struct Handler {
@@ -126,6 +236,10 @@ impl Session {
let handle = ClientHandle::new();
let shared = Arc::new(Shared::default());
shared.set_phase(Phase::Connecting, target.label());
+ let accessory = match &target {
+ Target::Accessory { fd } => Some(fd.clone()),
+ _ => None,
+ };
let dec = DecoderCtl::spawn(caps.caps.clone(), handle.clone(), shared.clone(), window);
let thread = {
let (handle, shared, dec) = (handle.clone(), shared.clone(), dec.clone());
@@ -139,14 +253,25 @@ impl Session {
shared,
dec,
thread: Some(thread),
+ accessory,
}
}
/// Stops the session. The decoder is released before returning; the network teardown
/// (Bye, drain) finishes on a background thread so the caller never waits for the socket.
+ /// An accessory is released before returning too: the app may be frozen right after.
pub fn stop(mut self) {
self.handle.stop();
self.dec.shutdown(Duration::from_secs(2));
+ if let Some(fd) = self.accessory.take() {
+ let start = std::time::Instant::now();
+ while self.thread.as_ref().is_some_and(|t| !t.is_finished())
+ && start.elapsed() < ACCESSORY_BYE_GRACE
+ {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ fd.revoke();
+ }
if let Some(t) = self.thread.take() {
let _ = std::thread::Builder::new()
.name("ezd-reaper".into())
@@ -236,6 +361,21 @@ async fn connect(target: &Target) -> Result {
detail: format!("connect {addr}: {e}"),
code: Some(error_code(&e)),
}),
+ Target::Accessory { fd } => {
+ let io = |what: &str, e: std::io::Error| ConnectError::from(format!("{what}: {e}"));
+ Link::from_blocking(
+ fd.clone(),
+ fd.clone(),
+ "usb-accessory",
+ BlockingOptions {
+ read_buf: ACCESSORY_BUF,
+ write_buf: ACCESSORY_BUF,
+ thread_name: "ezd-acc".into(),
+ ..Default::default()
+ },
+ )
+ .map_err(|e| io("accessory link", e))
+ }
}
}
@@ -290,6 +430,7 @@ fn run(
ClientEnd::HostBye(r) => format!("host: {r}"),
ClientEnd::HostEof => "host closed the connection".to_string(),
ClientEnd::TimedOut => "timed out".to_string(),
+ ClientEnd::HostSilent => "host stopped responding".to_string(),
};
shared.set_phase(Phase::Ended, detail);
}
@@ -299,5 +440,9 @@ fn run(
}
}
});
+ // A session that ended on its own leaves the read thread waiting on the device.
+ if let Target::Accessory { fd } = &target {
+ fd.revoke();
+ }
dec.shutdown(Duration::from_secs(2));
}
diff --git a/crates/ezd-client-core/src/session.rs b/crates/ezd-client-core/src/session.rs
index 54dc5c3..8a29e9a 100644
--- a/crates/ezd-client-core/src/session.rs
+++ b/crates/ezd-client-core/src/session.rs
@@ -73,6 +73,9 @@ pub struct ClientConfig {
pub ping_interval: Duration,
/// Give up if the session does not end within this time.
pub max_duration: Option,
+ /// End the session when nothing at all arrives from the host for this long. The host answers
+ /// every ping, so silence means it is gone; a USB accessory link never reports that itself.
+ pub host_silence: Option,
/// Handshake step timeout.
pub handshake_timeout: Duration,
/// Reason in the `Bye` sent when the client ends the session.
@@ -82,7 +85,7 @@ pub struct ClientConfig {
}
impl ClientConfig {
- /// Defaults (1 s stats, 500 ms pings, 10 s handshake steps) for `caps`.
+ /// Defaults (1 s stats, 500 ms pings, 5 s host silence, 10 s handshake steps) for `caps`.
pub fn new(device_name: impl Into, caps: ClientCaps) -> Self {
ClientConfig {
device_name: device_name.into(),
@@ -92,6 +95,7 @@ impl ClientConfig {
stats_interval: Duration::from_secs(1),
ping_interval: Duration::from_millis(500),
max_duration: None,
+ host_silence: Some(Duration::from_secs(5)),
handshake_timeout: Duration::from_secs(10),
bye_reason: "client done".into(),
proto_minor: None,
@@ -110,6 +114,8 @@ pub enum ClientEnd {
HostEof,
/// `max_duration` elapsed.
TimedOut,
+ /// Nothing arrived from the host for `host_silence`.
+ HostSilent,
}
/// Result of a finished session.
@@ -276,15 +282,20 @@ pub async fn run_client(
let mut last_stats = std::time::Instant::now();
let deadline = cfg.max_duration.map(|d| tokio::time::Instant::now() + d);
let mut loop_err: Option = None;
+ let mut last_rx = tokio::time::Instant::now();
let end = loop {
let sleep_until =
deadline.unwrap_or_else(|| tokio::time::Instant::now() + Duration::from_secs(3600));
+ let silent_at = last_rx + cfg.host_silence.unwrap_or(Duration::from_secs(3600));
let step: Result, ClientError> = async {
tokio::select! {
_ = tokio::time::sleep_until(sleep_until), if deadline.is_some() => {
Ok(Some(ClientEnd::TimedOut))
}
+ _ = tokio::time::sleep_until(silent_at), if cfg.host_silence.is_some() => {
+ Ok(Some(ClientEnd::HostSilent))
+ }
_ = handle.0.notify.notified() => {
if handle.is_stopped() {
return Ok(Some(ClientEnd::Stopped));
@@ -308,6 +319,7 @@ pub async fn run_client(
}
msg = rx.recv() => {
let Some(msg) = msg? else { return Ok(Some(ClientEnd::HostEof)) };
+ last_rx = tokio::time::Instant::now();
on_message(msg, &tx, handle, handler)
}
}
@@ -417,3 +429,113 @@ fn on_message(
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ezd_proto::{ClientCaps, Codec, DisplayInfo, EncoderCaps, HostCaps};
+
+ struct Nop;
+
+ impl ClientHandler for Nop {
+ fn on_stream_config(&mut self, _: &StreamConfig) -> HandlerResult {
+ Ok(Flow::Continue)
+ }
+ fn on_codec_config(&mut self, _: VideoFrame) -> HandlerResult {
+ Ok(Flow::Continue)
+ }
+ fn on_video_frame(&mut self, _: VideoFrame, _: u64) -> HandlerResult {
+ Ok(Flow::Continue)
+ }
+ }
+
+ fn caps() -> ClientCaps {
+ ClientCaps {
+ display: DisplayInfo {
+ width_px: 1280,
+ height_px: 800,
+ density_dpi: 160,
+ refresh_rates_mhz: vec![60000],
+ current_refresh_mhz: 60000,
+ },
+ decoders: vec![],
+ stylus: false,
+ max_touch_points: 0,
+ }
+ }
+
+ /// A host that completes the handshake, answers pings while `answer` holds, then goes quiet
+ /// without closing the link, like a host process that died behind a USB accessory.
+ async fn host(link: Link, answer: Duration) {
+ let (tx, mut rx, _task) = link.into_mux(ezd_proto::DEFAULT_CHUNK_LEN);
+ tx.send_control(Message::Hello(Hello::new(Role::Host, "0.1.0", "pc")))
+ .unwrap();
+ tx.send_control(Message::HostCaps(HostCaps {
+ os: "test".into(),
+ gpu: "none".into(),
+ encoders: vec![EncoderCaps {
+ codec: Codec::H264,
+ name: "test".into(),
+ hardware: false,
+ }],
+ }))
+ .unwrap();
+ tx.send_control(Message::StreamConfig(StreamConfig {
+ width: 1280,
+ height: 800,
+ refresh_mhz: 60000,
+ codec: Codec::H264,
+ bitrate_kbps: 1000,
+ encoder_name: "test".into(),
+ }))
+ .unwrap();
+ let quiet_at = tokio::time::Instant::now() + answer;
+ while let Ok(Some(m)) = rx.recv().await {
+ if let Message::Ping(p) = m
+ && tokio::time::Instant::now() < quiet_at
+ {
+ let _ = tx.send_control(Message::Pong(Pong {
+ seq: p.seq,
+ t0_us: p.t0_us,
+ t1_us: 0,
+ t2_us: 0,
+ }));
+ }
+ }
+ }
+
+ fn cfg() -> ClientConfig {
+ let mut cfg = ClientConfig::new("tablet", caps());
+ cfg.ping_interval = Duration::from_millis(20);
+ cfg.host_silence = Some(Duration::from_millis(300));
+ cfg
+ }
+
+ #[tokio::test]
+ async fn a_host_that_goes_quiet_ends_the_session() {
+ let (client, server) = Link::duplex_pair(64 * 1024);
+ let host = tokio::spawn(host(server, Duration::from_millis(500)));
+ let start = tokio::time::Instant::now();
+ let out = run_client(client, cfg(), &ClientHandle::new(), &mut Nop)
+ .await
+ .unwrap();
+ assert_eq!(out.end, ClientEnd::HostSilent);
+ // Pongs kept it alive until the host went quiet.
+ assert!(start.elapsed() >= Duration::from_millis(700));
+ host.abort();
+ }
+
+ #[tokio::test]
+ async fn no_silence_limit_keeps_waiting() {
+ let (client, server) = Link::duplex_pair(64 * 1024);
+ let host = tokio::spawn(host(server, Duration::ZERO));
+ let mut cfg = cfg();
+ cfg.host_silence = None;
+ cfg.max_duration = Some(Duration::from_millis(600));
+ let out = run_client(client, cfg, &ClientHandle::new(), &mut Nop)
+ .await
+ .unwrap();
+ assert_eq!(out.end, ClientEnd::TimedOut);
+ host.abort();
+ }
+}
diff --git a/crates/ezd-fake-client/src/lib.rs b/crates/ezd-fake-client/src/lib.rs
index 6ca0e46..89fd955 100644
--- a/crates/ezd-fake-client/src/lib.rs
+++ b/crates/ezd-fake-client/src/lib.rs
@@ -125,6 +125,8 @@ pub enum ClientEnd {
HostEof,
/// `max_duration` elapsed.
TimedOut,
+ /// The host stopped answering.
+ HostSilent,
}
/// Everything the client observed.
@@ -513,6 +515,7 @@ pub async fn run_fake_client(
ezd_client_core::ClientEnd::HostBye(r) => ClientEnd::HostBye(r),
ezd_client_core::ClientEnd::HostEof => ClientEnd::HostEof,
ezd_client_core::ClientEnd::TimedOut => ClientEnd::TimedOut,
+ ezd_client_core::ClientEnd::HostSilent => ClientEnd::HostSilent,
};
report.clock_offset_us = outcome.clock_offset_us;
report.rtt_us = outcome.rtt_us;
diff --git a/crates/ezd-host-service/Cargo.toml b/crates/ezd-host-service/Cargo.toml
index bc4f6f2..39ec583 100644
--- a/crates/ezd-host-service/Cargo.toml
+++ b/crates/ezd-host-service/Cargo.toml
@@ -9,13 +9,16 @@ repository.workspace = true
rust-version.workspace = true
[features]
-default = ["ffmpeg", "wifi"]
+default = ["ffmpeg", "wifi", "aoa"]
# The software (synthetic) source and the Windows hardware encode go through FFmpeg, which needs
# its headers/libs at build time. `--no-default-features` builds on a machine without them (the
# Windows cross-check in CI); the synthetic source then reports "built without ffmpeg".
ffmpeg = ["dep:ezd-ffmpeg", "ezd-host-windows/ffmpeg"]
# Wi-Fi (QUIC) transport with PIN pairing and mDNS discovery. ring (QUIC's crypto) has C code that
# the Windows cross-check from Linux cannot build, hence the feature, like `ffmpeg`.
+# USB without developer mode: switches a connected tablet to Android accessory mode (libusb). The
+# Windows cross-check from Linux cannot build libusb, hence the feature.
+aoa = ["ezd-link/aoa"]
wifi = ["ezd-link/quic", "dep:mdns-sd", "dep:dirs", "dep:gethostname"]
[dependencies]
diff --git a/crates/ezd-host-service/src/aoa.rs b/crates/ezd-host-service/src/aoa.rs
new file mode 100644
index 0000000..7e5b64e
--- /dev/null
+++ b/crates/ezd-host-service/src/aoa.rs
@@ -0,0 +1,922 @@
+//! The USB accessory acceptor: polls the USB devices, switches a connected tablet to Android
+//! accessory mode and runs a session over its bulk endpoints.
+//!
+//! One loop, once per [`AoaHooks::poll_interval`], on the session slot (see
+//! [`Inner::slot`](crate::service::Inner)): when the slot is busy the cycle is skipped, so nothing
+//! is switched while a session streams. The permit is held from before a switch until the session
+//! ends, so a TCP or Wi-Fi client waits instead of racing the accessory.
+//!
+//! * A device that exposes an MTP or adb interface is switched (the handshake), at most once: if
+//! the app never talks on the accessory, the device is declined for the rest of the process and
+//! reset, which gives a phone its file transfer back.
+//! * A device already in accessory mode (left from an earlier session, or the host restarted) is
+//! opened once and kept open while it is silent; each cycle listens to it for a moment. Silence
+//! never declines it, since the app may simply not be running yet, and keeping the link means
+//! no bytes the app sends between two polls are lost.
+//! * A declined device is tried again once polls have seen it off the bus for
+//! [`AoaHooks::declined_rearm`] (the user replugged it, maybe after installing the app).
+//! * A device whose session ended normally stays in accessory mode and is picked up again by the
+//! next cycle when the app reconnects.
+//!
+//! All USB I/O runs on blocking threads behind [`UsbBackend`], which tests replace.
+
+use crate::config::{AoaMode, ServiceConfig};
+use crate::service::{Inner, stream_session};
+use crate::status::Transport;
+use ezd_link::Link;
+use ezd_link::aoa::{Aoa, DeviceInfo, Mode};
+use std::collections::HashMap;
+use std::io;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+use std::time::{Duration, Instant};
+use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
+use tokio::sync::watch;
+
+/// How often the USB devices are polled.
+pub const POLL_INTERVAL: Duration = Duration::from_secs(1);
+/// How long a device we just switched gets to send its first bytes: Android may first ask the
+/// user which app to open.
+pub const SWITCHED_TIMEOUT: Duration = Duration::from_secs(30);
+/// How long an accessory that was already there is listened to per poll.
+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
+/// How long a declined device must be gone from the bus before it is tried again (a replug after
+/// installing the app). The re-enumeration after our own reset takes far less.
+pub const DECLINED_REARM: Duration = Duration::from_secs(10);
+/// How long a device must have been on the bus before it is switched: a tablet that was just
+/// plugged in ignores the handshake while it is still setting up its USB functions.
+pub const SETTLE: Duration = Duration::from_secs(2);
+/// Switch attempts before a device that keeps failing the handshake is declined.
+pub const SWITCH_ATTEMPTS: u32 = 3;
+/// Delay between two switch attempts on the same device.
+pub const SWITCH_RETRY: Duration = Duration::from_secs(3);
+
+/// The USB operations the acceptor needs. Every method blocks.
+pub trait UsbBackend: Send + Sync + 'static {
+ /// The accessory devices and the devices that may be switched.
+ fn list(&self) -> io::Result>;
+ /// Switches `dev` to accessory mode and returns the accessory it turned into.
+ fn switch(&self, dev: &DeviceInfo) -> io::Result;
+ /// Opens the accessory `dev`. Dropping the link releases it.
+ fn open(&self, dev: &DeviceInfo) -> io::Result ;
+ /// Resets `dev`.
+ fn reset(&self, dev: &DeviceInfo) -> io::Result<()>;
+}
+
+impl UsbBackend for Aoa {
+ fn list(&self) -> io::Result> {
+ Aoa::list(self)
+ }
+
+ fn switch(&self, dev: &DeviceInfo) -> io::Result {
+ Aoa::switch(self, dev)
+ }
+
+ fn open(&self, dev: &DeviceInfo) -> io::Result {
+ Aoa::open(self, dev)
+ }
+
+ fn reset(&self, dev: &DeviceInfo) -> io::Result<()> {
+ Aoa::reset(self, dev)
+ }
+}
+
+/// Creates the backend; `Err` carries why USB accessory mode is unavailable. Called again later
+/// while it fails.
+pub type UsbFactory = Arc Result, String> + Send + Sync>;
+
+/// The parts of the acceptor that tests replace.
+#[derive(Clone)]
+pub struct AoaHooks {
+ /// Creates the USB backend (libusb by default).
+ pub backend: UsbFactory,
+ /// Delay between polls.
+ pub poll_interval: Duration,
+ /// How long a device we just switched may stay silent before it is given up on.
+ pub switched_timeout: Duration,
+ /// How long an accessory that was already present is listened to per poll.
+ pub probe_timeout: Duration,
+ /// How long a declined device must be absent from the bus before it is switched again.
+ pub declined_rearm: Duration,
+ /// How long a device must have been on the bus before it is switched.
+ pub settle: Duration,
+ /// Delay between two switch attempts on the same device.
+ pub switch_retry: Duration,
+}
+
+impl Default for AoaHooks {
+ fn default() -> Self {
+ AoaHooks {
+ backend: Arc::new(|| {
+ Aoa::new()
+ .map(|a| Arc::new(a) as Arc)
+ .map_err(|e| e.to_string())
+ }),
+ poll_interval: POLL_INTERVAL,
+ switched_timeout: SWITCHED_TIMEOUT,
+ probe_timeout: PROBE_TIMEOUT,
+ declined_rearm: DECLINED_REARM,
+ settle: SETTLE,
+ switch_retry: SWITCH_RETRY,
+ }
+ }
+}
+
+/// What listening to an accessory ended with.
+enum Heard {
+ /// The app sent its first bytes.
+ Data(Vec),
+ /// Nothing arrived in time.
+ Silent,
+ /// The stream ended or broke: the device went away.
+ Gone,
+ /// The service is stopping.
+ Stopped,
+}
+
+/// Accessories that are open and have not said anything yet, by `DeviceInfo::key`. Kept across
+/// polls: dropping a link while a blocking read is in flight would discard the bytes it reads.
+type Idle = HashMap;
+
+/// Devices given up on, by `DeviceInfo::key`, with when a poll first found them gone (`None`
+/// while they are on the bus). Only polls that saw the device missing count, so a long session or
+/// AOA being off does not re-arm a phone that stayed plugged in.
+type Declined = HashMap>;
+
+/// Switch candidates on the bus, by `DeviceInfo::key`: when they showed up and how their switch
+/// attempts went. Forgotten as soon as a poll misses them.
+type Candidates = HashMap;
+
+struct Candidate {
+ /// When a poll first saw the device.
+ seen: Instant,
+ /// Failed switch attempts so far.
+ failures: u32,
+ /// No attempt before this.
+ next_try: Instant,
+}
+
+/// Sets the reported USB problem; observers are only woken when it changes.
+fn set_problem(inner: &Inner, problem: Option) {
+ inner.aoa_problem.send_if_modified(|cur| {
+ let changed = *cur != problem;
+ if changed {
+ *cur = problem;
+ }
+ changed
+ });
+}
+
+/// Runs the acceptor until the service stops. Idles while `cfg.aoa` is off.
+pub(crate) async fn run(inner: Arc) {
+ let mut stop_rx = inner.stop.subscribe();
+ let mut cfg_rx = inner.cfg.subscribe();
+ let hooks = inner.hooks.aoa.clone();
+ let mut backend: Option> = None;
+ // Devices (by `DeviceInfo::key` of the original device) that are never switched again.
+ let mut declined = Declined::new();
+ let mut idle = Idle::new();
+ let mut candidates = Candidates::new();
+ let mut reported: Option = None;
+ loop {
+ if *stop_rx.borrow() {
+ break;
+ }
+ let cfg = cfg_rx.borrow_and_update().clone();
+ let mut wait = hooks.poll_interval;
+ if cfg.aoa == AoaMode::Off {
+ backend = None;
+ idle.clear();
+ reported = None;
+ set_problem(&inner, None);
+ tokio::select! {
+ _ = cfg_rx.changed() => {}
+ _ = stop_rx.changed() => {}
+ }
+ continue;
+ }
+ if backend.is_none() {
+ let make = hooks.backend.clone();
+ match tokio::task::spawn_blocking(move || make()).await {
+ Ok(Ok(b)) => {
+ backend = Some(b);
+ reported = None;
+ set_problem(&inner, None);
+ }
+ Ok(Err(reason)) => {
+ if reported.as_ref() != Some(&reason) {
+ tracing::info!("USB accessory mode unavailable: {reason}");
+ reported = Some(reason.clone());
+ }
+ set_problem(&inner, Some(reason));
+ // Initializing again is not free: look less often.
+ wait = hooks.poll_interval * 10;
+ }
+ Err(e) => tracing::error!("USB backend setup failed: {e}"),
+ }
+ }
+ if let Some(b) = &backend {
+ // Without the permit a session is running (or about to): leave the devices alone.
+ if let Ok(permit) = inner.slot.clone().try_acquire_owned() {
+ let state = PollState {
+ declined: &mut declined,
+ idle: &mut idle,
+ candidates: &mut candidates,
+ };
+ cycle(&inner, &cfg, b, state, &mut stop_rx).await;
+ drop(permit);
+ }
+ }
+ tokio::select! {
+ _ = tokio::time::sleep(wait) => {}
+ _ = cfg_rx.changed() => {}
+ _ = stop_rx.changed() => {}
+ }
+ }
+}
+
+/// One poll: listens to the accessories that are there, then switches one new device.
+async fn cycle(
+ inner: &Inner,
+ cfg: &ServiceConfig,
+ backend: &Arc,
+ state: PollState<'_>,
+ stop_rx: &mut watch::Receiver,
+) {
+ let PollState {
+ declined,
+ idle,
+ candidates,
+ } = state;
+ let list = match blocking(backend, |b| b.list()).await {
+ Ok(l) => l,
+ Err(e) => {
+ tracing::debug!("cannot list the USB devices: {e}");
+ return;
+ }
+ };
+ let hooks = &inner.hooks.aoa;
+
+ // A declined device that has been gone long enough is a candidate again.
+ let now = Instant::now();
+ declined.retain(|key, gone_since| {
+ if list.iter().any(|d| d.key() == *key) {
+ // Back on the bus: a short absence (our own reset) is forgotten.
+ let rearm = gone_since.is_some_and(|t| now.duration_since(t) >= hooks.declined_rearm);
+ *gone_since = None;
+ return !rearm;
+ }
+ let since = *gone_since.get_or_insert(now);
+ now.duration_since(since) < hooks.declined_rearm
+ });
+
+ // Accessories that went away take their links with them.
+ idle.retain(|key, _| {
+ list.iter()
+ .any(|d| d.mode == Mode::Accessory && d.key() == *key)
+ });
+ for acc in list.iter().filter(|d| d.mode == Mode::Accessory) {
+ let key = acc.key();
+ if !idle.contains_key(&key) {
+ let target = acc.clone();
+ match blocking(backend, move |b| b.open(&target)).await {
+ Ok(link) => {
+ idle.insert(key.clone(), link);
+ }
+ Err(e) => {
+ tracing::debug!("cannot open the accessory {}: {e}", acc.describe());
+ continue;
+ }
+ }
+ }
+ let Some(link) = idle.get_mut(&key) else {
+ continue;
+ };
+ match listen(link, hooks.probe_timeout, stop_rx).await {
+ Heard::Data(first) => {
+ if let Some(link) = idle.remove(&key) {
+ start_session(inner, cfg, backend, acc, link, first, stop_rx).await;
+ }
+ return;
+ }
+ Heard::Silent => {}
+ Heard::Gone => {
+ idle.remove(&key);
+ }
+ Heard::Stopped => return,
+ }
+ }
+ candidates.retain(|key, _| list.iter().any(|d| d.key() == *key));
+ for d in list.iter().filter(|d| d.mode != Mode::Accessory) {
+ candidates.entry(d.key()).or_insert(Candidate {
+ seen: now,
+ failures: 0,
+ next_try: now,
+ });
+ }
+ let Some(dev) = list.iter().find(|d| {
+ let key = d.key();
+ d.mode != Mode::Accessory
+ && !declined.contains_key(&key)
+ && candidates
+ .get(&key)
+ .is_some_and(|c| now.duration_since(c.seen) >= hooks.settle && now >= c.next_try)
+ }) else {
+ return;
+ };
+ tracing::info!(
+ "switching {} ({}) to accessory mode",
+ dev.describe(),
+ dev.mode
+ );
+ let target = dev.clone();
+ let acc = match blocking(backend, move |b| b.switch(&target)).await {
+ Ok(acc) => acc,
+ Err(e) => {
+ let c = candidates
+ .get_mut(&dev.key())
+ .expect("the device was just picked from the candidates");
+ c.failures += 1;
+ c.next_try = Instant::now() + hooks.switch_retry;
+ // A device without accessory support never gets it; others may just not be ready.
+ if e.kind() == io::ErrorKind::Unsupported || c.failures >= SWITCH_ATTEMPTS {
+ tracing::warn!("cannot switch {} to accessory mode: {e}", dev.describe());
+ declined.insert(dev.key(), None);
+ } else {
+ tracing::info!(
+ "cannot switch {} to accessory mode yet ({e}), trying again",
+ dev.describe()
+ );
+ }
+ return;
+ }
+ };
+ match open_and_listen(backend, &acc, hooks.switched_timeout, stop_rx).await {
+ Ok((link, first)) => {
+ start_session(inner, cfg, backend, &acc, link, first, stop_rx).await;
+ return;
+ }
+ Err(Heard::Stopped) => return,
+ Err(_) => {}
+ }
+ tracing::info!(
+ "{} did not start the app in accessory mode: giving up on it and resetting it",
+ dev.describe()
+ );
+ declined.insert(dev.key(), None);
+ if let Err(e) = blocking(backend, move |b| b.reset(&acc)).await {
+ tracing::warn!("cannot reset {}: {e}", dev.describe());
+ }
+}
+
+/// What the acceptor remembers between polls.
+struct PollState<'a> {
+ declined: &'a mut Declined,
+ idle: &'a mut Idle,
+ candidates: &'a mut Candidates,
+}
+
+/// Opens the freshly switched accessory and waits up to `wait` for the app's first bytes. On
+/// silence the link is dropped (the caller resets the device).
+async fn open_and_listen(
+ backend: &Arc,
+ acc: &DeviceInfo,
+ wait: Duration,
+ stop_rx: &mut watch::Receiver,
+) -> Result<(Link, Vec), Heard> {
+ let target = acc.clone();
+ let mut link = match blocking(backend, move |b| b.open(&target)).await {
+ Ok(l) => l,
+ Err(e) => {
+ tracing::debug!("cannot open the accessory {}: {e}", acc.describe());
+ return Err(Heard::Gone);
+ }
+ };
+ match listen(&mut link, wait, stop_rx).await {
+ Heard::Data(first) => Ok((link, first)),
+ other => Err(other),
+ }
+}
+
+/// Waits up to `wait` for the first bytes on `link`. Cancel-safe: on a timeout nothing was read,
+/// so the link can be listened to again.
+async fn listen(link: &mut Link, wait: Duration, stop_rx: &mut watch::Receiver) -> Heard {
+ let mut first = vec![0u8; 4096];
+ tokio::select! {
+ r = tokio::time::timeout(wait, link.reader.read(&mut first)) => match r {
+ Err(_elapsed) => Heard::Silent,
+ Ok(Ok(n)) if n > 0 => {
+ first.truncate(n);
+ Heard::Data(first)
+ }
+ Ok(_) => Heard::Gone,
+ },
+ _ = stop_rx.changed() => Heard::Stopped,
+ }
+}
+
+/// Runs the session with the bytes already read put back in front of the stream.
+async fn start_session(
+ inner: &Inner,
+ cfg: &ServiceConfig,
+ backend: &Arc,
+ acc: &DeviceInfo,
+ mut link: Link,
+ first: Vec,
+ stop_rx: &mut watch::Receiver,
+) {
+ tracing::info!(peer = %link.peer, "USB accessory is talking");
+ let inner_reader = std::mem::replace(&mut link.reader, Box::new(tokio::io::empty()));
+ link.reader = Box::new(PrefixRead {
+ prefix: first,
+ pos: 0,
+ inner: inner_reader,
+ });
+ if stream_session(inner, cfg, link, Transport::Aoa, stop_rx).await {
+ // The app is still in a session with an earlier host process and cannot tell that it
+ // ended (an accessory never reports the host closing it). A reset makes it see the cable
+ // go away; the device then comes back in its normal mode and is switched again.
+ tracing::info!(
+ "{} is still in an old session: resetting it",
+ acc.describe()
+ );
+ let target = acc.clone();
+ if let Err(e) = blocking(backend, move |b| b.reset(&target)).await {
+ tracing::warn!("cannot reset {}: {e}", acc.describe());
+ }
+ }
+}
+
+/// Runs `f` on a blocking thread.
+async fn blocking(
+ backend: &Arc,
+ f: impl FnOnce(&dyn UsbBackend) -> io::Result + Send + 'static,
+) -> io::Result {
+ let b = backend.clone();
+ tokio::task::spawn_blocking(move || f(&*b))
+ .await
+ .map_err(io::Error::other)?
+}
+
+/// Yields `prefix` first, then the bytes of `inner`.
+struct PrefixRead {
+ prefix: Vec,
+ pos: usize,
+ inner: ezd_link::BoxRead,
+}
+
+impl AsyncRead for PrefixRead {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut ReadBuf<'_>,
+ ) -> Poll> {
+ if self.pos < self.prefix.len() {
+ let n = (self.prefix.len() - self.pos).min(buf.remaining());
+ buf.put_slice(&self.prefix[self.pos..self.pos + n]);
+ self.pos += n;
+ return Poll::Ready(Ok(()));
+ }
+ Pin::new(&mut self.inner).poll_read(cx, buf)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::AdbMode;
+ use crate::service::tests::{
+ WAIT, cfg, connect, handshake, hooks, start, wait_session_end, wait_status,
+ };
+ use crate::status::HostStatus;
+ use ezd_proto::{Bye, Message};
+ use std::collections::VecDeque;
+ use std::sync::Mutex;
+ use std::time::Instant;
+ use tokio::time::timeout;
+
+ fn mtp(serial: Option<&str>) -> DeviceInfo {
+ DeviceInfo {
+ vid: 0x04e8,
+ pid: 0x6860,
+ bus: 1,
+ address: 4,
+ ports: vec![2],
+ product: Some("Tab".into()),
+ serial: serial.map(String::from),
+ mode: Mode::Mtp,
+ }
+ }
+
+ fn accessory_of(d: &DeviceInfo) -> DeviceInfo {
+ DeviceInfo {
+ vid: 0x18d1,
+ pid: 0x2d00,
+ address: d.address + 1,
+ mode: Mode::Accessory,
+ ..d.clone()
+ }
+ }
+
+ /// A tablet on the bus: MTP until switched, then an accessory until reset.
+ #[derive(Default)]
+ struct FakeUsb {
+ devices: Mutex>,
+ /// The tablet side of every opened accessory, oldest first.
+ peers: Mutex>,
+ calls: Mutex>,
+ fail_switch: Mutex,
+ }
+
+ impl FakeUsb {
+ fn with(devices: Vec) -> Arc {
+ Arc::new(FakeUsb {
+ devices: Mutex::new(devices),
+ ..FakeUsb::default()
+ })
+ }
+
+ fn calls(&self, prefix: &str) -> usize {
+ self.calls
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|c| c.starts_with(prefix))
+ .count()
+ }
+
+ async fn peer(&self) -> Link {
+ timeout(WAIT, async {
+ loop {
+ if let Some(l) = self.peers.lock().unwrap().pop_front() {
+ return l;
+ }
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("the acceptor never opened an accessory")
+ }
+
+ async fn until(&self, what: &str, f: impl Fn(&FakeUsb) -> bool) {
+ let t = Instant::now();
+ while !f(self) {
+ assert!(t.elapsed() < WAIT, "timed out waiting for {what}");
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ }
+ }
+
+ impl UsbBackend for FakeUsb {
+ fn list(&self) -> io::Result> {
+ self.calls.lock().unwrap().push("list".into());
+ Ok(self.devices.lock().unwrap().clone())
+ }
+
+ fn switch(&self, dev: &DeviceInfo) -> io::Result {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(format!("switch {}", dev.key()));
+ if *self.fail_switch.lock().unwrap() {
+ return Err(io::Error::other("not an accessory-capable device"));
+ }
+ let acc = accessory_of(dev);
+ let mut devices = self.devices.lock().unwrap();
+ devices.retain(|d| d.key() != dev.key());
+ devices.push(acc.clone());
+ Ok(acc)
+ }
+
+ fn open(&self, dev: &DeviceInfo) -> io::Result {
+ self.calls.lock().unwrap().push(format!("open {}", dev.pid));
+ let (host, tablet) = Link::duplex_pair(64 * 1024);
+ // Kept alive so the host does not see the end of the stream.
+ self.peers.lock().unwrap().push_back(tablet);
+ Ok(host)
+ }
+
+ fn reset(&self, dev: &DeviceInfo) -> io::Result<()> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(format!("reset {}", dev.pid));
+ // Back to MTP at the original address.
+ let mut devices = self.devices.lock().unwrap();
+ devices.retain(|d| d.mode != Mode::Accessory);
+ devices.push(DeviceInfo {
+ address: dev.address - 1,
+ ..mtp(dev.serial.as_deref())
+ });
+ Ok(())
+ }
+ }
+
+ fn aoa_hooks(fake: &Arc, switched: Duration, probe: Duration) -> crate::ServiceHooks {
+ let mut h = hooks();
+ let f = fake.clone();
+ h.aoa = AoaHooks {
+ backend: Arc::new(move || Ok(f.clone() as Arc)),
+ poll_interval: Duration::from_millis(20),
+ switched_timeout: switched,
+ probe_timeout: probe,
+ declined_rearm: Duration::from_secs(10),
+ settle: Duration::ZERO,
+ switch_retry: Duration::from_millis(30),
+ };
+ h
+ }
+
+ fn aoa_cfg() -> ServiceConfig {
+ ServiceConfig {
+ aoa: AoaMode::Auto,
+ adb: AdbMode::Off,
+ ..cfg()
+ }
+ }
+
+ #[tokio::test]
+ async fn a_candidate_is_switched_and_its_first_bytes_start_the_session() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_secs(10), Duration::from_millis(50)),
+ );
+ let mut status = svc.status();
+ let mut events = svc.events();
+ let tablet = fake.peer().await;
+ // The hello is sent right away, before the host reads anything: it must not be lost.
+ let (tx, _rx) = handshake(tablet).await;
+ let HostStatus::Streaming(live) =
+ wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await
+ else {
+ unreachable!()
+ };
+ assert_eq!(live.transport, Transport::Aoa);
+ assert_eq!(live.device_name, "tablet");
+ assert_eq!(fake.calls("switch"), 1);
+ assert_eq!(fake.calls("reset"), 0);
+
+ tx.send_control(Message::Bye(Bye {
+ reason: "done".into(),
+ }))
+ .unwrap();
+ wait_session_end(&mut events).await;
+ wait_status(&mut status, |s| matches!(s, HostStatus::Waiting { .. })).await;
+ // A device that ended normally stays in accessory mode and is not declined.
+ assert_eq!(fake.calls("reset"), 0);
+ assert_eq!(fake.calls("switch"), 1);
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_switched_device_that_stays_silent_is_declined_and_reset() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_millis(100), Duration::from_millis(50)),
+ );
+ fake.until("the reset", |f| f.calls("reset") == 1).await;
+ // The device is back as MTP and a candidate again, but it is never switched twice.
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ assert_eq!(fake.calls("switch"), 1);
+ assert_eq!(fake.calls("reset"), 1);
+ assert!(
+ fake.devices
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|d| d.mode == Mode::Mtp)
+ );
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_failing_switch_is_retried_a_few_times_then_given_up() {
+ let fake = FakeUsb::with(vec![mtp(None)]);
+ *fake.fail_switch.lock().unwrap() = true;
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_millis(100), Duration::from_millis(50)),
+ );
+ let attempts = SWITCH_ATTEMPTS as usize;
+ fake.until("the last attempt", |f| f.calls("switch") == attempts)
+ .await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert_eq!(fake.calls("switch"), attempts);
+ assert_eq!(fake.calls("reset"), 0);
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_busy_slot_means_no_switch() {
+ let fake = FakeUsb::with(vec![]);
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_secs(10), Duration::from_millis(50)),
+ );
+ let mut status = svc.status();
+ let mut events = svc.events();
+ let (tx, _rx) = connect(svc.local_addr().unwrap()).await;
+ wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await;
+
+ fake.devices.lock().unwrap().push(mtp(Some("R1")));
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert_eq!(fake.calls("switch"), 0);
+ assert!(matches!(*status.borrow(), HostStatus::Streaming(_)));
+
+ // Once the session is over the device is switched.
+ tx.send_control(Message::Bye(Bye {
+ reason: "done".into(),
+ }))
+ .unwrap();
+ wait_session_end(&mut events).await;
+ fake.until("the switch", |f| f.calls("switch") == 1).await;
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn an_accessory_that_was_already_there_is_never_declined() {
+ let accessory = accessory_of(&mtp(Some("R1")));
+ let fake = FakeUsb::with(vec![accessory]);
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_millis(30), Duration::from_millis(30)),
+ );
+ let mut status = svc.status();
+ // The app stays silent for several polls: no switch, no reset, nothing declined, and the
+ // accessory is opened once and kept.
+ fake.until("a few probes", |f| f.calls("list") >= 5).await;
+ assert_eq!(fake.calls("switch"), 0);
+ assert_eq!(fake.calls("reset"), 0);
+ assert_eq!(fake.calls("open"), 1);
+
+ // The app starts later: its first bytes (sent after earlier probes timed out) arrive
+ // intact and the session handshake succeeds on the same link.
+ let tablet = fake.peer().await;
+ let (_tx, _rx) = handshake(tablet).await;
+ let HostStatus::Streaming(live) =
+ wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await
+ else {
+ unreachable!()
+ };
+ assert_eq!(live.transport, Transport::Aoa);
+ assert_eq!(fake.calls("reset"), 0);
+ assert_eq!(fake.calls("open"), 1);
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn an_accessory_still_in_an_old_session_is_reset() {
+ let fake = FakeUsb::with(vec![accessory_of(&mtp(Some("R1")))]);
+ let svc = start(
+ aoa_cfg(),
+ aoa_hooks(&fake, Duration::from_millis(100), Duration::from_millis(50)),
+ );
+ // The app talks as if a session were running: no Hello, just its statistics.
+ let tablet = fake.peer().await;
+ let (tx, _rx, _t) = tablet.into_mux(ezd_proto::DEFAULT_CHUNK_LEN);
+ tx.send_control(Message::ClientStats(ezd_proto::ClientStats {
+ window_ms: 1000,
+ frames_received: 0,
+ frames_decoded: 0,
+ frames_dropped: 0,
+ decode_us_p50: 0,
+ decode_us_p95: 0,
+ e2e_us_p50: 0,
+ e2e_us_p95: 0,
+ }))
+ .unwrap();
+ fake.until("the reset", |f| f.calls("reset") == 1).await;
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_device_that_just_showed_up_is_left_to_settle() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let mut h = aoa_hooks(&fake, Duration::from_millis(100), Duration::from_millis(50));
+ h.aoa.settle = Duration::from_millis(400);
+ let svc = start(aoa_cfg(), h);
+ fake.until("a few polls", |f| f.calls("list") >= 3).await;
+ assert_eq!(fake.calls("switch"), 0);
+ fake.until("the switch", |f| f.calls("switch") == 1).await;
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ fn rearm_hooks(fake: &Arc, rearm: Duration) -> crate::ServiceHooks {
+ let mut h = aoa_hooks(fake, Duration::from_millis(100), Duration::from_millis(50));
+ h.aoa.declined_rearm = rearm;
+ h
+ }
+
+ #[tokio::test]
+ async fn a_declined_device_is_tried_again_after_being_gone_long_enough() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let svc = start(aoa_cfg(), rearm_hooks(&fake, Duration::from_millis(300)));
+ fake.until("the reset", |f| f.calls("reset") == 1).await;
+ // Unplugged for longer than the re-arm time, then plugged in again.
+ fake.devices.lock().unwrap().clear();
+ tokio::time::sleep(Duration::from_millis(600)).await;
+ fake.devices.lock().unwrap().push(mtp(Some("R1")));
+ fake.until("the second switch", |f| f.calls("switch") == 2)
+ .await;
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn the_re_enumeration_after_our_reset_does_not_re_arm_a_declined_device() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let svc = start(aoa_cfg(), rearm_hooks(&fake, Duration::from_millis(400)));
+ fake.until("the reset", |f| f.calls("reset") == 1).await;
+ // Gone for a moment while it re-enumerates, shorter than the re-arm time.
+ fake.devices.lock().unwrap().clear();
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ fake.devices.lock().unwrap().push(mtp(Some("R1")));
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert_eq!(fake.calls("switch"), 1);
+ assert_eq!(fake.calls("reset"), 1);
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn aoa_off_leaves_the_usb_devices_alone() {
+ let fake = FakeUsb::with(vec![mtp(Some("R1"))]);
+ let svc = start(
+ ServiceConfig {
+ aoa: AoaMode::Off,
+ ..aoa_cfg()
+ },
+ aoa_hooks(&fake, Duration::from_secs(10), Duration::from_millis(50)),
+ );
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(fake.calls.lock().unwrap().is_empty());
+
+ // Turning it on at run time starts the acceptor.
+ svc.apply(aoa_cfg(), false);
+ fake.until("the switch", |f| f.calls("switch") == 1).await;
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn an_unavailable_backend_is_reported_and_retried() {
+ let fake = FakeUsb::with(vec![]);
+ let present = Arc::new(Mutex::new(false));
+ let mut h = aoa_hooks(&fake, Duration::from_secs(10), Duration::from_millis(50));
+ let (f, p) = (fake.clone(), present.clone());
+ h.aoa.backend = Arc::new(move || {
+ if *p.lock().unwrap() {
+ Ok(f.clone() as Arc)
+ } else {
+ Err("UsbDk is not installed".into())
+ }
+ });
+ let svc = start(aoa_cfg(), h);
+ let mut status = svc.status();
+ let mut problem = svc.aoa_problem();
+ timeout(
+ WAIT,
+ problem.wait_for(|p| p.as_deref() == Some("UsbDk is not installed")),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ // Informational only: the host is not in an error state because of it.
+ assert!(matches!(*status.borrow(), HostStatus::Waiting { .. }));
+ // A TCP client is still served.
+ let mut events = svc.events();
+ let (tx, _rx) = connect(svc.local_addr().unwrap()).await;
+ wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await;
+ tx.send_control(Message::Bye(Bye {
+ reason: "done".into(),
+ }))
+ .unwrap();
+ wait_session_end(&mut events).await;
+ // USB shows up later (UsbDk gets installed): the acceptor notices and the error goes.
+ *present.lock().unwrap() = true;
+ fake.until("a poll", |f| f.calls("list") > 0).await;
+ wait_status(&mut status, |s| matches!(s, HostStatus::Waiting { .. })).await;
+ timeout(WAIT, problem.wait_for(|p| p.is_none()))
+ .await
+ .unwrap()
+ .unwrap();
+ timeout(WAIT, svc.stop()).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn bytes_read_for_the_probe_come_back_first() {
+ use tokio::io::AsyncReadExt;
+ let (host, mut tablet) = Link::duplex_pair(1024);
+ let mut reader = PrefixRead {
+ prefix: b"abc".to_vec(),
+ pos: 0,
+ inner: host.reader,
+ };
+ tokio::io::AsyncWriteExt::write_all(&mut tablet.writer, b"def")
+ .await
+ .unwrap();
+ let mut got = [0u8; 6];
+ reader.read_exact(&mut got).await.unwrap();
+ assert_eq!(&got, b"abcdef");
+ }
+}
diff --git a/crates/ezd-host-service/src/config.rs b/crates/ezd-host-service/src/config.rs
index 25fa8b1..5f1731f 100644
--- a/crates/ezd-host-service/src/config.rs
+++ b/crates/ezd-host-service/src/config.rs
@@ -40,6 +40,18 @@ pub enum AdbMode {
Off,
}
+/// What the service does about USB accessory mode (USB without developer mode).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum AoaMode {
+ /// Switch a connected tablet that shows up as a file-transfer or debugging device to
+ /// accessory mode and stream over USB. adb keeps working as the fallback.
+ #[default]
+ Auto,
+ /// Leave the USB devices alone.
+ Off,
+}
+
/// Transport kind carrying the stream; selects the default bitrate ceiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -143,6 +155,10 @@ pub struct ServiceConfig {
pub source: SourceKind,
/// adb handling.
pub adb: AdbMode,
+ /// USB accessory mode (USB without developer mode). `Auto` tries the accessory first, and
+ /// adb keeps working as the fallback. The field exists without the `aoa` feature too, so
+ /// config files stay portable between builds.
+ pub aoa: AoaMode,
/// Transport kind.
pub link: LinkChoice,
/// Highest refresh rate to use, in millihertz.
@@ -186,6 +202,7 @@ impl Default for ServiceConfig {
listen: SocketAddr::from(([127, 0, 0, 1], ezd_proto::DEFAULT_PORT)),
source: SourceKind::default(),
adb: AdbMode::default(),
+ aoa: AoaMode::default(),
link: LinkChoice::default(),
max_refresh_mhz: 120_000,
bitrate_kbps: None,
@@ -409,6 +426,34 @@ mod tests {
assert_eq!(off.prefs().hdr, HdrMode::Off);
}
+ #[test]
+ fn aoa_defaults_to_auto_and_reads_its_serde_name() {
+ assert_eq!(ServiceConfig::default().aoa, AoaMode::Auto);
+ let empty: ServiceConfig = serde_json::from_str("{}").unwrap();
+ assert_eq!(empty.aoa, AoaMode::Auto);
+ let off: ServiceConfig = serde_json::from_str(r#"{ "aoa": "off" }"#).unwrap();
+ assert_eq!(off.aoa, AoaMode::Off);
+ let auto: ServiceConfig = serde_json::from_str(r#"{ "aoa": "auto" }"#).unwrap();
+ assert_eq!(auto.aoa, AoaMode::Auto);
+ assert!(serde_json::from_str::(r#"{ "aoa": "sometimes" }"#).is_err());
+ }
+
+ #[test]
+ fn aoa_round_trips_and_an_old_config_keeps_the_default() {
+ let c = ServiceConfig {
+ aoa: AoaMode::Off,
+ ..ServiceConfig::default()
+ };
+ let json = serde_json::to_string(&c).unwrap();
+ assert!(json.contains(r#""aoa":"off""#), "{json}");
+ let back: ServiceConfig = serde_json::from_str(&json).unwrap();
+ assert_eq!(back, c);
+ // A file written before the key existed.
+ let old: ServiceConfig =
+ serde_json::from_str(r#"{ "listen": "127.0.0.1:4000", "adb": "off" }"#).unwrap();
+ assert_eq!(old.aoa, AoaMode::Auto);
+ }
+
#[test]
fn round_trips() {
let c = ServiceConfig {
diff --git a/crates/ezd-host-service/src/lib.rs b/crates/ezd-host-service/src/lib.rs
index 641bdb4..65792e8 100644
--- a/crates/ezd-host-service/src/lib.rs
+++ b/crates/ezd-host-service/src/lib.rs
@@ -6,6 +6,8 @@
//! notifications (a session ended, ...) come from [`HostService::events`].
//! * With the `wifi` feature, [`ServiceConfig::wifi`] adds a QUIC listener for paired tablets
//! next to the plaintext TCP one; only one session streams at a time across both.
+//! * With the `aoa` feature, [`ServiceConfig::aoa`] switches a connected tablet to Android accessory
+//! mode and streams over USB without developer mode (see [`aoa`]).
//! * [`HostService::apply`] changes the [`ServiceConfig`] while running; [`HostService::stop`]
//! ends the session cleanly and removes the adb reverses.
//!
@@ -13,6 +15,8 @@
//! English for logs.
pub mod adb;
+#[cfg(feature = "aoa")]
+pub mod aoa;
pub mod config;
pub mod error;
#[cfg(feature = "wifi")]
@@ -26,7 +30,7 @@ pub mod store;
mod wifi;
pub use adb::{AdbClient, AdbLocator, is_network_serial};
-pub use config::{AdbMode, HdrChoice, LinkChoice, PenChoice, ServiceConfig, SourceKind};
+pub use config::{AdbMode, AoaMode, HdrChoice, LinkChoice, PenChoice, ServiceConfig, SourceKind};
#[cfg(feature = "wifi")]
pub use config::{CongestionChoice, WifiConfig};
pub use error::ServiceError;
diff --git a/crates/ezd-host-service/src/service.rs b/crates/ezd-host-service/src/service.rs
index 7203fc9..d8110b5 100644
--- a/crates/ezd-host-service/src/service.rs
+++ b/crates/ezd-host-service/src/service.rs
@@ -1,4 +1,4 @@
-//! [`HostService`]: the accept loop, the adb watcher and the shared state.
+//! [`HostService`]: the accept loop, the adb watcher, the USB accessory acceptor and the shared state.
use crate::adb::{AdbClient, AdbLocator, Watcher, locate_system_adb};
use crate::config::{AdbMode, ServiceConfig, SourceKind};
@@ -40,6 +40,9 @@ pub struct ServiceHooks {
pub create_source: SourceFactory,
/// How long a pairing window stays open.
pub pairing_ttl: Duration,
+ /// The USB accessory acceptor: backend and timings.
+ #[cfg(feature = "aoa")]
+ pub aoa: crate::aoa::AoaHooks,
}
impl Default for ServiceHooks {
@@ -49,6 +52,8 @@ impl Default for ServiceHooks {
locate_adb: Arc::new(locate_system_adb),
create_source: Arc::new(create_source),
pairing_ttl: DEFAULT_PAIRING_TTL,
+ #[cfg(feature = "aoa")]
+ aoa: crate::aoa::AoaHooks::default(),
}
}
}
@@ -98,7 +103,7 @@ impl State {
..s.clone()
}),
Phase::Error(e) => HostStatus::Error(e.clone()),
- Phase::Waiting => match &self.adb_error {
+ Phase::Waiting => match self.adb_error.as_ref() {
Some(e) => HostStatus::Error(e.clone()),
None => HostStatus::Waiting {
devices: self.devices.clone(),
@@ -124,6 +129,8 @@ pub(crate) struct Inner {
pub(crate) slot: Arc,
/// The Wi-Fi listener, when on.
pub(crate) wifi_info: watch::Sender>,
+ /// Why USB accessory mode cannot be used (libusb or UsbDk unavailable); informational only.
+ pub(crate) aoa_problem: watch::Sender >,
#[cfg(feature = "wifi")]
pub(crate) wifi: Option>,
}
@@ -196,6 +203,8 @@ pub struct HostService {
inner: Arc,
serve: Option>,
watch: Option>,
+ /// The USB accessory acceptor.
+ aoa: Option>,
/// Wi-Fi tasks (accept loop, pairing watcher).
wifi_tasks: Vec>,
}
@@ -251,6 +260,7 @@ impl HostService {
hooks,
slot: Arc::new(Semaphore::new(1)),
wifi_info: watch::channel(None).0,
+ aoa_problem: watch::channel(None).0,
#[cfg(feature = "wifi")]
wifi,
});
@@ -265,10 +275,17 @@ impl HostService {
}
let serve = handle.spawn(serve(inner.clone(), listener, requested));
let watch = handle.spawn(watch_adb(inner.clone()));
+ // Runs whatever `cfg.aoa` is at the start: it idles while the mode is off and reacts when
+ // `apply` turns it on.
+ #[cfg(feature = "aoa")]
+ let aoa = Some(handle.spawn(crate::aoa::run(inner.clone())));
+ #[cfg(not(feature = "aoa"))]
+ let aoa = None;
Ok(HostService {
inner,
serve: Some(serve),
watch: Some(watch),
+ aoa,
wifi_tasks,
})
}
@@ -278,6 +295,13 @@ impl HostService {
self.inner.wifi_info.subscribe()
}
+ /// Why USB accessory mode is unavailable (libusb failed to initialize, UsbDk is missing);
+ /// `None` while it works or is off. Informational: adb and the network still work, and the
+ /// host status is not an error because of it.
+ pub fn aoa_problem(&self) -> watch::Receiver> {
+ self.inner.aoa_problem.subscribe()
+ }
+
/// Opens the pairing window with a new PIN (the PIN and QR URI arrive as
/// [`HostEvent::PairingOpen`]). Returns the PIN, or `None` when Wi-Fi is off.
#[cfg(feature = "wifi")]
@@ -358,7 +382,7 @@ impl HostService {
/// tearing a hardware encoder down while the process exits can deadlock in the driver.
pub async fn stop(mut self) {
self.inner.stop.send_replace(true);
- let tasks = [self.serve.take(), self.watch.take()]
+ let tasks = [self.serve.take(), self.watch.take(), self.aoa.take()]
.into_iter()
.flatten()
.chain(std::mem::take(&mut self.wifi_tasks));
@@ -456,26 +480,27 @@ async fn serve(inner: Arc, first: TcpListener, requested: SocketAddr) {
}
/// Creates the source and runs one session on `link`; the caller holds the session slot.
-async fn stream_session(
+pub(crate) async fn stream_session(
inner: &Inner,
cfg: &ServiceConfig,
link: Link,
transport: Transport,
stop_rx: &mut watch::Receiver,
-) {
+) -> bool {
let source = match (inner.hooks.create_source)(cfg) {
Ok(s) => s,
Err(e) => {
tracing::warn!("cannot create virtual source: {e}");
inner.emit(HostEvent::SourceFailed(e.clone()));
inner.update(|st| st.phase = Phase::Error(e));
- return;
+ return false;
}
};
- finish_session(inner, cfg, link, transport, source, stop_rx).await;
+ finish_session(inner, cfg, link, transport, source, stop_rx).await
}
-/// Runs a session with an existing source and reports its end.
+/// Runs a session with an existing source and reports its end. True when the peer opened with
+/// something other than its handshake: a client still in a session with an earlier host process.
pub(crate) async fn finish_session(
inner: &Inner,
cfg: &ServiceConfig,
@@ -483,14 +508,16 @@ pub(crate) async fn finish_session(
transport: Transport,
source: Box,
stop_rx: &mut watch::Receiver,
-) {
+) -> bool {
let result = run_session(inner, cfg, link, transport, source, stop_rx).await;
inner.update(|st| st.phase = Phase::Waiting);
match &result {
Ok(s) => tracing::debug!(end = ?s.end, "session returned"),
Err(e) => tracing::debug!("session failed: {e}"),
}
+ let stale = matches!(result, Err(ezd_host_core::SessionError::Unexpected { .. }));
inner.emit(HostEvent::SessionEnded(result.map_err(|e| e.to_string())));
+ stale
}
async fn run_session(
@@ -507,7 +534,7 @@ async fn run_session(
let (ev_tx, mut ev_rx) = mpsc::unbounded_channel();
// A Wi-Fi session is always a network link, whatever `cfg.link` says.
let prefs: Prefs = match transport {
- Transport::Tcp => cfg.prefs(),
+ Transport::Tcp | Transport::Aoa => cfg.prefs(),
Transport::Wifi => cfg.wifi_prefs(),
};
let session = run_host_session_with(
@@ -611,6 +638,7 @@ async fn release_all(watcher: &Arc>, adb: &Arc) {
pub(crate) mod tests {
use super::*;
use crate::adb::fake::{FakeAdb, device};
+ use crate::config::AoaMode;
use ezd_host_core::testing::ScriptedSource;
use ezd_link::adb::DeviceState as AdbState;
use ezd_link::{MuxReceiver, MuxSender};
@@ -626,6 +654,8 @@ pub(crate) mod tests {
ServiceConfig {
listen: "127.0.0.1:0".parse().unwrap(),
adb: AdbMode::Off,
+ // Tests never touch the USB devices of the machine they run on.
+ aoa: AoaMode::Off,
input: false,
..ServiceConfig::default()
}
@@ -639,6 +669,8 @@ pub(crate) mod tests {
Ok(Box::new(ScriptedSource::new(Duration::from_millis(5), 200)))
}),
pairing_ttl: Duration::from_secs(60),
+ #[cfg(feature = "aoa")]
+ aoa: crate::aoa::AoaHooks::default(),
}
}
diff --git a/crates/ezd-host-service/src/status.rs b/crates/ezd-host-service/src/status.rs
index 4b3a6b5..6e27349 100644
--- a/crates/ezd-host-service/src/status.rs
+++ b/crates/ezd-host-service/src/status.rs
@@ -52,6 +52,8 @@ pub enum Transport {
Tcp,
/// Wi-Fi: QUIC with a paired device.
Wifi,
+ /// USB without developer mode: the tablet in Android accessory mode.
+ Aoa,
}
/// The Wi-Fi listener, see [`HostService::wifi`](crate::HostService::wifi).
diff --git a/crates/ezd-host-service/src/wifi.rs b/crates/ezd-host-service/src/wifi.rs
index 66142fe..9d487c7 100644
--- a/crates/ezd-host-service/src/wifi.rs
+++ b/crates/ezd-host-service/src/wifi.rs
@@ -475,7 +475,7 @@ async fn session(
tokio::pin!(guard);
// The guard never completes; it is dropped when the session returns.
tokio::select! {
- () = &mut run => {}
+ _ = &mut run => {}
() = &mut guard => unreachable!("the guard never completes"),
}
}
diff --git a/crates/ezd-host/Cargo.toml b/crates/ezd-host/Cargo.toml
index bcc31f6..9e28cd4 100644
--- a/crates/ezd-host/Cargo.toml
+++ b/crates/ezd-host/Cargo.toml
@@ -13,12 +13,15 @@ name = "ezd-host"
path = "src/main.rs"
[features]
-default = ["ffmpeg", "wifi"]
+default = ["ffmpeg", "wifi", "aoa"]
# Encoder probing in `diag` and the service's FFmpeg paths. `--no-default-features` builds without
# FFmpeg headers (the Windows cross-check in CI).
ffmpeg = ["dep:ezd-ffmpeg", "ezd-host-service/ffmpeg", "ezd-host-windows/ffmpeg"]
# Wi-Fi (QUIC) transport: `run --wifi`, `--pair` and the `paired` commands.
wifi = ["ezd-host-service/wifi", "dep:qrcode"]
+# USB without developer mode (Android accessory mode through libusb): `run --aoa` and the `usb`
+# section of `diag`. `--no-default-features` builds without libusb (the Windows cross-check in CI).
+aoa = ["ezd-host-service/aoa", "ezd-link/aoa"]
[dependencies]
qrcode = { workspace = true, optional = true }
diff --git a/crates/ezd-host/i18n/de/ezd-host.ftl b/crates/ezd-host/i18n/de/ezd-host.ftl
index 68edf7e..4cd61bb 100644
--- a/crates/ezd-host/i18n/de/ezd-host.ftl
+++ b/crates/ezd-host/i18n/de/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Version anzeigen
run-source = Videoquelle: "synthetic" ist ein softwaregeneriertes Testbild mit bewegtem Mauszeiger, "virtual" ist ein echter virtueller Bildschirm, der vom Plattform-Backend aufgenommen und kodiert wird.
run-listen = Adresse, auf der gelauscht wird.
run-adb = Führt `adb reverse tcp:27183 tcp:` für SERIAL aus, oder für jedes bereite USB-Gerät, wenn keines angegeben ist; drahtlose Geräte brauchen eine explizite SERIAL. Bleibt aktiv, solange der Host läuft, und wird beim Beenden wieder entfernt.
+run-aoa = USB ohne Entwickleroptionen: "auto" schaltet ein angeschlossenes Tablet in den Android-Zubehörmodus und streamt über USB, "off" lässt die USB-Geräte in Ruhe. adb bleibt als Ausweichlösung nutzbar.
run-link = Verbindungsart: wählt die Standard-Bitratenobergrenze (usb 80 Mbit/s, Netzwerk 30 Mbit/s).
run-max-refresh-mhz = Höchste zu verwendende Bildwiederholrate in Millihertz.
run-bitrate-kbps = Feste Bitrate in kbit/s (auf die Obergrenze der Verbindung begrenzt).
@@ -43,6 +44,7 @@ vdd-err-failed = Treiber für virtuelle Bildschirme: { $detail }
err-adb-not-found = adb wurde nicht gefunden; installiere die Android-Platform-Tools, um USB zu nutzen (der Host lauscht weiter im Netzwerk)
err-adb-reverse = adb reverse für { $serial }: { $reason }
+aoa-unavailable = USB ohne Entwickleroptionen ist nicht verfügbar ({ $reason }); USB-Debugging funktioniert weiterhin.
err-binding = Binden von { $addr }: { $reason }
err-scale-nan = `{ $value }` ist keine Zahl
err-scale-range = Der Maßstab muss zwischen 0,25 und 1,0 liegen, erhalten: { $value }
diff --git a/crates/ezd-host/i18n/en/ezd-host.ftl b/crates/ezd-host/i18n/en/ezd-host.ftl
index 617b924..24385f4 100644
--- a/crates/ezd-host/i18n/en/ezd-host.ftl
+++ b/crates/ezd-host/i18n/en/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Print version
run-source = Video source: "synthetic" is a software-generated test pattern with a moving cursor, "virtual" is a real virtual display captured and encoded by the platform backend.
run-listen = Address to listen on.
run-adb = Run `adb reverse tcp:27183 tcp:` for SERIAL, or for every ready USB device when no serial is given; wireless devices need an explicit SERIAL. Kept up while the host runs and removed on exit.
+run-aoa = USB without developer mode: "auto" switches a connected tablet to Android accessory mode and streams over USB, "off" leaves the USB devices alone. adb keeps working as the fallback.
run-link = Link kind: selects the default bitrate ceiling (usb 80 Mbps, network 30 Mbps).
run-max-refresh-mhz = Highest refresh rate to use, in millihertz.
run-bitrate-kbps = Fixed bitrate in kbit/s (clamped to the link ceiling).
@@ -43,6 +44,7 @@ vdd-err-failed = Virtual Display Driver: { $detail }
err-adb-not-found = adb was not found; install the Android platform-tools to use USB (the host keeps listening on the network)
err-adb-reverse = adb reverse for { $serial }: { $reason }
+aoa-unavailable = USB without developer mode is unavailable ({ $reason }); USB debugging still works.
err-binding = binding { $addr }: { $reason }
err-scale-nan = `{ $value }` is not a number
err-scale-range = scale must be between 0.25 and 1.0, got { $value }
diff --git a/crates/ezd-host/i18n/es/ezd-host.ftl b/crates/ezd-host/i18n/es/ezd-host.ftl
index 2a3ba03..0423112 100644
--- a/crates/ezd-host/i18n/es/ezd-host.ftl
+++ b/crates/ezd-host/i18n/es/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Muestra la versión
run-source = Fuente de video: "synthetic" es un patrón de prueba generado por software con un cursor en movimiento, "virtual" es una pantalla virtual real capturada y codificada por el backend de la plataforma.
run-listen = Dirección en la que escuchar.
run-adb = Ejecuta `adb reverse tcp:27183 tcp:` para SERIAL, o para cada dispositivo USB listo si no se indica ninguno; los dispositivos inalámbricos requieren un SERIAL explícito. Se mantiene mientras el host corre y se elimina al salir.
+run-aoa = USB sin modo desarrollador: "auto" pasa una tablet conectada al modo accesorio de Android y transmite por USB, "off" no toca los dispositivos USB. adb sigue funcionando como alternativa.
run-link = Tipo de enlace: elige el límite de bitrate por defecto (usb 80 Mbps, red 30 Mbps).
run-max-refresh-mhz = Frecuencia de actualización máxima a usar, en milihercios.
run-bitrate-kbps = Bitrate fijo en kbit/s (limitado al máximo del enlace).
@@ -43,6 +44,7 @@ vdd-err-failed = Controlador de pantalla virtual: { $detail }
err-adb-not-found = no se encontró adb; instalá las platform-tools de Android para usar USB (el host sigue escuchando en la red)
err-adb-reverse = adb reverse para { $serial }: { $reason }
+aoa-unavailable = USB sin modo desarrollador no está disponible ({ $reason }); la depuración USB sigue funcionando.
err-binding = enlazando { $addr }: { $reason }
err-scale-nan = `{ $value }` no es un número
err-scale-range = la escala debe estar entre 0,25 y 1,0, se recibió { $value }
diff --git a/crates/ezd-host/i18n/fr/ezd-host.ftl b/crates/ezd-host/i18n/fr/ezd-host.ftl
index ad9e7a9..4c40483 100644
--- a/crates/ezd-host/i18n/fr/ezd-host.ftl
+++ b/crates/ezd-host/i18n/fr/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Affiche la version
run-source = Source vidéo : "synthetic" est une mire générée par logiciel avec un curseur en mouvement, "virtual" est un véritable écran virtuel capturé et encodé par le backend de la plateforme.
run-listen = Adresse d'écoute.
run-adb = Exécute `adb reverse tcp:27183 tcp:` pour SERIAL, ou pour chaque appareil USB prêt si aucun n'est indiqué ; les appareils sans fil exigent un SERIAL explicite. Maintenu tant que l'hôte tourne et supprimé à la sortie.
+run-aoa = USB sans mode développeur : « auto » fait passer une tablette connectée en mode accessoire Android et diffuse par USB, « off » ne touche pas aux appareils USB. adb reste disponible en secours.
run-link = Type de liaison : choisit le débit maximal par défaut (usb 80 Mbit/s, réseau 30 Mbit/s).
run-max-refresh-mhz = Fréquence de rafraîchissement maximale à utiliser, en millihertz.
run-bitrate-kbps = Débit fixe en kbit/s (limité au maximum de la liaison).
@@ -43,6 +44,7 @@ vdd-err-failed = Pilote d'affichage virtuel : { $detail }
err-adb-not-found = adb est introuvable ; installez les platform-tools d'Android pour utiliser l'USB (l'hôte continue d'écouter sur le réseau)
err-adb-reverse = adb reverse pour { $serial } : { $reason }
+aoa-unavailable = L'USB sans mode développeur est indisponible ({ $reason }) ; le débogage USB fonctionne toujours.
err-binding = liaison à { $addr } : { $reason }
err-scale-nan = `{ $value }` n'est pas un nombre
err-scale-range = l'échelle doit être comprise entre 0,25 et 1,0, reçu { $value }
diff --git a/crates/ezd-host/i18n/it/ezd-host.ftl b/crates/ezd-host/i18n/it/ezd-host.ftl
index a384caf..56ba808 100644
--- a/crates/ezd-host/i18n/it/ezd-host.ftl
+++ b/crates/ezd-host/i18n/it/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Mostra la versione
run-source = Sorgente video: "synthetic" è un pattern di prova generato via software con un cursore in movimento, "virtual" è uno schermo virtuale reale catturato e codificato dal backend della piattaforma.
run-listen = Indirizzo su cui restare in ascolto.
run-adb = Esegue `adb reverse tcp:27183 tcp:` per SERIAL, o per ogni dispositivo USB pronto se non ne è indicato nessuno; i dispositivi wireless richiedono un SERIAL esplicito. Mantenuto finché l'host è in esecuzione, rimosso all'uscita.
+run-aoa = USB senza modalità sviluppatore: "auto" porta un tablet collegato in modalità accessorio Android e trasmette via USB, "off" non tocca i dispositivi USB. adb continua a funzionare come alternativa.
run-link = Tipo di collegamento: sceglie il limite di bitrate predefinito (usb 80 Mbps, rete 30 Mbps).
run-max-refresh-mhz = Frequenza di aggiornamento massima da usare, in millihertz.
run-bitrate-kbps = Bitrate fisso in kbit/s (limitato al massimo del collegamento).
@@ -43,6 +44,7 @@ vdd-err-failed = Driver di schermo virtuale: { $detail }
err-adb-not-found = adb non trovato; installa le platform-tools di Android per usare l'USB (l'host continua ad ascoltare sulla rete)
err-adb-reverse = adb reverse per { $serial }: { $reason }
+aoa-unavailable = L'USB senza modalità sviluppatore non è disponibile ({ $reason }); il debug USB funziona ancora.
err-binding = binding su { $addr }: { $reason }
err-scale-nan = `{ $value }` non è un numero
err-scale-range = la scala deve essere compresa tra 0,25 e 1,0, ricevuto { $value }
diff --git a/crates/ezd-host/i18n/pt/ezd-host.ftl b/crates/ezd-host/i18n/pt/ezd-host.ftl
index fe4b4e0..192480b 100644
--- a/crates/ezd-host/i18n/pt/ezd-host.ftl
+++ b/crates/ezd-host/i18n/pt/ezd-host.ftl
@@ -10,6 +10,7 @@ version-flag = Exibe a versão
run-source = Fonte de vídeo: "synthetic" é um padrão de teste gerado por software com um cursor em movimento, "virtual" é uma tela virtual real capturada e codificada pelo backend da plataforma.
run-listen = Endereço em que escutar.
run-adb = Executa `adb reverse tcp:27183 tcp:` para SERIAL, ou para cada dispositivo USB pronto se nenhum for informado; dispositivos sem fio exigem um SERIAL explícito. Mantido enquanto o host roda e removido ao sair.
+run-aoa = USB sem modo desenvolvedor: "auto" muda um tablet conectado para o modo acessório do Android e transmite por USB, "off" não mexe nos dispositivos USB. O adb continua funcionando como alternativa.
run-link = Tipo de conexão: define o limite de bitrate padrão (usb 80 Mbps, rede 30 Mbps).
run-max-refresh-mhz = Maior taxa de atualização a usar, em milihertz.
run-bitrate-kbps = Bitrate fixo em kbit/s (limitado ao máximo da conexão).
@@ -43,6 +44,7 @@ vdd-err-failed = Driver de vídeo virtual: { $detail }
err-adb-not-found = adb não encontrado; instale as platform-tools do Android para usar USB (o host continua escutando na rede)
err-adb-reverse = adb reverse para { $serial }: { $reason }
+aoa-unavailable = USB sem modo desenvolvedor indisponível ({ $reason }); a depuração USB continua funcionando.
err-binding = vinculando { $addr }: { $reason }
err-scale-nan = `{ $value }` não é um número
err-scale-range = a escala deve estar entre 0,25 e 1,0, recebido { $value }
diff --git a/crates/ezd-host/src/diag.rs b/crates/ezd-host/src/diag.rs
index 59e5d83..5e26ea8 100644
--- a/crates/ezd-host/src/diag.rs
+++ b/crates/ezd-host/src/diag.rs
@@ -30,6 +30,7 @@ pub fn sections() -> Vec> {
v.push(Box::new(Platform));
v.push(Box::new(Encoders));
v.push(Box::new(AdbInfo));
+ v.push(Box::new(UsbInfo));
v
}
@@ -232,6 +233,57 @@ impl Section for AdbInfo {
}
}
+/// USB without developer mode: whether libusb works and which devices could be switched.
+struct UsbInfo;
+impl Section for UsbInfo {
+ fn name(&self) -> &'static str {
+ "usb"
+ }
+ #[cfg(not(feature = "aoa"))]
+ fn collect(&self) -> Value {
+ json!({ "aoa": { "available": false, "reason": "built without the aoa feature" } })
+ }
+ #[cfg(feature = "aoa")]
+ fn collect(&self) -> Value {
+ use ezd_link::aoa::Aoa;
+ let mut v = json!({ "libusb": Aoa::libusb_version() });
+ let aoa = match Aoa::new() {
+ Ok(a) => a,
+ Err(e) => {
+ v["aoa"] = json!({ "available": false, "reason": e.to_string() });
+ #[cfg(windows)]
+ {
+ v["usbdk"] = json!({ "present": false });
+ }
+ return v;
+ }
+ };
+ v["aoa"] = json!({ "available": true });
+ #[cfg(windows)]
+ {
+ // libusb only initializes with UsbDk when it is installed.
+ v["usbdk"] = json!({ "present": true });
+ }
+ // Serial numbers are left out on purpose: a report gets pasted into issues.
+ v["devices"] = match aoa.list() {
+ Ok(list) => Value::Array(
+ list.into_iter()
+ .map(|d| {
+ json!({
+ "vid": format!("{:04x}", d.vid),
+ "pid": format!("{:04x}", d.pid),
+ "product": d.product,
+ "mode": d.mode.as_str(),
+ })
+ })
+ .collect(),
+ ),
+ Err(e) => json!({ "error": e.to_string() }),
+ };
+ v
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -243,6 +295,16 @@ mod tests {
assert!(v["arch"].is_string());
}
+ #[test]
+ fn the_usb_section_reports_aoa_and_no_serials() {
+ let v = UsbInfo.collect();
+ assert!(v["aoa"]["available"].is_boolean());
+ if v["aoa"]["available"] == false {
+ assert!(v["aoa"]["reason"].is_string());
+ }
+ assert!(!v.to_string().contains("serial"));
+ }
+
#[test]
fn section_names_are_unique() {
let names: Vec<_> = sections().iter().map(|s| s.name()).collect();
diff --git a/crates/ezd-host/src/run.rs b/crates/ezd-host/src/run.rs
index a186288..59c23b9 100644
--- a/crates/ezd-host/src/run.rs
+++ b/crates/ezd-host/src/run.rs
@@ -5,7 +5,7 @@ use anyhow::{Result, anyhow};
use clap::{Args, Command, ValueEnum};
use ezd_host_core::SessionSummary;
use ezd_host_service::{
- AdbMode, HostEvent, HostService, HostStatus, LinkChoice, PenChoice, ServiceConfig,
+ AdbMode, AoaMode, HostEvent, HostService, HostStatus, LinkChoice, PenChoice, ServiceConfig,
ServiceError, SourceKind,
};
use i18n_embed::fluent::FluentLanguageLoader;
@@ -23,6 +23,12 @@ pub enum LinkArg {
Network,
}
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum AoaArg {
+ Auto,
+ Off,
+}
+
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum PenModeArg {
Tablet,
@@ -38,6 +44,8 @@ pub struct RunArgs {
listen: String,
#[arg(long, num_args = 0..=1, value_name = "SERIAL")]
adb: Option>,
+ #[arg(long, value_enum, default_value = "auto")]
+ aoa: AoaArg,
#[arg(long, value_enum, default_value = "usb")]
link: LinkArg,
#[arg(long, default_value_t = 120_000)]
@@ -83,6 +91,7 @@ pub fn localize(cmd: Command, l: &FluentLanguageLoader) -> Command {
.mut_arg("source", |a| a.help(fl!(l, "run-source")))
.mut_arg("listen", |a| a.help(fl!(l, "run-listen")))
.mut_arg("adb", |a| a.help(fl!(l, "run-adb")))
+ .mut_arg("aoa", |a| a.help(fl!(l, "run-aoa")))
.mut_arg("link", |a| a.help(fl!(l, "run-link")))
.mut_arg("max_refresh_mhz", |a| a.help(fl!(l, "run-max-refresh-mhz")))
.mut_arg("bitrate_kbps", |a| a.help(fl!(l, "run-bitrate-kbps")))
@@ -143,6 +152,10 @@ fn config(args: &RunArgs) -> Result {
Some(None) => AdbMode::Auto,
Some(Some(serial)) => AdbMode::Serial(serial.clone()),
},
+ aoa: match args.aoa {
+ AoaArg::Auto => AoaMode::Auto,
+ AoaArg::Off => AoaMode::Off,
+ },
link: match args.link {
LinkArg::Usb => LinkChoice::Usb,
LinkArg::Network => LinkChoice::Network,
@@ -208,6 +221,7 @@ pub async fn run(args: RunArgs) -> Result<()> {
}
let mut shown: Shown = None;
let reporter = tokio::spawn(report_errors(service.status()));
+ let aoa_notice = tokio::spawn(report_aoa_problem(service.aoa_problem()));
// The service owns the event sender, so the channel stays open until `stop`.
loop {
@@ -236,6 +250,7 @@ pub async fn run(args: RunArgs) -> Result<()> {
log_event(Ok(ev), &mut shown);
}
reporter.abort();
+ aoa_notice.abort();
Ok(())
}
@@ -295,6 +310,20 @@ async fn report_errors(mut status: tokio::sync::watch::Receiver) {
}
}
+/// Prints a one-line notice whenever USB accessory mode turns out to be unavailable. It is not an
+/// error: adb and the network keep working.
+async fn report_aoa_problem(mut problem: tokio::sync::watch::Receiver>) {
+ loop {
+ let reason = problem.borrow_and_update().clone();
+ if let Some(reason) = reason {
+ eprintln!("{}", fl!("aoa-unavailable", reason = reason.as_str()));
+ }
+ if problem.changed().await.is_err() {
+ break;
+ }
+ }
+}
+
fn log_session_end(r: Result) {
match r {
Ok(s) => tracing::info!(
diff --git a/crates/ezd-link/Cargo.toml b/crates/ezd-link/Cargo.toml
index 3f10696..0886ba3 100644
--- a/crates/ezd-link/Cargo.toml
+++ b/crates/ezd-link/Cargo.toml
@@ -22,13 +22,21 @@ rcgen = { version = "0.14", default-features = false, features = ["ring"], optio
ring = { version = "0.17", optional = true }
spake2 = { version = "0.4", optional = true }
serde = { workspace = true, optional = true }
+# USB accessory (AOA) transport (`aoa` feature, not on Android). libusb comes from the system on
+# Linux; Windows builds it from source.
+rusb = { version = "0.9", optional = true }
[features]
default = ["quic"]
+# Host side of the Android Open Accessory USB transport (libusb through rusb).
+aoa = ["dep:rusb"]
quic = ["dep:quinn", "dep:rustls", "dep:rcgen", "dep:ring", "dep:spake2", "dep:serde"]
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
socket2 = { version = "0.6", features = ["all"] }
+[target.'cfg(windows)'.dependencies]
+rusb = { version = "0.9", optional = true, features = ["vendored"] }
+
[lints]
workspace = true
diff --git a/crates/ezd-link/src/aoa.rs b/crates/ezd-link/src/aoa.rs
new file mode 100644
index 0000000..3bb44ee
--- /dev/null
+++ b/crates/ezd-link/src/aoa.rs
@@ -0,0 +1,892 @@
+//! Host side of the Android Open Accessory (AOA) USB transport (libusb through `rusb`).
+//!
+//! A tablet that shows up as a file-transfer (MTP) or debugging (adb) device is asked to switch to
+//! accessory mode with a few vendor control requests. It then re-enumerates as a Google
+//! accessory device whose two bulk endpoints carry the normal ezdisplay byte stream, so no
+//! developer mode is needed on the tablet.
+//!
+//! The decisions that need no hardware (which devices may be switched, which one is the
+//! accessory after the switch, how a write is split) are plain functions and types, tested with
+//! fixtures. [`Aoa`] does the USB I/O and every call on it blocks: use `spawn_blocking` from async
+//! code. [`Aoa::open`] must run inside a tokio runtime (it builds a [`Link`] with
+//! [`Link::from_blocking`]).
+
+use crate::BlockingOptions;
+use crate::link::Link;
+use rusb::{Context, Device, DeviceHandle, Direction, Recipient, RequestType, UsbContext};
+use std::collections::HashMap;
+use std::fmt;
+use std::io::{self, ErrorKind, Read, Write};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+/// USB vendor id of every accessory-mode device.
+pub const ACCESSORY_VID: u16 = 0x18D1;
+/// Product ids of accessory-mode devices (`2D01`, `2D03` and `2D05` also expose adb).
+pub const ACCESSORY_PIDS: std::ops::RangeInclusive = 0x2D00..=0x2D05;
+/// The accessory data interface is always the first one.
+pub const ACCESSORY_INTERFACE: u8 = 0;
+
+/// Timeout of every control request of the handshake.
+pub const CONTROL_TIMEOUT: Duration = Duration::from_secs(1);
+/// How long a switched device may take to show up again as an accessory.
+pub const REENUMERATE_TIMEOUT: Duration = Duration::from_secs(5);
+/// How long a bulk read waits before it returns `TimedOut` (so the link can notice it was dropped).
+pub const READ_TIMEOUT: Duration = Duration::from_millis(200);
+/// How long a bulk write may take; a timeout is a hard error.
+pub const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
+/// Bytes asked for in each bulk read and most bytes sent in one bulk transfer.
+pub const TRANSFER_LEN: usize = 16 * 1024;
+
+const REQ_GET_PROTOCOL: u8 = 51;
+const REQ_SEND_STRING: u8 = 52;
+const REQ_START: u8 = 53;
+
+/// Why AOA cannot be used on this machine (no libusb, or no UsbDk on Windows).
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("{0}")]
+pub struct Unavailable(pub String);
+
+/// True for a device already in accessory mode.
+pub fn is_accessory(vid: u16, pid: u16) -> bool {
+ vid == ACCESSORY_VID && ACCESSORY_PIDS.contains(&pid)
+}
+
+/// True for an accessory-mode device that also exposes adb.
+pub fn accessory_has_adb(pid: u16) -> bool {
+ matches!(pid, 0x2D01 | 0x2D03 | 0x2D05)
+}
+
+/// Class, subclass and protocol of one USB interface.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct InterfaceClass {
+ /// Class code.
+ pub class: u8,
+ /// Subclass code.
+ pub subclass: u8,
+ /// Protocol code.
+ pub protocol: u8,
+}
+
+impl InterfaceClass {
+ /// Still Image / MTP (06/01/01).
+ pub fn is_mtp(self) -> bool {
+ (self.class, self.subclass, self.protocol) == (0x06, 0x01, 0x01)
+ }
+
+ /// Android Debug Bridge (ff/42/01).
+ pub fn is_adb(self) -> bool {
+ (self.class, self.subclass, self.protocol) == (0xFF, 0x42, 0x01)
+ }
+}
+
+/// What a USB device the module cares about currently is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Mode {
+ /// File transfer (an MTP interface).
+ Mtp,
+ /// Debugging (an adb interface, no MTP).
+ Adb,
+ /// Already in accessory mode.
+ Accessory,
+}
+
+impl Mode {
+ /// Lower-case name for logs and diagnostics.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Mode::Mtp => "mtp",
+ Mode::Adb => "adb",
+ Mode::Accessory => "accessory",
+ }
+ }
+}
+
+impl fmt::Display for Mode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+/// The mode of a device, or `None` when it is none of our business: only accessory devices and
+/// devices with an MTP or adb interface are ever listed, so vendor requests never reach anything
+/// else (a keyboard, a storage stick, ...).
+pub fn classify(vid: u16, pid: u16, interfaces: &[InterfaceClass]) -> Option {
+ if is_accessory(vid, pid) {
+ Some(Mode::Accessory)
+ } else if interfaces.iter().any(|i| i.is_mtp()) {
+ Some(Mode::Mtp)
+ } else if interfaces.iter().any(|i| i.is_adb()) {
+ Some(Mode::Adb)
+ } else {
+ None
+ }
+}
+
+/// One USB device from [`Aoa::list`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeviceInfo {
+ /// Vendor id.
+ pub vid: u16,
+ /// Product id.
+ pub pid: u16,
+ /// Bus number.
+ pub bus: u8,
+ /// Address on the bus.
+ pub address: u8,
+ /// Port path from the root hub.
+ pub ports: Vec,
+ /// Product string, when the device could be read.
+ pub product: Option,
+ /// Serial number string, when the device has one and could be read. Never print it.
+ pub serial: Option,
+ /// Current mode.
+ pub mode: Mode,
+}
+
+impl DeviceInfo {
+ /// Identity that survives a re-enumeration of the same device: the serial number when there
+ /// is one, otherwise the place it is plugged in. Used to remember devices we gave up on.
+ pub fn key(&self) -> String {
+ match &self.serial {
+ Some(s) => format!("{:04x}:{:04x}:{s}", self.vid, self.pid),
+ None => {
+ let ports: Vec = self.ports.iter().map(|p| p.to_string()).collect();
+ format!(
+ "{:04x}:{:04x}@{}-{}",
+ self.vid,
+ self.pid,
+ self.bus,
+ ports.join(".")
+ )
+ }
+ }
+ }
+
+ /// Readable description without the serial number, for logs and diagnostics.
+ pub fn describe(&self) -> String {
+ let id = format!("{:04x}:{:04x}", self.vid, self.pid);
+ match &self.product {
+ Some(p) => format!("{id} {p}"),
+ None => id,
+ }
+ }
+
+ fn same_device(&self, other: &DeviceInfo) -> bool {
+ (self.bus, self.address) == (other.bus, other.address)
+ }
+}
+
+/// Picks the accessory that `original` turned into after the switch. `before` is the accessory
+/// devices that were present before it, `now` the current device list.
+///
+/// A device with a serial number is matched by serial (an accessory that reports none is accepted
+/// too, since some devices drop the string); without a serial, the first accessory that was not
+/// there before is taken.
+pub fn pick_accessory<'a>(
+ original: &DeviceInfo,
+ before: &[DeviceInfo],
+ now: &'a [DeviceInfo],
+) -> Option<&'a DeviceInfo> {
+ let fresh =
+ |d: &&DeviceInfo| d.mode == Mode::Accessory && !before.iter().any(|b| b.same_device(d));
+ match &original.serial {
+ Some(serial) => now
+ .iter()
+ .filter(fresh)
+ .find(|d| d.serial.as_ref() == Some(serial))
+ .or_else(|| now.iter().filter(fresh).find(|d| d.serial.is_none())),
+ None => now.iter().find(fresh),
+ }
+}
+
+/// The identification strings sent with request 52, as `(index, bytes)` with the trailing NUL.
+pub fn accessory_strings() -> [(u16, Vec); 6] {
+ let nul = |s: &str| {
+ let mut v = s.as_bytes().to_vec();
+ v.push(0);
+ v
+ };
+ [
+ (0, nul("LibreStatic")),
+ (1, nul("ezdisplay")),
+ (2, nul("ezdisplay extended display")),
+ (3, nul(env!("CARGO_PKG_VERSION"))),
+ (4, nul("https://github.com/LibreStatic/ezdisplay")),
+ (5, nul("ezdisplay")),
+ ]
+}
+
+/// The protocol version from the 2-byte answer to request 51; `None` when it is short or zero
+/// (the device does not support accessory mode).
+pub fn parse_protocol(answer: &[u8]) -> Option {
+ let v = u16::from_le_bytes([*answer.first()?, *answer.get(1)?]);
+ (v >= 1).then_some(v)
+}
+
+/// Length of the next bulk transfer for `remaining` bytes: at most `limit`, and never a multiple
+/// of the OUT endpoint's `max_packet`. The accessory gadget completes a read early on a short
+/// packet and reads a zero-length packet as end of stream, so a transfer that would end on a full
+/// packet is sent one byte shorter and the rest goes in the next one.
+pub fn transfer_len(remaining: usize, limit: usize, max_packet: usize) -> usize {
+ let n = remaining.min(limit);
+ if max_packet > 1 && n > 1 && n % max_packet == 0 {
+ n - 1
+ } else {
+ n
+ }
+}
+
+/// Bulk transfers of one claimed accessory interface; the seam that tests replace.
+pub trait BulkIo: Send + Sync {
+ /// One bulk IN transfer.
+ fn read_bulk(&self, buf: &mut [u8], timeout: Duration) -> rusb::Result;
+ /// One bulk OUT transfer.
+ fn write_bulk(&self, buf: &[u8], timeout: Duration) -> rusb::Result;
+}
+
+fn io_error(e: rusb::Error) -> io::Error {
+ let kind = match e {
+ rusb::Error::Timeout => ErrorKind::TimedOut,
+ rusb::Error::NoDevice => ErrorKind::NotConnected,
+ rusb::Error::Pipe => ErrorKind::BrokenPipe,
+ rusb::Error::Interrupted => ErrorKind::Interrupted,
+ rusb::Error::Access => ErrorKind::PermissionDenied,
+ rusb::Error::NotFound => ErrorKind::NotFound,
+ _ => ErrorKind::Other,
+ };
+ io::Error::new(kind, format!("usb: {e}"))
+}
+
+/// `Read` over the bulk IN endpoint.
+pub struct BulkReader {
+ io: Arc,
+}
+
+impl BulkReader {
+ /// Reads from `io`.
+ pub fn new(io: Arc) -> Self {
+ BulkReader { io }
+ }
+}
+
+impl Read for BulkReader {
+ /// A timeout, and also a zero-length packet, is reported as `TimedOut`: neither is the end of
+ /// the stream, the caller just reads again.
+ fn read(&mut self, buf: &mut [u8]) -> io::Result {
+ match self.io.read_bulk(buf, READ_TIMEOUT) {
+ Ok(0) => Err(ErrorKind::TimedOut.into()),
+ Ok(n) => Ok(n),
+ Err(e) => Err(io_error(e)),
+ }
+ }
+}
+
+/// `Write` over the bulk OUT endpoint; never sends a transfer that ends on a full packet.
+pub struct BulkWriter {
+ io: Arc,
+ max_packet: usize,
+}
+
+impl BulkWriter {
+ /// Writes to `io`, whose OUT endpoint has `max_packet` as its maximum packet size.
+ pub fn new(io: Arc, max_packet: usize) -> Self {
+ BulkWriter { io, max_packet }
+ }
+}
+
+impl Write for BulkWriter {
+ /// One bulk transfer of at most [`TRANSFER_LEN`] bytes, see [`transfer_len`]. A timeout is an
+ /// error: the transfer may have been partial, so the stream cannot be trusted any more.
+ fn write(&mut self, buf: &[u8]) -> io::Result {
+ if buf.is_empty() {
+ return Ok(0);
+ }
+ let n = transfer_len(buf.len(), TRANSFER_LEN, self.max_packet);
+ self.io
+ .write_bulk(&buf[..n], WRITE_TIMEOUT)
+ .map_err(io_error)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+/// A claimed accessory interface; releases it when the last user lets go.
+struct Claimed {
+ handle: DeviceHandle,
+ iface: u8,
+ ep_in: u8,
+ ep_out: u8,
+}
+
+impl BulkIo for Claimed {
+ fn read_bulk(&self, buf: &mut [u8], timeout: Duration) -> rusb::Result {
+ self.handle.read_bulk(self.ep_in, buf, timeout)
+ }
+
+ fn write_bulk(&self, buf: &[u8], timeout: Duration) -> rusb::Result {
+ self.handle.write_bulk(self.ep_out, buf, timeout)
+ }
+}
+
+impl Drop for Claimed {
+ fn drop(&mut self) {
+ let _ = self.handle.release_interface(self.iface);
+ }
+}
+
+type Strings = (Option, Option);
+
+/// The USB subsystem: a libusb context plus a cache of the strings read from each device.
+pub struct Aoa {
+ ctx: Context,
+ /// Product and serial strings per `(bus, address, vid, pid)`: reading them opens the device,
+ /// which a poll every second must not do again and again.
+ strings: Mutex>,
+}
+
+impl Aoa {
+ /// Initializes libusb. On Windows this needs UsbDk (libusb cannot reach a device that has no
+ /// WinUSB driver otherwise), so a missing UsbDk makes AOA unavailable; USB then falls back to
+ /// adb.
+ pub fn new() -> Result {
+ #[cfg(windows)]
+ let ctx = Context::with_options(&[rusb::UsbOption::use_usbdk()])
+ .map_err(|_| Unavailable("UsbDk is not installed".into()))?;
+ #[cfg(not(windows))]
+ let ctx = Context::new().map_err(|e| Unavailable(format!("libusb: {e}")))?;
+ Ok(Aoa {
+ ctx,
+ strings: Mutex::new(HashMap::new()),
+ })
+ }
+
+ /// Version of the libusb in use, like `1.0.29`.
+ pub fn libusb_version() -> String {
+ let v = rusb::version();
+ format!("{}.{}.{}", v.major(), v.minor(), v.micro())
+ }
+
+ /// The accessory devices and the devices that may be switched, nothing else.
+ pub fn list(&self) -> io::Result> {
+ let devices = self.ctx.devices().map_err(io_error)?;
+ let mut out = Vec::new();
+ let mut seen = Vec::new();
+ for dev in devices.iter() {
+ let Ok(desc) = dev.device_descriptor() else {
+ continue;
+ };
+ let (vid, pid) = (desc.vendor_id(), desc.product_id());
+ let mode = if is_accessory(vid, pid) {
+ Mode::Accessory
+ } else {
+ match classify(vid, pid, &interfaces_of(&dev)) {
+ Some(m) => m,
+ None => continue,
+ }
+ };
+ let key = (dev.bus_number(), dev.address(), vid, pid);
+ seen.push(key);
+ let (product, serial) = self.strings_of(&dev, key);
+ out.push(DeviceInfo {
+ vid,
+ pid,
+ bus: key.0,
+ address: key.1,
+ ports: dev.port_numbers().unwrap_or_default(),
+ product,
+ serial,
+ mode,
+ });
+ }
+ lock(&self.strings).retain(|k, _| seen.contains(k));
+ Ok(out)
+ }
+
+ fn strings_of(&self, dev: &Device, key: (u8, u8, u16, u16)) -> Strings {
+ if let Some(s) = lock(&self.strings).get(&key) {
+ return s.clone();
+ }
+ let strings = read_strings(dev);
+ lock(&self.strings).insert(key, strings.clone());
+ strings
+ }
+
+ fn find(&self, info: &DeviceInfo) -> io::Result> {
+ let devices = self.ctx.devices().map_err(io_error)?;
+ devices
+ .iter()
+ .find(|d| {
+ (d.bus_number(), d.address()) == (info.bus, info.address)
+ && d.device_descriptor()
+ .is_ok_and(|x| (x.vendor_id(), x.product_id()) == (info.vid, info.pid))
+ })
+ .ok_or_else(|| io::Error::new(ErrorKind::NotFound, "usb: the device is gone"))
+ }
+
+ /// Switches `dev` (a device from [`list`](Self::list) that is not an accessory) to accessory
+ /// mode and waits for it to come back as one, which is returned.
+ ///
+ /// Sends vendor requests to the device, so only call it for devices that [`list`](Self::list)
+ /// returned.
+ pub fn switch(&self, dev: &DeviceInfo) -> io::Result {
+ if dev.mode == Mode::Accessory {
+ return Err(io::Error::new(
+ ErrorKind::InvalidInput,
+ "the device is already an accessory",
+ ));
+ }
+ let before: Vec = self
+ .list()?
+ .into_iter()
+ .filter(|d| d.mode == Mode::Accessory)
+ .collect();
+ {
+ let handle = self.find(dev)?.open().map_err(io_error)?;
+ handshake(&handle)?;
+ }
+ let deadline = Instant::now() + REENUMERATE_TIMEOUT;
+ loop {
+ std::thread::sleep(Duration::from_millis(200));
+ let now = self.list()?;
+ if let Some(a) = pick_accessory(dev, &before, &now) {
+ return Ok(a.clone());
+ }
+ if Instant::now() >= deadline {
+ return Err(io::Error::new(
+ ErrorKind::TimedOut,
+ "the device did not come back as an accessory",
+ ));
+ }
+ }
+ }
+
+ /// Claims the accessory interface of `dev` and returns a link over its bulk endpoints.
+ /// Dropping the link ends its threads and releases the interface.
+ ///
+ /// Must be called inside a tokio runtime.
+ pub fn open(&self, dev: &DeviceInfo) -> io::Result {
+ let device = self.find(dev)?;
+ let (ep_in, ep_out, max_packet) = bulk_endpoints(&device)?;
+ let handle = device.open().map_err(io_error)?;
+ // Not supported everywhere (Windows); the kernel driver is only an issue on Linux.
+ let _ = handle.set_auto_detach_kernel_driver(true);
+ handle
+ .claim_interface(ACCESSORY_INTERFACE)
+ .map_err(io_error)?;
+ let io = Arc::new(Claimed {
+ handle,
+ iface: ACCESSORY_INTERFACE,
+ ep_in,
+ ep_out,
+ });
+ let peer = format!(
+ "usb:{:04x}:{:04x} {}",
+ dev.vid,
+ dev.pid,
+ dev.product.as_deref().unwrap_or("accessory")
+ );
+ Link::from_blocking(
+ BulkReader::new(io.clone()),
+ BulkWriter::new(io, max_packet),
+ peer,
+ BlockingOptions {
+ read_buf: TRANSFER_LEN,
+ write_buf: TRANSFER_LEN,
+ thread_name: "ezd-aoa".into(),
+ ..BlockingOptions::default()
+ },
+ )
+ }
+
+ /// Resets `dev`. A device that switched to accessory mode but never answered goes back to its
+ /// normal USB mode this way (a phone gets its file transfer back).
+ pub fn reset(&self, dev: &DeviceInfo) -> io::Result<()> {
+ let handle = self.find(dev)?.open().map_err(io_error)?;
+ handle.reset().map_err(io_error)
+ }
+}
+
+fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+fn interfaces_of(dev: &Device) -> Vec {
+ let Ok(cfg) = dev.active_config_descriptor() else {
+ return Vec::new();
+ };
+ cfg.interfaces()
+ .flat_map(|i| i.descriptors().collect::>())
+ .map(|d| InterfaceClass {
+ class: d.class_code(),
+ subclass: d.sub_class_code(),
+ protocol: d.protocol_code(),
+ })
+ .collect()
+}
+
+fn read_strings(dev: &Device) -> Strings {
+ let (Ok(desc), Ok(handle)) = (dev.device_descriptor(), dev.open()) else {
+ return (None, None);
+ };
+ let product = handle.read_product_string_ascii(&desc).ok();
+ let serial = handle
+ .read_serial_number_string_ascii(&desc)
+ .ok()
+ .filter(|s| !s.is_empty());
+ (product, serial)
+}
+
+/// The bulk IN and OUT endpoint addresses of the accessory interface and the OUT endpoint's
+/// maximum packet size.
+fn bulk_endpoints(dev: &Device) -> io::Result<(u8, u8, usize)> {
+ let cfg = dev.active_config_descriptor().map_err(io_error)?;
+ let mut ep_in = None;
+ let mut ep_out = None;
+ for iface in cfg
+ .interfaces()
+ .filter(|i| i.number() == ACCESSORY_INTERFACE)
+ {
+ for d in iface.descriptors() {
+ for ep in d.endpoint_descriptors() {
+ if ep.transfer_type() != rusb::TransferType::Bulk {
+ continue;
+ }
+ match ep.direction() {
+ Direction::In => ep_in = ep_in.or(Some(ep.address())),
+ Direction::Out => {
+ ep_out = ep_out.or(Some((ep.address(), usize::from(ep.max_packet_size()))));
+ }
+ }
+ }
+ }
+ }
+ match (ep_in, ep_out) {
+ (Some(i), Some((o, mps))) => Ok((i, o, mps)),
+ _ => Err(io::Error::new(
+ ErrorKind::NotFound,
+ "usb: the accessory interface has no bulk endpoints",
+ )),
+ }
+}
+
+/// GET_PROTOCOL, the identification strings and START.
+fn handshake(handle: &DeviceHandle) -> io::Result<()> {
+ let vendor_in = rusb::request_type(Direction::In, RequestType::Vendor, Recipient::Device);
+ let vendor_out = rusb::request_type(Direction::Out, RequestType::Vendor, Recipient::Device);
+ let mut answer = [0u8; 2];
+ let n = handle
+ .read_control(
+ vendor_in,
+ REQ_GET_PROTOCOL,
+ 0,
+ 0,
+ &mut answer,
+ CONTROL_TIMEOUT,
+ )
+ .map_err(io_error)?;
+ let protocol = parse_protocol(&answer[..n]).ok_or_else(|| {
+ io::Error::new(
+ ErrorKind::Unsupported,
+ "the device does not support accessory mode",
+ )
+ })?;
+ tracing::debug!(protocol, "accessory protocol");
+ for (index, bytes) in accessory_strings() {
+ handle
+ .write_control(
+ vendor_out,
+ REQ_SEND_STRING,
+ 0,
+ index,
+ &bytes,
+ CONTROL_TIMEOUT,
+ )
+ .map_err(io_error)?;
+ }
+ match handle.write_control(vendor_out, REQ_START, 0, 0, &[], CONTROL_TIMEOUT) {
+ // The device may drop off the bus before it completes the request.
+ Ok(_) | Err(rusb::Error::NoDevice | rusb::Error::Io) => Ok(()),
+ Err(e) => Err(io_error(e)),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::VecDeque;
+
+ fn ic(class: u8, subclass: u8, protocol: u8) -> InterfaceClass {
+ InterfaceClass {
+ class,
+ subclass,
+ protocol,
+ }
+ }
+
+ const MTP: InterfaceClass = InterfaceClass {
+ class: 6,
+ subclass: 1,
+ protocol: 1,
+ };
+ const ADB: InterfaceClass = InterfaceClass {
+ class: 0xff,
+ subclass: 0x42,
+ protocol: 1,
+ };
+
+ fn dev(pid: u16, mode: Mode, addr: u8, serial: Option<&str>, ports: &[u8]) -> DeviceInfo {
+ DeviceInfo {
+ vid: if mode == Mode::Accessory {
+ ACCESSORY_VID
+ } else {
+ 0x04e8
+ },
+ pid,
+ bus: 1,
+ address: addr,
+ ports: ports.to_vec(),
+ product: Some("Tab".into()),
+ serial: serial.map(String::from),
+ mode,
+ }
+ }
+
+ #[test]
+ fn accessory_ids() {
+ for pid in 0x2D00..=0x2D05 {
+ assert!(is_accessory(0x18D1, pid));
+ }
+ assert!(!is_accessory(0x18D1, 0x2D06));
+ assert!(!is_accessory(0x18D1, 0x4EE1));
+ assert!(!is_accessory(0x04e8, 0x2D00));
+ let adb: Vec = (0x2D00..=0x2D05)
+ .filter(|p| accessory_has_adb(*p))
+ .collect();
+ assert_eq!(adb, [0x2D01, 0x2D03, 0x2D05]);
+ }
+
+ #[test]
+ fn only_mtp_adb_and_accessory_devices_are_candidates() {
+ assert_eq!(classify(0x04e8, 0x6860, &[MTP]), Some(Mode::Mtp));
+ assert_eq!(classify(0x04e8, 0x6860, &[MTP, ADB]), Some(Mode::Mtp));
+ assert_eq!(classify(0x18D1, 0x4EE2, &[ADB]), Some(Mode::Adb));
+ assert_eq!(classify(0x18D1, 0x2D01, &[]), Some(Mode::Accessory));
+ // Same class and subclass, other protocol; a keyboard; a mass storage stick; no interfaces.
+ assert_eq!(classify(1, 2, &[ic(6, 1, 2)]), None);
+ assert_eq!(classify(1, 2, &[ic(0xff, 0x42, 2)]), None);
+ assert_eq!(classify(1, 2, &[ic(3, 1, 1)]), None);
+ assert_eq!(classify(1, 2, &[ic(8, 6, 0x50)]), None);
+ assert_eq!(classify(1, 2, &[]), None);
+ }
+
+ #[test]
+ fn the_key_prefers_the_serial_and_falls_back_to_the_port() {
+ let with = dev(0x6860, Mode::Mtp, 4, Some("R52"), &[2, 1]);
+ assert_eq!(with.key(), "04e8:6860:R52");
+ let without = dev(0x6860, Mode::Mtp, 4, None, &[2, 1]);
+ assert_eq!(without.key(), "04e8:6860@1-2.1");
+ // Same device after a re-enumeration at another address.
+ let moved = DeviceInfo {
+ address: 9,
+ ..without.clone()
+ };
+ assert_eq!(moved.key(), without.key());
+ assert!(!with.describe().contains("R52"));
+ assert_eq!(with.describe(), "04e8:6860 Tab");
+ }
+
+ #[test]
+ fn the_accessory_is_matched_by_serial() {
+ let original = dev(0x6860, Mode::Mtp, 4, Some("A"), &[1]);
+ let before = vec![dev(0x2D00, Mode::Accessory, 2, Some("OLD"), &[3])];
+ let now = vec![
+ before[0].clone(),
+ dev(0x2D00, Mode::Accessory, 7, Some("B"), &[4]),
+ dev(0x2D00, Mode::Accessory, 8, Some("A"), &[1]),
+ ];
+ assert_eq!(pick_accessory(&original, &before, &now), Some(&now[2]));
+ // Not there yet.
+ assert_eq!(pick_accessory(&original, &before, &now[..2]), None);
+ }
+
+ #[test]
+ fn an_accessory_without_a_serial_is_accepted_for_a_device_with_one() {
+ let original = dev(0x6860, Mode::Mtp, 4, Some("A"), &[1]);
+ let now = vec![dev(0x2D00, Mode::Accessory, 8, None, &[1])];
+ assert_eq!(pick_accessory(&original, &[], &now), Some(&now[0]));
+ }
+
+ #[test]
+ fn without_a_serial_the_first_new_accessory_is_taken() {
+ let original = dev(0x6860, Mode::Mtp, 4, None, &[1]);
+ let before = vec![dev(0x2D00, Mode::Accessory, 2, None, &[3])];
+ let now = vec![
+ before[0].clone(),
+ dev(0x04e8, Mode::Mtp, 5, None, &[5]),
+ dev(0x2D01, Mode::Accessory, 8, None, &[1]),
+ ];
+ assert_eq!(pick_accessory(&original, &before, &now), Some(&now[2]));
+ assert_eq!(pick_accessory(&original, &before, &now[..2]), None);
+ }
+
+ #[test]
+ fn the_handshake_strings_are_nul_terminated_and_complete() {
+ let s = accessory_strings();
+ assert_eq!(
+ s.iter().map(|(i, _)| *i).collect::>(),
+ [0, 1, 2, 3, 4, 5]
+ );
+ assert!(s.iter().all(|(_, b)| b.last() == Some(&0)));
+ assert_eq!(s[0].1, b"LibreStatic\0");
+ assert_eq!(s[1].1, b"ezdisplay\0");
+ assert_eq!(s[2].1, b"ezdisplay extended display\0");
+ assert_eq!(
+ s[3].1,
+ format!("{}\0", env!("CARGO_PKG_VERSION")).as_bytes()
+ );
+ assert_eq!(s[4].1, b"https://github.com/LibreStatic/ezdisplay\0");
+ assert_eq!(s[5].1, b"ezdisplay\0");
+ }
+
+ #[test]
+ fn the_protocol_answer_is_little_endian_and_at_least_one() {
+ assert_eq!(parse_protocol(&[2, 0]), Some(2));
+ assert_eq!(parse_protocol(&[0, 1]), Some(256));
+ assert_eq!(parse_protocol(&[0, 0]), None);
+ assert_eq!(parse_protocol(&[1]), None);
+ assert_eq!(parse_protocol(&[]), None);
+ }
+
+ #[test]
+ fn transfers_never_end_on_a_full_packet() {
+ assert_eq!(transfer_len(100, 16384, 512), 100);
+ assert_eq!(transfer_len(512, 16384, 512), 511);
+ assert_eq!(transfer_len(1024, 16384, 512), 1023);
+ assert_eq!(transfer_len(16384, 16384, 512), 16383);
+ assert_eq!(transfer_len(100_000, 16384, 512), 16383);
+ assert_eq!(transfer_len(100_000, 16384, 64), 16383);
+ assert_eq!(transfer_len(1, 16384, 512), 1);
+ assert_eq!(transfer_len(513, 16384, 512), 513);
+ // A degenerate packet size cannot be avoided.
+ assert_eq!(transfer_len(10, 16384, 1), 10);
+ }
+
+ struct FakeIo {
+ reads: Mutex>>>,
+ writes: Mutex>,
+ write_result: Mutex>,
+ }
+
+ impl FakeIo {
+ fn new(reads: Vec>>) -> Arc {
+ Arc::new(FakeIo {
+ reads: Mutex::new(reads.into()),
+ writes: Mutex::new(Vec::new()),
+ write_result: Mutex::new(None),
+ })
+ }
+ }
+
+ impl BulkIo for FakeIo {
+ fn read_bulk(&self, buf: &mut [u8], _: Duration) -> rusb::Result {
+ match self.reads.lock().unwrap().pop_front() {
+ Some(Ok(d)) => {
+ buf[..d.len()].copy_from_slice(&d);
+ Ok(d.len())
+ }
+ Some(Err(e)) => Err(e),
+ None => Err(rusb::Error::Timeout),
+ }
+ }
+
+ fn write_bulk(&self, buf: &[u8], _: Duration) -> rusb::Result {
+ if let Some(e) = *self.write_result.lock().unwrap() {
+ return Err(e);
+ }
+ self.writes.lock().unwrap().push(buf.len());
+ Ok(buf.len())
+ }
+ }
+
+ #[test]
+ fn a_read_maps_timeouts_and_zero_length_packets_to_timed_out() {
+ let io = FakeIo::new(vec![
+ Ok(vec![1, 2, 3]),
+ Ok(vec![]),
+ Err(rusb::Error::Timeout),
+ Err(rusb::Error::NoDevice),
+ Err(rusb::Error::Pipe),
+ Err(rusb::Error::Io),
+ ]);
+ let mut r = BulkReader::new(io);
+ let mut buf = [0u8; 16];
+ assert_eq!(r.read(&mut buf).unwrap(), 3);
+ assert_eq!(&buf[..3], [1, 2, 3]);
+ assert_eq!(r.read(&mut buf).unwrap_err().kind(), ErrorKind::TimedOut);
+ assert_eq!(r.read(&mut buf).unwrap_err().kind(), ErrorKind::TimedOut);
+ assert_eq!(
+ r.read(&mut buf).unwrap_err().kind(),
+ ErrorKind::NotConnected
+ );
+ assert_eq!(r.read(&mut buf).unwrap_err().kind(), ErrorKind::BrokenPipe);
+ assert_eq!(r.read(&mut buf).unwrap_err().kind(), ErrorKind::Other);
+ }
+
+ #[test]
+ fn a_write_sends_one_transfer_and_avoids_full_packets() {
+ let io = FakeIo::new(vec![]);
+ let mut w = BulkWriter::new(io.clone(), 512);
+ let data = vec![7u8; 40_000];
+ w.write_all(&data).unwrap();
+ let sent = io.writes.lock().unwrap().clone();
+ assert_eq!(sent.iter().sum::(), 40_000);
+ assert!(
+ sent.iter().all(|n| *n <= TRANSFER_LEN && n % 512 != 0),
+ "{sent:?}"
+ );
+ assert_eq!(sent[0], 16383);
+
+ io.writes.lock().unwrap().clear();
+ assert_eq!(w.write(&[1u8; 512]).unwrap(), 511);
+ assert_eq!(w.write(&[]).unwrap(), 0);
+ assert_eq!(*io.writes.lock().unwrap(), [511]);
+ }
+
+ #[test]
+ fn a_write_timeout_is_a_hard_error() {
+ let io = FakeIo::new(vec![]);
+ *io.write_result.lock().unwrap() = Some(rusb::Error::Timeout);
+ let mut w = BulkWriter::new(io, 512);
+ let e = w.write_all(&[0u8; 10]).unwrap_err();
+ assert_eq!(e.kind(), ErrorKind::TimedOut);
+ }
+
+ #[tokio::test]
+ async fn a_link_over_the_fake_endpoints_moves_bytes() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let io = FakeIo::new(vec![Ok(b"hello".to_vec())]);
+ let mut link = Link::from_blocking(
+ BulkReader::new(io.clone()),
+ BulkWriter::new(io.clone(), 512),
+ "usb:test",
+ BlockingOptions::default(),
+ )
+ .unwrap();
+ let mut got = [0u8; 5];
+ link.reader.read_exact(&mut got).await.unwrap();
+ assert_eq!(&got, b"hello");
+ link.writer.write_all(&[9u8; 512]).await.unwrap();
+ link.writer.flush().await.unwrap();
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while io.writes.lock().unwrap().iter().sum::() < 512 {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .unwrap();
+ assert!(io.writes.lock().unwrap().iter().all(|n| n % 512 != 0));
+ }
+}
diff --git a/crates/ezd-link/src/blocking.rs b/crates/ezd-link/src/blocking.rs
new file mode 100644
index 0000000..f60c572
--- /dev/null
+++ b/crates/ezd-link/src/blocking.rs
@@ -0,0 +1,327 @@
+//! A [`Link`] over blocking reader and writer halves, such as USB bulk endpoints or an Android
+//! accessory file descriptor.
+//!
+//! Each half gets its own thread, bridged to the async side through an in-memory pipe (a
+//! [`DuplexStream`] per direction: dropping either end closes it, which a split simplex pipe does
+//! not do). The read
+//! thread forwards whatever one `read` returns, so a transport with a fixed transfer size picks it
+//! with [`BlockingOptions::read_buf`].
+
+use crate::link::{BoxRead, Link};
+use std::io::{self, ErrorKind, Read, Write};
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::task::{Context, Poll};
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, DuplexStream, ReadBuf};
+use tokio::runtime::Handle;
+
+/// How [`Link::from_blocking`] drives the halves.
+#[derive(Debug, Clone)]
+pub struct BlockingOptions {
+ /// Bytes asked for in each `read` call.
+ pub read_buf: usize,
+ /// Most bytes handed to one `write` call.
+ pub write_buf: usize,
+ /// Bytes buffered between each thread and the async side.
+ pub pipe_capacity: usize,
+ /// Prefix of the thread names (`-rx`, `-tx`).
+ pub thread_name: String,
+}
+
+impl Default for BlockingOptions {
+ fn default() -> Self {
+ BlockingOptions {
+ read_buf: 16 * 1024,
+ write_buf: 16 * 1024,
+ pipe_capacity: 256 * 1024,
+ thread_name: "ezd-link".into(),
+ }
+ }
+}
+
+impl Link {
+ /// Builds a link whose bytes come from `reader` and go to `writer`, each on its own thread.
+ ///
+ /// The reader may return [`ErrorKind::TimedOut`] or [`ErrorKind::WouldBlock`] to wake up
+ /// periodically: the read thread then checks whether the link was dropped and reads again.
+ /// `Ok(0)` from the reader ends the stream. The write thread ends when the link's writer is
+ /// shut down or dropped, and drops `writer` then.
+ ///
+ /// Must be called inside a tokio runtime.
+ pub fn from_blocking(
+ reader: R,
+ writer: W,
+ peer: impl Into,
+ opts: BlockingOptions,
+ ) -> io::Result
+ where
+ R: Read + Send + 'static,
+ W: Write + Send + 'static,
+ {
+ let handle = Handle::try_current().map_err(io::Error::other)?;
+ let (in_rx, in_tx) = tokio::io::duplex(opts.pipe_capacity);
+ let (out_rx, out_tx) = tokio::io::duplex(opts.pipe_capacity);
+ let dropped = Arc::new(AtomicBool::new(false));
+
+ let read_dropped = dropped.clone();
+ let read_handle = handle.clone();
+ let read_buf = opts.read_buf.max(1);
+ std::thread::Builder::new()
+ .name(format!("{}-rx", opts.thread_name))
+ .spawn(move || read_loop(reader, in_tx, read_buf, &read_dropped, &read_handle))?;
+
+ let write_buf = opts.write_buf.max(1);
+ std::thread::Builder::new()
+ .name(format!("{}-tx", opts.thread_name))
+ .spawn(move || write_loop(writer, out_rx, write_buf, &handle))?;
+
+ let reader: BoxRead = Box::new(DropFlagRead {
+ inner: in_rx,
+ dropped,
+ });
+ Ok(Link::new(reader, Box::new(out_tx), peer))
+ }
+}
+
+fn read_loop(
+ mut reader: R,
+ mut pipe: DuplexStream,
+ buf_len: usize,
+ dropped: &AtomicBool,
+ handle: &Handle,
+) {
+ let mut buf = vec![0u8; buf_len];
+ loop {
+ if dropped.load(Ordering::Acquire) {
+ return;
+ }
+ match reader.read(&mut buf) {
+ Ok(0) => return,
+ Ok(n) => {
+ if handle.block_on(pipe.write_all(&buf[..n])).is_err() {
+ return;
+ }
+ }
+ Err(e)
+ if matches!(
+ e.kind(),
+ ErrorKind::Interrupted | ErrorKind::TimedOut | ErrorKind::WouldBlock
+ ) => {}
+ Err(e) => {
+ tracing::debug!("blocking link read ended: {e}");
+ return;
+ }
+ }
+ }
+}
+
+fn write_loop(mut writer: W, mut pipe: DuplexStream, buf_len: usize, handle: &Handle) {
+ let mut buf = vec![0u8; buf_len];
+ loop {
+ let n = match handle.block_on(pipe.read(&mut buf)) {
+ Ok(0) | Err(_) => return,
+ Ok(n) => n,
+ };
+ if let Err(e) = writer.write_all(&buf[..n]).and_then(|()| writer.flush()) {
+ tracing::debug!("blocking link write ended: {e}");
+ return;
+ }
+ }
+}
+
+/// Read half that tells the read thread when the link is gone.
+struct DropFlagRead {
+ inner: DuplexStream,
+ dropped: Arc,
+}
+
+impl AsyncRead for DropFlagRead {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut ReadBuf<'_>,
+ ) -> Poll> {
+ Pin::new(&mut self.inner).poll_read(cx, buf)
+ }
+}
+
+impl Drop for DropFlagRead {
+ fn drop(&mut self) {
+ self.dropped.store(true, Ordering::Release);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex;
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ /// Reader fed by a channel; times out when nothing arrives, like a USB endpoint.
+ struct ChanRead {
+ rx: mpsc::Receiver>,
+ reads: Arc>>,
+ }
+
+ impl Read for ChanRead {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result {
+ self.reads.lock().unwrap().push(buf.len());
+ match self.rx.recv_timeout(Duration::from_millis(20)) {
+ Ok(data) => {
+ buf[..data.len()].copy_from_slice(&data);
+ Ok(data.len())
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => Err(ErrorKind::TimedOut.into()),
+ Err(mpsc::RecvTimeoutError::Disconnected) => Ok(0),
+ }
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct SharedWrite {
+ data: Arc>>,
+ calls: Arc>>,
+ /// Set when the write thread drops its copy.
+ dropped: Arc,
+ }
+
+ impl Write for SharedWrite {
+ fn write(&mut self, buf: &[u8]) -> io::Result {
+ self.calls.lock().unwrap().push(buf.len());
+ self.data.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ /// The copy handed to the link.
+ struct ThreadWrite(SharedWrite);
+
+ impl Write for ThreadWrite {
+ fn write(&mut self, buf: &[u8]) -> io::Result {
+ self.0.write(buf)
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl Drop for ThreadWrite {
+ fn drop(&mut self) {
+ self.0.dropped.store(true, Ordering::Release);
+ }
+ }
+
+ fn opts() -> BlockingOptions {
+ BlockingOptions {
+ read_buf: 64,
+ write_buf: 100,
+ pipe_capacity: 1024,
+ thread_name: "test".into(),
+ }
+ }
+
+ async fn eventually(what: &str, f: impl Fn() -> bool) {
+ for _ in 0..200 {
+ if f() {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ panic!("timed out waiting for {what}");
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn bytes_flow_both_ways_in_order() {
+ let (tx, rx) = mpsc::channel();
+ let reads = Arc::new(Mutex::new(Vec::new()));
+ let w = SharedWrite::default();
+ let mut link = Link::from_blocking(
+ ChanRead {
+ rx,
+ reads: reads.clone(),
+ },
+ ThreadWrite(w.clone()),
+ "test",
+ opts(),
+ )
+ .unwrap();
+
+ for i in 0..20u8 {
+ tx.send(vec![i; 50]).unwrap();
+ }
+ drop(tx);
+ let mut got = Vec::new();
+ link.reader.read_to_end(&mut got).await.unwrap();
+ let want: Vec = (0..20u8).flat_map(|i| [i; 50]).collect();
+ assert_eq!(got, want);
+ assert!(reads.lock().unwrap().iter().all(|&n| n == 64));
+
+ let out: Vec = (0..=255u8).cycle().take(1000).collect();
+ link.writer.write_all(&out).await.unwrap();
+ link.writer.shutdown().await.unwrap();
+ eventually("the writer to be dropped", || {
+ w.dropped.load(Ordering::Acquire)
+ })
+ .await;
+ assert_eq!(*w.data.lock().unwrap(), out);
+ assert!(w.calls.lock().unwrap().iter().all(|&n| n <= 100));
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn dropping_the_link_stops_a_timing_out_reader() {
+ let (tx, rx) = mpsc::channel::>();
+ let reads = Arc::new(Mutex::new(Vec::new()));
+ let link = Link::from_blocking(
+ ChanRead {
+ rx,
+ reads: reads.clone(),
+ },
+ SharedWrite::default(),
+ "test",
+ opts(),
+ )
+ .unwrap();
+ eventually("a first read", || !reads.lock().unwrap().is_empty()).await;
+ drop(link);
+ // The read thread owns the receiver: once it stops, sending fails.
+ eventually("the read thread to stop", || tx.send(Vec::new()).is_err()).await;
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_failing_writer_closes_the_write_half() {
+ struct Broken;
+ impl Write for Broken {
+ fn write(&mut self, _: &[u8]) -> io::Result {
+ Err(ErrorKind::BrokenPipe.into())
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+ let (_tx, rx) = mpsc::channel();
+ let mut link = Link::from_blocking(
+ ChanRead {
+ rx,
+ reads: Arc::default(),
+ },
+ Broken,
+ "test",
+ opts(),
+ )
+ .unwrap();
+ let mut failed = false;
+ for _ in 0..200 {
+ if link.writer.write_all(&[1; 64]).await.is_err() {
+ failed = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ assert!(failed, "writes must fail once the device is gone");
+ }
+}
diff --git a/crates/ezd-link/src/lib.rs b/crates/ezd-link/src/lib.rs
index 0c09516..36d4822 100644
--- a/crates/ezd-link/src/lib.rs
+++ b/crates/ezd-link/src/lib.rs
@@ -1,12 +1,16 @@
//! Transport layer for ezdisplay.
//!
-//! * [`Link`]: a reliable ordered byte stream (TCP, in-memory duplex, later AOA).
+//! * [`Link`]: a reliable ordered byte stream (TCP, in-memory duplex, blocking halves such as USB).
//! * [`mux`]: [`MuxSender`] / [`MuxReceiver`], the prioritized message mux on top of a link.
//! * [`adb`] (not on Android): locate `adb`, list devices, manage `adb reverse`.
+//! * [`aoa`] (`aoa` feature, not on Android): the host side of the USB accessory transport.
//! * [`quic`], [`pair`], [`identity`] (`quic` feature): Wi-Fi links over QUIC with PIN pairing.
#[cfg(not(target_os = "android"))]
pub mod adb;
+#[cfg(all(feature = "aoa", not(target_os = "android")))]
+pub mod aoa;
+pub mod blocking;
#[cfg(feature = "quic")]
pub mod identity;
pub mod link;
@@ -16,6 +20,7 @@ pub mod pair;
#[cfg(feature = "quic")]
pub mod quic;
+pub use blocking::BlockingOptions;
pub use link::{BoxRead, BoxWrite, Lanes, Link};
pub use mux::{
MuxClosed, MuxError, MuxOptions, MuxReceiver, MuxSender, MuxStats, MuxTask, VideoCredit,
diff --git a/crates/ezd-tray/Cargo.toml b/crates/ezd-tray/Cargo.toml
index 0777f41..1ae6cf9 100644
--- a/crates/ezd-tray/Cargo.toml
+++ b/crates/ezd-tray/Cargo.toml
@@ -15,13 +15,16 @@ name = "ezdisplay"
path = "src/main.rs"
[features]
-default = ["ffmpeg", "wifi"]
+default = ["ffmpeg", "wifi", "aoa"]
# FFmpeg paths of the service. `--no-default-features` builds without FFmpeg headers (the Windows
# cross-check in CI).
ffmpeg = ["ezd-host-service/ffmpeg"]
# Wi-Fi card: the QUIC transport and PIN pairing of the service. `--no-default-features` leaves it
# out (ring has C code the Windows cross-check from Linux cannot build).
wifi = ["ezd-host-service/wifi"]
+# USB without developer mode (Android accessory mode through libusb). `--no-default-features`
+# leaves it out (the Windows cross-check from Linux cannot build libusb).
+aoa = ["ezd-host-service/aoa"]
# Local only: PNG snapshots of the window (needs a GPU/wgpu). CI never enables it.
snapshots = ["egui_kittest/snapshot", "egui_kittest/wgpu"]
@@ -87,6 +90,7 @@ assets = [
["target/release/ezdisplay", "usr/bin/", "755"],
["target/release/ezd-host", "usr/bin/", "755"],
["../../packaging/linux/70-ezdisplay-uinput.rules", "usr/lib/udev/rules.d/", "644"],
+ ["../../packaging/linux/70-ezdisplay-usb.rules", "usr/lib/udev/rules.d/", "644"],
["../../packaging/linux/ufw/ezdisplay", "etc/ufw/applications.d/", "644"],
["../../packaging/linux/firewalld/ezdisplay.xml", "usr/lib/firewalld/services/", "644"],
["../../packaging/linux/com.librestatic.ezdisplay.desktop", "usr/share/applications/", "644"],
diff --git a/crates/ezd-tray/i18n/de/ezd-tray.ftl b/crates/ezd-tray/i18n/de/ezd-tray.ftl
index 8616e03..a5ff367 100644
--- a/crates/ezd-tray/i18n/de/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/de/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Übertragung an { $device } · { $width }×{ $height } mit {
error-bind = Auf { $addr } kann nicht gelauscht werden: { $reason }
error-adb-not-found = adb wurde nicht gefunden
error-adb-reverse = adb reverse ist für { $serial } fehlgeschlagen: { $reason }
+usb-unavailable-hint = USB ohne Entwickleroptionen ist nicht verfügbar ({ $reason }); USB-Debugging funktioniert weiterhin.
error-unsupported = Dieses System unterstützt noch keine virtuellen Bildschirme
error-source = Die Videoquelle kann nicht erstellt werden: { $reason }
@@ -45,6 +46,9 @@ devices-heading = Geräte
stats-heading = Live-Statistik
stats-waiting = Warte auf die ersten Messwerte…
stat-device = Tablet
+stat-connection = Verbindung
+transport-aoa = USB (Zubehör)
+transport-wifi = WLAN
stat-mode = Modus
stat-encoder = Encoder
stat-fps = Bildrate
@@ -129,6 +133,7 @@ device-unauthorized = wartet darauf, dass du das USB-Debugging bestätigst
device-offline = offline
open-app = Die App auf dem Tablet öffnen, sobald es verbunden ist
use-adb = Per USB mit adb verbinden
+use-aoa = USB ohne Entwickleroptionen
advanced = Erweitert
setting-port = Port
port-hint = Das Tablet erreicht diesen Computer über diesen Port. Änderungen gelten, wenn keine Sitzung läuft.
@@ -185,6 +190,7 @@ input-description = Nutze das Tablet als Touchscreen und Stift an diesem Compute
pen-description = Ein Grafiktablett fügt Druck und Neigung hinzu.
telemetry-description = Zeigt während des Streams Live-Leistungswerte auf dem Tablet.
use-adb-description = Findet Tablets, bei denen das USB-Debugging eingeschaltet ist.
+use-aoa-description = Schaltet das Tablet beim Anstecken in den Zubehörmodus, USB-Debugging ist nicht nötig. adb bleibt als Ausweichlösung.
autostart-description = Startet ezdisplay, wenn du dich anmeldest.
start-on-launch-description = Wartet auf dein Tablet, sobald ezdisplay geöffnet wird.
system-accent = Akzentfarbe des Systems verwenden
diff --git a/crates/ezd-tray/i18n/en/ezd-tray.ftl b/crates/ezd-tray/i18n/en/ezd-tray.ftl
index b0e83d7..1a322a2 100644
--- a/crates/ezd-tray/i18n/en/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/en/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Streaming to { $device } · { $width }×{ $height } at { $hz
error-bind = Cannot listen on { $addr }: { $reason }
error-adb-not-found = adb was not found
error-adb-reverse = adb reverse failed for { $serial }: { $reason }
+usb-unavailable-hint = USB without developer mode is unavailable ({ $reason }); USB debugging still works.
error-unsupported = This system has no virtual display support yet
error-source = Cannot create the video source: { $reason }
@@ -45,6 +46,9 @@ devices-heading = Devices
stats-heading = Live statistics
stats-waiting = Waiting for the first measurements…
stat-device = Tablet
+stat-connection = Connection
+transport-aoa = USB (accessory)
+transport-wifi = Wi-Fi
stat-mode = Mode
stat-encoder = Encoder
stat-fps = Frame rate
@@ -129,6 +133,7 @@ device-unauthorized = waiting for you to accept USB debugging
device-offline = offline
open-app = Open the app on the tablet when it is connected
use-adb = Connect over USB with adb
+use-aoa = USB without developer mode
advanced = Advanced
setting-port = Port
port-hint = The tablet reaches this computer on this port. Changes apply when no session is running.
@@ -185,6 +190,7 @@ input-description = Use the tablet as a touch screen and a pen on this computer.
pen-description = A graphics tablet adds pressure and tilt.
telemetry-description = Shows live performance numbers on the tablet while streaming.
use-adb-description = Finds tablets that have USB debugging turned on.
+use-aoa-description = Switches the tablet to accessory mode when you plug it in, so USB debugging is not needed. adb stays as the fallback.
autostart-description = Starts ezdisplay when you sign in.
start-on-launch-description = Starts waiting for your tablet as soon as ezdisplay opens.
system-accent = Use the system accent color
diff --git a/crates/ezd-tray/i18n/es/ezd-tray.ftl b/crates/ezd-tray/i18n/es/ezd-tray.ftl
index b37055d..51fda8a 100644
--- a/crates/ezd-tray/i18n/es/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/es/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Transmitiendo a { $device } · { $width }×{ $height } a { $h
error-bind = No se puede escuchar en { $addr }: { $reason }
error-adb-not-found = No se encontró adb
error-adb-reverse = Falló adb reverse para { $serial }: { $reason }
+usb-unavailable-hint = USB sin modo desarrollador no está disponible ({ $reason }); la depuración USB sigue funcionando.
error-unsupported = Este sistema todavía no admite pantallas virtuales
error-source = No se puede crear la fuente de video: { $reason }
@@ -45,6 +46,9 @@ devices-heading = Dispositivos
stats-heading = Estadísticas en vivo
stats-waiting = Esperando las primeras mediciones…
stat-device = Tablet
+stat-connection = Conexión
+transport-aoa = USB (accesorio)
+transport-wifi = Wi-Fi
stat-mode = Modo
stat-encoder = Codificador
stat-fps = Cuadros por segundo
@@ -129,6 +133,7 @@ device-unauthorized = esperando que aceptes la depuración USB
device-offline = sin conexión
open-app = Abrir la app en la tablet al conectarla
use-adb = Conectar por USB con adb
+use-aoa = USB sin modo desarrollador
advanced = Avanzado
setting-port = Puerto
port-hint = La tablet llega a esta computadora por este puerto. Los cambios se aplican cuando no hay una sesión en curso.
@@ -185,6 +190,7 @@ input-description = Usá la tablet como pantalla táctil y lápiz en esta comput
pen-description = Una tableta gráfica agrega presión e inclinación.
telemetry-description = Muestra mediciones de rendimiento en vivo en la tablet mientras transmitís.
use-adb-description = Encuentra las tablets que tienen la depuración USB activada.
+use-aoa-description = Pasa la tablet al modo accesorio al conectarla, así no hace falta la depuración USB. adb queda como alternativa.
autostart-description = Inicia ezdisplay cuando iniciás sesión.
start-on-launch-description = Empieza a esperar tu tablet apenas se abre ezdisplay.
system-accent = Usar el color de acento del sistema
diff --git a/crates/ezd-tray/i18n/fr/ezd-tray.ftl b/crates/ezd-tray/i18n/fr/ezd-tray.ftl
index 00ffed2..126494d 100644
--- a/crates/ezd-tray/i18n/fr/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/fr/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Diffusion vers { $device } · { $width }×{ $height } à { $h
error-bind = Impossible d'écouter sur { $addr } : { $reason }
error-adb-not-found = adb est introuvable
error-adb-reverse = Échec d'adb reverse pour { $serial } : { $reason }
+usb-unavailable-hint = L'USB sans mode développeur est indisponible ({ $reason }) ; le débogage USB fonctionne toujours.
error-unsupported = Ce système ne prend pas encore en charge les écrans virtuels
error-source = Impossible de créer la source vidéo : { $reason }
@@ -45,6 +46,9 @@ devices-heading = Appareils
stats-heading = Statistiques en direct
stats-waiting = En attente des premières mesures…
stat-device = Tablette
+stat-connection = Connexion
+transport-aoa = USB (accessoire)
+transport-wifi = Wi-Fi
stat-mode = Mode
stat-encoder = Encodeur
stat-fps = Fréquence d'images
@@ -129,6 +133,7 @@ device-unauthorized = en attente de votre acceptation du débogage USB
device-offline = hors ligne
open-app = Ouvrir l'application sur la tablette à la connexion
use-adb = Se connecter en USB avec adb
+use-aoa = USB sans mode développeur
advanced = Avancé
setting-port = Port
port-hint = La tablette joint cet ordinateur sur ce port. Les modifications s'appliquent quand aucune session n'est en cours.
@@ -185,6 +190,7 @@ input-description = Utilisez la tablette comme écran tactile et comme stylet su
pen-description = Une tablette graphique ajoute la pression et l'inclinaison.
telemetry-description = Affiche des mesures de performance en direct sur la tablette pendant la diffusion.
use-adb-description = Trouve les tablettes dont le débogage USB est activé.
+use-aoa-description = Fait passer la tablette en mode accessoire dès que vous la branchez, sans débogage USB. adb reste disponible en secours.
autostart-description = Lance ezdisplay à l'ouverture de votre session.
start-on-launch-description = Se met en attente de votre tablette dès l'ouverture d'ezdisplay.
system-accent = Utiliser la couleur d'accentuation du système
diff --git a/crates/ezd-tray/i18n/it/ezd-tray.ftl b/crates/ezd-tray/i18n/it/ezd-tray.ftl
index 47cec84..24ad8a2 100644
--- a/crates/ezd-tray/i18n/it/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/it/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Trasmissione verso { $device } · { $width }×{ $height } a {
error-bind = Impossibile mettersi in ascolto su { $addr }: { $reason }
error-adb-not-found = adb non trovato
error-adb-reverse = adb reverse non riuscito per { $serial }: { $reason }
+usb-unavailable-hint = L'USB senza modalità sviluppatore non è disponibile ({ $reason }); il debug USB funziona ancora.
error-unsupported = Questo sistema non supporta ancora gli schermi virtuali
error-source = Impossibile creare la sorgente video: { $reason }
@@ -45,6 +46,9 @@ devices-heading = Dispositivi
stats-heading = Statistiche in tempo reale
stats-waiting = In attesa delle prime misurazioni…
stat-device = Tablet
+stat-connection = Connessione
+transport-aoa = USB (accessorio)
+transport-wifi = Wi-Fi
stat-mode = Modalità
stat-encoder = Encoder
stat-fps = Frequenza dei fotogrammi
@@ -129,6 +133,7 @@ device-unauthorized = in attesa che accetti il debug USB
device-offline = offline
open-app = Apri l'app sul tablet quando si connette
use-adb = Connetti via USB con adb
+use-aoa = USB senza modalità sviluppatore
advanced = Avanzate
setting-port = Porta
port-hint = Il tablet raggiunge questo computer su questa porta. Le modifiche valgono quando non c'è nessuna sessione in corso.
@@ -185,6 +190,7 @@ input-description = Usa il tablet come touchscreen e penna su questo computer.
pen-description = Una tavoletta grafica aggiunge pressione e inclinazione.
telemetry-description = Mostra sul tablet valori di prestazione in tempo reale durante lo streaming.
use-adb-description = Trova i tablet con il debug USB attivo.
+use-aoa-description = Porta il tablet in modalità accessorio quando lo colleghi, senza bisogno del debug USB. adb resta come alternativa.
autostart-description = Avvia ezdisplay quando accedi.
start-on-launch-description = Si mette in attesa del tablet appena ezdisplay si apre.
system-accent = Usa il colore d'accento del sistema
diff --git a/crates/ezd-tray/i18n/pt/ezd-tray.ftl b/crates/ezd-tray/i18n/pt/ezd-tray.ftl
index abd3b1f..aa7a74a 100644
--- a/crates/ezd-tray/i18n/pt/ezd-tray.ftl
+++ b/crates/ezd-tray/i18n/pt/ezd-tray.ftl
@@ -18,6 +18,7 @@ status-streaming = Transmitindo para { $device } · { $width }×{ $height } a {
error-bind = Não foi possível escutar em { $addr }: { $reason }
error-adb-not-found = O adb não foi encontrado
error-adb-reverse = Falha no adb reverse para { $serial }: { $reason }
+usb-unavailable-hint = USB sem modo desenvolvedor indisponível ({ $reason }); a depuração USB continua funcionando.
error-unsupported = Este sistema ainda não tem suporte a telas virtuais
error-source = Não foi possível criar a fonte de vídeo: { $reason }
@@ -45,6 +46,9 @@ devices-heading = Dispositivos
stats-heading = Estatísticas ao vivo
stats-waiting = Aguardando as primeiras medições…
stat-device = Tablet
+stat-connection = Conexão
+transport-aoa = USB (acessório)
+transport-wifi = Wi-Fi
stat-mode = Modo
stat-encoder = Codificador
stat-fps = Taxa de quadros
@@ -129,6 +133,7 @@ device-unauthorized = aguardando você aceitar a depuração USB
device-offline = offline
open-app = Abrir o app no tablet ao conectar
use-adb = Conectar por USB com adb
+use-aoa = USB sem modo desenvolvedor
advanced = Avançado
setting-port = Porta
port-hint = O tablet alcança este computador por esta porta. As mudanças valem quando não há sessão em andamento.
@@ -185,6 +190,7 @@ input-description = Use o tablet como tela de toque e caneta neste computador.
pen-description = Uma mesa digitalizadora adiciona pressão e inclinação.
telemetry-description = Mostra números de desempenho ao vivo no tablet durante a transmissão.
use-adb-description = Encontra tablets com a depuração USB ativada.
+use-aoa-description = Muda o tablet para o modo acessório ao conectá-lo, sem precisar da depuração USB. O adb continua como alternativa.
autostart-description = Inicia o ezdisplay quando você entra na sessão.
start-on-launch-description = Começa a esperar pelo tablet assim que o ezdisplay abre.
system-accent = Usar a cor de destaque do sistema
diff --git a/crates/ezd-tray/src/controller.rs b/crates/ezd-tray/src/controller.rs
index bf1007b..44172ac 100644
--- a/crates/ezd-tray/src/controller.rs
+++ b/crates/ezd-tray/src/controller.rs
@@ -336,6 +336,7 @@ impl Controller {
input_fix,
has_licenses_dir: paths::licenses_dir().is_some(),
wifi: self.wifi_state(),
+ usb_problem: self.usb_problem(),
windows: cfg!(windows),
version: env!("CARGO_PKG_VERSION").to_string(),
}
@@ -349,6 +350,7 @@ impl Controller {
snap.config = self.config.clone();
snap.autostart = self.autostart;
snap.wifi = self.wifi_state();
+ snap.usb_problem = self.usb_problem();
snap.repair = self
.repair
.lock()
@@ -357,6 +359,11 @@ impl Controller {
(snap.input_access, snap.input_fix) = self.input_state();
}
+ /// Why USB accessory mode is unavailable, while the service runs.
+ fn usb_problem(&self) -> Option {
+ self.service.as_ref()?.aoa_problem().borrow().clone()
+ }
+
fn input_state(&self) -> (InputAccess, InputFixState) {
let input = self.input.lock().unwrap_or_else(|e| e.into_inner());
(input.access, input.fix.clone())
diff --git a/crates/ezd-tray/src/ui/view.rs b/crates/ezd-tray/src/ui/view.rs
index a4c779a..4f000ab 100644
--- a/crates/ezd-tray/src/ui/view.rs
+++ b/crates/ezd-tray/src/ui/view.rs
@@ -12,7 +12,8 @@ use crate::state::Lifecycle;
use crate::text;
use eframe::egui::{self, ComboBox, Margin, RichText, Ui};
use ezd_host_service::{
- AdbMode, DeviceInfo, DeviceState, HdrChoice, HostStatus, LiveSession, PenChoice, WifiInfo,
+ AdbMode, AoaMode, DeviceInfo, DeviceState, HdrChoice, HostStatus, LiveSession, PenChoice,
+ Transport, WifiInfo,
};
use ezd_proto::{DynamicRange, SdrReason};
use i18n_embed::fluent::FluentLanguageLoader;
@@ -162,6 +163,8 @@ pub struct Snapshot {
pub input_fix: InputFixState,
pub has_licenses_dir: bool,
pub wifi: WifiState,
+ /// Why USB accessory mode is unavailable; informational (adb still works).
+ pub usb_problem: Option,
/// GPU choices and the USB driver hint are Windows-only.
pub windows: bool,
pub version: String,
@@ -524,6 +527,11 @@ impl SettingsView {
(fl!(l, "stat-device"), live.device_name.clone()),
(fl!(l, "stat-mode"), mode),
];
+ match live.transport {
+ Transport::Aoa => session.push((fl!(l, "stat-connection"), fl!(l, "transport-aoa"))),
+ Transport::Wifi => session.push((fl!(l, "stat-connection"), fl!(l, "transport-wifi"))),
+ Transport::Tcp => {}
+ }
if let DynamicRange::SdrToneMapped(reason) = live.dynamic_range {
session.push((fl!(l, "stat-hdr"), sdr_reason_text(l, reason)));
}
@@ -1067,15 +1075,39 @@ impl SettingsView {
_ => Vec::new(),
};
let windows = self.snap.windows;
+ let usb_problem = self.snap.usb_problem.clone();
let cfg = &mut self.snap.config.service;
// Android Debug Bridge.
let mut use_adb = cfg.adb != AdbMode::Off;
+ let mut use_aoa = cfg.aoa != AoaMode::Off;
widgets::card(
ui,
pal,
Some((glyphs::PLUG_CONNECTED, &fl!(l, "card-adb"))),
|ui| {
+ if cfg!(feature = "aoa") {
+ if widgets::toggle_row(
+ ui,
+ pal,
+ &fl!(l, "use-aoa"),
+ Some(&fl!(l, "use-aoa-description")),
+ &mut use_aoa,
+ )
+ .changed()
+ {
+ cfg.aoa = if use_aoa { AoaMode::Auto } else { AoaMode::Off };
+ }
+ if let Some(reason) = usb_problem.as_deref().filter(|_| use_aoa) {
+ ui.add_space(4.0);
+ ui.label(
+ RichText::new(fl!(l, "usb-unavailable-hint", reason = reason))
+ .small()
+ .weak(),
+ );
+ }
+ widgets::row_divider(ui, pal);
+ }
widgets::info_row(ui, pal, "adb", &adb_value);
widgets::row_divider(ui, pal);
if widgets::toggle_row(
diff --git a/crates/ezd-tray/src/ui/view/tests.rs b/crates/ezd-tray/src/ui/view/tests.rs
index f6de65b..627b8ac 100644
--- a/crates/ezd-tray/src/ui/view/tests.rs
+++ b/crates/ezd-tray/src/ui/view/tests.rs
@@ -81,6 +81,7 @@ fn snapshot(status: HostStatus) -> Snapshot {
input_fix: InputFixState::Idle,
has_licenses_dir: false,
wifi: WifiState::default(),
+ usb_problem: None,
windows: false,
version: "0.1.0".into(),
}
@@ -136,6 +137,53 @@ fn waiting_stopped_and_error_states() {
h.get_by_label("No se encontr\u{f3} adb");
}
+#[test]
+fn the_session_transport_is_shown_for_usb_accessory_and_wifi() {
+ let with = |t: Transport| {
+ let HostStatus::Streaming(mut s) = live(None) else {
+ unreachable!()
+ };
+ s.transport = t;
+ snapshot(HostStatus::Streaming(s))
+ };
+ let h = harness(with(Transport::Aoa), "en");
+ h.get_by_label("USB (accessory)");
+ let h = harness(with(Transport::Aoa), "es");
+ h.get_by_label("USB (accesorio)");
+ // "Wi-Fi" is also the name of a page, so count the labels.
+ let wifi_labels = |t| harness(with(t), "en").query_all_by_label("Wi-Fi").count();
+ assert_eq!(
+ wifi_labels(Transport::Wifi),
+ wifi_labels(Transport::Tcp) + 1
+ );
+ let h = harness(with(Transport::Tcp), "en");
+ assert!(h.query_by_label("USB (accessory)").is_none());
+}
+
+#[test]
+fn an_unavailable_usb_accessory_mode_is_a_hint_in_the_user_language() {
+ let mut snap = snapshot(HostStatus::Waiting {
+ devices: Vec::new(),
+ });
+ snap.usb_problem = Some("UsbDk is not installed".into());
+ let mut h = harness_sized(snap.clone(), "en", egui::vec2(820.0, 720.0));
+ h.get_by_role_and_label(Role::Button, "Connection").click();
+ h.run();
+ h.get_by_label(
+ "USB without developer mode is unavailable (UsbDk is not installed); USB debugging still works.",
+ );
+ // Only a hint: the status stays "waiting".
+ assert!(matches!(h.state().snap.status, HostStatus::Waiting { .. }));
+ // Not shown once the mode is switched off.
+ h.get_by_role_and_label(Role::CheckBox, "USB without developer mode")
+ .click();
+ h.run();
+ assert!(
+ h.query_by_label_contains("USB debugging still works")
+ .is_none()
+ );
+}
+
#[test]
fn live_statistics_are_listed() {
let h = harness(snapshot(live(Some(stats()))), "en");
@@ -786,7 +834,12 @@ fn the_pen_choice_is_a_segmented_control_that_needs_input_on() {
#[test]
fn the_advanced_section_collapses_and_edits_the_port() {
- let mut h = harness(snapshot(HostStatus::Stopped), "en");
+ // Tall enough for the whole Connection page, which has a row for USB without developer mode.
+ let mut h = harness_sized(
+ snapshot(HostStatus::Stopped),
+ "en",
+ egui::vec2(820.0, 720.0),
+ );
h.get_by_role_and_label(Role::Button, "Connection").click();
h.run();
h.get_by_label("Android Debug Bridge");
@@ -813,6 +866,26 @@ fn turning_adb_off_changes_the_config() {
assert_eq!(h.state().snap.config.service.adb, AdbMode::Off);
}
+#[test]
+fn turning_usb_without_developer_mode_off_changes_the_config() {
+ let mut h = harness_sized(
+ snapshot(HostStatus::Stopped),
+ "en",
+ egui::vec2(820.0, 720.0),
+ );
+ h.get_by_role_and_label(Role::Button, "Connection").click();
+ h.run();
+ assert_eq!(h.state().snap.config.service.aoa, AoaMode::Auto);
+ h.get_by_role_and_label(Role::CheckBox, "USB without developer mode")
+ .click();
+ h.run();
+ assert_eq!(h.state().snap.config.service.aoa, AoaMode::Off);
+ h.get_by_role_and_label(Role::CheckBox, "USB without developer mode")
+ .click();
+ h.run();
+ assert_eq!(h.state().snap.config.service.aoa, AoaMode::Auto);
+}
+
#[test]
fn the_general_page_has_its_four_cards() {
let mut h = harness(snapshot(HostStatus::Stopped), "en");
diff --git a/docs/architecture.md b/docs/architecture.md
index af92cf4..7dffded 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -52,7 +52,7 @@ left out. The platform backends are only built on their own OS.
| Crate / dir | Role |
|---|---|
| `crates/ezd-proto` | Wire protocol: framing, messages, capabilities negotiation, clock sync. Pure, no I/O. |
-| `crates/ezd-link` | Links (TCP through ADB; QUIC on Wi-Fi with separate control and video streams; AOA later), device identity and PIN pairing, ADB helper, prioritized mux with video credit. |
+| `crates/ezd-link` | Links (TCP through ADB; QUIC on Wi-Fi with separate control and video streams; AOA over libusb bulk endpoints), device identity and PIN pairing, ADB helper, prioritized mux with video credit. |
| `crates/ezd-host-core` | Platform-independent host: `VideoSource` / `VirtualDisplay` traits, session, pacing, synthetic frames. |
| `crates/ezd-ffmpeg` | Thin safe wrapper over FFmpeg (encoders, decoders, hardware contexts). |
| `crates/ezd-host-service` | The host loop as a library: accepts the tablet, keeps `adb reverse` set up for each device, runs sessions and publishes live status. Used by the CLI and the tray app. |
@@ -65,7 +65,7 @@ left out. The platform backends are only built on their own OS.
| `crates/ezd-input` | Client input engine: motion events to protocol input messages, palm rejection, S Pen button gestures, local zoom. |
| `crates/ezd-android` + `android/` | Android client: Kotlin UI, Rust native lib with AMediaCodec decode to a SurfaceView. |
| `packaging/windows` | Inno Setup installer: bundles the driver, `nefconw.exe` and `adb`, downloads the pinned FFmpeg build during setup. |
-| `packaging/linux` | udev rule for `/dev/uinput`, desktop entry and icon; Arch `PKGBUILD`, Debian/Ubuntu `.deb` maintainer scripts (metadata in `crates/ezd-tray`) and the AppImage build (bundled FFmpeg and adb). |
+| `packaging/linux` | udev rules for `/dev/uinput` and USB access, desktop entry and icon; Arch `PKGBUILD`, Debian/Ubuntu `.deb` maintainer scripts (metadata in `crates/ezd-tray`) and the AppImage build (bundled FFmpeg and adb). |
| `tools/latency` | Web page for glass-to-glass measurements with a slow-motion camera. |
| `tools/input-test` | Web page and logger to check injected pen, touch, buttons and scroll as text. |
@@ -123,7 +123,7 @@ flowchart TB
0. Diagnosis and spikes (Nitro measurements, KDE virtual output, tablet probing).
1. Vertical slice on both hosts: video and local cursor over ADB. 1a core → 1b Android, 1c Linux KDE, 1d Windows in parallel.
2. Input: touch, pen, S Pen button gestures.
-3. Transports: Wi-Fi (QUIC with PIN or QR pairing, mDNS discovery) in progress; AOA later.
+3. Transports: Wi-Fi (QUIC with PIN or QR pairing, mDNS discovery) in progress; AOA (USB without developer mode, libusb) done.
4. Audio.
5. GNOME and wlroots backends.
6. Packaging: Windows installer (done, with the tray app), Linux packages (Arch, .deb, AppImage; done) and udev rules, Android `full`/`play` builds.
diff --git a/docs/windows-testing.md b/docs/windows-testing.md
index 40374b9..6641abc 100644
--- a/docs/windows-testing.md
+++ b/docs/windows-testing.md
@@ -100,6 +100,10 @@ the MUX mode) and, if possible, in a third pass that forces the GPU.
- **Firewall (Wi-Fi):** after installing, `netsh advfirewall firewall show rule name=all` must list
the two "ezdisplay Wi-Fi" inbound rules (UDP 27183, private profile); a reinstall must not
duplicate them and the uninstall must remove them.
+- **UsbDk task:** the "USB without developer mode (installs the UsbDk driver)" task must be
+ unchecked by default. When checked, setup downloads the pinned MSI (SHA-256 checked) and installs it
+ silently; a reinstall must not download it again once the `UsbDk` service exists. Uninstalling
+ ezdisplay leaves UsbDk in place on purpose.
- **Uninstall** from *Settings*, *Apps*: afterwards Device Manager (*Display adapters*, with
*View*, *Show hidden devices*) must not list "Virtual Display Driver", and
`C:\Program Files\ezdisplay` must be gone.
@@ -120,6 +124,16 @@ In each case check that the virtual monitor appears to the right of the main one
reaches the tablet in the requested mode, that the pointer moves without lag, and that video recovers
on its own after changing the resolution or locking/unlocking the session.
+## USB without developer mode (AOA)
+
+- With UsbDk installed and developer mode (USB debugging) off on the tablet, plugging it in over USB
+ must connect. The first time, Android asks which app should open the accessory: pick ezdisplay;
+ "always" avoids the question later.
+- Without UsbDk, USB must fall back to adb (needs USB debugging on the tablet).
+- A phone or tablet without the app must be switched once and then left alone: it returns to normal
+ mode (MTP) and is not retried while the host runs.
+- `--aoa off` (or `aoa = "off"` in `config.toml`) must skip the accessory attempt and use adb only.
+
## Input (pen and touch)
The host injects the tablet's pen and touch with Windows synthetic pointer devices (Windows 10 1809
diff --git a/packaging/linux/70-ezdisplay-usb.rules b/packaging/linux/70-ezdisplay-usb.rules
new file mode 100644
index 0000000..cd6e9d8
--- /dev/null
+++ b/packaging/linux/70-ezdisplay-usb.rules
@@ -0,0 +1,12 @@
+# ezdisplay: let the logged-in user open the USB devices the host talks to over AOA (Android Open
+# Accessory), without developer mode: phones and tablets with an MTP or ADB interface, and devices
+# already switched into accessory mode.
+#
+# Install:
+# sudo install -m644 packaging/linux/70-ezdisplay-usb.rules /etc/udev/rules.d/
+# sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb
+#
+# The file name must sort before 73-seat-late.rules, which applies the "uaccess" tag.
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:060101:*", TAG+="uaccess"
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:ff4201:*", TAG+="uaccess"
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{idVendor}=="18d1", ATTR{idProduct}=="2d0[0-5]", TAG+="uaccess"
diff --git a/packaging/linux/README.md b/packaging/linux/README.md
index 0de78c5..1fcea1d 100644
--- a/packaging/linux/README.md
+++ b/packaging/linux/README.md
@@ -9,10 +9,11 @@ Only KDE Plasma 6 on Wayland is supported today. CI builds all of this in
| Path | What it is |
| --- | --- |
| `70-ezdisplay-uinput.rules` | udev rule that lets the logged-in user create uinput devices (touch and pen input). |
+| `70-ezdisplay-usb.rules` | udev rule that lets the logged-in user open USB devices with an MTP or ADB interface, and devices in accessory mode, for the AOA transport (USB without developer mode). |
| `ufw/ezdisplay`, `firewalld/ezdisplay.xml` | ufw application profile and firewalld service for the Wi-Fi port (UDP 27183). The Arch package and the `.deb` install them to `/etc/ufw/applications.d/` and `/usr/lib/firewalld/services/`; nothing is enabled or opened automatically. |
| `com.librestatic.ezdisplay.desktop`, `.svg` | Desktop entry and icon. |
| `arch/PKGBUILD`, `arch/ezdisplay.install` | Arch package built from this checkout (no source download). |
-| `debian/postinst` | Maintainer script of the `.deb`: reloads udev and re-triggers `/dev/uinput`. The package metadata is `[package.metadata.deb]` in `crates/ezd-tray/Cargo.toml`. |
+| `debian/postinst` | Maintainer script of the `.deb`: reloads udev and re-triggers `/dev/uinput` and the USB devices. The package metadata is `[package.metadata.deb]` in `crates/ezd-tray/Cargo.toml`. |
| `appimage/build.sh`, `pins.env`, `smoke.sh` | AppImage build (FFmpeg and x264 built from pinned sources, adb bundled), its pinned downloads and a smoke test. |
## Arch
@@ -28,7 +29,7 @@ sudo pacman -U ezdisplay-*.pkg.tar.zst
```sh
docker run --rm -v "$PWD:/src:ro" -v ~/.cache/ezd-pkg/arch:/work archlinux:latest bash -c '
- pacman -Syu --noconfirm --needed base-devel sudo rust clang pkgconf ffmpeg pipewire libva
+ pacman -Syu --noconfirm --needed base-devel sudo rust clang pkgconf ffmpeg pipewire libva libusb
useradd -m builder && chmod 777 /work && cd /src/packaging/linux/arch
sudo -u builder env BUILDDIR=/work/build PKGDEST=/work/out SRCDEST=/work/src makepkg --noconfirm -f'
```
@@ -43,7 +44,7 @@ docker run --rm -v "$PWD:/src:ro" -v ~/.cache/ezd-pkg/deb:/work -e CARGO_HOME=/w
-e CARGO_TARGET_DIR=/work/target ubuntu:24.04 bash -c '
apt-get update && apt-get install -y --no-install-recommends build-essential clang libclang-dev \
pkg-config ca-certificates git curl dpkg-dev libavcodec-dev libavformat-dev libavfilter-dev \
- libavutil-dev libswscale-dev libswresample-dev libpipewire-0.3-dev libva-dev libx11-dev \
+ libavutil-dev libswscale-dev libswresample-dev libpipewire-0.3-dev libva-dev libusb-1.0-0-dev libx11-dev \
libxkbcommon-dev libwayland-dev
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal && . /work/cargo/env
cd /src && cargo build --release --locked -p ezd-host -p ezd-tray
@@ -67,7 +68,7 @@ docker run --rm -v "$PWD:/src:ro" -v ~/.cache/ezd-pkg/appimage:/work -e CARGO_HO
-e CARGO_TARGET_DIR=/work/target -e DEBIAN_FRONTEND=noninteractive ubuntu:24.04 bash -c '
apt-get update && apt-get install -y --no-install-recommends build-essential clang libclang-dev \
pkg-config nasm curl ca-certificates git xz-utils unzip file patchelf binutils libva-dev \
- libdrm-dev libpipewire-0.3-dev libvulkan-dev libxkbcommon-dev libwayland-dev libx11-dev \
+ libdrm-dev libpipewire-0.3-dev libvulkan-dev libusb-1.0-0-dev libxkbcommon-dev libwayland-dev libx11-dev \
glslang-tools glslang-dev spirv-tools
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal && . /work/cargo/env
/src/packaging/linux/appimage/build.sh --out /work/out --cache /work/downloads --work /work/build'
@@ -79,7 +80,7 @@ cached file with the right hash is not downloaded again. The result is
sources, see [docs/releasing.md](../../docs/releasing.md)).
The build refuses to produce an AppImage whose binaries need any library outside the bundle other
-than glibc, libgcc_s, libva, libva-drm, libdrm, libvulkan and PipeWire, or glibc symbols newer than
+than glibc, libgcc_s, libva, libva-drm, libdrm, libvulkan, libusb-1.0 (with its libudev and libcap dependencies) and PipeWire (libusb is a host dependency, present on practically every desktop distro), or glibc symbols newer than
2.39. Smoke test on a machine without FFmpeg (needs `jq`):
```sh
@@ -89,7 +90,15 @@ packaging/linux/appimage/smoke.sh out/ezdisplay-*.AppImage
Inside the image, `AppRun` starts the tray app; `AppRun host ...` runs `ezd-host`. The bundled adb
is at `usr/bin/adb/adb` and the licence texts at `usr/bin/licenses/`, where the app looks for them.
-An AppImage cannot install system files. To use the firewall profiles with it, copy them from
+An AppImage cannot install system files. For USB without developer mode, install the udev rule
+yourself, as for the uinput rule:
+
+```sh
+sudo install -m644 packaging/linux/70-ezdisplay-usb.rules /etc/udev/rules.d/
+sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb
+```
+
+To use the firewall profiles with it, copy them from
this directory (`ufw/ezdisplay` to `/etc/ufw/applications.d/`, `firewalld/ezdisplay.xml` to
`/etc/firewalld/services/`), or open the port directly; see the Wi-Fi section of the
[README](../../README.md#firewall-linux).
diff --git a/packaging/linux/appimage/build.sh b/packaging/linux/appimage/build.sh
index e1d7c05..756e9e2 100755
--- a/packaging/linux/appimage/build.sh
+++ b/packaging/linux/appimage/build.sh
@@ -5,14 +5,15 @@
#
# Run it inside an ubuntu:24.04 container (glibc 2.39 is the floor of the result). Supported
# targets: any x86_64 distro with glibc 2.39 or newer and KDE Plasma 6 on Wayland (KDE neon,
-# Debian 13, Fedora 40+, Arch, openSUSE Tumbleweed, Kubuntu 24.10+). libva, libdrm, libvulkan and
-# PipeWire come from the host; everything else is bundled.
+# Debian 13, Fedora 40+, Arch, openSUSE Tumbleweed, Kubuntu 24.10+). libva, libdrm, libvulkan,
+# libusb-1.0 (with its libudev and libcap dependencies) and PipeWire come from the host; everything
+# else is bundled.
#
# The container needs (and must NOT have any libav*-dev package, so the system FFmpeg can never
# be picked up):
# build-essential clang libclang-dev pkg-config nasm curl ca-certificates git xz-utils unzip
-# file patchelf binutils libva-dev libdrm-dev libpipewire-0.3-dev libvulkan-dev libxkbcommon-dev
-# libwayland-dev libx11-dev glslang-tools glslang-dev spirv-tools
+# file patchelf binutils libva-dev libdrm-dev libpipewire-0.3-dev libvulkan-dev libusb-1.0-0-dev
+# libxkbcommon-dev libwayland-dev libx11-dev glslang-tools glslang-dev spirv-tools
#
# Usage: build.sh [--out DIR] [--cache DIR] [--work DIR] [--jobs N]
# --out where the AppImage and the sources bundle go (default: ./out)
@@ -245,7 +246,7 @@ chmod 755 "$APPDIR/AppRun"
# --- 7. Dependency gate -------------------------------------------------------------------
log "Checking the dependencies of every ELF in the AppDir"
-ALLOW='^(libc\.so\.6|libm\.so\.6|libdl\.so\.2|libpthread\.so\.0|librt\.so\.1|libmvec\.so\.1|libgcc_s\.so\.1|ld-linux-x86-64\.so\.2|libva\.so\.2|libva-drm\.so\.2|libdrm\.so\.2|libvulkan\.so\.1|libpipewire-0\.3\.so\.0)$'
+ALLOW='^(libc\.so\.6|libm\.so\.6|libdl\.so\.2|libpthread\.so\.0|librt\.so\.1|libmvec\.so\.1|libgcc_s\.so\.1|ld-linux-x86-64\.so\.2|libva\.so\.2|libva-drm\.so\.2|libdrm\.so\.2|libvulkan\.so\.1|libpipewire-0\.3\.so\.0|libusb-1\.0\.so\.0|libudev\.so\.1|libcap\.so\.2)$'
MAX_GLIBC=2.39
gate_failed=0
while IFS= read -r -d '' f; do
diff --git a/packaging/linux/arch/PKGBUILD b/packaging/linux/arch/PKGBUILD
index b6c0ed4..f2b0374 100644
--- a/packaging/linux/arch/PKGBUILD
+++ b/packaging/linux/arch/PKGBUILD
@@ -11,7 +11,7 @@ pkgdesc='Use an Android tablet as an extended monitor over USB (KDE Plasma host
arch=(x86_64)
url='https://github.com/LibreStatic/ezdisplay'
license=('MIT OR Apache-2.0')
-depends=(ffmpeg pipewire libva gcc-libs glibc android-tools xdg-desktop-portal-kde libkscreen)
+depends=(ffmpeg pipewire libva gcc-libs glibc android-tools xdg-desktop-portal-kde libkscreen libusb)
makedepends=(rust clang pkgconf)
options=(!lto !debug)
install=ezdisplay.install
@@ -38,6 +38,8 @@ package() {
install -Dm755 "$t/ezd-host" "$pkgdir/usr/bin/ezd-host"
install -Dm644 packaging/linux/70-ezdisplay-uinput.rules \
"$pkgdir/usr/lib/udev/rules.d/70-ezdisplay-uinput.rules"
+ install -Dm644 packaging/linux/70-ezdisplay-usb.rules \
+ "$pkgdir/usr/lib/udev/rules.d/70-ezdisplay-usb.rules"
install -Dm644 packaging/linux/ufw/ezdisplay "$pkgdir/etc/ufw/applications.d/ezdisplay"
install -Dm644 packaging/linux/firewalld/ezdisplay.xml \
"$pkgdir/usr/lib/firewalld/services/ezdisplay.xml"
diff --git a/packaging/linux/arch/ezdisplay.install b/packaging/linux/arch/ezdisplay.install
index ccd2f15..4f7fdc2 100644
--- a/packaging/linux/arch/ezdisplay.install
+++ b/packaging/linux/arch/ezdisplay.install
@@ -1,6 +1,7 @@
post_install() {
- # pacman's own hook reloads the udev rules; apply the uaccess tag to an existing /dev/uinput.
+ # pacman's own hook reloads the udev rules; apply the uaccess tag to an existing /dev/uinput and to connected USB devices.
udevadm trigger --name-match=uinput 2>/dev/null || true
+ udevadm trigger --subsystem-match=usb 2>/dev/null || true
cat <<'MSG'
==> ezdisplay: nothing was opened in your firewall. To let tablets reach the host over Wi-Fi
(UDP port 27183), allow it yourself, scoped to your LAN:
@@ -11,4 +12,5 @@ MSG
post_upgrade() {
udevadm trigger --name-match=uinput 2>/dev/null || true
+ udevadm trigger --subsystem-match=usb 2>/dev/null || true
}
diff --git a/packaging/linux/debian/postinst b/packaging/linux/debian/postinst
index c8ca418..68fd8ea 100755
--- a/packaging/linux/debian/postinst
+++ b/packaging/linux/debian/postinst
@@ -1,11 +1,12 @@
#!/bin/sh
-# Applies the /dev/uinput udev rule right after install; containers and chroots have no udev.
+# Applies the /dev/uinput and USB udev rules right after install; containers and chroots have no udev.
set -e
case "$1" in
configure)
udevadm control --reload-rules 2>/dev/null || true
udevadm trigger --name-match=uinput 2>/dev/null || true
+ udevadm trigger --subsystem-match=usb 2>/dev/null || true
;;
esac
diff --git a/packaging/windows/ezdisplay.iss b/packaging/windows/ezdisplay.iss
index 108f601..1cab5b6 100644
--- a/packaging/windows/ezdisplay.iss
+++ b/packaging/windows/ezdisplay.iss
@@ -56,8 +56,13 @@ Name: "german"; MessagesFile: "compiler:Languages\German.isl,i18n\de-du.isl"
[CustomMessages]
english.TaskDriver=Install the virtual display driver
english.TaskAutostart=Start ezdisplay when you sign in
-english.DownloadTitle=Downloading FFmpeg
-english.DownloadDesc=Setup is downloading the FFmpeg video libraries (about 90 MB).
+english.TaskUsbDk=USB without developer mode (installs the UsbDk driver)
+english.DownloadingUsbDk=Downloading UsbDk
+english.UsbDkDownloadFailed=UsbDk could not be downloaded:%n%n%1%n%nClick Retry to try again or Cancel to exit Setup. You can also go back and clear the USB task.
+english.UsbDkInstallFailed=UsbDk could not be installed (code %1). USB without developer mode will not work; ezdisplay falls back to adb.
+english.InstallingUsbDk=Installing the UsbDk driver...
+english.DownloadTitle=Downloading components
+english.DownloadDesc=Setup is downloading the components it needs: the FFmpeg video libraries (about 90 MB) and, if selected, UsbDk.
english.ExtractingFfmpeg=Extracting FFmpeg...
english.InstallingDriver=Installing the virtual display driver...
english.FfmpegDownloadFailed=FFmpeg could not be downloaded:%n%n%1%n%nClick Retry to try again or Cancel to exit Setup.
@@ -67,8 +72,13 @@ english.DriverFailed=The virtual display driver could not be installed (code %1)
spanish.TaskDriver=Instalar el controlador de pantalla virtual
spanish.TaskAutostart=Iniciar ezdisplay al iniciar sesión
-spanish.DownloadTitle=Descargando FFmpeg
-spanish.DownloadDesc=El asistente está descargando las bibliotecas de video FFmpeg (unos 90 MB).
+spanish.TaskUsbDk=USB sin modo desarrollador (instala el controlador UsbDk)
+spanish.DownloadingUsbDk=Descargando UsbDk
+spanish.UsbDkDownloadFailed=No se pudo descargar UsbDk:%n%n%1%n%nHacé clic en Reintentar para probar de nuevo o en Cancelar para salir. También podés volver y desmarcar la tarea de USB.
+spanish.UsbDkInstallFailed=No se pudo instalar UsbDk (código %1). El USB sin modo desarrollador no va a funcionar; ezdisplay usa adb como alternativa.
+spanish.InstallingUsbDk=Instalando el controlador UsbDk...
+spanish.DownloadTitle=Descargando componentes
+spanish.DownloadDesc=El asistente está descargando los componentes que necesita: las bibliotecas de video FFmpeg (unos 90 MB) y, si lo elegiste, UsbDk.
spanish.ExtractingFfmpeg=Extrayendo FFmpeg...
spanish.InstallingDriver=Instalando el controlador de pantalla virtual...
spanish.FfmpegDownloadFailed=No se pudo descargar FFmpeg:%n%n%1%n%nHacé clic en Reintentar para probar de nuevo o en Cancelar para salir.
@@ -78,8 +88,13 @@ spanish.DriverFailed=No se pudo instalar el controlador de pantalla virtual (có
french.TaskDriver=Installer le pilote d'affichage virtuel
french.TaskAutostart=Lancer ezdisplay à l'ouverture de session
-french.DownloadTitle=Téléchargement de FFmpeg
-french.DownloadDesc=L'assistant télécharge les bibliothèques vidéo FFmpeg (environ 90 Mo).
+french.TaskUsbDk=USB sans mode développeur (installe le pilote UsbDk)
+french.DownloadingUsbDk=Téléchargement de UsbDk
+french.UsbDkDownloadFailed=UsbDk n'a pas pu être téléchargé :%n%n%1%n%nCliquez sur Réessayer pour recommencer ou sur Annuler pour quitter. Vous pouvez aussi revenir en arrière et décocher la tâche USB.
+french.UsbDkInstallFailed=UsbDk n'a pas pu être installé (code %1). L'USB sans mode développeur ne fonctionnera pas ; ezdisplay se rabat sur adb.
+french.InstallingUsbDk=Installation du pilote UsbDk...
+french.DownloadTitle=Téléchargement des composants
+french.DownloadDesc=L'assistant télécharge les composants nécessaires : les bibliothèques vidéo FFmpeg (environ 90 Mo) et, si vous l'avez choisi, UsbDk.
french.ExtractingFfmpeg=Extraction de FFmpeg...
french.InstallingDriver=Installation du pilote d'affichage virtuel...
french.FfmpegDownloadFailed=FFmpeg n'a pas pu être téléchargé :%n%n%1%n%nCliquez sur Réessayer pour recommencer ou sur Annuler pour quitter.
@@ -89,8 +104,13 @@ french.DriverFailed=Le pilote d'affichage virtuel n'a pas pu être installé (co
brazilianportuguese.TaskDriver=Instalar o driver de tela virtual
brazilianportuguese.TaskAutostart=Iniciar o ezdisplay ao entrar no Windows
-brazilianportuguese.DownloadTitle=Baixando o FFmpeg
-brazilianportuguese.DownloadDesc=O instalador está baixando as bibliotecas de vídeo do FFmpeg (cerca de 90 MB).
+brazilianportuguese.TaskUsbDk=USB sem modo desenvolvedor (instala o driver UsbDk)
+brazilianportuguese.DownloadingUsbDk=Baixando o UsbDk
+brazilianportuguese.UsbDkDownloadFailed=Não foi possível baixar o UsbDk:%n%n%1%n%nClique em Repetir para tentar de novo ou em Cancelar para sair. Você também pode voltar e desmarcar a tarefa de USB.
+brazilianportuguese.UsbDkInstallFailed=Não foi possível instalar o UsbDk (código %1). O USB sem modo desenvolvedor não vai funcionar; o ezdisplay recorre ao adb.
+brazilianportuguese.InstallingUsbDk=Instalando o driver UsbDk...
+brazilianportuguese.DownloadTitle=Baixando componentes
+brazilianportuguese.DownloadDesc=O instalador está baixando os componentes necessários: as bibliotecas de vídeo do FFmpeg (cerca de 90 MB) e, se você escolheu, o UsbDk.
brazilianportuguese.ExtractingFfmpeg=Extraindo o FFmpeg...
brazilianportuguese.InstallingDriver=Instalando o driver de tela virtual...
brazilianportuguese.FfmpegDownloadFailed=Não foi possível baixar o FFmpeg:%n%n%1%n%nClique em Repetir para tentar de novo ou em Cancelar para sair.
@@ -100,8 +120,13 @@ brazilianportuguese.DriverFailed=Não foi possível instalar o driver de tela vi
italian.TaskDriver=Installa il driver dello schermo virtuale
italian.TaskAutostart=Avvia ezdisplay all'accesso
-italian.DownloadTitle=Download di FFmpeg
-italian.DownloadDesc=Il programma di installazione sta scaricando le librerie video FFmpeg (circa 90 MB).
+italian.TaskUsbDk=USB senza modalità sviluppatore (installa il driver UsbDk)
+italian.DownloadingUsbDk=Download di UsbDk
+italian.UsbDkDownloadFailed=Impossibile scaricare UsbDk:%n%n%1%n%nFai clic su Riprova per riprovare o su Annulla per uscire. Puoi anche tornare indietro e deselezionare l'attività USB.
+italian.UsbDkInstallFailed=Impossibile installare UsbDk (codice %1). L'USB senza modalità sviluppatore non funzionerà; ezdisplay ripiega su adb.
+italian.InstallingUsbDk=Installazione del driver UsbDk...
+italian.DownloadTitle=Download dei componenti
+italian.DownloadDesc=Il programma di installazione sta scaricando i componenti necessari: le librerie video FFmpeg (circa 90 MB) e, se l'hai scelto, UsbDk.
italian.ExtractingFfmpeg=Estrazione di FFmpeg...
italian.InstallingDriver=Installazione del driver dello schermo virtuale...
italian.FfmpegDownloadFailed=Impossibile scaricare FFmpeg:%n%n%1%n%nFai clic su Riprova per riprovare o su Annulla per uscire.
@@ -111,8 +136,13 @@ italian.DriverFailed=Impossibile installare il driver dello schermo virtuale (co
german.TaskDriver=Treiber für den virtuellen Bildschirm installieren
german.TaskAutostart=ezdisplay bei der Anmeldung starten
-german.DownloadTitle=FFmpeg wird heruntergeladen
-german.DownloadDesc=Das Setup lädt die FFmpeg-Videobibliotheken herunter (etwa 90 MB).
+german.TaskUsbDk=USB ohne Entwickleroptionen (installiert den UsbDk-Treiber)
+german.DownloadingUsbDk=UsbDk wird heruntergeladen
+german.UsbDkDownloadFailed=UsbDk konnte nicht heruntergeladen werden:%n%n%1%n%nKlicke auf Wiederholen, um es erneut zu versuchen, oder auf Abbrechen, um das Setup zu beenden. Du kannst auch zurückgehen und die USB-Aufgabe abwählen.
+german.UsbDkInstallFailed=UsbDk konnte nicht installiert werden (Code %1). USB ohne Entwickleroptionen funktioniert nicht; ezdisplay weicht auf adb aus.
+german.InstallingUsbDk=UsbDk-Treiber wird installiert...
+german.DownloadTitle=Komponenten werden heruntergeladen
+german.DownloadDesc=Das Setup lädt die benötigten Komponenten herunter: die FFmpeg-Videobibliotheken (etwa 90 MB) und, falls ausgewählt, UsbDk.
german.ExtractingFfmpeg=FFmpeg wird entpackt...
german.InstallingDriver=Treiber für den virtuellen Bildschirm wird installiert...
german.FfmpegDownloadFailed=FFmpeg konnte nicht heruntergeladen werden:%n%n%1%n%nKlicke auf Wiederholen, um es erneut zu versuchen, oder auf Abbrechen, um das Setup zu beenden.
@@ -123,6 +153,8 @@ german.DriverFailed=Der Treiber für den virtuellen Bildschirm konnte nicht inst
[Tasks]
Name: "driver"; Description: "{cm:TaskDriver}"
Name: "autostart"; Description: "{cm:TaskAutostart}"
+; Optional, off by default: UsbDk lets the host open the tablet over USB without developer mode (AOA).
+Name: "usbdk"; Description: "{cm:TaskUsbDk}"; Flags: unchecked
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[Files]
@@ -192,6 +224,8 @@ var
DownloadPage: TDownloadWizardPage;
// Path of the FFmpeg archive to install ('' = the pinned build is already installed).
FfmpegZip: String;
+ // Path of the downloaded UsbDk MSI ('' = nothing to install).
+ UsbDkMsi: String;
RestartNeeded: Boolean;
procedure InitializeWizard;
@@ -228,6 +262,52 @@ begin
Result := FfmpegZip <> '';
end;
+// UsbDk registers a kernel service named "UsbDk".
+function UsbDkAlreadyInstalled: Boolean;
+begin
+ Result := RegKeyExists(HKLM64, 'SYSTEM\CurrentControlSet\Services\UsbDk');
+end;
+
+// Downloads the pinned UsbDk MSI when its task is selected and the driver is not installed yet.
+// False means the user cancelled Setup after a failed download.
+function DownloadUsbDk: Boolean;
+var
+ Retry: Boolean;
+begin
+ Result := True;
+ UsbDkMsi := '';
+ if not WizardIsTaskSelected('usbdk') then
+ Exit;
+ if UsbDkAlreadyInstalled then
+ begin
+ Log('ezdisplay: UsbDk already installed');
+ Exit;
+ end;
+ repeat
+ Retry := False;
+ Log('ezdisplay: downloading UsbDk');
+ DownloadPage.Clear;
+ DownloadPage.SetText(CustomMessage('DownloadingUsbDk'), '');
+ DownloadPage.Add('{#UsbDkUrl}', 'usbdk.msi', '{#UsbDkSha256}');
+ DownloadPage.Show;
+ try
+ try
+ DownloadPage.Download;
+ UsbDkMsi := ExpandConstant('{tmp}\usbdk.msi');
+ except
+ Log('ezdisplay: UsbDk download failed: ' + GetExceptionMessage);
+ if SuppressibleMsgBox(FmtMessage(CustomMessage('UsbDkDownloadFailed'), [GetExceptionMessage]),
+ mbError, MB_RETRYCANCEL, IDCANCEL) = IDRETRY then
+ Retry := True
+ else
+ Result := False;
+ end;
+ finally
+ DownloadPage.Hide;
+ end;
+ until not Retry;
+end;
+
// Runs on silent installs too (they simulate the Next clicks).
function NextButtonClick(CurPageID: Integer): Boolean;
var
@@ -238,6 +318,14 @@ begin
if CurPageID <> wpReady then
Exit;
+ if not DownloadUsbDk then
+ begin
+ Result := False;
+ Exit;
+ end;
+ // Clear the UsbDk line of the progress page before FFmpeg uses it.
+ DownloadPage.SetText('', '');
+
FfmpegZip := '';
if FfmpegAlreadyInstalled then
begin
@@ -354,6 +442,23 @@ begin
until Finished;
end;
+// Silent MSI install of the UsbDk driver. A failure is not fatal: without UsbDk the host falls back
+// to adb. Uninstall does not remove UsbDk on purpose, since other applications may depend on it.
+procedure InstallUsbDk;
+var
+ ResultCode: Integer;
+begin
+ WizardForm.StatusLabel.Caption := CustomMessage('InstallingUsbDk');
+ if not Exec(ExpandConstant('{sys}\msiexec.exe'), '/i "' + UsbDkMsi + '" /qn /norestart', '',
+ SW_HIDE, ewWaitUntilTerminated, ResultCode) then
+ ResultCode := -1;
+ Log('ezdisplay: UsbDk msiexec exit code ' + IntToStr(ResultCode));
+ if ResultCode = 3010 then
+ RestartNeeded := True
+ else if ResultCode <> 0 then
+ SuppressibleMsgBox(FmtMessage(CustomMessage('UsbDkInstallFailed'), [IntToStr(ResultCode)]), mbError, MB_OK, IDOK);
+end;
+
procedure CurStepChanged(CurStep: TSetupStep);
begin
// ssInstall comes before [Files]; ssPostInstall after [Files] and the non-postinstall [Run].
@@ -375,5 +480,7 @@ begin
end;
if WizardIsTaskSelected('driver') then
InstallDriver;
+ if UsbDkMsi <> '' then
+ InstallUsbDk;
end;
end;
diff --git a/packaging/windows/pins.iss b/packaging/windows/pins.iss
index 8840627..6e4cb9c 100644
--- a/packaging/windows/pins.iss
+++ b/packaging/windows/pins.iss
@@ -22,3 +22,9 @@
; Android SDK Platform-Tools r37.0.1. Bundled: adb.exe, AdbWinApi.dll, AdbWinUsbApi.dll, NOTICE.txt.
#define PlatformToolsUrl "https://dl.google.com/android/repository/platform-tools_r37.0.1-win.zip"
#define PlatformToolsSha256 "45f4d63113e895ebde0c90f194099a4676b6ac653bd28d54314a9e022bbc1a99"
+
+; UsbDk 1.0.22 (Apache-2.0, https://github.com/daynix/UsbDk): the filter driver that lets libusb open
+; devices Windows keeps for itself (MTP), needed for USB without developer mode (AOA). Optional
+; installer task: the installer downloads the MSI and runs it only when the task is selected.
+#define UsbDkUrl "https://github.com/daynix/UsbDk/releases/download/v1.00-22/UsbDk_1.0.22_x64.msi"
+#define UsbDkSha256 "91f6f695e1e13c656024e6d3b55620bf08d8835ef05ee0496935ba6bb62466a5"