@hiroosy/baileys-lite 0.3.7 → 0.3.9

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,13 @@ 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);
104
+ this.streamMaxBacklog = Math.floor(this.sampleRate * 1);
101
105
  }
102
106
  setAudioSender(sender) {
103
107
  this.audioSender = sender;
@@ -109,20 +113,15 @@ export class WaAudioEngine {
109
113
  this.onAudioFinished = callback;
110
114
  }
111
115
  setExternalMode(enabled) {
116
+ this.stopStream();
112
117
  this.externalMode = enabled;
113
118
  this.extStarted = false;
114
- this.extSkipCount = 0;
115
- this.extDropCount = 0;
116
119
  if (enabled) {
117
120
  this.audioBuffer = new Float32Array(this.extMaxBuffer);
118
121
  this.audioPosition = 0;
119
122
  this.liveWritePos = 0;
120
123
  this.audioFinished = false;
121
124
  }
122
- this.logger.debug('external audio mode changed', {
123
- enabled,
124
- preBufferSamples: this.extPreBufferSize
125
- });
126
125
  }
127
126
  isExternalMode() {
128
127
  return this.externalMode;
@@ -149,13 +148,6 @@ export class WaAudioEngine {
149
148
  this.audioBuffer.copyWithin(0, drop, this.liveWritePos);
150
149
  this.liveWritePos -= drop;
151
150
  }
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
151
  }
160
152
  this.audioBuffer.set(incoming, this.liveWritePos);
161
153
  this.liveWritePos += incoming.length;
@@ -168,15 +160,25 @@ export class WaAudioEngine {
168
160
  }
169
161
  static feedWatermarksMs() {
170
162
  return {
171
- pauseMs: Math.round(EXT_FEED_PAUSE_FRACTION * 1000),
172
- resumeMs: Math.round(EXT_FEED_RESUME_FRACTION * 1000)
163
+ pauseMs: 120,
164
+ resumeMs: 60
173
165
  };
174
166
  }
175
167
  isAudioFinished() {
176
168
  return this.audioFinished;
177
169
  }
170
+ async loadSource(source) {
171
+ if (WaAudioEngine.isRemoteSource(source)) {
172
+ this.startStream(source);
173
+ return;
174
+ }
175
+ await this.loadAudioFile(source);
176
+ }
177
+ static isRemoteSource(source) {
178
+ return /^https?:\/\//i.test(String(source));
179
+ }
178
180
  async loadAudioFile(audioPath) {
179
- this.logger.debug('loading audio file', { audioPath });
181
+ this.setExternalMode(false);
180
182
  try {
181
183
  await access(audioPath);
182
184
  }
@@ -190,11 +192,6 @@ export class WaAudioEngine {
190
192
  this.audioBuffer = this.int16ToFloat32(pcmData);
191
193
  this.audioPosition = 0;
192
194
  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
195
  }
199
196
  int16ToFloat32(pcmData) {
200
197
  const float32 = new Float32Array(pcmData.length);
@@ -262,13 +259,107 @@ export class WaAudioEngine {
262
259
  const t = i / this.sampleRate;
263
260
  this.audioBuffer[i] = Math.sin(2 * Math.PI * frequency * t) * amplitude;
264
261
  }
265
- this.logger.debug('test tone generated', { samples, durationSec: duration });
262
+ }
263
+ startStream(source) {
264
+ this.setExternalMode(true);
265
+ this.streamMode = true;
266
+ const token = this.streamToken;
267
+ const args = ['-hide_banner', '-loglevel', 'error', '-nostdin'];
268
+ if (WaAudioEngine.isRemoteSource(source)) {
269
+ 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');
270
+ }
271
+ if (/\.m3u8/i.test(source))
272
+ args.push('-live_start_index', '-1');
273
+ args.push('-i', source, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', String(this.sampleRate), '-acodec', 'pcm_s16le', '-f', 's16le', 'pipe:1');
274
+ const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'ignore'] });
275
+ this.streamProc = proc;
276
+ const markEnded = () => {
277
+ if (token === this.streamToken) {
278
+ this.streamEnded = true;
279
+ }
280
+ };
281
+ proc.stdout.on('data', (chunk) => {
282
+ if (token !== this.streamToken) {
283
+ return;
284
+ }
285
+ this.streamQueue.push(this.toStreamSamples(chunk));
286
+ this.pumpStream();
287
+ });
288
+ proc.on('error', markEnded);
289
+ proc.on('close', markEnded);
290
+ }
291
+ stopStream() {
292
+ this.streamToken++;
293
+ if (this.streamProc) {
294
+ this.streamProc.kill('SIGKILL');
295
+ this.streamProc = null;
296
+ }
297
+ this.streamMode = false;
298
+ this.streamEnded = false;
299
+ this.streamPaused = false;
300
+ this.streamQueue = [];
301
+ this.streamCarry = Buffer.alloc(0);
302
+ }
303
+ toStreamSamples(chunk) {
304
+ const bytes = this.streamCarry.length > 0 ? Buffer.concat([this.streamCarry, chunk]) : chunk;
305
+ const usable = bytes.length - (bytes.length % 2);
306
+ const samples = new Float32Array(usable / 2);
307
+ for (let i = 0; i < samples.length; i++) {
308
+ samples[i] = bytes.readInt16LE(i * 2) / 32768;
309
+ }
310
+ this.streamCarry = Buffer.from(bytes.subarray(usable));
311
+ return samples;
312
+ }
313
+ pumpStream() {
314
+ const proc = this.streamProc;
315
+ if (!proc) {
316
+ return;
317
+ }
318
+ while (this.streamQueue.length > 0) {
319
+ const room = this.streamHighWater - (this.liveWritePos - this.audioPosition);
320
+ if (room <= 0) {
321
+ break;
322
+ }
323
+ const head = this.streamQueue[0];
324
+ const take = Math.min(head.length, room);
325
+ this.feedExternalAudio(head.subarray(0, take));
326
+ if (take < head.length) {
327
+ this.streamQueue[0] = head.subarray(take);
328
+ }
329
+ else {
330
+ this.streamQueue.shift();
331
+ }
332
+ }
333
+ let queued = 0;
334
+ for (const chunk of this.streamQueue)
335
+ queued += chunk.length;
336
+ if (queued > this.streamMaxBacklog) {
337
+ proc.stdout?.pause();
338
+ }
339
+ else {
340
+ proc.stdout?.resume();
341
+ }
342
+ }
343
+ isStreamFinished() {
344
+ if (this.audioFinished) {
345
+ return true;
346
+ }
347
+ if (!this.streamEnded || this.streamQueue.length > 0 || this.audioPosition < this.liveWritePos) {
348
+ return false;
349
+ }
350
+ this.audioFinished = true;
351
+ const token = this.streamToken;
352
+ setTimeout(() => {
353
+ if (token === this.streamToken && this.onAudioFinished) {
354
+ this.onAudioFinished();
355
+ }
356
+ }, 0);
357
+ return true;
266
358
  }
