dsh-miniwin 0.0.0-stage → 0.3.0

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 (49) hide show
  1. package/LICENSE +28 -0
  2. package/README.en.md +83 -0
  3. package/README.md +304 -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/audio-router.js +175 -0
  20. package/runtime/avcc.js +186 -0
  21. package/runtime/device.js +307 -0
  22. package/runtime/main.js +3309 -0
  23. package/runtime/mkv-reader.js +326 -0
  24. package/runtime/package.json +5 -0
  25. package/runtime/preload.js +122 -0
  26. package/runtime/scrcpy-capture.js +623 -0
  27. package/runtime/streamer.js +192 -0
  28. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/AdbWinApi.dll +0 -0
  29. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/AdbWinUsbApi.dll +0 -0
  30. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/LICENSE.txt +204 -0
  31. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/SDL3.dll +0 -0
  32. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/adb.exe +0 -0
  33. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avcodec-63.dll +0 -0
  34. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avformat-63.dll +0 -0
  35. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/avutil-61.dll +0 -0
  36. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/disconnected.png +0 -0
  37. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/libusb-1.0.dll +0 -0
  38. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/open_a_terminal_here.bat +1 -0
  39. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy-noconsole.vbs +7 -0
  40. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy-server +0 -0
  41. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy.exe +0 -0
  42. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/scrcpy.png +0 -0
  43. package/runtime/tools/scrcpy/scrcpy-win64-v5.0.1/swresample-7.dll +0 -0
  44. package/runtime/ui.html +3166 -0
  45. package/runtime/usb-hotplug.js +194 -0
  46. package/runtime/wifi-adb-keeper.js +395 -0
  47. package/runtime/wifi-discovery.js +213 -0
  48. package/runtime/wifi-receiver.js +733 -0
  49. package/screenshots.json +5 -0
