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,619 @@
1
+ /**
2
+ * scrcpy 采集引擎 —— 命名管道 + MKV 流式解析。
3
+ *
4
+ * ══════════ 为什么换掉 APK ══════════
5
+ *
6
+ * 我们的 App 用 MediaProjection + createVirtualDisplay 采集,
7
+ * 在这台华为 Pura 70 Pro(HarmonyOS 4.2)上被系统限流到 4fps。
8
+ * 同一设备上 scrcpy.exe 用 Android 12 的 SurfaceControl 路径,
9
+ * 实测稳定 50~80fps —— 系统给两条 API 的合成优先级不同,
10
+ * 不是参数能调的(官方 scrcpy-server 在我们的连接方式下也只有 0.1fps)。
11
+ *
12
+ * ══════════ 为什么用命名管道 ══════════
13
+ *
14
+ * 最初让 scrcpy 录到 mkv 文件、我们再增量读。Windows 上行不通:
15
+ * scrcpy 用稀疏文件 + 大缓冲写入,Node 的 statSync 一直返回
16
+ * size=0(PowerShell 也是),只有 cmd dir 能看到 139GB 的逻辑大小,
17
+ * 实际数据憋在系统缓存里读不到 —— 表现为「文件 2.3MB 但一帧解析不出来」。
18
+ *
19
+ * 命名管道彻底绕开文件系统:scrcpy 直接往管道写,我们边收边解析,
20
+ * 零文件 IO、零缓冲延迟,也不用清理临时文件。
21
+ *
22
+ * ══════════ 数据通路 ══════════
23
+ *
24
+ * scrcpy.exe --record \\.\pipe\miniwin-stream --record-format mkv
25
+ * ↓ (管道字节流,约 400KB/s)
26
+ * net.createServer 接收
27
+ * ↓ reader.push(chunk)
28
+ * MkvReader 流式 EBML 解析
29
+ * ↓ SimpleBlock → AVCC 帧(4 字节长度前缀)
30
+ * onFrame(buf, ptsMs, isKey)
31
+ * ↓
32
+ * WebCodecs VideoDecoder
33
+ */
34
+
35
+ const net = require('node:net')
36
+ const { spawn } = require('node:child_process')
37
+ const { MkvReader } = require('./mkv-reader.js')
38
+
39
+ const PIPE_NAME = `\\\\.\\pipe\\miniwin-stream-${process.pid}`
40
+
41
+ class ScrcpyCapture {
42
+ /**
43
+ * @param {object} o
44
+ * @param {string} o.scrcpy scrcpy.exe 路径
45
+ * @param {string} [o.serial] 设备序列号
46
+ * @param {number} [o.maxSize] 最长边像素
47
+ * @param {string} [o.bitRate] 如 '8M'
48
+ * @param {number} [o.maxFps]
49
+ */
50
+ constructor (o) {
51
+ this.scrcpy = o.scrcpy
52
+ this.serial = o.serial || null
53
+ this.maxSize = o.maxSize || 720
54
+ this.bitRate = o.bitRate || '8M'
55
+ this.maxFps = o.maxFps || 30
56
+ /**
57
+ * adb.exe 路径 —— 用来清理手机侧的 scrcpy-server。
58
+ *
59
+ * scrcpy.exe 被 kill 之后,手机上那个 server 进程不会跟着死,
60
+ * 它继续占着 MediaCodec;下一次启动抢不到编码器就是
61
+ * 「管道连接超时」。做分辨率切换时这问题会稳定复现,
62
+ * 所以把 adb 传进来,让 _killStale 能一起清掉。
63
+ */
64
+ this.adb = o.adb || null
65
+
66
+ this.proc = null
67
+ this.server = null
68
+ this.sock = null
69
+ this.reader = null
70
+ this.running = false
71
+
72
+ this.onFrame = null
73
+ this.onLog = null
74
+ this.onReady = null
75
+ /** scrcpy 意外退出时回调(上层据此重连)*/
76
+ this.onExit = null
77
+ this.codecPrivate = null
78
+ this.width = 0
79
+ this.height = 0
80
+
81
+ this._startedAt = 0
82
+ this._frames = 0
83
+ /** 滑动窗口用的帧样本 [{t, n}],见 get fps */
84
+ this._fpsSamples = []
85
+ }
86
+
87
+ log (m) { if (this.onLog) this.onLog(m) }
88
+
89
+ /** 实时帧率(用于状态显示) */
90
+ /**
91
+ * 实时帧率 —— 滑动窗口,不是累计均值。
92
+ *
93
+ * ── 为什么必须用滑动窗口 ──
94
+ *
95
+ * 原来写的是 `frames / (now - startedAt)`,也就是「从启动到现在的
96
+ * 平均帧率」。这个值有两个致命问题:
97
+ *
98
+ * ① 启动阶段的空窗被永久计入
99
+ * scrcpy 要 push server(约 0.3s)+ 等首帧(可能 5~10s),
100
+ * 这段时间 frames=0。假设等首帧花了 8 秒、之后稳定 60fps,
101
+ * 累计均值要好几分钟才能爬回 22 以上 —— 而自适应降档判的是
102
+ * 「连续 5 秒 < 22」,于是刚启动就白降一档。
103
+ *
104
+ * ② 抹平瞬时抖动
105
+ * 某一秒掉到 15fps,累计均值几乎不动,看不出问题;
106
+ * 反过来某一秒正常,均值也升不上去。两头都不准。
107
+ *
108
+ * 现在:维护最近 2 秒的帧计数(滑动窗口),反映真实瞬时帧率。
109
+ * 窗口取 2 秒而不是 1 秒 —— 静止画面下编码器会主动降到 15~20fps
110
+ * 省电,1 秒窗口的抖动太大,2 秒能滤掉这种正常波动。
111
+ */
112
+ get fps () {
113
+ if (!this._startedAt) return 0
114
+ const now = Date.now()
115
+ const WINDOW = 2000
116
+ // 丢弃窗口外的样本
117
+ while (this._fpsSamples.length && now - this._fpsSamples[0].t > WINDOW) {
118
+ this._fpsSamples.shift()
119
+ }
120
+ if (!this._fpsSamples.length) return 0
121
+ const total = this._fpsSamples.reduce((a, s) => a + s.n, 0)
122
+ /**
123
+ * 分母用「窗口内实际跨度」而不是「到现在的跨度」。
124
+ *
125
+ * 踩过的坑:一开始写的是 now - samples[0].t。但最新的样本桶
126
+ * 可能已经是 250ms 前的了(那段没有新帧),于是
127
+ * 「n 帧 / 过长的跨度」把帧率算低;
128
+ * 反过来如果桶刚好新鲜,跨度又偏短,帧率偏高(实测 60fps
129
+ * 被算成 67fps,误差 12%)。
130
+ *
131
+ * 正确做法:跨度取「首样本到末样本 + 一个桶宽」——
132
+ * 末桶里的帧发生在这 250ms 内,算进去才对。
133
+ */
134
+ const firstT = this._fpsSamples[0].t
135
+ const lastT = this._fpsSamples[this._fpsSamples.length - 1].t
136
+ const span = Math.max(250, (lastT - firstT) + 250)
137
+ return total / (span / 1000)
138
+ }
139
+
140
+ /** 累加一个帧样本(由 onFrame 调用) */
141
+ _tickFps () {
142
+ const now = Date.now()
143
+ const last = this._fpsSamples[this._fpsSamples.length - 1]
144
+ // 每 250ms 归一个桶,避免每帧都 push 对象
145
+ if (last && now - last.t < 250) last.n++
146
+ else this._fpsSamples.push({ t: now, n: 1 })
147
+ // 兜底:样本数组不会无限增长
148
+ if (this._fpsSamples.length > 40) this._fpsSamples.shift()
149
+ }
150
+
151
+ /**
152
+ * ══════════ 启动采集(带一次自动重试)══════════
153
+ *
154
+ * 用户的投诉:「怎么老是第一次启动失败,点一下重连才好」。
155
+ *
156
+ * 根因不是参数错,而是**手机侧残留**:
157
+ * 上一次会话的 scrcpy-server 被强杀后,MediaCodec 归还编码器是异步的
158
+ * (实测 500~1000ms,卡在 native 层时更久)。如果我们紧接着启动,
159
+ * 新 server 抢不到硬编码器 → 一个字节都不写 → 35 秒后判定
160
+ * 「管道连接超时」。而这时手动重试一次,编码器已经空出来了,立刻成功。
161
+ *
162
+ * 所以这里不在上层反复点,而是在采集层自己补一次:
163
+ * 首次超时 → 清手机侧残留 → 等 1.2 秒(给 MediaCodec 归还时间)→ 再试一次。
164
+ *
165
+ * 只对「管道连接超时」重试 —— 设备没插、没授权这类错误重试一百次也没用。
166
+ */
167
+ async start () {
168
+ if (this.running) return { ok: true }
169
+
170
+ let r = await this._startOnce()
171
+ if (r.ok) return r
172
+
173
+ if (!/管道连接超时/.test(r.error || '')) return r
174
+
175
+ this.log('首次启动失败(' + r.error + '),清理手机侧残留后重试一次')
176
+ try { await this._killPhoneServer() } catch {}
177
+ await new Promise(res => setTimeout(res, 1200))
178
+
179
+ r = await this._startOnce()
180
+ if (r.ok) {
181
+ this.log('重试成功')
182
+ } else {
183
+ this.log('重试仍失败:' + (r.error || ''))
184
+ }
185
+ return r
186
+ }
187
+
188
+ async _startOnce () {
189
+ if (this.running) return { ok: true }
190
+ this._sawData = false
191
+ try {
192
+ /**
193
+ * 清掉上一次会话残留的 scrcpy 进程。
194
+ *
195
+ * 异常退出(崩溃、被强杀、调试中断)会留下孤儿进程,
196
+ * 它们继续占着设备的编码器,而且 —— 如果旧版本用的是
197
+ * --no-playback 而不是 --no-window —— 还会在屏幕上留下
198
+ * 一个空的 scrcpy 窗口。
199
+ *
200
+ * 这里按「命令行里带我们的管道名前缀」精确匹配,
201
+ * 不会误杀用户自己开的 scrcpy。
202
+ */
203
+ await this._killStale()
204
+
205
+ /**
206
+ * ══════════ 管道名必须每次都不一样 ══════════
207
+ *
208
+ * 踩过的坑:原来写的是 `miniwin-stream-${process.pid}` ——
209
+ * 同一个进程内「降档重启」时 pid 不变,管道名也不变。
210
+ * 而 stop() 里 server.close() 是异步的,句柄要等事件循环
211
+ * 转一圈才真正释放。紧接着的 start() 立刻 listen 同一个名字:
212
+ *
213
+ * listen EADDRINUSE: address already in use
214
+ * \\.\pipe\miniwin-stream-106080
215
+ *
216
+ * 结果是「重开迷你窗失败」,日志里刷几十条,得手动杀进程才好。
217
+ *
218
+ * 现在加一个自增序号:同一个进程内每次启动都是新名字,
219
+ * 旧管道的释放和新管道的创建彻底解耦。序号只用于管道,
220
+ * 不影响 _killStale 的匹配(它只看前缀)。
221
+ */
222
+ this._seq = (this._seq || 0) + 1
223
+ this.pipeName = `\\\\.\\pipe\\miniwin-stream-${process.pid}-${this._seq}`
224
+
225
+ // 1. 建管道,等 scrcpy 连上
226
+ const pipeReady = this._createPipe()
227
+
228
+ // 2. 起 scrcpy
229
+ const args = [
230
+ /**
231
+ * --no-window 必须加,不能只用 --no-playback。
232
+ *
233
+ * 踩过的坑:以为 --no-playback 就等于「不要窗口」,结果
234
+ * scrcpy 照样创建了一个标题为设备名的空窗口,里面显示它
235
+ * 自带的 Android 图标占位图 —— 用户看到屏幕上莫名多出
236
+ * 一个绿机器人窗口,不知道哪来的。
237
+ *
238
+ * --no-window 才是「完全不建窗口」,它同时隐含
239
+ * --no-video-playback。我们只要它往管道里录流,
240
+ * 窗口纯属多余。
241
+ */
242
+ '--no-window',
243
+ '--no-audio',
244
+ '--record', this.pipeName,
245
+ '--record-format', 'mkv',
246
+ '--max-size', String(this.maxSize),
247
+ '--video-bit-rate', this.bitRate,
248
+ '--max-fps', String(this.maxFps),
249
+ /**
250
+ * I 帧间隔缩到 1 秒(默认 2 秒)。
251
+ *
252
+ * 意义全在「丢帧后的恢复速度」上:
253
+ * 我们的背压策略是一丢帧就丢弃后续所有 P 帧、等下一个 IDR
254
+ * (因为 P 帧参考链断了,硬解只会得到花屏)。
255
+ * 所以 IDR 来得越快,画面恢复越快:
256
+ *
257
+ * 默认 2 秒 → 最长定格 2 秒
258
+ * 改成 1 秒 → 最长定格 1 秒
259
+ *
260
+ * 代价是码率略升(多一倍关键帧),实测在 16M 下完全看不出
261
+ * 差别 —— 换 1 秒的恢复时间很值。
262
+ *
263
+ * 这两个参数名是 Android MediaFormat 的 key,
264
+ * 通过 scrcpy 的 --video-codec-options 透传给设备端编码器。
265
+ */
266
+ '--video-codec-options', 'i-frame-interval=1'
267
+ ]
268
+ if (this.serial) args.unshift('--serial', this.serial)
269
+
270
+ this.log('启动 scrcpy(管道输出)')
271
+ this.log('管道名=' + JSON.stringify(this.pipeName))
272
+ this.log('参数=' + JSON.stringify(args.slice(0, 8)))
273
+ this.proc = spawn(this.scrcpy, args, { windowsHide: true })
274
+
275
+ /**
276
+ * 诊断:spawn 后立即看进程是否真的起来了。
277
+ *
278
+ * 重连场景下曾经出现「日志停在『管道就绪』,但 scrcpy 进程不存在」,
279
+ * 而 stderr 里什么都没打 —— 说明进程可能在 spawn 阶段就失败了,
280
+ * 或者启动后极短时间内被外部杀掉。
281
+ *
282
+ * 这两行能区分「没启动」和「启动后被杀了」。
283
+ */
284
+ if (this.proc.pid) {
285
+ this.log(`scrcpy 进程已创建 pid=${this.proc.pid}`)
286
+ } else {
287
+ this.log('scrcpy 进程创建失败(pid 为空)')
288
+ }
289
+ this.proc.on('spawn', () => this.log(`scrcpy spawn 事件 pid=${this.proc && this.proc.pid}`))
290
+ this.proc.stderr.on('data', d => {
291
+ const s = d.toString().trim()
292
+ if (!s) return
293
+ // 只报关键信息,避免刷屏
294
+ if (/error|warn|fail/i.test(s)) this.log('[scrcpy] ' + s.slice(0, 160))
295
+ })
296
+ /**
297
+ * scrcpy 退出 —— 这里必须上报,不能只是置个 flag。
298
+ *
299
+ * ── 踩过的坑(用户原话:「我拔掉 usb 画面直接断开了」)──
300
+ *
301
+ * 原来的实现:
302
+ * this.proc.on('exit', (code) => {
303
+ * if (this.running) this.log(`scrcpy 退出 (code=${code})`)
304
+ * this.running = false ← 就这样,没了
305
+ * })
306
+ *
307
+ * 拔掉 USB 后 adb 通道消失 → scrcpy 打印 Device disconnected
308
+ * → 进程退出 → 这里把 running 置 false → **然后什么都发生了**。
309
+ * 画面停在最后一帧,看起来像卡死,用户只能手动点重连。
310
+ *
311
+ * 现在改成回调 onExit,让上层(main.js)去决定是否重连 ——
312
+ * 采集层不该自己管重连策略(它不知道设备列表、不知道用户意图)。
313
+ */
314
+ this.proc.on('exit', (code) => {
315
+ const wasRunning = this.running
316
+ this.running = false
317
+ if (wasRunning) {
318
+ this.log(`scrcpy 退出 (code=${code})`)
319
+ if (this.onExit) {
320
+ try { this.onExit(code) } catch {}
321
+ }
322
+ }
323
+ })
324
+
325
+ // 3. 等管道连接 + 首帧
326
+ const ok = await pipeReady
327
+ if (!ok) {
328
+ await this.stop()
329
+ return { ok: false, error: '管道连接超时(检查设备是否连接)' }
330
+ }
331
+
332
+ this.running = true
333
+ this._startedAt = Date.now()
334
+ // 重连/换档时清空帧样本,否则滑动窗口里还留着上一次的桶
335
+ this._fpsSamples = []
336
+ this.log('采集已启动(命名管道 + MKV 流式解析)')
337
+ return { ok: true }
338
+ } catch (e) {
339
+ this.log('启动失败: ' + e.message)
340
+ await this.stop()
341
+ return { ok: false, error: String(e.message || e) }
342
+ }
343
+ }
344
+
345
+ /**
346
+ * 杀掉本项目残留的 scrcpy 进程 **+ 手机侧的 scrcpy-server**。
347
+ *
348
+ * ── 为什么必须连手机侧一起清 ──
349
+ *
350
+ * scrcpy 的架构是:PC 上的 scrcpy.exe 通过 adb 把 scrcpy-server
351
+ * 推到手机 /data/local/tmp/,用 app_process 跑起来,再由 server
352
+ * 把画面编码后送回来。
353
+ *
354
+ * PC 侧进程被 kill 之后,**手机侧的 server 进程不会跟着死**。
355
+ * 它继续占着 MediaCodec 硬编码器;下一次启动时新的 server 抢不到
356
+ * 编码器,表现就是:
357
+ *
358
+ * [error] 启动失败: 管道连接超时(检查设备是否连接)
359
+ *
360
+ * 而 adb devices 明明是好着的。这就是「连续切分辨率时后几档
361
+ * 必然失败」的根因 —— 做分辨率切换功能时这里是硬门槛。
362
+ *
363
+ * 修法:清理 PC 侧进程之后,再通过 adb 把手机上的
364
+ * com.genymobile.scrcpy.Server 一起 pkill 掉,并等一下让它彻底退出。
365
+ */
366
+ async _killStale () {
367
+ try {
368
+ const { execFileSync } = require('node:child_process')
369
+ const out = execFileSync('powershell', [
370
+ '-NoProfile', '-NonInteractive', '-Command',
371
+ "Get-CimInstance Win32_Process -Filter \"Name='scrcpy.exe'\" " +
372
+ "| ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }"
373
+ ], { encoding: 'utf8', timeout: 8000, windowsHide: true })
374
+
375
+ const pids = []
376
+ for (const line of out.split(/\r?\n/)) {
377
+ const m = line.match(/^\s*(\d+)\t(.*)$/)
378
+ if (!m) continue
379
+ const pid = parseInt(m[1], 10)
380
+ if (!(pid > 0) || pid === process.pid) continue
381
+ // 只杀我们自己的(命令行里带 miniwin-stream 管道名)
382
+ if (!/miniwin-stream/.test(m[2])) continue
383
+ pids.push(pid)
384
+ }
385
+
386
+ for (const pid of pids) {
387
+ try {
388
+ process.kill(pid, 'SIGKILL')
389
+ this.log(`清理残留 scrcpy 进程 ${pid}`)
390
+ } catch {}
391
+ }
392
+ if (pids.length) await new Promise(r => setTimeout(r, 600))
393
+ } catch (e) {
394
+ this.log('残留进程清理失败(不影响本次启动): ' + (e.message || e))
395
+ }
396
+
397
+ await this._killPhoneServer()
398
+ }
399
+
400
+ /**
401
+ * 清掉手机侧的 scrcpy-server。
402
+ *
403
+ * ── 为什么这一步这么讲究 ──
404
+ *
405
+ * scrcpy 的 server 是个 app_process 起的 Java 进程,它持有
406
+ * MediaCodec 硬编码器。PC 侧被强杀后它变成孤儿,继续占着编码器,
407
+ * 新 server 抢不到就表现为「管道连接超时」——而 adb devices 好着。
408
+ *
409
+ * ── 三个必须做对的细节 ──
410
+ *
411
+ * ① pkill -f 用 SIGTERM,Java 进程不一定响应
412
+ * 必须 -9 强杀。之前只写 pkill -f,对卡在 native 层(等编码器
413
+ * 的 surface)的进程经常杀不掉。
414
+ *
415
+ * ② 杀完要**验证**,不能只 sleep 一下就当它死了
416
+ * 所以循环 3 次:杀 → 查 → 还在就再杀,每次间隔递增。
417
+ *
418
+ * ③ MediaCodec 的释放是异步的
419
+ * kill 返回 ≠ 编码器已归还。实测需要等 500~1000ms,
420
+ * 只等 400ms 时偶发「编码器已占用」。
421
+ */
422
+ async _killPhoneServer () {
423
+ if (!this.adb || !this.serial) return
424
+ const { execFile } = require('node:child_process')
425
+ const run = (args) => new Promise(resolve => {
426
+ execFile(this.adb, args, { timeout: 10000, windowsHide: true },
427
+ (err, stdout, stderr) => resolve({ err, out: String(stdout || '') + String(stderr || '') }))
428
+ })
429
+
430
+ const countAlive = async () => {
431
+ const r = await run([
432
+ '-s', this.serial, 'shell',
433
+ 'ps -A 2>/dev/null | grep -c "[c]om.genymobile.scrcpy" || echo 0'
434
+ ])
435
+ const m = r.out.match(/(\d+)\s*$/)
436
+ return m ? parseInt(m[1], 10) : 0
437
+ }
438
+
439
+ try {
440
+ let alive = await countAlive()
441
+ if (alive === 0) {
442
+ // 干净,仍然给编码器一点归还时间
443
+ await new Promise(r => setTimeout(r, 250))
444
+ return
445
+ }
446
+
447
+ this.log(`手机侧有 ${alive} 个 scrcpy-server 残留,正在清理`)
448
+
449
+ for (let attempt = 0; attempt < 3; attempt++) {
450
+ await run([
451
+ '-s', this.serial, 'shell',
452
+ 'pkill -9 -f com.genymobile.scrcpy 2>/dev/null; ' +
453
+ 'pkill -9 -f "app_process.*scrcpy" 2>/dev/null; true'
454
+ ])
455
+ await new Promise(r => setTimeout(r, 400))
456
+ alive = await countAlive()
457
+ if (alive === 0) break
458
+ this.log(`第 ${attempt + 1} 次清理后仍有 ${alive} 个,重试`)
459
+ await new Promise(r => setTimeout(r, 400 * (attempt + 1)))
460
+ }
461
+
462
+ if (alive > 0) {
463
+ this.log(`⚠ 手机侧仍有 ${alive} 个 scrcpy-server 无法清理,本次可能启动失败`)
464
+ } else {
465
+ this.log('手机侧已清空')
466
+ }
467
+ } catch {
468
+ // adb 不可用就算了,让后面的 start 自己报错(错误信息更具体)
469
+ }
470
+
471
+ // ③ 给 MediaCodec 归还硬编码器的时间
472
+ await new Promise(r => setTimeout(r, 700))
473
+ }
474
+
475
+ /** 创建命名管道服务器,返回「拿到首个数据块」的 Promise */
476
+ _createPipe () {
477
+ return new Promise((resolve) => {
478
+ let settled = false
479
+ let done = (v) => { if (!settled) { settled = true; resolve(v) } }
480
+
481
+ this.reader = new MkvReader()
482
+ this.reader.onLog = (m) => this.log('[mkv] ' + m)
483
+ this.reader.onSample = (buf, ptsMs, isKey) => {
484
+ // 首次拿到 CodecPrivate → 通知上层 configure
485
+ if (!this.codecPrivate && this.reader.codecPrivate) {
486
+ this.codecPrivate = this.reader.codecPrivate
487
+ this.log(`CodecPrivate ${this.codecPrivate.length}B`)
488
+ if (this.onReady) {
489
+ this.onReady({
490
+ codecPrivate: this.codecPrivate,
491
+ width: this.width,
492
+ height: this.height
493
+ })
494
+ }
495
+ }
496
+ this._frames++
497
+ this._tickFps()
498
+ if (this.onFrame) this.onFrame(buf, ptsMs, isKey)
499
+ }
500
+
501
+ this.server = net.createServer(sock => {
502
+ this.sock = sock
503
+ sock.on('data', chunk => {
504
+ try { this.reader.push(chunk) } catch (e) {
505
+ this.log('解析异常: ' + e.message)
506
+ }
507
+ this._sawData = true
508
+ done(true) // 收到数据就算连上了
509
+ })
510
+ sock.on('error', e => this.log('管道错误: ' + e.message))
511
+ sock.on('close', () => {
512
+ if (this.running) this.log('管道关闭')
513
+ })
514
+ })
515
+
516
+ this.server.once('error', (e) => {
517
+ this.log('管道创建失败: ' + e.message)
518
+ done(false)
519
+ })
520
+
521
+ this.server.listen(this.pipeName, () => {
522
+ this.log('管道已就绪,等 scrcpy 连接')
523
+ })
524
+
525
+ /**
526
+ * ══════════ 超时保护:35 秒,且进程死了就立刻放弃 ══════════
527
+ *
528
+ * 为什么从 20 秒提到 35 秒:
529
+ *
530
+ * 实测这台手机的 scrcpy 首块数据要等 10~14 秒才写出来
531
+ * (它是大缓冲批量落盘,不是流式)。加上 adb push server
532
+ * 约 2~4 秒、server 启动 1~2 秒,20 秒的红线经常不够 ——
533
+ * 表现就是「管道连接超时」但设备明明在线、手动跑又正常。
534
+ *
535
+ * 另外加了「进程存活检查」:如果 scrcpy 进程已经退出,
536
+ * 没必要傻等满 35 秒,直接判失败并重试。
537
+ */
538
+ const HARD_TIMEOUT = 35000
539
+ const timer = setTimeout(() => done(false), HARD_TIMEOUT)
540
+
541
+ /**
542
+ * 进程死了就立刻放弃等待。
543
+ *
544
+ * ⚠️ 必须跳过「this.proc 还没赋值」的阶段:
545
+ * _createPipe() 在 spawn 之前就被调用,那时 this.proc 是 null。
546
+ * 早期版本没判这个,于是 500ms 后立刻判定「进程不存在」→
547
+ * 直接判失败,超时设多大都没用(实测 35 秒的设置 10 秒就失败)。
548
+ *
549
+ * 现在:只有当 proc 存在且确实退出过,才算失败。
550
+ */
551
+ /**
552
+ * ⚠️ 只检查「本次 spawn 出来的那个进程」。
553
+ *
554
+ * 踩过的坑(这次是真正的元凶):
555
+ * _createPipe() 是在 spawn 之前调用的,而 this.proc 此时
556
+ * 仍然指向**上一次会话的旧对象**(已经 exitCode !== null)。
557
+ * 于是 500ms 后这里立刻判定「进程已死」→ done(false) →
558
+ * 上层看到「管道连接超时」。
559
+ *
560
+ * 表现就是:手动跑 scrcpy 18 秒能出 543KB,主进程却
561
+ * 10 秒(其实是 0.5 秒)就报超时 —— 超时设 35 秒完全没用。
562
+ *
563
+ * 现在用 procAtCreate 快照:只认 spawn 之后的那个新进程。
564
+ */
565
+ const procAtCreate = this.proc
566
+ const procWatch = setInterval(() => {
567
+ const p = this.proc
568
+ if (!p) return // spawn 还没发生
569
+ if (p === procAtCreate && procAtCreate !== null) {
570
+ // 还是创建管道时那个旧进程 → 说明 spawn 尚未替换它,继续等
571
+ return
572
+ }
573
+ if (p.exitCode === null && !p.killed) return // 新进程还活着
574
+ clearInterval(procWatch)
575
+ done(this._sawData === true)
576
+ }, 500)
577
+
578
+ const origDone = done
579
+ done = (v) => {
580
+ clearTimeout(timer)
581
+ clearInterval(procWatch)
582
+ origDone(v)
583
+ }
584
+ })
585
+ }
586
+
587
+ async stop () {
588
+ this.running = false
589
+ try { if (this.sock) this.sock.destroy() } catch {}
590
+ this.sock = null
591
+ /**
592
+ * close() 之后要等 'close' 事件,句柄才算真的释放。
593
+ *
594
+ * Windows 命名管道被占用时不会立刻归还 —— 只调 close() 不 await,
595
+ * 紧接着 listen 同一个名字就会 EADDRINUSE。虽然现在管道名带序号
596
+ * 已经不会再撞,但这里等一等能让「连续重启」的时序更干净,
597
+ * 也少一处在事件循环里飘着的句柄。
598
+ */
599
+ const srv = this.server
600
+ this.server = null
601
+ if (srv) {
602
+ try {
603
+ await new Promise((resolve) => {
604
+ let done = false
605
+ const fin = () => { if (!done) { done = true; resolve() } }
606
+ srv.once('close', fin)
607
+ srv.close(fin)
608
+ // 兜底:万一 'close' 不触发(句柄已经烂掉),最多等 300ms
609
+ setTimeout(fin, 300)
610
+ })
611
+ } catch {}
612
+ }
613
+ try { if (this.proc) this.proc.kill() } catch {}
614
+ this.proc = null
615
+ this.reader = null
616
+ }
617
+ }
618
+
619
+ module.exports = { ScrcpyCapture }