Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

feat(viewer): a low-bandwidth mode for the picture (#104)

Qinghe Li8c98e6a48b4c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad5fbc2..6b8b74a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,12 +6,17 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
+### Added
+
+- Low-bandwidth mode for the control page's picture: a switch in Settings, for use over the internet or a weak signal. The phone's own video (HEVC) is asked for with a 2 Mbit/s cap instead of 6, about half the traffic at the same frame rate (on an iPhone's home screen 214 KB/s instead of 459–483 while swiping); a still screen looks the same, moving content gets a little blocky. There is one such stream per phone, so while any page watching it has the mode on, all of them get it, and the stream starts again (the picture stops for about half a second) when the first such page comes and when the last one goes. The H.264 picture changes only for that page (qp 26: 689 KB/s instead of 1350).
+
### Changed
- The control page's requests share a connection instead of opening one each (`Connection: keep-alive`). Over Wi-Fi a new connection and its TLS handshake cost two more round trips, for every tap, every check and each of the ten reports a second on the picture. With a 40 ms round trip a request from the page went from about 220 ms to 47 ms, and about 40 s on the page opened 19 connections instead of 763. A connection is kept only for a logged-in request, closes after 15 s of nothing, and isn't kept when fewer than 8 of the 32 places are free; streams (the picture, task events, `/mcp`) still have their own.
### Fixed
+- A control page watching the phone's own video got no more frames, and wasn't closed, when the phone's media stream was stopped and started again (the daemon's side of each page held the stream's channel open); it now hears that the stream ended and reconnects.
- Home on the control page is pressed at once: about 0.5 s instead of 1 s on an iPhone's home screen. The daemon first looked for a system alert that would stop Home working (0.8 s on the home screen), which the person at the page sees anyway; the page's requests now say someone is watching (`watched`), and for them the daemon looks only when the press didn't get to the home screen. Agents (MCP, CLI) are checked first as before.
- Taps and Home presses on the control page no longer wait behind its background checks. While it shows the phone's own picture the page asks every few seconds whether a system alert is up, which on the home screen keeps WDA busy for about 0.8 s, and its status check takes the phone too: an action that came meanwhile waited for them. These checks now give way: they don't start within 4 s (the status: 1 s) of an action, nor while one waits, and one that runs is dropped when an action comes. With the page checking, a finger's press went from 775 ms to 25 ms at the 90th percentile, a Home press from 1.8 s to 1.3 s.
- 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.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 6cf1e81..097bc95 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -6,12 +6,17 @@
## [Unreleased]
+### 新增
+
+- 控制台画面的弱网模式:「设置」里的开关,适合外网或信号差时用。手机自己的视频(HEVC)按 2 Mbit/s 的码率上限向手机要(原来 6),流量约减一半,帧率不变(iPhone 主屏幕上滑动时 214 KB/s,原来 459–483);画面静止时看不出区别,动起来时会有些糊块。每台手机只有一路这样的流,所以只要有一个在看它的页面开着,所有页面都一起降;第一个这样的页面来、最后一个走时流会重新开始(画面断开半秒左右)。H.264 只影响开它的页面(qp 26:689 KB/s,原来 1350)。
+
### 变更
- 控制台页面的请求共用连接(`Connection: keep-alive`),不再每个请求都新开一条。Wi-Fi 下新连接加 TLS 握手要多两个往返,每次点按、每次查询、画面每秒十次回报都要付出这个代价。往返 40 毫秒时,页面的一个请求从约 220 毫秒降到 47 毫秒,页面开约 40 秒建的连接从 763 条降到 19 条。只有登录过的请求才保持连接,空闲 15 秒关闭,32 个名额剩不到 8 个时也不保持;画面、任务事件、`/mcp` 这些流仍各用自己的连接。
### 修复
+- 手机的屏幕媒体流停下又重新开始时,正在看手机自己视频的控制台页面再也收不到画面,也不会断开(守护进程那边每个页面都握着流的通道,它关不掉);现在页面会知道流结束了并重新连接。
- 控制台上按 Home 立即按下:iPhone 主屏幕上从约 1 秒降到约 0.5 秒。守护进程原来先查一遍有没有挡住 Home 的系统弹窗(主屏幕上要 0.8 秒),而页面前的人本来就看得见;现在页面的请求会注明有人在看(`watched`),守护进程只在按下后没回到主屏幕时才去查。Agent(MCP、命令行)仍和原来一样先查。
- 控制台上的点按和按 Home 不再排在页面的后台查询后面。显示手机自己的画面时,页面每隔几秒查一次有没有系统弹窗,在主屏幕上这一下要占用 WDA 约 0.8 秒,状态查询也要占用手机,期间来的操作只能等着。现在这些查询会让路:操作后 4 秒内(状态查询 1 秒内)不查,有操作在排队时不开始,查到一半来了操作就放弃。页面在查询时,手指按下的 P90 从 775 毫秒降到 25 毫秒,按 Home 从 1.8 秒降到 1.3 秒。
- 控制台上手机自己的画面(HEVC)在 Wi-Fi 下不再时不时卡住半秒到一秒。页面的一次回报晚到几百毫秒,画面就会丢到下一个关键帧;现在这种情况下帧会先等最多 400 毫秒,允许的延迟也跟着链路往返的波动走,页面同时最多有两个回报在路上(原来一个)。模拟 Wi-Fi 延迟时,最长卡顿从 1.1 秒降到 0.1 秒。
diff --git a/apps/iphone-control/src/debug.rs b/apps/iphone-control/src/debug.rs
index a8544f1..e05173e 100644
--- a/apps/iphone-control/src/debug.rs
+++ b/apps/iphone-control/src/debug.rs
@@ -166,7 +166,7 @@ async fn e2e_with_wda(
// HID 路线:同样的点击和 Home,以 WDA 的前台 App 判断是否生效
let screen = wda.screen_size().await?;
let t = Instant::now();
- let hid = tunnel.hid(screen).await?;
+ let hid = tunnel.hid(screen, ictl_device::FULL_BITRATE).await?;
check(ictl_l10n::tr!("打开 HID 会话", "open HID session"), t, true, String::new())?;
let r = async {
let t = Instant::now();
@@ -225,7 +225,7 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
Check::Hid { x, y } => {
let mut t = device.open_tunnel().await?;
let r = async {
- let hid = t.hid(screen).await?;
+ let hid = t.hid(screen, ictl_device::FULL_BITRATE).await?;
hid.tap(x, y).await?;
println!(
"{}",
diff --git a/apps/iphone-control/src/video/device.rs b/apps/iphone-control/src/video/device.rs
index 3ceee14..ebb798a 100644
--- a/apps/iphone-control/src/video/device.rs
+++ b/apps/iphone-control/src/video/device.rs
@@ -38,8 +38,9 @@ const MAX_MESSAGE: usize = 16 * 1024 * 1024;
pub async fn open(
socket: &std::path::Path,
udid: &str,
+ low_bandwidth: bool,
) -> Result<(tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>, tokio::net::unix::OwnedWriteHalf), String> {
- match ictl_daemon::protocol::open_screen_stream(socket, Some(udid)).await {
+ match ictl_daemon::protocol::open_screen_stream(socket, Some(udid), low_bandwidth).await {
Ok(r) => r,
Err(e) => Err(e.to_string()),
}
diff --git a/apps/iphone-control/src/video/ffmpeg.rs b/apps/iphone-control/src/video/ffmpeg.rs
index 899d896..553ed6f 100644
--- a/apps/iphone-control/src/video/ffmpeg.rs
+++ b/apps/iphone-control/src/video/ffmpeg.rs
@@ -35,6 +35,9 @@ use super::mjpeg;
/// Default quantizer: about x264's crf 19, which looks the same as the source in normal use (see the docs)
pub const DEFAULT_QP: u8 = 20;
+/// A page in low-bandwidth mode: about half the bit rate of [`DEFAULT_QP`] (it doubles every 6 steps down); a higher
+/// `IPHONE_CONTROL_VIEWER_QP` stays
+pub const LOW_BANDWIDTH_QP: u8 = 26;
/// A keyframe every this many frames. Frames only flow while the screen changes, and a page that falls behind gets a
/// keyframe by restarting the encoder, so keyframes are rarely needed and cost about as much as 40 other frames
pub const GOP_FRAMES: u32 = 600;
@@ -431,24 +434,30 @@ impl Encoders {
}
/// Starts an encoder session for frames of `w`×`h`
- pub fn start(&self, w: u32, h: u32) -> Result<Session, String> {
+ /// A session at quantizer `qp` ([`Self::qp`], or more for a page in low-bandwidth mode)
+ pub fn start(&self, w: u32, h: u32, qp: u8) -> Result<Session, String> {
let c = self.current().ok_or_else(|| ictl_l10n::tr!("没有可用的编码器", "no working encoder").to_owned())?;
- self.session(&self.list[c.index], w, h, c.kicks, c.index, None)
+ self.session(&self.list[c.index], (w, h), qp, c.kicks, c.index, None)
}
- /// A session of `kind`; `info`: told how the native encoder was set up
+ /// The quantizer set for the picture (`IPHONE_CONTROL_VIEWER_QP`)
+ pub fn qp(&self) -> u8 {
+ self.qp
+ }
+
+ /// A session of `kind` for frames of `(w, h)`; `info`: told how the native encoder was set up
fn session(
&self,
kind: &Kind,
- w: u32,
- h: u32,
+ (w, h): (u32, u32),
+ qp: u8,
kicks: usize,
index: usize,
info: Option<tokio::sync::oneshot::Sender<NativeInfo>>,
) -> Result<Session, String> {
let inner = match kind {
#[cfg(target_os = "macos")]
- Kind::Native => Inner::Native(super::vt::Session::start(w, h, self.qp, kicks, info)),
+ Kind::Native => Inner::Native(super::vt::Session::start(w, h, qp, kicks, info)),
#[cfg(not(target_os = "macos"))]
Kind::Native => {
let _ = info;
@@ -456,7 +465,7 @@ impl Encoders {
}
k => {
let ffmpeg = self.ffmpeg.as_deref().ok_or_else(|| "no ffmpeg".to_owned())?;
- Inner::Process(Box::new(Process::spawn(ffmpeg, &args(k, w, h, self.qp, self.old), kicks)?))
+ Inner::Process(Box::new(Process::spawn(ffmpeg, &args(k, w, h, qp, self.old), kicks)?))
}
};
Ok(Session { size: (w, h), index, inner })
@@ -513,7 +522,7 @@ impl Encoders {
async fn calibrate(&self, kind: &Kind) -> Result<(usize, bool), String> {
let (w, h) = SAMPLE;
let (info_tx, info) = tokio::sync::oneshot::channel();
- let mut s = self.session(kind, w, h, 0, 0, Some(info_tx))?;
+ let mut s = self.session(kind, (w, h), self.qp, 0, 0, Some(info_tx))?;
let deadline = Instant::now() + CALIBRATE_FOR;
let mut out = 0;
while out == 0 {
@@ -876,7 +885,7 @@ mod tests {
return;
}
};
- let mut s = e.start(SAMPLE.0, SAMPLE.1).unwrap();
+ let mut s = e.start(SAMPLE.0, SAMPLE.1, e.qp()).unwrap();
s.push(e.sample.clone());
let mut config = None;
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs
index d6e6f2f..11d1462 100644
--- a/apps/iphone-control/src/video/mod.rs
+++ b/apps/iphone-control/src/video/mod.rs
@@ -40,7 +40,7 @@ use serde_json::json;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::{mpsc, watch};
-pub use ffmpeg::Encoders;
+pub use ffmpeg::{Encoders, LOW_BANDWIDTH_QP};
use flv::Packet;
/// `IPHONE_CONTROL_VIEWER_CODEC` allows the phone's own screen video ([`device`]): `auto` (the default) or `device`
@@ -217,6 +217,7 @@ fn config_message(avcc: &[u8], size: (u32, u32), encoder: &str, stream: &str) ->
/// Sends the picture of `src` (WDA's MJPEG response) to `client` until either ends. The HTTP head is already sent
pub async fn serve(
enc: Arc<Encoders>,
+ qp: u8,
acks: Arc<Acks>,
src: impl AsyncRead + Unpin + Send + 'static,
client: impl AsyncRead + AsyncWrite + Unpin + Send + 'static,
@@ -287,7 +288,7 @@ pub async fn serve(
let Some(size) = mjpeg::jpeg_size(&j) else { continue };
// a new size (the screen turned): a new session, whose first frame is a keyframe of that size
if session.as_ref().is_none_or(|s| s.size != size) {
- let Some(s) = start(&enc, size) else { return };
+ let Some(s) = start(&enc, size, qp) else { return };
session = Some(s);
produced = false;
}
@@ -339,7 +340,7 @@ pub async fn serve(
}
let Some(j) = &last else { continue };
let Some(size) = mjpeg::jpeg_size(j) else { continue };
- let Some(s) = start(&enc, size) else { return };
+ let Some(s) = start(&enc, size, qp) else { return };
s.push(j.clone());
session = Some(s);
produced = false;
@@ -360,7 +361,7 @@ pub async fn serve(
if need_key && out_tx.capacity() == QUEUE && restarted.elapsed() >= RESTART_EVERY {
let (Some(j), Some(old)) = (&last, &session) else { continue };
let size = old.size;
- let Some(s) = start(&enc, size) else { return };
+ let Some(s) = start(&enc, size, qp) else { return };
s.push(j.clone());
session = Some(s);
produced = false;
@@ -378,8 +379,8 @@ enum Ev {
Tick,
}
-fn start(enc: &Encoders, size: (u32, u32)) -> Option<ffmpeg::Session> {
- enc.start(size.0, size.1).map_err(|e| tracing::debug!("{e}")).ok()
+fn start(enc: &Encoders, size: (u32, u32), qp: u8) -> Option<ffmpeg::Session> {
+ enc.start(size.0, size.1, qp).map_err(|e| tracing::debug!("{e}")).ok()
}
/// The MJPEG picture (`GET /stream`, when there is no H.264): the phone's frames with repeated ones dropped (WDA
@@ -670,7 +671,7 @@ mod tests {
let mut page = tokio::net::TcpStream::connect(l.local_addr().unwrap()).await.unwrap();
let (server_side, _) = l.accept().await.unwrap();
let acks = Arc::new(Acks::default());
- let _server = AbortOnDrop(tokio::spawn(serve(enc, acks.clone(), src, server_side)));
+ let _server = AbortOnDrop(tokio::spawn(serve(enc.clone(), enc.qp(), acks.clone(), src, server_side)));
const RATE: f64 = 20.0 * 1024.0;
let (mut buf, mut total, mut frames_in) = (Vec::new(), 0u64, 0);
let (mut stream, mut last_frame, mut reported) = (None::<String>, None::<Instant>, Instant::now());
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 3c9b3c4..77265ab 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -728,6 +728,8 @@ button.nav-device:disabled { cursor: default; }
.appearance-options { display: grid; }
.appearance-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-block: 4px; font-size: var(--fs-xs); }
.appearance-row + .appearance-row { border-top: 1px solid var(--line); }
+.appearance-low .switch-row { font-size: inherit; color: inherit; }
+.appearance-hint { margin: 0 0 4px; font-size: var(--fs-xs); color: var(--text-2); max-width: 36em; }
.appearance-picker { min-width: 0; max-width: 65%; }
.pane-agent .pane-head { gap: 6px; padding-inline: 12px; }
.agent-brand { flex: 1; }
@@ -1086,6 +1088,8 @@ button.nav-device:disabled { cursor: default; }
<div class="appearance-row"><label for="language" id="language-label">界面语言</label><div class="appearance-picker"><select id="language-value" data-picker="language" hidden><option value="zh" lang="zh-CN">简体中文</option><option value="en" lang="en">English</option></select></div></div>
<div class="appearance-row"><label for="theme" id="theme-label">明暗</label><div class="appearance-picker"><select id="theme-value" data-picker="theme" hidden><option value="system">跟随系统</option><option value="light">浅色</option><option value="dark">深色</option></select></div></div>
<div class="appearance-row"><label for="text-size" id="text-size-label">界面字号</label><div class="appearance-picker"><select id="text-size-value" data-picker="text-size" hidden><option value="standard">标准</option><option value="large">大</option><option value="xlarge">特大</option></select></div></div>
+ <div class="appearance-row appearance-low"><label class="switch-row" for="low-bandwidth"><input type="checkbox" id="low-bandwidth" role="switch" aria-describedby="low-bandwidth-hint"><span>弱网模式</span></label></div>
+ <p class="appearance-hint" id="low-bandwidth-hint">画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。</p>
</div>
<form method="dialog" class="dialog-actions"><button class="btn btn-primary" type="submit">完成</button></form>
</dialog>
@@ -1120,7 +1124,7 @@ const LANG = (() => {
return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh';
})();
document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';
-const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};
+const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"};
Object.assign(EN, {
'未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device',
'外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large',
@@ -2359,7 +2363,7 @@ async function startVideo(q, dev) {
refreshFrame(reoriented);
};
try {
- const r = await fetch(`/video?${q}${dev ? '&src=device' : ''}`, { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } });
+ const r = await fetch(`/video?${q}${dev ? '&src=device' : ''}${lowBandwidthOn() ? '&low=1' : ''}`, { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } });
if (loggedOut(r)) return;
if (!r.ok || !r.body) return ended(r.status === 404);
const rd = r.body.getReader();
@@ -2423,7 +2427,8 @@ function renderFeed() {
if (!dims()) { dot.classList.add('wait'); txt.textContent = tr('画面已连接 · 等待屏幕尺寸和方向,仅可观看'); return; }
const route = S.dstatus?.route === 'hid' ? tr('HID 后备') : 'WDA';
const codec = V.on ? ` · ${V.codecName || 'H.264'}${V.label ? ` ${V.label}` : ''}${V.rate != null ? ` ${Math.round(V.rate / 1024)} KB/s` : ''}` : ' · MJPEG';
- txt.textContent = `${tr('实时画面')} · ${route}${codec}${S.rtt != null ? ` · ${tr('操作往返')} ${S.rtt} ms` : ''}`;
+ const low = V.on && lowBandwidthOn() ? ` · ${tr('弱网模式')}` : '';
+ txt.textContent = `${tr('实时画面')} · ${route}${codec}${low}${S.rtt != null ? ` · ${tr('操作往返')} ${S.rtt} ms` : ''}`;
}
/* ================================================================
@@ -3488,6 +3493,17 @@ $('#appearance').addEventListener('change', () => {
try { localStorage.setItem(appearanceKey, JSON.stringify({textSize:textSize.value, theme:theme.value})); } catch {}
});
$('#appearance-btn').addEventListener('click', () => $('#appearance').showModal());
+/* ---------- 弱网模式:画面码率约减半(手机自己的 HEVC:这台手机的所有页面一起;H.264:只这个页面),记在浏览器里 ---------- */
+const LOW_BANDWIDTH_KEY = 'ictl.lowBandwidth';
+function lowBandwidthOn() { try { return localStorage.getItem(LOW_BANDWIDTH_KEY) === '1'; } catch { return false; } }
+$('#low-bandwidth').checked = lowBandwidthOn();
+$('#low-bandwidth').addEventListener('change', ev => {
+ ev.stopPropagation();
+ try { localStorage.setItem(LOW_BANDWIDTH_KEY, ev.target.checked ? '1' : '0'); } catch { /* 预览环境可能禁用存储 */ }
+ if (S.mode === 'live') { connect(); show(tr(ev.target.checked ? '已开启弱网模式,正在重新连接画面…' : '已关闭弱网模式,正在重新连接画面…')); }
+ renderFeed();
+});
+window.addEventListener('storage', event => { if (event.key === LOW_BANDWIDTH_KEY) $('#low-bandwidth').checked = lowBandwidthOn(); });
/* ---------- 两侧栏宽度:拖拽、方向键调整,双击恢复默认,记在浏览器里 ---------- */
const MIN_STAGE = 420; // 中间设备画面至少保留的宽度
const isThreeCol = () => matchMedia('(min-width: 1280px)').matches;
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 5383429..e324b85 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -669,11 +669,14 @@ async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()>
if udid.is_empty() {
return reply(&mut client, 503, "text/plain", b"no device yet").await;
}
+ // the page's low-bandwidth mode (`?low=1`): the phone's own video at a lower bitrate (for every page on that
+ // phone, see `ictl_daemon::protocol::LOW_BANDWIDTH`), the H.264 picture at a higher quantizer (this page's only)
+ let low = req.query("low").as_deref() == Some("1");
if req.path == "/video" && req.query("src").as_deref() == Some("device") {
if !ctx.device_video_allowed {
return reply(&mut client, 404, "text/plain", b"turned off by IPHONE_CONTROL_VIEWER_CODEC").await;
}
- return match crate::video::device::open(&ctx.socket, &udid).await {
+ return match crate::video::device::open(&ctx.socket, &udid, low).await {
// the page takes 404 as "not this way" and falls back to H.264 or MJPEG
Err(e) => reply(&mut client, 404, "text/plain; charset=utf-8", e.as_bytes()).await,
Ok((src, w)) => {
@@ -701,7 +704,8 @@ async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()>
match video {
Some(enc) => {
video_head(&mut client).await?;
- crate::video::serve(enc, ctx.acks.clone(), remote, client).await;
+ let qp = if low { enc.qp().max(crate::video::LOW_BANDWIDTH_QP) } else { enc.qp() };
+ crate::video::serve(enc, qp, ctx.acks.clone(), remote, client).await;
}
None => crate::video::serve_mjpeg(remote, client, crate::video::STREAM_IDLE).await,
}
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 1f15020..71d79c0 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -238,6 +238,8 @@ pub struct CallCtx {
pub peer: Option<u32>,
/// A poll that gives way to actions ([`ictl_protocol::BACKGROUND`])
pub background: bool,
+ /// A screen stream for a page in low-bandwidth mode ([`ictl_protocol::LOW_BANDWIDTH`])
+ pub low_bandwidth: bool,
/// Someone watches the screen ([`ictl_protocol::WATCHED`])
pub watched: bool,
}
@@ -359,6 +361,9 @@ pub(crate) struct Inner {
/// Control pages watching the screen media stream (`screen.rs`): while there are any, the HID session (which owns
/// the stream) stays open however long it is idle
pub screen_viewers: usize,
+ /// Of those, the pages in low-bandwidth mode ([`ictl_protocol::LOW_BANDWIDTH`]): while there are any, the HID
+ /// session's video is capped at [`ictl_device::LOW_BANDWIDTH_BITRATE`]
+ pub low_bandwidth_viewers: usize,
/// 最近一次读到的元素树。只在调用方允许(max_age_ms)时复用;改变界面的操作做完就清掉
pub elements_cache: Option<(Instant, ictl_wda::elements::Tree)>,
/// 滑动等列表停下时最后读到的树([`crate::tools`] 的 `settle` 拿来当比较的起点)
@@ -483,6 +488,7 @@ impl Daemon {
offline_target: None,
hid_used: None,
screen_viewers: 0,
+ low_bandwidth_viewers: 0,
elements_cache: None,
swiped_tree: None,
dedup: Dedup::default(),
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index ac798de..d2fdc51 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -161,7 +161,7 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
// stops the daemon, which ends the stream; the viewer reconnects to the new one
(Ok((protocol::Request::ScreenStream, _, ctx, lang)), Ok(lease)) => {
drop(lease);
- ictl_l10n::scope(lang, daemon.screen_stream(reader, w, ctx.expect_udid)).await;
+ ictl_l10n::scope(lang, daemon.screen_stream(reader, w, ctx.expect_udid, ctx.low_bandwidth)).await;
return;
}
// also streams; an opened task's connection is its lease, so it isn't held against updates either
@@ -214,7 +214,7 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
/// No language (an older client) means Chinese, which is what those clients expect and parse
fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, core::CallCtx, ictl_l10n::Lang)> {
let mut v: serde_json::Value = serde_json::from_slice(line)?;
- let (cancel, udid, view, lang, task, task_step, background, watched) = match v.as_object_mut() {
+ let (cancel, udid, view, lang, task, task_step, background, watched, low_bandwidth) = match v.as_object_mut() {
Some(o) => (
o.remove(protocol::CANCEL_ON_CLOSE).is_some_and(|c| c == true),
o.remove(protocol::EXPECT_UDID).and_then(|u| u.as_str().map(str::to_owned)),
@@ -224,8 +224,9 @@ fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, co
o.remove(protocol::TASK_STEP).and_then(|s| s.as_u64()),
o.remove(protocol::BACKGROUND).is_some_and(|b| b == true),
o.remove(protocol::WATCHED).is_some_and(|b| b == true),
+ o.remove(protocol::LOW_BANDWIDTH).is_some_and(|b| b == true),
),
- None => (false, None, None, None, None, None, false, false),
+ None => (false, None, None, None, None, None, false, false, false),
};
Ok((
serde_json::from_value(v)?,
@@ -239,6 +240,7 @@ fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, co
peer: None,
background,
watched,
+ low_bandwidth,
},
lang.unwrap_or(ictl_l10n::Lang::Zh),
))
@@ -423,7 +425,10 @@ mod tests {
assert!(!ctx.watched && !ctx.background);
let (req, _, ctx, _) = parse_request(br#"{"op":"press_button","button":"home","watched":true}"#).unwrap();
assert_eq!(req, protocol::Request::PressButton { button: "home".into() });
- assert!(ctx.watched && !ctx.background);
+ assert!(ctx.watched && !ctx.background && !ctx.low_bandwidth);
+ let (req, _, ctx, _) = parse_request(br#"{"op":"screen_stream","low_bandwidth":true}"#).unwrap();
+ assert_eq!(req, protocol::Request::ScreenStream);
+ assert!(ctx.low_bandwidth);
assert_eq!(lang, Lang::Zh);
let (_, _, _, lang) = parse_request(br#"{"op":"status","lang":"klingon"}"#).unwrap();
assert_eq!(lang, Lang::Zh);
diff --git a/crates/ictl-daemon/src/screen.rs b/crates/ictl-daemon/src/screen.rs
index d14036c..9971ac6 100644
--- a/crates/ictl-daemon/src/screen.rs
+++ b/crates/ictl-daemon/src/screen.rs
@@ -7,19 +7,26 @@
//! second that cost WDA over 100 % of a core, and iOS kills a process above 80 % over a minute).
//!
//! While a page watches, the HID session stays open (`Inner::screen_viewers`): the phone keeps its screen on and
-//! shows "viewed remotely" meanwhile, as it does during HID use. The video is always portrait; the rotation of the
+//! shows "viewed remotely" meanwhile, as it does during HID use.
+//!
+//! A page in low-bandwidth mode ([`crate::protocol::LOW_BANDWIDTH`]) gets the video capped at
+//! [`ictl_device::LOW_BANDWIDTH_BITRATE`] while it watches. There is one stream per phone and its cap is set when it
+//! starts, so the HID session is closed and opened again when the cap has to change: when the first such page comes,
+//! and when the last one goes while others still watch (they get the full rate back). Every page's picture stops for
+//! about half a second then and reconnects, and a touch under way ends ([`crate::tools::video_bitrate`]). The video is always portrait; the rotation of the
//! interface is sent alongside ([`ScreenMsg::Info`]) and the page turns the picture.
use std::sync::Arc;
use std::time::{Duration, Instant};
-use ictl_device::Rotation;
+use ictl_device::{Rotation, Tunnel};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
use tokio::sync::broadcast::error::RecvError;
-use crate::core::{Daemon, hid_supported};
+use crate::core::{Daemon, close_hid, hid_supported};
use crate::protocol::{Response, SCREEN_KEYFRAME, ScreenMsg};
+use crate::tools::video_bitrate;
/// How often the interface rotation is asked of WDA while streaming (about 20 ms each, only when the device lock is
/// free)
@@ -34,15 +41,34 @@ fn degrees(r: Rotation) -> u32 {
}
}
-/// One watching page: counted while it lives, so the HID session isn't closed under it
-struct Viewer(Arc<Daemon>);
+/// One watching page: counted while it lives, so the HID session isn't closed under it. The flag: in low-bandwidth
+/// mode (`Inner::low_bandwidth_viewers`)
+struct Viewer(Arc<Daemon>, bool);
impl Drop for Viewer {
fn drop(&mut self) {
- let d = self.0.clone();
+ let (d, low) = (self.0.clone(), self.1);
tokio::spawn(async move {
let mut g = d.inner.lock().await;
g.screen_viewers = g.screen_viewers.saturating_sub(1);
+ if low {
+ g.low_bandwidth_viewers = g.low_bandwidth_viewers.saturating_sub(1);
+ // the last page in low-bandwidth mode is gone: the others get the full rate (they reconnect)
+ let full = video_bitrate(&g);
+ if g.low_bandwidth_viewers == 0
+ && g.screen_viewers > 0
+ && g.tunnel.as_mut().and_then(Tunnel::open_hid).is_some_and(|h| h.max_bitrate() < full)
+ {
+ close_hid(&mut g).await;
+ tracing::info!(
+ "{}",
+ ictl_l10n::log_tr!(
+ "控制台上没有弱网模式的页面了:屏幕媒体流按原码率重新开始",
+ "No control page is in low-bandwidth mode any more: the screen media stream starts again at the full bitrate"
+ )
+ );
+ }
+ }
// the idle countdown starts now
g.hid_used = Some(Instant::now());
});
@@ -56,8 +82,9 @@ impl Daemon {
mut reader: tokio::io::BufReader<OwnedReadHalf>,
mut w: OwnedWriteHalf,
expect_udid: Option<String>,
+ low_bandwidth: bool,
) {
- let (feed, viewer) = match self.screen_feed(expect_udid.as_deref()).await {
+ let (feed, viewer) = match self.screen_feed(expect_udid.as_deref(), low_bandwidth).await {
Ok(f) => f,
Err(e) => {
let mut line = serde_json::to_string(&Response::error(e)).unwrap_or_default();
@@ -72,7 +99,8 @@ impl Daemon {
return;
}
let _viewer = viewer;
- let mut frames = feed.subscribe();
+ // stopped already (the HID session closed meanwhile): the viewer reconnects
+ let Some(mut frames) = feed.subscribe() else { return };
feed.request_keyframe();
// nothing decodes before a keyframe (and the config message it brings)
let mut need_key = true;
@@ -158,10 +186,12 @@ impl Daemon {
rotation.map(degrees)
}
- /// The screen feed of the controlled device, opening the HID session for it if needed
+ /// The screen feed of the controlled device, opening the HID session for it if needed (again, at the lower rate,
+ /// for a page in low-bandwidth mode: see the module docs)
async fn screen_feed(
self: &Arc<Self>,
expect_udid: Option<&str>,
+ low_bandwidth: bool,
) -> crate::error::Result<(ictl_device::ScreenFeed, Viewer)> {
let mut g = self.inner.lock().await;
let g = &mut *g;
@@ -175,14 +205,35 @@ impl Daemon {
ictl_l10n::tr!("屏幕媒体流要 iOS 27 及以上", "The screen media stream needs iOS 27 or later").into()
);
}
+ let rate = if low_bandwidth { ictl_device::LOW_BANDWIDTH_BITRATE } else { video_bitrate(g) };
+ if g.tunnel.as_mut().and_then(Tunnel::open_hid).is_some_and(|h| h.max_bitrate() != rate) {
+ close_hid(g).await;
+ tracing::info!(
+ "{}",
+ if low_bandwidth {
+ ictl_l10n::log_tr!(
+ "控制台有页面开了弱网模式:屏幕媒体流降低码率重新开始",
+ "A control page is in low-bandwidth mode: the screen media stream starts again at a lower bitrate"
+ )
+ } else {
+ ictl_l10n::log_tr!(
+ "控制台上没有弱网模式的页面了:屏幕媒体流按原码率重新开始",
+ "No control page is in low-bandwidth mode any more: the screen media stream starts again at the full bitrate"
+ )
+ }
+ );
+ }
let feed = self
- .hid(g)
+ .hid_at(g, rate)
.await?
.screen_feed()
.ok_or(ictl_l10n::tr!("屏幕媒体流已停止", "The screen media stream stopped"))?;
g.screen_viewers += 1;
+ if low_bandwidth {
+ g.low_bandwidth_viewers += 1;
+ }
g.hid_used = Some(Instant::now());
- Ok((feed, Viewer(self.clone())))
+ Ok((feed, Viewer(self.clone(), low_bandwidth)))
}
}
diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs
index af7f7f7..3d46244 100644
--- a/crates/ictl-daemon/src/tools/mod.rs
+++ b/crates/ictl-daemon/src/tools/mod.rs
@@ -118,6 +118,16 @@ impl Daemon {
/// HID 会话(WDA 不可用时的后备路线)。开不起来就丢掉隧道,下次重建
pub(crate) async fn hid<'a>(&self, g: &'a mut Inner) -> crate::error::Result<&'a mut HidSession> {
+ let rate = video_bitrate(g);
+ self.hid_at(g, rate).await
+ }
+
+ /// [`Self::hid`], its screen video capped at `max_bitrate` if it has to be opened
+ pub(crate) async fn hid_at<'a>(
+ &self,
+ g: &'a mut Inner,
+ max_bitrate: u32,
+ ) -> crate::error::Result<&'a mut HidSession> {
// 低版本建隧道只会报 service not found:直接说清楚
if !hid_supported(g.info.as_ref()) {
return Err(wda_down(&g.state, g.info.as_ref()).into());
@@ -130,12 +140,12 @@ impl Daemon {
.ensure_tunnel(g, &device)
.await
.map_err(|e| ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}"))?;
- if let Err(e) = t.hid(screen).await {
+ if let Err(e) = t.hid(screen, max_bitrate).await {
drop_tunnel(g).await;
return Err(ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}").into());
}
// 第二次调用直接返回已开好的会话(这样写是为了绕开借用检查对条件返回的限制)
- Ok(g.tunnel.as_mut().expect("刚建好").hid(screen).await?)
+ Ok(g.tunnel.as_mut().expect("刚建好").hid(screen, max_bitrate).await?)
}
async fn hid_do<F>(&self, g: &mut Inner, f: F) -> crate::error::Result<()>
@@ -339,6 +349,12 @@ fn needs_wda() -> &'static str {
if ictl_l10n::is_en() { NEEDS_WDA_EN } else { NEEDS_WDA }
}
+/// The screen video's bitrate cap for a HID session opened now: low while a page in low-bandwidth mode watches
+/// (`crate::screen` opens the session again when that changes)
+pub(crate) fn video_bitrate(g: &Inner) -> u32 {
+ if g.low_bandwidth_viewers > 0 { ictl_device::LOW_BANDWIDTH_BITRATE } else { ictl_device::FULL_BITRATE }
+}
+
#[cfg(test)]
mod tests {
use super::input::*;
diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rs
index eb125a4..27e341f 100644
--- a/crates/ictl-device/src/hid.rs
+++ b/crates/ictl-device/src/hid.rs
@@ -111,6 +111,8 @@ pub struct HidSession {
pub rotation: Rotation,
contact: Option<(u16, u16)>,
stream: Option<ScreenMediaStream>,
+ /// The screen video's bitrate cap, set when it started ([`crate::media::FULL_BITRATE`])
+ max_bitrate: u32,
touch: UniversalHidServiceClient<Box<dyn ReadWrite>>,
indigo: IndigoHidClient<Box<dyn ReadWrite>>,
}
@@ -120,8 +122,9 @@ impl HidSession {
adapter: &mut AdapterHandle,
handshake: &mut RsdHandshake,
screen: ScreenSize,
+ max_bitrate: u32,
) -> Result<Self> {
- let stream = crate::media::start(adapter, handshake, 1).await?;
+ let stream = crate::media::start(adapter, handshake, 1, max_bitrate).await?;
// 时限加在这里而不是外层:外层取消会直接丢掉媒体流,走不到下面的 stop
let clients =
limit(ictl_l10n::tr!("连接 HID 服务", "connect to the HID service"), Duration::from_secs(20), async {
@@ -138,6 +141,7 @@ impl HidSession {
rotation: Rotation::Portrait,
contact: None,
stream: Some(stream),
+ max_bitrate,
touch,
indigo,
}),
@@ -232,6 +236,11 @@ impl HidSession {
}
/// 屏幕媒体流的画面(控制台用);流已经停了时为 None
+ /// The screen video's bitrate cap (bit/s): to change it, close the session and open another
+ pub fn max_bitrate(&self) -> u32 {
+ self.max_bitrate
+ }
+
pub fn screen_feed(&self) -> Option<crate::ScreenFeed> {
self.stream.as_ref().map(|s| s.feed())
}
diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs
index cb804c2..231da8a 100644
--- a/crates/ictl-device/src/lib.rs
+++ b/crates/ictl-device/src/lib.rs
@@ -41,7 +41,7 @@ use idevice::{
pub use apps::AppInfo;
pub use hid::{Button, HidSession};
-pub use media::{ScreenFeed, ScreenFrame, hevc_codec};
+pub use media::{FULL_BITRATE, LOW_BANDWIDTH_BITRATE, ScreenFeed, ScreenFrame, hevc_codec};
/// A running log stream from the phone; see [`Device::log_stream`]
pub struct LogStream(oslog::OsLogStream);
@@ -599,11 +599,12 @@ impl Tunnel {
.await
}
- /// HID 会话;没有就开一个:先启动显示媒体流(HID 的授权闸门),再连 universalhidservice 和 indigo
- pub async fn hid(&mut self, screen: ScreenSize) -> Result<&mut HidSession> {
+ /// HID 会话;没有就开一个:先启动显示媒体流(HID 的授权闸门,码率上限 `max_bitrate`,见 media.rs),再连
+ /// universalhidservice 和 indigo。已经开着就照旧用,不管它的码率上限
+ pub async fn hid(&mut self, screen: ScreenSize, max_bitrate: u32) -> Result<&mut HidSession> {
if self.hid.is_none() {
// 各步自带时限(见 HidSession::open):不能在这里整体取消,否则起来一半的媒体流没人停
- let h = HidSession::open(&mut self.adapter, &mut self.handshake, screen).await?;
+ let h = HidSession::open(&mut self.adapter, &mut self.handshake, screen, max_bitrate).await?;
self.hid = Some(h);
}
let h = self.hid.as_mut().expect("刚建好");
diff --git a/crates/ictl-device/src/media.rs b/crates/ictl-device/src/media.rs
index 7ac27d9..0c1e6e3 100644
--- a/crates/ictl-device/src/media.rs
+++ b/crates/ictl-device/src/media.rs
@@ -9,6 +9,9 @@
//! 每秒一个接收报告。上游说不回 RCTL 的话,剧烈运动时编码器和接收端的参考帧会对不上、画面花掉而解码不报错。
//! 关键帧只在开头有一个(KeyFrameInterval 0),之后要靠 PLI/FIR 请求(实测 15~20 毫秒后到)。
//!
+//! 码率上限在起流时协商([`FULL_BITRATE`],弱网模式 [`LOW_BANDWIDTH_BITRATE`]),之后改不了:换上限要关掉 HID 会话重开。
+//! 手机实测只认上限:报价里写更小的分辨率,它照样编原生分辨率;帧率也不随上限变(约 60 帧/秒,见 [`video_offer`])。
+//!
//! 起流部分移植自 idevice v0.1.68 `tools/src/coredevice_stream.rs`(MIT,Copyright Jackson Coxson),
//! 去掉了日志输出和应答转储,错误改成 `DeviceError`。
@@ -17,7 +20,7 @@ use idevice::{
core_device::{
CallInfoBlob, DisplayServiceClient, HevcDepacketizer, RtpPacket, 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,
+ build_start_video_parameters, is_rtcp, negotiation::build_screen_media_blob,
},
rsd::RsdHandshake,
tcp::handle::{AdapterHandle, UdpSocketHandle},
@@ -63,16 +66,18 @@ pub struct ScreenFrame {
}
/// 屏幕媒体流的画面:订阅([`Self::subscribe`])拿到之后的每一帧,要关键帧用 [`Self::request_keyframe`]。
-/// 克隆便宜;HID 会话关掉(媒体流停止)后订阅者收到 `Closed`
+/// 克隆便宜;HID 会话关掉(媒体流停止)后订阅者收到 `Closed`。所以这里只留弱引用:持有 feed 的订阅者
+/// 要是握着发送端,通道就永远不关,媒体流换掉后它一直等不到帧
#[derive(Clone)]
pub struct ScreenFeed {
- frames: broadcast::Sender<ScreenFrame>,
+ frames: broadcast::WeakSender<ScreenFrame>,
keyframe: mpsc::UnboundedSender<()>,
}
impl ScreenFeed {
- pub fn subscribe(&self) -> broadcast::Receiver<ScreenFrame> {
- self.frames.subscribe()
+ /// `None`: the media stream has stopped
+ pub fn subscribe(&self) -> Option<broadcast::Receiver<ScreenFrame>> {
+ self.frames.upgrade().map(|f| f.subscribe())
}
/// 请手机尽快发一个关键帧(新订阅者、跟不上丢了帧时)
@@ -285,6 +290,7 @@ pub(crate) async fn start(
adapter: &mut AdapterHandle,
handshake: &mut RsdHandshake,
display_id: i64,
+ max_bitrate: u32,
) -> Result<ScreenMediaStream> {
let fail = |what: &str, e: &dyn std::fmt::Display| {
DeviceError::Idevice(ictl_l10n::trf!("媒体流 {what}:{e}", "media stream {what}: {e}"))
@@ -331,7 +337,7 @@ pub(crate) async fn start(
let call_id = uuid::Uuid::new_v4().to_string().to_uppercase();
let ssrc = uuid::Uuid::new_v4().as_u128() as u32;
- let offer = build_screen_video_offer(&call_id, &call_info, ssrc)
+ let offer = video_offer(&call_id, &call_info, ssrc, max_bitrate)
.map_err(|e| fail(ictl_l10n::tr!("视频报价", "video offer"), &e))?;
let params = build_start_video_parameters(
&receiver_ip,
@@ -362,10 +368,102 @@ pub(crate) async fn start(
let (frames, _) = broadcast::channel(FEED_CAPACITY);
let (keyframe, keyframe_rx) = mpsc::unbounded_channel();
- let feed = ScreenFeed { frames: frames.clone(), keyframe };
+ let feed = ScreenFeed { frames: frames.downgrade(), keyframe };
Ok(ScreenMediaStream { client, receive: receive(audio_udp, video_udp, ssrc, frames, keyframe_rx), feed })
}
+/// What the screen video may use (bit/s), as idevice's offer has it: about 3 Mbit/s while swiping on an iPhone's home
+/// screen, 1.9 Mbit/s still (iPhone 15 Pro Max, iOS 27.2.1)
+pub const FULL_BITRATE: u32 = 6_000_000;
+/// The control page's low-bandwidth mode: about half the traffic (1.4 Mbit/s swiping, 0.8 still) at the same frame
+/// rate. A still screen looks the same; while things move, edges show blocks, gone about half a second after
+pub const LOW_BANDWIDTH_BITRATE: u32 = 2_000_000;
+
+/// The video offer with the bitrate cap `max_bitrate`. idevice's offer ([`build_screen_video_offer`]) asks for
+/// [`FULL_BITRATE`]; for another cap its media blob is built again with that entry of the parameter list changed (the
+/// phone takes it as `TXMaxBitrate`), and put into the same offer
+fn video_offer(
+ call_id: &str,
+ info: &CallInfoBlob,
+ ssrc: u32,
+ max_bitrate: u32,
+) -> std::result::Result<Vec<u8>, String> {
+ let offer = build_screen_video_offer(call_id, info, ssrc).map_err(|e| e.to_string())?;
+ if max_bitrate == FULL_BITRATE {
+ return Ok(offer);
+ }
+ let blob = build_screen_media_blob(ssrc, ntp_now());
+ let blob = with_max_bitrate(&blob, max_bitrate).ok_or("idevice's offer has no bitrate cap to change")?;
+ let mut d: plist::Dictionary = plist::from_bytes(&offer).map_err(|e| e.to_string())?;
+ d.insert(MEDIA_BLOB.into(), plist::Value::Data(zlib_stored(&blob)));
+ let mut out = Vec::new();
+ plist::to_writer_binary(&mut out, &plist::Value::Dictionary(d)).map_err(|e| e.to_string())?;
+ Ok(out)
+}
+
+/// The offer's key for the (zlib) media blob
+const MEDIA_BLOB: &str = "avcMediaStreamNegotiatorMediaBlob";
+
+/// The blob with the parameter `{1: 0, 2: FULL_BITRATE, 3: 0x20000}` (field 9) giving `max_bitrate` instead
+fn with_max_bitrate(blob: &[u8], max_bitrate: u32) -> Option<Vec<u8>> {
+ let old = bitrate_param(FULL_BITRATE);
+ let at = blob.windows(old.len()).position(|w| w == old.as_slice())?;
+ let mut out = blob[..at].to_vec();
+ out.extend(bitrate_param(max_bitrate));
+ out.extend_from_slice(&blob[at + old.len()..]);
+ Some(out)
+}
+
+/// Field 9 `{1: 0, 2: value, 3: 0x20000}` as protobuf
+fn bitrate_param(value: u32) -> Vec<u8> {
+ fn varint(o: &mut Vec<u8>, mut v: u64) {
+ while v >= 0x80 {
+ o.push((v as u8) | 0x80);
+ v >>= 7;
+ }
+ o.push(v as u8);
+ }
+ let mut m = Vec::new();
+ for (field, v) in [(1u64, 0u64), (2, u64::from(value)), (3, 0x20000)] {
+ varint(&mut m, field << 3);
+ varint(&mut m, v);
+ }
+ let mut o = Vec::new();
+ varint(&mut o, (9 << 3) | 2);
+ varint(&mut o, m.len() as u64);
+ o.extend(m);
+ o
+}
+
+/// zlib of `data` in stored (uncompressed) blocks: the blob is a few hundred bytes, and this needs no deflate
+fn zlib_stored(data: &[u8]) -> Vec<u8> {
+ let mut z = vec![0x78, 0x01];
+ let chunks: Vec<&[u8]> = data.chunks(0xffff).collect();
+ for (i, c) in chunks.iter().enumerate() {
+ z.push(u8::from(i + 1 == chunks.len()));
+ let n = c.len() as u16;
+ z.extend_from_slice(&n.to_le_bytes());
+ z.extend_from_slice(&(!n).to_le_bytes());
+ z.extend_from_slice(c);
+ }
+ if chunks.is_empty() {
+ z.extend_from_slice(&[1, 0, 0, 0xff, 0xff]);
+ }
+ let (mut a, mut b) = (1u32, 0u32);
+ for &x in data {
+ a = (a + u32::from(x)) % 65521;
+ b = (b + a) % 65521;
+ }
+ z.extend_from_slice(&((b << 16) | a).to_be_bytes());
+ z
+}
+
+/// Now as NTP (seconds since 1900 in the high 32 bits), for the media blob
+fn ntp_now() -> u64 {
+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
+ ((now.as_secs() + 2_208_988_800) << 32) | ((u64::from(now.subsec_nanos()) << 32) / 1_000_000_000)
+}
+
async fn stop(client: &mut DisplayServiceClient<Box<dyn ReadWrite>>) {
match tokio::time::timeout(STEP, client.stop_media_stream()).await {
Ok(Ok(_)) => {}
@@ -418,4 +516,58 @@ mod tests {
assert_eq!(hevc_codec(&sps).as_deref(), Some("hvc1.1.6.L150.B0"));
assert_eq!(hevc_codec(&[0, 0, 0, 1, 0x28, 1, 0xAA]), None, "no SPS");
}
+
+ /// The cap is the one entry of idevice's blob that changes; the offer is idevice's but for that blob, which the
+ /// phone reads (zlib, stored blocks)
+ #[test]
+ fn the_offer_carries_the_bitrate_cap() {
+ let blob = build_screen_media_blob(7, 1 << 32);
+ assert_eq!(with_max_bitrate(&blob, FULL_BITRATE).as_deref(), Some(blob.as_slice()));
+ let low = with_max_bitrate(&blob, LOW_BANDWIDTH_BITRATE).expect("idevice's blob has the 6M cap");
+ assert_ne!(low, blob);
+ assert!(
+ low.windows(bitrate_param(LOW_BANDWIDTH_BITRATE).len()).any(|w| w == bitrate_param(LOW_BANDWIDTH_BITRATE))
+ );
+ assert_eq!(low.len(), blob.len() - 1, "2_000_000 is one varint byte shorter");
+
+ let info = CallInfoBlob { device_type: "Mac17,7".into(), ..Default::default() };
+ let full = video_offer("C", &info, 7, FULL_BITRATE).unwrap();
+ let offer: plist::Dictionary =
+ plist::from_bytes(&video_offer("C", &info, 7, LOW_BANDWIDTH_BITRATE).unwrap()).unwrap();
+ let theirs: plist::Dictionary = plist::from_bytes(&full).unwrap();
+ assert_eq!(offer.keys().collect::<Vec<_>>(), theirs.keys().collect::<Vec<_>>());
+ for k in theirs.keys().filter(|k| *k != MEDIA_BLOB) {
+ assert_eq!(offer[k], theirs[k], "{k}");
+ }
+ let z = offer[MEDIA_BLOB].as_data().unwrap();
+ assert!(idevice::core_device::MediaNegotiationBlob::from_negotiator_offer(z).is_ok(), "valid zlib");
+ let raw = &z[7..z.len() - 4];
+ assert!(
+ raw.windows(bitrate_param(LOW_BANDWIDTH_BITRATE).len()).any(|w| w == bitrate_param(LOW_BANDWIDTH_BITRATE))
+ );
+ assert!(!raw.windows(bitrate_param(FULL_BITRATE).len()).any(|w| w == bitrate_param(FULL_BITRATE)));
+ }
+
+ #[test]
+ fn stored_zlib_inflates() {
+ for data in [vec![], b"abc".to_vec(), vec![7u8; 70_000]] {
+ let z = zlib_stored(&data);
+ // the decoder idevice uses for answers: a wrong checksum or block header fails
+ assert!(idevice::core_device::MediaNegotiationBlob::from_negotiator_offer(&z).is_ok(), "{}", data.len());
+ }
+ assert_eq!(zlib_stored(b"a"), [0x78, 0x01, 1, 1, 0, 0xfe, 0xff, b'a', 0, 0x62, 0, 0x62]);
+ }
+
+ /// Someone holding the feed doesn't keep the channel open: once the media stream stops (its receive task holds
+ /// the only sender), subscribers hear `Closed` and new ones get none
+ #[tokio::test]
+ async fn subscribers_hear_when_the_stream_stops() {
+ let (frames, _) = broadcast::channel::<ScreenFrame>(4);
+ let (keyframe, _rx) = mpsc::unbounded_channel();
+ let feed = ScreenFeed { frames: frames.downgrade(), keyframe };
+ let mut sub = feed.subscribe().expect("running");
+ drop(frames);
+ assert!(matches!(sub.recv().await, Err(broadcast::error::RecvError::Closed)));
+ assert!(feed.subscribe().is_none());
+ }
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 49bcec8..cca0cab 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -537,6 +537,7 @@ fn restarting(socket: &std::path::Path) -> bool {
pub async fn open_screen_stream(
socket: &std::path::Path,
expect_udid: Option<&str>,
+ low_bandwidth: bool,
) -> std::io::Result<
Result<(tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>, tokio::net::unix::OwnedWriteHalf), String>,
> {
@@ -549,6 +550,9 @@ pub async fn open_screen_stream(
if let Some(u) = expect_udid {
o.insert(EXPECT_UDID.into(), u.into());
}
+ if low_bandwidth {
+ o.insert(LOW_BANDWIDTH.into(), true.into());
+ }
}
let mut line = v.to_string();
line.push('\n');
@@ -661,6 +665,9 @@ pub const BACKGROUND: &str = "background";
/// see anyway. Pressing Home skips the alert lookup that comes first (0.8 s of a 1.3 s press on the home screen) and
/// looks only when the press didn't get to the home screen
pub const WATCHED: &str = "watched";
+/// Request key of a [`Request::ScreenStream`]: the page is in low-bandwidth mode, so the phone's video is capped at a
+/// lower bitrate while it watches (for every page watching that phone: there is one stream). Older daemons ignore it
+pub const LOW_BANDWIDTH: &str = "low_bandwidth";
/// 发一个请求、读一个响应(客户端用)。`timeout` 为 None 时一直等(例如 `sign` 要等签名装完)。
/// 返回之前被丢掉(超时、调用方取消)时连接随之关闭,守护进程会放弃还在排队的这个请求
diff --git a/tests/viewer/lowbandwidth.test.mjs b/tests/viewer/lowbandwidth.test.mjs
new file mode 100644
index 0000000..6bf1f24
--- /dev/null
+++ b/tests/viewer/lowbandwidth.test.mjs
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import { runInNewContext } from 'node:vm';
+
+const html = readFileSync(new URL('../../apps/iphone-control/src/viewer.html', import.meta.url), 'utf8');
+
+test('low-bandwidth mode is kept in the browser and asks the viewer for it with the picture', () => {
+ const fn = html.match(/^const LOW_BANDWIDTH_KEY = .*\n^function lowBandwidthOn\(\)[^\n]*$/m)[0];
+ const store = {};
+ const localStorage = { getItem: k => store[k] ?? null };
+ const { lowBandwidthOn } = runInNewContext(fn + '\n({ lowBandwidthOn })', { localStorage });
+ assert.equal(lowBandwidthOn(), false, 'off unless turned on');
+ store['ictl.lowBandwidth'] = '1';
+ assert.equal(lowBandwidthOn(), true);
+ const broken = runInNewContext(fn + '\n({ lowBandwidthOn })', { localStorage: { getItem() { throw new Error('denied'); } } });
+ assert.equal(broken.lowBandwidthOn(), false, 'storage turned off');
+ // one request for every kind of picture: the phone's own HEVC and the H.264
+ const fetches = [...html.matchAll(/fetch\(`\/video\?[^`]*`/g)].map(m => m[0]);
+ assert.equal(fetches.length, 1, fetches.join('\n'));
+ assert.match(fetches[0], /lowBandwidthOn\(\) \? '&low=1' : ''/);
+});
+
+test('the switch is in the settings, says what it costs, and is translated', () => {
+ assert.match(html, /<dialog[^>]*id="appearance"[^]*?id="low-bandwidth"[^]*?<\/dialog>/);
+ const hint = html.match(/<p class="appearance-hint" id="low-bandwidth-hint">([^<]+)<\/p>/)[1];
+ assert.match(hint, /所有在看这台手机的页面/, 'everyone watching that phone gets it');
+ const EN = JSON.parse(html.match(/^const EN = (\{.*\});$/m)[1]);
+ for (const zh of ['弱网模式', hint, '已开启弱网模式,正在重新连接画面…', '已关闭弱网模式,正在重新连接画面…']) {
+ assert.ok(EN[zh], zh);
+ }
+ // its own change handler: not saved as an appearance setting
+ assert.match(html, /\$\('#low-bandwidth'\)\.addEventListener\('change', ev => \{\n ev\.stopPropagation\(\);/);
+});
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 0945a51..56f7541 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -155,5 +155,6 @@ On macOS, and on Linux with ffmpeg installed, the control page's picture is H.26
- **Encoder:** `viewer` tries them in order when it starts, uses the first that works and says which in the terminal: NVENC on NVIDIA; VAAPI on AMD and Intel (the JPEG is decoded by the GPU too); QSV on Intel as well; V4L2 on ARM boards such as the Raspberry Pi; VideoToolbox on macOS (called directly, the JPEG decoded by the hardware too; with ffmpeg installed, its VideoToolbox is the fallback); otherwise x264 in software (uses the CPU). One that fails on the real picture is replaced by the next. On Linux the user must be in the `render` group to use the GPU; `doctor` checks it.
- **Slow links:** the page tells viewer every 100 ms how much it has received. When the link can't keep up, fewer frames are encoded: the frame rate drops, but the picture doesn't fall further and further behind. On a 200 KB/s link, for example, the picture catches up about 0.6 s after scrolling stops.
- **Falling back to MJPEG:** on Linux without ffmpeg, without a working encoder, or in a browser without WebCodecs (older ones), the page uses MJPEG. It no longer repeats the same frame while the screen is still, and on a slow link it only sends the newest frame.
+- **Low-bandwidth mode:** a switch in the control page's Settings, for use over the internet or a weak signal. About half the picture's traffic at the same frame rate; a still screen looks the same, while things move edges get a little blocky, clear again about half a second after they stop. The phone's own video (HEVC) is one stream per phone, its bitrate cap agreed with the phone when it starts, so while the mode is on every page watching that phone gets it (a 6 Mbit/s cap becomes 2 Mbit/s), and the first page to turn it on and the last to turn it off interrupt everyone's picture for about half a second and end a touch under way. H.264 only changes for the page that turned it on (qp 26). While it is on, the line under the picture says "Low-bandwidth mode".
- **Which one is in use:** shown under the picture, e.g. "Live · WDA · HEVC iPhone 312 KB/s" (the phone's own video) or "Live · WDA · H.264 VAAPI 254 KB/s".
- **Settings:** `IPHONE_CONTROL_VIEWER_CODEC` (`device`: only the phone's own video, `mjpeg`: only MJPEG), `IPHONE_CONTROL_VIEWER_QP`, `ICTL_FFMPEG`, see [Configuration](./configuration). On Linux install ffmpeg with `sudo apt install ffmpeg`; the .deb recommends it. Nothing to install on macOS.
diff --git a/website/en/troubleshoot/faq.md b/website/en/troubleshoot/faq.md
index 2b8b950..f0a9775 100644
--- a/website/en/troubleshoot/faq.md
+++ b/website/en/troubleshoot/faq.md
@@ -79,7 +79,7 @@ The picture area says why: not connected; pairing or Developer Mode still needed
## The control page's picture stutters or uses a lot of traffic
-On iOS 27 and later with a browser that decodes HEVC, the line under the picture says "HEVC iPhone" and the picture runs at about 60 frames a second; if your browser can't decode HEVC, use Chrome or Safari on a Mac. Look at the encoding shown under the picture. If it says MJPEG, install ffmpeg and restart `iphone-control viewer`: the picture switches to H.264 at about 1/15 of the traffic. The terminal says which encoder it uses when it starts, and `doctor` checks ffmpeg and access to the GPU. If it is already H.264 and the link is very slow, the frame rate drops but the picture doesn't fall further behind; to go further, raise `IPHONE_CONTROL_VIEWER_QP` a little (e.g. `24`). See [the control page's picture](../guide/cli#viewer-picture).
+On iOS 27 and later with a browser that decodes HEVC, the line under the picture says "HEVC iPhone" and the picture runs at about 60 frames a second; if your browser can't decode HEVC, use Chrome or Safari on a Mac. Look at the encoding shown under the picture. If it says MJPEG, install ffmpeg and restart `iphone-control viewer`: the picture switches to H.264 at about 1/15 of the traffic. The terminal says which encoder it uses when it starts, and `doctor` checks ffmpeg and access to the GPU. On a very slow link the frame rate drops but the picture doesn't fall further behind; turn on "Low-bandwidth mode" in the control page's Settings for about half the traffic (HEVC and H.264 alike), and for H.264 you can also raise `IPHONE_CONTROL_VIEWER_QP` a little (e.g. `24`). See [the control page's picture](../guide/cli#viewer-picture).
## WDA restarts every few minutes while the control page is open
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 2bac8c6..c19e2d8 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -155,5 +155,6 @@ macOS 上,以及 Linux 上装了 ffmpeg 时,控制台的画面是 H.264,
- **编码器:** `viewer` 启动时按顺序试,第一个能用的就用,并在终端里显示:NVIDIA 用 NVENC;AMD、Intel 用 VAAPI(JPEG 也交给显卡解码);Intel 还可以用 QSV;树莓派一类的 ARM 板用 V4L2;macOS 用 VideoToolbox(本程序直接调用,JPEG 也由硬件解码;装了 ffmpeg 时,它的 VideoToolbox 作备用);都不行就用 x264 软件编码(占 CPU)。处理真实画面时出错,会换下一个。Linux 上要用显卡,用户得在 `render` 组里,`doctor` 会检查。
- **链路慢时:** 页面每 100 毫秒告诉 viewer 收到了多少。链路跟不上时少编几帧,画面帧率下降,但不会越来越滞后。比如每秒 200 KB 的链路,滚动停下后约 0.6 秒画面追上。
- **自动改用 MJPEG:** Linux 上没有 ffmpeg、没有能用的编码器、浏览器不支持 WebCodecs(较旧的浏览器)时自动改用 MJPEG;画面静止时不再重复发同一张图,链路慢时只发最新的一张。
+- **弱网模式:** 控制台「设置」里的开关,适合外网或信号差时用。画面流量减少约一半,帧率不变;画面静止时看不出区别,动起来时边缘会有些糊块,停下约半秒后恢复。手机自己的视频(HEVC)每台手机只有一路,码率上限在开始时和手机协商,所以开着时所有在看这台手机的页面都会一起降(约 6 Mbit/s 上限降到 2 Mbit/s),第一个开它和最后一个关它的页面会让所有人的画面断开半秒左右再接上,进行中的触摸也会中断。H.264 只影响开它的那个页面(qp 提到 26)。开着时画面下方会写「弱网模式」。
- **看现在用的是哪种:** 画面下方写着,例如「实时画面 · WDA · HEVC iPhone 312 KB/s」(手机自己的视频)或「实时画面 · WDA · H.264 VAAPI 254 KB/s」。
- **设置:** `IPHONE_CONTROL_VIEWER_CODEC`(`device` 只用手机自己的视频,`mjpeg` 只用 MJPEG)、`IPHONE_CONTROL_VIEWER_QP`、`ICTL_FFMPEG`,见[配置](./configuration)。Linux 上安装 ffmpeg:`sudo apt install ffmpeg`,deb 包会推荐安装它;macOS 上不用装。
diff --git a/website/troubleshoot/faq.md b/website/troubleshoot/faq.md
index 371e7d4..673c431 100644
--- a/website/troubleshoot/faq.md
+++ b/website/troubleshoot/faq.md
@@ -77,7 +77,7 @@ iphone-control doctor # 逐层检查,每项失败都给出修复办法
## 控制台画面卡、流量大
-看画面下方写的编码方式。iOS 27 及以上、浏览器能解 HEVC 时是「HEVC iPhone」,约每秒 60 帧;浏览器解不了时换 Mac 上的 Chrome 或 Safari。是 MJPEG 的话,装上 ffmpeg 再重启 `iphone-control viewer`,画面改用 H.264,流量约为原来的 1/15;启动时终端里会写用的是哪个编码器,`doctor` 会检查 ffmpeg 和显卡能不能用。已经是 H.264、链路又很慢时,画面帧率会下降,但不会越来越滞后;还嫌慢,可以把 `IPHONE_CONTROL_VIEWER_QP` 调大一些(比如 `24`)。见[控制台的画面](../guide/cli#viewer-picture)。
+看画面下方写的编码方式。iOS 27 及以上、浏览器能解 HEVC 时是「HEVC iPhone」,约每秒 60 帧;浏览器解不了时换 Mac 上的 Chrome 或 Safari。是 MJPEG 的话,装上 ffmpeg 再重启 `iphone-control viewer`,画面改用 H.264,流量约为原来的 1/15;启动时终端里会写用的是哪个编码器,`doctor` 会检查 ffmpeg 和显卡能不能用。链路很慢时,画面帧率会下降,但不会越来越滞后;可以在控制台「设置」里打开「弱网模式」,流量约减一半(HEVC 和 H.264 都有效),H.264 还可以把 `IPHONE_CONTROL_VIEWER_QP` 调大一些(比如 `24`)。见[控制台的画面](../guide/cli#viewer-picture)。
## 控制台开着时 WDA 每隔几分钟重启一次