dsh-miniwin 0.2.1 → 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.
@@ -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
+