@hiroosy/baileys-lite 0.3.7 → 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.
@@ -1,6 +1,5 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { EventEmitter } from 'node:events';
3
- import { createNoopLogger } from '../../shim/core.js';
4
3
  import * as sctp from './wire.js';
5
4
 
6
5
  const SCTP_PORT = 5000;
@@ -11,9 +10,11 @@ const HEARTBEAT_INTERVAL_MS = 5000;
11
10
  const SEND_WINDOW_SIZE = 32;
12
11
  const MAX_VIDEO_QUEUE_AGE_MS = 400;
13
12
  const MAX_QUEUED_VIDEO_PACKETS = 200;
14
- const MAX_QUEUED_AUDIO_FRAMES = 20;
13
+ const MAX_QUEUED_AUDIO_FRAMES = 6;
15
14
  const MAX_VIDEO_IN_FLIGHT = 24;
16
15
  const STALE_GAP_TSN_LIMIT = 512;
16
+ const videoBurstBytes = 8192;
17
+ const videoPaceBytesPerMs = 120;
17
18
 
18
19
  function randomUint32() {
19
20
  return randomBytes(4).readUInt32BE(0);
@@ -21,15 +22,12 @@ function randomUint32() {
21
22
 
22
23
  export class SctpAssociation extends EventEmitter {
23
24
  #sendDtlsPayload;
24
- #logger;
25
25
  #state = 'idle';
26
26
 
27
27
  #myTag = randomUint32();
28
28
  #peerVerificationTag = 0;
29
29
  #initialTsn = randomUint32();
30
30
  #nextTsn;
31
- #peerInitialTsn = 0;
32
- #cumulativeAckReceived = -1;
33
31
  #stateCookie = null;
34
32
  #retransmitTimer = null;
35
33
  #initRetries = 0;
@@ -45,11 +43,16 @@ export class SctpAssociation extends EventEmitter {
45
43
  #videoQueue = [];
46
44
  #inboundCumulativeTsn = -1;
47
45
  #inboundReceivedAheadTsns = new Set();
48
-
49
- constructor({ sendDtlsPayload, logger }) {
46
+ #srttMs = null;
47
+ #rttVarMs = 0;
48
+ #rtoMs = RETRANSMIT_TIMEOUT_MS;
49
+ #videoBudgetBytes = videoBurstBytes;
50
+ #videoBudgetAt = performance.now();
51
+ #paceTimer = null;
52
+
53
+ constructor({ sendDtlsPayload }) {
50
54
  super();
51
55
  this.#sendDtlsPayload = sendDtlsPayload;
52
- this.#logger = logger ?? createNoopLogger();
53
56
  this.#nextTsn = this.#initialTsn;
54
57
  }
55
58
 
@@ -61,6 +64,8 @@ export class SctpAssociation extends EventEmitter {
61
64
  close() {
62
65
  this.#state = 'closed';
63
66
  clearTimeout(this.#retransmitTimer);
67
+ clearTimeout(this.#paceTimer);
68
+ this.#paceTimer = null;
64
69
  clearInterval(this.#heartbeatTimer);
65
70
  for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
66
71
  this.#inFlight.clear();
@@ -97,12 +102,8 @@ export class SctpAssociation extends EventEmitter {
97
102
  const oldest = this.#videoQueue[0];
98
103
  if (this.#videoQueue.length > MAX_QUEUED_VIDEO_PACKETS ||
99
104
  now - oldest.queuedAtMs > MAX_VIDEO_QUEUE_AGE_MS) {
100
- const dropped = this.#videoQueue.length;
101
105
  this.#videoQueue = [];
102
106
  this.#videoFlushCount++;
103
- this.#logger.trace('sctp flushed stale video queue to protect audio latency', {
104
- dropped
105
- });
106
107
  }
107
108
  }
108
109
  this.#pumpSendQueue();
@@ -114,21 +115,9 @@ export class SctpAssociation extends EventEmitter {
114
115
  try {
115
116
  header = sctp.parsePacketHeader(plaintext);
116
117
  } catch (e) {
117
-
118
- this.#logger.trace('sctp payload failed to parse', {
119
- message: e.message, bytes: plaintext.length, hex: Buffer.from(plaintext).toString('hex')
120
- });
121
118
  return;
122
119
  }
123
- const chunkTypesForLog = sctp.splitChunks(plaintext, header.chunksStart).map((c) => c.type);
124
- this.#logger.trace('sctp recv packet', {
125
- vtag: `0x${header.verificationTag.toString(16)}`,
126
- expectVtag: `0x${this.#myTag.toString(16)}`,
127
- chunkTypes: chunkTypesForLog,
128
- state: this.#state
129
- });
130
120
  if (this.#state !== 'wait_init_ack' && header.verificationTag !== this.#myTag) {
131
-
132
121
  return;
133
122
  }
134
123
  const chunks = sctp.splitChunks(plaintext, header.chunksStart);
@@ -146,13 +135,6 @@ export class SctpAssociation extends EventEmitter {
146
135
  });
147
136
 
148
137
  const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: 0, chunks: [chunk] });
149
- this.#logger.trace('sctp sending INIT', {
150
- myTag: `0x${this.#myTag.toString(16)}`, initialTsn: this.#initialTsn, attempt: this.#initRetries
151
- });
152
- if (this.#initRetries === 0) {
153
-
154
- this.#logger.trace('sctp INIT packet hex (first attempt only)', { hex: packet.toString('hex') });
155
- }
156
138
  this.#sendDtlsPayload(packet);
