Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

29.5 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// The iOS control helper: a cabled iPhone's or iPad's screen, touch screen, buttons and keyboard on
// this computer, through CoreDevice (what Xcode's device window uses): its screen stream (HEVC, the
// device's own encoder, ~60 fps) and its remote HID. iOS 27 or later, Developer Mode on, the device
// paired with this computer; nothing is installed on it. Older iOS answers "Remote control requires
// iOS 27.0 or later on this device." (passed on as it is; the app then shows the screen another way).
//
//   twindesk-ios-control list        the devices on the cable: [{"id":udid,"name":…,"version":"27.2.1"}]
//   twindesk-ios-control watch       the same, a line each time it changes, until stdin closes
//   twindesk-ios-control [udid] [--ddi DIR]   a session with one (the first when left out). DIR: Apple's
//                                    developer disk image (a DDI Restore directory: Xcode's
//                                    /Library/Developer/DeveloperDiskImages/iOS_DDI/Restore, or a copy):
//                                    mounted first when the device has none (remote input comes from it;
//                                    Xcode mounts it on a Mac it's used on), personalized by Apple's TSS
//                                    server for this device as Xcode does
//
// A session is what mac-helper's macshare-iosusb capture is to mac/iosusb.js, plus input: lines of
// JSON on stderr ({"event":"started","name":…}, {"event":"error","message":…}, {"event":"ended",
// "why":"unplugged"|…}), the picture on stdout in scrcpy's framing (12 bytes: a size packet, its
// first bit set, with width and height; else pts and flags (config, key) then the length, and the
// Annex-B data; the config packet carries VPS, SPS and PPS), and lines of JSON on stdin:
//
//   {"op":"touch","s":"down"|"move"|"up","x":0…1,"y":0…1}     one finger, across the picture
//   {"op":"button","b":"home"|"lock"|"volume_up"|"volume_down"|"mute"|"siri","s":"down"|"up"|"press"}
//   {"op":"key","u":usage,"s":"down"|"up"}                     a HID keyboard usage (page 7)
//   {"op":"keyframe"}                                          the decoder lost its place
//
// It ends when stdin closes. The stream is also what lets the device take input: backboardd drops
// every remote HID event while no screen stream is open. Both the picture and the touch screen are
// the device held upright, whatever way it's turned, so a point in the picture is a point to touch.
// The stream has to be stopped before the tunnel goes: otherwise the device keeps showing it's
// being viewed and doesn't lock by itself.
//
// The stream setup follows idevice's tools/src/coredevice_stream.rs (MIT, Jackson Coxson); the RTCP
// answers (a frame ack per frame, RCTL every 50 ms, a report every second) are Device Hub's, as
// iphone-control (MIT) does them.

use std::time::{Duration, Instant};

use idevice::{
    IdeviceService, ReadWrite, RsdService,
    provider::IdeviceProvider,
    core_device::{
        ButtonState, CallInfoBlob, DisplayServiceClient, HevcDepacketizer, IndigoHidClient, RtpPacket,
        TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, UniversalHidServiceClient, build_frame_ack,
        build_keyframe_request, build_liveness, build_rctl, build_screen_audio_offer, build_screen_video_offer,
        build_start_audio_parameters, build_start_video_parameters, is_rtcp,
    },
    core_device_proxy::CoreDeviceProxy,
    cryptexd::{Cryptex1Assets, install_ddi, installed_ddi},
    lockdown::LockdownClient,
    rsd::RsdHandshake,
    tcp::handle::{AdapterHandle, UdpSocketHandle},
    usbmuxd::{Connection, UsbmuxdAddr, UsbmuxdConnection, UsbmuxdDevice},
};
use futures_util::StreamExt;
use serde::Deserialize;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::mpsc;

