@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.
@@ -5,7 +5,7 @@ import { concatBytes, EMPTY_BYTES, readUInt32BE, toArrayBuffer } from '../bytes.
5
5
  import { derivePerJidSrtpKey } from '../crypto/encryption.js';
6
6
  import { SrtpSession } from '../crypto/srtp.js';
7
7
  import { SrtcpSendContext } from '../crypto/rtcp.js';
8
- import { generateSecureSsrc } from '../crypto/ssrc.js';
8
+ import { deriveWasmRelayStreamSsrcs, generateSecureSsrc } from '../crypto/ssrc.js';
9
9
  import { WaAppDataStream } from '../app-data/WaAppDataStream.js';
10
10
  import { buildScreenShareStanza, parseScreenShareNode, WA_SCREEN_SHARE_STATE } from '../signaling/screen-share.js';
11
11
  import { MLowCodec } from '../media/mlow-codec.js';
@@ -16,12 +16,10 @@ import { WaAudioEngine } from '../media/WaAudioEngine.js';
16
16
  import { WaVideoEngine } from '../media/WaVideoEngine.js';
17
17
  import { parseRelayFromAck } from '../relay/relay-ack.js';
18
18
  import { isRtpPacket, isStunPacket } from '../relay/stun.js';
19
- import { deriveWasmRelayStreamSsrcs } from '../crypto/ssrc.js';
20
19
  import { WaManualRelay } from '../relay/WaManualRelay.js';
21
20
  import { buildAcceptReceiptStanza, buildAcceptStanza, buildMuteV2Stanza, buildPreacceptStanza, buildRaiseHandStanza, buildRejectStanza, buildRelaylatencyForwardStanza, buildRelayLatencyStanza, buildTerminateStanza, buildTransportStanza, buildVideoStateStanza, decryptCallKey, extractNodeInfo, extractRelayEndpoints, needsDecryption, parseMuteV2, parseRaiseHandState, VideoDecAccept, VideoDecRequest, VideoState } from '../signaling/signaling.js';
22
21
  import { CallDirection, CallMediaType, CallState, EndCallReason, PayloadType, SRTP_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN, SRTP_SEND_AUTH_TAG_LEN } from '../types.js';
23
22
 
24
-
25
23
  export class WaCallMediaSession {
26
24
  info;
27
25
  deps;
@@ -34,6 +32,9 @@ export class WaCallMediaSession {
34
32
  audioEngine;
35
33
  initialTransportSent = false;
36
34
  outgoingPreacceptSent = false;
35
+ answeredRelays = new Map();
36
+ announcedRelayNames = new Set();
37
+ relayLatencyOpened = false;
37
38
  selfSsrc = 0;
38
39
  selfSsrcJid = '';
39
40
  peerSsrcs = [];
@@ -58,10 +59,9 @@ export class WaCallMediaSession {
58
59
  selfEchoCount = 0;
59
60
  lastRecvSeq = -1;
60
61
  recvSeqGaps = 0;
61
- lastCapturedAtMs = undefined;
62
- qLog = { n: 0, tiny: 0, sent: 0, octets: 0, retx: 0, rx: 0, plc: 0, late: 0, fec: 0, errors: 0 };
63
62
  actualPeerSsrc = null;
64
63
  ssrcResubscribed = false;
64
+ reconnecting = false;
65
65
 
66
66
  videoSsrc = 0;
67
67
  videoRtpStream = null;
@@ -113,13 +113,38 @@ export class WaCallMediaSession {
113
113
  this.sctpRelay.on('relay_connected', () => {
114
114
  this.onRelayConnected();
115
115
  });
116
+ this.sctpRelay.on('relay_answered', (detail) => {
117
+ this.onRelayAnswered(detail);
118
+ });
116
119
  this.sctpRelay.on('relay_receive', (relayInfo) => {
117
120
  this.onRelayData(relayInfo.data);
118
121
  });
122
+ this.sctpRelay.on('relay_lost', (detail) => {
123
+ if (!detail.anyOpen)
124
+ this.markReconnecting({ attempt: 0, max: detail.max });
125
+ });
126
+ this.sctpRelay.on('relay_retrying', (detail) => {
127
+ if (!detail.anyOpen)
128
+ this.markReconnecting({ attempt: detail.attempt, max: detail.max });
129
+ });
130
+ this.sctpRelay.on('relay_recovered', () => {
131
+ if (!this.reconnecting || !this.sctpRelay.hasConnection())
132
+ return;
133
+ this.reconnecting = false;
134
+ this.delegate.emitReconnected(this.info);
135
+ });
136
+ this.sctpRelay.on('relay_failed', (detail) => {
137
+ if (!detail.anyOpen)
138
+ this.endCall(EndCallReason.Failed).catch(() => { });
139
+ });
119
140
  }
120
141
  get callId() {
121
142
  return this.info.callId;
122
143
  }
144
+ markReconnecting(detail) {
145
+ this.reconnecting = true;
146
+ this.delegate.emitReconnecting(this.info, detail);
147
+ }
123
148
  onDecodedAudio = (pcm) => {
124
149
  this.audioEngine.onPlaybackData(pcm);
125
150
  this.delegate.emitInboundAudio?.(this.info, pcm);
@@ -131,31 +156,11 @@ export class WaCallMediaSession {
131
156
  this.selfSsrcJid = this.ensureDeviceJid(selfLid);
132
157
  const peerSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(peerJid));
133
158
  this.peerSsrcs = [peerSsrc];
134
- this.logger.media('call media initialized', {
135
- callId: this.info.callId,
136
- selfSsrc: `0x${ssrc.toString(16).toUpperCase()}`,
137
- peerSsrc: `0x${peerSsrc.toString(16).toUpperCase()}`
138
- });
139
- this.logger.warn('[DIAG] initMedia called', {
140
- callId: this.info.callId,
141
- selfSsrc: `0x${ssrc.toString(16).toUpperCase()}`,
142
- peerSsrc: `0x${peerSsrc.toString(16).toUpperCase()}`,
143
- videoEngineIsFresh: this.videoEngine?.proc === null
144
- });
145
159
  this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }) });
