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,175 @@
1
+ 'use strict'
2
+ /**
3
+ * 音频路由策略(手机端声音到底去哪)。
4
+ *
5
+ * 用户规则:
6
+ * 1. 手机插耳机(有线/蓝牙)时:不做任何投音频,声音留在手机
7
+ * 2. 手机外放时:连接后默认「双端静音」——手机静音 + 投屏音量 0
8
+ * 3. 手动把投屏音量调上去(>0)才把手机声音投到电脑
9
+ * 4. 投屏音量不影响手机音量
10
+ * 5. 手机音量变化 → 投屏音量被重置成手机音量
11
+ * 6. 断开连接 → 音频断开,并杀掉手机端 APK
12
+ *
13
+ * 数据来源(实测这台 HBN-AL00 可用):
14
+ * adb shell dumpsys audio → STREAM_MUSIC 段落里的
15
+ * "Devices: speaker, bt_a2dp"
16
+ * "streamVolume:10"
17
+ */
18
+ const { execFile } = require('child_process')
19
+
20
+ const HEADSET_DEVICES = ['headset', 'headphone', 'bt_a2dp', 'bt_a2dp_hp', 'bt_a2dp_spk',
21
+ 'bt_sco', 'bt_sco_hs', 'bt_sco_carkit', 'usb_headset']
22
+ const SPEAKER_DEVICES = ['speaker', 'speaker_safe']
23
+
24
+ class AudioRouter {
25
+ constructor (opts = {}) {
26
+ this.adb = opts.adb
27
+ this.serial = opts.serial
28
+ this.apkPackage = opts.apkPackage || 'com.miniwin.stream'
29
+ /** 接收端 HTTP 端口(/meta 的 phoneVolume 是手机音量意图的权威来源) */
30
+ this.httpPort = opts.httpPort || 0
31
+ this.onLog = opts.onLog || (() => {})
32
+ this.onState = opts.onState || (() => {})
33
+ this.timer = null
34
+ this.last = { devices: [], headset: false, speaker: false, phoneVolume: 0, pcVolume: 0 }
35
+ this.pcVolume = 0
36
+ this.manualOverride = false
37
+ }
38
+
39
+ _run (args, timeout = 8000) {
40
+ return new Promise((resolve) => {
41
+ execFile(this.adb, ['-s', this.serial, ...args], { timeout, windowsHide: true },
42
+ (err, stdout, stderr) => resolve({ ok: !err, out: String(stdout || ''), err: String(stderr || '') }))
43
+ })
44
+ }
45
+
46
+ /** 解析 dumpsys audio 里的音频路由与音乐音量 */
47
+ static parse (text) {
48
+ const idx = text.indexOf('STREAM_MUSIC')
49
+ if (idx < 0) return { devices: [], streamVolume: 0 }
50
+ const block = text.slice(idx, idx + 1200)
51
+ const devLine = (block.match(/Devices:\s*([^\n\r]+)/) || [])[1] || ''
52
+ const devices = devLine.split(',').map(s => s.trim()).filter(Boolean)
53
+ const vol = parseInt((block.match(/streamVolume:(\d+)/) || [])[1] || '0', 10)
54
+ return { devices, streamVolume: vol }
55
+ }
56
+
57
+ async poll () {
58
+ const { out } = await this._run(['shell', 'dumpsys audio'])
59
+ const p = AudioRouter.parse(out)
60
+ const headset = p.devices.some(d => HEADSET_DEVICES.includes(d))
61
+ const speaker = p.devices.some(d => SPEAKER_DEVICES.includes(d))
62
+
63
+ /**
64
+ * 「用户按了手机音量键」这件事,dumpsys 的 streamVolume 看不出来 ——
65
+ * APK 静音后它一直是 0。真正的意图值在 APK 读取的
66
+ * Settings.System.volume_music 里,它通过接收端 /meta 的
67
+ * phoneVolume(0..255)暴露出来。
68
+ *
69
+ * 所以:设备列表看 dumpsys,音量意图看 /meta。
70
+ */
71
+ let intentVol = p.streamVolume
72
+ if (this.httpPort) {
73
+ try {
74
+ const r = await fetch(`http://127.0.0.1:${this.httpPort}/meta`, {
75
+ cache: 'no-store', signal: AbortSignal.timeout(1500)
76
+ })
77
+ const j = await r.json()
78
+ if (j && typeof j.phoneVolume === 'number') {
79
+ intentVol = Math.round((j.phoneVolume / 255) * 15)
80
+ }
81
+ } catch { /* 接收端没起就用 dumpsys 的值 */ }
82
+ }
83
+
84
+ const prev = this.last
85
+ this.last = { devices: p.devices, headset, speaker, phoneVolume: intentVol, pcVolume: this.pcVolume }
86
+
87
+ if (headset) {
88
+ /**
89
+ * 耳机在场:投屏音量归零,并且**清掉手动标记**。
90
+ *
91
+ * 不清会踩这个坑:耳机插着时用户拖过投屏音量(或手机音量被同步过来),
92
+ * pcVolume 停在 7;耳机一拔条件立刻成立 → 手机声音突然被投到电脑,
93
+ * 而用户根本没开。规则是「外放默认静音,手动调高才转发」。
94
+ */
95
+ if (this.pcVolume !== 0 || this.manualOverride) this.onLog('[audio] 耳机在场:投屏音量归零')
96
+ this.pcVolume = 0
97
+ this.manualOverride = false
98
+ this.last.pcVolume = 0
99
+ } else if (intentVol !== prev.phoneVolume) {
100
+ /**
101
+ * 规则 5:手机端音量变化 → 投屏端直接重置成手机端音量。
102
+ * 不看 manualOverride —— 用户明确要求「手机端调音量就把投屏端重置过去」。
103
+ */
104
+ this.pcVolume = intentVol
105
+ this.manualOverride = this.pcVolume > 0
106
+ this.last.pcVolume = this.pcVolume
107
+ this.onLog(`[audio] 手机音量 ${intentVol}/15 → 投屏音量重置为 ${this.pcVolume}/15`)
108
+ }
109
+ this.onState({ ...this.last, forwarding: this.shouldForward() })
110
+ }
111
+
112
+ /** 规则 1:耳机时永不转发 */
113
+ shouldForward () {
114
+ if (this.last.headset) return false
115
+ return this.manualOverride && this.pcVolume > 0
116
+ }
117
+
118
+ /** 规则 3:用户手动调高投屏音量 → 允许转发 */
119
+ setPcVolume (v) {
120
+ this.pcVolume = Math.max(0, Math.min(15, Math.round(v)))
121
+ this.manualOverride = this.pcVolume > 0
122
+ this.last.pcVolume = this.pcVolume
123
+ const fwd = this.shouldForward()
124
+ this.onLog(`[audio] 投屏音量=${this.pcVolume} → ${fwd ? '开始转发手机声音' : '不转发'}`)
125
+ this.onState({ ...this.last, forwarding: fwd })
126
+ return { pcVolume: this.pcVolume, forwarding: fwd }
127
+ }
128
+
129
+ /** 规则 2:外放时连接即双端静音(用音量键把媒体音量降到 0) */
130
+ async mutePhone () {
131
+ // `cmd media_session` 一条命令就能把媒体音量设到 0,比连按音量键干净得多
132
+ const r = await this._run(['shell', 'cmd media_session volume --stream 3 --set 0'])
133
+ if (r.ok) {
134
+ this.last.phoneVolume = 0
135
+ this.onLog('[audio] 手机媒体音量已设 0(外放默认静音)')
136
+ return
137
+ }
138
+ // 老系统没有 cmd media_session:退回音量键
139
+ for (let i = 0; i < 16; i++) {
140
+ await this._run(['shell', 'input keyevent 25']) // VOLUME_DOWN
141
+ }
142
+ this.last.phoneVolume = 0
143
+ this.onLog('[audio] 手机媒体音量已降到 0(音量键兜底)')
144
+ }
145
+
146
+ /**
147
+ * 只停手机端 APK,不停轮询。
148
+ *
149
+ * 耳机插上时用它:APK 会把手机 STREAM_MUSIC 锁在 0,
150
+ * 不 force-stop 的话耳机里也没声。
151
+ */
152
+ async killApk () {
153
+ await this._run(['shell', `am force-stop ${this.apkPackage}`])
154
+ this.onLog(`[audio] 已停止手机端 ${this.apkPackage}`)
155
+ }
156
+
157
+ /** 规则 6:断开时停音频并杀掉手机端 APK */
158
+ async teardown () {
159
+ this.stop()
160
+ await this._run(['shell', `am force-stop ${this.apkPackage}`])
161
+ this.onLog(`[audio] 已断开音频并停止手机端 ${this.apkPackage}`)
162
+ }
163
+
164
+ start (intervalMs = 2000) {
165
+ if (this.timer) return
166
+ this.timer = setInterval(() => { this.poll().catch(() => {}) }, intervalMs)
167
+ this.poll().catch(() => {})
168
+ }
169
+
170
+ stop () {
171
+ if (this.timer) { clearInterval(this.timer); this.timer = null }
172
+ }
173
+ }
174
+
175
+ module.exports = { AudioRouter, HEADSET_DEVICES, SPEAKER_DEVICES }
@@ -0,0 +1,186 @@
1
+ 'use strict'
2
+ /**
3
+ * H.264 Annex-B ⇄ AVCC 转换,以及 AVCDecoderConfigurationRecord 构造
4
+ *
5
+ * 为什么需要:WebCodecs VideoDecoder 对 AVC 期望 AVCC 格式
6
+ * - EncodedVideoChunk 的 data 是 AVCC(每个 NAL 前 4 字节大端长度)
7
+ * - config.description 是 AVCDecoderConfigurationRecord(含 SPS/PPS)
8
+ * scrcpy 送来的是 Annex-B(00 00 00 01 起始码),必须转换。
9
+ */
10
+
11
+ /** 把 Annex-B 拆成 NAL 单元数组(不含起始码) */
12
+ function splitAnnexB (buf) {
13
+ const nals = []
14
+
15
+ // 收集所有起始码位置(先匹配 3 字节,若前面还有 0 则整体视为 4 字节起始码 + 前导 0)
16
+ const marks = []
17
+ let i = 0
18
+ while (i + 3 <= buf.length) {
19
+ if (buf[i] === 0 && buf[i + 1] === 0 && buf[i + 2] === 1) {
20
+ let pos = i
21
+ let len = 3
22
+ // 向前吸收多余的 0,它们属于 trailing_zero_8bits
23
+ while (pos > 0 && buf[pos - 1] === 0) { pos--; len++ }
24
+ marks.push({ pos, start: i + 3 })
25
+ i += 3
26
+ } else {
27
+ i++
28
+ }
29
+ }
30
+ if (!marks.length) return nals
31
+
32
+ for (let m = 0; m < marks.length; m++) {
33
+ const start = marks[m].start
34
+ const end = m + 1 < marks.length ? marks[m + 1].pos : buf.length
35
+ if (end <= start) continue
36
+
37
+ // H.264 Annex-B:rbsp_trailing_bits 结尾一定是 1 位,
38
+ // 因此 NAL 最后一个字节不会是 0x00,末尾的 0 一律属于 trailing_zero_8bits
39
+ let e = end
40
+ while (e > start && buf[e - 1] === 0) e--
41
+ if (e > start) nals.push(buf.subarray(start, e))
42
+ }
43
+ return nals
44
+ }
45
+
46
+ /** NAL 单元类型 */
47
+ const nalType = nal => nal[0] & 0x1f
48
+
49
+ /** Annex-B → AVCC(4 字节长度前缀) */
50
+ function annexBToAvcc (buf) {
51
+ const nals = splitAnnexB(buf)
52
+ if (!nals.length) return Buffer.alloc(0)
53
+
54
+ let total = 0
55
+ for (const n of nals) total += 4 + n.length
56
+
57
+ const out = Buffer.allocUnsafe(total)
58
+ let off = 0
59
+ for (const n of nals) {
60
+ out.writeUInt32BE(n.length, off)
61
+ off += 4
62
+ n.copy(out, off)
63
+ off += n.length
64
+ }
65
+ return out
66
+ }
67
+
68
+ /**
69
+ * 构造 AVCDecoderConfigurationRecord
70
+ * @param {Buffer} sps 不含起始码的 SPS NAL
71
+ * @param {Buffer} pps 不含起始码的 PPS NAL
72
+ * @param {number} [nalLengthSize=4]
73
+ */
74
+ function buildAvcDescription (sps, pps, nalLengthSize = 4) {
75
+ if (!sps || !sps.length || !pps || !pps.length) throw new Error('SPS/PPS 不能为空')
76
+
77
+ // AVCDecoderConfigurationRecord 布局:
78
+ // 0 configurationVersion = 1
79
+ // 1 AVCProfileIndication
80
+ // 2 profile_compatibility
81
+ // 3 AVCLevelIndication
82
+ // 4 111111 + lengthSizeMinusOne (2b)
83
+ // 5 111 + numOfSPS (5b)
84
+ // 6..7 SPS length (u16 BE)
85
+ // 8.. SPS
86
+ // +0 numOfPPS (1B)
87
+ // +1..2 PPS length (u16 BE)
88
+ // +3.. PPS
89
+ const header = Buffer.alloc(8)
90
+ header[0] = 1
91
+ header[1] = sps[1]
92
+ header[2] = sps[2]
93
+ header[3] = sps[3]
94
+ header[4] = 0xfc | (nalLengthSize - 1)
95
+ header[5] = 0xe0 | 1
96
+ header.writeUInt16BE(sps.length, 6)
97
+
98
+ const ppsCountAndLen = Buffer.alloc(3)
99
+ ppsCountAndLen[0] = 1
100
+ ppsCountAndLen.writeUInt16BE(pps.length, 1)
101
+
102
+ return Buffer.concat([header, sps, ppsCountAndLen, pps])
103
+ }
104
+
105
+ /**
106
+ * 从 Annex-B config 包里抽出 SPS/PPS,构造 description
107
+ * @returns {{description: Buffer, sps: Buffer, pps: Buffer, codecString: string} | null}
108
+ */
109
+ function makeDescriptionFromConfig (configBuf) {
110
+ const nals = splitAnnexB(configBuf)
111
+ let sps = null
112
+ let pps = null
113
+ for (const n of nals) {
114
+ const t = nalType(n)
115
+ if (t === 7 && !sps) sps = n
116
+ else if (t === 8 && !pps) pps = n
117
+ }
118
+ if (!sps || !pps) return null
119
+
120
+ const hx = n => n.toString(16).padStart(2, '0')
121
+ return {
122
+ description: buildAvcDescription(sps, pps, 4),
123
+ sps,
124
+ pps,
125
+ codecString: `avc1.${hx(sps[1])}${hx(sps[2])}${hx(sps[3])}`
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 判断一段 Annex-B 里是否含 SPS/PPS(有些流每个关键帧都带)
131
+ */
132
+ function hasParamSets (buf) {
133
+ for (const n of splitAnnexB(buf)) {
134
+ const t = nalType(n)
135
+ if (t === 7 || t === 8) return true
136
+ }
137
+ return false
138
+ }
139
+
140
+ /** 按 nalLengthSize 重新打包(scrcpy 固定 4) */
141
+ function repackWithLengthSize (buf, nalLengthSize = 4) {
142
+ return annexBToAvcc(buf)
143
+ }
144
+
145
+ /**
146
+ * 把一帧 Annex-B 转成 AVCC,并剥掉 SPS/PPS/AUD/SEI
147
+ *
148
+ * 关于关键帧:scrcpy 的 PACKET_FLAG_KEY_FRAME 理论上靠谱,但实际链路里
149
+ * 一旦有丢包或封装差异,标志可能和真实 NAL 类型不一致。VideoDecoder
150
+ * 对「configure 后第一帧不是 key」会直接抛错,所以这里以 NAL 类型为准:
151
+ * 含 IDR(5) 才是关键帧,并把它一起返回,让调用方覆盖 flag。
152
+ *
153
+ * @returns {{ data: Buffer, key: boolean } | null} null = 整帧只有参数集
154
+ */
155
+ function frameToAvcc (buf) {
156
+ const nals = splitAnnexB(buf)
157
+ const keep = []
158
+ let hasIdr = false
159
+
160
+ for (const n of nals) {
161
+ const t = nalType(n)
162
+ if (t === 7 || t === 8) continue // SPS / PPS:已在 description 里
163
+ if (t === 9) continue // AUD:解码器不需要
164
+ if (t === 6) continue // SEI:对纯画面无意义,且部分解码器会报错
165
+ if (t === 5) hasIdr = true // IDR = 关键帧
166
+ if (t >= 1 && t <= 5) keep.push(n) // 真正的 slice 数据
167
+ }
168
+ if (!keep.length) return null
169
+
170
+ let total = 0
171
+ for (const n of keep) total += 4 + n.length
172
+ const out = Buffer.allocUnsafe(total)
173
+ let off = 0
174
+ for (const n of keep) {
175
+ out.writeUInt32BE(n.length, off)
176
+ off += 4
177
+ n.copy(out, off)
178
+ off += n.length
179
+ }
180
+ return { data: out, key: hasIdr }
181
+ }
182
+
183
+ module.exports = {
184
+ splitAnnexB, annexBToAvcc, buildAvcDescription, makeDescriptionFromConfig,
185
+ hasParamSets, repackWithLengthSize, frameToAvcc, nalType
186
+ }
@@ -0,0 +1,307 @@
1
+ 'use strict'
2
+ /**
3
+ * 设备连接层:USB(adb forward)与 WiFi(adb connect + forward)统一入口
4
+ *
5
+ * scrcpy v5 的启动方式:
6
+ * 1) adb push scrcpy-server /data/local/tmp/scrcpy-server.jar
7
+ * 2) adb [shell] CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server 5.0.1 <args...>
8
+ * 3) 参数里 tunnel_forward=true 时:设备侧 LocalServerSocket("scrcpy") 等客户端
9
+ * 客户端通过 adb forward tcp:LOCAL localabstract:scrcpy 接进来
10
+ */
11
+
12
+ const { execFile } = require('child_process')
13
+ const path = require('path')
14
+ const fs = require('fs')
15
+ const net = require('net')
16
+
17
+ const SERVER_VERSION = '5.0.1'
18
+ const REMOTE_JAR = '/data/local/tmp/scrcpy-server.jar'
19
+ const SOCKET_NAME = 'scrcpy'
20
+
21
+ class Adb {
22
+ constructor (adbPath) {
23
+ this.adb = adbPath
24
+ this.serial = null
25
+ }
26
+
27
+ run (args, opts = {}) {
28
+ return new Promise((resolve, reject) => {
29
+ const full = this.serial ? ['-s', this.serial, ...args] : args
30
+ execFile(this.adb, full, { timeout: opts.timeout || 30000, windowsHide: true, maxBuffer: 8 << 20 },
31
+ (err, stdout, stderr) => {
32
+ if (err) {
33
+ err.stdout = stdout
34
+ err.stderr = stderr
35
+ return reject(err)
36
+ }
37
+ resolve({ stdout, stderr })
38
+ })
39
+ })
40
+ }
41
+
42
+ /** @returns {Promise<Array<{serial:string,state:string,model:string,transport:string}>>} */
43
+ async devices () {
44
+ const { stdout } = await this.run(['devices', '-l'])
45
+ const out = []
46
+ for (const line of stdout.split(/\r?\n/)) {
47
+ const m = line.match(/^(\S+)\s+(device|unauthorized|offline|no permissions)\b(.*)$/)
48
+ if (!m) continue
49
+ const rest = m[3] || ''
50
+ const modelM = rest.match(/model:(\S+)/)
51
+ out.push({
52
+ serial: m[1],
53
+ state: m[2],
54
+ model: modelM ? modelM[1].replace(/_/g, ' ') : '',
55
+ transport: m[1].includes(':') ? 'wifi' : 'usb'
56
+ })
57
+ }
58
+ return out
59
+ }
60
+
61
+ async pickDevice (wantSerial) {
62
+ const list = await this.devices()
63
+ if (!list.length) {
64
+ throw new Error('没有检测到设备。请确认:USB 线已连接 + 手机已开「USB 调试」+ 手机上点了「允许调试」')
65
+ }
66
+ if (wantSerial) {
67
+ const hit = list.find(d => d.serial === wantSerial)
68
+ if (!hit) throw new Error(`指定的设备 ${wantSerial} 不在列表里:${list.map(d => d.serial).join(', ')}`)
69
+ if (hit.state !== 'device') throw new Error(`设备 ${wantSerial} 状态是 ${hit.state},需要在手机上授权调试`)
70
+ this.serial = hit.serial
71
+ return hit
72
+ }
73
+ const ready = list.filter(d => d.state === 'device')
74
+ if (!ready.length) {
75
+ const bad = list[0]
76
+ throw new Error(`设备 ${bad.serial} 状态是 ${bad.state}。${bad.state === 'unauthorized' ? '请在手机上点「允许 USB 调试」' : '请检查连接'}`)
77
+ }
78
+ this.serial = ready[0].serial
79
+ return ready[0]
80
+ }
81
+
82
+ async props () {
83
+ const { stdout } = await this.run(['shell', 'getprop'])
84
+ const get = k => {
85
+ const m = stdout.match(new RegExp(`\\[${k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\]: \\[(.*?)\\]`))
86
+ return m ? m[1] : ''
87
+ }
88
+ return {
89
+ model: get('ro.product.model'),
90
+ brand: get('ro.product.brand'),
91
+ release: get('ro.build.version.release'),
92
+ sdk: parseInt(get('ro.build.version.sdk') || '0', 10),
93
+ abi: get('ro.product.cpu.abi'),
94
+ wm: await this.screenSize()
95
+ }
96
+ }
97
+
98
+ async screenSize () {
99
+ try {
100
+ const { stdout } = await this.run(['shell', 'wm', 'size'])
101
+ const m = stdout.match(/Override size:\s*(\d+)x(\d+)/) || stdout.match(/Physical size:\s*(\d+)x(\d+)/)
102
+ if (m) return { width: +m[1], height: +m[2] }
103
+ } catch { /* ignore */ }
104
+ return null
105
+ }
106
+
107
+ async pushServer (localJar) {
108
+ if (!fs.existsSync(localJar)) throw new Error('找不到 scrcpy-server: ' + localJar)
109
+ const remoteSize = await this.remoteFileSize()
110
+ const localSize = fs.statSync(localJar).size
111
+ if (remoteSize === localSize) return { pushed: false, size: localSize }
112
+ await this.run(['push', localJar, REMOTE_JAR], { timeout: 60000 })
113
+ return { pushed: true, size: localSize }
114
+ }
115
+
116
+ async remoteFileSize () {
117
+ try {
118
+ const { stdout } = await this.run(['shell', `stat -c %s ${REMOTE_JAR} 2>/dev/null || echo 0`])
119
+ return parseInt(stdout.trim(), 10) || 0
120
+ } catch { return 0 }
121
+ }
122
+
123
+ /** WiFi 连接:先配对(Android 11+ 无线调试),再连接 */
124
+ async connectWifi (host, port = 5555) {
125
+ const target = `${host}:${port}`
126
+ const { stdout, stderr } = await this.run(['connect', target], { timeout: 15000 })
127
+ const msg = (stdout + stderr).trim()
128
+ if (!/connected to/i.test(msg) && !/already connected/i.test(msg)) {
129
+ throw new Error('连接失败: ' + msg)
130
+ }
131
+ this.serial = target
132
+ return { target, message: msg }
133
+ }
134
+
135
+ /** 把当前 USB 设备切到 TCP 模式(Android 11+ 需先手动配对的端口) */
136
+ async enableTcpip (port = 5555) {
137
+ await this.run(['tcpip', String(port)], { timeout: 15000 })
138
+ const ip = await this.deviceWifiIp()
139
+ return { port, ip, target: ip ? `${ip}:${port}` : null }
140
+ }
141
+
142
+ async deviceWifiIp () {
143
+ try {
144
+ const { stdout } = await this.run(['shell', 'ip', 'route'])
145
+ const m = stdout.match(/src\s+(\d+\.\d+\.\d+\.\d+)/)
146
+ if (m) return m[1]
147
+ } catch { /* ignore */ }
148
+ try {
149
+ const { stdout } = await this.run(['shell', 'ifconfig', 'wlan0'])
150
+ const m = stdout.match(/inet addr:(\d+\.\d+\.\d+\.\d+)/) || stdout.match(/inet (\d+\.\d+\.\d+\.\d+)/)
151
+ if (m) return m[1]
152
+ } catch { /* ignore */ }
153
+ return null
154
+ }
155
+
156
+ async forward (localPort) {
157
+ await this.run(['forward', `tcp:${localPort}`, `localabstract:${SOCKET_NAME}`])
158
+ return localPort
159
+ }
160
+
161
+ async removeForward (localPort) {
162
+ try { await this.run(['forward', '--remove', `tcp:${localPort}`]) } catch { /* ignore */ }
163
+ }
164
+
165
+ async removeAllForwards () {
166
+ try { await this.run(['forward', '--remove-all']) } catch { /* ignore */ }
167
+ }
168
+ }
169
+
170
+ /** 起 server 进程并保持引用,便于 kill */
171
+ function startServer (adb, options) {
172
+ const {
173
+ maxSize = 1080, bitRate = 8000000, maxFps = 60, codec = 'h264',
174
+ tunnelForward = true, sendDummyByte = true, sendStreamMeta = true,
175
+ sendFrameMeta = true, sendDeviceMeta = true, control = true,
176
+ video = true, audio = false
177
+ } = options
178
+
179
+ const args = [
180
+ `CLASSPATH=${REMOTE_JAR}`,
181
+ 'app_process', '/', 'com.genymobile.scrcpy.Server', SERVER_VERSION,
182
+ `log_level=${options.logLevel || 'info'}`,
183
+ // 不传 scid:传了 socket 名会变成 scrcpy_xxxxxxxx,与 localabstract:scrcpy 对不上
184
+ `video=${video}`,
185
+ `audio=${audio}`,
186
+ `video_codec=${codec}`,
187
+ `max_size=${maxSize}`,
188
+ `video_bit_rate=${bitRate}`,
189
+ `max_fps=${maxFps}`,
190
+ `tunnel_forward=${tunnelForward}`,
191
+ `control=${control}`,
192
+ // send_device_meta=true 时 server 先发 64 字节定长设备名,解析器必须跳过
193
+ `send_device_meta=${sendDeviceMeta}`,
194
+ `send_frame_meta=${sendFrameMeta}`,
195
+ `send_dummy_byte=${sendDummyByte}`,
196
+ `send_stream_meta=${sendStreamMeta}`
197
+ ]
198
+
199
+ const full = adb.serial ? ['-s', adb.serial, 'shell', ...args] : ['shell', ...args]
200
+ const { spawn } = require('child_process')
201
+ const child = spawn(adb.adb, full, { windowsHide: true })
202
+
203
+ let stdout = ''
204
+ let stderr = ''
205
+ child.stdout.on('data', d => { stdout += d.toString() })
206
+ child.stderr.on('data', d => { stderr += d.toString() })
207
+
208
+ return {
209
+ child,
210
+ getLog: () => ({ stdout, stderr }),
211
+ kill: () => {
212
+ try { child.kill('SIGTERM') } catch { /* ignore */ }
213
+ // 设备侧进程也要杀,否则残留占用 scrcpy socket
214
+ return adb.run(['shell', 'pkill -f com.genymobile.scrcpy.Server']).catch(() => {})
215
+ }
216
+ }
217
+ }
218
+
219
+ /** 连本地 forward 端口,带重试(server 起得慢) */
220
+ function connectLocal (port, { retries = 40, interval = 150, timeout = 4000 } = {}) {
221
+ return new Promise((resolve, reject) => {
222
+ let attempt = 0
223
+ const tryOnce = () => {
224
+ attempt++
225
+ const sock = net.connect({ host: '127.0.0.1', port })
226
+ sock.setNoDelay(true)
227
+ let settled = false
228
+
229
+ const cleanup = () => {
230
+ sock.removeListener('connect', onConnect)
231
+ sock.removeListener('error', onError)
232
+ }
233
+ const onConnect = () => { if (settled) return; settled = true; cleanup(); resolve(sock) }
234
+ const onError = (err) => {
235
+ if (settled) return
236
+ settled = true
237
+ cleanup()
238
+ sock.destroy()
239
+ if (attempt >= retries) return reject(new Error(`连不上本地端口 ${port}:${err.message}`))
240
+ setTimeout(tryOnce, interval)
241
+ }
242
+
243
+ sock.once('connect', onConnect)
244
+ sock.once('error', onError)
245
+ sock.setTimeout(timeout, () => { if (!settled) { settled = true; cleanup(); sock.destroy(); onError(new Error('超时')) } })
246
+ }
247
+ tryOnce()
248
+ })
249
+ }
250
+
251
+ /**
252
+ * reverse 模式(tunnel_forward=false):
253
+ * - server 侧 connect("scrcpy") 到本地抽象 socket
254
+ * - 我们用 adb reverse 把设备上的 localabstract:scrcpy 映射回 PC 的 tcp 端口
255
+ * - PC 起监听,server 主动连进来
256
+ * 相比 forward 模式,这里 PC 是服务端,能先就绪再让 server 连,时序更稳。
257
+ */
258
+ function startReverse (adb, port) {
259
+ return adb.run(['reverse', `localabstract:${SOCKET_NAME}`, `tcp:${port}`])
260
+ }
261
+
262
+ /** 起本地 TCP 监听,等 server 连进来 */
263
+ function listenLocal (port, { timeout = 15000 } = {}) {
264
+ return new Promise((resolve, reject) => {
265
+ const srv = net.createServer()
266
+ let settled = false
267
+ const timer = setTimeout(() => {
268
+ if (settled) return
269
+ settled = true
270
+ try { srv.close() } catch {}
271
+ reject(new Error(`等待 server 连接超时(${timeout}ms)`))
272
+ }, timeout)
273
+
274
+ srv.once('connection', sock => {
275
+ if (settled) return
276
+ settled = true
277
+ clearTimeout(timer)
278
+ sock.setNoDelay(true)
279
+ try { srv.close() } catch {}
280
+ resolve({ sock, server: srv })
281
+ })
282
+ srv.once('error', e => {
283
+ if (settled) return
284
+ settled = true
285
+ clearTimeout(timer)
286
+ reject(e)
287
+ })
288
+ srv.listen(port, '127.0.0.1')
289
+ })
290
+ }
291
+
292
+ function findPort (start = 27183) {
293
+ return new Promise((resolve, reject) => {
294
+ const srv = net.createServer()
295
+ srv.once('error', () => findPort(start + 1).then(resolve, reject))
296
+ srv.once('listening', () => {
297
+ const p = srv.address().port
298
+ srv.close(() => resolve(p))
299
+ })
300
+ srv.listen(start, '127.0.0.1')
301
+ })
302
+ }
303
+
304
+ module.exports = {
305
+ Adb, startServer, connectLocal, listenLocal, startReverse, findPort,
306
+ SERVER_VERSION, REMOTE_JAR, SOCKET_NAME
307
+ }