@hiroosy/baileys-lite 0.3.9 → 0.4.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.
- package/README.md +97 -6
- package/package.json +1 -1
- package/src/socket/messages-recv.js +4 -6
- package/src/socket/messages-send.js +6 -1
- package/src/utils/auth-state-core.js +38 -3
- package/src/utils/message-compose.js +9 -0
- package/src/utils/message-processing.js +94 -33
- package/src/voip/WaVoipCoordinator.js +57 -1
- package/src/voip/call/WaCallManager.js +265 -6
- package/src/voip/call/WaCallMediaSession.js +865 -10
- package/src/voip/call/call-state.js +45 -0
- package/src/voip/crypto/rtcp.js +6 -0
- package/src/voip/crypto/srtp.js +5 -0
- package/src/voip/crypto/ssrc.js +10 -0
- package/src/voip/index.js +213 -17
- package/src/voip/media/WaAudioEngine.js +25 -16
- package/src/voip/media/WaVideoEngine.js +11 -6
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/mlow-codec.js +12 -8
- package/src/voip/relay/WaManualRelay.js +45 -6
- package/src/voip/relay/sctp/association.js +14 -1
- package/src/voip/relay/stun.js +52 -1
- package/src/voip/signaling/bridge.js +15 -1
- package/src/voip/signaling/signaling.js +432 -1
- package/src/voip/types.js +1 -0
- package/src/voip/voip-deps.js +7 -0
- package/src/voip/voipClient.js +152 -17
|
@@ -62,12 +62,15 @@ export class WaManualRelay extends EventEmitter {
|
|
|
62
62
|
stats = { sent: 0, received: 0, connected: 0 };
|
|
63
63
|
retrySchedule = [1000, 2000, 4000];
|
|
64
64
|
transports = ['dtls', 'raw'];
|
|
65
|
+
allocateBuilder = null;
|
|
66
|
+
destroyed = false;
|
|
65
67
|
|
|
66
68
|
constructor(options = {}) {
|
|
67
69
|
super();
|
|
68
70
|
this.logger = options.logger ?? createNoopLogger();
|
|
69
71
|
this.transports = options.transports ?? this.transports;
|
|
70
72
|
this.maxActiveRelays = options.maxActiveRelays ?? this.maxActiveRelays;
|
|
73
|
+
this.allocateBuilder = options.allocateBuilder ?? null;
|
|
71
74
|
}
|
|
72
75
|
|
|
73
76
|
setSsrc(ssrc) {
|
|
@@ -95,6 +98,24 @@ export class WaManualRelay extends EventEmitter {
|
|
|
95
98
|
this.subscriptionSsrc = ssrc;
|
|
96
99
|
}
|
|
97
100
|
|
|
101
|
+
setAllocateBuilder(builder) {
|
|
102
|
+
this.allocateBuilder = builder;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
refreshRelays(relays) {
|
|
106
|
+
const infos = relays.map((relay) => this.toRelayInfo(relay));
|
|
107
|
+
for (const conn of this.connections.values()) {
|
|
108
|
+
const current = conn.relayInfo;
|
|
109
|
+
const next = infos.find((info) => info.ip === current.ip && info.port === current.port && info.name === current.name)
|
|
110
|
+
?? infos.find((info) => info.ip === current.ip && info.port === current.port);
|
|
111
|
+
if (!next) continue;
|
|
112
|
+
conn.relayInfo = { ...next, id: current.id };
|
|
113
|
+
this.relayMap.set(current.id, conn.relayInfo);
|
|
114
|
+
conn.stunTransactionId = randomBytes(12);
|
|
115
|
+
}
|
|
116
|
+
this.resendSubscriptions();
|
|
117
|
+
}
|
|
118
|
+
|
|
98
119
|
makeConnectionId(ip, port, authTokenId) {
|
|
99
120
|
const base = ip.includes(':') ? `[${ip}]:${port}` : `${ip}:${port}`;
|
|
100
121
|
return authTokenId ? `${base}#${authTokenId}` : base;
|
|
@@ -120,6 +141,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
120
141
|
}
|
|
121
142
|
|
|
122
143
|
async configureRelays(relays) {
|
|
144
|
+
this.destroyed = false;
|
|
123
145
|
this.configuring = true;
|
|
124
146
|
const infos = relays.map((relay) => this.toRelayInfo(relay)).filter((info) => !this.failedRelays.has(info.id));
|
|
125
147
|
for (const info of infos) {
|
|
@@ -258,6 +280,9 @@ export class WaManualRelay extends EventEmitter {
|
|
|
258
280
|
}
|
|
259
281
|
|
|
260
282
|
ensureConnection = async (relayInfo) => {
|
|
283
|
+
if (this.destroyed) {
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
261
286
|
const conn = this.getOrCreateConnection(relayInfo);
|
|
262
287
|
if (conn.state === ConnectionState.Open || conn.state === ConnectionState.Connecting) {
|
|
263
288
|
return (conn.connectPromise ?? Promise.resolve()).catch(() => {});
|
|
@@ -272,7 +297,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
272
297
|
} finally {
|
|
273
298
|
conn.connectPromise = null;
|
|
274
299
|
}
|
|
275
|
-
if (failed && this.advanceRoute(conn, 'connect_failed')) {
|
|
300
|
+
if (failed && !this.destroyed && this.advanceRoute(conn, 'connect_failed')) {
|
|
276
301
|
await this.ensureConnection(relayInfo);
|
|
277
302
|
}
|
|
278
303
|
};
|
|
@@ -590,14 +615,14 @@ export class WaManualRelay extends EventEmitter {
|
|
|
590
615
|
}
|
|
591
616
|
|
|
592
617
|
sendStunAllocateOnOpen(conn, relayInfo) {
|
|
593
|
-
if (!relayInfo.key) {
|
|
618
|
+
if (this.destroyed || !relayInfo.key) {
|
|
594
619
|
return;
|
|
595
620
|
}
|
|
596
621
|
const ssrc = this.subscriptionSsrc || this.audioSsrc;
|
|
597
622
|
if (!ssrc) {
|
|
598
623
|
return;
|
|
599
624
|
}
|
|
600
|
-
if (conn.mode === 'dtls') {
|
|
625
|
+
if (conn.mode === 'dtls' && !this.allocateBuilder) {
|
|
601
626
|
this.sendBindingRegistrations(conn, relayInfo, ssrc);
|
|
602
627
|
}
|
|
603
628
|
this.sendAllocate(conn, relayInfo);
|
|
@@ -763,8 +788,17 @@ export class WaManualRelay extends EventEmitter {
|
|
|
763
788
|
}
|
|
764
789
|
const candidates = this.getAllocateCandidates(conn, relayInfo);
|
|
765
790
|
const candidate = candidates[Math.min(conn.allocateStage, candidates.length - 1)];
|
|
766
|
-
|
|
767
|
-
|
|
791
|
+
let packet;
|
|
792
|
+
if (this.allocateBuilder) {
|
|
793
|
+
packet = this.allocateBuilder(relayInfo, candidate, conn.stunTransactionId);
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
packet = buildAllocateForRelay(relayInfo.rawToken, this.streamSsrcs ? createWasmStreamDescriptors(this.streamSsrcs) : buildSSRCSubscriptionList([this.audioSsrc], [this.subscriptionSsrc], this.selfPid, this.peerPid), TEXT_ENCODER.encode(relayInfo.key), candidate.ip, candidate.port, conn.stunTransactionId, { relayedAddress: candidate.form });
|
|
797
|
+
}
|
|
798
|
+
if (!packet) {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
conn.allocatePacket = toArrayBuffer(packet);
|
|
768
802
|
const attemptKey = Buffer.from(conn.stunTransactionId).toString('hex');
|
|
769
803
|
if (!conn.allocateAttempts.has(attemptKey)) {
|
|
770
804
|
conn.allocateAttempts.set(attemptKey, { stage: conn.allocateStage, transactionId: conn.stunTransactionId, candidate });
|
|
@@ -900,7 +934,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
900
934
|
}
|
|
901
935
|
|
|
902
936
|
handleRelayLoss(conn) {
|
|
903
|
-
if (conn.state !== ConnectionState.Open) return;
|
|
937
|
+
if (this.destroyed || conn.state !== ConnectionState.Open) return;
|
|
904
938
|
if (!conn.answered) {
|
|
905
939
|
if (this.advanceRoute(conn, 'relay_lost_unanswered')) {
|
|
906
940
|
void this.ensureConnection(conn.relayInfo);
|
|
@@ -969,10 +1003,15 @@ export class WaManualRelay extends EventEmitter {
|
|
|
969
1003
|
}
|
|
970
1004
|
|
|
971
1005
|
cleanup() {
|
|
1006
|
+
this.destroyed = true;
|
|
972
1007
|
for (const [, conn] of this.connections) {
|
|
973
1008
|
if (conn.retryTimer) clearTimeout(conn.retryTimer);
|
|
974
1009
|
conn.retryTimer = null;
|
|
975
1010
|
this.closePeerObjects(conn);
|
|
1011
|
+
conn.state = ConnectionState.Closed;
|
|
1012
|
+
conn.connectPromise = null;
|
|
1013
|
+
conn.packetBuffer = [];
|
|
1014
|
+
conn.allocateAttempts.clear();
|
|
976
1015
|
}
|
|
977
1016
|
this.connections.clear();
|
|
978
1017
|
this.relayMap.clear();
|
|
@@ -11,6 +11,7 @@ const SEND_WINDOW_SIZE = 32;
|
|
|
11
11
|
const MAX_VIDEO_QUEUE_AGE_MS = 400;
|
|
12
12
|
const MAX_QUEUED_VIDEO_PACKETS = 200;
|
|
13
13
|
const MAX_QUEUED_AUDIO_FRAMES = 6;
|
|
14
|
+
const inFlightLifetimeMs = 1000;
|
|
14
15
|
const MAX_VIDEO_IN_FLIGHT = 24;
|
|
15
16
|
const STALE_GAP_TSN_LIMIT = 512;
|
|
16
17
|
const videoBurstBytes = 8192;
|
|
@@ -193,7 +194,7 @@ export class SctpAssociation extends EventEmitter {
|
|
|
193
194
|
const streamSeq = isAudio ? this.#outboundStreamSeq++ : this.#outboundVideoStreamSeq++;
|
|
194
195
|
const chunk = sctp.buildData({ tsn, streamId: 0, streamSeq, ppid: 53, payload, unordered: isAudio });
|
|
195
196
|
const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
|
|
196
|
-
const entry = { packet, timer: null, isAudio, sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
|
|
197
|
+
const entry = { packet, timer: null, isAudio, createdAt: performance.now(), sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
|
|
197
198
|
this.#inFlight.set(tsn, entry);
|
|
198
199
|
if (!isAudio) this.#videoInFlightCount++;
|
|
199
200
|
this.#sendDtlsPayload(packet);
|
|
@@ -208,6 +209,10 @@ export class SctpAssociation extends EventEmitter {
|
|
|
208
209
|
const delayMs = Math.min(RETRANSMIT_TIMEOUT_MS, this.#rtoMs * 2 ** entry.attempts);
|
|
209
210
|
entry.timer = setTimeout(() => {
|
|
210
211
|
if (!this.#inFlight.has(tsn)) return;
|
|
212
|
+
if (performance.now() - entry.createdAt > inFlightLifetimeMs) {
|
|
213
|
+
this.#abandonInFlight(tsn, entry);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
211
216
|
this.#retransmitCount++;
|
|
212
217
|
entry.attempts++;
|
|
213
218
|
entry.retransmitted = true;
|
|
@@ -218,6 +223,13 @@ export class SctpAssociation extends EventEmitter {
|
|
|
218
223
|
}, delayMs);
|
|
219
224
|
}
|
|
220
225
|
|
|
226
|
+
#abandonInFlight(tsn, entry) {
|
|
227
|
+
clearTimeout(entry.timer);
|
|
228
|
+
this.#inFlight.delete(tsn);
|
|
229
|
+
if (!entry.isAudio) this.#videoInFlightCount--;
|
|
230
|
+
this.#pumpSendQueue();
|
|
231
|
+
}
|
|
232
|
+
|
|
221
233
|
#refillVideoBudget(now) {
|
|
222
234
|
this.#videoBudgetBytes = Math.min(videoBurstBytes, this.#videoBudgetBytes + (now - this.#videoBudgetAt) * videoPaceBytesPerMs);
|
|
223
235
|
this.#videoBudgetAt = now;
|
|
@@ -248,6 +260,7 @@ export class SctpAssociation extends EventEmitter {
|
|
|
248
260
|
for (const [tsn, entry] of this.#inFlight) {
|
|
249
261
|
const behind = (highestTsn - tsn) >>> 0;
|
|
250
262
|
if (behind === 0 || behind >= 0x80000000) continue;
|
|
263
|
+
if (performance.now() - entry.createdAt > inFlightLifetimeMs) continue;
|
|
251
264
|
if (entry.sentAt + reorderWindowMs >= latestAckedSentAt) continue;
|
|
252
265
|
entry.missing++;
|
|
253
266
|
if (entry.missing < 3) continue;
|
package/src/voip/relay/stun.js
CHANGED
|
@@ -147,7 +147,7 @@ const WASM_STREAM_DESCRIPTOR_PLAN = [
|
|
|
147
147
|
{ participant: 2, layer: 2 }
|
|
148
148
|
];
|
|
149
149
|
|
|
150
|
-
export function createWasmStreamDescriptors(streamSsrcs) {
|
|
150
|
+
export function createWasmStreamDescriptors(streamSsrcs, hbhFecSsrcs = []) {
|
|
151
151
|
const entries = [];
|
|
152
152
|
for (let i = 0; i < streamSsrcs.length; i++) {
|
|
153
153
|
const ssrc = streamSsrcs[i];
|
|
@@ -162,8 +162,39 @@ export function createWasmStreamDescriptors(streamSsrcs) {
|
|
|
162
162
|
parts.push(encodeProtobufVarintField(3, ssrc));
|
|
163
163
|
entries.push(encodeProtobufLengthDelimited(1, concatBytes(parts)));
|
|
164
164
|
}
|
|
165
|
+
hbhFecSsrcs.forEach((ssrc, index) => {
|
|
166
|
+
if (ssrc === 0) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
entries.push(encodeProtobufLengthDelimited(1, concatBytes([
|
|
170
|
+
encodeProtobufVarintField(1, index + 3),
|
|
171
|
+
encodeProtobufVarintField(2, 3),
|
|
172
|
+
encodeProtobufVarintField(3, ssrc)
|
|
173
|
+
])));
|
|
174
|
+
});
|
|
165
175
|
return concatBytes(entries);
|
|
166
176
|
}
|
|
177
|
+
function createGroupSenderSubscription(ssrcs, pids, withVideoLayer) {
|
|
178
|
+
const parts = [encodeProtobufLengthDelimited(1, concatBytes(ssrcs.filter((ssrc) => ssrc !== 0).map(encodeVarint)))];
|
|
179
|
+
for (const pid of pids) {
|
|
180
|
+
const participant = withVideoLayer
|
|
181
|
+
? concatBytes([encodeProtobufVarintField(1, pid), encodeProtobufVarintField(2, 1)])
|
|
182
|
+
: encodeProtobufVarintField(1, pid);
|
|
183
|
+
parts.push(encodeProtobufLengthDelimited(2, participant));
|
|
184
|
+
}
|
|
185
|
+
return encodeProtobufLengthDelimited(1, encodeProtobufLengthDelimited(1, concatBytes(parts)));
|
|
186
|
+
}
|
|
187
|
+
export function createGroupSenderSubscriptions(streamSsrcs, appDataSsrc, pids) {
|
|
188
|
+
return concatBytes([
|
|
189
|
+
createGroupSenderSubscription(streamSsrcs.slice(3, 6), pids, true),
|
|
190
|
+
createGroupSenderSubscription(streamSsrcs.slice(6, 9), [], false),
|
|
191
|
+
createGroupSenderSubscription(streamSsrcs.slice(0, 3), pids, false),
|
|
192
|
+
createGroupSenderSubscription([appDataSsrc], pids, false)
|
|
193
|
+
]);
|
|
194
|
+
}
|
|
195
|
+
export function createGroupReceiverSubscriptions(pids) {
|
|
196
|
+
return concatBytes(pids.map((pid) => encodeProtobufLengthDelimited(2, encodeProtobufVarintField(1, pid))));
|
|
197
|
+
}
|
|
167
198
|
function parseIpv4Bytes(ip) {
|
|
168
199
|
const octets = ip.split('.');
|
|
169
200
|
if (octets.length !== 4) {
|
|
@@ -302,6 +333,26 @@ export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, re
|
|
|
302
333
|
const attrs = concatBytes(parts);
|
|
303
334
|
return buildStunMessage(STUN_ALLOCATE_REQUEST, attrs, transactionId, hmacKey, false);
|
|
304
335
|
}
|
|
336
|
+
export function buildGroupAllocateForRelay(relayToken, group, hmacKey, relayIp, relayPort, transactionId = generateTransactionId(), options = {}) {
|
|
337
|
+
const pids = [...new Set(group.pids)].sort((a, b) => a - b);
|
|
338
|
+
if (pids.length === 0) {
|
|
339
|
+
return buildAllocateForRelay(relayToken, createWasmStreamDescriptors(group.streamSsrcs), hmacKey, relayIp, relayPort, transactionId, options);
|
|
340
|
+
}
|
|
341
|
+
const parts = [
|
|
342
|
+
encodeAttribute(ATTR_SENDER_SUBSCRIPTIONS, relayToken),
|
|
343
|
+
encodeAttribute(0x4025, createGroupSenderSubscriptions(group.streamSsrcs, group.appDataSsrc, pids)),
|
|
344
|
+
encodeAttribute(0x4021, createGroupReceiverSubscriptions(pids)),
|
|
345
|
+
encodeAttribute(ATTR_SSRC_LIST, createWasmStreamDescriptors(group.streamSsrcs, pids.length > 1 ? group.hbhFecSsrcs ?? [] : [])),
|
|
346
|
+
encodeAttribute(0x805a, encodeVarint(pids.length))
|
|
347
|
+
];
|
|
348
|
+
if (relayIp && relayPort && options.relayedAddress !== 'none') {
|
|
349
|
+
const xorRelayedAddress = encodeXorRelayedAddress(relayIp, relayPort, transactionId, options.relayedAddress);
|
|
350
|
+
if (xorRelayedAddress) {
|
|
351
|
+
parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, xorRelayedAddress));
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return buildStunMessage(STUN_ALLOCATE_REQUEST, concatBytes(parts), transactionId, hmacKey, false);
|
|
355
|
+
}
|
|
305
356
|
export function buildBindingRequest(username, hmacKey, senderSubscriptions, includeIceControllingOrOptions = true) {
|
|
306
357
|
const options = typeof includeIceControllingOrOptions === 'boolean'
|
|
307
358
|
? { iceRole: includeIceControllingOrOptions ? 'controlling' : 'none' }
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createNoopLogger } from '../shim/core.js';
|
|
2
2
|
import { normalizeDeviceJid } from '../shim/protocol.js';
|
|
3
3
|
import { buildAckNode, getFirstNodeChild } from '../shim/transport.js';
|
|
4
|
+
import { buildCallControlAckNode } from './signaling.js';
|
|
4
5
|
import { toError } from '../shim/util.js';
|
|
5
6
|
const RECEIPT_CALL_TAGS = new Set([
|
|
6
7
|
'offer',
|
|
@@ -18,13 +19,26 @@ export async function routeCallStanza(manager, deps, node, logger) {
|
|
|
18
19
|
return null;
|
|
19
20
|
const tag = inner.tag;
|
|
20
21
|
const peerJid = node.attrs.from;
|
|
21
|
-
await deps.lowLevelCoordinator.sendNode(buildAckNode({
|
|
22
|
+
await deps.lowLevelCoordinator.sendNode(buildCallControlAckNode(node, tag) ?? buildAckNode({
|
|
22
23
|
kind: 'custom',
|
|
23
24
|
ackClass: 'call',
|
|
24
25
|
to: peerJid,
|
|
25
26
|
id: node.attrs.id,
|
|
26
27
|
type: tag
|
|
27
28
|
}));
|
|
29
|
+
switch (tag) {
|
|
30
|
+
case 'group_update':
|
|
31
|
+
await manager.handleGroupUpdate(node);
|
|
32
|
+
return tag;
|
|
33
|
+
case 'enc_rekey':
|
|
34
|
+
await manager.handleGroupEncRekey(node);
|
|
35
|
+
return tag;
|
|
36
|
+
case 'waiting_room_update':
|
|
37
|
+
manager.handleWaitingRoomUpdate(node);
|
|
38
|
+
return tag;
|
|
39
|
+
default:
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
28
42
|
let normalizedPeerJid;
|
|
29
43
|
try {
|
|
30
44
|
normalizedPeerJid = normalizeDeviceJid(peerJid);
|