267
359
  startPlayback() {
268
360
  if (this.playbackInterval) {
269
361
  return;
270
362
  }
271
- this.logger.debug('starting playback');
272
363
  this.resetBuffer();
273
364
  this.playbackInterval = createSelfCorrectingInterval(() => {
274
365
  this.readFromBuffer(this.outputSize);
@@ -288,15 +379,12 @@ export class WaAudioEngine {
288
379
  return;
289
380
  }
290
381
  this.silenceMode = true;
291
- this.logger.debug('starting silence capture for pre-accept warmup');
292
382
  this.captureInterval = createSelfCorrectingInterval(() => {
293
383
  if (this.audioSender) {
294
384
  try {
295
385
  this.audioSender.sendCapturedAudio(this.silenceChunkBuffer);
296
386
  }
297
- catch (err) {
298
- this.logger.trace('silence send failed', { message: toError(err).message });
299
- }
387
+ catch { }
300
388
  }
301
389
  }, this.intervalMs);
302
390
  }
@@ -309,93 +397,37 @@ export class WaAudioEngine {
309
397
  return;
310
398
  }
311
399
  this.silenceMode = false;
312
- if (this.externalMode) {
400
+ if (this.streamMode) {
401
+ this.extStarted = this.liveWritePos - this.audioPosition >= this.streamPreBufferSize;
402
+ }
403
+ else if (this.externalMode) {
313
404
  this.audioPosition = Math.max(0, this.liveWritePos - this.extPreBufferSize);
314
405
  const available = this.liveWritePos - this.audioPosition;
315
406
  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
407
  }
323
408
  else {
324
409
  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
410
  }
339
- catch { }
340
411
  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
412
  const chunk = this.getNextChunk();
353
413
  if (this.audioSender) {
354
414
  try {
355
415
  this.audioSender.sendCapturedAudio(chunk);
356
416
  }
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
- }
417
+ catch { }
371
418
  }
372
419
  }, this.intervalMs);