146
160
  if (this.info.mediaType === CallMediaType.Video) {
147
-
148
161
  this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
149
162
  this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
150
163
  this.videoAssembler = new H264AccessUnitAssembler();
151
- this.logger.media('video media initialized', {
152
- callId: this.info.callId,
153
- videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`
154
- });
155
- this.logger.warn('[DIAG] video media initialized', {
156
- callId: this.info.callId,
157
- videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`
158
- });
159
164
  }
160
165
  }
161
166
  resetOutgoingFlags() {
@@ -207,7 +212,6 @@ export class WaCallMediaSession {
207
212
  if (this.info.relayData) {
208
213
  await this.connectRelays(this.info.relayData.endpoints);
209
214
  }
210
- this.logger.media('call accepted', { callId });
211
215
  }
212
216
  async rejectCall(reason = EndCallReason.Declined) {
213
217
  this.info.applyTransition({ type: 'local_rejected', reason });
@@ -255,15 +259,13 @@ export class WaCallMediaSession {
255
259
  }
256
260
  async loadAudio(audioPath) {
257
261
  this.audioEngine.setLoopMode(false);
258
- await this.audioEngine.loadAudioFile(audioPath);
262
+ await this.audioEngine.loadSource(audioPath);
259
263
  this.resetEncodeState();
260
- this.logger.media('audio loaded for call', { callId: this.info.callId });
261
264
  }
262
265
  setExternalAudioMode(enabled) {
263
266
  this.audioEngine.setExternalMode(enabled);
264
267
  if (enabled) {
265
268
  this.resetEncodeState();
266
- this.logger.debug('external audio mode enabled', { callId: this.info.callId });
267
269
  }
268
270
  }
269
271
  feedLiveAudio(data) {
@@ -283,24 +285,31 @@ export class WaCallMediaSession {
283
285
  });
284
286
  }
285
287
  }
