@hiroosy/baileys-lite 0.3.6 → 0.3.8

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/src/voip/index.js CHANGED
@@ -142,10 +142,11 @@ async function normalizeItem(item, ffprobePath, tmpDir) {
142
142
  }
143
143
  let source = rawSource;
144
144
  let isTemp = false;
145
+ if (isUrl(rawSource) && kind === 'audio') {
146
+ return { kind, source: rawSource, isTemp: false, durationMs: undefined, autoAdvance };
147
+ }
145
148
  if (isUrl(rawSource)) {
146
- const extHint = kind === 'video' ? '.mp4' : '.audio';
147
- const maxBytes = kind === 'video' ? 50 * 1024 * 1024 : 20 * 1024 * 1024;
148
- source = await downloadToTemp(rawSource, extHint, maxBytes, tmpDir);
149
+ source = await downloadToTemp(rawSource, '.mp4', 50 * 1024 * 1024, tmpDir);
149
150
  isTemp = true;
150
151
  }
151
152
  else if (!fs.existsSync(rawSource)) {
@@ -176,6 +177,9 @@ class VoipCall extends EventEmitter {
176
177
  #startVideoOnFirst;
177
178
  #videoDown = false;
178
179
  #silenced = false;
180
+ #normalize = null;
181
+ #itemDeadline = 0;
182
+ #itemRemainingMs = null;
179
183
  _itemTimer = null;
180
184
  constructor(items, onRelease, opts = {}) {
181
185
  super();
@@ -187,6 +191,7 @@ class VoipCall extends EventEmitter {
187
191
  this.#target = opts.target ?? null;
188
192
  this.#autoDowngrade = opts.autoDowngrade === undefined ? true : !!opts.autoDowngrade;
189
193
  this.#startVideoOnFirst = !!opts.startVideoOnFirst;
194
+ this.#normalize = opts.normalize ?? null;
190
195
  }
191
196
  async _attach(activeCall) {
192
197
  this.#activeCall = activeCall;
@@ -197,6 +202,7 @@ class VoipCall extends EventEmitter {
197
202
  this._advance().catch((err) => this.emit('error', err));
198
203
  });
199
204
  activeCall.on('ended', (reason) => this._finish(reason));
205
+ activeCall.on('audio_finished', () => this._onAudioFinished());
200
206
  activeCall.on('error', (err) => this.emit('error', err));
201
207
  activeCall.on('peer_video', (change) => {
202
208
  this._onPeerVideo(change).catch((err) => this.emit('error', err));
@@ -209,7 +215,7 @@ class VoipCall extends EventEmitter {
209
215
  this.emit('connected');
210
216
  this._advance().catch((err) => this.emit('error', err));
211
217
  }
212
- for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished']) {
218
+ for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished', 'reconnecting', 'reconnected']) {
213
219
  activeCall.on(ev, (...args) => this.emit(ev, ...args));
214
220
  }
215
221
  }
@@ -260,12 +266,13 @@ class VoipCall extends EventEmitter {
260
266
  }
261
267
  }
262
268
 
263
- async _advance() {
269
+ async _advance(target = null) {
264
270
  if (this.#silenced)
265
271
  return;
266
272
  const previous = this.#items[this.#index] ?? null;
267
- this.#index += 1;
273
+ this.#index = target ?? this.#index + 1;
268
274
  let next = this.#items[this.#index];
275
+ this.#itemRemainingMs = null;
269
276
  if (!next) {
270
277
  if (this.#loop && this.#items.length > 0) {
271
278
  this.emit('playlist_looped');
@@ -273,6 +280,7 @@ class VoipCall extends EventEmitter {
273
280
  next = this.#items[0];
274
281
  }
275
282
  else {
283
+ this.#onItemAdvance?.(null);
276
284
  this.emit('playlist_ended');
277
285
  if (this.#autoEndCall) {
278
286
  this.end().catch((err) => this.emit('error', err));
@@ -280,7 +288,7 @@ class VoipCall extends EventEmitter {
280
288
  return;
281
289
  }
282
290
  }
283
- const isFirst = previous === null && this.#index === 0;
291
+ const isFirst = target === null && previous === null && this.#index === 0;
284
292
  if (isFirst && next.kind === 'video' && this.#startVideoOnFirst) {
285
293
  try {
286
294
  await this.#coordinator.startVideoMidCall(this.#activeCall.callId);
@@ -324,12 +332,55 @@ class VoipCall extends EventEmitter {
324
332
  }
325
333
  this.emit('item', { index: this.#index, kind: next.kind, source: next.source });
326
334
  this.#onItemAdvance?.(next);
327
- if ((next.kind !== 'video' || next.autoAdvance) && next.durationMs) {
328
- this._itemTimer = setTimeout(() => {
329
- this._advance().catch((err) => this.emit('error', err));
330
- }, next.durationMs);
335
+ if (next.kind === 'video' && next.autoAdvance && next.durationMs) {
336
+ this._scheduleAdvance(next.durationMs);
331
337
  }
332
338
  }
339
+ _onAudioFinished() {
340
+ if (this.#ended || this.#silenced)
341
+ return;
342
+ if (this.#items[this.#index]?.kind !== 'audio')
343
+ return;
344
+ this._advance().catch((err) => this.emit('error', err));
345
+ }
346
+ _scheduleAdvance(ms) {
347
+ this._clearItemTimer();
348
+ this.#itemDeadline = Date.now() + ms;
349
+ this._itemTimer = setTimeout(() => {
350
+ this._itemTimer = null;
351
+ this._advance().catch((err) => this.emit('error', err));
352
+ }, ms);
353
+ }
354
+ _clearItemTimer() {
355
+ if (this._itemTimer)
356
+ clearTimeout(this._itemTimer);
357
+ this._itemTimer = null;
358
+ }
359
+ setLoop(value = true) {
360
+ this.#loop = !!value;
361
+ return this.#loop;
362
+ }
363
+ async jump(index) {
364
+ if (this.#ended || !this.#activeCall?.connected || index < 0 || index >= this.#items.length)
365
+ return false;
366
+ if (this.#silenced)
367
+ await this.silent(false);
368
+ this._clearItemTimer();
369
+ await this._advance(index);
370
+ return true;
371
+ }
372
+ async append(media) {
373
+ if (this.#ended || !this.#normalize)
374
+ return false;
375
+ const incoming = [];
376
+ for (const raw of [].concat(media))
377
+ incoming.push(await this.#normalize(raw));
378
+ const start = this.#items.length;
379
+ this.#items.push(...incoming);
380
+ if (this.#index >= start && this.#activeCall?.connected)
381
+ await this._advance(start);
382
+ return true;
383
+ }
333
384
  _cleanupItem(item) {
334
385
  if (item?.isTemp && fs.existsSync(item.source)) {
335
386
  fs.unlink(item.source, () => { });
@@ -372,9 +423,10 @@ class VoipCall extends EventEmitter {
372
423
  this.#videoDown = true;
373
424
  }
374
425
  if (this._itemTimer) {
375
- clearTimeout(this._itemTimer);
376
- this._itemTimer = null;
426
+ this.#itemRemainingMs = Math.max(0, this.#itemDeadline - Date.now());
377
427
  }
428
+ this._clearItemTimer();
429
+ this.#onItemAdvance?.(null);
378
430
  }
379
431
  else {
380
432
  await this.#coordinator.setMute(callId, false);
@@ -382,7 +434,11 @@ class VoipCall extends EventEmitter {
382
434
  await this.#coordinator.startVideoMidCall(callId);
383
435
  this.#videoDown = false;
384
436
  }
385
-
437
+ const remaining = this.#itemRemainingMs;
438
+ this.#itemRemainingMs = null;
439
+ if (remaining !== null)
440
+ this._scheduleAdvance(remaining);
441
+ this.#onItemAdvance?.(current ?? null);
386
442
  }
387
443
  this.emit('silent', this.#silenced);
388
444
  }
@@ -529,10 +585,10 @@ export default class Voip {
529
585
  }, ms);
530
586
  };
531
587
  const rescheduleSafetyForItem = (item) => {
532
- const windowMs = item?.kind === 'video'
533
- ? 10 * 60_000
534
- : Math.max(item?.durationMs ?? 120_000, 45_000) + 60_000;
535
- scheduleSafety(windowMs);
588
+ clearTimeout(safetyTimer.handle);
589
+ if (item?.kind === 'video') {
590
+ scheduleSafety(10 * 60_000);
591
+ }
536
592
  };
537
593
  const call = new VoipCall(items, () => { this.#calls.delete(call); }, {
538
594
  autoEndCall: options.autoEndCall,
@@ -541,6 +597,7 @@ export default class Voip {
541
597
  startVideoOnFirst: options.startVideoOnFirst,
542
598
  target: targetJid,
543
599
  onItemAdvance: rescheduleSafetyForItem,
600
+ normalize: raw => normalizeItem(raw, this.#ffprobePath, this.#tmpDir),
544
601
  });
545
602
  this.#calls.add(call);
546
603
  releaseReservation();
@@ -1,13 +1,10 @@
1
1
  import { execFile, spawn } from 'node:child_process';
2
2
  import { access } from 'node:fs/promises';
3
- import { monitorEventLoopDelay } from 'node:perf_hooks';
4
3
  import { createNoopLogger } from '../shim/core.js';
5
- import { toBytesView, toError } from '../shim/util.js';
4
+ import { toBytesView } from '../shim/util.js';
6
5
  import { concatBytes, TEXT_DECODER } from '../bytes.js';
7
6
  import { DEFAULT_AUDIO_CONFIG } from '../types.js';
8
7
  const FFMPEG_BIN = 'ffmpeg';
9
- const EXT_FEED_PAUSE_FRACTION = 0.12;
10
- const EXT_FEED_RESUME_FRACTION = 0.06;
11
8
  const MAX_DECODE_BYTES = 128 * 1024 * 1024;
12
9
  const MAX_STDERR_CHARS = 16 * 1024;
13
10
  const ffmpegProbeCache = new Map();
@@ -26,18 +23,18 @@ async function hasFfmpeg(bin) {
26
23
  }
27
24
  return available;
28
25
  }
29
-
30
26
  function createSelfCorrectingInterval(callback, intervalMs) {
31
- let expected = Date.now() + intervalMs;
27
+ let expected = performance.now() + intervalMs;
32
28
  let timer = null;
33
29
  let stopped = false;
34
30
  function tick() {
35
31
  if (stopped) return;
32
+ if (performance.now() - expected > intervalMs * 3) {
33
+ expected = performance.now();
34
+ }
36
35
  callback();
37
36
  expected += intervalMs;
38
- const drift = Date.now() - expected;
39
-
40
- timer = setTimeout(tick, Math.max(0, intervalMs - drift));
37
+ timer = setTimeout(tick, Math.max(0, expected - performance.now()));
41
38
  }
42
39
  timer = setTimeout(tick, intervalMs);
43
40
  return {
@@ -66,9 +63,6 @@ export class WaAudioEngine {
66
63
  outputSize;
67
64
  intervalMs;
68
65
  silenceMode = false;
69
- lastTickPerf = 0;
70
- pacing = { ticks: 0, late90: 0, late200: 0, burst20: 0, maxGap: 0 };
71
- loopDelay = null;
72
66
  externalMode = false;
73
67
  loopMode = false;
74
68
  liveWritePos = 0;
@@ -77,11 +71,18 @@ export class WaAudioEngine {
77
71
  extTargetBuffer;
78
72
  extHighWater;
79
73
  extMaxBuffer;
80
- extSkipCount = 0;
81
- extDropCount = 0;
74
+ streamPreBufferSize;
75
+ streamHighWater;
82
76
  captureChunkBuffer;
83
77
  silenceChunkBuffer;
84
78
  playbackOutputBuffer;
79
+ streamProc = null;
80
+ streamMode = false;
81
+ streamEnded = false;
82
+ streamPaused = false;
83
+ streamToken = 0;
84
+ streamQueue = [];
85
+ streamCarry = Buffer.alloc(0);
85
86
  constructor(config = {}) {
86
87
  const c = { ...DEFAULT_AUDIO_CONFIG, ...config };
87
88
  this.logger = config.logger ?? createNoopLogger();
@@ -94,10 +95,12 @@ export class WaAudioEngine {
94
95
  this.captureChunkBuffer = new Float32Array(this.captureChunkSize);
95
96
  this.silenceChunkBuffer = new Float32Array(this.captureChunkSize);
96
97
  this.playbackOutputBuffer = new Float32Array(this.outputSize);
97
- this.extPreBufferSize = Math.floor(this.sampleRate * EXT_FEED_RESUME_FRACTION);
98
+ this.extPreBufferSize = Math.floor(this.sampleRate * 0.06);
98
99
  this.extTargetBuffer = Math.floor(this.sampleRate * 0.06);
99
100
  this.extHighWater = Math.floor(this.sampleRate * 0.2);
100
- this.extMaxBuffer = Math.floor(this.sampleRate * 0.5);
101
+ this.extMaxBuffer = Math.floor(this.sampleRate);
102
+ this.streamPreBufferSize = Math.floor(this.sampleRate * 0.3);
103
+ this.streamHighWater = Math.floor(this.sampleRate * 0.6);
101
104
  }
102
105
  setAudioSender(sender) {
103
106
  this.audioSender = sender;
@@ -109,20 +112,15 @@ export class WaAudioEngine {
109
112
  this.onAudioFinished = callback;
110
113
  }
111
114
  setExternalMode(enabled) {
115
+ this.stopStream();
112
116
  this.externalMode = enabled;
113
117
  this.extStarted = false;
114
- this.extSkipCount = 0;
115
- this.extDropCount = 0;
116
118
  if (enabled) {
117
119
  this.audioBuffer = new Float32Array(this.extMaxBuffer);
118
120
  this.audioPosition = 0;
119
121
  this.liveWritePos = 0;
120
122
  this.audioFinished = false;
121
123
  }
122
- this.logger.debug('external audio mode changed', {
123
- enabled,
124
- preBufferSamples: this.extPreBufferSize
125
- });
126
124
  }
127
125
  isExternalMode() {
128
126
  return this.externalMode;
@@ -149,13 +147,6 @@ export class WaAudioEngine {
149
147
  this.audioBuffer.copyWithin(0, drop, this.liveWritePos);
150
148
  this.liveWritePos -= drop;
151
149
  }
152
- this.extDropCount++;
153
- if (this.extDropCount <= 5 || this.extDropCount % 100 === 0) {
154
- this.logger.debug('live buffer overflow, dropped oldest', {
155
- droppedSamples: drop,
156
- dropCount: this.extDropCount
157
- });
158
- }
159
150
  }
160
151
  this.audioBuffer.set(incoming, this.liveWritePos);
161
152
  this.liveWritePos += incoming.length;
@@ -168,15 +159,25 @@ export class WaAudioEngine {
168
159
  }
169
160
  static feedWatermarksMs() {
170
161
  return {
171
- pauseMs: Math.round(EXT_FEED_PAUSE_FRACTION * 1000),
172
- resumeMs: Math.round(EXT_FEED_RESUME_FRACTION * 1000)
162
+ pauseMs: 120,
163
+ resumeMs: 60
173
164
  };
174
165
  }
175
166
  isAudioFinished() {
176
167
  return this.audioFinished;
177
168
  }
169
+ async loadSource(source) {
170
+ if (WaAudioEngine.isRemoteSource(source)) {
171
+ this.startStream(source);
172
+ return;
173
+ }
174
+ await this.loadAudioFile(source);
175
+ }
176
+ static isRemoteSource(source) {
177
+ return /^https?:\/\//i.test(String(source));
178
+ }
178
179
  async loadAudioFile(audioPath) {
179
- this.logger.debug('loading audio file', { audioPath });
180
+ this.setExternalMode(false);
180
181
  try {
181
182
  await access(audioPath);
182
183
  }
@@ -190,11 +191,6 @@ export class WaAudioEngine {
190
191
  this.audioBuffer = this.int16ToFloat32(pcmData);
191
192
  this.audioPosition = 0;
192
193
  this.audioFinished = false;
193
- const duration = this.audioBuffer.length / this.sampleRate;
194
- this.logger.media('audio file loaded', {
195
- samples: this.audioBuffer.length,
196
- durationSec: duration
197
- });
198
194
  }
199
195
  int16ToFloat32(pcmData) {
200
196
  const float32 = new Float32Array(pcmData.length);
@@ -262,13 +258,106 @@ export class WaAudioEngine {
262
258
  const t = i / this.sampleRate;
263
259
  this.audioBuffer[i] = Math.sin(2 * Math.PI * frequency * t) * amplitude;
264
260
  }
265
- this.logger.debug('test tone generated', { samples, durationSec: duration });
261
+ }
262
+ startStream(source) {
263
+ this.setExternalMode(true);
264
+ this.streamMode = true;
265
+ const token = this.streamToken;
266
+ const args = ['-hide_banner', '-loglevel', 'error', '-nostdin'];
267
+ if (WaAudioEngine.isRemoteSource(source)) {
268
+ args.push('-user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5');
269
+ }
270
+ args.push('-i', source, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', String(this.sampleRate), '-acodec', 'pcm_s16le', '-f', 's16le', 'pipe:1');
271
+ const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'ignore'] });
272
+ this.streamProc = proc;
273
+ const markEnded = () => {
274
+ if (token === this.streamToken) {
275
+ this.streamEnded = true;
276
+ }
277
+ };
278
+ proc.stdout.on('data', (chunk) => {
279
+ if (token !== this.streamToken) {
280
+ return;
281
+ }
282
+ this.streamQueue.push(this.toStreamSamples(chunk));
283
+ this.pumpStream();
284
+ });
285
+ proc.on('error', markEnded);
286
+ proc.on('close', markEnded);
287
+ }
288
+ stopStream() {
289
+ this.streamToken++;
290
+ if (this.streamProc) {
291
+ this.streamProc.kill('SIGKILL');
292
+ this.streamProc = null;
293
+ }
294
+ this.streamMode = false;
295
+ this.streamEnded = false;
296
+ this.streamPaused = false;
297
+ this.streamQueue = [];
298
+ this.streamCarry = Buffer.alloc(0);
299
+ }
300
+ toStreamSamples(chunk) {
301
+ const bytes = this.streamCarry.length > 0 ? Buffer.concat([this.streamCarry, chunk]) : chunk;
302
+ const usable = bytes.length - (bytes.length % 2);
303
+ const samples = new Float32Array(usable / 2);
304
+ for (let i = 0; i < samples.length; i++) {
305
+ samples[i] = bytes.readInt16LE(i * 2) / 32768;
306
+ }
307
+ this.streamCarry = Buffer.from(bytes.subarray(usable));
308
+ return samples;
309
+ }
310
+ pumpStream() {
311
+ const proc = this.streamProc;
312
+ if (!proc) {
313
+ return;
314
+ }
315
+ while (this.streamQueue.length > 0) {
316
+ const room = this.streamHighWater - (this.liveWritePos - this.audioPosition);
317
+ if (room <= 0) {
318
+ break;
319
+ }
320
+ const head = this.streamQueue[0];
321
+ const take = Math.min(head.length, room);
322
+ this.feedExternalAudio(head.subarray(0, take));
323
+ if (take < head.length) {
324
+ this.streamQueue[0] = head.subarray(take);
325
+ }
326
+ else {
327
+ this.streamQueue.shift();
328
+ }
329
+ }
330
+ if (this.streamQueue.length > 0) {
331
+ if (!this.streamPaused) {
332
+ this.streamPaused = true;
333
+ proc.stdout.pause();
334
+ }
335
+ }
336
+ else if (this.streamPaused) {
337
+ this.streamPaused = false;
338
+ proc.stdout.resume();
339
+ }
340
+ }
341
+ isStreamFinished() {
342
+ if (this.audioFinished) {
343
+ return true;
344
+ }
345
+ if (!this.streamEnded || this.streamQueue.length > 0 || this.audioPosition < this.liveWritePos) {
346
+ return false;
347
+ }
348
+ this.audioFinished = true;
349
+ const token = this.streamToken;
350
+ setTimeout(() => {
351
+ if (token === this.streamToken && this.onAudioFinished) {
352
+ this.onAudioFinished();
353
+ }
354
+ }, 0);
355
+ return true;
266
356
  }
267
357
  startPlayback() {
268
358
  if (this.playbackInterval) {
269
359
  return;
270
360
  }
271
- this.logger.debug('starting playback');
272
361
  this.resetBuffer();
273
362
  this.playbackInterval = createSelfCorrectingInterval(() => {
274
363
  this.readFromBuffer(this.outputSize);
@@ -288,15 +377,12 @@ export class WaAudioEngine {
288
377
  return;
289
378
  }
290
379
  this.silenceMode = true;
291
- this.logger.debug('starting silence capture for pre-accept warmup');
292
380
  this.captureInterval = createSelfCorrectingInterval(() => {
293
381
  if (this.audioSender) {
294
382
  try {
295
383
  this.audioSender.sendCapturedAudio(this.silenceChunkBuffer);
296
384
  }
297
- catch (err) {
298
- this.logger.trace('silence send failed', { message: toError(err).message });
299
- }
385
+ catch { }
300
386
  }
301
387
  }, this.intervalMs);
302
388
  }
@@ -309,93 +395,37 @@ export class WaAudioEngine {
309
395
  return;
310
396
  }
311
397
  this.silenceMode = false;
312
- if (this.externalMode) {
398
+ if (this.streamMode) {
399
+ this.extStarted = this.liveWritePos - this.audioPosition >= this.streamPreBufferSize;
400
+ }
401
+ else if (this.externalMode) {
313
402
  this.audioPosition = Math.max(0, this.liveWritePos - this.extPreBufferSize);
314
403
  const available = this.liveWritePos - this.audioPosition;
315
404
  this.extStarted = available >= this.extPreBufferSize;
316
- this.logger.debug('starting live capture', {
317
- readPos: this.audioPosition,
318
- writePos: this.liveWritePos,
319
- runwaySamples: available,
320
- started: this.extStarted
321
- });
322
405
  }
323
406
  else {
324
407
  this.audioPosition = 0;
325
- if (this.audioBuffer) {
326
- const durationSec = this.audioBuffer.length / this.sampleRate;
327
- this.logger.debug('starting capture with loaded audio', { durationSec });
328
- }
329
- else {
330
- this.logger.debug('starting capture with silence, no audio loaded');
331
- }
332
- }
333
- let frameCount = 0;
334
- this.lastTickPerf = 0;
335
- try {
336
- this.loopDelay ??= monitorEventLoopDelay({ resolution: 10 });
337
- this.loopDelay.enable();
338
408
  }
339
- catch { }
340
409
  this.captureInterval = createSelfCorrectingInterval(() => {
341
- frameCount++;
342
- const nowPerf = performance.now();
343
- if (this.lastTickPerf) {
344
- const gap = nowPerf - this.lastTickPerf;
345
- this.pacing.ticks++;
346
- if (gap > 90) this.pacing.late90++;
347
- if (gap > 200) this.pacing.late200++;
348
- if (gap < 20) this.pacing.burst20++;
349
- if (gap > this.pacing.maxGap) this.pacing.maxGap = gap;
350
- }
351
- this.lastTickPerf = nowPerf;
352
410
  const chunk = this.getNextChunk();
353
411
  if (this.audioSender) {
354
412
  try {
355
413
  this.audioSender.sendCapturedAudio(chunk);
356
414
  }
357
- catch (err) {
358
- this.logger.trace('captured audio send failed', {
359
- message: toError(err).message
360
- });
361
- }
362
- }
363
- if (frameCount % 500 === 0) {
364
- if (this.audioBuffer) {
365
- const positionSec = this.audioPosition / this.sampleRate;
366
- this.logger.trace('capture frame', { frameCount, positionSec });
367
- }
368
- else {
369
- this.logger.trace('capture frame with silence', { frameCount });
370
- }
415
+ catch { }
371
416
  }
372
417
  }, this.intervalMs);
373
418
  }
374
- takePacingStats() {
375
- const p = this.pacing;
376
- const out = { ...p, maxGap: Math.round(p.maxGap) };
377
- if (this.loopDelay) {
378
- out.loopP50 = Math.round(this.loopDelay.percentile(50) / 1e6);
379
- out.loopP99 = Math.round(this.loopDelay.percentile(99) / 1e6);
380
- out.loopMax = Math.round(this.loopDelay.max / 1e6);
381
- this.loopDelay.reset();
382
- }
383
- this.pacing = { ticks: 0, late90: 0, late200: 0, burst20: 0, maxGap: 0 };
384
- return out;
385
- }
386
419
  stopCapture() {
387
420
  if (this.captureInterval) {
388
421
  this.captureInterval.clear();
389
422
  this.captureInterval = null;
390
423
  }
391
- try {
392
- this.loopDelay?.disable();
393
- }
394
- catch { }
395
424
  }
396
425
  stop() {
397
426
  this.stopPlayback();
398
427
  this.stopCapture();
428
+ this.stopStream();
399
429
  }
400
430
  hasAudio() {
401
431
  return this.audioBuffer !== null && this.audioBuffer.length > 0;
@@ -427,35 +457,34 @@ export class WaAudioEngine {
427
457
  if (!this.audioBuffer) {
428
458
  return this.silenceChunkBuffer;
429
459
  }
460
+ if (this.streamMode) {
461
+ this.pumpStream();
462
+ if (this.isStreamFinished()) {
463
+ return this.silenceChunkBuffer;
464
+ }
465
+ }
430
466
  const endPos = this.externalMode ? this.liveWritePos : this.audioBuffer.length;
431
467
  if (endPos === 0 || (this.audioFinished && !this.externalMode)) {
432
468
  return this.silenceChunkBuffer;
433
469
  }
434
470
  if (this.externalMode) {
435
471
  const available = endPos - this.audioPosition;
472
+ const preBuffer = this.streamMode ? this.streamPreBufferSize : this.extPreBufferSize;
436
473
  if (!this.extStarted) {
437
- if (available < this.extPreBufferSize) {
474
+ if (available < preBuffer && !this.streamEnded) {
438
475
  return this.silenceChunkBuffer;
439
476
  }
440
477
  this.extStarted = true;
441
- this.logger.debug('live buffer ready, starting read', {
442
- availableSamples: available
443
- });
444
478
  }
445
- if (available > this.extHighWater) {
446
- const skipTo = endPos - this.extTargetBuffer;
447
- const skipped = skipTo - this.audioPosition;
448
- this.audioPosition = skipTo;
449
- this.extSkipCount++;
450
- if (this.extSkipCount <= 5) {
451
- this.logger.debug('live buffer overflow, skipped samples', {
452
- availableSamples: available,
453
- skippedSamples: skipped,
454
- targetSamples: this.extTargetBuffer,
455
- skipCount: this.extSkipCount
456
- });
479
+ if (this.streamMode) {
480
+ if (available < this.captureChunkSize && !this.streamEnded) {
481
+ this.extStarted = false;
482
+ return this.silenceChunkBuffer;
457
483
  }
458
484
  }
485
+ else if (available > this.extHighWater) {
486
+ this.audioPosition = endPos - this.extTargetBuffer;
487
+ }
459
488
  if (this.audioPosition >= endPos) {
460
489
  return this.silenceChunkBuffer;
461
490
  }
@@ -470,7 +499,6 @@ export class WaAudioEngine {
470
499
  }
471
500
  if (!this.externalMode && !this.audioFinished) {
472
501
  this.audioFinished = true;
473
- this.logger.debug('audio playback finished, sending silence');
474
502
  if (this.onAudioFinished) {
475
503
  const cb = this.onAudioFinished;
476
504
  setTimeout(() => cb(), 0);