@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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +716 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,1705 @@
1
+ import { toUserJid } from '../shim/protocol.js';
2
+ import { getFirstNodeChild, getNodeChildrenByTag } from '../shim/transport.js';
3
+ import { toError, uint8TimingSafeEqual } from '../shim/util.js';
4
+ import { concatBytes, EMPTY_BYTES, readUInt32BE, toArrayBuffer } from '../bytes.js';
5
+ import { derivePerJidSrtpKey } from '../crypto/encryption.js';
6
+ import { SrtpSession } from '../crypto/srtp.js';
7
+ import { SrtcpSendContext } from '../crypto/rtcp.js';
8
+ import { generateSecureSsrc } from '../crypto/ssrc.js';
9
+ import { WaAppDataStream } from '../app-data/WaAppDataStream.js';
10
+ import { buildScreenShareStanza, parseScreenShareNode, WA_SCREEN_SHARE_STATE } from '../signaling/screen-share.js';
11
+ import { MLowCodec } from '../media/mlow-codec.js';
12
+ import { RtpSession, RtpPacket, VideoRtpStream, VideoMediaFrameInfo, videoRtpDurationSamples } from '../media/rtp.js';
13
+ import { auHasIDR, buildAccessUnitPayload, packageH264NALU, H264AccessUnitAssembler } from '../media/h264.js';
14
+ import { buildSenderReportWithSdes, generateWhatsappRtcpCname } from '../media/rtcp.js';
15
+ import { WaAudioEngine } from '../media/WaAudioEngine.js';
16
+ import { WaVideoEngine } from '../media/WaVideoEngine.js';
17
+ import { parseRelayFromAck } from '../relay/relay-ack.js';
18
+ import { isRtpPacket, isStunPacket } from '../relay/stun.js';
19
+ import { deriveWasmRelayStreamSsrcs } from '../crypto/ssrc.js';
20
+ import { WaManualRelay } from '../relay/WaManualRelay.js';
21
+ 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
+ import { CallDirection, CallMediaType, CallState, EndCallReason, PayloadType, SRTP_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN, SRTP_SEND_AUTH_TAG_LEN } from '../types.js';
23
+
24
+
25
+ export class WaCallMediaSession {
26
+ info;
27
+ deps;
28
+ logger;
29
+ delegate;
30
+ rtpSession = null;
31
+ srtpSession = null;
32
+ opusCodec = null;
33
+ sctpRelay;
34
+ audioEngine;
35
+ initialTransportSent = false;
36
+ outgoingPreacceptSent = false;
37
+ selfSsrc = 0;
38
+ selfSsrcJid = '';
39
+ peerSsrcs = [];
40
+ firstPacketSent = false;
41
+ acceptedByJid = null;
42
+ debeEnabled = true;
43
+ audioSendCount = 0;
44
+ audioDropCount = 0;
45
+ realAudioSendCount = 0;
46
+ static EMPTY_BYTES = EMPTY_BYTES;
47
+ encodeBufferA = null;
48
+ encodeBufferB = null;
49
+ encodeBuffer = null;
50
+ encodeBufferPos = 0;
51
+ authPaddingBuffer = null;
52
+ audioRecvCount = 0;
53
+ recvRealCount = 0;
54
+ recvDtxCount = 0;
55
+ srtpErrorCount = 0;
56
+ relayPacketCount = 0;
57
+ stunResponseCount = 0;
58
+ selfEchoCount = 0;
59
+ lastRecvSeq = -1;
60
+ 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
+ actualPeerSsrc = null;
64
+ ssrcResubscribed = false;
65
+
66
+ videoSsrc = 0;
67
+ videoRtpStream = null;
68
+ videoSrtpSession = null;
69
+ videoEngine;
70
+ videoSendCount = 0;
71
+ videoKeyframeRequired = false;
72
+ videoFlushSeen = 0;
73
+ videoIdrSendCount = 0;
74
+ videoDropCount = 0;
75
+
76
+ audioRtcpSession = null;
77
+ videoRtcpSession = null;
78
+ audioRtcpCname = null;
79
+ videoRtcpCname = null;
80
+ audioOctetsSent = 0;
81
+ videoOctetsSent = 0;
82
+ rtcpTimer = null;
83
+ mediaStartedAtMs = null;
84
+ mediaFlowStarted = false;
85
+
86
+ peerVideoUpgradePending = false;
87
+ peerVideoActive = false;
88
+ peerVideoJids = new Set();
89
+ videoAssembler = null;
90
+ appDataStream = null;
91
+ appDataSrtpSession = null;
92
+ peerAppDataSsrcs = new Set();
93
+ constructor(options) {
94
+ this.deps = options.deps;
95
+ this.logger = options.logger;
96
+ this.info = options.info;
97
+ this.delegate = options.delegate;
98
+ this.sctpRelay = new WaManualRelay({
99
+ logger: this.logger.child({ component: 'sctp' })
100
+ });
101
+ this.audioEngine = new WaAudioEngine({
102
+ logger: this.logger.child({ component: 'audio-engine' })
103
+ });
104
+ this.audioEngine.setAudioSender(this);
105
+ this.audioEngine.setOnAudioFinished(() => {
106
+ this.delegate.emitOutboundAudioFinished(this.info);
107
+ });
108
+ this.videoEngine = new WaVideoEngine({
109
+ logger: this.logger.child({ component: 'video-engine' }),
110
+ ...(options.videoConfig || {})
111
+ });
112
+ this.videoEngine.setVideoSender(this);
113
+ this.sctpRelay.on('relay_connected', () => {
114
+ this.onRelayConnected();
115
+ });
116
+ this.sctpRelay.on('relay_receive', (relayInfo) => {
117
+ this.onRelayData(relayInfo.data);
118
+ });
119
+ }
120
+ get callId() {
121
+ return this.info.callId;
122
+ }
123
+ onDecodedAudio = (pcm) => {
124
+ this.audioEngine.onPlaybackData(pcm);
125
+ this.delegate.emitInboundAudio?.(this.info, pcm);
126
+ };
127
+ async initMedia(selfLid, peerJid) {
128
+ const ssrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid));
129
+ this.rtpSession = RtpSession.whatsappOpus(ssrc);
130
+ this.selfSsrc = ssrc;
131
+ this.selfSsrcJid = this.ensureDeviceJid(selfLid);
132
+ const peerSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(peerJid));
133
+ 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
+ this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }) });
146
+ if (this.info.mediaType === CallMediaType.Video) {
147
+
148
+ this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
149
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
150
+ 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
+ }
160
+ }
161
+ resetOutgoingFlags() {
162
+ this.initialTransportSent = false;
163
+ this.outgoingPreacceptSent = false;
164
+ }
165
+ async acceptCall() {
166
+ if (!this.info.canAccept) {
167
+ throw new Error(`Call ${this.info.callId} cannot be accepted in state ${this.info.stateData.state}`);
168
+ }
169
+ this.info.applyTransition({ type: 'local_accepted' });
170
+ this.delegate.emitState(this.info);
171
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
172
+ const callId = this.info.callId;
173
+ const callCreator = this.info.callCreator;
174
+ const peerJid = this.info.peerJid;
175
+ const isVideo = this.info.mediaType === CallMediaType.Video;
176
+ this.acceptedByJid = peerJid;
177
+ this.initSrtpKeys();
178
+ try {
179
+ const muteNode = buildMuteV2Stanza(peerJid, callId, callCreator, 0, meId);
180
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
181
+ }
182
+ catch (err) {
183
+ this.logger.error('error sending mute_v2', {
184
+ message: toError(err).message
185
+ });
186
+ }
187
+ try {
188
+ const transportNode = buildTransportStanza(peerJid, callId, callCreator, meId, '1', '1');
189
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
190
+ }
191
+ catch (err) {
192
+ this.logger.error('error sending transport', {
193
+ message: toError(err).message
194
+ });
195
+ }
196
+ if (this.info.encryptionKey) {
197
+ const acceptStanza = await buildAcceptStanza(this.deps, this.info.callId, this.info.encryptionKey, this.info.peerJid, this.info.callCreator, isVideo);
198
+ try {
199
+ await this.deps.lowLevelCoordinator.sendNode(acceptStanza);
200
+ }
201
+ catch (err) {
202
+ this.logger.error('accept send error', {
203
+ message: toError(err).message
204
+ });
205
+ }
206
+ }
207
+ if (this.info.relayData) {
208
+ await this.connectRelays(this.info.relayData.endpoints);
209
+ }
210
+ this.logger.media('call accepted', { callId });
211
+ }
212
+ async rejectCall(reason = EndCallReason.Declined) {
213
+ this.info.applyTransition({ type: 'local_rejected', reason });
214
+ this.delegate.emitState(this.info);
215
+ const node = buildRejectStanza(this.info.peerJid, this.info.callId, this.info.callCreator);
216
+ try {
217
+ await this.deps.lowLevelCoordinator.sendNode(node);
218
+ }
219
+ catch (err) {
220
+ this.logger.warn('reject send failed', { message: toError(err).message });
221
+ }
222
+ this.cleanup();
223
+ }
224
+ async endCall(reason = EndCallReason.UserEnded) {
225
+ if (this.info.isEnded)
226
+ return;
227
+ const connectedAt = this.info.stateData.connectedAt;
228
+ const audioDurationMs = connectedAt ? Date.now() - connectedAt.getTime() : undefined;
229
+ this.info.applyTransition({ type: 'terminated', reason });
230
+ const terminateTarget = this.acceptedByJid ?? this.info.peerJid;
231
+ const node = buildTerminateStanza(terminateTarget, this.info.callId, this.info.callCreator, audioDurationMs);
232
+ this.delegate.emitEnded(this.info);
233
+ this.delegate.emitState(this.info);
234
+ try {
235
+ await this.deps.lowLevelCoordinator.sendNode(node);
236
+ }
237
+ catch (err) {
238
+ this.logger.warn('terminate send failed', { message: toError(err).message });
239
+ }
240
+
241
+ await new Promise((resolve) => setTimeout(resolve, 400));
242
+ this.cleanup();
243
+ }
244
+ setMute(muted) {
245
+ if (!this.info.isActive)
246
+ return;
247
+ this.info.applyTransition({ type: 'audio_mute_changed', muted });
248
+ this.delegate.emitState(this.info);
249
+ if (muted) {
250
+ this.audioEngine.stopCapture();
251
+ }
252
+ else {
253
+ this.audioEngine.startCapture();
254
+ }
255
+ }
256
+ async loadAudio(audioPath) {
257
+ this.audioEngine.setLoopMode(false);
258
+ await this.audioEngine.loadAudioFile(audioPath);
259
+ this.resetEncodeState();
260
+ this.logger.media('audio loaded for call', { callId: this.info.callId });
261
+ }
262
+ setExternalAudioMode(enabled) {
263
+ this.audioEngine.setExternalMode(enabled);
264
+ if (enabled) {
265
+ this.resetEncodeState();
266
+ this.logger.debug('external audio mode enabled', { callId: this.info.callId });
267
+ }
268
+ }
269
+ feedLiveAudio(data) {
270
+ return this.audioEngine.feedExternalAudio(data);
271
+ }
272
+ getLiveBufferMs() {
273
+ return this.audioEngine.getLiveBufferMs();
274
+ }
275
+ async sendIncomingPreaccept(peerJid) {
276
+ try {
277
+ const preacceptNode = buildPreacceptStanza(peerJid, this.info.callId, this.info.callCreator);
278
+ await this.deps.lowLevelCoordinator.sendNode(preacceptNode);
279
+ }
280
+ catch (err) {
281
+ this.logger.error('error sending preaccept', {
282
+ message: toError(err).message
283
+ });
284
+ }
285
+ }
286
+ async sendIncomingRelayLatency() {
287
+ if (!this.info.relayData)
288
+ return;
289
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
290
+ const callId = this.info.callId;
291
+ const callCreator = this.info.callCreator;
292
+ const destinationJids = this.info.relayData.participantJids || [];
293
+ const seenRelayNames = new Set();
294
+ for (const ep of this.info.relayData.endpoints) {
295
+ const name = ep.relayName || '';
296
+ if (!name || seenRelayNames.has(name))
297
+ continue;
298
+ seenRelayNames.add(name);
299
+ try {
300
+ const relayData = [
301
+ {
302
+ relayName: name,
303
+ latency: ep.c2rRtt || 0,
304
+ addressBytes: ep.addressBytes
305
+ }
306
+ ];
307
+ const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
308
+ await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
309
+ }
310
+ catch (err) {
311
+ this.logger.error('error sending incoming relaylatency', {
312
+ relayName: name,
313
+ message: toError(err).message
314
+ });
315
+ }
316
+ }
317
+ }
318
+ async handleCallAccept(node, peerJid) {
319
+ const nodeInfo = extractNodeInfo(node);
320
+ if (!nodeInfo)
321
+ return;
322
+ let srtpFromPeerKey = false;
323
+ if (needsDecryption(nodeInfo.tag)) {
324
+ try {
325
+ const peerCallKey = await decryptCallKey(this.deps, nodeInfo.innerNode, peerJid, this.logger.child({ component: 'signaling' }));
326
+ if (peerCallKey) {
327
+ const ourCallKey = this.info.encryptionKey;
328
+ const keysMatch = ourCallKey
329
+ ? uint8TimingSafeEqual(ourCallKey, peerCallKey)
330
+ : false;
331
+ if (!keysMatch && ourCallKey) {
332
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
333
+ const meJid = this.deps.authClient.getCurrentCredentials()?.meJid;
334
+ const ourCredJid = meLid || meJid || '';
335
+ const ourBase = ourCredJid ? toUserJid(ourCredJid) : '';
336
+ const participants = this.info.relayData?.participantJids || [];
337
+ const ourDeviceJid = participants.find((jid) => {
338
+ const jBase = toUserJid(jid);
339
+ return jBase === ourBase && /:\d+@/.test(jid);
340
+ }) || ourCredJid;
341
+ if (ourDeviceJid && peerJid) {
342
+ try {
343
+ const sendKeying = derivePerJidSrtpKey(ourCallKey, this.ensureDeviceJid(ourDeviceJid));
344
+ const recvKeying = derivePerJidSrtpKey(peerCallKey, this.ensureDeviceJid(peerJid));
345
+ this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
346
+ srtpFromPeerKey = true;
347
+ this.logger.debug('srtp re-initialized with peer call_key', {
348
+ callId: this.info.callId
349
+ });
350
+ }
351
+ catch (err) {
352
+ this.logger.error('per-jid srtp re-derivation failed', {
353
+ message: toError(err).message
354
+ });
355
+ }
356
+ }
357
+ }
358
+ }
359
+ }
360
+ catch (err) {
361
+ this.logger.error('accept decrypt error', {
362
+ message: toError(err).message
363
+ });
364
+ }
365
+ }
366
+ try {
367
+ this.info.applyTransition({ type: 'remote_accepted' });
368
+ this.delegate.emitState(this.info);
369
+ }
370
+ catch (err) {
371
+ this.logger.trace('call transition skipped', { message: toError(err).message });
372
+ }
373
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
374
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
375
+ const ourJid = meLid || meId;
376
+ const ourBase = ourJid ? toUserJid(ourJid) : '';
377
+ const callId = this.info.callId;
378
+ const callCreator = this.info.callCreator;
379
+ const acceptingDeviceJid = peerJid;
380
+ this.acceptedByJid = acceptingDeviceJid;
381
+ 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
+ });
388
+ }
389
+ else {
390
+ const peerDeviceJidForSsrc = this.ensureDeviceJid(acceptingDeviceJid);
391
+ const acceptSsrc = generateSecureSsrc(callId, peerDeviceJidForSsrc);
392
+ this.peerSsrcs = [acceptSsrc];
393
+ this.logger.debug('accept ssrc assigned', {
394
+ callId,
395
+ jid: peerDeviceJidForSsrc,
396
+ ssrc: `0x${acceptSsrc.toString(16)}`
397
+ });
398
+ }
399
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
400
+ this.sctpRelay.resendSubscriptions();
401
+ if (!srtpFromPeerKey) {
402
+ this.initSrtpKeys();
403
+ }
404
+ if (this.info.relayData?.participantJids) {
405
+ const otherDevices = this.info.relayData.participantJids.filter((jid) => {
406
+ if (jid === acceptingDeviceJid)
407
+ return false;
408
+ const jidBase = toUserJid(jid);
409
+ if (jidBase === ourBase)
410
+ return false;
411
+ return true;
412
+ });
413
+ for (const deviceJid of otherDevices) {
414
+ try {
415
+ const terminateNode = buildTerminateStanza(deviceJid, callId, callCreator, undefined, 'accepted_elsewhere');
416
+ await this.deps.lowLevelCoordinator.sendNode(terminateNode);
417
+ }
418
+ catch (err) {
419
+ this.logger.error('error sending terminate_elsewhere', {
420
+ deviceJid,
421
+ message: toError(err).message
422
+ });
423
+ }
424
+ }
425
+ }
426
+ try {
427
+ const transportNode = buildTransportStanza(acceptingDeviceJid, callId, callCreator, meId, '1', '1');
428
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
429
+ }
430
+ catch (err) {
431
+ this.logger.error('error sending transport', {
432
+ message: toError(err).message
433
+ });
434
+ }
435
+ try {
436
+ const muteNode = buildMuteV2Stanza(acceptingDeviceJid, callId, callCreator, 0, meId);
437
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
438
+ }
439
+ catch (err) {
440
+ this.logger.error('error sending mute_v2', {
441
+ message: toError(err).message
442
+ });
443
+ }
444
+ const acceptMsgId = node.attrs?.id;
445
+ if (acceptMsgId) {
446
+ try {
447
+ const receiptNode = buildAcceptReceiptStanza(acceptingDeviceJid, acceptMsgId, callId, callCreator, ourJid);
448
+ await this.deps.lowLevelCoordinator.sendNode(receiptNode);
449
+ }
450
+ catch (err) {
451
+ this.logger.error('error sending accept receipt', {
452
+ message: toError(err).message
453
+ });
454
+ }
455
+ }
456
+ if (this.sctpRelay.hasConnection()) {
457
+ try {
458
+ this.info.applyTransition({ type: 'media_connected' });
459
+ this.delegate.emitState(this.info);
460
+ const MEDIA_START_DELAY_MS = 3000;
461
+ setTimeout(() => {
462
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path B)', {
463
+ callId: this.info.callId, state: this.info.stateData.state
464
+ });
465
+ if (this.info.stateData.state === CallState.Ended) {
466
+ return;
467
+ }
468
+ this.startMediaFlow();
469
+ }, MEDIA_START_DELAY_MS);
470
+ }
471
+ catch (err) {
472
+ this.logger.trace('call transition skipped', { message: toError(err).message });
473
+ }
474
+ }
475
+ else if (this.info.relayData) {
476
+ await this.connectRelays(this.info.relayData.endpoints);
477
+ }
478
+ }
479
+ async handleCallPreaccept(node, peerJid) {
480
+ const nodeInfo = extractNodeInfo(node);
481
+ if (!nodeInfo)
482
+ return;
483
+ if (this.info.direction === CallDirection.Outgoing && this.info.relayData) {
484
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
485
+ const callId = this.info.callId;
486
+ 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
+ }
512
+ if (!this.initialTransportSent) {
513
+ try {
514
+ const basePeerJid = toUserJid(peerJid);
515
+ const transportNode = buildTransportStanza(basePeerJid, callId, callCreator, meId);
516
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
517
+ this.initialTransportSent = true;
518
+ }
519
+ catch (err) {
520
+ this.logger.error('error sending initial transport', {
521
+ message: toError(err).message
522
+ });
523
+ }
524
+ }
525
+ }
526
+ }
527
+ async handleCallTransport(_node) {
528
+ const nodeInfo = extractNodeInfo(_node);
529
+ if (!nodeInfo)
530
+ return;
531
+ const relays = extractRelayEndpoints(nodeInfo.innerNode);
532
+ if (relays.length > 0 && !this.sctpRelay.hasConnection()) {
533
+ this.info.relayData = {
534
+ ...this.info.relayData,
535
+ endpoints: relays
536
+ };
537
+ await this.connectRelays(relays);
538
+ }
539
+ }
540
+ async handleCallAck(node) {
541
+ const ackType = node.attrs?.type;
542
+ if (ackType !== 'offer')
543
+ return;
544
+ const error = node.attrs?.error;
545
+ if (error) {
546
+ this.logger.error('ack error', { callId: this.info.callId, error });
547
+ return;
548
+ }
549
+ const { relays, participantJids, uuid, selfPid, peerPid, hbhKey } = parseRelayFromAck(node);
550
+ if (relays.length > 0) {
551
+ this.info.relayData = {
552
+ endpoints: relays,
553
+ participantJids,
554
+ uuid,
555
+ selfPid,
556
+ peerPid,
557
+ hbhKey
558
+ };
559
+ this.logger.debug('offer ack relays parsed', {
560
+ callId: this.info.callId,
561
+ relayCount: relays.length,
562
+ participantCount: participantJids.length
563
+ });
564
+ const callKey = this.info.encryptionKey;
565
+ if (participantJids.length > 0) {
566
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
567
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
568
+ const ourCredJid = meLid || meId || '';
569
+ const ourBase = ourCredJid ? toUserJid(ourCredJid) : '';
570
+ const ourDeviceJid = this.ensureDeviceJid(participantJids.find((jid) => {
571
+ const jidBase = toUserJid(jid);
572
+ return jidBase === ourBase && /:\d+@/.test(jid);
573
+ }) || ourCredJid);
574
+ const peerJids = participantJids.filter((jid) => {
575
+ const jidBase = toUserJid(jid);
576
+ return jidBase !== ourBase;
577
+ });
578
+ const peerCandidate = peerJids.find((jid) => /:\d+@/.test(jid) && !/:0@/.test(jid)) || peerJids[0];
579
+ const peerDeviceJid = peerCandidate ? this.ensureDeviceJid(peerCandidate) : undefined;
580
+ const newSelfSsrc = generateSecureSsrc(this.info.callId, ourDeviceJid);
581
+ if (newSelfSsrc !== this.selfSsrc) {
582
+ this.selfSsrc = newSelfSsrc;
583
+ this.selfSsrcJid = ourDeviceJid;
584
+ this.rtpSession = RtpSession.whatsappOpus(newSelfSsrc);
585
+ }
586
+ if (peerDeviceJid) {
587
+ const peerDeviceSsrc = generateSecureSsrc(this.info.callId, peerDeviceJid);
588
+ this.peerSsrcs = [peerDeviceSsrc];
589
+ }
590
+ if (callKey) {
591
+ this.initSrtpKeys();
592
+ }
593
+ else {
594
+ this.logger.media('no call_key, srtp not initialized', {
595
+ callId: this.info.callId
596
+ });
597
+ }
598
+ }
599
+ if (this.info.isInitiator && !this.outgoingPreacceptSent) {
600
+ try {
601
+ const preacceptNode = buildPreacceptStanza(this.info.peerJid, this.info.callId, this.info.callCreator);
602
+ await this.deps.lowLevelCoordinator.sendNode(preacceptNode);
603
+ this.outgoingPreacceptSent = true;
604
+ }
605
+ catch (err) {
606
+ this.logger.error('error sending preaccept (caller)', {
607
+ message: toError(err).message
608
+ });
609
+ }
610
+ }
611
+ await this.connectRelays(relays);
612
+ if (this.srtpSession &&
613
+ this.rtpSession &&
614
+ this.opusCodec &&
615
+ this.sctpRelay.hasConnection()) {
616
+ this.audioEngine.startSilenceCapture();
617
+ }
618
+ }
619
+ }
620
+ async handleCallRelaylatency(node, peerJid) {
621
+ const nodeInfo = extractNodeInfo(node);
622
+ if (!nodeInfo)
623
+ return;
624
+ const inner = nodeInfo.innerNode;
625
+ const callId = inner.attrs?.['call-id'] || this.info.callId;
626
+ const callCreator = inner.attrs?.['call-creator'] || this.info.callCreator;
627
+ const teNodes = getNodeChildrenByTag(inner, 'te');
628
+ if (teNodes.length === 0)
629
+ return;
630
+ const destinationJids = this.info.relayData?.participantJids || [];
631
+ if (destinationJids.length > 0) {
632
+ const forwardNode = buildRelaylatencyForwardStanza(peerJid, callId, callCreator, teNodes, destinationJids);
633
+ try {
634
+ await this.deps.lowLevelCoordinator.sendNode(forwardNode);
635
+ }
636
+ catch (err) {
637
+ this.logger.error('error forwarding relaylatency', {
638
+ message: toError(err).message
639
+ });
640
+ }
641
+ }
642
+ }
643
+ handleRelayElection(node) {
644
+ const inner = getFirstNodeChild(node);
645
+ if (!inner)
646
+ return;
647
+ let electedRelayIdx;
648
+ if (inner.attrs?.['elected_relay_idx'] !== undefined) {
649
+ const parsed = Number(inner.attrs['elected_relay_idx']);
650
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
651
+ electedRelayIdx = parsed;
652
+ }
653
+ else if (inner.attrs?.['relay_id'] !== undefined) {
654
+ const parsed = Number(inner.attrs['relay_id']);
655
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
656
+ electedRelayIdx = parsed;
657
+ }
658
+ else if (inner.content instanceof Uint8Array) {
659
+ const bytes = inner.content;
660
+ if (bytes.length >= 4)
661
+ electedRelayIdx = readUInt32BE(bytes, 0);
662
+ else if (bytes.length > 0)
663
+ electedRelayIdx = bytes[0];
664
+ }
665
+ if (electedRelayIdx !== undefined) {
666
+ this.info.electedRelayIdx = electedRelayIdx;
667
+ this.logger.debug('elected relay index', {
668
+ callId: this.info.callId,
669
+ electedRelayIdx
670
+ });
671
+ }
672
+ }
673
+ async handleCallMuteV2(node, peerJid) {
674
+ const nodeInfo = extractNodeInfo(node);
675
+ if (!nodeInfo)
676
+ return;
677
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
678
+ const callId = this.info.callId;
679
+ const callCreator = this.info.callCreator;
680
+ if (!this.isOwnAccountJid(peerJid)) {
681
+ const payload = parseMuteV2(nodeInfo.innerNode);
682
+ if (!payload.isRequest && payload.muted !== null && this.info.stateData.peerAudioMuted !== payload.muted) {
683
+ this.info.stateData.peerAudioMuted = payload.muted;
684
+ this.delegate.emitPeerMute?.(this.info, payload.muted);
685
+ }
686
+ }
687
+ try {
688
+ const muteNode = buildMuteV2Stanza(peerJid, callId, callCreator, 0, meId);
689
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
690
+ }
691
+ catch (err) {
692
+ this.logger.error('error sending mute_v2 response', {
693
+ message: toError(err).message
694
+ });
695
+ }
696
+ }
697
+ isOwnAccountJid(jid) {
698
+ const creds = this.deps.authClient.getCurrentCredentials();
699
+ const user = toUserJid(jid);
700
+ return ((!!creds?.meLid && user === toUserJid(creds.meLid)) ||
701
+ (!!creds?.meJid && user === toUserJid(creds.meJid)));
702
+ }
703
+ get videoSendActive() {
704
+ return !!(this.videoRtpStream && this.videoSrtpSession);
705
+ }
706
+ async setHandRaised(raised) {
707
+ if (!this.info.isActive)
708
+ return;
709
+ if (this.info.stateData.handRaised === raised)
710
+ return;
711
+ const node = buildRaiseHandStanza(this.acceptedByJid ?? this.info.peerJid, this.info.callId, this.info.callCreator, raised);
712
+ try {
713
+ await this.deps.lowLevelCoordinator.sendNode(node);
714
+ }
715
+ catch (err) {
716
+ this.logger.warn('raise hand send failed', {
717
+ raised,
718
+ message: toError(err).message
719
+ });
720
+ throw err;
721
+ }
722
+ this.info.applyTransition({ type: 'hand_raise_changed', raised });
723
+ this.delegate.emitState(this.info);
724
+ }
725
+ async setScreenShare(sharing) {
726
+ if (!this.info.isActive)
727
+ return;
728
+ if (this.info.stateData.screenSharing === sharing)
729
+ return;
730
+ if (sharing && !this.videoSendActive) {
731
+ throw new Error(`Call ${this.info.callId} carries no video to share the screen on`);
732
+ }
733
+ const peerDeviceJid = this.acceptedByJid ?? this.info.peerJid;
734
+ const state = sharing ? WA_SCREEN_SHARE_STATE.Started : WA_SCREEN_SHARE_STATE.Stopped;
735
+ try {
736
+ await this.deps.lowLevelCoordinator.sendNode(buildScreenShareStanza(peerDeviceJid, this.info.callId, this.info.callCreator, state));
737
+ }
738
+ catch (err) {
739
+ this.logger.warn('screen share request failed', {
740
+ sharing,
741
+ message: toError(err).message
742
+ });
743
+ throw err;
744
+ }
745
+ this.info.applyTransition({ type: 'screen_share_changed', sharing });
746
+ this.delegate.emitState(this.info);
747
+ }
748
+ handleCallUserAction(node, peerJid) {
749
+ this.applyPeerRaiseHand(node, peerJid);
750
+ }
751
+ handleCallRaiseHand(node, peerJid) {
752
+ this.applyPeerRaiseHand(node, peerJid);
753
+ }
754
+ applyPeerRaiseHand(node, peerJid) {
755
+ const nodeInfo = extractNodeInfo(node);
756
+ if (!nodeInfo)
757
+ return;
758
+ if (this.isOwnAccountJid(peerJid))
759
+ return;
760
+ const raised = parseRaiseHandState(nodeInfo.innerNode);
761
+ if (raised === null)
762
+ return;
763
+ const raisedHands = this.info.raisedHands;
764
+ if (raisedHands.has(peerJid) === raised)
765
+ return;
766
+ if (raised) {
767
+ if (raisedHands.size >= 64)
768
+ return;
769
+ raisedHands.add(peerJid);
770
+ }
771
+ else {
772
+ raisedHands.delete(peerJid);
773
+ }
774
+ this.delegate.emitHandRaise?.(this.info, peerJid, raised);
775
+ }
776
+ handleCallScreenShare(node) {
777
+ const nodeInfo = extractNodeInfo(node);
778
+ if (!nodeInfo)
779
+ return;
780
+ const share = parseScreenShareNode(nodeInfo.innerNode);
781
+ if (!share)
782
+ return;
783
+ this.info.peerScreenShare = share;
784
+ this.delegate.emitScreenShare?.(this.info, share);
785
+ this.delegate.emitState(this.info);
786
+ }
787
+ sendReaction(reaction) {
788
+ if (!this.appDataStream || !this.appDataSrtpSession)
789
+ return false;
790
+ if (!this.info.isActive)
791
+ return false;
792
+ return this.appDataStream.sendReaction(reaction);
793
+ }
794
+ openAppDataStream(selfDeviceJid) {
795
+ const ssrc = generateSecureSsrc(this.info.callId, selfDeviceJid, 6);
796
+ this.appDataStream?.close();
797
+ this.appDataStream = new WaAppDataStream({
798
+ logger: this.logger.child({ component: 'app-data' }),
799
+ ssrc,
800
+ sendPacket: (packet) => {
801
+ if (!this.appDataSrtpSession)
802
+ return false;
803
+ return this.sctpRelay.broadcast(toArrayBuffer(this.appDataSrtpSession.protect(packet)));
804
+ }
805
+ });
806
+ }
807
+ trackPeerAppDataSsrcs(deviceJids) {
808
+ for (const jid of deviceJids) {
809
+ if (!jid)
810
+ continue;
811
+ if (this.peerAppDataSsrcs.size >= 16)
812
+ break;
813
+ this.peerAppDataSsrcs.add(generateSecureSsrc(this.info.callId, this.ensureDeviceJid(jid), 6));
814
+ }
815
+ }
816
+ onAppDataPacket(data, payloadType, ssrc) {
817
+ const stream = this.appDataStream;
818
+ if (!stream || !this.appDataSrtpSession)
819
+ return;
820
+ try {
821
+ const packet = this.appDataSrtpSession.unprotect(data);
822
+ stream.observeInboundPayloadType(payloadType);
823
+ for (const reaction of stream.receive(packet.payload, ssrc)) {
824
+ this.delegate.emitCallReaction?.(this.info, reaction);
825
+ }
826
+ }
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
+ }
834
+ }
835
+
836
+ async handleCallVideo(node) {
837
+ const nodeInfo = extractNodeInfo(node);
838
+ if (!nodeInfo)
839
+ return;
840
+ const inner = nodeInfo.innerNode;
841
+ const state = Number(inner.attrs?.state ?? Number.NaN);
842
+ if (!Number.isFinite(state))
843
+ return;
844
+ const peerJid = this.acceptedByJid || this.info.peerJid;
845
+ const callId = this.info.callId;
846
+ const callCreator = this.info.callCreator;
847
+ const sourceJid = nodeInfo.peerJid || peerJid;
848
+ const setPeerVideo = (on) => {
849
+ const before = this.peerVideoJids.size;
850
+ if (on)
851
+ this.peerVideoJids.add(sourceJid);
852
+ else
853
+ this.peerVideoJids.delete(sourceJid);
854
+ this.peerVideoActive = this.peerVideoJids.size > 0;
855
+ return { before, after: this.peerVideoJids.size };
856
+ };
857
+ this.logger.media('inbound video state', { callId, state });
858
+ switch (state) {
859
+ case VideoState.UpgradeRequest:
860
+ case VideoState.UpgradeRequestV2: {
861
+ setPeerVideo(true);
862
+ this.peerVideoUpgradePending = true;
863
+ await this.enableVideoMidCall();
864
+ try {
865
+ const accept = buildVideoStateStanza(peerJid, callId, callCreator, VideoState.UpgradeAccept, { dec: VideoDecAccept });
866
+ await this.deps.lowLevelCoordinator.sendNode(accept);
867
+ }
868
+ catch (err) {
869
+ this.logger.error('error sending video upgrade accept', { callId, message: toError(err).message });
870
+ }
871
+ this.peerVideoUpgradePending = false;
872
+ this.info.mediaType = CallMediaType.Video;
873
+ this.info.stateData.videoOff = false;
874
+ this.delegate.emitState(this.info);
875
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: state, jid: sourceJid });
876
+ break;
877
+ }
878
+ case VideoState.Disabled:
879
+ case VideoState.Stopped: {
880
+ const { before, after } = setPeerVideo(false);
881
+ if (state === VideoState.Disabled && before === after)
882
+ break;
883
+ this.delegate.emitVideoState?.(this.info, {
884
+ active: false,
885
+ upgrade: false,
886
+ raw: state,
887
+ direction: 'inbound',
888
+ jid: sourceJid,
889
+ allOff: before > 0 && after === 0
890
+ });
891
+ break;
892
+ }
893
+ case VideoState.UpgradeReject:
894
+ case VideoState.UpgradeCancel: {
895
+ this.disableVideoMidCall({ keepSource: true });
896
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: state });
897
+ break;
898
+ }
899
+ case VideoState.Enabled: {
900
+ setPeerVideo(true);
901
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: false, raw: state, direction: 'inbound', jid: sourceJid });
902
+ break;
903
+ }
904
+ default:
905
+ break;
906
+ }
907
+ }
908
+
909
+ async startVideoMidCall() {
910
+ const peerJid = this.acceptedByJid || this.info.peerJid;
911
+ const request = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.UpgradeRequestV2, { dec: VideoDecRequest });
912
+ await this.deps.lowLevelCoordinator.sendNode(request);
913
+ await this.enableVideoMidCall();
914
+ this.info.mediaType = CallMediaType.Video;
915
+ this.info.stateData.videoOff = false;
916
+ this.delegate.emitState(this.info);
917
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: VideoState.UpgradeRequestV2 });
918
+ }
919
+ async enableVideoMidCall() {
920
+ if (this.videoRtpStream && this.videoSrtpSession)
921
+ return;
922
+ const creds = this.deps.authClient.getCurrentCredentials();
923
+ const selfLid = creds?.meLid || creds?.meJid || '';
924
+ if (!this.videoSsrc) {
925
+ this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
926
+ }
927
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
928
+
929
+ if (this.srtpSession) {
930
+ const meLid = creds?.meLid;
931
+ const meId = creds?.meJid;
932
+ const ourBase = toUserJid(meLid || meId || '');
933
+ const participants = this.info.relayData?.participantJids || [];
934
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => toUserJid(jid) === ourBase && /:\d+@/.test(jid)) || meLid || meId || '');
935
+ const peerDeviceJid = this.ensureDeviceJid(this.acceptedByJid || this.info.peerJid);
936
+ try {
937
+ const sendKeying = derivePerJidSrtpKey(this.info.encryptionKey, ourDeviceJid);
938
+ const recvKeying = derivePerJidSrtpKey(this.info.encryptionKey, peerDeviceJid);
939
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
940
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
941
+ }
942
+ catch (err) {
943
+ this.logger.error('video srtp key derivation failed', { callId: this.info.callId, message: toError(err).message });
944
+ }
945
+ }
946
+ this.videoAssembler = new H264AccessUnitAssembler();
947
+
948
+ if (!this.videoEngine.hasSource()) {
949
+ try {
950
+ await this.videoEngine.loadBlankSource();
951
+ }
952
+ catch (err) {
953
+ this.logger.error('blank video fallback unavailable', { callId: this.info.callId, message: toError(err).message });
954
+ }
955
+ }
956
+ if (this.sctpRelay.hasConnection()) {
957
+ this.videoEngine.start();
958
+ }
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
+ }
965
+
966
+ async swapVideoSource(videoPath) {
967
+ if (this.info.mediaType !== CallMediaType.Video) {
968
+ throw new Error(`Call ${this.info.callId} has no active video stream to swap`);
969
+ }
970
+ this.videoEngine.stop({ keepSource: false });
971
+ await this.videoEngine.loadVideoFile(videoPath);
972
+ this.audioEngine.setLoopMode(true);
973
+ this.videoEngine.start();
974
+ this.logger.media('video source swapped', { callId: this.info.callId, videoPath });
975
+ }
976
+
977
+ async stopVideoMidCall({ keepSource = false } = {}) {
978
+ const peerJid = this.acceptedByJid || this.info.peerJid;
979
+ try {
980
+ const stop = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.Stopped);
981
+ await this.deps.lowLevelCoordinator.sendNode(stop);
982
+ }
983
+ catch (err) {
984
+ this.logger.error('error sending video stop', { callId: this.info.callId, message: toError(err).message });
985
+ }
986
+ this.disableVideoMidCall({ keepSource });
987
+ this.info.stateData.videoOff = true;
988
+ this.delegate.emitState(this.info);
989
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: VideoState.Stopped });
990
+ }
991
+
992
+ disableVideoMidCall({ keepSource = false } = {}) {
993
+ this.videoEngine.stop({ keepSource });
994
+ this.videoRtpStream = null;
995
+ this.videoSrtpSession = null;
996
+ this.videoRtcpSession = null;
997
+ this.videoAssembler = null;
998
+ this.info.mediaType = CallMediaType.Audio;
999
+ this.logger.media('video disabled mid-call', { callId: this.info.callId, keptSource: keepSource });
1000
+ }
1001
+ handleCallTerminate() {
1002
+ try {
1003
+ this.info.applyTransition({
1004
+ type: 'terminated',
1005
+ reason: EndCallReason.UserEnded
1006
+ });
1007
+ }
1008
+ catch (err) {
1009
+ this.logger.trace('call transition skipped', { message: toError(err).message });
1010
+ }
1011
+ this.delegate.emitEnded(this.info);
1012
+ this.delegate.emitState(this.info);
1013
+ this.cleanup();
1014
+ }
1015
+ 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
+ const hasRelay = this.sctpRelay.hasConnection();
1031
+ if (!this.rtpSession || !this.srtpSession || !this.opusCodec || !hasRelay) {
1032
+ 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
+ return;
1049
+ }
1050
+ for (let i = 0; i < data.length; i++) {
1051
+ if (!Number.isFinite(data[i])) {
1052
+ data[i] = 0;
1053
+ }
1054
+ }
1055
+ const frameSamples = this.encodeFrameSamples;
1056
+ if (!this.encodeBuffer) {
1057
+ if (!this.encodeBufferA) {
1058
+ this.encodeBufferA = new Float32Array(frameSamples);
1059
+ this.encodeBufferB = new Float32Array(frameSamples);
1060
+ }
1061
+ this.encodeBuffer = this.encodeBufferA;
1062
+ this.encodeBufferPos = 0;
1063
+ }
1064
+ let offset = 0;
1065
+ while (offset < data.length) {
1066
+ const toCopy = Math.min(data.length - offset, frameSamples - this.encodeBufferPos);
1067
+ this.encodeBuffer.set(data.subarray(offset, offset + toCopy), this.encodeBufferPos);
1068
+ this.encodeBufferPos += toCopy;
1069
+ offset += toCopy;
1070
+ if (this.encodeBufferPos < frameSamples)
1071
+ break;
1072
+ const frameData = this.encodeBuffer;
1073
+ this.encodeBuffer =
1074
+ frameData === this.encodeBufferA ? this.encodeBufferB : this.encodeBufferA;
1075
+ this.encodeBufferPos = 0;
1076
+ try {
1077
+ const opusFrame = this.opusCodec.encode(frameData);
1078
+ if (opusFrame.length <= 18)
1079
+ this.qLog.tiny++;
1080
+ this.sendOpusFrame(opusFrame, false);
1081
+ this.realAudioSendCount++;
1082
+ }
1083
+ catch (err) {
1084
+ this.logger.error('encode error', {
1085
+ callId: this.info.callId,
1086
+ message: toError(err).message
1087
+ });
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ async loadVideo(videoPath) {
1093
+ if (this.info.mediaType !== CallMediaType.Video) {
1094
+ throw new Error(`Call ${this.info.callId} was not started with isVideo — no video SSRC/RTP stream to send on`);
1095
+ }
1096
+ await this.videoEngine.loadVideoFile(videoPath);
1097
+ this.audioEngine.setLoopMode(true);
1098
+
1099
+ if (this.mediaFlowStarted && this.sctpRelay.hasConnection()) {
1100
+ this.videoEngine.start();
1101
+ }
1102
+ }
1103
+
1104
+ sendCapturedVideoAU(au, durationMs) {
1105
+ const hasRelay = this.sctpRelay.hasConnection();
1106
+ if (!this.videoRtpStream || !this.videoSrtpSession || !hasRelay) {
1107
+ 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
+ return;
1119
+ }
1120
+ try {
1121
+ const payload = buildAccessUnitPayload(au);
1122
+ if (!payload)
1123
+ return;
1124
+ const idr = auHasIDR(au);
1125
+ const flushesBefore = this.sctpRelay.getVideoFlushCount();
1126
+ if (flushesBefore !== this.videoFlushSeen) {
1127
+ this.videoFlushSeen = flushesBefore;
1128
+ this.videoKeyframeRequired = true;
1129
+ }
1130
+ if (this.videoKeyframeRequired && !idr)
1131
+ return;
1132
+ const mediaFrameInfo = idr ? VideoMediaFrameInfo.IDR : VideoMediaFrameInfo.Delta;
1133
+ this.videoRtpStream.setTimestampStride(videoRtpDurationSamples(durationMs));
1134
+ const chunks = packageH264NALU(payload);
1135
+ for (let i = 0; i < chunks.length; i++) {
1136
+ const header = this.videoRtpStream.nextPacket(i === chunks.length - 1, mediaFrameInfo);
1137
+ const srtpData = this.videoSrtpSession.protect(new RtpPacket(header, chunks[i]));
1138
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1139
+ this.videoOctetsSent = (this.videoOctetsSent + chunks[i].length) >>> 0;
1140
+ }
1141
+ const flushesAfter = this.sctpRelay.getVideoFlushCount();
1142
+ if (flushesAfter !== flushesBefore) {
1143
+ this.videoFlushSeen = flushesAfter;
1144
+ this.videoKeyframeRequired = true;
1145
+ }
1146
+ else if (idr) {
1147
+ this.videoKeyframeRequired = false;
1148
+ }
1149
+ this.videoSendCount++;
1150
+ if (idr)
1151
+ 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
+ }
1160
+ catch (err) {
1161
+ this.logger.error('error sending video', {
1162
+ callId: this.info.callId, message: toError(err).message
1163
+ });
1164
+ }
1165
+ }
1166
+ 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
+ this.audioEngine.setOnAudioFinished(null);
1183
+ this.audioEngine.stop();
1184
+ this.videoEngine.stop();
1185
+ this.sctpRelay.cleanup();
1186
+ if (this.rtcpTimer) {
1187
+ clearInterval(this.rtcpTimer);
1188
+ this.rtcpTimer = null;
1189
+ }
1190
+ if (this.opusCodec) {
1191
+ this.opusCodec.destroy();
1192
+ this.opusCodec = null;
1193
+ }
1194
+ this.rtpSession = null;
1195
+ this.srtpSession = null;
1196
+ this.appDataStream?.close();
1197
+ this.appDataStream = null;
1198
+ this.appDataSrtpSession = null;
1199
+ this.peerAppDataSsrcs.clear();
1200
+ this.audioRtcpSession = null;
1201
+ this.audioRtcpCname = null;
1202
+ this.audioOctetsSent = 0;
1203
+ this.videoRtpStream = null;
1204
+ this.videoSrtpSession = null;
1205
+ this.videoRtcpSession = null;
1206
+ this.videoRtcpCname = null;
1207
+ this.videoOctetsSent = 0;
1208
+ this.videoSsrc = 0;
1209
+ this.videoAssembler = null;
1210
+ this.peerVideoUpgradePending = false;
1211
+ this.peerVideoActive = false;
1212
+ this.peerVideoJids.clear();
1213
+ this.mediaStartedAtMs = null;
1214
+ this.videoSendCount = 0;
1215
+ this.videoIdrSendCount = 0;
1216
+ this.videoDropCount = 0;
1217
+ this.audioSendCount = 0;
1218
+ this.audioDropCount = 0;
1219
+ this.audioRecvCount = 0;
1220
+ this.srtpErrorCount = 0;
1221
+ this.relayPacketCount = 0;
1222
+ this.stunResponseCount = 0;
1223
+ this.selfEchoCount = 0;
1224
+ this.lastRecvSeq = -1;
1225
+ this.recvSeqGaps = 0;
1226
+ this.actualPeerSsrc = null;
1227
+ this.ssrcResubscribed = false;
1228
+ this.recvRealCount = 0;
1229
+ this.recvDtxCount = 0;
1230
+ this.initialTransportSent = false;
1231
+ this.outgoingPreacceptSent = false;
1232
+ this.firstPacketSent = false;
1233
+ this.realAudioSendCount = 0;
1234
+ this.encodeBuffer = null;
1235
+ this.encodeBufferPos = 0;
1236
+ this.acceptedByJid = null;
1237
+ }
1238
+ get encodeFrameSamples() {
1239
+ return this.opusCodec?.getFrameSize() ?? 960;
1240
+ }
1241
+ get rtpTsDelta() {
1242
+ return this.encodeFrameSamples;
1243
+ }
1244
+ sendOpusFrame(opusFrame, isSilence) {
1245
+ if (!this.rtpSession || !this.srtpSession)
1246
+ return;
1247
+ try {
1248
+ let rtpPayload = opusFrame;
1249
+ const authPadding = SRTP_AUTH_TAG_LEN - SRTP_SEND_AUTH_TAG_LEN;
1250
+ if (authPadding > 0) {
1251
+ if (!this.authPaddingBuffer || this.authPaddingBuffer.length !== authPadding) {
1252
+ this.authPaddingBuffer = new Uint8Array(authPadding);
1253
+ }
1254
+ rtpPayload = concatBytes([rtpPayload, this.authPaddingBuffer]);
1255
+ }
1256
+ const marker = !this.firstPacketSent;
1257
+ const tsDelta = this.rtpTsDelta;
1258
+ const rtpPacket = this.rtpSession.createPacketWithDuration(rtpPayload, tsDelta, marker);
1259
+ if (this.debeEnabled) {
1260
+ rtpPacket.header.extension = true;
1261
+ rtpPacket.header.extensionProfile = 0xdebe;
1262
+ rtpPacket.header.extensionData = WaCallMediaSession.EMPTY_BYTES;
1263
+ }
1264
+ if (!this.firstPacketSent) {
1265
+ this.firstPacketSent = true;
1266
+ }
1267
+ const srtpData = this.srtpSession.protect(rtpPacket);
1268
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1269
+ this.audioSendCount++;
1270
+ 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
+ }
1282
+ catch (err) {
1283
+ this.logger.error('error sending audio', {
1284
+ callId: this.info.callId,
1285
+ message: toError(err).message
1286
+ });
1287
+ }
1288
+ }
1289
+ ensureDeviceJid(jid) {
1290
+ if (/:\d+@/.test(jid))
1291
+ return jid;
1292
+ return jid.replace('@', ':0@');
1293
+ }
1294
+ initSrtpKeys() {
1295
+ const callKey = this.info.encryptionKey;
1296
+ if (!callKey) {
1297
+ this.logger.media('no call_key, srtp not initialized', { callId: this.info.callId });
1298
+ return;
1299
+ }
1300
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
1301
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
1302
+ const ourCredJid = meLid || meId || '';
1303
+ const ourBase = toUserJid(ourCredJid);
1304
+ const participants = this.info.relayData?.participantJids || [];
1305
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => {
1306
+ const jBase = toUserJid(jid);
1307
+ return jBase === ourBase && /:\d+@/.test(jid);
1308
+ }) || ourCredJid);
1309
+ let rawPeerJid = this.acceptedByJid || this.info.peerJid;
1310
+ if (!this.acceptedByJid) {
1311
+ const peerFromParticipants = participants.find((jid) => {
1312
+ const jBase = toUserJid(jid);
1313
+ return jBase !== ourBase;
1314
+ });
1315
+ if (peerFromParticipants)
1316
+ rawPeerJid = peerFromParticipants;
1317
+ }
1318
+ const peerDeviceJid = this.ensureDeviceJid(rawPeerJid);
1319
+ try {
1320
+ const sendKeying = derivePerJidSrtpKey(callKey, ourDeviceJid);
1321
+ const recvKeying = derivePerJidSrtpKey(callKey, peerDeviceJid);
1322
+ this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1323
+ this.appDataSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1324
+ this.openAppDataStream(ourDeviceJid);
1325
+ this.peerAppDataSsrcs.clear();
1326
+ this.trackPeerAppDataSsrcs([peerDeviceJid, ...participants.filter((jid) => toUserJid(jid) !== ourBase)]);
1327
+ this.audioRtcpSession = new SrtcpSendContext(sendKeying);
1328
+ if (this.info.mediaType === CallMediaType.Video) {
1329
+
1330
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1331
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
1332
+ }
1333
+ 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
+ }
1346
+ }
1347
+
1348
+ startRtcpSenderReports() {
1349
+ if (this.rtcpTimer)
1350
+ clearInterval(this.rtcpTimer);
1351
+ if (!this.audioRtcpCname)
1352
+ this.audioRtcpCname = generateWhatsappRtcpCname();
1353
+ if (!this.videoRtcpCname)
1354
+ this.videoRtcpCname = generateWhatsappRtcpCname();
1355
+ this.rtcpTimer = setInterval(() => {
1356
+ if (!this.sctpRelay.hasConnection())
1357
+ return;
1358
+ if (++this.qLog.n % 3 === 0)
1359
+ this.logVoipQuality();
1360
+ const nowMs = Date.now();
1361
+ try {
1362
+ if (this.audioRtcpSession && this.selfSsrc) {
1363
+ const stats = {
1364
+ packetsSent: this.audioSendCount,
1365
+ octetsSent: this.audioOctetsSent,
1366
+ rtpTimestamp: this.rtpSession?.timestamp ?? 0
1367
+ };
1368
+ const plain = buildSenderReportWithSdes(this.selfSsrc, stats, nowMs, this.audioRtcpCname);
1369
+ const protectedPacket = this.audioRtcpSession.protect(this.selfSsrc, plain);
1370
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1371
+ }
1372
+ if (this.videoRtcpSession && this.videoSsrc && this.videoSendCount > 0) {
1373
+ const stats = {
1374
+ packetsSent: this.videoSendCount,
1375
+ octetsSent: this.videoOctetsSent,
1376
+ rtpTimestamp: this.videoRtpStream?.timestamp ?? 0
1377
+ };
1378
+ const plain = buildSenderReportWithSdes(this.videoSsrc, stats, nowMs, this.videoRtcpCname);
1379
+ const protectedPacket = this.videoRtcpSession.protect(this.videoSsrc, plain);
1380
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1381
+ }
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
+ }
1403
+ }, 1500);
1404
+ }
1405
+ resetEncodeState() {
1406
+ this.encodeBuffer = null;
1407
+ this.encodeBufferPos = 0;
1408
+ this.realAudioSendCount = 0;
1409
+ }
1410
+ onRelayConnected() {
1411
+ if (this.info.stateData.state === CallState.Connecting) {
1412
+ try {
1413
+ this.info.applyTransition({ type: 'media_connected' });
1414
+ this.delegate.emitState(this.info);
1415
+ this.logger.media('relay connected', {
1416
+ callId: this.info.callId, acceptedByJid: this.acceptedByJid ?? null
1417
+ });
1418
+ if (!this.acceptedByJid) {
1419
+ this.logger.media('relay connected before accept, deferring media start', {
1420
+ callId: this.info.callId
1421
+ });
1422
+ return;
1423
+ }
1424
+ const MEDIA_START_DELAY_MS = 3000;
1425
+ setTimeout(() => {
1426
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path A)', {
1427
+ callId: this.info.callId, state: this.info.stateData.state
1428
+ });
1429
+ if (this.info.stateData.state === CallState.Ended) {
1430
+ return;
1431
+ }
1432
+ this.startMediaFlow();
1433
+ }, MEDIA_START_DELAY_MS);
1434
+ }
1435
+ catch (err) {
1436
+ this.logger.trace('call transition skipped', { message: toError(err).message });
1437
+ }
1438
+ }
1439
+ }
1440
+ onRelayData(data) {
1441
+ this.relayPacketCount++;
1442
+ if (isStunPacket(data)) {
1443
+ this.stunResponseCount++;
1444
+ return;
1445
+ }
1446
+ if (!isRtpPacket(data))
1447
+ return;
1448
+ const pt = data[1] & 0x7f;
1449
+ if (this.peerAppDataSsrcs.size > 0 && data.length >= 12) {
1450
+ const appDataSsrc = readUInt32BE(data, 8);
1451
+ if (this.peerAppDataSsrcs.has(appDataSsrc)) {
1452
+ this.onAppDataPacket(data, pt, appDataSsrc);
1453
+ return;
1454
+ }
1455
+ }
1456
+ if (pt === PayloadType.H264) {
1457
+ this.onRelayVideoData(data);
1458
+ return;
1459
+ }
1460
+ if (!this.srtpSession || !this.opusCodec)
1461
+ return;
1462
+ if (pt !== 120)
1463
+ return;
1464
+ if (data.length >= 12) {
1465
+ const ssrc = ((data[8] << 24) | (data[9] << 16) | (data[10] << 8) | data[11]) >>> 0;
1466
+ if (ssrc === this.selfSsrc) {
1467
+ this.selfEchoCount++;
1468
+ return;
1469
+ }
1470
+ if (!this.ssrcResubscribed && this.actualPeerSsrc === null) {
1471
+ this.actualPeerSsrc = ssrc;
1472
+ const knownSsrc = this.peerSsrcs.includes(ssrc);
1473
+ if (!knownSsrc) {
1474
+ this.peerSsrcs = [ssrc];
1475
+ this.ssrcResubscribed = true;
1476
+ this.opusCodec.resetSequence();
1477
+ this.lastRecvSeq = -1;
1478
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1479
+ this.sctpRelay.resendSubscriptions();
1480
+ }
1481
+ }
1482
+ }
1483
+ try {
1484
+ const rtpPacket = this.srtpSession.unprotect(data);
1485
+ const opusPayload = rtpPacket.payload;
1486
+ this.audioRecvCount++;
1487
+ if (opusPayload.length === 0)
1488
+ return;
1489
+ const seq = rtpPacket.header.sequenceNumber;
1490
+ if (this.lastRecvSeq >= 0) {
1491
+ const gap = ((seq - this.lastRecvSeq + 65536) % 65536) - 1;
1492
+ if (gap > 0 && gap < 0x8000)
1493
+ this.recvSeqGaps += gap;
1494
+ }
1495
+ this.lastRecvSeq = seq;
1496
+ const isDtx = opusPayload.length <= 2;
1497
+ if (isDtx)
1498
+ this.recvDtxCount++;
1499
+ else
1500
+ this.recvRealCount++;
1501
+ this.opusCodec.decodeSequenced(seq, opusPayload, this.onDecodedAudio);
1502
+ if (this.audioRecvCount % 100 === 0) {
1503
+ const w = (this.lossWindow ??= { gaps: 0, pkts: 0 });
1504
+ const gaps = this.recvSeqGaps - w.gaps;
1505
+ const pkts = this.audioRecvCount - w.pkts;
1506
+ w.gaps = this.recvSeqGaps;
1507
+ w.pkts = this.audioRecvCount;
1508
+ const lossPct = pkts + gaps > 0 ? Math.min(100, Math.round((100 * gaps) / (pkts + gaps))) : 0;
1509
+ this.opusCodec.setExpectedPacketLossPercent(lossPct);
1510
+ }
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
+ }
1527
+ catch (err) {
1528
+ 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
+ }
1539
+ }
1540
+
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
+ onRelayVideoData(data) {
1595
+ if (!this.videoSrtpSession || !this.videoAssembler)
1596
+ return;
1597
+ try {
1598
+ const rtpPacket = this.videoSrtpSession.unprotect(data);
1599
+ const [accessUnit, complete] = this.videoAssembler.push(rtpPacket.header.sequenceNumber, rtpPacket.header.marker, rtpPacket.payload);
1600
+ if (complete && accessUnit) {
1601
+ this.delegate.emitInboundVideo?.(this.info, accessUnit);
1602
+ }
1603
+ }
1604
+ catch (err) {
1605
+ 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
+ }
1613
+ }
1614
+ async connectRelays(endpoints) {
1615
+ this.logger.debug('connecting relays', {
1616
+ callId: this.info.callId,
1617
+ endpointCount: endpoints.length
1618
+ });
1619
+ const seen = new Set();
1620
+ const uniqueEndpoints = [];
1621
+ for (const ep of endpoints) {
1622
+ if ((ep.protocol ?? 0) !== 0)
1623
+ continue;
1624
+ const key = `${ep.ip}:${ep.port}`;
1625
+ if (!seen.has(key)) {
1626
+ seen.add(key);
1627
+ uniqueEndpoints.push(ep);
1628
+ }
1629
+ }
1630
+ const usable = uniqueEndpoints.filter((ep) => ep.key && ep.rawToken);
1631
+
1632
+ const inbound = this.info.direction === CallDirection.Incoming;
1633
+ let chosen = null;
1634
+ if (inbound) {
1635
+ chosen = usable.find((ep) => ep.isFna) ?? null;
1636
+ }
1637
+ if (!chosen) {
1638
+ chosen =
1639
+ usable.find((ep) => !ep.isFna && parseInt(ep.authTokenId, 10) !== 0) ??
1640
+ usable.find((ep) => !ep.isFna) ??
1641
+ usable[0] ??
1642
+ null;
1643
+ }
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
+ : [];
1662
+ if (relays.length === 0) {
1663
+ this.logger.error('no relay configs', { callId: this.info.callId });
1664
+ return;
1665
+ }
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
+ }
1676
+ this.sctpRelay.setSsrc(this.selfSsrc);
1677
+ if (this.info.mediaType === CallMediaType.Video) {
1678
+ this.sctpRelay.setVideoSsrc(this.videoSsrc);
1679
+ }
1680
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1681
+ try {
1682
+ await this.sctpRelay.configureRelays(relays);
1683
+ this.logger.debug('sctp relays configured', {
1684
+ callId: this.info.callId,
1685
+ connected: this.sctpRelay.getConnectedCount()
1686
+ });
1687
+ }
1688
+ catch (err) {
1689
+ this.logger.error('sctp relay error', {
1690
+ callId: this.info.callId,
1691
+ message: toError(err).message
1692
+ });
1693
+ }
1694
+ }
1695
+ startMediaFlow() {
1696
+ this.mediaStartedAtMs = Date.now();
1697
+ this.mediaFlowStarted = true;
1698
+ this.logger.warn('[DIAG] startMediaFlow entered', { callId: this.info.callId });
1699
+ this.resetEncodeState();
1700
+ this.audioEngine.startPlayback();
1701
+ this.audioEngine.startCapture();
1702
+
1703
+ this.videoEngine.start();
1704
+ }
1705
+ }