// Ours (the controller's), not the device's: Device Hub's screen sharing sends 140.
const CLIENT_SUPPORTED_FEATURES: u64 = 140;
const STEP: Duration = Duration::from_secs(15);
const HID_MAX: f64 = 65535.0;
const MAX_FRAME: usize = 8 * 1024 * 1024;
const KEYFRAME_EVERY: Duration = Duration::from_millis(300);
const CONFIG: u64 = 1 << 62;
const KEY: u64 = 1 << 61;

#[derive(Deserialize)]
struct Cmd {
    op: String,
    #[serde(default)]
    s: String,
    #[serde(default)]
    x: f64,
    #[serde(default)]
    y: f64,
    #[serde(default)]
    b: String,
    #[serde(default)]
    u: u64,
}

fn event(v: serde_json::Value) {
    eprintln!("{v}");
}

fn fail(message: impl std::fmt::Display) -> ! {
    event(serde_json::json!({ "event": "error", "message": message.to_string() }));
    std::process::exit(1);
}

async fn step<T, E: std::fmt::Debug>(what: &str, f: impl Future<Output = Result<T, E>>) -> T {
    match tokio::time::timeout(STEP, f).await {
        Ok(Ok(v)) => v,
        Ok(Err(e)) => fail(format!("{what}: {}", readable(&format!("{e:?}")))),
        Err(_) => fail(format!("{what}: timed out")),
    }
}

// CoreDevice's errors come as a debug dump with the NSLocalizedDescription inside: that sentence
// is what the person should see ("Remote control requires iOS 27.0 or later on this device.").
fn readable(e: &str) -> String {
    let k = "NSLocalizedDescription\": String(\"";
    if let Some(i) = e.find(k) {
        let rest = &e[i + k.len()..];
        if let Some(j) = rest.find("\")") {
            return rest[..j].to_string();
        }
    }
    e.chars().take(300).collect()
}

async fn usb_devices() -> Vec<UsbmuxdDevice> {
    let Ok(mut mux) = UsbmuxdConnection::default().await else { return vec![] };
    mux.get_devices().await.unwrap_or_default().into_iter().filter(|d| matches!(d.connection_type, Connection::Usb)).collect()
}

// A domain's values want a session (the pairing record usbmuxd keeps for the device).
async fn lockdown(dev: &UsbmuxdDevice, key: &str, domain: Option<&str>) -> Option<plist::Value> {
    let provider = dev.to_provider(UsbmuxdAddr::default(), "twindesk-ios-control");
    let t = Duration::from_secs(5);
    let mut l = tokio::time::timeout(t, LockdownClient::connect(&provider)).await.ok()?.ok()?;
    if domain.is_some() {
        let pairing = tokio::time::timeout(t, provider.get_pairing_file()).await.ok()?.ok()?;
        tokio::time::timeout(t, l.start_session(&pairing)).await.ok()?.ok()?;
    }
    tokio::time::timeout(t, l.get_value(Some(key), domain)).await.ok()?.ok()
}

async fn lockdown_value(dev: &UsbmuxdDevice, key: &str) -> Option<String> {
    lockdown(dev, key, None).await?.as_string().map(str::to_string)
}

// The screen's pixels, upright. The stream's picture is that padded to the encoder's blocks (an SE's
// 750×1334 comes as 752×1344), with no crop in its SPS: the window crops it to this.
async fn screen_size(dev: &UsbmuxdDevice) -> Option<(u32, u32)> {
    let d = Some("com.apple.mobile.iTunes");
    let w = lockdown(dev, "ScreenWidth", d).await?.as_unsigned_integer()?;
    let h = lockdown(dev, "ScreenHeight", d).await?.as_unsigned_integer()?;
    let (w, h) = (w.min(h) as u32, w.max(h) as u32);
    (w > 0 && h < 16384).then_some((w, h))
}

async fn list() -> String {
    let mut out = vec![];
    for d in usb_devices().await {
        let name = lockdown_value(&d, "DeviceName").await.unwrap_or_default();
        let version = lockdown_value(&d, "ProductVersion").await.unwrap_or_default();
        out.push(serde_json::json!({ "id": d.udid, "name": name, "version": version }));
    }
    serde_json::Value::Array(out).to_string()
}

