@itznomo/baileys 0.0.0-stage → 0.0.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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,1727 @@
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, splitAnnexB, DROP_NAL_TYPES } 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
+ this.appDataSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
347
+ this.audioRtcpSession = new SrtcpSendContext(sendKeying);
348
+ if (this.info.mediaType === CallMediaType.Video) {
349
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
350
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
351
+ }
352
+ srtpFromPeerKey = true;
353
+ this.logger.debug('srtp re-initialized with peer call_key', {
354
+ callId: this.info.callId
355
+ });
356
+ }
357
+ catch (err) {
358
+ this.logger.error('per-jid srtp re-derivation failed', {
359
+ message: toError(err).message
360
+ });
361
+ }
362
+ }
363
+ }
364
+ }
365
+ }
366
+ catch (err) {
367
+ this.logger.error('accept decrypt error', {
368
+ message: toError(err).message
369
+ });
370
+ }
371
+ }
372
+ try {
373
+ this.info.applyTransition({ type: 'remote_accepted' });
374
+ this.delegate.emitState(this.info);
375
+ }
376
+ catch (err) {
377
+ this.logger.trace('call transition skipped', { message: toError(err).message });
378
+ }
379
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
380
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
381
+ const ourJid = meLid || meId;
382
+ const ourBase = ourJid ? toUserJid(ourJid) : '';
383
+ const callId = this.info.callId;
384
+ const callCreator = this.info.callCreator;
385
+ const acceptingDeviceJid = peerJid;
386
+ this.acceptedByJid = acceptingDeviceJid;
387
+ if (this.actualPeerSsrc !== null) {
388
+ const calculatedJid = this.ensureDeviceJid(acceptingDeviceJid);
389
+ this.logger.debug('accept keeping actual peer ssrc', {
390
+ callId,
391
+ actualPeerSsrc: `0x${this.actualPeerSsrc.toString(16)}`,
392
+ calculatedJid
393
+ });
394
+ }
395
+ else {
396
+ const peerDeviceJidForSsrc = this.ensureDeviceJid(acceptingDeviceJid);
397
+ const acceptSsrc = generateSecureSsrc(callId, peerDeviceJidForSsrc);
398
+ this.peerSsrcs = [acceptSsrc];
399
+ this.logger.debug('accept ssrc assigned', {
400
+ callId,
401
+ jid: peerDeviceJidForSsrc,
402
+ ssrc: `0x${acceptSsrc.toString(16)}`
403
+ });
404
+ }
405
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
406
+ this.sctpRelay.resendSubscriptions();
407
+ if (!srtpFromPeerKey) {
408
+ this.initSrtpKeys();
409
+ }
410
+ if (this.info.relayData?.participantJids) {
411
+ const otherDevices = this.info.relayData.participantJids.filter((jid) => {
412
+ if (jid === acceptingDeviceJid)
413
+ return false;
414
+ const jidBase = toUserJid(jid);
415
+ if (jidBase === ourBase)
416
+ return false;
417
+ return true;
418
+ });
419
+ for (const deviceJid of otherDevices) {
420
+ try {
421
+ const terminateNode = buildTerminateStanza(deviceJid, callId, callCreator, undefined, 'accepted_elsewhere');
422
+ await this.deps.lowLevelCoordinator.sendNode(terminateNode);
423
+ }
424
+ catch (err) {
425
+ this.logger.error('error sending terminate_elsewhere', {
426
+ deviceJid,
427
+ message: toError(err).message
428
+ });
429
+ }
430
+ }
431
+ }
432
+ try {
433
+ const transportNode = buildTransportStanza(acceptingDeviceJid, callId, callCreator, meId, '1', '1');
434
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
435
+ }
436
+ catch (err) {
437
+ this.logger.error('error sending transport', {
438
+ message: toError(err).message
439
+ });
440
+ }
441
+ try {
442
+ const muteNode = buildMuteV2Stanza(acceptingDeviceJid, callId, callCreator, 0, meId);
443
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
444
+ }
445
+ catch (err) {
446
+ this.logger.error('error sending mute_v2', {
447
+ message: toError(err).message
448
+ });
449
+ }
450
+ const acceptMsgId = node.attrs?.id;
451
+ if (acceptMsgId) {
452
+ try {
453
+ const receiptNode = buildAcceptReceiptStanza(acceptingDeviceJid, acceptMsgId, callId, callCreator, ourJid);
454
+ await this.deps.lowLevelCoordinator.sendNode(receiptNode);
455
+ }
456
+ catch (err) {
457
+ this.logger.error('error sending accept receipt', {
458
+ message: toError(err).message
459
+ });
460
+ }
461
+ }
462
+ if (this.sctpRelay.hasConnection()) {
463
+ try {
464
+ this.info.applyTransition({ type: 'media_connected' });
465
+ this.delegate.emitState(this.info);
466
+ const MEDIA_START_DELAY_MS = 3000;
467
+ setTimeout(() => {
468
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path B)', {
469
+ callId: this.info.callId, state: this.info.stateData.state
470
+ });
471
+ if (this.info.stateData.state === CallState.Ended) {
472
+ return;
473
+ }
474
+ this.startMediaFlow();
475
+ }, MEDIA_START_DELAY_MS);
476
+ }
477
+ catch (err) {
478
+ this.logger.trace('call transition skipped', { message: toError(err).message });
479
+ }
480
+ }
481
+ else if (this.info.relayData) {
482
+ await this.connectRelays(this.info.relayData.endpoints);
483
+ }
484
+ }
485
+ async handleCallPreaccept(node, peerJid) {
486
+ const nodeInfo = extractNodeInfo(node);
487
+ if (!nodeInfo)
488
+ return;
489
+ if (this.info.direction === CallDirection.Outgoing && this.info.relayData) {
490
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
491
+ const callId = this.info.callId;
492
+ const callCreator = this.info.callCreator;
493
+ const destinationJids = this.info.relayData.participantJids || [];
494
+ const seenRelayNames = new Set();
495
+ for (const ep of this.info.relayData.endpoints) {
496
+ const name = ep.relayName || '';
497
+ if (!name || seenRelayNames.has(name))
498
+ continue;
499
+ seenRelayNames.add(name);
500
+ try {
501
+ const relayData = [
502
+ {
503
+ relayName: name,
504
+ latency: ep.c2rRtt || 0,
505
+ addressBytes: ep.addressBytes
506
+ }
507
+ ];
508
+ const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
509
+ await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
510
+ }
511
+ catch (err) {
512
+ this.logger.error('error sending relaylatency', {
513
+ relayName: name,
514
+ message: toError(err).message
515
+ });
516
+ }
517
+ }
518
+ if (!this.initialTransportSent) {
519
+ try {
520
+ const basePeerJid = toUserJid(peerJid);
521
+ const transportNode = buildTransportStanza(basePeerJid, callId, callCreator, meId);
522
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
523
+ this.initialTransportSent = true;
524
+ }
525
+ catch (err) {
526
+ this.logger.error('error sending initial transport', {
527
+ message: toError(err).message
528
+ });
529
+ }
530
+ }
531
+ }
532
+ }
533
+ async handleCallTransport(_node) {
534
+ const nodeInfo = extractNodeInfo(_node);
535
+ if (!nodeInfo)
536
+ return;
537
+ const relays = extractRelayEndpoints(nodeInfo.innerNode);
538
+ if (relays.length > 0 && !this.sctpRelay.hasConnection()) {
539
+ this.info.relayData = {
540
+ ...this.info.relayData,
541
+ endpoints: relays
542
+ };
543
+ await this.connectRelays(relays);
544
+ }
545
+ }
546
+ async handleCallAck(node) {
547
+ const ackType = node.attrs?.type;
548
+ if (ackType !== 'offer')
549
+ return;
550
+ const error = node.attrs?.error;
551
+ if (error) {
552
+ this.logger.error('ack error', { callId: this.info.callId, error });
553
+ return;
554
+ }
555
+ const { relays, participantJids, uuid, selfPid, peerPid, hbhKey } = parseRelayFromAck(node);
556
+ if (relays.length > 0) {
557
+ this.info.relayData = {
558
+ endpoints: relays,
559
+ participantJids,
560
+ uuid,
561
+ selfPid,
562
+ peerPid,
563
+ hbhKey
564
+ };
565
+ this.logger.debug('offer ack relays parsed', {
566
+ callId: this.info.callId,
567
+ relayCount: relays.length,
568
+ participantCount: participantJids.length
569
+ });
570
+ const callKey = this.info.encryptionKey;
571
+ if (participantJids.length > 0) {
572
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
573
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
574
+ const ourCredJid = meLid || meId || '';
575
+ const ourBase = ourCredJid ? toUserJid(ourCredJid) : '';
576
+ const ourDeviceJid = this.ensureDeviceJid(participantJids.find((jid) => {
577
+ const jidBase = toUserJid(jid);
578
+ return jidBase === ourBase && /:\d+@/.test(jid);
579
+ }) || ourCredJid);
580
+ const peerJids = participantJids.filter((jid) => {
581
+ const jidBase = toUserJid(jid);
582
+ return jidBase !== ourBase;
583
+ });
584
+ const peerCandidate = peerJids.find((jid) => /:\d+@/.test(jid) && !/:0@/.test(jid)) || peerJids[0];
585
+ const peerDeviceJid = peerCandidate ? this.ensureDeviceJid(peerCandidate) : undefined;
586
+ const newSelfSsrc = generateSecureSsrc(this.info.callId, ourDeviceJid);
587
+ if (newSelfSsrc !== this.selfSsrc) {
588
+ this.selfSsrc = newSelfSsrc;
589
+ this.selfSsrcJid = ourDeviceJid;
590
+ this.rtpSession = RtpSession.whatsappOpus(newSelfSsrc);
591
+ }
592
+ if (peerDeviceJid) {
593
+ const peerDeviceSsrc = generateSecureSsrc(this.info.callId, peerDeviceJid);
594
+ this.peerSsrcs = [peerDeviceSsrc];
595
+ }
596
+ if (callKey) {
597
+ this.initSrtpKeys();
598
+ }
599
+ else {
600
+ this.logger.media('no call_key, srtp not initialized', {
601
+ callId: this.info.callId
602
+ });
603
+ }
604
+ }
605
+ if (this.info.isInitiator && !this.outgoingPreacceptSent) {
606
+ try {
607
+ const preacceptNode = buildPreacceptStanza(this.info.peerJid, this.info.callId, this.info.callCreator);
608
+ await this.deps.lowLevelCoordinator.sendNode(preacceptNode);
609
+ this.outgoingPreacceptSent = true;
610
+ }
611
+ catch (err) {
612
+ this.logger.error('error sending preaccept (caller)', {
613
+ message: toError(err).message
614
+ });
615
+ }
616
+ }
617
+ await this.connectRelays(relays);
618
+ if (this.srtpSession &&
619
+ this.rtpSession &&
620
+ this.opusCodec &&
621
+ this.sctpRelay.hasConnection()) {
622
+ this.audioEngine.startSilenceCapture();
623
+ }
624
+ }
625
+ }
626
+ async handleCallRelaylatency(node, peerJid) {
627
+ const nodeInfo = extractNodeInfo(node);
628
+ if (!nodeInfo)
629
+ return;
630
+ const inner = nodeInfo.innerNode;
631
+ const callId = inner.attrs?.['call-id'] || this.info.callId;
632
+ const callCreator = inner.attrs?.['call-creator'] || this.info.callCreator;
633
+ const teNodes = getNodeChildrenByTag(inner, 'te');
634
+ if (teNodes.length === 0)
635
+ return;
636
+ const destinationJids = this.info.relayData?.participantJids || [];
637
+ if (destinationJids.length > 0) {
638
+ const forwardNode = buildRelaylatencyForwardStanza(peerJid, callId, callCreator, teNodes, destinationJids);
639
+ try {
640
+ await this.deps.lowLevelCoordinator.sendNode(forwardNode);
641
+ }
642
+ catch (err) {
643
+ this.logger.error('error forwarding relaylatency', {
644
+ message: toError(err).message
645
+ });
646
+ }
647
+ }
648
+ }
649
+ handleRelayElection(node) {
650
+ const inner = getFirstNodeChild(node);
651
+ if (!inner)
652
+ return;
653
+ let electedRelayIdx;
654
+ if (inner.attrs?.['elected_relay_idx'] !== undefined) {
655
+ const parsed = Number(inner.attrs['elected_relay_idx']);
656
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
657
+ electedRelayIdx = parsed;
658
+ }
659
+ else if (inner.attrs?.['relay_id'] !== undefined) {
660
+ const parsed = Number(inner.attrs['relay_id']);
661
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
662
+ electedRelayIdx = parsed;
663
+ }
664
+ else if (inner.content instanceof Uint8Array) {
665
+ const bytes = inner.content;
666
+ if (bytes.length >= 4)
667
+ electedRelayIdx = readUInt32BE(bytes, 0);
668
+ else if (bytes.length > 0)
669
+ electedRelayIdx = bytes[0];
670
+ }
671
+ if (electedRelayIdx !== undefined) {
672
+ this.info.electedRelayIdx = electedRelayIdx;
673
+ this.logger.debug('elected relay index', {
674
+ callId: this.info.callId,
675
+ electedRelayIdx
676
+ });
677
+ }
678
+ }
679
+ async handleCallMuteV2(node, peerJid) {
680
+ const nodeInfo = extractNodeInfo(node);
681
+ if (!nodeInfo)
682
+ return;
683
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
684
+ const callId = this.info.callId;
685
+ const callCreator = this.info.callCreator;
686
+ if (!this.isOwnAccountJid(peerJid)) {
687
+ const payload = parseMuteV2(nodeInfo.innerNode);
688
+ if (!payload.isRequest && payload.muted !== null && this.info.stateData.peerAudioMuted !== payload.muted) {
689
+ this.info.stateData.peerAudioMuted = payload.muted;
690
+ this.delegate.emitPeerMute?.(this.info, payload.muted);
691
+ }
692
+ }
693
+ try {
694
+ const muteNode = buildMuteV2Stanza(peerJid, callId, callCreator, 0, meId);
695
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
696
+ }
697
+ catch (err) {
698
+ this.logger.error('error sending mute_v2 response', {
699
+ message: toError(err).message
700
+ });
701
+ }
702
+ }
703
+ isOwnAccountJid(jid) {
704
+ const creds = this.deps.authClient.getCurrentCredentials();
705
+ const user = toUserJid(jid);
706
+ return ((!!creds?.meLid && user === toUserJid(creds.meLid)) ||
707
+ (!!creds?.meJid && user === toUserJid(creds.meJid)));
708
+ }
709
+ get videoSendActive() {
710
+ return !!(this.videoRtpStream && this.videoSrtpSession);
711
+ }
712
+ async setHandRaised(raised) {
713
+ if (!this.info.isActive)
714
+ return;
715
+ if (this.info.stateData.handRaised === raised)
716
+ return;
717
+ const node = buildRaiseHandStanza(this.acceptedByJid ?? this.info.peerJid, this.info.callId, this.info.callCreator, raised);
718
+ try {
719
+ await this.deps.lowLevelCoordinator.sendNode(node);
720
+ }
721
+ catch (err) {
722
+ this.logger.warn('raise hand send failed', {
723
+ raised,
724
+ message: toError(err).message
725
+ });
726
+ throw err;
727
+ }
728
+ this.info.applyTransition({ type: 'hand_raise_changed', raised });
729
+ this.delegate.emitState(this.info);
730
+ }
731
+ async setScreenShare(sharing) {
732
+ if (!this.info.isActive)
733
+ return;
734
+ if (this.info.stateData.screenSharing === sharing)
735
+ return;
736
+ if (sharing && !this.videoSendActive) {
737
+ throw new Error(`Call ${this.info.callId} carries no video to share the screen on`);
738
+ }
739
+ const peerDeviceJid = this.acceptedByJid ?? this.info.peerJid;
740
+ const state = sharing ? WA_SCREEN_SHARE_STATE.Started : WA_SCREEN_SHARE_STATE.Stopped;
741
+ try {
742
+ await this.deps.lowLevelCoordinator.sendNode(buildScreenShareStanza(peerDeviceJid, this.info.callId, this.info.callCreator, state));
743
+ }
744
+ catch (err) {
745
+ this.logger.warn('screen share request failed', {
746
+ sharing,
747
+ message: toError(err).message
748
+ });
749
+ throw err;
750
+ }
751
+ this.info.applyTransition({ type: 'screen_share_changed', sharing });
752
+ this.delegate.emitState(this.info);
753
+ }
754
+ handleCallUserAction(node, peerJid) {
755
+ this.applyPeerRaiseHand(node, peerJid);
756
+ }
757
+ handleCallRaiseHand(node, peerJid) {
758
+ this.applyPeerRaiseHand(node, peerJid);
759
+ }
760
+ applyPeerRaiseHand(node, peerJid) {
761
+ const nodeInfo = extractNodeInfo(node);
762
+ if (!nodeInfo)
763
+ return;
764
+ if (this.isOwnAccountJid(peerJid))
765
+ return;
766
+ const raised = parseRaiseHandState(nodeInfo.innerNode);
767
+ if (raised === null)
768
+ return;
769
+ const raisedHands = this.info.raisedHands;
770
+ if (raisedHands.has(peerJid) === raised)
771
+ return;
772
+ if (raised) {
773
+ if (raisedHands.size >= 64)
774
+ return;
775
+ raisedHands.add(peerJid);
776
+ }
777
+ else {
778
+ raisedHands.delete(peerJid);
779
+ }
780
+ this.delegate.emitHandRaise?.(this.info, peerJid, raised);
781
+ }
782
+ handleCallScreenShare(node) {
783
+ const nodeInfo = extractNodeInfo(node);
784
+ if (!nodeInfo)
785
+ return;
786
+ const share = parseScreenShareNode(nodeInfo.innerNode);
787
+ if (!share)
788
+ return;
789
+ this.info.peerScreenShare = share;
790
+ this.delegate.emitScreenShare?.(this.info, share);
791
+ this.delegate.emitState(this.info);
792
+ }
793
+ sendReaction(reaction) {
794
+ if (!this.appDataStream || !this.appDataSrtpSession)
795
+ return false;
796
+ if (!this.info.isActive)
797
+ return false;
798
+ return this.appDataStream.sendReaction(reaction);
799
+ }
800
+ openAppDataStream(selfDeviceJid) {
801
+ const ssrc = generateSecureSsrc(this.info.callId, selfDeviceJid, 6);
802
+ this.appDataStream?.close();
803
+ this.appDataStream = new WaAppDataStream({
804
+ logger: this.logger.child({ component: 'app-data' }),
805
+ ssrc,
806
+ sendPacket: (packet) => {
807
+ if (!this.appDataSrtpSession)
808
+ return false;
809
+ return this.sctpRelay.broadcast(toArrayBuffer(this.appDataSrtpSession.protect(packet)));
810
+ }
811
+ });
812
+ }
813
+ trackPeerAppDataSsrcs(deviceJids) {
814
+ for (const jid of deviceJids) {
815
+ if (!jid)
816
+ continue;
817
+ if (this.peerAppDataSsrcs.size >= 16)
818
+ break;
819
+ this.peerAppDataSsrcs.add(generateSecureSsrc(this.info.callId, this.ensureDeviceJid(jid), 6));
820
+ }
821
+ }
822
+ onAppDataPacket(data, payloadType, ssrc) {
823
+ const stream = this.appDataStream;
824
+ if (!stream || !this.appDataSrtpSession)
825
+ return;
826
+ try {
827
+ const packet = this.appDataSrtpSession.unprotect(data);
828
+ stream.observeInboundPayloadType(payloadType);
829
+ for (const reaction of stream.receive(packet.payload, ssrc)) {
830
+ this.delegate.emitCallReaction?.(this.info, reaction);
831
+ }
832
+ }
833
+ catch (err) {
834
+ this.logger.debug('app data packet dropped', {
835
+ callId: this.info.callId,
836
+ payloadType,
837
+ message: toError(err).message
838
+ });
839
+ }
840
+ }
841
+
842
+ async handleCallVideo(node) {
843
+ const nodeInfo = extractNodeInfo(node);
844
+ if (!nodeInfo)
845
+ return;
846
+ const inner = nodeInfo.innerNode;
847
+ const state = Number(inner.attrs?.state ?? Number.NaN);
848
+ if (!Number.isFinite(state))
849
+ return;
850
+ const peerJid = this.acceptedByJid || this.info.peerJid;
851
+ const callId = this.info.callId;
852
+ const callCreator = this.info.callCreator;
853
+ const sourceJid = nodeInfo.peerJid || peerJid;
854
+ const setPeerVideo = (on) => {
855
+ const before = this.peerVideoJids.size;
856
+ if (on)
857
+ this.peerVideoJids.add(sourceJid);
858
+ else
859
+ this.peerVideoJids.delete(sourceJid);
860
+ this.peerVideoActive = this.peerVideoJids.size > 0;
861
+ return { before, after: this.peerVideoJids.size };
862
+ };
863
+ this.logger.media('inbound video state', { callId, state });
864
+ switch (state) {
865
+ case VideoState.UpgradeRequest:
866
+ case VideoState.UpgradeRequestV2: {
867
+ setPeerVideo(true);
868
+ this.peerVideoUpgradePending = true;
869
+ await this.enableVideoMidCall();
870
+ try {
871
+ const accept = buildVideoStateStanza(peerJid, callId, callCreator, VideoState.UpgradeAccept, { dec: VideoDecAccept });
872
+ await this.deps.lowLevelCoordinator.sendNode(accept);
873
+ }
874
+ catch (err) {
875
+ this.logger.error('error sending video upgrade accept', { callId, message: toError(err).message });
876
+ }
877
+ this.peerVideoUpgradePending = false;
878
+ this.info.mediaType = CallMediaType.Video;
879
+ this.info.stateData.videoOff = false;
880
+ this.delegate.emitState(this.info);
881
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: state, jid: sourceJid });
882
+ break;
883
+ }
884
+ case VideoState.Disabled:
885
+ case VideoState.Stopped: {
886
+ const { before, after } = setPeerVideo(false);
887
+ if (state === VideoState.Disabled && before === after)
888
+ break;
889
+ this.delegate.emitVideoState?.(this.info, {
890
+ active: false,
891
+ upgrade: false,
892
+ raw: state,
893
+ direction: 'inbound',
894
+ jid: sourceJid,
895
+ allOff: before > 0 && after === 0
896
+ });
897
+ break;
898
+ }
899
+ case VideoState.UpgradeReject:
900
+ case VideoState.UpgradeCancel: {
901
+ this.disableVideoMidCall({ keepSource: true });
902
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: state });
903
+ break;
904
+ }
905
+ case VideoState.Enabled: {
906
+ setPeerVideo(true);
907
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: false, raw: state, direction: 'inbound', jid: sourceJid });
908
+ break;
909
+ }
910
+ default:
911
+ break;
912
+ }
913
+ }
914
+
915
+ async startVideoMidCall() {
916
+ const peerJid = this.acceptedByJid || this.info.peerJid;
917
+ const request = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.UpgradeRequestV2, { dec: VideoDecRequest });
918
+ await this.deps.lowLevelCoordinator.sendNode(request);
919
+ await this.enableVideoMidCall();
920
+ this.info.mediaType = CallMediaType.Video;
921
+ this.info.stateData.videoOff = false;
922
+ this.delegate.emitState(this.info);
923
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: VideoState.UpgradeRequestV2 });
924
+ }
925
+ async enableVideoMidCall() {
926
+ if (this.videoRtpStream && this.videoSrtpSession)
927
+ return;
928
+ const creds = this.deps.authClient.getCurrentCredentials();
929
+ const selfLid = creds?.meLid || creds?.meJid || '';
930
+ if (!this.videoSsrc) {
931
+ this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
932
+ }
933
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
934
+
935
+ if (this.srtpSession) {
936
+ const meLid = creds?.meLid;
937
+ const meId = creds?.meJid;
938
+ const ourBase = toUserJid(meLid || meId || '');
939
+ const participants = this.info.relayData?.participantJids || [];
940
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => toUserJid(jid) === ourBase && /:\d+@/.test(jid)) || meLid || meId || '');
941
+ const peerDeviceJid = this.ensureDeviceJid(this.acceptedByJid || this.info.peerJid);
942
+ try {
943
+ const sendKeying = derivePerJidSrtpKey(this.info.encryptionKey, ourDeviceJid);
944
+ const recvKeying = derivePerJidSrtpKey(this.info.encryptionKey, peerDeviceJid);
945
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
946
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
947
+ }
948
+ catch (err) {
949
+ this.logger.error('video srtp key derivation failed', { callId: this.info.callId, message: toError(err).message });
950
+ }
951
+ }
952
+ this.videoAssembler = new H264AccessUnitAssembler();
953
+
954
+ if (!this.videoEngine.hasSource()) {
955
+ try {
956
+ await this.videoEngine.loadBlankSource();
957
+ }
958
+ catch (err) {
959
+ this.logger.error('blank video fallback unavailable', { callId: this.info.callId, message: toError(err).message });
960
+ }
961
+ }
962
+ if (this.sctpRelay.hasConnection()) {
963
+ this.videoEngine.start();
964
+ }
965
+ this.logger.media('video enabled mid-call', {
966
+ callId: this.info.callId,
967
+ videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`,
968
+ source: this.videoEngine.sourceKind
969
+ });
970
+ }
971
+
972
+ async swapVideoSource(videoPath) {
973
+ if (this.info.mediaType !== CallMediaType.Video) {
974
+ throw new Error(`Call ${this.info.callId} has no active video stream to swap`);
975
+ }
976
+ this.videoEngine.stop({ keepSource: false });
977
+ await this.videoEngine.loadVideoFile(videoPath);
978
+ this.audioEngine.setLoopMode(true);
979
+ this.videoEngine.start();
980
+ this.logger.media('video source swapped', { callId: this.info.callId, videoPath });
981
+ }
982
+
983
+ async stopVideoMidCall({ keepSource = false } = {}) {
984
+ const peerJid = this.acceptedByJid || this.info.peerJid;
985
+ try {
986
+ const stop = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.Stopped);
987
+ await this.deps.lowLevelCoordinator.sendNode(stop);
988
+ }
989
+ catch (err) {
990
+ this.logger.error('error sending video stop', { callId: this.info.callId, message: toError(err).message });
991
+ }
992
+ this.disableVideoMidCall({ keepSource });
993
+ this.info.stateData.videoOff = true;
994
+ this.delegate.emitState(this.info);
995
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: VideoState.Stopped });
996
+ }
997
+
998
+ disableVideoMidCall({ keepSource = false } = {}) {
999
+ this.videoEngine.stop({ keepSource });
1000
+ this.videoRtpStream = null;
1001
+ this.videoSrtpSession = null;
1002
+ this.videoRtcpSession = null;
1003
+ this.videoAssembler = null;
1004
+ this.info.mediaType = CallMediaType.Audio;
1005
+ this.logger.media('video disabled mid-call', { callId: this.info.callId, keptSource: keepSource });
1006
+ }
1007
+ handleCallTerminate() {
1008
+ try {
1009
+ this.info.applyTransition({
1010
+ type: 'terminated',
1011
+ reason: EndCallReason.UserEnded
1012
+ });
1013
+ }
1014
+ catch (err) {
1015
+ this.logger.trace('call transition skipped', { message: toError(err).message });
1016
+ }
1017
+ this.delegate.emitEnded(this.info);
1018
+ this.delegate.emitState(this.info);
1019
+ this.cleanup();
1020
+ }
1021
+ sendCapturedAudio(data) {
1022
+ const nowMs = Date.now();
1023
+ if (this.lastCapturedAtMs !== undefined) {
1024
+ const gapMs = nowMs - this.lastCapturedAtMs;
1025
+
1026
+ if (gapMs > 300) {
1027
+ this.logger.warn('captured audio frame gap larger than expected', {
1028
+ callId: this.info.callId,
1029
+ gapMs,
1030
+ audioSendCount: this.audioSendCount,
1031
+ sctpBacklog: this.sctpRelay.getSendBacklog()
1032
+ });
1033
+ }
1034
+ }
1035
+ this.lastCapturedAtMs = nowMs;
1036
+ const hasRelay = this.sctpRelay.hasConnection();
1037
+ if (!this.rtpSession || !this.srtpSession || !this.opusCodec || !hasRelay) {
1038
+ this.audioDropCount++;
1039
+ if (this.audioDropCount === 1 || this.audioDropCount % 500 === 0) {
1040
+ const missing = [
1041
+ !this.rtpSession && 'rtpSession',
1042
+ !this.srtpSession && 'srtpSession',
1043
+ !this.opusCodec && 'opusCodec',
1044
+ !hasRelay && 'relayConnection'
1045
+ ]
1046
+ .filter(Boolean)
1047
+ .join(', ');
1048
+ this.logger.media('audio dropped', {
1049
+ callId: this.info.callId,
1050
+ dropCount: this.audioDropCount,
1051
+ missing
1052
+ });
1053
+ }
1054
+ return;
1055
+ }
1056
+ for (let i = 0; i < data.length; i++) {
1057
+ if (!Number.isFinite(data[i])) {
1058
+ data[i] = 0;
1059
+ }
1060
+ }
1061
+ const frameSamples = this.encodeFrameSamples;
1062
+ if (!this.encodeBuffer) {
1063
+ if (!this.encodeBufferA) {
1064
+ this.encodeBufferA = new Float32Array(frameSamples);
1065
+ this.encodeBufferB = new Float32Array(frameSamples);
1066
+ }
1067
+ this.encodeBuffer = this.encodeBufferA;
1068
+ this.encodeBufferPos = 0;
1069
+ }
1070
+ let offset = 0;
1071
+ while (offset < data.length) {
1072
+ const toCopy = Math.min(data.length - offset, frameSamples - this.encodeBufferPos);
1073
+ this.encodeBuffer.set(data.subarray(offset, offset + toCopy), this.encodeBufferPos);
1074
+ this.encodeBufferPos += toCopy;
1075
+ offset += toCopy;
1076
+ if (this.encodeBufferPos < frameSamples)
1077
+ break;
1078
+ const frameData = this.encodeBuffer;
1079
+ this.encodeBuffer =
1080
+ frameData === this.encodeBufferA ? this.encodeBufferB : this.encodeBufferA;
1081
+ this.encodeBufferPos = 0;
1082
+ try {
1083
+ const opusFrame = this.opusCodec.encode(frameData);
1084
+ if (opusFrame.length <= 18)
1085
+ this.qLog.tiny++;
1086
+ this.sendOpusFrame(opusFrame, false);
1087
+ this.realAudioSendCount++;
1088
+ }
1089
+ catch (err) {
1090
+ this.logger.error('encode error', {
1091
+ callId: this.info.callId,
1092
+ message: toError(err).message
1093
+ });
1094
+ }
1095
+ }
1096
+ }
1097
+
1098
+ async loadVideo(videoPath) {
1099
+ if (this.info.mediaType !== CallMediaType.Video) {
1100
+ throw new Error(`Call ${this.info.callId} was not started with isVideo — no video SSRC/RTP stream to send on`);
1101
+ }
1102
+ await this.videoEngine.loadVideoFile(videoPath);
1103
+ this.audioEngine.setLoopMode(true);
1104
+
1105
+ if (this.mediaFlowStarted && this.sctpRelay.hasConnection()) {
1106
+ this.videoEngine.start();
1107
+ }
1108
+ }
1109
+
1110
+ sendCapturedVideoAU(au, durationMs) {
1111
+ const hasRelay = this.sctpRelay.hasConnection();
1112
+ if (!this.videoRtpStream || !this.videoSrtpSession || !hasRelay) {
1113
+ this.videoDropCount++;
1114
+ if (this.videoDropCount === 1 || this.videoDropCount % 150 === 0) {
1115
+ const missing = [
1116
+ !this.videoRtpStream && 'videoRtpStream',
1117
+ !this.videoSrtpSession && 'videoSrtpSession',
1118
+ !hasRelay && 'relayConnection'
1119
+ ].filter(Boolean).join(', ');
1120
+ this.logger.media('video access unit dropped', {
1121
+ callId: this.info.callId, dropCount: this.videoDropCount, missing
1122
+ });
1123
+ }
1124
+ return;
1125
+ }
1126
+ try {
1127
+ const idr = auHasIDR(au);
1128
+ const flushesBefore = this.sctpRelay.getVideoFlushCount();
1129
+ if (flushesBefore !== this.videoFlushSeen) {
1130
+ this.videoFlushSeen = flushesBefore;
1131
+ this.videoKeyframeRequired = true;
1132
+ }
1133
+ if (this.videoKeyframeRequired && !idr)
1134
+ return;
1135
+ const mediaFrameInfo = idr ? VideoMediaFrameInfo.IDR : VideoMediaFrameInfo.Delta;
1136
+ this.videoRtpStream.setTimestampStride(videoRtpDurationSamples(durationMs));
1137
+ // FIX: split the access unit into individual NALUs and package each one
1138
+ // separately. The old code merged all NALUs into one buffer via
1139
+ // buildAccessUnitPayload() and then passed that to packageH264NALU(),
1140
+ // which treated the entire merged buffer as a single NALU (inheriting the
1141
+ // first NALU's type byte, typically SPS=7). The receiver reassembled one
1142
+ // giant malformed NALU of the wrong type, so the IDR frame was never
1143
+ // decoded and video appeared blank.
1144
+ const allNalus = splitAnnexB(au).filter(
1145
+ (n) => n.length > 0 && !DROP_NAL_TYPES.has(n[0] & 0x1f)
1146
+ );
1147
+ if (allNalus.length === 0)
1148
+ return;
1149
+ // Build the full flat list of RTP chunks for this access unit
1150
+ const allChunks = [];
1151
+ for (const nalu of allNalus) {
1152
+ for (const chunk of packageH264NALU(nalu)) {
1153
+ allChunks.push(chunk);
1154
+ }
1155
+ }
1156
+ for (let i = 0; i < allChunks.length; i++) {
1157
+ const isLast = i === allChunks.length - 1;
1158
+ const header = this.videoRtpStream.nextPacket(isLast, mediaFrameInfo);
1159
+ const srtpData = this.videoSrtpSession.protect(new RtpPacket(header, allChunks[i]));
1160
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1161
+ this.videoOctetsSent = (this.videoOctetsSent + allChunks[i].length) >>> 0;
1162
+ }
1163
+ const flushesAfter = this.sctpRelay.getVideoFlushCount();
1164
+ if (flushesAfter !== flushesBefore) {
1165
+ this.videoFlushSeen = flushesAfter;
1166
+ this.videoKeyframeRequired = true;
1167
+ }
1168
+ else if (idr) {
1169
+ this.videoKeyframeRequired = false;
1170
+ }
1171
+ this.videoSendCount++;
1172
+ if (idr)
1173
+ this.videoIdrSendCount++;
1174
+ if (idr || this.videoSendCount === 1 || this.videoSendCount % 150 === 0) {
1175
+ this.logger.media('video sent', {
1176
+ callId: this.info.callId, sendCount: this.videoSendCount,
1177
+ idrSentTotal: this.videoIdrSendCount,
1178
+ auBytes: au.length, naluCount: allNalus.length, packets: allChunks.length, idr
1179
+ });
1180
+ }
1181
+ }
1182
+ catch (err) {
1183
+ this.logger.error('error sending video', {
1184
+ callId: this.info.callId, message: toError(err).message
1185
+ });
1186
+ }
1187
+ }
1188
+ cleanup() {
1189
+ this.logger.warn('[DIAG] cleanup entered', { callId: this.info.callId, state: this.info.stateData.state });
1190
+ const opusStats = this.opusCodec?.getStats();
1191
+ this.logger.media('call stats', {
1192
+ callId: this.info.callId,
1193
+ relayPackets: this.relayPacketCount,
1194
+ recvOk: this.audioRecvCount,
1195
+ srtpErrors: this.srtpErrorCount,
1196
+ sent: this.audioSendCount,
1197
+ dropped: this.audioDropCount,
1198
+ opusOk: opusStats?.success ?? 0,
1199
+ opusErr: opusStats?.errors ?? 0,
1200
+ videoSent: this.videoSendCount,
1201
+ videoIdrSent: this.videoIdrSendCount,
1202
+ videoDropped: this.videoDropCount
1203
+ });
1204
+ this.audioEngine.setOnAudioFinished(null);
1205
+ this.audioEngine.stop();
1206
+ this.videoEngine.stop();
1207
+ this.sctpRelay.cleanup();
1208
+ if (this.rtcpTimer) {
1209
+ clearInterval(this.rtcpTimer);
1210
+ this.rtcpTimer = null;
1211
+ }
1212
+ if (this.opusCodec) {
1213
+ this.opusCodec.destroy();
1214
+ this.opusCodec = null;
1215
+ }
1216
+ this.rtpSession = null;
1217
+ this.srtpSession = null;
1218
+ this.appDataStream?.close();
1219
+ this.appDataStream = null;
1220
+ this.appDataSrtpSession = null;
1221
+ this.peerAppDataSsrcs.clear();
1222
+ this.audioRtcpSession = null;
1223
+ this.audioRtcpCname = null;
1224
+ this.audioOctetsSent = 0;
1225
+ this.videoRtpStream = null;
1226
+ this.videoSrtpSession = null;
1227
+ this.videoRtcpSession = null;
1228
+ this.videoRtcpCname = null;
1229
+ this.videoOctetsSent = 0;
1230
+ this.videoSsrc = 0;
1231
+ this.videoAssembler = null;
1232
+ this.peerVideoUpgradePending = false;
1233
+ this.peerVideoActive = false;
1234
+ this.peerVideoJids.clear();
1235
+ this.mediaStartedAtMs = null;
1236
+ this.videoSendCount = 0;
1237
+ this.videoIdrSendCount = 0;
1238
+ this.videoDropCount = 0;
1239
+ this.audioSendCount = 0;
1240
+ this.audioDropCount = 0;
1241
+ this.audioRecvCount = 0;
1242
+ this.srtpErrorCount = 0;
1243
+ this.relayPacketCount = 0;
1244
+ this.stunResponseCount = 0;
1245
+ this.selfEchoCount = 0;
1246
+ this.lastRecvSeq = -1;
1247
+ this.recvSeqGaps = 0;
1248
+ this.actualPeerSsrc = null;
1249
+ this.ssrcResubscribed = false;
1250
+ this.recvRealCount = 0;
1251
+ this.recvDtxCount = 0;
1252
+ this.initialTransportSent = false;
1253
+ this.outgoingPreacceptSent = false;
1254
+ this.firstPacketSent = false;
1255
+ this.realAudioSendCount = 0;
1256
+ this.encodeBuffer = null;
1257
+ this.encodeBufferPos = 0;
1258
+ this.acceptedByJid = null;
1259
+ }
1260
+ get encodeFrameSamples() {
1261
+ return this.opusCodec?.getFrameSize() ?? 960;
1262
+ }
1263
+ get rtpTsDelta() {
1264
+ return this.encodeFrameSamples;
1265
+ }
1266
+ sendOpusFrame(opusFrame, isSilence) {
1267
+ if (!this.rtpSession || !this.srtpSession)
1268
+ return;
1269
+ try {
1270
+ let rtpPayload = opusFrame;
1271
+ const authPadding = SRTP_AUTH_TAG_LEN - SRTP_SEND_AUTH_TAG_LEN;
1272
+ if (authPadding > 0) {
1273
+ if (!this.authPaddingBuffer || this.authPaddingBuffer.length !== authPadding) {
1274
+ this.authPaddingBuffer = new Uint8Array(authPadding);
1275
+ }
1276
+ rtpPayload = concatBytes([rtpPayload, this.authPaddingBuffer]);
1277
+ }
1278
+ const marker = !this.firstPacketSent;
1279
+ const tsDelta = this.rtpTsDelta;
1280
+ const rtpPacket = this.rtpSession.createPacketWithDuration(rtpPayload, tsDelta, marker);
1281
+ if (this.debeEnabled) {
1282
+ rtpPacket.header.extension = true;
1283
+ rtpPacket.header.extensionProfile = 0xdebe;
1284
+ rtpPacket.header.extensionData = WaCallMediaSession.EMPTY_BYTES;
1285
+ }
1286
+ if (!this.firstPacketSent) {
1287
+ this.firstPacketSent = true;
1288
+ }
1289
+ const srtpData = this.srtpSession.protect(rtpPacket);
1290
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1291
+ this.audioSendCount++;
1292
+ this.audioOctetsSent = (this.audioOctetsSent + rtpPayload.length) >>> 0;
1293
+ if (this.audioSendCount === 1 || this.audioSendCount % 500 === 0) {
1294
+ this.logger.media('audio sent', {
1295
+ callId: this.info.callId,
1296
+ sendCount: this.audioSendCount,
1297
+ opusBytes: opusFrame.length,
1298
+ srtpBytes: srtpData.length,
1299
+ silence: isSilence,
1300
+ sctpBacklog: this.sctpRelay.getSendBacklog()
1301
+ });
1302
+ }
1303
+ }
1304
+ catch (err) {
1305
+ this.logger.error('error sending audio', {
1306
+ callId: this.info.callId,
1307
+ message: toError(err).message
1308
+ });
1309
+ }
1310
+ }
1311
+ ensureDeviceJid(jid) {
1312
+ if (/:\d+@/.test(jid))
1313
+ return jid;
1314
+ return jid.replace('@', ':0@');
1315
+ }
1316
+ initSrtpKeys() {
1317
+ const callKey = this.info.encryptionKey;
1318
+ if (!callKey) {
1319
+ this.logger.media('no call_key, srtp not initialized', { callId: this.info.callId });
1320
+ return;
1321
+ }
1322
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
1323
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
1324
+ const ourCredJid = meLid || meId || '';
1325
+ const ourBase = toUserJid(ourCredJid);
1326
+ const participants = this.info.relayData?.participantJids || [];
1327
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => {
1328
+ const jBase = toUserJid(jid);
1329
+ return jBase === ourBase && /:\d+@/.test(jid);
1330
+ }) || ourCredJid);
1331
+ let rawPeerJid = this.acceptedByJid || this.info.peerJid;
1332
+ if (!this.acceptedByJid) {
1333
+ const peerFromParticipants = participants.find((jid) => {
1334
+ const jBase = toUserJid(jid);
1335
+ return jBase !== ourBase;
1336
+ });
1337
+ if (peerFromParticipants)
1338
+ rawPeerJid = peerFromParticipants;
1339
+ }
1340
+ const peerDeviceJid = this.ensureDeviceJid(rawPeerJid);
1341
+ try {
1342
+ const sendKeying = derivePerJidSrtpKey(callKey, ourDeviceJid);
1343
+ const recvKeying = derivePerJidSrtpKey(callKey, peerDeviceJid);
1344
+ this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1345
+ this.appDataSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1346
+ this.openAppDataStream(ourDeviceJid);
1347
+ this.peerAppDataSsrcs.clear();
1348
+ this.trackPeerAppDataSsrcs([peerDeviceJid, ...participants.filter((jid) => toUserJid(jid) !== ourBase)]);
1349
+ this.audioRtcpSession = new SrtcpSendContext(sendKeying);
1350
+ if (this.info.mediaType === CallMediaType.Video) {
1351
+
1352
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1353
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
1354
+ }
1355
+ this.startRtcpSenderReports();
1356
+ this.logger.debug('srtp per-jid keys initialized', {
1357
+ callId: this.info.callId,
1358
+ sendJid: ourDeviceJid,
1359
+ recvJid: peerDeviceJid
1360
+ });
1361
+ }
1362
+ catch (err) {
1363
+ this.logger.debug('srtp key derivation failed', {
1364
+ callId: this.info.callId,
1365
+ message: toError(err).message
1366
+ });
1367
+ }
1368
+ }
1369
+
1370
+ startRtcpSenderReports() {
1371
+ if (this.rtcpTimer)
1372
+ clearInterval(this.rtcpTimer);
1373
+ if (!this.audioRtcpCname)
1374
+ this.audioRtcpCname = generateWhatsappRtcpCname();
1375
+ if (!this.videoRtcpCname)
1376
+ this.videoRtcpCname = generateWhatsappRtcpCname();
1377
+ this.rtcpTimer = setInterval(() => {
1378
+ if (!this.sctpRelay.hasConnection())
1379
+ return;
1380
+ if (++this.qLog.n % 3 === 0)
1381
+ this.logVoipQuality();
1382
+ const nowMs = Date.now();
1383
+ try {
1384
+ if (this.audioRtcpSession && this.selfSsrc) {
1385
+ const stats = {
1386
+ packetsSent: this.audioSendCount,
1387
+ octetsSent: this.audioOctetsSent,
1388
+ rtpTimestamp: this.rtpSession?.timestamp ?? 0
1389
+ };
1390
+ const plain = buildSenderReportWithSdes(this.selfSsrc, stats, nowMs, this.audioRtcpCname);
1391
+ const protectedPacket = this.audioRtcpSession.protect(this.selfSsrc, plain);
1392
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1393
+ }
1394
+ if (this.videoRtcpSession && this.videoSsrc && this.videoSendCount > 0) {
1395
+ const stats = {
1396
+ packetsSent: this.videoSendCount,
1397
+ octetsSent: this.videoOctetsSent,
1398
+ rtpTimestamp: this.videoRtpStream?.timestamp ?? 0
1399
+ };
1400
+ const plain = buildSenderReportWithSdes(this.videoSsrc, stats, nowMs, this.videoRtcpCname);
1401
+ const protectedPacket = this.videoRtcpSession.protect(this.videoSsrc, plain);
1402
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1403
+ }
1404
+
1405
+ if (this.mediaStartedAtMs) {
1406
+ const wallElapsedMs = nowMs - this.mediaStartedAtMs;
1407
+ const audioElapsedMs = this.audioSendCount * 60;
1408
+ const videoElapsedMs = this.videoSendCount * (1000 / this.videoEngine.frameRate);
1409
+ this.logger.media('av sync check', {
1410
+ callId: this.info.callId,
1411
+ wallElapsedMs,
1412
+ audioElapsedMs,
1413
+ videoElapsedMs,
1414
+ audioMinusWallMs: audioElapsedMs - wallElapsedMs,
1415
+ videoMinusWallMs: Math.round(videoElapsedMs - wallElapsedMs)
1416
+ });
1417
+ }
1418
+ }
1419
+ catch (err) {
1420
+ this.logger.debug('rtcp sender report failed', {
1421
+ callId: this.info.callId,
1422
+ message: toError(err).message
1423
+ });
1424
+ }
1425
+ }, 1500);
1426
+ }
1427
+ resetEncodeState() {
1428
+ this.encodeBuffer = null;
1429
+ this.encodeBufferPos = 0;
1430
+ this.realAudioSendCount = 0;
1431
+ }
1432
+ onRelayConnected() {
1433
+ if (this.info.stateData.state === CallState.Connecting) {
1434
+ try {
1435
+ this.info.applyTransition({ type: 'media_connected' });
1436
+ this.delegate.emitState(this.info);
1437
+ this.logger.media('relay connected', {
1438
+ callId: this.info.callId, acceptedByJid: this.acceptedByJid ?? null
1439
+ });
1440
+ if (!this.acceptedByJid) {
1441
+ this.logger.media('relay connected before accept, deferring media start', {
1442
+ callId: this.info.callId
1443
+ });
1444
+ return;
1445
+ }
1446
+ const MEDIA_START_DELAY_MS = 3000;
1447
+ setTimeout(() => {
1448
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path A)', {
1449
+ callId: this.info.callId, state: this.info.stateData.state
1450
+ });
1451
+ if (this.info.stateData.state === CallState.Ended) {
1452
+ return;
1453
+ }
1454
+ this.startMediaFlow();
1455
+ }, MEDIA_START_DELAY_MS);
1456
+ }
1457
+ catch (err) {
1458
+ this.logger.trace('call transition skipped', { message: toError(err).message });
1459
+ }
1460
+ }
1461
+ }
1462
+ onRelayData(data) {
1463
+ this.relayPacketCount++;
1464
+ if (isStunPacket(data)) {
1465
+ this.stunResponseCount++;
1466
+ return;
1467
+ }
1468
+ if (!isRtpPacket(data))
1469
+ return;
1470
+ const pt = data[1] & 0x7f;
1471
+ if (this.peerAppDataSsrcs.size > 0 && data.length >= 12) {
1472
+ const appDataSsrc = readUInt32BE(data, 8);
1473
+ if (this.peerAppDataSsrcs.has(appDataSsrc)) {
1474
+ this.onAppDataPacket(data, pt, appDataSsrc);
1475
+ return;
1476
+ }
1477
+ }
1478
+ if (pt === PayloadType.H264) {
1479
+ this.onRelayVideoData(data);
1480
+ return;
1481
+ }
1482
+ if (!this.srtpSession || !this.opusCodec)
1483
+ return;
1484
+ if (pt !== 120)
1485
+ return;
1486
+ if (data.length >= 12) {
1487
+ const ssrc = ((data[8] << 24) | (data[9] << 16) | (data[10] << 8) | data[11]) >>> 0;
1488
+ if (ssrc === this.selfSsrc) {
1489
+ this.selfEchoCount++;
1490
+ return;
1491
+ }
1492
+ if (!this.ssrcResubscribed && this.actualPeerSsrc === null) {
1493
+ this.actualPeerSsrc = ssrc;
1494
+ const knownSsrc = this.peerSsrcs.includes(ssrc);
1495
+ if (!knownSsrc) {
1496
+ this.peerSsrcs = [ssrc];
1497
+ this.ssrcResubscribed = true;
1498
+ this.opusCodec.resetSequence();
1499
+ this.lastRecvSeq = -1;
1500
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1501
+ this.sctpRelay.resendSubscriptions();
1502
+ }
1503
+ }
1504
+ }
1505
+ try {
1506
+ const rtpPacket = this.srtpSession.unprotect(data);
1507
+ const opusPayload = rtpPacket.payload;
1508
+ this.audioRecvCount++;
1509
+ if (opusPayload.length === 0)
1510
+ return;
1511
+ const seq = rtpPacket.header.sequenceNumber;
1512
+ if (this.lastRecvSeq >= 0) {
1513
+ const gap = ((seq - this.lastRecvSeq + 65536) % 65536) - 1;
1514
+ if (gap > 0 && gap < 0x8000)
1515
+ this.recvSeqGaps += gap;
1516
+ }
1517
+ this.lastRecvSeq = seq;
1518
+ const isDtx = opusPayload.length <= 2;
1519
+ if (isDtx)
1520
+ this.recvDtxCount++;
1521
+ else
1522
+ this.recvRealCount++;
1523
+ this.opusCodec.decodeSequenced(seq, opusPayload, this.onDecodedAudio);
1524
+ if (this.audioRecvCount % 100 === 0) {
1525
+ const w = (this.lossWindow ??= { gaps: 0, pkts: 0 });
1526
+ const gaps = this.recvSeqGaps - w.gaps;
1527
+ const pkts = this.audioRecvCount - w.pkts;
1528
+ w.gaps = this.recvSeqGaps;
1529
+ w.pkts = this.audioRecvCount;
1530
+ const lossPct = pkts + gaps > 0 ? Math.min(100, Math.round((100 * gaps) / (pkts + gaps))) : 0;
1531
+ this.opusCodec.setExpectedPacketLossPercent(lossPct);
1532
+ }
1533
+ if (this.audioRecvCount % 1500 === 0) {
1534
+ const stats = this.opusCodec.getStats();
1535
+
1536
+ this.logger.trace('audio recv stats', {
1537
+ callId: this.info.callId,
1538
+ recvCount: this.audioRecvCount,
1539
+ real: this.recvRealCount,
1540
+ dtx: this.recvDtxCount,
1541
+ decodeOk: stats.success,
1542
+ decodeErr: stats.errors,
1543
+ plc: stats.plc,
1544
+ fec: stats.fec,
1545
+ late: stats.late
1546
+ });
1547
+ }
1548
+ }
1549
+ catch (err) {
1550
+ this.srtpErrorCount++;
1551
+ if (this.srtpErrorCount <= 5) {
1552
+ const ssrc = data.length >= 12 ? readUInt32BE(data, 8) : 0;
1553
+ this.logger.debug('srtp recv error', {
1554
+ callId: this.info.callId,
1555
+ errorCount: this.srtpErrorCount,
1556
+ message: toError(err).message,
1557
+ ssrc: `0x${ssrc.toString(16)}`
1558
+ });
1559
+ }
1560
+ }
1561
+ }
1562
+
1563
+ logVoipQuality() {
1564
+ try {
1565
+ const q = this.qLog;
1566
+ const pace = this.audioEngine.takePacingStats();
1567
+ const bl = this.sctpRelay.getSendBacklog?.() ?? {};
1568
+ const sent = this.audioSendCount - q.sent;
1569
+ const octets = ((this.audioOctetsSent - q.octets) >>> 0);
1570
+ const rs = this.opusCodec?.getStats() ?? { late: 0, plc: 0, fec: 0, errors: 0 };
1571
+ const line = {
1572
+ callId: this.info.callId,
1573
+ tSec: this.mediaStartedAtMs ? Math.round((Date.now() - this.mediaStartedAtMs) / 1000) : 0,
1574
+ txFrames: sent,
1575
+ txAvgB: sent > 0 ? Math.round(octets / sent) : 0,
1576
+ txTinyPct: sent > 0 ? Math.round((100 * (this.qLog.tiny)) / sent) : 0,
1577
+ tickLate90: pace.late90,
1578
+ tickLate200: pace.late200,
1579
+ tickBurst: pace.burst20,
1580
+ tickMaxGapMs: pace.maxGap,
1581
+ loopP50ms: pace.loopP50,
1582
+ loopP99ms: pace.loopP99,
1583
+ loopMaxMs: pace.loopMax,
1584
+ sctpInFlight: bl.inFlight ?? 0,
1585
+ sctpQueuedAudio: bl.queuedAudio ?? 0,
1586
+ sctpRetx: (bl.retransmits ?? 0) - q.retx,
1587
+ aLagMs: this.mediaStartedAtMs ? this.audioSendCount * 60 - (Date.now() - this.mediaStartedAtMs) : 0,
1588
+ vLagMs: this.mediaStartedAtMs && this.videoSendCount > 0 && this.videoEngine?.frameRate
1589
+ ? Math.round(this.videoSendCount * (1000 / this.videoEngine.frameRate) - (Date.now() - this.mediaStartedAtMs))
1590
+ : 0,
1591
+ vRestarts: this.videoEngine?._restartCount ?? 0,
1592
+ relayRx: this.relayPacketCount,
1593
+ srtpErr: this.srtpErrorCount,
1594
+ stun: this.sctpRelay.getRxStunStats?.() ?? {},
1595
+ rxPkts: this.audioRecvCount - q.rx,
1596
+ rxLate: rs.late - q.late,
1597
+ rxPlc: rs.plc - q.plc,
1598
+ rxFec: rs.fec - q.fec,
1599
+ rxDecErr: rs.errors - q.errors
1600
+ };
1601
+ this.logger.warn('[VOIPQ] ' + JSON.stringify(line));
1602
+ q.sent = this.audioSendCount;
1603
+ q.octets = this.audioOctetsSent;
1604
+ q.tiny = 0;
1605
+ q.retx = bl.retransmits ?? 0;
1606
+ q.rx = this.audioRecvCount;
1607
+ q.late = rs.late;
1608
+ q.plc = rs.plc;
1609
+ q.fec = rs.fec;
1610
+ q.errors = rs.errors;
1611
+ }
1612
+ catch (err) {
1613
+ this.logger.trace('voip quality log failed', { message: toError(err).message });
1614
+ }
1615
+ }
1616
+ onRelayVideoData(data) {
1617
+ if (!this.videoSrtpSession || !this.videoAssembler)
1618
+ return;
1619
+ try {
1620
+ const rtpPacket = this.videoSrtpSession.unprotect(data);
1621
+ const [accessUnit, complete] = this.videoAssembler.push(rtpPacket.header.sequenceNumber, rtpPacket.header.marker, rtpPacket.payload);
1622
+ if (complete && accessUnit) {
1623
+ this.delegate.emitInboundVideo?.(this.info, accessUnit);
1624
+ }
1625
+ }
1626
+ catch (err) {
1627
+ this.srtpErrorCount++;
1628
+ if (this.srtpErrorCount <= 5) {
1629
+ this.logger.debug('video srtp recv error', {
1630
+ callId: this.info.callId,
1631
+ message: toError(err).message
1632
+ });
1633
+ }
1634
+ }
1635
+ }
1636
+ async connectRelays(endpoints) {
1637
+ this.logger.debug('connecting relays', {
1638
+ callId: this.info.callId,
1639
+ endpointCount: endpoints.length
1640
+ });
1641
+ const seen = new Set();
1642
+ const uniqueEndpoints = [];
1643
+ for (const ep of endpoints) {
1644
+ if ((ep.protocol ?? 0) !== 0)
1645
+ continue;
1646
+ const key = `${ep.ip}:${ep.port}`;
1647
+ if (!seen.has(key)) {
1648
+ seen.add(key);
1649
+ uniqueEndpoints.push(ep);
1650
+ }
1651
+ }
1652
+ const usable = uniqueEndpoints.filter((ep) => ep.key && ep.rawToken);
1653
+
1654
+ const inbound = this.info.direction === CallDirection.Incoming;
1655
+ let chosen = null;
1656
+ if (inbound) {
1657
+ chosen = usable.find((ep) => ep.isFna) ?? null;
1658
+ }
1659
+ if (!chosen) {
1660
+ chosen =
1661
+ usable.find((ep) => !ep.isFna && parseInt(ep.authTokenId, 10) !== 0) ??
1662
+ usable.find((ep) => !ep.isFna) ??
1663
+ usable[0] ??
1664
+ null;
1665
+ }
1666
+ const WA_RELAY_PORT = 3478;
1667
+ const relays = chosen
1668
+ ? [
1669
+ {
1670
+ ip: chosen.ip,
1671
+ port: WA_RELAY_PORT,
1672
+ token: chosen.token,
1673
+ authToken: chosen.authToken,
1674
+ rawAuthToken: chosen.rawAuthToken,
1675
+ rawToken: chosen.rawToken,
1676
+ key: chosen.key,
1677
+ relayId: chosen.relayId,
1678
+ name: chosen.relayName || `${chosen.ip}:${WA_RELAY_PORT}`,
1679
+ authTokenId: chosen.authTokenId,
1680
+ isFna: chosen.isFna
1681
+ }
1682
+ ]
1683
+ : [];
1684
+ if (relays.length === 0) {
1685
+ this.logger.error('no relay configs', { callId: this.info.callId });
1686
+ return;
1687
+ }
1688
+ this.logger.media('relay selected', {
1689
+ callId: this.info.callId,
1690
+ inbound,
1691
+ candidateCount: usable.length,
1692
+ chosen: relays[0].name,
1693
+ isFna: relays[0].isFna
1694
+ });
1695
+ if (this.selfSsrcJid) {
1696
+ this.sctpRelay.setStreamSsrcs(deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid));
1697
+ }
1698
+ this.sctpRelay.setSsrc(this.selfSsrc);
1699
+ if (this.info.mediaType === CallMediaType.Video) {
1700
+ this.sctpRelay.setVideoSsrc(this.videoSsrc);
1701
+ }
1702
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1703
+ try {
1704
+ await this.sctpRelay.configureRelays(relays);
1705
+ this.logger.debug('sctp relays configured', {
1706
+ callId: this.info.callId,
1707
+ connected: this.sctpRelay.getConnectedCount()
1708
+ });
1709
+ }
1710
+ catch (err) {
1711
+ this.logger.error('sctp relay error', {
1712
+ callId: this.info.callId,
1713
+ message: toError(err).message
1714
+ });
1715
+ }
1716
+ }
1717
+ startMediaFlow() {
1718
+ this.mediaStartedAtMs = Date.now();
1719
+ this.mediaFlowStarted = true;
1720
+ this.logger.warn('[DIAG] startMediaFlow entered', { callId: this.info.callId });
1721
+ this.resetEncodeState();
1722
+ this.audioEngine.startPlayback();
1723
+ this.audioEngine.startCapture();
1724
+
1725
+ this.videoEngine.start();
1726
+ }
1727
+ }