157
139
  clearTimeout(this.#retransmitTimer);
158
140
  this.#retransmitTimer = setTimeout(() => {
@@ -193,6 +175,14 @@ export class SctpAssociation extends EventEmitter {
193
175
  payload = this.#audioQueue.shift();
194
176
  isAudio = true;
195
177
  } else if (this.#videoQueue.length > 0 && this.#videoInFlightCount < MAX_VIDEO_IN_FLIGHT) {
178
+ this.#refillVideoBudget(performance.now());
179
+ const headBytes = this.#videoQueue[0].payload.length;
180
+ const neededBytes = Math.min(headBytes, videoBurstBytes);
181
+ if (this.#videoBudgetBytes < neededBytes) {
182
+ this.#scheduleVideoPump(neededBytes);
183
+ break;
184
+ }
185
+ this.#videoBudgetBytes -= headBytes;
196
186
  payload = this.#videoQueue.shift().payload;
197
187
  isAudio = false;
198
188
  } else {
@@ -203,7 +193,7 @@ export class SctpAssociation extends EventEmitter {
203
193
  const streamSeq = isAudio ? this.#outboundStreamSeq++ : this.#outboundVideoStreamSeq++;
204
194
  const chunk = sctp.buildData({ tsn, streamId: 0, streamSeq, ppid: 53, payload, unordered: isAudio });
205
195
  const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
206
- const entry = { packet, timer: null, isAudio };
196
+ const entry = { packet, timer: null, isAudio, sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
207
197
  this.#inFlight.set(tsn, entry);
208
198
  if (!isAudio) this.#videoInFlightCount++;
209
199
  this.#sendDtlsPayload(packet);
@@ -215,12 +205,59 @@ export class SctpAssociation extends EventEmitter {
215
205
 
216
206
  #armDataRetransmit(tsn, entry) {
217
207
  clearTimeout(entry.timer);
208
+ const delayMs = Math.min(RETRANSMIT_TIMEOUT_MS, this.#rtoMs * 2 ** entry.attempts);
218
209
  entry.timer = setTimeout(() => {
219
210
  if (!this.#inFlight.has(tsn)) return;
220
211
  this.#retransmitCount++;
212
+ entry.attempts++;
213
+ entry.retransmitted = true;
214
+ entry.missing = 0;
215
+ entry.sentAt = performance.now();
221
216
  this.#sendDtlsPayload(entry.packet);
222
217
  this.#armDataRetransmit(tsn, entry);
223
- }, RETRANSMIT_TIMEOUT_MS);
218
+ }, delayMs);
219
+ }
220
+
221
+ #refillVideoBudget(now) {
222
+ this.#videoBudgetBytes = Math.min(videoBurstBytes, this.#videoBudgetBytes + (now - this.#videoBudgetAt) * videoPaceBytesPerMs);
223
+ this.#videoBudgetAt = now;
224
+ }
225
+
226
+ #scheduleVideoPump(bytesNeeded) {
227
+ if (this.#paceTimer) return;
228
+ const waitMs = Math.ceil((bytesNeeded - this.#videoBudgetBytes) / videoPaceBytesPerMs);
229
+ this.#paceTimer = setTimeout(() => {
230
+ this.#paceTimer = null;
231
+ this.#pumpSendQueue();
232
+ }, waitMs);
233
+ }
234
+
235
+ #updateRto(sampleMs) {
236
+ if (this.#srttMs === null) {
237
+ this.#srttMs = sampleMs;
238
+ this.#rttVarMs = sampleMs / 2;
239
+ } else {
240
+ this.#rttVarMs = 0.75 * this.#rttVarMs + 0.25 * Math.abs(this.#srttMs - sampleMs);
241
+ this.#srttMs = 0.875 * this.#srttMs + 0.125 * sampleMs;
242
+ }
243
+ this.#rtoMs = Math.min(RETRANSMIT_TIMEOUT_MS, Math.max(500, this.#srttMs + 4 * this.#rttVarMs));
244
+ }
245
+
246
+ #fastRetransmitMissing(highestTsn, latestAckedSentAt) {
247
+ const reorderWindowMs = this.#srttMs === null ? 0 : this.#srttMs / 4;
248
+ for (const [tsn, entry] of this.#inFlight) {
249
+ const behind = (highestTsn - tsn) >>> 0;
250
+ if (behind === 0 || behind >= 0x80000000) continue;
251
+ if (entry.sentAt + reorderWindowMs >= latestAckedSentAt) continue;
252
+ entry.missing++;
253
+ if (entry.missing < 3) continue;
254
+ entry.missing = 0;
255
+ entry.retransmitted = true;
256
+ entry.sentAt = performance.now();
257
+ this.#retransmitCount++;
258
+ this.#sendDtlsPayload(entry.packet);
259
+ this.#armDataRetransmit(tsn, entry);
260
+ }
224
261
  }
225
262
 
226
263
  #handleChunk(chunk, header) {
@@ -230,7 +267,6 @@ export class SctpAssociation extends EventEmitter {
230
267
  const parsed = sctp.parseInitOrInitAck(chunk.value);
231
268
  if (!parsed.stateCookie) { this.#fail(new Error('SCTP: INIT ACK missing State Cookie')); return; }
232
269
  this.#peerVerificationTag = parsed.initiateTag;
233
- this.#peerInitialTsn = parsed.initialTsn;
234
270
  this.#inboundExpectedStreamSeq = 0;
235
271
  this.#inboundCumulativeTsn = (parsed.initialTsn - 1) >>> 0;
236
272
  this.#inboundReceivedAheadTsns.clear();
@@ -276,7 +312,6 @@ export class SctpAssociation extends EventEmitter {
276
312
  }
277
313
 
278
314
  #handleIncomingData({ tsn, streamId, streamSeq, ppid, payload, unordered }) {
279
-
280
315
  this.#recordInboundTsn(tsn);
281
316
  this.#buildAndSendSack();
282
317
 
@@ -301,9 +336,6 @@ export class SctpAssociation extends EventEmitter {
301
336
  this.#reorderBuffer.set(streamSeq, payload);
302
337
  if (this.#reorderBuffer.size > STALE_GAP_TSN_LIMIT) {
303
338
  const bufferedSeqs = [...this.#reorderBuffer.keys()].sort((a, b) => a - b);
304
- this.#logger.debug('sctp: forcing stream sequence past a stuck gap', {
305
- from: this.#inboundExpectedStreamSeq, bufferedCount: bufferedSeqs.length
306
- });
307
339
  this.#inboundExpectedStreamSeq = bufferedSeqs[0];
308
340
  const buffered = this.#reorderBuffer.get(this.#inboundExpectedStreamSeq);
309
341
  this.#reorderBuffer.delete(this.#inboundExpectedStreamSeq);
@@ -317,7 +349,6 @@ export class SctpAssociation extends EventEmitter {
317
349
  }
318
350
  }
319
351
  }
320
-
321
352
  }
322
353
 
323
354
  #recordInboundTsn(tsn) {
@@ -338,9 +369,6 @@ export class SctpAssociation extends EventEmitter {
338
369
  if (offset > maxAheadOffset) maxAheadOffset = offset;
339
370
  }
340
371
  const jumpTo = (this.#inboundCumulativeTsn + maxAheadOffset) >>> 0;
341
- this.#logger.debug('sctp: forcing cumulative TSN past a stuck gap', {
342
- from: this.#inboundCumulativeTsn, to: jumpTo, aheadCount: this.#inboundReceivedAheadTsns.size
343
- });
344
372
  this.#inboundReceivedAheadTsns.delete(jumpTo);