// usbmuxd says when a device comes or goes; the list is read again a moment later (a device that
// was just plugged in answers lockdown after a moment, and macOS's capture makes it leave and come
// back in a second).
async fn watch() {
    tokio::spawn(async {
        let mut stdin = tokio::io::stdin();
        let mut buf = [0u8; 64];
        while matches!(tokio::io::AsyncReadExt::read(&mut stdin, &mut buf).await, Ok(n) if n > 0) {}
        std::process::exit(0);
    });
    let mut last = String::new();
    loop {
        if let Ok(mut mux) = UsbmuxdConnection::default().await
            && let Ok(mut events) = mux.listen().await
        {
            loop {
                let now = list().await;
                if now != last {
                    println!("{now}");
                    last = now;
                }
                match events.next().await {
                    Some(Ok(_)) => tokio::time::sleep(Duration::from_millis(800)).await,
                    _ => break,
                }
            }
        }
        tokio::time::sleep(Duration::from_secs(3)).await;
    }
}

struct Stream {
    client: DisplayServiceClient<Box<dyn ReadWrite>>,
    receive: tokio::task::JoinHandle<()>,
}

async fn start_stream(
    adapter: &mut AdapterHandle,
    handshake: &mut RsdHandshake,
    out: mpsc::Sender<Vec<u8>>,
    keyframe: mpsc::UnboundedReceiver<()>,
    screen: Option<(u32, u32)>,
) -> Stream {
    let mut client = step("display service", DisplayServiceClient::connect_rsd(adapter, handshake)).await;
    let audio = step("audio socket", adapter.bind_udp(0)).await;
    let video = step("video socket", adapter.bind_udp(0)).await;
    let receiver_ip = adapter.host_ip().to_string();
    let sender_ip = adapter.peer_ip().to_string();
    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,
    };
    // Audio first: it opens the screen-sharing session; video joins it.
    let session = uuid::Uuid::new_v4();
    let audio_call = uuid::Uuid::new_v4().to_string().to_uppercase();
    let offer = build_screen_audio_offer(&audio_call, &call_info).unwrap_or_else(|e| fail(format!("audio offer: {e:?}")));
    let params = build_start_audio_parameters(&receiver_ip, audio.local_port(), &sender_ip, 50000, offer, CLIENT_SUPPORTED_FEATURES, session);
    step("screen stream", client.start_media_stream(params)).await;
    let video_call = uuid::Uuid::new_v4().to_string().to_uppercase();
    let ssrc = uuid::Uuid::new_v4().as_u128() as u32;
    let offer = build_screen_video_offer(&video_call, &call_info, ssrc).unwrap_or_else(|e| fail(format!("video offer: {e:?}")));
    let params = build_start_video_parameters(&receiver_ip, video.local_port(), &sender_ip, 50001, offer, CLIENT_SUPPORTED_FEATURES, 1, session);
    if let Err(e) = tokio::time::timeout(STEP, client.start_media_stream(params))
        .await
        .map_err(|_| "timed out".to_string())
        .and_then(|r| r.map_err(|e| readable(&format!("{e:?}"))))
    {
        let _ = client.stop_media_stream().await;
        fail(format!("screen stream: {e}"));
    }
    Stream { client, receive: tokio::spawn(receive(audio, video, ssrc, out, keyframe, screen)) }
}