373
420
  }
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
421
  stopCapture() {
387
422
  if (this.captureInterval) {
388
423
  this.captureInterval.clear();
389
424
  this.captureInterval = null;
390
425
  }
391
- try {
392
- this.loopDelay?.disable();
393
- }
394
- catch { }
395
426
  }
396
427
  stop() {
397
428
  this.stopPlayback();
398
429
  this.stopCapture();
430
+ this.stopStream();
399
431
  }
400
432
  hasAudio() {
401
433
  return this.audioBuffer !== null && this.audioBuffer.length > 0;
@@ -427,35 +459,34 @@ export class WaAudioEngine {
427
459
  if (!this.audioBuffer) {
428
460
  return this.silenceChunkBuffer;
429
461
  }
462
+ if (this.streamMode) {
463
+ this.pumpStream();
464
+ if (this.isStreamFinished()) {
465
+ return this.silenceChunkBuffer;
466
+ }
467
+ }
430
468
  const endPos = this.externalMode ? this.liveWritePos : this.audioBuffer.length;
431
469
  if (endPos === 0 || (this.audioFinished && !this.externalMode)) {
432
470
  return this.silenceChunkBuffer;
433
471
  }
434
472
  if (this.externalMode) {
435
473
  const available = endPos - this.audioPosition;
474
+ const preBuffer = this.streamMode ? this.streamPreBufferSize : this.extPreBufferSize;
436
475
  if (!this.extStarted) {
437
- if (available < this.extPreBufferSize) {
476
+ if (available < preBuffer && !this.streamEnded) {
438
477
  return this.silenceChunkBuffer;
439
478
  }
440
479
  this.extStarted = true;
441
- this.logger.debug('live buffer ready, starting read', {
442
- availableSamples: available
443
- });
444
480
  }
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
- });
481
+ if (this.streamMode) {
482
+ if (available < this.captureChunkSize && !this.streamEnded) {
483
+ this.extStarted = false;
484
+ return this.silenceChunkBuffer;
457
485
  }
458
486
  }
487
+ else if (available > this.extHighWater) {
488
+ this.audioPosition = endPos - this.extTargetBuffer;
489
+ }
459
490
  if (this.audioPosition >= endPos) {
460
491
  return this.silenceChunkBuffer;
461
492
  }
@@ -470,7 +501,6 @@ export class WaAudioEngine {
470
501
  }
471
502
  if (!this.externalMode && !this.audioFinished) {
472
503
  this.audioFinished = true;
473
- this.logger.debug('audio playback finished, sending silence');
474
504
  if (this.onAudioFinished) {
475
505
  const cb = this.onAudioFinished;
476
506
  setTimeout(() => cb(), 0);