dsh-miniwin 0.0.0-stage → 0.2.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.
Files changed (48) hide show
  1. package/LICENSE +28 -0
  2. package/README.en.md +83 -0
  3. package/README.md +289 -2
  4. package/cordis.patch.yml +10 -0
  5. package/lib/client.js +532 -0
  6. package/lib/discover.js +244 -0
  7. package/lib/index.js +2290 -0
  8. package/lib/qr.js +313 -0
  9. package/package.json +57 -6
  10. package/runtime/adb-control.js +470 -0
  11. package/runtime/apk/miniwin.apk +0 -0
  12. package/runtime/assets/icon.ico +0 -0
  13. package/runtime/assets/icon.png +0 -0
  14. package/runtime/assets/tray-16.png +0 -0
  15. package/runtime/assets/tray-32.png +0 -0
  16. package/runtime/au.js +131 -0
  17. package/runtime/audio-bridge.js +267 -0
  18. package/runtime/audio-healer.js +369 -0
  19. package/runtime/avcc.js +186 -0
  20. package/runtime/device.js +307 -0
  21. package/runtime/main.js +3268 -0
  22. package/runtime/mkv-reader.js +326 -0
  23. package/runtime/package.json +5 -0
  24. package/runtime/preload.js +106 -0
  25. package/runtime/scrcpy-capture.js +619 -0
  26. package/runtime/streamer.js +192 -0
  27. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/AdbWinApi.dll +0 -0
  28. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/AdbWinUsbApi.dll +0 -0
  29. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/LICENSE.txt +204 -0
  30. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/SDL3.dll +0 -0
  31. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/adb.exe +0 -0
  32. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avcodec-63.dll +0 -0
  33. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avformat-63.dll +0 -0
  34. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avutil-61.dll +0 -0
  35. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/disconnected.png +0 -0
  36. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/libusb-1.0.dll +0 -0
  37. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/open_a_terminal_here.bat +1 -0
  38. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy-noconsole.vbs +7 -0
  39. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy-server +0 -0
  40. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy.exe +0 -0
  41. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy.png +0 -0
  42. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/swresample-7.dll +0 -0
  43. package/runtime/ui.html +3143 -0
  44. package/runtime/usb-hotplug.js +194 -0
  45. package/runtime/wifi-adb-keeper.js +395 -0
  46. package/runtime/wifi-discovery.js +213 -0
  47. package/runtime/wifi-receiver.js +733 -0
  48. package/screenshots.json +5 -0
