@hiroosy/baileys-lite 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- import { toUserJid } from '../shim/protocol.js';
1
+ import { parseSignalAddressFromJid, toUserJid } from '../shim/protocol.js';
2
2
  import { getFirstNodeChild, getNodeChildrenByTag } from '../shim/transport.js';
3
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';
4
+ import { concatBytes, EMPTY_BYTES, readUInt32BE, TEXT_ENCODER, toArrayBuffer } from '../bytes.js';
5
+ import { derivePerJidSrtpKey, generateCallKey } from '../crypto/encryption.js';
6
+ import { SrtpContext, SrtpSession } from '../crypto/srtp.js';
7
7
  import { SrtcpSendContext } from '../crypto/rtcp.js';
8
- import { generateSecureSsrc } from '../crypto/ssrc.js';
8
+ import { deriveWasmRelayStreamSsrcs, formatParticipantId, generateSecureSsrc } from '../crypto/ssrc.js';
9
9
  import { WaAppDataStream } from '../app-data/WaAppDataStream.js';
10
10
  import { buildScreenShareStanza, parseScreenShareNode, WA_SCREEN_SHARE_STATE } from '../signaling/screen-share.js';
11
11
  import { MLowCodec } from '../media/mlow-codec.js';
@@ -15,9 +15,9 @@ import { buildSenderReportWithSdes, generateWhatsappRtcpCname } from '../media/r
15
15
  import { WaAudioEngine } from '../media/WaAudioEngine.js';
16
16
  import { WaVideoEngine } from '../media/WaVideoEngine.js';
17
17
  import { parseRelayFromAck } from '../relay/relay-ack.js';
18
- import { isRtpPacket, isStunPacket } from '../relay/stun.js';
18
+ import { buildGroupAllocateForRelay, isRtpPacket, isStunPacket } from '../relay/stun.js';
19
19
  import { WaManualRelay } from '../relay/WaManualRelay.js';
20
- import { buildAcceptReceiptStanza, buildAcceptStanza, buildMuteV2Stanza, buildPreacceptStanza, buildRaiseHandStanza, buildRejectStanza, buildRelaylatencyForwardStanza, buildRelayLatencyStanza, buildTerminateStanza, buildTransportStanza, buildVideoStateStanza, decryptCallKey, extractNodeInfo, extractRelayEndpoints, needsDecryption, parseMuteV2, parseRaiseHandState, VideoDecAccept, VideoDecRequest, VideoState } from '../signaling/signaling.js';
20
+ import { buildAcceptReceiptStanza, buildAcceptStanza, buildGroupAcceptStanza, buildGroupEncRekeyStanza, buildGroupInviteOfferStanza, buildGroupPreacceptStanza, buildGroupTerminateStanza, buildWaitingRoomRequestStanza, callJidFor, encodeWAMessage, generateCallStanzaId, parseGroupEncRekey, parseGroupUpdate, parseInitialGroupAck, parseWaitingRoomUpdate, buildMuteV2Stanza, buildPreacceptStanza, buildRaiseHandStanza, buildRejectStanza, buildRelaylatencyForwardStanza, buildRelayLatencyStanza, buildTerminateStanza, buildTransportStanza, buildVideoStateStanza, decryptCallKey, extractNodeInfo, extractRelayEndpoints, needsDecryption, parseMuteV2, parseRaiseHandState, VideoDecAccept, VideoDecRequest, VideoState } from '../signaling/signaling.js';
21
21
  import { CallDirection, CallMediaType, CallState, EndCallReason, PayloadType, SRTP_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN, SRTP_SEND_AUTH_TAG_LEN } from '../types.js';
22
22
 
23
23
  export class WaCallMediaSession {
@@ -32,6 +32,9 @@ export class WaCallMediaSession {
32
32
  audioEngine;
33
33
  initialTransportSent = false;
34
34
  outgoingPreacceptSent = false;
35
+ answeredRelays = new Map();
36
+ announcedRelayNames = new Set();
37
+ relayLatencyOpened = false;
35
38
  selfSsrc = 0;
36
39
  selfSsrcJid = '';
37
40
  peerSsrcs = [];
@@ -93,7 +96,8 @@ export class WaCallMediaSession {
93
96
  this.info = options.info;
94
97
  this.delegate = options.delegate;
95
98
  this.sctpRelay = new WaManualRelay({
96
- logger: this.logger.child({ component: 'sctp' })
99
+ logger: this.logger.child({ component: 'sctp' }),
100
+ maxActiveRelays: options.maxActiveRelays
97
101
  });
98
102
  this.audioEngine = new WaAudioEngine({
99
103
  logger: this.logger.child({ component: 'audio-engine' })
@@ -110,6 +114,9 @@ export class WaCallMediaSession {
110
114
  this.sctpRelay.on('relay_connected', () => {
111
115
  this.onRelayConnected();
112
116
  });
117
+ this.sctpRelay.on('relay_answered', (detail) => {
118
+ this.onRelayAnswered(detail);
119
+ });
113
120
  this.sctpRelay.on('relay_receive', (relayInfo) => {
114
121
  this.onRelayData(relayInfo.data);
115
122
  });
@@ -150,7 +157,7 @@ export class WaCallMediaSession {
150
157
  this.selfSsrcJid = this.ensureDeviceJid(selfLid);
151
158
  const peerSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(peerJid));
152
159
  this.peerSsrcs = [peerSsrc];
153
- this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }) });
160
+ this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }), fec: true });
154
161
  if (this.info.mediaType === CallMediaType.Video) {
155
162
  this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
156
163
  this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
@@ -279,24 +286,31 @@ export class WaCallMediaSession {
279
286
  });
280
287
  }
281
288
  }