// The RTP the device sends, read as it comes (the tunnel's UDP queues are unbounded: unread, it
// piles up in memory) and made into whole frames for stdout; audio is only read.
async fn receive(
    audio: UdpSocketHandle,
    video: UdpSocketHandle,
    ssrc: u32,
    out: mpsc::Sender<Vec<u8>>,
    mut keyframe: mpsc::UnboundedReceiver<()>,
    screen: Option<(u32, u32)>,
) {
    let start = Instant::now();
    let mut depack = HevcDepacketizer::new();
    let mut frame = Frames { screen, ..Default::default() };
    let (mut port, mut media_ssrc, mut first, mut last, mut frames) = (0u16, 0u32, None::<u16>, 0u16, 0u16);
    let (mut fir_seq, mut asked, mut want_key) = (0u8, None::<Instant>, false);
    let mut heard = Instant::now();
    let mut rctl = tokio::time::interval(Duration::from_millis(50));
    let mut report = tokio::time::interval(Duration::from_secs(1));
    loop {
        tokio::select! {
            r = audio.recv() => if r.is_err() { return },
            r = video.recv() => {
                let Ok(dg) = r else { return };
                heard = Instant::now();
                if is_rtcp(&dg.data) { continue }
                let Some(p) = RtpPacket::parse(&dg.data) else { continue };
                port = dg.source_port;
                media_ssrc = p.ssrc;
                first.get_or_insert(p.sequence_number);
                last = p.sequence_number;
                if frame.timestamp.is_some_and(|t| t != p.timestamp) {
                    // the marker of the last one was lost: it ends here
                    want_key |= frame.finish(&out);
                }
                frame.timestamp = Some(p.timestamp);
                depack.push(p.sequence_number, p.timestamp, p.payload);
                frame.push(&depack.take_output());
                if p.marker {
                    frames = frames.wrapping_add(1);
                    let _ = video.send_to(port, build_frame_ack(ssrc, p.timestamp)).await;
                    want_key |= frame.finish(&out);
                }
            }
            r = keyframe.recv() => match r { Some(()) => want_key = true, None => return },
            _ = rctl.tick() => if port != 0 {
                let clock = (start.elapsed().as_millis() & 0xffff) as u16;
                let _ = video.send_to(port, build_rctl(ssrc, clock, frames, last.wrapping_sub(first.unwrap_or(last)))).await;
            },
            _ = report.tick() => {
                // Nothing for a while, even on a still screen: the device ended the stream (another
                // tool's session took its place). main starts it again.
                if heard.elapsed() > Duration::from_secs(4) {
                    return;
                }
                if port != 0 {
                    let _ = video.send_to(port, build_liveness(ssrc, "twindesk", &[])).await;
                }
            },
        }
        // The device sends one keyframe at the start and then only when asked (PLI and FIR).
        if want_key && port != 0 && asked.is_none_or(|t| t.elapsed() >= KEYFRAME_EVERY) {
            want_key = false;
            asked = Some(Instant::now());
            fir_seq = fir_seq.wrapping_add(1);
            let _ = video.send_to(port, build_keyframe_request(ssrc, "twindesk", media_ssrc, &[], fir_seq)).await;
        }
    }
}

// One frame's NAL units as they come; the parameter sets go out on their own (a config packet, and
// the size from the SPS) whenever they change, as scrcpy's stream has them.
#[derive(Default)]
struct Frames {
    data: Vec<u8>,
    timestamp: Option<u32>,
    first_ts: Option<u32>,
    params: [Option<Vec<u8>>; 3],
    sent_params: Option<Vec<u8>>,
    size: Option<(u32, u32)>,
    screen: Option<(u32, u32)>,
    overflow: bool,
}

impl Frames {
    fn push(&mut self, annexb: &[u8]) {
        if self.overflow || self.data.len() + annexb.len() > MAX_FRAME {
            self.overflow = true;
            self.data.clear();
            return;
        }
        self.data.extend_from_slice(annexb);
    }