@@ -0,0 +1,470 @@
1
+ /**
2
+ * 反向控制:持久 adb shell 会话。
3
+ *
4
+ * ── 为什么放弃 scrcpy 控制协议 ──
5
+ *
6
+ * scrcpy 的二进制控制通道理论上是最优解(1~3ms、支持 UTF-8 文本)。
7
+ * 在这台华为(P70 Pro / HarmonyOS 4.2 / Android 12)上实测走不通:
8
+ *
9
+ * server 正常启动,socket 也能连上、能保持空闲连接;
10
+ * 但只要写入第一条控制消息(不管是 inject_touch 还是最简单的
11
+ * inject_keycode),server 立刻 SIGABRT 退出。
12
+ *
13
+ * 期间排除过的原因:
14
+ * - ClassNotFoundException → 定位到 scrcpy-server.jar 这个**文件名**
15
+ * 会被安全策略清理,改成随机名后 jar 稳定存活
16
+ * - scid 必须是十六进制且值不超过 int 范围,否则 Options.parse 抛异常
17
+ * - pkill -f 会匹配到执行它的 sh 自身,把自己进程组杀掉
18
+ *
19
+ * 以上都修完之后 server 能稳跑,但仍在收到首个控制消息时崩溃,
20
+ * 属于 server 侧与这套 ROM 的兼容问题,客户端无法绕过。
21
+ * 因此改用下面的方案。
22
+ *
23
+ * ── 现在的方案 ──
24
+ *
25
+ * 起一个**长驻的 adb shell**,把 input 命令通过 stdin 喂进去。
26
+ *
27
+ * 关键细节:必须带 `-T`(禁用 PTY 分配)。不带的话 adb 会给远端分配
28
+ * 伪终端,stdin 的换行处理会出问题,命令写进去没反应。
29
+ *
30
+ * 实测延迟对比(同一台设备):
31
+ * 每次 spawn adb + input tap 243 ms/次 ← 拖动完全不可用
32
+ * 持久 shell + stdin 写入 13 ms/次 ← 可用
33
+ *
34
+ * 缺点:input 命令是逐条执行的,没有「按住-移动-抬起」的连续手势,
35
+ * 所以拖动只能用 `input swipe`(系统自己插值)。
36
+ * 对投屏远控这个场景足够 —— 滚动、翻页、拖拽都能用。
37
+ */
38
+
39
+ const { spawn } = require('node:child_process')
40
+
41
+ /**
42
+ * 设备自动切换看门狗。
43
+ *
44
+ * ── 要解决什么 ──
45
+ *
46
+ * 用户的两种连接方式各有失效场景:
47
+ * - WiFi adb(tcpip 5555)在手机休眠/切网后会掉,表现为
48
+ * `cannot connect ... (10061)`,而 App 的 TCP 推流还在跑
49
+ * - USB 会被拔掉
50
+ *
51
+ * 手动 adb connect 很烦,所以这里做成自动的:
52
+ * 每 4 秒看一次设备表,按优先级挑一个可用的:
53
+ * WiFi 有效 → 继续用(省得反复重连)
54
+ * 只有 USB → 用 USB
55
+ * 都没有 → 尝试重连上次的 WiFi 地址,并尝试用 USB 重新开 tcpip
56
+ *
57
+ * 切换时**不重建 shell**,只改 serial 并在下次重建时生效 ——
58
+ * 正在跑的控制会话保持可用,用户感觉不到中断。
59
+ */
60
+ class DeviceWatcher {
61
+ /**
62
+ * @param {object} o
63
+ * @param {string} o.adb
64
+ * @param {string[]} [o.wifiCandidates] 已知的 WiFi 地址(如 172.31.100.199:5555)
65
+ */
66
+ constructor (o) {
67
+ this.adb = o.adb
68
+ this.wifiCandidates = o.wifiCandidates || []
69
+ this.current = null // 当前使用的 serial
70
+ this.lastKind = '' // 'wifi' | 'usb' | ''
71
+ this.timer = null
72
+ this._onChange = null
73
+ this._onLog = null
74
+ this._busy = false
75
+ /**
76
+ * 「现在是否正在投屏采集」——由上层注入。
77
+ *
78
+ * ══════════ 这个回调是本文件最重要的一行防护 ══════════
79
+ *
80
+ * 用户的投诉原话:「投屏鼠标只要操作连接就会断」。
81
+ *
82
+ * 复现链路(实测):
83
+ * ① 用户在画面上点一下 → 控制通道懒启动 → ensureCtrl()
84
+ * ② ensureCtrl 里 new DeviceWatcher(...).start(4000)
85
+ * ③ 第一次 _tick 立刻跑 → 只有 USB → _prepareTcpip(serial)
86
+ * ④ `adb tcpip 5555` → **手机侧 adbd 重启**
87
+ * ⑤ 重启瞬间 scrcpy 的 USB 传输被掐 → 打印
88
+ * `WARN: Device disconnected` → 退出 code=2
89
+ * ⑥ 上层看到 scrcpy 退出 → 断线重连 → 画面黑掉几秒
90
+ *
91
+ * 实测证据(scrcpy 录制中执行 tcpip):
92
+ * [6s] 存活 → 执行 adb tcpip 5555 → [7s] 已退出 code=2
93
+ * 对照组(录制中只发 input tap / swipe,不碰 tcpip):
94
+ * 连续 16 秒稳定出帧、文件持续增长,scrcpy 毫发无伤。
95
+ *
96
+ * 结论:**input 注入是安全的,tcpip 才是断流元凶。**
97
+ * 所以采集期间一律不碰 adbd —— 宁可等下次冷启动再准备无线通道。
98
+ */
99
+ this.isStreaming = o.isStreaming || null
100
+ }
101
+
102
+ onLog (fn) { this._onLog = fn }
103
+ onChange (fn) { this._onChange = fn }
104
+ log (m) { if (this._onLog) this._onLog(m) }
105
+
106
+ _run (args, timeout = 6000) {
107
+ const { execFile } = require('node:child_process')
108
+ return new Promise((resolve) => {
109
+ execFile(this.adb, args, { timeout, windowsHide: true },
110
+ (err, stdout, stderr) => resolve(String(stdout || '') + String(stderr || '')))
111
+ })
112
+ }
113
+
114
+ /** 读设备表,返回 { wifi: [], usb: [] } */
115
+ async _list () {
116
+ const out = await this._run(['devices'])
117
+ const wifi = []
118
+ const usb = []
119
+ for (const line of out.split(/\r?\n/)) {
120
+ const m = line.match(/^(\S+)\s+device\b/)
121
+ if (!m) continue
122
+ const s = m[1]
123
+ if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(s)) wifi.push(s)
124
+ else usb.push(s)
125
+ }
126
+ return { wifi, usb }
127
+ }
128
+
129
+ async _tick () {
130
+ if (this._busy) return
131
+ this._busy = true
132
+ try {
133
+ const { wifi, usb } = await this._list()
134
+
135
+ /**
136
+ * 选择顺序很重要。
137
+ *
138
+ * 优先 WiFi:一旦无线通了就别再切回 USB —— 用户插着线时
139
+ * 我们也不想把正在用的无线会话切走,那会造成无谓的抖动。
140
+ *
141
+ * 只有在完全没有 WiFi 时才用 USB,同时**顺手给它开 tcpip**,
142
+ * 这样拔线后能自动回到无线。
143
+ */
144
+ let pick = null
145
+ let kind = ''
146
+
147
+ if (wifi.length) {
148
+ pick = this.current && wifi.includes(this.current) ? this.current : wifi[0]
149
+ kind = 'wifi'
150
+ } else if (usb.length) {
151
+ pick = this.current && usb.includes(this.current) ? this.current : usb[0]
152
+ kind = 'usb'
153
+ // 用 USB 时开无线通道,为后续拔线做准备
154
+ this._prepareTcpip(pick).catch(() => {})
155
+ }
156
+
157
+ if (!pick) {
158
+ // 什么都没有:尝试重连已知的 WiFi 地址
159
+ await this._reconnectWifi()
160
+ return
161
+ }
162
+
163
+ if (pick !== this.current) {
164
+ const prev = this.current
165
+ this.current = pick
166
+ this.lastKind = kind
167
+ this.log(`设备${prev ? '切换' : '就绪'}: ${pick}(${kind === 'wifi' ? '无线' : 'USB'})`)
168
+ if (this._onChange) this._onChange({ serial: pick, kind, previous: prev })
169
+ }
170
+ } finally {
171
+ this._busy = false
172
+ }
173
+ }
174
+
175
+ /**
176
+ * USB 在场时开 tcpip,让拔线后能自动回无线。
177
+ *
178
+ * ══════════ 默认关闭,且采集期间硬阻断 ══════════
179
+ *
180
+ * 这个方法会执行 `adb tcpip 5555`,而 adb 的手册写得很清楚:
181
+ * "restarting in TCP mode port: 5555"
182
+ * 它是**重启 adbd**,不是「加个监听」。
183
+ *
184
+ * adbd 一重启,走 USB 传输的所有连接立刻失效 —— 包括
185
+ * scrcpy 的 forward/reverse 隧道。现象就是用户说的:
186
+ * 「投屏鼠标只要操作连接就会断」(点一下 → 触发控制通道
187
+ * → 触发本方法 → 画面断)。
188
+ *
189
+ * 而且设备一旦被设成 tcpip 模式,`getprop service.adb.tcp.port`
190
+ * 就一直是 5555,**根本不需要每次重新下发**。重复下发只是白挨
191
+ * 一次 adbd 重启。
192
+ *
193
+ * 所以这里三道闸:
194
+ * ① isStreaming() 为真 → 直接跳过(采集期绝不碰 adbd)
195
+ * ② 设备已经是 tcpip 模式 → 跳过(没必要重启)
196
+ * ③ 本实例已经准备过 → 跳过
197
+ */
198
+ async _prepareTcpip (usbSerial) {
199
+ if (this._tcpipDone === usbSerial) return
200
+
201
+ if (this.isStreaming && this.isStreaming()) {
202
+ this.log('采集进行中,跳过 tcpip(它会重启 adbd 导致断流)')
203
+ return
204
+ }
205
+
206
+ /**
207
+ * 先问设备:你现在是 TCP 模式吗?
208
+ * 已经是 5555 就什么都不做 —— 拔线后 adb connect 直接能连上,
209
+ * 不需要再让它重启一次。
210
+ */
211
+ try {
212
+ const cur = await this._run([
213
+ '-s', usbSerial, 'shell', 'getprop', 'service.adb.tcp.port'
214
+ ], 6000)
215
+ if (String(cur).trim() === '5555') {
216
+ this._tcpipDone = usbSerial
217
+ this.log('设备已在 TCP 模式(service.adb.tcp.port=5555),无需重启 adbd')
218
+ return
219
+ }
220
+ } catch { /* 查不到就按未开启处理 */ }
221
+
222
+ this._tcpipDone = usbSerial
223
+ await this._run(['-s', usbSerial, 'tcpip', '5555'], 12000).catch(() => {})
224
+ this.log('已为 USB 设备开启无线通道(拔线后可自动切换)')
225
+ }
226
+
227
+ /** 尝试重连已知的 WiFi 地址 */
228
+ async _reconnectWifi () {
229
+ if (!this.wifiCandidates.length) return
230
+ for (const addr of this.wifiCandidates) {
231
+ const out = await this._run(['connect', addr], 5000)
232
+ if (/connected to/.test(out)) {
233
+ this.log('已重连无线: ' + addr)
234
+ return
235
+ }
236
+ }
237
+ }
238
+
239
+ start (intervalMs = 4000) {
240
+ if (this.timer) return
241
+ this._tick().catch(() => {})
242
+ this.timer = setInterval(() => { this._tick().catch(() => {}) }, intervalMs)
243
+ }
244
+
245
+ stop () {
246
+ if (this.timer) { clearInterval(this.timer); this.timer = null }
247
+ }
248
+ }
249
+
250
+ class AdbShellControl {
251
+ /**
252
+ * @param {object} o
253
+ * @param {string} o.adb adb 可执行文件
254
+ * @param {string} o.serial 设备序列号
255
+ */
256
+ constructor (o) {
257
+ this.adb = o.adb
258
+ this.serial = o.serial
259
+ this.sh = null
260
+ this.ready = false
261
+ this.physW = 0
262
+ this.physH = 0
263
+ this.screenW = 0 // 视频像素宽(调用方坐标基准)
264
+ this.screenH = 0
265
+ this._buf = ''
266
+ this._waiters = []
267
+ }
268
+
269
+ log (msg) { if (this._onLog) this._onLog(msg) }
270
+ onLog (fn) { this._onLog = fn }
271
+
272
+ _run (args, timeout = 15000) {
273
+ const { execFile } = require('node:child_process')
274
+ return new Promise((resolve, reject) => {
275
+ execFile(this.adb, ['-s', this.serial, ...args],
276
+ { timeout, windowsHide: true },
277
+ (err, stdout, stderr) => {
278
+ if (err) reject(new Error(String(stderr || err.message).trim()))
279
+ else resolve(String(stdout || '').trim())
280
+ })
281
+ })
282
+ }
283
+
284
+ /** 查手机物理分辨率 —— input 命令的坐标基准 */
285
+ async _querySize () {
286
+ try {
287
+ const out = await this._run(['shell', 'wm', 'size'], 8000)
288
+ const m = out.match(/Physical size:\s*(\d+)x(\d+)/)
289
+ if (m) { this.physW = Number(m[1]); this.physH = Number(m[2]) }
290
+ } catch {}
291
+ if (!this.physW) { this.physW = this.screenW || 1080; this.physH = this.screenH || 2400 }
292
+ this.log(`物理分辨率 ${this.physW}×${this.physH}`)
293
+ }
294
+
295
+ async start () {
296
+ if (this.ready) return { ok: true, mode: 'adb-shell' }
297
+ try {
298
+ await this._querySize()
299
+
300
+ /**
301
+ * 起持久 shell。
302
+ *
303
+ * -T 是必需的:不加的话 adb 会分配 PTY,stdin 写入的命令
304
+ * 会被终端的行编辑逻辑吞掉,表现为「写了没反应」。
305
+ */
306
+ this.sh = spawn(this.adb, ['-s', this.serial, 'shell', '-T'],
307
+ { windowsHide: true })
308
+
309
+ this.sh.stdout.on('data', d => { this._buf += d.toString() })
310
+ this.sh.stderr.on('data', d => { this._buf += d.toString() })
311
+ this.sh.on('exit', () => { this.ready = false; this.sh = null })
312
+ this.sh.on('error', (e) => this.log('shell 错误: ' + e.message))
313
+
314
+ // 等 shell 真正可用:写一条 echo 并等回显
315
+ const ok = await this._ping()
316
+ if (!ok) throw new Error('shell 无响应')
317
+
318
+ this.ready = true
319
+ this.log('控制通道就绪(持久 adb shell)')
320
+ return { ok: true, mode: 'adb-shell' }
321
+ } catch (e) {
322
+ this.log('控制通道启动失败: ' + String(e.message || e))
323
+ await this.stop()
324
+ return { ok: false, error: String(e.message || e) }
325
+ }
326
+ }
327
+
328
+ /** 写一条命令进 shell,等它回显一个标记确认执行完 */
329
+ _ping (timeoutMs = 3000) {
330
+ return new Promise((resolve) => {
331
+ if (!this.sh) return resolve(false)
332
+ const mark = '__p' + Math.random().toString(36).slice(2, 7) + '__'
333
+ const t = setTimeout(() => resolve(false), timeoutMs)
334
+ const check = () => {
335
+ if (this._buf.includes(mark)) {
336
+ clearTimeout(t)
337
+ this.sh.stdout.removeListener('data', check)
338
+ resolve(true)
339
+ }
340
+ }
341
+ this.sh.stdout.on('data', check)
342
+ this.sh.stdin.write(`echo ${mark}\n`)
343
+ setTimeout(check, 50)
344
+ })
345
+ }
346
+
347
+ async stop () {
348
+ this.ready = false
349
+ try { if (this.sh) this.sh.kill() } catch {}
350
+ this.sh = null
351
+ }
352
+
353
+ /**
354
+ * 切换目标设备(USB ↔ WiFi 无感切换)。
355
+ *
356
+ * 只改 serial 并异步重建 shell,不阻塞调用方。
357
+ * 重建期间旧的 shell 还能继续用(它连着自己的设备),
358
+ * 所以用户感觉不到中断 —— 最多是切换瞬间的一两条命令丢失。
359
+ *
360
+ * 关键:**不 kill 旧 shell 直到新 shell 起来**,
361
+ * 否则会出现「两边都不可用」的窗口期。
362
+ */
363
+ switchTo (newSerial) {
364
+ if (!newSerial || newSerial === this.serial) return
365
+ const oldSerial = this.serial
366
+ this.serial = newSerial
367
+
368
+ // 异步重建,先让旧 shell 继续服务
369
+ ;(async () => {
370
+ const oldSh = this.sh
371
+ this.sh = null
372
+ this.ready = false
373
+ try {
374
+ await this.start()
375
+ // 新 shell 起来了,才关旧的
376
+ try { if (oldSh) oldSh.kill() } catch {}
377
+ this.log(`已切到 ${newSerial}(原 ${oldSerial})`)
378
+ } catch (e) {
379
+ this.log('切换失败,回滚: ' + String(e.message || e))
380
+ this.serial = oldSerial
381
+ this.sh = oldSh
382
+ this.ready = !!oldSh
383
+ }
384
+ })()
385
+ }
386
+
387
+ setScreen (w, h) {
388
+ if (w > 0) this.screenW = Math.round(w)
389
+ if (h > 0) this.screenH = Math.round(h)
390
+ }
391
+
392
+ /**
393
+ * 视频坐标 → 物理坐标。
394
+ *
395
+ * 画面是 720×1626(编码器缩放后的),而 input 命令要的是
396
+ * 屏幕物理坐标 1260×2844。不换算的话点击全部偏到别处,
397
+ * 看起来就像「点了没反应」。
398
+ */
399
+ toPhysical (x, y) {
400
+ const sx = (this.physW || 1260) / (this.screenW || this.physW || 1260)
401
+ const sy = (this.physH || 2844) / (this.screenH || this.physH || 2844)
402
+ return { x: Math.round(x * sx), y: Math.round(y * sy) }
403
+ }
404
+
405
+ _cmd (line) {
406
+ if (!this.sh || !this.sh.stdin.writable) {
407
+ this.log('命令丢弃:shell 不可用')
408
+ return false
409
+ }
410
+ try { this.sh.stdin.write(line + '\n') } catch (e) {
411
+ this.log('写入失败: ' + e.message)
412
+ return false
413
+ }
414
+ return true
415
+ }
416
+
417
+ tap (x, y) {
418
+ const p = this.toPhysical(x, y)
419
+ this._cmd(`input tap ${p.x} ${p.y}`)
420
+ }
421
+
422
+ /**
423
+ * 滑动。
424
+ *
425
+ * adb 的 input swipe 支持时长参数,系统自己插值中间帧,
426
+ * 比逐个 move 去喂要稳得多(后者在持久 shell 里会被
427
+ * 命令队列拖慢,反而更卡)。
428
+ */
429
+ swipe (x1, y1, x2, y2, ms) {
430
+ const a = this.toPhysical(x1, y1)
431
+ const b = this.toPhysical(x2, y2)
432
+ const dur = Math.max(40, Math.min(2000, Math.round(ms || 200)))
433
+ this._cmd(`input swipe ${a.x} ${a.y} ${b.x} ${b.y} ${dur}`)
434
+ }
435
+
436
+ /** 长按:起点终点相同的 swipe */
437
+ longPress (x, y, ms) {
438
+ const p = this.toPhysical(x, y)
439
+ const dur = Math.max(400, Math.min(3000, Math.round(ms || 650)))
440
+ this._cmd(`input swipe ${p.x} ${p.y} ${p.x} ${p.y} ${dur}`)
441
+ }
442
+
443
+ key (code) {
444
+ this._cmd(`input keyevent ${code}`)
445
+ }
446
+
447
+ /**
448
+ * 输入文字。
449
+ *
450
+ * input text 不支持中文(非 ASCII 会丢),也不支持空格(要写成 %s)。
451
+ * 这里做空格转义;中文直接拒绝并提示,避免用户以为输入了实际没进去。
452
+ */
453
+ text (str) {
454
+ if (!str) return
455
+ if (!/^[\x20-\x7E]*$/.test(str)) {
456
+ this.log('adb 只能输入英文数字和符号,中文请用手机输入法')
457
+ return
458
+ }
459
+ this._cmd('input text ' + str.replace(/ /g, '%s').replace(/([&|;<>()$`\\"'])/g, '\\$1'))
460
+ }
461
+
462
+ /** 滚动:用短距离 swipe 模拟 */
463
+ scroll (x, y, hscroll, vscroll) {
464
+ const p = this.toPhysical(x, y)
465
+ const stepY = Math.round(this.physH * 0.15) * (vscroll > 0 ? 1 : -1)
466
+ this._cmd(`input swipe ${p.x} ${p.y - stepY / 2} ${p.x} ${p.y + stepY / 2} 150`)
467
+ }
468
+ }
469
+
470
+ module.exports = { AdbShellControl, DeviceWatcher }
Binary file
Binary file
Binary file
Binary file
Binary file
package/runtime/au.js ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * AU(Access Unit)组装器 —— 把「多 slice 组成的一帧」正确还原成一帧。
3
+ *
4
+ * 为什么必须有这个:
5
+ * H.264 允许把一帧画面切成多个 slice 分别编码(x264 的 `slices` 参数,
6
+ * 手机硬编码器为了降延迟常开 4~17 片)。这些 slice 共享同一个时间戳,
7
+ * 合起来才是一帧完整画面。
8
+ *
9
+ * 如果按「一个 NAL = 一帧」喂给 WebCodecs,解码器会收到半个画面,
10
+ * 表现为:第 1 帧(IDR)能解出来,第 2 帧立刻 `Decoding error`,
11
+ * 之后解码器直接进入 closed 状态,画面永久冻结。
12
+ *
13
+ * 实测:476×1080 的视频被切成 17 片,30600 个 NAL 其实只有 1800 帧。
14
+ *
15
+ * 切分依据(按 H.264 规范,不靠时间戳):
16
+ * 1. first_mb_in_slice === 0 且已有累积 slice → 新的一帧开始
17
+ * 2. 遇到 AUD(9) / SPS(7) / PPS(8) / SEI(6) → 上一帧结束
18
+ * 3. 帧类型变化(IDR ↔ 非 IDR)→ 新的一帧
19
+ * 4. finish() 时把剩下的吐出来
20
+ */
21
+
22
+ /**
23
+ * 读 slice header 里的 first_mb_in_slice(第一个指数哥伦布码)。
24
+ * @returns {number} 0 表示这是新一帧的第一个 slice
25
+ */
26
+ function firstMbInSlice (nal) {
27
+ // nal[0] 是 NAL header,从 nal[1] 的 bit 0 开始
28
+ let pos = 8
29
+ const getBit = () => {
30
+ const byte = nal[pos >> 3]
31
+ if (byte === undefined) return 0
32
+ const b = (byte >> (7 - (pos & 7))) & 1
33
+ pos++
34
+ return b
35
+ }
36
+ // 指数哥伦布:数前导 0,然后读出 (zeros) 位
37
+ let zeros = 0
38
+ while (getBit() === 0 && zeros < 32) zeros++
39
+ if (zeros === 0) return 0
40
+ let v = 0
41
+ for (let i = 0; i < zeros; i++) v = (v << 1) | getBit()
42
+ return (1 << zeros) - 1 + v
43
+ }
44
+
45
+ class AuAssembler {
46
+ constructor () {
47
+ this.pendingSlices = []
48
+ this.pendingPrefix = [] // SPS/PPS/SEI,跟着下一个 AU 走
49
+ this.hasIdr = false
50
+ this.maxSlices = 512 // 防御:异常数据不要把内存吃光
51
+ }
52
+
53
+ /**
54
+ * 喂一个 NAL。
55
+ * @param {Buffer|Uint8Array} nal 不含起始码的 NAL
56
+ * @returns {Array<{nals: Buffer[], key: boolean}>} 已完成的 AU
57
+ */
58
+ push (nal) {
59
+ if (!nal || !nal.length) return []
60
+ const t = nal[0] & 0x1f
61
+ const done = []
62
+
63
+ const flush = () => {
64
+ if (!this.pendingSlices.length) return
65
+ done.push({ nals: this.pendingSlices, key: this.hasIdr })
66
+ this.pendingSlices = []
67
+ this.hasIdr = false
68
+ }
69
+
70
+ // AUD:显式的一帧边界,AUD 自身丢弃
71
+ if (t === 9) {
72
+ flush()
73
+ return done
74
+ }
75
+
76
+ // 参数集 / SEI:已累积 slice 则上一帧结束
77
+ if (t === 7 || t === 8 || t === 6) {
78
+ flush()
79
+ if (this.pendingPrefix.length < 16) this.pendingPrefix.push(nal)
80
+ return done
81
+ }
82
+
83
+ // slice(1=非IDR, 2=分区A, 5=IDR)
84
+ if (t === 1 || t === 2 || t === 5) {
85
+ const firstMb = firstMbInSlice(nal)
86
+ if (this.pendingSlices.length && firstMb === 0) flush()
87
+ // 类型翻转也算新帧(IDR 之后跟非 IDR)
88
+ if (this.pendingSlices.length && this.hasIdr && t !== 5) flush()
89
+ if (this.pendingSlices.length >= this.maxSlices) flush()
90
+
91
+ this.pendingSlices.push(nal)
92
+ if (t === 5) this.hasIdr = true
93
+ return done
94
+ }
95
+
96
+ // 其他类型(数据分区等)忽略
97
+ return done
98
+ }
99
+
100
+ /** 收尾:把还没吐出的 AU 交出来 */
101
+ finish () {
102
+ const done = []
103
+ if (this.pendingSlices.length) {
104
+ done.push({ nals: this.pendingSlices, key: this.hasIdr })
105
+ this.pendingSlices = []
106
+ this.hasIdr = false
107
+ }
108
+ return done
109
+ }
110
+
111
+ reset () {
112
+ this.pendingSlices = []
113
+ this.pendingPrefix = []
114
+ this.hasIdr = false
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 把 AU 里的多个 slice 拼成一段 Annex-B(带起始码)。
120
+ * @param {Array<{nals: Buffer[]}>} au
121
+ */
122
+ function auToAnnexB (au) {
123
+ const parts = []
124
+ for (const nal of au.nals) {
125
+ parts.push(Buffer.from([0, 0, 0, 1]))
126
+ parts.push(Buffer.isBuffer(nal) ? nal : Buffer.from(nal))
127
+ }
128
+ return Buffer.concat(parts)
129
+ }
130
+
131
+ module.exports = { AuAssembler, auToAnnexB, firstMbInSlice }