@hiroosy/baileys-lite 0.0.3 → 0.3.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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,465 @@
1
+ import { createNoopLogger } from '../shim/core.js';
2
+ import { toError } from '../shim/util.js';
3
+ const MLOW_SAMPLE_RATE = 16_000;
4
+ const MLOW_CHANNELS = 1;
5
+ const FRAME_SIZE = 960;
6
+ const MAX_FRAME_SIZE = 1_920;
7
+ const APPLICATION_VOIP = 2048;
8
+ const SIGNAL_VOICE = 3001;
9
+ const CONCEAL_QUANTUM = MLOW_SAMPLE_RATE / 400;
10
+ const DEFAULT_BITRATE = 15_000;
11
+ const DEFAULT_COMPLEXITY = 5;
12
+ const DEFAULT_MAX_CONCEAL_FRAMES = 5;
13
+ const MAX_LOSS_HINT = 5;
14
+ const SPEECH_TOC_MASK = 0xf8;
15
+ const SPEECH_TOC_60MS = 0x50;
16
+ const TINY_FRAME_BYTES = 18;
17
+ const RENEW_MIN_RMS = 120;
18
+ const RENEW_MIN_GAP_FRAMES = 4;
19
+ const SEQ_SPACE = 0x1_0000;
20
+ const SEQ_HALF = 0x8000;
21
+ export const MLOW_ENCODER_CTL = Object.freeze({
22
+ SUBFRAME_IMPORTANCE: 4060,
23
+ USE_SPEECH_ACTIVITY_FLATNESS: 4062,
24
+ VAD_NON_BINARY: 4066,
25
+ VAD_HIGHPASS_SHARPNESS: 4068
26
+ });
27
+ let wasmReady = null;
28
+ function loadMlowModule() {
29
+ if (!wasmReady) {
30
+ wasmReady = import('./audio-codec.js')
31
+ .then(async (mod) => {
32
+ const lib = mod;
33
+ await lib.loadLibopus();
34
+ return lib;
35
+ })
36
+ .catch((err) => {
37
+ wasmReady = null;
38
+ throw err;
39
+ });
40
+ }
41
+ return wasmReady;
42
+ }
43
+ export class MLowCodec {
44
+ encoder = null;
45
+ decoder = null;
46
+ frameSize = FRAME_SIZE;
47
+ logger = createNoopLogger();
48
+ decodeErrors = 0;
49
+ decodeSuccess = 0;
50
+ plcFrames = 0;
51
+ fecFrames = 0;
52
+ lateFrames = 0;
53
+ concealCapped = 0;
54
+ opts = {};
55
+ packetLossPercent = 0;
56
+ maxConcealFrames = DEFAULT_MAX_CONCEAL_FRAMES;
57
+ lastSeq = -1;
58
+ lastDecodedSamples = 0;
59
+ pcmScratch = new Int16Array(FRAME_SIZE);
60
+ lib = null;
61
+ encoderOptions = null;
62
+ spareEncoder = null;
63
+ spareBuilding = false;
64
+ generation = 0;
65
+ frameIndex = 0;
66
+ lastRenewFrame = -1000;
67
+ renewCount = 0;
68
+ silenceScratch = new Float32Array(MAX_FRAME_SIZE);
69
+ constructor() { }
70
+ static async create(opts = {}) {
71
+ const codec = new MLowCodec();
72
+ await codec.init(opts);
73
+ return codec;
74
+ }
75
+ async init(opts) {
76
+ this.opts = opts;
77
+ this.logger = opts.logger ?? createNoopLogger();
78
+ this.packetLossPercent = Math.min(MAX_LOSS_HINT, clampPercent(opts.packetLossPercent ?? 0));
79
+ const requestedConcealFrames = opts.maxConcealFrames;
80
+ this.maxConcealFrames = Math.max(0, Math.trunc(Number.isFinite(requestedConcealFrames)
81
+ ? requestedConcealFrames
82
+ : DEFAULT_MAX_CONCEAL_FRAMES));
83
+ const lib = await loadMlowModule();
84
+ this.lib = lib;
85
+ this.decoder = await lib.createDecoder({
86
+ channels: MLOW_CHANNELS,
87
+ sampleRate: MLOW_SAMPLE_RATE,
88
+ useSmpl: true,
89
+ maxFrameSize: MAX_FRAME_SIZE
90
+ });
91
+ try {
92
+ this.encoderOptions = {
93
+ channels: MLOW_CHANNELS,
94
+ sampleRate: MLOW_SAMPLE_RATE,
95
+ application: APPLICATION_VOIP,
96
+ frameSize: FRAME_SIZE,
97
+ useSmpl: true,
98
+ dtx: opts.dtx ?? false,
99
+ fec: opts.fec ?? true,
100
+ packetLossPercent: this.packetLossPercent,
101
+ bitrate: opts.bitrate ?? DEFAULT_BITRATE,
102
+ complexity: opts.complexity ?? DEFAULT_COMPLEXITY,
103
+ signal: SIGNAL_VOICE
104
+ };
105
+ this.encoder = await lib.createEncoder(this.encoderOptions);
106
+ }
107
+ catch (err) {
108
+ this.decoder?.free();
109
+ this.decoder = null;
110
+ throw err;
111
+ }
112
+ if (opts.tunables) {
113
+ this.applyEncoderTunables(opts.tunables);
114
+ }
115
+ this.frameIndex = 0;
116
+ this.lastRenewFrame = -1000;
117
+ this.prepareSpare();
118
+ this.logger.warn('[MLOW] encoder ready', {
119
+ vadRenew: true,
120
+ bitrate: this.encoderOptions.bitrate,
121
+ lossHintCap: MAX_LOSS_HINT
122
+ });
123
+ }
124
+ prepareSpare() {
125
+ if (this.spareEncoder || this.spareBuilding || !this.lib || !this.encoderOptions) {
126
+ return;
127
+ }
128
+ const generation = this.generation;
129
+ this.spareBuilding = true;
130
+ const options = { ...this.encoderOptions, packetLossPercent: this.packetLossPercent };
131
+ this.lib.createEncoder(options).then((enc) => {
132
+ this.spareBuilding = false;
133
+ if (generation !== this.generation) {
134
+ enc.free();
135
+ return;
136
+ }
137
+ const tunables = this.opts?.tunables;
138
+ if (tunables) {
139
+ this.writeCtlOn(enc, MLOW_ENCODER_CTL.SUBFRAME_IMPORTANCE, tunables.subframeImportance);
140
+ this.writeCtlOn(enc, MLOW_ENCODER_CTL.USE_SPEECH_ACTIVITY_FLATNESS, tunables.useSpeechActivityFlatness);
141
+ this.writeCtlOn(enc, MLOW_ENCODER_CTL.VAD_NON_BINARY, tunables.vadNonBinary);
142
+ this.writeCtlOn(enc, MLOW_ENCODER_CTL.VAD_HIGHPASS_SHARPNESS, tunables.vadHighpassSharpness);
143
+ }
144
+ this.spareEncoder = enc;
145
+ }, (err) => {
146
+ this.spareBuilding = false;
147
+ this.logger.warn('mlow spare encoder unavailable', { message: toError(err).message });
148
+ });
149
+ }
150
+ renewEncoder(pcm, original) {
151
+ const spare = this.spareEncoder;
152
+ this.spareEncoder = null;
153
+ const kept = Uint8Array.from(original);
154
+ try {
155
+ const alt = spare.encode(pcm, { frameSize: this.frameSize });
156
+ if (alt.length > 0 && (alt[0] & SPEECH_TOC_MASK) === SPEECH_TOC_60MS) {
157
+ const out = Uint8Array.from(alt);
158
+ const old = this.encoder;
159
+ this.encoder = spare;
160
+ try {
161
+ spare.setPacketLossPercent(this.packetLossPercent);
162
+ }
163
+ catch { }
164
+ try {
165
+ old.free();
166
+ }
167
+ catch { }
168
+ this.renewCount++;
169
+ this.lastRenewFrame = this.frameIndex;
170
+ if (this.renewCount === 1 || this.renewCount % 20 === 0) {
171
+ this.logger.warn('[MLOW] encoder renewed: frame came out with VAD off', {
172
+ renewCount: this.renewCount,
173
+ frame: this.frameIndex,
174
+ tocBefore: kept[0],
175
+ tocAfter: out[0]
176
+ });
177
+ }
178
+ this.prepareSpare();
179
+ return out;
180
+ }
181
+ spare.free();
182
+ }
183
+ catch (err) {
184
+ this.logger.warn('mlow encoder renew failed', { message: toError(err).message });
185
+ try {
186
+ spare.free();
187
+ }
188
+ catch { }
189
+ }
190
+ this.prepareSpare();
191
+ return kept;
192
+ }
193
+ encode(float32Audio) {
194
+ if (!this.encoder) {
195
+ throw new Error('[MLowCodec] encoder not initialized');
196
+ }
197
+ if (float32Audio.length !== this.frameSize) {
198
+ throw new Error(`[MLowCodec] encode expects ${this.frameSize} samples, got ${float32Audio.length}`);
199
+ }
200
+ const pcm = this.pcmScratch;
201
+ let sumSq = 0;
202
+ for (let i = 0; i < pcm.length; i++) {
203
+ const sample = Math.max(-1, Math.min(1, float32Audio[i]));
204
+ const v = Math.round(sample * 32_767);
205
+ pcm[i] = v;
206
+ sumSq += v * v;
207
+ }
208
+ const packet = this.encoder.encode(pcm, { frameSize: this.frameSize });
209
+ this.frameIndex++;
210
+ if (packet.length > TINY_FRAME_BYTES &&
211
+ (packet[0] & SPEECH_TOC_MASK) !== SPEECH_TOC_60MS &&
212
+ this.spareEncoder &&
213
+ this.frameIndex - this.lastRenewFrame >= RENEW_MIN_GAP_FRAMES &&
214
+ Math.sqrt(sumSq / pcm.length) >= RENEW_MIN_RMS) {
215
+ return this.renewEncoder(pcm, packet);
216
+ }
217
+ return packet;
218
+ }
219
+ decode(mlowFrame) {
220
+ if (!this.decoder) {
221
+ throw new Error('[MLowCodec] decoder not initialized');
222
+ }
223
+ if (mlowFrame === null) {
224
+ return this.conceal(this.concealFrameSize());
225
+ }
226
+ const decoded = this.tryDecode(mlowFrame);
227
+ return decoded ?? this.silence(this.concealFrameSize());
228
+ }
229
+ decodeSequenced(seq, packet, onFrame) {
230
+ if (!this.decoder) {
231
+ throw new Error('[MLowCodec] decoder not initialized');
232
+ }
233
+ if (packet.length === 0) {
234
+ return;
235
+ }
236
+ const current = seq & 0xffff;
237
+ if (this.lastSeq >= 0) {
238
+ const delta = (current - this.lastSeq + SEQ_SPACE) % SEQ_SPACE;
239
+ if (delta === 0 || delta >= SEQ_HALF) {
240
+ this.lateFrames++;
241
+ this.logger.trace('mlow packet arrived out of order', {
242
+ seq: current,
243
+ lastSeq: this.lastSeq
244
+ });
245
+ return;
246
+ }
247
+ if (delta > 1) {
248
+ this.concealGap(delta - 1, packet, onFrame);
249
+ }
250
+ }
251
+ const decoded = this.tryDecode(packet);
252
+ if (decoded === null) {
253
+ this.lastSeq = (current - 1 + SEQ_SPACE) % SEQ_SPACE;
254
+ return;
255
+ }
256
+ this.lastSeq = current;
257
+ onFrame(decoded);
258
+ }
259
+ resetSequence() {
260
+ this.lastSeq = -1;
261
+ this.lastDecodedSamples = 0;
262
+ }
263
+ setExpectedPacketLossPercent(percent) {
264
+ const next = Math.min(MAX_LOSS_HINT, clampPercent(percent));
265
+ if (next === this.packetLossPercent) {
266
+ return;
267
+ }
268
+ this.packetLossPercent = next;
269
+ if (!this.encoder) {
270
+ return;
271
+ }
272
+ try {
273
+ this.encoder.setPacketLossPercent(next);
274
+ }
275
+ catch (err) {
276
+ this.logger.warn('mlow packet loss percent rejected', {
277
+ percent: next,
278
+ message: toError(err).message
279
+ });
280
+ }
281
+ }
282
+ getExpectedPacketLossPercent() {
283
+ return this.packetLossPercent;
284
+ }
285
+ applyEncoderTunables(tunables) {
286
+ if (!this.encoder) {
287
+ throw new Error('[MLowCodec] encoder not initialized');
288
+ }
289
+ this.opts = { ...this.opts, tunables };
290
+ this.writeCtl(MLOW_ENCODER_CTL.SUBFRAME_IMPORTANCE, tunables.subframeImportance);
291
+ this.writeCtl(MLOW_ENCODER_CTL.USE_SPEECH_ACTIVITY_FLATNESS, tunables.useSpeechActivityFlatness);
292
+ this.writeCtl(MLOW_ENCODER_CTL.VAD_NON_BINARY, tunables.vadNonBinary);
293
+ this.writeCtl(MLOW_ENCODER_CTL.VAD_HIGHPASS_SHARPNESS, tunables.vadHighpassSharpness);
294
+ }
295
+ getStats() {
296
+ return {
297
+ success: this.decodeSuccess,
298
+ errors: this.decodeErrors,
299
+ plc: this.plcFrames,
300
+ fec: this.fecFrames,
301
+ late: this.lateFrames,
302
+ concealCapped: this.concealCapped,
303
+ vadRenew: this.renewCount
304
+ };
305
+ }
306
+ getFrameSize() {
307
+ return this.frameSize;
308
+ }
309
+ getFrameDurationMs() {
310
+ return (this.frameSize / MLOW_SAMPLE_RATE) * 1000;
311
+ }
312
+ getSampleRate() {
313
+ return MLOW_SAMPLE_RATE;
314
+ }
315
+ getMaxConcealFrames() {
316
+ return this.maxConcealFrames;
317
+ }
318
+ async reset() {
319
+ this.destroy();
320
+ await this.init(this.opts);
321
+ this.decodeErrors = 0;
322
+ this.decodeSuccess = 0;
323
+ this.plcFrames = 0;
324
+ this.fecFrames = 0;
325
+ this.lateFrames = 0;
326
+ this.concealCapped = 0;
327
+ this.renewCount = 0;
328
+ this.resetSequence();
329
+ }
330
+ destroy() {
331
+ if (this.frameIndex > 0) {
332
+ this.logger.warn('[MLOW] call summary', {
333
+ frames: this.frameIndex,
334
+ renewed: this.renewCount,
335
+ renewedPct: Math.round((1000 * this.renewCount) / this.frameIndex) / 10
336
+ });
337
+ }
338
+ this.generation++;
339
+ this.spareBuilding = false;
340
+ this.spareEncoder?.free();
341
+ this.spareEncoder = null;
342
+ this.encoder?.free();
343
+ this.decoder?.free();
344
+ this.encoder = null;
345
+ this.decoder = null;
346
+ }
347
+ concealGap(missing, nextPacket, onFrame) {
348
+ const limit = this.maxConcealFrames;
349
+ const frames = missing > limit ? limit : missing;
350
+ if (frames < missing) {
351
+ this.concealCapped++;
352
+ this.logger.trace('mlow concealment capped', { missing, frames });
353
+ }
354
+ if (frames <= 0) {
355
+ return;
356
+ }
357
+ const frameSize = this.concealFrameSize();
358
+ for (let i = 0; i < frames - 1; i++) {
359
+ onFrame(this.conceal(frameSize));
360
+ }
361
+ onFrame(this.recoverPrevious(nextPacket, frameSize));
362
+ }
363
+ tryDecode(mlowFrame) {
364
+ if (!this.decoder) {
365
+ return null;
366
+ }
367
+ try {
368
+ const audio = this.decoder.decodeFloat(mlowFrame);
369
+ this.decodeSuccess++;
370
+ if (audio.length > 0) {
371
+ this.lastDecodedSamples = audio.length;
372
+ }
373
+ return audio;
374
+ }
375
+ catch (err) {
376
+ this.decodeErrors++;
377
+ this.logger.trace('mlow decode failed', { message: toError(err).message });
378
+ return null;
379
+ }
380
+ }
381
+ recoverPrevious(nextPacket, frameSize) {
382
+ if (!this.decoder) {
383
+ return this.silence(frameSize);
384
+ }
385
+ try {
386
+ const recovered = this.decoder.decodeFloat(nextPacket, {
387
+ decodeFec: true,
388
+ frameSize
389
+ });
390
+ this.fecFrames++;
391
+ return recovered;
392
+ }
393
+ catch (err) {
394
+ this.logger.trace('mlow fec decode failed, concealing instead', {
395
+ message: toError(err).message
396
+ });
397
+ return this.conceal(frameSize);
398
+ }
399
+ }
400
+ conceal(frameSize) {
401
+ if (!this.decoder) {
402
+ return this.silence(frameSize);
403
+ }
404
+ try {
405
+ const concealed = this.decoder.decodePacketLossFloat(frameSize);
406
+ this.plcFrames++;
407
+ return concealed;
408
+ }
409
+ catch (err) {
410
+ this.logger.trace('mlow concealment failed', { message: toError(err).message });
411
+ return this.silence(frameSize);
412
+ }
413
+ }
414
+ concealFrameSize() {
415
+ const last = this.lastDecodedSamples;
416
+ if (last <= 0) {
417
+ return this.frameSize;
418
+ }
419
+ const quantized = Math.round(last / CONCEAL_QUANTUM) * CONCEAL_QUANTUM;
420
+ if (quantized < CONCEAL_QUANTUM) {
421
+ return CONCEAL_QUANTUM;
422
+ }
423
+ return quantized > MAX_FRAME_SIZE ? MAX_FRAME_SIZE : quantized;
424
+ }
425
+ silence(frameSize) {
426
+ const size = frameSize > MAX_FRAME_SIZE ? MAX_FRAME_SIZE : frameSize;
427
+ return this.silenceScratch.subarray(0, size);
428
+ }
429
+ writeCtlOn(enc, request, value) {
430
+ if (value === undefined || !enc) {
431
+ return;
432
+ }
433
+ try {
434
+ enc.encoderCtl(request, value);
435
+ }
436
+ catch (err) {
437
+ this.logger.warn('mlow spare ctl rejected', { request, message: toError(err).message });
438
+ }
439
+ }
440
+ writeCtl(request, value) {
441
+ if (value === undefined || !this.encoder) {
442
+ return;
443
+ }
444
+ try {
445
+ this.encoder.encoderCtl(request, value);
446
+ }
447
+ catch (err) {
448
+ this.logger.warn('mlow encoder ctl rejected', {
449
+ request,
450
+ value,
451
+ message: toError(err).message
452
+ });
453
+ }
454
+ }
455
+ }
456
+ function clampPercent(value) {
457
+ if (!Number.isFinite(value)) {
458
+ return 0;
459
+ }
460
+ const rounded = Math.round(value);
461
+ if (rounded < 0) {
462
+ return 0;
463
+ }
464
+ return rounded > 100 ? 100 : rounded;
465
+ }
@@ -0,0 +1,68 @@
1
+ import { writeUInt16BE, writeUInt32BE } from '../bytes.js';
2
+ import { randomBytes } from '../crypto/primitives.js';
3
+
4
+ export const RTCP_PT = {
5
+ SR: 200,
6
+ SDES: 202
7
+ };
8
+
9
+ const NTP_UNIX_OFFSET_SECS = 2208988800;
10
+ const WHATSAPP_RTCP_CNAME_LEN = 18;
11
+
12
+ const HEX_CHARS = '0123456789abcdef';
13
+
14
+ export function buildWhatsappRtcpCname(entropy) {
15
+ const randomHex = new Array(11);
16
+ for (let nibble = 0; nibble < 11; nibble++) {
17
+ const b = entropy[6 + Math.floor(nibble / 2)];
18
+ randomHex[nibble] = (nibble & 1) === 0 ? HEX_CHARS[b >> 4] : HEX_CHARS[b & 0x0f];
19
+ }
20
+ const cname = new Uint8Array(WHATSAPP_RTCP_CNAME_LEN);
21
+ const encoder = new TextEncoder();
22
+ cname.set(encoder.encode(randomHex.slice(0, 5).join('')), 0);
23
+ cname.set(encoder.encode('@pj'), 5);
24
+ cname.set(encoder.encode(randomHex.slice(5).join('')), 8);
25
+ cname.set(encoder.encode('.org'), 14);
26
+ return cname;
27
+ }
28
+
29
+ export function buildSenderReport(localSsrc, stats, nowMs) {
30
+ const buf = new Uint8Array(28);
31
+ buf[0] = 0x80;
32
+ buf[1] = RTCP_PT.SR;
33
+ buf[3] = 6;
34
+ writeUInt32BE(buf, localSsrc, 4);
35
+ const ntpSec = Math.floor(nowMs / 1000) + NTP_UNIX_OFFSET_SECS;
36
+ const ntpFrac = Math.round(((nowMs % 1000) / 1000) * 4294967296);
37
+ writeUInt32BE(buf, ntpSec >>> 0, 8);
38
+ writeUInt32BE(buf, ntpFrac >>> 0, 12);
39
+ writeUInt32BE(buf, stats.rtpTimestamp >>> 0, 16);
40
+ writeUInt32BE(buf, stats.packetsSent >>> 0, 20);
41
+ writeUInt32BE(buf, stats.octetsSent >>> 0, 24);
42
+ return buf;
43
+ }
44
+
45
+ export function buildSourceDescription(localSsrc, cname) {
46
+ const packet = new Uint8Array(32);
47
+ packet[0] = 0x81;
48
+ packet[1] = RTCP_PT.SDES;
49
+ writeUInt16BE(packet, 7, 2);
50
+ writeUInt32BE(packet, localSsrc, 4);
51
+ packet[8] = 1;
52
+ packet[9] = WHATSAPP_RTCP_CNAME_LEN;
53
+ packet.set(cname, 10);
54
+ return packet;
55
+ }
56
+
57
+ export function buildSenderReportWithSdes(localSsrc, stats, nowMs, cname) {
58
+ const sr = buildSenderReport(localSsrc, stats, nowMs);
59
+ const sdes = buildSourceDescription(localSsrc, cname);
60
+ const out = new Uint8Array(sr.length + sdes.length);
61
+ out.set(sr, 0);
62
+ out.set(sdes, sr.length);
63
+ return out;
64
+ }
65
+
66
+ export function generateWhatsappRtcpCname() {
67
+ return buildWhatsappRtcpCname(randomBytes(12));
68
+ }