Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
fix(viewer): the phone's picture no longer stalls over Wi-Fi (#100)
Qinghe Li1aa4df9ebd0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b977b9..8ed521c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,10 @@ All notable changes to this project are documented here. The format is based on## [Unreleased]+### Fixed++- The phone's own picture (HEVC) on the control page no longer stops for half a second to a second now and then over Wi-Fi. A report from the page that came a few hundred milliseconds late made the picture skip to the next keyframe; frames now wait up to 400 ms for such a page, the allowance follows how much the link's round trip varies, and the page has two reports on the way at most instead of one. Under emulated Wi-Fi delays the longest stop went from 1.1 s to 0.1 s.+## [0.2.5] - 2026-11-14### Upgrade notesdiff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 24853a9..111d8c5 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,6 +6,10 @@## [Unreleased]+### 修复++- 控制台上手机自己的画面(HEVC)在 Wi-Fi 下不再时不时卡住半秒到一秒。页面的一次回报晚到几百毫秒,画面就会丢到下一个关键帧;现在这种情况下帧会先等最多 400 毫秒,允许的延迟也跟着链路往返的波动走,页面同时最多有两个回报在路上(原来一个)。模拟 Wi-Fi 延迟时,最长卡顿从 1.1 秒降到 0.1 秒。+## [0.2.5] - 2026-11-14### 升级注意事项diff --git a/apps/iphone-control/src/video/device.rs b/apps/iphone-control/src/video/device.rsindex 4f23b7e..3ceee14 100644--- a/apps/iphone-control/src/video/device.rs+++ b/apps/iphone-control/src/video/device.rs@@ -7,8 +7,10 @@//! keyframes, which is how WebCodecs takes HEVC without one;//! - the picture is the phone's portrait framebuffer padded to multiples of 16 (1320×2868 arrives as 1328×2896): the//! page cuts the padding off and turns it by the `rotation` the daemon sends ([`ScreenMsg::Info`], type 3);-//! - falling behind can't be met by encoding fewer frames: frames other than keyframes are dropped until a keyframe,-//! which is asked for (one is 15–50 KB and arrives about 20 ms later).+//! - falling behind can't be met by encoding fewer frames. Frames first wait while the page is behind ([`Hold`]: up to+//! [`HOLD`]; over Wi-Fi a report is now and then a few hundred ms late though the link keeps up) and go together+//! once it caught up; past that they are dropped until a keyframe, which is asked for (one is 15–50 KB and arrives+//! about 20 ms later, but asking is limited to every [`ASK_EVERY`], so the picture stopped for 0.5 to 1 s).//!//! Browsers that can't decode HEVC (most without hardware decoding: Firefox, Chrome on most Linux) get the H.264//! picture or MJPEG instead; the page decides (`isConfigSupported`).@@ -24,6 +26,10 @@ use super::{AbortOnDrop, Acks, Flow, QUEUE, STREAM_IDLE, message, send_video};/// Asking for keyframes at most this often while dropping framesconst ASK_EVERY: Duration = Duration::from_millis(500);+/// How long frames wait for a page that is behind before they are dropped until a keyframe+const HOLD: Duration = Duration::from_millis(400);+/// … and how much of them+const HOLD_BYTES: usize = 1024 * 1024;/// Largest message accepted from the daemon (a keyframe is well under 1 MB)const MAX_MESSAGE: usize = 16 * 1024 * 1024;@@ -75,7 +81,9 @@ pub async fn serve(// dropping frames until a keyframe (the page fell behind, or its queue was full)let mut need_key = false;let mut asked: Option<Instant> = None;+ let mut held = Hold::default();loop {+ let wait_until = held.deadline().map(tokio::time::Instant::from_std);tokio::select! {_ = out_tx.closed() => return,m = msgs.recv() => {@@ -103,8 +111,8 @@ pub async fn serve(}Some(k @ (ScreenMsg::Key | ScreenMsg::Delta)) => {let key = k == ScreenMsg::Key;- if !key && (need_key || flow.behind(now)) {- need_key = true;+ // frames were dropped: only a keyframe continues the picture+ if need_key && !key {if asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {asked = Some(now);if daemon_w.write_all(&[SCREEN_KEYFRAME]).await.is_err() {@@ -113,22 +121,30 @@ pub async fn serve(}continue;}- // a keyframe while the page is still behind waits for the next one- if key && flow.behind(now) {- need_key = true;+ let m = message(if key { 1 } else { 2 }, &body);+ // the page is behind (or frames already wait): this one waits too, a while+ if flow.behind(now) || !held.is_empty() {+ held.push(m, key, now);+ if held.expired(now) {+ held.clear();+ need_key = true;+ if asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {+ asked = Some(now);+ if daemon_w.write_all(&[SCREEN_KEYFRAME]).await.is_err() {+ return;+ }+ }+ }continue;}- let m = message(if key { 1 } else { 2 }, &body);- let len = m.len();- match out_tx.try_send(m) {- Ok(()) => {- flow.sent(len, now);+ match send(&out_tx, &mut flow, m, now) {+ Sent::Yes => {if key {need_key = false;}}- Err(mpsc::error::TrySendError::Full(_)) => need_key = true,- Err(mpsc::error::TrySendError::Closed(_)) => return,+ Sent::Full => need_key = true,+ Sent::Closed => return,}}None => {}@@ -140,6 +156,23 @@ pub async fn serve(}let bytes = *acked.borrow_and_update();flow.ack(bytes, Instant::now());+ // caught up while frames waited: they go now, in order+ if !held.is_empty() && !flow.behind(Instant::now()) {+ for (m, key) in held.take() {+ match send(&out_tx, &mut flow, m, Instant::now()) {+ Sent::Yes => {+ if key {+ need_key = false;+ }+ }+ Sent::Full => {+ need_key = true;+ break;+ }+ Sent::Closed => return,+ }+ }+ }// caught up after dropping frames: a keyframe now rather than at the next requestif need_key && !flow.behind(Instant::now()) && asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {asked = Some(Instant::now());@@ -148,6 +181,105 @@ pub async fn serve(}}}+ // frames waited as long as they may and the page is still behind: drop them, a keyframe instead+ () = async { tokio::time::sleep_until(wait_until.unwrap_or_else(tokio::time::Instant::now)).await }, if wait_until.is_some() => {+ held.clear();+ need_key = true;+ if asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {+ asked = Some(Instant::now());+ if daemon_w.write_all(&[SCREEN_KEYFRAME]).await.is_err() {+ return;+ }+ }+ }+ }+ }+}++enum Sent {+ Yes,+ Full,+ Closed,+}++fn send(out: &mpsc::Sender<Vec<u8>>, flow: &mut Flow, m: Vec<u8>, now: Instant) -> Sent {+ let len = m.len();+ match out.try_send(m) {+ Ok(()) => {+ flow.sent(len, now);+ Sent::Yes}+ Err(mpsc::error::TrySendError::Full(_)) => Sent::Full,+ Err(mpsc::error::TrySendError::Closed(_)) => Sent::Closed,+ }+}++/// Frames waiting for a page that is a little behind ([`HOLD`]): a keyframe makes those before it needless+#[derive(Default)]+struct Hold {+ frames: Vec<(Vec<u8>, bool)>,+ bytes: usize,+ since: Option<Instant>,+}++impl Hold {+ fn is_empty(&self) -> bool {+ self.frames.is_empty()+ }++ fn push(&mut self, m: Vec<u8>, key: bool, now: Instant) {+ if key {+ self.clear();+ }+ self.since.get_or_insert(now);+ self.bytes += m.len();+ self.frames.push((m, key));+ }++ fn clear(&mut self) {+ self.frames.clear();+ self.bytes = 0;+ self.since = None;+ }++ /// Waited too long, or too much waits+ fn expired(&self, now: Instant) -> bool {+ self.since.is_some_and(|t| now.saturating_duration_since(t) >= HOLD) || self.bytes > HOLD_BYTES+ }++ /// When the waiting frames are given up+ fn deadline(&self) -> Option<Instant> {+ self.since.map(|t| t + HOLD)+ }++ fn take(&mut self) -> Vec<(Vec<u8>, bool)> {+ let f = std::mem::take(&mut self.frames);+ self.clear();+ f+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Frames wait up to [`HOLD`] (or [`HOLD_BYTES`]); a keyframe replaces whatever waited before it+ #[test]+ fn frames_wait_a_while_for_a_late_page() {+ let t0 = Instant::now();+ let mut h = Hold::default();+ assert!(h.deadline().is_none());+ h.push(vec![2; 100], false, t0);+ h.push(vec![2; 100], false, t0 + Duration::from_millis(40));+ assert!(!h.expired(t0 + Duration::from_millis(390)));+ assert!(h.expired(t0 + HOLD));+ assert_eq!(h.deadline(), Some(t0 + HOLD));+ h.push(vec![1; 50], true, t0 + Duration::from_millis(100));+ assert_eq!(h.frames.len(), 1, "the keyframe alone");+ assert_eq!(h.deadline(), Some(t0 + Duration::from_millis(100) + HOLD), "and it waits from now");+ assert_eq!(h.take().len(), 1);+ assert!(h.is_empty() && h.bytes == 0);+ h.push(vec![2; HOLD_BYTES + 1], false, t0);+ assert!(h.expired(t0), "too much waiting");}}diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rsindex cd93170..d6e6f2f 100644--- a/apps/iphone-control/src/video/mod.rs+++ b/apps/iphone-control/src/video/mod.rs@@ -16,8 +16,8 @@//! frames far faster than a slow link delivers them, so how full the queue here is says nothing; with a 30 KB/s//! reader the picture was 40 s late. The page therefore reports how many bytes it has read (`POST /api/video/ack`,//! every 100 ms while frames arrive, [`Acks`]). While the page is behind ([`Flow::behind`]: the oldest frame it-//! hasn't confirmed is older than the usual round trip plus [`SLACK`], or more is on the way than the link delivers-//! in that time), no new picture goes to the encoder; once the page has caught up, only the newest one does. Every encoded frame is still sent, so the chain of frames stays whole and no keyframe is needed (one would+//! hasn't confirmed is older than the usual round trip plus [`SLACK`] and the link's usual variation, or more is on+//! the way than the link delivers in that time), no new picture goes to the encoder; once the page has caught up, only the newest one does. Every encoded frame is still sent, so the chain of frames stays whole and no keyframe is needed (one would//! take seconds on such a link): the frame rate drops to what the link carries and the picture stays about that//! close to live. A page that never reports (an older one) only gets the queue check below.//!@@ -60,6 +60,11 @@ const RESTART_EVERY: Duration = Duration::from_secs(1);const TRIES: usize = 3;/// How much later than usual the page may confirm a frame before frames are skippedconst SLACK: Duration = Duration::from_millis(300);+/// On top of [`SLACK`], how much the round trip is seen to vary (its 90th percentile over [`BASE_WINDOW`] less its+/// shortest), at most this much. Over Wi-Fi each report is a new connection and TLS handshake, about three round+/// trips, and a round trip that is 2 ms at best was 30 to 80 ms at times: reports 400 ms late now and then, which+/// made the picture skip to the next keyframe again and again although the link kept up+const MAX_JITTER: Duration = Duration::from_millis(700);/// The usual round trip is the shortest seen over this longconst BASE_WINDOW: Duration = Duration::from_secs(10);/// The link's speed is the fastest delivery seen over this long@@ -156,6 +161,16 @@ impl Flow {}}+ /// How late a confirmation may be: the usual round trip (the shortest seen) plus [`SLACK`], plus how much the+ /// round trip varies on this link (up to [`MAX_JITTER`])+ fn allowance(&self) -> Duration {+ let mut d: Vec<Duration> = self.trips.iter().map(|(_, d)| *d).collect();+ d.sort();+ let Some(&min) = d.first() else { return SLACK };+ let p90 = d[(d.len() * 9 / 10).min(d.len() - 1)];+ min + SLACK + p90.saturating_sub(min).min(MAX_JITTER)+ }+/// The page is behind: its oldest unconfirmed message is older than a usual round trip plus [`SLACK`], or more/// is on the way than the link delivers in that time (without this, the pictures arriving in the first [`SLACK`]/// after catching up would all go out at once). The rate is what was delivered, which on a fast link is only@@ -166,7 +181,7 @@ impl Flow {if !self.reports || self.heard.is_some_and(|t| now.saturating_duration_since(t) > REPORTS_STALE) {return false;}- let allowed = self.trips.iter().map(|(_, d)| *d).min().unwrap_or_default() + SLACK;+ let allowed = self.allowance();if now.saturating_duration_since(*oldest) > allowed {return true;}@@ -539,12 +554,40 @@ mod tests {assert!(f.behind(ms(1360)));f.ack(400, ms(1400));assert!(!f.behind(ms(1400)));- // reports stop coming (one got lost): no waiting for them forever+ // reports stop coming (one got lost): no waiting for them forever. That one took 400 ms, so this link's round+ // trip varies by 350 ms, on top of the 50 + 300f.sent(100, ms(1500));- assert!(f.behind(ms(2000)));+ assert!(!f.behind(ms(2150)));+ assert!(f.behind(ms(2250)));assert!(!f.behind(ms(4500)), "nothing heard for over 3 s");}+ /// Over Wi-Fi the reports come 100 ms after the frames as a rule and now and then 450 ms: such a late one isn't+ /// falling behind. One that stops coming still is, a little later (at most [`MAX_JITTER`] later)+ #[test]+ fn a_link_that_varies_gets_its_variation_on_top() {+ let t0 = Instant::now();+ let ms = |n| t0 + Duration::from_millis(n);+ let mut f = Flow::default();+ // 50 frames, each confirmed 100 ms later, every 10th 450 ms later+ let mut t = 0;+ for i in 0..50u64 {+ f.sent(1000, ms(t));+ f.ack((i + 1) * 1000, ms(t + if i % 10 == 9 { 450 } else { 100 }));+ t += 500;+ }+ f.sent(1000, ms(t));+ assert!(!f.behind(ms(t + 450)), "as late as this link's slow reports");+ assert!(f.behind(ms(t + 800)), "later than that: behind");+ // a link that varied wildly: the allowance stops growing+ let mut g = Flow::default();+ for i in 0..20u64 {+ g.sent(1000, ms(i * 3000));+ g.ack((i + 1) * 1000, ms(i * 3000 + if i % 2 == 0 { 50 } else { 2500 }));+ }+ assert_eq!(g.allowance(), Duration::from_millis(50) + SLACK + MAX_JITTER);+ }+/// On a link that delivers 20 KB/s, a second 20 KB frame waits for the first: 300 ms of that link is 6 KB. On a/// link with a 200 ms round trip that keeps up, frames keep flowing#[test]diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex aa89399..155c6f4 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -1425,7 +1425,7 @@ const statusEl = $('#status'), promptEl = $('#prompt'), promptErr = $('#prompt-econst turnsEl = $('#turns'), stopDialog = $('#stop-dialog'), deviceEl = $('#device-value');/* 实时画面:H.264 画在 canvas 上(见「H.264 画面」),否则是 MJPEG 的 img */const cv = $('#live-v'), cvx = cv.getContext('2d');-const V = { on: false, off: false, noDevice: false, device: false, crop: false, rot: null, frameRotation: null, codecName: '', ctrl: null, dec: null, got: false, label: '', ts: 0, bytes: 0, rate: null, stream: '', recv: 0, acked: 0, acking: false };+const V = { on: false, off: false, noDevice: false, device: false, crop: false, rot: null, frameRotation: null, codecName: '', ctrl: null, dec: null, got: false, label: '', ts: 0, bytes: 0, rate: null, stream: '', recv: 0, acked: 0, acking: 0, reported: 0 };/* MJPEG 画面横屏时也画在 canvas 上转正(见 mjpegTurn) */const M = { on: false, raf: 0 };const onCanvas = () => V.on || M.on;@@ -2322,7 +2322,7 @@ function connect() {* 这一页从没出过画面就失败(没有编码器、浏览器解不了)就改用 MJPEG,之后不再试 ---------- */function stopVideo() {if (V.ctrl) V.ctrl.abort();- V.ctrl = null; V.on = false; V.got = false; V.rate = null; V.stream = ''; V.recv = 0; V.acked = 0; V.acking = false;+ V.ctrl = null; V.on = false; V.got = false; V.rate = null; V.stream = ''; V.recv = 0; V.acked = 0; V.acking = 0; V.reported = 0;V.device = false; V.crop = false; V.rot = null; V.frameRotation = null; V.bytes = 0; V.codecName = '';if (V.dec && V.dec.state !== 'closed') { try { V.dec.close(); } catch { /* 已经关了 */ } }V.dec = null;@@ -2402,15 +2402,16 @@ async function startVideo(q, dev) {/* 每秒算一次 H.264 画面的流量,显示在画面下方 */setInterval(() => { if (V.on) { V.rate = V.bytes; V.bytes = 0; renderFeed(); } }, 1000);/* 告诉服务端读到了多少:链路慢、隧道里堆了数据时,它据此少编几帧,画面不会越来越滞后。- * 服务端收到才算报过,丢了的下一轮再报(不然它会一直等这次回报) */+ * 服务端收到才算报过,丢了的下一轮再报(不然它会一直等这次回报)。最多两个回报同时在路上:+ * Wi-Fi 上一次回报偶尔要几百毫秒,下一个不必等它,先到的就先算 */setInterval(() => {- if (!V.on || !V.stream || V.recv === V.acked || V.acking) return;+ if (!V.on || !V.stream || V.recv === V.acked || V.acking >= 2 || V.recv === V.reported) return;const stream = V.stream, bytes = V.recv;- V.acking = true;+ V.acking = (V.acking || 0) + 1; V.reported = bytes;fetch('/api/video/ack', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ stream, bytes }) })- .then(r => { if (r.ok && V.stream === stream) V.acked = Math.max(V.acked, bytes); })- .catch(() => {})- .finally(() => { if (V.stream === stream) V.acking = false; });+ .then(r => { if (r.ok && V.stream === stream) V.acked = Math.max(V.acked, bytes); else if (V.stream === stream) V.reported = V.acked; })+ .catch(() => { if (V.stream === stream) V.reported = V.acked; })+ .finally(() => { if (V.stream === stream) V.acking = Math.max(0, V.acking - 1); });}, 100);function renderFeed() {const dot = $('#feed-dot'), txt = $('#feed-text');