    // true: something was lost (a keyframe is wanted)
    fn finish(&mut self, out: &mpsc::Sender<Vec<u8>>) -> bool {
        let ts = self.timestamp.take().unwrap_or(0);
        let data = std::mem::take(&mut self.data);
        if std::mem::take(&mut self.overflow) {
            return true;
        }
        let mut key = false;
        let mut body = Vec::with_capacity(data.len());
        for n in nal_units(&data) {
            match nal_type(n) {
                Some(t @ 32..=34) => self.params[usize::from(t - 32)] = Some(n.to_vec()),
                Some(t) if t <= 31 => {
                    key |= (16..=23).contains(&t);
                    body.extend_from_slice(n);
                }
                Some(_) => body.extend_from_slice(n),
                None => {}
            }
        }
        if body.is_empty() {
            return false;
        }
        if self.params.iter().any(Option::is_none) {
            return !key; // nothing to decode with yet
        }
        let params: Vec<u8> = self.params.iter().flatten().flatten().copied().collect();
        if self.sent_params.as_ref() != Some(&params) {
            if !key {
                return true;
            }
            if let Some(coded) = sps_size(self.params[1].as_deref().unwrap_or_default())
                && let size = self.screen.filter(|s| s.0 <= coded.0 && s.1 <= coded.1 && coded.0 - s.0 < 32 && coded.1 - s.1 < 32).unwrap_or(coded)
                && self.size != Some(size)
            {
                self.size = Some(size);
                let mut h = vec![0x80, 0, 0, 0];
                h.extend_from_slice(&size.0.to_be_bytes());
                h.extend_from_slice(&size.1.to_be_bytes());
                if !send(out, h, true) {
                    return true;
                }
            }
            if !send(out, packet(CONFIG, &params), true) {
                return true;
            }
            self.sent_params = Some(params);
        }
        let first = *self.first_ts.get_or_insert(ts);
        let pts = u64::from(ts.wrapping_sub(first)) * 100 / 9; // 90 kHz -> µs
        !send(out, packet(pts | if key { KEY } else { 0 }, &body), key)
    }
}

fn packet(flags: u64, data: &[u8]) -> Vec<u8> {
    let mut p = Vec::with_capacity(12 + data.len());
    p.extend_from_slice(&flags.to_be_bytes());
    p.extend_from_slice(&(data.len() as u32).to_be_bytes());
    p.extend_from_slice(data);
    p
}

// The app reads stdout as fast as it can; when it can't keep up, frames are dropped (and a keyframe
// asked for) rather than queued without end. A keyframe or a config packet waits for room.
fn send(out: &mpsc::Sender<Vec<u8>>, p: Vec<u8>, must: bool) -> bool {
    match out.try_send(p) {
        Ok(()) => true,
        Err(mpsc::error::TrySendError::Full(p)) if must => {
            let out = out.clone();
            tokio::spawn(async move { let _ = out.send(p).await; });
            true
        }
        Err(_) => false,
    }
}

fn nal_units(data: &[u8]) -> Vec<&[u8]> {
    let mut starts = Vec::new();
    let mut i = 0;
    while i + 3 <= data.len() {
        if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
            starts.push(if i > 0 && data[i - 1] == 0 { i - 1 } else { i });
            i += 3;
        } else {
            i += 1;
        }
    }
    starts.iter().enumerate().map(|(k, &s)| &data[s..starts.get(k + 1).copied().unwrap_or(data.len())]).collect()
}

fn nal_body(nal: &[u8]) -> Option<&[u8]> {
    if nal.starts_with(&[0, 0, 0, 1]) { Some(&nal[4..]) } else { nal.strip_prefix(&[0, 0, 1]) }
}

fn nal_type(nal: &[u8]) -> Option<u8> {
    nal_body(nal)?.first().map(|b| (b >> 1) & 0x3f)
}

struct Bits<'a> {
    b: &'a [u8],
    at: usize,
}

impl Bits<'_> {
    fn u(&mut self, n: usize) -> Option<u32> {
        let mut v = 0u32;
        for _ in 0..n {
            let byte = *self.b.get(self.at / 8)?;
            v = (v << 1) | u32::from((byte >> (7 - self.at % 8)) & 1);
            self.at += 1;
        }
        Some(v)
    }

    fn ue(&mut self) -> Option<u32> {
        let mut zeros = 0;
        while self.u(1)? == 0 {
            zeros += 1;
            if zeros > 31 {
                return None;
            }
        }
        Some((1u32 << zeros) - 1 + self.u(zeros)?)
    }
}

