@hiroosy/baileys-lite 0.0.4 → 0.3.1
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/LICENSE +21 -0
- package/README.md +658 -10
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
4
|
+
import { createNoopLogger } from '../shim/core.js';
|
|
5
|
+
import { toBytesView, toError } from '../shim/util.js';
|
|
6
|
+
import { concatBytes, TEXT_DECODER } from '../bytes.js';
|
|
7
|
+
import { DEFAULT_AUDIO_CONFIG } from '../types.js';
|
|
8
|
+
const FFMPEG_BIN = 'ffmpeg';
|
|
9
|
+
const EXT_FEED_PAUSE_FRACTION = 0.12;
|
|
10
|
+
const EXT_FEED_RESUME_FRACTION = 0.06;
|
|
11
|
+
const MAX_DECODE_BYTES = 128 * 1024 * 1024;
|
|
12
|
+
const MAX_STDERR_CHARS = 16 * 1024;
|
|
13
|
+
const ffmpegProbeCache = new Map();
|
|
14
|
+
function probeBinary(bin) {
|
|
15
|
+
return new Promise((resolve) => {
|
|
16
|
+
execFile(bin, ['-version'], { timeout: 5_000 }, (err) => resolve(!err));
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
async function hasFfmpeg(bin) {
|
|
20
|
+
let available = ffmpegProbeCache.get(bin);
|
|
21
|
+
if (available === undefined) {
|
|
22
|
+
available = await probeBinary(bin);
|
|
23
|
+
if (available) {
|
|
24
|
+
ffmpegProbeCache.set(bin, available);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return available;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function createSelfCorrectingInterval(callback, intervalMs) {
|
|
31
|
+
let expected = Date.now() + intervalMs;
|
|
32
|
+
let timer = null;
|
|
33
|
+
let stopped = false;
|
|
34
|
+
function tick() {
|
|
35
|
+
if (stopped) return;
|
|
36
|
+
callback();
|
|
37
|
+
expected += intervalMs;
|
|
38
|
+
const drift = Date.now() - expected;
|
|
39
|
+
|
|
40
|
+
timer = setTimeout(tick, Math.max(0, intervalMs - drift));
|
|
41
|
+
}
|
|
42
|
+
timer = setTimeout(tick, intervalMs);
|
|
43
|
+
return {
|
|
44
|
+
clear() {
|
|
45
|
+
stopped = true;
|
|
46
|
+
if (timer) clearTimeout(timer);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export class WaAudioEngine {
|
|
51
|
+
logger;
|
|
52
|
+
audioSender = null;
|
|
53
|
+
audioBuffer = null;
|
|
54
|
+
audioPosition = 0;
|
|
55
|
+
audioFinished = false;
|
|
56
|
+
onAudioFinished = null;
|
|
57
|
+
playbackInterval = null;
|
|
58
|
+
captureInterval = null;
|
|
59
|
+
circularBuffer;
|
|
60
|
+
bufferWritePos = 0;
|
|
61
|
+
bufferReadPos = 0;
|
|
62
|
+
bufferLength = 0;
|
|
63
|
+
sampleRate;
|
|
64
|
+
captureChunkSize;
|
|
65
|
+
maxBuffer;
|
|
66
|
+
outputSize;
|
|
67
|
+
intervalMs;
|
|
68
|
+
silenceMode = false;
|
|
69
|
+
lastTickPerf = 0;
|
|
70
|
+
pacing = { ticks: 0, late90: 0, late200: 0, burst20: 0, maxGap: 0 };
|
|
71
|
+
loopDelay = null;
|
|
72
|
+
externalMode = false;
|
|
73
|
+
loopMode = false;
|
|
74
|
+
liveWritePos = 0;
|
|
75
|
+
extStarted = false;
|
|
76
|
+
extPreBufferSize;
|
|
77
|
+
extTargetBuffer;
|
|
78
|
+
extHighWater;
|
|
79
|
+
extMaxBuffer;
|
|
80
|
+
extSkipCount = 0;
|
|
81
|
+
extDropCount = 0;
|
|
82
|
+
captureChunkBuffer;
|
|
83
|
+
silenceChunkBuffer;
|
|
84
|
+
playbackOutputBuffer;
|
|
85
|
+
constructor(config = {}) {
|
|
86
|
+
const c = { ...DEFAULT_AUDIO_CONFIG, ...config };
|
|
87
|
+
this.logger = config.logger ?? createNoopLogger();
|
|
88
|
+
this.sampleRate = c.sampleRate;
|
|
89
|
+
this.captureChunkSize = c.captureChunkSize;
|
|
90
|
+
this.maxBuffer = c.maxBufferSize;
|
|
91
|
+
this.outputSize = c.playbackOutputSize;
|
|
92
|
+
this.intervalMs = c.intervalMs;
|
|
93
|
+
this.circularBuffer = new Float32Array(this.maxBuffer);
|
|
94
|
+
this.captureChunkBuffer = new Float32Array(this.captureChunkSize);
|
|
95
|
+
this.silenceChunkBuffer = new Float32Array(this.captureChunkSize);
|
|
96
|
+
this.playbackOutputBuffer = new Float32Array(this.outputSize);
|
|
97
|
+
this.extPreBufferSize = Math.floor(this.sampleRate * EXT_FEED_RESUME_FRACTION);
|
|
98
|
+
this.extTargetBuffer = Math.floor(this.sampleRate * 0.06);
|
|
99
|
+
this.extHighWater = Math.floor(this.sampleRate * 0.2);
|
|
100
|
+
this.extMaxBuffer = Math.floor(this.sampleRate * 0.5);
|
|
101
|
+
}
|
|
102
|
+
setAudioSender(sender) {
|
|
103
|
+
this.audioSender = sender;
|
|
104
|
+
}
|
|
105
|
+
setLoopMode(enabled) {
|
|
106
|
+
this.loopMode = enabled;
|
|
107
|
+
}
|
|
108
|
+
setOnAudioFinished(callback) {
|
|
109
|
+
this.onAudioFinished = callback;
|
|
110
|
+
}
|
|
111
|
+
setExternalMode(enabled) {
|
|
112
|
+
this.externalMode = enabled;
|
|
113
|
+
this.extStarted = false;
|
|
114
|
+
this.extSkipCount = 0;
|
|
115
|
+
this.extDropCount = 0;
|
|
116
|
+
if (enabled) {
|
|
117
|
+
this.audioBuffer = new Float32Array(this.extMaxBuffer);
|
|
118
|
+
this.audioPosition = 0;
|
|
119
|
+
this.liveWritePos = 0;
|
|
120
|
+
this.audioFinished = false;
|
|
121
|
+
}
|
|
122
|
+
this.logger.debug('external audio mode changed', {
|
|
123
|
+
enabled,
|
|
124
|
+
preBufferSamples: this.extPreBufferSize
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
isExternalMode() {
|
|
128
|
+
return this.externalMode;
|
|
129
|
+
}
|
|
130
|
+
feedExternalAudio(data) {
|
|
131
|
+
if (!this.externalMode || !this.audioBuffer)
|
|
132
|
+
return 0;
|
|
133
|
+
let incoming = data;
|
|
134
|
+
if (incoming.length > this.extMaxBuffer) {
|
|
135
|
+
incoming = incoming.subarray(incoming.length - this.extMaxBuffer);
|
|
136
|
+
}
|
|
137
|
+
if (this.liveWritePos + incoming.length > this.audioBuffer.length) {
|
|
138
|
+
const unconsumed = this.liveWritePos - this.audioPosition;
|
|
139
|
+
if (unconsumed > 0 && this.audioPosition > 0) {
|
|
140
|
+
this.audioBuffer.copyWithin(0, this.audioPosition, this.liveWritePos);
|
|
141
|
+
}
|
|
142
|
+
this.liveWritePos = Math.max(0, unconsumed);
|
|
143
|
+
this.audioPosition = 0;
|
|
144
|
+
}
|
|
145
|
+
const overflow = this.liveWritePos + incoming.length - this.extMaxBuffer;
|
|
146
|
+
if (overflow > 0) {
|
|
147
|
+
const drop = Math.min(overflow, this.liveWritePos);
|
|
148
|
+
if (drop > 0) {
|
|
149
|
+
this.audioBuffer.copyWithin(0, drop, this.liveWritePos);
|
|
150
|
+
this.liveWritePos -= drop;
|
|
151
|
+
}
|
|
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
|
+
}
|
|
160
|
+
this.audioBuffer.set(incoming, this.liveWritePos);
|
|
161
|
+
this.liveWritePos += incoming.length;
|
|
162
|
+
return ((this.liveWritePos - this.audioPosition) / this.sampleRate) * 1000;
|
|
163
|
+
}
|
|
164
|
+
getLiveBufferMs() {
|
|
165
|
+
if (!this.externalMode || !this.audioBuffer)
|
|
166
|
+
return 0;
|
|
167
|
+
return ((this.liveWritePos - this.audioPosition) / this.sampleRate) * 1000;
|
|
168
|
+
}
|
|
169
|
+
static feedWatermarksMs() {
|
|
170
|
+
return {
|
|
171
|
+
pauseMs: Math.round(EXT_FEED_PAUSE_FRACTION * 1000),
|
|
172
|
+
resumeMs: Math.round(EXT_FEED_RESUME_FRACTION * 1000)
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
isAudioFinished() {
|
|
176
|
+
return this.audioFinished;
|
|
177
|
+
}
|
|
178
|
+
async loadAudioFile(audioPath) {
|
|
179
|
+
this.logger.debug('loading audio file', { audioPath });
|
|
180
|
+
try {
|
|
181
|
+
await access(audioPath);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
throw new Error(`File not found: ${audioPath}`);
|
|
185
|
+
}
|
|
186
|
+
if (!(await hasFfmpeg(FFMPEG_BIN))) {
|
|
187
|
+
throw new Error('ffmpeg not found on PATH (install ffmpeg to load audio files)');
|
|
188
|
+
}
|
|
189
|
+
const pcmData = await this.decodeWithFFmpeg(audioPath);
|
|
190
|
+
this.audioBuffer = this.int16ToFloat32(pcmData);
|
|
191
|
+
this.audioPosition = 0;
|
|
192
|
+
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
|
+
}
|
|
199
|
+
int16ToFloat32(pcmData) {
|
|
200
|
+
const float32 = new Float32Array(pcmData.length);
|
|
201
|
+
for (let i = 0; i < pcmData.length; i++) {
|
|
202
|
+
float32[i] = pcmData[i] / 32768.0;
|
|
203
|
+
}
|
|
204
|
+
return float32;
|
|
205
|
+
}
|
|
206
|
+
async decodeWithFFmpeg(inputPath) {
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
const proc = spawn(FFMPEG_BIN, [
|
|
209
|
+
'-hide_banner',
|
|
210
|
+
'-loglevel',
|
|
211
|
+
'error',
|
|
212
|
+
'-i',
|
|
213
|
+
inputPath,
|
|
214
|
+
'-ac',
|
|
215
|
+
'1',
|
|
216
|
+
'-ar',
|
|
217
|
+
String(this.sampleRate),
|
|
218
|
+
'-acodec',
|
|
219
|
+
'pcm_s16le',
|
|
220
|
+
'-f',
|
|
221
|
+
's16le',
|
|
222
|
+
'pipe:1'
|
|
223
|
+
], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
224
|
+
const chunks = [];
|
|
225
|
+
let decodedBytes = 0;
|
|
226
|
+
let stderr = '';
|
|
227
|
+
let aborted = false;
|
|
228
|
+
proc.stdout?.on('data', (chunk) => {
|
|
229
|
+
if (aborted)
|
|
230
|
+
return;
|
|
231
|
+
decodedBytes += chunk.length;
|
|
232
|
+
if (decodedBytes > MAX_DECODE_BYTES) {
|
|
233
|
+
aborted = true;
|
|
234
|
+
proc.kill('SIGKILL');
|
|
235
|
+
reject(new Error(`ffmpeg output exceeded ${MAX_DECODE_BYTES} bytes: ${inputPath}`));
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
chunks.push(toBytesView(chunk));
|
|
239
|
+
});
|
|
240
|
+
proc.stderr?.on('data', (chunk) => {
|
|
241
|
+
stderr = (stderr + TEXT_DECODER.decode(chunk)).slice(0, MAX_STDERR_CHARS);
|
|
242
|
+
});
|
|
243
|
+
proc.on('error', (err) => reject(new Error(`ffmpeg not available (install ffmpeg on PATH): ${err.message}`)));
|
|
244
|
+
proc.on('close', (code) => {
|
|
245
|
+
if (aborted)
|
|
246
|
+
return;
|
|
247
|
+
if (code !== 0) {
|
|
248
|
+
reject(new Error(`ffmpeg exited with code ${code}: ${stderr.trim()}`));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const pcmBytes = concatBytes(chunks);
|
|
252
|
+
resolve(new Int16Array(pcmBytes.buffer, pcmBytes.byteOffset, pcmBytes.byteLength >> 1));
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
generateTestTone(frequency = 440, duration = 3, amplitude = 0.3) {
|
|
257
|
+
const samples = this.sampleRate * duration;
|
|
258
|
+
this.audioBuffer = new Float32Array(samples);
|
|
259
|
+
this.audioPosition = 0;
|
|
260
|
+
this.audioFinished = false;
|
|
261
|
+
for (let i = 0; i < samples; i++) {
|
|
262
|
+
const t = i / this.sampleRate;
|
|
263
|
+
this.audioBuffer[i] = Math.sin(2 * Math.PI * frequency * t) * amplitude;
|
|
264
|
+
}
|
|
265
|
+
this.logger.debug('test tone generated', { samples, durationSec: duration });
|
|
266
|
+
}
|
|
267
|
+
startPlayback() {
|
|
268
|
+
if (this.playbackInterval) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
this.logger.debug('starting playback');
|
|
272
|
+
this.resetBuffer();
|
|
273
|
+
this.playbackInterval = createSelfCorrectingInterval(() => {
|
|
274
|
+
this.readFromBuffer(this.outputSize);
|
|
275
|
+
}, this.intervalMs);
|
|
276
|
+
}
|
|
277
|
+
stopPlayback() {
|
|
278
|
+
if (this.playbackInterval) {
|
|
279
|
+
this.playbackInterval.clear();
|
|
280
|
+
this.playbackInterval = null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
onPlaybackData(audioData) {
|
|
284
|
+
this.writeToBuffer(audioData);
|
|
285
|
+
}
|
|
286
|
+
startSilenceCapture() {
|
|
287
|
+
if (this.captureInterval) {
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
this.silenceMode = true;
|
|
291
|
+
this.logger.debug('starting silence capture for pre-accept warmup');
|
|
292
|
+
this.captureInterval = createSelfCorrectingInterval(() => {
|
|
293
|
+
if (this.audioSender) {
|
|
294
|
+
try {
|
|
295
|
+
this.audioSender.sendCapturedAudio(this.silenceChunkBuffer);
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
this.logger.trace('silence send failed', { message: toError(err).message });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}, this.intervalMs);
|
|
302
|
+
}
|
|
303
|
+
startCapture() {
|
|
304
|
+
if (this.captureInterval && this.silenceMode) {
|
|
305
|
+
this.captureInterval.clear();
|
|
306
|
+
this.captureInterval = null;
|
|
307
|
+
}
|
|
308
|
+
if (this.captureInterval) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
this.silenceMode = false;
|
|
312
|
+
if (this.externalMode) {
|
|
313
|
+
this.audioPosition = Math.max(0, this.liveWritePos - this.extPreBufferSize);
|
|
314
|
+
const available = this.liveWritePos - this.audioPosition;
|
|
315
|
+
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
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
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
|
+
}
|
|
339
|
+
catch { }
|
|
340
|
+
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
|
+
const chunk = this.getNextChunk();
|
|
353
|
+
if (this.audioSender) {
|
|
354
|
+
try {
|
|
355
|
+
this.audioSender.sendCapturedAudio(chunk);
|
|
356
|
+
}
|
|
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
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}, this.intervalMs);
|
|
373
|
+
}
|
|
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
|
+
stopCapture() {
|
|
387
|
+
if (this.captureInterval) {
|
|
388
|
+
this.captureInterval.clear();
|
|
389
|
+
this.captureInterval = null;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
this.loopDelay?.disable();
|
|
393
|
+
}
|
|
394
|
+
catch { }
|
|
395
|
+
}
|
|
396
|
+
stop() {
|
|
397
|
+
this.stopPlayback();
|
|
398
|
+
this.stopCapture();
|
|
399
|
+
}
|
|
400
|
+
hasAudio() {
|
|
401
|
+
return this.audioBuffer !== null && this.audioBuffer.length > 0;
|
|
402
|
+
}
|
|
403
|
+
resetBuffer() {
|
|
404
|
+
this.bufferWritePos = 0;
|
|
405
|
+
this.bufferReadPos = 0;
|
|
406
|
+
this.bufferLength = 0;
|
|
407
|
+
}
|
|
408
|
+
writeToBuffer(data) {
|
|
409
|
+
for (let i = 0; i < data.length && this.bufferLength < this.maxBuffer; i++) {
|
|
410
|
+
this.circularBuffer[this.bufferWritePos] = data[i];
|
|
411
|
+
this.bufferWritePos = (this.bufferWritePos + 1) % this.maxBuffer;
|
|
412
|
+
this.bufferLength++;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
readFromBuffer(count) {
|
|
416
|
+
this.playbackOutputBuffer.fill(0);
|
|
417
|
+
for (let i = 0; i < count; i++) {
|
|
418
|
+
if (this.bufferLength > 0) {
|
|
419
|
+
this.playbackOutputBuffer[i] = this.circularBuffer[this.bufferReadPos];
|
|
420
|
+
this.bufferReadPos = (this.bufferReadPos + 1) % this.maxBuffer;
|
|
421
|
+
this.bufferLength--;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return this.playbackOutputBuffer;
|
|
425
|
+
}
|
|
426
|
+
getNextChunk() {
|
|
427
|
+
if (!this.audioBuffer) {
|
|
428
|
+
return this.silenceChunkBuffer;
|
|
429
|
+
}
|
|
430
|
+
const endPos = this.externalMode ? this.liveWritePos : this.audioBuffer.length;
|
|
431
|
+
if (endPos === 0 || (this.audioFinished && !this.externalMode)) {
|
|
432
|
+
return this.silenceChunkBuffer;
|
|
433
|
+
}
|
|
434
|
+
if (this.externalMode) {
|
|
435
|
+
const available = endPos - this.audioPosition;
|
|
436
|
+
if (!this.extStarted) {
|
|
437
|
+
if (available < this.extPreBufferSize) {
|
|
438
|
+
return this.silenceChunkBuffer;
|
|
439
|
+
}
|
|
440
|
+
this.extStarted = true;
|
|
441
|
+
this.logger.debug('live buffer ready, starting read', {
|
|
442
|
+
availableSamples: available
|
|
443
|
+
});
|
|
444
|
+
}
|
|
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
|
+
});
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (this.audioPosition >= endPos) {
|
|
460
|
+
return this.silenceChunkBuffer;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
this.captureChunkBuffer.fill(0);
|
|
464
|
+
for (let i = 0; i < this.captureChunkSize; i++) {
|
|
465
|
+
if (this.audioPosition >= endPos) {
|
|
466
|
+
if (this.loopMode && !this.externalMode && endPos > 0) {
|
|
467
|
+
this.audioPosition = 0;
|
|
468
|
+
if (this.audioPosition >= endPos) break;
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (!this.externalMode && !this.audioFinished) {
|
|
472
|
+
this.audioFinished = true;
|
|
473
|
+
this.logger.debug('audio playback finished, sending silence');
|
|
474
|
+
if (this.onAudioFinished) {
|
|
475
|
+
const cb = this.onAudioFinished;
|
|
476
|
+
setTimeout(() => cb(), 0);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
this.captureChunkBuffer[i] = this.audioBuffer[this.audioPosition];
|
|
482
|
+
this.audioPosition++;
|
|
483
|
+
}
|
|
484
|
+
return this.captureChunkBuffer;
|
|
485
|
+
}
|
|
486
|
+
}
|