286
- async sendIncomingRelayLatency() {
288
+ onRelayAnswered(detail) {
289
+ if (!detail?.name || this.answeredRelays.has(detail.name))
290
+ return;
291
+ this.answeredRelays.set(detail.name, detail.rttMs);
292
+ if (this.relayLatencyOpened) {
293
+ void this.announceRelayLatency();
294
+ }
295
+ }
296
+ async announceRelayLatency(isEligible = (ep) => this.answeredRelays.has(ep.relayName)) {
287
297
  if (!this.info.relayData)
288
298
  return;
289
299
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
290
300
  const callId = this.info.callId;
291
301
  const callCreator = this.info.callCreator;
292
302
  const destinationJids = this.info.relayData.participantJids || [];
293
- const seenRelayNames = new Set();
294
303
  for (const ep of this.info.relayData.endpoints) {
295
304
  const name = ep.relayName || '';
296
- if (!name || seenRelayNames.has(name))
305
+ if (!name || ep.ip.includes(':') || this.announcedRelayNames.has(name) || !isEligible(ep))
297
306
  continue;
298
- seenRelayNames.add(name);
307
+ this.announcedRelayNames.add(name);
299
308
  try {
300
309
  const relayData = [
301
310
  {
302
311
  relayName: name,
303
- latency: ep.c2rRtt || 0,
312
+ latency: ep.c2rRtt ?? this.answeredRelays.get(name) ?? 0,
304
313
  addressBytes: ep.addressBytes
305
314
  }
306
315
  ];
@@ -308,13 +317,23 @@ export class WaCallMediaSession {
308
317
  await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
309
318
  }
310
319
  catch (err) {
311
- this.logger.error('error sending incoming relaylatency', {
320
+ this.announcedRelayNames.delete(name);
321
+ this.logger.error('error sending relaylatency', {
312
322
  relayName: name,
313
323
  message: toError(err).message
314
324
  });
315
325
  }
316
326
  }
317
327
  }
328
+ async sendIncomingRelayLatency() {
329
+ if (!this.info.relayData)
330
+ return;
331
+ this.relayLatencyOpened = true;
332
+ const dialed = new Set(this.selectRelayEndpoints(this.info.relayData.endpoints)
333
+ .slice(0, this.sctpRelay.maxActiveRelays)
334
+ .map((ep) => ep.relayName));
335
+ await this.announceRelayLatency((ep) => dialed.size === 0 || dialed.has(ep.relayName) || this.answeredRelays.has(ep.relayName));
336
+ }
318
337
  async handleCallAccept(node, peerJid) {
319
338
  const nodeInfo = extractNodeInfo(node);
320
339
  if (!nodeInfo)
@@ -344,9 +363,6 @@ export class WaCallMediaSession {
344
363
  const recvKeying = derivePerJidSrtpKey(peerCallKey, this.ensureDeviceJid(peerJid));
345
364
  this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
346
365
  srtpFromPeerKey = true;
347
- this.logger.debug('srtp re-initialized with peer call_key', {
348
- callId: this.info.callId
349
- });
350
366
  }
351
367
  catch (err) {
352
368
  this.logger.error('per-jid srtp re-derivation failed', {
@@ -367,9 +383,7 @@ export class WaCallMediaSession {
367
383
  this.info.applyTransition({ type: 'remote_accepted' });
368
384
  this.delegate.emitState(this.info);
369
385
  }
370
- catch (err) {
371
- this.logger.trace('call transition skipped', { message: toError(err).message });
372
- }
386
+ catch { }
373
387
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
374
388
  const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
375
389
  const ourJid = meLid || meId;
@@ -379,22 +393,12 @@ export class WaCallMediaSession {
379
393
  const acceptingDeviceJid = peerJid;
380
394
  this.acceptedByJid = acceptingDeviceJid;
381
395
  if (this.actualPeerSsrc !== null) {
382
- const calculatedJid = this.ensureDeviceJid(acceptingDeviceJid);
383
- this.logger.debug('accept keeping actual peer ssrc', {
384
- callId,
385
- actualPeerSsrc: `0x${this.actualPeerSsrc.toString(16)}`,
386
- calculatedJid
387
- });
396
+ this.ensureDeviceJid(acceptingDeviceJid);
388
397
  }
389
398
  else {
390
399
  const peerDeviceJidForSsrc = this.ensureDeviceJid(acceptingDeviceJid);
391
400
  const acceptSsrc = generateSecureSsrc(callId, peerDeviceJidForSsrc);
392
401
  this.peerSsrcs = [acceptSsrc];
393
- this.logger.debug('accept ssrc assigned', {
394
- callId,
395
- jid: peerDeviceJidForSsrc,
396
- ssrc: `0x${acceptSsrc.toString(16)}`
397
- });
398
402
  }
399
403
  this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
400
404
  this.sctpRelay.resendSubscriptions();
@@ -457,20 +461,14 @@ export class WaCallMediaSession {
457
461
  try {
458
462
  this.info.applyTransition({ type: 'media_connected' });
459
463
  this.delegate.emitState(this.info);
460
- const MEDIA_START_DELAY_MS = 3000;
461
464
  setTimeout(() => {
462
- this.logger.warn('[DIAG] delayed startMediaFlow firing (path B)', {
463
- callId: this.info.callId, state: this.info.stateData.state
464
- });
465
465
  if (this.info.stateData.state === CallState.Ended) {
466
466
  return;
467
467
  }
468
468
  this.startMediaFlow();
469
- }, MEDIA_START_DELAY_MS);
470
- }
471
- catch (err) {
472
- this.logger.trace('call transition skipped', { message: toError(err).message });
469
+ }, 3000);
473
470
  }
471
+ catch { }
474
472
  }
475
473
  else if (this.info.relayData) {
476
474
  await this.connectRelays(this.info.relayData.endpoints);
@@ -484,31 +482,8 @@ export class WaCallMediaSession {
484
482
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
485
483
  const callId = this.info.callId;
486
484
  const callCreator = this.info.callCreator;
487
- const destinationJids = this.info.relayData.participantJids || [];
488
- const seenRelayNames = new Set();
489
- for (const ep of this.info.relayData.endpoints) {
490
- const name = ep.relayName || '';
491
- if (!name || seenRelayNames.has(name))
492
- continue;
493
- seenRelayNames.add(name);
494
- try {
495
- const relayData = [
496
- {
497
- relayName: name,
498
- latency: ep.c2rRtt || 0,
499
- addressBytes: ep.addressBytes
500
- }
501
- ];
502
- const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
503
- await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
504
- }
505
- catch (err) {
506
- this.logger.error('error sending relaylatency', {
507
- relayName: name,
508
- message: toError(err).message
509
- });
510
- }
511
- }
485
+ this.relayLatencyOpened = true;
486
+ await this.announceRelayLatency();
512
487
  if (!this.initialTransportSent) {
513
488
  try {
514
489
  const basePeerJid = toUserJid(peerJid);
@@ -556,11 +531,6 @@ export class WaCallMediaSession {
556
531
  peerPid,
557
532
  hbhKey
558
533
  };
559
- this.logger.debug('offer ack relays parsed', {
560
- callId: this.info.callId,
561
- relayCount: relays.length,
562
- participantCount: participantJids.length
563
- });
564
534
  const callKey = this.info.encryptionKey;
565
535
  if (participantJids.length > 0) {
566
536
  const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
@@ -590,11 +560,6 @@ export class WaCallMediaSession {
590
560
  if (callKey) {
591
561
  this.initSrtpKeys();
592
562
  }
593
- else {
594
- this.logger.media('no call_key, srtp not initialized', {
595
- callId: this.info.callId
596
- });
597
- }
598
563
  }
599
564
  if (this.info.isInitiator && !this.outgoingPreacceptSent) {
600
565
  try {
@@ -664,10 +629,6 @@ export class WaCallMediaSession {
664
629
  }
665
630
  if (electedRelayIdx !== undefined) {
666
631
  this.info.electedRelayIdx = electedRelayIdx;
667
- this.logger.debug('elected relay index', {
668
- callId: this.info.callId,
669
- electedRelayIdx
670
- });
671
632
  }
672
633
  }
673
634
  async handleCallMuteV2(node, peerJid) {
@@ -824,13 +785,7 @@ export class WaCallMediaSession {
824
785
  this.delegate.emitCallReaction?.(this.info, reaction);
825
786
  }
826
787
  }
827
- catch (err) {
828
- this.logger.debug('app data packet dropped', {
829
- callId: this.info.callId,
830
- payloadType,
831
- message: toError(err).message
832
- });
833
- }
788
+ catch { }
834
789
  }
835
790
 
836
791
  async handleCallVideo(node) {
@@ -854,7 +809,6 @@ export class WaCallMediaSession {
854
809
  this.peerVideoActive = this.peerVideoJids.size > 0;
855
810
  return { before, after: this.peerVideoJids.size };
856
811
  };
857
- this.logger.media('inbound video state', { callId, state });
858
812
  switch (state) {
859
813
  case VideoState.UpgradeRequest:
860
814
  case VideoState.UpgradeRequestV2: {
@@ -956,11 +910,6 @@ export class WaCallMediaSession {
956
910
  if (this.sctpRelay.hasConnection()) {
957
911
  this.videoEngine.start();
958
912
  }
959
- this.logger.media('video enabled mid-call', {
960
- callId: this.info.callId,
961
- videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`,
962
- source: this.videoEngine.sourceKind
963
- });
964
913
  }
965
914
 
966
915
  async swapVideoSource(videoPath) {
@@ -971,7 +920,6 @@ export class WaCallMediaSession {
971
920
  await this.videoEngine.loadVideoFile(videoPath);
972
921
  this.audioEngine.setLoopMode(true);
973
922
  this.videoEngine.start();
974
- this.logger.media('video source swapped', { callId: this.info.callId, videoPath });
975
923
  }
976
924
 
977
925
  async stopVideoMidCall({ keepSource = false } = {}) {
@@ -996,7 +944,6 @@ export class WaCallMediaSession {
996
944
  this.videoRtcpSession = null;
997
945
  this.videoAssembler = null;
998
946
  this.info.mediaType = CallMediaType.Audio;
999
- this.logger.media('video disabled mid-call', { callId: this.info.callId, keptSource: keepSource });
1000
947
  }
1001
948
  handleCallTerminate() {
1002
949
  try {
@@ -1005,46 +952,15 @@ export class WaCallMediaSession {
1005
952
  reason: EndCallReason.UserEnded
1006
953
  });
1007
954
  }
1008
- catch (err) {
1009
- this.logger.trace('call transition skipped', { message: toError(err).message });
1010
- }
955
+ catch { }
1011
956
  this.delegate.emitEnded(this.info);
1012
957
  this.delegate.emitState(this.info);
1013
958
  this.cleanup();
1014
959
  }
1015
960
  sendCapturedAudio(data) {
1016
- const nowMs = Date.now();
1017
- if (this.lastCapturedAtMs !== undefined) {
1018
- const gapMs = nowMs - this.lastCapturedAtMs;
1019
-
1020
- if (gapMs > 300) {
1021
- this.logger.warn('captured audio frame gap larger than expected', {
1022
- callId: this.info.callId,
1023
- gapMs,
1024
- audioSendCount: this.audioSendCount,
1025
- sctpBacklog: this.sctpRelay.getSendBacklog()
1026
- });
1027
- }
1028
- }
1029
- this.lastCapturedAtMs = nowMs;
1030
961
  const hasRelay = this.sctpRelay.hasConnection();
1031
962
  if (!this.rtpSession || !this.srtpSession || !this.opusCodec || !hasRelay) {
1032
963
  this.audioDropCount++;
1033
- if (this.audioDropCount === 1 || this.audioDropCount % 500 === 0) {
1034
- const missing = [
1035
- !this.rtpSession && 'rtpSession',
1036
- !this.srtpSession && 'srtpSession',
1037
- !this.opusCodec && 'opusCodec',
1038
- !hasRelay && 'relayConnection'
1039
- ]
1040
- .filter(Boolean)
1041
- .join(', ');
1042
- this.logger.media('audio dropped', {
1043
- callId: this.info.callId,
1044
- dropCount: this.audioDropCount,
1045
- missing
1046
- });
1047
- }
1048
964
  return;
1049
965
  }
1050
966
  for (let i = 0; i < data.length; i++) {
@@ -1075,8 +991,6 @@ export class WaCallMediaSession {
1075
991
  this.encodeBufferPos = 0;
1076
992
  try {
1077
993
  const opusFrame = this.opusCodec.encode(frameData);
1078
- if (opusFrame.length <= 18)
1079
- this.qLog.tiny++;
1080
994
  this.sendOpusFrame(opusFrame, false);
1081
995
  this.realAudioSendCount++;
1082
996
  }
@@ -1105,16 +1019,6 @@ export class WaCallMediaSession {
1105
1019
  const hasRelay = this.sctpRelay.hasConnection();
1106
1020
  if (!this.videoRtpStream || !this.videoSrtpSession || !hasRelay) {
1107
1021
  this.videoDropCount++;
1108
- if (this.videoDropCount === 1 || this.videoDropCount % 150 === 0) {
1109
- const missing = [
1110
- !this.videoRtpStream && 'videoRtpStream',
1111
- !this.videoSrtpSession && 'videoSrtpSession',
1112
- !hasRelay && 'relayConnection'
1113
- ].filter(Boolean).join(', ');
1114
- this.logger.media('video access unit dropped', {
1115
- callId: this.info.callId, dropCount: this.videoDropCount, missing
1116
- });
1117
- }
1118
1022
  return;
1119
1023
  }
1120
1024
  try {
@@ -1149,13 +1053,6 @@ export class WaCallMediaSession {
1149
1053
  this.videoSendCount++;
1150
1054
  if (idr)
1151
1055
  this.videoIdrSendCount++;
1152
- if (idr || this.videoSendCount === 1 || this.videoSendCount % 150 === 0) {
1153
- this.logger.media('video sent', {
1154
- callId: this.info.callId, sendCount: this.videoSendCount,
1155
- idrSentTotal: this.videoIdrSendCount,
1156
- auBytes: au.length, packets: chunks.length, idr
1157
- });
1158
- }
1159
1056
  }
1160
1057
  catch (err) {
1161
1058
  this.logger.error('error sending video', {
@@ -1164,25 +1061,13 @@ export class WaCallMediaSession {
1164
1061
  }
1165
1062
  }
1166
1063
  cleanup() {
1167
- this.logger.warn('[DIAG] cleanup entered', { callId: this.info.callId, state: this.info.stateData.state });
1168
- const opusStats = this.opusCodec?.getStats();
1169
- this.logger.media('call stats', {
1170
- callId: this.info.callId,
1171
- relayPackets: this.relayPacketCount,
1172
- recvOk: this.audioRecvCount,
1173
- srtpErrors: this.srtpErrorCount,
1174
- sent: this.audioSendCount,
1175
- dropped: this.audioDropCount,
1176
- opusOk: opusStats?.success ?? 0,
1177
- opusErr: opusStats?.errors ?? 0,
1178
- videoSent: this.videoSendCount,
1179
- videoIdrSent: this.videoIdrSendCount,
1180
- videoDropped: this.videoDropCount
1181
- });
1182
1064
  this.audioEngine.setOnAudioFinished(null);
1183
1065
  this.audioEngine.stop();
1184
1066
  this.videoEngine.stop();
1185
1067
  this.sctpRelay.cleanup();
1068
+ this.answeredRelays.clear();
1069
+ this.announcedRelayNames.clear();
1070
+ this.relayLatencyOpened = false;
1186
1071
  if (this.rtcpTimer) {
1187
1072
  clearInterval(this.rtcpTimer);
1188
1073
  this.rtcpTimer = null;
@@ -1268,16 +1153,6 @@ export class WaCallMediaSession {
1268
1153
  this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1269
1154
  this.audioSendCount++;
1270
1155
  this.audioOctetsSent = (this.audioOctetsSent + rtpPayload.length) >>> 0;
1271
- if (this.audioSendCount === 1 || this.audioSendCount % 500 === 0) {
1272
- this.logger.media('audio sent', {
1273
- callId: this.info.callId,
1274
- sendCount: this.audioSendCount,
1275
- opusBytes: opusFrame.length,
1276
- srtpBytes: srtpData.length,
1277
- silence: isSilence,
1278
- sctpBacklog: this.sctpRelay.getSendBacklog()
1279
- });
1280
- }
1281
1156
  }
1282
1157
  catch (err) {
1283
1158
  this.logger.error('error sending audio', {
@@ -1294,7 +1169,6 @@ export class WaCallMediaSession {
1294
1169
  initSrtpKeys() {
1295
1170
  const callKey = this.info.encryptionKey;
1296
1171
  if (!callKey) {
1297
- this.logger.media('no call_key, srtp not initialized', { callId: this.info.callId });
1298
1172
  return;
1299
1173
  }
1300
1174
  const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
@@ -1326,23 +1200,12 @@ export class WaCallMediaSession {
1326
1200
  this.trackPeerAppDataSsrcs([peerDeviceJid, ...participants.filter((jid) => toUserJid(jid) !== ourBase)]);
1327
1201
  this.audioRtcpSession = new SrtcpSendContext(sendKeying);
1328
1202
  if (this.info.mediaType === CallMediaType.Video) {
1329
-
1330
1203
  this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1331
1204
  this.videoRtcpSession = new SrtcpSendContext(sendKeying);
1332
1205
  }
1333
1206
  this.startRtcpSenderReports();
1334
- this.logger.debug('srtp per-jid keys initialized', {
1335
- callId: this.info.callId,
1336
- sendJid: ourDeviceJid,
1337
- recvJid: peerDeviceJid
1338
- });
1339
- }
1340
- catch (err) {
1341
- this.logger.debug('srtp key derivation failed', {
1342
- callId: this.info.callId,
1343
- message: toError(err).message
1344
- });
1345
1207
  }
1208
+ catch { }
1346
1209
  }
1347
1210
 
1348
1211
  startRtcpSenderReports() {
@@ -1355,8 +1218,6 @@ export class WaCallMediaSession {
1355
1218
  this.rtcpTimer = setInterval(() => {
1356
1219
  if (!this.sctpRelay.hasConnection())
1357
1220
  return;
1358
- if (++this.qLog.n % 3 === 0)
1359
- this.logVoipQuality();
1360
1221
  const nowMs = Date.now();
1361
1222
  try {
1362
1223
  if (this.audioRtcpSession && this.selfSsrc) {
@@ -1379,27 +1240,8 @@ export class WaCallMediaSession {
1379
1240
  const protectedPacket = this.videoRtcpSession.protect(this.videoSsrc, plain);
1380
1241
  this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1381
1242
  }
1382
-
1383
- if (this.mediaStartedAtMs) {
1384
- const wallElapsedMs = nowMs - this.mediaStartedAtMs;
1385
- const audioElapsedMs = this.audioSendCount * 60;
1386
- const videoElapsedMs = this.videoSendCount * (1000 / this.videoEngine.frameRate);
1387
- this.logger.media('av sync check', {
1388
- callId: this.info.callId,
1389
- wallElapsedMs,
1390
- audioElapsedMs,
1391
- videoElapsedMs,
1392
- audioMinusWallMs: audioElapsedMs - wallElapsedMs,
1393
- videoMinusWallMs: Math.round(videoElapsedMs - wallElapsedMs)
1394
- });
1395
- }
1396
- }
1397
- catch (err) {
1398
- this.logger.debug('rtcp sender report failed', {
1399
- callId: this.info.callId,
1400
- message: toError(err).message
1401
- });
1402
1243
  }
1244
+ catch { }
1403
1245
  }, 1500);
1404
1246
  }
1405
1247
  resetEncodeState() {
@@ -1412,29 +1254,17 @@ export class WaCallMediaSession {
1412
1254
  try {
1413
1255
  this.info.applyTransition({ type: 'media_connected' });
1414
1256
  this.delegate.emitState(this.info);
1415
- this.logger.media('relay connected', {
1416
- callId: this.info.callId, acceptedByJid: this.acceptedByJid ?? null
1417
- });
1418
1257
  if (!this.acceptedByJid) {
1419
- this.logger.media('relay connected before accept, deferring media start', {
1420
- callId: this.info.callId
1421
- });
1422
1258
  return;
1423
1259
  }
1424
- const MEDIA_START_DELAY_MS = 3000;
1425
1260
  setTimeout(() => {
1426
- this.logger.warn('[DIAG] delayed startMediaFlow firing (path A)', {
1427
- callId: this.info.callId, state: this.info.stateData.state
1428
- });
1429
1261
  if (this.info.stateData.state === CallState.Ended) {
1430
1262
  return;
1431
1263
  }
1432
1264
  this.startMediaFlow();
1433
- }, MEDIA_START_DELAY_MS);
1434
- }
1435
- catch (err) {
1436
- this.logger.trace('call transition skipped', { message: toError(err).message });
1265
+ }, 3000);
1437
1266
  }
1267
+ catch { }
1438
1268
  }
1439
1269
  }
1440
1270
  onRelayData(data) {
@@ -1508,89 +1338,12 @@ export class WaCallMediaSession {
1508
1338
  const lossPct = pkts + gaps > 0 ? Math.min(100, Math.round((100 * gaps) / (pkts + gaps))) : 0;
1509
1339
  this.opusCodec.setExpectedPacketLossPercent(lossPct);
1510
1340
  }
1511
- if (this.audioRecvCount % 1500 === 0) {
1512
- const stats = this.opusCodec.getStats();
1513
-
1514
- this.logger.trace('audio recv stats', {
1515
- callId: this.info.callId,
1516
- recvCount: this.audioRecvCount,
1517
- real: this.recvRealCount,
1518
- dtx: this.recvDtxCount,
1519
- decodeOk: stats.success,
1520
- decodeErr: stats.errors,
1521
- plc: stats.plc,
1522
- fec: stats.fec,
1523
- late: stats.late
1524
- });
1525
- }
1526
1341
  }
1527
1342
  catch (err) {
1528
1343
  this.srtpErrorCount++;
1529
- if (this.srtpErrorCount <= 5) {
1530
- const ssrc = data.length >= 12 ? readUInt32BE(data, 8) : 0;
1531
- this.logger.debug('srtp recv error', {
1532
- callId: this.info.callId,
1533
- errorCount: this.srtpErrorCount,
1534
- message: toError(err).message,
1535
- ssrc: `0x${ssrc.toString(16)}`
1536
- });
1537
- }
1538
1344
  }
1539
1345
  }
1540
1346
 
1541
- logVoipQuality() {
1542
- try {
1543
- const q = this.qLog;
1544
- const pace = this.audioEngine.takePacingStats();
1545
- const bl = this.sctpRelay.getSendBacklog?.() ?? {};
1546
- const sent = this.audioSendCount - q.sent;
1547
- const octets = ((this.audioOctetsSent - q.octets) >>> 0);
1548
- const rs = this.opusCodec?.getStats() ?? { late: 0, plc: 0, fec: 0, errors: 0 };
1549
- const line = {
1550
- callId: this.info.callId,
1551
- tSec: this.mediaStartedAtMs ? Math.round((Date.now() - this.mediaStartedAtMs) / 1000) : 0,
1552
- txFrames: sent,
1553
- txAvgB: sent > 0 ? Math.round(octets / sent) : 0,
1554
- txTinyPct: sent > 0 ? Math.round((100 * (this.qLog.tiny)) / sent) : 0,
1555
- tickLate90: pace.late90,
1556
- tickLate200: pace.late200,
1557
- tickBurst: pace.burst20,
1558
- tickMaxGapMs: pace.maxGap,
1559
- loopP50ms: pace.loopP50,
1560
- loopP99ms: pace.loopP99,
1561
- loopMaxMs: pace.loopMax,
1562
- sctpInFlight: bl.inFlight ?? 0,
1563
- sctpQueuedAudio: bl.queuedAudio ?? 0,
1564
- sctpRetx: (bl.retransmits ?? 0) - q.retx,
1565
- aLagMs: this.mediaStartedAtMs ? this.audioSendCount * 60 - (Date.now() - this.mediaStartedAtMs) : 0,
1566
- vLagMs: this.mediaStartedAtMs && this.videoSendCount > 0 && this.videoEngine?.frameRate
1567
- ? Math.round(this.videoSendCount * (1000 / this.videoEngine.frameRate) - (Date.now() - this.mediaStartedAtMs))
1568
- : 0,
1569
- vRestarts: this.videoEngine?._restartCount ?? 0,
1570
- relayRx: this.relayPacketCount,
1571
- srtpErr: this.srtpErrorCount,
1572
- stun: this.sctpRelay.getRxStunStats?.() ?? {},
1573
- rxPkts: this.audioRecvCount - q.rx,
1574
- rxLate: rs.late - q.late,
1575
- rxPlc: rs.plc - q.plc,
1576
- rxFec: rs.fec - q.fec,
1577
- rxDecErr: rs.errors - q.errors
1578
- };
1579
- this.logger.warn('[VOIPQ] ' + JSON.stringify(line));
1580
- q.sent = this.audioSendCount;
1581
- q.octets = this.audioOctetsSent;
1582
- q.tiny = 0;
1583
- q.retx = bl.retransmits ?? 0;
1584
- q.rx = this.audioRecvCount;
1585
- q.late = rs.late;
1586
- q.plc = rs.plc;
1587
- q.fec = rs.fec;
1588
- q.errors = rs.errors;
1589
- }
1590
- catch (err) {
1591
- this.logger.trace('voip quality log failed', { message: toError(err).message });
1592
- }
1593
- }
1594
1347
  onRelayVideoData(data) {
1595
1348
  if (!this.videoSrtpSession || !this.videoAssembler)
1596
1349
  return;
@@ -1603,23 +1356,13 @@ export class WaCallMediaSession {
1603
1356
  }
1604
1357
  catch (err) {
1605
1358
  this.srtpErrorCount++;
1606
- if (this.srtpErrorCount <= 5) {
1607
- this.logger.debug('video srtp recv error', {
1608
- callId: this.info.callId,
1609
- message: toError(err).message
1610
- });
1611
- }
1612
1359
  }
1613
1360
  }
1614
- async connectRelays(endpoints) {
1615
- this.logger.debug('connecting relays', {
1616
- callId: this.info.callId,
1617
- endpointCount: endpoints.length
1618
- });
1361
+ selectRelayEndpoints(endpoints) {
1619
1362
  const seen = new Set();
1620
1363
  const uniqueEndpoints = [];
1621
1364
  for (const ep of endpoints) {
1622
- if ((ep.protocol ?? 0) !== 0)
1365
+ if ((ep.protocol ?? 0) !== 0 || ep.ip.includes(':'))
1623
1366
  continue;
1624
1367
  const key = `${ep.ip}:${ep.port}`;
1625
1368
  if (!seen.has(key)) {
@@ -1641,49 +1384,46 @@ export class WaCallMediaSession {
1641
1384
  usable[0] ??
1642
1385
  null;
1643
1386
  }
1644
- const WA_RELAY_PORT = 3478;
1645
- const relays = chosen
1646
- ? [
1647
- {
1648
- ip: chosen.ip,
1649
- port: WA_RELAY_PORT,
1650
- token: chosen.token,
1651
- authToken: chosen.authToken,
1652
- rawAuthToken: chosen.rawAuthToken,
1653
- rawToken: chosen.rawToken,
1654
- key: chosen.key,
1655
- relayId: chosen.relayId,
1656
- name: chosen.relayName || `${chosen.ip}:${WA_RELAY_PORT}`,
1657
- authTokenId: chosen.authTokenId,
1658
- isFna: chosen.isFna
1659
- }
1660
- ]
1661
- : [];
1387
+ const ordered = chosen ? [chosen] : [];
1388
+ const orderedAddresses = new Set(chosen ? [chosen.ip] : []);
1389
+ for (const ep of usable) {
1390
+ if (ordered.length >= 4)
1391
+ break;
1392
+ if (orderedAddresses.has(ep.ip))
1393
+ continue;
1394
+ orderedAddresses.add(ep.ip);
1395
+ ordered.push(ep);
1396
+ }
1397
+ return ordered;
1398
+ }
1399
+ async connectRelays(endpoints) {
1400
+ const ordered = this.selectRelayEndpoints(endpoints);
1401
+ const relays = ordered.map((ep) => ({
1402
+ ip: ep.ip,
1403
+ port: ep.port || 3478,
1404
+ token: ep.token,
1405
+ authToken: ep.authToken,
1406
+ rawAuthToken: ep.rawAuthToken,
1407
+ rawToken: ep.rawToken,
1408
+ key: ep.key,
1409
+ relayId: ep.relayId,
1410
+ name: ep.relayName || `${ep.ip}:${ep.port || 3478}`,
1411
+ authTokenId: ep.authTokenId,
1412
+ isFna: ep.isFna
1413
+ }));
1662
1414
  if (relays.length === 0) {
1663
1415
  this.logger.error('no relay configs', { callId: this.info.callId });
1664
1416
  return;
1665
1417
  }
1666
- this.logger.media('relay selected', {
1667
- callId: this.info.callId,
1668
- inbound,
1669
- candidateCount: usable.length,
1670
- chosen: relays[0].name,
1671
- isFna: relays[0].isFna
1672
- });
1673
- if (this.selfSsrcJid) {
1674
- this.sctpRelay.setStreamSsrcs(deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid));
1675
- }
1418
+ this.sctpRelay.setParticipantIds(this.info.relayData?.selfPid, this.info.relayData?.peerPid);
1676
1419
  this.sctpRelay.setSsrc(this.selfSsrc);
1420
+ this.sctpRelay.setStreamSsrcs(this.selfSsrcJid ? deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid) : null);
1677
1421
  if (this.info.mediaType === CallMediaType.Video) {
1678
1422
  this.sctpRelay.setVideoSsrc(this.videoSsrc);
1679
1423
  }
1680
1424
  this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1681
1425
  try {
1682
1426
  await this.sctpRelay.configureRelays(relays);
1683
- this.logger.debug('sctp relays configured', {
1684
- callId: this.info.callId,
1685
- connected: this.sctpRelay.getConnectedCount()
1686
- });
1687
1427
  }
1688
1428
  catch (err) {
1689
1429
  this.logger.error('sctp relay error', {
@@ -1695,7 +1435,6 @@ export class WaCallMediaSession {
1695
1435
  startMediaFlow() {
1696
1436
  this.mediaStartedAtMs = Date.now();
1697
1437
  this.mediaFlowStarted = true;
1698
- this.logger.warn('[DIAG] startMediaFlow entered', { callId: this.info.callId });
1699
1438
  this.resetEncodeState();
1700
1439
  this.audioEngine.startPlayback();
1701
1440
  this.audioEngine.startCapture();