@capyclaw/rsp-suite 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -2
- package/cordis.patch.yml +8 -0
- package/dsh-suite.json +91 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +72 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/README.md +7 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/contract/rsp-contract.json +478 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/package.json +33 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/plugin.mjs +15 -0
- package/node_modules/@capyclaw/rsp-skill-remote-screen/skills/remote-screen/SKILL.md +131 -0
- package/node_modules/@capyclaw/rsp-workbench/contract/capabilities.json +203 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/client.mjs +681 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/descriptors.mjs +28 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/host.mjs +51 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/manager.mjs +333 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/session-mode.mjs +68 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/tools.mjs +485 -0
- package/node_modules/@capyclaw/rsp-workbench/lib/workbench.mjs +184 -0
- package/node_modules/@capyclaw/rsp-workbench/package.json +47 -0
- package/node_modules/@capyclaw/rsp-workbench/plugin.mjs +17 -0
- package/node_modules/@capyclaw/rsp-workbench/ui/index.html +578 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +597 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/suite-kit/README.md +289 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +58 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +539 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +751 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1440 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +53 -4
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSP/1 控制端客户端(Remote Screen Protocol,第 1 版)。
|
|
3
|
+
*
|
|
4
|
+
* 严格实现 RSP/1 规范的控制端侧:
|
|
5
|
+
* - 画面通道:/screen.ws(TEXT hello + BINARY JPEG 帧),常驻 + 退避 1s→5s 重连;
|
|
6
|
+
* 另提供 /screen MJPEG 上游打开方法供查看器代理。
|
|
7
|
+
* - 操控通道:/control.ws(seq/ack,顺序注入)优先,POST /control 降级。
|
|
8
|
+
* - 鉴权:?token= 查询参数;401 / 关闭码 4001 → auth-error。
|
|
9
|
+
* - 坐标:上线一律逻辑点(hello width/height);帧像素→逻辑点换算在工具层做。
|
|
10
|
+
*
|
|
11
|
+
* 无 cordis 依赖,纯 Node(fetch + ws),可单测。
|
|
12
|
+
*/
|
|
13
|
+
import { EventEmitter } from 'node:events'
|
|
14
|
+
import WebSocket from 'ws'
|
|
15
|
+
|
|
16
|
+
export const PROTOCOL = 'rsp/1'
|
|
17
|
+
export const MAX_TEXT_UNITS = 4096 // §5.3 text 上限(UTF-16 码元)
|
|
18
|
+
export const MAX_EVENT_BYTES = 64 * 1024 // §5.4 单事件上限
|
|
19
|
+
const ACK_TIMEOUT_MS = 5000
|
|
20
|
+
const MOVE_MIN_GAP_MS = 16 // §5.1 合并 move ≤ 60/s
|
|
21
|
+
const RECONNECT_MIN_MS = 1000 // §8 退避 1s→5s
|
|
22
|
+
const RECONNECT_MAX_MS = 5000
|
|
23
|
+
const KEY_CODES = new Set([
|
|
24
|
+
...Array.from({ length: 26 }, (_, i) => 'Key' + String.fromCharCode(65 + i)),
|
|
25
|
+
...Array.from({ length: 10 }, (_, i) => 'Digit' + i),
|
|
26
|
+
'Minus', 'Equal', 'BracketLeft', 'BracketRight', 'Backslash', 'Semicolon', 'Quote', 'Comma', 'Period', 'Slash', 'Backquote',
|
|
27
|
+
'Enter', 'Tab', 'Space', 'Backspace', 'Escape', 'CapsLock', 'Delete', 'Insert', 'Home', 'End', 'PageUp', 'PageDown',
|
|
28
|
+
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'MetaLeft', 'MetaRight',
|
|
29
|
+
...Array.from({ length: 20 }, (_, i) => 'F' + (i + 1)), ...Array.from({ length: 10 }, (_, i) => 'Numpad' + i),
|
|
30
|
+
'NumpadDivide', 'NumpadMultiply', 'NumpadSubtract', 'NumpadAdd', 'NumpadEnter', 'NumpadDecimal',
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
// S4: 自动降档阶梯(低→高)。运行时调参只动 h264 通道三参;被控端按 features.quality 门控。
|
|
34
|
+
export const QUALITY_LADDER = [
|
|
35
|
+
{ bitrateKbps: 500, h264Fps: 15, h264MaxWidth: 960 }, // low
|
|
36
|
+
{ bitrateKbps: 1000, h264Fps: 30, h264MaxWidth: 1280 }, // smooth
|
|
37
|
+
{ bitrateKbps: 2000, h264Fps: 30, h264MaxWidth: 1920 }, // balanced
|
|
38
|
+
{ bitrateKbps: 4000, h264Fps: 60, h264MaxWidth: 1920 }, // hd
|
|
39
|
+
{ bitrateKbps: 8000, h264Fps: 60, h264MaxWidth: 3840 }, // uhd
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
/** 从 JPEG 字节解析像素尺寸(扫 SOF 段),无需图像库。返回 {width,height} 或 null。 */
|
|
43
|
+
export function jpegSize(buf) {
|
|
44
|
+
if (!buf || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null
|
|
45
|
+
let i = 2
|
|
46
|
+
while (i + 9 < buf.length) {
|
|
47
|
+
if (buf[i] !== 0xff) { i++; continue }
|
|
48
|
+
// 跳过填充 FF
|
|
49
|
+
while (i < buf.length && buf[i] === 0xff) i++
|
|
50
|
+
const marker = buf[i++]
|
|
51
|
+
if (marker === 0xd9 || marker === 0xda) break // EOI / SOS:尺寸必在 SOS 之前
|
|
52
|
+
if (marker === 0x00 || (marker >= 0xd0 && marker <= 0xd7)) continue // stuffed / RST
|
|
53
|
+
if (i + 2 > buf.length) break
|
|
54
|
+
const len = buf.readUInt16BE(i)
|
|
55
|
+
// SOF0..SOF15(除 C4/DHT、C8/JPG、CC/DAC)携带尺寸
|
|
56
|
+
const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
|
|
57
|
+
if (isSof) {
|
|
58
|
+
if (i + 7 > buf.length) break
|
|
59
|
+
const height = buf.readUInt16BE(i + 3)
|
|
60
|
+
const width = buf.readUInt16BE(i + 5)
|
|
61
|
+
return { width, height }
|
|
62
|
+
}
|
|
63
|
+
i += len
|
|
64
|
+
}
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 把长文本按 UTF-16 码元 ≤4096 分片(不切断代理对)。 */
|
|
69
|
+
export function splitText(text, limit = MAX_TEXT_UNITS) {
|
|
70
|
+
const out = []
|
|
71
|
+
let s = String(text)
|
|
72
|
+
while (s.length > limit) {
|
|
73
|
+
let cut = limit
|
|
74
|
+
// 避免在高位代理处切断
|
|
75
|
+
const code = s.charCodeAt(cut - 1)
|
|
76
|
+
if (code >= 0xd800 && code <= 0xdbff) cut -= 1
|
|
77
|
+
out.push(s.slice(0, cut))
|
|
78
|
+
s = s.slice(cut)
|
|
79
|
+
}
|
|
80
|
+
if (s.length) out.push(s)
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function maskToken(token) {
|
|
85
|
+
if (!token) return null
|
|
86
|
+
const s = String(token)
|
|
87
|
+
if (s.length <= 8) return '****'
|
|
88
|
+
return s.slice(0, 4) + '…' + s.slice(-4)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function normalizeBase({ url, host, port }) {
|
|
92
|
+
if (url) {
|
|
93
|
+
const u = new URL(url)
|
|
94
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw badArg('url 必须是 http/https')
|
|
95
|
+
return (u.origin + u.pathname).replace(/\/+$/, '')
|
|
96
|
+
}
|
|
97
|
+
if (!host) throw badArg('需要 url 或 host')
|
|
98
|
+
const p = port ?? 8765
|
|
99
|
+
const h = String(host).replace(/^https?:\/\//, '').replace(/\/+$/, '')
|
|
100
|
+
return `http://${h.includes(':') ? `[${h}]` : h}:${p}`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function badArg(message) { const e = new Error(message); e.code = 'bad_event'; return e }
|
|
104
|
+
|
|
105
|
+
export class RspClient extends EventEmitter {
|
|
106
|
+
/**
|
|
107
|
+
* @param {object} o
|
|
108
|
+
* @param {string} o.baseUrl http://host:port
|
|
109
|
+
* @param {string} o.token bearer 令牌
|
|
110
|
+
* @param {Function} [o.fetchImpl]
|
|
111
|
+
* @param {Function} [o.WebSocketImpl]
|
|
112
|
+
* @param {Function} [o.logger]
|
|
113
|
+
*/
|
|
114
|
+
constructor({ baseUrl, token, fetchImpl, WebSocketImpl, logger } = {}) {
|
|
115
|
+
super()
|
|
116
|
+
if (!baseUrl) throw badArg('baseUrl 必填')
|
|
117
|
+
if (!token) throw badArg('token 必填')
|
|
118
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '')
|
|
119
|
+
this.token = String(token)
|
|
120
|
+
this.fetch = fetchImpl || globalThis.fetch
|
|
121
|
+
this.WS = WebSocketImpl || WebSocket
|
|
122
|
+
this.log = logger || (() => {})
|
|
123
|
+
this.closed = false
|
|
124
|
+
this.info = null
|
|
125
|
+
this.hello = null
|
|
126
|
+
this.lastFrame = null // {width,height,bytes,at}
|
|
127
|
+
this.frameCount = 0
|
|
128
|
+
this.screenWs = null
|
|
129
|
+
this.controlWs = null
|
|
130
|
+
this.screenState = 'idle' // idle|connecting|open|reconnecting|closed|auth-error
|
|
131
|
+
this.controlState = 'idle'
|
|
132
|
+
this.controlMode = 'ws' // ws|post
|
|
133
|
+
this._seq = 0
|
|
134
|
+
this._pending = new Map() // seq -> {seq,resolve,reject,timer}(流水线多事件在途)
|
|
135
|
+
this._pressedKeys = new Set()
|
|
136
|
+
this._pressedButtons = new Set()
|
|
137
|
+
this._lastMoveAt = 0
|
|
138
|
+
// S4: 操控 ack 往返时延(EMA α=0.2),供 status() 与自动降档用。
|
|
139
|
+
this._rttEma = 0
|
|
140
|
+
this._rttLast = 0
|
|
141
|
+
this._rttSamples = 0
|
|
142
|
+
this._aq = null // 自动降档状态(enableAutoQuality 开启)
|
|
143
|
+
this._screenRetry = 0
|
|
144
|
+
this._screenTimer = null
|
|
145
|
+
this._authFailed = false
|
|
146
|
+
this.lastError = null
|
|
147
|
+
// 实时 H.264 增量通道(RSP/1 §7.3/§7.6,可选;被控端不提供时自动回退 JPEG)
|
|
148
|
+
this.h264Ws = null
|
|
149
|
+
this.h264State = 'idle' // idle|connecting|open|closed|unsupported
|
|
150
|
+
this.h264Hello = null
|
|
151
|
+
this.h264Head = [] // 最近 SPS/PPS/IDR,供新观众立即起播
|
|
152
|
+
this.h264Bytes = 0 // h264 通道累计接收字节(诊断用)
|
|
153
|
+
this.h264Nals = 0 // h264 通道累计 NAL 数(诊断用)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
get wsBase() { return this.baseUrl.replace(/^http/, 'ws') }
|
|
157
|
+
_url(path) { return `${this.baseUrl}${path}?token=${encodeURIComponent(this.token)}` }
|
|
158
|
+
_wsUrl(path) { return `${this.wsBase}${path}?token=${encodeURIComponent(this.token)}` }
|
|
159
|
+
|
|
160
|
+
/** 连接:拉 /info 校验协议,开 screen.ws(常驻)与 control.ws。返回 info。 */
|
|
161
|
+
async connect() {
|
|
162
|
+
if (this.closed) throw badArg('client 已关闭')
|
|
163
|
+
this._authFailed = false
|
|
164
|
+
const info = await this.fetchInfo()
|
|
165
|
+
this.info = info
|
|
166
|
+
if (info.protocol !== PROTOCOL) {
|
|
167
|
+
const e = new Error(`被控端协议为 ${info.protocol},本控制端仅支持 ${PROTOCOL}`)
|
|
168
|
+
e.code = 'protocol_mismatch'; throw e
|
|
169
|
+
}
|
|
170
|
+
const fmt = info.screen?.format
|
|
171
|
+
if (fmt && fmt !== 'jpeg') {
|
|
172
|
+
const e = new Error(`不支持的画面格式 ${fmt}(v1 仅 jpeg)`); e.code = 'unsupported_format'; throw e
|
|
173
|
+
}
|
|
174
|
+
this._openScreen()
|
|
175
|
+
this._openH264() // 尽力建立实时通道;失败/不支持则回退 JPEG,不致命
|
|
176
|
+
await this._openControl().catch((err) => {
|
|
177
|
+
// 操控 WS 建不起来不致命:降级 POST(sendEvent 时再试)
|
|
178
|
+
this.log('control.ws 建立失败,降级 POST:' + err.message)
|
|
179
|
+
this.controlMode = 'post'
|
|
180
|
+
this.controlState = 'post'
|
|
181
|
+
})
|
|
182
|
+
return info
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 实时 H.264 增量通道:WS /screen.h264.ws。被控端未实现时握手 404/失败→unsupported,回退 JPEG。 */
|
|
186
|
+
_openH264() {
|
|
187
|
+
if (this.closed || this._authFailed) return
|
|
188
|
+
this.h264State = 'connecting'
|
|
189
|
+
let ws
|
|
190
|
+
try { ws = new this.WS(this._wsUrl('/screen.h264.ws')) } catch { this.h264State = 'unsupported'; return }
|
|
191
|
+
ws.binaryType = 'nodebuffer'
|
|
192
|
+
this.h264Ws = ws
|
|
193
|
+
ws.on('open', () => { this.h264State = 'open'; this.emit('h264-state', this.h264State) })
|
|
194
|
+
ws.on('message', (data, isBinary) => {
|
|
195
|
+
if (!isBinary) {
|
|
196
|
+
try {
|
|
197
|
+
const msg = JSON.parse(data.toString())
|
|
198
|
+
if (msg.kind === 'hello' && msg.format === 'h264') { this.h264Hello = msg; this.emit('h264-hello', msg) }
|
|
199
|
+
} catch { /* ignore */ }
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
const t = h264NalType(data)
|
|
203
|
+
this.h264Bytes += data.length
|
|
204
|
+
this.h264Nals++
|
|
205
|
+
if (t === 7 || t === 8 || t === 5) {
|
|
206
|
+
// 累积 SPS/PPS/IDR 各一,按 SPS,PPS,IDR 规范顺序,供新观众立即起播
|
|
207
|
+
const rank = { 7: 0, 8: 1, 5: 2 }
|
|
208
|
+
this.h264Head = [...this.h264Head.filter((b) => h264NalType(b) !== t), data]
|
|
209
|
+
.sort((a, b) => rank[h264NalType(a)] - rank[h264NalType(b)])
|
|
210
|
+
}
|
|
211
|
+
this.emit('h264', data)
|
|
212
|
+
})
|
|
213
|
+
ws.on('close', (code) => {
|
|
214
|
+
this.h264Ws = null
|
|
215
|
+
this.h264State = (code === 4001) ? 'closed' : (this.h264State === 'open' ? 'closed' : 'unsupported')
|
|
216
|
+
this.emit('h264-state', this.h264State)
|
|
217
|
+
})
|
|
218
|
+
ws.on('error', () => { /* close 会跟进 */ })
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async fetchInfo() {
|
|
222
|
+
const res = await this.fetch(this._url('/info'), { headers: { accept: 'application/json' } })
|
|
223
|
+
if (res.status === 401) { const e = new Error('令牌缺失或错误(401)'); e.code = 'unauthorized'; throw e }
|
|
224
|
+
if (!res.ok) { const e = new Error(`/info 返回 ${res.status}`); e.code = 'engine_unavailable'; throw e }
|
|
225
|
+
return res.json()
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ---- 画面通道 ----
|
|
229
|
+
_openScreen() {
|
|
230
|
+
if (this.closed || this._authFailed) return
|
|
231
|
+
this.screenState = 'connecting'
|
|
232
|
+
const ws = new this.WS(this._wsUrl('/screen.ws'))
|
|
233
|
+
ws.binaryType = 'nodebuffer'
|
|
234
|
+
this.screenWs = ws
|
|
235
|
+
ws.on('open', () => { this.screenState = 'open'; this._screenRetry = 0; this.emit('screen-state', this.screenState) })
|
|
236
|
+
ws.on('message', (data, isBinary) => {
|
|
237
|
+
if (!isBinary) {
|
|
238
|
+
try {
|
|
239
|
+
const msg = JSON.parse(data.toString())
|
|
240
|
+
if (msg.kind === 'hello') {
|
|
241
|
+
this.hello = { width: msg.width, height: msg.height, fps: msg.fps, format: msg.format, protocol: msg.protocol }
|
|
242
|
+
if (msg.format && msg.format !== 'jpeg') {
|
|
243
|
+
this.lastError = { code: 'unsupported_format', message: `hello.format=${msg.format}` }
|
|
244
|
+
this.emit('error', this.lastError)
|
|
245
|
+
}
|
|
246
|
+
this.emit('hello', this.hello)
|
|
247
|
+
}
|
|
248
|
+
// 未知 kind 忽略(§7)
|
|
249
|
+
} catch (e) { this.log('screen TEXT 解析失败:' + e.message) }
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data)
|
|
253
|
+
const size = jpegSize(buf) || { width: this.hello?.width ?? 0, height: this.hello?.height ?? 0 }
|
|
254
|
+
this.lastFrame = { width: size.width, height: size.height, bytes: buf, at: Date.now() }
|
|
255
|
+
this.frameCount++
|
|
256
|
+
this.emit('frame', this.lastFrame)
|
|
257
|
+
})
|
|
258
|
+
ws.on('close', (code) => {
|
|
259
|
+
this.screenWs = null
|
|
260
|
+
if (this.closed) { this.screenState = 'closed'; this.emit('screen-state', this.screenState); return }
|
|
261
|
+
if (code === 4001) { this._authFailed = true; this.screenState = 'auth-error'; this.emit('auth-error', { channel: 'screen' }); this.emit('screen-state', this.screenState); return }
|
|
262
|
+
this.screenState = 'reconnecting'
|
|
263
|
+
this.emit('screen-state', this.screenState)
|
|
264
|
+
this._scheduleScreenReconnect()
|
|
265
|
+
})
|
|
266
|
+
ws.on('error', (err) => { this.log('screen.ws error: ' + err.message); this.lastError = { code: 'ws_error', message: err.message } })
|
|
267
|
+
// ws 自动回 Pong(§4.1.6)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
_scheduleScreenReconnect() {
|
|
271
|
+
if (this.closed || this._authFailed) return
|
|
272
|
+
const delay = Math.min(RECONNECT_MAX_MS, RECONNECT_MIN_MS * Math.pow(2, this._screenRetry))
|
|
273
|
+
this._screenRetry++
|
|
274
|
+
this._screenTimer = setTimeout(() => { this._screenTimer = null; this._openScreen() }, delay)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 打开上游 MJPEG 流(供查看器代理)。返回 {res, abort};调用方负责 pipe 与清理。 */
|
|
278
|
+
async openMjpeg() {
|
|
279
|
+
const ac = new AbortController()
|
|
280
|
+
const res = await this.fetch(this._url('/screen'), { signal: ac.signal, headers: { accept: 'multipart/x-mixed-replace' } })
|
|
281
|
+
if (res.status === 401) { const e = new Error('令牌缺失或错误(401)'); e.code = 'unauthorized'; throw e }
|
|
282
|
+
if (res.status === 503) { const e = new Error('引擎未就绪(503)'); e.code = 'engine_unavailable'; throw e }
|
|
283
|
+
if (!res.ok) { const e = new Error(`/screen 返回 ${res.status}`); e.code = 'engine_unavailable'; throw e }
|
|
284
|
+
return { res, abort: () => ac.abort() }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---- 操控通道 ----
|
|
288
|
+
_openControl() {
|
|
289
|
+
if (this.closed) return Promise.reject(badArg('client 已关闭'))
|
|
290
|
+
if (this.info && this.info.control && this.info.control.enabled === false) {
|
|
291
|
+
const e = new Error('操控通道被禁用(control.enabled=false)'); e.code = 'forbidden'; return Promise.reject(e)
|
|
292
|
+
}
|
|
293
|
+
return new Promise((resolve, reject) => {
|
|
294
|
+
this.controlState = 'connecting'
|
|
295
|
+
const ws = new this.WS(this._wsUrl('/control.ws'))
|
|
296
|
+
this.controlWs = ws
|
|
297
|
+
let settled = false
|
|
298
|
+
const fail = (err) => { if (settled) return; settled = true; this.controlWs = null; this.controlState = 'idle'; reject(err) }
|
|
299
|
+
ws.on('open', () => {
|
|
300
|
+
if (settled) return; settled = true
|
|
301
|
+
this.controlMode = 'ws'; this.controlState = 'open'
|
|
302
|
+
this.emit('control-state', this.controlState)
|
|
303
|
+
resolve()
|
|
304
|
+
})
|
|
305
|
+
ws.on('message', (data, isBinary) => {
|
|
306
|
+
if (isBinary) return
|
|
307
|
+
let msg; try { msg = JSON.parse(data.toString()) } catch { return }
|
|
308
|
+
if (msg.kind === 'ack') {
|
|
309
|
+
const p = this._pending.get(msg.seq)
|
|
310
|
+
if (p) {
|
|
311
|
+
this._pending.delete(msg.seq); clearTimeout(p.timer)
|
|
312
|
+
const rttMs = p.t0 != null ? performance.now() - p.t0 : null
|
|
313
|
+
if (rttMs != null) this._recordRtt(rttMs)
|
|
314
|
+
// 透传 quality 快照(cmd:'quality' 的 ack 携带),供 rsp_quality 回显。
|
|
315
|
+
p.resolve({ ok: true, seq: msg.seq, quality: msg.quality, batch: msg.batch, wake: msg.wake, rttMs })
|
|
316
|
+
}
|
|
317
|
+
} else if (msg.kind === 'error') {
|
|
318
|
+
const err = new Error(msg.message || 'bad_event'); err.code = msg.code || 'bad_event'; if (msg.batch) err.batch = msg.batch
|
|
319
|
+
// Error frames carry no seq: reject the oldest in-flight event (FIFO), which
|
|
320
|
+
// is the one the agent rejected (it processes messages in arrival order).
|
|
321
|
+
const oldest = this._pending.keys().next().value
|
|
322
|
+
if (oldest != null) { const p = this._pending.get(oldest); this._pending.delete(oldest); clearTimeout(p.timer); p.reject(err) }
|
|
323
|
+
else this.emit('error', { code: err.code, message: err.message })
|
|
324
|
+
}
|
|
325
|
+
})
|
|
326
|
+
ws.on('close', (code) => {
|
|
327
|
+
this.controlWs = null
|
|
328
|
+
// §5.5 被控端按连接自动补 up;本地状态同步清空
|
|
329
|
+
this._pressedKeys.clear(); this._pressedButtons.clear()
|
|
330
|
+
if (this._pending.size) { for (const [, p] of this._pending) { clearTimeout(p.timer); p.reject(new Error(`control.ws 关闭(${code})`)) } this._pending.clear() }
|
|
331
|
+
if (this.closed) { this.controlState = 'closed'; return }
|
|
332
|
+
if (code === 4001) { this._authFailed = true; this.controlState = 'auth-error'; this.emit('auth-error', { channel: 'control' }); return }
|
|
333
|
+
if (code === 4003) { this.controlMode = 'post'; this.controlState = 'disabled'; return }
|
|
334
|
+
this.controlState = 'idle' // 懒重连:下次 sendEvent 再建
|
|
335
|
+
this.emit('control-state', this.controlState)
|
|
336
|
+
})
|
|
337
|
+
ws.on('error', (err) => { this.log('control.ws error: ' + err.message); fail(err) })
|
|
338
|
+
// 握手被拒(4003/503/401)时 ws 触发 error+close
|
|
339
|
+
setTimeout(() => { if (!settled) fail(new Error('control.ws 握手超时')) }, ACK_TIMEOUT_MS).unref?.()
|
|
340
|
+
})
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async _ensureControl() {
|
|
344
|
+
if (this.controlMode === 'post') return 'post'
|
|
345
|
+
if (this.controlWs && this.controlWs.readyState === 1) return 'ws'
|
|
346
|
+
try { await this._openControl(); return 'ws' }
|
|
347
|
+
catch (err) {
|
|
348
|
+
if (err.code === 'forbidden') throw err
|
|
349
|
+
this.controlMode = 'post'; this.controlState = 'post'
|
|
350
|
+
return 'post'
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async sendBatch(events, options = {}) {
|
|
355
|
+
if (!Array.isArray(events) || events.length < 1 || events.length > 64) throw badArg('batch events must contain 1..64 events')
|
|
356
|
+
const moveIntervalMs = options.moveIntervalMs ?? 0
|
|
357
|
+
if (!Number.isInteger(moveIntervalMs) || moveIntervalMs < 0 || moveIntervalMs > 100) throw badArg('batch moveIntervalMs must be an integer in [0,100]')
|
|
358
|
+
const normalizeOne = (ev) => {
|
|
359
|
+
if (ev?.cmd === 'key' && Array.isArray(ev.modifiers) && ev.modifiers.length) {
|
|
360
|
+
const map = { cmd: 'MetaLeft', ctrl: 'ControlLeft', alt: 'AltLeft', shift: 'ShiftLeft' }
|
|
361
|
+
const mods = ev.modifiers.map((m) => map[m]).filter(Boolean)
|
|
362
|
+
if (!mods.length) return [ev]
|
|
363
|
+
return ev.action === 'down'
|
|
364
|
+
? [...mods.map((code) => ({ cmd: 'key', action: 'down', code })), { cmd: 'key', action: 'down', code: ev.code }]
|
|
365
|
+
: [{ cmd: 'key', action: 'up', code: ev.code }, ...[...mods].reverse().map((code) => ({ cmd: 'key', action: 'up', code }))]
|
|
366
|
+
}
|
|
367
|
+
return [ev]
|
|
368
|
+
}
|
|
369
|
+
const normalized = events.map(normalizeOne).flat()
|
|
370
|
+
const pressed = new Set(this._pressedKeys)
|
|
371
|
+
const buttons = new Set(this._pressedButtons)
|
|
372
|
+
for (const ev of normalized) {
|
|
373
|
+
if (!ev || !['key', 'mouse', 'text'].includes(ev.cmd)) throw badArg('unsupported batch event')
|
|
374
|
+
if (ev.cmd === 'text' && (typeof ev.text !== 'string' || ev.text.length > MAX_TEXT_UNITS)) throw badArg('text too long')
|
|
375
|
+
if (ev.cmd === 'key') {
|
|
376
|
+
if (!['down', 'up'].includes(ev.action) || !KEY_CODES.has(ev.code)) throw badArg('bad key event')
|
|
377
|
+
if (ev.action === 'down') pressed.add(ev.code); else pressed.delete(ev.code)
|
|
378
|
+
}
|
|
379
|
+
if (ev.cmd === 'mouse') {
|
|
380
|
+
if (!['move', 'down', 'up', 'click', 'scroll'].includes(ev.action) || (ev.action !== 'scroll' && (!Number.isFinite(ev.x) || !Number.isFinite(ev.y)))) throw badArg('bad mouse event')
|
|
381
|
+
const b = ev.button || 'left'
|
|
382
|
+
if (ev.action === 'down') buttons.add(b); else if (ev.action === 'up' || ev.action === 'click') buttons.delete(b)
|
|
383
|
+
}
|
|
384
|
+
const bytes = Buffer.byteLength(JSON.stringify(ev), 'utf8')
|
|
385
|
+
if (bytes > MAX_EVENT_BYTES) throw badArg('事件超过 64KiB')
|
|
386
|
+
}
|
|
387
|
+
if (Buffer.byteLength(JSON.stringify({ events: normalized }), 'utf8') > 60000) throw badArg('batch payload exceeds 60KiB')
|
|
388
|
+
if (this.closed || this._authFailed) throw badArg('client unavailable')
|
|
389
|
+
// Preserve held-input tracking across a failed batch ack; the batch may have
|
|
390
|
+
// reached the agent even if its response was lost.
|
|
391
|
+
this._pressedKeys = pressed
|
|
392
|
+
this._pressedButtons = buttons
|
|
393
|
+
try {
|
|
394
|
+
let result
|
|
395
|
+
try {
|
|
396
|
+
result = await this.sendEvent({ cmd: 'batch', events: normalized, ...(moveIntervalMs ? { moveIntervalMs } : {}) })
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (err.batch?.processed != null && err.batch.processed !== normalized.length) {
|
|
399
|
+
err.code = 'partial_batch'
|
|
400
|
+
err.message = `helper processed ${err.batch.processed}/${normalized.length} batch events${err.message ? `: ${err.message}` : ''}`
|
|
401
|
+
}
|
|
402
|
+
throw err
|
|
403
|
+
}
|
|
404
|
+
if (result.batch?.processed != null && result.batch.processed !== normalized.length) {
|
|
405
|
+
const e = new Error(`helper processed ${result.batch.processed}/${normalized.length} batch events`)
|
|
406
|
+
e.batch = result.batch
|
|
407
|
+
e.code = 'partial_batch'
|
|
408
|
+
throw e
|
|
409
|
+
}
|
|
410
|
+
return { ...result, count: normalized.length, batched: true }
|
|
411
|
+
} catch (err) {
|
|
412
|
+
// Older RSP/1 agents reject unknown cmd:'batch' before injection; safely
|
|
413
|
+
// fall back only for that explicit validation response, never on timeout.
|
|
414
|
+
if (err?.code !== 'bad_event') throw err
|
|
415
|
+
for (const ev of normalized) await this.sendEvent(ev)
|
|
416
|
+
return { ok: true, count: normalized.length, via: 'ws', batched: false, fallback: true }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 注入一个事件(自包含)。mouse move 限速;key/mouse 记录按下态。返回 {ok,seq?,via}。 */
|
|
421
|
+
async sendEvent(ev) {
|
|
422
|
+
if (this.closed) throw badArg('client 已关闭')
|
|
423
|
+
if (this._authFailed) { const e = new Error('鉴权失败,请重新提供令牌'); e.code = 'unauthorized'; throw e }
|
|
424
|
+
if (!ev || typeof ev !== 'object' || !ev.cmd) throw badArg('事件必须含 cmd')
|
|
425
|
+
// 快捷键修饰键展开:被控端助手只认物理键码(不解析 modifiers),所以控制端把
|
|
426
|
+
// modifiers 拆成真实的修饰键 down/up 事件。down=先按修饰键再按主键;up=先抬主键
|
|
427
|
+
// 再抬修饰键(逆序),与「down KeyA modifiers=[cmd] 再 up」的成对用法吻合。
|
|
428
|
+
if (ev.cmd === 'key' && Array.isArray(ev.modifiers) && ev.modifiers.length) {
|
|
429
|
+
const MODCODE = { cmd: 'MetaLeft', ctrl: 'ControlLeft', alt: 'AltLeft', shift: 'ShiftLeft' }
|
|
430
|
+
const mods = ev.modifiers.map((m) => MODCODE[m]).filter(Boolean)
|
|
431
|
+
const main = { cmd: 'key', action: ev.action, code: ev.code }
|
|
432
|
+
if (ev.action === 'down') {
|
|
433
|
+
for (const c of mods) await this.sendEvent({ cmd: 'key', action: 'down', code: c })
|
|
434
|
+
return await this.sendEvent(main)
|
|
435
|
+
}
|
|
436
|
+
const r = await this.sendEvent(main)
|
|
437
|
+
for (const c of [...mods].reverse()) await this.sendEvent({ cmd: 'key', action: 'up', code: c })
|
|
438
|
+
return r
|
|
439
|
+
}
|
|
440
|
+
// move 限速(§5.1 ≤60/s)
|
|
441
|
+
if (ev.cmd === 'mouse' && ev.action === 'move') {
|
|
442
|
+
const wait = this._lastMoveAt + MOVE_MIN_GAP_MS - Date.now()
|
|
443
|
+
if (wait > 0) await sleep(wait)
|
|
444
|
+
this._lastMoveAt = Date.now()
|
|
445
|
+
}
|
|
446
|
+
const bytes = Buffer.byteLength(JSON.stringify(ev), 'utf8')
|
|
447
|
+
if (bytes > MAX_EVENT_BYTES) { const e = new Error('事件超过 64KiB'); e.code = 'too_large'; throw e }
|
|
448
|
+
|
|
449
|
+
const via = await this._ensureControl()
|
|
450
|
+
let result
|
|
451
|
+
if (via === 'ws') result = await this._sendWs(ev)
|
|
452
|
+
else result = await this._sendPost(ev)
|
|
453
|
+
this._trackPressed(ev)
|
|
454
|
+
return { ...result, via }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
_sendWs(ev) {
|
|
458
|
+
const seq = ++this._seq
|
|
459
|
+
const payload = { ...ev, seq }
|
|
460
|
+
return new Promise((resolve, reject) => {
|
|
461
|
+
const timer = setTimeout(() => {
|
|
462
|
+
const p = this._pending.get(seq)
|
|
463
|
+
if (p) { this._pending.delete(seq); reject(new Error('ack 超时(5s)')) }
|
|
464
|
+
}, ACK_TIMEOUT_MS)
|
|
465
|
+
// Pipelined control: multiple events may be in flight at once, each matched by
|
|
466
|
+
// seq. The old single _pending slot serialized bursts (a rapid move stream or
|
|
467
|
+
// click+move waited one full ack RTT per event). The agent already processes
|
|
468
|
+
// messages concurrently and acks per-seq, so a Map is safe and lowers RTT.
|
|
469
|
+
this._pending.set(seq, { seq, resolve, reject, timer, t0: performance.now() })
|
|
470
|
+
try { this.controlWs.send(JSON.stringify(payload)) }
|
|
471
|
+
catch (err) { this._pending.delete(seq); clearTimeout(timer); reject(err) }
|
|
472
|
+
})
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async _sendPost(ev) {
|
|
476
|
+
const t0 = performance.now()
|
|
477
|
+
const res = await this.fetch(this._url('/control'), {
|
|
478
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(ev),
|
|
479
|
+
})
|
|
480
|
+
let body = null; try { body = await res.json() } catch { /* ignore */ }
|
|
481
|
+
this._recordRtt(performance.now() - t0)
|
|
482
|
+
if (res.status === 200 && body && body.ok) return { ok: true, quality: body.quality, wake: body.wake }
|
|
483
|
+
const code = body?.error?.code || httpCodeToError(res.status)
|
|
484
|
+
const err = new Error(body?.error?.message || `POST /control 返回 ${res.status}`)
|
|
485
|
+
err.code = code; throw err
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
_trackPressed(ev) {
|
|
489
|
+
if (ev.cmd === 'key') {
|
|
490
|
+
if (ev.action === 'down') this._pressedKeys.add(ev.code)
|
|
491
|
+
else if (ev.action === 'up') this._pressedKeys.delete(ev.code)
|
|
492
|
+
} else if (ev.cmd === 'mouse') {
|
|
493
|
+
const b = ev.button || 'left'
|
|
494
|
+
if (ev.action === 'down') this._pressedButtons.add(b)
|
|
495
|
+
else if (ev.action === 'up' || ev.action === 'click') this._pressedButtons.delete(b)
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** 尽力补发所有按下态的 up(POST 模式无服务端跟踪时尤其需要)。 */
|
|
500
|
+
async releaseAll() {
|
|
501
|
+
const keys = [...this._pressedKeys], buttons = [...this._pressedButtons]
|
|
502
|
+
for (const code of keys) { try { await this.sendEvent({ cmd: 'key', action: 'up', code }) } catch { /* best effort */ } }
|
|
503
|
+
for (const button of buttons) { try { await this.sendEvent({ cmd: 'mouse', action: 'up', x: 0, y: 0, button }) } catch { /* best effort */ } }
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
_recordRtt(ms) {
|
|
507
|
+
if (!(ms >= 0)) return
|
|
508
|
+
this._rttLast = ms
|
|
509
|
+
this._rttSamples++
|
|
510
|
+
this._rttEma = this._rttEma ? this._rttEma * 0.8 + ms * 0.2 : ms
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* S1: 运行时画质调参(被控端原子换档,画面不中断)。仅 h264 通道三参 + jpeg 三参。
|
|
515
|
+
* 被控端不支持(features.quality=false,旧版 agent)时抛 unsupported。返回 ack 的 quality 快照。
|
|
516
|
+
*/
|
|
517
|
+
async setQuality(params = {}) {
|
|
518
|
+
if (!this.info?.features?.quality) { const e = new Error('被控端不支持运行时调参(features.quality)'); e.code = 'unsupported'; throw e }
|
|
519
|
+
const ev = { cmd: 'quality' }
|
|
520
|
+
for (const k of ['bitrateKbps', 'h264Fps', 'h264MaxWidth', 'jpegFps', 'jpegQuality', 'maxWidth']) {
|
|
521
|
+
if (typeof params[k] === 'number' && Number.isFinite(params[k])) ev[k] = params[k]
|
|
522
|
+
}
|
|
523
|
+
if (Object.keys(ev).length === 1) throw badArg('至少提供一个画质参数')
|
|
524
|
+
const r = await this.sendEvent(ev)
|
|
525
|
+
// Keep the cached info snapshot live so rsp_status/status() reflects the applied quality.
|
|
526
|
+
if (r?.quality && this.info) this.info.quality = r.quality
|
|
527
|
+
// 手动换档后同步自动降档的当前档位,避免 auto 从旧档继续阶梯。手动抬高时把基线
|
|
528
|
+
// 也抬到新档(用户的手动选择成为新的恢复上限);并清零延迟累计防止立刻误触发。
|
|
529
|
+
if (this._aq && r?.quality && typeof r.quality.bitrateKbps === 'number') {
|
|
530
|
+
const lvl = this._levelForBitrate(r.quality.bitrateKbps)
|
|
531
|
+
this._aq.level = lvl
|
|
532
|
+
if (lvl > this._aq.baselineLevel) this._aq.baselineLevel = lvl
|
|
533
|
+
this._aq.highSince = 0
|
|
534
|
+
this._aq.lowSince = 0
|
|
535
|
+
}
|
|
536
|
+
return r
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 强制唤醒被控端显示器(点亮已息屏/睡眠的屏幕)。需被控端 features.wake(新版 agent)。
|
|
541
|
+
* 旧 agent 不支持时抛 unsupported。holdMs=点亮后保持唤醒的毫秒数(0..30000,默认 2000)。
|
|
542
|
+
* 返回 { ok, wake:{platform,method,holdMs,ok,error?}, via }。
|
|
543
|
+
*/
|
|
544
|
+
async wake(opts = {}) {
|
|
545
|
+
if (!this.info?.features?.wake) { const e = new Error('被控端不支持强制唤醒(features.wake)'); e.code = 'unsupported'; throw e }
|
|
546
|
+
const ev = { cmd: 'wake' }
|
|
547
|
+
if (typeof opts.holdMs === 'number' && Number.isFinite(opts.holdMs)) ev.holdMs = opts.holdMs
|
|
548
|
+
const r = await this.sendEvent(ev)
|
|
549
|
+
return { ok: r?.wake?.ok !== false, wake: r?.wake ?? null, via: r.via }
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** 阶梯中码率不超过 bitrate 的最高档索引。 */
|
|
553
|
+
_levelForBitrate(bitrate) {
|
|
554
|
+
let lvl = 0
|
|
555
|
+
for (let i = 0; i < QUALITY_LADDER.length; i++) if (QUALITY_LADDER[i].bitrateKbps <= bitrate) lvl = i
|
|
556
|
+
return lvl
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* S4: 自动降档(opt-in)。以操控 ack RTT 为信号:持续高延迟→沿阶梯降一档;持续健康→
|
|
561
|
+
* 升回但不超过启用时的基线。仅在被控端支持 features.quality 时生效。RTT 由操控流量驱动,
|
|
562
|
+
* 纯观看(无输入)时不更新——此时可手动 rsp_quality。
|
|
563
|
+
*/
|
|
564
|
+
enableAutoQuality(opts = {}) {
|
|
565
|
+
if (!this.info?.features?.quality) { const e = new Error('被控端不支持运行时调参,无法自动降档'); e.code = 'unsupported'; throw e }
|
|
566
|
+
this.disableAutoQuality()
|
|
567
|
+
const o = {
|
|
568
|
+
highRttMs: opts.highRttMs ?? 200,
|
|
569
|
+
lowRttMs: opts.lowRttMs ?? 120,
|
|
570
|
+
degradeAfterMs: opts.degradeAfterMs ?? 5000,
|
|
571
|
+
recoverAfterMs: opts.recoverAfterMs ?? 30000,
|
|
572
|
+
tickMs: opts.tickMs ?? 1000,
|
|
573
|
+
}
|
|
574
|
+
const baseline = this.info?.quality ?? null
|
|
575
|
+
// 基线档位:阶梯中码率不超过基线的最高档(无基线时从 balanced 起)。
|
|
576
|
+
let baselineLevel = 2
|
|
577
|
+
if (baseline && typeof baseline.bitrateKbps === 'number') baselineLevel = this._levelForBitrate(baseline.bitrateKbps)
|
|
578
|
+
const aq = { opts: o, baseline, baselineLevel, level: baselineLevel, highSince: 0, lowSince: 0, changes: 0, timer: null }
|
|
579
|
+
aq.timer = setInterval(() => this._aqTick(), o.tickMs)
|
|
580
|
+
aq.timer.unref?.()
|
|
581
|
+
this._aq = aq
|
|
582
|
+
return { enabled: true, baselineLevel, level: aq.level }
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
disableAutoQuality() {
|
|
586
|
+
if (this._aq?.timer) clearInterval(this._aq.timer)
|
|
587
|
+
this._aq = null
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
_aqTick() {
|
|
591
|
+
const aq = this._aq
|
|
592
|
+
if (!aq || this.closed || this._authFailed) return
|
|
593
|
+
const rtt = this._rttEma
|
|
594
|
+
const step = aq.opts.tickMs
|
|
595
|
+
if (rtt > aq.opts.highRttMs) aq.highSince += step; else aq.highSince = 0
|
|
596
|
+
if (rtt > 0 && rtt < aq.opts.lowRttMs) aq.lowSince += step; else aq.lowSince = 0
|
|
597
|
+
let next = null
|
|
598
|
+
if (aq.highSince >= aq.opts.degradeAfterMs && aq.level > 0) { next = aq.level - 1; aq.highSince = 0 }
|
|
599
|
+
else if (aq.lowSince >= aq.opts.recoverAfterMs && aq.level < aq.baselineLevel) { next = aq.level + 1; aq.lowSince = 0 }
|
|
600
|
+
if (next == null) return
|
|
601
|
+
aq.level = next
|
|
602
|
+
aq.changes++
|
|
603
|
+
this.setQuality(QUALITY_LADDER[next]).catch((e) => this.log('autoQuality 调参失败:' + e.message))
|
|
604
|
+
this.emit('auto-quality', { level: next, quality: QUALITY_LADDER[next], rttEma: +rtt.toFixed(1) })
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** 等待一帧比 since 更新的帧(fresh 截图用)。超时返回最近帧。 */
|
|
608
|
+
async waitFrame(since = Date.now(), timeoutMs = 2000) {
|
|
609
|
+
if (this.lastFrame && this.lastFrame.at >= since) return this.lastFrame
|
|
610
|
+
return new Promise((resolve) => {
|
|
611
|
+
let done = false
|
|
612
|
+
const finish = (f) => { if (done) return; done = true; clearTimeout(timer); this.off('frame', onFrame); resolve(f) }
|
|
613
|
+
const onFrame = (f) => finish(f)
|
|
614
|
+
const timer = setTimeout(() => finish(this.lastFrame), timeoutMs)
|
|
615
|
+
this.on('frame', onFrame)
|
|
616
|
+
if (this.lastFrame && this.lastFrame.at >= since) finish(this.lastFrame)
|
|
617
|
+
})
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
status() {
|
|
621
|
+
return {
|
|
622
|
+
baseUrl: this.baseUrl,
|
|
623
|
+
token: maskToken(this.token),
|
|
624
|
+
protocol: this.info?.protocol ?? null,
|
|
625
|
+
connected: this.screenState === 'open',
|
|
626
|
+
screenState: this.screenState,
|
|
627
|
+
controlState: this.controlState,
|
|
628
|
+
controlMode: this.controlMode,
|
|
629
|
+
controlEnabled: this.info?.control?.enabled ?? null,
|
|
630
|
+
controlRttMs: { ema: +this._rttEma.toFixed(1), last: +this._rttLast.toFixed(1), samples: this._rttSamples },
|
|
631
|
+
quality: this.info?.quality ?? null,
|
|
632
|
+
features: this.info?.features ?? null,
|
|
633
|
+
autoQuality: this._aq ? { enabled: true, level: this._aq.level, baselineLevel: this._aq.baselineLevel, changes: this._aq.changes } : { enabled: false },
|
|
634
|
+
hello: this.hello,
|
|
635
|
+
logical: this.hello ? { width: this.hello.width, height: this.hello.height } : (this.info?.screen ? { width: this.info.screen.width, height: this.info.screen.height } : null),
|
|
636
|
+
lastFrame: this.lastFrame ? { width: this.lastFrame.width, height: this.lastFrame.height, at: this.lastFrame.at, ageMs: Date.now() - this.lastFrame.at, bytes: this.lastFrame.bytes.length } : null,
|
|
637
|
+
frameCount: this.frameCount,
|
|
638
|
+
viewers: this.info?.viewers ?? null,
|
|
639
|
+
engine: this.info?.engine ?? null,
|
|
640
|
+
pressedKeys: [...this._pressedKeys],
|
|
641
|
+
pressedButtons: [...this._pressedButtons],
|
|
642
|
+
authFailed: this._authFailed,
|
|
643
|
+
lastError: this.lastError,
|
|
644
|
+
h264: this.h264State === 'open',
|
|
645
|
+
h264State: this.h264State,
|
|
646
|
+
h264Hello: this.h264Hello,
|
|
647
|
+
h264Bytes: this.h264Bytes,
|
|
648
|
+
h264Nals: this.h264Nals,
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async disconnect() {
|
|
653
|
+
if (this.closed) return
|
|
654
|
+
this.disableAutoQuality()
|
|
655
|
+
try { await this.releaseAll() } catch { /* best effort */ }
|
|
656
|
+
this.closed = true
|
|
657
|
+
if (this._screenTimer) { clearTimeout(this._screenTimer); this._screenTimer = null }
|
|
658
|
+
if (this._pending.size) { for (const [, p] of this._pending) { clearTimeout(p.timer); p.reject(new Error('client 关闭')) } this._pending.clear() }
|
|
659
|
+
try { this.screenWs?.close(1000) } catch { /* ignore */ }
|
|
660
|
+
try { this.controlWs?.close(1000) } catch { /* ignore */ }
|
|
661
|
+
try { this.h264Ws?.close(1000) } catch { /* ignore */ }
|
|
662
|
+
this.screenWs = null; this.controlWs = null; this.h264Ws = null
|
|
663
|
+
this.screenState = 'closed'; this.controlState = 'closed'; this.h264State = 'closed'
|
|
664
|
+
this.emit('screen-state', this.screenState)
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Annex-B NAL 类型(跳过 3/4 字节起始码)。 */
|
|
669
|
+
function h264NalType(buf) {
|
|
670
|
+
let i = 0
|
|
671
|
+
if (buf[0] === 0 && buf[1] === 0 && buf[2] === 0 && buf[3] === 1) i = 4
|
|
672
|
+
else if (buf[0] === 0 && buf[1] === 0 && buf[2] === 1) i = 3
|
|
673
|
+
return buf[i] & 0x1f
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function httpCodeToError(status) {
|
|
677
|
+
return ({ 401: 'unauthorized', 403: 'forbidden', 400: 'bad_event', 413: 'too_large', 404: 'not_found', 503: 'engine_unavailable' })[status] || 'engine_unavailable'
|
|
678
|
+
}
|
|
679
|
+
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)) }
|
|
680
|
+
|
|
681
|
+
export { maskToken, normalizeBase }
|