From d154a9fa8280a21aceaa82dfadeff238275bfd3a Mon Sep 17 00:00:00 2001 From: beichen24a1 <262405272+beichen24a1@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:13:44 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=8F=90=E9=AB=98=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=B8=A7=E7=8E=87=E5=B9=B6=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=20Windows=20=E6=88=AA=E5=9B=BE=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- changelog.d/427.feat.md | 2 + changelog.d/429.change.md | 2 + internal/i18n/locales/en/ui.json | 4 +- internal/i18n/locales/en/web.json | 4 +- internal/ui/API.en.md | 4 +- internal/ui/API.md | 4 +- internal/ui/backend.go | 2 +- internal/ui/device.go | 160 +++++++++++++--------------- internal/ui/device_test.go | 81 ++++++-------- internal/ui/fake_test.go | 24 +---- internal/ui/handlers.go | 9 +- internal/ui/shmshot.go | 20 +++- internal/ui/shmshot_other.go | 34 +++++- internal/ui/shmshot_windows.go | 14 ++- internal/ui/shmshot_windows_test.go | 88 +++++---------- internal/ui/shotrotation.go | 4 +- internal/ui/web/app.css | 4 +- internal/ui/web/dev/mock.js | 4 +- internal/ui/web/js/cards.js | 25 ++--- internal/ui/web/js/viewer.js | 141 ++++++++++++++++-------- 20 files changed, 329 insertions(+), 301 deletions(-) create mode 100644 changelog.d/427.feat.md create mode 100644 changelog.d/429.change.md diff --git a/changelog.d/427.feat.md b/changelog.d/427.feat.md new file mode 100644 index 00000000..805bd9e0 --- /dev/null +++ b/changelog.d/427.feat.md @@ -0,0 +1,2 @@ +画面弹窗支持 2–30 帧/秒,默认 15 帧/秒,显示实际帧率。 +The screen viewer supports 2–30 fps, defaults to 15 and shows the actual frame rate. diff --git a/changelog.d/429.change.md b/changelog.d/429.change.md new file mode 100644 index 00000000..17f638da --- /dev/null +++ b/changelog.d/429.change.md @@ -0,0 +1,2 @@ +管理器的卡片缩略图和画面弹窗统一使用共享内存截图。 +Manager thumbnails and the screen viewer use shared-memory capture. diff --git a/internal/i18n/locales/en/ui.json b/internal/i18n/locales/en/ui.json index c791b406..3238463d 100644 --- a/internal/i18n/locales/en/ui.json +++ b/internal/i18n/locales/en/ui.json @@ -113,10 +113,11 @@ "实例 %d 已整理磁盘,释放 %s": "Instance %d: disk cleaned up, freed %s", "实例 %d 已移除模块 %s": "Instance %d module %s removed", "实例 %d 已触发磁盘回收": "Instance %d: disk space reclaim triggered", + "实例 %d 本来就没开机": "Instance %d was not running", "实例 %d 截图失败: %s": "Instance %d screenshot failed: %s", "实例 %d 截图的数据不是 PNG(%d 字节)": "The screenshot data of instance %d is not a PNG (%d bytes)", "实例 %d 截图超时(%.0f 秒)": "Instance %d screenshot timed out (%.0f s)", - "实例 %d 本来就没开机": "Instance %d was not running", + "实例 %d 共享内存截图失败: %v": "Instance %d shared-memory capture failed: %v", "实例 %d 正在%s(任务 %s),等它做完再试": "Instance %d is busy (%s, task %s). Try again when it finishes", "实例 %d 正在%s,一台实例都没关": "Instance %d is busy (%s); no instance was shut down", "实例 %d 正在%s,等它做完再试": "Instance %d is busy (%s). Try again when it finishes", @@ -173,6 +174,7 @@ "当前平台暂不支持打开目录或浏览器": "Opening a folder or browser is not supported on this platform yet", "当前平台暂不支持窗口操作": "Window operations are not supported on this platform yet", "当前平台没有托盘图标和老板键": "This platform has no tray icon or boss key", + "取不到画面": "Cannot get the screen", "截图的显示尺寸读不出": "Cannot read the display size of the screenshot", "打不开管理器窗口: %v": "Cannot open the manager window: %v", "打开实例文件夹要给 index": "index is required to open an instance folder", diff --git a/internal/i18n/locales/en/web.json b/internal/i18n/locales/en/web.json index 3a88b6d2..58d94f39 100644 --- a/internal/i18n/locales/en/web.json +++ b/internal/i18n/locales/en/web.json @@ -269,7 +269,9 @@ "实例运行中,内存、CPU、帧率、分辨率、DPI、数据盘和声音在下次开机生效。诊断设置立即生效。": "The instance is running. Memory, CPU, frame rate, resolution, DPI, data disk and sound take effect at the next start; the diagnostics setting takes effect at once.", "实例里没有装别的应用": "No other apps are installed in the instance", "实例里的 Google 服务框架联网登记后才有:开着网等一两分钟,再试一次。": "It exists once Google Services Framework in the instance has registered online: stay online for a minute or two, then try again.", - "实时 · 约 2 帧/秒": "Live · about 2 frames/s", + "实际 {fps} 帧/秒": "Actual: {fps} fps", + "目标 {fps} 帧/秒": "Target: {fps} fps", + "目标帧率": "Target frame rate", "实时画面,可以点按": "Live screen, you can tap it", "实时跟随": "Follow live", "实验功能,要用的话在实例的「更多操作」菜单里开启": "Experimental. To use it, turn it on from the instance's “More actions” menu", diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index f96adf31..a83d6415 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -36,7 +36,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | Method | Path | Request | Response | | --- | --- | --- | --- | -| GET | `/api/info` | | `{"version","protocol","root":RootInfo}` | +| GET | `/api/info` | | `{"version","protocol","root":RootInfo,"live_screenshots":bool}` | | GET | `/api/locale` | | `{"language","preference","system","languages":[{code,name}],"messages"}`: the language the manager shows now (`zh-CN` / `en`), the one chosen in the settings (`auto` follows the system), what `auto` picks, the languages on offer, and the translations of the page's own strings (keyed by the Chinese text; `{}` in Chinese). Text the back end sends to the page (errors, progress, logs, check items) is already translated into `language`; the CLI's `--json`, MCP, logs and problem reports are not translated and stay Chinese | | PUT | `/api/locale` | `{preference: "auto"\|"zh-CN"\|"en"}` | as above; saved for this Windows user in `%LOCALAPPDATA%\ModAVD\language.json` (the CLI follows it too); the manager switches at once and the page reloads | | GET | `/api/theme` | | `{"preference","saved"}`: the interface theme (`system` follows the system, `light`, `dark`); `saved` is `false` while none has been saved (it reads as `system`), and the page then moves its browser's old choice over once | @@ -64,7 +64,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | POST | `/api/instances/{i}/gles32-off` | `{}` | 202 `Job` (`kind` is `gles32-off`): removes the line written above; after a cold boot the instance reports 3.1 again (same as `gles32 off`); the result is a `GLES32Result`. The checks are the same as for `gles32-on` | | GET | `/api/instances/{i}/playstore-gsfid` | | `{"index","decimal","hex"}`: the GSF ID of a running instance (same as `modavd playstore gsfid --json`; the decimal form is what GSF records, the hex form is the same number, with negative numbers in two's complement); takes a few seconds. Used to register at https://www.google.com/android/uncertified/. If the instance is not running (according to the latest list) or a job is running on it, it is 409 `busy`; if there is no ID yet it is 422 `not_ready` with `details.reason` `no_gsf_id` (stay online for a minute or two and try again) | | POST | `/api/instances/{i}/input` | `{type:"tap", x, y}` (the coordinates are in the pixels this instance displays (1280×720 or 1920×1080, with width and height swapped in portrait)) or `{type:"key", key:"back"\|"home"\|"recents"}` | `{}` | -| GET | `/api/instances/{i}/screenshot` | | `image/png` in the current display orientation (a shared-memory frame is turned by the instance's orientation setting while the guest's rotation is not known yet), `X-Shot-Source: shm` for shared memory or `adb` for `adb exec-out screencap -p`, `Cache-Control: no-store`; 409 if the instance is not running | +| GET | `/api/instances/{i}/screenshot` | Optional query `after` with the previous `X-Shot-Frame` value (empty on the first live request) | On Windows, shared-memory `image/png` in the current display orientation and `X-Shot-Frame` when available. 204 when the requested frame is unchanged, 409 when not booted, or an error when shared memory is unavailable. `Cache-Control: no-store`. Uses the instance orientation setting until the guest rotation is known. macOS uses adb capture. | | GET | `/api/instances/{i}/log?kind=emulator\|logcat&lines=300` | | `text/plain; charset=utf-8`, the tail of the newest log; 404 if there is none | | GET | `/api/instances/{i}/proxy` | | `ProxyView`, see below | | PUT | `/api/instances/{i}/proxy` | `{enabled?: bool, server?: string, apps?: [string]}` | `ProxyView`: the items given are replaced with the new values, the ones not given stay unchanged; giving no item at all returns 400 `usage`. `server` may omit the protocol (it is detected) or be `auto` (take this computer's proxy settings); when it is turned on for the first time without an address, `auto` is used as well. If the address cannot be probed, 502 `proxy_unavailable`. If the instance is running, it takes effect immediately and returns within a few seconds | diff --git a/internal/ui/API.md b/internal/ui/API.md index ab0698e3..79a757e2 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -36,7 +36,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | 方法 | 路径 | 请求 | 返回 | | --- | --- | --- | --- | -| GET | `/api/info` | | `{"version","protocol","root":RootInfo}` | +| GET | `/api/info` | | `{"version","protocol","root":RootInfo,"live_screenshots":bool}` | | GET | `/api/locale` | | `{"language","preference","system","languages":[{code,name}],"messages"}`:管理器现在用的语言(`zh-CN` / `en`)、设置里选的(`auto` 是跟随系统)、跟随系统时会选哪种、可选的语言,以及页面自己那部分字符串的译文(键是中文原文,中文时是 `{}`)。后端发给页面的文字(错误、进度、日志、检查项)已经按 `language` 翻好;命令行 `--json`、MCP、日志和问题包不翻,照旧是中文 | | PUT | `/api/locale` | `{preference: "auto"\|"zh-CN"\|"en"}` | 同上;记进这个 Windows 用户的 `%LOCALAPPDATA%\ModAVD\language.json`(命令行也按它选),管理器马上换语言,页面随后重新加载 | | GET | `/api/theme` | | `{"preference","saved"}`:界面主题(`system` 跟随系统 / `light` / `dark`),`saved` 是 `false` 时还没存过(按 `system`),页面会把自己浏览器里旧的选择搬过来一次 | @@ -64,7 +64,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | POST | `/api/instances/{i}/gles32-off` | `{}` | 202 `Job`(`kind` 是 `gles32-off`):去掉上面写进去的行,冷启动后实例改回报 3.1(同 `gles32 off`);结果是 `GLES32Result`。检查同 `gles32-on` | | GET | `/api/instances/{i}/playstore-gsfid` | | `{"index","decimal","hex"}`:开着的实例的 GSF ID(同 `modavd playstore gsfid --json`;十进制是 GSF 记的,十六进制是同一个数,负数按补码),几秒钟。用来到 https://www.google.com/android/uncertified/ 登记。没开机(按最近的列表)或实例上有任务在跑是 409 `busy`;还没有 ID 是 422 `not_ready`,`details.reason` 为 `no_gsf_id`(开着网等一两分钟再试) | | POST | `/api/instances/{i}/input` | `{type:"tap", x, y}`(坐标是这台实例显示的像素(1280×720 或 1920×1080,竖屏时宽高对调))或 `{type:"key", key:"back"\|"home"\|"recents"}` | `{}` | -| GET | `/api/instances/{i}/screenshot` | | 当前显示方向的 `image/png`(共享内存的帧在客体方向暂时读不到时按实例设置的方向转),`X-Shot-Source` 为 `shm`(共享内存)或 `adb`(`adb exec-out screencap -p`),`Cache-Control: no-store`;没开机回 409 | +| GET | `/api/instances/{i}/screenshot` | 可选查询参数 `after`,填上次返回的 `X-Shot-Frame`,实时取图的首次请求留空 | Windows 上共享内存的当前方向 `image/png` 和帧标识 `X-Shot-Frame`(可用时)。帧没变回 204,没开机回 409,共享内存不可用时报错。`Cache-Control: no-store`。读到客体方向前按实例设置的方向转。macOS 仍使用 adb 截图。 | | GET | `/api/instances/{i}/log?kind=emulator\|logcat&lines=300` | | `text/plain; charset=utf-8`,最新那份日志的末尾;没有回 404 | | GET | `/api/instances/{i}/proxy` | | `ProxyView`,见下 | | PUT | `/api/instances/{i}/proxy` | `{enabled?: bool, server?: string, apps?: [string]}` | `ProxyView`:给出的项换成新值,没给的不变;一项都没给回 400 `usage`。`server` 可以不写协议(探测出来)或写 `auto`(取这台电脑的代理设置);第一次打开没给地址也按 `auto`。地址探测不到回 502 `proxy_unavailable`。实例开着就马上生效,几秒内回 | diff --git a/internal/ui/backend.go b/internal/ui/backend.go index 7c76288e..03f0a500 100644 --- a/internal/ui/backend.go +++ b/internal/ui/backend.go @@ -57,7 +57,7 @@ type backend interface { // GLES32 is `modavd gles32 on|off|status`; GLES32Check what it refuses before touching the instance (no bridge ...). GLES32(ctx context.Context, i int, action string) (*emu.GLES32Result, error) GLES32Check(i int, action string) error - // AdbRun is Manager.ADB.Run (the screenshot: exec-out screencap -p with Raw). + // AdbRun supports screenshot capture on hosts without ModAVDExtras. AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result // Serial is instance i's adb serial in the root's port plan. Serial(i int) string diff --git a/internal/ui/device.go b/internal/ui/device.go index b3b01c70..c133aabb 100644 --- a/internal/ui/device.go +++ b/internal/ui/device.go @@ -11,13 +11,11 @@ import ( "sync" "time" - "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" ) const ( - shotTimeout = 10 * time.Second // shotReuse: a capture this young is served again; several views of one instance (list thumbnail, detail) then // cost one screencap. shotReuse = 300 * time.Millisecond @@ -26,8 +24,6 @@ const ( inputTimeout = 10 * time.Second ) -var pngSignature = []byte("\x89PNG\r\n\x1a\n") - // shotCache holds at most one capture in flight per instance and its last result. type shotCache struct { mu sync.Mutex @@ -35,12 +31,11 @@ type shotCache struct { } type shotEntry struct { - data []byte - src string // shotSourceShm or shotSourceAdb: where data came from - at time.Time - flight *shotCall - // shmSkip: no shared-memory attempt before this time (the last one failed: library absent, sharing off, old emulator) - shmSkip time.Time + data []byte + id string + at time.Time + flight *shotCall + failureLogged time.Time rotation *shotRotation rotationRetry time.Time rotationRevision uint64 @@ -49,18 +44,10 @@ type shotEntry struct { type shotCall struct { done chan struct{} data []byte - src string + id string err error } -const ( - // X-Shot-Source values: the page refreshes thumbnails of an unfocused window only when they come from shared memory. - shotSourceShm = "shm" - shotSourceAdb = "adb" - // shmRetry: how long after a failed shared-memory capture the instance goes straight to adb. - shmRetry = 20 * time.Second -) - func (c *shotCache) entry(i int) *shotEntry { if c.by == nil { c.by = map[int]*shotEntry{} @@ -87,29 +74,36 @@ func (s *server) handleScreenshot(w http.ResponseWriter, r *http.Request) { if !ok { return } - data, src, err := s.screenshot(r.Context(), i) + query := r.URL.Query() + data, id, err := s.screenshot(r.Context(), i, query.Has("after")) if err != nil { writeError(w, err) return } h := w.Header() - h.Set("Content-Type", "image/png") - h.Set("X-Shot-Source", src) h.Set("Cache-Control", "no-store") + if id != "" && id == query.Get("after") { + w.WriteHeader(http.StatusNoContent) + return + } + h.Set("Content-Type", "image/png") + if id != "" { + h.Set("X-Shot-Frame", id) + } h.Set("Content-Length", strconv.Itoa(len(data))) w.WriteHeader(http.StatusOK) w.Write(data) } -// screenshot joins the capture in flight, reuses one younger than shotReuse, or starts one. The capture runs on the -// server's context, so a viewer that goes away does not fail the others waiting for it. -func (s *server) screenshot(ctx context.Context, i int) ([]byte, string, error) { +// Live viewers sample a fresh frame. Thumbnails and input validation can reuse a recent one. +// Both share captures in flight, which outlive any individual caller. +func (s *server) screenshot(ctx context.Context, i int, live bool) ([]byte, string, error) { s.shots.mu.Lock() e := s.shots.entry(i) - if e.data != nil && time.Since(e.at) < shotReuse { - data, src := e.data, e.src + if !live && e.data != nil && time.Since(e.at) < shotReuse { + data, id := e.data, e.id s.shots.mu.Unlock() - return data, src, nil + return data, id, nil } call := e.flight if call == nil { @@ -120,30 +114,27 @@ func (s *server) screenshot(ctx context.Context, i int) ([]byte, string, error) s.shots.mu.Unlock() select { case <-call.done: - return call.data, call.src, call.err + return call.data, call.id, call.err case <-ctx.Done(): return nil, "", errs.Wrap(errs.Canceled, ctx.Err(), "已取消") } } func (s *server) capture(i int, e *shotEntry, call *shotCall) { - ctx, cancel := context.WithTimeout(s.ctx, shotTimeout) - defer cancel() s.shots.mu.Lock() - skip := time.Now().Before(e.shmSkip) revision := e.rotationRevision s.shots.mu.Unlock() - data, src, shmFailed, err := s.captureOnce(ctx, i, e, skip) + data, id, err := s.captureOnce(i, e) s.shots.mu.Lock() e.flight = nil - if shmFailed { - e.shmSkip = time.Now().Add(shmRetry) - } - if err == nil && (src != shotSourceShm || revision == e.rotationRevision) { - e.data, e.src, e.at = data, src, time.Now() + if err != nil { + e.data = nil + } else if revision == e.rotationRevision { + e.data, e.id, e.at = data, id, time.Now() + e.failureLogged = time.Time{} } s.shots.mu.Unlock() - call.data, call.src, call.err = data, src, err + call.data, call.id, call.err = data, id, err close(call.done) } @@ -152,38 +143,47 @@ func notBooted(i int) error { return errs.Newf(errs.Busy, "实例 %d 没有开机", i).WithAdvice("开机后再看画面") } -// captureOnce takes the frame from the emulator's shared memory when it can (unless skipShm), else from adb screencap. -// shmFailed: the shared-memory attempt was made and failed, so the caller holds the next ones back for a while. -func (s *server) captureOnce(ctx context.Context, i int, e *shotEntry, skipShm bool) (data []byte, src string, shmFailed bool, err error) { - // A recent list that says offline saves an adb call (which would also start the private adb server). +func (s *server) captureOnce(i int, e *shotEntry) ([]byte, string, error) { if in, ok := s.hub.cachedInstance(i, statusMaxAge); ok && !in.Running { - return nil, "", false, notBooted(i) + return nil, "", notBooted(i) } - if !skipShm && s.frame != nil { - png, ferr := s.captureSharedFrame(i, e) - if ferr == nil { - return png, shotSourceShm, false, nil - } - shmFailed = true - } - data, err = s.captureAdb(ctx, i) + data, id, err := s.capturePlatformFrame(i, e) if err == nil { - src = shotSourceAdb + return data, id, nil + } + s.shots.mu.Lock() + logFailure := time.Since(e.failureLogged) >= 30*time.Second + if sharedMemoryScreenshots && logFailure { + e.failureLogged = time.Now() } - return data, src, shmFailed, err + s.shots.mu.Unlock() + if logFailure { + s.log.Warnf("实例 %d 共享内存截图失败: %v", i, err) + } + ctx, cancel := context.WithTimeout(s.ctx, 6*time.Second) + defer cancel() + in, statusErr := s.instanceNow(ctx, i) + if statusErr != nil { + return nil, "", statusErr + } + if !in.Booted { + return nil, "", notBooted(i) + } + if !sharedMemoryScreenshots { + return nil, "", err + } + return nil, "", errs.New(errs.Internal, "取不到画面") } // captureSharedFrame reads the shared frame and turns it upright: by the guest's display rotation when the watcher // knows it, else by the instance's setting (fallbackShotRotation; never waiting for the watcher, never adb for it). -// The watcher starts only once a shared frame was read: an instance without shared memory stays on adb screencap and -// gets no adb shell for it. A rotation that changes while the frame is read is tried once more; capture does not keep -// a frame whose rotation changed meanwhile. -func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, error) { +// The watcher starts only after a shared frame is read. A rotation that changes during the read is tried once more. +func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, string, error) { for attempt := 0; ; attempt++ { before, knownBefore := s.currentShotRotation(e) frame, err := s.frame(s.root.Dir, s.mgr.Serial(i)) if err != nil { - return nil, err + return nil, "", err } rotation, known := s.shotRotationFor(i, e) if known && (!knownBefore || before != rotation) && attempt == 0 { @@ -193,36 +193,20 @@ func (s *server) captureSharedFrame(i int, e *shotEntry) ([]byte, error) { if !known { angle = s.fallbackShotRotation(i, frame) } - return frame.png(angle) - } -} - -func (s *server) captureAdb(ctx context.Context, i int) ([]byte, error) { - res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: s.mgr.Serial(i), Timeout: shotTimeout, Raw: true}, - "exec-out", "screencap", "-p") - if res.Code == 0 && bytes.HasPrefix(res.Stdout, pngSignature) { - return res.Stdout, nil - } - if ctx.Err() != nil { - if s.ctx.Err() != nil { - return nil, errs.New(errs.Canceled, "管理器正在退出") + var id string + if frame.timestamp != 0 || frame.number != 0 { + id = fmt.Sprintf("%x-%x-%x", frame.timestamp, frame.number, angle) + s.shots.mu.Lock() + data := e.data + unchanged := data != nil && e.id == id + s.shots.mu.Unlock() + if unchanged { + return data, id, nil + } } - return nil, errs.Newf(errs.Timeout, "实例 %d 截图超时(%.0f 秒)", i, shotTimeout.Seconds()) - } - // Find out why: an instance that is not (or no longer) booted is the usual reason, and a 409 for it. - ictx, cancel := context.WithTimeout(s.ctx, 6*time.Second) - defer cancel() - info, err := s.mgr.Info(ictx, i) - if err != nil { - return nil, err - } - if !info.Booted { - return nil, notBooted(i) - } - if res.Code != 0 { - return nil, errs.Newf(errs.Internal, "实例 %d 截图失败: %s", i, clip(res.Out, 300)) + data, err := frame.png(angle) + return data, id, err } - return nil, errs.Newf(errs.Internal, "实例 %d 截图的数据不是 PNG(%d 字节)", i, len(res.Stdout)) } // clip keeps the first n bytes of s on a rune boundary. @@ -306,7 +290,7 @@ func (s *server) handleInput(w http.ResponseWriter, r *http.Request) { if body.Type == "tap" { // Config describes the next boot. A running guest may still use the previous // preset, so validate against its screenshot, shared with the viewer cache. - data, _, err := s.screenshot(r.Context(), i) + data, _, err := s.screenshot(r.Context(), i, false) if err != nil { writeError(w, err) return diff --git a/internal/ui/device_test.go b/internal/ui/device_test.go index 4f41c3f2..22ca310e 100644 --- a/internal/ui/device_test.go +++ b/internal/ui/device_test.go @@ -4,10 +4,9 @@ package ui import ( "bytes" + "context" "errors" "fmt" - "image" - "image/png" "io" "io/fs" "mime/multipart" @@ -17,11 +16,11 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "unicode/utf8" - "modavd/internal/adb" "modavd/internal/emu" "modavd/internal/errs" "modavd/internal/root" @@ -51,11 +50,21 @@ func TestManagerBackendSerial(t *testing.T) { func TestScreenshot(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - png := append(append([]byte{}, pngSignature...), []byte("IHDR rest of the image")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: png} - h.f.shotDelay = 150 * time.Millisecond - h.f.mu.Unlock() + frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4} + want, err := frame.png(rotation0) + if err != nil { + t.Fatal(err) + } + var calls atomic.Int32 + h.s.frame = func(_, serial string) (sharedFrame, error) { + if serial != "emulator-21030" { + return sharedFrame{}, errors.New("no frame for " + serial) + } + frame := frame + frame.number = uint32(calls.Add(1)) + time.Sleep(150 * time.Millisecond) + return frame, nil + } // five viewers at once share one capture var wg sync.WaitGroup @@ -73,60 +82,38 @@ func TestScreenshot(t *testing.T) { } wg.Wait() for _, b := range bodies { - if !bytes.Equal(b, png) { + if !bytes.Equal(b, want) { t.Fatalf("screenshot body %q", b) } } - if n := h.f.adbCalls.Load(); n != 1 { + if n := calls.Load(); n != 1 { t.Fatalf("%d captures for five concurrent requests", n) } - // the serial is the root's (portBase 21000 in the fake), never counted from 20000 here - h.f.mu.Lock() - serials := append([]string(nil), h.f.shotSerials...) - h.f.mu.Unlock() - if len(serials) != 1 || serials[0] != "emulator-21030" { - t.Fatalf("captured serials %q", serials) - } - // a capture younger than 300 ms is served again - expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) - if n := h.f.adbCalls.Load(); n != 1 { - t.Fatalf("fresh capture not reused (%d captures)", n) + // Cards reuse a recent capture. Live requests sample shared memory again immediately. + resp := h.do("GET", "/api/instances/3/screenshot", nil) + before := resp.Header.Get("X-Shot-Frame") + expect(t, resp, 200, nil) + resp = h.do("GET", "/api/instances/3/screenshot?after="+before, nil) + if id := resp.Header.Get("X-Shot-Frame"); id == "" || id == before || calls.Load() != 2 { + t.Fatalf("live screenshot: old ID=%q, new ID=%q, captures=%d", before, id, calls.Load()) } - time.Sleep(shotReuse + 50*time.Millisecond) - expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) - if n := h.f.adbCalls.Load(); n != 2 { - t.Fatalf("stale capture reused (%d captures)", n) - } - - // adb output that is no PNG - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: []byte("/system/bin/sh: screencap: not found\r\n")} - h.f.shotDelay = 0 - h.f.mu.Unlock() - time.Sleep(shotReuse + 50*time.Millisecond) - expectError(t, h.do("GET", "/api/instances/3/screenshot", nil), 500, errs.Internal) - - // not booted: 409; unknown instance: 404 - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 1, Out: "error: device 'emulator-20040' not found"} - h.f.mu.Unlock() + expect(t, resp, 200, nil) expectError(t, h.do("GET", "/api/instances/4/screenshot", nil), http.StatusConflict, errs.Busy) expectError(t, h.do("GET", "/api/instances/8/screenshot", nil), http.StatusNotFound, errs.NotFound) } -func displayPNG(t *testing.T, width, height int) []byte { - t.Helper() - var b bytes.Buffer - if err := png.Encode(&b, image.NewGray(image.Rect(0, 0, width, height))); err != nil { - t.Fatal(err) +func setFrameSize(s *server, width, height int) { + frame := sharedFrame{pixels: make([]byte, width*height*4), width: width, height: height, stride: width * 4} + s.frame = func(string, string) (sharedFrame, error) { return frame, nil } + s.readDisplayRotation = func(_ context.Context, _ int, _ string, publish func(displayRotation)) { + publish(rotation0) } - return b.Bytes() } func TestInputValidation(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - h.f.shot = adb.Result{Code: 0, Stdout: displayPNG(t, 1280, 720)} + setFrameSize(h.s, 1280, 720) ok := map[string]string{ `{"type":"tap","x":100,"y":200}`: "input tap 100 200", @@ -422,7 +409,7 @@ func TestInputUsesLiveDisplayAfterPresetChange(t *testing.T) { in.Config.Width, in.Config.Height = 1920, 1080 } h.f.instances[3] = in - h.f.shot = adb.Result{Code: 0, Stdout: displayPNG(t, dimensions[0], dimensions[1])} + setFrameSize(h.s, dimensions[0], dimensions[1]) h.f.mu.Unlock() x, y := dimensions[0]-1, dimensions[1]-1 expect(t, h.do("POST", "/api/instances/3/input", fmt.Sprintf(`{"type":"tap","x":%d,"y":%d}`, x, y)), 200, nil) diff --git a/internal/ui/fake_test.go b/internal/ui/fake_test.go index 2f0272e7..a719f25d 100644 --- a/internal/ui/fake_test.go +++ b/internal/ui/fake_test.go @@ -77,12 +77,8 @@ type fake struct { toggles []string showHidden int - shot adb.Result - shotDelay time.Duration - shotSerials []string // the serial of each capture - adbCalls atomic.Int32 - listCalls atomic.Int32 - checks atomic.Int32 + listCalls atomic.Int32 + checks atomic.Int32 } type fakeInstall struct { @@ -497,20 +493,8 @@ func (b fakeBackend) DiskCompact(ctx context.Context, i int) (*emu.DiskCompactRe BeforeOnDiskBytes: 12 << 30, AfterOnDiskBytes: 10 << 30, FreedBytes: 2 << 30}, nil } -func (b fakeBackend) AdbRun(ctx context.Context, opt adb.RunOptions, args ...string) adb.Result { - b.f.adbCalls.Add(1) - b.f.mu.Lock() - res, delay := b.f.shot, b.f.shotDelay - b.f.shotSerials = append(b.f.shotSerials, opt.Serial) - b.f.mu.Unlock() - if delay > 0 { - select { - case <-time.After(delay): - case <-ctx.Done(): - return adb.Result{Code: -1, Out: "已取消"} - } - } - return res +func (fakeBackend) AdbRun(context.Context, adb.RunOptions, ...string) adb.Result { + panic("Windows manager screenshots must use shared memory") } func (b fakeBackend) RootInfo() emu.RootInfo { return fakeRoot } diff --git a/internal/ui/handlers.go b/internal/ui/handlers.go index 5e8596f7..49bc7de1 100644 --- a/internal/ui/handlers.go +++ b/internal/ui/handlers.go @@ -26,10 +26,11 @@ func detached(r *http.Request) context.Context { return context.WithoutCancel(r. func (s *server) handleInfo(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, struct { - Version string `json:"version"` - Protocol int `json:"protocol"` - Root emu.RootInfo `json:"root"` - }{buildinfo.Version, buildinfo.Protocol, s.mgr.RootInfo()}) + Version string `json:"version"` + Protocol int `json:"protocol"` + Root emu.RootInfo `json:"root"` + LiveScreenshots bool `json:"live_screenshots"` + }{buildinfo.Version, buildinfo.Protocol, s.mgr.RootInfo(), sharedMemoryScreenshots}) } func (s *server) handleList(w http.ResponseWriter, r *http.Request) { diff --git a/internal/ui/shmshot.go b/internal/ui/shmshot.go index 7d9053ad..7b2abe2b 100644 --- a/internal/ui/shmshot.go +++ b/internal/ui/shmshot.go @@ -5,11 +5,28 @@ import ( "errors" "image" "image/png" + "sync" ) +// PNG keeps its compressor and scanline buffers here across live captures. +type shotEncoderPool struct{ buffers sync.Pool } + +func (p *shotEncoderPool) Get() *png.EncoderBuffer { + if b := p.buffers.Get(); b != nil { + return b.(*png.EncoderBuffer) + } + return nil +} + +func (p *shotEncoderPool) Put(b *png.EncoderBuffer) { p.buffers.Put(b) } + +var shotEncoder = png.Encoder{CompressionLevel: png.BestSpeed, BufferPool: &shotEncoderPool{}} + type sharedFrame struct { pixels []byte width, height, stride int + number uint32 + timestamp uint64 } func (f sharedFrame) png(rotation displayRotation) ([]byte, error) { @@ -43,8 +60,7 @@ func (f sharedFrame) png(rotation displayRotation) ([]byte, error) { } } var b bytes.Buffer - enc := png.Encoder{CompressionLevel: png.BestSpeed} - if err := enc.Encode(&b, img); err != nil { + if err := shotEncoder.Encode(&b, img); err != nil { return nil, err } return b.Bytes(), nil diff --git a/internal/ui/shmshot_other.go b/internal/ui/shmshot_other.go index 26a27868..c4767a2d 100644 --- a/internal/ui/shmshot_other.go +++ b/internal/ui/shmshot_other.go @@ -2,7 +2,39 @@ package ui -import "errors" +import ( + "bytes" + "context" + "errors" + "time" + + "modavd/internal/adb" + "modavd/internal/errs" +) + +const sharedMemoryScreenshots = false + +// Non-Windows packages have no shared-memory library. This is their screenshot path. +func (s *server) capturePlatformFrame(i int, _ *shotEntry) ([]byte, string, error) { + const timeout = 10 * time.Second + ctx, cancel := context.WithTimeout(s.ctx, timeout) + defer cancel() + res := s.mgr.AdbRun(ctx, adb.RunOptions{Serial: s.mgr.Serial(i), Timeout: timeout, Raw: true}, + "exec-out", "screencap", "-p") + if res.Code == 0 && bytes.HasPrefix(res.Stdout, []byte("\x89PNG\r\n\x1a\n")) { + return res.Stdout, "", nil + } + if ctx.Err() != nil { + if s.ctx.Err() != nil { + return nil, "", errs.New(errs.Canceled, "管理器正在退出") + } + return nil, "", errs.Newf(errs.Timeout, "实例 %d 截图超时(%.0f 秒)", i, timeout.Seconds()) + } + if res.Code != 0 { + return nil, "", errs.Newf(errs.Internal, "实例 %d 截图失败: %s", i, clip(res.Out, 300)) + } + return nil, "", errs.Newf(errs.Internal, "实例 %d 截图的数据不是 PNG(%d 字节)", i, len(res.Stdout)) +} // shmFrame: the screenshot library is Windows only; elsewhere thumbnails stay on adb. func shmFrame(rootDir, serial string) (sharedFrame, error) { diff --git a/internal/ui/shmshot_windows.go b/internal/ui/shmshot_windows.go index ff1b8a82..3a419b11 100644 --- a/internal/ui/shmshot_windows.go +++ b/internal/ui/shmshot_windows.go @@ -19,10 +19,15 @@ import ( // replacing the DLL. const ( - mxFmtBGRA = 1 - mxOK = 0 + sharedMemoryScreenshots = true + mxFmtBGRA = 1 + mxOK = 0 ) +func (s *server) capturePlatformFrame(i int, e *shotEntry) ([]byte, string, error) { + return s.captureSharedFrame(i, e) +} + type mxOpenParams struct { Size uint32 _ uint32 @@ -101,7 +106,10 @@ func shmFrame(rootDir, serial string) (sharedFrame, error) { buf := make([]byte, int(size)) switch r := call(buf, &info); r { case mxOK: - return sharedFrame{pixels: buf, width: int(info.Width), height: int(info.Height), stride: int(info.Stride)}, nil + return sharedFrame{ + pixels: buf, width: int(info.Width), height: int(info.Height), stride: int(info.Stride), + number: info.FrameNumber, timestamp: info.TimestampUs, + }, nil case -5: // MODAVD_E_BUFFER: grew in between, probe again continue default: diff --git a/internal/ui/shmshot_windows_test.go b/internal/ui/shmshot_windows_test.go index 30400017..e552f538 100644 --- a/internal/ui/shmshot_windows_test.go +++ b/internal/ui/shmshot_windows_test.go @@ -11,23 +11,19 @@ import ( "testing" "time" - "modavd/internal/adb" "modavd/internal/avd" "modavd/internal/emu" + "modavd/internal/errs" ) func TestScreenshotSharedMemory(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4} + frame := sharedFrame{pixels: []byte{12, 34, 56, 0}, width: 1, height: 1, stride: 4, number: 1} shm, err := frame.png(rotation0) if err != nil { t.Fatal(err) } - adbPNG := append(append([]byte{}, pngSignature...), []byte("from adb")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: adbPNG} - h.f.mu.Unlock() var calls atomic.Int32 var serial, dir atomic.Value @@ -45,67 +41,37 @@ func TestScreenshotSharedMemory(t *testing.T) { } return frame, nil } - get := func() (string, string) { - t.Helper() - resp := h.do("GET", "/api/instances/3/screenshot", nil) - defer resp.Body.Close() - if resp.StatusCode != 200 { - t.Fatalf("status %d", resp.StatusCode) - } - b, _ := io.ReadAll(resp.Body) - return string(b), resp.Header.Get("X-Shot-Source") - } - - if body, src := get(); body != string(shm) || src != "shm" { - t.Fatalf("shared memory capture: %q from %q", body, src) - } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls for a shared-memory frame", n) + resp := h.do("GET", "/api/instances/3/screenshot", nil) + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + id := resp.Header.Get("X-Shot-Frame") + if resp.StatusCode != 200 || id == "" || !bytes.Equal(body, shm) { + t.Fatalf("shared memory capture: status %d, frame %q", resp.StatusCode, id) } if serial.Load() != "emulator-21030" || dir.Load() != h.s.root.Dir { t.Fatalf("asked for %v in %v", serial.Load(), dir.Load()) } + expect(t, h.do("GET", "/api/instances/3/screenshot?after="+id, nil), 204, nil) - // shared memory fails: adb answers, and the next capture does not even try shared memory + // A failed read returns an error. A later request can read shared memory again immediately. fail.Store(true) - time.Sleep(shotReuse + 50*time.Millisecond) - if body, src := get(); body != string(adbPNG) || src != "adb" { - t.Fatalf("fallback: %q from %q", body, src) - } + expectError(t, h.do("GET", "/api/instances/3/screenshot?after="+id, nil), 500, errs.Internal) tried := calls.Load() - time.Sleep(shotReuse + 50*time.Millisecond) - if _, src := get(); src != "adb" || calls.Load() != tried { - t.Fatalf("shared memory retried inside the hold-back (%d -> %d calls)", tried, calls.Load()) - } - - h.s.frame = func(string, string) (sharedFrame, error) { return sharedFrame{}, nil } - h.s.shots.forget(3) - if body, src := get(); body != string(adbPNG) || src != "adb" { - t.Fatalf("invalid frame: %q from %q", body, src) - } - - // no library function at all: adb only - h.s.frame = nil - h.s.shots.forget(3) - if _, src := get(); src != "adb" { - t.Fatalf("source %q without frame function", src) + fail.Store(false) + expect(t, h.do("GET", "/api/instances/3/screenshot", nil), 200, nil) + if calls.Load() <= tried { + t.Fatal("shared memory was not retried") } } -// An instance without a shared frame (no extras library, sharing off) stays on adb screencap and gets no rotation -// watcher: that is an adb shell in the guest, and a shell for nothing. func TestScreenshotWithoutSharedFrameStartsNoRotationWatcher(t *testing.T) { h := newHarness(t, nil) h.f.put(3, emu.StatusOnline) - adbPNG := append(append([]byte{}, pngSignature...), []byte("from adb")...) - h.f.mu.Lock() - h.f.shot = adb.Result{Code: 0, Stdout: adbPNG} - h.f.mu.Unlock() var watchers atomic.Int32 h.s.readDisplayRotation = func(context.Context, int, string, func(displayRotation)) { watchers.Add(1) } h.s.frame = func(string, string) (sharedFrame, error) { return sharedFrame{}, errors.New("sharing is off") } - if _, src, err := h.s.screenshot(t.Context(), 3); err != nil || src != shotSourceAdb { + if _, src, err := h.s.screenshot(t.Context(), 3, false); errs.CodeOf(err) != errs.Internal { t.Fatalf("screenshot from %q: %v", src, err) } h.s.shots.mu.Lock() @@ -157,13 +123,13 @@ func TestScreenshotReusesFirstFrameAndRetriesAfterRotation(t *testing.T) { } // the watcher has no rotation yet: the first frame does not wait for it - first, src, err := h.s.screenshot(t.Context(), 3) - if src != shotSourceShm || err != nil { + first, src, err := h.s.screenshot(t.Context(), 3, false) + if err != nil { t.Fatalf("initial screenshot from %q: %v", src, err) } reads := readFrames.Load() - reused, src, err := h.s.screenshot(t.Context(), 3) - if src != shotSourceShm || err != nil || !bytes.Equal(first, reused) || readFrames.Load() != reads { + reused, src, err := h.s.screenshot(t.Context(), 3, false) + if err != nil || !bytes.Equal(first, reused) || readFrames.Load() != reads { t.Fatalf("second request from %q, err=%v, read %d more raw frames", src, err, readFrames.Load()-reads) } @@ -185,14 +151,11 @@ func TestScreenshotReusesFirstFrameAndRetriesAfterRotation(t *testing.T) { e.at = time.Time{} h.s.shots.mu.Unlock() rotateOnRead.Store(true) - got, src, err := h.s.screenshot(t.Context(), 3) + got, src, err := h.s.screenshot(t.Context(), 3, false) want, encodeErr := after.png(rotation270) - if src != shotSourceShm || err != nil || encodeErr != nil || !bytes.Equal(got, want) { + if err != nil || encodeErr != nil || !bytes.Equal(got, want) { t.Fatalf("expected a fresh rotated frame, got %q (screenshot error %v, encoding error %v)", src, err, encodeErr) } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls", n) - } } // ModAVD/ModAVD#391: while the guest's rotation is unknown (the watcher gets nothing), a frame is still read from @@ -217,8 +180,8 @@ func TestScreenshotUnknownRotationUsesInstanceSetting(t *testing.T) { for i, angle := range map[int]displayRotation{3: rotation270, 4: rotation0} { started := time.Now() - got, src, err := h.s.screenshot(t.Context(), i) - if err != nil || src != shotSourceShm { + got, src, err := h.s.screenshot(t.Context(), i, false) + if err != nil { t.Fatalf("instance %d: %q, %v", i, src, err) } if waited := time.Since(started); waited > time.Second { @@ -232,9 +195,6 @@ func TestScreenshotUnknownRotationUsesInstanceSetting(t *testing.T) { t.Errorf("instance %d: frame not turned by rotation %d", i, angle) } } - if n := h.f.adbCalls.Load(); n != 0 { - t.Fatalf("%d adb calls while the rotation is unknown", n) - } for deadline := time.Now().Add(5 * time.Second); watchers.Load() < 2; time.Sleep(5 * time.Millisecond) { if time.Now().After(deadline) { t.Fatalf("%d rotation watchers started, want one per instance", watchers.Load()) diff --git a/internal/ui/shotrotation.go b/internal/ui/shotrotation.go index ca5590ed..f68ddefb 100644 --- a/internal/ui/shotrotation.go +++ b/internal/ui/shotrotation.go @@ -154,9 +154,7 @@ func (s *server) runShotRotation(i int, e *shotEntry, r *shotRotation) { func (e *shotEntry) invalidateShotRotation() { e.rotationRevision++ - if e.src == shotSourceShm { - e.data = nil - } + e.data = nil } // Read events beginning just before the snapshot so a switch during dumpsys is visible. diff --git a/internal/ui/web/app.css b/internal/ui/web/app.css index 8e6a6ebd..7dd0ee3b 100644 --- a/internal/ui/web/app.css +++ b/internal/ui/web/app.css @@ -1108,7 +1108,9 @@ dialog > .toasts .toast.out { animation-name: toast-out-left; } /* viewer: the dialog hugs the 16:9 frame (no side bands), the keys sit in the title row */ .dlg-viewer { --w: min(1180px, calc((100vh - 176px) * 16 / 9 + 40px)); } .dlg-viewer .dlg-body { padding: 0 20px 20px; overflow: hidden; scrollbar-gutter: auto; } -.viewer-tools { display: flex; align-items: center; gap: 12px; flex: none; margin-top: -2px; } +.viewer-tools { display: flex; align-items: center; gap: 8px 12px; flex: none; flex-wrap: wrap; margin-top: -2px; } +.viewer-rate { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; } +.viewer-rate input { width: 88px; } .viewer-frame { position: relative; width: 100%; max-height: calc(100vh - 176px); aspect-ratio: 16 / 9; margin: 0 auto; border-radius: 10px; overflow: hidden; background: #120D0B; cursor: crosshair; user-select: none; diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index bae99958..bf9343e7 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -966,7 +966,7 @@ async function handle(url, init) { const p = url.pathname; let body = {}; if (typeof init.body === 'string') { try { body = JSON.parse(init.body); } catch { return errResp('usage', '请求体不是 JSON'); } } - await sleep(p.endsWith('/screenshot') ? 40 : 80 + Math.random() * 120); + await sleep(p.endsWith('/screenshot') ? 8 : 80 + Math.random() * 120); if (p === '/api/locale') { // the page's language: the mock stays Chinese (messages {}); a PUT is remembered and echoed if (method === 'PUT' && ['auto', 'zh-CN', 'en'].includes(body.preference)) db.localePreference = body.preference; @@ -1256,7 +1256,7 @@ async function handle(url, init) { if (act === 'screenshot') { window.__mockShots[i] = (window.__mockShots[i] || 0) + 1; if (inst.status !== 'online') return errResp('busy', `ModAVD 实例 ${i} 没有开机`); - if (db.shotfail) return errResp('internal', '截图失败:adb exec-out screencap 退出码 1', ''); + if (db.shotfail || !inst.screencap.shm_ready) return errResp('internal', '取不到画面', ''); const blob = await screenshot(inst); return new Response(blob, { status: 200, headers: { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' } }); } diff --git a/internal/ui/web/js/cards.js b/internal/ui/web/js/cards.js index c871ce7b..9d2b9840 100644 --- a/internal/ui/web/js/cards.js +++ b/internal/ui/web/js/cards.js @@ -124,7 +124,7 @@ export function renderGrid() { } function makeCard(i) { - const c = { i, url: null, next: 0, last: 0, fail: 0, shm: false, visible: false }; + const c = { i, url: null, next: 0, last: 0, fail: 0, visible: false }; const view = () => { if (c.inst.status === 'online') openViewer(i); }; const menu = () => openMenu(c.more, menuItems(c)); c.img = h('img', { class: 'shot', alt: '', draggable: 'false' }); @@ -433,25 +433,23 @@ function glesItem(inst, i, held) { } // ---- thumbnails: only while the card view is on screen, the card is in view and no dialog covers the grid (the first -// frame too). A frame is either read from the emulator's shared memory (cheap; the backend says so in X-Shot-Source) -// or comes from `adb exec-out screencap`, which runs a process in the guest. Shared-memory cards refresh about every -// second while the window has focus and every 2.5 s without it (window visible, not minimized); adb cards about every -// 5 s with focus and not at all without (ModAVD/ModAVD#361). Each interval counts from when the last frame arrived. A +// frame too). Visible cards refresh about every second with focus and every 2.5 s without it. +// Each interval counts from when the last frame arrived. A // failing card backs off up to 30 s and a 409 (not booted after all) waits for the next instances event. -const SHOT_EVERY_SHM = 1000; -const SHOT_EVERY_SHM_UNFOCUSED = 2500; -const SHOT_EVERY_ADB = 5000; +const SHOT_EVERY = 1000; +const SHOT_EVERY_UNFOCUSED = 2500; function tick() { if (view !== 'card') return; if (document.visibilityState !== 'visible' || document.querySelector('dialog[open]')) return; const focused = document.hasFocus(); + const live = S.info?.live_screenshots !== false; + if (!live && !focused) return; const now = Date.now(); for (const c of cards.values()) { if (!c.inst || c.inst.status !== 'online' || c.inflight || !c.visible) continue; if (c.hold && c.hold === S.list) continue; - if (!focused && !c.shm) continue; let due = c.next; - if (!focused && !c.fail) due = Math.max(c.next, c.last + SHOT_EVERY_SHM_UNFOCUSED); + if (!focused && !c.fail) due = Math.max(c.next, c.last + SHOT_EVERY_UNFOCUSED); if (now >= due) shoot(c); } } @@ -461,16 +459,15 @@ async function shoot(c) { c.hold = null; let url = null; let ok = false; - let shm = false; try { const res = await fetch(`/api/instances/${c.i}/screenshot`, { credentials: 'same-origin', cache: 'no-store', signal: AbortSignal.timeout(8000) }); if (res.status === 409) { c.hold = S.list; + dropShot(c); ok = true; return; } if (!res.ok) return; - shm = res.headers.get('X-Shot-Source') === 'shm'; url = URL.createObjectURL(await res.blob()); // decode off screen first: the swap never shows a blank frame, and a broken image counts as a failure const im = new Image(); @@ -491,10 +488,10 @@ async function shoot(c) { c.inflight = false; if (ok) { c.fail = 0; - c.shm = shm; c.last = Date.now(); - c.next = c.last + (c.shm ? SHOT_EVERY_SHM : SHOT_EVERY_ADB); + c.next = c.last + (S.info?.live_screenshots === false ? 5000 : SHOT_EVERY); } else { + dropShot(c); c.fail++; c.next = Date.now() + Math.min(30000, 2000 * 2 ** c.fail); } diff --git a/internal/ui/web/js/viewer.js b/internal/ui/web/js/viewer.js index 394fc16e..91d3e076 100644 --- a/internal/ui/web/js/viewer.js +++ b/internal/ui/web/js/viewer.js @@ -1,4 +1,4 @@ -// 画面 viewer (about 2 frames a second, click = tap) and the log viewer. +// 画面 viewer (click = tap) and the log viewer. import { t } from './i18n.js'; import { h, icon, btn, setText, attr } from './dom.js'; @@ -11,8 +11,6 @@ import { displayTap } from './display.js'; import { createBootScreen } from './bootview.js'; import { openComponents } from './panels.js'; -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - export function openViewer(i) { const inst = instance(i); if (!inst) return; @@ -29,11 +27,15 @@ export function openViewer(i) { const frame = h('div', { class: 'viewer-frame off', role: 'group', 'aria-label': t('「{name}」的画面', { name: label(inst) }) }, img, ph, boot.el); const dot = h('span', { class: 'live-dot off' }); const status = h('span'); + const adjustable = S.info?.live_screenshots !== false; + const fps = h('input', { type: 'range', min: '2', max: '30', value: '15', 'aria-label': t('目标帧率') }); + const target = h('span', { text: t('目标 {fps} 帧/秒', { fps: fps.value }) }); const keys = [['back', t('返回')], ['home', t('主页')], ['recents', t('最近任务')]].map(([k, name]) => btn('btn btn-secondary btn-sm', [icon(k), name], () => { if (!frame.classList.contains('off')) A.input(i, { type: 'key', key: k }); })); const ctl = openDialog({ title: t('「{name}」的画面', { name: label(inst) }), sub: t('点按画面即在模拟器上点按 · Esc 关闭'), cls: 'dlg-viewer', light: true, - tools: h('div', { class: 'viewer-tools' }, h('span', { class: 'viewer-status' }, dot, status), h('div', { class: 'navkeys' }, keys)), + tools: h('div', { class: 'viewer-tools' }, h('span', { class: 'viewer-status' }, dot, status), + adjustable && h('label', { class: 'viewer-rate' }, fps, target), h('div', { class: 'navkeys' }, keys)), body: h('div', { class: 'dlg-body' }, frame), }); frame.setAttribute('aria-describedby', ctl.subEl.id); @@ -41,6 +43,9 @@ export function openViewer(i) { let alive = true; let url = null; let state = ''; + let timer, pending, frameID = '', fail = 0; + let sampleStart = performance.now(), frames = 0, actual = 0; + const resetRate = () => { sampleStart = performance.now(); frames = actual = 0; }; // s: live | wait | off | boot | error const setState = (s, text = '', sub = '') => { const blocked = s === 'off' && rootBlocked(); @@ -53,7 +58,10 @@ export function openViewer(i) { frame.classList.toggle('booting', s === 'boot'); img.hidden = !live; dot.classList.toggle('off', !live); - setText(status, live ? t('实时 · 约 2 帧/秒') : s === 'wait' ? t('正在取画面…') : t('没有画面')); + if (!live) { + resetRate(); + setText(status, s === 'wait' ? t('正在取画面…') : t('没有画面')); + } for (const b of keys) attr(b, 'aria-disabled', !live || null); phLead.replaceChildren(s === 'wait' || s === 'boot' ? h('span', { class: 'spin' }) : s === 'error' ? icon('alert') : ''); setText(phMsg, text); @@ -65,47 +73,83 @@ export function openViewer(i) { const OFF = t('实例没有开机'); setState('wait', t('正在取画面…')); - (async () => { - let fail = 0; - while (alive) { - const t0 = performance.now(); - let wait = 500; - const cur = instance(i); - if (!cur) { setState('off', t('这台实例已经不在了')); break; } - if (cur.status === 'starting' || S.pending[i] === 'start') { setState('boot', t('正在开机,开好后这里会显示画面')); boot.update(cur); } - else if (cur.status !== 'online') setState('off', OFF, t('开机后这里会显示实时画面')); - else if (document.visibilityState === 'visible') { - let u = null; - try { - const res = await api.get(`/api/instances/${i}/screenshot`, { raw: true, signal: AbortSignal.timeout(8000) }); - u = URL.createObjectURL(await res.blob()); - const im = new Image(); - im.src = u; - await im.decode(); - fail = 0; - if (alive) { - img.src = u; - if (url) URL.revokeObjectURL(url); - url = u; - u = null; - setState('live'); - } - } catch (e) { - if (e.status === 409) setState('off', OFF, t('开机后这里会显示实时画面')); - else { - fail++; - if (e.name === 'TimeoutError') setState('error', t('取画面超时'), t('模拟器可能卡住了,过一会儿会再试')); - else setState('error', e.message || t('取不到画面'), e.advice); - } - } - if (u) URL.revokeObjectURL(u); - // every frame is an adb screencap: slower while the window is in the background, back off while it fails - if (!document.hasFocus()) wait = 2000; - if (fail) wait = Math.min(10000, 1000 * 2 ** fail); + const schedule = (ms) => { + clearTimeout(timer); + if (alive && !pending && document.visibilityState === 'visible') timer = setTimeout(poll, ms); + }; + async function poll() { + if (!alive || document.visibilityState !== 'visible') return; + const t0 = performance.now(); + const cur = instance(i); + if (!cur) { setState('off', t('这台实例已经不在了')); return; } + if (cur.status === 'starting' || S.pending[i] === 'start') { + frameID = ''; + setState('boot', t('正在开机,开好后这里会显示画面')); + boot.update(cur); + schedule(500); + return; + } + if (cur.status !== 'online') { + frameID = ''; + setState('off', OFF, t('开机后这里会显示实时画面')); + schedule(500); + return; + } + + pending = new AbortController(); + const signal = AbortSignal.any([pending.signal, AbortSignal.timeout(8000)]); + let u; + try { + const query = adjustable ? `?after=${encodeURIComponent(frameID)}` : ''; + const res = await api.get(`/api/instances/${i}/screenshot${query}`, { raw: true, signal }); + if (res.status !== 204) { + u = URL.createObjectURL(await res.blob()); + const im = new Image(); + im.src = u; + await im.decode(); + signal.throwIfAborted(); + img.src = u; + if (url) URL.revokeObjectURL(url); + url = u; + u = null; + frameID = res.headers.get('X-Shot-Frame') || ''; + frames++; + } + signal.throwIfAborted(); + fail = 0; + setState('live'); + const now = performance.now(); + if (now - sampleStart >= 1000) { + actual = Math.round(frames * 1000 / (now - sampleStart)); + sampleStart = now; + frames = 0; + } + setText(status, t('实际 {fps} 帧/秒', { fps: actual })); + } catch (e) { + if (!pending.signal.aborted) { + frameID = ''; + fail++; + if (e.status === 409) setState('off', OFF, t('开机后这里会显示实时画面')); + else if (e.name === 'TimeoutError') setState('error', t('取画面超时'), t('模拟器可能卡住了,过一会儿会再试')); + else setState('error', t('取不到画面'), e.message === t('取不到画面') ? '' : e.message); } - await sleep(Math.max(150, wait - (performance.now() - t0))); + } finally { + if (u) URL.revokeObjectURL(u); + let wait = adjustable ? 1000 / Number(fps.value) : document.hasFocus() ? 500 : 2000; + if (fail) wait = Math.min(10000, 500 * 2 ** fail); + if (pending.signal.aborted) wait = 0; + pending = null; + schedule(Math.max(0, wait - (performance.now() - t0))); } - })(); + } + const onVisibility = () => { + resetRate(); + if (document.visibilityState !== 'visible') pending?.abort(); + schedule(0); + }; + document.addEventListener('visibilitychange', onVisibility); + fps.addEventListener('input', () => setText(target, t('目标 {fps} 帧/秒', { fps: fps.value }))); + schedule(0); frame.addEventListener('click', (e) => { if (frame.classList.contains('off')) return; @@ -127,7 +171,14 @@ export function openViewer(i) { attr(frame, 'aria-label', t('「{name}」的画面', { name: label(cur) })); attr(img, 'alt', t('{name} 的当前画面', { name: label(cur) })); }); - ctl.onClose.push(() => { alive = false; un(); if (url) URL.revokeObjectURL(url); }); + ctl.onClose.push(() => { + alive = false; + clearTimeout(timer); + pending?.abort(); + document.removeEventListener('visibilitychange', onVisibility); + un(); + if (url) URL.revokeObjectURL(url); + }); } // ---- logs From fc43aed44d8e98c541f57619b3a426f70dcec0f8 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 5 Dec 2026 19:52:02 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=E7=94=BB=E9=9D=A2=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E6=8C=89=E5=9B=BA=E5=AE=9A=E8=8A=82=E6=8B=8D=E5=8F=96=E5=B8=A7?= =?UTF-8?q?=EF=BC=8C=E7=9B=AE=E6=A0=87=2015=20=E5=B8=A7=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=8E=89=E5=88=B0=2013=20=E5=B8=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来每帧做完再等「间隔减已用时间」。Windows 上 Chromium 把 32 ms 以上的定时器向上取整到 15.6 ms 一格,目标 15 时 55–64 ms 的等待都变成 78 ms,实际只有约 13 帧(上机 720p、1080p 都是)。改成从上一次的预定时刻往后排,定时器晚到的那点下一帧补回来;一帧超时就从现在重新起算,不连发追帧;出错、中止、未开机时清零。 无头 Edge 同样 6 ms 工作量:旧 13.0 / 29.8 帧,新 15.0 / 30.0 帧。 Refs ModAVD/ModAVD#427 --- internal/ui/web/js/viewer.js | 23 ++++++++++++++++++----- scripts/test_topbar_ui.mjs | 16 ++++++++++++---- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/internal/ui/web/js/viewer.js b/internal/ui/web/js/viewer.js index 443dd32b..de1758c5 100644 --- a/internal/ui/web/js/viewer.js +++ b/internal/ui/web/js/viewer.js @@ -45,7 +45,9 @@ export function openViewer(i) { let alive = true; let url = null; let state = ''; - let timer, pending, frameID = '', fail = 0; + // due: when the current live poll was meant to start. Pacing from it rather than from when the + // frame finished keeps the target rate even when the OS rounds each timer up to its tick. + let timer, pending, frameID = '', fail = 0, due = 0; // s: live | wait | off | boot | error const setState = (s, text = '', sub = '') => { const blocked = s === 'off' && rootBlocked(); @@ -79,6 +81,7 @@ export function openViewer(i) { if (!cur) { setState('off', t('这台实例已经不在了')); return; } if (cur.status === 'starting' || S.pending[i] === 'start') { frameID = ''; + due = 0; setState('boot', t('正在开机,开好后这里会显示画面')); boot.update(cur); schedule(500); @@ -86,6 +89,7 @@ export function openViewer(i) { } if (cur.status !== 'online') { frameID = ''; + due = 0; setState('off', OFF, t('开机后这里会显示实时画面')); schedule(500); return; @@ -131,11 +135,20 @@ export function openViewer(i) { } } finally { if (u) URL.revokeObjectURL(u); - let wait = liveFrames ? 1000 / Number(fps.value) : document.hasFocus() ? 500 : 2000; - if (fail) wait = Math.min(10000, 500 * 2 ** fail); - if (pending.signal.aborted) wait = 0; + const now = performance.now(); + let wait; + if (pending.signal.aborted || fail) { + due = 0; + wait = pending.signal.aborted ? 0 : Math.min(10000, 500 * 2 ** fail) - (now - t0); + } else if (liveFrames) { + // A frame that ran past its slot starts the next one now instead of bursting to catch up. + due = Math.max((due || t0) + 1000 / Number(fps.value), now); + wait = due - now; + } else { + wait = (document.hasFocus() ? 500 : 2000) - (now - t0); + } pending = null; - schedule(Math.max(0, wait - (performance.now() - t0))); + schedule(Math.max(0, wait)); } } const onVisibility = () => { diff --git a/scripts/test_topbar_ui.mjs b/scripts/test_topbar_ui.mjs index bc50db52..e663975a 100644 --- a/scripts/test_topbar_ui.mjs +++ b/scripts/test_topbar_ui.mjs @@ -775,7 +775,7 @@ test('the live viewer draws raw pixels, skips 204s, pauses when hidden and cance const requests = []; const callbacks = []; const draws = []; - let nextTimer = 0, dialog; + let nextTimer = 0, dialog, clock = 0; const visible = { index: 3, status: 'online', title: 'Test' }; const { mod } = await load('viewer.js', { 'api.js': { api: { get: (path, { signal }) => new Promise((resolve, reject) => { @@ -785,6 +785,7 @@ test('the live viewer draws raw pixels, skips 204s, pauses when hidden and cance 'i18n.js': { t: text => text }, 'dom.js': { ...dom, h(tag, props, ...kids) { const el = h(tag, props, ...kids); + if (tag === 'input') el.value = props.value; // the target-fps slider, as a browser reflects it if (tag === 'canvas') el.getContext = () => ({ putImageData: image => draws.push(['pixels', [...image.data]]), setTransform: (...args) => draws.push(['transform', ...args]), @@ -802,17 +803,18 @@ test('the live viewer draws raw pixels, skips 204s, pauses when hidden and cance 'bootview.js': { createBootScreen: () => ({ el: h('div'), update: noop }) }, 'panels.js': { openComponents: noop }, }, { - document, AbortController, AbortSignal, performance: { now: () => 0 }, - setTimeout: fn => { timers.set(++nextTimer, fn); return nextTimer; }, + document, AbortController, AbortSignal, performance: { now: () => clock }, + setTimeout: (fn, ms) => { timers.set(++nextTimer, { fn, ms }); return nextTimer; }, clearTimeout: id => timers.delete(id), ImageData: class { constructor(data) { this.data = data; } }, }); const tick = () => { assert.equal(timers.size, 1); - const [id, fn] = [...timers][0]; + const [id, { fn }] = [...timers][0]; timers.delete(id); return fn(); }; + const nextDelay = () => [...timers.values()][0].ms; mod.openViewer(3); let polling = tick(); assert.match(requests[0].path, /\?format=rgba&after=$/); @@ -821,14 +823,20 @@ test('the live viewer draws raw pixels, skips 204s, pauses when hidden and cance arrayBuffer: async () => Uint8Array.of(1, 2, 3, 0, 4, 5, 6, 0, 9, 9, 9, 9).buffer, headers: new Headers({ 'X-Shot-Frame': 'frame-1', 'X-Shot-Width': '2', 'X-Shot-Height': '1', 'X-Shot-Stride': '12', 'X-Shot-Rotation': '90' }) }); + clock = 10; await polling; + // Default 15 fps: the next poll is due 66.7 ms after this one started, not after it finished. + assert.ok(Math.abs(nextDelay() - (1000 / 15 - 10)) < 1e-9); const canvas = all(dialog.body).find(el => el.tagName === 'CANVAS'); assert.deepEqual([canvas.width, canvas.height], [1, 2]); assert.deepEqual(draws, [['pixels', [1, 2, 3, 255, 4, 5, 6, 255]], ['transform', 0, -1, 1, 0, 0, 2], ['draw']]); + clock = 78; // the timer fired late, as Windows rounds longer timers up to its 15.6 ms tick polling = tick(); assert.match(requests.at(-1).path, /\?format=rgba&after=frame-1$/); + clock = 80; requests.at(-1).resolve({ status: 204 }); await polling; + assert.ok(Math.abs(nextDelay() - (2000 / 15 - 80)) < 1e-9, 'a late timer must not push back the next frame'); assert.equal(draws.length, 3, '204 must keep the canvas as it was'); assert.equal(all(dialog.tools).some(el => el.classList.contains('viewer-status')), false);