@hiroosy/baileys-lite 0.3.7 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/voip/app-data/WaAppDataStream.js +0 -39
- package/src/voip/call/WaCallManager.js +4 -32
- package/src/voip/call/WaCallMediaSession.js +100 -361
- package/src/voip/index.js +75 -18
- package/src/voip/media/WaAudioEngine.js +152 -122
- package/src/voip/media/WaVideoEngine.js +7 -22
- package/src/voip/media/mlow-codec.js +7 -141
- package/src/voip/relay/WaManualRelay.js +531 -154
- package/src/voip/relay/dtls/handshake.js +4 -42
- package/src/voip/relay/relay-ack.js +66 -25
- package/src/voip/relay/sctp/association.js +89 -54
- package/src/voip/relay/stun.js +133 -17
- package/src/voip/types.js +1 -1
- package/src/voip/voipClient.js +3 -1
|
@@ -7,14 +7,12 @@ import { generateSelfSignedCert } from './cert-builder.js';
|
|
|
7
7
|
import { generateEcdheKeypair, buildEcdheSignedParams, verifyEcdheParams, signEcdheParams } from './ecdhe.js';
|
|
8
8
|
import { deriveMasterSecret, deriveKeyBlock, deriveVerifyData } from './prf.js';
|
|
9
9
|
import { encryptRecord, decryptRecord, aes128GcmParams } from './aead.js';
|
|
10
|
-
import { createNoopLogger } from '../../shim/core.js';
|
|
11
10
|
|
|
12
11
|
const RETRANSMIT_TIMEOUTS_MS = [1000, 2000, 4000, 8000, 8000];
|
|
13
12
|
const HANDSHAKE_TIMEOUT_MS = 25000;
|
|
14
13
|
|
|
15
14
|
export class DtlsClient extends EventEmitter {
|
|
16
15
|
#sendDatagram;
|
|
17
|
-
#logger;
|
|
18
16
|
#state = 'idle';
|
|
19
17
|
#messageSeq = 0;
|
|
20
18
|
#reassembler = new HandshakeReassembler();
|
|
@@ -37,10 +35,9 @@ export class DtlsClient extends EventEmitter {
|
|
|
37
35
|
#lastFlightDatagrams = [];
|
|
38
36
|
#overallTimeoutTimer = null;
|
|
39
37
|
|
|
40
|
-
constructor({ sendDatagram
|
|
38
|
+
constructor({ sendDatagram }) {
|
|
41
39
|
super();
|
|
42
40
|
this.#sendDatagram = sendDatagram;
|
|
43
|
-
this.#logger = logger ?? createNoopLogger();
|
|
44
41
|
}
|
|
45
42
|
|
|
46
43
|
start() {
|
|
@@ -84,25 +81,15 @@ export class DtlsClient extends EventEmitter {
|
|
|
84
81
|
const out = [];
|
|
85
82
|
let records;
|
|
86
83
|
try { records = decodeRecords(datagram); } catch (e) {
|
|
87
|
-
|
|
88
|
-
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
89
|
-
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
90
|
-
});
|
|
91
84
|
return out;
|
|
92
85
|
}
|
|
93
86
|
for (const record of records) {
|
|
94
87
|
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
95
|
-
this.#logger.trace('post-handshake non-application_data record', {
|
|
96
|
-
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
97
|
-
});
|
|
98
88
|
this.#handleRecord(record);
|
|
99
89
|
continue;
|
|
100
90
|
}
|
|
101
91
|
const readFloor = this.#readSeqByEpoch.get(record.epoch) ?? -1n;
|
|
102
92
|
if (record.sequenceNumber <= readFloor) {
|
|
103
|
-
this.#logger.trace('dropping application_data as replay/duplicate', {
|
|
104
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), readFloor: readFloor.toString()
|
|
105
|
-
});
|
|
106
93
|
continue;
|
|
107
94
|
}
|
|
108
95
|
try {
|
|
@@ -111,16 +98,8 @@ export class DtlsClient extends EventEmitter {
|
|
|
111
98
|
epoch: record.epoch, sequenceNumber: record.sequenceNumber, type: record.type, fragment: record.fragment,
|
|
112
99
|
});
|
|
113
100
|
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
114
|
-
this.#logger.trace('decrypted application_data', {
|
|
115
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), plaintextLen: plaintext.length
|
|
116
|
-
});
|
|
117
101
|
out.push(plaintext);
|
|
118
|
-
} catch
|
|
119
|
-
|
|
120
|
-
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
121
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
122
|
-
});
|
|
123
|
-
}
|
|
102
|
+
} catch { }
|
|
124
103
|
}
|
|
125
104
|
return out;
|
|
126
105
|
}
|
|
@@ -216,7 +195,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
216
195
|
return;
|
|
217
196
|
}
|
|
218
197
|
if (record.type === ContentType.CHANGE_CIPHER_SPEC) {
|
|
219
|
-
|
|
220
198
|
return;
|
|
221
199
|
}
|
|
222
200
|
if (record.type === ContentType.ALERT) {
|
|
@@ -256,7 +234,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
256
234
|
return;
|
|
257
235
|
}
|
|
258
236
|
if (msgType === HandshakeType.CERTIFICATE_REQUEST) {
|
|
259
|
-
|
|
260
237
|
this.#serverRequestedClientCert = true;
|
|
261
238
|
return;
|
|
262
239
|
}
|
|
@@ -323,7 +300,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
323
300
|
|
|
324
301
|
export class DtlsServer extends EventEmitter {
|
|
325
302
|
#sendDatagram;
|
|
326
|
-
#logger;
|
|
327
303
|
#state = 'idle';
|
|
328
304
|
#messageSeq = 0;
|
|
329
305
|
#reassembler = new HandshakeReassembler();
|
|
@@ -342,10 +318,9 @@ export class DtlsServer extends EventEmitter {
|
|
|
342
318
|
#lastFlightDatagrams = [];
|
|
343
319
|
#overallTimeoutTimer = null;
|
|
344
320
|
|
|
345
|
-
constructor({ sendDatagram
|
|
321
|
+
constructor({ sendDatagram }) {
|
|
346
322
|
super();
|
|
347
323
|
this.#sendDatagram = sendDatagram;
|
|
348
|
-
this.#logger = logger ?? createNoopLogger();
|
|
349
324
|
}
|
|
350
325
|
|
|
351
326
|
startPassive() {
|
|
@@ -387,16 +362,10 @@ export class DtlsServer extends EventEmitter {
|
|
|
387
362
|
const out = [];
|
|
388
363
|
let records;
|
|
389
364
|
try { records = decodeRecords(datagram); } catch (e) {
|
|
390
|
-
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
391
|
-
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
392
|
-
});
|
|
393
365
|
return out;
|
|
394
366
|
}
|
|
395
367
|
for (const record of records) {
|
|
396
368
|
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
397
|
-
this.#logger.trace('post-handshake non-application_data record', {
|
|
398
|
-
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
399
|
-
});
|
|
400
369
|
this.#handleRecord(record);
|
|
401
370
|
continue;
|
|
402
371
|
}
|
|
@@ -409,11 +378,7 @@ export class DtlsServer extends EventEmitter {
|
|
|
409
378
|
});
|
|
410
379
|
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
411
380
|
out.push(plaintext);
|
|
412
|
-
} catch
|
|
413
|
-
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
414
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
415
|
-
});
|
|
416
|
-
}
|
|
381
|
+
} catch { }
|
|
417
382
|
}
|
|
418
383
|
return out;
|
|
419
384
|
}
|
|
@@ -485,15 +450,12 @@ export class DtlsServer extends EventEmitter {
|
|
|
485
450
|
} catch (e) {
|
|
486
451
|
this.#fail(new Error(`DTLS: server-side key derivation failed: ${e.message}`));
|
|
487
452
|
}
|
|
488
|
-
|
|
489
453
|
}
|
|
490
454
|
|
|
491
455
|
#tryDecryptClientFinished(record) {
|
|
492
456
|
const readFloor = this.#readSeqByEpoch.get(1) ?? -1n;
|
|
493
457
|
if (record.sequenceNumber <= readFloor) return;
|
|
494
458
|
if (!this.#keys) {
|
|
495
|
-
|
|
496
|
-
this.#logger.trace('client Finished arrived before key derivation completed', {});
|
|
497
459
|
return;
|
|
498
460
|
}
|
|
499
461
|
let plaintext;
|
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
import { getNodeChildren, getNodeChildrenByTag, getNodeTextContent } from '../shim/transport.js';
|
|
2
2
|
import { base64ToBytes, bytesToBase64 } from '../shim/util.js';
|
|
3
3
|
import { TEXT_DECODER } from '../bytes.js';
|
|
4
|
+
function formatIpv6(bytes) {
|
|
5
|
+
const groups = new Array(8);
|
|
6
|
+
let bestStart = -1;
|
|
7
|
+
let bestLen = 0;
|
|
8
|
+
let runStart = -1;
|
|
9
|
+
let runLen = 0;
|
|
10
|
+
for (let i = 0; i < 8; i++) {
|
|
11
|
+
const value = (bytes[i * 2] << 8) | bytes[i * 2 + 1];
|
|
12
|
+
groups[i] = value.toString(16);
|
|
13
|
+
if (value === 0) {
|
|
14
|
+
if (runStart < 0) {
|
|
15
|
+
runStart = i;
|
|
16
|
+
}
|
|
17
|
+
runLen++;
|
|
18
|
+
if (runLen > bestLen) {
|
|
19
|
+
bestStart = runStart;
|
|
20
|
+
bestLen = runLen;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
runStart = -1;
|
|
25
|
+
runLen = 0;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (bestLen < 2) {
|
|
29
|
+
return groups.join(':');
|
|
30
|
+
}
|
|
31
|
+
return `${groups.slice(0, bestStart).join(':')}::${groups.slice(bestStart + bestLen).join(':')}`;
|
|
32
|
+
}
|
|
4
33
|
export function parseRelayFromAck(ackNode) {
|
|
5
34
|
const relays = [];
|
|
6
35
|
const participantJids = [];
|
|
@@ -98,37 +127,49 @@ export function parseRelayFromAck(ackNode) {
|
|
|
98
127
|
}
|
|
99
128
|
}
|
|
100
129
|
}
|
|
101
|
-
for (const
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
relays.push({
|
|
117
|
-
ip,
|
|
118
|
-
port,
|
|
119
|
-
token,
|
|
120
|
-
authToken,
|
|
130
|
+
for (const endpointTag of ['te2', 'te']) {
|
|
131
|
+
for (const rcNode of getNodeChildrenByTag(relayNode, endpointTag)) {
|
|
132
|
+
const addrBytes = rcNode.content;
|
|
133
|
+
if (!(addrBytes instanceof Uint8Array)) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const addrLength = addrBytes.length;
|
|
137
|
+
if (addrLength !== 6 && addrLength !== 18 && addrLength !== 24) {
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const tokenId = rcNode.attrs?.token_id || '0';
|
|
141
|
+
const authTokenId = rcNode.attrs?.auth_token_id || '';
|
|
142
|
+
const shared = {
|
|
143
|
+
token: tokens.get(tokenId) || '',
|
|
144
|
+
authToken: authTokenId ? authTokens.get(authTokenId) : undefined,
|
|
121
145
|
rawAuthToken: authTokenId ? rawAuthTokens.get(authTokenId) : undefined,
|
|
122
146
|
rawToken: rawTokens.get(tokenId),
|
|
123
147
|
key: relayKey,
|
|
124
148
|
relayId: parseInt(rcNode.attrs?.relay_id || '0', 10),
|
|
125
|
-
protocol,
|
|
149
|
+
protocol: rcNode.attrs?.protocol ? parseInt(rcNode.attrs.protocol, 10) : 0,
|
|
126
150
|
c2rRtt: rcNode.attrs?.c2r_rtt ? parseInt(rcNode.attrs.c2r_rtt, 10) : undefined,
|
|
127
|
-
relayName,
|
|
128
|
-
addressBytes,
|
|
151
|
+
relayName: rcNode.attrs?.relay_name || '',
|
|
129
152
|
authTokenId: authTokenId || tokenId,
|
|
130
|
-
isFna
|
|
131
|
-
}
|
|
153
|
+
isFna: rcNode.attrs?.is_fna === '1'
|
|
154
|
+
};
|
|
155
|
+
if (addrLength !== 18) {
|
|
156
|
+
const v4 = addrBytes.subarray(0, 6);
|
|
157
|
+
relays.push({
|
|
158
|
+
...shared,
|
|
159
|
+
ip: `${v4[0]}.${v4[1]}.${v4[2]}.${v4[3]}`,
|
|
160
|
+
port: (v4[4] << 8) | v4[5],
|
|
161
|
+
addressBytes: new Uint8Array(v4)
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (addrLength !== 6) {
|
|
165
|
+
const v6 = addrLength === 18 ? addrBytes : addrBytes.subarray(6);
|
|
166
|
+
relays.push({
|
|
167
|
+
...shared,
|
|
168
|
+
ip: formatIpv6(v6),
|
|
169
|
+
port: (v6[16] << 8) | v6[17],
|
|
170
|
+
addressBytes: new Uint8Array(v6)
|
|
171
|
+
});
|
|
172
|
+
}
|
|
132
173
|
}
|
|
133
174
|
}
|
|
134
175
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
|
-
import { createNoopLogger } from '../../shim/core.js';
|
|
4
3
|
import * as sctp from './wire.js';
|
|
5
4
|
|
|
6
5
|
const SCTP_PORT = 5000;
|
|
@@ -11,9 +10,11 @@ const HEARTBEAT_INTERVAL_MS = 5000;
|
|
|
11
10
|
const SEND_WINDOW_SIZE = 32;
|
|
12
11
|
const MAX_VIDEO_QUEUE_AGE_MS = 400;
|
|
13
12
|
const MAX_QUEUED_VIDEO_PACKETS = 200;
|
|
14
|
-
const MAX_QUEUED_AUDIO_FRAMES =
|
|
13
|
+
const MAX_QUEUED_AUDIO_FRAMES = 6;
|
|
15
14
|
const MAX_VIDEO_IN_FLIGHT = 24;
|
|
16
15
|
const STALE_GAP_TSN_LIMIT = 512;
|
|
16
|
+
const videoBurstBytes = 8192;
|
|
17
|
+
const videoPaceBytesPerMs = 120;
|
|
17
18
|
|
|
18
19
|
function randomUint32() {
|
|
19
20
|
return randomBytes(4).readUInt32BE(0);
|
|
@@ -21,15 +22,12 @@ function randomUint32() {
|
|
|
21
22
|
|
|
22
23
|
export class SctpAssociation extends EventEmitter {
|
|
23
24
|
#sendDtlsPayload;
|
|
24
|
-
#logger;
|
|
25
25
|
#state = 'idle';
|
|
26
26
|
|
|
27
27
|
#myTag = randomUint32();
|
|
28
28
|
#peerVerificationTag = 0;
|
|
29
29
|
#initialTsn = randomUint32();
|
|
30
30
|
#nextTsn;
|
|
31
|
-
#peerInitialTsn = 0;
|
|
32
|
-
#cumulativeAckReceived = -1;
|
|
33
31
|
#stateCookie = null;
|
|
34
32
|
#retransmitTimer = null;
|
|
35
33
|
#initRetries = 0;
|
|
@@ -45,11 +43,16 @@ export class SctpAssociation extends EventEmitter {
|
|
|
45
43
|
#videoQueue = [];
|
|
46
44
|
#inboundCumulativeTsn = -1;
|
|
47
45
|
#inboundReceivedAheadTsns = new Set();
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
#srttMs = null;
|
|
47
|
+
#rttVarMs = 0;
|
|
48
|
+
#rtoMs = RETRANSMIT_TIMEOUT_MS;
|
|
49
|
+
#videoBudgetBytes = videoBurstBytes;
|
|
50
|
+
#videoBudgetAt = performance.now();
|
|
51
|
+
#paceTimer = null;
|
|
52
|
+
|
|
53
|
+
constructor({ sendDtlsPayload }) {
|
|
50
54
|
super();
|
|
51
55
|
this.#sendDtlsPayload = sendDtlsPayload;
|
|
52
|
-
this.#logger = logger ?? createNoopLogger();
|
|
53
56
|
this.#nextTsn = this.#initialTsn;
|
|
54
57
|
}
|
|
55
58
|
|
|
@@ -61,6 +64,8 @@ export class SctpAssociation extends EventEmitter {
|
|
|
61
64
|
close() {
|
|
62
65
|
this.#state = 'closed';
|
|
63
66
|
clearTimeout(this.#retransmitTimer);
|
|
67
|
+
clearTimeout(this.#paceTimer);
|
|
68
|
+
this.#paceTimer = null;
|
|
64
69
|
clearInterval(this.#heartbeatTimer);
|
|
65
70
|
for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
|
|
66
71
|
this.#inFlight.clear();
|
|
@@ -97,12 +102,8 @@ export class SctpAssociation extends EventEmitter {
|
|
|
97
102
|
const oldest = this.#videoQueue[0];
|
|
98
103
|
if (this.#videoQueue.length > MAX_QUEUED_VIDEO_PACKETS ||
|
|
99
104
|
now - oldest.queuedAtMs > MAX_VIDEO_QUEUE_AGE_MS) {
|
|
100
|
-
const dropped = this.#videoQueue.length;
|
|
101
105
|
this.#videoQueue = [];
|
|
102
106
|
this.#videoFlushCount++;
|
|
103
|
-
this.#logger.trace('sctp flushed stale video queue to protect audio latency', {
|
|
104
|
-
dropped
|
|
105
|
-
});
|
|
106
107
|
}
|
|
107
108
|
}
|
|
108
109
|
this.#pumpSendQueue();
|
|
@@ -114,21 +115,9 @@ export class SctpAssociation extends EventEmitter {
|
|
|
114
115
|
try {
|
|
115
116
|
header = sctp.parsePacketHeader(plaintext);
|
|
116
117
|
} catch (e) {
|
|
117
|
-
|
|
118
|
-
this.#logger.trace('sctp payload failed to parse', {
|
|
119
|
-
message: e.message, bytes: plaintext.length, hex: Buffer.from(plaintext).toString('hex')
|
|
120
|
-
});
|
|
121
118
|
return;
|
|
122
119
|
}
|
|
123
|
-
const chunkTypesForLog = sctp.splitChunks(plaintext, header.chunksStart).map((c) => c.type);
|
|
124
|
-
this.#logger.trace('sctp recv packet', {
|
|
125
|
-
vtag: `0x${header.verificationTag.toString(16)}`,
|
|
126
|
-
expectVtag: `0x${this.#myTag.toString(16)}`,
|
|
127
|
-
chunkTypes: chunkTypesForLog,
|
|
128
|
-
state: this.#state
|
|
129
|
-
});
|
|
130
120
|
if (this.#state !== 'wait_init_ack' && header.verificationTag !== this.#myTag) {
|
|
131
|
-
|
|
132
121
|
return;
|
|
133
122
|
}
|
|
134
123
|
const chunks = sctp.splitChunks(plaintext, header.chunksStart);
|
|
@@ -146,13 +135,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
146
135
|
});
|
|
147
136
|
|
|
148
137
|
const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: 0, chunks: [chunk] });
|
|
149
|
-
this.#logger.trace('sctp sending INIT', {
|
|
150
|
-
myTag: `0x${this.#myTag.toString(16)}`, initialTsn: this.#initialTsn, attempt: this.#initRetries
|
|
151
|
-
});
|
|
152
|
-
if (this.#initRetries === 0) {
|
|
153
|
-
|
|
154
|
-
this.#logger.trace('sctp INIT packet hex (first attempt only)', { hex: packet.toString('hex') });
|
|
155
|
-
}
|
|
156
138
|
this.#sendDtlsPayload(packet);
|
|
157
139
|
clearTimeout(this.#retransmitTimer);
|
|
158
140
|
this.#retransmitTimer = setTimeout(() => {
|
|
@@ -193,6 +175,14 @@ export class SctpAssociation extends EventEmitter {
|
|
|
193
175
|
payload = this.#audioQueue.shift();
|
|
194
176
|
isAudio = true;
|
|
195
177
|
} else if (this.#videoQueue.length > 0 && this.#videoInFlightCount < MAX_VIDEO_IN_FLIGHT) {
|
|
178
|
+
this.#refillVideoBudget(performance.now());
|
|
179
|
+
const headBytes = this.#videoQueue[0].payload.length;
|
|
180
|
+
const neededBytes = Math.min(headBytes, videoBurstBytes);
|
|
181
|
+
if (this.#videoBudgetBytes < neededBytes) {
|
|
182
|
+
this.#scheduleVideoPump(neededBytes);
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
this.#videoBudgetBytes -= headBytes;
|
|
196
186
|
payload = this.#videoQueue.shift().payload;
|
|
197
187
|
isAudio = false;
|
|
198
188
|
} else {
|
|
@@ -203,7 +193,7 @@ export class SctpAssociation extends EventEmitter {
|
|
|
203
193
|
const streamSeq = isAudio ? this.#outboundStreamSeq++ : this.#outboundVideoStreamSeq++;
|
|
204
194
|
const chunk = sctp.buildData({ tsn, streamId: 0, streamSeq, ppid: 53, payload, unordered: isAudio });
|
|
205
195
|
const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
|
|
206
|
-
const entry = { packet, timer: null, isAudio };
|
|
196
|
+
const entry = { packet, timer: null, isAudio, sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
|
|
207
197
|
this.#inFlight.set(tsn, entry);
|
|
208
198
|
if (!isAudio) this.#videoInFlightCount++;
|
|
209
199
|
this.#sendDtlsPayload(packet);
|
|
@@ -215,12 +205,59 @@ export class SctpAssociation extends EventEmitter {
|
|
|
215
205
|
|
|
216
206
|
#armDataRetransmit(tsn, entry) {
|
|
217
207
|
clearTimeout(entry.timer);
|
|
208
|
+
const delayMs = Math.min(RETRANSMIT_TIMEOUT_MS, this.#rtoMs * 2 ** entry.attempts);
|
|
218
209
|
entry.timer = setTimeout(() => {
|
|
219
210
|
if (!this.#inFlight.has(tsn)) return;
|
|
220
211
|
this.#retransmitCount++;
|
|
212
|
+
entry.attempts++;
|
|
213
|
+
entry.retransmitted = true;
|
|
214
|
+
entry.missing = 0;
|
|
215
|
+
entry.sentAt = performance.now();
|
|
221
216
|
this.#sendDtlsPayload(entry.packet);
|
|
222
217
|
this.#armDataRetransmit(tsn, entry);
|
|
223
|
-
},
|
|
218
|
+
}, delayMs);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#refillVideoBudget(now) {
|
|
222
|
+
this.#videoBudgetBytes = Math.min(videoBurstBytes, this.#videoBudgetBytes + (now - this.#videoBudgetAt) * videoPaceBytesPerMs);
|
|
223
|
+
this.#videoBudgetAt = now;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
#scheduleVideoPump(bytesNeeded) {
|
|
227
|
+
if (this.#paceTimer) return;
|
|
228
|
+
const waitMs = Math.ceil((bytesNeeded - this.#videoBudgetBytes) / videoPaceBytesPerMs);
|
|
229
|
+
this.#paceTimer = setTimeout(() => {
|
|
230
|
+
this.#paceTimer = null;
|
|
231
|
+
this.#pumpSendQueue();
|
|
232
|
+
}, waitMs);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
#updateRto(sampleMs) {
|
|
236
|
+
if (this.#srttMs === null) {
|
|
237
|
+
this.#srttMs = sampleMs;
|
|
238
|
+
this.#rttVarMs = sampleMs / 2;
|
|
239
|
+
} else {
|
|
240
|
+
this.#rttVarMs = 0.75 * this.#rttVarMs + 0.25 * Math.abs(this.#srttMs - sampleMs);
|
|
241
|
+
this.#srttMs = 0.875 * this.#srttMs + 0.125 * sampleMs;
|
|
242
|
+
}
|
|
243
|
+
this.#rtoMs = Math.min(RETRANSMIT_TIMEOUT_MS, Math.max(500, this.#srttMs + 4 * this.#rttVarMs));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
#fastRetransmitMissing(highestTsn, latestAckedSentAt) {
|
|
247
|
+
const reorderWindowMs = this.#srttMs === null ? 0 : this.#srttMs / 4;
|
|
248
|
+
for (const [tsn, entry] of this.#inFlight) {
|
|
249
|
+
const behind = (highestTsn - tsn) >>> 0;
|
|
250
|
+
if (behind === 0 || behind >= 0x80000000) continue;
|
|
251
|
+
if (entry.sentAt + reorderWindowMs >= latestAckedSentAt) continue;
|
|
252
|
+
entry.missing++;
|
|
253
|
+
if (entry.missing < 3) continue;
|
|
254
|
+
entry.missing = 0;
|
|
255
|
+
entry.retransmitted = true;
|
|
256
|
+
entry.sentAt = performance.now();
|
|
257
|
+
this.#retransmitCount++;
|
|
258
|
+
this.#sendDtlsPayload(entry.packet);
|
|
259
|
+
this.#armDataRetransmit(tsn, entry);
|
|
260
|
+
}
|
|
224
261
|
}
|
|
225
262
|
|
|
226
263
|
#handleChunk(chunk, header) {
|
|
@@ -230,7 +267,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
230
267
|
const parsed = sctp.parseInitOrInitAck(chunk.value);
|
|
231
268
|
if (!parsed.stateCookie) { this.#fail(new Error('SCTP: INIT ACK missing State Cookie')); return; }
|
|
232
269
|
this.#peerVerificationTag = parsed.initiateTag;
|
|
233
|
-
this.#peerInitialTsn = parsed.initialTsn;
|
|
234
270
|
this.#inboundExpectedStreamSeq = 0;
|
|
235
271
|
this.#inboundCumulativeTsn = (parsed.initialTsn - 1) >>> 0;
|
|
236
272
|
this.#inboundReceivedAheadTsns.clear();
|
|
@@ -276,7 +312,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
276
312
|
}
|
|
277
313
|
|
|
278
314
|
#handleIncomingData({ tsn, streamId, streamSeq, ppid, payload, unordered }) {
|
|
279
|
-
|
|
280
315
|
this.#recordInboundTsn(tsn);
|
|
281
316
|
this.#buildAndSendSack();
|
|
282
317
|
|
|
@@ -301,9 +336,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
301
336
|
this.#reorderBuffer.set(streamSeq, payload);
|
|
302
337
|
if (this.#reorderBuffer.size > STALE_GAP_TSN_LIMIT) {
|
|
303
338
|
const bufferedSeqs = [...this.#reorderBuffer.keys()].sort((a, b) => a - b);
|
|
304
|
-
this.#logger.debug('sctp: forcing stream sequence past a stuck gap', {
|
|
305
|
-
from: this.#inboundExpectedStreamSeq, bufferedCount: bufferedSeqs.length
|
|
306
|
-
});
|
|
307
339
|
this.#inboundExpectedStreamSeq = bufferedSeqs[0];
|
|
308
340
|
const buffered = this.#reorderBuffer.get(this.#inboundExpectedStreamSeq);
|
|
309
341
|
this.#reorderBuffer.delete(this.#inboundExpectedStreamSeq);
|
|
@@ -317,7 +349,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
317
349
|
}
|
|
318
350
|
}
|
|
319
351
|
}
|
|
320
|
-
|
|
321
352
|
}
|
|
322
353
|
|
|
323
354
|
#recordInboundTsn(tsn) {
|
|
@@ -338,9 +369,6 @@ export class SctpAssociation extends EventEmitter {
|
|
|
338
369
|
if (offset > maxAheadOffset) maxAheadOffset = offset;
|
|
339
370
|
}
|
|
340
371
|
const jumpTo = (this.#inboundCumulativeTsn + maxAheadOffset) >>> 0;
|
|
341
|
-
this.#logger.debug('sctp: forcing cumulative TSN past a stuck gap', {
|
|
342
|
-
from: this.#inboundCumulativeTsn, to: jumpTo, aheadCount: this.#inboundReceivedAheadTsns.size
|
|
343
|
-
});
|
|
344
372
|
this.#inboundReceivedAheadTsns.delete(jumpTo);
|
|
345
373
|
this.#inboundCumulativeTsn = jumpTo;
|
|
346
374
|
}
|
|
@@ -380,28 +408,33 @@ export class SctpAssociation extends EventEmitter {
|
|
|
380
408
|
|
|
381
409
|
#handleSack({ cumulativeTsnAck, gapAckBlocks }) {
|
|
382
410
|
if (this.#inFlight.size === 0) return;
|
|
411
|
+
const now = performance.now();
|
|
383
412
|
let acked = false;
|
|
413
|
+
let rttSample = null;
|
|
414
|
+
let latestAckedSentAt = -1;
|
|
415
|
+
const release = (tsn, entry) => {
|
|
416
|
+
clearTimeout(entry.timer);
|
|
417
|
+
this.#inFlight.delete(tsn);
|
|
418
|
+
if (!entry.isAudio) this.#videoInFlightCount--;
|
|
419
|
+
if (!entry.retransmitted) rttSample = now - entry.sentAt;
|
|
420
|
+
if (entry.sentAt > latestAckedSentAt) latestAckedSentAt = entry.sentAt;
|
|
421
|
+
acked = true;
|
|
422
|
+
};
|
|
384
423
|
for (const [tsn, entry] of this.#inFlight) {
|
|
385
|
-
if (sackAcksTsn(cumulativeTsnAck, tsn))
|
|
386
|
-
clearTimeout(entry.timer);
|
|
387
|
-
this.#inFlight.delete(tsn);
|
|
388
|
-
if (!entry.isAudio) this.#videoInFlightCount--;
|
|
389
|
-
acked = true;
|
|
390
|
-
}
|
|
424
|
+
if (sackAcksTsn(cumulativeTsnAck, tsn)) release(tsn, entry);
|
|
391
425
|
}
|
|
426
|
+
let highestGapOffset = -1;
|
|
392
427
|
if (gapAckBlocks && gapAckBlocks.length > 0 && this.#inFlight.size > 0) {
|
|
393
428
|
for (const block of gapAckBlocks) {
|
|
429
|
+
if (block.end > highestGapOffset) highestGapOffset = block.end;
|
|
394
430
|
for (const [tsn, entry] of this.#inFlight) {
|
|
395
431
|
const offset = (tsn - cumulativeTsnAck) >>> 0;
|
|
396
|
-
if (offset >= block.start && offset <= block.end)
|
|
397
|
-
clearTimeout(entry.timer);
|
|
398
|
-
this.#inFlight.delete(tsn);
|
|
399
|
-
if (!entry.isAudio) this.#videoInFlightCount--;
|
|
400
|
-
acked = true;
|
|
401
|
-
}
|
|
432
|
+
if (offset >= block.start && offset <= block.end) release(tsn, entry);
|
|
402
433
|
}
|
|
403
434
|
}
|
|
404
435
|
}
|
|
436
|
+
if (rttSample !== null) this.#updateRto(rttSample);
|
|
437
|
+
if (highestGapOffset >= 0 && latestAckedSentAt >= 0) this.#fastRetransmitMissing((cumulativeTsnAck + highestGapOffset) >>> 0, latestAckedSentAt);
|
|
405
438
|
if (acked) this.#pumpSendQueue();
|
|
406
439
|
}
|
|
407
440
|
|
|
@@ -416,6 +449,8 @@ export class SctpAssociation extends EventEmitter {
|
|
|
416
449
|
#fail(err) {
|
|
417
450
|
this.#state = 'closed';
|
|
418
451
|
clearTimeout(this.#retransmitTimer);
|
|
452
|
+
clearTimeout(this.#paceTimer);
|
|
453
|
+
this.#paceTimer = null;
|
|
419
454
|
clearInterval(this.#heartbeatTimer);
|
|
420
455
|
for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
|
|
421
456
|
this.#inFlight.clear();
|