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

release: 0.2.1 — the phone's own HEVC video on iOS 27+, H.264 elsewhere (#42)

Qinghe Li112d103a253b
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index ed46431..99c7291 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -38,7 +38,7 @@ body:
id: version
attributes:
label: Version or commit / 版本或提交
- placeholder: v0.2.0, or the output of `git rev-parse --short HEAD`
+ placeholder: v0.2.1, or the output of `git rev-parse --short HEAD`
- type: textarea
id: doctor
attributes:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4aaa5c2..829aa6a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,18 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
+## [0.2.1] - 2026-11-12
+
### Added
+- On iOS 27 and later the control page shows the phone's own hardware-encoded video (the CoreDevice screen media stream, HEVC): about 60 frames a second at native resolution, nothing encoded on this machine and no capturing by WDA; the picture turns with the screen. Browsers that can't decode HEVC (Firefox, Chrome on most Linux machines) and older iOS fall back to H.264 or MJPEG. `IPHONE_CONTROL_VIEWER_CODEC=device` uses only this stream.
+- The control page shows the picture as H.264 at about 1/15 of the traffic: on macOS with VideoToolbox called directly (the JPEG decoded by the hardware too), no ffmpeg needed; on Linux with ffmpeg installed, GPU encoding first (NVENC, VAAPI, QSV, V4L2, else x264); on a slow link the frame rate drops instead of the picture falling further behind. Without ffmpeg it stays MJPEG, now without repeated frames. Settings: `IPHONE_CONTROL_VIEWER_CODEC`, `IPHONE_CONTROL_VIEWER_QP`.
- Experimental `ICTL_WDA_DETACHED=1`: WebDriverAgent is launched in the background without an XCTest session, so it also starts while the phone is locked and keeps running when the daemon restarts. See [WDA dependency research](docs/dev/wda-dependency-research.md).
+### Fixed
+
+- With the control page open, WDA is no longer killed by iOS every few minutes (iOS 27 and later): capturing the picture took WDA over a CPU core, iOS kills a process averaging more than 80 % over a minute, and the daemon restarted WDA, failing actions meanwhile. With the phone's own video WDA stays around 3 %. Below iOS 27 the picture still comes from WDA; close the control page when you aren't watching.
+
## [0.2.0] - 2026-11-11
### Upgrade notes
@@ -181,7 +189,8 @@ First public release.
- Docker image (single binary plus Debian's usbmuxd, not privileged) with a generated third-party license list, published to `ghcr.io/derrors/iphone-control` for linux/amd64 and linux/arm64.
- Running without Docker, from source or from the prebuilt Linux binaries (x86_64, aarch64): as a regular user with the system usbmuxd, XDG data and socket paths, the unsigned WebDriverAgent downloaded and checksum-verified before the first signing, `mcp-config` printing a direct command, and a systemd user service.
-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.0...HEAD
+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.1...HEAD
+[0.2.1]: https://github.com/Derrors/iphone-control/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/Derrors/iphone-control/compare/v0.1.5...v0.2.0
[0.1.5]: https://github.com/Derrors/iphone-control/compare/v0.1.4...v0.1.5
[0.1.4]: https://github.com/Derrors/iphone-control/compare/v0.1.3...v0.1.4
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 444e544..d1d0cce 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -6,10 +6,18 @@
## [Unreleased]
+## [0.2.1] - 2026-11-12
+
### 新增
+- iOS 27 及以上,控制台的画面直接用手机自己硬件编码的视频(CoreDevice 屏幕媒体流,HEVC):约每秒 60 帧、原生分辨率,本机不编码,WDA 也不用截图;转屏时画面跟着转正。浏览器解不了 HEVC(Firefox、多数 Linux 上的 Chrome)或设备低于 iOS 27 时自动改用 H.264 或 MJPEG。`IPHONE_CONTROL_VIEWER_CODEC=device` 只用这条流。
+- 控制台的画面改用 H.264,流量约为原来的 1/15:macOS 上本程序直接调 VideoToolbox(JPEG 也由硬件解码),不需要 ffmpeg;Linux 上装了 ffmpeg 时显卡编码优先(NVENC、VAAPI、QSV、V4L2,都不行用 x264);链路慢时降帧率,画面不会越来越滞后。没有 ffmpeg 时仍是 MJPEG,静止时不再重复发同一张。设置:`IPHONE_CONTROL_VIEWER_CODEC`、`IPHONE_CONTROL_VIEWER_QP`。
- 实验开关 `ICTL_WDA_DETACHED=1`:在后台启动 WebDriverAgent、不持有 XCTest 会话,锁屏时也能启动,守护进程重启时它不跟着断。见 [WDA 依赖调研](docs/dev/wda-dependency-research.md)。
+### 修复
+
+- 控制台开着时 WDA 不再每隔几分钟被 iOS 杀掉(iOS 27 及以上):WDA 一直截图给画面用,CPU 超过一个核,iOS 按一分钟平均超过 80% 杀掉它,守护进程随之重启 WDA,期间操作失败。改用手机自己的视频后 WDA 的 CPU 约 3%。iOS 27 以下仍靠 WDA 截图,不看时请关掉控制台页面。
+
## [0.2.0] - 2026-11-11
### 升级注意事项
@@ -179,7 +187,8 @@
- `setup`、`doctor`、`status`、`mcp-config`、`wda-bridge`、`notify-test` 命令。
- Docker 镜像(非 privileged,linux/amd64、linux/arm64);也可不用 Docker,从源码或预编译二进制以普通用户运行,附 systemd 用户服务。
-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.0...HEAD
+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.2.1...HEAD
+[0.2.1]: https://github.com/Derrors/iphone-control/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/Derrors/iphone-control/compare/v0.1.5...v0.2.0
[0.1.5]: https://github.com/Derrors/iphone-control/compare/v0.1.4...v0.1.5
[0.1.4]: https://github.com/Derrors/iphone-control/compare/v0.1.3...v0.1.4
diff --git a/Cargo.lock b/Cargo.lock
index 274af32..143f109 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1947,7 +1947,7 @@ dependencies = [
[[package]]
name = "ictl-daemon"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"anyhow",
"base64 0.23.1",
@@ -1969,7 +1969,7 @@ dependencies = [
[[package]]
name = "ictl-device"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"ictl-l10n",
"ictl-webinspector",
@@ -1985,14 +1985,14 @@ dependencies = [
[[package]]
name = "ictl-l10n"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"tokio",
]
[[package]]
name = "ictl-mcp"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"anyhow",
"ictl-l10n",
@@ -2004,7 +2004,7 @@ dependencies = [
[[package]]
name = "ictl-protocol"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"ictl-l10n",
"libc",
@@ -2015,7 +2015,7 @@ dependencies = [
[[package]]
name = "ictl-sign"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"ictl-l10n",
"plist",
@@ -2031,7 +2031,7 @@ dependencies = [
[[package]]
name = "ictl-unlock"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"ictl-l10n",
"ictl-wda",
@@ -2044,7 +2044,7 @@ dependencies = [
[[package]]
name = "ictl-wda"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"base64 0.23.1",
"ictl-device",
@@ -2060,7 +2060,7 @@ dependencies = [
[[package]]
name = "ictl-webinspector"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"idevice",
"plist",
@@ -2270,7 +2270,7 @@ dependencies = [
[[package]]
name = "iphone-control"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"anyhow",
"clap",
diff --git a/Cargo.toml b/Cargo.toml
index 7b07f59..9e16372 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,7 +17,7 @@ members = [
exclude = ["vendor"]
[workspace.package]
-version = "0.2.0"
+version = "0.2.1"
edition = "2024"
# rmcp 3.8 要求 1.88;Impactor/idevice 用 edition 2024
rust-version = "1.88"
diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.toml
index a741505..445af2b 100644
--- a/apps/iphone-control/Cargo.toml
+++ b/apps/iphone-control/Cargo.toml
@@ -44,6 +44,8 @@ hands tasks to a local Claude Code or Codex. Runs as a systemd user service; see
section = "utils"
priority = "optional"
depends = "$auto, usbmuxd"
+# the control page's picture as H.264 (about 1/15 of MJPEG's traffic); without it the page uses MJPEG
+recommends = "ffmpeg"
maintainer-scripts = "../../deploy/deb"
assets = [
["target/release/iphone-control", "usr/bin/", "755"],
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index c135663..4c23076 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -19,6 +19,7 @@ mod debug;
mod envfile;
mod guide;
mod service;
+mod video;
mod viewer;
#[derive(Parser)]
diff --git a/apps/iphone-control/src/video/device.rs b/apps/iphone-control/src/video/device.rs
new file mode 100644
index 0000000..e9f065c
--- /dev/null
+++ b/apps/iphone-control/src/video/device.rs
@@ -0,0 +1,170 @@
+//! The phone's own screen video (`GET /video?src=device`): the CoreDevice screen media stream (HEVC, iOS 27 and
+//! later) as the daemon hands it on ([`ictl_daemon::protocol::Request::ScreenStream`]), passed to the page in the
+//! same messages as the H.264 picture (see the module docs). Nothing is encoded here.
+//!
+//! Differences from the H.264 picture:
+//! - the config message has `annexb: true` and no `description`: frames are Annex-B with their parameter sets in the
+//! keyframes, which is how WebCodecs takes HEVC without one;
+//! - the picture is the phone's portrait framebuffer padded to multiples of 16 (1320×2868 arrives as 1328×2896): the
+//! page cuts the padding off and turns it by the `rotation` the daemon sends ([`ScreenMsg::Info`], type 3);
+//! - falling behind can't be met by encoding fewer frames: frames other than keyframes are dropped until a keyframe,
+//! which is asked for (one is 15–50 KB and arrives about 20 ms later).
+//!
+//! Browsers that can't decode HEVC (most without hardware decoding: Firefox, Chrome on most Linux) get the H.264
+//! picture or MJPEG instead; the page decides (`isConfigSupported`).
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use ictl_daemon::protocol::{SCREEN_KEYFRAME, ScreenMsg};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio::sync::mpsc;
+
+use super::{AbortOnDrop, Acks, Flow, QUEUE, message};
+
+/// Asking for keyframes at most this often while dropping frames
+const ASK_EVERY: Duration = Duration::from_millis(500);
+/// Largest message accepted from the daemon (a keyframe is well under 1 MB)
+const MAX_MESSAGE: usize = 16 * 1024 * 1024;
+
+/// Opens the daemon's screen stream for `udid`. `Err`: why there is none (an older iOS, no device, the phone
+/// locked when the tunnel had to be opened…); the caller answers the page with that
+pub async fn open(
+ socket: &std::path::Path,
+ udid: &str,
+) -> Result<(tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>, tokio::net::unix::OwnedWriteHalf), String> {
+ match ictl_daemon::protocol::open_screen_stream(socket, Some(udid)).await {
+ Ok(r) => r,
+ Err(e) => Err(e.to_string()),
+ }
+}
+
+/// Passes the stream to `client` until either ends. The HTTP head is already sent
+pub async fn serve(
+ mut src: tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>,
+ mut daemon_w: tokio::net::unix::OwnedWriteHalf,
+ acks: Arc<Acks>,
+ client: TcpStream,
+) {
+ let (mut client_rd, mut client_wr) = client.into_split();
+ let (ack_guard, mut acked) = acks.register();
+ let mut flow = Flow::default();
+
+ // messages from the daemon, read on their own so a slow page never stalls the daemon's side
+ let (msg_tx, mut msgs) = mpsc::channel::<(u8, Vec<u8>)>(8);
+ let reader = tokio::spawn(async move {
+ loop {
+ let mut head = [0u8; 5];
+ if src.read_exact(&mut head).await.is_err() {
+ return;
+ }
+ let len = u32::from_be_bytes([head[1], head[2], head[3], head[4]]) as usize;
+ if len > MAX_MESSAGE {
+ return;
+ }
+ let mut body = vec![0u8; len];
+ if src.read_exact(&mut body).await.is_err() || msg_tx.send((head[0], body)).await.is_err() {
+ return;
+ }
+ }
+ });
+ let _reader = AbortOnDrop(reader);
+
+ let (gone_tx, mut gone) = tokio::sync::oneshot::channel::<()>();
+ let watcher = tokio::spawn(async move {
+ let mut b = [0u8; 256];
+ while matches!(client_rd.read(&mut b).await, Ok(n) if n > 0) {}
+ let _ = gone_tx.send(());
+ });
+ let _watcher = AbortOnDrop(watcher);
+
+ let (out_tx, mut out_rx) = mpsc::channel::<Vec<u8>>(QUEUE);
+ let writer = tokio::spawn(async move {
+ while let Some(m) = out_rx.recv().await {
+ if client_wr.write_all(&m).await.is_err() {
+ return;
+ }
+ }
+ });
+ let _writer = AbortOnDrop(writer);
+
+ // dropping frames until a keyframe (the page fell behind, or its queue was full)
+ let mut need_key = false;
+ let mut asked: Option<Instant> = None;
+ loop {
+ tokio::select! {
+ _ = &mut gone => return,
+ m = msgs.recv() => {
+ let Some((kind, body)) = m else { return };
+ let now = Instant::now();
+ match ScreenMsg::from_byte(kind) {
+ Some(ScreenMsg::Config) => {
+ let Ok(mut v) = serde_json::from_slice::<serde_json::Value>(&body) else { continue };
+ v["stream"] = ack_guard.id.clone().into();
+ v["annexb"] = true.into();
+ v["description"] = "".into();
+ v["encoder"] = "iPhone".into();
+ let m = message(0, v.to_string().as_bytes());
+ flow.sent(m.len(), now);
+ if out_tx.send(m).await.is_err() {
+ return;
+ }
+ }
+ Some(ScreenMsg::Info) => {
+ let m = message(3, &body);
+ flow.sent(m.len(), now);
+ if out_tx.send(m).await.is_err() {
+ return;
+ }
+ }
+ Some(k @ (ScreenMsg::Key | ScreenMsg::Delta)) => {
+ let key = k == ScreenMsg::Key;
+ if !key && (need_key || flow.behind(now)) {
+ need_key = true;
+ if asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {
+ asked = Some(now);
+ if daemon_w.write_all(&[SCREEN_KEYFRAME]).await.is_err() {
+ return;
+ }
+ }
+ continue;
+ }
+ // a keyframe while the page is still behind waits for the next one
+ if key && flow.behind(now) {
+ need_key = true;
+ continue;
+ }
+ let m = message(if key { 1 } else { 2 }, &body);
+ let len = m.len();
+ match out_tx.try_send(m) {
+ Ok(()) => {
+ flow.sent(len, now);
+ if key {
+ need_key = false;
+ }
+ }
+ Err(mpsc::error::TrySendError::Full(_)) => need_key = true,
+ Err(mpsc::error::TrySendError::Closed(_)) => return,
+ }
+ }
+ None => {}
+ }
+ }
+ r = acked.changed() => {
+ if r.is_err() {
+ return;
+ }
+ let bytes = *acked.borrow_and_update();
+ flow.ack(bytes, Instant::now());
+ // caught up after dropping frames: a keyframe now rather than at the next request
+ if need_key && !flow.behind(Instant::now()) && asked.is_none_or(|t| t.elapsed() >= ASK_EVERY) {
+ asked = Some(Instant::now());
+ if daemon_w.write_all(&[SCREEN_KEYFRAME]).await.is_err() {
+ return;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apps/iphone-control/src/video/ffmpeg.rs b/apps/iphone-control/src/video/ffmpeg.rs
new file mode 100644
index 0000000..ee5bc87
--- /dev/null
+++ b/apps/iphone-control/src/video/ffmpeg.rs
@@ -0,0 +1,894 @@
+//! The encoder: an ffmpeg process per picture connection (on macOS first VideoToolbox inside this program, see
+//! `vt.rs`), picked from what this machine has, hardware first.
+//!
+//! ffmpeg runs as a separate program, not linked in: the builds that Linux distributions ship have the hardware
+//! encoders, and x264 being GPL doesn't reach this MIT program. Without ffmpeg the page keeps MJPEG (on macOS the
+//! native encoder needs no ffmpeg).
+//!
+//! Candidates in order ([`candidates`]): VideoToolbox in this program (macOS), NVENC (NVIDIA), VAAPI on each render
+//! node (AMD, Intel; first with the JPEG decoded by the GPU too, then decoded by ffmpeg on the CPU), QSV (Intel),
+//! V4L2 M2M (ARM boards), VideoToolbox through ffmpeg (macOS, the fallback for the native one), x264 (software). The first one that encodes a test frame is used; one that fails
+//! on the real frames is dropped for the next ([`Encoders::give_up`]).
+//!
+//! Held frames: ffmpeg keeps the newest frame until the next one arrives (one frame with VAAPI on an AMD 780M:
+//! the `mpjpeg` input and the decoder wait for more). The phone's repeated frames are dropped before ffmpeg, so on a
+//! screen that stopped changing the last change would wait, up to forever. Each frame is therefore written again
+//! `kicks` times right after itself: the copies push it out (16 ms instead of up to seconds on that machine) and
+//! encode to about 100 bytes each. `kicks` is measured when an encoder is picked: frames written minus frames out
+//! once the output has settled ([`Encoders::calibrate`]).
+
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use ictl_daemon::config::env;
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::process::{Child, Command};
+use tokio::sync::{mpsc, watch};
+use tokio::task::JoinHandle;
+
+use super::flv::{self, Packet};
+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 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;
+/// More copies than this would mean the measurement went wrong; the copies cost little, so it is only a cap
+const MAX_KICKS: usize = 4;
+/// Size of the test frame (any size the real frames could have; small enough to be quick)
+const SAMPLE: (u32, u32) = (480, 1040);
+/// How long picking one encoder may take, start-up of the GPU included
+const CALIBRATE_FOR: Duration = Duration::from_secs(8);
+
+/// What `IPHONE_CONTROL_VIEWER_CODEC` accepts besides `auto` and `mjpeg`
+pub const IDS: [&str; 6] = ["nvenc", "vaapi", "qsv", "v4l2m2m", "videotoolbox", "x264"];
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Kind {
+ /// NVIDIA; `hw_jpeg`: the JPEG is decoded by the GPU too
+ Nvenc { hw_jpeg: bool },
+ /// VAAPI on this render node (AMD, Intel)
+ Vaapi { node: PathBuf, hw_jpeg: bool },
+ /// Intel Quick Sync
+ Qsv,
+ /// The video encoder of ARM boards (Raspberry Pi 4 and the like)
+ V4l2m2m,
+ /// macOS, VideoToolbox called by this program (`vt.rs`): no ffmpeg needed
+ Native,
+ /// macOS, VideoToolbox through ffmpeg
+ VideoToolbox,
+ /// Software
+ X264,
+}
+
+impl Kind {
+ pub fn id(&self) -> &'static str {
+ match self {
+ Self::Nvenc { .. } => "nvenc",
+ Self::Vaapi { .. } => "vaapi",
+ Self::Qsv => "qsv",
+ Self::V4l2m2m => "v4l2m2m",
+ Self::Native | Self::VideoToolbox => "videotoolbox",
+ Self::X264 => "x264",
+ }
+ }
+
+ /// Short name, shown on the page
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::Nvenc { .. } => "NVENC",
+ Self::Vaapi { .. } => "VAAPI",
+ Self::Qsv => "QSV",
+ Self::V4l2m2m => "V4L2",
+ Self::Native | Self::VideoToolbox => "VideoToolbox",
+ Self::X264 => "x264",
+ }
+ }
+
+ /// The longer description for the terminal
+ /// Runs in an ffmpeg process (everything but [`Kind::Native`])
+ pub fn needs_ffmpeg(&self) -> bool {
+ !matches!(self, Self::Native)
+ }
+
+ pub fn describe(&self) -> String {
+ let jpeg = |hw: bool| {
+ if hw {
+ ictl_l10n::tr!("JPEG 也由显卡解码", "JPEG decoded by the GPU too")
+ } else {
+ ictl_l10n::tr!("JPEG 由 CPU 解码", "JPEG decoded on the CPU")
+ }
+ };
+ match self {
+ Self::Nvenc { hw_jpeg } => {
+ ictl_l10n::trf!("NVENC 硬件编码({})", "NVENC hardware encoding ({})", jpeg(*hw_jpeg))
+ }
+ Self::Vaapi { node, hw_jpeg } => ictl_l10n::trf!(
+ "VAAPI 硬件编码({},{})",
+ "VAAPI hardware encoding ({}, {})",
+ node.display(),
+ jpeg(*hw_jpeg)
+ ),
+ Self::Qsv => ictl_l10n::tr!("Intel QSV 硬件编码", "Intel QSV hardware encoding").into(),
+ Self::V4l2m2m => ictl_l10n::tr!("V4L2 M2M 硬件编码", "V4L2 M2M hardware encoding").into(),
+ Self::Native => ictl_l10n::tr!(
+ "VideoToolbox 硬件编码(本程序直接调用,JPEG 也由硬件解码)",
+ "VideoToolbox hardware encoding (called directly, JPEG decoded by the hardware too)"
+ )
+ .into(),
+ Self::VideoToolbox => {
+ ictl_l10n::tr!("VideoToolbox 硬件编码(经 ffmpeg)", "VideoToolbox hardware encoding (through ffmpeg)")
+ .into()
+ }
+ Self::X264 => ictl_l10n::tr!("x264 软件编码(占 CPU)", "x264 software encoding (uses the CPU)").into(),
+ }
+ }
+}
+
+/// The encoders worth trying on this machine, best first
+pub fn candidates() -> Vec<Kind> {
+ let mut v = Vec::new();
+ if cfg!(target_os = "macos") {
+ v.extend([Kind::Native, Kind::VideoToolbox]);
+ }
+ if cfg!(target_os = "linux") {
+ if Path::new("/dev/nvidiactl").exists() {
+ v.extend([Kind::Nvenc { hw_jpeg: true }, Kind::Nvenc { hw_jpeg: false }]);
+ }
+ let nodes = render_nodes();
+ for n in &nodes {
+ v.push(Kind::Vaapi { node: n.clone(), hw_jpeg: true });
+ v.push(Kind::Vaapi { node: n.clone(), hw_jpeg: false });
+ }
+ if nodes.iter().any(|n| gpu_vendor(n).as_deref() == Some("0x8086")) {
+ v.push(Kind::Qsv);
+ }
+ if cfg!(any(target_arch = "aarch64", target_arch = "arm"))
+ && std::fs::read_dir("/dev")
+ .is_ok_and(|d| d.flatten().any(|e| e.file_name().to_string_lossy().starts_with("video")))
+ {
+ v.push(Kind::V4l2m2m);
+ }
+ }
+ v.push(Kind::X264);
+ v
+}
+
+fn render_nodes() -> Vec<PathBuf> {
+ let Ok(d) = std::fs::read_dir("/dev/dri") else { return Vec::new() };
+ let mut v: Vec<PathBuf> = d
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("renderD")))
+ .collect();
+ v.sort();
+ v
+}
+
+/// PCI vendor of a render node's GPU (`0x8086` Intel, `0x1002` AMD, `0x10de` NVIDIA)
+fn gpu_vendor(node: &Path) -> Option<String> {
+ let name = node.file_name()?.to_string_lossy().into_owned();
+ std::fs::read_to_string(format!("/sys/class/drm/{name}/device/vendor")).ok().map(|s| s.trim().to_owned())
+}
+
+/// Bit rate for the encoders that only take one: 4 Mbit/s at qp 20, doubling every 6 steps down (as qp does)
+fn bitrate(qp: u8) -> String {
+ let kbps = 4000.0 * 2f64.powf((f64::from(DEFAULT_QP) - f64::from(qp)) / 6.0);
+ format!("{}k", kbps.round() as u64)
+}
+
+/// The full ffmpeg command line (without the program) for frames of `w`×`h`. `old`: ffmpeg before 5.1
+pub fn args(kind: &Kind, w: u32, h: u32, qp: u8, old: bool) -> Vec<String> {
+ // 4:2:0 needs even sizes (the phone's frames are 968×2097 at 75%): stretched by at most one pixel
+ let (w, h) = (w + (w & 1), h + (h & 1));
+ let qp_s = qp.to_string();
+ let sw_scale = format!("scale={w}:{h},format=nv12");
+ let (input, filter, codec): (Vec<String>, String, Vec<String>) = match kind {
+ Kind::Nvenc { hw_jpeg } => (
+ if *hw_jpeg { strings(&["-hwaccel", "cuda", "-hwaccel_output_format", "cuda"]) } else { Vec::new() },
+ if *hw_jpeg { format!("scale_cuda={w}:{h}:format=nv12") } else { sw_scale },
+ strings(&[
+ "-c:v",
+ "h264_nvenc",
+ "-preset",
+ "p4",
+ "-tune",
+ "ll",
+ "-rc",
+ "constqp",
+ "-qp",
+ &qp_s,
+ "-delay",
+ "0",
+ "-zerolatency",
+ "1",
+ ]),
+ ),
+ Kind::Vaapi { node, hw_jpeg } => {
+ let node = node.to_string_lossy().into_owned();
+ let mut codec = strings(&["-c:v", "h264_vaapi", "-rc_mode", "CQP", "-qp", &qp_s]);
+ // the default keeps several frames in flight (about 200 ms on an AMD 780M); the option is from ffmpeg 5
+ if !old {
+ codec.extend(strings(&["-async_depth", "1"]));
+ }
+ if *hw_jpeg {
+ (
+ strings(&["-hwaccel", "vaapi", "-hwaccel_device", &node, "-hwaccel_output_format", "vaapi"]),
+ format!("scale_vaapi=w={w}:h={h}:format=nv12"),
+ codec,
+ )
+ } else {
+ (strings(&["-vaapi_device", &node]), format!("{sw_scale},hwupload"), codec)
+ }
+ }
+ Kind::Qsv => (
+ Vec::new(),
+ sw_scale,
+ strings(&["-c:v", "h264_qsv", "-global_quality", &qp_s, "-look_ahead", "0", "-async_depth", "1"]),
+ ),
+ Kind::V4l2m2m => (Vec::new(), sw_scale, strings(&["-c:v", "h264_v4l2m2m", "-b:v", &bitrate(qp)])),
+ // never run through ffmpeg; the same line as ffmpeg's VideoToolbox keeps the match whole
+ Kind::Native | Kind::VideoToolbox => {
+ (Vec::new(), sw_scale, strings(&["-c:v", "h264_videotoolbox", "-realtime", "1", "-b:v", &bitrate(qp)]))
+ }
+ // crf one below the quantizer gives about the same size and quality as the hardware encoders at that qp
+ Kind::X264 => (
+ Vec::new(),
+ format!("scale={w}:{h}"),
+ strings(&[
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-tune",
+ "zerolatency",
+ "-crf",
+ &qp.saturating_sub(1).to_string(),
+ "-pix_fmt",
+ "yuv420p",
+ ]),
+ ),
+ };
+ let mut a = strings(&[
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostats",
+ "-probesize",
+ "32",
+ "-analyzeduration",
+ "0",
+ "-fflags",
+ "nobuffer",
+ ]);
+ a.extend(input);
+ a.extend(strings(&[
+ "-f",
+ "mpjpeg",
+ "-i",
+ "pipe:0",
+ if old { "-vsync" } else { "-fps_mode" },
+ "passthrough",
+ "-an",
+ ]));
+ a.extend(strings(&["-vf", &filter]));
+ a.extend(codec);
+ a.extend(strings(&[
+ "-bf",
+ "0",
+ "-g",
+ &GOP_FRAMES.to_string(),
+ "-f",
+ "flv",
+ "-flvflags",
+ "no_duration_filesize",
+ "-flush_packets",
+ "1",
+ ]));
+ a.push("pipe:1".into());
+ a
+}
+
+fn strings(v: &[&str]) -> Vec<String> {
+ v.iter().map(|s| (*s).to_owned()).collect()
+}
+
+/// `IPHONE_CONTROL_VIEWER_QP`: 1 (best, largest) to 51 (worst, smallest); anything else is the default
+pub fn qp_from(v: Option<&str>) -> u8 {
+ v.and_then(|v| v.parse::<u8>().ok()).filter(|q| (1..=51).contains(q)).unwrap_or(DEFAULT_QP)
+}
+
+/// Whether `ffmpeg -version`'s first line names a version before 5.1 (no `-fps_mode`). Builds from git
+/// (`N-…`) and anything that doesn't parse count as new
+pub fn is_old(version_line: &str) -> bool {
+ let Some(v) = version_line.split_whitespace().nth(2) else { return false };
+ let v = v.trim_start_matches('n');
+ let mut parts = v.split(|c: char| !c.is_ascii_digit());
+ let (Some(Ok(major)), minor) = (parts.next().map(str::parse::<u32>), parts.next()) else { return false };
+ let minor = minor.and_then(|m| m.parse::<u32>().ok()).unwrap_or(0);
+ (major, minor) < (5, 1)
+}
+
+/// The one in use and how many copies follow each frame
+#[derive(Debug, Clone, Copy)]
+struct Current {
+ index: usize,
+ kicks: usize,
+ /// The native encoder runs in software (a VM without the media engine)
+ software: bool,
+}
+
+/// The encoders of this machine and the one in use, shared by every picture connection
+pub struct Encoders {
+ /// `None`: only the native encoder (macOS without ffmpeg)
+ ffmpeg: Option<PathBuf>,
+ qp: u8,
+ old: bool,
+ list: Vec<Kind>,
+ /// A test frame (from ffmpeg itself, or VideoToolbox's JPEG encoder without ffmpeg)
+ sample: Arc<Vec<u8>>,
+ current: Mutex<Option<Current>>,
+ /// Only one picks at a time (picking starts processes and takes a second or two)
+ picking: tokio::sync::Mutex<()>,
+}
+
+impl Encoders {
+ /// Finds and checks an encoder. `Err`: why the page keeps MJPEG (no ffmpeg, none works, or turned off)
+ pub async fn detect() -> Result<Arc<Self>, String> {
+ let want = env("IPHONE_CONTROL_VIEWER_CODEC").map(|v| v.to_ascii_lowercase());
+ let want = want.as_deref().filter(|v| *v != "auto");
+ if want == Some("mjpeg") {
+ return Err(ictl_l10n::tr!("IPHONE_CONTROL_VIEWER_CODEC=mjpeg", "IPHONE_CONTROL_VIEWER_CODEC=mjpeg").into());
+ }
+ // only the phone's own video (`super::device`), MJPEG where it can't be used
+ if want == Some("device") {
+ return Err(
+ ictl_l10n::tr!("IPHONE_CONTROL_VIEWER_CODEC=device", "IPHONE_CONTROL_VIEWER_CODEC=device").into()
+ );
+ }
+ let mut list = candidates();
+ if let Some(w) = want {
+ if !IDS.contains(&w) {
+ return Err(ictl_l10n::trf!(
+ "IPHONE_CONTROL_VIEWER_CODEC={w} 不认识,可以是 auto、device、mjpeg、{}",
+ "IPHONE_CONTROL_VIEWER_CODEC={w} isn't known; it can be auto, device, mjpeg, {}",
+ IDS.join("、")
+ ));
+ }
+ list.retain(|k| k.id() == w);
+ if list.is_empty() {
+ return Err(ictl_l10n::trf!(
+ "IPHONE_CONTROL_VIEWER_CODEC={w},但这台机器上没有它",
+ "IPHONE_CONTROL_VIEWER_CODEC={w}, but this machine doesn't have it"
+ ));
+ }
+ }
+ let mut found = None;
+ for p in ictl_daemon::config::ffmpeg_paths() {
+ if let Some(v) = version_line(&p).await {
+ found = Some((p, v));
+ break;
+ }
+ }
+ let (ffmpeg, old) = match found {
+ Some((p, v)) => (Some(p), is_old(&v)),
+ None => {
+ list.retain(|k| !k.needs_ffmpeg());
+ (None, false)
+ }
+ };
+ if list.is_empty() {
+ return Err(ictl_l10n::tr!(
+ "没找到 ffmpeg;装上它画面改用 H.264,流量约为现在的 1/15",
+ "ffmpeg not found; with it installed the picture uses H.264 at about 1/15 of the traffic"
+ )
+ .to_owned());
+ }
+ let sample = Arc::new(match &ffmpeg {
+ Some(f) => sample_jpeg(f).await?,
+ None => native_sample().await?,
+ });
+ let e = Arc::new(Self {
+ ffmpeg,
+ qp: qp_from(env("IPHONE_CONTROL_VIEWER_QP").as_deref()),
+ old,
+ list,
+ sample,
+ current: Mutex::new(None),
+ picking: tokio::sync::Mutex::new(()),
+ });
+ e.pick_from(0).await?;
+ Ok(e)
+ }
+
+ fn current(&self) -> Option<Current> {
+ *self.current.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ /// The encoder in use (for the page), `None` once none is left
+ pub fn label(&self) -> Option<&'static str> {
+ self.current().map(|c| self.list[c.index].label())
+ }
+
+ /// The encoder in use and its settings (for the terminal)
+ pub fn describe(&self) -> String {
+ match self.current() {
+ Some(c) if c.software => ictl_l10n::trf!(
+ "{},qp {}(这台机器上是软件编码)",
+ "{}, qp {} (encoding in software on this machine)",
+ self.list[c.index].describe(),
+ self.qp
+ ),
+ Some(c) => ictl_l10n::trf!("{},qp {}", "{}, qp {}", self.list[c.index].describe(), self.qp),
+ None => ictl_l10n::tr!("没有可用的编码器", "no working encoder").into(),
+ }
+ }
+
+ /// Starts an encoder session for frames of `w`×`h`
+ pub fn start(&self, w: u32, h: u32) -> 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)
+ }
+
+ /// A session of `kind`; `info`: told how the native encoder was set up
+ fn session(
+ &self,
+ kind: &Kind,
+ w: u32,
+ h: u32,
+ 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)),
+ #[cfg(not(target_os = "macos"))]
+ Kind::Native => {
+ let _ = info;
+ return Err("VideoToolbox is only on macOS".into());
+ }
+ 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)?))
+ }
+ };
+ Ok(Session { size: (w, h), index, inner })
+ }
+
+ /// The encoder at `index` failed on real frames: use the next one that works. False when none is left
+ pub async fn give_up(&self, index: usize) -> bool {
+ let _one = self.picking.lock().await;
+ match self.current() {
+ // another connection moved on already
+ Some(c) if c.index != index => return true,
+ None => return false,
+ Some(_) => {}
+ }
+ tracing::warn!(
+ "{}",
+ ictl_l10n::log_trf!(
+ "画面编码器 {} 处理真实画面失败,换下一个",
+ "Picture encoder {} failed on the real frames, trying the next one",
+ self.list[index].describe()
+ )
+ );
+ self.pick_inner(index + 1).await.is_ok()
+ }
+
+ async fn pick_from(&self, start: usize) -> Result<(), String> {
+ let _one = self.picking.lock().await;
+ self.pick_inner(start).await
+ }
+
+ async fn pick_inner(&self, start: usize) -> Result<(), String> {
+ let mut last = String::new();
+ for i in start..self.list.len() {
+ match self.calibrate(&self.list[i]).await {
+ Ok((kicks, software)) => {
+ tracing::debug!("picture encoder {}: {} copies after each frame", self.list[i].id(), kicks);
+ *self.current.lock().unwrap_or_else(|p| p.into_inner()) =
+ Some(Current { index: i, kicks, software });
+ return Ok(());
+ }
+ Err(e) => {
+ tracing::debug!("picture encoder {} doesn't work: {e}", self.list[i].id());
+ last = format!("{}: {e}", self.list[i].label());
+ }
+ }
+ }
+ *self.current.lock().unwrap_or_else(|p| p.into_inner()) = None;
+ Err(ictl_l10n::trf!("没有能用的 H.264 编码器({last})", "No working H.264 encoder ({last})"))
+ }
+
+ /// Checks that `kind` encodes, and measures how many frames it holds back (see the module docs): the test
+ /// frame is written until a frame comes out, then, once nothing more comes, written minus out is what stays held.
+ /// Also whether the native encoder runs in software
+ 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 deadline = Instant::now() + CALIBRATE_FOR;
+ let mut out = 0;
+ while out == 0 {
+ if Instant::now() > deadline {
+ return Err(ictl_l10n::tr!("测试帧编码超时", "timed out encoding a test frame").into());
+ }
+ s.push(self.sample.clone());
+ // the writer sends it before the next round (it is small), so every push is one frame written
+ out += s.frames_within(Duration::from_millis(300)).await?;
+ }
+ out += s.frames_within(Duration::from_millis(500)).await?;
+ let written = s.written();
+ let software = matches!(info.await, Ok(i) if in_software(&i));
+ Ok((written.saturating_sub(out).min(MAX_KICKS), software))
+ }
+}
+
+#[cfg(target_os = "macos")]
+type NativeInfo = super::vt::Info;
+/// No native encoder here, so never a report from one
+#[cfg(not(target_os = "macos"))]
+enum NativeInfo {}
+
+/// The native encoder runs in software (no media engine, e.g. in a VM)
+#[cfg(target_os = "macos")]
+fn in_software(i: &NativeInfo) -> bool {
+ !i.hardware
+}
+#[cfg(not(target_os = "macos"))]
+fn in_software(i: &NativeInfo) -> bool {
+ match *i {}
+}
+
+/// The test frame without ffmpeg: from VideoToolbox's JPEG encoder (macOS)
+async fn native_sample() -> Result<Vec<u8>, String> {
+ #[cfg(target_os = "macos")]
+ {
+ tokio::task::spawn_blocking(|| super::vt::sample_jpeg(SAMPLE.0, SAMPLE.1, 0))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| ictl_l10n::trf!("生成测试帧失败:{e}", "Making a test frame failed: {e}"))
+ }
+ #[cfg(not(target_os = "macos"))]
+ Err("no ffmpeg".into())
+}
+
+/// `ffmpeg -version`'s first line; `None` when it doesn't run
+async fn version_line(ffmpeg: &Path) -> Option<String> {
+ let out = tokio::time::timeout(
+ Duration::from_secs(10),
+ Command::new(ffmpeg).arg("-version").stdin(Stdio::null()).stderr(Stdio::null()).output(),
+ )
+ .await
+ .ok()?
+ .ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).lines().next().unwrap_or_default().to_owned())
+}
+
+/// A 4:2:0 JPEG like the phone's, drawn by ffmpeg's test source
+async fn sample_jpeg(ffmpeg: &Path) -> Result<Vec<u8>, String> {
+ let size = format!("testsrc2=s={}x{}", SAMPLE.0, SAMPLE.1);
+ let out = tokio::time::timeout(
+ Duration::from_secs(10),
+ Command::new(ffmpeg)
+ .args(["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", &size, "-frames:v", "1"])
+ .args(["-c:v", "mjpeg", "-pix_fmt", "yuvj420p", "-q:v", "5", "-f", "mjpeg", "pipe:1"])
+ .stdin(Stdio::null())
+ .output(),
+ )
+ .await
+ .map_err(|_| ictl_l10n::tr!("ffmpeg 生成测试帧超时", "ffmpeg timed out making a test frame").to_owned())?
+ .map_err(|e| e.to_string())?;
+ if !out.status.success() || mjpeg::jpeg_size(&out.stdout).is_none() {
+ return Err(ictl_l10n::trf!(
+ "ffmpeg 生成测试帧失败:{}",
+ "ffmpeg failed to make a test frame: {}",
+ String::from_utf8_lossy(&out.stderr).trim()
+ ));
+ }
+ Ok(out.stdout)
+}
+
+/// One encoder session for frames of one size: an ffmpeg process, or the native encoder's thread
+pub struct Session {
+ /// The frames' size (the JPEG's, before rounding to even)
+ pub size: (u32, u32),
+ /// Which encoder ([`Encoders::give_up`])
+ pub index: usize,
+ inner: Inner,
+}
+
+enum Inner {
+ Process(Box<Process>),
+ #[cfg(target_os = "macos")]
+ Native(super::vt::Session),
+}
+
+impl Session {
+ /// Encode this frame next (replaces one not yet written)
+ pub fn push(&self, jpeg: Arc<Vec<u8>>) {
+ match &self.inner {
+ Inner::Process(p) => p.push(jpeg),
+ #[cfg(target_os = "macos")]
+ Inner::Native(n) => n.push(jpeg),
+ }
+ }
+
+ /// The next packet; `None` when the encoder ended. Cancel-safe
+ pub async fn next(&mut self) -> Option<Result<Packet, String>> {
+ match &mut self.inner {
+ Inner::Process(p) => p.next().await,
+ #[cfg(target_os = "macos")]
+ Inner::Native(n) => n.next().await,
+ }
+ }
+
+ /// Frames given to the encoder so far, copies included
+ fn written(&self) -> usize {
+ match &self.inner {
+ Inner::Process(p) => p.written(),
+ #[cfg(target_os = "macos")]
+ Inner::Native(n) => n.written(),
+ }
+ }
+
+ /// Why the encoder ended
+ pub fn error(&self) -> String {
+ match &self.inner {
+ Inner::Process(p) => p.error(),
+ #[cfg(target_os = "macos")]
+ Inner::Native(n) => n.error(),
+ }
+ }
+
+ /// Frames that come out within `d`; an error when the encoder fails or ends
+ async fn frames_within(&mut self, d: Duration) -> Result<usize, String> {
+ let until = tokio::time::Instant::now() + d;
+ let mut n = 0;
+ loop {
+ match tokio::time::timeout_at(until, self.next()).await {
+ Err(_) => return Ok(n),
+ Ok(Some(Ok(Packet::Frame { .. }))) => n += 1,
+ Ok(Some(Ok(Packet::Config(_)))) => {}
+ Ok(Some(Err(e))) => return Err(e),
+ Ok(None) => return Err(self.error()),
+ }
+ }
+ }
+}
+
+/// One ffmpeg process encoding frames of one size
+struct Process {
+ input: watch::Sender<Option<Arc<Vec<u8>>>>,
+ out: mpsc::Receiver<Result<Packet, String>>,
+ written: Arc<AtomicUsize>,
+ errors: Arc<Mutex<VecDeque<String>>>,
+ tasks: Vec<JoinHandle<()>>,
+ _child: Child,
+}
+
+impl Drop for Process {
+ fn drop(&mut self) {
+ for t in &self.tasks {
+ t.abort();
+ }
+ }
+}
+
+impl Process {
+ fn spawn(ffmpeg: &Path, args: &[String], kicks: usize) -> Result<Self, String> {
+ let mut child = Command::new(ffmpeg)
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .spawn()
+ .map_err(|e| ictl_l10n::trf!("启动 ffmpeg 失败:{e}", "Starting ffmpeg failed: {e}"))?;
+ let (Some(mut stdin), Some(mut stdout), Some(stderr)) =
+ (child.stdin.take(), child.stdout.take(), child.stderr.take())
+ else {
+ return Err("ffmpeg pipes".into());
+ };
+ let (input, mut rx) = watch::channel::<Option<Arc<Vec<u8>>>>(None);
+ let written = Arc::new(AtomicUsize::new(0));
+ let w = written.clone();
+ // the newest frame wins: if ffmpeg falls behind, frames in between are skipped rather than queued
+ let writer = tokio::spawn(async move {
+ while rx.changed().await.is_ok() {
+ let Some(j) = rx.borrow_and_update().clone() else { continue };
+ let part = mjpeg::part(&j);
+ for _ in 0..=kicks {
+ if stdin.write_all(&part).await.is_err() {
+ return;
+ }
+ }
+ if stdin.flush().await.is_err() {
+ return;
+ }
+ w.fetch_add(1 + kicks, Ordering::Relaxed);
+ }
+ });
+ let (tx, out) = mpsc::channel(16);
+ let reader = tokio::spawn(async move {
+ let mut p = flv::Parser::default();
+ let mut buf = vec![0; 256 * 1024];
+ loop {
+ let n = match stdout.read(&mut buf).await {
+ Ok(0) | Err(_) => return,
+ Ok(n) => n,
+ };
+ p.push(&buf[..n]);
+ loop {
+ match p.next() {
+ Ok(Some(pk)) => {
+ if tx.send(Ok(pk)).await.is_err() {
+ return;
+ }
+ }
+ Ok(None) => break,
+ Err(e) => {
+ let _ = tx.send(Err(e)).await;
+ return;
+ }
+ }
+ }
+ }
+ });
+ let errors = Arc::new(Mutex::new(VecDeque::new()));
+ let e = errors.clone();
+ let logger = tokio::spawn(async move {
+ let mut lines = BufReader::new(stderr).lines();
+ while let Ok(Some(l)) = lines.next_line().await {
+ tracing::debug!("ffmpeg: {l}");
+ let mut e = e.lock().unwrap_or_else(|p| p.into_inner());
+ if e.len() == 3 {
+ e.pop_front();
+ }
+ e.push_back(l);
+ }
+ });
+ Ok(Self { input, out, written, errors, tasks: vec![writer, reader, logger], _child: child })
+ }
+
+ fn push(&self, jpeg: Arc<Vec<u8>>) {
+ self.input.send_replace(Some(jpeg));
+ }
+
+ async fn next(&mut self) -> Option<Result<Packet, String>> {
+ self.out.recv().await
+ }
+
+ fn written(&self) -> usize {
+ self.written.load(Ordering::Relaxed)
+ }
+
+ /// What ffmpeg said before it ended
+ fn error(&self) -> String {
+ let e = self.errors.lock().unwrap_or_else(|p| p.into_inner());
+ if e.is_empty() {
+ ictl_l10n::tr!("ffmpeg 退出了", "ffmpeg exited").into()
+ } else {
+ e.iter().cloned().collect::<Vec<_>>().join("; ")
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn versions_before_5_1_are_old() {
+ assert!(is_old("ffmpeg version 4.4.2-0ubuntu0.22.04.1 Copyright (c) 2000-2021 the FFmpeg developers"));
+ assert!(is_old("ffmpeg version 5.0.1 Copyright"));
+ assert!(!is_old("ffmpeg version 5.1.6-0+deb12u1 Copyright"));
+ assert!(!is_old("ffmpeg version 8.1.1-mediasrv Copyright (c) 2000-2026 the FFmpeg developers"));
+ assert!(!is_old("ffmpeg version n7.1 Copyright"));
+ assert!(!is_old("ffmpeg version N-118302-g1234abcd Copyright"));
+ assert!(!is_old(""));
+ }
+
+ #[test]
+ fn qp_is_checked() {
+ assert_eq!(qp_from(None), 20);
+ assert_eq!(qp_from(Some("24")), 24);
+ assert_eq!(qp_from(Some("0")), 20);
+ assert_eq!(qp_from(Some("52")), 20);
+ assert_eq!(qp_from(Some("high")), 20);
+ assert_eq!(bitrate(20), "4000k");
+ assert_eq!(bitrate(26), "2000k");
+ }
+
+ /// The VAAPI line as measured on an AMD 780M: GPU JPEG decoding, size rounded to even, one frame in flight,
+ /// FLV out with every packet flushed
+ #[test]
+ fn vaapi_arguments() {
+ let k = Kind::Vaapi { node: "/dev/dri/renderD128".into(), hw_jpeg: true };
+ let a = args(&k, 968, 2097, 20, false).join(" ");
+ assert!(
+ a.contains(
+ "-hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format vaapi -f mpjpeg -i pipe:0"
+ ),
+ "{a}"
+ );
+ assert!(a.contains("-fps_mode passthrough"), "{a}");
+ assert!(
+ a.contains("-vf scale_vaapi=w=968:h=2098:format=nv12 -c:v h264_vaapi -rc_mode CQP -qp 20 -async_depth 1"),
+ "{a}"
+ );
+ assert!(a.ends_with("-bf 0 -g 600 -f flv -flvflags no_duration_filesize -flush_packets 1 pipe:1"), "{a}");
+ let old = args(&k, 968, 2097, 20, true).join(" ");
+ assert!(old.contains("-vsync passthrough") && !old.contains("async_depth"), "{old}");
+ let sw =
+ args(&Kind::Vaapi { node: "/dev/dri/renderD128".into(), hw_jpeg: false }, 2097, 968, 20, false).join(" ");
+ assert!(
+ sw.contains("-vaapi_device /dev/dri/renderD128 -f mpjpeg")
+ && sw.contains("scale=2098:968,format=nv12,hwupload"),
+ "{sw}"
+ );
+ }
+
+ #[test]
+ fn x264_uses_crf_one_below() {
+ let a = args(&Kind::X264, 968, 2097, 20, false).join(" ");
+ assert!(a.contains("-c:v libx264 -preset veryfast -tune zerolatency -crf 19"), "{a}");
+ }
+
+ #[test]
+ fn software_is_always_last() {
+ assert_eq!(candidates().last(), Some(&Kind::X264));
+ }
+
+ /// On macOS the encoder inside this program comes first and ffmpeg's VideoToolbox stays as its fallback; both
+ /// answer to IPHONE_CONTROL_VIEWER_CODEC=videotoolbox
+ #[test]
+ fn native_videotoolbox_comes_first_on_macos() {
+ let c = candidates();
+ if cfg!(target_os = "macos") {
+ assert_eq!(&c[..2], [Kind::Native, Kind::VideoToolbox]);
+ assert!(!c[0].needs_ffmpeg() && c[1].needs_ffmpeg());
+ assert_eq!(c[0].id(), c[1].id());
+ } else {
+ assert!(!c.contains(&Kind::Native));
+ }
+ }
+
+ /// End to end with this machine's ffmpeg, when there is one: an encoder is picked and a frame comes out with
+ /// its decoder configuration
+ #[tokio::test]
+ async fn encodes_with_the_local_ffmpeg() {
+ if version_line(Path::new("ffmpeg")).await.is_none() && !cfg!(target_os = "macos") {
+ eprintln!("no ffmpeg here, skipped");
+ return;
+ }
+ let e = match Encoders::detect().await {
+ Ok(e) => e,
+ Err(m) => {
+ eprintln!("no H.264 encoder here ({m}), skipped");
+ return;
+ }
+ };
+ let mut s = e.start(SAMPLE.0, SAMPLE.1).unwrap();
+ s.push(e.sample.clone());
+ let mut config = None;
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+ loop {
+ match tokio::time::timeout_at(deadline, s.next()).await.expect("a frame within 10 s") {
+ Some(Ok(Packet::Config(c))) => config = Some(c),
+ Some(Ok(Packet::Frame { key, .. })) => {
+ assert!(key, "the first frame is a keyframe");
+ break;
+ }
+ other => panic!("{other:?} ({})", s.error()),
+ }
+ }
+ assert!(flv::codec_string(&config.expect("config before the frame")).unwrap().starts_with("avc1."));
+ }
+}
diff --git a/apps/iphone-control/src/video/flv.rs b/apps/iphone-control/src/video/flv.rs
new file mode 100644
index 0000000..cd13ed0
--- /dev/null
+++ b/apps/iphone-control/src/video/flv.rs
@@ -0,0 +1,141 @@
+//! Reads the FLV that ffmpeg writes. Every frame is a tag that carries its length, so a frame can go to the page
+//! as soon as its last byte is in; in a raw H.264 stream the end of a frame only shows when the next one starts, and
+//! the next one is held back by ffmpeg (see `ffmpeg.rs`). Only what ffmpeg's FLV muxer writes for H.264 is handled.
+
+/// What one FLV video tag holds
+#[derive(Debug, PartialEq, Eq)]
+pub enum Packet {
+ /// The decoder configuration (`avcC`), before the first frame of each encoder session
+ Config(Vec<u8>),
+ /// One encoded frame, NAL units with 4-byte lengths (the `avcC` format)
+ Frame { key: bool, data: Vec<u8> },
+}
+
+/// A tag larger than this means the stream is out of step
+const MAX_TAG: usize = 16 * 1024 * 1024;
+
+#[derive(Default)]
+pub struct Parser {
+ buf: Vec<u8>,
+ /// Past the file header
+ started: bool,
+}
+
+impl Parser {
+ pub fn push(&mut self, data: &[u8]) {
+ self.buf.extend_from_slice(data);
+ }
+
+ /// The next complete packet, if the bytes for one are in
+ pub fn next(&mut self) -> Result<Option<Packet>, String> {
+ loop {
+ if !self.started {
+ if self.buf.len() < 9 {
+ return Ok(None);
+ }
+ if &self.buf[..3] != b"FLV" {
+ return Err("ffmpeg's output isn't FLV".into());
+ }
+ // the header's own length, then the first "previous tag size" (0)
+ let skip = u32::from_be_bytes([self.buf[5], self.buf[6], self.buf[7], self.buf[8]]) as usize + 4;
+ if self.buf.len() < skip {
+ return Ok(None);
+ }
+ self.buf.drain(..skip);
+ self.started = true;
+ }
+ if self.buf.len() < 11 {
+ return Ok(None);
+ }
+ let size = u32::from_be_bytes([0, self.buf[1], self.buf[2], self.buf[3]]) as usize;
+ if size > MAX_TAG {
+ return Err(format!("FLV tag of {size} bytes, out of step"));
+ }
+ let end = 11 + size + 4;
+ if self.buf.len() < end {
+ return Ok(None);
+ }
+ let kind = self.buf[0] & 0x1F;
+ let tag: Vec<u8> = self.buf[11..11 + size].to_vec();
+ self.buf.drain(..end);
+ // 18 is the metadata, 8 audio (there is none)
+ if kind != 9 || tag.len() < 5 {
+ continue;
+ }
+ if tag[0] & 0x0F != 7 {
+ return Err(format!("FLV video codec {} isn't H.264", tag[0] & 0x0F));
+ }
+ // byte 1: 0 sequence header, 1 frame, 2 end of sequence; then a 3-byte composition time
+ match tag[1] {
+ 0 => return Ok(Some(Packet::Config(tag[5..].to_vec()))),
+ 1 => return Ok(Some(Packet::Frame { key: tag[0] >> 4 == 1, data: tag[5..].to_vec() })),
+ _ => {}
+ }
+ }
+ }
+}
+
+/// The WebCodecs codec string for an `avcC`: profile, compatibility flags and level, e.g. `avc1.640028`
+pub fn codec_string(avcc: &[u8]) -> Option<String> {
+ let p = avcc.get(1..4)?;
+ Some(format!("avc1.{:02x}{:02x}{:02x}", p[0], p[1], p[2]))
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ pub(crate) fn tag(kind: u8, body: &[u8]) -> Vec<u8> {
+ let mut t = vec![kind];
+ t.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]);
+ t.extend_from_slice(&[0; 7]);
+ t.extend_from_slice(body);
+ t.extend_from_slice(&((11 + body.len()) as u32).to_be_bytes());
+ t
+ }
+
+ pub(crate) fn header() -> Vec<u8> {
+ let mut h = b"FLV\x01\x01\x00\x00\x00\x09".to_vec();
+ h.extend_from_slice(&[0; 4]);
+ h
+ }
+
+ #[test]
+ fn tags_come_out_whole_however_the_bytes_arrive() {
+ let avcc = [1u8, 0x64, 0x00, 0x28, 0xFF];
+ let mut s = header();
+ s.extend(tag(18, b"metadata"));
+ s.extend(tag(9, &[[0x17, 0, 0, 0, 0].as_slice(), &avcc].concat()));
+ s.extend(tag(9, &[0x17, 1, 0, 0, 0, 0xAA, 0xBB]));
+ s.extend(tag(9, &[0x27, 1, 0, 0, 0, 0xCC]));
+ // one byte at a time: nothing comes out early, everything comes out once its last byte is in
+ let mut p = Parser::default();
+ let mut got = Vec::new();
+ for b in &s {
+ p.push(&[*b]);
+ while let Some(x) = p.next().unwrap() {
+ got.push(x);
+ }
+ }
+ assert_eq!(
+ got,
+ [
+ Packet::Config(avcc.to_vec()),
+ Packet::Frame { key: true, data: vec![0xAA, 0xBB] },
+ Packet::Frame { key: false, data: vec![0xCC] },
+ ]
+ );
+ assert_eq!(codec_string(&avcc).as_deref(), Some("avc1.640028"));
+ }
+
+ #[test]
+ fn other_input_is_an_error() {
+ let mut p = Parser::default();
+ p.push(b"HTTP/1.1 200 OK\r\n");
+ assert!(p.next().is_err());
+ let mut p = Parser::default();
+ p.push(&header());
+ p.push(&tag(9, &[0x1C, 1, 0, 0, 0]));
+ assert!(p.next().is_err(), "HEVC isn't expected");
+ }
+}
diff --git a/apps/iphone-control/src/video/mjpeg.rs b/apps/iphone-control/src/video/mjpeg.rs
new file mode 100644
index 0000000..ec8864d
--- /dev/null
+++ b/apps/iphone-control/src/video/mjpeg.rs
@@ -0,0 +1,180 @@
+//! Reads WDA's MJPEG stream: an HTTP response whose body is `multipart/x-mixed-replace`. WDA gives every part a
+//! `Content-Length`, so a frame is taken as soon as its last byte is in, without waiting for the next boundary.
+
+use std::io;
+
+use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, BufReader};
+
+/// Largest JPEG accepted (a full-size frame at the highest quality is well under 2 MB)
+const MAX_FRAME: usize = 16 * 1024 * 1024;
+const MAX_LINE: u64 = 8 * 1024;
+
+pub struct Frames<R> {
+ r: BufReader<R>,
+ /// Past the HTTP response head
+ in_body: bool,
+}
+
+impl<R: AsyncRead + Unpin> Frames<R> {
+ pub fn new(r: R) -> Self {
+ Self { r: BufReader::with_capacity(256 * 1024, r), in_body: false }
+ }
+
+ /// The next JPEG; `None` when the stream ends
+ pub async fn next(&mut self) -> io::Result<Option<Vec<u8>>> {
+ if !self.in_body {
+ let Some(status) = self.line().await? else { return Ok(None) };
+ if String::from_utf8_lossy(&status).split(' ').nth(1) != Some("200") {
+ return Err(bad("the MJPEG server didn't answer 200"));
+ }
+ loop {
+ match self.line().await? {
+ None => return Ok(None),
+ Some(l) if l.is_empty() => break,
+ Some(_) => {}
+ }
+ }
+ self.in_body = true;
+ }
+ // blank lines before the boundary, then the boundary and the part's headers up to a blank line
+ let mut len = None;
+ let mut in_part = false;
+ loop {
+ let Some(l) = self.line().await? else { return Ok(None) };
+ if l.is_empty() {
+ if in_part {
+ break;
+ }
+ continue;
+ }
+ in_part = true;
+ let l = String::from_utf8_lossy(&l);
+ if let Some((k, v)) = l.split_once(':')
+ && k.trim().eq_ignore_ascii_case("content-length")
+ {
+ len = v.trim().parse::<usize>().ok();
+ }
+ }
+ let len = len.ok_or_else(|| bad("a part without Content-Length"))?;
+ if len > MAX_FRAME {
+ return Err(bad("frame too large"));
+ }
+ let mut buf = vec![0; len];
+ self.r.read_exact(&mut buf).await?;
+ Ok(Some(buf))
+ }
+
+ /// One line without its line break; `None` at the end of the stream
+ async fn line(&mut self) -> io::Result<Option<Vec<u8>>> {
+ let mut line = Vec::new();
+ let n = (&mut self.r).take(MAX_LINE).read_until(b'\n', &mut line).await?;
+ if n == 0 {
+ return Ok(None);
+ }
+ if !line.ends_with(b"\n") {
+ return Err(bad("header line too long or cut off"));
+ }
+ while matches!(line.last(), Some(b'\n' | b'\r')) {
+ line.pop();
+ }
+ Ok(Some(line))
+ }
+}
+
+fn bad(m: &str) -> io::Error {
+ io::Error::new(io::ErrorKind::InvalidData, m)
+}
+
+/// The part ffmpeg's `mpjpeg` input reads: its own boundary, the length, the JPEG
+pub fn part(jpeg: &[u8]) -> Vec<u8> {
+ let mut p = format!("--ictl\r\nContent-Type: image/jpeg\r\nContent-Length: {}\r\n\r\n", jpeg.len()).into_bytes();
+ p.extend_from_slice(jpeg);
+ p.extend_from_slice(b"\r\n");
+ p
+}
+
+/// Width and height from a JPEG's frame header (SOF), without decoding it
+pub fn jpeg_size(j: &[u8]) -> Option<(u32, u32)> {
+ if j.get(..2)? != [0xFF, 0xD8] {
+ return None;
+ }
+ let mut i = 2;
+ while i + 4 <= j.len() {
+ if j[i] != 0xFF {
+ return None;
+ }
+ let m = j[i + 1];
+ match m {
+ // fill byte
+ 0xFF => i += 1,
+ // markers without a length
+ 0x01 | 0xD0..=0xD7 => i += 2,
+ // start of scan: the frame header comes before it
+ 0xDA => return None,
+ 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => {
+ let s = j.get(i + 5..i + 9)?;
+ let h = u16::from_be_bytes([s[0], s[1]]);
+ let w = u16::from_be_bytes([s[2], s[3]]);
+ return (w > 0 && h > 0).then_some((u32::from(w), u32::from(h)));
+ }
+ _ => i += 2 + usize::from(u16::from_be_bytes([j[i + 2], j[i + 3]])),
+ }
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A JPEG that is only the markers `jpeg_size` reads: SOI, an APP0 to skip, SOF0, SOS
+ pub(crate) fn fake_jpeg(w: u16, h: u16, fill: u8) -> Vec<u8> {
+ let mut j = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, fill, fill];
+ j.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
+ j.extend_from_slice(&h.to_be_bytes());
+ j.extend_from_slice(&w.to_be_bytes());
+ j.extend_from_slice(&[3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1]);
+ j.extend_from_slice(&[0xFF, 0xDA, 0x00, 0x02, 0xFF, 0xD9]);
+ j
+ }
+
+ #[test]
+ fn size_comes_from_the_frame_header() {
+ assert_eq!(jpeg_size(&fake_jpeg(968, 2097, 0)), Some((968, 2097)));
+ assert_eq!(jpeg_size(&fake_jpeg(2097, 968, 0)), Some((2097, 968)));
+ assert_eq!(jpeg_size(b"not a jpeg"), None);
+ assert_eq!(jpeg_size(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None);
+ }
+
+ /// The stream as WDA sends it: response head, then parts with a blank line before each boundary
+ #[tokio::test]
+ async fn frames_are_cut_by_their_length() {
+ let (a, b) = (fake_jpeg(10, 20, 1), fake_jpeg(10, 20, 2));
+ let mut s = b"HTTP/1.0 200 OK\r\nServer: WDA MJPEG Server\r\nContent-Type: multipart/x-mixed-replace; boundary=--BoundaryString\r\n\r\n".to_vec();
+ for j in [&a, &b] {
+ s.extend_from_slice(
+ format!("--BoundaryString\r\nContent-type: image/jpeg\r\nContent-Length: {}\r\n\r\n", j.len())
+ .as_bytes(),
+ );
+ s.extend_from_slice(j);
+ s.extend_from_slice(b"\r\n\r\n");
+ }
+ let mut f = Frames::new(&s[..]);
+ assert_eq!(f.next().await.unwrap(), Some(a));
+ assert_eq!(f.next().await.unwrap(), Some(b));
+ assert_eq!(f.next().await.unwrap(), None);
+ }
+
+ #[tokio::test]
+ async fn refuses_an_error_answer_and_parts_without_length() {
+ assert!(Frames::new(&b"HTTP/1.0 404 Not Found\r\n\r\n"[..]).next().await.is_err());
+ let s = b"HTTP/1.0 200 OK\r\n\r\n--x\r\nContent-Type: image/jpeg\r\n\r\nabc";
+ assert!(Frames::new(&s[..]).next().await.is_err());
+ }
+
+ #[test]
+ fn part_is_what_mpjpeg_reads() {
+ let p = part(b"JPEG");
+ assert_eq!(p, b"--ictl\r\nContent-Type: image/jpeg\r\nContent-Length: 4\r\n\r\nJPEG\r\n");
+ }
+}
diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs
new file mode 100644
index 0000000..299e7e0
--- /dev/null
+++ b/apps/iphone-control/src/video/mod.rs
@@ -0,0 +1,623 @@
+//! H.264 for the viewer's live picture (`GET /video`). WDA's MJPEG stream is 4 to 10 MB/s, too much for a tunnel
+//! over the internet; H.264 of the same frames is about 1/15 of that at the same frame rate and, to the eye, the
+//! same picture.
+//!
+//! Per connection: WDA's MJPEG over usbmuxd → frames equal to the previous one dropped (WDA repeats a still screen
+//! about 25 times a second) → the encoder (on macOS VideoToolbox inside this program, `vt.rs`; else ffmpeg
+//! ([`ffmpeg`]: hardware encoder first, `mpjpeg` in, FLV out)) → the page as
+//! messages of one type byte, a 4-byte big-endian length and the payload:
+//!
+//! - `0` JSON: `codec` (WebCodecs string), `description` (the `avcC`, hex), `width`/`height` (the frames' size),
+//! `encoder` (its short name) and `stream` (the id for `POST /api/video/ack`). Before the first frame, and again whenever the encoder restarts (rotation, falling
+//! behind)
+//! - `1` a keyframe, `2` any other frame, in the `avcC` format
+//!
+//! Falling behind: buffers between here and the page (the kernel's, an SSH tunnel's window of a few MB) take in
+//! frames far faster than a slow link delivers them, so how full the queue here is says nothing; with a 30 KB/s
+//! reader the picture was 40 s late. The page therefore reports how many bytes it has read (`POST /api/video/ack`,
+//! every 100 ms while frames arrive, [`Acks`]). While the page is behind ([`Flow::behind`]: the oldest frame it
+//! hasn't confirmed is older than the usual round trip plus [`SLACK`], or more is on the way than the link delivers
+//! in that time), no new picture goes to the encoder; once the page has caught up, only the newest one does. Every encoded frame is still sent, so the chain of frames stays whole and no keyframe is needed (one would
+//! take seconds on such a link): the frame rate drops to what the link carries and the picture stays about that
+//! close to live. A page that never reports (an older one) only gets the queue check below.
+//!
+//! The queue to the page full (a page that doesn't report): frames are dropped until a keyframe, and a new encoder
+//! session starts for one.
+
+pub mod device;
+mod ffmpeg;
+mod flv;
+mod mjpeg;
+mod sps;
+#[cfg(target_os = "macos")]
+mod vt;
+
+use std::collections::VecDeque;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde_json::json;
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio::sync::{mpsc, watch};
+
+pub use ffmpeg::Encoders;
+use flv::Packet;
+
+/// `IPHONE_CONTROL_VIEWER_CODEC` allows the phone's own screen video ([`device`]): `auto` (the default) or `device`
+pub fn device_allowed() -> bool {
+ ictl_daemon::config::env("IPHONE_CONTROL_VIEWER_CODEC")
+ .is_none_or(|v| v.eq_ignore_ascii_case("auto") || v.eq_ignore_ascii_case("device"))
+}
+
+/// Messages waiting for the page; more means it is falling behind
+const QUEUE: usize = 8;
+/// Restarting for a keyframe at most this often (a link too slow for the picture would otherwise restart all the
+/// time)
+const RESTART_EVERY: Duration = Duration::from_secs(1);
+/// An encoder that keeps failing on a connection is given up for the next one after this many tries
+const TRIES: usize = 3;
+/// How much later than usual the page may confirm a frame before frames are skipped
+const SLACK: Duration = Duration::from_millis(300);
+/// The usual round trip is the shortest seen over this long
+const BASE_WINDOW: Duration = Duration::from_secs(10);
+/// The link's speed is the fastest delivery seen over this long
+const RATE_WINDOW: Duration = Duration::from_secs(5);
+/// No report for this long (one got lost, the page is gone or its timers are throttled): stop waiting for them
+const REPORTS_STALE: Duration = Duration::from_secs(3);
+
+/// Pages' reports of how much of each picture stream they have read, by stream id
+#[derive(Default)]
+pub struct Acks(std::sync::Mutex<std::collections::HashMap<String, watch::Sender<u64>>>);
+
+impl Acks {
+ /// The page read `bytes` of stream `id` so far. False for a stream that has ended
+ pub fn report(&self, id: &str, bytes: u64) -> bool {
+ let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
+ map.get(id).is_some_and(|tx| {
+ tx.send_replace(bytes);
+ true
+ })
+ }
+
+ fn register(self: &Arc<Self>) -> (AckGuard, watch::Receiver<u64>) {
+ let id = uuid::Uuid::new_v4().simple().to_string();
+ let (tx, rx) = watch::channel(0);
+ self.0.lock().unwrap_or_else(|p| p.into_inner()).insert(id.clone(), tx);
+ (AckGuard { acks: self.clone(), id }, rx)
+ }
+}
+
+struct AckGuard {
+ acks: Arc<Acks>,
+ id: String,
+}
+
+impl Drop for AckGuard {
+ fn drop(&mut self) {
+ self.acks.0.lock().unwrap_or_else(|p| p.into_inner()).remove(&self.id);
+ }
+}
+
+/// What was sent to the page and what it confirmed
+#[derive(Default)]
+struct Flow {
+ sent: u64,
+ /// End offset and time of each message not confirmed yet
+ in_flight: VecDeque<(u64, Instant)>,
+ /// Bytes confirmed so far, and when the last report with more of them came
+ acked: u64,
+ last_report: Option<Instant>,
+ /// When the last report of any kind came
+ heard: Option<Instant>,
+ /// Round trips measured over [`BASE_WINDOW`]
+ trips: VecDeque<(Instant, Duration)>,
+ /// Delivery rates (bytes per second between two reports) over [`RATE_WINDOW`]
+ rates: VecDeque<(Instant, f64)>,
+ /// The page reports at all
+ reports: bool,
+}
+
+impl Flow {
+ fn sent(&mut self, len: usize, now: Instant) {
+ self.sent += len as u64;
+ self.in_flight.push_back((self.sent, now));
+ }
+
+ fn ack(&mut self, bytes: u64, now: Instant) {
+ self.reports = true;
+ self.heard = Some(now);
+ if bytes > self.acked {
+ if let Some(t) = self.last_report {
+ let dt = now.saturating_duration_since(t).as_secs_f64();
+ if dt > 0.01 {
+ self.rates.push_back((now, (bytes - self.acked) as f64 / dt));
+ }
+ }
+ self.acked = bytes;
+ self.last_report = Some(now);
+ }
+ while self.rates.front().is_some_and(|(t, _)| now.saturating_duration_since(*t) > RATE_WINDOW) {
+ self.rates.pop_front();
+ }
+ let mut last = None;
+ while let Some(&(end, at)) = self.in_flight.front()
+ && end <= bytes
+ {
+ last = Some(at);
+ self.in_flight.pop_front();
+ }
+ if let Some(at) = last {
+ self.trips.push_back((now, now.saturating_duration_since(at)));
+ }
+ while self.trips.front().is_some_and(|(t, _)| now.saturating_duration_since(*t) > BASE_WINDOW) {
+ self.trips.pop_front();
+ }
+ }
+
+ /// The page is behind: its oldest unconfirmed message is older than a usual round trip plus [`SLACK`], or more
+ /// is on the way than the link delivers in that time (without this, the pictures arriving in the first [`SLACK`]
+ /// after catching up would all go out at once). The rate is what was delivered, which on a fast link is only
+ /// what was sent; with the round trip in the allowance the normal amount on the way (rate × round trip) stays
+ /// under it, so the limit doesn't feed on itself. Nothing on the way is never behind: one frame always goes
+ fn behind(&self, now: Instant) -> bool {
+ let Some((_, oldest)) = self.in_flight.front() else { return false };
+ if !self.reports || self.heard.is_some_and(|t| now.saturating_duration_since(t) > REPORTS_STALE) {
+ return false;
+ }
+ let allowed = self.trips.iter().map(|(_, d)| *d).min().unwrap_or_default() + SLACK;
+ if now.saturating_duration_since(*oldest) > allowed {
+ return true;
+ }
+ let rate = self.rates.iter().map(|(_, r)| *r).fold(0.0, f64::max);
+ rate > 0.0 && (self.sent - self.acked) as f64 > rate * allowed.as_secs_f64()
+ }
+}
+
+fn message(kind: u8, payload: &[u8]) -> Vec<u8> {
+ let mut m = Vec::with_capacity(5 + payload.len());
+ m.push(kind);
+ m.extend_from_slice(&(payload.len() as u32).to_be_bytes());
+ m.extend_from_slice(payload);
+ m
+}
+
+fn config_message(avcc: &[u8], size: (u32, u32), encoder: &str, stream: &str) -> Option<Vec<u8>> {
+ // so the browser's decoder shows each frame at once instead of keeping a few (see `sps.rs`)
+ let avcc = sps::low_delay(avcc).unwrap_or_else(|| avcc.to_vec());
+ let avcc = avcc.as_slice();
+ let hex: String = avcc.iter().map(|b| format!("{b:02x}")).collect();
+ let v = json!({
+ "stream": stream,
+ "codec": flv::codec_string(avcc)?,
+ "description": hex,
+ "width": size.0,
+ "height": size.1,
+ "encoder": encoder,
+ });
+ Some(message(0, v.to_string().as_bytes()))
+}
+
+/// 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>,
+ acks: Arc<Acks>,
+ src: impl AsyncRead + Unpin + Send + 'static,
+ client: TcpStream,
+) {
+ let (mut client_rd, mut client_wr) = client.into_split();
+ let (ack_guard, mut acked) = acks.register();
+ let mut flow = Flow::default();
+
+ // the phone's frames, repeated ones dropped; the newest wins if encoding falls behind
+ let (frame_tx, mut frames) = watch::channel::<Option<Arc<Vec<u8>>>>(None);
+ let reader = tokio::spawn(async move {
+ let mut f = mjpeg::Frames::new(src);
+ let mut last: Option<Arc<Vec<u8>>> = None;
+ loop {
+ match f.next().await {
+ Ok(Some(j)) => {
+ if last.as_ref().is_some_and(|l| **l == j) {
+ continue;
+ }
+ let j = Arc::new(j);
+ last = Some(j.clone());
+ if frame_tx.send(Some(j)).is_err() {
+ return;
+ }
+ }
+ Ok(None) => return,
+ Err(e) => {
+ tracing::debug!("MJPEG stream: {e}");
+ return;
+ }
+ }
+ }
+ });
+ let _reader = AbortOnDrop(reader);
+
+ // the page reads nothing after the request: a read that ends means it went away (a still screen sends nothing,
+ // so a failed write wouldn't notice)
+ let (gone_tx, mut gone) = tokio::sync::oneshot::channel::<()>();
+ let watcher = tokio::spawn(async move {
+ let mut b = [0u8; 256];
+ while matches!(client_rd.read(&mut b).await, Ok(n) if n > 0) {}
+ let _ = gone_tx.send(());
+ });
+ let _watcher = AbortOnDrop(watcher);
+
+ let (out_tx, mut out_rx) = mpsc::channel::<Vec<u8>>(QUEUE);
+ let writer = tokio::spawn(async move {
+ while let Some(m) = out_rx.recv().await {
+ if client_wr.write_all(&m).await.is_err() {
+ return;
+ }
+ }
+ });
+ let _writer = AbortOnDrop(writer);
+
+ let mut session: Option<ffmpeg::Session> = None;
+ let mut last: Option<Arc<Vec<u8>>> = None;
+ // frames out of the current session; one that fails before any is the encoder's fault
+ let mut produced = false;
+ let mut failures = 0;
+ // dropping frames until a keyframe (the queue to the page was full)
+ let mut need_key = false;
+ // the page is behind: the newest picture (`last`) waits instead of going to the encoder
+ let mut waiting = false;
+ let mut restarted = Instant::now();
+ let mut tick = tokio::time::interval(Duration::from_millis(200));
+
+ loop {
+ let ev = tokio::select! {
+ _ = &mut gone => return,
+ r = frames.changed() => match r {
+ Ok(()) => Ev::Frame(frames.borrow_and_update().clone()),
+ // the phone's stream ended (unplugged, WDA restarted): the page reconnects
+ Err(_) => return,
+ },
+ p = next_packet(&mut session) => Ev::Packet(p),
+ r = acked.changed() => match r {
+ Ok(()) => Ev::Acked(*acked.borrow_and_update()),
+ Err(_) => return,
+ },
+ _ = tick.tick() => Ev::Tick,
+ };
+ match ev {
+ Ev::Frame(None) => {}
+ Ev::Frame(Some(j)) => {
+ 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 };
+ session = Some(s);
+ produced = false;
+ }
+ last = Some(j);
+ if flow.behind(Instant::now()) {
+ waiting = true;
+ } else if let (Some(s), Some(j)) = (&session, &last) {
+ s.push(j.clone());
+ }
+ }
+ Ev::Packet(Some(Ok(Packet::Config(avcc)))) => {
+ let (Some(s), Some(label)) = (&session, enc.label()) else { continue };
+ let Some(m) = config_message(&avcc, s.size, label, &ack_guard.id) else { continue };
+ flow.sent(m.len(), Instant::now());
+ // small and needed before any frame: wait for room
+ if out_tx.send(m).await.is_err() {
+ return;
+ }
+ }
+ Ev::Packet(Some(Ok(Packet::Frame { key, data }))) => {
+ produced = true;
+ if need_key && !key {
+ continue;
+ }
+ need_key = false;
+ let m = message(if key { 1 } else { 2 }, &data);
+ let len = m.len();
+ match out_tx.try_send(m) {
+ Ok(()) => flow.sent(len, Instant::now()),
+ Err(mpsc::error::TrySendError::Full(_)) => need_key = true,
+ Err(mpsc::error::TrySendError::Closed(_)) => return,
+ }
+ }
+ // ffmpeg ended or sent something unreadable
+ Ev::Packet(end) => {
+ let Some(s) = session.take() else { continue };
+ let why = match end {
+ Some(Err(e)) => e,
+ _ => s.error(),
+ };
+ tracing::debug!("picture encoder ended: {why}");
+ failures += 1;
+ // never got a frame out (this size, these frames), or keeps failing: try the next encoder
+ if (!produced || failures >= TRIES) && !enc.give_up(s.index).await {
+ return;
+ }
+ if !produced || failures >= TRIES {
+ failures = 0;
+ }
+ let Some(j) = &last else { continue };
+ let Some(size) = mjpeg::jpeg_size(j) else { continue };
+ let Some(s) = start(&enc, size) else { return };
+ s.push(j.clone());
+ session = Some(s);
+ produced = false;
+ }
+ Ev::Acked(bytes) => {
+ flow.ack(bytes, Instant::now());
+ // caught up: the newest picture, encoded against the last one sent
+ if waiting && !flow.behind(Instant::now()) {
+ waiting = false;
+ if let (Some(s), Some(j)) = (&session, &last) {
+ s.push(j.clone());
+ }
+ }
+ }
+ Ev::Tick => {
+ // the queue was full: once it has drained, a new session gives a keyframe now instead of at the next
+ // scheduled one
+ 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 };
+ s.push(j.clone());
+ session = Some(s);
+ produced = false;
+ restarted = Instant::now();
+ }
+ }
+ }
+ }
+}
+
+enum Ev {
+ Frame(Option<Arc<Vec<u8>>>),
+ Packet(Option<Result<Packet, String>>),
+ Acked(u64),
+ Tick,
+}
+
+fn start(enc: &Encoders, size: (u32, u32)) -> Option<ffmpeg::Session> {
+ enc.start(size.0, size.1).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
+/// repeats a still screen about 25 times a second, 4 to 10 MB/s for nothing), and only the newest frame when the
+/// page reads slower than they come, so a slow link skips frames instead of falling behind more and more. Each frame
+/// is followed right away by the next boundary and the next part's headers: Chrome shows a part only once it has
+/// those (seen on Chrome 14x), and on a still screen no next frame would come. So the parts carry no
+/// `Content-Length` (the next one isn't known yet); browsers cut at the boundary anyway. The HTTP response head is
+/// written here
+pub async fn serve_mjpeg(src: impl AsyncRead + Unpin + Send + 'static, mut client: TcpStream) {
+ let (tx, mut rx) = watch::channel::<Option<Arc<Vec<u8>>>>(None);
+ let reader = tokio::spawn(async move {
+ let mut f = mjpeg::Frames::new(src);
+ let mut last: Option<Vec<u8>> = None;
+ while let Ok(Some(j)) = f.next().await {
+ if last.as_ref() == Some(&j) {
+ continue;
+ }
+ last = Some(j.clone());
+ if tx.send(Some(Arc::new(j))).is_err() {
+ return;
+ }
+ }
+ });
+ let _reader = AbortOnDrop(reader);
+ const NEXT: &[u8] = b"\r\n--ictl\r\nContent-Type: image/jpeg\r\n\r\n";
+ let head =
+ b"HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace; boundary=ictl\r\nCache-Control: no-store\r\n\
+ X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n";
+ // the first part's boundary and headers, without the line break that ends a part
+ if client.write_all(head).await.is_err() || client.write_all(&NEXT[2..]).await.is_err() {
+ return;
+ }
+ while rx.changed().await.is_ok() {
+ let Some(j) = rx.borrow_and_update().clone() else { continue };
+ let mut part = Vec::with_capacity(j.len() + NEXT.len());
+ part.extend_from_slice(&j);
+ part.extend_from_slice(NEXT);
+ if client.write_all(&part).await.is_err() {
+ return;
+ }
+ }
+}
+
+struct AbortOnDrop(tokio::task::JoinHandle<()>);
+
+impl Drop for AbortOnDrop {
+ fn drop(&mut self) {
+ self.0.abort();
+ }
+}
+
+async fn next_packet(s: &mut Option<ffmpeg::Session>) -> Option<Result<Packet, String>> {
+ match s {
+ Some(s) => s.next().await,
+ None => std::future::pending().await,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A page that confirms in time is never behind; one whose confirmations stop coming is, once the oldest
+ /// unconfirmed message is older than the usual round trip plus the slack
+ #[test]
+ fn behind_means_late_beyond_the_usual_round_trip() {
+ let t0 = Instant::now();
+ let ms = |n| t0 + Duration::from_millis(n);
+ let mut f = Flow::default();
+ f.sent(100, ms(0));
+ assert!(!f.behind(ms(5000)), "no reports yet: an older page, never throttled");
+ f.ack(100, ms(50));
+ f.sent(100, ms(100));
+ f.sent(100, ms(140));
+ f.ack(300, ms(190));
+ assert!(!f.behind(ms(1000)), "everything confirmed");
+ f.sent(100, ms(1000));
+ assert!(!f.behind(ms(1340)), "within 50 ms round trip + 300 ms");
+ assert!(f.behind(ms(1360)));
+ f.ack(400, ms(1400));
+ assert!(!f.behind(ms(1400)));
+ // reports stop coming (one got lost): no waiting for them forever
+ f.sent(100, ms(1500));
+ assert!(f.behind(ms(2000)));
+ assert!(!f.behind(ms(4500)), "nothing heard for over 3 s");
+ }
+
+ /// On a link that delivers 20 KB/s, a second 20 KB frame waits for the first: 300 ms of that link is 6 KB. On a
+ /// link with a 200 ms round trip that keeps up, frames keep flowing
+ #[test]
+ fn no_more_on_the_way_than_the_link_carries_in_the_slack() {
+ let t0 = Instant::now();
+ let ms = |n| t0 + Duration::from_millis(n);
+ let mut f = Flow::default();
+ f.sent(20_000, ms(0));
+ f.ack(2_000, ms(100));
+ f.ack(4_000, ms(200));
+ assert!(f.behind(ms(250)), "16 KB still on the way, the link does 20 KB/s");
+ f.ack(20_000, ms(1000));
+ assert!(!f.behind(ms(1000)), "all delivered: the next frame goes");
+ // 20 KB every 40 ms (500 KB/s) over a 200 ms round trip, reported every 100 ms as the page does: about
+ // 120 KB is always on the way, and that is no reason to wait
+ let mut g = Flow::default();
+ for i in 0..100u64 {
+ let t = i * 40;
+ if t >= 200 && t % 100 == 0 {
+ // what was sent up to 200 ms ago has arrived
+ g.ack(((t - 200) / 40 + 1) * 20_000, ms(t));
+ }
+ assert!(!g.behind(ms(t)), "at {t} ms");
+ g.sent(20_000, ms(t));
+ }
+ }
+
+ /// A page reading 20 KB/s while the picture changes 15 times a second (several times what it can take, like a
+ /// slow link behind an SSH tunnel) stays close to live: once the picture stops changing, its last frame arrives
+ /// within a couple of seconds. Without the reports it was 40 s on the phone. Needs ffmpeg and takes about 15 s:
+ /// `cargo test -p iphone-control slow_page -- --ignored --nocapture`
+ #[tokio::test]
+ #[ignore]
+ async fn slow_page_stays_close_to_live() {
+ use tokio::io::AsyncWriteExt;
+ let enc = match Encoders::detect().await {
+ Ok(e) => e,
+ Err(m) => panic!("no H.264 encoder: {m}"),
+ };
+ // 90 different frames from ffmpeg's test source, cut with the same reader the phone's stream goes through;
+ // without ffmpeg (macOS) a scrolling test picture from VideoToolbox's JPEG encoder
+ let out = tokio::process::Command::new("ffmpeg")
+ .args(["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=s=480x1040:r=15"])
+ .args(["-frames:v", "90", "-c:v", "mjpeg", "-pix_fmt", "yuvj420p", "-q:v", "3", "-f", "mpjpeg", "pipe:1"])
+ .output()
+ .await;
+ let mut frames = Vec::new();
+ if let Ok(out) = out {
+ let mut whole = b"HTTP/1.0 200 OK\r\n\r\n".to_vec();
+ whole.extend(out.stdout);
+ let mut f = mjpeg::Frames::new(&whole[..]);
+ while let Some(j) = f.next().await.unwrap() {
+ frames.push(j);
+ }
+ } else {
+ #[cfg(target_os = "macos")]
+ for n in 0..90 {
+ frames.push(vt::sample_jpeg(480, 1040, n).unwrap());
+ }
+ }
+ assert_eq!(frames.len(), 90);
+
+ // the phone: those frames at 15 a second, then a still screen (the stream stays open)
+ let (mut phone, src) = tokio::io::duplex(1 << 20);
+ let feeder = tokio::spawn(async move {
+ phone.write_all(b"HTTP/1.0 200 OK\r\nContent-Type: multipart/x-mixed-replace\r\n\r\n").await.unwrap();
+ for j in &frames {
+ let head =
+ format!("--BoundaryString\r\nContent-type: image/jpeg\r\nContent-Length: {}\r\n\r\n", j.len());
+ phone.write_all(head.as_bytes()).await.unwrap();
+ phone.write_all(j).await.unwrap();
+ phone.write_all(b"\r\n").await.unwrap();
+ tokio::time::sleep(Duration::from_millis(66)).await;
+ }
+ (Instant::now(), phone)
+ });
+
+ // the page, over a real TCP connection, reporting what it read every 100 ms like viewer.html
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut page = 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)));
+ 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());
+ let started = Instant::now();
+ loop {
+ let mut chunk = [0u8; 2048];
+ let n = match tokio::time::timeout(Duration::from_secs(4), page.read(&mut chunk)).await {
+ Ok(Ok(n)) if n > 0 => n,
+ Ok(_) => panic!("stream ended"),
+ // nothing for 4 s: done once the picture has stopped
+ Err(_) if feeder.is_finished() => break,
+ Err(_) => continue,
+ };
+ total += n as u64;
+ buf.extend_from_slice(&chunk[..n]);
+ while buf.len() >= 5 {
+ let len = u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]) as usize;
+ if buf.len() < 5 + len {
+ break;
+ }
+ if buf[0] == 0 {
+ let v: serde_json::Value = serde_json::from_slice(&buf[5..5 + len]).unwrap();
+ stream = v["stream"].as_str().map(str::to_owned);
+ } else {
+ frames_in += 1;
+ last_frame = Some(Instant::now());
+ }
+ buf.drain(..5 + len);
+ }
+ if let Some(id) = &stream
+ && reported.elapsed() >= Duration::from_millis(100)
+ {
+ acks.report(id, total);
+ reported = Instant::now();
+ }
+ tokio::time::sleep(Duration::from_secs_f64(n as f64 / RATE)).await;
+ assert!(started.elapsed() < Duration::from_secs(60), "took too long");
+ }
+ let (stopped, _phone) = feeder.await.unwrap();
+ let late = last_frame.unwrap().saturating_duration_since(stopped);
+ eprintln!("{frames_in} frames, {total} bytes; the last one arrived {late:?} after the picture stopped");
+ assert!(late < Duration::from_secs(3), "fell {late:?} behind");
+ }
+
+ #[test]
+ fn messages_have_type_and_length() {
+ assert_eq!(message(2, b"abc"), [2, 0, 0, 0, 3, b'a', b'b', b'c']);
+ let m = config_message(&[1, 0x64, 0, 0x28, 0xFF], (968, 2097), "VAAPI", "s1").unwrap();
+ let v: serde_json::Value = serde_json::from_slice(&m[5..]).unwrap();
+ assert_eq!(v["codec"], "avc1.640028");
+ assert_eq!(v["description"], "01640028ff");
+ assert_eq!((v["width"].as_u64(), v["height"].as_u64()), (Some(968), Some(2097)));
+ assert_eq!(v["stream"], "s1");
+ }
+
+ #[tokio::test]
+ async fn reports_reach_their_stream_only() {
+ let acks = Arc::new(Acks::default());
+ let (g, mut rx) = acks.register();
+ assert!(acks.report(&g.id, 42));
+ rx.changed().await.unwrap();
+ assert_eq!(*rx.borrow(), 42);
+ assert!(!acks.report("other", 1));
+ let id = g.id.clone();
+ drop(g);
+ assert!(!acks.report(&id, 43), "gone with the stream");
+ }
+}
diff --git a/apps/iphone-control/src/video/sps.rs b/apps/iphone-control/src/video/sps.rs
new file mode 100644
index 0000000..e6e8094
--- /dev/null
+++ b/apps/iphone-control/src/video/sps.rs
@@ -0,0 +1,396 @@
+//! Telling the page's decoder that frames are never reordered, so it shows each one as soon as it is decoded.
+//!
+//! An SPS without the VUI's bitstream restriction (`max_num_reorder_frames`) leaves a decoder to assume the worst:
+//! as many frames reordered as the level's picture buffer holds. Chrome's hardware decoder on macOS then keeps that
+//! many frames before it outputs one (4 for the phone's 990×2151 at level 4.2, measured), `optimizeForLatency` or not:
+//! the picture runs 4 frames late, and when the screen stops changing no frame follows to push the last 4 out, so the
+//! page stays on a frame from the middle of the last movement. VideoToolbox writes no VUI at all.
+//!
+//! [`low_delay`] rewrites the SPS in the `avcC` with the restriction saying 0 frames are reordered (true: B-frames
+//! are off everywhere) and the buffer is the reference frames only. Only the `avcC` matters: the frames carry no SPS.
+//! An SPS that already says 0 is left as it is.
+
+/// The `avcC` with every SPS saying no frame is reordered; `None` when it can't be read (then send it as it is)
+pub fn low_delay(avcc: &[u8]) -> Option<Vec<u8>> {
+ let n_sps = usize::from(*avcc.get(5)? & 0x1f);
+ let mut out = avcc.get(..6)?.to_vec();
+ let mut i = 6;
+ for _ in 0..n_sps {
+ let len = usize::from(u16::from_be_bytes([*avcc.get(i)?, *avcc.get(i + 1)?]));
+ let sps = avcc.get(i + 2..i + 2 + len)?;
+ let new = sps_low_delay(sps)?;
+ out.extend_from_slice(&u16::try_from(new.len()).ok()?.to_be_bytes());
+ out.extend_from_slice(&new);
+ i += 2 + len;
+ }
+ // the PPS and, for High profiles, the extension: unchanged
+ out.extend_from_slice(avcc.get(i..)?);
+ Some(out)
+}
+
+/// What [`read`] found in an SPS
+#[derive(Debug, PartialEq)]
+struct Sps {
+ max_num_ref_frames: u32,
+ /// Bit position (in the RBSP) of the field to rewrite from: `bitstream_restriction_flag`, or
+ /// `vui_parameters_present_flag` when there is no VUI
+ cut: usize,
+ vui: bool,
+ /// `max_num_reorder_frames`, when the VUI has the restriction
+ reorder: Option<u32>,
+}
+
+fn sps_low_delay(nal: &[u8]) -> Option<Vec<u8>> {
+ let (&header, ebsp) = nal.split_first()?;
+ if header & 0x1f != 7 {
+ return None;
+ }
+ let rbsp = unescape(ebsp);
+ let s = read(&rbsp)?;
+ if s.reorder == Some(0) {
+ return Some(nal.to_vec());
+ }
+ let mut w = Writer::default();
+ let mut r = Reader::new(&rbsp);
+ for _ in 0..s.cut {
+ w.bit(r.u(1)?);
+ }
+ if !s.vui {
+ // vui_parameters_present_flag, then no aspect ratio, overscan, signal type, chroma location, timing, NAL or
+ // VCL HRD, picture structure
+ w.bit(1);
+ for _ in 0..8 {
+ w.bit(0);
+ }
+ }
+ w.bit(1); // bitstream_restriction_flag
+ w.bit(1); // motion_vectors_over_pic_boundaries_flag
+ w.ue(2); // max_bytes_per_pic_denom (the default)
+ w.ue(1); // max_bits_per_mb_denom (the default)
+ w.ue(16); // log2_max_mv_length_horizontal (the default)
+ w.ue(16); // log2_max_mv_length_vertical
+ w.ue(0); // max_num_reorder_frames
+ w.ue(s.max_num_ref_frames.max(1)); // max_dec_frame_buffering
+ w.bit(1); // rbsp_stop_one_bit
+ let mut out = vec![header];
+ out.extend(escape(&w.finish()));
+ Some(out)
+}
+
+/// Reads an SPS RBSP (after the NAL header) up to the VUI's bitstream restriction
+fn read(rbsp: &[u8]) -> Option<Sps> {
+ let mut r = Reader::new(rbsp);
+ let profile = r.u(8)?;
+ r.u(8)?;
+ r.u(8)?;
+ r.ue()?;
+ if matches!(profile, 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135) {
+ let chroma = r.ue()?;
+ if chroma == 3 {
+ r.u(1)?;
+ }
+ r.ue()?;
+ r.ue()?;
+ r.u(1)?;
+ if r.u(1)? == 1 {
+ for list in 0..if chroma == 3 { 12 } else { 8 } {
+ if r.u(1)? == 1 {
+ let (mut last, mut next) = (8i64, 8i64);
+ for _ in 0..if list < 6 { 16 } else { 64 } {
+ if next != 0 {
+ next = (last + r.se()? + 256) % 256;
+ }
+ if next != 0 {
+ last = next;
+ }
+ }
+ }
+ }
+ }
+ }
+ r.ue()?;
+ match r.ue()? {
+ 0 => {
+ r.ue()?;
+ }
+ 1 => {
+ r.u(1)?;
+ r.se()?;
+ r.se()?;
+ for _ in 0..r.ue()? {
+ r.se()?;
+ }
+ }
+ _ => {}
+ }
+ let max_num_ref_frames = r.ue()?;
+ r.u(1)?;
+ r.ue()?;
+ r.ue()?;
+ if r.u(1)? == 0 {
+ r.u(1)?;
+ }
+ r.u(1)?;
+ if r.u(1)? == 1 {
+ for _ in 0..4 {
+ r.ue()?;
+ }
+ }
+ let at_vui = r.pos;
+ if r.u(1)? == 0 {
+ return Some(Sps { max_num_ref_frames, cut: at_vui, vui: false, reorder: None });
+ }
+ if r.u(1)? == 1 && r.u(8)? == 255 {
+ r.u(32)?;
+ }
+ if r.u(1)? == 1 {
+ r.u(1)?;
+ }
+ if r.u(1)? == 1 {
+ r.u(4)?;
+ if r.u(1)? == 1 {
+ r.u(24)?;
+ }
+ }
+ if r.u(1)? == 1 {
+ r.ue()?;
+ r.ue()?;
+ }
+ if r.u(1)? == 1 {
+ r.u(32)?;
+ r.u(32)?;
+ r.u(1)?;
+ }
+ let hrd = |r: &mut Reader| -> Option<()> {
+ let count = r.ue()? + 1;
+ r.u(8)?;
+ for _ in 0..count {
+ r.ue()?;
+ r.ue()?;
+ r.u(1)?;
+ }
+ r.u(20)?;
+ Some(())
+ };
+ let nal_hrd = r.u(1)? == 1;
+ if nal_hrd {
+ hrd(&mut r)?;
+ }
+ let vcl_hrd = r.u(1)? == 1;
+ if vcl_hrd {
+ hrd(&mut r)?;
+ }
+ if nal_hrd || vcl_hrd {
+ r.u(1)?;
+ }
+ r.u(1)?;
+ let cut = r.pos;
+ let reorder = if r.u(1)? == 1 {
+ r.u(1)?;
+ for _ in 0..4 {
+ r.ue()?;
+ }
+ Some(r.ue()?)
+ } else {
+ None
+ };
+ Some(Sps { max_num_ref_frames, cut, vui: true, reorder })
+}
+
+/// Emulation prevention removed (`00 00 03` → `00 00`)
+fn unescape(ebsp: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(ebsp.len());
+ let mut zeros = 0;
+ for &b in ebsp {
+ if zeros >= 2 && b == 3 {
+ zeros = 0;
+ continue;
+ }
+ zeros = if b == 0 { zeros + 1 } else { 0 };
+ out.push(b);
+ }
+ out
+}
+
+/// Emulation prevention added: a `03` after two zeros wherever the next byte is 0 to 3
+fn escape(rbsp: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(rbsp.len() + 4);
+ let mut zeros = 0;
+ for &b in rbsp {
+ if zeros >= 2 && b <= 3 {
+ out.push(3);
+ zeros = 0;
+ }
+ zeros = if b == 0 { zeros + 1 } else { 0 };
+ out.push(b);
+ }
+ out
+}
+
+struct Reader<'a> {
+ data: &'a [u8],
+ pos: usize,
+}
+
+impl<'a> Reader<'a> {
+ fn new(data: &'a [u8]) -> Self {
+ Self { data, pos: 0 }
+ }
+
+ fn u(&mut self, n: u32) -> Option<u32> {
+ let mut v = 0u32;
+ for _ in 0..n {
+ let byte = *self.data.get(self.pos / 8)?;
+ v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1);
+ self.pos += 1;
+ }
+ Some(v)
+ }
+
+ fn ue(&mut self) -> Option<u32> {
+ let mut zeros = 0;
+ while self.u(1)? == 0 {
+ zeros += 1;
+ if zeros > 31 {
+ return None;
+ }
+ }
+ Some((1u32 << zeros) - 1 + self.u(zeros)?)
+ }
+
+ fn se(&mut self) -> Option<i64> {
+ let k = i64::from(self.ue()?);
+ Some(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) })
+ }
+}
+
+#[derive(Default)]
+struct Writer {
+ bytes: Vec<u8>,
+ bits: usize,
+}
+
+impl Writer {
+ fn bit(&mut self, b: u32) {
+ if self.bits.is_multiple_of(8) {
+ self.bytes.push(0);
+ }
+ if b != 0 {
+ *self.bytes.last_mut().expect("pushed above") |= 0x80 >> (self.bits % 8);
+ }
+ self.bits += 1;
+ }
+
+ fn ue(&mut self, v: u32) {
+ let x = u64::from(v) + 1;
+ let len = 64 - x.leading_zeros();
+ for _ in 1..len {
+ self.bit(0);
+ }
+ for i in (0..len).rev() {
+ self.bit(((x >> i) & 1) as u32);
+ }
+ }
+
+ /// The bytes, zero-padded to a whole byte (after the stop bit the caller wrote)
+ fn finish(self) -> Vec<u8> {
+ self.bytes
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hex(s: &str) -> Vec<u8> {
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
+ }
+
+ /// The `avcC` VideoToolbox gave for the phone's 990×2151 picture (iPhone 18 Pro Max, macOS 27): High profile,
+ /// level 4.2, one reference frame, no VUI. After the rewrite the SPS says no frame is reordered, everything
+ /// else (the fields before, the PPS, the High-profile extension) is unchanged, and doing it again changes nothing
+ #[test]
+ fn videotoolbox_sps_gets_no_reordering() {
+ let avcc = hex("0164002affe1000c2764002aac5680f8043fa95001000428ee3cb0fdf8f800");
+ let sps = &avcc[8..20];
+ let before = read(&unescape(&sps[1..])).unwrap();
+ assert_eq!(before, Sps { max_num_ref_frames: 1, cut: before.cut, vui: false, reorder: None });
+
+ let fixed = low_delay(&avcc).unwrap();
+ assert_eq!(&fixed[..6], &avcc[..6], "profile and level as they were");
+ let len = usize::from(u16::from_be_bytes([fixed[6], fixed[7]]));
+ let new_sps = &fixed[8..8 + len];
+ let after = read(&unescape(&new_sps[1..])).unwrap();
+ assert_eq!((after.vui, after.reorder, after.max_num_ref_frames), (true, Some(0), 1));
+ assert_eq!(after.cut - before.cut, 9, "the VUI's 9 flags up to the restriction");
+ // the bits before the VUI are the same
+ let (a, b) = (unescape(&sps[1..]), unescape(&new_sps[1..]));
+ let (mut ra, mut rb) = (Reader::new(&a), Reader::new(&b));
+ for _ in 0..before.cut {
+ assert_eq!(ra.u(1), rb.u(1));
+ }
+ assert_eq!(&fixed[8 + len..], &avcc[20..], "PPS and extension untouched");
+ assert_eq!(low_delay(&fixed).unwrap(), fixed, "already says 0: unchanged");
+ }
+
+ /// An SPS with a VUI (signal type, timing) but no restriction keeps those and gets the restriction after them
+ #[test]
+ fn vui_without_restriction_keeps_its_fields() {
+ // Baseline SPS built here: profile 66, level 31, sps id 0, log2_max_frame_num 4, poc type 2, 1 ref frame,
+ // 40×23 macroblocks, frame_mbs_only, direct_8x8, no cropping; VUI with full-range video signal and timing
+ let mut w = Writer::default();
+ for (v, n) in [(66, 8), (0, 8), (31, 8)] {
+ for i in (0..n).rev() {
+ w.bit((v >> i) & 1);
+ }
+ }
+ for v in [0, 0, 2, 1] {
+ w.ue(v);
+ }
+ w.bit(0);
+ w.ue(39);
+ w.ue(22);
+ w.bit(1);
+ w.bit(1);
+ w.bit(0);
+ w.bit(1); // VUI
+ w.bit(0);
+ w.bit(0);
+ w.bit(1); // video signal type: format 5, full range, no colour description
+ for b in [1, 0, 1, 1, 0] {
+ w.bit(b);
+ }
+ w.bit(0);
+ w.bit(1); // timing
+ for _ in 0..64 {
+ w.bit(1);
+ }
+ w.bit(1);
+ for _ in 0..4 {
+ w.bit(0); // no NAL HRD, no VCL HRD, no pic struct, no bitstream restriction
+ }
+ w.bit(1); // rbsp_stop_one_bit
+ let rbsp = w.finish();
+ let s = read(&rbsp).unwrap();
+ assert_eq!((s.vui, s.reorder, s.max_num_ref_frames), (true, None, 1));
+ let mut nal = vec![0x67];
+ nal.extend(escape(&rbsp));
+ let fixed = sps_low_delay(&nal).unwrap();
+ let after = read(&unescape(&fixed[1..])).unwrap();
+ assert_eq!((after.vui, after.reorder, after.cut), (true, Some(0), s.cut));
+ }
+
+ #[test]
+ fn escaping_round_trips() {
+ let raw = [0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 2, 5];
+ let e = escape(&raw);
+ assert_eq!(e, [0, 0, 3, 0, 0, 3, 1, 0, 0, 3, 3, 0, 0, 3, 2, 5]);
+ assert_eq!(unescape(&e), raw);
+ }
+
+ #[test]
+ fn unreadable_input_is_none() {
+ assert_eq!(low_delay(&[1, 2]), None);
+ assert_eq!(low_delay(&hex("0164002affe10002ff00")), None, "not an SPS");
+ }
+}
diff --git a/apps/iphone-control/src/video/vt.rs b/apps/iphone-control/src/video/vt.rs
new file mode 100644
index 0000000..53bdcc6
--- /dev/null
+++ b/apps/iphone-control/src/video/vt.rs
@@ -0,0 +1,1262 @@
+//! macOS: H.264 with VideoToolbox inside this program, no ffmpeg needed. Tried before ffmpeg's `h264_videotoolbox`,
+//! which stays as the fallback ([`super::ffmpeg::candidates`]).
+//!
+//! One thread per session: the phone's JPEG is decoded by VideoToolbox's JPEG decoder (the hardware one on Apple
+//! silicon) into an NV12 pixel buffer, which goes straight to the H.264 encoder; neither touches the CPU's copy of the
+//! picture. The encoder runs without frame reordering and with no frames held back (`MaxFrameDelayCount` 0), and
+//! every frame is completed before the next one is taken, so nothing waits for a following frame: no copies are needed
+//! after each frame (`kicks` measures 0, unlike ffmpeg). An odd size (the phone's frames at 75 %) is stretched to
+//! the next even one by the JPEG decoder, as ffmpeg's `scale` does: the H.264 encoder would cut the last column and
+//! row off instead. What comes out is already in the `avcC` format (NAL units with
+//! 4-byte lengths); the `avcC` itself is the one VideoToolbox puts in the format description.
+//!
+//! Quality: the quantizer is pinned (`MinAllowedFrameQP` = `MaxAllowedFrameQP` = qp) where the encoder supports it
+//! (macOS 12 and later, Apple silicon), the same constant-qp setting the hardware encoders get through ffmpeg; else
+//! `Quality` is set from qp ([`quality_for`]).
+//!
+//! Keys added after macOS 11 are looked up at run time ([`key`]): linked directly, the program wouldn't start on an
+//! older system.
+
+#![allow(non_upper_case_globals)]
+
+use std::collections::VecDeque;
+use std::ffi::{CStr, c_void};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::Instant;
+
+use tokio::sync::mpsc;
+
+use super::flv::Packet;
+
+mod sys {
+ use std::ffi::{c_char, c_void};
+
+ pub type CFTypeRef = *const c_void;
+ pub type CFStringRef = *const c_void;
+ pub type CFAllocatorRef = *const c_void;
+ pub type OSStatus = i32;
+
+ #[repr(C)]
+ #[derive(Clone, Copy, Debug)]
+ pub struct CMTime {
+ pub value: i64,
+ pub timescale: i32,
+ pub flags: u32,
+ pub epoch: i64,
+ }
+
+ #[repr(C)]
+ pub struct CMSampleTimingInfo {
+ pub duration: CMTime,
+ pub pts: CMTime,
+ pub dts: CMTime,
+ }
+
+ /// The dictionary callback structs, only ever passed by address
+ #[repr(C)]
+ pub struct Opaque {
+ _p: [u8; 0],
+ }
+
+ pub type CompressionCallback = extern "C" fn(*mut c_void, *mut c_void, OSStatus, u32, *mut c_void);
+ pub type DecompressionCallback =
+ extern "C" fn(*mut c_void, *mut c_void, OSStatus, u32, *mut c_void, CMTime, CMTime);
+
+ #[repr(C)]
+ pub struct DecompressionCallbackRecord {
+ pub callback: DecompressionCallback,
+ pub refcon: *mut c_void,
+ }
+
+ pub const kCFNumberSInt32Type: isize = 3;
+ pub const kCFNumberFloat64Type: isize = 6;
+ pub const kCFStringEncodingUTF8: u32 = 0x0800_0100;
+ pub const kCMTimeFlags_Valid: u32 = 1;
+ /// 'avc1', 'jpeg'
+ pub const kCMVideoCodecType_H264: u32 = u32::from_be_bytes(*b"avc1");
+ pub const kCMVideoCodecType_JPEG: u32 = u32::from_be_bytes(*b"jpeg");
+ /// '420v': NV12, video range (what ffmpeg's `format=nv12` gives too)
+ pub const kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: u32 = u32::from_be_bytes(*b"420v");
+
+ #[link(name = "CoreFoundation", kind = "framework")]
+ unsafe extern "C" {
+ pub static kCFAllocatorNull: CFAllocatorRef;
+ pub static kCFBooleanTrue: CFTypeRef;
+ pub static kCFBooleanFalse: CFTypeRef;
+ pub static kCFTypeDictionaryKeyCallBacks: Opaque;
+ pub static kCFTypeDictionaryValueCallBacks: Opaque;
+ pub fn CFRelease(cf: CFTypeRef);
+ pub fn CFRetain(cf: CFTypeRef) -> CFTypeRef;
+ pub fn CFDictionaryCreateMutable(
+ a: CFAllocatorRef,
+ cap: isize,
+ k: *const Opaque,
+ v: *const Opaque,
+ ) -> *mut c_void;
+ pub fn CFDictionarySetValue(d: *mut c_void, k: *const c_void, v: *const c_void);
+ pub fn CFDictionaryGetValue(d: CFTypeRef, k: *const c_void) -> *const c_void;
+ pub fn CFNumberCreate(a: CFAllocatorRef, t: isize, v: *const c_void) -> CFTypeRef;
+ pub fn CFArrayGetCount(a: CFTypeRef) -> isize;
+ pub fn CFArrayGetValueAtIndex(a: CFTypeRef, i: isize) -> *const c_void;
+ pub fn CFDataGetLength(d: CFTypeRef) -> isize;
+ pub fn CFDataGetBytePtr(d: CFTypeRef) -> *const u8;
+ pub fn CFStringCreateWithCString(a: CFAllocatorRef, s: *const c_char, enc: u32) -> CFStringRef;
+ pub fn CFBooleanGetValue(b: CFTypeRef) -> u8;
+ }
+
+ #[link(name = "CoreMedia", kind = "framework")]
+ unsafe extern "C" {
+ pub static kCMTimeInvalid: CMTime;
+ pub static kCMSampleAttachmentKey_NotSync: CFStringRef;
+ pub static kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms: CFStringRef;
+ pub fn CMSampleBufferGetDataBuffer(s: *mut c_void) -> *mut c_void;
+ pub fn CMSampleBufferGetFormatDescription(s: *mut c_void) -> *mut c_void;
+ pub fn CMSampleBufferGetSampleAttachmentsArray(s: *mut c_void, create: u8) -> CFTypeRef;
+ pub fn CMBlockBufferGetDataLength(b: *mut c_void) -> usize;
+ pub fn CMBlockBufferCopyDataBytes(b: *mut c_void, offset: usize, len: usize, dest: *mut c_void) -> OSStatus;
+ pub fn CMFormatDescriptionGetExtension(d: *mut c_void, key: CFStringRef) -> CFTypeRef;
+ pub fn CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
+ d: *mut c_void,
+ i: usize,
+ ptr: *mut *const u8,
+ size: *mut usize,
+ count: *mut usize,
+ nal_len: *mut i32,
+ ) -> OSStatus;
+ pub fn CMVideoFormatDescriptionCreate(
+ a: CFAllocatorRef,
+ codec: u32,
+ w: i32,
+ h: i32,
+ ext: CFTypeRef,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ pub fn CMBlockBufferCreateWithMemoryBlock(
+ a: CFAllocatorRef,
+ mem: *mut c_void,
+ len: usize,
+ block_alloc: CFAllocatorRef,
+ custom: *const c_void,
+ offset: usize,
+ data_len: usize,
+ flags: u32,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ pub fn CMSampleBufferCreateReady(
+ a: CFAllocatorRef,
+ data: *mut c_void,
+ desc: *mut c_void,
+ n: isize,
+ ntiming: isize,
+ timing: *const CMSampleTimingInfo,
+ nsizes: isize,
+ sizes: *const usize,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ }
+
+ #[link(name = "CoreVideo", kind = "framework")]
+ unsafe extern "C" {
+ pub static kCVPixelBufferPixelFormatTypeKey: CFStringRef;
+ pub static kCVPixelBufferIOSurfacePropertiesKey: CFStringRef;
+ pub static kCVPixelBufferWidthKey: CFStringRef;
+ pub static kCVPixelBufferHeightKey: CFStringRef;
+ pub fn CVPixelBufferCreate(
+ a: CFAllocatorRef,
+ w: usize,
+ h: usize,
+ fmt: u32,
+ attrs: CFTypeRef,
+ out: *mut *mut c_void,
+ ) -> i32;
+ pub fn CVPixelBufferLockBaseAddress(b: *mut c_void, flags: u64) -> i32;
+ pub fn CVPixelBufferUnlockBaseAddress(b: *mut c_void, flags: u64) -> i32;
+ pub fn CVPixelBufferGetBaseAddressOfPlane(b: *mut c_void, plane: usize) -> *mut u8;
+ pub fn CVPixelBufferGetBytesPerRowOfPlane(b: *mut c_void, plane: usize) -> usize;
+ pub fn CVPixelBufferGetWidth(b: *mut c_void) -> usize;
+ pub fn CVPixelBufferGetHeight(b: *mut c_void) -> usize;
+ }
+
+ #[link(name = "VideoToolbox", kind = "framework")]
+ unsafe extern "C" {
+ pub static kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder: CFStringRef;
+ pub static kVTCompressionPropertyKey_RealTime: CFStringRef;
+ pub static kVTCompressionPropertyKey_AllowFrameReordering: CFStringRef;
+ pub static kVTCompressionPropertyKey_MaxKeyFrameInterval: CFStringRef;
+ pub static kVTCompressionPropertyKey_MaxFrameDelayCount: CFStringRef;
+ pub static kVTCompressionPropertyKey_ExpectedFrameRate: CFStringRef;
+ pub static kVTCompressionPropertyKey_ProfileLevel: CFStringRef;
+ pub static kVTCompressionPropertyKey_Quality: CFStringRef;
+ pub static kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder: CFStringRef;
+ pub static kVTProfileLevel_H264_High_AutoLevel: CFStringRef;
+ pub fn VTSessionSetProperty(s: *mut c_void, key: CFStringRef, value: CFTypeRef) -> OSStatus;
+ pub fn VTSessionCopyProperty(s: *mut c_void, key: CFStringRef, a: CFAllocatorRef, out: *mut c_void)
+ -> OSStatus;
+ pub fn VTCompressionSessionCreate(
+ a: CFAllocatorRef,
+ w: i32,
+ h: i32,
+ codec: u32,
+ spec: CFTypeRef,
+ source_attrs: CFTypeRef,
+ data_alloc: CFAllocatorRef,
+ callback: CompressionCallback,
+ refcon: *mut c_void,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ pub fn VTCompressionSessionPrepareToEncodeFrames(s: *mut c_void) -> OSStatus;
+ pub fn VTCompressionSessionEncodeFrame(
+ s: *mut c_void,
+ image: *mut c_void,
+ pts: CMTime,
+ duration: CMTime,
+ props: CFTypeRef,
+ frame_refcon: *mut c_void,
+ flags_out: *mut u32,
+ ) -> OSStatus;
+ pub fn VTCompressionSessionCompleteFrames(s: *mut c_void, until: CMTime) -> OSStatus;
+ pub fn VTCompressionSessionInvalidate(s: *mut c_void);
+ pub fn VTDecompressionSessionCreate(
+ a: CFAllocatorRef,
+ desc: *mut c_void,
+ spec: CFTypeRef,
+ dest_attrs: CFTypeRef,
+ callback: *const DecompressionCallbackRecord,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ pub fn VTDecompressionSessionDecodeFrame(
+ s: *mut c_void,
+ sample: *mut c_void,
+ flags: u32,
+ frame_refcon: *mut c_void,
+ flags_out: *mut u32,
+ ) -> OSStatus;
+ pub fn VTDecompressionSessionWaitForAsynchronousFrames(s: *mut c_void) -> OSStatus;
+ pub fn VTDecompressionSessionInvalidate(s: *mut c_void);
+ }
+}
+
+use sys::*;
+
+/// An owned Core Foundation object, released when dropped
+struct Cf(*mut c_void);
+
+impl Cf {
+ fn new(p: *const c_void) -> Option<Self> {
+ (!p.is_null()).then_some(Self(p as *mut c_void))
+ }
+ fn ptr(&self) -> *mut c_void {
+ self.0
+ }
+}
+
+impl Drop for Cf {
+ fn drop(&mut self) {
+ unsafe { CFRelease(self.0) }
+ }
+}
+
+/// A mutable CF dictionary with CF-typed keys and values
+struct Dict(Cf);
+
+impl Dict {
+ fn new() -> Self {
+ let d = unsafe {
+ CFDictionaryCreateMutable(
+ std::ptr::null(),
+ 0,
+ &raw const kCFTypeDictionaryKeyCallBacks,
+ &raw const kCFTypeDictionaryValueCallBacks,
+ )
+ };
+ Self(Cf::new(d).expect("CFDictionaryCreateMutable"))
+ }
+ fn set(&self, k: CFStringRef, v: CFTypeRef) {
+ unsafe { CFDictionarySetValue(self.0.ptr(), k, v) }
+ }
+}
+
+fn number_i32(v: i32) -> Cf {
+ Cf::new(unsafe { CFNumberCreate(std::ptr::null(), kCFNumberSInt32Type, (&raw const v).cast()) }).expect("CFNumber")
+}
+
+fn number_f64(v: f64) -> Cf {
+ Cf::new(unsafe { CFNumberCreate(std::ptr::null(), kCFNumberFloat64Type, (&raw const v).cast()) }).expect("CFNumber")
+}
+
+fn cfstr(s: &CStr) -> Cf {
+ Cf::new(unsafe { CFStringCreateWithCString(std::ptr::null(), s.as_ptr(), kCFStringEncodingUTF8) })
+ .expect("CFString")
+}
+
+/// A key exported by a framework, looked up at run time; `None` on a system that doesn't have it
+fn key(name: &CStr) -> Option<CFStringRef> {
+ let p = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) } as *const CFStringRef;
+ if p.is_null() { None } else { Some(unsafe { *p }).filter(|k| !k.is_null()) }
+}
+
+fn time(value: i64, timescale: i32) -> CMTime {
+ CMTime { value, timescale, flags: kCMTimeFlags_Valid, epoch: 0 }
+}
+
+fn check(status: OSStatus, what: &str) -> Result<(), String> {
+ if status == 0 { Ok(()) } else { Err(format!("{what}: OSStatus {status}")) }
+}
+
+/// `Quality` (0 to 1) for an encoder that can't pin the quantizer (before macOS 12): qp 20 → 0.75, 0.03 less per
+/// step. An estimate, not measured: on Apple silicon with macOS 12 or later the quantizer is pinned instead
+pub fn quality_for(qp: u8) -> f64 {
+ (0.75 - (f64::from(qp) - 20.0) * 0.03).clamp(0.1, 1.0)
+}
+
+// ------------------------------------------------------------------ the encoder's output
+
+/// What the compression callback writes to
+struct Sink {
+ tx: mpsc::UnboundedSender<Result<Packet, String>>,
+ /// H.264: the `avcC` sent last, so a new one goes out before the frame that needs it. JPEG: unused
+ avcc: Mutex<Vec<u8>>,
+ h264: bool,
+}
+
+extern "C" fn on_encoded(refcon: *mut c_void, _frame: *mut c_void, status: OSStatus, _flags: u32, sample: *mut c_void) {
+ let sink = unsafe { &*(refcon as *const Sink) };
+ if status != 0 {
+ let _ = sink.tx.send(Err(format!("VideoToolbox encoder: OSStatus {status}")));
+ return;
+ }
+ // a frame the encoder dropped
+ if sample.is_null() {
+ return;
+ }
+ let Some(data) = (unsafe { sample_bytes(sample) }) else {
+ let _ = sink.tx.send(Err("VideoToolbox encoder: no data".into()));
+ return;
+ };
+ if !sink.h264 {
+ let _ = sink.tx.send(Ok(Packet::Frame { key: true, data }));
+ return;
+ }
+ let key = unsafe { is_sync(sample) };
+ if key {
+ let Some(avcc) = (unsafe { avcc_of(CMSampleBufferGetFormatDescription(sample)) }) else {
+ let _ = sink.tx.send(Err("VideoToolbox encoder: no avcC".into()));
+ return;
+ };
+ let mut last = sink.avcc.lock().unwrap_or_else(|p| p.into_inner());
+ if *last != avcc {
+ *last = avcc.clone();
+ let _ = sink.tx.send(Ok(Packet::Config(avcc)));
+ }
+ }
+ let _ = sink.tx.send(Ok(Packet::Frame { key, data }));
+}
+
+unsafe fn sample_bytes(sample: *mut c_void) -> Option<Vec<u8>> {
+ let bb = unsafe { CMSampleBufferGetDataBuffer(sample) };
+ if bb.is_null() {
+ return None;
+ }
+ let len = unsafe { CMBlockBufferGetDataLength(bb) };
+ let mut v = vec![0u8; len];
+ (unsafe { CMBlockBufferCopyDataBytes(bb, 0, len, v.as_mut_ptr().cast()) } == 0).then_some(v)
+}
+
+/// A keyframe: no `NotSync` attachment, or one that is false
+unsafe fn is_sync(sample: *mut c_void) -> bool {
+ let a = unsafe { CMSampleBufferGetSampleAttachmentsArray(sample, 0) };
+ if a.is_null() || unsafe { CFArrayGetCount(a) } == 0 {
+ return true;
+ }
+ let d = unsafe { CFArrayGetValueAtIndex(a, 0) };
+ let v = unsafe { CFDictionaryGetValue(d, kCMSampleAttachmentKey_NotSync) };
+ v.is_null() || unsafe { CFBooleanGetValue(v) } == 0
+}
+
+/// The `avcC` of a format description: the one VideoToolbox stores as a sample description atom, else built from
+/// the parameter sets
+unsafe fn avcc_of(desc: *mut c_void) -> Option<Vec<u8>> {
+ if desc.is_null() {
+ return None;
+ }
+ let atoms =
+ unsafe { CMFormatDescriptionGetExtension(desc, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms) };
+ if !atoms.is_null() {
+ let name = cfstr(c"avcC");
+ let d = unsafe { CFDictionaryGetValue(atoms, name.ptr()) };
+ if !d.is_null() {
+ let n = unsafe { CFDataGetLength(d) } as usize;
+ let p = unsafe { CFDataGetBytePtr(d) };
+ if n > 6 && !p.is_null() {
+ return Some(unsafe { std::slice::from_raw_parts(p, n) }.to_vec());
+ }
+ }
+ }
+ let (mut count, mut nal_len) = (0usize, 0i32);
+ let mut sets = Vec::new();
+ let mut i = 0;
+ loop {
+ let (mut p, mut n) = (std::ptr::null(), 0usize);
+ let s = unsafe {
+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex(desc, i, &mut p, &mut n, &mut count, &mut nal_len)
+ };
+ if s != 0 || p.is_null() {
+ return None;
+ }
+ sets.push(unsafe { std::slice::from_raw_parts(p, n) }.to_vec());
+ i += 1;
+ if i >= count {
+ break;
+ }
+ }
+ build_avcc(&sets, nal_len)
+}
+
+/// An `avcC` from the SPS (NAL type 7) and PPS (8) and the length size of the NAL units
+fn build_avcc(sets: &[Vec<u8>], nal_len: i32) -> Option<Vec<u8>> {
+ let sps: Vec<&Vec<u8>> = sets.iter().filter(|s| s.first().is_some_and(|b| b & 0x1f == 7)).collect();
+ let pps: Vec<&Vec<u8>> = sets.iter().filter(|s| s.first().is_some_and(|b| b & 0x1f == 8)).collect();
+ let first = sps.first().filter(|s| s.len() >= 4)?;
+ if pps.is_empty() || !(1..=4).contains(&nal_len) {
+ return None;
+ }
+ let mut v = vec![1, first[1], first[2], first[3], 0xFC | (nal_len as u8 - 1), 0xE0 | sps.len() as u8];
+ for s in &sps {
+ v.extend_from_slice(&(s.len() as u16).to_be_bytes());
+ v.extend_from_slice(s);
+ }
+ v.push(pps.len() as u8);
+ for p in &pps {
+ v.extend_from_slice(&(p.len() as u16).to_be_bytes());
+ v.extend_from_slice(p);
+ }
+ Some(v)
+}
+
+// ------------------------------------------------------------------ sessions
+
+/// A VideoToolbox compression session (H.264 or JPEG) and the sink its callback writes to
+struct Encoder {
+ session: Cf,
+ sink: *mut Sink,
+ start: Instant,
+ /// The last presentation time, so two frames in the same microsecond still go up
+ last_pts: i64,
+ hardware: bool,
+}
+
+impl Encoder {
+ fn new(
+ w: u32,
+ h: u32,
+ codec: u32,
+ tune: impl Fn(*mut c_void) -> Result<(), String>,
+ sink: Sink,
+ ) -> Result<Self, String> {
+ let spec = Dict::new();
+ spec.set(unsafe { kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder }, unsafe {
+ kCFBooleanTrue
+ });
+ let sink = Box::into_raw(Box::new(sink));
+ let mut s = std::ptr::null_mut();
+ let st = unsafe {
+ VTCompressionSessionCreate(
+ std::ptr::null(),
+ w as i32,
+ h as i32,
+ codec,
+ spec.0.ptr(),
+ std::ptr::null(),
+ std::ptr::null(),
+ on_encoded,
+ sink.cast(),
+ &mut s,
+ )
+ };
+ if st != 0 || s.is_null() {
+ drop(unsafe { Box::from_raw(sink) });
+ return Err(format!("VTCompressionSessionCreate: OSStatus {st}"));
+ }
+ let mut e = Self { session: Cf(s), sink, start: Instant::now(), last_pts: -1, hardware: false };
+ tune(s)?;
+ check(unsafe { VTCompressionSessionPrepareToEncodeFrames(s) }, "VTCompressionSessionPrepareToEncodeFrames")?;
+ let mut hw: CFTypeRef = std::ptr::null();
+ if unsafe {
+ VTSessionCopyProperty(
+ s,
+ kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
+ std::ptr::null(),
+ (&raw mut hw).cast(),
+ )
+ } == 0
+ && let Some(hw) = Cf::new(hw)
+ {
+ e.hardware = unsafe { CFBooleanGetValue(hw.ptr()) } != 0;
+ }
+ Ok(e)
+ }
+
+ /// Encodes one picture and waits until it has come out (the callback has run)
+ fn encode(&mut self, image: *mut c_void) -> Result<(), String> {
+ let pts = (self.start.elapsed().as_micros() as i64).max(self.last_pts + 1);
+ self.last_pts = pts;
+ let s = self.session.ptr();
+ check(
+ unsafe {
+ VTCompressionSessionEncodeFrame(
+ s,
+ image,
+ time(pts, 1_000_000),
+ kCMTimeInvalid,
+ std::ptr::null(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ )
+ },
+ "VTCompressionSessionEncodeFrame",
+ )?;
+ check(unsafe { VTCompressionSessionCompleteFrames(s, kCMTimeInvalid) }, "VTCompressionSessionCompleteFrames")
+ }
+}
+
+impl Drop for Encoder {
+ fn drop(&mut self) {
+ unsafe {
+ // every frame was completed in `encode`, so no callback is pending once this returns
+ VTCompressionSessionCompleteFrames(self.session.ptr(), kCMTimeInvalid);
+ VTCompressionSessionInvalidate(self.session.ptr());
+ }
+ // the session is released after the sink (fields drop after this): it no longer calls back once invalidated
+ drop(unsafe { Box::from_raw(self.sink) });
+ }
+}
+
+fn set(s: *mut c_void, k: CFStringRef, v: CFTypeRef, what: &str) -> Result<(), String> {
+ check(unsafe { VTSessionSetProperty(s, k, v) }, what)
+}
+
+/// An H.264 encoder for the viewer: real time, no reordering, nothing held back, qp pinned where it can be
+fn h264(w: u32, h: u32, qp: u8, sink: Sink) -> Result<(Encoder, bool), String> {
+ let pinned = std::cell::Cell::new(false);
+ let tune = |s: *mut c_void| -> Result<(), String> {
+ let t = unsafe { kCFBooleanTrue };
+ let f = unsafe { kCFBooleanFalse };
+ set(s, unsafe { kVTCompressionPropertyKey_RealTime }, t, "RealTime")?;
+ set(s, unsafe { kVTCompressionPropertyKey_AllowFrameReordering }, f, "AllowFrameReordering")?;
+ set(
+ s,
+ unsafe { kVTCompressionPropertyKey_ProfileLevel },
+ unsafe { kVTProfileLevel_H264_High_AutoLevel },
+ "ProfileLevel",
+ )?;
+ set(
+ s,
+ unsafe { kVTCompressionPropertyKey_MaxKeyFrameInterval },
+ number_i32(super::ffmpeg::GOP_FRAMES as i32).ptr(),
+ "MaxKeyFrameInterval",
+ )?;
+ // not every encoder takes these; they only help
+ let _ =
+ set(s, unsafe { kVTCompressionPropertyKey_MaxFrameDelayCount }, number_i32(0).ptr(), "MaxFrameDelayCount");
+ let _ =
+ set(s, unsafe { kVTCompressionPropertyKey_ExpectedFrameRate }, number_i32(60).ptr(), "ExpectedFrameRate");
+ if let (Some(min), Some(max)) =
+ (key(c"kVTCompressionPropertyKey_MinAllowedFrameQP"), key(c"kVTCompressionPropertyKey_MaxAllowedFrameQP"))
+ {
+ let q = number_i32(i32::from(qp));
+ pinned.set(
+ set(s, min, q.ptr(), "MinAllowedFrameQP").is_ok() && set(s, max, q.ptr(), "MaxAllowedFrameQP").is_ok(),
+ );
+ }
+ if !pinned.get() {
+ set(s, unsafe { kVTCompressionPropertyKey_Quality }, number_f64(quality_for(qp)).ptr(), "Quality")?;
+ }
+ Ok(())
+ };
+ let e = Encoder::new(w, h, kCMVideoCodecType_H264, tune, sink)?;
+ Ok((e, pinned.get()))
+}
+
+/// The size frames are encoded at: 4:2:0 needs even sizes, so an odd one grows by a pixel (as in `ffmpeg::args`)
+fn even((w, h): (u32, u32)) -> (u32, u32) {
+ (w + (w & 1), h + (h & 1))
+}
+
+/// VideoToolbox's JPEG decoder for frames of one size, giving NV12 pixel buffers of that size made even ([`even`])
+struct Decoder {
+ session: Cf,
+ desc: Cf,
+ out: *mut DecodedSlot,
+ size: (u32, u32),
+}
+
+/// Where the decompression callback leaves its picture
+#[derive(Default)]
+struct DecodedSlot {
+ image: Option<Cf>,
+ status: OSStatus,
+}
+
+extern "C" fn on_decoded(
+ refcon: *mut c_void,
+ _frame: *mut c_void,
+ status: OSStatus,
+ _flags: u32,
+ image: *mut c_void,
+ _pts: CMTime,
+ _dur: CMTime,
+) {
+ let slot = unsafe { &mut *(refcon as *mut DecodedSlot) };
+ slot.status = status;
+ if status == 0 && !image.is_null() {
+ slot.image = Cf::new(unsafe { CFRetain(image) });
+ }
+}
+
+impl Decoder {
+ fn new(w: u32, h: u32) -> Result<Self, String> {
+ let mut desc = std::ptr::null_mut();
+ check(
+ unsafe {
+ CMVideoFormatDescriptionCreate(
+ std::ptr::null(),
+ kCMVideoCodecType_JPEG,
+ w as i32,
+ h as i32,
+ std::ptr::null(),
+ &mut desc,
+ )
+ },
+ "CMVideoFormatDescriptionCreate",
+ )?;
+ Self::with_desc(Cf(desc), (w, h), even((w, h)))
+ }
+
+ /// A decoder for `desc` (frames of `size`) giving NV12 pixel buffers of `out` size
+ fn with_desc(desc: Cf, size: (u32, u32), (ew, eh): (u32, u32)) -> Result<Self, String> {
+ let attrs = Dict::new();
+ attrs.set(
+ unsafe { kCVPixelBufferPixelFormatTypeKey },
+ number_i32(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange as i32).ptr(),
+ );
+ attrs.set(unsafe { kCVPixelBufferIOSurfacePropertiesKey }, Dict::new().0.ptr());
+ attrs.set(unsafe { kCVPixelBufferWidthKey }, number_i32(ew as i32).ptr());
+ attrs.set(unsafe { kCVPixelBufferHeightKey }, number_i32(eh as i32).ptr());
+ let out = Box::into_raw(Box::<DecodedSlot>::default());
+ let record = DecompressionCallbackRecord { callback: on_decoded, refcon: out.cast() };
+ let mut s = std::ptr::null_mut();
+ let st = unsafe {
+ VTDecompressionSessionCreate(std::ptr::null(), desc.ptr(), std::ptr::null(), attrs.0.ptr(), &record, &mut s)
+ };
+ if st != 0 || s.is_null() {
+ drop(unsafe { Box::from_raw(out) });
+ return Err(format!("VTDecompressionSessionCreate: OSStatus {st}"));
+ }
+ Ok(Self { session: Cf(s), desc, out, size })
+ }
+
+ /// The JPEG (or other frame) as a pixel buffer (decoded synchronously)
+ fn decode(&mut self, jpeg: &[u8]) -> Result<Cf, String> {
+ let mut bb = std::ptr::null_mut();
+ // the block points at `jpeg` without copying (kCFAllocatorNull: never freed by Core Media); it is released
+ // below, after the decoder is done with it
+ check(
+ unsafe {
+ CMBlockBufferCreateWithMemoryBlock(
+ std::ptr::null(),
+ jpeg.as_ptr() as *mut c_void,
+ jpeg.len(),
+ kCFAllocatorNull,
+ std::ptr::null(),
+ 0,
+ jpeg.len(),
+ 0,
+ &mut bb,
+ )
+ },
+ "CMBlockBufferCreateWithMemoryBlock",
+ )?;
+ let bb = Cf(bb);
+ let mut sample = std::ptr::null_mut();
+ let len = jpeg.len();
+ check(
+ unsafe {
+ CMSampleBufferCreateReady(
+ std::ptr::null(),
+ bb.ptr(),
+ self.desc.ptr(),
+ 1,
+ 0,
+ std::ptr::null(),
+ 1,
+ &len,
+ &mut sample,
+ )
+ },
+ "CMSampleBufferCreateReady",
+ )?;
+ let sample = Cf(sample);
+ let slot = unsafe { &mut *self.out };
+ *slot = DecodedSlot::default();
+ let s = self.session.ptr();
+ check(
+ unsafe {
+ VTDecompressionSessionDecodeFrame(s, sample.ptr(), 0, std::ptr::null_mut(), std::ptr::null_mut())
+ },
+ "VTDecompressionSessionDecodeFrame",
+ )?;
+ unsafe { VTDecompressionSessionWaitForAsynchronousFrames(s) };
+ check(slot.status, "decoder")?;
+ slot.image.take().ok_or_else(|| "decoder: no picture".to_owned())
+ }
+}
+
+impl Drop for Decoder {
+ fn drop(&mut self) {
+ unsafe {
+ VTDecompressionSessionWaitForAsynchronousFrames(self.session.ptr());
+ VTDecompressionSessionInvalidate(self.session.ptr());
+ }
+ drop(unsafe { Box::from_raw(self.out) });
+ }
+}
+
+// ------------------------------------------------------------------ the session the viewer uses
+
+/// What the caller and the encoding thread share
+struct Shared {
+ state: Mutex<State>,
+ wake: Condvar,
+}
+
+#[derive(Default)]
+struct State {
+ /// The next frame to encode; a newer one replaces it
+ next: Option<Arc<Vec<u8>>>,
+ stop: bool,
+ /// Frames given to the encoder so far, copies included
+ written: usize,
+ /// The last errors
+ errors: VecDeque<String>,
+}
+
+/// One encoding thread for frames of one size. Same use as an ffmpeg session: `push` the newest JPEG, `next` the
+/// packets
+pub struct Session {
+ shared: Arc<Shared>,
+ out: mpsc::UnboundedReceiver<Result<Packet, String>>,
+}
+
+impl Drop for Session {
+ fn drop(&mut self) {
+ self.shared.state.lock().unwrap_or_else(|p| p.into_inner()).stop = true;
+ self.shared.wake.notify_all();
+ }
+}
+
+/// What the thread found out about the encoder once it was set up
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Info {
+ pub hardware: bool,
+ /// The quantizer is pinned to qp (else `Quality` approximates it)
+ pub pinned_qp: bool,
+}
+
+impl Session {
+ /// Starts the thread; `kicks`: copies after each frame (0 unless measured otherwise). `info` is told once the
+ /// encoder is set up
+ pub fn start(w: u32, h: u32, qp: u8, kicks: usize, info: Option<tokio::sync::oneshot::Sender<Info>>) -> Self {
+ let shared = Arc::new(Shared { state: Mutex::default(), wake: Condvar::new() });
+ let (tx, out) = mpsc::unbounded_channel();
+ let sh = shared.clone();
+ let spawned = std::thread::Builder::new().name("ictl-videotoolbox".into()).spawn(move || {
+ if let Err(e) = run(&sh, w, h, qp, kicks, tx.clone(), info) {
+ note(&sh, &e);
+ let _ = tx.send(Err(e));
+ }
+ });
+ if let Err(e) = spawned {
+ note(&shared, &e.to_string());
+ }
+ Self { shared, out }
+ }
+
+ pub fn push(&self, jpeg: Arc<Vec<u8>>) {
+ self.shared.state.lock().unwrap_or_else(|p| p.into_inner()).next = Some(jpeg);
+ self.shared.wake.notify_all();
+ }
+
+ /// The next packet; `None` once the thread has ended. Cancel-safe
+ pub async fn next(&mut self) -> Option<Result<Packet, String>> {
+ self.out.recv().await
+ }
+
+ pub fn written(&self) -> usize {
+ self.shared.state.lock().unwrap_or_else(|p| p.into_inner()).written
+ }
+
+ pub fn error(&self) -> String {
+ let s = self.shared.state.lock().unwrap_or_else(|p| p.into_inner());
+ if s.errors.is_empty() {
+ ictl_l10n::tr!("VideoToolbox 编码停了", "VideoToolbox encoding stopped").into()
+ } else {
+ s.errors.iter().cloned().collect::<Vec<_>>().join("; ")
+ }
+ }
+}
+
+fn note(sh: &Shared, e: &str) {
+ let mut s = sh.state.lock().unwrap_or_else(|p| p.into_inner());
+ if s.errors.len() == 3 {
+ s.errors.pop_front();
+ }
+ s.errors.push_back(e.to_owned());
+}
+
+fn run(
+ sh: &Shared,
+ w: u32,
+ h: u32,
+ qp: u8,
+ kicks: usize,
+ tx: mpsc::UnboundedSender<Result<Packet, String>>,
+ info: Option<tokio::sync::oneshot::Sender<Info>>,
+) -> Result<(), String> {
+ let (ew, eh) = even((w, h));
+ let (mut enc, pinned_qp) = h264(ew, eh, qp, Sink { tx, avcc: Mutex::default(), h264: true })?;
+ let mut dec = Decoder::new(w, h)?;
+ if let Some(i) = info {
+ let _ = i.send(Info { hardware: enc.hardware, pinned_qp });
+ }
+ loop {
+ let jpeg = {
+ let mut s = sh.state.lock().unwrap_or_else(|p| p.into_inner());
+ loop {
+ if s.stop {
+ return Ok(());
+ }
+ if let Some(j) = s.next.take() {
+ break j;
+ }
+ s = sh.wake.wait(s).unwrap_or_else(|p| p.into_inner());
+ }
+ };
+ if super::mjpeg::jpeg_size(&jpeg) != Some(dec.size) {
+ return Err(format!("JPEG of another size than {}×{}", dec.size.0, dec.size.1));
+ }
+ let image = dec.decode(&jpeg)?;
+ // counted before it goes in: the frame may reach the caller before `encode` returns
+ sh.state.lock().unwrap_or_else(|p| p.into_inner()).written += 1 + kicks;
+ for _ in 0..=kicks {
+ enc.encode(image.ptr())?;
+ }
+ }
+}
+
+// ------------------------------------------------------------------ a test picture without ffmpeg
+
+/// A JPEG of `w`×`h` from VideoToolbox's JPEG encoder: a list of rows with dark "text" and coloured icons,
+/// scrolled by `n` so consecutive pictures differ, about as large as a phone screen of that size. Blocks the calling
+/// thread for a moment
+pub fn sample_jpeg(w: u32, h: u32, n: u32) -> Result<Vec<u8>, String> {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let image = pattern(w, h, n)?;
+ let tune = |s: *mut c_void| set(s, unsafe { kVTCompressionPropertyKey_Quality }, number_f64(0.8).ptr(), "Quality");
+ let mut e = Encoder::new(w, h, kCMVideoCodecType_JPEG, tune, Sink { tx, avcc: Mutex::default(), h264: false })?;
+ e.encode(image.ptr())?;
+ drop(e);
+ match rx.try_recv() {
+ Ok(Ok(Packet::Frame { data, .. })) if super::mjpeg::jpeg_size(&data) == Some((w, h)) => Ok(data),
+ Ok(Ok(_)) => Err("VideoToolbox JPEG encoder: not a JPEG of that size".into()),
+ Ok(Err(e)) => Err(e),
+ Err(_) => Err("VideoToolbox JPEG encoder: nothing came out".into()),
+ }
+}
+
+/// An NV12 picture to encode (see [`sample_jpeg`])
+fn pattern(w: u32, h: u32, n: u32) -> Result<Cf, String> {
+ let attrs = Dict::new();
+ attrs.set(unsafe { kCVPixelBufferIOSurfacePropertiesKey }, Dict::new().0.ptr());
+ let mut pb = std::ptr::null_mut();
+ let st = unsafe {
+ CVPixelBufferCreate(
+ std::ptr::null(),
+ w as usize,
+ h as usize,
+ kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
+ attrs.0.ptr(),
+ &mut pb,
+ )
+ };
+ check(st, "CVPixelBufferCreate")?;
+ let pb = Cf(pb);
+ unsafe {
+ check(CVPixelBufferLockBaseAddress(pb.ptr(), 0), "CVPixelBufferLockBaseAddress")?;
+ let (bw, bh) = (CVPixelBufferGetWidth(pb.ptr()), CVPixelBufferGetHeight(pb.ptr()));
+ let (y, ys) =
+ (CVPixelBufferGetBaseAddressOfPlane(pb.ptr(), 0), CVPixelBufferGetBytesPerRowOfPlane(pb.ptr(), 0));
+ let (uv, uvs) =
+ (CVPixelBufferGetBaseAddressOfPlane(pb.ptr(), 1), CVPixelBufferGetBytesPerRowOfPlane(pb.ptr(), 1));
+ // a list scrolling 4 rows a picture: rows of 48, two in three with a line of "text" (glyphs of 2-pixel strokes
+ // in 9-pixel cells, words of 3 to 8), a coloured icon on the left of every third row
+ let scroll = n as usize * 4;
+ let glyph = |cell: usize, x: usize, y: usize| -> bool {
+ // y in 0..12, x in 0..9: a few stroke shapes chosen by the cell number
+ let mid = (5..7).contains(&x);
+ let even = cell.is_multiple_of(2);
+ let v = x < 2 || (cell.is_multiple_of(3) && mid);
+ let hz = (cell % 4 == 1 && y < 2) || (cell % 5 == 2 && y >= 10) || (cell % 7 == 3 && (5..7).contains(&y));
+ (v && even) || hz || (!even && mid)
+ };
+ for r in 0..bh {
+ let row = std::slice::from_raw_parts_mut(y.add(r * ys), bw);
+ let (item, line) = ((r + scroll) / 48, (r + scroll) % 48);
+ let has_text = item % 3 != 2 && (18..30).contains(&line);
+ for (c, p) in row.iter_mut().enumerate() {
+ let mut dark = false;
+ if has_text && c >= 64 && c < bw.saturating_sub(24) {
+ let cell = (c - 64) / 9 + item * 13;
+ // a space after every 3 to 8 letters
+ let word_len = 3 + (cell / 11) % 6;
+ let in_space = (cell % (word_len + 1)) == word_len;
+ dark = !in_space && glyph(cell, (c - 64) % 9, line - 18);
+ }
+ // separator line at the bottom of each row
+ *p = if dark {
+ 35
+ } else if line == 47 {
+ 200
+ } else {
+ 245
+ };
+ }
+ }
+ for r in 0..bh.div_ceil(2) {
+ let row = std::slice::from_raw_parts_mut(uv.add(r * uvs), bw.div_ceil(2) * 2);
+ let (item, line) = ((r * 2 + scroll) / 48, (r * 2 + scroll) % 48);
+ for (c, p) in row.as_chunks_mut::<2>().0.iter_mut().enumerate() {
+ let icon = item % 3 == 0 && (10..38).contains(&line) && (6..20).contains(&c);
+ p[0] = if icon { 90 + (item % 5) as u8 * 20 } else { 128 };
+ p[1] = if icon { 200 - (item % 4) as u8 * 25 } else { 128 };
+ }
+ }
+ CVPixelBufferUnlockBaseAddress(pb.ptr(), 0);
+ }
+ Ok(pb)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use super::*;
+
+ #[test]
+ fn avcc_from_parameter_sets() {
+ let sps = vec![0x67, 0x64, 0x00, 0x28, 0xAC];
+ let pps = vec![0x68, 0xEE, 0x3C];
+ let a = build_avcc(&[sps, pps], 4).unwrap();
+ assert_eq!(a, [1, 0x64, 0x00, 0x28, 0xFF, 0xE1, 0, 5, 0x67, 0x64, 0x00, 0x28, 0xAC, 1, 0, 3, 0x68, 0xEE, 0x3C]);
+ assert!(build_avcc(&[vec![0x68, 1]], 4).is_none(), "no SPS");
+ }
+
+ #[test]
+ fn odd_sizes_grow_to_even() {
+ assert_eq!(even((968, 2097)), (968, 2098));
+ assert_eq!(even((481, 1041)), (482, 1042));
+ assert_eq!(even((480, 1040)), (480, 1040));
+ }
+
+ #[test]
+ fn quality_follows_qp() {
+ assert_eq!(quality_for(20), 0.75);
+ assert!(quality_for(24) < quality_for(20) && quality_for(1) <= 1.0 && quality_for(51) >= 0.1);
+ }
+
+ /// The native encoder on this Mac, when VideoToolbox can encode here (a CI VM may not): a test picture of an
+ /// odd size (like the phone's 75 % frames) comes out as a keyframe after its `avcC`, the next one as a delta
+ /// frame, and each comes out as soon as it went in, without a following frame
+ #[tokio::test]
+ async fn encodes_natively_without_holding_frames() {
+ let (w, h) = (481, 1041);
+ let pics: Vec<Arc<Vec<u8>>> = match (0..3).map(|n| sample_jpeg(w, h, n)).collect::<Result<Vec<_>, _>>() {
+ Ok(p) => p.into_iter().map(Arc::new).collect(),
+ Err(e) => {
+ eprintln!("VideoToolbox can't make JPEG here ({e}), skipped");
+ return;
+ }
+ };
+ let (itx, irx) = tokio::sync::oneshot::channel();
+ let mut s = Session::start(w, h, 20, 0, Some(itx));
+ let info = match tokio::time::timeout(Duration::from_secs(10), irx).await {
+ Ok(Ok(i)) => i,
+ _ => {
+ eprintln!("no VideoToolbox H.264 encoder here ({}), skipped", s.error());
+ return;
+ }
+ };
+ eprintln!("{info:?}");
+ let mut got = Vec::new();
+ for p in &pics {
+ s.push(p.clone());
+ loop {
+ let pk = tokio::time::timeout(Duration::from_secs(5), s.next())
+ .await
+ .expect("a frame within 5 s of its picture, with nothing pushed after it")
+ .expect("session alive")
+ .unwrap_or_else(|e| panic!("{e}"));
+ let frame = matches!(pk, Packet::Frame { .. });
+ got.push(pk);
+ if frame {
+ break;
+ }
+ }
+ }
+ let Packet::Config(avcc) = &got[0] else { panic!("config first: {got:?}") };
+ assert!(super::super::flv::codec_string(avcc).unwrap().starts_with("avc1.64"), "High profile");
+ assert_eq!(avcc[4] & 3, 3, "4-byte NAL lengths");
+ assert!(matches!(got[1], Packet::Frame { key: true, .. }));
+ assert!(matches!(got[2], Packet::Frame { key: false, .. }));
+ assert!(matches!(got[3], Packet::Frame { key: false, .. }));
+ assert_eq!(s.written(), 3);
+ // every frame is NAL units with 4-byte lengths that add up
+ for p in &got[1..] {
+ let Packet::Frame { data, .. } = p else { unreachable!() };
+ let mut i = 0;
+ while i < data.len() {
+ let n = u32::from_be_bytes(data[i..i + 4].try_into().unwrap()) as usize;
+ i += 4 + n;
+ }
+ assert_eq!(i, data.len());
+ }
+ }
+}
+
+/// Measuring the encoder on a recording of the phone's real picture: traffic, size per frame, time per frame and
+/// SSIM of what the page would show against what the encoder was given. Records come from the viewer's `/stream`
+/// (repeated frames already dropped), one JPEG per file named `<ms since start>.jpg`:
+/// `ICTL_RECORDING=<dir> ICTL_QPS=20,24 cargo test --release -p iphone-control measure_recording -- --ignored --nocapture`
+#[cfg(test)]
+mod measure {
+ use std::collections::BTreeMap;
+
+ use super::*;
+
+ #[link(name = "CoreMedia", kind = "framework")]
+ unsafe extern "C" {
+ fn CMVideoFormatDescriptionCreateFromH264ParameterSets(
+ a: CFAllocatorRef,
+ count: usize,
+ ptrs: *const *const u8,
+ sizes: *const usize,
+ nal_len: i32,
+ out: *mut *mut c_void,
+ ) -> OSStatus;
+ }
+
+ /// An H.264 decoder for the `avcC` (the page's side), giving NV12 of the frames' size
+ fn h264_decoder(avcc: &[u8], size: (u32, u32)) -> Decoder {
+ // avcC: 5 bytes, SPS count & 0x1f, then length-prefixed SPS; PPS count, length-prefixed PPS
+ let mut sets: Vec<&[u8]> = Vec::new();
+ let mut i = 5;
+ // the SPS list, then the PPS list
+ for _ in 0..2 {
+ let n = (avcc[i] & 0x1f) as usize;
+ i += 1;
+ for _ in 0..n {
+ let l = u16::from_be_bytes([avcc[i], avcc[i + 1]]) as usize;
+ sets.push(&avcc[i + 2..i + 2 + l]);
+ i += 2 + l;
+ }
+ }
+ let ptrs: Vec<*const u8> = sets.iter().map(|s| s.as_ptr()).collect();
+ let sizes: Vec<usize> = sets.iter().map(|s| s.len()).collect();
+ let mut desc = std::ptr::null_mut();
+ let st = unsafe {
+ CMVideoFormatDescriptionCreateFromH264ParameterSets(
+ std::ptr::null(),
+ sets.len(),
+ ptrs.as_ptr(),
+ sizes.as_ptr(),
+ 4,
+ &mut desc,
+ )
+ };
+ assert_eq!(st, 0, "H.264 format description");
+ Decoder::with_desc(Cf(desc), size, size).unwrap()
+ }
+
+ /// The Y, Cb and Cr planes of an NV12 buffer
+ fn planes(pb: &Cf) -> (usize, usize, Vec<u8>, Vec<u8>, Vec<u8>) {
+ unsafe {
+ CVPixelBufferLockBaseAddress(pb.ptr(), 1);
+ let (w, h) = (CVPixelBufferGetWidth(pb.ptr()), CVPixelBufferGetHeight(pb.ptr()));
+ let (y, ys) =
+ (CVPixelBufferGetBaseAddressOfPlane(pb.ptr(), 0), CVPixelBufferGetBytesPerRowOfPlane(pb.ptr(), 0));
+ let (uv, uvs) =
+ (CVPixelBufferGetBaseAddressOfPlane(pb.ptr(), 1), CVPixelBufferGetBytesPerRowOfPlane(pb.ptr(), 1));
+ let mut yy = Vec::with_capacity(w * h);
+ for r in 0..h {
+ yy.extend_from_slice(std::slice::from_raw_parts(y.add(r * ys), w));
+ }
+ let (cw, ch) = (w / 2, h / 2);
+ let (mut u, mut v) = (Vec::with_capacity(cw * ch), Vec::with_capacity(cw * ch));
+ for r in 0..ch {
+ let row = std::slice::from_raw_parts(uv.add(r * uvs), cw * 2);
+ for p in row.as_chunks::<2>().0 {
+ u.push(p[0]);
+ v.push(p[1]);
+ }
+ }
+ CVPixelBufferUnlockBaseAddress(pb.ptr(), 1);
+ (w, h, yy, u, v)
+ }
+ }
+
+ /// SSIM of one plane the way ffmpeg's `ssim` filter computes it: 8×8 windows every 4 pixels
+ fn ssim(a: &[u8], b: &[u8], w: usize, h: usize) -> f64 {
+ const C1: f64 = 0.01 * 0.01 * 255.0 * 255.0;
+ const C2: f64 = 0.03 * 0.03 * 255.0 * 255.0;
+ let (mut total, mut n) = (0.0, 0usize);
+ let mut y = 0;
+ while y + 8 <= h {
+ let mut x = 0;
+ while x + 8 <= w {
+ let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0f64, 0f64, 0f64, 0f64, 0f64);
+ for r in y..y + 8 {
+ for c in x..x + 8 {
+ let (p, q) = (f64::from(a[r * w + c]), f64::from(b[r * w + c]));
+ sa += p;
+ sb += q;
+ saa += p * p;
+ sbb += q * q;
+ sab += p * q;
+ }
+ }
+ let (ma, mb) = (sa / 64.0, sb / 64.0);
+ let (va, vb, cov) = (saa / 64.0 - ma * ma, sbb / 64.0 - mb * mb, sab / 64.0 - ma * mb);
+ total += ((2.0 * ma * mb + C1) * (2.0 * cov + C2)) / ((ma * ma + mb * mb + C1) * (va + vb + C2));
+ n += 1;
+ x += 4;
+ }
+ y += 4;
+ }
+ total / n.max(1) as f64
+ }
+
+ fn pct(v: &mut [f64], p: f64) -> f64 {
+ v.sort_by(f64::total_cmp);
+ v[((v.len() - 1) as f64 * p).round() as usize]
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn measure_recording() {
+ let dir = std::env::var("ICTL_RECORDING").expect("ICTL_RECORDING=<dir of <ms>.jpg>");
+ let mut files: Vec<(u64, std::path::PathBuf)> = std::fs::read_dir(&dir)
+ .unwrap()
+ .flatten()
+ .filter_map(|e| {
+ let p = e.path();
+ let ms = p.file_stem()?.to_str()?.parse().ok()?;
+ (p.extension()? == "jpg").then_some((ms, p))
+ })
+ .collect();
+ files.sort();
+ let frames: Vec<(u64, Arc<Vec<u8>>)> =
+ files.iter().map(|(ms, p)| (*ms, Arc::new(std::fs::read(p).unwrap()))).collect();
+ let size = super::super::mjpeg::jpeg_size(&frames[0].1).unwrap();
+ let frames: Vec<_> =
+ frames.into_iter().filter(|(_, j)| super::super::mjpeg::jpeg_size(j) == Some(size)).collect();
+ let span = frames.last().unwrap().0 - frames[0].0;
+ let jpeg_bytes: usize = frames.iter().map(|(_, j)| j.len()).sum();
+ eprintln!(
+ "recording: {} frames of {}x{} over {:.1} s; MJPEG (repeats dropped) {:.0} KB/s on average",
+ frames.len(),
+ size.0,
+ size.1,
+ span as f64 / 1000.0,
+ jpeg_bytes as f64 / 1024.0 / (span as f64 / 1000.0)
+ );
+ let qps: Vec<u8> = std::env::var("ICTL_QPS")
+ .unwrap_or_else(|_| "20".into())
+ .split(',')
+ .filter_map(|q| q.trim().parse().ok())
+ .collect();
+ for qp in qps {
+ let (itx, irx) = tokio::sync::oneshot::channel();
+ let mut s = Session::start(size.0, size.1, qp, 0, Some(itx));
+ let info = irx.await.unwrap();
+ let mut reference = Decoder::new(size.0, size.1).unwrap();
+ let mut avcc = Vec::new();
+ let mut page: Option<Decoder> = None;
+ let (mut ssims, mut ssims_y, mut times, mut sizes) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ let mut per_second: BTreeMap<u64, (usize, usize)> = BTreeMap::new();
+ let mut keys = 0;
+ for (ms, j) in &frames {
+ let t = Instant::now();
+ s.push(j.clone());
+ let (key, data) = loop {
+ match s.next().await.unwrap().unwrap() {
+ Packet::Config(c) => avcc = c,
+ Packet::Frame { key, data } => break (key, data),
+ }
+ };
+ times.push(t.elapsed().as_secs_f64() * 1000.0);
+ sizes.push(data.len() as f64);
+ keys += usize::from(key);
+ let e = per_second.entry((ms - frames[0].0) / 1000).or_default();
+ e.0 += data.len();
+ e.1 += j.len();
+ let dec = page.get_or_insert_with(|| h264_decoder(&avcc, even(size)));
+ let shown = planes(&dec.decode(&data).unwrap());
+ let given = planes(&reference.decode(j).unwrap());
+ let (w, h) = (shown.0, shown.1);
+ let sy = ssim(&given.2, &shown.2, w, h);
+ let su = ssim(&given.3, &shown.3, w / 2, h / 2);
+ let sv = ssim(&given.4, &shown.4, w / 2, h / 2);
+ ssims_y.push(sy);
+ // ffmpeg's "All" for 4:2:0
+ ssims.push((4.0 * sy + su + sv) / 6.0);
+ }
+ let rates: Vec<String> = per_second
+ .iter()
+ .map(|(sec, (h264, jpeg))| format!("{sec}s {}/{}", h264 / 1024, jpeg / 1024))
+ .collect();
+ let mut busy: Vec<f64> = per_second.values().map(|(b, _)| *b as f64 / 1024.0).collect();
+ let total: usize = sizes.iter().map(|s| *s as usize).sum();
+ eprintln!("\nqp {qp} ({info:?})");
+ eprintln!(
+ " H.264 {:.0} KB in all = {:.1}% of MJPEG; {:.0} KB/s on average, per second median {:.0} max {:.0} KB/s",
+ total as f64 / 1024.0,
+ 100.0 * total as f64 / jpeg_bytes as f64,
+ total as f64 / 1024.0 / (span as f64 / 1000.0),
+ pct(&mut busy.clone(), 0.5),
+ pct(&mut busy, 1.0)
+ );
+ eprintln!(
+ " frames {} ({} key), bytes median {:.0} p90 {:.0} max {:.0}",
+ sizes.len(),
+ keys,
+ pct(&mut sizes.clone(), 0.5),
+ pct(&mut sizes.clone(), 0.9),
+ pct(&mut sizes, 1.0)
+ );
+ eprintln!(
+ " SSIM all median {:.4} p10 {:.4} min {:.4}; Y median {:.4} min {:.4}",
+ pct(&mut ssims.clone(), 0.5),
+ pct(&mut ssims.clone(), 0.1),
+ pct(&mut ssims, 0.0),
+ pct(&mut ssims_y.clone(), 0.5),
+ pct(&mut ssims_y, 0.0)
+ );
+ eprintln!(
+ " push to frame: median {:.1} ms, p90 {:.1}, max {:.1}",
+ pct(&mut times.clone(), 0.5),
+ pct(&mut times.clone(), 0.9),
+ pct(&mut times, 1.0)
+ );
+ eprintln!(" KB/s H.264/MJPEG each second: {}", rates.join(", "));
+ }
+ }
+}
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 5b83ca6..d6f6baf 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -357,7 +357,7 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }
.frame[data-kind="ipad"] { --pad: 14px; border-radius: 34px; }
.frame[data-kind="ipad"] .stage { border-radius: 20px; }
.stage > * { grid-area: 1 / 1; }
-.stage img { width: 100%; height: 100%; object-fit: contain; display: block; -webkit-user-drag: none; }
+.stage img, .stage canvas { width: 100%; height: 100%; object-fit: contain; display: block; -webkit-user-drag: none; }
.stage-msg { place-self: center; padding: var(--sp-6); color: #d4d7dc; text-align: center; font-size: var(--fs-sm); max-width: 34ch; }
.stage-msg code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.92em; color: #fff; overflow-wrap: anywhere; }
.stage-msg .btn { margin-top: var(--sp-3); }
@@ -739,6 +739,7 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }
<div class="frame" id="frame" data-ctl="user">
<div class="stage" id="stage" role="group" aria-label="设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按" aria-describedby="status">
<img id="live" alt="设备的实时画面" draggable="false" hidden>
+ <canvas id="live-v" aria-label="设备的实时画面" hidden></canvas>
<div id="demo" class="ph" aria-hidden="true" hidden></div>
<svg id="marks" class="marks" viewBox="0 0 393 852" aria-hidden="true"></svg>
<div class="stage-msg" id="stage-msg">正在连接 iphone-control 服务…</div>
@@ -983,6 +984,12 @@ const badge = st => `<span class="badge tone-${st.tone}">${icon(st.icon, st.icon
const shell = $('#shell'), stage = $('#stage'), frame = $('#frame'), live = $('#live'), demoEl = $('#demo'), marks = $('#marks'), stageMsg = $('#stage-msg');
const statusEl = $('#status'), promptEl = $('#prompt'), promptErr = $('#prompt-error'), typeEl = $('#type-text');
const turnsEl = $('#turns'), stopDialog = $('#stop-dialog'), deviceEl = $('#device');
+/* 实时画面:H.264 画在 canvas 上(见「H.264 画面」),否则是 MJPEG 的 img */
+const cv = $('#live-v'), cvx = cv.getContext('2d');
+const V = { on: false, off: false, noDevice: false, device: false, crop: false, rot: 0, codecName: '', ctrl: null, dec: null, got: false, label: '', ts: 0, bytes: 0, rate: null, stream: '', recv: 0, acked: 0, acking: false };
+const picEl = () => V.on ? cv : live;
+const picW = () => V.on ? cv.width : live.naturalWidth;
+const picH = () => V.on ? cv.height : live.naturalHeight;
const S = {
mode: 'detecting', // detecting | live | demo
@@ -1190,7 +1197,7 @@ function demoElements() {
function dims() {
if (S.mode === 'demo') return { W: DW(), H: DH() };
if (!S.size) return null;
- const land = live.naturalWidth > live.naturalHeight;
+ const land = picW() > picH();
return land ? { W: S.size.h, H: S.size.w } : { W: S.size.w, H: S.size.h };
}
function setRatio(w, h) {
@@ -1209,9 +1216,9 @@ function toPoints(cx, cy) {
const d = dims(); if (!d) return null;
const r = stage.getBoundingClientRect();
let w = r.width, h = r.height, ox = 0, oy = 0;
- if (S.mode === 'live' && live.naturalWidth) {
- const sc = Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight);
- w = live.naturalWidth * sc; h = live.naturalHeight * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;
+ if (S.mode === 'live' && picW()) {
+ const sc = Math.min(r.width / picW(), r.height / picH());
+ w = picW() * sc; h = picH() * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;
}
const fx = (cx - r.left - ox) / w, fy = (cy - r.top - oy) / h;
if (fx < 0 || fx > 1 || fy < 0 || fy > 1) return null;
@@ -1295,9 +1302,9 @@ function clampPoint(cx, cy) {
const d = dims(); if (!d) return null;
const r = stage.getBoundingClientRect();
let w = r.width, h = r.height, ox = 0, oy = 0;
- if (S.mode === 'live' && live.naturalWidth) {
- const sc = Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight);
- w = live.naturalWidth * sc; h = live.naturalHeight * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;
+ if (S.mode === 'live' && picW()) {
+ const sc = Math.min(r.width / picW(), r.height / picH());
+ w = picW() * sc; h = picH() * sc; ox = (r.width - w) / 2; oy = (r.height - h) / 2;
}
const fx = Math.min(1, Math.max(0, (cx - r.left - ox) / w)), fy = Math.min(1, Math.max(0, (cy - r.top - oy) / h));
return { x: round1(fx * d.W), y: round1(fy * d.H) };
@@ -1306,7 +1313,7 @@ function clampPoint(cx, cy) {
function pointsPerPx() {
const d = dims(), r = stage.getBoundingClientRect();
if (!d || !r.width) return 1;
- if (S.mode === 'live' && live.naturalWidth) return d.W / (live.naturalWidth * Math.min(r.width / live.naturalWidth, r.height / live.naturalHeight));
+ if (S.mode === 'live' && picW()) return d.W / (picW() * Math.min(r.width / picW(), r.height / picH()));
return d.W / r.width;
}
@@ -1493,6 +1500,8 @@ typeEl.addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isCompo
* ================================================================ */
function applyInfo(v) {
S.size = v.width && v.height ? { w: v.width, h: v.height } : null;
+ S.video = v.video || null;
+ S.deviceVideo = !!v.device_video;
if (v.device) S.deviceName = v.device;
if (v.udid && S.udid && v.udid.toLowerCase() !== S.udid.toLowerCase()) { onDeviceChanged(v); return; }
if (v.udid) S.udid = v.udid;
@@ -1502,6 +1511,8 @@ function applyInfo(v) {
}
/* 守护进程控制的设备变了(本页、别的页面、命令行切换,或拔掉后自动换了一台):画面和各面板都换过去 */
function onDeviceChanged(v) {
+ // 新设备可能支持手机自己的视频(iOS 27),重新试
+ V.noDevice = false;
const mine = S.switching;
S.udid = v.udid;
// 上一台设备上按着的手指、没走完的滚动,都不能带到新设备上
@@ -1547,20 +1558,122 @@ function showStageNote() {
}
async function loadInfo() { try { applyInfo(await (await fetch('/api/info', { headers: { 'X-Ictl-Lang': LANG } })).json()); } catch { /* 跟着画面一起重试 */ } }
function connect() {
- S.stream = 'connecting'; stageMsg.textContent = tr('正在连接画面…'); delete stageMsg.dataset.note; stageMsg.hidden = false; live.hidden = false;
- live.src = `/stream?${S.udid ? `udid=${encodeURIComponent(S.udid)}&` : ''}t=${Date.now()}`; renderFeed(); renderChips();
+ S.stream = 'connecting'; stageMsg.textContent = tr('正在连接画面…'); delete stageMsg.dataset.note; stageMsg.hidden = false;
+ stopVideo();
+ const q = `${S.udid ? `udid=${encodeURIComponent(S.udid)}&` : ''}t=${Date.now()}`;
+ // 先试手机自己编的视频(iOS 27,HEVC),再试本机编的 H.264,都不行用 MJPEG
+ const dev = S.deviceVideo && !V.noDevice;
+ if ((dev || (S.video && !V.off)) && 'VideoDecoder' in window) {
+ V.on = true; live.hidden = true; live.removeAttribute('src'); cv.hidden = false; startVideo(q, dev);
+ } else {
+ cv.hidden = true; live.hidden = false; live.src = `/stream?${q}`;
+ }
+ renderFeed(); renderChips();
}
-live.addEventListener('load', () => {
- if (S.mode !== 'live') return;
- S.stream = 'ok'; stageMsg.hidden = true; live.style.visibility = ''; setRatio(live.naturalWidth, live.naturalHeight); syncMarksBox(); renderFeed(); renderChips();
-});
-live.addEventListener('error', () => {
- if (S.mode !== 'live') return;
- S.stream = 'error'; live.style.visibility = 'hidden'; showStageNote();
+/* 有画面了(第一帧、尺寸变了):和 MJPEG 的 load 一样处理 */
+function streamOk() {
+ S.stream = 'ok'; stageMsg.hidden = true; picEl().style.visibility = ''; setRatio(picW(), picH()); syncMarksBox(); renderFeed(); renderChips();
+}
+function streamLost() {
+ S.stream = 'error'; picEl().style.visibility = 'hidden'; showStageNote();
renderFeed(); renderChips(); loadDeviceState();
// 换了设备时 loadInfo 自己会重连;没换就重试这一台
setTimeout(async () => { const u = S.udid; await loadInfo(); if (S.udid === u) connect(); }, 3000);
-});
+}
+live.addEventListener('load', () => { if (S.mode === 'live' && !V.on) streamOk(); });
+live.addEventListener('error', () => { if (S.mode === 'live' && !V.on && live.getAttribute('src')) streamLost(); });
+
+/* ---------- H.264 画面:服务端用 ffmpeg 编码(硬件优先),这里用 WebCodecs 解码(浏览器自己选硬件)画到 canvas。
+ * 消息:1 字节类型 + 4 字节长度 + 内容。0 是解码配置(JSON),1 关键帧,2 其他帧。
+ * 这一页从没出过画面就失败(没有编码器、浏览器解不了)就改用 MJPEG,之后不再试 ---------- */
+function stopVideo() {
+ if (V.ctrl) V.ctrl.abort();
+ V.ctrl = null; V.on = false; V.got = false; V.rate = null; V.stream = ''; V.recv = 0; V.acked = 0; V.acking = false;
+ V.device = false; V.crop = false; V.rot = 0; V.codecName = '';
+ if (V.dec && V.dec.state !== 'closed') { try { V.dec.close(); } catch { /* 已经关了 */ } }
+ V.dec = null;
+}
+async function startVideo(q, dev) {
+ const ctrl = new AbortController(); V.ctrl = ctrl;
+ const ended = permanent => {
+ if (V.ctrl !== ctrl) return; // 已经换了一条连接
+ const got = V.got;
+ stopVideo();
+ // 这一路从没出过画面就走不通:手机的视频走不通改用本机编码,本机编码也不行改用 MJPEG,之后不再试
+ if (permanent && !got) { if (dev) V.noDevice = true; else V.off = true; connect(); return; }
+ streamLost();
+ };
+ const onFrame = f => {
+ if (V.ctrl !== ctrl) { f.close(); return; }
+ // 手机的视频是竖放的帧缓冲,宽高补到 16 的倍数(1320×2868 编成 1328×2896):裁掉补的边,再按界面方向转正
+ let sw = f.displayWidth, sh = f.displayHeight;
+ if (V.crop && S.size) {
+ const pw = Math.min(S.size.w, S.size.h), ph = Math.max(S.size.w, S.size.h), k = Math.round(sw / pw) || 1;
+ sw = Math.min(sw, Math.round(pw * k)); sh = Math.min(sh, Math.round(ph * k));
+ }
+ const r = V.crop ? V.rot : 0, turned = r === 90 || r === 270;
+ const W = turned ? sh : sw, H = turned ? sw : sh;
+ const resized = cv.width !== W || cv.height !== H;
+ if (resized) { cv.width = W; cv.height = H; }
+ if (r) {
+ cvx.save(); cvx.translate(W / 2, H / 2); cvx.rotate(r * Math.PI / 180); // r:竖放的顶边顺时针转过的角度,画面同向转回来
+ cvx.drawImage(f, 0, 0, sw, sh, -sw / 2, -sh / 2, sw, sh); cvx.restore();
+ } else cvx.drawImage(f, 0, 0, sw, sh, 0, 0, sw, sh);
+ f.close();
+ if (!V.got || resized) { V.got = true; streamOk(); }
+ };
+ try {
+ const r = await fetch(`/video?${q}${dev ? '&src=device' : ''}`, { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } });
+ if (!r.ok || !r.body) return ended(r.status === 404);
+ const rd = r.body.getReader();
+ let buf = new Uint8Array(0);
+ for (;;) {
+ const { value, done } = await rd.read();
+ if (done) return ended(false);
+ V.bytes += value.length; V.recv += value.length;
+ const n = new Uint8Array(buf.length + value.length); n.set(buf); n.set(value, buf.length); buf = n;
+ while (buf.length >= 5) {
+ const len = ((buf[1] << 24) | (buf[2] << 16) | (buf[3] << 8) | buf[4]) >>> 0;
+ if (buf.length < 5 + len) break;
+ const kind = buf[0], body = buf.slice(5, 5 + len);
+ buf = buf.slice(5 + len);
+ if (kind === 0) {
+ const c = JSON.parse(new TextDecoder().decode(body));
+ // 手机的 HEVC 是 Annex-B(参数集在关键帧里),不带 description
+ const config = c.annexb ? { codec: c.codec, optimizeForLatency: true }
+ : { codec: c.codec, description: Uint8Array.from(c.description.match(/../g) || [], h => parseInt(h, 16)), optimizeForLatency: true };
+ V.device = !!c.annexb; V.crop = !!c.annexb; V.codecName = /^(hvc|hev)/.test(c.codec) ? 'HEVC' : 'H.264';
+ let ok = false;
+ try { ok = (await VideoDecoder.isConfigSupported(config)).supported; } catch { /* 当作不支持 */ }
+ if (!ok) return ended(true);
+ if (V.ctrl !== ctrl) return;
+ if (!V.dec) V.dec = new VideoDecoder({ output: onFrame, error: () => ended(false) });
+ V.dec.configure(config); V.label = c.encoder || ''; V.stream = c.stream || '';
+ } else if (kind === 3) {
+ // 手机的视频:界面转了多少度(竖放的顶边顺时针转过去的角度),下一帧按它转正
+ try { const i = JSON.parse(new TextDecoder().decode(body)); if (typeof i.rotation === 'number') V.rot = i.rotation; } catch { /* 忽略 */ }
+ } else if (V.dec && V.dec.state === 'configured') {
+ V.dec.decode(new EncodedVideoChunk({ type: kind === 1 ? 'key' : 'delta', timestamp: V.ts += 40000, data: body }));
+ }
+ }
+ }
+ } catch {
+ if (!ctrl.signal.aborted) ended(!V.got);
+ }
+}
+/* 每秒算一次 H.264 画面的流量,显示在画面下方 */
+setInterval(() => { if (V.on) { V.rate = V.bytes; V.bytes = 0; renderFeed(); } }, 1000);
+/* 告诉服务端读到了多少:链路慢、隧道里堆了数据时,它据此少编几帧,画面不会越来越滞后。
+ * 服务端收到才算报过,丢了的下一轮再报(不然它会一直等这次回报) */
+setInterval(() => {
+ if (!V.on || !V.stream || V.recv === V.acked || V.acking) return;
+ const stream = V.stream, bytes = V.recv;
+ V.acking = true;
+ fetch('/api/video/ack', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ stream, bytes }) })
+ .then(r => { if (r.ok && V.stream === stream) V.acked = Math.max(V.acked, bytes); })
+ .catch(() => {})
+ .finally(() => { V.acking = false; });
+}, 100);
function renderFeed() {
const dot = $('#feed-dot'), txt = $('#feed-text');
dot.className = 'feed-dot';
@@ -1568,7 +1681,8 @@ function renderFeed() {
if (S.mode === 'detecting' || S.stream === 'connecting') { dot.classList.add('wait'); txt.textContent = tr('正在连接画面…'); return; }
if (S.stream === 'error') { dot.classList.add('off'); txt.textContent = tr('画面断开 · 自动重试中'); return; }
const route = S.dstatus?.route === 'hid' ? tr('HID 后备') : 'WDA';
- txt.textContent = `${tr('实时画面')} · ${route}${S.rtt != null ? ` · ${tr('操作往返')} ${S.rtt} ms` : ''}`;
+ 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` : ''}`;
}
/* ================================================================
@@ -2318,7 +2432,7 @@ async function detect() {
setInterval(() => { loadInfo(); loadDeviceState(); }, 10000);
} catch {
S.mode = 'demo'; S.stream = 'ok';
- stageMsg.hidden = true; live.hidden = true; demoEl.hidden = false; $('#demo-note').hidden = false;
+ stageMsg.hidden = true; live.hidden = true; cv.hidden = true; demoEl.hidden = false; $('#demo-note').hidden = false;
applyDemoGeometry(); renderDemo();
show(tr('演示模式:没有连上 iphone-control 服务,画面是本地模拟的。'));
}
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index ea86c69..d69db1c 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -1,7 +1,9 @@
//! `iphone-control viewer`: a page on 127.0.0.1 to watch the phone live, act on it with the mouse, look at its
//! state, apps and elements, and hand tasks to a local AI agent (see [`crate::agent`]).
//!
-//! - `GET /` the page, `GET /stream` WDA's MJPEG stream (port 9100 on the phone, over usbmuxd, read-only).
+//! - `GET /` the page, `GET /stream` WDA's MJPEG stream (port 9100 on the phone, over usbmuxd, read-only; repeated
+//! frames dropped), `GET /video` the same frames as H.264 when ffmpeg can encode them ([`crate::video`]), about
+//! 1/15 of the traffic.
//! - `GET /api/{info,daemon,status,devices,apps,elements}`: the daemon's answers as JSON for the page.
//! - `POST /api/{tap,swipe,long_press,type,button,launch_app,terminate_app,open_url,tap_element,wait_for,select}`
//! turn into ordinary daemon requests, so they queue with an agent's calls, get auto-unlock and follow the
@@ -56,6 +58,10 @@ struct Ctx {
agents: Arc<Agents>,
/// Bundle id → display name, for the foreground app
names: tokio::sync::Mutex<HashMap<String, String>>,
+ /// H.264 for the picture; `None`: MJPEG only
+ video: Option<Arc<crate::video::Encoders>>,
+ /// How much of each H.264 stream its page has read
+ acks: Arc<crate::video::Acks>,
}
impl Ctx {
@@ -95,6 +101,32 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
if udid.is_empty() { ictl_l10n::tr!("跟随守护进程", "whichever the daemon controls") } else { &udid }
)
);
+ if crate::video::device_allowed() {
+ println!(
+ "{}",
+ ictl_l10n::tr!(
+ "画面:iOS 27 及以上直接用手机自己编的视频(HEVC,约 60 帧/秒,本机不编码);浏览器解不了 HEVC 或更早的系统用下面这种",
+ "Picture: on iOS 27 and later the phone's own video (HEVC, about 60 fps, nothing encoded here); browsers that can't decode HEVC and older systems get the one below"
+ )
+ );
+ }
+ let video = match crate::video::Encoders::detect().await {
+ Ok(e) => {
+ println!("{}", ictl_l10n::trf!("画面编码:H.264,{}", "Picture: H.264, {}", e.describe()));
+ println!(
+ "{}",
+ ictl_l10n::tr!(
+ " 浏览器不支持 WebCodecs 时自动改用 MJPEG;改设置见 IPHONE_CONTROL_VIEWER_CODEC、IPHONE_CONTROL_VIEWER_QP",
+ " Browsers without WebCodecs get MJPEG; settings: IPHONE_CONTROL_VIEWER_CODEC, IPHONE_CONTROL_VIEWER_QP"
+ )
+ );
+ Some(e)
+ }
+ Err(why) => {
+ println!("{}", ictl_l10n::trf!("画面编码:MJPEG({why})", "Picture: MJPEG ({why})"));
+ None
+ }
+ };
let found: Vec<&str> =
agent::Backend::ALL.iter().filter(|b| b.find().is_some()).map(|b| b.id()).collect::<Vec<_>>();
println!(
@@ -124,6 +156,8 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
agents,
names: tokio::sync::Mutex::default(),
page: page_in(ictl_l10n::lang()),
+ video,
+ acks: Arc::default(),
});
let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));
loop {
@@ -168,7 +202,39 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
let path = req.path.as_str();
match (req.method.as_str(), path) {
("GET", "/") => reply(&mut client, 200, "text/html; charset=utf-8", ctx.page.as_bytes()).await,
- ("GET", "/stream") => {
+ // the phone's own screen video (iOS 27 and later), see `crate::video::device`
+ ("GET", "/video") if req.query("src").as_deref() == Some("device") => {
+ if !crate::video::device_allowed() {
+ return reply(&mut client, 404, "text/plain", b"turned off by IPHONE_CONTROL_VIEWER_CODEC").await;
+ }
+ let udid = req.query("udid").filter(|u| !u.is_empty()).unwrap_or_else(|| ctx.udid());
+ if udid.is_empty() {
+ return reply(&mut client, 503, "text/plain", b"no device yet").await;
+ }
+ match crate::video::device::open(&ctx.socket, &udid).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)) => {
+ client
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nCache-Control: no-store\r\n\
+ X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n",
+ )
+ .await?;
+ crate::video::device::serve(src, w, ctx.acks.clone(), client).await;
+ Ok(())
+ }
+ }
+ }
+ ("GET", "/stream" | "/video") => {
+ let video = if path == "/video" {
+ match ctx.video.clone().filter(|e| e.label().is_some()) {
+ Some(e) => Some(e),
+ None => return reply(&mut client, 404, "text/plain", b"no H.264 encoder").await,
+ }
+ } else {
+ None
+ };
// the device the page shows (`?udid=`), so a page that hasn't noticed a switch keeps its own picture
// instead of silently showing another phone. Looked up again each time: after a replug usbmuxd gives the
// device a new id
@@ -183,7 +249,18 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
};
// WDA's MJPEG server answers any request with the multipart stream
remote.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").await?;
- tokio::io::copy_bidirectional(&mut client, &mut remote).await?;
+ match video {
+ Some(enc) => {
+ client
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nCache-Control: no-store\r\n\
+ X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n",
+ )
+ .await?;
+ crate::video::serve(enc, ctx.acks.clone(), remote, client).await;
+ }
+ None => crate::video::serve_mjpeg(remote, client).await,
+ }
Ok(())
}
("GET", p) if p.starts_with("/api/agent/tasks/") && p.ends_with("/events") => {
@@ -244,6 +321,14 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
/// `device`: the one the page shows (`X-Ictl-Device`); actions only go to it
async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, Value) {
let conflict = |m: String| (409, json!({"ok": false, "message": m}));
+ // how much of an H.264 stream the page has read (see `crate::video`)
+ if name == "video/ack" {
+ let ok = match (b["stream"].as_str(), b["bytes"].as_u64()) {
+ (Some(id), Some(n)) => ctx.acks.report(id, n),
+ _ => false,
+ };
+ return (if ok { 200 } else { 404 }, json!({"ok": ok}));
+ }
if name == "agent/tasks" {
let prompt = b["prompt"].as_str().unwrap_or_default();
let backend = b["agent"].as_str().unwrap_or("claude");
@@ -551,14 +636,19 @@ async fn info(ctx: &Ctx) -> Result<Value, String> {
}
let udid = ctx.udid();
let screen = screen_of(&s.persisted, &udid);
+ let live_touch = s.device.as_ref().is_some_and(|d| d.major_version() >= 27);
Ok(json!({
"width": screen.map(|s| s.width),
"height": screen.map(|s| s.height),
"udid": udid,
// the picture's pointer drives a finger over CoreDevice HID (iOS 27 and later); older phones get whole gestures
- "live_touch": s.device.as_ref().is_some_and(|d| d.major_version() >= 27),
+ "live_touch": live_touch,
"device": s.device.map(|d| d.name),
"state": state_of(&s.state).0,
+ // the picture as H.264 (`/video`) and with which encoder; null: MJPEG only
+ "video": ctx.video.as_ref().and_then(|e| e.label()),
+ // the phone's own screen video can be tried (`/video?src=device`): iOS 27 and later, not turned off
+ "device_video": crate::video::device_allowed() && live_touch,
}))
}
diff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rs
index cf81651..a288f4e 100644
--- a/crates/ictl-daemon/src/config.rs
+++ b/crates/ictl-daemon/src/config.rs
@@ -49,6 +49,20 @@ pub fn env(k: &str) -> Option<String> {
std::env::var(k).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
}
+/// Where to look for ffmpeg (the viewer's H.264 picture; on macOS only the fallback for the native VideoToolbox
+/// encoder), in order: `ICTL_FFMPEG`, else `ffmpeg` on `PATH` and, on macOS, Homebrew's places (a launchd service
+/// doesn't have them on its `PATH`)
+pub fn ffmpeg_paths() -> Vec<PathBuf> {
+ if let Some(p) = env("ICTL_FFMPEG") {
+ return vec![PathBuf::from(p)];
+ }
+ let mut v = vec![PathBuf::from("ffmpeg")];
+ if cfg!(target_os = "macos") {
+ v.extend(["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"].map(PathBuf::from));
+ }
+ v
+}
+
fn wda_unsigned_cache(data_dir: &Path) -> PathBuf {
data_dir.join("wda/WDA-unsigned.ipa")
}
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index e55cc9b..3676571 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -272,6 +272,9 @@ pub(crate) struct Inner {
pub offline_since: Option<Instant>,
/// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流)
pub hid_used: Option<Instant>,
+ /// 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,
/// 最近一次读到的元素树。只在调用方允许(max_age_ms)时复用;改变界面的操作做完就清掉
pub elements_cache: Option<(Instant, ictl_wda::elements::Tree)>,
/// 滑动等列表停下时最后读到的树([`crate::tools`] 的 `settle` 拿来当比较的起点)
@@ -380,6 +383,7 @@ impl Daemon {
list_errors: 0,
offline_since: Some(now),
hid_used: None,
+ screen_viewers: 0,
elements_cache: None,
swiped_tree: None,
dedup: Dedup::default(),
@@ -657,6 +661,10 @@ impl Daemon {
let mut outcome = crate::protocol::Outcome::default();
let r = match req {
Request::Status => Ok(self.status_text(g).await),
+ // streams on its own connection (`lib::serve_conn` hands it to `screen::stream`); never queued here
+ Request::ScreenStream => {
+ Err("screen_stream is a streaming request: open it with open_screen_stream".into())
+ }
Request::Screenshot { region } => {
let resp = self.screenshot(g, region).await.unwrap_or_else(Response::error);
self.publish(g);
@@ -751,6 +759,7 @@ fn lane(req: &Request) -> Lane {
Request::WebTargets | Request::WebEval { .. } => Lane::Web,
Request::InstallApp { .. } => Lane::Install,
Request::Status
+ | Request::ScreenStream
| Request::Screenshot { .. }
| Request::ListElements { .. }
| Request::Tap { .. }
diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rs
index d35d254..a5a4e89 100644
--- a/crates/ictl-daemon/src/doctor.rs
+++ b/crates/ictl-daemon/src/doctor.rs
@@ -265,6 +265,7 @@ impl Daemon {
.into(),
);
}
+ out.push(viewer_picture().await);
out.push(String::new());
out.push(if fails == 0 {
ictl_l10n::tr!("全部正常", "All good").into()
@@ -275,6 +276,68 @@ impl Daemon {
}
}
+/// 控制台(`iphone-control viewer`)的画面能不能用 H.264:macOS 上本程序直接调 VideoToolbox,不用 ffmpeg;
+/// 其他系统要有 ffmpeg,Linux 上用显卡编码还要能打开 `/dev/dri/renderD*`(`render` 组)。只看前提,不试编码:
+/// 用哪个编码器,`viewer` 启动时会说
+async fn viewer_picture() -> String {
+ if crate::config::env("IPHONE_CONTROL_VIEWER_CODEC").is_some_and(|v| v.eq_ignore_ascii_case("mjpeg")) {
+ return ictl_l10n::tr!(
+ "✅ 控制台画面按设置用 MJPEG(IPHONE_CONTROL_VIEWER_CODEC=mjpeg)",
+ "✅ Viewer picture uses MJPEG as set (IPHONE_CONTROL_VIEWER_CODEC=mjpeg)"
+ )
+ .into();
+ }
+ if cfg!(target_os = "macos") {
+ return ictl_l10n::tr!(
+ "✅ 控制台画面用 H.264(VideoToolbox,本程序直接调用,不需要 ffmpeg)",
+ "✅ The viewer's picture uses H.264 (VideoToolbox, called directly, no ffmpeg needed)"
+ )
+ .into();
+ }
+ let mut version = None;
+ for p in crate::config::ffmpeg_paths() {
+ let run = tokio::process::Command::new(&p).arg("-version").stdin(std::process::Stdio::null()).output();
+ if let Ok(Ok(o)) = tokio::time::timeout(Duration::from_secs(5), run).await
+ && o.status.success()
+ {
+ let line = String::from_utf8_lossy(&o.stdout).lines().next().unwrap_or_default().to_owned();
+ version = Some(line.split_whitespace().nth(2).unwrap_or("?").to_owned());
+ break;
+ }
+ }
+ let Some(version) = version else {
+ return ictl_l10n::trf!(
+ "⚠️ 没找到 ffmpeg 控制台画面用 MJPEG,流量约为 H.264 的 15 倍,走外网会卡(可选:{})",
+ "⚠️ ffmpeg not found the viewer's picture uses MJPEG, about 15 times the traffic of H.264, which stutters over the internet (optional: {})",
+ if cfg!(target_os = "macos") { "brew install ffmpeg" } else { "sudo apt install ffmpeg" }
+ );
+ };
+ if cfg!(target_os = "linux") {
+ let nodes: Vec<std::path::PathBuf> = std::fs::read_dir("/dev/dri")
+ .map(|d| {
+ d.flatten()
+ .map(|e| e.path())
+ .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("renderD")))
+ .collect()
+ })
+ .unwrap_or_default();
+ let usable = nodes.iter().any(|n| std::fs::OpenOptions::new().read(true).write(true).open(n).is_ok());
+ if !nodes.is_empty() && !usable {
+ return ictl_l10n::trf!(
+ "⚠️ ffmpeg {version} 在,但打不开显卡({}),控制台画面只能用 CPU 编码
+ → sudo usermod -aG render $USER,重新登录后生效",
+ "⚠️ ffmpeg {version} is there, but the GPU ({}) can't be opened, so the viewer's picture is encoded on the CPU
+ → sudo usermod -aG render $USER, then log in again",
+ nodes[0].display()
+ );
+ }
+ }
+ ictl_l10n::trf!(
+ "✅ 控制台画面可用 H.264(ffmpeg {version};用哪个编码器,运行 viewer 时显示)",
+ "✅ The viewer's picture can use H.264 (ffmpeg {version}; the encoder is shown when viewer starts)"
+ )
+}
+
/// 多久以前,粗到分钟、小时
fn ago(d: Duration) -> String {
let m = d.as_secs() / 60;
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index b912ac2..c6975a6 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -14,6 +14,7 @@ pub mod eventlog;
pub mod imaging;
pub mod machine;
pub mod notify;
+mod screen;
mod supervise;
mod tools;
mod watchdog;
@@ -123,6 +124,12 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
protocol::Response::error(ictl_l10n::tr!("请求太长", "request too long"))
} else {
match parse_request(&line) {
+ // streams until either side closes: the connection is the stream's from here on
+ Ok((protocol::Request::ScreenStream, _, expect_udid, lang)) => {
+ let w = w;
+ ictl_l10n::scope(lang, daemon.screen_stream(reader, w, expect_udid)).await;
+ return;
+ }
Ok((req, false, expect_udid, lang)) => {
let handling = daemon.handle(req, queued_at, core::CallCtx { gone: None, expect_udid });
ictl_l10n::scope(lang, handling).await
diff --git a/crates/ictl-daemon/src/screen.rs b/crates/ictl-daemon/src/screen.rs
new file mode 100644
index 0000000..1368b24
--- /dev/null
+++ b/crates/ictl-daemon/src/screen.rs
@@ -0,0 +1,195 @@
+//! The phone's own screen video for the control page ([`protocol::Request::ScreenStream`]).
+//!
+//! The CoreDevice screen media stream (iOS 27 and later) is the phone's hardware-encoded HEVC at about 60 frames a
+//! second and its native size. The HID session already owns it (HID events need it); here it is handed on:
+//! `ictl_device` turns the RTP into frames ([`ictl_device::ScreenFeed`]), this sends them to the viewer, which passes
+//! them to the page. The host encodes nothing, and WDA doesn't have to capture its MJPEG picture (at 60 frames a
+//! 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
+//! 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 tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
+use tokio::sync::broadcast::error::RecvError;
+
+use crate::core::{Daemon, hid_supported};
+use crate::protocol::{Response, SCREEN_KEYFRAME, ScreenMsg};
+
+/// How often the interface rotation is asked of WDA while streaming (about 20 ms each, only when the device lock is
+/// free)
+const ROTATION_EVERY: Duration = Duration::from_secs(1);
+
+fn degrees(r: Rotation) -> u32 {
+ match r {
+ Rotation::Portrait => 0,
+ Rotation::TopToRight => 90,
+ Rotation::UpsideDown => 180,
+ Rotation::TopToLeft => 270,
+ }
+}
+
+/// One watching page: counted while it lives, so the HID session isn't closed under it
+struct Viewer(Arc<Daemon>);
+
+impl Drop for Viewer {
+ fn drop(&mut self) {
+ let d = self.0.clone();
+ tokio::spawn(async move {
+ let mut g = d.inner.lock().await;
+ g.screen_viewers = g.screen_viewers.saturating_sub(1);
+ // the idle countdown starts now
+ g.hid_used = Some(Instant::now());
+ });
+ }
+}
+
+impl Daemon {
+ /// Serves one [`protocol::Request::ScreenStream`] connection until either side closes it
+ pub(crate) async fn screen_stream(
+ self: &Arc<Self>,
+ mut reader: tokio::io::BufReader<OwnedReadHalf>,
+ mut w: OwnedWriteHalf,
+ expect_udid: Option<String>,
+ ) {
+ let (feed, viewer) = match self.screen_feed(expect_udid.as_deref()).await {
+ Ok(f) => f,
+ Err(e) => {
+ let mut line = serde_json::to_string(&Response::error(e)).unwrap_or_default();
+ line.push('\n');
+ let _ = w.write_all(line.as_bytes()).await;
+ return;
+ }
+ };
+ let mut line = serde_json::to_string(&Response::text("streaming")).unwrap_or_default();
+ line.push('\n');
+ if w.write_all(line.as_bytes()).await.is_err() {
+ return;
+ }
+ let _viewer = viewer;
+ let mut frames = feed.subscribe();
+ feed.request_keyframe();
+ // nothing decodes before a keyframe (and the config message it brings)
+ let mut need_key = true;
+ let mut codec: Option<String> = None;
+ let mut rotation: Option<u32> = None;
+ let mut asked_rotation = Instant::now() - ROTATION_EVERY;
+ let mut tick = tokio::time::interval(Duration::from_millis(250));
+ let mut buf = [0u8; 64];
+ loop {
+ let out = tokio::select! {
+ r = frames.recv() => match r {
+ Ok(f) => {
+ if need_key && !f.key {
+ continue;
+ }
+ let mut out = Vec::new();
+ if f.key {
+ need_key = false;
+ if let Some(c) = ictl_device::hevc_codec(&f.data)
+ && codec.as_deref() != Some(c.as_str())
+ {
+ out.extend(ScreenMsg::Config.frame(serde_json::json!({ "codec": c }).to_string().as_bytes()));
+ codec = Some(c);
+ }
+ }
+ if codec.is_none() {
+ continue;
+ }
+ out.extend(if f.key { ScreenMsg::Key } else { ScreenMsg::Delta }.frame(&f.data));
+ out
+ }
+ // this connection fell more than the feed's buffer behind: go on from the next keyframe
+ Err(RecvError::Lagged(_)) => {
+ need_key = true;
+ feed.request_keyframe();
+ continue;
+ }
+ // the HID session (and its media stream) closed: the viewer reconnects
+ Err(RecvError::Closed) => return,
+ },
+ r = reader.read(&mut buf) => match r {
+ Ok(0) | Err(_) => return,
+ Ok(n) => {
+ if buf[..n].contains(&SCREEN_KEYFRAME) {
+ feed.request_keyframe();
+ }
+ continue;
+ }
+ },
+ _ = tick.tick() => {
+ // still waiting for a keyframe: ask again. One asked for right as the stream starts can be
+ // ignored by the phone, and the stream's own first keyframe may have passed before subscribing
+ if need_key {
+ feed.request_keyframe();
+ }
+ if asked_rotation.elapsed() < ROTATION_EVERY {
+ continue;
+ }
+ asked_rotation = Instant::now();
+ let Some(r) = self.current_rotation().await else { continue };
+ if rotation == Some(r) {
+ continue;
+ }
+ rotation = Some(r);
+ ScreenMsg::Info.frame(serde_json::json!({ "rotation": r }).to_string().as_bytes())
+ }
+ };
+ if w.write_all(&out).await.is_err() {
+ return;
+ }
+ }
+ }
+
+ /// The interface rotation in degrees: asked of WDA when the device lock is free, else the last one known
+ async fn current_rotation(&self) -> Option<u32> {
+ let mut g = self.inner.try_lock().ok()?;
+ self.refresh_hid_rotation(&mut g).await;
+ g.dev.wda_rotation.map(|(_, r)| degrees(r))
+ }
+
+ /// The screen feed of the controlled device, opening the HID session for it if needed
+ async fn screen_feed(
+ self: &Arc<Self>,
+ expect_udid: Option<&str>,
+ ) -> Result<(ictl_device::ScreenFeed, Viewer), String> {
+ let mut g = self.inner.lock().await;
+ let g = &mut *g;
+ let udid =
+ g.device.as_ref().map(|d| d.udid.clone()).ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ if expect_udid.is_some_and(|u| !u.eq_ignore_ascii_case(&udid)) {
+ return Err(ictl_l10n::tr!("正在控制的设备变了", "The controlled device changed").into());
+ }
+ if !hid_supported(g.info.as_ref()) {
+ return Err(
+ ictl_l10n::tr!("屏幕媒体流要 iOS 27 及以上", "The screen media stream needs iOS 27 or later").into()
+ );
+ }
+ let feed = self
+ .hid(g)
+ .await?
+ .screen_feed()
+ .ok_or(ictl_l10n::tr!("屏幕媒体流已停止", "The screen media stream stopped"))?;
+ g.screen_viewers += 1;
+ g.hid_used = Some(Instant::now());
+ Ok((feed, Viewer(self.clone())))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rotation_degrees() {
+ assert_eq!(
+ [Rotation::Portrait, Rotation::TopToRight, Rotation::UpsideDown, Rotation::TopToLeft].map(degrees),
+ [0, 90, 180, 270]
+ );
+ }
+}
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index 36f5cd3..c91ca02 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -78,7 +78,10 @@ impl Daemon {
let Ok(mut g) = self.inner.try_lock() else { return };
let g = &mut *g;
- if g.tunnel.as_ref().is_some_and(Tunnel::hid_open) && g.hid_used.is_none_or(|t| t.elapsed() >= HID_IDLE) {
+ if g.tunnel.as_ref().is_some_and(Tunnel::hid_open)
+ && g.screen_viewers == 0
+ && g.hid_used.is_none_or(|t| t.elapsed() >= HID_IDLE)
+ {
close_hid(g).await;
tracing::info!(
"{}",
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index b89b41f..6983fb9 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -120,7 +120,7 @@ impl Daemon {
}
/// HID 会话(WDA 不可用时的后备路线)。开不起来就丢掉隧道,下次重建
- async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {
+ pub(crate) async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {
// 低版本建隧道只会报 service not found:直接说清楚
if !hid_supported(g.info.as_ref()) {
return Err(wda_down(&g.state, g.info.as_ref()));
diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rs
index 793fa11..86a43e8 100644
--- a/crates/ictl-device/src/hid.rs
+++ b/crates/ictl-device/src/hid.rs
@@ -227,6 +227,11 @@ impl HidSession {
Ok(())
}
+ /// 屏幕媒体流的画面(控制台用);流已经停了时为 None
+ pub fn screen_feed(&self) -> Option<crate::ScreenFeed> {
+ self.stream.as_ref().map(|s| s.feed())
+ }
+
/// 停止屏幕媒体流。必须调用:直接丢掉的话手机端一直挂着这个会话(见 [`crate::Tunnel`])
pub async fn close(mut self) {
if let Some(s) = self.stream.take() {
diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs
index 9ba2e0b..8f8881e 100644
--- a/crates/ictl-device/src/lib.rs
+++ b/crates/ictl-device/src/lib.rs
@@ -39,6 +39,7 @@ use idevice::{
pub use apps::AppInfo;
pub use hid::{Button, HidSession};
+pub use media::{ScreenFeed, ScreenFrame, hevc_codec};
/// A running log stream from the phone; see [`Device::log_stream`]
pub struct LogStream(oslog::OsLogStream);
diff --git a/crates/ictl-device/src/media.rs b/crates/ictl-device/src/media.rs
index 883cd88..7ac27d9 100644
--- a/crates/ictl-device/src/media.rs
+++ b/crates/ictl-device/src/media.rs
@@ -1,20 +1,32 @@
//! 启动 CoreDevice 屏幕媒体流。HID 事件只有在媒体流存在时才会被系统接受(否则静默丢弃),
-//! 所以 HID 会话期间要一直持有它;RTP 数据不读,直接丢弃。
+//! 所以 HID 会话期间要一直持有它。
//!
-//! 移植自 idevice v0.1.68 `tools/src/coredevice_stream.rs`(MIT,Copyright Jackson Coxson),
+//! 流本身是手机硬件编码的 HEVC(RTP,payload type 100,不加密),约 60 帧/秒、原生分辨率(宽高补到 16 的倍数,
+//! 1320×2868 的屏编成 1328×2896)。收下来还原成一帧帧的 Annex-B([`ScreenFeed`]),给控制台当画面用;
+//! 没人订阅时照样收、照样解包(便宜),只是不往外发。
+//!
+//! 回传给手机的 RTCP 照 Device Hub 的做法(上游 idevice 抓包整理):每收完一帧回一个帧确认,每 50 毫秒一个 RCTL,
+//! 每秒一个接收报告。上游说不回 RCTL 的话,剧烈运动时编码器和接收端的参考帧会对不上、画面花掉而解码不报错。
+//! 关键帧只在开头有一个(KeyFrameInterval 0),之后要靠 PLI/FIR 请求(实测 15~20 毫秒后到)。
+//!
+//! 起流部分移植自 idevice v0.1.68 `tools/src/coredevice_stream.rs`(MIT,Copyright Jackson Coxson),
//! 去掉了日志输出和应答转储,错误改成 `DeviceError`。
use idevice::{
ReadWrite, RsdService,
core_device::{
- CallInfoBlob, DisplayServiceClient, build_screen_audio_offer, build_screen_video_offer,
- build_start_audio_parameters, build_start_video_parameters,
+ 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,
},
rsd::RsdHandshake,
tcp::handle::{AdapterHandle, UdpSocketHandle},
};
-use std::time::Duration;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use tokio::sync::{broadcast, mpsc};
use crate::{DeviceError, Result, limit};
@@ -28,39 +40,245 @@ const CLIENT_SUPPORTED_FEATURES: u64 = 140;
/// 活着的媒体流。两个 UDP 套接字必须一直绑定,丢掉就会解绑端口。
///
/// 手机按码率不停地发 RTP 包,jktcp 给每个 UDP 端口的是无界队列:不读的话包一直堆在内存里,HID 会话开多久就
-/// 堆多久。`drain` 任务读出来直接丢掉,随媒体流结束
+/// 堆多久。`receive` 任务一直读:音频丢掉,视频解包成帧([`ScreenFeed`]),随媒体流结束
pub(crate) struct ScreenMediaStream {
client: DisplayServiceClient<Box<dyn ReadWrite>>,
- drain: tokio::task::JoinHandle<()>,
+ receive: tokio::task::JoinHandle<()>,
+ feed: ScreenFeed,
}
impl Drop for ScreenMediaStream {
fn drop(&mut self) {
- // 任务持有两个套接字:中止后它们随之释放、解绑端口
- self.drain.abort();
+ // 任务持有两个套接字:中止后它们随之释放、解绑端口;订阅者随之收到流结束
+ self.receive.abort();
+ }
+}
+
+/// 一帧画面:Annex-B(起始码分隔的 NAL),关键帧前面带着 VPS/SPS/PPS(手机按请求补发的关键帧不带,这里补上),
+/// 所以从任何一个关键帧开始都能解
+#[derive(Debug, Clone)]
+pub struct ScreenFrame {
+ pub key: bool,
+ pub data: Arc<Vec<u8>>,
+}
+
+/// 屏幕媒体流的画面:订阅([`Self::subscribe`])拿到之后的每一帧,要关键帧用 [`Self::request_keyframe`]。
+/// 克隆便宜;HID 会话关掉(媒体流停止)后订阅者收到 `Closed`
+#[derive(Clone)]
+pub struct ScreenFeed {
+ frames: broadcast::Sender<ScreenFrame>,
+ keyframe: mpsc::UnboundedSender<()>,
+}
+
+impl ScreenFeed {
+ pub fn subscribe(&self) -> broadcast::Receiver<ScreenFrame> {
+ self.frames.subscribe()
+ }
+
+ /// 请手机尽快发一个关键帧(新订阅者、跟不上丢了帧时)
+ pub fn request_keyframe(&self) {
+ let _ = self.keyframe.send(());
}
}
-/// 读走并丢弃两个套接字上的数据,直到它们关闭
-fn drain(audio: UdpSocketHandle, video: UdpSocketHandle) -> tokio::task::JoinHandle<()> {
+/// 一秒多的帧:订阅者落后更多就收到 `Lagged`,要从下一个关键帧接着来
+const FEED_CAPACITY: usize = 90;
+/// 关键帧请求最多这么频繁(PLI/FIR 每个都会让手机编一个 15~50 KB 的关键帧)
+const KEYFRAME_EVERY: Duration = Duration::from_millis(300);
+
+/// 收两个套接字上的数据,直到它们关闭:音频丢掉;视频解包、组帧、发给订阅者,并回传 RTCP(见模块说明)
+fn receive(
+ audio: UdpSocketHandle,
+ video: UdpSocketHandle,
+ our_ssrc: u32,
+ frames: broadcast::Sender<ScreenFrame>,
+ mut keyframe: mpsc::UnboundedReceiver<()>,
+) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
+ let mut depack = HevcDepacketizer::new();
+ let mut asm = Assembler::default();
+ // 手机发 RTP 的端口(RTCP 回到这里),收到第一个包才知道
+ let mut device_port = 0u16;
+ let (mut media_ssrc, mut first_seq, mut last_seq) = (0u32, None::<u16>, 0u16);
+ let (mut received, mut fir_seq) = (0u16, 0u8);
+ let mut last_keyframe_ask = None::<Instant>;
+ let mut keyframe_wanted = false;
+ let start = Instant::now();
+ let mut rctl = tokio::time::interval(Duration::from_millis(50));
+ let mut report = tokio::time::interval(Duration::from_secs(1));
loop {
// mpsc 的接收可以安全取消:没收完的包留在队列里,下一轮照样读到
- let r = tokio::select! {
- r = audio.recv() => r,
- r = video.recv() => r,
- };
- if r.is_err() {
- return;
+ tokio::select! {
+ r = audio.recv() => if r.is_err() { return },
+ r = video.recv() => {
+ let Ok(dg) = r else { return };
+ if is_rtcp(&dg.data) {
+ continue;
+ }
+ let Some(p) = RtpPacket::parse(&dg.data) else { continue };
+ device_port = dg.source_port;
+ media_ssrc = p.ssrc;
+ first_seq.get_or_insert(p.sequence_number);
+ last_seq = p.sequence_number;
+ // 新的时间戳开始了新的一帧:上一帧要是还没随 marker 结束,先把它发出去
+ if let Some(f) = asm.new_timestamp(p.timestamp) {
+ let _ = frames.send(f);
+ }
+ depack.push(p.sequence_number, p.timestamp, p.payload);
+ asm.push(&depack.take_output());
+ if p.marker && let Some(f) = asm.finish() {
+ received = received.wrapping_add(1);
+ let _ = video.send_to(device_port, build_frame_ack(our_ssrc, p.timestamp)).await;
+ let _ = frames.send(f);
+ }
+ }
+ r = keyframe.recv() => {
+ if r.is_none() {
+ return;
+ }
+ keyframe_wanted = true;
+ }
+ _ = rctl.tick() => {
+ if device_port != 0 {
+ let clock = (start.elapsed().as_millis() & 0xffff) as u16;
+ let rel = last_seq.wrapping_sub(first_seq.unwrap_or(last_seq));
+ let _ = video.send_to(device_port, build_rctl(our_ssrc, clock, received, rel)).await;
+ }
+ }
+ _ = report.tick() => {
+ if device_port != 0 {
+ let _ = video.send_to(device_port, build_liveness(our_ssrc, "iphone-control", &[])).await;
+ }
+ }
+ }
+ if keyframe_wanted && device_port != 0 && last_keyframe_ask.is_none_or(|t| t.elapsed() >= KEYFRAME_EVERY) {
+ keyframe_wanted = false;
+ last_keyframe_ask = Some(Instant::now());
+ fir_seq = fir_seq.wrapping_add(1);
+ let ask = build_keyframe_request(our_ssrc, "iphone-control", media_ssrc, &[], fir_seq);
+ let _ = video.send_to(device_port, ask).await;
}
}
})
}
+/// 把解包器吐出的 Annex-B 攒成一帧:帧以 RTP marker 结束(或下一帧的时间戳开始)。记下最近的参数集,补到没带它们
+/// 的关键帧前面
+#[derive(Default)]
+struct Assembler {
+ current: Vec<u8>,
+ timestamp: Option<u32>,
+ /// 最近一次见到的 VPS、SPS、PPS(各自带起始码)
+ params: [Option<Vec<u8>>; 3],
+}
+
+impl Assembler {
+ fn new_timestamp(&mut self, ts: u32) -> Option<ScreenFrame> {
+ let done = if self.timestamp.is_some_and(|t| t != ts) { self.finish() } else { None };
+ self.timestamp = Some(ts);
+ done
+ }
+
+ fn push(&mut self, annexb: &[u8]) {
+ self.current.extend_from_slice(annexb);
+ }
+
+ /// 攒好的一帧;没有画面数据(只有参数集、AUD)时不算一帧,参数集留下
+ fn finish(&mut self) -> Option<ScreenFrame> {
+ let data = std::mem::take(&mut self.current);
+ let nals = nal_units(&data);
+ let mut key = false;
+ let mut has = [false; 3];
+ let mut vcl = false;
+ for n in &nals {
+ match nal_type(n) {
+ Some(t @ 32..=34) => {
+ has[usize::from(t - 32)] = true;
+ self.params[usize::from(t - 32)] = Some(n.to_vec());
+ }
+ Some(t) if t <= 31 => {
+ vcl = true;
+ key |= (16..=23).contains(&t);
+ }
+ _ => {}
+ }
+ }
+ if !vcl {
+ return None;
+ }
+ let data = if key && has != [true; 3] && self.params.iter().all(Option::is_some) {
+ let mut v: Vec<u8> = self.params.iter().flatten().flatten().copied().collect();
+ v.extend(nals.iter().filter(|n| !matches!(nal_type(n), Some(32..=34))).flat_map(|n| n.iter().copied()));
+ v
+ } else {
+ data
+ };
+ Some(ScreenFrame { key, data: Arc::new(data) })
+ }
+}
+
+/// Annex-B 里的各个 NAL(各自带着起始码)
+pub(crate) fn nal_units(data: &[u8]) -> Vec<&[u8]> {
+ let mut starts = Vec::new();
+ let mut i = 0;
+ while i + 3 <= data.len() {
+ if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
+ starts.push(if i > 0 && data[i - 1] == 0 { i - 1 } else { i });
+ i += 3;
+ } else {
+ i += 1;
+ }
+ }
+ starts.iter().enumerate().map(|(k, &s)| &data[s..starts.get(k + 1).copied().unwrap_or(data.len())]).collect()
+}
+
+/// 一个带起始码的 NAL 的类型(HEVC:首字节的第 2~7 位)
+fn nal_type(nal: &[u8]) -> Option<u8> {
+ let body = if nal.starts_with(&[0, 0, 0, 1]) { &nal[4..] } else { nal.strip_prefix(&[0, 0, 1])? };
+ body.first().map(|b| (b >> 1) & 0x3f)
+}
+
+/// WebCodecs 的 HEVC 编码串(例如 `hvc1.1.6.L150.B0`),从一帧(关键帧,带 SPS)里的 SPS 算出来
+pub fn hevc_codec(frame: &[u8]) -> Option<String> {
+ let sps = nal_units(frame).into_iter().find(|n| nal_type(n) == Some(33))?;
+ let body = if sps.starts_with(&[0, 0, 0, 1]) { &sps[4..] } else { &sps[3..] };
+ // 去掉防竞争字节,跳过 2 字节的 NAL 头和 1 字节(vps id、max_sub_layers、temporal_id_nesting)
+ let mut raw = Vec::with_capacity(body.len());
+ let mut zeros = 0;
+ for &b in body.get(2..)? {
+ if zeros >= 2 && b == 3 {
+ zeros = 0;
+ continue;
+ }
+ zeros = if b == 0 { zeros + 1 } else { 0 };
+ raw.push(b);
+ }
+ // profile_tier_level:profile_space(2) tier(1) profile_idc(5),32 位兼容标志,48 位约束标志,level_idc
+ let ptl = raw.get(1..13)?;
+ let (space, tier, profile) = (ptl[0] >> 6, (ptl[0] >> 5) & 1, ptl[0] & 0x1f);
+ let compat = u32::from_be_bytes(ptl[1..5].try_into().ok()?).reverse_bits();
+ let constraints: Vec<String> = {
+ let c = &ptl[5..11];
+ let last = c.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1);
+ c[..last].iter().map(|b| format!("{b:X}")).collect()
+ };
+ let space = ["", "A", "B", "C"][usize::from(space)];
+ let mut s = format!("hvc1.{space}{profile}.{compat:X}.{}{}", if tier == 1 { 'H' } else { 'L' }, ptl[11]);
+ for c in constraints {
+ s.push('.');
+ s.push_str(&c);
+ }
+ Some(s)
+}
+
impl ScreenMediaStream {
pub async fn stop(mut self) {
stop(&mut self.client).await;
}
+
+ pub fn feed(&self) -> ScreenFeed {
+ self.feed.clone()
+ }
}
pub(crate) async fn start(
@@ -142,7 +360,10 @@ pub(crate) async fn start(
return Err(e);
}
- Ok(ScreenMediaStream { client, drain: drain(audio_udp, video_udp) })
+ let (frames, _) = broadcast::channel(FEED_CAPACITY);
+ let (keyframe, keyframe_rx) = mpsc::unbounded_channel();
+ let feed = ScreenFeed { frames: frames.clone(), keyframe };
+ Ok(ScreenMediaStream { client, receive: receive(audio_udp, video_udp, ssrc, frames, keyframe_rx), feed })
}
async fn stop(client: &mut DisplayServiceClient<Box<dyn ReadWrite>>) {
@@ -158,3 +379,43 @@ async fn stop(client: &mut DisplayServiceClient<Box<dyn ReadWrite>>) {
),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 手机按请求补发的关键帧只有 IDR 切片:前面补上开头那一帧带的参数集;没有画面数据的不算一帧
+ #[test]
+ fn keyframes_get_the_parameter_sets() {
+ let (vps, sps, pps) = ([0u8, 0, 0, 1, 0x40, 1, 9], [0u8, 0, 0, 1, 0x42, 1, 8], [0u8, 0, 0, 1, 0x44, 1, 7]);
+ let idr = [0u8, 0, 0, 1, 0x28, 1, 0xAA];
+ let trail = [0u8, 0, 0, 1, 0x02, 1, 0xBB];
+ let mut a = Assembler::default();
+ a.push(&[vps.as_slice(), &sps, &pps, &idr].concat());
+ let first = a.finish().unwrap();
+ assert!(first.key);
+ assert_eq!(*first.data, [vps.as_slice(), &sps, &pps, &idr].concat());
+ a.push(&trail);
+ assert!(!a.finish().unwrap().key);
+ a.push(&idr);
+ let later = a.finish().unwrap();
+ assert_eq!(*later.data, [vps.as_slice(), &sps, &pps, &idr].concat(), "parameter sets added");
+ a.push(&[0, 0, 0, 1, 0x46, 1, 0x50]);
+ assert!(a.finish().is_none(), "an access unit delimiter alone isn't a frame");
+ // a frame without a marker ends when the next timestamp starts
+ assert!(a.new_timestamp(1).is_none());
+ a.push(&trail);
+ assert!(a.new_timestamp(2).is_some());
+ }
+
+ /// The SPS the iPhone 18 Pro Max (iOS 27.2.1) sends: Main profile, level 5.0
+ #[test]
+ fn codec_string_from_the_phones_sps() {
+ let sps = [
+ 0u8, 0, 0, 1, 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0xB0, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x03, 0x00, 0x96, 0xA0, 0x02,
+ ];
+ 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");
+ }
+}
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 9f98e7a..565fd97 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -833,6 +833,7 @@ pub fn wants_alert_check(req: &Request) -> bool {
| Request::UninstallApp { .. }
| Request::WebEval { .. }
| Request::Status
+ | Request::ScreenStream
| Request::Screenshot { .. }
| Request::ListElements { .. }
| Request::ListApps { .. }
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index acea668..a15c0bb 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -55,6 +55,11 @@ pub enum TouchPhase {
pub enum Request {
/// MCP 的 iphone_status:与 toolkit 相同的文字
Status,
+ /// The phone's own screen video (CoreDevice screen media stream, HEVC, iOS 27 and later) for the control page.
+ /// Streaming: the daemon answers one line ([`Response::Text`] when it streams, [`Response::Error`] when it
+ /// can't), then sends [`ScreenMsg`] messages on the same connection until either side closes it. The client may
+ /// write [`SCREEN_KEYFRAME`] to ask for a keyframe. Use [`open_screen_stream`]
+ ScreenStream,
/// 区域单位为点;None 表示整屏
Screenshot {
region: Option<(f64, f64, f64, f64)>,
@@ -244,6 +249,7 @@ impl Request {
| Self::UninstallApp { .. }
| Self::WebEval { .. } => true,
Self::Status
+ | Self::ScreenStream
| Self::Screenshot { .. }
| Self::ListElements { .. }
| Self::ListApps { .. }
@@ -262,6 +268,77 @@ impl Request {
}
}
+/// Messages after a [`Request::ScreenStream`] answer: one type byte, a 4-byte big-endian length, the payload
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ScreenMsg {
+ /// JSON: `codec` (WebCodecs string), before the first frame and whenever it changes
+ Config = 0,
+ /// A keyframe, Annex-B, with its parameter sets
+ Key = 1,
+ /// Any other frame, Annex-B
+ Delta = 2,
+ /// JSON: `rotation` in degrees (0, 90, 180, 270: how far the portrait top edge has turned clockwise), when it
+ /// becomes known or changes. The video itself is always portrait
+ Info = 3,
+}
+
+impl ScreenMsg {
+ pub fn from_byte(b: u8) -> Option<Self> {
+ Some(match b {
+ 0 => Self::Config,
+ 1 => Self::Key,
+ 2 => Self::Delta,
+ 3 => Self::Info,
+ _ => return None,
+ })
+ }
+
+ /// The message with its header
+ pub fn frame(self, payload: &[u8]) -> Vec<u8> {
+ let mut m = Vec::with_capacity(5 + payload.len());
+ m.push(self as u8);
+ m.extend_from_slice(&(payload.len() as u32).to_be_bytes());
+ m.extend_from_slice(payload);
+ m
+ }
+}
+
+/// The byte a [`Request::ScreenStream`] client writes to ask for a keyframe
+pub const SCREEN_KEYFRAME: u8 = b'K';
+
+/// Opens a [`Request::ScreenStream`]: `Ok(Ok(..))` with the reading half (buffered: it may already hold the first
+/// messages) and the writing half, `Ok(Err(why))` when the daemon can't stream, `Err` when it can't be reached
+pub async fn open_screen_stream(
+ socket: &std::path::Path,
+ expect_udid: Option<&str>,
+) -> std::io::Result<
+ Result<(tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>, tokio::net::unix::OwnedWriteHalf), String>,
+> {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ let stream = tokio::net::UnixStream::connect(socket).await?;
+ let (r, mut w) = stream.into_split();
+ let mut v = serde_json::to_value(Request::ScreenStream)?;
+ if let Some(o) = v.as_object_mut() {
+ o.insert(LANG.into(), ictl_l10n::lang().code().into());
+ if let Some(u) = expect_udid {
+ o.insert(EXPECT_UDID.into(), u.into());
+ }
+ }
+ let mut line = v.to_string();
+ line.push('\n');
+ w.write_all(line.as_bytes()).await?;
+ let mut r = BufReader::with_capacity(256 * 1024, r);
+ let mut first = String::new();
+ tokio::time::timeout(std::time::Duration::from_secs(30), r.read_line(&mut first))
+ .await
+ .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "screen stream: no answer"))??;
+ Ok(match serde_json::from_str::<Response>(&first).map_err(std::io::Error::other)? {
+ Response::Error { message } => Err(message),
+ _ => Ok((r, w)),
+ })
+}
+
/// 工具结果里报告系统弹窗挡着屏幕的固定写法(后面接「弹窗文字」)。MCP 端据此判断结果里是否已经报过弹窗,
/// 不能只找「系统弹窗」几个字:按名字点到的元素文字里也可能有
pub const ALERT_BLOCKING: &str = "屏幕上有系统弹窗";
diff --git a/docs/architecture.md b/docs/architecture.md
index 489d5f1..e2f1526 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -46,6 +46,8 @@
- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。
- `iphone-control viewer` 同样显式开启、只绑 127.0.0.1、检查 Host 头:页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。它跟着守护进程控制的设备:在本页、别的页面、`iphone-control select`、MCP 工具里切换,或拔掉后自动换了一台,`/api/info` 的 `udid` 都会变,页面最迟在下一次 10 秒轮询时发现,把画面(`/stream?udid=`)和各面板换过去。每个操作带上页面显示的那台的 UDID(`X-Ictl-Device`),守护进程控制的不是这台就拒绝,不会发到用户没在看的手机上。还没装 WDA 的设备,登录了 Apple ID 时页面上可以直接签名安装(`/api/sign`,即 `Request::Resign { force: true }`,时限 16 分钟)。AI 任务执行中不能切换设备,设了 `IPHONE_UDID` 时也不能。
- viewer 的画面像触摸屏:iOS 27 起按下、移动、松开各发一个 `Request::Touch`(`prepare`/`down`/`move`/`up`),守护进程在已开的 HID 会话上发一个 touchscreen 报告(约 2 毫秒);解锁、核对方向只在 `down` 时做一次。页面一次只发一个请求,没发出去的移动只留最新的一个,按住不动时每 100 毫秒再报一次位置。滚轮、触控板换成同样的手指拖动。iOS 27 以下松开后发整段手势(WDA)。画面的 MJPEG 流在 `WdaClient::fast_stream` 下是每秒 60 帧、75% 尺寸。页面的文字中英两套,请求带 `X-Ictl-Lang`,viewer 在这种语言下处理,AI 任务记下开始时的语言。
+- viewer 的画面编码(`video/`):macOS 上和装了 ffmpeg 时页面拉 `/video`,是 H.264。每个连接读手机的 MJPEG,丢掉和上一帧相同的(静止时 WDA 每秒重复约 25 次),交给一个 ffmpeg 子进程(`mpjpeg` 进,FLV 出;FLV 每帧带长度,收完最后一个字节就能发,裸 H.264 要等下一帧开头才知道这一帧结束),再按「1 字节类型 + 4 字节长度 + 内容」发给页面,页面用 WebCodecs 解码画到 canvas。发出去的解码配置先改写 SPS,写明不重排帧(`video/sps.rs`):没写的话 Chrome 的硬件解码器按级别的最坏情况扣着几帧不出(990×2151 时 4 帧),画面滞后,静止后停在动作中间。macOS 上先用本程序直接调的 VideoToolbox(`video/vt.rs`,每个连接一个线程:VideoToolbox 的 JPEG 解码器把 JPEG 解成 NV12,奇数尺寸顺带拉成偶数,直接交给 H.264 编码器;不重排、不扣帧,每帧编完才取下一帧,不用补帧;输出本来就是 avcC 格式,avcC 取自格式描述;qp 用 `MinAllowedFrameQP`/`MaxAllowedFrameQP` 定住,macOS 12 以前的系统按 `Quality` 近似;macOS 11 以后才有的键运行时用 `dlsym` 找,免得在旧系统上起不来),不需要 ffmpeg。其余编码器在 `viewer` 启动时按顺序试(NVENC、各渲染节点上的 VAAPI(先显卡解 JPEG,再 CPU 解)、QSV、V4L2 M2M、ffmpeg 的 VideoToolbox(原生的备用)、x264),处理真实画面失败就换下一个。ffmpeg 会扣住最新的一帧等下一帧来(AMD 780M 的 VAAPI 是 1 帧),画面静止时最后一次变化就出不来,所以每帧后面紧跟着把它再写 K 遍,K 在探测时测出(写入的帧数减去出来的帧数),这几份副本各编成约 100 字节。流量控制:系统和 SSH 隧道的缓冲能吞下几 MB,光看队列满不满判断不了页面跟不跟得上(每秒读 30 KB 的客户端曾落后 40 秒),所以页面每 100 毫秒 `POST /api/video/ack` 报告收到多少字节;最早一个没确认的消息比平常的往返时间晚 300 毫秒以上,或者在路上的字节超过「链路速度 ×(往返时间 + 300 毫秒)」时,新画面先不交给编码器,追上后只交最新一张。编好的帧一个不丢,帧链完整,不需要关键帧。没有 ffmpeg 或浏览器不支持 WebCodecs 时用 `/stream`:同样丢掉重复帧、只发最新一张,每帧后面紧跟下一部分的分隔线和头部(Chrome 要看到这些才显示上一帧)。
+- 手机自己的视频(iOS 27 及以上,页面优先用它):CoreDevice 屏幕媒体流本来就由 HID 会话持有(HID 事件要它在才生效)。`ictl-device` 的 `media.rs` 不再丢掉 RTP:用上游的 `HevcDepacketizer` 还原成 Annex-B,按 RTP marker 组成一帧,记下 VPS/SPS/PPS 补到手机按请求发来、不带参数集的关键帧前面,经 broadcast 发给订阅者(`ScreenFeed`);并照 Device Hub 回传 RTCP(每帧一个帧确认、每 50 毫秒一个 RCTL、每秒一个接收报告),按需发 PLI+FIR 要关键帧(最多每 300 毫秒一次)。守护进程的 `screen.rs` 处理流式请求 `ScreenStream`:先回一行 JSON,之后在同一连接上发「类型 + 长度 + 内容」的消息(0 解码配置、1 关键帧、2 其他帧、3 界面方向),客户端写 `K` 要关键帧;还没收到关键帧时每 250 毫秒再要一次(刚开流时要的那次手机可能不理);界面方向每秒问一次 WDA。有页面在看时(`screen_viewers`),HID 会话不因空闲关闭。viewer 的 `video/device.rs` 转发到 `/video?src=device`,流量控制沿用页面的回报:落后时丢掉非关键帧、再要一个关键帧。页面不带 description 配置 HEVC 解码器(Annex-B),按 `/api/info` 的屏幕尺寸裁掉宽高补到 16 倍数的边(1320×2868 编成 1328×2896),按方向转正;`isConfigSupported` 不支持或从没出过画面就退回 H.264,再退回 MJPEG。
- viewer 的 AI 任务(`agent.rs`):页面上写的任务交给本机的 Claude Code(`claude -p --output-format stream-json`,`--tools ""`、`--strict-mcp-config`,只有 iphone 的 MCP 工具)或 Codex(`codex exec --json`,只读沙箱,`-c` 挂上 iphone 的 MCP 服务),作为子进程(单独的进程组,停止时整组结束)。它的 MCP 服务带上环境变量 `ICTL_AGENT_GATE`(viewer 在控制接口旁边监听的 Unix socket `viewer-<端口>.sock`,0600)和 `ICTL_AGENT_TOKEN`(这个任务的口令),于是每次工具调用前先问 viewer(`ictl_mcp::gate`):记成任务的一步、暂停或用户接管时挂住、任务停了就拒绝;调用后把结果和截图报回去;另外多列一个 `iphone_confirm`,等用户在页面上同意或拒绝。所以步骤、暂停、接管、确认都在 iphone-control 这一层,和用哪种 agent 无关;agent 自己的输出只取它说的话(挂到下一步上)和最后的总结。Codex 对标了 destructive 的 MCP 工具默认要审批,非交互运行时会全部拒绝,所以给这个服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关。页面按 SSE 收任务事件(`step`/`confirm`/`state`/`done`),重连时先重放;同一时间只有一个任务,任务执行中(没有接管时)viewer 拒绝页面的手动操作。
### 并发模型
@@ -115,7 +117,7 @@
| `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` |
| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |
| `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 17 个,开启开发者工具后 23 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`ictl-l10n`、`rmcp`(`server`、`transport-io`) |
-| `apps/iphone-control` | CLI 入口:不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
+| `apps/iphone-control` | CLI 入口:不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`video/`:画面的 H.264 编码(外部 ffmpeg)和 MJPEG 去重;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`,还直接依赖 `ictl-device`、`ictl-sign`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还直接依赖 `ictl-webinspector`、`ictl-sign` 和 `ictl-protocol`。`ictl-device` 也依赖 `ictl-webinspector`(打开连接)。`ictl-mcp` 只依赖 `ictl-protocol` 和 `ictl-l10n`,不依赖守护进程和设备层。`ictl-l10n` 不依赖其他 crate,除 `ictl-webinspector` 外都用它。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。
diff --git a/docs/decisions.md b/docs/decisions.md
index a1a315b..f72e2f4 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -103,3 +103,36 @@
- 少一套要维护的东西:自管 usbmuxd、容器没有 udev 的热插拔兜底、镜像构建和 SBOM、`docker exec` 形式的注册命令都不要了。
- **代价**:Docker 用户要迁移(数据目录拷到 `~/.local/share/iphone-control`,`.env` 改成 `~/.config/iphone-control/env`,手机可能要重新信任,见更新日志的升级注意事项);Linux 上要自己装 usbmuxd;不能再用容器把它和宿主机隔离开,守护进程的权限就是登录用户的权限;Intel Mac 没有预编译版本,要从源码编译。
- **重新评估**:有人需要在无人值守的服务器上隔离运行、又不用控制台的 AI 任务时。
+
+## D15:控制台画面用 H.264,调用外部 ffmpeg,显卡编码优先(2026-11-11)
+
+- **背景**:控制台(`iphone-control viewer`)的画面是 WDA 的 MJPEG 流,每秒 4~10 MB(画面静止时 WDA 也每秒重发约 25 张)。经 SSH 隧道在外网看时卡,而且系统和隧道的缓冲会把积压藏起来,画面越来越滞后。
+- **决定**:装了 ffmpeg 时画面改用 H.264,页面用 WebCodecs 解码;没有 ffmpeg、没有能用的编码器、浏览器不支持时退回 MJPEG。编码交给外部的 ffmpeg 进程,按机器挑编码器,显卡优先:NVENC、VAAPI、QSV、V4L2 M2M、VideoToolbox,最后是 x264。默认画质 qp 20,可以用 `IPHONE_CONTROL_VIEWER_QP` 调。页面回报收到多少,链路跟不上时少编几帧。
+- **理由**:
+ - 实测(AMD 780M,VAAPI,在设置里来回滚动):MJPEG 约 4.5 MB/s,H.264 约 250~430 KB/s,静止时为零,逐帧 SSIM 中位 0.999;收到新画面的时间和 MJPEG 差 −2~+37 毫秒;CPU 约 2%(JPEG 也交给显卡解码),软件 x264 约 36% 单核。
+ - 调用 ffmpeg 程序而不链接它:各发行版的 ffmpeg 已经带了各家显卡的编码器,不用自己适配;x264 是 GPL,不链接就不影响本项目的 MIT 许可证;不装也照常能用。
+ - 帧格式选 FLV:每帧带长度,帧一编好就能发;裸 H.264 要等下一帧开头才知道这一帧结束,而下一帧正被 ffmpeg 扣着。
+- **代价**:
+ - 多一个可选依赖,Linux 上用显卡还要在 `render` 组里。
+ - 4:2:0 色度采样,彩色小字的边缘比 JPEG 略软。
+ - 依赖 ffmpeg 命令行的行为:它会扣住一帧,靠紧跟的副本挤出来,扣几帧在探测时测,换了 ffmpeg 版本可能变。
+ - Intel、NVIDIA、树莓派的编码器参数只按文档定,还没在真机上验证。
+- **补充(2026-11-11)**:macOS 上改为本程序直接调 VideoToolbox(JPEG 也交给 VideoToolbox 的硬件解码器),不再需要 ffmpeg;ffmpeg 的 VideoToolbox 留作备用。VideoToolbox 不扣帧,不用补帧;qp 能直接定住,画质设置和其他硬件编码器一致。只多了几个系统框架的链接,没有新依赖。实测(Apple 芯片,macOS 27):从送进 JPEG 到出帧 3.5~6 毫秒;模拟列表滚动的测试画面(480×1040)每帧 5~9 KB,关键帧约 31 KB;每秒 20 KB 的链路上,画面停下后约 0.8 秒最后一帧到达。手机真实画面(iPhone 18 Pro Max,990×2151,76 秒:主屏翻页、设置里滚动、网页滚动,931 个不同的帧):qp 20 时 H.264 是去重后 MJPEG 的 11.4%,平均 337 KB/s,最忙的一秒 1076 KB/s;逐帧 SSIM 中位 0.9976、最低 0.9927;从送进到出帧中位 17 毫秒。qp 16/18/24 的 SSIM 中位是 0.9986/0.9982/0.9964,流量是 qp 20 的 1.64/1.29/0.58 倍。SSIM 是本程序的量法(`measure_recording`:页面解出的画面对比编码器拿到的 NV12,ffmpeg `ssim` 的 8×8 窗口),和 Linux 上用 ffmpeg 量的 0.999 不是同一个工具、同一台手机,不能直接比。VideoToolbox 的 SPS 不带 VUI,Chrome 的硬件解码器会因此扣住 4 帧,所以发给页面前改写 SPS,写明不重排帧(见架构文档)。
+- **重新评估**:浏览器普遍支持更省的编码(AV1)且本机有硬件编码时;或者 iOS 27 的 CoreDevice 屏幕媒体流(手机自己编的视频)能直接转给页面时,可以省掉本机编码。
+
+## D16:iOS 27 及以上,控制台画面直接用手机自己编的视频(2026-11-12)
+
+- **背景**:控制台的画面原来都来自 WDA 截图(MJPEG)。复杂页面上 WDA 每秒只出 7~16 帧,而且截图本身让 WDA 的 CPU 超过一个核:控制台开着时,iOS 按「一分钟平均超过 80%」每隔几分钟就把 WDA 杀掉(`cpu_resource_fatal`),WDA 重启期间操作失败。降帧率、改缩放和画质都没有明显改善。
+- **决定**:iOS 27 及以上,页面优先用 CoreDevice 屏幕媒体流:手机硬件编码的 HEVC,守护进程解 RTP、组帧,经 viewer 原样转给页面,用 WebCodecs 解码。浏览器解不了 HEVC、设备低于 iOS 27、设了 `IPHONE_CONTROL_VIEWER_CODEC=mjpeg` 或指定某个编码器时,照旧用 D15 的 H.264 或 MJPEG。
+- **理由**(iPhone 18 Pro Max,iOS 27.2.1,Mac 上的 Chrome):
+ - 滚动时页面每秒画出约 52 帧,原生分辨率 1320×2868;WDA 画面同样的操作是 9~16 帧、990×2151。
+ - 主机不解 JPEG、不编码;WDA 的 CPU 从 110~120% 降到约 3%,不再被杀。
+ - 延迟和 WDA 画面相当或更早;码流里写明不重排帧,Chrome 的硬件解码器不扣帧。
+ - HID 会话本来就持有这条流,多的只是不再把数据丢掉。
+- **代价**:
+ - 只有 iOS 27 及以上;Chrome 只能用硬件解 HEVC,Firefox 和多数 Linux 上的 Chrome 解不了,要退回 D15。
+ - 流量不比 H.264 省:滚动时每秒 150~600 KB,静止时也不为零(白底页约 15 KB/s,图多的页约 250 KB/s);链路慢时只能丢帧等关键帧,不能少编几帧。
+ - 看画面期间手机不自动锁屏、灵动岛显示正被查看(同 HID 后备路线)。
+ - 视频总是竖的:界面方向要另外问 WDA(每秒一次),转屏后约 1~2 秒画面才转正;WDA 不可用时按最后知道的方向。
+ - 依赖苹果没公开的协议:RTCP 反馈照上游对 Device Hub 的抓包;上游提醒不回 RCTL 时剧烈运动会花屏,回了之后的长时间表现还没测过。
+- **重新评估**:长时间运行出现花屏或断流时;浏览器普遍能软解 HEVC 时,可以去掉对硬件解码的依赖。
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index 6aecbca..4db45d9 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -80,3 +80,19 @@
| 74 | 每次 HID 触摸前截图核对方向(几百毫秒),实时移动跟不上 | 只在 `down` 时核对一次(有 WDA 时读它的旋转角),移动、抬起直接用已开的会话 | 真机计时 |
| 75 | WDA 的 MJPEG 默认每秒 10 帧,画面比操作慢 | 每秒 60 帧、75% 尺寸(`fast_stream`);只在有客户端时采集 | 真机:约 48 fps、34 KB/帧,读元素树不变慢 |
| 76 | viewer 页面只有中文 | 页面文字中英两套(`tr()`),默认跟着 `IPHONE_CONTROL_LANG`,可切换;请求带 `X-Ictl-Lang`,守护进程的提示和 AI 任务用同一种语言 | 单测(`the_page_says_its_default_language`)+ Playwright(英文页面除切换按钮和手机上的数据外没有中文;360×800 到 1920×1080 中英文都没有横向溢出)+ 真机(英文 AI 任务) |
+| 77 | 控制台画面每秒 4~10 MB,经隧道在外网看会卡 | 装了 ffmpeg 时改用 H.264(`/video`),显卡编码优先,约为 MJPEG 的 1/15 | 真机:设置里来回滚动,`/video` 约 250~430 KB/s,静止时为零 |
+| 78 | ffmpeg 扣住最新一帧,画面静止时最后一次变化一直出不来 | 每帧后面紧跟 K 份副本,K 在探测时测出 | 单测 encodes_with_the_local_ffmpeg;真机:每帧延迟 16 毫秒 |
+| 79 | 裸 H.264 流要等下一帧开头才知道这一帧结束 | ffmpeg 输出 FLV,每帧带长度 | 单测 tags_come_out_whole_however_the_bytes_arrive |
+| 80 | 链路慢时系统和 SSH 隧道的缓冲吞下几 MB,画面越来越滞后(每秒读 30 KB 落后 40 秒) | 页面每 100 毫秒回报收到多少;落后时新画面先不编码,追上后只编最新的 | 单测 behind_means_late_beyond_the_usual_round_trip、no_more_on_the_way_than_the_link_carries_in_the_slack;手动 slow_page_stays_close_to_live;真机:每秒 200 KB 时滚动停下后约 0.6 秒追上 |
+| 81 | 一次回报丢了,服务端一直等,画面卡住 | 页面收到确认才算报过;服务端 3 秒没收到回报就不再等 | 单测 behind_means_late_beyond_the_usual_round_trip |
+| 82 | 转屏后帧的尺寸变了 | 尺寸一变就开新的编码会话,页面按新的解码配置重新配置 | 真机:Safari 横竖屏切换,解码配置发 3 次,ffmpeg 解码无错 |
+| 83 | 浏览器没有 WebCodecs 或解不了 H.264 | 这一页从没出过画面就改用 MJPEG | 无头 Chrome:删掉 VideoDecoder 后画面是 MJPEG |
+| 84 | MJPEG 去重后画面静止时不显示(Chrome 要看到下一部分的头部才显示上一帧) | 每帧后面紧跟下一部分的分隔线和头部,不带 Content-Length | 无头 Chrome:静止画面下 MJPEG 有图 |
+| 85 | macOS 上要装 ffmpeg 才有 H.264 | 本程序直接调 VideoToolbox:JPEG 由它的硬件解码器解成 NV12,直接交给 H.264 编码器;ffmpeg 的 VideoToolbox 作备用 | 单测 encodes_natively_without_holding_frames、encodes_with_the_local_ffmpeg(没装 ffmpeg 也选中原生的);真机(Apple 芯片):从送进到出帧 3.5~6 毫秒;手机真实画面(990×2151)中位 17 毫秒,qp 20 时流量为 MJPEG 的 11.4%,SSIM 中位 0.9976(手动测试 measure_recording) |
+| 86 | VideoToolbox 把奇数尺寸的最后一列、一行裁掉(481×1041 编成 480×1040) | JPEG 解码时就拉成偶数尺寸(482×1042),和 ffmpeg 的 `scale` 一样 | 单测 odd_sizes_grow_to_even;无头 Chrome 用 WebCodecs 解出 482×1042 |
+| 87 | 比 macOS 11 新的 VideoToolbox 键直接链接的话,旧系统上程序起不来 | `MinAllowedFrameQP` 等运行时用 `dlsym` 找,没有就按 `Quality` 近似 qp | 代码审查 |
+| 88 | 页面画面滞后 4 帧,手势结束后停在动作中间那一帧(Chrome 的硬件解码器扣着帧等后面的帧来挤) | VideoToolbox 的 SPS 没有 VUI,解码器按 Level 4.2 的缓冲最坏情况扣 4 帧;发给页面前改写 avcC 里的 SPS,写明 `max_num_reorder_frames=0`(`video/sps.rs`),已经写明的不动 | 单测 videotoolbox_sps_gets_no_reordering、vui_without_restriction_keeps_its_fields;无头 Chrome 逐帧喂:硬件解码器从扣 4 帧变为 0 帧 |
+| 89 | 控制台开着时 WDA 每隔几分钟被 iOS 杀掉(`cpu_resource_fatal`:一分钟平均 84%,限额 80%),守护进程跟着记「WDA 不可用」 | iOS 27 及以上改用手机自己的视频(`ScreenStream`),WDA 不再截图 | 真机:页面看了 70 秒,WDA 的 CPU 平均 3%、最高 11%(原来 110~120%),没有再重启 |
+| 90 | 新页面一直黑屏:刚开流时要的关键帧手机不理,流自带的第一个关键帧在订阅前就过去了 | 没收到关键帧时每 250 毫秒再要一次 | 真机:刚开流 1.6~1.8 秒出第一帧 |
+| 91 | 手机按请求补发的关键帧不带参数集,新页面从它开始解不了 | 组帧时记下 VPS/SPS/PPS,补到这样的关键帧前面 | 单测 keyframes_get_the_parameter_sets |
+| 92 | 横屏时页面上的画面上下颠倒(转正方向写反) | 按「竖放顶边顺时针转过的角度」同向转回来;方向每秒问一次 | 真机:向左、向右横屏的画面和手机截图一致,1.1~2.7 秒跟上;横屏点地址栏点中 |
diff --git a/install.sh b/install.sh
index ba68cd7..5647ea1 100755
--- a/install.sh
+++ b/install.sh
@@ -2,7 +2,7 @@
# iphone-control installer for macOS (Apple Silicon) and Linux (x86_64, aarch64).
#
# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh
-# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --version v0.2.0
+# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --version v0.2.1
#
# Downloads the release archive for this machine, checks its sha256, installs the binary into ~/.local/bin and
# sets up the daemon as a per-user service (launchd on macOS, systemd --user on Linux) that starts at login and
@@ -217,6 +217,12 @@ if [ "$started" = 1 ]; then
elif [ "$SERVICE" = 0 ]; then
say "没有安装服务。启动守护进程:$BIN daemon" "No service installed. Start the daemon: $BIN daemon"
fi
+# on macOS the control page encodes H.264 with VideoToolbox itself
+if [ "$OS" = Linux ] && ! command -v ffmpeg >/dev/null 2>&1; then
+ say "可选:装上 ffmpeg,控制台(iphone-control viewer)的画面改用 H.264,流量约为原来的 1/15:sudo apt install ffmpeg" \
+ "Optional: with ffmpeg installed, the control page (iphone-control viewer) uses H.264 at about 1/15 of the traffic: sudo apt install ffmpeg"
+ echo
+fi
say "接下来:用数据线连上 iPhone,然后运行
iphone-control
diff --git a/packaging/env.example b/packaging/env.example
index a3ec831..57f545a 100644
--- a/packaging/env.example
+++ b/packaging/env.example
@@ -17,6 +17,15 @@ IPHONE_CONTROL_LANG=
# The daemon and every iphone-control command (the MCP server too) read this file at start-up; a variable already set in the environment wins.
IPHONE_CONTROL_DEV_TOOLS=
+# 控制台(iphone-control viewer)的画面:auto(默认:iOS 27 及以上用手机自己编的视频,HEVC;其余 H.264,macOS 上直接用 VideoToolbox,Linux 上要装 ffmpeg,先试显卡编码)、device(只用手机自己的视频)、mjpeg(只用 MJPEG),
+# 或指定 nvenc、vaapi、qsv、v4l2m2m、videotoolbox、x264。H.264 的流量约为 MJPEG 的 1/15,走外网时更顺
+# Viewer picture: auto (default: the phone's own HEVC video on iOS 27 and later, else H.264, on macOS with VideoToolbox directly, on Linux with ffmpeg; GPU encoding first), device (only the phone's own video), mjpeg (only MJPEG), or one of
+# nvenc, vaapi, qsv, v4l2m2m, videotoolbox, x264. H.264 is about 1/15 of MJPEG's traffic.
+IPHONE_CONTROL_VIEWER_CODEC=
+# H.264 的画质:1~51,越小越清晰、流量越大。默认 20,正常使用看不出和原画的差别;24 约省三分之一流量,快速滚动时小字略糊
+# H.264 quality, 1 to 51: lower is sharper and larger. Default 20 looks like the source; 24 saves about a third, small text blurs a little while scrolling fast.
+IPHONE_CONTROL_VIEWER_QP=
+
# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;
# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换
IPHONE_UDID=
diff --git a/packaging/homebrew/formula.sh b/packaging/homebrew/formula.sh
index 1006f99..ae9918b 100755
--- a/packaging/homebrew/formula.sh
+++ b/packaging/homebrew/formula.sh
@@ -1,6 +1,6 @@
#!/bin/sh
# Prints the Homebrew formula for one release (the release workflow pushes it to Derrors/homebrew-tap):
-# packaging/homebrew/formula.sh v0.2.0 <sha256 macos-arm64> <sha256 linux-x86_64> <sha256 linux-aarch64>
+# packaging/homebrew/formula.sh v0.2.1 <sha256 macos-arm64> <sha256 linux-x86_64> <sha256 linux-aarch64>
# The formula installs the prebuilt binary from the GitHub release; `brew services start iphone-control` runs the
# daemon (launchd on macOS, systemd on Linux) with the settings in ~/.config/iphone-control/env.
set -eu
diff --git a/website/deploy/macos.md b/website/deploy/macos.md
index 409589b..8ccbba4 100644
--- a/website/deploy/macos.md
+++ b/website/deploy/macos.md
@@ -20,7 +20,7 @@ iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需
curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh
```
-它会下载最新版本、校验 sha256,装到 `~/.local/bin/iphone-control`,再装一个 launchd 用户服务(`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`):登录后自动启动守护进程,崩溃后自动重启,读取 `~/.config/iphone-control/env`,日志在 `~/Library/Logs/iphone-control/daemon.log`。可选参数写在 `sh -s --` 后面:`--version v0.2.0`(指定版本)、`--prefix 目录`(装到 `目录/bin`)、`--no-service`(只装程序,不装服务)。
+它会下载最新版本、校验 sha256,装到 `~/.local/bin/iphone-control`,再装一个 launchd 用户服务(`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`):登录后自动启动守护进程,崩溃后自动重启,读取 `~/.config/iphone-control/env`,日志在 `~/Library/Logs/iphone-control/daemon.log`。可选参数写在 `sh -s --` 后面:`--version v0.2.1`(指定版本)、`--prefix 目录`(装到 `目录/bin`)、`--no-service`(只装程序,不装服务)。
### Homebrew
diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.md
index d04eaac..b38802d 100644
--- a/website/en/deploy/macos.md
+++ b/website/en/deploy/macos.md
@@ -20,7 +20,7 @@ Verified on a MacBook Pro (Apple M3 Pro) / macOS 26.6.2 with an iPhone 15 Pro Ma
curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh
```
-It downloads the latest release, checks its sha256, installs `~/.local/bin/iphone-control` and a launchd user service (`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`) that starts the daemon at login, restarts it after a crash, reads `~/.config/iphone-control/env` and logs to `~/Library/Logs/iphone-control/daemon.log`. Options go after `sh -s --`: `--version v0.2.0`, `--prefix DIR` (installs into `DIR/bin`), `--no-service` (only the binary, no service).
+It downloads the latest release, checks its sha256, installs `~/.local/bin/iphone-control` and a launchd user service (`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`) that starts the daemon at login, restarts it after a crash, reads `~/.config/iphone-control/env` and logs to `~/Library/Logs/iphone-control/daemon.log`. Options go after `sh -s --`: `--version v0.2.1`, `--prefix DIR` (installs into `DIR/bin`), `--no-service` (only the binary, no service).
### Homebrew
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 9c7ec10..7889481 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -78,7 +78,7 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic
|---|---|
| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) |
| `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |
-| `viewer [--port <port>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. The picture is WDA's MJPEG stream, so there is none until WDA is ready. **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |
+| `viewer [--port <port>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |
The `debug` subcommand for diagnostics isn't compiled by default; see the [contributing guide](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone).
@@ -87,3 +87,16 @@ The `debug` subcommand for diagnostics isn't compiled by default; see the [contr
- **Need the daemon running:** the phone part of `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, and MCP tool calls.
- **Need an interactive terminal:** `iphone-control` with no command (the first time), `setup`, `login`, `passcode set`.
- **Settings:** every command reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](./configuration#settings-file).
+
+## The control page's picture {#viewer-picture}
+
+**iOS 27 and later**: the picture is the phone's own hardware-encoded video (the CoreDevice screen media stream, HEVC), about 60 frames a second at native resolution; nothing is encoded on this machine and WDA doesn't capture anything. It takes 150–600 KB/s while scrolling, and a little even on a still screen (about 15 KB/s on a white page, 250 KB/s on a busy one). When the screen turns, the page turns the picture with it within about 1–2 seconds. The browser has to decode HEVC: Chrome and Safari on a Mac can; Firefox and Chrome on most Linux machines can't and fall back to H.264 or MJPEG as below. While you watch, the phone doesn't auto-lock and the Dynamic Island shows it is being viewed; that ends 30 seconds after the page closes.
+
+**Below iOS 27, or a browser without HEVC**:
+On macOS, and on Linux with ffmpeg installed, the control page's picture is H.264; otherwise MJPEG. The phone's picture is encoded on this machine (on macOS by VideoToolbox, called by this program, no ffmpeg needed; on Linux by ffmpeg) and decoded in the browser with WebCodecs (the browser picks hardware decoding itself). For the same picture it is about 1/15 of MJPEG's traffic: next to nothing on a still screen and about 300–450 KB/s while scrolling, against 4–10 MB/s for MJPEG. The delay is within a frame of MJPEG's.
+
+- **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.
+- **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/guide/configuration.md b/website/en/guide/configuration.md
index bd519fc..fa1f642 100644
--- a/website/en/guide/configuration.md
+++ b/website/en/guide/configuration.md
@@ -25,6 +25,8 @@ iphone-control service restart
| `HTTP_PROXY` / `HTTPS_PROXY` | direct | Proxy for Apple, anisette, Developer Disk Image and notification traffic |
| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. See the note below the table |
| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. See the note below the table |
+| `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | The control page's picture: `auto` uses the phone's own video (HEVC) on iOS 27 and later, else H.264 (on macOS with VideoToolbox directly, on Linux when ffmpeg is installed), GPU encoding first; `device` only the phone's own video, MJPEG where it can't be used; `mjpeg` only MJPEG; or name one of `nvenc`, `vaapi`, `qsv`, `v4l2m2m`, `videotoolbox`, `x264`. `iphone-control viewer` says which one it uses when it starts, see [CLI](./cli#viewer-picture) |
+| `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 quality, 1 to 51: lower is sharper and larger. `20` looks like the source in normal use; `24` saves about a third of the traffic, small text blurs a little while scrolling fast |
| `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused |
| `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain |
| `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices |
@@ -46,6 +48,7 @@ Notification variables: see [Notifications](./notifications).
| `ICTL_WDA_UNSIGNED` | Path of the unsigned WDA. Default: `wda/WDA-unsigned.ipa` in the data directory, downloaded before the first signing. A path you set yourself is not downloaded |
| `SCREEN_W` / `SCREEN_H` | Screen size in points for the HID fallback, used only while WDA is down and there is no record of this device's size: WDA has never connected, or you switched to a device without one. It applies to every device, so take care with several |
| `ICTL_LOG` | Log filter, e.g. `info,ictl_wda::http=debug` logs every WDA request with its duration |
+| `ICTL_FFMPEG` | Path to ffmpeg (the control page's H.264 picture; on macOS only the fallback for VideoToolbox). By default it is looked up on `PATH`, and on macOS in Homebrew's places too |
## Directories and control socket
diff --git a/website/en/guide/getting-started.md b/website/en/guide/getting-started.md
index f13743d..6fc699a 100644
--- a/website/en/guide/getting-started.md
+++ b/website/en/guide/getting-started.md
@@ -45,6 +45,10 @@ You can skip the second line: the guide below starts it for you.
Talking to the phone over USB goes through the system's usbmuxd: `sudo apt install usbmuxd` (or your distribution's package manager). The .deb pulls it in.
:::
+::: tip Optional: ffmpeg
+On Linux with ffmpeg installed, the control page's picture is H.264, about 1/15 of the traffic, which is much smoother through a tunnel or over the internet: `sudo apt install ffmpeg`. On macOS it is H.264 without installing anything. See [the control page's picture](./cli#viewer-picture).
+:::
+
Intel Macs have no prebuilt binary and need a build from source, as does development. See [Build from Source](../deploy/source).
## 2. Plug in the phone and run iphone-control {#first-run}
diff --git a/website/en/troubleshoot/faq.md b/website/en/troubleshoot/faq.md
index 04e16ed..b0ef18c 100644
--- a/website/en/troubleshoot/faq.md
+++ b/website/en/troubleshoot/faq.md
@@ -62,10 +62,17 @@ Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTR
The picture area says why: not connected; pairing or Developer Mode still needed (run `iphone-control setup --reconfigure` and pick *Phone*); WDA starting (usually 10–60 seconds); or it needs unlocking. When the new device has no WDA yet and an Apple ID is signed in, click *Sign and install WDA*; it takes about 1–2 minutes, keep the phone unlocked. Without an Apple ID, run `iphone-control setup --reconfigure` and pick *Apple ID*. Switching is refused while an AI task runs, and when `IPHONE_UDID` is set. See [Several devices](../guide/multi-device).
-## "Paired computer" icon stays and the phone won't auto-lock
+## 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).
+
+## WDA restarts every few minutes while the control page is open
-The HID fallback opens a screen-mirroring session while in use and closes it after 30 seconds idle. If the icon doesn't go away, restart the daemon (`iphone-control service restart`).
+Below iOS 27 (or when the browser can't decode HEVC and gets H.264 or MJPEG), the picture comes from WDA capturing the screen all the time, which takes WDA over one CPU core. iOS kills a process that averages more than 80 % over a minute: the phone keeps a `WebDriverAgentRunner-Runner.cpu_resource_fatal` crash report, the daemon logs "WDA unavailable" and starts it again about 10 seconds later, and actions fail meanwhile. Close the control page when you aren't watching; on iOS 27 and later the phone's own video avoids this (WDA stays around 3 %).
+
+## "Paired computer" icon stays and the phone won't auto-lock
+The HID fallback, and the control page while it shows the phone's own video (iOS 27 and later), open a screen mirroring session; it closes 30 seconds after it was last used (after the page closes). If the icon doesn't go away, restart the daemon (`iphone-control service restart`).
## Reporting a problem
[Open an issue](https://github.com/Derrors/iphone-control/issues/new/choose) with the phone model, iOS version, how you installed it (one command, Homebrew, .deb or source), and the `doctor` output — with UDID, Apple ID and notification keys removed.
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 8d5f825..1f6f9b2 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -78,7 +78,7 @@
|---|---|
| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) |
| `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |
-| `viewer [--port <端口>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口),中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。画面来自 WDA 的 MJPEG 流,WDA 没就绪时没有画面。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
+| `viewer [--port <端口>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口),中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。
@@ -87,3 +87,16 @@
- **要守护进程在运行的:** `setup` 的手机部分、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`,以及 MCP 工具调用。
- **要在终端里交互运行的:** 不带命令的 `iphone-control`(首次运行时)、`setup`、`login`、`passcode set`。
- **设置:** 每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](./configuration#settings-file)。
+
+## 控制台的画面 {#viewer-picture}
+
+**iOS 27 及以上**:画面直接用手机自己硬件编码的视频(CoreDevice 屏幕媒体流,HEVC),约每秒 60 帧、原生分辨率,本机不用编码,WDA 也不用截图。滚动时每秒 150~600 KB;画面静止时也一直有一点流量(白底页面约 15 KB/s,图多的页面约 250 KB/s)。转屏时页面按界面方向把画面转正,约 1~2 秒跟上。需要浏览器能解 HEVC:Mac 上的 Chrome、Safari 可以;Firefox 和多数 Linux 上的 Chrome 解不了,自动改用下面的 H.264 或 MJPEG。看画面期间手机不会自动锁屏,灵动岛显示屏幕正被查看,关掉页面 30 秒后恢复。
+
+**iOS 27 以下,或浏览器解不了 HEVC**:
+macOS 上,以及 Linux 上装了 ffmpeg 时,控制台的画面是 H.264,否则是 MJPEG。手机的画面先在本机编码(macOS 上本程序直接调 VideoToolbox,不需要 ffmpeg;Linux 上交给 ffmpeg),浏览器再用 WebCodecs 解码(浏览器自己选用硬件解码)。同样的画面,流量约为 MJPEG 的 1/15:画面静止时几乎为零,连续滚动时约 300~450 KB/s,MJPEG 要 4~10 MB/s。延迟和 MJPEG 相差不到一帧。
+
+- **编码器:** `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;画面静止时不再重复发同一张图,链路慢时只发最新的一张。
+- **看现在用的是哪种:** 画面下方写着,例如「实时画面 · 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/guide/configuration.md b/website/guide/configuration.md
index 05c2b05..09e5000 100644
--- a/website/guide/configuration.md
+++ b/website/guide/configuration.md
@@ -25,6 +25,8 @@ iphone-control service restart
| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |
| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。见表下说明 |
| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。见表下说明 |
+| `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | 控制台画面的编码:`auto` 在 iOS 27 及以上用手机自己的视频(HEVC),其余用 H.264(macOS 上直接用 VideoToolbox;Linux 上要装 ffmpeg),先试显卡编码;`device` 只用手机自己的视频,用不了时是 MJPEG;`mjpeg` 只用 MJPEG;也可以指定 `nvenc`、`vaapi`、`qsv`、`v4l2m2m`、`videotoolbox`、`x264`。`iphone-control viewer` 启动时会显示用的是哪个,见[命令行](./cli#viewer-picture) |
+| `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 的画质,1~51,越小越清晰、流量越大。`20` 正常使用看不出和原画的差别;`24` 约省三分之一流量,快速滚动时小字略糊 |
| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 |
| `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |
| `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |
@@ -46,6 +48,7 @@ MCP 服务由 AI 客户端拉起,注册时写进去的环境变量优先于设
| `ICTL_WDA_UNSIGNED` | 未签名 WDA 的路径。默认是数据目录的 `wda/WDA-unsigned.ipa`,第一次签名前下载。自己指定的路径不会下载 |
| `SCREEN_W` / `SCREEN_H` | HID 后备路线换算坐标用的屏幕尺寸(点):WDA 不可用、又没有这台设备的尺寸记录时才用,比如 WDA 从没连上过,或切到记录里没有尺寸的设备。不分设备,接多台时要小心 |
| `ICTL_LOG` | 日志级别,例如 `info,ictl_wda::http=debug` 记录每个 WDA 请求的耗时 |
+| `ICTL_FFMPEG` | ffmpeg 的路径(控制台的 H.264 画面;macOS 上只是 VideoToolbox 的备用)。默认在 `PATH` 里找,macOS 上还会找 Homebrew 的位置 |
## 目录和控制接口
diff --git a/website/guide/getting-started.md b/website/guide/getting-started.md
index defdcd7..8e5418c 100644
--- a/website/guide/getting-started.md
+++ b/website/guide/getting-started.md
@@ -45,6 +45,10 @@ systemctl --user enable --now iphone-control # 以普通用户运行,每
和手机通过 USB 通信要用系统的 usbmuxd:`sudo apt install usbmuxd`(其他发行版用对应的包管理器)。deb 包会自动装上它。
:::
+::: tip 可选:ffmpeg
+Linux 上装了 ffmpeg,控制台的画面改用 H.264,流量约为原来的 1/15,经隧道、走外网时更顺:`sudo apt install ffmpeg`。macOS 上不用装,直接就是 H.264。见[控制台的画面](./cli#viewer-picture)。
+:::
+
Intel Mac 没有预编译版本,要从源码编译;参与开发也从源码运行。见[从源码编译](../deploy/source)。
## 2. 接上手机,运行 iphone-control {#first-run}
diff --git a/website/troubleshoot/faq.md b/website/troubleshoot/faq.md
index 1e006c8..f24ec1f 100644
--- a/website/troubleshoot/faq.md
+++ b/website/troubleshoot/faq.md
@@ -60,9 +60,17 @@ iphone-control doctor # 逐层检查,每项失败都给出修复办法
画面区域会写明原因:没连上、还要配对或打开开发者模式(运行 `iphone-control setup --reconfigure` 选「手机」)、WDA 正在启动(通常 10–60 秒)、要先解锁。新设备上还没装 WDA 时,已登录 Apple ID 的可以点「签名并安装 WDA」,大约 1–2 分钟,期间保持手机解锁;没登录的运行 `iphone-control setup --reconfigure` 选「Apple ID」。AI 任务执行中,或设了 `IPHONE_UDID` 时,不能切换设备。见[多台设备](../guide/multi-device)。
+## 控制台画面卡、流量大
+
+看画面下方写的编码方式。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)。
+
+## 控制台开着时 WDA 每隔几分钟重启一次
+
+iOS 27 以下(或浏览器解不了 HEVC、改用 H.264/MJPEG)时,画面靠 WDA 一直截图,WDA 的 CPU 占到一个核以上。iOS 对一个进程的限额是一分钟平均 80%,超过就把它杀掉:手机上会有 `WebDriverAgentRunner-Runner.cpu_resource_fatal` 崩溃报告,守护进程记「WDA 不可用」,约 10 秒后重新拉起。期间操作会失败。不看的时候关掉控制台页面;iOS 27 及以上用手机自己的视频就没有这个问题(WDA 的 CPU 约 3%)。
+
## 灵动岛一直显示「配对的电脑」、手机不自动锁屏
-HID 后备路线使用时会开一个屏幕镜像会话,空闲 30 秒自动关闭。图标一直不消失时,重启一下守护进程(`iphone-control service restart`)。
+HID 后备路线使用时,以及控制台在显示手机自己的视频(iOS 27 及以上)时,会开一个屏幕镜像会话;不再使用(关掉控制台页面)30 秒后自动关闭。图标一直不消失时,重启一下守护进程(`iphone-control service restart`)。
## 报告问题