345
373
  this.#inboundCumulativeTsn = jumpTo;
346
374
  }
@@ -380,28 +408,33 @@ export class SctpAssociation extends EventEmitter {
380
408
 
381
409
  #handleSack({ cumulativeTsnAck, gapAckBlocks }) {
382
410
  if (this.#inFlight.size === 0) return;
411
+ const now = performance.now();
383
412
  let acked = false;
413
+ let rttSample = null;
414
+ let latestAckedSentAt = -1;
415
+ const release = (tsn, entry) => {
416
+ clearTimeout(entry.timer);
417
+ this.#inFlight.delete(tsn);
418
+ if (!entry.isAudio) this.#videoInFlightCount--;
419
+ if (!entry.retransmitted) rttSample = now - entry.sentAt;
420
+ if (entry.sentAt > latestAckedSentAt) latestAckedSentAt = entry.sentAt;
421
+ acked = true;
422
+ };
384
423
  for (const [tsn, entry] of this.#inFlight) {
385
- if (sackAcksTsn(cumulativeTsnAck, tsn)) {
386
- clearTimeout(entry.timer);
387
- this.#inFlight.delete(tsn);
388
- if (!entry.isAudio) this.#videoInFlightCount--;
389
- acked = true;
390
- }
424
+ if (sackAcksTsn(cumulativeTsnAck, tsn)) release(tsn, entry);
391
425
  }
426
+ let highestGapOffset = -1;
392
427
  if (gapAckBlocks && gapAckBlocks.length > 0 && this.#inFlight.size > 0) {
393
428
  for (const block of gapAckBlocks) {
429
+ if (block.end > highestGapOffset) highestGapOffset = block.end;
394
430
  for (const [tsn, entry] of this.#inFlight) {
395
431
  const offset = (tsn - cumulativeTsnAck) >>> 0;
396
- if (offset >= block.start && offset <= block.end) {
397
- clearTimeout(entry.timer);
398
- this.#inFlight.delete(tsn);
399
- if (!entry.isAudio) this.#videoInFlightCount--;
400
- acked = true;
401
- }
432
+ if (offset >= block.start && offset <= block.end) release(tsn, entry);
402
433
  }
403
434
  }
404
435
  }
436
+ if (rttSample !== null) this.#updateRto(rttSample);
437
+ if (highestGapOffset >= 0 && latestAckedSentAt >= 0) this.#fastRetransmitMissing((cumulativeTsnAck + highestGapOffset) >>> 0, latestAckedSentAt);
405
438
  if (acked) this.#pumpSendQueue();
406
439
  }
407
440
 
@@ -416,6 +449,8 @@ export class SctpAssociation extends EventEmitter {
416
449
  #fail(err) {
417
450
  this.#state = 'closed';
418
451
  clearTimeout(this.#retransmitTimer);
452
+ clearTimeout(this.#paceTimer);
453
+ this.#paceTimer = null;
419
454
  clearInterval(this.#heartbeatTimer);
420
455
  for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
421
456
  this.#inFlight.clear();
@@ -175,11 +175,13 @@ function encodeXorRelayedAddress(ip, port) {
175
175
  return data;
176
176
  }
177
177
 
178
- export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort) {
179
- const transactionId = generateTransactionId();
178
+ export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort, username, transactionId = generateTransactionId()) {
180
179
  const parts = [];
181
180
  parts.push(encodeAttribute(ATTR_SENDER_SUBSCRIPTIONS, relayToken));
182
181
  parts.push(encodeAttribute(ATTR_SSRC_LIST, streamDescriptors));
182
+ parts.push(encodeAttribute(ATTR_REQUESTED_TRANSPORT, new Uint8Array([17, 0, 0, 0])));
183
+ if (username && username.length > 0)
184
+ parts.push(encodeAttribute(ATTR_USERNAME, username));
183
185
  parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, encodeXorRelayedAddress(relayIp, relayPort)));
184
186
  const attrs = concatBytes(parts);
185
187
  return buildStunMessage(STUN_ALLOCATE_REQUEST, attrs, transactionId, hmacKey, false);
@@ -236,8 +238,7 @@ export function buildBindingSuccessResponse(transactionId, mappedIp, mappedPort,
236
238
  const STUN_BINDING_SUCCESS_RESPONSE = 0x0101;
237
239
  return buildStunMessage(STUN_BINDING_SUCCESS_RESPONSE, attrs, transactionId, hmacKey, true);
238
240
  }
239
- export function buildBindingRequestWithSubs(username, hmacKey, senderSubscriptions, includeIceControlling, includeFingerprint) {
240
- const transactionId = generateTransactionId();
241
+ export function buildBindingRequestWithSubs(username, hmacKey, senderSubscriptions, includeIceControlling, includeFingerprint, transactionId = generateTransactionId()) {
241
242
  const parts = [];
242
243
  if (username && username.length > 0) {
243
244
  parts.push(encodeAttribute(ATTR_USERNAME, username));
@@ -279,8 +280,7 @@ export function buildAllocateRequest(username, hmacKey, lifetime = 3600) {
279
280
  export function buildRelayBindingSuccess(transactionId, hmacKey) {
280
281
  return buildStunMessage(0x0101, new Uint8Array(0), transactionId, hmacKey, true);
281
282
  }
282
- export function buildWhatsAppPing() {
283
- const transactionId = generateTransactionId();
283
+ export function buildWhatsAppPing(transactionId = generateTransactionId()) {
284
284
  const header = new Uint8Array(20);
285
285
  writeUInt16BE(header, WHATSAPP_PING, 0);
286
286
  writeUInt16BE(header, 0, 2);
package/src/voip/types.js CHANGED
@@ -46,7 +46,7 @@ export const DEFAULT_VIDEO_CONFIG = {
46
46
  export const DEFAULT_AUDIO_CONFIG = {
47
47
  sampleRate: 16000,
48
48
  captureChunkSize: 960,
49
- playbackOutputSize: 256,
49
+ playbackOutputSize: 960,
50
50
  maxBufferSize: 1600,
51
51
  intervalMs: 60
52
52
  };
@@ -248,7 +248,9 @@ export class VoipClient {
248
248
  ['call_video_state', 'peer_video', (c, change) => [change]],
249
249
  ['call_inbound_audio', 'inbound_audio', (c, pcm) => [pcm]],
250
250
  ['call_inbound_video', 'inbound_video', (c, frame) => [frame]],
251
- ['call_outbound_audio_finished', 'audio_finished', () => []]
251
+ ['call_outbound_audio_finished', 'audio_finished', () => []],
252
+ ['call_reconnecting', 'reconnecting', (c, detail) => [detail]],
253
+ ['call_reconnected', 'reconnected', () => []]
252
254
  ].map(([source, target, shape]) => {
253
255
  const listener = (info, ...rest) => {
254
256
  if (info?.callId === callId)