// The picture's size from an HEVC SPS (H.265 7.3.2.2), its conformance window taken off.
fn sps_size(nal: &[u8]) -> Option<(u32, u32)> {
    let body = nal_body(nal)?.get(2..)?;
    let mut raw = Vec::with_capacity(body.len());
    let mut zeros = 0;
    for &b in body {
        if zeros >= 2 && b == 3 {
            zeros = 0;
            continue;
        }
        zeros = if b == 0 { zeros + 1 } else { 0 };
        raw.push(b);
    }
    let mut r = Bits { b: &raw, at: 0 };
    r.u(4)?;
    let sub_layers = r.u(3)? as usize;
    r.u(1)?;
    r.u(96)?; // general profile, tier and level
    let mut present = vec![];
    for _ in 0..sub_layers {
        present.push((r.u(1)?, r.u(1)?));
    }
    if sub_layers > 0 {
        for _ in sub_layers..8 {
            r.u(2)?;
        }
    }
    for (profile, level) in present {
        if profile == 1 {
            r.u(88)?;
        }
        if level == 1 {
            r.u(8)?;
        }
    }
    r.ue()?;
    let chroma = r.ue()?;
    if chroma == 3 {
        r.u(1)?;
    }
    let (mut w, mut h) = (r.ue()?, r.ue()?);
    if r.u(1)? == 1 {
        let (sw, sh) = match chroma {
            1 => (2, 2),
            2 => (2, 1),
            _ => (1, 1),
        };
        let (left, right, top, bottom) = (r.ue()?, r.ue()?, r.ue()?, r.ue()?);
        w = w.saturating_sub(sw * (left + right));
        h = h.saturating_sub(sh * (top + bottom));
    }
    (w > 0 && h > 0 && w < 16384 && h < 16384).then_some((w, h))
}

fn button(name: &str) -> Option<(u64, u64)> {
    Some(match name {
        "home" => (0x0C, 0x40),
        "lock" => (0x0C, 0x30),
        "volume_up" => (0x0C, 0xE9),
        "volume_down" => (0x0C, 0xEA),
        "mute" => (0x0C, 0xE2),
        "siri" => (0x0C, 0xCF),
        _ => return None,
    })
}

