dsh-miniwin 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -22,6 +22,16 @@
22
22
 
23
23
  import { fileURLToPath } from 'node:url'
24
24
  import path from 'node:path'
25
+
26
+ /**
27
+ * 别名。
28
+ *
29
+ * 有的请求处理函数里会 const path = ... 承接 URL 路径,把模块名遮住了 ——
30
+ * 于是 pathMod.join(...) 变成「对一个字符串取 join」,实测报
31
+ * pathMod.join is not a function
32
+ * 表现为手机点「下载 APK」拿 500。统一改用 pathMod,别再被遮。
33
+ */
34
+ const pathMod = path
25
35
  import fs from 'node:fs'
26
36
 
27
37
  /* ==========================================================================
@@ -38,12 +48,12 @@ import fs from 'node:fs'
38
48
  旧的写法是把作者本机的绝对路径写死在源码里 ——
39
49
  只有作者那台机器能跑,别人装上之后扫码出码、投屏起不来。
40
50
  ========================================================================== */
41
- const PKG_DIR = path.dirname(fileURLToPath(import.meta.url)) // <pkg>/lib
51
+ const PKG_DIR = pathMod.dirname(fileURLToPath(import.meta.url)) // <pkg>/lib
42
52
 
43
53
  function runtimeRoot() {
44
54
  if (process.env.MINIWIN_HOME) return process.env.MINIWIN_HOME
45
- const bundled = path.join(PKG_DIR, '..', 'runtime')
46
- if (fs.existsSync(path.join(bundled, 'main.js'))) return bundled
55
+ const bundled = pathMod.join(PKG_DIR, '..', 'runtime')
56
+ if (fs.existsSync(pathMod.join(bundled, 'main.js'))) return bundled
47
57
  throw new Error(
48
58
  'dsh-miniwin: 找不到投屏运行时目录:' + bundled +
49
59
  '。请重新安装插件;如果是从源码目录挂载,设置环境变量 MINIWIN_HOME 指向 miniwin-stream 目录。'
@@ -53,19 +63,168 @@ function runtimeRoot() {
53
63
  /**
54
64
  * 迷你窗用哪个 Electron。
55
65
  *
56
- * DSH 宿主自己就跑在 Electron 里,`process.execPath` 就是 electron.exe ——
57
- * 直接复用宿主,不用在 25MB 运行时之外再塞一份 200MB 的 Electron。
58
- * 宿主不是 Electron 的场合(纯 node 跑),用环境变量指一个。
66
+ * ── 为什么不能直接用 process.execPath ──
67
+ *
68
+ * 上一版写的是「宿主是 Electron,execPath 就是 electron.exe,直接复用」。
69
+ * 实测被打脸:DSH 桌面端的可执行文件叫 **`DSH NEXT.exe`** —— 它确实是
70
+ * Electron 内核,但它是**打包过的**应用(同级有 resources/app.asar),
71
+ * `DSH NEXT.exe <某个脚本>` 只会重新拉起它自己,根本不会跑我们的 main.js。
72
+ * 结果是插件点「启动」直接报:
73
+ *
74
+ * dsh-miniwin: 找不到 Electron 宿主可执行文件(process.execPath=...\DSH NEXT.exe)
75
+ *
76
+ * 用户看到的现象就是「连不上」。
77
+ *
78
+ * ── 现在的查找顺序 ──
79
+ * 1. MINIWIN_ELECTRON 环境变量(显式指定,永远优先)
80
+ * 2. 宿主确实是未打包的 Electron(没有 resources/app.asar)→ 复用它
81
+ * 3. 插件包内 node_modules/electron/dist/electron.exe
82
+ * 4. 工作目录 / 工作目录下一两级的 node_modules/electron/dist/electron.exe
83
+ * (开发机上常见的 `research/_probe/node_modules/electron` 就在这一层被找到)
84
+ * 5. DSH 运行时的 dsh-runtimes 目录里翻一层
85
+ * 6. 全都找不到 → 报错,并明确告诉用户两条出路
86
+ */
87
+ function looksPackaged(exe) {
88
+ try {
89
+ return fs.existsSync(pathMod.join(pathMod.dirname(exe), 'resources', 'app.asar'))
90
+ } catch { return false }
91
+ }
92
+
93
+ function listDirs (dir) {
94
+ try {
95
+ return fs.readdirSync(dir, { withFileTypes: true })
96
+ .filter(d => d.isDirectory() && !d.name.startsWith('.'))
97
+ .map(d => pathMod.join(dir, d.name))
98
+ } catch { return [] }
99
+ }
100
+
101
+ /**
102
+ * 缓存文件:解析成功的 electron 路径落盘。
103
+ *
104
+ * 为什么需要它:DSH 宿主的工作目录不一定是用户的项目目录(可能直接是
105
+ * 安装目录),只按 cwd 猜会漏。第一次全盘搜到之后记下来,下次直接命中,
106
+ * 也省得每次都扫盘。
107
+ */
108
+ function configPath () {
109
+ const home = process.env.USERPROFILE || process.env.HOME || PKG_DIR
110
+ return pathMod.join(home, '.dsh', 'dsh-miniwin.json')
111
+ }
112
+
113
+ function readCachedElectron () {
114
+ try {
115
+ const raw = JSON.parse(fs.readFileSync(configPath(), 'utf8'))
116
+ if (raw && typeof raw.electron === 'string' && fs.existsSync(raw.electron)) return raw.electron
117
+ } catch {}
118
+ return null
119
+ }
120
+
121
+ function writeCachedElectron (exe) {
122
+ try {
123
+ const p = configPath()
124
+ let cfg = {}
125
+ try { cfg = JSON.parse(fs.readFileSync(p, 'utf8')) } catch {}
126
+ cfg.electron = exe
127
+ fs.mkdirSync(pathMod.dirname(p), { recursive: true })
128
+ fs.writeFileSync(p, JSON.stringify(cfg, null, 2))
129
+ } catch {}
130
+ }
131
+
132
+ /**
133
+ * 有界深搜:从几个根往下找 `<某个目录>/node_modules/electron/dist/electron.exe`。
134
+ *
135
+ * 约束:最多 6 层、最多访问 20000 个目录、3 秒硬超时,遇到 node_modules
136
+ * 就不再往里钻(只在它下面按固定相对路径查一次),跳过 AppData / .git /
137
+ * Windows 这类明显的无底洞。命中即返回。
59
138
  */
139
+ const SKIP_DIRS = new Set(['appdata', 'windows', 'program files', 'program files (x86)',
140
+ 'programdata', '$recycle.bin', 'system volume information', '.git', '.cache',
141
+ '.npm', '.pnpm-store', '.vscode', '.cursor', 'dist', 'out', 'build'])
142
+
143
+ function deepFindElectron (roots) {
144
+ const t0 = Date.now()
145
+ const seen = new Set()
146
+ let visited = 0
147
+ const queue = roots.filter(Boolean).map(r => ({ dir: r, depth: 0 }))
148
+ while (queue.length) {
149
+ if (Date.now() - t0 > 3000 || visited > 20000) break
150
+ const { dir, depth } = queue.shift()
151
+ if (seen.has(dir) || depth > 6) continue
152
+ seen.add(dir)
153
+ visited++
154
+ const direct = pathMod.join(dir, 'node_modules', 'electron', 'dist', 'electron.exe')
155
+ try { if (fs.existsSync(direct)) return direct } catch {}
156
+ if (dir.toLowerCase().endsWith('node_modules')) continue
157
+ let entries = []
158
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue }
159
+ for (const e of entries) {
160
+ if (!e.isDirectory()) continue
161
+ const name = e.name.toLowerCase()
162
+ if (SKIP_DIRS.has(name) || name.startsWith('.')) continue
163
+ queue.push({ dir: pathMod.join(dir, e.name), depth: depth + 1 })
164
+ }
165
+ }
166
+ return null
167
+ }
168
+
60
169
  function resolveElectron() {
61
170
  if (process.env.MINIWIN_ELECTRON) return process.env.MINIWIN_ELECTRON
171
+
172
+ // 上次解析成功过就直接用
173
+ const cached = readCachedElectron()
174
+ if (cached) return cached
175
+
62
176
  const exe = process.execPath || ''
63
- if (/^electron(\.exe)?$/i.test(path.basename(exe))) return exe
64
- const sibling = path.join(path.dirname(exe), 'electron.exe')
65
- if (fs.existsSync(sibling)) return sibling
177
+ const isElectronHost = !!(process.versions && process.versions.electron)
178
+ if (isElectronHost && exe && !looksPackaged(exe)) {
179
+ writeCachedElectron(exe)
180
+ return exe
181
+ }
182
+
183
+ const rel = ['node_modules', 'electron', 'dist', 'electron.exe']
184
+ const cands = []
185
+
186
+ // 插件包内(如果有人把它装成依赖)与它旁边一层
187
+ cands.push(pathMod.join(PKG_DIR, '..', ...rel))
188
+ cands.push(pathMod.join(PKG_DIR, '..', '..', ...rel))
189
+
190
+ // 工作目录及其下两级(覆盖 <cwd>/xxx/node_modules 这种布局)
191
+ const cwd = process.cwd()
192
+ cands.push(pathMod.join(cwd, ...rel))
193
+ for (const d1 of listDirs(cwd)) {
194
+ cands.push(pathMod.join(d1, ...rel))
195
+ for (const d2 of listDirs(d1)) cands.push(pathMod.join(d2, ...rel))
196
+ }
197
+
198
+ // DSH 运行时目录
199
+ const home = process.env.USERPROFILE || process.env.HOME || ''
200
+ if (home) {
201
+ const rt = pathMod.join(home, '.dsh', 'dsh-runtimes')
202
+ for (const d1 of listDirs(rt)) {
203
+ cands.push(pathMod.join(d1, ...rel))
204
+ for (const d2 of listDirs(d1)) cands.push(pathMod.join(d2, ...rel))
205
+ cands.push(pathMod.join(d1, 'dependencies', 'electron', 'dist', 'electron.exe'))
206
+ }
207
+ }
208
+
209
+ for (const c of cands) {
210
+ try {
211
+ if (c && fs.existsSync(c)) { writeCachedElectron(c); return c }
212
+ } catch {}
213
+ }
214
+
215
+ // 兜底:有界深搜(cwd / 用户目录 / DSH_HOME)
216
+ const hit = deepFindElectron([cwd, home, process.env.DSH_HOME])
217
+ if (hit) {
218
+ writeCachedElectron(hit)
219
+ return hit
220
+ }
221
+
222
+
66
223
  throw new Error(
67
- 'dsh-miniwin: 找不到 Electron 宿主可执行文件(process.execPath=' + exe +
68
- ')。如果宿主不是 Electron,设置环境变量 MINIWIN_ELECTRON 指向 electron.exe。'
224
+ 'dsh-miniwin: 找不到可用的 Electron(迷你窗需要一个真正的 electron.exe,' +
225
+ '而宿主 ' + (exe || '未知') + ' 是打包过的应用,不能拿来跑脚本)。' +
226
+ '两条出路:① 设置环境变量 MINIWIN_ELECTRON 指向任意 electron.exe;' +
227
+ '② 在与 DSH 相同的工作目录里装一份 `npm i -D electron`。'
69
228
  )
70
229
  }
71
230
 
@@ -195,7 +354,7 @@ async function resolveNodeBin() {
195
354
  if (process.env.DSH_HOME) roots.push(process.env.DSH_HOME)
196
355
  if (process.resourcesPath) {
197
356
  roots.push(process.resourcesPath) // <install>/resources
198
- roots.push(path.dirname(process.resourcesPath)) // <install>
357
+ roots.push(pathMod.dirname(process.resourcesPath)) // <install>
199
358
  }
200
359
  const rels = [
201
360
  'runtime/x64/primary-runtime/dependencies/node/bin/node.exe',
@@ -204,7 +363,7 @@ async function resolveNodeBin() {
204
363
  'node/bin/node.exe'
205
364
  ]
206
365
  for (const r of roots) {
207
- for (const rel of rels) candidates.push(path.join(r, rel))
366
+ for (const rel of rels) candidates.push(pathMod.join(r, rel))
208
367
  }
209
368
 
210
369
  // PATH 里的 node
@@ -515,7 +674,7 @@ async function startLanServer(onPair, onConnect, onLaunch, getState) {
515
674
  if ((req.method === 'GET' || req.method === 'HEAD') && routePath === '/app.apk') {
516
675
  try {
517
676
  const fs = await import('node:fs')
518
- const apkPath = path.join(runtimeRoot(), 'apk', 'miniwin.apk')
677
+ const apkPath = pathMod.join(runtimeRoot(), 'apk', 'miniwin.apk')
519
678
  const stat = fs.statSync(apkPath)
520
679
  res.writeHead(200, {
521
680
  'Content-Type': 'application/vnd.android.package-archive',
@@ -1072,7 +1231,13 @@ function apply(ctx) {
1072
1231
  * 3. 返回手机要扫的深链
1073
1232
  * 手机装过 APK 后扫这个码 → App 自动填地址 → 点允许 → 画面出现。
1074
1233
  */
1075
- route('POST', ROUTE_BASE + '/wifi-start', async (req, res) => {
1234
+ /**
1235
+ * WiFi(APK 推流)模式的完整启动流程。
1236
+ *
1237
+ * 抽成具名函数是因为 /launch 也要用它:没有 adb 设备时,
1238
+ * 点「启动迷你窗」不该走去等 adb 的那条路(那条要等 3 分钟)。
1239
+ */
1240
+ const startWifiMode = async (req, res) => {
1076
1241
  try {
1077
1242
  const { spawn } = await import('node:child_process')
1078
1243
  const m = await loadMiniwin()
@@ -1171,7 +1336,9 @@ function apply(ctx) {
1171
1336
  pushLog('error', 'wifi-start 异常: ' + String((e && e.stack) || e).slice(0, 400))
1172
1337
  sendJson(res, 500, { ok: false, error: String((e && e.message) || e) })
1173
1338
  }
1174
- })
1339
+ }
1340
+
1341
+ route('POST', ROUTE_BASE + '/wifi-start', startWifiMode)
1175
1342
 
1176
1343
  /* ---------- 本机地址(给 PC 端生成二维码用) ---------- */
1177
1344
  route('GET', ROUTE_BASE + '/addrs', async (req, res) => {
@@ -1722,7 +1889,7 @@ function apply(ctx) {
1722
1889
  function adbPath() {
1723
1890
  if (process.env.MINIWIN_ADB) return process.env.MINIWIN_ADB
1724
1891
  try {
1725
- return path.join(runtimeRoot(), 'tools', 'scrcpy', 'scrcpy-win64-v5.0.1', 'adb.exe')
1892
+ return pathMod.join(runtimeRoot(), 'tools', 'scrcpy', 'scrcpy-win64-v5.0.1', 'adb.exe')
1726
1893
  } catch {
1727
1894
  // 运行时没就位时不要让设备发现直接崩,退回 PATH 里的 adb
1728
1895
  return 'adb'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-miniwin",
3
- "version": "0.3.0",
3
+ "version": "0.3.3",
4
4
  "description": "Phone screen mirroring in the DSH sidebar: scan a QR code to pair, then the phone screen opens in a transparent desktop mini-window. Ships its own scrcpy runtime; audio follows a headset-aware routing policy and starts muted on both ends.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -37,8 +37,9 @@ class AudioRouter {
37
37
  }
38
38
 
39
39
  _run (args, timeout = 8000) {
40
+ const full = this.serial ? ['-s', this.serial, ...args] : args
40
41
  return new Promise((resolve) => {
41
- execFile(this.adb, ['-s', this.serial, ...args], { timeout, windowsHide: true },
42
+ execFile(this.adb, full, { timeout, windowsHide: true },
42
43
  (err, stdout, stderr) => resolve({ ok: !err, out: String(stdout || ''), err: String(stderr || '') }))
43
44
  })
44
45
  }
@@ -55,8 +56,17 @@ class AudioRouter {
55
56
  }
56
57
 
57
58
  async poll () {
58
- const { out } = await this._run(['shell', 'dumpsys audio'])
59
- const p = AudioRouter.parse(out)
59
+ /**
60
+ * 没有 adb 通道时(纯 WiFi、手机没开 tcpip 也没插线),
61
+ * 拿不到 dumpsys —— 这时候不能盲判成「外放」把手机静音掉。
62
+ * 我们只保留「/meta 的手机音量」这一路,headset 记为未知(false),
63
+ * 由上层决定降级行为;投屏侧音量仍然默认 0。
64
+ */
65
+ let p = { devices: [], streamVolume: 0 }
66
+ if (this.serial) {
67
+ const { out } = await this._run(['shell', 'dumpsys audio'])
68
+ p = AudioRouter.parse(out)
69
+ }
60
70
  const headset = p.devices.some(d => HEADSET_DEVICES.includes(d))
61
71
  const speaker = p.devices.some(d => SPEAKER_DEVICES.includes(d))
62
72
 
@@ -128,6 +138,7 @@ class AudioRouter {
128
138
 
129
139
  /** 规则 2:外放时连接即双端静音(用音量键把媒体音量降到 0) */
130
140
  async mutePhone () {
141
+ if (!this.serial) return
131
142
  // `cmd media_session` 一条命令就能把媒体音量设到 0,比连按音量键干净得多
132
143
  const r = await this._run(['shell', 'cmd media_session volume --stream 3 --set 0'])
133
144
  if (r.ok) {
@@ -150,6 +161,8 @@ class AudioRouter {
150
161
  * 不 force-stop 的话耳机里也没声。
151
162
  */
152
163
  async killApk () {
164
+ /** 没有 adb 通道(纯 WiFi)时做不到,直接跳过 —— 别让 adb 报「no devices」刷屏 */
165
+ if (!this.serial) return
153
166
  await this._run(['shell', `am force-stop ${this.apkPackage}`])
154
167
  this.onLog(`[audio] 已停止手机端 ${this.apkPackage}`)
155
168
  }
package/runtime/main.js CHANGED
@@ -3151,6 +3151,79 @@ async function bootWindow () {
3151
3151
  */
3152
3152
  win.webContents.on('did-finish-load', () => { replayStateToRenderer() })
3153
3153
 
3154
+ /**
3155
+ * ══════════ WiFi 模式:把流地址交给渲染层 ══════════
3156
+ *
3157
+ * 这里曾经是个致命缺口:`--wifi <url>` 解析出来了,却**从来没有人把它
3158
+ * 发给渲染层** —— ui.html 里的 `onWifiStart` 监听器永远等不到事件,
3159
+ * 于是 WiFi 模式下窗口就是一块占位图,用户看到的是「连不上」。
3160
+ *
3161
+ * 现在每次加载完成都发一次(页面重载后也能自己恢复),
3162
+ * 渲染层收到就开始长轮询 /frames 拉画面 + 起 WifiAudio 播放声音。
3163
+ */
3164
+ if (wifiSource) {
3165
+ const sendWifiStart = () => {
3166
+ if (!win || win.isDestroyed()) return
3167
+ try {
3168
+ win.webContents.send('wifi:start', { source: wifiSource })
3169
+ logLine('info', '[wifi] 已通知渲染层拉流: ' + wifiSource)
3170
+ } catch (e) { logLine('warn', '[wifi] 通知渲染层失败: ' + e.message) }
3171
+ }
3172
+ win.webContents.on('did-finish-load', sendWifiStart)
3173
+ sendWifiStart()
3174
+ /**
3175
+ * 首帧加载时的竞态:bootWindow() 是 await loadFile 回来的,此时
3176
+ * did-finish-load 已经过去,而渲染层的监听器可能刚注册完 —— 一条事件
3177
+ * 丢了就是「窗口一直空白」。补两次延迟发送,渲染层用 wifiRunning 去重,
3178
+ * 多发无害。
3179
+ */
3180
+ setTimeout(sendWifiStart, 700)
3181
+ setTimeout(sendWifiStart, 2200)
3182
+
3183
+ /**
3184
+ * WiFi 模式下的音频策略。
3185
+ *
3186
+ * 复用同一套 AudioRouter:
3187
+ * · 有 adb 通道 → 能识别耳机,完整规则生效
3188
+ * · 没有 adb → 耳机不可知,按外放处理(投屏音量默认 0,
3189
+ * 手机端由 APK 自己锁 0),手机音量键仍能遥控投屏音量
3190
+ * 投屏音量 = 渲染层本地增益,永远不会写回手机。
3191
+ */
3192
+ ;(async () => {
3193
+ try {
3194
+ const { AudioRouter } = require('./audio-router.js')
3195
+ let serial = null
3196
+ try {
3197
+ const adb = new Adb(adbPath())
3198
+ const list = await adb.devices()
3199
+ const ready = list.filter(d => d.state === 'device')
3200
+ if (ready.length) serial = ready[0].serial
3201
+ } catch {}
3202
+ const httpPort = (() => {
3203
+ try { return Number(new URL(wifiSource).port) || 0 } catch { return 0 }
3204
+ })()
3205
+ const router = new AudioRouter({
3206
+ adb: adbPath(),
3207
+ serial,
3208
+ httpPort,
3209
+ apkPackage: 'com.miniwin.stream',
3210
+ onLog: (m) => logLine('info', m),
3211
+ onState: (st) => { try { win && win.webContents.send('audio:state', st) } catch {} }
3212
+ })
3213
+ await router.poll()
3214
+ router.setPcVolume(0)
3215
+ router.start()
3216
+ app.on('will-quit', () => { try { router.stop() } catch {} })
3217
+ logLine(serial ? 'info' : 'warn',
3218
+ serial
3219
+ ? '[audio] WiFi 模式:音频策略已接管,能识别耳机(' + serial + ')'
3220
+ : '[audio] WiFi 模式:没有 adb 通道,耳机状态无法探测,按外放处理(投屏音量默认 0)')
3221
+ } catch (e) {
3222
+ logLine('warn', '[audio] WiFi 模式音频策略初始化失败: ' + e.message)
3223
+ }
3224
+ })()
3225
+ }
3226
+
3154
3227
  /**
3155
3228
  * ══════════ Esc 只在窗口有焦点时才退出 ══════════
3156
3229
  *
@@ -0,0 +1,133 @@
1
+ 'use strict'
2
+ /**
3
+ * 手机扫码后打开的「配对页」。
4
+ *
5
+ * ── 这个文件为什么曾经是空的 ──
6
+ *
7
+ * wifi-receiver.js 里有 `require('./pair-page.js')`,但仓库里根本没有这个文件:
8
+ * 一访问 /pair 就抛 MODULE_NOT_FOUND,**整个接收端进程直接退出**。
9
+ * 用户看到的现象就是「纯 WiFi 连不上」:二维码扫开是空白,随后连 APK
10
+ * 推流也一起断了(同一个进程)。
11
+ *
12
+ * 现在的实现:一张自包含的页面,不依赖任何外网资源。
13
+ * ① 无线调试配对(Android 11+):填「IP:端口」+ 6 位配对码 → POST /pair
14
+ * ② 配对成功后自动 POST /start-zero 起传输
15
+ * ③ 上面两条走不通时,页面直接给出 APK 下载入口(走 App 推流那条路)
16
+ */
17
+
18
+ function esc (s) {
19
+ return String(s == null ? '' : s)
20
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
21
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;')
22
+ }
23
+
24
+ /**
25
+ * @param {string} lanIp PC 的局域网 IP(页面会用到)
26
+ * @param {number} port 接收端 HTTP 端口(页面里的请求都打自己所在的 origin)
27
+ */
28
+ function pairPageHtml (lanIp, port) {
29
+ const ip = esc(lanIp)
30
+ const p = Number(port) || 0
31
+ return `<!doctype html>
32
+ <html lang="zh-CN">
33
+ <head>
34
+ <meta charset="utf-8">
35
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
36
+ <meta name="theme-color" content="#0b0e14">
37
+ <title>MiniWin 投屏配对</title>
38
+ <style>
39
+ :root{color-scheme:dark}
40
+ *{box-sizing:border-box}
41
+ body{margin:0;min-height:100dvh;padding:24px 18px calc(28px + env(safe-area-inset-bottom));
42
+ background:#0b0e14;color:#e9ebf2;
43
+ font:15px/1.6 -apple-system,"PingFang SC","HarmonyOS Sans SC",system-ui,sans-serif}
44
+ h1{font-size:19px;margin:6px 0 4px}
45
+ .sub{color:rgba(233,235,242,.55);font-size:13px;margin-bottom:22px}
46
+ .card{background:#141922;border:1px solid rgba(255,255,255,.09);border-radius:14px;padding:16px;margin-bottom:16px}
47
+ .card h2{font-size:14px;margin:0 0 10px;font-weight:600;color:rgba(233,235,242,.9)}
48
+ label{display:block;font-size:12px;color:rgba(233,235,242,.55);margin:10px 0 4px}
49
+ input{width:100%;padding:11px 12px;border-radius:10px;border:1px solid rgba(255,255,255,.14);
50
+ background:#0e1219;color:#e9ebf2;font:inherit;font-variant-numeric:tabular-nums}
51
+ input:focus{outline:none;border-color:#4a90f8}
52
+ button{width:100%;margin-top:14px;padding:13px;border:0;border-radius:11px;
53
+ background:linear-gradient(180deg,#4a90f8,#2b6fe0);color:#fff;font:600 15px/1 inherit;letter-spacing:.02em}
54
+ button:disabled{opacity:.5}
55
+ .alt{margin-top:12px;padding:13px;border-radius:11px;border:1px solid rgba(255,255,255,.14);
56
+ background:transparent;color:#a9ccff;font-weight:600;text-align:center;display:block;text-decoration:none}
57
+ .hint{font-size:12px;color:rgba(233,235,242,.45);margin-top:8px}
58
+ .msg{margin-top:14px;padding:11px 12px;border-radius:10px;font-size:13px;display:none;white-space:pre-wrap}
59
+ .msg.ok{display:block;background:rgba(61,220,132,.12);border:1px solid rgba(61,220,132,.3);color:#9ff0c4}
60
+ .msg.err{display:block;background:rgba(255,93,85,.12);border:1px solid rgba(255,93,85,.3);color:#ffb3ae}
61
+ .ip{font-family:Consolas,monospace;color:#a9ccff}
62
+ </style>
63
+ </head>
64
+ <body>
65
+ <h1>MiniWin 投屏配对</h1>
66
+ <div class="sub">电脑:<span class="ip">${ip}${p ? ':' + p : ''}</span></div>
67
+
68
+ <div class="card">
69
+ <h2>方式一 · 无线调试配对(Android 11+)</h2>
70
+ <label>配对地址(手机:开发者选项 → 无线调试 → 使用配对码配对设备)</label>
71
+ <input id="addr" placeholder="192.168.1.23:38571" autocapitalize="off" autocomplete="off" spellcheck="false">
72
+ <label>6 位配对码</label>
73
+ <input id="code" placeholder="123456" inputmode="numeric" maxlength="6" autocomplete="one-time-code">
74
+ <button id="go">配对并开始投屏</button>
75
+ <div class="hint">配对成功后手机会被 adb 接管,电脑上的迷你窗会自己亮起来。</div>
76
+ </div>
77
+
78
+ <div class="card">
79
+ <h2>方式二 · 装 App(任何安卓版本都行)</h2>
80
+ <a class="alt" href="/app.apk">下载 MiniWin 投屏 APK</a>
81
+ <div class="hint">装好后点开 App,它会把画面和声音直接推给这台电脑,不需要 adb。</div>
82
+ </div>
83
+
84
+ <div id="msg" class="msg"></div>
85
+
86
+ <script>
87
+ (function () {
88
+ var addr = document.getElementById('addr')
89
+ var code = document.getElementById('code')
90
+ var btn = document.getElementById('go')
91
+ var msg = document.getElementById('msg')
92
+
93
+ function say (text, kind) {
94
+ msg.className = 'msg ' + (kind || 'ok')
95
+ msg.textContent = text
96
+ }
97
+
98
+ function post (path, body) {
99
+ return fetch(path, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/json' },
102
+ body: JSON.stringify(body || {})
103
+ }).then(function (r) { return r.json() })
104
+ }
105
+
106
+ btn.addEventListener('click', function () {
107
+ var a = (addr.value || '').trim()
108
+ var c = (code.value || '').trim()
109
+ if (!/^\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+$/.test(a)) return say('配对地址要写成 IP:端口', 'err')
110
+ if (!/^\\d{6}$/.test(c)) return say('配对码是 6 位数字', 'err')
111
+
112
+ btn.disabled = true
113
+ say('正在配对…')
114
+ post('/pair', { addr: a, code: c })
115
+ .then(function (r) {
116
+ if (!r || !r.ok) throw new Error((r && r.error) || '配对失败')
117
+ say('配对成功,正在连接…')
118
+ return post('/start-zero', { addr: a, wlanPort: r.wlanPort })
119
+ })
120
+ .then(function (r) {
121
+ if (!r || !r.ok) throw new Error((r && r.error) || '连接失败')
122
+ say('已连上。看电脑上的迷你窗,画面应该出来了。')
123
+ })
124
+ .catch(function (e) { say(String(e.message || e), 'err') })
125
+ .finally(function () { btn.disabled = false })
126
+ })
127
+ })()
128
+ </script>
129
+ </body>
130
+ </html>`
131
+ }
132
+
133
+ module.exports = { pairPageHtml }
File without changes
@@ -0,0 +1,32 @@
1
+ 'use strict'
2
+ /**
3
+ * 零 APK 直连的 scrcpy 传输层。
4
+ *
5
+ * ── 现状 ──
6
+ *
7
+ * wifi-receiver.js 的 /start-zero 会 `require('./scrcpy-transport.js')`,
8
+ * 但这个模块从来没有进过仓库。以前它的后果被 pair-page.js 的崩溃掩盖了;
9
+ * 现在 pair-page 修好了,走到这里会抛出明确的错误,而不是让整个接收端
10
+ * 进程挂掉。
11
+ *
12
+ * ── 为什么先不实现 ──
13
+ *
14
+ * 真正的实现要跑完整的 scrcpy 控制协议(握手 → video socket + control
15
+ * socket → 自己解 SPS/PPS → 转发 input 事件)。而这条路只在
16
+ * 「Android 11+ 无线调试 + 不想装 App」时才用得上,且**必须先有 adb 通道**
17
+ * (adb pair + adb connect)。本机实测的结论是:装了 APK 的推流链路
18
+ * 更稳、帧率更高、还带声音。
19
+ *
20
+ * 所以这里给出一个显式失败,让上层把原因原样回给手机页面:
21
+ * 用户看到的是「这条通道没打包,请用 App」,而不是一个转圈。
22
+ */
23
+ class ScrcpyTransport {
24
+ constructor () {
25
+ throw new Error(
26
+ '零 APK 直连(scrcpy 传输层)在当前版本未打包。' +
27
+ '请改用手机端 MiniWin 投屏 App 推流(方式二),或先用 adb 连上手机走 scrcpy 采集。'
28
+ )
29
+ }
30
+ }
31
+
32
+ module.exports = { ScrcpyTransport }
@@ -0,0 +1,479 @@
1
+ /**
2
+ * WiFi 模式音频播放。
3
+ *
4
+ * 链路:手机 AudioPlaybackCapture → AAC 编码 → TCP → wifi-receiver
5
+ * → HTTP /audio → 这里 → WebCodecs AudioDecoder → Web Audio 输出
6
+ *
7
+ * ── 为什么不能简单 Audio 标签播 ──
8
+ *
9
+ * 收到的是裸 AAC 帧(ADTS 之外的 raw AAC + AudioSpecificConfig),
10
+ * 不是 mp4/m4a 这种容器,Audio 元素无法直接播放。
11
+ * WebCodecs 的 AudioDecoder 正好能吃这种输入。
12
+ *
13
+ * ── 音频时钟 ──
14
+ *
15
+ * 音频对时间极其敏感:早 200ms 或晚 200ms 都能听出来(爆音/断续)。
16
+ * 解码出来的 AudioData 自带 timestamp,但「什么时候该送到扬声器」
17
+ * 需要一个自己的时钟来排程。
18
+ *
19
+ * 这里用最简单的做法:每个解码出来的 AudioBuffer 直接
20
+ * schedule 到 currentTime + 小缓冲(30ms),靠 Web Audio 自己的
21
+ * 调度保证连续性。不做重采样、不做变速 —— 网络抖动通过
22
+ * 「积压就丢旧帧」来吸收。
23
+ */
24
+
25
+ export class WifiAudio {
26
+ constructor (source) {
27
+ this.source = source
28
+ this.ctx = null
29
+ this.decoder = null
30
+ this.running = false
31
+ this.ready = false
32
+ this.config = null
33
+
34
+ // 播放调度:下一次该排到的时间点
35
+ this.nextTime = 0
36
+ this.gain = null
37
+
38
+ // 统计
39
+ this.decoded = 0
40
+ this.dropped = 0
41
+ this.bytes = 0
42
+ /** 排程重置次数(延迟纠正)。持续增长说明抖动大,但不影响正确性。 */
43
+ this.resyncs = 0
44
+ /** 因积压被跳过的帧数 */
45
+ this.skips = 0
46
+ /** jitter buffer 状态 */
47
+ this._buffered = 0
48
+ this._started = false
49
+ /**
50
+ * PCM 队列:解码输出在这里排队,由排程泵均匀消耗。
51
+ * 解码(受网络影响,节奏不均)和排程(恒定节奏)解耦,
52
+ * 网络抖动在这里被吸收 —— 这是消除长时间卡顿的核心。
53
+ */
54
+ this.pcmQueue = []
55
+ /** 暂停状态:暂停时不解码也不播放,继续消费队列避免积压 */
56
+ this.paused = false
57
+ /** 目标音量(0..1)。暂停时 gain 归零,恢复时用它还原。 */
58
+ this._volume = 1
59
+ /**
60
+ * 所有已排程但还在播的 source。
61
+ *
62
+ * 暂停时必须逐个 stop() —— 只把 gain 归零的话,
63
+ * AudioContext 内部那些已排程的 buffer 仍在跑,
64
+ * 恢复时会和新的排程重叠,听起来像回声。
65
+ */
66
+ this._sources = new Set()
67
+
68
+ this._onLog = null
69
+ }
70
+
71
+ log (level, msg) {
72
+ if (this._onLog) this._onLog(level, msg)
73
+ }
74
+
75
+ onLog (fn) { this._onLog = fn }
76
+
77
+ /**
78
+ * 启动。
79
+ *
80
+ * AudioContext 必须在用户手势之后才能 started(浏览器自动播放策略),
81
+ * 但 Electron 里默认允许,所以这里直接创建;万一被挂起,
82
+ * 下面 resume() 会再试一次。
83
+ */
84
+ async start () {
85
+ if (this.running && this.ready) return { ok: true }
86
+ this.running = true
87
+
88
+ try {
89
+ // 1. 拿 AudioSpecificConfig
90
+ const cfgRes = await fetch(this.source + '/audio-config', { cache: 'no-store' })
91
+ if (cfgRes.status === 204) {
92
+ /**
93
+ * 还没有音频配置。
94
+ *
95
+ * 这是可重试状态,不是错误 —— 手机端可能还没连上、
96
+ * 或者刚重连还没补发配置。调用方会隔一会儿再试。
97
+ * 注意这里要把 running 复位,否则下次 start() 会以为已经在跑。
98
+ */
99
+ this.running = false
100
+ return { ok: false, error: 'no-audio' }
101
+ }
102
+ if (!cfgRes.ok) throw new Error('HTTP ' + cfgRes.status)
103
+ this.config = new Uint8Array(await cfgRes.arrayBuffer())
104
+ this.log('ok', '音频配置 ' + this.config.length + ' 字节')
105
+
106
+ // 2. 建 AudioContext + 解码器
107
+ const AC = window.AudioContext || window.webkitAudioContext
108
+ this.ctx = new AC({ sampleRate: 44100, latencyHint: 'interactive' })
109
+ if (this.ctx.state === 'suspended') {
110
+ try { await this.ctx.resume() } catch {}
111
+ }
112
+
113
+ this.gain = this.ctx.createGain()
114
+ this.gain.gain.value = 1
115
+ this.gain.connect(this.ctx.destination)
116
+
117
+ if (typeof AudioDecoder === 'undefined') {
118
+ throw new Error('当前环境不支持 WebCodecs AudioDecoder')
119
+ }
120
+
121
+ this.decoder = new AudioDecoder({
122
+ output: (data) => this._onAudioData(data),
123
+ error: (e) => this.log('error', '音频解码错误: ' + e.message)
124
+ })
125
+
126
+ /**
127
+ * 配置解码器。
128
+ *
129
+ * codec 字符串必须和实际编码匹配:'mp4a.40.2' = AAC-LC,
130
+ * 对应手机侧 MediaCodec 的 AACObjectLC。
131
+ * sampleRate / numberOfChannels 要和编码参数一致,
132
+ * description 就是 AudioSpecificConfig。
133
+ */
134
+ this.decoder.configure({
135
+ codec: 'mp4a.40.2',
136
+ sampleRate: 44100,
137
+ numberOfChannels: 2,
138
+ description: this.config
139
+ })
140
+
141
+ this.ready = true
142
+ this.log('ok', '音频解码器就绪')
143
+ this._pullLoop()
144
+ // 启动排程泵
145
+ if (!this._raf) this._pump()
146
+ return { ok: true }
147
+ } catch (e) {
148
+ this.running = false
149
+ this.log('error', '音频启动失败: ' + e.message)
150
+ return { ok: false, error: String(e.message || e) }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * 拉音频帧(批量 + 挂起等待)。
156
+ *
157
+ * ── 批量大小的权衡(实测结论)──
158
+ *
159
+ * 小批量(n=6)的初衷是拉平节奏,但实测暴露新问题:
160
+ * 服务端的音频生产本身是突发的(App 编码器 + TCP Nagle 聚合),
161
+ * 队列经常不足 6 帧 → 长轮询等 400ms 超时回 204 → 大量空转。
162
+ * 实测 10 次拉流拿到 11 帧,而播放需要 43 帧/秒 —— 供给严重不足。
163
+ *
164
+ * 改回大批量(n=24)+不设超时上限:批次大意味着
165
+ * 「等更久但一次拿更多」,平均吞吐不变,空转减少。
166
+ * 抖动由排程泵的 PCM 队列吸收(3 秒容量),不需要拉流侧实时。
167
+ */
168
+ async _pullLoop () {
169
+ let lastPts = -1
170
+ this._buffered = 0
171
+ let consecutiveErrors = 0
172
+ while (this.running) {
173
+ try {
174
+ const r = await fetch(this.source + '/audio?n=24&wait=900', { cache: 'no-store' })
175
+ if (r.status === 204) continue
176
+ if (!r.ok) throw new Error('HTTP ' + r.status)
177
+ consecutiveErrors = 0
178
+
179
+ const buf = await r.arrayBuffer()
180
+ const dv = new DataView(buf)
181
+ const count = dv.getUint32(0)
182
+ let off = 4
183
+
184
+ for (let i = 0; i < count; i++) {
185
+ const pts = dv.getFloat64(off); off += 8
186
+ const len = dv.getUint32(off); off += 4
187
+ const data = new Uint8Array(buf, off, len)
188
+ off += len
189
+
190
+ this.bytes += len
191
+
192
+ /**
193
+ * 暂停期间:继续拉取但不解码。
194
+ *
195
+ * 为什么还要拉:不拉的话接收端队列会堆满,
196
+ * 恢复瞬间会一次性灌进来几百帧旧音频,
197
+ * 要么爆一段过期的声音、要么得等它排空才好。
198
+ * 现在这样「拉了就丢」,恢复时从最新的帧开始,延迟是 0。
199
+ */
200
+ if (this.paused) continue
201
+
202
+ /**
203
+ * 时间戳单调化。
204
+ *
205
+ * AudioDecoder 要求每个 chunk 的 timestamp 严格递增。
206
+ * 网络抖动可能让包乱序到达,或者 pts 相同,
207
+ * 那样解码器会报 "timestamp must be increasing" 然后停摆。
208
+ *
209
+ * 这里强制 +1 保证严格递增 —— 音频播放靠的是
210
+ * AudioContext 的排程,chunk 上的 timestamp 只用于
211
+ * 内部排序,+1 微秒的偏差听不出来。
212
+ */
213
+ let ts = Math.max(0, Math.round(pts))
214
+ if (ts <= lastPts) ts = lastPts + 1
215
+ lastPts = ts
216
+
217
+ try {
218
+ this.decoder.decode(new EncodedAudioChunk({
219
+ type: 'key', // AAC 每帧都是独立可解的,全是 key
220
+ timestamp: ts,
221
+ data
222
+ }))
223
+ } catch (e) {
224
+ this.dropped++
225
+ }
226
+ }
227
+ } catch (e) {
228
+ if (!this.running) break
229
+ this.log('warn', '音频拉流中断: ' + e.message)
230
+ await new Promise(z => setTimeout(z, 500))
231
+ }
232
+ }
233
+ }
234
+
235
+ /**
236
+ * 解码出来一帧 PCM,排程播放。
237
+ *
238
+ * 关键点:nextTime 的推进。
239
+ * - 正常情况下 nextTime 就等于上一帧的结束时间,实现无缝拼接
240
+ * - 如果 nextTime 落后于当前时间太多(说明卡了/积压了),
241
+ * 直接跳到 now + 30ms,丢掉这段延迟 —— 宁可漏一点也不要
242
+ * 让声音越拖越晚(那样会累积成几秒的延迟)
243
+ */
244
+ /**
245
+ * 解码出来一帧 PCM,排程播放。
246
+ *
247
+ * ── 延迟为什么会越积越大 ──
248
+ *
249
+ * 原来只在 nextTime **落后** 于当前时间时才重置:
250
+ * if (this.nextTime < now) this.nextTime = now + 0.03
251
+ *
252
+ * 但真正的延迟来自 **nextTime 超前**:每次排程都往后推一个帧长,
253
+ * 只要解码速度略快于播放速度(网络突发、批量取帧都会造成),
254
+ * nextTime 就一路往后跑,永远不回头 —— 几分钟后声音能落后十几秒。
255
+ *
256
+ * 这就是「越用越延迟」的根因。
257
+ *
258
+ * ── 现在的做法 ──
259
+ *
260
+ * 给 nextTime 设一个上界 LATENCY 之外的漂移就拉回来:
261
+ * - 落后于 now → 直接重置到 now + TARGET
262
+ * - 超前 now 超过 LATENCY → 也重置(说明排程堆积了)
263
+ * - 两者之间 → 正常续接,保证无缝
264
+ *
265
+ * LATENCY 取 120ms:低于人耳对音画不同步的容忍阈值(
266
+ * 视频一般 150~200ms 才明显),又不至于频繁重置造成爆音。
267
+ */
268
+ /**
269
+ * 解码出来一帧 PCM → 进 PCM 队列(不直接排程)。
270
+ *
271
+ * ── 为什么解耦 ──
272
+ *
273
+ * 之前的做法是「解码一帧排一帧」:排程时刻由解码时刻决定,
274
+ * 而解码时刻取决于网络批次到达。批次之间一旦有空窗,
275
+ * 排程前沿(nextTime)就跟着掉,跌到 currentTime 以下
276
+ * → 触发 resync 硬跳 → 可闻卡顿。实测 lag 轨迹是
277
+ * 0.067 → -0.022 → -0.121 → -0.223 → 跳回 0.017 的锯齿。
278
+ *
279
+ * 现在分成两级:
280
+ * 一级:解码线程(受网络批次影响,节奏不均)→ 写进 pcmQueue
281
+ * 二级:排程线程(requestAnimationFrame 驱动,节奏恒定)
282
+ * → 只要队列里有货就按 nextTime 匀速排
283
+ *
284
+ * 网络抖动被 pcmQueue 吸收:队列空了排程线程也不会把
285
+ * nextTime 拉到 currentTime 以下,而是等队列来货再继续,
286
+ * 前沿保持稳定,不再锯齿。
287
+ */
288
+ _onAudioData (data) {
289
+ try {
290
+ const ch = data.numberOfChannels
291
+ const frames = data.numberOfFrames
292
+ if (!frames) { data.close(); return }
293
+
294
+ const ab = this.ctx.createBuffer(ch, frames, data.sampleRate)
295
+ for (let c = 0; c < ch; c++) {
296
+ const dst = ab.getChannelData(c)
297
+ data.copyTo(dst, { planeIndex: c, format: 'f32-planar' })
298
+ }
299
+ data.close()
300
+
301
+ this.pcmQueue.push(ab)
302
+ // 队列上限 3 秒,防爆内存
303
+ if (this.pcmQueue.length > 130) this.pcmQueue.shift()
304
+ this.decoded++
305
+ } catch (e) {
306
+ this.log('warn', '音频解码入队失败: ' + e.message)
307
+ }
308
+ }
309
+
310
+ /**
311
+ * 排程泵:把 PCM 队列的内容按恒定节奏送上扬声器。
312
+ *
313
+ * ── 深度优化版:自适应前沿 + 事件驱动唤醒 ──
314
+ *
315
+ * rAF 泵有两个问题(60 秒双监控实测):
316
+ * 1. rAF 在窗口失焦/最小化时被浏览器暂停 → 泵停转 →
317
+ * 前沿跌落 → 恢复时 lag=-56s 级别的跳变(实测出现过)
318
+ * 2. 主线程拥塞时 rAF 延迟,排程粒度不稳定
319
+ *
320
+ * 改用 setTimeout 链(后台也会跑,Electron 里不被节流)+
321
+ * 自适应前沿:前沿追赶速度根据队列深度调整 ——
322
+ * - 队列深(>30 帧)→ 前沿以 1.03 倍速推进,缓慢消化积压
323
+ * - 队列浅(<5 帧)→ 前沿以 0.97 倍速推进,留出缓冲回填时间
324
+ * - 正常 → 1.0 倍速
325
+ * 这样不需要丢帧(skips)也不需要硬跳(resyncs),
326
+ * 延迟在 80~160ms 之间自适应,听感平稳。
327
+ */
328
+ _pump () {
329
+ if (!this.running || !this.ctx) return
330
+ const now = this.ctx.currentTime
331
+ const TARGET = 0.1 // 期望前沿领先 100ms
332
+ const SOFT = 0.14 // 超过 140ms → 提速消化
333
+ const HARD = 0.3 // 超过 300ms → 快速追
334
+ const FRAME_DUR = 1024 / 44100
335
+
336
+ if (!this._started) {
337
+ const targetFrames = Math.ceil(TARGET / FRAME_DUR)
338
+ if (this.pcmQueue.length >= targetFrames) {
339
+ this._started = true
340
+ this.nextTime = now + TARGET
341
+ this.log('ok', `jitter buffer 就绪(${this.pcmQueue.length} 帧),开始播放`)
342
+ }
343
+ } else {
344
+ // 断流恢复
345
+ if (this.nextTime < now) {
346
+ if (this.pcmQueue.length) this.nextTime = now + 0.03
347
+ this.resyncs++
348
+ }
349
+
350
+ const lag = this.nextTime - now
351
+ // 自适应速率:队列深/前沿远 → 微微加速;浅 → 微微减速
352
+ let rate = 1.0
353
+ if (lag > HARD) rate = 1.08
354
+ else if (lag > SOFT) rate = 1.03
355
+ else if (lag < TARGET * 0.5 || this.pcmQueue.length < 5) rate = 0.97
356
+
357
+ // 排程到「前沿恰好领先 TARGET×(1/rate)」为止
358
+ // rate>1 时每帧占用时长略短于真实时长 → 前沿逐渐追回
359
+ while (this.pcmQueue.length && this.nextTime < now + Math.min(SOFT, lag + 0.05) * 1.0 + 0.02) {
360
+ const ab = this.pcmQueue.shift()
361
+ const src = this.ctx.createBufferSource()
362
+ src.buffer = ab
363
+ // 用 playbackRate 实现微加速/减速:1.03 = 消耗快 3%
364
+ src.playbackRate.value = rate
365
+ src.connect(this.gain)
366
+ src.start(this.nextTime)
367
+ this._sources.add(src)
368
+ src.onended = () => { this._sources.delete(src) }
369
+ // 前沿推进量 = 帧时长 / rate(rate>1 → 推进更短 → 前沿相对.currentTime 提前追赶)
370
+ this.nextTime += ab.duration / rate
371
+ }
372
+
373
+ // 队列硬上限:真正积压才丢
374
+ while (this.pcmQueue.length > 120) {
375
+ this.pcmQueue.shift()
376
+ this.skips++
377
+ }
378
+
379
+ // 队列空且前沿贴地 → 停在安全水位等来货
380
+ if (!this.pcmQueue.length && this.nextTime < now + 0.02) {
381
+ this.nextTime = now + 0.02
382
+ }
383
+ }
384
+
385
+ // setTimeout 链:窗口失焦也继续跑(Electron 不节流后台定时器)
386
+ this._raf = setTimeout(() => this._pump(), 20)
387
+ }
388
+
389
+ /**
390
+ * 设置音量(0..1)。
391
+ *
392
+ * _volume 是单一真相源:暂停时 gain 被压到 0,
393
+ * 恢复时要靠它还原 —— 否则恢复后音量会变成 0,看起来像「暂停后没声音了」。
394
+ */
395
+ setVolume (v) {
396
+ this._volume = Math.max(0, Math.min(1, v))
397
+ if (!this.gain) return
398
+ // 暂停期间不动 gain(它应该是 0),只记录目标值
399
+ if (this.paused) return
400
+ try {
401
+ this.gain.gain.setTargetAtTime(this._volume, this.ctx.currentTime, 0.01)
402
+ } catch {
403
+ this.gain.gain.value = this._volume
404
+ }
405
+ }
406
+
407
+ /**
408
+ * 暂停 / 恢复。
409
+ *
410
+ * 暂停必须**立即静音**,不能等缓冲区播完 —— 用户点了暂停还继续响
411
+ * 一两秒是很糟的体验。所以这里三步一起做:
412
+ * 1. gain 瞬间归零(已有的排程立刻无声)
413
+ * 2. 停掉所有正在排程的 source
414
+ * 3. 重置 nextTime,恢复时从「现在」重新开始
415
+ *
416
+ * 注意:暂停期间**继续拉流并丢弃**,而不是停止拉取。
417
+ * 如果停止拉取,接收端队列会堆满,恢复时要么爆一段旧声音、
418
+ * 要么得等队列排空 —— 两种都很难受。
419
+ */
420
+ setPaused (on) {
421
+ this.paused = !!on
422
+ if (!this.gain) return
423
+
424
+ if (this.paused) {
425
+ // 立即静音:用短时间常量避免咔哒声,但足够快(5ms)
426
+ try {
427
+ this.gain.gain.cancelScheduledValues(this.ctx.currentTime)
428
+ this.gain.gain.setTargetAtTime(0, this.ctx.currentTime, 0.005)
429
+ } catch { this.gain.gain.value = 0 }
430
+
431
+ // 停掉所有已排程但还没播完的 buffer
432
+ for (const s of this._sources) { try { s.stop() } catch {} }
433
+ this._sources.clear()
434
+ this.nextTime = 0
435
+ // PCM 队列和冷启动状态一并复位:恢复时重新攒缓冲
436
+ this.pcmQueue.length = 0
437
+ this._started = false
438
+ this.log('info', '音频已暂停')
439
+ } else {
440
+ // 恢复:把 gain 拉回目标音量,jitter buffer 重新攒
441
+ const target = this._volume
442
+ try {
443
+ this.gain.gain.cancelScheduledValues(this.ctx.currentTime)
444
+ this.gain.gain.setTargetAtTime(target, this.ctx.currentTime, 0.01)
445
+ } catch { this.gain.gain.value = target }
446
+ this.nextTime = 0
447
+ this.pcmQueue.length = 0
448
+ this._started = false
449
+ this.log('info', '音频已恢复')
450
+ }
451
+ }
452
+
453
+ /** 当前音量的单一真相源(暂停恢复时要还原它) */
454
+ get volume () { return this._volume }
455
+
456
+ async stop () {
457
+ this.running = false
458
+ this.ready = false
459
+ if (this._raf) { clearTimeout(this._raf); this._raf = null }
460
+ this.pcmQueue.length = 0
461
+ this._started = false
462
+ try { if (this.decoder && this.decoder.state !== 'closed') this.decoder.close() } catch {}
463
+ this.decoder = null
464
+ try { if (this.ctx) await this.ctx.close() } catch {}
465
+ this.ctx = null
466
+ this.gain = null
467
+ this.nextTime = 0
468
+ }
469
+
470
+ stats () {
471
+ return {
472
+ decoded: this.decoded,
473
+ dropped: this.dropped,
474
+ bytes: this.bytes,
475
+ ready: this.ready
476
+ }
477
+ }
478
+ }
479
+