From 9ab16e80b1e03b84568043b210bb57f55543d0f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 14:46:27 +0000 Subject: [PATCH 1/6] Several iPhones at once and Wi-Fi connections (experimental, both editions) - More iPhones: extra phones follow the main one. The player still talks to one device; every position is also handed to each mirror, which sends it from its own coalescing queue (Python: mirrors.py MirrorLink/FanOut, Rust: device/mirror.rs), so a slow or lost phone never holds up playback. Lost phones are marked until removed; removing one clears its location. API: POST /api/mirrors, DELETE /api/mirrors/{udid}, status "mirrors". In Rust a mirror connects without the device lock held. - Connection choice (auto / usb / network) for connect and mirrors, a device list that shows USB, Wi-Fi or both, and "Allow Wi-Fi connection" (lockdown EnableWifiConnections). Browser edition: a second iOS 17+ phone or an iOS 17+ phone over Wi-Fi falls back to tunneld, because pymobiledevice3 allows one userspace tunnel per process. - The Simulator has two phones. Tests in both editions; test notes in docs/testing/multiple-iphones-and-wifi.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdn8QS1XrFZScnrMdvK --- CHANGELOG.md | 4 + browser/spoofer/device/base.py | 9 +- browser/spoofer/device/cli.py | 2 +- browser/spoofer/device/mock.py | 21 +- browser/spoofer/device/pmd3.py | 91 +++++++-- browser/spoofer/mirrors.py | 146 ++++++++++++++ browser/spoofer/server.py | 85 +++++++- browser/tests/test_mirrors.py | 229 ++++++++++++++++++++++ docs/testing/multiple-iphones-and-wifi.md | 31 +++ standalone/src/device/idev.rs | 85 ++++++-- standalone/src/device/mirror.rs | 213 ++++++++++++++++++++ standalone/src/device/mock.rs | 24 ++- standalone/src/device/mod.rs | 145 +++++++++++++- standalone/src/player.rs | 2 +- standalone/src/server.rs | 203 ++++++++++++++++++- ui/app.js | 71 ++++++- ui/index.html | 24 +++ ui/style.css | 11 ++ 18 files changed, 1326 insertions(+), 70 deletions(-) create mode 100644 browser/spoofer/mirrors.py create mode 100644 browser/tests/test_mirrors.py create mode 100644 docs/testing/multiple-iphones-and-wifi.md create mode 100644 standalone/src/device/mirror.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c4a27e..d75d2fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ Test builds from the `dev` branch are marked as pre-releases. ## Unreleased (dev) +### Experimental (`feature-testing` only; see [docs/testing/multiple-iphones-and-wifi.md](docs/testing/multiple-iphones-and-wifi.md)) +- Several iPhones at once: phones added under *Device › More iPhones* follow the main one (teleports, routes, GPX, joystick, Stop spoofing). Each gets positions from its own queue, so a slow or lost phone never holds up the others; a lost phone is marked until removed, and removing one sends it back to its real location. The Simulator has a second phone to try it. +- Wi-Fi connections: *Device tools › Connect over* (Automatic, USB cable only, Wi-Fi only) and *Allow Wi-Fi connection*, which turns on the phone's "Show this iPhone when on Wi-Fi" setting. The device list shows how each phone can be reached (USB, Wi-Fi, or both). In the browser version, a second iOS 17+ phone or an iOS 17+ phone over Wi-Fi needs the tunnel helper. Bluetooth isn't possible. + ### New - A real dark map: the default map is now OpenFreeMap, drawn from vector data, so it is sharp at every zoom and has a true dark style (with colours tuned so water, parks, the road hierarchy and labels stand out) and a light style. Free, no account or key. Choose the map in *Settings › Appearance › Map* (OpenFreeMap, OpenStreetMap, Topographic, Satellite) or with the map's layer button; the choice is remembered. Without WebGL, or if OpenFreeMap can't be reached, the app says so and shows OpenStreetMap. - The tutorial has an animated drawing for each step (the route being drawn, the cable and Trust prompt, the Developer Mode switch, a position moving along a route), and each step slides in. diff --git a/browser/spoofer/device/base.py b/browser/spoofer/device/base.py index 88d03e9..9fea12b 100644 --- a/browser/spoofer/device/base.py +++ b/browser/spoofer/device/base.py @@ -17,7 +17,7 @@ class DeviceInfo: name: str = "iPhone" ios_version: str = "" product_type: str = "" - connection: str = "" # USB / Network / Simulated + connection: str = "" # USB / Wi-Fi / Simulated transport: str = "" # how location commands reach it (DVT tunnel, lockdown, CLI, ...) notes: list[str] = field(default_factory=list) @@ -44,7 +44,8 @@ def connected(self) -> bool: async def list_devices(self) -> list[dict]: ... @abstractmethod - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: ... + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + """`connection`: "auto" (USB when the phone is plugged in, else Wi-Fi), "usb" or "network".""" @abstractmethod async def disconnect(self) -> None: ... @@ -61,6 +62,10 @@ async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: async def mount_developer_image(self) -> str: raise DeviceError("Not supported by this connection method") + async def enable_wifi(self, udid: Optional[str] = None) -> str: + """Let the phone be reached over Wi-Fi from now on (needs it plugged in once).""" + raise DeviceError("Not supported by this connection method") + # Only used by non-live drivers async def play_gpx(self, path: str) -> None: raise DeviceError("Not supported by this connection method") diff --git a/browser/spoofer/device/cli.py b/browser/spoofer/device/cli.py index 1985e46..4887b46 100644 --- a/browser/spoofer/device/cli.py +++ b/browser/spoofer/device/cli.py @@ -169,7 +169,7 @@ async def list_devices(self) -> list[dict]: if isinstance(d, dict) ] - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: devices = await self.list_devices() if not devices: raise DeviceError("No iPhone found. Plug it in, unlock it, tap Trust and keep the Apple Devices app open.") diff --git a/browser/spoofer/device/mock.py b/browser/spoofer/device/mock.py index 299b7af..252ca60 100644 --- a/browser/spoofer/device/mock.py +++ b/browser/spoofer/device/mock.py @@ -4,11 +4,13 @@ from typing import Optional -from .base import DeviceDriver, DeviceInfo +from .base import DeviceDriver, DeviceError, DeviceInfo -# The pretend phone always reports this iOS version (the current major release). +# The pretend phones always report this iOS version (the current major release). SIMULATED_IOS = "27" +# Two pretend phones, so several iPhones at once can be tried without hardware. +SIMULATED_DEVICES = {"SIMULATED-0001": "Simulated iPhone", "SIMULATED-0002": "Simulated iPhone 2"} class MockDriver(DeviceDriver): @@ -22,12 +24,16 @@ def __init__(self) -> None: self.history: list[tuple[float, float]] = [] async def list_devices(self) -> list[dict]: - return [{"udid": "SIMULATED-0001", "name": "Simulated iPhone", "ios_version": SIMULATED_IOS, "connection": "Simulated"}] + return [{"udid": udid, "name": name, "ios_version": SIMULATED_IOS, "connection": "Simulated", "connections": ["Simulated"]} + for udid, name in SIMULATED_DEVICES.items()] - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + udid = udid or next(iter(SIMULATED_DEVICES)) + if udid not in SIMULATED_DEVICES: + raise DeviceError("No such simulated iPhone") self.info = DeviceInfo( - udid="SIMULATED-0001", - name="Simulated iPhone", + udid=udid, + name=SIMULATED_DEVICES[udid], ios_version=SIMULATED_IOS, product_type="Simulated", connection="Simulated", @@ -52,3 +58,6 @@ async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: async def mount_developer_image(self) -> str: return "Simulator: nothing to mount." + + async def enable_wifi(self, udid: Optional[str] = None) -> str: + return "Simulator: nothing to do." diff --git a/browser/spoofer/device/pmd3.py b/browser/spoofer/device/pmd3.py index 5272a7b..94e22db 100644 --- a/browser/spoofer/device/pmd3.py +++ b/browser/spoofer/device/pmd3.py @@ -45,6 +45,18 @@ def _friendly(e: BaseException) -> str: return hints.get(name, f"{name}: {msg}") +# The app's connection choice -> usbmuxd's connection type (None: USB when plugged in, else Wi-Fi) +CONNECTION_TYPES = {"auto": None, "usb": "USB", "network": "Network"} +WIFI_HELP = ( + "This iPhone can't be reached over Wi-Fi. Plug it in once, press Device tools > Allow Wi-Fi connection, " + "then keep it unlocked and on the same network as this computer." +) + + +def _conn_label(connection_type: Optional[str]) -> str: + return {"USB": "USB", "Network": "Wi-Fi"}.get(connection_type or "", connection_type or "") + + class Pmd3Driver(DeviceDriver): key = "pmd3" label = "Direct (pymobiledevice3 API)" @@ -66,13 +78,20 @@ async def list_devices(self) -> list[dict]: devices = await usbmux.list_devices() except Exception as e: raise DeviceError(_friendly(e)) from e + # A phone that is plugged in and on Wi-Fi is listed twice by usbmuxd: show it once, with both ways. + ways: dict[str, list[str]] = {} + for d in devices: + label = _conn_label(d.connection_type) + if label not in ways.setdefault(d.serial, []): + ways[d.serial].append(label) out = [] seen = set() - for d in devices: + for d in sorted(devices, key=lambda d: not d.is_usb): if d.serial in seen: continue seen.add(d.serial) - entry = {"udid": d.serial, "connection": d.connection_type, "name": "", "ios_version": ""} + conns = sorted(ways[d.serial], key=lambda c: c != "USB") + entry = {"udid": d.serial, "connection": " + ".join(conns), "connections": conns, "name": "", "ios_version": ""} try: ld = await create_using_usbmux(serial=d.serial, autopair=False) try: @@ -86,7 +105,7 @@ async def list_devices(self) -> list[dict]: out.append(entry) return out - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: await self.disconnect() try: from pymobiledevice3.lockdown import create_using_usbmux @@ -96,20 +115,27 @@ async def connect(self, udid: Optional[str] = None) -> DeviceInfo: stack = AsyncExitStack() notes: list[str] = [] try: - lockdown = await create_using_usbmux(serial=udid, autopair=True) + try: + lockdown = await create_using_usbmux(serial=udid, autopair=True, connection_type=CONNECTION_TYPES.get(connection)) + except Exception as e: + if connection == "network" and e.__class__.__name__ in ("NoDeviceConnectedError", "DeviceNotFoundError", "ConnectionFailedError"): + raise DeviceError(WIFI_HELP) from e + raise stack.push_async_callback(lockdown.close) short = lockdown.short_info version = lockdown.product_version + mux = getattr(getattr(lockdown, "service", None), "mux_device", None) + over = _conn_label(getattr(mux, "connection_type", None)) or "USB" info = DeviceInfo( udid=lockdown.udid, name=short.get("DeviceName", "iPhone"), ios_version=version, product_type=short.get("ProductType", ""), - connection="USB", + connection=over, ) if _major(version) >= 17: serial = udid or getattr(lockdown, "identifier", None) or lockdown.udid - rsd, how = await self._open_rsd(stack, serial, lockdown.udid) + rsd, how = await self._open_rsd(stack, serial, lockdown.udid, wifi=over == "Wi-Fi") notes.append(await self._try_mount(rsd)) from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider from pymobiledevice3.services.dvt.instruments.location_simulation import LocationSimulation @@ -135,25 +161,38 @@ async def connect(self, udid: Optional[str] = None) -> DeviceInfo: self.info = info return info - async def _open_rsd(self, stack: AsyncExitStack, serial: str, udid: str): - from pymobiledevice3.exceptions import UserspaceTunnelUnavailableError + async def _open_rsd(self, stack: AsyncExitStack, serial: str, udid: str, wifi: bool = False): + from pymobiledevice3.exceptions import PyMobileDevice3Exception, UserspaceTunnelUnavailableError from pymobiledevice3.remote.userspace_tunnel import UserspaceRsdTunnel - try: - tunnel = UserspaceRsdTunnel(serial=serial, remotepairing_fallback=False) - rsd = await tunnel.aopen() - stack.push_async_callback(tunnel.aclose) - return rsd, "userspace tunnel (no admin)" - except UserspaceTunnelUnavailableError: - log.info("userspace tunnel unavailable (iOS 17.0-17.3?), trying tunneld") - # iOS 17.0-17.3: a privileged tunneld must already be running. + why = "This iOS version needs tunneld." + if wifi: + # The no-admin tunnel always picks the cable when there is one, so a Wi-Fi connection + # goes through tunneld, which reaches phones over the network. + why = "An iOS 17+ iPhone over Wi-Fi needs tunneld in the browser version (the standalone app doesn't)." + else: + try: + tunnel = UserspaceRsdTunnel(serial=serial, remotepairing_fallback=False) + rsd = await tunnel.aopen() + stack.push_async_callback(tunnel.aclose) + return rsd, "userspace tunnel (no admin)" + except UserspaceTunnelUnavailableError: + log.info("userspace tunnel unavailable (iOS 17.0-17.3?), trying tunneld") + except PyMobileDevice3Exception as e: + # pymobiledevice3 runs one no-admin tunnel per process: a second iOS 17+ iPhone + # (a mirror) has to use tunneld. + if "already active" not in str(e): + raise + log.info("a userspace tunnel is already open (another iPhone), trying tunneld") + why = "A second iOS 17+ iPhone needs tunneld in the browser version (the standalone app doesn't)." + # iOS 17.0-17.3, Wi-Fi, or a second phone: a privileged tunneld must already be running. from pymobiledevice3.tunneld.api import get_tunneld_devices try: rsds = await get_tunneld_devices() except Exception as e: raise DeviceError( - "This iOS version needs tunneld. Use Device tools > Start tunnel helper (admin), keep its window open, then connect again." + f"{why} Use Device tools > Start tunnel helper (admin), keep its window open, then connect again." ) from e match = None for r in rsds: @@ -229,5 +268,21 @@ async def mount_developer_image(self) -> str: if not self.connected: raise DeviceError("Connect first") # Reconnecting runs the mount step with the right provider (RSD on iOS 17+). - info = await self.connect(self.info.udid if self.info else None) + conn = "network" if self.info and self.info.connection == "Wi-Fi" else "auto" + info = await self.connect(self.info.udid if self.info else None, conn) return " ".join(info.notes) or "Developer Disk Image is mounted." + + async def enable_wifi(self, udid: Optional[str] = None) -> str: + """Turns on the phone's "Show this iPhone when on Wi-Fi" setting (Wi-Fi sync), over the cable.""" + try: + from pymobiledevice3.lockdown import create_using_usbmux + + ld = await create_using_usbmux(serial=udid or (self.info.udid if self.info else None), autopair=True, connection_type="USB") + try: + await ld.set_enable_wifi_connections(True) + finally: + await ld.close() + except Exception as e: + raise DeviceError(f"Plug the iPhone in with a cable for this step. ({_friendly(e)})") from e + return ("Wi-Fi connections are on for this iPhone. Choose Wi-Fi in Device tools > Connect over, keep the phone " + "unlocked on the same network, and connect.") diff --git a/browser/spoofer/mirrors.py b/browser/spoofer/mirrors.py new file mode 100644 index 0000000..3324605 --- /dev/null +++ b/browser/spoofer/mirrors.py @@ -0,0 +1,146 @@ +"""More than one iPhone at a time: extra phones ("mirrors") follow the main one. + +The player only ever talks to the main phone (through FanOut). Every position it sends is also +handed to each mirror, which sends it from its own task: a slow or lost mirror never holds up +playback on the main phone. A mirror that is behind skips straight to the newest position, and a +mirror that stops answering is marked as lost (the others keep going) until it is removed. +""" + +from __future__ import annotations + +import asyncio +import contextlib +from typing import Callable, Optional + +from .device.base import DeviceDriver, DeviceError, DeviceInfo + +SEND_TIMEOUT_S = 20.0 + + +class MirrorLink: + def __init__(self, driver: DeviceDriver) -> None: + self.driver = driver + self.info: Optional[DeviceInfo] = driver.info + self.error: Optional[str] = None + self.sent = 0 + self._busy = False + self._pending: Optional[tuple] = None # ("set", lat, lon) or ("clear",): only the newest counts + self._wake = asyncio.Event() + self._task = asyncio.create_task(self._run()) + + @property + def lost(self) -> bool: + return self.error is not None + + def push_set(self, lat: float, lon: float) -> None: + if not self.lost: + self._pending = ("set", lat, lon) + self._wake.set() + + def push_clear(self) -> None: + if not self.lost: + self._pending = ("clear",) + self._wake.set() + + async def settle(self, timeout: float = 5.0) -> None: + """Wait until the newest position has been sent (tests, and before removing a mirror).""" + end = asyncio.get_running_loop().time() + timeout + while (self._pending is not None or self._wake.is_set() or self._busy) and not self.lost: + if asyncio.get_running_loop().time() > end: + return + await asyncio.sleep(0.01) + await asyncio.sleep(0) + + async def _run(self) -> None: + while True: + await self._wake.wait() + self._wake.clear() + cmd, self._pending = self._pending, None + if cmd is None: + continue + self._busy = True + try: + if cmd[0] == "set": + await asyncio.wait_for(self.driver.set_location(cmd[1], cmd[2]), SEND_TIMEOUT_S) + else: + await asyncio.wait_for(self.driver.clear_location(), SEND_TIMEOUT_S) + self.sent += 1 + except asyncio.CancelledError: + raise + except asyncio.TimeoutError: + self.error = "The iPhone stopped answering." + return + except Exception as e: # DeviceError or a transport failure: this mirror is lost + self.error = str(e) or e.__class__.__name__ + return + finally: + self._busy = False + + async def close(self, clear: bool) -> None: + """Stop following; with `clear`, the phone goes back to its real location first.""" + if clear and not self.lost: + await self.settle(2.0) + self._task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await self._task + if clear and not self.lost: + with contextlib.suppress(Exception): + await asyncio.wait_for(self.driver.clear_location(), 10) + with contextlib.suppress(Exception): + await self.driver.disconnect() + + def to_dict(self) -> dict: + d = self.info.to_dict() if self.info else {} + d.update({"state": "lost" if self.lost else "ok", "error": self.error}) + return d + + +class FanOut(DeviceDriver): + """What the player talks to: the main device, plus every mirror (without waiting for them).""" + + key = "fanout" + label = "Main device and mirrors" + + def __init__(self, primary: Callable[[], DeviceDriver], mirrors: Callable[[], list[MirrorLink]]) -> None: + # (no super().__init__(): `info` is the main device's, read through the property below) + self._primary = primary + self._mirrors = mirrors + + @property + def info(self) -> Optional[DeviceInfo]: # type: ignore[override] + return self._primary().info + + @property + def live(self) -> bool: # type: ignore[override] + return self._primary().live + + async def list_devices(self) -> list[dict]: + return await self._primary().list_devices() + + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + raise DeviceError("Connect through the server") + + async def disconnect(self) -> None: + await self._primary().disconnect() + + async def set_location(self, lat: float, lon: float) -> None: + await self._primary().set_location(lat, lon) + for m in self._mirrors(): + m.push_set(lat, lon) + + async def clear_location(self) -> None: + await self._primary().clear_location() + for m in self._mirrors(): + m.push_clear() + + async def play_gpx(self, path: str) -> None: + await self._primary().play_gpx(path) + + async def stop_gpx(self) -> None: + await self._primary().stop_gpx() + + async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: + return await self._primary().reveal_developer_mode(udid) + + async def mount_developer_image(self) -> str: + return await self._primary().mount_developer_image() diff --git a/browser/spoofer/server.py b/browser/spoofer/server.py index ace3b86..9b5ef8c 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -22,6 +22,7 @@ from .device.mock import MockDriver from .device.pmd3 import Pmd3Driver from .gpx_io import parse_gpx, safe_filename, write_gpx +from .mirrors import FanOut, MirrorLink from .player import Player from .profile import ( Leg, @@ -54,7 +55,10 @@ class AppState: def __init__(self) -> None: self.drivers: dict[str, DeviceDriver] = {d.key: d for d in (Pmd3Driver(), CliDriver(), MockDriver())} self.driver_key = "pmd3" - self.player = Player(lambda: self.driver) + # extra iPhones that follow the main one, by UDID (see mirrors.py) + self.mirrors: dict[str, MirrorLink] = {} + self.fanout = FanOut(lambda: self.driver, lambda: list(self.mirrors.values())) + self.player = Player(lambda: self.fanout) self.timelines: "OrderedDict[str, tuple[Timeline, str, list, bool]]" = OrderedDict() self.store = Store() self.updater = Updater() # replaced by __main__ with the real one; disabled from source @@ -63,6 +67,17 @@ def __init__(self) -> None: def driver(self) -> DeviceDriver: return self.drivers[self.driver_key] + async def drop_mirror(self, udid: str, clear: bool = False) -> bool: + link = self.mirrors.pop(udid, None) + if link is None: + return False + await link.close(clear) + return True + + async def drop_mirrors(self, clear: bool = False) -> None: + for udid in list(self.mirrors): + await self.drop_mirror(udid, clear) + def keep_timeline(self, tl: Timeline, name: str, waypoints: list, exportable: bool = True) -> str: tid = uuid.uuid4().hex[:12] self.timelines[tid] = (tl, name, waypoints, exportable) @@ -90,6 +105,7 @@ async def lifespan(app: FastAPI): upd_task.cancel() try: await app.state.s.player.stop() + await app.state.s.drop_mirrors() for d in app.state.s.drivers.values(): await d.disconnect() finally: @@ -153,6 +169,19 @@ class TextIn(BaseModel): class ConnectIn(BaseModel): driver: Literal["pmd3", "cli", "mock"] = "pmd3" udid: Optional[str] = None + connection: Literal["auto", "usb", "network"] = "auto" + + +class MirrorIn(BaseModel): + udid: str + connection: Literal["auto", "usb", "network"] = "auto" + + +class UdidIn(BaseModel): + udid: Optional[str] = None + + +MAX_MIRRORS = 8 class WaypointIn(BaseModel): @@ -265,13 +294,14 @@ async def status(): return { "version": __version__, "app": "browser", - "features": {"cli_driver": True, "tunnel_helper": True}, + "features": {"cli_driver": True, "tunnel_helper": True, "multi_device": True, "wifi": True}, "driver": s.driver_key, "drivers": [{"key": k, "label": v.label, "live": v.live} for k, v in s.drivers.items()], "device": d.info.to_dict() if d.info else None, "live": d.live, "player": s.player.status(), "update": s.updater.status(), + "mirrors": [m.to_dict() for m in s.mirrors.values()], } @@ -285,9 +315,13 @@ async def connect(body: ConnectIn): s = S() await s.player.stop() if body.driver != s.driver_key: + await s.drop_mirrors() await s.driver.disconnect() s.driver_key = body.driver - info = await s.driver.connect(body.udid or None) + if body.udid: + await s.drop_mirror(body.udid) # it becomes the main phone instead + info = await s.driver.connect(body.udid or None, body.connection) + await s.drop_mirror(info.udid) return {"device": info.to_dict()} @@ -295,10 +329,55 @@ async def connect(body: ConnectIn): async def disconnect(): s = S() await s.player.stop() + await s.drop_mirrors() await s.driver.disconnect() return {"ok": True} +@app.post("/api/mirrors") +async def mirror_add(body: MirrorIn): + """Another iPhone follows the main one: same position, same route, from now on.""" + s = S() + main = s.driver + if not main.connected or main.info is None: + raise DeviceError("Connect the main iPhone first.") + if not main.live: + raise DeviceError("Several iPhones at once need the Direct connection (or the Simulator).") + if body.udid == main.info.udid: + raise DeviceError("That is the main iPhone already.") + if body.udid in s.mirrors: + raise DeviceError("That iPhone already follows the main one.") + if len(s.mirrors) >= MAX_MIRRORS: + raise DeviceError(f"Up to {MAX_MIRRORS} extra iPhones can follow the main one.") + drv = type(main)() + info = await drv.connect(body.udid, body.connection) + if info.udid == main.info.udid or info.udid in s.mirrors: + await drv.disconnect() + raise DeviceError("That iPhone is connected already.") + link = MirrorLink(drv) + s.mirrors[info.udid] = link + pos = s.player.position + if pos is not None: + link.push_set(pos.lat, pos.lon) # catch up with the main phone straight away + return {"mirror": link.to_dict(), "mirrors": [m.to_dict() for m in s.mirrors.values()]} + + +@app.delete("/api/mirrors/{udid}") +async def mirror_remove(udid: str, clear: bool = True): + """Stop following; by default the phone goes back to its real location.""" + s = S() + if not await s.drop_mirror(udid, clear): + raise HTTPException(404, "That iPhone doesn't follow the main one.") + return {"mirrors": [m.to_dict() for m in s.mirrors.values()]} + + +@app.post("/api/device/wifi") +async def enable_wifi(body: UdidIn): + s = S() + udid = body.udid or (s.driver.info.udid if s.driver.info else None) + return {"message": await s.driver.enable_wifi(udid)} + + @app.post("/api/device/reveal-developer-mode") async def reveal_dev_mode(): return {"message": await S().driver.reveal_developer_mode()} diff --git a/browser/tests/test_mirrors.py b/browser/tests/test_mirrors.py new file mode 100644 index 0000000..46586e3 --- /dev/null +++ b/browser/tests/test_mirrors.py @@ -0,0 +1,229 @@ +"""Several iPhones at once (extra phones follow the main one) and the USB / Wi-Fi connection choice.""" + +import asyncio +import time + +import pytest +from fastapi.testclient import TestClient + +from spoofer import geo +from spoofer.device import pmd3 +from spoofer.device.base import DeviceError + +A = (51.5, -0.12) +B = geo.destination(A, 90, 300) +MAIN, SECOND = "SIMULATED-0001", "SIMULATED-0002" + + +@pytest.fixture() +def client(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + yield c + + +def _state(): + from spoofer import server + + return server.app.state.s + + +def _until(pred, timeout=5.0): + end = time.monotonic() + timeout + while time.monotonic() < end: + if pred(): + return True + time.sleep(0.02) + return False + + +def _connect_two(client): + assert client.post("/api/connect", json={"driver": "mock", "udid": MAIN}).status_code == 200 + r = client.post("/api/mirrors", json={"udid": SECOND}) + assert r.status_code == 200, r.text + return r.json() + + +def test_two_simulated_phones_and_status(client): + devices = client.get("/api/devices?driver=mock").json()["devices"] + assert [d["udid"] for d in devices] == [MAIN, SECOND] + data = _connect_two(client) + assert data["mirror"]["name"] == "Simulated iPhone 2" and data["mirror"]["state"] == "ok" + st = client.get("/api/status").json() + assert st["device"]["udid"] == MAIN + assert [m["udid"] for m in st["mirrors"]] == [SECOND] + assert st["features"]["multi_device"] and st["features"]["wifi"] + + +def test_mirror_follows_teleport_route_and_stop(client): + _connect_two(client) + s = _state() + main, mirror = s.driver, s.mirrors[SECOND].driver + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert _until(lambda: mirror.location == main.location == pytest.approx(A, abs=1e-5)) + body = {"name": "Two", "waypoints": [{"lat": A[0], "lon": A[1]}, {"lat": B[0], "lon": B[1]}], + "legs": [{"mode": "straight", "cruise_kmh": 36}], + "settings": {"default_cruise_kmh": 36, "accel_ms2": 2, "decel_ms2": 2}} + tid = client.post("/api/route/build", json=body).json()["id"] + client.post(f"/api/player/load/{tid}", json={}) + assert client.post("/api/player-options", json={"multiplier": 10, "tick_s": 0.2}).status_code == 200 + client.post("/api/player/play", json={}) + assert _until(lambda: client.get("/api/status").json()["player"]["state"] == "finished", 20) + assert _until(lambda: mirror.location is not None and geo.haversine_m(mirror.location, B) < 1.0) + assert geo.haversine_m(main.location, B) < 1.0 + assert len(mirror.history) > 5 # it moved along the route, not just to the end + assert len(mirror.history) >= 0.8 * len(main.history) + # Stop spoofing clears every phone + client.post("/api/location/clear", json={}) + assert _until(lambda: mirror.location is None and main.location is None) + + +def test_a_slow_mirror_never_holds_up_the_main_phone(client): + _connect_two(client) + s = _state() + mirror = s.mirrors[SECOND].driver + real_set = mirror.set_location + + async def slow(lat, lon): + await asyncio.sleep(0.4) + await real_set(lat, lon) + + mirror.set_location = slow + t0 = time.monotonic() + for i in range(6): + client.post("/api/location/set", json={"lat": A[0] + i * 1e-4, "lon": A[1]}) + assert time.monotonic() - t0 < 1.5 # six sends to a 0.4 s phone would take 2.4 s if waited for + assert s.driver.location == pytest.approx((A[0] + 5e-4, A[1]), abs=1e-7) + # the mirror skips the positions it fell behind on and ends where the main phone is + assert _until(lambda: mirror.location == pytest.approx((A[0] + 5e-4, A[1]), abs=1e-7)) + assert s.mirrors[SECOND].sent < 6 + + +def test_a_lost_mirror_is_marked_and_the_rest_keeps_going(client): + _connect_two(client) + s = _state() + + async def broken(lat, lon): + raise DeviceError("Lost the connection to the iPhone") + + s.mirrors[SECOND].driver.set_location = broken + assert client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}).status_code == 200 + assert _until(lambda: client.get("/api/status").json()["mirrors"][0]["state"] == "lost") + m = client.get("/api/status").json()["mirrors"][0] + assert "Lost the connection" in m["error"] + assert client.post("/api/location/set", json={"lat": B[0], "lon": B[1]}).status_code == 200 + assert s.driver.location == pytest.approx(B, abs=1e-7) + assert client.delete(f"/api/mirrors/{SECOND}").json()["mirrors"] == [] + + +def test_removing_a_mirror_sends_it_back_to_its_real_location(client): + _connect_two(client) + s = _state() + mirror = s.mirrors[SECOND].driver + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert _until(lambda: mirror.location is not None) + assert client.delete(f"/api/mirrors/{SECOND}").status_code == 200 + assert mirror.location is None and mirror.info is None + assert s.driver.location == pytest.approx(A, abs=1e-7) # the main phone keeps its position + assert client.delete(f"/api/mirrors/{SECOND}").status_code == 404 + + +def test_new_mirror_catches_up_and_rules(client): + assert client.post("/api/mirrors", json={"udid": SECOND}).status_code == 409 # no main phone yet + client.post("/api/connect", json={"driver": "mock", "udid": MAIN}) + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert client.post("/api/mirrors", json={"udid": MAIN}).status_code == 409 # that's the main phone + assert client.post("/api/mirrors", json={"udid": SECOND, "connection": "usb"}).status_code == 200 + s = _state() + assert _until(lambda: s.mirrors[SECOND].driver.location == pytest.approx(A, abs=1e-7)) # caught up at once + assert client.post("/api/mirrors", json={"udid": SECOND}).status_code == 409 # already following + assert client.post("/api/mirrors", json={"udid": "SIMULATED-9999"}).status_code == 409 + assert client.post("/api/mirrors", json={"udid": SECOND, "connection": "bluetooth"}).status_code == 422 + # connecting the main phone to the mirrored one makes it the main phone instead + client.post("/api/connect", json={"driver": "mock", "udid": SECOND}) + st = client.get("/api/status").json() + assert st["device"]["udid"] == SECOND and st["mirrors"] == [] + # disconnecting ends the mirrors too + client.post("/api/mirrors", json={"udid": MAIN}) + client.post("/api/disconnect", json={}) + assert client.get("/api/status").json()["mirrors"] == [] + + +def test_wifi_tool_and_connection_field(client): + assert client.post("/api/connect", json={"driver": "mock", "connection": "network"}).status_code == 200 + assert client.post("/api/device/wifi", json={}).json()["message"].startswith("Simulator") + assert client.post("/api/connect", json={"driver": "mock", "connection": "carrier-pigeon"}).status_code == 422 + + +# ---------------------------------------------------------------- pymobiledevice3 driver, faked usbmux +class _Mux: + def __init__(self, serial, ct): + self.serial, self.connection_type = serial, ct + + @property + def is_usb(self): + return self.connection_type == "USB" + + +class _Lockdown: + def __init__(self, ct): + self.short_info = {"DeviceName": "Test phone", "ProductVersion": "16.7", "ProductType": "iPhone10,1"} + self.product_version = "16.7" + self.udid = "00008030-TEST" + self.service = type("S", (), {"mux_device": _Mux("00008030-TEST", ct)})() + + async def close(self): + pass + + +def test_pmd3_lists_a_phone_once_with_both_connections(monkeypatch): + from pymobiledevice3 import lockdown, usbmux + + async def fake_list(usbmux_address=None): + return [_Mux("00008030-TEST", "Network"), _Mux("00008030-TEST", "USB"), _Mux("OTHER", "Network")] + + async def fake_lockdown(serial=None, autopair=True, connection_type=None, **kw): + return _Lockdown(connection_type or "USB") + + monkeypatch.setattr(usbmux, "list_devices", fake_list) + monkeypatch.setattr(lockdown, "create_using_usbmux", fake_lockdown) + out = asyncio.run(pmd3.Pmd3Driver().list_devices()) + assert [(d["udid"], d["connection"], d["connections"]) for d in out] == [ + ("00008030-TEST", "USB + Wi-Fi", ["USB", "Wi-Fi"]), ("OTHER", "Wi-Fi", ["Wi-Fi"])] + + +def test_pmd3_connects_over_the_chosen_connection(monkeypatch): + from pymobiledevice3 import lockdown + + asked = [] + + class NoDeviceConnectedError(Exception): + pass + + async def fake_lockdown(serial=None, autopair=True, connection_type=None, **kw): + asked.append(connection_type) + if connection_type == "Network" and serial == "OFFLINE": + raise NoDeviceConnectedError() + return _Lockdown(connection_type or "USB") + + monkeypatch.setattr(lockdown, "create_using_usbmux", fake_lockdown) + drv = pmd3.Pmd3Driver() + + async def no_mount(provider): + return "" + + monkeypatch.setattr(drv, "_try_mount", no_mount) + info = asyncio.run(drv.connect("00008030-TEST", "network")) + assert info.connection == "Wi-Fi" and asked[-1] == "Network" + assert info.transport == "Lockdown simulatelocation" + info = asyncio.run(drv.connect("00008030-TEST", "auto")) + assert info.connection == "USB" and asked[-1] is None + asyncio.run(drv.connect("00008030-TEST", "usb")) + assert asked[-1] == "USB" + with pytest.raises(DeviceError, match="Allow Wi-Fi connection"): + asyncio.run(drv.connect("OFFLINE", "network")) diff --git a/docs/testing/multiple-iphones-and-wifi.md b/docs/testing/multiple-iphones-and-wifi.md new file mode 100644 index 0000000..f3d94c0 --- /dev/null +++ b/docs/testing/multiple-iphones-and-wifi.md @@ -0,0 +1,31 @@ +# Testing several iPhones at once and Wi-Fi connections + +These features are on the `feature-testing` branch only. Run that branch from source (see [CONTRIBUTING.md](../../CONTRIBUTING.md#trying-the-feature-testing-branch)), ideally with an empty data folder (`SPOOFER_DATA_DIR`). + +## What they do + +- **More iPhones** (Device section, after connecting): every iPhone added there follows the main one. Teleports, routes, GPX tracks, the joystick and *Stop spoofing* reach all of them. Each extra phone gets positions from its own queue, so a slow phone or one that drops out never holds up the main phone or the others. A phone that stops answering is marked in red until you remove it. *Remove* sends it back to its real location. Up to 8 extra phones. +- **Connect over** (Device tools): *Automatic* uses the cable when the phone is plugged in and Wi-Fi otherwise. *USB cable only* and *Wi-Fi only* force one of them. The choice also applies to phones added under More iPhones. +- **Allow Wi-Fi connection** (Device tools): turns on the phone's "Show this iPhone when on Wi-Fi" setting over the cable, so it can be reached without the cable afterwards. + +## Without an iPhone + +1. Choose *Simulator (no iPhone)* as the Connection and press **Connect**. The Simulator now has two phones. +2. Under **More iPhones**, *Simulated iPhone 2* appears. Press **Add**. +3. Teleport, play a route or use the joystick. The status shows both phones; nothing is sent to real hardware. +4. Press **Remove**, then **Stop spoofing**. + +## With real iPhones + +1. Connect the first iPhone as usual (cable, unlocked, trusted, Developer Mode on). +2. Plug in the second iPhone, unlock it and trust the computer. Press the refresh button next to *Device*. +3. Under **More iPhones**, pick it and press **Add**. iOS 17+ can take up to 30 s. +4. Teleport and play a short route. Check that both phones follow. Unplug one phone while a route plays: the other must keep going, and the unplugged one must turn red. +5. Wi-Fi: with the phone plugged in, press **Allow Wi-Fi connection**. Then set **Connect over** to *Wi-Fi only*, unplug the phone, keep it unlocked on the same network, and connect. + +## Known limits + +- **Browser version, iOS 17+:** pymobiledevice3 allows only one no-admin tunnel per app. A second iOS 17+ phone, and any iOS 17+ phone over Wi-Fi, therefore needs the tunnel helper: *Device tools › Start tunnel helper (admin)*. The standalone app has no such limit, because it opens one tunnel per phone itself. +- **Wi-Fi with iOS 17+:** whether Apple's developer tunnel accepts a Wi-Fi connection depends on the iOS version and on how the phone was paired. This hasn't been verified on hardware yet; the error message says what failed. +- **Wi-Fi needs Apple's device service to see the phone on the network.** On Windows that is the Apple Devices app or iTunes, and the computer and phone must be on the same network (no client isolation). +- **Bluetooth isn't possible.** iPhones only offer the location-simulation service over a cable or the network (usbmuxd and lockdown). No Apple protocol carries it over Bluetooth. diff --git a/standalone/src/device/idev.rs b/standalone/src/device/idev.rs index 8115bdc..c64ec5c 100644 --- a/standalone/src/device/idev.rs +++ b/standalone/src/device/idev.rs @@ -63,18 +63,40 @@ async fn usbmux() -> Result { addr().connect(1).await.map_err(|e| friendly(&e)) } -async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), String> { +pub const WIFI_HELP: &str = "This iPhone can't be reached over Wi-Fi. Plug it in once, press Device tools › Allow Wi-Fi \ + connection, then keep it unlocked and on the same network as this computer."; + +fn is_usb(c: &Connection) -> bool { + matches!(c, Connection::Usb) +} + +fn conn_label(c: &Connection) -> &'static str { + match c { + Connection::Usb => "USB", + Connection::Network(_) => "Wi-Fi", + Connection::Unknown(_) => "Other", + } +} + +/// The phone to talk to, over the chosen connection: `Auto` takes the cable when the phone is +/// plugged in, else Wi-Fi. usbmuxd lists a phone that is both plugged in and on Wi-Fi twice. +async fn find_device(udid: Option<&str>, via: super::Via) -> Result<(UsbmuxdProvider, String), String> { + use super::Via; let mut mux = usbmux().await?; let devices = mux.get_devices().await.map_err(|e| friendly(&e))?; - let dev = match udid { - Some(u) if !u.is_empty() => devices.into_iter().find(|d| d.udid == u), - _ => devices - .iter() - .find(|d| matches!(d.connection_type, Connection::Usb)) - .cloned() - .or_else(|| devices.into_iter().next()), - } - .ok_or("No iPhone found. Plug it in with a cable, unlock it and tap Trust.")?; + let wanted = |d: &&idevice::usbmuxd::UsbmuxdDevice| { + udid.is_none_or(|u| u.is_empty() || d.udid == u) + && match via { + Via::Auto => true, + Via::Usb => is_usb(&d.connection_type), + Via::Network => matches!(d.connection_type, Connection::Network(_)), + } + }; + let dev = devices.iter().filter(wanted).find(|d| is_usb(&d.connection_type)).or_else(|| devices.iter().find(wanted)).cloned(); + let dev = dev.ok_or(match via { + super::Via::Network => WIFI_HELP, + _ => "No iPhone found. Plug it in with a cable, unlock it and tap Trust.", + })?; let conn = match &dev.connection_type { Connection::Usb => "USB".to_string(), Connection::Network(ip) => format!("Wi-Fi ({ip})"), @@ -85,12 +107,25 @@ async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), St pub async fn list_devices() -> Result, String> { let mut mux = usbmux().await?; - let devices = mux.get_devices().await.map_err(|e| friendly(&e))?; + let mut devices = mux.get_devices().await.map_err(|e| friendly(&e))?; + // one entry per phone (the cable first), naming every way it can be reached + devices.sort_by_key(|d| !is_usb(&d.connection_type)); let mut out = Vec::new(); - for d in devices { + let mut seen = std::collections::HashSet::new(); + for d in devices.iter() { + if !seen.insert(d.udid.clone()) { + continue; + } + let mut conns: Vec<&str> = Vec::new(); + for o in devices.iter().filter(|o| o.udid == d.udid) { + let l = conn_label(&o.connection_type); + if !conns.contains(&l) { + conns.push(l); + } + } let provider = d.to_provider(addr(), LABEL); let mut entry = serde_json::json!({"udid": d.udid, "name": "", "ios_version": "", - "connection": if matches!(d.connection_type, Connection::Usb) { "USB" } else { "Network" }}); + "connection": conns.join(" + "), "connections": conns}); match LockdownClient::connect(&provider).await { Ok(mut ld) => { if let Ok(v) = ld.get_value(Some("ProductVersion"), None).await { @@ -191,9 +226,9 @@ async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result { + pub async fn connect(&mut self, udid: Option, via: super::Via) -> Result { self.disconnect().await; - let (provider, connection) = find_device(udid.as_deref()).await?; + let (provider, connection) = find_device(udid.as_deref(), via).await?; let real_udid = provider.udid.clone(); ensure_paired(&provider).await?; let pairing = provider.get_pairing_file().await.map_err(|e| friendly(&e))?; @@ -391,8 +426,26 @@ async fn session_legacy(provider: UsbmuxdProvider, mut rx: mpsc::Receiver, } } +/// Turns on the phone's "Show this iPhone when on Wi-Fi" setting (Wi-Fi sync), over the cable, so +/// it can be connected over Wi-Fi from then on. +pub async fn enable_wifi(udid: Option) -> Result { + let (provider, _) = find_device(udid.as_deref(), super::Via::Usb) + .await + .map_err(|e| format!("Plug the iPhone in with a cable for this step. ({e})"))?; + ensure_paired(&provider).await?; + let pairing = provider.get_pairing_file().await.map_err(|e| friendly(&e))?; + let mut ld = LockdownClient::connect(&provider).await.map_err(|e| friendly(&e))?; + ld.start_session(&pairing).await.map_err(|e| friendly(&e))?; + ld.set_value("EnableWifiConnections", true.into(), Some("com.apple.mobile.wireless_lockdown")) + .await + .map_err(|e| friendly(&e))?; + Ok("Wi-Fi connections are on for this iPhone. Choose Wi-Fi in Device tools › Connect over, keep the phone \ + unlocked on the same network, and connect." + .into()) +} + pub async fn reveal_developer_mode(udid: Option) -> Result { - let (provider, _) = find_device(udid.as_deref()).await?; + let (provider, _) = find_device(udid.as_deref(), super::Via::Auto).await?; ensure_paired(&provider).await?; let mut amfi = AmfiClient::connect(&provider).await.map_err(|e| friendly(&e))?; amfi.reveal_developer_mode_option_in_ui().await.map_err(|e| friendly(&e))?; diff --git a/standalone/src/device/mirror.rs b/standalone/src/device/mirror.rs new file mode 100644 index 0000000..a6a65af --- /dev/null +++ b/standalone/src/device/mirror.rs @@ -0,0 +1,213 @@ +//! More than one iPhone at a time: extra phones ("mirrors") follow the main one. +//! +//! The player only ever talks to the main phone (through `DeviceManager`). Every position it sends +//! is also handed to each mirror, which sends it from its own task: a slow or lost mirror never +//! holds up playback on the main phone. A mirror that is behind skips straight to the newest +//! position, and a mirror that stops answering is marked as lost (the others keep going) until it +//! is removed. Same behaviour as the browser version's `mirrors.py`. + +use super::{idev::IdeviceDriver, mock::MockDriver, DeviceInfo}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::watch; + +const SEND_TIMEOUT: Duration = Duration::from_secs(20); + +/// The connection a mirror owns: a real iPhone or a simulated one. +pub enum Backend { + Idevice(IdeviceDriver), + Mock(MockDriver), +} + +impl Backend { + async fn set(&mut self, lat: f64, lon: f64) -> Result<(), String> { + match self { + Self::Idevice(d) => d.set_location(lat, lon).await, + Self::Mock(d) => d.set_location(lat, lon), + } + } + async fn clear(&mut self) -> Result<(), String> { + match self { + Self::Idevice(d) => d.clear_location().await, + Self::Mock(d) => d.clear_location(), + } + } + async fn disconnect(&mut self) { + match self { + Self::Idevice(d) => d.disconnect().await, + Self::Mock(d) => d.info = None, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Cmd { + Idle, + Set(f64, f64), + Clear, + Close { clear: bool }, +} + +/// What the mirror's task reports back. +#[derive(Default)] +pub struct Shared { + pub error: Option, + pub sent: usize, + /// the last position this phone accepted (None after a clear) + pub location: Option<(f64, f64)>, + pub history: usize, + done_seq: u64, + /// test hooks: a delay before each send, and every send failing + pub delay_ms: u64, + pub fail: bool, +} + +pub struct Mirror { + pub info: DeviceInfo, + tx: watch::Sender<(u64, Cmd)>, + seq: u64, + pub shared: Arc>, + task: Option>, +} + +impl Mirror { + pub fn start(info: DeviceInfo, backend: Backend) -> Self { + let (tx, rx) = watch::channel((0, Cmd::Idle)); + let shared = Arc::new(Mutex::new(Shared::default())); + let task = tokio::spawn(run(backend, rx, shared.clone())); + Self { info, tx, seq: 0, shared, task: Some(task) } + } + + pub fn lost(&self) -> bool { + self.shared.lock().unwrap().error.is_some() + } + + fn push(&mut self, cmd: Cmd) { + self.seq += 1; + self.tx.send_replace((self.seq, cmd)); // replaces a position the task has not sent yet + } + + pub fn push_set(&mut self, lat: f64, lon: f64) { + if !self.lost() { + self.push(Cmd::Set(lat, lon)); + } + } + + pub fn push_clear(&mut self) { + if !self.lost() { + self.push(Cmd::Clear); + } + } + + /// Waits until the newest position has been sent (or the phone is lost). + pub async fn settle(&self, max: Duration) { + let end = tokio::time::Instant::now() + max; + loop { + { + let s = self.shared.lock().unwrap(); + if s.error.is_some() || s.done_seq >= self.seq { + return; + } + } + if tokio::time::Instant::now() > end { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + /// Stops following; with `clear`, the phone goes back to its real location first. + pub async fn close(mut self, clear: bool) { + if clear { + self.settle(Duration::from_secs(2)).await; + } + self.push(Cmd::Close { clear }); + if let Some(t) = self.task.take() { + let _ = tokio::time::timeout(Duration::from_secs(15), t).await; + } + } + + pub fn to_json(&self) -> serde_json::Value { + let mut v = serde_json::to_value(&self.info).unwrap_or_default(); + let err = self.shared.lock().unwrap().error.clone(); + v["state"] = serde_json::json!(if err.is_some() { "lost" } else { "ok" }); + v["error"] = serde_json::json!(err); + v + } +} + +async fn run(mut backend: Backend, mut rx: watch::Receiver<(u64, Cmd)>, shared: Arc>) { + loop { + if rx.changed().await.is_err() { + break; // the mirror was dropped without closing + } + let (seq, cmd) = *rx.borrow_and_update(); + let (delay, fail) = { + let s = shared.lock().unwrap(); + (s.delay_ms, s.fail) + }; + let res = match cmd { + Cmd::Idle => Ok(()), + Cmd::Close { clear } => { + if clear && shared.lock().unwrap().error.is_none() { + let _ = tokio::time::timeout(Duration::from_secs(10), backend.clear()).await; + shared.lock().unwrap().location = None; + } + break; + } + Cmd::Set(..) | Cmd::Clear => { + if delay > 0 { + tokio::time::sleep(Duration::from_millis(delay)).await; + } + let send = async { + if fail { + return Err("Lost the connection to the iPhone".to_string()); + } + match cmd { + Cmd::Set(lat, lon) => backend.set(lat, lon).await, + _ => backend.clear().await, + } + }; + match tokio::time::timeout(SEND_TIMEOUT, send).await { + Ok(r) => r, + Err(_) => Err("The iPhone stopped answering.".to_string()), + } + } + }; + let lost = { + let mut s = shared.lock().unwrap(); + s.done_seq = seq; + match res { + Ok(()) => { + match cmd { + Cmd::Set(lat, lon) => { + s.location = Some((lat, lon)); + s.history += 1; + s.sent += 1; + } + Cmd::Clear => { + s.location = None; + s.sent += 1; + } + _ => {} + } + false + } + Err(e) => { + s.error = Some(e); + true + } + } + }; + if lost { + // wait until the mirror is removed, then let go of the connection + while rx.changed().await.is_ok() { + if matches!(rx.borrow_and_update().1, Cmd::Close { .. }) { + break; + } + } + break; + } + } + backend.disconnect().await; +} diff --git a/standalone/src/device/mock.rs b/standalone/src/device/mock.rs index 4fcd23e..675958c 100644 --- a/standalone/src/device/mock.rs +++ b/standalone/src/device/mock.rs @@ -2,8 +2,10 @@ use super::DeviceInfo; -/// The pretend phone always reports this iOS version (the current major release). +/// The pretend phones always report this iOS version (the current major release). pub const SIMULATED_IOS: &str = "27"; +/// Two pretend phones, so several iPhones at once can be tried without hardware. +pub const SIMULATED_DEVICES: [(&str, &str); 2] = [("SIMULATED-0001", "Simulated iPhone"), ("SIMULATED-0002", "Simulated iPhone 2")]; #[derive(Default)] pub struct MockDriver { @@ -14,12 +16,22 @@ pub struct MockDriver { impl MockDriver { pub fn list_devices(&self) -> Vec { - vec![serde_json::json!({"udid": "SIMULATED-0001", "name": "Simulated iPhone", "ios_version": SIMULATED_IOS, "connection": "Simulated"})] + SIMULATED_DEVICES + .iter() + .map(|(udid, name)| { + serde_json::json!({"udid": udid, "name": name, "ios_version": SIMULATED_IOS, + "connection": "Simulated", "connections": ["Simulated"]}) + }) + .collect() } - pub fn connect(&mut self) -> DeviceInfo { + pub fn connect(&mut self, udid: Option<&str>) -> Result { + let (udid, name) = match udid.filter(|u| !u.is_empty()) { + None => SIMULATED_DEVICES[0], + Some(u) => *SIMULATED_DEVICES.iter().find(|(id, _)| *id == u).ok_or("No such simulated iPhone")?, + }; let info = DeviceInfo { - udid: "SIMULATED-0001".into(), - name: "Simulated iPhone".into(), + udid: udid.into(), + name: name.into(), ios_version: SIMULATED_IOS.into(), product_type: "Simulated".into(), connection: "Simulated".into(), @@ -27,7 +39,7 @@ impl MockDriver { notes: vec![], }; self.info = Some(info.clone()); - info + Ok(info) } pub fn set_location(&mut self, lat: f64, lon: f64) -> Result<(), String> { if self.info.is_none() { diff --git a/standalone/src/device/mod.rs b/standalone/src/device/mod.rs index 4028cc4..c689175 100644 --- a/standalone/src/device/mod.rs +++ b/standalone/src/device/mod.rs @@ -1,6 +1,7 @@ //! Ways this app can move a device's location: a real iPhone (idevice) or a simulator. pub mod idev; +pub mod mirror; pub mod mock; use serde::Serialize; @@ -40,16 +41,65 @@ impl DriverKind { } } -/// Owns both drivers; one is active. +/// How to reach the phone: `Auto` takes the cable when it is plugged in, else Wi-Fi. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Via { + #[default] + Auto, + Usb, + Network, +} + +impl Via { + pub fn parse(s: Option<&str>) -> Option { + match s.unwrap_or("auto") { + "auto" | "" => Some(Self::Auto), + "usb" => Some(Self::Usb), + "network" => Some(Self::Network), + _ => None, + } + } +} + +/// Up to this many extra iPhones can follow the main one. +pub const MAX_MIRRORS: usize = 8; + +/// Owns both drivers (one is active, the main phone) and the extra phones that follow it. pub struct DeviceManager { pub kind: DriverKind, pub idev: idev::IdeviceDriver, pub mock: mock::MockDriver, + pub mirrors: Vec, + /// the last position sent to the main phone, so a new mirror can catch up at once + last: Option<(f64, f64)>, } impl Default for DeviceManager { fn default() -> Self { - Self { kind: DriverKind::Idevice, idev: idev::IdeviceDriver::default(), mock: mock::MockDriver::default() } + Self { + kind: DriverKind::Idevice, + idev: idev::IdeviceDriver::default(), + mock: mock::MockDriver::default(), + mirrors: Vec::new(), + last: None, + } + } +} + +/// Connects another phone of the same kind as the main one, for use as a mirror. Runs without the +/// device lock held, so a slow iOS 17 handshake doesn't stall playback on the main phone. +pub async fn connect_mirror(kind: DriverKind, udid: String, via: Via) -> Result<(DeviceInfo, mirror::Backend), String> { + match kind { + DriverKind::Idevice => { + let mut d = idev::IdeviceDriver::default(); + let info = d.connect(Some(udid), via).await?; + Ok((info, mirror::Backend::Idevice(d))) + } + DriverKind::Mock => { + let mut d = mock::MockDriver::default(); + let info = d.connect(Some(&udid))?; + Ok((info, mirror::Backend::Mock(d))) + } } } @@ -69,17 +119,28 @@ impl DeviceManager { DriverKind::Mock => Ok(self.mock.list_devices()), } } - pub async fn connect(&mut self, kind: DriverKind, udid: Option) -> Result { + pub async fn connect(&mut self, kind: DriverKind, udid: Option, via: Via) -> Result { if kind != self.kind { self.disconnect().await; self.kind = kind; } - match kind { - DriverKind::Idevice => self.idev.connect(udid).await, - DriverKind::Mock => Ok(self.mock.connect()), + if let Some(u) = udid.as_deref() { + self.remove_mirror(u, false).await; // it becomes the main phone instead } + let info = match kind { + DriverKind::Idevice => self.idev.connect(udid, via).await?, + DriverKind::Mock => self.mock.connect(udid.as_deref())?, + }; + self.remove_mirror(&info.udid, false).await; + Ok(info) } + /// Disconnects the main phone and every mirror. pub async fn disconnect(&mut self) { + self.drop_mirrors().await; + self.disconnect_main().await; + } + async fn disconnect_main(&mut self) { + self.last = None; match self.kind { DriverKind::Idevice => self.idev.disconnect().await, DriverKind::Mock => self.mock.info = None, @@ -89,12 +150,78 @@ impl DeviceManager { match self.kind { DriverKind::Idevice => self.idev.set_location(lat, lon).await, DriverKind::Mock => self.mock.set_location(lat, lon), + }?; + self.last = Some((lat, lon)); + for m in &mut self.mirrors { + m.push_set(lat, lon); } + Ok(()) } pub async fn clear_location(&mut self) -> Result<(), String> { match self.kind { DriverKind::Idevice => self.idev.clear_location().await, DriverKind::Mock => self.mock.clear_location(), + }?; + self.last = None; + for m in &mut self.mirrors { + m.push_clear(); + } + Ok(()) + } + + /// Why `udid` can't become a mirror right now, if it can't. + pub fn mirror_refusal(&self, udid: &str) -> Option { + let main = match self.info() { + Some(i) => i, + None => return Some("Connect the main iPhone first.".into()), + }; + if udid == main.udid { + return Some("That is the main iPhone already.".into()); + } + if self.mirrors.iter().any(|m| m.info.udid == udid) { + return Some("That iPhone already follows the main one.".into()); + } + if self.mirrors.len() >= MAX_MIRRORS { + return Some(format!("Up to {MAX_MIRRORS} extra iPhones can follow the main one.")); + } + None + } + /// Adds a phone connected by `connect_mirror`; it moves to the main phone's position at once. + pub async fn attach_mirror(&mut self, info: DeviceInfo, backend: mirror::Backend) -> Result { + if let Some(why) = self.mirror_refusal(&info.udid) { + mirror::Mirror::start(info, backend).close(false).await; + return Err(if why.starts_with("That is") { "That iPhone is connected already.".into() } else { why }); + } + let mut m = mirror::Mirror::start(info, backend); + if let Some((lat, lon)) = self.last { + m.push_set(lat, lon); + } + let v = m.to_json(); + self.mirrors.push(m); + Ok(v) + } + /// Stops a mirror; with `clear`, that phone goes back to its real location first. + pub async fn remove_mirror(&mut self, udid: &str, clear: bool) -> bool { + match self.mirrors.iter().position(|m| m.info.udid == udid) { + Some(i) => { + self.mirrors.remove(i).close(clear).await; + true + } + None => false, + } + } + pub async fn drop_mirrors(&mut self) { + for m in std::mem::take(&mut self.mirrors) { + m.close(false).await; + } + } + pub fn mirrors_json(&self) -> Vec { + self.mirrors.iter().map(|m| m.to_json()).collect() + } + pub async fn enable_wifi(&mut self, udid: Option) -> Result { + match self.kind { + DriverKind::Idevice => idev::enable_wifi(udid.or_else(|| self.idev.info.as_ref().map(|i| i.udid.clone()))).await, + DriverKind::Mock => Ok("Simulator: nothing to do.".into()), } } pub async fn reveal_developer_mode(&mut self) -> Result { @@ -106,8 +233,10 @@ impl DeviceManager { pub async fn mount_developer_image(&mut self) -> Result { match self.kind { DriverKind::Idevice => { - let udid = self.idev.info.as_ref().map(|i| i.udid.clone()).ok_or("Connect first")?; - let info = self.idev.connect(Some(udid)).await?; + let cur = self.idev.info.as_ref().ok_or("Connect first")?; + let via = if cur.connection.starts_with("Wi-Fi") { Via::Network } else { Via::Auto }; + let udid = cur.udid.clone(); + let info = self.idev.connect(Some(udid), via).await?; Ok(if info.notes.is_empty() { "Developer Disk Image is mounted.".into() } else { info.notes.join(" ") }) } DriverKind::Mock => Ok("Simulator: nothing to mount.".into()), diff --git a/standalone/src/player.rs b/standalone/src/player.rs index 79d4124..eb0e21f 100644 --- a/standalone/src/player.rs +++ b/standalone/src/player.rs @@ -465,7 +465,7 @@ mod tests { async fn player() -> (Arc, Devices) { let devices: Devices = Arc::new(AsyncMutex::new(DeviceManager::default())); - devices.lock().await.connect(DriverKind::Mock, None).await.unwrap(); + devices.lock().await.connect(DriverKind::Mock, None, crate::device::Via::Auto).await.unwrap(); (Arc::new(Player::new(devices.clone())), devices) } diff --git a/standalone/src/server.rs b/standalone/src/server.rs index ded621a..b3231cc 100644 --- a/standalone/src/server.rs +++ b/standalone/src/server.rs @@ -1,7 +1,7 @@ //! Local HTTP server for the UI: same JSON API as the browser version (server.py), so the //! front end in ui/ is shared between both apps. -use crate::device::{DeviceManager, DriverKind}; +use crate::device::{DeviceManager, DriverKind, Via}; use crate::player::{Devices, Player}; use crate::profile::{self, Leg, ProfileSettings, Ramp, Timeline, Waypoint}; use crate::{geo, gmaps_links, gpx, routing, store::Store, updater::Updater}; @@ -10,7 +10,7 @@ use axum::{ extract::{DefaultBodyLimit, Multipart, Path, Query, State}, http::{header, StatusCode}, response::{IntoResponse, Response}, - routing::{get, post}, + routing::{delete, get, post}, Json, Router, }; use rust_embed::RustEmbed; @@ -81,6 +81,7 @@ impl AppState { } // ---------------------------------------------------------------- errors +#[derive(Debug)] pub struct ApiError(pub u16, pub String); impl IntoResponse for ApiError { @@ -110,6 +111,9 @@ pub fn router(app: App) -> Router { .route("/api/disconnect", post(disconnect)) .route("/api/device/reveal-developer-mode", post(reveal)) .route("/api/device/mount", post(mount)) + .route("/api/device/wifi", post(enable_wifi)) + .route("/api/mirrors", post(mirror_add)) + .route("/api/mirrors/{udid}", delete(mirror_remove)) .route("/api/location/set", post(set_location)) .route("/api/location/clear", post(clear_location)) .route("/api/parse-coords", post(parse_coords)) @@ -196,11 +200,12 @@ async fn status(State(app): State) -> R { "app": "standalone", "driver": d.kind.key(), "drivers": [{"key": "pmd3", "label": "Direct", "live": true}, {"key": "mock", "label": "Simulator (no iPhone)", "live": true}], - "features": {"cli_driver": false, "tunnel_helper": false}, + "features": {"cli_driver": false, "tunnel_helper": false, "multi_device": true, "wifi": true}, "device": d.info(), "live": true, "player": app.player.status(), "update": app.updater.status(), + "mirrors": d.mirrors_json(), }))) } @@ -219,15 +224,63 @@ async fn devices(State(app): State, Query(q): Query) -> R { struct ConnectIn { driver: Option, udid: Option, + connection: Option, } async fn connect(State(app): State, Json(b): Json) -> R { let kind = DriverKind::parse(b.driver.as_deref().unwrap_or("pmd3")).ok_or(bad("unknown driver"))?; + let via = Via::parse(b.connection.as_deref()).ok_or(bad("unknown connection"))?; app.player.stop().await; - let info = app.devices.lock().await.connect(kind, b.udid.filter(|s| !s.is_empty())).await.map_err(dev)?; + let info = app.devices.lock().await.connect(kind, b.udid.filter(|s| !s.is_empty()), via).await.map_err(dev)?; Ok(Json(json!({"device": info}))) } +#[derive(Deserialize)] +struct MirrorIn { + udid: String, + connection: Option, +} + +/// Another iPhone follows the main one: same position, same route, from now on. +async fn mirror_add(State(app): State, Json(b): Json) -> R { + let via = Via::parse(b.connection.as_deref()).ok_or(bad("unknown connection"))?; + let kind = { + let d = app.devices.lock().await; + if let Some(why) = d.mirror_refusal(&b.udid) { + return Err(dev(why)); + } + d.kind + }; + let (info, backend) = crate::device::connect_mirror(kind, b.udid, via).await.map_err(dev)?; + let mut d = app.devices.lock().await; + let m = d.attach_mirror(info, backend).await.map_err(dev)?; + Ok(Json(json!({"mirror": m, "mirrors": d.mirrors_json()}))) +} + +#[derive(Deserialize)] +struct ClearQ { + clear: Option, +} + +/// Stops following; by default the phone goes back to its real location. +async fn mirror_remove(State(app): State, Path(udid): Path, Query(q): Query) -> R { + let mut d = app.devices.lock().await; + if !d.remove_mirror(&udid, q.clear.unwrap_or(true)).await { + return Err(ApiError(404, "That iPhone doesn't follow the main one.".into())); + } + Ok(Json(json!({"mirrors": d.mirrors_json()}))) +} + +#[derive(Deserialize)] +struct UdidIn { + udid: Option, +} + +async fn enable_wifi(State(app): State, Json(b): Json) -> R { + let m = app.devices.lock().await.enable_wifi(b.udid.filter(|s| !s.is_empty())).await.map_err(dev)?; + Ok(Json(json!({"message": m}))) +} + async fn disconnect(State(app): State) -> R { app.player.stop().await; app.devices.lock().await.disconnect().await; @@ -1008,6 +1061,148 @@ mod tests { assert!(held.hold && !serde_json::from_value::(json!({"lat": 1.0, "lon": 2.0})).unwrap().hold); } + // ------------------------------------------------ several iPhones at once (mirrors) + const MAIN: &str = "SIMULATED-0001"; + const SECOND: &str = "SIMULATED-0002"; + + fn connect_in(udid: Option<&str>, connection: Option<&str>) -> Json { + Json(ConnectIn { driver: Some("mock".into()), udid: udid.map(String::from), connection: connection.map(String::from) }) + } + fn mirror_in(udid: &str, connection: Option<&str>) -> Json { + Json(MirrorIn { udid: udid.into(), connection: connection.map(String::from) }) + } + async fn two_phones() -> (App, Arc>) { + let a = app(); + let _ = connect(State(a.clone()), connect_in(Some(MAIN), None)).await.unwrap(); + let r = mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_or_else(|e| panic!("{}", e.1)); + assert_eq!(r.0["mirror"]["name"], "Simulated iPhone 2"); + assert_eq!(r.0["mirror"]["state"], "ok"); + let shared = a.devices.lock().await.mirrors[0].shared.clone(); + (a, shared) + } + async fn until(f: impl Fn() -> bool) -> bool { + for _ in 0..300 { + if f() { + return true; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + false + } + fn here(lat: f64, lon: f64) -> Json { + Json(LatLonIn { lat, lon }) + } + + #[tokio::test] + async fn mirror_follows_teleport_playback_and_stop() { + let (a, m) = two_phones().await; + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["device"]["udid"], MAIN); + assert_eq!(st["mirrors"][0]["udid"], SECOND); + assert!(st["features"]["multi_device"].as_bool().unwrap() && st["features"]["wifi"].as_bool().unwrap()); + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().location == Some((51.5, -0.12))).await); + // a route played on the main phone moves the mirror along it too + let start = (51.5, -0.12); + let end = geo::destination(start, 90.0, 300.0); + let s = crate::profile::ProfileSettings { default_cruise_kmh: 36.0, accel_ms2: 2.0, decel_ms2: 2.0, ..Default::default() }; + let w = [crate::profile::Waypoint::at(start), crate::profile::Waypoint::at(end)]; + let tl = Arc::new(crate::profile::build_timeline(&w, &[crate::profile::Leg::new(vec![start, end])], &s).unwrap()); + a.player.load(tl, "two".into()).await; + a.player.set_options(Some(10.0), None, None, Some(0.2), None).unwrap(); + a.player.play().await.unwrap(); + assert!(until(|| a.player.status()["state"] == "finished").await); + assert!(until(|| m.lock().unwrap().location.is_some_and(|p| geo::haversine_m(p, end) < 1.0)).await); + let main_end = a.devices.lock().await.mock.location.unwrap(); + assert!(geo::haversine_m(main_end, end) < 1.0); + assert!(m.lock().unwrap().history > 5, "it moved along the route, not just to the end"); + // Stop spoofing clears every phone + let _ = clear_location(State(a.clone())).await.unwrap(); + assert!(until(|| m.lock().unwrap().location.is_none()).await); + assert!(a.devices.lock().await.mock.location.is_none()); + } + + #[tokio::test] + async fn a_slow_mirror_never_holds_up_the_main_phone() { + let (a, m) = two_phones().await; + m.lock().unwrap().delay_ms = 300; + let t0 = std::time::Instant::now(); + for i in 0..6 { + let _ = set_location(State(a.clone()), here(51.5 + i as f64 * 1e-4, -0.12)).await.unwrap(); + } + assert!(t0.elapsed() < std::time::Duration::from_millis(1200), "six sends to a 0.3 s phone would take 1.8 s"); + let last = (51.5 + 5e-4, -0.12); + let main = a.devices.lock().await.mock.location.unwrap(); + assert!((main.0 - last.0).abs() < 1e-9); + // the mirror skips the positions it fell behind on and ends where the main phone is + assert!(until(|| m.lock().unwrap().location.is_some_and(|p| (p.0 - last.0).abs() < 1e-9)).await); + assert!(m.lock().unwrap().sent < 6); + } + + #[tokio::test] + async fn a_lost_mirror_is_marked_and_the_rest_keeps_going() { + let (a, m) = two_phones().await; + m.lock().unwrap().fail = true; + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().error.is_some()).await); + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["mirrors"][0]["state"], "lost"); + assert!(st["mirrors"][0]["error"].as_str().unwrap().contains("Lost the connection")); + let _ = set_location(State(a.clone()), here(51.6, -0.12)).await.unwrap(); + assert_eq!(a.devices.lock().await.mock.location, Some((51.6, -0.12))); + let r = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap(); + assert_eq!(r.0["mirrors"], json!([])); + } + + #[tokio::test] + async fn removing_a_mirror_sends_it_back_to_its_real_location() { + let (a, m) = two_phones().await; + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().location.is_some()).await); + let _ = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap(); + assert_eq!(m.lock().unwrap().location, None); + assert_eq!(a.devices.lock().await.mock.location, Some((51.5, -0.12)), "the main phone keeps its position"); + let e = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap_err(); + assert_eq!(e.0, 404); + } + + #[tokio::test] + async fn new_mirror_catches_up_and_rules() { + let a = app(); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_err().0, 409, "no main phone yet"); + let _ = connect(State(a.clone()), connect_in(Some(MAIN), None)).await.unwrap(); + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert_eq!(mirror_add(State(a.clone()), mirror_in(MAIN, None)).await.unwrap_err().0, 409, "that's the main phone"); + let _ = mirror_add(State(a.clone()), mirror_in(SECOND, Some("usb"))).await.unwrap(); + let m = a.devices.lock().await.mirrors[0].shared.clone(); + assert!(until(|| m.lock().unwrap().location == Some((51.5, -0.12))).await, "caught up at once"); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_err().0, 409, "already following"); + assert_eq!(mirror_add(State(a.clone()), mirror_in("SIMULATED-9999", None)).await.unwrap_err().0, 409); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, Some("bluetooth"))).await.unwrap_err().0, 400); + // connecting the main phone to the mirrored one makes it the main phone instead + let _ = connect(State(a.clone()), connect_in(Some(SECOND), None)).await.unwrap(); + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["device"]["udid"], SECOND); + assert_eq!(st["mirrors"], json!([])); + // disconnecting ends the mirrors too + let _ = mirror_add(State(a.clone()), mirror_in(MAIN, None)).await.unwrap(); + let _ = disconnect(State(a.clone())).await.unwrap(); + assert_eq!(status(State(a.clone())).await.unwrap().0["mirrors"], json!([])); + } + + #[tokio::test] + async fn wifi_tool_and_connection_field() { + let a = app(); + let _ = connect(State(a.clone()), connect_in(None, Some("network"))).await.unwrap(); + let r = enable_wifi(State(a.clone()), Json(UdidIn { udid: None })).await.unwrap(); + assert!(r.0["message"].as_str().unwrap().starts_with("Simulator")); + assert_eq!(connect(State(a.clone()), connect_in(None, Some("carrier-pigeon"))).await.unwrap_err().0, 400); + assert_eq!(Via::parse(None), Some(Via::Auto)); + assert_eq!(Via::parse(Some("network")), Some(Via::Network)); + let list = a.devices.lock().await.list_devices(DriverKind::Mock).await.unwrap(); + assert_eq!(list.iter().map(|d| d["udid"].as_str().unwrap()).collect::>(), [MAIN, SECOND]); + } + #[tokio::test] async fn bad_requests_are_rejected_before_routing() { let mut r = route(); diff --git a/ui/app.js b/ui/app.js index 6d5e0ba..366a1cd 100644 --- a/ui/app.js +++ b/ui/app.js @@ -735,6 +735,7 @@ async function refreshDevices(userAsked = false) { state.devicesError = null; try { const { devices } = await api(`/api/devices?driver=${driver}`); + state.devices = devices; for (const d of devices) { const label = `${d.name || "iPhone"}${d.ios_version ? ` (iOS ${d.ios_version})` : ""} — ${d.connection || ""}${d.error ? " (needs attention)" : ""}`; sel.append(el("option", { value: d.udid, textContent: label, title: d.error || d.udid })); @@ -754,7 +755,7 @@ async function connectNow() { $("device-status").className = "status"; $("device-status").textContent = "Connecting… (iOS 17+ can take up to 30 s)"; try { - const { device } = await api("/api/connect", { body: { driver: $("driver").value, udid: $("device-select").value || null } }); + const { device } = await api("/api/connect", { body: { driver: $("driver").value, udid: $("device-select").value || null, connection: $("conn-via").value } }); toast(`Connected to ${device.name}`); for (const n of device.notes || []) toast(n); return device; @@ -768,6 +769,64 @@ $("btn-disconnect").onclick = guard(disconnectNow); async function revealDevMode() { toast((await api("/api/device/reveal-developer-mode", { body: {} })).message); } $("btn-reveal").onclick = busy($("btn-reveal"), "Asking the iPhone…", revealDevMode); $("btn-mount").onclick = busy($("btn-mount"), "Mounting…", async () => toast((await api("/api/device/mount", { body: {} })).message)); +$("btn-wifi").onclick = busy($("btn-wifi"), "Asking the iPhone…", async () => { + toast((await api("/api/device/wifi", { body: { udid: (state.status && state.status.device && state.status.device.udid) || $("device-select").value || null } })).message); + refreshDevices(false); +}); + +// ---- more iPhones at once: extra phones follow the main one (see mirrors.py / device/mirror.rs) +const lostMirrorsToasted = new Set(); +async function addMirror() { + const udid = $("mirror-select").value; + if (!udid) { toast("Plug in or connect another iPhone, press the refresh button next to Device, then pick it here.", true); return; } + const { mirror } = await api("/api/mirrors", { body: { udid, connection: $("conn-via").value } }); + toast(`${mirror.name} now follows ${state.status.device.name}`); + for (const n of mirror.notes || []) toast(n); + await poll(); +} +$("btn-mirror-add").onclick = busy($("btn-mirror-add"), "Connecting…", addMirror); +async function removeMirror(m) { + await api(`/api/mirrors/${encodeURIComponent(m.udid)}`, { method: "DELETE" }); + toast(`${m.name} no longer follows and is back on its real location`); + lostMirrorsToasted.delete(m.udid); + await poll(); +} +function renderMirrors(st) { + const box = $("mirrors"); + const on = !!(st.device && st.live && st.features && st.features.multi_device); + box.hidden = !on; + if (!on) return; + const mirrors = st.mirrors || []; + const listKey = JSON.stringify(mirrors.map((m) => [m.udid, m.state, m.error])); + if (box.dataset.list !== listKey) { + box.dataset.list = listKey; + $("mirror-list").replaceChildren(...mirrors.map((m) => { + const lost = m.state === "lost"; + const line = el("div", { class: `status ${lost ? "err" : "ok"}`, title: m.error || m.transport || "" }, + el("span", { textContent: `${m.name}${m.ios_version ? ` · iOS ${m.ios_version}` : ""}${m.connection && m.connection !== "Simulated" ? ` · ${m.connection}` : ""}${lost ? ` · ${m.error}` : ""}` })); + const rm = el("button", { type: "button", textContent: "Remove", title: "Stop following and send this iPhone back to its real location" }); + rm.onclick = busy(rm, "Removing…", () => removeMirror(m)); + return el("li", {}, line, rm); + })); + for (const m of mirrors) { + if (m.state === "lost" && !lostMirrorsToasted.has(m.udid)) { lostMirrorsToasted.add(m.udid); toast(`${m.name} stopped following: ${m.error}`, true); } + } + } + // phones that can still be added: found in the last device scan, not the main one, not following yet + const taken = new Set([st.device.udid, ...mirrors.map((m) => m.udid)]); + const free = (state.devices || []).filter((d) => !taken.has(d.udid)); + const optKey = JSON.stringify(free.map((d) => [d.udid, d.connection])); + const sel = $("mirror-select"); + if (sel.dataset.opts !== optKey) { + sel.dataset.opts = optKey; + const keep = sel.value; + sel.replaceChildren(...(free.length + ? free.map((d) => el("option", { value: d.udid, textContent: `${d.name || "iPhone"}${d.ios_version ? ` (iOS ${d.ios_version})` : ""} — ${d.connection || ""}`, title: d.error || d.udid })) + : [el("option", { value: "", textContent: "No other iPhone found" })])); + if (keep && free.some((d) => d.udid === keep)) sel.value = keep; + } + $("btn-mirror-add").disabled = !free.length; +} async function stopSpoofing() { await api("/api/location/clear", { body: {} }); @@ -783,12 +842,14 @@ function renderDevice(st) { const box = $("device-status"), chip = $("conn-chip"); $("btn-connect").hidden = !!d; $("btn-disconnect").hidden = !d; + renderMirrors(st); if (d) { + const extra = (st.mirrors || []).length; box.className = "status ok"; - box.textContent = `${d.name}${d.ios_version ? ` · iOS ${d.ios_version}` : ""} · ${d.transport}`; + box.textContent = `${d.name}${d.ios_version ? ` · iOS ${d.ios_version}` : ""}${d.connection && d.connection !== "Simulated" ? ` · ${d.connection}` : ""} · ${d.transport}`; $("driver").value = st.driver; - chip.className = "chip ok"; chip.textContent = d.name; - $("dev-summary").textContent = `Connected · ${d.name}`; + chip.className = "chip ok"; chip.textContent = extra ? `${d.name} + ${extra}` : d.name; + $("dev-summary").textContent = `Connected · ${d.name}${extra ? ` + ${extra} more` : ""}`; } else if (state.devicesError && $("driver").value !== "mock") { box.className = "status warn"; box.textContent = state.devicesError; chip.className = "chip warn"; chip.textContent = "Not ready"; @@ -2552,7 +2613,7 @@ function saveSettingsSoon() { await saveStore(); }), 700); } -const SETTING_IDS = ["driver", "provider", "default-mode", "default-speed", "accel", "decel", "alt-count", "start-rest", "stop-end", +const SETTING_IDS = ["driver", "conn-via", "provider", "default-mode", "default-speed", "accel", "decel", "alt-count", "start-rest", "stop-end", "road-aware", "road-data", "corner-slow", "match-eta", "speed-factor", "multiplier", "loop", "jitter", "tick", "laps", "joy-speed", "gpx-speed"]; function collectSettings() { const s = {}; diff --git a/ui/index.html b/ui/index.html index 2dd25d8..b41f544 100644 --- a/ui/index.html +++ b/ui/index.html @@ -111,9 +111,33 @@

Location Spoofer

Not connected
+ +
Device tools
+
+ + +
+
+
diff --git a/ui/style.css b/ui/style.css index 48add8c..d4f1561 100644 --- a/ui/style.css +++ b/ui/style.css @@ -339,6 +339,17 @@ button.info:hover, button.info:focus-visible { color: var(--accent); opacity: 1; color: var(--text); background: var(--panel); border: 1px solid var(--border-strong); border-radius: var(--radius); box-shadow: var(--shadow-pop); } .tool-list { display: flex; flex-direction: column; gap: 4px; } +/* more iPhones (mirrors) */ +.mirrors { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border-radius: var(--radius); background: var(--well); } +.mirrors-head { display: flex; align-items: center; gap: 8px; } +.mirrors-title { font-size: 12px; font-weight: 600; } +.mirrors-head .info { margin-left: auto; } +.mirror-list { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; } +.mirror-list:empty { display: none; } +.mirror-list li { display: flex; align-items: center; gap: 8px; min-height: 26px; animation: panel-in .2s var(--ease-out); } +.mirror-list li .status { flex: 1; min-width: 0; } +.mirror-list li .status span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mirror-list li button { height: 24px; min-height: 24px; } .tool { display: flex; align-items: center; gap: 6px; } .tool > button:first-child { flex: 1; justify-content: flex-start; } .exp label.check button.info { margin-left: auto; } From c0469626312c4a2088ab1d5e91fc6111c9507189 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 16:29:49 +0000 Subject: [PATCH 2/6] Screen mirroring backend: picture, sound, touch and keys over the developer tunnel Both editions get the same /api/mirror routes and WebSocket: GET /api/mirror, POST /api/mirror/start|stop|input, GET /api/mirror/screenshot, GET /api/mirror/ws (decoder setup, frames as length-prefixed HEVC, PCM sound, status JSON; input JSON the other way). iOS 27+ streams its display through com.apple.coredevice.displayservice as HEVC over RTP inside the developer tunnel. Frames are reassembled into whole access units (Apple's 14-byte slice footer removed, frames held back after a lost packet until the next keyframe) and sent with an hvcC description and codec string for WebCodecs. Receiver reports keep both streams alive, frames are acknowledged and keyframes requested for new viewers, after losses and after 4 s of a still screen. Touch, buttons, keys and typing go through the CoreDevice HID services, which only accept input while a stream runs. Standalone: idevice's display_stream support on its own thread and tunnel; sound decoded from AAC-ELD with FDK AAC (not in MinGW builds, whose headers clash; the release uses MSVC). The iOS 27 developer image mount now tries the personalized image instead of refusing. Browser edition: pymobiledevice3's services (needs 11.63+); sound on macOS only. Its WebSocket repeats the local-only check, which HTTP middleware skips. The simulator driver accepts mirroring and input without a screen, for tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdk7FBJL1zvtWFNTApV --- browser/requirements.txt | 2 +- browser/spoofer/mirror.py | 741 +++++++++++++++++++++++++++++++ browser/spoofer/server.py | 83 +++- browser/tests/test_mirror.py | 168 +++++++ standalone/Cargo.lock | 70 +++ standalone/Cargo.toml | 9 +- standalone/src/device/idev.rs | 19 +- standalone/src/main.rs | 1 + standalone/src/mirror/hevc.rs | 553 +++++++++++++++++++++++ standalone/src/mirror/mod.rs | 475 ++++++++++++++++++++ standalone/src/mirror/session.rs | 332 ++++++++++++++ standalone/src/server.rs | 123 +++++ 12 files changed, 2563 insertions(+), 13 deletions(-) create mode 100644 browser/spoofer/mirror.py create mode 100644 browser/tests/test_mirror.py create mode 100644 standalone/src/mirror/hevc.rs create mode 100644 standalone/src/mirror/mod.rs create mode 100644 standalone/src/mirror/session.rs diff --git a/browser/requirements.txt b/browser/requirements.txt index b5b6939..bb5c140 100644 --- a/browser/requirements.txt +++ b/browser/requirements.txt @@ -1,6 +1,6 @@ # Device control. Written against 11.x; newer major versions may change the Python API # (the "Guide commands" connection method keeps working as long as the CLI does). -pymobiledevice3>=11.49,<12 +pymobiledevice3>=11.63,<12 # Offline sea-lane routing searoute>=1.6,<2 fastapi>=0.115 diff --git a/browser/spoofer/mirror.py b/browser/spoofer/mirror.py new file mode 100644 index 0000000..2166e80 --- /dev/null +++ b/browser/spoofer/mirror.py @@ -0,0 +1,741 @@ +"""Screen mirroring: the iPhone's screen and sound in the app, and mouse/keyboard control. + +Same behaviour, messages and WebSocket format as the standalone app (standalone/src/mirror). +iOS 27+ streams its display through ``com.apple.coredevice.displayservice`` as HEVC over RTP +and its sound as AAC-ELD; touches, buttons and keys go back through the CoreDevice HID +services, which only accept input while a stream runs. pymobiledevice3 provides the services. + +WebSocket messages to clients (``/api/mirror/ws``): + +* ``[1][width u16][height u16][codec length u8][codec][hvcC]``: decoder setup; +* ``[2][key u8][timestamp µs u64][frame as 4-byte length-prefixed NAL units]``; +* ``[3][timestamp µs u64][PCM s16le, 48 kHz, stereo]``; +* text: the status JSON whenever it changes. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import logging +import random +import struct +import sys +import time +import uuid +from contextlib import AsyncExitStack +from typing import Any, Optional + +log = logging.getLogger(__name__) + +# name -> (HID usage page, usage, hold in seconds). Siri needs a long press. +BUTTONS = { + "home": (0x0C, 0x40, 0.05), + "lock": (0x0C, 0x30, 0.05), + "volume-up": (0x0C, 0xE9, 0.05), + "volume-down": (0x0C, 0xEA, 0.05), + "mute": (0x0C, 0xE2, 0.05), + "siri": (0x0C, 0xCF, 1.0), +} + + +class MirrorError(Exception): + """Shown to the user as is (HTTP 409).""" + + +def _coord(v: dict, k: str) -> int: + f = v.get(k) + if isinstance(f, bool) or not isinstance(f, (int, float)): + raise ValueError(f"'{k}' must be a number from 0 to 1") + if not 0 <= f <= 1: + raise ValueError(f"'{k}' must be from 0 to 1 (a fraction of the screen)") + return round(f * 65535) + + +def parse_input(v: Any) -> tuple: + """Parse one input message (coordinates are fractions of the screen, top left 0,0). + + ``{"t":"touch","phase":"down|move|up","x":..,"y":..}``, ``{"t":"tap","x":..,"y":..}``, + ``{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}``, ``{"t":"button","name":"home"}``, + ``{"t":"key","usage":40,"down":true}``, ``{"t":"text","text":"hi"}``, ``{"t":"keyframe"}``. + Raises ValueError with a message for the user. + """ + if not isinstance(v, dict): + raise ValueError("'t' must be touch, tap, swipe, button, key, text or keyframe") + t = v.get("t") + if t == "touch": + if v.get("phase") not in ("down", "move", "up"): + raise ValueError("'phase' must be down, move or up") + return ("touch", v["phase"], _coord(v, "x"), _coord(v, "y")) + if t == "tap": + return ("tap", _coord(v, "x"), _coord(v, "y")) + if t == "swipe": + ms = v.get("ms", 300) + ms = min(max(int(ms), 50), 5000) if isinstance(ms, int) and not isinstance(ms, bool) else 300 + return ("swipe", _coord(v, "x1"), _coord(v, "y1"), _coord(v, "x2"), _coord(v, "y2"), ms) + if t == "button": + name = v.get("name", "") + if name not in BUTTONS: + raise ValueError(f"Unknown button '{name}'. Use one of: home, lock, volume-up, volume-down, mute, siri") + return ("button", name) + if t == "key": + usage = v.get("usage") + if isinstance(usage, bool) or not isinstance(usage, int) or not 4 <= usage <= 0xE7: + raise ValueError("'usage' must be a HID keyboard usage (4–231)") + if not isinstance(v.get("down"), bool): + raise ValueError("'down' must be true or false") + return ("key", usage, v["down"]) + if t == "text": + text = v.get("text") + if not isinstance(text, str): + raise ValueError("'text' must be a string") + if len(text) > 2000: + raise ValueError("Type at most 2000 characters at a time") + return ("text", text) + if t == "keyframe": + return ("keyframe",) + raise ValueError("'t' must be touch, tap, swipe, button, key, text or keyframe") + + +_SHIFTED_DIGITS = "!@#$%^&*()" +_PUNCT = {"-": "_", "=": "+", "[": "{", "]": "}", "\\": "|", ";": ":", "'": '"', "`": "~", ",": "<", ".": ">", "/": "?"} +_PUNCT_USAGE = dict(zip(_PUNCT, (0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38))) + + +def char_usage(c: str) -> Optional[tuple[int, bool]]: + """HID keyboard usage and whether Shift is needed, for one character (US layout).""" + if "a" <= c <= "z": + return 0x04 + ord(c) - ord("a"), False + if "A" <= c <= "Z": + return 0x04 + ord(c) - ord("A"), True + if "1" <= c <= "9": + return 0x1E + ord(c) - ord("1"), False + fixed = {"0": (0x27, False), "\n": (0x28, False), "\t": (0x2B, False), " ": (0x2C, False)} + if c in fixed: + return fixed[c] + if c and c in _SHIFTED_DIGITS: + return 0x1E + _SHIFTED_DIGITS.index(c), True + for plain, shifted in _PUNCT.items(): + if c in (plain, shifted): + return _PUNCT_USAGE[plain], c == shifted + return None + + +# ---------------------------------------------------------------- HEVC +NAL_VPS, NAL_SPS, NAL_PPS, NAL_AUD, NAL_AP, NAL_FU = 32, 33, 34, 35, 48, 49 +# Apple's display service ends every coded slice with this footer; it is not HEVC data. +APPLE_SLICE_FOOTER = bytes.fromhex("04f00ac0000003000004ec0ab003") + + +def nal_type(nal: bytes) -> int: + return (nal[0] >> 1) & 0x3F if nal else 0xFF + + +def _strip_footer(nal: bytes) -> bytes: + if nal_type(nal) <= 31 and nal.endswith(APPLE_SLICE_FOOTER): + return nal[: -len(APPLE_SLICE_FOOTER)] + return nal + + +class Depacketizer: + """RTP/HEVC (RFC 7798) to whole frames: ``push`` returns ``[(rtp_ts, key, [nal, ...])]``.""" + + def __init__(self) -> None: + self.expect_seq: Optional[int] = None + self.fu: Optional[bytearray] = None + self.cur: list[bytes] = [] + self.cur_ts: Optional[int] = None + self.cur_key = False + self.waiting_for_key = True # after a loss, frames are held back until a keyframe + self.vps = self.sps = self.pps = None + self.config_changed = False + self.lost_packets = 0 + + def push(self, seq: int, ts: int, marker: bool, payload: bytes) -> list: + done: list = [] + if self.expect_seq is not None: + gap = (seq - self.expect_seq) & 0xFFFF + if gap >= 0x8000: + return done # a late duplicate + if gap: + self.lost_packets += gap + self.fu, self.cur, self.cur_key, self.cur_ts = None, [], False, None + self.waiting_for_key = True + self.expect_seq = (seq + 1) & 0xFFFF + if self.cur_ts is not None and self.cur_ts != ts: + self._finish(done) + self.cur_ts = ts + if len(payload) < 2: + return done + t = nal_type(payload) + if t == NAL_AP: + i = 2 + while i + 2 <= len(payload): + n = int.from_bytes(payload[i : i + 2], "big") + i += 2 + if n == 0 or i + n > len(payload): + break + self._add(payload[i : i + n]) + i += n + elif t == NAL_FU: + if len(payload) < 3: + return done + h = payload[2] + if h & 0x80: + self.fu = bytearray([(payload[0] & 0x81) | ((h & 0x3F) << 1), payload[1]]) + payload[3:] + elif self.fu is not None: + self.fu += payload[3:] + if h & 0x40 and self.fu is not None: + self._add(_strip_footer(bytes(self.fu))) + self.fu = None + else: + self._add(_strip_footer(bytes(payload))) + if marker: + self._finish(done) + return done + + def _add(self, nal: bytes) -> None: + t = nal_type(nal) + names = {NAL_VPS: "vps", NAL_SPS: "sps", NAL_PPS: "pps"} + if t in names: + if getattr(self, names[t]) != nal: + setattr(self, names[t], nal) + self.config_changed = True + return + if t == NAL_AUD: + return + if 16 <= t <= 21: + self.cur_key = True + self.cur.append(nal) + + def _finish(self, done: list) -> None: + nals, key, ts = self.cur, self.cur_key, self.cur_ts or 0 + self.cur, self.cur_key, self.cur_ts, self.fu = [], False, None, None + if not nals: + return + if self.waiting_for_key: + if not key or None in (self.vps, self.sps, self.pps): + return + self.waiting_for_key = False + done.append((ts, key, nals)) + + def decoder_config(self) -> Optional[dict]: + if None in (self.vps, self.sps, self.pps): + return None + info = parse_sps(self.sps) + if info is None: + return None + return {"codec": codec_string(info), "hvcc": hvcc(info, self.vps, self.sps, self.pps), "width": info["width"], "height": info["height"]} + + +def rbsp(nal: bytes) -> bytes: + """Remove emulation-prevention bytes (00 00 03 -> 00 00) after the 2-byte NAL header.""" + out, zeros = bytearray(), 0 + for b in nal[2:]: + if zeros >= 2 and b == 3: + zeros = 0 + continue + zeros = zeros + 1 if b == 0 else 0 + out.append(b) + return bytes(out) + + +class _Bits: + def __init__(self, d: bytes) -> None: + self.d, self.pos = d, 0 + + def bits(self, n: int) -> int: + v = 0 + for _ in range(n): + byte = self.d[self.pos // 8] # IndexError on a short SPS: caught by parse_sps + v = (v << 1) | ((byte >> (7 - self.pos % 8)) & 1) + self.pos += 1 + return v + + def ue(self) -> int: + zeros = 0 + while self.bits(1) == 0: + zeros += 1 + if zeros > 31: + raise ValueError("bad exp-Golomb code") + return (1 << zeros) - 1 + self.bits(zeros) + + +def parse_sps(sps: bytes) -> Optional[dict]: + """What the SPS says: the 12-byte general profile_tier_level, size, chroma and bit depths.""" + if nal_type(sps) != NAL_SPS: + return None + d = rbsp(sps) + b = _Bits(d) + try: + b.bits(4) + sub = b.bits(3) + nested = b.bits(1) + ptl = d[b.pos // 8 : b.pos // 8 + 12] + if len(ptl) != 12: + return None + b.pos += 96 + flags = [(b.bits(1), b.bits(1)) for _ in range(sub)] + if sub > 0: + for _ in range(sub, 8): + b.bits(2) + for profile, level in flags: + b.pos += 88 * profile + 8 * level + b.ue() + chroma = b.ue() + if chroma == 3: + b.bits(1) + width, height = b.ue(), b.ue() + if b.bits(1): + left, right, top, bottom = b.ue(), b.ue(), b.ue(), b.ue() + sx, sy = {1: (2, 2), 2: (2, 1)}.get(chroma, (1, 1)) + width, height = max(0, width - sx * (left + right)), max(0, height - sy * (top + bottom)) + depth_luma, depth_chroma = b.ue() + 8, b.ue() + 8 + except (IndexError, ValueError): + return None + return {"ptl": bytes(ptl), "max_sub_layers": sub + 1, "nested": bool(nested), "chroma": chroma, + "depth_luma": depth_luma, "depth_chroma": depth_chroma, "width": width, "height": height} + + +def codec_string(info: dict) -> str: + """WebCodecs / RFC 6381 codec string (ISO/IEC 14496-15 Annex E), e.g. ``hev1.1.6.L180.90``.""" + p = info["ptl"] + compat = int("{:032b}".format(int.from_bytes(p[1:5], "big"))[::-1], 2) + s = f"hev1.{['', 'A', 'B', 'C'][p[0] >> 6]}{p[0] & 0x1F}.{compat:X}.{'H' if p[0] & 0x20 else 'L'}{p[11]}" + constraints = p[5:11].rstrip(b"\0") + return s + "".join(f".{c:X}" for c in constraints) + + +def hvcc(info: dict, vps: bytes, sps: bytes, pps: bytes) -> bytes: + """HEVCDecoderConfigurationRecord (``hvcC``), the WebCodecs ``description`` for HEVC.""" + r = bytearray([1]) + info["ptl"] + r += bytes([0xF0, 0x00, 0xFC, 0xFC | (info["chroma"] & 3), 0xF8 | ((info["depth_luma"] - 8) & 7), + 0xF8 | ((info["depth_chroma"] - 8) & 7), 0, 0]) + r.append(((info["max_sub_layers"] & 7) << 3) | (int(info["nested"]) << 2) | 3) + r.append(3) + for t, nal in ((NAL_VPS, vps), (NAL_SPS, sps), (NAL_PPS, pps)): + r += bytes([0x80 | t]) + (1).to_bytes(2, "big") + len(nal).to_bytes(2, "big") + nal + return bytes(r) + + +def config_message(c: dict) -> bytes: + codec = c["codec"].encode() + return bytes([1]) + struct.pack(">HHB", min(c["width"], 65535), min(c["height"], 65535), len(codec)) + codec + c["hvcc"] + + +def frame_message(key: bool, nals: list, ts_us: int) -> bytes: + return bytes([2, int(key)]) + struct.pack(">Q", ts_us) + b"".join(len(n).to_bytes(4, "big") + n for n in nals) + + +def audio_message(pcm: bytes, ts_us: int) -> bytes: + return bytes([3]) + struct.pack(">Q", ts_us) + pcm + + +# ---------------------------------------------------------------- RTCP (RFC 3550 / 4585) +def _rr_sdes(ours: int, phone: int, highest_seq: int) -> bytes: + """Receiver report plus an empty CNAME, as Xcode sends them; keeps a stream alive.""" + rr = struct.pack(">BBHII4xIIII", 0x81, 201, 7, ours, phone, highest_seq, 0, 0, 0) + return rr + struct.pack(">BBHIBBBB", 0x81, 202, 2, ours, 1, 0, 0, 0) + + +def _keyframe_request(ours: int, phone: int, highest_seq: int, fir_seq: int) -> bytes: + pli = struct.pack(">BBHII", 0x81, 206, 2, ours, phone) + fir = struct.pack(">BBHIIIB3x", 0x84, 206, 4, ours, 0, phone, fir_seq & 0xFF) + return _rr_sdes(ours, phone, highest_seq) + pli + fir + + +def _frame_ack(ours: int, rtp_ts: int) -> bytes: + return struct.pack(">BBHIII", 0x80, 204, 3, ours, 5, rtp_ts) + + +def _rtp(data: bytes) -> Optional[tuple[int, int, bool, bytes]]: + """(seq, timestamp, marker, payload) of an RTP packet, or None for RTCP or junk.""" + if len(data) < 12 or data[0] >> 6 != 2 or 200 <= data[1] <= 206: + return None + off = 12 + 4 * (data[0] & 0x0F) + if data[0] & 0x10: + if off + 4 > len(data): + return None + off += 4 + 4 * int.from_bytes(data[off + 2 : off + 4], "big") + end = len(data) - (data[-1] if data[0] & 0x20 else 0) + if off > end: + return None + seq, ts = struct.unpack(">HI", data[2:8]) + return seq, ts, bool(data[1] & 0x80), data[off:end] + + +class _SeqCounter: + """Extended highest RTP sequence number; a late packet from before a wrap is ignored.""" + + def __init__(self) -> None: + self.value: Optional[int] = None + + def add(self, seq: int) -> None: + if self.value is None: + self.value = seq + return + d = (seq - self.value) & 0xFFFF + if 0 < d < 0x8000: + self.value = (self.value + d) & 0xFFFFFFFF + + +def _stream_config(answer: Any) -> tuple[int, int, int]: + """(phone RTP port, our SSRC, phone SSRC); the answer names them from the phone's side.""" + try: + cfg = answer["connection"]["streamConfig"] + except (KeyError, TypeError): + return 0, 0, 0 + return int(cfg.get("SourcePort", 0)), int(cfg.get("RemoteSSRC", 0)), int(cfg.get("LocalSSRC", 0)) + + +def _status(**kw) -> dict: + s = {"state": "off", "error": None, "simulated": False, "width": None, "height": None, "audio": False, "note": None} + s.update(kw) + return s + + +class _Client: + def __init__(self) -> None: + self.queue: asyncio.Queue = asyncio.Queue(maxsize=512) + self.need_key = True + + +class Mirror: + def __init__(self) -> None: + self.status = _status() + self.session = 0 + self.config: Optional[bytes] = None + self.clients: set[_Client] = set() + self.sim_inputs: list[tuple] = [] + self._live: Optional["_Live"] = None + self._task: Optional[asyncio.Task] = None + + # ---- clients + def subscribe(self) -> _Client: + c = _Client() + self.clients.add(c) + return c + + def unsubscribe(self, c: _Client) -> None: + self.clients.discard(c) + + def _broadcast(self, msg: Any) -> None: + for c in list(self.clients): + if isinstance(msg, (bytes, bytearray)) and msg[0] == 2: + if c.need_key and not msg[1]: + continue + c.need_key = False + try: + c.queue.put_nowait(msg) + except asyncio.QueueFull: # a slow viewer: start it again from the next keyframe + while not c.queue.empty(): + c.queue.get_nowait() + c.need_key = True + if self._live: + self._live.want_key = True + + def _set(self, session: int, **kw) -> None: + if session != self.session: + return + self.status.update(kw) + self._broadcast(json.dumps({"type": "status", "status": self.status})) + + def _ended(self, session: int, error: Optional[str]) -> None: + if session != self.session: + return + self._live, self.config = None, None + self.status = _status(state="error" if error else "off", error=error) + self._broadcast(json.dumps({"type": "status", "status": self.status})) + + # ---- control + async def start(self, simulated: bool, udid: Optional[str], audio: bool) -> dict: + await self._cancel() + self.session += 1 + session = self.session + self.config, self.sim_inputs = None, [] + self.status = _status(state="starting", simulated=simulated) + self._set(session) + if simulated: + self._live = None + self._set(session, state="on", width=1170, height=2532, + note="Simulator: there is no real screen; input is accepted and ignored.") + return dict(self.status) + ready: asyncio.Future = asyncio.get_running_loop().create_future() + self._task = asyncio.create_task(self._run(session, udid, audio, ready)) + try: + await asyncio.wait_for(asyncio.shield(ready), 60) + except asyncio.TimeoutError: + await self.stop() + raise MirrorError("Timed out starting screen mirroring. Unlock the iPhone and try again.") from None + return dict(self.status) + + async def _cancel(self) -> None: + task, self._task = self._task, None + if task and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + + async def stop(self) -> dict: + session = self.session + await self._cancel() + self._ended(session, None) + return dict(self.status) + + def _require(self) -> Optional["_Live"]: + if self.status["state"] != "on": + raise MirrorError("Screen mirroring is not running. Start it first.") + return self._live + + async def input(self, i: tuple) -> None: + live = self._require() + if live is None: # simulator + if len(self.sim_inputs) < 1000: + self.sim_inputs.append(i) + return + await live.apply(i) + + async def screenshot(self) -> bytes: + live = self._require() + if live is None: + raise MirrorError("The simulator has no screen to capture.") + return await live.screenshot() + + async def _run(self, session: int, udid: Optional[str], audio: bool, ready: asyncio.Future) -> None: + error = None + try: + async with AsyncExitStack() as stack: + live = _Live(self, session) + await live.open(stack, udid, audio) + self._live = live + ready.set_result(None) + await live.loop() + except asyncio.CancelledError: + raise + except MirrorError as e: + error = str(e) + except Exception as e: # noqa: BLE001 - shown to the user + log.exception("screen mirroring failed") + from .device.pmd3 import _friendly + + error = _friendly(e) + finally: + if not ready.done(): + ready.set_exception(MirrorError(error or "Screen mirroring stopped.")) + self._ended(session, error) + + +MEDIA_IN_USE_CODE = 9022 + + +class _Live: + """One mirroring session with a real iPhone.""" + + def __init__(self, m: Mirror, session: int) -> None: + self.m, self.session = m, session + self.want_key = True + self.hid = self.indigo = None + self.held: set[int] = set() + self.kb_id: Optional[int] = None + + async def open(self, stack: AsyncExitStack, udid: Optional[str], audio: bool) -> None: + from pymobiledevice3.lockdown import create_using_usbmux + from pymobiledevice3.remote.core_device.display_service import DisplayService + from pymobiledevice3.remote.core_device.hid_service import IndigoHIDService, UniversalHIDServiceService + from pymobiledevice3.remote.core_device.screen_stream import open_media_receiver + + from .device.pmd3 import Pmd3Driver, _major + + lockdown = await create_using_usbmux(serial=udid, autopair=True) + stack.push_async_callback(lockdown.close) + version = lockdown.product_version + if _major(version) < 27: + raise MirrorError(f"Screen mirroring needs iOS 27 or newer. This iPhone has iOS {version}.") + driver = Pmd3Driver() + self.rsd, _how = await driver._open_rsd(stack, udid or lockdown.udid, lockdown.udid) + mount_note = await driver._try_mount(self.rsd) + try: + self.display = await stack.enter_async_context(DisplayService(self.rsd)) + except Exception as e: # noqa: BLE001 + raise MirrorError(f"The iPhone's screen service is not available ({e}). {mount_note or 'Check that Developer Mode is on.'}") from e + self.video, receiver_ip = open_media_receiver(self.display, (8 << 20, 4 << 20)) + stack.callback(self.video.close) + self.audio_rx, _ = open_media_receiver(self.display, (1 << 20,)) + stack.callback(self.audio_rx.close) + self.sender_ip = self.rsd.service.address[0] + sid = uuid.uuid4() + try: + # The audio stream goes first: it sets up the screen-sharing session the video joins. + a = await self.display.start_audio_stream(receiver_ip, self.audio_rx.port, self.sender_ip, client_session_id=sid) + # shortcut: display 1 is the built-in screen; foldables with two panels would need the active one. + v = await self.display.start_video_stream(receiver_ip, self.video.port, self.sender_ip, display_id=1, client_session_id=sid) + except Exception as e: + if getattr(e, "code", None) == MEDIA_IN_USE_CODE: + raise MirrorError("The iPhone won't share its screen while an app uses the camera or microphone " + "(for example Camera or Voice Memos). Close that app and try again.") from e + raise + stack.push_async_callback(self._stop_streams) + self.a_port, self.a_ours, self.a_phone = _stream_config(a) + self.v_port, self.v_ours, self.v_phone = _stream_config(v) + self.v_ours = self.v_ours or random.getrandbits(32) + + await asyncio.sleep(0.3) # the phone matches HID input to the new stream first + notes = [] + try: + self.hid = await stack.enter_async_context(UniversalHIDServiceService(self.rsd)) + self.indigo = await stack.enter_async_context(IndigoHIDService(self.rsd)) + except Exception: # noqa: BLE001 + log.exception("HID services unavailable") + self.hid = self.indigo = None + notes.append("The iPhone did not accept touch input, so it can only be watched.") + self.decoder = None + if audio: + if sys.platform == "darwin": + from pymobiledevice3.remote.core_device.aac_eld import AAC_ELD_ASC_48K_STEREO_480, AACELDDecoder + + self.decoder = AACELDDecoder(AAC_ELD_ASC_48K_STEREO_480) + else: + notes.append("The browser edition can only play the iPhone's sound on a Mac; the standalone app plays it on Windows.") + self.m._set(self.session, state="on", audio=self.decoder is not None, note=" ".join(notes) or None) + + async def _stop_streams(self) -> None: + with contextlib.suppress(Exception): + await asyncio.wait_for(self.display.stop_media_stream(), 3) + + async def loop(self) -> None: + self.started = time.monotonic() + self.v_seq, self.a_seq = _SeqCounter(), _SeqCounter() + tasks = [asyncio.create_task(c) for c in (self._video(), self._audio(), self._feedback())] + try: + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for t in done: + t.result() + finally: + for t in tasks: + t.cancel() + raise MirrorError("The connection to the iPhone was lost.") + + def _ts(self) -> int: + return int((time.monotonic() - self.started) * 1e6) + + async def _video(self) -> None: + depack = Depacketizer() + while True: + p = _rtp(await self.video.recv(65535)) + if p is None: + continue + self.last_video = time.monotonic() + seq, ts, marker, payload = p + self.v_seq.add(seq) + was_waiting = depack.waiting_for_key + frames = depack.push(seq, ts, marker, payload) + if depack.waiting_for_key and not was_waiting: + self.want_key = True + for rtp_ts, key, nals in frames: + if depack.config_changed: + c = depack.decoder_config() + if c: + self.m._set(self.session, width=c["width"], height=c["height"]) + self.m.config = config_message(c) + self.m._broadcast(self.m.config) + depack.config_changed = False + self.m._broadcast(frame_message(key, nals, self._ts())) + await self._rtcp(self.video, self.v_port, _frame_ack(self.v_ours, rtp_ts)) + + async def _audio(self) -> None: + while True: + p = _rtp(await self.audio_rx.recv(65535)) + if p is None: + continue + self.a_seq.add(p[0]) + if self.decoder is not None: + try: + pcm = self.decoder.decode(p[3]) + except Exception: # noqa: BLE001 - one bad packet + continue + if pcm: + self.m._broadcast(audio_message(pcm, self._ts())) + + async def _rtcp(self, transport, port: int, packet: bytes) -> None: + if port: + with contextlib.suppress(OSError): + await transport.sendto(packet, self.sender_ip, port) + + async def _feedback(self) -> None: + """Receiver reports every second (the phone stops after ~20 s without them) and + rate-limited keyframe requests.""" + fir_seq, last_report, last_request = 0, 0.0, 0.0 + self.last_video = time.monotonic() + while True: + await asyncio.sleep(0.1) + now = time.monotonic() + if now - self.last_video > 4: # a still screen sends nothing: refresh for new viewers + self.want_key, self.last_video = True, now + if self.want_key and now - last_request > 0.7 and self.v_phone: + await self._rtcp(self.video, self.v_port, _keyframe_request(self.v_ours, self.v_phone, self.v_seq.value or 0, fir_seq)) + fir_seq, last_request, self.want_key = fir_seq + 1, now, False + if now - last_report >= 1: + last_report = now + if self.v_phone: + await self._rtcp(self.video, self.v_port, _rr_sdes(self.v_ours, self.v_phone, self.v_seq.value or 0)) + if self.a_phone: + await self._rtcp(self.audio_rx, self.a_port, _rr_sdes(self.a_ours, self.a_phone, self.a_seq.value or 0)) + + # ---- input + async def apply(self, i: tuple) -> None: + from pymobiledevice3.remote.core_device.hid_service import ( + HID_BUTTON_STATE_DOWN, + HID_BUTTON_STATE_UP, + TOUCHSCREEN_STATE_CONTACT, + TOUCHSCREEN_STATE_RELEASE, + ) + + kind = i[0] + if kind == "keyframe": + self.want_key = True + return + if self.hid is None or self.indigo is None: + raise MirrorError("The iPhone did not accept touch input in this session. Stop and start mirroring again.") + if kind == "touch": + state = TOUCHSCREEN_STATE_RELEASE if i[1] == "up" else TOUCHSCREEN_STATE_CONTACT + await self.hid.send_touchscreen(state, i[2], i[3]) + elif kind == "tap": + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, i[1], i[2]) + await asyncio.sleep(0.05) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, i[1], i[2]) + elif kind == "swipe": + x1, y1, x2, y2, ms = i[1:] + steps = max(ms // 16, 2) # ~60 samples a second, so the phone sees a drag with a speed + for n in range(steps + 1): + f = n / steps + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, round(x1 + (x2 - x1) * f), round(y1 + (y2 - y1) * f)) + await asyncio.sleep(0.016) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, x2, y2) + elif kind == "button": + page, usage, hold = BUTTONS[i[1]] + await self.indigo.send_button(page, usage, HID_BUTTON_STATE_DOWN) + await asyncio.sleep(hold) + await self.indigo.send_button(page, usage, HID_BUTTON_STATE_UP) + elif kind == "key": + (self.held.add if i[2] else self.held.discard)(i[1]) + await self._keys(self.held) + elif kind == "text": + for ch in i[1]: + u = char_usage(ch) + if u: + await self._keys({u[0], 0xE1} if u[1] else {u[0]}) + await self._keys(set()) + await asyncio.sleep(0.012) # keystrokes sent back to back get merged + + async def _keys(self, held: set[int]) -> None: + if self.kb_id is None: + self.kb_id = await self.hid.create_keyboard_service() + await self.hid.send_keyboard(self.kb_id, sorted(held)) + + async def screenshot(self) -> bytes: + from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider + from pymobiledevice3.services.dvt.instruments.screenshot import Screenshot + + async with DvtProvider(self.rsd) as dvt, Screenshot(dvt) as shot: + return await shot.get_screenshot() diff --git a/browser/spoofer/server.py b/browser/spoofer/server.py index 6ab1f69..c272df3 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import contextlib import json import logging import uuid @@ -11,7 +12,7 @@ from pathlib import Path from typing import Awaitable, Callable, Literal, Optional -from fastapi import FastAPI, File, HTTPException, Request, UploadFile +from fastapi import FastAPI, File, HTTPException, Request, UploadFile, WebSocket, WebSocketDisconnect from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field @@ -24,6 +25,7 @@ from .device.mock import MockDriver from .device.pmd3 import Pmd3Driver from .gpx_io import parse_gpx, safe_filename, write_gpx +from .mirror import Mirror, MirrorError, parse_input from .player import Player from .profile import ( Leg, @@ -62,6 +64,7 @@ def __init__(self) -> None: self.updater = Updater() # replaced by __main__ with the real one; disabled from source self.offline = Offline(data_dir()) self.feature_tests = FeatureTests(data_dir()) + self.mirror = Mirror() @property def driver(self) -> DeviceDriver: @@ -93,6 +96,7 @@ async def lifespan(app: FastAPI): yield upd_task.cancel() try: + await app.state.s.mirror.stop() await app.state.s.player.stop() for d in app.state.s.drivers.values(): await d.disconnect() @@ -144,6 +148,11 @@ async def _feature_test_error(_: Request, exc: FeatureTestError): return JSONResponse({"detail": str(exc)}, status_code=exc.status) +@app.exception_handler(MirrorError) +async def _mirror_error(_: Request, exc: MirrorError): + return JSONResponse({"detail": str(exc)}, status_code=409) + + @app.exception_handler(ValueError) async def _value_error(_: Request, exc: ValueError): return JSONResponse({"detail": str(exc)}, status_code=400) @@ -862,3 +871,75 @@ async def index(): app.mount("/static", StaticFiles(directory=STATIC), name="static") + + +# ---------------------------------------------------------------- screen mirroring +class MirrorStartIn(BaseModel): + driver: Optional[Literal["pmd3", "cli", "mock"]] = None + udid: Optional[str] = None + audio: bool = True + + +@app.get("/api/mirror") +async def mirror_status(): + return S().mirror.status + + +@app.post("/api/mirror/start") +async def mirror_start(body: MirrorStartIn): + s = S() + driver = body.driver or s.driver_key + udid = body.udid or (s.driver.info.udid if s.driver.info else None) + return await s.mirror.start(driver == "mock", udid, body.audio) + + +@app.post("/api/mirror/stop") +async def mirror_stop(): + return await S().mirror.stop() + + +@app.post("/api/mirror/input") +async def mirror_input(body: dict): + await S().mirror.input(parse_input(body)) + return {"ok": True} + + +@app.get("/api/mirror/screenshot") +async def mirror_screenshot(): + return Response(await S().mirror.screenshot(), media_type="image/png", headers={"Cache-Control": "no-store"}) + + +@app.websocket("/api/mirror/ws") +async def mirror_ws(ws: WebSocket): + """Live picture, sound and status for the Mirror tab or another program; input goes the other way.""" + # HTTP middleware does not run for WebSockets, so the local-only check is repeated here. + if not _is_local_request(ws.headers.get("host", ""), ws.headers.get("origin", "")): + await ws.close(code=1008) + return + await ws.accept() + m = S().mirror + client = m.subscribe() + await ws.send_text(json.dumps({"type": "status", "status": m.status})) + if m.config: + await ws.send_bytes(m.config) + with contextlib.suppress(MirrorError): + await m.input(("keyframe",)) + + async def send() -> None: + while True: + msg = await client.queue.get() + await (ws.send_text(msg) if isinstance(msg, str) else ws.send_bytes(msg)) + + sender = asyncio.create_task(send()) + try: + while True: + text = await ws.receive_text() + try: + await m.input(parse_input(json.loads(text))) + except (ValueError, MirrorError, DeviceError) as e: + await ws.send_text(json.dumps({"type": "error", "detail": str(e)})) + except (WebSocketDisconnect, RuntimeError): + pass + finally: + sender.cancel() + m.unsubscribe(client) diff --git a/browser/tests/test_mirror.py b/browser/tests/test_mirror.py new file mode 100644 index 0000000..54f4b1f --- /dev/null +++ b/browser/tests/test_mirror.py @@ -0,0 +1,168 @@ +"""Screen mirroring: input parsing, HEVC framing and the simulated session (same cases as the standalone).""" + +import json +import struct + +import pytest +from fastapi.testclient import TestClient + +from spoofer import mirror as mi + + +class _Writer: + def __init__(self): + self.bits = [] + + def put(self, v, n): + self.bits += [(v >> i) & 1 for i in reversed(range(n))] + + def ue(self, v): + x = v + 1 + n = x.bit_length() + self.put(0, n - 1) + self.put(x, n) + + def finish(self): + self.bits += [0] * (-len(self.bits) % 8) + return bytes(int("".join(map(str, self.bits[i : i + 8])), 2) for i in range(0, len(self.bits), 8)) + + +def sample_sps(): + """A 1170x2532 Main-profile SPS (level 6.0), with emulation prevention as an encoder adds it.""" + w = _Writer() + w.put(0, 4); w.put(0, 3); w.put(1, 1) + w.put(0, 2); w.put(0, 1); w.put(1, 5); w.put(0x60000000, 32); w.put(0x90, 8); w.put(0, 40); w.put(180, 8) + w.ue(0); w.ue(1); w.ue(1184); w.ue(2544) + w.put(1, 1); w.ue(0); w.ue(7); w.ue(0); w.ue(6) + w.ue(0); w.ue(0); w.put(1, 1) + nal, zeros = bytearray([mi.NAL_SPS << 1, 1]), 0 + for b in w.finish(): + if zeros >= 2 and b <= 3: + nal.append(3) + zeros = 0 + zeros = zeros + 1 if b == 0 else 0 + nal.append(b) + return bytes(nal) + + +def nal(t, body=b""): + return bytes([t << 1, 1]) + body + + +def with_params(d, seq=0): + for n in (nal(mi.NAL_VPS, b"\1"), sample_sps(), nal(mi.NAL_PPS, b"\2")): + d.push(seq, 1000, False, n) + seq += 1 + return seq + + +def test_parses_sps_codec_and_hvcc(): + info = mi.parse_sps(sample_sps()) + assert (info["width"], info["height"], info["chroma"]) == (1170, 2532, 1) + assert mi.codec_string(info) == "hev1.1.6.L180.90" + r = mi.hvcc(info, nal(32, b"\xaa"), sample_sps(), nal(34, b"\xbb")) + assert r[0] == 1 and r[1:13] == info["ptl"] and r[16] == 0xFD and r[21] & 3 == 3 and r[22] == 3 + assert r[23] == 0x80 | 32 and r.endswith(nal(34, b"\xbb")) + assert mi.parse_sps(sample_sps()[:8]) is None + + +def test_frames_fragments_and_footer(): + d = mi.Depacketizer() + seq = with_params(d) + out = d.push(seq, 1000, True, nal(19, b"\x09\x09") + mi.APPLE_SLICE_FOOTER) + assert out == [(1000, True, [nal(19, b"\x09\x09")])] and d.config_changed + assert d.decoder_config()["width"] == 1170 + body = bytes(range(30)) + fu = lambda s, e, part: bytes([mi.NAL_FU << 1, 1, (0x80 if s else 0) | (0x40 if e else 0) | 1]) + part + assert d.push(seq + 1, 2000, False, fu(True, False, body[:10])) == [] + assert d.push(seq + 2, 2000, False, fu(False, False, body[10:20])) == [] + assert d.push(seq + 3, 2000, True, fu(False, True, body[20:])) == [(2000, False, [nal(1, body)])] + sei, idr = nal(39, b"\5"), nal(19, b"\1\2") + ap = bytes([mi.NAL_AP << 1, 1]) + b"".join(len(n).to_bytes(2, "big") + n for n in (sei, idr)) + assert d.push(seq + 4, 3000, True, ap) == [(3000, True, [sei, idr])] + + +def test_loss_holds_frames_until_keyframe(): + d = mi.Depacketizer() + seq = with_params(d) + assert len(d.push(seq, 1, True, nal(19, b"\1"))) == 1 + assert d.push(seq + 2, 2, True, nal(1, b"\1")) == [] and d.waiting_for_key and d.lost_packets == 1 + assert d.push(seq + 3, 3, True, nal(1, b"\1")) == [] + assert d.push(seq + 4, 4, True, nal(20, b"\1"))[0][1] is True + assert d.push(seq + 1, 2, True, nal(1, b"\1")) == [] # late duplicate + assert d.push(seq + 5, 10, False, nal(1, b"\1")) == [] + assert d.push(seq + 6, 11, False, nal(1, b"\2"))[0][0] == 10 # a new timestamp ends the frame + + +def test_inputs_and_keys(): + assert mi.parse_input({"t": "touch", "phase": "down", "x": 0.5, "y": 1}) == ("touch", "down", 32768, 65535) + assert mi.parse_input({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})[-1] == 300 + assert mi.parse_input({"t": "key", "usage": 40, "down": False}) == ("key", 40, False) + for bad in ({"t": "tap", "x": 1.5, "y": 0}, {"t": "tap", "x": "0.2", "y": 0}, {"t": "touch", "phase": "hover", "x": 0, "y": 0}, + {"t": "button", "name": "power"}, {"t": "key", "usage": 1, "down": True}, {"t": "fly"}, []): + with pytest.raises(ValueError): + mi.parse_input(bad) + assert [mi.char_usage(c) for c in "aZ0(?/"] == [(4, False), (0x1D, True), (0x27, False), (0x26, True), (0x38, True), (0x38, False)] + assert mi.char_usage("é") is None + + +def test_message_layouts_match_the_standalone(): + c = {"codec": "hev1.1.6.L180.90", "hvcc": b"\1\2", "width": 1170, "height": 2532} + assert mi.config_message(c) == bytes([1, 0x04, 0x92, 0x09, 0xE4, 16]) + b"hev1.1.6.L180.90\1\2" + assert mi.frame_message(True, [b"\x26\1\7"], 5) == bytes([2, 1]) + struct.pack(">Q", 5) + b"\0\0\0\3\x26\1\7" + assert mi.audio_message(b"\1\0", 2) == bytes([3]) + struct.pack(">Q", 2) + b"\1\0" + + +def test_rtcp_and_rtp_helpers(): + assert len(mi._rr_sdes(1, 2, 3)) == 44 and mi._rr_sdes(1, 2, 3)[1] == 201 + kf = mi._keyframe_request(1, 2, 3, 4) + assert len(kf) == 44 + 12 + 20 and kf[45] == 206 + assert mi._frame_ack(7, 9) == struct.pack(">BBHIII", 0x80, 204, 3, 7, 5, 9) + pkt = bytes([0x80, 0x80 | 100]) + struct.pack(">HII", 7, 99, 1) + b"payload" + assert mi._rtp(pkt) == (7, 99, True, b"payload") + assert mi._rtp(bytes([0x80, 201]) + bytes(10)) is None + s = mi._SeqCounter() + for seq in (65534, 65535, 0, 1, 65535, 2): + s.add(seq) + assert s.value == 0x10002 + answer = {"connection": {"streamConfig": {"SourcePort": 50001, "LocalSSRC": 7, "RemoteSSRC": 9}}} + assert mi._stream_config(answer) == (50001, 9, 7) and mi._stream_config(None) == (0, 0, 0) + + +@pytest.fixture() +def client(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + yield c + + +def test_mirror_routes_with_the_simulator(client): + assert client.get("/api/mirror").json()["state"] == "off" + assert client.post("/api/mirror/input", json={"t": "tap", "x": 0.5, "y": 0.5}).status_code == 409 + s = client.post("/api/mirror/start", json={"driver": "mock"}).json() + assert (s["state"], s["simulated"], s["width"]) == ("on", True, 1170) + assert client.post("/api/mirror/input", json={"t": "text", "text": "hi"}).json() == {"ok": True} + assert client.post("/api/mirror/input", json={"t": "tap", "x": 2, "y": 0}).status_code == 400 + assert client.get("/api/mirror/screenshot").status_code == 409 + # The test client sends "Host: testserver" for WebSockets unless told otherwise. + with client.websocket_connect("/api/mirror/ws", headers={"host": "127.0.0.1:8765"}) as ws: + assert json.loads(ws.receive_text())["status"]["state"] == "on" + ws.send_text(json.dumps({"t": "button", "name": "nope"})) + assert json.loads(ws.receive_text())["type"] == "error" + from spoofer import server + + assert ("text", "hi") in server.app.state.s.mirror.sim_inputs + assert client.post("/api/mirror/stop").json()["state"] == "off" + + +def test_websocket_refuses_other_websites(client): + from starlette.websockets import WebSocketDisconnect + + with pytest.raises(WebSocketDisconnect): + with client.websocket_connect("/api/mirror/ws", headers={"host": "127.0.0.1:8765", "origin": "https://evil.example"}) as ws: + ws.receive_text() diff --git a/standalone/Cargo.lock b/standalone/Cargo.lock index ae07316..8ef8f0f 100644 --- a/standalone/Cargo.lock +++ b/standalone/Cargo.lock @@ -96,6 +96,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -115,8 +116,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite", "tower", "tower-layer", "tower-service", @@ -259,6 +262,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -487,6 +492,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "der" version = "0.7.10" @@ -685,6 +696,24 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fdk-aac" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb67e142688083cb9afb63f2424203fc98c4e7afb494bf912b60b55513b177e" +dependencies = [ + "fdk-aac-sys", +] + +[[package]] +name = "fdk-aac-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24516d2611506d5cb1833555adc75f6baf9fe2706b9c13e6fc33a6b22c51ca83" +dependencies = [ + "cc", +] + [[package]] name = "field-offset" version = "0.3.6" @@ -1443,6 +1472,7 @@ dependencies = [ "async-stream", "base64 0.22.1", "chrono", + "flate2", "futures", "indexmap", "jktcp", @@ -1612,6 +1642,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -1679,6 +1719,7 @@ dependencies = [ "axum", "chrono", "dirs", + "fdk-aac", "futures-util", "hex", "idevice", @@ -1703,6 +1744,7 @@ dependencies = [ "tracing", "tracing-subscriber", "url", + "uuid", "webview2-com", "windows-core 0.61.2", "winresource", @@ -3550,6 +3592,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3773,6 +3827,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/standalone/Cargo.toml b/standalone/Cargo.toml index 5183cdf..fad4269 100644 --- a/standalone/Cargo.toml +++ b/standalone/Cargo.toml @@ -20,7 +20,7 @@ store = [] anyhow = "1" thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "fs", "process", "signal"] } -axum = { version = "0.8", features = ["multipart", "json", "query"] } +axum = { version = "0.8", features = ["multipart", "json", "query", "ws"] } serde = { version = "1", features = ["derive"] } serde_json = "1" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] } @@ -54,11 +54,18 @@ idevice = { version = "=0.1.68", default-features = false, features = [ "tss", "amfi", "pair", + "display_stream", ] } +uuid = "1" tao = { version = "0.34", optional = true } wry = { version = "0.53", optional = true } png = { version = "0.17", optional = true } +# AAC-ELD decoder for the iPhone's sound while mirroring. Left out of MinGW builds, whose +# headers clash with FDK's (the release is built with MSVC); those builds mirror without sound. +[target.'cfg(not(all(windows, target_env = "gnu")))'.dependencies] +fdk-aac = "0.8" + # Windows: WebView2 permission handling for the window (the same versions wry uses). [target.'cfg(windows)'.dependencies] webview2-com = { version = "0.38", optional = true } diff --git a/standalone/src/device/idev.rs b/standalone/src/device/idev.rs index ee94a68..aaa1f38 100644 --- a/standalone/src/device/idev.rs +++ b/standalone/src/device/idev.rs @@ -63,7 +63,7 @@ async fn usbmux() -> Result { addr().connect(1).await.map_err(|e| friendly(&e)) } -async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), String> { +pub(crate) async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), String> { let mut mux = usbmux().await?; let devices = mux.get_devices().await.map_err(|e| friendly(&e))?; let dev = match udid { @@ -108,7 +108,7 @@ pub async fn list_devices() -> Result, String> { } /// Pair if this computer has no pairing record for the phone yet (shows "Trust This Computer?"). -async fn ensure_paired(provider: &UsbmuxdProvider) -> Result<(), String> { +pub(crate) async fn ensure_paired(provider: &UsbmuxdProvider) -> Result<(), String> { if provider.get_pairing_file().await.is_ok() { return Ok(()); } @@ -133,7 +133,7 @@ fn random_uuid() -> String { ) } -fn major(v: &str) -> u32 { +pub(crate) fn major(v: &str) -> u32 { v.split('.').next().and_then(|x| x.parse().ok()).unwrap_or(0) } @@ -158,18 +158,13 @@ async fn download(path: &str) -> Result, String> { } /// Mount the Developer Disk Image if it is not mounted yet. Returns a note for the user. -async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result, String> { +pub(crate) async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result, String> { let mut mounter = ImageMounter::connect(provider).await.map_err(|e| friendly(&e))?; let personalized = major(version) >= 17; let kind = if personalized { "Personalized" } else { "Developer" }; if mounter.lookup_image(kind).await.map(|s| !s.is_empty()).unwrap_or(false) { return Ok(None); } - if major(version) >= 27 { - return Err("iOS 27+ installs the developer image as a cryptex, which this version cannot do yet. \ - Mount it once with Xcode or pymobiledevice3, then connect again." - .into()); - } if personalized { let image = download("PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg").await?; let manifest = download("PersonalizedImages/Xcode_iOS_DDI_Personalized/BuildManifest.plist").await?; @@ -178,7 +173,11 @@ async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option= 27 { " If this keeps failing, mount it once with Xcode or the browser edition." } else { "" }; + format!("Could not mount the Developer Disk Image: {}.{hint}", friendly(&e)) + })?; } else { let mut parts: Vec<&str> = version.split('.').collect(); parts.truncate(2); diff --git a/standalone/src/main.rs b/standalone/src/main.rs index 8067d64..3e1d8a9 100644 --- a/standalone/src/main.rs +++ b/standalone/src/main.rs @@ -12,6 +12,7 @@ mod feature_tests; mod geo; mod gmaps_links; mod gpx; +mod mirror; mod offline; mod player; mod profile; diff --git a/standalone/src/mirror/hevc.rs b/standalone/src/mirror/hevc.rs new file mode 100644 index 0000000..0576708 --- /dev/null +++ b/standalone/src/mirror/hevc.rs @@ -0,0 +1,553 @@ +//! RTP/HEVC (RFC 7798) to whole frames for the browser's video decoder. +//! +//! The phone sends its screen as HEVC over plain RTP. This module reassembles the NAL units, +//! groups them into access units (one frame each), keeps the parameter sets (VPS/SPS/PPS) and +//! turns them into what WebCodecs needs: a codec string, an `hvcC` record (ISO/IEC 14496-15 +//! §8.3.3.1) and frames as 4-byte length-prefixed NAL units. + +pub const NAL_VPS: u8 = 32; +pub const NAL_SPS: u8 = 33; +pub const NAL_PPS: u8 = 34; +const NAL_AUD: u8 = 35; +const NAL_AP: u8 = 48; +const NAL_FU: u8 = 49; + +/// Apple's display service ends every coded slice with this 14-byte footer. It is not part of +/// the HEVC bitstream, so it is removed before decoding (a no-op when a stream has none). +pub const APPLE_SLICE_FOOTER: [u8; 14] = [0x04, 0xf0, 0x0a, 0xc0, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0xec, 0x0a, 0xb0, 0x03]; + +pub fn nal_type(nal: &[u8]) -> u8 { + nal.first().map(|b| (b >> 1) & 0x3f).unwrap_or(0xff) +} + +/// IRAP pictures (BLA, IDR, CRA) can be decoded on their own. +fn is_key(t: u8) -> bool { + (16..=21).contains(&t) +} + +fn strip_footer(mut nal: Vec) -> Vec { + if nal_type(&nal) <= 31 && nal.ends_with(&APPLE_SLICE_FOOTER) { + nal.truncate(nal.len() - APPLE_SLICE_FOOTER.len()); + } + nal +} + +/// One decoded-ready frame. +#[derive(Debug, Clone, PartialEq)] +pub struct AccessUnit { + pub rtp_ts: u32, + pub key: bool, + /// Coded slices and SEI, without parameter sets or access-unit delimiters. + pub nals: Vec>, +} + +impl AccessUnit { + /// The frame as WebCodecs expects it in `hvcC` mode: each NAL with a 4-byte big-endian length. + pub fn length_prefixed(&self) -> Vec { + let mut out = Vec::with_capacity(self.nals.iter().map(|n| n.len() + 4).sum()); + for n in &self.nals { + out.extend_from_slice(&(n.len() as u32).to_be_bytes()); + out.extend_from_slice(n); + } + out + } +} + +#[derive(Debug, Default)] +pub struct Depacketizer { + expect_seq: Option, + fu: Option>, + cur: Vec>, + cur_ts: Option, + cur_key: bool, + /// A packet was lost: frames are held back until the next keyframe. + pub waiting_for_key: bool, + pub vps: Option>, + pub sps: Option>, + pub pps: Option>, + /// Set when a parameter set changed; the caller sends a new decoder config and clears it. + pub config_changed: bool, + pub lost_packets: u64, +} + +impl Depacketizer { + pub fn new() -> Self { + Self { waiting_for_key: true, ..Default::default() } + } + + /// Feed one RTP packet. Returns the frames it completed (usually zero or one). + pub fn push(&mut self, seq: u16, ts: u32, marker: bool, payload: &[u8]) -> Vec { + let mut done = Vec::new(); + if let Some(expect) = self.expect_seq { + let gap = seq.wrapping_sub(expect); + if gap >= 0x8000 { + return done; // a late duplicate of a packet already handled + } + if gap != 0 { + self.lost_packets += gap as u64; + self.drop_partial(); + self.waiting_for_key = true; + } + } + self.expect_seq = Some(seq.wrapping_add(1)); + + if self.cur_ts.is_some_and(|t| t != ts) { + self.finish(&mut done); + } + self.cur_ts = Some(ts); + + if payload.len() < 2 { + return done; + } + match nal_type(payload) { + NAL_AP => { + let mut i = 2; + while i + 2 <= payload.len() { + let n = u16::from_be_bytes([payload[i], payload[i + 1]]) as usize; + i += 2; + if n == 0 || i + n > payload.len() { + break; + } + self.add_nal(payload[i..i + n].to_vec()); + i += n; + } + } + NAL_FU => { + if payload.len() < 3 { + return done; + } + let h = payload[2]; + let (start, end, t) = (h & 0x80 != 0, h & 0x40 != 0, h & 0x3f); + if start { + let mut nal = vec![(payload[0] & 0x81) | (t << 1), payload[1]]; + nal.extend_from_slice(&payload[3..]); + self.fu = Some(nal); + } else if let Some(buf) = self.fu.as_mut() { + buf.extend_from_slice(&payload[3..]); + } + if end { + if let Some(nal) = self.fu.take() { + self.add_nal(strip_footer(nal)); + } + } + } + _ => self.add_nal(strip_footer(payload.to_vec())), + } + if marker { + self.finish(&mut done); + } + done + } + + fn add_nal(&mut self, nal: Vec) { + let t = nal_type(&nal); + let slot = match t { + NAL_VPS => Some(&mut self.vps), + NAL_SPS => Some(&mut self.sps), + NAL_PPS => Some(&mut self.pps), + _ => None, + }; + if let Some(slot) = slot { + if slot.as_deref() != Some(&nal[..]) { + *slot = Some(nal); + self.config_changed = true; + } + return; + } + if t == NAL_AUD { + return; + } + if is_key(t) { + self.cur_key = true; + } + self.cur.push(nal); + } + + fn drop_partial(&mut self) { + self.fu = None; + self.cur.clear(); + self.cur_key = false; + self.cur_ts = None; + } + + fn finish(&mut self, done: &mut Vec) { + let nals = std::mem::take(&mut self.cur); + let key = std::mem::replace(&mut self.cur_key, false); + let ts = self.cur_ts.take().unwrap_or(0); + self.fu = None; + if nals.is_empty() { + return; + } + if self.waiting_for_key { + if !key || self.sps.is_none() || self.pps.is_none() || self.vps.is_none() { + return; + } + self.waiting_for_key = false; + } + done.push(AccessUnit { rtp_ts: ts, key, nals }); + } + + /// Codec string, `hvcC` record and picture size for the current parameter sets. + pub fn decoder_config(&self) -> Option { + let (vps, sps, pps) = (self.vps.as_ref()?, self.sps.as_ref()?, self.pps.as_ref()?); + let info = parse_sps(sps)?; + Some(DecoderConfig { codec: info.codec_string(), hvcc: hvcc(&info, vps, sps, pps), width: info.width, height: info.height }) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DecoderConfig { + pub codec: String, + pub hvcc: Vec, + pub width: u32, + pub height: u32, +} + +/// Remove emulation-prevention bytes (00 00 03 -> 00 00) after the 2-byte NAL header. +pub fn rbsp(nal: &[u8]) -> Vec { + let mut out = Vec::with_capacity(nal.len()); + let mut zeros = 0; + for &b in nal.iter().skip(2) { + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out +} + +struct Bits<'a> { + d: &'a [u8], + pos: usize, +} + +impl Bits<'_> { + fn bit(&mut self) -> Option { + let byte = *self.d.get(self.pos / 8)?; + let v = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Some(v as u32) + } + fn bits(&mut self, n: usize) -> Option { + let mut v = 0u64; + for _ in 0..n { + v = (v << 1) | self.bit()? as u64; + } + Some(v) + } + fn ue(&mut self) -> Option { + let mut zeros = 0; + while self.bit()? == 0 { + zeros += 1; + if zeros > 31 { + return None; + } + } + Some(((1u64 << zeros) - 1 + self.bits(zeros)?) as u32) + } +} + +/// What the SPS says about the stream. +#[derive(Debug, Clone, PartialEq)] +pub struct SpsInfo { + /// The 12-byte general profile_tier_level (profile space/tier/idc, compatibility flags, + /// constraint flags, level), exactly as `hvcC` stores it. + pub ptl: [u8; 12], + pub max_sub_layers: u8, + pub temporal_id_nested: bool, + pub chroma_format_idc: u32, + pub bit_depth_luma: u32, + pub bit_depth_chroma: u32, + pub width: u32, + pub height: u32, +} + +pub fn parse_sps(sps: &[u8]) -> Option { + if nal_type(sps) != NAL_SPS { + return None; + } + let d = rbsp(sps); + let mut b = Bits { d: &d, pos: 0 }; + b.bits(4)?; // sps_video_parameter_set_id + let max_sub_layers_minus1 = b.bits(3)? as usize; + let nested = b.bit()? == 1; + let start = b.pos / 8; + let ptl: [u8; 12] = d.get(start..start + 12)?.try_into().ok()?; + b.pos += 96; + let mut profile_present = [false; 8]; + let mut level_present = [false; 8]; + for i in 0..max_sub_layers_minus1 { + profile_present[i] = b.bit()? == 1; + level_present[i] = b.bit()? == 1; + } + if max_sub_layers_minus1 > 0 { + for _ in max_sub_layers_minus1..8 { + b.bits(2)?; + } + } + for i in 0..max_sub_layers_minus1 { + if profile_present[i] { + b.pos += 88; + } + if level_present[i] { + b.pos += 8; + } + } + b.ue()?; // sps_seq_parameter_set_id + let chroma = b.ue()?; + if chroma == 3 { + b.bit()?; // separate_colour_plane_flag + } + let mut width = b.ue()?; + let mut height = b.ue()?; + if b.bit()? == 1 { + // Conformance window, in chroma units. + let (l, r, t, bo) = (b.ue()?, b.ue()?, b.ue()?, b.ue()?); + let (sx, sy) = match chroma { + 1 => (2, 2), + 2 => (2, 1), + _ => (1, 1), + }; + width = width.saturating_sub(sx * (l + r)); + height = height.saturating_sub(sy * (t + bo)); + } + let bit_depth_luma = b.ue()? + 8; + let bit_depth_chroma = b.ue()? + 8; + Some(SpsInfo { + ptl, + max_sub_layers: max_sub_layers_minus1 as u8 + 1, + temporal_id_nested: nested, + chroma_format_idc: chroma, + bit_depth_luma, + bit_depth_chroma, + width, + height, + }) +} + +impl SpsInfo { + /// The WebCodecs / RFC 6381 codec string (ISO/IEC 14496-15 Annex E), e.g. `hev1.1.6.L120.90`. + pub fn codec_string(&self) -> String { + let p = &self.ptl; + let space = p[0] >> 6; + let tier = if p[0] & 0x20 != 0 { 'H' } else { 'L' }; + let idc = p[0] & 0x1f; + let compat = u32::from_be_bytes([p[1], p[2], p[3], p[4]]).reverse_bits(); + let mut s = format!("hev1.{}{}.{:X}.{}{}", ["", "A", "B", "C"][space as usize], idc, compat, tier, p[11]); + let constraints = &p[5..11]; + let used = constraints.iter().rposition(|&c| c != 0).map(|i| i + 1).unwrap_or(0); + for c in &constraints[..used] { + s.push_str(&format!(".{c:X}")); + } + s + } +} + +/// HEVCDecoderConfigurationRecord (`hvcC`), the WebCodecs `description` for HEVC. +pub fn hvcc(info: &SpsInfo, vps: &[u8], sps: &[u8], pps: &[u8]) -> Vec { + let mut r = Vec::with_capacity(64 + vps.len() + sps.len() + pps.len()); + r.push(1); // configurationVersion + r.extend_from_slice(&info.ptl); + r.extend_from_slice(&[0xf0, 0x00]); // reserved + min_spatial_segmentation_idc = 0 + r.push(0xfc); // reserved + parallelismType = 0 (unknown) + r.push(0xfc | (info.chroma_format_idc as u8 & 3)); + r.push(0xf8 | ((info.bit_depth_luma.saturating_sub(8)) as u8 & 7)); + r.push(0xf8 | ((info.bit_depth_chroma.saturating_sub(8)) as u8 & 7)); + r.extend_from_slice(&[0, 0]); // avgFrameRate unknown + // constantFrameRate 0 | numTemporalLayers | temporalIdNested | lengthSizeMinusOne = 3 + r.push(((info.max_sub_layers & 7) << 3) | ((info.temporal_id_nested as u8) << 2) | 3); + r.push(3); + for (t, nal) in [(NAL_VPS, vps), (NAL_SPS, sps), (NAL_PPS, pps)] { + r.push(0x80 | t); // array_completeness = 1: parameter sets only come out of band + r.extend_from_slice(&1u16.to_be_bytes()); + r.extend_from_slice(&(nal.len() as u16).to_be_bytes()); + r.extend_from_slice(nal); + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + + // A real 1170x2532 Main-profile SPS (level 6.0), built to the spec: see `sample_sps`. + fn sample_sps() -> Vec { + // Write an SPS with known values using a tiny bit writer. + let mut w = Writer::default(); + w.put(0, 4); // vps id + w.put(0, 3); // max_sub_layers_minus1 + w.put(1, 1); // temporal_id_nesting + w.put(0, 2); // profile space + w.put(0, 1); // tier + w.put(1, 5); // profile idc = Main + w.put(0x6000_0000, 32); // compatibility flags: Main and Main10 + w.put(0x90, 8); // progressive + frame_only constraint bits + w.put(0, 40); + w.put(180, 8); // level 6.0 + w.ue(0); // sps id + w.ue(1); // chroma 4:2:0 + w.ue(1184); // coded width + w.ue(2544); // coded height + w.put(1, 1); // conformance window + w.ue(0); + w.ue(7); // right: 14 luma px + w.ue(0); + w.ue(6); // bottom: 12 luma px + w.ue(0); // bit depth luma 8 + w.ue(0); // bit depth chroma 8 + w.put(1, 1); // stop bit + let mut nal = vec![NAL_SPS << 1, 1]; + // Emulation prevention, as an encoder would add it. + let mut zeros = 0; + for b in w.finish() { + if zeros >= 2 && b <= 3 { + nal.push(3); + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + nal.push(b); + } + nal + } + + #[derive(Default)] + struct Writer { + bits: Vec, + } + impl Writer { + fn put(&mut self, v: u64, n: usize) { + for i in (0..n).rev() { + self.bits.push(((v >> i) & 1) as u8); + } + } + fn ue(&mut self, v: u32) { + let x = v as u64 + 1; + let len = 64 - x.leading_zeros() as usize; + self.put(0, len - 1); + self.put(x, len); + } + fn finish(mut self) -> Vec { + while self.bits.len() % 8 != 0 { + self.bits.push(0); + } + self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | b)).collect() + } + } + + #[test] + fn parses_sps_size_and_codec() { + let info = parse_sps(&sample_sps()).unwrap(); + assert_eq!((info.width, info.height), (1170, 2532)); + assert_eq!(info.chroma_format_idc, 1); + assert_eq!((info.bit_depth_luma, info.bit_depth_chroma), (8, 8)); + assert_eq!(info.codec_string(), "hev1.1.6.L180.90"); + } + + #[test] + fn hvcc_record_layout() { + let sps = sample_sps(); + let info = parse_sps(&sps).unwrap(); + let vps = vec![NAL_VPS << 1, 1, 0xaa]; + let pps = vec![NAL_PPS << 1, 1, 0xbb]; + let r = hvcc(&info, &vps, &sps, &pps); + assert_eq!(r[0], 1); + assert_eq!(&r[1..13], &info.ptl); + assert_eq!(r[16], 0xfd); // 4:2:0 + assert_eq!(r[21] & 3, 3); // 4-byte lengths + assert_eq!(r[22], 3); + assert_eq!(r[23], 0x80 | NAL_VPS); + assert_eq!(&r[26..28], &3u16.to_be_bytes()); + assert!(r.ends_with(&pps)); + } + + fn slice(t: u8, body: &[u8]) -> Vec { + let mut v = vec![t << 1, 1]; + v.extend_from_slice(body); + v + } + + fn params(d: &mut Depacketizer, seq: &mut u16) { + for nal in [slice(NAL_VPS, &[1]), sample_sps(), slice(NAL_PPS, &[2])] { + d.push(*seq, 1000, false, &nal); + *seq += 1; + } + } + + #[test] + fn single_nal_frames_and_footer() { + let mut d = Depacketizer::new(); + let mut seq = 10; + params(&mut d, &mut seq); + let mut idr = slice(19, &[9, 9, 9]); + idr.extend_from_slice(&APPLE_SLICE_FOOTER); + let out = d.push(seq, 1000, true, &idr); + assert_eq!(out.len(), 1); + assert!(out[0].key); + assert_eq!(out[0].nals, vec![slice(19, &[9, 9, 9])]); + assert!(d.config_changed); + let cfg = d.decoder_config().unwrap(); + assert_eq!((cfg.width, cfg.height), (1170, 2532)); + assert_eq!(out[0].length_prefixed(), [&[0, 0, 0, 5][..], &slice(19, &[9, 9, 9])].concat()); + } + + #[test] + fn fragmented_and_aggregated() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + // An aggregation packet carrying an SEI and a short IDR slice. + let sei = slice(39, &[5]); + let idr = slice(19, &[1, 2]); + let mut ap = vec![NAL_AP << 1, 1]; + for n in [&sei, &idr] { + ap.extend_from_slice(&(n.len() as u16).to_be_bytes()); + ap.extend_from_slice(n); + } + let out = d.push(seq, 2000, true, &ap); + seq += 1; + assert_eq!(out[0].nals, vec![sei.clone(), idr.clone()]); + // A TRAIL_R slice split into three fragments. + let body: Vec = (0..30).collect(); + let fu = |start: bool, end: bool, part: &[u8]| { + let mut v = vec![NAL_FU << 1, 1, (if start { 0x80 } else { 0 }) | (if end { 0x40 } else { 0 }) | 1]; + v.extend_from_slice(part); + v + }; + assert!(d.push(seq, 3000, false, &fu(true, false, &body[..10])).is_empty()); + assert!(d.push(seq + 1, 3000, false, &fu(false, false, &body[10..20])).is_empty()); + let out = d.push(seq + 2, 3000, true, &fu(false, true, &body[20..])); + assert_eq!(out.len(), 1); + assert!(!out[0].key); + assert_eq!(out[0].nals, vec![slice(1, &body)]); + } + + #[test] + fn loss_holds_frames_until_keyframe() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + assert_eq!(d.push(seq, 1, true, &slice(19, &[1])).len(), 1); + // seq + 1 is lost. + assert!(d.push(seq + 2, 2, true, &slice(1, &[1])).is_empty()); + assert!(d.waiting_for_key); + assert_eq!(d.lost_packets, 1); + assert!(d.push(seq + 3, 3, true, &slice(1, &[1])).is_empty()); + let out = d.push(seq + 4, 4, true, &slice(20, &[1])); + assert!(out[0].key && !d.waiting_for_key); + // A late duplicate is ignored. + assert!(d.push(seq + 1, 2, true, &slice(1, &[1])).is_empty()); + } + + #[test] + fn timestamp_change_closes_a_frame_without_marker() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + assert!(d.push(seq, 10, false, &slice(19, &[1])).is_empty()); + let out = d.push(seq + 1, 11, false, &slice(1, &[2])); + assert_eq!(out.len(), 1); + assert_eq!(out[0].rtp_ts, 10); + } +} diff --git a/standalone/src/mirror/mod.rs b/standalone/src/mirror/mod.rs new file mode 100644 index 0000000..e85e9fd --- /dev/null +++ b/standalone/src/mirror/mod.rs @@ -0,0 +1,475 @@ +//! Screen mirroring: the iPhone's screen and sound in the app, and mouse/keyboard control. +//! +//! iOS 27+ streams its display through `com.apple.coredevice.displayservice` (the service Xcode +//! uses) as HEVC over RTP, and its sound as AAC-ELD, inside the developer tunnel. Touches, +//! buttons and keys go back through the CoreDevice HID services, which only accept input while +//! a stream is running. Each session runs on its own thread with its own tunnel, like the +//! location session (the idevice futures are not `Send`). +//! +//! Clients (the Mirror tab, or other programs) read a WebSocket at `/api/mirror/ws`: +//! * binary `[1][width u16][height u16][codec length u8][codec][hvcC]`: decoder setup; +//! * binary `[2][key u8][timestamp µs u64][frame as 4-byte length-prefixed NAL units]`; +//! * binary `[3][timestamp µs u64][PCM s16le, 48 kHz, stereo]`; +//! * text: the status JSON whenever it changes. +//! +//! and send input as JSON (the same body `POST /api/mirror/input` takes), see [`parse_input`]. + +pub mod hevc; + +use serde::Serialize; +use serde_json::{json, Value}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::{broadcast, mpsc, oneshot}; + +/// Hardware buttons: (name, HID usage page, usage, hold in ms). Siri needs a long press. +pub const BUTTONS: [(&str, u64, u64, u64); 6] = [ + ("home", 0x0C, 0x40, 50), + ("lock", 0x0C, 0x30, 50), + ("volume-up", 0x0C, 0xE9, 50), + ("volume-down", 0x0C, 0xEA, 50), + ("mute", 0x0C, 0xE2, 50), + ("siri", 0x0C, 0xCF, 1000), +]; + +#[derive(Debug, Clone, PartialEq)] +pub enum Input { + /// One finger: down, move or up at a point. Coordinates are 0..65535 across the screen. + Touch { phase: Phase, x: u16, y: u16 }, + Tap { x: u16, y: u16 }, + Swipe { x1: u16, y1: u16, x2: u16, y2: u16, ms: u64 }, + Button(&'static str, u64, u64, u64), + /// A HID keyboard usage (page 7) going down or up. + Key { usage: u64, down: bool }, + Text(String), + /// Ask the phone for a fresh full frame (a new viewer, or a decoder error). + KeyFrame, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Phase { + Down, + Move, + Up, +} + +fn coord(v: &Value, k: &str) -> Result { + let f = v.get(k).and_then(Value::as_f64).ok_or(format!("'{k}' must be a number from 0 to 1"))?; + if !(0.0..=1.0).contains(&f) { + return Err(format!("'{k}' must be from 0 to 1 (a fraction of the screen)")); + } + Ok((f * 65535.0).round() as u16) +} + +/// Parse one input message. Coordinates are fractions of the screen (0..1, top left is 0,0). +/// +/// `{"t":"touch","phase":"down|move|up","x":0.5,"y":0.5}`, `{"t":"tap","x":..,"y":..}`, +/// `{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}`, `{"t":"button","name":"home"}`, +/// `{"t":"key","usage":40,"down":true}`, `{"t":"text","text":"hello"}`, `{"t":"keyframe"}`. +pub fn parse_input(v: &Value) -> Result { + let t = v.get("t").and_then(Value::as_str).unwrap_or(""); + Ok(match t { + "touch" => Input::Touch { + phase: match v.get("phase").and_then(Value::as_str) { + Some("down") => Phase::Down, + Some("move") => Phase::Move, + Some("up") => Phase::Up, + _ => return Err("'phase' must be down, move or up".into()), + }, + x: coord(v, "x")?, + y: coord(v, "y")?, + }, + "tap" => Input::Tap { x: coord(v, "x")?, y: coord(v, "y")? }, + "swipe" => Input::Swipe { + x1: coord(v, "x1")?, + y1: coord(v, "y1")?, + x2: coord(v, "x2")?, + y2: coord(v, "y2")?, + ms: v.get("ms").and_then(Value::as_u64).unwrap_or(300).clamp(50, 5000), + }, + "button" => { + let name = v.get("name").and_then(Value::as_str).unwrap_or(""); + let &(n, page, usage, hold) = BUTTONS + .iter() + .find(|b| b.0 == name) + .ok_or(format!("Unknown button '{name}'. Use one of: home, lock, volume-up, volume-down, mute, siri"))?; + Input::Button(n, page, usage, hold) + } + "key" => Input::Key { + usage: v.get("usage").and_then(Value::as_u64).filter(|u| (4..=0xE7).contains(u)).ok_or("'usage' must be a HID keyboard usage (4–231)")?, + down: v.get("down").and_then(Value::as_bool).ok_or("'down' must be true or false")?, + }, + "text" => { + let text = v.get("text").and_then(Value::as_str).ok_or("'text' must be a string")?; + if text.chars().count() > 2000 { + return Err("Type at most 2000 characters at a time".into()); + } + Input::Text(text.into()) + } + "keyframe" => Input::KeyFrame, + _ => return Err("'t' must be touch, tap, swipe, button, key, text or keyframe".into()), + }) +} + +/// HID keyboard usage and whether Shift is needed, for one character (US layout). +pub fn char_usage(c: char) -> Option<(u64, bool)> { + const SHIFTED: &str = "!@#$%^&*()"; + Some(match c { + 'a'..='z' => (0x04 + (c as u64 - 'a' as u64), false), + 'A'..='Z' => (0x04 + (c as u64 - 'A' as u64), true), + '1'..='9' => (0x1E + (c as u64 - '1' as u64), false), + '0' => (0x27, false), + '\n' => (0x28, false), + '\t' => (0x2B, false), + ' ' => (0x2C, false), + _ if SHIFTED.contains(c) => (0x1E + SHIFTED.find(c)? as u64, true), + _ => { + const KEYS: [(char, char, u64); 11] = [ + ('-', '_', 0x2D), ('=', '+', 0x2E), ('[', '{', 0x2F), (']', '}', 0x30), ('\\', '|', 0x31), + (';', ':', 0x33), ('\'', '"', 0x34), ('`', '~', 0x35), (',', '<', 0x36), ('.', '>', 0x37), ('/', '?', 0x38), + ]; + let &(plain, _, u) = KEYS.iter().find(|k| k.0 == c || k.1 == c)?; + (u, c != plain) + } + }) +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Status { + /// off, starting, on or error + pub state: &'static str, + pub error: Option, + pub simulated: bool, + pub width: Option, + pub height: Option, + /// Whether the phone's sound is being sent. + pub audio: bool, + /// Why there is no sound, or no touch control, when there isn't. + pub note: Option, +} + +impl Default for Status { + fn default() -> Self { + Self { state: "off", error: None, simulated: false, width: None, height: None, audio: false, note: None } + } +} + +#[derive(Clone, Debug)] +pub enum Out { + Bin(Arc>), + Text(Arc), +} + +enum Cmd { + Input(Input, oneshot::Sender>), + Screenshot(oneshot::Sender, String>>), +} + +#[derive(Default)] +struct Inner { + status: Status, + cmd: Option>, + /// The last decoder setup message, for viewers that join mid-stream. + config: Option>>, + /// Which session the fields belong to, so a stopped session can't overwrite a new one. + session: u64, + /// Simulator only: the inputs received, for tests and the API's dry runs. + pub sim_inputs: Vec, +} + +pub struct Mirror { + inner: Mutex, + out: broadcast::Sender, +} + +impl Default for Mirror { + fn default() -> Self { + Self { inner: Mutex::default(), out: broadcast::channel(512).0 } + } +} + +impl Mirror { + pub fn status(&self) -> Status { + self.inner.lock().unwrap().status.clone() + } + + pub fn subscribe(&self) -> (broadcast::Receiver, Option>>, Status) { + let rx = self.out.subscribe(); + let g = self.inner.lock().unwrap(); + (rx, g.config.clone(), g.status.clone()) + } + + fn set(&self, session: u64, f: impl FnOnce(&mut Status)) { + let mut g = self.inner.lock().unwrap(); + if g.session != session { + return; + } + f(&mut g.status); + let text = serde_json::to_string(&json!({"type": "status", "status": g.status})).unwrap(); + let _ = self.out.send(Out::Text(Arc::new(text))); + } + + fn send_config(&self, session: u64, msg: Vec) { + let msg = Arc::new(msg); + let mut g = self.inner.lock().unwrap(); + if g.session == session { + g.config = Some(msg.clone()); + let _ = self.out.send(Out::Bin(msg)); + } + } + + fn send(&self, msg: Vec) { + let _ = self.out.send(Out::Bin(Arc::new(msg))); + } + + /// Start mirroring (stopping any earlier session) and wait until the stream runs. + pub async fn start(self: &Arc, simulated: bool, udid: Option, audio: bool) -> Result { + let (tx, rx) = mpsc::unbounded_channel(); + let session = { + let mut g = self.inner.lock().unwrap(); + g.session += 1; + g.cmd = Some(tx); + g.config = None; + g.sim_inputs.clear(); + g.status = Status { state: "starting", simulated, ..Default::default() }; + g.session + }; + self.set(session, |_| {}); + if simulated { + tokio::spawn(simulator(self.clone(), session, rx)); + self.set(session, |s| { + *s = Status { state: "on", simulated: true, width: Some(1170), height: Some(2532), ..Default::default() }; + s.note = Some("Simulator: there is no real screen; input is accepted and ignored.".into()); + }); + return Ok(self.status()); + } + let (ready_tx, ready_rx) = oneshot::channel(); + let me = self.clone(); + std::thread::Builder::new() + .name("iphone-mirror".into()) + .spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build(); + match rt { + Ok(rt) => rt.block_on(session::run(me, session, udid, audio, rx, ready_tx)), + Err(e) => me.ended(session, Some(format!("Could not start the mirroring thread: {e}"))), + } + }) + .map_err(|e| e.to_string())?; + match tokio::time::timeout(Duration::from_secs(60), ready_rx).await { + Ok(Ok(Ok(()))) => Ok(self.status()), + Ok(Ok(Err(e))) => Err(e), + _ => { + self.stop(); + Err("Timed out starting screen mirroring. Unlock the iPhone and try again.".into()) + } + } + } + + pub fn stop(&self) { + let session = { + let mut g = self.inner.lock().unwrap(); + g.cmd = None; // the session sees the closed channel and ends + g.config = None; + g.session + }; + self.set(session, |s| *s = Status::default()); + } + + fn ended(&self, session: u64, error: Option) { + self.set(session, |s| { + *s = Status { state: if error.is_some() { "error" } else { "off" }, error, ..Default::default() }; + }); + let mut g = self.inner.lock().unwrap(); + if g.session == session { + g.cmd = None; + g.config = None; + } + } + + fn command(&self) -> Result, String> { + self.inner.lock().unwrap().cmd.clone().ok_or_else(|| "Screen mirroring is not running. Start it first.".into()) + } + + pub async fn input(&self, input: Input) -> Result<(), String> { + let (tx, rx) = oneshot::channel(); + self.command()?.send(Cmd::Input(input, tx)).map_err(|_| "Screen mirroring stopped.".to_string())?; + tokio::time::timeout(Duration::from_secs(30), rx) + .await + .map_err(|_| "The iPhone did not answer.".to_string())? + .map_err(|_| "Screen mirroring stopped.".to_string())? + } + + pub async fn screenshot(&self) -> Result, String> { + let (tx, rx) = oneshot::channel(); + self.command()?.send(Cmd::Screenshot(tx)).map_err(|_| "Screen mirroring stopped.".to_string())?; + tokio::time::timeout(Duration::from_secs(30), rx) + .await + .map_err(|_| "The iPhone did not answer.".to_string())? + .map_err(|_| "Screen mirroring stopped.".to_string())? + } + + #[cfg(test)] + pub fn sim_inputs(&self) -> Vec { + self.inner.lock().unwrap().sim_inputs.clone() + } +} + +async fn simulator(m: Arc, session: u64, mut rx: mpsc::UnboundedReceiver) { + while let Some(cmd) = rx.recv().await { + match cmd { + Cmd::Input(i, r) => { + let mut g = m.inner.lock().unwrap(); + if g.session == session && g.sim_inputs.len() < 1000 { + g.sim_inputs.push(i); + } + let _ = r.send(Ok(())); + } + Cmd::Screenshot(r) => { + let _ = r.send(Err("The simulator has no screen to capture.".into())); + } + } + } + m.ended(session, None); +} + +/// Decoder setup message for viewers. +pub fn config_message(c: &hevc::DecoderConfig) -> Vec { + let mut m = vec![1]; + m.extend_from_slice(&(c.width.min(65535) as u16).to_be_bytes()); + m.extend_from_slice(&(c.height.min(65535) as u16).to_be_bytes()); + m.push(c.codec.len() as u8); + m.extend_from_slice(c.codec.as_bytes()); + m.extend_from_slice(&c.hvcc); + m +} + +pub fn frame_message(au: &hevc::AccessUnit, ts_us: u64) -> Vec { + let mut m = vec![2, au.key as u8]; + m.extend_from_slice(&ts_us.to_be_bytes()); + m.extend_from_slice(&au.length_prefixed()); + m +} + +pub fn audio_message(pcm: &[i16], ts_us: u64) -> Vec { + let mut m = Vec::with_capacity(9 + pcm.len() * 2); + m.push(3); + m.extend_from_slice(&ts_us.to_be_bytes()); + for s in pcm { + m.extend_from_slice(&s.to_le_bytes()); + } + m +} + +/// AAC-ELD (48 kHz stereo, 480-sample frames, as the phone sends it) to PCM. +pub mod audio { + /// AudioSpecificConfig: AAC-ELD, 48 kHz, stereo, frameLengthFlag = 1 (480 samples). + #[cfg(not(all(windows, target_env = "gnu")))] + pub const ASC: [u8; 4] = [0xF8, 0xE6, 0x50, 0x00]; + + #[cfg(not(all(windows, target_env = "gnu")))] + pub struct Decoder { + dec: fdk_aac::dec::Decoder, + pcm: Vec, + } + + #[cfg(not(all(windows, target_env = "gnu")))] + impl Decoder { + pub fn new() -> Option { + let mut dec = fdk_aac::dec::Decoder::new(fdk_aac::dec::Transport::Raw); + dec.config_raw(&ASC).ok()?; + Some(Self { dec, pcm: vec![0; 4096] }) + } + /// Decode one access unit (one RTP payload) to interleaved stereo samples. + pub fn decode(&mut self, au: &[u8]) -> Option> { + self.dec.fill(au).ok()?; + self.dec.decode_frame(&mut self.pcm).ok()?; + Some(self.pcm[..self.dec.decoded_frame_size()].to_vec()) + } + } + + #[cfg(all(windows, target_env = "gnu"))] + pub struct Decoder; + + #[cfg(all(windows, target_env = "gnu"))] + impl Decoder { + pub fn new() -> Option { + None + } + pub fn decode(&mut self, _au: &[u8]) -> Option> { + None + } + } +} + +mod session; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_inputs() { + assert_eq!( + parse_input(&json!({"t": "touch", "phase": "down", "x": 0.5, "y": 1.0})).unwrap(), + Input::Touch { phase: Phase::Down, x: 32768, y: 65535 } + ); + assert_eq!(parse_input(&json!({"t": "button", "name": "siri"})).unwrap(), Input::Button("siri", 0x0C, 0xCF, 1000)); + assert_eq!(parse_input(&json!({"t": "key", "usage": 40, "down": false})).unwrap(), Input::Key { usage: 40, down: false }); + assert!(matches!(parse_input(&json!({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})).unwrap(), Input::Swipe { ms: 300, .. })); + for bad in [ + json!({"t": "tap", "x": 1.5, "y": 0}), + json!({"t": "tap", "x": "0.2", "y": 0}), + json!({"t": "touch", "phase": "hover", "x": 0, "y": 0}), + json!({"t": "button", "name": "power"}), + json!({"t": "key", "usage": 1, "down": true}), + json!({"t": "fly"}), + ] { + assert!(parse_input(&bad).is_err(), "{bad}"); + } + } + + #[test] + fn characters_map_to_us_keys() { + assert_eq!(char_usage('a'), Some((0x04, false))); + assert_eq!(char_usage('Z'), Some((0x1D, true))); + assert_eq!(char_usage('0'), Some((0x27, false))); + assert_eq!(char_usage('('), Some((0x26, true))); + assert_eq!(char_usage('?'), Some((0x38, true))); + assert_eq!(char_usage('/'), Some((0x38, false))); + assert_eq!(char_usage('é'), None); + } + + #[test] + fn messages_have_the_documented_layout() { + let c = hevc::DecoderConfig { codec: "hev1.1.6.L180.90".into(), hvcc: vec![1, 2], width: 1170, height: 2532 }; + let m = config_message(&c); + assert_eq!(&m[..6], &[1, 0x04, 0x92, 0x09, 0xE4, 16]); + assert_eq!(&m[6..22], b"hev1.1.6.L180.90"); + assert_eq!(&m[22..], &[1, 2]); + let au = hevc::AccessUnit { rtp_ts: 0, key: true, nals: vec![vec![0x26, 1, 7]] }; + assert_eq!(frame_message(&au, 5), [vec![2, 1], 5u64.to_be_bytes().to_vec(), vec![0, 0, 0, 3, 0x26, 1, 7]].concat()); + assert_eq!(audio_message(&[1, -1], 2), [vec![3], 2u64.to_be_bytes().to_vec(), vec![1, 0, 0xff, 0xff]].concat()); + } + + #[tokio::test] + async fn simulated_session_takes_input_and_stops() { + let m = Arc::new(Mirror::default()); + assert!(m.input(Input::KeyFrame).await.is_err()); + let s = m.start(true, None, true).await.unwrap(); + assert_eq!((s.state, s.simulated, s.width), ("on", true, Some(1170))); + m.input(Input::Tap { x: 1, y: 2 }).await.unwrap(); + assert_eq!(m.sim_inputs(), vec![Input::Tap { x: 1, y: 2 }]); + assert!(m.screenshot().await.is_err()); + m.stop(); + assert_eq!(m.status().state, "off"); + assert!(m.input(Input::KeyFrame).await.is_err()); + } + + #[cfg(not(all(windows, target_env = "gnu")))] + #[test] + fn audio_decoder_accepts_the_phone_setup_and_survives_garbage() { + let mut d = audio::Decoder::new().expect("FDK accepts the 480-sample AAC-ELD setup"); + assert!(d.decode(&[0xff; 7]).is_none()); + assert!(d.decode(&[]).is_none()); + } +} diff --git a/standalone/src/mirror/session.rs b/standalone/src/mirror/session.rs new file mode 100644 index 0000000..74319c1 --- /dev/null +++ b/standalone/src/mirror/session.rs @@ -0,0 +1,332 @@ +//! One mirroring session with a real iPhone: tunnel, display stream, HID input, RTCP feedback. +//! Protocol details follow the idevice crate's `displayservice` support (MIT) and +//! pymobiledevice3's notes on what the phone expects. + +use super::{audio, config_message, frame_message, audio_message, hevc, Cmd, Input, Mirror, Phase}; +use crate::device::idev; +use idevice::{ + core_device::{ + build_keyframe_request, build_liveness, build_screen_audio_offer, build_screen_video_offer, build_start_audio_parameters, + build_start_video_parameters, is_rtcp, ButtonState, CallInfoBlob, DisplayServiceClient, IndigoHidClient, ReportBlock, RtpPacket, + UniversalHidServiceClient, TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, + }, + core_device_proxy::CoreDeviceProxy, + dvt::{remote_server::RemoteServerClient, screenshot::ScreenshotClient}, + lockdown::LockdownClient, + provider::IdeviceProvider, + rsd::RsdHandshake, + IdeviceService, ReadWrite, RsdService, +}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::{mpsc, oneshot}; + +/// What Device Hub announces as its own features; the phone's own mask breaks negotiation. +const CLIENT_FEATURES: u64 = 140; +/// Error code CoreDevice returns when Camera or a recording app holds the camera or microphone. +const MEDIA_IN_USE: &str = "9022"; + +type Hid = UniversalHidServiceClient>; +type Indigo = IndigoHidClient>; + +pub(super) async fn run( + m: Arc, + session: u64, + udid: Option, + audio_on: bool, + rx: mpsc::UnboundedReceiver, + ready: oneshot::Sender>, +) { + let mut ready = Some(ready); + let result = stream(&m, session, udid, audio_on, rx, &mut ready).await; + if let Some(r) = ready.take() { + let _ = r.send(Err(result.clone().err().unwrap_or_else(|| "Screen mirroring stopped.".into()))); + } + m.ended(session, result.err()); +} + +/// The `streamConfig` values of a start answer: the phone's RTP port and both SSRCs. +fn stream_config(answer: &plist::Value) -> (u16, u32, u32) { + let cfg = answer.as_dictionary().and_then(|d| d.get("connection")).and_then(|c| c.as_dictionary()).and_then(|c| c.get("streamConfig")); + let num = |k: &str| cfg.and_then(|c| c.as_dictionary()).and_then(|c| c.get(k)).and_then(|v| v.as_unsigned_integer()).unwrap_or(0); + // Named from the phone's side: LocalSSRC is the phone's, RemoteSSRC is ours. + (num("SourcePort") as u16, num("RemoteSSRC") as u32, num("LocalSSRC") as u32) +} + +fn start_error(what: &str, e: idevice::IdeviceError) -> String { + let text = format!("{e:?}"); + if text.contains(MEDIA_IN_USE) { + return "The iPhone won't share its screen while an app uses the camera or microphone (for example Camera or Voice Memos). Close that app and try again.".into(); + } + format!("Could not start the {what} stream: {}", idev::friendly(&e)) +} + +/// Extended highest RTP sequence number (RFC 3550): wrap count in the high 16 bits. +#[derive(Default)] +struct SeqCounter(Option); + +impl SeqCounter { + fn add(&mut self, seq: u16) { + self.0 = Some(match self.0 { + None => seq as u32, + // Only newer packets move it forward; a late one from before a wrap is ignored. + Some(cur) => match seq.wrapping_sub(cur as u16) as i16 { + d if d > 0 => cur.wrapping_add(d as u32), + _ => cur, + }, + }); + } +} + +async fn stream( + m: &Arc, + session: u64, + udid: Option, + audio_on: bool, + mut rx: mpsc::UnboundedReceiver, + ready: &mut Option>>, +) -> Result<(), String> { + let fr = |e: idevice::IdeviceError| idev::friendly(&e); + let (provider, _) = idev::find_device(udid.as_deref()).await?; + idev::ensure_paired(&provider).await?; + let pairing = provider.get_pairing_file().await.map_err(fr)?; + let mut ld = LockdownClient::connect(&provider).await.map_err(fr)?; + ld.start_session(&pairing).await.map_err(fr)?; + let version = ld.get_value(Some("ProductVersion"), None).await.ok().and_then(|v| v.as_string().map(String::from)).unwrap_or_default(); + let chip = ld.get_value(Some("UniqueChipID"), None).await.ok().and_then(|v| v.as_unsigned_integer()); + drop(ld); + if idev::major(&version) < 27 { + return Err(format!("Screen mirroring needs iOS 27 or newer. This iPhone has iOS {version}.")); + } + // A failed mount is reported only if the display service then turns out to be missing. + let ddi = idev::ensure_ddi(&provider, &version, chip).await.err(); + + let proxy = CoreDeviceProxy::connect(&provider).await.map_err(fr)?; + let rsd_port = proxy.tunnel_info().server_rsd_port; + let mut adapter = proxy.create_software_tunnel().map_err(fr)?.to_async_handle(); + let rsd = adapter.connect(rsd_port).await.map_err(|e| format!("Could not open the developer tunnel: {e}"))?; + let mut hs = RsdHandshake::new(rsd).await.map_err(fr)?; + let mut display = DisplayServiceClient::connect_rsd(&mut adapter, &mut hs).await.map_err(|e| match &ddi { + Some(d) => format!("The iPhone's screen service is not available ({}). {d}", fr(e)), + None => format!("The iPhone's screen service is not available: {}. Check that Developer Mode is on.", fr(e)), + })?; + + let audio_udp = adapter.bind_udp(0).await.map_err(|e| e.to_string())?; + let video_udp = adapter.bind_udp(0).await.map_err(|e| e.to_string())?; + let (host, peer) = (adapter.host_ip().to_string(), adapter.peer_ip().to_string()); + // Values from a captured Device Hub offer that the phone accepts. + let call_info = CallInfoBlob { + call_id: 0, + client_version: 1, + device_type: "Mac17,7".into(), + framework_version: "2205.3.1".into(), + os_version: "25F71".into(), + device_name: None, + audio_device_uid: None, + }; + let call_id = || uuid::Uuid::from_bytes(rand::random()).hyphenated().to_string().to_uppercase(); + let session_id = uuid::Uuid::from_bytes(rand::random()); + // The audio stream goes first: it sets up the screen-sharing session the video joins. + let offer = build_screen_audio_offer(&call_id(), &call_info).map_err(fr)?; + let a_params = build_start_audio_parameters(&host, audio_udp.local_port(), &peer, 50000, offer, CLIENT_FEATURES, session_id); + let (a_port, a_ours, a_phone) = stream_config(&display.start_media_stream(a_params).await.map_err(|e| start_error("sound", e))?); + let our_ssrc: u32 = rand::random(); + let offer = build_screen_video_offer(&call_id(), &call_info, our_ssrc).map_err(fr)?; + // shortcut: display 1 is the built-in screen; foldables with two panels would need the active one. + let v_params = build_start_video_parameters(&host, video_udp.local_port(), &peer, 50001, offer, CLIENT_FEATURES, 1, session_id); + let (v_port, v_ours, v_phone) = stream_config(&display.start_media_stream(v_params).await.map_err(|e| start_error("screen", e))?); + let v_ours = if v_ours != 0 { v_ours } else { our_ssrc }; + + // Touch and buttons are refused until the phone has matched them to the new stream. + tokio::time::sleep(Duration::from_millis(300)).await; + let mut hid: Option = UniversalHidServiceClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + let mut indigo: Option = IndigoHidClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + let mut decoder = if audio_on { audio::Decoder::new() } else { None }; + let mut note = Vec::new(); + if hid.is_none() || indigo.is_none() { + note.push("The iPhone did not accept touch input, so it can only be watched."); + } + if audio_on && decoder.is_none() { + note.push("This build of the app cannot play the iPhone's sound."); + } + m.set(session, |s| { + s.state = "on"; + s.audio = decoder.is_some(); + s.note = (!note.is_empty()).then(|| note.join(" ")); + }); + if let Some(r) = ready.take() { + let _ = r.send(Ok(())); + } + + let started = Instant::now(); + let mut depack = hevc::Depacketizer::new(); + let (mut v_seq, mut a_seq) = (SeqCounter::default(), SeqCounter::default()); + let mut last_keyframe_request = Instant::now() - Duration::from_secs(5); + let mut fir_seq = 0u8; + let mut want_key = true; + let mut tick = tokio::time::interval(Duration::from_secs(1)); + let mut last_video = Instant::now(); + + let result = loop { + if want_key && last_keyframe_request.elapsed() > Duration::from_millis(700) && v_phone != 0 { + let block = ReportBlock { source_ssrc: v_phone, highest_seq: v_seq.0.unwrap_or(0), ..Default::default() }; + let _ = video_udp.send_to(v_port, build_keyframe_request(v_ours, "", v_phone, &[block], fir_seq)).await; + fir_seq = fir_seq.wrapping_add(1); + last_keyframe_request = Instant::now(); + want_key = false; + } + tokio::select! { + dg = video_udp.recv() => { + let Ok(dg) = dg else { break Err("The connection to the iPhone was lost.".to_string()) }; + if is_rtcp(&dg.data) { continue; } + let Some(p) = RtpPacket::parse(&dg.data) else { continue }; + last_video = Instant::now(); + v_seq.add(p.sequence_number); + let was_waiting = depack.waiting_for_key; + let frames = depack.push(p.sequence_number, p.timestamp, p.marker, p.payload); + if depack.waiting_for_key && !was_waiting { + want_key = true; // a packet was lost + } + for au in frames { + if depack.config_changed { + if let Some(c) = depack.decoder_config() { + m.set(session, |s| { s.width = Some(c.width); s.height = Some(c.height); }); + m.send_config(session, config_message(&c)); + } + depack.config_changed = false; + } + m.send(frame_message(&au, started.elapsed().as_micros() as u64)); + let _ = video_udp.send_to(v_port, idevice::core_device::build_frame_ack(v_ours, au.rtp_ts)).await; + } + } + dg = audio_udp.recv() => { + let Ok(dg) = dg else { break Err("The connection to the iPhone was lost.".to_string()) }; + if is_rtcp(&dg.data) { continue; } + let Some(p) = RtpPacket::parse(&dg.data) else { continue }; + a_seq.add(p.sequence_number); + if let Some(pcm) = decoder.as_mut().and_then(|d| d.decode(p.payload)) { + m.send(audio_message(&pcm, started.elapsed().as_micros() as u64)); + } + } + _ = tick.tick() => { + // Receiver reports keep both streams alive; without them the phone stops after ~20 s. + if v_phone != 0 { + let b = ReportBlock { source_ssrc: v_phone, highest_seq: v_seq.0.unwrap_or(0), ..Default::default() }; + let _ = video_udp.send_to(v_port, build_liveness(v_ours, "", &[b])).await; + } + if a_phone != 0 && a_port != 0 { + let b = ReportBlock { source_ssrc: a_phone, highest_seq: a_seq.0.unwrap_or(0), ..Default::default() }; + let _ = audio_udp.send_to(a_port, build_liveness(a_ours, "", &[b])).await; + } + if last_video.elapsed() > Duration::from_secs(4) { + want_key = true; // a still screen sends nothing; ask again so new viewers get a picture + last_video = Instant::now(); + } + } + cmd = rx.recv() => match cmd { + None => break Ok(()), + Some(Cmd::Input(Input::KeyFrame, r)) => { want_key = true; let _ = r.send(Ok(())); } + Some(Cmd::Input(i, r)) => { + let res = apply(i, hid.as_mut(), indigo.as_mut()).await; + let _ = r.send(res); + } + Some(Cmd::Screenshot(r)) => { + let _ = r.send(screenshot(&mut adapter, &mut hs).await); + } + } + } + }; + let _ = display.stop_media_stream().await; + result +} + +async fn press(indigo: &mut Indigo, page: u64, usage: u64, hold: u64) -> Result<(), idevice::IdeviceError> { + indigo.send_button(page, usage, ButtonState::Down).await?; + tokio::time::sleep(Duration::from_millis(hold)).await; + indigo.send_button(page, usage, ButtonState::Up).await +} + +async fn key(indigo: &mut Indigo, usage: u64, shift: bool) -> Result<(), idevice::IdeviceError> { + const SHIFT: u64 = 0xE1; + if shift { + indigo.send_keyboard(SHIFT, ButtonState::Down).await?; + } + indigo.send_keyboard(usage, ButtonState::Down).await?; + indigo.send_keyboard(usage, ButtonState::Up).await?; + if shift { + indigo.send_keyboard(SHIFT, ButtonState::Up).await?; + } + // Keystrokes sent back to back get merged. + tokio::time::sleep(Duration::from_millis(12)).await; + Ok(()) +} + +async fn apply(i: Input, hid: Option<&mut Hid>, indigo: Option<&mut Indigo>) -> Result<(), String> { + const NO_CONTROL: &str = "The iPhone did not accept touch input in this session. Stop and start mirroring again."; + let r = match i { + Input::Touch { phase, x, y } => { + let state = if phase == Phase::Up { TOUCHSCREEN_STATE_RELEASE } else { TOUCHSCREEN_STATE_CONTACT }; + hid.ok_or(NO_CONTROL)?.send_touchscreen(state, x, y, None).await + } + Input::Tap { x, y } => hid.ok_or(NO_CONTROL)?.tap(x, y).await, + // ~60 samples a second, so the phone sees a drag with a speed rather than a tap. + Input::Swipe { x1, y1, x2, y2, ms } => hid.ok_or(NO_CONTROL)?.drag(x1, y1, x2, y2, (ms / 16).max(2) as u32, 16).await, + Input::Button(_, page, usage, hold) => press(indigo.ok_or(NO_CONTROL)?, page, usage, hold).await, + Input::Key { usage, down } => { + indigo.ok_or(NO_CONTROL)?.send_keyboard(usage, if down { ButtonState::Down } else { ButtonState::Up }).await + } + Input::Text(text) => { + let indigo = indigo.ok_or(NO_CONTROL)?; + for c in text.chars() { + if let Some((usage, shift)) = super::char_usage(c) { + key(indigo, usage, shift).await.map_err(|e| idev::friendly(&e))?; + } + } + Ok(()) + } + Input::KeyFrame => Ok(()), + }; + r.map_err(|e| idev::friendly(&e)) +} + +async fn screenshot(adapter: &mut idevice::tcp::handle::AdapterHandle, hs: &mut RsdHandshake) -> Result, String> { + let fr = |e: idevice::IdeviceError| idev::friendly(&e); + let mut rs = RemoteServerClient::connect_rsd(adapter, hs).await.map_err(fr)?; + rs.read_message(0).await.map_err(fr)?; + let mut shot = ScreenshotClient::new(&mut rs).await.map_err(fr)?; + shot.take_screenshot().await.map_err(fr) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sequence_numbers_extend_across_wraps() { + let mut s = SeqCounter::default(); + for seq in [65534, 65535, 0, 1, 65535, 2] { + s.add(seq); + } + assert_eq!(s.0, Some(0x1_0002)); + } + + #[test] + fn reads_the_stream_config() { + let answer: plist::Value = plist::Value::Dictionary( + [("connection".to_string(), plist::Value::Dictionary( + [("streamConfig".to_string(), plist::Value::Dictionary( + [("SourcePort", 50001u64), ("LocalSSRC", 7), ("RemoteSSRC", 9)] + .into_iter() + .map(|(k, v)| (k.to_string(), plist::Value::Integer(v.into()))) + .collect(), + ))] + .into_iter() + .collect(), + ))] + .into_iter() + .collect(), + ); + assert_eq!(stream_config(&answer), (50001, 9, 7)); + assert_eq!(stream_config(&plist::Value::Boolean(true)), (0, 0, 0)); + } +} diff --git a/standalone/src/server.rs b/standalone/src/server.rs index 1892c78..d43b2c9 100644 --- a/standalone/src/server.rs +++ b/standalone/src/server.rs @@ -45,6 +45,7 @@ pub struct AppState { pub restart_requested: std::sync::atomic::AtomicBool, pub offline: Arc, pub feature_tests: Arc, + pub mirror: Arc, } pub type App = Arc; @@ -63,6 +64,7 @@ impl AppState { updater: Arc::new(updater), restart: tokio::sync::Notify::new(), restart_requested: std::sync::atomic::AtomicBool::new(false), + mirror: Arc::default(), }) } @@ -152,6 +154,12 @@ pub fn router(app: App) -> Router { .route("/api/feature-tests/lock", post(ft_lock)) .route("/api/feature-tests/open", post(ft_open)) .route("/api/feature-tests/progress", get(ft_progress)) + .route("/api/mirror", get(mirror_status)) + .route("/api/mirror/start", post(mirror_start)) + .route("/api/mirror/stop", post(mirror_stop)) + .route("/api/mirror/input", post(mirror_input)) + .route("/api/mirror/screenshot", get(mirror_screenshot)) + .route("/api/mirror/ws", get(mirror_ws)) .layer(DefaultBodyLimit::max(64 * 1024 * 1024)) .layer(axum::middleware::from_fn(local_only)) .with_state(app) @@ -176,6 +184,107 @@ async fn local_only(req: axum::extract::Request, next: axum::middleware::Next) - next.run(req).await } +// ---------------------------------------------------------------- screen mirroring +async fn mirror_status(State(app): State) -> R { + Ok(Json(json!(app.mirror.status()))) +} + +#[derive(Deserialize)] +struct MirrorStartIn { + driver: Option, + udid: Option, + #[serde(default = "yes")] + audio: bool, +} +fn yes() -> bool { + true +} + +async fn mirror_start(State(app): State, Json(b): Json) -> R { + let (kind, connected) = { + let d = app.devices.lock().await; + (d.kind, d.info().map(|i| i.udid)) + }; + let kind = match b.driver.as_deref() { + Some(k) => DriverKind::parse(k).ok_or(bad("unknown driver"))?, + None => kind, + }; + let udid = b.udid.filter(|s| !s.is_empty()).or(connected); + let s = app.mirror.start(kind == DriverKind::Mock, udid, b.audio).await.map_err(dev)?; + Ok(Json(json!(s))) +} + +async fn mirror_stop(State(app): State) -> R { + app.mirror.stop(); + Ok(Json(json!(app.mirror.status()))) +} + +async fn mirror_input(State(app): State, Json(b): Json) -> R { + let input = crate::mirror::parse_input(&b).map_err(bad)?; + app.mirror.input(input).await.map_err(dev)?; + Ok(Json(json!({"ok": true}))) +} + +async fn mirror_screenshot(State(app): State) -> Result { + let png = app.mirror.screenshot().await.map_err(dev)?; + Ok(([(header::CONTENT_TYPE, "image/png"), (header::CACHE_CONTROL, "no-store")], png).into_response()) +} + +/// Live picture, sound and status for the Mirror tab or another program; input goes the other way. +async fn mirror_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgrade) -> Response { + use axum::extract::ws::Message; + use crate::mirror::Out; + ws.on_upgrade(move |mut socket| async move { + let (mut rx, config, status) = app.mirror.subscribe(); + let status = json!({"type": "status", "status": status}).to_string(); + if socket.send(Message::Text(status.into())).await.is_err() { + return; + } + if let Some(c) = config { + let _ = socket.send(Message::Binary(c.to_vec().into())).await; + } + let _ = app.mirror.input(crate::mirror::Input::KeyFrame).await; + // Frames only make sense from a keyframe on: skip until one arrives (also after falling behind). + let mut need_key = true; + loop { + tokio::select! { + out = rx.recv() => { + let msg = match out { + Ok(Out::Text(t)) => Message::Text(t.as_str().into()), + Ok(Out::Bin(b)) => { + if b[0] == 2 { + if need_key && b[1] == 0 { continue; } + need_key = false; + } + Message::Binary(b.to_vec().into()) + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + need_key = true; + let _ = app.mirror.input(crate::mirror::Input::KeyFrame).await; + continue; + } + Err(_) => break, + }; + if socket.send(msg).await.is_err() { break; } + } + msg = socket.recv() => match msg { + Some(Ok(Message::Text(t))) => { + let reply = match serde_json::from_str::(&t).map_err(|e| e.to_string()).and_then(|v| crate::mirror::parse_input(&v)) { + Ok(i) => app.mirror.input(i).await.err(), + Err(e) => Some(e), + }; + if let Some(e) = reply { + let _ = socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await; + } + } + Some(Ok(_)) => {} + _ => break, + } + } + } + }) +} + // ---------------------------------------------------------------- offline maps /// OpenFreeMap through the local cache (the page rewrites its map requests to /ofm/...). async fn ofm(State(app): State, uri: axum::http::Uri) -> Response { @@ -1129,4 +1238,18 @@ mod tests { let e = build_route_core(app(), r, quiet).await.unwrap_err(); assert_eq!((e.0, e.1.as_str()), (400, "Expected 2 legs, got 1")); } + + #[tokio::test] + async fn mirror_routes_with_the_simulator() { + let a = app(); + let e = mirror_input(State(a.clone()), Json(json!({"t": "tap", "x": 0.5, "y": 0.5}))).await.unwrap_err(); + assert_eq!(e.0, 409); + let start = MirrorStartIn { driver: Some("mock".into()), udid: None, audio: true }; + let s = mirror_start(State(a.clone()), Json(start)).await.unwrap_or_else(|e| panic!("{}", e.1)).0; + assert_eq!((s["state"].as_str(), s["simulated"].as_bool()), (Some("on"), Some(true))); + assert!(mirror_input(State(a.clone()), Json(json!({"t": "text", "text": "hi"}))).await.is_ok()); + assert_eq!(mirror_input(State(a.clone()), Json(json!({"t": "tap", "x": 2, "y": 0}))).await.unwrap_err().0, 400); + assert_eq!(mirror_screenshot(State(a.clone())).await.unwrap_err().0, 409); + assert_eq!(mirror_stop(State(a.clone())).await.unwrap_or_else(|e| panic!("{}", e.1)).0["state"], "off"); + } } From 1ee92c146f0373ccfff0027d8be688c1799ef81d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 16:35:55 +0000 Subject: [PATCH 3/6] Mirror tab: the iPhone's screen, sound and control in the app; local API docs A sixth tab (shortcut 6) swaps the map for the iPhone's screen: - frames decoded with WebCodecs from the hvcC setup the server sends; a clear message when the PC can't decode HEVC; - click to tap, drag to swipe (moves sent once per frame), right-click for Home, buttons for Home, Lock, Volume and Siri; - typing: the picture takes the keyboard while focused (Esc or a click outside gives it back), Ctrl maps to the iPhone's Command key; or send a line of text; - sound played through Web Audio with a small jitter cushion; - screenshots (PNG from the picture) and recordings with sound (MediaRecorder: MP4 where supported, else WebM). docs/API.md documents the local API for other programs: device and location endpoints, mirroring, inputs and the WebSocket format, with examples. README, changelog and roadmap describe the feature. THIRD_PARTY_NOTICES lists FDK AAC with its full licence text in docs/licenses/fdk-aac.txt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdk7FBJL1zvtWFNTApV --- CHANGELOG.md | 3 + README.md | 22 +++- ROADMAP.md | 2 +- THIRD_PARTY_NOTICES.md | 3 +- docs/API.md | 101 +++++++++++++++ docs/licenses/fdk-aac.txt | 92 ++++++++++++++ ui/app.js | 254 ++++++++++++++++++++++++++++++++++++++ ui/index.html | 32 +++++ ui/style.css | 16 ++- 9 files changed, 519 insertions(+), 6 deletions(-) create mode 100644 docs/API.md create mode 100644 docs/licenses/fdk-aac.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 5906107..b057ac2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ Test builds from the `dev` branch are marked as pre-releases. ## Unreleased (dev) ### New +- **Screen mirroring (Mirror tab, iOS 27 and newer):** the iPhone's screen in the app over the USB cable. Click to tap, drag to swipe, right-click for Home, buttons for Home, Lock, Volume and Siri, and typing from your keyboard (Ctrl works as ⌘). The standalone app also plays the iPhone's sound. Save screenshots, or record the screen with its sound as a video. +- **Local API:** other programs on your computer can set the location, watch the screen, tap, swipe and type through the app while it is open (websites can't). See [docs/API.md](docs/API.md). +- **iOS 27:** the standalone app now tries to mount the developer image itself instead of asking for Xcode first. - **New name: Sideport.** Location Spoofer is now called Sideport, because it is growing into a toolkit for working with your iPhone from Windows, not only for its location. Nothing else changes: updating keeps your settings, favourites, routes and offline maps, and the download files keep their names so installed copies keep updating. - **Website:** [iphone-spoofer.vercel.app](https://iphone-spoofer.vercel.app) shows what the app does, has the downloads, and lets you try a small version of it in your browser. The Terms of Use, Privacy Policy and licences now open there (setup guide and *Settings › About*). - **Offline maps:** *Settings › Offline maps* saves the area on screen (up to 3,000 map tiles, about a city, per download; as many areas as you like), so the map works without internet. Saved areas can be shown on the map or deleted. diff --git a/README.md b/README.md index 22c13d8..fdcec49 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

Sideport

A free Windows toolkit for working with your iPhone over USB, with no jailbreak and no Mac.
-Set the iPhone's GPS location: teleport anywhere, drive routes that follow real roads at realistic speeds (with bends, roundabouts and braking), replay GPX files, or walk around live with the keyboard. No accounts, no telemetry.

+Set the iPhone's GPS location: teleport anywhere, drive routes that follow real roads at realistic speeds (with bends, roundabouts and braking), replay GPX files, or walk around live with the keyboard. Mirror the iPhone's screen and sound on your PC, control it with the mouse and keyboard, and record it. Other programs can do the same through a local API. No accounts, no telemetry.

Sideport was previously called Location Spoofer. Updating keeps your settings, favourites and routes.

@@ -38,8 +38,9 @@ Most people should use the **standalone app**. The browser edition exists for iP | Size and start-up | Under 20 MB, starts instantly | About 80 MB, 10–20 s to start | | iOS 17.4 and newer, iOS 16 and older | ✅ | ✅ | | iOS 17.0–17.3 | ❌ | ✅ (needs administrator permission once per session) | +| Screen mirroring and control (iOS 27 and newer) | ✅ with sound | ✅, sound only on a Mac | -Both have the same look and features, and both update themselves. The download files keep their original names (`LocationSpooferStandalone.exe` and `LocationSpooferBrowser.exe`) so copies that are already installed keep updating. +Both have the same look and features (apart from the differences above), and both update themselves. The download files keep their original names (`LocationSpooferStandalone.exe` and `LocationSpooferBrowser.exe`) so copies that are already installed keep updating. ## Getting started @@ -57,7 +58,7 @@ Both have the same look and features, and both update themselves. The download f Requirements * Windows 10 or 11 (64-bit) with the Microsoft Edge WebView2 Runtime, which is built into Windows 11 and installed on up-to-date Windows 10. -* An iPhone or iPad with Developer Mode. +* An iPhone or iPad with Developer Mode. Screen mirroring needs iOS 27 or newer. * A USB cable. * An internet connection for maps and road routing. @@ -76,6 +77,9 @@ Both have the same look and features, and both update themselves. The download f | "My real location" says Windows blocked it | Turn on *Settings › Privacy & security › Location* and "Let desktop apps access your location" (the message has a button for it) | | Location stays wrong after you finish | Press **Stop spoofing**, or restart the iPhone | | The app shows an older version number | An older copy is still running in the background. Close every Sideport window, end any **location-spoofer** or **LocationSpooferStandalone** task in Task Manager, then open the new file | +| Mirroring: "won't share its screen while an app uses the camera or microphone" | Close Camera, Voice Memos or any app that is recording, then press Start mirroring again | +| Mirroring: "can't decode the iPhone's video (HEVC)" | Update the graphics driver, or install *HEVC Video Extensions* from the Microsoft Store | +| Mirroring: the picture stays black | Unlock the iPhone. Some apps hide their content from screen mirroring, for example video streaming apps | | Something else | [Open an issue](https://github.com/YK3D/iPhone-location-spoofer/issues/new) and describe what happened, with the app's version (*Settings › About*) |
@@ -127,6 +131,18 @@ Both have the same look and features, and both update themselves. The download f +
+Screen mirroring and control (Mirror tab) + +* **See the iPhone's screen** live in the app, over the USB cable. Needs iOS 27 or newer. +* **Control it:** click to tap, drag to swipe or scroll, right-click for Home. Buttons for Home, Lock, Volume and Siri. +* **Type:** click the screen and type on your keyboard (Ctrl works as the iPhone's ⌘, so Ctrl+C and Ctrl+V copy and paste on the phone), or send a whole line of text. +* **Sound:** hear what the iPhone plays (standalone app). +* **Screenshots and recordings:** save a picture, or record the screen with its sound as a video file. +* **For developers:** other programs on your computer can watch the screen, tap, type and set the location through the [local API](docs/API.md). + +
+
Comfort and customisation diff --git a/ROADMAP.md b/ROADMAP.md index 391b485..3345679 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -29,4 +29,4 @@ Ideas being considered for future versions. None of them is promised; suggestion - Search history and recent places. - More languages for the interface. - Portable mode (settings stored next to the `.exe`). -- Control the app from scripts, and record and replay test sessions. +- Record and replay test sessions (scripts can already control the app through the [local API](docs/API.md)). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 34a1ce6..70dc39a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -24,7 +24,8 @@ The licences below belong to the third-party components and are not changed by t | Component | Use | Licence | |---|---|---| -| [idevice](https://github.com/jkcoxson/idevice), [jktcp](https://crates.io/crates/jktcp) | iPhone communication (usbmuxd, lockdown, CoreDevice tunnel, DVT) | MIT | +| [idevice](https://github.com/jkcoxson/idevice), [jktcp](https://crates.io/crates/jktcp) | iPhone communication (usbmuxd, lockdown, CoreDevice tunnel, DVT, screen streaming and touch input) | MIT | +| [Fraunhofer FDK AAC](https://github.com/mstorsjo/fdk-aac) through [fdk-aac-rs](https://github.com/haileys/fdk-aac-rs) | Plays the iPhone's sound while mirroring (AAC-ELD decoding) | FDK AAC licence, full text in [docs/licenses/fdk-aac.txt](docs/licenses/fdk-aac.txt) (the Rust bindings are MIT). Included unmodified; its complete source code is available free of charge from [crates.io](https://crates.io/crates/fdk-aac-sys/0.5.0) and [GitHub](https://github.com/mstorsjo/fdk-aac). The licence grants no patent rights | | [wry](https://github.com/tauri-apps/wry), [tao](https://github.com/tauri-apps/tao) | Native window and Microsoft WebView2 | Apache-2.0 OR MIT | | [axum](https://github.com/tokio-rs/axum), [tokio](https://tokio.rs/), [reqwest](https://github.com/seanmonstar/reqwest), [rustls](https://github.com/rustls/rustls), [ring](https://github.com/briansmith/ring) | Local server, networking, TLS | MIT / Apache-2.0 / ISC-style (ring) | | [cssparser](https://github.com/servo/rust-cssparser), [selectors](https://github.com/servo/stylo), [dtoa-short](https://github.com/upsuper/dtoa-short), [option-ext](https://github.com/soc/option-ext) | Used by the window and settings-folder libraries | MPL-2.0. Included unmodified; their source code is available from [crates.io](https://crates.io/) at the versions listed in `standalone/Cargo.lock` | diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..7187ab1 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,101 @@ +# Sideport local API + +While Sideport is open, other programs on the same computer can use the same HTTP API as its own window: connect to the iPhone, set its location, watch its screen and control it. + +* **Address:** `http://127.0.0.1:8766` for the standalone app, `http://127.0.0.1:8765` for the browser edition. Start the app with `--port ` to choose another port; if the standalone app's port is taken by another program, it picks a free one at random. +* **Who can use it:** programs on this computer. Requests must use the host `127.0.0.1` or `localhost`. Requests from websites (any `Origin` header other than the app's own page) are refused with `403`, and the server is not reachable from other computers. +* **Format:** JSON in and out. Errors come back as `{"detail": "message"}` with status `400` (bad request), `409` (the device or mirroring is not ready) or `502` (an online service failed). +* **Stability:** these endpoints are what the app's own window uses. They are kept stable where possible, but check the [changelog](../CHANGELOG.md) when you update. + +## Device and location + +| Method and path | Body | What it does | +|---|---|---| +| `GET /api/status` | | App version, the connected device, playback state | +| `GET /api/devices?driver=pmd3` | | iPhones found over USB (`driver=mock` lists the simulator) | +| `POST /api/connect` | `{"driver": "pmd3", "udid": null}` | Connect (first iPhone when `udid` is null). Use `"mock"` to try things without a phone | +| `POST /api/disconnect` | `{}` | Disconnect | +| `POST /api/location/set` | `{"lat": 51.5007, "lon": -0.1246}` | Set the simulated location | +| `POST /api/location/clear` | `{}` | Back to the real GPS | + +```bash +curl -X POST http://127.0.0.1:8766/api/connect -H "Content-Type: application/json" -d '{"driver":"pmd3"}' +``` + +```bash +curl -X POST http://127.0.0.1:8766/api/location/set -H "Content-Type: application/json" -d '{"lat":48.8584,"lon":2.2945}' +``` + +## Screen mirroring and control + +Needs iOS 27 or newer. The phone only accepts touches and keys while mirroring runs, so start it first (the app's Mirror tab and other programs share one session). + +| Method and path | Body | What it does | +|---|---|---| +| `GET /api/mirror` | | Status: `state` (`off`, `starting`, `on`, `error`), `error`, `simulated`, `width`, `height` (screen pixels), `audio`, `note` | +| `POST /api/mirror/start` | `{"driver": "pmd3", "udid": null, "audio": true}` | Start (all fields optional; defaults to the device the app is connected to). Returns the status once the picture is flowing | +| `POST /api/mirror/stop` | `{}` | Stop | +| `POST /api/mirror/input` | one input, see below | Tap, swipe, press a button or type | +| `GET /api/mirror/screenshot` | | A PNG of the screen, taken by the phone | +| `GET /api/mirror/ws` | WebSocket | Live picture, sound and status; send inputs on it too | + +### Inputs + +Coordinates are fractions of the screen as the phone holds it natively (portrait on an iPhone): `0,0` is the top left, `1,1` the bottom right. Multiply by `width`/`height` from the status to work in pixels. + +| Input | Example | +|---|---| +| Tap | `{"t": "tap", "x": 0.5, "y": 0.9}` | +| Swipe (`ms` 50–5000, default 300) | `{"t": "swipe", "x1": 0.5, "y1": 0.8, "x2": 0.5, "y2": 0.2, "ms": 300}` | +| One finger, step by step | `{"t": "touch", "phase": "down", "x": 0.5, "y": 0.5}`, then `"move"`, then `"up"` | +| Hardware button | `{"t": "button", "name": "home"}`: `home`, `lock`, `volume-up`, `volume-down`, `mute`, `siri` | +| Type text (US keyboard layout, up to 2000 characters) | `{"t": "text", "text": "Hello"}` | +| One key down or up ([HID keyboard usage](https://usb.org/sites/default/files/hut1_5.pdf), page 7) | `{"t": "key", "usage": 40, "down": true}` (40 is Return) | +| Ask for a fresh full frame | `{"t": "keyframe"}` | + +```bash +curl -X POST http://127.0.0.1:8766/api/mirror/start -H "Content-Type: application/json" -d '{}' +``` + +```bash +curl -X POST http://127.0.0.1:8766/api/mirror/input -H "Content-Type: application/json" -d '{"t":"tap","x":0.5,"y":0.5}' +``` + +```bash +curl -o screen.png http://127.0.0.1:8766/api/mirror/screenshot +``` + +### The WebSocket + +`ws://127.0.0.1:8766/api/mirror/ws` sends: + +* **text**: `{"type": "status", "status": {...}}` when the status changes (one straight away), and `{"type": "error", "detail": "..."}` when an input you sent failed; +* **binary**, first byte is the kind, numbers are big-endian: + * `1` decoder setup: `width` (u16), `height` (u16), codec string length (u8), codec string (for example `hev1.1.6.L150.90`), then the HEVC decoder configuration record (`hvcC`); + * `2` frame: keyframe flag (u8, 1 = key), timestamp in microseconds (u64), then the frame as HEVC NAL units, each with a 4-byte length; + * `3` sound: timestamp in microseconds (u64), then PCM: 16-bit little-endian, 48 kHz, stereo, interleaved. + +A new connection gets the decoder setup (if the picture has started) and frames from the next keyframe on. Send inputs as text messages with the same JSON as `POST /api/mirror/input`. + +To decode in a browser, use WebCodecs: `VideoDecoder.configure({codec, description: hvcC})`, then `new EncodedVideoChunk({type: key ? "key" : "delta", timestamp, data})` for each frame. To save the raw stream for a player, write the `hvcC` parameter sets and each NAL unit with `00 00 00 01` start codes instead of lengths; `ffplay` and VLC play the result. + +### Example: Python + +```python +import json, requests +from websockets.sync.client import connect # pip install requests websockets + +base = "http://127.0.0.1:8766" +print(requests.post(f"{base}/api/mirror/start", json={}).json()) +requests.post(f"{base}/api/mirror/input", json={"t": "button", "name": "home"}).raise_for_status() +requests.post(f"{base}/api/mirror/input", json={"t": "swipe", "x1": 0.5, "y1": 0.8, "x2": 0.5, "y2": 0.3}) +open("screen.png", "wb").write(requests.get(f"{base}/api/mirror/screenshot").content) + +with connect("ws://127.0.0.1:8766/api/mirror/ws") as ws: + for _ in range(100): + msg = ws.recv() + if isinstance(msg, str): + print(json.loads(msg)) + elif msg[0] == 2: + print("frame", "key" if msg[1] else "delta", len(msg) - 10, "bytes") +``` diff --git a/docs/licenses/fdk-aac.txt b/docs/licenses/fdk-aac.txt new file mode 100644 index 0000000..05b32bd --- /dev/null +++ b/docs/licenses/fdk-aac.txt @@ -0,0 +1,92 @@ +Software License for The Fraunhofer FDK AAC Codec Library for Android + +© Copyright 1995 - 2018 Fraunhofer-Gesellschaft zur Förderung der angewandten +Forschung e.V. All rights reserved. + + 1. INTRODUCTION +The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software +that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding +scheme for digital audio. This FDK AAC Codec software is intended to be used on +a wide variety of Android devices. + +AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient +general perceptual audio codecs. AAC-ELD is considered the best-performing +full-bandwidth communications codec by independent studies and is widely +deployed. AAC has been standardized by ISO and IEC as part of the MPEG +specifications. + +Patent licenses for necessary patent claims for the FDK AAC Codec (including +those of Fraunhofer) may be obtained through Via Licensing +(www.vialicensing.com) or through the respective patent owners individually for +the purpose of encoding or decoding bit streams in products that are compliant +with the ISO/IEC MPEG audio standards. Please note that most manufacturers of +Android devices already license these patent claims through Via Licensing or +directly from the patent owners, and therefore FDK AAC Codec software may +already be covered under those patent licenses when it is used for those +licensed purposes only. + +Commercially-licensed AAC software libraries, including floating-point versions +with enhanced sound quality, are also available from Fraunhofer. Users are +encouraged to check the Fraunhofer website for additional applications +information and documentation. + +2. COPYRIGHT LICENSE + +Redistribution and use in source and binary forms, with or without modification, +are permitted without payment of copyright license fees provided that you +satisfy the following conditions: + +You must retain the complete text of this software license in redistributions of +the FDK AAC Codec or your modifications thereto in source code form. + +You must retain the complete text of this software license in the documentation +and/or other materials provided with redistributions of the FDK AAC Codec or +your modifications thereto in binary form. You must make available free of +charge copies of the complete source code of the FDK AAC Codec and your +modifications thereto to recipients of copies in binary form. + +The name of Fraunhofer may not be used to endorse or promote products derived +from this library without prior written permission. + +You may not charge copyright license fees for anyone to use, copy or distribute +the FDK AAC Codec software or your modifications thereto. + +Your modified versions of the FDK AAC Codec must carry prominent notices stating +that you changed the software and the date of any change. For modified versions +of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android" +must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK +AAC Codec Library for Android." + +3. NO PATENT LICENSE + +NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without +limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE. +Fraunhofer provides no warranty of patent non-infringement with respect to this +software. + +You may use this FDK AAC Codec software or modifications thereto only for +purposes that are authorized by appropriate patent licenses. + +4. DISCLAIMER + +This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright +holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, +including but not limited to the implied warranties of merchantability and +fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, +or consequential damages, including but not limited to procurement of substitute +goods or services; loss of use, data, or profits, or business interruption, +however caused and on any theory of liability, whether in contract, strict +liability, or tort (including negligence), arising in any way out of the use of +this software, even if advised of the possibility of such damage. + +5. CONTACT INFORMATION + +Fraunhofer Institute for Integrated Circuits IIS +Attention: Audio and Multimedia Departments - FDK AAC LL +Am Wolfsmantel 33 +91058 Erlangen, Germany + +www.iis.fraunhofer.de/amm +amm-info@iis.fraunhofer.de + diff --git a/ui/app.js b/ui/app.js index 541ecea..9787f47 100644 --- a/ui/app.js +++ b/ui/app.js @@ -867,6 +867,12 @@ function openTab(name) { document.querySelectorAll(".tabs button").forEach((x) => x.classList.toggle("active", x.dataset.tab === name)); document.querySelectorAll(".tab-panel").forEach((p) => (p.hidden = p.id !== `tab-${name}`)); map.getContainer().style.cursor = name === "route" ? "crosshair" : ""; + const mirroring = name === "mirror"; + if (document.body.classList.contains("mirroring") !== mirroring) { + document.body.classList.toggle("mirroring", mirroring); + $("mirror-view").hidden = !mirroring; + if (mirroring) fitMirror(); else requestAnimationFrame(() => map.invalidateSize()); + } } document.querySelectorAll(".tabs button").forEach((b) => b.addEventListener("click", () => openTab(b.dataset.tab))); @@ -2609,6 +2615,7 @@ const ACTIONS = [ ["tab-gpx", "3", "GPX tab", () => openTab("gpx")], ["tab-joystick", "4", "Joystick tab", () => openTab("joystick")], ["tab-saved", "5", "Saved tab", () => openTab("saved")], + ["tab-mirror", "6", "Mirror tab", () => openTab("mirror")], ]; const actionById = Object.fromEntries(ACTIONS.map((a) => [a[0], a])); function shortcutMap() { @@ -3220,6 +3227,252 @@ document.addEventListener("pointerdown", (e) => { setTimeout(done, 1200); // in case the animation never runs (hidden button) }, { passive: true }); +// ------------------------------------------------------------------ screen mirroring +// The server sends the phone's screen as HEVC frames (decoded here with WebCodecs) and its sound as +// PCM over /api/mirror/ws; touches and keys go back as JSON. Message layout: see standalone/src/mirror. +const mirror = { ws: null, decoder: null, status: { state: "off" }, audio: null, nextAudio: 0, recorder: null, down: false, typing: false }; +// KeyboardEvent.code -> HID keyboard usage. Ctrl is sent as the iPhone's Command key. +const HID_KEYS = (() => { + const m = { Enter: 40, NumpadEnter: 40, Escape: 41, Backspace: 42, Tab: 43, Space: 44, Minus: 45, Equal: 46, BracketLeft: 47, + BracketRight: 48, Backslash: 49, Semicolon: 51, Quote: 52, Backquote: 53, Comma: 54, Period: 55, Slash: 56, CapsLock: 57, + Home: 74, PageUp: 75, Delete: 76, End: 77, PageDown: 78, ArrowRight: 79, ArrowLeft: 80, ArrowDown: 81, ArrowUp: 82, + ControlLeft: 227, ShiftLeft: 225, AltLeft: 226, MetaLeft: 227, ControlRight: 231, ShiftRight: 229, AltRight: 230, MetaRight: 231 }; + for (let i = 0; i < 26; i++) m[`Key${String.fromCharCode(65 + i)}`] = 4 + i; + for (let i = 1; i <= 9; i++) m[`Digit${i}`] = 29 + i; + m.Digit0 = 39; + return m; +})(); + +function mirrorSend(msg) { + if (mirror.ws && mirror.ws.readyState === 1) mirror.ws.send(JSON.stringify(msg)); +} +function renderMirror(s) { + mirror.status = s; + const on = s.state === "on", busy = s.state === "starting"; + $("btn-mirror").textContent = on ? "Stop mirroring" : busy ? "Starting…" : "Start mirroring"; + $("btn-mirror").classList.toggle("primary", !on); + $("btn-mirror").disabled = busy; + const box = $("mirror-status"); + box.className = "status" + (on ? " ok" : s.state === "error" ? " warn" : ""); + box.textContent = on + ? `Mirroring${s.width ? ` · ${s.width}×${s.height}` : ""}${s.audio ? " · with sound" : ""}${s.note ? `. ${s.note}` : ""}` + : s.state === "error" ? s.error : busy ? "Starting… (unlock the iPhone)" : "Not mirroring"; + for (const b of [...$("mirror-buttons").children, $("btn-mirror-shot"), $("btn-mirror-rec"), $("btn-mirror-type")]) b.disabled = !on; + $("mirror-empty").hidden = on && !s.simulated && $("mirror-canvas").hasAttribute("width"); + if (on && s.simulated) { + $("mirror-empty").textContent = "Simulator: there is no real screen. Clicks and keys are accepted and ignored."; + } else if (!on) { + $("mirror-empty").textContent = s.state === "error" ? s.error : "Press Start mirroring to see the iPhone's screen here."; + } + if (on) mirrorOpen(); + else if (!busy) mirrorClose(); +} + +function fitMirror() { + const c = $("mirror-canvas"), view = $("mirror-view"); + if (!c.width || !c.height) return; + const k = Math.min((view.clientWidth - 32) / c.width, (view.clientHeight - 32) / c.height); + c.style.width = `${Math.max(1, c.width * k)}px`; + c.style.height = `${Math.max(1, c.height * k)}px`; +} +new ResizeObserver(fitMirror).observe($("mirror-view")); + +async function mirrorDecoder(view) { + const w = view.getUint16(1), h = view.getUint16(3), n = view.getUint8(5); + const codec = new TextDecoder().decode(new Uint8Array(view.buffer, 6, n)); + const config = { codec, description: new Uint8Array(view.buffer, 6 + n).slice(), codedWidth: w, codedHeight: h, optimizeForLatency: true }; + if (typeof VideoDecoder === "undefined" || !(await VideoDecoder.isConfigSupported(config)).supported) { + $("mirror-empty").hidden = false; + $("mirror-empty").textContent = "This computer can't decode the iPhone's video (HEVC). Update the graphics driver, or install " + + "“HEVC Video Extensions” from the Microsoft Store, then start mirroring again."; + return; + } + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + const c = $("mirror-canvas"), ctx = c.getContext("2d"); + mirror.decoder = new VideoDecoder({ + output: (frame) => { + if (c.width !== frame.displayWidth || c.height !== frame.displayHeight) { + c.width = frame.displayWidth; + c.height = frame.displayHeight; + fitMirror(); + $("mirror-empty").hidden = true; + } + ctx.drawImage(frame, 0, 0); + frame.close(); + }, + error: () => { mirror.waitKey = true; mirrorSend({ t: "keyframe" }); }, + }); + mirror.decoder.configure(config); + mirror.waitKey = true; +} + +function mirrorAudio(view) { + const a = mirror.audio; + if (!a) return; + const pcm = new Int16Array(view.buffer.slice(9)); + const n = pcm.length / 2; + const buf = a.ctx.createBuffer(2, n, 48000); + const l = buf.getChannelData(0), r = buf.getChannelData(1); + for (let i = 0; i < n; i++) { l[i] = pcm[2 * i] / 32768; r[i] = pcm[2 * i + 1] / 32768; } + const src = a.ctx.createBufferSource(); + src.buffer = buf; + src.connect(a.out); + // A small cushion against network jitter; if playback fell behind, catch up instead of drifting. + const now = a.ctx.currentTime; + if (mirror.nextAudio < now || mirror.nextAudio > now + 0.3) mirror.nextAudio = now + 0.06; + src.start(mirror.nextAudio); + mirror.nextAudio += n / 48000; +} + +function mirrorOpen() { + if (mirror.ws) return; + const ws = new WebSocket(`ws://${location.host}/api/mirror/ws`); + ws.binaryType = "arraybuffer"; + mirror.ws = ws; + ws.onmessage = (e) => { + if (typeof e.data === "string") { + const m = JSON.parse(e.data); + if (m.type === "status") renderMirror(m.status); + else if (m.type === "error") toast(m.detail, true); + return; + } + const v = new DataView(e.data); + const kind = v.getUint8(0); + if (kind === 1) mirrorDecoder(v); + else if (kind === 3) mirrorAudio(v); + else if (kind === 2 && mirror.decoder && mirror.decoder.state === "configured") { + const key = v.getUint8(1) === 1; + if (mirror.waitKey && !key) return; + // Behind by more than a few frames: drop until the next keyframe rather than lag further. + if (!key && mirror.decoder.decodeQueueSize > 6) { mirror.waitKey = true; mirrorSend({ t: "keyframe" }); return; } + mirror.waitKey = false; + mirror.decoder.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp: Number(v.getBigUint64(2)), data: new Uint8Array(e.data, 10) })); + } + }; + ws.onclose = () => { if (mirror.ws === ws) { mirror.ws = null; if (mirror.status.state === "on") setTimeout(mirrorOpen, 1000); } }; +} + +function mirrorClose() { + if (mirror.recorder) mirror.recorder.stop(); + const ws = mirror.ws; + mirror.ws = null; + if (ws) ws.close(); + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = null; + if (mirror.audio) { mirror.audio.ctx.close(); mirror.audio = null; } + const c = $("mirror-canvas"); + c.removeAttribute("width"); + c.removeAttribute("height"); +} + +$("btn-mirror").onclick = guard(async () => { + if (mirror.status.state === "on") { renderMirror(await api("/api/mirror/stop", { body: {} })); return; } + const audio = $("mirror-audio").checked; + if (audio && !mirror.audio) { + // Created on the click: browsers only allow sound that starts from a user action. + const ctx = new AudioContext({ sampleRate: 48000, latencyHint: "interactive" }); + const out = ctx.createGain(); + const tap = ctx.createMediaStreamDestination(); // recordings take the sound from here + out.connect(ctx.destination); + out.connect(tap); + mirror.audio = { ctx, out, tap }; + } + renderMirror({ state: "starting" }); + try { + renderMirror(await api("/api/mirror/start", { body: { driver: $("driver").value, udid: $("device-select").value || null, audio } })); + } catch (e) { + renderMirror({ state: "error", error: e.message }); + throw e; + } +}); + +$("mirror-buttons").onclick = (e) => { + const b = e.target.closest("[data-button]"); + if (b) mirrorSend({ t: "button", name: b.dataset.button }); +}; +$("btn-mirror-type").onclick = guard(async () => { + const text = $("mirror-text").value; + if (!text) return; + await api("/api/mirror/input", { body: { t: "text", text } }); + $("mirror-text").value = ""; +}); +$("mirror-text").addEventListener("keydown", (e) => { if (e.key === "Enter") $("btn-mirror-type").click(); }); + +function saveBlob(blob, name) { + const a = el("a", { href: URL.createObjectURL(blob), download: name }); + document.body.append(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 60000); +} +const stamp = () => new Date().toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-"); +$("btn-mirror-shot").onclick = guard(async () => { + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + saveBlob(await new Promise((r) => c.toBlob(r, "image/png")), `sideport-screenshot-${stamp()}.png`); +}); +$("btn-mirror-rec").onclick = guard(async () => { + const btn = $("btn-mirror-rec"); + if (mirror.recorder) { mirror.recorder.stop(); return; } + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + const stream = c.captureStream(60); + if (mirror.audio) mirror.audio.tap.stream.getAudioTracks().forEach((t) => stream.addTrack(t)); + const type = ["video/mp4;codecs=avc1.640028,mp4a.40.2", "video/mp4", "video/webm;codecs=vp9,opus", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)); + const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 12e6 }); + const parts = []; + rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); }; + rec.onstop = () => { + mirror.recorder = null; + btn.classList.remove("recording"); + btn.querySelector("span").textContent = "Record"; + if (parts.length) saveBlob(new Blob(parts, { type: rec.mimeType }), `sideport-recording-${stamp()}.${rec.mimeType.startsWith("video/mp4") ? "mp4" : "webm"}`); + }; + rec.start(1000); + mirror.recorder = rec; + btn.classList.add("recording"); + btn.querySelector("span").textContent = "Stop recording"; +}); + +// Touch: the pointer's position as a fraction of the picture. +const canvasPoint = (e) => { + const r = $("mirror-canvas").getBoundingClientRect(); + return { x: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)), y: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)) }; +}; +const mc = $("mirror-canvas"); +mc.addEventListener("pointerdown", (e) => { + if (e.button !== 0) return; + mc.setPointerCapture(e.pointerId); + mirror.down = true; + mirrorSend({ t: "touch", phase: "down", ...canvasPoint(e) }); +}); +mc.addEventListener("pointermove", (e) => { + if (!mirror.down) return; + const p = canvasPoint(e); + // Pointer events can come faster than the screen refreshes: send the newest once per frame. + if (!mirror.pending) requestAnimationFrame(() => { mirrorSend({ t: "touch", phase: "move", ...mirror.pending }); mirror.pending = null; }); + mirror.pending = p; +}); +const touchUp = (e) => { + if (!mirror.down) return; + mirror.down = false; + mirror.pending = null; + mirrorSend({ t: "touch", phase: "up", ...canvasPoint(e) }); +}; +mc.addEventListener("pointerup", touchUp); +mc.addEventListener("pointercancel", touchUp); +mc.addEventListener("contextmenu", (e) => { e.preventDefault(); mirrorSend({ t: "button", name: "home" }); }); +// Keys go to the iPhone while the picture has focus (click it); the app's shortcuts stay off meanwhile. +mc.addEventListener("focus", () => mc.classList.add("typing")); +mc.addEventListener("blur", () => { mc.classList.remove("typing"); }); +for (const type of ["keydown", "keyup"]) { + mc.addEventListener(type, (e) => { + if (e.key === "Escape") { mc.blur(); return; } // never trap the keyboard in the picture + const usage = HID_KEYS[e.code]; + e.preventDefault(); + e.stopPropagation(); + if (usage && !(type === "keydown" && e.repeat)) mirrorSend({ t: "key", usage, down: type === "keydown" }); + }); +} + // ------------------------------------------------------------------ boot wireInfoButtons(); wireSections(); @@ -3235,6 +3488,7 @@ function notifyReady() { (async () => { try { await loadStore(); } finally { requestAnimationFrame(() => requestAnimationFrame(notifyReady)); } await refreshGoogleStatus(); + api("/api/mirror").then(renderMirror, () => {}); await poll(); refreshDevices(false); if (!settings().tutorial_done) openTutorial(0); diff --git a/ui/index.html b/ui/index.html index 4c8a04e..936eb11 100644 --- a/ui/index.html +++ b/ui/index.html @@ -69,6 +69,8 @@ + + @@ -145,6 +147,7 @@

Sideport

+ @@ -340,6 +343,31 @@

Sideport

+ + + + diff --git a/ui/style.css b/ui/style.css index 83112fa..e2c5dbb 100644 --- a/ui/style.css +++ b/ui/style.css @@ -255,7 +255,7 @@ details.sub[open] > summary { margin-bottom: 6px; } .stack { display: flex; flex-direction: column; gap: var(--gap); } /* ---------- tabs: a segmented control pinned under the title bar ---------- */ -.tabs { display: grid; grid-template-columns: repeat(5, 1fr); gap: 2px; position: sticky; top: var(--header-h); z-index: 6; +.tabs { display: grid; grid-template-columns: repeat(6, 1fr); gap: 2px; position: sticky; top: var(--header-h); z-index: 6; margin: var(--card-gap) var(--card-inset) 0; padding: 3px; border-radius: var(--radius-lg); background: color-mix(in srgb, var(--side-bg) 70%, var(--panel)); border: 1px solid var(--divider); box-shadow: 0 4px 12px -6px rgba(0, 0, 0, .35); } @@ -866,3 +866,17 @@ p.small.warn { color: var(--warn-text); } .list li a.icon-link { padding: 0; } #dev-access > summary .ico { width: 13px; height: 13px; } #feature-test-list, #offline-areas { max-height: 240px; overflow-y: auto; } + +/* ---------- Mirror tab: the iPhone's screen takes the map's place ---------- */ +#mirror-view { flex: 1; min-height: 300px; position: relative; display: flex; align-items: center; justify-content: center; + padding: 16px; background: var(--bg); overflow: hidden; } +#mirror-view[hidden] { display: none; } +body.mirroring #map { display: none; } +#mirror-canvas { display: block; border-radius: 18px; background: #000; box-shadow: 0 10px 40px -12px rgba(0, 0, 0, .6); + touch-action: none; cursor: pointer; outline: none; } +#mirror-canvas:focus-visible, #mirror-canvas.typing { box-shadow: 0 0 0 3px var(--accent), 0 10px 40px -12px rgba(0, 0, 0, .6); } +#mirror-canvas:not([width]) { display: none; } +.mirror-empty { position: absolute; max-width: 320px; margin: 0; color: var(--muted); text-align: center; font-size: 13px; } +.mirror-buttons button { padding: 0 4px; font-size: 12px; } +#btn-mirror-rec.recording { color: var(--danger); border-color: currentColor; } +@media (max-width: 760px) { #mirror-view { height: 70vh; flex: none; } } From c4ee5d89246e410748ce33556152b0e51e04a0cc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:46:30 +0000 Subject: [PATCH 4/6] Screen section: frozen-picture recovery, rotation, wheel, gestures, stats, save folder; MCP server for AI agents - Picture freezes: the page now rebuilds its decoder after a decoding error (WebCodecs closes it) and on a new stream setup asks for a keyframe (the old code could wait forever); both servers repeat unanswered keyframe requests and restart the stream after three, or after 6 s of silence; inputs (Siri's 1 s hold, swipes, typing) run on their own task so they no longer stall the picture. New "refresh" input restarts it on demand. - "'x' must be a number" error: a touch move could be sent after the finger lifted. - Rotation: the phone's display orientation (CoreDevice getdisplayinfo) as status.rotation; the page turns the picture and maps touches back. Rotate button as a fallback. - Screen is its own section (Location / Screen switch); buttons and gestures (app switcher, Control Centre, Notification Centre, Back) beside the screen; mouse wheel scrolls; touch dot and ripple; Stats overlay (fps, Mbit/s, decode delay, dropped frames, sound buffer). - Screenshots and recordings saved by the app (POST /api/screen/save) to Downloads or the folder chosen in Settings > Screen. - Lock: longer press (unconfirmed on a device). - agents/: stdlib MCP server over the local API, and a skill; Terms and Privacy cover it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdk7FBJL1zvtWFNTApV --- CHANGELOG.md | 3 +- CONTRIBUTING.md | 1 + PRIVACY.md | 4 +- README.md | 13 +- TERMS.md | 2 + agents/sideport_mcp.py | 288 ++++++++++++++++++++ agents/skills/sideport-iphone/SKILL.md | 56 ++++ browser/spoofer/screen.py | 143 ++++++++-- browser/spoofer/server.py | 29 ++ browser/tests/test_mcp.py | 69 +++++ browser/tests/test_screen.py | 43 +++ docs/API.md | 26 +- standalone/src/screen/mod.rs | 18 +- standalone/src/screen/session.rs | 165 ++++++++++-- standalone/src/server.rs | 80 +++++- ui/app.js | 352 +++++++++++++++++++------ ui/index.html | 85 ++++-- ui/style.css | 38 ++- 18 files changed, 1226 insertions(+), 189 deletions(-) create mode 100644 agents/sideport_mcp.py create mode 100644 agents/skills/sideport-iphone/SKILL.md create mode 100644 browser/tests/test_mcp.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1afaa9b..a5b43fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,9 @@ Test builds from the `dev` branch are marked as pre-releases. - Wi-Fi connections: *Device tools › Connect over* (Automatic, USB cable only, Wi-Fi only) and *Allow Wi-Fi connection*, which turns on the phone's "Show this iPhone when on Wi-Fi" setting. The device list shows how each phone can be reached (USB, Wi-Fi, or both). In the browser version, a second iOS 17+ phone or an iOS 17+ phone over Wi-Fi needs the tunnel helper. Bluetooth isn't possible. ### New -- **Screen mirroring (Mirror tab, iOS 27 and newer):** the iPhone's screen in the app over the USB cable. Click to tap, drag to swipe, right-click for Home, buttons for Home, Lock, Volume and Siri, and typing from your keyboard (Ctrl works as ⌘). The standalone app also plays the iPhone's sound. Save screenshots, or record the screen with its sound as a video. +- **Screen mirroring (iOS 27 and newer):** the iPhone's screen in its own *Screen* section (switch at the top of the side menu), over the USB cable. Click to tap, drag to swipe, scroll with the mouse wheel, right-click for Home, and type from your keyboard (Ctrl works as ⌘). Buttons next to the screen press Home, Lock, Volume, Mute and Siri and do the app switcher, Control Centre, Notification Centre and Back gestures; a dot shows where you touch. The picture turns when the phone does (or with *Rotate*). The standalone app also plays the iPhone's sound. Save screenshots, or record the screen with its sound as a video, to Downloads or a folder chosen in *Settings › Screen*. *Stats* shows the frame rate, data rate and decoding delay. A frozen picture restarts by itself after a few seconds, or at once with *Refresh*; holding Siri, swiping or typing no longer stalls the picture. - **Local API:** other programs on your computer can set the location, watch the screen, tap, swipe and type through the app while it is open (websites can't). See [docs/API.md](docs/API.md). +- **AI agents:** an MCP server and a skill let AI agents such as Claude Code or Cursor see the iPhone's screen, tap, swipe, type and set its location through the app. See [docs/API.md](docs/API.md#ai-agents-mcp). - **iOS 27:** the standalone app now tries to mount the developer image itself instead of asking for Xcode first. - **New name: Sideport.** Location Spoofer is now called Sideport, because it is growing into a toolkit for working with your iPhone from Windows, not only for its location. Nothing else changes: updating keeps your settings, favourites, routes and offline maps, and the download files keep their names so installed copies keep updating. - **Website:** [iphone-spoofer.vercel.app](https://iphone-spoofer.vercel.app) shows what the app does, has the downloads, and lets you try a small version of it in your browser. The Terms of Use, Privacy Policy and licences now open there (setup guide and *Settings › About*). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab47f60..a1fd73a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,7 @@ Set `SPOOFER_DATA_DIR` to an empty folder first if you don't want the experiment | `standalone/` | Standalone app (Rust): local server, iPhone driver, routing, speed engine, native window | | `browser/` | Browser edition (Python, FastAPI) | | `ui/` | The interface both editions serve (HTML, CSS, JavaScript; no build step) | +| `agents/` | MCP server for AI agents (Python standard library only, talks to the local API) and its skill; tested by `browser/tests/test_mcp.py` | | `assets/icon/` | Icon artwork; `make_icons.py` regenerates every icon file from `source.jpg` | | `docs/screenshots/` | README screenshots; `capture.js` makes them, and `website/scripts/record-clips.cjs` makes the animation (`demo.webp`) with the website's clips | | `website/` | The showcase website with an in-browser demo (Vite + React, hosted on Vercel); see `website/README.md` | diff --git a/PRIVACY.md b/PRIVACY.md index b04c2a5..5d71080 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -10,8 +10,8 @@ This policy covers both editions of Sideport, formerly called Location Spoofer: * Everything you create — favourites, saved routes, settings, an optional Google API key — is stored **only on your computer**. * To show maps, find places and calculate routes, the app talks **directly from your computer to third-party online services** listed below. Those services receive the information needed to answer each request (for example map coordinates or a search term) and your IP address, under their own privacy policies. * The app talks to your iPhone **only over the USB cable or your local network**; nothing about the phone is sent to the internet by the app. -* **Screen mirroring** (the picture, the sound and your clicks and key presses) travels only between the phone and your computer. The app does not upload it, analyse it or keep a copy. Only screenshots and recordings that you save are written to disk, where you choose. -* The **local API for other programs** works only while the app is open, only for programs on your computer (not websites or other computers). Programs that use it can receive the phone's screen and control the phone; what they do with it is covered by their own privacy policies. +* **Screen mirroring** (the picture, the sound and your clicks and key presses) travels only between the phone and your computer. The app does not upload it, analyse it or keep a copy. Only screenshots and recordings that you save are written to disk, in your Downloads folder or the folder you choose in *Settings › Screen*. +* The **local API for other programs** works only while the app is open, only for programs on your computer (not websites or other computers). Programs that use it can receive the phone's screen and control the phone; what they do with it is covered by their own privacy policies. This includes the **AI agent connector** that comes with the app: if you connect an AI assistant (for example Claude Code or Cursor) to it, the screenshots it takes, what is visible on them and what you ask it are sent to that AI service, under its own privacy policy. ## What is stored on your computer diff --git a/README.md b/README.md index fdcec49..7bb9172 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,8 @@ Both have the same look and features (apart from the differences above), and bot | Mirroring: "won't share its screen while an app uses the camera or microphone" | Close Camera, Voice Memos or any app that is recording, then press Start mirroring again | | Mirroring: "can't decode the iPhone's video (HEVC)" | Update the graphics driver, or install *HEVC Video Extensions* from the Microsoft Store | | Mirroring: the picture stays black | Unlock the iPhone. Some apps hide their content from screen mirroring, for example video streaming apps | +| Mirroring: the picture freezes | It restarts by itself after a few seconds; press **Refresh** next to the screen to do it at once | +| Mirroring: the picture is sideways | Press **Rotate** next to the screen | | Something else | [Open an issue](https://github.com/YK3D/iPhone-location-spoofer/issues/new) and describe what happened, with the app's version (*Settings › About*) | @@ -132,14 +134,15 @@ Both have the same look and features (apart from the differences above), and bot
-Screen mirroring and control (Mirror tab) +Screen mirroring and control (Screen section) -* **See the iPhone's screen** live in the app, over the USB cable. Needs iOS 27 or newer. -* **Control it:** click to tap, drag to swipe or scroll, right-click for Home. Buttons for Home, Lock, Volume and Siri. +* **See the iPhone's screen** live in its own section of the app (switch between *Location* and *Screen* at the top), over the USB cable. Needs iOS 27 or newer. The picture turns with the phone. +* **Control it:** click to tap, drag to swipe, scroll with the mouse wheel, right-click for Home. Buttons next to the screen for Home, Lock, Volume, Mute and Siri, and for the gestures: app switcher, Control Centre, Notification Centre and Back. A small dot shows where you touch. * **Type:** click the screen and type on your keyboard (Ctrl works as the iPhone's ⌘, so Ctrl+C and Ctrl+V copy and paste on the phone), or send a whole line of text. * **Sound:** hear what the iPhone plays (standalone app). -* **Screenshots and recordings:** save a picture, or record the screen with its sound as a video file. -* **For developers:** other programs on your computer can watch the screen, tap, type and set the location through the [local API](docs/API.md). +* **Screenshots and recordings:** save a picture, or record the screen with its sound as a video file, to your Downloads folder or a folder you choose in *Settings › Screen*. +* **Stats** shows the frame rate, data rate and decoding delay; **Refresh** restarts a frozen picture (the app also does this by itself). +* **For developers:** other programs on your computer can watch the screen, tap, type and set the location through the [local API](docs/API.md), and AI agents (Claude Code, Cursor and others) can use the phone through the included [MCP server and skill](docs/API.md#ai-agents-mcp).
diff --git a/TERMS.md b/TERMS.md index df695d5..23d5da6 100644 --- a/TERMS.md +++ b/TERMS.md @@ -40,6 +40,8 @@ The app cannot hide that a location is simulated: apps can detect it, and other While the app is open, programs on your computer can use its local API to do what the app can do: see the device's screen, control the device and change its location. Websites cannot use it, and it cannot be reached from other computers. Only run programs you trust, and close the app when you are not using it. Programs that use the API are not made by YK3D, and their own terms and privacy policies apply to them. See [docs/API.md](docs/API.md). +The app includes a connector that lets AI agents use the API. An agent connected to it sees the screen and acts on the device by itself, and it can make mistakes: watch what it does, don't leave it unattended where a mistake can't be undone (purchases, messages, deleting data), and you remain responsible for what it does on your device. What you and the agent send to an AI service is covered by that service's terms. + ## 5. No warranty THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING FITNESS FOR A PARTICULAR PURPOSE, ACCURACY AND NON-INFRINGEMENT. Routes, speeds, travel times and speed limits are estimates and may be wrong. Mirrored pictures and sound can lag, freeze or be incomplete. **Never use the app for navigation or safety-critical purposes.** diff --git a/agents/sideport_mcp.py b/agents/sideport_mcp.py new file mode 100644 index 0000000..89fb7e0 --- /dev/null +++ b/agents/sideport_mcp.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Sideport MCP server: lets AI agents (Claude Code, Claude Desktop, Cursor, ...) see and use an iPhone. + +It speaks the Model Context Protocol over stdio and forwards each tool to Sideport's local API +(docs/API.md), so Sideport must be open on this computer. Python 3.9+ standard library only. + + claude mcp add sideport -- python /path/to/sideport_mcp.py + +Sideport's address is found by itself (the standalone app on port 8766, the browser edition on +8765); set SIDEPORT_URL to use another one. +""" + +from __future__ import annotations + +import base64 +import json +import os +import sys +import time +import urllib.error +import urllib.request +from typing import Any, Callable + +VERSION = "1.0.0" +CANDIDATES = [os.environ["SIDEPORT_URL"].rstrip("/")] if os.environ.get("SIDEPORT_URL") else ["http://127.0.0.1:8766", "http://127.0.0.1:8765"] +_base: list[str] = [] # the address that answered last + + +class ToolError(Exception): + """Shown to the agent as the tool's result (isError).""" + + +def http(method: str, path: str, body: Any = None, timeout: float = 70) -> tuple[bytes, str]: + """One request to Sideport: (body, content type). Tries each known address until one answers.""" + data = json.dumps(body).encode() if body is not None else None + for base in _base + [c for c in CANDIDATES if c not in _base]: + req = urllib.request.Request(base + path, data=data, method=method, headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + _base[:] = [base] + return r.read(), r.headers.get("Content-Type", "") + except urllib.error.HTTPError as e: + _base[:] = [base] + try: + detail = json.loads(e.read()).get("detail") + except Exception: # noqa: BLE001 - not JSON + detail = None + raise ToolError(str(detail or f"Sideport answered HTTP {e.code}")) from None + except (urllib.error.URLError, OSError): + continue + raise ToolError("Sideport is not running. Open the Sideport app on this computer, then try again.") + + +def api(method: str, path: str, body: Any = None) -> Any: + return json.loads(http(method, path, body)[0] or b"null") + + +def screen_input(msg: dict) -> None: + api("POST", "/api/screen/input", msg) + + +# ---------------------------------------------------------------- tools +def _num(a: dict, k: str) -> float: + v = a.get(k) + if isinstance(v, bool) or not isinstance(v, (int, float)) or not 0 <= v <= 1: + raise ToolError(f"'{k}' must be a number from 0 to 1 (a fraction of the screen's width or height)") + return float(v) + + +def t_status(a: dict) -> list: + s = api("GET", "/api/status") + out = {"app_version": s.get("version"), "device": s.get("device"), "location_playback": (s.get("player") or {}).get("state"), + "screen": api("GET", "/api/screen")} + return [_text(json.dumps(out, indent=2))] + + +def t_devices(a: dict) -> list: + return [_text(json.dumps(api("GET", "/api/devices?driver=pmd3"), indent=2))] + + +def t_connect(a: dict) -> list: + r = api("POST", "/api/connect", {"driver": "mock" if a.get("simulator") else "pmd3", "udid": a.get("udid")}) + return [_text(json.dumps(r, indent=2))] + + +def t_start(a: dict) -> list: + s = api("POST", "/api/screen/start", {"udid": a.get("udid"), "audio": bool(a.get("audio", False)), + **({"driver": "mock"} if a.get("simulator") else {})}) + return [_text(json.dumps(s, indent=2))] + + +def t_stop(a: dict) -> list: + return [_text(json.dumps(api("POST", "/api/screen/stop", {}), indent=2))] + + +def t_screenshot(a: dict) -> list: + wait = a.get("wait_ms", 0) + if isinstance(wait, (int, float)) and not isinstance(wait, bool) and wait > 0: + time.sleep(min(wait, 10000) / 1000) + png, _ = http("GET", "/api/screen/screenshot") + s = api("GET", "/api/screen") + note = f"iPhone screen ({s.get('width')}×{s.get('height')} pixels). Give positions as fractions: x = pixel x / width, y = pixel y / height." + return [{"type": "image", "data": base64.b64encode(png).decode(), "mimeType": "image/png"}, _text(note)] + + +def t_tap(a: dict) -> list: + screen_input({"t": "tap", "x": _num(a, "x"), "y": _num(a, "y")}) + return [_text("Tapped.")] + + +def t_swipe(a: dict) -> list: + ms = a.get("ms", 300) + screen_input({"t": "swipe", "x1": _num(a, "x1"), "y1": _num(a, "y1"), "x2": _num(a, "x2"), "y2": _num(a, "y2"), + "ms": ms if isinstance(ms, int) and not isinstance(ms, bool) else 300}) + return [_text("Swiped.")] + + +def t_long_press(a: dict) -> list: + x, y = _num(a, "x"), _num(a, "y") + ms = a.get("ms", 800) + screen_input({"t": "touch", "phase": "down", "x": x, "y": y}) + time.sleep(min(max(ms if isinstance(ms, (int, float)) else 800, 100), 5000) / 1000) + screen_input({"t": "touch", "phase": "up", "x": x, "y": y}) + return [_text("Pressed and held.")] + + +# System gestures: start and end point (portrait), drag time, hold before lifting. +GESTURES = { + "home": ((0.5, 0.995), (0.5, 0.55), 0.2, 0), + "app_switcher": ((0.5, 0.995), (0.5, 0.62), 0.26, 0.45), + "control_centre": ((0.92, 0.004), (0.92, 0.45), 0.26, 0), + "notification_centre": ((0.3, 0.004), (0.3, 0.6), 0.26, 0), + "back": ((0.004, 0.5), (0.65, 0.5), 0.26, 0), +} + + +def t_gesture(a: dict) -> list: + name = a.get("name") + if name not in GESTURES: + raise ToolError(f"'name' must be one of: {', '.join(GESTURES)}") + (x1, y1), (x2, y2), secs, hold = GESTURES[name] + screen_input({"t": "touch", "phase": "down", "x": x1, "y": y1}) + steps = 12 + for i in range(1, steps + 1): + time.sleep(secs / steps) + screen_input({"t": "touch", "phase": "move", "x": x1 + (x2 - x1) * i / steps, "y": y1 + (y2 - y1) * i / steps}) + time.sleep(hold) + screen_input({"t": "touch", "phase": "up", "x": x2, "y": y2}) + return [_text(f"Did the {name.replace('_', ' ')} gesture.")] + + +BUTTONS = ["home", "lock", "volume-up", "volume-down", "mute", "siri"] + + +def t_button(a: dict) -> list: + if a.get("name") not in BUTTONS: + raise ToolError(f"'name' must be one of: {', '.join(BUTTONS)}") + screen_input({"t": "button", "name": a["name"]}) + return [_text(f"Pressed {a['name']}.")] + + +def t_type(a: dict) -> list: + text = a.get("text") + if not isinstance(text, str) or not text: + raise ToolError("'text' must be some text") + screen_input({"t": "text", "text": text}) + return [_text("Typed.")] + + +KEYS = {"return": 40, "escape": 41, "backspace": 42, "tab": 43, "space": 44, "delete": 76, "home": 74, "end": 77, + "page_up": 75, "page_down": 78, "right": 79, "left": 80, "down": 81, "up": 82} +KEYS.update({chr(c): 4 + c - ord("a") for c in range(ord("a"), ord("z") + 1)}) +COMMAND = 227 + + +def t_key(a: dict) -> list: + usage = KEYS.get(str(a.get("key", "")).lower()) + if usage is None: + raise ToolError(f"'key' must be one of: {', '.join(KEYS)}") + held = [COMMAND, usage] if a.get("command") else [usage] + for u in held: + screen_input({"t": "key", "usage": u, "down": True}) + for u in reversed(held): + screen_input({"t": "key", "usage": u, "down": False}) + return [_text("Pressed " + ("⌘" if a.get("command") else "") + str(a["key"]) + ".")] + + +def t_set_location(a: dict) -> list: + lat, lon = a.get("lat"), a.get("lon") + if not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in (lat, lon)): + raise ToolError("'lat' and 'lon' must be numbers") + api("POST", "/api/location/set", {"lat": lat, "lon": lon}) + return [_text(f"The iPhone now reports {lat}, {lon}.")] + + +def t_clear_location(a: dict) -> list: + api("POST", "/api/location/clear", {}) + return [_text("The iPhone is back on its real location.")] + + +def _text(t: str) -> dict: + return {"type": "text", "text": t} + + +def _schema(props: dict | None = None, required: tuple = ()) -> dict: + return {"type": "object", "properties": props or {}, "required": list(required), "additionalProperties": False} + + +FRACTION = {"type": "number", "minimum": 0, "maximum": 1} +TOOLS: dict[str, tuple[str, dict, Callable[[dict], list]]] = { + "iphone_status": ("Sideport's state: the connected iPhone, the location playback and screen mirroring (state, width, " + "height, rotation).", _schema(), t_status), + "list_devices": ("iPhones plugged into this computer.", _schema(), t_devices), + "connect_device": ("Connect to an iPhone for location tools (the first one plugged in unless udid is given). " + "simulator: true uses a pretend phone.", _schema({"udid": {"type": "string"}, "simulator": {"type": "boolean"}}), t_connect), + "start_screen": ("Start screen mirroring; needed before screenshots and any touch, button or typing. iOS 27+, " + "Developer Mode, cable. Unlock the iPhone first.", + _schema({"udid": {"type": "string"}, "audio": {"type": "boolean"}, "simulator": {"type": "boolean"}}), t_start), + "stop_screen": ("Stop screen mirroring.", _schema(), t_stop), + "screenshot": ("See the iPhone's screen now (a PNG). wait_ms waits first, e.g. for an animation or a page to load.", + _schema({"wait_ms": {"type": "integer", "minimum": 0, "maximum": 10000}}), t_screenshot), + "tap": ("Tap a point. x and y are fractions of the screenshot's width and height (0,0 top left; 1,1 bottom right).", + _schema({"x": FRACTION, "y": FRACTION}, ("x", "y")), t_tap), + "long_press": ("Touch and hold a point (context menus, rearranging icons). ms: how long, default 800.", + _schema({"x": FRACTION, "y": FRACTION, "ms": {"type": "integer", "minimum": 100, "maximum": 5000}}, ("x", "y")), t_long_press), + "swipe": ("Drag a finger from (x1,y1) to (x2,y2) over ms milliseconds (default 300); to scroll down, swipe upwards.", + _schema({"x1": FRACTION, "y1": FRACTION, "x2": FRACTION, "y2": FRACTION, "ms": {"type": "integer", "minimum": 50, "maximum": 5000}}, + ("x1", "y1", "x2", "y2")), t_swipe), + "gesture": ("A system gesture: home (go to the Home Screen), app_switcher, control_centre, notification_centre, " + "back (swipe in from the left edge).", _schema({"name": {"type": "string", "enum": list(GESTURES)}}, ("name",)), t_gesture), + "press_button": ("Press a hardware button. siri is a long press.", _schema({"name": {"type": "string", "enum": BUTTONS}}, ("name",)), t_button), + "type_text": ("Type text into the focused field (tap the field first). US keyboard layout; up to 2000 characters.", + _schema({"text": {"type": "string"}}, ("text",)), t_type), + "press_key": ("Press one key, optionally with ⌘ (command: true), e.g. return to submit, or a with command for Select All.", + _schema({"key": {"type": "string", "enum": list(KEYS)}, "command": {"type": "boolean"}}, ("key",)), t_key), + "set_location": ("Make the iPhone report this GPS position (connect_device first).", + _schema({"lat": {"type": "number", "minimum": -90, "maximum": 90}, "lon": {"type": "number", "minimum": -180, "maximum": 180}}, + ("lat", "lon")), t_set_location), + "clear_location": ("Send the iPhone back to its real GPS position.", _schema(), t_clear_location), +} + +INSTRUCTIONS = ("Controls a real iPhone through the Sideport app. Call start_screen once, then loop: screenshot, decide, " + "act (tap, swipe, type_text, gesture), screenshot again to check. Positions are fractions of the screenshot.") + + +# ---------------------------------------------------------------- protocol (JSON-RPC 2.0, one message per line) +def handle(msg: dict) -> dict | None: + method, mid = msg.get("method"), msg.get("id") + if mid is None: # a notification: nothing to answer + return None + if method == "initialize": + version = (msg.get("params") or {}).get("protocolVersion") or "2025-06-18" + result: Any = {"protocolVersion": version, "capabilities": {"tools": {}}, + "serverInfo": {"name": "sideport", "version": VERSION}, "instructions": INSTRUCTIONS} + elif method == "ping": + result = {} + elif method == "tools/list": + result = {"tools": [{"name": n, "description": d, "inputSchema": s} for n, (d, s, _) in TOOLS.items()]} + elif method == "tools/call": + params = msg.get("params") or {} + tool = TOOLS.get(params.get("name")) + if tool is None: + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": f"Unknown tool {params.get('name')!r}"}} + try: + result = {"content": tool[2](params.get("arguments") or {})} + except ToolError as e: + result = {"content": [_text(str(e))], "isError": True} + else: + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"Method not found: {method}"}} + return {"jsonrpc": "2.0", "id": mid, "result": result} + + +def main() -> None: + for line in sys.stdin: + if not line.strip(): + continue + try: + msg = json.loads(line) + reply = handle(msg) if isinstance(msg, dict) else {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid request"}} + except json.JSONDecodeError: + reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} + if reply is not None: + sys.stdout.write(json.dumps(reply) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/agents/skills/sideport-iphone/SKILL.md b/agents/skills/sideport-iphone/SKILL.md new file mode 100644 index 0000000..6170664 --- /dev/null +++ b/agents/skills/sideport-iphone/SKILL.md @@ -0,0 +1,56 @@ +--- +name: sideport-iphone +description: Operate a real iPhone through the Sideport MCP tools (screenshot, tap, swipe, type, gestures, buttons, GPS location). Use when asked to test, use, explore or automate an iOS app or setting on a connected iPhone, or to check how an app behaves at another location. +--- + +# Using an iPhone through Sideport + +The `sideport` MCP server controls a real iPhone plugged into this computer, through the Sideport app (which must be open). You see the phone with `screenshot` and act with `tap`, `swipe`, `type_text` and friends. + +## Start + +1. `iphone_status`. If `screen.state` is not `on`, call `start_screen`. It fails if the phone is locked, has no Developer Mode, runs iOS older than 27, or the Camera or a recording app is open: tell the user what the error says and stop. +2. `screenshot` to see where you are. + +## The loop + +Look, act once, look again. Never chain several taps blind: screens change, keyboards appear, alerts pop up. + +- `screenshot`, decide on one action, do it, then `screenshot` again (use `wait_ms` 500–2000 after opening an app, navigating or submitting a form). +- If nothing changed, the tap missed or the app is still busy. Wait once, then retry with an adjusted position. Don't repeat the same miss more than twice. + +## Positions + +Every position is a fraction of the screenshot: `x` from 0 (left) to 1 (right), `y` from 0 (top) to 1 (bottom). Work it out from the screenshot: `x = pixel x / width`, `y = pixel y / height`. Aim for the centre of a button, not its edge. + +Avoid the very edges unless you mean a system gesture: the top ~5% is the status bar, the bottom ~3% is the home indicator. + +## Actions + +| Want | Tool | +|---|---| +| Press a button, link, field, cell | `tap` | +| Scroll down a list | `swipe` from `y: 0.75` to `y: 0.3` (the finger moves up). Scroll up: the reverse | +| Swipe between pages / delete a row | `swipe` sideways | +| Context menu, rearrange icons | `long_press` | +| Type into a field | `tap` the field, check the keyboard is up (`screenshot`), then `type_text`. US layout; characters it can't type (accents, emoji) are skipped | +| Submit / new line | `press_key` `return` | +| Select all / copy / paste | `press_key` `a` / `c` / `v` with `command: true` | +| Go to the Home Screen | `gesture` `home` (or `press_button` `home` on phones with a Home button) | +| Switch apps | `gesture` `app_switcher` | +| Go back | the app's back button first; `gesture` `back` otherwise | +| Open an app | Home Screen, then `swipe` down from the middle to open Search, `type_text` its name, tap the result | +| Pretend to be somewhere | `connect_device`, then `set_location` with latitude and longitude; `clear_location` when done | + +## Care + +- This is someone's real phone. Don't buy anything, send messages, post, delete data, change passwords or accept terms unless the user asked for exactly that; ask first when an action can't be undone. +- Screenshots can show private information (messages, notifications, emails). Use only what the task needs and don't repeat the rest. +- If a system alert asks for a permission (location, notifications, tracking), choose what the user's task needs; ask when unsure. +- When finished, leave the phone where the user would expect it (usually the app you were testing), and say what you did and what you saw. + +## When it goes wrong + +- `screenshot` fails with "not running": call `start_screen` again. +- "Sideport is not running": ask the user to open the Sideport app. +- The phone locked itself: ask the user to unlock it (you can't type the passcode). diff --git a/browser/spoofer/screen.py b/browser/spoofer/screen.py index 2eae79f..13e3cd5 100644 --- a/browser/spoofer/screen.py +++ b/browser/spoofer/screen.py @@ -32,7 +32,8 @@ # name -> (HID usage page, usage, hold in seconds). Siri needs a long press. BUTTONS = { "home": (0x0C, 0x40, 0.05), - "lock": (0x0C, 0x30, 0.05), + # shortcut: lock uses the side button's usage with a longer press; unconfirmed on a real iPhone, change the usage if it still does nothing. + "lock": (0x0C, 0x30, 0.25), "volume-up": (0x0C, 0xE9, 0.05), "volume-down": (0x0C, 0xEA, 0.05), "mute": (0x0C, 0xE2, 0.05), @@ -58,11 +59,11 @@ def parse_input(v: Any) -> tuple: ``{"t":"touch","phase":"down|move|up","x":..,"y":..}``, ``{"t":"tap","x":..,"y":..}``, ``{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}``, ``{"t":"button","name":"home"}``, - ``{"t":"key","usage":40,"down":true}``, ``{"t":"text","text":"hi"}``, ``{"t":"keyframe"}``. + ``{"t":"key","usage":40,"down":true}``, ``{"t":"text","text":"hi"}``, ``{"t":"keyframe"}``, ``{"t":"refresh"}``. Raises ValueError with a message for the user. """ if not isinstance(v, dict): - raise ValueError("'t' must be touch, tap, swipe, button, key, text or keyframe") + raise ValueError(_KINDS) t = v.get("t") if t == "touch": if v.get("phase") not in ("down", "move", "up"): @@ -93,9 +94,12 @@ def parse_input(v: Any) -> tuple: if len(text) > 2000: raise ValueError("Type at most 2000 characters at a time") return ("text", text) - if t == "keyframe": - return ("keyframe",) - raise ValueError("'t' must be touch, tap, swipe, button, key, text or keyframe") + if t in ("keyframe", "refresh"): + return (t,) + raise ValueError(_KINDS) + + +_KINDS = "'t' must be touch, tap, swipe, button, key, text, keyframe or refresh" _SHIFTED_DIGITS = "!@#$%^&*()" @@ -390,7 +394,8 @@ def _stream_config(answer: Any) -> tuple[int, int, int]: def _status(**kw) -> dict: - s = {"state": "off", "error": None, "simulated": False, "width": None, "height": None, "audio": False, "note": None} + s = {"state": "off", "error": None, "simulated": False, "width": None, "height": None, "audio": False, "note": None, + "rotation": 0} s.update(kw) return s @@ -490,27 +495,43 @@ def _require(self) -> Optional["_Live"]: async def input(self, i: tuple) -> None: live = self._require() - if live is None: # simulator + if self.status["simulated"]: if len(self.sim_inputs) < 1000: self.sim_inputs.append(i) return + if live is None: + raise ScreenError("Reconnecting to the iPhone's screen. Try again in a moment.") await live.apply(i) async def screenshot(self) -> bytes: live = self._require() - if live is None: + if self.status["simulated"]: raise ScreenError("The simulator has no screen to capture.") + if live is None: + raise ScreenError("Reconnecting to the iPhone's screen. Try again in a moment.") return await live.screenshot() async def _run(self, session: int, udid: Optional[str], audio: bool, ready: asyncio.Future) -> None: error = None + restarts, last_restart = 0, 0.0 try: - async with AsyncExitStack() as stack: - live = _Live(self, session) - await live.open(stack, udid, audio) - self._live = live - ready.set_result(None) - await live.loop() + while True: + try: + async with AsyncExitStack() as stack: + live = _Live(self, session) + await live.open(stack, udid, audio) + self._live = live + if not ready.done(): + ready.set_result(None) + await live.loop() + except _Restart as r: + self._live = None + if r.auto: + restarts = restarts + 1 if time.monotonic() - last_restart < 60 else 1 + last_restart = time.monotonic() + if restarts > MAX_RESTARTS: + raise ScreenError("The iPhone stopped sending its screen. Unlock it, then start mirroring again.") from None + self._set(session, note="Reconnecting to the iPhone's screen…") except asyncio.CancelledError: raise except ScreenError as e: @@ -527,6 +548,31 @@ async def _run(self, session: int, udid: Optional[str], audio: bool, ready: asyn MEDIA_IN_USE_CODE = 9022 +# Unanswered keyframe requests (while the picture is broken) before the stream is restarted; +# iOS 27's encoder sometimes stops answering them, and a fresh stream always opens with one. +MAX_KEY_REQUESTS = 3 +SILENCE = 6.0 # seconds without any datagram (the phone's RTCP reports come every second) +MAX_RESTARTS = 3 # automatic restarts in a row (less than a minute apart) before giving up + + +class _Restart(Exception): + """Start the stream again: ``auto`` when it froze, False when the user asked (Refresh).""" + + def __init__(self, auto: bool) -> None: + super().__init__("restart") + self.auto = auto + + +def display_rotation(info: Any) -> int: + """Clockwise degrees (0, 90, 180, 270) that turn the streamed picture upright, from a + ``getdisplayinfo`` answer: the built-in display in use, else the primary one.""" + displays = info.get("displays", []) if isinstance(info, dict) else [] + built_in = [d for d in displays if not d.get("external")] + chosen = (next((d for d in built_in if d.get("active")), None) + or next((d for d in built_in if d.get("backlightState", "off") != "off"), None) + or next((d for d in displays if d.get("primary")), None) + or (displays[0] if displays else {})) + return {"rot90": 90, "rot180": 180, "rot270": 270}.get(chosen.get("currentOrientation"), 0) class _Live: @@ -535,6 +581,12 @@ class _Live: def __init__(self, m: Screen, session: int) -> None: self.m, self.session = m, session self.want_key = True + self.refresh = False # a still screen gets a keyframe now and then; doesn't count towards a restart + self.restart_asked = False + self.key_requests = 0 + self.depack = Depacketizer() + self.lock = asyncio.Lock() # one input at a time on the HID services + self.info = None self.hid = self.indigo = None self.held: set[int] = set() self.kb_id: Optional[int] = None @@ -589,6 +641,12 @@ async def open(self, stack: AsyncExitStack, udid: Optional[str], audio: bool) -> log.exception("HID services unavailable") self.hid = self.indigo = None notes.append("The iPhone did not accept touch input, so it can only be watched.") + try: # which way the screen is turned; without it the Rotate button helps + from pymobiledevice3.remote.core_device.device_info import DeviceInfoService + + self.info = await stack.enter_async_context(DeviceInfoService(self.rsd)) + except Exception: # noqa: BLE001 + self.info = None self.decoder = None if audio: if sys.platform == "darwin": @@ -606,7 +664,7 @@ async def _stop_streams(self) -> None: async def loop(self) -> None: self.started = time.monotonic() self.v_seq, self.a_seq = _SeqCounter(), _SeqCounter() - tasks = [asyncio.create_task(c) for c in (self._video(), self._audio(), self._feedback())] + tasks = [asyncio.create_task(c) for c in (self._video(), self._audio(), self._feedback(), self._orientation())] try: done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for t in done: @@ -620,19 +678,20 @@ def _ts(self) -> int: return int((time.monotonic() - self.started) * 1e6) async def _video(self) -> None: - depack = Depacketizer() + depack = self.depack while True: - p = _rtp(await self.video.recv(65535)) + data = await self.video.recv(65535) + self.last_dgram = time.monotonic() + p = _rtp(data) if p is None: continue self.last_video = time.monotonic() seq, ts, marker, payload = p self.v_seq.add(seq) - was_waiting = depack.waiting_for_key frames = depack.push(seq, ts, marker, payload) - if depack.waiting_for_key and not was_waiting: - self.want_key = True for rtp_ts, key, nals in frames: + if key: + self.key_requests = 0 if depack.config_changed: c = depack.decoder_config() if c: @@ -666,15 +725,24 @@ async def _feedback(self) -> None: """Receiver reports every second (the phone stops after ~20 s without them) and rate-limited keyframe requests.""" fir_seq, last_report, last_request = 0, 0.0, 0.0 - self.last_video = time.monotonic() + self.last_video = self.last_dgram = time.monotonic() while True: await asyncio.sleep(0.1) now = time.monotonic() + if self.restart_asked: + raise _Restart(False) + if now - self.last_dgram > SILENCE: + raise _Restart(True) if now - self.last_video > 4: # a still screen sends nothing: refresh for new viewers - self.want_key, self.last_video = True, now - if self.want_key and now - last_request > 0.7 and self.v_phone: + self.refresh, self.last_video = True, now + broken = self.want_key or self.depack.waiting_for_key + if (broken or self.refresh) and now - last_request > 1 and self.v_phone: + if broken: + if self.key_requests >= MAX_KEY_REQUESTS: + raise _Restart(True) + self.key_requests += 1 await self._rtcp(self.video, self.v_port, _keyframe_request(self.v_ours, self.v_phone, self.v_seq.value or 0, fir_seq)) - fir_seq, last_request, self.want_key = fir_seq + 1, now, False + fir_seq, last_request, self.want_key, self.refresh = fir_seq + 1, now, False, False if now - last_report >= 1: last_report = now if self.v_phone: @@ -682,8 +750,30 @@ async def _feedback(self) -> None: if self.a_phone: await self._rtcp(self.audio_rx, self.a_port, _rr_sdes(self.a_ours, self.a_phone, self.a_seq.value or 0)) + async def _orientation(self) -> None: + while True: + await asyncio.sleep(0.5) + if self.info is None: + continue + try: + r = display_rotation(await asyncio.wait_for(self.info.get_display_info(), 0.8)) + except Exception: # noqa: BLE001 - not supported by this iPhone: stop asking + self.info = None + continue + if r != self.m.status.get("rotation"): + self.m._set(self.session, rotation=r) + # ---- input async def apply(self, i: tuple) -> None: + if i[0] == "keyframe": + self.want_key = True + elif i[0] == "refresh": + self.restart_asked = True + else: + async with self.lock: + await self._apply(i) + + async def _apply(self, i: tuple) -> None: from pymobiledevice3.remote.core_device.hid_service import ( HID_BUTTON_STATE_DOWN, HID_BUTTON_STATE_UP, @@ -692,9 +782,6 @@ async def apply(self, i: tuple) -> None: ) kind = i[0] - if kind == "keyframe": - self.want_key = True - return if self.hid is None or self.indigo is None: raise ScreenError("The iPhone did not accept touch input in this session. Stop and start mirroring again.") if kind == "touch": diff --git a/browser/spoofer/server.py b/browser/spoofer/server.py index b763f2f..5b600a5 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -6,6 +6,7 @@ import contextlib import json import logging +import re import uuid from collections import OrderedDict from contextlib import asynccontextmanager @@ -988,6 +989,34 @@ async def screen_screenshot(): return Response(await S().screen.screenshot(), media_type="image/png", headers={"Cache-Control": "no-store"}) +_CAPTURE_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,119}") + + +@app.post("/api/screen/save") +async def screen_save(name: str, request: Request): + """Saves a screenshot or recording from the Mirror tab to the folder chosen in Settings + (the Downloads folder by default) and returns where it went.""" + if not _CAPTURE_NAME.fullmatch(name) or not name.endswith((".png", ".mp4", ".webm")): + raise HTTPException(400, "Unexpected file name.") + chosen = str((S().store.load().get("settings") or {}).get("capture_folder") or "").strip() + folder = Path(chosen).expanduser() if chosen else Path.home() / "Downloads" + body = await request.body() + + def write() -> str: + try: + folder.mkdir(parents=True, exist_ok=True) + path, stem, ext = folder / name, *name.rsplit(".", 1) + n = 1 + while path.exists(): + path, n = folder / f"{stem}-{n}.{ext}", n + 1 + path.write_bytes(body) + except OSError as e: + raise HTTPException(400, f"Can't save to {folder}: {e.strerror or e}") from e + return str(path) + + return {"path": await asyncio.to_thread(write)} + + @app.websocket("/api/screen/ws") async def screen_ws(ws: WebSocket): """Live picture, sound and status for the Mirror tab or another program; input goes the other way.""" diff --git a/browser/tests/test_mcp.py b/browser/tests/test_mcp.py new file mode 100644 index 0000000..cb80805 --- /dev/null +++ b/browser/tests/test_mcp.py @@ -0,0 +1,69 @@ +"""The MCP server for AI agents (agents/sideport_mcp.py) against this edition's API, with the simulator.""" + +import importlib.util +import json +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +spec = importlib.util.spec_from_file_location("sideport_mcp", Path(__file__).resolve().parents[2] / "agents" / "sideport_mcp.py") +mcp = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mcp) + + +@pytest.fixture() +def rpc(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + def http(method, path, body=None, timeout=70): + r = c.request(method, path, json=body) + if r.status_code >= 400: + raise mcp.ToolError(r.json().get("detail")) + return r.content, r.headers.get("content-type", "") + + monkeypatch.setattr(mcp, "http", http) + monkeypatch.setattr(mcp.time, "sleep", lambda s: None) + ids = iter(range(1, 1000)) + yield lambda method, params=None: mcp.handle({"jsonrpc": "2.0", "id": next(ids), "method": method, "params": params or {}}) + + +def call(rpc, tool, **args): + return rpc("tools/call", {"name": tool, "arguments": args})["result"] + + +def test_handshake_and_tool_list(rpc): + init = rpc("initialize", {"protocolVersion": "2025-06-18"})["result"] + assert init["serverInfo"]["name"] == "sideport" and "tools" in init["capabilities"] + assert mcp.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None + tools = {t["name"]: t for t in rpc("tools/list")["result"]["tools"]} + assert {"screenshot", "tap", "swipe", "gesture", "type_text", "set_location"} <= set(tools) + assert tools["tap"]["inputSchema"]["required"] == ["x", "y"] + assert rpc("nope")["error"]["code"] == -32601 + + +def test_drives_the_simulated_iphone(rpc): + assert call(rpc, "tap", x=0.5, y=0.5)["isError"] # not mirroring yet + s = json.loads(call(rpc, "start_screen", simulator=True)["content"][0]["text"]) + assert s["state"] == "on" + for tool, args in [("tap", {"x": 0.5, "y": 0.9}), ("swipe", {"x1": 0.5, "y1": 0.8, "x2": 0.5, "y2": 0.2}), + ("gesture", {"name": "app_switcher"}), ("press_button", {"name": "home"}), ("type_text", {"text": "hi"}), + ("press_key", {"key": "a", "command": True}), ("long_press", {"x": 0.2, "y": 0.2})]: + assert not call(rpc, tool, **args).get("isError"), tool + sent = __import__("spoofer.server", fromlist=["app"]).app.state.s.screen.sim_inputs + assert ("text", "hi") in sent and ("key", 227, True) in sent and sent[-1][:2] == ("touch", "up") + bad = call(rpc, "tap", x=2, y=0) + assert bad["isError"] and "fraction" in bad["content"][0]["text"] + assert call(rpc, "screenshot")["isError"] # the simulator has no screen + assert json.loads(call(rpc, "iphone_status")["content"][0]["text"])["screen"]["simulated"] is True + + +def test_location_tools(rpc): + call(rpc, "connect_device", simulator=True) + assert not call(rpc, "set_location", lat=48.8584, lon=2.2945).get("isError") + assert not call(rpc, "clear_location").get("isError") diff --git a/browser/tests/test_screen.py b/browser/tests/test_screen.py index d265cd0..27d4f6f 100644 --- a/browser/tests/test_screen.py +++ b/browser/tests/test_screen.py @@ -98,6 +98,7 @@ def test_inputs_and_keys(): assert mi.parse_input({"t": "touch", "phase": "down", "x": 0.5, "y": 1}) == ("touch", "down", 32768, 65535) assert mi.parse_input({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})[-1] == 300 assert mi.parse_input({"t": "key", "usage": 40, "down": False}) == ("key", 40, False) + assert mi.parse_input({"t": "refresh"}) == ("refresh",) for bad in ({"t": "tap", "x": 1.5, "y": 0}, {"t": "tap", "x": "0.2", "y": 0}, {"t": "touch", "phase": "hover", "x": 0, "y": 0}, {"t": "button", "name": "power"}, {"t": "key", "usage": 1, "down": True}, {"t": "fly"}, []): with pytest.raises(ValueError): @@ -129,6 +130,14 @@ def test_rtcp_and_rtp_helpers(): assert mi._stream_config(answer) == (50001, 9, 7) and mi._stream_config(None) == (0, 0, 0) +def test_reads_the_screen_rotation(): + info = {"displays": [{"external": True, "currentOrientation": "rot180"}, {"primary": True, "currentOrientation": "rot90"}, + {"active": True, "currentOrientation": "rot270"}]} + assert mi.display_rotation(info) == 270 + assert mi.display_rotation({"displays": [{"currentOrientation": "rot90"}]}) == 90 + assert mi.display_rotation(True) == 0 + + @pytest.fixture() def client(tmp_path, monkeypatch): monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) @@ -166,3 +175,37 @@ def test_websocket_refuses_other_websites(client): with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/api/screen/ws", headers={"host": "127.0.0.1:8765", "origin": "https://evil.example"}) as ws: ws.receive_text() + + +def test_screen_captures_go_to_the_chosen_folder(client, tmp_path): + folder = tmp_path / "captures" + client.put("/api/store", json={"settings": {"capture_folder": str(folder)}}) + first = client.post("/api/screen/save?name=shot.png", content=b"png").json()["path"] + second = client.post("/api/screen/save?name=shot.png", content=b"png").json()["path"] + assert open(first, "rb").read() == b"png" and second.endswith("shot-1.png") + for bad in ("../x.png", "x.exe", ".png", "a/b.png"): + assert client.post("/api/screen/save", params={"name": bad}, content=b"x").status_code == 400, bad + + +def test_unanswered_keyframe_requests_restart_the_stream(monkeypatch): + import asyncio + import itertools + import types + + clock = itertools.count(0, 0.6) # every look at the clock is 0.6 s later + monkeypatch.setattr(mi, "time", types.SimpleNamespace(monotonic=lambda: next(clock))) + live = mi._Live(mi.Screen(), 1) + live.v_phone, live.v_ours, live.v_port, live.a_phone = 2, 1, 5, 0 + live.v_seq, live.a_seq = mi._SeqCounter(), mi._SeqCounter() + live.video = live.audio_rx = None + requests = [] + + async def rtcp(_transport, _port, packet): + live.last_dgram = mi.time.monotonic() # the phone keeps sending, just no keyframe + if len(packet) > 44: + requests.append(packet) + + live._rtcp = rtcp + with pytest.raises(mi._Restart) as e: + asyncio.run(asyncio.wait_for(live._feedback(), 10)) + assert e.value.auto and len(requests) == mi.MAX_KEY_REQUESTS diff --git a/docs/API.md b/docs/API.md index 2810ef0..a2a7b06 100644 --- a/docs/API.md +++ b/docs/API.md @@ -32,17 +32,20 @@ Needs iOS 27 or newer. The phone only accepts touches and keys while mirroring r | Method and path | Body | What it does | |---|---|---| -| `GET /api/screen` | | Status: `state` (`off`, `starting`, `on`, `error`), `error`, `simulated`, `width`, `height` (screen pixels), `audio`, `note` | +| `GET /api/screen` | | Status: `state` (`off`, `starting`, `on`, `error`), `error`, `simulated`, `width`, `height` (screen pixels), `audio`, `note`, `rotation` (see below) | | `POST /api/screen/start` | `{"driver": "pmd3", "udid": null, "audio": true}` | Start (all fields optional; defaults to the device the app is connected to). Returns the status once the picture is flowing | | `POST /api/screen/stop` | `{}` | Stop | | `POST /api/screen/input` | one input, see below | Tap, swipe, press a button or type | | `GET /api/screen/screenshot` | | A PNG of the screen, taken by the phone | | `GET /api/screen/ws` | WebSocket | Live picture, sound and status; send inputs on it too | +| `POST /api/screen/save?name=` | the file | Saves a screenshot or recording (`.png`, `.mp4`, `.webm`) to the folder chosen in *Settings › Screen* (Downloads by default); answers `{"path": ...}` | ### Inputs Coordinates are fractions of the screen as the phone holds it natively (portrait on an iPhone): `0,0` is the top left, `1,1` the bottom right. Multiply by `width`/`height` from the status to work in pixels. +The picture always arrives in that native orientation. When the phone is turned, the status's `rotation` says how many degrees clockwise (0, 90, 180 or 270) to turn the picture to show it upright; turn your coordinates back the same way before sending them. + | Input | Example | |---|---| | Tap | `{"t": "tap", "x": 0.5, "y": 0.9}` | @@ -52,6 +55,7 @@ Coordinates are fractions of the screen as the phone holds it natively (portrait | Type text (US keyboard layout, up to 2000 characters) | `{"t": "text", "text": "Hello"}` | | One key down or up ([HID keyboard usage](https://usb.org/sites/default/files/hut1_5.pdf), page 7) | `{"t": "key", "usage": 40, "down": true}` (40 is Return) | | Ask for a fresh full frame | `{"t": "keyframe"}` | +| Restart the picture (if it froze; the app also does this by itself after a few seconds) | `{"t": "refresh"}` | ```bash curl -X POST http://127.0.0.1:8766/api/screen/start -H "Content-Type: application/json" -d '{}' @@ -99,3 +103,23 @@ with connect("ws://127.0.0.1:8766/api/screen/ws") as ws: elif msg[0] == 2: print("frame", "key" if msg[1] else "delta", len(msg) - 10, "bytes") ``` + +## AI agents (MCP) + +[`agents/sideport_mcp.py`](../agents/sideport_mcp.py) is a [Model Context Protocol](https://modelcontextprotocol.io) server that gives AI agents (Claude Code, Claude Desktop, Cursor and others) tools to use the iPhone through this API: `screenshot`, `tap`, `swipe`, `long_press`, `gesture` (home, app switcher, Control Centre, Notification Centre, back), `press_button`, `type_text`, `press_key`, `set_location`, `clear_location`, `start_screen`, `stop_screen`, `iphone_status`, `list_devices` and `connect_device`. It needs Python 3.9 or newer (nothing to install) and Sideport open. + +Claude Code: + +```bash +claude mcp add sideport -- python C:\path\to\sideport_mcp.py +``` + +Claude Desktop, Cursor and other apps take the same command in their MCP settings, for example: + +```json +{ "mcpServers": { "sideport": { "command": "python", "args": ["C:\\path\\to\\sideport_mcp.py"] } } } +``` + +[`agents/skills/sideport-iphone`](../agents/skills/sideport-iphone/SKILL.md) is a skill that teaches an agent how to work with the phone (look, act, look again; positions as fractions; what not to do on someone's real phone). For Claude Code, copy the folder to `~/.claude/skills/` (or a project's `.claude/skills/`). + +The agent sees what the screenshots show, and the AI service it runs on receives them. Keep an eye on what it does: its taps act on the real phone. diff --git a/standalone/src/screen/mod.rs b/standalone/src/screen/mod.rs index 42abc0a..6dbf45d 100644 --- a/standalone/src/screen/mod.rs +++ b/standalone/src/screen/mod.rs @@ -25,7 +25,8 @@ use tokio::sync::{broadcast, mpsc, oneshot}; /// Hardware buttons: (name, HID usage page, usage, hold in ms). Siri needs a long press. pub const BUTTONS: [(&str, u64, u64, u64); 6] = [ ("home", 0x0C, 0x40, 50), - ("lock", 0x0C, 0x30, 50), + // shortcut: lock uses the side button's usage with a longer press; unconfirmed on a real iPhone, change the usage if it still does nothing. + ("lock", 0x0C, 0x30, 250), ("volume-up", 0x0C, 0xE9, 50), ("volume-down", 0x0C, 0xEA, 50), ("mute", 0x0C, 0xE2, 50), @@ -44,6 +45,8 @@ pub enum Input { Text(String), /// Ask the phone for a fresh full frame (a new viewer, or a decoder error). KeyFrame, + /// Restart the stream (a frozen picture). + Refresh, } #[derive(Debug, Clone, Copy, PartialEq)] @@ -65,7 +68,7 @@ fn coord(v: &Value, k: &str) -> Result { /// /// `{"t":"touch","phase":"down|move|up","x":0.5,"y":0.5}`, `{"t":"tap","x":..,"y":..}`, /// `{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}`, `{"t":"button","name":"home"}`, -/// `{"t":"key","usage":40,"down":true}`, `{"t":"text","text":"hello"}`, `{"t":"keyframe"}`. +/// `{"t":"key","usage":40,"down":true}`, `{"t":"text","text":"hello"}`, `{"t":"keyframe"}`, `{"t":"refresh"}`. pub fn parse_input(v: &Value) -> Result { let t = v.get("t").and_then(Value::as_str).unwrap_or(""); Ok(match t { @@ -107,7 +110,8 @@ pub fn parse_input(v: &Value) -> Result { Input::Text(text.into()) } "keyframe" => Input::KeyFrame, - _ => return Err("'t' must be touch, tap, swipe, button, key, text or keyframe".into()), + "refresh" => Input::Refresh, + _ => return Err("'t' must be touch, tap, swipe, button, key, text, keyframe or refresh".into()), }) } @@ -146,11 +150,13 @@ pub struct Status { pub audio: bool, /// Why there is no sound, or no touch control, when there isn't. pub note: Option, + /// Clockwise degrees (0, 90, 180, 270) that turn the picture upright: the phone is turned. + pub rotation: u16, } impl Default for Status { fn default() -> Self { - Self { state: "off", error: None, simulated: false, width: None, height: None, audio: false, note: None } + Self { state: "off", error: None, simulated: false, width: None, height: None, audio: false, note: None, rotation: 0 } } } @@ -250,7 +256,8 @@ impl Screen { .spawn(move || { let rt = tokio::runtime::Builder::new_current_thread().enable_all().build(); match rt { - Ok(rt) => rt.block_on(session::run(me, session, udid, audio, rx, ready_tx)), + // A LocalSet lets the session run its (non-Send) input on a task of its own. + Ok(rt) => tokio::task::LocalSet::new().block_on(&rt, session::run(me, session, udid, audio, rx, ready_tx)), Err(e) => me.ended(session, Some(format!("Could not start the mirroring thread: {e}"))), } }) @@ -415,6 +422,7 @@ mod tests { ); assert_eq!(parse_input(&json!({"t": "button", "name": "siri"})).unwrap(), Input::Button("siri", 0x0C, 0xCF, 1000)); assert_eq!(parse_input(&json!({"t": "key", "usage": 40, "down": false})).unwrap(), Input::Key { usage: 40, down: false }); + assert_eq!(parse_input(&json!({"t": "refresh"})).unwrap(), Input::Refresh); assert!(matches!(parse_input(&json!({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})).unwrap(), Input::Swipe { ms: 300, .. })); for bad in [ json!({"t": "tap", "x": 1.5, "y": 0}), diff --git a/standalone/src/screen/session.rs b/standalone/src/screen/session.rs index f8f9fed..f6880a7 100644 --- a/standalone/src/screen/session.rs +++ b/standalone/src/screen/session.rs @@ -7,13 +7,13 @@ use crate::device::idev; use idevice::{ core_device::{ build_keyframe_request, build_liveness, build_screen_audio_offer, build_screen_video_offer, build_start_audio_parameters, - build_start_video_parameters, is_rtcp, ButtonState, CallInfoBlob, DisplayServiceClient, IndigoHidClient, ReportBlock, RtpPacket, - UniversalHidServiceClient, TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, + build_start_video_parameters, is_rtcp, ButtonState, CallInfoBlob, CoreDeviceServiceClient, DisplayServiceClient, IndigoHidClient, + ReportBlock, RtpPacket, UniversalHidServiceClient, TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, }, core_device_proxy::CoreDeviceProxy, dvt::{remote_server::RemoteServerClient, screenshot::ScreenshotClient}, lockdown::LockdownClient, - provider::IdeviceProvider, + provider::{IdeviceProvider, RsdProvider}, rsd::RsdHandshake, IdeviceService, ReadWrite, RsdService, }; @@ -29,6 +29,21 @@ const MEDIA_IN_USE: &str = "9022"; type Hid = UniversalHidServiceClient>; type Indigo = IndigoHidClient>; +/// Unanswered keyframe requests (while the picture is broken) before the stream is restarted; +/// iOS 27's encoder sometimes stops answering them, and a fresh stream always opens with one. +const MAX_KEY_REQUESTS: u32 = 3; +/// No datagram at all (the phone's RTCP reports come every second) means the stream died. +const SILENCE: Duration = Duration::from_secs(6); +/// Automatic restarts in a row (less than a minute apart) before giving up. +const MAX_RESTARTS: u32 = 3; + +/// How a stream ended without an error. +enum Ended { + Stopped, + /// Start it again: `auto` when the stream froze, false when the user asked (Refresh). + Restart { auto: bool }, +} + pub(super) async fn run( m: Arc, session: u64, @@ -38,7 +53,24 @@ pub(super) async fn run( ready: oneshot::Sender>, ) { let mut ready = Some(ready); - let result = stream(&m, session, udid, audio_on, rx, &mut ready).await; + let mut rx = rx; + let (mut restarts, mut last_restart) = (0, Instant::now()); + let result = loop { + match stream(&m, session, udid.clone(), audio_on, &mut rx, &mut ready).await { + Ok(Ended::Restart { auto }) => { + if auto { + restarts = if last_restart.elapsed() < Duration::from_secs(60) { restarts + 1 } else { 1 }; + last_restart = Instant::now(); + if restarts > MAX_RESTARTS { + break Err("The iPhone stopped sending its screen. Unlock it, then start mirroring again.".to_string()); + } + } + m.set(session, |s| s.note = Some("Reconnecting to the iPhone's screen…".into())); + } + Ok(Ended::Stopped) => break Ok(()), + Err(e) => break Err(e), + } + }; if let Some(r) = ready.take() { let _ = r.send(Err(result.clone().err().unwrap_or_else(|| "Screen mirroring stopped.".into()))); } @@ -83,9 +115,9 @@ async fn stream( session: u64, udid: Option, audio_on: bool, - mut rx: mpsc::UnboundedReceiver, + rx: &mut mpsc::UnboundedReceiver, ready: &mut Option>>, -) -> Result<(), String> { +) -> Result { let fr = |e: idevice::IdeviceError| idev::friendly(&e); let (provider, _) = idev::find_device(udid.as_deref(), crate::device::Via::Auto).await?; idev::ensure_paired(&provider).await?; @@ -139,8 +171,16 @@ async fn stream( // Touch and buttons are refused until the phone has matched them to the new stream. tokio::time::sleep(Duration::from_millis(300)).await; - let mut hid: Option = UniversalHidServiceClient::connect_rsd(&mut adapter, &mut hs).await.ok(); - let mut indigo: Option = IndigoHidClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + let hid: Option = UniversalHidServiceClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + let indigo: Option = IndigoHidClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + // Which way the screen is turned; without it the picture stays upright and the Rotate button helps. + let mut info = match hs.services.get("com.apple.coredevice.deviceinfo").map(|s| s.port) { + Some(port) => match adapter.connect_to_service_port(port).await { + Ok(stream) => CoreDeviceServiceClient::new(stream).await.ok(), + Err(_) => None, + }, + None => None, + }; let mut decoder = if audio_on { audio::Decoder::new() } else { None }; let mut note = Vec::new(); if hid.is_none() || indigo.is_none() { @@ -157,37 +197,60 @@ async fn stream( if let Some(r) = ready.take() { let _ = r.send(Ok(())); } + // Input runs on its own task, in order: a held button (Siri: 1 s), a swipe or typing must + // not stop the picture from being received meanwhile. + let (input_tx, mut input_rx) = mpsc::unbounded_channel::<(Input, oneshot::Sender>)>(); + let input_task = tokio::task::spawn_local(async move { + let (mut hid, mut indigo) = (hid, indigo); + while let Some((i, r)) = input_rx.recv().await { + let _ = r.send(apply(i, hid.as_mut(), indigo.as_mut()).await); + } + }); let started = Instant::now(); let mut depack = hevc::Depacketizer::new(); let (mut v_seq, mut a_seq) = (SeqCounter::default(), SeqCounter::default()); let mut last_keyframe_request = Instant::now() - Duration::from_secs(5); let mut fir_seq = 0u8; - let mut want_key = true; + // `want_key`: someone needs a keyframe (a viewer, or lost packets); `refresh`: a still screen + // gets one now and then for new viewers. Only the first kind counts towards a restart. + let (mut want_key, mut refresh, mut key_requests) = (true, false, 0u32); let mut tick = tokio::time::interval(Duration::from_secs(1)); - let mut last_video = Instant::now(); + let mut orient_tick = tokio::time::interval(Duration::from_millis(500)); + let (mut last_video, mut last_dgram) = (Instant::now(), Instant::now()); + let mut rotation = 0u16; let result = loop { - if want_key && last_keyframe_request.elapsed() > Duration::from_millis(700) && v_phone != 0 { + let broken = want_key || depack.waiting_for_key; + if (broken || refresh) && last_keyframe_request.elapsed() > Duration::from_secs(1) && v_phone != 0 { + if broken { + if key_requests >= MAX_KEY_REQUESTS { + break Ok(Ended::Restart { auto: true }); + } + key_requests += 1; + } let block = ReportBlock { source_ssrc: v_phone, highest_seq: v_seq.0.unwrap_or(0), ..Default::default() }; let _ = video_udp.send_to(v_port, build_keyframe_request(v_ours, "", v_phone, &[block], fir_seq)).await; fir_seq = fir_seq.wrapping_add(1); last_keyframe_request = Instant::now(); - want_key = false; + (want_key, refresh) = (false, false); + } + if last_dgram.elapsed() > SILENCE { + break Ok(Ended::Restart { auto: true }); } tokio::select! { dg = video_udp.recv() => { let Ok(dg) = dg else { break Err("The connection to the iPhone was lost.".to_string()) }; + last_dgram = Instant::now(); if is_rtcp(&dg.data) { continue; } let Some(p) = RtpPacket::parse(&dg.data) else { continue }; last_video = Instant::now(); v_seq.add(p.sequence_number); - let was_waiting = depack.waiting_for_key; let frames = depack.push(p.sequence_number, p.timestamp, p.marker, p.payload); - if depack.waiting_for_key && !was_waiting { - want_key = true; // a packet was lost - } for au in frames { + if au.key { + key_requests = 0; + } if depack.config_changed { if let Some(c) = depack.decoder_config() { m.set(session, |s| { s.width = Some(c.width); s.height = Some(c.height); }); @@ -219,16 +282,35 @@ async fn stream( let _ = audio_udp.send_to(a_port, build_liveness(a_ours, "", &[b])).await; } if last_video.elapsed() > Duration::from_secs(4) { - want_key = true; // a still screen sends nothing; ask again so new viewers get a picture + refresh = true; // a still screen sends nothing; ask again so new viewers get a picture last_video = Instant::now(); } } + _ = orient_tick.tick(), if info.is_some() => { + let answer = match info.as_mut() { + Some(c) => tokio::time::timeout(Duration::from_millis(800), c.invoke("com.apple.coredevice.feature.getdisplayinfo", None)) + .await + .ok() + .and_then(Result::ok), + None => None, + }; + match answer { + Some(v) => { + let r = display_rotation(&v); + if r != rotation { + rotation = r; + m.set(session, |s| s.rotation = r); + } + } + None => info = None, // not supported by this iPhone: stop asking + } + } cmd = rx.recv() => match cmd { - None => break Ok(()), + None => break Ok(Ended::Stopped), Some(Cmd::Input(Input::KeyFrame, r)) => { want_key = true; let _ = r.send(Ok(())); } + Some(Cmd::Input(Input::Refresh, r)) => { let _ = r.send(Ok(())); break Ok(Ended::Restart { auto: false }); } Some(Cmd::Input(i, r)) => { - let res = apply(i, hid.as_mut(), indigo.as_mut()).await; - let _ = r.send(res); + let _ = input_tx.send((i, r)); } Some(Cmd::Screenshot(r)) => { let _ = r.send(screenshot(&mut adapter, &mut hs).await); @@ -236,6 +318,7 @@ async fn stream( } } }; + input_task.abort(); let _ = display.stop_media_stream().await; result } @@ -284,11 +367,33 @@ async fn apply(i: Input, hid: Option<&mut Hid>, indigo: Option<&mut Indigo>) -> } Ok(()) } - Input::KeyFrame => Ok(()), + Input::KeyFrame | Input::Refresh => Ok(()), }; r.map_err(|e| idev::friendly(&e)) } +/// Clockwise degrees (0, 90, 180, 270) that turn the streamed picture upright, from a +/// `getdisplayinfo` answer: the built-in display in use, else the primary one. +fn display_rotation(info: &plist::Value) -> u16 { + let displays = info.as_dictionary().and_then(|d| d.get("displays")).and_then(|v| v.as_array()).map(Vec::as_slice).unwrap_or(&[]); + let get = |d: &plist::Value, k: &str| d.as_dictionary().and_then(|d| d.get(k)).cloned(); + let flag = |d: &plist::Value, k: &str| get(d, k).and_then(|v| v.as_boolean()).unwrap_or(false); + let built_in: Vec<&plist::Value> = displays.iter().filter(|d| !flag(d, "external")).collect(); + let chosen = built_in + .iter() + .find(|d| flag(d, "active")) + .or_else(|| built_in.iter().find(|d| get(d, "backlightState").and_then(|v| v.as_string().map(String::from)).is_some_and(|b| b != "off"))) + .copied() + .or_else(|| displays.iter().find(|d| flag(d, "primary"))) + .or_else(|| displays.first()); + match chosen.and_then(|d| get(d, "currentOrientation")).and_then(|v| v.as_string().map(String::from)).as_deref() { + Some("rot90") => 90, + Some("rot180") => 180, + Some("rot270") => 270, + _ => 0, + } +} + async fn screenshot(adapter: &mut idevice::tcp::handle::AdapterHandle, hs: &mut RsdHandshake) -> Result, String> { let fr = |e: idevice::IdeviceError| idev::friendly(&e); let mut rs = RemoteServerClient::connect_rsd(adapter, hs).await.map_err(fr)?; @@ -310,6 +415,24 @@ mod tests { assert_eq!(s.0, Some(0x1_0002)); } + #[test] + fn reads_the_screen_rotation() { + let d = |pairs: &[(&str, plist::Value)]| plist::Value::Dictionary(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()); + let s = |v: &str| plist::Value::String(v.into()); + let info = d(&[( + "displays", + plist::Value::Array(vec![ + d(&[("external", true.into()), ("currentOrientation", s("rot180"))]), + d(&[("primary", true.into()), ("currentOrientation", s("rot90"))]), + d(&[("active", true.into()), ("currentOrientation", s("rot270"))]), + ]), + )]); + assert_eq!(display_rotation(&info), 270); + let single = d(&[("displays", plist::Value::Array(vec![d(&[("currentOrientation", s("rot90"))])]))]); + assert_eq!(display_rotation(&single), 90); + assert_eq!(display_rotation(&plist::Value::Boolean(true)), 0); + } + #[test] fn reads_the_stream_config() { let answer: plist::Value = plist::Value::Dictionary( diff --git a/standalone/src/server.rs b/standalone/src/server.rs index d4deb83..f223290 100644 --- a/standalone/src/server.rs +++ b/standalone/src/server.rs @@ -164,6 +164,8 @@ pub fn router(app: App) -> Router { .route("/api/screen/input", post(screen_input)) .route("/api/screen/screenshot", get(screen_screenshot)) .route("/api/screen/ws", get(screen_ws)) + // Recordings can be long; they come from the app's own page. + .route("/api/screen/save", post(screen_save).layer(DefaultBodyLimit::max(2 << 30))) .layer(DefaultBodyLimit::max(64 * 1024 * 1024)) .layer(axum::middleware::from_fn(local_only)) .with_state(app) @@ -234,6 +236,42 @@ async fn screen_screenshot(State(app): State) -> Result Ok(([(header::CONTENT_TYPE, "image/png"), (header::CACHE_CONTROL, "no-store")], png).into_response()) } +#[derive(Deserialize)] +struct SaveQ { + name: String, +} + +/// File names the Mirror tab saves: letters, digits, `-`, `_`, `.`; a picture or video. +fn capture_name_ok(name: &str) -> bool { + let ext_ok = [".png", ".mp4", ".webm"].iter().any(|e| name.ends_with(e)); + ext_ok && name.len() <= 120 && !name.starts_with('.') && name.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) +} + +/// Saves a screenshot or recording from the Mirror tab to the folder chosen in Settings +/// (the Downloads folder by default) and returns where it went. +async fn screen_save(State(app): State, Query(q): Query, body: axum::body::Bytes) -> R { + if !capture_name_ok(&q.name) { + return Err(bad("Unexpected file name.")); + } + let chosen = app.store.load()["settings"]["capture_folder"].as_str().map(str::trim).unwrap_or("").to_string(); + let dir = if chosen.is_empty() { + dirs::download_dir().or_else(dirs::home_dir).ok_or(bad("Choose a folder for screenshots and recordings in Settings."))? + } else { + std::path::PathBuf::from(chosen) + }; + tokio::fs::create_dir_all(&dir).await.map_err(|e| bad(format!("Can't use the folder {}: {e}", dir.display())))?; + let (stem, ext) = q.name.rsplit_once('.').unwrap_or((&q.name, "")); + let mut path = dir.join(&q.name); + for n in 1.. { + if !path.exists() { + break; + } + path = dir.join(format!("{stem}-{n}.{ext}")); + } + tokio::fs::write(&path, &body).await.map_err(|e| bad(format!("Can't save to {}: {e}", dir.display())))?; + Ok(Json(json!({"path": path.display().to_string()}))) +} + /// Live picture, sound and status for the Mirror tab or another program; input goes the other way. async fn screen_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgrade) -> Response { use axum::extract::ws::Message; @@ -248,10 +286,27 @@ async fn screen_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgra let _ = socket.send(Message::Binary(c.to_vec().into())).await; } let _ = app.screen.input(crate::screen::Input::KeyFrame).await; + // Inputs run one after another on their own task, so a long one (Siri, typing) doesn't + // hold up the picture; their errors come back here. + let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel::(); + let (err_tx, mut err_rx) = tokio::sync::mpsc::unbounded_channel::(); + let worker = { + let app = app.clone(); + tokio::spawn(async move { + while let Some(i) = input_rx.recv().await { + if let Err(e) = app.screen.input(i).await { + let _ = err_tx.send(e); + } + } + }) + }; // Frames only make sense from a keyframe on: skip until one arrives (also after falling behind). let mut need_key = true; loop { tokio::select! { + Some(e) = err_rx.recv() => { + if socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await.is_err() { break; } + } out = rx.recv() => { let msg = match out { Ok(Out::Text(t)) => Message::Text(t.as_str().into()), @@ -273,12 +328,9 @@ async fn screen_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgra } msg = socket.recv() => match msg { Some(Ok(Message::Text(t))) => { - let reply = match serde_json::from_str::(&t).map_err(|e| e.to_string()).and_then(|v| crate::screen::parse_input(&v)) { - Ok(i) => app.screen.input(i).await.err(), - Err(e) => Some(e), - }; - if let Some(e) = reply { - let _ = socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await; + match serde_json::from_str::(&t).map_err(|e| e.to_string()).and_then(|v| crate::screen::parse_input(&v)) { + Ok(i) => { let _ = input_tx.send(i); } + Err(e) => { let _ = socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await; } } } Some(Ok(_)) => {} @@ -286,6 +338,7 @@ async fn screen_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgra } } } + worker.abort(); }) } @@ -1447,4 +1500,19 @@ mod tests { assert_eq!(screen_screenshot(State(a.clone())).await.unwrap_err().0, 409); assert_eq!(screen_stop(State(a.clone())).await.unwrap_or_else(|e| panic!("{}", e.1)).0["state"], "off"); } + + #[tokio::test] + async fn screen_captures_go_to_the_chosen_folder() { + let a = app(); + let dir = std::env::temp_dir().join(format!("sideport-captures-{}", rand::random::())); + a.store.save(&json!({"settings": {"capture_folder": dir.to_string_lossy()}})).unwrap(); + let save = |name: &str| screen_save(State(a.clone()), Query(SaveQ { name: name.into() }), axum::body::Bytes::from_static(b"png")); + let first = save("shot.png").await.unwrap_or_else(|e| panic!("{}", e.1)).0; + let second = save("shot.png").await.unwrap_or_else(|e| panic!("{}", e.1)).0; + assert_eq!(std::fs::read(first["path"].as_str().unwrap()).unwrap(), b"png"); + assert!(second["path"].as_str().unwrap().ends_with("shot-1.png")); + for bad_name in ["../x.png", "x.exe", ".png", "a/b.png"] { + assert_eq!(save(bad_name).await.unwrap_err().0, 400, "{bad_name}"); + } + } } diff --git a/ui/app.js b/ui/app.js index f404419..270df90 100644 --- a/ui/app.js +++ b/ui/app.js @@ -863,16 +863,11 @@ $("btn-show-sidebar").onclick = () => setSidebarHidden(false); // ------------------------------------------------------------------ tabs function openTab(name) { + setMode("location"); state.tab = name; document.querySelectorAll(".tabs button").forEach((x) => x.classList.toggle("active", x.dataset.tab === name)); document.querySelectorAll(".tab-panel").forEach((p) => (p.hidden = p.id !== `tab-${name}`)); map.getContainer().style.cursor = name === "route" ? "crosshair" : ""; - const mirroring = name === "mirror"; - if (document.body.classList.contains("mirroring") !== mirroring) { - document.body.classList.toggle("mirroring", mirroring); - $("mirror-view").hidden = !mirroring; - if (mirroring) fitMirror(); else requestAnimationFrame(() => map.invalidateSize()); - } } document.querySelectorAll(".tabs button").forEach((b) => b.addEventListener("click", () => openTab(b.dataset.tab))); @@ -2627,7 +2622,7 @@ function keyVector() { } const typing = () => ["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement.tagName) || !!document.querySelector("dialog[open]"); function joystickKeydown(e) { - if (state.tab !== "joystick" || !KEYS[e.code] || typing()) return false; + if (state.tab !== "joystick" || document.body.classList.contains("mode-screen") || !KEYS[e.code] || typing()) return false; e.preventDefault(); if (!held.has(e.code)) { held.add(e.code); @@ -2676,7 +2671,7 @@ const ACTIONS = [ ["tab-gpx", "3", "GPX tab", () => openTab("gpx")], ["tab-joystick", "4", "Joystick tab", () => openTab("joystick")], ["tab-saved", "5", "Saved tab", () => openTab("saved")], - ["tab-mirror", "6", "Mirror tab", () => openTab("mirror")], + ["screen", "6", "Screen section (mirroring)", () => setMode("screen")], ]; const actionById = Object.fromEntries(ACTIONS.map((a) => [a[0], a])); function shortcutMap() { @@ -2791,6 +2786,7 @@ function applySettings(s) { $("google-key").value = s.google_api_key || ""; $("pref-compact").checked = !!s.compact; $("pref-channel").value = s.update_channel === "dev" ? "dev" : "stable"; + renderCaptureFolder(); if (s.sidebar_w) setSidebarWidth(s.sidebar_w, false); applyAppearance(); applySections(); @@ -3290,8 +3286,9 @@ document.addEventListener("pointerdown", (e) => { // ------------------------------------------------------------------ screen mirroring // The server sends the phone's screen as HEVC frames (decoded here with WebCodecs) and its sound as -// PCM over /api/screen/ws; touches and keys go back as JSON. Message layout: see standalone/src/mirror. -const mirror = { ws: null, decoder: null, status: { state: "off" }, audio: null, nextAudio: 0, recorder: null, down: false, typing: false }; +// PCM over /api/screen/ws; touches and keys go back as JSON. Message layout: see standalone/src/screen. +const mirror = { ws: null, decoder: null, config: null, supported: {}, status: { state: "off" }, audio: null, nextAudio: 0, + recorder: null, down: false, turn: 0, lastKeyAsk: 0, errors: 0, wheel: null, stats: null }; // KeyboardEvent.code -> HID keyboard usage. Ctrl is sent as the iPhone's Command key. const HID_KEYS = (() => { const m = { Enter: 40, NumpadEnter: 40, Escape: 41, Backspace: 42, Tab: 43, Space: 44, Minus: 45, Equal: 46, BracketLeft: 47, @@ -3304,10 +3301,31 @@ const HID_KEYS = (() => { return m; })(); +// Location or Screen: the two sections of the app. Screen hides the location tools and the map. +function setMode(mode) { + const screen = mode === "screen"; + document.querySelectorAll("#modes button").forEach((b) => b.classList.toggle("active", b.dataset.mode === mode)); + try { localStorage.setItem("ls-mode", mode); } catch (_) { /* storage blocked */ } + if (document.body.classList.contains("mode-screen") === screen) return; + document.body.classList.toggle("mode-screen", screen); + $("mirror-view").hidden = !screen; + $("screen-panel").hidden = !screen; + if (screen) fitMirror(); else requestAnimationFrame(() => map.invalidateSize()); +} +document.querySelectorAll("#modes button").forEach((b) => b.addEventListener("click", () => setMode(b.dataset.mode))); + function mirrorSend(msg) { if (mirror.ws && mirror.ws.readyState === 1) mirror.ws.send(JSON.stringify(msg)); } +// Ask for a fresh full frame, at most once a second (the phone's encoder stalls if asked too often). +function askKeyframe() { + const now = performance.now(); + if (now - mirror.lastKeyAsk < 1000) return; + mirror.lastKeyAsk = now; + mirrorSend({ t: "keyframe" }); +} function renderMirror(s) { + const turned = (s.rotation || 0) !== (mirror.status.rotation || 0); mirror.status = s; const on = s.state === "on", busy = s.state === "starting"; $("btn-mirror").textContent = on ? "Stop mirroring" : busy ? "Starting…" : "Start mirroring"; @@ -3318,53 +3336,103 @@ function renderMirror(s) { box.textContent = on ? `Mirroring${s.width ? ` · ${s.width}×${s.height}` : ""}${s.audio ? " · with sound" : ""}${s.note ? `. ${s.note}` : ""}` : s.state === "error" ? s.error : busy ? "Starting… (unlock the iPhone)" : "Not mirroring"; - for (const b of [...$("mirror-buttons").children, $("btn-mirror-shot"), $("btn-mirror-rec"), $("btn-mirror-type")]) b.disabled = !on; + for (const b of [...$("mirror-tools").querySelectorAll("button"), $("btn-mirror-type")]) b.disabled = !on; + $("btn-mirror-stats").disabled = false; $("mirror-empty").hidden = on && !s.simulated && $("mirror-canvas").hasAttribute("width"); if (on && s.simulated) { $("mirror-empty").textContent = "Simulator: there is no real screen. Clicks and keys are accepted and ignored."; } else if (!on) { $("mirror-empty").textContent = s.state === "error" ? s.error : "Press Start mirroring to see the iPhone's screen here."; } + if (turned) { + mirror.turn = 0; // the phone says which way it is now; drop the manual turn + if (mirror.prev) drawMirror(mirror.prev); + } if (on) mirrorOpen(); else if (!busy) mirrorClose(); } +// Clockwise degrees the picture is turned: the phone's own orientation plus the Rotate button. +const mirrorTurn = () => ((mirror.status.rotation || 0) + mirror.turn) % 360; function fitMirror() { const c = $("mirror-canvas"), view = $("mirror-view"); if (!c.width || !c.height) return; - const k = Math.min((view.clientWidth - 32) / c.width, (view.clientHeight - 32) / c.height); + const tools = $("mirror-tools").getBoundingClientRect(); + const wide = view.clientWidth > 760; + const w = view.clientWidth - 32 - (wide ? tools.width + 14 : 0), h = view.clientHeight - 32 - (wide ? 0 : tools.height + 14); + const k = Math.min(w / c.width, h / c.height); c.style.width = `${Math.max(1, c.width * k)}px`; c.style.height = `${Math.max(1, c.height * k)}px`; } new ResizeObserver(fitMirror).observe($("mirror-view")); +function drawMirror(frame) { + const c = $("mirror-canvas"), turn = mirrorTurn(), side = turn % 180 !== 0; + const w = side ? frame.displayHeight : frame.displayWidth, h = side ? frame.displayWidth : frame.displayHeight; + if (c.width !== w || c.height !== h) { + c.width = w; + c.height = h; + fitMirror(); + $("mirror-empty").hidden = true; + } + const ctx = c.getContext("2d"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (turn === 90) ctx.setTransform(0, 1, -1, 0, w, 0); + else if (turn === 180) ctx.setTransform(-1, 0, 0, -1, w, h); + else if (turn === 270) ctx.setTransform(0, -1, 1, 0, 0, h); + ctx.drawImage(frame, 0, 0); +} + +// A new decoder for the current setup; the old one is dropped (also after a decoding error, +// after which WebCodecs refuses further frames). Waits for a keyframe and asks for one. +function mirrorMakeDecoder() { + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = null; + if (!mirror.config) return; + const pending = new Map(); // timestamp -> when it went in, for the decode delay + mirror.decoder = new VideoDecoder({ + output: (frame) => { + mirror.errors = 0; + const st = mirror.stats, t = pending.get(frame.timestamp); + if (st) { st.frames++; if (t !== undefined) { st.decodeMs += performance.now() - t; st.decoded++; } } + pending.delete(frame.timestamp); + drawMirror(frame); + if (mirror.prev) mirror.prev.close(); + mirror.prev = frame; // kept until the next one, to redraw a still screen when it turns + }, + error: () => { + if (++mirror.errors > 3) { + $("mirror-empty").hidden = false; + $("mirror-empty").textContent = "The picture can't be decoded. Press Refresh, or stop and start mirroring."; + return; + } + mirrorMakeDecoder(); + }, + }); + mirror.decoder.configure(mirror.config); + mirror.pending = pending; + mirror.waitKey = true; + mirror.lastKeyAsk = 0; + askKeyframe(); +} + async function mirrorDecoder(view) { const w = view.getUint16(1), h = view.getUint16(3), n = view.getUint8(5); const codec = new TextDecoder().decode(new Uint8Array(view.buffer, 6, n)); const config = { codec, description: new Uint8Array(view.buffer, 6 + n).slice(), codedWidth: w, codedHeight: h, optimizeForLatency: true }; - if (typeof VideoDecoder === "undefined" || !(await VideoDecoder.isConfigSupported(config)).supported) { + mirror.config = config; + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = null; // frames that come meanwhile are dropped; the new decoder asks for a keyframe + if (mirror.supported[codec] === undefined) { + mirror.supported[codec] = typeof VideoDecoder !== "undefined" && (await VideoDecoder.isConfigSupported(config)).supported; + } + if (!mirror.supported[codec]) { $("mirror-empty").hidden = false; $("mirror-empty").textContent = "This computer can't decode the iPhone's video (HEVC). Update the graphics driver, or install " + "“HEVC Video Extensions” from the Microsoft Store, then start mirroring again."; return; } - if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); - const c = $("mirror-canvas"), ctx = c.getContext("2d"); - mirror.decoder = new VideoDecoder({ - output: (frame) => { - if (c.width !== frame.displayWidth || c.height !== frame.displayHeight) { - c.width = frame.displayWidth; - c.height = frame.displayHeight; - fitMirror(); - $("mirror-empty").hidden = true; - } - ctx.drawImage(frame, 0, 0); - frame.close(); - }, - error: () => { mirror.waitKey = true; mirrorSend({ t: "keyframe" }); }, - }); - mirror.decoder.configure(config); - mirror.waitKey = true; + if (mirror.config === config) mirrorMakeDecoder(); } function mirrorAudio(view) { @@ -3385,6 +3453,26 @@ function mirrorAudio(view) { mirror.nextAudio += n / 48000; } +function mirrorFrame(data, v) { + const st = mirror.stats; + if (st) st.bytes += data.byteLength; + const key = v.getUint8(1) === 1; + if (!mirror.decoder || mirror.decoder.state !== "configured") return; + if (mirror.waitKey && !key) { if (st) st.dropped++; askKeyframe(); return; } + // Behind by more than a few frames: drop until the next keyframe rather than lag further. + if (!key && mirror.decoder.decodeQueueSize > 6) { mirror.waitKey = true; if (st) st.dropped++; askKeyframe(); return; } + mirror.waitKey = false; + if (st && key) st.keys++; + const timestamp = Number(v.getBigUint64(2)); + mirror.pending.set(timestamp, performance.now()); + if (mirror.pending.size > 60) mirror.pending.clear(); + try { + mirror.decoder.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp, data: new Uint8Array(data, 10) })); + } catch (_) { + mirrorMakeDecoder(); // the decoder refused the chunk (closed after an error) + } +} + function mirrorOpen() { if (mirror.ws) return; const ws = new WebSocket(`ws://${location.host}/api/screen/ws`); @@ -3401,14 +3489,7 @@ function mirrorOpen() { const kind = v.getUint8(0); if (kind === 1) mirrorDecoder(v); else if (kind === 3) mirrorAudio(v); - else if (kind === 2 && mirror.decoder && mirror.decoder.state === "configured") { - const key = v.getUint8(1) === 1; - if (mirror.waitKey && !key) return; - // Behind by more than a few frames: drop until the next keyframe rather than lag further. - if (!key && mirror.decoder.decodeQueueSize > 6) { mirror.waitKey = true; mirrorSend({ t: "keyframe" }); return; } - mirror.waitKey = false; - mirror.decoder.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp: Number(v.getBigUint64(2)), data: new Uint8Array(e.data, 10) })); - } + else if (kind === 2) mirrorFrame(e.data, v); }; ws.onclose = () => { if (mirror.ws === ws) { mirror.ws = null; if (mirror.status.state === "on") setTimeout(mirrorOpen, 1000); } }; } @@ -3419,7 +3500,8 @@ function mirrorClose() { mirror.ws = null; if (ws) ws.close(); if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); - mirror.decoder = null; + mirror.decoder = mirror.config = null; + if (mirror.prev) { mirror.prev.close(); mirror.prev = null; } if (mirror.audio) { mirror.audio.ctx.close(); mirror.audio = null; } const c = $("mirror-canvas"); c.removeAttribute("width"); @@ -3447,10 +3529,6 @@ $("btn-mirror").onclick = guard(async () => { } }); -$("mirror-buttons").onclick = (e) => { - const b = e.target.closest("[data-button]"); - if (b) mirrorSend({ t: "button", name: b.dataset.button }); -}; $("btn-mirror-type").onclick = guard(async () => { const text = $("mirror-text").value; if (!text) return; @@ -3459,68 +3537,104 @@ $("btn-mirror-type").onclick = guard(async () => { }); $("mirror-text").addEventListener("keydown", (e) => { if (e.key === "Enter") $("btn-mirror-type").click(); }); -function saveBlob(blob, name) { - const a = el("a", { href: URL.createObjectURL(blob), download: name }); - document.body.append(a); a.click(); a.remove(); - setTimeout(() => URL.revokeObjectURL(a.href), 60000); +// ---- positions: the picture as shown (turned upright) vs. the phone's own screen +// A point on the picture (fractions, 0..1) -> the same point on the phone's native screen. +function toPhone(u, v) { + const turn = mirrorTurn(); + const p = turn === 90 ? [v, 1 - u] : turn === 180 ? [1 - u, 1 - v] : turn === 270 ? [1 - v, u] : [u, v]; + return { x: Math.min(1, Math.max(0, p[0])), y: Math.min(1, Math.max(0, p[1])) }; } -const stamp = () => new Date().toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-"); -$("btn-mirror-shot").onclick = guard(async () => { - const c = $("mirror-canvas"); - if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); - saveBlob(await new Promise((r) => c.toBlob(r, "image/png")), `sideport-screenshot-${stamp()}.png`); -}); -$("btn-mirror-rec").onclick = guard(async () => { - const btn = $("btn-mirror-rec"); - if (mirror.recorder) { mirror.recorder.stop(); return; } - const c = $("mirror-canvas"); - if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); - const stream = c.captureStream(60); - if (mirror.audio) mirror.audio.tap.stream.getAudioTracks().forEach((t) => stream.addTrack(t)); - const type = ["video/mp4;codecs=avc1.640028,mp4a.40.2", "video/mp4", "video/webm;codecs=vp9,opus", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)); - const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 12e6 }); - const parts = []; - rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); }; - rec.onstop = () => { - mirror.recorder = null; - btn.classList.remove("recording"); - btn.querySelector("span").textContent = "Record"; - if (parts.length) saveBlob(new Blob(parts, { type: rec.mimeType }), `sideport-recording-${stamp()}.${rec.mimeType.startsWith("video/mp4") ? "mp4" : "webm"}`); - }; - rec.start(1000); - mirror.recorder = rec; - btn.classList.add("recording"); - btn.querySelector("span").textContent = "Stop recording"; -}); - -// Touch: the pointer's position as a fraction of the picture. -const canvasPoint = (e) => { +const viewPoint = (e) => { const r = $("mirror-canvas").getBoundingClientRect(); - return { x: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)), y: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)) }; + return { u: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)), v: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)) }; }; +// The finger on screen: a dot while pressed, a ripple when it lifts. +function showTouch(p, phase) { + const dot = $("mirror-touch"), c = $("mirror-canvas"); + dot.style.translate = `${p.u * c.clientWidth}px ${p.v * c.clientHeight}px`; + if (phase === "down") { dot.hidden = false; dot.className = "mirror-touch"; requestAnimationFrame(() => dot.classList.add("down")); } + if (phase === "up") dot.className = "mirror-touch up"; +} +function touch(phase, p) { + showTouch(p, phase); + mirrorSend({ t: "touch", phase, ...toPhone(p.u, p.v) }); +} + const mc = $("mirror-canvas"); mc.addEventListener("pointerdown", (e) => { - if (e.button !== 0) return; + if (e.button !== 0 || mirror.wheel) return; mc.setPointerCapture(e.pointerId); mirror.down = true; - mirrorSend({ t: "touch", phase: "down", ...canvasPoint(e) }); + touch("down", viewPoint(e)); }); mc.addEventListener("pointermove", (e) => { if (!mirror.down) return; - const p = canvasPoint(e); // Pointer events can come faster than the screen refreshes: send the newest once per frame. - if (!mirror.pending) requestAnimationFrame(() => { mirrorSend({ t: "touch", phase: "move", ...mirror.pending }); mirror.pending = null; }); - mirror.pending = p; + if (!mirror.pending_move) requestAnimationFrame(() => { if (mirror.down && mirror.pending_move) touch("move", mirror.pending_move); mirror.pending_move = null; }); + mirror.pending_move = viewPoint(e); }); const touchUp = (e) => { if (!mirror.down) return; mirror.down = false; - mirror.pending = null; - mirrorSend({ t: "touch", phase: "up", ...canvasPoint(e) }); + mirror.pending_move = null; + touch("up", viewPoint(e)); }; mc.addEventListener("pointerup", touchUp); mc.addEventListener("pointercancel", touchUp); mc.addEventListener("contextmenu", (e) => { e.preventDefault(); mirrorSend({ t: "button", name: "home" }); }); + +// Mouse wheel / trackpad: a finger drag that follows the wheel, lifted when the wheel rests. +mc.addEventListener("wheel", (e) => { + e.preventDefault(); + if (mirror.down || mirror.status.state !== "on") return; + const r = mc.getBoundingClientRect(), line = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? r.height : 1; + let dx = e.deltaX * line, dy = e.deltaY * line; + if (e.shiftKey && !dx) [dx, dy] = [dy, 0]; + const w = mirror.wheel || (mirror.wheel = { start: viewPoint(e), p: null }); + if (!w.p) { w.p = { ...w.start }; touch("down", w.p); } + w.p = { u: w.p.u - dx / r.width, v: w.p.v - dy / r.height }; + const out = w.p.u < 0.03 || w.p.u > 0.97 || w.p.v < 0.03 || w.p.v > 0.97; + w.p = { u: Math.min(0.97, Math.max(0.03, w.p.u)), v: Math.min(0.97, Math.max(0.03, w.p.v)) }; + touch("move", w.p); + clearTimeout(w.timer); + if (out) { touch("up", w.p); w.p = null; } // reached the edge: lift, the next turn starts again where it began + w.timer = setTimeout(() => { if (w.p) touch("up", w.p); mirror.wheel = null; }, 160); +}, { passive: false }); + +// System gestures, drawn on the upright picture: [start, end], how long the drag takes, how long to hold. +const GESTURES = { + switcher: [[0.5, 0.995], [0.5, 0.62], 260, 450], + control: [[0.92, 0.004], [0.92, 0.45], 260, 0], + notices: [[0.3, 0.004], [0.3, 0.6], 260, 0], + back: [[0.004, 0.5], [0.65, 0.5], 260, 0], +}; +async function gesture(name) { + const [[u1, v1], [u2, v2], ms, hold] = GESTURES[name]; + const sleep = (t) => new Promise((r) => setTimeout(r, t)); + touch("down", { u: u1, v: v1 }); + const steps = Math.max(2, Math.round(ms / 16)); + for (let i = 1; i <= steps; i++) { + await sleep(16); + touch("move", { u: u1 + (u2 - u1) * i / steps, v: v1 + (v2 - v1) * i / steps }); + } + if (hold) await sleep(hold); + touch("up", { u: u2, v: v2 }); +} +$("mirror-tools").addEventListener("click", (e) => { + const b = e.target.closest("button"); + if (!b) return; + if (b.dataset.button) mirrorSend({ t: "button", name: b.dataset.button }); + else if (b.dataset.gesture) gesture(b.dataset.gesture); +}); +$("btn-mirror-rotate").onclick = () => { + mirror.turn = (mirror.turn + 90) % 360; + if (mirror.prev) drawMirror(mirror.prev); // show it now, even on a still screen +}; +$("btn-mirror-refresh").onclick = guard(async () => { + await api("/api/screen/input", { body: { t: "refresh" } }); + toast("Restarting the picture…"); +}); + // Keys go to the iPhone while the picture has focus (click it); the app's shortcuts stay off meanwhile. mc.addEventListener("focus", () => mc.classList.add("typing")); mc.addEventListener("blur", () => { mc.classList.remove("typing"); }); @@ -3534,6 +3648,71 @@ for (const type of ["keydown", "keyup"]) { }); } +// ---- screenshots and recordings: saved by the app to the folder chosen in Settings › Screen +const stamp = () => new Date().toISOString().slice(0, 23).replace(/[-:]/g, "").replace("T", "-").replace(".", ""); +async function saveCapture(blob, name) { + const r = await fetch(`/api/screen/save?name=${encodeURIComponent(name)}`, { method: "POST", body: blob }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(errorText(data, r.status)); + toast(`Saved to ${data.path}`); +} +function renderCaptureFolder() { + const f = (settings().capture_folder || "").trim(); + $("capture-folder").value = f; + $("capture-folder-hint").textContent = f || "your Downloads folder"; +} +$("capture-folder").addEventListener("change", (e) => { settings().capture_folder = e.target.value.trim(); renderCaptureFolder(); saveSettingsSoon(); }); +$("link-capture-settings").onclick = (e) => { e.preventDefault(); openSettings("screen"); }; +$("btn-mirror-shot").onclick = guard(async () => { + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + await saveCapture(await new Promise((r) => c.toBlob(r, "image/png")), `sideport-screenshot-${stamp()}.png`); +}); +$("btn-mirror-rec").onclick = guard(async () => { + const btn = $("btn-mirror-rec"); + if (mirror.recorder) { mirror.recorder.stop(); return; } + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + const stream = c.captureStream(60); + if (mirror.audio) mirror.audio.tap.stream.getAudioTracks().forEach((t) => stream.addTrack(t)); + const type = ["video/mp4;codecs=avc1.640028,mp4a.40.2", "video/mp4", "video/webm;codecs=vp9,opus", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)); + const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 12e6 }); + const parts = []; + rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); }; + rec.onstop = guard(async () => { + mirror.recorder = null; + btn.classList.remove("recording"); + btn.querySelector("span").textContent = "Record"; + if (parts.length) await saveCapture(new Blob(parts, { type: rec.mimeType }), `sideport-recording-${stamp()}.${rec.mimeType.startsWith("video/mp4") ? "mp4" : "webm"}`); + }); + rec.start(1000); + mirror.recorder = rec; + btn.classList.add("recording"); + btn.querySelector("span").textContent = "Stop"; +}); + +// ---- performance: frame rate, data rate, decode delay, dropped frames, sound buffer +function newStats() { return { frames: 0, bytes: 0, decodeMs: 0, decoded: 0, dropped: 0, keys: 0, total: 0, at: performance.now() }; } +setInterval(() => { + const st = mirror.stats, box = $("mirror-stats"); + if (!st || box.hidden) return; + const s = (performance.now() - st.at) / 1000, c = $("mirror-canvas"); + st.total += st.dropped; + const sound = mirror.audio ? ` sound buffer ${Math.max(0, Math.round((mirror.nextAudio - mirror.audio.ctx.currentTime) * 1000))} ms` : ""; + box.textContent = `${Math.round(st.frames / s)} fps ${(st.bytes * 8 / s / 1e6).toFixed(1)} Mbit/s decode ${st.decoded ? (st.decodeMs / st.decoded).toFixed(1) : "–"} ms\n` + + `${c.width}×${c.height} dropped ${st.total} keyframes ${st.keys}${sound}`; + Object.assign(st, { frames: 0, bytes: 0, decodeMs: 0, decoded: 0, dropped: 0, at: performance.now() }); +}, 1000); +function setStats(on) { + mirror.stats = on ? newStats() : null; + $("mirror-stats").hidden = !on; + $("mirror-stats").textContent = "Measuring…"; + $("btn-mirror-stats").classList.toggle("on", on); + try { localStorage.setItem("ls-mirror-stats", on ? "1" : ""); } catch (_) { /* storage blocked */ } +} +$("btn-mirror-stats").onclick = () => setStats(!mirror.stats); +try { if (localStorage.getItem("ls-mirror-stats")) setStats(true); } catch (_) { /* storage blocked */ } + // ------------------------------------------------------------------ boot wireInfoButtons(); wireSections(); @@ -3550,6 +3729,7 @@ function notifyReady() { try { await loadStore(); } finally { requestAnimationFrame(() => requestAnimationFrame(notifyReady)); } await refreshGoogleStatus(); api("/api/screen").then(renderMirror, () => {}); + try { if (localStorage.getItem("ls-mode") === "screen") setMode("screen"); } catch (_) { /* storage blocked */ } await poll(); refreshDevices(false); if (!settings().tutorial_done) openTutorial(0); diff --git a/ui/index.html b/ui/index.html index eb965e8..604efa4 100644 --- a/ui/index.html +++ b/ui/index.html @@ -94,6 +94,11 @@

Sideport

+ +
@@ -157,7 +162,7 @@

Sideport

-
+
@@ -171,7 +176,6 @@

Sideport

- @@ -367,31 +371,6 @@

Sideport

- - - @@ -512,6 +534,7 @@

Sideport

+ @@ -577,6 +600,12 @@

Theme

Saved areas

    + @@ -534,7 +540,7 @@

    iDevBench

    - + @@ -602,9 +608,10 @@

    Saved areas