fn hid(v: f64) -> u16 {
    (if v.is_finite() { v } else { 0.0 }.clamp(0.0, 1.0) * HID_MAX).round() as u16
}

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let ddi = args.iter().position(|a| a == "--ddi").and_then(|i| args.get(i + 1)).cloned();
    let arg = args.iter().enumerate().find(|(i, a)| !a.starts_with("--") && !(*i > 0 && args[i - 1] == "--ddi")).map(|(_, a)| a.clone()).filter(|s| !s.is_empty());
    match arg.as_deref() {
        Some("list") => return println!("{}", list().await),
        Some("watch") => return watch().await,
        _ => {}
    }
    // Waited for a moment: macOS's own screen capture starting or stopping makes the device leave
    // USB and come back.
    let mut dev = None;
    for _ in 0..40 {
        dev = usb_devices().await.into_iter().find(|d| arg.as_ref().is_none_or(|w| w == &d.udid));
        if dev.is_some() {
            break;
        }
        tokio::time::sleep(Duration::from_millis(250)).await;
    }
    let dev = dev.unwrap_or_else(|| fail("No iPhone or iPad on a cable. Plug it in, unlock it and tap Trust."));
    let name = lockdown_value(&dev, "DeviceName").await.unwrap_or_default();
    let screen = screen_size(&dev).await;
    let provider = dev.to_provider(UsbmuxdAddr::default(), "twindesk-ios-control");
    let proxy = step("tunnel", CoreDeviceProxy::connect(&provider)).await;
    let rsd_port = proxy.tunnel_info().server_rsd_port;
    let mut adapter = proxy.create_software_tunnel().unwrap_or_else(|e| fail(format!("tunnel: {e:?}"))).to_async_handle();
    let rsd = step("service directory", adapter.connect(rsd_port)).await;
    let mut handshake = step("service directory", RsdHandshake::new(rsd)).await;
    // The developer disk image: remote input (dtuhidd) comes from it. Xcode mounts it on a Mac it's used
    // on; anywhere else, it's mounted here from DIR (it stays until the device restarts).
    match tokio::time::timeout(STEP, installed_ddi(&mut adapter, &mut handshake)).await {
        Ok(Ok(Some(_))) => {}
        Ok(Ok(None)) => match &ddi {
            Some(dir) => {
                event(serde_json::json!({ "event": "ddi", "state": "mounting" }));
                let assets = step("developer disk image", Cryptex1Assets::load(dir)).await;
                match tokio::time::timeout(Duration::from_secs(180), install_ddi(&mut adapter, &mut handshake, &assets)).await {
                    Ok(Ok(_)) => event(serde_json::json!({ "event": "ddi", "state": "mounted" })),
                    Ok(Err(e)) => fail(format!("developer disk image: {}", readable(&format!("{e:?}")))),
                    Err(_) => fail("developer disk image: timed out"),
                }
            }
            None => event(serde_json::json!({ "event": "ddi", "state": "missing" })),
        },
        _ => {} // can't tell (an older iOS): go on
    }

    let (out, mut out_rx) = mpsc::channel::<Vec<u8>>(8);
    let writer = tokio::spawn(async move {
        let mut stdout = tokio::io::stdout();
        while let Some(p) = out_rx.recv().await {
            if stdout.write_all(&p).await.is_err() || stdout.flush().await.is_err() {
                return;
            }
        }
    });
    let (mut keyframe, keyframe_rx) = mpsc::unbounded_channel();
    let mut stream = start_stream(&mut adapter, &mut handshake, out.clone(), keyframe_rx, screen).await;
    // backboardd takes a moment to match the HID surfaces with the stream it just allowed: events
    // sent before that are dropped without an error.
    tokio::time::sleep(Duration::from_millis(400)).await;
    let mut touch = step("touch screen", UniversalHidServiceClient::connect_rsd(&mut adapter, &mut handshake)).await;
    let mut indigo = step("buttons", IndigoHidClient::connect_rsd(&mut adapter, &mut handshake)).await;
    event(serde_json::json!({ "event": "started", "name": name, "udid": dev.udid }));

    let mut lines = BufReader::new(tokio::io::stdin()).lines();
    let mut down = false;
    let mut at = (0u16, 0u16);
    let mut why = "stopped".to_string();
    loop {
        let line = tokio::select! {
            l = lines.next_line() => match l { Ok(Some(l)) => l, _ => break },
            _ = &mut stream.receive => {
                // The picture stopped: once more on the same tunnel (a new config and keyframe
                // follow); a device that's gone fails here and ends the session.
                let _ = tokio::time::timeout(Duration::from_secs(5), stream.client.stop_media_stream()).await;
                if !usb_devices().await.iter().any(|d| d.udid == dev.udid) {
                    why = "unplugged".into();
                    break;
                }
                let (k, rx) = mpsc::unbounded_channel();
                keyframe = k;
                stream = start_stream(&mut adapter, &mut handshake, out.clone(), rx, screen).await;
                continue;
            }
        };
        let Ok(c) = serde_json::from_str::<Cmd>(&line) else { continue };
        let r = match c.op.as_str() {
            "touch" => {
                at = (hid(c.x), hid(c.y));
                match c.s.as_str() {
                    "down" | "move" => {
                        down = true;
                        touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, at.0, at.1, None).await
                    }
                    "up" if down => {
                        down = false;
                        touch.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, at.0, at.1, None).await
                    }
                    _ => Ok(()),
                }
            }
            "button" => match button(&c.b) {
                Some((page, usage)) => match c.s.as_str() {
                    "down" => indigo.send_button(page, usage, ButtonState::Down).await,
                    "up" => indigo.send_button(page, usage, ButtonState::Up).await,
                    _ => {
                        let r = indigo.send_button(page, usage, ButtonState::Down).await;
                        tokio::time::sleep(Duration::from_millis(if c.b == "lock" { 200 } else { 80 })).await;
                        r.and(indigo.send_button(page, usage, ButtonState::Up).await)
                    }
                },
                None => Ok(()),
            },
            "key" if c.u > 0 && c.u < 0x100 => {
                indigo.send_keyboard(c.u, if c.s == "up" { ButtonState::Up } else { ButtonState::Down }).await
            }
            "keyframe" => {
                let _ = keyframe.send(());
                Ok(())
            }
            _ => Ok(()),
        };
        if let Err(e) = r {
            why = format!("The connection to the device ended: {}", readable(&format!("{e:?}")));
            break;
        }
    }
    // A finger still down when the window closed: lift it, or the device keeps it pressed.
    if down {
        let _ = touch.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, at.0, at.1, None).await;
    }
    stream.receive.abort();
    writer.abort();
    let _ = tokio::time::timeout(Duration::from_secs(5), stream.client.stop_media_stream()).await;
    event(serde_json::json!({ "event": "ended", "why": why }));
}