282
- async sendIncomingRelayLatency() {
289
+ onRelayAnswered(detail) {
290
+ if (!detail?.name || this.answeredRelays.has(detail.name))
291
+ return;
292
+ this.answeredRelays.set(detail.name, detail.rttMs);
293
+ if (this.relayLatencyOpened) {
294
+ void this.announceRelayLatency();
295
+ }
296
+ }
297
+ async announceRelayLatency(isEligible = (ep) => this.answeredRelays.has(ep.relayName)) {
283
298
  if (!this.info.relayData)
284
299
  return;
285
300
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
286
301
  const callId = this.info.callId;
287
302
  const callCreator = this.info.callCreator;
288
303
  const destinationJids = this.info.relayData.participantJids || [];
289
- const seenRelayNames = new Set();
290
304
  for (const ep of this.info.relayData.endpoints) {
291
305
  const name = ep.relayName || '';
292
- if (!name || seenRelayNames.has(name))
306
+ if (!name || ep.ip.includes(':') || this.announcedRelayNames.has(name) || !isEligible(ep))
293
307
  continue;
294
- seenRelayNames.add(name);
308
+ this.announcedRelayNames.add(name);
295
309
  try {
296
310
  const relayData = [
297
311
  {
298
312
  relayName: name,
299
- latency: ep.c2rRtt || 0,
313
+ latency: ep.c2rRtt ?? this.answeredRelays.get(name) ?? 0,
300
314
  addressBytes: ep.addressBytes
301
315
  }
302
316
  ];
@@ -304,13 +318,23 @@ export class WaCallMediaSession {
304
318
  await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
305
319
  }
306
320
  catch (err) {
307
- this.logger.error('error sending incoming relaylatency', {
321
+ this.announcedRelayNames.delete(name);
322
+ this.logger.error('error sending relaylatency', {
308
323
  relayName: name,
309
324
  message: toError(err).message
310
325
  });
311
326
  }
312
327
  }
313
328
  }
329
+ async sendIncomingRelayLatency() {
330
+ if (!this.info.relayData)
331
+ return;
332
+ this.relayLatencyOpened = true;
333
+ const dialed = new Set(this.selectRelayEndpoints(this.info.relayData.endpoints)
334
+ .slice(0, this.sctpRelay.maxActiveRelays)
335
+ .map((ep) => ep.relayName));
336
+ await this.announceRelayLatency((ep) => dialed.size === 0 || dialed.has(ep.relayName) || this.answeredRelays.has(ep.relayName));
337
+ }
314
338
  async handleCallAccept(node, peerJid) {
315
339
  const nodeInfo = extractNodeInfo(node);
316
340
  if (!nodeInfo)
@@ -459,31 +483,8 @@ export class WaCallMediaSession {
459
483
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
460
484
  const callId = this.info.callId;
461
485
  const callCreator = this.info.callCreator;
462
- const destinationJids = this.info.relayData.participantJids || [];
463
- const seenRelayNames = new Set();
464
- for (const ep of this.info.relayData.endpoints) {
465
- const name = ep.relayName || '';
466
- if (!name || seenRelayNames.has(name))
467
- continue;
468
- seenRelayNames.add(name);
469
- try {
470
- const relayData = [
471
- {
472
- relayName: name,
473
- latency: ep.c2rRtt || 0,
474
- addressBytes: ep.addressBytes
475
- }
476
- ];
477
- const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
478
- await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
479
- }
480
- catch (err) {
481
- this.logger.error('error sending relaylatency', {
482
- relayName: name,
483
- message: toError(err).message
484
- });
485
- }
486
- }
486
+ this.relayLatencyOpened = true;
487
+ await this.announceRelayLatency();
487
488
  if (!this.initialTransportSent) {
488
489
  try {
489
490
  const basePeerJid = toUserJid(peerJid);
@@ -1062,9 +1063,12 @@ export class WaCallMediaSession {
1062
1063
  }
1063
1064
  cleanup() {
1064
1065
  this.audioEngine.setOnAudioFinished(null);
1065
- this.audioEngine.stop();
1066
+ this.audioEngine.release();
1066
1067
  this.videoEngine.stop();
1067
1068
  this.sctpRelay.cleanup();
1069
+ this.answeredRelays.clear();
1070
+ this.announcedRelayNames.clear();
1071
+ this.relayLatencyOpened = false;
1068
1072
  if (this.rtcpTimer) {
1069
1073
  clearInterval(this.rtcpTimer);
1070
1074
  this.rtcpTimer = null;
@@ -1355,11 +1359,11 @@ export class WaCallMediaSession {
1355
1359
  this.srtpErrorCount++;
1356
1360
  }
1357
1361
  }
1358
- async connectRelays(endpoints) {
1362
+ selectRelayEndpoints(endpoints) {
1359
1363
  const seen = new Set();
1360
1364
  const uniqueEndpoints = [];
1361
1365
  for (const ep of endpoints) {
1362
- if ((ep.protocol ?? 0) !== 0)
1366
+ if ((ep.protocol ?? 0) !== 0 || ep.ip.includes(':'))
1363
1367
  continue;
1364
1368
  const key = `${ep.ip}:${ep.port}`;
1365
1369
  if (!seen.has(key)) {
@@ -1381,30 +1385,40 @@ export class WaCallMediaSession {
1381
1385
  usable[0] ??
1382
1386
  null;
1383
1387
  }
1384
- const WA_RELAY_PORT = 3478;
1385
- const relays = chosen
1386
- ? [
1387
- {
1388
- ip: chosen.ip,
1389
- port: WA_RELAY_PORT,
1390
- token: chosen.token,
1391
- authToken: chosen.authToken,
1392
- rawAuthToken: chosen.rawAuthToken,
1393
- rawToken: chosen.rawToken,
1394
- key: chosen.key,
1395
- relayId: chosen.relayId,
1396
- name: chosen.relayName || `${chosen.ip}:${WA_RELAY_PORT}`,
1397
- authTokenId: chosen.authTokenId,
1398
- isFna: chosen.isFna
1399
- }
1400
- ]
1401
- : [];
1388
+ const ordered = chosen ? [chosen] : [];
1389
+ const orderedAddresses = new Set(chosen ? [chosen.ip] : []);
1390
+ for (const ep of usable) {
1391
+ if (ordered.length >= 4)
1392
+ break;
1393
+ if (orderedAddresses.has(ep.ip))
1394
+ continue;
1395
+ orderedAddresses.add(ep.ip);
1396
+ ordered.push(ep);
1397
+ }
1398
+ return ordered;
1399
+ }
1400
+ async connectRelays(endpoints) {
1401
+ const ordered = this.selectRelayEndpoints(endpoints);
1402
+ const relays = ordered.map((ep) => ({
1403
+ ip: ep.ip,
1404
+ port: ep.port || 3478,
1405
+ token: ep.token,
1406
+ authToken: ep.authToken,
1407
+ rawAuthToken: ep.rawAuthToken,
1408
+ rawToken: ep.rawToken,
1409
+ key: ep.key,
1410
+ relayId: ep.relayId,
1411
+ name: ep.relayName || `${ep.ip}:${ep.port || 3478}`,
1412
+ authTokenId: ep.authTokenId,
1413
+ isFna: ep.isFna
1414
+ }));
1402
1415
  if (relays.length === 0) {
1403
1416
  this.logger.error('no relay configs', { callId: this.info.callId });
1404
1417
  return;
1405
1418
  }
1406
1419
  this.sctpRelay.setParticipantIds(this.info.relayData?.selfPid, this.info.relayData?.peerPid);
1407
1420
  this.sctpRelay.setSsrc(this.selfSsrc);
1421
+ this.sctpRelay.setStreamSsrcs(this.selfSsrcJid ? deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid) : null);
1408
1422
  if (this.info.mediaType === CallMediaType.Video) {
1409
1423
  this.sctpRelay.setVideoSsrc(this.videoSsrc);
1410
1424
  }
@@ -1429,3 +1443,857 @@ export class WaCallMediaSession {
1429
1443
  this.videoEngine.start();
1430
1444
  }
1431
1445
  }
1446
+
1447
+ export async function resolveUserLid(deps, jid) {
1448
+ const raw = String(jid ?? '').trim();
1449
+ if (!raw) {
1450
+ throw new Error('participant is required');
1451
+ }
1452
+ const normalized = raw.includes('@') ? raw : `${raw.replace(/\D/g, '')}@s.whatsapp.net`;
1453
+ if (normalized.endsWith('@lid')) {
1454
+ return normalized;
1455
+ }
1456
+ const [mapped] = await deps.signalDeviceSync.queryLidsByPhoneJids([normalized]);
1457
+ if (!mapped?.lidJid?.endsWith('@lid')) {
1458
+ throw new Error(`no LID mapping found for ${normalized}`);
1459
+ }
1460
+ return mapped.lidJid;
1461
+ }
1462
+ export async function listUserDevices(deps, lid) {
1463
+ const devices = await deps.signalDeviceSync.getDevices([lid]);
1464
+ return [...new Set(devices.filter(Boolean))];
1465
+ }
1466
+ export function stripDevice(jid) {
1467
+ return String(jid).replace(/:\d+@/, '@');
1468
+ }
1469
+ function unwrapGroupForwarding(data) {
1470
+ if (data.length === 0 || data[0] !== 0x09) {
1471
+ return data;
1472
+ }
1473
+ const headerBytes = { 2: 8, 4: 12, 7: 18 }[data[1]];
1474
+ if (!headerBytes || data.length < headerBytes + 12 || data[headerBytes] >> 6 !== 2) {
1475
+ return null;
1476
+ }
1477
+ return data.subarray(headerBytes);
1478
+ }
1479
+ function joinFloats(left, right) {
1480
+ const merged = new Float32Array(left.length + right.length);
1481
+ merged.set(left, 0);
1482
+ merged.set(right, left.length);
1483
+ return merged;
1484
+ }
1485
+ export class GroupAudioMixer {
1486
+ chunkSamples = 160;
1487
+ frameSamples = 960;
1488
+ streams = new Map();
1489
+ allowed = new Set();
1490
+ rosterApplied = false;
1491
+ framePending = new Float32Array(0);
1492
+ add(participantId, pcm) {
1493
+ if (!participantId || pcm.length === 0) {
1494
+ return false;
1495
+ }
1496
+ if (this.rosterApplied && !this.allowed.has(participantId)) {
1497
+ return false;
1498
+ }
1499
+ let queue = this.streams.get(participantId);
1500
+ if (!queue) {
1501
+ queue = { pending: new Float32Array(0), started: false };
1502
+ this.streams.set(participantId, queue);
1503
+ }
1504
+ const maxSamples = this.frameSamples * 4;
1505
+ if (pcm.length >= maxSamples) {
1506
+ queue.pending = pcm.slice(pcm.length - maxSamples);
1507
+ return true;
1508
+ }
1509
+ const merged = joinFloats(queue.pending, pcm);
1510
+ queue.pending = merged.length > maxSamples ? merged.slice(merged.length - maxSamples) : merged;
1511
+ return true;
1512
+ }
1513
+ retain(participantIds) {
1514
+ this.allowed = new Set(participantIds.filter(Boolean));
1515
+ this.rosterApplied = true;
1516
+ for (const participantId of [...this.streams.keys()]) {
1517
+ if (!this.allowed.has(participantId)) {
1518
+ this.streams.delete(participantId);
1519
+ }
1520
+ }
1521
+ }
1522
+ mixChunk() {
1523
+ const mixed = new Float32Array(this.chunkSamples);
1524
+ let contributed = false;
1525
+ for (const participantId of [...this.streams.keys()].sort()) {
1526
+ const queue = this.streams.get(participantId);
1527
+ if (!queue.started) {
1528
+ if (queue.pending.length < this.frameSamples * 2) {
1529
+ continue;
1530
+ }
1531
+ queue.started = true;
1532
+ }
1533
+ if (queue.pending.length < this.chunkSamples) {
1534
+ queue.started = false;
1535
+ continue;
1536
+ }
1537
+ for (let i = 0; i < mixed.length; i++) {
1538
+ mixed[i] += queue.pending[i];
1539
+ }
1540
+ queue.pending = queue.pending.subarray(this.chunkSamples);
1541
+ contributed = true;
1542
+ }
1543
+ if (!contributed) {
1544
+ return null;
1545
+ }
1546
+ for (let i = 0; i < mixed.length; i++) {
1547
+ mixed[i] = Math.max(-1, Math.min(1, mixed[i]));
1548
+ }
1549
+ return mixed;
1550
+ }
1551
+ pushChunk(chunk) {
1552
+ this.framePending = joinFloats(this.framePending, chunk);
1553
+ if (this.framePending.length < this.frameSamples) {
1554
+ return null;
1555
+ }
1556
+ const frame = this.framePending.slice(0, this.frameSamples);
1557
+ this.framePending = this.framePending.slice(this.frameSamples);
1558
+ return frame;
1559
+ }
1560
+ reset() {
1561
+ this.streams.clear();
1562
+ this.allowed.clear();
1563
+ this.rosterApplied = false;
1564
+ this.framePending = new Float32Array(0);
1565
+ }
1566
+ }
1567
+ class GroupReceiver {
1568
+ audioCtx = null;
1569
+ videoCtx = null;
1570
+ appDataCtx = null;
1571
+ codec = null;
1572
+ closed = false;
1573
+ constructor(callId, participantId, deviceJid, pid, logger) {
1574
+ this.participantId = participantId;
1575
+ this.deviceJid = deviceJid;
1576
+ this.pid = pid;
1577
+ this.audioSsrc = generateSecureSsrc(callId, participantId, 0);
1578
+ this.videoSsrc = generateSecureSsrc(callId, participantId, 2);
1579
+ this.appDataSsrc = generateSecureSsrc(callId, participantId, 6);
1580
+ this.assembler = new H264AccessUnitAssembler();
1581
+ MLowCodec.create({ logger, fec: false, decodeOnly: true })
1582
+ .then((codec) => {
1583
+ if (this.closed) {
1584
+ codec.destroy();
1585
+ return;
1586
+ }
1587
+ this.codec = codec;
1588
+ })
1589
+ .catch(() => { });
1590
+ }
1591
+ install(rawKey, tagLength) {
1592
+ const keying = derivePerJidSrtpKey(rawKey, this.participantId);
1593
+ if (this.audioCtx) {
1594
+ this.audioCtx.rekey(keying);
1595
+ this.videoCtx.rekey(keying);
1596
+ this.appDataCtx.rekey(keying);
1597
+ return;
1598
+ }
1599
+ this.audioCtx = new SrtpContext(keying, tagLength);
1600
+ this.videoCtx = new SrtpContext(keying, tagLength);
1601
+ this.appDataCtx = new SrtpContext(keying, tagLength);
1602
+ }
1603
+ close() {
1604
+ this.closed = true;
1605
+ this.codec?.destroy();
1606
+ this.codec = null;
1607
+ }
1608
+ }
1609
+ export class WaGroupCallSession extends WaCallMediaSession {
1610
+ roster = null;
1611
+ rosterTransactionId = null;
1612
+ epoch = null;
1613
+ pendingEpochs = new Map();
1614
+ receivers = new Map();
1615
+ audioBySsrc = new Map();
1616
+ videoBySsrc = new Map();
1617
+ appDataBySsrc = new Map();
1618
+ selfParticipantId = '';
1619
+ selfPid = 0;
1620
+ warpTagLength = 4;
1621
+ groupEndpoints = [];
1622
+ relayConfigured = false;
1623
+ subscribedPids = '';
1624
+ offerStanzaId = null;
1625
+ inviteSnapshot = null;
1626
+ mixer = new GroupAudioMixer();
1627
+ mixTimer = null;
1628
+ heartbeatTimer = null;
1629
+ constructor(options) {
1630
+ super({ ...options, maxActiveRelays: 1 });
1631
+ this.info.peerJid = callJidFor(this.info.callId);
1632
+ this.acceptedByJid = this.info.peerJid;
1633
+ this.sctpRelay.setAllocateBuilder((relayInfo, candidate, transactionId) => this.buildGroupAllocate(relayInfo, candidate, transactionId));
1634
+ }
1635
+ get callJid() {
1636
+ return callJidFor(this.info.callId);
1637
+ }
1638
+ async initMedia(selfLid) {
1639
+ const selfId = formatParticipantId(selfLid);
1640
+ this.selfParticipantId = selfId;
1641
+ this.selfSsrcJid = selfId;
1642
+ this.selfSsrc = generateSecureSsrc(this.info.callId, selfId, 0);
1643
+ this.rtpSession = RtpSession.whatsappOpus(this.selfSsrc);
1644
+ this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }), fec: true, encodeOnly: true });
1645
+ this.videoSsrc = generateSecureSsrc(this.info.callId, selfId, 2);
1646
+ if (this.info.mediaType === CallMediaType.Video) {
1647
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
1648
+ this.videoAssembler = new H264AccessUnitAssembler();
1649
+ }
1650
+ }
1651
+ async sendIncomingPreaccept() {
1652
+ await this.deps.lowLevelCoordinator.sendNode(buildGroupPreacceptStanza(this.info.callId, this.info.callCreator, this.info.mediaType === CallMediaType.Video));
1653
+ }
1654
+ async sendIncomingRelayLatency() { }
1655
+ async acceptCall() {
1656
+ if (!this.info.canAccept) {
1657
+ throw new Error(`Call ${this.info.callId} cannot be accepted in state ${this.info.stateData.state}`);
1658
+ }
1659
+ this.info.applyTransition({ type: 'local_accepted' });
1660
+ this.delegate.emitState(this.info);
1661
+ await this.deps.lowLevelCoordinator.sendNode(buildGroupAcceptStanza(this.info.callId, this.info.callCreator));
1662
+ await this.maybeStartMedia();
1663
+ }
1664
+ async rejectCall(reason = EndCallReason.Declined) {
1665
+ this.info.applyTransition({ type: 'local_rejected', reason });
1666
+ this.delegate.emitState(this.info);
1667
+ try {
1668
+ await this.deps.lowLevelCoordinator.sendNode({
1669
+ tag: 'call',
1670
+ attrs: { to: this.callJid, id: generateCallStanzaId() },
1671
+ content: [{ tag: 'reject', attrs: { 'call-id': this.info.callId, 'call-creator': this.info.callCreator } }]
1672
+ });
1673
+ }
1674
+ catch (err) {
1675
+ this.logger.warn('reject send failed', { message: toError(err).message });
1676
+ }
1677
+ this.cleanup();
1678
+ }
1679
+ async endCall(reason = EndCallReason.UserEnded) {
1680
+ if (this.info.isEnded) {
1681
+ return;
1682
+ }
1683
+ this.info.applyTransition({ type: 'terminated', reason });
1684
+ this.delegate.emitEnded(this.info);
1685
+ this.delegate.emitState(this.info);
1686
+ try {
1687
+ await this.deps.lowLevelCoordinator.sendNode(buildGroupTerminateStanza(this.info.callId, this.info.callCreator));
1688
+ }
1689
+ catch (err) {
1690
+ this.logger.warn('terminate send failed', { message: toError(err).message });
1691
+ }
1692
+ await new Promise((resolve) => setTimeout(resolve, 400));
1693
+ this.cleanup();
1694
+ }
1695
+ handleCallTerminate(node) {
1696
+ const participant = node?.attrs?.participant;
1697
+ if (participant && toUserJid(participant) !== toUserJid(this.info.callCreator)) {
1698
+ return false;
1699
+ }
1700
+ return super.handleCallTerminate();
1701
+ }
1702
+ async handleCallAccept() {
1703
+ if (this.info.stateData.state === CallState.Ringing) {
1704
+ try {
1705
+ this.info.applyTransition({ type: 'remote_accepted' });
1706
+ this.delegate.emitState(this.info);
1707
+ }
1708
+ catch { }
1709
+ }
1710
+ await this.maybeStartMedia();
1711
+ }
1712
+ async handleCallPreaccept() { }
1713
+ async handleCallTransport() { }
1714
+ async handleCallRelaylatency() { }
1715
+ handleRelayElection() { }
1716
+ handleCallUserAction(node) {
1717
+ this.applyPeerRaiseHand(node, node.attrs?.participant || node.attrs?.from);
1718
+ }
1719
+ handleCallRaiseHand(node) {
1720
+ this.applyPeerRaiseHand(node, node.attrs?.participant || node.attrs?.from);
1721
+ }
1722
+ async handleCallAck(node) {
1723
+ if (node.attrs?.type && node.attrs.type !== 'offer') {
1724
+ return;
1725
+ }
1726
+ if (node.attrs?.error) {
1727
+ this.logger.warn('group offer rejected', { error: node.attrs.error });
1728
+ await this.endCall(EndCallReason.Failed);
1729
+ return;
1730
+ }
1731
+ let update;
1732
+ try {
1733
+ update = parseInitialGroupAck(node);
1734
+ }
1735
+ catch (err) {
1736
+ this.logger.warn('group offer ack parse failed', { message: toError(err).message });
1737
+ return;
1738
+ }
1739
+ if (update) {
1740
+ await this.processGroupSnapshot(update);
1741
+ }
1742
+ }
1743
+ async handleGroupUpdate(node) {
1744
+ let update;
1745
+ try {
1746
+ update = parseGroupUpdate(getFirstNodeChild(node));
1747
+ }
1748
+ catch (err) {
1749
+ this.logger.warn('group update parse failed', { message: toError(err).message });
1750
+ return;
1751
+ }
1752
+ await this.processGroupSnapshot(update);
1753
+ }
1754
+ async handleGroupEncRekey(node) {
1755
+ const inner = getFirstNodeChild(node);
1756
+ let rekey;
1757
+ try {
1758
+ rekey = parseGroupEncRekey(inner);
1759
+ }
1760
+ catch (err) {
1761
+ this.logger.warn('group rekey parse failed', { message: toError(err).message });
1762
+ return;
1763
+ }
1764
+ const rawKey = await decryptCallKey(this.deps, inner, node.attrs?.participant || node.attrs?.from, this.logger);
1765
+ if (!rawKey) {
1766
+ this.logger.warn('group rekey could not be decrypted', { transactionId: rekey.transactionId });
1767
+ return;
1768
+ }
1769
+ if (this.applyEpoch(rekey.transactionId, rawKey)) {
1770
+ this.refreshRelayAllocation();
1771
+ await this.maybeStartMedia();
1772
+ }
1773
+ }
1774
+ handleWaitingRoomUpdate(node) {
1775
+ let room;
1776
+ try {
1777
+ room = parseWaitingRoomUpdate(getFirstNodeChild(node));
1778
+ }
1779
+ catch (err) {
1780
+ this.logger.warn('waiting room update parse failed', { message: toError(err).message });
1781
+ return;
1782
+ }
1783
+ this.info.waitingRoom = room;
1784
+ this.delegate.emitWaitingRoom?.(this.info, room);
1785
+ this.delegate.emitState(this.info);
1786
+ }
1787
+ async beginLinkJoin(result) {
1788
+ if (result.waitingRoom) {
1789
+ this.info.waitingRoom = result.waitingRoom;
1790
+ }
1791
+ if (result.group) {
1792
+ this.info.applyTransition({ type: 'group_joined' });
1793
+ this.delegate.emitState(this.info);
1794
+ await this.processGroupSnapshot(result.group);
1795
+ return;
1796
+ }
1797
+ this.info.applyTransition({ type: 'waiting_room_entered' });
1798
+ this.delegate.emitState(this.info);
1799
+ this.delegate.emitWaitingRoom?.(this.info, this.info.waitingRoom);
1800
+ this.startWaitingHeartbeat();
1801
+ }
1802
+ startWaitingHeartbeat() {
1803
+ this.stopWaitingHeartbeat();
1804
+ this.heartbeatTimer = setInterval(() => {
1805
+ if (this.info.stateData.state !== CallState.WaitingRoom) {
1806
+ this.stopWaitingHeartbeat();
1807
+ return;
1808
+ }
1809
+ this.sendWaitingRoomRequest('heartbeat', { type: 'waiting_room' }).catch(() => { });
1810
+ }, 10000);
1811
+ this.heartbeatTimer.unref?.();
1812
+ }
1813
+ stopWaitingHeartbeat() {
1814
+ if (this.heartbeatTimer) {
1815
+ clearInterval(this.heartbeatTimer);
1816
+ this.heartbeatTimer = null;
1817
+ }
1818
+ }
1819
+ async sendWaitingRoomRequest(tag, attrs, children) {
1820
+ await this.deps.lowLevelCoordinator.sendNode(buildWaitingRoomRequestStanza(tag, this.info.callId, this.info.callCreator, generateCallStanzaId(), attrs, children));
1821
+ }
1822
+ async setApprovalRequired(enabled) {
1823
+ await this.sendWaitingRoomRequest('waiting_room_toggle', { enabled: enabled ? '1' : '0' });
1824
+ }
1825
+ async admitParticipant(jid) {
1826
+ const lid = await resolveUserLid(this.deps, jid);
1827
+ await this.sendWaitingRoomRequest('waiting_room_admit', {}, [{ tag: 'user', attrs: { jid: lid } }]);
1828
+ }
1829
+ async denyParticipant(jid) {
1830
+ const lid = await resolveUserLid(this.deps, jid);
1831
+ await this.sendWaitingRoomRequest('waiting_room_deny', {}, [{ tag: 'user', attrs: { jid: lid } }]);
1832
+ }
1833
+ async addParticipant(target) {
1834
+ await this.inviteParticipant(target, false);
1835
+ }
1836
+ async ringParticipant(target) {
1837
+ await this.inviteParticipant(target, true);
1838
+ }
1839
+ async inviteParticipant(target, ring) {
1840
+ if (!this.roster) {
1841
+ throw new Error('the call roster is not available yet');
1842
+ }
1843
+ const lid = stripDevice(await resolveUserLid(this.deps, target));
1844
+ if (lid === stripDevice(this.selfParticipantId)) {
1845
+ throw new Error('this account is already in its own call');
1846
+ }
1847
+ const entry = this.roster.participants.find((participant) => stripDevice(participant.jid) === lid);
1848
+ if (ring && !entry) {
1849
+ throw new Error('participant is not in the call roster');
1850
+ }
1851
+ if (ring && entry.state === 'connected') {
1852
+ throw new Error('participant is already connected');
1853
+ }
1854
+ if (!ring && entry) {
1855
+ throw new Error('participant is already in the call roster');
1856
+ }
1857
+ const participants = ring ? this.roster.participants.filter((participant) => participant.state === 'connected') : this.roster.participants;
1858
+ if (participants.length === 0) {
1859
+ throw new Error('the call has no connected participants');
1860
+ }
1861
+ const targetDevices = await listUserDevices(this.deps, lid);
1862
+ if (targetDevices.length === 0) {
1863
+ throw new Error(`no reachable devices for ${lid}`);
1864
+ }
1865
+ const stanza = buildGroupInviteOfferStanza({
1866
+ callId: this.info.callId,
1867
+ to: lid,
1868
+ creator: this.info.callCreator,
1869
+ targetDevices,
1870
+ participants,
1871
+ video: this.info.mediaType === CallMediaType.Video
1872
+ });
1873
+ stanza.attrs.id = generateCallStanzaId();
1874
+ await this.deps.lowLevelCoordinator.sendNode(stanza);
1875
+ }
1876
+ getParticipants() {
1877
+ return this.info.groupState?.participants ?? [];
1878
+ }
1879
+ applyGroupUpdate(update) {
1880
+ if (this.rosterTransactionId !== null && update.transactionId <= this.rosterTransactionId) {
1881
+ return false;
1882
+ }
1883
+ const next = new Map();
1884
+ let selfPid = this.selfPid;
1885
+ for (const participant of update.participants) {
1886
+ if (participant.state !== 'connected') {
1887
+ continue;
1888
+ }
1889
+ for (const device of participant.devices) {
1890
+ if (!device.jid || device.pid === undefined) {
1891
+ continue;
1892
+ }
1893
+ const participantId = formatParticipantId(device.jid);
1894
+ if (participantId === this.selfParticipantId) {
1895
+ selfPid = device.pid;
1896
+ continue;
1897
+ }
1898
+ const receiver = this.receivers.get(participantId) ?? new GroupReceiver(this.info.callId, participantId, device.jid, device.pid, this.logger.child({ component: 'mlow' }));
1899
+ receiver.pid = device.pid;
1900
+ next.set(participantId, receiver);
1901
+ }
1902
+ }
1903
+ for (const [participantId, receiver] of this.receivers) {
1904
+ if (!next.has(participantId)) {
1905
+ receiver.close();
1906
+ }
1907
+ }
1908
+ this.receivers = next;
1909
+ this.selfPid = selfPid;
1910
+ this.audioBySsrc = new Map([...next.values()].map((receiver) => [receiver.audioSsrc, receiver]));
1911
+ this.videoBySsrc = new Map([...next.values()].map((receiver) => [receiver.videoSsrc, receiver]));
1912
+ this.appDataBySsrc = new Map([...next.values()].map((receiver) => [receiver.appDataSsrc, receiver]));
1913
+ this.roster = update;
1914
+ this.rosterTransactionId = update.transactionId;
1915
+ this.mixer.retain([...next.keys()]);
1916
+ const ready = [...this.pendingEpochs.keys()].filter((transactionId) => transactionId <= update.transactionId).sort((a, b) => b - a);
1917
+ if (ready.length > 0) {
1918
+ const newest = ready[0];
1919
+ const rawKey = this.pendingEpochs.get(newest);
1920
+ for (const transactionId of this.pendingEpochs.keys()) {
1921
+ if (transactionId <= newest) {
1922
+ this.pendingEpochs.delete(transactionId);
1923
+ }
1924
+ }
1925
+ if (!this.epoch || newest > this.epoch.transactionId) {
1926
+ this.installEpoch(newest, rawKey);
1927
+ }
1928
+ }
1929
+ if (this.epoch) {
1930
+ for (const receiver of next.values()) {
1931
+ receiver.install(this.epoch.rawKey, this.warpTagLength);
1932
+ }
1933
+ }
1934
+ return true;
1935
+ }
1936
+ applyEpoch(transactionId, rawKey) {
1937
+ if (this.rosterTransactionId === null || transactionId > this.rosterTransactionId) {
1938
+ this.pendingEpochs.set(transactionId, rawKey);
1939
+ while (this.pendingEpochs.size > 8) {
1940
+ this.pendingEpochs.delete(Math.min(...this.pendingEpochs.keys()));
1941
+ }
1942
+ return false;
1943
+ }
1944
+ if (this.epoch && transactionId <= this.epoch.transactionId) {
1945
+ return false;
1946
+ }
1947
+ this.installEpoch(transactionId, rawKey);
1948
+ return true;
1949
+ }
1950
+ installEpoch(transactionId, rawKey) {
1951
+ this.epoch = { transactionId, rawKey };
1952
+ this.info.encryptionKey = rawKey;
1953
+ const keying = derivePerJidSrtpKey(rawKey, this.selfParticipantId);
1954
+ if (this.srtpSession) {
1955
+ this.srtpSession.rekey(keying);
1956
+ this.appDataSrtpSession.rekey(keying);
1957
+ this.audioRtcpSession.rekey(keying);
1958
+ this.videoSrtpSession?.rekey(keying);
1959
+ this.videoRtcpSession?.rekey(keying);
1960
+ }
1961
+ else {
1962
+ this.srtpSession = new SrtpContext(keying, this.warpTagLength);
1963
+ this.appDataSrtpSession = new SrtpContext(keying, this.warpTagLength);
1964
+ this.audioRtcpSession = new SrtcpSendContext(keying);
1965
+ this.openAppDataStream(this.selfParticipantId);
1966
+ this.startRtcpSenderReports();
1967
+ }
1968
+ if (this.videoRtpStream && !this.videoSrtpSession) {
1969
+ this.videoSrtpSession = new SrtpContext(keying, this.warpTagLength);
1970
+ this.videoRtcpSession = new SrtcpSendContext(keying);
1971
+ }
1972
+ for (const receiver of this.receivers.values()) {
1973
+ receiver.install(rawKey, this.warpTagLength);
1974
+ }
1975
+ }
1976
+ async distributeEpoch(update) {
1977
+ const rawKey = generateCallKey();
1978
+ const targets = [...this.receivers.values()].map((receiver) => receiver.deviceJid);
1979
+ if (targets.length > 0) {
1980
+ try {
1981
+ await this.deps.sessionResolver.ensureSessionsBatch(targets);
1982
+ }
1983
+ catch (err) {
1984
+ this.logger.warn('group rekey session setup failed', { message: toError(err).message });
1985
+ }
1986
+ for (const result of await Promise.allSettled(targets.map(async (jid) => {
1987
+ const { type, ciphertext } = await this.deps.signalProtocol.encryptMessage(parseSignalAddressFromJid(jid), await encodeWAMessage({ call: { callKey: rawKey } }));
1988
+ await this.deps.lowLevelCoordinator.sendNode(buildGroupEncRekeyStanza({
1989
+ callId: this.info.callId,
1990
+ to: jid,
1991
+ creator: this.info.callCreator,
1992
+ transactionId: update.transactionId,
1993
+ encType: type,
1994
+ ciphertext
1995
+ }));
1996
+ }))) {
1997
+ if (result.status === 'rejected') {
1998
+ this.logger.warn('group rekey delivery failed', { message: toError(result.reason).message });
1999
+ }
2000
+ }
2001
+ }
2002
+ this.applyEpoch(update.transactionId, rawKey);
2003
+ }
2004
+ async processGroupSnapshot(update) {
2005
+ if (this.info.isEnded || !this.applyGroupUpdate(update)) {
2006
+ return;
2007
+ }
2008
+ if (update.relay) {
2009
+ this.applyGroupRelay(update.relay);
2010
+ }
2011
+ this.info.groupState = {
2012
+ transactionId: update.transactionId,
2013
+ media: update.media,
2014
+ groupJid: update.groupJid,
2015
+ joinable: update.joinable,
2016
+ connectedLimit: update.connectedLimit,
2017
+ participants: update.participants.map((participant) => ({
2018
+ jid: participant.jid,
2019
+ pn: participant.pn,
2020
+ state: participant.state,
2021
+ type: participant.type,
2022
+ isSelf: stripDevice(participant.jid) === stripDevice(this.selfParticipantId),
2023
+ devices: participant.devices.map((device) => ({ jid: device.jid, pid: device.pid, platform: device.platform }))
2024
+ }))
2025
+ };
2026
+ this.advanceJoinState();
2027
+ this.delegate.emitGroupState?.(this.info, this.info.groupState);
2028
+ this.delegate.emitState(this.info);
2029
+ if (update.rekeyRequested) {
2030
+ await this.distributeEpoch(update);
2031
+ }
2032
+ else if (!this.epoch && this.info.linkToken && this.receivers.size === 0 && this.groupEndpoints.length > 0) {
2033
+ this.applyEpoch(update.transactionId, generateCallKey());
2034
+ }
2035
+ this.refreshRelayAllocation(!!update.relay);
2036
+ await this.maybeStartMedia();
2037
+ }
2038
+ advanceJoinState() {
2039
+ const state = this.info.stateData.state;
2040
+ try {
2041
+ if (state === CallState.WaitingRoom) {
2042
+ this.stopWaitingHeartbeat();
2043
+ this.info.applyTransition({ type: 'group_joined' });
2044
+ }
2045
+ else if (state === CallState.Ringing && this.receivers.size > 0) {
2046
+ this.info.applyTransition({ type: 'remote_accepted' });
2047
+ }
2048
+ }
2049
+ catch { }
2050
+ }
2051
+ applyGroupRelay(relay) {
2052
+ if (relay.selfPid !== undefined) {
2053
+ this.selfPid = relay.selfPid;
2054
+ }
2055
+ if (relay.warpMiTagLength) {
2056
+ this.warpTagLength = relay.warpMiTagLength;
2057
+ }
2058
+ const { relays } = parseRelayFromAck({ content: [relay.node] });
2059
+ if (relays.length > 0) {
2060
+ this.groupEndpoints = relays;
2061
+ }
2062
+ }
2063
+ currentPids() {
2064
+ return [...new Set([...this.receivers.values()].map((receiver) => receiver.pid))].sort((a, b) => a - b);
2065
+ }
2066
+ buildGroupAllocate(relayInfo, candidate, transactionId) {
2067
+ return buildGroupAllocateForRelay(relayInfo.rawToken, {
2068
+ streamSsrcs: deriveWasmRelayStreamSsrcs(this.info.callId, this.selfParticipantId),
2069
+ appDataSsrc: generateSecureSsrc(this.info.callId, this.selfParticipantId, 6),
2070
+ hbhFecSsrcs: [generateSecureSsrc(this.info.callId, this.selfParticipantId, 7), generateSecureSsrc(this.info.callId, this.selfParticipantId, 8)],
2071
+ pids: this.currentPids()
2072
+ }, TEXT_ENCODER.encode(relayInfo.key), candidate.ip, candidate.port, transactionId, { relayedAddress: candidate.form });
2073
+ }
2074
+ refreshRelayAllocation(credentialsChanged = false) {
2075
+ if (!this.relayConfigured || this.groupEndpoints.length === 0) {
2076
+ return;
2077
+ }
2078
+ const pids = this.currentPids().join(',');
2079
+ if (pids === this.subscribedPids && !credentialsChanged) {
2080
+ return;
2081
+ }
2082
+ this.subscribedPids = pids;
2083
+ this.connectRelays(this.groupEndpoints).catch(() => { });
2084
+ }
2085
+ async maybeStartMedia() {
2086
+ const state = this.info.stateData.state;
2087
+ if (this.relayConfigured || !this.epoch || this.groupEndpoints.length === 0) {
2088
+ return;
2089
+ }
2090
+ if (state !== CallState.Connecting && state !== CallState.Active) {
2091
+ return;
2092
+ }
2093
+ this.subscribedPids = this.currentPids().join(',');
2094
+ await this.connectRelays(this.groupEndpoints);
2095
+ }
2096
+ async connectRelays(endpoints) {
2097
+ const relays = this.selectRelayEndpoints(endpoints).map((ep) => ({
2098
+ ip: ep.ip,
2099
+ port: ep.port || 3478,
2100
+ token: ep.token,
2101
+ authToken: ep.authToken,
2102
+ rawAuthToken: ep.rawAuthToken,
2103
+ rawToken: ep.rawToken,
2104
+ key: ep.key,
2105
+ relayId: ep.relayId,
2106
+ name: ep.relayName || `${ep.ip}:${ep.port || 3478}`,
2107
+ authTokenId: ep.authTokenId,
2108
+ isFna: ep.isFna
2109
+ }));
2110
+ if (relays.length === 0) {
2111
+ this.logger.error('no usable group relay endpoints', { callId: this.info.callId });
2112
+ return;
2113
+ }
2114
+ this.sctpRelay.setParticipantIds(this.selfPid, 0);
2115
+ this.sctpRelay.setSsrc(this.selfSsrc);
2116
+ this.sctpRelay.setStreamSsrcs(deriveWasmRelayStreamSsrcs(this.info.callId, this.selfParticipantId));
2117
+ this.sctpRelay.setSubscriptionSsrc(0);
2118
+ if (this.relayConfigured) {
2119
+ this.sctpRelay.refreshRelays(relays);
2120
+ return;
2121
+ }
2122
+ this.relayConfigured = true;
2123
+ try {
2124
+ await this.sctpRelay.configureRelays(relays);
2125
+ }
2126
+ catch (err) {
2127
+ this.logger.error('group relay error', { callId: this.info.callId, message: toError(err).message });
2128
+ }
2129
+ }
2130
+ onRelayConnected() {
2131
+ if (this.info.stateData.state === CallState.Connecting) {
2132
+ try {
2133
+ this.info.applyTransition({ type: 'media_connected' });
2134
+ this.delegate.emitState(this.info);
2135
+ }
2136
+ catch { }
2137
+ }
2138
+ if (!this.mediaFlowStarted && this.epoch && this.info.stateData.state === CallState.Active) {
2139
+ this.startMediaFlow();
2140
+ }
2141
+ }
2142
+ startMediaFlow() {
2143
+ super.startMediaFlow();
2144
+ this.startMixer();
2145
+ }
2146
+ startMixer() {
2147
+ if (this.mixTimer) {
2148
+ return;
2149
+ }
2150
+ this.mixTimer = setInterval(() => {
2151
+ if (this.receivers.size < 2) {
2152
+ return;
2153
+ }
2154
+ for (let i = 0; i < 2; i++) {
2155
+ const chunk = this.mixer.mixChunk();
2156
+ if (!chunk) {
2157
+ return;
2158
+ }
2159
+ const frame = this.mixer.pushChunk(chunk);
2160
+ if (frame) {
2161
+ this.onDecodedAudio(frame);
2162
+ }
2163
+ }
2164
+ }, 10);
2165
+ this.mixTimer.unref?.();
2166
+ }
2167
+ onRelayData(data) {
2168
+ this.relayPacketCount++;
2169
+ const packet = unwrapGroupForwarding(data);
2170
+ if (!packet) {
2171
+ return;
2172
+ }
2173
+ if (isStunPacket(packet)) {
2174
+ this.stunResponseCount++;
2175
+ return;
2176
+ }
2177
+ if (!isRtpPacket(packet) || packet.length < 12) {
2178
+ return;
2179
+ }
2180
+ const payloadType = packet[1] & 0x7f;
2181
+ if (payloadType >= 72 && payloadType <= 76) {
2182
+ return;
2183
+ }
2184
+ const ssrc = readUInt32BE(packet, 8);
2185
+ if (ssrc === this.selfSsrc) {
2186
+ this.selfEchoCount++;
2187
+ return;
2188
+ }
2189
+ const audioReceiver = this.audioBySsrc.get(ssrc);
2190
+ if (audioReceiver) {
2191
+ this.onGroupAudio(audioReceiver, packet, payloadType);
2192
+ return;
2193
+ }
2194
+ const videoReceiver = this.videoBySsrc.get(ssrc);
2195
+ if (videoReceiver) {
2196
+ this.onGroupVideo(videoReceiver, packet);
2197
+ return;
2198
+ }
2199
+ const appDataReceiver = this.appDataBySsrc.get(ssrc);
2200
+ if (appDataReceiver) {
2201
+ this.onGroupAppData(appDataReceiver, packet, payloadType, ssrc);
2202
+ }
2203
+ }
2204
+ onGroupAudio(receiver, data, payloadType) {
2205
+ if (payloadType !== 120 || !receiver.audioCtx || !receiver.codec) {
2206
+ return;
2207
+ }
2208
+ try {
2209
+ const packet = receiver.audioCtx.unprotect(data);
2210
+ this.audioRecvCount++;
2211
+ if (packet.payload.length === 0) {
2212
+ return;
2213
+ }
2214
+ receiver.codec.decodeSequenced(packet.header.sequenceNumber, packet.payload, (pcm) => this.onParticipantAudio(receiver, pcm));
2215
+ }
2216
+ catch {
2217
+ this.srtpErrorCount++;
2218
+ }
2219
+ }
2220
+ onParticipantAudio(receiver, pcm) {
2221
+ this.delegate.emitParticipantAudio?.(this.info, receiver.participantId, pcm);
2222
+ if (this.receivers.size > 1) {
2223
+ this.mixer.add(receiver.participantId, pcm);
2224
+ return;
2225
+ }
2226
+ this.onDecodedAudio(pcm);
2227
+ }
2228
+ onGroupVideo(receiver, data) {
2229
+ if (!receiver.videoCtx) {
2230
+ return;
2231
+ }
2232
+ try {
2233
+ const packet = receiver.videoCtx.unprotect(data);
2234
+ const [accessUnit, complete] = receiver.assembler.push(packet.header.sequenceNumber, packet.header.marker, packet.payload);
2235
+ if (complete && accessUnit) {
2236
+ this.delegate.emitInboundVideo?.(this.info, accessUnit, receiver.participantId);
2237
+ }
2238
+ }
2239
+ catch {
2240
+ this.srtpErrorCount++;
2241
+ }
2242
+ }
2243
+ onGroupAppData(receiver, data, payloadType, ssrc) {
2244
+ const stream = this.appDataStream;
2245
+ if (!stream || !receiver.appDataCtx) {
2246
+ return;
2247
+ }
2248
+ try {
2249
+ const packet = receiver.appDataCtx.unprotect(data);
2250
+ stream.observeInboundPayloadType(payloadType);
2251
+ for (const reaction of stream.receive(packet.payload, ssrc)) {
2252
+ this.delegate.emitCallReaction?.(this.info, { ...reaction, participantJid: receiver.deviceJid });
2253
+ }
2254
+ }
2255
+ catch { }
2256
+ }
2257
+ async enableVideoMidCall() {
2258
+ if (this.videoRtpStream && this.videoSrtpSession) {
2259
+ return;
2260
+ }
2261
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
2262
+ this.videoAssembler = new H264AccessUnitAssembler();
2263
+ if (this.epoch) {
2264
+ const keying = derivePerJidSrtpKey(this.epoch.rawKey, this.selfParticipantId);
2265
+ this.videoSrtpSession = new SrtpContext(keying, this.warpTagLength);
2266
+ this.videoRtcpSession = new SrtcpSendContext(keying);
2267
+ }
2268
+ if (!this.videoEngine.hasSource()) {
2269
+ try {
2270
+ await this.videoEngine.loadBlankSource();
2271
+ }
2272
+ catch (err) {
2273
+ this.logger.error('blank video fallback unavailable', { callId: this.info.callId, message: toError(err).message });
2274
+ }
2275
+ }
2276
+ if (this.sctpRelay.hasConnection()) {
2277
+ this.videoEngine.start();
2278
+ }
2279
+ }
2280
+ cleanup() {
2281
+ this.stopWaitingHeartbeat();
2282
+ if (this.mixTimer) {
2283
+ clearInterval(this.mixTimer);
2284
+ this.mixTimer = null;
2285
+ }
2286
+ for (const receiver of this.receivers.values()) {
2287
+ receiver.close();
2288
+ }
2289
+ this.receivers.clear();
2290
+ this.audioBySsrc.clear();
2291
+ this.videoBySsrc.clear();
2292
+ this.appDataBySsrc.clear();
2293
+ this.pendingEpochs.clear();
2294
+ this.mixer.reset();
2295
+ this.relayConfigured = false;
2296
+ super.cleanup();
2297
+ this.acceptedByJid = this.info.peerJid;
2298
+ }
2299
+ }