@@ -0,0 +1,733 @@
1
+ /* ── 代理绕过:本机与局域网请求不走代理 ──
2
+ *
3
+ * 用户开着本地代理时,Node 的 fetch/http 会读 HTTP_PROXY 环境变量,
4
+ * 把 127.0.0.1 和 172.31.* 的请求也转发给代理 —— 必然失败。
5
+ * 这里把回环和私有网段加入 NO_PROXY,保证本地链路直连。
6
+ */
7
+ ;(function () {
8
+ const KEEP = '127.0.0.1,localhost,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16'
9
+ process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',' + KEEP : KEEP
10
+ process.env.no_proxy = process.env.NO_PROXY
11
+ delete process.env.HTTP_PROXY
12
+ delete process.env.http_proxy
13
+ delete process.env.HTTPS_PROXY
14
+ delete process.env.https_proxy
15
+ delete process.env.ALL_PROXY
16
+ delete process.env.all_proxy
17
+ })()
18
+
19
+ /**
20
+ * WiFi 接收端:监听 TCP,接收手机 App 推来的 H.264(帧头协议见 StreamActivity),
21
+ * 转成本地 HTTP 轮询源,让 miniwin-stream 的窗口显示画面。
22
+ *
23
+ * 与真机 scrcpy 的关系:手机 App 编码出的就是 Annex-B AU(多 slice 已由
24
+ * 编码器组装好),帧头格式对齐 ScrcpyParser 期望的 stage,所以这里直接
25
+ * 复用 ScrcpyParser 解析 + frameToAvcc 转换 + 现有迷你窗渲染。
26
+ */
27
+ const http = require('http')
28
+ const net = require('net')
29
+ const { ScrcpyParser } = require('./streamer.js')
30
+ const { makeDescriptionFromConfig, frameToAvcc } = require('./avcc.js')
31
+ const { AuAssembler, auToAnnexB } = require('./au.js')
32
+
33
+ /**
34
+ * 端口约定:接收端 TCP = LAN 端口 + 1,HTTP = LAN 端口 + 2。
35
+ * deep-link 路由(/deep-link)用同一公式算出给 App 的端口,两边必须一致。
36
+ * 命令行 --lan <端口> 时自动对齐;否则用默认 27190/27191。
37
+ */
38
+ let LISTEN_PORT = Number(process.argv[2] || 27190)
39
+ let HTTP_PORT = Number(process.argv[3] || 27191)
40
+ const lanIdx = process.argv.indexOf('--lan')
41
+ if (lanIdx >= 0 && process.argv[lanIdx + 1]) {
42
+ const lanPort = Number(process.argv[lanIdx + 1])
43
+ if (lanPort > 0) {
44
+ LISTEN_PORT = lanPort + 1
45
+ HTTP_PORT = lanPort + 2
46
+ }
47
+ }
48
+ /* 2.0:命令行传 adb 路径与 server jar(供零 APK 配对页使用) */
49
+ let ADB_PATH = process.argv[4] || 'adb'
50
+ let SERVER_JAR = process.argv[5] || ''
51
+
52
+ const state = {
53
+ codecString: null,
54
+ description: null,
55
+ videoSize: null,
56
+ frames: 0,
57
+ dropped: 0,
58
+ lastFrame: null, // { data(Uint8Array), pts, key }
59
+ lastKey: null, // 最后一个 IDR,渲染层启动时补帧用
60
+ seq: 0, // 帧序列号,渲染层据此跳过重复帧
61
+ /**
62
+ * 待取帧队列。渲染层按 seq 顺序消费,保证 P 帧参考链完整。
63
+ * 详见 TCP 帧处理处的注释 —— 这是修花屏的关键结构。
64
+ */
65
+ queue: [],
66
+ /**
67
+ * 等待中的长轮询回调。
68
+ *
69
+ * /frames 在队列空时会把响应挂起,把「来帧了就叫我」这个回调存在这里。
70
+ * TCP 收到新帧时遍历唤醒,实现「零往返延迟」的推送效果。
71
+ */
72
+ waiters: [],
73
+
74
+ /* ---- 音频 ---- */
75
+ hasAudio: false,
76
+ audioConfig: null, // AudioSpecificConfig 原始字节
77
+ audioQueue: [],
78
+ audioWaiters: [],
79
+ audioFrames: 0,
80
+ /** 手机上报的音量(0..255)。音量键 = 电脑音量遥控器 */
81
+ phoneVolume: 0,
82
+ fps: 0,
83
+ connected: false,
84
+ startedAt: Date.now()
85
+ }
86
+
87
+ // ── TCP 接收:手机 App 推流到这里 ──
88
+ const tcpServer = net.createServer(sock => {
89
+ sock.setNoDelay(true)
90
+ state.connected = true
91
+ state.frames = 0
92
+ // 新连接从干净状态开始:旧队列里的帧属于上一路流,seq 也对不上
93
+ state.queue.length = 0
94
+ state.seq = 0
95
+ state.dropped = 0
96
+ state.lastFrame = null
97
+ state.lastKey = null
98
+ // 音频同样重置 —— 新连线的音频参数可能不同(换了设备/采样率)
99
+ state.audioQueue.length = 0
100
+ state.audioFrames = 0
101
+ state.audioConfig = null
102
+ state.hasAudio = false
103
+ console.log('[tcp] 手机已连接 ' + sock.remoteAddress)
104
+
105
+ const parser = new ScrcpyParser({ sendDummyByte: false, sendStreamMeta: false, sendDeviceMeta: false })
106
+ const auAsm = new AuAssembler()
107
+ let sawKey = false
108
+ let buf = Buffer.alloc(0)
109
+
110
+ sock.on('data', chunk => {
111
+ buf = Buffer.concat([buf, chunk])
112
+ // 12 字节帧头循环切
113
+ for (;;) {
114
+ if (buf.length < 12) break
115
+ const tag = buf.readBigUInt64BE(0)
116
+ const size = buf.readUInt32BE(8)
117
+ if (buf.length < 12 + size) break
118
+ const payload = buf.subarray(12, 12 + size)
119
+ buf = buf.subarray(12 + size)
120
+
121
+ const isConfig = (tag & 0x4000000000000000n) !== 0n
122
+ const isKey = (tag & 0x8000000000000000n) !== 0n
123
+ /**
124
+ * 音频标志。
125
+ *
126
+ * App 把视频和音频复用同一条 TCP(省端口,也天然对齐时间轴),
127
+ * 靠帧头 tag 里的这一位区分:置位 = AAC 音频,不置位 = H.264 视频。
128
+ *
129
+ * 音频帧不能走 frameToAvcc(那是 H.264 的 Annex-B → AVCC 转换),
130
+ * 也不参与关键帧/参考链逻辑,直接原样丢进音频队列。
131
+ */
132
+ const isAudio = (tag & 0x2000000000000000n) !== 0n
133
+ const pts = Number(tag & 0x1fffffffffffffffn) / 1000 // 纳秒 → 微秒
134
+
135
+ if (isAudio) {
136
+ if (isConfig) {
137
+ /**
138
+ * AudioSpecificConfig(AAC 解码器初始化参数)。
139
+ *
140
+ * 通常是 2 字节,包含 object type / 采样率索引 / 声道数。
141
+ * 渲染层用 WebCodecs 的 AudioDecoder 时需要它作为 description,
142
+ * 不给的话 configure 会失败或解出噪音。
143
+ */
144
+ state.audioConfig = Buffer.from(payload)
145
+ state.hasAudio = true
146
+ console.log('[tcp] 音频配置 ' + payload.length + ' 字节: ' +
147
+ Buffer.from(payload).toString('hex'))
148
+ continue
149
+ }
150
+
151
+ /**
152
+ * 音量控制消息:手机音量键 → 电脑音量。
153
+ *
154
+ * 特征是 size==1(AAC 帧都是几十字节起)。
155
+ * 1 字节负载 = 归一化音量 0..255。
156
+ *
157
+ * 不进音频队列(那会当成一帧 AAC 解出噪音),
158
+ * 存到 state.phoneVolume,渲染层通过 /meta 或
159
+ * 音量拉流响应头拿到后同步滑块。
160
+ */
161
+ if (payload.length === 1) {
162
+ state.phoneVolume = payload[0]
163
+ continue
164
+ }
165
+
166
+ state.hasAudio = true
167
+ state.audioFrames++
168
+ /**
169
+ * 音频队列 —— 保持很短。
170
+ *
171
+ * 音频对延迟极其敏感:队列里每积一帧就是 23ms 的延迟。
172
+ * 120 帧的旧上限 = 2.8 秒的延迟,完全不可接受。
173
+ *
174
+ * 现在压到 8 帧(约 185ms)。超过就丢最旧的 ——
175
+ * 音频丢一小段听感上是轻微「跳」一下,
176
+ * 比听到几秒前的声音好得多。
177
+ *
178
+ * 渲染端是长轮询(来帧就取),正常情况下队列始终接近空,
179
+ * 这个上限只是兜底。
180
+ */
181
+ state.audioQueue.push({ data: Buffer.from(payload), pts })
182
+ if (state.audioQueue.length > 8) {
183
+ state.audioQueue.splice(0, state.audioQueue.length - 8)
184
+ state.audioDropped = (state.audioDropped || 0) + 1
185
+ }
186
+ /**
187
+ * 唤醒挂起的拉流请求 —— 但延迟 35ms。
188
+ *
189
+ * 立刻唤醒的话队列里通常只有刚到的这 1 帧(23ms 音频),
190
+ * 渲染端一趟往返只拿走 1 帧,实测吞吐掉到 14 帧/秒
191
+ * (生产是 43)—— 一半以上的音频在传输层就被节奏差吃掉了。
192
+ *
193
+ * 延 35ms 给队列一个攒帧窗口(通常能攒 1~2 帧),
194
+ * 每批平均 2~3 帧,吞吐回升到 30+/s。
195
+ * 35ms 远小于渲染端 jitter buffer 的 90ms 缓冲,无感。
196
+ */
197
+ if (state.audioWaiters.length) {
198
+ setTimeout(() => {
199
+ const ws = state.audioWaiters.slice()
200
+ for (const w of ws) { try { w() } catch {} }
201
+ }, 35)
202
+ }
203
+ continue
204
+ }
205
+
206
+ if (isConfig) {
207
+ // App 的 codec config 是 SPS+PPS 的 Annex-B
208
+ const info = makeDescriptionFromConfig(payload)
209
+ if (info) {
210
+ state.codecString = info.codecString
211
+ state.description = info.description
212
+ console.log('[tcp] codec ' + info.codecString)
213
+ }
214
+ continue
215
+ }
216
+
217
+ // 普通帧:payload 是一个完整 AU(编码器已按 AU 输出)
218
+ const packed = frameToAvcc(payload)
219
+ if (!packed) continue
220
+ // 诊断:前 20 帧打印 key 标志
221
+ if (state.frames < 20) {
222
+ console.log('[tcp] 帧' + state.frames + ' key=' + packed.key +
223
+ ' nal0=' + (packed.data.length > 4 ? (packed.data[4] & 0x1f) : '?') +
224
+ ' len=' + packed.data.length)
225
+ }
226
+ if (!sawKey) {
227
+ if (!packed.key) {
228
+ // 关键帧判定兜底:AVCC 首个 NAL 类型 5 = IDR。
229
+ // 有些编码器(华为/海思)不置 BUFFER_FLAG_SYNC_FRAME,
230
+ // 只能靠 NAL 类型判断。
231
+ if (packed.data.length > 4 && (packed.data[4] & 0x1f) === 5) {
232
+ console.log('[tcp] 通过 NAL 类型识别到关键帧(编码器未置 SYNC 标志)')
233
+ packed.key = true
234
+ } else {
235
+ continue
236
+ }
237
+ }
238
+ sawKey = true
239
+ console.log('[tcp] 首个关键帧')
240
+ }
241
+ if (!state.videoSize) state.videoSize = { w: 720, h: 1600 }
242
+ state.frames++
243
+ // 用 NAL 类型判 IDR:AVCC 首 NAL(跳过 4 字节长度)type==5
244
+ const isIdr = packed.data.length > 4 && (packed.data[4] & 0x1f) === 5
245
+ const seq = ++state.seq
246
+ state.lastFrame = { data: packed.data, pts, key: isIdr, seq }
247
+
248
+ /**
249
+ * 帧队列 —— 修花屏的核心。
250
+ *
251
+ * 之前 /frame 只返回「最新那一帧」。渲染层每次轮询拿到的都是当前槽位,
252
+ * 轮询间隔一旦大于编码间隔,中间的 P 帧就被**整段跳过**。
253
+ *
254
+ * H.264 的 P 帧是帧间预测编码,必须按顺序解码:
255
+ * 丢了中间帧不是「卡一下」,而是参考图像全错 ——
256
+ * 屏幕上直接出现绿块、灰块、上一帧残影错位,也就是花屏。
257
+ *
258
+ * 所以这里改成有界队列,渲染层按 seq 顺序往后取,
259
+ * 只要它跟得上就一帧不丢,花屏自然消失。
260
+ *
261
+ * 队列上限 90 帧(30fps 下约 3 秒):正常延迟远低于此,
262
+ * 真的积压到上限说明渲染端已经跟不上了,丢掉最旧的并打标记,
263
+ * 让渲染层知道「参考链断了,必须等下一个 IDR」。
264
+ */
265
+ state.queue.push({ data: packed.data, pts, key: isIdr, seq })
266
+ if (state.queue.length > 90) {
267
+ state.queue.shift()
268
+ state.dropped++
269
+ }
270
+
271
+ /**
272
+ * 有新帧 → 立刻唤醒挂起的 /frames 请求。
273
+ *
274
+ * 这就是「推」而不是「拉」:渲染层不用每 16ms 空轮询一次,
275
+ * 而是一帧到达就马上拿到。省掉的是每个往返 3~8ms 的开销,
276
+ * 30fps 下相当于抢回 20% 的时间预算。
277
+ *
278
+ * 复制一份再遍历:回调里会自己从 waiters 里移除,直接遍历会跳过元素。
279
+ */
280
+ if (state.waiters.length) {
281
+ const ws = state.waiters.slice()
282
+ for (const w of ws) {
283
+ try { w() } catch {}
284
+ }
285
+ }
286
+ /**
287
+ * 单独保存最后一个 IDR。
288
+ *
289
+ * 渲染层 configure() 后必须先吃关键帧才能解码,而 /frame 只留最新一帧,
290
+ * 轮询极容易错过 2 秒才出现一次的 IDR —— 实测一直 decoded=0。
291
+ * 提供 /keyframe 让渲染层启动时先补一个关键帧。
292
+ */
293
+ if (isIdr) state.lastKey = { data: packed.data, pts, key: true, seq }
294
+ }
295
+ })
296
+
297
+ sock.on('close', () => { state.connected = false; console.log('[tcp] 断开') })
298
+ sock.on('error', e => console.log('[tcp] 错误: ' + e.message))
299
+ })
300
+
301
+ tcpServer.listen(LISTEN_PORT, '0.0.0.0', () => {
302
+ console.log('[tcp] 监听 0.0.0.0:' + LISTEN_PORT + '(手机 App 推流到这里)')
303
+ })
304
+
305
+ // ── HTTP:给迷你窗拉帧 ──
306
+ const httpServer = http.createServer((req, res) => {
307
+ res.setHeader('Access-Control-Allow-Origin', '*')
308
+ res.setHeader('Cache-Control', 'no-store')
309
+ const u = new URL(req.url, 'http://x')
310
+
311
+ if (u.pathname === '/config') {
312
+ res.writeHead(200, { 'Content-Type': 'application/json' })
313
+ res.end(JSON.stringify({
314
+ ok: true,
315
+ codecString: state.codecString,
316
+ description: state.description ? Array.from(state.description) : null,
317
+ videoSize: state.videoSize,
318
+ // 音频信息一起返回,渲染层可以据此决定要不要起音频链路
319
+ hasAudio: state.hasAudio,
320
+ audioConfigLen: state.audioConfig ? state.audioConfig.length : 0
321
+ }))
322
+ return
323
+ }
324
+
325
+ /**
326
+ * 批量取帧 —— 渲染层的唯一取帧入口。
327
+ *
328
+ * 一次返回队列里最多 N 帧(默认 12),按 seq 升序。
329
+ * 这样即使轮询是 60ms 一次、编码是 33ms 一帧,也能一次把中间攒的
330
+ * 两三帧全取走,P 帧参考链不会断 —— 花屏就没了。
331
+ *
332
+ * **长轮询**:队列空的时候不立刻回 204,而是把响应挂起来,
333
+ * 最多等 timeout 毫秒;期间一有帧进来就马上返回。
334
+ *
335
+ * 为什么必须这样做:
336
+ * 之前是「立刻返回 204 → 渲染层再发一次请求」的忙轮询。
337
+ * 每次往返(HTTP 握手 + 头部 + 空响应)大约 3~8ms,
338
+ * 而一帧的编码间隔只有 33ms —— 光往返就吃掉了三分之一的时间窗,
339
+ * 实测帧率在 0 / 63 / 4.5 之间乱跳。
340
+ * 改成挂起式之后,一次请求拿到新帧就返回,没有无效往返。
341
+ */
342
+ if (u.pathname === '/frames' || u.pathname === '/frames-next') {
343
+ const n = Math.max(1, Math.min(60, Number(u.searchParams.get('n') || 12)))
344
+ const waitMs = Math.max(0, Math.min(3000, Number(u.searchParams.get('wait') || 500)))
345
+
346
+ const flush = () => {
347
+ const out = state.queue.splice(0, n)
348
+ if (!out.length) return false
349
+
350
+ // 4 + 每帧(4B seq + 4B len) + 数据
351
+ let total = 4
352
+ for (const f of out) total += 8 + f.data.length
353
+ const buf = Buffer.allocUnsafe(total)
354
+ let off = 0
355
+ buf.writeUInt32BE(out.length, off); off += 4
356
+ for (const f of out) {
357
+ buf.writeUInt32BE(f.seq >>> 0, off); off += 4
358
+ buf.writeUInt32BE(f.data.length, off); off += 4
359
+ Buffer.from(f.data).copy(buf, off)
360
+ off += f.data.length
361
+ }
362
+ res.writeHead(200, {
363
+ 'Content-Type': 'application/octet-stream',
364
+ 'Content-Length': String(total),
365
+ 'Cache-Control': 'no-store',
366
+ 'X-Count': String(out.length),
367
+ 'X-Dropped': String(state.dropped),
368
+ 'X-First-Seq': String(out[0].seq),
369
+ 'X-Last-Seq': String(out[out.length - 1].seq)
370
+ })
371
+ res.end(buf)
372
+ return true
373
+ }
374
+
375
+ // 有货就直接给
376
+ if (flush()) return
377
+
378
+ /**
379
+ * 没货:挂起等待。
380
+ *
381
+ * 用数组存回调而不是只存一个 —— 万一有两端同时请求(比如小窗重连期间
382
+ * 旧的请求还没断),都该被唤醒,否则会有一个永远挂着。
383
+ */
384
+ let done = false
385
+ const waiter = () => {
386
+ if (done) return
387
+ if (flush()) {
388
+ done = true
389
+ cleanup()
390
+ }
391
+ }
392
+ const timer = setTimeout(() => {
393
+ if (done) return
394
+ done = true
395
+ cleanup()
396
+ // 超时:回 204,渲染层立刻再发一次(此时通常已有新帧)
397
+ try {
398
+ res.writeHead(204, { 'Cache-Control': 'no-store', 'X-Dropped': String(state.dropped) })
399
+ res.end()
400
+ } catch {}
401
+ }, waitMs)
402
+
403
+ const cleanup = () => {
404
+ clearTimeout(timer)
405
+ const i = state.waiters.indexOf(waiter)
406
+ if (i >= 0) state.waiters.splice(i, 1)
407
+ }
408
+
409
+ state.waiters.push(waiter)
410
+ // 客户端提前断开也要清理,不然 waiters 会越积越多
411
+ res.on('close', () => {
412
+ if (done) return
413
+ done = true
414
+ cleanup()
415
+ })
416
+ return
417
+ }
418
+
419
+ if (u.pathname === '/frame') {
420
+ const f = state.lastFrame
421
+ if (!f) {
422
+ res.writeHead(204)
423
+ res.end()
424
+ return
425
+ }
426
+ /**
427
+ * 带序列号返回。
428
+ * 渲染层轮询很快,会反复拿到同一帧;重复喂给解码器会导致
429
+ * "Decoding error" 然后 closed(实测只解 5 帧就崩)。
430
+ * 渲染层靠 X-Seq 跳过重复帧。
431
+ */
432
+ res.writeHead(200, {
433
+ 'Content-Type': 'application/octet-stream',
434
+ 'X-Seq': String(f.seq)
435
+ })
436
+ res.end(Buffer.from(f.data))
437
+ return
438
+ }
439
+
440
+ /** 最后一个 IDR 关键帧。渲染层启动时先 GET 这个补帧。 */
441
+ if (u.pathname === '/keyframe') {
442
+ const k = state.lastKey
443
+ if (!k) {
444
+ res.writeHead(204)
445
+ res.end()
446
+ return
447
+ }
448
+ res.writeHead(200, {
449
+ 'Content-Type': 'application/octet-stream',
450
+ 'X-Seq': String(k.seq)
451
+ })
452
+ res.end(Buffer.from(k.data))
453
+ return
454
+ }
455
+
456
+ /**
457
+ * 音频批量取帧 —— 和 /frames 完全同构(长轮询 + 二进制容器)。
458
+ *
459
+ * 容器格式:[4B 帧数][每帧: 8B pts(微秒) | 4B 长度 | 数据]
460
+ * pts 用 float64 存微秒,因为音频包间隔不均匀,需要时间戳来
461
+ * 驱动 AudioDecoder 和音频时钟,不能像视频那样用「到达时间」凑。
462
+ */
463
+ if (u.pathname === '/audio') {
464
+ const n = Math.max(1, Math.min(120, Number(u.searchParams.get('n') || 24)))
465
+ const waitMs = Math.max(0, Math.min(3000, Number(u.searchParams.get('wait') || 800)))
466
+
467
+ const flush = () => {
468
+ const out = state.audioQueue.splice(0, n)
469
+ if (!out.length) return false
470
+ let total = 4
471
+ for (const f of out) total += 12 + f.data.length
472
+ const buf = Buffer.allocUnsafe(total)
473
+ let off = 0
474
+ buf.writeUInt32BE(out.length, off); off += 4
475
+ for (const f of out) {
476
+ buf.writeDoubleBE(f.pts || 0, off); off += 8
477
+ buf.writeUInt32BE(f.data.length, off); off += 4
478
+ f.data.copy(buf, off); off += f.data.length
479
+ }
480
+ res.writeHead(200, {
481
+ 'Content-Type': 'application/octet-stream',
482
+ 'Content-Length': String(total),
483
+ 'Cache-Control': 'no-store',
484
+ 'X-Count': String(out.length)
485
+ })
486
+ res.end(buf)
487
+ return true
488
+ }
489
+
490
+ if (flush()) return
491
+
492
+ let done = false
493
+ const waiter = () => {
494
+ if (done) return
495
+ if (flush()) { done = true; cleanup() }
496
+ }
497
+ const cleanup = () => {
498
+ clearTimeout(timer)
499
+ const i = state.audioWaiters.indexOf(waiter)
500
+ if (i >= 0) state.audioWaiters.splice(i, 1)
501
+ }
502
+ const timer = setTimeout(() => {
503
+ if (done) return
504
+ done = true
505
+ cleanup()
506
+ try { res.writeHead(204, { 'Cache-Control': 'no-store' }); res.end() } catch {}
507
+ }, waitMs)
508
+
509
+ state.audioWaiters.push(waiter)
510
+ res.on('close', () => { if (!done) { done = true; cleanup() } })
511
+ return
512
+ }
513
+
514
+ /** 音频解码器初始化参数(AudioSpecificConfig) */
515
+ if (u.pathname === '/audio-config') {
516
+ if (!state.hasAudio || !state.audioConfig) {
517
+ res.writeHead(204, { 'Cache-Control': 'no-store' })
518
+ res.end()
519
+ return
520
+ }
521
+ res.writeHead(200, {
522
+ 'Content-Type': 'application/octet-stream',
523
+ 'Content-Length': String(state.audioConfig.length),
524
+ 'Cache-Control': 'no-store'
525
+ })
526
+ res.end(state.audioConfig)
527
+ return
528
+ }
529
+
530
+ /* ══════════ 2.0:网页配对 + 零 APK 直连 ══════════ */
531
+
532
+ /** 配对页(手机扫码后打开的页面,GET) */
533
+ if (u.pathname === '/pair' && req.method === 'GET') {
534
+ const { pairPageHtml } = require('./pair-page.js')
535
+ const html = pairPageHtml(state.lanIp || '本机', LISTEN_PORT + 2)
536
+ const buf = Buffer.from(html, 'utf8')
537
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': String(buf.length), 'Cache-Control': 'no-store' })
538
+ res.end(buf)
539
+ return
540
+ }
541
+
542
+ /**
543
+ * POST /pair —— 手机网页提交配对码,PC 执行 adb pair。
544
+ *
545
+ * body: { addr: "172.31.100.199:38571", code: "123456" }
546
+ * 成功返回 { ok:true, stage:'paired', wlanPort } —— 页面随后调 /start-zero
547
+ */
548
+ if (u.pathname === '/pair' && req.method === 'POST') {
549
+ let body = ''
550
+ req.on('data', d => { body += d; if (body.length > 4096) req.destroy() })
551
+ req.on('end', async () => {
552
+ try {
553
+ const j = JSON.parse(body)
554
+ const addr = String(j.addr || '').trim()
555
+ const code = String(j.code || '').trim()
556
+ if (!/^\d+\.\d+\.\d+\.\d+:\d+$/.test(addr) || !/^\d{6}$/.test(code)) {
557
+ res.writeHead(200, { 'Content-Type': 'application/json' })
558
+ res.end(JSON.stringify({ ok: false, error: '参数格式错误' }))
559
+ return
560
+ }
561
+ const adbPath = ADB_PATH
562
+ const { execFile } = require('child_process')
563
+ const run = (args, timeout = 20000) => new Promise((resolve, reject) => {
564
+ execFile(adbPath, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
565
+ if (err) reject(new Error(String(stderr || err.message).trim()))
566
+ else resolve(String(stdout || '').trim())
567
+ })
568
+ })
569
+
570
+ // 1. adb pair
571
+ const pairOut = await run(['pair', addr, code])
572
+ if (!/Successfully paired|paired with/i.test(pairOut)) {
573
+ throw new Error('配对失败: ' + pairOut.slice(0, 120))
574
+ }
575
+ state.pairIp = addr.split(':')[0]
576
+
577
+ // 2. 查无线调试的 connect 端口(配对端口 ≠ 连接端口)
578
+ // mDNS 服务 _adb-tls-connect._tcp 会广播真实端口;这里先试常用端口段
579
+ let wlanPort = 0
580
+ for (const p of [5555, addr.split(':')[1]]) {
581
+ const r = await run(['connect', `${state.pairIp}:${p}`], 8000).catch(() => '')
582
+ if (/connected to/i.test(r)) { wlanPort = Number(p); break }
583
+ }
584
+ if (!wlanPort) {
585
+ // 5555 不通时提示用户查看「无线调试」主页面的端口
586
+ res.writeHead(200, { 'Content-Type': 'application/json' })
587
+ res.end(JSON.stringify({ ok: true, stage: 'paired', needPort: true,
588
+ error: '配对成功,但未找到连接端口。请查看「无线调试」主页面显示的 IP 地址和端口(不是配对页的端口)' }))
589
+ return
590
+ }
591
+
592
+ res.writeHead(200, { 'Content-Type': 'application/json' })
593
+ res.end(JSON.stringify({ ok: true, stage: 'paired', wlanPort, phoneIp: state.pairIp }))
594
+ } catch (e) {
595
+ res.writeHead(200, { 'Content-Type': 'application/json' })
596
+ res.end(JSON.stringify({ ok: false, error: String(e.message || e) }))
597
+ }
598
+ })
599
+ return
600
+ }
601
+
602
+ /**
603
+ * POST /start-zero —— 配对完成后启动零 APK 投屏。
604
+ *
605
+ * body: { phoneIp, wlanPort? } —— 用户可在页面补填「无线调试主页面」的端口
606
+ * 流程:adb connect → ScrcpyTransport.start() → 视频帧推入渲染管线
607
+ */
608
+ if (u.pathname === '/start-zero' && req.method === 'POST') {
609
+ let body = ''
610
+ req.on('data', d => { body += d; if (body.length > 4096) req.destroy() })
611
+ req.on('end', async () => {
612
+ try {
613
+ const j = JSON.parse(body || '{}')
614
+ const adbPath = ADB_PATH
615
+ const { execFile } = require('child_process')
616
+ const run = (args, timeout = 20000) => new Promise((resolve, reject) => {
617
+ execFile(adbPath, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
618
+ if (err) reject(new Error(String(stderr || err.message).trim()))
619
+ else resolve(String(stdout || '').trim())
620
+ })
621
+ })
622
+
623
+ let ip = j.phoneIp || state.pairIp
624
+ let port = Number(j.wlanPort || 5555)
625
+ if (!ip) throw new Error('缺少手机地址')
626
+
627
+ // 尝试连接(可能要试多个端口:用户补填的优先)
628
+ let connected = false
629
+ const tryPorts = j.wlanPort ? [port] : [port, 5555, 37123, 40123, 42123]
630
+ for (const p of tryPorts) {
631
+ const r = await run(['connect', `${ip}:${p}`], 8000).catch(() => '')
632
+ if (/connected to/i.test(r)) { port = p; connected = true; break }
633
+ }
634
+ if (!connected) throw new Error('无法连接手机。请查看「无线调试」主页面上的端口并填入上方输入框')
635
+
636
+ // 启动 scrcpy 传输(零 APK:视频+控制)
637
+ const { ScrcpyTransport } = require('./scrcpy-transport.js')
638
+ if (state.transport) { try { await state.transport.stop() } catch {} }
639
+ const t = new ScrcpyTransport({
640
+ adb: adbPath,
641
+ serial: `${ip}:${port}`,
642
+ serverJar: SERVER_JAR,
643
+ maxSize: 720, bitRate: 6000000, maxFps: 30
644
+ })
645
+ t.onLog(m => console.log('[2.0]', m))
646
+ // 视频帧直接进渲染管线(与 1.x App 推流同一出口)
647
+ t.onVideo(f => {
648
+ if (f.type === 'config') {
649
+ // SPS/PPS → 生成 description 供渲染层 configure
650
+ try {
651
+ const info = makeDescriptionFromConfig(f.data)
652
+ if (info) {
653
+ state.codecString = info.codecString
654
+ state.description = info.description
655
+ console.log('[2.0] codec ' + info.codecString)
656
+ }
657
+ } catch {}
658
+ return
659
+ }
660
+ const seq = ++state.seq
661
+ state.lastFrame = { data: f.data, pts: 0, key: f.type === 'key', seq }
662
+ state.queue.push({ data: f.data, pts: 0, key: f.type === 'key', seq })
663
+ if (state.queue.length > 90) { state.queue.shift(); state.dropped++ }
664
+ if (state.waiters.length) {
665
+ const ws = state.waiters.slice()
666
+ for (const w of ws) { try { w() } catch {} }
667
+ }
668
+ })
669
+ const r = await t.start()
670
+ if (!r.ok) throw new Error('传输启动失败: ' + (r.error || ''))
671
+
672
+ state.zeroMode = true
673
+ state.hasAudio = false // 2.0 音频暂缺(华为 audio socket 兼容问题)
674
+ console.log('[2.0] 零 APK 投屏已启动')
675
+
676
+ res.writeHead(200, { 'Content-Type': 'application/json' })
677
+ res.end(JSON.stringify({ ok: true, videoW: t.videoW, videoH: t.videoH }))
678
+ } catch (e) {
679
+ res.writeHead(200, { 'Content-Type': 'application/json' })
680
+ res.end(JSON.stringify({ ok: false, error: String(e.message || e) }))
681
+ }
682
+ })
683
+ return
684
+ }
685
+ if (u.pathname === '/meta') {
686
+ res.writeHead(200, { 'Content-Type': 'application/json' })
687
+ res.end(JSON.stringify({
688
+ ok: true,
689
+ frames: state.frames,
690
+ connected: state.connected,
691
+ codecString: state.codecString,
692
+ videoSize: state.videoSize,
693
+ hasAudio: state.hasAudio,
694
+ audioFrames: state.audioFrames,
695
+ audioConfigLen: state.audioConfig ? state.audioConfig.length : 0,
696
+ phoneVolume: state.phoneVolume,
697
+ uptime: Math.round((Date.now() - state.startedAt) / 1000)
698
+ }))
699
+ return
700
+ }
701
+
702
+ res.writeHead(404)
703
+ res.end()
704
+ })
705
+
706
+ /**
707
+ * 2.0:HTTP 改绑 0.0.0.0。
708
+ *
709
+ * 之前只绑 127.0.0.1(迷你窗在本机拉流就够了)。2.0 的配对页 /pair
710
+ * 要让手机浏览器直接访问 —— 扫码后的 URL 是
711
+ * http://<PC局域网IP>:HTTP_PORT/pair,必须绑通配地址。
712
+ * 数据端点(/audio /frames)无鉴权但仅局域网可达,与 LAN server 一致。
713
+ */
714
+ httpServer.listen(HTTP_PORT, '0.0.0.0', () => {
715
+ console.log('[http] 监听 0.0.0.0:' + HTTP_PORT + '(迷你窗拉流 + 2.0 配对页)')
716
+ console.log('')
717
+ console.log('把下面两个数字告诉手机 App:')
718
+ console.log(' host = 本机任一局域网 IP(172.31.100.174)')
719
+ console.log(' port = ' + LISTEN_PORT)
720
+ })
721
+
722
+ // 1 秒窗口统计
723
+ setInterval(() => {
724
+ const prev = state._f || 0
725
+ state.fps = state.frames - prev
726
+ state._f = state.frames
727
+ }, 1000)
728
+
729
+
730
+
731
+
732
+
733
+