#[cfg(test)]
mod tests {
    use super::*;

    // VPS, SPS and PPS from an iPhone SE on iOS 27.2.1: 750×1334 coded as 752×1344, no crop.
    const SE_CONFIG: &str = "0000000140010c01ffff016000000300b000000300000300780cc09000000001420101016000000300b00000030000030078a005e20054162033b914862e7f13f0bfa1bf50ffaa08fd5413faaa0afd55417faaaa0cfd5554a6e040404010000000014401c072f05b24";

    fn hex(s: &str) -> Vec<u8> {
        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
    }

    #[test]
    fn splits_parameter_sets_and_reads_the_coded_size() {
        let cfg = hex(SE_CONFIG);
        let nals = nal_units(&cfg);
        assert_eq!(nals.iter().map(|n| nal_type(n)).collect::<Vec<_>>(), [Some(32), Some(33), Some(34)]);
        assert_eq!(sps_size(nals[1]), Some((752, 1344)));
    }

    #[test]
    fn a_frame_goes_out_after_its_size_and_config() {
        let (tx, mut rx) = mpsc::channel(8);
        let mut f = Frames { screen: Some((750, 1334)), ..Default::default() };
        f.timestamp = Some(9000);
        f.push(&hex(SE_CONFIG));
        f.push(&[0, 0, 0, 1, 0x26, 0x01, 0xaf]); // IDR_W_RADL (19): a keyframe
        assert!(!f.finish(&tx));
        let size = rx.try_recv().unwrap();
        assert_eq!(&size[..4], &[0x80, 0, 0, 0]);
        assert_eq!((u32::from_be_bytes(size[4..8].try_into().unwrap()), u32::from_be_bytes(size[8..12].try_into().unwrap())), (750, 1334));
        let config = rx.try_recv().unwrap();
        assert_eq!(u64::from_be_bytes(config[..8].try_into().unwrap()), CONFIG);
        assert_eq!(&config[12..], &hex(SE_CONFIG)[..]);
        let key = rx.try_recv().unwrap();
        assert_eq!(u64::from_be_bytes(key[..8].try_into().unwrap()), KEY);
        assert_eq!(&key[12..], &[0, 0, 0, 1, 0x26, 0x01, 0xaf]);
        // a delta frame before any config is lost: a keyframe is wanted
        let mut g = Frames::default();
        g.push(&[0, 0, 0, 1, 0x02, 0x01, 0xd0]);
        assert!(g.finish(&tx));
    }
}